GIF89a; %PDF-1.5 %���� ºaâÚÎΞ-ÌE1ÍØÄ÷{òò2ÿ ÛÖ^ÔÀá TÎ{¦?§®¥kuµù Õ5sLOšuY Donat Was Here
DonatShell
Server IP : 134.29.175.74  /  Your IP : 216.73.216.160
Web Server : nginx/1.10.2
System : Windows NT CST-WEBSERVER 10.0 build 19045 (Windows 10) i586
User : Administrator ( 0)
PHP Version : 7.1.0
Disable Function : NONE
MySQL : OFF  |  cURL : ON  |  WGET : OFF  |  Perl : OFF  |  Python : OFF  |  Sudo : OFF  |  Pkexec : OFF
Directory :  C:/nginx/html/JimMartinson/_Archive/MMDT1145/_Archive/Common/

Upload File :
current_dir [ Writeable ] document_root [ Writeable ]

 

Command :


[ HOME SHELL ]     

Current File : C:/nginx/html/JimMartinson/_Archive/MMDT1145/_Archive/Common//functions.phpinc
<?
// functions.phpinc
// Setus up application variables and functions.
if (isset($GLOBALS['TRACK']) && $GLOBALS['TRACK'] != '') $_SESSION['TRACK'] .= "<li><b>".basename(__FILE__)."</b> (".__FILE__.")\n<ol>\n";

// arrayToList($array,$separator)
// Returns the array as an trimmed list.
//      $array = the array used to create the list.
// $separator = the list separator. Default is a comma ','.
function arrayToList($array,$separator=',') {
	$list = '';
	foreach($array as $item) {
		$list .= $item.$separator;
	}
	$list = substr($list,0,-1);
	if (isset($GLOBALS['TRACK']) && $GLOBALS['TRACK'] != '') { $_SESSION['TRACK'] .= '<li class="db_f">function '."arrayToList($array,$separator)=$list".": ".basename(__FILE__).":".__LINE__."</li>\n"; }
	return $list;
}

// classDueDate($meetingTime,$startDate,$week,$day)
// Returns the due date given a meeeting time, starting date, a week number, and an optional day offset.
// Example: classDueDate('10:00am-11:001am','2007-01-22',1) returns "before 10:00am on Monday, January 22nd 2007".
function classDueDate($meetingTime,$startDate,$week,$day=0) {
	if (is_array($meetingTime)) $meetingTime = $meetingTime[0];
	if (is_array($startDate)) $startDate = $startDate[0];
	// A week = 60*60*24*7 = 604800. A day = 60*60*24 = 86400.
	//echo "<b>".$meetingTime."</b><br>\n";
	#$startDate = $startDateArray[count($startDateArray)-1];
	if ($meetingTime != 'START-END') {
		#printVar('$meetingTime',$meetingTime);
		#printVar('$startDate',$startDate);
		$classDueDate = 'before '.ereg_replace('-.*$',"",$meetingTime).' on '.date("l, F jS Y",strtotime($startDate)+($week-1)*604800+$day*86400+43200); // Added half a day (43200) to stop math errors.
		#$classDueDate = ereg_replace('-.*$',"",$meetingTime).' on '.date("l, F jS Y",strtotime($startDate)+($week-1)*604800+$day*86400+43200); // Added half a day (43200) to stop math errors.
	} else {
		if ($startDate == '' || $startDate == 'STARTDATE') {
			$classDueDate = 'by week '.$week;
		} else {
			$classDueDate = 'by '.date("l, F jS Y",strtotime($startDate)+($week-1)*604800+$day*86400+43200); // Added half a day (43200) to stop math errors.	
			#$classDueDate = date("l, F jS Y",strtotime($startDate)+($week-1)*604800+$day*86400+43200); // Added half a day (43200) to stop math errors.	
		}
	}
	if (isset($GLOBALS['TRACK']) && $GLOBALS['TRACK'] != '') $_SESSION['TRACK'] .= '<li class="db_f">function '."classDueDate($meetingTime,$startDate,$week,$day)=[$classDueDate]".'</li>'."\n";
	return $classDueDate;
}

// classCourseNumber($classId)
// Returns the course number for that classId.
// $classId = The classId to use for looking up the course number.
function classCourseNumber($classId) {
	$query = "
 SELECT courseNumber
   FROM course
  INNER JOIN class ON course.courseId = class.courseId
  WHERE class.classId = ".$classId."
	";
	$courseResult = query_do($query);
	$courseCount = $_SESSION['mysql_num_rows'];
	if ($courseCount) {
		$courseRow = mysql_fetch_assoc($courseResult);
		$courseNumber = $courseRow['courseNumber'];
	} else {
		$courseNumber = "Unknown";
	}
	if (isset($GLOBALS['TRACK']) && $GLOBALS['TRACK'] != '') $_SESSION['TRACK'] .= '<li class="db_f">function '."classCourseNumber($classId)=[$courseNumber]".'</li>'."\n";
	return $courseNumber;
}

// classWeekDate($startDateArray,$week,$day)
// Returns the date given a starting date, a week number, and an optional day offset.
// Example: classWeekDate('2007-01-22',1) returns "Monday, January 22nd 2007".
function classWeekDate($startDate,$week,$day=0) {
	$classWeekDate = '';
	if (!is_array($startDate)) {
		$classDate = strtotime($startDate)+($week-1)*604800+$day*86400+43200; // Added half a day (43200) to stop math errors.
		$classWeekDate = listAppend($classWeekDate,date("l F jS Y",$classDate));
	} else {
		foreach ($startDate as $thisDate) {
			$classDate = strtotime($thisDate)+($week-1)*604800+$day*86400+43200; // Added half a day (43200) to stop math errors.
			$classWeekDate = listAppend($classWeekDate,date("l F jS Y",$classDate));
		}
	}
	#echo "\$classWeekDate=".$classWeekDate."<br>\n";
	$datetime = getdate();
	$currentDate = strtotime($datetime['year']."-".twoDigit($datetime['mon'])."-".twoDigit($datetime['mday']));
	$satDate = $currentDate-($datetime['wday']!=6?$datetime['wday']+1:0)*86400;
	$friDate = $currentDate+($datetime['wday']!=6?5-$datetime['wday']:6)*86400+86399;
	/* *-/
	echo "\$classDate=".$classDate."<br>\n";
	echo "\$datetime="; print_r($datetime); echo "<br>\n";
	echo "\$currentDate=".$currentDate."<br>\n";
	echo "\$satDate=".$satDate."<br>\n";
	echo "\$friDate=".$friDate."<br>\n";
	/* */
	$classWeekDate = listAnd($classWeekDate);
	$classWeekDate = $classWeekDate.' <span class="small">Week '.$week.'</span>';
	if (isset($GLOBALS['TRACK']) && $GLOBALS['TRACK'] != '') $_SESSION['TRACK'] .= '<li class="db_f">function '."classWeekDateCSS($startDate,$week,$day=0)=[$classWeekDate]".'</li>'."\n";
	return $classWeekDate;
}

function classWeekDateCSS($startDate,$week,$day=0) {
	$classWeekDate = '';
	if ((!is_array($startDate) && ($startDate == '' || $startDate == 'STARTDATE')) || (is_array($startDate) && ($startDate[0] == '' || $startDate[0] == 'STARTDATE'))) {
		$classWeekDateCSS = '<span class="classDate"> Week '.$week.'</span>';
	} else {
		if (!is_array($startDate)) {
			$classDate = strtotime($startDate)+($week-1)*604800+$day*86400+43200; // Added half a day (43200) to stop math errors.
			$classWeekDate = listAppend($classWeekDate,date("l F jS Y",$classDate));
		} else {
			foreach ($startDate as $thisDate) {
				$classDate = strtotime($thisDate)+($week-1)*604800+$day*86400+43200; // Added half a day (43200) to stop math errors.
				$classWeekDate = listAppend($classWeekDate,date("l F jS Y",$classDate));
			}
		}
		#echo "\$classWeekDate=".$classWeekDate."<br>\n";
		$datetime = getdate();
		$currentDate = strtotime($datetime['year']."-".twoDigit($datetime['mon'])."-".twoDigit($datetime['mday']));
		$satDate = $currentDate-($datetime['wday']!=6?$datetime['wday']+1:0)*86400;
		$friDate = $currentDate+($datetime['wday']!=6?5-$datetime['wday']:6)*86400+86399;
		/* *-/
		echo "\$classDate=".$classDate."<br>\n";
		echo "\$datetime="; print_r($datetime); echo "<br>\n";
		echo "\$currentDate=".$currentDate."<br>\n";
		echo "\$satDate=".$satDate."<br>\n";
		echo "\$friDate=".$friDate."<br>\n";
		/* */
		$classWeekDate = listAnd($classWeekDate);
		if ($classDate < $satDate || $classDate > $friDate) {
			$classWeekDateCSS = '<span class="classDate">'.$classWeekDate.'</span> <span class="small">Week '.$week.'</span>';
		} else {
			$classWeekDateCSS = '<span class="classDateToday">'.$classWeekDate.'</span> <span class="small">Week '.$week.'</span>';
		}
	}
	if (isset($GLOBALS['TRACK']) && $GLOBALS['TRACK'] != '') $_SESSION['TRACK'] .= '<li class="db_f">function '."classWeekDateCSS($startDate,$week,$day=0)=[$classWeekDateCSS]".'</li>'."\n";
	return $classWeekDateCSS;
}

// courseDeptNumber($courseNumber)
// Returns an array with [0]=department and [1]=number.
// $courseNumber = the course number to parse.
function courseDeptNumber($courseNumber) {
	$courseDeptNumber = array(strtoupper(ereg_replace('[0-9]',"",$courseNumber)),ereg_replace('[A-Za-z]',"",$courseNumber	));
	if (isset($GLOBALS['TRACK']) && $GLOBALS['TRACK'] != '') { $_SESSION['TRACK'] .= '<li class="db_f">function '."courseDeptNumber($courseNumber)=Array "; foreach($courseDeptNumber as $key=>$value) { $_SESSION['TRACK'] .= "[$key]=$value "; } $_SESSION['TRACK'] .= '</li>'."\n"; }
	return $courseDeptNumber;
}

// currentDate()
// Returns the current date.
function currentDate() {
	$datetime = getdate();
	$currentDate =$datetime['year']."-".$datetime['mon']."-".$datetime['mday'];
	if (isset($GLOBALS['TRACK']) && $GLOBALS['TRACK'] != '') $_SESSION['TRACK'] .= '<li class="db_f">function '."currentDate()=$currentDate".": ".basename(__FILE__).":".__LINE__."</li>\n";
	return $currentDate;
}

//CRtoBR($string)
// Returns $string with all \n converted to <br />
function CRtoBR($string) {
	$CRtoBR = str_replace("\n", "<br />", $string);
	if (isset($GLOBALS['TRACK']) && $GLOBALS['TRACK'] != '') $_SESSION['TRACK'] .= '<li class="db_f">function '."CRtoBR($string)=$CRtoBR".": ".basename(__FILE__).":".__LINE__."</li>\n";
	return $CRtoBR;
}

// currentDateTime()
// Returns the current date and time.
function currentDateTime() {
	$datetime = getdate();
	$currentDateTime = $datetime['year']."-".twoDigit($datetime['mon'])."-".twoDigit($datetime['mday'])." ".twoDigit($datetime['hours']).":".twoDigit($datetime['minutes']).":".twoDigit($datetime['seconds']);
	if (isset($GLOBALS['TRACK']) && $GLOBALS['TRACK'] != '') $_SESSION['TRACK'] .= '<li class="db_f">function '."currentDateTime()=$currentDateTime".": ".basename(__FILE__).":".__LINE__."</li>\n";
	return $currentDateTime;
}

// date_difference($start_date, $end_date, $workdays_only = false, $skip_holidays = false)
// Calculates the number of work days between 2 given times.
// $start_date = First date.
// $end_date = Second date.
// $workdays_only =  Whether to count only work days (eg. Mon-Fri). default is false.
// $skip_holidays = Whether to use the get_holidays() function to skip holiday days as well. default is false.
function date_difference($start_date, $end_date, $workdays_only = false, $skip_holidays = false) {
	if ($start_date == '') { return 999999999; }
	if ($end_date == '') { return 999999999; }
	$start_date = strtotime($start_date);
	$end_date = strtotime($end_date);
	if ($start_date > 0 && $end_date > 0) {
    $seconds_in_a_day = 86400;
    $sunday_val = "0";
    $saturday_val = "6";
    $workday_counter = 0;
    $holiday_array = array();

    $ptr_year = intval(date("Y", $start_date));
    $holiday_array[$ptr_year] = get_holidays(date("Y", $start_date));

    for($day_val = $start_date; $day_val <= $end_date; $day_val+=$seconds_in_a_day) {
        $pointer_day = date("w", $day_val);
        if ($workdays_only == true) {
            if (($pointer_day != $sunday_val) AND ($pointer_day != $saturday_val)) {
                if ($skip_holidays == true) {
                    if (intval(date("Y", $day_val))!=$ptr_year) {
                        $ptr_year = intval(date("Y", $day_val));
                        $holiday_array[$ptr_year] = get_holidays(date("Y", $day_val));
                    }
                    if (!in_array($day_val, $holiday_array[date("Y", $day_val)])) {
                        $workday_counter++;
                    }
                } else {
                    $workday_counter++;
                }
            }
        } else {
            if ($skip_holidays == true) {
                if (intval(date("Y", $day_val))!=$ptr_year) {
                    $ptr_year = intval(date("Y", $day_val));
                    $holiday_array[$ptr_year] = get_holidays(date("Y", $day_val));
                }
                if (!in_array($day_val, $holiday_array[date("Y", $day_val)])) {
                    $workday_counter++;
                }
            } else {
                $workday_counter++;
            }
        }
    }
    $date_difference = $workday_counter;
	} else {
		$date_difference =  0;
	}
	if (isset($GLOBALS['TRACK']) && $GLOBALS['TRACK'] != '') $_SESSION['TRACK'] .= '<li class="db_f">function '."date_difference($start_date, $end_date, $workdays_only, $skip_holidays)=$date_difference".": ".basename(__FILE__).":".__LINE__."</li>\n";
	return $date_difference;
}

// decimalIP($IPaddress)
// Returns decimal ip address
function decimalIP($IPaddress) {
	$octet = explode(".",$IPaddress);
	$decimalIP = $octet[0]*256*256*256 + $octet[1]*256*256 + $octet[2]*256 + $octet[3];
	if (isset($GLOBALS['TRACK']) && $GLOBALS['TRACK'] != '') $_SESSION['TRACK'] .= '<li class="db_f">function '."decimalIP($IPaddress)=$decimalIP".": ".basename(__FILE__).":".__LINE__."</li>\n";
	return $decimalIP;
}
// displayError($message)
// Display the $_SESSION['MESSAGE_ERROR'].
function displayError($message = '') {
	if ($message == '') { $message = $_SESSION['MESSAGE_ERROR']; }
	if ($message != '') {
	//if (substr($message,strlen($message)-4,4) != '<br>') { $message .= '<br>'; }
?>
		<div class="center"><span class="errorbold">ERROR!</span><br><span class="error"><?=$message?></span></div><embed src="<?=$_SESSION['HTTP_ROOT']?>/sounds/error1.wav" autostart="true" hidden="true"></embed>
<?
	}
	$_SESSION['MESSAGE_ERROR'] = '';
	if (isset($GLOBALS['TRACK']) && $GLOBALS['TRACK'] != '') $_SESSION['TRACK'] .= '<li class="db_f">function '."displayError($message)".": ".basename(__FILE__).":".__LINE__."</li>\n";
}

// displayInformation($message)
// Display the $_SESSION['MESSAGE_INFORMATION'].
function displayInformation($message = '') {
	if ($message == '') { $message = $_SESSION['MESSAGE_INFORMATION']; }
	if ($message != '') {
	//if (substr($message,strlen($message)-4,4) != '<br>') { $message .= '<br>'; }
?>
		<div class="center"><span class="bold" style="color:#FFFF00;"><?=$message?></span></div>
<?
	}
	$_SESSION['MESSAGE_INFORMATION'] = '';
	if (isset($GLOBALS['TRACK']) && $GLOBALS['TRACK'] != '') $_SESSION['TRACK'] .= '<li class="db_f">function '."displayInformation($message)".": ".basename(__FILE__).":".__LINE__."</li>\n";
}

// displayNotice($message)
// Display the $_SESSION['MESSAGE_NOTICE'].
function displayNotice($message = '') {
	if ($message == '') { $message = $_SESSION['MESSAGE_NOTICE']; }
	if ($message != '') {
	//if (substr($message,strlen($message)-4,4) != '<br>') { $message .= '<br>'; }
?>
		<div class="center"><span class="errorbold">NOTICE: </span><span class="bold"><?=$message?></span></div><embed src="<?=$_SESSION['HTTP_ROOT']?>/sounds/notice1.wav" autostart="true" hidden="true"></embed>
<?
	}
	$_SESSION['MESSAGE_NOTICE'] = '';
	if (isset($GLOBALS['TRACK']) && $GLOBALS['TRACK'] != '') $_SESSION['TRACK'] .= '<li class="db_f">function '."displayNotice($message)".": ".basename(__FILE__).":".__LINE__."</li>\n";
}

// displayWarning($message)
// Display the $_SESSION['MESSAGE_WARNING'].
function displayWarning($message = '') {
	if ($message == '') { $message = $_SESSION['MESSAGE_WARNING']; }
	if ($message != '') {
	//if (substr($message,strlen($message)-4,4) != '<br>') { $message .= '<br>'; }
?>
		<div class="center"><span class="warningbold">WARNING!</span><br><span class="warning"><?=$message?></span></div><embed src="<?=$_SESSION['HTTP_ROOT']?>/sounds/warning1.wav" autostart="true" hidden="true"></embed>
<?
	}
$_SESSION['MESSAGE_WARNING'] = '';
	if (isset($GLOBALS['TRACK']) && $GLOBALS['TRACK'] != '') $_SESSION['TRACK'] .= '<li class="db_f">function '."displayWarning($message)".": ".basename(__FILE__).":".__LINE__."</li>\n";
}

// doctype(__FILE__)
// Places the doctype into the HTML page.
function doctype($file) {
	if (!isset($_SESSION['OB_START']) || $_SESSION['OB_START'] == '') { ob_start(); $_SESSION['OB_START'] = 1; }
	if (!isset($_SESSION['DOCTYPE']) || $_SESSION['DOCTYPE'] == '') {
		//$_SESSION['DOCTYPE'] = '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">';
		//$_SESSION['HTML'] = '<html>';
		$_SESSION['DOCTYPE'] = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/ xhtml1-transitional.dtd">';
		$_SESSION['HTML'] = '<html xmlns="http://www.w3.org/1999/xhtml">';
		header("Cache-Control: no-cache, must-revalidate"); // HTTP/1.1
		header("Expires: Mon, 26 Jul 1997 05:00:00 GMT"); // Date in the past
		echo $_SESSION['DOCTYPE']."\n\n";
		//echo "DOCTYPE set. ".$file."<br>\n";
	} else {
		//echo "DOCTYPE already set. ".$file."<br>\n";
	}
	if (isset($GLOBALS['TRACK']) && $GLOBALS['TRACK'] != '') $_SESSION['TRACK'] .= '<li class="db_f">function '."doctype($file)".": ".basename(__FILE__).":".__LINE__."</li>\n";
}

// errorHandler($errno, $errstr, $errfile, $errline)
// General errorHandler.
function errorHandler($errno, $errstr, $errfile, $errline) {
	switch ($errno) {
		case E_COMPILE_ERROR:
			echo "<b>COMPILE_ERROR</b> #$errno in file:$errfile line:$errline. $errstr<br />\n";
			break;
		case E_COMPILE_WARNING:
			echo "<b>COMPILE_WARNING</b> #$errno in file:$errfile line:$errline. $errstr<br />\n";
			break;
		case E_CORE_ERROR:
			echo "<b>CORE_ERROR</b> #$errno in file:$errfile line:$errline. $errstr<br />\n";
			break;
		case E_CORE_WARNING:
			echo "<b>CORE_WARNING</b> #$errno in file:$errfile line:$errline. $errstr<br />\n";
			break;
		case E_ERROR:
			echo "<b>ERROR</b> #$errno in file:$errfile line:$errline. $errstr<br />\n";
			break;
		case E_NOTICE:
			echo "<b>NOTICE</b> #$errno in file:$errfile line:$errline. $errstr<br />\n";
			break;
		case E_PARSE:
			echo "<b>PARSE</b> #$errno in file:$errfile line:$errline. $errstr<br />\n";
			break;
		case E_USER_ERROR:
			echo "<b>USER_ERROR</b> #$errno in file:$errfile line:$errline. $errstr<br />\n";
			echo "  Fatal error in line $errline of file $errfile";
			echo ", PHP " . PHP_VERSION . " (" . PHP_OS . ")<br />\n";
			echo "Aborting...<br />\n";
			exit(1);
			break;
		case E_USER_NOTICE:
			echo "<b>USER_NOTICE</b> #$errno in file:$errfile line:$errline. $errstr<br />\n";
			break;
		case E_USER_WARNING:
			echo "<b>USER_WARNING</b> #$errno in file:$errfile line:$errline. $errstr<br />\n";
			break;
		case E_WARNING:
			echo "<b>WARNING</b> #$errno in file:$errfile line:$errline. $errstr<br />\n";
			break;
		default:
			echo "Unknown error type: #$errno in file:$errfile line:$errline. $errstr<br />\n";
			break;
	}
	if (isset($GLOBALS['TRACK']) && $GLOBALS['TRACK'] != '') $_SESSION['TRACK'] .= '<li class="db_f">function '."errorHandler($errno, $errstr, $errfile, $errline)".": ".basename(__FILE__).":".__LINE__."</li>\n";
}

// expandHeader($string)
// Return the string with _CSTRC_ and _CST_ expanded.
function expandHeader($string) {
	$expandHeader = str_replace("_CSTRC_",$_SESSION['NAME_LONG'],str_replace("_CST_",$_SESSION['NAME_SHORT'],$string));
	if (isset($GLOBALS['TRACK']) && $GLOBALS['TRACK'] != '') $_SESSION['TRACK'] .= '<li class="db_f">function '."expandHeader($string)=$expandHeader".": ".basename(__FILE__).":".__LINE__."</li>\n";
	return $expandHeader;
}

// formValue($formvariable,$prefix)
// Returns the $_GET or $_POST value if there is one, else returns 0.
function formValue($formvariable,$prefix = "f_") {
	if (isset($_GET[$prefix.$formvariable])) {
		if (get_magic_quotes_gpc() == true) {
			if (!is_array($_GET[$prefix.$formvariable])) {
				$formValue = trim($_GET[$prefix.$formvariable]);
			} else {
				$tempArray = array();
				foreach ($_GET[$prefix.$formvariable] as $temp) {
					$tempArray[] = trim($temp);
				}
				$formValue = $tempArray;
			}			
		} else {
			if (!is_array($_GET[$prefix.$formvariable])) {
				$formValue = $_GET[$prefix.$formvariable];
			} else {
				$tempArray = array();
				foreach ($_GET[$prefix.$formvariable] as $temp) {
					$tempArray[] = addslashes(trim($temp));
				}
				$formValue = $tempArray;
			}
		}
	} else {
		if (isset($_POST[$prefix.$formvariable])) {
			if (get_magic_quotes_gpc() == true) {
				if (!is_array($_POST[$prefix.$formvariable])) {
					$formValue = trim($_POST[$prefix.$formvariable]);
				} else {
					$tempArray = array();
					foreach ($_POST[$prefix.$formvariable] as $temp) {
						$tempArray[] = trim($temp);
					}
					$formValue = $tempArray;
				}			
			} else {
				if (!is_array($_POST[$prefix.$formvariable])) {
					$formValue = $_POST[$prefix.$formvariable];
				} else {
					$tempArray = array();
					foreach ($_POST[$prefix.$formvariable] as $temp) {
						$tempArray[] = addslashes(trim($temp));
					}
					$formValue = $tempArray;
				}
			}
		} else {
			$formValue = false;
		}
	}
	if (!is_array($formValue)) {
		if (isset($GLOBALS['TRACK']) && $GLOBALS['TRACK'] != '') $_SESSION['TRACK'] .= '<li class="db_f">function '."formValue($formvariable,$prefix)=$formValue".": ".basename(__FILE__).":".__LINE__."</li>\n";
	} else {
		if (isset($GLOBALS['TRACK']) && $GLOBALS['TRACK'] != '') { $_SESSION['TRACK'] .= '<li class="db_f">function '."formValue($formvariable,$prefix)=Array"; foreach($formValue as $key=>$value) { $_SESSION['TRACK'] .= " [$key]=$value"; } $_SESSION['TRACK'] .= ": ".basename(__FILE__).":".__LINE__."</li>\n"; }
	}
	return $formValue;
}

// get_holidays($inc_year)
// Looks through a lists of defined holidays and tells you which one is coming up next.
// $inc_year The year we are looking for holidays in
function get_holidays($inc_year) {
	//$year = date("Y");
	$year = $inc_year;
	$holidays[] = new Holiday("New Year's Day", get_timestamp("$year-1-1"));
	//$holidays[] = new Holiday("Australia Day", get_timestamp("$year-1-26"));
	//$holidays[] = new Holiday("Labour Day", ordinal_day(1, 'Mon', 3, $year));
	//$holidays[] = new Holiday("Anzac Day", get_timestamp("$year-4-25"));
	//$holidays[] = new Holiday("St. Patrick's Day", get_timestamp("$year-3-17"));
	//$holidays[] = new Holiday("Good Friday", easter_date($year)-86400*2);
	$holidays[] = new Holiday("Easter", easter_date($year));
	//$holidays[] = new Holiday("Easter Monday", easter_date($year)+86400);
	//$holidays[] = new Holiday("Foundation Day", ordinal_day(1, 'Mon', 6, $year));
	//$holidays[] = new Holiday("Queen's Birthday", ordinal_day(1, 'Mon', 10, $year));
	$holidays[] = new Holiday("Memorial Day", memorial_day($year));
	$holidays[] = new Holiday("Mother's Day", ordinal_day(2, 'Sun', 5, $year));
	$holidays[] = new Holiday("Father's Day", ordinal_day(3, 'Sun', 6, $year));
	$holidays[] = new Holiday("Independence Day", get_timestamp("$year-7-4"));
	$holidays[] = new Holiday("Labor Day", ordinal_day(1, 'Mon', 9, $year));
	$holidays[] = new Holiday("Veterans Day", get_timestamp("$year-11-11"));
	$holidays[] = new Holiday("Christmas", get_timestamp("$year-12-25"));
	//$holidays[] = new Holiday("Boxing Day", get_timestamp("$year-12-26"));
	$numHolidays = count($holidays) - 1;
	$holidayDatesOnly = array();
	for ($i = 0; $i < $numHolidays; $i++) {
			$holidayDatesOnly[] = $holidays[$i]->date;
	}
	unset($holidays);
	if (isset($GLOBALS['TRACK']) && $GLOBALS['TRACK'] != '') { $_SESSION['TRACK'] .= '<li class="db_f">function '."get_holidays($inc_year)=Array"; foreach($holidayDatesOnly as $key=>$value) { $_SESSION['TRACK'] .= " [$key]=$value"; } $_SESSION['TRACK'] .= ": ".basename(__FILE__).":".__LINE__."</li>\n"; }
	return $holidayDatesOnly;
}

// get_timestamp($MySqlDateTime)
// Takes a datetime in yyyy-mm-dd hh:mm:ss format and returns a PHP timestamp
// $MySqlDateTime = The date to convert in yyyy-mm-dd hh:mm:ss format.
// $atMidnight = 1 = a time of 00:00:00, 0 = time from MySqlDateTime (default).
function get_timestamp($MySqlDateTime,$atMidnight = 0) {
	// Split the date from the time.
	$dateTime = explode(" ",$MySqlDateTime);
	// Split the date into year, month, day.
	if (isset($dateTime[0])) { $datePart = explode("-",$dateTime[0]); } else { $datePart = ''; }
	for ($i=0; $i<3; $i++) {
		if (!isset($datePart[$i]) || $datePart[$i] == '') { $datePart[$i] = 0;; }
	}
	// Split the time int hour, minute, second.
	if (isset($dateTime[1]) && !$atMidnight) { $timePart = explode(":",$dateTime[1]); } else { $timePart = ''; }
	for ($i=0; $i<3; $i++) {
		if (!isset($timePart[$i]) || $timePart[$i] == '') { $timePart[$i] = 0;; }
	}
	#echo "\$MySqlDateTime=",$MySqlDateTime,": ",basename(__FILE__),": ",__LINE__,"<br>\n";
	#echo "\$datePart="; print_r($datePart); echo ": ",basename(__FILE__),": ",__LINE__,"<br>\n";
	#echo "\$timePart="; print_r($timePart); echo ": ",basename(__FILE__),": ",__LINE__,"<br>\n";
	// Create the timestamp mktime($hour, $minute, $second, $month, $day, $year).
	$var_timestamp = mktime($timePart[0],$timePart[1],$timePart[2],$datePart[1],$datePart[2],$datePart[0]);
	if (isset($GLOBALS['TRACK']) && $GLOBALS['TRACK'] != '') $_SESSION['TRACK'] .= '<li class="db_f">function '."get_timestamp($MySqlDateTime,$atMidnight)=$var_timestamp".": ".basename(__FILE__).":".__LINE__."</li>\n";
	return($var_timestamp);
}

// GradeCommentCodeReplace($courseNumber,$assignmentPoints,$gradePoints,$gradeComment)
// Returns the comment with any codes replaced by their calculated string values.
//     $courseNumber = the course number.
// $assignmentPoints = the total points the assignment is worth.
//      $gradePoints = the points given for the grade.
//     $gradeComment = the grade comment
function GradeCommentCodeReplace($assignmentName,$courseNumber,$assignmentPoints,$gradePoints,$gradeComment) {
	$gradeComment = stripslashes($gradeComment);
	$gradeComment = GradeCommentCodeReplace_e($assignmentName,$courseNumber,$assignmentPoints,$gradePoints,$gradeComment);
	$gradeComment = GradeCommentCodeReplace_p($assignmentName,$courseNumber,$gradeComment);
	$gradeComment = GradeCommentCodeReplace_e($assignmentName,$courseNumber,$assignmentPoints,$gradePoints,$gradeComment);
	if (isset($GLOBALS['TRACK']) && $GLOBALS['TRACK'] != '') $_SESSION['TRACK'] .= '<li class="db_f">function '."GradeCommentCodeReplace($assignmentName,$courseNumber,$assignmentPoints,$gradePoints,$gradeComment)=$gradeComment".": ".basename(__FILE__).":".__LINE__."</li>\n";
	return $gradeComment;
}
function GradeCommentCodeReplace_e($assignmentName,$courseNumber,$assignmentPoints,$gradePoints,$gradeComment) {
	$gradePercentage = $gradePoints / $assignmentPoints * 100;
	switch ($assignmentName) {
		case 'Class Profile':
			// =e: 'You may edit and re-submit your CST1025 Class Profile for a better grade. '
			$repStr = 'If you wish to improve your <b>'.gradeLetterAC($gradePercentage).'</b> grade please <a href="http://cst.ridgewater.edu/JimMartinson/'.$courseNumber.'/?ClassProfile">edit</a> and re-submit your '.$courseNumber.' Class Profile.';
			$gradeComment = str_replace("=e", $repStr, $gradeComment);
			break;
		case 'Student Profile':
			// =e: 'You may edit and re-submit your Student Profile for a better grade. '
			if ($courseNumber != '') {
				$repStr = 'If you wish to improve your <b>'.gradeLetterAC($gradePercentage).'</b> grade please <a href="http://cst.ridgewater.edu/JimMartinson/'.$courseNumber.'/?StudentProfile">edit</a> and re-submit your Student Profile.';
			} else {
				$repStr = 'If you wish to improve your <b>'.gradeLetterAC($gradePercentage).'</b> grade please edit and re-submit your Student Profile.';
			}
			$gradeComment = str_replace("=e", $repStr, $gradeComment);
			break;
		default:
			// =e: 'You may re-submit your CST1794 Lab-01 for a better grade. '
			$repStr = 'If you wish to improve your <b>'.gradeLetterAC($gradePercentage).'</b> grade please re-submit your '.$courseNumber.' '.$assignmentName.'.';
			$gradeComment = str_replace("=e", $repStr, $gradeComment);
		}
	return $gradeComment;
}
function GradeCommentCodeReplace_g($assignmentName,$courseNumber,$assignmentPoints,$gradePoints,$gradeComment) {
	$gradePercentage = $gradePoints / $assignmentPoints * 100;
	if ($assignmentName != 'Student Profile') {
		// =g: 'The grade for your CST1025 Class Profile is A, 26/27 points (96.3%). '
		$repStr = 'The grade for your '.$courseNumber.' '.$assignmentName.' is: <b>'.gradeLetterAC($gradePercentage).'</b>, '.$gradePoints.'/'.$assignmentPoints.' points ('.$gradePoints.'%).';
		$gradeComment = str_replace("=g", $repStr, $gradeComment);
	} else {
		// =g: 'The grade for your Student Profile is A, 96%. '
		if (listLen($courseNumber) > 1) { $classText = 'classes'; } else { $classText = 'class'; }
		$repStr = 'The grade for your '.$assignmentName.' is: <b>'.gradeLetterAC($gradePercentage).'</b>, '.$gradePercentage.'%. This grade impacts your '.listAnd($courseNumber).' '.$classText.'.';
		$gradeComment = str_replace("=g", $repStr, $gradeComment);
	}
	return $gradeComment;
}
function GradeCommentCodeReplace_p($assignmentName,$courseNumber,$gradeComment) {
	// =p: 'CST1025 Class Profile'
	if ($courseNumber != '') {
		$repStr = $courseNumber.' '.$assignmentName;
	} else {
		$repStr = $assignmentName;
	}
	$gradeComment = str_replace("=p", $repStr, $gradeComment);
	return $gradeComment;
}

// gradeLetter($percentage)
// Returns a grade letter based on the $percentage, $gradePoints, and $gradeLetters
function gradeLetter($percentage,$gradePoints,$gradeLetters) {
	$gradeLetter = $gradeLetters[count($gradePoints)-1];
	for ($i=count($gradePoints)-2; $i>=0; $i--) {
		if ($percentage >= $gradePoints[$i]) { $gradeLetter = $gradeLetters[$i]; }
	}
	return $gradeLetter;
}

// gradeLetterAF($percentage)
// Returns an A-F grade letter based on the $percentage.
// A:93%+, A-:90%+, B+:87%+, B:83%+, B-:80%+, C+:77%+, C:73%+, C-:70%+, D+:67%+, D:63%+, D-:60%+, F:<60%
function gradeLetterAF($percentage) {
	$gradeLetterAF = gradeLetter($percentage, 
		array(93,  90,   87,   83,  80,   77,   73,  70,   67,   63,  60,   0), 
		array('A', 'A-', 'B+', 'B', 'B-', 'C+', 'C', 'C-', 'D+', 'D', 'D-', 'F'));
	if (isset($GLOBALS['TRACK']) && $GLOBALS['TRACK'] != '') $_SESSION['TRACK'] .= '<li class="db_f">function '."gradeLetterF($percentage)=$gradeLetterAF".": ".basename(__FILE__).":".__LINE__."</li>\n";
	return $gradeLetterAF;
}

// gradeLetterAC($percentage)
// Returns an A-NC grade letter based on the $percentage.
// A:93%+, A-:90%+, B+:87%+, B:83%+, B-:80%+, C+:77%+, C:73%+, C-:70%+, NC:<70%
function gradeLetterAC($percentage) {
	$gradeLetterAC = gradeLetter($percentage, 
		array(93,  90,   87,   83,  80,   77,   73,  70,   0), 
		array('A', 'A-', 'B+', 'B', 'B-', 'C+', 'C', 'C-', 'NC'));
	if (isset($GLOBALS['TRACK']) && $GLOBALS['TRACK'] != '') $_SESSION['TRACK'] .= '<li class="db_f">function '."gradeLetterAC($percentage)=$gradeLetterAC".": ".basename(__FILE__).":".__LINE__."</li>\n";
	return $gradeLetterAC;
}

// Holiday:class
// Holds a holiday name and date.
class Holiday{
	//var $name;
	//var $date;
	public $name;
	public $date;
	// Contructor to define the details of each holiday as it is created.
	function holiday($name, $date) {
			$this->name   = $name;   // Official name of holiday
			$this->date   = $date;   // UNIX timestamp of date
	}
}

//htmlCRtoBR($string)
// Returns an htmlView($string) with all \n converted to <br />
function htmlCRtoBR($string) {
	$htmlCRtoBR = str_replace("\n", "<br />", htmlView($string));
	if (isset($GLOBALS['TRACK']) && $GLOBALS['TRACK'] != '') $_SESSION['TRACK'] .= '<li class="db_f">function '."htmlCRtoBR($string)=$htmlCRtoBR".": ".basename(__FILE__).":".__LINE__."</li>\n";
	return $htmlCRtoBR;
}

// htmlView($string)
// Returns $string with < = &lt; and & = &amp;.
function htmlView($string) {
	$safe = array("\\\"" => "&quot;", "\"" => "&quot;", '"' => "&quot;", "\\\'" => "&#39;", "\'" => "&#39;", "'" => "&#39;", "&" => "&amp;", "<" => "&lt;", ">" => "&gt;", "\\\\" => '&#92;',"\\" => '&#92;');
	$htmlView = strtr($string, $safe);
	if (isset($GLOBALS['TRACK']) && $GLOBALS['TRACK'] != '') $_SESSION['TRACK'] .= '<li class="db_f">function '."htmlView($string)=$htmlView".": ".basename(__FILE__).":".__LINE__."</li>\n";
	return $htmlView;
}

// is_positivenumber($value)
function is_positivenumber($value) {
if(ereg("^[0-9]+$", $value) && $value > 0){
  $is_positivenumber= true;
  } else {
  $is_positivenumber= false;
 }
 if (isset($GLOBALS['TRACK']) && $GLOBALS['TRACK'] != '') { $_SESSION['TRACK'] .= '<li class="db_f">function '."is_positivenumber($value)="; if($is_positivenumber) { $_SESSION['TRACK'] .='true'; } else { $_SESSION['TRACK'] .= 'false'; } $_SESSION['TRACK'] .=": ".basename(__FILE__).":".__LINE__."</li>\n"; }
	return $is_positivenumber;
}

// linkTest($thisLink)
function linkTest($thisLink) {
	if ($thisLink != '') {
		if (substr($thisLink,0,4) != 'http') {
			if (substr($thisLink,0,1) == '/') {
				$thisLink = "http://".$_SERVER['SERVER_NAME'].$thisLink;
			} else {
				$thisLink = "http://".$_SERVER['SERVER_NAME'].'/'.$thisLink;
			}
		}
		$current_error_reporting = ini_get("error_reporting");
		error_reporting(0);
		if (file_get_contents($thisLink,false,null) != '') {
			$linkTest  = '<a href="'.$thisLink.'" target="_blank"><span class="ok">OK</span></a>';
		} else {
			$linkTest = '<a href="'.$thisLink.'" target="_blank"><span class="error">Error</span></a>';
		}
		error_reporting($current_error_reporting);
	} else {
		$linkTest = '';
	}
	if (isset($GLOBALS['TRACK']) && $GLOBALS['TRACK'] != '') $_SESSION['TRACK'] .= '<li class="db_f">function '."linkTest($thisLink)=$linkTest".": ".basename(__FILE__).":".__LINE__."</li>\n";
	return $linkTest;
}

function linkTest2($link) {
	$url_parts = @parse_url($link);
	if (empty($url_parts["host"])) return(false);
	if (!empty($url_parts["path"])) {
		$documentpath = $url_parts["path"];
	} else {
		$documentpath = "/";
	}
	if (!empty($url_parts["query"])) {
		$documentpath .= "?" . $url_parts["query"];
	}
	$host = $url_parts["host"];
	$port = $url_parts["port"];
	// Now (HTTP-)GET $documentpath at $host";
	if (empty($port)) $port = "80"; $socket = @fsockopen($host, $port, $errno, $errstr, 30);
	if (!$socket) {
		$linkTest2 = false;
	} else {
		fwrite ($socket, "HEAD ".$documentpath." HTTP/1.0\r\nHost: $host\r\n\r\n");
		$http_response = fgets($socket, 22);
		if (ereg("200 OK", $http_response, $regs)) {
			$linkTest2 = true;
			fclose($socket);
		} else {
			//                echo "HTTP-Response: $http_response<br>";
			$linkTest2 = false;
		}
	}
	 if (isset($GLOBALS['TRACK']) && $GLOBALS['TRACK'] != '') { $_SESSION['TRACK'] .= '<li class="db_f">function '."linkTest2($link)="; if($linkTest2) { $_SESSION['TRACK'] .='true'; } else { $_SESSION['TRACK'] .= 'false'; } $_SESSION['TRACK'] .=": ".basename(__FILE__).":".__LINE__."</li>\n"; }
	return $linkTest2;
}

// listAnd($list,$separator)
// Returns the list with 'and' inserted.
//      $list = the list to modify.
// $separator = the list separator. Default is a comma ','.
// IE: $list='one' returns 'one'.
// IE: $list='one,two' returns 'one and two'.
// IE: $list='one,two,three' returns 'one, two, and three'.
function listAnd($list,$separator=',',$word='and') {
	$listArray = listToArray($list,$separator);
	$listLen = count($listArray);
	if ($listLen > 1) {
		$listReturn = '';
		$separator='';
		if ($listLen != 2) { $separatorNext = ', '; } else { $separatorNext = ' '; }
		for ($i = 0; $i < $listLen; $i++) {
			if ($i == $listLen-1) { $separator .= $word.' '; }
			$listReturn .= $separator.$listArray[$i];
			$separator = $separatorNext;
		}
		$listAnd = $listReturn;
	} else {
		$listAnd = $list;
	}
	if (isset($GLOBALS['TRACK']) && $GLOBALS['TRACK'] != '') $_SESSION['TRACK'] .= '<li class="db_f">function '."listAnd($list,$separator,$word)=$listAnd".": ".basename(__FILE__).":".__LINE__."</li>\n";
	return $listAnd;
}

// listAppend($list,$item,$separator)
// Returns the list with the $item appended to the end of the list.
//      $list = the list.
//      $item = the item to append to the list.
// $separator = the list separator. Default is a comma ','.
function listAppend($list,$item,$separator=',') {
	if ($list != '') {
		if ($item != '') $list .= $separator.$item;
	} else {
		if ($item != '') $list .= $item;
	}
	if (isset($GLOBALS['TRACK']) && $GLOBALS['TRACK'] != '') $_SESSION['TRACK'] .= '<li class="db_f">function '."listAppend($list,$item,$separator)=$list".": ".basename(__FILE__).":".__LINE__."</li>\n";
	return $list;
}

// listFind($list,$item,$separator)
// Searches the $list for the $item and returns the first position found. Returns false if not found.
//      $list = the list.
//      $item = the item to append to the list.
// $separator = the list separator. Default is a comma ','.
function listFind($list,$item,$separator=',') {
	$listArray = explode($separator,$list);
	$listFind = false;
	$listSearch = 0;
	foreach ($listArray as $key => $value) {
		$listSearch++;
		if (!$listFind && $value == $item) $listFind = $listSearch;
	}
	if (isset($GLOBALS['TRACK']) && $GLOBALS['TRACK'] != '') $_SESSION['TRACK'] .= '<li class="db_f">function '."listFind($list,$item,$separator)=$list".": ".basename(__FILE__).":".__LINE__."</li>\n";
	return $listFind;
}

// listLen($list,$separator)
// Returns the length of the list.
//      $list = the list to count.
// $separator = the list separator. Default is a comma ','.
function listLen($list,$separator=',') {
	$listArray = split($separator,$list);
	$listLen = count($listArray);
	if (isset($GLOBALS['TRACK']) && $GLOBALS['TRACK'] != '') $_SESSION['TRACK'] .= '<li class="db_f">function '."listLen($list,$separator)=$listLen".": ".basename(__FILE__).":".__LINE__."</li>\n";
	return $listLen;
}

// listOr($list,$separator)
// Returns the list with 'or' inserted.
//      $list = the list to modify.
// $separator = the list separator. Default is a comma ','.
// IE: $list='one' returns 'one'.
// IE: $list='one,two' returns 'one or two'.
// IE: $list='one,two,three' returns 'one, two, or three'.
function listOr($list,$separator=',') {
	$listOr = listAnd($list,$separator,'or');
	if (isset($GLOBALS['TRACK']) && $GLOBALS['TRACK'] != '') $_SESSION['TRACK'] .= '<li class="db_f">function '."listOr($list,$separator)=$listOr".": ".basename(__FILE__).":".__LINE__."</li>\n";
	return $listOr;
}

// listPrepend($list,$item,$separator)
// Returns the list with the $item prepended to the beginning of the list.
//      $list = the list.
//      $item = the item to prepend to the list.
// $separator = the list separator. Default is a comma ','.
function listPrepend($list,$item,$separator=',') {
	if ($list != '') {
		$list = $item.$separator.$list;
	} else {
		$list .= $item;
	}
	if (isset($GLOBALS['TRACK']) && $GLOBALS['TRACK'] != '') $_SESSION['TRACK'] .= '<li class="db_f">function '."listPrepend($list,$item,$separator)=$list".": ".basename(__FILE__).":".__LINE__."</li>\n";
	return $list;
}

// listToArray($list,$separator)
// Returns the list as an trimmed array.
//      $list = the list to split.
// $separator = the list separator. Default is a comma ','.
function listToArray($list,$separator=',') {
	$listToArray = split($separator,$list);
	for ($i = 0; $i < count($listToArray); $i++) {
		$listToArray[$i] = trim($listToArray[$i]);
	}
	if (isset($GLOBALS['TRACK']) && $GLOBALS['TRACK'] != '') { $_SESSION['TRACK'] .= '<li class="db_f">function '."listToArray($list,$separator)=Array"; foreach($listToArray as $key=>$value) { $_SESSION['TRACK'] .= " [$key]=$value"; } $_SESSION['TRACK'] .= ": ".basename(__FILE__).":".__LINE__."</li>\n"; }
	return $listToArray;
}

// memorial_day($inc_year)
// Returns the date of Memorial Day for a givven year.
// $inc_year = The year to calc Memorial Day for.
function memorial_day($inc_year) {
	for($date_stepper = intval(date("t", strtotime("$inc_year-05-01"))); $date_stepper >= 1; $date_stepper--) {
		if (date("l", strtotime("$inc_year-05-$date_stepper"))=="Monday") {
			$memorial_day = strtotime("$inc_year-05-$date_stepper");
			if (isset($GLOBALS['TRACK']) && $GLOBALS['TRACK'] != '') $_SESSION['TRACK'] .= '<li class="db_f">function '."memorial_day($inc_year)=$memorial_day".": ".basename(__FILE__).":".__LINE__."</li>\n";
	return $memorial_day;
			break;
		}
	}
}

// mk_dir($path,$rights)
// Will make a directory.
function mk_dir($path, $rights = 0777) {
	#echo "\$path=".$path."<br>\n";
	$mk_dir_flag = true;
	$folder_path = array(strstr($path, '.') ? dirname($path) : $path);
	#echo "\$folder_path=";
	#print_r($folder_path);
	#echo "<br>\n";	
	while(!@is_dir(dirname(end($folder_path))) && dirname(end($folder_path)) != '/' && dirname(end($folder_path)) != '.' && dirname(end($folder_path)) != '') {
		array_push($folder_path, dirname(end($folder_path)));
	#echo "\$folder_path=";
	#print_r($folder_path);
	#echo "<br>\n";	
	}
	while($parent_folder_path = array_pop($folder_path)) {
		#echo "\$parent_folder_path=".$parent_folder_path."<br>\n";
		if(!@mkdir($parent_folder_path, $rights)) $mk_dir_flag = false;
	}
	 if (isset($GLOBALS['TRACK']) && $GLOBALS['TRACK'] != '') { $_SESSION['TRACK'] .= '<li class="db_f">function '."mk_dir($path, $rights)="; if($mk_dir_flag) { $_SESSION['TRACK'] .='true'; } else { $_SESSION['TRACK'] .= 'false'; } $_SESSION['TRACK'] .=": ".basename(__FILE__).":".__LINE__."</li>\n"; }
	return $mk_dir_flag;
}

// nonEmptyList($list)
// Returns the list without any empty elements.
//      $list = the list to parse.
// $separator = the list separator. Default is a comma ','.
function nonEmptyList($list,$separator=',') {
	$listArray = split($separator,$list);
	$resultList = '';
	foreach ($listArray as $value) {
		if ($value != '') { $resultList .= ', '.$value; }
	}
	$resultList = substr($resultList,2);
	if (isset($GLOBALS['TRACK']) && $GLOBALS['TRACK'] != '') $_SESSION['TRACK'] .= '<li class="db_f">function '."nonEmptyList($list,$separator)=$resultList".": ".basename(__FILE__).":".__LINE__."</li>\n";
	return $resultList;
}

// ordinal_day($ord, $day, $month, $year)
// Returns the date of the $ord $day of the $month.
// I.E. ordinal_day(3, 'Sun', 5, 2001) returns the date of the 3rd Sunday of May (ie. Mother's Day).
// $ord = The week count.
// $day = The day of the week. Must be 3 char abbrev Mon, Tue, Wed, Thu, Fri, Sat, Sun.
// $month = The month of the yeat.
// $year = The year.
/* @return unknown */
function ordinal_day($ord, $day, $month, $year) {
	$firstOfMonth = get_timestamp("$year-$month-01");
	$lastOfMonth  = $firstOfMonth + date("t", $firstOfMonth) * 86400;
	$dayOccurs = 0;
	for ($i = $firstOfMonth; $i < $lastOfMonth ; $i += 86400) {
		if (date("D", $i) == $day) {
			$dayOccurs++;
			if ($dayOccurs == $ord) {
				$ordDay = $i;
			}
		}
	}
	if (isset($GLOBALS['TRACK']) && $GLOBALS['TRACK'] != '') $_SESSION['TRACK'] .= '<li class="db_f">function '."ordinal_day($ord, $day, $month, $year)=$ordDay".": ".basename(__FILE__).":".__LINE__."</li>\n";
	return $ordDay;
}

// printQuery($resultName,$result,$file,$line)
// Displays a SQL query in HTML table format with the calling file and line number.
// $resultName - The name of the query.
//     $result - The query.
// RETURNS:
// true if there is data in the result set.
// false if there is no data in the result.
function printQuery($resultName,$result) {
	$debug_backtrace = debug_backtrace();
	$file = basename($debug_backtrace['0']['file']);
	$line = $debug_backtrace['0']['line'];
	echo "<div class=\"left\"><span class = \"error\">",$resultName,"=</span> $file:$line<br />\n";
	//get the first row in the table:
	if(!mysql_num_rows($result)) {
		echo "null</div>\n";
		return false;
	}
	//set up the table:
	print("<table><tr>");
	//print the column names as table headers:
	mysql_data_seek($result, 0);
	$row = mysql_fetch_assoc($result);
	foreach($row as $key=>$value) {
		print("<th>$key</th>");
	}
	print("</tr>");
	//loop through the table, printing
	//the field values in table cells:
	mysql_data_seek($result, 0);
	while ($row = mysql_fetch_assoc($result)) {
		print("<tr>");
		foreach($row as $key=>$value) {
			print("<td>$value</td>");
		}
		print("</tr>");
	}
	//close out the table:
	print("</tr></table></div>");
	mysql_data_seek($result, 0);
	return true;
}

// printVar($varName,$var,$varDisplay,$varShow)
// Displays the value of a variable or array with the calling file and line number.
//    $varName = The name of the variable.
//        $var = The variable.
// $varDisplay = b = show br before output.
//               f = show calling file name and line.
//               n = =$var is not shown.
//               p = show passwords. Othwewise keys with 'password' or 'pw' in the key name are hidden.
//               i = show varName using class="info".
//               a = show varName using class="attention".
//               w = show varName using class="warning".
//               e = show varName using class="error".
//               'bfp' would show a br before output, show calling file name and line, and show passwords.
//               'bpe' would show a br before output, show varName using class="error", and show passwords.
//               default is f for non array variables and fe for arrays.
//    $varShow = true = display printVar
//               false = add printVar to $thisTRACK.
//               default is true.
function printVar($varName,$var,$varDisplay = 'f',$varShow = true) {
	$debug_backtrace = debug_backtrace(); $file = basename($debug_backtrace['0']['file']); $filepath = $debug_backtrace['0']['file']; $line = $debug_backtrace['0']['line']; global $TRACK;
	$bShow = (stripos($varDisplay,'b') !== false ? '<br />' : '');
	$cShow = (stripos($varDisplay,'i') !== false ? ' class="info"' : '');
	if ($cShow == '') $cShow = (stripos($varDisplay,'a') !== false ? ' class="attention"' : '');
	if ($cShow == '') $cShow = (stripos($varDisplay,'w') !== false ? ' class="warning"' : '');
	if ($cShow == '') $cShow = (stripos($varDisplay,'e') !== false ? ' class="error"' : '');
	if ($cShow == '') if (is_array($var)) $cShow = ' class="error"';
	$fShow = (stripos($varDisplay,'f') !== false ? " $file:$line" : '');
	$nShow = (stripos($varDisplay,'n') !== false ? false : true);
	$pShow = (stripos($varDisplay,'p') !== false ? true : false);
	$printVarArray_Debug = false;
	if ($printVarArray_Debug) {
		$l1 = ' <span class="attention">l1</span>'; $l2 = ' <span class="attention">l2</span>'; $l3 = ' <span class="attention">l3</span>'; $l4 = ' <span class="attention">l4</span>'; $l5 = ' <span class="attention">l5</span>';
	} else {
		$l1 = ''; $l2 = ''; $l3 = ''; $l4 = ''; $l5 = '';
	}
	$displayTrack = '<div class="left">'.$l1;
	if (isset($var)) {
		if (!is_array($var)) {
			if ($var === true) {
				$displayTrack .= "$bShow<span$cShow>$varName===</span>true$fShow\n".$l2;
			} else {
				if ($var === false) {
					$displayTrack .= "$bShow<span$cShow>$varName===</span>false$fShow\n".$l2;
				} else {
					if ($nShow) {
						$displayTrack .= "$bShow<span$cShow>$varName=</span>".htmlView($var)."$fShow\n".$l2;
					} else {
						$displayTrack .= "$bShow<span$cShow>$varName</span>"."$fShow\n".$l2;
					}
				}
			}
		} else {
			$displayTrack .= printVarArray($varName,$var,'',$bShow,$cShow,$fShow,$pShow,$printVarArray_Debug).$l3;
		}
	} else {
		$displayTrack .= "$bShow<span$cShow>$varName</span> is unset.$fShow\n".$l4;
	}
	$displayTrack .= "</div>\n".$l5;
	if ($varShow) {
		echo $displayTrack;
	} else {
		track($displayTrack);
	}
	unset($displayTrack);
	return $varShow;
}

// printVarArray($var,$keys,$bShow,$cShow,$fShow,$pShow);
// Called from printVar to print an array variable.
function printVarArray($varName,$var,$keys,$bShow,$cShow,$fShow,$pShow,$printVarArray_Debug) {
	$displayTrack = "$bShow<span$cShow>".$varName."=</span>$fShow<br />\n";
	$bShow = '';
	if ($printVarArray_Debug) {
		$l6 = ' <span class="attention">l6</span>'; $l7 = ' <span class="attention">l7</span>';
	} else {
		$l6 = '';  $l7 = ''; 
	}
	foreach ($var as $key => $value) {
		if (!is_array($value)) {
			if (!$pShow && (stristr($key,'password') || stristr($key,'pw'))) $value = '***hidden***';
			$displayTrack .= $varName."['".$key."']=".htmlView($value).$l6."<br />\n";
			$bShow = '';
		} else {
			$displayTrack .= "".printVarArray($varName."['".$key."']",$value,$keys."['".$key."']",$bShow,$cShow,$fShow,$pShow,$printVarArray_Debug).$l7."";
			$bShow = '';
		}
	}
	return $displayTrack;
}

/********************************************
* printTable outputs any SQL table in an    *
* HTML tabular format.                      *
* ARGUMENTS:                                *
* $result :	the return value of a call  *
*		to mysql_query()            *
* RETURNS:                                  *
* true if there is data in the result set   *
* false if there is no data in the result   *
* set					    *
********************************************/
function printTable($result) {
	//get the first row in the table:
	if(!$row = mysql_fetch_assoc($result)) {
		return false;
	}
	//set up the table:
	print("<table><tr>");
	//print the column names as table headers:
	foreach($row as $key=>$value) {
		print("<th>$key</th>");
	}
	print("</tr>");
	//loop through the table, printing
	//the field values in table cells:
	do {
		print("<tr>");
		foreach($row as $key=>$value) {
			print("<td>$value</td>");
		}
		print("</tr>");
	}
	while ($row = mysql_fetch_assoc($result));
	//close out the table:
	print("</tr></table>");
	if (isset($GLOBALS['TRACK']) && $GLOBALS['TRACK'] != '') $_SESSION['TRACK'] .= '<li class="db_f">function '."printTable($result)".": ".basename(__FILE__).":".__LINE__."</li>\n";
	return true;
}

// query_do($query)
// Perform the requested $query.
function query_do($query = 'use_global',$xfile = '',$xline = '') {
	if ($query == 'use_global') global $query;
	$_SESSION['query'] = $query;
	$debug_backtrace = debug_backtrace();
	$file = $debug_backtrace['0']['file'];
	$_SESSION['file'] = $file;
	$line = $debug_backtrace['0']['line'];
	$_SESSION['line'] = $line;
	if ($_SESSION['DEBUG_MYSQL']) { 
		echo basename($file).":".$line.": ".$query."<br>\n";
	}
	if (isset($GLOBALS['TRACK']) && $GLOBALS['TRACK'] != '') $_SESSION['TRACK'] .= '<li class="db_q">'.$query;
 	$result = mysql_query($query, mysql_pconnect($_SESSION['DB_HN'], $_SESSION['DB_UN'], $_SESSION['DB_PW']));
	if ($result) {
		if (!ereg("^[0-9]+$", $result) && $result > 0) { // Test if result is a positive number.
			$_SESSION['mysql_num_rows'] = mysql_num_rows($result);
		} else {
			$_SESSION['mysql_num_rows'] = $result;
		}
	} else {
		$_SESSION['mysql_num_rows'] = false;
		query_error();
	}
	if (isset($GLOBALS['TRACK']) && $GLOBALS['TRACK'] != '') $_SESSION['TRACK'] .= '<span class="db_qc">: count='.$_SESSION['mysql_num_rows']."</span>: ".basename($file).":".$line."</li>\n";
	return $result;
}

// query_error()
// Report a program query error.
function query_error() {
?>
	<span class="error bold">There is a programming error.</span><br>
	<span class="error">The following query caused an error:</span>
	<pre><?=
	$_SESSION['query']?></pre>
	<span class="error">File: <?=basename($_SESSION['file'])?>, line: <?=$_SESSION['line']?>.</span> <?=$_SESSION['file']?><br>
	Please notify the website administrator <a href="mailto:<?=$_SESSION['websiteAdministratorEmail']?>"><?=$_SESSION['websiteAdministratorName']?></a> at <?=$_SESSION['websiteAdministratorEmail']?>.<br>
	<span class="error bold">Error:</span> <?=mysql_errno()?>-<?=mysql_error()?><br>
<?
	if (isset($GLOBALS['TRACK']) && $GLOBALS['TRACK'] != '') $_SESSION['TRACK'] .= '<li class="db_f">function '."query_error()".": ".basename(__FILE__).":".__LINE__."</li>\n";
}

// query_to_list($result,$field='')
// Returns a comma seperated list from a query result.
// $result = The query result to use to build the list. 
function query_to_list($result,$field = '') {
  $resultList = '';
	#echo "\$result=",$result,": ",basename(__FILE__),": ",__LINE__,"<br>\n";
	#echo "mysql_num_rows($result)=",mysql_num_rows($result),": ",basename(__FILE__),": ",__LINE__,"<br>\n";
	if (mysql_num_rows($result)) {
		mysql_data_seek($result, 0);
		if ($field == '') {
			while ($row = mysql_fetch_assoc($result)) {
				#echo "\$row="; print_r($row); echo ": ",basename(__FILE__),": ",__LINE__,"<br>\n";
				foreach ($row as $value) {
					if ($value != '') $resultList .= ', '.$value;
				}
			}
		} else {
			while ($row = mysql_fetch_assoc($result)) {
				if ($row[$field] != '') $resultList .= ', '.$row[$field];
			}
		}
	}
	$resultList = substr($resultList,2);
	#echo "\$resultList=",$resultList,": ",basename(__FILE__),": ",__LINE__,"<br>\n";
	if (isset($GLOBALS['TRACK']) && $GLOBALS['TRACK'] != '') $_SESSION['TRACK'] .= '<li class="db_f">function '."query_to_list($result)=$resultList".": ".basename(__FILE__).":".__LINE__."</li>\n";
	return $resultList;
}

// twoDigit($number)
// Returns two+ digit number.
function twoDigit($number) {
	if (strlen($number) > 1) {
		$twoDigit = $number;
	} else {
		if (strlen($number) == 1) {
			$twoDigit = '0'.$number;
		} else {
			$twoDigit = '00';
		}
	}
	if (isset($GLOBALS['TRACK']) && $GLOBALS['TRACK'] != '') $_SESSION['TRACK'] .= '<li class="db_f">function '."twoDigit($number)=$twoDigit".": ".basename(__FILE__).":".__LINE__."</li>\n";
	return $twoDigit;
}

// time_difference($start, $end)
/**
 * Function to calculate date or time difference.
 * 
 * Function to calculate date or time difference. Returns an array or
 * false on error.
 *
 * @author       J de Silva                             <giddomains@gmail.com>
 * @copyright    Copyright &copy; 2005, J de Silva
 * @link         http://www.gidnetwork.com/b-16.html    Get the date / time difference with PHP
 * @param        string                                 $start
 * @param        string                                 $end
 * @return       array
 */
function time_difference($start, $end) {
	$uts['start'] = strtotime($start);
	$uts['end']   = strtotime($end);
	if ($uts['start']!==-1 && $uts['end']!==-1) {
		if ($uts['end'] >= $uts['start']) {
			$diff    =    $uts['end'] - $uts['start'];
			if ($days=intval((floor($diff/86400)))) $diff = $diff % 86400;
			if ($hours=intval((floor($diff/3600)))) $diff = $diff % 3600;
			if ($minutes=intval((floor($diff/60)))) $diff = $diff % 60;
			$diff    =    intval($diff);            
			$time_difference = array('days'=>$days, 'hours'=>$hours, 'minutes'=>$minutes, 'seconds'=>$diff);
		} else {
			trigger_error("Ending date/time is earlier than the start date/time", E_USER_WARNING);
			$time_difference = false;
		}
	} else {
		trigger_error("Invalid date/time data detected", E_USER_WARNING);
		$time_difference = false;
	}
	if (isset($GLOBALS['TRACK']) && $GLOBALS['TRACK'] != '') { $_SESSION['TRACK'] .= '<li class="db_f">function '."time_difference($start, $end)=Array"; foreach($time_difference as $key=>$value) { $_SESSION['TRACK'] .= " [$key]=$value"; } $_SESSION['TRACK'] .= ": ".basename(__FILE__).":".__LINE__."</li>\n"; }
	return $time_difference;
}

// userEmail($userId)
// Return the user's email address from the userId.
function userEmail($userId) {
$query=sprintf("SELECT userEmail FROM user WHERE userId='%s'", get_magic_quotes_gpc() ? $userId : addslashes($userId));
	$userResult = query_do($query);
	if (mysql_num_rows($userResult)) {
		$userRow = mysql_fetch_assoc($userResult);
		$userEmail = $userRow['userEmail'];
	}	else {
		$userEmail = "";
	}
	if (isset($GLOBALS['TRACK']) && $GLOBALS['TRACK'] != '') $_SESSION['TRACK'] .= '<li class="db_f">function '."userEmail($userId)=$userEmail".": ".basename(__FILE__).":".__LINE__."</li>\n";
	return $userEmail;
}

// username($userId)
// Return the user's name from the userId.
function username($userId) {
	$query=sprintf("SELECT userFirstName, userNickname, userLastName FROM user WHERE userId='%s'", get_magic_quotes_gpc() ? $userId : addslashes($userId));
	$userResult = query_do($query);
	if (mysql_num_rows($userResult)) {
		$userRow = mysql_fetch_assoc($userResult);
		if ($userRow['userNickname'] == "") {
			$userFullName = $userRow['userFirstName'] . " " . $userRow['userLastName'];
		} else {
			$userFullName = $userRow['userNickname'] . " " . $userRow['userLastName'];
		}
	}	else {
		if ($userId !== 0) {
			$userFullName = "N/A";
		} else {
			$userFullName = "default";
		}
	}
	if (isset($GLOBALS['TRACK']) && $GLOBALS['TRACK'] != '') $_SESSION['TRACK'] .= '<li class="db_f">function '."username($userId)=[$userFullName]".'</li>'."\n";
	return $userFullName;
}

// userNickName($userId)
// Return the user's nickname or first name from the userId.
function userNickName($userId) {
$query=sprintf("SELECT userFirstName, userNickname FROM user WHERE userId='%s'", get_magic_quotes_gpc() ? $userId : addslashes($userId));
	$userResult = query_do($query);
	if (mysql_num_rows($userResult)) {
		$userRow = mysql_fetch_assoc($userResult);
		if ($userRow['userNickname'] == "") {
			$f_userNickName = $userRow['userFirstName'];
		} else {
			$f_userNickName = $userRow['userNickname'];
		}
	}	else {
		if ($userId !== 0) {
			$f_userNickName = "N/A";
		} else {
			$f_userNickName = "default";
		}
	}
	if (isset($GLOBALS['TRACK']) && $GLOBALS['TRACK'] != '') $_SESSION['TRACK'] .= '<li class="db_f">function '."userNickName($userId)=$f_userNickName".": ".basename(__FILE__).":".__LINE__."</li>\n";
	return $f_userNickName;
}

// uuid()
// Generate a uuid for form control (used to prevent reload).
function uuid() {
	$uuid = md5(getmypid().uniqid(rand()).$_SERVER['SERVER_NAME']);
	if (isset($GLOBALS['TRACK']) && $GLOBALS['TRACK'] != '') $_SESSION['TRACK'] .= '<li class="db_f">function '."uuid()=$uuid".": ".basename(__FILE__).":".__LINE__."</li>\n";
	return $uuid;
} 

// quot()
// Change quote (") marks to &quot;.
function quot($string) {
	$quot = str_replace('"', '&quot;', str_replace('\"', '&quot;', $string));
	if (isset($GLOBALS['TRACK']) && $GLOBALS['TRACK'] != '') $_SESSION['TRACK'] .= '<li class="db_f">function '."quot($string)=$quot".": ".basename(__FILE__).":".__LINE__."</li>\n";
	return $quot;
} 

if (isset($GLOBALS['TRACK']) && $GLOBALS['TRACK'] != '') $_SESSION['TRACK'] .= "<li>End ".basename(__FILE__)."</ol>\n";
?>

Anon7 - 2022
AnonSec Team