<?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."
 * 
 * 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
	include_once('mapi/class.recurrence.php');
	
	/**
	 * Appointment ItemModule
	 * Module which openes, creates, saves and deletes an item. It 
	 * extends the Module class.
	 */
	class AppointmentItemModule extends ItemModule
	{
		/**
		 * Constructor
		 * @param int $id unique id.
		 * @param array $data list of all actions.
		 */
		function AppointmentItemModule($id, $data)
		{
			$this->properties = $GLOBALS["properties"]->getAppointmentProperties();
			
			parent::ItemModule($id, $data);
		}
		
		function open($store, $entryid, $action)
		{
			if(isset($action["attachments"]) && isset($action["attachments"]["attach_num"]) && isset($action["attachments"]["attach_num"][0])) {
				$basedate = $action["attachments"]["attach_num"][0];
				
				$message = mapi_msgstore_openentry($store, $entryid);
				
				$recur = new Recurrence($store, $message);
				
				$exceptionatt = $recur->getExceptionAttachment($basedate);

				if($exceptionatt) {
					// Existing exception (open existing item, which includes basedate)
					$exception = mapi_attach_openobj($exceptionatt, 0);
				
    	            $data = array();
        	        $data["attributes"] = array("type" => "item");
					// First add all the properties from the series-message and than overwrite them with the ones form the exception
					$data["item"] = $GLOBALS["operations"]->getMessageProps($store, $message, $this->properties, true);
            	    $exceptionProps = $GLOBALS["operations"]->getMessageProps($store, $exception, $this->properties, true);

					// HACK: when occurrence is dragged in OL, recipients are not set in occurrence
					if (isset($exceptionProps['recipients']) && count($exceptionProps['recipients']['recipient']) == 0)
						unset($exceptionProps['recipients']);
					// HACK: When body is empty use the body of the series-message
					if(strlen($exceptionProps['body']) == 0){
						unset($exceptionProps['body'], $exceptionProps['isHTML']);
					}
					$data["item"] = array_merge($data['item'], $exceptionProps);
                
            	    // The entryid should be the entryid of the main message, not that of the attachment
            	    $data["item"]["entryid"] = bin2hex($entryid);
                    
                    // Make sure we are using the passed basedate and not something wrong in the opened item
                    $data["item"]["basedate"] = $basedate;
                     
            	    array_push($this->responseData["action"], $data);
					$GLOBALS["bus"]->addData($this->responseData);
					return;
				}
				
				// Recurring but non-existing exception (same as normal open, but add basedate, startdate and enddate)
				$data = array();
				$data["attributes"] = array("type" => "item");
				$data["item"] = $GLOBALS["operations"]->getMessageProps($store, $message, $this->properties, true);
				$data["item"]["basedate"]["attributes"]["unixtime"] = $basedate;
				$data["item"]["basedate"]["_content"] = strftime("%a %d-%m-%Y %H:%M", $basedate);
				$data["item"]["startdate"]["attributes"]["unixtime"] = $recur->getOccurrenceStart($basedate);
				$data["item"]["startdate"]["_content"] = strftime("%a %d-%m-%Y %H:%M", $recur->getOccurrenceStart($basedate));
				$data["item"]["duedate"]["attributes"]["unixtime"] = $recur->getOccurrenceEnd($basedate);
				$data["item"]["duedate"]["_content"] = strftime("%a %d-%m-%Y %H:%M", $recur->getOccurrenceEnd($basedate));
				$data["item"]["commonstart"] = $data["item"]["startdate"];
				$data["item"]["commonend"] = $data["item"]["duedate"];
				unset($data["item"]["reminder_time"]);
				
				array_push($this->responseData["action"], $data);
				$GLOBALS["bus"]->addData($this->responseData);
				return;
			}
			
			$message = mapi_msgstore_openentry($store, $entryid);
			
			// Normal item (may be the 'entire series' for a recurring item)
			$data = array();
			$data["attributes"] = array("type" => "item");

			// Get the standard properties
			$data["item"] = $GLOBALS["operations"]->getMessageProps($store, $message, $this->properties, true);

			// Get the recurrence information			
			$recur = new Recurrence($store, $message);
			$recurpattern = $recur->getRecurrence();
			$tz = $recur->tz; // no function to do this at the moment

			// Add the recurrence pattern to the data
			if(isset($recurpattern) && is_array($recurpattern))			
				$data["item"] += $recurpattern;

			// Add the timezone information to the data
			if(isset($tz) && is_array($tz))			
				$data["item"] += $tz;
			
			// Send the data
			array_push($this->responseData["action"], $data);
			$GLOBALS["bus"]->addData($this->responseData);
		}
		
		function save($store, $parententryid, $action)
		{
			$result = false;

			// Save appointment (saveAppointment takes care of creating/modifying exceptions to recurring
			// items if necessary)
			$messageProps = $GLOBALS["operations"]->saveAppointment($store, $parententryid, $action);

			// Notify the bus if the save was OK
			if($messageProps && !(is_array($messageProps) && isset($messageProps['error'])) ){
				$GLOBALS["bus"]->notify(bin2hex($parententryid), TABLE_SAVE, $messageProps);
				$result = true;
			}


			// Recurring but non-existing exception (same as normal open, but add basedate, startdate and enddate)
			$data = array();
			$data["attributes"] = array("type" => "saved");
			$data["meeting_request_saved"] = ($result) ? '1' : '0';
			$data["sent_meetingrequest"] = ($result && !empty($action['send'])) ? '1' : '0';
			if(is_array($messageProps) && isset($messageProps['error'])){
				$data["errorcode"] = $messageProps['error'];
				$data["displayname"] = $messageProps['displayname'];
			}
			
			array_push($this->responseData["action"], $data);
			$GLOBALS["bus"]->addData($this->responseData);

			return $result;
		}
	}
?>
