Location: PHPKode > projects > Silicon Fodder > SiliconFodder/DocumentRoot/diary/util.php
<?
$useCache = true;

$eventtypestoavoidindiary = "(991,996,997)";
if(getApplicationObject("diaryshowtasks") == "yes") $eventtypestoavoidindiary = "(991)";

$arrMonths = array("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December");
$arrMonthsShort = array("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec");
$arrDays   = array(31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);
$arrDayNames = array("Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday");

// notification times (Strings) and hours
$arrNotificationStrs  = array("1 hour", "4 hours", "12 hours", "1 day", "2 days", "1 week");
$arrNotificationTimes = array(1, 4, 12, 24, 48, 168);

// recurring times
$arrRecurringStrs = array("Daily","Weekly","Monthly","Quarterly","Annually");
$arrRecurringInts = array(3,1,2,5,4);

// Colours for events - 0 = default, 1 = holiday, 2 = client meeting, 3 = internal meeting, 4 = training, 5 = client visit, 6 = Billing, 7 = Doctor/Dentist
// $eventColours = array("#FFFFD5", "#FFDDC5", "#C3DAF9", "#CCAAAB", "yellow", "#B6D7B9", "#66FF99", "#FFDDC5");
$eventColours = array();
$mySQL = "SELECT * FROM diaryeventtypes WHERE eventId>0";
$rows = gendb_query($mySQL, $myDb) or die(gendb_error());
while($row = gendb_fetch_assoc($rows)) {
	$eventColours[$row["eventId"]] = "#".$row["colour"];
	if($row["eventName"] == "Holiday") {
		$holidayid = $row["eventId"];
		$holidaycolour = $row["colour"];
	}
}
// color for invoices and timesheets from project module
$eventColours[994] = "#AAFFAA"; // recurring invoicing
$eventColours[991] = "#BBBBFF"; // timesheet
$eventColours[989] = "#FFBBBB"; // prototype due
$eventColours[988] = "#FFAAAA"; // final project due
// color for not-yet-authorised holiday
$eventColours[993] = $holidaycolour;

// How many days in a month?
function getDaysInMonth($inpMonth, $inpYear) {
	global $arrDays;
	if($inpMonth != 1) {
		return $arrDays[$inpMonth];
	} elseif($inpYear % 4 == 0) {
		return 29;
	} else {
		return 28;
	}
}

function getWeekNumber($currentDate) {
	return date("W", $currentDate);
}

// Gets the info for the days in bold on the RH side - getting the cache if it exists
function getBusyDays($inpMonth, $inpYear, $inpViewFor) {
	global $myDb, $useCache, $HTTP_SESSION_VARS, $myCompId;

	if($useCache) {
		if($inpViewFor == "all") {
			$cacheKey = "diary,".$inpMonth.",".$inpYear.",all";
		} elseif($inpViewFor == "me") {
			$cacheKey = "diary,".$inpMonth.",".$inpYear.",".$HTTP_SESSION_VARS["mwoid"];
		} elseif(substr($inpViewFor, 0, 2) == "p2") {
			$cacheKey = "diary,".$inpMonth.",".$inpYear.",".substr($inpViewFor, 2);
		} else {
			$cacheKey = "diary,".$inpMonth.",".$inpYear.",d".$inpViewFor;
		}

		$mySQL = "SELECT busyDays FROM diarycachebusy WHERE cacheKey='".$cacheKey."' AND companyId=".$myCompId;
		$rows = gendb_query($mySQL, $myDb) or die(gendb_error());
		$row = gendb_fetch_assoc($rows);
		if($row === false) {
			$getBusyDays = getBusyDaysFromDb($inpMonth, $inpYear, $inpViewFor);
			gendb_query("INSERT INTO diarycachebusy (cacheKey, busyDays, companyId) VALUES ('".$cacheKey."','".$getBusyDays."',".$myCompId.")", $myDb) or die(gendb_error());
		} else {
			$getBusyDays = $row["busyDays"];
		}
		gendb_free_result($rows);
	} else {
		echo("No-cache warning!");
		clearAllBusyDaysCache();
		$getBusyDays = getBusyDaysFromDb($inpMonth, $inpYear, $inpViewFor);
	}
	
	return $getBusyDays;

}

function clearAllBusyDaysCache() {
	global $myDb, $myCompId;
	gendb_query("DELETE FROM diarycachebusy WHERE companyId=".$myCompId, $myDb) or die(gendb_error());
}

function clearBusyDaysCacheForUser($userId) {
	global $myDb, $myCompId;
	if($userId == 0) {
		clearAllBusyDaysCache();
	} else {
		// delete for that individual user
		gendb_query("DELETE FROM diarycachebusy WHERE cacheKey LIKE '%,".$userId."' AND companyId=".$myCompId, $myDb) or die(gendb_error());

		// delete for their department
		$mySQL = "SELECT department FROM users where id=".$userId;
		$rows = gendb_query($mySQL, $myDb) or die(gendb_error());
		$row = gendb_fetch_assoc($rows);
		$department = $row["department"];
		gendb_free_result($rows);
		if($department != "") {
			$mySQL = "DELETE FROM diarycachebusy WHERE cacheKey LIKE '%,d".$department."%' AND companyId=".$myCompId;
			gendb_query($mySQL, $myDb) or die(gendb_error());
		}
		
		// delete for the 'all users' key
		gendb_query("DELETE FROM diarycachebusy WHERE cacheKey LIKE '%,all' AND companyId=".$myCompId, $myDb) or die(gendb_error());
	}
}

function clearBusyDaysCacheFromDiaryId($diaryId) {
	global $myDb, $myCompId;

	// delete for the user
	$mySQL = "SELECT userid FROM diary WHERE id=".$diaryId;
	$rows = gendb_query($mySQL, $myDb) or die(gendb_error());
	$row = gendb_fetch_assoc($rows);
	$userid = $row["userid"];
	gendb_free_result($rows);
	if($userid != "" && $userid != 0) {
		$mySQL = "DELETE FROM diarycachebusy WHERE cacheKey LIKE '%,".$userid."' AND companyId=".$myCompId;
	} else {
		$mySQL = "DELETE FROM diarycachebusy WHERE companyId=".$myCompId;
	}
	gendb_query($mySQL, $myDb) or die(gendb_error());
	
	// delete for the department
	if($userid != "") {
		$mySQL = "SELECT department FROM users where id=".$userid;
		$rows = gendb_query($mySQL, $myDb) or die(gendb_error());
		$row = gendb_fetch_assoc($rows);
		$department = $row["department"];
		gendb_free_result($rows);
		if($department != "") {
			$mySQL = "DELETE FROM diarycachebusy WHERE cacheKey LIKE '%,d".$department."%' AND companyId=".$myCompId;
			gendb_query($mySQL, $myDb) or die(gendb_error());
		}
	}

	// delete for the 'all users' key
	gendb_query("DELETE FROM diarycachebusy WHERE cacheKey LIKE '%,all' AND companyId=".$myCompId, $myDb) or die(gendb_error());
}

// note - not including tasks or timesheets when getting this data for the bold numbers in the diary
function getBusyDaysFromDb($month, $year, $viewFor) {
	global $myDb, $arrMonths, $HTTP_SESSION_VARS, $myCompId;
	global $eventtypestoavoidindiary;

	$arrReturn = array(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);

	$dbDate = $year."-".($month+ 1)."-01";

	// look at non-recurring events

	$mySQL = "SELECT starttime, endtime, users.isDeleted AS userIsDeleted FROM diary LEFT JOIN users ON diary.userid=users.id WHERE diary.companyId=".$myCompId." AND diary.isDeleted=0 AND eventType NOT IN ".$eventtypestoavoidindiary." AND recurring=-1 AND (starttime < DATE_ADD('".$dbDate."', INTERVAL 1 MONTH) AND endtime > '".$dbDate."')";
	if($viewFor == "me") {
		$mySQL.= " AND (userid=0 OR userid=".$HTTP_SESSION_VARS["mwoid"].")";
	} elseif(substr($viewFor, 0, 2) == "p2") {
		$mySQL.= " AND (userid=0 OR userid=".substr($viewFor, 2).")";
	} elseif($viewFor != "all") {
		$mySQL.=" AND (userid=0 OR department=".$viewFor.")";
	}
	$rows = gendb_query($mySQL, $myDb) or die(gendb_error());
	while ($row = gendb_fetch_assoc($rows)) {
		$userIsDeleted = $row["userIsDeleted"];
		if($userIsDeleted == 1) continue;
		$mystarttime  = strtotime(substr($row["starttime"],0,10));
		$myendtime    = strtotime(substr($row["endtime"],0,10));
		$mycurrentDay = strtotime($dbDate);
		for($j = 1; $j <= getDaysInMonth($month, $year); $j++) {
			//echo ($mystarttime).",".($mycurrentDay).",".($myendtime)."<br>";
			if($mystarttime<=$mycurrentDay && $myendtime>=$mycurrentDay) {
				$arrReturn[$j] = 1;
			}
			$mycurrentDay += (60*60*24);
		}

	}
	gendb_free_result($rows);

	// recurring events now!
	$mySQL = "SELECT starttime, recurring, users.isDeleted AS userIsDeleted FROM diary LEFT JOIN users ON diary.userid=users.id WHERE diary.companyId=".$myCompId." AND diary.isDeleted=0 AND eventType NOT IN ".$eventtypestoavoidindiary." AND recurring!=-1 AND starttime < DATE_ADD('".$dbDate."', INTERVAL 1 MONTH)";
	if($viewFor == "me") {
		$mySQL.= " AND (userid=0 OR userid=".$HTTP_SESSION_VARS["mwoid"].")";
	} elseif(substr($viewFor, 0, 2) == "p2") {
		$mySQL.= " AND (userid=0 OR userid=".substr($viewFor, 2).")";
	} elseif($viewFor != "all") {
		$mySQL.= " AND (userid=0 OR department=".$viewFor.")";
	}

	$rows = gendb_query($mySQL, $myDb) or die(gendb_error());
	while ($row = gendb_fetch_assoc($rows)) {
		$userIsDeleted = $row["userIsDeleted"];
		if($userIsDeleted == 1) continue;
		$mystarttime = strtotime($row["starttime"]);
		$recurring   = $row["recurring"];

		if($recurring == 2) { //monthly
			if(date("j", $mystarttime) > getDaysInMonth($month, $year)) {
				// recurring event is, e.g. 31st March - so we want to highlight 30th May
				$arrReturn[getDaysInMonth($month, $year)] = 1;
			} else {
				$arrReturn[date("j", $mystarttime)] = 1;
			}
		} elseif($recurring == 3) { // daily
			if(date("Y", $mystarttime) < $year || date("n", $mystarttime) <= $month) {
				gendb_free_result($rows);
				return ",1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,";
			} else {
				for($j = date("j", $mystarttime); $j <= getDaysInMonth($month, $year); $j++) {
					$arrReturn[$j] = 1;
				}
			}
		} elseif ($recurring == 4) { // annually
			if(date("n", $mystarttime) == $month + 1) {
				$arrReturn[date("j", $mystarttime)] = 1;
			}
		} elseif ($recurring == 5) { // quarterly
			if(date("n", $mystarttime) % 3 == ($month+1) % 3) {
				if(date("d", $mystarttime) > getDaysInMonth($month, $year)) {
					// recurring event is, e.g. 31st March - so we want to highlight 30th May
					$arrReturn[getDaysInMonth($month, $year)] = 1;
				} else {
					$arrReturn[date("j", $mystarttime)] = 1;
				}
			}
		} elseif ($recurring == 1) { // weekly
			$mycurrentDay = strtotime($dbDate);
			for($j = 1; $j <= getDaysInMonth($month, $year); $j++) {
				if(date("w", $mycurrentDay) == date("w", $mystarttime) && ($mycurrentDay-$mystarttime > (-60*60*24))) {
					$arrReturn[$j] = 1;
				}
				$mycurrentDay += (60*60*24);
			}
		}

	}

	gendb_free_result($rows);
	$getBusyDaysFromDb = ",";
	for ($j = 1; $j <= getDaysInMonth($month, $year); $j++) {
		if($arrReturn[$j] == 1) $getBusyDaysFromDb.= $j.",";
	}

	return $getBusyDaysFromDb;
}

// get next notification date
function getNextNotificationDate($diaryStartTime, $notTime, $recurring) {

	if($notTime == -1) {
		return "null";
	} else {
		$getNextNotificationDate = strtotime($diaryStartTime);
	}

	if($recurring != -1) {
		$dayForDiaryStart = date("d", $getNextNotificationDate);

		while(DateAdd("h", $notTime, time()) > $getNextNotificationDate) {
			if($recurring == 1) { // weekly
				$getNextNotificationDate = DateAdd("d", 7, $getNextNotificationDate);
			} elseif($recurring == 2) { // monthly
				$getNextNotificationDate = DateAdd("m", 1, $getNextNotificationDate);
			} elseif($recurring == 3) { // daily
				$getNextNotificationDate = DateAdd("d", 1, $getNextNotificationDate);
			} elseif($recurring == 4) { // annually
				$getNextNotificationDate = DateAdd("Y", 1, $getNextNotificationDate);
			} elseif($recurring == 5) { // quarterly
				$getNextNotificationDate = DateAdd("m", 3, $getNextNotificationDate);
			} else {
				echo("diary/util.php - unknown value for 'recurring' - fatal error");
				exit;
			}
		}

		// when adding 2 months to 31st Jan, need to make sure we get out 31st March - not 28th March!
		if($recurring == 2 || $recurring == 5) {
			$getNextNotificationDate = getDayPushedInRightPlace($getNextNotificationDate, $dayForDiaryStart);
		}
	}

	return "'".dateForDb(DateAdd("h", -$notTime, $getNextNotificationDate), 0)."'";

}

// adds daysToAdd days to the PHP timstamp object myDate, then returns a mySQL-friendly date
// String, e.g. "2004-12-02 10:30:30"
function dateForDb($myDate, $daysToAdd = 0) {
	global $arrMonths;
	
	$newDate = DateAdd("d", $daysToAdd, $myDate);
	return date("Y-m-d H:i:00", $newDate);
	//return date("Y", $newDate)."-".date("m", $newDate)."-".date("d", $newDate)." ".date("H", $newDate).":".date("i", $newDate).":00";
}

// will turn ("29 March 2004", 31) into "31 March 2004"
function getDayPushedInRightPlace($myDate, $targetDay) {
	$getDayPushedInRightPlace = $myDate;
	if(date("d", $getDayPushedInRightPlace) != $targetDay) {
	// might need to mangle the numbers - add a day until we're at the original number, or at the end of the month
		while((date("d", $getDayPushedInRightPlace) != $targetDay) && (date("d", $getDayPushedInRightPlace) < getDaysInMonth(date("m", $getDayPushedInRightPlace) - 1, date("Y", $getDayPushedInRightPlace)))) {
			$getDayPushedInRightPlace = DateAdd("d", 1, $getDayPushedInRightPlace);
		}
	}
	
	return $getDayPushedInRightPlace;
}

function DateAdd($interval, $number, $myTimeStamp) {
	global $arrMonths;
	
	if($interval == "d") {	// days
		return $myTimeStamp + ($number * 60 * 60 * 24);
	}
	if($interval == "h") {  // hours
		return $myTimeStamp + ($number * 60 * 60);
	}
	if($interval == "Y") {  // years
		$myDate = getdate($myTimeStamp);
		$myDate["year"] += $number;
		return strtotime($myDate["mday"]." ".$myDate["month"]." ".$myDate["year"]." ".$myDate["hours"].":".$myDate["minutes"].":".$myDate["seconds"]);
	}
	if($interval == "m") {  // months
		$myDate = getdate($myTimeStamp);
		$myYear = $myDate["year"];
		$myMonth = $myDate["mon"];
		while($number > 0) {
			$myMonth++;
			if($myMonth == 13) {
				$myMonth = 1;
				$myYear++;
			}
			$number--;
		}
		return strtotime($myDate["mday"]." ".$arrMonths[$myMonth - 1]." ".$myYear." ".$myDate["hours"].":".$myDate["minutes"].":".$myDate["seconds"]);
	}
	echo "Unsupported interval $interval in DateAdd - exiting!!!";
	exit;
}

function DateDiff($interval, $date1, $date2) {
	if($interval == "d") {
		$date1 = date("Y-m-d", $date1);
		$date2 = date("Y-m-d", $date2);
		return ceil((strtotime($date2) - strtotime($date1)) / (60*60*24));
	}
	echo "Unsupported interval $interval in DateDiff - exiting!!!";
	exit;
}

// ****************************************
// functions used in diary.php / pdaDay.php
// ****************************************
function addDayFromRecurring() {
	global $eventtype, $viewFor, $diaryType, $daysToView, $diaryContent, $starttime, $endtime, $diaryevent, $diaryId, $personName, $notTime, $i, $currentDay, $userId, $smartdb, $dayToLookAt, $userids;

	if($eventtype==1 && $viewFor=="me" && $userId != 0) $diaryType[$i] = "Hol";
	if($daysToView == 1 || isPda()) {
		$diaryContent[$i] = $diaryContent[$i].getEventForDisplay($starttime, $endtime, $diaryevent, $diaryId, $personName, -1, $eventtype, false, true, $notTime);
		addTimeToDictionary($starttime, true, $notTime, 0, $i);
		updateBusyIntervals($diaryId, $starttime, $endtime, $eventtype, $dayToLookAt);
	} else {
		$diaryContent[$i] = $diaryContent[$i].getEventForDisplay($starttime, $endtime, $diaryevent, $diaryId, $personName, -1, $eventtype, true, true, $notTime);
	}
}

// displays contents of diary - puts a newline at the end for spacing, unless we're on 15-min diary type
function showHourContent($myTime, $key) {
	global $diaryMinutes;

	if($myTime == "span") {
		return $diaryMinutes[$key]["span"];
	} elseif($diaryMinutes[$key][showTime($myTime)] != "") {
		return $diaryMinutes[$key][showTime($myTime)];
	} else {
		if(getApplicationObject("weboffice15mins") != "yes") return "<br>&nbsp;";
	}
}

// converts 10.5 to 10:30, 10.25 to 10:15, etc.
function showTime($myTime) {
	if(floor($myTime) == $myTime) {
		$showTime = $myTime.":00";
	} elseif(floor($myTime * 2) == $myTime * 2) {
		$showTime = floor($myTime).":30";
	} elseif($myTime - floor($myTime) > 0.5) {
		$showTime = floor($myTime).":45";
	} else {
		$showTime = floor($myTime).":15";
	}
	if($myTime < 10) {
		$showTime = "0".$showTime;
	}
	return $showTime;
}

// displays date at top of diary box, e.g. "13 July"
function displayDay($myDate, $daysToAdd, $showday = false, $dbformat = false) {
	global $arrMonths;
	
	if($dbformat) {
		return date("Y-m-d", DateAdd("d", $daysToAdd, $myDate));
	} elseif($showday) {
		return date("l d", DateAdd("d", $daysToAdd, $myDate))."&nbsp;".$arrMonths[date("m", DateAdd("d", $daysToAdd, $myDate)) - 1];
	} else {
		return date("d", DateAdd("d", $daysToAdd, $myDate))."&nbsp;".$arrMonths[date("m", DateAdd("d", $daysToAdd, $myDate)) - 1];
	}
}

// daynum - 0 = monday, 1 = tuesday, etc.
// only used with Web Office instances where internal users' start/end times are recorded against their record (none do this at present)
// todo - this needs updating so it works in 30-mins and 15-mins intervals
function setBusyIntervalsWithStartEndTime($userID, $daynum, $firstdayofweek) {
	global $busyContent;

	for($i = 1; $i <= 6; $i++) {
		$currentDay = DateAdd("d", $i - 1, $firstdayofweek);
		$key = date("Ymd", $currentDay);

		$start1 = getApplicationObject($userID."_start1_".$i) * 2;
		$start2 = getApplicationObject($userID."_start2_".$i) * 2;
		$end1 = getApplicationObject($userID."_end1_".$i) * 2;
		$end2 = getApplicationObject($userID."_end2_".$i) * 2;

		// 7:00 to 23:30
		for($j = 14; $j < 47; $j++) {
			if($start1 == "" && $start2 == "") {
				$busyContent[$key][$j] = 2;
			} elseif($start1 != "" && $end1 == "" && $start2 == "" && $end2 != "") {
				if($j < $start1 || $j > $end2) $busyContent[$key][$j] = 2;
			} elseif($start1 != "" && $end1 != "" && $start2 == "" && $end2 == "") {
				if($j < $start1 || $j > $end1) $busyContent[$key][$j] = 2;
			} elseif($start1 == "" && $end1 == "" && $start2 != "" && $end2 != "") {
				if($j < $start2 || $j > $end2) $busyContent[$key][$j] = 2;
			} elseif($start1 != "" && $end1 != "" && $start2 != "" && $end2 != "") {
				if($j < $start1 || ($j > $end1 && $j < $start2) || $j > $end2) $busyContent[$key][$j] = 2;
			}

		}
	}
}

// updates busy / not busy array - busyContent
// busyContent[yearmonthday][0 -> 48] => 1 (for 30-min MWO diary)
// busyContent[yearmonthday][0 -> 96] => 1 (for 15-min MWO diary)
// if using start/end times, then 2 = not working at this time
// on (authorised) holiday => 3
function updateBusyIntervals($diaryId, $starttime, $endtime, $eventtype, $dateForRecurring = null) {
	global $busyContent, $holidayid, $prodcatcolour, $busyDiaryIds;

	if(is_null($dateForRecurring)) {
		$key = date("Ymd", $starttime);
	} else {
		$key = date("Ymd", $dateForRecurring);
	}

	if(getApplicationObject("weboffice15mins") == "yes") {
		$startval = floor(((date("G", $starttime) * 60) + date("i", $starttime)) / 15);
		$endval   = floor(((date("G", $endtime) * 60) + date("i", $endtime)) / 15);
	} else {
		$startval = floor(((date("G", $starttime) * 60) + date("i", $starttime)) / 30);
		$endval   = floor(((date("G", $endtime) * 60) + date("i", $endtime)) / 30);
	}

	for($i = $startval; $i < $endval; $i++) {
		if($prodcatcolour == "") {
			$busyContent[$key][$i] = ($eventtype == $holidayid ? 3 : 1);
		} else {
			$busyContent[$key][$i] = $prodcatcolour; 
		}

		if(isset($busyDiaryIds[$key][$i])) $busyDiaryIds[$key][$i].= ",".$diaryId; else $busyDiaryIds[$key][$i] = $diaryId;
	}
}

// takes in a diary event, and updates our array that is used for display
function updateDiaryContent($currentDate, $starttime, $endtime, $diaryevent, $diaryId, $personName, $eventtype, $updateHours, $notTime) {
	global $diaryType, $diaryContent, $viewFor, $currentDay, $linkedId, $userId, $daysToView, $smartdb, $userids;

	$myDateStart = $starttime;
	$myDateEnd   = $endtime;
	if(DateDiff("d", $myDateStart, $myDateEnd) == 0) {
		// event starts and ends on same day
		if($daysToView == 31) {
			$dayOfWeek = date("j", $starttime) - 1;
		} else {
			$dayOfWeek = getDayInt($starttime);
		}
		$diaryContent[$dayOfWeek].= getEventForDisplay($starttime, $endtime, $diaryevent, $diaryId, $personName, -1, $eventtype, true, false, $notTime);
		// set colour!
		if($eventtype==1 && $viewFor=="me" && $userId != 0) $diaryType[$dayOfWeek] = "Hol";
		// one-day view - set time
		if($updateHours) {
			addTimeToDictionary($starttime, false, $notTime, 0, DateDiff("d", $currentDate, $myDateStart));
		}
		// update array that contains booleans - busy / not busy
		// change to the above - now colours
		if($daysToView == 1) updateBusyIntervals($diaryId, $starttime, $endtime, $eventtype);
	} else {
		for($i = 0; $i < 31; $i++) {
			$dayToLookAt = DateAdd("d", $i, $currentDate);
			if(DateDiff("d", $dayToLookAt, $myDateStart) == 0) {
				// start of multi-day
				$diaryContent[$i].= getEventForDisplay($starttime, $endtime, $diaryevent, $diaryId, $personName, 0, $eventtype, true, false, $notTime);
				if($eventtype==1 && $viewFor=="me" && $userId != 0) $diaryType[$i] = "Hol";
				// one-day view - set time
				if($updateHours) {
					addTimeToDictionary($starttime, false, $notTime, 1, $i);
				}
			} elseif(DateDiff("d", $dayToLookAt, $myDateEnd) == 0) {
				// end of multi-day
				$diaryContent[$i].= getEventForDisplay($starttime, $endtime, $diaryevent, $diaryId, $personName, 2, $eventtype, true, false, $notTime);
				if($eventtype==1 && $viewFor=="me" && $userId != 0) $diaryType[$i] = "Hol";
				// one-day view - set time
				if($updateHours) {
					addTimeToDictionary($endtime, false, $notTime, 3, $i);
				}
			} elseif(DateDiff("d", $dayToLookAt, $myDateStart) < 0 && DateDiff("d", $dayToLookAt, $myDateEnd) > 0) {
				// during event
				$diaryContent[$i].= getEventForDisplay($starttime, $endtime, $diaryevent, $diaryId, $personName, 1, $eventtype, true, false, $notTime);
				if($eventtype==1 && $viewFor=="me" && $userId != 0) $diaryType[$i] = "Hol";
				// one-day view - set time
				if($updateHours) {
					addTimeToDictionary($dayToLookAt, false, $notTime, 2, $i);
				}
			}
		}
	}

}

// eventType: 0=non-spanning; 1=1st day of spanning; 2=middle of spanning; 3=end of spanning
function addTimeToDictionary($starttime, $recur, $notTime, $partofday, $key) {
	global $diaryMinutes, $endtime, $diaryevent, $diaryId, $personName, $eventtype, $smartdb, $userids;

	$dictKey = date("H:i", $starttime);
	if($partofday == 3) {
		$diaryMinutes[$key][$dictKey].= "(event ends)".getEventForDisplay($starttime, $endtime, $diaryevent, $diaryId, $personName, 0, $eventtype, false, $recur, $notTime);
	} elseif($partofday == 2) {
		$diaryMinutes[$key]["span"].= "(all day)".getEventForDisplay($starttime, $endtime, $diaryevent, $diaryId, $personName, 0, $eventtype, false, $recur, $notTime);
	} elseif($partofday == 1) {
		$diaryMinutes[$key][$dictKey].= "(event starts)".getEventForDisplay($starttime, $endtime, $diaryevent, $diaryId, $personName, 0, $eventtype, false, $recur, $notTime);
	} else {
		$diaryMinutes[$key][$dictKey].= getEventForDisplay($starttime, $endtime, $diaryevent, $diaryId, $personName, 0, $eventtype, false, $recur, $notTime);
	}
}

// adds daysToAdd days to myDate, then returns a comma-separated list of the components:
// day, month (0 -> 11), year
function jscriptDate($myDate, $daysToAdd) {
	return date("d", DateAdd("d", $daysToAdd, $myDate)).",".(date("m", DateAdd("d", $daysToAdd, $myDate)) - 1).",".date("Y", DateAdd("d", $daysToAdd, $myDate));
}

// returns the HTML for an event, takes in database dates
// partofday is: -1 for a one-day event
//               0  for start of event that spans more than one day
//               1  for an event that is in the middle of two days
//               2  the last day in a multi-day event
function getEventForDisplay($starttime, $endtime, $diaryevent, $diaryId, $personName, $partofday, $eventtype, $showTime, $recur, $notTime) {
	global $eventColours, $viewFor, $daysToView, $userId, $HTTP_SESSION_VARS, $linkedId, $smartdb, $mulview, $userids;

	// icons
	if($eventtype == 999) {
		$getEventForDisplay.= "<img alt=\"Private\" hspace=\"1\" align=\"top\" src=\"/images/private.gif\" width=\"12\" height=\"14\">";
	} elseif($eventtype == 998) {
		$getEventForDisplay.= "<img alt=\"Meeting\" hspace=\"1\" align=\"top\" src=\"/images/meetingicon.gif\" width=\"12\" height=\"14\">";
	} elseif($eventtype == 997 || $eventtype == 996) {
		$getEventForDisplay.= "<img alt=\"Task\" hspace=\"1\" align=\"top\" src=\"/images/taskicon.gif\" width=\"13\" height=\"14\">";
	}
	if($eventtype == 995) {
		$getEventForDisplay.= "<img alt=\"SMART\" hspace=\"1\" align=\"top\" src=\"/images/smarticon.gif\" width=\"13\" height=\"14\">";
	}
	if($recur) {
		$getEventForDisplay.= "<img alt=\"Recurring event\" hspace=\"1\" align=\"top\" src=\"/images/recurrArrow.gif\" width=\"12\" height=\"14\">";
	}
	if($notTime > -1) {
		$getEventForDisplay.= "<img alt=\"Notification\" hspace=\"1\" align=\"top\" src=\"/images/diaryNotif.gif\" width=\"12\" height=\"14\">";
	}

	if($eventtype == 999 && $userId != $HTTP_SESSION_VARS["mwoid"]) {
		// no link for private events!
	} elseif((($viewFor != "me" || $userId == 0) && $eventtype == 1) || ($eventtype > 1 && $eventtype < 900)) {
		// highlight line for events
		$getEventForDisplay.= "<a style=\"background-color:".$eventColours[$eventtype]."\" href=\"javascript:viewEvent(".$diaryId.",'".$smartdb."')\">";
	} elseif($eventtype == 997 || $eventtype == 996) { // tasks
		if($eventtype == 996) {
			// strike-through completed tasks
			$getEventForDisplay.= "<a style=\"text-decoration:line-through\" href=\"javascript:viewEvent(".$diaryId.",'".$smartdb."')\">";
		} else {
			$getEventForDisplay.= "<a href=\"javascript:viewEvent(".$diaryId.",'".$smartdb."')\">";
		}
	} elseif($eventtype == 994 || $eventtype == 991 || $eventtype == 989 || $eventtype == 988) {
		// invoice link to a project (994 - reccuring invoice, or 991 - timesheet, or 989 - prototype req., 988 - final required)
		$getEventForDisplay.= "<a style=\"background-color:".$eventColours[$eventtype]."\" href=\"javascript:viewProject(".$diaryId.")\">";
		if($eventtype == 991 && $userId == $HTTP_SESSION_VARS["mwoid"]) {
			$getEventForDisplay = " [<a href=\"#\" onClick=\"if(confirm('Delete this timesheet?')) parent.location='index.php?delevent=true&delid=".$diaryId."&mulview=true&eventType=991'; return false;\">del</a>] ".$getEventForDisplay;
		}
	} elseif($eventtype == 993) {
		// not-yet-authorised holiday
		$getEventForDisplay.= "<a style=\"background-color:".$eventColours[993]."\" href=\"javascript:viewEvent(".$diaryId.",'".$smartdb."')\">";
		$diaryevent = "NOT YET AUTHORISED - ".$diaryevent;
	} elseif($eventtype == 992 || $eventtype == 990 || $eventtype == 987) {
		// booking (client linked to product ('service')) - 990 is completed booking, 987 is no-show
		if($eventtype == 992) {
			$getEventForDisplay.= "<a title=\"Booking - ".date("h:i", $starttime)." to ".date("h:i", $endtime)."\" href=\"javascript:viewBooking(".$diaryId.")\">";
		} else {
			$getEventForDisplay.= "<a title=\"Booking - ".date("h:i", $starttime)." to ".date("h:i", $endtime)."\" style=\"color:#FFFFCC;\" href=\"javascript:viewBooking(".$diaryId.")\">";
		}
	} else {
		// no line hightlighting
		$getEventForDisplay.= "<a href=\"javascript:viewEvent(".$diaryId.",'".$smartdb."')\">";
	}

	if($showTime) {
		if($partofday == -1 || $partofday == 0) {
			$getEventForDisplay.= date("H:i", $starttime);
		}
		if($partofday == -1 || $partofday == 2) {
			$getEventForDisplay.= "-".date("H:i", $endtime);
		}
		if($partofday == 1) {
			$getEventForDisplay.= "(all day)";
		}
	}

	if($linkedId > 0) {
		$getEventForDisplay.= "&nbsp;[".getNamesForLinkedDiary($linkedId)."]";
	} elseif($mulview == "true") {
		// don't display person's name?
	} elseif($viewFor != "me" || $personName == "All" || $userids != "") {
		$getEventForDisplay.= "&nbsp;[".$personName."]";
	}
	
	if(getApplicationObject("weboffice15mins") == "yes") {
		$linend = "<br>";
	} else {
		$linend = "<br><br>";
	}

	if($eventtype == 999 && $userId != $HTTP_SESSION_VARS["mwoid"]) {
		return $getEventForDisplay."&nbsp;[busy]".$linend;
	} elseif($daysToView == 1 || isPda()) {
		return $getEventForDisplay."&nbsp;".$diaryevent."</a>".$linend;
	} elseif($daysToView == 31) {
		return $getEventForDisplay."&nbsp;".getShortenedString($diaryevent, 20)."</a>".$linend;
	} else {
		return $getEventForDisplay."&nbsp;".getShortenedString($diaryevent, 50)."</a>".$linend;
	}
}

function getNamesForLinkedDiary($linkedId) {
	global $myDb;
	
	$namesToReturn = "";
	$mySQL = "SELECT firstname, lastname FROM diary, users WHERE diary.userid=users.id AND diary.isDeleted=0 AND diary.linkedId=".$linkedId;
	$rows = gendb_query($mySQL, $myDb) or die(gendb_error());
	while ($row = gendb_fetch_assoc($rows)) {
		if($namesToReturn == "") {
			$namesToReturn = $row["firstname"]." ".$row["lastname"];
		} else {
			$namesToReturn.= ", ".$row["firstname"]." ".$row["lastname"];
		}
	}
	gendb_free_result($rows);
	
	return $namesToReturn;
}

// takes in a database date, returns 0 for Monday, 1 for Tuesday, etc.
function getDayInt($starttime) {
	return (date("w", $starttime) + 6) % 7;
}

// if the user is part of diary admin, it displays a drop-down of departments
// if mulview == true, then instead offer user to select people who can view diary
function dispAdminView($mulview = "false", $myaction = "", $userids = "") {
	global $myDb, $p2, $currentDay, $currentWeek, $currentMonth, $currentYear, $daysToView, $viewFor, $myCompId, $HTTP_SESSION_VARS, $client, $eventType;

	if(isPda()) {
		if(isDiaryAdminUser() && $p2=="" && $HTTP_SESSION_VARS["is-smart"] != "true") {
			$dispAdminView = "<form name=\"frm\" style=\"margin:0px\" method=\"get\" action=\"pdamonth.php\">";
			$dispAdminView.= "<select name=\"viewFor\" onChange=\"document.frm.submit();\">";
			if($viewFor == "me") {
				$dispAdminView.= "<option value=\"me\" selected>View my diary</option>";
			} else {
				$dispAdminView.= "<option value=\"me\">View my diary</option>";
			}
			if($viewFor == "all") {
				$dispAdminView.= "<option value=\"all\" selected>View all users' diaries</option>";
			} else {
				$dispAdminView.= "<option value=\"all\">View all users' diaries</option>";
			}
			$mySQL = "SELECT * FROM departments WHERE isDeleted=0 AND companyId=".$myCompId." ORDER BY name";
			$rows = gendb_query($mySQL, $myDb) or die(gendb_error());
			while ($row = gendb_fetch_assoc($rows)) {
				if($viewFor == $row["id"]) {
					$dispAdminView.= "<option selected value=\"".$row["id"]."\">View for dept. ".$row["name"]."</option>";
				} else {
					$dispAdminView.= "<option value=\"".$row["id"]."\">View for dept. ".$row["name"]."</option>";
				}
			}
			gendb_free_result($rows);
			$dispAdminView.= "</select>";

			return $dispAdminView;
		}
	} else {
		if($userids != "") {
			$dispAdminView = "<table><tr><td>Viewing diary for ";
			$myuserids = explode(",", $userids);
			foreach($myuserids as $userid) {
				$dispAdminView.= getSingleValueFromSQL("SELECT CONCAT(firstname,' ',lastname) FROM users WHERE id=".$userid).", ";
			}
			$dispAdminView = eregi_replace(", $", "", $dispAdminView);
			$dispAdminView.= "</td><td> <a target=\"_parent\" href=\"/phonebook/phoneServ.php?makeappointment=true&interpreter=true&client=".$client."\" class=\"liteButton\">Cancel</a></td></tr></table>";

			return $dispAdminView;
		} elseif($mulview == "true") {
			if(getApplicationObject("webofficemulviewbook") == "yes") {
				if($myaction == "confirmbooking") {
					return "<table width=\"100%\"><tr><td style=\"font-weight:bold;font-size:14px\">Make appointment for ".getSingleValueFromSQL("SELECT CONCAT(firstname,' ',lastname) AS fullname FROM users WHERE id=".$client, "fullname")." - <a target=\"main\" class=\"liteButton\" href=\"index.php?mulview=true\">Cancel</a></td></tr></table>";
				} else {
					return "<table width=\"100%\"><tr><td><a target=\"main\" class=\"liteButton\" style=\"font-weight:bold;color:red\" href=\"/clients/index.php?pbook=991&myaction=makebooking\">Make appointment &gt;&gt;</a>&nbsp;&nbsp;&nbsp;<a target=\"main\" class=\"liteButton\" href=\"/bookings/till.php?getbasketfromsession=true\">Till &gt;&gt;</a>&nbsp;&nbsp;&nbsp;<a target=\"main\" class=\"liteButton\" href=\"/clients/index.php?pbook=991\">Customer list</a></td><td align=\"right\"><a target=\"main\" href=\"../permissions/selectusers.php?objecttype=1&objectid=0\">Change whose diary you are viewing &gt;&gt;</a>&nbsp;<a href=\"#\" onClick=\"javascript:self.print();\"><img src=\"/images/print1.gif\" border=\"0\" alt=\"Print this page\"></a></td></tr></table>";
				}
			} else {
				return "<table width=\"100%\"><tr><td><a target=\"main\" href=\"../permissions/selectusers.php?objecttype=1&objectid=0&eventType=".$eventType."\">Change whose diary you are viewing &gt;&gt;</a></td><td align=\"right\"><a href=\"#\" onClick=\"javascript:self.print();\"><img src=\"/images/print1.gif\" border=\"0\" alt=\"Print this page\"></a></td></tr></table>";
			}
		} elseif(isDiaryAdminUser() && $p2=="" && $HTTP_SESSION_VARS["is-smart"] != "true") {
			$dispAdminView = "<form name=\"frm\" style=\"margin:0px\" method=\"get\" action=\"months.php\" target=\"diaryMonths\"><table width=\"100%\"><tr><td align=\"left\" width=\"100\">View diary for:</td>";
			$dispAdminView.= "<td><select name=\"viewFor\" onChange=\"document.frm.submit();\">";
			if($viewFor == "me") {
				$dispAdminView.= "<option value=\"me\" selected>Me</option>";
			} else {
				$dispAdminView.= "<option value=\"me\">Me</option>";
			}
			if($viewFor == "all") {
				$dispAdminView.= "<option value=\"all\" selected>All users</option>";
			} else {
				$dispAdminView.= "<option value=\"all\">All users</option>";
			}
			$mySQL = "SELECT * FROM departments WHERE isDeleted=0 AND companyId=".$myCompId." ORDER BY name";
			$rows = gendb_query($mySQL, $myDb) or die(gendb_error());
			while ($row = gendb_fetch_assoc($rows)) {
				if($viewFor == $row["id"]) {
					$dispAdminView.= "<option selected value=\"".$row["id"]."\">".$row["name"]."</option>";
				} else {
					$dispAdminView.= "<option value=\"".$row["id"]."\">".$row["name"]."</option>";
				}
			}
			gendb_free_result($rows);
			$dispAdminView.= "</select></td><td align=\"right\"><a href=\"#\" onClick=\"javascript:self.print();\"><img src=\"/images/print1.gif\" border=\"0\" alt=\"Print this page\"></a></td></tr></table>";
			$dispAdminView.= "<input type=\"hidden\" name=\"cd\" value=\"".($currentDay+1)."\">";
			$dispAdminView.= "<input type=\"hidden\" name=\"cw\" value=\"".$currentWeek."\">";
			$dispAdminView.= "<input type=\"hidden\" name=\"cm\" value=\"".$currentMonth."\">";
			$dispAdminView.= "<input type=\"hidden\" name=\"cy\" value=\"".$currentYear."\">";
			$dispAdminView.= "<input type=\"hidden\" name=\"dtv\" value=\"".$daysToView."\">";

			return $dispAdminView;
		} elseif(strpos($HTTP_SESSION_VARS["mwogroups"], ",Diary Dept View,") !== false) {
			$mydepartment = getSingleValueFromSQL("SELECT department FROM users WHERE id=".$HTTP_SESSION_VARS["mwoid"]);
			$dispAdminView = "<form name=\"frm\" style=\"margin:0px\" method=\"get\" action=\"months.php\" target=\"diaryMonths\"><table width=\"100%\"><tr><td align=\"left\" width=\"100\">View diary for:</td>";
			$dispAdminView.= "<td><select name=\"viewFor\" onChange=\"document.frm.submit();\">";
			if($viewFor == "me") {
				$dispAdminView.= "<option value=\"me\" selected>Me</option>";
			} else {
				$dispAdminView.= "<option value=\"me\">Me</option>";
			}
			if($mydepartment != "") {
				if($viewFor == $mydepartment) {
					$dispAdminView.= "<option value=\"".$mydepartment."\" selected>Users</option>";
				} else {
					$dispAdminView.= "<option value=\"".$mydepartment."\">Users</option>";
				}
			}
			$dispAdminView.= "</select></td><td align=\"right\"><a href=\"#\" onClick=\"javascript:self.print();\"><img src=\"/images/print1.gif\" border=\"0\" alt=\"Print this page\"></a></td></tr></table>";
			$dispAdminView.= "<input type=\"hidden\" name=\"cd\" value=\"".($currentDay+1)."\">";
			$dispAdminView.= "<input type=\"hidden\" name=\"cw\" value=\"".$currentWeek."\">";
			$dispAdminView.= "<input type=\"hidden\" name=\"cm\" value=\"".$currentMonth."\">";
			$dispAdminView.= "<input type=\"hidden\" name=\"cy\" value=\"".$currentYear."\">";
			$dispAdminView.= "<input type=\"hidden\" name=\"dtv\" value=\"".$daysToView."\">";

			return $dispAdminView;
		} else {
			return "<table width=\"100%\"><tr><td align=\"right\"><a href=\"#\" onClick=\"javascript:self.print();\"><img src=\"/images/print1.gif\" border=\"0\" alt=\"Print this page\"></a></td></tr></table>";
		}
	}
}

// ****************************************
// functions used in addDiary.php / pdaaddDiary.php
// ****************************************
function displayTimes($defaultTime) {
	if(getApplicationObject("weboffice15mins") == "yes") {
		for($i = 1; $i <= 22; $i++) {
			$timekey = ($i < 10 ? "0" : "").$i.":00";
			echo "<option value=\"".$timekey."\"".($defaultTime==$timekey ?  " selected" : "").">".$i.":00</option>";
			$timekey = ($i < 10 ? "0" : "").$i.":15";
			echo "<option value=\"".$timekey."\"".($defaultTime==$timekey ?  " selected" : "").">".$i.":15</option>";
			$timekey = ($i < 10 ? "0" : "").$i.":30";
			echo "<option value=\"".$timekey."\"".($defaultTime==$timekey ?  " selected" : "").">".$i.":30</option>";
			$timekey = ($i < 10 ? "0" : "").$i.":45";
			echo "<option value=\"".$timekey."\"".($defaultTime==$timekey ?  " selected" : "").">".$i.":45</option>";
		}
	} else {
		for($i = 1; $i <= 22; $i++) {
			$timekey = ($i < 10 ? "0" : "").$i.":00";
			echo "<option value=\"".$timekey."\"".($defaultTime==$timekey ?  " selected" : "").">".$i.":00</option>";
			$timekey = ($i < 10 ? "0" : "").$i.":30";
			echo "<option value=\"".$timekey."\"".($defaultTime==$timekey ?  " selected" : "").">".$i.":30</option>";
		}
	}
}

function getOptionsForEvents($defaultEvent) {
	global $p2n, $addedBy, $myDb, $dbname;

	if($defaultEvent == 993) {
		echo "<option value=\"\">Cancel request</option>";
		echo "<option selected value=\"993\">Holiday request</option>";
		return;
	}
	?>
	<option value="">Default</option>
	<? if(false && isDiaryAdminUser()) { ?>
	<option value="998"<?if($defaultEvent==998) echo(" selected")?>>Invited meeting</option>);
	<? } ?>

	<? if($dbname == "ballinger") { ?>
	<option value="995"<?if($defaultEvent==995) echo(" selected")?>>SMART</option>);
	<? } ?>

	<? if($defaultEvent==997) { ?>
	<option value="997" selected>Task</option>
	<? } elseif($defaultEvent==996) { ?>
	<option value="996" selected>Task</option>
	<? } else { ?>
	<option value="997">Task</option>
	<? } ?>
	<?
	$mySQL = "SELECT * FROM diaryeventtypes WHERE eventId>0 ORDER BY eventId";
	$rows = gendb_query($mySQL, $myDb) or die(gendb_error());
	while($row = gendb_fetch_assoc($rows)) {
		echo "<option value=\"".$row["eventId"]."\"";
		if($defaultEvent == $row["eventId"]) echo(" selected");
		echo ">".$row["eventName"]."</option>";
	}
	?>
	<option value="999"<?if($defaultEvent==999) echo(" selected")?>>Private</option>
	<?
}

function displayDate($myDate) {
	global $arrMonths;
	return date("d", $myDate)."&nbsp;".$arrMonths[date("m", $myDate) - 1]."&nbsp;".date("Y", $myDate);
}

function getDateForDb($myDate, $myTime = "") {
	// Requires a date object, then a time - e.g. "15:30" 
	// Update - or just a date object
	if($myTime != "") {
		return date("Y", $myDate)."-".date("m", $myDate)."-".date("d", $myDate)." ".$myTime.":00";
	} else {
		return date("Y-m-d H:i:s", $myDate);
	}
}

function displayNotificationDropdown($defaultNot) {
	global $arrNotificationStrs, $arrNotificationTimes;
?>
<option value="-1">No notification</option>
<option value="0"<? if($defaultNot == 0) echo " selected"; ?>>At event start</option>
<?
$notIndex = 0;
foreach($arrNotificationStrs as $notifStr) {
	if($defaultNot == $arrNotificationTimes[$notIndex]) {
		echo("<option selected value=\"".$arrNotificationTimes[$notIndex]."\">".$notifStr." before event</option>");
	} else {
		echo("<option value=\"".$arrNotificationTimes[$notIndex]."\">".$notifStr." before event</option>");
	}
	$notIndex++;
}

}

function getRecurringValue($defaultRec) {
	global $arrRecurringInts, $arrRecurringStrs;
	$recIndex = 0;
	foreach($arrRecurringStrs as $recurStr) {
		if($defaultRec == $arrRecurringInts[$recIndex]) {
			return $recurStr;
		}
		$recIndex++;
	}
	return "n/a";
}

function displayRecurringDropdown($defaultRec) {
	echo getRecurringDropdown($defaultRec);
}

function getRecurringDropdown($defaultRec) {
	global $arrRecurringInts, $arrRecurringStrs;
	$toReturn = "<option value=\"-1\">n/a</option>";
	$recIndex = 0;
	foreach($arrRecurringStrs as $recurStr) {
		if($defaultRec == $arrRecurringInts[$recIndex]) {
			$toReturn.= "<option selected value=\"".$arrRecurringInts[$recIndex]."\">".$recurStr."</option>";
		} else {
			$toReturn.= "<option value=\"".$arrRecurringInts[$recIndex]."\">".$recurStr."</option>";
		}
		$recIndex++;
	}

	return $toReturn;
}
?>
Return current item: Silicon Fodder