<?php
/*
This file is part of Thomas Bley's moregroupware webmail2/calendar2/admin2 module. (tb-mgw)

More information:
-----------------

Simple Groupware Solutions Thomas Bley
Fichtenstr. 23
Germany, 85640 Putzbrunn

Contact:
--------

info@simple-groupware.de

http://www.simple-groupware.de


Copyright 2002-2003 Thomas Bley
tb-mgw is distributed under the terms of the GNU General Public License 

tb-mgw is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.

tb-mgw is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with tb-mgw; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
*/

// Ical_parser
// Moregroupware.org

include(CAL2_INC_DIR.'init.inc.php');
include(CAL2_INC_DIR.'init2.inc.php');
include_once(CAL2_INC_DIR.'timezones.php');

$fillTime = $day_start;
$day_array = array ();
while ($fillTime != $day_end) {
	array_push ($day_array, $fillTime);
	ereg ('([0-9]{2})([0-9]{2})', $fillTime, $dTime);
	$fill_h = $dTime[1];
	$fill_min = $dTime[2];
	$fill_min = sprintf('%02d', $fill_min + $gridLength);
	if ($fill_min == 60) {
		$fill_h = sprintf('%02d', ($fill_h + 1));
		$fill_min = '00';
	}
	$fillTime = $fill_h . $fill_min;
}

// what date we want to get data for (for day calendar)
if (!isset($getdate) || $getdate == '') $getdate = date('Ymd');
ereg ('([0-9]{4})([0-9]{2})([0-9]{2})', $getdate, $day_array2);
$this_day = $day_array2[3];
$this_month = $day_array2[2];
$this_year = $day_array2[1];


// Set a value so we can check to make sure $master_array contains valid data
$master_array['-1'] = 'valid cal file';
$master_array['calendar_tz'] = $_SESSION["MGW"]->settings["cal2_timezone"];

$calendar_tz = $master_array['calendar_tz'];

// auxiliary array for determining overlaps of events
$overlap_array = array ();
$cal_legend = array();

$all_cals = array();	
	
// using $uid to set specific points in array, if $uid is not in the 
// .ics file, we need to have some unique place in the array
$uid_counter = 0;

$the_duration = "";
$valarm_description = "";
$wkst = "";
$recurrence_d = "";
$calendar_name = "";
$processed = array();

$color_i=0;

if (count($cal_entries)>0) {
  foreach ($cal_entries as $calendar) {
	foreach ($calendar as $entry) {

	  if (!count($entry)>0) continue;
	
  	  if (!isset($cal_legend[$entry["dcalendar"]])) {
		$color_i++;
	    $cal_legend[$entry["dcalendar"]] = array(ucfirst(get_real_calendar_name($entry["dcalendar"]))." (".get_type_calendar($entry["dcalendar"]).")",$colors[$color_i]);
	  }
	
  	  $except_dates = array();
	  $except_times = array();
	  $first_duration = TRUE;
	  $count = 1000000;
	  $valarm_set = FALSE;
	  
	  $bymonth = "";
	  $byday = "";
	  $bymonthday = "";
	  $byweek = "";
	  $byweekno = "";
	  
	  $hour = "";
	  $minute = "";
	  $status = "";
	  
	  unset(
	  	$start, $end,
		$until,
		$byminute, $byhour, $bysecond, $byyearday, $bysetpos, $wkst, 
		$interval, $number
	  );
	  $homepage = "";
	  
	  $uid = $entry["id"];
	  
	  $description = trim(modify_html(str_replace(array("\\n","\\r","\n","\r"), "", $entry["ddesc"])));
	  if ($description=="<br />" or $description=="<p />") $description="";
	  
	  $summary = htmlentities(str_replace(array("\\n","\\r"), "<br>", strip_tags($entry["dsummary"])));
	  $summary_gantt = str_replace(array("\\n","\\r"), "<br>", strip_tags($entry["dsummary"]));
 	  $location = htmlentities(str_replace(array("\\n","\\r"), "<br>", strip_tags($entry["dlocation"])));

	  $entry["dorganizer"] = isset($entry["dorganizer"])?get_array_from_string($entry["dorganizer"]):array();
	  $entry["dattendee"] = isset($entry["dattendee"])?get_array_from_string($entry["dattendee"]):array();
	  $entry["dattendee_non"] = isset($entry["dattendee_non"])?get_array_from_string($entry["dattendee_non"]):array();
	  $entry["doptional"] = isset($entry["doptional"])?get_array_from_string($entry["doptional"]):array();
	  
	  $entry["daccepted"] = isset($entry["daccepted"])?get_array_from_string($entry["daccepted"]):array();
	  $entry["ddeclined"] = isset($entry["ddeclined"])?get_array_from_string($entry["ddeclined"]):array();
	  $entry["dtentative"] = isset($entry["dtentative"])?get_array_from_string($entry["dtentative"]):array();
	  
      /*	  
	  if ($entry["dcalendar"]!=$_SESSION["MGW"]->username or count($entry["dorganizer"])>0 or count($entry["dattendee"])>0 or count($entry["dattendee_non"])>0 or count($entry["doptional"])>0) {
        $sql = "select username,email from mgw_users where id=".(int)$entry["c_duser_id"];
        if(!$res2 = $conn->Execute($sql)) exit(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));
	    $row2 = $res2->FetchRow();
        if (isset($row2["username"]) and $row2["username"]!="") {
  	      $entry["dorganizer"][] = $row2["username"];
        }
	  }
	  */
	  
	  $summary2 = "";
	  if ($entry["dcalendar"]==$hashmap["preview"]) {
	    $summary2 = '#';
	    if ($entry["dstatus"]=="cancelled") $summary2 = 'delete';
	  }
	  
	  if (isset($entry["dhomepage"])) $homepage = htmlentities(str_replace(array("\\n","\\r"), "<br>", strip_tags($entry["dhomepage"])));
 	  $class = htmlentities(str_replace(array("\\n","\\r"), "<br>", strip_tags($entry["dclass"])));

 	  $color = $cal_legend[$entry["dcalendar"]][1];

	  if ($entry["dcategories"]!="None") {
	    $categories = htmlentities(str_replace(array("\\n","\\r"), "<br>", strip_tags(str_replace("None,","",$entry["dcategories"]))));
	  } else {
	    $categories = "";
	  }
	  
      if (strlen($entry["dstart"]) > 8 and strlen($entry["dend"]) > 8) {
		$tz_dtstart = $calendar_tz;
		$tz_dtend = $calendar_tz;
		  
		ereg ('([0-9]{4})([0-9]{2})([0-9]{2})T([0-9]{0,2})([0-9]{0,2})', $entry["dstart"], $regs);
		$start_date = $regs[1] . $regs[2] . $regs[3];
		$start_time = $regs[4] . $regs[5];
		$start_unixtime = mktime($regs[4], $regs[5], 0, $regs[2], $regs[3], $regs[1]);
		
		ereg ('([0-9]{4})([0-9]{2})([0-9]{2})T([0-9]{0,2})([0-9]{0,2})', $entry["dend"], $regs);
		$end_date = $regs[1] . $regs[2] . $regs[3];
		$end_time = $regs[4] . $regs[5];
		$end_unixtime = mktime($regs[4], $regs[5], 0, $regs[2], $regs[3], $regs[1]);

		$start_unixtime = calcTime($tz_array[$tz_dtstart][date('I', $start_unixtime)], chooseOffset($start_unixtime), $start_unixtime);
		$start_date = date('Ymd', $start_unixtime);
		$start_time = date('Hi', $start_unixtime);

		$end_unixtime = calcTime($tz_array[$tz_dtend][date('I', $end_unixtime)], chooseOffset($end_unixtime), $end_unixtime);
		$end_date = date('Ymd', $end_unixtime);
		$end_time = date('Hi', $end_unixtime);

		$allday_start = "";
		$allday_end = "";
	  } else {
		$allday_start = $entry["dstart"];
		$allday_end = $entry["dend"];
		$start_date = $entry["dstart"];
		$start_time = "";
		$end_time = "";
		$start_unixtime = "";
		$end_unixtime = "";
		$end_date = "";
	  }
	  
	  $rrule_array = array();
	  if ($entry["drep_freq"]!="none" and $entry["drep_interval"]!=0 and ($entry["drep_freq"]!="weekly" or $entry["drep_days"])) {
		$rrule_array["INTERVAL"] = $entry["drep_interval"];
		$rrule_array["FREQ"] = strtoupper($entry["drep_freq"]);
	  
        if ($entry["drep_until"]!="forever" and $entry["drep_until"]!="") $rrule_array["UNTIL"] = $entry["drep_until"];
        if ($entry["drep_count"]!=0 and $entry["drep_count"]) $rrule_array["COUNT"] = $entry["drep_count"];

        if ($entry["drep_freq"]=="weekly") $rrule_array["BYDAY"] = strtoupper($entry["drep_days"]);
        if ($entry["drep_freq"]=="monthly") $rrule_array["BYMONTHDAY"] = (int)substr($entry["dstart"],6,2);
        if ($entry["drep_freq"]=="yearly") $rrule_array["BYMONTH"] = (int)substr($entry["dstart"],4,2);

		if (isset($entry["drep_exdate"]) and $entry["drep_exdate"]!="") {
		  $except_dates = explode(",",$entry["drep_exdate"]);
		  foreach ($except_dates as $except_date) {
		    $except_times[] = "0000";
		  }
		}
	  }

	  $all_cals[$uid] = array(
	    "calendar"=>addslashes($entry["dcalendar"]),
	    "homepage"=>$homepage,
		"location"=>$location,
		"description"=>$description,
		"categories"=>addslashes($categories),
		"summary"=>$summary,
		"summary_gantt"=>$summary_gantt,
		"summary2"=>$summary2,
		"color"=>$color,
		"class"=>addslashes($class),
		"dorganizer"=>implode($entry["dorganizer"],", "),
		"dattendee"=>implode($entry["dattendee"],", "),
		"dattendee_non"=>implode($entry["dattendee_non"],", "),
		"doptional"=>implode($entry["doptional"],", "),
		"daccepted"=>implode($entry["daccepted"],", "),
		"ddeclined"=>implode($entry["ddeclined"],", "),
		"dtentative"=>implode($entry["dtentative"],", "),
		"row"=>$entry
	  );
	  
			$uid_valid = true;
			$write_processed = true;
			
			$mArray_begin = mktime (0,0,0,12,21,($this_year - 1));
			$mArray_end = mktime (0,0,0,1,12,($this_year + 1));

			if (isset($start_time) && isset($end_time)) {
				// Mozilla style all-day events or just really long events
				if (($end_time - $start_time) > 2345) {
					$allday_start = $start_date;
					$allday_end = ($start_date + 1);
				}
			}
			if (isset($start_unixtime,$end_unixtime) && date('d',$start_unixtime) != date('d',$end_unixtime)) {
				$spans_day = true;
			} else {
				$spans_day = false;
			}
			if (isset($start_time) && $start_time != '') {
				ereg ('([0-9]{2})([0-9]{2})', $start_time, $time);
				ereg ('([0-9]{2})([0-9]{2})', $end_time, $time2);
				if (isset($start_unixtime) && isset($end_unixtime)) {
					$length = $end_unixtime - $start_unixtime;
				} else {
					$length = ($time2[1]*60+$time2[2]) - ($time[1]*60+$time[2]);
				}
				
				$drawKey = drawEventTimes($start_time, $end_time);
				ereg ('([0-9]{2})([0-9]{2})', $drawKey['draw_start'], $time3);
				$hour = $time3[1];
				$minute = $time3[2];
			}

			// RECURRENCE-ID Support
			if ($recurrence_d) {
				$recurrence_delete["$recurrence_d"]["$recurrence_t"] = $uid;
			}
				
			// handle single changes in recurring events
			// Maybe this is no longer need since done at bottom of parser? - CL 11/20/02
			if ($uid_valid && $write_processed) {
				$processed[$uid] = array($start_date,($hour.$minute));
			}
						
			// Handling of the all day events
			if ((isset($allday_start) && $allday_start != '')) {
				$start = strtotime2($allday_start);
				if (isset($allday_end)) {
					$end = strtotime2($allday_end);
				} else {
					$end = strtotime2('+1 day', $start);
				}
				if (($end > $mArray_begin) && ($end < $mArray_end)) {
				    $while_i = 0;
					while ($start != $end) {
					    $while_i++;
						if ($while_i==10000) break;
						$start_date2 = date('Ymd', $start);
						$master_array[($start_date2)][('-1')][$uid]= array ('@' => "");
						$start = strtotime2('+1 day', $start);
					}
					if (!$write_processed) $master_array[($start_date)]['-1'][$uid]['exception'] = true;
				}
			}
			
			// Handling regular events
			if ((isset($start_time) && $start_time != '') && (!isset($allday_start) || $allday_start == '')) {
				if ($spans_day) {
					$start_tmp = strtotime2(date('Ymd',$start_unixtime));
					$end_date_tmp = date('Ymd',$end_unixtime);
					while ($start_tmp < $end_unixtime) {
						$start_date_tmp = date('Ymd',$start_tmp);
						if ($start_date_tmp == $start_date) {
							$time_tmp = $hour.$minute;
							$start_time_tmp = $start_time;
						} else {
							$time_tmp = '0000';
							$start_time_tmp = '0000';
						}
						if ($start_date_tmp == $end_date_tmp) {
							$end_time_tmp = $end_time;
						} else {
							$end_time_tmp = '2400';
						}

						$nbrOfOverlaps = checkOverlap($start_date_tmp, $start_time_tmp, $end_time_tmp, $uid);
						$master_array[$start_date_tmp][$time_tmp][$uid] = array ('event_start' => $start_time_tmp, 'event_end' => $end_time_tmp, 'start_unixtime' => $start_unixtime, 'end_unixtime' => $end_unixtime, 'event_length' => $length, 'event_overlap' => $nbrOfOverlaps, 'status' => $status, 'spans_day' => true);
						$start_tmp = strtotime2('+1 day',$start_tmp);
					}
					if (!$write_processed) $master_array[$start_date][($hour.$minute)][$uid]['exception'] = true;
				} else {
					$nbrOfOverlaps = checkOverlap($start_date, $start_time, $end_time, $uid);
					$master_array[($start_date)][($hour.$minute)][$uid] = array ('event_start' => $start_time, 'event_end' => $end_time, 'start_unixtime' => $start_unixtime, 'end_unixtime' => $end_unixtime, 'event_length' => $length, 'event_overlap' => $nbrOfOverlaps, 'status' => $status, 'spans_day' => false);
					if (!$write_processed) $master_array[($start_date)][($hour.$minute)][$uid]['exception'] = true;
				}
			}
			
			// Handling of the recurring events, RRULE
			if (isset($rrule_array) && is_array($rrule_array) && count($rrule_array)>0) {
				if (isset($allday_start) && $allday_start != '') {
					$hour = '-';
					$minute = '1';
					$rrule_array['START_DAY'] = $allday_start;
					$rrule_array['END_DAY'] = $allday_end;
					$rrule_array['END'] = 'end';
					$recur_start = $allday_start;
					$start_date = $allday_start;
					if (isset($allday_end)) {
						$diff_allday_days = dayCompare($allday_end, $allday_start);
					 } else {
						$diff_allday_days = 1;
					}
				} else {
					$rrule_array['START_DATE'] = $start_date;
					$rrule_array['START_TIME'] = $start_time;
					$rrule_array['END_TIME'] = $end_time;
					$rrule_array['END'] = 'end';
				}
				
				$start_date_time = strtotime2($start_date);
				$this_month_start_time = strtotime2($this_year.$this_month.'01');

					$start_range_time = strtotime2($this_year.'-01-01 -1 month -2 days');
					$end_range_time = strtotime2($this_year.'-12-31 +1 month +2 days');

				// $start_range_time = strtotime2('-1 month -2 day', $this_month_start_time);
				// $end_range_time = strtotime2('+2 month +2 day', $this_month_start_time);
				
				foreach ($rrule_array as $key => $val) {
					switch($key) {
						case 'FREQ':
							switch ($val) {
								case 'YEARLY':		$freq_type = 'year';	break;
								case 'MONTHLY':		$freq_type = 'month';	break;
								case 'WEEKLY':		$freq_type = 'week';	break;
								case 'DAILY':		$freq_type = 'day';		break;
								case 'HOURLY':		$freq_type = 'hour';	break;
								case 'MINUTELY':	$freq_type = 'minute';	break;
								case 'SECONDLY':	$freq_type = 'second';	break;
							}
							$master_array[($start_date)][($hour.$minute)][$uid]['recur'][$key] = strtolower($val);
							break;
						case 'COUNT':
							$count = $val;
							$master_array[($start_date)][($hour.$minute)][$uid]['recur'][$key] = $count;
							break;
						case 'UNTIL':
							$until = ereg_replace('T', '', $val);
							$until = ereg_replace('Z', '', $until);
							ereg ('([0-9]{4})([0-9]{2})([0-9]{2})([0-9]{0,2})([0-9]{0,2})', $until, $regs);
							$year = $regs[1];
							$month = $regs[2];
							$day = $regs[3];
							$until = mktime(0,0,0,$month,$day,$year);
							if (ereg('^([0-9]{4})([0-9]{2})([0-9]{2})T([0-9]{2})([0-9]{2})([0-9]{2})$', $val)) {
								// RFC 2445 says that if an UNTIL has a date-time value,
								// it MUST be in UTC (i.e. trailing Z).  iCal tends to
								// put an end date on the next day early in the morning,
								// not in UTC time, so we try to correct for it.
								//
								// Bill's guess: iCal stores the UNTIL internally as
								// 23:59:59 UTC, then accidentally converts that to local
								// time when exporting the event.  Thus, if the UNTIL time
								// is before noon, it is a day ahead; if it's after noon
								// it's the right day.
								if ($regs[4] < 12)
									$until = strtotime2('-1 day', $until);
							}
							$master_array[($start_date)][($hour.$minute)][$uid]['recur'][$key] = localizeDate($hashmap["dateFormat_week"],$until);
							break;
						case 'INTERVAL':
							$number = $val;
							$master_array[($start_date)][($hour.$minute)][$uid]['recur'][$key] = $number;
							break;
						case 'BYSECOND':
							$bysecond = $val;
							$bysecond = split (',', $bysecond);
							$master_array[($start_date)][($hour.$minute)][$uid]['recur'][$key] = $bysecond;
							break;
						case 'BYMINUTE':
							$byminute = $val;
							$byminute = split (',', $byminute);
							$master_array[($start_date)][($hour.$minute)][$uid]['recur'][$key] = $byminute;
							break;
						case 'BYHOUR':
							$byhour = $val;
							$byhour = split (',', $byhour);
							$master_array[($start_date)][($hour.$minute)][$uid]['recur'][$key] = $byhour;
							break;
						case 'BYDAY':
							$byday = $val;
							$byday = split (',', $byday);
							$master_array[($start_date)][($hour.$minute)][$uid]['recur'][$key] = $byday;
							break;
						case 'BYMONTHDAY':
							$bymonthday = $val;
							$bymonthday = split (',', $bymonthday);
							$master_array[($start_date)][($hour.$minute)][$uid]['recur'][$key] = $bymonthday;
							break;					
						case 'BYYEARDAY':
							$byyearday = $val;
							$byyearday = split (',', $byyearday);
							$master_array[($start_date)][($hour.$minute)][$uid]['recur'][$key] = $byyearday;
							break;
						case 'BYWEEKNO':
							$byweekno = $val;
							$byweekno = split (',', $byweekno);
							$master_array[($start_date)][($hour.$minute)][$uid]['recur'][$key] = $byweekno;
							break;
						case 'BYMONTH':
							$bymonth = $val;
							$bymonth = split (',', $bymonth);
							$master_array[($start_date)][($hour.$minute)][$uid]['recur'][$key] = $bymonth;
							break;
						case 'BYSETPOS':
							$bysetpos = $val;
							$master_array[($start_date)][($hour.$minute)][$uid]['recur'][$key] = $bysetpos;
							break;
						case 'WKST':
							$wkst = $val;
							$master_array[($start_date)][($hour.$minute)][$uid]['recur'][$key] = $wkst;
							break;
						case 'END':
					
						// if $until isn't set yet, we set it to the end of our range we're looking at
						if (!isset($until)) $until = $end_range_time;
						$end_date_time = $until;
						$start_range_time_tmp = $start_range_time;
						$end_range_time_tmp = $end_range_time;
						
						// If the $end_range_time is less than the $start_date_time, or $start_range_time is greater
						// than $end_date_time, we may as well forget the whole thing
						// It doesn't do us any good to spend time adding data we aren't even looking at
						// this will prevent the year view from taking way longer than it needs to
						if ($end_range_time_tmp >= $start_date_time && $start_range_time_tmp <= $end_date_time) {
						
							// if the beginning of our range is less than the start of the item, we may as well set it equal to it
							if ($start_range_time_tmp < $start_date_time) $start_range_time_tmp = $start_date_time;
							if ($end_range_time_tmp > $end_date_time) $end_range_time_tmp = $end_date_time;
				
							// initialze the time we will increment
							$next_range_time = $start_range_time_tmp;
							
							$count_to = 0;
							// start at the $start_range and go until we hit the end of our range.
							while (($next_range_time >= $start_range_time_tmp) && ($next_range_time <= $end_range_time_tmp) && ($count_to != $count)) {

								$func = $freq_type.'Compare';
								$diff = $func(date('Ymd',$next_range_time), $start_date);
								if ($diff < $count) {
									if ($diff % $number == 0) {
										$interval = $number;
										switch ($rrule_array['FREQ']) {
											case 'DAILY':
												$next_date_time = $next_range_time;
												$recur_data[] = $next_date_time;
												break;
											case 'WEEKLY':
												if (is_array($byday)) {
													// loop through the days on which this event happens
													foreach($byday as $day) {
														// use my fancy little function to get the date of each day
														$day = two2threeCharDays($day);														
														$next_date = dateOfWeek(date('Ymd', $next_range_time),$day);
														$next_date_time = strtotime2($next_date);
														$recur_data[] = $next_date_time;
													}
												}
												break;
											case 'MONTHLY':
												$next_range_time = strtotime2(date('Y-m-01', $next_range_time));
												// month has two cases, either $bymonthday or $byday
												if (is_array($bymonthday)) {
													// loop through the days on which this event happens
													foreach($bymonthday as $day) {
														$year = date('Y', $next_range_time);
														$month = date('m', $next_range_time);
														if (checkdate($month,$day,$year)) {
															$next_date_time = mktime(0,0,0,$month,$day,$year);
															$recur_data[] = $next_date_time;
														}
													}
												// our other case
												} else {
													// loop through the days on which this event happens
													foreach($byday as $day) {
														ereg ('([-\+]{0,1})([0-9]{1})([A-Z]{2})', $day, $byday_arr);
														$nth = $byday_arr[2]-1;
														$on_day = two2threeCharDays($byday_arr[3]);
														$on_day_num = two2threeCharDays($byday_arr[3],false);
														if ($byday_arr[1] == '-') {
															$last_day_tmp = date('t',$next_range_time);
															$next_range_time = strtotime2(date('Y-m-'.$last_day_tmp, $next_range_time));
															$last_tmp = (date('w',$next_range_time) == $on_day_num) ? '' : 'last ';
															$next_date_time = strtotime2($last_tmp.$on_day.' -'.$nth.' week', $next_range_time);
														} else {
															$next_date_time = strtotime2($on_day.' +'.$nth.' week', $next_range_time);
														}
														$next_date = date('Ymd', $next_date_time);
														$recur_data[] = $next_date_time;
													}
												}
												break;
											case 'YEARLY':
												if (!isset($bymonth)) $bymonth[] = date('m', $start_date_time);
												foreach($bymonth as $month) {
													$year = date('Y', $next_range_time);
													if (is_array($byday)) {
														$checkdate_time = mktime(0,0,0,$month,1,$year);
														foreach($byday as $day) {
															ereg ('([-\+]{0,1})([0-9]{1})([A-Z]{2})', $day, $byday_arr);
															$nth = $byday_arr[2]-1;
															$on_day = two2threeCharDays($byday_arr[3]);
															if ($byday_arr[1] == '-') {
																$last_day_tmp = date('t',$checkdate_time);
																$checkdate_time = strtotime2(date('Y-m-'.$last_day_tmp, $checkdate_time));
																$last_tmp = (date('w',$checkdate_time) == $on_day_num) ? '' : 'last ';
																$next_date_time = strtotime2($last_tmp.$on_day.' -'.$nth.' week', $checkdate_time);
															} else {															
																$next_date_time = strtotime2($on_day.' +'.$nth.' week', $checkdate_time);
															}
														}
													} else {
														$day = date('d', $start_date_time);
														$next_date_time = mktime(0,0,0,$month,$day,$year);
													}
													$recur_data[] = $next_date_time;
												}
												break;
											default:
												// anything else we need to end the loop
												$next_range_time = $end_range_time_tmp + 100;
												$count_to = $count;
										}
									} else {
										$interval = 1;
									}
									$next_range_time = strtotime2('+'.$interval.' '.$freq_type, $next_range_time);
								} else {
									// end the loop because we aren't going to write this event anyway
									$count_to = $count;
								}
								// use the same code to write the data instead of always changing it 5 times						
								if (isset($recur_data) && is_array($recur_data)) {
									$recur_data_hour = substr($start_time,0,2);
									$recur_data_minute = substr($start_time,2,2);
									foreach($recur_data as $recur_data_time) {
										$recur_data_year = date('Y', $recur_data_time);
										$recur_data_month = date('m', $recur_data_time);
										$recur_data_day = date('d', $recur_data_time);
										$recur_data_date = $recur_data_year.$recur_data_month.$recur_data_day;
										
										if (($recur_data_time > $start_date_time) && ($recur_data_time <= $end_date_time) && ($count_to != $count) && !in_array($recur_data_date, $except_dates)) {
											if (isset($allday_start) && $allday_start != '') {
												$start_time2 = $recur_data_time;
												$end_time2 = strtotime2('+'.$diff_allday_days.' days', $recur_data_time);
												while ($start_time2 < $end_time2) {
													$start_date2 = date('Ymd', $start_time2);
													$master_array[($start_date2)][('-1')][$uid]= array ('@' => "");
													$start_time2 = strtotime2('+1 day', $start_time2);
												}
											} else {
												$start_unixtime_tmp = mktime($recur_data_hour,$recur_data_minute,0,$recur_data_month,$recur_data_day,$recur_data_year);
												$end_unixtime_tmp = $start_unixtime_tmp + $length;
												
												if ($spans_day) {
													$start_tmp = strtotime2(date('Ymd',$start_unixtime_tmp));
													$end_date_tmp = date('Ymd',$end_unixtime_tmp);
													while ($start_tmp < $end_unixtime_tmp) {
														$start_date_tmp = date('Ymd',$start_tmp);
														if ($start_date_tmp == $start_date) {
															$time_tmp = $hour.$minute;
															$start_time_tmp = $start_time;
														} else {
															$time_tmp = '0000';
															$start_time_tmp = '0000';
														}
														if ($start_date_tmp == $end_date_tmp) {
															$end_time_tmp = $end_time;
														} else {
															$end_time_tmp = '2400';
														}
														$nbrOfOverlaps = checkOverlap($start_date_tmp, $start_time_tmp, $end_time_tmp, $uid);
														$master_array[$start_date_tmp][$time_tmp][$uid] = array ('event_start' => $start_time_tmp, 'event_end' => $end_time_tmp, 'start_unixtime' => $start_unixtime_tmp, 'end_unixtime' => $end_unixtime_tmp, 'event_length' => $length, 'event_overlap' => $nbrOfOverlaps, 'status' => $status, 'spans_day' => true);
														$start_tmp = strtotime2('+1 day',$start_tmp);
													}
												} else {
													$nbrOfOverlaps = checkOverlap($recur_data_date, $start_time, $end_time, $uid);
													$master_array[($recur_data_date)][($hour.$minute)][$uid] = array ('event_start' => $start_time, 'event_end' => $end_time, 'start_unixtime' => $start_unixtime_tmp, 'end_unixtime' => $end_unixtime_tmp, 'event_length' => $length, 'event_overlap' => $nbrOfOverlaps, 'status' => $status, 'spans_day' => false);
												}
											}
										}
									}
									unset($recur_data);
								}
							}
						}
					}	
				}
			}
		
	}
	
  }
}
		


//print '<pre>';	
	// Remove pesky recurrences
	if (isset($recurrence_delete) and is_array($recurrence_delete)) {
		foreach ($recurrence_delete as $delete => $delete_key) {
			foreach ($delete_key as $key => $val) {
				#echo "Before Delete::  $delete  $key  $val<br>";
				#print_r($master_array["$delete"]);
				if (is_array($master_array[($delete)][($key)][($val)])) {
					removeOverlap($delete, $key, $val);
					unset($master_array["$delete"]["$key"]["$val"]);
					// Remove date from array if no events
					if (sizeof($master_array["$delete"]["$key"] = 1)) {
						#echo "deleting  $delete  $key  $val<br>";
						unset($master_array["$delete"]["$key"]);
						if (!sizeof($master_array["$delete"] > 1)) {
							#echo "deleting  $delete  $key  $val<br>";
							unset($master_array["$delete"]);
						}
					}
					#print_r($master_array["$delete"]);
					// Check for overlaps and rewrite them
					foreach($master_array["$delete"] as $overlap_time => $overlap_val) {
						$recur_data_date = $delete;
						foreach ($overlap_val as $uid => $val) {
							$start_time = $val['event_start'];
							$end_time = $val['event_end'];
							#$nbrOfOverlaps = checkOverlap($recur_data_date, $start_time, $end_time, $uid);
							#$master_array[($recur_data_date)][($start_time)][($uid)]['event_overlap'] = 0;
							#echo "$recur_data_date - $uid - $start_time - $end_time - $nbrOfOverlaps<br>";
							#print_r($val);
						}
					}
				}
			}
		}
	}	
	// Sort the array by absolute date.
	if (isset($master_array) && is_array($master_array)) { 
		ksort($master_array);
		reset($master_array);
		
		// sort the sub (day) arrays so the times are in order
		foreach (array_keys($master_array) as $k) {
			if (isset($master_array[$k]) && is_array($master_array[$k])) {
				ksort($master_array[$k]);
				reset($master_array[$k]);
			}
		}
	}
	

function replace_null_in_array(&$ano_array) {
  if (is_array($ano_array) and count($ano_array)!=0) {
    foreach ($ano_array as $key1=>$key2) {
      if ($key1 === "event_end" and $key2=="2400") { $ano_array[$key1]="2400"; }
      if (is_array($key2)) { replace_null_in_array($ano_array[$key1]); }
    }
  }
}

// replace_null_in_array($master_array);

if (isset($_GET["debug"]) and $_SESSION["MGW"]->username=="admin") show_print_r($all_cals);
if (isset($_GET["debug"]) and $_SESSION["MGW"]->username=="admin") show_print_r($master_array);

//print_r($overlap_array);
//print_r($day_array);
//print_r($rrule);
//print_r($recurrence_delete);	
	
?>
