814 lines
31 KiB
PHP
814 lines
31 KiB
PHP
<?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;
|
|
}
|
|
}
|