<?php
	/*
	** File: init
	** Description: Initialize system
	** 	1. Connect to database server
	**	2. Select database
	**	3. Create browser constants
	**	4. Check the session identifier
	**
	** Version: $Revision: 1.14 $
	** Created: 09/18/98
	** Author: Leon Atkinson
	** Email: leon@clearink.com
	** CVS Author: $Author: leon $
	** Last Revised: $Date: 2000/02/02 18:59:46 $
	**
	** Log : $Log: init,v $
	** Log : Revision 1.14  2000/02/02 18:59:46  leon
	** Log : Fixing bugs reported by Ted Henigson.
	** Log :
	** Log : Revision 1.13  1999/12/20 17:17:38  leon
	** Log : Fixed bug in error text
	** Log :
	** Log : Revision 1.12  1999/12/07 18:48:56  leon
	** Log : Fixed a reference to the old $Application_Root variable.
	** Log :
	** Log : Revision 1.11  1999/11/02 21:00:00  leon
	** Log : Changed the database variables into constants.
	** Log :
	** Log : Revision 1.10  1999/10/05 21:41:00  jj
	** Log : Submitting Leon's bug fix. InvoiceID's were not getting set properly for anonymous users.
	** Log :
	** Log : Revision 1.9  1999/10/05 18:33:22  leon
	** Log : The random number generator needs to be seeded with the seconds on the
	** Log : clock.  This is for the places in the code that clean the session table
	** Log : and stuff like that.
	** Log :
	** Log : Revision 1.8  1999/10/04 22:09:54  leon
	** Log : Removed getInvoiceID.  The active invoice is now added to $UserInfo
	** Log : by the check sid functionality in init.
	** Log :
	** Log : Revision 1.7  1999/10/04 20:08:22  leon
	** Log : Made the comments inside module a little better.
	** Log :
	** Log : Revision 1.5  1999/08/18 22:32:05  leon
	** Log : Returning opening PHP tag to XML-friendly tag
	** Log :
	** Log : Revision 1.4  1999/08/04 16:33:18  jj
	** Log : Created a nice error message if unable to connect to the database (on first attempt). Not having this error message caused problems for 2 people.
	** Log :
	** Log : Revision 1.3  1999/07/28 19:27:21  leon
	** Log : Mass update based on code donation from a live project
	** Log :
	**
	** Copyright (c) 1999 Working Dogs.  All rights reserved.
	*/

	/*
	** Setup Database Connection
	*/

	//establish persistent connection
	$DatabaseLink = mysql_pconnect(DATABASE_HOST, DATABASE_USER, DATABASE_PASSWORD);
	if(!$DatabaseLink)
	{
		print("<P><B>Unable to connect to \"".DATABASE_HOST."\" in order to " . 
			"use the \"".DATABASE_NAME."\" database. Perhaps the database is not " . 
			"running, or perhaps the admin needs to change a few variables in ". 
			"modules/include/global_settings in order to point to the correct ".
			"database.</B><BR>\n");
		print("<!--mysql_pconnect " . 
			mysql_errno() . ": " . 
			mysql_error() . "-->\n");
	}

	//select database
	if(!(mysql_select_db(DATABASE_NAME, $DatabaseLink)))
	{
		print("<!--mysql_select_db " . 
			mysql_errno() . ": " . 
			mysql_error() . "-->\n");
	}

	//Seed random number generator
	//This is used below for cleaning the
	//session, session_sku and invoice tables
	srand(time());

	/*
	** Generate browser information
	*/
	if(GENERATE_CLOAKING_CONSTANTS)
	{
		/*
		** Cloaking Variables 
		** Version 2.1
		** Leon Atkisnon <leon@clearink.com>
		** with contributions from:
		**	Chris Mospaw <mospaw@polk-county.com>
		**	Benjamin Elijah Griffin <bgriffin@cddb.com>
		**
		** This bit of code parses HTTP_USER_AGENT and sets the following variables:
		** Browser_Name
		** Browser_Version
		** Browser_Platform
		** Browser_JavaScriptOK
		** Browser_CSSOK
		** Browser_TextOnly
		** Browser_FileUpload
		**
		** JavaScriptOK means that the browser understands JavaScript on       
		** the same level the Navigator 3 does.  Specifically, it can use  
		** named images.  This allows easier rollovers.  If a browser doesn't
		** do this (Nav 2 or MSIE 3), then we just assume it can't do any 
		** JavaScript.  Referencing images by load order is too hard to maintain.                                 
		**
		** CSSOK is kind of sketchy in that Nav 4 and MSIE work differently,   
		** but they do seem to have most of the functionality.  MSIE 4 for the 
		** Mac has buggy CSS support, so we let it do JavaScript, but no CSS.  
		*/
	
		// Get the name the browser calls itself and what version
		$Browser_Name = strtok($HTTP_USER_AGENT, "/");
		$Browser_Version = strtok(" ");
		
		// MSIE lies about its name
		if(ereg("MSIE", $HTTP_USER_AGENT))
		{
			$Browser_Name = "MSIE";
			$Browser_Version = strtok("MSIE");
			$Browser_Version = strtok(" ");
			$Browser_Version = strtok(";");
		}
	
		// Opera isn't completely honest, either ...
		// Modificaton by Chris Mospaw <mospaw@polk-county.com>
		if(ereg("Opera", $HTTP_USER_AGENT))
		{
			$Browser_Name = "Opera";
			$Browser_Version = strtok("Opera");
			$Browser_Version = strtok("/");
			$Browser_Version = strtok(";");
		}
	
	
		// try to figure out what platform, windows or mac
		$Browser_Platform = "unknown";
		
		if(ereg("Windows",$HTTP_USER_AGENT) || 
			ereg("WinNT",$HTTP_USER_AGENT) ||
			ereg("Win98",$HTTP_USER_AGENT) ||
			ereg("Win95",$HTTP_USER_AGENT))
		{
			$Browser_Platform = "Windows";
		}
		
		if(ereg("Mac", $HTTP_USER_AGENT))
		{
			$Browser_Platform = "Macintosh";
		}
	
		if(ereg("X11", $HTTP_USER_AGENT)) 
		{ 
			$Browser_Platform =  "Unix"; 
		} 
	
		//default to no JavaScript or CSS support
		$Browser_JavaScriptOK = FALSE;
		$Browser_CSSOK = FALSE;
		$Browser_FileUpload = FALSE;
	
		if($Browser_Platform == "Windows")
		{
			if($Browser_Name == "Mozilla")
			{
				if($Browser_Version >= 3.0)
				{
					$Browser_JavaScriptOK = TRUE;
					$Browser_FileUpload = TRUE;
				}		
				if($Browser_Version >= 4.0)
				{
					$Browser_CSSOK = TRUE;
				}
			}
			elseif($Browser_Name == "MSIE")
			{
				if($Browser_Version >= 4.0)
				{
					$Browser_JavaScriptOK = TRUE;
					$Browser_FileUpload = TRUE;
					$Browser_CSSOK = TRUE;
				}		
			}
			elseif($Browser_Name == "Opera")
			{
				if($Browser_Version >= 3.0)
				{
					$Browser_JavaScriptOK = TRUE;
					$Browser_FileUpload = TRUE;
					$Browser_CSSOK = TRUE;
				}		
			}
		}
		elseif($Browser_Platform == "Macintosh")
		{
			if($Browser_Name == "Mozilla")
			{
				if($Browser_Version >= 3.0)
				{
					$Browser_JavaScriptOK = TRUE;
					$Browser_FileUpload = TRUE;
				}		
				if($Browser_Version >= 4.0)
				{
					$Browser_CSSOK = TRUE;
				}
			}
			elseif($Browser_Name == "MSIE")
			{
				if($Browser_Version >= 4.0)
				{
					$Browser_JavaScriptOK = TRUE;
					$Browser_CSSOK = TRUE;
					$Browser_FileUpload = TRUE;
				}		
			}
		}
		elseif($Browser_Platform ==  "Unix") 
		{ 
			if($Browser_Name ==  "Mozilla") 
			{ 
				if($Browser_Version >= 3.0) 
				{ 
					$Browser_JavaScriptOK = TRUE; 
					$Browser_FileUpload = TRUE; 
				}         
				if($Browser_Version >= 4.0) 
				{ 
					$Browser_CSSOK = TRUE; 
				} 
			} 
		}

		//Create the constants
		define('BROWSER_NAME', $Browser_Name);
		define('BROWSER_VERSION', $Browser_Version);
		define('BROWSER_PLATFORM', $Browser_Platform);
		define('BROWSER_JAVASCRIPTOK', $Browser_JavaScriptOK);
		define('BROWSER_CSSOK', $Browser_CSSOK);
		define('BROWSER_TEXTONLY', $Browser_TextOnly);
		define('BROWSER_FILEUPLOAD', $Browser_FileUpload);

	}


	/* 
	** clean out old session ids
	** time()-3600 is 1 hour ago 
	*/
	$Query = "DELETE FROM session WHERE LastAction < '" .
		date("Y-m-d H:i:s", (time()-SESSION_LIFETIME)) . 
		"'";
	$DatabaseResult = mysql_query($Query, $DatabaseLink);


	/*
	** Clean out stale baskets
	** On average, every BASKET_CLEAN_FREQUENCY page views, 
	** clean out stale baskets
	*/
	if(rand()%BASKET_CLEAN_FREQUENCY == 0)
	{
		//get list of sessions
		$Query = "SELECT ID FROM session ";
		$DatabaseResult = mysql_query($Query, $DatabaseLink);
		$SessionIDs = "''";
		while($DatabaseRow = mysql_fetch_row($DatabaseResult))
		{
			$SessionIDs .= ", '" . $DatabaseRow[0] . "'";
		}
		
		//delete all baskets not in list of sessions
		$Query = "DELETE FROM session_sku ";
		$Query .= "WHERE Session not in ($SessionIDs) ";
		$DatabaseResult = mysql_query($Query, $DatabaseLink);
	}


	/*
	** Clean out stale invoices
	** On average, every INVOICE_CLEAN_FREQUENCY page views, 
	** clean out stale invoices
	*/
	if(rand()%INVOICE_CLEAN_FREQUENCY == 0)
	{
		//get purgeInvoice() function
		include(APPLICATION_ROOT . "/modules/include/purgeInvoice");

		//get inactive invoices created more than 
		//INACTIVE_INVOICE_LIFETIME seconds ago
		$Query = "SELECT ID ";
		$Query .= "FROM invoice ";
		$Query .= "WHERE Active='N' ";
		$Query .= "AND User=0 ";
		$Query .= "AND Created < '".date("Y-m-d H:i:s", time()-INACTIVE_INVOICE_LIFETIME)."'  ";
		$DatabaseResult = mysql_query($Query, $DatabaseLink);
		while($DatabaseRow = mysql_fetch_row($DatabaseResult))
		{
			//purge each one
			purgeInvoice($DatabaseRow[0]);
		}
	}


	/*
	** Check sid
	*/
	if(isset($sid))
	{
		//we have sid, check if it's valid
		$Query = "SELECT User, Invoice ";
		$Query .= "FROM session ";
		$Query .= "WHERE ID='$sid' ";
		$DatabaseResult = mysql_query($Query, $DatabaseLink);
				
		if(mysql_num_rows($DatabaseResult))
		{
			list($Session_User, $ActiveInvoice) = mysql_fetch_row($DatabaseResult);
		
			// update its time
			$Query = "UPDATE session SET LastAction = now() " .
				"WHERE ID='$sid'";
			mysql_query($Query, $DatabaseLink);

			$UserInfo = GetUserInfo($Session_User);
			$UserInfo['Invoice'] = $ActiveInvoice;

			if(USE_COOKIES)
			{
				//update session cookie lifetime
				setcookie("sid", $sid, time()+SESSION_LIFETIME);
			}

		}
		else
		{
			//bad sid, so generate a new one
			$ACTION="GENERATE_SID";
			$sid = "";
			
			if(USE_COOKIES)
			{
				//erase cookie
				setcookie("sid");
			}
		}
	
	}
	else
	{
		//missing sid, so generate a new one
		$ACTION="GENERATE_SID";
	}



?>
