<?php
/*
 * Copyright 2005 - 2009  Zarafa B.V.
 * 
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License, version 3, 
 * as published by the Free Software Foundation with the following additional 
 * term according to sec. 7:
 *  
 * According to sec. 7 of the GNU Affero General Public License, version
 * 3, the terms of the AGPL are supplemented with the following terms:
 * 
 * "Zarafa" is a registered trademark of Zarafa B.V. The licensing of
 * the Program under the AGPL does not imply a trademark license.
 * Therefore any rights, title and interest in our trademarks remain
 * entirely with us.
 * 
 * However, if you propagate an unmodified version of the Program you are
 * allowed to use the term "Zarafa" to indicate that you distribute the
 * Program. Furthermore you may use our trademarks where it is necessary
 * to indicate the intended purpose of a product or service provided you
 * use it in accordance with honest practices in industrial or commercial
 * matters.  If you want to propagate modified versions of the Program
 * under the name "Zarafa" or "Zarafa Server", you may only do so if you
 * have a written permission by Zarafa B.V. (to acquire a permission
 * please contact Zarafa at trademark@zarafa.com).
 * 
 * The interactive user interface of the software displays an attribution
 * notice containing the term "Zarafa" and/or the logo of Zarafa.
 * Interactive user interfaces of unmodified and modified versions must
 * display Appropriate Legal Notices according to sec. 5 of the GNU
 * Affero General Public License, version 3, when you propagate
 * unmodified or modified versions of the Program. In accordance with
 * sec. 7 b) of the GNU Affero General Public License, version 3, these
 * Appropriate Legal Notices must retain the logo of Zarafa or display
 * the words "Initial Development by Zarafa" if the display of the logo
 * is not reasonably feasible for technical reasons. The use of the logo
 * of Zarafa in Legal Notices is allowed for unmodified and modified
 * versions of the software.
 * 
 * This program 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 Affero General Public License for more details.
 *  
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 * 
 */

?>
<?php
	/**
	 * Recurrence 
	 * @author Steve Hardy <steve@zarafa.com>
	 * @author Michel de Ron <michel@zarafa.com>
	 */
	class Recurrence
	{
		/*
		 * ABOUT TIMEZONES
		 *
		 * Timezones are rather complicated here so here are some rules to think about:
		 *
		 * - Timestamps in mapi-like properties (so in PT_SYSTIME properties) are always in GMT (including
		 *   the 'basedate' property in exceptions !!)
		 * - Timestamps for recurrence (so start/end of recurrence, and basedates for exceptions (everything
		 *   outside the 'basedate' property in the exception !!), and start/endtimes for exceptions) are 
		 *   always in LOCAL time. 
		 */
	
		/**
		 * @var object Mapi Message Store (may be null if readonly)
		 */
		var $store;
		
		/**
		 * @var object Mapi Message (may be null if readonly)
		 */
		var $message;
		
		/**
		 * @var array Message Properties
		 */
		var $messageprops;

		/**
		 * @var array list of property tags
		 */
		var $proptags;

		/**
		 * @var recurrence data of this calendar item
		 */
        var $recur;
        
		/**
		 * Constructor
		 * @param resource $store MAPI Message Store Object
		 * @param resource $message the MAPI (appointment) message
		 */
		function Recurrence($store, $message)
		{

			$properties = array();
	  		$properties["entryid"] = PR_ENTRYID;
	  		$properties["parent_entryid"] = PR_PARENT_ENTRYID;
	  		$properties["message_class"] = PR_MESSAGE_CLASS;
	  		$properties["icon_index"] = PR_ICON_INDEX;
	  		$properties["subject"] = PR_SUBJECT;
	  		$properties["display_to"] = PR_DISPLAY_TO;
	  		$properties["importance"] = PR_IMPORTANCE;
	  		$properties["sensitivity"] = PR_SENSITIVITY;
			$properties["startdate"] = "PT_SYSTIME:PSETID_Appointment:0x820d";
			$properties["duedate"] = "PT_SYSTIME:PSETID_Appointment:0x820e";
			$properties["recurring"] = "PT_BOOLEAN:PSETID_Appointment:0x8223";
			$properties["recurring_data"] = "PT_BINARY:PSETID_Appointment:0x8216";
			$properties["busystatus"] = "PT_LONG:PSETID_Appointment:0x8205";
			$properties["label"] = "PT_LONG:PSETID_Appointment:0x8214";
			$properties["alldayevent"] = "PT_BOOLEAN:PSETID_Appointment:0x8215";
			$properties["private"] = "PT_BOOLEAN:PSETID_Common:0x8506";
			$properties["meeting"] = "PT_LONG:PSETID_Appointment:0x8217";
			$properties["startdate_recurring"] = "PT_SYSTIME:PSETID_Appointment:0x8235";
			$properties["enddate_recurring"] = "PT_SYSTIME:PSETID_Appointment:0x8236";
			$properties["location"] = "PT_STRING8:PSETID_Appointment:0x8208";
			$properties["duration"] = "PT_LONG:PSETID_Appointment:0x8213";
			$properties["responsestatus"] = "PT_LONG:PSETID_Appointment:0x8218";
			$properties["reminder"] = "PT_BOOLEAN:PSETID_Common:0x8503";
			$properties["reminder_minutes"] = "PT_LONG:PSETID_Common:0x8501";
			$properties["recurrencetype"] = "PT_LONG:PSETID_Appointment:0x8231";
			$properties["contacts"] = "PT_MV_STRING8:PSETID_Common:0x853a";
			$properties["contacts_string"] = "PT_STRING8:PSETID_Common:0x8586";
			$properties["categories"] = "PT_MV_STRING8:PS_PUBLIC_STRINGS:Keywords";
			$properties["reminder_time"] = "PT_SYSTIME:PSETID_Common:0x8502";
			$properties["commonstart"] = "PT_SYSTIME:PSETID_Common:0x8516";
			$properties["commonend"] = "PT_SYSTIME:PSETID_Common:0x8517";
			$properties["basedate"] = "PT_SYSTIME:PSETID_Appointment:0x8228";
			$properties["timezone_data"] = "PT_BINARY:PSETID_Appointment:0x8233";
			$properties["timezone"] = "PT_STRING8:PSETID_Appointment:0x8234";
			$properties["start"] = "PT_SYSTIME:PSETID_Appointment:0x820d";
			$properties["end"] = "PT_SYSTIME:PSETID_Appointment:0x820e";
			$properties["flagdueby"] = "PT_SYSTIME:PSETID_Common:0x8560";
			$properties["prop8510"] = "PT_LONG:PSETID_Common:0x8510";
			$properties["hideattachments"] = "PT_BOOLEAN:PSETID_Common:0x8514";

			$this->proptags = getPropIdsFromStrings($store, $properties);


			$this->store = $store;
			
			$this->tz = array();
			
			if(is_array($message)) {
				$this->messageprops = $message;
			} else {		
				$this->message = $message;
				$this->messageprops = mapi_getprops($this->message, $this->proptags);
			}

			if(isset($this->messageprops[$this->proptags["recurring_data"]]))
				$this->recur = $this->parseRecurrence($this->messageprops[$this->proptags["recurring_data"]]);
			if(isset($this->messageprops[$this->proptags["timezone_data"]]))
				$this->tz = $this->parseTimezone($this->messageprops[$this->proptags["timezone_data"]]);
		}

		/**
		 * Function which returns the items in a given interval.
		 * @param string $entryid the entryid of the message
		 * @param array $props the properties of the message
		 * @param date $start start time of the interval (GMT)
		 * @param date $end end time of the interval (GMT)		 
		 */		 		
		function getItems($start, $end, $limit = 0, $remindersonly = false)
		{
			$items = array();
			
			if(isset($this->recur)) {
				
				// Optimization: remindersonly and default reminder is off; since only exceptions with reminder set will match, just look which
				// exceptions are in range and have a reminder set
				if($remindersonly && (!isset($this->messageprops[$this->proptags["reminder"]]) || $this->messageprops[$this->proptags["reminder"]] == false)) {
				    // Sort exceptions by start time
				    uasort($this->recur["changed_occurences"], array($this, "sortExceptionStart"));
				    
				    // Loop through all changed exceptions
				    foreach($this->recur["changed_occurences"] as $exception) {
				        // Check reminder set
                        if(!isset($exception["reminder"]) || $exception["reminder"] == false)
                            continue;
                            
                        // Convert to GMT
                        $occstart = $this->toGMT($tz, $exception["start"]);
                        $occend = $this->toGMT($tz, $exception["end"]);

                        // Check range criterium
                        if($occstart > $end || $occend < $start)
                            continue;
                            
                        // OK, add to items.
                        array_push($items, $this->getExceptionProperties($exception));
                        if($limit && (count($items) == $limit))
                            break;
                            
				    }
				    
				    uasort($items, array($this, "sortStarttime"));
				    
				    return $items;
				}
				
				// From here on, the dates of the occurrences are calculated in local time, so the days we're looking
				// at are calculated from the local time dates of $start and $end

				$daystart = $this->dayStartOf($this->recur["start"]); // start on first day of occurrence

                // Calculate the last day on which we want to be looking at a recurrence; this is either the end of the view
                // or the end of the recurrence, whichever comes first
				if($end > $this->toGMT($this->tz, $this->recur["end"])) {
				    $rangeend = $this->toGMT($this->tz, $this->recur["end"]);
                } else {
                    $rangeend = $end;
                }
                
                $dayend = $this->dayStartOf($this->fromGMT($this->tz, $rangeend));
                
				// Loop through the entire recurrence range of dates, and check for each occurrence whether it is in the view range.
				
				switch($this->recur["type"])
				{
                case 10:
                    // Daily
                    if($this->recur["everyn"] <= 0)
                        $this->recur["everyn"] = 1440;
                        
                    if($this->recur["subtype"] == 0) {
                        // Every Nth day
                        for($now = $daystart; $now <= $dayend && ($limit == 0 || count($items) < $limit); $now += 60 * $this->recur["everyn"]) {
                            $this->processOccurrenceItem($items, $start, $end, $now, $this->recur["startocc"], $this->recur["endocc"], $this->tz, $remindersonly);
                        } 
                    } else {
                        // Every workday
                        for($now = $daystart; $now <= $dayend && ($limit == 0 || count($items) < $limit); $now += 60 * 1440)
                        {
                            $nowtime = $this->gmtime($now);
                            if ($nowtime["tm_wday"] > 0 && $nowtime["tm_wday"] < 6) { // only add items in the given timespace
                                $this->processOccurrenceItem($items, $start, $end, $now, $this->recur["startocc"], $this->recur["endocc"], $this->tz, $remindersonly);
                            }
                        } 
                    } 
                    break;
                case 11:
                    // Weekly
                    if($this->recur["everyn"] <= 0)
                        $this->recur["everyn"] = 1;
                       
                    for($now = $daystart; $now <= $dayend && ($limit == 0 || count($items) < $limit); $now += 60 * 60 * 24 * 7 * $this->recur["everyn"])
                    { 
                        // Loop through the whole following week to the first occurrence of the week, add each day that is specified
                        for($wday = 0; $wday < 7; $wday++)
                        {
                            $daynow = $now + $wday * 60 * 60 * 24;
                            //checks weather the next coming day in recurring pattern is less than or equal to end day of the recurring item
                            if ($daynow <= $dayend){
                          		$nowtime = $this->gmtime($daynow); // Get the weekday of the current day
	                            
	                            if(($this->recur["weekdays"] &(1 << $nowtime["tm_wday"]))) { // Selected ?
	                                $this->processOccurrenceItem($items, $start, $end, $daynow, $this->recur["startocc"], $this->recur["endocc"], $this->tz, $remindersonly);
	                            }
                            }    
                        } 
                    } 
                    break;
                case 12:
                	// Monthly
                    if($this->recur["everyn"] <= 0)
                        $this->recur["everyn"] = 1;
                        
                    // Loop through all months from start to end of occurrence, starting at beginning of first month
                    for($now = $this->monthStartOf($daystart); $now <= $dayend && ($limit == 0 || count($items) < $limit); $now += $this->daysInMonth($now, $this->recur["everyn"]) * 24 * 60 * 60 )
                    { 
                        if(isset($this->recur["monthday"])) { // Day M of every N months
                            $difference = 1;
                        	if ($this->daysInMonth($now, $this->recur["everyn"]) < $this->recur["monthday"]) {
                        		$difference = $this->recur["monthday"] - $this->daysInMonth($now, $this->recur["everyn"]) + 1;
                        	}
                        	$daynow = $now + (($this->recur["monthday"] - $difference) * 24 * 60 * 60);
                            //checks weather the next coming day in recurrence pattern is less than or equal to end day of the recurring item 
                        	if ($daynow <= $dayend){
                        		$this->processOccurrenceItem($items, $start, $end, $daynow, $this->recur["startocc"], $this->recur["endocc"], $this->tz, $remindersonly);
                             }
                        }
                        else if(isset($this->recur["nday"]) && isset($this->recur["weekdays"])) { // Nth [weekday] of every N months
							// If nday is not set to the last day in the month
							if ($this->recur["nday"] < 5) {
								// Find first matching weekday in this month
								for($wday = 0; $wday < 7; $wday++)
								{
									$daynow = $now + $wday * 60 * 60 * 24;
									$nowtime = $this->gmtime($daynow); // Get the weekday of the current day
									
									if($this->recur["weekdays"] & (1 << $nowtime["tm_wday"])) { // Selected ?
										$firstday = $wday;
										break;
									}
								}
								// $firstday is the first of all the selected weekdays in the month, so add [nday] weeks
								$daynow = $now + ($firstday + ($this->recur["nday"]-1)*7) * 60 * 60 * 24;
							}else{
								// Find last day in the month ($now is the firstday of the month)
								$NumDaysInMonth =  $this->daysInMonth($now, 1);
								$daynow = $now + (($NumDaysInMonth-1) * 24*60*60);

								$nowtime = $this->gmtime($daynow);
								while (($this->recur["weekdays"] & (1 << $nowtime["tm_wday"]))==0){
									$daynow -= 86400;
									$nowtime = $this->gmtime($daynow);
								}
							}

							//checks weather the next coming day in recurrence pattern is less than or equal to end day of the recurring item 
							if ($daynow <= $dayend){
                            	$this->processOccurrenceItem($items, $start, $end, $daynow, $this->recur["startocc"], $this->recur["endocc"], $this->tz , $remindersonly);
							}
						}
                    } 
                    break;
                case 13:
                	// Yearly
                    if($this->recur["everyn"] <= 0)
                        $this->recur["everyn"] = 12;
                        
                	for($now = $this->yearStartOf($daystart); $now <= $dayend && ($limit == 0 || count($items) < $limit); $now += $this->daysInMonth($now, $this->recur["everyn"]) * 24 * 60 * 60 )
                	{
                		if(isset($this->recur["monthday"])) { // same as monthly, but in a specific month
                			// recur["month"] is in minutes since the beginning of the year
                			$month = $this->monthOfYear($this->recur["month"]); // $month is now month of year [0..11]
                			$monthday = $this->recur["monthday"]; // $monthday is day of the month [1..31]
                			$monthstart = $now + $this->daysInMonth($now, $month) * 24 * 60 * 60; // $monthstart is the timestamp of the beginning of the month
                			if($monthday > $this->daysInMonth($monthstart, 1))
                			    $monthday = $this->daysInMonth($monthstart, 1);	// Cap $monthday on month length (eg 28 feb instead of 29 feb)
                			$daynow = $monthstart + ($monthday-1) * 24 * 60 * 60;
							$this->processOccurrenceItem($items, $start, $end, $daynow, $this->recur["startocc"], $this->recur["endocc"], $this->tz, $remindersonly);
	                    }
	                    else if(isset($this->recur["nday"]) && isset($this->recur["weekdays"])) { // Nth [weekday] in month X of every N years
	                    
							// Go the correct month
							$monthnow = $now + $this->daysInMonth($now, $this->monthOfYear($this->recur["month"])) * 24 * 60 * 60;
							
							// Find first matching weekday in this month
							for($wday = 0; $wday < 7; $wday++)
							{
								$daynow = $monthnow + $wday * 60 * 60 * 24;
								$nowtime = $this->gmtime($daynow); // Get the weekday of the current day
								
								if($this->recur["weekdays"] & (1 << $nowtime["tm_wday"])) { // Selected ?
									$firstday = $wday;
									break;
								}
							}

							// Same as above (monthly)
							$daynow = $monthnow + ($firstday + ($this->recur["nday"]-1)*7) * 60 * 60 * 24;
							
							while($this->monthStartOf($daynow) != $this->monthStartOf($monthnow)) {
								$daynow -= 7 * 60 * 60 * 24;
							}

							$this->processOccurrenceItem($items, $start, $end, $daynow, $this->recur["startocc"], $this->recur["endocc"], $this->tz, $remindersonly);
						}
                	}
				}
				//to get all exception items	
				$this->processExceptionItems($items, $start, $end);
			}
			
			// sort items on starttime
			uasort($items, array($this, "sortStarttime"));
			
            // Return the MAPI-compatible list of items for this object
			return $items;
		}

		/**
		 * Create an exception
		 * @param array $exception_props the exception properties (same properties as normal recurring items)
		 * @param date $base_date the base date of the exception (LOCAL time of non-exception occurrence)
		 * @param boolean $delete true - delete occurrence, false - create new exception or modify existing
		 */
		function createException($exception_props, $base_date, $delete = false, $exception_recips = array())
		{
			$baseday = $this->dayStartOf($base_date);
			$basetime = $baseday + $this->recur["startocc"] * 60;
			
            // Remove any pre-existing exception on this base date
            if($this->isException($baseday)) {
                $this->deleteException($baseday); // note that deleting an exception is different from creating a deleted exception (deleting an occurrence).
            }
			if(!$delete) {

                if(!$this->isValidExceptionDate($base_date, $this->fromGMT($this->tz, $exception_props[$this->proptags["startdate"]]))) {
                    return false;
                }
				// Properties in the attachment are the properties of the base object, plus $exception_props plus the base date
				foreach (array("subject", "location", "label", "reminder", "reminder_minutes", "alldayevent", "busystatus") as $propname) {
					if(isset($this->messageprops[$this->proptags[$propname]]))
						$props[$this->proptags[$propname]] = $this->messageprops[$this->proptags[$propname]];
				}
				
				$props[PR_MESSAGE_CLASS] = "IPM.OLE.CLASS.{00061055-0000-0000-C000-000000000046}";
				unset($exception_props[PR_MESSAGE_CLASS]);
				unset($exception_props[PR_ICON_INDEX]);
				$props = $exception_props + $props;
				
				// Basedate in the exception attachment is the GMT time at which the original occurrence would have been
				$props[$this->proptags["basedate"]] = $this->toGMT($this->tz, $basetime);

				// Save the data into an attachment
				$this->createExceptionAttachment($props, $exception_recips);
				
                $changed_item = array();
                
                $startdate = $this->gmtime($exception_props[$this->proptags["startdate"]]);
                $enddate = $this->gmtime($exception_props[$this->proptags["duedate"]]);
                
                $changed_item["basedate"] = $baseday;
                $changed_item["start"] = $this->fromGMT($this->tz, $exception_props[$this->proptags["startdate"]]);
                $changed_item["end"] =   $this->fromGMT($this->tz, $exception_props[$this->proptags["duedate"]]);

                if(array_key_exists($this->proptags["subject"], $exception_props)) {
                    $changed_item["subject"] = $exception_props[$this->proptags["subject"]];
                }
                
                if(array_key_exists($this->proptags["location"], $exception_props)) {
                    $changed_item["location"] = $exception_props[$this->proptags["location"]];
                }	
                
                if(array_key_exists($this->proptags["label"], $exception_props)) {
                    $changed_item["label"] = $exception_props[$this->proptags["label"]];
                }
                
                if(array_key_exists($this->proptags["reminder"], $exception_props)) {
                    $changed_item["reminder_set"] = $exception_props[$this->proptags["reminder"]];
                }
                
                if(array_key_exists($this->proptags["alldayevent"], $exception_props)) {
                    $changed_item["alldayevent"] = $exception_props[$this->proptags["alldayevent"]];
                }

                if(array_key_exists($this->proptags["busystatus"], $exception_props)) {
                    $changed_item["busystatus"] = $exception_props[$this->proptags["busystatus"]];
                }

                // Add the changed occurrence to the list
                array_push($this->recur["changed_occurences"], $changed_item);
			} else { 
			    // Delete the occurrence by placing it in the deleted occurrences list
			    array_push($this->recur["deleted_occurences"], $baseday);
			}
			
			// Turn on hideattachments, because the attachments in this item are the exceptions
			mapi_setprops($this->message, array ( $this->proptags["hideattachments"] => true ));

			// Save recurrence data to message			
			$this->saveRecurrence();
			
			return true;
		}
		
		/**
		 * Modifies an existing exception, but only updates the given properties
		 * NOTE: You can't remove properites from an exception, only add new ones
		 */
		function modifyException($exception_props, $base_date, $exception_recips = array())
		{
		    if(!$this->isValidExceptionDate($base_date, $this->fromGMT($this->tz, $exception_props[$this->proptags["startdate"]]))) {
		        return false;
            }
		        
			$baseday = $this->dayStartOf($base_date);
			$basetime = $baseday + $this->recur["startocc"] * 60;
			$extomodify = false;

			for($i=0;$i<count($this->recur["changed_occurences"]);$i++) {			
		    	if($this->isSameDay($this->recur["changed_occurences"][$i]["basedate"], $baseday))
		    		$extomodify = &$this->recur["changed_occurences"][$i];
		    }
			
			if(!$extomodify)
				return false;

			$startdate = $this->gmtime($exception_props[$this->proptags["startdate"]]);
			$enddate = $this->gmtime($exception_props[$this->proptags["duedate"]]);

			// remove basedate property as we want to preserver the old value
			// client will send basedate with time part as zero, so discard that value
			unset($exception_props[$this->proptags["basedate"]]);

			if(array_key_exists($this->proptags["startdate"], $exception_props)) {
				$extomodify["start"] = $this->fromGMT($this->tz, $exception_props[$this->proptags["startdate"]]);
			}
			
			if(array_key_exists($this->proptags["duedate"], $exception_props)) {
				$extomodify["end"] =   $this->fromGMT($this->tz, $exception_props[$this->proptags["duedate"]]);
			}

			if(array_key_exists($this->proptags["subject"], $exception_props)) {
				$extomodify["subject"] = $exception_props[$this->proptags["subject"]];
			}
			
			if(array_key_exists($this->proptags["location"], $exception_props)) {
				$extomodify["location"] = $exception_props[$this->proptags["location"]];
			}	
			
			if(array_key_exists($this->proptags["label"], $exception_props)) {
				$extomodify["label"] = $exception_props[$this->proptags["label"]];
			}
			
			if(array_key_exists($this->proptags["reminder"], $exception_props)) {
				$extomodify["reminder_set"] = $exception_props[$this->proptags["reminder"]];
			}
			
			if(array_key_exists($this->proptags["alldayevent"], $exception_props)) {
				$extomodify["alldayevent"] = $exception_props[$this->proptags["alldayevent"]];
			}

			if(array_key_exists($this->proptags["busystatus"], $exception_props)) {
				$extomodify["busystatus"] = $exception_props[$this->proptags["busystatus"]];
			}

			$exception_props[PR_MESSAGE_CLASS] = "IPM.OLE.CLASS.{00061055-0000-0000-C000-000000000046}";

			$attach = $this->getExceptionAttachment($baseday);
			if(!$attach) {
				$this->createExceptionAttachment($exception_props, $exception_recips);
			} else {
				$message = mapi_attach_openobj($attach, MAPI_MODIFY);

				$this->setExceptionRecipients($message, $exception_recips);

				mapi_setprops($message, $exception_props);
				
				mapi_savechanges($message);
				mapi_savechanges($attach);
			}

			// Save recurrence data to message			
			$this->saveRecurrence();

			return true;
		}
		
		// Checks to see if the following is true:
		// 1) The exception to be created doesn't create two exceptions starting on one day (however, they can END on the same day by modifying duration)
		// 2) The exception to be created doesn't 'jump' over another occurrence (which may be an exception itself!)
		//
		// Both $basedate and $start are in LOCAL time
		function isValidExceptionDate($basedate, $start)
		{
		    // The way we do this is to look at the days that we're 'moving' the item in the exception. Each
		    // of these days may only contain the item that we're modifying. Any other item violates the rules.
		    
		    if($this->isException($basedate)) {
		        // If we're modifying an exception, we want to look at the days that we're 'moving' compared to where
		        // the exception used to be.
		        $oldexception = $this->getChangeException($basedate);
		        $prevday = $this->dayStartOf($oldexception["start"]);
		    } else {
		        // If its a new exception, we want to look at the original placement of this item.
		        $prevday = $basedate;
		    }
		    
		    $startday = $this->dayStartOf($start);
		    
		    // Get all the occurrences on the days between the basedate (may be reversed)
		    if($prevday < $startday)
		        $items = $this->getItems($this->toGMT($this->tz, $prevday), $this->toGMT($this->tz, $startday + 24 * 60 * 60));
            else 
		        $items = $this->getItems($this->toGMT($this->tz, $startday), $this->toGMT($this->tz, $prevday + 24 * 60 * 60));
		        
            // There should now be exactly one item, namely the item that we are modifying. If there are any other items in the range,
            // then we abort the change, since one of the rules has been violated.
            return count($items) == 1;
		}
		
		function getRecurrence()
		{
			return $this->recur;
		}
		
		function setRecurrence($tz, $recur) 
		{
			// only reset timezone if specified
			if($tz)
				$this->tz = $tz;
				
			$this->recur = $recur;
			
			if(!isset($this->recur["changed_occurences"]))
				$this->recur["changed_occurences"] = Array();
			
			if(!isset($this->recur["deleted_occurences"]))
				$this->recur["deleted_occurences"] = Array();
			
			$this->deleteAttachments();
			$this->saveRecurrence();
		}
		
		// Returns the start or end time of the occurrence on the given base date.
		// This assumes that the basedate you supply is in LOCAL time
		function getOccurrenceStart($basedate)  {
			$daystart = $this->dayStartOf($basedate);
			return $this->toGMT($this->tz, $daystart + $this->recur["startocc"] * 60);
		}
		
		function getOccurrenceEnd($basedate)  {
			$daystart = $this->dayStartOf($basedate);
			return $this->toGMT($this->tz, $daystart + $this->recur["endocc"] * 60);
		}
		

		// Backwards compatible code
		function getOccurenceStart($basedate)  {
			return $this->getOccurrenceStart($basedate);
		}
		function getOccurenceEnd($basedate)  {
			return $this->getOccurrenceEnd($basedate);
		}

		/**
		* This function returns the next remindertime starting from $timestamp
		* When no next reminder exists, false is returned.
		*
		* Note: Before saving this new reminder time (when snoozing), you must check for 
		*       yourself if this reminder time is earlier than your snooze time, else 
		*       use your snooze time and not this reminder time.
		*/
		function getNextReminderTime($timestamp)
		{
			/**
		     * Get next item from now until forever, but max 1 item with reminder set
		     * Note 0x7ff00000 instead of 0x7fffffff because of possible overflow failures when converting to GMT....
			 * Here for getting next 10 occurences assuming that next here we will be able to find 
			 * nextreminder occurence in 10 occureneces
			 */
			$items = $this->getItems($timestamp, 0x7ff00000, 10, true); 

			// Initially setting nextreminder to false so when no next reminder exists, false is returned.
			$nextreminder = false;
			/**
			 * Loop through all reminder which we get in items variable 
			 * and check whether the remindertime is greater than timestamp.
			 * On the first occurence of greater nextreminder break the loop
			 * and return the value to calling function.
			 */
			for($i=0; $i<count($items) ;$i++)
			{
				$item = $items[$i];
				$tempnextreminder = $item[$this->proptags["startdate"]] - ( $item[$this->proptags["reminder_minutes"]] * 60 );
				
				// If tempnextreminder is greater than timestamp then save it in nextreminder and break from the loop.
				if($tempnextreminder > $timestamp)
				{
					$nextreminder = $tempnextreminder;
					break;
				}
			}
			return $nextreminder;
		}
		
		/**
		 * Note: Static function, more like a utility function.
		 *
		 * Gets all the items (including recurring items) in the specified calendar in the given timeframe. Items are
		 * included as a whole if they overlap the interval <$start, $end> (non-inclusive). This means that if the interval
		 * is <08:00 - 14:00>, the item [6:00 - 8:00> is NOT included, nor is the item [14:00 - 16:00>. However, the item
		 * [7:00 - 9:00> is included as a whole, and is NOT capped to [8:00 - 9:00>.
		 *
		 * @param $store resource The store in which the calendar resides
		 * @param $calendar resource The calendar to get the items from
		 * @param $viewstart int Timestamp of beginning of view window
		 * @param $viewend int Timestamp of end of view window
		 * @param $propsrequested array Array of properties to return
		 * @param $rows array Array of rowdata as if they were returned directly from mapi_table_queryrows. Each recurring item is
		 *                    expanded so that it seems that there are only many single appointments in the table.
		 */
		function getCalendarItems($store, $calendar, $viewstart, $viewend, $propsrequested)
		{
		    $result = array();
            $properties = getPropIdsFromStrings($store, Array( "duedate" => "PT_SYSTIME:PSETID_Appointment:0x820e",
                                                       "startdate" =>  "PT_SYSTIME:PSETID_Appointment:0x820d",
                                                       "enddate_recurring" => "PT_SYSTIME:PSETID_Appointment:0x8236",
                                                       "recurring" => "PT_BOOLEAN:PSETID_Appointment:0x8223",
                                                       "recurring_data" => "PT_BINARY:PSETID_Appointment:0x8216",
                                                       "timezone_data" => "PT_BINARY:PSETID_Appointment:0x8233",
                                                       "label" => "PT_LONG:PSETID_Appointment:0x8214"
                                                        ));
                                                        
            // Create a restriction that will discard rows of appointments that are definitely not in our
            // requested time frame
		    
		    $table = mapi_folder_getcontentstable($calendar);
		    
            $restriction = 
                // OR
                Array(RES_OR,
                         Array(
                               Array(RES_AND,	// Normal items: itemEnd must be after viewStart, itemStart must be before viewEnd
                                     Array(
                                           Array(RES_PROPERTY,
                                                 Array(RELOP => RELOP_GT,
                                                       ULPROPTAG => $properties["duedate"],
                                                       VALUE => $viewstart
                                                       )
                                                 ),
                                           Array(RES_PROPERTY,
                                                 Array(RELOP => RELOP_LT,
                                                       ULPROPTAG => $properties["startdate"],
                                                       VALUE => $viewend
                                                       )
                                                 )
                                           )
                                     ),
                               // OR
                               Array(RES_PROPERTY,
                                     Array(RELOP => RELOP_EQ,
                                           ULPROPTAG => $properties["recurring"],
                                           VALUE => true
                                           )
                                     )
                               ) // EXISTS OR
                         );		// global OR

            // Get requested properties, plus whatever we need		    
            $proplist = array($properties["recurring"], $properties["recurring_data"], $properties["timezone_data"]);
            $proplist = array_merge($proplist, $propsrequested);
            $propslist = array_unique($proplist);
		    
            $rows = mapi_table_queryallrows($table, $proplist, $restriction);
            
            // $rows now contains all the items that MAY be in the window; a recurring item needs expansion before including in the output.
            
            foreach($rows as $row) {
                $items = array();
                
                if(isset($row[$properties["recurring"]]) && $row[$properties["recurring"]]) {
                    // Recurring item
                    $rec = new Recurrence($store, $row);

                    // GetItems guarantees that the item overlaps the interval <$viewstart, $viewend>                    
                    $occurrences = $rec->getItems($viewstart, $viewend);
                    
                    foreach($occurrences as $occurrence) {
                        // The occurrence takes all properties from the main row, but overrides some properties (like start and end obviously)
                        $item = $row;
                        array_merge($item, $occurrence);
                        array_push($items, $item);
                    }
                    
                } else {
                    // Normal item, it matched the search criteria and therefore overlaps the interval <$viewstart, $viewend>
                    array_push($items, $row);
                }
                
                $result = array_merge($result,$items);
            }
            
            // All items are guaranteed to overlap the interval <$viewstart, $viewend>. Note that we may be returning a few extra
            // properties that the caller did not request (recurring, etc). This shouldn't be a problem though.
            return $result;
		}


		/*****************************************************************************************************************
		 * CODE BELOW THIS LINE IS FOR INTERNAL USE ONLY
		 *****************************************************************************************************************
		 */
		 
		/*
		 * Remove an exception by base_date. This is the base date in local daystart time
		 */
		function deleteException($base_date)
		{
		    // Remove all exceptions on $base_date from the deleted and changed occurrences lists

		    // Remove all items in $todelete from deleted_occurences
		    $new = Array();
		    
		    foreach($this->recur["deleted_occurences"] as $entry) {
		    	if($entry != $base_date)
		    		$new[] = $entry;
		    }
		    $this->recur["deleted_occurences"] = $new;
		    
		    $new = Array();
		    
		    foreach($this->recur["changed_occurences"] as $entry) {
		    	if(!$this->isSameDay($entry["basedate"], $base_date))
		    		$new[] = $entry;
		    	else
		    		$this->deleteExceptionAttachment($this->toGMT($this->tz, $base_date + $this->recur["startocc"] * 60));
		    }
		    
		    $this->recur["changed_occurences"] = $new;
		}
		
		/**
		 * Function which saves the exception data in an attachment.
		 * @param array $exception_props the exception data (like any other MAPI appointment)
		 * @param array $exception_recips list of recipients
		 * @return array properties of the exception		 		  		 
		 */		 		
		function createExceptionAttachment($exception_props, $exception_recips = array())
		{
		  	//Create new attachment.
		  	$attachment = mapi_message_createattach($this->message);
		  	$props = array();
		  	$props[PR_ATTACHMENT_FLAGS] = 2;
		  	$props[PR_ATTACHMENT_HIDDEN] = true;
		  	$props[PR_ATTACHMENT_LINKID] = 0;
		  	$props[PR_ATTACH_FLAGS] = 0;
		  	$props[PR_ATTACH_METHOD] = 5;
		  	$props[PR_DISPLAY_NAME] = "Exception";
		  	$props[PR_EXCEPTION_STARTTIME] = $this->fromGMT($this->tz, $exception_props[$this->proptags["startdate"]]);
		  	$props[PR_EXCEPTION_ENDTIME] = $this->fromGMT($this->tz, $exception_props[$this->proptags["duedate"]]);	
		  	mapi_message_setprops($attachment, $props);
			
			$imessage = mapi_attach_openobj($attachment, MAPI_CREATE | MAPI_MODIFY);
		
			$props = $props + $exception_props;

			// FIXME: the following piece of code is written to fix the creation 
			// of an exception. This is only a quickfix as it is not yet possible
			// to change an existing exception.
			// remove mv properties when needed
			foreach($props as $propTag=>$propVal){
				if ((mapi_prop_type($propTag) & MV_FLAG) == MV_FLAG && is_null($propVal)){
					unset($props[$propTag]);
				}
			}

			$this->setExceptionRecipients($imessage, $exception_recips);
			mapi_message_setprops($imessage, $props);
			mapi_message_savechanges($imessage);
			mapi_message_savechanges($attachment);
		}
		
		/**
		 * Function which deletes the attachment of an exception.
		 * @param date $base_date base date of the attachment. Should be in GMT. The attachment
		 *                        actually saves the real time of the original date, so we have
		 *						  to check whether it's on the same day.
		 */		 		
		function deleteExceptionAttachment($base_date)
		{
			$attachments = mapi_message_getattachmenttable($this->message);
			$attachTable = mapi_table_queryallrows($attachments, Array(PR_ATTACH_NUM));
			
			foreach($attachTable as $attachRow)
			{
				$tempattach = mapi_message_openattach($this->message, $attachRow[PR_ATTACH_NUM]);
				$exception = mapi_attach_openobj($tempattach);
		
			  	$data = mapi_message_getprops($exception, array($this->proptags["basedate"]));
			  	
			  	if($this->dayStartOf($this->fromGMT($this->tz, $data[$this->proptags["basedate"]])) == $this->dayStartOf($base_date)) {
			  		mapi_message_deleteattach($this->message, $attachRow[PR_ATTACH_NUM]);
			  	}
			}
		}
		
		/**
		 * Function which deletes all attachments of a message.
		 */		 		
		function deleteAttachments()
		{
			$attachments = mapi_message_getattachmenttable($this->message);
			$attachTable = mapi_table_queryallrows($attachments, Array(PR_ATTACH_NUM, PR_ATTACHMENT_HIDDEN));
			
			foreach($attachTable as $attachRow)
			{
				if(isset($attachRow[PR_ATTACHMENT_HIDDEN]) && $attachRow[PR_ATTACHMENT_HIDDEN]) {
					mapi_message_deleteattach($this->message, $attachRow[PR_ATTACH_NUM]);
				}
			}
		}
		
		/**
		 * Get an exception attachment based on its basedate
		 */
		function getExceptionAttachment($base_date)
		{
			// Retrieve only embedded messages
			$attach_res = Array(RES_AND,
							Array(
								Array(RES_PROPERTY,
									Array(RELOP => RELOP_EQ,
										ULPROPTAG => PR_ATTACH_METHOD,
										VALUE => array(PR_ATTACH_METHOD => 5)
									)
								)
							)
			);
			$attachments = mapi_message_getattachmenttable($this->message);
			$attachTable = mapi_table_queryallrows($attachments, Array(PR_ATTACH_NUM), $attach_res);

			foreach($attachTable as $attachRow)
			{
				$tempattach = mapi_message_openattach($this->message, $attachRow[PR_ATTACH_NUM]);
				$exception = mapi_attach_openobj($tempattach);
		
			  	$data = mapi_message_getprops($exception, array($this->proptags["basedate"]));
			  	
			  	if($this->isSameDay($this->fromGMT($this->tz,$data[$this->proptags["basedate"]]), $base_date)) {
			  		return $tempattach;
			  	}
			}
			
			return false;
		}
		
		/**
		* gmtime() doesn't exist in standard PHP, so we have to implement it ourselves
		* @author Steve Hardy
		*/
		function GetTZOffset($ts)
		{
			$Offset = date("O", $ts);
		
			$Parity = $Offset < 0 ? -1 : 1;
			$Offset = $Parity * $Offset;
			$Offset = ($Offset - ($Offset % 100)) / 100 * 60 + $Offset % 100;
		
			return $Parity * $Offset;
		} 
		
		/**
		* gmtime() doesn't exist in standard PHP, so we have to implement it ourselves
		* @author Steve Hardy
		* @param Date $time
		* @return Date GMT Time
		*/
		function gmtime($time)
		{
			$TZOffset = $this->GetTZOffset($time);
		
			$t_time = $time - $TZOffset * 60; #Counter adjust for localtime()
			$t_arr = localtime($t_time, 1);
		
			return $t_arr;
		} 
		
		/**
		* Function which converts a recurrence date timestamp to an unix date timestamp.
		* @author Steve Hardy
		* @param Int $rdate the date which will be converted
		* @return Int the converted date
		*/ 
		function recurDataToUnixData($rdate)
		{
			return ($rdate - 194074560) * 60 ;
		} 
		
		/**
		* Function which converts an unix date timestamp to recurrence date timestamp.
		* @author Johnny Biemans
		* @param Date $date the date which will be converted
		* @return Int the converted date in minutes
		*/ 
		function unixDataToRecurData($date)
		{
			return ($date / 60) + 194074560;
		} 

		function isLeapYear($year) {
			return ( $year % 4 == 0 && ($year % 100 != 0 || $year % 400 == 0) );
		}
		
		function getMonthInSeconds($year, $month)
		{
			if( in_array($month, array(1,3,5,7,8,10,12) ) ) {
				$day = 31;
			} else if( in_array($month, array(4,6,9,11) ) ) {
				$day = 30;
			} else {
				$day = 28;
				if( $this->isLeapYear($year) == 1 )
					$day++;
			}
			return $day * 24 * 60 * 60;
		}

		/**
		 * Function to get a date by Year Nr, Month Nr, Week Nr, Day Nr, and hour
		 * @param int $year
		 * @param int $month
		 * @param int $week
		 * @param int $day
		 * @param int $hour
		 * @return returns the timestamp of the given date, timezone-independant
		 */
		
        function getDateByYearMonthWeekDayHour($year, $month, $week, $day, $hour)
        {
        	// get first day of month
        	$date = gmmktime(0,0,0,$month,0,$year + 1900);

        	// get wday info
        	$gmdate = $this->gmtime($date);

        	$date -= $gmdate["tm_wday"] * 24 * 60 * 60; // back up to start of week

        	$date += $week * 7 * 24 * 60 * 60; // go to correct week nr
        	$date += $day * 24 * 60 * 60;
        	$date += $hour * 60 * 60;

        	$gmdate = $this->gmtime($date);

        	// if we are in the next month, then back up a week, because week '5' means
        	// 'last week of month'

        	if($gmdate["tm_mon"]+1 != $month)
        		$date -= 7 * 24 * 60 * 60;

        	return $date; 
        }

        /**
         * getWeekNr() returns the week nr of the month (ie first week of february is 1)
         */
        function getWeekNr($date)
        {
        	$gmdate = gmtime($date);
        	$gmdate["tm_mday"] = 0;
        	return strftime("%W", $date) - strftime("%W", gmmktime($gmdate)) + 1;
        }

        /** 
         * parseTimezone parses the timezone as specified in named property 0x8233
         * in Outlook calendar messages. Returns the timezone in minutes negative
         * offset (GMT +2:00 -> -120)
         */
        function parseTimezone($data)
        {
        	if(strlen($data) < 48)
        		return;
        		
        	$tz = unpack("ltimezone/lunk/ltimezonedst/lunk/ldstendmonth/vdstendweek/vdstendhour/lunk/lunk/vunk/ldststartmonth/vdststartweek/vdststarthour/lunk/vunk", $data);

        	return $tz;
        }
        
        function getTimezoneData($tz)
        {
        	$data = pack("lllllvvllvlvvlv", $tz["timezone"], 0, $tz["timezonedst"], 0, $tz["dstendmonth"], $tz["dstendweek"], $tz["dstendhour"], 0, 0, 0, $tz["dststartmonth"], $tz["dststartweek"], $tz["dststarthour"], 0 ,0);
        	
        	return $data;
        }

        /**
         * createTimezone creates the timezone as specified in the named property 0x8233
         * see also parseTimezone()
         * $tz is an array with the timezone data
         */
        function createTimezone($tz)
        {
        	$data = pack("lxxxxlxxxxlvvxxxxxxxxxxlvvxxxxxx", 
        				$tz["timezone"],
        				array_key_exists("timezonedst",$tz)?$tz["timezonedst"]:0,
        				array_key_exists("dstendmonth",$tz)?$tz["dstendmonth"]:0,
        				array_key_exists("dstendweek",$tz)?$tz["dstendweek"]:0,
        				array_key_exists("dstendhour",$tz)?$tz["dstendhour"]:0,
        				array_key_exists("dststartmonth",$tz)?$tz["dststartmonth"]:0,
        				array_key_exists("dststartweek",$tz)?$tz["dststartweek"]:0,
        				array_key_exists("dststarthour",$tz)?$tz["dststarthour"]:0
        			);
        	
        	return $data;
        }


        /**
         * getTimezone gives the timezone offset (in minutes) of the given
         * local date/time according to the given TZ info
         */
        function getTimezone($tz, $date)
        {
            // No timezone -> GMT (+0)
            if(!isset($tz["timezone"]))
                return 0;
			
			$dst = false;
        	$gmdate = $this->gmtime($date);

        	$dststart = $this->getDateByYearMonthWeekDayHour($gmdate["tm_year"], $tz["dststartmonth"], $tz["dststartweek"], 0, $tz["dststarthour"]);
        	$dstend = $this->getDateByYearMonthWeekDayHour($gmdate["tm_year"], $tz["dstendmonth"], $tz["dstendweek"], 0, $tz["dstendhour"]);

        	if($dststart < $dstend) {
        		// Northern hemisphere, eg DST is during Mar-Oct
				if($date > $dststart && $date < $dstend) {
					$dst = true;
				}
			} else {
				// Southern hemisphere, eg DST is during Oct-Mar
				if($date < $dstend || $date > $dststart) {
					$dst = true;
				}
			}
			
			if($dst) {
				return $tz["timezone"] + $tz["timezonedst"];
			} else {
				return $tz["timezone"];
			}
				
        }
        
        /**
         * toGMT returns a timestamp in GMT time for the time and timezone given
         */
        function toGMT($tz, $date) {
            if(!isset($tz['timezone']))
                return $date;
        	$offset = $this->getTimezone($tz, $date);
        	
        	return $date + $offset * 60;
        }
        
        /**
         * fromGMT returns a timestamp in the local timezone given from the GMT time given
         */
        function fromGMT($tz, $date) {
        	$offset = $this->getTimezone($tz, $date);
        	
        	return $date - $offset * 60;
        }

		/**
		 * processOccurrenceItem, adds an item to a list of occurrences, but only if the following criteria are met:
		 * - The resulting occurrence (or exception) starts or ends in the interval <$start, $end>
		 * - The ocurrence isn't specified as a deleted occurrence
		 * @param array $items reference to the array to be added to
		 * @param date $start start of timeframe in GMT TIME
		 * @param date $end end of timeframe in GMT TIME
		 * @param date $basedate (hour/sec/min assumed to be 00:00:00) in LOCAL TIME OF THE OCCURRENCE
		 * @param int $startocc start of occurrence since beginning of day in minutes
		 * @param int $endocc end of occurrence since beginning of day in minutes
		 * @param int $tz the timezone info for this occurrence ( applied to $basedate / $startocc / $endocc )
		 * @param bool $reminderonly If TRUE, only add the item if the reminder is set
		 */
        function processOccurrenceItem(&$items, $start, $end, $basedate, $startocc, $endocc, $tz, $reminderonly)
        {
			$exception = $this->isException($basedate);
			if($exception){
				return false;
			}else{
				$occstart = $basedate + $startocc * 60;
				$occend = $basedate + $endocc * 60;
				
				// Convert to GMT
				$occstart = $this->toGMT($tz, $occstart);
				$occend = $this->toGMT($tz, $occend);
				
				/**
				 * FIRST PART : Check range criterium. Exact matches (eg when $occstart == $end), do NOT match since you cannot
				 * see any part of the appointment. Partial overlaps DO match.
				 *
				 * SECOND PART : check if occurence is not a zero duration occurrence which
				 * starts at 00:00 and ends on 00:00. if it is so, then process 
				 * the occurrence and send it in response.
				 */
				if(($occstart  >= $end || $occend <=  $start) && !($occstart == $occend && $occstart == $start))
					return;
			
                // Properties for this occurrence are the same as the main object, 
                // With these properties overridden
                $newitem = $this->messageprops;
                $newitem[$this->proptags["startdate"]] = $occstart;
                $newitem[$this->proptags["duedate"]] = $occend;
                $newitem["basedate"] = $basedate;
            }
            
            // If reminderonly is set, only add reminders
            if($reminderonly && (!isset($newitem[$this->proptags["reminder"]]) || $newitem[$this->proptags["reminder"]] == false))
                return;
                
            $items[] = $newitem;
        }
		
		/**
		 * processExceptionItem, adds an all exception item to a list of occurrences, without any constraint on timeframe
		 * @param array $items reference to the array to be added to
		 * @param date $start start of timeframe in GMT TIME
		 * @param date $end end of timeframe in GMT TIME
		 */
		function processExceptionItems(&$items, $start, $end)
		{
			$limit = 0;
			foreach($this->recur["changed_occurences"] as $exception) {
					
				// Convert to GMT
				$occstart = $this->toGMT($this->tz, $exception["start"]);
				$occend = $this->toGMT($this->tz, $exception["end"]);

				// Check range criterium. Exact matches (eg when $occstart == $end), do NOT match since you cannot
				// see any part of the appointment. Partial overlaps DO match.	
				if($occstart > $end || $occend < $start)
					continue;				         	
					
				array_push($items, $this->getExceptionProperties($exception));
			    if($limit && (count($items) == $limit))
					break;
				}	
		}
		
		/**
		 * Function which verifies if on the given date an exception, delete or change, occurs.
		 * @param date $date the date
		 * @return array the exception, true - if an occurrence is deleted on the given date, false - no exception occurs on the given date
		 */		 		
		function isException($basedate)
		{
            if($this->isDeleteException($basedate))
                return true;
            			
            if($this->getChangeException($basedate) != false)
                return true;
 			
			return false;
		}
		
		/**
		 * Returns TRUE if there is a DELETE exception on the given base date
		 */
        function isDeleteException($basedate)
        {
		    // Check if the occurrence is deleted on the specified date
			foreach($this->recur["deleted_occurences"] as $deleted)
			{
			    if($this->isSameDay($deleted, $basedate))
			        return true;
			}
			
			return false;
        }
        
        /**
         * Returns the exception if there is a CHANGE exception on the given base date, or FALSE otherwise
         */
        function getChangeException($basedate)
        {
            // Check if the occurrence is modified on the specified date
			foreach($this->recur["changed_occurences"] as $changed)
			{
                if($this->isSameDay($changed["basedate"], $basedate))
                    return $changed;
			}
			
			return false;
        }
		
		/**
		 * Function to see if two dates are on the same day
		 * @param date $time1 date 1
		 * @param date $time2 date 2
		 * @return boolean Returns TRUE when both dates are on the same day
		 */
		function isSameDay($date1, $date2)
		{
		    $time1 = $this->gmtime($date1);
		    $time2 = $this->gmtime($date2);
		    
		    return $time1["tm_mon"] == $time2["tm_mon"] && $time1["tm_year"] == $time2["tm_year"] && $time1["tm_mday"] == $time2["tm_mday"];
		}
		
		/**
		 * Function to get timestamp of the beginning of the day of the timestamp given
		 * @param date $date
		 * @return date timestamp referring to same day but at 00:00:00
		 */
		function dayStartOf($date)
		{
		    $time1 = $this->gmtime($date);
		    
		    return gmmktime(0, 0, 0, $time1["tm_mon"] + 1, $time1["tm_mday"], $time1["tm_year"] + 1900);
		}
		
		/**
         * Function to get timestamp of the beginning of the month of the timestamp given
         * @param date $date
         * @return date Timestamp referring to same month but on the first day, and at 00:00:00
         */
		function monthStartOf($date)
		{
		    $time1 = $this->gmtime($date);
		    
		    return gmmktime(0, 0, 0, $time1["tm_mon"] + 1, 1, $time1["tm_year"] + 1900);
		}
		
		/**
		 * Function to get timestamp of the beginning of the year of the timestamp given
		 * @param date $date
		 * @return date Timestamp referring to the same year but on Jan 01, at 00:00:00
		 */
		function yearStartOf($date)
		{
			$time1 = $this->gmtime($date);
			
			return gmmktime(0, 0, 0, 1, 1, $time1["tm_year"] + 1900);
		}
		
		/**
		 * Function to get all properties of a single changed exception. 
		 * @param date $date base date of exception
		 * @return array associative array of properties for the exception, compatible with 
		 */
        function getExceptionProperties($exception)
        {
        	// Exception has same properties as main object, with some properties overridden:
            $item = $this->messageprops;
            
            // Special properties
            $item["exception"] = true;
            $item["basedate"] = $exception["basedate"]; // note that the basedate is always in local time !
            
            // MAPI-compatible properties (you can handle an exception as a normal calendar item like this)
            $item[$this->proptags["startdate"]] = $this->toGMT($this->tz, $exception["start"]);
            $item[$this->proptags["duedate"]] = $this->toGMT($this->tz, $exception["end"]);
            
            if(isset($exception["subject"])) {
                $item[$this->proptags["subject"]] = $exception["subject"];
            }
            
            if(isset($exception["label"])) {
                $item[$this->proptags["label"]] = $exception["label"];
            }
            
            if(isset($exception["alldayevent"])) {
                $item[$this->proptags["alldayevent"]] = $exception["alldayevent"];
            }
            
            if(isset($exception["location"])) {
                $item[$this->proptags["location"]] = $exception["location"];
            }
            
            if(isset($exception["remind_before"])) {
                $item[$this->proptags["reminder_minutes"]] = $exception["remind_before"];
            }
            
            if(isset($exception["reminder_set"])) {
                $item[$this->proptags["reminder"]] = $exception["reminder_set"];
            }

            if(isset($exception["busystatus"])) {
                $item[$this->proptags["busystatus"]] = $exception["busystatus"];
            }
            
            return $item;
        }
       
		/**
		* Function for parsing the Recurrence value of a Calendar item.
		*
		* Retrieve it from Named Property 0x8216 as a PT_BINARY and pass the
		* data to this function
		*
		* Returns a structure containing the data:
		*
		* type		- type of recurrence: day=10, week=11, month=12, year=13
		* subtype	- type of day recurrence: 2=monthday (ie 21st day of month), 3=nday'th weekdays (ie. 2nd Tuesday and Wednesday)
		* start	- unix timestamp of first occurrence
		* end		- unix timestamp of last occurrence (up to and including), so when start == end -> occurrences = 1
		* numoccur     - occurrences (may be very large when there is no end data)
		*
		* then, for each type:
		*
		* Daily:
		*  everyn	- every [everyn] days in minutes
		*  regen	- regenerating event (like tasks)
		* 
		* Weekly:
		*  everyn	- every [everyn] weeks in weeks
		*  regen	- regenerating event (like tasks)
		*  weekdays - bitmask of week days, where each bit is one weekday (weekdays & 1 = Sunday, weekdays & 2 = Monday, etc)
		*  
		* Monthly:
		*  everyn	- every [everyn] months
		*  regen	- regenerating event (like tasks)
		*  
		*  subtype 2:
		*	  monthday - on day [monthday] of the month
		*
		*  subtype 3:
		*	  weekdays - bitmask of week days, where each bit is one weekday (weekdays & 1 = Sunday, weekdays & 2 = Monday, etc)
		*   nday	- on [nday]'th [weekdays] of the month
		*
		* Yearly:
		*  everyn	- every [everyn] months (12, 24, 36, ...)
		*  month	- in month [month] (although the month is encoded in minutes since the startning of the year ........)
		*  regen	- regenerating event (like tasks)
		*
		*  subtype 2:
		*   monthday - on day [monthday] of the month
		*
		*  subtype 3:
		*   weekdays - bitmask of week days, where each bit is one weekday (weekdays & 1 = Sunday, weekdays & 2 = Monday, etc)
		*	  nday	- on [nday]'th [weekdays] of the month [month]
		* @param string $rdata Binary string
		* @return array recurrence data.
		*/
		function parseRecurrence($rdata)
		{
			if (strlen($rdata) < 10) {
				return;
			}
			
			$ret["changed_occurences"] = array();
			$ret["deleted_occurences"] = array();
			
			$data = unpack("Vconst1/Crtype/Cconst2/Vrtype2", $rdata);
		
			$ret["type"] = $data["rtype"];
			$ret["subtype"] = $data["rtype2"];
			$rdata = substr($rdata, 10);
		
			switch ($data["rtype"])
			{
				case 0x0a: 
					// Daily
					if (strlen($rdata) < 12) {
						return $ret;
					}
		
					$data = unpack("Vunknown/Veveryn/Vregen", $rdata);
					$ret["everyn"] = $data["everyn"];
					$ret["regen"] = $data["regen"];
		
					switch($ret["subtype"])
					{
						case 0:
							$rdata = substr($rdata, 12);
							break;
						case 1:
							$rdata = substr($rdata, 16);
							break;
					}
		
					break;
		
				case 0x0b: 
					// Weekly
					if (strlen($rdata) < 16) {
						return $ret;
					}
		
					$data = unpack("Vconst1/Veveryn/Vregen/Vweekdays", $rdata);
		
					$ret["everyn"] = $data["everyn"];
					$ret["regen"] = $data["regen"];
					$ret["weekdays"] = $data["weekdays"];
					
					$rdata = substr($rdata, 16);
					break;
		
				case 0x0c: 
					// Monthly
					if (strlen($rdata) < 16) {
						return $ret;
					}
		
					$data = unpack("Vconst1/Veveryn/Vregen/Vmonthday", $rdata);
		
					$ret["everyn"] = $data["everyn"];
					$ret["regen"] = $data["regen"];
		
					if ($ret["subtype"] == 3) {
						$ret["weekdays"] = $data["monthday"];
					} else {
						$ret["monthday"] = $data["monthday"];
					}
		
					$rdata = substr($rdata, 16);
		
					if ($ret["subtype"] == 3) {
						$data = unpack("Vnday", $rdata);
						$ret["nday"] = $data["nday"];
						$rdata = substr($rdata, 4);
					} 
					break;
		
				case 0x0d: 
					// Yearly
					if (strlen($rdata) < 16)
						return $ret;
		
					$data = unpack("Vmonth/Veveryn/Vregen/Vmonthday", $rdata);
		
					$ret["month"] = $data["month"];
					$ret["everyn"] = $data["everyn"];
					$ret["regen"] = $data["regen"];
					
					if ($ret["subtype"] == 3) {
						$ret["weekdays"] = $data["monthday"];
					} else {
						$ret["monthday"] = $data["monthday"];
					}
					
					$rdata = substr($rdata, 16);
		
					if ($ret["subtype"] == 3) {
						$data = unpack("Vnday", $rdata);
						$ret["nday"] = $data["nday"];
						$rdata = substr($rdata, 4);
					} 
					break;
			} 
		
			if (strlen($rdata) < 16) {
				return $ret;
			}
			
			$data = unpack("Cterm/C3const1/Vnumoccur/Vconst2/Vnumexcept", $rdata);
		
			$rdata = substr($rdata, 16);
		
			$ret["term"] = $data["term"];
			$ret["numoccur"] = $data["numoccur"];
			$ret["numexcept"] = $data["numexcept"]; 
		
			// exc_base_dates are *all* the base dates that have been either deleted or modified
			$exc_base_dates = array();
			for($i = 0; $i < $ret["numexcept"]; $i++)
			{
				$data = unpack("Vbasedate", $rdata);
				$rdata = substr($rdata, 4);
				$exc_base_dates[] = $this->recurDataToUnixData($data["basedate"]);
			}
			
			$data = unpack("Vnumexceptmod", $rdata);
			$rdata = substr($rdata, 4);
			
			$ret["numexceptmod"] = $data["numexceptmod"];
		
			// exc_changed are the base dates of *modified* occurrences. exactly what is modified
			// is in the attachments *and* in the data further down this function.
			$exc_changed = array();
			for($i = 0; $i < $ret["numexceptmod"]; $i++)
			{
				$data = unpack("Vstartdate", $rdata);
				$rdata = substr($rdata, 4);
				$exc_changed[] = $this->recurDataToUnixData($data["startdate"]);
			}
		
			if (strlen($rdata) < 24) {
				return $ret;
			}
			
			$data = unpack("Vstart/Vend/Vconst1/Cversion/C3const2/Vstartmin/Vendmin", $rdata);
		
			$ret["start"] = $this->recurDataToUnixData($data["start"]);
			$ret["end"] = $this->recurDataToUnixData($data["end"]);
			$ret["startocc"] = $data["startmin"];
			$ret["endocc"] = $data["endmin"];
		
			$rdata = substr($rdata, 24); 
			
	 		$data = unpack("vnumber", $rdata);
	 		$rdata = substr($rdata, 2);
	 		
	 		$nexceptions = $data["number"];
	 		
	 		$exc_changed_details = array();
	 		
            // Parse n modified exceptions			
			for($i=0;$i<$nexceptions;$i++) 
			{
		  		$item = array();
		  		
		  		// Get exception startdate, enddate and basedate (the date at which the occurrence would have started)
		  		$data = unpack("Vstartdate/Venddate/Vbasedate", $rdata);
		  		$rdata = substr($rdata, 12);
		
				// Convert recurtimestamp to unix timestamp
		  		$startdate = $this->recurDataToUnixData($data["startdate"]);
		   		$enddate = $this->recurDataToUnixData($data["enddate"]);
		   		$basedate = $this->recurDataToUnixData($data["basedate"]);
		   		
				// Set the right properties
		  		$item["basedate"] = $this->dayStartOf($basedate);
		  		$item["start"] = $startdate;
		  		$item["end"] = $enddate;
		
		  		$data = unpack("vbitmask", $rdata);
		  		$rdata = substr($rdata, 2);
		  		
		  		// Bitmask to verify what properties are changed
		  		$bitmask = $data["bitmask"];
		  
		  		if(($bitmask &(1 << 0))) {
		  			$data = unpack("vnull_length/vlength", $rdata);
		  			$rdata = substr($rdata, 4);
		  			
		  			$length = $data["length"];
		  			$item["subject"] = "";
		  			for($j = 0; $j < $length && strlen($rdata); $j++)
		  			{
		  				$data = unpack("Cchar", $rdata);
		  				$rdata = substr($rdata, 1);
		  				
		  				$item["subject"] .= chr($data["char"]);
		  			}
		  		}
		  		
		  		if(($bitmask &(1 << 1))) {
		  		    // Attendees modified: no data here (only in attachment)
		  		}
		  		
		  		if(($bitmask &(1 << 2))) {
		  			$data = unpack("Vremind_before", $rdata);
		  			$rdata = substr($rdata, 4);
		  			
		  			$item["remind_before"] = $data["remind_before"];
		  		}
		  			
		  		if(($bitmask &(1 << 3))) {
		  			$data = unpack("Vreminder_set", $rdata);
		  			$rdata = substr($rdata, 4);
		  			
		  			$item["reminder_set"] = $data["reminder_set"];
		  		}
		  		
		  		if(($bitmask &(1 << 4))) {
		  			$data = unpack("vnull_length/vlength", $rdata);
		  			$rdata = substr($rdata, 4);
		  			
		  			$item["location"] = "";
		  			
		  			$length = $data["length"];
	  				$data = substr($rdata, 0, $length);
	  				$rdata = substr($rdata, $length);
		  				
	  				$item["location"] .= $data;
		  		}
		  		
		  		if(($bitmask &(1 << 5))) {
		  			$data = unpack("Vbusystatus", $rdata);
		  			$rdata = substr($rdata, 4);
		  			
		  			$item["busystatus"] = $data["busystatus"];
		  		}
		  			
		  		if(($bitmask &(1 << 6))) {
		  		    // no data: RESERVED
		  		}
		  			
		  		if(($bitmask &(1 << 7))) {
		  			$data = unpack("Vallday", $rdata);
		  			$rdata = substr($rdata, 4);
		  			
		  			$item["alldayevent"] = $data["allday"];
		  		}
		  		
		  		if(($bitmask &(1 << 8))) {
		  			$data = unpack("Vlabel", $rdata);
		  			$rdata = substr($rdata, 4);
		  			
		  			$item["label"] = $data["label"];
		  		}
		  		
		  		if(($bitmask &(1 << 9))) {
		  		    // Notes or Attachments modified: no data here (only in attachment)
		  		}
		
		  		array_push($exc_changed_details, $item);
			}

            // We now have $exc_changed, $exc_base_dates and $exc_changed_details
            // We will ignore $exc_changed, as this information is available in $exc_changed_details
            // also. If an item is in $exc_base_dates and NOT in $exc_changed_details, then the item
            // has been deleted.
            
            // Find deleted occurrences
            $deleted_occurences = array();
            
            foreach($exc_base_dates as $base_date) {
                $found = false;
                
                foreach($exc_changed_details as $details) {
                    if($details["basedate"] == $base_date) {
                        $found = true;
                        break;
                    }
                }
                if(! $found) {
                    // item was not in exc_changed_details, so it must be deleted
                    $deleted_occurences[] = $base_date;
                } 
            }
            
            $ret["deleted_occurences"] = $deleted_occurences;
            $ret["changed_occurences"] = $exc_changed_details;

			return $ret;
		}
		
		/**
		 * Saves the recurrence data to the recurrence property
		 * @param array $properties the recurrence data. 
		 * @return string binary string
		 */
		function saveRecurrence()
		{
			// Only save if a message was passed
			if(!isset($this->message))
				return;
				
			// Abort if no recurrence was set
			if(!isset($this->recur["type"]) && !isset($this->recur["subtype"])) {
				return;
			}
			
			if(!isset($this->recur["start"]) && !isset($this->recur["end"])) {
				return;
			}
			
			if(!isset($this->recur["startocc"]) && !isset($this->recur["endocc"])) {
				return;
			}
			
			$rdata = pack("CCCCCCV", 0x04, 0x30, 0x04, 0x30, intval($this->recur["type"]), 0x20, intval($this->recur["subtype"]));

			$weekstart = 1; //monday
			$forwardcount = 0;
			$restocc = 0;
			$dayofweek = intval(gmdate("w", intval($this->recur["start"]))); //0 (for Sunday) through 6 (for Saturday)
			
			$term = intval($this->recur["type"]);
			switch($term)
			{
				case 0x0A:
				    // Daily
				    
					if(!isset($this->recur["everyn"])) {
						return;
					}
						
					if($this->recur["subtype"] == 1) {

						// Daily every workday
						$rdata .= pack("VVVV", (6 * 24 * 60), 1, 0, 0x3E);
					} else {
						// Daily every N days (everyN in minutes)

						$everyn =  intval($this->recur["everyn"]) / 1440;
						
						// Calc first occ
						$firstocc = $this->unixDataToRecurData($this->recur["start"]) % intval($this->recur["everyn"]);
						
						$rdata .= pack("VVV", $firstocc, intval($this->recur["everyn"]), 0);
					}						
					break;
				case 0x0B:
				    // Weekly
					if(!isset($this->recur["everyn"]) && !isset($this->recur["weekdays"])) {
						return;
					}
					
					// Calculate start date of recurrence
					
					// Find the first day that matches one of the weekdays selected
					$daycount = 0;
					$dayskip = -1;
					for($j = 0; $j < 7; $j++) {
						if(intval($this->recur["weekdays"]) & (1<<( ($dayofweek+$j)%7)) ) {
							if($dayskip == -1)
								$dayskip = $j;
							
							$daycount++;
						}
					}
					
					// $dayskip is the number of days to skip from the startdate until the first occurrence
					// $daycount is the number of days per week that an occurrence occurs
					
					$weekskip = 0;
					if(($dayofweek < $weekstart && $dayskip > 0) || ($dayofweek+$dayskip) > 6)
						$weekskip = 1;
						
                    // $weekskip is the amount of weeks to skip from the startdate before the first occurence
					
                    // $forwardcount is the maximum number of week occurrences we can go ahead after the first occurrence that
                    // is still inside the recurrence. We subtract one to make sure that the last week is never forwarded over
                    // (eg when numoccur = 2, and daycount = 1)
					$forwardcount = floor( intval($this->recur["numoccur"] -1 ) / $daycount);
					
					// $restocc is the number of occurrences left after $forwardcount whole weeks of occurrences, minus one
					// for the occurrence on the first day
					$restocc = intval($this->recur["numoccur"]) - ($forwardcount*$daycount) - 1; 

                    // $forwardcount is now the number of weeks we can go forward and still be inside the recurrence
					$forwardcount *= intval($this->recur["everyn"]);
					
					// The real start is start + dayskip + weekskip-1 (since dayskip will already bring us into the next week)
					$this->recur["start"] = intval($this->recur["start"]) + ($dayskip * 24*60*60)+ ($weekskip *(intval($this->recur["everyn"]) - 1) * 7 * 24*60*60);
					
					// Calc first occ
					$firstocc = ($this->unixDataToRecurData($this->recur["start"]) ) % ( intval($this->recur["everyn"]) * 7 * 24 * 60);

					$firstocc -= (intval(gmdate("w", intval($this->recur["start"]))) - 1) * 24 * 60;

					$rdata .= pack("VVVV", $firstocc, intval($this->recur["everyn"]), 0, intval($this->recur["weekdays"]));
					break;
				case 0x0C:
				    // Monthly
				case 0x0D:
				    // Yearly
					if(!isset($this->recur["everyn"])) {
						return;
					}
					if($term == 0x0D /*yearly*/ && !isset($this->recur["month"])) {
						return;
					}
					
					if($term == 0x0C /*monthly*/) {
						$everyn = intval($this->recur["everyn"]);
					}else {
						$everyn = 12;
					}
					
					// Get montday/month/year of original start
					$curmonthday = gmdate("j", intval($this->recur["start"]) );
					$curyear = gmdate("Y", intval($this->recur["start"]) );
					$curmonth = gmdate("n", intval($this->recur["start"]) );
					
					// $forwardcount is the number of occurrences we can skip and still be inside the recurrence range (minus
					// one to make sure there are always at least one occurrence left)
					$forwardcount = ((intval($this->recur["numoccur"])-1) * $everyn );
					
					// Get month for yearly on D'th day of month M
					if($term == 0x0D /*yearly*/) {
						$selmonth = floor(intval($this->recur["month"]) / (24 * 60 *29)) + 1; // 1=jan, 2=feb, eg
					}
					
					switch(intval($this->recur["subtype"]))
					{
						// on D day of every M month 
						case 2:
							if(!isset($this->recur["monthday"])) {
								return;
							}
							// Recalc startdate
							
							// Set on the right begin day
							
							// Go the beginning of the month
							$this->recur["start"] -= ($curmonthday-1) * 24*60*60;
							// Go the the correct month day
							$this->recur["start"] += (intval($this->recur["monthday"])-1) * 24*60*60;

							// If the previous calculation gave us a start date *before* the original start date, then we need to skip to the next occurrence
							if ( ($term == 0x0C /*monthly*/ && intval($this->recur["monthday"]) < $curmonthday) ||
								($term == 0x0D /*yearly*/ &&( $selmonth < $curmonth || ($selmonth == $curmonth && intval($this->recur["monthday"]) < $curmonthday)) ))
							{
								if($term == 0x0D /*yearly*/)
									$count = ($everyn - ($curmonth - $selmonth)); // Yearly, go to next occurrence in 'everyn' months minus difference in first occurence and original date
								else
									$count = $everyn; // Monthly, go to next occurrence in 'everyn' months

                                // Forward by $count months. This is done by getting the number of days in that month and forwarding that many days
								for($i=0; $i < $count; $i++) {
									$this->recur["start"] += $this->getMonthInSeconds($curyear, $curmonth);
									
									if($curmonth == 12) {
										$curyear++;
										$curmonth = 0;
									}
									$curmonth++;
								}								
							}
							
							// "start" is now pointing to the first occurrence, except that it will overshoot if the
							// month in which it occurs has less days than specified as the day of the month. So 31st
							// of each month will overshoot in february (29 days). We compensate for that by checking
							// if the day of the month we got is wrong, and then back up to the last day of the previous
							// month.
							if(intval($this->recur["monthday"]) >=28 && intval($this->recur["monthday"]) <= 31 && 
								gmdate("j", intval($this->recur["start"])) < intval($this->recur["monthday"]))
							{
								$this->recur["start"] -= gmdate("j", intval($this->recur["start"])) * 24 * 60 *60;
							}
							
							// "start" is now the first occurrence
							
							if($term == 0x0C /*monthly*/) {
								// Calc first occ
								$monthIndex = ((((12%$everyn) * ((intval(gmdate("Y", $this->recur["start"])) - 1601)%$everyn)) % $everyn) + (intval(gmdate("n", $this->recur["start"])) - 1))%$everyn;

								$firstocc = 0;
								for($i=0; $i < $monthIndex; $i++) {
									$firstocc+= $this->getMonthInSeconds(1601 + floor($i/12), ($i%12)+1) / 60;
								}
								
								$rdata .= pack("VVVV", $firstocc, $everyn, 0, intval($this->recur["monthday"]));
							} else{
								// Calc first occ
								$firstocc = 0;
								$monthIndex = intval(gmdate("n", $this->recur["start"]));
								for($i=1; $i < $monthIndex; $i++) {
									$firstocc+= $this->getMonthInSeconds(1601 + floor($i/12), $i) / 60;
								}
								
								$rdata .= pack("VVVV", $firstocc, $everyn, 0, intval($this->recur["monthday"]));
							}
							break;
						
						case 3:
							// monthly: on Nth weekday of every M month
							// yearly: on Nth weekday of M month
							if(!isset($this->recur["weekdays"]) && !isset($this->recur["nday"])) {
								return;
							}
							
							$weekdays = intval($this->recur["weekdays"]);
							$nday = intval($this->recur["nday"]);
							
							// Calc startdate
							$monthbegindow = intval($this->recur["start"]);
							
							if($nday == 5) {
								// Set date on the last day of the last month
								$monthbegindow += (gmdate("t", $monthbegindow ) - gmdate("j", $monthbegindow )) * 24 * 60 * 60;
							}else {
								// Set on the first day of the month
								$monthbegindow -= ((gmdate("j", $monthbegindow )-1) * 24 * 60 * 60);
							}

							if($term == 0x0D /*yearly*/) {
								// Set on right month
								if($selmonth < $curmonth)
									$tmp = 12 - $curmonth + $selmonth;
								else
									$tmp = ($selmonth - $curmonth);
								
								for($i=0; $i < $tmp; $i++) {
									$monthbegindow += $this->getMonthInSeconds($curyear, $curmonth);
									
									if($curmonth == 12) {
										$curyear++;
										$curmonth = 0;
									}
									$curmonth++;
								}
								
							}else {							
								// Check or you exist in the right month

								for($i = 0; $i < 7; $i++) {
									if($nday == 5 && (1<<( (gmdate("w", $monthbegindow)-$i)%7) ) & $weekdays) {										
										$day = gmdate("j", $monthbegindow) - $i;
										break;
									}else if($nday != 5 && (1<<( (gmdate("w", $monthbegindow )+$i)%7) ) & $weekdays) {
										$day = (($nday-1)*7) + ($i+1);
										break;
									}
								}
								
								// Goto the next X month
								if(isset($day) && ($day < gmdate("j", intval($this->recur["start"]))) ) {
									if($nday == 5) {
										$monthbegindow += 24 * 60 * 60;
										if($curmonth == 12) {
											$curyear++;
											$curmonth = 0;
										}
										$curmonth++;
									}
								
									for($i=0; $i < $everyn; $i++) {
										$monthbegindow += $this->getMonthInSeconds($curyear, $curmonth);
										
										if($curmonth == 12) {
											$curyear++;
											$curmonth = 0;
										}
										$curmonth++;
									}
									
									if($nday == 5) {
										$monthbegindow -= 24 * 60 * 60;
									}
								}
							}
								
							//FIXME: weekstart?
							
							$day = 0;
							// Set start on the right day							
							for($i = 0; $i < 7; $i++) {
								if($nday == 5 && (1<<( (gmdate("w", $monthbegindow )-$i)%7) ) & $weekdays) {
									$day = $i;
									break;
								}else if($nday != 5 && (1<<( (gmdate("w", $monthbegindow )+$i)%7) ) & $weekdays) {
									$day = ($nday - 1) * 7 + ($i+1);
									break;
								}
							}
							if($nday == 5)
								$monthbegindow -= $day * 24 * 60 *60;
							else
								$monthbegindow += ($day-1) * 24 * 60 *60;

							$firstocc = 0;
							
							if($term == 0x0C /*monthly*/) {
								// Calc first occ
								$monthIndex = ((((12%$everyn) * ((intval(gmdate("Y", $this->recur["start"])) - 1601)%$everyn)) % $everyn) + (intval(gmdate("n", $this->recur["start"])) - 1))%$everyn;
								
								for($i=0; $i < $monthIndex; $i++) {
									$firstocc+= $this->getMonthInSeconds(1601 + floor($i/12), ($i%12)+1) / 60;
								}
								
								$rdata .= pack("VVVVV", $firstocc, $everyn, 0, $weekdays, $nday);
							} else {
								// Calc first occ								
								$monthIndex = intval(gmdate("n", $this->recur["start"]));
								
								for($i=1; $i < $monthIndex; $i++) {
									$firstocc+= $this->getMonthInSeconds(1601 + floor($i/12), $i) / 60;
								}
								
								$rdata .= pack("VVVVV", $firstocc, $everyn, 0, $weekdays, $nday);
							}
							break;
					}
					break;
				


			}
			
			if(!isset($this->recur["term"])) {
				return;
			}
			
			// Terminate
			$term = intval($this->recur["term"]);
			$rdata .= pack("CCCC", $term, 0x20, 0x00, 0x00);
			
			switch($term)
			{
				// After the given enddate
				case 0x21:
					$rdata .= pack("V", 10);
					break;
				// After a number of times
				case 0x22:
					if(!isset($this->recur["numoccur"])) {
						return;
					}
					
					$rdata .= pack("V", intval($this->recur["numoccur"]));
					break;
				// Never ends
				case 0x23:
					$rdata .= pack("V", 0);
					break;
			}
			
			// Strange little thing for the recurrence type "every workday"
			if(intval($this->recur["type"]) == 0x0B && intval($this->recur["subtype"]) == 1) {
				$rdata .= pack("V", 1);
			} else { // Other recurrences
				$rdata .= pack("V", 0);
			}
			
			// Exception data

			// Get all exceptions
			$deleted_items = $this->recur["deleted_occurences"];
			$changed_items = $this->recur["changed_occurences"];
			
			// Merge deleted and changed items into one list
	  		$items = $deleted_items;
	  		
	  		foreach($changed_items as $changed_item)
	  			array_push($items, $changed_item["basedate"]);

	  		sort($items);
	  		
	  		// Add the merged list in to the rdata
	  		$rdata .= pack("V", count($items));
	  		foreach($items as $item)
				$rdata .= pack("V", $this->unixDataToRecurData($item));
			
			// Loop through the changed exceptions (not deleted)
			$rdata .= pack("V", count($changed_items));
			$items = array();
			
			foreach($changed_items as $changed_item)
			{
				$items[] = $this->dayStartOf($changed_item["start"]);
			}

			sort($items);

			// Add the changed items list int the rdata
			foreach($items as $item)
				$rdata .= pack("V", $this->unixDataToRecurData($item));
			
			// Set start date
			$rdata .= pack("V", $this->unixDataToRecurData(intval($this->recur["start"])));
		
			// Set enddate
			switch($term)
			{
				// After the given enddate
				case 0x21:
					$rdata .= pack("V", $this->unixDataToRecurData(intval($this->recur["end"])));
					break;
				// After a number of times
				case 0x22:
					// @todo: calculate enddate with intval($this->recur["startocc"]) + intval($this->recur["duration"]) > 24 hour
					$occenddate = intval($this->recur["start"]);
					
					switch(intval($this->recur["type"])) {
						case 0x0A: //daily
														
							if($this->recur["subtype"] == 1) {
								// Daily every workday
								$restocc = intval($this->recur["numoccur"]);
								
								// Get starting weekday
								$nowtime = $this->gmtime($occenddate);
								$j = $nowtime["tm_wday"];
								
								while(1)
								{
									if(($j%7) > 0 && ($j%7)<6 ) {
										$restocc--;
									}
									
									$j++;

									if($restocc <= 0)
									    break;
									    
									$occenddate += 24*60*60;
								}
								
							} else {
							    // -1 because the first day already counts (from 1-1-1980 to 1-1-1980 is 1 occurrence)
								$occenddate += (intval($this->recur["everyn"]) * 60 * (intval($this->recur["numoccur"]-1)));
							}
							break;
						case 0x0B: //weekly
							// Needed values
							// $forwardcount - number of weeks we can skip forward
							// $restocc - number of remaning occurrences after the week skip
			
							// Add the weeks till the last item
							$occenddate+=($forwardcount*7*24*60*60);
							
							$dayofweek = gmdate("w", $occenddate);						
							
							// Loop through the last occurrences until we have had them all
							for($j = 1; $restocc>0; $j++)
							{
							    // Jump to the next week (which may be N weeks away) when going over the week boundary
								if((($dayofweek+$j)%7) == $weekstart)
									$occenddate += (intval($this->recur["everyn"])-1) * 7 * 24*60*60;

                                // If this is a matching day, once less occurrence to process
								if(intval($this->recur["weekdays"]) & (1<<(($dayofweek+$j)%7)) ) {
									$restocc--;
								}
								
								// Next day
								$occenddate += 24*60*60;
							}
							
							break;
						case 0x0C: //monthly
						case 0x0D: //yearly
								
							$curyear = gmdate("Y", intval($this->recur["start"]) );
							$curmonth = gmdate("n", intval($this->recur["start"]) );
							// $forwardcount = months

							switch(intval($this->recur["subtype"]))
							{
								case 2: // on D day of every M month
									while($forwardcount > 0)
									{
										$occenddate += $this->getMonthInSeconds($curyear, $curmonth);
										
										if($curmonth >=12) {
											$curmonth = 1;
											$curyear++;
										} else { 
											$curmonth++;
										}
										$forwardcount--;
									}
									
									// compensation between 28 and 31
									if(intval($this->recur["monthday"]) >=28 && intval($this->recur["monthday"]) <= 31 && 
										gmdate("j", $occenddate) < intval($this->recur["monthday"]))
									{
										if(gmdate("j", $occenddate) < 28)
											$occenddate -= gmdate("j", $occenddate) * 24 * 60 *60;
										else
											$occenddate += (gmdate("t", $occenddate) - gmdate("j", $occenddate)) * 24 * 60 *60;
									}
									
									
									break;
								case 3: // on Nth weekday of every M month
									$nday = intval($this->recur["nday"]); //1 tot 5
									$weekdays = intval($this->recur["weekdays"]);
									

									while($forwardcount > 0)
									{
										$occenddate += $this->getMonthInSeconds($curyear, $curmonth);
										if($curmonth >=12) {
											$curmonth = 1;
											$curyear++;
										} else {
											$curmonth++;
										}

										$forwardcount--;
									}

									if($nday == 5) {
										// Set date on the last day of the last month
										$occenddate += (gmdate("t", $occenddate ) - gmdate("j", $occenddate )) * 24 * 60 * 60;
									}else {
										// Set date on the first day of the last month
										$occenddate -= (gmdate("j", $occenddate )-1) * 24 * 60 * 60;
									}
									
									for($i = 0; $i < 7; $i++) {
										if( $nday == 5 && (1<<( (gmdate("w", $occenddate)-$i)%7) ) & $weekdays) {
											$occenddate -= $i * 24 * 60 * 60;
											break;
										}else if($nday != 5 && (1<<( (gmdate("w", $occenddate)+$i)%7) ) & $weekdays) {
											$occenddate +=  ($i + (($nday-1) *7)) * 24 * 60 * 60;
											break;
										}
									}

								break; //case 3:
								}

							break;

					}

					if (defined("PHP_INT_MAX") && $occenddate > PHP_INT_MAX)
						$occenddate = PHP_INT_MAX;
					
					$this->recur["end"] = $occenddate;

					$rdata .= pack("V", $this->unixDataToRecurData(intval($this->recur["end"])) );
					break;
				// Never ends
				case 0x23:
				default:
					$this->recur["end"] = 0x7fffffff; // max date -> 2038
					$rdata .= pack("V", 0x5AE980DF);
					break;
			}
			
			// UTC date
			$utcstart = $this->toGMT($this->tz, intval($this->recur["start"]));
			$utcend = $this->toGMT($this->tz, intval($this->recur["end"]));
			
			//utc date+time
			$utcfirstoccstartdatetime = $utcstart + (intval($this->recur["startocc"])*60);
			$utcfirstoccenddatetime = $utcstart + (intval($this->recur["endocc"]) * 60);
			
			// update reminder time
			mapi_setprops($this->message, Array($this->proptags["reminder_time"] => $utcfirstoccstartdatetime ));
			
			// update first occurrence date
			mapi_setprops($this->message, Array($this->proptags["start"] => $utcfirstoccstartdatetime ));
			mapi_setprops($this->message, Array($this->proptags["end"] => $utcfirstoccenddatetime ));
			mapi_setprops($this->message, Array($this->proptags["commonstart"] => $utcfirstoccstartdatetime ));
			mapi_setprops($this->message, Array($this->proptags["commonend"] => $utcfirstoccenddatetime ));
			
			// update real begin and real end date
			mapi_setprops($this->message, Array($this->proptags["startdate_recurring"] => $utcstart));
			mapi_setprops($this->message, Array($this->proptags["enddate_recurring"] => $utcend));
			
			// recurrencetype
			// Strange enough is the property recurrencetype, (type-0x9) and not the CDO recurrencetype
			mapi_setprops($this->message, Array($this->proptags["recurrencetype"] => intval($this->recur["type"]) - 0x9));

			// set named prop 0x8510 to 369, needed for Outlook to ask for single or total recurrence when deleting
			mapi_setprops($this->message, Array($this->proptags["prop8510"] => 369));
			
			// FlagDueBy is datetime of the first reminder occurrence. Outlook gives on this time a reminder popup dialog
			$reminderprops = mapi_getprops($this->message, array($this->proptags["reminder_minutes"]) );
			if(isset($reminderprops[$this->proptags["reminder_minutes"]]) ) {
				//TODO: $utcfirstoccstartdatetime must the first upcomming occurrence, so you need the current 
				//      client time. When you create a recurrent before the current date, the FlagDueBy must be the 
				//      first upcomming occurrence after the current date.
				mapi_setprops($this->message, Array($this->proptags["flagdueby"] => $utcfirstoccstartdatetime - ($reminderprops[$this->proptags["reminder_minutes"]] * 60) ));
			}
			
			
			// Default data
			// Second item (0x08) indicates the Outlook version (see documentation at the bottom of this file for more information) 
			$rdata .= pack("VCCCC", 0x00003006, 0x08, 0x30, 0x00, 0x00);
		
			// Set start and endtime in minutes
			$rdata .= pack("VV", intval($this->recur["startocc"]), intval($this->recur["endocc"]));
			
			// Detailed exception data
			
			$changed_items = $this->recur["changed_occurences"];
				
			$rdata .= pack("v", count($changed_items));
			
			$string_changed = false;
			foreach($changed_items as $changed_item)
			{
				// Set start and end time of exception
	  			$rdata .= pack("V", $this->unixDataToRecurData($changed_item["start"]));
	  			$rdata .= pack("V", $this->unixDataToRecurData($changed_item["end"]));
	  			$rdata .= pack("V", $this->unixDataToRecurData($changed_item["basedate"]));
	  		
	  			//Bitmask
	  			$bitmask = 0;
	  			
	  			// Check for changed strings
	  			if(isset($changed_item["subject"]))	{
  					$bitmask |= 1 << 0;
	  			}
	  			
	  			if(isset($changed_item["reminder_set"])) {
  					$bitmask |= 1 << 3;
	  			}
	  			
	  			if(isset($changed_item["location"])) {
  					$bitmask |= 1 << 4;
	  			}
	  			
	  			if(isset($changed_item["busystatus"])) {
	  				$bitmask |= 1 << 5;
	  			}
	  			
	  			if(isset($changed_item["alldayevent"]))	{
  					$bitmask |= 1 << 7;
	  			}
	  			
	  			if(isset($changed_item["label"])) {
  					$bitmask |= 1 << 8;
	  			}
	  			
	  			$rdata .= pack("v", $bitmask);
	  			
	  			// Set "subject"
	    		if(isset($changed_item["subject"]))	{
	    			$length = strlen($changed_item["subject"]);
	    			$rdata .= pack("vv", $length + 1, $length);
	
					$chars = preg_split('//', $changed_item["subject"], -1, PREG_SPLIT_NO_EMPTY);
	    			for($j = 0; $j < $length; $j++)
	    			{
	    				$rdata .= pack("C", ord($chars[$j]));
	    			}
						
	    			$string_changed = true;
	    		}
	    		
	    		if(isset($changed_item["reminder_set"])) {
	    			$rdata .= pack("V", $changed_item["reminder_set"]);
	    		}
	    		
	    		if(isset($changed_item["location"])) {
	    			$length = strlen($changed_item["location"]);
	    			$rdata .= pack("vv", $length + 1, $length);
	
					$chars = preg_split('//', $changed_item["location"], -1, PREG_SPLIT_NO_EMPTY);
	    			for($j = 0; $j < $length; $j++)
	    			{
	    				$rdata .= pack("C", ord($chars[$j]));
	    			}
						
	    			$string_changed = true;
	    		}
	    		
	    		if(isset($changed_item["busystatus"])) {
	    			$rdata .= pack("V", $changed_item["busystatus"]);
				}
	    			
	    		if(isset($changed_item["alldayevent"]))	{
	    			$rdata .= pack("V", $changed_item["alldayevent"]);
	    		}
	    		
	    		if(isset($changed_item["label"])) {
	    			$rdata .= pack("V", $changed_item["label"]);
	    		}
			}
			
			$rdata .= pack("V", 0);

            foreach($changed_items as $changed_item)
            {
                $rdata .= pack("V", 0);
                if(isset($changed_item["subject"]) || isset($changed_item["location"])) {
                    $rdata .= pack("V", $this->unixDataToRecurData($changed_item["start"]));
                    $rdata .= pack("V", $this->unixDataToRecurData($changed_item["end"]));
                    $rdata .= pack("V", $this->unixDataToRecurData($changed_item["basedate"]));
                }

                if(isset($changed_item["subject"])) {
                    $rdata .= pack("v", strlen($changed_item["subject"]));
                    $chars = preg_split('//', $changed_item["subject"], -1, PREG_SPLIT_NO_EMPTY);
                    
                    //Pack Unicode Char: convert to ascii and pack it like a short
                    for($j = 0; $j < count($chars); $j++)
                    {
                        $rdata .= pack("v", ord($chars[$j]));
                    }
                }
                    
                if(isset($changed_item["location"])) {
                    $rdata .= pack("v", strlen($changed_item["location"]));
                    $chars = preg_split('//', $changed_item["location"], -1, PREG_SPLIT_NO_EMPTY);

                    //Pack Unicode Char: convert to ascii and pack it like a short
                    for($j = 0; $j < count($chars); $j++)
                    {
                        $rdata .= pack("v", ord($chars[$j]));
                    }
                }
                    
                if(isset($changed_item["subject"]) || isset($changed_item["location"])) {
                    $rdata .= pack("V", 0);
                }
            }
			
			$rdata .= pack("V", 0);
		
			// Set props
			mapi_setprops($this->message, Array($this->proptags["recurring_data"] => $rdata, $this->proptags["recurring"] => true));
			if(isset($this->tz)){
				$timezone = "GMT";
				if ($this->tz["timezone"]!=0){
					// Create user readable timezone information
					$timezone = sprintf("(GMT %s%02d:%02d)",	(-$this->tz["timezone"]>0 ? "+" : "-"), 
															abs($this->tz["timezone"]/60), 
															abs($this->tz["timezone"]%60));
				}
	        	mapi_setprops($this->message, Array($this->proptags["timezone_data"] => $this->getTimezoneData($this->tz),
													$this->proptags["timezone"] => $timezone));
			}

		} 
		
		/**
		 * daysInMonth
		 * 
		 * Returns the number of days in the upcoming number of months. If you specify 1 month as 
		 * $months it will give you the number of days in the month of $date. If you specify more it
		 * will also count the days in the upcomming months and add that to the number of days. So 
		 * if you have a date in march and you specify $months as 2 it will return 61.
		 * @param Integer $date Specified date as timestamp from which you want to know the number 
		 * of days in the month.
		 * @param Integer $months Number of months you want to know the number of days in.
		 * @returns Integer Number of days in the specified amount of months.
		 */
		function daysInMonth($date, $months) {
		    $days = 0;
		    
		    for($i=0;$i<$months;$i++) {
		        $days += date("t", $date + $days * 24 * 60 * 60);
		    }
		    
		    return $days;
		}
		
		// Converts MAPI-style 'minutes' into the month of the year [0..11]
		function monthOfYear($minutes) {
		    $d = gmmktime(0,0,0,1,1,2001); // The year 2001 was a non-leap year, and the minutes provided are always in non-leap-year-minutes
		    
		    $d += $minutes*60;
		    
		    $dtime = $this->gmtime($d);
		    
		    return $dtime["tm_mon"];
		}

		function sortStarttime($a, $b)
		{
			$aTime = $a[$this->proptags["startdate"]];
			$bTime = $b[$this->proptags["startdate"]];

			return $aTime==$bTime?0:($aTime>$bTime?1:-1);
		}
		
		function sortExceptionStart($a, $b)
		{
		    return $a["start"] == $b["start"] ? 0 : ($a["start"]  > $b["start"] ? 1 : -1 );
		}
		
		/**
		 * Function which sets recipients for an exception, also checks for deleted recipients.
		 *
		 * @param resource $message exception attachment of recurring item
		 * @param array $exception_recips list of recipients
		 */
		function setExceptionRecipients($message, $exception_recips)
		{
			$deletedRecipients = array();
			$recipientTable = mapi_message_getrecipienttable($message);
			$recipientRows = mapi_table_queryallrows($recipientTable, array(PR_ENTRYID, PR_DISPLAY_NAME, PR_EMAIL_ADDRESS, PR_RECIPIENT_ENTRYID, PR_RECIPIENT_TYPE, PR_SEND_INTERNET_ENCODING, PR_SEND_RICH_INFO, PR_RECIPIENT_DISPLAY_NAME, PR_ADDRTYPE, PR_DISPLAY_TYPE, PR_RECIPIENT_TRACKSTATUS, PR_RECIPIENT_FLAGS, PR_ROWID));

			if (count($recipientRows) == 0) {
				$recipientTable = mapi_message_getrecipienttable($this->message);
				$recipientRows = mapi_table_queryallrows($recipientTable, array(PR_ENTRYID, PR_DISPLAY_NAME, PR_EMAIL_ADDRESS, PR_RECIPIENT_ENTRYID, PR_RECIPIENT_TYPE, PR_SEND_INTERNET_ENCODING, PR_SEND_RICH_INFO, PR_RECIPIENT_DISPLAY_NAME, PR_ADDRTYPE, PR_DISPLAY_TYPE, PR_RECIPIENT_TRACKSTATUS, PR_RECIPIENT_FLAGS, PR_ROWID));
			}

			if (count($exception_recips) > 0) {
				foreach($recipientRows as $key => $recipient) {
					$found = false;
					foreach($exception_recips as $excep_recip) {
						if ($recipient[PR_ENTRYID] == $excep_recip[PR_ENTRYID])
							$found = true;
					}

					if (!$found) {
						if (count($deletedRecipients) == 0) {
							$recipient[PR_RECIPIENT_FLAGS] = $recipient[PR_RECIPIENT_FLAGS] != 545 ? recipSendable | recipExceptionalDeleted : 545;
							$recipient[PR_RECIPIENT_TRACKSTATUS] = 0;		// No Response required
							$deletedRecipients[] = $recipient;
						}

						foreach($deletedRecipients as $recip) {
							if ($recip[PR_ENTRYID] != $recipient[PR_ENTRYID]){
								$recipient[PR_RECIPIENT_FLAGS] = $recipient[PR_RECIPIENT_FLAGS] != 545 ? recipSendable | recipExceptionalDeleted : 545;			// recipExceptionDeleted
								$recipient[PR_RECIPIENT_TRACKSTATUS] = 0;		// No Response required
								$deletedRecipients[] = $recipient;
							}
						}
					}

					// First remove this recipient from message
					mapi_message_modifyrecipients($message, MODRECIP_REMOVE, array($recipient));
				}
				$exception_recips = array_merge($exception_recips, $deletedRecipients);
			} else {
				$exception_recips = $recipientRows;
			}

			if (count($exception_recips) > 0) {
				// Set the new list of recipients on the exception message, this also removes the existing recipients
				mapi_message_modifyrecipients($message, 0, $exception_recips);
			}
		}

		/**
		 * Function returns basedates of all changed occurrences
		 *@return array array(
							0 => 123459321
						)
		 */
		function getAllExceptions()
		{
			$result = false;
			if (count($this->recur["changed_occurences"]) > 0) {
				$result = array();
				foreach($this->recur["changed_occurences"] as $exception) {
					$result[] = $exception["basedate"];
				}
				return $result;
			}
			return $result;
		}
	}
	
	/*
	
	From http://www.ohelp-one.com/new-6765483-3268.html:
	
	Recurrence Data Structure Offset Type Value
	
	0 ULONG (?) Constant : { 0x04, 0x30, 0x04, 0x30}
	
	4 UCHAR 0x0A + recurrence type: 0x0A for daily, 0x0B for weekly, 0x0C for
	monthly, 0x0D for yearly
	
	5 UCHAR Constant: { 0x20}
	
	6 ULONG Seems to be a variant of the recurrence type: 1 for daily every n
	days, 2 for daily every weekday and weekly, 3 for monthly or yearly. The
	special exception is regenerating tasks that regenerate on a weekly basis: 0
	is used in that case (I have no idea why).
	
	Here's the recurrence-type-specific data. Because the daily every N days
	data are 4 bytes shorter than the data for the other types, the offsets for
	the rest of the data will be 4 bytes off depending on the recurrence type.
	
	Daily every N days: 
	
	10 ULONG ( N - 1) * ( 24 * 60). I'm not sure what this is used for, but it's consistent.
	
	14 ULONG N * 24 * 60: minutes between recurrences
	
	18 ULONG 0 for all events and non-regenerating recurring tasks. 1 for
	regenerating tasks.
	
	Daily every weekday (this is essentially a subtype of weekly recurrence): 
	
	10 ULONG 6 * 24 * 60: minutes between recurrences ( a week... sort of)
	
	14 ULONG 1: recur every week (corresponds to the second parameter for weekly
	recurrence)
	
	18 ULONG 0 for all events and non-regenerating recurring tasks. 1 for
	regenerating tasks.
	
	22 ULONG 0x3E: bitmask for recurring every weekday (corresponds to fourth
	parameter for weekly recurrence)
	
	Weekly every N weeks for all events and non-regenerating tasks: 
	
	10 ULONG 6 * 24 * 60: minutes between recurrences (a week... sort of)
	
	14 ULONG N: recurrence interval
	
	18 ULONG Constant: 0
	
	22 ULONG Bitmask for determining which days of the week the event recurs on
	( 1 << dayOfWeek, where Sunday is 0).
	
	Weekly every N weeks for regenerating tasks: 10 ULONG Constant: 0
	
	14 ULONG N * 7 * 24 * 60: recurrence interval in minutes between occurrences
	
	18 ULONG Constant: 1
	
	Monthly every N months on day D: 
	
	10 ULONG This is the most complicated value
	in the entire mess. It's basically a very complicated way of stating the
	recurrence interval. I tweaked fbs' basic algorithm. DateTime::MonthInDays
	simply returns the number of days in a given month, e.g. 31 for July for 28
	for February (the algorithm doesn't take into account leap years, but it
	doesn't seem to matter). My DateTime object, like Microsoft's COleDateTime,
	uses 1-based months (i.e. January is 1, not 0). With that in mind, this
	works:
	
	long monthIndex = ( ( ( ( 12 % schedule-=GetInterval()) *
	
	( ( schedule-=GetStartDate().GetYear() - 1601) %
	
	schedule-=GetInterval())) % schedule-=GetInterval()) +
	
	( schedule-=GetStartDate().GetMonth() - 1)) % schedule-=GetInterval();
	
	for( int i = 0; i < monthIndex; i++)
	
	{
	
	value += DateTime::GetDaysInMonth( ( i % 12) + 1) * 24 * 60;
	
	}
	
	This should work for any recurrence interval, including those greater than
	12.
	
	14 ULONG N: recurrence interval
	
	18 ULONG 0 for all events and non-regenerating recurring tasks. 1 for
	regenerating tasks.
	
	22 ULONG D: day of month the event recurs on (if this value is greater than
	the number of days in a given month [e.g. 31 for and recurs in June], then
	the event will recur on the last day of the month)
	
	Monthly every N months on the Xth Y (e.g. "2nd Tuesday"): 
	
	10 ULONG See above: same as for monthly every N months on day D
	
	14 ULONG N: recurrence interval
	
	18 ULONG 0 for all events and non-regenerating recurring tasks. 1 for
	regenerating tasks.
	
	22 ULONG Y: bitmask for determining which day of the week the event recurs
	on (see weekly every N weeks). Some useful values are 0x7F for any day, 0x3E
	for a weekday, or 0x41 for a weekend day.
	
	26 ULONG X: 1 for first occurrence, 2 for second, etc. 5 for last
	occurrence. E.g. for "2nd Tuesday", you should have values of 0x04 for the
	prior value and 2 for this one.
	
	Yearly on day D of month M: 
	
	10 ULONG M (sort of): This is another messy
	value. It's the number of minute since the startning of the year to the
	given month. For an explanation of GetDaysInMonth, see monthly every N
	months. This will work:
	
	ULONG monthOfYearInMinutes = 0;
	
	for( int i = DateTime::cJanuary; i < schedule-=GetMonth(); i++)
	
	{
	
	monthOfYearInMinutes += DateTime::GetDaysInMonth( i) * 24 * 60;
	
	}
	
	
	
	14 ULONG 12: recurrence interval in months. Naturally, 12.
	
	18 ULONG 0 for all events and non-regenerating recurring tasks. 1 for
	regenerating tasks.
	
	22 ULONG D: day of month the event recurs on. See monthly every N months on
	day D.
	
	Yearly on the Xth Y of month M: 10 ULONG M (sort of): See yearly on day D of
	month M.
	
	14 ULONG 12: recurrence interval in months. Naturally, 12.
	
	18 ULONG Constant: 0
	
	22 ULONG Y: see monthly every N months on the Xth Y.
	
	26 ULONG X: see monthly every N months on the Xth Y.
	
	After these recurrence-type-specific values, the offsets will change
	depending on the type. For every type except daily every N days, the offsets
	will grow by at least 4. For those types using the Xth Y, the offsets will
	grow by an additional 4, for a total of 8. The offsets for the rest of these
	values will be given for the most basic case, daily every N days, i.e.
	without any growth. Adjust as necessary. Also, the presence of exceptions
	will change the offsets following the exception data by a variable number of
	bytes, so the offsets given in the table are accurate only for those
	recurrence patterns without any exceptions. 
	
	
	22 UCHAR Type of pattern termination: 0x21 for terminating on a given date, 0x22 for terminating
	after a given number of recurrences, or 0x23 for never terminating
	(recurring infinitely)
	
	23 UCHARx3 Constant: { 0x20, 0x00, 0x00}
	
	26 ULONG Number of occurrences in pattern: 0 for infinite recurrence,
	otherwise supply the value, even if it terminates on a given date, not after
	a given number
	
	30 ULONG Constant: 0
	
	34 ULONG Number of exceptions to pattern (i.e. deleted or changed
	occurrences)
	
	.... ULONGxN Base date of each exception, given in hundreds of nanoseconds
	since 1601, so see below to turn them into a comprehensible format. The base
	date of an exception is the date (and only the date-- not the time) the
	exception would have occurred on in the pattern. They must occur in
	ascending order.
	
	38 ULONG Number of changed exceptions (i.e. total number of exceptions -
	number of deleted exceptions): if there are changed exceptions, again, more
	data will be needed, but that will wait
	
	.... ULONGxN Start date (and only the date-- not the time) of each changed
	exception, i.e. the exceptions which aren't deleted. These must also occur
	in ascending order. If all of the exceptions are deleted, this data will be
	absent. If present, they will be in the format above. Any dates that are in
	the first list but not in the second are exceptions that have been deleted
	(i.e. the difference between the two sets). Note that this is the start date
	(including time), not the base date. Given that the values are unordered and
	that they can't be matched up against the previous list in this iteration of
	the recurrence data (they could in previous ones), it is very difficult to
	tell which exceptions are deleted and which are changed. Fortunately, for
	this new format, the base dates are given on the attachment representing the
	changed exception (described below), so you can simply ignore this list of
	changed exceptions. Just create a list of exceptions from the previous list
	and assume they're all deleted unless you encounter an attachment with a
	matching base date later on.
	
	42 ULONG Start date of pattern given in hundreds of nanoseconds since 1601;
	see below for an explanation.
	
	46 ULONG End date of pattern: see start date of pattern
	
	50 ULONG Constant: { 0x06, 0x30, 0x00, 0x00}
	
	NOTE: I find the following 8-byte sequence of bytes to be very useful for
	orienting myself when looking at the raw data. If you can find { 0x06, 0x30,
	0x00, 0x00, 0x08, 0x30, 0x00, 0x00}, you can use these tables to work either
	forwards or backwards to find the data you need. The sequence sort of
	delineates certain critical exception-related data and delineates the
	exceptions themselves from the rest of the data and is relatively easy to
	find. If you're going to be meddling in here a lot, I suggest making a
	friend of ol' 0x00003006.
	
	54 UCHAR This number is some kind of version indicator. Use 0x08 for Outlook
	2003. I believe 0x06 is Outlook 2000 and possibly 98, while 0x07 is Outlook
	XP. This number must be consistent with the features of the data structure
	generated by the version of Outlook indicated thereby-- there are subtle
	differences between the structures, and, if the version doesn't match the
	data, Outlook will sometimes failto read the structure.
	
	55 UCHARx3 Constant: { 0x30, 0x00, 0x00}
	
	58 ULONG Start time of occurrence in minutes: e.g. 0 for midnight or 720 for
	12 PM
	
	62 ULONG End time of occurrence in minutes: i.e. start time + duration, e.g.
	900 for an event that starts at 12 PM and ends at 3PM
	
	Exception Data 66 USHORT Number of changed exceptions: essentially a check
	on the prior occurrence of this value; should be equivalent.
	
	NOTE: The following structure will occur N many times (where N = number of
	changed exceptions), and each structure can be of variable length.
	
	.... ULONG Start date of changed exception given in hundreds of nanoseconds
	since 1601
	
	.... ULONG End date of changed exception given in hundreds of nanoseconds
	since 1601
	
	.... ULONG This is a value I don't clearly understand. It seems to be some
	kind of archival value that matches the start time most of the time, but
	will lag behind when the start time is changed and then match up again under
	certain conditions later. In any case, setting to the same value as the
	start time seems to work just fine (more information on this value would be
	appreciated).
	
	.... USHORT Bitmask of changes to the exception (see below). This will be 0
	if the only changes to the exception were to its start or end time.
	
	.... ULONGxN Numeric values (e.g. label or minutes to remind before the
	event) changed in the exception. These will occur in the order of their
	corresponding bits (see below). If no numeric values were changed, then
	these values will be absent.
	
	NOTE: The following three values constitute a single sub-structure that will
	occur N many times, where N is the number of strings that are changed in the
	exception. Since there are at most 2 string values that can be excepted
	(i.e. subject [or description], and location), there can at most be two of
	these, but there may be none.
	
	.... USHORT Length of changed string value with NULL character
	
	.... USHORT Length of changed string value without NULL character (i.e.
	previous value - 1)
	
	.... CHARxN Changed string value (without NULL terminator)
	
	Unicode Data NOTE: If a string value was changed on an exception, those
	changed string values will reappear here in Unicode format after 8 bytes of
	NULL padding (possibly a Unicode terminator?). For each exception with a
	changed string value, there will be an identifier, followed by the changed
	strings in Unicode. The strings will occur in the order of their
	corresponding bits (see below). E.g., if both subject and location were
	changed in the exception, there would be the 3-ULONG identifier, then the
	length of the subject, then the subject, then the length of the location,
	then the location.
	
	70 ULONGx2 Constant: { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}. This
	padding serves as a barrier between the older data structure and the
	appended Unicode data. This is the same sequence as the Unicode terminator,
	but I'm not sure whether that's its identity or not.
	
	.... ULONGx3 These are the three times used to identify the exception above:
	start date, end date, and repeated start date. These should be the same as
	they were above.
	
	.... USHORT Length of changed string value without NULL character. This is
	given as count of WCHARs, so it should be identical to the value above.
	
	.... WCHARxN Changed string value in Unicode (without NULL terminator)
	
	Terminator ... ULONGxN Constant: { 0x00, 0x00, 0x00, 0x00}. 4 bytes of NULL
	padding per changed exception. If there were no changed exceptions, all
	you'll need is the final terminator below.
	
	.... ULONGx2 Constant: { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}.
	
	*/
?>
