Initial upload to Gitea

This commit is contained in:
antonn committed 2026-11-30 16:32:37 +00:00
1 parent 78193254ad
commit 8478998cae
1485 files changed
+461025 -42348

No files matched your search

@@ -0,0 +1,434 @@
<?php
/*
* SPDX-FileCopyrightText: Copyright 2020 - 2026 grommunio GmbH
* SPDX-FileCopyrightText: Copyright 2016 Kopano and its licensors
* SPDX-FileCopyrightText: Copyright 2005 - 2016 Zarafa B.V. and its licensors
* SPDX-License-Identifier: AGPL-3.0-or-later
*/
/**
* Read Mail ItemModule.
*/
class AddressbookItemModule extends ItemModule {
private $userDetailProperties;
private $abObjectDetailProperties;
private $groupDetailProperties;
/**
* Constructor.
*
* @param int $id unique id
* @param array $data list of all actions
*/
public function __construct($id, $data) {
$this->userDetailProperties = $GLOBALS["properties"]->getAddressBookItemMailuserProperties();
$this->abObjectDetailProperties = $GLOBALS["properties"]->getAddressBookItemABObjectProperties();
$this->groupDetailProperties = $GLOBALS["properties"]->getAddressBookItemDistlistProperties();
parent::__construct($id, $data);
}
/**
* Function which opens an item.
*
* @param object $store MAPI Message Store Object
* @param string $entryid entryid of the message
* @param array $action the action data, sent by the client
*/
#[Override]
public function open($store, $entryid, $action) {
if ($entryid) {
$data = [];
try {
$abentry = mapi_ab_openentry($GLOBALS["mapisession"]->getAddressbook(false, true), $entryid);
}
catch (MAPIException $e) {
// If the item not found in addressbook, it might be possible that
// this particular item was added by setup-contact-provider mechanism.
// Let us try to get that particular contact item in respective user store.
// @Fixme: After implementation of KC-350 this extra handling can be removed.
if ($e->getCode() == MAPI_E_NOT_FOUND || $e->getCode() == MAPI_E_INVALID_PARAMETER) {
if ($GLOBALS['entryid']->hasNoMuid(bin2hex($entryid))) {
$entryid = substr($entryid, 0, -1);
}
else {
// unwrap ab entry id
$entryid = substr($entryid, 28);
}
try {
$contactItem = $GLOBALS['operations']->openMessage($GLOBALS['mapisession']->getDefaultMessageStore(), $entryid);
}
catch (MAPIException $me) {
if (!empty($action['store_entryid'])) {
$e->setHandled();
$me->setHandled();
$userStore = $GLOBALS['mapisession']->openMessageStore(hex2bin((string) $action['store_entryid']));
$contactItem = $GLOBALS['operations']->openMessage($userStore, $entryid);
}
}
finally {
if (isset($contactItem) && $contactItem != false) {
// Get necessary property from respective contact item
$contactItemProps = mapi_getprops($contactItem, [PR_GIVEN_NAME, PR_DISPLAY_NAME, PR_TITLE, PR_COMPANY_NAME]);
// Use the data retrieved from contact item to prepare response
// as similar as it seems like an addressbook item.
$data['props'] = [
'object_type' => MAPI_MAILUSER,
'given_name' => $contactItemProps[PR_GIVEN_NAME],
'display_name' => $contactItemProps[PR_DISPLAY_NAME],
'title' => $contactItemProps[PR_TITLE],
'company_name' => $contactItemProps[PR_COMPANY_NAME],
];
$data['entryid'] = bin2hex($entryid);
$this->addActionData("item", $data);
$GLOBALS["bus"]->addData($this->getResponseData());
return;
}
}
}
}
if (mapi_last_hresult() == NOERROR && $abentry) {
$objecttypeprop = mapi_getprops($abentry, [PR_OBJECT_TYPE]);
if (isset($objecttypeprop[PR_OBJECT_TYPE])) {
// Get the properties for a MAILUSER object and process those MAILUSER specific props that require some more actions
if ($objecttypeprop[PR_OBJECT_TYPE] == MAPI_MAILUSER) {
$messageprops = mapi_getprops($abentry, $this->userDetailProperties);
$props = Conversion::mapMAPI2XML($this->userDetailProperties, $messageprops);
if (isset($messageprops[PR_EMS_AB_THUMBNAIL_PHOTO])) {
$props['props']['ems_ab_thumbnail_photo'] = $GLOBALS['operations']->compressedImage($messageprops[PR_EMS_AB_THUMBNAIL_PHOTO]);
}
// Get the properties of the manager
$managerProps = $this->getManagerDetails($messageprops);
if ($managerProps !== false) {
$props['ems_ab_manager'] = [
'item' => $managerProps,
];
}
$homePhoneNumbers = $this->getHomePhoneNumbers($messageprops);
if (!empty($homePhoneNumbers)) {
// Add the list of home2_telephone_number_mv in the correct format to $props list to be send to the client
$props['home2_telephone_numbers'] = [
'item' => $homePhoneNumbers,
];
}
$businessPhoneNumbers = $this->getBusinessPhoneNumbers($messageprops);
if (!empty($businessPhoneNumbers)) {
// Add the list of business2_telephone_number_mv in the correct format to $props list to be send to the client
$props['business2_telephone_numbers'] = [
'item' => $businessPhoneNumbers,
];
}
// Get the properties of the "direct reports"
$directReportsList = $this->getDirectReportsDetails($messageprops);
if (!empty($directReportsList)) {
// Add the list of proxy_addresses in the correct format to the $props list to be send to the client.
$props['ems_ab_reports'] = [
'item' => $directReportsList,
];
}
// Get the properties for a DISTLIST object and process those DISTLIST specific props that require some more actions
}
else {
$messageprops = mapi_getprops($abentry, $this->groupDetailProperties);
$props = Conversion::mapMAPI2XML($this->groupDetailProperties, $messageprops);
// Get the properties of the owner
$ownerProps = $this->getOwnerDetails($messageprops);
if ($ownerProps !== false) {
// We can use the same properties as we use for the manager in a MAILUSER
$props['ems_ab_owner'] = [
'item' => $ownerProps,
];
}
// Get the list of members for this DISTLSIT
$props['members'] = [
'item' => $this->getMembersDetails($abentry),
];
}
// Get the proxy addresses list, this property exists in both MAILUSER and DISTLIST
$proxyAddresses = $this->getProxyAddressesDetails($messageprops);
// Remove the MV-flagged property
if (!empty($proxyAddresses)) {
// Add the list of proxy_addresses in the correct format to the $props list to be send to the client.
$props['ems_ab_proxy_addresses'] = [
'item' => $proxyAddresses,
];
}
// Get the properties of the group membership, this property exists in both MAILUSER and DISTLIST
$memberOfList = $this->getMemberOfDetails($messageprops);
if (!empty($memberOfList)) {
// Add the list of proxy_addresses in the correct format to the $props list to be send to the client.
$props['ems_ab_is_member_of_dl'] = [
'item' => $memberOfList,
];
}
// Remove the MV-flagged properties and also its single valued counterpart
unset($props['props']['ems_ab_is_member_of_dl'], $props['props']['business2_telephone_number_mv'], $props['props']['business2_telephone_number'], $props['props']['home2_telephone_number_mv'], $props['props']['home2_telephone_number'], $props['props']['ems_ab_proxy_addresses'], $props['props']['ems_ab_reports_mv'], $props['props']['ems_ab_reports'], $props['props']['ems_ab_owner'], $props['props']['ems_ab_manager']);
// Allowing to hook in and add more properties
$GLOBALS['PluginManager']->triggerHook("server.module.addressbookitemmodule.open.props", [
'moduleObject' => &$this,
'abentry' => $abentry,
'object_type' => $objecttypeprop[PR_OBJECT_TYPE],
'messageprops' => $messageprops,
'props' => &$props,
]);
$data["item"] = $props;
$this->addActionData("item", $data);
}
else {
// Handling error: not able to handle this type of object
$data["error"] = [];
$data["error"]["message"] = _("Could not handle this type of object.");
$this->addActionData("error", $data);
}
}
else {
// Handle not being able to open the object
$data["error"] = [];
$data["error"]["hresult"] = mapi_last_hresult();
$data["error"]["hresult_name"] = get_mapi_error_name(mapi_last_hresult());
$data["error"]["message"] = _("Could not open this object.");
$this->addActionData("error", $data);
}
$GLOBALS["bus"]->addData($this->getResponseData());
}
}
/**
* Get Business Telephone numbers in the messageprops array when it is set in the
* PR_HOME2_TELEPHONE_NUMBER_MV. This property is poorly documented and in Outlook it checks
* the property with and without the MV flag. The one without a MV flag can contain only one
* entry and the one with MV flag can contain a list. It then merges both into one list.
* This function has the same behavior and sets the list in the $messageprops.
*
* @param $messageprops Array Details properties of an user entry
*
* @return array List of telephone numbers
*/
public function getHomePhoneNumbers($messageprops) {
$list = [];
if (isset($messageprops[$this->userDetailProperties['home2_telephone_number']])) {
$list[] = $messageprops[$this->userDetailProperties['home2_telephone_number']];
}
if (isset($messageprops[$this->userDetailProperties['home2_telephone_number_mv']])) {
$list = array_merge($list, $messageprops[$this->userDetailProperties['home2_telephone_number_mv']]);
}
$returnList = [];
for ($i = 0, $len = count($list); $i < $len; ++$i) {
array_push($returnList, ['number' => $list[$i]]);
}
return $returnList;
}
/**
* Get Business Telephone numbers in the messageprops array when it is set in the
* PR_BUSINESS2_TELEPHONE_NUMBER_MV. This property is poorly documented and in Outlook it checks
* the property with and without the MV flag. The one without a MV flag can contain only one
* entry and the one with MV flag can contain a list. It then merges both into one list.
* This function has the same behavior and sets the list in the $messageprops.
*
* @param $messageprops Array Details properties of an user entry
*
* @return array List of telephone numbers
*/
public function getBusinessPhoneNumbers($messageprops) {
$list = [];
if (isset($messageprops[$this->userDetailProperties['business2_telephone_number']])) {
$list[] = $messageprops[$this->userDetailProperties['business2_telephone_number']];
}
if (isset($messageprops[$this->userDetailProperties['business2_telephone_number_mv']])) {
$list = array_merge($list, $messageprops[$this->userDetailProperties['business2_telephone_number_mv']]);
}
$returnList = [];
for ($i = 0, $len = count($list); $i < $len; ++$i) {
array_push($returnList, ['number' => $list[$i]]);
}
return $returnList;
}
/**
* Get Proxy Addresses in the messageprops array when it is set in the
* PR_EMS_AB_PROXY_ADDRESSES. This property is poorly documented and in Outlook it checks
* the property with and without the MV flag. The one without a MV flag can contain only one
* entry and the one with MV flag can contain a list. It then merges both into one list.
* This function has the same behavior and sets the list in the $messageprops.
*
* @param $messageprops Array Details properties of an user entry
*
* @return array List of addresses
*/
public function getProxyAddressesDetails($messageprops) {
$returnList = [];
if (isset($messageprops[$this->userDetailProperties['ems_ab_proxy_addresses']]) &&
is_array($messageprops[$this->userDetailProperties['ems_ab_proxy_addresses']])) {
foreach ($messageprops[$this->userDetailProperties['ems_ab_proxy_addresses']] as $eapa) {
$returnList[] = ['address' => $eapa];
}
}
return $returnList;
}
/**
* Get the information of the manager from the GAB details of a MAPI_MAILUSER. Will use the
* entryid to get the properties. If no entryid if found false is returned.
*
* @param $messageprops Array Details properties of an user entry
*
* @return array|bool List of properties or false if no manager is set
*/
public function getManagerDetails($messageprops) {
if (isset($messageprops[$this->userDetailProperties['ems_ab_manager']])) {
$entryidMananager = $messageprops[$this->userDetailProperties['ems_ab_manager']];
$managerEntry = mapi_ab_openentry($GLOBALS["mapisession"]->getAddressbook(), $entryidMananager);
$managerProps = mapi_getprops($managerEntry, $this->abObjectDetailProperties);
return Conversion::mapMAPI2XML($this->abObjectDetailProperties, $managerProps);
}
return false;
}
/**
* Get the list of users that have been set in the PR_EMS_AB_REPORTS property in the
* $messageprops array. This property is poorly documented and in Outlook it checks
* the property with and without the MV flag. The one without a MV flag can contain only one
* entry and the one with MV flag can contain a list. It then merges both into one list.
* This function has the same behavior and sets the list in the $messageprops.
*
* @param $messageprops Array Details properties of an user entry
*
* @return array|bool List of properties or false if no manager is set
*/
public function getDirectReportsDetails($messageprops) {
/*
* Get the entryIds from the PR_EMS_AB_REPORTS property (with and without MV flag as a
* fallback) and put the entryIds in a list.
*/
$entryids = [];
if (isset($messageprops[$this->userDetailProperties['ems_ab_reports']])) {
$entryids[] = $messageprops[$this->userDetailProperties['ems_ab_reports']];
}
if (isset($messageprops[$this->userDetailProperties['ems_ab_reports_mv']])) {
$entryids = array_merge($entryids, $messageprops[$this->userDetailProperties['ems_ab_reports_mv']]);
}
$result = [];
// Convert the entryIds in an array of properties of the AB entryies
for ($i = 0, $len = count($entryids); $i < $len; ++$i) {
// Get the properties from the AB entry
$entry = mapi_ab_openentry($GLOBALS["mapisession"]->getAddressbook(), $entryids[$i]);
$props = mapi_getprops($entry, $this->abObjectDetailProperties);
// Convert the properties for each entry and put it in an array
$result[] = Conversion::mapMAPI2XML($this->abObjectDetailProperties, $props);
}
return $result;
}
/**
* Get the list of users that have been set in the PR_EMS_AB_MEMBER_OF_DL property in the
* $messageprops array. This property is poorly documented and in Outlook it checks
* the property with and without the MV flag. The one without a MV flag can contain only one
* entry and the one with MV flag can contain a list. It then merges both into one list.
* This function has the same behavior and sets the list in the $messageprops.
*
* @param $messageprops Array Details properties of an user entry
*
* @return array|bool List of properties or false if no manager is set
*/
public function getMemberOfDetails($messageprops) {
$result = [];
// Get the properties of the group membership
if (isset($messageprops[$this->userDetailProperties['ems_ab_is_member_of_dl']])) {
$entryids = $messageprops[$this->userDetailProperties['ems_ab_is_member_of_dl']];
// Get the properties from every entryid in the memberOf list
for ($i = 0, $len = count($entryids); $i < $len; ++$i) {
// Get the properties from the AB entry
$entry = mapi_ab_openentry($GLOBALS["mapisession"]->getAddressbook(), $entryids[$i]);
$props = mapi_getprops($entry, $this->abObjectDetailProperties);
// Convert the properties for each entry and put it in an array
$result[] = Conversion::mapMAPI2XML($this->abObjectDetailProperties, $props);
}
}
return $result;
}
/**
* Get the information of the owner from the GAB details of a MAPI_DISTLIST. Will use the
* entryid to get the properties. If no entryid if found false is returned.
*
* @param $messageprops Array Details properties of an distlist entry
*
* @return array|bool List of properties or false if no owner is set
*/
public function getOwnerDetails($messageprops) {
if (isset($messageprops[$this->groupDetailProperties['ems_ab_owner']])) {
$entryidOwner = $messageprops[$this->groupDetailProperties['ems_ab_owner']];
$ownerEntry = mapi_ab_openentry($GLOBALS["mapisession"]->getAddressbook(), $entryidOwner);
$ownerProps = mapi_getprops($ownerEntry, $this->abObjectDetailProperties);
return Conversion::mapMAPI2XML($this->abObjectDetailProperties, $ownerProps);
}
return false;
}
/**
* Get the information of the members from the GAB details of a MAPI_DISTLIST. The
* information can be found in the contentstable of the AB entry opened by the user.
*
* @param $abentry Resource Reference to the user-opened AB entry
*
* @return array|bool List of members
*/
public function getMembersDetails($abentry) {
$result = [];
$table = mapi_folder_getcontentstable($abentry, MAPI_DEFERRED_ERRORS);
/*
* To prevent loading a huge list that the browser cannot handle, it is possible to
* limit the maximum number of shown items. Note that when the table doesn't
* contain the requested number of rows, it will not give any errors and simply
* return what is available.
* When the limit is 0 or below, then no limit is applied and we use 0x7fffffff
* to indicate we want to have all rows from the table.
*/
$rows = mapi_table_queryrows($table, $this->abObjectDetailProperties, 0, (ABITEMDETAILS_MAX_NUM_DISTLIST_MEMBERS > 0) ? ABITEMDETAILS_MAX_NUM_DISTLIST_MEMBERS : 0x7FFFFFFF);
for ($i = 0, $len = count($rows); $i < $len; ++$i) {
$result[] = Conversion::mapMAPI2XML($this->abObjectDetailProperties, $rows[$i]);
}
return $result;
}
}
@@ -0,0 +1,813 @@
<?php
/*
* SPDX-FileCopyrightText: Copyright 2020 - 2026 grommunio GmbH
* SPDX-FileCopyrightText: Copyright 2016 Kopano and its licensors
* SPDX-FileCopyrightText: Copyright 2005 - 2016 Zarafa B.V. and its licensors
* SPDX-License-Identifier: AGPL-3.0-or-later
*/
require_once BASE_PATH . 'server/includes/core/class.indexsqlite.php';
require_once BASE_PATH . 'server/includes/core/class.ftsrestrictionconverter.php';
class AdvancedSearchListModule extends ListModule {
/**
* Length gromox truncates PT_UNICODE cells of a table row to. Applied to
* properties read off an opened message so both paths return equal rows.
*/
private const LIST_STRING_CAP = 255;
/**
* Set once publicStoreSearch() has run for this request, so the
* messageList() fallback below does not try the same index again.
*/
private $publicSearchAttempted = false;
/**
* Constructor.
*
* @param int $id unique id
* @param array $data list of all actions
*/
public function __construct($id, $data) {
parent::__construct($id, $data);
// TODO: create a new method in Properties class that will return only the properties we
// need for search list (and perhaps for preview???)
$this->properties = $GLOBALS["properties"]->getMailListProperties();
$this->properties = array_merge($this->properties, $GLOBALS["properties"]->getAppointmentListProperties());
$this->properties = array_merge($this->properties, $GLOBALS["properties"]->getContactListProperties());
$this->properties = array_merge($this->properties, $GLOBALS["properties"]->getStickyNoteListProperties());
$this->properties = array_merge($this->properties, $GLOBALS["properties"]->getTaskListProperties());
// Note: no html_body here. Table rows are truncated by the server
// (gromox caps table cells), and a truncated html_body from the row
// would survive the open merge and poison the preview pane whenever
// the opened item returns no html_body (e.g. plaintext mails).
$this->properties = array_merge($this->properties, [
'body' => PR_BODY,
'startdate' => "PT_SYSTIME:PSETID_Appointment:" . PidLidAppointmentStartWhole,
'duedate' => "PT_SYSTIME:PSETID_Appointment:" . PidLidAppointmentEndWhole,
'creation_time' => PR_CREATION_TIME,
"task_duedate" => "PT_SYSTIME:PSETID_Task:" . PidLidTaskDueDate,
]);
$this->properties = getPropIdsFromStrings($GLOBALS["mapisession"]->getDefaultMessageStore(), $this->properties);
$this->sort = [
PR_MESSAGE_DELIVERY_TIME => TABLE_SORT_DESCEND,
];
}
/**
* Returns the domain a public store entryid points at, or null when the
* action does not address a public store.
*
* This reads the store entryid the client already sent instead of asking
* the server for PR_MDB_PROVIDER, so recognising the (far more common)
* private store costs no extra round trip.
*
* @param array $action the action data, sent by the client
*
* @return null|string
*/
private function publicStoreDomain($action) {
if (empty($action['store_entryid'])) {
return null;
}
$eidObj = $GLOBALS["entryid"]->createMsgStoreEntryIdObj(hex2bin((string) $action['store_entryid']));
if (($eidObj['WrappedProviderUID'] ?? '') !== MUID_STORE_PUBLIC_GUID) {
return null;
}
$domain = $eidObj['ServerShortname'] ?? '';
return $domain === '' ? null : $domain;
}
/**
* Answers a search in a public store from the fulltext index.
*
* The index is keyed by the domain name, which is what gromox puts into
* the public store entryid as the server shortname, and grommunio-index
* writes it to the same place as the per-user indexes.
*
* @param resource $store MAPI message store
* @param string $entryid entryid of the folder to search in
* @param array $action the action data, sent by the client
* @param string $actionType the action type to answer with
* @param null|string $domain domain owning the public store
*
* @return bool true when the response was sent, false to fall back
*/
private function publicStoreSearch($store, $entryid, $action, $actionType, $domain) {
$this->publicSearchAttempted = true;
if ($domain === null) {
return false;
}
$this->searchFolderList = true;
$this->restriction = false;
$this->parseRestriction($action);
if ($this->restriction === false) {
return false;
}
$ftsDescriptor = $this->buildFtsDescriptor($this->restriction);
if (empty($ftsDescriptor['ast'])) {
return false;
}
if (is_array($ftsDescriptor['message_classes']) &&
count($ftsDescriptor['message_classes']) >= 7) {
$ftsDescriptor['message_classes'] = null;
}
$indexDB = new IndexSqlite($domain, $GLOBALS["mapisession"]->getSession(), $store);
if (!$indexDB->is_open()) {
return false;
}
/*
* "subfolders" only rides along with the initial search request, so
* remember it for the paging requests that follow.
*/
$recursive = isset($action["subfolders"]) && $action["subfolders"] == "true";
$scopeKey = md5(bin2hex($entryid) . $domain);
if (!is_array($this->sessionData)) {
$this->sessionData = [];
}
if (isset($action["subfolders"])) {
$this->sessionData['publicSearchRecursive'][$scopeKey] = $recursive;
}
else {
$recursive = $this->sessionData['publicSearchRecursive'][$scopeKey] ?? false;
}
$this->logFtsDebug('Dispatching public store search to index backend', [
'domain' => $domain,
'recursive' => $recursive,
'message_classes' => $ftsDescriptor['message_classes'] ?? null,
'ast' => $ftsDescriptor['ast'] ?? null,
]);
$entryids = $indexDB->searchEntryIds($ftsDescriptor, $entryid, $recursive);
if ($entryids === false) {
return false;
}
$this->parseSortOrder($action, null, true);
$limit = $action['restriction']['limit'] ?? $GLOBALS['settings']->get('grommunio/v1/main/page_size', 50);
$limit = max(1, (int) $limit);
$start = max(0, (int) $this->start);
$data = ["item" => []];
/*
* The index hands back the hits ordered by date, newest first, and the
* page is cut from that list so only the messages actually shown have
* to be opened. A sort on any other column therefore only orders the
* page, not the whole result set - the index has no data to sort the
* rest by.
*/
foreach (array_slice($entryids, $start, $limit) as $messageEntryid) {
try {
$message = mapi_msgstore_openentry($store, $messageEntryid);
}
catch (Exception $e) {
$this->logFtsDebug('Skipping unreadable search hit', [
'error' => $e->getMessage(),
]);
continue;
}
if ($message === false) {
continue;
}
$row = mapi_getprops($message, $this->properties);
/*
* A table row arrives with its string cells already truncated by
* the server; reading the properties off an opened message does
* not, which would put whole message bodies into a list response.
* Cut them to the same length the table would have returned.
*/
foreach ($row as $tag => $value) {
$type = $tag & 0xFFFF;
if (($type === PT_UNICODE || $type === PT_STRING8) &&
is_string($value) && mb_strlen($value) > self::LIST_STRING_CAP) {
$row[$tag] = mb_substr($value, 0, self::LIST_STRING_CAP);
}
}
$item = Conversion::mapMAPI2XML($this->properties, $row);
// Mirror getTable(): the list view expects the *_username aliases
if (isset($item['props']["sent_representing_email_address"])) {
$item['props']["sent_representing_username"] = $item['props']["sent_representing_email_address"];
}
if (isset($item['props']["sender_email_address"])) {
$item['props']["sender_username"] = $item['props']["sender_email_address"];
}
if (isset($item['props']["received_by_email_address"])) {
$item['props']["received_by_username"] = $item['props']["received_by_email_address"];
}
$data["item"][] = $item;
}
$data["page"] = [
"start" => $start,
"rowcount" => $limit,
"totalrowcount" => count($entryids),
];
$this->getDelegateFolderInfo($store);
$data = $this->filterPrivateItems($data);
$data["item"] = array_values($data["item"]);
$data["search_meta"] = [
// No searchfolder_entryid: there is no search folder to page
// through, which also tells the client to keep sending the
// restriction along with the next page.
"search_store_entryid" => $action["store_entryid"],
"searchstate" => 0,
"results" => count($data["item"]),
];
$this->addActionData($actionType, $data);
$GLOBALS["bus"]->addData($this->getResponseData());
$this->logFtsDebug('Public store search response dispatched', [
'domain' => $domain,
'total_hits' => count($entryids),
'items_returned' => count($data["item"]),
'start' => $start,
]);
return true;
}
/**
* Executes all the actions in the $data variable.
*/
#[Override]
public function execute() {
foreach ($this->data as $actionType => $action) {
if (isset($actionType)) {
try {
$store = $this->getActionStore($action);
$entryid = $this->getActionSingleEntryID($action);
if ($store === false || is_array($store)) {
$this->sendFeedback(false);
continue;
}
switch ($actionType) {
case "list":
case "updatelist":
$this->getDelegateFolderInfo($store);
$this->messageList($store, $entryid, $action, $actionType);
break;
case "search":
$this->search($store, $entryid, $action, $actionType);
break;
case "updatesearch":
$this->updatesearch($store, $entryid, $action);
break;
case "stopsearch":
$this->stopSearch($store, $entryid, $action);
break;
case "delete_searchfolder":
$this->deleteSearchFolder($store, $entryid, $action);
break;
}
}
catch (MAPIException $e) {
// This is a very nasty hack that makes sure that grommunio Web doesn't show an error message when
// search wants to throw an error. This is only done because a proper fix for this bug has not
// been found yet. When WA-9161 is really solved, this should be removed again.
if ($actionType !== 'search' && $actionType !== 'updatesearch' && $actionType !== 'stopsearch') {
$this->processException($e, $actionType);
}
else {
if (DEBUG_LOADER === 0) {
// Log all info we can get about this error to the error log of the web server
error_log("Error in search: \n" . var_export($e, true) . "\n\n" . var_export(debug_backtrace(), true));
}
// Send success feedback without data, as if nothing strange happened...
$this->sendFeedback(true);
}
}
}
}
}
/**
* Function which retrieves a list of messages in a folder.
*
* @param false|resource $store MAPI message store, or false when unavailable
* @param false|string $entryid entryid of the folder, or false when unavailable
* @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) {
/*
* A public-store search has no search folder for the client to page
* through, so the client re-sends the search restriction as a plain
* list request. Answer those from the index as well, otherwise page 2
* would come from a different search than page 1.
*/
if (!$this->publicSearchAttempted && $store !== false && !is_array($store) &&
is_string($entryid) && $entryid !== '' &&
!empty($action['restriction']['search']) && !isset($action['search_folder_entryid']) &&
$this->publicStoreSearch($store, $entryid, $action, $actionType,
$this->publicStoreDomain($action))) {
return;
}
$this->searchFolderList = false; // Set to indicate this is not the search result, but a normal folder content
$data = [];
if ($store !== false && $entryid !== false) {
// Restriction
$this->parseRestriction($action);
// Sort
$this->parseSortOrder($action, null, true);
$limit = $action['restriction']['limit'] ?? 1000;
$isSearchFolder = isset($action['search_folder_entryid']);
$entryid = $isSearchFolder ? hex2bin((string) $action['search_folder_entryid']) : $entryid;
if ($actionType == 'search') {
$rows = [[PR_ENTRYID => $entryid]];
if (isset($action['subfolders']) && $action['subfolders']) {
$inboxEntryId = null;
try {
$folder = mapi_msgstore_openentry($store, $entryid);
}
catch (Exception) {
// Probably trying to open a store without having appropriate permissions.
// Try to open the inbox instead.
$folder = mapi_msgstore_getreceivefolder($store);
$props = mapi_getprops($folder, [PR_ENTRYID]);
$inboxEntryId = $props[PR_ENTRYID];
}
if (!is_null($folder)) {
$flags = MAPI_DEFERRED_ERRORS;
$eidObj = $GLOBALS["entryid"]->createMsgStoreEntryIdObj(hex2bin((string) $action['store_entryid']));
if (isset($eidObj['MailboxDN'])) {
$sharedUserSetting = $GLOBALS["settings"]->get(
"grommunio/v1/contexts/hierarchy/shared_stores/" . bin2hex(strtolower((string) $eidObj['MailboxDN']))
);
if (isset($sharedUserSetting['all']) ||
(isset($sharedUserSetting['inbox']['show_subfolders']) && $sharedUserSetting['inbox']['show_subfolders'])) {
$flags |= CONVENIENT_DEPTH;
}
}
$htable = mapi_folder_gethierarchytable($folder, $flags);
$rows = mapi_table_queryallrows($htable, [PR_ENTRYID]);
}
// The inbox itself is not the hierarchy list, add it to the begin.
if (!is_null($inboxEntryId)) {
array_unshift($rows, [PR_ENTRYID => $inboxEntryId]);
}
}
$data['item'] = [];
foreach ($rows as $row) {
$items = $GLOBALS["operations"]->getTable($store, $row[PR_ENTRYID], $this->properties, $this->sort, $this->start, $limit, $this->restriction);
$data['item'] = array_merge($data['item'], $items['item']);
if (count($data['item']) >= $limit) {
break;
}
}
$data['page'] = [];
$data['page']['start'] = 0;
$data['page']['rowcount'] = 0;
$data['page']['totalrowcount'] = count($data['item']);
$data['search_meta'] = [];
$data['search_meta']['searchfolder_entryid'] = null;
$data['search_meta']['search_store_entryid'] = $action['store_entryid'];
$data['search_meta']['searchstate'] = null;
$data['search_meta']['results'] = count($data['item']);
$data['folder'] = [];
$data['folder']['content_count'] = count($data['item']);
$data['folder']['content_unread'] = 0;
}
else {
// Get the table and merge the arrays
$data = $GLOBALS["operations"]->getTable($store, $entryid, $this->properties, $this->sort, $this->start, $limit, $this->restriction);
}
// If the request come from search folder then no need to send folder information
if (!$isSearchFolder && !isset($data['folder'])) {
// Open the folder.
$folder = mapi_msgstore_openentry($store, $entryid);
$data["folder"] = [];
// Obtain some statistics from the folder contents
$contentcount = mapi_getprops($folder, [PR_CONTENT_COUNT, PR_CONTENT_UNREAD]);
if (isset($contentcount[PR_CONTENT_COUNT])) {
$data["folder"]["content_count"] = $contentcount[PR_CONTENT_COUNT];
}
if (isset($contentcount[PR_CONTENT_UNREAD])) {
$data["folder"]["content_unread"] = $contentcount[PR_CONTENT_UNREAD];
}
}
$data = $this->filterPrivateItems($data);
// 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,
'entryid' => $entryid,
'action' => $action,
'data' => &$data,
]);
// unset will remove the value but will not regenerate array keys, so we need to
// do it here
$data["item"] = array_values($data["item"]);
$this->addActionData($actionType, $data);
$GLOBALS["bus"]->addData($this->getResponseData());
}
}
private function buildFtsDescriptor($restriction) {
return (new FtsRestrictionConverter($this->properties))->buildDescriptor($restriction);
}
/**
* Function will set search restrictions on search folder and start search process
* and it will also parse visible columns and sorting data when sending results to client.
*
* @param resource $store MAPI message store
* @param false|string $entryid entryid of the folder scope, or false when absent
* @param array $action the action data, sent by the client
* @param string $actionType the action type, sent by the client
*/
#[Override]
public function search($store, $entryid, $action, $actionType) {
$useSearchFolder = $action["use_searchfolder"] ?? false;
$this->logFtsDebug('Search requested', [
'store_entryid' => $action['store_entryid'] ?? null,
'entryid' => $this->formatEntryIdForLog($entryid),
'subfolders' => $action['subfolders'] ?? null,
'use_searchfolder' => (bool) $useSearchFolder,
'restriction_present' => array_key_exists('restriction', $action),
]);
if (!$useSearchFolder) {
$this->logFtsDebug('Search fallback: store does not support search folders', []);
/*
* store doesn't support search folders so we can't use this
* method instead we will pass restriction to messageList and
* it will give us the restricted results
*/
parent::messageList($store, $entryid, $action, "list");
return;
}
if (!is_string($entryid) || $entryid === '') {
$this->sendFeedback(false);
return;
}
$store_props = mapi_getprops($store, [PR_MDB_PROVIDER, PR_DEFAULT_STORE, PR_IPM_SUBTREE_ENTRYID]);
$this->logFtsDebug('Resolved store properties for search', [
'provider' => isset($store_props[PR_MDB_PROVIDER]) ? bin2hex((string) $store_props[PR_MDB_PROVIDER]) : null,
'default_store' => $store_props[PR_DEFAULT_STORE] ?? null,
]);
if ($store_props[PR_MDB_PROVIDER] == ZARAFA_STORE_PUBLIC_GUID) {
/*
* A public store cannot host a search folder (gromox answers
* ecNotSupported), and public messages cannot be linked into a
* private one either, so the usual "link the hits into a search
* folder and read that folder" route is closed. Serve the hits
* straight from the index instead; if there is no usable index,
* fall back to the server-side restriction as before.
*/
if ($this->publicStoreSearch($store, $entryid, $action, "search", $this->publicStoreDomain($action))) {
return true;
}
$this->logFtsDebug('Search fallback: public store without usable index', []);
/*
* Our own messageList() walks the folder hierarchy when the
* request asks for subfolders; ListModule's does not and would
* silently search the one folder, which is what made "include
* subfolders" look broken on public folders.
*/
$this->messageList($store, $entryid, $action, "search");
return;
}
$todoListEntryId = TodoList::getEntryId();
if ($todoListEntryId !== false && $GLOBALS['entryid']->compareEntryIds(bin2hex($entryid), bin2hex($todoListEntryId))) {
$this->logFtsDebug('Search fallback: todo list uses legacy restriction path', []);
// todo list do not need to perform full text index search
parent::messageList($store, $entryid, $action, "list");
return;
}
$this->searchFolderList = true; // Set to indicate this is not the normal folder, but a search folder
$this->restriction = false;
// Parse Restriction
$this->parseRestriction($action);
if ($this->restriction == false) {
$this->logFtsDebug('Restriction parsing failed', [
'action_type' => $actionType,
]);
// if error in creating restriction then send error to client
$errorInfo = [];
$errorInfo["error_message"] = _("Error in search, please try again.");
$errorInfo["original_error_message"] = "Error in parsing restrictions.";
return $this->sendSearchErrorToClient($store, $entryid, $action, $errorInfo);
}
$ftsDescriptor = $this->buildFtsDescriptor($this->restriction);
if (empty($ftsDescriptor['ast'])) {
$this->logFtsDebug('Failed to translate restriction to FTS descriptor', [
'restriction_sample' => array_keys($this->restriction),
]);
$errorInfo = [];
$errorInfo["error_message"] = _("Error in search, please try again.");
$errorInfo["original_error_message"] = "Unable to translate search query to full-text expression.";
return $this->sendSearchErrorToClient($store, $entryid, $action, $errorInfo);
}
$serializedRestriction = serialize($this->restriction);
$restrictionSignature = md5($serializedRestriction);
$this->logFtsDebug('Restriction parsed for full-text search', [
'restriction_signature' => $restrictionSignature,
'fts_descriptor' => $ftsDescriptor,
]);
if (isset($action['search_folder_entryid'])) {
$this->sessionData['searchFolderEntryId'] = $action['search_folder_entryid'];
}
// Each search gets its own freshly created search folder. We populate
// the folder ourselves (entryid by entryid) instead of letting the
// server run the criteria, so a reused folder would accumulate the
// previous result set and, with two searches sharing one folder,
// double-link the same message and stall the mailbox. A fresh folder
// per search keeps the result set correct and isolates concurrent
// searches from each other.
$previousSearchFolderEntryId = $this->sessionData['searchFolderEntryId'] ?? null;
$isSetSearchFolderEntryId = false;
// create or open search folder
$searchFolder = $this->createSearchFolder($store, $isSetSearchFolderEntryId);
if ($searchFolder === false) {
if ($store_props[PR_MDB_PROVIDER] == ZARAFA_STORE_DELEGATE_GUID) {
$this->messageList($store, $entryid, $action, "search");
return true;
}
// if error in creating search folder then send error to client
$errorInfo = [];
$errorInfo["error_message"] = match (mapi_last_hresult()) {
MAPI_E_NO_ACCESS => _("Unable to perform search query, no permissions to create search folder."),
MAPI_E_NOT_FOUND => _("Unable to perform search query, search folder not found."),
default => _("Unable to perform search query, store might not support searching."),
};
$errorInfo["original_error_message"] = _("Error in creating search folder.");
return $this->sendSearchErrorToClient($store, $entryid, $action, $errorInfo);
}
// Retire the folder used by the previous search in this session now
// that a fresh one is in place, so old search folders do not pile up.
if ($previousSearchFolderEntryId !== null &&
$previousSearchFolderEntryId !== ($this->sessionData['searchFolderEntryId'] ?? null)) {
$searchFolderRoot = $this->getSearchFoldersRoot($store);
if ($searchFolderRoot !== false) {
$this->safeDeleteSearchFolder($searchFolderRoot, hex2bin((string) $previousSearchFolderEntryId));
}
}
$subfolder_flag = 0;
$recursive = false;
if (isset($action["subfolders"]) && $action["subfolders"] == "true") {
$recursive = true;
$subfolder_flag = RECURSIVE_SEARCH;
}
$entryids = (array) $entryid;
$searchFolderEntryId = $this->sessionData['searchFolderEntryId'];
// check if searchcriteria has changed
$restrictionCheck = md5($serializedRestriction . $searchFolderEntryId . $subfolder_flag);
// check if there is need to set searchcriteria again
if (!isset($this->sessionData['searchCriteriaCheck']) || $restrictionCheck != $this->sessionData['searchCriteriaCheck']) {
if (!empty($this->sessionData['searchOriginalEntryids']) &&
isset($action['entryid']) &&
in_array($action['entryid'], $this->sessionData['searchOriginalEntryids'])
) {
// get entryids of original folders, and use it to set new search criteria
$entryids = [];
$entryIdsCount = count($this->sessionData['searchOriginalEntryids']);
for ($index = 0; $index < $entryIdsCount; ++$index) {
$entryids[] = hex2bin((string) $this->sessionData['searchOriginalEntryids'][$index]);
}
}
else {
// store entryids of original folders, so that can be used for re-setting the search criteria if needed
$this->sessionData['searchOriginalEntryids'] = [];
for ($index = 0, $len = count($entryids); $index < $len; ++$index) {
$this->sessionData['searchOriginalEntryids'][] = bin2hex($entryids[$index]);
}
}
// we never start the search folder because we will populate the search folder by ourselves
mapi_folder_setsearchcriteria($searchFolder, $this->restriction, $entryids, $subfolder_flag | STOP_SEARCH);
$this->logFtsDebug('Search criteria updated', [
'search_folder_entryid' => $searchFolderEntryId,
'restriction_signature' => $restrictionSignature,
'recursive' => $recursive,
'scope_entryids' => $this->formatEntryIdForLog($entryids),
]);
$this->sessionData['searchCriteriaCheck'] = $restrictionCheck;
}
if (isset($this->sessionData['searchCriteriaCheck']) || $restrictionCheck == $this->sessionData['searchCriteriaCheck']) {
$folderEntryid = bin2hex($entryid);
if ($this->sessionData['searchOriginalEntryids'][0] !== $folderEntryid) {
$this->sessionData['searchOriginalEntryids'][0] = $folderEntryid;
// we never start the search folder because we will populate the search folder by ourselves
mapi_folder_setsearchcriteria($searchFolder, $this->restriction, [$entryid], $subfolder_flag | STOP_SEARCH);
$this->logFtsDebug('Search criteria refreshed for active folder', [
'search_folder_entryid' => $searchFolderEntryId,
'restriction_signature' => $restrictionSignature,
'target_entryid' => $this->formatEntryIdForLog($entryid),
'recursive' => $recursive,
]);
}
}
// Sort; multi-instance is folded back into one row per item by getTable()
$this->parseSortOrder($action, null, true);
// Initialize search patterns with default values
if (is_array($ftsDescriptor['message_classes']) &&
count($ftsDescriptor['message_classes']) >= 7) {
$ftsDescriptor['message_classes'] = null;
}
$username = null;
$indexDB = null;
if ($store_props[PR_MDB_PROVIDER] == ZARAFA_STORE_DELEGATE_GUID) {
$eidObj = $GLOBALS["entryid"]->createMsgStoreEntryIdObj(hex2bin((string) $action['store_entryid']));
$username = $eidObj['ServerShortname'];
$session = $GLOBALS["mapisession"]->getSession();
if ($username) {
$indexDB = new IndexSqlite($username, $session, $store);
}
}
else {
$indexDB = new IndexSqlite();
}
if (!($indexDB instanceof IndexSqlite) || !$indexDB->is_open()) {
return parent::search($store, $entryid, $action, $actionType);
}
$this->logFtsDebug('Dispatching search to index backend', [
'search_folder_entryid' => $searchFolderEntryId,
'restriction_signature' => $restrictionSignature,
'recursive' => $recursive,
'delegate_username' => $username,
'message_classes' => $ftsDescriptor['message_classes'] ?? null,
'filters' => [
'date_start' => $ftsDescriptor['date_start'] ?? null,
'date_end' => $ftsDescriptor['date_end'] ?? null,
'unread' => !empty($ftsDescriptor['unread']),
'has_attachments' => !empty($ftsDescriptor['has_attachments']),
],
'ast' => $ftsDescriptor['ast'] ?? null,
]);
$search_result = $indexDB->search(hex2bin((string) $searchFolderEntryId), $ftsDescriptor, $entryid, $recursive);
if ($search_result === false) {
$this->logFtsDebug('Index search returned no data', [
'search_folder_entryid' => $searchFolderEntryId,
'restriction_signature' => $restrictionSignature,
'recursive' => $recursive,
]);
$errorInfo = [];
$errorInfo["error_message"] = _("Unable to perform search query, store might not support searching.");
$errorInfo["original_error_message"] = "Full-text search backend returned no result set.";
return $this->sendSearchErrorToClient($store, $entryid, $action, $errorInfo);
}
unset($action["restriction"]);
// Get the table and merge the arrays
$table = $GLOBALS["operations"]->getTable($store, hex2bin((string) $searchFolderEntryId), $this->properties, $this->sort, $this->start);
$this->logFtsDebug('Search folder table retrieved', [
'search_folder_entryid' => $searchFolderEntryId,
'table_item_count' => isset($table['item']) ? count($table['item']) : null,
'start' => $this->start,
'sort' => $this->sort,
]);
// Create the data array, which will be send back to the client
$data = [];
$data = array_merge($data, $table);
$this->getDelegateFolderInfo($store);
$data = $this->filterPrivateItems($data);
$this->logFtsDebug('Search results filtered for privacy', [
'search_folder_entryid' => $searchFolderEntryId,
'item_count_after_filter' => isset($data['item']) ? count($data['item']) : null,
]);
// remember which entryid's are send to the client
$searchResults = [];
foreach ($table["item"] as $item) {
// store entryid => last_modification_time mapping
$searchResults[$item["entryid"]] = $item["props"]["last_modification_time"];
}
// store search results into session data
if (!isset($this->sessionData['searchResults'])) {
$this->sessionData['searchResults'] = [];
}
$this->sessionData['searchResults'][$searchFolderEntryId] = $searchResults;
$this->logFtsDebug('Search results stored in session', [
'search_folder_entryid' => $searchFolderEntryId,
'result_count' => count($searchResults),
]);
$result = mapi_folder_getsearchcriteria($searchFolder);
$this->logFtsDebug('Search folder state retrieved', [
'search_folder_entryid' => $searchFolderEntryId,
'searchstate' => $result['searchstate'] ?? null,
]);
$data["search_meta"] = [];
$data["search_meta"]["searchfolder_entryid"] = $searchFolderEntryId;
$data["search_meta"]["search_store_entryid"] = $action["store_entryid"];
$data["search_meta"]["searchstate"] = $result["searchstate"];
$data["search_meta"]["results"] = count($searchResults);
// Reopen the search folder, because otherwise the suggestion property will
// not have been updated
$searchFolder = $this->createSearchFolder($store, true);
$storeProps = mapi_getprops($searchFolder, [PR_EC_SUGGESTION]);
if (isset($storeProps[PR_EC_SUGGESTION])) {
$data["search_meta"]["suggestion"] = $storeProps[PR_EC_SUGGESTION];
$this->logFtsDebug('Search suggestion ready', [
'search_folder_entryid' => $searchFolderEntryId,
'suggestion' => $storeProps[PR_EC_SUGGESTION],
]);
}
$this->addActionData("search", $data);
$GLOBALS["bus"]->addData($this->getResponseData());
$this->logFtsDebug('Search response dispatched to client', [
'search_folder_entryid' => $searchFolderEntryId,
'items_returned' => isset($data['item']) ? count($data['item']) : null,
'search_meta' => $data['search_meta'] ?? null,
]);
return true;
}
private function logFtsDebug(string $message, array $context = []): void {
if (!DEBUG_FULLTEXT_SEARCH) {
return;
}
$prefix = '[fts-debug][module] ';
if (!empty($context)) {
$encoded = json_encode($context, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
if ($encoded === false) {
$encoded = 'context_encoding_failed';
}
error_log($prefix . $message . ' ' . $encoded);
}
else {
error_log($prefix . $message);
}
}
private function formatEntryIdForLog($entryid) {
if ($entryid === null) {
return null;
}
if (is_array($entryid)) {
return array_map([$this, 'formatEntryIdForLog'], $entryid);
}
if (!is_string($entryid)) {
return $entryid;
}
if ($entryid === '') {
return '';
}
if (preg_match('/[^\x20-\x7E]/', $entryid)) {
return bin2hex($entryid);
}
return $entryid;
}
}
@@ -0,0 +1,399 @@
<?php
/*
* SPDX-FileCopyrightText: Copyright 2020 - 2026 grommunio GmbH
* SPDX-FileCopyrightText: Copyright 2016 Kopano and its licensors
* SPDX-FileCopyrightText: Copyright 2005 - 2016 Zarafa B.V. and its licensors
* SPDX-License-Identifier: AGPL-3.0-or-later
*/
/**
* Appointment ItemModule
* Module which opens, creates, saves and deletes an item. It
* extends the Module class.
*/
class AppointmentItemModule extends ItemModule {
/**
* @var string client or server IANA timezone
*/
protected $tziana;
/**
* @var bool|string client timezone definition
*/
protected $tzdef;
/**
* Constructor.
*
* @param int $id unique id
* @param array $data list of all actions
*/
public function __construct($id, $data) {
parent::__construct($id, $data);
$this->properties = $GLOBALS['properties']->getAppointmentProperties();
$this->plaintext = false;
$this->skipCopyProperties = [
$this->properties['goid'],
$this->properties['goid2'],
$this->properties['request_sent'],
PR_OWNER_APPT_ID,
];
$this->tziana = 'Etc/UTC';
$this->tzdef = false;
}
#[Override]
public function open($store, $entryid, $action) {
if ($store && $entryid) {
$data = [];
$message = $GLOBALS['operations']->openMessage($store, $entryid);
if (empty($message)) {
return;
}
// Open embedded message if requested
$attachNum = !empty($action['attach_num']) ? $action['attach_num'] : false;
if ($attachNum) {
// get message props of sub message
$parentMessage = $message;
$message = $GLOBALS['operations']->openMessage($store, $entryid, $attachNum);
if (empty($message)) {
return;
}
$data['item'] = $GLOBALS['operations']->getEmbeddedMessageProps($store, $message, $this->properties, $parentMessage, $attachNum);
}
else {
// add all standard properties from the series/normal message
$data['item'] = $GLOBALS['operations']->getMessageProps($store, $message, $this->properties, $this->plaintext, true);
}
if (!empty($action["timezone_iana"])) {
$this->tziana = $action["timezone_iana"];
$this->tzdef = TimezoneUtil::GetBinaryTZ($action['timezone_iana']);
}
// if appointment is recurring then only we should get properties of occurrence if basedate is supplied
if ($data['item']['props']['recurring'] === true) {
if (!empty($action['basedate'])) {
// check for occurrence/exception
$basedate = $action['basedate'];
$recur = new Recurrence($store, $message);
$exceptionatt = $recur->getExceptionAttachment($basedate);
// Single occurrences are never recurring
$data['item']['props']['recurring'] = false;
if ($exceptionatt) {
// Existing exception (open existing item, which includes basedate)
$exceptionattProps = mapi_getprops($exceptionatt, [PR_ATTACH_NUM]);
$exception = mapi_attach_openobj($exceptionatt, 0);
// overwrite properties with the ones from the exception
$exceptionProps = $GLOBALS['operations']->getMessageProps($store, $exception, $this->properties, $this->plaintext, true);
/*
* If recurring item has set reminder to true then
* all occurrences before the 'flagdueby' value(of recurring item)
* should not show that reminder is set.
*/
if (isset($exceptionProps['props']['reminder']) && $data['item']['props']['reminder'] == true) {
$flagDueByDay = $recur->dayStartOf($data['item']['props']['flagdueby']);
if ($flagDueByDay > $basedate) {
$exceptionProps['props']['reminder'] = false;
}
}
// The properties must be merged, if the recipients or attachments are present in the exception
// then that list should be used. Otherwise the list from the series must be applied (this
// corresponds with OL2007).
// @FIXME getMessageProps should not return empty string if exception doesn't contain body
// by this change we can handle a situation where user has set empty string in the body explicitly
if (!empty($exceptionProps['props']['body']) || !empty($exceptionProps['props']['html_body'])) {
if (!empty($exceptionProps['props']['body'])) {
$data['item']['props']['body'] = $exceptionProps['props']['body'];
}
if (!empty($exceptionProps['props']['html_body'])) {
$data['item']['props']['html_body'] = $exceptionProps['props']['html_body'];
}
$data['item']['props']['isHTML'] = $exceptionProps['props']['isHTML'];
}
// remove properties from $exceptionProps so array_merge will not overwrite it
unset($exceptionProps['props']['html_body'], $exceptionProps['props']['body'], $exceptionProps['props']['isHTML']);
$data['item']['props'] = array_merge($data['item']['props'], $exceptionProps['props']);
if (isset($exceptionProps['recipients'])) {
$data['item']['recipients'] = $exceptionProps['recipients'];
}
if (isset($exceptionProps['attachments'])) {
$data['item']['attachments'] = $exceptionProps['attachments'];
}
// Make sure we are using the passed basedate and not something wrong in the opened item
$data['item']['props']['basedate'] = $basedate;
$data['item']['attach_num'] = [$exceptionattProps[PR_ATTACH_NUM]];
}
elseif ($recur->isDeleteException($basedate)) {
// Exception is deleted, should not happen, but if it the case then give error
$this->sendFeedback(
false,
[
'type' => ERROR_GROMMUNIO,
'info' => [
'original_message' => _('Could not open occurrence.'),
'display_message' => _('Could not open occurrence, specific occurrence is probably deleted.'),
],
]
);
return;
}
else {
// opening an occurrence of a recurring series (same as normal open, but add basedate, startdate and enddate)
$data['item']['props']['basedate'] = $basedate;
$data['item']['props']['startdate'] = $recur->getOccurrenceStart($basedate);
$data['item']['props']['duedate'] = $recur->getOccurrenceEnd($basedate);
$data['item']['props']['commonstart'] = $data['item']['props']['startdate'];
$data['item']['props']['commonend'] = $data['item']['props']['duedate'];
unset($data['item']['props']['reminder_time']);
}
}
else {
// Opening a recurring series, 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']['props'] += $recurpattern;
}
// Add the timezone information to the data
if (isset($tz) && is_array($tz)) {
$data['item']['props'] += $tz;
}
}
}
// Fix for all-day events which have a different timezone than the user's browser
if ($data['item']['props']['alldayevent'] == 1 && $this->tzdef !== false) {
$this->processAllDayItem($store, $data['item'], $message);
}
// Send the data
$this->addActionData('item', $data);
$GLOBALS['bus']->addData($this->getResponseData());
}
}
/**
* Function does customization of exception based on module data.
* like, here it will generate display message based on actionType
* for particular exception.
*
* @param object $e Exception object
* @param string $actionType the action type, sent by the client
* @param resource $store MAPI store containing the message
* @param string $parententryid parent entryid of the message
* @param string $entryid entryid of the message
* @param array $action the action data, sent by the client
*/
#[Override]
public function handleException(&$e, $actionType = null, $store = null, $parententryid = null, $entryid = null, $action = null) {
if (is_null($e->displayMessage)) {
switch ($actionType) {
case "save":
if ($e->getCode() == MAPI_E_NO_ACCESS) {
if ($store === null || $store === false || !$entryid) {
break;
}
$message = mapi_msgstore_openentry($store, $entryid);
$messageProps = mapi_getprops($message, [PR_MESSAGE_CLASS, PR_ENTRYID, PR_PARENT_ENTRYID, PR_STORE_ENTRYID]);
$messageClass = $messageProps[PR_MESSAGE_CLASS];
$msg = $messageClass !== "IPM.Appointment" ?
_('You have insufficient privileges to move a meeting request in this calendar. The calendar owner can set these using the \'permissions\'-tab of the folder properties (right click the calendar folder > properties > permissions)') :
_('You have insufficient privileges to move an appointment in this calendar. The calendar owner can set these using the \'permissions\'-tab of the folder properties (right click the calendar folder > properties > permissions)');
$e->setDisplayMessage($msg);
$e->setTitle(_('Insufficient privileges'));
// Need this notification to refresh the calendar.
$GLOBALS['bus']->notify(bin2hex((string) $parententryid), TABLE_DELETE, $messageProps);
}
break;
}
}
parent::handleException($e, $actionType, $store, $parententryid, $entryid, $action);
}
/**
* Save the give appointment or meeting request to the calendar.
*
* @param resource $store MAPI store of the message
* @param string $parententryid Parent entryid of the message (folder entryid, NOT message entryid)
* @param string $entryid entryid of the message
* @param array $action Action array containing json request
* @param string $actionType The action type which triggered this action
*/
#[Override]
public function save($store, $parententryid, $entryid, $action, $actionType = 'save') {
$result = false;
// The read flag belongs to the message itself, so it is set directly: going
// through saveAppointment() would write an exception into a series as soon as
// one of its occurrences is marked read.
if ($entryid && isset($action['props']['message_flags'])) {
$flagProps = [];
$GLOBALS['operations']->setMessageFlag($store, $entryid, $action['props']['message_flags'], $action['message_action'] ?? false, $flagProps);
unset($action['props']['message_flags']);
// the client sends its timezone along with every save, it is not a change
$changed = $action['props'];
unset($changed['timezone_iana']);
if (empty($changed) && empty($action['recipients']) && empty($action['attachments'])) {
$GLOBALS['bus']->notify(bin2hex((string) $parententryid), TABLE_SAVE, $flagProps);
$this->sendFeedback(true);
return true;
}
}
// Save appointment (saveAppointment takes care of creating/modifying exceptions to recurring
// items if necessary)
$messageProps = $GLOBALS['operations']->saveAppointment($store, $entryid, $parententryid, $action, $actionType, $this->directBookingMeetingRequest);
// Notify the bus if the save was OK
if ($messageProps && !(is_array($messageProps) && isset($messageProps['error'])) && !isset($messageProps['remindertimeerror'])) {
$GLOBALS['bus']->notify(bin2hex($parententryid), TABLE_SAVE, $messageProps);
$result = true;
}
$errorMsg = false;
if (!$result && isset($messageProps['remindertimeerror']) && !$messageProps['remindertimeerror']) {
$errorMsg = _('Cannot set a reminder to appear before the previous occurrence. Reset reminder to save the change');
}
elseif (isset($messageProps['isexceptionallowed']) && $messageProps['isexceptionallowed'] === false) {
$errorMsg = _('Two occurrences cannot occur on the same day');
}
elseif (is_array($messageProps) && isset($messageProps['error'])) {
$errorMsg = match ($messageProps['error']) {
1 => sprintf(_('You marked \'%s\' as a resource. You cannot schedule a meeting with \'%s\' because you do not have the appropriate permissions for that account. Either enter the name as a required or optional attendee or talk to your administrator about giving you permission to schedule \'%s\'.'), $messageProps['displayname'], $messageProps['displayname'], $messageProps['displayname']),
2 => sprintf(_('\'%s\' has declined your meeting because \'%s\' does not automatically accept meeting requests.'), $messageProps['displayname'], $messageProps['displayname']),
3 => sprintf(_('\'%s\' has declined your meeting because it is recurring. You must book each meeting separately with this resource.'), $messageProps['displayname']),
4 => sprintf(_('\'%s\' is already booked for this specified time. You must use another time or find another resource.'), $messageProps['displayname']),
default => _('Meeting was not scheduled.'),
};
}
else {
// Recurring but non-existing exception (same as normal open, but add basedate, startdate and enddate)
$data = [];
if ($result) {
$data = Conversion::mapMAPI2XML($this->properties, $messageProps);
// Get recipient information from the saved appointment to update client side
// according to the latest recipient related changes only if changes requested from client.
$savedAppointment = $GLOBALS['operations']->openMessage($store, $messageProps[PR_ENTRYID]);
if (!empty($action['recipients'])) {
$recipients = $GLOBALS["operations"]->getRecipientsInfo($savedAppointment);
if (!empty($recipients)) {
$data["recipients"] = [
"item" => $recipients,
];
}
}
// Get attachments information from the saved appointment to update client side
// according to the latest attachments related changes only if changes requested from client.
if (!empty($action['attachments'])) {
$attachments = $GLOBALS["operations"]->getAttachmentsInfo($savedAppointment);
if (!empty($attachments)) {
$data["attachments"] = [
"item" => $attachments,
];
}
}
$data['action_response'] = [
'resources_booked' => $this->directBookingMeetingRequest,
];
if (isset($action['message_action'], $action['message_action']['paste'])) {
$data['action_response']['resources_pasted'] = true;
}
}
else {
if (!empty($action['message_action']['send'])) {
$errorMsg = _('Meeting could not be sent.');
}
else {
$errorMsg = _('Meeting could not be saved.');
}
}
}
if ($errorMsg === false) {
$this->addActionData('update', ['item' => $data]);
$GLOBALS['bus']->addData($this->getResponseData());
}
else {
$this->sendFeedback(false, [
'type' => ERROR_GROMMUNIO,
'info' => [
'display_message' => $errorMsg,
],
]);
}
}
/**
* Processes an all-day item and calculates the correct starttime if necessary.
*
* @param resource $store
* @param array $calendaritem
* @param resource $message
*/
private function processAllDayItem(/* @scrutinizer ignore-unused */ $store, &$calendaritem, /* @scrutinizer ignore-unused */ $message) {
// 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).
$isTzdefstartSet = isset($calendaritem['props']['tzdefstart']);
$tzdefstart = $isTzdefstartSet ?
hex2bin((string) $calendaritem['props']['tzdefstart']) :
mapi_ianatz_to_tzdef("Etc/UTC");
// Compare the timezone definitions of the client and the appointment.
// Further processing is only required if they don't match.
if ($isTzdefstartSet && $GLOBALS['entryid']->compareEntryIds($this->tzdef, $tzdefstart)) {
return;
}
$duration = $calendaritem['props']['duedate'] - $calendaritem['props']['startdate'];
if (!$isTzdefstartSet) {
$localStart = getLocalStart($calendaritem['props']['startdate'], $this->tziana);
}
else {
$localStart = TimezoneUtil::ConvertAllDayStart($calendaritem['props']['startdate'], $tzdefstart, $this->tzdef);
if ($localStart === null) {
return;
}
}
$calendaritem['props']['startdate'] = $calendaritem['props']['commonstart'] = $localStart;
$calendaritem['props']['duedate'] = $calendaritem['props']['commonend'] = $localStart + $duration;
}
}
@@ -0,0 +1,802 @@
<?php
/*
* SPDX-FileCopyrightText: Copyright 2020 - 2026 grommunio GmbH
* SPDX-FileCopyrightText: Copyright 2016 Kopano and its licensors
* SPDX-FileCopyrightText: Copyright 2005 - 2016 Zarafa B.V. and its licensors
* SPDX-License-Identifier: AGPL-3.0-or-later
*/
/**
* Appointment Module.
*/
class AppointmentListModule extends ListModule {
/**
* @var false|int start of the visible interval as a Unix timestamp
*/
private $startdate;
/**
* @var false|int end of the visible interval as a Unix timestamp
*/
private $enddate;
/**
* @var string client or server IANA timezone
*/
protected $tziana;
/**
* @var bool|string client timezone definition
*/
protected $tzdef;
/**
* @var int number of appointments skipped while processing a list request
*/
private $skippedCount = 0;
/**
* @var string first skipped appointment subjects to include in the client message
*/
private $skippedInfo = "";
/**
* Constructor.
*
* @param int $id unique id
* @param array $data list of all actions
*/
public function __construct($id, $data) {
parent::__construct($id, $data);
$this->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<int, false|resource>|false|resource $store MAPI message store or stores
* @param array<int, false|string>|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<int, false|resource>|false|resource $store MAPI message store or stores
* @param array<int, false|string>|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 .= "<br/>" . _("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 .= "<br/>- " . 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 <start, end].
[RES_OR,
[
// AND
// - The AppointmentEnd must fall after the start of the range
// - The AppointmentStart must fall before the end of the range
[RES_AND,
[
// start < appointmentEnd
[RES_PROPERTY,
[RELOP => 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"]] ?? '<empty 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;
}
}
@@ -0,0 +1,94 @@
<?php
/*
* SPDX-FileCopyrightText: Copyright 2020 - 2026 grommunio GmbH
* SPDX-FileCopyrightText: Copyright 2016 Kopano and its licensors
* SPDX-FileCopyrightText: Copyright 2005 - 2016 Zarafa B.V. and its licensors
* SPDX-License-Identifier: AGPL-3.0-or-later
*/
/**
* BusyTime Module.
*/
require_once BASE_PATH . 'server/includes/modules/class.appointmentlistmodule.php';
class BusyTimeListModule extends AppointmentListModule {
/**
* @var array the properties sent back to the client - a minimal set of data
*/
private $minproperties;
/**
* Constructor.
*
* @param int $id unique id
* @param array $data list of all actions
*/
public function __construct($id, $data) {
parent::__construct($id, $data);
$this->minproperties = $GLOBALS["properties"]->getBusyTimeProperties();
}
/**
* Creates the notifiers for this module,
* and register them to the Bus.
*/
#[Override]
public function createNotifiers() {
// Keep empty, the BusyTimeListModule doesn't need notifiers.
}
/**
* Process calendar items to prepare them for being sent back to the client.
*
* @param array $calendaritems array of appointments retrieved from the mapi tablwe
* @param object $store message store
* @param mixed $entryid
* @param int $start startdate of the interval
* @param int $end enddate of the interval
*
* @return array $items processed items
*/
#[Override]
public function processItems($calendaritems, $store, $entryid, $start, $end) {
$items = [];
foreach ($calendaritems as $calendaritem) {
if (isset($calendaritem[$this->properties["recurring"]]) && $calendaritem[$this->properties["recurring"]]) {
$recurrence = new Recurrence($store, $calendaritem);
try {
$recuritems = $recurrence->getItems($start, $end);
}
catch (RecurrenceException $re) {
$subject = $calendaritem[$this->properties["subject"]] ?? '<empty subject>';
error_log(sprintf(
"processItems (busytimelist) RecurrenceException (%d) for item '%s' - %s - %s",
$re->getCode(),
$subject,
bin2hex($calendaritem[$this->properties["entryid"]]),
bin2hex($calendaritem[$this->properties["recurring_data"]])
));
continue;
}
foreach ($recuritems as $recuritem) {
$item = Conversion::mapMAPI2XML($this->minproperties, $recuritem);
// only add it in response if its not removed by above function
if (!empty($item)) {
array_push($items, $item['props']);
}
}
}
else {
$item = Conversion::mapMAPI2XML($this->minproperties, $calendaritem);
// only add it in response if its not removed by above function
if (!empty($item)) {
array_push($items, $item['props']);
}
}
}
return $items;
}
}
@@ -0,0 +1,139 @@
<?php
/*
* SPDX-FileCopyrightText: Copyright 2020 - 2026 grommunio GmbH
* SPDX-License-Identifier: AGPL-3.0-or-later
*/
require_once __DIR__ . '/../core/class.categorylist.php';
/**
* CategoryListModule.
*
* Serves the per-mailbox master category list (the Outlook-compatible list
* stored in each mailbox's Calendar folder, see {@link CategoryList}). Every
* request targets a single store via store_entryid; when none is given the
* logged-in user's own default store is used. This is what makes the list
* per-mailbox and shared: opening a shared mailbox reads that mailbox's list,
* not the current user's.
*/
class CategoryListModule extends Module {
/**
* @param int $id unique id
* @param array $data list of all actions
*/
public function __construct($id, $data) {
parent::__construct($id, $data);
}
/**
* Execute all actions in the request.
*/
#[Override]
public function execute() {
foreach ($this->data as $actionType => $action) {
if (isset($actionType)) {
try {
switch ($actionType) {
case "list":
$this->listCategories($action);
break;
case "save":
$this->saveCategories($action);
break;
case "migrate":
$this->migrateCategories();
break;
default:
$this->handleUnknownActionType($actionType);
}
}
catch (MAPIException $e) {
$this->processException($e, $actionType);
}
}
}
}
/**
* Resolve the store an action targets, defaulting to the user's own store
* only when no store_entryid was supplied. A supplied store that cannot be
* opened (revoked share, stale entryid) must error out - falling back
* would silently read or overwrite the wrong mailbox's list.
*
* @param array $action the action data sent by the client
*
* @return resource the message store to operate on
*/
private function getStoreForAction($action) {
$store = empty($action["store_entryid"])
? $GLOBALS["mapisession"]->getDefaultMessageStore()
: $this->getActionStore($action);
if ($store === false || is_array($store)) {
throw new MAPIException("Could not open the requested mailbox.", MAPI_E_NOT_FOUND, null, _("Could not open the requested mailbox."));
}
return $store;
}
/**
* Return the master category list of the requested store.
*
* @param array $action the action data sent by the client
*/
private function listCategories($action) {
$store = $this->getStoreForAction($action);
$this->sendCategories("list", $store, new CategoryList($store));
}
/**
* Store the master category list of the requested store, then return the
* re-read list so the client picks up merged/preserved data.
*
* @param array $action the action data sent by the client
*/
private function saveCategories($action) {
$store = $this->getStoreForAction($action);
$categories = isset($action["categories"]) && is_array($action["categories"]) ? $action["categories"] : [];
$categoryList = new CategoryList($store);
$categoryList->setCategories($categories);
$this->sendCategories("update", $store, $categoryList);
}
/**
* Migrate every category assigned to an item in the user's mailbox to the
* Outlook-compatible master list.
*/
private function migrateCategories() {
$store = $this->getStoreForAction([]);
$legacyCategories = $GLOBALS['settings']->getPersistent('grommunio/main/categories', []);
$categoryList = new CategoryList($store);
$categoryList->migrateItemCategories(is_array($legacyCategories) ? $legacyCategories : []);
$this->sendCategories("migrate", $store, $categoryList);
}
/**
* Send a category list to the client, tagged with the store it belongs to
* (so the client can key its per-store cache).
*
* @param string $actionType the response action type
* @param resource $store the store the list belongs to
* @param CategoryList $categoryList the list accessor for that store
*/
private function sendCategories($actionType, $store, CategoryList $categoryList) {
$storeProps = mapi_getprops($store, [PR_ENTRYID]);
$categories = $categoryList->getCategories();
$this->addActionData($actionType, [
"store_entryid" => bin2hex((string) $storeProps[PR_ENTRYID]),
"categories" => $categories,
// lets the client distinguish "no list stored yet" (seed it)
// from a deliberately emptied list (leave it alone)
"exists" => $categoryList->listExists(),
]);
$GLOBALS["bus"]->addData($this->getResponseData());
}
}
@@ -0,0 +1,678 @@
<?php
/*
* SPDX-FileCopyrightText: Copyright 2020 - 2026 grommunio GmbH
* SPDX-FileCopyrightText: Copyright 2016 Kopano and its licensors
* SPDX-FileCopyrightText: Copyright 2005 - 2016 Zarafa B.V. and its licensors
* SPDX-License-Identifier: AGPL-3.0-or-later
*/
/**
* Contact ItemModule
* Module which opens, creates, saves and deletes an item. It
* extends the Module class.
*/
class ContactItemModule extends ItemModule {
/**
* Special date properties and the entry ID property of their appointment.
*/
private const SPECIAL_DATE_EVENTIDS = [
'birthday' => 'birthday_eventid',
'wedding_anniversary' => 'anniversary_eventid',
];
/**
* Constructor.
*
* @param int $id unique id
* @param array $data list of all actions
*/
public function __construct($id, $data) {
$this->properties = $GLOBALS['properties']->getContactProperties();
parent::__construct($id, $data);
$this->plaintext = false;
}
/**
* Create a one-off entry ID and fail the save if MAPI cannot produce one.
*
* @param mixed $displayName
* @param mixed $addressType
* @param mixed $emailAddress
* @param mixed $flags
*
* @return string binary one-off entry ID
*/
private function createOneOffEntryId($displayName, $addressType, $emailAddress, $flags = 0) {
$entryId = mapi_createoneoff($displayName, $addressType, $emailAddress, $flags);
if ($entryId === false) {
throw new RuntimeException('Unable to create one-off entry ID');
}
return $entryId;
}
/**
* Function which opens an item.
*
* @param resource $store MAPI message store
* @param string $entryid entryid of the message
* @param array $action the action data, sent by the client
*/
#[Override]
public function open($store, $entryid, $action) {
$data = [];
$orEntryid = $entryid;
$message = false;
if ($entryid) {
// Check if OneOff entryid is a local contact
if ($GLOBALS['entryid']->hasAddressBookOneOff(bin2hex($entryid))) {
try {
$oneoff = mapi_parseoneoff($entryid);
$ab = $GLOBALS['mapisession']->getAddressbook();
$ab_dir = mapi_ab_openentry($ab);
$res = $this->searchContactsFolders($ab, $ab_dir, $oneoff['address']);
if (count($res) > 0) {
$entryid = $res[0][PR_ENTRYID];
}
}
catch (MAPIException $ex) {
error_log(sprintf(
"Unable to open contact because mapi_parseoneoff failed: %s - %s",
get_mapi_error_name($ex->getCode()),
$ex->getDisplayMessage()
));
}
}
/* Check if given entryid is shared folder distlist then
* get the store of distlist for fetching it's members.
*/
$storeData = $this->getStoreParentEntryIdFromEntryId($entryid);
$store = $storeData["store"];
$message = $storeData["message"];
}
if (empty($message)) {
return;
}
// Open embedded message if requested
$attachNum = !empty($action['attach_num']) ? $action['attach_num'] : false;
if ($attachNum) {
// get message props of sub message
$parentMessage = $message;
$message = $GLOBALS['operations']->openMessage($store, $entryid, $attachNum);
if (empty($message)) {
return;
}
// Check if message is distlist then we need to use different set of properties
$props = mapi_getprops($message, [PR_MESSAGE_CLASS]);
if (class_match_prefix($props[PR_MESSAGE_CLASS], "IPM.Distlist")) {
// for distlist we need to use different set of properties
$this->properties = $GLOBALS['properties']->getDistListProperties();
}
$data['item'] = $GLOBALS['operations']->getEmbeddedMessageProps($store, $message, $this->properties, $parentMessage, $attachNum);
}
else {
// Check if message is distlist then we need to use different set of properties
$props = mapi_getprops($message, [PR_MESSAGE_CLASS]);
if (class_match_prefix($props[PR_MESSAGE_CLASS], "IPM.Distlist")) {
// for distlist we need to use different set of properties
$this->properties = $GLOBALS['properties']->getDistListProperties();
}
// get message props of the message
$data['item'] = $GLOBALS['operations']->getMessageProps($store, $message, $this->properties, $this->plaintext, true);
}
// By openentry from address book, the entryid will differ, make it same as the origin
$data['item']['entryid'] = bin2hex($orEntryid);
// Allowing to hook in just before the data sent away to be sent to the client
$GLOBALS['PluginManager']->triggerHook('server.module.contactitemmodule.open.after', [
'moduleObject' => &$this,
'store' => $store,
'entryid' => $entryid,
'action' => $action,
'message' => &$message,
'data' => &$data,
]);
$this->addActionData('item', $data);
$GLOBALS['bus']->addData($this->getResponseData());
}
/**
* Function which saves an item. It sets the right properties for a contact
* item (address book properties).
*
* @param false|resource $store MAPI message store, or false to use the default
* @param false|string $parententryid parent folder entry ID, or false to infer it
* @param false|string $entryid entry ID of the message, or false for a new item
* @param array $action action data sent by the client
* @param string $actionType action type that triggered the save
*/
#[Override]
public function save($store, $parententryid, $entryid, $action, $actionType = 'save') {
$propertiesToDelete = []; // create an array of properties which should be deleted
$isCopyGABToContact = false;
// this array is passed to $GLOBALS['operations']->saveMessage() function
if ($store === false && !$parententryid) {
if (isset($action['props']['message_class'])) {
$store = $GLOBALS['mapisession']->getDefaultMessageStore();
$parententryid = $this->getDefaultFolderEntryID($store, $action['props']['message_class']);
}
elseif ($entryid) {
$data = $this->getStoreParentEntryIdFromEntryId($entryid);
$store = $data["store"];
$parententryid = $data["parent_entryid"];
}
}
elseif (!$parententryid) {
if (isset($action['props']['message_class'])) {
$parententryid = $this->getDefaultFolderEntryID($store, $action['props']['message_class']);
}
}
if ($store !== false && $parententryid && isset($action['props'])) {
if (isset($action['members'])) {
$props = $this->prepareDistListProps($action, $propertiesToDelete);
}
else {
$isCopyGABToContact = ($action["message_action"]["action_type"] ?? null) === "copyToContact";
$props = $this->prepareContactProps($store, $action, $isCopyGABToContact, $propertiesToDelete);
}
$messageProps = [];
$result = $GLOBALS['operations']->saveMessage($store, $entryid, $parententryid, $props, $messageProps, [], $action['attachments'] ?? [], $propertiesToDelete);
if ($result) {
$GLOBALS['bus']->notify(bin2hex($parententryid), TABLE_SAVE, $messageProps);
if ($isCopyGABToContact) {
$message = mapi_msgstore_openentry($store, $messageProps[PR_ENTRYID]);
$messageProps = mapi_getprops($message, $this->properties);
}
$this->addActionData('update', ['item' => Conversion::mapMAPI2XML($this->properties, $messageProps)]);
$GLOBALS['bus']->addData($this->getResponseData());
}
}
}
/**
* Converts the client data of a distribution list, packing its members.
*
* @param array $action action data sent by the client
* @param array $propertiesToDelete receives the properties to remove
*
* @return array MAPI properties to save
*/
private function prepareDistListProps($action, &$propertiesToDelete) {
$this->properties = $GLOBALS['properties']->getDistListProperties();
$props = Conversion::mapXML2MAPI($this->properties, $action['props']);
$members = [];
$oneoff_members = [];
foreach ($action['members'] as $item) {
if (empty($item['email_address'])) {
// mapi_parseoneoff fails without an address; OL07 uses Unknown as well
$item['email_address'] = 'Unknown';
}
if (empty($item['address_type']) && in_array($item['distlist_type'], [DL_DIST, DL_DIST_AB])) {
$item['address_type'] = 'MAPIPDL';
}
$oneoff = $this->createOneOffEntryId($item['display_name'], $item['address_type'], $item['email_address']);
if ($item['distlist_type'] == DL_EXTERNAL_MEMBER) {
$member = $oneoff;
}
else {
$member = pack('VA16CA*', 0, WAB_GUID, $item['distlist_type'], hex2bin((string) $item['entryid']));
}
$oneoff_members[] = $oneoff;
$members[] = $member;
}
if (!empty($members) && !empty($oneoff_members)) {
$props[$this->properties['members']] = $members;
$props[$this->properties['oneoff_members']] = $oneoff_members;
}
else {
$propertiesToDelete[] = $this->properties['members'];
$propertiesToDelete[] = $this->properties['oneoff_members'];
}
return $props;
}
/**
* Converts the client data of a contact, deriving one-off entry IDs and
* the birthday and anniversary appointments.
*
* @param resource $store MAPI message store
* @param array $action action data sent by the client
* @param bool $isCopyGABToContact whether the contact is copied from the address book
* @param array $propertiesToDelete receives the properties to remove
*
* @return array MAPI properties to save
*/
private function prepareContactProps($store, $action, $isCopyGABToContact, &$propertiesToDelete) {
if ($isCopyGABToContact) {
$this->copyGABRecordProps($action);
}
for ($index = 1; $index < 4; ++$index) {
if (!empty($action['props']['email_address_' . $index]) && !empty($action['props']['email_address_display_name_' . $index])) {
$action['props']['email_address_entryid_' . $index] = bin2hex($this->createOneOffEntryId($action['props']['email_address_display_name_' . $index], $action['props']['email_address_type_' . $index], $action['props']['email_address_' . $index]));
}
}
// fax 1 is primary, 2 business, 3 home
for ($index = 1; $index < 4; ++$index) {
$fax = 'fax_' . $index . '_';
if (!empty($action['props'][$fax . 'email_address'])) {
$action['props'][$fax . 'original_entryid'] = bin2hex($this->createOneOffEntryId($action['props'][$fax . 'original_display_name'], $action['props'][$fax . 'address_type'], $action['props'][$fax . 'email_address'], MAPI_UNICODE));
}
else {
$propertiesToDelete[] = $this->properties[$fax . 'address_type'];
$propertiesToDelete[] = $this->properties[$fax . 'original_display_name'];
$propertiesToDelete[] = $this->properties[$fax . 'email_address'];
$propertiesToDelete[] = $this->properties[$fax . 'original_entryid'];
}
}
if (!empty($action['entryid'])) {
$this->collectClearedContactProps($store, $action['props'], $propertiesToDelete);
}
/*
* convert all line endings(LF) into CRLF
* XML parser will normalize all CR, LF and CRLF into LF
* but outlook(windows) uses CRLF as line ending
*/
foreach (['business_address', 'home_address', 'other_address'] as $address) {
if (isset($action['props'][$address])) {
$action['props'][$address] = preg_replace('/\r?\n/', "\r\n", (string) $action['props'][$address]);
}
}
foreach (self::SPECIAL_DATE_EVENTIDS as $date => $eventid) {
if (!empty($action['props'][$date])) {
$action['props'][$eventid] = $this->updateAppointments($store, $action, $date);
}
}
return Conversion::mapXML2MAPI($this->properties, $action['props']);
}
/**
* Adds the properties an existing contact had cleared to the delete list,
* removing the appointments of cleared special dates.
*
* @param resource $store MAPI message store
* @param array $props contact properties sent by the client
* @param array $propertiesToDelete receives the properties to remove
*/
private function collectClearedContactProps($store, $props, &$propertiesToDelete) {
for ($i = 1; $i < 4; ++$i) {
if (isset($props['email_address_' . $i]) && empty($props['email_address_' . $i])) {
array_push($propertiesToDelete, $this->properties['email_address_entryid_' . $i]);
array_push($propertiesToDelete, $this->properties['email_address_' . $i]);
array_push($propertiesToDelete, $this->properties['email_address_display_name_' . $i]);
array_push($propertiesToDelete, $this->properties['email_address_display_name_email_' . $i]);
array_push($propertiesToDelete, $this->properties['email_address_type_' . $i]);
}
}
if (isset($props['address_book_long']) && $props['address_book_long'] === 0) {
$propertiesToDelete[] = $this->properties['address_book_mv'];
$propertiesToDelete[] = $this->properties['address_book_long'];
}
foreach (self::SPECIAL_DATE_EVENTIDS as $date => $eventid) {
if (array_key_exists($date, $props) && empty($props[$date])) {
array_push($propertiesToDelete, $this->properties[$date]);
array_push($propertiesToDelete, $this->properties[$eventid]);
if (!empty($props[$eventid])) {
$this->deleteSpecialDateAppointment($store, $props[$eventid]);
}
}
}
}
/**
* Function copy the some property from address book record to contact props.
*
* @param array $action the action data, sent by the client
*/
public function copyGABRecordProps(&$action) {
$addrbook = $GLOBALS["mapisession"]->getAddressbook();
$abitem = mapi_ab_openentry($addrbook, hex2bin((string) $action["message_action"]["source_entryid"]));
$abItemProps = mapi_getprops($abitem, [
PR_COMPANY_NAME,
PR_ASSISTANT,
PR_BUSINESS_TELEPHONE_NUMBER,
PR_BUSINESS2_TELEPHONE_NUMBER,
PR_HOME2_TELEPHONE_NUMBER,
PR_STREET_ADDRESS,
PR_LOCALITY,
PR_STATE_OR_PROVINCE,
PR_POSTAL_CODE,
PR_COUNTRY,
PR_MOBILE_TELEPHONE_NUMBER,
]);
$action["props"]["company_name"] = $abItemProps[PR_COMPANY_NAME] ?? '';
$action["props"]["assistant"] = $abItemProps[PR_ASSISTANT] ?? '';
$action["props"]["business_telephone_number"] = $abItemProps[PR_BUSINESS_TELEPHONE_NUMBER] ?? '';
$action["props"]["business2_telephone_number"] = $abItemProps[PR_BUSINESS2_TELEPHONE_NUMBER] ?? '';
$action["props"]["home2_telephone_number"] = $abItemProps[PR_HOME2_TELEPHONE_NUMBER] ?? '';
$action["props"]["home_address_street"] = $abItemProps[PR_STREET_ADDRESS] ?? '';
$action["props"]["home_address_city"] = $abItemProps[PR_LOCALITY] ?? '';
$action["props"]["home_address_state"] = $abItemProps[PR_STATE_OR_PROVINCE] ?? '';
$action["props"]["home_address_postal_code"] = $abItemProps[PR_POSTAL_CODE] ?? '';
$action["props"]["home_address_country"] = $abItemProps[PR_COUNTRY] ?? '';
$action["props"]["cellular_telephone_number"] = $abItemProps[PR_MOBILE_TELEPHONE_NUMBER] ?? '';
// Set the home_address property value
$props = ["street", "city", "state", "postal_code", "country"];
$homeAddress = "";
foreach ($props as $index => $prop) {
if (isset($action["props"]["home_address_" . $prop]) && !empty($action["props"]["home_address_" . $prop])) {
$homeAddress .= $action["props"]["home_address_" . $prop] . " ";
if ($prop == "street" || $prop == "postal_code") {
$homeAddress .= PHP_EOL;
}
}
}
$action["props"]["home_address"] = $homeAddress;
}
/**
* Function which deletes an item. Extended here to also delete corresponding birthday/anniversary
* appointments from calendar.
*
* @param false|resource $store MAPI message store, or false to infer it
* @param false|string $parententryid parent folder entry ID, or false to infer it
* @param false|string $entryid entry ID of the message, or false when unavailable
* @param array $action action data sent by the client
*/
#[Override]
public function delete($store, $parententryid, $entryid, $action) {
$message = false;
if ($store === false && !$parententryid && $entryid) {
$data = $this->getStoreParentEntryIdFromEntryId($entryid);
$store = $data["store"];
$message = $data["message"];
$parententryid = $data["parent_entryid"];
}
if ($store !== false && $entryid) {
try {
if ($message === false) {
$message = $GLOBALS["operations"]->openMessage($store, $entryid);
}
$props = mapi_getprops($message, [$this->properties['anniversary_eventid'], $this->properties['birthday_eventid']]);
// if any of the appointment entryid exists then delete it
if (!empty($props[$this->properties['birthday_eventid']])) {
$this->deleteSpecialDateAppointment($store, bin2hex((string) $props[$this->properties['birthday_eventid']]));
}
if (!empty($props[$this->properties['anniversary_eventid']])) {
$this->deleteSpecialDateAppointment($store, bin2hex((string) $props[$this->properties['anniversary_eventid']]));
}
}
catch (MAPIException $e) {
// if any error occurs in deleting appointments then we shouldn't block deletion of contact item
// so ignore errors now
$e->setHandled();
}
parent::delete($store, $parententryid, $entryid, $action);
}
}
/**
* Function which retrieve the store, parent_entryid from record entryid.
*
* @param $entryid entryid of the message
*
* @return array which contains store and message object and parent entryid of that message
*/
public function getStoreParentEntryIdFromEntryId($entryid) {
$message = $GLOBALS['mapisession']->openMessage($entryid);
$messageStoreInfo = mapi_getprops($message, [PR_STORE_ENTRYID, PR_PARENT_ENTRYID]);
$store = $GLOBALS['mapisession']->openMessageStore($messageStoreInfo[PR_STORE_ENTRYID]);
$parentEntryid = $messageStoreInfo[PR_PARENT_ENTRYID];
return ["message" => $message, "store" => $store, "parent_entryid" => $parentEntryid];
}
/**
* Calculate the number of minutes from the start of a timestamp's year to its month.
*
* @param int $timestamp
*
* @return int
*/
private static function getMonthOffset($timestamp) {
$month = (int) date('m', $timestamp);
$year = (int) date('Y', $timestamp);
$yearStart = new DateTime();
$yearStart->setDate($year, 1, 1);
$monthStart = clone $yearStart;
$monthStart->setDate($year, $month, 1);
return $monthStart->diff($yearStart)->days * 24 * 60;
}
/**
* Function will create/update a yearly recurring appointment on the respective date of birthday or anniversary in user's calendar.
*
* @param resource $store MAPI message store
* @param array $action the action data, sent by the client
* @param string $type type of appointment that should be created/updated, valid values are 'birthday' and 'wedding_anniversary'
*
* @return false|string entry ID of the newly created appointment in hexadecimal form, or false
*/
public function updateAppointments($store, $action, $type) {
$result = false;
$root = mapi_msgstore_openentry($store);
$rootProps = mapi_getprops($root, [PR_IPM_APPOINTMENT_ENTRYID, PR_STORE_ENTRYID]);
$parentEntryId = bin2hex((string) $rootProps[PR_IPM_APPOINTMENT_ENTRYID]);
$storeEntryId = bin2hex((string) $rootProps[PR_STORE_ENTRYID]);
$actionProps = $action['props'];
$subject = !empty($actionProps['subject']) ? $actionProps['subject'] : _('Untitled');
$subject = ($type === 'birthday' ? sprintf(_('%s\'s Birthday'), $subject) : sprintf(_('%s\'s Anniversary'), $subject));
// UTC time
$startDateUTC = $actionProps[$type];
$dueDateUTC = $actionProps[$type] + (24 * 60 * 60); // ONE DAY is added to set duedate of item.
// get local time from UTC time
$recur = new Recurrence($store, []);
$startDate = $recur->fromGMT($actionProps, $startDateUTC);
$dueDate = $recur->fromGMT($actionProps, $dueDateUTC);
// Find the number of minutes since the start of the year to the given month,
// taking leap years into account.
$month = self::getMonthOffset($startDate);
$defAllDayReminder = $GLOBALS['settings']->get('grommunio/v1/contexts/calendar/default_allday_reminder_time', 1080);
$props = [
'message_class' => 'IPM.Appointment',
'icon_index' => 1025,
'busystatus' => fbFree,
'meeting' => olNonMeeting,
'object_type' => MAPI_MESSAGE,
'message_flags' => MSGFLAG_READ | MSGFLAG_UNSENT,
'subject' => $subject,
'startdate' => $startDateUTC,
'duedate' => $dueDateUTC,
'commonstart' => $startDateUTC,
'commonend' => $dueDateUTC,
'alldayevent' => true,
'duration' => 1440,
'reminder' => true,
'reminder_minutes' => $defAllDayReminder,
'reminder_time' => $startDateUTC,
'flagdueby' => $startDateUTC - ($defAllDayReminder * 60),
'recurring' => true,
'recurring_reset' => true,
'startocc' => 0,
'endocc' => 1440,
'start' => $startDate,
'end' => $dueDate,
'term' => 35,
'everyn' => 1,
'subtype' => 2,
'type' => 13,
'regen' => 0,
'month' => $month,
'monthday' => date('j', $startDate),
'timezone' => $actionProps['timezone'],
'timezonedst' => $actionProps['timezonedst'],
'dststartmonth' => $actionProps['dststartmonth'],
'dststartweek' => $actionProps['dststartweek'],
'dststartday' => $actionProps['dststartday'],
'dststarthour' => $actionProps['dststarthour'],
'dstendmonth' => $actionProps['dstendmonth'],
'dstendweek' => $actionProps['dstendweek'],
'dstendday' => $actionProps['dstendday'],
'dstendhour' => $actionProps['dstendhour'],
];
$data = [];
$data['store'] = $storeEntryId;
$data['parententryid'] = $parentEntryId;
$entryid = false;
// if entryid is provided then update existing appointment, else create new one
if ($type === 'birthday' && !empty($actionProps['birthday_eventid'])) {
$entryid = $actionProps['birthday_eventid'];
}
elseif ($type === 'wedding_anniversary' && !empty($actionProps['anniversary_eventid'])) {
$entryid = $actionProps['anniversary_eventid'];
}
if ($entryid !== false) {
$data['entryid'] = $entryid;
}
if (isset($action['timezone_iana'])) {
$props['timezone_iana'] = $action['timezone_iana'];
}
$data['props'] = $props;
// Save appointment (saveAppointment takes care of creating/modifying exceptions to recurring
// items if necessary)
try {
$messageProps = $GLOBALS['operations']->saveAppointment($store, hex2bin((string) $entryid), hex2bin($parentEntryId), $data);
}
catch (MAPIException $e) {
// if the appointment is deleted then create a new one
if ($e->getCode() == MAPI_E_NOT_FOUND) {
$e->setHandled();
$messageProps = $GLOBALS['operations']->saveAppointment($store, false, hex2bin($parentEntryId), $data);
}
else {
// The calendar entry is a convenience; the contact is saved regardless.
$e->setHandled();
error_log(sprintf('Unable to save the %s appointment of a contact: %s', $type, $e->getMessage()));
$messageProps = false;
}
}
// Notify the bus if the save was OK
if ($messageProps && !(is_array($messageProps) && isset($messageProps['error']))) {
$GLOBALS['bus']->notify($parentEntryId, TABLE_SAVE, $messageProps);
$result = bin2hex((string) $messageProps[PR_ENTRYID]);
}
return $result;
}
/**
* Function will delete the appointment on the respective date of birthday or anniversary in user's calendar.
*
* @param resource $store MAPI message store
* @param string $entryid entry ID of the message to delete
*/
public function deleteSpecialDateAppointment($store, $entryid) {
$root = mapi_msgstore_openentry($store);
$rootProps = mapi_getprops($root, [PR_IPM_APPOINTMENT_ENTRYID, PR_STORE_ENTRYID]);
$parentEntryId = $rootProps[PR_IPM_APPOINTMENT_ENTRYID];
$storeEntryId = $rootProps[PR_STORE_ENTRYID];
$props = [];
$props[PR_PARENT_ENTRYID] = $parentEntryId;
$props[PR_ENTRYID] = hex2bin((string) $entryid);
$props[PR_STORE_ENTRYID] = $storeEntryId;
$result = $GLOBALS['operations']->deleteMessages($store, $parentEntryId, $props[PR_ENTRYID]);
if ($result) {
$GLOBALS['bus']->notify(bin2hex((string) $parentEntryId), TABLE_DELETE, $props);
}
}
/**
* This function searches the private contact folders for users and returns an array with data.
* Please note that the returning array must be UTF8.
*
* @param resource $ab The addressbook
* @param resource $ab_dir The addressbook container
* @param string $searchstr The search query, case is ignored
*/
public function searchContactsFolders($ab, $ab_dir, $searchstr) {
$r = [];
$abhtable = mapi_folder_gethierarchytable($ab_dir, MAPI_DEFERRED_ERRORS | CONVENIENT_DEPTH);
$abcntfolders = mapi_table_queryallrows($abhtable, [PR_ENTRYID, PR_AB_PROVIDER_ID, PR_DISPLAY_NAME]);
$restriction = [
RES_CONTENT,
[
FUZZYLEVEL => FL_SUBSTRING | FL_IGNORECASE,
ULPROPTAG => PR_SMTP_ADDRESS,
VALUE => [PR_SMTP_ADDRESS => $searchstr],
],
];
// restriction on hierarchy table for PR_AB_PROVIDER_ID
// seems not to work, just loop through
foreach ($abcntfolders as $abcntfolder) {
if ($abcntfolder[PR_AB_PROVIDER_ID] == ZARAFA_CONTACTS_GUID) {
$abfldentry = mapi_ab_openentry($ab, $abcntfolder[PR_ENTRYID]);
$abfldcontents = mapi_folder_getcontentstable($abfldentry);
mapi_table_restrict($abfldcontents, $restriction);
$r = mapi_table_queryallrows($abfldcontents, [PR_ENTRYID]);
if (is_array($r) && !empty($r)) {
return $r;
}
}
}
return $r;
}
}
@@ -0,0 +1,82 @@
<?php
/*
* SPDX-FileCopyrightText: Copyright 2020 - 2026 grommunio GmbH
* SPDX-FileCopyrightText: Copyright 2016 Kopano and its licensors
* SPDX-FileCopyrightText: Copyright 2005 - 2016 Zarafa B.V. and its licensors
* SPDX-License-Identifier: AGPL-3.0-or-later
*/
/**
* Contact Module.
*/
class ContactListModule extends ListModule {
/**
* Constructor.
*
* @param int $id unique id
* @param array $data list of all actions
*/
public function __construct($id, $data) {
parent::__construct($id, $data);
$this->properties = $GLOBALS["properties"]->getContactListProperties();
$this->start = 0;
}
/**
* Creates the notifiers for this module,
* and register them to the Bus.
*/
public function createNotifiers() {
$entryid = $this->getEntryID();
$GLOBALS["bus"]->registerNotifier('contactlistnotifier', $entryid);
}
/**
* Executes all the actions in the $data variable.
*/
#[Override]
public function execute() {
foreach ($this->data as $actionType => $action) {
if (isset($actionType)) {
try {
$store = $this->getActionStore($action);
$entryid = $this->getActionSingleEntryID($action);
if ($store === false || is_array($store)) {
$this->sendFeedback(false);
continue;
}
switch ($actionType) {
case "list":
$this->getDelegateFolderInfo($store);
$this->messageList($store, $entryid, $action, $actionType);
break;
case "search":
// @FIXME add handling for private items
$this->search($store, $entryid, $action, $actionType);
break;
case "updatesearch":
$this->updatesearch($store, $entryid, $action);
break;
case "stopsearch":
$this->stopSearch($store, $entryid, $action);
break;
default:
$this->handleUnknownActionType($actionType);
}
}
catch (MAPIException $e) {
$this->processException($e, $actionType);
}
}
}
}
}
@@ -0,0 +1,754 @@
<?php
/*
* SPDX-FileCopyrightText: Copyright 2020 - 2026 grommunio GmbH
* SPDX-FileCopyrightText: Copyright 2016 Kopano and its licensors
* SPDX-FileCopyrightText: Copyright 2005 - 2016 Zarafa B.V. and its licensors
* SPDX-License-Identifier: AGPL-3.0-or-later
*/
require_once __DIR__ . '/../hexutil.php';
/**
* Create Mail ItemModule
* Module which opens, creates, saves and deletes an item. It
* extends the Module class.
*/
class CreateMailItemModule extends ItemModule {
/**
* Constructor.
*
* @param int $id unique id
* @param array $data list of all actions
*/
public function __construct($id, $data) {
parent::__construct($id, $data);
$this->properties = $GLOBALS['properties']->getMailProperties();
$useHtmlPreview = $GLOBALS['settings']->get('grommunio/v1/contexts/mail/use_html_email_preview', USE_HTML_EMAIL_PREVIEW);
$this->plaintext = !$useHtmlPreview;
}
/**
* Function which saves and/or sends an item.
*
* @param false|resource $store MAPI message store, or false when unavailable
* @param false|string $parententryid parent entry ID of the message
* @param false|string $entryid entry ID of the message
* @param array $action the action data, sent by the client
*/
#[Override]
public function save($store, $parententryid, $entryid, $action, $actionType = 'save') {
$messageProps = [];
$store = $this->resolveStore($store);
if ($store === false) {
return;
}
$parententryid = $this->resolveParentEntryId($store, $parententryid, $action);
$attachments = !empty($action['attachments']) ? $action['attachments'] : [];
$recipients = !empty($action['recipients']) ? $action['recipients'] : [];
$result = $this->applyMessageFlags($store, $entryid, $action, $messageProps);
$send = $this->shouldSendMessage($action);
$saveChanges = $this->shouldPersistMessage($send, $action, $attachments, $recipients);
if ($saveChanges) {
if ($send) {
$this->restoreSendAsPropsFromDraft($store, $entryid, $action);
}
$copyContext = $this->createCopyContext($store, $action, $send);
$store = $copyContext['store'];
$copyFromMessage = $copyContext['copyFromMessage'];
$copyAttachments = $copyContext['copyAttachments'];
$copyInlineAttachmentsOnly = $copyContext['copyInlineAttachmentsOnly'];
$this->threadingSource = $copyContext['threadingSource'];
if ($send) {
$sendOutcome = $this->handleSend($store, $entryid, $parententryid, $action, $recipients, $messageProps, $copyFromMessage, $copyAttachments, $copyInlineAttachmentsOnly);
if ($sendOutcome['aborted']) {
return;
}
$result = $sendOutcome['result'];
}
else {
$draftOutcome = $this->handleDraftSave($store, $entryid, $parententryid, $action, $messageProps, $copyFromMessage, $copyAttachments, $copyInlineAttachmentsOnly);
if ($draftOutcome['aborted']) {
return;
}
$result = $draftOutcome['result'];
}
}
if ($result === false && isset($action['message_action']['soft_delete'])) {
$result = true;
}
if ($result && !$send && isset($messageProps[PR_PARENT_ENTRYID])) {
$GLOBALS['bus']->notify(bin2hex($messageProps[PR_PARENT_ENTRYID]), TABLE_SAVE, $messageProps);
}
if ($send) {
$this->addActionData('update', ['item' => Conversion::mapMAPI2XML($this->properties, $messageProps)]);
}
$this->sendFeedback($result ? true : false, [], true);
}
/**
* Resolve the message store that should be used for the save operation.
*
* @param false|resource $store MAPI message store, or false when unavailable
*
* @return false|resource resolved MAPI message store, or false when unavailable
*/
private function resolveStore($store) {
if ($store !== false) {
return $store;
}
return $GLOBALS['mapisession']->getDefaultMessageStore();
}
/**
* Resolve parent entry id based on provided data or defaults.
*
* @param resource $store MAPI message store
* @param false|string $parententryid parent entry ID, or false when unspecified
*
* @return false|string resolved parent entry ID, or false when unavailable
*/
private function resolveParentEntryId($store, $parententryid, array $action) {
if ($parententryid) {
return $parententryid;
}
$messageClass = $action['props']['message_class'] ?? '';
return $this->getDefaultFolderEntryID($store, $messageClass);
}
/**
* Apply message flag updates if requested by the client.
*
* @param mixed $store
* @param mixed $entryid
*
* @return bool
*/
private function applyMessageFlags($store, $entryid, array &$action, array &$messageProps) {
if (!isset($action['props']['message_flags']) || !$entryid) {
return false;
}
$msgAction = $action['message_action'] ?? false;
$result = $GLOBALS['operations']->setMessageFlag($store, $entryid, $action['props']['message_flags'], $msgAction, $messageProps);
unset($action['props']['message_flags']);
return (bool) $result;
}
/**
* Determine whether the current action requests sending the message.
*
* @return bool
*/
private function shouldSendMessage(array $action) {
return isset($action['message_action']['send']) ? (bool) $action['message_action']['send'] : false;
}
/**
* Decide if the message requires saving based on provided data.
*
* @param bool $send
*
* @return bool
*/
private function shouldPersistMessage($send, array $action, array $attachments, array $recipients) {
return $send || !empty($action['props']) || $this->hasAttachmentChanges($attachments) || !empty($recipients);
}
/**
* Check if attachment updates are pending in the attachment state.
*
* @return bool
*/
private function hasAttachmentChanges(array $attachments) {
if (!isset($attachments['dialog_attachments'])) {
return false;
}
$attachmentState = new AttachmentState();
$attachmentState->open();
$hasChanges = $attachmentState->isChangesPending($attachments['dialog_attachments']);
$attachmentState->close();
return $hasChanges;
}
/**
* Restore the SendAs / on-behalf identity from a previously saved draft.
*
* The client only transmits properties which changed since the last save,
* so a send request following an intermediate (auto)save may no longer
* carry the sent_representing_* properties even though the draft was
* composed under another identity. Without them both the store selection
* in createCopyContext() and the representing-sender handling in
* submitMessage() would silently fall back to the logged-in user's own
* address. Read the identity back from the stored draft and treat it as
* if the client had supplied it.
*
* @param resource $store store containing the draft
* @param false|string $entryid entryid of the draft, false for an unsaved message
*/
private function restoreSendAsPropsFromDraft($store, $entryid, array &$action) {
if (!$entryid) {
return;
}
// The presence of any sent_representing_* key expresses client intent,
// even with an empty value: the client transmits empty strings when the
// user explicitly removes the From identity, and restoring the draft's
// identity in that case would send under the address the user just
// removed. Only a request which does not mention the identity at all
// (unchanged since the last save) may fall back to the stored draft.
foreach (['sent_representing_name', 'sent_representing_email_address',
'sent_representing_address_type', 'sent_representing_entryid',
'sent_representing_search_key', 'sent_representing_smtp_address'] as $propName) {
if (array_key_exists($propName, $action['props'] ?? [])) {
return;
}
}
try {
$draft = mapi_msgstore_openentry($store, $entryid);
$draftProps = mapi_getprops($draft, [
PR_SENT_REPRESENTING_NAME,
PR_SENT_REPRESENTING_EMAIL_ADDRESS,
PR_SENT_REPRESENTING_ADDRTYPE,
PR_SENT_REPRESENTING_ENTRYID,
PR_SENT_REPRESENTING_SEARCH_KEY,
PR_SENT_REPRESENTING_SMTP_ADDRESS,
]);
}
catch (MAPIException $e) {
$e->setHandled();
return;
}
$smtpAddress = (string) ($draftProps[PR_SENT_REPRESENTING_SMTP_ADDRESS] ?? '');
$emailAddress = (string) ($draftProps[PR_SENT_REPRESENTING_EMAIL_ADDRESS] ?? '');
$addrType = (string) ($draftProps[PR_SENT_REPRESENTING_ADDRTYPE] ?? '');
if (!$GLOBALS['operations']->isEmailAddressLike($smtpAddress)) {
$smtpAddress = '';
}
if ($smtpAddress === '' && strcasecmp($addrType, 'SMTP') === 0 &&
$GLOBALS['operations']->isEmailAddressLike($emailAddress)) {
$smtpAddress = $emailAddress;
}
// An EX identity carries an X500 DN - and a draft written by an older
// client may even carry a plain display name - in
// PR_SENT_REPRESENTING_EMAIL_ADDRESS. Resolve the SMTP form through
// the address book, like getMessageProps() does for the client.
if ($smtpAddress === '' && !empty($draftProps[PR_SENT_REPRESENTING_ENTRYID])) {
$smtpAddress = (string) $GLOBALS['operations']->getEmailAddress(
$draftProps[PR_SENT_REPRESENTING_ENTRYID],
$draftProps[PR_SENT_REPRESENTING_SEARCH_KEY] ?? false
);
}
// The resolver may hand back an X500 DN when the address book entry
// carries no SMTP address; injecting that as a claimed-SMTP identity
// would arm the identity guard with a value that self-matches on the
// assembled message. Rather inject nothing at all.
if (!$GLOBALS['operations']->isEmailAddressLike($smtpAddress)) {
return;
}
$action['props']['sent_representing_name'] = (string) ($draftProps[PR_SENT_REPRESENTING_NAME] ?? '') !== '' ?
$draftProps[PR_SENT_REPRESENTING_NAME] : $smtpAddress;
$action['props']['sent_representing_email_address'] = $smtpAddress;
$action['props']['sent_representing_address_type'] = 'SMTP';
$action['props']['sent_representing_smtp_address'] = $smtpAddress;
if (!empty($draftProps[PR_SENT_REPRESENTING_ENTRYID])) {
$action['props']['sent_representing_entryid'] = bin2hex((string) $draftProps[PR_SENT_REPRESENTING_ENTRYID]);
}
if (!empty($draftProps[PR_SENT_REPRESENTING_SEARCH_KEY])) {
$action['props']['sent_representing_search_key'] = bin2hex((string) $draftProps[PR_SENT_REPRESENTING_SEARCH_KEY]);
}
}
/**
* Prepare context data when the new message should copy content from another message.
*
* @param mixed $store
* @param bool $send
*
* @return array
*/
/** Source message whose threading headers the response inherits, or false. */
private $threadingSource = false;
/** Persist threading headers with the first save so later sends keep them. */
private function withThreadingProperties(array $props, $reply): array {
if ($this->threadingSource === false) {
return $props;
}
return $GLOBALS['operations']->threadingProperties($this->threadingSource, (bool) $reply, $props);
}
private function createCopyContext($store, array $action, $send) {
$context = [
'store' => $store,
'copyAttachments' => false,
'copyFromMessage' => false,
'copyInlineAttachmentsOnly' => false,
'threadingSource' => false,
];
if (isset($action['message_action']['action_type'])) {
$actionType = $action['message_action']['action_type'];
$requiresCopy = in_array($actionType, ['reply', 'replyall', 'forward', 'edit_as_new'], true);
if ($requiresCopy) {
$copyFromMessageId = (string) ($action['message_action']['source_entryid'] ?? '');
$copyFromStoreId = (string) ($action['message_action']['source_store_entryid'] ?? '');
$copyFromAttachNum = !empty($action['message_action']['source_attach_num']) ? $action['message_action']['source_attach_num'] : false;
$copyStoreBinary = $copyFromStoreId !== '' ? $this->hexToBinOrFalse($copyFromStoreId) : false;
$copyMessageBinary = $copyFromMessageId !== '' ? $this->hexToBinOrFalse($copyFromMessageId) : false;
$copyFromStore = $copyStoreBinary !== false ? $GLOBALS['mapisession']->openMessageStore($copyStoreBinary) : false;
$copyFromMessage = false;
if ($copyFromStore && $copyMessageBinary !== false) {
try {
$copyFromMessage = $GLOBALS['operations']->openMessage($copyFromStore, $copyMessageBinary, $copyFromAttachNum);
}
catch (MAPIException $e) {
$copyFromMessage = false;
}
}
if ($copyFromStore && $send) {
$context['store'] = $copyFromStore;
}
if ($copyFromStore && $copyFromMessage) {
parse_smime($copyFromStore, $copyFromMessage);
}
// Threading headers are inherited even when nothing is copied.
$context['threadingSource'] = $copyFromMessage;
if (($action['message_action']['browser_decrypted'] ?? false) === true) {
// The browser has uploaded the selected decrypted attachments
// through the normal attachment pipeline. Copying the source
// here would duplicate its opaque encrypted MIME envelope.
$copyFromMessage = false;
}
$context['copyAttachments'] = true;
$context['copyFromMessage'] = $copyFromMessage;
$context['copyInlineAttachmentsOnly'] = in_array($actionType, ['reply', 'replyall'], true);
}
}
elseif (isset($action['props']['sent_representing_email_address'], $action['props']['sent_representing_address_type']) &&
strlen(trim($action['props']['sent_representing_email_address'])) !== 0) {
$addrType = $action['props']['sent_representing_address_type'];
if (strcasecmp($addrType, 'EX') === 0 || strcasecmp($addrType, 'SMTP') === 0) {
try {
$otherStore = $GLOBALS['mapisession']->addUserStore($action['props']['sent_representing_email_address']);
}
catch (MAPIException $e) {
$e->setTitle(_('Unknown error'));
$e->setDisplayMessage(sprintf(_("Unable to add store: '%s'. Please check if you have the necessary permissions."),
$action['props']['sent_representing_email_address']));
throw $e;
}
if ($otherStore && $send) {
$context['store'] = $otherStore;
}
}
}
return $context;
}
/**
* Handle the send flow including plugin hooks and recipient processing.
*
* @param mixed $store
* @param mixed $entryid
* @param mixed $parententryid
* @param mixed $copyFromMessage
* @param bool $copyAttachments
* @param bool $copyInlineAttachmentsOnly
*
* @return array
*/
private function handleSend($store, $entryid, $parententryid, array &$action, array $recipients, array &$messageProps, $copyFromMessage, $copyAttachments, $copyInlineAttachmentsOnly) {
// Before any work is done, so a replayed request costs nothing.
Operations::assertSubmitRateLimit();
// Keep this check in core: disabled/removed plugins cannot register hooks
// or property mappings, but a previously opened compose tab retains intent.
if (!empty($action['props']['pgp_sign']) || !empty($action['props']['pgp_encrypt'])) {
Operations::assertOpenPgpAvailable($action['props']);
}
$success = true;
$GLOBALS['PluginManager']->triggerHook('server.module.createmailitemmodule.beforesend', [
'moduleObject' => $this,
'store' => $store,
'entryid' => $entryid,
'action' => $action,
'success' => &$success,
'properties' => $this->properties,
'messageProps' => $messageProps,
'parententryid' => $parententryid,
]);
if (!$success) {
return ['result' => false, 'aborted' => true];
}
if (!isset($action['message_action']['action_type']) || $action['message_action']['action_type'] !== 'edit_as_new') {
$this->setReplyForwardInfo($action);
}
$savedUnsavedRecipients = [];
if ($entryid) {
// $store may already have been switched to the delegator's store
// while the draft lives in the user's own store.
try {
$message = $GLOBALS['operations']->openMessage($store, $entryid);
}
catch (MAPIException $e) {
$e->setHandled();
try {
$defaultStore = $GLOBALS['mapisession']->getDefaultMessageStore();
if ($defaultStore === false) {
$message = false;
}
else {
$message = $GLOBALS['operations']->openMessage($defaultStore, $entryid);
}
}
catch (MAPIException $e) {
$e->setHandled();
$message = false;
}
}
if ($message) {
$savedRecipients = $GLOBALS['operations']->getRecipientsInfo($message);
foreach ($savedRecipients as $recipient) {
$savedUnsavedRecipients['saved'][] = $recipient['props'];
}
}
}
if (!empty($recipients['add'])) {
foreach ($recipients['add'] as $recipient) {
$savedUnsavedRecipients['unsaved'][] = $recipient;
}
}
$remove = !empty($recipients['remove']) ? $recipients['remove'] : [];
$members = $GLOBALS['operations']->convertLocalDistlistMembersToRecipients($savedUnsavedRecipients, $remove);
$action['recipients'] = $action['recipients'] ?? [];
$action['recipients']['add'] = $members['add'];
$action['recipients']['remove'] = !empty($remove) ? array_merge($action['recipients']['remove'] ?? [], $members['remove']) : $members['remove'];
$error = $GLOBALS['operations']->submitMessage(
$store,
$entryid,
$this->withThreadingProperties(Conversion::mapXML2MAPI($this->properties, $action['props']), $copyInlineAttachmentsOnly),
$messageProps,
$action['recipients'] ?? [],
$action['attachments'] ?? [],
$copyFromMessage,
$copyAttachments,
false,
$copyInlineAttachmentsOnly,
isset($action['props']['isHTML']) ? !$action['props']['isHTML'] : false
);
if (!$error) {
$GLOBALS['operations']->parseDistListAndAddToRecipientHistory($savedUnsavedRecipients, $remove);
if ($entryid) {
$props = [];
$props[PR_ENTRYID] = $entryid;
$props[PR_PARENT_ENTRYID] = $parententryid;
$storeProps = mapi_getprops($store, [PR_ENTRYID]);
$props[PR_STORE_ENTRYID] = $storeProps[PR_ENTRYID];
$GLOBALS['bus']->addData($this->getResponseData());
$GLOBALS['bus']->notify(bin2hex($parententryid), TABLE_DELETE, $props);
}
$this->sendFeedback(true, [], false);
return ['result' => true, 'aborted' => false];
}
$data = [];
$data['type'] = 1;
$data['info'] = [];
if ($error === 'MAPI_E_NO_ACCESS') {
$data['info']['title'] = _('Insufficient permissions');
$data['info']['display_message'] = _("You don't have the permission to complete this action");
}
elseif ($error === 'ecQuotaExceeded') {
$data['info']['title'] = _('Quota error');
$data['info']['display_message'] = _('Send quota limit reached');
}
elseif ($error === 'SENDAS_IDENTITY_MISMATCH') {
$data['info']['title'] = _('Sender address could not be applied');
$data['info']['display_message'] = _('The message was not sent because the selected sender address could not be applied. Please try again.');
}
else {
$data['info']['title'] = _('Operation failed');
$data['info']['display_message'] = sprintf(_('Email sending failed (%s). Check the log files for more information.'), $error);
}
$this->addActionData('error', $data);
return ['result' => false, 'aborted' => false];
}
/**
* Handle the draft save flow including attachment and plugin updates.
*
* @param mixed $store
* @param mixed $entryid
* @param mixed $parententryid
* @param mixed $copyFromMessage
* @param bool $copyAttachments
* @param bool $copyInlineAttachmentsOnly
*
* @return array
*/
private function handleDraftSave($store, $entryid, $parententryid, array $action, array &$messageProps, $copyFromMessage, $copyAttachments, $copyInlineAttachmentsOnly) {
$propertiesToDelete = [];
$mapiProps = $this->withThreadingProperties(Conversion::mapXML2MAPI($this->properties, $action['props']), $copyInlineAttachmentsOnly);
if (isset($action['props']['sent_representing_entryid']) && empty($action['props']['sent_representing_entryid'])) {
$propertiesToDelete[] = PR_SENT_REPRESENTING_ENTRYID;
$propertiesToDelete[] = PR_SENT_REPRESENTING_SEARCH_KEY;
// Also drop a previously stored SMTP address, otherwise it would
// survive the removal of the From identity on the draft and could
// be picked up again as the sending identity.
$propertiesToDelete[] = PR_SENT_REPRESENTING_SMTP_ADDRESS;
}
$result = $GLOBALS['operations']->saveMessage(
$store,
$entryid,
$parententryid,
$mapiProps,
$messageProps,
$action['recipients'] ?? [],
$action['attachments'] ?? [],
$propertiesToDelete,
$copyFromMessage,
$copyAttachments,
false,
$copyInlineAttachmentsOnly
);
if (!$result) {
return ['result' => false, 'aborted' => false];
}
$props = mapi_getprops($result, [PR_ENTRYID]);
$savedMsg = $GLOBALS['operations']->openMessage($store, $props[PR_ENTRYID]);
$attachNum = !empty($action['attach_num']) ? $action['attach_num'] : false;
$data = [];
if ($attachNum) {
$message = $GLOBALS['operations']->openMessage($store, $props[PR_ENTRYID], $attachNum);
if (empty($message)) {
return ['result' => false, 'aborted' => true];
}
$data['item'] = $GLOBALS['operations']->getEmbeddedMessageProps($store, $message, $this->properties, $savedMsg, $attachNum);
}
else {
$data = $GLOBALS['operations']->getMessageProps($store, $savedMsg, $this->properties, $this->plaintext, true);
}
unset($data['props']['body'], $data['props']['html_body'], $data['props']['isHTML']);
$GLOBALS['PluginManager']->triggerHook('server.module.createmailitemmodule.aftersave', [
'data' => &$data,
'entryid' => $props[PR_ENTRYID],
'action' => $action,
'properties' => $this->properties,
'messageProps' => $messageProps,
'parententryid' => $parententryid,
]);
$this->addActionData('update', ['item' => $data]);
return ['result' => $result, 'aborted' => false];
}
/**
* Convert a hexadecimal string to binary data, returning false when invalid.
*
* @param string $value
*
* @return false|string
*/
private function hexToBinOrFalse($value) {
if ($value === '') {
return '';
}
if (!is_hex_entryid($value)) {
return false;
}
return hex2bin($value);
}
/**
* Function which is used to get the source message information, which contains the information of
* reply/forward and entry id of original mail, where we have to set the reply/forward arrow when
* draft(saved mail) is send.
*
* @param array $action the action data, sent by the client
*
* @return array|bool false when entryid and source message entryid is missing otherwise array with
* source store entryid and source message entryid if message has
*/
public function getSourceMsgInfo($action) {
$metaData = [];
if (isset($action["props"]["source_message_info"]) && !empty($action["props"]["source_message_info"])) {
if (isset($action["props"]['sent_representing_entryid']) && !empty($action["props"]['sent_representing_entryid'])) {
$storeEntryid = hex2bin((string) $action['message_action']['source_store_entryid']);
}
else {
$storeEntryid = hex2bin((string) $action['store_entryid']);
}
$metaData['source_message_info'] = $action["props"]["source_message_info"];
$metaData['storeEntryid'] = $storeEntryid;
return $metaData;
}
if (isset($action["entryid"]) && !empty($action["entryid"])) {
$storeEntryid = hex2bin((string) $action['store_entryid']);
$store = $GLOBALS['mapisession']->openMessageStore($storeEntryid);
$entryid = hex2bin((string) $action['entryid']);
try {
$message = $GLOBALS['operations']->openMessage($store, $entryid);
}
catch (MAPIException $e) {
$e->setHandled();
return false;
}
$messageProps = mapi_getprops($message);
$props = Conversion::mapMAPI2XML($this->properties, $messageProps);
$sourceMsgInfo = !empty($props['props']['source_message_info']) ? $props['props']['source_message_info'] : false;
if ($sourceMsgInfo === false) {
return false;
}
if (isset($props["props"]['sent_representing_entryid']) && !empty($props["props"]['sent_representing_entryid'])) {
$storeEntryid = $this->getSourceStoreEntryId($props);
}
$metaData['source_message_info'] = $sourceMsgInfo;
$metaData['storeEntryid'] = $storeEntryid;
return $metaData;
}
return false;
}
/**
* Function is used to get the shared or delegate store entryid where
* source message was stored, so the reply/forward arrow can be set when
* the draft (saved mail) is sent.
*
* @param array $props the $props data, which get from saved mail
*
* @return string source store entryid
*/
public function getSourceStoreEntryId($props) {
$sentRepresentingEntryid = $props['props']['sent_representing_entryid'];
$user = mapi_ab_openentry($GLOBALS['mapisession']->getAddressbook(), hex2bin((string) $sentRepresentingEntryid));
$userProps = mapi_getprops($user, [PR_EMAIL_ADDRESS]);
return $GLOBALS['mapisession']->getStoreEntryIdOfUser(strtolower((string) $userProps[PR_EMAIL_ADDRESS]));
}
/**
* Function is used to set the reply/forward arrow on original mail.
*
* @param array $action the action data, sent by the client
*/
public function setReplyForwardInfo($action) {
$sourceMsgInfo = $this->getSourceMsgInfo($action);
if (isset($sourceMsgInfo['source_message_info']) && $sourceMsgInfo['source_message_info']) {
/**
* $sourceMsgInfo['source_message_info'] contains a hexadecimal record. The action type occupies
* two hexadecimal characters starting at offset 24 (byte 12), and the original message entry ID
* begins at offset 48, after the 24-byte metadata prefix.
*
* Example: 01000E000C00000005010000660000000200000030000000 + record entry ID
* Here, 66 represents REPLY; similarly, 67 and 68 represent REPLY ALL and FORWARD, respectively.
*/
$mailActionType = substr((string) $sourceMsgInfo['source_message_info'], 24, 2);
// Get the entry ID of the original message.
$originalEntryid = substr((string) $sourceMsgInfo['source_message_info'], 48);
$entryid = hex2bin($originalEntryid);
$store = $GLOBALS['mapisession']->openMessageStore($sourceMsgInfo['storeEntryid']);
try {
// if original mail of reply/forward mail is deleted from inbox then,
// it will throw an exception so to handle it we need to write this block in try catch.
$message = $GLOBALS['operations']->openMessage($store, $entryid);
}
catch (MAPIException $e) {
$e->setHandled();
return;
}
if ($message) {
$messageProps = mapi_getprops($message);
$props = Conversion::mapMAPI2XML($this->properties, $messageProps);
switch ($mailActionType) {
case '66': // Reply
case '67': // Reply All
$props['icon_index'] = 261;
break;
case '68':// Forward
$props['icon_index'] = 262;
break;
}
$props['last_verb_executed'] = hexdec($mailActionType);
$props['last_verb_execution_time'] = time();
$mapiProps = Conversion::mapXML2MAPI($this->properties, $props);
$messageActionProps = [];
$messageActionResult = $GLOBALS['operations']->saveMessage($store, $mapiProps[PR_ENTRYID], $mapiProps[PR_PARENT_ENTRYID], $mapiProps, $messageActionProps);
if ($messageActionResult) {
if (isset($messageActionProps[PR_PARENT_ENTRYID])) {
$GLOBALS['bus']->notify(bin2hex($messageActionProps[PR_PARENT_ENTRYID]), TABLE_SAVE, $messageActionProps);
}
}
}
}
}
}
@@ -0,0 +1,847 @@
<?php
/*
* SPDX-FileCopyrightText: Copyright 2020 - 2026 grommunio GmbH
* SPDX-FileCopyrightText: Copyright 2016 Kopano and its licensors
* SPDX-FileCopyrightText: Copyright 2005 - 2016 Zarafa B.V. and its licensors
* SPDX-License-Identifier: AGPL-3.0-or-later
*/
/**
* DelegatesModule
* Class can be used to get delegate information of a particular user.
* The delegate information can be created/update using this class as well.
*/
class DelegatesModule extends Module {
/**
* @var array contains entryid's of all default folders
*/
private $defaultFolders;
/**
* @var array contains delegate properties from special message (LocalFreebusy)
*/
private $delegateProps;
/**
* @var false|resource LocalFreeBusy message, or false before it is opened
*/
private $localFreeBusyMessage;
/**
* @var false|resource FreeBusy folder in IPM_SUBTREE, or false before it is opened
*/
private $freeBusyFolder;
/**
* @var false|resource default store of the current user, or false before it is opened
*/
private $defaultStore;
/**
* Constructor.
*
* @param int $id unique id
* @param array $data list of all actions
*/
public function __construct($id, $data) {
$this->defaultFolders = [];
$this->delegateProps = [];
$this->localFreeBusyMessage = false;
$this->freeBusyFolder = false;
$this->defaultStore = false;
parent::__construct($id, $data);
}
/**
* Executes all the actions in the $data variable.
*/
#[Override]
public function execute() {
$delegatesLock = State::forStore('delegates-write');
if (!$delegatesLock->open()) {
throw new RuntimeException('Unable to lock the delegate settings');
}
try {
$this->executeLocked();
}
finally {
$delegatesLock->close();
}
}
private function executeLocked() {
foreach ($this->data as $actionType => $action) {
if (isset($actionType)) {
try {
switch ($actionType) {
case 'list':
$this->delegateList();
break;
case 'open':
$this->openDelegate($action);
break;
case 'save':
$this->saveDelegates($action);
break;
case 'delete':
$this->deleteDelegates($action);
break;
default:
$this->handleUnknownActionType($actionType);
}
}
catch (MAPIException $e) {
$this->processException($e, $actionType);
}
}
}
}
/* Generic functions to access data */
/**
* Function will return values of the properties PR_DELEGATE_FLAGS, PR_SCHDINFO_DELEGATE_ENTRYIDS and
* PR_SCHDINFO_DELEGATE_NAMES from LocalFreeBusyMessage of the user's store.
*
* @param resource $localFreeBusyMessage (optional) local freebusy message of the user's store
*
* @return array values of delegate properties
*/
public function getDelegateProps($localFreeBusyMessage = false) {
if (empty($this->delegateProps)) {
if ($localFreeBusyMessage === false) {
$localFreeBusyMessage = FreeBusy::getLocalFreeBusyMessage($this->getDefaultStore());
}
$this->delegateProps = mapi_getprops($localFreeBusyMessage, [PR_DELEGATE_FLAGS, PR_SCHDINFO_DELEGATE_ENTRYIDS, PR_SCHDINFO_DELEGATE_NAMES]);
// check if properties exists or not, if not then initialize with default values
// this way in caller functions we don't need to check for non-existent properties
if (!isset($this->delegateProps[PR_DELEGATE_FLAGS])) {
$this->delegateProps[PR_DELEGATE_FLAGS] = [];
}
if (!isset($this->delegateProps[PR_SCHDINFO_DELEGATE_ENTRYIDS])) {
$this->delegateProps[PR_SCHDINFO_DELEGATE_ENTRYIDS] = [];
}
if (!isset($this->delegateProps[PR_SCHDINFO_DELEGATE_NAMES])) {
$this->delegateProps[PR_SCHDINFO_DELEGATE_NAMES] = [];
}
}
return $this->delegateProps;
}
/**
* Function will return array of entryids of default folders of the user's store.
*
* @param resource $store (optional) user's store
*
* @return array default folder entryids
*/
public function getDefaultFolders($store = false) {
if (empty($this->defaultFolders)) {
if ($store === false) {
$store = $this->getDefaultStore();
}
// Get root store
$root = mapi_msgstore_openentry($store);
// Get Inbox folder
$inbox = mapi_msgstore_getreceivefolder($store);
$inboxprops = mapi_getprops($inbox, [PR_ENTRYID]);
// Get entryids of default folders.
$rootStoreProps = mapi_getprops($root, [PR_IPM_APPOINTMENT_ENTRYID, PR_IPM_TASK_ENTRYID, PR_IPM_CONTACT_ENTRYID, PR_IPM_NOTE_ENTRYID, PR_IPM_JOURNAL_ENTRYID]);
$this->defaultFolders = [
'calendar' => $rootStoreProps[PR_IPM_APPOINTMENT_ENTRYID],
'tasks' => $rootStoreProps[PR_IPM_TASK_ENTRYID],
'inbox' => $inboxprops[PR_ENTRYID],
'contacts' => $rootStoreProps[PR_IPM_CONTACT_ENTRYID],
'notes' => $rootStoreProps[PR_IPM_NOTE_ENTRYID],
'journal' => $rootStoreProps[PR_IPM_JOURNAL_ENTRYID],
];
}
return $this->defaultFolders;
}
/**
* Function will return index of a particular delegate, this index can be used to get information of
* delegate from PR_DELEGATE_FLAGS, PR_SCHDINFO_DELEGATE_ENTRYIDS and
* PR_SCHDINFO_DELEGATE_NAMES properties.
*
* @param string $entryId entryid of delegate
*
* @return false|int|string index of the delegate information, or false when it is absent
*/
public function getDelegateIndex($entryId) {
$delegateProps = $this->getDelegateProps();
// Check if user is existing delegate.
if (!empty($delegateProps[PR_SCHDINFO_DELEGATE_ENTRYIDS])) {
return array_search($entryId, $delegateProps[PR_SCHDINFO_DELEGATE_ENTRYIDS]);
}
return false;
}
/**
* Function will return resource of the default store of the current logged in user.
*
* @return resource current user's store
*/
public function getDefaultStore() {
if (!$this->defaultStore) {
$this->defaultStore = $GLOBALS['mapisession']->getDefaultMessageStore();
}
return $this->defaultStore;
}
/**
* Function will return properties of the user from addressbook based on passed user's entryid.
*
* @param string $userEntryId entryid of the user from addressbook
*
* @return array properties of user from addressbook
*/
public function getUserInfo($userEntryId) {
// default return stuff
$result = [
'display_name' => _('Unknown user/group'),
'entryid' => null,
];
// open the addressbook
$ab = $GLOBALS['mapisession']->getAddressbook();
try {
// try userid as normal user
$user = mapi_ab_openentry($ab, $userEntryId);
}
catch (MAPIException $e) {
if ($e->getCode() === MAPI_E_NOT_FOUND) {
$e->setHandled();
return $result;
}
throw $e;
}
$props = mapi_getprops($user, [PR_DISPLAY_NAME]);
$result['display_name'] = $props[PR_DISPLAY_NAME];
$result['entryid'] = bin2hex($userEntryId);
return $result;
}
/* Functions to get delegates information */
/**
* Function will return all the delegates information for current user.
*/
public function delegateList() {
$data = [];
$delegates = mapi_getdelegates($GLOBALS['mapisession']->getSession(), 0);
if (!empty($delegates)) {
$delegateMeetingRule = $this->getDelegateMeetingRule();
foreach ($delegates as $username) {
// Exact lookup: resolvename substring-matches names, addresses and
// aliases, so one delegate could resolve ambiguously and fail the list.
try {
$userEntryId = nsp_getuserinfo($username)['userid'];
}
catch (MAPIException $e) {
// Stale entry, e.g. a deleted user
continue;
}
array_push($data, $this->getDelegatePermissions($userEntryId, $delegateMeetingRule));
}
}
$this->addActionData('list', ['item' => $data]);
$GLOBALS['bus']->addData($this->getResponseData());
}
/**
* Function will return the permissions assigned for a particular delegate user.
*
* @param array $delegate the delegate information sent by client
*/
public function openDelegate($delegate) {
// Get permissions of a delegate.
$data = $this->getDelegatePermissions(hex2bin((string) $delegate['entryid']));
$this->addActionData('item', ['item' => $data]);
$GLOBALS['bus']->addData($this->getResponseData());
}
/**
* Function will return information of a particular delegate from current user's store.
*
* @param string $userEntryId entryid of the delegate
* @param null|array|false $delegateMeetingRule (optional) delegate meeting rule or false when none exists, fetched when null
*
* @return array delegate information
*/
public function getDelegatePermissions($userEntryId, $delegateMeetingRule = null) {
$delegateProps = $this->getDelegateProps();
$delegateIndex = $this->getDelegateIndex($userEntryId);
$userinfo = $this->getUserInfo($userEntryId);
if ($delegateMeetingRule === null) {
$delegateMeetingRule = $this->getDelegateMeetingRule();
}
$ruleUsers = $this->getDelegateMeetingRuleUsers($delegateMeetingRule);
$delegate = [];
$delegate['entryid'] = bin2hex($userEntryId);
$delegate['props'] = [];
$delegate['props']['display_name'] = $userinfo['display_name'];
$delegate['props']['can_see_private'] = $delegateIndex !== false && isset($delegateProps[PR_DELEGATE_FLAGS][$delegateIndex]) ? ($delegateProps[PR_DELEGATE_FLAGS][$delegateIndex] == 1) : false;
$delegate['props']['has_meeting_rule'] = $this->findDelegateMeetingRuleUser($ruleUsers, $userEntryId) !== false;
$delegate['props'] = array_merge($delegate['props'], $this->getFolderPermissions($userEntryId));
return $delegate;
}
/**
* Function will return folder permissions of a delegate user.
*
* @param string $userEntryId entryid of the delegate
*
* @return array folder permissions of a delegate user
*/
public function getFolderPermissions($userEntryId) {
$delegateRights = [];
$store = $this->getDefaultStore();
foreach ($this->getDefaultFolders($store) as $folderName => $folderEntryId) {
$folder = mapi_msgstore_openentry($store, $folderEntryId);
// Get all users who has permissions
$grants = mapi_zarafa_getpermissionrules($folder, ACCESS_TYPE_GRANT);
// Find current delegate and get permission.
foreach ($grants as $id => $grant) {
if ($GLOBALS["entryid"]->compareEntryIds(bin2hex($userEntryId), bin2hex((string) $grant['userid']))) {
$delegateRights['rights_' . $folderName] = $grant['rights'];
}
}
}
return $delegateRights;
}
/**
* Function will return properties of meeting rule that is used to send meeting related messages to delegate.
*
* @return array|false delegate meeting rule information, or false when no rule exists
*/
public function getDelegateMeetingRule() {
$inbox = mapi_msgstore_getreceivefolder($this->getDefaultStore());
$rulesTable = mapi_folder_getrulestable($inbox);
// get delegate meeting rule
$restriction = [RES_CONTENT,
[
FUZZYLEVEL => FL_FULLSTRING | FL_IGNORECASE,
ULPROPTAG => PR_RULE_PROVIDER,
VALUE => [
PR_RULE_PROVIDER => 'Schedule+ EMS Interface',
],
],
];
mapi_table_restrict($rulesTable, $restriction);
// there will be only one rule, so fetch that only
$delegateMeetingRule = mapi_table_queryrows($rulesTable, $GLOBALS['properties']->getRulesProperties(), 0, 1);
return !empty($delegateMeetingRule) ? $delegateMeetingRule[0] : false;
}
/**
* @param array|false $delegateMeetingRule delegate meeting rule
*
* @return array recipients of the rule's delegate action
*/
private function getDelegateMeetingRuleUsers($delegateMeetingRule) {
return $delegateMeetingRule !== false ? ($delegateMeetingRule[PR_RULE_ACTIONS][0]['adrlist'] ?? []) : [];
}
/**
* @param array $users recipients of the delegate meeting rule
* @param string $userEntryId entryid of the delegate
*
* @return false|int position of the delegate in $users, or false when absent
*/
private function findDelegateMeetingRuleUser($users, $userEntryId) {
foreach ($users as $index => $user) {
if (isset($user[PR_ENTRYID]) && $GLOBALS['entryid']->compareEntryIds(bin2hex((string) $user[PR_ENTRYID]), bin2hex($userEntryId))) {
return $index;
}
}
return false;
}
/* Functions to update delegates information */
/**
* Function which saves delegates information sent from client.
*
* @param array $delegates the delegates information sent by client
*/
public function saveDelegates($delegates) {
$responseData = [];
// @FIXME currently client only sends a single delegate in a request, if we can change that to contain
// multiple delegates that would be good
if (is_assoc_array($delegates)) {
// wrap single delegate in an array
$delegates = [$delegates];
}
for ($index = 0, $len = count($delegates); $index < $len; ++$index) {
$delegate = $delegates[$index];
$this->setFolderPermissions($delegate);
// set properties for delegates on user's freebusy folder
array_push($responseData, ['entryid' => $delegate['entryid']]);
}
$this->setDelegateProps($delegates);
// set delegate meeting rule
$this->setDelegateMeetingRule($delegates);
// send response to indicate success
if (!empty($responseData)) {
$this->addActionData('update', ['item' => $responseData]);
$GLOBALS['bus']->addData($this->getResponseData());
}
}
/**
* Function will update PR_DELEGATE_FLAGS, PR_SCHDINFO_DELEGATE_ENTRYIDS and
* PR_SCHDINFO_DELEGATE_NAMES properties in the current user's store.
*
* @param mixed $delegates
*/
public function setDelegateProps($delegates) {
$localFreeBusyMessage = FreeBusy::getLocalFreeBusyMessage($this->getDefaultStore());
$delegateProps = $this->getDelegateProps($localFreeBusyMessage);
$len = count($delegates);
for ($i = 0; $i < $len; ++$i) {
$delegate = $delegates[$i];
$len1 = count($delegateProps[PR_SCHDINFO_DELEGATE_ENTRYIDS]);
for ($j = 0; $j < $len1; ++$j) {
if ($delegateProps[PR_SCHDINFO_DELEGATE_ENTRYIDS][$j] == hex2bin((string) $delegate['entryid'])) {
break;
}
}
$delegateProps[PR_SCHDINFO_DELEGATE_ENTRYIDS][$j] = hex2bin((string) $delegate['entryid']);
if (isset($delegate['props']['display_name'])) {
$delegateProps[PR_SCHDINFO_DELEGATE_NAMES][$j] = $delegate['props']['display_name'];
}
elseif (!isset($delegateProps[PR_SCHDINFO_DELEGATE_NAMES][$j])) {
$addrBook = $GLOBALS['mapisession']->getAddressbook();
$user = mapi_ab_openentry($addrBook, hex2bin((string) $delegate['entryid']));
if (empty($user)) {
$delegateProps[PR_SCHDINFO_DELEGATE_NAMES][$j] = "";
}
else {
$userProps = mapi_getprops($user, [PR_SMTP_ADDRESS]);
if (empty($userProps[PR_SMTP_ADDRESS])) {
$delegateProps[PR_SCHDINFO_DELEGATE_NAMES][$j] = "";
}
else {
$delegateProps[PR_SCHDINFO_DELEGATE_NAMES][$j] = $userProps[PR_SMTP_ADDRESS];
}
}
}
if (isset($delegate['props']['can_see_private'])) {
$delegateProps[PR_DELEGATE_FLAGS][$j] = $delegate['props']['can_see_private'];
}
elseif (!isset($delegateProps[PR_DELEGATE_FLAGS][$j])) {
$delegateProps[PR_DELEGATE_FLAGS][$j] = false;
}
}
mapi_setprops($localFreeBusyMessage, $delegateProps);
mapi_savechanges($localFreeBusyMessage);
// unset the module variable, so subsequent calls will have the updated value
unset($this->delegateProps);
}
/**
* Function will set folder permissions for a delegate user.
*
* @param array $delegate delegate information sent from client
*/
public function setFolderPermissions($delegate) {
$store = $this->getDefaultStore();
// Get all default folders and set permissions.
foreach ($this->getDefaultFolders($store) as $folderName => $folderEntryID) {
// we need to only modify those permissions which are modified on client
if (isset($delegate['props']['rights_' . $folderName]) && $delegate['props']['rights_' . $folderName] !== '') {
$folder = mapi_msgstore_openentry($store, $folderEntryID);
// Set new permissions.
$acls = [
[
'type' => ACCESS_TYPE_GRANT,
'userid' => hex2bin((string) $delegate['entryid']),
'rights' => $delegate['props']['rights_' . $folderName],
'state' => RIGHT_NEW | RIGHT_AUTOUPDATE_DENIED,
'memberid' => 0,
],
];
mapi_zarafa_setpermissionrules($folder, $acls);
mapi_savechanges($folder);
if ($folderName === 'calendar') {
$freeBusyFolder = FreeBusy::getLocalFreeBusyFolder($store);
if ($freeBusyFolder !== false) {
// set permissions on free/busy message
$acls[0]['rights'] |= ecRightsDefaultPublic;
mapi_zarafa_setpermissionrules($freeBusyFolder, $acls);
mapi_savechanges($freeBusyFolder);
}
}
}
}
}
/**
* Function which creates/modifies delegate meeting rule in user store
* to send meeting request mails to delegates also.
*
* @param array $delegates all delegate information
*/
public function setDelegateMeetingRule($delegates) {
$delegateMeetingRule = $this->getDelegateMeetingRule();
$users = $this->getDelegateMeetingRuleUsers($delegateMeetingRule);
$addrBook = $GLOBALS['mapisession']->getAddressbook();
$changed = false;
foreach ($delegates as $delegate) {
// existing delegates only send the flag when the checkbox changed
if (!isset($delegate['props']['has_meeting_rule'])) {
continue;
}
$userEntryId = hex2bin((string) $delegate['entryid']);
$index = $this->findDelegateMeetingRuleUser($users, $userEntryId);
if (!$delegate['props']['has_meeting_rule']) {
if ($index !== false) {
array_splice($users, $index, 1);
$changed = true;
}
continue;
}
$user = mapi_ab_openentry($addrBook, $userEntryId);
$userProps = mapi_getprops($user, [PR_ENTRYID, PR_ADDRTYPE, PR_EMAIL_ADDRESS, PR_DISPLAY_NAME, PR_SEARCH_KEY, PR_SMTP_ADDRESS, PR_OBJECT_TYPE, PR_DISPLAY_TYPE, PR_DISPLAY_TYPE_EX]);
if (!is_array($userProps)) {
continue;
}
$userProps[PR_RECIPIENT_TYPE] = MAPI_TO;
if ($index === false) {
$users[] = $userProps;
}
else {
$users[$index] = $userProps;
}
$changed = true;
}
if (!$changed) {
return;
}
if ($delegateMeetingRule === false) {
$this->createDelegateMeetingRule($users);
}
else {
$this->modifyDelegateMeetingRule($delegateMeetingRule, $users);
}
}
/**
* Function will create a new delegate meeting rule if it is not present in current user's store.
*
* @param array $usersInfo user properties which should be added in PR_RULE_ACTIONS
*/
public function createDelegateMeetingRule($usersInfo) {
// create new rule
$rule = [];
// no need to pass rule_id when creating new rule
$rule[PR_RULE_ACTIONS] = [
[
'action' => OP_DELEGATE,
// don't set this value it will have no effect, its hardcoded to FWD_PRESERVE_SENDER | FWD_DO_NOT_MUNGE_MSG
'flavor' => 0,
'flags' => 0,
'adrlist' => $usersInfo,
],
];
$rule[PR_RULE_CONDITION] = [RES_AND,
[
[RES_CONTENT,
[
FUZZYLEVEL => FL_PREFIX,
ULPROPTAG => PR_MESSAGE_CLASS,
VALUE => [PR_MESSAGE_CLASS => 'IPM.Schedule.Meeting'],
],
],
[RES_NOT,
[
[RES_EXIST,
[
ULPROPTAG => PR_DELEGATED_BY_RULE,
],
],
],
],
[RES_OR,
[
[RES_NOT,
[
[RES_EXIST,
[
ULPROPTAG => PR_SENSITIVITY,
],
],
],
],
[RES_PROPERTY,
[
RELOP => RELOP_NE,
ULPROPTAG => PR_SENSITIVITY,
VALUE => [PR_SENSITIVITY => SENSITIVITY_PRIVATE],
],
],
],
],
],
];
$rule[PR_RULE_NAME] = '';
$rule[PR_RULE_PROVIDER_DATA] = ''; // 0 byte binary string
$rule[PR_RULE_STATE] = ST_ENABLED;
$rule[PR_RULE_LEVEL] = 0;
$rule[PR_RULE_SEQUENCE] = 0;
$rule[PR_RULE_PROVIDER] = 'Schedule+ EMS Interface';
$rule[PR_RULE_USER_FLAGS] = 0;
$rows = [
0 => [
'rowflags' => ROW_ADD,
'properties' => $rule,
],
];
$inbox = mapi_msgstore_getreceivefolder($this->getDefaultStore());
mapi_folder_modifyrules($inbox, $rows);
}
public function modifyDelegateMeetingRule($delegateMeetingRule, $users) {
$inbox = mapi_msgstore_getreceivefolder($this->getDefaultStore());
if (count($users) > 0) {
// update the adrlist in the rule
$delegateMeetingRule[PR_RULE_ACTIONS][0]['adrlist'] = $users;
$rows = [
[
'rowflags' => ROW_MODIFY,
'properties' => $delegateMeetingRule,
],
];
}
else {
// no users remaining in the rule so delete the rule
$rows = [
0 => [
'rowflags' => ROW_REMOVE,
'properties' => $delegateMeetingRule,
],
];
}
mapi_folder_modifyrules($inbox, $rows);
}
/* Functions to delete delegates information */
/**
* Function which deletes delegates information sent by client.
*
* @param array $delegates delegates information sent by client
*/
public function deleteDelegates($delegates) {
if (is_assoc_array($delegates)) {
// wrap single delegate in an array
$delegates = [$delegates];
}
foreach ($delegates as $delegate) {
// set properties for delegates on user's freebusy folder
$this->deleteDelegateProps($delegate);
// set permissions on user's default folders
$this->deleteFolderPermissions($delegate);
}
// delete delegate meeting rule
$this->removeDelegatesFromDelegateMeetingRule($delegates);
$this->sendFeedback(true);
}
/**
* Function will delete values from PR_DELEGATE_FLAGS, PR_SCHDINFO_DELEGATE_ENTRYIDS and PR_SCHDINFO_DELEGATE_NAMES and save the properties back if its not empty.
*
* @param array $delegate delegate information sent from client
*/
public function deleteDelegateProps($delegate) {
$localFreeBusyMessage = FreeBusy::getLocalFreeBusyMessage($this->getDefaultStore());
$delegateProps = $this->getDelegateProps($localFreeBusyMessage);
$delegateIndex = -1;
$len = count($delegateProps[PR_SCHDINFO_DELEGATE_ENTRYIDS]);
for ($i = 0; $i < $len; ++$i) {
if ($delegateProps[PR_SCHDINFO_DELEGATE_ENTRYIDS][$i] == hex2bin((string) $delegate["entryid"])) {
$delegateIndex = $i;
break;
}
}
if ($delegateIndex == -1) {
return;
}
unset($delegateProps[PR_DELEGATE_FLAGS][$delegateIndex], $delegateProps[PR_SCHDINFO_DELEGATE_ENTRYIDS][$delegateIndex], $delegateProps[PR_SCHDINFO_DELEGATE_NAMES][$delegateIndex]);
// unset will remove the value but will not regenerate array keys, so we need to
// do it here
$delegateProps[PR_DELEGATE_FLAGS] = array_values($delegateProps[PR_DELEGATE_FLAGS]);
$delegateProps[PR_SCHDINFO_DELEGATE_ENTRYIDS] = array_values($delegateProps[PR_SCHDINFO_DELEGATE_ENTRYIDS]);
$delegateProps[PR_SCHDINFO_DELEGATE_NAMES] = array_values($delegateProps[PR_SCHDINFO_DELEGATE_NAMES]);
if (!empty($delegateProps[PR_SCHDINFO_DELEGATE_ENTRYIDS])) {
mapi_setprops($localFreeBusyMessage, $delegateProps);
}
else {
// Delete delegate properties.
mapi_deleteprops($localFreeBusyMessage, [PR_DELEGATE_FLAGS, PR_SCHDINFO_DELEGATE_ENTRYIDS, PR_SCHDINFO_DELEGATE_NAMES]);
}
mapi_savechanges($localFreeBusyMessage);
// unset the module variable, so subsequent calls will have the updated value
unset($this->delegateProps);
}
/**
* Function which deletes permissions from all default folder for a particular delegate.
*
* @param array $delegate delegate's information sent by client
*/
public function deleteFolderPermissions($delegate) {
$store = $this->getDefaultStore();
// Get all default folders and set permissions.
foreach ($this->getDefaultFolders($store) as $folderName => $folderEntryID) {
$folder = mapi_msgstore_openentry($store, $folderEntryID);
// delete current acl's
$acls = [
[
'type' => ACCESS_TYPE_GRANT,
'userid' => hex2bin((string) $delegate['entryid']),
'rights' => ecRightsNone,
'state' => RIGHT_DELETED | RIGHT_AUTOUPDATE_DENIED,
'memberid' => 0,
],
];
mapi_zarafa_setpermissionrules($folder, $acls);
if ($folderName === 'calendar') {
$freeBusyFolder = FreeBusy::getLocalFreeBusyFolder($store);
if ($freeBusyFolder !== false) {
mapi_zarafa_setpermissionrules($freeBusyFolder, $acls);
mapi_savechanges($freeBusyFolder);
}
}
mapi_savechanges($folder);
}
}
/**
* Function will remove delegates from delegate meeting rule when the user is deleted from delegate list.
*
* @param array $delegates all delegate information that are deleted
*/
public function removeDelegatesFromDelegateMeetingRule($delegates) {
$delegateMeetingRule = $this->getDelegateMeetingRule();
if ($delegateMeetingRule === false) {
return;
}
$users = $this->getDelegateMeetingRuleUsers($delegateMeetingRule);
$changed = false;
foreach ($delegates as $delegate) {
$index = $this->findDelegateMeetingRuleUser($users, hex2bin((string) $delegate['entryid']));
if ($index !== false) {
array_splice($users, $index, 1);
$changed = true;
}
}
if ($changed) {
$this->modifyDelegateMeetingRule($delegateMeetingRule, $users);
}
}
/* Functions for exception handling */
/**
* Function does customization of MAPIException based on module data.
* like, here it will generate display message based on actionType
* for particular exception.
*
* @param object $e Exception object
* @param string $actionType the action type, sent by the client
* @param resource $store current user's MAPI store
* @param string $parententryid parent entryid of the message
* @param string $entryid entryid of the message/folder
* @param array $action the action data, sent by the client
*/
#[Override]
public function handleException(&$e, $actionType = null, $store = null, $parententryid = null, $entryid = null, $action = null) {
switch ($actionType) {
case 'save':
$e->setDisplayMessage(_('Could not save delegate information.'));
break;
case 'delete':
$e->setDisplayMessage(_('Could not delete delegate.'));
break;
case 'list':
$e->setDisplayMessage(_('Can not get list of delegates.'));
break;
}
parent::handleException($e, $actionType, $store, $parententryid, $entryid, $action);
}
}
@@ -0,0 +1,122 @@
<?php
/*
* SPDX-FileCopyrightText: Copyright 2020 - 2026 grommunio GmbH
* SPDX-FileCopyrightText: Copyright 2016 Kopano and its licensors
* SPDX-FileCopyrightText: Copyright 2005 - 2016 Zarafa B.V. and its licensors
* SPDX-License-Identifier: AGPL-3.0-or-later
*/
/**
* ExpandDistlist Module.
*/
class ExpandDistlistModule extends Module {
private $addrbook;
/**
* Constructor.
*
* @param mixed $id
* @param mixed $data
*/
public function __construct($id, $data) {
parent::__construct($id, $data);
$this->properties = $GLOBALS["properties"]->getRecipientProperties();
}
/**
* Executes all the actions in the $data variable.
*/
#[Override]
public function execute() {
foreach ($this->data as $actionType => $action) {
if (isset($actionType)) {
try {
switch ($actionType) {
case 'expand':
$this->expand($action);
break;
default:
$this->handleUnknownActionType($actionType);
}
}
catch (MAPIException $e) {
$this->processException($e, $actionType);
}
}
}
}
/**
* Function which expands a distribution list, optionally expands a distribution list in a distribution list.
* Duplicate members will not be filtered.
*
* @param string $entryid entryid of distribution list
* @param array $data an array of members in the distribution list
* @param bool $isRecurse true if we want to expand a distribution list in distribution lists
*
* @return array $data an array of members in the distribution list
*/
public function expandDist($entryid, $data = [], $isRecurse = false) {
$heid = bin2hex($entryid);
if ($GLOBALS['entryid']->hasAddressBookGUID($heid) || $GLOBALS['entryid']->hasAddressBookRecipientGUID($heid)) {
$abentry = mapi_ab_openentry($this->addrbook, $entryid);
$table = mapi_folder_getcontentstable($abentry, MAPI_DEFERRED_ERRORS);
$rows = mapi_table_queryrows($table, $this->properties, 0, (ABITEMDETAILS_MAX_NUM_DISTLIST_MEMBERS > 0) ? ABITEMDETAILS_MAX_NUM_DISTLIST_MEMBERS : 0x7FFFFFFF);
/*
* To prevent loading a huge list that the browser cannot handle, it is possible to
* limit the maximum number of shown items. Note that when the table doesn't
* contain the requested number of rows, it will not give any errors and simply
* return what is available.
* When the limit is 0 or below, then no limit is applied and we use 0x7fffffff
* to indicate we want to have all rows from the table.
*/
for ($i = 0, $len = count($rows); $i < $len; ++$i) {
$memberProps = Conversion::mapMAPI2XML($this->properties, $rows[$i]);
$isDistlist = $memberProps['props']['object_type'] == MAPI_DISTLIST;
if ($isDistlist && $isRecurse === true) {
$data = array_merge($data, $this->expandDist(hex2bin((string) $memberProps['entryid']), [], $isRecurse));
}
else {
$data[] = $memberProps;
}
}
}
else {
/**
* If distribution list was belongs to local/shared folder then
* it will expand all members of distribution list.
*/
$distlistMembers = $GLOBALS['operations']->expandDistList($heid, $isRecurse);
$recipients = [];
foreach ($distlistMembers as $distlistMember) {
$recipients['props'] = $distlistMember;
array_push($data, $recipients);
}
}
return $data;
}
/**
* Function which expand the distribution list, sent by the client. This function is used
* when a user wants to replace the distribution list with its members
* in the to, cc and bcc field. This function retrieve members of that particular distribution list
* and send that list back to the client.
*
* @param array $action the action data, sent by the client
*/
public function expand($action) {
// Get the distribution list entryid from request
$entryid = hex2bin((string) $action["entryid"]);
$this->addrbook = $GLOBALS["mapisession"]->getAddressbook();
if ($entryid) {
$data = ["results" => $this->expandDist($entryid, [], $action['recurse'])];
$this->addActionData("expand", $data);
$GLOBALS["bus"]->addData($this->getResponseData());
}
}
}
@@ -0,0 +1,108 @@
<?php
/*
* SPDX-FileCopyrightText: Copyright 2020 - 2026 grommunio GmbH
* SPDX-FileCopyrightText: Copyright 2016 Kopano and its licensors
* SPDX-FileCopyrightText: Copyright 2005 - 2016 Zarafa B.V. and its licensors
* SPDX-License-Identifier: AGPL-3.0-or-later
*/
/**
* FreeBusyModule Module.
*/
class FreeBusyModule extends Module {
#[Override]
protected function getExecutionLockName() {
return null;
}
public function __construct($id, $data) {
parent::__construct($id, $data);
}
#[Override]
public function execute() {
foreach ($this->data as $actionType => $selUser) {
if (isset($actionType)) {
try {
switch ($actionType) {
case 'list':
$this->addUserData($selUser);
break;
default:
$this->handleUnknownActionType($actionType);
}
}
catch (MAPIException $e) {
$this->processException($e, $actionType);
}
}
}
}
/**
* This function will get user info from address book and add freebusy data of the user to
* response.
*
* @param array $selUser User that should be resolved
*/
public function addUserData($selUser) {
$data = [
'users' => [],
];
foreach ($selUser['users'] as $fbUser) {
// Copy the identifier of the user.
$user = [
'userid' => $fbUser['userid'],
'entryid' => $fbUser['entryid'],
];
// Obtain the Freebusy data for this user
$busyArray = $this->getFreeBusyInfo($fbUser['entryid'], $selUser['start'], $selUser['end']);
$user['items'] = $busyArray;
$data['users'][] = $user;
}
$this->addActionData('list', $data);
$GLOBALS['bus']->addData($this->getResponseData());
}
/**
* This function will get freebusy data for user based on the timeframe passed in arguments.
*
* @param string $entryID Entryid of the user for which we need to get freebusy data
* @param int $start start offset for freebusy publish range
* @param int $end end offset for freebusy publish range
*
* @return array freebusy blocks for passed publish range
*/
public function getFreeBusyInfo($entryID, $start, $end) {
$result = [];
try {
$fbdata = mapi_getuserfreebusy($GLOBALS['mapisession']->getSession(), hex2bin($entryID), $start, $end);
foreach ($fbdata['fbevents'] as $event) {
$result[] = [
'start' => $event['start'],
'end' => $event['end'],
'status' => $event['busystatus'],
];
}
}
catch (Exception $e) {
error_log(sprintf("getFreeBusyInfo exception: %s (0x%08X)", $e->getMessage(), $e->getCode()));
// -1 is the client's status for an absent answer. fbNoData cannot
// say it here, because it shares its value with fbWorkingElsewhere.
$result[] = [
'start' => $start,
'end' => $end,
'status' => -1,
];
}
return $result;
}
}
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,387 @@
<?php
/*
* SPDX-FileCopyrightText: Copyright 2020 - 2026 grommunio GmbH
* SPDX-License-Identifier: AGPL-3.0-or-later
*/
require_once BASE_PATH . 'server/includes/core/class.junkrule.php';
require_once BASE_PATH . 'server/includes/core/class.junksenderlist.php';
/**
* JunkMailModule Module.
*
* This class reads and writes the Outlook Junk Email Rule (MS-OXCSPAM). The
* IPM.ExtendedRule.Message FAI message in the inbox whose extended rule
* condition carries the blocked senders, safe senders and safe recipients
* lists. Outlook reads and writes the same message, so both clients see
* one set of lists.
*/
class JunkMailModule extends Module {
public const MAX_ENTRIES = 1024;
public const MAX_ENTRY_LENGTH = JunkSenderList::MAX_ENTRY_LENGTH;
/**
* Per-request cache of parsed lists.
*/
private static $cachedLists;
/**
* Executes all the actions in the $data variable.
*/
#[Override]
public function execute() {
foreach ($this->data as $actionType => $action) {
if (isset($actionType)) {
try {
switch ($actionType) {
case "list":
$this->getJunkSettings();
break;
case "save":
$this->saveJunkSettings($action);
break;
default:
$this->handleUnknownActionType($actionType);
}
}
catch (MAPIException $e) {
$this->processException($e, $actionType);
}
catch (GrommunioException $e) {
$this->sendFeedback(false, [
"type" => ERROR_GROMMUNIO,
"info" => ["display_message" => $e->getDisplayMessage()],
]);
}
}
}
}
/**
* Find the Junk Email Rule FAI message in the inbox associated contents.
*
* @param resource $store MAPI message store
*
* @return array [message|false, inbox]
*/
public static function findJunkRule($store) {
$inbox = mapi_msgstore_getreceivefolder($store);
$table = mapi_folder_getcontentstable($inbox, MAPI_ASSOCIATED);
mapi_table_restrict($table, [RES_AND, [
[RES_CONTENT,
[
FUZZYLEVEL => FL_FULLSTRING | FL_IGNORECASE,
ULPROPTAG => PR_MESSAGE_CLASS,
VALUE => [PR_MESSAGE_CLASS => 'IPM.ExtendedRule.Message'],
],
],
[RES_CONTENT,
[
FUZZYLEVEL => FL_FULLSTRING | FL_IGNORECASE,
ULPROPTAG => PR_RULE_MSG_PROVIDER,
VALUE => [PR_RULE_MSG_PROVIDER => JunkRule::PROVIDER],
],
],
]]);
// Newest first, so a duplicate created by a racing client is shadowed
// deterministically rather than by table order.
mapi_table_sort($table, [PR_LAST_MODIFICATION_TIME => TABLE_SORT_DESCEND], TBL_BATCH);
$rows = mapi_table_queryallrows($table, [PR_ENTRYID]);
if (!empty($rows)) {
return [mapi_msgstore_openentry($store, $rows[0][PR_ENTRYID]), $inbox];
}
return [false, $inbox];
}
/**
* Read the lists and options. Never creates the rule, because a mailbox without
* one simply has empty lists, like a fresh Outlook profile.
*/
public function getJunkSettings() {
$store = $GLOBALS['mapisession']->getDefaultMessageStore();
$lists = self::getSenderLists($store);
$data = [
'props' => [
'safe_senders' => $lists['safe_senders'],
'safe_recipients' => $lists['safe_recipients'],
'blocked_senders' => $lists['blocked_senders'],
'junk_include_contacts' => $lists['junk_include_contacts'],
'migrated_pending' => $lists['migrated_pending'],
],
];
$this->addActionData('list', ['item' => [$data]]);
$GLOBALS['bus']->addData($this->getResponseData());
}
/**
* The parsed lists, cached per request. Entries of the old webapp
* safe_senders_list setting are merged into safe_senders (marked by
* 'migrated_pending') until a verified save retires the setting.
*
* @param resource $store MAPI message store
*
* @return array lists plus options
*/
public static function getSenderLists($store) {
if (isset(self::$cachedLists)) {
return self::$cachedLists;
}
$lists = [
'safe_senders' => [],
'safe_recipients' => [],
'blocked_senders' => [],
'contacts' => [],
'junk_include_contacts' => 0,
'migrated_pending' => false,
];
try {
[$message] = self::findJunkRule($store);
}
catch (MAPIException $e) {
$e->setHandled();
$message = false;
}
if ($message !== false) {
$props = mapi_getprops($message, [PR_EXTENDED_RULE_MSG_CONDITION, PR_JUNK_INCLUDE_CONTACTS]);
$blob = $props[PR_EXTENDED_RULE_MSG_CONDITION] ?? readMapiPropStream($message, PR_EXTENDED_RULE_MSG_CONDITION);
$parsed = is_string($blob) ? JunkRule::parseCondition($blob) : false;
if ($parsed !== false) {
$lists['safe_senders'] = $parsed['safe_senders'];
$lists['safe_recipients'] = $parsed['safe_recipients'];
$lists['blocked_senders'] = $parsed['blocked_senders'];
$lists['contacts'] = $parsed['contacts'];
}
$lists['junk_include_contacts'] = ($props[PR_JUNK_INCLUDE_CONTACTS] ?? 0) ? 1 : 0;
}
JunkSenderList::mergeLegacy($GLOBALS['settings']->get('grommunio/v1/contexts/mail/safe_senders_list'), $lists);
self::$cachedLists = $lists;
return $lists;
}
/**
* Save the lists. Rebuilds the whole condition and actions, verifies the
* write by reading it back, and only then retires the old webapp setting.
*
* @param array $action the action data sent by the client
*/
public function saveJunkSettings($action) {
$props = $action['props'] ?? [];
$safeSenders = $this->sanitizeList($props['safe_senders'] ?? null);
$safeRecipients = $this->sanitizeList($props['safe_recipients'] ?? null);
$blockedSenders = $this->sanitizeList($props['blocked_senders'] ?? null);
if ($safeSenders === false || $safeRecipients === false || $blockedSenders === false) {
throw new GrommunioException(_("The sender lists could not be saved"));
}
$store = $GLOBALS['mapisession']->getDefaultMessageStore();
[$message, $inbox] = self::findJunkRule($store);
// The lists the client did not send keep their stored value.
$current = self::getSenderLists($store);
$explicitSafeSenders = $safeSenders !== null;
$safeSenders ??= $current['safe_senders'];
$safeRecipients ??= $current['safe_recipients'];
$blockedSenders ??= $current['blocked_senders'];
// MS-OXCSPAM v12 §2.2.2.2: The contacts clause must be empty while the
// option is off. Outlook repopulates it when re-enabled.
$includeContacts = isset($props['junk_include_contacts']) ?
(empty($props['junk_include_contacts']) ? 0 : 1) :
$current['junk_include_contacts'];
$condition = JunkRule::buildCondition(
$blockedSenders,
$safeSenders,
$safeRecipients,
$includeContacts ? $current['contacts'] : []
);
$renState = State::forStore('additional-ren-entryids-write');
if (!$renState->open()) {
throw new RuntimeException('Unable to lock additional folder entryids');
}
try {
$actions = JunkRule::buildActions(
$this->getJunkFolderEntryId($inbox),
$this->getMoveStamp($inbox)
);
}
finally {
$renState->close();
}
$writeProps = [
PR_EXTENDED_RULE_MSG_CONDITION => $condition,
PR_EXTENDED_RULE_MSG_ACTIONS => $actions,
// Re-enable on every save. Outlook may have flagged ST_ERROR.
PR_RULE_MSG_STATE => JunkRule::RULE_STATE,
];
if (isset($props['junk_include_contacts'])) {
$writeProps[PR_JUNK_INCLUDE_CONTACTS] = $includeContacts;
}
$created = $message === false;
if ($created) {
$message = mapi_folder_createmessage($inbox, MAPI_ASSOCIATED);
$writeProps += [
PR_MESSAGE_CLASS => 'IPM.ExtendedRule.Message',
PR_RULE_MSG_NAME => JunkRule::RULE_NAME,
PR_SUBJECT => JunkRule::RULE_NAME,
PR_RULE_MSG_PROVIDER => JunkRule::PROVIDER,
PR_RULE_MSG_SEQUENCE => 0,
PR_RULE_MSG_LEVEL => 0,
PR_RULE_MSG_USER_FLAGS => 0,
PR_JUNK_INCLUDE_CONTACTS => $writeProps[PR_JUNK_INCLUDE_CONTACTS] ?? 0,
PR_JUNK_THRESHOLD => -1,
PR_JUNK_PERMANENTLY_DELETE => 0,
PR_JUNK_ADD_RECIPS_TO_SSL => 0,
PR_JUNK_PHISHING_ENABLE_LINKS => false,
PR_REPORT_TIME => time(),
];
}
mapi_setprops($message, $writeProps);
mapi_savechanges($message);
// zcore silently rejects an oversized or non-FAI condition write.
// mapi_setprops still succeeds, so the only proof is reading back.
$check = mapi_getprops($message, [PR_EXTENDED_RULE_MSG_CONDITION]);
$stored = $check[PR_EXTENDED_RULE_MSG_CONDITION] ?? readMapiPropStream($message, PR_EXTENDED_RULE_MSG_CONDITION);
if ($stored !== $condition) {
if ($created) {
// Do not leave an enabled rule without a condition behind.
try {
$eid = mapi_getprops($message, [PR_ENTRYID]);
mapi_folder_deletemessages($inbox, [$eid[PR_ENTRYID]], DELETE_HARD_DELETE);
}
catch (MAPIException $e) {
$e->setHandled();
}
}
throw new GrommunioException(_("The sender lists could not be saved"));
}
$this->retireOldSetting($safeSenders, $explicitSafeSenders);
self::$cachedLists = null;
$this->sendFeedback(true);
}
/**
* @param mixed $list the client-sent list
*
* @return null|array|false null when absent, false when invalid
*/
private function sanitizeList($list) {
if ($list === null) {
return null;
}
if (!is_array($list) || count($list) > self::MAX_ENTRIES) {
return false;
}
$out = [];
$seen = [];
foreach ($list as $entry) {
if (!is_string($entry)) {
return false;
}
$entry = trim($entry);
if ($entry === '') {
continue;
}
if (!JunkSenderList::isSaneEntry($entry)) {
return false;
}
$lower = strtolower($entry);
if (!isset($seen[$lower])) {
$seen[$lower] = true;
$out[] = $entry;
}
}
return $out;
}
/**
* The junk folder entryid is PR_ADDITIONAL_REN_ENTRYIDS index 4 on the inbox.
*
* @param resource $inbox
*
* @return string 46-byte folder entryid
*/
private function getJunkFolderEntryId($inbox) {
$props = mapi_getprops($inbox, [PR_ADDITIONAL_REN_ENTRYIDS]);
$eid = $props[PR_ADDITIONAL_REN_ENTRYIDS][4] ?? '';
if (strlen($eid) !== 46) {
throw new GrommunioException(_("The sender lists could not be saved"));
}
return $eid;
}
/**
* The junk email move stamp is PR_ADDITIONAL_REN_ENTRYIDS index 5 on the
* inbox, generated and stored there when absent (MS-OXCSPAM v12 §3.2.4.1).
*
* @param resource $inbox
*
* @return int
*/
private function getMoveStamp($inbox) {
$props = mapi_getprops($inbox, [PR_ADDITIONAL_REN_ENTRYIDS]);
$entries = $props[PR_ADDITIONAL_REN_ENTRYIDS] ?? [];
if (isset($entries[5]) && strlen((string) $entries[5]) === 4) {
return unpack('V', $entries[5])[1];
}
$stamp = random_int(1, 0x7FFFFFFF);
for ($i = 0; $i <= 5; ++$i) {
$entries[$i] ??= '';
}
$entries[5] = pack('V', $stamp);
ksort($entries);
mapi_setprops($inbox, [PR_ADDITIONAL_REN_ENTRYIDS => array_values($entries)]);
mapi_savechanges($inbox);
return $stamp;
}
/**
* Delete the old webapp setting after a verified save. An explicitly sent
* safe senders list was built from the merged view (the client refuses to
* save before loading), so deletions in it are deliberate. Otherwise, the
* setting is kept until a save covers every remaining entry.
*
* @param array $safeSenders the just-saved safe senders
* @param bool $explicit the client sent the list itself
*/
private function retireOldSetting($safeSenders, $explicit) {
$old = $GLOBALS['settings']->get('grommunio/v1/contexts/mail/safe_senders_list');
if (!is_array($old) || empty($old)) {
return;
}
if (!$explicit && !JunkSenderList::legacyCoveredBy($old, $safeSenders)) {
return;
}
$GLOBALS['settings']->delete('grommunio/v1/contexts/mail/safe_senders_list');
$GLOBALS['settings']->saveSettings();
}
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,474 @@
<?php
/*
* SPDX-FileCopyrightText: Copyright 2020 - 2026 grommunio GmbH
* SPDX-FileCopyrightText: Copyright 2016 Kopano and its licensors
* SPDX-FileCopyrightText: Copyright 2005 - 2016 Zarafa B.V. and its licensors
* SPDX-License-Identifier: AGPL-3.0-or-later
*/
require_once __DIR__ . '/../hexutil.php';
/**
* Mail Module.
*/
class MailListModule extends ListModule {
// Temporary var to store the inbox entryid of the processed store
private $_inboxEntryId;
private $_inbox;
private $_inboxTotal;
private $_inboxTotalUnread;
private $store;
private $currentActionData;
// The server drops a contents table together with its folder handle.
private $sentItemsFolder;
/**
* Constructor.
*
* @param int $id unique id
* @param array $data list of all actions
*/
public function __construct($id, $data) {
parent::__construct($id, $data);
$this->properties = $GLOBALS["properties"]->getMailListProperties();
}
/**
* Checks if the conversation view may be used. The message list itself is not
* affected by this (the client groups the messages by their conversation id),
* this only gates the conversationitems action that fetches the sent items
* belonging to a conversation.
*
* @return bool true if the conversation view may be used, false otherwise
*/
public function useConversationView() {
// ENABLE_CONVERSATION_VIEW acts as an administrative kill-switch.
return
(!defined('ENABLE_CONVERSATION_VIEW') || ENABLE_CONVERSATION_VIEW) &&
$GLOBALS['settings']->get('grommunio/v1/contexts/mail/enable_conversation_view') === true;
}
/**
* Creates the notifiers for this module,
* and register them to the Bus.
*/
public function createNotifiers() {
$entryid = $this->getEntryID();
$GLOBALS["bus"]->registerNotifier('maillistnotifier', $entryid);
}
/**
* Executes all the actions in the $data variable.
*/
#[Override]
public function execute() {
$GLOBALS['PluginManager']->triggerHook("server.module.maillistmodule.execute.before", ['moduleObject' => &$this]);
foreach ($this->data as $actionType => $action) {
if (isset($actionType)) {
try {
$this->store = $this->getActionStore($action);
$entryid = $this->getActionSingleEntryID($action);
if ($this->store === false || is_array($this->store)) {
$this->sendFeedback(false);
continue;
}
// Reset variables
$this->_inbox = null;
$this->_inboxEntryId = null;
$this->_inboxTotal = null;
$this->_inboxTotalUnread = null;
$this->currentActionData = [
'store' => $this->store,
'entryid' => $entryid,
'actionType' => $actionType,
'action' => $action,
];
switch ($actionType) {
case "list":
case "updatelist":
$this->getDelegateFolderInfo($this->store);
$this->messageList($this->store, $entryid, $action, $actionType);
break;
case "search":
// @FIXME add handling for private items
$this->search($this->store, $entryid, $action, $actionType);
break;
case "updatesearch":
$this->updatesearch($this->store, $entryid, $action);
break;
case "stopsearch":
$this->stopSearch($this->store, $entryid, $action);
break;
case "conversationitems":
$this->getDelegateFolderInfo($this->store);
$this->getConversationItems($this->store, $action);
break;
case "conversationcounts":
$this->getDelegateFolderInfo($this->store);
$this->getConversationCounts($this->store, $action);
break;
default:
$this->handleUnknownActionType($actionType);
}
}
catch (MAPIException|SearchException $e) {
$this->processException($e, $actionType);
}
}
}
$GLOBALS['PluginManager']->triggerHook("server.module.maillistmodule.execute.after", ['moduleObject' => &$this]);
}
/**
* Returns the Inbox folder of the currently used store if found, NULL otherwise.
*
* @return resource The inbox folder of the currently used store
*/
public function getInbox() {
if ($this->_inbox === null) {
try {
$this->_inbox = mapi_msgstore_getreceivefolder($this->store);
}
catch (MAPIException $e) {
// don't propagate this error to parent handlers, if store doesn't support it
if ($e->getCode() === MAPI_E_NO_SUPPORT) {
$e->setHandled();
return null;
}
}
}
return $this->_inbox;
}
/**
* Returns the entryid of the Inbox folder of the currently used store if found, false otherwise.
*
* @return false|string hexadecimal Inbox entry ID, or false when unavailable
*/
public function getInboxEntryId() {
if ($this->_inboxEntryId === null) {
$inbox = $this->getInbox();
try {
$inboxProps = mapi_getprops($inbox, [PR_ENTRYID]);
$this->_inboxEntryId = bin2hex((string) $inboxProps[PR_ENTRYID]);
}
catch (MAPIException $e) {
// don't propagate this error to parent handlers, if store doesn't support it
if ($e->getCode() === MAPI_E_NO_SUPPORT) {
$e->setHandled();
return false;
}
}
}
return $this->_inboxEntryId;
}
/**
* Returns the total number of items in the Inbox of the currently used store.
*
* @param mixed $force
*
* @return int the number if items in the Inbox folder
*/
public function getInboxTotal($force = false) {
if ($this->_inboxTotal === null || $force) {
$inbox = $this->getInbox();
$contentcount = mapi_getprops($inbox, [PR_CONTENT_COUNT, PR_CONTENT_UNREAD]);
$this->_inboxTotal = $contentcount[PR_CONTENT_COUNT];
$this->_inboxTotalUnread = $contentcount[PR_CONTENT_UNREAD];
}
return $this->_inboxTotal;
}
/**
* Returns the number of unread items in the Inbox of the currently used store.
*
* @param mixed $force
*
* @return int the number of unread items in the Inbox folder
*/
public function getInboxTotalUnread($force = false) {
if ($this->_inboxTotalUnread === null || $force) {
$this->getInboxTotal($force);
}
return $this->_inboxTotalUnread;
}
/**
* Opens the contents table of the Sent Items folder of the given store, or
* returns false when it is not available. Public stores do not have that
* folder. Shared mailboxes can withhold access, where the refusal surfaces
* at the folder or at its table, depending on the rights granted. In any
* case, these conditions must not turn into an error for the whole request.
*
* @param resource $store MAPI message store
*
* @return false|resource Sent Items contents table, or false when unavailable
*/
protected function openSentItemsTable($store) {
$msgstoreProps = mapi_getprops($store, [PR_IPM_SENTMAIL_ENTRYID]);
if (!isset($msgstoreProps[PR_IPM_SENTMAIL_ENTRYID])) {
return false;
}
try {
$this->sentItemsFolder = mapi_msgstore_openentry($store, $msgstoreProps[PR_IPM_SENTMAIL_ENTRYID]);
return mapi_folder_getcontentstable($this->sentItemsFolder, MAPI_DEFERRED_ERRORS);
}
catch (MAPIException $e) {
$e->setHandled();
}
return false;
}
/**
* Returns, for the given list of conversation ids, how many messages of each
* conversation are in the Sent Items folder. The client uses this to know
* which messages must be presented as a conversation even though only one
* of them is in the Inbox (a mail that was replied to).
*
* @param resource $store MAPI message store
* @param array $action the action data, sent by the client
*/
public function getConversationCounts($store, $action) {
$counts = [];
$ids = $action['conversation_ids'] ?? [];
if ($this->useConversationView() && is_array($ids) && !empty($ids)) {
$validIds = [];
foreach ($ids as $id) {
if (is_hex_string($id)) {
$validIds[] = $id;
// The client asks per loaded page; cap the restriction size.
if (count($validIds) >= 500) {
break;
}
}
}
$table = empty($validIds) ? false : $this->openSentItemsTable($store);
if ($table !== false) {
$subRestrictions = [];
foreach ($validIds as $id) {
$subRestrictions[] = [
RES_PROPERTY,
[
RELOP => RELOP_EQ,
ULPROPTAG => PR_CONVERSATION_ID,
VALUE => [PR_CONVERSATION_ID => hex2bin($id)],
],
];
}
mapi_table_restrict($table, [RES_OR, $subRestrictions], TBL_BATCH);
$rows = mapi_table_queryallrows($table, [PR_CONVERSATION_ID, PR_SENSITIVITY]);
foreach ($rows as $row) {
if (!isset($row[PR_CONVERSATION_ID])) {
continue;
}
// getConversationItems() removes private items from the
// conversation, so they must not be counted here either.
// The count is what the conversation header announces.
$props = [];
if (isset($row[PR_SENSITIVITY])) {
$props['sensitivity'] = $row[PR_SENSITIVITY];
}
if ($this->checkPrivateItem(['props' => $props])) {
continue;
}
$id = bin2hex((string) $row[PR_CONVERSATION_ID]);
$counts[$id] = ($counts[$id] ?? 0) + 1;
}
}
}
$this->addActionData('conversationcounts', [
// Force an object so an empty result is {} instead of [].
'counts' => empty($counts) ? new stdClass() : $counts,
]);
$GLOBALS['bus']->addData($this->getResponseData());
}
/**
* Returns the messages from the Sent Items folder that belong to the given
* conversation, identified by its PR_CONVERSATION_ID. The inbox part of a
* conversation is already available to the client through the normal message
* list; this action supplies the sent counterparts when the user expands a
* conversation.
*
* @param resource $store MAPI message store
* @param array $action the action data, sent by the client
*/
public function getConversationItems($store, $action) {
$data = ['item' => []];
$conversationId = $action['conversation_id'] ?? '';
$data['conversation_id'] = $conversationId;
if ($this->useConversationView() && is_hex_string($conversationId)) {
$restriction = [
RES_PROPERTY,
[
RELOP => RELOP_EQ,
ULPROPTAG => PR_CONVERSATION_ID,
VALUE => [PR_CONVERSATION_ID => hex2bin($conversationId)],
],
];
$tables = [];
$sentTable = $this->openSentItemsTable($store);
if ($sentTable !== false) {
$tables['sent_items'] = $sentTable;
}
// The mail list already contains the inbox part of a conversation,
// but callers without that context (e.g. the search results
// preview) need the complete conversation.
if (!empty($action['include_inbox'])) {
try {
$inbox = mapi_msgstore_getreceivefolder($store);
$tables['inbox'] = mapi_folder_getcontentstable($inbox, MAPI_DEFERRED_ERRORS);
}
catch (MAPIException $e) {
$e->setHandled();
}
}
foreach ($tables as $folderName => $table) {
mapi_table_restrict($table, $restriction, TBL_BATCH);
$rows = mapi_table_queryallrows($table, $this->properties);
foreach ($rows as $row) {
$item = Conversion::mapMAPI2XML($this->properties, $row);
$item['props']['folder_name'] = $folderName;
$data['item'][] = $item;
}
}
// Newest first, like the conversation items in the mail list.
usort($data['item'], function ($a, $b) {
$dateA = $a['props']['message_delivery_time'] ?? $a['props']['client_submit_time'] ?? 0;
$dateB = $b['props']['message_delivery_time'] ?? $b['props']['client_submit_time'] ?? 0;
return $dateB <=> $dateA;
});
$data = $this->filterPrivateItems($data);
$data['item'] = array_values($data['item']);
}
$this->addActionData('conversationitems', $data);
$GLOBALS['bus']->addData($this->getResponseData());
}
/**
* Function does customization of exception based on module data.
* like, here it will generate display message based on actionType
* for particular exception.
*
* @param object $e Exception object
* @param string $actionType the action type, sent by the client
* @param resource $store current user's MAPI store
* @param string $parententryid parent entryid of the message
* @param string $entryid entryid of the message
* @param array $action the action data, sent by the client
*/
#[Override]
public function handleException(&$e, $actionType = null, $store = null, $parententryid = null, $entryid = null, $action = null) {
if (is_null($e->displayMessage)) {
switch ($actionType) {
case "list":
if ($e->getCode() == MAPI_E_NO_ACCESS) {
$e->setDisplayMessage(_("You have insufficient privileges to see the contents of this folder."));
}
else {
$e->setDisplayMessage(_("Could not load the contents of this folder."));
}
break;
case "search":
if ($e->getCode() == MAPI_E_NO_ACCESS) {
$e->setDisplayMessage(_("You have insufficient privileges to perform search operation in this folder."));
}
else {
$e->setDisplayMessage(_("Error in search, please try again."));
}
break;
case "updatesearch":
$e->setDisplayMessage(_("Could not update search results."));
break;
case "stopsearch":
$e->setDisplayMessage(_("Could not stop search operation."));
break;
}
}
parent::handleException($e, $actionType, $store, $parententryid, $entryid, $action);
}
/**
* Parses the incoming sort request and builds a MAPI sort order.
* Overridden to rewrite the sorting for flags. (because the flags that are shown in grommunio Web
* are a combination of several properties).
*
* @param array $action action data sent by the client
* @param array|false $map optional property mapping
* @param bool $allow_multi_instance whether to sort each multi-value instance as a separate row
* @param array|false $properties custom properties, or false to use the module properties
*/
#[Override]
public function parseSortOrder($action, $map = false, $allow_multi_instance = false, $properties = false) {
if (isset($action['sort'])) {
// Check if the user wants to sort the maillist on flags.
// If so, we will rewrite the sorting a little
if (is_array($action['sort']) && count($action['sort']) > 0 && $action['sort'][0]['field'] === 'flag_due_by') {
$dir = $action['sort'][0]['direction'];
$action['sort'] = [
[
'field' => 'flag_status',
'direction' => $dir,
],
[
'field' => 'duedate',
'direction' => $dir === 'ASC' ? 'DESC' : 'ASC',
],
[
'field' => 'flag_due_by',
'direction' => $dir,
],
];
}
}
parent::parseSortOrder($action, $map, $allow_multi_instance, $properties);
}
}
@@ -0,0 +1,641 @@
<?php
/*
* SPDX-FileCopyrightText: Copyright 2020 - 2026 grommunio GmbH
* SPDX-FileCopyrightText: Copyright 2016 Kopano and its licensors
* SPDX-FileCopyrightText: Copyright 2005 - 2016 Zarafa B.V. and its licensors
* SPDX-License-Identifier: AGPL-3.0-or-later
*/
require_once __DIR__ . '/../exceptions/class.SearchException.php';
/**
* Module
* Superclass of every module. Many default functions are defined in this class.
*/
class Module {
/**
* @var string entryid, which will be registered by the bus object
*/
public $entryid;
/**
* @var array list of the results, which is send to the client
*/
public $responseData;
/**
* @var array list of all the errors occurred
*/
public $errors;
/**
* @var false|State The state object which refers to the statefile
*/
public $sessionState;
/**
* @var mixed data stored in session for this module
*/
public $sessionData;
/**
* @var array list of the properties necessary for the module
*/
public $properties;
/**
* @var array list of the folder list properties
*/
public $list_properties;
/**
* @var bool whether the session state is shared
*/
public $_sharedSessionState;
/**
* @var false|State per-module execution lock
*/
private $sessionExecutionLock = false;
/**
* @var null|string serialized module state loaded before execution
*/
private $sessionDataSnapshot;
/**
* Constructor.
*
* @param int $id unique id
* @param array $data list of all actions
*/
public function __construct(public $id, public $data) {
$this->errors = [];
$this->responseData = [];
$this->sessionState = false;
$this->sessionData = false;
$this->_sharedSessionState = false;
$this->sessionDataSnapshot = null;
$this->createNotifiers();
// Get the store from $data and set it to properties class.
// It is requires for multi server environment where namespace differs.
// e.g. 'categories' => -2062020578, 'categories' => -2062610402,
if (isset($GLOBALS['properties'])) {
$GLOBALS['properties']->setStore($this->getActionStore($this->getActionData($this->data)));
}
}
/**
* Creates the notifiers for this module,
* and register them to the Bus.
*/
public function createNotifiers() {}
/**
* Executes all the actions in the $data variable.
*/
public function execute() {
// you must implement this function for each module
}
/**
* This will call $handleException of updating the MAPIException based in the module data.
* When this is done, $sendFeedback will be called to send the message to the client.
*
* @param object $e exception object
* @param null|string $actionType the action type, sent by the client
* @param null|array|false|resource $store MAPI store or stores
* @param null|false|string $parententryid parent entryid of the message
* @param null|false|string $entryid entryid of the message/folder
* @param null|array $action the action data, sent by the client
*/
public function processException(&$e, $actionType = null, $store = null, $parententryid = null, $entryid = null, $action = null) {
$this->handleException($e, $actionType, $store, $parententryid, $entryid, $action);
$this->sendFeedback(false, $this->errorDetailsFromException($e));
}
/**
* Function does customization of MAPIException based on module data.
* like, here it will generate display message based on actionType
* for particular exception.
*
* @param object $e exception object
* @param string $actionType the action type, sent by the client
* @param resource $store MAPI store containing the message
* @param string $parententryid parent entryid of the message
* @param string $entryid entryid of the message/folder
* @param array $action the action data, sent by the client
*/
public function handleException(&$e, $actionType = null, $store = null, $parententryid = null, $entryid = null, $action = null) {
if (is_null($e->displayMessage)) {
switch ($actionType) {
case "save":
if ($e->getCode() == MAPI_E_NO_ACCESS) {
$e->setDisplayMessage(_("You have insufficient privileges to save this message."));
}
else {
$e->setDisplayMessage(_("Could not save message."));
}
$e->allowToShowDetailsMessage = true;
break;
case "delete":
if ($e->getCode() == MAPI_E_NO_ACCESS) {
$e->setDisplayMessage(_("You have insufficient privileges to delete this message."));
}
else {
$e->setDisplayMessage(_("Could not delete message."));
}
break;
case "cancelMeetingRequest":
if ($e->getCode() == MAPI_E_NO_ACCESS) {
$e->setDisplayMessage(_("You have insufficient privileges to cancel this Meeting Request."));
}
else {
$e->setDisplayMessage(_("Could not cancel Meeting Request."));
}
break;
case "declineMeetingRequest":
if ($e->getCode() == MAPI_E_NO_ACCESS) {
$e->setDisplayMessage(_("You have insufficient privileges to decline this Meeting Request."));
}
else {
$e->setDisplayMessage(_("Could not decline Meeting Request."));
}
break;
case "acceptMeetingRequest":
if ($e->getCode() == MAPI_E_NO_ACCESS) {
$e->setDisplayMessage(_("You have insufficient privileges to accept this Meeting Request."));
}
else {
$e->setDisplayMessage(_("Could not accept Meeting Request."));
}
break;
case "cancelInvitation":
if ($e->getCode() == MAPI_E_NO_ACCESS) {
$e->setDisplayMessage(_("You have insufficient privileges to cancel Meeting Request invitation."));
}
else {
$e->setDisplayMessage(_("Could not cancel Meeting Request invitations."));
}
break;
case "updatesearch":
case "stopsearch":
case "search":
if ($e->getCode() == MAPI_E_NOT_INITIALIZED) {
$e->setDisplayMessage(_("You can not continue search operation on this folder."));
}
else {
$e->setDisplayMessage(_("Error in search, please try again."));
}
break;
case "expand":
$e->setDisplayMessage(_("Error in distribution list expansion."));
break;
}
Log::Write(
LOGLEVEL_ERROR,
"Module::handleException():" . $actionType . ": " . $e->displayMessage
);
}
}
/**
* Get quota information of user store and check for over qouta restrictions,
* if any qouta (softquota/hardquota) limit is exceeded then it will simply
* return appropriate message string according to quota type(hardquota/softquota).
*
* @param mixed $store Store object of the store
*
* @return string short message according to quota type(hardquota/softquota) or a blank string
*/
public function getOverQuotaMessage($store) {
if ($store === false) {
$store = $GLOBALS['mapisession']->getDefaultMessageStore();
}
$storeProps = mapi_getprops($store, [PR_QUOTA_WARNING_THRESHOLD, PR_QUOTA_SEND_THRESHOLD, PR_QUOTA_RECEIVE_THRESHOLD, PR_MESSAGE_SIZE_EXTENDED]);
$quotaDetails = [
'store_size' => round($storeProps[PR_MESSAGE_SIZE_EXTENDED] / 1024),
'quota_warning' => $storeProps[PR_QUOTA_WARNING_THRESHOLD],
'quota_soft' => $storeProps[PR_QUOTA_SEND_THRESHOLD],
'quota_hard' => $storeProps[PR_QUOTA_RECEIVE_THRESHOLD],
];
if ($quotaDetails['quota_hard'] !== 0 && $quotaDetails['store_size'] > $quotaDetails['quota_hard']) {
return _('The message store has exceeded its hard quota limit.') . '<br/>' .
_('To reduce the amount of data in this message store, select some items that you no longer need, delete them and cleanup your Deleted Items folder.');
}
// if hard quota limit doesn't restrict the operation then check for soft qouta limit
if ($quotaDetails['quota_soft'] !== 0 && $quotaDetails['store_size'] > $quotaDetails['quota_soft']) {
return _('The message store has exceeded its soft quota limit.') . '<br/> ' .
_('To reduce the amount of data in this message store, select some items that you no longer need, delete them and cleanup your Deleted Items folder.');
}
return '';
}
/**
* sends a success or error message to client based on parameters passed.
*
* @param bool $success operation completed successfully or not
* @param array $data the data array that will be send to the client as a response to success/failure
* @param bool $addResponseDataToBus if true then data will be added to bus otherwise data
* will be stored in module and later requests can add it to bus
*/
public function sendFeedback($success = false, $data = [], $addResponseDataToBus = true) {
// Send success/error message to client
$this->addActionData($success === true ? "success" : "error", $data);
if ($addResponseDataToBus) {
$GLOBALS["bus"]->addData($this->getResponseData());
}
}
/**
* Function will retrieve error details from exception object based on exception type.
* it should also send type of exception with the data. so client can know which type
* of exception is generated.
*
* @param object $exception the exception object which is generated
*
* @return array error data
*/
public function errorDetailsFromException($exception) {
if (!$exception->isHandled) {
if ($exception instanceof MAPIException) {
$exception->setHandled();
return [
"type" => ERROR_MAPI,
"info" => [
"hresult" => $exception->getCode(),
"title" => $exception->getTitle(),
"hresult_name" => get_mapi_error_name($exception->getCode()),
"file" => $exception->getFileLine(),
"display_message" => $exception->getDisplayMessage(),
"details_message" => $exception->getDetailsMessage(),
],
];
}
if ($exception instanceof GrommunioException) {
$exception->setHandled();
return [
"type" => ERROR_GROMMUNIO,
"info" => [
"file" => $exception->getFileLine(),
"title" => $exception->getTitle(),
"display_message" => $exception->getDisplayMessage(),
"original_message" => $exception->getMessage(),
],
];
}
}
return [];
}
/**
* Function which returns an entryid, which is used to register this module. It
* searches in the class variable $data for a ParentEntryID or an EntryID.
*
* @return string an entryid if found, false if entryid not found
*/
public function getEntryID() {
$entryid = false;
foreach ($this->data as $action) {
if (isset($action["parent_entryid"]) && !empty($action["parent_entryid"])) {
$entryid = $action["parent_entryid"];
}
elseif (isset($action["entryid"]) && !empty($action["entryid"])) {
$entryid = $action["entryid"];
}
}
return $entryid;
}
/**
* Returns all the errors, which occurred.
*
* @return array an array of all the errors, which occurred
*/
public function getErrors() {
return $this->errors;
}
/**
* Returns the response data.
*
* @return array An array of the response data. This data is send to the client.
*/
public function getData() {
return $this->responseData;
}
/**
* Sets the action data, which will be executed.
*
* @param array $data array of all the actions
*/
public function setData($data) {
$this->data = $data;
}
/**
* Function which returns MAPI Message Store Object. It
* searches in the variable $action for a storeid.
*
* @param array|false $action XML action data, or false when none is present
*
* @return array<int, false|resource>|false|resource MAPI store or stores, or false when no store ID is present
*/
public function getActionStore($action) {
$store = false;
try {
if (isset($action["store_entryid"]) && !empty($action["store_entryid"])) {
if (is_array($action["store_entryid"])) {
$store = [];
foreach ($action["store_entryid"] as $store_id) {
array_push($store, $GLOBALS["mapisession"]->openMessageStore(hex2bin((string) $store_id)));
}
}
elseif (ctype_xdigit((string) $action["store_entryid"])) {
$store = $GLOBALS["mapisession"]->openMessageStore(hex2bin((string) $action["store_entryid"]));
}
}
}
catch (Exception) {
return false;
}
return $store;
}
/**
* Function which returns a parent entryid. It
* searches in the variable $action for a parententryid.
*
* @param array $action the XML data retrieved from the client
*
* @return false|string binary parent entry ID, or false when it is not present
*/
public function getActionParentEntryID($action) {
$parententryid = false;
if (isset($action["parent_entryid"]) && !empty($action["parent_entryid"])) {
$parententryid = hex2bin((string) $action["parent_entryid"]);
}
return $parententryid;
}
/**
* Function which returns an entryid. It
* searches in the variable $action for an entryid.
*
* @param array $action the XML data retrieved from the client
*
* @return array<int, false|string>|false|string binary folder entry ID or IDs, or false when absent or invalid
*/
public function getActionEntryID($action) {
$entryid = false;
if (isset($action["entryid"]) && !empty($action["entryid"])) {
if (is_array($action["entryid"])) {
$entryid = [];
foreach ($action["entryid"] as $action_entryid) {
array_push($entryid, hex2bin((string) $action_entryid));
}
}
else {
$entryid = hex2bin((string) $action["entryid"]);
}
}
return $entryid;
}
/**
* Return the single entry ID expected by scalar actions.
*
* Calendar list requests may address several stores and therefore use
* getActionEntryID() directly. Other actions accept one item or folder and
* reject an array instead of passing it to scalar MAPI calls.
*
* @param array $action the XML data retrieved from the client
*
* @return false|string binary entry ID, or false when absent, invalid, or multiple
*/
protected function getActionSingleEntryID($action) {
$entryid = $this->getActionEntryID($action);
return is_string($entryid) ? $entryid : false;
}
/**
* Helper function which used to get the action data from request.
*
* @param array $data list of all actions
*
* @return array|false JSON action data, or false when no action is present
*/
public function getActionData($data) {
$actionData = false;
foreach ($data as $actionType => $action) {
if (isset($actionType)) {
$actionData = $action;
}
}
return $actionData;
}
/**
* Function which adds action data to module, so later it can be retrieved to send.
*
* @param string $actionType type of action that response data corresponds
* @param mixed $data
*/
public function addActionData($actionType, $data) {
if (!isset($this->responseData[$actionType])) {
$this->responseData[$actionType] = $data;
}
}
/**
* Function which returns response data that will be sent to client. If there isn't any data added
* to response data then it will return a blank array.
*
* @return array response data
*/
public function getResponseData() {
if (!empty($this->responseData)) {
return
[
$this->getModuleName() => [
$this->id => $this->responseData,
],
];
}
return [];
}
/**
* Function which returns name of the module class.
*
* @return string module name
*/
public function getModuleName() {
return strtolower(static::class);
}
/**
* Resource group whose requests must execute serially, null to run unlocked.
*/
protected function getExecutionLockName() {
return $this->getModuleName();
}
/**
* Initialize resources that need the module execution lock.
*/
protected function afterLoadSessionData() {}
/**
* Function which will handle unknown action type for all modules.
*
* @param string $actionType action type
*/
public function handleUnknownActionType($actionType) {
$this->sendFeedback(
false,
[
"type" => ERROR_GROMMUNIO,
"info" => [
"display_message" => _("Could not process request data properly."),
"original_message" => sprintf(_("Unknown action type specified - %s"), $actionType),
],
]
);
Log::Write(
LOGLEVEL_ERROR,
"Module::handleUnknownActionType(): ERROR_GROMMUNIO : " . _("Could not process request data properly.")
);
}
/**
* Loads sessiondata of the module from state file on disk.
*
* @param State $sharedState optional shared State object so that
* multiple modules can reuse a single lock
* and avoid repeated open/serialize/close cycles
*/
public function loadSessionData($sharedState = null) {
if ($sharedState) {
$this->sessionState = $sharedState;
$this->_sharedSessionState = true;
$this->sessionData = $this->sessionState->read($this->getModuleName());
$this->sessionDataSnapshot = serialize($this->sessionData);
$this->afterLoadSessionData();
return;
}
$moduleName = $this->getModuleName();
$lockName = $this->getExecutionLockName();
if ($lockName === null) {
$this->sessionData = null;
$this->sessionDataSnapshot = serialize(null);
$this->afterLoadSessionData();
return;
}
$this->sessionExecutionLock = new State('module-lock-' . hash('sha256', $lockName));
if (!$this->sessionExecutionLock->open()) {
throw new RuntimeException('Unable to lock module session state');
}
$this->sessionState = new State('module_sessiondata');
if (!$this->sessionState->open()) {
throw new RuntimeException('Unable to read module session state');
}
try {
$this->sessionData = $this->sessionState->read($moduleName);
$this->sessionDataSnapshot = serialize($this->sessionData);
}
finally {
$this->sessionState->close();
}
$this->afterLoadSessionData();
}
/**
* Saves sessiondata of the module to the state file on disk.
*/
public function saveSessionData() {
if ($this->_sharedSessionState) {
if ($this->sessionData !== false) {
$this->sessionState->write($this->getModuleName(), $this->sessionData, false);
}
return;
}
if ($this->sessionData !== false) {
$sessionData = serialize($this->sessionData);
if ($sessionData === $this->sessionDataSnapshot) {
return;
}
$moduleName = $this->getModuleName();
$this->sessionState = new State('module_sessiondata');
if (!$this->sessionState->open()) {
error_log('Unable to save module session state: ' . $moduleName);
return;
}
try {
$currentSessionData = $this->sessionState->read($moduleName);
if ($this->sessionDataSnapshot !== null && serialize($currentSessionData) !== $this->sessionDataSnapshot) {
error_log('Module session state changed without its execution lock: ' . $moduleName);
$this->sessionData = $currentSessionData;
$this->sessionDataSnapshot = serialize($currentSessionData);
return;
}
$this->sessionState->write($moduleName, $this->sessionData);
$this->sessionDataSnapshot = $sessionData;
}
finally {
$this->sessionState->close();
}
}
}
/**
* Release this module's execution lock.
*/
public function closeSessionData() {
if (!$this->_sharedSessionState && $this->sessionExecutionLock instanceof State) {
$this->sessionExecutionLock->close();
$this->sessionExecutionLock = false;
}
}
}
@@ -0,0 +1,201 @@
<?php
/*
* SPDX-FileCopyrightText: Copyright 2020 - 2026 grommunio GmbH
* SPDX-License-Identifier: AGPL-3.0-or-later
*/
/**
* OutOfOfficeSettingsModule Module.
*/
class OutOfOfficeSettingsModule extends Module {
/**
* Constructor.
*
* @param int $id unique id
* @param array $data list of all actions
*/
public function __construct($id, $data) {
parent::__construct($id, $data);
$this->properties = $GLOBALS["properties"]->getOutOfOfficeProperties();
}
/**
* Executes all the actions in the $data variable.
*/
#[Override]
public function execute() {
foreach ($this->data as $actionType => $action) {
if (isset($actionType)) {
try {
switch ($actionType) {
case "list":
$this->getOofSettings();
break;
case "save":
$this->saveOofSettings($action);
break;
default:
$this->handleUnknownActionType($actionType);
}
}
catch (MAPIException|SettingsException $e) {
$this->processException($e, $actionType);
}
}
}
}
/**
* Read 'out of office' settings from PR_EC_OUTOFOFFICE_*.
*
* Internal function to retrieve the 'out of office' settings from the store, these settings are normal properties on the store
*/
public function getOofSettings() {
$otherStores = $this->getOwnerPermissionStores();
array_unshift($otherStores, $GLOBALS['mapisession']->getDefaultMessageStore());
$oofSettings = [];
foreach ($otherStores as $storeEntryId => $storeObj) {
$externalProps = ['props' => []];
$props = mapi_getprops($storeObj, $this->properties);
if (!isset($props[PR_EC_OUTOFOFFICE])) {
$props[PR_EC_OUTOFOFFICE] = false;
}
if (!isset($props[PR_EC_OUTOFOFFICE_MSG])) {
$props[PR_EC_OUTOFOFFICE_MSG] = '';
}
if (!isset($props[PR_EC_OUTOFOFFICE_SUBJECT])) {
$props[PR_EC_OUTOFOFFICE_SUBJECT] = '';
}
if (!isset($props[PR_EC_OUTOFOFFICE_FROM])) {
$props[PR_EC_OUTOFOFFICE_FROM] = 0;
}
if (!isset($props[PR_EC_OUTOFOFFICE_UNTIL]) || $props[PR_EC_OUTOFOFFICE_UNTIL] === FUTURE_ENDDATE) {
$props[PR_EC_OUTOFOFFICE_UNTIL] = 0;
}
if (!isset($props[PR_EC_ALLOW_EXTERNAL])) {
$props[PR_EC_ALLOW_EXTERNAL] = 0;
}
if (!isset($props[PR_EC_EXTERNAL_AUDIENCE])) {
$props[PR_EC_EXTERNAL_AUDIENCE] = 0;
}
if (!isset($props[PR_EC_EXTERNAL_REPLY])) {
$props[PR_EC_EXTERNAL_REPLY] = '';
}
if (!isset($props[PR_EC_EXTERNAL_SUBJECT])) {
$props[PR_EC_EXTERNAL_SUBJECT] = '';
}
$externalProps['props']['entryid'] = bin2hex((string) $props[PR_MAILBOX_OWNER_ENTRYID]);
$externalProps['props']['store_entryid'] = bin2hex((string) $props[PR_ENTRYID]);
$externalProps['props']['set'] = $props[PR_EC_OUTOFOFFICE];
$externalProps['props']['internal_reply'] = trim((string) $props[PR_EC_OUTOFOFFICE_MSG]);
$externalProps['props']['internal_subject'] = trim((string) $props[PR_EC_OUTOFOFFICE_SUBJECT]);
$externalProps['props']['from'] = $props[PR_EC_OUTOFOFFICE_FROM];
$externalProps['props']['until'] = $props[PR_EC_OUTOFOFFICE_UNTIL];
$externalProps['props']['allow_external'] = $props[PR_EC_ALLOW_EXTERNAL];
$externalProps['props']['external_audience'] = $props[PR_EC_EXTERNAL_AUDIENCE];
$externalProps['props']['external_reply'] = trim((string) $props[PR_EC_EXTERNAL_REPLY]);
$externalProps['props']['external_subject'] = trim((string) $props[PR_EC_EXTERNAL_SUBJECT]);
array_push($oofSettings, $externalProps);
}
// Send success message to client
$this->addActionData('list', ['item' => $oofSettings]);
$GLOBALS["bus"]->addData($this->getResponseData());
}
/**
* Function returns array of user stores who has given 'Owner' permission to logged in user.
* Internal function to retrieve the shared stores with 'owner' permission.
*
* @return array array of user stores who has given 'owner' permission
*/
public function getOwnerPermissionStores() {
$stores = $GLOBALS['mapisession']->getOtherUserStore();
// $sharedOwnerStores array will contains store of users who has given 'owner' permission.
// Or store of users which can be fully accessible by default user in case of 'Admin User'.
$sharedOwnerStores = [];
foreach ($stores as $storeEntryId => $storeObj) {
try {
$subTree = mapi_getprops($storeObj, [PR_IPM_SUBTREE_ENTRYID]);
$subtreeObj = mapi_msgstore_openentry($storeObj, $subTree[PR_IPM_SUBTREE_ENTRYID]);
}
catch (MAPIException $e) {
// Skip stores that are inaccessible or where we
// don't have rights to open the folder.
$e->setHandled();
continue;
}
$permission = mapi_getprops($subtreeObj, [PR_RIGHTS]);
$hasSufficientPermission = $permission[PR_RIGHTS] & ecRightsSecretary === ecRightsSecretary;
// If User store's IPM subtree has rights higher than 'secretary' then include that User's store.
if ($hasSufficientPermission) {
$sharedOwnerStores[$storeEntryId] = $storeObj;
}
}
return $sharedOwnerStores;
}
/**
* Internal function to save the 'out of office' settings to the correct properties on the store.
* On success function will send 'success' feedback to user.
*
* Writes some properties to the PR_EC_OUTOFOFFICE_* properties
*
* @param array $action the action data, sent by the client
*/
public function saveOofSettings($action) {
$storeEntryId = $action['store_entryid'];
$oofSettings = $action['props'];
$store = $GLOBALS['mapisession']->openMessageStore(hex2bin((string) $storeEntryId));
$props = Conversion::mapXML2MAPI($this->properties, $oofSettings);
$oofProps = mapi_getprops($store, [PR_EC_OUTOFOFFICE, PR_EC_OUTOFOFFICE_FROM, PR_EC_OUTOFOFFICE_UNTIL]);
// If client sent until value as 0 or User set OOF to true but don't set until
// then save FUTURE_ENDDATE as until date. Also when OOF is already ON and User
// don't change 'until' field then check if 'until' value is available in User's store
// and if not then set until date to FUTURE_ENDDATE.
// Note: If we remove PR_EC_OUTOFOFFICE_UNTIL property from User's store,
// then gromox is setting past value "1970-01-01 00:00:00" as until date.
// To avoid this issue and for OOF to work as expected, we are setting until date as FUTURE_ENDDATE.
if (isset($oofSettings['until']) && $oofSettings['until'] === 0 ||
!isset($oofSettings['until']) && isset($oofSettings['set']) ||
(!isset($oofSettings['until'], $oofSettings['set']) &&
(!isset($oofProps[PR_EC_OUTOFOFFICE_UNTIL]) || $oofProps[PR_EC_OUTOFOFFICE_UNTIL] === 0))) {
$props[$this->properties['until']] = FUTURE_ENDDATE;
}
// Check if the OOF is set for the future
$oofSet = (isset($oofSettings['set']) && $oofSettings['set']) || (!isset($oofSettings['set']) && $oofProps[PR_EC_OUTOFOFFICE]);
if ($oofSet && isset($oofSettings['from']) && intval($oofSettings['from']) > time()) {
$props[$this->properties['set']] = 2;
}
// A subject of nothing but spaces counts as none. Gromox then titles
// the reply from the incoming subject like Exchange does.
foreach (['internal_subject', 'external_subject'] as $subject) {
$tag = $this->properties[$subject];
if (array_key_exists($tag, $props)) {
$props[$tag] = trim((string) $props[$tag]);
}
}
if (!empty($props)) {
mapi_setprops($store, $props);
mapi_savechanges($store);
}
$this->sendFeedback(true);
}
}
@@ -0,0 +1,277 @@
<?php
/*
* SPDX-FileCopyrightText: Copyright 2020 - 2026 grommunio GmbH
* SPDX-FileCopyrightText: Copyright 2016 Kopano and its licensors
* SPDX-FileCopyrightText: Copyright 2005 - 2016 Zarafa B.V. and its licensors
* SPDX-License-Identifier: AGPL-3.0-or-later
*/
/**
* Reminder ItemModule
* Module which saves an item and it
* extends the CreateMailItemModule class.
*/
class ReminderItemModule extends ItemModule {
/**
* Constructor.
*
* @param int $id unique id
* @param array $data list of all actions
*/
public function __construct($id, $data) {
parent::__construct($id, $data);
}
/**
* Set message flags for a flagged mail item.
*
* @param false|resource $store MAPI message store, or false when unavailable
* @param false|string $parententryid binary parent entry ID, or false when absent
* @param array|false|string $entryid binary message entry ID or IDs, or false when absent
* @param array $action the action data, sent by the client
* @param string $actionType the action type which triggered this action
*/
#[Override]
public function save($store, $parententryid, $entryid, $action, $actionType = 'save') {
$this->properties = $GLOBALS['properties']->getMailProperties();
$result = false;
if ($store === false) {
$store = $GLOBALS['mapisession']->getDefaultMessageStore();
}
if ($store !== false) {
// Reference to an array which will be filled with PR_ENTRYID, PR_STORE_ENTRYID and PR_PARENT_ENTRYID of the message
$messageProps = [];
// Set message flags
if (isset($action['props'], $action['props']['message_flags']) && $entryid) {
$msg_action = $action['message_action'] ?? false;
$result = $GLOBALS['operations']->setMessageFlag($store, $entryid, $action['props']['message_flags'], $msg_action, $messageProps);
}
// Feedback for successful save
if ($result) {
$GLOBALS['bus']->notify(bin2hex($messageProps[PR_PARENT_ENTRYID]), TABLE_SAVE, $messageProps);
}
$this->sendFeedback($result ? true : false, [], true);
}
}
/**
* Dismiss or snooze a reminder item.
*
* @param false|resource $store MAPI message store, or false when unavailable
* @param false|string $parententryid binary parent entry ID, or false when absent
* @param array|false|string $entryid binary message entry ID or IDs, or false when absent
* @param array $action the action data, sent by the client
*/
#[Override]
public function delete($store, $parententryid, $entryid, $action) {
$this->properties = $GLOBALS["properties"]->getReminderProperties();
if ($store === false) {
$store = $GLOBALS["mapisession"]->getDefaultMessageStore();
}
$subActionType = false;
if (isset($action["message_action"], $action["message_action"]["action_type"])) {
$subActionType = $action["message_action"]["action_type"];
}
switch ($subActionType) {
case "snooze":
$entryid = $this->getActionSingleEntryID($action);
$this->snoozeItem($store, $entryid, $action);
break;
case "dismiss":
$entryid = $this->getActionSingleEntryID($action);
$this->dismissItem($store, $entryid);
break;
default:
$this->handleUnknownActionType($subActionType);
}
}
/**
* Snooze a reminder for the requested time.
*
* @param false|resource $store MAPI message store, or false when unavailable
* @param false|string $entryid entryid of the message, or false when absent
* @param array $action the action data, sent by the client
*/
public function snoozeItem($store, $entryid, $action) {
if ($store === false || !is_string($entryid) || $entryid === '') {
$this->sendFeedback(false);
return;
}
$result = false;
$message = mapi_msgstore_openentry($store, $entryid);
if ($message) {
$newProps = [PR_ENTRYID => $entryid];
$props = mapi_getprops($message, $this->properties);
$snoozeTime = $GLOBALS["settings"]->get('grommunio/v1/main/reminder/default_snooze_time', 5);
if (isset($action["message_action"]["snoozeTime"]) && is_numeric($action["message_action"]["snoozeTime"])) {
$snoozeTime = $action["message_action"]["snoozeTime"];
}
$reminderTime = time() + ($snoozeTime * 60);
if (class_match_prefix($props[$this->properties["message_class"]], "IPM.Appointment")) {
if (isset($props[$this->properties["appointment_recurring"]]) && $props[$this->properties["appointment_recurring"]]) {
$recurrence = new Recurrence($store, $message);
$nextReminder = $recurrence->getNextReminderTime(time());
// flagdueby must be the snooze time or the time of the next instance, whichever is earlier
if ($reminderTime < $nextReminder) {
$newProps[$this->properties["flagdueby"]] = $reminderTime;
}
else {
$newProps[$this->properties["flagdueby"]] = $nextReminder;
}
}
else {
$newProps[$this->properties["flagdueby"]] = $reminderTime;
}
}
else {
$newProps[$this->properties["flagdueby"]] = $reminderTime;
}
// save props
mapi_setprops($message, $newProps);
mapi_savechanges($message);
$result = true;
}
if ($result) {
/*
* @FIXME: Fix notifications for reminders.
* Notifications are currently disabled, because deleting multiple items will notify
* hierarchy multiple time but no data is changed with folder item in hierarchy.
* so it will push same data again which will lead to an error.
*/
// $props = mapi_getprops($message, array(PR_ENTRYID, PR_PARENT_ENTRYID, PR_STORE_ENTRYID));
// $GLOBALS["bus"]->notify(bin2hex($props[PR_PARENT_ENTRYID]), TABLE_SAVE, $props);
}
$this->sendFeedback($result);
}
/**
* Dismiss a reminder.
*
* @param false|resource $store MAPI message store, or false when unavailable
* @param false|string $entryid entryid of the message, or false when absent
*/
public function dismissItem($store, $entryid) {
if ($store === false || !is_string($entryid) || $entryid === '') {
$this->sendFeedback(false);
return;
}
$result = false;
$message = mapi_msgstore_openentry($store, $entryid);
if ($message) {
$newProps = [];
$props = mapi_getprops($message, $this->properties);
if (class_match_prefix($props[$this->properties["message_class"]], "IPM.Appointment")) {
if (isset($props[$this->properties["appointment_recurring"]]) && $props[$this->properties["appointment_recurring"]]) {
$recurrence = new Recurrence($store, $message);
// check for next reminder after "now" for the next instance
$nextReminder = $recurrence->getNextReminderTime(time());
if ($nextReminder !== false) {
$newProps[$this->properties["flagdueby"]] = $nextReminder;
}
else {
$newProps[$this->properties["reminder"]] = false;
}
}
else {
$newProps[$this->properties["reminder"]] = false;
}
}
elseif (class_match_prefix($props[$this->properties["message_class"]], "IPM.Task")) {
$newProps[$this->properties["reminder"]] = false;
if (isset($props[$this->properties['task_recurring']]) && $props[$this->properties['task_recurring']] == 1) {
$newProps[$this->properties['task_resetreminder']] = true;
}
}
else {
$newProps[$this->properties["reminder"]] = false;
}
// save props
mapi_setprops($message, $newProps);
mapi_savechanges($message);
$result = true;
}
if ($result) {
/*
* @FIXME: Fix notifications for reminders.
* Notifications are currently disabled, because deleting multiple items will notify
* hierarchy multiple time but no data is changed with folder item in hierarchy.
* so it will push same data again which will lead to an error.
*/
// $props = mapi_getprops($message, array(PR_ENTRYID, PR_PARENT_ENTRYID, PR_STORE_ENTRYID));
// $GLOBALS["bus"]->notify(bin2hex($props[PR_PARENT_ENTRYID]), TABLE_SAVE, $props);
}
$this->sendFeedback($result);
}
/**
* Function does customization of exception based on module data.
* like, here it will generate display message based on actionType
* for particular exception.
*
* @param object $e Exception object
* @param string $actionType the action type, sent by the client
* @param resource $store MAPI store containing the message
* @param string $parententryid parent entryid of the message
* @param string $entryid entryid of the message
* @param array $action the action data, sent by the client
*/
#[Override]
public function handleException(&$e, $actionType = null, $store = null, $parententryid = null, $entryid = null, $action = null) {
if (is_null($e->displayMessage)) {
switch ($actionType) {
case 'delete':
if (!empty($action['message_action']['action_type'])) {
switch ($action['message_action']['action_type']) {
case 'snooze':
if ($e->getCode() == MAPI_E_STORE_FULL) {
$e->setDisplayMessage(_('Cannot snooze the reminder. You may be reminded again.') . '<br />' . $this->getOverQuotaMessage($store));
}
else {
$e->setDisplayMessage(_('Cannot snooze the reminder. You may be reminded again.'));
}
break;
case 'dismiss':
if ($e->getCode() == MAPI_E_STORE_FULL) {
$e->setDisplayMessage(_('Cannot dismiss the reminder. You may be reminded again.') . '<br />' . $this->getOverQuotaMessage($store));
}
else {
$e->setDisplayMessage(_('Cannot dismiss the reminder. You may be reminded again.'));
}
break;
}
}
break;
}
}
parent::handleException($e, $actionType, $store, $parententryid, $entryid, $action);
}
}
@@ -0,0 +1,343 @@
<?php
/*
* SPDX-FileCopyrightText: Copyright 2020 - 2026 grommunio GmbH
* SPDX-FileCopyrightText: Copyright 2016 Kopano and its licensors
* SPDX-FileCopyrightText: Copyright 2005 - 2016 Zarafa B.V. and its licensors
* SPDX-License-Identifier: AGPL-3.0-or-later
*/
/**
* Reminder Module.
*
* TODO: add description
*/
class ReminderListModule extends ListModule {
#[Override]
protected function getExecutionLockName() {
return null;
}
private $reminderEntryId;
/**
* Constructor.
*
* @param int $id unique id
* @param array $data list of all actions
*/
public function __construct($id, $data) {
parent::__construct($id, $data);
$this->properties = $GLOBALS["properties"]->getReminderProperties();
}
#[Override]
public function execute() {
foreach ($this->data as $actionType => $action) {
$store = $GLOBALS["mapisession"]->getDefaultMessageStore();
$this->reminderEntryId = $this->getReminderFolderEntryId($store);
if (isset($actionType)) {
try {
switch ($actionType) {
case "list":
$this->getReminders();
break;
default:
$this->handleUnknownActionType($actionType);
}
}
catch (MAPIException $e) {
$this->processException($e, $actionType, $store, null, null, $action);
}
}
}
}
public function getReminderFolderEntryId($store) {
$root = mapi_msgstore_openentry($store);
$rootProps = mapi_getprops($root, [PR_REM_ONLINE_ENTRYID]);
// Reminder folder didn't exist, create one
return $rootProps[PR_REM_ONLINE_ENTRYID] ?? $this->createReminderFolder($store);
}
public function createReminderFolder($store) {
$storeProps = mapi_getprops($store, [PR_IPM_OUTBOX_ENTRYID, PR_IPM_WASTEBASKET_ENTRYID, PR_IPM_SUBTREE_ENTRYID]);
$root = mapi_msgstore_openentry($store);
$rootProps = mapi_getprops($root, [PR_ADDITIONAL_REN_ENTRYIDS, PR_IPM_DRAFTS_ENTRYID]);
$folders = [];
/* The list of forbidden folders (MS-OXORMDR v14 §1.1) */
if (isset($storeProps[PR_IPM_WASTEBASKET_ENTRYID])) {
$folders[] = $storeProps[PR_IPM_WASTEBASKET_ENTRYID];
}
if (isset($rootProps[PR_ADDITIONAL_REN_ENTRYIDS]) && !empty($rootProps[PR_ADDITIONAL_REN_ENTRYIDS][4])) {
$folders[] = $rootProps[PR_ADDITIONAL_REN_ENTRYIDS][4];
} // junk mail
if (isset($rootProps[PR_IPM_DRAFTS_ENTRYID])) {
$folders[] = $rootProps[PR_IPM_DRAFTS_ENTRYID];
}
if (isset($storeProps[PR_IPM_OUTBOX_ENTRYID])) {
$folders[] = $storeProps[PR_IPM_OUTBOX_ENTRYID];
}
if (isset($rootProps[PR_ADDITIONAL_REN_ENTRYIDS]) && !empty($rootProps[PR_ADDITIONAL_REN_ENTRYIDS][0])) {
$folders[] = $rootProps[PR_ADDITIONAL_REN_ENTRYIDS][0];
} // conflicts
if (isset($rootProps[PR_ADDITIONAL_REN_ENTRYIDS]) && !empty($rootProps[PR_ADDITIONAL_REN_ENTRYIDS][2])) {
$folders[] = $rootProps[PR_ADDITIONAL_REN_ENTRYIDS][2];
} // local failures
if (isset($rootProps[PR_ADDITIONAL_REN_ENTRYIDS]) && !empty($rootProps[PR_ADDITIONAL_REN_ENTRYIDS][3])) {
$folders[] = $rootProps[PR_ADDITIONAL_REN_ENTRYIDS][3];
} // server failures
if (isset($rootProps[PR_ADDITIONAL_REN_ENTRYIDS]) && !empty($rootProps[PR_ADDITIONAL_REN_ENTRYIDS][1])) {
$folders[] = $rootProps[PR_ADDITIONAL_REN_ENTRYIDS][1];
} // sync issues
$folderRestriction = [];
foreach ($folders as $folder) {
$folderRestriction[] = [RES_PROPERTY,
[
RELOP => RELOP_NE,
ULPROPTAG => $this->properties["parent_entryid"],
VALUE => [$this->properties["parent_entryid"] => $folder],
],
];
}
$res =
[RES_AND,
[
[RES_AND,
$folderRestriction,
],
[RES_AND,
[
[RES_NOT,
[
[RES_AND,
[
[RES_EXIST,
[
ULPROPTAG => $this->properties["message_class"],
],
],
[RES_CONTENT,
[
FUZZYLEVEL => FL_PREFIX,
ULPROPTAG => $this->properties["message_class"],
VALUE => [$this->properties["message_class"] => "IPM.Schedule"],
],
],
],
],
],
],
[RES_BITMASK,
[
ULTYPE => BMR_EQZ,
ULPROPTAG => $this->properties["message_flags"],
ULMASK => MSGFLAG_SUBMIT,
],
],
[RES_OR,
[
[RES_PROPERTY,
[
RELOP => RELOP_EQ,
ULPROPTAG => $this->properties["reminder"],
VALUE => [$this->properties["reminder"] => true],
],
],
[RES_AND,
[
[RES_EXIST,
[
ULPROPTAG => $this->properties["recurring"],
],
],
[RES_PROPERTY,
[
RELOP => RELOP_EQ,
ULPROPTAG => $this->properties["recurring"],
VALUE => [$this->properties["recurring"] => true],
],
],
],
],
],
],
],
],
],
];
$folder = mapi_folder_createfolder($root, _("Reminders"), "", OPEN_IF_EXISTS, FOLDER_SEARCH);
mapi_setprops($folder, [PR_CONTAINER_CLASS => "Outlook.Reminder"]);
mapi_savechanges($folder);
mapi_folder_setsearchcriteria($folder, $res, [$storeProps[PR_IPM_SUBTREE_ENTRYID]], RECURSIVE_SEARCH);
$folderProps = mapi_getprops($folder, [PR_ENTRYID]);
mapi_setprops($root, [PR_REM_ONLINE_ENTRYID => $folderProps[PR_ENTRYID]]);
mapi_savechanges($root);
return $folderProps[PR_ENTRYID];
}
public function getReminders() {
$data = [];
$store = $GLOBALS["mapisession"]->getDefaultMessageStore();
$restriction = [RES_AND,
[
[RES_PROPERTY,
[
RELOP => RELOP_LT,
ULPROPTAG => $this->properties["flagdueby"],
VALUE => [$this->properties["flagdueby"] => time()],
],
],
[RES_PROPERTY,
[
RELOP => RELOP_EQ,
ULPROPTAG => $this->properties["reminder"],
VALUE => true,
],
],
[RES_PROPERTY,
[
RELOP => RELOP_NE,
ULPROPTAG => $this->properties["message_class"],
VALUE => "IPM.TaskRequest",
],
],
[RES_PROPERTY,
[
RELOP => RELOP_NE,
ULPROPTAG => $this->properties["message_class"],
VALUE => "IPM.TaskRequest.Cancel",
],
],
[RES_PROPERTY,
[
RELOP => RELOP_NE,
ULPROPTAG => $this->properties["message_class"],
VALUE => "IPM.TaskRequest.Accept",
],
],
[RES_PROPERTY,
[
RELOP => RELOP_NE,
ULPROPTAG => $this->properties["message_class"],
VALUE => "IPM.TaskRequest.Update",
],
],
[RES_PROPERTY,
[
RELOP => RELOP_NE,
ULPROPTAG => $this->properties["message_class"],
VALUE => "IPM.TaskRequest.Complete",
],
],
],
];
try {
$reminderfolder = mapi_msgstore_openentry($store, $this->reminderEntryId);
}
catch (MAPIException $e) {
// if the reminder folder does not exist, try to recreate it.
if ($e->getCode() == MAPI_E_NOT_FOUND) {
$e->setHandled();
$this->reminderEntryId = $this->createReminderFolder($store);
$reminderfolder = mapi_msgstore_openentry($store, $this->reminderEntryId);
}
else {
throw $e;
}
}
$remindertable = mapi_folder_getcontentstable($reminderfolder, MAPI_DEFERRED_ERRORS);
if (!$remindertable) {
return false;
}
mapi_table_restrict($remindertable, $restriction, TBL_BATCH);
mapi_table_sort($remindertable, [$this->properties["flagdueby"] => TABLE_SORT_DESCEND], TBL_BATCH);
// reminder store hold only 99 records as
// we show 99 notification on client side.
$rows = mapi_table_queryrows($remindertable, $this->properties, 0, MAX_NUM_REMINDERS);
$data["item"] = [];
foreach ($rows as $row) {
if (isset($row[$this->properties["appointment_recurring"]]) && $row[$this->properties["appointment_recurring"]]) {
$recur = new Recurrence($store, $row);
/**
* FlagDueBy == PidLidReminderSignalTime.
* FlagDueBy handles whether we should be showing the item; if now() is after FlagDueBy, then we should show a reminder
* for this recurrence. However, the item we will show is either the most recent past occurrence (overdue), or the next occurrence, depending
* on whether we have reached the next occurrence yet (the reminder_time of the next item is ignored).
*
* The way we handle this is to get all occurrences between the 'flagdueby' moment and the current time. This will
* yield N items (possibly many if it was not dismissed for a long time). We can then take the last item in this list, and this is the item
* we will show to the user. The idea here is:
*
* The item we want to show is the last item in that list (new occurrences that have started up to now should override old ones).
*
* Add the reminder_minutes (default 15 minutes for calendar, 0 for tasks) to check over the gap between FlagDueBy and the start time of the
* occurrence, if "now" would be in between these values.
*/
$remindertimeinseconds = (int) ($row[$this->properties["reminder_minutes"]] ?? 0) * 60;
$flagDueBy = $row[$this->properties["flagdueby"]] ?? null;
if (!is_numeric($flagDueBy)) {
$flagDueBy = $row[$this->properties["reminder_time"]] ??
$row[$this->properties["appointment_startdate"]] ??
null;
}
$flagDueBy = is_numeric($flagDueBy) ? (int) $flagDueBy : null;
$occurrences = null;
if ($flagDueBy !== null) {
try {
$occurrences = $recur->getItems($flagDueBy, time() + $remindertimeinseconds, 0, true);
}
catch (RecurrenceException $re) {
$re->setHandled();
continue;
}
if (empty($occurrences)) {
continue;
}
// More than one occurrence, use the last one instead of the first one after flagdueby
$occ = $occurrences[count($occurrences) - 1];
// By default, occurrence reminders are enabled. A false reminder value suppresses the popup for this occurrence.
if (!(isset($occ[$this->properties['reminder']]) && $occ[$this->properties['reminder']] == 0)) {
$row[$this->properties["reminder_time"]] = $occ[$this->properties["appointment_startdate"]];
$row[$this->properties["appointment_startdate"]] = $occ[$this->properties["appointment_startdate"]];
$row[$this->properties["appointment_enddate"]] = $occ[$this->properties["appointment_startdate"]];
}
}
}
// Add the non-bogus rows
array_push($data["item"], Conversion::mapMAPI2XML($this->properties, $row));
}
$this->addActionData("list", $data);
$GLOBALS["bus"]->addData($this->getResponseData());
// Trigger the newmailnotifier
$GLOBALS["bus"]->notify(REQUEST_ENTRYID, HIERARCHY_UPDATE, ['', '']);
return true;
}
}
@@ -0,0 +1,618 @@
<?php
/*
* SPDX-FileCopyrightText: Copyright 2020 - 2026 grommunio GmbH
* SPDX-FileCopyrightText: Copyright 2016 Kopano and its licensors
* SPDX-FileCopyrightText: Copyright 2005 - 2016 Zarafa B.V. and its licensors
* SPDX-License-Identifier: AGPL-3.0-or-later
*/
/**
* ResolveNames Module.
*/
class ResolveNamesModule extends Module {
#[Override]
protected function getExecutionLockName() {
return null;
}
/**
* Constructor.
*
* @param mixed $id
* @param mixed $data
*/
public function __construct($id, $data) {
parent::__construct($id, $data);
}
/**
* Executes all the actions in the $data variable.
*/
#[Override]
public function execute() {
foreach ($this->data as $actionType => $action) {
if (isset($actionType)) {
try {
switch ($actionType) {
case 'checknames':
$this->checkNames($action);
break;
default:
$this->handleUnknownActionType($actionType);
}
}
catch (MAPIException $e) {
$this->processException($e, $actionType);
}
}
}
}
/**
* Function which checks the names, sent by the client. This function is used
* when a user wants to sent an email and want to check the names filled in
* by the user in the to, cc and bcc field. This function uses the global
* user list to check if the names are correct.
*
* @param array $action the action data, sent by the client
*/
public function checkNames($action) {
if (isset($action['resolverequests'])) {
$data = [];
$excludeLocalContacts = $action['exclude_local_contacts'] ?? false;
$excludeGABGroups = $action['exclude_gab_groups'] ?? false;
$resolveRequest = $action['resolverequests'];
if (!is_array($resolveRequest)) {
$resolveRequest = [$resolveRequest];
}
// open addressbook
// When local contacts need to be excluded we have pass true as the first argument
// so we will not have any Contact Providers set on the Addressbook resource.
$ab = $GLOBALS['mapisession']->getAddressbook($excludeLocalContacts);
$ab_dir = mapi_ab_openentry($ab);
$resolveResponse = [];
// check names
foreach ($resolveRequest as $query) {
if (is_array($query) && isset($query['id'])) {
$responseEntry = [];
$responseEntry['id'] = $query['id'];
if (!empty($query['display_name']) || !empty($query['email_address'])) {
$responseEntry['result'] = $this->searchAddressBook($ab, $ab_dir, $query, $excludeGABGroups);
$resolveResponse[] = $responseEntry;
}
}
}
$data['resolveresponse'] = $resolveResponse;
$this->addActionData('checknames', $data);
$GLOBALS['bus']->addData($this->getResponseData());
}
}
/**
* This function searches the addressbook specified for users and returns an array with data
* Please note that the returning array must be UTF8.
*
* @param resource $ab The addressbook
* @param resource $ab_dir The addressbook container
* @param array $query The search query, case is ignored
* @param bool $excludeGABGroups flag to exclude groups from resolving
*/
public function searchAddressBook($ab, $ab_dir, $query, $excludeGABGroups) {
$searchstr = $this->getSearchString($query);
if ($searchstr === '') {
return [];
}
// If the address_type is 'EX' then we are resolving something which must be found in
// the GAB as an exact match. So add the flag EMS_AB_ADDRESS_LOOKUP to ensure we will not
// get multiple results when multiple items have a partial match.
$flags = $query['address_type'] === 'EX' ? EMS_AB_ADDRESS_LOOKUP : 0;
try {
// First, try an addressbook lookup
$rows = mapi_ab_resolvename($ab, [[PR_DISPLAY_NAME => $searchstr]], $flags);
// If the lookup succeeded but we should also check for exact hidden matches
if (defined('ENABLE_RESOLVE_HIDDEN_USERS') && ENABLE_RESOLVE_HIDDEN_USERS && !($flags & EMS_AB_ADDRESS_LOOKUP)) {
$hiddenRows = $this->resolveHiddenExactMatches($ab, $query);
if (!empty($hiddenRows)) {
$rows = $this->mergeAndDeduplicateRows($rows, $hiddenRows);
}
}
$this->searchContactsFolders($ab, $ab_dir, $searchstr, $rows);
}
catch (MAPIException $e) {
if ($e->getCode() == MAPI_E_AMBIGUOUS_RECIP) {
$ab_entryid = mapi_ab_getdefaultdir($ab);
if ($ab_entryid === false) {
throw $e;
}
$ab_dir = mapi_ab_openentry($ab, $ab_entryid);
if ($ab_dir === false) {
throw $e;
}
// Ambiguous, show possibilities:
$table = mapi_folder_getcontentstable($ab_dir, MAPI_DEFERRED_ERRORS);
$restriction = $this->getAmbigiousContactRestriction($searchstr, $excludeGABGroups, PR_ACCOUNT);
mapi_table_restrict($table, $restriction, TBL_BATCH);
mapi_table_sort($table, [PR_DISPLAY_NAME => TABLE_SORT_ASCEND], TBL_BATCH);
$rows = mapi_table_queryallrows($table, [PR_ACCOUNT, PR_ADDRTYPE, PR_DISPLAY_NAME, PR_ENTRYID, PR_SEARCH_KEY, PR_OBJECT_TYPE, PR_SMTP_ADDRESS, PR_DISPLAY_TYPE_EX, PR_EMAIL_ADDRESS, PR_OBJECT_TYPE, PR_DISPLAY_TYPE]);
$rows = array_merge($rows, $this->getAmbigiousContactResolveResults($ab, $searchstr, $excludeGABGroups));
// Also check for hidden users if enabled and this is an exact match
if (defined('ENABLE_RESOLVE_HIDDEN_USERS') && ENABLE_RESOLVE_HIDDEN_USERS) {
$hiddenRows = $this->resolveHiddenExactMatches($ab, $query);
if (!empty($hiddenRows)) {
$rows = $this->mergeAndDeduplicateRows($rows, $hiddenRows);
}
}
}
elseif ($e->getCode() == MAPI_E_NOT_FOUND) {
$rows = [];
if (defined('ENABLE_RESOLVE_HIDDEN_USERS') && ENABLE_RESOLVE_HIDDEN_USERS) {
$rows = $this->resolveHiddenExactMatches($ab, $query);
}
if (empty($rows) && (($query['address_type'] ?? '') === 'SMTP')) {
// If we still can't find anything, and we were searching for a SMTP user
// we can generate a oneoff entry which contains the information of the user.
// Only for an actual address, else the one-off would be undeliverable.
if ($GLOBALS['operations']->isEmailAddressLike($searchstr)) {
$entryId = mapi_createoneoff($query['display_name'], 'SMTP', $searchstr);
if ($entryId !== false) {
$rows[] = [
PR_ACCOUNT => $searchstr, PR_ADDRTYPE => 'SMTP', PR_EMAIL_ADDRESS => $searchstr,
PR_DISPLAY_NAME => $query['display_name'], PR_DISPLAY_TYPE_EX => DT_REMOTE_MAILUSER, PR_DISPLAY_TYPE => DT_MAILUSER,
PR_SMTP_ADDRESS => $searchstr, PR_OBJECT_TYPE => MAPI_MAILUSER,
PR_ENTRYID => $entryId,
];
}
}
// Check also the user's contacts folders
else {
$this->searchContactsFolders($ab, $ab_dir, $searchstr, $rows);
}
}
elseif (empty($rows)) {
$this->searchContactsFolders($ab, $ab_dir, $searchstr, $rows);
}
}
else {
// all other errors should be propagated to higher level exception handlers
throw $e;
}
}
$items = [];
$searchstr = 'smtp:' . strtolower($searchstr);
if ($rows) {
foreach ($rows as $user_data) {
$item = [];
if (!isset($user_data[PR_ACCOUNT])) {
$abitem = mapi_ab_openentry($ab, $user_data[PR_ENTRYID]);
$user_data = mapi_getprops($abitem, [PR_ACCOUNT, PR_ADDRTYPE, PR_DISPLAY_NAME, PR_DISPLAY_TYPE_EX, PR_ENTRYID, PR_SEARCH_KEY, PR_EMAIL_ADDRESS, PR_SMTP_ADDRESS, PR_OBJECT_TYPE, PR_DISPLAY_TYPE]);
}
if ($excludeGABGroups && $user_data[PR_OBJECT_TYPE] === MAPI_DISTLIST) {
// exclude groups from result
continue;
}
$item = [];
$item['object_type'] = $user_data[PR_OBJECT_TYPE] ?? MAPI_MAILUSER;
$item['entryid'] = isset($user_data[PR_ENTRYID]) ? bin2hex($user_data[PR_ENTRYID]) : '';
$item['display_name'] = $user_data[PR_DISPLAY_NAME] ?? '';
$item['display_type'] = $user_data[PR_DISPLAY_TYPE] ?? DT_MAILUSER;
// Test whether the GUID in the entryid is from the Contact Provider
if ($GLOBALS['entryid']->hasContactProviderGUID($item['entryid'])) {
// The properties for a Distribution List differs from the other objects
if ($item['object_type'] == MAPI_DISTLIST) {
$item['address_type'] = 'MAPIPDL';
// The email_address is empty for DistList, using display name for resolving
$item['email_address'] = $item['display_name'];
$item['smtp_address'] ??= '';
}
else {
$item['address_type'] = $user_data[PR_ADDRTYPE] ?? 'SMTP';
if (isset($user_data['address_type']) && $user_data['address_type'] === 'EX') {
$item['email_address'] = $user_data[PR_EMAIL_ADDRESS] ?? '';
}
else {
// Fake being an EX account, since it's actually an SMTP addrtype the email address is in a different property.
$item['smtp_address'] = $user_data[PR_EMAIL_ADDRESS] ?? '';
// Keep the old scenario happy.
$item['email_address'] = $user_data[PR_EMAIL_ADDRESS] ?? '';
}
}
// It can be considered a GAB entry
}
else {
$item['user_name'] = $user_data[PR_ACCOUNT] ?? $item['display_name'];
$item['display_type_ex'] = $user_data[PR_DISPLAY_TYPE_EX] ?? MAPI_MAILUSER;
$item['email_address'] = $user_data[PR_EMAIL_ADDRESS] ?? '';
$item['smtp_address'] = $user_data[PR_SMTP_ADDRESS] ?? $item['email_address'];
$item['address_type'] = $user_data[PR_ADDRTYPE] ?? 'SMTP';
}
if (isset($user_data[PR_SEARCH_KEY])) {
$item['search_key'] = bin2hex($user_data[PR_SEARCH_KEY]);
}
else {
$emailAddress = $item['smtp_address'] ?? $item['email_address'];
$item['search_key'] = bin2hex(strtoupper($item['address_type'] . ':' . $emailAddress)) . '00';
}
// Check for aliases
if (isset($user_data[PR_EMS_AB_PROXY_ADDRESSES]) &&
is_array($user_data[PR_EMS_AB_PROXY_ADDRESSES]) &&
in_array($searchstr, array_map('strtolower', $user_data[PR_EMS_AB_PROXY_ADDRESSES])) &&
!str_ends_with($searchstr, $user_data[PR_SMTP_ADDRESS]) &&
$flags === 0) {
$item['email_address'] = $item['smtp_address'] = substr($searchstr, 5);
$item['display_name'] .= ' <' . $item['smtp_address'] . '>';
$item['address_type'] = 'SMTP';
}
array_push($items, $item);
}
}
return $items;
}
/**
* Pick the string used to resolve a recipient: a plausible email_address
* first, Exchange DNs as-is (exact DN match), then smtp_address, then
* display name. Legacy non-address values in email_address (e.g. old
* account names) would otherwise fuzzy-match unrelated GAB entries.
*
* @param array $query resolve request sent by the client
*
* @return string the search string, may be empty
*/
public function getSearchString($query) {
$emailAddress = trim((string) ($query['email_address'] ?? ''));
$smtpAddress = trim((string) ($query['smtp_address'] ?? ''));
$displayName = trim((string) ($query['display_name'] ?? ''));
if ($emailAddress !== '' &&
($GLOBALS['operations']->isEmailAddressLike($emailAddress) || stripos($emailAddress, '/o=') === 0)) {
return $emailAddress;
}
// Only when a (legacy) email_address was present: an empty one means
// the client deliberately asked for display name resolution.
if ($emailAddress !== '' && $GLOBALS['operations']->isEmailAddressLike($smtpAddress)) {
return $smtpAddress;
}
if ($displayName !== '') {
return $displayName;
}
return $emailAddress;
}
/**
* Try to resolve a hidden user by matching the provided query exactly against
* common address book properties. Hidden entries are not returned in regular
* searches, but the EMS_AB_ADDRESS_LOOKUP flag allows us to perform an exact
* lookup that also returns hidden entries.
*
* @param resource $ab The addressbook
* @param array $query Resolve query sent by the client
*
* @return array
*/
protected function resolveHiddenExactMatches($ab, $query) {
if (!defined('ENABLE_RESOLVE_HIDDEN_USERS') || !ENABLE_RESOLVE_HIDDEN_USERS) {
return [];
}
$candidates = [];
if (!empty($query['display_name'])) {
$candidates[] = trim((string) $query['display_name']);
}
if (!empty($query['email_address'])) {
$candidates[] = trim((string) $query['email_address']);
}
$candidates = array_values(array_unique(array_filter($candidates, 'strlen')));
$addressType = strtoupper((string) ($query['address_type'] ?? ''));
foreach ($candidates as $candidate) {
$lookups = [PR_DISPLAY_NAME];
if ($addressType === 'EX') {
$lookups[] = PR_ACCOUNT;
}
if (str_contains($candidate, '@')) {
$lookups[] = PR_EMAIL_ADDRESS;
$lookups[] = PR_SMTP_ADDRESS;
if ($addressType !== 'EX') {
$lookups[] = PR_ACCOUNT;
}
}
foreach (array_unique($lookups) as $property) {
$rows = $this->resolveNameByProperty($ab, $property, $candidate);
if (!empty($rows)) {
return $rows;
}
}
}
return [];
}
/**
* Execute an exact resolve against the GAB for the provided property.
*
* @param resource $ab The addressbook
* @param int $property Property tag used for the lookup
* @param string $value Search value
*
* @return array
*/
protected function resolveNameByProperty($ab, $property, $value) {
if ($value === '') {
return [];
}
try {
return mapi_ab_resolvename($ab, [[$property => $value]], EMS_AB_ADDRESS_LOOKUP);
}
catch (MAPIException $e) {
if ($e->getCode() == MAPI_E_NOT_FOUND || $e->getCode() == MAPI_E_AMBIGUOUS_RECIP) {
return [];
}
throw $e;
}
}
/**
* Merge two arrays of rows and remove duplicates based on entryid.
* This prevents the same user from appearing multiple times when they're
* found through both normal and hidden user resolution.
*
* @param array $existingRows Existing rows from table/resolve queries
* @param array $newRows New rows from hidden user resolution
*
* @return array Merged array with duplicates removed
*/
protected function mergeAndDeduplicateRows($existingRows, $newRows) {
// Build a map of existing entryids
$entryidMap = [];
foreach ($existingRows as $row) {
if (isset($row[PR_ENTRYID])) {
$entryidMap[bin2hex($row[PR_ENTRYID])] = true;
}
}
// Add new rows only if they don't already exist
foreach ($newRows as $row) {
if (isset($row[PR_ENTRYID])) {
$entryidHex = bin2hex($row[PR_ENTRYID]);
if (!isset($entryidMap[$entryidHex])) {
$existingRows[] = $row;
$entryidMap[$entryidHex] = true;
}
}
}
return $existingRows;
}
/**
* Used to find multiple entries from the contact folders in the Addressbook when resolving
* returned an ambiguous result. It will find the Contact folders in the Addressbook and
* apply a restriction to extract the entries.
*
* @param resource $ab The addressbook
* @param string $query The search query, case is ignored
* @param bool $excludeGABGroups flag to exclude groups from resolving
*/
public function getAmbigiousContactResolveResults($ab, $query, $excludeGABGroups) {
/* We need to look for the Contact folders at the bottom of the following tree.
*
* IAddrBook
* - Root Container
* - HIERARCHY TABLE
* - Contacts Folders (Contact Container)
* - HIERARCHY TABLE (Contact Container Hierarchy)
* - Contact folder 1
* - Contact folder 2
*/
$rows = [];
$contactFolderRestriction = $this->getAmbigiousContactRestriction($query, $excludeGABGroups, PR_EMAIL_ADDRESS);
// Open the AB Root Container by not supplying an entryid
$abRootContainer = mapi_ab_openentry($ab);
// Get the 'Contact Folders'
$hierarchyTable = mapi_folder_gethierarchytable($abRootContainer, MAPI_DEFERRED_ERRORS);
$abHierarchyRows = mapi_table_queryallrows($hierarchyTable, [PR_AB_PROVIDER_ID, PR_ENTRYID]);
$abContactContainerEntryid = null;
// Look for the 'Contacts Folders'
for ($i = 0,$len = count($abHierarchyRows); $i < $len; ++$i) {
// Check if the folder matches the Contact Provider GUID
if ($abHierarchyRows[$i][PR_AB_PROVIDER_ID] == MUIDZCSAB) {
$abContactContainerEntryid = $abHierarchyRows[$i][PR_ENTRYID];
break;
}
}
// Next go into the 'Contacts Folders' and look in the hierarchy table for the Contact folders.
if ($abContactContainerEntryid) {
// Get the rows from hierarchy table of the 'Contacts Folders'
$abContactContainer = mapi_ab_openentry($ab, $abContactContainerEntryid);
$abContactContainerHierarchyTable = mapi_folder_gethierarchytable($abContactContainer, MAPI_DEFERRED_ERRORS);
$abContactContainerHierarchyRows = mapi_table_queryallrows($abContactContainerHierarchyTable, [PR_DISPLAY_NAME, PR_OBJECT_TYPE, PR_ENTRYID]);
// Loop through all the contact folders found under the 'Contacts Folders' hierarchy
for ($j = 0,$len = count($abContactContainerHierarchyRows); $j < $len; ++$j) {
// Open, get contents table, restrict, sort and then merge the result in the list of $rows
$abContactFolder = mapi_ab_openentry($ab, $abContactContainerHierarchyRows[$j][PR_ENTRYID]);
$abContactFolderTable = mapi_folder_getcontentstable($abContactFolder, MAPI_DEFERRED_ERRORS);
mapi_table_restrict($abContactFolderTable, $contactFolderRestriction, TBL_BATCH);
mapi_table_sort($abContactFolderTable, [PR_DISPLAY_NAME => TABLE_SORT_ASCEND], TBL_BATCH);
// Go go gadget, merge!
$rows = array_merge($rows, mapi_table_queryallrows($abContactFolderTable, [PR_ACCOUNT, PR_DISPLAY_NAME, PR_ENTRYID, PR_OBJECT_TYPE, PR_SMTP_ADDRESS, PR_DISPLAY_TYPE_EX, PR_EMAIL_ADDRESS, PR_OBJECT_TYPE, PR_DISPLAY_TYPE]));
}
}
return $rows;
}
/**
* Setup the restriction used for resolving in the Contact folders or GAB.
*
* @param string $query The search query, case is ignored
* @param bool $excludeGABGroups flag to exclude groups from resolving
* @param int $content the PROPTAG to search in
*/
public function getAmbigiousContactRestriction($query, $excludeGABGroups, $content) {
// only return users from who the displayName or the username starts with $name
// TODO: use PR_ANR for this restriction instead of PR_DISPLAY_NAME and $content.
$resAnd = [
[RES_OR,
[
[RES_CONTENT,
[
FUZZYLEVEL => FL_PREFIX | FL_IGNORECASE,
ULPROPTAG => PR_DISPLAY_NAME,
VALUE => $query,
],
],
[RES_CONTENT,
[
FUZZYLEVEL => FL_PREFIX | FL_IGNORECASE,
ULPROPTAG => $content,
VALUE => $query,
],
],
], // RES_OR
],
];
// create restrictions based on excludeGABGroups flag
if ($excludeGABGroups) {
array_push($resAnd, [
RES_PROPERTY,
[
RELOP => RELOP_EQ,
ULPROPTAG => PR_OBJECT_TYPE,
VALUE => MAPI_MAILUSER,
],
]);
}
else {
array_push($resAnd, [RES_OR,
[
[RES_PROPERTY,
[
RELOP => RELOP_EQ,
ULPROPTAG => PR_OBJECT_TYPE,
VALUE => MAPI_MAILUSER,
],
],
[RES_PROPERTY,
[
RELOP => RELOP_EQ,
ULPROPTAG => PR_OBJECT_TYPE,
VALUE => MAPI_DISTLIST,
],
],
],
]);
}
return [RES_AND, $resAnd];
}
/**
* Function does customization of exception based on module data.
* like, here it will generate display message based on actionType
* for particular exception.
*
* @param object $e Exception object
* @param string $actionType the action type, sent by the client
* @param resource $store MAPI store containing the message
* @param string $parententryid parent entryid of the message
* @param string $entryid entryid of the message
* @param array $action the action data, sent by the client
*/
#[Override]
public function handleException(&$e, $actionType = null, $store = null, $parententryid = null, $entryid = null, $action = null) {
if (is_null($e->displayMessage)) {
switch ($actionType) {
case 'checknames':
if ($e->getCode() == MAPI_E_NO_ACCESS) {
$e->setDisplayMessage(_('You have insufficient privileges to perform this action.'));
}
else {
$e->setDisplayMessage(_('Could not resolve user.'));
}
break;
}
}
parent::handleException($e, $actionType, $store, $parententryid, $entryid, $action);
}
/**
* This function searches the private contact folders for users and returns an array with data.
* Please note that the returning array must be UTF8.
*
* @param resource $ab The addressbook
* @param resource $ab_dir The addressbook container
* @param string $searchstr The search query, case is ignored
* @param array $rows Array of the found contacts
*/
public function searchContactsFolders($ab, $ab_dir, $searchstr, &$rows) {
$abhtable = mapi_folder_gethierarchytable($ab_dir, MAPI_DEFERRED_ERRORS | CONVENIENT_DEPTH);
$abcntfolders = mapi_table_queryallrows($abhtable, [PR_ENTRYID, PR_AB_PROVIDER_ID]);
$restriction = [
RES_CONTENT,
[
FUZZYLEVEL => FL_SUBSTRING | FL_IGNORECASE,
ULPROPTAG => PR_DISPLAY_NAME,
VALUE => [PR_DISPLAY_NAME => $searchstr],
],
];
// restriction on hierarchy table for PR_AB_PROVIDER_ID
// seems not to work, just loop through
foreach ($abcntfolders as $abcntfolder) {
if ($abcntfolder[PR_AB_PROVIDER_ID] == ZARAFA_CONTACTS_GUID) {
$abfldentry = mapi_ab_openentry($ab, $abcntfolder[PR_ENTRYID]);
$abfldcontents = mapi_folder_getcontentstable($abfldentry);
mapi_table_restrict($abfldcontents, $restriction);
$r = mapi_table_queryallrows($abfldcontents, [PR_ACCOUNT, PR_ADDRTYPE, PR_DISPLAY_NAME, PR_ENTRYID,
PR_SEARCH_KEY, PR_OBJECT_TYPE, PR_SMTP_ADDRESS, PR_DISPLAY_TYPE_EX, PR_EMAIL_ADDRESS,
PR_OBJECT_TYPE, PR_DISPLAY_TYPE]);
if (is_array($r) && !empty($r)) {
$rows = array_merge($rows, $r);
}
}
}
}
}
@@ -0,0 +1,404 @@
<?php
/*
* SPDX-FileCopyrightText: Copyright 2020 - 2026 grommunio GmbH
* SPDX-FileCopyrightText: Copyright 2016 Kopano and its licensors
* SPDX-FileCopyrightText: Copyright 2005 - 2016 Zarafa B.V. and its licensors
* SPDX-License-Identifier: AGPL-3.0-or-later
*/
/**
* RestoreItemsList Module.
*/
class RestoreItemsListModule extends ListModule {
/**
* Constructor.
*
* @param int $id unique id
* @param array $data list of all actions
*/
public function __construct($id, $data) {
parent::__construct($id, $data);
$this->properties = $GLOBALS['properties']->getRestoreItemListProperties();
}
/**
* Executes all the actions in the $data variable.
*/
#[Override]
public function execute() {
foreach ($this->data as $actionType => $action) {
if (isset($actionType)) {
try {
if (!is_array($action)) {
throw new MAPIException(_("Could not process request data properly."), MAPI_E_INVALID_PARAMETER);
}
$store = $this->getActionStore($action);
$parententryid = $this->getActionParentEntryID($action);
$folderentryid = $this->getActionSingleEntryID($action);
if ($store === false || is_array($store)) {
throw new MAPIException(_("Could not process request data properly."), MAPI_E_INVALID_PARAMETER);
}
switch ($actionType) {
case "list":
case "updatelist":
if (!is_string($folderentryid)) {
throw new MAPIException(_("Could not process request data properly."), MAPI_E_INVALID_PARAMETER);
}
if (isset($action["message_action"])) {
if (!is_string($action["message_action"]["action_type"] ?? null)) {
throw new MAPIException(_("Could not process request data properly."), MAPI_E_INVALID_PARAMETER);
}
$subActionType = $action["message_action"]["action_type"];
switch ($subActionType) {
case "restoreAll":
$this->restoreAll($store, $folderentryid, $action);
break;
case "deleteAll":
$this->deleteAll($store, $folderentryid, $action);
break;
}
}
else {
$this->itemList($store, $folderentryid, $action);
}
break;
case "delete":
if ($parententryid === false || !is_string($action["message_action"]["action_type"] ?? null)) {
throw new MAPIException(_("Could not process request data properly."), MAPI_E_INVALID_PARAMETER);
}
$itemType = $action["message_action"]["action_type"];
switch ($itemType) {
case "restorefolder":
if (!is_string($folderentryid)) {
throw new MAPIException(_("Could not process request data properly."), MAPI_E_INVALID_PARAMETER);
}
$this->restoreFolder($store, $parententryid, $folderentryid);
break;
case "deletefolder":
$this->deleteFolder($store, $parententryid, $action);
break;
case "restoremessage":
$this->restoreItems($store, $parententryid, $action);
break;
case "deletemessage":
$this->deleteItems($store, $parententryid, $action);
break;
default:
$this->handleUnknownActionType($itemType);
}
break;
default:
$this->handleUnknownActionType($actionType);
}
}
catch (MAPIException $e) {
$this->processException($e, $actionType);
}
}
}
}
/**
* Function which permanently delete all folder or message items.
*
* @param resource $store MAPI message store
* @param string $folderentryid entry ID of the target folder
* @param array $action action data sent by the client
*/
public function deleteAll($store, $folderentryid, $action) {
$folder = mapi_msgstore_openentry($store, $folderentryid);
// delete all folders.
if (isset($action["itemType"]) && $action["itemType"] == "folder") {
$table = mapi_folder_gethierarchytable($folder, MAPI_DEFERRED_ERRORS | SHOW_SOFT_DELETES);
$restoreItems = array_column(mapi_table_queryallrows($table, [PR_ENTRYID]), PR_ENTRYID);
foreach ($restoreItems as $restoreItem) {
mapi_folder_deletefolder($folder, $restoreItem, DEL_FOLDERS | DEL_MESSAGES | DELETE_HARD_DELETE);
}
}
else {
// delete all messages
$table = mapi_folder_getcontentstable($folder, MAPI_DEFERRED_ERRORS | SHOW_SOFT_DELETES);
$restoreItems = array_column(mapi_table_queryallrows($table, [PR_ENTRYID]), PR_ENTRYID);
mapi_folder_deletemessages($folder, $restoreItems, DELETE_HARD_DELETE);
}
$this->addActionData("list", ["item" => []]);
$GLOBALS["bus"]->addData($this->getResponseData());
}
/**
* Function used to restore all folders.
*
* @param resource $store MAPI message store
* @param resource $folder folder whose contents need to be restored
*
* @throws MAPIException
*/
public function restoreAllFolders($store, $folder) {
$table = mapi_folder_gethierarchytable($folder, MAPI_DEFERRED_ERRORS | SHOW_SOFT_DELETES);
$rows = mapi_table_queryallrows($table, [PR_ENTRYID, PR_DISPLAY_NAME]);
foreach ($rows as $row) {
$restoreItem = $row[PR_ENTRYID];
$name = $row[PR_DISPLAY_NAME] ?? '';
// a move within the parent only renames, so copy and hard-delete the source
try {
mapi_folder_copyfolder($folder, $restoreItem, $folder, $name);
}
catch (MAPIException $e) {
if ($e->getCode() != MAPI_E_COLLISION) {
throw $e;
}
$name = $GLOBALS["operations"]->checkFolderNameConflict($store, $folder, $name);
mapi_folder_copyfolder($folder, $restoreItem, $folder, $name);
}
mapi_folder_deletefolder($folder, $restoreItem, DEL_MESSAGES | DEL_FOLDERS | DELETE_HARD_DELETE);
}
// Notify the parent folder.
$this->notifyParentFolder($store, $folder, $folder);
}
/**
* Restore every message in the given folder.
*
* @param resource $folder folder whose contents need to be restored
*/
public function restoreAllItems($folder) {
$table = mapi_folder_getcontentstable($folder, MAPI_DEFERRED_ERRORS | SHOW_SOFT_DELETES);
$restoreItems = array_column(mapi_table_queryallrows($table, [PR_ENTRYID]), PR_ENTRYID);
mapi_folder_copymessages($folder, $restoreItems, $folder, MESSAGE_MOVE);
// as after moving the message/s the entryid gets changed, so need to notify about the folder
// so that we can update the folder on parent page.
$folderProps = mapi_getprops($folder, [PR_STORE_ENTRYID, PR_ENTRYID]);
/* when we restore any message from soft deleted system then we are actually copying the item, so at that time entryid of
* that particular item gets changed, so to notify client about changes we need to
* notify parent folder where we have restored the message
*/
$props = [];
$props[PR_PARENT_ENTRYID] = $folderProps[PR_ENTRYID];
$props[PR_STORE_ENTRYID] = $folderProps[PR_STORE_ENTRYID];
$GLOBALS["bus"]->notify(bin2hex((string) $folderProps[PR_ENTRYID]), TABLE_SAVE, $props);
}
/**
* Restore all folders or messages according to the requested item type.
*
* @param resource $store MAPI message store
* @param string $folderentryid entry ID of the target folder
* @param array $action action data sent by the client
*
* @throws MAPIException
*/
public function restoreAll($store, $folderentryid, $action) {
$folder = mapi_msgstore_openentry($store, $folderentryid);
if (isset($action["itemType"]) && $action["itemType"] == "folder") {
$this->restoreAllFolders($store, $folder);
}
else {
$this->restoreAllItems($folder);
}
$this->addActionData("list", ["item" => []]);
$GLOBALS["bus"]->addData($this->getResponseData());
}
/**
* Function to retrieve the list of messages or folder of particular folder.
*
* @param resource $store MAPI message store
* @param string $entryid entry ID of the folder
* @param array $action request data
*/
public function itemList($store, $entryid, $action) {
// Restriction
$this->parseRestriction($action);
// set the this->$sort variable.
$this->parseSortOrder($action);
$limit = $action['restriction']['limit'] ?? $GLOBALS['settings']->get('grommunio/v1/main/page_size', 50);
$getHierarchy = isset($action["itemType"]) && $action["itemType"] == "folder";
$data = $GLOBALS["operations"]->getTable(
$store,
$entryid,
$this->properties,
$this->sort,
$this->start,
$limit,
$this->restriction,
$getHierarchy,
MAPI_DEFERRED_ERRORS | SHOW_SOFT_DELETES
);
$this->addActionData("list", $data);
$GLOBALS["bus"]->addData($this->getResponseData());
}
/**
* Function to delete selected items of particular folder.
*
* @param resource $store MAPI message store
* @param string $parententryid entry ID of the folder containing the item to delete
* @param array $items items to delete
*/
public function deleteItems($store, $parententryid, $items) {
if (is_assoc_array($items)) {
// wrap single item in an array
$items = [$items];
}
$sfolder = mapi_msgstore_openentry($store, $parententryid);
for ($index = 0, $len = count($items); $index < $len; ++$index) {
mapi_folder_deletemessages($sfolder, [hex2bin((string) $items[$index]['entryid'])], DELETE_HARD_DELETE);
}
$this->sendFeedback(true);
}
/**
* Function to restore message present into the selected folder.
*
* @param resource $store MAPI message store
* @param string $parententryid entry ID of the folder containing the item to restore
* @param array $items items to restore
*/
public function restoreItems($store, $parententryid, $items) {
if (is_assoc_array($items)) {
// wrap single item in an array
$items = [$items];
}
$sfolder = mapi_msgstore_openentry($store, $parententryid);
for ($index = 0, $len = count($items); $index < $len; ++$index) {
mapi_folder_copymessages($sfolder, [hex2bin((string) $items[$index]['entryid'])], $sfolder, MESSAGE_MOVE);
}
// as after moving the message/s the entryid gets changed, so need to notify about the folder
// so that we can update the folder on parent page.
$folderProps = mapi_getprops($sfolder, [PR_STORE_ENTRYID, PR_ENTRYID]);
/* when we restore any message from soft deleted system then we are actually copying the item, so at that time entryid of
* that particular item gets changed, so to notify client about changes we need to
* notify parent folder where we have restored the message
*/
$props = [];
$props[PR_PARENT_ENTRYID] = $folderProps[PR_ENTRYID];
$props[PR_STORE_ENTRYID] = $folderProps[PR_STORE_ENTRYID];
$GLOBALS["bus"]->notify(bin2hex((string) $folderProps[PR_ENTRYID]), TABLE_SAVE, $props);
$this->sendFeedback(true);
}
/**
* Function to delete selected folders.
*
* @param resource $store MAPI message store
* @param string $parententryid entry ID of the parent folder
* @param array $folders folders to delete
*/
public function deleteFolder($store, $parententryid, $folders) {
if (is_assoc_array($folders)) {
// wrap single folder in an array
$folders = [$folders];
}
$sfolder = mapi_msgstore_openentry($store, $parententryid);
for ($index = 0, $len = count($folders); $index < $len; ++$index) {
mapi_folder_deletefolder($sfolder, hex2bin((string) $folders[$index]['entryid']), DEL_FOLDERS | DEL_MESSAGES | DELETE_HARD_DELETE);
}
$this->sendFeedback(true);
}
/**
* Function to restore soft deleted folder of particular folder. The folder
* restore action involves two operations: copy the folder marked as deleted
* as a new one and then delete the source folder.
*
* @param resource $store MAPI message store
* @param string $parententryid entry ID of the parent folder
* @param string $folderentryid entry ID of the folder to restore
*/
public function restoreFolder($store, $parententryid, $folderentryid) {
$sfolder = mapi_msgstore_openentry($store, $parententryid);
$folder = mapi_msgstore_openentry($store, $folderentryid, SHOW_SOFT_DELETES);
$folderNameProps = mapi_getprops($folder, [PR_DISPLAY_NAME]);
try {
/*
* We should first try to copy folder and if it returns MAPI_E_COLLISION then
* only we should check for the conflicting folder names and generate a new name
* and restore folder with the generated name.
*/
mapi_folder_copyfolder($sfolder, $folderentryid, $sfolder, $folderNameProps[PR_DISPLAY_NAME]);
}
catch (MAPIException $e) {
if ($e->getCode() == MAPI_E_COLLISION) {
$foldername = $GLOBALS["operations"]->checkFolderNameConflict($store, $sfolder, $folderNameProps[PR_DISPLAY_NAME]);
mapi_folder_copyfolder($sfolder, $folderentryid, $sfolder, $foldername);
}
else {
// all other errors should be propagated to higher level exception handlers
throw $e;
}
}
// Reaching this point means the folder was copied successfully.
mapi_folder_deletefolder($sfolder, $folderentryid, DEL_MESSAGES | DEL_FOLDERS | DELETE_HARD_DELETE);
// notify the parent folder
$parentFolder = mapi_msgstore_openentry($store, $parententryid);
$this->notifyParentFolder($store, $sfolder, $parentFolder);
$this->sendFeedback(true);
}
/**
* Notify the parent folder about restoration.
*
* @param resource $store MAPI message store
* @param resource $folder folder containing the restored folder
* @param resource $parentFolder folder to notify
*/
public function notifyParentFolder($store, $folder, $parentFolder) {
/* when we restore any folder from soft deleted system then we are actually copying the folder, so at that time entryid of
* folder gets changed and we don't have notification system to get new entryid, so to notify client about changes we need to
* notify all subfolders of parent folder where we have restored the folder
*/
$hierarchyTable = mapi_folder_gethierarchytable($folder, CONVENIENT_DEPTH | MAPI_DEFERRED_ERRORS);
mapi_table_sort($hierarchyTable, [PR_DISPLAY_NAME => TABLE_SORT_ASCEND], TBL_BATCH);
$subfolders = mapi_table_queryallrows($hierarchyTable, [PR_ENTRYID]);
foreach ($subfolders as $subfolder) {
$folderObject = mapi_msgstore_openentry($store, $subfolder[PR_ENTRYID]);
$folderProps = mapi_getprops($folderObject, [PR_ENTRYID, PR_STORE_ENTRYID]);
$GLOBALS["bus"]->notify(bin2hex((string) $subfolder[PR_ENTRYID]), OBJECT_SAVE, $folderProps);
}
$folderProps = mapi_getprops($parentFolder, [PR_ENTRYID, PR_STORE_ENTRYID]);
$GLOBALS["bus"]->notify(bin2hex((string) $folderProps[PR_ENTRYID]), OBJECT_SAVE, $folderProps);
}
}
@@ -0,0 +1,372 @@
<?php
/*
* SPDX-FileCopyrightText: Copyright 2020 - 2026 grommunio GmbH
* SPDX-FileCopyrightText: Copyright 2016 Kopano and its licensors
* SPDX-FileCopyrightText: Copyright 2005 - 2016 Zarafa B.V. and its licensors
* SPDX-License-Identifier: AGPL-3.0-or-later
*/
/**
* Rules Module
* Module will be used to save rules information to rules table.
*/
class RulesModule extends Module {
/**
* @var resource rules modification table
*/
private $rulesFolder;
/**
* Constructor.
*
* @param int $id unique id
* @param array $data list of all actions
*/
public function __construct($id, $data) {
$this->properties = $GLOBALS['properties']->getRulesProperties();
$this->rulesFolder = null;
parent::__construct($id, $data);
}
/**
* Executes all the actions in the $data variable.
*/
#[Override]
public function execute() {
$locks = [];
foreach ($this->storeEntryIds() as $storeEntryId) {
$lock = new State('rules-write', 'store_' . hash('sha256', $storeEntryId));
if (!$lock->open()) {
throw new RuntimeException('Unable to lock the mail filters');
}
$locks[] = $lock;
}
try {
$this->executeLocked();
}
finally {
foreach (array_reverse($locks) as $lock) {
$lock->close();
}
}
}
/**
* Sorted hex entryids of the stores addressed by this request.
*/
private function storeEntryIds() {
$ids = [];
foreach ($this->data as $action) {
if (!isset($action[0]) && isset($action['props'])) {
$action = [$action];
}
$id = isset($action[0]) ? ($action[0]['message_action']['store_entryid'] ?? null) : ($action['store_entryid'] ?? null);
if (is_string($id) && $id !== '') {
$ids[strtolower($id)] = strtolower($id);
}
}
sort($ids);
return $ids;
}
private function executeLocked() {
foreach ($this->data as $actionType => $action) {
// The client proxy may send rule data as an indexed array
// (multiple rules) or as a single associative array (one
// rule, unwrapped by ExtJS). Normalize to indexed form so
// the rest of the code can rely on $action[0].
if (!isset($action[0]) && isset($action['props'])) {
$action = [$action];
}
if (isset($action[0])) {
$storeEntryid = $action[0]['message_action']['store_entryid'];
}
else {
$storeEntryid = $action['store_entryid'];
}
$ownStoreEntryId = $GLOBALS['mapisession']->getDefaultMessageStoreEntryId();
try {
if (ENABLE_SHARED_RULES !== true && !$GLOBALS['entryid']->compareEntryIds($storeEntryid, $ownStoreEntryId)) {
// When the admin does not allow a user to set rules on the store of other users, but somehow
// the user still tries this (probably hacking) we will not allow this
throw new MAPIException(_('Setting mail filters on the stores of other users is not allowed.'));
}
$store = $GLOBALS['mapisession']->openMessageStore(hex2bin((string) $storeEntryid));
switch ($actionType) {
case 'list':
$rules = $this->getRules($store);
$this->addActionData('list', $rules);
$GLOBALS['bus']->addData($this->getResponseData());
break;
case 'save':
// When saving the rules, we expect _all_ rules
// to have been send. So our first task, is to
// delete all existing rules.
$this->deleteRules($store);
// Now can save all rules, note that $action can contain just a store key when
// all rules are removed.
if (isset($action[0])) {
$this->saveRules($store, $action);
}
// delete (outlook) client rules
$this->deleteOLClientRules($store);
// Respond with the full set of rules.
$rules = $this->getRules($store);
$this->addActionData('update', $rules);
$GLOBALS['bus']->addData($this->getResponseData());
break;
default:
$this->handleUnknownActionType($actionType);
}
}
catch (MAPIException $e) {
$this->processException($e, $actionType);
}
}
}
public function getRulesFolder($store = false) {
if ($store === false) {
$store = $GLOBALS['mapisession']->getDefaultMessageStore();
}
if (!$this->rulesFolder) {
$this->rulesFolder = mapi_msgstore_getreceivefolder($store);
}
return $this->rulesFolder;
}
/**
* Create a restriction to search for rules which have a rule provider
* which starts with RuleOrganizer. Outlook will generate some rules
* with PR_RULE_PROVIDER RuleOrganizer2 for client-only rules, however
* we still want to show these in the client, hence we perform a prefix
* search.
*
* @return array The restriction which should be applied to the RulesTable
* to obtain all the rules which should be shown to the user
*/
public function getRestriction() {
return [RES_CONTENT,
[
FUZZYLEVEL => FL_PREFIX | FL_IGNORECASE,
ULPROPTAG => PR_RULE_PROVIDER,
VALUE => [
PR_RULE_PROVIDER => 'RuleOrganizer',
],
],
];
}
/**
* Get all rules of a store.
*
* This function opens the rules table for the specified store, and reads
* all rules with PR_RULE_PROVIDER equal to 'RuleOrganizer'. These are the rules
* that the user sees when managing rules from Outlook.
*
* @param resource $store Store in which rules reside
*
* @return array rules data
*/
public function getRules($store) {
$rules_folder = $this->getRulesFolder($store);
$rulesTable = mapi_folder_getrulestable($rules_folder);
mapi_table_restrict($rulesTable, $this->getRestriction(), TBL_BATCH);
mapi_table_sort($rulesTable, [PR_RULE_SEQUENCE => TABLE_SORT_ASCEND], TBL_BATCH);
$rows = mapi_table_queryallrows($rulesTable, $this->properties);
$rules = [];
foreach ($rows as &$row) {
$rules[] = Conversion::mapMAPI2XML($this->properties, $row);
}
unset($row);
return ['item' => $rules];
}
/**
* Function used to delete all the rules the user currently has.
*
* @param resource $store in which we want to delete the rules
*/
public function deleteRules($store) {
$rules_folder = $this->getRulesFolder($store);
$rulesTable = mapi_folder_getrulestable($rules_folder);
mapi_table_restrict($rulesTable, $this->getRestriction(), TBL_BATCH);
mapi_table_sort($rulesTable, [PR_RULE_SEQUENCE => TABLE_SORT_ASCEND], TBL_BATCH);
$rows = mapi_table_queryallrows($rulesTable, $this->properties);
$rules = [];
foreach ($rows as &$row) {
$rules[] = [
'rowflags' => ROW_REMOVE,
'properties' => $row,
];
}
if (!empty($rules)) {
mapi_folder_modifyrules($rules_folder, $rules);
}
}
/**
* Function will be used to create/update rule in user's rules table.
* This function only usee ROW_MODIFY flag to save rules data, Which is correct when modifying existing rules
* but for adding new rules Gromox automatically checks existence of rule id and if it si not then
* use ROW_ADD flag.
*
* @param resource $store The store into which the rules must be saved
* @param array $rulesData rules data that should be deleted
*/
public function saveRules($store, $rulesData) {
if (is_assoc_array($rulesData)) {
// wrap single rule in an array
$rulesData = [$rulesData];
}
// save rules in rules table
$saveRules = [];
for ($index = 0, $len = count($rulesData); $index < $len; ++$index) {
$rule = $rulesData[$index];
if (!empty($rule['props'])) {
$rule += $rule['props'];
}
$rule = Conversion::mapXML2MAPI($this->properties, $rule);
// Always reset the PR_RULE_ID property, it is going
// to be regenerated by the server anyway, so we can safely
// discard whatever value the client has given.
$rule[PR_RULE_ID] = $index;
// provide default action and rule if client has not provided
if (empty($rule[PR_RULE_ACTIONS])) {
$rule[PR_RULE_ACTIONS] = [
[
'action' => OP_DEFER_ACTION,
'dam' => hex2bin('E0C810000120000100000000000000010000000000000001000000360000000200FFFF00000C004352756C65456C656D656E7490010000010000000000000001000000018064000000010000000000000001000000'),
],
];
}
if (empty($rule[PR_RULE_CONDITION])) {
$rule[PR_RULE_CONDITION] = [
RES_EXIST,
[
ULPROPTAG => PR_MESSAGE_CLASS,
],
];
}
if (empty($rule[PR_RULE_NAME])) {
$rule[PR_RULE_NAME] = _('Untitled rule');
}
// generate rule provider data
$rule[PR_RULE_PROVIDER_DATA] = pack('VVa*', 1, $rule[PR_RULE_ID], Conversion::UnixTimeToCOleDateTime(time()));
$saveRules[] = [
'rowflags' => ROW_ADD,
'properties' => $rule,
];
}
if (!empty($saveRules)) {
mapi_folder_modifyrules($this->getRulesFolder($store), $saveRules);
$hresult = mapi_last_hresult();
if ($hresult !== NOERROR) {
throw new MAPIException(_('Could not save rules.'), $hresult);
}
}
}
/**
* Function will delete (outlook) client rules. Outlook maintains client rules
* in associated table of inbox, When we create/delete/update rule from webapp
* it won't match with outlook's client rules, so it will confuse outlook and
* it will ask user to preserve whether client or server side rules, so every time
* we save rules we need to remove this outlook generated client rule to remove
* ambigiuty.
*
* @param resource $store (optional) current user's store
*/
public function deleteOLClientRules($store = false) {
if ($store === false) {
$store = $GLOBALS['mapisession']->getDefaultMessageStore();
}
$inbox = mapi_msgstore_getreceivefolder($store);
// get inbox' associatedTable
$associatedTable = mapi_folder_getcontentstable($inbox, MAPI_ASSOCIATED);
mapi_table_restrict(
$associatedTable,
[RES_CONTENT,
[
FUZZYLEVEL => FL_FULLSTRING | FL_IGNORECASE,
ULPROPTAG => PR_MESSAGE_CLASS,
VALUE => [
PR_MESSAGE_CLASS => "IPM.RuleOrganizer",
],
],
]
);
$messages = mapi_table_queryallrows($associatedTable, [PR_ENTRYID]);
$deleteMessages = [];
for ($i = 0, $len = count($messages); $i < $len; ++$i) {
array_push($deleteMessages, $messages[$i][PR_ENTRYID]);
}
if (!empty($deleteMessages)) {
mapi_folder_deletemessages($inbox, $deleteMessages);
}
}
/**
* Function does customization of MAPIException based on module data.
* like, here it will generate display message based on actionType
* for particular exception.
*
* @param object $e exception object
* @param string $actionType the action type, sent by the client
* @param resource $store MAPI store containing the message
* @param string $parententryid parent entryid of the message
* @param string $entryid entryid of the message/folder
* @param array $action the action data, sent by the client
*/
#[Override]
public function handleException(&$e, $actionType = null, $store = null, $parententryid = null, $entryid = null, $action = null) {
if (is_null($e->displayMessage)) {
switch ($actionType) {
case 'list':
$e->setDisplayMessage(_('Could not load rules.'));
break;
case 'save':
$e->setDisplayMessage(_('Could not save rules.'));
break;
}
}
}
}
@@ -0,0 +1,234 @@
<?php
/*
* SPDX-FileCopyrightText: Copyright 2020 - 2026 grommunio GmbH
* SPDX-FileCopyrightText: Copyright 2016 Kopano and its licensors
* SPDX-FileCopyrightText: Copyright 2005 - 2016 Zarafa B.V. and its licensors
* SPDX-License-Identifier: AGPL-3.0-or-later
*/
/**
* Settings Module.
*/
class SettingsModule extends Module {
private const FILES_ACCOUNT_SETTINGS = 'grommunio/v1/plugins/files/accounts';
/**
* Constructor.
*
* @param int $id unique id
* @param array $data list of all actions
*/
public function __construct($id, $data) {
parent::__construct($id, $data);
}
#[Override]
protected function getExecutionLockName() {
foreach ($this->data as $actionType => $action) {
if ($actionType === 'set') {
if ($this->settingsTouchFilesAccounts($action['setting'] ?? null, true)) {
return 'files';
}
}
elseif (($actionType === 'delete' || $actionType === 'reset') &&
$this->settingsTouchFilesAccounts($action['setting'] ?? null, false)) {
return 'files';
}
}
return null;
}
/**
* Check whether a settings action overlaps the Files account tree.
*
* @param mixed $settings
* @param mixed $withValues
*/
private function settingsTouchFilesAccounts($settings, $withValues) {
if ($withValues) {
if (isset($settings['path'])) {
$settings = [$settings];
}
if (!is_array($settings)) {
return false;
}
$paths = [];
foreach ($settings as $setting) {
if (is_array($setting) && isset($setting['path']) && is_string($setting['path'])) {
$paths[] = $setting['path'];
}
}
}
else {
$paths = is_array($settings) ? $settings : [$settings];
}
foreach ($paths as $path) {
if (!is_string($path)) {
continue;
}
$path = implode('/', array_values(array_filter(explode('/', $path), static fn ($key) => $key !== '')));
if ($path === self::FILES_ACCOUNT_SETTINGS ||
str_starts_with($path, self::FILES_ACCOUNT_SETTINGS . '/') ||
str_starts_with(self::FILES_ACCOUNT_SETTINGS, $path . '/')) {
return true;
}
}
return false;
}
/**
* Executes all the actions in the $data variable.
*
* All setting mutations (set, delete, reset) are applied first and
* then flushed to the MAPI store in a single saveSettings() /
* savePersistentSettings() call at the end, avoiding redundant
* MAPI round-trips when multiple action types arrive in the same
* HTTP request (e.g. a batched delete + set).
*/
#[Override]
public function execute() {
$needsSave = false;
$needsPersistentSave = false;
foreach ($this->data as $actionType => $action) {
if (isset($actionType)) {
try {
switch ($actionType) {
case "retrieveAll":
$this->retrieveAll($actionType);
break;
case "set":
if (isset($action["setting"])) {
$this->set($action["setting"], false, false);
$needsSave = true;
}
if (isset($action["persistentSetting"])) {
$this->set($action["persistentSetting"], true, false);
$needsPersistentSave = true;
}
break;
case "delete":
case "reset":
$renState = State::forStore('additional-ren-entryids-write');
if (!$renState->open()) {
throw new RuntimeException('Unable to lock additional folder entryids');
}
try {
$userStore = $GLOBALS['mapisession']->getDefaultMessageStore();
$inbox = mapi_msgstore_getreceivefolder($userStore);
mapi_deleteprops($inbox, [PR_ADDITIONAL_REN_ENTRYIDS_EX, PR_ADDITIONAL_REN_ENTRYIDS]);
}
finally {
$renState->close();
}
$this->delete($action["setting"], false);
$needsSave = true;
break;
default:
$this->handleUnknownActionType($actionType);
}
}
catch (MAPIException|SettingsException $e) {
$this->processException($e, $actionType);
}
}
}
// Flush all accumulated mutations to the MAPI store in one go.
if ($needsSave) {
$GLOBALS['settings']->saveSettings();
}
if ($needsPersistentSave) {
$GLOBALS['settings']->savePersistentSettings();
}
}
/**
* Function will retrieve all settings stored in PR_EC_WEBACCESS_SETTINGS_JSON property
* if property is not defined then it will return generate SettingsException but silently ignores it.
*
* @param mixed $type
*/
public function retrieveAll($type) {
$data = $GLOBALS['settings']->get();
$this->addActionData($type, $data);
$GLOBALS["bus"]->addData($this->getResponseData());
}
/**
* Function will set a value of a setting indicated by path of the setting.
*
* @param mixed $settings Object containing a $path and $value of the setting
* which must be modified
* @param bool $persistent If true the settings will be stored in the persistent settings
* as opposed to the normal settings
* @param bool $save If true the settings will be saved to the MAPI store
* immediately. Pass false to defer saving (caller is
* responsible for calling saveSettings()).
*/
public function set($settings, $persistent = false, $save = true) {
if (isset($settings)) {
// we will set the settings but wait with saving until the entire batch has been applied.
foreach (isset($settings['path']) ? [$settings] : (array) $settings as $setting) {
if (isset($setting['path'], $setting['value'])) {
if ((bool) $persistent) {
$GLOBALS['settings']->setPersistent($setting['path'], $setting['value']);
}
else {
$GLOBALS['settings']->set($setting['path'], $setting['value']);
}
}
}
if ($save) {
// Save the settings to the MAPI store.
if ((bool) $persistent) {
$GLOBALS['settings']->savePersistentSettings();
}
else {
$GLOBALS['settings']->saveSettings();
}
}
// send success notification to client
$this->sendFeedback(true);
}
}
/**
* Function will delete a setting indicated by setting path.
*
* @param null|string|string[] $path path or paths of the settings to delete
* @param bool $save whether to save the settings to the MAPI store immediately
*/
public function delete($path, $save = true) {
if (isset($path)) {
// we will delete the settings but wait with saving until the entire batch has been applied.
if (is_array($path)) {
foreach ($path as $item) {
$GLOBALS['settings']->delete($item);
}
}
else {
$GLOBALS['settings']->delete($path);
}
if ($save) {
// Save the settings to the MAPI store.
$GLOBALS['settings']->saveSettings();
}
// send success notification to client
$this->sendFeedback(true);
}
}
}
@@ -0,0 +1,29 @@
<?php
/*
* SPDX-FileCopyrightText: Copyright 2020 - 2026 grommunio GmbH
* SPDX-FileCopyrightText: Copyright 2016 Kopano and its licensors
* SPDX-FileCopyrightText: Copyright 2005 - 2016 Zarafa B.V. and its licensors
* SPDX-License-Identifier: AGPL-3.0-or-later
*/
/**
* StickyNote ItemModule
* Module which opens, creates, saves and deletes an item. It
* extends the Module class.
*/
class StickyNoteItemModule extends ItemModule {
/**
* Constructor.
*
* @param int $id unique id
* @param array $data list of all actions
*/
public function __construct($id, $data) {
parent::__construct($id, $data);
$this->properties = $GLOBALS["properties"]->getStickyNoteProperties();
$this->plaintext = true;
}
}
@@ -0,0 +1,94 @@
<?php
/*
* SPDX-FileCopyrightText: Copyright 2020 - 2026 grommunio GmbH
* SPDX-FileCopyrightText: Copyright 2016 Kopano and its licensors
* SPDX-FileCopyrightText: Copyright 2005 - 2016 Zarafa B.V. and its licensors
* SPDX-License-Identifier: AGPL-3.0-or-later
*/
/**
* StickyNote Module.
*/
class StickyNoteListModule extends ListModule {
/**
* Constructor.
*
* @param int $id unique id
* @param array $data list of all actions
*/
public function __construct($id, $data) {
parent::__construct($id, $data);
$this->properties = $GLOBALS["properties"]->getStickyNoteListProperties();
$this->start = 0;
}
/**
* Creates the notifiers for this module,
* and register them to the Bus.
*/
public function createNotifiers() {
$entryid = $this->getEntryID();
$GLOBALS["bus"]->registerNotifier('stickynotelistnotifier', $entryid);
}
/**
* Executes all the actions in the $data variable.
*/
#[Override]
public function execute() {
foreach ($this->data as $actionType => $action) {
if (isset($actionType)) {
try {
$store = $this->getActionStore($action);
$entryid = $this->getActionSingleEntryID($action);
if ($store === false || is_array($store)) {
$this->sendFeedback(false);
continue;
}
switch ($actionType) {
case "list":
$this->messageList($store, $entryid, $action, $actionType);
break;
case "search":
$this->search($store, $entryid, $action, $actionType);
break;
case "updatesearch":
$this->updatesearch($store, $entryid, $action);
break;
case "stopsearch":
$this->stopSearch($store, $entryid, $action);
break;
default:
$this->handleUnknownActionType($actionType);
}
}
catch (MAPIException $e) {
$this->processException($e, $actionType);
}
}
}
}
/**
* Function will be used to process private items in a list response,
* sticky notes doesn't have private items so function is overridden to not do
* any processing.
*
* @param array $item item properties
*
* @return array unchanged item properties
*/
#[Override]
public function processPrivateItem($item) {
return $item;
}
}
@@ -0,0 +1,410 @@
<?php
/*
* SPDX-FileCopyrightText: Copyright 2020 - 2026 grommunio GmbH
* SPDX-FileCopyrightText: Copyright 2016 Kopano and its licensors
* SPDX-FileCopyrightText: Copyright 2005 - 2016 Zarafa B.V. and its licensors
* SPDX-License-Identifier: AGPL-3.0-or-later
*/
/**
* suggestEmailAddressModule.
*
* Class is used to store/retrieve suggestion list entries from a mapi property PR_EC_RECIPIENT_HISTORY_JSON
* on default store. The format of recipient history that is stored in this property is shown below
* {
* recipients : [
* 'display_name' : 'foo bar',
* 'smtp_address' : 'foo@local.com',
* 'count' : 1,
* 'last_used' : 1232313121,
* 'object_type' : 6 // MAPI_MAILUSER
* ]
* }
*/
class suggestEmailAddressModule extends Module {
public const MAX_SUGGESTIONS = 10;
// Shorter queries match too much of a large address book to be useful.
public const DIRECTORY_MIN_CHARS = 3;
#[Override]
protected function getExecutionLockName() {
return null;
}
public function __construct($id, $data) {
parent::__construct($id, $data);
}
#[Override]
public function execute() {
$actionType = null;
$historyState = false;
if (isset($this->data['delete'])) {
$historyState = State::forStore('recipient-history-write');
if (!$historyState->open()) {
throw new RuntimeException('Unable to lock recipient history for writing');
}
}
try {
// Retrieve the recipient history
$storeProps = mapi_getprops($GLOBALS["mapisession"]->getDefaultMessageStore(), [PR_EC_RECIPIENT_HISTORY_JSON]);
$recipient_history = [];
$datastring = readMapiProp($GLOBALS["mapisession"]->getDefaultMessageStore(), PR_EC_RECIPIENT_HISTORY_JSON, $storeProps);
if (!empty($datastring)) {
$decodedHistory = json_decode_data($datastring, true);
if (is_array($decodedHistory)) {
$recipient_history = $decodedHistory;
}
}
foreach ($this->data as $actionType => $action) {
if (isset($actionType)) {
switch ($actionType) {
case 'delete':
$this->deleteRecipient($action, $recipient_history);
break;
case 'list':
$data = $this->getRecipientList($action, $recipient_history);
// Pass data on to be returned to the client
$this->addActionData("list", $data);
$GLOBALS["bus"]->addData($this->getResponseData());
break;
}
}
}
}
catch (MAPIException $e) {
$this->processException($e, $actionType);
}
finally {
if ($historyState instanceof State) {
$historyState->close();
}
}
}
public static function cmpSortResultList($a, $b) {
if ($a['count'] < $b['count']) {
return 1;
}
if ($a['count'] > $b['count']) {
return -1;
}
$l_iReturnVal = strnatcasecmp((string) $a['display_name'], (string) $b['display_name']);
if ($l_iReturnVal == 0) {
$l_iReturnVal = strnatcasecmp((string) $a['smtp_address'], (string) $b['smtp_address']);
}
return $l_iReturnVal;
}
/**
* Function is used to delete a recipient entry from already stored recipient history
* in mapi property. it searches for deleteRecipients key in the action array which will
* contain email addresses of recipients that should be deleted in semicolon separated format.
*
* @param array $action action data in associative array format
* @param array $recipient_history recipient history stored in mapi property
*/
public function deleteRecipient($action, $recipient_history) {
if (isset($action) && !empty($recipient_history) && !empty($recipient_history['recipients'])) {
/*
* A foreach is used instead of a normal for-loop to
* prevent the loop from finishing before the end of
* the array, because of the unsetting of elements
* in that array.
*/
foreach ($recipient_history['recipients'] as $index => $recipient) {
if ($action['email_address'] == $recipient['email_address'] || $action['smtp_address'] == $recipient['smtp_address']) {
unset($recipient_history['recipients'][$index]);
}
}
// Re-indexing recipients' array to adjust index of deleted recipients
$recipient_history['recipients'] = array_values($recipient_history['recipients']);
// Write new recipient history to property
$l_sNewRecipientHistoryJSON = json_encode($recipient_history);
writeMapiPropStream($GLOBALS["mapisession"]->getDefaultMessageStore(), PR_EC_RECIPIENT_HISTORY_JSON, $l_sNewRecipientHistoryJSON);
mapi_savechanges($GLOBALS["mapisession"]->getDefaultMessageStore());
}
// send success message to client
$this->sendFeedback(true);
}
/**
* Function is used to get recipient history from mapi property based
* on the query specified by the client in action array.
*
* @param array $action action data in associative array format
* @param array $recipient_history recipient history stored in mapi property
*
* @return array data holding recipients that matched the query
*/
public function getRecipientList($action, $recipient_history) {
$data = $this->getHistoryList($action, $recipient_history);
$data['directory_searched'] = false;
$query = trim((string) ($action['query'] ?? ''));
$free = self::MAX_SUGGESTIONS - count($data['results']);
if ($free > 0 && ENABLE_DIRECTORY_SUGGESTIONS && ($action['directory'] ?? true) !== false &&
mb_strlen($query) >= self::DIRECTORY_MIN_CHARS) {
$known = [];
foreach ($data['results'] as $recipient) {
$known[strtolower((string) $recipient['smtp_address'])] = true;
}
foreach ($this->getDirectoryRecipients($query, $free, $known) as $recipient) {
$recipient['id'] = count($data['results']) + 1;
$data['results'][] = $recipient;
}
$data['directory_searched'] = true;
}
return $data;
}
/**
* Look the query up in the global address book and then in the default contacts
* folder, each with a single restricted table query of at most $limit rows.
*
* @param string $query search text
* @param int $limit maximum number of entries
* @param array $known lowercase SMTP addresses already suggested
*
* @return array suggestion entries, marked with source 'directory'
*/
public function getDirectoryRecipients($query, $limit, $known) {
$results = [];
$add = function ($entry) use (&$results, &$known, $limit) {
$key = strtolower((string) $entry['smtp_address']);
if ($key === '' || isset($known[$key]) || count($results) >= $limit) {
return;
}
$known[$key] = true;
$results[] = $entry + ['count' => 0, 'last_used' => 0, 'source' => 'directory'];
};
$match = fn ($tags) => [RES_OR, array_map(fn ($tag) => [RES_CONTENT,
[FUZZYLEVEL => FL_SUBSTRING | FL_IGNORECASE, ULPROPTAG => $tag, VALUE => $query]], $tags)];
try {
$ab = $GLOBALS['mapisession']->getAddressbook();
// The table lives only as long as its container, so keep it referenced.
$gal = mapi_ab_openentry($ab, mapi_ab_getdefaultdir($ab));
$table = mapi_folder_getcontentstable($gal, MAPI_DEFERRED_ERRORS);
mapi_table_restrict($table, $match([PR_DISPLAY_NAME, PR_SMTP_ADDRESS, PR_ACCOUNT]), TBL_BATCH);
$rows = mapi_table_queryrows($table, [PR_ENTRYID, PR_DISPLAY_NAME, PR_SMTP_ADDRESS, PR_EMAIL_ADDRESS,
PR_ADDRTYPE, PR_OBJECT_TYPE, PR_DISPLAY_TYPE, PR_DISPLAY_TYPE_EX, PR_SEARCH_KEY], 0, $limit);
foreach ($rows as $row) {
$add([
'entryid' => bin2hex((string) $row[PR_ENTRYID]),
'search_key' => isset($row[PR_SEARCH_KEY]) ? bin2hex((string) $row[PR_SEARCH_KEY]) : '',
'display_name' => $row[PR_DISPLAY_NAME] ?? '',
'smtp_address' => $row[PR_SMTP_ADDRESS] ?? '',
'email_address' => $row[PR_EMAIL_ADDRESS] ?? ($row[PR_SMTP_ADDRESS] ?? ''),
'address_type' => $row[PR_ADDRTYPE] ?? 'SMTP',
'object_type' => $row[PR_OBJECT_TYPE] ?? MAPI_MAILUSER,
'display_type' => $row[PR_DISPLAY_TYPE] ?? DT_MAILUSER,
'display_type_ex' => $row[PR_DISPLAY_TYPE_EX] ?? DT_MAILUSER,
]);
}
}
catch (MAPIException $e) {
$e->setHandled();
}
if (count($results) >= $limit) {
return $results;
}
try {
$store = $GLOBALS['mapisession']->getDefaultMessageStore();
$root = mapi_msgstore_openentry($store);
$contactsId = mapi_getprops($root, [PR_IPM_CONTACT_ENTRYID])[PR_IPM_CONTACT_ENTRYID] ?? null;
if ($contactsId === null) {
return $results;
}
$props = getPropIdsFromStrings($store, [
'email_address_1' => 'PT_STRING8:PSETID_Address:' . PidLidEmail1EmailAddress,
'email_address_2' => 'PT_STRING8:PSETID_Address:' . PidLidEmail2EmailAddress,
'email_address_3' => 'PT_STRING8:PSETID_Address:' . PidLidEmail3EmailAddress,
]);
$emails = [$props['email_address_1'], $props['email_address_2'], $props['email_address_3']];
$contacts = mapi_msgstore_openentry($store, $contactsId);
$table = mapi_folder_getcontentstable($contacts, MAPI_DEFERRED_ERRORS);
mapi_table_restrict($table, [RES_AND, [
[RES_PROPERTY, [RELOP => RELOP_EQ, ULPROPTAG => PR_MESSAGE_CLASS, VALUE => 'IPM.Contact']],
$match(array_merge([PR_DISPLAY_NAME], $emails)),
]], TBL_BATCH);
foreach (mapi_table_queryrows($table, array_merge([PR_DISPLAY_NAME], $emails), 0, $limit) as $row) {
foreach ($emails as $tag) {
if (!empty($row[$tag]) && str_contains((string) $row[$tag], '@')) {
$add([
'display_name' => $row[PR_DISPLAY_NAME] ?? $row[$tag],
'smtp_address' => $row[$tag],
'email_address' => $row[$tag],
'address_type' => 'SMTP',
'object_type' => MAPI_MAILUSER,
]);
}
}
}
}
catch (MAPIException $e) {
$e->setHandled();
}
return $results;
}
/**
* Match the query against the stored recipient history.
*
* @param array $action action data in associative array format
* @param array $recipient_history recipient history stored in mapi property
*
* @return array data holding recipients that matched the query
*/
private function getHistoryList($action, $recipient_history) {
if (!empty($action["query"]) && !empty($recipient_history) && !empty($recipient_history['recipients'])) {
// Setup result array with match levels
$l_aResult = [
0 => [],
1 => [],
];
// Track seen email addresses to skip duplicates
$seen = [];
$l_sSearchString = strtolower((string) $action["query"]);
// Loop through all the recipients
for ($i = 0, $len = count($recipient_history['recipients']); $i < $len; ++$i) {
$entry = $recipient_history['recipients'][$i];
// Prepare strings for case sensitive search
$l_sName = strtolower((string) $entry['display_name']);
$l_sEmail = strtolower((string) $entry['smtp_address']);
// Deduplicate by smtp_address (case-insensitive)
$dedupeKey = $l_sEmail !== '' ? $l_sEmail : strtolower((string) $entry['email_address']);
if ($dedupeKey !== '' && isset($seen[$dedupeKey])) {
// Keep the entry with the higher count
$prevLevel = $seen[$dedupeKey][0];
$prevIndex = $seen[$dedupeKey][1];
$prevCount = $l_aResult[$prevLevel][$prevIndex]['count'] ?? 0;
if (($entry['count'] ?? 0) > $prevCount) {
// Replace previous entry with this one
unset($l_aResult[$prevLevel][$prevIndex]);
}
else {
continue;
}
}
// Check for the presence of the search string
$l_ibPosName = strpos($l_sName, $l_sSearchString);
$l_ibPosEmail = strpos($l_sEmail, $l_sSearchString);
// Check if the string is present in name or email fields
if ($l_ibPosName !== false || $l_ibPosEmail !== false) {
// Check if the found string matches from the start of the word
if ($l_ibPosName === 0 || substr($l_sName, $l_ibPosName - 1, 1) == ' ' || $l_ibPosEmail === 0 || substr($l_sEmail, $l_ibPosEmail - 1, 1) == ' ') {
$idx = count($l_aResult[0]);
$l_aResult[0][$idx] = [
'display_name' => $entry['display_name'],
'smtp_address' => $entry['smtp_address'],
'email_address' => $entry['email_address'],
'address_type' => $entry['address_type'],
'count' => $entry['count'],
'last_used' => $entry['last_used'],
'object_type' => $entry['object_type'],
];
if ($dedupeKey !== '') {
$seen[$dedupeKey] = [0, $idx];
}
// Does not match from start of a word, but start in the middle
}
else {
$idx = count($l_aResult[1]);
$l_aResult[1][$idx] = [
'display_name' => $entry['display_name'],
'smtp_address' => $entry['smtp_address'],
'email_address' => $entry['email_address'],
'address_type' => $entry['address_type'],
'count' => $entry['count'],
'last_used' => $entry['last_used'],
'object_type' => $entry['object_type'],
];
if ($dedupeKey !== '') {
$seen[$dedupeKey] = [1, $idx];
}
}
}
}
// Re-index after potential unset operations
$l_aResult[0] = array_values($l_aResult[0]);
$l_aResult[1] = array_values($l_aResult[1]);
// Prevent the displaying of the exact match of the whole email address when only one item is found.
if (count($l_aResult[0]) == 1 && empty($l_aResult[1]) && $l_sSearchString == strtolower((string) $l_aResult[0][0]['smtp_address'])) {
$recipientList = [];
}
else {
/**
* Sort lists.
*
* This block of code sorts the two lists and creates one final list.
* The first list holds the matches based on whole words or words
* beginning with the search string and the second list contains the
* partial matches that start in the middle of the words.
* The first list is sorted on count (the number of emails sent to this
* email address), name and finally on the email address. This is done
* by a natural sort. When this first list already contains the maximum
* number of returned items the second list needs no sorting. If it has
* fewer items, the second list is sorted and included in the first list
* as well. At the end the final list is sorted on name and email again.
*/
$l_iMaxNumListItems = self::MAX_SUGGESTIONS;
$l_aSortedList = [];
usort($l_aResult[0], [self::class, 'cmpSortResultList']);
for ($i = 0, $len = min($l_iMaxNumListItems, count($l_aResult[0])); $i < $len; ++$i) {
$l_aSortedList[] = $l_aResult[0][$i];
}
if (count($l_aSortedList) < $l_iMaxNumListItems) {
$l_iMaxNumRemainingListItems = $l_iMaxNumListItems - count($l_aSortedList);
usort($l_aResult[1], [self::class, 'cmpSortResultList']);
for ($i = 0, $len = min($l_iMaxNumRemainingListItems, count($l_aResult[1])); $i < $len; ++$i) {
$l_aSortedList[] = $l_aResult[1][$i];
}
}
$recipientList = [];
foreach ($l_aSortedList as $index => $recipient) {
$recipient['id'] = count($recipientList) + 1;
$recipientList[] = $recipient;
}
}
$data = [
'query' => $action["query"],
'results' => $recipientList,
];
}
else {
$data = [
'query' => $action["query"],
'results' => [],
];
}
return $data;
}
}
@@ -0,0 +1,380 @@
<?php
/*
* SPDX-FileCopyrightText: Copyright 2020 - 2026 grommunio GmbH
* SPDX-FileCopyrightText: Copyright 2016 Kopano and its licensors
* SPDX-FileCopyrightText: Copyright 2005 - 2016 Zarafa B.V. and its licensors
* SPDX-License-Identifier: AGPL-3.0-or-later
*/
/**
* Task ItemModule
* Module which opens, creates, saves and deletes an item. It
* extends the Module class.
*/
class TaskItemModule extends ItemModule {
/**
* Constructor.
*
* @param int $id unique id
* @param array $data list of all actions
*/
public function __construct($id, $data) {
parent::__construct($id, $data);
$this->properties = $GLOBALS["properties"]->getTaskProperties();
$this->plaintext = false;
}
#[Override]
public function open($store, $entryid, $action) {
$data = [];
$message = $GLOBALS['operations']->openMessage($store, $entryid);
if (empty($message)) {
return;
}
// Open embedded message if requested
$attachNum = !empty($action['attach_num']) ? $action['attach_num'] : false;
if ($attachNum) {
// get message props of sub message
$parentMessage = $message;
$message = $GLOBALS['operations']->openMessage($store, $entryid, $attachNum);
if (empty($message)) {
return;
}
$data['item'] = $GLOBALS['operations']->getEmbeddedMessageProps($store, $message, $this->properties, $parentMessage, $attachNum);
}
else {
$data['item'] = $GLOBALS['operations']->getMessageProps($store, $message, $this->properties, $this->plaintext, true);
$tr = new TaskRequest($store, $message, $GLOBALS['mapisession']->getSession());
if ($tr->isTaskRequest() || $tr->isTaskRequestResponse()) {
$tr->isTaskRequest() ? $tr->processTaskRequest() : $tr->processTaskResponse();
$task = $tr->getAssociatedTask(false);
$action["message_action"]["open_task"] = true;
$data = $this->getMessageProps($store, $entryid, $action, $task);
$data['item']['props']['task_not_found'] = ($task === false);
}
}
$this->addActionData('item', $data);
$GLOBALS['bus']->addData($this->getResponseData());
}
/**
* Open a task request and collect its message properties. If message_action
* "open_task" is true, open the associated task and return its data;
* otherwise, return the task-request data.
*
* @param resource $store MAPI message store
* @param string $entryid entry ID of the message
* @param array $action action data sent by the client
* @param false|resource $task associated task, or false when unavailable
*
* @return array $data item properties of given message
*/
public function getMessageProps($store, $entryid, $action, $task) {
$data = [];
if (isset($action["message_action"]["open_task"]) && $action["message_action"]["open_task"] && $task !== false) {
$taskProps = mapi_getprops($task, [PR_ENTRYID, PR_PARENT_ENTRYID, PR_STORE_ENTRYID]);
$message = $GLOBALS['operations']->openMessage($store, $taskProps[PR_ENTRYID]);
}
else {
$message = $GLOBALS['operations']->openMessage($store, $entryid);
}
$data['item'] = $GLOBALS['operations']->getMessageProps($store, $message, $this->properties, $this->plaintext, true);
return $data;
}
/**
* Function which saves an item.
*
* @param false|resource $store MAPI message store, or false to use the default
* @param false|string $parententryid parent entry ID, or false to infer it
* @param false|string $entryid entry ID of the message, or false for a new item
* @param array $action action data sent by the client
* @param string $actionType action type that triggered the save
*/
#[Override]
public function save($store, $parententryid, $entryid, $action, $actionType = 'save') {
if (isset($action["props"])) {
if ($store === false && !$parententryid) {
if (isset($action["props"]["message_class"])) {
$store = $GLOBALS["mapisession"]->getDefaultMessageStore();
$parententryid = $this->getDefaultFolderEntryID($store, $action["props"]["message_class"]);
}
}
if ($store !== false && $parententryid) {
// Set the message flag for the item
if (isset($action['props']['message_flags']) && $entryid) {
$GLOBALS['operations']->setMessageFlag($store, $entryid, $action['props']['message_flags']);
}
$messageProps = $this->saveTask($store, $parententryid, $entryid, $action);
if ($messageProps) {
$send = $action["message_action"]["send"] ?? false;
$message = $GLOBALS['operations']->openMessage($store, $messageProps[PR_ENTRYID]);
$data = $GLOBALS['operations']->getMessageProps($store, $message, $this->properties, $this->plaintext, true);
// taskupdates property true if assigner as checked "Keep copy of task in task list" checkbox.
// if it is not checked then it means user don't want assigned task copy in his task list.
if ($send && isset($data["props"]['taskupdates']) && $data["props"]['taskupdates'] === false) {
// Hard delete the task if taskupdates property is not true.
$folder = mapi_msgstore_openentry($store, $parententryid);
mapi_folder_deletemessages($folder, [$messageProps[PR_ENTRYID]], DELETE_HARD_DELETE);
$data = Conversion::mapMAPI2XML($this->properties, $messageProps);
$GLOBALS["bus"]->notify(bin2hex($parententryid), TABLE_DELETE, $messageProps);
}
else {
$GLOBALS["bus"]->notify(bin2hex($parententryid), TABLE_SAVE, $messageProps);
}
// Notify To-Do list folder as new task item was created.
$todoListEntryId = TodoList::getEntryId();
if ($todoListEntryId !== false) {
$GLOBALS["bus"]->notify(bin2hex($todoListEntryId), OBJECT_SAVE, $messageProps);
}
$this->addActionData("update", ["item" => $data]);
$GLOBALS["bus"]->addData($this->getResponseData());
}
}
}
}
/**
* Function which deletes an item.
*
* @param false|resource $store MAPI message store, or false when unavailable
* @param false|string $parententryid parent entry ID, or false when unavailable
* @param array|false|string $entryids entry IDs to delete, or false when unavailable
* @param array $action action data sent by the client
*/
#[Override]
public function delete($store, $parententryid, $entryids, $action) {
if ($entryids === false) {
return;
}
if ($store !== false && $parententryid) {
$props = [];
$props[PR_PARENT_ENTRYID] = $parententryid;
$props[PR_ENTRYID] = $entryids;
$storeprops = mapi_getprops($store, [PR_ENTRYID]);
$props[PR_STORE_ENTRYID] = $storeprops[PR_ENTRYID];
// A plain task delete moves the task to the wastebasket (see
// deleteTask), so snapshot the undo information beforehand just
// like ItemModule::delete does. Occurrence deletions and
// task-request declines are not tracked (the client never asks to
// track them, as they carry an action_type).
$soft = $action['message_action']['soft_delete'] ?? false;
$undoInfo = $this->prepareDeleteUndo($store, $parententryid, $entryids, $action, $soft);
$result = $this->deleteTask($store, $parententryid, $entryids, $action);
if ($result) {
if (isset($result['occurrenceDeleted']) && $result['occurrenceDeleted']) {
// Occurrence deleted, update item
$GLOBALS["bus"]->notify(bin2hex($parententryid), TABLE_SAVE, $props);
$this->sendFeedback(true);
}
else {
$GLOBALS["bus"]->notify(bin2hex($parententryid), TABLE_DELETE, $props);
$this->sendFeedback(true, $this->buildDeleteUndoFeedback($undoInfo));
}
}
}
}
/**
* Deletes a task.
*
* deletes occurrence if task is a recurring item.
*
* @param resource $store MAPI message store
* @param string $parententryid parent entry ID of the messages to delete
* @param array|string $entryids entry ID or list of entry IDs to delete
* @param array $action action data from the client
*
* @return array|bool occurrence result, or whether deleting the task succeeded
*/
public function deleteTask($store, $parententryid, $entryids, $action) {
$result = false;
$messageAction = $action["message_action"]["action_type"] ?? false;
// If user wants to delete only occurrence then delete this occurrence
if (!is_array($entryids) && $messageAction) {
$message = mapi_msgstore_openentry($store, $entryids);
if ($message) {
if ($messageAction == 'occurrence') {
$recur = new TaskRecurrence($store, $message);
$occurrenceDeleted = $recur->deleteOccurrence($action);
}
elseif ($messageAction == 'declineAndDelete' || $messageAction == 'completeAndDelete') {
$taskReq = new TaskRequest($store, $message, $GLOBALS["mapisession"]->getSession());
if ($messageAction == 'declineAndDelete') {
$taskReq->doDecline();
}
elseif ($messageAction == 'completeAndDelete') {
$taskReq->sendCompleteUpdate();
}
}
}
}
// Deleting occurrence failed, maybe that was its last occurrence, so now we delete whole series.
if (!isset($occurrenceDeleted) || !$occurrenceDeleted) {
$properties = $GLOBALS["properties"]->getTaskProperties();
foreach (is_array($entryids) ? $entryids : [$entryids] as $entryid) {
$message = mapi_msgstore_openentry($store, $entryid);
if (!$message) {
continue;
}
$goid = mapi_getprops($message, [$properties["task_goid"]]);
// If task is assigned task to assignee and user is trying to delete the task,
// remove the corresponding task request notification from the inbox.
if (!empty($goid[$properties["task_goid"]])) {
$taskReq = new TaskRequest($store, $message, $GLOBALS["mapisession"]->getSession());
$taskRequestProps = $taskReq->deleteReceivedTR();
if ($taskRequestProps) {
$GLOBALS["bus"]->notify(bin2hex((string) $taskRequestProps[PR_PARENT_ENTRYID]), TABLE_DELETE, $taskRequestProps);
}
}
}
// If softdelete is set then set it in softDelete variable and pass it for deleting message.
$softDelete = $action['message_action']['soft_delete'] ?? false;
$result = $GLOBALS["operations"]->deleteMessages($store, $parententryid, $entryids, $softDelete);
}
else {
$result = ['occurrenceDeleted' => true];
}
return $result;
}
/**
* Save task item.
*
* just one step more before saving task message that to support recurrence and task request here. We need
* to regenerate task if it is recurring and client has changed either set as complete or delete or
* given new start or end date.
*
* @param false|resource $store MAPI store of the message, or false
* @param false|string $parententryid parent folder entry ID, or false
* @param false|string $entryid entry ID of the message, or false for a new item
* @param array $action action data sent by the client
*
* @return array of PR_ENTRYID, PR_PARENT_ENTRYID and PR_STORE_ENTRYID properties of modified item
*/
public function saveTask($store, $parententryid, $entryid, $action) {
$properties = $this->properties;
$messageProps = [];
$send = $action["message_action"]["send"] ?? false;
if ($store !== false && $parententryid) {
if (isset($action["props"])) {
if (isset($action["entryid"]) && empty($action["entryid"])) {
$GLOBALS["operations"]->setSenderAddress($store, $action);
}
$props = $action["props"];
$recips = [];
if (isset($action["recipients"]) && is_array($action["recipients"])) {
$recips = $action["recipients"];
}
if (isset($action["entryid"]) && !empty($action["entryid"])) {
$message = mapi_msgstore_openentry($store, hex2bin((string) $action["entryid"]));
if ($message) {
$messageProps = mapi_getprops($message, [PR_ENTRYID, PR_PARENT_ENTRYID, PR_STORE_ENTRYID, $properties['recurring']]);
if ((isset($messageProps[$properties['recurring']]) && $messageProps[$properties['recurring']]) ||
(isset($props['recurring']) && $props['recurring'])) {
$recur = new TaskRecurrence($store, $message);
if (isset($props['recurring_reset']) && $props['recurring_reset'] == 1) {
$msgProps = $recur->setRecurrence($props);
}
elseif (isset($props['complete']) && $props['complete'] == 1) {
$msgProps = $recur->markOccurrenceComplete($props);
}
}
mapi_savechanges($message);
$messageProps = Conversion::mapXML2MAPI($properties, $props);
$message = $GLOBALS["operations"]->saveMessage($store, $entryid, $parententryid, $messageProps, $messageProps, $recips, $action['attachments'] ?? [], []);
if (isset($msgProps) && $msgProps) {
$messageProps = $msgProps;
}
}
}
else {
$messageProps = Conversion::mapXML2MAPI($properties, $props);
// New message
$copyAttachments = false;
$copyFromMessage = false;
// we need to copy the original attachments when create task from message.
if (isset($action['message_action'], $action['message_action']['source_entryid'])) {
$copyFromMessage = hex2bin($action['message_action']['source_entryid']);
$copyFromStore = hex2bin((string) $action['message_action']['source_store_entryid']);
$copyAttachments = true;
// get resources of store and message
$copyFromStore = $GLOBALS['mapisession']->openMessageStore($copyFromStore);
$copyFromMessage = $GLOBALS['operations']->openMessage($copyFromStore, $copyFromMessage);
}
$message = $GLOBALS["operations"]->saveMessage($store, $entryid, $parententryid, $messageProps, $messageProps, $recips, $action['attachments'] ?? [], [], $copyFromMessage, $copyAttachments, false, false, false);
// Set recurrence
if (isset($action['props']['recurring']) && $action['props']['recurring'] == 1) {
$recur = new TaskRecurrence($store, $message);
$recur->setRecurrence($props);
}
}
if ($message) {
$tr = new TaskRequest($store, $message, $GLOBALS["mapisession"]->getSession());
if ($send) {
$tr->sendTaskRequest(_("Task Request:") . " ");
return $messageProps;
}
if (isset($action["message_action"]["response_type"]) && $action["message_action"]["response_type"] === tdmtTaskUpd) {
$tr->doUpdate();
return $messageProps;
}
if (isset($action["message_action"]["action_type"]) && $action["message_action"]["action_type"] === "restoreToTaskList") {
$deleteTRProps = $tr->deleteReceivedTR();
if ($deleteTRProps) {
$GLOBALS["bus"]->notify(bin2hex((string) $deleteTRProps[PR_PARENT_ENTRYID]), TABLE_DELETE, $deleteTRProps);
}
return $messageProps;
}
}
mapi_savechanges($message);
}
}
// Return message properties that can be sent to the bus to notify changes
return $messageProps;
}
}
@@ -0,0 +1,86 @@
<?php
/*
* SPDX-FileCopyrightText: Copyright 2020 - 2026 grommunio GmbH
* SPDX-FileCopyrightText: Copyright 2016 Kopano and its licensors
* SPDX-FileCopyrightText: Copyright 2005 - 2016 Zarafa B.V. and its licensors
* SPDX-License-Identifier: AGPL-3.0-or-later
*/
/**
* Task Module.
*/
class TaskListModule extends ListModule {
/**
* Constructor.
*
* @param int $id unique id
* @param array $data list of all actions
*/
public function __construct($id, $data) {
parent::__construct($id, $data);
$this->properties = $GLOBALS["properties"]->getTaskGridProperties();
$this->start = 0;
}
/**
* Creates the notifiers for this module,
* and register them to the Bus.
*/
public function createNotifiers() {
$entryid = $this->getEntryID();
$GLOBALS["bus"]->registerNotifier('tasklistnotifier', $entryid);
$todoListEntryId = TodoList::getEntryId();
if ($todoListEntryId !== false) {
$GLOBALS["bus"]->registerNotifier('newtodotasknotifier', bin2hex($todoListEntryId));
}
}
/**
* Executes all the actions in the $data variable.
*/
#[Override]
public function execute() {
foreach ($this->data as $actionType => $action) {
if (isset($actionType)) {
try {
$store = $this->getActionStore($action);
$entryid = $this->getActionSingleEntryID($action);
if ($store === false || is_array($store)) {
$this->sendFeedback(false);
continue;
}
switch ($actionType) {
case "list":
$this->getDelegateFolderInfo($store);
$this->messageList($store, $entryid, $action, $actionType);
break;
case "search":
// @FIXME add handling of private items
$this->search($store, $entryid, $action, $actionType);
break;
case "updatesearch":
$this->updatesearch($store, $entryid, $action);
break;
case "stopsearch":
$this->stopSearch($store, $entryid, $action);
break;
default:
$this->handleUnknownActionType($actionType);
}
}
catch (MAPIException $e) {
$this->processException($e, $actionType);
}
}
}
}
}