"""
cgihelper.py - Misc. stuff useful in CGI-BINs
(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)
"""

__version__ = '0.1.6'

import sys, os, string, re

known_browsers = {
                   'MSIE':'Microsoft Internet Explorer',
		   'Mozilla':'Netscape Navigator',
		   'Lynx':'Lynx',
		   'Opera':'Opera',
		   'StarOffice':'StarOffice',
		   'NCSA_Mosaic':'NCSA Mosaic',
		   'NetPositive':'Net Positive'
                 }
known_browsers_rev = {}
for b in known_browsers.keys():
  known_browsers_rev[known_browsers[b]]=b

compatible_browsers = known_browsers.keys()
compatible_browsers.remove('Mozilla')

compatible_browsers_re = re.compile('(%s)[/ ]+([0-9.]*)' % string.join(compatible_browsers,'|'))
mozilla_re             = re.compile('(Mozilla)[/ ]+([0-9.]*)')


def BrowserType(http_user_agent):
  """
  Parse the HTTP_USER_AGENT environment variable and return the
  tuple (Browser,Version).

  Not sure if this succeeds in every situation since most
  browsers have very obscure HTTP_USER_AGENT entries for compability reasons.
  The following browsers are known by name:
  Netscape	Netscape Navigator, Netscape Communicator)
  MSIE		MS Internet Explorer
  Opera		Opera browser from http://www.operasoftware.com/
  StarOffice	built-in browser of Star Office
  Lynx		the text-based browser Lynx
  NetPositive	Net Positive (BeOS)
  """

  if not http_user_agent:
    return ('','')
  else:
    browserrm = compatible_browsers_re.search(http_user_agent)
    if browserrm:
      return browserrm.groups()
    else:
      browserrm = mozilla_re.search(http_user_agent)
      if browserrm:
        return browserrm.groups()
      else:
        return ('','')
