# cgiutils.py
#
# Copyright 2001,2002 Wichert Akkerman <wichert@deephackmode.org>
#
# This file is free software; you can redistribute it and/or modify it
# under the terms of version 2 of the GNU General Public License as
# published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
# Calculate shared library dependencies

"""Utility functions to make writing CGI scripts in python easier.
"""

__docformat__	= "epytext en"

# Import all system packages we need
import os, sys, types, cgi, re, Cookie


def setcookie(key, value):
	"""Output HTTP header to store a cookie

	@param key:   cookie name
	@type key:    string
	@param value: data to store in the cookie
	@type value:  string
	"""
	c=Cookie.SimpleCookie()
	c[key]=value
	print c


def extractcookies(dict):
	"""Extract HTTP cookies.
	
	Extract all http cookies that the browser passed to use and merge them
	in a dictionary.
	
	@param dict: dictionary to store cookies in
	@type dict:  dictionary"""

	return dict.update(GetCookies())


def extractcgiparams(dict):
	"""Extract form parameters

	Extract all CGI parameters that the browser passed to use and merge
	them in a dictionary.

	@param dict: dictionary to store CGI PUT/POST parameters in
	@type dict:  dictionary.
	"""

	dict.update(GetParameters())


def GetCookies():
	"""Extract HTTP cookies.
	
	Extract all http cookies that the browser passed to use and return
	them as a dictionary.
	
	@return: cookies
	@rtype: dictionary
	"""
	dict={}
	if os.environ.has_key("HTTP_COOKIE"):
		c=Cookie.SimpleCookie(os.environ.get("HTTP_COOKIE"))
		for key in c.keys():
			dict[key]=c[key].value
	
	return dict


def GetParameters():
	"""Extract CGI parameters.

	Extract all CGI parameters that the browser passed to use and 
	return them as a dictionary.

	@return: CGI parameters
	@rtype: dictionary
	"""

	dict={}
	form=cgi.FieldStorage()
	for frm in form.keys():
		if type(form[frm]) is types.ListType:
			dict[frm]=map(lambda x: x.value, form[frm])
		else:
			dict[frm]=form[frm].value
	
	return dict

def scriptname(script):
	"""Return a link to another CGI script in the same directory.

	The SCRIPT_NAME environment variable is used to determine the
	location of the current CGI.

	@param script: name of CGI script to link to
	@type script:  string
	@return:       relative URL to CGI
	@rtype:        string
	"""
	if os.environ.has_key("SCRIPT_NAME"):
		base=re.sub("[^/]*$", script, os.environ["SCRIPT_NAME"])
	else:
		base=script
	return base


def redirect(url):
	"""Output redirector.

	Generate HTTP headers and a XHTML page to redirect a browser to
	another URL.

	@param url: URL to redirect to
	@type url:  string
	"""
	print "Content-Type: text/html"
	print "Location: %s" % url
	print "Status: 302\n"

	print '''<?xml version="1.0" encoding="iso-8859-1"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
	   "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"/>
    <title>Redirecting</title>
  </head>
  <body>
    <p>
      Redirecting. If this does not work automatically please go to
      <a href="%s">%s</a> manually.
    </p>
  </body>
</html>
''' % (url, url)


def getsessionkey(Parameters):
	"""Extract a session key.

	This function should not exist.
	"""
	if Parameters.has_key("SESSION"):
		return Parameters["SESSION"]

	redirect("/nocookies.xhtml")
	sys.exit(0)


class Request:
	"""CGI request object.

	This class extracts all the available information about a CGI requests
	and stores that in its instance.
	"""
	def __init__(self):
		self.params=GetParameters()
		self.cookies=GetCookies()
		for key in [ "SERVER_PROTOCOL", "SERVER_PORT", "REQUEST_URI",
			"REQUEST_METHOD", "PATH_INFO", "PATH_TRANSLATED",
			"SCRIPT_NAME", "QUERY_STRING", "REMOTE_HOST",
			"REMOTE_ADDR", "AUTH_TYPE", "REMOTE_USER",
			"REMOTE_IDENT", "CONTENT_TYPE", "CONTENT_LENGTH" ] :
			if os.environ.has_key(key):
				setattr(self, key.lower(), os.environ[key])

		self.headers={}
		for key in filter(lambda x: x.startswith("HTTP_"), os.environ.keys()):
			self.headers[key[5:].lower().replace("_", "-")]=os.environ[key]


