<?php
/**
 * ###############################################
 *
 * SWIFT Framework
 * _______________________________________________
 *
 * @author		Varun Shoor
 *
 * @package		SWIFT
 * @copyright	Copyright (c) 2001-2012, Kayako
 * @license		http://www.kayako.com/license
 * @link		http://www.kayako.com
 *
 * ###############################################
 */

/**
 * The Ticket List Retrieval Controller
 *
 * @author Varun Shoor
 */
class Controller_Push extends Controller_staffapi
{
	/**
	 * Constructor
	 *
	 * @author Varun Shoor
	 * @return bool "true" on Success, "false" otherwise
	 */
	public function __construct()
	{
		parent::__construct();

		$this->Language->Load('staff_ticketsmain');
		$this->Language->Load('staff_ticketsmanage');
		$this->Language->Load('staff_ticketssearch');

		SWIFT_Ticket::LoadLanguageTable();

		return true;
	}

	/**
	 * Destructor
	 *
	 * @author Varun Shoor
	 * @return bool "true" on Success, "false" otherwise
	 */
	public function __destruct()
	{
		parent::__destruct();

		return true;
	}

	/**
	 * Initiate the Push
	 *
	 * @author Varun Shoor
	 * @return bool "true" on Success, "false" otherwise
	 * @throws SWIFT_Exception If the Class is not Loaded
	 */
	public function Index()
	{
		$_SWIFT = SWIFT::GetInstance();

		if (!$this->GetIsClassLoaded())
		{
			throw new SWIFT_Exception(SWIFT_CLASSNOTLOADED);

			return false;
		}

		$_payLoadXML = '';
		if (isset($_POST['payload'])) {
			$_payLoadXML = $_POST['payload'];
		}

		$_PushDataObject = simplexml_load_string($_payLoadXML);

		$_statusMessage = '';
		$_statusCode = 1;

		$_departmentCache = $this->Cache->Get('departmentcache');
		$_ticketStatusCache = $this->Cache->Get('statuscache');
		$_ticketPriorityCache = $this->Cache->Get('prioritycache');
		$_ticketTypeCache = $this->Cache->Get('tickettypecache');
		$_staffCache = $this->Cache->Get('staffcache');
		$_emailQueueCache = $this->Cache->Get('queuecache');

		$_createStaffAPIIDMap = $_returnTicketIDList = $_extendedTicketMapper = array();


		/**
		 * ---------------------------------------------
		 * Process Create
		 * ---------------------------------------------
		 */
		/**
		 * BUG FIX - Ravi Sharma <ravi.sharma@kayako.com>
		 *
		 * SWIFT-2599 Staff is able to delete the ticket from Android phone even if he does not have the permission
		 */
		if (isset($_PushDataObject->create) && $_SWIFT->Staff->GetPermission('staff_tcaninsertticket') != '0') {
			foreach ($_PushDataObject->create as $_CreateObject) {
				$_staffAPIID = (string) $_CreateObject->attributes()->staffapiid;

				$_subject = (string) $_CreateObject->subject;
				$_fullName = (string) $_CreateObject->fullname;
				$_email = (string) $_CreateObject->email;

				$_departmentID = (int) $_CreateObject->departmentid;
				$_ticketStatusID = (int) $_CreateObject->ticketstatusid;
				$_ticketPriorityID = (int) $_CreateObject->ticketpriorityid;
				$_ticketTypeID = (int) $_CreateObject->tickettypeid;
				$_ownerStaffID = (int) $_CreateObject->ownerstaffid;
				$_emailQueueID = (int) $_CreateObject->emailqueueid;

				if (!isset($_departmentCache[$_departmentID])) {
					$_statusCode = '0';
					$_statusMessage .= 'Unable to create ticket: ' . $_staffAPIID . ', department id is invalid.' . SWIFT_CRLF;

					continue;
				}

				if (!isset($_ticketStatusCache[$_ticketStatusID])) {
					$_statusCode = '0';
					$_statusMessage .= 'Unable to create ticket: ' . $_staffAPIID . ', ticket status id is invalid.' . SWIFT_CRLF;

					continue;
				}

				if (!isset($_ticketPriorityCache[$_ticketPriorityID])) {
					$_statusCode = '0';
					$_statusMessage .= 'Unable to create ticket: ' . $_staffAPIID . ', ticket priority id is invalid.' . SWIFT_CRLF;

					continue;
				}

				if (!isset($_ticketTypeCache[$_ticketTypeID])) {
					$_statusCode = '0';
					$_statusMessage .= 'Unable to create ticket: ' . $_staffAPIID . ', ticket type id is invalid.' . SWIFT_CRLF;

					continue;
				}

				$_assignedDepartmentIDList = array();
				if ($_ownerStaffID != '0' && !isset($_staffCache[$_ownerStaffID])) {
					$_statusCode = '0';
					$_statusMessage .= 'Unable to create ticket: ' . $_staffAPIID . ', owner staff id is invalid.' . SWIFT_CRLF;

					continue;
				} else if ($_ownerStaffID != '0') {
					$_assignedDepartmentIDList = SWIFT_Staff::GetAssignedDepartmentsOnStaffID($_ownerStaffID);
				}

				$_creator = (string) $_CreateObject->creator;
				$_userID = $_staffID = 0;

				/*
				 * BUG FIX - Simaranjit Singh
				 *
				 * SWIFT-4151 : Phone number in user profile does not get updated if a ticket is created using Staff API.
				 */
				$_phoneNumber = '';
				if (isset($_CreateObject->phonenumber)) {
					$_phoneNumber = (string) $_CreateObject->phonenumber;
				}

				// Get the User Object
				$_SWIFT_UserObject = false;
				if (isset($_CreateObject->userid)) {
					try {
						$_SWIFT_UserObject = new SWIFT_User(new SWIFT_DataID($_CreateObject->userid));
						$_userID           = $_CreateObject->userid;
					} catch (SWIFT_Exception $_SWIFT_ExceptionObject) {
					}

					if (!$_SWIFT_UserObject instanceof SWIFT_User || !$_SWIFT_UserObject->GetIsClassLoaded()) {
						$_SWIFT_TemplateGroupObject = new SWIFT_TemplateGroup(SWIFT_TemplateGroup::GetDefaultGroupID());
						if (!$_SWIFT_TemplateGroupObject instanceof SWIFT_TemplateGroup || !$_SWIFT_TemplateGroupObject->GetIsClassLoaded()) {
							throw new SWIFT_Exception('Unable to load master template group object');
						}

						$_userID           = SWIFT_Ticket::GetOrCreateUserID($_fullName, $_email, $_SWIFT_TemplateGroupObject->GetRegisteredUserGroupID(), false, false, $_phoneNumber);
						$_SWIFT_UserObject = new SWIFT_User(new SWIFT_DataID($_userID));
					}
				} else if ($_creator != 'staff') {
					$_userID = SWIFT_Ticket::GetOrCreateUserID($_fullName, $_email, SWIFT_UserGroup::RetrieveDefaultUserGroupID(SWIFT_UserGroup::TYPE_REGISTERED), false, false, $_phoneNumber);
				}

				if (isset($_CreateObject->staffid)) {
					$_staffID = (int) $_CreateObject->staffid;
				}

				$_ticketType = (string) $_CreateObject->type;

				$_sendAutoresponder = true;
				if (isset($_CreateObject->sendautoresponder)) {
					$_sendAutoresponder = (int) $_CreateObject->sendautoresponder;
				}

				$_flagType = 0;
				if (isset($_CreateObject->flagtype)) {
					$_flagType = (int) $_CreateObject->flagtype;
				}

				$_ccToList = array();
				if (isset($_CreateObject->ccto)) {
					foreach ($_CreateObject->ccto as $_CCToObject) {
						$_ccToEmail = (string) $_CCToObject;

						if (!IsEmailValid($_ccToEmail)) {
							continue;
						}

						$_ccToList[] = $_ccToEmail;
					}
				}

				$_bccToList = array();
				if (isset($_CreateObject->bccto)) {
					foreach ($_CreateObject->bccto as $_BCCToObject) {
						$_bccToEmail = (string) $_BCCToObject;

						if (!IsEmailValid($_bccToEmail)) {
							continue;
						}

						$_bccToList[] = $_bccToEmail;
					}
				}

				$_resolutionDue = $_replyDue = -1;
				if (isset($_CreateObject->resolutiondue)) {
					$_resolutionDue = (int) $_CreateObject->resolutiondue;
				}

				if (isset($_CreateObject->replydue)) {
					$_replyDue = (int) $_CreateObject->replydue;
				}

				$_replyContents = (string) $_CreateObject->reply->contents;

				$_finalTicketType = SWIFT_Ticket::TYPE_DEFAULT;
				if ($_ticketType == 'phone') {
					$_finalTicketType = SWIFT_Ticket::TYPE_PHONE;
				}

				$_finalCreatorType = SWIFT_Ticket::CREATOR_USER;
				if ($_creator == 'staff') {
					$_finalCreatorType = SWIFT_Ticket::CREATOR_STAFF;
				}

				$_destinationEmail = '';
				$_fromEmail = $_email;
				if ($_creator == 'staff') {
					$_destinationEmail = $_email;
					$_fromEmail = $_SWIFT->Staff->GetProperty('email');
				}

				$_fromEmailAddress = self::_GetDispatchFromEmail($_departmentID);

				if (!in_array($_departmentID, $_assignedDepartmentIDList)) {
					$_ownerStaffID = 0;
				}

				$_SWIFT_TicketObject = SWIFT_Ticket::Create($_subject, $_fullName, $_fromEmail, $_replyContents, $_ownerStaffID, $_departmentID, $_ticketStatusID, $_ticketPriorityID,
															$_ticketTypeID, $_userID, $_staffID, $_finalTicketType, $_finalCreatorType, SWIFT_Ticket::CREATIONMODE_STAFFAPI,
															$_phoneNumber, $_emailQueueID, $_sendAutoresponder, $_destinationEmail, false);
				if (!$_SWIFT_TicketObject instanceof SWIFT_Ticket || !$_SWIFT_TicketObject->GetIsClassLoaded()) {
					$_statusCode = '0';
					$_statusMessage .= 'Ticket Creation Failed, StaffAPI ID: ' . $_staffAPIID . SWIFT_CRLF;
				}

				$_signatureContentsDefault = $_signatureContentsHTML = '';
				if ($_ticketType == 'sendmail') {
					$_signatureContentsDefault = $_SWIFT_TicketObject->GetSignature(false, $_SWIFT->Staff);
					$_signatureContentsHTML = $_SWIFT_TicketObject->GetSignature(true, $_SWIFT->Staff);
				}

				if (count($_ccToList)) {
					SWIFT_TicketRecipient::Create($_SWIFT_TicketObject, SWIFT_TicketRecipient::TYPE_CC, $_ccToList);
				}

				if (count($_bccToList)) {
					SWIFT_TicketRecipient::Create($_SWIFT_TicketObject, SWIFT_TicketRecipient::TYPE_BCC, $_bccToList);
				}

				if ($_creator == 'staff') {
					// Carry out the email dispatch logic
					$_SWIFT_TicketEmailDispatchObject = new SWIFT_TicketEmailDispatch($_SWIFT_TicketObject);
					$_SWIFT_TicketEmailDispatchObject->DispatchStaffReply($_SWIFT->Staff, $_replyContents, false, $_fromEmailAddress, array($_signatureContentsDefault, $_signatureContentsHTML));
				}

				$_createStaffAPIIDMap[$_SWIFT_TicketObject->GetTicketID()] = $_staffAPIID;

				$_returnTicketIDList[] = $_SWIFT_TicketObject->GetTicketID();
				$_extendedTicketMapper[$_SWIFT_TicketObject->GetTicketID()] = array('basicinfo' => true, 'extendedinfo' => true, 'ticketposts' => true);

				if (isset($_staffCache[$_ownerStaffID])) {
					$_SWIFT_TicketObject->SetOwner($_ownerStaffID);
				}

				if ($_flagType != '0') {
					$_SWIFT_TicketObject->SetFlag($_flagType);
				}

				if (isset($_CreateObject->tags)) {
					$_tagListCombined = (string) $_CreateObject->tags;

					$_tagList = explode(' ', $_tagListCombined);
					if (!count($_tagList)) {
						$_tagList = array($_tagListCombined);
					}

					$_finalTagList = array();
					foreach ($_tagList as $_key => $_val) {
						$_finalTag = trim(CleanTag($_val));

						if (empty($_finalTag)) {
							continue;
						}

						$_finalTagList[] = CleanTag(trim($_val));
					}

					if (count($_finalTagList)) {
						SWIFT_Tag::Process(SWIFT_TagLink::TYPE_TICKET, $_SWIFT_TicketObject->GetTicketID(), $_finalTagList, $_SWIFT->Staff->GetStaffID());
					}
				}

				if ($_resolutionDue != '-1' && $_resolutionDue != '0') {
					$_SWIFT_TicketObject->SetResolutionDue($_resolutionDue);
				}

				if ($_replyDue != '-1' && $_replyDue != '0') {
					$_SWIFT_TicketObject->SetDue($_replyDue);
				}

				// Process Watcher
				if (isset($_CreateObject->watch) && $_SWIFT->Staff->GetPermission('staff_tcanupateticket') != '0') {
					$_watchTicket = (int) $_CreateObject->watch;

					if ($_watchTicket == '1') {
						SWIFT_Ticket::Watch(array($_SWIFT_TicketObject->GetTicketID()), $_SWIFT->Staff);
					}
				} else if (isset($_CreateObject->watch)) {
					$_statusCode = '0';
					$_statusMessage .= 'Unable to watch';
				}

				$_SWIFT_TicketPostObject = new SWIFT_TicketPost(new SWIFT_DataID($_SWIFT_TicketObject->GetProperty('firstpostid')));

				// Process Attachments
				if (isset($_CreateObject->reply->attachment)) {
					foreach ($_CreateObject->reply->attachment as $_AttachmentObject) {
						$_fileName = (string) $_AttachmentObject->attributes()->filename;
						$_fileMD5 = (string) $_AttachmentObject->attributes()->md5;

						$_fileContents = (string) $_AttachmentObject;

						$_AttachmentStoreObject = new SWIFT_AttachmentStoreString($_fileName, 'application/download', base64_decode($_fileContents));

						SWIFT_Attachment::CreateOnTicket($_SWIFT_TicketObject, $_SWIFT_TicketPostObject, $_AttachmentStoreObject);
						$_SWIFT_TicketObject->AddToAttachments($_fileName, 'application/download', base64_decode($_fileContents));
						$_SWIFT_TicketObject->MarkHasAttachments();
					}
				}

				// Process Notes
				if (isset($_CreateObject->note) && $_SWIFT->Staff->GetPermission('staff_tcaninsertticketnote') != '0') {
					foreach ($_CreateObject->note as $_NoteObject) {
						$_noteContents = (string) $_NoteObject;

						$_noteColor = 1;
						if (isset($_NoteObject->attributes()->notecolor)) {
							$_noteColor = (int) $_NoteObject->attributes()->notecolor;
						}

						$_noteType = (string) $_NoteObject->attributes()->type;

						$_SWIFT_TicketObject->CreateNote($_SWIFT_UserObject, trim($_noteContents), $_noteColor, $_noteType);
					}
				} else if (isset($_CreateObject->note)) {
					$_statusCode = '0';
					$_statusMessage .= 'Unable to insert note';
				}

				// Process Billing
				if (isset($_CreateObject->billing) && $_SWIFT->Staff->GetPermission('staff_tcaninsertbilling') != '0') {
					foreach ($_CreateObject->billing as $_BillingObject) {
						$_workDateline = DATENOW;
						if (isset($_BillingObject->attributes()->workdate)) {
							$_workDateline = (int) $_BillingObject->attributes()->workdate;
						}

						$_billDateline = $_workDateline;

						if (isset($_BillingObject->attributes()->billdate)) {
							$_billDateline = (int) $_BillingObject->attributes()->billdate;
						}

						$_noteColor = (int) $_BillingObject->attributes()->notecolor;

						$_SWIFT_StaffObject_Worker = $_SWIFT->Staff;
						if (isset($_BillingObject->attributes()->worker)) {
							$_workerStaffID = (int) $_BillingObject->attributes()->worker;
							if (isset($_staffCache[$_workerStaffID])) {
								$_SWIFT_StaffObject_Worker = new SWIFT_Staff(new SWIFT_DataStore($_staffCache[$_workerStaffID]));
							}
						}

						$_noteContents = (string) $_BillingObject;

						$_timeSpent = (int) $_BillingObject->attributes()->timeworked;
						$_timeBillable = (int) $_BillingObject->attributes()->timebillable;

						SWIFT_TicketTimeTrack::Create($_SWIFT_TicketObject, $_SWIFT->Staff, $_timeSpent, $_timeBillable, $_noteColor, trim($_noteContents), $_SWIFT_StaffObject_Worker, $_workDateline, $_billDateline);
					}
				} else if (isset($_CreateObject->billing)) {
					$_statusCode = '0';
					$_statusMessage .= 'Unable to insert billing';
				}

				$_SWIFT_TicketObject->ProcessUpdatePool();

                /*
                 * BUG FIX - Rahul Bhattacharya
                 *
                 * SWIFT-3050 : Activities performed from Mobile apps are not recorded in activity logs.
                 */
                // Activity Log
                SWIFT_StaffActivityLog::AddToLog(sprintf($_SWIFT->Language->Get('log_newticket'), $_SWIFT_TicketObject->GetTicketDisplayID(), $_subject),
                    SWIFT_StaffActivityLog::ACTION_INSERT, SWIFT_StaffActivityLog::SECTION_TICKETS, SWIFT_StaffActivityLog::INTERFACE_API);
			}
		}


		/**
		 * ---------------------------------------------
		 * Process Delete
		 * ---------------------------------------------
		 */
		if (isset($_PushDataObject->delete) && $_SWIFT->Staff->GetPermission('staff_tcantrashticket') != '0') {
			$_deleteTicketIDList = array();

			foreach ($_PushDataObject->delete as $_DeleteObject) {
				$_ticketID = (string) $_DeleteObject->attributes()->ticketid;

				try {
					$_SWIFT_TicketObject = SWIFT_Ticket::GetObjectOnID($_ticketID);
					if ($_SWIFT_TicketObject instanceof SWIFT_Ticket && $_SWIFT_TicketObject->GetIsClassLoaded()) {
						$_deleteTicketIDList[] = $_SWIFT_TicketObject->GetTicketID();
					}
				} catch (SWIFT_Exception $_SWIFT_ExceptionObject) {
					$_statusCode = '0';
					$_statusMessage .= 'Invalid Ticket (Delete): ' . $_ticketID . SWIFT_CRLF;
				}
			}

			if (count($_deleteTicketIDList)) {
				SWIFT_Ticket::TrashList($_deleteTicketIDList);

                /*
                 * BUG FIX - Rahul Bhattacharya
                 *
                 * SWIFT-3050 : Activities performed from Mobile apps are not recorded in activity logs.
                 */
                // Activity Log
                $_departmentTitle = $this->Language->Get('na');
                if ($_SWIFT_TicketObject->GetProperty('departmentid') == '0') {
                    $_departmentTitle = $this->Language->Get('trash');
                } else if (isset($_departmentCache[$_SWIFT_TicketObject->GetProperty('departmentid')])) {
                    $_departmentTitle = $_departmentCache[$_SWIFT_TicketObject->GetProperty('departmentid')]['title'];
                }

                $_ticketStatusContainer = array();
                $_ticketStatusTitle = $this->Language->Get('na');
                if (isset($_ticketStatusCache[$_SWIFT_TicketObject->GetProperty('ticketstatusid')])) {
                    $_ticketStatusContainer = $_ticketStatusCache[$_SWIFT_TicketObject->GetProperty('ticketstatusid')];
                    $_ticketStatusTitle = $_ticketStatusContainer['title'];
                }

                SWIFT_StaffActivityLog::AddToLog(sprintf($_SWIFT->Language->Get('activitytrashticket'),
                        htmlspecialchars($_SWIFT_TicketObject->GetProperty('subject')), htmlspecialchars($_departmentTitle),
                        htmlspecialchars($_ticketStatusTitle), htmlspecialchars($_SWIFT_TicketObject->GetProperty('fullname'))),
                    SWIFT_StaffActivityLog::ACTION_DELETE, SWIFT_StaffActivityLog::SECTION_TICKETS, SWIFT_StaffActivityLog::INTERFACE_API);
			}
		} else if (isset($_PushDataObject->delete)) {
			$_statusCode = '0';
			$_statusMessage .= 'Unable to Delete ticket';
		}



		/**
		 * ---------------------------------------------
		 * Process Modify Request
		 * ---------------------------------------------
		 */
		if (isset($_PushDataObject->modify) && $_SWIFT->Staff->GetPermission('staff_tcanupateticket') != '0') {
			foreach ($_PushDataObject->modify as $_ModifyObject) {
				$_ticketID = (string) $_ModifyObject->attributes()->ticketid;

				$_mapOptionBasic = $_mapOptionExtended = $_mapOptionPost = false;

				try {
					$_SWIFT_TicketObject = SWIFT_Ticket::GetObjectOnID($_ticketID);
					if ($_SWIFT_TicketObject instanceof SWIFT_Ticket && $_SWIFT_TicketObject->GetIsClassLoaded()) {

						$_SWIFT_TicketPostObject = false;
						$_departmentID = $_ticketStatusID = $_ticketPriorityID = $_ticketTypeID = $_ownerStaffID = -1;

						if (isset($_ModifyObject->departmentid)) {
							$_departmentID = (int) $_ModifyObject->departmentid;

							if (!isset($_departmentCache[$_departmentID])) {
								$_departmentID = -1;
							}
						}

						if (isset($_ModifyObject->ticketstatusid)) {
							$_ticketStatusID = (int) $_ModifyObject->ticketstatusid;

							if (!isset($_ticketStatusCache[$_ticketStatusID])) {
								$_ticketStatusID = -1;
							}
						}

						if (isset($_ModifyObject->ticketpriorityid)) {
							$_ticketPriorityID = (int) $_ModifyObject->ticketpriorityid;

							if (!isset($_ticketPriorityCache[$_ticketPriorityID])) {
								$_ticketPriorityID = -1;
							}
						}

						if (isset($_ModifyObject->tickettypeid)) {
							$_ticketTypeID = (int) $_ModifyObject->tickettypeid;

							if (!isset($_ticketTypeCache[$_ticketTypeID])) {
								$_ticketTypeID = -1;
							}
						}

						if (isset($_ModifyObject->ownerstaffid)) {
							$_ownerStaffID = (int) $_ModifyObject->ownerstaffid;

							if ($_ownerStaffID != '0' && !isset($_staffCache[$_ownerStaffID])) {
								$_ownerStaffID = -1;
							}
						}

						$_flagType = -1;
						if (isset($_ModifyObject->flagtype)) {
							$_flagType = (int) $_ModifyObject->flagtype;
						}

						$_ccToList = array();
						if (isset($_ModifyObject->ccto)) {
							foreach ($_ModifyObject->ccto as $_CCToObject) {
								$_ccToEmail = (string) $_CCToObject;

								if (!IsEmailValid($_ccToEmail)) {
									continue;
								}

								$_ccToList[] = $_ccToEmail;
							}
						}

						$_bccToList = array();
						if (isset($_ModifyObject->bccto)) {
							foreach ($_ModifyObject->bccto as $_BCCToObject) {
								$_bccToEmail = (string) $_BCCToObject;

								if (!IsEmailValid($_bccToEmail)) {
									continue;
								}

								$_bccToList[] = $_bccToEmail;
							}
						}

						$_resolutionDue = $_replyDue = -1;
						if (isset($_ModifyObject->resolutiondue)) {
							$_resolutionDue = (int) $_ModifyObject->resolutiondue;
						}

						if (isset($_ModifyObject->replydue)) {
							$_replyDue = (int) $_ModifyObject->replydue;
						}

						$_replyContents = '';

						if (count($_ccToList)) {
							SWIFT_TicketRecipient::Create($_SWIFT_TicketObject, SWIFT_TicketRecipient::TYPE_CC, $_ccToList);
						}

						if (count($_bccToList)) {
							SWIFT_TicketRecipient::Create($_SWIFT_TicketObject, SWIFT_TicketRecipient::TYPE_BCC, $_bccToList);
						}

						if (isset($_ModifyObject->reply->contents)) {
							$_replyContents = (string) $_ModifyObject->reply->contents;

							$_SWIFT_TicketPostObject = SWIFT_TicketPost::CreateStaff($_SWIFT_TicketObject, $_SWIFT->Staff, SWIFT_Ticket::CREATIONMODE_STAFFAPI, $_replyContents, $_SWIFT_TicketObject->GetProperty('subject'),
									false, false);

                            /*
                             * BUG FIX - Rahul Bhattacharya
                             *
                             * SWIFT-3050 : Activities performed from Mobile apps are not recorded in activity logs.
                             */
                            // Activity Log
                            SWIFT_StaffActivityLog::AddToLog(sprintf($_SWIFT->Language->Get('log_newreply'), $_SWIFT_TicketObject->GetTicketDisplayID()),
                                SWIFT_StaffActivityLog::ACTION_UPDATE, SWIFT_StaffActivityLog::SECTION_TICKETS, SWIFT_StaffActivityLog::INTERFACE_API);

							$_mapOptionPost = true;
						}

						$_returnTicketIDList[] = $_SWIFT_TicketObject->GetTicketID();

						if ($_flagType != '-1') {
							$_SWIFT_TicketObject->SetFlag($_flagType);
							$_mapOptionBasic = true;
						}

						if ($_departmentID != '-1' && $_departmentID != '0') {
							$_SWIFT_TicketObject->SetDepartment($_departmentID);
							$_mapOptionBasic = true;
						}

						if ($_ticketStatusID != '-1' && $_ticketStatusID != '0') {
							$_SWIFT_TicketObject->SetStatus($_ticketStatusID);
							$_mapOptionBasic = true;
						}

						if ($_ticketPriorityID != '-1' && $_ticketPriorityID != '0') {
							$_SWIFT_TicketObject->SetPriority($_ticketPriorityID);
							$_mapOptionBasic = true;
						}

						if ($_ticketTypeID != '-1' && $_ticketTypeID != '0') {
							$_SWIFT_TicketObject->SetType($_ticketTypeID);
							$_mapOptionBasic = true;
						}

						if ($_ownerStaffID != '-1') {
							$_SWIFT_TicketObject->SetOwner($_ownerStaffID);
							$_mapOptionBasic = true;
						}

						if (isset($_ModifyObject->tags)) {
							$_tagListCombined = (string) $_ModifyObject->tags;

							$_tagList = explode(' ', $_tagListCombined);
							if (!count($_tagList)) {
								$_tagList = array($_tagListCombined);
							}

							$_finalTagList = array();
							foreach ($_tagList as $_key => $_val) {
								$_finalTag = trim(CleanTag($_val));

								if (empty($_finalTag)) {
									continue;
								}

								$_finalTagList[] = CleanTag(trim($_val));
							}

							if (count($_finalTagList)) {
								SWIFT_Tag::Process(SWIFT_TagLink::TYPE_TICKET, $_SWIFT_TicketObject->GetTicketID(), $_finalTagList, $_SWIFT->Staff->GetStaffID());
							}
							$_mapOptionBasic = true;
						}

						if ($_resolutionDue != '-1' && $_resolutionDue != '0') {
							$_SWIFT_TicketObject->SetResolutionDue($_resolutionDue);
							$_mapOptionBasic = true;
						} else if ($_resolutionDue == '0') {
							$_SWIFT_TicketObject->ClearResolutionDue();
							$_mapOptionBasic = true;
						}

						if ($_replyDue != '-1' && $_replyDue != '0') {
							$_SWIFT_TicketObject->SetDue($_replyDue);
							$_mapOptionBasic = true;
						} else if ($_replyDue == '0') {
							$_SWIFT_TicketObject->ClearOverdue();
							$_mapOptionBasic = true;
						}

						// Process Watcher
						if (isset($_ModifyObject->watch) && $_SWIFT->Staff->GetPermission('staff_tcanupateticket') != '0') {
							$_watchTicket = (int) $_ModifyObject->watch;

							if ($_watchTicket == '1') {
								SWIFT_Ticket::Watch(array($_SWIFT_TicketObject->GetTicketID()), $_SWIFT->Staff);
							} else {
								SWIFT_Ticket::UnWatch(array($_SWIFT_TicketObject->GetTicketID()), $_SWIFT->Staff);
							}
							$_mapOptionExtended = true;
						} else if (isset($_ModifyObject->watch)) {
							$_statusCode = '0';
							$_statusMessage .= 'Unable to update watch';
						}

						// Get the User Object
						$_SWIFT_UserObject = false;
						try {
							$_SWIFT_UserObject = new SWIFT_User(new SWIFT_DataID($_SWIFT_TicketObject->GetProperty('userid')));
						} catch (SWIFT_Exception $_SWIFT_ExceptionObject) {
						}

						if (!$_SWIFT_UserObject instanceof SWIFT_User || !$_SWIFT_UserObject->GetIsClassLoaded()) {
							$_SWIFT_TemplateGroupObject = new SWIFT_TemplateGroup(SWIFT_TemplateGroup::GetDefaultGroupID());
							if (!$_SWIFT_TemplateGroupObject instanceof SWIFT_TemplateGroup || !$_SWIFT_TemplateGroupObject->GetIsClassLoaded()) {
								throw new SWIFT_Exception('Unable to load master template group object');
							}

							$_userID = SWIFT_Ticket::GetOrCreateUserID($_SWIFT_TicketObject->GetProperty('fullname'), $_SWIFT_TicketObject->GetProperty('email'),
									$_SWIFT_TemplateGroupObject->GetRegisteredUserGroupID());
							$_SWIFT_UserObject = new SWIFT_User(new SWIFT_DataID($_userID));
						}

						// Process Attachments
						if (isset($_ModifyObject->reply->attachment) && $_SWIFT_TicketPostObject instanceof SWIFT_TicketPost) {
							foreach ($_ModifyObject->reply->attachment as $_AttachmentObject) {
								$_fileName = (string) $_AttachmentObject->attributes()->filename;
								$_fileMD5 = (string) $_AttachmentObject->attributes()->md5;

								$_fileContents = (string) $_AttachmentObject;

								$_AttachmentStoreObject = new SWIFT_AttachmentStoreString($_fileName, 'application/download', base64_decode($_fileContents));

								SWIFT_Attachment::CreateOnTicket($_SWIFT_TicketObject, $_SWIFT_TicketPostObject, $_AttachmentStoreObject);
								$_SWIFT_TicketObject->AddToAttachments($_fileName, 'application/download', base64_decode($_fileContents));
								$_SWIFT_TicketObject->MarkHasAttachments();
							}
						}

						// Process Notes
						if (isset($_ModifyObject->note) && $_SWIFT->Staff->GetPermission('staff_tcanupateticketnote') != '0') {
							foreach ($_ModifyObject->note as $_NoteObject) {
								$_noteContents = (string) $_NoteObject;

								$_noteColor = 1;
								if (isset($_NoteObject->attributes()->notecolor)) {
									$_noteColor = (int) $_NoteObject->attributes()->notecolor;
								}

								$_noteType = (string) $_NoteObject->attributes()->type;

								$_SWIFT_TicketObject->CreateNote($_SWIFT_UserObject, trim($_noteContents), $_noteColor, $_noteType);
							}
							$_mapOptionExtended = true;
						} else if (isset($_ModifyObject->note)) {
							$_statusCode = '0';
							$_statusMessage .= 'Unable to update notes';
						}

						// Process Billing
						if (isset($_ModifyObject->billing) && $_SWIFT->Staff->GetPermission('staff_tcanupatebilling') != '0') {
							foreach ($_ModifyObject->billing as $_BillingObject) {
								$_workDateline = DATENOW;
								if (isset($_BillingObject->attributes()->workdate)) {
									$_workDateline = (int) $_BillingObject->attributes()->workdate;
								}

								$_billDateline = $_workDateline;

								if (isset($_BillingObject->attributes()->billdate)) {
									$_billDateline = (int) $_BillingObject->attributes()->billdate;
								}

								$_noteColor = (int) $_BillingObject->attributes()->notecolor;

								$_SWIFT_StaffObject_Worker = $_SWIFT->Staff;
								if (isset($_BillingObject->attributes()->worker)) {
									$_workerStaffID = (int) $_BillingObject->attributes()->worker;
									if (isset($_staffCache[$_workerStaffID])) {
										$_SWIFT_StaffObject_Worker = new SWIFT_Staff(new SWIFT_DataStore($_staffCache[$_workerStaffID]));
									}
								}

								$_noteContents = (string) $_BillingObject;

								$_timeSpent = (int) $_BillingObject->attributes()->timeworked;
								$_timeBillable = (int) $_BillingObject->attributes()->timebillable;

								SWIFT_TicketTimeTrack::Create($_SWIFT_TicketObject, $_SWIFT->Staff, $_timeSpent, $_timeBillable, $_noteColor, trim($_noteContents), $_SWIFT_StaffObject_Worker, $_workDateline, $_billDateline);
							}
							$_mapOptionExtended = true;
						} else if (isset($_ModifyObject->billing)) {
							$_statusCode = '0';
							$_statusMessage .= 'Unable to update billing';
						}

						$_extendedTicketMapper[$_SWIFT_TicketObject->GetTicketID()] = array('basicinfo' => $_mapOptionBasic, 'extendedinfo' => $_mapOptionExtended, 'ticketposts' => $_mapOptionPost);
						$_SWIFT_TicketObject->ProcessUpdatePool();

					}
				} catch (SWIFT_Exception $_SWIFT_ExceptionObject) {
					$_statusCode = '0';
					$_statusMessage .= 'Invalid Ticket (Modify): ' . $_ticketID . SWIFT_CRLF . $_SWIFT_ExceptionObject->getMessage() . SWIFT_CRLF . $_SWIFT_ExceptionObject->getTraceAsString() . SWIFT_CRLF;
				}
			}
		}


		/**
		 * ---------------------------------------------
		 * Dispatch Final Result
		 * ---------------------------------------------
		 */

		SWIFT_TicketStaffAPIManager::DispatchOnTicketIDList($_returnTicketIDList, 0, '', '', true, true, false, 1000, $_createStaffAPIIDMap, $_statusMessage, false, 0, 1000, $_extendedTicketMapper);

		return true;
	}

	/**
	 * Retrieve the From Email Address
	 *
	 * @author Varun Shoor
	 * @param int $_departmentID
	 * @return string The From Email Address
	 * @throws SWIFT_Exception If Invalid Data is Provided
	 */
	static protected function _GetDispatchFromEmail($_departmentID)
	{
		$_SWIFT = SWIFT::GetInstance();

		$_fromEmailAddress = '';

		$_emailQueueCache = $_SWIFT->Cache->Get('queuecache');

		$_fromEmailAddress = $_SWIFT->Settings->Get('general_returnemail');

		if (isset($_emailQueueCache['list'])) {
			foreach ($_emailQueueCache['list'] as $_emailQueue) {
				if ($_emailQueue['departmentid'] != $_departmentID) {
					continue;
				}

				if (!empty($_emailQueue['customfromemail'])) {
					$_fromEmailAddress = $_emailQueue['customfromemail'];
				} else {
					$_fromEmailAddress = $_emailQueue['email'];
				}
			}
		}

		return $_fromEmailAddress;
	}
}

?>