"""
httphelper.py - basic HTTP-related functions
(c) by Michael Stroeder <michael@stroeder.com>

This module is distributed under the terms of the
GPL (GNU GENERAL PUBLIC LICENSE) Version 2
(see http://www.gnu.org/copyleft/gpl.html)

$Id: httphelper.py,v 1.4 2002/01/27 00:36:35 michael Exp $
"""

__version__ = '0.0.3'

import sys,time

HTTP_LINESEP = '\r\n'

def DateTimeRFC1123(secs=0):
  """
  Return seconds as RFC1123 date/time format preferred
  for HTTP 1.1 (see RFC2616)
  """
  return time.strftime(
    '%a, %d %b %Y %H:%M:%S GMT',
    time.gmtime(secs)
  )

# Write HTTP-Header
def SendHeader(
  outf=sys.stdout,
  contenttype='text/html',
  charset='ISO-8859-1',
  contentlength=None,
  expires_offset=0,
  lastmodified=None,
  additional_header = {}
):
  """
  Generate HTTP header
  
  outf                          File object used for sending to client.
  contenttype='text/html',      MIME type of object in HTTP body.
  charset='ISO-8859-1',         Character set used.
  contentlength=None,           Content-Length if known and
                                gzip-encoding is not used.
  expires_offset=0,             Expiry time from current time in seconds.
  lastmodified=None,            Last-modified time.
  additional_header = {}        Dictionary containing arbitrary
                                additional HTTP header fields.
  """
  gzip = hasattr(outf,'fileobj')
  # Get current time as GMT (seconds since epoch)
  gmt = time.time()
  # Determine times for HTTP header
  if lastmodified is None:
    lastmodified = DateTimeRFC1123(gmt)
  expires = DateTimeRFC1123(gmt+expires_offset)
  # Build list of header lines
  header_lines = []
  # Write header
  if not (contenttype is None):
    header_lines.append('Content-Type: %s;charset=%s' % (contenttype,charset))
  if not (contentlength is None):
    header_lines.append('Content-Length: %d' % (contentlength))
  if gzip:
    header_lines.append('Content-Encoding: gzip')
    header_lines.append('Vary: Accept-Encoding')
  header_lines.append('Last-Modified: %s' % (lastmodified))
  header_lines.append('Expires: %s' % (expires))
  for h,v in additional_header.items():
    header_lines.append('%s: %s' % (h,v))
  # Write empty end-of-header line
  header_lines.extend(['',''])
  if gzip:
    outf.fileobj.write(HTTP_LINESEP.join(header_lines))
    outf.fileobj.flush()
  else:
    outf.write(HTTP_LINESEP.join(header_lines))
  return


def URLRedirect(outf,url,refreshtime=0,msg='Redirecting...'):
  """
  Output HTML text with redirecting <head> section.
  """
  SendHeader(outf)
  outf.write("""
<html>
  <head>
    <meta http-equiv="refresh" content="%(refreshtime)s; url=%(url)s">
  </head>
  <body>
    %(msg)s <a href="%(url)s">Redirecting...</a>
  </body>
</html>
    """ % vars()
  )
