"""quixote.http_response

Provides the HTTPResponse class.

Derived from Zope's HTTPResponse module.
"""

##############################################################################
# 
# Zope Public License (ZPL) Version 1.0
# -------------------------------------
# 
# Copyright (c) Digital Creations.  All rights reserved.
# 
# This license has been certified as Open Source(tm).
# 
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
# 
# 1. Redistributions in source code must retain the above copyright
#    notice, this list of conditions, and the following disclaimer.
# 
# 2. Redistributions in binary form must reproduce the above copyright
#    notice, this list of conditions, and the following disclaimer in
#    the documentation and/or other materials provided with the
#    distribution.
# 
# 3. Digital Creations requests that attribution be given to Zope
#    in any manner possible. Zope includes a "Powered by Zope"
#    button that is installed by default. While it is not a license
#    violation to remove this button, it is requested that the
#    attribution remain. A significant investment has been put
#    into Zope, and this effort will continue if the Zope community
#    continues to grow. This is one way to assure that growth.
# 
# 4. All advertising materials and documentation mentioning
#    features derived from or use of this software must display
#    the following acknowledgement:
# 
#      "This product includes software developed by Digital Creations
#      for use in the Z Object Publishing Environment
#      (http://www.zope.org/)."
# 
#    In the event that the product being advertised includes an
#    intact Zope distribution (with copyright and license included)
#    then this clause is waived.
# 
# 5. Names associated with Zope or Digital Creations must not be used to
#    endorse or promote products derived from this software without
#    prior written permission from Digital Creations.
# 
# 6. Modified redistributions of any form whatsoever must retain
#    the following acknowledgment:
# 
#      "This product includes software developed by Digital Creations
#      for use in the Z Object Publishing Environment
#      (http://www.zope.org/)."
# 
#    Intact (re-)distributions of any official Zope release do not
#    require an external acknowledgement.
# 
# 7. Modifications are encouraged but must be packaged separately as
#    patches to official Zope releases.  Distributions that do not
#    clearly separate the patches from the original work must be clearly
#    labeled as unofficial distributions.  Modifications which do not
#    carry the name Zope may be packaged in any form, as long as they
#    conform to all of the clauses above.
# 
# 
# Disclaimer
# 
#   THIS SOFTWARE IS PROVIDED BY DIGITAL CREATIONS ``AS IS'' AND ANY
#   EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
#   IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
#   PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL DIGITAL CREATIONS OR ITS
#   CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
#   SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
#   LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
#   USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
#   ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
#   OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
#   OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
#   SUCH DAMAGE.
# 
# 
# This software consists of contributions made by Digital Creations and
# many individuals on behalf of Digital Creations.  Specific
# attributions are listed in the accompanying credits file.
# 
##############################################################################

__revision__ = "$Id: http_response.py,v 1.25 2001/09/19 14:51:32 nascheme Exp $"

import sys
from types import StringType, IntType

status_reasons = {
    100: 'Continue',
    101: 'Switching Protocols',
    102: 'Processing',
    200: 'OK',
    201: 'Created',
    202: 'Accepted',
    203: 'Non-Authoritative Information',
    204: 'No Content',
    205: 'Reset Content',
    206: 'Partial Content',
    207: 'Multi-Status',
    300: 'Multiple Choices',
    301: 'Moved Permanently',
    302: 'Moved Temporarily',
    303: 'See Other',
    304: 'Not Modified',
    305: 'Use Proxy',
    307: 'Temporary Redirect',
    400: 'Bad Request',
    401: 'Unauthorized',
    402: 'Payment Required',
    403: 'Forbidden',
    404: 'Not Found',
    405: 'Method Not Allowed',
    406: 'Not Acceptable',
    407: 'Proxy Authentication Required',
    408: 'Request Time-out',
    409: 'Conflict',
    410: 'Gone',
    411: 'Length Required',
    412: 'Precondition Failed',
    413: 'Request Entity Too Large',
    414: 'Request-URI Too Large',
    415: 'Unsupported Media Type',
    416: 'Requested range not satisfiable',
    417: 'Expectation Failed',
    422: 'Unprocessable Entity',
    423: 'Locked',
    424: 'Failed Dependency',
    500: 'Internal Server Error',
    501: 'Not Implemented',
    502: 'Bad Gateway',
    503: 'Service Unavailable',
    504: 'Gateway Time-out',
    505: 'HTTP Version not supported',
    507: 'Insufficient Storage',
}


class HTTPResponse:
    """
    An object representation of an HTTP response.
    
    The Response type encapsulates all possible responses to HTTP
    requests.  Responses are normally created by the Quixote publisher
    or by the HTTPRequest class (every request must have a response,
    after all).

    Instance attributes:
      status_code : int
        HTTP response status code (integer between 100 and 599)
      reason_phrase : string
        the reason phrase that accompanies status_code (usually
        set automatically by the set_status() method)
      headers : { string : string }
        most of the headers included with the response; every header set
        by 'set_header()' goes here.  Does not include "Status" or
        "Set-Cookie" headers (unless someone uses set_header() to set
        them, but that would be foolish).
      body : string
        the response body, None by default.  If the body is never
        set (ie. left as None), the response will not include 
        "Content-type" or "Content-length" headers.  These headers
        are set as soon as the body is set (with set_body()), even
        if the body is an empty string.
      cookies : { name:string : { attrname : value } }
        collection of cookies to set in this response; it is expected
        that the user-agent will remember the cookies and send them on
        future requests.  The cookie value is stored as the "value"
        attribute.  The other attributes are as specified by RFC 2109.
      cache : boolean = false
        if false, instruct the user-agent not to cache the response
        body.  (Currently done with an HTTP 1.0-style "Pragma: no-cache"
        header.)

    """

    def __init__ (self, status=200, body=None):
        """
        Creates a new HTTP response.
        """
        self.set_status(status)
        self.headers = {}
        
        if body is not None:
            self.set_body(body)
        else:
            self.body = None

        self.cookies = {}
        self.cache = 0

    def set_status (self, status, reason=None):
        """set_status(status : int, reason : string = None)

        Sets the HTTP status code of the response.  'status' must be an
        integer in the range 100 .. 599.  'reason' must be a string; if
        not supplied, the default reason phrase for 'status' will be
        used.  If 'status' is a non-standard status code, the generic
        reason phrase for its group of status codes will be used; eg.
        if status == 493, the reason for status 400 will be used.
        """
        if type(status) is not IntType:
            raise TypeError, "status must be an integer"
        if not (100 <= status <= 599):
            raise ValueError, "status must be between 100 and 599"

        self.status_code = status
        if reason is None:
            if status_reasons.has_key(status):
                reason = status_reasons[status]
            else:
                # Eg. for generic 4xx failures, use the reason
                # associated with status 400.
                reason = status_reasons[(status / 100) * 100]
        else:
            reason = str(reason)

        self.reason_phrase = reason

    def set_header (self, name, value, literal=0):
        """set_header(name : string, value : string)

        Sets an HTTP return header "name" with value "value", clearing
        the previous value set for the header, if one exists.
        """
        self.headers[name.lower()] = value

    def set_body (self, body):
        """set_body(body : string)
        
        Sets the return body equal to the (string) argument "body". Also
        updates the "Content-length" return header.  Sets the
        "Content-type" header if it hasn't already been set.
        """
        if type(body) is not StringType:
            raise TypeError("'body' must be a string")

        self.body = body
        self.set_header('content-length', len(body))
        if not self.headers.has_key('content-type'):
            self.set_header('content-type', 'text/html; charset=iso-8859-1')

    def expire_cookie (self, name, **attrs):
        """
        Cause an HTTP cookie to be removed from the browser
        
        The response will include an HTTP header that will remove the cookie
        corresponding to "name" on the client, if one exists.  This is
        accomplished by sending a new cookie with an expiration date
        that has already passed.  Note that some clients require a path
        to be specified - this path must exactly match the path given
        when creating the cookie.  The path can be specified as a keyword
        argument.
        """
        dict = {'max_age': 0, 'expires': 'Thu, 01-Jan-1970 00:00:00 GMT'}
        dict.update(attrs)
        self.set_cookie(name, "deleted", **dict)

    def set_cookie (self, name, value, **attrs):
        """set_cookie(name : string, value : string, **attrs)

        Set an HTTP cookie on the browser.

        The response will include an HTTP header that sets a cookie on
        cookie-enabled browsers with a key "name" and value "value".
        Cookie attributes such as "expires" and "domains" may be
        supplied as keyword arguments; see RFC 2109 for a full list.
        (For the "secure" attribute, use any true value.)

        This overrides any previous value for this cookie.  Any
        previously-set attributes for the cookie are preserved, unless
        they are explicitly overridden with keyword arguments to this
        call.
        """
        cookies = self.cookies
        if cookies.has_key(name):
            cookie = cookies[name]
        else:
            cookie = cookies[name] = {}
        cookie.update(attrs)
        cookie['value'] = value

    def redirect (self, location, permanent=0):
        """Cause a redirection without raising an error"""
        if not isinstance(location, StringType):
            raise TypeError, "location must be a string (got %s)" % `location`
        # Ensure that location is a full URL
        if location.find('://') == -1:
            raise ValueError, "URL must include the server name"
        if permanent:
            status = 301
        else:
            status = 302
        self.set_status(status)
        self.headers['location'] = location

        doc = """\
<html>
 <head><title>Redirect to %(location)s</title></head>
 <body>
 <h1>Redirect</h1>
 <p>Your browser should have redirected you to
 <center><a href="%(location)s">%(location)s</a></center>
 </p>
 </body>
</html>
""" % vars()

        return doc


    def _gen_cookie_headers (self):
        """_gen_cookie_headers() -> [string]

        Build a list of "Set-Cookie" headers based on all cookies
        set with 'set_cookie()', and return that list.
        """
        cookie_list = []
        for (name, attrs) in self.cookies.items():

            # Note that as of May 98, IE4 ignores cookies with
            # quoted cookie attr values, so only the value part
            # of name=value pairs may be quoted.

            # 'chunks' is a list of "name=val" chunks; will be joined
            # with "; " to create the "Set-cookie" header.
            chunks = ['%s="%s"' % (name, attrs['value'])] 
                
            for (name, val) in attrs.items():
                name = name.lower()
                if name in ('expires', 'domain', 'path', 'max_age', 'comment'):
                    name = name.replace('_', '-')
                    chunks.append("%s=%s" % (name, val))
                elif name == 'secure' and v:
                    chunks.append("secure")

            cookie = "Set-Cookie: " + ("; ".join(chunks))
            cookie_list.append(cookie)

        # Should really check size of cookies here!
        
        return cookie_list

    def write (self, file):
        """write(file : file)

        Write the HTTP response headers and body to 'file'.  This is not
        a complete HTTP response, as it doesn't start with a response
        status line as specified by RFC 2616.  It does, however, start
        with a "Status" header as described by the CGI spec.  It
        is expected that this response is parsed by the web server
        and turned into a complete HTTP response.
        """

        # XXX currently we write a response like this:
        #  Status: 200 OK
        #  Content-type: text/html; charset=iso-8859-1
        #  Content-length: 100
        #  Set-Cookie: foo=bar
        #  Set-Cookie: bar=baz
        #
        #  <html><body>This is a document</body></html>
        #
        # which has to be interpreted by the web server to create
        # a true HTTP response -- that is, this is for a
        # "parsed header" CGI driver script.
        #
        # We should probably have provisions for operating in
        # "non-parsed header" mode, where the CGI script is responsible
        # for generating a complete HTTP response with no help from the
        # server.

        headers = self.headers

        # "Status" header must come first.
        file.write("Status: %03d %s\r\n" % (self.status_code,
                                            self.reason_phrase))

        # Now the bulk of the headers (anything set with 'set_header()',
        # most likely "Content-type" and "Content-length").
        for (key, val) in headers.items():
            file.write("%s: %s\r\n" % (key, val))

        # All the "Set-Cookie" headers.
        if self.cookies:
            for hdr in self._gen_cookie_headers():
                file.write(hdr + "\r\n")

        # Cache directives (HTTP 1.0 only, arggh).
        if not self.cache:
            file.write("Pragma: no-cache\r\n")

        # And the respone body.
        file.write("\r\n")
        if self.body is not None:
            file.write(self.body)
