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,592 @@
<?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
*/
/**
* AttachmentState.
*
* A wrapper around the State class for handling the Attachment State file.
* This class supplies operators for correctly managing the State contents.
*/
class AttachmentState {
/**
* The basedir in which the attachments for all sessions are found.
*/
private $basedir;
/**
* The directory in which the attachments for the current session are found.
*/
private $sessiondir;
/**
* The directory in which the session files are created.
*/
private $attachmentdir = 'attachments';
/**
* The State object which refers to the Attachments state.
*/
private $state;
/**
* List of attachment files from the $state.
*/
private $files;
/**
* List of deleted attachment files from the $state.
*/
private $deleteattachment;
/**
* List of aborted attachment files while uploading is going on.
*/
private $abortedattachment;
/**
* Constructor.
*/
public function __construct() {
$this->basedir = TMP_PATH . DIRECTORY_SEPARATOR . $this->attachmentdir;
$this->sessiondir = $this->basedir . DIRECTORY_SEPARATOR . session_id();
$this->state = new State('attachments');
}
/**
* Open the session file.
*
* The session file is opened and locked so that other processes can not access the state information
*/
public function open() {
$this->ensureSessionDir();
$this->state->open();
$this->files = $this->state->read('files');
$this->deleteattachment = $this->state->read('deleteattachment');
$this->abortedattachment = $this->state->read('abortedattachment');
// Check if any aborted attachments are pending to be removed
if (!empty($this->abortedattachment)) {
// Remove aborted attachments
$this->removeAbortedAttachments();
}
}
/**
* Create the session attachment folder when it does not exist yet.
*/
private function ensureSessionDir() {
if (!is_dir($this->sessiondir)) {
mkdir($this->sessiondir, 0755, true /* recursive */);
}
}
/**
* Checks if any information regarding attachments is stored in this attachment state.
*
* @param string $message_id The unique identifier for referencing the attachments for a single message
*
* @return bool True to indicate if any changes needed to save in message else false
*/
public function isChangesPending($message_id) {
$files = $this->getAttachmentFiles($message_id);
$deletedfiles = $this->getDeletedAttachments($message_id);
if (empty($files) && empty($deletedfiles)) {
return false;
}
return true;
}
/**
* Obtain the folder in which the attachments for the current session
* can be found. All handling of attachments will be isolated to this
* folder to prevent any other user to be able to access the attachment
* files of another user.
*
* @return string The foldername in which the attachments can be found
*/
private function getAttachmentFolder() {
return $this->sessiondir;
}
/**
* Obtain the full path for a new filename on the harddisk
* This uses tempnam to generate a new filename in the default
* attachments folder.
*
* @param string $filename The file for which the temporary path is requested
*
* @return string The full path to the attachment file
*/
public function getAttachmentTmpPath($filename) {
$this->ensureSessionDir();
$attachmentPath = tempnam($this->getAttachmentFolder(), mb_basename($filename));
if ($attachmentPath === false) {
throw new GrommunioException(_('Could not attach item as an attachment.'));
}
// Convert in UTF-8 properly if any Malformed UTF-8 characters.
return (string) mb_convert_encoding($attachmentPath, 'UTF-8');
}
/**
* Obtain the full path of the given filename on the harddisk.
*
* @param string $filename The file for which the path is requested
*
* @return string The full path to the attachment file
*/
public function getAttachmentPath($filename) {
return $this->getAttachmentFolder() . DIRECTORY_SEPARATOR . mb_basename($filename);
}
/**
* Remove a temporary attachment and report cleanup failures.
*/
private function deleteTemporaryFile(string $filepath): void {
if ((is_file($filepath) || is_link($filepath)) && !@unlink($filepath)) {
error_log("Unable to remove temporary attachment file: {$filepath}");
}
}
/**
* Check if attachment file which belongs to the given $message_id
* and is identified by the given $attachid is an embedded attachment.
*
* @param string $message_id The unique identifier for referencing the
* attachments for a single message
* @param string $attachid The unique identifier for referencing the
* attachment
*
* @return bool True if attachment is an embedded else false
*/
public function isEmbeddedAttachment($message_id, $attachid) {
$attach = $this->getAttachmentFile($message_id, $attachid);
if ($attach !== false) {
if ($attach['sourcetype'] === 'embedded') {
return true;
}
}
return false;
}
/**
* Function which identifies whether an attachment is an inline or normal attachment.
*
* @param resource $attachment MAPI attachment object
*
* @return bool true if the attachment is inline, otherwise false
*/
public function isInlineAttachment($attachment) {
$props = mapi_attach_getprops($attachment, [PR_ATTACH_CONTENT_ID, PR_ATTACHMENT_HIDDEN, PR_ATTACH_FLAGS]);
$isInlineAttachmentFlag = (isset($props[PR_ATTACH_FLAGS]) && $props[PR_ATTACH_FLAGS] & 4) ? true : false;
return isset($props[PR_ATTACH_CONTENT_ID]) && $isInlineAttachmentFlag;
}
/**
* Function which identifies whether an attachment is contact photo or normal attachment.
*
* @param resource $attachment MAPI attachment object
*
* @return bool true if the attachment is a contact photo, otherwise false
*/
public function isContactPhoto($attachment) {
$attachmentProps = mapi_attach_getprops($attachment, [PR_ATTACHMENT_CONTACTPHOTO, PR_ATTACHMENT_HIDDEN]);
$isHidden = $attachmentProps[PR_ATTACHMENT_HIDDEN] ?? false;
$isAttachmentContactPhoto = $attachmentProps[PR_ATTACHMENT_CONTACTPHOTO] ?? false;
return $isAttachmentContactPhoto && $isHidden;
}
/**
* Add a file which was uploaded to the server by moving it to the attachments directory,
* and then register (addAttachmentFile) it.
*
* @param string $message_id The unique identifier for referencing the
* attachments for a single message
* @param string $filename The filename of the attachment
* @param string $uploadedfile The file which was uploaded and will be moved to the attachments directory
* @param array $fileinfo The attachment data
*
* @return string attachment identifier used to reference the file in the temporary folder
*/
public function addUploadedAttachmentFile($message_id, $filename, $uploadedfile, $fileinfo) {
// Create the destination path, the attachment must
// be placed in the attachment folder with a unique name.
$filepath = $this->getAttachmentTmpPath($filename);
// Obtain the generated filename
$tmpname = mb_basename($filepath);
move_uploaded_file($uploadedfile, $filepath);
$this->addAttachmentFile($message_id, $tmpname, $fileinfo);
return $tmpname;
}
/**
* Move a file from an alternative location to the attachments directory,
* this will call addAttachmentFile to register the attachment to the state.
*
* @param string $message_id The unique identifier for referencing the
* attachments for a single message
* @param string $filename The filename of the attachment
* @param string $sourcefile The path of the file to move to the attachments directory
* @param array $fileinfo The attachment data
*
* @return string attachment identifier used to reference the file in the temporary folder
*/
public function addProvidedAttachmentFile($message_id, $filename, $sourcefile, $fileinfo) {
// Create the destination path, the attachment must
// be placed in the attachment folder with a unique name.
$filepath = $this->getAttachmentTmpPath($filename);
// Obtain the generated filename
$tmpname = mb_basename($filepath);
$attachmentBase = realpath($this->basedir);
$attachmentFolder = realpath($this->getAttachmentFolder());
clearstatcache(true, $this->getAttachmentFolder());
$attachmentFolderStat = @lstat($this->getAttachmentFolder());
clearstatcache(true, $sourcefile);
$sourceStat = @lstat($sourcefile);
if ($attachmentBase === false || $attachmentFolder === false ||
$attachmentFolderStat === false || ($attachmentFolderStat['mode'] & 0170000) !== 0040000 ||
dirname($attachmentFolder) !== $attachmentBase || realpath(dirname($filepath)) !== $attachmentFolder ||
$sourceStat === false || ($sourceStat['mode'] & 0170000) !== 0100000) {
$this->deleteTemporaryFile($filepath);
throw new GrommunioException(_('Could not attach item as an attachment.'));
}
// Move the provided regular file into the session directory. Only register
// it after both the move and the post-move file type check succeeded.
if (!@rename($sourcefile, $filepath)) {
$this->deleteTemporaryFile($filepath);
throw new GrommunioException(_('Could not attach item as an attachment.'));
}
clearstatcache(true, $filepath);
$movedFileStat = @lstat($filepath);
if ($movedFileStat === false || ($movedFileStat['mode'] & 0170000) !== 0100000) {
$this->deleteTemporaryFile($filepath);
throw new GrommunioException(_('Could not attach item as an attachment.'));
}
$this->addAttachmentFile($message_id, $tmpname, $fileinfo);
return $tmpname;
}
/**
* Add information regarding embedded attachment to attachment state.
*
* @param string $message_id The unique identifier for referencing the
* attachments for a single message
* @param array $fileinfo The attachment data
*
* @return string attachment identifier used to reference the file in the temporary folder
*/
public function addEmbeddedAttachment($message_id, $fileinfo) {
// generate a random number to be used as unique id of attachment
$tmpname = md5(random_int(0, mt_getrandmax()));
$this->addAttachmentFile($message_id, $tmpname, $fileinfo);
return $tmpname;
}
/**
* Delete a file which was previously uploaded to the attachments directory,
* this will call removeAttachmentFile to unregister the attachment from the state.
*
* @param string $message_id The unique identifier for referencing the
* attachments for a single message
* @param string $filename The filename of the attachment to delete
* @param string $attachID The unique identifier for referencing attachment
*/
public function deleteUploadedAttachmentFile($message_id, $filename, $attachID) {
// Create the destination path, the attachment has
// previously been placed in the attachment folder
$filepath = $this->getAttachmentPath($filename);
if (is_file($filepath)) {
$this->deleteTemporaryFile($filepath);
}
$this->removeAttachmentFile($message_id, mb_basename($filepath), $attachID);
}
/**
* Obtain all files which were registered for the given $message_id.
*
* @param string $message_id The unique identifier for referencing the
* attachments for a single message
*
* @return array|false the attachments, or false when no attachments are registered
*/
public function getAttachmentFiles($message_id) {
if ($this->files && isset($this->files[$message_id])) {
return $this->files[$message_id];
}
return false;
}
/**
* Obtain a single attachment file which belongs to the given $message_id
* and is identified by the given $attachid.
*
* @param string $message_id The unique identifier for referencing the
* attachments for a single message
* @param string $attachid The unique identifier for referencing the
* attachment
*
* @return array|false the attachment description, or false when it is not registered
*/
public function getAttachmentFile($message_id, $attachid) {
if ($this->files && isset($this->files[$message_id], $this->files[$message_id][$attachid])) {
return $this->files[$message_id][$attachid];
}
return false;
}
/**
* Add an attachment file to the message.
*
* @param string $message_id The unique identifier for referencing the
* attachments for a single message
* @param string $name The name of the new attachment
* @param array $attachment The attachment data
*/
public function addAttachmentFile($message_id, $name, $attachment) {
if (!$this->files) {
$this->files = [$message_id => []];
}
elseif (!isset($this->files[$message_id])) {
$this->files[$message_id] = [];
}
$this->files[$message_id][$name] = $attachment;
}
/**
* Remove an attachment file from the message.
*
* @param string $message_id The unique identifier for referencing the
* attachments for a single message
* @param string $name The name of the attachment
* @param string $attachID The unique identifier for referencing attachment
*/
public function removeAttachmentFile($message_id, $name, $attachID) {
if ($this->files && isset($this->files[$message_id])) {
unset($this->files[$message_id][$name]);
}
// if attachID is supplied then user is trying to remove the attachment which is
// still uploading
if ($attachID) {
$found = false;
if (!empty($this->files)) {
// Loop over and find the attachment from attachID and remove the same
foreach ($this->files as $tmpDir => $attachment) {
foreach ($this->files[$tmpDir] as $tmpName => $attachmentVal) {
if ($this->files[$tmpDir][$tmpName]['attach_id'] === $attachID) {
$found = true;
$filepath = $this->getAttachmentPath($tmpName);
if (is_file($filepath)) {
$this->deleteTemporaryFile($filepath);
}
unset($this->files[$tmpDir][$tmpName]);
}
}
}
}
if (!$found) {
// if files array is empty or attachment is not found then just remember
// this particular attachment, which will be removed when attachment_state
// will be opened again.
$this->addAbortedAttachment($message_id, $attachID);
return;
}
}
}
/**
* Remove all attachment files from the message.
*
* @param string $message_id The unique identifier for referencing the
* attachments for a single message
*/
public function clearAttachmentFiles($message_id) {
if ($this->files) {
unset($this->files[$message_id]);
}
}
/**
* Obtain all files which were removed for the given $message_id.
*
* @param string $message_id The unique identifier for referencing the
* attachments for a single message
*
* @return array|false the deleted attachments, or false when none are registered
*/
public function getDeletedAttachments($message_id) {
if ($this->deleteattachment && isset($this->deleteattachment[$message_id])) {
return $this->deleteattachment[$message_id];
}
return false;
}
/**
* Add a deleted attachment file to the message.
*
* @param string $message_id The unique identifier for referencing the
* attachments for a single message
* @param string $name The name of the attachment
*/
public function addDeletedAttachment($message_id, $name) {
if (!$this->deleteattachment) {
$this->deleteattachment = [$message_id => []];
}
elseif (!isset($this->deleteattachment[$message_id])) {
$this->deleteattachment[$message_id] = [];
}
$this->deleteattachment[$message_id][] = $name;
}
/**
* Remove a deleted attachment from the message.
*
* @param string $message_id The unique identifier for referencing the
* attachments for a single message
* @param string $name The name of the attachment
*/
public function removeDeletedAttachment($message_id, $name) {
if ($this->deleteattachment && isset($this->deleteattachment[$message_id])) {
$index = array_search($name, $this->deleteattachment[$message_id]);
if ($index !== false) {
unset($this->deleteattachment[$message_id][$index]);
$this->deleteattachment[$message_id] = array_values($this->deleteattachment[$message_id]);
}
}
}
/**
* Add an aborted attachment file to the 'abortedattachment' array.
* So that it can be removed from message while it is available in 'files' array.
*
* @param string $message_id The unique identifier for referencing the
* attachments for a single message
* @param string $attachID The unique identifier for referencing attachment
*/
public function addAbortedAttachment($message_id, $attachID) {
if (!$this->abortedattachment) {
$this->abortedattachment = [$message_id => []];
}
elseif (!isset($this->abortedattachment[$message_id])) {
$this->abortedattachment[$message_id] = [];
}
$this->abortedattachment[$message_id][] = $attachID;
}
/**
* Remove an aborted attachment from the message and files list.
*/
public function removeAbortedAttachments() {
if (empty($this->files)) {
return;
}
// Loop over and find the attachment from attachID and remove the same
foreach ($this->files as $tmpDir => $attachment) {
foreach ($this->files[$tmpDir] as $tmpName => $attachmentVal) {
if (!isset($this->abortedattachment[$tmpDir])) {
continue;
}
// check if the aborted attachID is present in files array
$index = array_search($this->files[$tmpDir][$tmpName]['attach_id'], $this->abortedattachment[$tmpDir]);
if ($index !== false) {
// Remove attachment from the list of aborted attachments.
unset($this->abortedattachment[$tmpDir][$index]);
// If respective file is still there in tmp directory then remove
$filepath = $this->getAttachmentPath($tmpName);
if (is_file($filepath)) {
$this->deleteTemporaryFile($filepath);
}
// Remove attachment from state as well
unset($this->files[$tmpDir][$tmpName]);
}
}
}
}
/**
* Remove all deleted attachment files from the message.
*
* @param string $message_id The unique identifier for referencing the
* attachments for a single message
*/
public function clearDeletedAttachments($message_id) {
if ($this->deleteattachment) {
unset($this->deleteattachment[$message_id]);
}
}
/**
* Close the state and flush all information back
* to the State file on the disk.
*/
public function close() {
$this->state->write('files', $this->files, false);
$this->state->write('deleteattachment', $this->deleteattachment, false);
$this->state->write('abortedattachment', $this->abortedattachment, false);
$this->state->flush();
$this->state->close();
}
/**
* Cleans all old attachments in the attachment directory.
*
* @param int $maxLifeTime the maximum allowed age of files in seconds
*/
public function clean($maxLifeTime = UPLOADED_ATTACHMENT_MAX_LIFETIME) {
cleanTemp($this->basedir, $maxLifeTime);
// remove base directory also
if (is_dir($this->sessiondir)) {
/*
* FIXME: We should remove the folder when it is not needed,
* Because of WA-6523 this is creating an issue, so need to fix this properly
*/
// Directory should be empty to remove it, So first remove all files in the directory
/*if(function_exists("glob")) {
array_map('unlink', glob($this->sessiondir . "/*"));
}*/
rmdir($this->sessiondir);
}
}
}
@@ -0,0 +1,28 @@
<?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
*/
/**
* A class that tries to identify a browser by its fingerprint. It will try to find
* as many properties of the browser as it can, and use those to create a fingerprint.
*
* Note: This is not a very strong method to prevent stealing of sessions, but it will
* make it a little more difficult, as the attacker needs to send the same headers
* as the original user did when he created the session.
*/
class BrowserFingerprint {
public static function getFingerprint() {
$properties = [];
$properties['HTTP_ACCEPT_LANGUAGE'] = $_SERVER['HTTP_ACCEPT_LANGUAGE'] ?? 'HTTP_ACCEPT_LANGUAGE_NOT_FOUND';
$properties['HTTP_USER_AGENT'] = $_SERVER['HTTP_USER_AGENT'] ?? 'HTTP_USER_AGENT_NOT_FOUND';
$properties['REMOTE_USER'] = $_SERVER['REMOTE_USER'] ?? 'REMOTE_USER_NOT_FOUND';
return md5(json_encode($properties));
}
}
@@ -0,0 +1,801 @@
<?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.BusException.php';
/**
* Generic event bus with subscribe/notify architecture.
*
* Every notifier registers itself by this class so that it can receive events. The events represent changes in the underlying
* MAPI store like changes to folders, e-mails, calendar items, etc.
*
* A notifier can register itself for the following events:
* - OBJECT_SAVE
* - OBJECT_DELETE
*
* - TABLE_SAVE
* - TABLE_DELETE
*
* - REQUEST_START
* - REQUEST_END
*
* To use the REQUEST_* events, make sure you register your notifier with REQUEST_ENTRYID
* as the dummy entryid.
*
* Events:
*
* (The parameters that are discussed are passed to notify() and sent to the update() methods of the notifiers)
*
* <b>OBJECT_SAVE</b>
* This event is triggered when a folder object is created or modified. The entryid parameter is the entryid
* of the object that has been created or modified. The data parameter contains an array of properties of the
* object, with the following properties: PR_ENTRYID, PR_STORE_ENTRYID
*
* <b>OBJECT_DELETE</b>
* This event is triggered when a folder is deleted. The entryid parameter is the entryid of the object
* that has been deleted. The data parameter contains an array of properties of the deleted object, with
* the following properties: PR_ENTRYID, PR_STORE_ENTRYID
*
* <b>TABLE_SAVE</b>
* This event is triggered when a message item is created or modified. The entryid parameter is the entryid of the modified
* object. The data parameter contains the following properties of the modified message: PR_ENTRYID, PR_PARENT_ENTRYID,
* PR_STORE_ENTRYID
*
* <b>TABLE_DELETE</b>
* This event is triggered when a message item is deleted. The entryid parameter is the entryid of the deleted object. The
* data parameter contains the following properties of the deleted message: PR_ENTRYID, PR_PARENT_ENTRYID, PR_STORE_ENTRYID
*
* <b>REQUEST_START</b>
* This event is triggered for EVERY XML request that is done to the backend, before processing of the XML or other events.
* The entryid parameter must be the fixed value REQUEST_ENTRYID. The $data parameter is not passed.
*
* <b>REQUEST_END</b>
* This event is triggereed for EVERY XML request that is done to the backend, after all notifiers processing and will be the last
* event triggered. The entryid parameter must be that fixed value REQUEST_ENTRYID. The $data parameter is not passed.
*
* @todo The event names are rather misleading and should be renamed to FOLDER_CHANGE, FOLDER_DELETE, MESSAGE_CHANGE, MESSAGE_DELETE
* @todo The entryid is passed in $entryid AND in $data in almost all cases, which is rather wasteful
*/
class Bus {
/**
* data which is sent back to the client.
*/
private $responseData;
/**
* all registered notifiers.
*/
private $registeredNotifiers;
/**
* all registered store notifiers.
*/
private $registeredStoreNotifiers;
/**
* all notifier objects.
*/
private $notifiers;
/**
* Monotonic versions for notifier state persisted independently of the Bus.
*/
private $notifierVersions;
/**
* Registration generation observed by this request.
*/
private $synchronizedRegistrationVersion;
private $registrationStateDirty;
/**
* Constructor.
*/
public function __construct() {
$this->responseData = [];
$this->registeredNotifiers = [];
$this->registeredStoreNotifiers = [];
$this->notifiers = [];
$this->notifierVersions = [];
$this->synchronizedRegistrationVersion = null;
$this->registrationStateDirty = false;
}
/**
* Register a notifier on the bus.
*
* This will check if a instance for the given $notifierName already exists, and if
* not will instantiate it through the dispatcher. It will then use $this->registerEvent
* to register the instance for all correct events on the given $entryid(s)
*
* After a notifier is registered on the bus, it will receive updates to objects generated by the modules
* which are handling the requests. For example a notifier is registered on the inbox can receive changes
* of the item count of the inbox by specifying the entryid of the inbox here and the event
*
* @param string $notifierName class name of the notifier to register
* @param string|string[] $entryid entry ID or entry IDs on which to register the notifier
* @param bool $store whether the entry ID points to a store whose events should bubble
*/
public function registerNotifier($notifierName, $entryid, $store = false) {
if (!isset($this->notifiers[$notifierName])) {
$this->notifiers[$notifierName] = $GLOBALS["dispatcher"]->loadNotifier($notifierName);
$this->registrationStateDirty = true;
}
// Obtain the events which are supported by this notifier
$events = $this->notifiers[$notifierName]->getEvents();
if (is_array($entryid)) {
foreach ($entryid as $id) {
$this->registerEvent($notifierName, $id, $events, $store);
}
}
else {
$this->registerEvent($notifierName, $entryid, $events, $store);
}
}
/**
* Register notifier events on the bus.
*
* Called by $registerNotifier after the notifier instance was created. This function will then
* register the given $notifierName to the provided $entryid and will mark the $events for which
* this notifier should be fired.
*
* Valid values for $events are OBJECT_SAVE, OBJECT_DELETE, TABLE_SAVE, TABLE_DELETE, REQUEST_START and REQUEST_END
*
* @param string $notifierName The classname of the notifier to register
* @param string $entryid EntryID of an object coupled to the notifier
* @param number $events Bitmask of events that the notifier should receive
* @param bool $store optional If true, the $entryid points to the store and all events within the store are
* bubbled to this notifier object
*/
public function registerEvent($notifierName, $entryid, $events, $store = false) {
if (!self::isRegistrationEntryid($entryid)) {
return;
}
$entryidCmp = $GLOBALS["entryid"];
if ($store) {
$found = false;
foreach ($this->registeredStoreNotifiers as $key => &$storeNotifier) {
if ($entryidCmp->compareEntryIds($storeNotifier['entryid'], $entryid)) {
if (!isset($storeNotifier[$notifierName]['events']) || $storeNotifier[$notifierName]['events'] !== $events) {
$this->registrationStateDirty = true;
}
$storeNotifier[$notifierName] = ['events' => $events];
$found = true;
break;
}
}
unset($storeNotifier);
if (!$found) {
$this->registeredStoreNotifiers[] = [
'entryid' => $entryid,
$notifierName => ['events' => $events],
];
$this->registrationStateDirty = true;
}
}
else {
$found = false;
foreach ($this->registeredNotifiers as $key => &$folderNotifier) {
if ($entryidCmp->compareEntryIds($folderNotifier['entryid'], $entryid)) {
if (!isset($folderNotifier[$notifierName]['events']) || $folderNotifier[$notifierName]['events'] !== $events) {
$this->registrationStateDirty = true;
}
$folderNotifier[$notifierName] = ['events' => $events];
$found = true;
break;
}
}
unset($folderNotifier);
if (!$found) {
$this->registeredNotifiers[] = [
'entryid' => $entryid,
$notifierName => ['events' => $events],
];
$this->registrationStateDirty = true;
}
}
}
/**
* Broadcast an update to notifiers attached to bus.
*
* This function is used to send an update to other notifiers that have been attached to the bus via register().
*
* @param string $entryID Entryid of the object for which the event has happened
* @param int $event Event which should be fired. Can be any of OBJECT_SAVE, OBJECT_DELETE, TABLE_SAVE, TABLE_DELETE, REQUEST_START and REQUEST_END.
* @param array $data the data which is used to execute the event, which differs for each event type
*/
public function notify($entryID, $event, $data = null) {
if (!$this->synchronizePersistentState() && $event === REQUEST_START) {
throw new RuntimeException('Unable to synchronize notifier state');
}
$entryidCmp = $GLOBALS["entryid"];
// Notifiers must be get only ONE update
$updatedNotifiers = [];
// Check if there are bubbled notifiers, and if a PR_STORE_ENTRYID was provided
// on which the notifiers should be executed.
if ($entryID !== REQUEST_ENTRYID && $data && isset($data[PR_STORE_ENTRYID])) {
$storeEntryid = bin2hex($data[PR_STORE_ENTRYID]);
// Update the store notifier
foreach ($this->registeredStoreNotifiers as &$storeNotifier) {
if ($entryidCmp->compareEntryIds($storeNotifier['entryid'], $storeEntryid)) {
foreach ($storeNotifier as $notifierName => $notifier) {
if (isset($notifier['events']) && ($notifier['events'] & $event)) {
if (!isset($updatedNotifiers[$notifierName])) {
if (isset($this->notifiers[$notifierName]) && is_object($this->notifiers[$notifierName])) {
$this->updateNotifier($notifierName, $event, $entryID, $data);
$updatedNotifiers[$notifierName] = true;
}
}
}
}
break;
}
}
unset($storeNotifier);
}
// Update the notifier
foreach ($this->registeredNotifiers as &$folderNotifier) {
if (($entryID === REQUEST_ENTRYID && $folderNotifier['entryid'] === REQUEST_ENTRYID) ||
$entryidCmp->compareEntryIds($folderNotifier['entryid'], $entryID)) {
foreach ($folderNotifier as $notifierName => $notifier) {
if (isset($notifier['events']) && ($notifier['events'] & $event)) {
if (!isset($updatedNotifiers[$notifierName])) {
if (isset($this->notifiers[$notifierName]) && is_object($this->notifiers[$notifierName])) {
$this->updateNotifier($notifierName, $event, $entryID, $data);
$updatedNotifiers[$notifierName] = true;
}
}
}
}
break;
}
}
unset($folderNotifier);
}
/**
* Update one notifier against its latest persistent state.
*
* @param mixed $notifierName
* @param mixed $event
* @param mixed $entryID
* @param mixed $data
*/
private function updateNotifier($notifierName, $event, $entryID, $data) {
$notifier = $this->notifiers[$notifierName] ?? null;
if (!is_object($notifier)) {
return;
}
if (method_exists($notifier, 'usePersistentStateLock') && !$notifier->usePersistentStateLock($event)) {
$notifier->update($event, $entryID, $data);
return;
}
$stateId = $GLOBALS['request_state_id'] ?? null;
if (!is_string($stateId) || $stateId === '' || ($GLOBALS['bus'] ?? null) !== $this) {
$notifier->update($event, $entryID, $data);
return;
}
// A notifier that notifies itself must not wait for its own lock
static $updating = [];
if (isset($updating[$notifierName])) {
$notifier->update($event, $entryID, $data);
return;
}
$updating[$notifierName] = true;
try {
$this->updateNotifierLocked($notifierName, $notifier, $event, $entryID, $data, $stateId);
}
finally {
unset($updating[$notifierName]);
}
}
/**
* Run one notifier update under its persistent state lock.
*
* @param mixed $notifierName
* @param mixed $notifier
* @param mixed $event
* @param mixed $entryID
* @param mixed $data
* @param mixed $stateId
*/
private function updateNotifierLocked($notifierName, $notifier, $event, $entryID, $data, $stateId) {
$notifierState = new State('bus-notifier-' . hash('sha256', $stateId . "\0" . $notifierName));
if (!$notifierState->open()) {
if ($event === REQUEST_START) {
throw new RuntimeException('Unable to lock notifier state');
}
$notifier->update($event, $entryID, $data);
return;
}
try {
$version = isset($this->notifierVersions[$notifierName]) ? (int) $this->notifierVersions[$notifierName] : 0;
$storedNotifier = $notifierState->read('notifier');
$storedVersion = (int) $notifierState->read('version');
if (is_object($storedNotifier) && get_class($storedNotifier) === get_class($notifier) && $storedVersion > $version) {
$notifier = $this->mergeNotifierPersistentState($notifier, $storedNotifier);
$version = $storedVersion;
$this->notifiers[$notifierName] = $notifier;
}
$before = serialize($this->persistentNotifierCopy($notifier));
try {
$notifier->update($event, $entryID, $data);
}
finally {
$persistentNotifier = $this->persistentNotifierCopy($notifier);
if (serialize($persistentNotifier) !== $before) {
++$version;
$notifierState->write('notifier', $persistentNotifier, false);
$notifierState->write('version', $version, false);
$notifierState->flush();
}
$this->notifierVersions[$notifierName] = $version;
}
}
finally {
$notifierState->close();
}
}
/**
* Clone a notifier in the same reset form stored with the Bus.
*
* @param mixed $notifier
*/
private function persistentNotifierCopy($notifier) {
if (!is_object($notifier)) {
return $notifier;
}
$copy = unserialize(serialize($notifier));
$copy->reset();
return $copy;
}
/**
* Import reset-form state without replacing request-local notifier data.
*
* @param mixed $local
* @param mixed $persistent
*/
private function mergeNotifierPersistentState($local, $persistent) {
if (!is_object($local) || !is_object($persistent) || get_class($local) !== get_class($persistent)) {
return $local;
}
$resetLocal = $this->persistentNotifierCopy($local);
$reflection = new ReflectionObject($local);
do {
foreach ($reflection->getProperties() as $property) {
if ($property->getDeclaringClass()->getName() !== $reflection->getName() ||
$property->isStatic() || $property->isReadOnly()) {
continue;
}
$localInitialized = $property->isInitialized($local);
$resetInitialized = $property->isInitialized($resetLocal);
if ($localInitialized !== $resetInitialized ||
($localInitialized && serialize($property->getValue($local)) !== serialize($property->getValue($resetLocal)))) {
continue;
}
if ($property->isInitialized($persistent)) {
$property->setValue($local, $property->getValue($persistent));
}
}
$reflection = $reflection->getParentClass();
}
while ($reflection !== false);
return $local;
}
/**
* Add response data to collected XML response.
*
* This function is called by all modules when they want to output some XML response data
* to the client. It simply copies the XML response data to an internal structure. The data
* is later collected via getData() when all modules are done processing, after which the
* data is sent to the client.
*
* The data added is not checked for validity, and is therefore completely free-form. However,
*
* @param array $data data to be added
*/
public function addData($data) {
foreach ($data as $moduleName => $module) {
if (isset($this->responseData[$moduleName])) {
foreach ($module as $moduleId => $action) {
if (isset($this->responseData[$moduleName][$moduleId])) {
foreach ($action as $actionType => $actionData) {
if (isset($this->responseData[$moduleName][$moduleId][$actionType])) {
if ($this->responseData[$moduleName][$moduleId][$actionType] == $actionData) {
// in future we can think something about this but for now we throw exception
throw new BusException(_("Can't add data to bus, same action type is present in bus"));
}
}
}
}
}
}
}
$this->responseData = array_replace_recursive($this->responseData, $data);
}
/**
* Function which returns the data stored via addData().
*
* @return array|string response data, or an encoded empty response when no data is available
*/
public function getData() {
if (empty($this->responseData)) {
// Helps to avoid unnecessary bus error message on client side when gromox is stopped.
// we just error_log and send empty grommunio array on client side
error_log(_("Response data requested from bus but it doesn't have any data."));
return json_encode(["grommunio" => []]);
}
return $this->responseData;
}
/**
* Merge persistent registrations from a concurrently completed request.
* Existing notifier instances belong to the newer on-disk state; notifier
* names and registrations only present in the other request are additive.
*
* @param Bus $bus request-local bus state
* @param null|Bus $baseBus state from which the request started
* @param bool $reset clear transient notifier and response data
* @param bool $preserveTransient retain request-local notifier data while importing
*/
public function mergePersistentState($bus, $baseBus = null, $reset = true, $preserveTransient = false) {
if (!$bus instanceof self) {
return;
}
if (!is_array($this->notifiers)) {
$this->notifiers = [];
}
if (!is_array($this->notifierVersions)) {
$this->notifierVersions = [];
}
if (is_array($bus->notifiers)) {
foreach ($bus->notifiers as $notifierName => $notifier) {
$currentVersion = isset($this->notifierVersions[$notifierName]) ? (int) $this->notifierVersions[$notifierName] : 0;
$otherVersion = isset($bus->notifierVersions[$notifierName]) ? (int) $bus->notifierVersions[$notifierName] : 0;
if (!isset($this->notifiers[$notifierName])) {
$this->notifiers[$notifierName] = $notifier;
$this->notifierVersions[$notifierName] = $otherVersion;
}
elseif ($otherVersion > $currentVersion) {
$this->notifiers[$notifierName] = $preserveTransient ?
$this->mergeNotifierPersistentState($this->notifiers[$notifierName], $notifier) : $notifier;
$this->notifierVersions[$notifierName] = $otherVersion;
}
elseif ($otherVersion === $currentVersion && $baseBus instanceof self && isset($baseBus->notifiers[$notifierName])) {
$baseNotifier = serialize($baseBus->notifiers[$notifierName]);
if (serialize($this->notifiers[$notifierName]) === $baseNotifier && serialize($notifier) !== $baseNotifier) {
$this->notifiers[$notifierName] = $preserveTransient ?
$this->mergeNotifierPersistentState($this->notifiers[$notifierName], $notifier) : $notifier;
$this->notifierVersions[$notifierName] = $otherVersion;
}
}
}
}
$baseRegistrations = $baseBus instanceof self ? $baseBus->registeredNotifiers : [];
$baseStoreRegistrations = $baseBus instanceof self ? $baseBus->registeredStoreNotifiers : [];
$this->mergeRegistrations($bus->registeredNotifiers, $baseRegistrations, false);
$this->mergeRegistrations($bus->registeredStoreNotifiers, $baseStoreRegistrations, true);
if ($reset) {
$this->reset();
}
}
/**
* Publish new registrations before module execution and import registrations
* published by requests that started from the same state snapshot.
*/
public function synchronizePersistentState() {
$stateId = $GLOBALS['request_state_id'] ?? null;
if (!is_string($stateId) || $stateId === '' || ($GLOBALS['bus'] ?? null) !== $this) {
return true;
}
$registrationState = new State('bus-registration-' . hash('sha256', $stateId));
if (!$registrationState->open()) {
return false;
}
$version = (int) $registrationState->read('version');
if ($this->synchronizedRegistrationVersion === $version && !$this->registrationStateDirty) {
$registrationState->close();
return true;
}
$state = new State($stateId);
if (!$state->open()) {
$registrationState->close();
return false;
}
try {
$currentBus = $state->read('bus');
if ($currentBus instanceof self) {
$currentBus->reset();
}
else {
$currentBus = unserialize(serialize($this));
$currentBus->reset();
}
$before = serialize($currentBus);
$beforeTopology = $currentBus->persistentTopologyFingerprint();
$baseBus = $GLOBALS['request_bus_base'] ?? null;
$localCopy = clone $this;
$localCopy->responseData = [];
foreach ($this->notifiers as $notifierName => $notifier) {
$localCopy->notifiers[$notifierName] = $this->persistentNotifierCopy($notifier);
}
$currentBus->mergePersistentState($localCopy, $baseBus instanceof self ? $baseBus : null);
$topology = $currentBus->persistentTopologyFingerprint();
if ($topology !== $beforeTopology) {
++$version;
$registrationState->write('version', $version);
}
$currentBus->synchronizedRegistrationVersion = $version;
$currentBus->registrationStateDirty = false;
if (serialize($currentBus) !== $before) {
$state->write('bus', $currentBus);
}
}
finally {
$state->close();
$registrationState->close();
}
$this->mergePersistentState($currentBus, null, false, true);
$this->synchronizedRegistrationVersion = $version;
$this->registrationStateDirty = false;
if ($baseBus instanceof self) {
$baseBus->mergePublishedBaseline($currentBus);
}
return true;
}
/**
* Extend a request's merge baseline with registrations it has observed.
*
* @param mixed $bus
*/
private function mergePublishedBaseline($bus) {
if (!$bus instanceof self) {
return;
}
foreach ($bus->notifiers as $notifierName => $notifier) {
$currentVersion = isset($this->notifierVersions[$notifierName]) ? (int) $this->notifierVersions[$notifierName] : 0;
$otherVersion = isset($bus->notifierVersions[$notifierName]) ? (int) $bus->notifierVersions[$notifierName] : 0;
if (!isset($this->notifiers[$notifierName]) || $otherVersion > $currentVersion) {
$this->notifiers[$notifierName] = unserialize(serialize($notifier));
$this->notifierVersions[$notifierName] = $otherVersion;
}
}
$baseRegistrations = $this->registeredNotifiers;
$baseStoreRegistrations = $this->registeredStoreNotifiers;
$this->mergeRegistrations($bus->registeredNotifiers, $baseRegistrations, false);
$this->mergeRegistrations($bus->registeredStoreNotifiers, $baseStoreRegistrations, true);
$this->synchronizedRegistrationVersion = $bus->synchronizedRegistrationVersion;
$this->registrationStateDirty = false;
}
/**
* Fingerprint notifier names and their append-only registrations.
*/
private function persistentTopologyFingerprint() {
$notifierClasses = [];
if (is_array($this->notifiers)) {
foreach ($this->notifiers as $name => $notifier) {
$notifierClasses[$name] = is_object($notifier) ? get_class($notifier) : gettype($notifier);
}
}
ksort($notifierClasses);
return hash('sha256', serialize([
$notifierClasses,
$this->registeredNotifiers,
$this->registeredStoreNotifiers,
]));
}
/**
* Three-way merge one of the append-only registration lists.
*
* @param mixed $registrations registrations from another Bus
* @param mixed $baseRegistrations registrations from its starting state
* @param bool $store whether these are store registrations
*/
private function mergeRegistrations($registrations, $baseRegistrations, $store) {
if (!is_array($registrations)) {
return;
}
if ($store) {
$target = &$this->registeredStoreNotifiers;
}
else {
$target = &$this->registeredNotifiers;
}
if (!is_array($target)) {
$target = [];
}
$basePairs = [];
$baseEntries = [];
if (is_array($baseRegistrations)) {
foreach ($baseRegistrations as $registration) {
if (!is_array($registration) || !self::isRegistrationEntryid($registration['entryid'] ?? null)) {
continue;
}
$entryKey = $this->registrationEntryKey($registration['entryid']);
if (isset($baseEntries[$entryKey])) {
continue;
}
$baseEntries[$entryKey] = true;
foreach ($registration as $notifierName => $notifier) {
if ($notifierName !== 'entryid' && is_string($notifierName) && is_array($notifier) && isset($notifier['events'])) {
$basePairs[$this->registrationPairKey($entryKey, $notifierName)] = $notifier['events'];
}
}
}
}
$targetEntries = [];
$targetPairs = [];
foreach ($target as $index => $registration) {
if (!is_array($registration) || !self::isRegistrationEntryid($registration['entryid'] ?? null)) {
continue;
}
$entryKey = $this->registrationEntryKey($registration['entryid']);
if (isset($targetEntries[$entryKey])) {
continue;
}
$targetEntries[$entryKey] = $index;
foreach ($registration as $notifierName => $notifier) {
if ($notifierName !== 'entryid' && is_string($notifierName) && is_array($notifier) && isset($notifier['events'])) {
$targetPairs[$this->registrationPairKey($entryKey, $notifierName)] = $notifier['events'];
}
}
}
$localEntries = [];
foreach ($registrations as $registration) {
if (!is_array($registration) || !self::isRegistrationEntryid($registration['entryid'] ?? null)) {
continue;
}
$entryKey = $this->registrationEntryKey($registration['entryid']);
if (isset($localEntries[$entryKey])) {
continue;
}
$localEntries[$entryKey] = true;
foreach ($registration as $notifierName => $notifier) {
if ($notifierName === 'entryid' || !is_string($notifierName) || !is_array($notifier) || !isset($notifier['events'])) {
continue;
}
$pairKey = $this->registrationPairKey($entryKey, $notifierName);
$baseHasPair = array_key_exists($pairKey, $basePairs);
if ($baseHasPair && $basePairs[$pairKey] === $notifier['events']) {
continue;
}
$targetHasPair = array_key_exists($pairKey, $targetPairs);
$targetMatchesBase = $targetHasPair === $baseHasPair &&
(!$baseHasPair || $targetPairs[$pairKey] === $basePairs[$pairKey]);
if (!$targetMatchesBase) {
continue;
}
if (!isset($targetEntries[$entryKey])) {
$target[] = ['entryid' => $registration['entryid']];
$targetEntries[$entryKey] = array_key_last($target);
}
$target[$targetEntries[$entryKey]][$notifierName] = ['events' => $notifier['events']];
$targetPairs[$pairKey] = $notifier['events'];
}
}
unset($target);
}
/**
* Registrations without an entryid never match a notification.
*/
private function pruneRegistrations() {
foreach (['registeredNotifiers', 'registeredStoreNotifiers'] as $list) {
if (!is_array($this->{$list})) {
$this->{$list} = [];
continue;
}
$this->{$list} = array_values(array_filter($this->{$list}, static fn ($registration) => is_array($registration) &&
self::isRegistrationEntryid($registration['entryid'] ?? null)));
}
}
/**
* @param mixed $entryid
*
* @return bool
*/
private static function isRegistrationEntryid($entryid) {
return is_string($entryid) && $entryid !== '';
}
/**
* Build a type-safe index key for an entryid.
*
* @param mixed $entryid
*/
private function registrationEntryKey($entryid) {
return 'e' . strlen($entryid) . ':' . $entryid;
}
/**
* Build a type-safe index key for an entryid/notifier pair.
*
* @param mixed $entryKey
* @param mixed $notifierName
*/
private function registrationPairKey($entryKey, $notifierName) {
return $entryKey . '|n' . strlen($notifierName) . ':' . $notifierName;
}
/**
* Reset the bus state and response data, and send resets to all notifier.
*
* Since the bus is a global, persistent object, the reset() function is called before or after
* processing. This makes sure that the on-disk serialized representation of the bus object is as
* small as possible.
*/
public function reset() {
$this->responseData = [];
$this->pruneRegistrations();
foreach ($this->notifiers as $key => $notifier) {
$this->notifiers[$key]->reset();
}
}
}
@@ -0,0 +1,692 @@
<?php
/*
* SPDX-FileCopyrightText: Copyright 2020 - 2026 grommunio GmbH
* SPDX-License-Identifier: AGPL-3.0-or-later
*/
/**
* CategoryList - the per-mailbox master category list.
*
* Outlook/Exchange store the list of available categories (name + colour) once
* per mailbox, as a hidden associated (FAI) message of class
* "IPM.Configuration.CategoryList" in the mailbox's Calendar folder. The
* definitions live in the PR_ROAMING_XMLSTREAM property as an XML document.
* Because it is stored in the mailbox itself, every client - and every user who
* opens that mailbox - shares the same list. grommunio Web historically kept
* its category list in per-user WebApp settings instead; this class reads and
* writes the Outlook-compatible per-mailbox list so the two interoperate.
*
* The class speaks the grommunio Web category shape
* ({name, color, standardIndex, quickAccess, sortIndex, used}) on its public
* API and the Outlook XML shape on disk, translating between them. Outlook's
* per-category bookkeeping (guid, usageCount, lastTimeUsed*, keyboardShortcut,
* renameOnFirstUse) is preserved verbatim across web edits by merging incoming
* categories onto the categories already stored, matched by guid then by name.
*/
class CategoryList {
/**
* Message class of the FAI configuration message holding the list.
*/
public const MESSAGE_CLASS = 'IPM.Configuration.CategoryList';
/**
* grommunio Web's placeholder colour for "no colour chosen". Categories
* carrying it are treated as uncoloured rather than mapped to the palette.
*/
public const DEFAULT_COLOR = '#BDC3C7';
/**
* Outlook OlCategoryColor palette: index (as written in the XML `color`
* attribute) => RGB hex used to render the swatch.
*/
private static $palette = [
0 => '#d6252e', // Red
1 => '#f06c15', // Orange
2 => '#ffca4c', // Peach
3 => '#fffe3d', // Yellow
4 => '#4ab63f', // Green
5 => '#40bd95', // Teal
6 => '#859a52', // Olive
7 => '#3267b8', // Blue
8 => '#613db4', // Purple
9 => '#a34e78', // maroon
10 => '#c4ccdd', // Steel
11 => '#8c9cbd', // Dark Steel
12 => '#c4c4c4', // Gray
13 => '#a5a5a5', // Dark Gray
14 => '#1c1c1c', // Black
15 => '#af1e25', // Dark Red
16 => '#b14f0d', // Dark Orange
17 => '#ab7b05', // Dark Peach
18 => '#999400', // Dark Yellow
19 => '#35792b', // Dark Green
20 => '#2e7d64', // Dark Teal
21 => '#5f6c3a', // Dark Olive
22 => '#2a5191', // Dark Blue
23 => '#50328f', // Dark Purple
24 => '#82375f', // Dark Maroon
];
/**
* Return the Outlook category colour palette in display order.
*
* @return string[] RGB hex colours
*/
public static function getPalette() {
return array_values(self::$palette);
}
/**
* Hex colour => grommunio Web standardIndex (the colour-flag mapping used to
* show an old-style coloured flag as a category). Only the six standard
* flag colours have one.
*/
private static $standardIndexByHex = [
'#e40023' => 6, // Red flag
'#f99406' => 2, // Orange flag
'#f7ca17' => 4, // Yellow flag
'#5ab556' => 3, // Green flag
'#0f70bd' => 5, // Blue flag
'#912887' => 1, // Purple flag
];
/**
* @var resource the message store whose category list this instance manages
*/
private $store;
/**
* @var false|resource cached Calendar folder, or false before it is opened
*/
private $calendar = false;
/**
* @var null|bool whether the FAI config message exists; null until known
*/
private $exists;
/**
* @var array Root element attributes of the stored XML (e.g. Outlook's
* Quick Click category in 'default'), preserved across saves.
*/
private $rootAttributes = [];
/**
* @param resource $store the (own or shared) message store to operate on
*/
public function __construct($store) {
$this->store = $store;
}
/**
* Open the store's Calendar folder, where the list is stored.
*
* @return false|resource the Calendar folder, or false when unavailable
*/
private function getCalendarFolder() {
if ($this->calendar === false) {
try {
$root = mapi_msgstore_openentry($this->store);
if ($root === false) {
return false;
}
$props = mapi_getprops($root, [PR_IPM_APPOINTMENT_ENTRYID]);
if (empty($props[PR_IPM_APPOINTMENT_ENTRYID])) {
return false;
}
/** @var false|resource $calendar php-mapi Calendar folder */
$calendar = /** @scrutinizer ignore-type */ mapi_msgstore_openentry($this->store, $props[PR_IPM_APPOINTMENT_ENTRYID]);
if ($calendar === false) {
return false;
}
$this->calendar = $calendar;
}
catch (MAPIException $e) {
// A store without an accessible Calendar (e.g. the public
// store) simply has no category list; treat it as empty.
$e->setHandled();
return false;
}
}
return /** @scrutinizer ignore-type */ $this->calendar;
}
/**
* Find the FAI configuration message that holds the list.
*
* @param bool $create create the message when it does not exist yet
*
* @return false|resource the message, or false when absent (and not created)
*/
private function findConfigMessage($create = false) {
$calendar = $this->getCalendarFolder();
if (/** @scrutinizer ignore-type */ $calendar === false) {
return false;
}
try {
$table = mapi_folder_getcontentstable($calendar, MAPI_ASSOCIATED);
$restriction = [RES_PROPERTY, [
RELOP => RELOP_EQ,
ULPROPTAG => PR_MESSAGE_CLASS,
VALUE => [PR_MESSAGE_CLASS => self::MESSAGE_CLASS],
]];
mapi_table_restrict($table, $restriction);
$rows = mapi_table_queryallrows($table, [PR_ENTRYID]);
if (!empty($rows)) {
$this->exists = true;
return mapi_msgstore_openentry($this->store, $rows[0][PR_ENTRYID]);
}
$this->exists = false;
if ($create) {
$message = mapi_folder_createmessage($calendar, MAPI_ASSOCIATED);
mapi_setprops($message, [PR_MESSAGE_CLASS => self::MESSAGE_CLASS]);
return $message;
}
}
catch (MAPIException $e) {
// A save must not silently misreport success when the message
// cannot be created (e.g. a read-only share).
if ($create) {
throw $e;
}
// No accessible associated store / config message; treat as empty.
$e->setHandled();
}
return false;
}
/**
* Whether a category list is stored in the mailbox at all. False both for
* a mailbox never touched by categories and one whose Calendar is
* inaccessible; distinguishes "seed a first list" from "list is empty".
*
* @return bool
*/
public function listExists() {
if ($this->exists === null) {
$this->findConfigMessage(false);
}
return $this->exists === true;
}
/**
* Read the raw category-list XML.
*
* @return string the XML document, or '' when no list is stored yet
*/
public function getXml() {
$message = $this->findConfigMessage(false);
if ($message === false) {
return '';
}
$props = mapi_getprops($message, [PR_ROAMING_XMLSTREAM]);
if (isset($props[PR_ROAMING_XMLSTREAM]) && is_string($props[PR_ROAMING_XMLSTREAM])) {
return $props[PR_ROAMING_XMLSTREAM];
}
// Large binaries come back as an error placeholder; read via a stream.
$stream = mapi_openproperty($message, PR_ROAMING_XMLSTREAM, IID_IStream, 0, 0);
if ($stream === false) {
return '';
}
$xml = '';
$stat = mapi_stream_stat($stream);
mapi_stream_seek($stream, 0, STREAM_SEEK_SET);
for ($read = 0; $read < $stat['cb'];) {
$chunk = mapi_stream_read($stream, 8192);
if ($chunk === '' || $chunk === false) {
break;
}
$xml .= $chunk;
$read += strlen($chunk);
}
return $xml;
}
/**
* Write the raw category-list XML, creating the FAI message if needed.
*
* @param string $xml the XML document to store
*/
public function setXml($xml) {
$message = $this->findConfigMessage(true);
if ($message === false) {
// no accessible Calendar folder, the save must not silently no-op
throw new MAPIException("Cannot store the category list.", MAPI_E_NOT_FOUND, null, _("Cannot store the category list in this mailbox."));
}
mapi_setprops($message, [
PR_MESSAGE_CLASS => self::MESSAGE_CLASS,
PR_ROAMING_XMLSTREAM => $xml,
]);
mapi_savechanges($message);
$this->exists = true;
}
/**
* Return the categories in grommunio Web shape.
*
* @return array a list of associative arrays with keys name, color,
* standardIndex, quickAccess, sortIndex, used, guid
*/
public function getCategories() {
$nodes = $this->parseXml($this->getXml());
$categories = [];
foreach ($nodes as $index => $node) {
$colorIndex = isset($node['color']) && $node['color'] !== '' ? (int) $node['color'] : -1;
$hex = self::colorIndexToHex($colorIndex);
$categories[] = [
'name' => isset($node['name']) ? $node['name'] : '',
'color' => $hex,
'standardIndex' => isset($node['x-standardindex']) && $node['x-standardindex'] !== '' ?
(int) $node['x-standardindex'] : self::hexToStandardIndex($hex),
// grommunio-only fields are carried in custom x- attributes so
// they survive a round trip through the shared list.
'quickAccess' => isset($node['x-quickaccess']) ? $node['x-quickaccess'] === '1' : false,
'sortIndex' => isset($node['x-sortindex']) ? (int) $node['x-sortindex'] : ($index + 1),
'used' => isset($node['x-used']) ? $node['x-used'] === '1' : false,
'guid' => isset($node['guid']) ? $node['guid'] : '',
];
}
return $categories;
}
/**
* Add every category currently assigned to an item in this mailbox to the
* master category list. Legacy category definitions provide the colours for
* categories not already present; {@link setCategories} maps those colours
* to the nearest Outlook palette entry.
*
* @param array $legacyCategories legacy grommunio Web category definitions
*
* @return int number of distinct category names found on items
*/
public function migrateItemCategories($legacyCategories) {
$itemCategories = $this->getItemCategoryNames();
$categories = $this->getCategories();
$knownCategories = [];
foreach ($categories as $category) {
if (!empty($category['name'])) {
$knownCategories[strtolower($category['name'])] = true;
}
}
$legacyByName = [];
foreach ($legacyCategories as $category) {
if (is_array($category) && !empty($category['name'])) {
$legacyByName[strtolower($category['name'])] = $category;
}
}
$changed = false;
foreach ($itemCategories as $name) {
$key = strtolower($name);
if (isset($knownCategories[$key])) {
continue;
}
$category = isset($legacyByName[$key]) ? $legacyByName[$key] : [];
$category['name'] = $name;
$category['used'] = true;
if (!isset($category['color'])) {
$category['color'] = self::DEFAULT_COLOR;
}
$categories[] = $category;
$knownCategories[$key] = true;
$changed = true;
}
if ($changed) {
$this->setCategories($categories);
}
return count($itemCategories);
}
/**
* Scan the normal contents of every folder below the IPM subtree and return
* the distinct category names assigned to those items.
*
* @return string[] category names in first-seen order
*/
protected function getItemCategoryNames() {
$storeProps = mapi_getprops($this->store, [PR_IPM_SUBTREE_ENTRYID]);
if (empty($storeProps[PR_IPM_SUBTREE_ENTRYID])) {
throw new MAPIException('Cannot open the mailbox folder tree.', MAPI_E_NOT_FOUND, null, _('Cannot scan this mailbox for categories.'));
}
$subtreeEntryId = $storeProps[PR_IPM_SUBTREE_ENTRYID];
$subtree = mapi_msgstore_openentry($this->store, $subtreeEntryId);
if ($subtree === false) {
throw new MAPIException('Cannot open the mailbox folder tree.', MAPI_E_NOT_FOUND, null, _('Cannot scan this mailbox for categories.'));
}
$folderEntryIds = [$subtreeEntryId];
$hierarchy = mapi_folder_gethierarchytable($subtree, CONVENIENT_DEPTH | MAPI_DEFERRED_ERRORS);
foreach (mapi_table_queryallrows($hierarchy, [PR_ENTRYID]) as $folderRow) {
if (!empty($folderRow[PR_ENTRYID])) {
$folderEntryIds[] = $folderRow[PR_ENTRYID];
}
}
$properties = getPropIdsFromStrings($this->store, [
'categories' => 'PT_MV_STRING8:PS_PUBLIC_STRINGS:Keywords',
]);
$categoriesProperty = $properties['categories'];
$restriction = [RES_EXIST, [ULPROPTAG => $categoriesProperty]];
$names = [];
$knownNames = [];
foreach ($folderEntryIds as $folderEntryId) {
$folder = mapi_msgstore_openentry($this->store, $folderEntryId);
if ($folder === false) {
continue;
}
$table = mapi_folder_getcontentstable($folder, MAPI_DEFERRED_ERRORS);
mapi_table_restrict($table, $restriction, TBL_BATCH);
$rows = mapi_table_queryallrows($table, [$categoriesProperty]);
foreach ($rows as $row) {
if (!isset($row[$categoriesProperty]) || !is_array($row[$categoriesProperty])) {
continue;
}
foreach ($row[$categoriesProperty] as $name) {
$name = trim((string) $name);
$key = strtolower($name);
if ($name !== '' && !isset($knownNames[$key])) {
$names[] = $name;
$knownNames[$key] = true;
}
}
}
}
return $names;
}
/**
* Store the given categories, preserving each existing category's Outlook
* bookkeeping (matched by guid, then by case-insensitive name).
*
* @param array $categories grommunio Web category dicts (name, color, ...)
*/
public function setCategories($categories) {
$existing = $this->parseXml($this->getXml());
$byGuid = [];
$byName = [];
foreach ($existing as $node) {
if (!empty($node['guid'])) {
$byGuid[strtolower($node['guid'])] = $node;
}
if (isset($node['name'])) {
$byName[strtolower($node['name'])] = $node;
}
}
$nodes = [];
foreach ($categories as $i => $category) {
$name = isset($category['name']) ? (string) $category['name'] : '';
if ($name === '') {
continue;
}
$guid = !empty($category['guid']) ? $category['guid'] : '';
// Start from the existing node so Outlook's attributes are kept.
$node = [];
if ($guid !== '' && isset($byGuid[strtolower($guid)])) {
$node = $byGuid[strtolower($guid)];
}
elseif (isset($byName[strtolower($name)])) {
$node = $byName[strtolower($name)];
}
if (empty($node['guid'])) {
$node['guid'] = $guid !== '' ? $guid : self::newGuid();
}
$node['name'] = $name;
// Only recompute the colour index when the hex actually changed, so
// an untouched Outlook colour keeps its exact original index.
// MS-OXOCFG requires color to be an integer in [-1,24]; -1 = none.
$hex = isset($category['color']) ? strtolower($category['color']) : '';
$prevIndex = isset($node['color']) && $node['color'] !== '' ? (int) $node['color'] : -1;
if ($hex === '' || $hex === strtolower(self::DEFAULT_COLOR)) {
$node['color'] = (string) $prevIndex;
}
elseif ($prevIndex >= 0 && strtolower(self::colorIndexToHex($prevIndex)) === $hex) {
$node['color'] = (string) $prevIndex;
}
else {
$node['color'] = (string) self::hexToColorIndex($hex);
}
// Sensible defaults for attributes Outlook expects.
if (!isset($node['keyboardShortcut'])) {
$node['keyboardShortcut'] = '0';
}
if (!isset($node['renameOnFirstUse'])) {
$node['renameOnFirstUse'] = '0';
}
// grommunio-only fields, namespaced so Outlook ignores them.
$node['x-quickaccess'] = !empty($category['quickAccess']) ? '1' : '0';
$node['x-used'] = !empty($category['used']) ? '1' : '0';
$node['x-sortindex'] = (string) (isset($category['sortIndex']) ? (int) $category['sortIndex'] : $i);
// keep the flag mapping stable when a standard category is recoloured
if (isset($category['standardIndex']) && $category['standardIndex'] !== null && $category['standardIndex'] !== '') {
$node['x-standardindex'] = (string) (int) $category['standardIndex'];
}
$nodes[] = $node;
}
$this->setXml($this->buildXml($nodes));
}
/**
* Map an Outlook colour index to an RGB hex string.
*
* @param int $index palette index, or -1 for no colour
*
* @return string hex colour (grommunio's default placeholder when unmapped)
*/
public static function colorIndexToHex($index) {
if (isset(self::$palette[$index])) {
return self::$palette[$index];
}
return self::DEFAULT_COLOR;
}
/**
* Map an RGB hex string to the nearest Outlook colour index.
*
* @param string $hex the RGB hex string (with or without leading #)
*
* @return int the matching or nearest palette index
*/
public static function hexToColorIndex($hex) {
$hex = strtolower(ltrim($hex, '#'));
foreach (self::$palette as $index => $paletteHex) {
if (ltrim($paletteHex, '#') === $hex) {
return $index;
}
}
// No exact match: pick the nearest palette colour by RGB distance.
$target = self::hexToRgb($hex);
if ($target === null) {
return 0;
}
$best = 0;
$bestDistance = PHP_INT_MAX;
foreach (self::$palette as $index => $paletteHex) {
$rgb = self::hexToRgb(ltrim($paletteHex, '#'));
$distance = ($rgb[0] - $target[0]) ** 2 + ($rgb[1] - $target[1]) ** 2 + ($rgb[2] - $target[2]) ** 2;
if ($distance < $bestDistance) {
$bestDistance = $distance;
$best = $index;
}
}
return $best;
}
/**
* Map an RGB hex string to a grommunio Web standardIndex, if it is one of
* the six standard flag colours.
*
* @param string $hex the RGB hex string
*
* @return null|int the standardIndex, or null when not a standard colour
*/
public static function hexToStandardIndex($hex) {
$hex = strtolower($hex);
return isset(self::$standardIndexByHex[$hex]) ? self::$standardIndexByHex[$hex] : null;
}
/**
* Convert a hex colour to an [r, g, b] triplet.
*
* @param string $hex hex string without a leading #
*
* @return null|array [r, g, b], or null when malformed
*/
private static function hexToRgb($hex) {
if (strlen($hex) !== 6 || !ctype_xdigit($hex)) {
return null;
}
return [hexdec(substr($hex, 0, 2)), hexdec(substr($hex, 2, 2)), hexdec(substr($hex, 4, 2))];
}
/**
* Generate a category GUID in Outlook's brace-wrapped upper-case form.
*
* @return string e.g. {AABBCCDD-EEFF-0011-2233-445566778899}
*/
private static function newGuid() {
$bytes = random_bytes(16);
return sprintf(
'{%s-%s-%s-%s-%s}',
strtoupper(bin2hex(substr($bytes, 0, 4))),
strtoupper(bin2hex(substr($bytes, 4, 2))),
strtoupper(bin2hex(substr($bytes, 6, 2))),
strtoupper(bin2hex(substr($bytes, 8, 2))),
strtoupper(bin2hex(substr($bytes, 10, 6)))
);
}
/**
* Parse the category-list XML into a list of attribute maps (one per
* <category>), keeping every attribute so nothing is lost on a round trip.
*
* @param string $xml the XML document
*
* @return array a list of associative arrays of attribute name => value
*/
private function parseXml($xml) {
if (trim($xml) === '') {
return [];
}
$previous = libxml_use_internal_errors(true);
$doc = new DOMDocument();
$loaded = $doc->loadXML($xml);
libxml_clear_errors();
libxml_use_internal_errors($previous);
if (!$loaded) {
return [];
}
// Remember the root attributes (e.g. Outlook's Quick Click category
// in 'default') so buildXml can write them back.
if ($doc->documentElement) {
foreach ($doc->documentElement->attributes as $attribute) {
$this->rootAttributes[$attribute->name] = $attribute->value;
}
}
$nodes = [];
foreach ($doc->getElementsByTagName('category') as $element) {
$attributes = [];
foreach ($element->attributes as $attribute) {
// Normalise our own custom attributes to lower case so lookups
// are predictable; Outlook attributes keep their case.
$name = $attribute->name;
if (strpos($name, 'x-') === 0) {
$name = strtolower($name);
}
$attributes[$name] = $attribute->value;
}
$nodes[] = $attributes;
}
return $nodes;
}
/**
* Build the category-list XML from a list of attribute maps.
*
* @param array $nodes a list of associative arrays of attribute name => value
*
* @return string the XML document
*/
private function buildXml($nodes) {
$root = array_merge([
'default' => '',
'lastSavedSession' => '00000000',
], $this->rootAttributes);
$root['lastSavedTime'] = gmdate('Y-m-d\TH:i:s.000');
$root['xmlns'] = 'CategoryList.xsd';
$xml = '<?xml version="1.0"?>' . "\n";
$xml .= '<categories';
foreach ($root as $name => $value) {
$xml .= ' ' . $name . '="' . self::xmlAttribute($value) . '"';
}
$xml .= '>';
foreach ($nodes as $node) {
$xml .= '<category';
foreach ($node as $name => $value) {
$xml .= ' ' . $name . '="' . self::xmlAttribute($value) . '"';
}
$xml .= '/>';
}
$xml .= '</categories>';
return $xml;
}
/**
* Escape a value for use in an XML attribute. Also strips characters that
* are illegal in XML 1.0 (raw control characters), which htmlspecialchars
* passes through and which would make the whole document unparseable.
*
* @param string $value the attribute value
*
* @return string the escaped value
*/
private static function xmlAttribute($value) {
$value = preg_replace('/[^\x{09}\x{0A}\x{0D}\x{20}-\x{D7FF}\x{E000}-\x{FFFD}\x{10000}-\x{10FFFF}]/u', '', (string) $value);
// a non-UTF-8 byte sequence makes preg_replace return null
if ($value === null) {
$value = '';
}
return htmlspecialchars($value, ENT_QUOTES | ENT_XML1, 'UTF-8');
}
}
@@ -0,0 +1,473 @@
<?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
*/
/**
* Utility class for color conversions.
*/
class Colors {
/**
* Creates a lighter color.
*
* @param array|string $color A hexstring or color array with r, g, b keys
* @param float $percentage the percentage with which the luminance of the color
* should be changed
*
* @return string A hexstring with the new color (including '#')
*/
public static function lighter($color, $percentage) {
$hsl = Colors::rgb2hsl($color);
$hsl['l'] += $percentage;
if ($hsl['l'] > 100) {
$hsl['l'] = 100;
}
elseif ($hsl['l'] < 0) {
$hsl['l'] = 0;
}
$rgb = Colors::hsl2rgb($hsl);
return Colors::colorObject2string($rgb);
}
/**
* Creates a darker color.
*
* @param array|string $color A hexstring or color array with r, g, b keys
* @param float $percentage the percentage with which the luminance of the color
* should be changed
*
* @return string A hexstring with the new color (including '#')
*/
public static function darker($color, $percentage) {
return Colors::lighter($color, -$percentage);
}
/**
* Sets the luminance to a certain value.
*
* @param array|string $color A hexstring or color array with r, g, b keys
* @param float $percentage the percentage to which the luminance of the color
* should be set
*
* @return string A hexstring with the new color (including '#')
*/
public static function setLuminance($color, $percentage) {
$hsl = Colors::rgb2hsl($color);
$hsl['l'] = $percentage;
if ($hsl['l'] > 100) {
$hsl['l'] = 100;
}
elseif ($hsl['l'] < 0) {
$hsl['l'] = 0;
}
$rgb = Colors::hsl2rgb($hsl);
return Colors::colorObject2string($rgb);
}
/**
* Transforms a hexstring into a color object (array with r, g, b keys).
*
* @param string $color A hexstring or color object (array with r, g, b keys)
*
* @return array An array with values for r, g, b
*/
public static function colorString2Object($color) {
if (str_starts_with($color, '#')) {
$color = substr($color, 1);
}
if (strlen($color) === 3) {
$red = intval(substr($color, 0, 1) . substr($color, 0, 1), 16);
$green = intval(substr($color, 1, 1) . substr($color, 1, 1), 16);
$blue = intval(substr($color, 2, 1) . substr($color, 2, 1), 16);
}
else {
$red = intval(substr($color, 0, 2), 16);
$green = intval(substr($color, 2, 2), 16);
$blue = intval(substr($color, 4, 2), 16);
}
return [
'r' => $red,
'g' => $green,
'b' => $blue,
];
}
/**
* Transforms a color object (array with r, g, b keys) into a hexstring.
*
* @param array $color An array with values for r, g, b
*
* @return string A hexstring or color object (array with r, g, b keys)
*/
public static function colorObject2string($color) {
$r = dechex($color['r']);
if (strlen($r) === 1) {
$r = '0' . $r;
}
$g = dechex($color['g']);
if (strlen($g) === 1) {
$g = '0' . $g;
}
$b = dechex($color['b']);
if (strlen($b) === 1) {
$b = '0' . $b;
}
return '#' . $r . $g . $b;
}
/**
* Transforms a red-green-blue color object to a hue-saturation-luminance object.
* See http://www.niwa.nu/2013/05/math-behind-colorspace-conversions-rgb-hsl/ for
* more information.
*
* @param array|string $color A hexstring or an array with values for r, g, b
*
* @return array An array with values for h, s, l
*/
public static function rgb2hsl($color) {
if (is_string($color)) {
$color = Colors::colorString2Object($color);
}
$min = min([$color['r'], $color['g'], $color['b']]);
$max = max([$color['r'], $color['g'], $color['b']]);
$lum = (100 / 255) * ($min + $max) / 2;
if ($min === $max) {
// greyscale
return [
'h' => 0,
's' => 0,
'l' => $lum,
];
}
if ($lum < 50) {
$sat = 100 * ($max - $min) / ($max + $min);
}
else {
$sat = 100 * ($max / 255 - $min / 255) / (2 - $max / 255 - $min / 255);
}
if ($max === $color['r']) {
$hue = ($color['g'] - $color['b']) / ($max - $min);
}
elseif ($max === $color['g']) {
$hue = 2 + ($color['b'] - $color['r']) / ($max - $min);
}
else {
$hue = 4 + ($color['r'] - $color['g']) / ($max - $min);
}
$hue *= 60;
if ($hue < 0) {
$hue += 360;
}
return [
'h' => $hue,
's' => $sat,
'l' => $lum,
];
}
/**
* Transforms a hue-saturation-luminance object to a red-green-blue color object.
* See http://www.niwa.nu/2013/05/math-behind-colorspace-conversions-rgb-hsl/ for
* more information.
*
* @param array $color An array with values for h, s, l
*
* @return array An array with values for r, g, b
*/
public static function hsl2rgb($color) {
$hue = $color['h'];
$sat = $color['s'];
$lum = $color['l'];
if ($color['s'] === 0) {
// greyscale
return [
'r' => $lum * (255 / 100),
'g' => $lum * (255 / 100),
'b' => $lum * (255 / 100),
];
}
$temp1 = $lum / 100 < 0.5 ? ($lum / 100) * (1 + $sat / 100) : ($lum + $sat - $lum * $sat / 100) / 100;
$temp2 = 2 * $lum / 100 - $temp1;
$tempr = $hue / 360 + 0.333;
if ($tempr > 1) {
--$tempr;
}
$tempg = $hue / 360;
$tempb = $hue / 360 - 0.333;
if ($tempb < 0) {
++$tempb;
}
if (6 * $tempr < 1) {
$red = $temp2 + ($temp1 - $temp2) * 6 * $tempr;
}
elseif (2 * $tempr < 1) {
$red = $temp1;
}
elseif (3 * $tempr < 2) {
$red = $temp2 + ($temp1 - $temp2) * (0.666 - $tempr) * 6;
}
else {
$red = $temp2;
}
if (6 * $tempg < 1) {
$green = $temp2 + ($temp1 - $temp2) * 6 * $tempg;
}
elseif (2 * $tempg < 1) {
$green = $temp1;
}
elseif (3 * $tempg < 2) {
$green = $temp2 + ($temp1 - $temp2) * (0.666 - $tempg) * 6;
}
else {
$green = $temp2;
}
if (6 * $tempb < 1) {
$blue = $temp2 + ($temp1 - $temp2) * 6 * $tempb;
}
elseif (2 * $tempb < 1) {
$blue = $temp1;
}
elseif (3 * $tempb < 2) {
$blue = $temp2 + ($temp1 - $temp2) * (0.666 - $tempb) * 6;
}
else {
$blue = $temp2;
}
return [
'r' => 255 * $red,
'g' => 255 * $green,
'b' => 255 * $blue,
];
}
/**
* Returns the luma value (brightness perception)
* See http://stackoverflow.com/a/12043228.
*
* @param array|string $color A hexstring or a color object (rgb or hsl)
*
* @return float luma value
*/
public static function getLuma($color) {
if (is_string($color)) {
$color = Colors::colorString2Object($color);
}
elseif (!isset($color['r']) && isset($color['h'])) {
// assume that this is an hsl color
$color = Colors::hsl2rgb($color);
}
return 0.2126 * $color['r'] + 0.7152 * $color['g'] + 0.0722 * $color['b']; // per ITU-R BT.709
}
/**
* Translates a css color value to a hex color value. So rgb, rgba and
* color keywords will be translated to their hex counterparts.
*
* @param string $color The color that needs to be translated
*
* @return string The hex color value
*/
public static function getHexColorFromCssColor($color) {
$color = strtolower($color);
if (isset(Colors::$keyWords[$color])) {
return Colors::$keyWords[$color];
}
if (preg_match('/^#([0-9a-f]{3}|[0-9a-f]{4}|[0-9a-f]{6}|[0-9a-f]{8})$/', $color)) {
// Already a hex color
return $color;
}
if (preg_match('/^rgb\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\)$/', $color, $m)) {
$r = intval($m[1]);
$g = intval($m[2]);
$b = intval($m[3]);
if ($r < 0 || $r > 255 || $g < 0 || $g > 255 || $b < 0 || $b > 255) {
// Not a valid color
return null;
}
return Colors::colorObject2string(['r' => $r, 'g' => $g, 'b' => $b]);
}
// Not a valid color
// Note: alphanumeric channels are not supported (i.e. rgba(x, x, x, x) or #xxxxxxxx or #xxxx)
return null;
}
/**
* Color keywords. Taken from https://developer.mozilla.org/en-US/docs/Web/CSS/color_value.
*/
public static $keyWords = [
'black' => '#000000',
'silver' => '#c0c0c0',
'gray' => '#808080',
'white' => '#ffffff',
'maroon' => '#800000',
'red' => '#ff0000',
'purple' => '#800080',
'fuchsia' => '#ff00ff',
'green' => '#008000',
'lime' => '#00ff00',
'olive' => '#808000',
'yellow' => '#ffff00',
'navy' => '#000080',
'blue' => '#0000ff',
'teal' => '#008080',
'aqua' => '#00ffff',
'orange' => '#ffa500',
'aliceblue' => '#f0f8ff',
'antiquewhite' => '#faebd7',
'aquamarine' => '#7fffd4',
'azure' => '#f0ffff',
'beige' => '#f5f5dc',
'bisque' => '#ffe4c4',
'blanchedalmond' => '#ffebcd',
'blueviolet' => '#8a2be2',
'brown' => '#a52a2a',
'burlywood' => '#deb887',
'cadetblue' => '#5f9ea0',
'chartreuse' => '#7fff00',
'chocolate' => '#d2691e',
'coral' => '#ff7f50',
'cornflowerblue' => '#6495ed',
'cornsilk' => '#fff8dc',
'crimson' => '#dc143c',
'cyan' => '#00ffff',
'darkblue' => '#00008b',
'darkcyan' => '#008b8b',
'darkgoldenrod' => '#b8860b',
'darkgray' => '#a9a9a9',
'darkgreen' => '#006400',
'darkgrey' => '#a9a9a9',
'darkkhaki' => '#bdb76b',
'darkmagenta' => '#8b008b',
'darkolivegreen' => '#556b2f',
'darkorange' => '#ff8c00',
'darkorchid' => '#9932cc',
'darkred' => '#8b0000',
'darksalmon' => '#e9967a',
'darkseagreen' => '#8fbc8f',
'darkslateblue' => '#483d8b',
'darkslategray' => '#2f4f4f',
'darkslategrey' => '#2f4f4f',
'darkturquoise' => '#00ced1',
'darkviolet' => '#9400d3',
'deeppink' => '#ff1493',
'deepskyblue' => '#00bfff',
'dimgray' => '#696969',
'dimgrey' => '#696969',
'dodgerblue' => '#1e90ff',
'firebrick' => '#b22222',
'floralwhite' => '#fffaf0',
'forestgreen' => '#228b22',
'gainsboro' => '#dcdcdc',
'ghostwhite' => '#f8f8ff',
'gold' => '#ffd700',
'goldenrod' => '#daa520',
'greenyellow' => '#adff2f',
'grey' => '#808080',
'honeydew' => '#f0fff0',
'hotpink' => '#ff69b4',
'indianred' => '#cd5c5c',
'indigo' => '#4b0082',
'ivory' => '#fffff0',
'khaki' => '#f0e68c',
'lavender' => '#e6e6fa',
'lavenderblush' => '#fff0f5',
'lawngreen' => '#7cfc00',
'lemonchiffon' => '#fffacd',
'lightblue' => '#add8e6',
'lightcoral' => '#f08080',
'lightcyan' => '#e0ffff',
'lightgoldenrodyellow' => '#fafad2',
'lightgray' => '#d3d3d3',
'lightgreen' => '#90ee90',
'lightgrey' => '#d3d3d3',
'lightpink' => '#ffb6c1',
'lightsalmon' => '#ffa07a',
'lightseagreen' => '#20b2aa',
'lightskyblue' => '#87cefa',
'lightslategray' => '#778899',
'lightslategrey' => '#778899',
'lightsteelblue' => '#b0c4de',
'lightyellow' => '#ffffe0',
'limegreen' => '#32cd32',
'linen' => '#faf0e6',
'magenta' => '#ff00ff',
'mediumaquamarine' => '#66cdaa',
'mediumblue' => '#0000cd',
'mediumorchid' => '#ba55d3',
'mediumpurple' => '#9370db',
'mediumseagreen' => '#3cb371',
'mediumslateblue' => '#7b68ee',
'mediumspringgreen' => '#00fa9a',
'mediumturquoise' => '#48d1cc',
'mediumvioletred' => '#c71585',
'midnightblue' => '#191970',
'mintcream' => '#f5fffa',
'mistyrose' => '#ffe4e1',
'moccasin' => '#ffe4b5',
'navajowhite' => '#ffdead',
'oldlace' => '#fdf5e6',
'olivedrab' => '#6b8e23',
'orangered' => '#ff4500',
'orchid' => '#da70d6',
'palegoldenrod' => '#eee8aa',
'palegreen' => '#98fb98',
'paleturquoise' => '#afeeee',
'palevioletred' => '#db7093',
'papayawhip' => '#ffefd5',
'peachpuff' => '#ffdab9',
'peru' => '#cd853f',
'pink' => '#ffc0cb',
'plum' => '#dda0dd',
'powderblue' => '#b0e0e6',
'rosybrown' => '#bc8f8f',
'royalblue' => '#4169e1',
'saddlebrown' => '#8b4513',
'salmon' => '#fa8072',
'sandybrown' => '#f4a460',
'seagreen' => '#2e8b57',
'seashell' => '#fff5ee',
'sienna' => '#a0522d',
'skyblue' => '#87ceeb',
'slateblue' => '#6a5acd',
'slategray' => '#708090',
'slategrey' => '#708090',
'snow' => '#fffafa',
'springgreen' => '#00ff7f',
'steelblue' => '#4682b4',
'tan' => '#d2b48c',
'thistle' => '#d8bfd8',
'tomato' => '#ff6347',
'turquoise' => '#40e0d0',
'violet' => '#ee82ee',
'wheat' => '#f5deb3',
'whitesmoke' => '#f5f5f5',
'yellowgreen' => '#9acd32',
'rebeccapurple' => '#663399',
];
}
@@ -0,0 +1,398 @@
<?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
*/
/**
* This class will check the server configuration and it stops the
* webapp from working until this is fixed.
*/
class ConfigCheck {
public $result;
public $siteconfig;
public $phpini;
public function __construct(public $haltOnError = true) {
$this->result = true;
// here we check our settings, changes to the config and
// additional checks must be added/changed here
$this->checkPHP("5.4", "You must upgrade PHP");
$this->checkExtension("mapi", "", "If you have upgraded Gromox, please restart nginx/php-fpm");
$this->checkExtension("gettext", "", "Install the gettext extension for PHP");
$this->checkPHPsetting("session.auto_start", "0", "Modify this setting in '%s'");
$this->checkPHPsetting("output_handler", "", "With this option set, it is unsure if the grommunio Web will work correctly");
$this->checkPHPsetting("zlib.output_handler", "", "With this option set, it is unsure if the grommunio Web will work correctly");
# Replicate value logic from php-src/ext/zlib/zlib.c
$sv = ini_get("zlib.output_compression");
$sv = strcasecmp($sv, "on") == 0 ? 1 : (strcasecmp($sv, "off") == 0 ? 0 : intval($sv));
if ($sv != 0) {
$this->error_config("zlib.output_compression", "off", "With this option enabled, it could occur that XMLHTTP requests will fail");
}
if (CONFIG_CHECK_COOKIES_HTTP) {
$this->checkPHPsecurity("session.cookie_httponly", "on", "Modify this setting in '%s'");
}
if (CONFIG_CHECK_COOKIES_SSL) {
$this->checkPHPsecurity("session.cookie_secure", "on", "Modify this setting in '%s'");
}
# More custom logic needed :(
# When save_path is left unset/empty, ini_get reports it as empty,
# even though PHP uses some directory anyway (usually /tmp).
$sp = ini_get("session.save_path");
if (ini_get("session.save_handler") === 'files' && strlen($sp) > 0 && !$this->checkDirectory(
$sp,
"w",
"session.save_path is not writable. This means PHP is practically running stateless, which is incompatible with the requirements of grommunio-web."
)) {
error_log("session.save_path ({$sp}) is not writable");
}
$this->checkDirectory(TMP_PATH, "rw", "Please make sure this directory exists and is writable for nginx/php-fpm");
$this->checkFunction("iconv", "Install the 'iconv' module for PHP, or else you don't have euro-sign support.");
$this->checkFunction("gzencode", "You don't have zlib support: <a href=\"https://php.net/manual/en/ref.zlib.php#zlib.installation\">https://php.net/manual/en/ref.zlib.php#zlib.installation</a>");
$this->checkLoader(DEBUG_LOADER, "Your 'DEBUG_LOADER' configuration isn't valid for the current folder");
// check if there were *any* errors and we need to stop grommunio Web
if (!$this->result && $this->haltOnError) {
?>
<p style="font-weight: bold;">grommunio Web can't start because of incompatible configuration.</p>
<p>Please correct above errors, a good start is by checking your '<tt><?php echo $this->get_php_ini(); ?></tt>' file.</p>
<p>You can disable this configuration check by editing the file '<tt><?php echo dirname((string) $_SERVER["SCRIPT_FILENAME"]); ?>/config.php</tt>', but this is not recommended.</p>
<?php
exit;
}
}
/**
* This function throws all the errors, make sure that the check-function
* will call this in case of an error.
*
* @param mixed $string
* @param mixed $help
*/
public function error($string, $help) {
if ($this->haltOnError) {
printf("<div style=\"color: #f00;\">%s</div><div style=\"font-size: smaller; margin-left: 20px;\">%s</div>\n", $string, $help);
}
else {
trigger_error(strip_tags((string) $string), E_USER_NOTICE);
}
$this->result = false;
}
/**
* See error().
*
* @param mixed $name
* @param mixed $needed
* @param mixed $found
* @param mixed $help
*/
public function error_version($name, $needed, $found, $help) {
$this->error("<strong>Version error:</strong> {$name} {$found} found, but {$needed} needed.", $help);
}
/**
* See error().
*
* @param mixed $name
* @param mixed $help
*/
public function error_notfound($name, $help) {
$this->error("<strong>Not Found:</strong> {$name} not found", $help);
}
/**
* See error().
*
* @param mixed $name
* @param mixed $needed
* @param mixed $help
*/
public function error_config($name, $needed, $help) {
$help = sprintf($help, "<tt>" . $this->get_php_ini() . "</tt>");
$this->error("<strong>PHP Config error:</strong> {$name} must be '{$needed}'", $help);
}
/**
* See error().
*
* @param mixed $name
* @param mixed $needed
* @param mixed $help
*/
public function error_security($name, $needed, $help) {
$help = sprintf($help, "<tt>" . $this->get_site_config() . "</tt>");
$this->error("<strong>PHP Security Config error:</strong> {$name} must be '{$needed}'", $help);
}
/**
* See error().
*
* @param mixed $dir
* @param mixed $msg
* @param mixed $help
*/
public function error_directory($dir, $msg, $help) {
$this->error("<strong>Directory Error:</strong> {$dir} {$msg}", $help);
}
/**
* Retrieves the location of the apache site config.
*/
public function get_site_config() {
if (isset($this->siteconfig)) {
return $this->siteconfig;
}
// This is not 100% accurate, so it needs to be improved a bit.
$result = "sites-enabled" . DIRECTORY_SEPARATOR . "grommunio-web";
ob_start();
phpinfo(INFO_MODULES);
$phpinfo = ob_get_contents();
ob_end_clean();
preg_match("/<td class=\"e\">[\\s]*Server Root[\\s]*<\\/td>[\\s]*<td class=\"v\">[\\s]*(.*)[\\s]*<\\/td>/i", $phpinfo, $matches);
if (isset($matches[1])) {
$result = trim($matches[1]) . DIRECTORY_SEPARATOR . $result;
}
$this->siteconfig = $result;
return $result;
}
/**
* Retrieves the location of php.ini.
*/
public function get_php_ini() {
if (isset($this->phpini)) {
return $this->phpini;
}
$result = "php.ini";
ob_start();
phpinfo(INFO_GENERAL);
$phpinfo = ob_get_contents();
ob_end_clean();
preg_match("/<td class=\"v\">(.*php[45]?\\.ini)/i", $phpinfo, $matches);
if (isset($matches[0])) {
$result = $matches[0];
}
$this->phpini = $result;
return $result;
}
/*\
* Check functions *
\*/
/**
* Checks for the PHP version.
*
* @param mixed $version
* @param mixed $help_msg
*/
public function checkPHP($version, $help_msg = "") {
$result = true;
if (version_compare(phpversion(), $version) == -1) {
$this->error_version("PHP", $version, phpversion(), $help_msg);
$result = false;
}
return $result;
}
/**
* Check if extension is loaded and if the version is what we need.
*
* @param mixed $name
* @param mixed $version
* @param mixed $help_msg
*/
public function checkExtension($name, $version = "", $help_msg = "") {
$result = true;
if (extension_loaded($name)) {
if (version_compare(phpversion($name), $version) == -1) {
$this->error_version("PHP " . $name . " extension", phpversion($name), $version, $help_msg);
$result = false;
}
}
else {
$this->error_notfound("PHP " . $name . " extension", $help_msg);
$result = false;
}
return $result;
}
/**
* Check if a function exists.
*
* @param mixed $name
* @param mixed $help_msg
*/
public function checkFunction($name, $help_msg = "") {
$result = true;
if (!function_exists($name)) {
$this->error_notfound("PHP function '" . $name . "' ", $help_msg);
$result = false;
}
return $result;
}
/**
* This function checks if a specific php setting (php.ini) is set to a
* value we need, for example register_globals.
*
* @param mixed $setting
* @param mixed $value_needed
* @param mixed $help_msg
*/
public function checkPHPsetting($setting, $value_needed, $help_msg = "") {
$result = true;
$inival = ini_get($setting);
if (strcmp($inival, (string) $value_needed) != 0) {
$this->error_config($setting, $value_needed, $help_msg . " (Current value: \"{$inival}\")");
$result = false;
}
return $result;
}
/**
* This function checks if a specific php setting (php.ini) is set to a
* value we need, for example register_globals.
*
* @param mixed $setting
* @param mixed $value_needed
* @param mixed $help_msg
*/
public function checkPHPsecurity($setting, $value_needed, $help_msg = "") {
$result = true;
// convert $value_needed
$value = match ($value_needed) {
"on", "yes", "true" => 1,
"off", "no", "false" => 0,
default => $value_needed,
};
if (ini_get($setting) != $value) {
$this->error_security($setting, $value_needed, $help_msg);
$result = false;
}
return $result;
}
/**
* This functions checks if a directory exists and if requested also if
* this directory is readable/writable specified with the $states parameter.
*
* $states is a string which can contain these chars:
* r - check if directory is readable
* w - check if directory is writable
*
* @param mixed $dir
* @param mixed $states
* @param mixed $help_msg
*/
public function checkDirectory($dir, $states = "r", $help_msg = "") {
$result = true;
if (!is_dir($dir)) {
if (@mkdir($dir) === false) {
$this->error_directory($dir, "couldn't be created", $help_msg);
}
}
if (is_dir($dir)) {
$states = strtolower((string) $states);
if (str_contains($states, "r")) {
if (!is_readable($dir)) {
$this->error_directory($dir, "isn't readable", $help_msg);
$result = false;
}
}
if (str_contains($states, "w")) {
if (!is_writable($dir)) {
$this->error_directory($dir, "isn't writable", $help_msg);
$result = false;
}
}
}
else {
$this->error_directory($dir, "doesn't exist", $help_msg);
$result = false;
}
return $result;
}
/**
* Check if the correct files are present in the current folder based on the DEBUG_LOADER configuration
* option. This should prevent odd errors when the incorrect folders are present.
*
* @param mixed $loader
* @param mixed $help_msg
*/
public function checkLoader($loader, $help_msg = "") {
$result = true;
switch ($loader) {
case LOAD_RELEASE:
if (!is_file(BASE_PATH . '/client/grommunio.js')) {
$this->error('<strong>LOAD_RELEASE configured, but no release files found</strong>', $help_msg);
$result = false;
}
elseif (is_dir(BASE_PATH . '/client/grommunio')) {
$this->error('<strong>LOAD_RELEASE configured, but source files were found</strong>', $help_msg);
$result = false;
}
break;
case LOAD_DEBUG:
if (!is_file(BASE_PATH . '/client/grommunio-debug.js')) {
$this->error('<strong>LOAD_DEBUG configured, but no debug files found</strong>', $help_msg);
$result = false;
}
elseif (is_dir(BASE_PATH . '/client/grommunio')) {
$this->error('<strong>LOAD_DEBUG configured, but source files were found</strong>', $help_msg);
$result = false;
}
break;
case LOAD_SOURCE:
if (!is_dir(BASE_PATH . '/client/grommunio')) {
$this->error('<strong>LOAD_SOURCE configured, but no source files found</strong>', $help_msg);
$result = false;
}
elseif (is_file(BASE_PATH . '/client/grommunio.js') || is_file(BASE_PATH . '/client/grommunio-debug.js')) {
$this->error('<strong>LOAD_SOURCE configured, but release & debug file were found</strong>', $help_msg);
$result = false;
}
break;
default:
$this->error('<strong>Unknown \'DEBUG_LOADER\' value: ' . $loader . '</strong>', $help_msg);
$result = false;
break;
}
return $result;
}
}
?>
@@ -0,0 +1,679 @@
<?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
*/
/**
* Conversion utility functions for converting various data types and structures.
*/
class Conversion {
/**
* Converts a COleDateTime binary string to an unix timestamp.
*
* The time component of the returned timestamp is 00:00:00
*
* @param int $cOleDateTime is a binary string which represents the number of
* days since 30-12-1899
*
* @return int unix timestamp of given date
*/
public static function COleDateTimeToUnixTime($cOleDateTime) {
$days = unpack("d", $cOleDateTime);
return ($days[1] - 25569) * 24 * 60 * 60; // 25569 is the number of days between 30-12-1899 and 01-01-1970
}
/**
* Converts an unix timestamp to a COleDateTime binary string.
*
* The time component of the unix timestamp is discarded before conversion
*
* @param int $unixtime The unix timestamp to convert
*
* @return string COleDateTime binary string representing the same day
*/
public static function UnixTimeToCOleDateTime($unixtime) {
$days = ($unixtime / (60 * 60 * 24)) + 25569;
return pack("d", $days);
}
/**
* Convert XML properties into MAPI properties.
*
* This function converts an XML array to a MAPI array. For example:
* $props["subject"] = "Meeting" --> $props[PR_SUBJECT] = "Meeting"
*
* If a mapping between a property name ('subject') and a property tag (PR_SUBJECT) cannot be found,
* it is ignored and will not be returned in the return array.
*
* The return value of this function is suitable for direct use in mapi_setprops() or related functions.
*
* Note that a conversion is done between utf-8 and windows-1252 here since all XML data is assumed to be
* utf-8 and all data written to MAPI is windows-1252.
*
* @param array &$props Mapping of property name to MAPI property tag
* @param array &$message_properties Properties to be converted
*
* @return array MAPI property array
*
* @todo This function is slow. Since it is used very very frequently, we could get some speedup from
* optimising this function.
* @todo This function does more than just converting, most notably doing something with 'body'. This needs
* commenting.
*/
public static function mapXML2MAPI(&$props, &$message_properties) {
$properties = [];
foreach ($message_properties as $key => $value) {
// HACK alert !: frontend may send back partial record (eg when setting 'read' when record is not fully loaded). Ignore for now
if (isset($props[$key])) {
$mapi_property = $props[$key];
switch (mapi_prop_type($mapi_property)) {
case PT_LONG:
$properties[$mapi_property] = (int) $value;
break;
case PT_DOUBLE:
$properties[$mapi_property] = (float) $value;
break;
case PT_MV_STRING8:
case PT_MV_STRING8 | MVI_FLAG:
$properties[$mapi_property & ~MV_INSTANCE] = Conversion::splitMultiValue($value);
break;
case PT_MV_BINARY:
// TODO: not supported at the moment
break;
case PT_BINARY:
if (!empty($value)) {
$properties[$mapi_property] = hex2bin((string) $value);
}
break;
case PT_SRESTRICTION:
if (!empty($value)) {
$properties[$mapi_property] = Conversion::json2restriction($props, $value);
}
break;
case PT_ACTIONS:
if (!empty($value)) {
$properties[$mapi_property] = Conversion::json2actions($props, $value);
}
break;
default:
$properties[$mapi_property] = $value;
break;
}
}
}
// The body is a bit special, as we have to consider the HTML body and the plain-text body
$isHTML = isset($message_properties["isHTML"]) && $message_properties["isHTML"] == true;
if (isset($message_properties["html_body"]) && $isHTML) {
$properties[PR_INTERNET_CPID] = 65001; // always write UTF-8 codepage
$properties[PR_HTML] = $message_properties["html_body"];
}
elseif (isset($message_properties["body"]) && !$isHTML) {
$properties[PR_INTERNET_CPID] = 65001; // always write UTF-8 codepage
$properties[PR_BODY] = $message_properties["body"];
}
return $properties;
}
/**
* Convert MAPI properties to XML array.
*
* This function converts a MAPI property array to a XML array. For example:
* $props[PR_SUBJECT] = "Meeting" --> $props["subject"] = "Meeting"
*
* <b>WARNING</b> Properties in PT_STRING8 are assumed to be in windows-1252. This is true
* for all PT_STRING8 properties in MAPI. The data in $props is UTF-8, so the conversion is done
* here.
*
* Conversion is done as the reverse of mapXML2MAPI.
*
* @see Conversion::mapXML2MAPI()
*
* @param array &$props List of MAPI properties
* @param array &$message_properties MAPI array
*
* @return array list of properties which will be sent back to the client
*/
public static function mapMAPI2XML(&$props, &$message_properties) {
$idProps = [PR_ENTRYID => 1, PR_PARENT_ENTRYID => 1, PR_STORE_ENTRYID => 1, PR_RULE_ID => 1];
$properties = ["props" => []];
foreach ($props as $name => $property) {
if (isset($message_properties[$property & ~MVI_FLAG])) {
$property = ($property & ~MVI_FLAG);
}
elseif (!isset($message_properties[$property])) {
continue;
}
// inlined below function for speed (only used here anyway)
$value = $message_properties[$property];
switch (mapi_prop_type($property)) {
case PT_BINARY:
// PR_HTML has PT_BINARY prop type, but it is not necessary
// to convert it to hex.
if ($property != PR_HTML) {
$value = bin2hex((string) $value);
}
break;
case PT_MV_BINARY:
$value = array_map("bin2hex", $value);
break;
case PT_MV_STRING8:
$result = "";
foreach ($value as $entry) {
if (!empty($entry)) {
$result .= $entry . "; ";
}
}
$value = $result;
break;
case PT_SRESTRICTION:
$value = Conversion::restriction2json($value);
break;
case PT_ACTIONS:
$value = Conversion::actions2json($value);
break;
}
if (isset($idProps[$property])) {
// put identification properties to root level
$properties[$name] = $value;
}
else {
$properties["props"][$name] = $value;
}
}
if (empty($properties["props"])) {
unset($properties["props"]);
}
return $properties;
}
/* JSON related functions */
/**
* Convert a JSON reference to a property into a MAPI property tag.
*
* Note that this depends on the definition of the property tag constants
* in mapitags.php
* Mappings are defined per module in class.properties.php
*
* @example json2property('subject') => 0x0037001e
* @example this also works json2property('PR_SUBJECT') => 0x0037001e
*
* @param array $mapping props A mapping of property names to their corresponding MAPI property tags
* @param string $prop property name
* @param bool $convertToSingleValued whether to convert the multi valued property tag to single valued or not
*
* @return int The property tag
*/
public static function json2property($mapping, $prop, $convertToSingleValued = false) {
$propTag = false;
if (isset($mapping[$prop])) {
// Normally we would go for this case, where the property is defined in our mapping
$propTag = $mapping[$prop];
}
elseif (defined($prop)) {
// This is for cases where the proptag reference is defined as a constant, e.g. PR_BODY
$propTag = constant($prop);
}
elseif (substr_count($prop, ':') == 2) {
// This is for named properties, e.g. 'PT_STRING8:PSETID_Address:0x8005'
$props = getPropIdsFromStrings($GLOBALS["mapisession"]->getDefaultMessageStore(), [$prop]);
$propTag = $props[0];
}
else {
// In this case we expect the string to be a hex id of the proptag
$propTag = hexdec($prop);
}
// if getting multi valued property then sometimes we need to convert it to
// its single valued counterpart to use in VALUES structure of restriction
if ($convertToSingleValued) {
$propTag = Conversion::convertToSingleValuedProperty($propTag);
}
return $propTag;
}
/**
* Convert a MAPI property tag into a JSON reference.
*
* Note that this depends on the definition of the property tag constants
* in mapitags.php
*
* @example property2json(0x0037001e) => 'PR_SUBJECT'
*
* @param int|string $property property tag or an already converted value
*
* @return string the symbolic name or original string value
*/
public static function property2json($property) {
static $names = [];
if (!is_integer($property)) {
return $property;
}
if (empty($names)) {
// Retrieve constants categories, zcore provides them in 'Core'
foreach (get_defined_constants(true)['Core'] as $key => $value) {
if (is_int($value) && str_starts_with($key, 'PR_')) {
$names[$value] ??= $key;
}
}
}
return $names[$property] ?? sprintf("0x%08X", $property);
}
/**
* Splits a ';' separated multi-valued string, dropping empty entries.
*
* @param mixed $value
*
* @return string[]
*/
private static function splitMultiValue($value) {
$values = [];
foreach (explode(";", (string) $value) as $mv_value) {
if (!empty($mv_value)) {
$values[] = ltrim($mv_value);
}
}
return $values;
}
/**
* Convert an JSON restriction structure into a MAPI SRestriction array.
*
* @param array $mapping An associative array mapping property keys to MAPI proptags
* @param mixed $json The parsed JSON restriction data
*
* @return mixed MAPI restriction data compatible with MAPI extension restriction format
*/
public static function json2restriction($mapping, $json) {
if (!is_array($json)) {
return $json;
}
switch ($json[0]) {
case RES_AND:
case RES_OR:
if (isset($json[1][0]) && is_array($json[1][0])) {
foreach ($json[1] as &$res) {
$res = Conversion::json2restriction($mapping, $res);
}
unset($res);
}
elseif (!empty($json[1])) {
$json[1] = Conversion::json2restriction($mapping, $json[1]);
}
break;
case RES_NOT:
// Note that a normal RES_NOT restriction should not be placed
// in an array, but the php-ext does expect an array to be
// given, so we wrap it here.
$json[1] = [Conversion::json2restriction($mapping, $json[1])];
break;
case RES_COMMENT:
$props = [];
foreach ($json[1][PROPS] as $propTag => $propValue) {
$propTag = Conversion::json2property($mapping, $propTag);
if (mapi_prop_type($propTag) === PT_BINARY) {
$propValue = hex2bin((string) $propValue);
}
$props[$propTag] = $propValue;
}
$json[1][PROPS] = $props;
$json[1][RESTRICTION] = Conversion::json2restriction($mapping, $json[1][RESTRICTION]);
break;
case RES_PROPERTY:
case RES_CONTENT:
$json[1][ULPROPTAG] = Conversion::json2property($mapping, $json[1][ULPROPTAG]);
$value = [];
foreach ($json[1][VALUE] as $propTag => $propValue) {
$propTag = Conversion::json2property($mapping, $propTag);
$type = mapi_prop_type($propTag);
if ($type === PT_BINARY) {
$propValue = hex2bin((string) $propValue);
}
elseif ($type === PT_MV_STRING8) {
$propValue = Conversion::splitMultiValue($propValue);
}
$value[$propTag] = $propValue;
}
unset($json[1][VALUE]);
$json[1][VALUE] = $value;
break;
case RES_COMPAREPROPS:
$json[1][ULPROPTAG1] = Conversion::json2property($mapping, $json[1][ULPROPTAG1]);
$json[1][ULPROPTAG2] = Conversion::json2property($mapping, $json[1][ULPROPTAG2]);
break;
case RES_BITMASK:
case RES_SIZE:
case RES_EXIST:
$json[1][ULPROPTAG] = Conversion::json2property($mapping, $json[1][ULPROPTAG]);
break;
case RES_SUBRESTRICTION:
$json[1][ULPROPTAG] = Conversion::json2property($mapping, $json[1][ULPROPTAG]);
$json[1][RESTRICTION] = Conversion::json2restriction($mapping, $json[1][RESTRICTION]);
break;
}
return $json;
}
/**
* Convert a MAPI SRestriction array into an JSON restriction structure.
*
* @param mixed $restriction The MAPI Restriction array
*
* @return array Array structure that can be easily serialized to JSON format
*/
public static function restriction2json($restriction) {
if (!is_array($restriction)) {
return $restriction;
}
switch ($restriction[0]) {
case RES_AND:
case RES_OR:
if (!empty($restriction[1][0])) {
foreach ($restriction[1] as &$res) {
$res = Conversion::restriction2json($res);
}
unset($res);
}
elseif (!empty($restriction[1])) {
$restriction[1] = Conversion::restriction2json($restriction[1]);
}
break;
case RES_NOT:
// Note that a normal RES_NOT restriction should not be placed
// in an array, but the php-ext does put it in one, so unwrap it here.
$restriction[1] = Conversion::restriction2json($restriction[1][0]);
break;
case RES_COMMENT:
$restriction[1][RESTRICTION] = Conversion::restriction2json($restriction[1][RESTRICTION]);
$props = [];
foreach ($restriction[1][PROPS] as $propTag => $propValue) {
if (mapi_prop_type($propTag) === PT_BINARY) {
$propValue = bin2hex((string) $propValue);
}
$props[Conversion::property2json($propTag)] = is_array($propValue) ? $propValue[$propTag] : $propValue;
}
unset($restriction[1][PROPS]);
$restriction[1][PROPS] = $props;
break;
case RES_COMPAREPROPS:
$restriction[1][ULPROPTAG1] = Conversion::property2json($restriction[1][ULPROPTAG1]);
$restriction[1][ULPROPTAG2] = Conversion::property2json($restriction[1][ULPROPTAG2]);
break;
case RES_PROPERTY:
case RES_CONTENT:
$restriction[1][ULPROPTAG] = Conversion::property2json($restriction[1][ULPROPTAG]);
$value = [];
foreach ($restriction[1][VALUE] as $propTag => $propValue) {
if (mapi_prop_type($propTag) === PT_BINARY) {
$propValue = bin2hex((string) $propValue);
}
$value[Conversion::property2json($propTag)] = $propValue;
}
// remove non restriction data
unset($restriction[1][VALUE]);
$restriction[1][VALUE] = $value;
break;
case RES_BITMASK:
case RES_SIZE:
case RES_EXIST:
$restriction[1][ULPROPTAG] = Conversion::property2json($restriction[1][ULPROPTAG]);
break;
case RES_SUBRESTRICTION:
$restriction[1][ULPROPTAG] = Conversion::property2json($restriction[1][ULPROPTAG]);
$restriction[1][RESTRICTION] = Conversion::restriction2json($restriction[1][RESTRICTION]);
break;
}
return $restriction;
}
/**
* Retrieves singlevalued counterpart of a multivalued property.
*
* Multivalued properties has different property tags in VALUES part
* so we need to find that singlevalued property tag
*
* @param int|string $propTag The multivalued property tag
*
* @return int|string The singlevalued property tag
*/
public static function convertToSingleValuedProperty($propTag) {
if (is_string($propTag)) {
// if the string starts with '0x' then we have
// an acceptable propTag on which we can work
// to change the MV_flag value
if (str_starts_with($propTag, '0x')) {
$propTag = hexdec($propTag);
$propTag &= ~MV_FLAG;
$propTag = '0x' . strtoupper(str_pad((string) dechex_32($propTag), 8, '0', STR_PAD_LEFT));
}
}
else {
// If numeric, just remove the MV_FLAG
$propTag &= ~MV_FLAG;
}
return $propTag;
}
/**
* Converts a JSON Representation of PT_ACTIONS value array to its MAPI form.
*
* @param array $actions JSON representation PT_ACTIONS structure
* @param mixed $mapping
*
* @return array Converted PT_ACTIONS structure that can be used in MAPI
*/
public static function json2actions($mapping, $actions) {
foreach ($actions as &$action) {
foreach ($action as $key => $value) {
switch ($key) {
case 'storeentryid':
case 'folderentryid':
case 'replyentryid':
case 'replyguid':
case 'dam':
$action[$key] = hex2bin((string) $value);
break;
case 'adrlist':
$recipients = [];
foreach ($value as $addr) {
$recipient = [];
foreach ($addr as $addrkey => $addrval) {
$addrkey = Conversion::json2property($mapping, $addrkey);
if (mapi_prop_type($addrkey) === PT_BINARY) {
$addrval = hex2bin((string) $addrval);
}
$recipient[$addrkey] = $addrval;
}
unset($addrval);
$recipients[] = $recipient;
}
unset($addr);
$action[$key] = $recipients;
break;
}
}
}
return $actions;
}
/**
* Converts a MAPI PT_ACTIONS value array to its JSON representation.
*
* @param array $actions MAPI PT_ACTIONS structure
*
* @return array Converted PT_ACTIONS structure that can be used in javascript
*/
public static function actions2json($actions) {
foreach ($actions as &$action) {
foreach ($action as $key => $value) {
switch ($key) {
case 'storeentryid':
case 'folderentryid':
case 'replyentryid':
case 'replyguid':
case 'dam':
$action[$key] = bin2hex((string) $value);
break;
case 'adrlist':
$recipients = [];
foreach ($value as $addr) {
$recipient = [];
foreach ($addr as $addrkey => $addrval) {
if (mapi_prop_type($addrkey) === PT_BINARY) {
$addrval = bin2hex((string) $addrval);
}
$recipient[Conversion::property2json($addrkey)] = $addrval;
}
unset($addrval);
$recipients[] = $recipient;
}
unset($addr);
$action[$key] = $recipients;
break;
}
}
}
return $actions;
}
/**
* Get charset name from a codepage.
*
* @param mixed $codepage
*
* @return string iconv-compatible charset name
*/
public static function getCodepageCharset($codepage) {
return \getCodepageCharset((int) $codepage);
}
/**
* Tries to find the character set of a given string.
*
* @param string $string The string for which a charset is requested
*
* @return string
*/
private static function findCharSet($string) {
// Let's try mb_detect_encoding first
$charset = mb_detect_encoding($string, "auto");
if ($charset !== false) {
return $charset;
}
// Trying every known encoding is pointless. There
// is at least one encoding where all imaginable input byte
// sequences are valid, and a heuristic would pick that even if
// it is completely inaccurate. So just return a fixed charset
// here.
//
// With
// https://en.wikipedia.org/wiki/Popularity_of_text_encodings
// in mind, we want to pick an ASCII-compatible encoding so
// that not everything becomes illegible (like with "cp037"),
// but where codepage mismatch is otherwise apparent. This
// necessitates a non-poular charset, so iso-8859-1/15,
// cp1251/1252, utf-8 are all ruled out.
//
return "cp850";
}
/**
* Converts a string with a given codepage to utf-8.
*
* @param int $codepage The codepage of the given string
* @param string $string The string that must be converted
*
* @return string
*/
public static function convertCodepageStringToUtf8($codepage, $string) {
$charset = Conversion::getCodepageCharset($codepage);
// Sometimes a mail identifies itself with a charset that it really isn't, so let's do an extra check
// Only do the extra check if iconv was able to convert string. See grommunio-web#142
$converted = iconv($charset, $charset, $string);
if ($converted !== false && strlen($converted) !== strlen($string)) {
$foundCharset = Conversion::findCharSet($string);
if ($foundCharset) {
$charset = $foundCharset;
}
}
return iconv($charset, "utf-8", $string);
}
}
@@ -0,0 +1,91 @@
<?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.DispatcherException.php';
/**
* On-demand module loader.
*
* The dispatcher is simply a class instance factory, returning an instance of a class. If
* the source was not loaded yet, then the specified file is loaded.
*/
class Dispatcher {
public function __construct() {}
/**
* Load a module with a specific name.
*
* If required, loads the source for the module, then instantiates a module of that type
* with the specified id and initial data. The $id and $data parameters are directly
* forwarded to the module constructor.
*
* Source is loaded from server/modules/class.$modulename.php
*
* @param string $moduleName The name of the module which should be loaded (eg 'hierarchymodule')
* @param int $id Unique id number which represents this module
* @param array $data Array of data which is received from the client
*
* @return object Module object on success, false on failed
*/
public function loadModule($moduleName, $id, $data) {
$module = false;
$path = BASE_PATH . 'server/includes/modules/class.' . $moduleName . '.php';
if (is_file($path) === true) {
require_once $path;
$module = new $moduleName($id, $data);
}
else {
$path = $GLOBALS['PluginManager']->getModuleFilePath($moduleName);
if (is_file($path)) {
require_once $path;
$module = new $moduleName($id, $data);
}
else {
throw new DispatcherException(sprintf(_("Unknown module '%s' with id '%s'"), $moduleName, $id), 0, null, _("Server encountered some problem, so it was not able to handle the request."));
}
}
return $module;
}
/**
* Load a notifier with a specific name.
*
* If required, loads the source for the notifier, then instantiates a notifier of that type.
*
* Source is loaded from server/notifiers/class.$notifiername.php
*
* @param string $notifierName The name of the module which should be loaded (eg 'hierarchynotifier')
*
* @return object Notifier object on success, false on failed
*/
public function loadNotifier($notifierName) {
$notifier = false;
$path = BASE_PATH . 'server/includes/notifiers/class.' . $notifierName . '.php';
if (is_file($path) === true) {
require_once $path;
$notifier = new $notifierName();
}
else {
$path = $GLOBALS['PluginManager']->getNotifierFilePath($notifierName);
if (is_file($path)) {
require_once $path;
$notifier = new $notifierName();
}
else {
throw new DispatcherException(sprintf(_("Unknown notifier '%s'"), $notifierName), 0, null, _("Server encountered some problem, so it was not able to handle the request."));
}
}
return $notifier;
}
}
@@ -0,0 +1,309 @@
<?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.webappsession.php';
/**
* The EncryptionStore class can be used to store strings in an encrypted
* way in the PHP session. The initialization vector will be stored in the
* session, but the encryption key will be stored in a cookie.
* This way the encrypted strings and the encryption key will not be
* stored on the same computer.
*
* The class uses the openssl libs to handle the encryption. This means
* that the openssl libs should be available on the system, and PHP
* should be compiled with the following option --with-openssl[=DIR]
* See http://php.net/manual/en/openssl.installation.php for more information.
*
* @singleton
*/
class EncryptionStore {
/**
* Holds the only instance of this class.
*
* @var null|EncryptionStore
*/
private static $_instance;
// TODO: Should this be moved to config.php???
public const _CIPHER_METHOD = 'aes-256-cbc';
public const _SESSION_KEY = 'encryption-store';
private static $_initializionVector = '';
private static $_encryptionKey = '';
/**
* Will create a store and an initialization vector in the session
* if that hasn't been done yet.
*/
private function __construct() {
// Make sure the php session is started
WebAppSession::getInstance();
// Create an encryption store in the session if it doesn't exist yet
if (!isset($_SESSION[EncryptionStore::_SESSION_KEY])) {
$_SESSION[EncryptionStore::_SESSION_KEY] = [];
}
// Check if we have an initializing vector stored in the session
// If we don't, then we will create a new one, together with a new
// encryption key
$iv = $this->getInitializationVector();
if (empty($iv)) {
$this->createInitializationVector();
$this->createEncryptionKey();
}
else {
// If there is a encryption store in the session then we
// can get the encryption key from the cookie.
$this->getEncryptionKey();
}
$this->removeExpiredEntries();
}
/**
* Returns the only instance of this class.
* Creates one if it doesn't exist yet.
*
* @return object
*/
public static function getInstance() {
if (is_null(EncryptionStore::$_instance)) {
EncryptionStore::$_instance = new EncryptionStore();
}
return EncryptionStore::$_instance;
}
/**
* Creates a random initialization vector and stores it in the php session.
*/
private function createInitializationVector() {
EncryptionStore::$_initializionVector = openssl_random_pseudo_bytes(openssl_cipher_iv_length(EncryptionStore::_CIPHER_METHOD));
// Store it in the session
$_SESSION['encryption-store-iv'] = bin2hex(EncryptionStore::$_initializionVector);
}
/**
* Returns the initialization vector. If necessary it will try to find the vector
* in the php session.
*
* @return string
*/
private function getInitializationVector() {
if (empty(EncryptionStore::$_initializionVector)) {
// Try to find the initialization vector in the session
if (isset($_SESSION['encryption-store-iv'])) {
EncryptionStore::$_initializionVector = hex2bin((string) $_SESSION['encryption-store-iv']);
}
}
return EncryptionStore::$_initializionVector;
}
/**
* Creates a random encryption key and stores it in the cookie.
*/
private function createEncryptionKey() {
EncryptionStore::$_encryptionKey = openssl_random_pseudo_bytes(openssl_cipher_iv_length(EncryptionStore::_CIPHER_METHOD));
$cookieName = 'encryption-store-key';
$secure = useSecureCookies();
if ($secure) {
$cookieName = '__Secure-' . $cookieName;
}
$path = ini_get('session.cookie_path');
$domain = ini_get('session.cookie_domain');
setcookie($cookieName, bin2hex(EncryptionStore::$_encryptionKey), [
'expires' => 0,
'path' => $path,
'domain' => $domain,
'secure' => $secure,
'httponly' => true,
// SameSite=None without Secure is rejected by browsers
'samesite' => $secure ? 'None' : 'Lax',
]);
if (!$secure) {
// expire a stale prefixed cookie from an earlier secure config,
// it would otherwise shadow the one written above
setcookie('__Secure-encryption-store-key', '', [
'expires' => 1,
'path' => $path,
'domain' => $domain,
'secure' => true,
'httponly' => true,
'samesite' => 'None',
]);
}
}
/**
* Returns the encryption key. If necessary it will try to find the key in
* the cookie.
*
* @return string
*/
private function getEncryptionKey() {
if (empty(EncryptionStore::$_encryptionKey)) {
// Try to find the encryption key in the cookie. The read mirrors
// createEncryptionKey(): with secure cookies the name carries the
// __Secure- prefix. The unprefixed fallback covers sessions from
// before the prefixed name was read; the prefixed name is ignored
// with SECURE_COOKIES=false, where it can only be a stale cookie
// the server is unable to overwrite.
if (useSecureCookies() && isset($_COOKIE['__Secure-encryption-store-key'])) {
EncryptionStore::$_encryptionKey = hex2bin((string) $_COOKIE['__Secure-encryption-store-key']);
}
elseif (isset($_COOKIE['encryption-store-key'])) {
EncryptionStore::$_encryptionKey = hex2bin((string) $_COOKIE['encryption-store-key']);
}
}
return EncryptionStore::$_encryptionKey;
}
/*
* Remove expired entries from the $_SESSION
*/
private function removeExpiredEntries() {
// Remove expired entries
foreach ($_SESSION[EncryptionStore::_SESSION_KEY] ?? [] as $key => $value) {
if (!isset($value['exp'])) {
continue;
}
if ($value['exp'] < time()) {
unset($_SESSION[EncryptionStore::_SESSION_KEY][$key]);
}
}
}
/**
* Adds a key/value combination to the encryption store.
*
* @param string $key The key that will be added (or overwritten)
* @param string $value The value that will be stored for the given $key
* @param string $expiration The expiration time in epoch for the given $key
*/
public function add($key, $value, $expiration = 0) {
$session_did_exists = $this->open_session(true);
// When the session was closed early (e.g. by WebAppSession for
// grommunio.php), the IV that was created in __construct() only
// lives in the static variable — $_SESSION was already written
// to disk before the IV existed. Re-opening the session above
// reloaded $_SESSION from the file, losing the IV. Persist it
// now so that future requests can find it.
if (!empty(EncryptionStore::$_initializionVector)) {
$_SESSION['encryption-store-iv'] = bin2hex(EncryptionStore::$_initializionVector);
}
$encryptedValue = openssl_encrypt($value, EncryptionStore::_CIPHER_METHOD, EncryptionStore::$_encryptionKey, 0, EncryptionStore::$_initializionVector);
$_SESSION[EncryptionStore::_SESSION_KEY][$key] = ['val' => $encryptedValue];
if ($expiration) {
$_SESSION[EncryptionStore::_SESSION_KEY][$key]['exp'] = $expiration;
}
$this->close_session($session_did_exists);
}
/**
* Returns the value that has been stored for the given $key.
*
* @param string $key key whose value should be retrieved
*
* @return null|string
*/
public function get($key) {
$session_did_exists = $this->open_session();
try {
$this->removeExpiredEntries();
$values = $_SESSION[EncryptionStore::_SESSION_KEY][$key] ?? null;
if (!isset($values['val'])) {
return null;
}
return openssl_decrypt($values['val'], EncryptionStore::_CIPHER_METHOD, EncryptionStore::$_encryptionKey, 0, EncryptionStore::$_initializionVector);
}
finally {
$this->close_session($session_did_exists);
}
}
/**
* Atomically consume a value under the PHP session handler's exclusive lock.
* Unlike get(), this must reload a previously closed session: its cached
* snapshot may contain a receipt already consumed by another request.
* The entry is removed even when decryption fails. A caller that already
* owns the session lock retains it until its usual session close.
*
* @return false|null|string
*/
public function take($key) {
$opened = $this->open_session(true);
try {
if (!$this->session_exists()) {
throw new RuntimeException('Cannot lock the encrypted session store.');
}
$this->removeExpiredEntries();
$values = $_SESSION[EncryptionStore::_SESSION_KEY][$key] ?? null;
unset($_SESSION[EncryptionStore::_SESSION_KEY][$key]);
if (!isset($values['val'])) {
return null;
}
return openssl_decrypt($values['val'], EncryptionStore::_CIPHER_METHOD, EncryptionStore::$_encryptionKey, 0, EncryptionStore::$_initializionVector);
}
finally {
$this->close_session($opened);
}
}
/**
* Open the php session if it isn't open.
*
* @param mixed $forWrite
*
* @return bool return if the session was opened or not
*/
private function open_session($forWrite = false) {
if (!$this->session_exists()) {
// For read-only access, if session data was loaded into
// memory (e.g. via read_and_close), skip reopening to
// avoid the session file lock.
if (!$forWrite && isset($_SESSION[self::_SESSION_KEY])) {
return false;
}
session_start();
return true;
}
return false;
}
/**
* Close session if it was explicitly opened.
*
* @param bool $opened whether the session was opened
*/
private function close_session($opened) {
if ($this->session_exists() && $opened) {
session_write_close();
}
}
/**
* Returns true if the session exists otherwise false.
*
* @return bool true if session exists
*/
private function session_exists() {
return session_status() === PHP_SESSION_ACTIVE;
}
}
@@ -0,0 +1,664 @@
<?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
*/
class EntryId {
/* Bit definitions for abFlags[3] of ENTRYID */
public const GROMMUNIO_FAVORITE = '01';
/* GUID of root public folder */
public const STATIC_GUID_PUBLICFOLDER = '00000000000000000000000000000003';
/* GUID of root favorite folder */
public const STATIC_GUID_FAVORITE = '00000000000000000000000000000002';
/* GUID of ipm_subtree of public store */
public const STATIC_GUID_FAVSUBTREE = '00000000000000000000000000000001';
/* GUID of Global Addressbook */
public const MUIDECSAB = 'AC21A95040D3EE48B319FBA753304425';
/* GUID of Contact Provider */
public const MUIDZCSAB = '727F0430E3924FDAB86AE52A7FE46571';
/* GUID for OneOff entryid */
public const MAPI_ONE_OFF_UID = '812B1FA4BEA310199D6E00DD010F5402';
/* GUID for Address book recipient */
public const MUIDEMSAB = 'DCA740C8C042101AB4B908002B2FE182';
/* Hardcoded ID used for generating entryid of addressbook container */
public const GROMMUNIO_UID_ADDRESS_BOOK = '00000000';
/* Hardcoded ID used for generating entryid of global addressbook container */
public const GROMMUNIO_UID_GLOBAL_ADDRESS_BOOK = '01000000';
/* Hardcoded ID used for generating entryid of global addresslists container */
public const GROMMUNIO_UID_GLOBAL_ADDRESS_LISTS = '02000000';
public function __construct() {}
// Detect padding (max 3 bytes) from the entryId
private function getPadding($entryId) {
$len = strlen((string) $entryId);
$padding = '';
$offset = 0;
for ($iterations = 4; $iterations > 0; --$iterations) {
if (substr((string) $entryId, $len - ($offset + 2), $len - $offset) == '00') {
$padding .= '00';
$offset += 2;
}
else {
// if non-null character found then break the loop
break;
}
}
return $padding;
}
/**
* Entryid from version 6.
*
* @param mixed $entryid
*
* @return array
*/
private function getEIDVersion($entryid) {
// always make entryids in uppercase so comparison will be case insensitive
$entryId = strtoupper((string) $entryid);
$res = [
'abFlags' => '', // BYTE[4], 4 bytes, 8 hex characters
'guid' => '', // GUID, 16 bytes, 32 hex characters
'version' => '', // ULONG, 4 bytes, 8 hex characters
'type' => '', // ULONG, 4 bytes, 8 hex characters
'uniqueId' => '', // ULONG, 16 bytes, 32 hex characters
'server' => '', // CHAR, variable length
'padding' => '', // TCHAR[3], 4 bytes, 8 hex characters (upto 4 bytes)
];
$res['length'] = strlen($entryId);
$offset = 0;
// First determine padding, and remove if from the entryId
$res['padding'] = $this->getPadding($entryId);
$entryId = substr($entryId, 0, strlen($entryId) - strlen((string) $res['padding']));
$res['abFlags'] = substr($entryId, $offset, 8);
$offset = +8;
$res['guid'] = substr($entryId, $offset, 32);
$offset += 32;
$res['version'] = substr($entryId, $offset, 8);
$offset += 8;
$res['type'] = substr($entryId, $offset, 8);
$offset += 8;
$res['uniqueId'] = substr($entryId, $offset, 32);
$offset += 32;
$res['server'] = substr($entryId, $offset);
$res['min_length'] = 88;
$res['name'] = 'EID';
return $res;
}
/**
* The entryid from the begin of grommunio till 5.20.
*
* @param mixed $entryid
*
* @return array
*/
private function getEID_V0Version($entryid) {
// always make entryids in uppercase so comparison will be case insensitive
$entryId = strtoupper((string) $entryid);
$res = [
'abFlags' => '', // BYTE[4], 4 bytes, 8 hex characters
'guid' => '', // GUID, 16 bytes, 32 hex characters
'version' => '', // ULONG, 4 bytes, 8 hex characters
'type' => '', // ULONG, 4 bytes, 8 hex characters
'id' => '', // ULONG, 4 bytes, 8 hex characters
'server' => '', // CHAR, variable length
'padding' => '', // TCHAR[3], 4 bytes, 8 hex characters (upto 4 bytes)
];
$res['length'] = strlen($entryId);
$offset = 0;
// First determine padding, and remove if from the entryId
$res['padding'] = $this->getPadding($entryId);
$entryId = substr($entryId, 0, strlen($entryId) - strlen((string) $res['padding']));
$res['abFlags'] = substr($entryId, $offset, 8);
$offset = +8;
$res['guid'] = substr($entryId, $offset, 32);
$offset += 32;
$res['version'] = substr($entryId, $offset, 8);
$offset += 8;
$res['type'] = substr($entryId, $offset, 8);
$offset += 8;
$res['id'] = substr($entryId, $offset, 8);
$offset += 8;
$res['server'] = substr($entryId, $offset);
$res['min_length'] = 64;
$res['name'] = 'EID_V0';
return $res;
}
/**
* Addressbook Entryid.
*
* @param mixed $entryId
*
* @return array
*/
private function getABEIDVersion($entryId) {
// always make entryids in uppercase so comparison will be case insensitive
$entryId = strtoupper((string) $entryId);
$res = [
'abFlags' => '', // BYTE[4], 4 bytes, 8 hex characters
'guid' => '', // GUID, 16 bytes, 32 hex characters
'version' => '', // ULONG, 4 bytes, 8 hex characters
'type' => '', // ULONG, 4 bytes, 8 hex characters
'id' => '', // ULONG, 16 bytes, 32 hex characters
'extid' => '', // CHAR, variable length
'padding' => '', // TCHAR[3], 4 bytes, 8 hex characters (upto 4 bytes)
];
$res['length'] = strlen($entryId);
$offset = 0;
// First determine padding, and remove if from the entryId
$res['padding'] = $this->getPadding($entryId);
$entryId = substr($entryId, 0, strlen($entryId) - strlen((string) $res['padding']));
$res['abFlags'] = substr($entryId, $offset, 8);
$offset = +8;
$res['guid'] = substr($entryId, $offset, 32);
$offset += 32;
$res['version'] = substr($entryId, $offset, 8);
$offset += 8;
$res['type'] = substr($entryId, $offset, 8);
$offset += 8;
$res['id'] = substr($entryId, $offset, 8);
$offset += 8;
$res['extid'] = substr($entryId, $offset);
$res['min_length'] = 88;
$res['name'] = 'ABEID';
return $res;
}
/**
* Creates an object that has split up all the components of an entryID.
*
* @param mixed $entryid
*
* @return array EntryID object
*/
private function createEntryIdObj($entryid) {
// check if we are dealing with old or new object entryids
$versionString = substr((string) $entryid, 40, 8);
if ($versionString == '00000000') {
// use EID_V0 struct
$eidObj = $this->getEID_V0Version($entryid);
}
else {
// use EID struct
$eidObj = $this->getEIDVersion($entryid);
}
return $eidObj;
}
/**
* Compares two entryIds. It is possible to have two different entryIds that should match as they
* represent the same object (in multiserver environments).
*
* @param mixed $entryId1
* @param mixed $entryId2
*
* @return bool Result of the comparison
*/
public function compareEntryIds($entryId1, $entryId2) {
return \compareEntryIds($entryId1, $entryId2);
}
/**
* Creates an object that has split up all the components of an addressbook entryid.
*
* @param mixed $abEntryId unwrapped addressbook entryid
*
* @return array addresbook entryid object
*/
public function createABEntryIdObj($abEntryId) {
return $this->getABEIDVersion($abEntryId);
}
/**
* Creates an object that has wrapped a normal entryid using the AddressBook Provider GUID.
*
* @param mixed $entryId unwrapped entryid
* @param mixed $objType The ObjectType which represents the object
*
* @return string wrapped addresbook entryid object
*/
public function wrapABEntryIdObj($entryId, $objType) {
$objType = dechex($objType);
// add padding for the type, which is of 4 bytes (8 characters)
$objType = str_pad($objType, 2, '0', STR_PAD_LEFT);
$objType = str_pad($objType, 8, '0', STR_PAD_RIGHT);
return '00000000' . self::MUIDZCSAB . $objType . '00000000' . $entryId;
}
/**
* Unwrap a Address Book Provider Entryid to a normal entryid.
*
* @param mixed $abEntryId wrapped entryid
*
* @return string unwrapped entryid
*/
public function unwrapABEntryIdObj($abEntryId) {
// Remove ulVersion (8 char), muid (32 char), ulObjType (8 char) and ulOffset (8 char)
return substr((string) $abEntryId, 56);
}
/**
* Checks if the passed folder entryid is a folder in the favorites folder, favorites folder
* contains 0x01 in the abFlags[3] flag.
*
* @param mixed $entryId folder entryid
*
* @return bool true of folder is a favorite folder else false
*/
public function isFavoriteFolder($entryId) {
$entryIdObj = $this->createEntryIdObj($entryId);
return substr((string) $entryIdObj['abFlags'], 6, 8) == self::GROMMUNIO_FAVORITE;
}
/**
* Checks if the GUID part of the entryid is of the contact provider.
*
* @param mixed $entryId Addressbook entryid
*
* @return bool true if guid matches contact provider else false
*/
public function hasContactProviderGUID($entryId) {
$entryIdObj = $this->createABEntryIdObj($entryId);
return $entryIdObj['guid'] == self::MUIDZCSAB;
}
/**
* Checks if the GUID part of the entryid is of the Global Addressbook.
*
* @param mixed $entryId Address Book entryid
*
* @return bool true if guid matches the Global Addressbook else false
*/
public function hasAddressBookGUID($entryId) {
$entryIdObj = $this->createABEntryIdObj($entryId);
return $entryIdObj['guid'] == self::MUIDECSAB;
}
/**
* Checks if the GUID part of the entryid is of the Address book recipient.
*
* @param mixed $entryId Address Book entryid
*
* @return bool true if guid matches the Ab recipient else false
*/
public function hasAddressBookRecipientGUID($entryId) {
$entryIdObj = $this->createABEntryIdObj($entryId);
return $entryIdObj['guid'] == self::MUIDEMSAB;
}
/**
* Checks if the GUID part of the entryid is of the OneOff.
*
* @param mixed $entryId Address Book entryid
*
* @return bool true if guid matches the OneOff else false
*/
public function hasAddressBookOneOff($entryId) {
$entryIdObj = $this->createABEntryIdObj($entryId);
return $entryIdObj['guid'] == self::MAPI_ONE_OFF_UID;
}
/**
* Creates an object that has split up all the components of an message store entryid.
*
* @param mixed $entryId message store entryid
*
* @return array message store entryid object
*/
public function createMsgStoreEntryIdObj($entryId) {
$res = [
'Flags' => '',
'ProviderUID' => '',
'Version' => '',
'Flag' => '',
'DLLFileName' => '',
'WrappedFlags' => '',
'WrappedProviderUID' => '',
'WrappedType' => '',
'ServerShortname' => '',
'MailboxDN' => '',
'V2' => [
'Magic' => '',
'Size' => '',
'Version' => '',
'OffsetDN' => '',
'OffsetFQDN' => '',
'ServerDN' => '',
'ServerFQDN' => '',
'ReservedBlock' => '',
],
'V3' => [
'Magic' => '',
'Size' => '',
'Version' => '',
'OffsetSmtpAddress' => '',
'SmtpAddress' => '',
],
];
if (!$entryId) {
return $res;
}
$offset = 0;
if (!$this->getAndCheckComponents($entryId, $offset, 4, 0x0, $res, 'Flags')) {
return $res;
}
$offset += 4;
if (!$this->getAndCheckComponents($entryId, $offset, 16, MUID_STORE_WRAP_GUID, $res, 'ProviderUID')) {
return $res;
}
$offset += 16;
if (!$this->getAndCheckComponents($entryId, $offset, 1, 0x0, $res, 'Version')) {
return $res;
}
++$offset;
if (!$this->getAndCheckComponents($entryId, $offset, 1, 0x0, $res, 'Flag')) {
return $res;
}
++$offset;
if (!$this->getAndCheckComponents($entryId, $offset, 10, 'emsmdb.dll', $res, 'DLLFileName')) {
return $res;
}
$offset += 14;
if (!$this->getAndCheckComponents($entryId, $offset, 4, 0x0, $res, 'WrappedFlags')) {
return $res;
}
$offset += 4;
if (!$this->getAndCheckComponents($entryId, $offset, 16, [MUID_STORE_PRIVATE_GUID, MUID_STORE_PUBLIC_GUID], $res, 'WrappedProviderUID')) {
return $res;
}
$offset += 16;
if (!$this->getAndCheckComponents($entryId, $offset, 4, array_map('hex2bin', ['0C000000', '06000000']), $res, 'WrappedType')) {
return $res;
}
$offset += 4;
$zeroBytePos = strpos((string) $entryId, "\0", $offset);
if ($zeroBytePos !== false) {
$res['ServerShortname'] = trim(substr((string) $entryId, $offset, $zeroBytePos - $offset));
$offset = $zeroBytePos + 1;
}
$zeroBytePos = strpos((string) $entryId, "\0", $offset);
if ($zeroBytePos !== false) {
$res['MailboxDN'] = trim(substr((string) $entryId, $offset, $zeroBytePos - $offset));
}
// TODO V2 and V3 structs
return $res;
}
/**
* Reads $len bytes beginning from $start of the $entryid,
* checks if the value of resulting string is expected and adds it
* to $res object in such case.
*
* @param string $entryId message store entryid
* @param int $start start position of the value to get
* @param int $len length in bytes of the value to get
* @param mixed $checkValue value to check against
* @param array $res message store entryid object
* @param string $key component name
*
* @return bool true if the component has the expected value, false otherwise
*/
private function getAndCheckComponents($entryId, $start, $len, $checkValue, &$res, $key) {
$val = substr($entryId, $start, $len);
if (is_int($checkValue)) {
$val = intval($val);
}
if (is_array($checkValue)) {
if (!in_array($val, $checkValue)) {
error_log(sprintf(
"Unexpected value in store entryid for user %s. Entryid: %s key: '%s' value: '%s' expected: %s",
$GLOBALS["mapisession"]->getUserName(),
bin2hex($entryId),
$key,
$val,
implode(', ', array_map('bin2hex', $checkValue))
));
return false;
}
}
elseif ($checkValue !== null && $val != $checkValue) {
$user = $GLOBALS["mapisession"] !== null ? $GLOBALS["mapisession"]->getUserName() :
"<mapisession not yet initialized>";
error_log(sprintf(
"Unexpected value in store entryid for user %s. Entryid: %s key: '%s' value: '%s' expected: %s",
$user,
bin2hex($entryId),
$key,
$val,
/* @scrutinizer ignore-type */
$checkValue
));
return false;
}
$res[$key] = $val;
return true;
}
/**
* Creates an object that has split up all the components of a message entryid.
*
* @param mixed $entryId message entryid
*
* @return array message entryid object
*/
public function createMessageEntryIdObj($entryId) {
// always make entryids in uppercase so comparison will be case insensitive
$entryId = strtoupper((string) $entryId);
$res = [
'providerguid' => '', // GUID, 16 bytes, 32 hex characters
'messagetype' => '', // UINT, 2 bytes, 4 hex characters
'folderdbguid' => '', // GUID, 16 bytes, 32 hex characters
'foldercounter' => '', // ULONG, 6 bytes, 12 hex characters
'padding' => '', // TCHAR[3], 2 bytes, 4 hex characters
'messagedbguid' => '', // GUID, 16 bytes, 32 hex characters
'messagecounter' => '', // ULONG, 6 bytes, 12 hex characters
];
if (!$entryId) {
return $res;
}
$res['length'] = strlen($entryId);
$offset = 0;
$res['providerguid'] = substr($entryId, $offset, 32);
$offset += 32;
$res['messagetype'] = substr($entryId, $offset, 4);
$offset += 4;
$res['folderdbguid'] = substr($entryId, $offset, 32);
$offset += 32;
$res['foldercounter'] = substr($entryId, $offset, 12);
$offset += 12;
$res['padding'] = substr($entryId, $offset, 4);
$offset += 4;
$res['messagedbguid'] = substr($entryId, $offset, 32);
$offset += 32;
$res['messagecounter'] = substr($entryId, $offset, 12);
$offset += 12;
return $res;
}
/**
* Creates a folder entryid with provided parameters.
*
* @param string $providerguid provider guid
* @param int $foldertype folder type flag
* @param string $folderdbguid folder db guid
* @param string $foldercounter folder counter
*
* @return string folder entryid
*/
public function createFolderEntryId($providerguid, $foldertype, $folderdbguid, $foldercounter) {
return strtoupper('00000000' . $providerguid . $foldertype . $folderdbguid . $foldercounter . '0000');
}
/**
* Creates an object that has split up all the components of a folder entryid.
*
* @param mixed $entryId folder entryid
*
* @return array folder entryid object
*/
public function createFolderEntryIdObj($entryId) {
// always make entryids in uppercase so comparison will be case insensitive
$entryId = strtoupper((string) $entryId);
$res = [
'abflags' => '', // BYTE[4], 4 bytes, 8 hex characters
'providerguid' => '', // GUID, 16 bytes, 32 hex characters
'foldertype' => '', // UINT, 2 bytes, 4 hex characters
'folderdbguid' => '', // GUID, 16 bytes, 32 hex characters
'foldercounter' => '', // ULONG, 6 bytes, 12 hex characters
'padding' => '', // TCHAR[3], 2 bytes, 4 hex characters
];
if (!$entryId) {
return $res;
}
$res['length'] = strlen($entryId);
$offset = 0;
$res['abflags'] = substr($entryId, $offset, 8);
$offset += 8;
$res['providerguid'] = substr($entryId, $offset, 32);
$offset += 32;
$res['foldertype'] = substr($entryId, $offset, 4);
$offset += 4;
$res['folderdbguid'] = substr($entryId, $offset, 32);
$offset += 32;
$res['foldercounter'] = substr($entryId, $offset, 12);
$offset += 12;
$res['padding'] = substr($entryId, $offset, 4);
$offset += 4;
return $res;
}
/**
* Creates a Muidemsab entryid with provided parameters.
*
* @param string $user username
*
* @return string Muidemsab entryid
*/
public function createMuidemsabEntryid($user) {
return "00000000dca740c8c042101ab4b908002b2fe1820100000000000000" . bin2hex($user);
}
/**
* Checks if the GUID part of the entryid has one of the known MUIDs.
*
* @param mixed $entryId Addressbook entryid
* @param array $entryIdObj Addressbook entryid object
*
* @return bool true if guid matches one of the known MUIDs else false
*/
public function hasNoMuid($entryId, $entryIdObj = []) {
if (empty($entryIdObj)) {
$entryIdObj = $this->createABEntryIdObj($entryId);
}
return $entryIdObj['guid'] != self::MUIDZCSAB &&
$entryIdObj['guid'] != self::MUIDECSAB &&
$entryIdObj['guid'] != self::MUIDEMSAB;
}
/**
* Creates a message entryid from an entryid object.
*
* @param array $eidObj
*
* @return string message entry id
*/
public function createMessageEntryId($eidObj) {
return $eidObj['guid'] . $eidObj['version'] . $eidObj['type'] . $eidObj['id'] . $eidObj['extid'];
}
}
// Create global entryId object
$GLOBALS["entryid"] = new EntryId();
@@ -0,0 +1,243 @@
<?php
/*
* SPDX-FileCopyrightText: Copyright 2020 - 2026 grommunio GmbH
* SPDX-License-Identifier: AGPL-3.0-or-later
*/
/**
* Builds the SQLite FTS5 query and its bindings for a search descriptor.
*/
class FtsQueryBuilder {
/** @var callable */
private $log;
/**
* @param null|callable $logger receives a debug message and its context
*/
public function __construct(?callable $logger = null) {
$this->log = $logger ?? static function () {};
}
/**
* Return [sql, bindings, ftsQuery], or null when the AST yields no expression.
*
* @param mixed $descriptor
* @param array $folderIds folder ids the search is limited to, empty for all
*
* @return null|array
*/
public function build($descriptor, array $folderIds) {
$message_classes = $descriptor['message_classes'] ?? null;
$date_start = $descriptor['date_start'] ?? null;
$date_end = $descriptor['date_end'] ?? null;
$unread = !empty($descriptor['unread']);
$has_attachments = !empty($descriptor['has_attachments']);
[$ast, $excluded] = self::splitNegation($descriptor['ast'] ?? null);
$ftsQuery = $this->compile($ast);
if ($ftsQuery === null || $ftsQuery === '') {
return null;
}
$whereClauses = [];
$bindings = [];
if (!empty($folderIds)) {
$folderPlaceholders = [];
foreach (array_values(array_unique(array_map("intval", $folderIds))) as $index => $folderId) {
$placeholder = ":folder_id_" . $index;
$folderPlaceholders[] = $placeholder;
$bindings[] = [$placeholder, $folderId, SQLITE3_INTEGER];
}
$whereClauses[] = "c.folder_id in (" . implode(", ", $folderPlaceholders) . ")";
}
// FTS5 NOT is binary, so a query of exclusions only is matched as a set difference
$whereClauses[] = $excluded ? "c.message_id NOT IN (SELECT rowid FROM messages WHERE messages MATCH :fts_query)" : "messages MATCH :fts_query";
$bindings[] = [":fts_query", $ftsQuery, SQLITE3_TEXT];
// Push filters into SQL so LIMIT applies to already-filtered rows.
// PHP-side filtering in IndexSqlite::filter_content() is kept as a safety net.
if ($date_start !== null) {
$whereClauses[] = "c.date >= :date_start";
$bindings[] = [":date_start", (int) $date_start, SQLITE3_INTEGER];
}
if ($date_end !== null) {
$whereClauses[] = "c.date <= :date_end";
$bindings[] = [":date_end", (int) $date_end, SQLITE3_INTEGER];
}
if ($unread) {
$whereClauses[] = "(c.readflag IS NULL OR c.readflag = 0)";
}
if ($has_attachments) {
$whereClauses[] = "c.attach_indexed = 1";
}
if (is_array($message_classes) && $message_classes !== []) {
$classConditions = [];
foreach (array_values($message_classes) as $index => $mc) {
$placeholder = ":message_class_" . $index;
$classConditions[] = "c.message_class LIKE " . $placeholder;
$bindings[] = [$placeholder, (string) $mc . "%", SQLITE3_TEXT];
}
$whereClauses[] = "(" . implode(" OR ", $classConditions) . ")";
}
$bindings[] = [":limit", (int) MAX_FTS_RESULT_ITEMS, SQLITE3_INTEGER];
$sql = "SELECT c.message_id, c.entryid, c.folder_id, " .
"c.message_class, c.date, c.readflag, c.attach_indexed " .
"FROM msg_content c " .
"JOIN messages m ON c.message_id = m.rowid " .
"WHERE " . implode(" AND ", $whereClauses) .
" ORDER BY c.date DESC LIMIT :limit";
return [$sql, $bindings, $ftsQuery];
}
/**
* Split a NOT node, or an AND of NOT nodes only, into the AST to exclude.
*
* @param mixed $ast
*
* @return array [ast, excluded]
*/
private static function splitNegation($ast) {
$op = $ast['op'] ?? null;
$children = $ast['children'] ?? [];
if ($op === 'NOT') {
return [$children[0] ?? null, true];
}
$negated = array_filter($children, fn ($child) => ($child['op'] ?? null) === 'NOT' && isset($child['children'][0]));
if ($op !== 'AND' || $children === [] || count($negated) !== count($children)) {
return [$ast, false];
}
$excluded = array_map(fn ($child) => $child['children'][0], array_values($negated));
return [count($excluded) > 1 ? ['op' => 'OR', 'children' => $excluded] : $excluded[0], true];
}
/**
* Compile a search AST into an FTS5 MATCH expression.
*
* @param mixed $ast
*
* @return null|string
*/
public function compile($ast) {
if ($ast === null) {
return null;
}
if (isset($ast['type']) && $ast['type'] === 'term') {
$fields = $ast['fields'] ?? [];
if (empty($fields)) {
return null;
}
$words = $this->quoteWords($ast['value'] ?? '');
if (empty($words)) {
return null;
}
$segments = [];
foreach ($fields as $field) {
$fieldWords = [];
foreach ($words as $word) {
$fieldWords[] = $field . ':' . $word;
}
$segments[] = implode(' ', $fieldWords);
}
if (count($segments) === 1) {
return $segments[0];
}
return '(' . implode(' OR ', array_map(function ($s) {
return '(' . $s . ')';
}, $segments)) . ')';
}
$operator = $ast['op'] ?? null;
$children = $ast['children'] ?? [];
if ($operator === 'NOT') {
$child = $this->compile($children[0] ?? null);
if ($child === null) {
return null;
}
return 'NOT (' . $child . ')';
}
if ($operator === 'AND' || $operator === 'OR') {
// In FTS5, NOT is a binary infix operator (a NOT b), not a
// unary prefix. When an AND node contains NOT children we
// must emit them with the FTS5 NOT operator instead of
// producing the invalid "a AND (NOT b)" form.
$positiveParts = [];
$negativeParts = [];
foreach ($children as $child) {
if ($operator === 'AND' && isset($child['op']) && $child['op'] === 'NOT') {
$compiled = $this->compile($child['children'][0] ?? null);
if ($compiled !== null) {
$negativeParts[] = $compiled;
}
}
else {
$compiled = $this->compile($child);
if ($compiled !== null) {
$positiveParts[] = $compiled;
}
}
}
if (empty($positiveParts) && empty($negativeParts)) {
return null;
}
if (empty($positiveParts)) {
// FTS5 NOT requires a left-hand operand
return null;
}
if (count($positiveParts) === 1) {
$result = $positiveParts[0];
}
else {
$wrapped = array_map(function ($segment) {
return '(' . $segment . ')';
}, $positiveParts);
$result = implode(' ' . $operator . ' ', $wrapped);
}
foreach ($negativeParts as $neg) {
$result = '(' . $result . ') NOT (' . $neg . ')';
}
return $result;
}
return null;
}
private function quoteWords($search_string) {
$words = preg_split('/\s+/', trim($search_string), -1, PREG_SPLIT_NO_EMPTY);
// With the trigram tokenizer terms shorter than 3 characters cause a
// full table scan instead of an index lookup. Skip them to avoid
// excessive CPU usage.
$minLength = (SQLITE_FTS_TOKENIZER === 'trigram') ? 3 : 1;
$quoted = [];
foreach ($words as $word) {
if (mb_strlen($word) < $minLength) {
($this->log)('Skipping short search term', [
'term' => $word,
'min_length' => $minLength,
'tokenizer' => SQLITE_FTS_TOKENIZER,
]);
continue;
}
$quoted[] = '"' . SQLite3::escapeString($word) . '"*';
if (MAX_FTS_QUERY_TERMS > 0 && count($quoted) >= MAX_FTS_QUERY_TERMS) {
($this->log)('Search term limit reached', [
'limit' => MAX_FTS_QUERY_TERMS,
'total_words' => count($words),
]);
break;
}
}
return $quoted;
}
}
@@ -0,0 +1,272 @@
<?php
/*
* SPDX-FileCopyrightText: Copyright 2020 - 2026 grommunio GmbH
* SPDX-License-Identifier: AGPL-3.0-or-later
*/
/**
* Converts a MAPI search restriction into the query AST and the side filters
* (message classes, date range, unread, attachments) of the full-text index.
*/
class FtsRestrictionConverter {
private $properties;
/**
* @param array $properties the search module's property tags
*/
public function __construct($properties) {
$this->properties = $properties;
}
public function buildDescriptor($restriction) {
[$ast, $filters] = $this->convert($restriction);
$filters['message_classes'] = array_values(array_unique($filters['message_classes']));
return [
'ast' => $ast,
'message_classes' => $filters['message_classes'],
'date_start' => $filters['date_start'],
'date_end' => $filters['date_end'],
'unread' => $filters['unread'],
'has_attachments' => $filters['has_attachments'],
];
}
/**
* @param mixed $restriction
* @param null|string $context 'attachments' or 'recipients' inside a subrestriction
*
* @return array [ast node or null, filter state]
*/
public function convert($restriction, $context = null) {
$filters = FtsFilterState::create();
if (!is_array($restriction) || empty($restriction)) {
return [null, $filters];
}
$type = $restriction[0];
switch ($type) {
case RES_AND:
case RES_OR:
return $this->convertList($type, $restriction, $context, $filters);
case RES_NOT:
return $this->convertNot($restriction, $context, $filters);
case RES_CONTENT:
return $this->convertContent($restriction, $context, $filters);
case RES_PROPERTY:
return $this->convertProperty($restriction, $filters);
case RES_BITMASK:
$subres = $restriction[1];
if (($subres[ULPROPTAG] ?? null) == PR_MESSAGE_FLAGS && ($subres[ULTYPE] ?? null) == BMR_EQZ) {
$filters['unread'] = true;
}
return [null, $filters];
case RES_SUBRESTRICTION:
return $this->convertSubRestriction($restriction, $context, $filters);
case RES_COMMENT:
return $this->convertInner($restriction[1][RESTRICTION] ?? null, $context, $filters);
default:
return [null, $filters];
}
}
private function mapPropTagToFields($propTag, $context = null) {
if (in_array($context, ['attachments', 'recipients'], true)) {
return [$context];
}
static $map = null;
if ($map === null) {
$map = [
PR_SUBJECT => ['subject'],
PR_BODY => ['content', 'attachments'],
PR_SENDER_NAME => ['sender'],
PR_SENDER_EMAIL_ADDRESS => ['sender'],
PR_SENT_REPRESENTING_NAME => ['sending'],
PR_SENT_REPRESENTING_EMAIL_ADDRESS => ['sending'],
PR_DISPLAY_TO => ['recipients'],
PR_DISPLAY_CC => ['recipients'],
PR_DISPLAY_BCC => ['recipients'],
PR_EMAIL_ADDRESS => ['recipients'],
PR_SMTP_ADDRESS => ['recipients'],
PR_DISPLAY_NAME => ['others'],
PR_ATTACH_LONG_FILENAME => ['attachments'],
];
if (defined('PR_NORMALIZED_SUBJECT')) {
$map[PR_NORMALIZED_SUBJECT] = ['subject'];
}
if (isset($this->properties['categories'])) {
$map[$this->properties['categories']] = ['others'];
}
}
return $map[$propTag] ?? [];
}
/**
* Null for no children, the child itself for one, an $op node otherwise.
*
* @param string $op
*/
private static function combine($op, array $children) {
if (count($children) > 1) {
return [
'op' => $op,
'children' => $children,
];
}
return $children[0] ?? null;
}
private function convertInner($inner, $context, array $filters) {
[$childAst, $childFilters] = $this->convert($inner, $context);
return [$childAst, FtsFilterState::merge($filters, $childFilters)];
}
private function convertList($type, $restriction, $context, array $filters) {
$children = [];
$subRestrictions = $restriction[1] ?? [];
if (is_array($subRestrictions)) {
foreach ($subRestrictions as $subRestriction) {
[$childAst, $filters] = $this->convertInner($subRestriction, $context, $filters);
if ($childAst !== null) {
$children[] = $childAst;
}
}
}
return [self::combine($type == RES_AND ? 'AND' : 'OR', $children), $filters];
}
private function convertNot($restriction, $context, array $filters) {
[$childAst, $filters] = $this->convertInner($restriction[1][0] ?? null, $context, $filters);
if ($childAst === null) {
return [null, $filters];
}
return [[
'op' => 'NOT',
'children' => [$childAst],
], $filters];
}
private function convertContent($restriction, $context, array $filters) {
$subres = $restriction[1];
$propTag = $subres[ULPROPTAG] ?? null;
if ($propTag === null) {
return [null, $filters];
}
$value = $subres[VALUE][$propTag] ?? null;
if ($propTag == PR_MESSAGE_CLASS) {
if ($value !== null) {
$filters['message_classes'][] = $value;
}
return [null, $filters];
}
$fields = $this->mapPropTagToFields($propTag, $context);
if (empty($fields) || $value === null) {
return [null, $filters];
}
// A scalar '' still yields a term, empty array entries do not.
$values = is_array($value) ? array_filter($value, fn ($entry) => !in_array($entry, ['', null], true)) : [$value];
$terms = [];
foreach ($values as $entry) {
$terms[] = [
'type' => 'term',
'fields' => $fields,
'value' => (string) $entry,
];
}
return [self::combine('OR', $terms), $filters];
}
private function convertProperty($restriction, array $filters) {
$subres = $restriction[1];
$propTag = $subres[ULPROPTAG] ?? null;
if ($propTag === null) {
return [null, $filters];
}
if (in_array($propTag, [PR_MESSAGE_DELIVERY_TIME, PR_LAST_MODIFICATION_TIME])) {
$value = $subres[VALUE][$propTag] ?? null;
if ($value !== null) {
if (in_array($subres[RELOP], [RELOP_LT, RELOP_LE])) {
$filters['date_end'] = $value;
}
elseif (in_array($subres[RELOP], [RELOP_GT, RELOP_GE])) {
$filters['date_start'] = $value;
}
}
return [null, $filters];
}
if (isset($this->properties['hide_attachments']) && $propTag == $this->properties['hide_attachments']) {
$filters['has_attachments'] = true;
}
return [null, $filters];
}
private function convertSubRestriction($restriction, $context, array $filters) {
$subres = $restriction[1];
$propTag = $subres[ULPROPTAG] ?? null;
if ($propTag == PR_MESSAGE_ATTACHMENTS) {
$filters['has_attachments'] = true;
$context = 'attachments';
}
elseif ($propTag == PR_MESSAGE_RECIPIENTS) {
$context = 'recipients';
}
return $this->convertInner($subres[RESTRICTION] ?? null, $context, $filters);
}
}
/**
* Filter state of a converted restriction, as a plain array.
*/
final class FtsFilterState {
public static function create() {
return [
'message_classes' => [],
'date_start' => null,
'date_end' => null,
'unread' => false,
'has_attachments' => false,
];
}
public static function merge(array $base, array $delta) {
$base['message_classes'] = array_merge($base['message_classes'], $delta['message_classes']);
if ($delta['date_start'] !== null) {
$base['date_start'] = max($base['date_start'] ?? $delta['date_start'], $delta['date_start']);
}
if ($delta['date_end'] !== null) {
$base['date_end'] = min($base['date_end'] ?? $delta['date_end'], $delta['date_end']);
}
$base['unread'] = $base['unread'] || $delta['unread'];
$base['has_attachments'] = $base['has_attachments'] || $delta['has_attachments'];
return $base;
}
}
@@ -0,0 +1,84 @@
<?php
/*
* SPDX-FileCopyrightText: Copyright 2020 - 2026 grommunio GmbH
* SPDX-License-Identifier: AGPL-3.0-or-later
*/
/**
* Validates and normalizes HTTP(S) origins.
*/
class HttpOrigin {
/**
* Extract and normalize the origin portion of an absolute HTTP(S) URL.
*
* @param mixed $url
*
* @return null|string
*/
public static function fromUrl($url) {
if (!is_string($url) || $url === '' || strlen($url) > 4096 ||
preg_match('/[\x00-\x20\x5c\x7f]/', $url) === 1) {
return null;
}
$parts = @parse_url($url);
if ($parts === false || !isset($parts['scheme'], $parts['host']) ||
isset($parts['user']) || isset($parts['pass'])) {
return null;
}
$host = trim((string) $parts['host'], '[]');
$authority = str_contains($host, ':') ? '[' . $host . ']' : $host;
if (isset($parts['port'])) {
$authority .= ':' . $parts['port'];
}
return self::normalize($parts['scheme'] . '://' . $authority);
}
/**
* Normalize an HTTP origin for exact comparisons and safe reflection.
*
* @param mixed $origin
*
* @return null|string
*/
public static function normalize($origin) {
if (!is_string($origin) || $origin === '' || strlen($origin) > 4096 ||
preg_match('/[\x00-\x20\x5c\x7f]/', $origin) === 1) {
return null;
}
$parts = @parse_url($origin);
if ($parts === false || !in_array(strtolower($parts['scheme'] ?? ''), ['http', 'https'], true) ||
empty($parts['host']) || isset($parts['user']) || isset($parts['pass']) ||
isset($parts['query']) || isset($parts['fragment']) ||
(isset($parts['path']) && $parts['path'] !== '' && $parts['path'] !== '/')) {
return null;
}
$scheme = strtolower($parts['scheme']);
$host = trim(strtolower((string) $parts['host']), '[]');
if (filter_var($host, FILTER_VALIDATE_IP) === false) {
$host = rtrim($host, '.');
if ($host === '' || strlen($host) > 253 ||
preg_match('/\A(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)(?:\.(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?))*\z/iD', $host) !== 1) {
return null;
}
}
$defaultPort = $scheme === 'https' ? 443 : 80;
$port = $parts['port'] ?? $defaultPort;
if (!is_int($port) || $port < 1 || $port > 65535) {
return null;
}
$authority = str_contains($host, ':') ? '[' . $host . ']' : $host;
if ($port !== $defaultPort) {
$authority .= ':' . $port;
}
return $scheme . '://' . $authority;
}
}
@@ -0,0 +1,178 @@
<?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
*/
define('ICONSETS_PATH', 'client/resources/iconsets');
/**
* This class provides some functionality for theming grommunio Web.
*/
class Iconsets {
/**
* A hash that is used to cache the properties of iconsets.
*
* @var array
*/
private static $iconsetsCache = [];
/**
* Retrieves all installed iconsets.
*
* @return array An array with the directory names of the iconsets as keys and their display names
* as values
*/
public static function getIconsets() {
if (empty(Iconsets::$iconsetsCache)) {
$baseDirs = [
BASE_PATH . constant('ICONSETS_PATH'),
BASE_PATH . PATH_PLUGIN_DIR,
];
foreach ($baseDirs as $dir) {
$directoryIterator = new DirectoryIterator($dir);
foreach ($directoryIterator as $info) {
if ($info->isDot() || !$info->isDir()) {
continue;
}
if (!is_file($info->getPathname() . DIRECTORY_SEPARATOR . 'iconset.json')) {
continue;
}
$props = Iconsets::getProps($info->getPathname(), $info->getFileName());
if (!$props) {
continue;
}
if (!isset($props['stylesheet'])) {
// We cannot do anything with an iconset without a stylesheet
continue;
}
if (!isset($props['display-name'])) {
$props['display-name'] = $info->getFileName();
}
$props['stylesheet'] = substr($info->getPathname(), strlen(BASE_PATH)) . DIRECTORY_SEPARATOR . $props['stylesheet'];
Iconsets::$iconsetsCache[$info->getFileName()] = $props;
}
}
}
return Iconsets::$iconsetsCache;
}
/**
* Returns the name of the active iconset if one was found, and false otherwise.
* The active iconset can be set by the admin in the config.php, or by
* the user in his settings.
*
* @return bool|string
*/
public static function getActiveIconset() {
$iconset = false;
$installedIconsets = Iconsets::getIconsets();
// First check if a iconset was set by this user in his settings
if (WebAppAuthentication::isAuthenticated()) {
if (ENABLE_ICONSETS === false) {
$iconset = ICONSET !== "" ? ICONSET : 'breeze';
}
else {
$iconset = $GLOBALS['settings']->get('grommunio/v1/main/active_iconset');
}
if (!isset($iconset) || empty($iconset) || !array_key_exists($iconset, $installedIconsets)) {
$iconset = false;
}
}
// If a valid iconset was not found in the settings of the user, let's see if a one
// was defined by the admin.
if (!$iconset && defined('ICONSET') && ICONSET && array_key_exists(ICONSET, $installedIconsets)) {
$iconset = ICONSET;
}
// If no valid iconset was found, we'll use the default one
if (!$iconset) {
$iconset = 'classic';
}
return $iconset;
}
/**
* Returns the stylesheet of the active icon set.
*
* @return string The stylesheet of the active icon set
*/
public static function getActiveStylesheet() {
$iconsets = Iconsets::getIconsets();
$activeIconset = Iconsets::getActiveIconset();
return versionedUrl($iconsets[$activeIconset]['stylesheet']);
}
/**
* Returns an array with the about texts of the iconsets.
*
* @return array an array with the ids of the iconsets as keys and
* an array with the display name and the about text as values
*/
public static function getAboutTexts() {
$iconsets = Iconsets::getIconsets();
$about = [];
foreach ($iconsets as $i) {
if (!empty($i['about'])) {
$about[$i['id']] = [
'displayName' => $i['display-name'],
'about' => $i['about'],
];
}
}
return $about;
}
/**
* Retrieves the properties set in the iconset.json file of the iconset.
*
* @param string $dir The directory of the iconset for which the properties should be retrieved
* @param mixed $id
*
* @return array<string, mixed>|false The properties defined in iconset.json, or false when the
* file cannot be read or does not contain an array of properties
*/
public static function getProps($dir, $id) {
// Check if we have the props in the cache before reading the file
if (isset(Iconsets::$iconsetsCache[$id])) {
return Iconsets::$iconsetsCache[$id];
}
$json = @file_get_contents($dir . DIRECTORY_SEPARATOR . '/iconset.json');
if ($json === false) {
error_log("The iconset '{$id}' does not have a readable iconset.json file.");
return false;
}
$props = json_decode($json, true);
if (json_last_error() !== JSON_ERROR_NONE) {
error_log("The iconset '{$id}' does not have a valid iconset.json file. " . json_last_error_msg());
return false;
}
if (!is_array($props)) {
error_log("The iconset '{$id}' iconset.json file must contain an array of properties.");
return false;
}
return $props;
}
}
@@ -0,0 +1,548 @@
<?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__ . '/class.ftsquerybuilder.php';
define('PRIVATE_FID_ROOT', 0x1);
define('PR_FOLDER_ID', 0x67480014);
define('PR_MID', 0x674A0014);
define('PR_CHANGE_NUMBER', 0x67A40014);
class IndexSqlite extends SQLite3 {
private $username;
private $count;
private $store;
private $session;
private $openResult;
private const DEBUG_SAMPLE_LIMIT = 5;
private function logDebug(string $message, array $context = []): void {
if (!DEBUG_FULLTEXT_SEARCH) {
return;
}
$prefix = '[fts-debug][index] ';
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 static function formatEntryIdForLog($entryid) {
if ($entryid === null) {
return null;
}
if (is_array($entryid)) {
return array_map([self::class, 'formatEntryIdForLog'], $entryid);
}
if (!is_string($entryid)) {
return $entryid;
}
return bin2hex($entryid);
}
private static function formatBinaryFieldForLog($value) {
if ($value === null) {
return null;
}
if (!is_string($value)) {
return $value;
}
if (preg_match('/[^\x20-\x7E]/', $value)) {
return bin2hex($value);
}
return $value;
}
private static function get_gc_value($eid) {
$r0 = ($eid >> 56) & 0xFF;
$r1 = ($eid >> 48) & 0xFF;
$r2 = ($eid >> 40) & 0xFF;
$r3 = ($eid >> 32) & 0xFF;
$r4 = ($eid >> 24) & 0xFF;
$r5 = ($eid >> 16) & 0xFF;
$value = $r0 | ($r1 << 8) | ($r2 << 16) | ($r3 << 24) | ($r4 << 32) | ($r5 << 40);
return $value;
}
public function __construct($username = null, $session = null, $store = null) {
$this->username = $username ?? $GLOBALS["mapisession"]->getSMTPAddress();
$this->session = $session ?? $GLOBALS["mapisession"]->getSession();
$this->store = $store ?? $GLOBALS["mapisession"]->getDefaultMessageStore();
$indexPath = SQLITE_INDEX_PATH . '/' . $this->username . '/index.sqlite3';
try {
$this->open($indexPath, SQLITE3_OPEN_READONLY);
$this->openResult = 0;
$this->logDebug('Opened index database', ['path' => $indexPath]);
}
catch (Exception $e) {
$this->openResult = 1;
$this->logDebug('Failed to open index database', [
'path' => $indexPath,
'error' => $e->getMessage(),
]);
}
}
public function is_open() {
return !$this->openResult;
}
/**
* Apply the per-result filters and return the message entryid that should
* be linked into the search folder, or null when the row is filtered out
* or unusable. Linking itself is deferred to the caller so it can be
* batched into a single RPC instead of one round trip per message.
*
* @param mixed $row
* @param mixed $message_classes
* @param mixed $date_start
* @param mixed $date_end
* @param mixed $unread
* @param mixed $has_attachments
*/
private function filter_content(
$row,
$message_classes,
$date_start,
$date_end,
$unread,
$has_attachments
) {
// if match condition contains '@', $row['entryid'] will disappear. it seems a bug for php-sqlite
if (empty($row['entryid'])) {
$results = $this->query("SELECT entryid FROM msg_content WHERE message_id=" . $row['message_id']);
$row1 = $results->fetchArray(SQLITE3_NUM);
if ($row1 !== false && !empty($row1[0])) {
$row['entryid'] = $row1[0];
$this->logDebug('Recovered missing entryid from msg_content', [
'message_id' => $row['message_id'],
]);
}
// abort if the entryid is not available
else {
error_log(sprintf("No entryid available, not possible to link the message %d.", $row['message_id']));
$this->logDebug('Missing entryid prevents linking message', [
'message_id' => $row['message_id'],
]);
return null;
}
}
if (is_array($message_classes) && $message_classes !== []) {
$found = false;
foreach ($message_classes as $message_class) {
if (strncasecmp((string) $row['message_class'], (string) $message_class, strlen((string) $message_class)) == 0) {
$found = true;
break;
}
}
if (!$found) {
$this->logDebug('Skipping message because message class is filtered out', [
'message_id' => $row['message_id'] ?? null,
'message_class' => $row['message_class'] ?? null,
]);
return null;
}
}
if ($date_start !== null && $row['date'] < $date_start) {
$this->logDebug('Skipping message before start date filter', [
'message_id' => $row['message_id'] ?? null,
'message_date' => $row['date'] ?? null,
'date_start' => $date_start,
]);
return null;
}
if ($date_end !== null && $row['date'] > $date_end) {
$this->logDebug('Skipping message after end date filter', [
'message_id' => $row['message_id'] ?? null,
'message_date' => $row['date'] ?? null,
'date_end' => $date_end,
]);
return null;
}
if ($unread && $row['readflag']) {
$this->logDebug('Skipping message because unread flag filter is active', [
'message_id' => $row['message_id'] ?? null,
'readflag' => $row['readflag'] ?? null,
]);
return null;
}
if ($has_attachments && !$row['attach_indexed']) {
$this->logDebug('Skipping message because attachment filter is active', [
'message_id' => $row['message_id'] ?? null,
'attach_indexed' => $row['attach_indexed'] ?? null,
]);
return null;
}
return $row['entryid'];
}
/**
* Link the collected result entryids into the search folder. When the
* php-mapi extension exposes the batch binding (mapi_linkmessages), all
* messages are linked in a single RPC; otherwise we fall back to the
* per-message mapi_linkmessage path so a new web release keeps working
* against an older gromox. Returns the number of linked messages.
*
* @param mixed $search_entryid
*/
private function link_entryids($search_entryid, array $entryids): int {
if ($entryids === []) {
return 0;
}
if (function_exists('mapi_linkmessages')) {
try {
mapi_linkmessages($this->session, $search_entryid, $entryids);
return count($entryids);
}
catch (Exception $e) {
$details = [
'count' => count($entryids),
'error' => $e->getMessage(),
'hresult' => mapi_last_hresult(),
];
$this->logDebug('MAPI linkmessages (batch) failed, falling back to per-message linking', $details);
// fall through to the per-message path below
}
}
$linked = 0;
foreach ($entryids as $entryid) {
try {
mapi_linkmessage($this->session, $search_entryid, $entryid);
}
catch (Exception $e) {
$details = [
'entryid' => self::formatBinaryFieldForLog($entryid),
'error' => $e->getMessage(),
'hresult' => mapi_last_hresult(),
];
$this->logDebug('MAPI linkmessage failed', $details);
continue;
}
++$linked;
}
return $linked;
}
/**
* Runs the query and links every hit into the given search folder.
* Only usable for stores that can host a search folder, i.e. private ones.
*
* @param mixed $search_entryid
* @param mixed $descriptor
* @param mixed $folder_entryid
* @param mixed $recursive
*/
public function search($search_entryid, $descriptor, $folder_entryid, $recursive) {
$this->logDebug('Search invoked', [
'user' => $this->username,
'search_entryid' => self::formatEntryIdForLog($search_entryid),
'folder_entryid' => self::formatEntryIdForLog($folder_entryid),
'recursive' => (bool) $recursive,
'descriptor' => $descriptor,
]);
$entryids = $this->collectEntryIds($descriptor, $folder_entryid, $recursive);
if ($entryids === false) {
return false;
}
$linkStart = microtime(true);
$this->count = $this->link_entryids($search_entryid, $entryids);
$this->logDebug('Search results linked', [
'selected_messages' => count($entryids),
'linked_messages' => $this->count,
'batch_link' => function_exists('mapi_linkmessages'),
'duration_ms' => (int) round((microtime(true) - $linkStart) * 1000),
]);
return true;
}
/**
* Runs the query and returns the matching message entryids, most recent
* first. Public stores cannot host a search folder - gromox rejects
* creating one and refuses to link public messages into a private one - so
* for those the caller builds the result list straight from these ids.
*
* @param mixed $descriptor
* @param mixed $folder_entryid
* @param mixed $recursive
*
* @return array|false
*/
public function searchEntryIds($descriptor, $folder_entryid, $recursive) {
$this->logDebug('Search (entryid list) invoked', [
'user' => $this->username,
'folder_entryid' => self::formatEntryIdForLog($folder_entryid),
'recursive' => (bool) $recursive,
'descriptor' => $descriptor,
]);
return $this->collectEntryIds($descriptor, $folder_entryid, $recursive);
}
/**
* Shared query path: resolves the folder scope, runs the FTS query and
* applies the filters, returning the surviving entryids in date order.
*
* @param mixed $descriptor
* @param mixed $folder_entryid
* @param mixed $recursive
*
* @return array|false
*/
private function collectEntryIds($descriptor, $folder_entryid, $recursive) {
$startTime = microtime(true);
if ($this->openResult) {
error_log('Search aborted: index database unavailable');
return false;
}
$whereFolderids = [];
if (isset($folder_entryid)) {
try {
$folder = mapi_msgstore_openentry($this->store, $folder_entryid);
if (!$folder) {
return false;
}
$tmp_props = mapi_getprops($folder, [PR_FOLDER_ID]);
if (empty($tmp_props[PR_FOLDER_ID])) {
return false;
}
$folder_id = IndexSqlite::get_gc_value((int) $tmp_props[PR_FOLDER_ID]);
$whereFolderids[] = $folder_id;
if ($recursive) {
$this->getWhereFolderids($folder, $whereFolderids);
}
$this->logDebug('Folder scope resolved', [
'root_folder_gc_id' => $folder_id,
'folder_ids' => $whereFolderids,
]);
}
catch (Exception $e) {
error_log(sprintf("Index: error getting folder information %s - %s", $this->username, $e));
$this->logDebug('Failed to resolve folder scope', ['error' => $e->getMessage()]);
return false;
}
}
$ftsAst = $descriptor['ast'] ?? null;
$message_classes = $descriptor['message_classes'] ?? null;
$date_start = $descriptor['date_start'] ?? null;
$date_end = $descriptor['date_end'] ?? null;
$unread = !empty($descriptor['unread']);
$has_attachments = !empty($descriptor['has_attachments']);
$this->logDebug('Search filters resolved', [
'unread' => $unread,
'has_attachments' => $has_attachments,
'date_start' => $date_start,
'date_end' => $date_end,
'message_classes_count' => is_array($message_classes) ? count($message_classes) : null,
]);
$builder = new FtsQueryBuilder(fn ($message, $context = []) => $this->logDebug($message, $context));
$query = $builder->build($descriptor, $whereFolderids);
if ($query === null) {
error_log(sprintf("FTS query compilation returned empty expression: ast => %s", json_encode($ftsAst)));
return false;
}
[$sql, $bindings, $ftsQuery] = $query;
$this->count = 0;
$this->logDebug('Executing SQLite FTS query', [
'sql' => $sql,
'bindings' => array_map(static function ($binding) {
return [
'name' => $binding[0],
'value' => $binding[1],
];
}, $bindings),
]);
// Tighten PHP's execution-time limit for the duration of the
// query + result processing so a single expensive search cannot
// monopolise a PHP-FPM worker for the full max_execution_time.
$prevTimeLimit = (int) ini_get('max_execution_time');
if (MAX_FTS_EXECUTION_TIME > 0) {
set_time_limit(MAX_FTS_EXECUTION_TIME);
}
$deadline = MAX_FTS_EXECUTION_TIME > 0 ? microtime(true) + MAX_FTS_EXECUTION_TIME : 0;
$matchedRows = 0;
$sampleRows = [];
$entryids = [];
try {
$stmt = $this->prepare($sql);
if ($stmt === false) {
error_log(sprintf(
"SQLite query prepare failed: %s (%d)",
$this->lastErrorMsg(),
$this->lastErrorCode()
));
return false;
}
foreach ($bindings as $binding) {
if (!$stmt->bindValue($binding[0], $binding[1], $binding[2])) {
error_log(sprintf(
"SQLite query bind failed for param '%s' with value '%s': %s (%d)",
$binding[0],
$binding[1],
$this->lastErrorMsg(),
$this->lastErrorCode()
));
return false;
}
}
$results = $stmt->execute();
if ($results === false) {
error_log(sprintf(
"SQLite query execution failed: %s (%d)",
$this->lastErrorMsg(),
$this->lastErrorCode()
));
return false;
}
// Collect the entryids that pass the filters; the actual linking
// is deferred until after the loop so it can be batched into a
// single RPC instead of one round trip per matched message.
while (($row = $results->fetchArray(SQLITE3_ASSOC)) && count($entryids) < MAX_FTS_RESULT_ITEMS) {
// Graceful abort when the wall-clock deadline is reached
// so we return partial results instead of letting PHP
// kill the process via max_execution_time.
if ($deadline > 0 && microtime(true) >= $deadline) {
$this->logDebug('Search aborted: execution time limit reached', [
'limit_seconds' => MAX_FTS_EXECUTION_TIME,
'matched_rows' => $matchedRows,
'selected_messages' => count($entryids),
]);
break;
}
++$matchedRows;
$entryid = $this->filter_content(
$row,
$message_classes,
$date_start,
$date_end,
$unread,
$has_attachments
);
if ($entryid === null) {
continue;
}
$entryids[] = $entryid;
if (count($sampleRows) < self::DEBUG_SAMPLE_LIMIT) {
$sampleRows[] = [
'message_id' => $row['message_id'] ?? null,
'entryid' => self::formatBinaryFieldForLog($row['entryid'] ?? null),
'message_class' => $row['message_class'] ?? null,
'date' => $row['date'] ?? null,
'readflag' => $row['readflag'] ?? null,
'attach_indexed' => $row['attach_indexed'] ?? null,
];
}
}
}
finally {
if (isset($results) && $results !== false) {
$results->finalize();
}
if (isset($stmt) && $stmt !== false) {
$stmt->close();
}
// Always restore the original time limit, even after an error.
set_time_limit($prevTimeLimit);
}
$durationMs = (int) round((microtime(true) - $startTime) * 1000);
$this->logDebug('Search completed', [
'fts_query' => $ftsQuery,
'matched_rows' => $matchedRows,
'selected_messages' => count($entryids),
'limit_reached' => count($entryids) >= MAX_FTS_RESULT_ITEMS,
'folder_ids' => $whereFolderids !== [] ? $whereFolderids : null,
'sample_messages' => $sampleRows,
'duration_ms' => $durationMs,
]);
return $entryids;
}
/**
* Returns the restriction to filter hidden folders.
*
* @return array
*/
private function getHiddenRestriction() {
return
[RES_OR, [
[RES_PROPERTY,
[
RELOP => RELOP_EQ,
ULPROPTAG => PR_ATTR_HIDDEN,
VALUE => [PR_ATTR_HIDDEN => false],
],
],
[RES_NOT,
[
[RES_EXIST,
[
ULPROPTAG => PR_ATTR_HIDDEN,
],
],
],
],
]];
}
/**
* Appends the recursive folder ids for the search scope.
*
* @param mixed $folder
* @param array $whereFolderids
*/
private function getWhereFolderids($folder, &$whereFolderids) {
/**
* remove hidden folders, folders with PR_ATTR_HIDDEN property set
* should not be shown to the client.
*/
$restriction = $this->getHiddenRestriction();
$hierarchy = mapi_folder_gethierarchytable($folder, CONVENIENT_DEPTH | MAPI_DEFERRED_ERRORS);
mapi_table_restrict($hierarchy, $restriction, TBL_BATCH);
$rows = mapi_table_queryallrows($hierarchy, [PR_FOLDER_ID]);
foreach ($rows as $row) {
if (isset($row[PR_FOLDER_ID])) {
$whereFolderids[] = IndexSqlite::get_gc_value((int) $row[PR_FOLDER_ID]);
}
}
}
}
@@ -0,0 +1,159 @@
<?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
*/
/**
* JSON Request handler.
*
* This class handles all incoming JSON requests from the client. In short, it receives the JSON,
* decodes JSON data, then sends the requests to the correct modules, and builds the reply JSON. The reply
* JSON is encoded and then returned for reply.
*/
class JSONRequest {
public function __construct() {}
/**
* Execute incoming JSON request.
*
* This function executes the actions in the JSON, which are received from
* the client. The entire JSON request is processed at once here, and this function
* is therefore called only once for each HTTP request to the server.
*
* @param string $json the json string which is received by the client
*
* @return string the built json which will be sent back to the client
*
* @todo Reduce overhead by outputting created JSON by outputting directly to php://output instead of returning a
* (possibly huge) string containing the serialized JSON
*/
public function execute($json) {
/* If json_encode produces an empty string, wa-js shows an absolutely
* worthless "Invalid data received from the server" dialog. */
$jsonflags = JSON_THROW_ON_ERROR | JSON_INVALID_UTF8_SUBSTITUTE;
try {
// decode JSON data
$data = json_decode_data($json, true);
// Reset the bus
$GLOBALS["bus"]->reset();
// notify modules that wants to do something at the start of a request
$GLOBALS["bus"]->notify(REQUEST_ENTRYID, REQUEST_START);
// Check if the JSON is parsed correctly into an array
$data = $data["grommunio"] ?: false;
// @TODO throw exception if grommunio tag is not present
if (is_array($data)) {
// iterate over all module names
foreach ($data as $moduleName => $modules) {
// each module can contain multiple requests using different module ids
foreach ($modules as $moduleId => $moduleData) {
// Create the module via the Dispatcher
$moduleObj = $GLOBALS["dispatcher"]->loadModule($moduleName, $moduleId, $moduleData);
// Check if the module is loaded
if (is_object($moduleObj)) {
if (!$GLOBALS["bus"]->synchronizePersistentState()) {
throw new RuntimeException('Unable to publish notifier state');
}
try {
$moduleObj->loadSessionData();
// Execute the actions in the module
$moduleObj->execute();
$moduleObj->saveSessionData();
}
finally {
$moduleObj->closeSessionData();
}
}
}
}
}
// notify modules that wants to do something at the end of a request
$GLOBALS["bus"]->notify(REQUEST_ENTRYID, REQUEST_END);
// Build the JSON and return it
return json_encode(["grommunio" => $GLOBALS["bus"]->getData()], $jsonflags);
}
catch (GrommunioException $e) {
if (!$e->isHandled) {
$data = [
"error" => [
"type" => ERROR_GROMMUNIO,
"info" => [
"file" => $e->getFileLine(),
"display_message" => $e->getDisplayMessage(),
"original_message" => $e->getMessage(),
],
],
];
return json_encode(["grommunio" => $data], $jsonflags);
}
}
catch (GrommunioErrorException $e) {
if (!$e->isHandled) {
$data = [
"error" => [
"type" => ERROR_GENERAL,
"info" => [
"file" => $e->getFileLine(),
"display_message" => $e->getDisplayMessage(),
"original_message" => $e->getMessage(),
],
],
];
return json_encode(["grommunio" => $data], $jsonflags);
}
}
catch (Exception $e) {
// handle exceptions that are not handled by modules
dump($e);
$data = [
"error" => [
"type" => ERROR_GENERAL,
"info" => [
"file" => basename($e->getFile()) . ':' . $e->getLine(),
"display_message" => _('An unexpected error has occurred'),
"original_message" => $e->getMessage(),
],
],
];
return json_encode(["grommunio" => $data], $jsonflags);
}
catch (Throwable $e) {
// Catch PHP Errors/TypeErrors as JSON to avoid HTTP 500s
dump($e);
$data = [
"error" => [
"type" => ERROR_GENERAL,
"info" => [
"file" => basename($e->getFile()) . ':' . $e->getLine(),
"display_message" => _('An unexpected error has occurred'),
"original_message" => $e->getMessage(),
],
],
];
return json_encode(["grommunio" => $data], $jsonflags);
}
// A handled exception already put its error response on the bus.
return json_encode(["grommunio" => $GLOBALS["bus"]->getData()], $jsonflags);
}
}
@@ -0,0 +1,598 @@
<?php
/*
* SPDX-FileCopyrightText: Copyright 2020 - 2026 grommunio GmbH
* SPDX-License-Identifier: AGPL-3.0-or-later
*/
/**
* Turns the properties of a json theme into the inline styles of the page.
*/
class JsonThemeStyles {
/**
* @param string $theme The name of the json theme
* @param array $themeProps The properties of its theme.json file
*
* @return string The styles (between <style> tags) and the stylesheet links
*/
public static function render($theme, $themeProps) {
$themeProps = self::derivePalette(self::normalizeColors($themeProps));
$themeProps = self::resolveUrls($themeProps, $theme);
$styles = '<style>' . self::getVariables($themeProps);
foreach ($themeProps as $k => $v) {
if ($v && isset(self::$styles[$k])) {
$styles .= str_replace("{{{$k}}}", htmlspecialchars((string) $v), self::$styles[$k]);
}
}
$styles .= '</style>' . "\n";
return $styles . self::stylesheetLinks($themeProps, $theme);
}
/**
* Fills in the colors a theme left out from the ones it set.
*
* @param array $themeProps A hash with the normalized properties of a theme.json file
*
* @return array
*/
private static function derivePalette($themeProps) {
if ($themeProps['primary-color']) {
$themeProps = self::derivePrimaryPalette($themeProps);
}
if ($themeProps['action-color'] && !$themeProps['action-color:hover']) {
$themeProps['action-color:hover'] = Colors::darker($themeProps['action-color'], 10);
}
if (isset($themeProps['selection-color']) && !isset($themeProps['selection-text-color'])) {
// Set a text color for the selection-color
$hsl = Colors::rgb2hsl($themeProps['selection-color']);
if ($hsl['l'] > 50) {
$hsl['l'] = 5;
}
else {
$hsl['l'] = 95;
}
$themeProps['selection-text-color'] = Colors::colorObject2string(Colors::hsl2rgb($hsl));
}
return $themeProps;
}
/**
* @param array $themeProps A hash with the normalized properties of a theme.json file
*
* @return array
*/
private static function derivePrimaryPalette($themeProps) {
if (!$themeProps['primary-color:hover']) {
$hsl = Colors::rgb2hsl($themeProps['primary-color']);
if ($hsl['l'] > 20) {
$themeProps['primary-color:hover'] = Colors::darker($themeProps['primary-color'], 10);
}
else {
$themeProps['primary-color:hover'] = Colors::lighter($themeProps['primary-color'], 20);
}
}
// Check if the main bar is not too light for white text (i.e. the default color)
if (!$themeProps['mainbar-text-color'] && Colors::getLuma($themeProps['primary-color']) > 155) {
$themeProps['mainbar-text-color'] = '#000000';
}
if (!$themeProps['selection-color']) {
$themeProps['selection-color'] = Colors::setLuminance($themeProps['primary-color'], 80);
}
if (!$themeProps['primary-color:dark']) {
$themeProps['primary-color:dark'] = Colors::darker($themeProps['primary-color'], 20);
}
// The top bar is a flat primary-color unless the theme asks for a gradient,
// which is what the key has always promised.
if (!$themeProps['gradient-start']) {
$themeProps['gradient-start'] = $themeProps['primary-color'];
}
if (!$themeProps['gradient-end']) {
$themeProps['gradient-end'] = $themeProps['gradient-start'];
}
return $themeProps;
}
/**
* @param array $themeProps A hash with the properties of a theme.json file
* @param string $theme the name of the theme the urls are part of
*
* @return array
*/
private static function resolveUrls($themeProps, $theme) {
foreach (['background-image', 'logo-large', 'logo-small'] as $key) {
if (isset($themeProps[$key])) {
$themeProps[$key] = self::fixUrl($themeProps[$key], $theme);
}
}
if (isset($themeProps['logo-large']) && !isset($themeProps['logo-small'])) {
$themeProps['logo-small'] = $themeProps['logo-large'];
}
if (isset($themeProps['logo-small:dark'])) {
$themeProps['logo-small:dark'] = self::fixUrl($themeProps['logo-small:dark'], $theme);
}
elseif (isset($themeProps['logo-small'])) {
$themeProps['logo-small:dark'] = $themeProps['logo-small'];
}
if (isset($themeProps['spinner-image'])) {
$themeProps['spinner-image'] = self::fixUrl($themeProps['spinner-image'], $theme);
}
return $themeProps;
}
/**
* @param array $themeProps A hash with the properties of a theme.json file
* @param string $theme the name of the theme the stylesheets are part of
*
* @return string the link tags of the stylesheets the theme defines
*/
private static function stylesheetLinks($themeProps, $theme) {
$stylesheets = $themeProps['stylesheets'] ?? [];
if (is_string($stylesheets)) {
$stylesheets = explode(' ', $stylesheets);
}
elseif (!is_array($stylesheets)) {
return '';
}
$links = '';
foreach ($stylesheets as $stylesheet) {
if (!is_string($stylesheet) || empty(trim($stylesheet))) {
continue;
}
$links .= "\t\t" . '<link rel="stylesheet" type="text/css" href="' . htmlspecialchars((string) self::fixUrl(trim($stylesheet), $theme)) . '" />' . "\n";
}
return $links;
}
/**
* Normalizes all defined colors in a JSON theme to valid hex colors.
*
* @param array $themeProps A hash with the properties defined a theme.json file
*/
private static function normalizeColors($themeProps) {
$colorKeys = [
'primary-color',
'primary-color:hover',
'primary-color:dark',
'gradient-start',
'gradient-end',
'mainbar-text-color',
'action-color',
'action-color:hover',
'selection-color',
'selection-text-color',
'focus-color',
];
foreach ($colorKeys as $ck) {
$themeProps[$ck] = isset($themeProps[$ck]) ? Colors::getHexColorFromCssColor($themeProps[$ck]) : null;
}
return $themeProps;
}
/**
* Utility function to fix relative urls in JSON themes.
*
* @param string $url the url to be fixed
* @param string $theme the name of the theme the url is part of
*/
private static function fixUrl($url, $theme) {
// the url is absolute we don't have to fix anything
if (preg_match('/^https?:\/\//', $url)) {
return $url;
}
return versionedUrl(PATH_PLUGIN_DIR . '/' . $theme . '/' . $url);
}
/**
* The custom properties a theme feeds. grommunio.css is written against these and
* uses them far more widely than the fixed selectors below, so a theme that sets
* none of them only reaches the handful of places those selectors name.
*
* The built-in themes declare the same properties in grommunio.css; a json theme
* gets no rule of its own there, so they are emitted here instead. One theme is
* active per request, which is why plain "body" is specific enough.
*
* @param array $themeProps A hash with the properties defined in a theme.json file
*
* @return string a css rule, or an empty string when the theme sets no colors
*/
private static function getVariables($themeProps) {
$variables = [
'--theme-primary-color' => $themeProps['primary-color'] ?? null,
'--theme-primary-hover' => $themeProps['primary-color:hover'] ?? null,
'--theme-primary-dark' => $themeProps['primary-color:dark'] ?? null,
'--theme-gradient-start' => $themeProps['gradient-start'] ?? null,
'--theme-gradient-end' => $themeProps['gradient-end'] ?? null,
'--theme-selection-bg' => $themeProps['selection-color'] ?? null,
'--theme-spinner-image' => isset($themeProps['spinner-image']) ? 'url(' . $themeProps['spinner-image'] . ')' : null,
];
$declarations = '';
foreach ($variables as $name => $value) {
if ($value) {
$declarations .= "\n\t\t\t\t" . $name . ': ' . htmlspecialchars((string) $value) . ';';
}
}
if (empty($declarations)) {
return '';
}
return "\n\t\t\t/* The palette grommunio.css is written against */\n\t\t\tbody {" . $declarations . "\n\t\t\t}\n";
}
/**
* The templates of the styles that a json theme can add to the page.
*
* @var array<string, string>
*/
private static $styles = [
'primary-color' => '
/* The Sign in button of the login screen */
body.login #form-container #submitbutton,
#loading-mask #form-container #submitbutton {
background: {{primary-color}};
}
/* The top bar of the Welcome dialog */
.grommunio-welcome-body > .x-panel-bwrap > .x-panel-body div.grommunio-welcome-title {
border-left: 1px solid {{primary-color}};
border-right: 1px solid {{primary-color}};
background: {{primary-color}};
}
/* The border line under the top menu bar */
body #grommunio-mainmenu {
border-color: {{primary-color}};
}
/* The background color of the top menu bar */
body #grommunio-mainmenu.grommunio-maintabbar > .x-toolbar-ct {
background-color: {{primary-color}};
}
/* Unread items */
.k-unreadborders .x-grid3-row.x-grid3-row-collapsed.mail_unread > table,
.k-unreadborders .x-grid3-row.x-grid3-row-expanded.mail_unread > table {
border-left: 4px solid {{primary-color}} !important;
}
',
'primary-color:hover' => '
/* Hover state and active state of the Sign in button */
body.login #form-container #submitbutton:hover,
#loading-mask #form-container #submitbutton:hover,
body.login #form-container #submitbutton:active,
#loading-mask #form-container #submitbutton:active {
background: {{primary-color:hover}};
}
/* Background color of the hover state of the buttons in the top menu bar */
body #grommunio-mainmenu.grommunio-maintabbar > .x-toolbar-ct .x-btn.x-btn-over,
/* Background color of the active state of the buttons (i.e. when the buttons get clicked) */
body #grommunio-mainmenu.grommunio-maintabbar > .x-toolbar-ct .x-btn.x-btn-over.x-btn-click,
/* Background color of the selected button */
body #grommunio-mainmenu.grommunio-maintabbar > .x-toolbar-ct .grommunio-maintabbar-maintab-active,
/* Background color of the hover state of selected button */
body #grommunio-mainmenu.grommunio-maintabbar > .x-toolbar-ct .grommunio-maintabbar-maintab-active.x-btn-over,
/* Background color of the active state of selected button */
body #grommunio-mainmenu.grommunio-maintabbar > .x-toolbar-ct .grommunio-maintabbar-maintab-active.x-btn-over.x-btn-click {
background-color: {{primary-color:hover}} !important;
}
',
'mainbar-text-color' => '
body #grommunio-mainmenu.grommunio-maintabbar > .x-toolbar-ct,
/* Text color of the buttons in the top menu bar */
body #grommunio-mainmenu.grommunio-maintabbar > .x-toolbar-ct .x-btn button.x-btn-text,
body #grommunio-mainmenu.grommunio-maintabbar > .x-toolbar-ct .x-btn-over button.x-btn-text,
body #grommunio-mainmenu.grommunio-maintabbar > .x-toolbar-ct .x-btn-over.x-btn-click button.x-btn-text,
/* Text color of the selected button in the top menu bar */
body #grommunio-mainmenu.grommunio-maintabbar > .x-toolbar-ct .grommunio-maintabbar-maintab-active button.x-btn-text,
body #grommunio-mainmenu.grommunio-maintabbar > .x-toolbar-ct .grommunio-maintabbar-maintab-active.x-btn-over button.x-btn-text,
body #grommunio-mainmenu.grommunio-maintabbar > .x-toolbar-ct .grommunio-maintabbar-maintab-active.x-btn-over.x-btn-click button.x-btn-text {
color: {{mainbar-text-color}} !important;
}
',
'action-color' => '
/****************************************************************************
* Action color
* ===============
* Some elements have a different color than the default color of these elements
* to get extra attention, e.g. "call-to-action buttons", the current day
* in the calendar, etc.
****************************************************************************/
/* Buttons, normal state */
.x-btn.grommunio-action .x-btn-small,
.x-btn.grommunio-action .x-btn-medium,
.x-btn.grommunio-action .x-btn-large,
/* Buttons, active state */
.x-btn.grommunio-action.x-btn-over.x-btn-click .x-btn-small,
.x-btn.grommunio-action.x-btn-over.x-btn-click .x-btn-medium,
.x-btn.grommunio-action.x-btn-over.x-btn-click .x-btn-large,
.x-btn.grommunio-action.x-btn-click .x-btn-small,
.x-btn.grommunio-action.x-btn-click .x-btn-medium,
.x-btn.grommunio-action.x-btn-click .x-btn-large,
/* Special case: Popup, Windows, or Messageboxes (first button is by default styled as the action button) */
.x-window .x-panel-footer .x-toolbar-left-row .x-toolbar-cell:not(.x-hide-offsets) .x-btn:not(.grommunio-normal) .x-btn-small,
.x-window .x-panel-footer .x-toolbar-left-row .x-toolbar-cell:not(.x-hide-offsets) .x-btn:not(.grommunio-normal) .x-btn-medium,
.x-window .x-panel-footer .x-toolbar-left-row .x-toolbar-cell:not(.x-hide-offsets) .x-btn:not(.grommunio-normal) .x-btn-large,
.x-window .x-panel-footer .x-toolbar-right-row .x-toolbar-cell:not(.x-hide-offsets) .x-btn:not(.grommunio-normal) .x-btn-small,
.x-window .x-panel-footer .x-toolbar-right-row .x-toolbar-cell:not(.x-hide-offsets) .x-btn:not(.grommunio-normal) .x-btn-medium,
.x-window .x-panel-footer .x-toolbar-right-row .x-toolbar-cell:not(.x-hide-offsets) .x-btn:not(.grommunio-normal) .x-btn-large,
.x-window .x-window-footer .x-toolbar-left-row .x-toolbar-cell:not(.x-hide-offsets) .x-btn:not(.grommunio-normal) .x-btn-small,
.x-window .x-window-footer .x-toolbar-left-row .x-toolbar-cell:not(.x-hide-offsets) .x-btn:not(.grommunio-normal) .x-btn-medium,
.x-window .x-window-footer .x-toolbar-left-row .x-toolbar-cell:not(.x-hide-offsets) .x-btn:not(.grommunio-normal) .x-btn-large,
.x-window .x-window-footer .x-toolbar-right-row .x-toolbar-cell:not(.x-hide-offsets) .x-btn:not(.grommunio-normal) .x-btn-small,
.x-window .x-window-footer .x-toolbar-right-row .x-toolbar-cell:not(.x-hide-offsets) .x-btn:not(.grommunio-normal) .x-btn-medium,
.x-window .x-window-footer .x-toolbar-right-row .x-toolbar-cell:not(.x-hide-offsets) .x-btn:not(.grommunio-normal) .x-btn-large,
.x-window .x-panel-footer .x-toolbar-left-row .x-toolbar-cell:not(.x-hide-offsets) .x-btn.x-btn-click:not(.grommunio-normal) .x-btn-small,
.x-window .x-panel-footer .x-toolbar-left-row .x-toolbar-cell:not(.x-hide-offsets) .x-btn.x-btn-click:not(.grommunio-normal) .x-btn-medium,
.x-window .x-panel-footer .x-toolbar-left-row .x-toolbar-cell:not(.x-hide-offsets) .x-btn.x-btn-click:not(.grommunio-normal) .x-btn-large,
.x-window .x-panel-footer .x-toolbar-right-row .x-toolbar-cell:not(.x-hide-offsets) .x-btn.x-btn-click:not(.grommunio-normal) .x-btn-small,
.x-window .x-panel-footer .x-toolbar-right-row .x-toolbar-cell:not(.x-hide-offsets) .x-btn.x-btn-click:not(.grommunio-normal) .x-btn-medium,
.x-window .x-panel-footer .x-toolbar-right-row .x-toolbar-cell:not(.x-hide-offsets) .x-btn.x-btn-click:not(.grommunio-normal) .x-btn-large,
.x-window .x-window-footer .x-toolbar-left-row .x-toolbar-cell:not(.x-hide-offsets) .x-btn.x-btn-click:not(.grommunio-normal) .x-btn-small,
.x-window .x-window-footer .x-toolbar-left-row .x-toolbar-cell:not(.x-hide-offsets) .x-btn.x-btn-click:not(.grommunio-normal) .x-btn-medium,
.x-window .x-window-footer .x-toolbar-left-row .x-toolbar-cell:not(.x-hide-offsets) .x-btn.x-btn-click:not(.grommunio-normal) .x-btn-large,
.x-window .x-window-footer .x-toolbar-right-row .x-toolbar-cell:not(.x-hide-offsets) .x-btn.x-btn-click:not(.grommunio-normal) .x-btn-small,
.x-window .x-window-footer .x-toolbar-right-row .x-toolbar-cell:not(.x-hide-offsets) .x-btn.x-btn-click:not(.grommunio-normal) .x-btn-medium,
.x-window .x-window-footer .x-toolbar-right-row .x-toolbar-cell:not(.x-hide-offsets) .x-btn.x-btn-click:not(.grommunio-normal) .x-btn-large,
.x-window .x-panel-footer .x-toolbar-left-row .x-toolbar-cell:not(.x-hide-offsets) .x-btn.x-btn-over.x-btn-click:not(.grommunio-normal) .x-btn-small,
.x-window .x-panel-footer .x-toolbar-left-row .x-toolbar-cell:not(.x-hide-offsets) .x-btn.x-btn-over.x-btn-click:not(.grommunio-normal) .x-btn-medium,
.x-window .x-panel-footer .x-toolbar-left-row .x-toolbar-cell:not(.x-hide-offsets) .x-btn.x-btn-over.x-btn-click:not(.grommunio-normal) .x-btn-large,
.x-window .x-panel-footer .x-toolbar-right-row .x-toolbar-cell:not(.x-hide-offsets) .x-btn.x-btn-over.x-btn-click:not(.grommunio-normal) .x-btn-small,
.x-window .x-panel-footer .x-toolbar-right-row .x-toolbar-cell:not(.x-hide-offsets) .x-btn.x-btn-over.x-btn-click:not(.grommunio-normal) .x-btn-medium,
.x-window .x-panel-footer .x-toolbar-right-row .x-toolbar-cell:not(.x-hide-offsets) .x-btn.x-btn-over.x-btn-click:not(.grommunio-normal) .x-btn-large,
.x-window .x-window-footer .x-toolbar-left-row .x-toolbar-cell:not(.x-hide-offsets) .x-btn.x-btn-over.x-btn-click:not(.grommunio-normal) .x-btn-small,
.x-window .x-window-footer .x-toolbar-left-row .x-toolbar-cell:not(.x-hide-offsets) .x-btn.x-btn-over.x-btn-click:not(.grommunio-normal) .x-btn-medium,
.x-window .x-window-footer .x-toolbar-left-row .x-toolbar-cell:not(.x-hide-offsets) .x-btn.x-btn-over.x-btn-click:not(.grommunio-normal) .x-btn-large,
.x-window .x-window-footer .x-toolbar-right-row .x-toolbar-cell:not(.x-hide-offsets) .x-btn.x-btn-over.x-btn-click:not(.grommunio-normal) .x-btn-small,
.x-window .x-window-footer .x-toolbar-right-row .x-toolbar-cell:not(.x-hide-offsets) .x-btn.x-btn-over.x-btn-click:not(.grommunio-normal) .x-btn-medium,
.x-window .x-window-footer .x-toolbar-right-row .x-toolbar-cell:not(.x-hide-offsets) .x-btn.x-btn-over.x-btn-click:not(.grommunio-normal) .x-btn-large,
/* action button in reminder popout */
.k-reminderpanel .x-panel-footer .x-toolbar-right-row .x-toolbar-cell:not(.x-hide-offsets) .x-btn:not(.grommunio-normal) .x-btn-small,
.k-reminderpanel .x-panel-footer .x-toolbar-right-row .x-toolbar-cell:not(.x-hide-offsets) .x-btn.x-btn-click:not(.grommunio-normal) .x-btn-small,
.k-reminderpanel .x-panel-footer .x-toolbar-right-row .x-toolbar-cell:not(.x-hide-offsets) .x-btn.x-btn-over.x-btn-click:not(.grommunio-normal) .x-btn-small,
/* Current day in the calendar */
.grommunio-freebusy-panel .x-freebusy-timeline-container .x-freebusy-header .x-freebusy-header-body .x-freebusy-timeline-day.x-freebusy-timeline-day-current,
.grommunio-freebusy-panel .x-freebusy-timeline-container .x-freebusy-header .x-freebusy-header-body .x-freebusy-timeline-day.x-freebusy-timeline-day-current table,
.grommunio-freebusy-panel .x-freebusy-timeline-container .x-freebusy-header .x-freebusy-header-body .x-freebusy-timeline-day.x-freebusy-timeline-day-current table tr.x-freebusy-timeline-day td,
/* The date pickers */
.x-date-picker .x-date-inner td.x-date-today a,
.x-date-picker .x-date-mp table td.x-date-mp-sel a,
.x-date-picker .x-date-mp table tr.x-date-mp-btns td button.x-date-mp-ok {
background: {{action-color}} !important;
}
/* Focused Action button */
.x-btn.grommunio-action.x-btn-focus .x-btn-small, .x-btn.grommunio-action.x-btn-focus .x-btn-medium, .x-btn.grommunio-action.x-btn-focus .x-btn-large {
background: {{action-color}} !important;
}
/* Selected calendar */
.grommunio-calendar-tabarea-stroke.grommunio-calendar-tab-selected {
border-top-color: {{action-color}};
}
.x-date-picker .x-date-inner td.x-date-weeknumber a,
.grommunio-hierarchy-node-total-count span.grommunio-hierarchy-node-counter,
.grommunio-hierarchy-node-unread-count span.grommunio-hierarchy-node-counter {
color: {{action-color}};
}
.x-date-picker .x-date-inner td.x-date-today a {
border-color: {{action-color}};
}
.grommunio-freebusy-panel .x-freebusy-timeline-container .x-freebusy-header .x-freebusy-header-body .x-freebusy-timeline-day.x-freebusy-timeline-day-current,
.grommunio-freebusy-panel .x-freebusy-timeline-container .x-freebusy-body .x-freebusy-background .x-freebusy-timeline-day.x-freebusy-timeline-day-current {
border-right-color: {{action-color}};
}
.grommunio-freebusy-panel .x-freebusy-timeline-container .x-freebusy-header .x-freebusy-header-body .x-freebusy-timeline-day.x-freebusy-timeline-day-current table tr.x-freebusy-timeline-hour td:first-child,
.grommunio-freebusy-panel .x-freebusy-timeline-container .x-freebusy-body .x-freebusy-background .x-freebusy-timeline-day.x-freebusy-timeline-day-current td:first-child {
border-left-color: {{action-color}};
}
',
'action-color:hover' => '
/* Buttons, hover state */
.x-btn.grommunio-action.x-btn-over .x-btn-small,
.x-btn.grommunio-action.x-btn-over .x-btn-medium,
.x-btn.grommunio-action.x-btn-over .x-btn-large,
/* Special case: Popup, Windows, or Messageboxes */
.x-window .x-panel-footer .x-toolbar-left-row .x-toolbar-cell:not(.x-hide-offsets) .x-btn.x-btn-over:not(.grommunio-normal) .x-btn-small,
.x-window .x-panel-footer .x-toolbar-left-row .x-toolbar-cell:not(.x-hide-offsets) .x-btn.x-btn-over:not(.grommunio-normal) .x-btn-medium,
.x-window .x-panel-footer .x-toolbar-left-row .x-toolbar-cell:not(.x-hide-offsets) .x-btn.x-btn-over:not(.grommunio-normal) .x-btn-large,
.x-window .x-panel-footer .x-toolbar-right-row .x-toolbar-cell:not(.x-hide-offsets) .x-btn.x-btn-over:not(.grommunio-normal) .x-btn-small,
.x-window .x-panel-footer .x-toolbar-right-row .x-toolbar-cell:not(.x-hide-offsets) .x-btn.x-btn-over:not(.grommunio-normal) .x-btn-medium,
.x-window .x-panel-footer .x-toolbar-right-row .x-toolbar-cell:not(.x-hide-offsets) .x-btn.x-btn-over:not(.grommunio-normal) .x-btn-large,
.x-window .x-window-footer .x-toolbar-left-row .x-toolbar-cell:not(.x-hide-offsets) .x-btn.x-btn-over:not(.grommunio-normal) .x-btn-small,
.x-window .x-window-footer .x-toolbar-left-row .x-toolbar-cell:not(.x-hide-offsets) .x-btn.x-btn-over:not(.grommunio-normal) .x-btn-medium,
.x-window .x-window-footer .x-toolbar-left-row .x-toolbar-cell:not(.x-hide-offsets) .x-btn.x-btn-over:not(.grommunio-normal) .x-btn-large,
.x-window .x-window-footer .x-toolbar-right-row .x-toolbar-cell:not(.x-hide-offsets) .x-btn.x-btn-over:not(.grommunio-normal) .x-btn-small,
.x-window .x-window-footer .x-toolbar-right-row .x-toolbar-cell:not(.x-hide-offsets) .x-btn.x-btn-over:not(.grommunio-normal) .x-btn-medium,
.x-window .x-window-footer .x-toolbar-right-row .x-toolbar-cell:not(.x-hide-offsets) .x-btn.x-btn-over:not(.grommunio-normal) .x-btn-large,
/* action button in reminder popout */
.k-reminderpanel .x-panel-footer .x-toolbar-right-row .x-toolbar-cell:not(.x-hide-offsets) .x-btn.x-btn-over:not(.grommunio-normal) .x-btn-small,
/* The date pickers */
.x-date-picker .x-date-mp table tr.x-date-mp-btns td button.x-date-mp-ok:hover {
background: {{action-color:hover}} !important;
}
',
'selection-color' => '
/*********************************************************************
* Selected items in grids and trees
* =================================
* The background color of the selected items in grids and trees can
* be changed to better suit the theme.
*********************************************************************/
/* selected item in grids */
.x-grid3-row.x-grid3-row-selected,
.x-grid3 .x-grid3-row-selected .grommunio-grid-button-container,
/* selected item in tree hierarchies */
.x-tree-node .grommunio-hierarchy-node.x-tree-selected,
/* selected items in boxfields (e.g. the recipient fields) */
.x-grommunio-boxfield ul .x-grommunio-boxfield-item-focus,
.x-grommunio-boxfield ul .x-grommunio-boxfield-recipient-item.x-grommunio-boxfield-item-focus,
/* selected items in card view of Contacts context */
div.grommunio-contact-cardview-selected,
/* selected items in icon view of Notes context */
.grommunio-note-iconview-selected,
/* selected category in the Settings context */
#grommunio-mainpanel-contentpanel-settings .grommunio-settings-category-panel .grommunio-settings-category-tab-active,
/* selected date in date pickers */
.x-date-picker .x-date-inner td.x-date-selected:not(.x-date-today) a,
.x-date-picker .x-date-inner td.x-date-selected:not(.x-date-today) a:hover {
background-color: {{selection-color}} !important;
border-color: {{selection-color}};
}
/* Selected x-menu */
.x-menu-item-selected {
background-color: {{selection-color}};
}
/*********************************************************************
* Extra information about items
* =================================
* Sometimes extra information is shown in opened items. (e.g. "You replied
* to this message etc"). This can be styled with the following rules.
*********************************************************************/
.preview-header-extrainfobox,
.preview-header-extrainfobox-item,
.k-appointmentcreatetab .grommunio-calendar-appointment-extrainfo div,
.k-taskgeneraltab .grommunio-calendar-appointment-extrainfo div,
.grommunio-mailcreatepanel > .x-panel-bwrap > .x-panel-body .grommunio-mailcreatepanel-extrainfo div {
background: {{selection-color}} !important;
}
/* Selected mail item */
.k-unreadborders .x-grid3-row.x-grid3-row-expanded.mail_read.x-grid3-row-selected > table {
border-left: 4px solid {{selection-color}} !important;
}
/* Hover selected item */
.k-unreadborders .x-grid3-row.x-grid3-row-expanded.mail_read.x-grid3-row-selected.x-grid3-row-over > table,
.k-unreadborders .x-grid3-row.x-grid3-row-collapsed.mail_read.x-grid3-row-selected > table {
border-left: 4px solid {{selection-color}} !important;
}
',
'selection-text-color' => '
/*********************************************************************
* Extra information about items
* =================================
* Sometimes extra information is shown in opened items. (e.g. "You replied
* to this message etc"). This can be styled with the following rules.
*********************************************************************/
.preview-header-extrainfobox,
.preview-header-extrainfobox-item,
.k-appointmentcreatetab .grommunio-calendar-appointment-extrainfo div,
.k-taskgeneraltab .grommunio-calendar-appointment-extrainfo div,
.grommunio-mailcreatepanel > .x-panel-bwrap > .x-panel-body .grommunio-mailcreatepanel-extrainfo div {
color: {{selection-text-color}};
}
',
'focus-color' => '
/*********************************************************************
* Focused items
* =================================
*********************************************************************/
/* Normal button */
.x-window .x-window-footer .x-toolbar-left-row .x-toolbar-cell:not(.x-hide-offsets) ~ .x-toolbar-cell:not(.x-hide-offsets) .x-btn.x-btn-focus:not(.grommunio-action):not(.x-btn-over):not(.x-btn-click) .x-btn-small,
.x-window .x-panel-footer .x-toolbar-right-row .x-toolbar-cell:not(.x-hide-offsets) ~ .x-toolbar-cell:not(.x-hide-offsets) .x-btn.x-btn-focus:not(.grommunio-action):not(.x-btn-over):not(.x-btn-click) .x-btn-small,
.x-btn.x-btn-focus:not(.grommunio-action):not(.x-btn-click) .x-btn-small,
.x-btn.x-btn-focus:not(.grommunio-action):not(.x-btn-click) .x-btn-medium,
.x-btn.x-btn-focus:not(.grommunio-action):not(.x-btn-click) .x-btn-large,
.x-toolbar .x-btn.x-btn-focus:not(.grommunio-action):not(.x-btn-noicon) .x-btn-small {
border: 1px solid {{focus-color}} !important;
}
/* Login */
body.login #form-container input:focus,
#loading-mask #form-container input:focus {
border-color: {{focus-color}};
}
input:focus {
border-color: {{focus-color}};
}
/* Form elements */
.x-form-text.x-form-focus:not(.x-trigger-noedit) {
border-color: {{focus-color}} !important;
}
.x-form-field-wrap.x-trigger-wrap-focus:not(.x-freebusy-userlist-container) {
border-color: {{focus-color}};
}
input.x-form-text.x-form-field.x-form-focus {
border-color: {{focus-color}} !important;
}
.x-form-field-wrap.x-trigger-wrap-focus:not(.x-freebusy-userlist-container) input.x-form-text.x-form-field.x-form-focus {
border-color: {{focus-color}} !important;
}
',
'logo-large' => '
/* The logo in the Login screen. Maximum size of the logo image is 220x60px. */
body.login #form-container #logo,
#loading-mask #form-container #logo {
background: url({{logo-large}}) no-repeat right center;
background-size: contain;
}
',
'logo-small' => '
/****************************************************************************
* The logo (shown on the right below the top bar)
* ===============================================
* The maximum height of the image that can be shown is 45px.
****************************************************************************/
.grommunio-maintoolbar {
background-image: url({{logo-small}});
background-size: auto 38px;
}
',
/* Dark mode gives the stock logo a light variant; a branded deployment has its
own. The selector matches the one in darkmode.css and this block comes after
it, so it wins without !important. */
'logo-small:dark' => '
body.dark-mode .grommunio-maintoolbar {
background-image: url({{logo-small:dark}});
background-size: auto 38px;
}
',
'background-image' => '
/*********************************************************************************************
* The Login screen and the Welcome screen
* =======================================
********************************************************************************************/
/* Background image of the login screen */
body.login,
#loading-mask,
#bg,
/* Background image of the Welcome screen */
body.grommunio-welcome {
background: url({{background-image}}) no-repeat center center;
background-size: cover;
}
',
'spinner-image' => '
/* The spinner of the login/loading screen. The one inside the application
is drawn from --theme-spinner-image, which getVariables() sets. */
body.login #form-container.loading .right,
#loading-mask #form-container.loading .right {
background: url({{spinner-image}}) no-repeat center center;
}
',
];
}
@@ -0,0 +1,478 @@
<?php
/*
* SPDX-FileCopyrightText: Copyright 2020 - 2026 grommunio GmbH
* SPDX-License-Identifier: AGPL-3.0-or-later
*/
/**
* JunkRule.
*
* Builds and parses the Outlook Junk Email Rule: the IPM.ExtendedRule.Message
* FAI message in the inbox whose PR_EXTENDED_RULE_MSG_CONDITION carries the
* blocked senders, safe senders and safe recipients lists in the restriction
* format of MS-OXORULE, exactly as Outlook reads and writes them (MS-OXCSPAM).
* All integers little-endian. Strings inside the blobs UTF-16LE, including
* trailing U+0000 codepoint.
* Array counts are 32-bit (extended rule flavour of MS-OXCDATA v20 §2.12).
*/
class JunkRule {
public const PROVIDER = 'JunkEmailRule';
public const RULE_NAME = 'Junk E-mail rule';
// ST_ENABLED | ST_EXIT_LEVEL | ST_SKIP_IF_SCL_IS_SAFE (MS-OXCSPAM v12 §3.1.4.1)
public const RULE_STATE = 0x31;
private const RES_AND = 0x00;
private const RES_OR = 0x01;
private const RES_NOT = 0x02;
private const RES_CONTENT = 0x03;
private const RES_PROPERTY = 0x04;
private const RES_EXIST = 0x08;
private const RES_SUB = 0x09;
private const RES_COMMENT = 0x0A;
private const TAG_SENDER = 0x0C1F001F; // PidTagSenderEmailAddress
private const TAG_RECIPIENT = 0x3003001F; // PidTagEmailAddress
private const TAG_SCL = 0x40760003; // PidTagContentFilterSpamConfidenceLevel
private const SUBOBJ_RECIPIENTS = 0x0E12000D;
private const FL_FULLSTRING_IGNORECASE = 0x00010000;
private const FL_SUBSTRING_IGNORECASE = 0x00010001;
private const MOVESTAMP_NAME = "http://schemas.microsoft.com/exchange/junkemailmovestamp";
private const PS_PUBLIC_STRINGS = "\x29\x03\x02\x00\x00\x00\x00\x00\xC0\x00\x00\x00\x00\x00\x00\x46";
/**
* Serialize the junk rule condition (MS-OXCSPAM v12 §2.2.4 template).
*
* Every list entry starting with '@' is a domain (substring clause). Any
* other entry is an address (fullstring clause). $contacts carries the trusted
* contact addresses Outlook maintains. Pass through what parse() returned.
*
* @param array $blockedSenders addresses and @domains
* @param array $safeSenders addresses and @domains
* @param array $safeRecipients addresses and @domains
* @param array $contacts trusted contact addresses (preserved verbatim)
*
* @return string the PR_EXTENDED_RULE_MSG_CONDITION blob
*/
public static function buildCondition($blockedSenders, $safeSenders, $safeRecipients, $contacts = []) {
[$blockedAddr, $blockedDom] = self::splitList($blockedSenders);
[$safeAddr, $safeDom] = self::splitList($safeSenders);
[$recipAddr, $recipDom] = self::splitList($safeRecipients);
$sclClause = self::resAnd([
self::resExist(self::TAG_SCL),
self::resProperty(0x02 /* RELOP_GT */, self::TAG_SCL, pack('V', 0xFFFFFFFF)),
]);
$tree = self::resAnd([
self::resOr([
self::contentList($blockedAddr, self::TAG_SENDER, self::FL_FULLSTRING_IGNORECASE),
self::resAnd([
self::resOr([
$sclClause,
self::contentList($blockedDom, self::TAG_SENDER, self::FL_SUBSTRING_IGNORECASE),
]),
self::resNot(self::resOr([
self::contentList($safeDom, self::TAG_SENDER, self::FL_SUBSTRING_IGNORECASE),
self::resSub(self::contentList($recipDom, self::TAG_RECIPIENT, self::FL_SUBSTRING_IGNORECASE)),
])),
]),
]),
self::resNot(self::resOr([
self::contentList($safeAddr, self::TAG_SENDER, self::FL_FULLSTRING_IGNORECASE),
self::resSub(self::contentList($recipAddr, self::TAG_RECIPIENT, self::FL_FULLSTRING_IGNORECASE)),
self::contentList($contacts, self::TAG_SENDER, self::FL_SUBSTRING_IGNORECASE),
])),
]);
// No named properties in the condition.
return pack('v', 0) . $tree;
}
/**
* Serialize the junk rule actions, i.e. OP_MOVE to the junk folder plus OP_TAG
* with PidNameExchangeJunkEmailMoveStamp (MS-OXORULE v23 §2.2.4.1.9).
*
* @param string $junkFolderEntryId the 46-byte junk folder entryid
* @param int $moveStamp the stamp from PR_ADDITIONAL_REN_ENTRYIDS[5]
*
* @return string the PR_EXTENDED_RULE_MSG_ACTIONS blob
*/
public static function buildActions($junkFolderEntryId, $moveStamp) {
$name = iconv('UTF-8', 'UTF-16LE', self::MOVESTAMP_NAME) . "\x00\x00";
$propName = "\x01" . self::PS_PUBLIC_STRINGS . chr(strlen($name)) . $name;
$namedProps = pack('v', 1) . pack('v', 0x8001) . pack('V', strlen($propName)) . $propName;
$moveData = pack('V', 1) . "\x01" .
pack('V', strlen($junkFolderEntryId)) . $junkFolderEntryId;
$tagData = pack('V', (0x8001 << 16) | 0x0003) . pack('V', $moveStamp);
$blocks = '';
foreach ([[0x01, $moveData], [0x09, $tagData]] as [$type, $data]) {
$body = chr($type) . pack('V', 0) . pack('V', 0) . $data;
$blocks .= pack('V', strlen($body)) . $body;
}
return $namedProps . pack('V', 1) . pack('V', 2) . $blocks;
}
/**
* Parse a condition blob back into the lists. Walks the restriction tree
* leniently, classifying every string comparison by property, fuzzy level
* and polarity, so rules Outlook rewrote in a different shape still parse.
*
* @param string $blob the PR_EXTENDED_RULE_MSG_CONDITION value
*
* @return array|false lists or false when the blob cannot be parsed
*/
public static function parseCondition($blob) {
$pos = 0;
if (!self::skipNamedProps($blob, $pos)) {
return false;
}
$tree = self::pullRestriction($blob, $pos, 0);
if ($tree === false) {
return false;
}
$lists = [
'blocked_senders' => [],
'safe_senders' => [],
'safe_recipients' => [],
'contacts' => [],
];
self::collect($tree, false, false, $lists);
foreach ($lists as &$l) {
$l = array_values(array_unique($l));
}
return $lists;
}
/**
* @param array $entries
*
* @return array [addresses, domains] split on the leading '@'
*/
private static function splitList($entries) {
$addr = [];
$dom = [];
foreach ($entries as $e) {
$e = trim((string) $e);
if ($e === '') {
continue;
}
if ($e[0] === '@') {
$dom[] = $e;
}
else {
$addr[] = $e;
}
}
return [$addr, $dom];
}
private static function utf16($str) {
return iconv('UTF-8', 'UTF-16LE', $str) . "\x00\x00";
}
private static function resAnd($subs) {
return chr(self::RES_AND) . pack('V', count($subs)) . implode('', $subs);
}
private static function resOr($subs) {
return chr(self::RES_OR) . pack('V', count($subs)) . implode('', $subs);
}
private static function resNot($sub) {
return chr(self::RES_NOT) . $sub;
}
private static function resSub($sub) {
return chr(self::RES_SUB) . pack('V', self::SUBOBJ_RECIPIENTS) . $sub;
}
private static function resExist($tag) {
return chr(self::RES_EXIST) . pack('V', $tag);
}
private static function resProperty($relop, $tag, $packedValue) {
return chr(self::RES_PROPERTY) . chr($relop) . pack('V', $tag) . pack('V', $tag) . $packedValue;
}
private static function resContent($fuzzy, $tag, $str) {
return chr(self::RES_CONTENT) . pack('V', $fuzzy) . pack('V', $tag) . pack('V', $tag) . self::utf16($str);
}
/**
* @param mixed $entries
* @param mixed $tag
* @param mixed $fuzzy
*
* @return string a RES_OR of one RES_CONTENT per entry (zero-count when empty)
*/
private static function contentList($entries, $tag, $fuzzy) {
$subs = [];
foreach ($entries as $e) {
$subs[] = self::resContent($fuzzy, $tag, $e);
}
return self::resOr($subs);
}
private static function skipNamedProps($blob, &$pos) {
if (strlen($blob) < $pos + 2) {
return false;
}
$count = unpack('v', substr($blob, $pos, 2))[1];
$pos += 2;
if ($count === 0) {
return true;
}
$pos += 2 * $count;
if (strlen($blob) < $pos + 4) {
return false;
}
$size = unpack('V', substr($blob, $pos, 4))[1];
$pos += 4 + $size;
return $pos <= strlen($blob);
}
/**
* Pull one restriction. Returns a node array or false.
* Nodes: ['t' => type, 'subs' => [], 'tag' => int, 'fuzzy' => int, 'val' => string].
* A depth bound keeps a hostile deeply-nested blob from exhausting memory.
*
* @param mixed $blob
* @param mixed $pos
* @param mixed $depth
*/
private static function pullRestriction($blob, &$pos, $depth = 0) {
if ($pos >= strlen($blob) || $depth > 64) {
return false;
}
$type = ord($blob[$pos++]);
switch ($type) {
case self::RES_AND:
case self::RES_OR:
$count = self::pullUint32($blob, $pos);
if ($count === false || $count > 0x10000) {
return false;
}
$subs = [];
for ($i = 0; $i < $count; ++$i) {
$sub = self::pullRestriction($blob, $pos, $depth + 1);
if ($sub === false) {
return false;
}
$subs[] = $sub;
}
return ['t' => $type, 'subs' => $subs];
case self::RES_NOT:
$sub = self::pullRestriction($blob, $pos, $depth + 1);
return $sub === false ? false : ['t' => $type, 'subs' => [$sub]];
case self::RES_CONTENT:
$fuzzy = self::pullUint32($blob, $pos);
$tag = self::pullUint32($blob, $pos);
$vtag = self::pullUint32($blob, $pos);
if ($vtag === false) {
return false;
}
$val = self::pullValue($blob, $pos, $vtag & 0xFFFF);
if ($val === false) {
return false;
}
return ['t' => $type, 'fuzzy' => $fuzzy, 'tag' => $tag, 'val' => $val];
case self::RES_PROPERTY:
++$pos; // relop
$tag = self::pullUint32($blob, $pos);
$vtag = self::pullUint32($blob, $pos);
if ($vtag === false || self::pullValue($blob, $pos, $vtag & 0xFFFF) === false) {
return false;
}
return ['t' => $type, 'tag' => $tag];
case self::RES_EXIST:
$tag = self::pullUint32($blob, $pos);
return $tag === false ? false : ['t' => $type, 'tag' => $tag];
case self::RES_SUB:
$subobj = self::pullUint32($blob, $pos);
$sub = self::pullRestriction($blob, $pos, $depth + 1);
return $sub === false ? false : ['t' => $type, 'tag' => $subobj, 'subs' => [$sub]];
case self::RES_COMMENT:
$count = ord($blob[$pos++] ?? "\x00");
for ($i = 0; $i < $count; ++$i) {
$vtag = self::pullUint32($blob, $pos);
if ($vtag === false || self::pullValue($blob, $pos, $vtag & 0xFFFF) === false) {
return false;
}
}
$present = ord($blob[$pos++] ?? "\x00");
if ($present) {
$sub = self::pullRestriction($blob, $pos, $depth + 1);
if ($sub === false) {
return false;
}
return $sub;
}
return ['t' => self::RES_AND, 'subs' => []];
default:
return false;
}
}
private static function pullUint32($blob, &$pos) {
if (strlen($blob) < $pos + 4) {
return false;
}
$v = unpack('V', substr($blob, $pos, 4))[1];
$pos += 4;
return $v;
}
/**
* Pull a property value of the given PT type. Strings decode to UTF-8.
*
* @param mixed $blob
* @param mixed $pos
* @param mixed $type
*/
private static function pullValue($blob, &$pos, $type) {
switch ($type) {
case 0x001F: // PT_UNICODE
$end = $pos;
$len = strlen($blob);
while ($end + 1 < $len && ($blob[$end] !== "\x00" || $blob[$end + 1] !== "\x00")) {
$end += 2;
}
if ($end + 1 >= $len) {
return false;
}
$val = iconv('UTF-16LE', 'UTF-8', substr($blob, $pos, $end - $pos));
$pos = $end + 2;
return $val;
case 0x001E: // PT_STRING8
$end = strpos($blob, "\x00", $pos);
if ($end === false) {
return false;
}
$val = substr($blob, $pos, $end - $pos);
$pos = $end + 1;
return $val;
case 0x0003: // PT_LONG
case 0x000A: // PT_ERROR
$v = self::pullUint32($blob, $pos);
return $v === false ? false : (string) $v;
case 0x000B: // PT_BOOLEAN
if ($pos >= strlen($blob)) {
return false;
}
return (string) ord($blob[$pos++]);
case 0x0002: // PT_SHORT
if (strlen($blob) < $pos + 2) {
return false;
}
$v = unpack('v', substr($blob, $pos, 2))[1];
$pos += 2;
return (string) $v;
case 0x0102: // PT_BINARY
$len = self::pullUint32($blob, $pos);
if ($len === false || strlen($blob) < $pos + $len) {
return false;
}
$val = substr($blob, $pos, $len);
$pos += $len;
return $val;
default:
return false;
}
}
/**
* Classify every string comparison in the tree into the four lists.
* $negated: inside an odd number of RES_NOT.
* $inRecipients: inside a RES_SUB on the recipients table.
*
* @param mixed $node
* @param mixed $negated
* @param mixed $inRecipients
* @param mixed $lists
*/
private static function collect($node, $negated, $inRecipients, &$lists) {
switch ($node['t']) {
case self::RES_AND:
case self::RES_OR:
foreach ($node['subs'] as $sub) {
self::collect($sub, $negated, $inRecipients, $lists);
}
break;
case self::RES_NOT:
self::collect($node['subs'][0], !$negated, $inRecipients, $lists);
break;
case self::RES_SUB:
self::collect($node['subs'][0], $negated, true, $lists);
break;
case self::RES_CONTENT:
$val = $node['val'];
if (!is_string($val) || $val === '') {
break;
}
$substring = (($node['fuzzy'] ?? 0) & 0x0001) === 0x0001;
if ($inRecipients) {
if (!$negated) {
break;
}
$lists['safe_recipients'][] = $val;
}
elseif (!$negated) {
$lists['blocked_senders'][] = $val;
}
elseif ($substring && $val[0] !== '@') {
// Outlook's trusted-contacts clause contains full addresses matched
// as substrings. It is preserved, and never shown as safe senders.
$lists['contacts'][] = $val;
}
else {
$lists['safe_senders'][] = $val;
}
break;
}
}
}
@@ -0,0 +1,75 @@
<?php
/*
* SPDX-FileCopyrightText: Copyright 2020 - 2026 grommunio GmbH
* SPDX-License-Identifier: AGPL-3.0-or-later
*/
/**
* Entry rules of the junk sender lists and the merge of the old webapp
* safe_senders_list setting into them.
*/
class JunkSenderList {
public const MAX_ENTRY_LENGTH = 256;
/**
* @param string $entry
*
* @return bool True when the entry can live in a sender list
*/
public static function isSaneEntry($entry) {
return strlen($entry) <= self::MAX_ENTRY_LENGTH && !preg_match('/[;,\s\x00-\x1F]/', $entry);
}
/**
* @param mixed $old value of the old safe_senders_list setting
*
* @return array usable entries, bare domains prefixed with '@'
*/
public static function legacyEntries($old) {
if (!is_array($old)) {
return [];
}
$out = [];
foreach ($old as $entry) {
$entry = trim((string) $entry);
if ($entry === '' || !self::isSaneEntry($entry)) {
continue;
}
$out[] = str_contains($entry, '@') ? $entry : '@' . $entry;
}
return $out;
}
/**
* Appends the legacy entries missing from $lists['safe_senders'] and sets
* $lists['migrated_pending'] when there were any.
*
* @param mixed $old value of the old safe_senders_list setting
* @param array $lists sender lists as returned by JunkMailModule::getSenderLists
*/
public static function mergeLegacy($old, array &$lists) {
$known = array_map('strtolower', $lists['safe_senders']);
foreach (self::legacyEntries($old) as $entry) {
if (!in_array(strtolower($entry), $known, true)) {
$lists['safe_senders'][] = $entry;
$known[] = strtolower($entry);
$lists['migrated_pending'] = true;
}
}
}
/**
* @param mixed $old value of the old safe_senders_list setting
* @param array $safeSenders safe senders list
*
* @return bool True when every legacy entry is in $safeSenders
*/
public static function legacyCoveredBy($old, array $safeSenders) {
$known = array_map('strtolower', $safeSenders);
$legacy = array_map('strtolower', self::legacyEntries($old));
return !array_diff($legacy, $known);
}
}
@@ -0,0 +1,745 @@
<?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
*/
/**
* Broken-down representation of an XPG locale identifier
* (language[_territory][.codeset][@modifier]), after gromox lib/string.cpp.
*/
class XpgLocale {
public string $language = "";
public string $territory = "";
public string $codeset = "";
public string $modifier = "";
public function __construct(string $locale) {
$pos = strpos($locale, '@');
if ($pos !== false) {
$this->modifier = substr($locale, $pos + 1);
$locale = substr($locale, 0, $pos);
}
$pos = strpos($locale, '.');
if ($pos !== false) {
$this->codeset = substr($locale, $pos + 1);
$locale = substr($locale, 0, $pos);
}
$pos = strpos($locale, '_');
if ($pos !== false) {
$this->territory = substr($locale, $pos + 1);
$locale = substr($locale, 0, $pos);
}
$this->language = $locale;
}
public function __toString(): string {
return $this->toString('_');
}
/**
* @param string $tsep separator between language and territory
*/
public function toString($tsep): string {
$o = $this->language;
if ($o === '') {
return $o;
}
if ($this->territory !== '') {
$o .= $tsep . $this->territory;
}
if ($this->codeset !== '') {
$o .= '.' . $this->codeset;
}
if ($this->modifier !== '') {
$o .= '@' . $this->modifier;
}
return $o;
}
}
/**
* Language handling class.
*/
class Language {
// Key and size of the shared memory segment the parsed translations live in.
private const CACHE_KEY = 0x950412DE;
private const CACHE_SIZE = 32 * 1024 * 1024;
private $languages = ["en_US" => "English"];
private $lang;
private $loaded = false;
private $translations;
/**
* Default constructor.
*
* By default, the Language class only knows about en_GB (English). If you want more languages, you
* must call loadLanguages().
*/
public function __construct() {}
/**
* Loads languages from disk.
*
* loadLanguages() reads the languages from disk by reading LANGUAGE_DIR and opening all directories
* in that directory. Each directory must contain a 'language.txt' file containing:
*
* <language display name>
* <win32 language name>
*
* For example:
* <code>
* Nederlands
* nld_NLD
* </code>
*
* Also, the directory names must be XPG locale identifiers without a
* codeset that are available to the server's locale system, for example nl_NL.
*/
public function loadLanguages() {
if ($this->loaded) {
return;
}
// Older configurations still list the languages with a codeset
$languages = [];
foreach (explode(";", ENABLED_LANGUAGES) as $language) {
$language = new XpgLocale($language);
$language->codeset = "";
$languages[] = (string) $language;
}
$dh = opendir(LANGUAGE_DIR);
while (($entry = readdir($dh)) !== false) {
if (in_array($entry, $languages)) {
if (is_dir(LANGUAGE_DIR . $entry . "/LC_MESSAGES") && is_file(LANGUAGE_DIR . $entry . "/language.txt")) {
$fh = fopen(LANGUAGE_DIR . $entry . "/language.txt", "r");
$lang_title = fgets($fh);
fclose($fh);
$lang_title = trim($lang_title);
// Names in other scripts get the English name next to them, so
// the entry stays readable without a font for that script
if (class_exists('Locale') && !preg_match('/\p{Latin}/u', $lang_title)) {
$english = Locale::getDisplayLanguage($entry, 'en');
if (!empty($english) && $english !== $entry) {
$lang_title .= " ({$english})";
}
}
$this->languages[$entry] = "{$entry}: " . $lang_title;
}
}
}
asort($this->languages, SORT_LOCALE_STRING);
$this->loaded = true;
}
/**
* Attempt to set language.
*
* setLanguage attempts to set the language to the specified language. The language passed
* is the name of the directory containing the language.
*
* For setLanguage() to succeed, the language has to have been loaded via loadLanguages() AND
* the gettext system must 'know' the language specified.
*
* @param string $lang XPG locale identifier (eg nl_NL)
*/
public function setLanguage($lang) {
if (isset($GLOBALS['translations'])) {
return;
}
$lang = (empty($lang) || str_starts_with($lang, '.') || $lang == "C") ? LANG : $lang; // default language fix
$selected = $this->findLanguage($lang);
if ($selected === false) {
error_log(sprintf("setLanguage: no translations present for \"%s\"", $lang));
$this->resetLocale();
return;
}
$this->lang = $selected;
$this->translations = null;
$this->bindTextDomain($selected);
$tmp_translations = $this->getTranslations();
$translations = [];
foreach ($tmp_translations as $program => $resources) {
if (substr($program, 0, 1) == '_') {
continue;
}
$resourcesCount = count($resources);
for ($i = 0; $i < $resourcesCount; ++$i) {
$msgid = $resources[$i]['msgid'];
if (isset($msgid)) {
$translations[$msgid] = $resources[$i]['msgstr'];
}
}
}
$GLOBALS['translations'] = $translations;
}
/**
* Match a locale identifier request to a directory in LANGUAGE_DIR.
*
* @param string $lang XPG locale identifier
*
* @return bool|XpgLocale the locale naming the directory, or false if none matches
*/
private function findLanguage($lang) {
$p = new XpgLocale($lang);
// Directory names never contain a codeset
$p->codeset = "";
if (is_dir(LANGUAGE_DIR . "/{$p}")) {
return $p;
}
// Try from most specific to least specific
$p->modifier = "";
if (is_dir(LANGUAGE_DIR . "/{$p}")) {
return $p;
}
$p->territory = "";
if (is_dir(LANGUAGE_DIR . "/{$p}")) {
return $p;
}
// PR_EC_USER_LANGUAGE may be a bare language code, which has no directory of
// its own; prefer the administrator's territory of it, then the usual one.
$base = strtolower($p->language);
$aliases = ['no' => 'nb', 'in' => 'id', 'iw' => 'he', 'tl' => 'fil'];
$base = $aliases[$base] ?? $base;
$admin = new XpgLocale(LANG);
$admin->codeset = "";
$adminInstalled = is_dir(LANGUAGE_DIR . "/{$admin}");
if (!preg_match('/^[a-z]{2,3}$/', $base)) {
return $adminInstalled ? $admin : false;
}
if (strtolower($admin->language) === $base && $adminInstalled) {
return $admin;
}
$candidates = glob(LANGUAGE_DIR . '/' . $base . '_' . strtoupper($base)) ?: glob(LANGUAGE_DIR . '/' . $base . '_*') ?: [];
sort($candidates);
if (!empty($candidates)) {
return new XpgLocale(basename($candidates[0]));
}
// An unknown language falls back to the administrator's, as before.
return $adminInstalled ? $admin : false;
}
/**
* @param string $lang XPG locale identifier
*
* @return bool true if translations for the language are installed
*/
public function isLanguage($lang) {
return $this->findLanguage($lang) !== false;
}
/**
* Bind the gettext text domain for the given language.
*
* The JavaScript client receives its translation table from
* getTranslations(). Templates, modules and plugins output strings
* through gettext directly, which needs the text domain bound.
*
* @param XpgLocale $lang
*/
private function bindTextDomain($lang) {
if (!function_exists('bindtextdomain') || !defined('LC_MESSAGES')) {
return;
}
// No failure below may leave another request's language active in this worker.
$this->resetLocale();
// bindtextdomain() resolves a relative path against the working directory at
// lookup time, which is not ours to rely on, so hand it an absolute one.
$dir = realpath(LANGUAGE_DIR);
if ($dir === false) {
return;
}
// LC_CTYPE is set elsewhere!
$lang = clone $lang;
$lang->codeset = "UTF-8";
if (setlocale(LC_MESSAGES, $lang) === false) {
return;
}
bindtextdomain('grommunio_web', $dir);
bind_textdomain_codeset('grommunio_web', 'UTF-8');
textdomain('grommunio_web');
}
/**
* Return the process to the untranslated state. The locale is process-wide and a
* PHP-FPM worker outlives the request, so one request's language would otherwise
* still be active in the next one, served to a different user. LANGUAGE is
* cleared because glibc consults it before LC_MESSAGES. It must never be set per
* user, as glibc does not notice a changed LANGUAGE within the same process.
*/
private function resetLocale() {
if (!function_exists('bindtextdomain') || !defined('LC_MESSAGES')) {
return;
}
setlocale(LC_MESSAGES, 'C');
putenv('LANGUAGE=');
}
public static function getstring($string) {
if (isset($GLOBALS['translations'], $GLOBALS['translations'][$string])) {
return $GLOBALS['translations'][$string];
}
return $string;
}
/**
* Return a list of supported languages.
*
* Returns an associative array in the format langid -> langname, for example "nl_NL.utf8" -> "Nederlands"
*
* @return array List of supported languages
*/
public function getLanguages() {
$this->loadLanguages();
return $this->languages;
}
/**
* Returns the $getLanguages and formats in JSON so it can be parsed
* by the javascript.
*
* @return string The javascript string
*/
public function getJSON() {
$json = [];
$languages = $this->getLanguages();
foreach ($languages as $key => $lang) {
$json[] = [
"lang" => $key,
"name" => $lang,
];
}
return json_encode($json);
}
/**
* @return null|XpgLocale the selected language, null if none is set
*/
public function getSelected() {
return $this->lang;
}
/**
* @return string the selected language in RFC 5646 notation
*/
public function getSelectedIetf() {
if (!is_object($this->lang)) {
return 'en';
}
$l = clone $this->lang;
$l->codeset = $l->modifier = "";
return $l->toString('-');
}
/**
* Populate the shared memory segment with all translations and yield
* the translations of the currently selected language.
*/
public function getTranslations() {
if ($this->translations === null) {
$this->translations = $this->readTranslations();
}
return $this->translations;
}
/**
* @return string fingerprint of the selected language's translations, empty when
* there are none; a URL carrying it changes whenever they do
*/
public function getTranslationsEtag() {
return $this->getTranslations()['_etag'] ?? '';
}
private function readTranslations() {
$selected_lang = (string) $this->getSelected();
// sysvshm is an optional PHP extension. Hosts without it can still read
// the selected catalog from disk; they merely miss the shared cache.
$memid = function_exists('shm_attach') ? @shm_attach(self::CACHE_KEY, self::CACHE_SIZE, 0644) : false;
$memid = $memid instanceof SysvSharedMemory ? $memid : false;
if ($memid !== false && @shm_has_var($memid, 0)) {
$cache_table = @shm_get_var($memid, 0);
// An empty array is a valid table: a host without compiled catalogs
// would otherwise destroy and rebuild the segment on every request.
if (is_array($cache_table)) {
if (!empty($cache_table[$selected_lang])) {
$translations = @shm_get_var($memid, $cache_table[$selected_lang]);
if (!empty($translations)) {
$this->detachCache($memid);
return $translations;
}
/*
* The table promises a payload the segment does not hold, so the
* write behind it failed unnoticed - running out of room in the
* segment does that. Dropping only the table would leave every
* payload allocated, so the rebuild would run out of room again
* and again while still advertising its entries, and this language
* would stay untranslated until the segment is removed by hand.
*/
$memid = $this->resetCache($memid);
return $this->buildTranslations($memid);
}
/*
* A usable table that simply does not list this language. Read it from
* disk rather than rebuilding: a rebuild would write a second copy of
* every other language into a segment that already holds them.
*/
$this->detachCache($memid);
return $this->selectedTranslations($this->parseLanguage($selected_lang));
}
// The table itself is unusable, for instance left behind by another PHP
// version, whose serialized data this one cannot read back.
$memid = $this->resetCache($memid);
}
return $this->buildTranslations($memid);
}
/**
* Discard the translation cache in its entirety and start a new one.
*
* shm_remove_var() frees a single variable, which is not enough once the segment
* is in a state the code cannot read: the payloads stay allocated and the next
* rebuild has nowhere to put its own. Removing the segment releases everything.
*
* @param SysvSharedMemory $memid the segment to discard
*
* @return false|SysvSharedMemory a fresh segment, or false without one
*/
private function resetCache($memid) {
if (!@shm_remove($memid)) {
error_log('Unable to remove the translation cache segment');
}
$this->detachCache($memid);
$replacement = @shm_attach(self::CACHE_KEY, self::CACHE_SIZE, 0644);
return $replacement instanceof SysvSharedMemory ? $replacement : false;
}
/**
* Detach a shared-memory translation cache and report cleanup failures.
*
* @param SysvSharedMemory $memid the segment to detach
*/
private function detachCache($memid) {
if (!@shm_detach($memid)) {
error_log('Unable to detach the translation cache segment');
}
}
/**
* Read every installed language from disk, caching what fits in the segment.
*
* @param false|SysvSharedMemory $memid the segment to fill, or false to skip caching
*
* @return array the translations for the selected language
*/
private function buildTranslations($memid) {
$handle = opendir(LANGUAGE_DIR);
if ($handle === false) {
error_log(sprintf("Cannot read translations from '%s'", LANGUAGE_DIR));
if ($memid !== false) {
$this->detachCache($memid);
}
return ['grommunio_web' => []];
}
$last_id = 1;
$cache_table = [];
$ret_val = false;
while (false !== ($entry = readdir($handle))) {
if (strcmp($entry, ".") == 0 ||
strcmp($entry, "..") == 0) {
continue;
}
$translations = $this->parseLanguage($entry);
if ($translations === false) {
continue;
}
// Answer this request from what was just read, whether or not it caches.
if (strcmp($entry, (string) $this->getSelected()) == 0) {
$ret_val = $translations;
}
if ($memid === false) {
continue;
}
// Advertise only what the segment really holds. An entry pointing at a
// payload that failed to store makes every later request resolve it to
// nothing, which is served as an untranslated interface.
if (@shm_put_var($memid, $last_id, $translations)) {
$cache_table[$entry] = $last_id;
++$last_id;
}
}
closedir($handle);
if ($memid !== false) {
if (!@shm_put_var($memid, 0, $cache_table)) {
error_log('Unable to write the translation cache index');
}
$this->detachCache($memid);
}
return $this->selectedTranslations($ret_val);
}
/**
* Read one language's translations, including those of the plugins.
*
* @param string $entry name of the directory in LANGUAGE_DIR
*
* @return array|bool the translations per domain, or false if there are none
*/
private function parseLanguage($entry) {
$file = LANGUAGE_DIR . $entry . '/LC_MESSAGES/grommunio_web.mo';
$translations = [];
$translations['grommunio_web'] = $this->getTranslationsFromFile($file);
if (!$translations['grommunio_web']) {
return false;
}
$etag = [$entry, @filemtime($file), @filesize($file)];
if (isset($GLOBALS['PluginManager'])) {
// What we did above, we are also now going to do for each plugin that has translations.
$pluginTranslationPaths = $GLOBALS['PluginManager']->getTranslationFilePaths();
foreach ($pluginTranslationPaths as $pluginname => $path) {
$pluginFile = $path . '/' . $entry . '/LC_MESSAGES/plugin_' . $pluginname . '.mo';
$plugin_translations = $this->getTranslationsFromFile($pluginFile);
if ($plugin_translations) {
$translations['plugin_' . $pluginname] = $plugin_translations;
$pluginMtime = @filemtime($pluginFile);
$etag[] = $pluginname . '@' . ($pluginMtime === false ? 0 : $pluginMtime);
}
}
}
// Derived from the files rather than the clock, so a language served from
// disk keeps a stable Etag and clients can still revalidate with 304.
$translations['_etag'] = 'M' . md5(implode('|', $etag));
return $translations;
}
/**
* Hand back the translations that were found, and say so when there are none.
*
* An empty set means the entire interface falls back to its English msgids, which
* is worth a line in the log: it is otherwise indistinguishable from a user who
* selected English, and the .mo files themselves are usually fine.
*
* @param array|bool $translations the translations found for the selected language
*
* @return array translations, or the empty fallback domain
*/
private function selectedTranslations($translations) {
if (is_array($translations) && !empty($translations)) {
return $translations;
}
error_log(sprintf("No translations available for language '%s'", (string) $this->getSelected()));
return ['grommunio_web' => []];
}
/**
* getTranslationsFromFile.
*
* This file reads the translations from the binary .mo file and returns
* them in an array containing the original and the translation variant.
* The .mo file format is described on the following URL.
* http://www.gnu.org/software/gettext/manual/gettext.html#MO-Files
*
* byte
* +------------------------------------------+
* 0 | magic number = 0x950412de |
* | |
* 4 | file format revision = 0 |
* | |
* 8 | number of strings | == N
* | |
* 12 | offset of table with original strings | == O
* | |
* 16 | offset of table with translation strings | == T
* | |
* 20 | size of hashing table | == S
* | |
* 24 | offset of hashing table | == H
* | |
* . .
* . (possibly more entries later) .
* . .
* | |
* O | length & offset 0th string ----------------.
* O + 8 | length & offset 1st string ------------------.
* ... ... | |
* O + ((N-1)*8)| length & offset (N-1)th string | | |
* | | | |
* T | length & offset 0th translation ---------------.
* T + 8 | length & offset 1st translation -----------------.
* ... ... | | | |
* T + ((N-1)*8)| length & offset (N-1)th translation | | | | |
* | | | | | |
* H | start hash table | | | | |
* ... ... | | | |
* H + S * 4 | end hash table | | | | |
* | | | | | |
* | NUL terminated 0th string <----------------' | | |
* | | | | |
* | NUL terminated 1st string <------------------' | |
* | | | |
* ... ... | |
* | | | |
* | NUL terminated 0th translation <---------------' |
* | | |
* | NUL terminated 1st translation <-----------------'
* | |
* ... ...
* | |
* +------------------------------------------+
*
* @param $filename string Name of the .mo file.
*
* @return array|bool false when file is missing otherwise array with
* translations
*/
public function getTranslationsFromFile($filename) {
if (!is_file($filename)) {
return false;
}
$fp = fopen($filename, 'r');
if (!$fp) {
return false;
}
// Get number of strings in .mo file
fseek($fp, 8, SEEK_SET);
$num_of_str = unpack('Lnum', fread($fp, 4));
$num_of_str = $num_of_str['num'];
// Get offset to table with original strings
fseek($fp, 12, SEEK_SET);
$offset_orig_tbl = unpack('Loffset', fread($fp, 4));
$offset_orig_tbl = $offset_orig_tbl['offset'];
// Get offset to table with translation strings
fseek($fp, 16, SEEK_SET);
$offset_transl_tbl = unpack('Loffset', fread($fp, 4));
$offset_transl_tbl = $offset_transl_tbl['offset'];
// The following arrays will contain the length and offset of the strings
$data_orig_strs = [];
$data_transl_strs = [];
/*
* Get the length and offset to the original strings by using the table
* with original strings
*/
// Set pointer to start of orig string table
fseek($fp, $offset_orig_tbl, SEEK_SET);
for ($i = 0; $i < $num_of_str; ++$i) {
// Length 4 bytes followed by offset 4 bytes
$length = unpack('Llen', fread($fp, 4));
$offset = unpack('Loffset', fread($fp, 4));
$data_orig_strs[$i] = ['length' => $length['len'], 'offset' => $offset['offset']];
}
/*
* Get the length and offset to the translation strings by using the table
* with translation strings
*/
// Set pointer to start of translations string table
fseek($fp, $offset_transl_tbl, SEEK_SET);
for ($i = 0; $i < $num_of_str; ++$i) {
// Length 4 bytes followed by offset 4 bytes
$length = unpack('Llen', fread($fp, 4));
$offset = unpack('Loffset', fread($fp, 4));
$data_transl_strs[$i] = ['length' => $length['len'], 'offset' => $offset['offset']];
}
// This array will contain the actual original and translation strings
$translation_data = [];
// Get the original strings using the length and offset
for ($i = 0, $len = count($data_orig_strs); $i < $len; ++$i) {
$translation_data[$i] = [];
// Set pointer to the offset of the string
fseek($fp, $data_orig_strs[$i]['offset'], SEEK_SET);
// Set default values for context and plural forms
$translation_data[$i]['msgctxt'] = false;
$translation_data[$i]['msgid_plural'] = false;
if ($data_orig_strs[$i]['length'] > 0) { // fread does not accept length=0
$length = $data_orig_strs[$i]['length'];
$orig_str = unpack('a' . $length . 'str', fread($fp, $length));
$translation_data[$i]['msgid'] = $orig_str['str']; // unpack converts to array :S
// Find context in the original string
if (str_contains((string) $translation_data[$i]['msgid'], "\004")) {
$contextSplit = explode("\004", (string) $translation_data[$i]['msgid']);
$translation_data[$i]['msgctxt'] = $contextSplit[0];
$translation_data[$i]['msgid'] = $contextSplit[1];
}
// Find plural forms in the original string
if (str_contains((string) $translation_data[$i]['msgid'], "\0")) {
$original = explode("\0", (string) $translation_data[$i]['msgid']);
$translation_data[$i]['msgid'] = $original[0];
$translation_data[$i]['msgid_plural'] = $original[1];
}
}
else {
$translation_data[$i]['msgid'] = '';
}
}
// Get the translation strings using the length and offset
for ($i = 0, $len = count($data_transl_strs); $i < $len; ++$i) {
// Set pointer to the offset of the string
fseek($fp, $data_transl_strs[$i]['offset'], SEEK_SET);
if ($data_transl_strs[$i]['length'] > 0) { // fread does not accept length=0
$length = $data_transl_strs[$i]['length'];
$trans_str = unpack('a' . $length . 'str', fread($fp, $length));
$translation_data[$i]['msgstr'] = $trans_str['str']; // unpack converts to array :S
// If there are plural forms in the source string,
// then the translated string must contain plural
// forms as well. We cannot depend on a \0 being
// present at all times, because languages that
// have only one plural form won't have this
// (e.g. Japanese)
if ($translation_data[$i]['msgid_plural'] !== false) {
$translation_data[$i]['msgstr'] = explode("\0", (string) $translation_data[$i]['msgstr']);
}
}
else {
$translation_data[$i]['msgstr'] = '';
}
}
return $translation_data;
}
}
@@ -0,0 +1,50 @@
<?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
*/
class Log {
/**
* @var Logger
*/
private static $logger;
/**
* Returns the logger object. If no logger has been initialized,
* FileLog will be initialized and returned.
*
* @return Logger
*
* @throws Exception thrown if the logger class cannot be instantiated
*/
private static function getLogger() {
if (!Log::$logger) {
Log::$logger = new FileLog();
Log::$logger->SetUser($GLOBALS["mapisession"]->getUserName());
Log::$logger->SetSpecialLogUsers(explode(";", LOG_USERS));
}
return Log::$logger;
}
/**
* Writes a log line.
*
* @param int $loglevel one of the defined LOGLEVELS
* @param string $message The log message which we want to log in user specific log file
* @param mixed $exception
* @param mixed $requestData
*/
public static function Write($loglevel, $message, $exception = false, $requestData = false) {
try {
Log::getLogger()->Log($loglevel, $message, $exception, $requestData);
}
catch (Exception $e) {
error_log("There is problem to log user action. Exceptions:: " . $e);
}
}
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,64 @@
<?php
/*
* SPDX-FileCopyrightText: Copyright 2020 - 2026 grommunio GmbH
* SPDX-License-Identifier: AGPL-3.0-or-later
*/
/**
* MeetingRequestForwarder.
*
* Forwards a meeting request to additional recipients and informs the
* organizer with a forward notification.
*/
class MeetingRequestForwarder {
/**
* Has mapi-header-php forward a meeting request to additional recipients
* and notify the organizer.
*
* @param resource $store MAPI store of the appointment
* @param string $entryid entryid of the appointment to forward
* @param array $action action data from the client
*
* @return bool true when the request was submitted
*/
public function forward($store, $entryid, $action) {
$message = $GLOBALS['operations']->openMessage($store, $entryid);
if (empty($message)) {
return false;
}
// Build recipient list using the standard Operations helper which
// handles address resolution and one-off entryid creation.
$recipientRows = $GLOBALS['operations']->createRecipientList($this->getForwardRecipients($action), 'add', false, true);
if (empty($recipientRows)) {
return false;
}
$req = new Meetingrequest($store, $message, $GLOBALS['mapisession']->getSession());
$req->forwardMeetingRequest($recipientRows, $action['message_action']['forwardSubjectPrefix'] ?? 'FW: ', empty($action['basedate']) ? false : (int) $action['basedate']);
return true;
}
/**
* @param array $action action data from the client
*
* @return array forward recipients with defaults for missing fields
*/
private function getForwardRecipients($action) {
$forwardRecipients = $action['message_action']['forwardRecipients'] ?? [];
foreach ($forwardRecipients as &$recip) {
$recip['recipient_type'] ??= MAPI_TO;
$recip['address_type'] ??= 'SMTP';
$recip['display_type'] ??= DT_MAILUSER;
$recip['display_type_ex'] ??= DT_MAILUSER;
$recip['object_type'] ??= MAPI_MAILUSER;
}
unset($recip);
return $forwardRecipients;
}
}
@@ -0,0 +1,111 @@
<?php
/*
* SPDX-FileCopyrightText: Copyright 2020 - 2026 grommunio GmbH
* SPDX-License-Identifier: AGPL-3.0-or-later
*/
/**
* Store and folder lookups behind the new mail notification.
*/
class NewMailFolderQuery {
/**
* Collect the default folders for which the client never shows a new mail
* notification.
*
* @param mixed $store the store to inspect
*
* @return array hex entryids of the excluded folders
*/
public static function excludedFolders($store) {
$excluded = [];
try {
$storeProps = mapi_getprops($store, [PR_IPM_WASTEBASKET_ENTRYID, PR_IPM_OUTBOX_ENTRYID, PR_IPM_SENTMAIL_ENTRYID]);
$root = mapi_msgstore_openentry($store);
$rootProps = $root ? mapi_getprops($root, [PR_IPM_DRAFTS_ENTRYID, PR_IPM_JOURNAL_ENTRYID, PR_ADDITIONAL_REN_ENTRYIDS]) : [];
$entryids = [
$storeProps[PR_IPM_WASTEBASKET_ENTRYID] ?? null,
$storeProps[PR_IPM_OUTBOX_ENTRYID] ?? null,
$storeProps[PR_IPM_SENTMAIL_ENTRYID] ?? null,
$rootProps[PR_IPM_DRAFTS_ENTRYID] ?? null,
$rootProps[PR_IPM_JOURNAL_ENTRYID] ?? null,
// Junk mail, see MS-OXOSFLD.
$rootProps[PR_ADDITIONAL_REN_ENTRYIDS][4] ?? null,
];
foreach ($entryids as $folderEntryid) {
if (!empty($folderEntryid)) {
$excluded[] = bin2hex((string) $folderEntryid);
}
}
}
catch (MAPIException $e) {
$e->setHandled();
}
return $excluded;
}
/**
* @param array $entryids hex entryids
* @param string $entryid hex entryid to look for
*
* @return bool true when $entryid is one of $entryids
*/
public static function containsEntryid($entryids, $entryid) {
foreach ($entryids as $candidate) {
if ($GLOBALS["entryid"]->compareEntryIds($candidate, $entryid)) {
return true;
}
}
return false;
}
/**
* Fetch sender and subject of the newest unread message in a folder, used
* to enrich the notification when exactly one new message arrived.
*
* @param mixed $store store containing the folder
* @param string $entryid hex folder entryid
*
* @return null|array sender_name and subject, or null when unavailable
*/
public static function newestUnreadMessage($store, $entryid) {
try {
$folder = mapi_msgstore_openentry($store, hex2bin($entryid));
$table = mapi_folder_getcontentstable($folder, MAPI_DEFERRED_ERRORS);
mapi_table_restrict($table, [RES_BITMASK,
[
ULTYPE => BMR_EQZ,
ULPROPTAG => PR_MESSAGE_FLAGS,
ULMASK => MSGFLAG_READ,
],
], TBL_BATCH);
mapi_table_sort($table, [PR_MESSAGE_DELIVERY_TIME => TABLE_SORT_DESCEND], TBL_BATCH);
$rows = mapi_table_queryrows($table, [PR_SENT_REPRESENTING_NAME, PR_SENDER_NAME, PR_SENT_REPRESENTING_SMTP_ADDRESS, PR_SUBJECT], 0, 1);
if (empty($rows)) {
return null;
}
$row = $rows[0];
$sender = $row[PR_SENT_REPRESENTING_NAME] ?? $row[PR_SENDER_NAME] ?? $row[PR_SENT_REPRESENTING_SMTP_ADDRESS] ?? '';
$subject = $row[PR_SUBJECT] ?? '';
if ($sender === '' && $subject === '') {
return null;
}
return [
'sender_name' => $sender,
'subject' => $subject,
];
}
catch (MAPIException $e) {
$e->setHandled();
return null;
}
}
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,135 @@
<?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
*/
class Plugin {
/** @var string identifying name assigned by PluginManager */
private $pluginname = '';
// holds session data of the plugin
private $sessionData = false;
public function __construct() {}
/**
* setPluginName.
*
* Sets the identifying name of the plugin in a member variable.
*
* @param string $name identifying name of the plugin
*/
public function setPluginName($name) {
$this->pluginname = $name;
}
/**
* getPluginName.
*
* Gets the identifying name of the plugin.
*
* @return string identifying name of the plugin
*/
public function getPluginName() {
return $this->pluginname;
}
/**
* registerHook.
*
* This functions calls the PluginManager to register a hook for this plugin.
*
* @param string $eventID identifier of the event where this hook must be triggered
*/
public function registerHook($eventID) {
if ($this->getPluginName()) {
$GLOBALS['PluginManager']->registerHook($eventID, $this->getPluginName());
}
}
/**
* getData.
*
* This functions returns session data for a key. If the sessiondata is not yet
* loaded the PluginManager is invoked to take care of this
*
* @param $key string Identifier in the session data
*/
public function getData($key) {
// lazy load of plugindata
if (!$this->sessionData) {
$GLOBALS['PluginManager']->loadSessionData($this->getPluginName());
}
if (is_array($this->sessionData) && isset($this->sessionData[$key])) {
return $this->sessionData[$key];
}
return null;
}
/**
* setData.
*
* This functions sets session data for a key. If the sessiondata is not yet
* loaded the PluginManager is invoked to take care of this.
* By default, the function saves the sessiondata to the disk by invoking the PluginManager.
* This could be disabled for performance improvement, but this may cause data loss if the
* data is never saved
*
* @param $key string Identifier in the session data
* @param $value mixed data associated to the key
* @param $autosave boolean By default all data is saved
*/
public function setData($key, $value, $autosave = true) {
// lazy load of plugindata
if (!is_array($this->sessionData)) {
$GLOBALS['PluginManager']->loadSessionData($this->getPluginName());
}
$this->sessionData[$key] = $value;
if ($autosave) {
$GLOBALS['PluginManager']->saveSessionData($this->getPluginName());
}
}
/**
* setSessionData.
*
* Setter for session data
*
* @param $sessionData array() the session data for the plugin
*/
public function setSessionData($sessionData) {
$this->sessionData = $sessionData;
}
/**
* getSessionData.
*
* Getter for session data
*/
public function getSessionData() {
return $this->sessionData;
}
/**
* returns the PLUGINPATH and pluginname as a single string.
*
* @return string path
*/
public function getPluginPath() {
return PATH_PLUGIN_DIR . "/" . (string) $this->getPluginName() . "/";
}
// Placeholder functions keep the signature implemented by event hooks.
public function execute($eventID, &$data) {
unset($eventID, $data);
}
public function init() {}
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,274 @@
<?php
/*
* SPDX-FileCopyrightText: Copyright 2020 - 2026 grommunio GmbH
* SPDX-License-Identifier: AGPL-3.0-or-later
*/
/**
* Turns a plugin manifest.xml into the plugin data used by the PluginManager.
*/
class PluginManifestParser {
private const EMPTY_FILE_LIST = [
LOAD_SOURCE => [],
LOAD_DEBUG => [],
LOAD_RELEASE => [],
];
private $loadMap;
private $typeMap;
private $dependMap;
/**
* @param array $loadMap 'load' attribute values to LOAD_* defines
* @param array $typeMap <serverfile> 'type' attribute values to TYPE_* defines
* @param array $dependMap <depends> 'type' attribute values to DEPEND_* defines
*/
public function __construct(array $loadMap, array $typeMap, array $dependMap) {
$this->loadMap = $loadMap;
$this->typeMap = $typeMap;
$this->dependMap = $dependMap;
}
/**
* @param string $xml plugin XML manifest
* @param string $dirname plugin directory name
*
* @return array|false plugin data, or false when the manifest is unsupported or incomplete
*/
public function parse($xml, $dirname) {
$plugindata = [
'components' => [],
'dependencies' => null,
'translationsdir' => null,
'version' => null,
'title' => $dirname,
'optional' => null,
];
$data = new SimpleXMLElement($xml);
if (isset($data['version']) && (int) $data['version'] !== 2) {
if (DEBUG_PLUGINS) {
dump("[PLUGIN ERROR] Plugin {$dirname} manifest uses version " . $data['version'] . " while only version 2 is supported");
}
return false;
}
if (isset($data->info->version)) {
$plugindata['version'] = (string) $data->info->version;
}
else {
dump("[PLUGIN WARNING] Plugin {$dirname} has not specified version information in manifest.xml");
}
if (isset($data->info->title)) {
$plugindata['title'] = (string) $data->info->title;
}
if (isset($data->config)) {
$plugindata['components'][] = $this->parseConfig($data->config, $dirname);
}
if (isset($data->dependencies, $data->dependencies->depends)) {
$plugindata['dependencies'] = $this->parseDependencies($data->dependencies->depends, $dirname);
}
if (isset($data->optional)) {
$plugindata['optional'] = ((string) $data->optional['settingsname']) ?: $dirname;
}
if (isset($data->translations, $data->translations->translationsdir)) {
$plugindata['translationsdir'] = [
'dir' => (string) $data->translations->translationsdir,
];
}
if (!isset($data->components, $data->components->component)) {
if (DEBUG_PLUGINS) {
dump("[PLUGIN ERROR] Plugin {$dirname} manifest didn't provide any components");
}
return false;
}
foreach ($data->components->component as $component) {
if (isset($component->files)) {
$plugindata['components'][] = $this->parseComponentFiles($component->files, $dirname);
}
}
return $plugindata;
}
/**
* @param SimpleXMLElement $config
* @param string $dirname
*
* @return array
*/
private function parseConfig($config, $dirname) {
if (isset($config->configfile)) {
if (empty($config->configfile)) {
dump("[PLUGIN ERROR] Plugin {$dirname} manifest contains empty configfile declaration");
}
if (!file_exists($config->configfile)) {
dump("[PLUGIN ERROR] Plugin {$dirname} manifest config file does not exists");
}
}
else {
dump("[PLUGIN ERROR] Plugin {$dirname} manifest configfile entry is missing");
}
$files = self::EMPTY_FILE_LIST;
foreach ($config->configfile as $filename) {
$files[LOAD_RELEASE][] = [
'file' => (string) $filename,
'type' => TYPE_CONFIG,
'load' => LOAD_RELEASE,
'module' => null,
'notifier' => null,
];
}
return [
'serverfiles' => $files,
'clientfiles' => [],
'resourcefiles' => [],
];
}
/**
* @param SimpleXMLElement $dependsList the <depends> elements
* @param string $dirname
*
* @return array
*/
private function parseDependencies($dependsList, $dirname) {
$dependencies = [
DEPEND_DEPENDS => [],
DEPEND_REQUIRES => [],
DEPEND_RECOMMENDS => [],
DEPEND_SUGGESTS => [],
];
foreach ($dependsList as $depends) {
$type = $this->dependMap[(string) $depends['type']] ?? null;
if ($type === null) {
dump("[PLUGIN ERROR] Plugin {$dirname} manifest declares dependency {$depends->dependsname} with unknown type \"{$depends['type']}\", the dependency is ignored");
continue;
}
$dependencies[$type][] = [
'plugin' => (string) $depends->dependsname,
];
}
return $dependencies;
}
/**
* @param SimpleXMLElement $files the <files> element of a component
* @param string $dirname
*
* @return array
*/
private function parseComponentFiles($files, $dirname) {
return [
'serverfiles' => $this->parseFileList($files->server->serverfile ?? [], $dirname, true),
'clientfiles' => $this->parseFileList($files->client->clientfile ?? [], $dirname, false),
'resourcefiles' => $this->parseFileList($files->resources->resourcefile ?? [], $dirname, false),
];
}
/**
* @param array|SimpleXMLElement $elements the file elements
* @param string $dirname
* @param bool $server whether these are <serverfile> elements
*
* @return array the file entries keyed by load level
*/
private function parseFileList($elements, $dirname, $server) {
$files = self::EMPTY_FILE_LIST;
foreach ($elements as $element) {
$entry = $server ? $this->serverFileEntry($element) : $this->clientFileEntry($element);
if (empty($entry['file'])) {
$this->reportEmptyFile($dirname, $element);
continue;
}
$unknown = $this->unknownAttribute($entry);
if ($unknown !== null) {
dump("[PLUGIN ERROR] Plugin {$dirname} manifest declares {$element->getName()} {$entry['file']} with unknown {$unknown} \"{$element[$unknown]}\", the file is ignored");
continue;
}
$files[$entry['load']][] = $entry;
}
return [
LOAD_SOURCE => $files[LOAD_SOURCE],
LOAD_DEBUG => $files[LOAD_DEBUG],
LOAD_RELEASE => $files[LOAD_RELEASE],
];
}
/**
* @param SimpleXMLElement $element
*
* @return array
*/
private function serverFileEntry($element) {
return [
'file' => (string) $element,
'type' => isset($element['type']) ? $this->typeMap[(string) $element['type']] ?? null : TYPE_PLUGIN,
'load' => $this->fileLoad($element),
'module' => isset($element['module']) ? (string) $element['module'] : null,
'notifier' => isset($element['notifier']) ? (string) $element['notifier'] : null,
];
}
/**
* @param SimpleXMLElement $element
*
* @return array
*/
private function clientFileEntry($element) {
return [
'file' => (string) $element,
'load' => $this->fileLoad($element),
];
}
/**
* @param SimpleXMLElement $element
*/
private function fileLoad($element) {
return isset($element['load']) ? $this->loadMap[(string) $element['load']] ?? null : LOAD_RELEASE;
}
/**
* @param array $entry the parsed file entry
*
* @return null|string the attribute whose value is not known
*/
private function unknownAttribute($entry) {
foreach (['load', 'type'] as $attribute) {
if (array_key_exists($attribute, $entry) && $entry[$attribute] === null) {
return $attribute;
}
}
return null;
}
/**
* @param string $dirname
* @param SimpleXMLElement $element
*/
private function reportEmptyFile($dirname, $element) {
$name = $element->getName();
if ($name === 'serverfile' || DEBUG_PLUGINS) {
dump("[PLUGIN ERROR] Plugin {$dirname} manifest contains empty {$name} declaration");
}
}
}
@@ -0,0 +1,153 @@
<?php
/*
* SPDX-FileCopyrightText: Copyright 2020 - 2026 grommunio GmbH
* SPDX-License-Identifier: AGPL-3.0-or-later
*/
/**
* Persists plugin session data in the 'plugin_sessiondata' state. Saves merge
* only the keys a plugin changed since it loaded, so concurrent requests of
* the same session do not overwrite each other.
*/
class PluginSessionStore {
/**
* Serialized plugin session data at load time, keyed by plugin name.
*/
private $snapshots = [];
/**
* Reads the session data of all plugins on first use and prepares the
* entry of one plugin.
*
* @param array|false $sessionData session data of all plugins, false when not read yet
* @param string $pluginname plugin name as requested, possibly a legacy alias
* @param string $canonicalName canonical plugin name
* @param bool $exists whether the plugin is loaded
*/
public function load(&$sessionData, $pluginname, $canonicalName, $exists) {
if ($sessionData === false) {
$sessionData = $this->read();
}
if ($pluginname !== $canonicalName && isset($sessionData[$pluginname])) {
$sessionData[$canonicalName] = $sessionData[$pluginname];
unset($sessionData[$pluginname]);
}
if ($exists) {
if (!isset($sessionData[$canonicalName])) {
$sessionData[$canonicalName] = [];
}
$this->snapshots[$canonicalName] = serialize($sessionData[$canonicalName]);
}
}
/**
* Merges the changes of one plugin into the stored session data.
*
* @param array|false $sessionData session data of all plugins, replaced by the stored state
* @param string $pluginname plugin name as requested, possibly a legacy alias
* @param string $canonicalName canonical plugin name
* @param mixed $pluginSessionData the plugin's current session data
*
* @return bool false when the state could not be opened
*/
public function save(&$sessionData, $pluginname, $canonicalName, $pluginSessionData) {
if (isset($this->snapshots[$canonicalName])) {
$baseSessionData = unserialize($this->snapshots[$canonicalName]);
}
else {
$baseSessionData = is_array($sessionData) && array_key_exists($canonicalName, $sessionData) ?
$sessionData[$canonicalName] : [];
}
if (!is_array($sessionData)) {
$sessionData = [];
}
$sessState = new State('plugin_sessiondata');
if (!$sessState->open()) {
error_log('Unable to save plugin session state: ' . $canonicalName);
return false;
}
try {
$currentSessionData = $sessState->read("sessionData");
if (!is_array($currentSessionData)) {
$currentSessionData = [];
}
if ($pluginname !== $canonicalName) {
if (!isset($currentSessionData[$canonicalName]) && isset($currentSessionData[$pluginname])) {
$currentSessionData[$canonicalName] = $currentSessionData[$pluginname];
}
unset($currentSessionData[$pluginname]);
}
$currentPluginData = $currentSessionData[$canonicalName] ?? [];
$currentSessionData[$canonicalName] = $this->merge(
$currentPluginData,
$pluginSessionData,
$baseSessionData
);
$sessState->write("sessionData", $currentSessionData);
$sessionData = $currentSessionData;
$this->snapshots[$canonicalName] = serialize($currentSessionData[$canonicalName]);
}
finally {
$sessState->close();
}
return true;
}
/**
* @return array
*/
private function read() {
$sessState = new State('plugin_sessiondata');
if (!$sessState->open()) {
throw new RuntimeException('Unable to read plugin session state');
}
try {
$sessionData = $sessState->read("sessionData");
}
finally {
$sessState->close();
}
if (!isset($sessionData) || $sessionData == "") {
$sessionData = [];
}
return $sessionData;
}
/**
* Merge keys changed by one plugin instance into the latest state.
*
* @param mixed $current
* @param mixed $local
* @param mixed $base
*/
private function merge($current, $local, $base) {
if (!is_array($current) || !is_array($local) || !is_array($base)) {
return $local;
}
foreach ($base as $key => $value) {
if (!array_key_exists($key, $local)) {
unset($current[$key]);
}
elseif (serialize($local[$key]) !== serialize($value)) {
$current[$key] = $local[$key];
}
}
foreach ($local as $key => $value) {
if (!array_key_exists($key, $base)) {
$current[$key] = $value;
}
}
return $current;
}
}
@@ -0,0 +1,122 @@
<?php
/*
* SPDX-FileCopyrightText: Copyright 2020 - 2026 grommunio GmbH
* SPDX-License-Identifier: AGPL-3.0-or-later
*/
/**
* File cache in a directory that only the web server user may modify.
* Entries are never read through links, and writes replace them atomically.
*/
final class PrivateFileCache {
/**
* Create the cache directory or tighten an existing one to 0700.
*
* @param string $dir cache directory
*
* @return bool true when the directory is safe and writable
*/
public static function ensureDir($dir) {
if (is_link($dir)) {
return false;
}
if (!is_dir($dir) && !@mkdir($dir, 0700, true) && !is_dir($dir)) {
return false;
}
// If the process does not own the directory, never trust entries from it.
if (!@chmod($dir, 0700)) {
return false;
}
clearstatcache(true, $dir);
$stat = @lstat($dir);
if ($stat === false || ($stat['mode'] & 0170000) !== 0040000 || ($stat['mode'] & 0077) !== 0 ||
(function_exists('posix_geteuid') && $stat['uid'] !== posix_geteuid())) {
return false;
}
return is_writable($dir);
}
/**
* Read a cache entry without following a pre-created link.
*
* @param string $file cache filename
* @param null|int $maxAge maximum age in seconds, null for no limit
* @param null|int $maxSize maximum size in bytes, null for no limit
*
* @return null|string cached data, or null for an unsafe, stale or unreadable entry
*/
public static function read($file, $maxAge = null, $maxSize = null) {
if (!is_file($file) || is_link($file)) {
return null;
}
$stat = @lstat($file);
$dirStat = @lstat(dirname($file));
if ($stat === false || $dirStat === false ||
($stat['mode'] & 0170000) !== 0100000 ||
($dirStat['mode'] & 0170000) !== 0040000 ||
($stat['mode'] & 0077) !== 0 || ($dirStat['mode'] & 0077) !== 0 ||
$stat['uid'] !== $dirStat['uid'] ||
($maxSize !== null && $stat['size'] > $maxSize) ||
($maxAge !== null && time() - $stat['mtime'] >= $maxAge)) {
return null;
}
$data = @file_get_contents($file);
return is_string($data) && ($maxSize === null || strlen($data) <= $maxSize) ? $data : null;
}
/**
* Re-check the cache directory, then atomically replace a 0600 entry in it.
*
* @param string $dir cache directory
* @param string $file cache filename
* @param string $data cache contents
* @param string $tmpPrefix temporary file prefix
* @param string $cleanupLog error_log prefix when the temporary file cannot be removed
*
* @return bool true when the cache entry was written
*/
public static function write($dir, $file, $data, $tmpPrefix, $cleanupLog) {
if (!self::ensureDir($dir)) {
return false;
}
return self::writeAtomic($dir, $file, $data, $tmpPrefix, 0600, $cleanupLog);
}
/**
* Atomically replace a file without following a pre-created link.
*
* @param string $dir directory for the temporary file
* @param string $file target filename
* @param string $data file contents
* @param string $tmpPrefix temporary file prefix
* @param int $mode permissions of the new file
* @param string $cleanupLog error_log prefix when the temporary file cannot be removed
*
* @return bool true when the file was replaced
*/
public static function writeAtomic($dir, $file, $data, $tmpPrefix, $mode, $cleanupLog) {
$tmpFile = tempnam($dir, $tmpPrefix);
if ($tmpFile === false) {
return false;
}
try {
$written = file_put_contents($tmpFile, $data, LOCK_EX);
if ($written !== strlen($data) || !@chmod($tmpFile, $mode)) {
return false;
}
return @rename($tmpFile, $file);
}
finally {
if ((is_file($tmpFile) || is_link($tmpFile)) && !@unlink($tmpFile)) {
error_log("{$cleanupLog}: {$tmpFile}");
}
}
}
}
@@ -0,0 +1,114 @@
<?php
/*
* SPDX-FileCopyrightText: Copyright 2020 - 2026 grommunio GmbH
* SPDX-License-Identifier: AGPL-3.0-or-later
*/
/**
* Normalises the profile picture before it is stored on the mailbox.
*/
class ProfilePicture {
/**
* Brings a profile picture into the shape every client renders well: a
* square JPEG of at most PROFILE_PICTURE_MAX_EDGE pixels and
* PROFILE_PICTURE_MAX_BYTES bytes. An image which already fits is kept
* byte for byte.
*
* @param string $dataUrl the base64 data url as sent by the client
*
* @return false|string the JPEG data, or false when it is not usable
*/
public static function normalize($dataUrl) {
if (!preg_match('/^data:image\/(?<extension>(?:png|gif|jpg|jpeg));base64,(?<image>.+)$/', (string) $dataUrl, $matches)) {
return false;
}
$image = base64_decode($matches['image'], true);
if ($image === false || strlen($image) > PROFILE_PICTURE_MAX_BYTES) {
return false;
}
// A small file can still carry a huge canvas; GD would allocate it all.
$size = @getimagesizefromstring($image);
if ($size === false || $size[0] * $size[1] > PROFILE_PICTURE_MAX_PIXELS) {
return false;
}
$source = @imagecreatefromstring($image);
if ($source === false) {
return false;
}
$width = imagesx($source);
$height = imagesy($source);
$isJpeg = strcasecmp($matches['extension'], 'jpeg') == 0 || strcasecmp($matches['extension'], 'jpg') == 0;
if ($isJpeg && $width === $height && $width <= PROFILE_PICTURE_MAX_EDGE) {
imagedestroy($source);
return $image;
}
// Anything else gets the centre square scaled into the bounds.
$square = min($width, $height);
$result = self::encode(
$source,
(int) (($width - $square) / 2),
(int) (($height - $square) / 2),
$square,
min($square, PROFILE_PICTURE_MAX_EDGE)
);
imagedestroy($source);
return $result;
}
/**
* Scales a square region of an image to $edge pixels and encodes it as
* JPEG, lowering the quality and finally the edge length until it fits
* PROFILE_PICTURE_MAX_BYTES.
*
* @param GdImage $source the decoded image
* @param int $x left edge of the region
* @param int $y top edge of the region
* @param int $square edge length of the region
* @param int $edge edge length of the result
*
* @return false|string the JPEG data, or false when it could not be encoded
*/
private static function encode($source, $x, $y, $square, $edge) {
$target = imagecreatetruecolor($edge, $edge);
if ($target === false) {
return false;
}
// Transparency would come out black in JPEG, blend it onto white instead.
imagealphablending($target, true);
imagefilledrectangle($target, 0, 0, $edge, $edge, imagecolorallocate($target, 255, 255, 255));
imagecopyresampled($target, $source, 0, 0, $x, $y, $edge, $edge, $square, $square);
// Above 90 libjpeg drops the chroma subsampling, which multiplies the
// size for no visible gain at this resolution.
$result = false;
for ($quality = 85; $quality >= 40; $quality -= 10) {
ob_start();
$written = imagejpeg($target, null, $quality);
$jpeg = ob_get_clean();
if (!$written) {
break;
}
$result = $jpeg;
if (strlen($jpeg) <= PROFILE_PICTURE_MAX_BYTES) {
break;
}
}
imagedestroy($target);
if ($result === false || strlen($result) <= PROFILE_PICTURE_MAX_BYTES) {
return $result;
}
return $edge > 144 ? self::encode($source, $x, $y, $square, (int) ($edge / 2)) : false;
}
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,409 @@
<?php
/*
* SPDX-FileCopyrightText: Copyright 2020 - 2026 grommunio GmbH
* SPDX-License-Identifier: AGPL-3.0-or-later
*/
/**
* Fetches a small HTTPS resource from a public, DNS-pinned destination.
*
* This is intended for URLs supplied by untrusted external data. Every
* redirect is resolved and checked independently so neither redirects nor
* DNS rebinding can move a request onto an internal network.
*/
final class PublicHttpsResource {
private const MAX_URL_LENGTH = 4096;
/**
* Fetch an HTTPS resource from a public address.
*
* @param string $url URL to fetch
* @param int $maxBytes maximum response body size
* @param int $maxRedirects maximum number of redirects
* @param array $headers request headers
*
* @return null|string response body, or null when the request is refused or fails
*/
public static function fetch($url, $maxBytes, $maxRedirects = 0, $headers = []) {
if (!function_exists('curl_init') || !is_array($headers)) {
return null;
}
foreach ($headers as $header) {
if (!is_string($header) || strlen($header) > 8192 || preg_match('/[\r\n]/', $header) === 1) {
return null;
}
}
$maxBytes = max(1, (int) $maxBytes);
$maxRedirects = max(0, (int) $maxRedirects);
$url = self::normalizeUrl($url);
if ($url === null) {
return null;
}
for ($redirects = 0; $redirects <= $maxRedirects; ++$redirects) {
$response = self::request($url, $maxBytes, $headers);
if ($response === null) {
return null;
}
if ($response['status'] === 200) {
return $response['body'];
}
if ($response['status'] < 300 || $response['status'] > 399 ||
$response['location'] === null || $redirects === $maxRedirects) {
return null;
}
$url = self::resolveRedirectUrl($url, $response['location']);
if ($url === null) {
return null;
}
}
return null;
}
/**
* Perform one request after resolving and pinning its destination.
*
* @param string $url
* @param int $maxBytes
* @param array $headers
*
* @return null|array{body: string, location: null|string, status: int}
*/
private static function request($url, $maxBytes, $headers) {
$pin = self::resolvePin($url);
if ($pin === null) {
return null;
}
$body = '';
$location = null;
$ch = curl_init();
if ($ch === false) {
return null;
}
curl_setopt_array($ch, [
CURLOPT_URL => $url,
CURLOPT_CONNECTTIMEOUT => 3,
CURLOPT_TIMEOUT => 5,
CURLOPT_PROTOCOLS => CURLPROTO_HTTPS,
CURLOPT_FOLLOWLOCATION => false,
CURLOPT_MAXREDIRS => 0,
CURLOPT_MAXFILESIZE => $maxBytes,
CURLOPT_SSL_VERIFYPEER => true,
CURLOPT_SSL_VERIFYHOST => 2,
CURLOPT_PROXY => '',
CURLOPT_HTTPHEADER => $headers,
CURLOPT_HEADERFUNCTION => function ($ch, $line) use (&$location) {
if (stripos($line, 'Location:') === 0) {
$value = trim(substr($line, 9));
$location = preg_match('/[\x00-\x20\x7f]/', $value) === 1 ? null : $value;
}
return strlen($line);
},
CURLOPT_WRITEFUNCTION => function ($ch, $chunk) use (&$body, $maxBytes) {
$length = strlen($chunk);
if ($length > $maxBytes - strlen($body)) {
return 0;
}
$body .= $chunk;
return $length;
},
]);
if (!empty($pin)) {
curl_setopt($ch, CURLOPT_RESOLVE, $pin);
}
$result = curl_exec($ch);
$status = (int) curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
unset($ch);
if ($result === false) {
return null;
}
return [
'body' => $body,
'location' => $location,
'status' => $status,
];
}
/**
* Normalize and strictly validate an HTTPS URL.
*
* @param mixed $url
*
* @return null|string canonical URL
*/
private static function normalizeUrl($url) {
if (!is_string($url) || $url === '' || strlen($url) > self::MAX_URL_LENGTH ||
preg_match('/[\x00-\x20\x5c\x7f]/', $url) === 1) {
return null;
}
$parts = @parse_url($url);
if ($parts === false || strtolower($parts['scheme'] ?? '') !== 'https' ||
empty($parts['host']) || isset($parts['user']) || isset($parts['pass'])) {
return null;
}
$host = self::normalizeHost($parts['host']);
if ($host === null) {
return null;
}
$port = $parts['port'] ?? 443;
if (!is_int($port) || $port < 1 || $port > 65535) {
return null;
}
$authority = str_contains($host, ':') ? '[' . $host . ']' : $host;
if ($port !== 443) {
$authority .= ':' . $port;
}
$path = $parts['path'] ?? '/';
if ($path === '') {
$path = '/';
}
$query = isset($parts['query']) ? '?' . $parts['query'] : '';
return 'https://' . $authority . $path . $query;
}
/**
* Normalize a hostname and reject ambiguous numeric forms.
*
* @param string $host
*
* @return null|string
*/
private static function normalizeHost($host) {
$host = trim((string) $host, '[]');
if (filter_var($host, FILTER_VALIDATE_IP) !== false) {
return strtolower($host);
}
$host = strtolower(rtrim($host, '.'));
if ($host === '' || strlen($host) > 253 || preg_match('/\A[0-9.]+\z/D', $host) === 1 ||
preg_match('/\A(?:0x[0-9a-f]+|[0-9]+)(?:\.(?:0x[0-9a-f]+|[0-9]+)){0,3}\z/iD', $host) === 1 ||
preg_match('/\A(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)(?:\.(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?))*\z/D', $host) !== 1) {
return null;
}
return $host;
}
/**
* Resolve a URL to public addresses and return CURLOPT_RESOLVE entries.
*
* @param string $url normalized URL
*
* @return null|array
*/
private static function resolvePin($url) {
$parts = parse_url($url);
$host = self::normalizeHost($parts['host'] ?? '');
$port = $parts['port'] ?? 443;
if ($host === null) {
return null;
}
if (filter_var($host, FILTER_VALIDATE_IP) !== false) {
return self::isPublicIp($host) ? [] : null;
}
$ips = [];
foreach (@dns_get_record($host, DNS_A | DNS_AAAA) ?: [] as $record) {
$ip = $record['ip'] ?? $record['ipv6'] ?? '';
if (is_string($ip) && self::isPublicIp($ip)) {
$ips[] = $ip;
}
}
foreach (@gethostbynamel($host) ?: [] as $ip) {
if (self::isPublicIp($ip)) {
$ips[] = $ip;
}
}
$ips = array_values(array_unique($ips));
if (empty($ips)) {
return null;
}
$pinned = array_map(function ($ip) {
return str_contains($ip, ':') ? '[' . $ip . ']' : $ip;
}, $ips);
return [$host . ':' . $port . ':' . implode(',', $pinned)];
}
/**
* Require a globally routable unicast address.
*
* @param string $ip
*
* @return bool
*/
private static function isPublicIp($ip) {
$packed = @inet_pton($ip);
if ($packed === false) {
return false;
}
// Validate IPv4-mapped IPv6 addresses as their embedded IPv4 address.
if (strlen($packed) === 16 && substr($packed, 0, 12) === str_repeat("\0", 10) . "\xff\xff") {
$ip = inet_ntop(substr($packed, 12));
$packed = inet_pton($ip);
}
if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE) === false) {
return false;
}
if (strlen($packed) === 16 && !self::ipInCidr($ip, '2000::/3')) {
return false;
}
$nonPublicRanges = [
'100.64.0.0/10', '192.0.0.0/24', '192.0.2.0/24',
'192.88.99.0/24', '198.18.0.0/15', '198.51.100.0/24',
'203.0.113.0/24', '224.0.0.0/4',
'64:ff9b::/96', '64:ff9b:1::/48', '100::/64',
'2001::/23', '2001:db8::/32', '2002::/16',
'3fff::/20', '5f00::/16', 'ff00::/8',
];
foreach ($nonPublicRanges as $range) {
if (self::ipInCidr($ip, $range)) {
return false;
}
}
return true;
}
/**
* Test whether an IP address belongs to a CIDR block.
*
* @param string $ip
* @param string $cidr
*
* @return bool
*/
private static function ipInCidr($ip, $cidr) {
[$network, $prefix] = explode('/', $cidr, 2);
$addressBytes = @inet_pton($ip);
$networkBytes = @inet_pton($network);
$prefix = (int) $prefix;
if ($addressBytes === false || $networkBytes === false || strlen($addressBytes) !== strlen($networkBytes) ||
$prefix < 0 || $prefix > strlen($addressBytes) * 8) {
return false;
}
$wholeBytes = intdiv($prefix, 8);
if ($wholeBytes > 0 && substr($addressBytes, 0, $wholeBytes) !== substr($networkBytes, 0, $wholeBytes)) {
return false;
}
$remainingBits = $prefix % 8;
if ($remainingBits === 0) {
return true;
}
$mask = (0xFF << (8 - $remainingBits)) & 0xFF;
return (ord($addressBytes[$wholeBytes]) & $mask) === (ord($networkBytes[$wholeBytes]) & $mask);
}
/**
* Resolve a Location header relative to the request URL.
*
* @param string $baseUrl
* @param string $location
*
* @return null|string normalized redirect URL
*/
private static function resolveRedirectUrl($baseUrl, $location) {
if ($location === '' || strlen($location) > self::MAX_URL_LENGTH ||
preg_match('/[\x00-\x20\x5c\x7f]/', $location) === 1) {
return null;
}
$locationParts = @parse_url($location);
if ($locationParts === false) {
return null;
}
if (isset($locationParts['scheme'])) {
return self::normalizeUrl($location);
}
if (str_starts_with($location, '//')) {
return self::normalizeUrl('https:' . $location);
}
$base = parse_url($baseUrl);
$host = $base['host'];
$authority = str_contains($host, ':') ? '[' . trim($host, '[]') . ']' : $host;
if (isset($base['port']) && $base['port'] !== 443) {
$authority .= ':' . $base['port'];
}
if (str_starts_with($location, '/')) {
$pathAndQuery = $location;
}
elseif (str_starts_with($location, '?')) {
$pathAndQuery = ($base['path'] ?? '/') . $location;
}
else {
$basePath = $base['path'] ?? '/';
$directory = substr($basePath, 0, strrpos($basePath, '/') + 1);
$pathAndQuery = $directory . $location;
}
$relative = parse_url($pathAndQuery);
if ($relative === false) {
return null;
}
$path = self::removeDotSegments($relative['path'] ?? '/');
$query = isset($relative['query']) ? '?' . $relative['query'] : '';
return self::normalizeUrl('https://' . $authority . $path . $query);
}
/**
* Remove dot segments from a URL path.
*
* @param string $path
*
* @return string
*/
private static function removeDotSegments($path) {
$trailingSlash = str_ends_with($path, '/') || str_ends_with($path, '/.') || str_ends_with($path, '/..');
$segments = [];
foreach (explode('/', $path) as $index => $segment) {
if (($index === 0 && $segment === '') || $segment === '.') {
continue;
}
if ($segment === '..') {
if (!empty($segments)) {
array_pop($segments);
}
}
else {
$segments[] = $segment;
}
}
$result = '/' . implode('/', $segments);
return $trailingSlash && !str_ends_with($result, '/') ? $result . '/' : $result;
}
}
@@ -0,0 +1,105 @@
<?php
/*
* SPDX-FileCopyrightText: Copyright 2020 - 2026 grommunio GmbH
* SPDX-License-Identifier: AGPL-3.0-or-later
*/
require_once __DIR__ . '/class.httporigin.php';
/**
* Derives and compares the origin of the current request.
*/
class RequestOrigin {
/**
* Check whether browser metadata proves that a GET request originated here.
*
* This is only intended for compatibility endpoints whose state-changing GET
* behavior predates CSRF protection. Cross-site top-level navigations commonly
* omit Origin, so a request without trustworthy browser metadata fails closed.
*
* @return bool true when the browser identifies a same-origin initiator
*/
public static function isSameOriginSource() {
$requestOrigin = self::get();
if ($requestOrigin === null) {
return false;
}
if (isset($_SERVER['HTTP_ORIGIN'])) {
return HttpOrigin::normalize($_SERVER['HTTP_ORIGIN']) === $requestOrigin;
}
// "none" marks a navigation the user started (typed URL, bookmark);
// no other site can produce it.
$fetchSite = strtolower(trim((string) ($_SERVER['HTTP_SEC_FETCH_SITE'] ?? '')));
if ($fetchSite !== '') {
return $fetchSite === 'same-origin' || $fetchSite === 'none';
}
if (isset($_SERVER['HTTP_REFERER'])) {
return HttpOrigin::fromUrl($_SERVER['HTTP_REFERER']) === $requestOrigin;
}
// XMLHttpRequest is not a CORS-safelisted header, so a cross-origin page
// cannot add it without a successful preflight. The logout endpoints reject
// preflight, making this a safe fallback for older same-origin AJAX clients.
return isset($_SERVER['HTTP_X_REQUESTED_WITH']) &&
is_string($_SERVER['HTTP_X_REQUESTED_WITH']) &&
strcasecmp(trim($_SERVER['HTTP_X_REQUESTED_WITH']), 'XMLHttpRequest') === 0;
}
/**
* Return the normalized origin of this request.
*
* @return null|string
*/
public static function get() {
$directHttps = (!empty($_SERVER['HTTPS']) && strtolower((string) $_SERVER['HTTPS']) !== 'off') ||
(int) ($_SERVER['SERVER_PORT'] ?? 0) === 443;
$https = $directHttps;
// A TLS-terminating proxy reports the public scheme in X-Forwarded-Proto.
$forwardedProto = strtolower(trim(explode(',', (string) ($_SERVER['HTTP_X_FORWARDED_PROTO'] ?? ''), 2)[0]));
if ($forwardedProto === 'https') {
$https = true;
}
// Secure cookies are the default and require the public application URL to use HTTPS.
if (!$https && (!defined('SECURE_COOKIES') || SECURE_COOKIES !== false)) {
$https = true;
}
$scheme = $https ? 'https' : 'http';
// HTTP_HOST is the authority the browser used for this request and carries
// aliases and public ports through common reverse proxies. A proxy that
// rewrites Host passes the public authority in X-Forwarded-Host. Use them
// only for this same-request origin comparison; redirects and OAuth
// callbacks must continue to use separately trusted configuration.
$forwardedHost = trim(explode(',', (string) ($_SERVER['HTTP_X_FORWARDED_HOST'] ?? ''), 2)[0]);
$host = $forwardedHost !== '' ? $forwardedHost : ($_SERVER['HTTP_HOST'] ?? null);
if ($host !== null) {
if (!is_string($host) ||
preg_match('/[\x00-\x20\x23\x2f\x3f\x40\x5c\x7f]/', $host) === 1 ||
str_ends_with($host, ':')) {
return null;
}
return HttpOrigin::normalize($scheme . '://' . $host);
}
$host = trim((string) ($_SERVER['SERVER_NAME'] ?? ''), '[]');
$serverAuthority = str_contains($host, ':') ? '[' . $host . ']' : $host;
if (HttpOrigin::normalize($scheme . '://' . $serverAuthority) === null) {
return null;
}
$authority = $serverAuthority;
$port = (int) ($_SERVER['SERVER_PORT'] ?? 0);
// A TLS-terminating proxy can expose any HTTP upstream port here.
if ($https && !$directHttps) {
$port = 443;
}
if ($port > 0 && $port !== ($https ? 443 : 80)) {
$authority .= ':' . $port;
}
return HttpOrigin::normalize($scheme . '://' . $authority);
}
}
@@ -0,0 +1,184 @@
<?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__ . '/class.requestorigin.php';
/**
* This class has some methods to utilize http responses.
*/
class Response {
/**
* Sends a 405 Method Not Allowed header and stops the script.
*/
public static function wrongMethod(): never {
header('HTTP/1.1 405 Method Not Allowed');
exit;
}
/**
* Sends a 404 Not Found header and stops the script.
*/
public static function notFound(): never {
header('HTTP/1.1 404 Not Found');
exit;
}
/**
* Sends a 401 Unauthorized and stops the script.
*/
public static function unAuthorized(): never {
header('HTTP/1.1 401 Unauthorized');
exit;
}
/**
* Sends a 403 Forbidden and stops the script.
*/
public static function forbidden(): never {
header('HTTP/1.1 403 Forbidden');
exit;
}
/**
* Authorize the request origin and answer CORS preflight requests.
*
* @param string $allowedMethod method accepted by the controller
*/
public static function enforceCors($allowedMethod) {
if (!self::addCorsHeaders()) {
self::forbidden();
}
if (strtoupper((string) ($_SERVER['REQUEST_METHOD'] ?? '')) !== 'OPTIONS') {
return;
}
$allowedMethod = strtoupper((string) $allowedMethod);
$requestedMethod = strtoupper((string) ($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD'] ?? ''));
if ($requestedMethod !== $allowedMethod) {
header('Allow: ' . $allowedMethod);
self::wrongMethod();
}
$allowedHeaders = ['content-type', 'x-requested-with'];
$requestedHeaders = trim((string) ($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS'] ?? ''));
if ($requestedHeaders !== '') {
foreach (explode(',', strtolower($requestedHeaders)) as $header) {
$header = trim($header);
if (!in_array($header, $allowedHeaders, true)) {
self::forbidden();
}
}
header('Access-Control-Allow-Headers: Content-Type, X-Requested-With');
}
header('Access-Control-Allow-Methods: ' . $allowedMethod);
header('Vary: Access-Control-Request-Method', false);
header('Vary: Access-Control-Request-Headers', false);
http_response_code(204);
exit;
}
/**
* Check whether the request origin is permitted without granting response access.
*
* @return bool true when the request origin is permitted
*/
public static function isOriginAllowed() {
return self::checkOrigin(false);
}
/**
* Check whether browser metadata proves that a GET request originated here.
*
* @return bool true when the browser identifies a same-origin initiator
*/
public static function isSameOriginRequestSource() {
return RequestOrigin::isSameOriginSource();
}
/**
* Will add the necessary CORS headers to the response, in order to enable
* cross domain requests. Will only add the headers if the administrator
* has enabled it for the domain that sent the request.
*
* @return bool true when the request origin is permitted
*/
public static function addCorsHeaders() {
return self::checkOrigin(true);
}
/**
* Evaluate the configured request-origin policy.
*
* @param bool $addHeaders grant cross-origin response access when permitted
*
* @return bool true when the request origin is permitted
*/
private static function checkOrigin($addHeaders) {
$allowedDomains = defined('CROSS_DOMAIN_AUTHENTICATION_ALLOWED_DOMAINS') ? CROSS_DOMAIN_AUTHENTICATION_ALLOWED_DOMAINS : '';
$originHeader = $_SERVER['HTTP_ORIGIN'] ?? null;
if ($originHeader === null) {
// Preserve non-browser and legacy same-origin clients which omit Origin.
return true;
}
$origin = HttpOrigin::normalize($originHeader);
if ($origin === null) {
return false;
}
$requestOrigin = RequestOrigin::get();
if ($requestOrigin === null) {
return false;
}
if ($origin === $requestOrigin) {
return true;
}
if ($allowedDomains === '*') {
// All domains are allowed
if ($addHeaders) {
header('Access-Control-Allow-Origin: *');
}
return true;
}
if (gettype($allowedDomains) !== 'string') {
// Misconfigured. Don't add any CORS headers.
$webAppTitle = defined('WEBAPP_TITLE') && WEBAPP_TITLE ? WEBAPP_TITLE : 'grommunio Web';
error_log($webAppTitle . ': CROSS_DOMAIN_AUTHENTICATION_ALLOWED_DOMAINS misconfigured');
return false;
}
$allowedDomains = preg_split('/\s+/', trim($allowedDomains)) ?: [];
foreach ($allowedDomains as $domain) {
if (HttpOrigin::normalize($domain) === $origin) {
if ($addHeaders) {
// This domain was granted access by the administrator, so add the CORS headers
header('Access-Control-Allow-Origin: ' . $origin);
header('Access-Control-Allow-Credentials: true');
header('Vary: Origin', false);
}
return true;
}
}
return false;
}
}
@@ -0,0 +1,810 @@
<?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 __DIR__ . '/../exceptions/class.SettingsException.php';
require_once __DIR__ . '/class.profilepicture.php';
/**
* Generic settings class.
*
* This class allows access to various user settings which are normally
* configured by the user. Settings can be set and retrieved
* via this class. Default values must be provided at retrieval time.
*
* Settings have a path-like structure, for example:
* <code>
* path/to/setting => 5
* </code>
*/
class Settings {
/**
* Root key of the settings tree inside PR_EC_WEBACCESS_SETTINGS_JSON.
*/
private const SETTINGS_ROOT = 'grommunio';
/**
* The root key used before the rename. Trees still carrying it are moved
* onto {@link self::SETTINGS_ROOT} by {@link #migrateLegacyRoot}.
*/
private const LEGACY_SETTINGS_ROOT = 'zarafa';
/**
* User's default message store where we will be storing all the settings in a property.
*/
private $store;
/**
* Associative array that stores all webapp settings; it is filled by retrieveAllSettings()
* and will be used when we call saveSettings.
*/
private $settings;
/**
* Associative array that stores all persistent webapp settings; it is filled by
* retrieveAllSettings() and used when saveSettings() is called.
*/
private $persistentSettings;
/**
* Boolean Flag to indicate that settings has been initialized and we can safely call saveSettings to
* add/update new settings, if this is false then it will indicate that there was some problem
* initializing $this->settings object and we shouldn't continue saving new settings as that will
* lose all existing settings of the user.
*/
private $init;
/**
* True once retrieveSettings() returned, i.e. $this->settings came from the store.
*/
private $settingsLoaded;
/**
* True once retrievePersistentSettings() returned.
*/
private $persistentSettingsLoaded;
/**
* Array Settings that are defined by system admin.
*/
private $sysAdminDefaults;
/**
* True once a load attempt threw, so it is not retried on every accessor.
*/
private $loadFailed;
/**
* Json encoded string which represents existing set of settings, this can be compared with json encoded
* string of $this->settings to check if there was a change in settings and we need to save the changes
* to mapi.
*/
private $settings_string;
/**
* Json encoded string which represents existing set of settings, this can be compared with json encoded
* string of $this->settings to check if there was a change in settings and we need to save the changes
* to mapi.
*/
private $persistentSettingsString;
/**
* Keeps track of all modifications on settings which are not saved yet.
* The array is reset in saveSettings() after a successful save.
*/
private $modified;
/**
* Keeps track of all modifications on persistent settings which are not saved yet.
* The array is reset in savePersistentSettings() after a successful save.
*/
private $modifiedPersistent;
/**
* True when the loaded tree still used the legacy root, so the migrated
* tree has to be written back once even if nothing else changed.
*/
private $legacyRootMigrated;
public function __construct() {
$this->settings = [];
$this->persistentSettings = [];
$this->sysAdminDefaults = [];
$this->settings_string = '';
$this->persistentSettingsString = '';
$this->modified = [];
$this->modifiedPersistent = [];
$this->init = false;
$this->loadFailed = false;
$this->settingsLoaded = false;
$this->persistentSettingsLoaded = false;
$this->legacyRootMigrated = false;
}
/**
* Initialise the settings class.
*
* Opens the default store and gets the settings. This is done only once. Therefore
* changes written to the settings after the first Init() call will be invisible to this
* instance of the Settings class
*/
public function Init() {
if ($this->init || $this->loadFailed) {
return;
}
$GLOBALS['PluginManager']->triggerHook('server.core.settings.init.before', ['settingsObj' => $this]);
$this->store = $GLOBALS['mapisession']->getDefaultMessageStore();
// ignore exceptions when loading settings
try {
$this->retrieveSettings();
$this->settingsLoaded = true;
$this->retrievePersistentSettings();
$this->persistentSettingsLoaded = true;
// this object will only be initialized when we are able to retrieve existing settings correctly
$this->init = true;
}
catch (SettingsException $e) {
$e->setHandled();
// $this->init stays false, so from here get() answers with its
// default for every path.
$this->loadFailed = true;
$msg = "Settings::Init(): the settings of this store could not be loaded, continuing with defaults for every setting: " . $e->getMessage();
error_log($msg);
Log::Write(LOGLEVEL_ERROR, $msg);
}
// The tree is already migrated in memory, so every read is correct from
// here on. Write it back once so the legacy root leaves the store.
if ($this->init && $this->legacyRootMigrated) {
$this->saveSettings();
}
}
/**
* False means the load threw and was handled, so {@link #get} answers with
* its default for every path rather than with a stored value.
*
* @return bool true when the settings came from the store
*/
public function isLoaded() {
if (!$this->init) {
$this->Init();
}
return $this->settingsLoaded;
}
/**
* Get a setting from the settings repository.
*
* Retrieves the setting at the path specified. If the setting is not found, and no $default value
* is passed, returns null.
*
* @param null|string $path path to the setting you want to get, separated with slashes
* @param mixed $default value returned when the setting is not found
* @param bool $persistent set to true to get the given $path from the persistent settings
*
* @return mixed setting data, the complete settings array when no path is supplied, or the default
*/
public function get($path = null, $default = null, $persistent = false) {
$path = $this->aliasPath($path);
if (!$this->init) {
$this->Init();
}
$settings = (bool) $persistent ? $this->persistentSettings : $this->settings;
if ($path === null) {
return $settings;
}
$path = explode('/', $path);
$tmp = $settings;
foreach ($path as $pointer) {
if (!empty($pointer)) {
if (!isset($tmp[$pointer])) {
return $default;
}
$tmp = $tmp[$pointer];
}
}
return $tmp;
}
/**
* Get a setting from the persistent settings repository.
*
* Retrieves the setting at the path specified. If the setting is not found, and no $default value
* is passed, returns null.
*
* @param null|string $path path to the setting you want to get, separated with slashes
* @param mixed $default value returned when the setting is not found
*
* @return mixed setting data, the complete settings array when no path is supplied, or the default
*/
public function getPersistent($path = null, $default = null) {
return $this->get($path, $default, true);
}
/**
* Store a setting.
*
* Overwrites a setting at a specific settings path with the value passed.
*
* @param string $path path to the setting you want to set, separated with slashes
* @param mixed $value New value for the setting
* @param bool $autoSave true to directly save the settings to the MAPI Store,
* this defaults to false as the settings will be saved at the end of the request
* @param bool $persistent true to set a persistent setting, false otherwise
*/
public function set($path, $value, $autoSave = false, $persistent = false) {
$path = $this->aliasPath($path);
if (!$this->init) {
$this->Init();
}
if ((bool) $persistent) {
$this->modifiedPersistent[] = ['path' => $path, 'value' => $value];
}
else {
$this->modified[] = ['path' => $path, 'value' => $value, 'delete' => false];
}
if ((bool) $persistent) {
$this->setPathValue($this->persistentSettings, $path, $value);
}
else {
$this->setPathValue($this->settings, $path, $value);
}
if ($autoSave === true) {
(bool) $persistent ? $this->savePersistentSettings() : $this->saveSettings();
}
}
/**
* Store a persistent setting.
*
* Overwrites a persistent setting at a specific settings path with the value passed.
*
* @param string $path path to the setting you want to set, separated with slashes
* @param mixed $value New value for the setting
* @param bool $autoSave true to directly save the settings to the MAPI Store,
* this defaults to false as the settings will be saved at the end of the request
*/
public function setPersistent($path, $value, $autoSave = false) {
$this->set($path, $value, $autoSave, true);
}
/**
* Delete a setting.
*
* Deletes the setting references by $path
*
* @param string $path Path to the setting you want to delete
* @param bool $autoSave true to directly save the settings to the MAPI Store,
* this defaults to false as the settings will be saved at the end of the request
*/
public function delete($path, $autoSave = false) {
$path = $this->aliasPath($path);
if (!$this->init) {
$this->Init();
}
$this->modified[] = ['path' => $path, 'delete' => true];
if (!$this->deletePathValue($this->settings, $path)) {
return;
}
if ($autoSave === true) {
$this->saveSettings();
}
}
/**
* Get all settings as a Javascript script.
*
* This function will output all settings as a JSON object, allowing easy including in client-side javascript.
*
* @return string json encoded php array
*/
public function getJSON() {
if (!$this->init) {
$this->Init();
}
return json_encode($this->settings);
}
/**
* Get all persistent settings as a Javascript script.
*
* This function will output all persistent settings as a JSON object, allowing easy including in client-side
* javascript.
*
* @return string json encoded php array
*/
public function getPersistentSettingsJSON() {
if (!$this->init) {
$this->Init();
}
return json_encode($this->persistentSettings);
}
/**
* Accept the legacy settings root plugins written before the rename still use.
*
* @param null|string $path
*
* @return null|string
*/
private function aliasPath($path) {
return is_string($path) ? preg_replace('#^/?' . self::LEGACY_SETTINGS_ROOT . '(?=/|$)#', self::SETTINGS_ROOT, $path, 1) : $path;
}
/**
* Move a settings tree that still uses the legacy root onto the current one.
*
* Runs on every load rather than once, because reloadModifiedSettings()
* throws the in-memory tree away and re-reads the store before replaying
* this request's changes; normalising here keeps both paths on the new
* shape. The legacy subtree is dropped, and since writeSettings()
* serialises the whole tree the first save persists that removal.
*
* @param array $settings the decoded settings tree
*
* @return array the tree rooted at {@link self::SETTINGS_ROOT}
*/
private function migrateLegacyRoot($settings) {
if (!isset($settings[self::LEGACY_SETTINGS_ROOT])) {
return $settings;
}
$legacy = $settings[self::LEGACY_SETTINGS_ROOT];
unset($settings[self::LEGACY_SETTINGS_ROOT]);
// Both roots exist when an earlier migration was interrupted, or when
// the store saw a downgrade and then this version again. What the newer
// root holds is the more recent value, so it wins over the legacy one.
$settings[self::SETTINGS_ROOT] = isset($settings[self::SETTINGS_ROOT]) && is_array($settings[self::SETTINGS_ROOT])
? array_replace_recursive(is_array($legacy) ? $legacy : [], $settings[self::SETTINGS_ROOT])
: (is_array($legacy) ? $legacy : []);
$this->legacyRootMigrated = true;
return $settings;
}
/**
* Get settings from store.
*
* This function retrieves the actual settings from the store.
* Settings are stored in two different properties as we wanted to ship new webaccess and older webaccess
* simultenously so both webaccess uses different settings and doesn't interfere with each other.
*
* new webaccess uses string property PR_EC_WEBACCESS_SETTINGS_JSON which contains settings in JSON format
*
* This function returns nothing, but populates the 'settings' property of the class.
*/
public function retrieveSettings() {
// first check if property exist and we can open that using mapi_openproperty
$storeProps = mapi_getprops($this->store, [PR_EC_WEBACCESS_SETTINGS_JSON, PR_EC_USER_LANGUAGE]);
$language = $storeProps[PR_EC_USER_LANGUAGE] ?? $_COOKIE['lang'] ?? null;
$settings = ["settings" => ["grommunio" => ["v1" => ["main" => []]]]];
// Check if property exists, if it does not exist then we can continue with empty set of settings
$settingsString = readMapiProp($this->store, PR_EC_WEBACCESS_SETTINGS_JSON, $storeProps);
if ($settingsString !== null) {
$this->settings_string = $settingsString;
if (!empty($this->settings_string)) {
$settings = json_decode_data($this->settings_string, true);
if (empty($settings) || empty($settings['settings'])) {
throw new SettingsException(_('Error retrieving existing settings'));
}
$settings['settings'] = $this->migrateLegacyRoot($settings['settings']);
}
if ($language !== null) {
$settings["settings"]["grommunio"]["v1"]["main"]["language"] = $language;
}
// Get and apply the System Administrator default settings
$sysadminSettings = $this->getDefaultSysAdminSettings();
$settings = array_replace_recursive($sysadminSettings, $settings['settings']);
$this->settings = array_replace_recursive($settings, $this->settings);
}
elseif (!ENABLE_WELCOME_SCREEN) {
/*
* if ENABLE_WELCOME_SCREEN is false and PR_EC_WEBACCESS_SETTINGS_JSON does not exist at that time, we
* just append the admin settings to settings array. Normally system admin settings
* contains plugin default enable/disable and other plugins related settings information which required
* while webapp loads.
*/
if ($language !== null) {
$settings["settings"]["grommunio"]["v1"]["main"]["language"] = $language;
}
$sysadminSettings = $this->getDefaultSysAdminSettings();
$this->settings = array_replace_recursive($sysadminSettings, $settings['settings']);
}
}
/**
* Get persistent settings from store.
*
* This function retrieves the actual persistent settings from the store.
* Persistent settings are stored in PR_EC_WEBAPP_PERSISTENT_SETTINGS_JSON.
*
* This function returns nothing, but populates the 'persistentSettings' property of the class.
*/
private function retrievePersistentSettings() {
// first check if property exist and we can open that using mapi_openproperty
$storeProps = mapi_getprops($this->store, [PR_EC_WEBAPP_PERSISTENT_SETTINGS_JSON]);
// Check if property exists, if it does not exist then we can continue with empty set of settings
$persistentSettingsString = readMapiProp($this->store, PR_EC_WEBAPP_PERSISTENT_SETTINGS_JSON, $storeProps);
if ($persistentSettingsString !== null) {
$this->persistentSettingsString = $persistentSettingsString;
if (!empty($this->persistentSettingsString)) {
try {
$persistentSettings = json_decode_data($this->persistentSettingsString, true);
}
catch (Exception) {
throw new SettingsException(_('Error retrieving existing persistent settings'));
}
if (empty($persistentSettings) || empty($persistentSettings['settings'])) {
throw new SettingsException(_('Error retrieving existing persistent settings'));
}
$this->persistentSettings = $persistentSettings['settings'];
}
}
}
/**
* Retrieves the default settings as defined by the System Administrator.
*
* @return array Settings object
*/
public function getDefaultSysAdminSettings() {
return $this->sysAdminDefaults;
}
/**
* Applies the default settings defined by the System Administrator to the sysAdminDefaults
* property.
*
* @param array $settings The default settings
*/
public function addSysAdminDefaults($settings) {
$this->sysAdminDefaults = array_replace_recursive($this->sysAdminDefaults, $this->migrateLegacyRoot($settings));
}
/**
* Takes two arrays, one settings and one defaults and removes the items from the settings
* array that have the same value as the defaults array. What is left is the settings that
* are not in the defaults array and the changed values of the ones that their keys do match
* in the defaults. It calls itself recursively to check the full array.
*
* @param array $settings The array containing the unfiltered settings
* @param array $defaults the array containing the default key/values
*
* @return array The filtered settings array
*/
public function filterOutSettings($settings, $defaults) {
foreach ($defaults as $key => $value) {
if (isset($settings[$key])) {
if ($defaults[$key] == $settings[$key]) {
unset($settings[$key]);
}
elseif (is_array($defaults[$key])) {
$settings[$key] = $this->filterOutSettings($settings[$key], $defaults[$key]);
}
}
}
return $settings;
}
/**
* Set one slash-separated path in a settings array.
*
* @param mixed $settings
* @param mixed $path
* @param mixed $value
*/
private function setPathValue(&$settings, $path, $value) {
$path = self::pathKeys($path);
$lastKey = array_pop($path);
if ($lastKey === null) {
return;
}
$pointer = &$settings;
foreach ($path as $key) {
if (!isset($pointer[$key]) || !is_array($pointer[$key])) {
$pointer[$key] = [];
}
$pointer = &$pointer[$key];
}
$pointer[$lastKey] = $value;
unset($pointer);
}
/**
* Split a slash-separated settings path into its non-empty keys.
*
* @param mixed $path
*
* @return array
*/
private static function pathKeys($path) {
return array_values(array_filter(explode('/', $path), static fn ($key) => $key !== ''));
}
/**
* Remove one slash-separated path from a settings array.
*
* @param mixed $settings
* @param mixed $path
*/
private function deletePathValue(&$settings, $path) {
$keys = self::pathKeys($path);
$lastKey = array_pop($keys);
if ($lastKey === null) {
return false;
}
$pointer = &$settings;
foreach ($keys as $key) {
if (!isset($pointer[$key]) || !is_array($pointer[$key])) {
return false;
}
$pointer = &$pointer[$key];
}
if (!array_key_exists($lastKey, $pointer)) {
return false;
}
unset($pointer[$lastKey], $pointer);
return true;
}
/**
* Reload the latest regular settings and replay this request's changes.
*/
private function reloadModifiedSettings() {
$settings = $this->settings;
$settingsString = $this->settings_string;
$this->settings = [];
$this->settings_string = '';
try {
$this->retrieveSettings();
}
catch (Throwable $e) {
$this->settings = $settings;
$this->settings_string = $settingsString;
throw $e;
}
foreach ($this->modified as $operation) {
if ($operation['delete']) {
$this->deletePathValue($this->settings, $operation['path']);
}
else {
$this->setPathValue($this->settings, $operation['path'], $operation['value']);
}
}
}
/**
* Reload the latest persistent settings and replay this request's changes.
*/
private function reloadModifiedPersistentSettings() {
$settings = $this->persistentSettings;
$settingsString = $this->persistentSettingsString;
$this->persistentSettings = [];
$this->persistentSettingsString = '';
try {
$this->retrievePersistentSettings();
}
catch (Throwable $e) {
$this->persistentSettings = $settings;
$this->persistentSettingsString = $settingsString;
throw $e;
}
foreach ($this->modifiedPersistent as $operation) {
$this->setPathValue($this->persistentSettings, $operation['path'], $operation['value']);
}
}
/**
* Refresh regular settings while preserving unsaved local changes.
*/
public function refreshSettings() {
if (!$this->init) {
$this->Init();
}
if ($this->settingsLoaded) {
$this->reloadModifiedSettings();
}
}
/**
* Save settings to store.
*
* This function saves all settings to the store's PR_EC_WEBACCESS_SETTINGS_JSON property, and to the
* PR_EC_OUTOFOFFICE_* properties.
*/
public function saveSettings() {
if (!$this->init) {
$this->Init();
}
// Saving now would replace stored settings that could not be read.
if (!$this->settingsLoaded) {
$msg = "Settings::saveSettings() skipped: the settings of this store could not be read, saving would replace them.";
error_log($msg);
Log::Write(LOGLEVEL_ERROR, $msg);
return;
}
if (empty($this->modified) && !$this->legacyRootMigrated) {
return;
}
$settingsState = State::forStore('settings-write');
if (!$settingsState->open()) {
throw new RuntimeException('Unable to lock settings for writing');
}
try {
$this->reloadModifiedSettings();
$this->writeSettings();
}
finally {
$settingsState->close();
}
}
/**
* Write the merged regular settings.
*/
private function writeSettings() {
if (isset($this->settings['grommunio']['v1'])) {
unset($this->settings['grommunio']['v1']['contexts']['mail']['outofoffice']);
}
// The picture goes to its own property, it must not reach the settings blob.
$thumbnailPhoto = $this->settings['grommunio']['v1']['main']['thumbnail_photo'] ?? null;
unset($this->settings['grommunio']['v1']['main']['thumbnail_photo']);
if ($thumbnailPhoto !== null) {
$photo = ProfilePicture::normalize($thumbnailPhoto);
if ($photo !== false) {
mapi_setprops($this->store, [PR_EMS_AB_THUMBNAIL_PHOTO => $photo]);
mapi_savechanges($this->store);
$GLOBALS['mapisession']->setUserImage("data:image/jpeg;base64," . base64_encode($photo));
}
}
// Filter out the unchanged default sysadmin settings
$settings = $this->filterOutSettings($this->settings, $this->getDefaultSysAdminSettings());
$settings = json_encode(['settings' => $settings]);
// Check if the settings have been changed.
if ($this->settings_string !== $settings) {
if (isset($this->settings['grommunio']['v1']['main']['language'])) {
mapi_setprops($this->store, [PR_EC_USER_LANGUAGE => $this->settings['grommunio']['v1']['main']['language']]);
}
try {
writeMapiPropStream($this->store, PR_EC_WEBACCESS_SETTINGS_JSON, $settings);
mapi_savechanges($this->store);
}
catch (Exception) {
return;
}
// Settings saved, update settings_string.
$this->settings_string = $settings;
$this->legacyRootMigrated = false;
}
$this->modified = [];
}
/**
* Save persistent settings to store.
*
* This function saves all persistent settings to the store's PR_EC_WEBAPP_PERSISTENT_SETTINGS_JSON property.
*/
public function savePersistentSettings() {
if (!$this->init) {
$this->Init();
}
if (!$this->persistentSettingsLoaded) {
$msg = "Settings::savePersistentSettings() skipped: the persistent settings of this store could not be read.";
error_log($msg);
Log::Write(LOGLEVEL_ERROR, $msg);
return;
}
if (empty($this->modifiedPersistent)) {
return;
}
$settingsState = State::forStore('settings-write');
if (!$settingsState->open()) {
throw new RuntimeException('Unable to lock persistent settings for writing');
}
try {
$this->reloadModifiedPersistentSettings();
$this->writePersistentSettings();
}
finally {
$settingsState->close();
}
}
/**
* Write the merged persistent settings.
*/
private function writePersistentSettings() {
$persistentSettings = json_encode(['settings' => $this->persistentSettings]);
// Check if the settings have been changed.
if ($this->persistentSettingsString !== $persistentSettings) {
writeMapiPropStream($this->store, PR_EC_WEBAPP_PERSISTENT_SETTINGS_JSON, $persistentSettings);
mapi_savechanges($this->store);
// Settings saved, update settings string.
$this->persistentSettingsString = $persistentSettings;
}
$this->modifiedPersistent = [];
}
/**
* Get session-wide settings.
*
* Returns one explicit setting in an associative array:
*
* 'lang' -> setting('grommunio/v1/main/language')
*
* @return array associative array with 'lang' entry
*/
public function getSessionSettings() {
$store = $GLOBALS['mapisession']->getDefaultMessageStore();
$storeProps = mapi_getprops($store, [PR_EC_USER_LANGUAGE]);
if (!empty($storeProps[PR_EC_USER_LANGUAGE])) {
$lang = $storeProps[PR_EC_USER_LANGUAGE];
}
else {
$lang = $this->get('grommunio/v1/main/language', LANG);
}
return [
'lang' => $lang,
];
}
}
@@ -0,0 +1,287 @@
<?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__ . '/class.statecleaner.php';
/**
* Secondary state handling.
*
* This class works exactly the same as standard PHP sessions files. We implement it here
* so we can have improved granularity and don't have to put everything into the session
* variables. Basically we have multiple session objects corresponding to multiple webclient
* objects on the client. This class also locks the session files (in the same way as standard
* PHP sessions), in order to serialize requests from the same client object.
*
* The main reason for creating this is to improve performance; normally PHP will lock the session
* file for as long as your PHP request is running. However, we want to do multiple PHP requests at
* once. For this reason, we only use the PHP session system for login information, and use this
* class for other state information. This means that we can set a message as 'read' at the same time
* as opening a dialog to view a message.
*
* Currently, there is one 'state' for each 'subsystem'. The 'subsystem' is simply a tag which is appended
* to the request URL when the client does an XML request. Each 'subsystem' has its own state file.
*
* Currently the subsystem is equal to the module ID. This means that if you have two requests from the same
* module, they will have to wait for each other. In practice this should hardly ever happen.
*
* It can also create global state that can be accessed by every PHP request.
*/
class State {
/**
* The file pointer of the state file.
*
* @var false|resource
*/
private $fp = false;
/**
* The base directory in which the state files are found.
*/
private $basedir;
/**
* The filename which is opened by this state file.
*/
private $filename;
/**
* Name of the subsystem, used in log messages.
*/
private $subsystem;
/**
* The directory in which the session files are created.
*/
private $sessiondir = "session";
/**
* The unserialized data as it has been read from the file.
*
* @var array<string, mixed>
*/
public $sessioncache = [];
/**
* The raw data as it has been read from the file.
*
* @var null|string
*/
public $contents;
/**
* @param string $subsystem Name of the subsystem
* @param null|string $owner File prefix, defaults to the session id
*/
public function __construct($subsystem, $owner = null) {
$this->basedir = TMP_PATH . DIRECTORY_SEPARATOR . $this->sessiondir;
$this->subsystem = $subsystem;
$this->filename = $this->basedir . DIRECTORY_SEPARATOR . ($owner ?? session_id()) . "." . $subsystem;
}
/**
* State shared by every session of the store owner.
*
* @param string $subsystem Name of the subsystem
*
* @return State
*/
public static function forStore($subsystem) {
return new self($subsystem, 'store_' . hash('sha256', $GLOBALS['mapisession']->getDefaultMessageStoreEntryId()));
}
/**
* Open the session file.
*
* The session file is opened and locked so that other processes cannot access the state information.
*
* @param int $retry Reopen attempts when clean() replaced the file while waiting for its lock
*
* @return bool true when the file is locked
*/
public function open($retry = 2) {
if ($this->fp === false) {
if (!is_dir($this->basedir)) {
if (!@mkdir($this->basedir, 0755, true /* recursive */) && !is_dir($this->basedir)) {
error_log('[STATE ERROR] State directory "' . $this->basedir . '" could not be created.');
return false;
}
}
$cleanupLock = StateCleaner::lock($this->basedir, LOCK_SH);
if ($cleanupLock === false) {
error_log('[STATE ERROR] State cleanup lock could not be acquired.');
return false;
}
$this->fp = @fopen($this->filename, "a+");
if ($this->fp === false) {
StateCleaner::unlock($cleanupLock);
error_log('[STATE ERROR] State file for "' . $this->subsystem . '" could not be opened.');
return false;
}
$this->sessioncache = [];
// Never wait for a busy state file while holding the cleanup lock
$locked = flock($this->fp, LOCK_EX | LOCK_NB);
StateCleaner::unlock($cleanupLock);
if (!$locked && !flock($this->fp, LOCK_EX)) {
fclose($this->fp);
$this->fp = false;
error_log('[STATE ERROR] State file for "' . $this->subsystem . '" could not be locked.');
return false;
}
if (!$locked && !$this->isLinked()) {
$this->close();
if ($retry <= 0) {
error_log('[STATE ERROR] State file for "' . $this->subsystem . '" was replaced while locking.');
return false;
}
return $this->open($retry - 1);
}
if (!@touch($this->filename)) {
error_log('[STATE ERROR] State file for "' . $this->subsystem . '" could not be timestamped.');
}
}
return true;
}
/**
* @return bool true when the locked handle still is the file at $this->filename
*/
private function isLinked() {
if (!is_resource($this->fp)) {
return false;
}
$handle = $this->fp;
clearstatcache(true, $this->filename);
$open = fstat($handle);
$disk = @stat($this->filename);
return $open !== false && $disk !== false && $open['ino'] === $disk['ino'] && $open['dev'] === $disk['dev'];
}
/**
* Read a setting from the state file.
*
* @param string $name Name of the setting to retrieve
*
* @return mixed Value of the state value, or null if not found
*/
public function read($name) {
if (!is_resource($this->fp)) {
dump('[STATE ERROR] State file "' . $this->filename . '" is not open. Open it before reading.');
return null;
}
$handle = $this->fp;
// If the file has already been read, we only have to access
// our cache to obtain the requested data.
if (empty($this->sessioncache)) {
rewind($handle);
$contents = stream_get_contents($handle);
$this->contents = $contents === false ? '' : $contents;
$this->sessioncache = $this->contents === '' ? [] : unserialize($this->contents);
if (!is_array($this->sessioncache)) {
$this->sessioncache = [];
}
}
if (isset($this->sessioncache[$name])) {
return $this->sessioncache[$name];
}
return null;
}
/**
* Write a setting to the state file.
*
* @param string $name Name of the setting to write
* @param mixed $object Value of the object to be written to the setting
* @param bool $flush false to prevent the changes written to disk
* This requires a call to flush() to write the changes to disk
*/
public function write($name, $object, $flush = true) {
if (is_resource($this->fp)) {
// If the file has already been read, then we don't
// need to read the entire file again.
if (empty($this->sessioncache)) {
$this->read($name);
}
$this->sessioncache[$name] = $object;
if ($flush === true) {
$this->flush();
}
}
else {
dump('[STATE ERROR] State file "' . $this->filename . '" is not open. Open it before writing.');
}
}
/**
* Flushes all changes to disk.
*
* This flushes all changes made to $this->sessioncache to disk.
*/
public function flush() {
if (!is_resource($this->fp)) {
dump('[STATE ERROR] State file "' . $this->filename . '" is not open. Open it before writing.');
return;
}
$handle = $this->fp;
if (!empty($this->sessioncache)) {
$contents = serialize($this->sessioncache);
if ($contents !== $this->contents) {
ftruncate($handle, 0);
fseek($handle, 0);
fwrite($handle, $contents);
$this->contents = $contents;
}
}
}
/**
* Close the state file.
*
* This closes and unlocks the state file so that other processes can access the state
*/
public function close() {
if (!is_resource($this->fp)) {
return;
}
$handle = $this->fp;
// release write lock -- fclose does this automatically
// but only in PHP <= 5.3.2
flock($handle, LOCK_UN);
fclose($handle);
$this->fp = false;
}
public function __destruct() {
$this->close();
}
/**
* Cleans all old state information in the session directory.
*
* @param int $maxLifeTime the maximum allowed age of files in seconds
*/
public function clean($maxLifeTime = STATE_FILE_MAX_LIFETIME) {
StateCleaner::clean($this->basedir, $maxLifeTime);
}
}
@@ -0,0 +1,142 @@
<?php
/*
* SPDX-FileCopyrightText: Copyright 2020 - 2026 grommunio GmbH
* SPDX-License-Identifier: AGPL-3.0-or-later
*/
/**
* Removes stale state files and guards the state directory with the cleanup lock.
*
* Opening a state file holds the cleanup lock shared, sweeping holds it exclusively.
*/
class StateCleaner {
/**
* Files without content only carry a lock and expire earlier.
*/
private const LOCK_FILE_MAX_LIFETIME = 3600;
/**
* @param string $basedir State directory
* @param int $operation LOCK_SH or LOCK_EX
*
* @return false|resource the locked handle
*/
public static function lock($basedir, $operation) {
$cleanupLock = @fopen($basedir . DIRECTORY_SEPARATOR . '.cleanup.lock', 'c');
if ($cleanupLock === false || !flock($cleanupLock, $operation)) {
if (is_resource($cleanupLock)) {
fclose($cleanupLock);
}
return false;
}
return $cleanupLock;
}
/**
* @param resource $cleanupLock handle returned by lock()
*/
public static function unlock($cleanupLock) {
flock($cleanupLock, LOCK_UN);
fclose($cleanupLock);
}
/**
* Cleans all old state information in the state directory.
*
* @param string $basedir State directory
* @param int $maxLifeTime the maximum allowed age of files in seconds
*/
public static function clean($basedir, $maxLifeTime) {
if (!is_dir($basedir)) {
return;
}
$stalePaths = self::findStale($basedir, $maxLifeTime);
if (empty($stalePaths)) {
return;
}
$cleanupLock = self::lock($basedir, LOCK_EX);
if ($cleanupLock === false) {
return;
}
foreach ($stalePaths as $path) {
self::remove($path, $maxLifeTime);
}
self::unlock($cleanupLock);
}
/**
* @param string $basedir State directory
* @param int $maxLifeTime the maximum allowed age of files in seconds
*
* @return string[]
*/
private static function findStale($basedir, $maxLifeTime) {
$directory = @opendir($basedir);
if ($directory === false) {
return [];
}
$stalePaths = [];
while (($file = readdir($directory)) !== false) {
if ($file === '.' || $file === '..' || $file === '.cleanup.lock') {
continue;
}
$path = $basedir . DIRECTORY_SEPARATOR . $file;
if (self::isStaleRegularFile(@lstat($path), $maxLifeTime)) {
$stalePaths[] = $path;
}
}
closedir($directory);
return $stalePaths;
}
/**
* Removes a state file unless it was used or locked since it was found.
*
* @param string $path State file
* @param int $maxLifeTime the maximum allowed age of files in seconds
*/
private static function remove($path, $maxLifeTime) {
if (!self::isStaleRegularFile(@lstat($path), $maxLifeTime)) {
return;
}
$handle = @fopen($path, 'r+');
if ($handle === false) {
return;
}
if (flock($handle, LOCK_EX | LOCK_NB)) {
clearstatcache(true, $path);
$fileInfo = @stat($path);
if ($fileInfo !== false && self::isStale($fileInfo, $maxLifeTime) && !@unlink($path) && file_exists($path)) {
error_log('[STATE ERROR] Stale state file "' . $path . '" could not be removed.');
}
flock($handle, LOCK_UN);
}
fclose($handle);
}
/**
* @param array|false $fileInfo lstat() result
* @param int $maxLifeTime the maximum allowed age of state files in seconds
*
* @return bool
*/
private static function isStaleRegularFile($fileInfo, $maxLifeTime) {
return $fileInfo !== false && ($fileInfo['mode'] & 0170000) === 0100000 && self::isStale($fileInfo, $maxLifeTime);
}
/**
* @param array $fileInfo stat() result of a regular file
* @param int $maxLifeTime the maximum allowed age of state files in seconds
*
* @return bool
*/
private static function isStale($fileInfo, $maxLifeTime) {
$lifeTime = $fileInfo['size'] === 0 ? min($maxLifeTime, self::LOCK_FILE_MAX_LIFETIME) : $maxLifeTime;
return $fileInfo['atime'] < time() - $lifeTime;
}
}
@@ -0,0 +1,433 @@
<?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__ . '/class.colors.php';
require_once __DIR__ . '/class.jsonthemestyles.php';
// The themes are moved to a different location when released
// so we will define these constants for their location
define('THEME_PATH_' . LOAD_SOURCE, 'client/grommunio/core/themes');
define('THEME_PATH_' . LOAD_DEBUG, 'client/themes');
define('THEME_PATH_' . LOAD_RELEASE, 'client/themes');
/**
* This class provides some functionality for theming grommunio Web.
*/
class Theming {
/**
* Built-in color themes that live in grommunio.css and have no directory.
*/
private const UNIFIED_THEMES = ['purple', 'orange', 'lime', 'magenta', 'highcontrast', 'blue', 'teal', 'indigo', 'red', 'green', 'amber', 'brown', 'cyan'];
/**
* A hash that is used to cache if a theme is a json theme.
*
* @var array<string, bool>
*/
private static $isJsonThemeCache = [];
/**
* A hash that is used to cache the properties of json themes.
*
* @var array
*/
private static $jsonThemePropsCache = [];
/**
* The title and favicon override of the requested host: false until
* looked up, then null or an array.
*
* @var null|array|false
*/
private static $brandCache = false;
/**
* Retrieves all installed json themes.
*
* @return array An array with the directory names of the json themes as keys and their display names
* as values
*/
public static function getJsonThemes() {
$themes = [];
$directoryIterator = new DirectoryIterator(BASE_PATH . PATH_PLUGIN_DIR);
foreach ($directoryIterator as $info) {
if ($info->isDot() || !$info->isDir()) {
continue;
}
if (!Theming::isJsonTheme($info->getFileName())) {
continue;
}
$themeProps = Theming::getJsonThemeProps($info->getFileName());
if (empty($themeProps)) {
continue;
}
$themes[$info->getFileName()] = $themeProps['display-name'] ?? $info->getFileName();
}
return $themes;
}
/**
* Returns the name of the active theme if one was found, and false otherwise.
* The active theme can be set by the admin in the config.php, or by
* the user in his settings.
*
* @return bool|string
*/
public static function getActiveTheme() {
$theme = false;
$themePath = BASE_PATH . constant('THEME_PATH_' . DEBUG_LOADER);
// First check if a theme was set by this user in his settings
if (WebAppAuthentication::isAuthenticated()) {
if (ENABLE_THEMES === false) {
$theme = THEME !== "" ? THEME : 'basic';
}
else {
$theme = $GLOBALS['settings']->get('grommunio/v1/main/active_theme');
}
// Migrate legacy "dark" theme users: the dark theme directory
// has been removed. Switch them to basic theme + dark mode.
if ($theme === 'dark') {
$darkMode = $GLOBALS['settings']->get('grommunio/v1/main/dark_mode');
if (empty($darkMode) || $darkMode === 'light') {
$GLOBALS['settings']->set('grommunio/v1/main/dark_mode', 'dark');
}
$GLOBALS['settings']->set('grommunio/v1/main/active_theme', 'basic');
$GLOBALS['settings']->saveSettings();
$theme = 'basic';
}
// If a theme was found, check if the theme is still installed
// Remember that 'basic' is not a real theme, but the name for the default look of grommunio Web
// Unified themes don't require directories, so we skip the directory check for them
if (
!empty($theme) && $theme !== 'basic' &&
!in_array($theme, self::UNIFIED_THEMES) &&
!is_dir($themePath . '/' . $theme) &&
!is_dir(BASE_PATH . PATH_PLUGIN_DIR . '/' . $theme)
) {
$theme = false;
}
}
// If a valid theme was not found in the settings of the user, let's see if a valid theme
// was defined by the admin.
if (!$theme && defined('THEME') && THEME) {
// Check if it's a unified theme or if the directory exists
if (in_array(THEME, self::UNIFIED_THEMES)) {
$theme = THEME;
}
else {
$theme = is_dir($themePath . '/' . THEME) || is_dir(BASE_PATH . PATH_PLUGIN_DIR . '/' . THEME) ? THEME : false;
}
}
if (Theming::isJsonTheme($theme) && !is_array(Theming::getJsonThemeProps($theme))) {
// Someone made an error, we cannot read this json theme
return false;
}
return $theme;
}
/**
* Returns the path to the favicon if included with the theme. If found the
* path to it will be returned. Otherwise false.
*
* @param string $theme the name of the theme for which the css will be returned.
* Note: This is the directory name of the theme plugin.
*
* @return false|string favicon path, or false when the theme has no favicon
*/
public static function getFavicon($theme) {
$themePath = constant('THEME_PATH_' . DEBUG_LOADER);
// First check if we can find a core theme with this name
// A theme package can replace its icon without a grommunio Web release, so the
// file's own mtime is the cache buster
if ($theme && is_dir(BASE_PATH . $themePath . '/' . $theme) && is_file(BASE_PATH . $themePath . '/' . $theme . '/favicon.ico')) {
return $themePath . '/' . $theme . '/favicon.ico?' . filemtime(BASE_PATH . $themePath . '/' . $theme . '/favicon.ico');
}
// If no core theme was found, let's try to find a theme plugin with this name
if ($theme && is_dir(BASE_PATH . PATH_PLUGIN_DIR . '/' . $theme) && is_file(BASE_PATH . PATH_PLUGIN_DIR . '/' . $theme . '/favicon.ico')) {
return PATH_PLUGIN_DIR . '/' . $theme . '/favicon.ico?' . filemtime(BASE_PATH . PATH_PLUGIN_DIR . '/' . $theme . '/favicon.ico');
}
return false;
}
/**
* Returns the host name of the request, lower-case and without the port.
*
* @return string empty when the header is missing or malformed
*/
public static function getRequestHost() {
$host = strtolower(trim((string) ($_SERVER['HTTP_HOST'] ?? '')));
$host = preg_replace('/:\d+$/', '', $host);
return preg_match('/^[a-z0-9.-]+$/', $host) ? $host : '';
}
/**
* Returns the title and favicon that apply to the requested host, or
* null when none is installed. Hosts are matched exactly, then by the
* longest "*.suffix" pattern, then by "*". The title is HTML-escaped,
* the favicon is a same-origin absolute path.
*
* @return null|array{title: string, favicon: string}
*/
public static function getBrand() {
if (self::$brandCache !== false) {
return self::$brandCache;
}
self::$brandCache = null;
$file = '/run/grommunio-brand/brand/brand.json';
if (!is_readable($file)) {
return null;
}
$data = json_decode((string) file_get_contents($file), true);
$hosts = is_array($data['hosts'] ?? null) ? $data['hosts'] : [];
$host = self::getRequestHost();
$entry = $host !== '' ? ($hosts[$host] ?? null) : null;
if (!is_array($entry)) {
$suffixLength = 0;
foreach ($hosts as $pattern => $values) {
$pattern = (string) $pattern;
if (!is_array($values) || !str_starts_with($pattern, '*.')) {
continue;
}
$suffix = substr($pattern, 1);
if (strlen($suffix) > $suffixLength && strlen($host) > strlen($suffix) && str_ends_with($host, $suffix)) {
$entry = $values;
$suffixLength = strlen($suffix);
}
}
}
if (!is_array($entry)) {
$entry = $hosts['*'] ?? null;
}
if (!is_array($entry)) {
return null;
}
$title = $entry['title'] ?? '';
$title = is_string($title) ? trim(preg_replace('/[\x00-\x1f\x7f]/', '', strip_tags($title))) : '';
$title = htmlspecialchars($title, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
$favicon = $entry['favicon'] ?? '';
if (!is_string($favicon) || !preg_match('#^/(?!/)[A-Za-z0-9._~/%-]+$#', $favicon)) {
$favicon = '';
}
if ($title === '' && $favicon === '') {
return null;
}
self::$brandCache = ['title' => $title, 'favicon' => $favicon];
return self::$brandCache;
}
/**
* Returns the CSS files provided by the theme.
*
* @param string $theme the name of the theme for which the css will be returned.
* Note: This is the directory name of the theme plugin.
*
* @return string[] paths relative to the application root
*/
public static function getCss($theme) {
$themePathCoreThemes = BASE_PATH . constant('THEME_PATH_' . DEBUG_LOADER);
$cssFiles = [];
if (in_array($theme, self::UNIFIED_THEMES)) {
return [];
}
// First check if this is a core theme, and if it isn't, check if it is a theme plugin
if ($theme && is_dir($themePathCoreThemes . '/' . $theme)) {
$themePath = $themePathCoreThemes . '/' . $theme;
}
elseif ($theme && is_dir(BASE_PATH . PATH_PLUGIN_DIR . '/' . $theme)) {
if (Theming::isJsonTheme($theme)) {
return [];
}
$themePath = BASE_PATH . PATH_PLUGIN_DIR . '/' . $theme;
}
// A theme does not have to bring style sheets - one which only replaces the
// favicon is enough - and the iterator below throws on a missing directory.
if (isset($themePath) && is_dir($themePath . '/css/')) {
// Use SPL iterators to recursively traverse the css directory and find all css files
$directoryIterator = new RecursiveDirectoryIterator($themePath . '/css/', FilesystemIterator::SKIP_DOTS);
$iterator = new RecursiveIteratorIterator($directoryIterator, RecursiveIteratorIterator::SELF_FIRST);
// Always rewind an iterator before using it!!! See https://bugs.php.net/bug.php?id=62914 (it might save you a couple of hours debugging)
$iterator->rewind();
while ($iterator->valid()) {
$file = $iterator->current();
$fileName = $file->getFilename();
if (!$file->isDir() && (strtolower($file->getExtension()) === 'css' || str_ends_with($fileName, '.css.php'))) {
$cssFiles[] = substr((string) $iterator->key(), strlen(BASE_PATH));
}
$iterator->next();
}
}
// Sort the array alphabetically before adding the css
sort($cssFiles);
return $cssFiles;
}
/**
* Returns the value that is assigned to a property by the active theme
* or null otherwise.
* Currently only implemented for JSON themes.
*
* @param mixed $propName
*
* @return mixed the configured value, or false when the theme or property is unavailable
*/
public static function getThemeProperty($propName) {
$theme = Theming::getActiveTheme();
if (!Theming::isJsonTheme($theme)) {
return false;
}
$props = Theming::getJsonThemeProps($theme);
if (!isset($props[$propName])) {
return false;
}
return $props[$propName];
}
/**
* Returns the color that the active theme has set for the primary color
* of the icons. Currently only supported for JSON themes.
* Note: Only SVG icons of an iconset that has defined the primary color
* can be 'recolored'.
*
* @return false|string primary icon color, or false when it is not configured
*/
public static function getPrimaryIconColor() {
$val = Theming::getThemeProperty('icons-primary-color');
return $val ?? false;
}
/**
* Returns the color that the active theme has set for the secondary color
* of the icons. Currently only supported for JSON themes.
* Note: Only SVG icons of an iconset that has defined the secondary color
* can be 'recolored'.
*
* @return false|string secondary icon color, or false when it is not configured
*/
public static function getSecondaryIconColor() {
$val = Theming::getThemeProperty('icons-secondary-color');
return $val ?? false;
}
/**
* Checks if a theme is a JSON theme. (Basically this means that it checks if a
* directory with the theme name exists and if that directory contains a file
* called theme.json).
*
* @param string $theme The name of the theme to check
*
* @return bool True if the theme is a json theme, false otherwise
*/
public static function isJsonTheme($theme) {
if (empty($theme)) {
return false;
}
if (!isset(Theming::$isJsonThemeCache[$theme])) {
$themePathCoreThemes = BASE_PATH . constant('THEME_PATH_' . DEBUG_LOADER);
// First check if this is a core theme, and if it isn't, check if it is a theme plugin
if (is_dir($themePathCoreThemes . '/' . $theme)) {
// We don't have core json themes, so return false
Theming::$isJsonThemeCache[$theme] = false;
}
elseif (is_dir(BASE_PATH . PATH_PLUGIN_DIR . '/' . $theme) && is_file(BASE_PATH . PATH_PLUGIN_DIR . '/' . $theme . '/theme.json')) {
Theming::$isJsonThemeCache[$theme] = true;
}
else {
Theming::$isJsonThemeCache[$theme] = false;
}
}
return Theming::$isJsonThemeCache[$theme];
}
/**
* Retrieves the properties set in the theme.json file of the theme.
*
* @param string $theme The theme for which the properties should be retrieved
*
* @return array|false the decoded properties, or false when the theme is not a JSON theme
*/
public static function getJsonThemeProps($theme) {
if (!Theming::isJsonTheme($theme)) {
return false;
}
// Check if we have the props in the cache before reading the file
if (!isset(Theming::$jsonThemePropsCache[$theme])) {
$json = file_get_contents(BASE_PATH . PATH_PLUGIN_DIR . '/' . $theme . '/theme.json');
$props = json_decode($json, true);
if (!is_array($props) || json_last_error() !== JSON_ERROR_NONE) {
$reason = json_last_error() === JSON_ERROR_NONE ? 'The root value must be an object.' : json_last_error_msg();
error_log("The theme '{$theme}' does not have a valid theme.json file. {$reason}");
$props = false;
}
Theming::$jsonThemePropsCache[$theme] = $props;
}
return Theming::$jsonThemePropsCache[$theme];
}
/**
* Retrieves the styles that should be added to the page for the json theme.
*
* @param string $theme The theme for which the properties should be retrieved
*
* @return string The styles (between <style> tags)
*/
public static function getStyles($theme) {
$styles = '';
if (!Theming::isJsonTheme($theme)) {
$css = Theming::getCss($theme);
foreach ($css as $file) {
$styles .= '<link rel="stylesheet" type="text/css" href="' . versionedUrl($file) . '" />' . "\n";
}
return $styles;
}
// Convert the json theme to css styles
$themeProps = Theming::getJsonThemeProps($theme);
if (!$themeProps) {
return $styles;
}
return JsonThemeStyles::render($theme, $themeProps);
}
}
@@ -0,0 +1,505 @@
<?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
*/
/**
* This class contains the functionality for the To-do list.
* Since there is only one To-do list this class will be a singleton.
*/
class TodoList {
/**
* The entryid of the Todo-list search folder. TodoList::getEntryId will retrieve it
* if it isn't yet.
*/
private static false|string $_entryId = false;
/**
* Returns the entryid of the To-do list search folder.
*
* @return false|string entry ID of the To-do list search folder, or false when unavailable
*/
public static function getEntryId(): false|string {
if (TodoList::$_entryId === false) {
TodoList::_retrieveEntryId();
}
return TodoList::$_entryId;
}
/**
* Retrieves the entryid of the To-do list from the property PR_ADDITIONAL_REN_ENTRYIDS_EX
* of the user store. Will create a new to-do search folder if it does not yet exist.
*
* @see https://msdn.microsoft.com/en-us/library/office/cc842311.aspx
*
* @return false|string The entryid of the Todo-list search folder, or false when unavailable
*/
private static function _retrieveEntryId(): false|string {
$userStore = $GLOBALS['mapisession']->getDefaultMessageStore();
$root = mapi_msgstore_openentry($userStore);
TodoList::$_entryId = self::normalizeEntryId(self::readEntryId($root));
if (TodoList::$_entryId === false) {
TodoList::createTodoSearchFolder();
}
return TodoList::$_entryId;
}
/**
* Read the stored To-do search folder entryid.
*
* @param mixed $root
*
* @return false|string stored entry ID, or false when none is present
*/
private static function readEntryId($root): false|string {
$rootProperties = mapi_getprops($root, [PR_ADDITIONAL_REN_ENTRYIDS_EX]);
$additionalRenEntryidsEx = $rootProperties[PR_ADDITIONAL_REN_ENTRYIDS_EX] ?? '';
$headerFormat = 'Sid/Ssize';
while (strlen((string) $additionalRenEntryidsEx) > 0) {
$header = unpack($headerFormat, substr((string) $additionalRenEntryidsEx, 0, 4));
$additionalRenEntryidsEx = substr((string) $additionalRenEntryidsEx, 4);
if ($header['id'] === PERSIST_SENTINEL) {
// We found the end block
break;
}
// We're only interested in the entryid of the to-do search folder
if ($header['id'] === RSF_PID_TODO_SEARCH) {
// Now read the PersistElementBlock
$dataHeader = unpack($headerFormat, substr($additionalRenEntryidsEx, 0, 4));
return substr($additionalRenEntryidsEx, 4, $dataHeader['size']);
}
$additionalRenEntryidsEx = substr($additionalRenEntryidsEx, $header['size']);
}
return false;
}
/**
* Accept only non-empty binary entry IDs for the static cache.
*
* @param mixed $entryId
*/
private static function normalizeEntryId($entryId): false|string {
return is_string($entryId) && $entryId !== '' ? $entryId : false;
}
/**
* Creates a search folder for the To-do list under the root folder of the store. Adds the entryid
* to the PR_ADDITIONAL_REN_ENTRYIDS_EX property of the root folder, and also stores it in TodoList::$_entryId.
*
* @param null|mixed $expectedEntryId
*
* @return false|string entry ID of the new search folder, or false when it cannot be created
*/
public static function createTodoSearchFolder($expectedEntryId = null): false|string {
$renState = State::forStore('additional-ren-entryids-write');
if (!$renState->open()) {
throw new RuntimeException('Unable to lock additional folder entryids');
}
try {
return self::createTodoSearchFolderLocked($expectedEntryId);
}
finally {
$renState->close();
}
}
/**
* Create the To-do search folder while the entryid property is locked.
*
* @param mixed $expectedEntryId
*
* @return false|string entry ID of the search folder, or false when it cannot be created
*/
private static function createTodoSearchFolderLocked($expectedEntryId): false|string {
$userStore = $GLOBALS['mapisession']->getDefaultMessageStore();
$root = mapi_msgstore_openentry($userStore);
$entryid = self::normalizeEntryId(self::readEntryId($root));
if ($entryid !== false && ($expectedEntryId === null || $entryid !== $expectedEntryId)) {
TodoList::$_entryId = $entryid;
return $entryid;
}
$props = mapi_getprops($userStore, [PR_IPM_SUBTREE_ENTRYID]);
$ipmSubTreeEntryId = $props[PR_IPM_SUBTREE_ENTRYID];
$entryid = false;
try {
if ($resource = mapi_folder_createfolder($root, 'To-do Search', '', OPEN_IF_EXISTS, FOLDER_SEARCH)) {
mapi_setprops($resource, [PR_CONTAINER_CLASS => 'IPF.Task']);
mapi_folder_setsearchcriteria($resource, TodoList::_createRestriction(), [$ipmSubTreeEntryId], RECURSIVE_SEARCH);
$props = mapi_getprops($resource, [PR_ENTRYID]);
$entryid = self::normalizeEntryId($props[PR_ENTRYID] ?? false);
}
}
catch (MAPIException $e) {
// don't propagate the event to higher level exception handlers
$e->setHandled();
}
if ($entryid === false) {
return false;
}
// Now add the entryid to the PR_ADDITIONAL_REN_ENTRYIDS_EX property of the store root
$rootProperties = mapi_getprops($root, [PR_ADDITIONAL_REN_ENTRYIDS_EX]);
$additionalRenEntryidsEx = $rootProperties[PR_ADDITIONAL_REN_ENTRYIDS_EX] ?? '';
$dataHeader = pack('SS', RSF_ELID_ENTRYID, strlen((string) $entryid));
$dataElement = $dataHeader . $entryid;
$blockHeader = pack('SS', RSF_PID_TODO_SEARCH, strlen($dataElement));
// We'll just put it at the beginning of the property, so we don't have to bother with
// the end block (PERSIST_SENTINEL)
$additionalRenEntryidsEx = $blockHeader . $dataElement . $additionalRenEntryidsEx;
try {
mapi_setprops($root, [PR_ADDITIONAL_REN_ENTRYIDS_EX => $additionalRenEntryidsEx]);
mapi_savechanges($root);
}
catch (MAPIException $e) {
// Entryid could not be saved, so don't use it.
$entryid = false;
// don't propagate the event to higher level exception handlers
$e->setHandled();
}
if ($entryid !== false) {
TodoList::$_entryId = $entryid;
}
return $entryid;
}
/**
* Retrieves the Todo search folder and creates it if not found.
*
* @param resource $store user's MAPI store
*
* @return null|false|resource MAPI search folder, false on an open failure, or null after an exception
*/
public static function getTodoSearchFolder($store) {
$entryid = self::getEntryId();
if ($entryid === false) {
return false;
}
try {
return mapi_msgstore_openentry($store, $entryid);
}
catch (MAPIException $e) {
$e->setHandled();
if ($e->getCode() === MAPI_E_NOT_FOUND || $e->getCode() === MAPI_E_INVALID_ENTRYID) {
// Entryid invalid or no not found
$entryid = self::createTodoSearchFolder($entryid);
if ($entryid !== false) {
return mapi_msgstore_openentry($store, $entryid);
}
}
// Something went wrong, inform the administrator
error_log(sprintf("Unable to open 'To-do Search' for user: %s", $GLOBALS["mapisession"]->getUserName()) . ": " . $e->getMessage());
return null;
}
}
/**
* Creates the restriction for the To-do list search folder for the currently logged in user. The
* restriction was 'copied' from Outlook to show exactly the same items in the To-do list.
*
* @return array The restriction for the To-do list search folder for the currently logged in user
*/
public static function _createRestriction() {
$userStore = $GLOBALS['mapisession']->getDefaultMessageStore();
// First get some entryids that we need for the restriction
$storeProperties = mapi_getprops($userStore, [PR_IPM_OUTBOX_ENTRYID, PR_IPM_WASTEBASKET_ENTRYID]);
$root = mapi_msgstore_openentry($userStore);
$rootProperties = mapi_getprops($root, [PR_IPM_DRAFTS_ENTRYID, PR_ADDITIONAL_REN_ENTRYIDS]);
$additionalRenEntryids = $rootProperties[PR_ADDITIONAL_REN_ENTRYIDS];
$entryIds = [
'deletedItems' => $storeProperties[PR_IPM_WASTEBASKET_ENTRYID],
'junk' => $additionalRenEntryids[4],
'drafts' => $rootProperties[PR_IPM_DRAFTS_ENTRYID],
'outbox' => $storeProperties[PR_IPM_OUTBOX_ENTRYID],
];
// Now get some task request properties that we need in the restriction
$properties = [
'taskstate' => "PT_LONG:PSETID_Task:0x8113",
'taskaccepted' => "PT_BOOLEAN:PSETID_Task:0x8108",
'taskstatus' => "PT_LONG:PSETID_Task:" . PidLidTaskStatus,
];
$propertyIds = getPropIdsFromStrings($userStore, $properties);
return [
RES_AND,
[
[
RES_AND,
[
[
RES_NOT,
[
[
RES_CONTENT,
[
FUZZYLEVEL => FL_PREFIX | FL_IGNORECASE,
ULPROPTAG => PR_MESSAGE_CLASS,
VALUE => "IPM.Appointment",
],
],
],
],
[
RES_NOT,
[
[
RES_CONTENT,
[
FUZZYLEVEL => FL_PREFIX | FL_IGNORECASE,
ULPROPTAG => PR_MESSAGE_CLASS,
VALUE => "IPM.Activity",
],
],
],
],
[
RES_NOT,
[
[
RES_CONTENT,
[
FUZZYLEVEL => FL_PREFIX | FL_IGNORECASE,
ULPROPTAG => PR_MESSAGE_CLASS,
VALUE => "IPM.StickyNote",
],
],
],
],
],
],
[
RES_AND,
[
[
RES_AND,
[
[
RES_PROPERTY,
[
RELOP => RELOP_NE,
ULPROPTAG => PR_PARENT_ENTRYID,
VALUE => $entryIds['deletedItems'],
],
],
[
RES_PROPERTY,
[
RELOP => RELOP_NE,
ULPROPTAG => PR_PARENT_ENTRYID,
VALUE => $entryIds['junk'],
],
],
[
RES_PROPERTY,
[
RELOP => RELOP_NE,
ULPROPTAG => PR_PARENT_ENTRYID,
VALUE => $entryIds['drafts'],
],
],
[
RES_PROPERTY,
[
RELOP => RELOP_NE,
ULPROPTAG => PR_PARENT_ENTRYID,
VALUE => $entryIds['outbox'],
],
],
],
],
[
RES_OR,
[
[
RES_OR,
[
[
RES_AND,
[
[
RES_OR,
[
[
RES_NOT,
[
[
RES_EXIST,
[
ULPROPTAG => PR_FOLLOWUP_ICON,
],
],
],
],
[
RES_PROPERTY,
[
RELOP => RELOP_EQ,
ULPROPTAG => PR_FOLLOWUP_ICON,
VALUE => 0,
],
],
],
],
[
RES_EXIST,
[
ULPROPTAG => PR_FLAG_STATUS,
],
],
[
RES_PROPERTY,
[
RELOP => RELOP_EQ,
ULPROPTAG => PR_FLAG_STATUS,
VALUE => 1,
],
],
],
],
[
RES_AND,
[
[
RES_PROPERTY,
[
RELOP => RELOP_EQ,
ULPROPTAG => $propertyIds['taskstatus'],
VALUE => olTaskComplete,
],
],
[
RES_EXIST,
[
ULPROPTAG => $propertyIds['taskstatus'],
],
],
],
],
],
],
[
RES_AND,
[
[
RES_EXIST,
[
ULPROPTAG => PR_TODO_ITEM_FLAGS,
],
],
[
RES_BITMASK,
[
ULPROPTAG => PR_TODO_ITEM_FLAGS,
ULTYPE => BMR_NEZ,
ULMASK => 1,
],
],
],
],
[
RES_AND,
[
[
RES_EXIST,
[
ULPROPTAG => PR_FOLLOWUP_ICON,
],
],
[
RES_PROPERTY,
[
RELOP => RELOP_GT,
ULPROPTAG => PR_FOLLOWUP_ICON,
VALUE => 0,
],
],
],
],
[
RES_AND,
[
[
RES_NOT,
[
[
RES_AND,
[
[
RES_PROPERTY,
[
RELOP => RELOP_NE,
ULPROPTAG => $propertyIds['taskaccepted'],
VALUE => true,
],
],
[
RES_PROPERTY,
[
RELOP => RELOP_EQ,
ULPROPTAG => $propertyIds['taskstate'],
VALUE => 2,
],
],
],
],
],
],
[
RES_OR,
[
[
RES_CONTENT,
[
FUZZYLEVEL => FL_PREFIX | FL_IGNORECASE,
ULPROPTAG => PR_MESSAGE_CLASS,
VALUE => "IPM.Task.",
],
],
[
RES_CONTENT,
[
FUZZYLEVEL => FL_FULLSTRING | FL_IGNORECASE,
ULPROPTAG => PR_MESSAGE_CLASS,
VALUE => "IPM.Task",
],
],
],
],
],
],
],
],
],
],
],
];
}
}
@@ -0,0 +1,577 @@
<?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 UMAPI_PATH . '/mapi.util.php';
require_once UMAPI_PATH . '/class.keycloak.php';
require_once BASE_PATH . 'server/includes/core/class.webappkeycloak.php';
require_once BASE_PATH . 'server/includes/core/class.encryptionstore.php';
require_once BASE_PATH . 'server/includes/core/class.webappsession.php';
require_once BASE_PATH . 'server/includes/core/class.mapisession.php';
require_once BASE_PATH . 'server/includes/core/class.browserfingerprint.php';
/*
* Class that handles authentication.
*
* @singleton
*/
class WebAppAuthentication {
/**
* @var null|self A reference to the only instance of this class
*/
private static $_instance;
/**
* @var bool|false True if the user is authenticated, false otherwise
*/
private static $_authenticated = false;
/**
* @var null|WebAppSession A reference to the php session object
*/
private static ?WebAppSession $_phpSession = null;
/**
* @var null|MAPISession A reference to the MAPISession object
*/
private static ?MAPISession $_mapiSession = null;
/**
* @var int code that reflects the latest error
*/
private static $_errorCode = NOERROR;
/**
* @var bool true if MAPI session saving support exists
*/
private static $_sessionSaveSupport = false;
/**
* Initialize and return the PHP and MAPI session helpers.
*
* @return array{0: WebAppSession, 1: MAPISession}
*/
private static function initializeSessions(): array {
$phpSession = WebAppAuthentication::$_phpSession;
if ($phpSession === null) {
$phpSession = WebAppSession::getInstance();
WebAppAuthentication::$_phpSession = $phpSession;
}
$mapiSession = WebAppAuthentication::$_mapiSession;
if ($mapiSession === null) {
$mapiSession = new MAPISession();
WebAppAuthentication::$_mapiSession = $mapiSession;
}
return [$phpSession, $mapiSession];
}
/**
* Returns the only instance of the WebAppAuthentication class.
* If it does not exist yet, it will create an instance, and
* also an MAPISession object, and it will start a php session
* by instantiating a WebAppSession.
*
* @return self
*/
public static function getInstance() {
if (is_null(WebAppAuthentication::$_instance)) {
WebAppAuthentication::initializeSessions();
// Instantiate this class
WebAppAuthentication::$_instance = new WebAppAuthentication();
// Check if MAPI Saving session support exists
WebAppAuthentication::$_sessionSaveSupport = function_exists('kc_session_save') && function_exists('kc_session_restore');
}
return WebAppAuthentication::$_instance;
}
/**
* Returns the error code of the last logon attempt.
*
* @return int
*/
public static function getErrorCode() {
return WebAppAuthentication::$_errorCode;
}
/**
* Returns an error message that corresponds to the error code of
* the last logon attempt.
*
* @return string
*/
public static function getErrorMessage() {
return match (WebAppAuthentication::getErrorCode()) {
NOERROR => '',
ecUnknownUser, MAPI_E_LOGON_FAILED, MAPI_E_UNCONFIGURED => _('Logon failed. Please verify your credentials and try again.'),
MAPI_E_NETWORK_ERROR => _('Cannot connect to Gromox.'),
MAPI_E_INVALID_WORKSTATION_ACCOUNT => _('Login did not work due to a duplicate session. The issue was automatically resolved, please log in again.'),
MAPI_E_END_OF_SESSION => '',
default => _('Unknown MAPI Error') . ': ' . get_mapi_error_name(WebAppAuthentication::getErrorCode()),
};
}
/**
* Returns the MAPISession instance.
*/
public static function getMAPISession(): MAPISession {
[, $mapiSession] = WebAppAuthentication::initializeSessions();
return $mapiSession;
}
/**
* Set the underlying MAPI session handle.
*
* @param false|resource $session the MAPI session resource to set, or false to clear it
*/
public static function setMAPISession($session) {
WebAppAuthentication::getMAPISession()->setSession($session);
}
/**
* Tries to authenticate the user. First it will check if the
* user is using the login-form. And finally if not of above
* methods apply, it will try to find credentials in the
* php session.
*/
public static function authenticate() {
if (!WebAppAuthentication::regenerate_access_token()) {
return;
}
if (isset($_GET['code']) && (!defined('DISABLE_KEYCLOAK') || !DISABLE_KEYCLOAK)) {
WebAppAuthentication::authenticateWithAccessToken($_GET['code'], $_GET['state'] ?? null);
}
elseif (WebAppAuthentication::isUsingLoginForm()) {
WebAppAuthentication::authenticateWithPostedCredentials();
}
// At last check if we have credentials in the session
// and if found, try to login with those
else {
WebAppAuthentication::_authenticateWithSession();
}
}
/**
* Checks if keycloak features are enabled and regenerates
* the access token before expiration.
*
* @return bool false when the request must stop and reauthenticate
*/
public static function regenerate_access_token() {
if (isset($_SESSION['_keycloak_auth'])) {
$_keycloak_auth = $_SESSION['_keycloak_auth'];
if (time() - $_keycloak_auth->get_last_refresh_time() > 280) {
if (!$_keycloak_auth->refresh_grant_req() && !$_keycloak_auth->validate_grant()) {
$reopenedSession = false;
$sessionActive = session_status() === PHP_SESSION_ACTIVE;
if (!$sessionActive) {
$reopenedSession = session_start();
$sessionActive = $reopenedSession;
}
$keycloak = null;
if ($sessionActive) {
$keycloak = $_keycloak_auth instanceof WebAppKeyCloak
? $_keycloak_auth
: WebAppKeyCloak::getInstance();
}
if ($keycloak !== null) {
header('Location:' . $keycloak->login_url($keycloak->redirect_url));
}
// Do not let a later authentication path reuse either the invalid
// Keycloak object or its encrypted access-token credentials. Keep
// the newly generated OAuth state in this same session.
unset($_SESSION['_keycloak_auth']);
$_SESSION[EncryptionStore::_SESSION_KEY] = [];
if ($reopenedSession) {
session_write_close();
}
WebAppAuthentication::$_errorCode = MAPI_E_END_OF_SESSION;
return false;
}
$token = $_keycloak_auth->access_token->get_payload();
$user = $_keycloak_auth->access_token->get_claims('email');
WebAppAuthentication::_storeCredentialsInSession($user, $token);
$_keycloak_auth->set_last_refresh_time(time());
// Persist the updated Keycloak auth to the session.
// After read_and_close the session is not active, so
// briefly reopen it for writing.
if (session_status() !== PHP_SESSION_ACTIVE) {
session_start();
}
$_SESSION['_keycloak_auth'] = $_keycloak_auth;
session_write_close();
}
}
return true;
}
/**
* Returns true if a user is authenticated, or false otherwise.
*
* @return bool
*/
public static function isAuthenticated() {
return WebAppAuthentication::$_authenticated;
}
/**
* Tries to logon to Gromox with the given username and password/token. Returns
* the error code that was given back.
*
* @param string $username The username
* @param string $pass The password/token
*
* @return int
*/
public static function login($username, $pass) {
// Release the PHP session file lock before any blocking MAPI
// calls so concurrent requests from the same session are not
// serialized behind this one. EncryptionStore re-opens the
// session briefly when it needs to read or write credentials.
if (session_status() === PHP_SESSION_ACTIVE) {
session_write_close();
}
$mapiSession = WebAppAuthentication::getMAPISession();
if (!WebAppAuthentication::_restoreMAPISession()) {
// TODO: move logon from MAPISession to here
WebAppAuthentication::$_errorCode = isset($_SESSION['_keycloak_auth']) ?
$mapiSession->logon_token($username, $pass) :
$mapiSession->logon($username, $pass, DEFAULT_SERVER);
// Include external login plugins to be loaded
if (file_exists(BASE_PATH . 'extlogin.php')) {
include BASE_PATH . 'extlogin.php';
}
if (WebAppAuthentication::$_errorCode === NOERROR) {
WebAppAuthentication::$_authenticated = true;
WebAppAuthentication::_storeMAPISession($mapiSession->getSession());
$tmp = explode('@', $username);
if (count($tmp) == 2) {
setcookie('domainname', $tmp[1], ['expires' => time() + 31536000, 'path' => '/', 'domain' => '', 'secure' => true, 'httponly' => true, 'samesite' => 'Lax']);
}
$wa_title = (string) $mapiSession->getFullName();
$companyname = (string) $mapiSession->getCompanyName();
if ($companyname !== '') {
$wa_title .= " ({$companyname})";
}
if ($wa_title !== '') {
setcookie('webapp_title', $wa_title, ['expires' => time() + 31536000, 'path' => '/', 'domain' => '', 'secure' => true, 'httponly' => true, 'samesite' => 'Lax']);
}
}
elseif (WebAppAuthentication::$_errorCode == MAPI_E_LOGON_FAILED || WebAppAuthentication::$_errorCode == MAPI_E_UNCONFIGURED) {
error_log('grommunio Web user: ' . $username . ': authentication failure at MAPI');
}
}
return WebAppAuthentication::$_errorCode;
}
/**
* Store a serialized MAPI Session, which can be used by _restoreMAPISession to re-create
* a MAPISession, which saves a login call.
*
* @param resource $session the MAPI session handle to serialize and save
*/
private static function _storeMAPISession($session) {
if (!WebAppAuthentication::$_sessionSaveSupport) {
return;
}
$encryptionStore = EncryptionStore::getInstance();
$data = '';
if (kc_session_save($session, $data) === NOERROR) {
$encryptionStore->add('savedsession', bin2hex((string) $data));
}
}
/**
* Restore a MAPISession from the serialized with kc_session_restore.
*
* @return bool true if session has been restored successfully
*/
private static function _restoreMAPISession() {
$encryptionStore = EncryptionStore::getInstance();
if (!WebAppAuthentication::$_sessionSaveSupport || $encryptionStore->get('savedsession') === null) {
return false;
}
if (kc_session_restore(hex2bin((string) $encryptionStore->get('savedsession')), $session) === NOERROR) {
WebAppAuthentication::$_errorCode = NOERROR;
WebAppAuthentication::$_authenticated = true;
WebAppAuthentication::setMAPISession($session);
return true;
}
return false;
}
/**
* Stores the given username and password in the session using the encryptionstore.
*
* @param string The username
* @param string The password
* @param mixed $username
* @param mixed $password
*/
private static function _storeCredentialsInSession($username, $password) {
$encryptionStore = EncryptionStore::getInstance();
$encryptionStore->add('username', $username);
$encryptionStore->add('password', $password);
}
/**
* Checks if a user tries to log in by submitting the login form.
*
* @return bool
*/
public static function isUsingLoginForm() {
// Login form is only found on index.php
// If we don't check it, then posting to grommunio.php would
// also make authenticating possible.
if (basename((string) $_SERVER['SCRIPT_NAME']) !== 'index.php') {
return false;
}
return isset($_POST) && isset($_POST['username'], $_POST['password']);
}
/**
* Tries to authenticate the user with credentials that were posted.
* Returns the error code from the logon attempt.
*
* @return int
*/
public static function authenticateWithPostedCredentials() {
$email = appendDefaultDomain($_POST['username']);
if (empty($email) || empty($_POST['password'])) {
WebAppAuthentication::$_errorCode = MAPI_E_LOGON_FAILED;
return WebAppAuthentication::getErrorCode();
}
// Check if a session is already running and if the credentials match
$encryptionStore = EncryptionStore::getInstance();
$username = $encryptionStore->get('username');
$password = $encryptionStore->get('password');
if (!is_null($username) && !is_null($password)) {
if ($username != $email || $password != $_POST['password']) {
WebAppAuthentication::$_errorCode = MAPI_E_INVALID_WORKSTATION_ACCOUNT;
[$phpSession] = WebAppAuthentication::initializeSessions();
$phpSession->destroy();
return WebAppAuthentication::getErrorCode();
}
}
else {
// If no session is currently running, then store a fingerprint of the requester
// in the session.
$_SESSION['fingerprint'] = BrowserFingerprint::getFingerprint();
}
// Give the session a new id
session_regenerate_id();
WebAppAuthentication::login($email, $_POST['password']);
// Store the credentials in the session if logging in was successful
if (WebAppAuthentication::$_errorCode === NOERROR) {
WebAppAuthentication::_storeCredentialsInSession($email, $_POST['password']);
return WebAppAuthentication::getErrorCode();
}
return WebAppAuthentication::getErrorCode();
}
/**
* Login with Oauth2.0 keycloak access token.
* User selects login with keycloak, then gets redirected to keycloak server.
* If login is successful, the user is redirected with code grant back to gromox server.
* gromox requests access token with the received grant.
* keycloak server verifies grant, and sends access token.
* access token is used to authenticate user.
*
* @param mixed $code authorization code
* @param mixed $state OAuth state returned by Keycloak
*/
public static function authenticateWithAccessToken($code, $state = null) {
$keycloak = WebAppKeyCloak::getInstance();
if (!is_null($keycloak)) {
if (is_string($code) && $keycloak->consumeState($state) &&
$keycloak->client_credential_grant_req($code) && $keycloak->validate_grant()) {
$keycloak->set_last_refresh_time(time());
$_SESSION['_keycloak_auth'] = $keycloak;
if (isset($_SESSION['_keycloak_auth'])) {
$email = appendDefaultDomain($_SESSION['_keycloak_auth']->access_token->get_claims('email'));
$token = $_SESSION['_keycloak_auth']->access_token->get_payload();
// Check if a session is already running and if the credentials match
$encryptionStore = EncryptionStore::getInstance();
$username = $encryptionStore->get('username');
$password = $encryptionStore->get('password');
if (!is_null($username) && !is_null($password)) {
if ($username != $email || $password != $token) {
WebAppAuthentication::$_errorCode = MAPI_E_INVALID_WORKSTATION_ACCOUNT;
[$phpSession] = WebAppAuthentication::initializeSessions();
$phpSession->destroy();
return WebAppAuthentication::getErrorCode();
}
}
else {
// If no session is currently running, then store a fingerprint of the requester
// in the session.
$_SESSION['fingerprint'] = BrowserFingerprint::getFingerprint();
}
// Give the session a new id
session_regenerate_id();
WebAppAuthentication::login($email, $token);
// Store the credentials in the session if logging in was successful
if (WebAppAuthentication::$_errorCode === NOERROR) {
WebAppAuthentication::_storeCredentialsInSession($email, $token);
return WebAppAuthentication::getErrorCode();
}
}
}
header('Location:' . $keycloak->login_url($keycloak->redirect_url));
}
return WebAppAuthentication::getErrorCode();
}
/**
* Logs the user in with a given username and token in $_POST and logs
* in with the special flag for token authentication enabled. If $new
* is true it's assumed that a session does not exists and there will
* be a new one generated and fingerprint stored in session which is
* later compared after logon. After successful logon the session is stored.
*
* @param bool $new true if user has no session yet
*
* @return int|void
*/
public static function authenticateWithToken($new = true) {
if (empty($_POST['token'])) {
WebAppAuthentication::$_errorCode = MAPI_E_LOGON_FAILED;
return WebAppAuthentication::getErrorCode();
}
if ($new) {
// If no session is currently running, then store a fingerprint of the requester
// in the session.
$_SESSION['fingerprint'] = BrowserFingerprint::getFingerprint();
// Give the session a new id
session_regenerate_id();
}
// Release the session lock before the blocking MAPI logon.
if (session_status() === PHP_SESSION_ACTIVE) {
session_write_close();
}
$mapiSession = WebAppAuthentication::getMAPISession();
WebAppAuthentication::$_errorCode = $mapiSession->logon(
$_POST['username'],
$_POST['token'],
DEFAULT_SERVER,
null,
null,
0
);
// Store the credentials in the session if logging in was successful
if (WebAppAuthentication::$_errorCode === NOERROR) {
WebAppAuthentication::_storeCredentialsInSession($_POST['username'], $_POST['token']);
WebAppAuthentication::_storeMAPISession($mapiSession->getSession());
}
return WebAppAuthentication::getErrorCode();
}
/**
* Tries to authenticate the user with credentials from the session. When credentials
* are found in the session it will return the error code from the logon attempt with
* those credentials, otherwise it will return void.
*
* Before trying to logon, it will compare the requesters fingerprint with the
* fingerprint stored in the session. If they are not the same, the session will be
* destroyed and the script will be killed.
*
* @return int|void
*/
private static function _authenticateWithSession() {
[$phpSession] = WebAppAuthentication::initializeSessions();
// Check if the session hasn't timed out
if ($phpSession->hasTimedOut()) {
// Using a MAPI error code here, while it is not really a MAPI session timeout
// However to the user this should make no difference, so the MAPI error will do.
WebAppAuthentication::$_errorCode = MAPI_E_END_OF_SESSION;
return WebAppAuthentication::getErrorCode();
}
// Now check if we stored credentials in the session (in the encryption store)
$encryptionStore = EncryptionStore::getInstance();
$username = $encryptionStore->get('username');
$password = $encryptionStore->get('password');
if (is_null($username) || is_null($password)) {
return;
}
// Check if the browser fingerprint is the same as that of the browser that was
// used to login in the first place.
if (!DISABLE_FINGERPRINT_CHECK && $_SESSION['fingerprint'] !== BrowserFingerprint::getFingerprint()) {
// Another browser presents this session cookie; end the session the way a
// timeout does, every entry point answers that with its login or 401 path
$phpSession->destroy();
WebAppAuthentication::$_errorCode = MAPI_E_END_OF_SESSION;
return WebAppAuthentication::getErrorCode();
}
// The helper strips every character that could inject another header.
/** @scrutinizer ignore-call */
header('X-grommunio-Authuser:' . removeHTTPControlCharacters($username));
return WebAppAuthentication::login($username, $password);
}
/**
* Returns the username that is stored in the session.
*
* @return string
*/
public static function getUserName() {
$encryptionStore = EncryptionStore::getInstance();
return $encryptionStore->get('username');
}
}
// Instantiate the class
WebAppAuthentication::getInstance();
@@ -0,0 +1,331 @@
<?php
/*
* SPDX-FileCopyrightText: Copyright 2020 - 2026 grommunio GmbH
* SPDX-License-Identifier: AGPL-3.0-or-later
*/
/**
* Webapp-specific security policy for the shared KeyCloak client.
*/
class WebAppKeyCloak extends KeyCloak {
private const MAX_PENDING_STATES = 8;
private const STATE_LIFETIME = 600;
private const STATE_SESSION_KEY = '_keycloak_oauth_states';
// checked in order; a nested path is only reached once its parent passed
private const TYPE_RULES = [
[['realm'], 'is_string', 'Invalid Keycloak configuration value'],
[['resource'], 'is_string', 'Invalid Keycloak configuration value'],
[['redirect-url'], 'is_string', 'Invalid Keycloak configuration value'],
[['realm-public-key'], 'is_string', 'Invalid Keycloak configuration value'],
[['secret'], 'is_string', 'Invalid Keycloak configuration value'],
[['public-client'], 'is_bool', 'Invalid Keycloak public-client setting'],
[['credentials'], 'is_array', 'Invalid Keycloak credentials'],
[['credentials', 'secret'], 'is_string', 'Invalid Keycloak credentials'],
];
/** @var null|self */
private static $instance;
/**
* Use a configured callback URL, or derive one without trusting Host and
* Request-URI headers supplied by the client.
*
* @param mixed $keycloakConfig decoded keycloak.json configuration
*/
public function __construct(mixed $keycloakConfig) {
if (is_string($keycloakConfig)) {
$keycloakConfig = json_decode($keycloakConfig, true);
}
if (!is_array($keycloakConfig)) {
$keycloakConfig = [];
}
foreach (self::TYPE_RULES as [$path, $isValid, $message]) {
$value = $keycloakConfig;
foreach ($path as $key) {
$value = $value[$key] ?? null;
}
if ($value !== null && !$isValid($value)) {
throw new InvalidArgumentException($message);
}
}
$authServerUrl = $keycloakConfig['auth-server-url'] ?? null;
if (!is_string($authServerUrl) || filter_var($authServerUrl, FILTER_VALIDATE_URL) === false) {
throw new InvalidArgumentException('Invalid Keycloak server URL');
}
$redirectUrl = self::callbackUrl($keycloakConfig);
if ($redirectUrl === null) {
throw new UnexpectedValueException('No valid Keycloak callback URL is configured');
}
// Older mapi-header releases access this optional key without a default.
if (($keycloakConfig['public-client'] ?? false) && !isset($keycloakConfig['realm-public-key'])) {
$keycloakConfig['realm-public-key'] = '';
}
parent::__construct($keycloakConfig);
$this->redirect_url = $redirectUrl;
}
/**
* Return the webapp Keycloak singleton configured by keycloak.json.
*/
public static function getInstance(): ?WebAppKeyCloak {
if (!defined('GROMOX_CONFIG_PATH')) {
define('GROMOX_CONFIG_PATH', '/etc/gromox/');
}
$configFile = GROMOX_CONFIG_PATH . 'keycloak.json';
if (self::$instance === null && is_file($configFile)) {
$config = json_decode((string) @file_get_contents($configFile), true);
if (!is_array($config)) {
error_log('Unable to load webapp Keycloak configuration');
return null;
}
try {
self::$instance = new self($config);
}
catch (InvalidArgumentException|UnexpectedValueException) {
error_log('Unable to load webapp Keycloak configuration');
return null;
}
}
return self::$instance;
}
/**
* Build an authorization URL and remember its one-time state value.
*
* The argument remains for compatibility with KeyCloak::login_url(); the
* validated callback established by the constructor is always used.
*
* @param string $redirectUrl ignored caller-supplied redirect URL
* @param bool $usePkce ignored parent-client compatibility option
*
* @return string authorization URL
*/
public function login_url($redirectUrl, $usePkce = false): string {
$state = bin2hex(random_bytes(32));
$this->storeState($state);
$params = [
'scope' => 'openid',
'client_id' => $this->client_id,
'state' => $state,
'redirect_uri' => $this->redirect_url,
'response_type' => 'code',
];
return $this->realm_url . '/protocol/openid-connect/auth?' . http_build_query($params, '', '&', PHP_QUERY_RFC3986);
}
/**
* Consume a current state value exactly once.
*
* @param mixed $state callback state parameter
*
* @return bool true when the state was generated by this session
*/
public function consumeState($state) {
$states = $this->pendingStates();
if (!is_string($state) || preg_match('/\A[a-f0-9]{64}\z/D', $state) !== 1) {
$this->saveStates($states);
return false;
}
$key = hash('sha256', $state);
if (!isset($states[$key])) {
$this->saveStates($states);
return false;
}
unset($states[$key]);
$this->saveStates($states);
return true;
}
/**
* Require the introspection endpoint to return the JSON boolean true.
*
* @param mixed $token access token
*/
protected function validate_token(mixed $token): bool {
if (!isset($token)) {
return false;
}
$headers = ['Content-Type: application/x-www-form-urlencoded'];
$params = ['token' => $token->get_payload()];
if ($this->is_public) {
$params['client_id'] = $this->client_id;
}
else {
$headers[] = 'Authorization: Basic ' . base64_encode($this->client_id . ':' . $this->secret);
}
$response = $this->http_curl_request(
'POST',
'/protocol/openid-connect/token/introspect',
$headers,
http_build_query($params)
);
if ($response['code'] < 200 || $response['code'] > 299) {
return false;
}
try {
$data = json_decode((string) $response['body'], true, 512, JSON_THROW_ON_ERROR);
}
catch (JsonException) {
return false;
}
return is_array($data) && !array_key_exists('error', $data) && ($data['active'] ?? null) === true;
}
/**
* Choose and normalize the OAuth callback URL.
*
* The callback is the deployment directory (https://host/web), which is the
* redirect URI the grommunio-auth client template registers; nginx sends the
* browser on to index.php. A fixed SERVER_NAME is preferred. The stock nginx
* configuration serves grommunio Web from a catch-all server block
* (server_name _;), so the Host header is used when SERVER_NAME is not a
* usable host name. Set redirect-url in keycloak.json to pin the callback.
*
* @param array $config keycloak.json configuration
*
* @return null|string
*/
private static function callbackUrl($config) {
if (isset($config['redirect-url'])) {
return self::normalizeCallbackUrl($config['redirect-url']);
}
$scriptName = (string) ($_SERVER['SCRIPT_NAME'] ?? '/index.php');
$scriptName = preg_replace('/[\x00-\x1f\x7f]/', '', str_replace('\\', '/', $scriptName));
$directory = rtrim(dirname('/' . ltrim($scriptName, '/')), '/');
$serverName = (string) ($_SERVER['SERVER_NAME'] ?? '');
$host = (string) ($_SERVER['HTTP_HOST'] ?? '');
// SERVER_NAME never carries the port the browser used
if ($serverName !== '' && preg_match('~\A' . preg_quote($serverName, '~') . '(:\d{1,5})\z~i', $host, $match) === 1) {
$serverName .= $match[1];
}
foreach ([$serverName, $host] as $authority) {
// a host with an optional port, nothing that could smuggle in a path
if ($authority === '' || preg_match('~[^A-Za-z0-9.:\[\]-]~', $authority) === 1) {
continue;
}
$url = self::normalizeCallbackUrl('https://' . $authority . $directory);
if ($url !== null) {
return $url;
}
}
return null;
}
/**
* Normalize an absolute HTTPS callback URL.
*
* @param mixed $url
*
* @return null|string
*/
private static function normalizeCallbackUrl($url) {
if (!is_string($url) || $url === '' || strlen($url) > 4096 ||
preg_match('/[\x00-\x20\x5c\x7f]/', $url) === 1) {
return null;
}
$parts = @parse_url($url);
if ($parts === false || strtolower($parts['scheme'] ?? '') !== 'https' || empty($parts['host']) ||
isset($parts['user']) || isset($parts['pass']) || isset($parts['fragment'])) {
return null;
}
$host = trim(strtolower((string) $parts['host']), '[]');
if (filter_var($host, FILTER_VALIDATE_IP) === false) {
$host = rtrim($host, '.');
if ($host === '' || strlen($host) > 253 || preg_match('/\A[0-9.]+\z/D', $host) === 1 ||
preg_match('/\A(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)(?:\.(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?))*\z/D', $host) !== 1) {
return null;
}
}
$port = $parts['port'] ?? 443;
if (!is_int($port) || $port < 1 || $port > 65535) {
return null;
}
$authority = str_contains($host, ':') ? '[' . $host . ']' : $host;
if ($port !== 443) {
$authority .= ':' . $port;
}
// Keycloak matches the string exactly, so keep the path as given
$path = $parts['path'] ?? '';
$query = isset($parts['query']) ? '?' . $parts['query'] : '';
return 'https://' . $authority . $path . $query;
}
/**
* Store a state value and retain a small set for concurrent login tabs.
*
* @param string $state
*/
private function storeState($state) {
$states = $this->pendingStates();
$states[hash('sha256', $state)] = time() + self::STATE_LIFETIME;
asort($states, SORT_NUMERIC);
if (count($states) > self::MAX_PENDING_STATES) {
$states = array_slice($states, -self::MAX_PENDING_STATES, null, true);
}
$this->saveStates($states);
}
/**
* Return pending, unexpired state hashes from the session.
*
* @return array<string, int>
*/
private function pendingStates() {
$stored = $_SESSION[self::STATE_SESSION_KEY] ?? [];
if (!is_array($stored)) {
return [];
}
$states = [];
$now = time();
foreach ($stored as $hash => $expires) {
if (is_string($hash) && preg_match('/\A[a-f0-9]{64}\z/D', $hash) === 1 &&
is_int($expires) && $expires >= $now) {
$states[$hash] = $expires;
}
}
return $states;
}
/**
* Save pending states, removing the session key when none remain.
*
* @param array $states
*/
private function saveStates($states) {
if (empty($states)) {
unset($_SESSION[self::STATE_SESSION_KEY]);
}
else {
$_SESSION[self::STATE_SESSION_KEY] = $states;
}
}
}
@@ -0,0 +1,246 @@
<?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
*/
// Includes. Will probably already be included.
require_once BASE_PATH . 'config.php';
require_once BASE_PATH . 'defaults.php';
require_once BASE_PATH . 'server/includes/util.php';
require_once BASE_PATH . 'server/includes/exceptions/class.JSONException.php';
/**
* A class with helper functions for the PHP session.
*
* @singleton
*/
class WebAppSession {
// Holds the instance of this class
// Use public static method getInstance() to retrieve its value
private static $instance;
// Set to true when the session has timed out
// Use public method hasTimedOut() to retrieve its value
private $timeout = false;
/**
* Constructor.
*/
private function __construct() {
$secure = useSecureCookies();
if (defined('COOKIE_NAME')) {
// Create a named session (otherwise use the PHP default, normally PHPSESSID)
if ($secure) {
// Create a named session and set secure cookies params.
session_name('__Secure-' . COOKIE_NAME);
}
else {
session_name(COOKIE_NAME);
}
}
// Keycloak/OAuth requires SameSite=None so the session cookie
// survives the cross-site redirect back from the identity provider.
// Firefox strictly enforces SameSite=Lax on cross-site redirects
// and would otherwise drop the session cookie, causing a login loop.
$keycloakEnabled = !defined('DISABLE_KEYCLOAK') || !DISABLE_KEYCLOAK;
$samesite = $keycloakEnabled && $secure ? 'None' : 'Lax';
session_set_cookie_params([
'lifetime' => (int) ini_get('session.cookie_lifetime'),
'path' => ini_get('session.cookie_path') ?: '/',
'domain' => ini_get('session.cookie_domain') ?: '',
'secure' => $secure,
'httponly' => true,
'samesite' => $samesite,
]);
$this->start();
// For grommunio.php, release the session file lock early so parallel
// requests from the same browser session are not serialized behind it;
// a later write reopens it with updateSession(). Service requests
// (authenticate, token, fingerprint) write the session themselves, so
// they keep it open until the controller finishes.
$isGrommunioPhp = basename((string) $_SERVER['PHP_SELF']) === 'grommunio.php';
if (!$isGrommunioPhp) {
// We will only check for timeout in the grommunio.php page
$this->setStartTime();
}
else {
$this->checkForTimeout();
if (!isset($_GET['service'])) {
session_write_close();
}
}
}
/**
* returns the instance of this class. Creates one if it doesn't exist yet.
* To force this class to be used as singleton, the constructor is private
* and the single instance can be created/retrieved with this static method
* e.g.: $session = WebAppSession::createInstance().
*
* @return WebAppSession the only available instance of this class
*/
public static function getInstance() {
if (!isset(WebAppSession::$instance)) {
WebAppSession::$instance = new WebAppSession();
}
return WebAppSession::$instance;
}
/**
* The method getInstance() was first called createInstance(), so
* for backward compatibility we also define createInstance as an alias.
*/
public static function createInstance() {
return WebAppSession::getInstance();
}
/**
* Starts the session.
*/
public function start() {
session_start();
}
/**
* Closes the session.
*/
public function close() {
session_write_close();
}
/**
* Destroy the session.
*/
public function destroy() {
// Make sure the session is open
if (session_status() !== PHP_SESSION_ACTIVE) {
session_start();
}
// Destroy the session cookie
if (isset($_COOKIE[session_name()])) {
setcookie(session_name(), '', ['expires' => time() - 42000, 'path' => '/']);
}
// Destroy the session
$_SESSION = [];
session_destroy();
}
/**
* Sets the start time in the session to current timestamp.
* This is used to logout the user when CLIENT_TIMEOUT has
* been set in config.php.
*/
public function setStartTime() {
$_SESSION['starttime'] = time();
}
/**
* gets the start time from the session. This is used to logout the user
* when CLIENT_TIMEOUT has been set in config.php.
*
* @return false|int The starttime (timestamp) when set, false otherwise
*/
public function getStartTime() {
return $_SESSION['starttime'] ?? false;
}
/**
* Checks if the session should timeout and destroys the session if it should.
*/
private function checkForTimeout() {
if (!defined('CLIENT_TIMEOUT') || !CLIENT_TIMEOUT) {
// Timeout was not set in configuration, so do nothing
return;
}
if (array_key_exists('HTTP_CONTENT_TYPE', $_SERVER) && !str_contains((string) $_SERVER['HTTP_CONTENT_TYPE'], 'application/json')) {
return;
}
$starttime = $this->getStartTime();
// let's add 5 seconds to the CLIENT_TIMEOUT to handle possible latency
if ($starttime !== false && (time() - $starttime > CLIENT_TIMEOUT + 5)) {
$this->destroy();
$this->timeout = true;
}
else {
try {
// decode JSON data
$requestJsonString = readData();
$requestJson = json_decode_data($requestJsonString, true);
}
catch (JsonException $e) {
// Invalid json sent with the request
// Log the error and do nothing is best option
dump($e->getMessage());
return;
}
$isReminderlistRequest = $this->isReminderListRequest($requestJson);
$isDestroySessionRequest = $this->isDestroySessionRequest($requestJson);
if (!$isReminderlistRequest && !$isDestroySessionRequest) {
$this->setStartTime();
}
elseif ($isDestroySessionRequest) {
// sessiondestroy is sent because of timeout at client side
$this->timeout = true;
$this->destroy();
}
}
}
/**
* Checks if the current request is a destroysession request.
*
* @param array $requestJson The JSON that was sent as the current request
*
* @return bool
*/
private function isDestroySessionRequest($requestJson) {
$isDestroySession = false;
if (isset($requestJson, $requestJson['grommunio'])) {
if (isset($requestJson['grommunio']['hierarchymodule'])) {
foreach ($requestJson['grommunio']['hierarchymodule'] as $requestId => $action) {
if (isset($action, $action['destroysession'])) {
$isDestroySession = true;
}
}
}
}
return $isDestroySession;
}
/**
* Checks if the current request is a reminderlist request.
*
* @param array $requestJson The JSON that was sent as the current request
*
* @return bool
*/
private function isReminderListRequest($requestJson) {
return isset($requestJson) && isset($requestJson['grommunio'], $requestJson['grommunio']['reminderlistmodule']);
}
/**
* Returns true if the current session has timed out, false otherwise.
*
* @return bool
*/
public function hasTimedOut() {
return $this->timeout;
}
}
@@ -0,0 +1,50 @@
<?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
*/
/**
* This file contains only some constants used anywhere in grommunio Web.
*/
// These are the events, which a module can register for.
define("OBJECT_SAVE", 0x0001);
define("OBJECT_DELETE", 0x0002);
define("TABLE_SAVE", 0x0004);
define("TABLE_DELETE", 0x0008);
define("REQUEST_START", 0x0010);
define("REQUEST_END", 0x0020);
define("HIERARCHY_UPDATE", 0x0022);
// dummy entryid, used for the REQUEST events
define("REQUEST_ENTRYID", "dummy_value");
// dummy entryid, used for the Update addressbook
define("ADDRESSBOOK_ENTRYID", "dummy_addressbook_value");
// used in operations->getHierarchyList
define("HIERARCHY_GET_ALL", 0);
define("HIERARCHY_GET_DEFAULT", 1);
define("HIERARCHY_GET_ONE", 2);
// Distribution list constants moved to mapi-header-php/mapidefs.php
// Constants are used to indicate error type on client
define("ERROR_MAPI", 1);
define("ERROR_GROMMUNIO", 2);
define("ERROR_ZARAFA", ERROR_GROMMUNIO);
define("ERROR_GENERAL", 3);
define("LOGLEVEL_OFF", 0);
define("LOGLEVEL_FATAL", 1);
define("LOGLEVEL_ERROR", 2);
define("LOGLEVEL_WARN", 3);
define("LOGLEVEL_INFO", 4);
define("LOGLEVEL_DEBUG", 5);
// Future last time date for out of office "19-01-2038"
define("FUTURE_ENDDATE", 0x7FFFFFFF);