properties = $GLOBALS["properties"]->getAppointmentListProperties(); $this->startdate = false; $this->enddate = false; $this->tziana = 'Etc/UTC'; $this->tzdef = false; } /** * Creates the notifiers for this module, * and register them to the Bus. */ public function createNotifiers() { $entryid = $this->getEntryID(); $GLOBALS["bus"]->registerNotifier('appointmentlistnotifier', $entryid); } /** * Normalize paired message stores and folder entry IDs and discard failed opens. * * @param array|false|resource $store MAPI message store or stores * @param array|false|string $entryid folder entry ID or IDs * * @return array{0: resource[], 1: string[]} valid store/folder pairs */ private function normalizeStoreEntryIds($store, $entryid) { $stores = is_array($store) ? $store : [$store]; $entryids = is_array($entryid) ? $entryid : [$entryid]; if (count($stores) !== count($entryids)) { return [[], []]; } $validStores = []; $validEntryids = []; foreach ($stores as $index => $messageStore) { $folderEntryid = $entryids[$index]; if ($messageStore === false || !is_string($folderEntryid) || $folderEntryid === '') { continue; } $validStores[] = $messageStore; $validEntryids[] = $folderEntryid; } return [$validStores, $validEntryids]; } /** * Executes all the actions in the $data variable. */ #[Override] public function execute() { foreach ($this->data as $actionType => $action) { if (!isset($actionType)) { continue; } try { $store = $this->getActionStore($action); $entryid = $this->getActionEntryID($action); switch ($actionType) { case "list": $this->messageList($store, $entryid, $action, $actionType); break; case "search": // @FIXME add functionality to handle private items $this->search($store, $entryid, $action, $actionType); break; case "updatesearch": if ($store === false || is_array($store) || is_array($entryid)) { $this->sendFeedback(false); break; } $this->updatesearch($store, $entryid, $action); break; case "stopsearch": if ($store === false || is_array($store) || is_array($entryid)) { $this->sendFeedback(false); break; } $this->stopSearch($store, $entryid, $action); break; default: $this->handleUnknownActionType($actionType); } } catch (MAPIException $e) { if (isset($action['suppress_exception']) && $action['suppress_exception'] === true) { $e->setNotificationType('console'); } $this->processException($e, $actionType); } } } /** * Function which retrieves a list of calendar items in a calendar folder. * * @param array|false|resource $store MAPI message store or stores * @param array|false|string $entryid entryid of the folder or folders * @param array $action the action data, sent by the client * @param string $actionType the action type, sent by the client */ #[Override] public function messageList($store, $entryid, $action, $actionType) { [$store, $entryid] = $this->normalizeStoreEntryIds($store, $entryid); if ($store === []) { return; } // initialize start and due date with false value so it will not take values from previous request $this->startdate = false; $this->enddate = false; $this->skippedCount = 0; $this->skippedInfo = ""; if (isset($action["restriction"])) { if (isset($action["restriction"]["startdate"])) { $this->startdate = $action["restriction"]["startdate"]; } if (isset($action["restriction"]["duedate"])) { $this->enddate = $action["restriction"]["duedate"]; } } if (!empty($action["timezone_iana"])) { $this->tziana = $action["timezone_iana"]; $this->tzdef = TimezoneUtil::GetBinaryTZ($action['timezone_iana']); } if ($this->startdate && $this->enddate) { $data = []; $data["item"] = []; for ($index = 0, $index2 = count($entryid); $index < $index2; ++$index) { $this->getDelegateFolderInfo($store[$index]); // Set the active store in properties class and get the props based on active store. // we need to do this because of multi server env where shared store belongs to the different server. // Here name space is different per server. e.g. There is user A and user B and both are belongs to // different server and user B is shared store of user A because of that user A has 'categories' => -2062020578 // and user B 'categories' => -2062610402, $GLOBALS["properties"]->setActiveStore($store[$index]); $this->properties = $GLOBALS["properties"]->getAppointmentListProperties(); array_push($data["item"], ...$this->getCalendarItems($store[$index], $entryid[$index], $this->startdate, $this->enddate)); } $this->addSkippedInfo($data); $this->addActionData("list", $data); $GLOBALS["bus"]->addData($this->getResponseData()); return; } // for list view in calendar as startdate and enddate is passed as false // this will set sorting and paging for items in listview. /* This is an override for parent::messageList(), which ignores an array of entryids / stores. * The following block considers this possibly and merges the data of several folders / stores. */ $this->searchFolderList = false; // Set to indicate this is not the search result, but a normal folder content // Restriction $this->parseRestriction($action); // Sort $this->parseSortOrder($action, null, true); $limit = false; if (isset($action['restriction']['limit'])) { $limit = $action['restriction']['limit']; } else { $limit = $GLOBALS['settings']->get('grommunio/v1/main/page_size', 50); } $isSearchFolder = isset($action['search_folder_entryid']); if ($isSearchFolder) { $searchFolderEntryid = hex2bin((string) $action['search_folder_entryid']); if ($searchFolderEntryid === false) { return; } $entryid = [$searchFolderEntryid]; $store = [$store[0]]; } $this->getDelegateFolderInfo($store[0]); // Get the table and merge the arrays $data = []; $items = []; for ($i = 0, $c = count($entryid); $i < $c; ++$i) { $newItems = $GLOBALS["operations"]->getTable($store[$i], $entryid[$i], $this->properties, $this->sort, $this->start, $limit, $this->restriction); array_push($items, ...$newItems['item']); if (isset($newItems['page']['totalrowcount']) && $newItems['page']['totalrowcount'] > $limit) { $data['page'] = $newItems['page']; } } // If the request come from search folder then no need to send folder information if (!$isSearchFolder) { $contentCount = 0; $contentUnread = 0; // For each folder for ($i = 0, $c = count($entryid); $i < $c; ++$i) { // Open folder $folder = mapi_msgstore_openentry($store[$i], $entryid[$i]); // Obtain some statistics from the folder contents $content = mapi_getprops($folder, [PR_CONTENT_COUNT, PR_CONTENT_UNREAD]); if (isset($content[PR_CONTENT_COUNT])) { $contentCount += $content[PR_CONTENT_COUNT]; } if (isset($content[PR_CONTENT_UNREAD])) { $contentUnread += $content[PR_CONTENT_UNREAD]; } } $data["folder"] = []; $data["folder"]["content_count"] = $contentCount; $data["folder"]["content_unread"] = $contentUnread; } $items = $this->filterPrivateItems(['item' => $items]); // unset will remove the value but will not regenerate array keys, so we need to // do it here $data["item"] = array_values($items["item"]); for ($i = 0, $c = count($entryid); $i < $c; ++$i) { // Allowing to hook in just before the data sent away to be sent to the client $GLOBALS['PluginManager']->triggerHook('server.module.listmodule.list.after', [ 'moduleObject' => &$this, 'store' => $store[$i], 'entryid' => $entryid[$i], 'action' => $action, 'data' => &$data, ]); } $this->addSkippedInfo($data); $this->addActionData($actionType, $data); $GLOBALS["bus"]->addData($this->getResponseData()); } /** * Adds an informational message to the list response when appointments were skipped. * * @param array $data list response data */ private function addSkippedInfo(&$data) { if ($this->skippedCount === 0) { return; } $displayMessage = sprintf(ngettext("There was %d skipped appointment:", "There were %d skipped appointments:", $this->skippedCount), $this->skippedCount); if (!empty($this->skippedInfo)) { $displayMessage .= $this->skippedInfo; } if ($this->skippedCount > 5) { $displayMessage .= "
" . _("More skipped appointments are not shown."); } $data["warning"] = [ "display_message" => $displayMessage, ]; } /** * Tracks skipped appointments and stores the first few subjects for client feedback. * * @param string $subject appointment properties from the MAPI table */ private function recordSkipped($subject) { ++$this->skippedCount; if ($this->skippedCount >= 5) { return; } $this->skippedInfo .= "
- " . htmlspecialchars((string) $subject, ENT_QUOTES | ENT_SUBSTITUTE, "UTF-8"); } /** * Function to return all Calendar items in a given timeframe. This * function also takes recurring items into account. * * @param resource $store message store * @param mixed $entryid entryid of the folder * @param mixed $start startdate of the interval * @param mixed $end enddate of the interval */ public function getCalendarItems($store, $entryid, $start, $end) { $restriction = // OR // - Either we want all appointments which fall within the given range // - Or we want all recurring items which we manually check if an occurrence // exists which will fall inside the range [RES_OR, [ // OR // - Either we want all properties which fall inside the range (or overlap the range somewhere) // (start < appointmentEnd && due > appointmentStart) // - Or we want all zero-minute appointments which fall at the start of the restriction. // Note that this will effectively exclude any appointments which have an enddate on the restriction // start date, as those are not useful for us. Secondly, we exclude all zero-minute appointments // which fall on the end of the restriction as the restriction is RELOP_GT, ULPROPTAG => $this->properties["duedate"], VALUE => $start, ], ], // due > appointmentStart [RES_PROPERTY, [RELOP => RELOP_LT, ULPROPTAG => $this->properties["startdate"], VALUE => $end, ], ], ], ], // AND // - The AppointmentStart equals the start of the range // - The AppointmentEnd equals the start of the range // In other words the zero-minute appointments on the start of the range [RES_AND, [ // appointmentStart == start [RES_PROPERTY, [RELOP => RELOP_EQ, ULPROPTAG => $this->properties["startdate"], VALUE => $start, ], ], // appointmentEnd == start [RES_PROPERTY, [RELOP => RELOP_EQ, ULPROPTAG => $this->properties["duedate"], VALUE => $start, ], ], ], ], ], ], // OR // (item[isRecurring] == true) // Add one day to the start and the end of the periods to avoid // timezone offset related differences between start/clipstart // and end/clipend. [RES_AND, [ [RES_PROPERTY, [RELOP => RELOP_EQ, ULPROPTAG => $this->properties["recurring"], VALUE => true, ], ], [RES_AND, [ [RES_PROPERTY, [RELOP => RELOP_GT, ULPROPTAG => $this->properties["enddate_recurring"], VALUE => (int) $start - 86400, ], ], [RES_PROPERTY, [RELOP => RELOP_LT, ULPROPTAG => $this->properties["startdate_recurring"], VALUE => (int) $end + 86400, ], ], ], ], ], ], ], ]; // global OR try { $folder = mapi_msgstore_openentry($store, $entryid); $table = mapi_folder_getcontentstable($folder, MAPI_DEFERRED_ERRORS); // Restricting the table filters it while it loads; passing the // restriction to queryallrows instead walks it row by row. mapi_table_restrict($table, $restriction, TBL_BATCH); $calendaritems = mapi_table_queryallrows($table, $this->properties); return $this->processItems($calendaritems, $store, $entryid, $start, $end); } catch (Exception $e) { // Without read rights the table is refused (gromox answers MAPI_E_NOT_FOUND); // the owner's free/busy data is all that may be shown then. if ($e->getCode() == MAPI_E_NOT_FOUND || $e->getCode() == MAPI_E_NO_ACCESS) { return $this->getFreebusyItems($store, $entryid, $start, $end); } error_log(sprintf("getCalendarItems: unable to list folder %s: %s (0x%08X)", bin2hex((string) $entryid), $e->getMessage(), $e->getCode())); } return []; } /** * Process calendar items to prepare them for being sent back to the client. * * @param array $calendaritems array of appointments retrieved from the MAPI table * @param resource $store MAPI message store * @param mixed $entryid * @param mixed $start startdate of the interval * @param mixed $end enddate of the interval * * @return array $items processed items */ public function processItems($calendaritems, $store, $entryid, $start, $end) { $items = []; $openedMessages = []; $proptags = $GLOBALS["properties"]->getRecurrenceProperties(); foreach ($calendaritems as $calendaritem) { $item = null; if (!isset($calendaritem[$this->properties["recurring"]]) || !$calendaritem[$this->properties["recurring"]]) { $item = Conversion::mapMAPI2XML($this->properties, $calendaritem); $this->addItems($store, $item, $openedMessages, $start, $end, $items); continue; } // Fix for all-day events which have a different timezone than the user's browser $recurrence = new Recurrence($store, $calendaritem, $proptags); try { $recuritems = $recurrence->getItems($start, $end); } catch (RecurrenceException $re) { $subject = $calendaritem[$this->properties["subject"]] ?? ''; error_log(sprintf( "processItems RecurrenceException (%d) for item '%s' - %s - %s", $re->getCode(), $subject, bin2hex($calendaritem[$this->properties["entryid"]]), bin2hex($calendaritem[$this->properties["recurring_data"]]) )); $this->recordSkipped($subject); continue; } $msgRecurrence = null; foreach ($recuritems as $recuritem) { // Recurrence blob is not needed for occurrence display unset($recuritem[$this->properties['recurring_data']]); $item = Conversion::mapMAPI2XML($this->properties, $recuritem); // Single occurrences are never recurring $item['props']['recurring'] = false; if (isset($recuritem["exception"])) { $item["props"]["exception"] = true; } if (isset($recuritem["basedate"])) { $item["props"]["basedate"] = $recuritem["basedate"]; } if (isset($recuritem["exception"])) { // Add categories if they are set on the exception. // We need a Recurrence object backed by the mapi message // (not just props) so we can open the exception attachments. // Create it once per series and reuse for all exceptions. if ($msgRecurrence === null) { $msgEntryid = bin2hex((string) $calendaritem[$this->properties["entryid"]]); if (!isset($openedMessages[$msgEntryid])) { $message = mapi_msgstore_openentry($store, $calendaritem[$this->properties["entryid"]]); $openedMessages[$msgEntryid] = $message; } else { $message = $openedMessages[$msgEntryid]; } $msgRecurrence = new Recurrence($store, $message, $proptags); } $exceptionatt = $msgRecurrence->getExceptionAttachment($recuritem["basedate"]); if ($exceptionatt) { // Existing exception (open existing item, which includes basedate) $exception = mapi_attach_openobj($exceptionatt, 0); $exceptionProps = $GLOBALS['operations']->getMessageProps($store, $exception, ['categories' => $this->properties["categories"]]); if (isset($exceptionProps['props']['categories'])) { $item["props"]["categories"] = $exceptionProps['props']['categories']; } } } $this->addItems($store, $item, $openedMessages, $start, $end, $items); } } usort($items, ["AppointmentListModule", "compareCalendarItems"]); return $items; } /** * Function will be used to process private items in a list response, modules can * can decide what to do with the private items, remove the entire row or just * hide the data. This function will only hide the data of the private appointments. * * @param array $item item properties * * @return array item properties after processing private items */ #[Override] public function processPrivateItem($item) { if (!$this->startdate || !$this->enddate) { // if we are in list view then we need to follow normal procedure of other listviews return parent::processPrivateItem($item); } if (!$this->checkPrivateItem($item)) { return $item; } $item['props']['subject'] = _('Private Appointment'); $item['props']['normalized_subject'] = _('Private Appointment'); $item['props']['location'] = ''; $item['props']['reminder'] = 0; $item['props']['access'] = 0; $item['props']['sent_representing_name'] = ''; $item['props']['sender_name'] = ''; $item['props']['display_to'] = ''; $item['props']['display_cc'] = ''; $item['props']['display_bcc'] = ''; $item['props']['body_preview'] = ''; return $item; } /** * Function will sort items for the month view * small startdate on top. * * @param mixed $a * @param mixed $b */ public static function compareCalendarItems($a, $b) { $start_a = $a["props"]["startdate"]; $start_b = $b["props"]["startdate"]; return $start_a <=> $start_b; } /** * Processes an all-day item and calculates the correct start time if necessary. * * @param resource $store * @param array $calendaritem * @param array $openedMessages */ private function processAllDayItem($store, &$calendaritem, &$openedMessages) { // If the appointment doesn't have tzdefstart property, it was probably // created on a mobile device (mobile devices do not send a timezone for // all-day events) or was imported from a system which doesn't set it. $isTzdefstartSet = isset($calendaritem['props']['tzdefstart']); $tzdefstart = $isTzdefstartSet ? hex2bin((string) $calendaritem['props']['tzdefstart']) : mapi_ianatz_to_tzdef("Etc/UTC"); if ($tzdefstart === false) { $isTzdefstartSet = false; $tzdefstart = ''; } // queryrows only returns 510 chars max, so if tzdef is longer than that // it was probably silently truncated. In such case we need to open // the message and read the prop value as stream. if (strlen($tzdefstart) > 500 && $isTzdefstartSet) { if (!isset($openedMessages[$calendaritem['entryid']])) { // Open the message and add it to the openedMessages property $openedMessages[$calendaritem['entryid']] = mapi_msgstore_openentry($store, hex2bin((string) $calendaritem['entryid'])); } $tzdefstart = readMapiPropStream($openedMessages[$calendaritem['entryid']], $this->properties['tzdefstart']); } $duration = $calendaritem['props']['duedate'] - $calendaritem['props']['startdate']; // Set the start and endtimes to the midnight of the client's timezone // if that's not the case already. if (!$isTzdefstartSet) { $localStart = getLocalStart($calendaritem['props']['startdate'], $this->tziana); if ($localStart != $calendaritem['props']['startdate']) { $calendaritem['props']['startdate'] = $calendaritem['props']['commonstart'] = $localStart; $calendaritem['props']['duedate'] = $calendaritem['props']['commonend'] = $localStart + $duration; } } // Compare the timezone definitions of the client and the appointment. // Further processing is only required if they don't match. elseif ($isTzdefstartSet && !$GLOBALS['entryid']->compareEntryIds($this->tzdef, $tzdefstart)) { $localStart = TimezoneUtil::ConvertAllDayStart($calendaritem['props']['startdate'], $tzdefstart, $this->tzdef); if ($localStart !== null) { $calendaritem['props']['startdate'] = $calendaritem['props']['commonstart'] = $localStart; $calendaritem['props']['duedate'] = $calendaritem['props']['commonend'] = $localStart + $duration; } } } /** * Adds items to return items list. * * @param resource $store * @param array $openedMessages * @param mixed $start startdate of the interval * @param mixed $end enddate of the interval * @param array $items * @param mixed $item */ private function addItems($store, &$item, &$openedMessages, $start, $end, &$items) { $item = $this->processPrivateItem($item); // only add it in response if its not removed by above function if (empty($item)) { return; } $this->prepareBodyPreview($item); if (empty($item["props"]["commonstart"]) && isset($item["props"]["startdate"])) { $item["props"]["commonstart"] = $item["props"]["startdate"]; } if (empty($item["props"]["commonend"]) && isset($item["props"]["duedate"])) { $item["props"]["commonend"] = $item["props"]["duedate"]; } if (isset($item["props"]["alldayevent"]) && $item["props"]["alldayevent"]) { $this->processAllDayItem($store, $item, $openedMessages); } // After processing the all-day events, their start and due dates // may have changed, so it's necessary to check again if they are // still in the requested interval. if (($start <= $item["props"]["startdate"] && $end > $item['props']['startdate']) || ($start < $item["props"]["duedate"] && $end >= $item['props']['duedate']) || ($start > $item["props"]["startdate"] && $end < $item['props']['duedate'])) { array_push($items, $item); } } /** * Gets items using freebusy entry point. * * @param resource $store MAPI message store * @param mixed $folderEntryid entryid of the folder * @param mixed $start startdate of the interval * @param mixed $end enddate of the interval */ public function getFreebusyItems($store, $folderEntryid, $start, $end) { $items = []; $storeProps = mapi_getprops($store, [PR_ENTRYID, PR_MAILBOX_OWNER_ENTRYID]); // A public store has no owner whose free/busy could stand in for the folder if (empty($storeProps[PR_MAILBOX_OWNER_ENTRYID])) { return $items; } $folderEntryid = bin2hex((string) $folderEntryid); $storeEntryid = bin2hex((string) $storeProps[PR_ENTRYID]); // if start was not set, get items one month back if ($start === false) { $start = time() - 2592000; } // if end was not set, get items 3 months ahead if ($end === false) { $end = time() + 7776000; } try { $fbdata = mapi_getuserfreebusy($GLOBALS['mapisession']->getSession(), $storeProps[PR_MAILBOX_OWNER_ENTRYID], $start, $end); } catch (MAPIException $e) { // No free/busy rights either: the calendar is simply empty for this user if ($e->getCode() != MAPI_E_NO_ACCESS) { error_log(sprintf("getFreebusyItems: %s (0x%08X)", $e->getMessage(), $e->getCode())); } return $items; } $fbEvents = $fbdata['fbevents'] ?? []; foreach ($fbEvents as $fbEvent) { // check if the event is in start - end range if ($fbEvent['end'] < $start || $fbEvent['start'] > $end) { continue; } $isPrivate = $fbEvent['private'] ?? false; $items[] = [ // entryid is required, generate a fake one if a real is not available 'entryid' => isset($fbEvent['id']) ? bin2hex($fbEvent['id']) : bin2hex(random_bytes(16)), 'parent_entryid' => $folderEntryid, 'store_entryid' => $storeEntryid, 'props' => [ 'access' => 0, 'subject' => $isPrivate ? _('Private Appointment') : ($fbEvent['subject'] ?? _('Busy')), 'normalized_subject' => $isPrivate ? _('Private Appointment') : ($fbEvent['subject'] ?? _('Busy')), 'location' => $isPrivate ? '' : ($fbEvent['location'] ?? ''), 'startdate' => $fbEvent['start'], 'duedate' => $fbEvent['end'], 'commonstart' => $fbEvent['start'], 'commonend' => $fbEvent['end'], 'message_class' => 'IPM.Appointment', 'object_type' => MAPI_MESSAGE, 'icon_index' => 1024, 'display_to' => '', 'display_cc' => '', 'display_bcc' => '', 'importance' => 1, 'sensitivity' => 0, 'message_size' => 0, 'hasattach' => false, 'sent_representing_entryid' => '', 'sent_representing_name' => '', 'sent_representing_address_type' => '', 'sent_representing_email_address' => '', 'sent_representing_search_key' => '', 'sender_email_address' => '', 'sender_name' => '', 'sender_address_type' => '', 'sender_entryid' => '', 'sender_search_key' => '', 'recurring' => false, 'recurring_data' => '', 'recurring_pattern' => '', 'meeting' => $fbEvent['meeting'] ?? false, 'reminder' => 0, 'reminder_minutes' => 0, 'private' => $isPrivate, ], ]; } return $items; } }