<?php
/*
	(c) 2002 John Lim. Released under BSD-style license. 
	
	Server/Application Variable Support
	
	Do not use Server Variables as a cache for large objects or arrays.
	
	Version 1.01
*/
if (!defined('SERVERVARS_FILE')) define('SERVERVARS_FILE','../_servervars.inc.php');


// called by shutdown function
function _SaveServerVars($name='SERVER')
{
global $$name;

	$array = $$name;
	if (empty($array['save'])) return false;
	
	$d = date('Y-m-d H:i:s');
	$s = "<?php\n/* SERVER VARS START $d */\n\nglobal \$$name;\n\n";
	foreach($array as $k => $v) {
		if ($k == 'save') continue;
		if (is_string($v)) {
			$v = str_replace("'","\\'",$v);
			$s .= "\${$name}['$k'] = '$v';\n";	
		} else if (is_bool($v)) {	
			$v = ($v)? 'true' : 'false';
			$s .= "\${$name}['$k'] = $v;\n";
		} else if (is_numeric($v)) {
			$s .= "\${$name}['$k'] = $v;\n";
		} else {
			$v =  str_replace("'","\\'",serialize($v));
			$s .= "\${$name}['$k'] = unserialize('$v');\n";	
		}
	}
	
	$s .= "\n\${$name}['save']=0; # set this to 1 to save server vars\n/* SERVER VARS END */\n?>";
	
	$f = fopen(SERVERVARS_FILE,'w');
	if ($f === false) {
		LensLog("Unable to create application vars",'APPL',LENSERROR_SEVERE,'NEW',$s);
		return;
	}
	 if ( strtoupper(substr(PHP_OS, 0, 3)) == 'WIN' || flock($f,LOCK_EX))
		$rez = fwrite($f,$s);
	fclose($f);
	
	if ($rez == -1) {
		LensLog("Unable to save application vars",'APPL',LENSERROR_SEVERE,'SAVE',$s);
	}
	$array['save'] = false; # reset so repeated calls do not force save
}

/* Try loading once */
@include(SERVERVARS_FILE);

/* if include failed, give some time to allow writing of other process to complete */
register_shutdown_function('_SaveServerVars');

/* 
	Test if file is being written to, as $SERVER['save'] is saved last.
	So if we are still writing, $SERVER['save'] would not have been written yet.
	This depends on the CPU speed, IO buffering and Hard Disk write speed.
*/
$INCLUDE_SERVERVARS_COUNT = 99;
while (!isset($SERVER['save']) && --$INCLUDE_SERVERVARS_COUNT) {
	@include(APPVARS_FILE);
}

/*
if ($_GET['test']) {
	print $SERVER['cnt'];
	
	$SERVER['cnt'] += 1;
	$SERVER['string'] = "abc def?'\\test";
	$SERVER['array'] = array(1,2,3,4,"the'\\a\"");
	$SERVER['bool'] = false;
	$SERVER['float'] = time();
	$SERVER['save'] = true;
}*/
?>