<?php
// seed mt_srand with microseconds
list($usec, $sec) = explode(' ', microtime());
mt_srand((float) $sec + ((float) $usec * 100000));

function mt_rand_str($minlen=32, $maxlen=null)
{
	if (!isset($maxlen)) $maxlen = $minlen;
	$len = mt_rand($minlen, $maxlen);
	for($r='';
	    strlen($r)<$len;
		$r.=chr(!mt_rand(0,2)?mt_rand(48,57):(!mt_rand(0,1)?mt_rand(65,90):mt_rand(97,122))));
	return $r;
}

function microtime_float()
{
	if (version_compare(php_version(), "5.0", ">="))
	{
		$res = microtime(true);
	}
	else
	{
		list($usec, $sec) = explode(" ", microtime());
		$res = ((float)$usec + (float)$sec);
	}
	return $res;
}

if (!function_exists('is_a')) {
  function is_a( $object, $className ) {
   return ((strtolower($className) == get_class($object))
         or (is_subclass_of($object, $className)));
  }
}

function get_basedir()
{
	static $cache = null;
	
	if (!isset($cache))
	{
		// 
		$uri = strrev($_SERVER['SCRIPT_NAME']);
		$file = strrev($_SERVER['SCRIPT_FILENAME']);
	
		// remove any matching tail (now the head) of these two paths
		while(strlen($uri) && strlen($file) && substr($uri, 0, 1)==substr($file, 0, 1))
		{
			$uri = substr($uri, 1);
			$file = substr($file, 1);
		}
		
		$cache = strrev($uri);
	
	}
	return $cache;
}

// display contents of a variable
function look_r($var, $nesting=null)
{
    // short circuit when doing error, warning and abort tracing.
    if (DEBUG <= 3) return('..');
    
        $neststr = '';
	if (isset($nesting)) $neststr = "<br>\n".str_repeat('&nbsp;&nbsp;&nbsp;', $nesting);
	if (!isset($var))
	{
		$str = ' <null>';
	}
	else if (is_array($var))
	{
		$str = '';
		foreach($var as $key => $value)
		{
			if (strlen($str)>0) $str .= ',';
			$str .= $neststr.$key.' => '.look_r($value, (isset($nesting)?$nesting+1:null));
		}
		$str = ' ['.$str.$neststr.']';
	}
	else if (is_object($var))
	{
		$visited = array();
                $max_levels = 10;
		$str = '';
                
		$vars = get_object_vars($var);  // look into using casting to array, which allows access to protected and private properties.
		foreach($vars as $key => $value)
		{
			if (strlen($str)>0) $str .= ',';
			$str .= $neststr.$key.' => '.look__r($value, $max_levels, (isset($nesting)?$nesting+1:null), $visited);
		}
		$str = $neststr.' <object of class '.get_class($var).' {'.$str.$neststr.'}>';
	}
	else if (is_resource($var))
	{
		$str = $neststr.' <resource of type '.get_resource_type($var).'('.$var.')>';
	}
	else if (is_bool($var))
	{
		$str = ' <'.($var?'true':'false').'>';
	}
	else if (is_string($var))
	{
		$str = ' "'.$var.'"';
	}
	else
	{
		$str = ' '.$var;
	}
	return $str;
}

// a version of look_r that can avoid endless recursion in "base" objects.  Still
// can have a problem with endless recursion in generic objects and arrays
function look__r($var, $max_levels=10, $nesting=null, &$visited)
{
        $neststr = '';
	if (isset($nesting)) $neststr = "<br>\n".str_repeat('&nbsp;&nbsp;&nbsp;', $nesting);
        if ($max_levels <= 0) {
            $str = '...';
        }
	else if (!isset($var))
	{
		$str = ' <null>';
	}
	else if (is_array($var))
	{
                // search for this array in our "visited" list
                $n = 1;
                foreach ($visited as $previous) {
                    if ($previous === $var) {
                        $str = $neststr.'array() =>  recursive array reference [#'.$n.']>.';
                        break;
                    }
                    $n++;
                }
   		if (!isset($str))
		{
                        $str = '';
                        array_push($visited, $var);
                        foreach($var as $key => $value)
                        {
                        	if (strlen($str)>0) $str .= ',';
                        	$str .= $neststr.$key.' => '.look__r($value, $max_levels-1, (isset($nesting)?$nesting+1:null), $visited);
                        }
                        $str = ' ['.$str.$neststr.']';
                }
	}
	else if (is_object($var))
	{
                // search for this object in our "visited" list
                $n = 1;
                foreach ($visited as $previous) {
                        if ($previous === $var) {
                                $str = $neststr.'<object of class '.get_class($var).': recursive object reference [#'.$n.']>.';
                                break;
                        }
                        $n++;
                }
    		if (!isset($str))
		{
        		$str = '';
                        array_push($visited, $var);
                        $vars = get_object_vars($var);  // look into using casting to array, which allows access to protected and private properties.
			foreach($vars as $key => $value)
			{
				if (strlen($str)>0) $str .= ',';
				$str .= $neststr.$key.' => '.look__r($value, $max_levels-1, (isset($nesting)?$nesting+1:null), $visited);
			}
			$str = $neststr.'<object of class '.get_class($var).' {'.$str.$neststr.'}>';
		}
	}
	else if (is_resource($var))
	{
		$str = $neststr.' <resource of type '.get_resource_type($var).'('.$var.')>';
	}
	else if (is_bool($var))
	{
		$str = ' <'.($var?'true':'false').'>';
	}
	else if (is_string($var))
	{
		$str = ' "'.$var.'"';
	}
	else
	{
		$str = ' '.$var;
	}
	return $str;
}

function is_empty($what)
{
	return empty($what);
}

define('PARSE_STATE_IN_SEP', 1);	// state of being within a (possibly multicharcter) separator
define('PARSE_STATE_TOKEN', 2);		// state of being within a token
define('PARSE_STATE_PUNCTUATION', 3);		// state of being within a token
define('PARSE_STATE_IN_QUOT', 4);		// state of being within a quoted string
define('PARSE_STATE_ESCAPE', 5);	// state of detecting an escape character
define('PARSE_STATE_ESCAPE_QUOT', 6);	// state of detecting an escape character
define('PARSE_STATE_TERMINATE_OR_ESCAPE', 7);	// state of detecting an escape character

define('PARSE_ACTION_NEW_TOKEN', 1);	// create a new token
define('PARSE_ACTION_COPY', 2);			// copy character to current token
define('PARSE_ACTION_DISCARD', 3);		// discard character
define('PARSE_ACTION_RETAIN', 4);		// retain character in input and reprocess after state change
define('PARSE_ACTION_RECURSE', 5);		// recurse into parse_quoted_strings with a specified termination charctare
define('PARSE_ACTION_RETURN', 6);		// exit recursion, returning unparsed remainder of string

function parse_quoted_strings($string, &$token, $terminator=null)
{
	$proc = __FUNCTION__.': ';
	base::static_dbgecho($proc.'('.substr($string, 0, 20).'..., '.count($token).', '.$terminator.') entering', DEBUG_PROC_TRACE);
	
	// special characters are '\' escape, "'" single quote, '"' double quote
	// single and double quotes normally start and terminate a quoted string
	// either may be present within the quoted string by escaping with '\'
	// backslash or by doubling.  A backslash within the quoted string must be
	// doubled.
	
	static $consequence;
	
	// structure of parse table is a three dimensional matrix, with the current state as
	// the x axis, a pattern as the y axis, and an action and new state as the z axis
	$tokenchars = '[a-zA-Z0-9_]';
	$parsetable = array( PARSE_STATE_IN_SEP => 
							array ( '\s' => array( 'action' => PARSE_ACTION_DISCARD, 'newstate' => PARSE_STATE_IN_SEP),
							        '"' => array( 'action' => PARSE_ACTION_NEW_TOKEN.','.PARSE_ACTION_DISCARD.','.PARSE_ACTION_RECURSE.' "',
									              'newstate' => PARSE_STATE_IN_QUOT),
							        '\'' => array( 'action' => PARSE_ACTION_NEW_TOKEN.','.PARSE_ACTION_DISCARD.','.PARSE_ACTION_RECURSE.' \'',
									              'newstate' => PARSE_STATE_IN_QUOT),
									$tokenchars => array( 'action' => PARSE_ACTION_NEW_TOKEN.','.PARSE_ACTION_COPY, newstate => PARSE_STATE_TOKEN),
							        '' => array( 'action' => PARSE_ACTION_NEW_TOKEN.','.PARSE_ACTION_COPY, 'newstate' => PARSE_STATE_PUNCTUATION )
								  ),
						 PARSE_STATE_TOKEN => 
							array ( '\s' => array( 'action' => PARSE_ACTION_DISCARD, 'newstate' => PARSE_STATE_IN_SEP),
							        '"' => array( 'action' => PARSE_ACTION_NEW_TOKEN.','.PARSE_ACTION_DISCARD.','.PARSE_ACTION_RECURSE.' "',
									              'newstate' => PARSE_STATE_IN_QUOT),
							        '\'' => array( 'action' => PARSE_ACTION_NEW_TOKEN.','.PARSE_ACTION_DISCARD.','.PARSE_ACTION_RECURSE.' \'',
									              'newstate' => PARSE_STATE_IN_QUOT),
									$tokenchars => array( 'action' => PARSE_ACTION_COPY, newstate => PARSE_STATE_TOKEN),
									'\\\\' => array ( 'action' => PARSE_ACTION_DISCARD, 'newstate' => PARSE_STATE_ESCAPE),
							        '' => array( 'action' => PARSE_ACTION_NEW_TOKEN.','.PARSE_ACTION_COPY, 'newstate' => PARSE_STATE_PUNCTUATION )
							      ),
						 PARSE_STATE_PUNCTUATION => 
							array ( '\s' => array( 'action' => PARSE_ACTION_DISCARD, 'newstate' => PARSE_STATE_IN_SEP),
							        '"' => array( 'action' => PARSE_ACTION_NEW_TOKEN.','.PARSE_ACTION_DISCARD.','.PARSE_ACTION_RECURSE.' "',
									              'newstate' => PARSE_STATE_IN_QUOT),
							        '\'' => array( 'action' => PARSE_ACTION_NEW_TOKEN.','.PARSE_ACTION_DISCARD.','.PARSE_ACTION_RECURSE.' \'',
									              'newstate' => PARSE_STATE_IN_QUOT),
									$tokenchars => array( 'action' => PARSE_ACTION_NEW_TOKEN.','.PARSE_ACTION_COPY, newstate => PARSE_STATE_TOKEN),
							        '' => array( 'action' => PARSE_ACTION_NEW_TOKEN.','.PARSE_ACTION_COPY, 'newstate' => PARSE_STATE_PUNCTUATION )
							      ),
						 PARSE_STATE_IN_QUOT => 
							array ( $terminator => array ( 'action' => PARSE_ACTION_DISCARD, 'newstate' => PARSE_STATE_TERMINATE_OR_ESCAPE),
									'\\\\' => array ( 'action' => PARSE_ACTION_DISCARD, 'newstate' => PARSE_STATE_ESCAPE_QUOT),
									'' => array ( 'action' => PARSE_ACTION_COPY, 'newstate' => PARSE_STATE_IN_QUOT)
							      ),
						 PARSE_STATE_ESCAPE_QUOT => 
							array ( '' => array ( 'action' => PARSE_ACTION_COPY, 'newstate' => PARSE_STATE_IN_QUOT)
								  ),
						 PARSE_STATE_ESCAPE => 
							array ( '' => array ( 'action' => PARSE_ACTION_COPY, 'newstate' => PARSE_STATE_TOKEN)
								  ),
						 PARSE_STATE_TERMINATE_OR_ESCAPE => 
							array ( $terminator => array ( 'action' => PARSE_ACTION_COPY, 'newstate' => PARSE_STATE_IN_QUOT),
									'' => array ( 'action' => PARSE_ACTION_RETURN, 'newstate' => PARSE_STATE_IN_SEP)
							      )
						);
	
	// run the state machine on this string
	$curstate = (!isset($terminator)?PARSE_STATE_IN_SEP:PARSE_STATE_IN_QUOT);
	for($i=0; $i<strlen($string); $i++)
	{
		base::static_dbgecho($proc.'i='.$i.' current state='.$curstate, DEBUG_DETAIL_TRACE);
		foreach($parsetable[$curstate] as $pattern => $consequence)
		{
			$ok = false;
			base::static_dbgecho($proc.'trying pattern=/'.$pattern.'/', DEBUG_DETAIL_TRACE);
			if (($pattern == '') || preg_match('/'.$pattern.'/', substr($string, $i, 1)))
			{
				base::static_dbgecho($proc.'pattern=/'.$pattern.'/ matched', DEBUG_DETAIL_TRACE);
				// perform the action(s) specified
				$actionlist = explode(',', $consequence['action']);
				foreach( $actionlist as $action )
				{
					base::static_dbgecho($proc.'doing action '.$action, DEBUG_DETAIL_TRACE);
					switch((integer)$action)
					{
					case PARSE_ACTION_NEW_TOKEN:
						base::static_dbgecho($proc.'starting new token ['.(count($token)).']', DEBUG_DETAIL_TRACE);
						$token[count($token)] = '';
						break;
					case PARSE_ACTION_COPY:
						base::static_dbgecho($proc.'copy char \''.substr($string, $i, 1).'\' to token ['.(count($token)).']', DEBUG_DETAIL_TRACE);
						$token[count($token)-1] .= substr($string, $i, 1);
						break;
					case PARSE_ACTION_DISCARD:
						base::static_dbgecho($proc.'discard char \''.substr($string, $i, 1).'\'', DEBUG_DETAIL_TRACE);
						break;
					case PARSE_ACTION_RECURSE:
						base::static_dbgecho($proc.'recurse', DEBUG_DETAIL_TRACE);
						$string = parse_quoted_strings(substr($string, $i+1), $token, substr($action, strlen($action)-1));
						$i = -1;
						break;
					case PARSE_ACTION_RETURN:
						base::static_dbgecho($proc.'return str '.substr($string, $i), DEBUG_DETAIL_TRACE);
						return substr($string, $i);
						break;
					default:
					}
				}
				// set the new state
				$curstate = $consequence['newstate'];
				base::static_dbgecho($proc.'new state='.$curstate, DEBUG_DETAIL_TRACE);
				$ok = true;
				break;
			}
		}
		if (!$ok)
		{
			// some bad error in my logic
			break;
		}
	}
	if ($ok) base::static_dbgecho($proc.'returning - '.look_r($token), DEBUG_PROC_TRACE);
	
	base::static_dbgecho($proc.'leaving - '.($ok?'succeeded':'failed'), DEBUG_PROC_TRACE);
	return $ok;
}

define('PARSE_STATE_IN_SEP_MULTI', 8);	// state of being within a (possibly multicharcter) separator

// a more flexible parser with configurable token definition
// implemented as a class
class xsv_parser
{
	var $tokenpattern = '[a-zA-Z0-9_]';
	var $quotepattern = '["\']';
	var $escapechar = '\\\\';
	var $multicharseperators = ' '; 	// seperators where a sequence of multiple separates two tokens
	
	function __construct($tokenchars=null, $chars_include=true)
	{
		if (isset($tokenchars))
		{
			$this->tokenpattern ='['.($chars_include?'':'^').$tokenchars.']';
		}
	}
	
	function multichar_seperators($sep_chars)
	{
		// ensure that none of these are in the are token characters
		for($i=0; $i<strlen($sep_chars); $i++)
		{
			if (preg_match('/'.$this->tokenpattern.'/', substr($sep_chars, $i, 1)))
			{
				trigger_error(__CLASS__.' ERROR: Seperator character ['.substr($sep_chars, $i, 1).'] defined in token pattern '.$this->tokenpattern, E_USER_ERROR);
			}
		}
		$this->multicharseperators = $sep_chars;
	}
	
	function parse($string, &$token)
	{
		return $this->_parse($string, $token);
	}
	
	function _parse($string, &$token, $terminator=null)
	{
		$proc = __CLASS__.'::'.__FUNCTION__.': ';
		
		static $consequence;
		
		// structure of parse table is a three dimensional matrix, with the current state as
		// the x axis, a pattern as the y axis, and an action and new state as the z axis
		$tokenchars = $this->tokenpattern;
		$multiseps = '['.$this->multicharseperators.']';
		$parsetable = array( PARSE_STATE_IN_SEP => 
								array ( $this->quotepattern => array( 'action' => PARSE_ACTION_NEW_TOKEN.','.PARSE_ACTION_DISCARD.','.PARSE_ACTION_RECURSE,
										              'newstate' => PARSE_STATE_IN_QUOT),
										$tokenchars => array( 'action' => PARSE_ACTION_NEW_TOKEN.','.PARSE_ACTION_COPY, newstate => PARSE_STATE_TOKEN),
								        $multiseps => array( 'action' => PARSE_ACTION_NEW_TOKEN.','.PARSE_ACTION_DISCARD, 'newstate' => PARSE_STATE_IN_SEP_MULTI),
										'' => array( 'action' => PARSE_ACTION_NEW_TOKEN.','.PARSE_ACTION_DISCARD, 'newstate' => PARSE_STATE_IN_SEP )
									  ),
							 PARSE_STATE_IN_SEP_MULTI => 
								array ( $this->quotepattern => array( 'action' => PARSE_ACTION_NEW_TOKEN.','.PARSE_ACTION_DISCARD.','.PARSE_ACTION_RECURSE,
										              'newstate' => PARSE_STATE_IN_QUOT),
										$tokenchars => array( 'action' => PARSE_ACTION_NEW_TOKEN.','.PARSE_ACTION_COPY, newstate => PARSE_STATE_TOKEN),
								        $multiseps => array( 'action' => PARSE_ACTION_DISCARD, 'newstate' => PARSE_STATE_IN_SEP_MULTI),
							    	    '' => array( 'action' => PARSE_ACTION_NEW_TOKEN.','.PARSE_ACTION_DISCARD, 'newstate' => PARSE_STATE_IN_SEP )
								      ),
							 PARSE_STATE_TOKEN => 
								array ( $this->quotepattern => array( 'action' => PARSE_ACTION_NEW_TOKEN.','.PARSE_ACTION_DISCARD.','.PARSE_ACTION_RECURSE,
										              'newstate' => PARSE_STATE_IN_QUOT),
										$this->escapechar => array ( 'action' => PARSE_ACTION_DISCARD, 'newstate' => PARSE_STATE_ESCAPE),
										$tokenchars => array( 'action' => PARSE_ACTION_COPY, newstate => PARSE_STATE_TOKEN),
								        $multiseps => array( 'action' => PARSE_ACTION_DISCARD, 'newstate' => PARSE_STATE_IN_SEP_MULTI),
							    	    '' => array( 'action' => PARSE_ACTION_DISCARD, 'newstate' => PARSE_STATE_IN_SEP )
								      ),
							 PARSE_STATE_IN_QUOT => 
								array ( $terminator => array ( 'action' => PARSE_ACTION_DISCARD, 'newstate' => PARSE_STATE_TERMINATE_OR_ESCAPE),
										$this->escapechar => array ( 'action' => PARSE_ACTION_DISCARD, 'newstate' => PARSE_STATE_ESCAPE_QUOT),
										'' => array ( 'action' => PARSE_ACTION_COPY, 'newstate' => PARSE_STATE_IN_QUOT)
								      ),
							 PARSE_STATE_ESCAPE_QUOT => 
								array ( '' => array ( 'action' => PARSE_ACTION_COPY, 'newstate' => PARSE_STATE_IN_QUOT)
									  ),
							 PARSE_STATE_ESCAPE => 
								array ( '' => array ( 'action' => PARSE_ACTION_COPY, 'newstate' => PARSE_STATE_TOKEN)
									  ),
							 PARSE_STATE_TERMINATE_OR_ESCAPE => 
								array ( $terminator => array ( 'action' => PARSE_ACTION_COPY, 'newstate' => PARSE_STATE_IN_QUOT),
										'' => array ( 'action' => PARSE_ACTION_RETURN, 'newstate' => PARSE_STATE_TOKEN)
								      )
							);
		
		// run the state machine on this string
		$curstate = (!isset($terminator)?PARSE_STATE_IN_SEP:PARSE_STATE_IN_QUOT);
		for($i=0; $i<strlen($string); $i++)
		{
			base::static_dbgecho($proc.'i='.$i.' current state='.$curstate, DEBUG_DETAIL_TRACE);
			foreach($parsetable[$curstate] as $pattern => $consequence)
			{
				$ok = false;
				base::static_dbgecho($proc.'trying pattern=/'.$pattern.'/', DEBUG_DETAIL_TRACE);
				if (($pattern == '') || preg_match('/'.$pattern.'/', substr($string, $i, 1)))
				{
					base::static_dbgecho($proc.'pattern=/'.$pattern.'/ matched', DEBUG_DETAIL_TRACE);
					// perform the action(s) specified
					$actionlist = explode(',', $consequence['action']);
					foreach( $actionlist as $action )
					{
						base::static_dbgecho($proc.'doing action '.$action, DEBUG_DETAIL_TRACE);
						switch((integer)$action)
						{
						case PARSE_ACTION_NEW_TOKEN:
							base::static_dbgecho($proc.'starting new token ['.(count($token)).']', DEBUG_DETAIL_TRACE);
							$token[count($token)] = '';
							break;
						case PARSE_ACTION_COPY:
							base::static_dbgecho($proc.'copy char \''.substr($string, $i, 1).'\' to token ['.(count($token)).']', DEBUG_DETAIL_TRACE);
							$token[count($token)-1] .= substr($string, $i, 1);
							break;
						case PARSE_ACTION_DISCARD:
							base::static_dbgecho($proc.'discard char \''.substr($string, $i, 1).'\'', DEBUG_DETAIL_TRACE);
							break;
						case PARSE_ACTION_RECURSE:
							base::static_dbgecho($proc.'recurse', DEBUG_DETAIL_TRACE);
							$string = $this->_parse(substr($string, $i+1), $token, substr($string, $i, 1));
							$i = -1;
							break;
						case PARSE_ACTION_RETURN:
							base::static_dbgecho($proc.'return str '.substr($string, $i), DEBUG_DETAIL_TRACE);
							return substr($string, $i);
							break;
						default:
						}
					}
					// set the new state
					$curstate = $consequence['newstate'];
					base::static_dbgecho($proc.'new state='.$curstate, DEBUG_DETAIL_TRACE);
					$ok = true;
					break;
				}
			}
			if (!$ok)
			{
				// some bad error in my logic
				break;
			}
		}
		if ($ok) base::static_dbgecho($proc.'returning - '.look_r($token), DEBUG_PROC_TRACE);
	
		base::static_dbgecho($proc.'leaving - '.($ok?'succeeded':'failed'), DEBUG_PROC_TRACE);
		return $ok;
	}
}

function & smart_strip_gpc_quotes(&$var)
{
	if (get_magic_quotes_gpc())
	{
		if (is_string($var))
		{
			$var = stripslashes($var);
		}
		elseif (is_array($var))
		{
			foreach($var as $key => $val)
			{
				smart_strip_gpc_quotes($var[$key]);
			}
		}
	}
	
	return $var;
}

function array_max($list)
{
	$max = reset($list);
	foreach($list as $val)
	{
		if ($val > $max) $max = $val;
	}
	return $max;
}

function array_min($list)
{
	$min = reset($list);
	foreach($list as $val)
	{
		if ($val < $min) $min = $val;
	}
	return $min;
}

function get_config_number($str)
{
	$val = (integer)trim($str);
	switch (substr($str, -1))
	{
	case 'g':
	case 'G';
		$val *= 1024;
	case 'm':
	case 'M';
		$val *= 1024;
	case 'k';
	case 'K';
		$val *= 1024;
	}
	
	return $val;
}

function remove_request_option($url, $option)
{
	// break request into components
	if (!$parts = parse_url($url))
	{
		$url = false;
	}
	else
	{
		// turn query portion into array
		if (isset($parts['query']))
		{
			$qarray = explode('&', $parts['query']);
			$parts['query'] = '';
			foreach($qarray as $optval)
			{
				$oarray = explode('=', $optval);
				// remove the option
				if ($oarray[0] !== $option)
				{
					if (strlen($parts['query'])>0) $parts['query'] .= '&';
					$parts['query'] .= $optval;
				}
			}
			
			// reassemble request
			$url = (isset($parts['scheme'])?($parts['scheme'].'://'):'').
				   (isset($parts['user'])?$parts['user'].
				   		(isset($parts['pass'])?':'.$parts['pass']:'').'@':'').
				   (isset($parts['host'])?$parts['host']:'').
				   (isset($parts['port'])?':'.$parts['port']:'').
				   (isset($parts['path'])?$parts['path']:'/').
				   (isset($parts['query'])?'?'.$parts['query']:'').
				   (isset($parts['fragment'])?'#'.$parts['fragment']:'');
		}
	}
	
	return $url;
}

function ensure_request_option($url, $option, $value)
{
	// break request into components
	if (!$parts = parse_url($url))
	{
		$url = false;
	}
	else
	{
		$optionfound = false;
                if (isset($parts['query']))
                {
                    // turn query portion into array
                    $qarray = explode('&', $parts['query']);
                    $parts['query'] = '';
                    foreach($qarray as $optval)
                    {
			$oarray = explode('=', $optval);
			// check for the option
			if (isset($oarray[0]) && $oarray[0] == $option)
			{
				// replace option
				if (strlen($parts['query'])>0) $parts['query'] .= '&';
				$parts['query'] .= $option.'='.urlencode($value);
				$optionfound = true;
			}
			else
			{
				if (strlen($parts['query'])>0) $parts['query'] .= '&';
				$parts['query'] .= $optval;
			}
                    }
                }
		if (!$optionfound)
		{
			// add new option
                    if (isset($parts['query']))
                    {
                        if (strlen($parts['query'])>0) { $parts['query'] .= '&'; }
			$parts['query'] .= $option.'='.urlencode($value);
                    }
                    else
                    {
                        $parts['query'] = $option.'='.urlencode($value);
                    }
		}
		
		// reassemble request
		$url = (isset($parts['scheme'])?$parts['scheme'].'://':'').
			   (isset($parts['user'])?$parts['user'].
			   		(isset($parts['pass'])?':'.$parts['pass']:'').'@':'').
			   (isset($parts['host'])?$parts['host']:'').
			   (isset($parts['port'])?':'.$parts['port']:'').
			   (isset($parts['path'])?$parts['path']:'/').
			   (isset($parts['query'])?'?'.$parts['query']:'').
			   (isset($parts['fragment'])?'#'.$parts['fragment']:'');
	}
	
	return $url;
}

function ensure_request_fragment($url, $fragment)
{
	// break request into components
	if (!$parts = parse_url($url))
	{
		$url = false;
	}
	else
	{
		// replace or remove fragment
		if (isset($fragment))
		{
			$parts['fragment'] = $fragment;
		}
		else
		{
			unset($parts['fragment']);
		}
		
		// reassemble request
		$url = (isset($parts['scheme'])?$parts['scheme'].'://':'').
			   (isset($parts['user'])?$parts['user'].
			   		(isset($parts['pass'])?':'.$parts['pass']:'').'@':'').
			   (isset($parts['host'])?$parts['host']:'').
			   (isset($parts['port'])?':'.$parts['port']:'').
			   (isset($parts['path'])?$parts['path']:'/').
			   (isset($parts['query'])?'?'.$parts['query']:'').
			   (isset($parts['fragment'])?'#'.$parts['fragment']:'');
	}
	
	return $url;
}

function html_obfusticate($str)
{
	$tmp='';
	for($i=0; $i<strlen($str); $i++)
	{
		$tmp.='&#'.ord($str[$i]).';';
	}
	return $tmp;
}

function logmsg($txt, $logfile, $nl=true)
{
	static $eol = true;
	
	if (!isset($GLOBALS['_utils1_log_conn'][$logfile]))
	{
		$GLOBALS['_utils1_log_conn'][$logfile] = fopen($logfile, 'a');
		if ($GLOBALS['_utils1_log_conn'][$logfile] === false)
		{
			unset($GLOBALS['_utils1_log_conn'][$logfile]);
		}
	}
	if (isset($GLOBALS['_utils1_log_conn'][$logfile]))
	{
		list($usec, $sec) = explode(' ', microtime());
		fwrite($GLOBALS['_utils1_log_conn'][$logfile], ($eol?('['.date('m/d/y H:i:s').substr($usec, 1, 5).'] '):'').$txt.($nl?"\n":''));
		$eol = $nl;
	}
}

function array_merge_v4($a1, $a2)
{
	if (is_null($a1)) $a1 = array();
	if (is_null($a2)) $a2 = array();
	if (!is_array($a1)) $a1 = array($a1);
	if (!is_array($a2)) $a2 = array($a2);
	$tmp = array_merge($a1, $a2);
	return $tmp;
}

function root($a,$p)
{
	return	(($a<0 && $p%2>0)? -1 : 1 ) * pow(abs($a),1/$p);
}

function unpow($val, $root)
{
	if ($val == 1) return 0;
	$i = 0;
	do {
		$res = pow($root, ++$i);
	} while ($res < $val);
	if ($res > $val)
	{
		$maxloops = 20;
		$min = $i-1; $max = $i;
		for($x=0; $x<$maxloops; $x++)
		{
			$i = ($min+$max)/2;
			$res = pow($root, $i);
			if ($res < $val)
			{
				$min = $i;
			}
			elseif ($res > $val)
			{
				$max = $i;
			}
			else
			{
				break;
			}
		}
	}
	return $i;
}

/**
Validate an email address.
Provide email address (raw input)
Returns true if the email address has the email 
address format and the domain exists.
*/
function validEmail($email, $checkdns=false)
{
   $isValid = true;
   $atIndex = strrpos($email, "@");
   if (is_bool($atIndex) && !$atIndex)
   {
      $isValid = false;
   }
   else
   {
      $domain = substr($email, $atIndex+1);
      $local = substr($email, 0, $atIndex);
      $localLen = strlen($local);
      $domainLen = strlen($domain);
      if ($localLen < 1 || $localLen > 64)
      {
         // local part length exceeded
         $isValid = false;
      }
      else if ($domainLen < 1 || $domainLen > 255)
      {
         // domain part length exceeded
         $isValid = false;
      }
      else if ($local[0] == '.' || $local[$localLen-1] == '.')
      {
         // local part starts or ends with '.'
         $isValid = false;
      }
      else if (preg_match('/\\.\\./', $local))
      {
         // local part has two consecutive dots
         $isValid = false;
      }
      else if (!preg_match('/^[A-Za-z0-9.-]+$/', $domain))
      {
         // character not valid in domain part
         $isValid = false;
      }
      else if (preg_match('/\\.\\./', $domain))
      {
         // domain part has two consecutive dots
         $isValid = false;
      }
      else if (!preg_match('/^(\\\\.|[A-Za-z0-9!#%&`_=\\/$\'*+?^{}|~.-])+$/',
                 str_replace("\\\\","",$local)))
      {
         // character not valid in local part unless 
         // local part is quoted
         if (!preg_match('/^"(\\\\"|[^"])+"$/',
             str_replace("\\\\","",$local)))
         {
            $isValid = false;
         }
      }
      if ($isValid && $checkdns && !(checkdnsrr($domain,"MX") || checkdnsrr($domain,"A")))
      {
         // domain not found in DNS
         $isValid = false;
      }
   }
   return $isValid;
}
 ?>