<?php
require_once(searchinc('base.inc'));

define('END_OF_UNIX_ERA', 2147483647);
define('START_OF_UNIX_ERA', -2147483648);

define('DT_TZ_PST', -28800);
define('DT_TZ_PDT', -25200);
define('DT_TZ_PET', 'tz_pac');
define('DT_TZ_MST', -25200);
define('DT_TZ_MDT', -21600);
define('DT_TZ_MET', 'tz_mnt');
define('DT_TZ_CST', -21600);
define('DT_TZ_CDT', -18000);
define('DT_TZ_CET', 'tz_cnt');
define('DT_TZ_EST', -18000);
define('DT_TZ_EDT', -14400);
define('DT_TZ_EET', 'tz_est');
define('DT_TZ_GMT', 0);
define('DT_TZ_SERVER_LOCAL', 'svloctz');

if (!defined('DZ_TZ_DEFAULT_LOCAL')) define('DZ_TZ_DEFAULT_LOCAL', DT_TZ_PET);

	function get_client_tz()
	{
		// look in the session, if there is one
		if (isset($_SESSION['user']['timezone']))
		{
			$tz = $_SESSION['user']['timezone'];
		}
		elseif (isset($_SESSION['timezone']))
		{
			$tz = $_SESSION['timezone'];
		}
		// look in the globals
		elseif (isset($GLOBALS['client_timezone']))
		{
			$tz = $GLOBALS['client_timezone'];
		}
		elseif (isset($GLOBALS['default_client_timezone']))
		{
			$tz = $GLOBALS['default_client_timezone'];
		}
		// use the default
		else
		{
			$tz = DZ_TZ_DEFAULT_LOCAL;
		}
		return $tz;
	}
	
	define('DT_TZ_SET_PERMANENT', true);
	define('DT_TZ_SET_SESSION_ONLY', false);
	function set_client_tz($tz, $permanent=DT_TZ_SET_SESSION_ONLY)
	{
		// look in the session, if there is one
		if ($permanent)
		{
			$_SESSION['user']['timezone'] = $tz;
		}
		else
		{
			$_SESSION['timezone'] = $tz;
		}
	}

	class dateobj extends base
	{
//		var $_debug = DEBUG_DETAIL_TRACE;
		
		var $_when;
		var $_when_ts;
		
		var $_request_tz;
		var $_srvrtzoffset;
		var $_usertzoffset;
		var $_usedst;
		
		function __construct($pointintime=null, $tz=DT_TZ_SERVER_LOCAL, $mode=DEFAULT_TRIGGER_ON_ERROR)
		{
			$proc = __CLASS__.'::'.__FUNCTION__.': ';
			$this->dbgecho($proc.'('.look_r($pointintime).','.look_r($tz).') entering', DEBUG_PROC_TRACE);
			
			parent::__construct($mode);
			if ($this->is_ok())
			{
				$this->_request_tz = $tz;
				
				// get local tz offset as specified by user
				if (is_null($tz))
				{
					$tz=DT_TZ_SERVER_LOCAL;
					$this->dbgecho($proc.'Null requested TZ set to '.look_r($tz), DEBUG_DETAIL_TRACE);
				}
				else
				{
					$this->dbgecho($proc.'Requested TZ is '.look_r($tz), DEBUG_DETAIL_TRACE);
				}
				
				$this->_actual_tz_offset($this->_usertzoffset, $this->_usedst, $tz);
				
				// get server tz offset
				$this->_actual_tz_offset($this->_srvrtzoffset, $ignore, DT_TZ_SERVER_LOCAL);
				
				// interpret point in time passed in
				if (!isset($pointintime))
				{
					// use now()
					$pointintime = $this->now();	// in user's requested local timezone
					$this->dbgecho($proc.'initializing with now() '.$pointintime, DEBUG_DETAIL_TRACE);
				}
				elseif (is_a($pointintime, 'dateobj'))
				{
					$pointintime = $pointintime->timestamp($tz);
					$this->dbgecho($proc.'initializing from another dateobj: '.$pointintime, DEBUG_DETAIL_TRACE);
				}
				
				if (is_array($pointintime))
				{
					$this->_when = (float)0;
					$this->dbgecho($proc.'initializing from array', DEBUG_DETAIL_TRACE);
					
					// look for enumerated keys for date/time parts
					// first check for date portions
					if (isset($pointintime['julian']))
					{
						$this->_when = (float)$pointintime['julian'];	// assume this is in user's requested local timezone
						$this->dbgecho($proc.'initializing directly from julian '.((float)$pointintime['julian']), DEBUG_DETAIL_TRACE);
					}
					elseif (isset($pointintime['julian_day']))
					{
						if (!isset($pointintime['year']))
						{
							$pointintime['year'] = date('Y');
							$this->dbgecho($proc.'initializing year with date() '.$pointintime['year'], DEBUG_DETAIL_TRACE);
						}
						// assume this is in user's requested local timezone, but may need to check on what gegoriantojd() does
						$this->_when = (float)(gregoriantojd(1, 1, $pointintime['year'])+($pointintime['julian_day']-1));
						$this->dbgecho($proc.'initializing from julian day '.($pointintime['julian_day']).' of year '.$pointintime['year'], DEBUG_DETAIL_TRACE);
					}
					elseif (isset($pointintime['year']) || isset($pointintime['month']) || isset($pointintime['day']))
					{
						// assume this is in user's requested local timezone, but may need to check on what gegoriantojd() does
						if (!isset($pointintime['year']))
						{
							$pointintime['year'] = date('Y', $this->now($this->_usertzreq));
							$this->dbgecho($proc.'initializing year with date() '.$pointintime['year'], DEBUG_DETAIL_TRACE);
						}
						if (!isset($pointintime['month']))
						{
							$pointintime['month'] = date('n', $this->now($this->_usertzreq));
							$this->dbgecho($proc.'initializing month with date() '.$pointintime['month'], DEBUG_DETAIL_TRACE);
						}
						if (!isset($pointintime['day']))
						{
							$pointintime['day'] = date('j', $this->now($this->_usertzreq));
							$this->dbgecho($proc.'initializing day with date() '.$pointintime['day'], DEBUG_DETAIL_TRACE);
						}
						$this->_when = (float)(gregoriantojd($pointintime['month'], $pointintime['day'], $pointintime['year']));
						$this->dbgecho($proc.'initializing from day '.($pointintime['day']).', month '.($pointintime['month']).' of year '.($pointintime['year']), DEBUG_DETAIL_TRACE);
					}
					
					// check for time portions
					if (isset($pointintime['hour']) || isset($pointintime['minute']) || isset($pointintime['second']))
					{
						// assume this is in user's requested local timezone
						if (!isset($pointintime['hour']))
						{
							$pointintime['hour'] = date('G', $this->now($this->_usertzreq));
							$this->dbgecho($proc.'initializing hour with date() '.$pointintime['hour'], DEBUG_DETAIL_TRACE);
						}
						if (!isset($pointintime['minute']))
						{
							$pointintime['minute'] = date('i',$this->now($this->_usertzreq));
							$this->dbgecho($proc.'initializing minute with date() '.$pointintime['minute'], DEBUG_DETAIL_TRACE);
						}
						if (!isset($pointintime['second']))
						{
							$pointintime['second'] = date('s', $this->now($this->_usertzreq));
							$this->dbgecho($proc.'initializing second with date() '.$pointintime['second'], DEBUG_DETAIL_TRACE);
						}
						$this->_when += (float)(($pointintime['hour']*60*60) +
						                        ($pointintime['minute']*60) +
												$pointintime['second'])/((float)24*60*60);
						$this->dbgecho($proc.'initializing from hour '.($pointintime['hour']).', minute '.($pointintime['minute']).', second '.($pointintime['second']), DEBUG_DETAIL_TRACE);
					}
				}
				elseif (is_numeric($pointintime))
				{
					if ($pointintime == (integer)$pointintime)
					{
						// assume this is a UNIX style timestamp
						$this->_when = unixtojd($pointintime);
						$this->dbgecho($proc.'UNIX timestamp '.$pointintime.' julian is '.$this->_when, DEBUG_DETAIL_TRACE);
						$this->dbgecho($proc.'UNIX timestamp '.$pointintime.' day fraction is '.($pointintime-$this->_jdtounix($this->_when)), DEBUG_DETAIL_TRACE);
						// add any remaining time part
						$this->_when += (($pointintime-$this->_jdtounix($this->_when))/(float)(24*60*60));
						$this->dbgecho($proc.'initializing from UNIX timestamp '.$pointintime, DEBUG_DETAIL_TRACE);
					}
					else
					{
						// assume this is an internal format date/time
						// integer portion is julian day, decimal part is fraction of a day
						$this->_when = $pointintime;
						$this->dbgecho($proc.'initializing from internal value '.$pointintime, DEBUG_DETAIL_TRACE);
					}
				}
				elseif (is_string($pointintime))
				{
					$ts = strtotime($pointintime);
					$this->dbgecho($proc.'Timestamp from '.$pointintime.' is: '.$ts.', '.date('Y-m-d G:i:s', $ts), DEBUG_DETAIL_TRACE);
					
					// initialize date part
					$this->_when = unixtojd($ts);
					$jdts = $this->_jdtounix($this->_when, true);
					$this->dbgecho($proc.'Julian day is: '.$this->_when.', '.date('Y-m-d G:i:s', $jdts), DEBUG_DETAIL_TRACE);
					// add any remaining time part
					$secinday = ($ts-$jdts);
					$secadd = $secinday/((float)(24*60*60));
					$this->dbgecho($proc.'Seconds in day is: '.$secinday.' or '.$secadd.' fraction of a day', DEBUG_DETAIL_TRACE);
					$this->_when += $secadd;
					$this->dbgecho($proc.'initializing from text '.$pointintime, DEBUG_DETAIL_TRACE);
				}
				$this->dbgecho($proc.'internal date value is '.$this->_when.' or '.$this->display('Y-m-d G:i:s'), DEBUG_DETAIL_TRACE);
			}
			
			$this->dbgecho($proc.' leaving - '.($this->is_ok()?'succeeded':'failed'), DEBUG_PROC_TRACE);
			if (!$this->is_ok())
			{
				$this->trigger_error();
			}
//			return $this->is_ok();
		}
		
		function gmt($usedst=false)
		{
			$proc = __CLASS__.'::'.__FUNCTION__.': ';
			$this->dbgecho($proc.'('.($usedst?'DST':'STD').') entering', DEBUG_PROC_TRACE);
			$this->clear_error();
			
			$slt = time();
			$this->dbgecho($proc.'Server local timestamp: '.$slt.', '.date('Y-m-d G:i:s', $slt), DEBUG_DETAIL_TRACE);
			
			$gmt = $slt-$this->_srvrtzoffset;
			$this->dbgecho($proc.'Derived GMT timestamp: '.$gmt.', '.date('Y-m-d G:i:s', $gmt), DEBUG_DETAIL_TRACE);
			
			$dstadj = ($usedst && $this->dst_in_effect($gmt)?(60*60):0)*-1;
			$this->dbgecho($proc.'DST adjustment: '.$dstadj.' seconds', DEBUG_DETAIL_TRACE);
			
			$gmt += $dstadj;
			$this->dbgecho($proc.'Completed GMT timestamp: '.$gmt.', '.date('Y-m-d G:i:s', $gmt), DEBUG_DETAIL_TRACE);
			
			$this->dbgecho($proc.' leaving - '.($this->is_ok()?'succeeded':'failed'), DEBUG_PROC_TRACE);
			return $this->is_ok($gmt);
		}
		
		function now($tz=null)
		{
			$proc = __CLASS__.'::'.__FUNCTION__.': ';
			$this->dbgecho($proc.'('.$tz.') entering', DEBUG_PROC_TRACE);
			$this->clear_error();
			
			$now = $this->gmt();	// current GMT time
			$this->dbgecho($proc.'GMT timestamp: '.$now.', '.date('Y-m-d G:i:s', $now), DEBUG_DETAIL_TRACE);
			if (isset($tz))
			{
				$this->_actual_tz_offset($tzoff, $usedst, $tz);	// in user's requested local timezone
			}
			else
			{
				$tzoff = $this->_usertzoffset;
				$usedst = $this->_usedst;
			}
			if ($this->is_ok())
			{
				$now += $tzoff;
				$this->dbgecho($proc.'Local timestamp: '.$now.' at TZ offset '.$tzoff.', '.date('Y-m-d G:i:s', $now), DEBUG_DETAIL_TRACE);
				if ($usedst)
				{
					$dstoff = ($this->dst_in_effect($now)?(60*60):0);
					$now += $dstoff;
					$this->dbgecho($proc.'DST corrected: '.$now.' using offset '.$dstoff.' seconds, '.date('Y-m-d G:i:s', $now), DEBUG_DETAIL_TRACE);
				}
			}
			
			$this->dbgecho($proc.' leaving - '.($this->is_ok()?'succeeded':'failed'), DEBUG_PROC_TRACE);
			return $this->is_ok($now);
		}
		
		function display($format='', $tz=null)
		{
			return date($format, $this->timestamp($tz));
		}
		
		function as_array($tz=null)
		{
			return getdate($this->timestamp($tz));
		}
		
		function year($tz=null)
		{
			return date('Y', $this->timestamp($tz));
		}
		
		function month($tz=null)
		{
			return date('n', $this->timestamp($tz));
		}
		
		function day($tz=null)
		{
			return date('j', $this->timestamp($tz));
		}
		
		function weekday($tz=null)
		{
			return date('w', $this->timestamp($tz));
		}
		
		function weekday_instance_in_month($tz=null)
		{
			$proc = __CLASS__.'::'.__FUNCTION__.': ';
			$this->dbgecho($proc.'('.$tz.')entering', DEBUG_PROC_TRACE);
			$this->clear_error();
			
			$day = date('j', $this->timestamp($tz));
			$this->dbgecho($proc.'$day: '.$day, DEBUG_DETAIL_TRACE);
			$val = ((integer)(($day-1)/7))+1;
			
			$this->dbgecho($proc.' leaving - '.($this->is_ok()?look_r($val):'failed'), DEBUG_PROC_TRACE);
			return $val;
		}
		
		function hour($tz=null)
		{
			$proc = __CLASS__.'::'.__FUNCTION__.': ';
			$this->dbgecho($proc.'('.$tz.')entering', DEBUG_PROC_TRACE);
			$this->clear_error();
			
			$val = date('G', $this->timestamp($tz));
			$this->dbgecho($proc.$val, DEBUG_DETAIL_TRACE);
			
			$this->dbgecho($proc.' leaving - '.($this->is_ok()?'succeeded':'failed'), DEBUG_PROC_TRACE);
			return $val;
		}
		
		function minute($tz=null)
		{
			return date('i', $this->timestamp($tz));
		}
		
		function second($tz=null)
		{
			return date('s', $this->timestamp($tz));
		}
		
		function julian_day($tz=null)
		{
			$proc = __CLASS__.'::'.__FUNCTION__.': ';
			$this->dbgecho($proc.'('.look_r($tz).')entering', DEBUG_PROC_TRACE);
			$this->clear_error();
			
			if (isset($tz))
			{
				$this->_actual_tz_offset($tzoff, $usedst, $tz);	// in user's requested local timezone
			}
			else
			{
				$tzoff = $this->_usertzoffset;
				$usedst = $this->_usedst;
			}
			
			// calculate the zimezone conversion value in seconds
			$tdiff = 0;
			if ($tzoff != $this->_usertzoffset)
			{
				// convert from user timezone to requested timezone
				$tdiff = ($tzoff-$this->_usertzoffset);
				$this->dbgecho($proc.'time zone conversion from '.$this->_usertzoffset.' to '.$tzoff.' is '.$tdiff, DEBUG_DETAIL_TRACE);
			}
			$dstdiff = 0;
			if (($usedst != $this->_usedst) & $this->dst_in_effect($this->timestamp()))
			{
				$dstdiff += (!$usedst?-1:1)*(60*60);
				$this->dbgecho($proc.'daylight savings conversion is '.$dstdiff, DEBUG_DETAIL_TRACE);
			}
			
			$this->dbgecho($proc.'internal date value is '.$this->_when, DEBUG_DETAIL_TRACE);
			
			// calculate the offset as a day fraction
			if (($tdiff+$dstdiff) > 0)
			{
				$offfract = ($tdiff+$dstdiff)/(24*60*60);
				$this->dbgecho($proc.'conversion is '.$offfract.' days', DEBUG_DETAIL_TRACE);
				
				$this->dbgecho($proc.'converted date value is '.($this->_when+$offfract), DEBUG_DETAIL_TRACE);
			}
			else
			{
				$offract =0.0;
			}
			
			$jd = (integer)($this->_when+$offfract);
			$this->dbgecho($proc.'julian day is '.look_r($jd), DEBUG_DETAIL_TRACE);
			
			return $jd;
		}
		
		function gregorian($tz=null)
		{
			$proc = __CLASS__.'::'.__FUNCTION__.': ';
			$this->dbgecho($proc.'('.look_r($tz).')entering', DEBUG_PROC_TRACE);
			$this->clear_error();
			
			if (isset($tz))
			{
				$this->_actual_tz_offset($tzoff, $usedst, $tz);	// in user's requested local timezone
			}
			else
			{
				$tzoff = $this->_usertzoffset;
				$usedst = $this->_usedst;
			}
			
			// calculate the zimezone conversion value in seconds
			$tdiff = 0;
			if ($tzoff != $this->_usertzoffset)
			{
				// convert from user timezone to requested timezone
				$tdiff = ($tzoff-$this->_usertzoffset);
				$this->dbgecho($proc.'time zone conversion from '.$this->_usertzoffset.' to '.$tzoff.' is '.$tdiff, DEBUG_DETAIL_TRACE);
			}
			$dstdiff = 0;
			if (($usedst != $this->_usedst) & $this->dst_in_effect($this->timestamp()))
			{
				$dstdiff += (!$usedst?-1:1)*(60*60);
				$this->dbgecho($proc.'daylight savings conversion is '.$dstdiff, DEBUG_DETAIL_TRACE);
			}
			
			$this->dbgecho($proc.'internal date value is '.$this->_when, DEBUG_DETAIL_TRACE);
			
			// calculate the offset as a day fraction
			if (($tdiff+$dstdiff) > 0)
			{
				$offfract = ($tdiff+$dstdiff)/(24*60*60);
				$this->dbgecho($proc.'conversion is '.$offfract.' days', DEBUG_DETAIL_TRACE);
				
				$this->dbgecho($proc.'converted date value is '.($this->_when+$offfract), DEBUG_DETAIL_TRACE);
			}
			else
			{
				$offract =0.0;
			}
			
			$greg = jdtogregorian($this->_when+$offfract);
			$this->dbgecho($proc.'converted gregorian date is '.look_r($greg), DEBUG_DETAIL_TRACE);
			
			return $greg;
		}
		
		function timestamp($tz=null)
		{
			$proc = __CLASS__.'::'.__FUNCTION__.': ';
			$this->dbgecho($proc.'('.look_r($tz).') entering', DEBUG_PROC_TRACE);
			$this->clear_error();
			
			if (isset($tz) && ($tz != $this->_request_tz))
			{
				$this->_actual_tz_offset($tzoff, $usedst, $tz);	// in user's requested local timezone
			}
			else
			{
				$tzoff = $this->_usertzoffset;
				$usedst = $this->_usedst;
			}
			
			$this->dbgecho($proc.'internal date value is '.$this->_when.' $usedst='.$usedst.' $this->_usedst='.$this->_usedst, DEBUG_DETAIL_TRACE);
			
			if (!isset($this->_when_ts))
			{
				$dt = (integer)$this->_when;
				$tm = ($this->_when - (float)$dt);
				$this->dbgecho($proc.'julian day value is '.$dt.', fraction of day is '.$tm, DEBUG_DETAIL_TRACE);
			
				$ux = $this->_jdtounix($dt, true);
				$this->dbgecho($proc.'timestanp of day is '.$ux.', '.date('Y-m-d G:i:s', $ux), DEBUG_DETAIL_TRACE);
				$ds = round((24*60*60)*$tm);
				$tmps = $ds % 60;
				$tmpm = ((integer)($ds/60)) % 60;
				$this->dbgecho($proc.'seconds in day is '.$ds.' or '.((integer)($ds/(60*60))).':'.$tmpm.':'.$tmps, DEBUG_DETAIL_TRACE);
			
				$ts = $ux+$ds;
				$this->_when_ts = $ts;
			}
			else
			{
				$ts = $this->_when_ts;
			}
			$this->dbgecho($proc.'timestamp of day and time is '.$ts.', '.date('Y-m-d G:i:s', $ts), DEBUG_DETAIL_TRACE);
			
			if ($tzoff != $this->_usertzoffset)
			{
				// convert from user timezone to requested timezone
				$tdiff = ($tzoff-$this->_usertzoffset);
				$this->dbgecho($proc.'timzone conversion from '.$this->_usertzoffset.' to '.$tzoff.' is '.$tdiff, DEBUG_DETAIL_TRACE);
				$ts += $tdiff;
				$this->dbgecho($proc.'converted timestamp is '.$ts.', '.date('Y-m-d G:i:s', $ts), DEBUG_DETAIL_TRACE);
			}
			if (($usedst != $this->_usedst) & $this->dst_in_effect($ts))
			{
				$dst_adj = (!$usedst?-1:1)*(60*60);
				$ts += $dst_adj;
				$this->dbgecho($proc.'daylight savings time aadjusted by '.$dst_adj.' seconds to '.$ts.', '.date('Y-m-d G:i:s', $ts), DEBUG_DETAIL_TRACE);
			}
			
			$this->dbgecho($proc.' leaving - '.($this->is_ok()?'succeeded':'failed'), DEBUG_PROC_TRACE);
			return $ts;
		}
		
		function _actual_tz_offset(&$tsoff, &$usedst, $tz=null)
		{
			$proc = __CLASS__.'::'.__FUNCTION__.': ';
			$this->dbgecho($proc.'('.look_r($tz).') entering', DEBUG_PROC_TRACE);
			$this->clear_error();
			
			$usedst = false;
			
			if (!isset($tz)) $tz = DT_TZ_SERVER_LOCAL;
			
			switch($tz)
			{
			case DT_TZ_SERVER_LOCAL:
				$usedst = false;
				$tsoff = date('Z');
				break;
			case DT_TZ_PET:
				$usedst = true;
				$tsoff = DT_TZ_PST;
				break;
			case DT_TZ_MET:
				$usedst = true;
				$tsoff = DT_TZ_MST;
				break;
			case DT_TZ_CET:
				$usedst = true;
				$tsoff = DT_TZ_CST;
				break;
			case DT_TZ_EET:
				$usedst = true;
				$tsoff = DT_TZ_EST;
				break;
			default:
				if (!is_numeric($tz) ||
					($tz<(-24*60*60)) ||
					($tz>(24*60*60)))
				{
					$this->set_error('Timezome offset invalid or out of range: '.$tz, __FILE__, __LINE__);
				}
				else
				{
					$usedst = false;
					$tsoff = $tz;
				}
			}
			
			$this->dbgecho($proc.' leaving - '.($this->is_ok()?look_r($tsoff):'failed'), DEBUG_PROC_TRACE);
			return $this->is_ok($act);
		}
		
		function dst_in_effect($ts)
		{
			$proc = __CLASS__.'::'.__FUNCTION__.': ';
			$this->dbgecho($proc.'('.look_r($ts).') entering', DEBUG_PROC_TRACE);
			$this->clear_error();
			
			$ineffect = (date('I', $ts) == 1);
			
			$this->dbgecho($proc.' leaving - '.($this->is_ok()?($ineffect?'true':'false'):'failed'), DEBUG_PROC_TRACE);
			return $this->is_ok($ineffect);
		}
		
		function _jdtounix($jday, $usedst=false)
		{
			$proc = __CLASS__.'::'.__FUNCTION__.': ';
			$ts = jdtounix($jday);
			$this->dbgecho($proc.'Julian day '.$jday.' converts to timestamp: '.$ts.' in server localtime, '.date('Y-m-d G:i:s', $ts), DEBUG_DETAIL_TRACE);
			$gmt = ($ts-$this->_srvrtzoffset);	// correct for offset jdtounix automnatically adds
			$this->dbgecho($proc.'Converts to timestamp in GMT: '.$gmt.' using offset '.$this->_srvrtzoffset.', '.date('Y-m-d G:i:s', $gmt), DEBUG_DETAIL_TRACE);
			$svrnowdst = $this->dst_in_effect(time())?1:0;
			$thendst = $this->dst_in_effect($gmt)?1:0;
			$this->dbgecho($proc.'Svr now DST: '.($svrnowdst?'true':'false').', then DST: '.($thendst?'true':'false'), DEBUG_DETAIL_TRACE);
			if ($svrnowdst != $thendst)
			{
				$dst_adj = ($svrnowdst-$thendst) * (60*60);
				$this->dbgecho($proc.'Magic adjustment of '.$dst_adj.' sec to correct for DST weirdness.', DEBUG_DETAIL_TRACE);
				$gmt += $dst_adj;
				$this->dbgecho($proc.'Adjusted timestamp in GMT: '.$gmt.', '.date('Y-m-d G:i:s', $gmt), DEBUG_DETAIL_TRACE);
			}
			$this->dbgecho($proc.'$usedst: '.($usedst?'true':'fales').', DST in effect: '.($thendst?'true':'false'), DEBUG_DETAIL_TRACE);
/*			if (!$usedst && $this->dst_in_effect($gmt))
			{
				$dst_adj = (60*60);
				$this->dbgecho($proc.'DST in effect but no DST requested.  Removing DST adjustment of '.$dst_adj.' seconds', DEBUG_DETAIL_TRACE);
				$gmt -= $dst_adj;
				$this->dbgecho($proc.'Timestamp in GMT with DST: '.$gmt.', '.date('Y-m-d G:i:s', $gmt), DEBUG_DETAIL_TRACE);
			} */
			return $gmt;
		}
		
		function tz_offset()
		{
			return $this->_usertzoffset;
		}
		
		function has_no_date()
		{
			return ((integer)$this->_when === 0);
		}
		
		function has_no_time()
		{
			return (($this->_when - (float)((integer)$this->_when)) === 0.0);
		}
		
		function to_string($tz=null)
		{
			$proc = __CLASS__.'::'.__FUNCTION__.': ';
			$this->dbgecho($proc.'('.$tzoffset.')entering', DEBUG_PROC_TRACE);
			
			$str = ($this->has_no_date()?'':$this->display('Y-m-d', $tz)).
				   ($this->has_no_time()?'':($this->has_no_date()?'':' ').$this->display('G:i:s', $tz));
			$this->dbgecho($proc.$str, DEBUG_DETAIL_TRACE);
			
			$this->dbgecho($proc.' leaving - '.($this->is_ok()?'succeeded':'failed'), DEBUG_PROC_TRACE);
			return $str;
		}
		
		function range_string($time)
		{
			// are these the same year
			if ($this->year()!=$time->year($this->_usertzreq))
			{
				$format = 'M j, Y';
				$rng = $this->display($format).'-'.$time->display($format, $this->_usertzreq);
			}
			// are these the same month
			elseif ($this->month()!=$time->month($this->_usertzreq))
			{
				$format = 'M j';
				$rng = $this->display($format).'-'.$time->display($format, $this->_usertzreq).' '.$this->year();
			}
			// are these the same date
			elseif ($this->day()!=$time->day($this->_usertzreq))
			{
				$rng = $this->display('M').' '.$this->display('j').'-'.$time->display('j', $this->_usertzreq).' '.$this->year();
			}
			else
			{
				$format = 'M j, Y';
				$rng = $this->display($format);
			}
			
			return $rng;
		}
		
		function diff_seconds($dateobj)
		{
			$proc = __CLASS__.'::'.__FUNCTION__.': ';
			$this->dbgecho($proc.'('.$dateobj->to_string().')entering', DEBUG_PROC_TRACE);
			$this->clear_error();
			
			$finalts = $dateobj->timestamp($this->_request_tz);
			if (!$dateobj->is_ok())
			{
			}
			else
			{
				$final_dst = $this->dst_in_effect($finalts);
				$initialts = $this->timestamp();
				$initial_dst = $this->dst_in_effect($initial_dst);
				$diff = $initialts-$finalts;
				if ($this->_usedst)
				{
					if ($initial_dst && !$final_dst)
					{
						// fall back
						$diff -= (60*60);
					}
					elseif (!$initial_dst && $final_dst)
					{
						// spring forward
						$diff += (60*60);
					}
				}
			}
			$this->dbgecho($proc.' leaving - '.($this->is_ok()?'succeeded':'failed'), DEBUG_PROC_TRACE);
			return $this->is_ok($diff);
		}
		
		function diff_minutes($dateobj)
		{
			$difsecs = $this->diff_seconds($dateobj);
			return $this->is_ok((integer)($difsecs/60));
		}
		
		function diff_hours($dateobj)
		{
			$difsecs = $this->diff_seconds($dateobj);
			return $this->is_ok((integer)($difsecs/(60*60)));
		}
		
		function diff_days($dateobj)
		{
			$difsecs = $this->diff_seconds($dateobj);
			return $this->is_ok((integer)($difsecs/(60*60*24)));
		}
		
		function diff_weeks($dateobj)
		{
			$difsecs = $this->diff_seconds($dateobj);
			return $this->is_ok((integer)($difsecs/(60*60*24*7)));
		}
		
		function diff_months($dateobj)
		{
			$proc = __CLASS__.'::'.__FUNCTION__.': ';
			$this->dbgecho($proc.'('.$dateobj->to_string().')entering', DEBUG_PROC_TRACE);
			$this->clear_error();
			
			$this->dbgecho($proc.'initial date - '.$this->to_string(), DEBUG_PROC_TRACE);
			
			$difsecs = $this->diff_seconds($dateobj);
			$this->dbgecho($proc.'Difference in seconds is '.$difsecs, DEBUG_DETAIL_TRACE);
			if ($difsecs<0)
			{
				$early = $this;
				$late = $dateobj;
				$sign = -1;
			}
			elseif ($difsecs>0)
			{
				$early = $dateobj;
				$late = $this;
				$sign = 1;
			}
			else
			{
				$this->dbgecho($proc.'No difference - returning 0', DEBUG_DETAIL_TRACE);
				return 0;
			}
			$this->dbgecho($proc.'Sign of difference is '.$sign, DEBUG_DETAIL_TRACE);
			$early_day = $early->day();
			$early_month = $early->month();
			$early_year = $early->year();
			$this->dbgecho($proc.'Earlier date is '.$early_month.'/'.$early_day.'/'.$early_year, DEBUG_DETAIL_TRACE);
			$late_day = $late->day();
			$late_month = $late->month();
			$late_year = $late->year();
			$this->dbgecho($proc.'Later date is '.$late_month.'/'.$late_day.'/'.$late_year, DEBUG_DETAIL_TRACE);
			// adjust for last day in month effect
			if ($early_day==cal_days_in_month(CAL_GREGORIAN, $early_month, $early_year) && ($late_day>$early_day))
			{
				$this->dbgecho($proc.'Changing earlier date day to '.$late_day.' because last day in '.$early_month, DEBUG_DETAIL_TRACE);
				$early_day = $late_day;
			}
			elseif ($late_day==cal_days_in_month(CAL_GREGORIAN, $late_month, $late_year) && ($early_day>$late_day))
			{
				$this->dbgecho($proc.'Changing later date day to '.$early_day.' because last day in '.$late_month, DEBUG_DETAIL_TRACE);
				$late_day = $early_day;
			}
			
			$months = 0;
			$years = 0;
			if ($early_day>$late_day)
			{
				$this->dbgecho($proc.'Earlier day ('.$early_day.') larger than later day ('.$late_day.') Set num months to -1.', DEBUG_DETAIL_TRACE);
				$months = -1;
			}
			if (($early_month>$late_month) || (($early_month==$late_month) && $months<0))
			{
				if ($early_month>$late_month)
				{
					$this->dbgecho($proc.'Earlier month ('.$early_month.') larger than later month ('.$late_month.') Set num years to -1.', DEBUG_DETAIL_TRACE);
				}
				else
				{
					$this->dbgecho($proc.'Earlier month same as later month ('.$late_month.') and earlier day larger than later day. Set num years to -1.', DEBUG_DETAIL_TRACE);
				}
				$years = -1;
			}
			$old_months = $months;
			$months += ($early_month!=$late_month)?(12-$early_month)+$late_month+(12*$months):0;
			$this->dbgecho($proc.'Calc months (12-'.$early_month.')+'.$late_month.'+(12*'.$old_months.') as '.$months, DEBUG_DETAIL_TRACE);
			$old_years = $years;
			$years += $late_year-$early_year;
			$this->dbgecho($proc.'Calc years ('.$old_years.'+('.$late_year.'-'.$early_year.') as '.$years, DEBUG_DETAIL_TRACE);
			$this->dbgecho($proc.'Calc total months as ((('.$years.'*12)+'.$months.')*'.$sign.') as '.((($years*12)+$months)*$sign), DEBUG_DETAIL_TRACE);
			
			$this->dbgecho($proc.' leaving - '.($this->is_ok()?'succeeded - '.((($years*12)+$months)*$sign):'failed'), DEBUG_PROC_TRACE);
			return $this->is_ok((($years*12)+$months)*$sign);
		}
		
		function diff_years($dateobj)
		{
			$difmons = $this->diff_months($dateobj);
			return $this->is_ok((integer)($difmons/12));
		}
		
		function equal($dateobj)
		{
			$this->clear_error();
			$equal = 0 === $this->diff_seconds($dateobj);
			return $this->is_ok($equal);
		}
		
		function inc_second($num_secs, $tz=null, $mode=null)
		{
			if (!isset($tz)) $tz=$this->_request_tz;
			if (!isset($mode)) $mode=$this->_mode;
			return new dateobj($this->timestamp()+$num_secs, $tz, $mode);
		}
		
		function inc_minute($num_mins, $tz=null, $mode=null)
		{
			return $this->inc_second($num_mins*60, $tz, $mode);
		}
		
		function inc_hour($num_hours, $tz=null, $mode=null)
		{
			return $this->inc_second($num_hours*(60*60), $tz, $mode);
		}
		
		function inc_day($num_days, $tz=null, $mode=null)
		{
			return $this->inc_second($num_days*(60*60*24), $tz, $mode);
		}
		
		function inc_week($num_weeks, $tz=null, $mode=null)
		{
			return $this->inc_second($num_weeks*(60*60*24*7), $tz, $mode);
		}
		
		function inc_month($num_months, $tz=null, $mode=null)
		{
			// factor months into years and months not greater than 11
			$inc_years = (integer)($num_months/12);
			$inc_month = $num_months%12;
			$this_day_of_month = $this->day();
			$this_month = $this->month();
			$this_year = $this->year();
			if (($this_month+$inc_month)>12)
			{
				$that_year = $this_year+$inc_years+1;
				$that_month = ($this_month+$inc_month)%12;
			}
			elseif(($this_month+$inc_month)<1)
			{
				$that_year = $this_year+$inc_years-1;
				$that_month = 12+($this_month+$inc_month);
			}
			else
			{
				$that_year = $this_year+$inc_years;
				$that_month = $this_month+$inc_month;
			}
			$days_in_that_month = cal_days_in_month(CAL_GREGORIAN, $that_month, $that_year);
			if ($this_day_of_month > $days_in_that_month)
			{
				$that_day = $days_in_that_month;
			}
			else
			{
				$that_day = $this_day_of_month;
			}
			if (!isset($tz)) $tz=$this->_request_tz;
			if (!isset($mode)) $mode=$this->_mode;
			return new dateobj(sprintf('%04u-%02u-%02u %s', $that_year, $that_month, $that_day, $this->display('G:i:s')), DT_TZ_PET, $mode);
		}
		
		function inc_year($num_years, $tz=null, $mode=DEFAULT_TRIGGER_ON_ERROR)
		{
			// factor months into years and months not greater than 11
			$this_day_of_month = $this->day();
			$this_month = $this->month();
			$that_year = $this->year()+$num_years;
			$days_in_that_month = cal_days_in_month(CAL_GREGORIAN, $this_month, $that_year);
			if ($this_day_of_month > $days_in_that_month)
			{
				$that_day = $days_in_that_month;
			}
			else
			{
				$that_day = $this_day_of_month;
			}
			if (!isset($tz)) $tz=$this->_request_tz;
			if (!isset($mode)) $mode=$this->_mode;
			return new dateobj(sprintf('%04u-%02u-%02u %s', $that_year, $this_month, $that_day, $this->display('G:i:s')), DT_TZ_PET, $mode);
		}
	}
	
	class sql_dates extends base
	{
		function __construct($tz=null, $mode=DEFAULT_TRIGGER_ON_ERROR)
		{
			$proc = __CLASS__.'::'.__FUNCTION__.': ';
			$this->dbgecho($proc.'('.look_r($tz).') entering', DEBUG_PROC_TRACE);
			parent::__construct($mode);
			
			$this->dbgecho($proc.' leaving - '.($this->is_ok()?'succeeded':'failed'), DEBUG_PROC_TRACE);
			if (!$this->is_ok())
			{
				$this->trigger_error();
			}
//			return $this->is_ok();
		}
		
		static public function now_sql($tz=null)
		{
			if (!isset($tz)) $tz = get_client_tz();
			$dt = new dateobj(null, $tz);
			return 'date_sub(now(), interval '.($dt->timestamp(DT_TZ_SERVER_LOCAL)-$dt->timestamp(DZ_TZ_DEFAULT_LOCAL)).' SECOND)';
		}
		
		static public function curdate_str_sql($tz=null)
		{
			return 'date_format('.self::now_sql($tz).', \'%Y-%m-%d\')';
		}
		
		static public function curdate_num_sql($tz=null)
		{
			return 'date_format('.self::now_sql($tz).', \'%Y%m%d\')';
		}
		
		static public function curweekday_sql($tz=null)
		{
			return 'WEEKDAY('.self::now_sql($tz).')';
		}
		
		static public function curday_of_month_sql($tz=null)
		{
			return 'DAYOFMONTH('.self::now_sql($tz).')';
		}
		
		static public function curday_of_year_sql($tz=null)
		{
			return 'DAYOFYEAR('.self::now_sql($tz).')';
		}
		
		static public function curmonth_sql($tz=null)
		{
			return 'MONTH('.self::now_sql($tz).')';
		}
		
		static public function curyear_sql($tz=null)
		{
			return 'YEAR('.self::now_sql($tz).')';
		}
		
		static public function start_of_week_sql($tz=null)
		{
			return 'DATE_SUB('.self::curdate_num_sql($tz).', INTERVAL '.self::curweekday_sql($tz).' DAY)';
		}
		
		static public function start_of_month_sql($tz=null)
		{
			return 'DATE_SUB('.self::curdate_num_sql($tz).', INTERVAL ('.self::curday_of_month_sql($tz).'-1) DAY)';
		}
		
		static public function start_of_quarter_sql($tz=null)
		{
			return 'DATE_SUB('.self::start_of_month_sql($tz).', INTERVAL (('.self::curmonth_sql($tz).'-1)%3) MONTH)';
		}
		
		static public function start_of_year_sql($tz=null)
		{
			return 'DATE_SUB('.self::curdate_num_sql($tz).', INTERVAL ('.self::curday_of_year_sql($tz).'-1) DAY)';
		}
		
//		function start_of_specific_previous_month_sql($month, $tz=null)
//		{
//			return 'DATE_SUB('.self::curdate_num_sql($tz.', INTERVAL ('.sql_dates::curday_of_month_sql($tz).'-1) DAY)';
//		}
	}
 ?>