Initial upload to Gitea
This commit is contained in:
1 parent
78193254ad
commit
8478998cae
1485 files changed
+461025
-42348
No files matched your search
@@ -0,0 +1,135 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* SPDX-FileCopyrightText: Copyright 2020 - 2026 grommunio GmbH
|
||||
* SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
*/
|
||||
|
||||
require_once BASE_PATH . 'server/includes/core/class.privatefilecache.php';
|
||||
require_once BASE_PATH . 'server/includes/core/class.publichttpsresource.php';
|
||||
|
||||
/**
|
||||
* Serves the BIMI logo of a sender domain (RFC draft-brand-indicators-for-message-identification).
|
||||
* The logo is looked up once per domain and cached in TMP_PATH, so a mailbox full of mails from
|
||||
* the same sender costs one DNS query and one HTTPS fetch a week.
|
||||
*/
|
||||
class BimiLogo {
|
||||
public const TTL = 7 * 86400;
|
||||
public const NEGATIVE_TTL = 86400;
|
||||
public const MAX_SIZE = 65536;
|
||||
|
||||
public function serve($domain) {
|
||||
$dir = TMP_PATH . DIRECTORY_SEPARATOR . 'bimi';
|
||||
$base = $dir . DIRECTORY_SEPARATOR . hash('sha256', $domain);
|
||||
$logo = $base . '.svg';
|
||||
$miss = $base . '.miss';
|
||||
$cacheReady = PrivateFileCache::ensureDir($dir);
|
||||
|
||||
$cachedLogo = $cacheReady ? PrivateFileCache::read($logo, self::TTL, self::MAX_SIZE) : null;
|
||||
if ($cachedLogo !== null && $this->isLogo($cachedLogo)) {
|
||||
$this->output($cachedLogo);
|
||||
|
||||
return;
|
||||
}
|
||||
$cachedMiss = $cacheReady ? PrivateFileCache::read($miss, self::NEGATIVE_TTL, 0) : null;
|
||||
if ($cachedMiss !== null) {
|
||||
$this->notFound();
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$data = $this->fetch($domain);
|
||||
if ($data === null) {
|
||||
if ($cacheReady) {
|
||||
$this->writeCacheFile($dir, $miss, '');
|
||||
}
|
||||
$this->notFound();
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
if ($cacheReady) {
|
||||
$this->writeCacheFile($dir, $logo, $data);
|
||||
if (is_file($miss) && !@unlink($miss)) {
|
||||
error_log("[bimi] Could not remove negative cache entry: {$miss}");
|
||||
}
|
||||
}
|
||||
$this->output($data);
|
||||
}
|
||||
|
||||
private function writeCacheFile($dir, $file, $data) {
|
||||
return PrivateFileCache::write($dir, $file, $data, '.bimi-', '[bimi] Could not remove temporary cache file');
|
||||
}
|
||||
|
||||
private function fetch($domain) {
|
||||
$records = @dns_get_record('default._bimi.' . $domain, DNS_TXT);
|
||||
if (empty($records)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$url = null;
|
||||
foreach ($records as $record) {
|
||||
$txt = $record['txt'] ?? '';
|
||||
if (stripos($txt, 'v=BIMI1') !== 0) {
|
||||
continue;
|
||||
}
|
||||
foreach (explode(';', $txt) as $tag) {
|
||||
$tag = trim($tag);
|
||||
if (stripos($tag, 'l=') === 0) {
|
||||
$url = trim(substr($tag, 2));
|
||||
}
|
||||
}
|
||||
}
|
||||
if (empty($url) || !preg_match('#^https://#i', $url)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$data = PublicHttpsResource::fetch($url, self::MAX_SIZE, 2, [
|
||||
'Accept: image/svg+xml',
|
||||
'User-Agent: grommunio-web',
|
||||
]);
|
||||
|
||||
return $data !== null && $this->isLogo($data) ? $data : null;
|
||||
}
|
||||
|
||||
private function isLogo($data) {
|
||||
$previous = libxml_use_internal_errors(true);
|
||||
$doc = new DOMDocument();
|
||||
$ok = $doc->loadXML($data, LIBXML_NONET) && $doc->documentElement !== null &&
|
||||
strtolower($doc->documentElement->localName) === 'svg' &&
|
||||
$doc->getElementsByTagName('script')->length === 0 &&
|
||||
$doc->getElementsByTagName('foreignObject')->length === 0;
|
||||
libxml_clear_errors();
|
||||
libxml_use_internal_errors($previous);
|
||||
|
||||
return $ok;
|
||||
}
|
||||
|
||||
private function output($data) {
|
||||
header('Content-Type: image/svg+xml');
|
||||
header('Content-Length: ' . strlen($data));
|
||||
header('Content-Disposition: inline; filename="bimi.svg"');
|
||||
header('Cache-Control: private, max-age=86400');
|
||||
header('X-Content-Type-Options: nosniff');
|
||||
header("Content-Security-Policy: default-src 'none'; style-src 'unsafe-inline'");
|
||||
echo $data;
|
||||
}
|
||||
|
||||
private function notFound() {
|
||||
header('HTTP/1.1 404 Not Found');
|
||||
header('Cache-Control: private, max-age=3600');
|
||||
}
|
||||
}
|
||||
|
||||
if (!WebAppAuthentication::isAuthenticated()) {
|
||||
header('HTTP/1.1 401 Unauthorized');
|
||||
|
||||
exit;
|
||||
}
|
||||
$domain = strtolower(sanitizeGetValue('domain', '', '/^[a-z0-9.-]{3,253}$/i'));
|
||||
if (!ENABLE_BIMI || $domain === '' || str_contains($domain, '..')) {
|
||||
header('HTTP/1.1 404 Not Found');
|
||||
|
||||
exit;
|
||||
}
|
||||
(new BimiLogo())->serve($domain);
|
||||
@@ -0,0 +1,25 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* SPDX-FileCopyrightText: Copyright 2020 - 2026 grommunio GmbH
|
||||
* SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
*/
|
||||
|
||||
/*
|
||||
*
|
||||
* This script contains all includes that are necessary for grommunio.php
|
||||
*
|
||||
*/
|
||||
|
||||
// First include all generally necessary classes
|
||||
require_once 'server/includes/bootstrap.php';
|
||||
|
||||
// Following classes are needed for grommunio.php
|
||||
require_once BASE_PATH . 'server/includes/core/class.jsonrequest.php';
|
||||
require_once BASE_PATH . 'server/includes/notifiers/class.notifier.php';
|
||||
require_once BASE_PATH . 'server/includes/modules/class.module.php';
|
||||
require_once BASE_PATH . 'server/includes/modules/class.listmodule.php';
|
||||
require_once BASE_PATH . 'server/includes/modules/class.itemmodule.php';
|
||||
require_once BASE_PATH . 'server/includes/core/class.dispatcher.php';
|
||||
require_once BASE_PATH . 'server/includes/core/class.properties.php';
|
||||
require_once BASE_PATH . 'server/includes/core/class.bus.php';
|
||||
@@ -0,0 +1,117 @@
|
||||
<?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 script bootstraps the entry scripts (index.php and grommunio.php) by:
|
||||
* - including all classes that are used by both entry scripts
|
||||
* - check the correctness of the configuration file (if configured to do so)
|
||||
* - start buffering output (so we can add headers at any time)
|
||||
* - set the locale for character classification and conversion to en_US.UTF-8
|
||||
* - start a php session
|
||||
*
|
||||
* Note: Additional includes for grommunio.php are added by bootstrap.grommunio.php
|
||||
*
|
||||
*/
|
||||
|
||||
// It would be better if we could just put the few lines of code that are in init.php
|
||||
// in this script. Unfortunately that would break plugins that include init.php on their
|
||||
// own. (e.g. the spellchecker plugin)
|
||||
require_once __DIR__ . '/../../init.php';
|
||||
|
||||
// Polyfill for PHP 8.3's built-in #[\Override] attribute on PHP 8.1/8.2
|
||||
// Define only if it doesn't already exist (i.e., when running on < 8.3).
|
||||
if (!class_exists('Override')) {
|
||||
if (class_exists('Attribute')) {
|
||||
#[Attribute(Attribute::TARGET_METHOD)]
|
||||
class Override {}
|
||||
}
|
||||
}
|
||||
|
||||
// load configuration file
|
||||
if (!file_exists(BASE_PATH . 'config.php')) {
|
||||
exit("<strong>config.php is missing!</strong>");
|
||||
}
|
||||
require_once BASE_PATH . 'server/includes/core/constants.php';
|
||||
require_once BASE_PATH . 'config.php';
|
||||
require_once BASE_PATH . 'defaults.php';
|
||||
|
||||
// Reject foreign browser requests before session startup can refresh or destroy
|
||||
// state. Requests without Origin remain available to legacy/non-browser clients.
|
||||
if (isset($_SERVER['HTTP_ORIGIN'])) {
|
||||
require_once BASE_PATH . 'server/includes/core/class.response.php';
|
||||
if (!Response::isOriginAllowed()) {
|
||||
Response::forbidden();
|
||||
}
|
||||
}
|
||||
|
||||
// check if configuration is correct (only for the index.php)
|
||||
if (defined("CONFIG_CHECK") && basename((string) $_SERVER['SCRIPT_NAME']) === 'index.php') {
|
||||
require_once BASE_PATH . 'server/includes/core/class.configcheck.php';
|
||||
new ConfigCheck(CONFIG_CHECK);
|
||||
}
|
||||
|
||||
// Include the files
|
||||
require_once UMAPI_PATH . '/mapi.util.php';
|
||||
require_once UMAPI_PATH . '/mapidefs.php';
|
||||
require_once UMAPI_PATH . '/mapitags.php';
|
||||
require_once UMAPI_PATH . '/mapiguid.php';
|
||||
require_once UMAPI_PATH . '/class.baseexception.php';
|
||||
require_once UMAPI_PATH . '/class.mapiexception.php';
|
||||
require_once UMAPI_PATH . '/class.recurrenceexception.php';
|
||||
|
||||
require_once BASE_PATH . 'server/includes/exceptions/class.GrommunioException.php';
|
||||
require_once BASE_PATH . 'server/includes/exceptions/class.GrommunioErrorException.php';
|
||||
require_once BASE_PATH . 'server/includes/core/class.webappsession.php';
|
||||
require_once UMAPI_PATH . '/class.baserecurrence.php';
|
||||
require_once UMAPI_PATH . '/class.recurrence.php';
|
||||
require_once UMAPI_PATH . '/class.meetingrequest.php';
|
||||
require_once UMAPI_PATH . '/class.taskrecurrence.php';
|
||||
require_once UMAPI_PATH . '/class.taskrequest.php';
|
||||
require_once UMAPI_PATH . '/class.timezoneutil.php';
|
||||
|
||||
require_once BASE_PATH . 'server/includes/util.php';
|
||||
require_once UMAPI_PATH . '/gettext.php';
|
||||
|
||||
require_once BASE_PATH . 'server/includes/core/class.conversion.php';
|
||||
require_once BASE_PATH . 'server/includes/core/class.mapisession.php';
|
||||
require_once BASE_PATH . 'server/includes/core/class.properties.php';
|
||||
require_once BASE_PATH . 'server/includes/core/class.operations.php';
|
||||
require_once BASE_PATH . 'server/includes/core/class.entryid.php';
|
||||
|
||||
require_once BASE_PATH . 'server/includes/core/class.settings.php';
|
||||
require_once BASE_PATH . 'server/includes/core/class.language.php';
|
||||
|
||||
require_once BASE_PATH . 'server/includes/core/class.state.php';
|
||||
require_once BASE_PATH . 'server/includes/core/class.attachmentstate.php';
|
||||
|
||||
require_once BASE_PATH . 'server/includes/core/class.pluginmanager.php';
|
||||
require_once BASE_PATH . 'server/includes/core/class.plugin.php';
|
||||
|
||||
require_once BASE_PATH . 'server/includes/core/class.encryptionstore.php';
|
||||
require_once BASE_PATH . 'server/includes/core/class.webappauthentication.php';
|
||||
|
||||
require_once BASE_PATH . 'server/includes/core/class.todolist.php';
|
||||
|
||||
require_once UMAPI_PATH . '/class.freebusy.php';
|
||||
|
||||
require_once BASE_PATH . 'server/includes/core/class.theming.php';
|
||||
require_once BASE_PATH . 'server/includes/core/class.iconsets.php';
|
||||
|
||||
require_once BASE_PATH . 'server/includes/core/class.log.php';
|
||||
require_once BASE_PATH . 'server/includes/logger/class.baselogger.php';
|
||||
require_once BASE_PATH . 'server/includes/logger/class.filelog.php';
|
||||
|
||||
ob_start();
|
||||
$locale = new XpgLocale(LANG);
|
||||
$locale->codeset = "UTF-8";
|
||||
setlocale(LC_CTYPE, (string) $locale);
|
||||
|
||||
// Start a new session
|
||||
$webappSession = WebAppSession::getInstance();
|
||||
@@ -0,0 +1,226 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* SPDX-FileCopyrightText: Copyright 2020 - 2026 grommunio GmbH
|
||||
* SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
*/
|
||||
|
||||
/**
|
||||
* Orders JS source files by their @class, @extends and #dependsFile annotations.
|
||||
* Only used for LOAD_SOURCE mode.
|
||||
*/
|
||||
class JsLoadOrder {
|
||||
/**
|
||||
* @param array $files List of files that have to be included
|
||||
* @param array $coreFiles (Optional) List of folders that contain core files
|
||||
* @param array $libFiles (Optional) List of library files
|
||||
*
|
||||
* @return array List of files sorted in the correct loading sequence
|
||||
*/
|
||||
public static function sort($files, $coreFiles = [], $libFiles = []) {
|
||||
$libFileLookup = self::scanLibFiles($libFiles);
|
||||
$classFileLookup = [];
|
||||
$fileDataLookup = [];
|
||||
$fileDependencies = [];
|
||||
|
||||
foreach ($files as $filename) {
|
||||
$fileData = self::scanFile($filename, $coreFiles);
|
||||
$fileDataLookup[$filename] = $fileData;
|
||||
$fileDependencies[$filename] = [
|
||||
'depends' => [],
|
||||
'core' => $fileData['core'],
|
||||
];
|
||||
foreach ($fileData['class'] as $class) {
|
||||
$classFileLookup[$class] = $filename;
|
||||
}
|
||||
}
|
||||
|
||||
foreach ($fileDataLookup as $filename => $fileData) {
|
||||
$fileDependencies[$filename]['depends'] = array_merge(
|
||||
self::resolveExtends($filename, $fileData['extends'], $libFileLookup, $classFileLookup),
|
||||
self::resolveDependsFile($filename, $fileData['dependsFile'], $fileDataLookup)
|
||||
);
|
||||
}
|
||||
|
||||
return self::depthOrder($fileDependencies);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array $libFiles List of library files
|
||||
*
|
||||
* @return array Library filenames and the classes they define
|
||||
*/
|
||||
private static function scanLibFiles($libFiles) {
|
||||
$libFileLookup = [];
|
||||
foreach ($libFiles as $filename) {
|
||||
$content = file_get_contents(strtok($filename, '?'));
|
||||
$class = [];
|
||||
preg_match_all('(@class\W([^\n\r]*))', $content, $class);
|
||||
|
||||
$libFileLookup[$filename] = ['class' => $class[1]];
|
||||
foreach ($class[1] as $className) {
|
||||
$libFileLookup[$className] = true;
|
||||
}
|
||||
}
|
||||
|
||||
return $libFileLookup;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $filename File to scan
|
||||
* @param array $coreFiles List of folders that contain core files
|
||||
*
|
||||
* @return array The annotations of the file
|
||||
*/
|
||||
private static function scanFile($filename, $coreFiles) {
|
||||
$content = file_get_contents(strtok($filename, '?'));
|
||||
$extends = [];
|
||||
$dependsFile = [];
|
||||
$class = [];
|
||||
|
||||
preg_match_all('(@extends\W([^\n\r]*))', $content, $extends);
|
||||
preg_match_all('(@class\W([^\n\r]*))', $content, $class);
|
||||
preg_match_all('(#dependsFile\W([^\n\r\*]+))', $content, $dependsFile);
|
||||
|
||||
return [
|
||||
'class' => $class[1],
|
||||
'extends' => $extends[1],
|
||||
'dependsFile' => $dependsFile[1],
|
||||
'core' => str_contains($content, '#core') || self::inCoreFolder($filename, $coreFiles),
|
||||
];
|
||||
}
|
||||
|
||||
private static function inCoreFolder($filename, $coreFiles) {
|
||||
foreach ($coreFiles as $coreFile) {
|
||||
if (str_starts_with((string) $filename, (string) $coreFile)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param mixed $filename
|
||||
* @param mixed $extends
|
||||
* @param mixed $libFileLookup
|
||||
* @param mixed $classFileLookup
|
||||
*
|
||||
* @return array Files defining the Grommunio classes $filename extends
|
||||
*/
|
||||
private static function resolveExtends($filename, $extends, $libFileLookup, $classFileLookup) {
|
||||
$depends = [];
|
||||
foreach ($extends as $className) {
|
||||
if (!str_starts_with($className, 'Grommunio') || isset($libFileLookup[$className])) {
|
||||
continue;
|
||||
}
|
||||
if (!isset($classFileLookup[$className])) {
|
||||
trigger_error('Unable to find @extends dependency "' . $className . '" for file "' . $filename . '"');
|
||||
|
||||
continue;
|
||||
}
|
||||
if ($classFileLookup[$className] != $filename) {
|
||||
$depends[] = $classFileLookup[$className];
|
||||
}
|
||||
}
|
||||
|
||||
return $depends;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param mixed $filename
|
||||
* @param mixed $dependsFile
|
||||
* @param mixed $fileDataLookup
|
||||
*
|
||||
* @return array Files named by the #dependsFile annotations of $filename
|
||||
*/
|
||||
private static function resolveDependsFile($filename, $dependsFile, $fileDataLookup) {
|
||||
$depends = [];
|
||||
foreach ($dependsFile as $dependencyFilename) {
|
||||
if (!isset($fileDataLookup[$dependencyFilename])) {
|
||||
trigger_error('Unable to find file #dependsFile dependency "' . $dependencyFilename . '" for file "' . $filename . '"');
|
||||
|
||||
continue;
|
||||
}
|
||||
if ($dependencyFilename != $filename) {
|
||||
$depends[] = $dependencyFilename;
|
||||
}
|
||||
}
|
||||
|
||||
return $depends;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array $fileData List of files with dependency data
|
||||
*
|
||||
* @return array List of filenames ordered by dependency depth, core files first at each depth
|
||||
*/
|
||||
private static function depthOrder($fileData) {
|
||||
$fileDepths = self::depths($fileData);
|
||||
if (count($fileDepths) < count($fileData)) {
|
||||
$errorMsg = '[LOADER] Could not compute all dependencies. The following files cannot be resolved properly: ';
|
||||
$errorMsg .= implode(', ', array_diff(array_keys($fileData), array_keys($fileDepths)));
|
||||
trigger_error($errorMsg);
|
||||
}
|
||||
|
||||
$fileWeights = [];
|
||||
foreach ($fileData as $file => $dependencyData) {
|
||||
if (isset($fileDepths[$file])) {
|
||||
$weight = $fileDepths[$file] * 2 + ($dependencyData['core'] ? 0 : 1);
|
||||
}
|
||||
else {
|
||||
$weight = count($fileData);
|
||||
}
|
||||
$fileWeights[$weight][] = $file;
|
||||
}
|
||||
ksort($fileWeights);
|
||||
|
||||
return array_merge(...array_values($fileWeights));
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array $fileData List of files with dependency data
|
||||
*
|
||||
* @return array Dependency depth per file, missing for files in a cycle
|
||||
*/
|
||||
private static function depths($fileData) {
|
||||
$fileDepths = [];
|
||||
$changed = true;
|
||||
while ($changed && count($fileDepths) < count($fileData)) {
|
||||
$changed = false;
|
||||
foreach ($fileData as $file => $dependencyData) {
|
||||
if (isset($fileDepths[$file])) {
|
||||
continue;
|
||||
}
|
||||
$depth = self::depth($dependencyData['depends'], $fileDepths);
|
||||
if ($depth !== null) {
|
||||
$fileDepths[$file] = $depth;
|
||||
$changed = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return $fileDepths;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param mixed $dependencies
|
||||
* @param mixed $fileDepths
|
||||
*
|
||||
* @return null|int one more than the deepest dependency, null while one is unassigned
|
||||
*/
|
||||
private static function depth($dependencies, $fileDepths) {
|
||||
if (count($dependencies) === 0) {
|
||||
return 0;
|
||||
}
|
||||
$highestParentDepth = 0;
|
||||
foreach ($dependencies as $dependency) {
|
||||
if (!isset($fileDepths[$dependency])) {
|
||||
return null;
|
||||
}
|
||||
$highestParentDepth = max($highestParentDepth, $fileDepths[$dependency]);
|
||||
}
|
||||
|
||||
return $highestParentDepth + 1;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
<?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 handles the ping request that is sent by the front-end of grommunio Web
|
||||
* to check if a broken connection with the server can be re-established.
|
||||
*/
|
||||
|
||||
// Include the files that this script need
|
||||
require_once BASE_PATH . 'server/includes/core/class.webappauthentication.php';
|
||||
require_once UMAPI_PATH . '/mapi.util.php';
|
||||
|
||||
$pingTag = [
|
||||
'info' => [
|
||||
'hresult' => WebAppAuthentication::getErrorCode(),
|
||||
'hresult_name' => get_mapi_error_name(WebAppAuthentication::getErrorCode()),
|
||||
],
|
||||
];
|
||||
|
||||
switch (WebAppAuthentication::getErrorCode()) {
|
||||
// A network error indicates that the connection
|
||||
// to the server could not be established.
|
||||
case MAPI_E_NETWORK_ERROR:
|
||||
$pingTag['success'] = false;
|
||||
break;
|
||||
|
||||
// The following errors are specific to logging on,
|
||||
// it means the connection to the server did work,
|
||||
// but the user simply isn't logged in.
|
||||
case MAPI_E_PASSWORD_CHANGE_REQUIRED:
|
||||
case MAPI_E_PASSWORD_EXPIRED:
|
||||
case MAPI_E_INVALID_WORKSTATION_ACCOUNT:
|
||||
case MAPI_E_INVALID_ACCESS_TIME:
|
||||
case MAPI_E_ACCOUNT_DISABLED:
|
||||
// Error name says it all, connection exists, but cannot logon.
|
||||
case MAPI_E_LOGON_FAILED:
|
||||
// MAPI_E_UNCONFIGURED means we didn't try to connect to the server,
|
||||
// but the user is not logged in, so the state has changed for the user.
|
||||
case MAPI_E_UNCONFIGURED:
|
||||
// NOERROR means the logon was successful, and the connection to the
|
||||
// server is working as expected.
|
||||
case NOERROR:
|
||||
// All other errors are considered a 'success' for connecting to the
|
||||
// server and the 'active' property will indicate if the user still
|
||||
// has an active session to the server.
|
||||
default:
|
||||
$pingTag['success'] = true;
|
||||
$pingTag['active'] = WebAppAuthentication::isAuthenticated();
|
||||
break;
|
||||
}
|
||||
|
||||
// Write the JSON response
|
||||
echo json_encode($pingTag);
|
||||
@@ -0,0 +1,78 @@
|
||||
<?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 controller handles the following request:
|
||||
*
|
||||
* authenticate (login)
|
||||
*
|
||||
* Method: POST
|
||||
* GET Parameters:
|
||||
* service=authenticate
|
||||
* POST Parameters:
|
||||
* username=username
|
||||
* password=password
|
||||
* Response:
|
||||
* 200 Ok
|
||||
* JSON
|
||||
* {
|
||||
* 'authenticated': 'true',
|
||||
* 'username': '<username>'
|
||||
* }
|
||||
*
|
||||
* 401 Unauthorized
|
||||
* JSON
|
||||
* {
|
||||
* 'error': {
|
||||
* 'code': <nr>
|
||||
* 'message: '<error message>'
|
||||
* }
|
||||
* }
|
||||
*
|
||||
*/
|
||||
|
||||
require_once BASE_PATH . 'server/includes/core/class.response.php';
|
||||
require_once BASE_PATH . 'server/includes/core/class.webappauthentication.php';
|
||||
|
||||
// This request only works when POSTed
|
||||
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
|
||||
Response::wrongMethod();
|
||||
}
|
||||
|
||||
if (isset($_POST['username'], $_POST['password'])) {
|
||||
WebAppAuthentication::authenticateWithPostedCredentials();
|
||||
}
|
||||
|
||||
if (WebAppAuthentication::getErrorCode() !== NOERROR) {
|
||||
// If we have an error, we will communicate it in our response
|
||||
$response['error'] = [
|
||||
'code' => WebAppAuthentication::getErrorCode(),
|
||||
'hcode' => get_mapi_error_name(WebAppAuthentication::getErrorCode()),
|
||||
'message' => WebAppAuthentication::getErrorMessage(),
|
||||
];
|
||||
}
|
||||
else {
|
||||
// We successfully logged in, so we can communicate this in our response
|
||||
$response = [
|
||||
'authenticated' => WebAppAuthentication::isAuthenticated(),
|
||||
'user' => WebAppAuthentication::getUserName(),
|
||||
];
|
||||
}
|
||||
|
||||
// We will send a 401 header when the user is not authenticated
|
||||
// We also send it when there was an error when we tried to log in. This error
|
||||
// could be that another user is already logged in. (Not sure if 401 is logical then)
|
||||
if (!WebAppAuthentication::isAuthenticated() || WebAppAuthentication::getErrorCode() !== NOERROR) {
|
||||
header('HTTP/1.1 401 Unauthorized');
|
||||
}
|
||||
|
||||
// Send the response and stop the script
|
||||
echo json_encode($response);
|
||||
|
||||
exit;
|
||||
@@ -0,0 +1,45 @@
|
||||
<?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 controller handles the following request:
|
||||
*
|
||||
* authenticated
|
||||
*
|
||||
* Method: GET
|
||||
* GET Parameters:
|
||||
* service=authenticated
|
||||
* Response:
|
||||
* 200/Ok
|
||||
* JSON
|
||||
* {
|
||||
* 'authenticated': 'true' | 'false',
|
||||
* 'username': '<username>'
|
||||
* }
|
||||
*
|
||||
*
|
||||
*/
|
||||
|
||||
require_once BASE_PATH . 'server/includes/core/class.response.php';
|
||||
require_once BASE_PATH . 'server/includes/core/class.webappauthentication.php';
|
||||
|
||||
// This request only works with GET
|
||||
if ($_SERVER['REQUEST_METHOD'] !== 'GET') {
|
||||
Response::wrongMethod();
|
||||
}
|
||||
|
||||
// We will always respond with status 200 for this request.
|
||||
// The response will tell the requester if he is authenticated
|
||||
// or not.
|
||||
echo json_encode([
|
||||
'authenticated' => WebAppAuthentication::isAuthenticated(),
|
||||
'username' => WebAppAuthentication::getUserName(),
|
||||
]);
|
||||
|
||||
exit;
|
||||
@@ -0,0 +1,102 @@
|
||||
<?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 service should read the fingerprint that was sent by the frontend.
|
||||
* If the user is not yet logged in, the fingerprint will be stored in the
|
||||
* session. If the user is logged in and the fingerprint request is sent,
|
||||
* the fingerprint will be compared to the one stored in the session. If
|
||||
* the fingerprint do not match, the session will be destroyed.
|
||||
*
|
||||
* This controller handles the following request:
|
||||
*
|
||||
* fingerprint
|
||||
*
|
||||
* Method: POST
|
||||
* GET Parameters:
|
||||
* service=fingerprint
|
||||
* JSON body:
|
||||
* {"fingerprint":"<fingerprint>"}
|
||||
* Response:
|
||||
* 200 Ok
|
||||
*
|
||||
* 401 Unauthorized
|
||||
*
|
||||
*/
|
||||
|
||||
require_once BASE_PATH . 'server/includes/core/class.response.php';
|
||||
require_once BASE_PATH . 'server/includes/core/class.webappauthentication.php';
|
||||
require_once BASE_PATH . 'server/includes/core/class.webappsession.php';
|
||||
|
||||
// This request only works when POSTed
|
||||
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
|
||||
Response::wrongMethod();
|
||||
}
|
||||
|
||||
// Make sure the session is started
|
||||
$phpSession = WebAppSession::getInstance();
|
||||
|
||||
// If we get a keep-alive request from the fingerprint script
|
||||
// and the user is not authenticated (i.e. user is at login page)
|
||||
// we will respond with the php session expiration time
|
||||
// The fingerprint script will then send another keep-alive request
|
||||
// after half the expiration time has been passed.
|
||||
if (isset($_GET['type']) && $_GET['type'] === 'keepalive') {
|
||||
if (!WebAppAuthentication::isAuthenticated()) {
|
||||
echo ini_get('session.gc_maxlifetime');
|
||||
}
|
||||
|
||||
exit;
|
||||
}
|
||||
|
||||
// The fingerprint can destroy an authenticated session when it differs. Do
|
||||
// not accept CORS-simple form posts that another website can submit with the
|
||||
// victim's cookies.
|
||||
$contentType = strtolower(trim(explode(';', (string) ($_SERVER['CONTENT_TYPE'] ?? ''), 2)[0]));
|
||||
if ($contentType !== 'application/json') {
|
||||
http_response_code(415);
|
||||
|
||||
exit;
|
||||
}
|
||||
|
||||
$input = json_decode((string) file_get_contents('php://input'), true);
|
||||
if (!is_array($input) || !array_key_exists('fingerprint', $input)) {
|
||||
http_response_code(400);
|
||||
|
||||
exit;
|
||||
}
|
||||
$fingerprint = (string) $input['fingerprint'];
|
||||
|
||||
// Store the fingerprint in the session when the user is not yet
|
||||
// authenticated. (i.e. when the login page is loaded)
|
||||
if (!WebAppAuthentication::isAuthenticated()) {
|
||||
updateSession(function () use ($fingerprint) {
|
||||
$_SESSION['frontend-fingerprint'] = $fingerprint;
|
||||
});
|
||||
|
||||
exit;
|
||||
}
|
||||
|
||||
// If the frontend fingerprint was never stored (e.g. SSO/Keycloak where
|
||||
// the login page is skipped or the fingerprint request was cancelled
|
||||
// during redirect), store it now instead of killing the session.
|
||||
if (!isset($_SESSION['frontend-fingerprint'])) {
|
||||
updateSession(function () use ($fingerprint) {
|
||||
$_SESSION['frontend-fingerprint'] = $fingerprint;
|
||||
});
|
||||
}
|
||||
elseif (!DISABLE_FINGERPRINT_CHECK && $fingerprint !== $_SESSION['frontend-fingerprint']) {
|
||||
error_log('frontend-fingerprint did not match. Session terminated. ' . WebAppAuthentication::getUserName());
|
||||
$phpSession->destroy();
|
||||
Response::unAuthorized();
|
||||
}
|
||||
|
||||
// If we get here, then everything is fine. The user is authenticated and the
|
||||
// frontend fingerprints match. So we don't have to do anything anymore.
|
||||
exit;
|
||||
@@ -0,0 +1,43 @@
|
||||
<?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 controller handles the following request:
|
||||
*
|
||||
* authenticated
|
||||
*
|
||||
* Method: POST (GET is accepted only with same-origin browser metadata)
|
||||
* GET Parameters:
|
||||
* service=logout
|
||||
* Response:
|
||||
* 200/Ok
|
||||
* JSON
|
||||
* {
|
||||
* 'authenticated': 'false'
|
||||
* }
|
||||
*
|
||||
*
|
||||
*/
|
||||
|
||||
require_once BASE_PATH . 'server/includes/core/class.response.php';
|
||||
require_once BASE_PATH . 'server/includes/core/class.webappauthentication.php';
|
||||
|
||||
// Preserve the historical GET endpoint for same-origin callers only. A bare
|
||||
// cross-site navigation has no trustworthy initiator metadata and must fail.
|
||||
$requestMethod = strtoupper((string) ($_SERVER['REQUEST_METHOD'] ?? ''));
|
||||
if ($requestMethod !== 'POST' &&
|
||||
($requestMethod !== 'GET' || !Response::isSameOriginRequestSource())) {
|
||||
header('Allow: POST');
|
||||
Response::wrongMethod();
|
||||
}
|
||||
|
||||
// Destroy the session. This will effectively logout the user
|
||||
WebAppSession::getInstance()->destroy();
|
||||
|
||||
exit;
|
||||
@@ -0,0 +1,27 @@
|
||||
<?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 controller script handles REST requests. Every request needs its own controller script
|
||||
* to handle the request. This script will only check if a controller for the request
|
||||
* exists, and if so it will delegate control to that script. If a controller for the
|
||||
* request can not be found, this script will respond with
|
||||
* 404 Not Found
|
||||
*
|
||||
*/
|
||||
|
||||
require_once BASE_PATH . 'server/includes/core/class.response.php';
|
||||
|
||||
$service = $_GET['service'] ?? null;
|
||||
if (!is_string($service) || preg_match('/\A[a-z]+\z/D', $service) !== 1 ||
|
||||
!file_exists(BASE_PATH . 'server/includes/controllers/service.' . $service . '.php')) {
|
||||
Response::notFound();
|
||||
}
|
||||
|
||||
include BASE_PATH . 'server/includes/controllers/service.' . $service . '.php';
|
||||
@@ -0,0 +1,113 @@
|
||||
<?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 controller handles the following request:
|
||||
*
|
||||
* update token (login)
|
||||
*
|
||||
* Method: POST
|
||||
* GET Parameters:
|
||||
* service=authenticate
|
||||
* POST Parameters:
|
||||
* username=username
|
||||
* token=token
|
||||
* new=new
|
||||
* Response:
|
||||
* 200 Ok
|
||||
* JSON
|
||||
* {
|
||||
* 'authenticated': 'true',
|
||||
* 'username': '<username>'
|
||||
* }
|
||||
*
|
||||
* 401 Unauthorized
|
||||
* JSON
|
||||
* {
|
||||
* 'error': {
|
||||
* 'code': <nr>
|
||||
* 'message: '<error message>'
|
||||
* }
|
||||
* }
|
||||
*
|
||||
*/
|
||||
|
||||
require_once BASE_PATH . 'server/includes/core/class.response.php';
|
||||
require_once BASE_PATH . 'server/includes/core/class.webappauthentication.php';
|
||||
|
||||
/**
|
||||
* Decode an JWT access token which contains of a header, payload and
|
||||
* verify signature separated by a dot.
|
||||
*
|
||||
* @param string $accessToken the accessToken to extract the user entryid from
|
||||
*
|
||||
* @return string empty string when entryid is not found
|
||||
*/
|
||||
function extractUserEntryId($accessToken) {
|
||||
$parts = explode(".", $accessToken);
|
||||
if (count($parts) !== 3) {
|
||||
return '';
|
||||
}
|
||||
|
||||
$data = base64_decode($parts[1]);
|
||||
if (!$data) {
|
||||
return '';
|
||||
}
|
||||
|
||||
$json = json_decode($data, true);
|
||||
if (!$json) {
|
||||
return '';
|
||||
}
|
||||
|
||||
if (!isset($json['kc.identity']) || !isset($json['kc.identity']['kc.i.id'])) {
|
||||
return '';
|
||||
}
|
||||
|
||||
return $json['kc.identity']['kc.i.id'];
|
||||
}
|
||||
|
||||
// This request only works when POSTed
|
||||
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
|
||||
Response::wrongMethod();
|
||||
}
|
||||
|
||||
$new = isset($_POST['new']);
|
||||
|
||||
if (isset($_POST['token'])) {
|
||||
$_POST['username'] = extractUserEntryid($_POST['token']);
|
||||
WebAppAuthentication::authenticateWithToken($new);
|
||||
}
|
||||
|
||||
if (WebAppAuthentication::getErrorCode() !== NOERROR) {
|
||||
// If we have an error, we will communicate it in our response
|
||||
$response['error'] = [
|
||||
'code' => WebAppAuthentication::getErrorCode(),
|
||||
'hcode' => get_mapi_error_name(WebAppAuthentication::getErrorCode()),
|
||||
'message' => WebAppAuthentication::getErrorMessage(),
|
||||
];
|
||||
}
|
||||
else {
|
||||
// We successfully logged in, so we can communicate this in our response
|
||||
$response = [
|
||||
'authenticated' => WebAppAuthentication::isAuthenticated(),
|
||||
'user' => WebAppAuthentication::getUserName(),
|
||||
];
|
||||
}
|
||||
|
||||
// We will send a 401 header when the user is not authenticated
|
||||
// We also send it when there was an error when we tried to log in. This error
|
||||
// could be that another user is already logged in. (Not sure if 401 is logical then)
|
||||
if (!WebAppAuthentication::isAuthenticated() || WebAppAuthentication::getErrorCode() !== NOERROR) {
|
||||
header('HTTP/1.1 401 Unauthorized');
|
||||
}
|
||||
|
||||
// Send the response and stop the script
|
||||
echo json_encode($response);
|
||||
|
||||
exit;
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
+272
@@ -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
+64
@@ -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);
|
||||
@@ -0,0 +1,72 @@
|
||||
<?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
|
||||
*/
|
||||
|
||||
// required to handle php errors
|
||||
require_once __DIR__ . '/exceptions/class.GrommunioErrorException.php';
|
||||
require_once __DIR__ . '/download_base.php';
|
||||
|
||||
/**
|
||||
* DownloadAppointment.
|
||||
*
|
||||
* A class to manage downloading of appointment as a file,
|
||||
* it will generate the appointment as RFC2445-formatted ics stream.
|
||||
* It extends the DownloadBase class.
|
||||
*/
|
||||
class DownloadAppointment extends DownloadBase {
|
||||
/**
|
||||
* Function get appointment using respective mapi function.
|
||||
* It also sends the ics file to the client.
|
||||
*/
|
||||
public function downloadAppointmentAsFile() {
|
||||
if ($this->message && $this->store) {
|
||||
// Get addressbook for current session
|
||||
$addrBook = $GLOBALS['mapisession']->getAddressbook();
|
||||
|
||||
// get message properties.
|
||||
$messageProps = mapi_getprops($this->message, [PR_SUBJECT]);
|
||||
|
||||
// Read the appointment as RFC2445-formatted ics stream.
|
||||
$appointmentStream = mapi_mapitoical($GLOBALS['mapisession']->getSession(), $addrBook, $this->message, []);
|
||||
if ($appointmentStream === false) {
|
||||
throw new RuntimeException('Unable to convert appointment');
|
||||
}
|
||||
|
||||
$filename = (!empty($messageProps[PR_SUBJECT])) ? $messageProps[PR_SUBJECT] : _('Untitled');
|
||||
$filename .= '.ics';
|
||||
|
||||
$this->setNecessaryHeaders($filename, strlen($appointmentStream));
|
||||
|
||||
$split = str_split($appointmentStream, BLOCK_SIZE);
|
||||
foreach ($split as $s) {
|
||||
echo $s;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Generic function to check received data and download ics file.
|
||||
*/
|
||||
public function download() {
|
||||
$this->downloadAppointmentAsFile();
|
||||
}
|
||||
}
|
||||
|
||||
// create instance of class to download message as file
|
||||
$messageInstance = new DownloadAppointment();
|
||||
|
||||
try {
|
||||
// initialize variables
|
||||
$messageInstance->init($_GET);
|
||||
|
||||
// download message
|
||||
$messageInstance->download();
|
||||
}
|
||||
catch (Exception $e) {
|
||||
$messageInstance->handleSaveMessageException($e);
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,294 @@
|
||||
<?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
|
||||
*/
|
||||
|
||||
/**
|
||||
* DownloadBase.
|
||||
*
|
||||
* An abstract class which serve as base to manage downloading
|
||||
*/
|
||||
abstract class DownloadBase {
|
||||
/**
|
||||
* Resource of the MAPIStore which holds the message which we need to save as file.
|
||||
*/
|
||||
protected $store;
|
||||
|
||||
/**
|
||||
* Entryid of the MAPIStore which holds the message which we need to save as file.
|
||||
*/
|
||||
protected $storeId;
|
||||
|
||||
/**
|
||||
* Entryid of the MAPIMessage which we need to save as file.
|
||||
*/
|
||||
protected $entryId;
|
||||
|
||||
/**
|
||||
* Array of entryids of all the MAPIMessages which we need to include in ZIP.
|
||||
*/
|
||||
protected $entryIds;
|
||||
|
||||
/**
|
||||
* Resource of MAPIMessage which we need to save as file.
|
||||
*/
|
||||
protected $message;
|
||||
|
||||
/**
|
||||
* A boolean value, set to false by default, to define if all the attachments are requested to be downloaded in a zip or not.
|
||||
*/
|
||||
protected $allAsZip;
|
||||
|
||||
/**
|
||||
* Array to hold file names added into the ZIP which is used to avoid similar file names to be added in ZIP.
|
||||
*/
|
||||
protected $fileNameTracker;
|
||||
|
||||
/**
|
||||
* Constructor.
|
||||
*/
|
||||
public function __construct() {
|
||||
$this->storeId = false;
|
||||
$this->entryId = false;
|
||||
$this->allAsZip = false;
|
||||
$this->fileNameTracker = [];
|
||||
$this->entryIds = [];
|
||||
$this->message = false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Function will initialize data for this class object. it will also sanitize data
|
||||
* for possible XSS attack because data is received in $_GET.
|
||||
*
|
||||
* @param array $data parameters received with the request
|
||||
*/
|
||||
public function init($data) {
|
||||
if (isset($data['storeid'])) {
|
||||
$this->storeId = sanitizeValue($data['storeid'], '', ID_REGEX);
|
||||
}
|
||||
|
||||
if (isset($data['AllAsZip'])) {
|
||||
$this->allAsZip = sanitizeValue($data['AllAsZip'], '', STRING_REGEX);
|
||||
}
|
||||
|
||||
if ($this->storeId) {
|
||||
$this->store = $GLOBALS['mapisession']->openMessageStore(hex2bin((string) $this->storeId));
|
||||
}
|
||||
|
||||
if ($this->allAsZip) {
|
||||
if ($_POST && array_key_exists('entryids', $_POST) && isset($_POST['entryids'])) {
|
||||
$this->entryIds = $_POST['entryids'];
|
||||
}
|
||||
}
|
||||
else {
|
||||
if (isset($data['entryid'])) {
|
||||
$this->entryId = sanitizeValue($data['entryid'], '', ID_REGEX);
|
||||
$this->message = mapi_msgstore_openentry($this->store, hex2bin((string) $this->entryId));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Offers the functionality to postfixed the file name with number derived from
|
||||
* the appearance of other file with same name.
|
||||
* We need to keep track of the file names used so far to prevent duplicates.
|
||||
*
|
||||
* @param string $filename name of the file to be added in ZIP
|
||||
*
|
||||
* @return string $filename changed name of the file to be added in ZIP to avoid same file names
|
||||
*/
|
||||
public function handleDuplicateFileNames($filename) {
|
||||
// A local name is optional.
|
||||
if (!empty($filename)) {
|
||||
// Check and add if file name is not there in tracker array
|
||||
if (!array_key_exists($filename, $this->fileNameTracker)) {
|
||||
$this->fileNameTracker[$filename] = 0;
|
||||
}
|
||||
|
||||
// We have to make sure that there aren't two of the same file names.
|
||||
// Otherwise, one file will override the other and we will be missing the file.
|
||||
while ($this->fileNameTracker[$filename] > 0) {
|
||||
$fileNameInfo = pathinfo($filename);
|
||||
$intNext = $this->fileNameTracker[$filename]++;
|
||||
$filename = "{$fileNameInfo['filename']} ({$intNext}).{$fileNameInfo['extension']}";
|
||||
|
||||
// Check and add if newly prepared file name is not there in tracker array
|
||||
if (!array_key_exists($filename, $this->fileNameTracker)) {
|
||||
$this->fileNameTracker[$filename] = 0;
|
||||
}
|
||||
}
|
||||
|
||||
// Add to the count.
|
||||
++$this->fileNameTracker[$filename];
|
||||
}
|
||||
|
||||
return $filename;
|
||||
}
|
||||
|
||||
/**
|
||||
* Helper function to set necessary headers.
|
||||
*
|
||||
* @param string $filename proper name for the file to be downloaded
|
||||
* @param Number $contentLength total size of file content
|
||||
*/
|
||||
public function setNecessaryHeaders($filename, $contentLength) {
|
||||
// Set the headers
|
||||
header('Pragma: public');
|
||||
header('Expires: 0'); // set expiration time
|
||||
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
|
||||
header('Content-Transfer-Encoding: binary');
|
||||
|
||||
// Set Content Disposition header
|
||||
header('Content-Disposition: attachment; filename="' . addslashes(browserDependingHTTPHeaderEncode($filename)) . '"');
|
||||
// Set content type header
|
||||
header('Content-Type: application/octet-stream');
|
||||
|
||||
// Set the file length
|
||||
header('Content-Length: ' . $contentLength);
|
||||
}
|
||||
|
||||
/**
|
||||
* Function will return message type according to the MAPI message class
|
||||
* to display exception. so, user can easily understand the exception message.
|
||||
*
|
||||
* @param string $mapiMessageClass message type as defined in MAPI
|
||||
*
|
||||
* @return string $messageClass message type to prepare exception message
|
||||
*/
|
||||
public function getMessageType($mapiMessageClass) {
|
||||
// Convert message class into human readable format, so user can easily understand the display message.
|
||||
return match ($this->getTrimmedMessageClass($mapiMessageClass)) {
|
||||
'Appointment' => _('Appointment'),
|
||||
'StickyNote' => _('Sticky Note'),
|
||||
'Contact' => _('Contact'),
|
||||
'DistList' => _('Distribution list'),
|
||||
'Task' => _('Task'),
|
||||
'TaskRequest' => _('Task Request'),
|
||||
default => $mapiMessageClass,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns message-class removing technical prefix/postfix from
|
||||
* original/technical message class.
|
||||
*
|
||||
* @param string $mapiMessageClass message type as defined in MAPI
|
||||
*
|
||||
* @return string $messageClass message class without any prefix/postfix
|
||||
*/
|
||||
public function getTrimmedMessageClass($mapiMessageClass) {
|
||||
// Here, we have technical message class, so we need to remove technical prefix/postfix, if any.
|
||||
// Creates an array of strings by splitting the message class from dot(.)
|
||||
$explodedMessageClass = explode(".", $mapiMessageClass);
|
||||
$ipmIndex = array_search('IPM', $explodedMessageClass);
|
||||
|
||||
return $explodedMessageClass[$ipmIndex + 1];
|
||||
}
|
||||
|
||||
/**
|
||||
* Function will encode all the necessary information about the exception
|
||||
* into JSON format and send the response back to client.
|
||||
*
|
||||
* @param object $exception exception object
|
||||
*/
|
||||
public function handleSaveMessageException($exception) {
|
||||
$return = [];
|
||||
|
||||
// MAPI_E_NOT_FOUND exception contains generalize exception message.
|
||||
// Set proper exception message as display message should be user understandable.
|
||||
if ($exception->getCode() == MAPI_E_NOT_FOUND) {
|
||||
$exception->setDisplayMessage($this->notFoundMessage());
|
||||
}
|
||||
|
||||
// Set the headers
|
||||
header('Expires: 0'); // set expiration time
|
||||
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
|
||||
|
||||
// Set Content Disposition header
|
||||
header('Content-Disposition: inline');
|
||||
// Set content type header
|
||||
header('Content-Type: text/plain');
|
||||
|
||||
// prepare exception response according to exception class
|
||||
if ($exception instanceof MAPIException) {
|
||||
$return = [
|
||||
'success' => false,
|
||||
'grommunio' => [
|
||||
'error' => [
|
||||
'type' => ERROR_MAPI,
|
||||
'info' => [
|
||||
'hresult' => $exception->getCode(),
|
||||
'hresult_name' => get_mapi_error_name($exception->getCode()),
|
||||
'file' => $exception->getFileLine(),
|
||||
'display_message' => $exception->getDisplayMessage(),
|
||||
],
|
||||
],
|
||||
],
|
||||
];
|
||||
}
|
||||
elseif ($exception instanceof GrommunioException) {
|
||||
$return = [
|
||||
'success' => false,
|
||||
'grommunio' => [
|
||||
'error' => [
|
||||
'type' => ERROR_GROMMUNIO,
|
||||
'info' => [
|
||||
'file' => $exception->getFileLine(),
|
||||
'display_message' => $exception->getDisplayMessage(),
|
||||
'original_message' => $exception->getMessage(),
|
||||
],
|
||||
],
|
||||
],
|
||||
];
|
||||
}
|
||||
elseif ($exception instanceof BaseException) {
|
||||
$return = [
|
||||
'success' => false,
|
||||
'grommunio' => [
|
||||
'error' => [
|
||||
'type' => ERROR_GENERAL,
|
||||
'info' => [
|
||||
'file' => $exception->getFileLine(),
|
||||
'display_message' => $exception->getDisplayMessage(),
|
||||
'original_message' => $exception->getMessage(),
|
||||
],
|
||||
],
|
||||
],
|
||||
];
|
||||
}
|
||||
else {
|
||||
$return = [
|
||||
'success' => false,
|
||||
'grommunio' => [
|
||||
'error' => [
|
||||
'type' => ERROR_GENERAL,
|
||||
'info' => [
|
||||
'display_message' => _('Operation failed'),
|
||||
'original_message' => $exception->getMessage(),
|
||||
],
|
||||
],
|
||||
],
|
||||
];
|
||||
}
|
||||
echo json_encode($return);
|
||||
}
|
||||
|
||||
/**
|
||||
* Display message for a MAPI_E_NOT_FOUND download failure.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
protected function notFoundMessage() {
|
||||
return _('Could not find message, either it has been moved or deleted.');
|
||||
}
|
||||
|
||||
/**
|
||||
* Abstract Generic function to check received data and decide either the eml/vcf file or
|
||||
* ZIP file is requested to be downloaded.
|
||||
*/
|
||||
abstract protected function download();
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
<?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
|
||||
*/
|
||||
|
||||
// required to handle php errors
|
||||
require_once __DIR__ . '/exceptions/class.GrommunioErrorException.php';
|
||||
require_once __DIR__ . '/download_base.php';
|
||||
|
||||
/**
|
||||
* DownloadContact.
|
||||
*
|
||||
* A class to manage downloading of contact as a file,
|
||||
* it will generate the contact as RFC6350-formatted vCard stream.
|
||||
* It extends the DownloadBase class.
|
||||
*/
|
||||
class DownloadContact extends DownloadBase {
|
||||
/**
|
||||
* Function get contact-stream using respective mapi function.
|
||||
* It also sends the vcf file to the client.
|
||||
*/
|
||||
public function downloadContactAsFile() {
|
||||
if ($this->message && $this->store) {
|
||||
// Get addressbook for current session
|
||||
$addrBook = $GLOBALS['mapisession']->getAddressbook();
|
||||
|
||||
// get message properties.
|
||||
$messageProps = mapi_getprops($this->message, [PR_DISPLAY_NAME]);
|
||||
|
||||
// Read the contact as RFC6350-formatted vCard stream.
|
||||
$contactStream = mapi_mapitovcf($GLOBALS['mapisession']->getSession(), $addrBook, $this->message, []);
|
||||
if ($contactStream === false) {
|
||||
throw new RuntimeException('Unable to convert contact');
|
||||
}
|
||||
|
||||
$filename = (!empty($messageProps[PR_DISPLAY_NAME])) ? $messageProps[PR_DISPLAY_NAME] : _('Untitled');
|
||||
$filename .= '.vcf';
|
||||
|
||||
$this->setNecessaryHeaders($filename, strlen($contactStream));
|
||||
|
||||
$split = str_split($contactStream, BLOCK_SIZE);
|
||||
foreach ($split as $s) {
|
||||
echo $s;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Generic function to check received data and download vcf file.
|
||||
*/
|
||||
public function download() {
|
||||
// download contact as file
|
||||
$this->downloadContactAsFile();
|
||||
}
|
||||
}
|
||||
|
||||
// create instance of class to download message as file
|
||||
$messageInstance = new DownloadContact();
|
||||
|
||||
try {
|
||||
// initialize variables
|
||||
$messageInstance->init($_GET);
|
||||
|
||||
// download message
|
||||
$messageInstance->download();
|
||||
}
|
||||
catch (Exception $e) {
|
||||
$messageInstance->handleSaveMessageException($e);
|
||||
}
|
||||
@@ -0,0 +1,188 @@
|
||||
<?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
|
||||
*/
|
||||
|
||||
// required to handle php errors
|
||||
require_once __DIR__ . '/exceptions/class.GrommunioErrorException.php';
|
||||
require_once __DIR__ . '/download_base.php';
|
||||
|
||||
/**
|
||||
* DownloadMessage.
|
||||
*
|
||||
* A class to manage downloading of message as a file,
|
||||
* it will generate the message as RFC822-formatted e-mail stream.
|
||||
* It extends the DownloadBase class.
|
||||
*/
|
||||
class DownloadMessage extends DownloadBase {
|
||||
/**
|
||||
* Function get message-stream using respective mapi function.
|
||||
* It also sends the eml file to the client.
|
||||
*/
|
||||
public function downloadMessageAsFile() {
|
||||
if (!$this->message || !$this->store) {
|
||||
return;
|
||||
}
|
||||
// get message properties.
|
||||
$messageProps = mapi_getprops($this->message, [PR_SUBJECT, PR_MESSAGE_CLASS]);
|
||||
|
||||
$stream = $this->getEmlStream($messageProps);
|
||||
|
||||
$filename = (!empty($messageProps[PR_SUBJECT])) ? $messageProps[PR_SUBJECT] : _('Untitled');
|
||||
$filename .= '.eml';
|
||||
|
||||
// Set the file length
|
||||
$stat = mapi_stream_stat($stream);
|
||||
|
||||
$this->setNecessaryHeaders($filename, $stat['cb']);
|
||||
|
||||
// Read whole message and echo it.
|
||||
for ($i = 0; $i < $stat['cb']; $i += BLOCK_SIZE) {
|
||||
// Print stream
|
||||
$contents = mapi_stream_read($stream, BLOCK_SIZE);
|
||||
if ($contents === false) {
|
||||
error_log('Unable to read message stream');
|
||||
|
||||
throw new RuntimeException('Unable to read message stream');
|
||||
}
|
||||
echo $contents;
|
||||
|
||||
// Need to discard the buffer contents to prevent memory
|
||||
// exhaustion while echoing large content.
|
||||
ob_flush();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Function will create a ZIP archive and add eml files into the same.
|
||||
* It also configures necessary header information which required to send the ZIP file to client.
|
||||
* Send ZIP to the client if all the requested eml files included successfully into the same.
|
||||
*/
|
||||
public function downloadMessageAsZipFile() {
|
||||
if (!$this->store) {
|
||||
return;
|
||||
}
|
||||
// Generate random ZIP file name at default temporary path of PHP
|
||||
$randomZipName = tempnam(sys_get_temp_dir(), 'zip');
|
||||
|
||||
// Create an open zip archive.
|
||||
$zip = new ZipArchive();
|
||||
$result = $zip->open($randomZipName, ZipArchive::CREATE);
|
||||
|
||||
if ($result === true) {
|
||||
for ($index = 0, $count = count($this->entryIds); $index < $count; ++$index) {
|
||||
$this->message = mapi_msgstore_openentry($this->store, hex2bin((string) $this->entryIds[$index]));
|
||||
|
||||
// get message properties.
|
||||
$messageProps = mapi_getprops($this->message, [PR_SUBJECT, PR_MESSAGE_CLASS]);
|
||||
|
||||
$stream = $this->getEmlStream($messageProps);
|
||||
$stat = mapi_stream_stat($stream);
|
||||
|
||||
// Get the stream
|
||||
$datastring = '';
|
||||
for ($i = 0; $i < $stat['cb']; $i += BLOCK_SIZE) {
|
||||
$contents = mapi_stream_read($stream, BLOCK_SIZE);
|
||||
if ($contents === false) {
|
||||
$zip->close();
|
||||
unlink($randomZipName);
|
||||
error_log('Unable to read message stream');
|
||||
|
||||
throw new RuntimeException('Unable to read message stream');
|
||||
}
|
||||
$datastring .= $contents;
|
||||
// Need to discard the buffer contents to prevent memory
|
||||
// exhaustion.
|
||||
ob_flush();
|
||||
}
|
||||
|
||||
$filename = (!empty($messageProps[PR_SUBJECT])) ? $messageProps[PR_SUBJECT] : _('Untitled');
|
||||
$filename .= '.eml';
|
||||
|
||||
$filename = $this->handleDuplicateFileNames($filename);
|
||||
// Remove slashes to prevent unwanted directories to be created in the zip file.
|
||||
$filename = str_replace('\\', '_', $filename);
|
||||
$filename = str_replace('/', '_', $filename);
|
||||
|
||||
// Add file into zip by stream
|
||||
$zip->addFromString($filename, $datastring);
|
||||
}
|
||||
}
|
||||
else {
|
||||
$zip->close();
|
||||
// Remove the zip file to avoid unnecessary disk-space consumption
|
||||
unlink($randomZipName);
|
||||
|
||||
// Throw exception if ZIP is not created successfully
|
||||
throw new GrommunioException(_("ZIP is not created successfully"));
|
||||
}
|
||||
|
||||
$zip->close();
|
||||
|
||||
// Set the headers
|
||||
header('Pragma: public');
|
||||
header('Expires: 0'); // set expiration time
|
||||
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
|
||||
header('Content-Disposition: attachment; filename="' . addslashes(browserDependingHTTPHeaderEncode(_("Messages") . date(" d-m-Y") . ".zip")) . '"');
|
||||
header('Content-Transfer-Encoding: binary');
|
||||
header('Content-Type: application/zip');
|
||||
header('Content-Length: ' . filesize($randomZipName));
|
||||
|
||||
// Send the actual response as ZIP file
|
||||
readfile($randomZipName);
|
||||
|
||||
// Remove the zip file to avoid unnecessary disk-space consumption
|
||||
unlink($randomZipName);
|
||||
}
|
||||
|
||||
/**
|
||||
* Function will obtain stream from the message, For email messages it will open email as
|
||||
* inet object and get the stream content as eml format, when user has IMAP enabled.
|
||||
*
|
||||
* @param array $messageProps properties of this particular message
|
||||
*
|
||||
* @return resource EML stream obtained from the message
|
||||
*/
|
||||
public function getEmlStream($messageProps) {
|
||||
// Get addressbook for current session
|
||||
$addrBook = $GLOBALS['mapisession']->getAddressbook();
|
||||
|
||||
// Read the message as RFC822-formatted e-mail stream.
|
||||
$stream = mapi_inetmapi_imtoinet($GLOBALS['mapisession']->getSession(), $addrBook, $this->message, []);
|
||||
|
||||
return $stream;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check received data and decide either the eml file or
|
||||
* ZIP file is requested to be downloaded.
|
||||
*/
|
||||
public function download() {
|
||||
if ($this->allAsZip) {
|
||||
// download multiple eml messages in a ZIP file
|
||||
$this->downloadMessageAsZipFile();
|
||||
}
|
||||
else {
|
||||
// download message as file
|
||||
$this->downloadMessageAsFile();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// create instance of class to download message as file
|
||||
$messageInstance = new DownloadMessage();
|
||||
|
||||
try {
|
||||
// initialize variables
|
||||
$messageInstance->init($_GET);
|
||||
|
||||
// download message
|
||||
$messageInstance->download();
|
||||
}
|
||||
catch (Exception $e) {
|
||||
$messageInstance->handleSaveMessageException($e);
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
<?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 will be used for exceptions that are generated by class.bus.php.
|
||||
*/
|
||||
class BusException extends GrommunioException {}
|
||||
+13
@@ -0,0 +1,13 @@
|
||||
<?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 will be used for exceptions that are generated by class.dispatcher.php.
|
||||
*/
|
||||
class DispatcherException extends GrommunioException {}
|
||||
+55
@@ -0,0 +1,55 @@
|
||||
<?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
|
||||
*/
|
||||
|
||||
/**
|
||||
* Defines an exception class for all php Errors.
|
||||
* ErrorException properties and methods http://php.net/manual/en/class.errorexception.php
|
||||
* Exception properties and methods http://www.php.net/manual/en/class.exception.php.
|
||||
*/
|
||||
class GrommunioErrorException extends BaseException {
|
||||
/**
|
||||
* Constructs the Exception.
|
||||
*
|
||||
* @param string $errorMessage The exception message
|
||||
* @param int $code The Exception code
|
||||
* @param string $filename the filename where the exception is thrown
|
||||
* @param int $lineno the line number where the exception is thrown
|
||||
* @param mixed $errorContext
|
||||
* @param null|string $displayMessage the exception message to show at client side
|
||||
*/
|
||||
public function __construct($errorMessage, $code, $filename, $lineno, protected $errorContext = null, $displayMessage = null) {
|
||||
if (!$displayMessage) {
|
||||
$displayMessage = _('Action is not performed correctly.');
|
||||
}
|
||||
|
||||
parent::__construct($errorMessage, $code, null, $displayMessage);
|
||||
$this->setFile($filename);
|
||||
$this->setLineNo($lineno);
|
||||
}
|
||||
|
||||
/**
|
||||
* Function sets the filename where the exception was thrown.
|
||||
*
|
||||
* @param string $filename name of the file where the exception was thrown
|
||||
*/
|
||||
protected function setFile($filename = '') {
|
||||
$this->file = $filename;
|
||||
}
|
||||
|
||||
/**
|
||||
* Function sets the line where the exception was thrown.
|
||||
*
|
||||
* @param int $lineno line number where the exception was thrown
|
||||
*/
|
||||
protected function setLineNo($lineno = 0) {
|
||||
$this->line = $lineno;
|
||||
}
|
||||
}
|
||||
|
||||
class_alias(GrommunioErrorException::class, 'ZarafaErrorException');
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
<?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
|
||||
*/
|
||||
|
||||
/**
|
||||
* Defines a base exception class for custom grommunio generated exceptions, these exceptions
|
||||
* are generated and handled by our application only.
|
||||
*/
|
||||
class GrommunioException extends BaseException {}
|
||||
|
||||
class_alias(GrommunioException::class, 'ZarafaException');
|
||||
@@ -0,0 +1,64 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* SPDX-FileCopyrightText: Copyright 2020 - 2026 grommunio GmbH
|
||||
* SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
*/
|
||||
|
||||
require_once __DIR__ . '/class.GrommunioException.php';
|
||||
|
||||
/**
|
||||
* Builds the user-facing exception for a file that could not be imported into a folder.
|
||||
*/
|
||||
class ImportError {
|
||||
/**
|
||||
* @param Exception $e conversion failure
|
||||
* @param string $filename name of the imported file
|
||||
* @param resource $folder destination folder
|
||||
* @param callable $otherStore returns the delegate store owning the folder
|
||||
* @param string $emptyText message for a file without importable items
|
||||
*/
|
||||
public static function fromException($e, $filename, $folder, callable $otherStore, $emptyText): GrommunioException {
|
||||
$message = sprintf(_("Unable to import '%s' to '%s'. "), $filename, self::qualifiedFolderName($folder, $otherStore));
|
||||
if ($e->getCode() === MAPI_E_TABLE_EMPTY) {
|
||||
$message .= $emptyText;
|
||||
}
|
||||
elseif ($e->getCode() === MAPI_E_CORRUPT_DATA) {
|
||||
$message .= _("The file is corrupt.");
|
||||
}
|
||||
elseif ($e->getCode() === MAPI_E_INVALID_PARAMETER) {
|
||||
$message .= _("The file is invalid.");
|
||||
}
|
||||
else {
|
||||
$message = sprintf(_("Unable to import '%s'. "), $filename) . $e->getMessage();
|
||||
}
|
||||
|
||||
$error = new GrommunioException($message);
|
||||
$error->setTitle(_("Import error"));
|
||||
|
||||
return $error;
|
||||
}
|
||||
|
||||
/**
|
||||
* Folder name followed by the public store name or the delegate store owner.
|
||||
*
|
||||
* @param resource $folder
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
private static function qualifiedFolderName($folder, callable $otherStore) {
|
||||
$folderProps = mapi_getprops($folder, [PR_DISPLAY_NAME, PR_MDB_PROVIDER]);
|
||||
$name = $folderProps[PR_DISPLAY_NAME];
|
||||
if ($folderProps[PR_MDB_PROVIDER] === ZARAFA_STORE_PUBLIC_GUID) {
|
||||
$publicStore = $GLOBALS["mapisession"]->getPublicMessageStore();
|
||||
$publicStoreName = mapi_getprops($publicStore, [PR_DISPLAY_NAME]);
|
||||
$name .= " - " . $publicStoreName[PR_DISPLAY_NAME];
|
||||
}
|
||||
elseif ($folderProps[PR_MDB_PROVIDER] === ZARAFA_STORE_DELEGATE_GUID) {
|
||||
$ownerName = mapi_getprops($otherStore(), [PR_MAILBOX_OWNER_NAME]);
|
||||
$name .= " - " . $ownerName[PR_MAILBOX_OWNER_NAME];
|
||||
}
|
||||
|
||||
return $name;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
<?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.GrommunioException.php';
|
||||
|
||||
if (!class_exists('JSONException')) {
|
||||
/**
|
||||
* Class will be used for exceptions that are generated by json_decode_data
|
||||
* in server/util.php
|
||||
* getCode() method will return actual JSON error constant.
|
||||
*/
|
||||
class JSONException extends GrommunioException {}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
<?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 will be used for exceptions that are generated by search in list modules.
|
||||
*/
|
||||
class SearchException extends GrommunioException {}
|
||||
+13
@@ -0,0 +1,13 @@
|
||||
<?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 will be used for exceptions that are generated by class.setting.php.
|
||||
*/
|
||||
class SettingsException extends GrommunioException {}
|
||||
@@ -0,0 +1,36 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* SPDX-FileCopyrightText: Copyright 2026 grommunio GmbH
|
||||
* SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
*/
|
||||
|
||||
/*
|
||||
* Strings that reach the user through grommunio Web but live in a package it only
|
||||
* consumes. tools/update_translations scans this checkout, so without this list
|
||||
* they never enter the catalogues and stay English in every language.
|
||||
*
|
||||
* Nothing includes this file; it exists for xgettext. Keep it in step with the
|
||||
* sources named below.
|
||||
*/
|
||||
|
||||
return;
|
||||
// mapi-header-php, class.meetingrequest.php: subject prefix of a meeting response
|
||||
_('Tentatively accepted');
|
||||
_('New Time Proposed');
|
||||
|
||||
// mapi-header-php, class.taskrequest.php: subject prefix of a task response
|
||||
_("Task Accepted:");
|
||||
_("Task Declined:");
|
||||
_("Task Updated:");
|
||||
_("Task Completed:");
|
||||
_("Cannot assign tasks in public folders. Public folders are not mail-enabled and cannot send task assignment notifications.");
|
||||
|
||||
// mapi-header-php, class.mapiexception.php: what the user reads when a MAPI call fails
|
||||
_("Can not connect to Gromox.");
|
||||
_("Can not find object.");
|
||||
_("Can not open object with provided id.");
|
||||
_("Logon Failed. Please check your name/password.");
|
||||
_("Operation failed: Server does not have enough memory.");
|
||||
_("There are no recipients in the message.");
|
||||
_("You have insufficient privileges to open this object.");
|
||||
@@ -0,0 +1,28 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* SPDX-FileCopyrightText: Copyright 2020 - 2026 grommunio GmbH
|
||||
* SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
*/
|
||||
|
||||
/**
|
||||
* Check whether a value is a non-empty string of hexadecimal digits.
|
||||
*
|
||||
* @param mixed $value
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
function is_hex_string($value) {
|
||||
return is_string($value) && $value !== '' && ctype_xdigit($value);
|
||||
}
|
||||
|
||||
/**
|
||||
* Check whether a value is a hex-encoded binary such as an entryid.
|
||||
*
|
||||
* @param mixed $value
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
function is_hex_entryid($value) {
|
||||
return is_hex_string($value) && (strlen($value) % 2) === 0;
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
<?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.webappauthentication.php';
|
||||
|
||||
// Return a nice error when we are not authenticated
|
||||
if (!WebAppAuthentication::isAuthenticated()) {
|
||||
if (WebAppAuthentication::getErrorCode() === MAPI_E_NETWORK_ERROR) {
|
||||
// The user is not logged in because gromox could not be reached.
|
||||
// Return a HTTP 503 error so the client can act upon this event correctly.
|
||||
header('HTTP/1.1 503 Service unavailable');
|
||||
header("X-grommunio-Hresult: " . get_mapi_error_name(WebAppAuthentication::getErrorCode()));
|
||||
}
|
||||
else {
|
||||
// The session expired, or the user is otherwise not logged on.
|
||||
// Return a HTTP 401 error so the client can act upon this event correctly.
|
||||
header('HTTP/1.1 401 Unauthorized');
|
||||
header("X-grommunio-Hresult: " . get_mapi_error_name(WebAppAuthentication::getErrorCode()));
|
||||
}
|
||||
|
||||
exit;
|
||||
}
|
||||
|
||||
// index.php has the plugins loaded already for an authenticated user
|
||||
if (!isset($GLOBALS['PluginManager'])) {
|
||||
$disabledPlugins = getDisabledPluginsList();
|
||||
$GLOBALS['PluginManager'] = new PluginManager(ENABLE_PLUGINS);
|
||||
$GLOBALS['PluginManager']->detectPlugins($disabledPlugins);
|
||||
$GLOBALS['PluginManager']->initPlugins(DEBUG_LOADER);
|
||||
}
|
||||
|
||||
switch ($_GET['load']) {
|
||||
case "translations.js":
|
||||
$GLOBALS['PluginManager']->triggerHook("server.index.load.jstranslations.before");
|
||||
include BASE_PATH . 'server/includes/translations.js.php';
|
||||
$GLOBALS['PluginManager']->triggerHook("server.index.load.jstranslations.after");
|
||||
break;
|
||||
|
||||
case "custom":
|
||||
$name = sanitizeGetValue('name', '', STRING_REGEX);
|
||||
$GLOBALS['PluginManager']->triggerHook("server.index.load.custom", ['name' => $name]);
|
||||
break;
|
||||
|
||||
case "upload_attachment":
|
||||
$GLOBALS['PluginManager']->triggerHook("server.index.load.upload_attachment.before");
|
||||
include BASE_PATH . 'server/includes/upload_attachment.php';
|
||||
$GLOBALS['PluginManager']->triggerHook("server.index.load.upload_attachment.after");
|
||||
break;
|
||||
|
||||
case "download_attachment":
|
||||
$GLOBALS['PluginManager']->triggerHook("server.index.load.download_attachment.before");
|
||||
include BASE_PATH . 'server/includes/download_attachment.php';
|
||||
$GLOBALS['PluginManager']->triggerHook("server.index.load.download_attachment.after");
|
||||
break;
|
||||
|
||||
case "download_message":
|
||||
$GLOBALS['PluginManager']->triggerHook("server.index.load.download_message.before");
|
||||
include BASE_PATH . 'server/includes/download_message.php';
|
||||
$GLOBALS['PluginManager']->triggerHook("server.index.load.download_message.after");
|
||||
break;
|
||||
|
||||
case "download_contact":
|
||||
$GLOBALS['PluginManager']->triggerHook("server.index.load.download_contact.before");
|
||||
include BASE_PATH . 'server/includes/download_contact.php';
|
||||
$GLOBALS['PluginManager']->triggerHook("server.index.load.download_contact.after");
|
||||
break;
|
||||
|
||||
case "download_appointment":
|
||||
include BASE_PATH . 'server/includes/download_appointment.php';
|
||||
break;
|
||||
|
||||
case "bimi":
|
||||
include BASE_PATH . 'server/includes/bimi.php';
|
||||
break;
|
||||
|
||||
case "separate_window":
|
||||
$GLOBALS['PluginManager']->triggerHook("server.index.load.separate_window.before");
|
||||
include BASE_PATH . 'server/includes/templates/webclient_separatewindow.php';
|
||||
$GLOBALS['PluginManager']->triggerHook("server.index.load.separate_window.after");
|
||||
break;
|
||||
|
||||
default:
|
||||
// The session expired, or the user is otherwise not logged on.
|
||||
// Return a HTTP 401 error so the client can act upon this event correctly.
|
||||
header('HTTP/1.1 404 Not Found');
|
||||
break;
|
||||
}
|
||||
@@ -0,0 +1,298 @@
|
||||
<?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.jsloadorder.php';
|
||||
|
||||
/**
|
||||
* Manager for including JS and CSS files into the desired order.
|
||||
*/
|
||||
class FileLoader {
|
||||
private $extjsFiles;
|
||||
private $webappFiles;
|
||||
private $pluginFiles;
|
||||
private $remoteFiles;
|
||||
|
||||
/**
|
||||
* Obtain the list of Extjs & UX files.
|
||||
*
|
||||
* @param number $load the LOAD_RELEASE | LOAD_DEBUG | LOAD_SOURCE flag
|
||||
*
|
||||
* @return array The array of Javascript files
|
||||
*/
|
||||
public function getExtjsJavascriptFiles($load) {
|
||||
$jsLoadingSequence = [];
|
||||
|
||||
if ($load == LOAD_RELEASE) {
|
||||
$jsLoadingSequence[] = "client/extjs/ext-base-all.js";
|
||||
$jsLoadingSequence[] = "client/extjs-mod/extjs-mod.js";
|
||||
$jsLoadingSequence[] = "client/tinymce/tinymce.min.js";
|
||||
$jsLoadingSequence[] = "client/third-party/ux-thirdparty.js";
|
||||
$jsLoadingSequence[] = "client/dompurify/purify.js";
|
||||
}
|
||||
elseif ($load == LOAD_DEBUG) {
|
||||
$jsLoadingSequence[] = "client/extjs/ext-base-all-debug.js";
|
||||
$jsLoadingSequence[] = "client/extjs-mod/extjs-mod-debug.js";
|
||||
$jsLoadingSequence[] = "client/tinymce/tinymce.js";
|
||||
$jsLoadingSequence[] = "client/third-party/ux-thirdparty-debug.js";
|
||||
$jsLoadingSequence[] = "client/dompurify/purify.js";
|
||||
}
|
||||
else {
|
||||
$jsLoadingSequence[] = "client/extjs/ext-base-debug.js";
|
||||
$jsLoadingSequence[] = "client/extjs/ext-all-debug.js";
|
||||
$jsLoadingSequence[] = "client/extjs/ux/ux-all-debug.js";
|
||||
$jsLoadingSequence = array_merge(
|
||||
$jsLoadingSequence,
|
||||
JsLoadOrder::sort(
|
||||
$this->getListOfFiles('js', 'client/extjs-mod')
|
||||
)
|
||||
);
|
||||
$jsLoadingSequence[] = "client/tinymce/tinymce.js";
|
||||
$jsLoadingSequence[] = "client/dompurify/purify.js";
|
||||
$jsLoadingSequence = array_merge(
|
||||
$jsLoadingSequence,
|
||||
JsLoadOrder::sort(
|
||||
$this->getListOfFiles('js', 'client/third-party')
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
return $jsLoadingSequence;
|
||||
}
|
||||
|
||||
/**
|
||||
* Obtain the list of Extjs & UX CSS files.
|
||||
*
|
||||
* The stylesheet is shared by all load modes, but this method follows the
|
||||
* same mode-aware public contract as the other loader methods.
|
||||
*
|
||||
* @param int $load the LOAD_RELEASE | LOAD_DEBUG | LOAD_SOURCE flag
|
||||
*
|
||||
* @return array The array of CSS files
|
||||
*/
|
||||
public function getExtjsCSSFiles(/* @scrutinizer ignore-unused */ $load) {
|
||||
return ["client/extjs/resources/css/ext-all-ux.css"];
|
||||
}
|
||||
|
||||
/**
|
||||
* Obtain the list of grommunio Web files.
|
||||
*
|
||||
* @param number $load the LOAD_RELEASE | LOAD_DEBUG | LOAD_SOURCE flag
|
||||
* @param array $libFiles (optional) library files when $load = LOAD_SOURCE
|
||||
*
|
||||
* @return array The array of Javascript files
|
||||
*/
|
||||
public function getGrommunioJavascriptFiles($load, $libFiles = []) {
|
||||
if ($load == LOAD_RELEASE) {
|
||||
return ["client/grommunio.js"];
|
||||
}
|
||||
if ($load == LOAD_DEBUG) {
|
||||
return ["client/grommunio-debug.js"];
|
||||
}
|
||||
|
||||
return JsLoadOrder::sort(
|
||||
$this->getListOfFiles('js', 'client/grommunio'),
|
||||
['client/grommunio/core'],
|
||||
$libFiles
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Obtain the list of all Javascript files as registered by the plugins.
|
||||
*
|
||||
* @param number $load the LOAD_RELEASE | LOAD_DEBUG | LOAD_SOURCE flag
|
||||
* @param array $libFiles (optional) library files when $load = LOAD_SOURCE
|
||||
*
|
||||
* @return array The array of Javascript files
|
||||
*/
|
||||
public function getPluginJavascriptFiles($load, $libFiles = []) {
|
||||
if ($load === LOAD_SOURCE) {
|
||||
return JsLoadOrder::sort(
|
||||
$GLOBALS['PluginManager']->getClientFiles($load),
|
||||
[],
|
||||
$libFiles
|
||||
);
|
||||
}
|
||||
|
||||
return $GLOBALS['PluginManager']->getClientFiles($load);
|
||||
}
|
||||
|
||||
/**
|
||||
* Obtain the list of all CSS files as registered by the plugins.
|
||||
*
|
||||
* @param number $load the LOAD_RELEASE | LOAD_DEBUG | LOAD_SOURCE flag
|
||||
*
|
||||
* @return array The array of CSS files
|
||||
*/
|
||||
public function getPluginCSSFiles($load) {
|
||||
return $GLOBALS['PluginManager']->getResourceFiles($load);
|
||||
}
|
||||
|
||||
/**
|
||||
* Obtain the list of all Javascript files as provided by plugins using PluginManager#triggerHook
|
||||
* for the hook 'server.main.include.jsfiles'.
|
||||
*
|
||||
* @param number $load the LOAD_RELEASE | LOAD_DEBUG | LOAD_SOURCE flag
|
||||
*
|
||||
* @return array The array of Javascript files
|
||||
*/
|
||||
public function getRemoteJavascriptFiles($load) {
|
||||
$files = [];
|
||||
$GLOBALS['PluginManager']->triggerHook('server.main.include.jsfiles', ['load' => $load, 'files' => &$files]);
|
||||
|
||||
return $files;
|
||||
}
|
||||
|
||||
/**
|
||||
* Obtain the list of all CSS files as provided by plugins using PluginManager#triggerHook
|
||||
* for the hook 'server.main.include.cssfiles'.
|
||||
*
|
||||
* @param number $load the LOAD_RELEASE | LOAD_DEBUG | LOAD_SOURCE flag
|
||||
*
|
||||
* @return array The array of CSS files
|
||||
*/
|
||||
public function getRemoteCSSFiles($load) {
|
||||
$files = [];
|
||||
$GLOBALS['PluginManager']->triggerHook('server.main.include.cssfiles', ['load' => $load, 'files' => &$files]);
|
||||
|
||||
return $files;
|
||||
}
|
||||
|
||||
/**
|
||||
* Print each file on a new line using the given $template.
|
||||
*
|
||||
* @param array $files The files to print
|
||||
* @param string $template The template used to print each file, the string {file} will
|
||||
* be replaced with the filename
|
||||
* @param bool $base True if only the basename of the file must be printed
|
||||
* @param bool $concatVersion true if concatenate unique webapp version
|
||||
* with file name to avoid the caching issue
|
||||
*/
|
||||
public function printFiles($files, $template = '{file}', $base = false, $concatVersion = true) {
|
||||
foreach ($files as $file) {
|
||||
$file = $base === true ? basename((string) $file) : $file;
|
||||
if ($concatVersion) {
|
||||
$file = versionedUrl($file);
|
||||
}
|
||||
echo str_replace('{file}', $file, $template) . PHP_EOL;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Return grommunio Web version.
|
||||
*
|
||||
* @return string returns grommunio Web version
|
||||
*/
|
||||
public function getVersion() {
|
||||
return getWebappVersion();
|
||||
}
|
||||
|
||||
/**
|
||||
* getCSSFiles.
|
||||
*
|
||||
* Scanning files and subdirectories that can be found within the supplied
|
||||
* path and add all located CSS files to a list.
|
||||
*
|
||||
* @param $path String Path of the directory to scan
|
||||
* @param $recursive Boolean If set to true scans subdirectories as well
|
||||
* @param $excludeFiles Array Optional Paths of files or directories that
|
||||
* are excluded from the search
|
||||
*
|
||||
* @return array list of arrays containing the paths to files that have to be included
|
||||
*/
|
||||
public function getCSSFiles($path, $recursive = true, $excludeFiles = []) {
|
||||
return $this->getListOfFiles('css', $path, $recursive, $excludeFiles);
|
||||
}
|
||||
|
||||
/**
|
||||
* Scanning files and subdirectories that can be found within the supplied
|
||||
* path and add the files to a list.
|
||||
*
|
||||
* @param $ext The extension of files that are included ("js" or "css")
|
||||
* @param $path String Path of the directory to scan
|
||||
* @param $recursive Boolean If set to true scans subdirectories as well
|
||||
* @param $excludeFiles Array Optional Paths of files or directories that
|
||||
* are excluded from the search
|
||||
*
|
||||
* @return array list of arrays containing the paths to files that have to be included
|
||||
*/
|
||||
private function getListOfFiles($ext, $path, $recursive = true, $excludeFiles = []) {
|
||||
$files = [];
|
||||
$subDirFiles = [];
|
||||
|
||||
$dir = opendir($path);
|
||||
if (!is_resource($dir)) {
|
||||
return $files;
|
||||
}
|
||||
|
||||
while (($file = readdir($dir)) !== false) {
|
||||
$filepath = $path . '/' . $file;
|
||||
if (!str_starts_with($file, ".") && !in_array($filepath, $excludeFiles)) {
|
||||
$info = pathinfo($filepath, PATHINFO_EXTENSION);
|
||||
|
||||
if (is_file($filepath) && $info == $ext) {
|
||||
$files[] = $filepath;
|
||||
}
|
||||
elseif ($recursive && is_dir($filepath)) {
|
||||
$subDirFiles = array_merge($subDirFiles, $this->getListOfFiles($ext, $filepath, $recursive, $excludeFiles));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
sort($files);
|
||||
sort($subDirFiles);
|
||||
|
||||
return array_merge($files, $subDirFiles);
|
||||
}
|
||||
|
||||
/**
|
||||
* The JavaScript load order for grommunio Web.
|
||||
*/
|
||||
public function jsOrder() {
|
||||
[$extjsFiles, $webappFiles, $pluginFiles, $remoteFiles] = $this->getJsFiles();
|
||||
|
||||
$jsTemplate = "\t\t<script src=\"{file}\"></script>";
|
||||
$this->printFiles($extjsFiles, $jsTemplate);
|
||||
$this->printFiles($webappFiles, $jsTemplate);
|
||||
$this->printFiles($pluginFiles, $jsTemplate);
|
||||
$this->printFiles($remoteFiles, $jsTemplate);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns an array with all javascript files.
|
||||
*
|
||||
* @return array An array that contains the names of all the javascript files that should be loaded
|
||||
*/
|
||||
private function getJsFiles() {
|
||||
if (!isset($this->extjsFiles)) {
|
||||
$this->extjsFiles = $this->getExtjsJavascriptFiles(DEBUG_LOADER);
|
||||
$this->webappFiles = $this->getGrommunioJavascriptFiles(DEBUG_LOADER, $this->extjsFiles);
|
||||
$this->pluginFiles = $this->getPluginJavascriptFiles(DEBUG_LOADER, array_merge($this->extjsFiles, $this->webappFiles));
|
||||
$this->remoteFiles = $this->getRemoteJavascriptFiles(DEBUG_LOADER);
|
||||
}
|
||||
|
||||
return [$this->extjsFiles, $this->webappFiles, $this->pluginFiles, $this->remoteFiles];
|
||||
}
|
||||
|
||||
/**
|
||||
* The CSS load order for grommunio Web.
|
||||
*/
|
||||
public function cssOrder() {
|
||||
$cssTemplate = "\t\t<link rel=\"stylesheet\" type=\"text/css\" href=\"{file}\">";
|
||||
$extjsFiles = $this->getExtjsCSSFiles(DEBUG_LOADER);
|
||||
$this->printFiles($extjsFiles, $cssTemplate);
|
||||
|
||||
$this->printFiles(["client/resources/css/grommunio.css", "client/resources/css/message-security.css"], $cssTemplate);
|
||||
|
||||
$pluginFiles = $this->getPluginCSSFiles(DEBUG_LOADER);
|
||||
$this->printFiles($pluginFiles, $cssTemplate);
|
||||
|
||||
$remoteFiles = $this->getRemoteCSSFiles(DEBUG_LOADER);
|
||||
$this->printFiles($remoteFiles, $cssTemplate);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,166 @@
|
||||
<?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
|
||||
*/
|
||||
|
||||
abstract class Logger {
|
||||
/**
|
||||
* @var string
|
||||
*/
|
||||
protected $user = '';
|
||||
|
||||
/**
|
||||
* @var array
|
||||
*/
|
||||
protected $specialLogUsers = [];
|
||||
|
||||
/**
|
||||
* Only used as a cache value for IsUserInSpecialLogUsers.
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
private $isUserInSpecialLogUsers = [];
|
||||
|
||||
/**
|
||||
* Only used as a cache value for IsAuthUserInSpecialLogUsers function.
|
||||
*
|
||||
* @var bool
|
||||
*/
|
||||
private $isAuthUserInSpecialLogUsers = false;
|
||||
|
||||
/**
|
||||
* Returns the current user.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function GetUser() {
|
||||
return $this->user;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the current user.
|
||||
*
|
||||
* @param string $value name of the currently logged-in user
|
||||
*/
|
||||
public function SetUser($value) {
|
||||
$this->user = $value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Indicates if special log users are known.
|
||||
*
|
||||
* @return bool True if we do have to log some specific user. False otherwise.
|
||||
*/
|
||||
public function HasSpecialLogUsers() {
|
||||
return !empty($this->specialLogUsers);
|
||||
}
|
||||
|
||||
/**
|
||||
* Indicates if the user is in the special log users.
|
||||
*
|
||||
* @param string $user
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
public function IsUserInSpecialLogUsers($user) {
|
||||
if (isset($this->isUserInSpecialLogUsers[$user])) {
|
||||
return true;
|
||||
}
|
||||
if ($this->HasSpecialLogUsers()) {
|
||||
$specialLogUsers = $this->GetSpecialLogUsers();
|
||||
if (array_search($user, $specialLogUsers, true) !== false) {
|
||||
$this->isUserInSpecialLogUsers[$user] = true;
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the current special log users array.
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
public function GetSpecialLogUsers() {
|
||||
return $this->specialLogUsers;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the current special log users array.
|
||||
*/
|
||||
public function SetSpecialLogUsers(array $value) {
|
||||
$this->isUserInSpecialLogUsers = []; // reset cache
|
||||
$this->specialLogUsers = $value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check that the current login user is in the special log user array.
|
||||
* This call is equivalent to `$this->IsUserInSpecialLogUsers($this->GetUser())` at the exception that this
|
||||
* call uses cache so there won't be more than one check to the specialLogUser for the login user.
|
||||
*
|
||||
* @return bool true if user exist in special log user array else false
|
||||
*/
|
||||
public function IsAuthUserInSpecialLogUsers() {
|
||||
if ($this->isAuthUserInSpecialLogUsers) {
|
||||
return true;
|
||||
}
|
||||
if ($this->IsUserInSpecialLogUsers($this->GetUser())) {
|
||||
$this->isAuthUserInSpecialLogUsers = true;
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Logs a message with a given log level.
|
||||
*
|
||||
* @param int $logLevel The log level which will be configured in config file
|
||||
* @param string $message The log message which we want to log in user specific log file
|
||||
* @param mixed $detailMessage (optional) The detailed log message. it can be Error/Exception array.
|
||||
* @param mixed $request (optional) The request data sent by the user
|
||||
*/
|
||||
public function Log($logLevel, $message, $detailMessage = false, $request = false) {
|
||||
if ($logLevel <= LOG_USER_LEVEL) {
|
||||
if ($this->IsAuthUserInSpecialLogUsers()) {
|
||||
$this->Write($logLevel, $message, $detailMessage, $request);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the string representation of the given $loglevel.
|
||||
*
|
||||
* @param int $loglevel one of the LOGLEVELs
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
protected function GetLogLevelString($loglevel) {
|
||||
return match ($loglevel) {
|
||||
LOGLEVEL_OFF => "",
|
||||
LOGLEVEL_FATAL => "[FATAL]",
|
||||
LOGLEVEL_ERROR => "[ERROR]",
|
||||
LOGLEVEL_WARN => "[WARN]",
|
||||
LOGLEVEL_INFO => "[INFO]",
|
||||
LOGLEVEL_DEBUG => "[DEBUG]",
|
||||
default => "",
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Writes a log message to the general log.
|
||||
*
|
||||
* @param int $logLevel The log level which will be configured in config file
|
||||
* @param string $message The log message which we want to log in user specific log file
|
||||
* @param mixed $detailMessage (optional) The detailed log message. it can be Error/Exception array.
|
||||
* @param mixed $request (optional) The request data sent by the user
|
||||
*/
|
||||
abstract protected function Write($logLevel, $message, $detailMessage, $request);
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
<?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 FileLog extends Logger {
|
||||
/**
|
||||
* @var string
|
||||
*/
|
||||
private $logToUserFile = "";
|
||||
|
||||
/**
|
||||
* Writes a log message to the general log.
|
||||
*
|
||||
* @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 $detailMessage (optional) The detailed log message. it can be Error/Exception array.
|
||||
* @param mixed $request (optional) The request data sent by the user
|
||||
*/
|
||||
protected function Write($logLevel, $message, $detailMessage = false, $request = false) {
|
||||
$dir = LOG_FILE_DIR;
|
||||
if (!str_ends_with(LOG_FILE_DIR, "/")) {
|
||||
$dir .= "/";
|
||||
}
|
||||
|
||||
// If users directory not created then create it first.
|
||||
if (!is_dir($dir)) {
|
||||
if (empty($dir)) {
|
||||
error_log("Log directory has not configured. provide valid directory path.");
|
||||
|
||||
return;
|
||||
}
|
||||
if (mkdir($dir, 0777, true) === false) {
|
||||
error_log("Problem in creating log folder " . $dir);
|
||||
|
||||
return;
|
||||
}
|
||||
}
|
||||
$data = $this->BuildLogString($logLevel, $message, $detailMessage, $request) . PHP_EOL;
|
||||
file_put_contents($dir . $this->getLogToUserFile(), $data, FILE_APPEND);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the log user file.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
private function getLogToUserFile() {
|
||||
if (strlen($this->logToUserFile) == 0) {
|
||||
$this->setLogToUserFile($this->getUser() . ".log");
|
||||
}
|
||||
|
||||
return $this->logToUserFile;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set user log-file relative to log directory.
|
||||
*
|
||||
* @param string $value
|
||||
*/
|
||||
private function setLogToUserFile($value) {
|
||||
$this->logToUserFile = $value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the string to be logged.
|
||||
*
|
||||
* @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 $detailMessage (optional) The detailed log message. it can be Error/Exception array.
|
||||
* @param mixed $request (optional) The request data sent by the user
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function BuildLogString($loglevel, $message, $detailMessage = false, $request = false) {
|
||||
$dateTime = date("d-M-Y H:i:s");
|
||||
$log = "[" . $dateTime . "] ";
|
||||
$log .= $this->GetLogLevelString($loglevel);
|
||||
$log .= ' ' . $message;
|
||||
|
||||
if ($detailMessage) {
|
||||
$log .= ' :' . var_export($detailMessage, true) . "\r\n";
|
||||
}
|
||||
|
||||
if ($request) {
|
||||
$log .= ' Request:' . var_export($request, true) . "\r\n";
|
||||
}
|
||||
|
||||
return $log;
|
||||
}
|
||||
}
|
||||
+434
@@ -0,0 +1,434 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* SPDX-FileCopyrightText: Copyright 2020 - 2026 grommunio GmbH
|
||||
* SPDX-FileCopyrightText: Copyright 2016 Kopano and its licensors
|
||||
* SPDX-FileCopyrightText: Copyright 2005 - 2016 Zarafa B.V. and its licensors
|
||||
* SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
*/
|
||||
|
||||
/**
|
||||
* Read Mail ItemModule.
|
||||
*/
|
||||
class AddressbookItemModule extends ItemModule {
|
||||
private $userDetailProperties;
|
||||
private $abObjectDetailProperties;
|
||||
private $groupDetailProperties;
|
||||
|
||||
/**
|
||||
* Constructor.
|
||||
*
|
||||
* @param int $id unique id
|
||||
* @param array $data list of all actions
|
||||
*/
|
||||
public function __construct($id, $data) {
|
||||
$this->userDetailProperties = $GLOBALS["properties"]->getAddressBookItemMailuserProperties();
|
||||
$this->abObjectDetailProperties = $GLOBALS["properties"]->getAddressBookItemABObjectProperties();
|
||||
$this->groupDetailProperties = $GLOBALS["properties"]->getAddressBookItemDistlistProperties();
|
||||
|
||||
parent::__construct($id, $data);
|
||||
}
|
||||
|
||||
/**
|
||||
* Function which opens an item.
|
||||
*
|
||||
* @param object $store MAPI Message Store Object
|
||||
* @param string $entryid entryid of the message
|
||||
* @param array $action the action data, sent by the client
|
||||
*/
|
||||
#[Override]
|
||||
public function open($store, $entryid, $action) {
|
||||
if ($entryid) {
|
||||
$data = [];
|
||||
|
||||
try {
|
||||
$abentry = mapi_ab_openentry($GLOBALS["mapisession"]->getAddressbook(false, true), $entryid);
|
||||
}
|
||||
catch (MAPIException $e) {
|
||||
// If the item not found in addressbook, it might be possible that
|
||||
// this particular item was added by setup-contact-provider mechanism.
|
||||
// Let us try to get that particular contact item in respective user store.
|
||||
// @Fixme: After implementation of KC-350 this extra handling can be removed.
|
||||
if ($e->getCode() == MAPI_E_NOT_FOUND || $e->getCode() == MAPI_E_INVALID_PARAMETER) {
|
||||
if ($GLOBALS['entryid']->hasNoMuid(bin2hex($entryid))) {
|
||||
$entryid = substr($entryid, 0, -1);
|
||||
}
|
||||
else {
|
||||
// unwrap ab entry id
|
||||
$entryid = substr($entryid, 28);
|
||||
}
|
||||
|
||||
try {
|
||||
$contactItem = $GLOBALS['operations']->openMessage($GLOBALS['mapisession']->getDefaultMessageStore(), $entryid);
|
||||
}
|
||||
catch (MAPIException $me) {
|
||||
if (!empty($action['store_entryid'])) {
|
||||
$e->setHandled();
|
||||
$me->setHandled();
|
||||
$userStore = $GLOBALS['mapisession']->openMessageStore(hex2bin((string) $action['store_entryid']));
|
||||
$contactItem = $GLOBALS['operations']->openMessage($userStore, $entryid);
|
||||
}
|
||||
}
|
||||
finally {
|
||||
if (isset($contactItem) && $contactItem != false) {
|
||||
// Get necessary property from respective contact item
|
||||
$contactItemProps = mapi_getprops($contactItem, [PR_GIVEN_NAME, PR_DISPLAY_NAME, PR_TITLE, PR_COMPANY_NAME]);
|
||||
|
||||
// Use the data retrieved from contact item to prepare response
|
||||
// as similar as it seems like an addressbook item.
|
||||
$data['props'] = [
|
||||
'object_type' => MAPI_MAILUSER,
|
||||
'given_name' => $contactItemProps[PR_GIVEN_NAME],
|
||||
'display_name' => $contactItemProps[PR_DISPLAY_NAME],
|
||||
'title' => $contactItemProps[PR_TITLE],
|
||||
'company_name' => $contactItemProps[PR_COMPANY_NAME],
|
||||
];
|
||||
$data['entryid'] = bin2hex($entryid);
|
||||
|
||||
$this->addActionData("item", $data);
|
||||
$GLOBALS["bus"]->addData($this->getResponseData());
|
||||
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (mapi_last_hresult() == NOERROR && $abentry) {
|
||||
$objecttypeprop = mapi_getprops($abentry, [PR_OBJECT_TYPE]);
|
||||
|
||||
if (isset($objecttypeprop[PR_OBJECT_TYPE])) {
|
||||
// Get the properties for a MAILUSER object and process those MAILUSER specific props that require some more actions
|
||||
if ($objecttypeprop[PR_OBJECT_TYPE] == MAPI_MAILUSER) {
|
||||
$messageprops = mapi_getprops($abentry, $this->userDetailProperties);
|
||||
|
||||
$props = Conversion::mapMAPI2XML($this->userDetailProperties, $messageprops);
|
||||
|
||||
if (isset($messageprops[PR_EMS_AB_THUMBNAIL_PHOTO])) {
|
||||
$props['props']['ems_ab_thumbnail_photo'] = $GLOBALS['operations']->compressedImage($messageprops[PR_EMS_AB_THUMBNAIL_PHOTO]);
|
||||
}
|
||||
|
||||
// Get the properties of the manager
|
||||
$managerProps = $this->getManagerDetails($messageprops);
|
||||
if ($managerProps !== false) {
|
||||
$props['ems_ab_manager'] = [
|
||||
'item' => $managerProps,
|
||||
];
|
||||
}
|
||||
|
||||
$homePhoneNumbers = $this->getHomePhoneNumbers($messageprops);
|
||||
if (!empty($homePhoneNumbers)) {
|
||||
// Add the list of home2_telephone_number_mv in the correct format to $props list to be send to the client
|
||||
$props['home2_telephone_numbers'] = [
|
||||
'item' => $homePhoneNumbers,
|
||||
];
|
||||
}
|
||||
|
||||
$businessPhoneNumbers = $this->getBusinessPhoneNumbers($messageprops);
|
||||
if (!empty($businessPhoneNumbers)) {
|
||||
// Add the list of business2_telephone_number_mv in the correct format to $props list to be send to the client
|
||||
$props['business2_telephone_numbers'] = [
|
||||
'item' => $businessPhoneNumbers,
|
||||
];
|
||||
}
|
||||
|
||||
// Get the properties of the "direct reports"
|
||||
$directReportsList = $this->getDirectReportsDetails($messageprops);
|
||||
if (!empty($directReportsList)) {
|
||||
// Add the list of proxy_addresses in the correct format to the $props list to be send to the client.
|
||||
$props['ems_ab_reports'] = [
|
||||
'item' => $directReportsList,
|
||||
];
|
||||
}
|
||||
|
||||
// Get the properties for a DISTLIST object and process those DISTLIST specific props that require some more actions
|
||||
}
|
||||
else {
|
||||
$messageprops = mapi_getprops($abentry, $this->groupDetailProperties);
|
||||
$props = Conversion::mapMAPI2XML($this->groupDetailProperties, $messageprops);
|
||||
|
||||
// Get the properties of the owner
|
||||
$ownerProps = $this->getOwnerDetails($messageprops);
|
||||
if ($ownerProps !== false) {
|
||||
// We can use the same properties as we use for the manager in a MAILUSER
|
||||
$props['ems_ab_owner'] = [
|
||||
'item' => $ownerProps,
|
||||
];
|
||||
}
|
||||
|
||||
// Get the list of members for this DISTLSIT
|
||||
$props['members'] = [
|
||||
'item' => $this->getMembersDetails($abentry),
|
||||
];
|
||||
}
|
||||
|
||||
// Get the proxy addresses list, this property exists in both MAILUSER and DISTLIST
|
||||
$proxyAddresses = $this->getProxyAddressesDetails($messageprops);
|
||||
// Remove the MV-flagged property
|
||||
if (!empty($proxyAddresses)) {
|
||||
// Add the list of proxy_addresses in the correct format to the $props list to be send to the client.
|
||||
$props['ems_ab_proxy_addresses'] = [
|
||||
'item' => $proxyAddresses,
|
||||
];
|
||||
}
|
||||
|
||||
// Get the properties of the group membership, this property exists in both MAILUSER and DISTLIST
|
||||
$memberOfList = $this->getMemberOfDetails($messageprops);
|
||||
if (!empty($memberOfList)) {
|
||||
// Add the list of proxy_addresses in the correct format to the $props list to be send to the client.
|
||||
$props['ems_ab_is_member_of_dl'] = [
|
||||
'item' => $memberOfList,
|
||||
];
|
||||
}
|
||||
|
||||
// Remove the MV-flagged properties and also its single valued counterpart
|
||||
unset($props['props']['ems_ab_is_member_of_dl'], $props['props']['business2_telephone_number_mv'], $props['props']['business2_telephone_number'], $props['props']['home2_telephone_number_mv'], $props['props']['home2_telephone_number'], $props['props']['ems_ab_proxy_addresses'], $props['props']['ems_ab_reports_mv'], $props['props']['ems_ab_reports'], $props['props']['ems_ab_owner'], $props['props']['ems_ab_manager']);
|
||||
|
||||
// Allowing to hook in and add more properties
|
||||
$GLOBALS['PluginManager']->triggerHook("server.module.addressbookitemmodule.open.props", [
|
||||
'moduleObject' => &$this,
|
||||
'abentry' => $abentry,
|
||||
'object_type' => $objecttypeprop[PR_OBJECT_TYPE],
|
||||
'messageprops' => $messageprops,
|
||||
'props' => &$props,
|
||||
]);
|
||||
|
||||
$data["item"] = $props;
|
||||
$this->addActionData("item", $data);
|
||||
}
|
||||
else {
|
||||
// Handling error: not able to handle this type of object
|
||||
$data["error"] = [];
|
||||
$data["error"]["message"] = _("Could not handle this type of object.");
|
||||
$this->addActionData("error", $data);
|
||||
}
|
||||
}
|
||||
else {
|
||||
// Handle not being able to open the object
|
||||
$data["error"] = [];
|
||||
$data["error"]["hresult"] = mapi_last_hresult();
|
||||
$data["error"]["hresult_name"] = get_mapi_error_name(mapi_last_hresult());
|
||||
$data["error"]["message"] = _("Could not open this object.");
|
||||
$this->addActionData("error", $data);
|
||||
}
|
||||
|
||||
$GLOBALS["bus"]->addData($this->getResponseData());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get Business Telephone numbers in the messageprops array when it is set in the
|
||||
* PR_HOME2_TELEPHONE_NUMBER_MV. This property is poorly documented and in Outlook it checks
|
||||
* the property with and without the MV flag. The one without a MV flag can contain only one
|
||||
* entry and the one with MV flag can contain a list. It then merges both into one list.
|
||||
* This function has the same behavior and sets the list in the $messageprops.
|
||||
*
|
||||
* @param $messageprops Array Details properties of an user entry
|
||||
*
|
||||
* @return array List of telephone numbers
|
||||
*/
|
||||
public function getHomePhoneNumbers($messageprops) {
|
||||
$list = [];
|
||||
if (isset($messageprops[$this->userDetailProperties['home2_telephone_number']])) {
|
||||
$list[] = $messageprops[$this->userDetailProperties['home2_telephone_number']];
|
||||
}
|
||||
if (isset($messageprops[$this->userDetailProperties['home2_telephone_number_mv']])) {
|
||||
$list = array_merge($list, $messageprops[$this->userDetailProperties['home2_telephone_number_mv']]);
|
||||
}
|
||||
|
||||
$returnList = [];
|
||||
for ($i = 0, $len = count($list); $i < $len; ++$i) {
|
||||
array_push($returnList, ['number' => $list[$i]]);
|
||||
}
|
||||
|
||||
return $returnList;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get Business Telephone numbers in the messageprops array when it is set in the
|
||||
* PR_BUSINESS2_TELEPHONE_NUMBER_MV. This property is poorly documented and in Outlook it checks
|
||||
* the property with and without the MV flag. The one without a MV flag can contain only one
|
||||
* entry and the one with MV flag can contain a list. It then merges both into one list.
|
||||
* This function has the same behavior and sets the list in the $messageprops.
|
||||
*
|
||||
* @param $messageprops Array Details properties of an user entry
|
||||
*
|
||||
* @return array List of telephone numbers
|
||||
*/
|
||||
public function getBusinessPhoneNumbers($messageprops) {
|
||||
$list = [];
|
||||
if (isset($messageprops[$this->userDetailProperties['business2_telephone_number']])) {
|
||||
$list[] = $messageprops[$this->userDetailProperties['business2_telephone_number']];
|
||||
}
|
||||
if (isset($messageprops[$this->userDetailProperties['business2_telephone_number_mv']])) {
|
||||
$list = array_merge($list, $messageprops[$this->userDetailProperties['business2_telephone_number_mv']]);
|
||||
}
|
||||
|
||||
$returnList = [];
|
||||
for ($i = 0, $len = count($list); $i < $len; ++$i) {
|
||||
array_push($returnList, ['number' => $list[$i]]);
|
||||
}
|
||||
|
||||
return $returnList;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get Proxy Addresses in the messageprops array when it is set in the
|
||||
* PR_EMS_AB_PROXY_ADDRESSES. This property is poorly documented and in Outlook it checks
|
||||
* the property with and without the MV flag. The one without a MV flag can contain only one
|
||||
* entry and the one with MV flag can contain a list. It then merges both into one list.
|
||||
* This function has the same behavior and sets the list in the $messageprops.
|
||||
*
|
||||
* @param $messageprops Array Details properties of an user entry
|
||||
*
|
||||
* @return array List of addresses
|
||||
*/
|
||||
public function getProxyAddressesDetails($messageprops) {
|
||||
$returnList = [];
|
||||
if (isset($messageprops[$this->userDetailProperties['ems_ab_proxy_addresses']]) &&
|
||||
is_array($messageprops[$this->userDetailProperties['ems_ab_proxy_addresses']])) {
|
||||
foreach ($messageprops[$this->userDetailProperties['ems_ab_proxy_addresses']] as $eapa) {
|
||||
$returnList[] = ['address' => $eapa];
|
||||
}
|
||||
}
|
||||
|
||||
return $returnList;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the information of the manager from the GAB details of a MAPI_MAILUSER. Will use the
|
||||
* entryid to get the properties. If no entryid if found false is returned.
|
||||
*
|
||||
* @param $messageprops Array Details properties of an user entry
|
||||
*
|
||||
* @return array|bool List of properties or false if no manager is set
|
||||
*/
|
||||
public function getManagerDetails($messageprops) {
|
||||
if (isset($messageprops[$this->userDetailProperties['ems_ab_manager']])) {
|
||||
$entryidMananager = $messageprops[$this->userDetailProperties['ems_ab_manager']];
|
||||
|
||||
$managerEntry = mapi_ab_openentry($GLOBALS["mapisession"]->getAddressbook(), $entryidMananager);
|
||||
$managerProps = mapi_getprops($managerEntry, $this->abObjectDetailProperties);
|
||||
|
||||
return Conversion::mapMAPI2XML($this->abObjectDetailProperties, $managerProps);
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the list of users that have been set in the PR_EMS_AB_REPORTS property in the
|
||||
* $messageprops array. This property is poorly documented and in Outlook it checks
|
||||
* the property with and without the MV flag. The one without a MV flag can contain only one
|
||||
* entry and the one with MV flag can contain a list. It then merges both into one list.
|
||||
* This function has the same behavior and sets the list in the $messageprops.
|
||||
*
|
||||
* @param $messageprops Array Details properties of an user entry
|
||||
*
|
||||
* @return array|bool List of properties or false if no manager is set
|
||||
*/
|
||||
public function getDirectReportsDetails($messageprops) {
|
||||
/*
|
||||
* Get the entryIds from the PR_EMS_AB_REPORTS property (with and without MV flag as a
|
||||
* fallback) and put the entryIds in a list.
|
||||
*/
|
||||
$entryids = [];
|
||||
if (isset($messageprops[$this->userDetailProperties['ems_ab_reports']])) {
|
||||
$entryids[] = $messageprops[$this->userDetailProperties['ems_ab_reports']];
|
||||
}
|
||||
if (isset($messageprops[$this->userDetailProperties['ems_ab_reports_mv']])) {
|
||||
$entryids = array_merge($entryids, $messageprops[$this->userDetailProperties['ems_ab_reports_mv']]);
|
||||
}
|
||||
|
||||
$result = [];
|
||||
// Convert the entryIds in an array of properties of the AB entryies
|
||||
for ($i = 0, $len = count($entryids); $i < $len; ++$i) {
|
||||
// Get the properties from the AB entry
|
||||
$entry = mapi_ab_openentry($GLOBALS["mapisession"]->getAddressbook(), $entryids[$i]);
|
||||
$props = mapi_getprops($entry, $this->abObjectDetailProperties);
|
||||
// Convert the properties for each entry and put it in an array
|
||||
$result[] = Conversion::mapMAPI2XML($this->abObjectDetailProperties, $props);
|
||||
}
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the list of users that have been set in the PR_EMS_AB_MEMBER_OF_DL property in the
|
||||
* $messageprops array. This property is poorly documented and in Outlook it checks
|
||||
* the property with and without the MV flag. The one without a MV flag can contain only one
|
||||
* entry and the one with MV flag can contain a list. It then merges both into one list.
|
||||
* This function has the same behavior and sets the list in the $messageprops.
|
||||
*
|
||||
* @param $messageprops Array Details properties of an user entry
|
||||
*
|
||||
* @return array|bool List of properties or false if no manager is set
|
||||
*/
|
||||
public function getMemberOfDetails($messageprops) {
|
||||
$result = [];
|
||||
// Get the properties of the group membership
|
||||
if (isset($messageprops[$this->userDetailProperties['ems_ab_is_member_of_dl']])) {
|
||||
$entryids = $messageprops[$this->userDetailProperties['ems_ab_is_member_of_dl']];
|
||||
// Get the properties from every entryid in the memberOf list
|
||||
for ($i = 0, $len = count($entryids); $i < $len; ++$i) {
|
||||
// Get the properties from the AB entry
|
||||
$entry = mapi_ab_openentry($GLOBALS["mapisession"]->getAddressbook(), $entryids[$i]);
|
||||
$props = mapi_getprops($entry, $this->abObjectDetailProperties);
|
||||
// Convert the properties for each entry and put it in an array
|
||||
$result[] = Conversion::mapMAPI2XML($this->abObjectDetailProperties, $props);
|
||||
}
|
||||
}
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the information of the owner from the GAB details of a MAPI_DISTLIST. Will use the
|
||||
* entryid to get the properties. If no entryid if found false is returned.
|
||||
*
|
||||
* @param $messageprops Array Details properties of an distlist entry
|
||||
*
|
||||
* @return array|bool List of properties or false if no owner is set
|
||||
*/
|
||||
public function getOwnerDetails($messageprops) {
|
||||
if (isset($messageprops[$this->groupDetailProperties['ems_ab_owner']])) {
|
||||
$entryidOwner = $messageprops[$this->groupDetailProperties['ems_ab_owner']];
|
||||
|
||||
$ownerEntry = mapi_ab_openentry($GLOBALS["mapisession"]->getAddressbook(), $entryidOwner);
|
||||
$ownerProps = mapi_getprops($ownerEntry, $this->abObjectDetailProperties);
|
||||
|
||||
return Conversion::mapMAPI2XML($this->abObjectDetailProperties, $ownerProps);
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the information of the members from the GAB details of a MAPI_DISTLIST. The
|
||||
* information can be found in the contentstable of the AB entry opened by the user.
|
||||
*
|
||||
* @param $abentry Resource Reference to the user-opened AB entry
|
||||
*
|
||||
* @return array|bool List of members
|
||||
*/
|
||||
public function getMembersDetails($abentry) {
|
||||
$result = [];
|
||||
|
||||
$table = mapi_folder_getcontentstable($abentry, MAPI_DEFERRED_ERRORS);
|
||||
|
||||
/*
|
||||
* To prevent loading a huge list that the browser cannot handle, it is possible to
|
||||
* limit the maximum number of shown items. Note that when the table doesn't
|
||||
* contain the requested number of rows, it will not give any errors and simply
|
||||
* return what is available.
|
||||
* When the limit is 0 or below, then no limit is applied and we use 0x7fffffff
|
||||
* to indicate we want to have all rows from the table.
|
||||
*/
|
||||
$rows = mapi_table_queryrows($table, $this->abObjectDetailProperties, 0, (ABITEMDETAILS_MAX_NUM_DISTLIST_MEMBERS > 0) ? ABITEMDETAILS_MAX_NUM_DISTLIST_MEMBERS : 0x7FFFFFFF);
|
||||
for ($i = 0, $len = count($rows); $i < $len; ++$i) {
|
||||
$result[] = Conversion::mapMAPI2XML($this->abObjectDetailProperties, $rows[$i]);
|
||||
}
|
||||
|
||||
return $result;
|
||||
}
|
||||
}
|
||||
+1397
File diff suppressed because it is too large.
Load diff
+813
@@ -0,0 +1,813 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* SPDX-FileCopyrightText: Copyright 2020 - 2026 grommunio GmbH
|
||||
* SPDX-FileCopyrightText: Copyright 2016 Kopano and its licensors
|
||||
* SPDX-FileCopyrightText: Copyright 2005 - 2016 Zarafa B.V. and its licensors
|
||||
* SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
*/
|
||||
|
||||
require_once BASE_PATH . 'server/includes/core/class.indexsqlite.php';
|
||||
require_once BASE_PATH . 'server/includes/core/class.ftsrestrictionconverter.php';
|
||||
|
||||
class AdvancedSearchListModule extends ListModule {
|
||||
/**
|
||||
* Length gromox truncates PT_UNICODE cells of a table row to. Applied to
|
||||
* properties read off an opened message so both paths return equal rows.
|
||||
*/
|
||||
private const LIST_STRING_CAP = 255;
|
||||
|
||||
/**
|
||||
* Set once publicStoreSearch() has run for this request, so the
|
||||
* messageList() fallback below does not try the same index again.
|
||||
*/
|
||||
private $publicSearchAttempted = false;
|
||||
|
||||
/**
|
||||
* Constructor.
|
||||
*
|
||||
* @param int $id unique id
|
||||
* @param array $data list of all actions
|
||||
*/
|
||||
public function __construct($id, $data) {
|
||||
parent::__construct($id, $data);
|
||||
// TODO: create a new method in Properties class that will return only the properties we
|
||||
// need for search list (and perhaps for preview???)
|
||||
$this->properties = $GLOBALS["properties"]->getMailListProperties();
|
||||
$this->properties = array_merge($this->properties, $GLOBALS["properties"]->getAppointmentListProperties());
|
||||
$this->properties = array_merge($this->properties, $GLOBALS["properties"]->getContactListProperties());
|
||||
$this->properties = array_merge($this->properties, $GLOBALS["properties"]->getStickyNoteListProperties());
|
||||
$this->properties = array_merge($this->properties, $GLOBALS["properties"]->getTaskListProperties());
|
||||
// Note: no html_body here. Table rows are truncated by the server
|
||||
// (gromox caps table cells), and a truncated html_body from the row
|
||||
// would survive the open merge and poison the preview pane whenever
|
||||
// the opened item returns no html_body (e.g. plaintext mails).
|
||||
$this->properties = array_merge($this->properties, [
|
||||
'body' => PR_BODY,
|
||||
'startdate' => "PT_SYSTIME:PSETID_Appointment:" . PidLidAppointmentStartWhole,
|
||||
'duedate' => "PT_SYSTIME:PSETID_Appointment:" . PidLidAppointmentEndWhole,
|
||||
'creation_time' => PR_CREATION_TIME,
|
||||
"task_duedate" => "PT_SYSTIME:PSETID_Task:" . PidLidTaskDueDate,
|
||||
]);
|
||||
$this->properties = getPropIdsFromStrings($GLOBALS["mapisession"]->getDefaultMessageStore(), $this->properties);
|
||||
$this->sort = [
|
||||
PR_MESSAGE_DELIVERY_TIME => TABLE_SORT_DESCEND,
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the domain a public store entryid points at, or null when the
|
||||
* action does not address a public store.
|
||||
*
|
||||
* This reads the store entryid the client already sent instead of asking
|
||||
* the server for PR_MDB_PROVIDER, so recognising the (far more common)
|
||||
* private store costs no extra round trip.
|
||||
*
|
||||
* @param array $action the action data, sent by the client
|
||||
*
|
||||
* @return null|string
|
||||
*/
|
||||
private function publicStoreDomain($action) {
|
||||
if (empty($action['store_entryid'])) {
|
||||
return null;
|
||||
}
|
||||
$eidObj = $GLOBALS["entryid"]->createMsgStoreEntryIdObj(hex2bin((string) $action['store_entryid']));
|
||||
if (($eidObj['WrappedProviderUID'] ?? '') !== MUID_STORE_PUBLIC_GUID) {
|
||||
return null;
|
||||
}
|
||||
$domain = $eidObj['ServerShortname'] ?? '';
|
||||
|
||||
return $domain === '' ? null : $domain;
|
||||
}
|
||||
|
||||
/**
|
||||
* Answers a search in a public store from the fulltext index.
|
||||
*
|
||||
* The index is keyed by the domain name, which is what gromox puts into
|
||||
* the public store entryid as the server shortname, and grommunio-index
|
||||
* writes it to the same place as the per-user indexes.
|
||||
*
|
||||
* @param resource $store MAPI message store
|
||||
* @param string $entryid entryid of the folder to search in
|
||||
* @param array $action the action data, sent by the client
|
||||
* @param string $actionType the action type to answer with
|
||||
* @param null|string $domain domain owning the public store
|
||||
*
|
||||
* @return bool true when the response was sent, false to fall back
|
||||
*/
|
||||
private function publicStoreSearch($store, $entryid, $action, $actionType, $domain) {
|
||||
$this->publicSearchAttempted = true;
|
||||
if ($domain === null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$this->searchFolderList = true;
|
||||
$this->restriction = false;
|
||||
$this->parseRestriction($action);
|
||||
if ($this->restriction === false) {
|
||||
return false;
|
||||
}
|
||||
$ftsDescriptor = $this->buildFtsDescriptor($this->restriction);
|
||||
if (empty($ftsDescriptor['ast'])) {
|
||||
return false;
|
||||
}
|
||||
if (is_array($ftsDescriptor['message_classes']) &&
|
||||
count($ftsDescriptor['message_classes']) >= 7) {
|
||||
$ftsDescriptor['message_classes'] = null;
|
||||
}
|
||||
|
||||
$indexDB = new IndexSqlite($domain, $GLOBALS["mapisession"]->getSession(), $store);
|
||||
if (!$indexDB->is_open()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
/*
|
||||
* "subfolders" only rides along with the initial search request, so
|
||||
* remember it for the paging requests that follow.
|
||||
*/
|
||||
$recursive = isset($action["subfolders"]) && $action["subfolders"] == "true";
|
||||
$scopeKey = md5(bin2hex($entryid) . $domain);
|
||||
if (!is_array($this->sessionData)) {
|
||||
$this->sessionData = [];
|
||||
}
|
||||
if (isset($action["subfolders"])) {
|
||||
$this->sessionData['publicSearchRecursive'][$scopeKey] = $recursive;
|
||||
}
|
||||
else {
|
||||
$recursive = $this->sessionData['publicSearchRecursive'][$scopeKey] ?? false;
|
||||
}
|
||||
|
||||
$this->logFtsDebug('Dispatching public store search to index backend', [
|
||||
'domain' => $domain,
|
||||
'recursive' => $recursive,
|
||||
'message_classes' => $ftsDescriptor['message_classes'] ?? null,
|
||||
'ast' => $ftsDescriptor['ast'] ?? null,
|
||||
]);
|
||||
$entryids = $indexDB->searchEntryIds($ftsDescriptor, $entryid, $recursive);
|
||||
if ($entryids === false) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$this->parseSortOrder($action, null, true);
|
||||
$limit = $action['restriction']['limit'] ?? $GLOBALS['settings']->get('grommunio/v1/main/page_size', 50);
|
||||
$limit = max(1, (int) $limit);
|
||||
$start = max(0, (int) $this->start);
|
||||
$data = ["item" => []];
|
||||
/*
|
||||
* The index hands back the hits ordered by date, newest first, and the
|
||||
* page is cut from that list so only the messages actually shown have
|
||||
* to be opened. A sort on any other column therefore only orders the
|
||||
* page, not the whole result set - the index has no data to sort the
|
||||
* rest by.
|
||||
*/
|
||||
foreach (array_slice($entryids, $start, $limit) as $messageEntryid) {
|
||||
try {
|
||||
$message = mapi_msgstore_openentry($store, $messageEntryid);
|
||||
}
|
||||
catch (Exception $e) {
|
||||
$this->logFtsDebug('Skipping unreadable search hit', [
|
||||
'error' => $e->getMessage(),
|
||||
]);
|
||||
|
||||
continue;
|
||||
}
|
||||
if ($message === false) {
|
||||
continue;
|
||||
}
|
||||
$row = mapi_getprops($message, $this->properties);
|
||||
/*
|
||||
* A table row arrives with its string cells already truncated by
|
||||
* the server; reading the properties off an opened message does
|
||||
* not, which would put whole message bodies into a list response.
|
||||
* Cut them to the same length the table would have returned.
|
||||
*/
|
||||
foreach ($row as $tag => $value) {
|
||||
$type = $tag & 0xFFFF;
|
||||
if (($type === PT_UNICODE || $type === PT_STRING8) &&
|
||||
is_string($value) && mb_strlen($value) > self::LIST_STRING_CAP) {
|
||||
$row[$tag] = mb_substr($value, 0, self::LIST_STRING_CAP);
|
||||
}
|
||||
}
|
||||
$item = Conversion::mapMAPI2XML($this->properties, $row);
|
||||
// Mirror getTable(): the list view expects the *_username aliases
|
||||
if (isset($item['props']["sent_representing_email_address"])) {
|
||||
$item['props']["sent_representing_username"] = $item['props']["sent_representing_email_address"];
|
||||
}
|
||||
if (isset($item['props']["sender_email_address"])) {
|
||||
$item['props']["sender_username"] = $item['props']["sender_email_address"];
|
||||
}
|
||||
if (isset($item['props']["received_by_email_address"])) {
|
||||
$item['props']["received_by_username"] = $item['props']["received_by_email_address"];
|
||||
}
|
||||
$data["item"][] = $item;
|
||||
}
|
||||
|
||||
$data["page"] = [
|
||||
"start" => $start,
|
||||
"rowcount" => $limit,
|
||||
"totalrowcount" => count($entryids),
|
||||
];
|
||||
$this->getDelegateFolderInfo($store);
|
||||
$data = $this->filterPrivateItems($data);
|
||||
$data["item"] = array_values($data["item"]);
|
||||
$data["search_meta"] = [
|
||||
// No searchfolder_entryid: there is no search folder to page
|
||||
// through, which also tells the client to keep sending the
|
||||
// restriction along with the next page.
|
||||
"search_store_entryid" => $action["store_entryid"],
|
||||
"searchstate" => 0,
|
||||
"results" => count($data["item"]),
|
||||
];
|
||||
|
||||
$this->addActionData($actionType, $data);
|
||||
$GLOBALS["bus"]->addData($this->getResponseData());
|
||||
$this->logFtsDebug('Public store search response dispatched', [
|
||||
'domain' => $domain,
|
||||
'total_hits' => count($entryids),
|
||||
'items_returned' => count($data["item"]),
|
||||
'start' => $start,
|
||||
]);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Executes all the actions in the $data variable.
|
||||
*/
|
||||
#[Override]
|
||||
public function execute() {
|
||||
foreach ($this->data as $actionType => $action) {
|
||||
if (isset($actionType)) {
|
||||
try {
|
||||
$store = $this->getActionStore($action);
|
||||
$entryid = $this->getActionSingleEntryID($action);
|
||||
if ($store === false || is_array($store)) {
|
||||
$this->sendFeedback(false);
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
switch ($actionType) {
|
||||
case "list":
|
||||
case "updatelist":
|
||||
$this->getDelegateFolderInfo($store);
|
||||
$this->messageList($store, $entryid, $action, $actionType);
|
||||
break;
|
||||
|
||||
case "search":
|
||||
$this->search($store, $entryid, $action, $actionType);
|
||||
break;
|
||||
|
||||
case "updatesearch":
|
||||
$this->updatesearch($store, $entryid, $action);
|
||||
break;
|
||||
|
||||
case "stopsearch":
|
||||
$this->stopSearch($store, $entryid, $action);
|
||||
break;
|
||||
|
||||
case "delete_searchfolder":
|
||||
$this->deleteSearchFolder($store, $entryid, $action);
|
||||
break;
|
||||
}
|
||||
}
|
||||
catch (MAPIException $e) {
|
||||
// This is a very nasty hack that makes sure that grommunio Web doesn't show an error message when
|
||||
// search wants to throw an error. This is only done because a proper fix for this bug has not
|
||||
// been found yet. When WA-9161 is really solved, this should be removed again.
|
||||
if ($actionType !== 'search' && $actionType !== 'updatesearch' && $actionType !== 'stopsearch') {
|
||||
$this->processException($e, $actionType);
|
||||
}
|
||||
else {
|
||||
if (DEBUG_LOADER === 0) {
|
||||
// Log all info we can get about this error to the error log of the web server
|
||||
error_log("Error in search: \n" . var_export($e, true) . "\n\n" . var_export(debug_backtrace(), true));
|
||||
}
|
||||
// Send success feedback without data, as if nothing strange happened...
|
||||
$this->sendFeedback(true);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Function which retrieves a list of messages in a folder.
|
||||
*
|
||||
* @param false|resource $store MAPI message store, or false when unavailable
|
||||
* @param false|string $entryid entryid of the folder, or false when unavailable
|
||||
* @param array $action the action data, sent by the client
|
||||
* @param string $actionType the action type, sent by the client
|
||||
*/
|
||||
#[Override]
|
||||
public function messageList($store, $entryid, $action, $actionType) {
|
||||
/*
|
||||
* A public-store search has no search folder for the client to page
|
||||
* through, so the client re-sends the search restriction as a plain
|
||||
* list request. Answer those from the index as well, otherwise page 2
|
||||
* would come from a different search than page 1.
|
||||
*/
|
||||
if (!$this->publicSearchAttempted && $store !== false && !is_array($store) &&
|
||||
is_string($entryid) && $entryid !== '' &&
|
||||
!empty($action['restriction']['search']) && !isset($action['search_folder_entryid']) &&
|
||||
$this->publicStoreSearch($store, $entryid, $action, $actionType,
|
||||
$this->publicStoreDomain($action))) {
|
||||
return;
|
||||
}
|
||||
|
||||
$this->searchFolderList = false; // Set to indicate this is not the search result, but a normal folder content
|
||||
$data = [];
|
||||
|
||||
if ($store !== false && $entryid !== false) {
|
||||
// Restriction
|
||||
$this->parseRestriction($action);
|
||||
|
||||
// Sort
|
||||
$this->parseSortOrder($action, null, true);
|
||||
|
||||
$limit = $action['restriction']['limit'] ?? 1000;
|
||||
|
||||
$isSearchFolder = isset($action['search_folder_entryid']);
|
||||
$entryid = $isSearchFolder ? hex2bin((string) $action['search_folder_entryid']) : $entryid;
|
||||
|
||||
if ($actionType == 'search') {
|
||||
$rows = [[PR_ENTRYID => $entryid]];
|
||||
if (isset($action['subfolders']) && $action['subfolders']) {
|
||||
$inboxEntryId = null;
|
||||
|
||||
try {
|
||||
$folder = mapi_msgstore_openentry($store, $entryid);
|
||||
}
|
||||
catch (Exception) {
|
||||
// Probably trying to open a store without having appropriate permissions.
|
||||
// Try to open the inbox instead.
|
||||
$folder = mapi_msgstore_getreceivefolder($store);
|
||||
$props = mapi_getprops($folder, [PR_ENTRYID]);
|
||||
$inboxEntryId = $props[PR_ENTRYID];
|
||||
}
|
||||
if (!is_null($folder)) {
|
||||
$flags = MAPI_DEFERRED_ERRORS;
|
||||
$eidObj = $GLOBALS["entryid"]->createMsgStoreEntryIdObj(hex2bin((string) $action['store_entryid']));
|
||||
if (isset($eidObj['MailboxDN'])) {
|
||||
$sharedUserSetting = $GLOBALS["settings"]->get(
|
||||
"grommunio/v1/contexts/hierarchy/shared_stores/" . bin2hex(strtolower((string) $eidObj['MailboxDN']))
|
||||
);
|
||||
if (isset($sharedUserSetting['all']) ||
|
||||
(isset($sharedUserSetting['inbox']['show_subfolders']) && $sharedUserSetting['inbox']['show_subfolders'])) {
|
||||
$flags |= CONVENIENT_DEPTH;
|
||||
}
|
||||
}
|
||||
$htable = mapi_folder_gethierarchytable($folder, $flags);
|
||||
$rows = mapi_table_queryallrows($htable, [PR_ENTRYID]);
|
||||
}
|
||||
// The inbox itself is not the hierarchy list, add it to the begin.
|
||||
if (!is_null($inboxEntryId)) {
|
||||
array_unshift($rows, [PR_ENTRYID => $inboxEntryId]);
|
||||
}
|
||||
}
|
||||
$data['item'] = [];
|
||||
foreach ($rows as $row) {
|
||||
$items = $GLOBALS["operations"]->getTable($store, $row[PR_ENTRYID], $this->properties, $this->sort, $this->start, $limit, $this->restriction);
|
||||
$data['item'] = array_merge($data['item'], $items['item']);
|
||||
if (count($data['item']) >= $limit) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
$data['page'] = [];
|
||||
$data['page']['start'] = 0;
|
||||
$data['page']['rowcount'] = 0;
|
||||
$data['page']['totalrowcount'] = count($data['item']);
|
||||
$data['search_meta'] = [];
|
||||
$data['search_meta']['searchfolder_entryid'] = null;
|
||||
$data['search_meta']['search_store_entryid'] = $action['store_entryid'];
|
||||
$data['search_meta']['searchstate'] = null;
|
||||
$data['search_meta']['results'] = count($data['item']);
|
||||
$data['folder'] = [];
|
||||
$data['folder']['content_count'] = count($data['item']);
|
||||
$data['folder']['content_unread'] = 0;
|
||||
}
|
||||
else {
|
||||
// Get the table and merge the arrays
|
||||
$data = $GLOBALS["operations"]->getTable($store, $entryid, $this->properties, $this->sort, $this->start, $limit, $this->restriction);
|
||||
}
|
||||
|
||||
// If the request come from search folder then no need to send folder information
|
||||
if (!$isSearchFolder && !isset($data['folder'])) {
|
||||
// Open the folder.
|
||||
$folder = mapi_msgstore_openentry($store, $entryid);
|
||||
$data["folder"] = [];
|
||||
|
||||
// Obtain some statistics from the folder contents
|
||||
$contentcount = mapi_getprops($folder, [PR_CONTENT_COUNT, PR_CONTENT_UNREAD]);
|
||||
if (isset($contentcount[PR_CONTENT_COUNT])) {
|
||||
$data["folder"]["content_count"] = $contentcount[PR_CONTENT_COUNT];
|
||||
}
|
||||
|
||||
if (isset($contentcount[PR_CONTENT_UNREAD])) {
|
||||
$data["folder"]["content_unread"] = $contentcount[PR_CONTENT_UNREAD];
|
||||
}
|
||||
}
|
||||
|
||||
$data = $this->filterPrivateItems($data);
|
||||
|
||||
// Allowing to hook in just before the data sent away to be sent to the client
|
||||
$GLOBALS['PluginManager']->triggerHook('server.module.listmodule.list.after', [
|
||||
'moduleObject' => &$this,
|
||||
'store' => $store,
|
||||
'entryid' => $entryid,
|
||||
'action' => $action,
|
||||
'data' => &$data,
|
||||
]);
|
||||
|
||||
// unset will remove the value but will not regenerate array keys, so we need to
|
||||
// do it here
|
||||
$data["item"] = array_values($data["item"]);
|
||||
$this->addActionData($actionType, $data);
|
||||
$GLOBALS["bus"]->addData($this->getResponseData());
|
||||
}
|
||||
}
|
||||
|
||||
private function buildFtsDescriptor($restriction) {
|
||||
return (new FtsRestrictionConverter($this->properties))->buildDescriptor($restriction);
|
||||
}
|
||||
|
||||
/**
|
||||
* Function will set search restrictions on search folder and start search process
|
||||
* and it will also parse visible columns and sorting data when sending results to client.
|
||||
*
|
||||
* @param resource $store MAPI message store
|
||||
* @param false|string $entryid entryid of the folder scope, or false when absent
|
||||
* @param array $action the action data, sent by the client
|
||||
* @param string $actionType the action type, sent by the client
|
||||
*/
|
||||
#[Override]
|
||||
public function search($store, $entryid, $action, $actionType) {
|
||||
$useSearchFolder = $action["use_searchfolder"] ?? false;
|
||||
$this->logFtsDebug('Search requested', [
|
||||
'store_entryid' => $action['store_entryid'] ?? null,
|
||||
'entryid' => $this->formatEntryIdForLog($entryid),
|
||||
'subfolders' => $action['subfolders'] ?? null,
|
||||
'use_searchfolder' => (bool) $useSearchFolder,
|
||||
'restriction_present' => array_key_exists('restriction', $action),
|
||||
]);
|
||||
if (!$useSearchFolder) {
|
||||
$this->logFtsDebug('Search fallback: store does not support search folders', []);
|
||||
|
||||
/*
|
||||
* store doesn't support search folders so we can't use this
|
||||
* method instead we will pass restriction to messageList and
|
||||
* it will give us the restricted results
|
||||
*/
|
||||
parent::messageList($store, $entryid, $action, "list");
|
||||
|
||||
return;
|
||||
}
|
||||
if (!is_string($entryid) || $entryid === '') {
|
||||
$this->sendFeedback(false);
|
||||
|
||||
return;
|
||||
}
|
||||
$store_props = mapi_getprops($store, [PR_MDB_PROVIDER, PR_DEFAULT_STORE, PR_IPM_SUBTREE_ENTRYID]);
|
||||
$this->logFtsDebug('Resolved store properties for search', [
|
||||
'provider' => isset($store_props[PR_MDB_PROVIDER]) ? bin2hex((string) $store_props[PR_MDB_PROVIDER]) : null,
|
||||
'default_store' => $store_props[PR_DEFAULT_STORE] ?? null,
|
||||
]);
|
||||
if ($store_props[PR_MDB_PROVIDER] == ZARAFA_STORE_PUBLIC_GUID) {
|
||||
/*
|
||||
* A public store cannot host a search folder (gromox answers
|
||||
* ecNotSupported), and public messages cannot be linked into a
|
||||
* private one either, so the usual "link the hits into a search
|
||||
* folder and read that folder" route is closed. Serve the hits
|
||||
* straight from the index instead; if there is no usable index,
|
||||
* fall back to the server-side restriction as before.
|
||||
*/
|
||||
if ($this->publicStoreSearch($store, $entryid, $action, "search", $this->publicStoreDomain($action))) {
|
||||
return true;
|
||||
}
|
||||
$this->logFtsDebug('Search fallback: public store without usable index', []);
|
||||
/*
|
||||
* Our own messageList() walks the folder hierarchy when the
|
||||
* request asks for subfolders; ListModule's does not and would
|
||||
* silently search the one folder, which is what made "include
|
||||
* subfolders" look broken on public folders.
|
||||
*/
|
||||
$this->messageList($store, $entryid, $action, "search");
|
||||
|
||||
return;
|
||||
}
|
||||
$todoListEntryId = TodoList::getEntryId();
|
||||
if ($todoListEntryId !== false && $GLOBALS['entryid']->compareEntryIds(bin2hex($entryid), bin2hex($todoListEntryId))) {
|
||||
$this->logFtsDebug('Search fallback: todo list uses legacy restriction path', []);
|
||||
|
||||
// todo list do not need to perform full text index search
|
||||
parent::messageList($store, $entryid, $action, "list");
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$this->searchFolderList = true; // Set to indicate this is not the normal folder, but a search folder
|
||||
$this->restriction = false;
|
||||
|
||||
// Parse Restriction
|
||||
$this->parseRestriction($action);
|
||||
if ($this->restriction == false) {
|
||||
$this->logFtsDebug('Restriction parsing failed', [
|
||||
'action_type' => $actionType,
|
||||
]);
|
||||
// if error in creating restriction then send error to client
|
||||
$errorInfo = [];
|
||||
$errorInfo["error_message"] = _("Error in search, please try again.");
|
||||
$errorInfo["original_error_message"] = "Error in parsing restrictions.";
|
||||
|
||||
return $this->sendSearchErrorToClient($store, $entryid, $action, $errorInfo);
|
||||
}
|
||||
$ftsDescriptor = $this->buildFtsDescriptor($this->restriction);
|
||||
if (empty($ftsDescriptor['ast'])) {
|
||||
$this->logFtsDebug('Failed to translate restriction to FTS descriptor', [
|
||||
'restriction_sample' => array_keys($this->restriction),
|
||||
]);
|
||||
$errorInfo = [];
|
||||
$errorInfo["error_message"] = _("Error in search, please try again.");
|
||||
$errorInfo["original_error_message"] = "Unable to translate search query to full-text expression.";
|
||||
|
||||
return $this->sendSearchErrorToClient($store, $entryid, $action, $errorInfo);
|
||||
}
|
||||
$serializedRestriction = serialize($this->restriction);
|
||||
$restrictionSignature = md5($serializedRestriction);
|
||||
$this->logFtsDebug('Restriction parsed for full-text search', [
|
||||
'restriction_signature' => $restrictionSignature,
|
||||
'fts_descriptor' => $ftsDescriptor,
|
||||
]);
|
||||
|
||||
if (isset($action['search_folder_entryid'])) {
|
||||
$this->sessionData['searchFolderEntryId'] = $action['search_folder_entryid'];
|
||||
}
|
||||
|
||||
// Each search gets its own freshly created search folder. We populate
|
||||
// the folder ourselves (entryid by entryid) instead of letting the
|
||||
// server run the criteria, so a reused folder would accumulate the
|
||||
// previous result set and, with two searches sharing one folder,
|
||||
// double-link the same message and stall the mailbox. A fresh folder
|
||||
// per search keeps the result set correct and isolates concurrent
|
||||
// searches from each other.
|
||||
$previousSearchFolderEntryId = $this->sessionData['searchFolderEntryId'] ?? null;
|
||||
$isSetSearchFolderEntryId = false;
|
||||
|
||||
// create or open search folder
|
||||
$searchFolder = $this->createSearchFolder($store, $isSetSearchFolderEntryId);
|
||||
if ($searchFolder === false) {
|
||||
if ($store_props[PR_MDB_PROVIDER] == ZARAFA_STORE_DELEGATE_GUID) {
|
||||
$this->messageList($store, $entryid, $action, "search");
|
||||
|
||||
return true;
|
||||
}
|
||||
// if error in creating search folder then send error to client
|
||||
$errorInfo = [];
|
||||
|
||||
$errorInfo["error_message"] = match (mapi_last_hresult()) {
|
||||
MAPI_E_NO_ACCESS => _("Unable to perform search query, no permissions to create search folder."),
|
||||
MAPI_E_NOT_FOUND => _("Unable to perform search query, search folder not found."),
|
||||
default => _("Unable to perform search query, store might not support searching."),
|
||||
};
|
||||
|
||||
$errorInfo["original_error_message"] = _("Error in creating search folder.");
|
||||
|
||||
return $this->sendSearchErrorToClient($store, $entryid, $action, $errorInfo);
|
||||
}
|
||||
|
||||
// Retire the folder used by the previous search in this session now
|
||||
// that a fresh one is in place, so old search folders do not pile up.
|
||||
if ($previousSearchFolderEntryId !== null &&
|
||||
$previousSearchFolderEntryId !== ($this->sessionData['searchFolderEntryId'] ?? null)) {
|
||||
$searchFolderRoot = $this->getSearchFoldersRoot($store);
|
||||
if ($searchFolderRoot !== false) {
|
||||
$this->safeDeleteSearchFolder($searchFolderRoot, hex2bin((string) $previousSearchFolderEntryId));
|
||||
}
|
||||
}
|
||||
|
||||
$subfolder_flag = 0;
|
||||
$recursive = false;
|
||||
if (isset($action["subfolders"]) && $action["subfolders"] == "true") {
|
||||
$recursive = true;
|
||||
$subfolder_flag = RECURSIVE_SEARCH;
|
||||
}
|
||||
|
||||
$entryids = (array) $entryid;
|
||||
|
||||
$searchFolderEntryId = $this->sessionData['searchFolderEntryId'];
|
||||
|
||||
// check if searchcriteria has changed
|
||||
$restrictionCheck = md5($serializedRestriction . $searchFolderEntryId . $subfolder_flag);
|
||||
|
||||
// check if there is need to set searchcriteria again
|
||||
if (!isset($this->sessionData['searchCriteriaCheck']) || $restrictionCheck != $this->sessionData['searchCriteriaCheck']) {
|
||||
if (!empty($this->sessionData['searchOriginalEntryids']) &&
|
||||
isset($action['entryid']) &&
|
||||
in_array($action['entryid'], $this->sessionData['searchOriginalEntryids'])
|
||||
) {
|
||||
// get entryids of original folders, and use it to set new search criteria
|
||||
$entryids = [];
|
||||
$entryIdsCount = count($this->sessionData['searchOriginalEntryids']);
|
||||
for ($index = 0; $index < $entryIdsCount; ++$index) {
|
||||
$entryids[] = hex2bin((string) $this->sessionData['searchOriginalEntryids'][$index]);
|
||||
}
|
||||
}
|
||||
else {
|
||||
// store entryids of original folders, so that can be used for re-setting the search criteria if needed
|
||||
$this->sessionData['searchOriginalEntryids'] = [];
|
||||
for ($index = 0, $len = count($entryids); $index < $len; ++$index) {
|
||||
$this->sessionData['searchOriginalEntryids'][] = bin2hex($entryids[$index]);
|
||||
}
|
||||
}
|
||||
// we never start the search folder because we will populate the search folder by ourselves
|
||||
mapi_folder_setsearchcriteria($searchFolder, $this->restriction, $entryids, $subfolder_flag | STOP_SEARCH);
|
||||
$this->logFtsDebug('Search criteria updated', [
|
||||
'search_folder_entryid' => $searchFolderEntryId,
|
||||
'restriction_signature' => $restrictionSignature,
|
||||
'recursive' => $recursive,
|
||||
'scope_entryids' => $this->formatEntryIdForLog($entryids),
|
||||
]);
|
||||
$this->sessionData['searchCriteriaCheck'] = $restrictionCheck;
|
||||
}
|
||||
|
||||
if (isset($this->sessionData['searchCriteriaCheck']) || $restrictionCheck == $this->sessionData['searchCriteriaCheck']) {
|
||||
$folderEntryid = bin2hex($entryid);
|
||||
if ($this->sessionData['searchOriginalEntryids'][0] !== $folderEntryid) {
|
||||
$this->sessionData['searchOriginalEntryids'][0] = $folderEntryid;
|
||||
// we never start the search folder because we will populate the search folder by ourselves
|
||||
mapi_folder_setsearchcriteria($searchFolder, $this->restriction, [$entryid], $subfolder_flag | STOP_SEARCH);
|
||||
$this->logFtsDebug('Search criteria refreshed for active folder', [
|
||||
'search_folder_entryid' => $searchFolderEntryId,
|
||||
'restriction_signature' => $restrictionSignature,
|
||||
'target_entryid' => $this->formatEntryIdForLog($entryid),
|
||||
'recursive' => $recursive,
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
// Sort; multi-instance is folded back into one row per item by getTable()
|
||||
$this->parseSortOrder($action, null, true);
|
||||
// Initialize search patterns with default values
|
||||
if (is_array($ftsDescriptor['message_classes']) &&
|
||||
count($ftsDescriptor['message_classes']) >= 7) {
|
||||
$ftsDescriptor['message_classes'] = null;
|
||||
}
|
||||
|
||||
$username = null;
|
||||
$indexDB = null;
|
||||
if ($store_props[PR_MDB_PROVIDER] == ZARAFA_STORE_DELEGATE_GUID) {
|
||||
$eidObj = $GLOBALS["entryid"]->createMsgStoreEntryIdObj(hex2bin((string) $action['store_entryid']));
|
||||
$username = $eidObj['ServerShortname'];
|
||||
$session = $GLOBALS["mapisession"]->getSession();
|
||||
|
||||
if ($username) {
|
||||
$indexDB = new IndexSqlite($username, $session, $store);
|
||||
}
|
||||
}
|
||||
else {
|
||||
$indexDB = new IndexSqlite();
|
||||
}
|
||||
if (!($indexDB instanceof IndexSqlite) || !$indexDB->is_open()) {
|
||||
return parent::search($store, $entryid, $action, $actionType);
|
||||
}
|
||||
|
||||
$this->logFtsDebug('Dispatching search to index backend', [
|
||||
'search_folder_entryid' => $searchFolderEntryId,
|
||||
'restriction_signature' => $restrictionSignature,
|
||||
'recursive' => $recursive,
|
||||
'delegate_username' => $username,
|
||||
'message_classes' => $ftsDescriptor['message_classes'] ?? null,
|
||||
'filters' => [
|
||||
'date_start' => $ftsDescriptor['date_start'] ?? null,
|
||||
'date_end' => $ftsDescriptor['date_end'] ?? null,
|
||||
'unread' => !empty($ftsDescriptor['unread']),
|
||||
'has_attachments' => !empty($ftsDescriptor['has_attachments']),
|
||||
],
|
||||
'ast' => $ftsDescriptor['ast'] ?? null,
|
||||
]);
|
||||
|
||||
$search_result = $indexDB->search(hex2bin((string) $searchFolderEntryId), $ftsDescriptor, $entryid, $recursive);
|
||||
if ($search_result === false) {
|
||||
$this->logFtsDebug('Index search returned no data', [
|
||||
'search_folder_entryid' => $searchFolderEntryId,
|
||||
'restriction_signature' => $restrictionSignature,
|
||||
'recursive' => $recursive,
|
||||
]);
|
||||
$errorInfo = [];
|
||||
$errorInfo["error_message"] = _("Unable to perform search query, store might not support searching.");
|
||||
$errorInfo["original_error_message"] = "Full-text search backend returned no result set.";
|
||||
|
||||
return $this->sendSearchErrorToClient($store, $entryid, $action, $errorInfo);
|
||||
}
|
||||
|
||||
unset($action["restriction"]);
|
||||
|
||||
// Get the table and merge the arrays
|
||||
$table = $GLOBALS["operations"]->getTable($store, hex2bin((string) $searchFolderEntryId), $this->properties, $this->sort, $this->start);
|
||||
$this->logFtsDebug('Search folder table retrieved', [
|
||||
'search_folder_entryid' => $searchFolderEntryId,
|
||||
'table_item_count' => isset($table['item']) ? count($table['item']) : null,
|
||||
'start' => $this->start,
|
||||
'sort' => $this->sort,
|
||||
]);
|
||||
// Create the data array, which will be send back to the client
|
||||
$data = [];
|
||||
$data = array_merge($data, $table);
|
||||
|
||||
$this->getDelegateFolderInfo($store);
|
||||
$data = $this->filterPrivateItems($data);
|
||||
$this->logFtsDebug('Search results filtered for privacy', [
|
||||
'search_folder_entryid' => $searchFolderEntryId,
|
||||
'item_count_after_filter' => isset($data['item']) ? count($data['item']) : null,
|
||||
]);
|
||||
|
||||
// remember which entryid's are send to the client
|
||||
$searchResults = [];
|
||||
foreach ($table["item"] as $item) {
|
||||
// store entryid => last_modification_time mapping
|
||||
$searchResults[$item["entryid"]] = $item["props"]["last_modification_time"];
|
||||
}
|
||||
|
||||
// store search results into session data
|
||||
if (!isset($this->sessionData['searchResults'])) {
|
||||
$this->sessionData['searchResults'] = [];
|
||||
}
|
||||
$this->sessionData['searchResults'][$searchFolderEntryId] = $searchResults;
|
||||
$this->logFtsDebug('Search results stored in session', [
|
||||
'search_folder_entryid' => $searchFolderEntryId,
|
||||
'result_count' => count($searchResults),
|
||||
]);
|
||||
|
||||
$result = mapi_folder_getsearchcriteria($searchFolder);
|
||||
$this->logFtsDebug('Search folder state retrieved', [
|
||||
'search_folder_entryid' => $searchFolderEntryId,
|
||||
'searchstate' => $result['searchstate'] ?? null,
|
||||
]);
|
||||
|
||||
$data["search_meta"] = [];
|
||||
$data["search_meta"]["searchfolder_entryid"] = $searchFolderEntryId;
|
||||
$data["search_meta"]["search_store_entryid"] = $action["store_entryid"];
|
||||
$data["search_meta"]["searchstate"] = $result["searchstate"];
|
||||
$data["search_meta"]["results"] = count($searchResults);
|
||||
|
||||
// Reopen the search folder, because otherwise the suggestion property will
|
||||
// not have been updated
|
||||
$searchFolder = $this->createSearchFolder($store, true);
|
||||
$storeProps = mapi_getprops($searchFolder, [PR_EC_SUGGESTION]);
|
||||
if (isset($storeProps[PR_EC_SUGGESTION])) {
|
||||
$data["search_meta"]["suggestion"] = $storeProps[PR_EC_SUGGESTION];
|
||||
$this->logFtsDebug('Search suggestion ready', [
|
||||
'search_folder_entryid' => $searchFolderEntryId,
|
||||
'suggestion' => $storeProps[PR_EC_SUGGESTION],
|
||||
]);
|
||||
}
|
||||
|
||||
$this->addActionData("search", $data);
|
||||
$GLOBALS["bus"]->addData($this->getResponseData());
|
||||
|
||||
$this->logFtsDebug('Search response dispatched to client', [
|
||||
'search_folder_entryid' => $searchFolderEntryId,
|
||||
'items_returned' => isset($data['item']) ? count($data['item']) : null,
|
||||
'search_meta' => $data['search_meta'] ?? null,
|
||||
]);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
private function logFtsDebug(string $message, array $context = []): void {
|
||||
if (!DEBUG_FULLTEXT_SEARCH) {
|
||||
return;
|
||||
}
|
||||
$prefix = '[fts-debug][module] ';
|
||||
if (!empty($context)) {
|
||||
$encoded = json_encode($context, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
|
||||
if ($encoded === false) {
|
||||
$encoded = 'context_encoding_failed';
|
||||
}
|
||||
error_log($prefix . $message . ' ' . $encoded);
|
||||
}
|
||||
else {
|
||||
error_log($prefix . $message);
|
||||
}
|
||||
}
|
||||
|
||||
private function formatEntryIdForLog($entryid) {
|
||||
if ($entryid === null) {
|
||||
return null;
|
||||
}
|
||||
if (is_array($entryid)) {
|
||||
return array_map([$this, 'formatEntryIdForLog'], $entryid);
|
||||
}
|
||||
if (!is_string($entryid)) {
|
||||
return $entryid;
|
||||
}
|
||||
if ($entryid === '') {
|
||||
return '';
|
||||
}
|
||||
if (preg_match('/[^\x20-\x7E]/', $entryid)) {
|
||||
return bin2hex($entryid);
|
||||
}
|
||||
|
||||
return $entryid;
|
||||
}
|
||||
}
|
||||
+399
@@ -0,0 +1,399 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* SPDX-FileCopyrightText: Copyright 2020 - 2026 grommunio GmbH
|
||||
* SPDX-FileCopyrightText: Copyright 2016 Kopano and its licensors
|
||||
* SPDX-FileCopyrightText: Copyright 2005 - 2016 Zarafa B.V. and its licensors
|
||||
* SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
*/
|
||||
|
||||
/**
|
||||
* Appointment ItemModule
|
||||
* Module which opens, creates, saves and deletes an item. It
|
||||
* extends the Module class.
|
||||
*/
|
||||
class AppointmentItemModule extends ItemModule {
|
||||
/**
|
||||
* @var string client or server IANA timezone
|
||||
*/
|
||||
protected $tziana;
|
||||
|
||||
/**
|
||||
* @var bool|string client timezone definition
|
||||
*/
|
||||
protected $tzdef;
|
||||
|
||||
/**
|
||||
* Constructor.
|
||||
*
|
||||
* @param int $id unique id
|
||||
* @param array $data list of all actions
|
||||
*/
|
||||
public function __construct($id, $data) {
|
||||
parent::__construct($id, $data);
|
||||
|
||||
$this->properties = $GLOBALS['properties']->getAppointmentProperties();
|
||||
|
||||
$this->plaintext = false;
|
||||
$this->skipCopyProperties = [
|
||||
$this->properties['goid'],
|
||||
$this->properties['goid2'],
|
||||
$this->properties['request_sent'],
|
||||
PR_OWNER_APPT_ID,
|
||||
];
|
||||
|
||||
$this->tziana = 'Etc/UTC';
|
||||
$this->tzdef = false;
|
||||
}
|
||||
|
||||
#[Override]
|
||||
public function open($store, $entryid, $action) {
|
||||
if ($store && $entryid) {
|
||||
$data = [];
|
||||
|
||||
$message = $GLOBALS['operations']->openMessage($store, $entryid);
|
||||
|
||||
if (empty($message)) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Open embedded message if requested
|
||||
$attachNum = !empty($action['attach_num']) ? $action['attach_num'] : false;
|
||||
if ($attachNum) {
|
||||
// get message props of sub message
|
||||
$parentMessage = $message;
|
||||
$message = $GLOBALS['operations']->openMessage($store, $entryid, $attachNum);
|
||||
|
||||
if (empty($message)) {
|
||||
return;
|
||||
}
|
||||
|
||||
$data['item'] = $GLOBALS['operations']->getEmbeddedMessageProps($store, $message, $this->properties, $parentMessage, $attachNum);
|
||||
}
|
||||
else {
|
||||
// add all standard properties from the series/normal message
|
||||
$data['item'] = $GLOBALS['operations']->getMessageProps($store, $message, $this->properties, $this->plaintext, true);
|
||||
}
|
||||
|
||||
if (!empty($action["timezone_iana"])) {
|
||||
$this->tziana = $action["timezone_iana"];
|
||||
$this->tzdef = TimezoneUtil::GetBinaryTZ($action['timezone_iana']);
|
||||
}
|
||||
|
||||
// if appointment is recurring then only we should get properties of occurrence if basedate is supplied
|
||||
if ($data['item']['props']['recurring'] === true) {
|
||||
if (!empty($action['basedate'])) {
|
||||
// check for occurrence/exception
|
||||
$basedate = $action['basedate'];
|
||||
|
||||
$recur = new Recurrence($store, $message);
|
||||
|
||||
$exceptionatt = $recur->getExceptionAttachment($basedate);
|
||||
|
||||
// Single occurrences are never recurring
|
||||
$data['item']['props']['recurring'] = false;
|
||||
|
||||
if ($exceptionatt) {
|
||||
// Existing exception (open existing item, which includes basedate)
|
||||
$exceptionattProps = mapi_getprops($exceptionatt, [PR_ATTACH_NUM]);
|
||||
$exception = mapi_attach_openobj($exceptionatt, 0);
|
||||
|
||||
// overwrite properties with the ones from the exception
|
||||
$exceptionProps = $GLOBALS['operations']->getMessageProps($store, $exception, $this->properties, $this->plaintext, true);
|
||||
|
||||
/*
|
||||
* If recurring item has set reminder to true then
|
||||
* all occurrences before the 'flagdueby' value(of recurring item)
|
||||
* should not show that reminder is set.
|
||||
*/
|
||||
if (isset($exceptionProps['props']['reminder']) && $data['item']['props']['reminder'] == true) {
|
||||
$flagDueByDay = $recur->dayStartOf($data['item']['props']['flagdueby']);
|
||||
|
||||
if ($flagDueByDay > $basedate) {
|
||||
$exceptionProps['props']['reminder'] = false;
|
||||
}
|
||||
}
|
||||
|
||||
// The properties must be merged, if the recipients or attachments are present in the exception
|
||||
// then that list should be used. Otherwise the list from the series must be applied (this
|
||||
// corresponds with OL2007).
|
||||
// @FIXME getMessageProps should not return empty string if exception doesn't contain body
|
||||
// by this change we can handle a situation where user has set empty string in the body explicitly
|
||||
if (!empty($exceptionProps['props']['body']) || !empty($exceptionProps['props']['html_body'])) {
|
||||
if (!empty($exceptionProps['props']['body'])) {
|
||||
$data['item']['props']['body'] = $exceptionProps['props']['body'];
|
||||
}
|
||||
|
||||
if (!empty($exceptionProps['props']['html_body'])) {
|
||||
$data['item']['props']['html_body'] = $exceptionProps['props']['html_body'];
|
||||
}
|
||||
|
||||
$data['item']['props']['isHTML'] = $exceptionProps['props']['isHTML'];
|
||||
}
|
||||
// remove properties from $exceptionProps so array_merge will not overwrite it
|
||||
unset($exceptionProps['props']['html_body'], $exceptionProps['props']['body'], $exceptionProps['props']['isHTML']);
|
||||
|
||||
$data['item']['props'] = array_merge($data['item']['props'], $exceptionProps['props']);
|
||||
if (isset($exceptionProps['recipients'])) {
|
||||
$data['item']['recipients'] = $exceptionProps['recipients'];
|
||||
}
|
||||
|
||||
if (isset($exceptionProps['attachments'])) {
|
||||
$data['item']['attachments'] = $exceptionProps['attachments'];
|
||||
}
|
||||
|
||||
// Make sure we are using the passed basedate and not something wrong in the opened item
|
||||
$data['item']['props']['basedate'] = $basedate;
|
||||
$data['item']['attach_num'] = [$exceptionattProps[PR_ATTACH_NUM]];
|
||||
}
|
||||
elseif ($recur->isDeleteException($basedate)) {
|
||||
// Exception is deleted, should not happen, but if it the case then give error
|
||||
$this->sendFeedback(
|
||||
false,
|
||||
[
|
||||
'type' => ERROR_GROMMUNIO,
|
||||
'info' => [
|
||||
'original_message' => _('Could not open occurrence.'),
|
||||
'display_message' => _('Could not open occurrence, specific occurrence is probably deleted.'),
|
||||
],
|
||||
]
|
||||
);
|
||||
|
||||
return;
|
||||
}
|
||||
else {
|
||||
// opening an occurrence of a recurring series (same as normal open, but add basedate, startdate and enddate)
|
||||
$data['item']['props']['basedate'] = $basedate;
|
||||
$data['item']['props']['startdate'] = $recur->getOccurrenceStart($basedate);
|
||||
$data['item']['props']['duedate'] = $recur->getOccurrenceEnd($basedate);
|
||||
$data['item']['props']['commonstart'] = $data['item']['props']['startdate'];
|
||||
$data['item']['props']['commonend'] = $data['item']['props']['duedate'];
|
||||
unset($data['item']['props']['reminder_time']);
|
||||
}
|
||||
}
|
||||
else {
|
||||
// Opening a recurring series, get the recurrence information
|
||||
$recur = new Recurrence($store, $message);
|
||||
$recurpattern = $recur->getRecurrence();
|
||||
$tz = $recur->tz; // no function to do this at the moment
|
||||
|
||||
// Add the recurrence pattern to the data
|
||||
if (isset($recurpattern) && is_array($recurpattern)) {
|
||||
$data['item']['props'] += $recurpattern;
|
||||
}
|
||||
|
||||
// Add the timezone information to the data
|
||||
if (isset($tz) && is_array($tz)) {
|
||||
$data['item']['props'] += $tz;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Fix for all-day events which have a different timezone than the user's browser
|
||||
if ($data['item']['props']['alldayevent'] == 1 && $this->tzdef !== false) {
|
||||
$this->processAllDayItem($store, $data['item'], $message);
|
||||
}
|
||||
|
||||
// Send the data
|
||||
$this->addActionData('item', $data);
|
||||
$GLOBALS['bus']->addData($this->getResponseData());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Function does customization of exception based on module data.
|
||||
* like, here it will generate display message based on actionType
|
||||
* for particular exception.
|
||||
*
|
||||
* @param object $e Exception object
|
||||
* @param string $actionType the action type, sent by the client
|
||||
* @param resource $store MAPI store containing the message
|
||||
* @param string $parententryid parent entryid of the message
|
||||
* @param string $entryid entryid of the message
|
||||
* @param array $action the action data, sent by the client
|
||||
*/
|
||||
#[Override]
|
||||
public function handleException(&$e, $actionType = null, $store = null, $parententryid = null, $entryid = null, $action = null) {
|
||||
if (is_null($e->displayMessage)) {
|
||||
switch ($actionType) {
|
||||
case "save":
|
||||
if ($e->getCode() == MAPI_E_NO_ACCESS) {
|
||||
if ($store === null || $store === false || !$entryid) {
|
||||
break;
|
||||
}
|
||||
$message = mapi_msgstore_openentry($store, $entryid);
|
||||
$messageProps = mapi_getprops($message, [PR_MESSAGE_CLASS, PR_ENTRYID, PR_PARENT_ENTRYID, PR_STORE_ENTRYID]);
|
||||
$messageClass = $messageProps[PR_MESSAGE_CLASS];
|
||||
|
||||
$msg = $messageClass !== "IPM.Appointment" ?
|
||||
_('You have insufficient privileges to move a meeting request in this calendar. The calendar owner can set these using the \'permissions\'-tab of the folder properties (right click the calendar folder > properties > permissions)') :
|
||||
_('You have insufficient privileges to move an appointment in this calendar. The calendar owner can set these using the \'permissions\'-tab of the folder properties (right click the calendar folder > properties > permissions)');
|
||||
|
||||
$e->setDisplayMessage($msg);
|
||||
$e->setTitle(_('Insufficient privileges'));
|
||||
|
||||
// Need this notification to refresh the calendar.
|
||||
$GLOBALS['bus']->notify(bin2hex((string) $parententryid), TABLE_DELETE, $messageProps);
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
parent::handleException($e, $actionType, $store, $parententryid, $entryid, $action);
|
||||
}
|
||||
|
||||
/**
|
||||
* Save the give appointment or meeting request to the calendar.
|
||||
*
|
||||
* @param resource $store MAPI store of the message
|
||||
* @param string $parententryid Parent entryid of the message (folder entryid, NOT message entryid)
|
||||
* @param string $entryid entryid of the message
|
||||
* @param array $action Action array containing json request
|
||||
* @param string $actionType The action type which triggered this action
|
||||
*/
|
||||
#[Override]
|
||||
public function save($store, $parententryid, $entryid, $action, $actionType = 'save') {
|
||||
$result = false;
|
||||
|
||||
// The read flag belongs to the message itself, so it is set directly: going
|
||||
// through saveAppointment() would write an exception into a series as soon as
|
||||
// one of its occurrences is marked read.
|
||||
if ($entryid && isset($action['props']['message_flags'])) {
|
||||
$flagProps = [];
|
||||
$GLOBALS['operations']->setMessageFlag($store, $entryid, $action['props']['message_flags'], $action['message_action'] ?? false, $flagProps);
|
||||
unset($action['props']['message_flags']);
|
||||
|
||||
// the client sends its timezone along with every save, it is not a change
|
||||
$changed = $action['props'];
|
||||
unset($changed['timezone_iana']);
|
||||
|
||||
if (empty($changed) && empty($action['recipients']) && empty($action['attachments'])) {
|
||||
$GLOBALS['bus']->notify(bin2hex((string) $parententryid), TABLE_SAVE, $flagProps);
|
||||
$this->sendFeedback(true);
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
// Save appointment (saveAppointment takes care of creating/modifying exceptions to recurring
|
||||
// items if necessary)
|
||||
$messageProps = $GLOBALS['operations']->saveAppointment($store, $entryid, $parententryid, $action, $actionType, $this->directBookingMeetingRequest);
|
||||
|
||||
// Notify the bus if the save was OK
|
||||
if ($messageProps && !(is_array($messageProps) && isset($messageProps['error'])) && !isset($messageProps['remindertimeerror'])) {
|
||||
$GLOBALS['bus']->notify(bin2hex($parententryid), TABLE_SAVE, $messageProps);
|
||||
$result = true;
|
||||
}
|
||||
|
||||
$errorMsg = false;
|
||||
if (!$result && isset($messageProps['remindertimeerror']) && !$messageProps['remindertimeerror']) {
|
||||
$errorMsg = _('Cannot set a reminder to appear before the previous occurrence. Reset reminder to save the change');
|
||||
}
|
||||
elseif (isset($messageProps['isexceptionallowed']) && $messageProps['isexceptionallowed'] === false) {
|
||||
$errorMsg = _('Two occurrences cannot occur on the same day');
|
||||
}
|
||||
elseif (is_array($messageProps) && isset($messageProps['error'])) {
|
||||
$errorMsg = match ($messageProps['error']) {
|
||||
1 => sprintf(_('You marked \'%s\' as a resource. You cannot schedule a meeting with \'%s\' because you do not have the appropriate permissions for that account. Either enter the name as a required or optional attendee or talk to your administrator about giving you permission to schedule \'%s\'.'), $messageProps['displayname'], $messageProps['displayname'], $messageProps['displayname']),
|
||||
2 => sprintf(_('\'%s\' has declined your meeting because \'%s\' does not automatically accept meeting requests.'), $messageProps['displayname'], $messageProps['displayname']),
|
||||
3 => sprintf(_('\'%s\' has declined your meeting because it is recurring. You must book each meeting separately with this resource.'), $messageProps['displayname']),
|
||||
4 => sprintf(_('\'%s\' is already booked for this specified time. You must use another time or find another resource.'), $messageProps['displayname']),
|
||||
default => _('Meeting was not scheduled.'),
|
||||
};
|
||||
}
|
||||
else {
|
||||
// Recurring but non-existing exception (same as normal open, but add basedate, startdate and enddate)
|
||||
$data = [];
|
||||
if ($result) {
|
||||
$data = Conversion::mapMAPI2XML($this->properties, $messageProps);
|
||||
|
||||
// Get recipient information from the saved appointment to update client side
|
||||
// according to the latest recipient related changes only if changes requested from client.
|
||||
$savedAppointment = $GLOBALS['operations']->openMessage($store, $messageProps[PR_ENTRYID]);
|
||||
if (!empty($action['recipients'])) {
|
||||
$recipients = $GLOBALS["operations"]->getRecipientsInfo($savedAppointment);
|
||||
if (!empty($recipients)) {
|
||||
$data["recipients"] = [
|
||||
"item" => $recipients,
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
// Get attachments information from the saved appointment to update client side
|
||||
// according to the latest attachments related changes only if changes requested from client.
|
||||
if (!empty($action['attachments'])) {
|
||||
$attachments = $GLOBALS["operations"]->getAttachmentsInfo($savedAppointment);
|
||||
if (!empty($attachments)) {
|
||||
$data["attachments"] = [
|
||||
"item" => $attachments,
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
$data['action_response'] = [
|
||||
'resources_booked' => $this->directBookingMeetingRequest,
|
||||
];
|
||||
|
||||
if (isset($action['message_action'], $action['message_action']['paste'])) {
|
||||
$data['action_response']['resources_pasted'] = true;
|
||||
}
|
||||
}
|
||||
else {
|
||||
if (!empty($action['message_action']['send'])) {
|
||||
$errorMsg = _('Meeting could not be sent.');
|
||||
}
|
||||
else {
|
||||
$errorMsg = _('Meeting could not be saved.');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if ($errorMsg === false) {
|
||||
$this->addActionData('update', ['item' => $data]);
|
||||
$GLOBALS['bus']->addData($this->getResponseData());
|
||||
}
|
||||
else {
|
||||
$this->sendFeedback(false, [
|
||||
'type' => ERROR_GROMMUNIO,
|
||||
'info' => [
|
||||
'display_message' => $errorMsg,
|
||||
],
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Processes an all-day item and calculates the correct starttime if necessary.
|
||||
*
|
||||
* @param resource $store
|
||||
* @param array $calendaritem
|
||||
* @param resource $message
|
||||
*/
|
||||
private function processAllDayItem(/* @scrutinizer ignore-unused */ $store, &$calendaritem, /* @scrutinizer ignore-unused */ $message) {
|
||||
// If the appointment doesn't have tzdefstart property, it was probably
|
||||
// created on a mobile device (mobile devices do not send a timezone for
|
||||
// all-day events).
|
||||
$isTzdefstartSet = isset($calendaritem['props']['tzdefstart']);
|
||||
$tzdefstart = $isTzdefstartSet ?
|
||||
hex2bin((string) $calendaritem['props']['tzdefstart']) :
|
||||
mapi_ianatz_to_tzdef("Etc/UTC");
|
||||
|
||||
// Compare the timezone definitions of the client and the appointment.
|
||||
// Further processing is only required if they don't match.
|
||||
if ($isTzdefstartSet && $GLOBALS['entryid']->compareEntryIds($this->tzdef, $tzdefstart)) {
|
||||
return;
|
||||
}
|
||||
|
||||
$duration = $calendaritem['props']['duedate'] - $calendaritem['props']['startdate'];
|
||||
if (!$isTzdefstartSet) {
|
||||
$localStart = getLocalStart($calendaritem['props']['startdate'], $this->tziana);
|
||||
}
|
||||
else {
|
||||
$localStart = TimezoneUtil::ConvertAllDayStart($calendaritem['props']['startdate'], $tzdefstart, $this->tzdef);
|
||||
if ($localStart === null) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
$calendaritem['props']['startdate'] = $calendaritem['props']['commonstart'] = $localStart;
|
||||
$calendaritem['props']['duedate'] = $calendaritem['props']['commonend'] = $localStart + $duration;
|
||||
}
|
||||
}
|
||||
+802
@@ -0,0 +1,802 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* SPDX-FileCopyrightText: Copyright 2020 - 2026 grommunio GmbH
|
||||
* SPDX-FileCopyrightText: Copyright 2016 Kopano and its licensors
|
||||
* SPDX-FileCopyrightText: Copyright 2005 - 2016 Zarafa B.V. and its licensors
|
||||
* SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
*/
|
||||
|
||||
/**
|
||||
* Appointment Module.
|
||||
*/
|
||||
class AppointmentListModule extends ListModule {
|
||||
/**
|
||||
* @var false|int start of the visible interval as a Unix timestamp
|
||||
*/
|
||||
private $startdate;
|
||||
|
||||
/**
|
||||
* @var false|int end of the visible interval as a Unix timestamp
|
||||
*/
|
||||
private $enddate;
|
||||
|
||||
/**
|
||||
* @var string client or server IANA timezone
|
||||
*/
|
||||
protected $tziana;
|
||||
|
||||
/**
|
||||
* @var bool|string client timezone definition
|
||||
*/
|
||||
protected $tzdef;
|
||||
|
||||
/**
|
||||
* @var int number of appointments skipped while processing a list request
|
||||
*/
|
||||
private $skippedCount = 0;
|
||||
|
||||
/**
|
||||
* @var string first skipped appointment subjects to include in the client message
|
||||
*/
|
||||
private $skippedInfo = "";
|
||||
|
||||
/**
|
||||
* Constructor.
|
||||
*
|
||||
* @param int $id unique id
|
||||
* @param array $data list of all actions
|
||||
*/
|
||||
public function __construct($id, $data) {
|
||||
parent::__construct($id, $data);
|
||||
|
||||
$this->properties = $GLOBALS["properties"]->getAppointmentListProperties();
|
||||
|
||||
$this->startdate = false;
|
||||
$this->enddate = false;
|
||||
$this->tziana = 'Etc/UTC';
|
||||
$this->tzdef = false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates the notifiers for this module,
|
||||
* and register them to the Bus.
|
||||
*/
|
||||
public function createNotifiers() {
|
||||
$entryid = $this->getEntryID();
|
||||
$GLOBALS["bus"]->registerNotifier('appointmentlistnotifier', $entryid);
|
||||
}
|
||||
|
||||
/**
|
||||
* Normalize paired message stores and folder entry IDs and discard failed opens.
|
||||
*
|
||||
* @param array<int, false|resource>|false|resource $store MAPI message store or stores
|
||||
* @param array<int, false|string>|false|string $entryid folder entry ID or IDs
|
||||
*
|
||||
* @return array{0: resource[], 1: string[]} valid store/folder pairs
|
||||
*/
|
||||
private function normalizeStoreEntryIds($store, $entryid) {
|
||||
$stores = is_array($store) ? $store : [$store];
|
||||
$entryids = is_array($entryid) ? $entryid : [$entryid];
|
||||
if (count($stores) !== count($entryids)) {
|
||||
return [[], []];
|
||||
}
|
||||
|
||||
$validStores = [];
|
||||
$validEntryids = [];
|
||||
foreach ($stores as $index => $messageStore) {
|
||||
$folderEntryid = $entryids[$index];
|
||||
if ($messageStore === false || !is_string($folderEntryid) || $folderEntryid === '') {
|
||||
continue;
|
||||
}
|
||||
|
||||
$validStores[] = $messageStore;
|
||||
$validEntryids[] = $folderEntryid;
|
||||
}
|
||||
|
||||
return [$validStores, $validEntryids];
|
||||
}
|
||||
|
||||
/**
|
||||
* Executes all the actions in the $data variable.
|
||||
*/
|
||||
#[Override]
|
||||
public function execute() {
|
||||
foreach ($this->data as $actionType => $action) {
|
||||
if (!isset($actionType)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
try {
|
||||
$store = $this->getActionStore($action);
|
||||
$entryid = $this->getActionEntryID($action);
|
||||
|
||||
switch ($actionType) {
|
||||
case "list":
|
||||
$this->messageList($store, $entryid, $action, $actionType);
|
||||
break;
|
||||
|
||||
case "search":
|
||||
// @FIXME add functionality to handle private items
|
||||
$this->search($store, $entryid, $action, $actionType);
|
||||
break;
|
||||
|
||||
case "updatesearch":
|
||||
if ($store === false || is_array($store) || is_array($entryid)) {
|
||||
$this->sendFeedback(false);
|
||||
|
||||
break;
|
||||
}
|
||||
$this->updatesearch($store, $entryid, $action);
|
||||
break;
|
||||
|
||||
case "stopsearch":
|
||||
if ($store === false || is_array($store) || is_array($entryid)) {
|
||||
$this->sendFeedback(false);
|
||||
|
||||
break;
|
||||
}
|
||||
$this->stopSearch($store, $entryid, $action);
|
||||
break;
|
||||
|
||||
default:
|
||||
$this->handleUnknownActionType($actionType);
|
||||
}
|
||||
}
|
||||
catch (MAPIException $e) {
|
||||
if (isset($action['suppress_exception']) && $action['suppress_exception'] === true) {
|
||||
$e->setNotificationType('console');
|
||||
}
|
||||
$this->processException($e, $actionType);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Function which retrieves a list of calendar items in a calendar folder.
|
||||
*
|
||||
* @param array<int, false|resource>|false|resource $store MAPI message store or stores
|
||||
* @param array<int, false|string>|false|string $entryid entryid of the folder or folders
|
||||
* @param array $action the action data, sent by the client
|
||||
* @param string $actionType the action type, sent by the client
|
||||
*/
|
||||
#[Override]
|
||||
public function messageList($store, $entryid, $action, $actionType) {
|
||||
[$store, $entryid] = $this->normalizeStoreEntryIds($store, $entryid);
|
||||
if ($store === []) {
|
||||
return;
|
||||
}
|
||||
// initialize start and due date with false value so it will not take values from previous request
|
||||
$this->startdate = false;
|
||||
$this->enddate = false;
|
||||
$this->skippedCount = 0;
|
||||
$this->skippedInfo = "";
|
||||
|
||||
if (isset($action["restriction"])) {
|
||||
if (isset($action["restriction"]["startdate"])) {
|
||||
$this->startdate = $action["restriction"]["startdate"];
|
||||
}
|
||||
|
||||
if (isset($action["restriction"]["duedate"])) {
|
||||
$this->enddate = $action["restriction"]["duedate"];
|
||||
}
|
||||
}
|
||||
|
||||
if (!empty($action["timezone_iana"])) {
|
||||
$this->tziana = $action["timezone_iana"];
|
||||
$this->tzdef = TimezoneUtil::GetBinaryTZ($action['timezone_iana']);
|
||||
}
|
||||
|
||||
if ($this->startdate && $this->enddate) {
|
||||
$data = [];
|
||||
|
||||
$data["item"] = [];
|
||||
for ($index = 0, $index2 = count($entryid); $index < $index2; ++$index) {
|
||||
$this->getDelegateFolderInfo($store[$index]);
|
||||
|
||||
// Set the active store in properties class and get the props based on active store.
|
||||
// we need to do this because of multi server env where shared store belongs to the different server.
|
||||
// Here name space is different per server. e.g. There is user A and user B and both are belongs to
|
||||
// different server and user B is shared store of user A because of that user A has 'categories' => -2062020578
|
||||
// and user B 'categories' => -2062610402,
|
||||
$GLOBALS["properties"]->setActiveStore($store[$index]);
|
||||
$this->properties = $GLOBALS["properties"]->getAppointmentListProperties();
|
||||
|
||||
array_push($data["item"], ...$this->getCalendarItems($store[$index], $entryid[$index], $this->startdate, $this->enddate));
|
||||
}
|
||||
|
||||
$this->addSkippedInfo($data);
|
||||
$this->addActionData("list", $data);
|
||||
$GLOBALS["bus"]->addData($this->getResponseData());
|
||||
|
||||
return;
|
||||
}
|
||||
// for list view in calendar as startdate and enddate is passed as false
|
||||
// this will set sorting and paging for items in listview.
|
||||
|
||||
/* This is an override for parent::messageList(), which ignores an array of entryids / stores.
|
||||
* The following block considers this possibly and merges the data of several folders / stores.
|
||||
*/
|
||||
|
||||
$this->searchFolderList = false; // Set to indicate this is not the search result, but a normal folder content
|
||||
|
||||
// Restriction
|
||||
$this->parseRestriction($action);
|
||||
|
||||
// Sort
|
||||
$this->parseSortOrder($action, null, true);
|
||||
|
||||
$limit = false;
|
||||
if (isset($action['restriction']['limit'])) {
|
||||
$limit = $action['restriction']['limit'];
|
||||
}
|
||||
else {
|
||||
$limit = $GLOBALS['settings']->get('grommunio/v1/main/page_size', 50);
|
||||
}
|
||||
|
||||
$isSearchFolder = isset($action['search_folder_entryid']);
|
||||
if ($isSearchFolder) {
|
||||
$searchFolderEntryid = hex2bin((string) $action['search_folder_entryid']);
|
||||
if ($searchFolderEntryid === false) {
|
||||
return;
|
||||
}
|
||||
$entryid = [$searchFolderEntryid];
|
||||
$store = [$store[0]];
|
||||
}
|
||||
|
||||
$this->getDelegateFolderInfo($store[0]);
|
||||
|
||||
// Get the table and merge the arrays
|
||||
$data = [];
|
||||
$items = [];
|
||||
for ($i = 0, $c = count($entryid); $i < $c; ++$i) {
|
||||
$newItems = $GLOBALS["operations"]->getTable($store[$i], $entryid[$i], $this->properties, $this->sort, $this->start, $limit, $this->restriction);
|
||||
array_push($items, ...$newItems['item']);
|
||||
if (isset($newItems['page']['totalrowcount']) && $newItems['page']['totalrowcount'] > $limit) {
|
||||
$data['page'] = $newItems['page'];
|
||||
}
|
||||
}
|
||||
|
||||
// If the request come from search folder then no need to send folder information
|
||||
if (!$isSearchFolder) {
|
||||
$contentCount = 0;
|
||||
$contentUnread = 0;
|
||||
|
||||
// For each folder
|
||||
for ($i = 0, $c = count($entryid); $i < $c; ++$i) {
|
||||
// Open folder
|
||||
$folder = mapi_msgstore_openentry($store[$i], $entryid[$i]);
|
||||
// Obtain some statistics from the folder contents
|
||||
$content = mapi_getprops($folder, [PR_CONTENT_COUNT, PR_CONTENT_UNREAD]);
|
||||
if (isset($content[PR_CONTENT_COUNT])) {
|
||||
$contentCount += $content[PR_CONTENT_COUNT];
|
||||
}
|
||||
|
||||
if (isset($content[PR_CONTENT_UNREAD])) {
|
||||
$contentUnread += $content[PR_CONTENT_UNREAD];
|
||||
}
|
||||
}
|
||||
|
||||
$data["folder"] = [];
|
||||
$data["folder"]["content_count"] = $contentCount;
|
||||
$data["folder"]["content_unread"] = $contentUnread;
|
||||
}
|
||||
|
||||
$items = $this->filterPrivateItems(['item' => $items]);
|
||||
// unset will remove the value but will not regenerate array keys, so we need to
|
||||
// do it here
|
||||
$data["item"] = array_values($items["item"]);
|
||||
|
||||
for ($i = 0, $c = count($entryid); $i < $c; ++$i) {
|
||||
// Allowing to hook in just before the data sent away to be sent to the client
|
||||
$GLOBALS['PluginManager']->triggerHook('server.module.listmodule.list.after', [
|
||||
'moduleObject' => &$this,
|
||||
'store' => $store[$i],
|
||||
'entryid' => $entryid[$i],
|
||||
'action' => $action,
|
||||
'data' => &$data,
|
||||
]);
|
||||
}
|
||||
|
||||
$this->addSkippedInfo($data);
|
||||
$this->addActionData($actionType, $data);
|
||||
$GLOBALS["bus"]->addData($this->getResponseData());
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds an informational message to the list response when appointments were skipped.
|
||||
*
|
||||
* @param array $data list response data
|
||||
*/
|
||||
private function addSkippedInfo(&$data) {
|
||||
if ($this->skippedCount === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
$displayMessage = sprintf(ngettext("There was %d skipped appointment:", "There were %d skipped appointments:", $this->skippedCount), $this->skippedCount);
|
||||
|
||||
if (!empty($this->skippedInfo)) {
|
||||
$displayMessage .= $this->skippedInfo;
|
||||
}
|
||||
|
||||
if ($this->skippedCount > 5) {
|
||||
$displayMessage .= "<br/>" . _("More skipped appointments are not shown.");
|
||||
}
|
||||
|
||||
$data["warning"] = [
|
||||
"display_message" => $displayMessage,
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Tracks skipped appointments and stores the first few subjects for client feedback.
|
||||
*
|
||||
* @param string $subject appointment properties from the MAPI table
|
||||
*/
|
||||
private function recordSkipped($subject) {
|
||||
++$this->skippedCount;
|
||||
|
||||
if ($this->skippedCount >= 5) {
|
||||
return;
|
||||
}
|
||||
|
||||
$this->skippedInfo .= "<br/>- " . htmlspecialchars((string) $subject, ENT_QUOTES | ENT_SUBSTITUTE, "UTF-8");
|
||||
}
|
||||
|
||||
/**
|
||||
* Function to return all Calendar items in a given timeframe. This
|
||||
* function also takes recurring items into account.
|
||||
*
|
||||
* @param resource $store message store
|
||||
* @param mixed $entryid entryid of the folder
|
||||
* @param mixed $start startdate of the interval
|
||||
* @param mixed $end enddate of the interval
|
||||
*/
|
||||
public function getCalendarItems($store, $entryid, $start, $end) {
|
||||
$restriction =
|
||||
// OR
|
||||
// - Either we want all appointments which fall within the given range
|
||||
// - Or we want all recurring items which we manually check if an occurrence
|
||||
// exists which will fall inside the range
|
||||
[RES_OR,
|
||||
[
|
||||
// OR
|
||||
// - Either we want all properties which fall inside the range (or overlap the range somewhere)
|
||||
// (start < appointmentEnd && due > appointmentStart)
|
||||
// - Or we want all zero-minute appointments which fall at the start of the restriction.
|
||||
// Note that this will effectively exclude any appointments which have an enddate on the restriction
|
||||
// start date, as those are not useful for us. Secondly, we exclude all zero-minute appointments
|
||||
// which fall on the end of the restriction as the restriction is <start, end].
|
||||
[RES_OR,
|
||||
[
|
||||
// AND
|
||||
// - The AppointmentEnd must fall after the start of the range
|
||||
// - The AppointmentStart must fall before the end of the range
|
||||
[RES_AND,
|
||||
[
|
||||
// start < appointmentEnd
|
||||
[RES_PROPERTY,
|
||||
[RELOP => RELOP_GT,
|
||||
ULPROPTAG => $this->properties["duedate"],
|
||||
VALUE => $start,
|
||||
],
|
||||
],
|
||||
// due > appointmentStart
|
||||
[RES_PROPERTY,
|
||||
[RELOP => RELOP_LT,
|
||||
ULPROPTAG => $this->properties["startdate"],
|
||||
VALUE => $end,
|
||||
],
|
||||
],
|
||||
],
|
||||
],
|
||||
// AND
|
||||
// - The AppointmentStart equals the start of the range
|
||||
// - The AppointmentEnd equals the start of the range
|
||||
// In other words the zero-minute appointments on the start of the range
|
||||
[RES_AND,
|
||||
[
|
||||
// appointmentStart == start
|
||||
[RES_PROPERTY,
|
||||
[RELOP => RELOP_EQ,
|
||||
ULPROPTAG => $this->properties["startdate"],
|
||||
VALUE => $start,
|
||||
],
|
||||
],
|
||||
// appointmentEnd == start
|
||||
[RES_PROPERTY,
|
||||
[RELOP => RELOP_EQ,
|
||||
ULPROPTAG => $this->properties["duedate"],
|
||||
VALUE => $start,
|
||||
],
|
||||
],
|
||||
],
|
||||
],
|
||||
],
|
||||
],
|
||||
// OR
|
||||
// (item[isRecurring] == true)
|
||||
// Add one day to the start and the end of the periods to avoid
|
||||
// timezone offset related differences between start/clipstart
|
||||
// and end/clipend.
|
||||
[RES_AND,
|
||||
[
|
||||
[RES_PROPERTY,
|
||||
[RELOP => RELOP_EQ,
|
||||
ULPROPTAG => $this->properties["recurring"],
|
||||
VALUE => true,
|
||||
],
|
||||
],
|
||||
[RES_AND,
|
||||
[
|
||||
[RES_PROPERTY,
|
||||
[RELOP => RELOP_GT,
|
||||
ULPROPTAG => $this->properties["enddate_recurring"],
|
||||
VALUE => (int) $start - 86400,
|
||||
],
|
||||
],
|
||||
[RES_PROPERTY,
|
||||
[RELOP => RELOP_LT,
|
||||
ULPROPTAG => $this->properties["startdate_recurring"],
|
||||
VALUE => (int) $end + 86400,
|
||||
],
|
||||
],
|
||||
],
|
||||
],
|
||||
],
|
||||
],
|
||||
],
|
||||
]; // global OR
|
||||
|
||||
try {
|
||||
$folder = mapi_msgstore_openentry($store, $entryid);
|
||||
$table = mapi_folder_getcontentstable($folder, MAPI_DEFERRED_ERRORS);
|
||||
// Restricting the table filters it while it loads; passing the
|
||||
// restriction to queryallrows instead walks it row by row.
|
||||
mapi_table_restrict($table, $restriction, TBL_BATCH);
|
||||
$calendaritems = mapi_table_queryallrows($table, $this->properties);
|
||||
|
||||
return $this->processItems($calendaritems, $store, $entryid, $start, $end);
|
||||
}
|
||||
catch (Exception $e) {
|
||||
// Without read rights the table is refused (gromox answers MAPI_E_NOT_FOUND);
|
||||
// the owner's free/busy data is all that may be shown then.
|
||||
if ($e->getCode() == MAPI_E_NOT_FOUND || $e->getCode() == MAPI_E_NO_ACCESS) {
|
||||
return $this->getFreebusyItems($store, $entryid, $start, $end);
|
||||
}
|
||||
error_log(sprintf("getCalendarItems: unable to list folder %s: %s (0x%08X)", bin2hex((string) $entryid), $e->getMessage(), $e->getCode()));
|
||||
}
|
||||
|
||||
return [];
|
||||
}
|
||||
|
||||
/**
|
||||
* Process calendar items to prepare them for being sent back to the client.
|
||||
*
|
||||
* @param array $calendaritems array of appointments retrieved from the MAPI table
|
||||
* @param resource $store MAPI message store
|
||||
* @param mixed $entryid
|
||||
* @param mixed $start startdate of the interval
|
||||
* @param mixed $end enddate of the interval
|
||||
*
|
||||
* @return array $items processed items
|
||||
*/
|
||||
public function processItems($calendaritems, $store, $entryid, $start, $end) {
|
||||
$items = [];
|
||||
$openedMessages = [];
|
||||
$proptags = $GLOBALS["properties"]->getRecurrenceProperties();
|
||||
|
||||
foreach ($calendaritems as $calendaritem) {
|
||||
$item = null;
|
||||
if (!isset($calendaritem[$this->properties["recurring"]]) ||
|
||||
!$calendaritem[$this->properties["recurring"]]) {
|
||||
$item = Conversion::mapMAPI2XML($this->properties, $calendaritem);
|
||||
$this->addItems($store, $item, $openedMessages, $start, $end, $items);
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
// Fix for all-day events which have a different timezone than the user's browser
|
||||
$recurrence = new Recurrence($store, $calendaritem, $proptags);
|
||||
|
||||
try {
|
||||
$recuritems = $recurrence->getItems($start, $end);
|
||||
}
|
||||
catch (RecurrenceException $re) {
|
||||
$subject = $calendaritem[$this->properties["subject"]] ?? '<empty subject>';
|
||||
error_log(sprintf(
|
||||
"processItems RecurrenceException (%d) for item '%s' - %s - %s",
|
||||
$re->getCode(),
|
||||
$subject,
|
||||
bin2hex($calendaritem[$this->properties["entryid"]]),
|
||||
bin2hex($calendaritem[$this->properties["recurring_data"]])
|
||||
));
|
||||
$this->recordSkipped($subject);
|
||||
|
||||
continue;
|
||||
}
|
||||
$msgRecurrence = null;
|
||||
|
||||
foreach ($recuritems as $recuritem) {
|
||||
// Recurrence blob is not needed for occurrence display
|
||||
unset($recuritem[$this->properties['recurring_data']]);
|
||||
|
||||
$item = Conversion::mapMAPI2XML($this->properties, $recuritem);
|
||||
|
||||
// Single occurrences are never recurring
|
||||
$item['props']['recurring'] = false;
|
||||
|
||||
if (isset($recuritem["exception"])) {
|
||||
$item["props"]["exception"] = true;
|
||||
}
|
||||
|
||||
if (isset($recuritem["basedate"])) {
|
||||
$item["props"]["basedate"] = $recuritem["basedate"];
|
||||
}
|
||||
|
||||
if (isset($recuritem["exception"])) {
|
||||
// Add categories if they are set on the exception.
|
||||
// We need a Recurrence object backed by the mapi message
|
||||
// (not just props) so we can open the exception attachments.
|
||||
// Create it once per series and reuse for all exceptions.
|
||||
if ($msgRecurrence === null) {
|
||||
$msgEntryid = bin2hex((string) $calendaritem[$this->properties["entryid"]]);
|
||||
if (!isset($openedMessages[$msgEntryid])) {
|
||||
$message = mapi_msgstore_openentry($store, $calendaritem[$this->properties["entryid"]]);
|
||||
$openedMessages[$msgEntryid] = $message;
|
||||
}
|
||||
else {
|
||||
$message = $openedMessages[$msgEntryid];
|
||||
}
|
||||
$msgRecurrence = new Recurrence($store, $message, $proptags);
|
||||
}
|
||||
$exceptionatt = $msgRecurrence->getExceptionAttachment($recuritem["basedate"]);
|
||||
if ($exceptionatt) {
|
||||
// Existing exception (open existing item, which includes basedate)
|
||||
$exception = mapi_attach_openobj($exceptionatt, 0);
|
||||
$exceptionProps = $GLOBALS['operations']->getMessageProps($store, $exception, ['categories' => $this->properties["categories"]]);
|
||||
|
||||
if (isset($exceptionProps['props']['categories'])) {
|
||||
$item["props"]["categories"] = $exceptionProps['props']['categories'];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
$this->addItems($store, $item, $openedMessages, $start, $end, $items);
|
||||
}
|
||||
}
|
||||
|
||||
usort($items, ["AppointmentListModule", "compareCalendarItems"]);
|
||||
|
||||
return $items;
|
||||
}
|
||||
|
||||
/**
|
||||
* Function will be used to process private items in a list response, modules can
|
||||
* can decide what to do with the private items, remove the entire row or just
|
||||
* hide the data. This function will only hide the data of the private appointments.
|
||||
*
|
||||
* @param array $item item properties
|
||||
*
|
||||
* @return array item properties after processing private items
|
||||
*/
|
||||
#[Override]
|
||||
public function processPrivateItem($item) {
|
||||
if (!$this->startdate || !$this->enddate) {
|
||||
// if we are in list view then we need to follow normal procedure of other listviews
|
||||
return parent::processPrivateItem($item);
|
||||
}
|
||||
|
||||
if (!$this->checkPrivateItem($item)) {
|
||||
return $item;
|
||||
}
|
||||
|
||||
$item['props']['subject'] = _('Private Appointment');
|
||||
$item['props']['normalized_subject'] = _('Private Appointment');
|
||||
$item['props']['location'] = '';
|
||||
$item['props']['reminder'] = 0;
|
||||
$item['props']['access'] = 0;
|
||||
$item['props']['sent_representing_name'] = '';
|
||||
$item['props']['sender_name'] = '';
|
||||
$item['props']['display_to'] = '';
|
||||
$item['props']['display_cc'] = '';
|
||||
$item['props']['display_bcc'] = '';
|
||||
$item['props']['body_preview'] = '';
|
||||
|
||||
return $item;
|
||||
}
|
||||
|
||||
/**
|
||||
* Function will sort items for the month view
|
||||
* small startdate on top.
|
||||
*
|
||||
* @param mixed $a
|
||||
* @param mixed $b
|
||||
*/
|
||||
public static function compareCalendarItems($a, $b) {
|
||||
$start_a = $a["props"]["startdate"];
|
||||
$start_b = $b["props"]["startdate"];
|
||||
|
||||
return $start_a <=> $start_b;
|
||||
}
|
||||
|
||||
/**
|
||||
* Processes an all-day item and calculates the correct start time if necessary.
|
||||
*
|
||||
* @param resource $store
|
||||
* @param array $calendaritem
|
||||
* @param array $openedMessages
|
||||
*/
|
||||
private function processAllDayItem($store, &$calendaritem, &$openedMessages) {
|
||||
// If the appointment doesn't have tzdefstart property, it was probably
|
||||
// created on a mobile device (mobile devices do not send a timezone for
|
||||
// all-day events) or was imported from a system which doesn't set it.
|
||||
$isTzdefstartSet = isset($calendaritem['props']['tzdefstart']);
|
||||
$tzdefstart = $isTzdefstartSet ?
|
||||
hex2bin((string) $calendaritem['props']['tzdefstart']) :
|
||||
mapi_ianatz_to_tzdef("Etc/UTC");
|
||||
if ($tzdefstart === false) {
|
||||
$isTzdefstartSet = false;
|
||||
$tzdefstart = '';
|
||||
}
|
||||
|
||||
// queryrows only returns 510 chars max, so if tzdef is longer than that
|
||||
// it was probably silently truncated. In such case we need to open
|
||||
// the message and read the prop value as stream.
|
||||
if (strlen($tzdefstart) > 500 && $isTzdefstartSet) {
|
||||
if (!isset($openedMessages[$calendaritem['entryid']])) {
|
||||
// Open the message and add it to the openedMessages property
|
||||
$openedMessages[$calendaritem['entryid']] = mapi_msgstore_openentry($store, hex2bin((string) $calendaritem['entryid']));
|
||||
}
|
||||
$tzdefstart = readMapiPropStream($openedMessages[$calendaritem['entryid']], $this->properties['tzdefstart']);
|
||||
}
|
||||
|
||||
$duration = $calendaritem['props']['duedate'] - $calendaritem['props']['startdate'];
|
||||
// Set the start and endtimes to the midnight of the client's timezone
|
||||
// if that's not the case already.
|
||||
if (!$isTzdefstartSet) {
|
||||
$localStart = getLocalStart($calendaritem['props']['startdate'], $this->tziana);
|
||||
if ($localStart != $calendaritem['props']['startdate']) {
|
||||
$calendaritem['props']['startdate'] = $calendaritem['props']['commonstart'] = $localStart;
|
||||
$calendaritem['props']['duedate'] = $calendaritem['props']['commonend'] = $localStart + $duration;
|
||||
}
|
||||
}
|
||||
// Compare the timezone definitions of the client and the appointment.
|
||||
// Further processing is only required if they don't match.
|
||||
elseif ($isTzdefstartSet && !$GLOBALS['entryid']->compareEntryIds($this->tzdef, $tzdefstart)) {
|
||||
$localStart = TimezoneUtil::ConvertAllDayStart($calendaritem['props']['startdate'], $tzdefstart, $this->tzdef);
|
||||
if ($localStart !== null) {
|
||||
$calendaritem['props']['startdate'] = $calendaritem['props']['commonstart'] = $localStart;
|
||||
$calendaritem['props']['duedate'] = $calendaritem['props']['commonend'] = $localStart + $duration;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds items to return items list.
|
||||
*
|
||||
* @param resource $store
|
||||
* @param array $openedMessages
|
||||
* @param mixed $start startdate of the interval
|
||||
* @param mixed $end enddate of the interval
|
||||
* @param array $items
|
||||
* @param mixed $item
|
||||
*/
|
||||
private function addItems($store, &$item, &$openedMessages, $start, $end, &$items) {
|
||||
$item = $this->processPrivateItem($item);
|
||||
|
||||
// only add it in response if its not removed by above function
|
||||
if (empty($item)) {
|
||||
return;
|
||||
}
|
||||
$this->prepareBodyPreview($item);
|
||||
if (empty($item["props"]["commonstart"]) && isset($item["props"]["startdate"])) {
|
||||
$item["props"]["commonstart"] = $item["props"]["startdate"];
|
||||
}
|
||||
if (empty($item["props"]["commonend"]) && isset($item["props"]["duedate"])) {
|
||||
$item["props"]["commonend"] = $item["props"]["duedate"];
|
||||
}
|
||||
if (isset($item["props"]["alldayevent"]) && $item["props"]["alldayevent"]) {
|
||||
$this->processAllDayItem($store, $item, $openedMessages);
|
||||
}
|
||||
// After processing the all-day events, their start and due dates
|
||||
// may have changed, so it's necessary to check again if they are
|
||||
// still in the requested interval.
|
||||
if (($start <= $item["props"]["startdate"] && $end > $item['props']['startdate']) ||
|
||||
($start < $item["props"]["duedate"] && $end >= $item['props']['duedate']) ||
|
||||
($start > $item["props"]["startdate"] && $end < $item['props']['duedate'])) {
|
||||
array_push($items, $item);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets items using freebusy entry point.
|
||||
*
|
||||
* @param resource $store MAPI message store
|
||||
* @param mixed $folderEntryid entryid of the folder
|
||||
* @param mixed $start startdate of the interval
|
||||
* @param mixed $end enddate of the interval
|
||||
*/
|
||||
public function getFreebusyItems($store, $folderEntryid, $start, $end) {
|
||||
$items = [];
|
||||
$storeProps = mapi_getprops($store, [PR_ENTRYID, PR_MAILBOX_OWNER_ENTRYID]);
|
||||
// A public store has no owner whose free/busy could stand in for the folder
|
||||
if (empty($storeProps[PR_MAILBOX_OWNER_ENTRYID])) {
|
||||
return $items;
|
||||
}
|
||||
$folderEntryid = bin2hex((string) $folderEntryid);
|
||||
$storeEntryid = bin2hex((string) $storeProps[PR_ENTRYID]);
|
||||
// if start was not set, get items one month back
|
||||
if ($start === false) {
|
||||
$start = time() - 2592000;
|
||||
}
|
||||
// if end was not set, get items 3 months ahead
|
||||
if ($end === false) {
|
||||
$end = time() + 7776000;
|
||||
}
|
||||
try {
|
||||
$fbdata = mapi_getuserfreebusy($GLOBALS['mapisession']->getSession(), $storeProps[PR_MAILBOX_OWNER_ENTRYID], $start, $end);
|
||||
}
|
||||
catch (MAPIException $e) {
|
||||
// No free/busy rights either: the calendar is simply empty for this user
|
||||
if ($e->getCode() != MAPI_E_NO_ACCESS) {
|
||||
error_log(sprintf("getFreebusyItems: %s (0x%08X)", $e->getMessage(), $e->getCode()));
|
||||
}
|
||||
|
||||
return $items;
|
||||
}
|
||||
$fbEvents = $fbdata['fbevents'] ?? [];
|
||||
foreach ($fbEvents as $fbEvent) {
|
||||
// check if the event is in start - end range
|
||||
if ($fbEvent['end'] < $start || $fbEvent['start'] > $end) {
|
||||
continue;
|
||||
}
|
||||
$isPrivate = $fbEvent['private'] ?? false;
|
||||
$items[] = [
|
||||
// entryid is required, generate a fake one if a real is not available
|
||||
'entryid' => isset($fbEvent['id']) ? bin2hex($fbEvent['id']) : bin2hex(random_bytes(16)),
|
||||
'parent_entryid' => $folderEntryid,
|
||||
'store_entryid' => $storeEntryid,
|
||||
'props' => [
|
||||
'access' => 0,
|
||||
'subject' => $isPrivate ? _('Private Appointment') : ($fbEvent['subject'] ?? _('Busy')),
|
||||
'normalized_subject' => $isPrivate ? _('Private Appointment') : ($fbEvent['subject'] ?? _('Busy')),
|
||||
'location' => $isPrivate ? '' : ($fbEvent['location'] ?? ''),
|
||||
'startdate' => $fbEvent['start'],
|
||||
'duedate' => $fbEvent['end'],
|
||||
'commonstart' => $fbEvent['start'],
|
||||
'commonend' => $fbEvent['end'],
|
||||
'message_class' => 'IPM.Appointment',
|
||||
'object_type' => MAPI_MESSAGE,
|
||||
'icon_index' => 1024,
|
||||
'display_to' => '',
|
||||
'display_cc' => '',
|
||||
'display_bcc' => '',
|
||||
'importance' => 1,
|
||||
'sensitivity' => 0,
|
||||
'message_size' => 0,
|
||||
'hasattach' => false,
|
||||
'sent_representing_entryid' => '',
|
||||
'sent_representing_name' => '',
|
||||
'sent_representing_address_type' => '',
|
||||
'sent_representing_email_address' => '',
|
||||
'sent_representing_search_key' => '',
|
||||
'sender_email_address' => '',
|
||||
'sender_name' => '',
|
||||
'sender_address_type' => '',
|
||||
'sender_entryid' => '',
|
||||
'sender_search_key' => '',
|
||||
'recurring' => false,
|
||||
'recurring_data' => '',
|
||||
'recurring_pattern' => '',
|
||||
'meeting' => $fbEvent['meeting'] ?? false,
|
||||
'reminder' => 0,
|
||||
'reminder_minutes' => 0,
|
||||
'private' => $isPrivate,
|
||||
],
|
||||
];
|
||||
}
|
||||
|
||||
return $items;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* SPDX-FileCopyrightText: Copyright 2020 - 2026 grommunio GmbH
|
||||
* SPDX-FileCopyrightText: Copyright 2016 Kopano and its licensors
|
||||
* SPDX-FileCopyrightText: Copyright 2005 - 2016 Zarafa B.V. and its licensors
|
||||
* SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
*/
|
||||
|
||||
/**
|
||||
* BusyTime Module.
|
||||
*/
|
||||
require_once BASE_PATH . 'server/includes/modules/class.appointmentlistmodule.php';
|
||||
|
||||
class BusyTimeListModule extends AppointmentListModule {
|
||||
/**
|
||||
* @var array the properties sent back to the client - a minimal set of data
|
||||
*/
|
||||
private $minproperties;
|
||||
|
||||
/**
|
||||
* Constructor.
|
||||
*
|
||||
* @param int $id unique id
|
||||
* @param array $data list of all actions
|
||||
*/
|
||||
public function __construct($id, $data) {
|
||||
parent::__construct($id, $data);
|
||||
$this->minproperties = $GLOBALS["properties"]->getBusyTimeProperties();
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates the notifiers for this module,
|
||||
* and register them to the Bus.
|
||||
*/
|
||||
#[Override]
|
||||
public function createNotifiers() {
|
||||
// Keep empty, the BusyTimeListModule doesn't need notifiers.
|
||||
}
|
||||
|
||||
/**
|
||||
* Process calendar items to prepare them for being sent back to the client.
|
||||
*
|
||||
* @param array $calendaritems array of appointments retrieved from the mapi tablwe
|
||||
* @param object $store message store
|
||||
* @param mixed $entryid
|
||||
* @param int $start startdate of the interval
|
||||
* @param int $end enddate of the interval
|
||||
*
|
||||
* @return array $items processed items
|
||||
*/
|
||||
#[Override]
|
||||
public function processItems($calendaritems, $store, $entryid, $start, $end) {
|
||||
$items = [];
|
||||
foreach ($calendaritems as $calendaritem) {
|
||||
if (isset($calendaritem[$this->properties["recurring"]]) && $calendaritem[$this->properties["recurring"]]) {
|
||||
$recurrence = new Recurrence($store, $calendaritem);
|
||||
try {
|
||||
$recuritems = $recurrence->getItems($start, $end);
|
||||
}
|
||||
catch (RecurrenceException $re) {
|
||||
$subject = $calendaritem[$this->properties["subject"]] ?? '<empty subject>';
|
||||
error_log(sprintf(
|
||||
"processItems (busytimelist) RecurrenceException (%d) for item '%s' - %s - %s",
|
||||
$re->getCode(),
|
||||
$subject,
|
||||
bin2hex($calendaritem[$this->properties["entryid"]]),
|
||||
bin2hex($calendaritem[$this->properties["recurring_data"]])
|
||||
));
|
||||
continue;
|
||||
}
|
||||
|
||||
foreach ($recuritems as $recuritem) {
|
||||
$item = Conversion::mapMAPI2XML($this->minproperties, $recuritem);
|
||||
|
||||
// only add it in response if its not removed by above function
|
||||
if (!empty($item)) {
|
||||
array_push($items, $item['props']);
|
||||
}
|
||||
}
|
||||
}
|
||||
else {
|
||||
$item = Conversion::mapMAPI2XML($this->minproperties, $calendaritem);
|
||||
|
||||
// only add it in response if its not removed by above function
|
||||
if (!empty($item)) {
|
||||
array_push($items, $item['props']);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return $items;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,139 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* SPDX-FileCopyrightText: Copyright 2020 - 2026 grommunio GmbH
|
||||
* SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
*/
|
||||
|
||||
require_once __DIR__ . '/../core/class.categorylist.php';
|
||||
|
||||
/**
|
||||
* CategoryListModule.
|
||||
*
|
||||
* Serves the per-mailbox master category list (the Outlook-compatible list
|
||||
* stored in each mailbox's Calendar folder, see {@link CategoryList}). Every
|
||||
* request targets a single store via store_entryid; when none is given the
|
||||
* logged-in user's own default store is used. This is what makes the list
|
||||
* per-mailbox and shared: opening a shared mailbox reads that mailbox's list,
|
||||
* not the current user's.
|
||||
*/
|
||||
class CategoryListModule extends Module {
|
||||
/**
|
||||
* @param int $id unique id
|
||||
* @param array $data list of all actions
|
||||
*/
|
||||
public function __construct($id, $data) {
|
||||
parent::__construct($id, $data);
|
||||
}
|
||||
|
||||
/**
|
||||
* Execute all actions in the request.
|
||||
*/
|
||||
#[Override]
|
||||
public function execute() {
|
||||
foreach ($this->data as $actionType => $action) {
|
||||
if (isset($actionType)) {
|
||||
try {
|
||||
switch ($actionType) {
|
||||
case "list":
|
||||
$this->listCategories($action);
|
||||
break;
|
||||
|
||||
case "save":
|
||||
$this->saveCategories($action);
|
||||
break;
|
||||
|
||||
case "migrate":
|
||||
$this->migrateCategories();
|
||||
break;
|
||||
|
||||
default:
|
||||
$this->handleUnknownActionType($actionType);
|
||||
}
|
||||
}
|
||||
catch (MAPIException $e) {
|
||||
$this->processException($e, $actionType);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve the store an action targets, defaulting to the user's own store
|
||||
* only when no store_entryid was supplied. A supplied store that cannot be
|
||||
* opened (revoked share, stale entryid) must error out - falling back
|
||||
* would silently read or overwrite the wrong mailbox's list.
|
||||
*
|
||||
* @param array $action the action data sent by the client
|
||||
*
|
||||
* @return resource the message store to operate on
|
||||
*/
|
||||
private function getStoreForAction($action) {
|
||||
$store = empty($action["store_entryid"])
|
||||
? $GLOBALS["mapisession"]->getDefaultMessageStore()
|
||||
: $this->getActionStore($action);
|
||||
if ($store === false || is_array($store)) {
|
||||
throw new MAPIException("Could not open the requested mailbox.", MAPI_E_NOT_FOUND, null, _("Could not open the requested mailbox."));
|
||||
}
|
||||
|
||||
return $store;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the master category list of the requested store.
|
||||
*
|
||||
* @param array $action the action data sent by the client
|
||||
*/
|
||||
private function listCategories($action) {
|
||||
$store = $this->getStoreForAction($action);
|
||||
$this->sendCategories("list", $store, new CategoryList($store));
|
||||
}
|
||||
|
||||
/**
|
||||
* Store the master category list of the requested store, then return the
|
||||
* re-read list so the client picks up merged/preserved data.
|
||||
*
|
||||
* @param array $action the action data sent by the client
|
||||
*/
|
||||
private function saveCategories($action) {
|
||||
$store = $this->getStoreForAction($action);
|
||||
$categories = isset($action["categories"]) && is_array($action["categories"]) ? $action["categories"] : [];
|
||||
$categoryList = new CategoryList($store);
|
||||
$categoryList->setCategories($categories);
|
||||
$this->sendCategories("update", $store, $categoryList);
|
||||
}
|
||||
|
||||
/**
|
||||
* Migrate every category assigned to an item in the user's mailbox to the
|
||||
* Outlook-compatible master list.
|
||||
*/
|
||||
private function migrateCategories() {
|
||||
$store = $this->getStoreForAction([]);
|
||||
$legacyCategories = $GLOBALS['settings']->getPersistent('grommunio/main/categories', []);
|
||||
$categoryList = new CategoryList($store);
|
||||
$categoryList->migrateItemCategories(is_array($legacyCategories) ? $legacyCategories : []);
|
||||
|
||||
$this->sendCategories("migrate", $store, $categoryList);
|
||||
}
|
||||
|
||||
/**
|
||||
* Send a category list to the client, tagged with the store it belongs to
|
||||
* (so the client can key its per-store cache).
|
||||
*
|
||||
* @param string $actionType the response action type
|
||||
* @param resource $store the store the list belongs to
|
||||
* @param CategoryList $categoryList the list accessor for that store
|
||||
*/
|
||||
private function sendCategories($actionType, $store, CategoryList $categoryList) {
|
||||
$storeProps = mapi_getprops($store, [PR_ENTRYID]);
|
||||
$categories = $categoryList->getCategories();
|
||||
$this->addActionData($actionType, [
|
||||
"store_entryid" => bin2hex((string) $storeProps[PR_ENTRYID]),
|
||||
"categories" => $categories,
|
||||
// lets the client distinguish "no list stored yet" (seed it)
|
||||
// from a deliberately emptied list (leave it alone)
|
||||
"exists" => $categoryList->listExists(),
|
||||
]);
|
||||
$GLOBALS["bus"]->addData($this->getResponseData());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,678 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* SPDX-FileCopyrightText: Copyright 2020 - 2026 grommunio GmbH
|
||||
* SPDX-FileCopyrightText: Copyright 2016 Kopano and its licensors
|
||||
* SPDX-FileCopyrightText: Copyright 2005 - 2016 Zarafa B.V. and its licensors
|
||||
* SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
*/
|
||||
|
||||
/**
|
||||
* Contact ItemModule
|
||||
* Module which opens, creates, saves and deletes an item. It
|
||||
* extends the Module class.
|
||||
*/
|
||||
class ContactItemModule extends ItemModule {
|
||||
/**
|
||||
* Special date properties and the entry ID property of their appointment.
|
||||
*/
|
||||
private const SPECIAL_DATE_EVENTIDS = [
|
||||
'birthday' => 'birthday_eventid',
|
||||
'wedding_anniversary' => 'anniversary_eventid',
|
||||
];
|
||||
|
||||
/**
|
||||
* Constructor.
|
||||
*
|
||||
* @param int $id unique id
|
||||
* @param array $data list of all actions
|
||||
*/
|
||||
public function __construct($id, $data) {
|
||||
$this->properties = $GLOBALS['properties']->getContactProperties();
|
||||
|
||||
parent::__construct($id, $data);
|
||||
|
||||
$this->plaintext = false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a one-off entry ID and fail the save if MAPI cannot produce one.
|
||||
*
|
||||
* @param mixed $displayName
|
||||
* @param mixed $addressType
|
||||
* @param mixed $emailAddress
|
||||
* @param mixed $flags
|
||||
*
|
||||
* @return string binary one-off entry ID
|
||||
*/
|
||||
private function createOneOffEntryId($displayName, $addressType, $emailAddress, $flags = 0) {
|
||||
$entryId = mapi_createoneoff($displayName, $addressType, $emailAddress, $flags);
|
||||
if ($entryId === false) {
|
||||
throw new RuntimeException('Unable to create one-off entry ID');
|
||||
}
|
||||
|
||||
return $entryId;
|
||||
}
|
||||
|
||||
/**
|
||||
* Function which opens an item.
|
||||
*
|
||||
* @param resource $store MAPI message store
|
||||
* @param string $entryid entryid of the message
|
||||
* @param array $action the action data, sent by the client
|
||||
*/
|
||||
#[Override]
|
||||
public function open($store, $entryid, $action) {
|
||||
$data = [];
|
||||
$orEntryid = $entryid;
|
||||
$message = false;
|
||||
|
||||
if ($entryid) {
|
||||
// Check if OneOff entryid is a local contact
|
||||
if ($GLOBALS['entryid']->hasAddressBookOneOff(bin2hex($entryid))) {
|
||||
try {
|
||||
$oneoff = mapi_parseoneoff($entryid);
|
||||
$ab = $GLOBALS['mapisession']->getAddressbook();
|
||||
$ab_dir = mapi_ab_openentry($ab);
|
||||
$res = $this->searchContactsFolders($ab, $ab_dir, $oneoff['address']);
|
||||
if (count($res) > 0) {
|
||||
$entryid = $res[0][PR_ENTRYID];
|
||||
}
|
||||
}
|
||||
catch (MAPIException $ex) {
|
||||
error_log(sprintf(
|
||||
"Unable to open contact because mapi_parseoneoff failed: %s - %s",
|
||||
get_mapi_error_name($ex->getCode()),
|
||||
$ex->getDisplayMessage()
|
||||
));
|
||||
}
|
||||
}
|
||||
/* Check if given entryid is shared folder distlist then
|
||||
* get the store of distlist for fetching it's members.
|
||||
*/
|
||||
$storeData = $this->getStoreParentEntryIdFromEntryId($entryid);
|
||||
$store = $storeData["store"];
|
||||
$message = $storeData["message"];
|
||||
}
|
||||
|
||||
if (empty($message)) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Open embedded message if requested
|
||||
$attachNum = !empty($action['attach_num']) ? $action['attach_num'] : false;
|
||||
if ($attachNum) {
|
||||
// get message props of sub message
|
||||
$parentMessage = $message;
|
||||
$message = $GLOBALS['operations']->openMessage($store, $entryid, $attachNum);
|
||||
|
||||
if (empty($message)) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Check if message is distlist then we need to use different set of properties
|
||||
$props = mapi_getprops($message, [PR_MESSAGE_CLASS]);
|
||||
|
||||
if (class_match_prefix($props[PR_MESSAGE_CLASS], "IPM.Distlist")) {
|
||||
// for distlist we need to use different set of properties
|
||||
$this->properties = $GLOBALS['properties']->getDistListProperties();
|
||||
}
|
||||
|
||||
$data['item'] = $GLOBALS['operations']->getEmbeddedMessageProps($store, $message, $this->properties, $parentMessage, $attachNum);
|
||||
}
|
||||
else {
|
||||
// Check if message is distlist then we need to use different set of properties
|
||||
$props = mapi_getprops($message, [PR_MESSAGE_CLASS]);
|
||||
|
||||
if (class_match_prefix($props[PR_MESSAGE_CLASS], "IPM.Distlist")) {
|
||||
// for distlist we need to use different set of properties
|
||||
$this->properties = $GLOBALS['properties']->getDistListProperties();
|
||||
}
|
||||
|
||||
// get message props of the message
|
||||
$data['item'] = $GLOBALS['operations']->getMessageProps($store, $message, $this->properties, $this->plaintext, true);
|
||||
}
|
||||
|
||||
// By openentry from address book, the entryid will differ, make it same as the origin
|
||||
$data['item']['entryid'] = bin2hex($orEntryid);
|
||||
|
||||
// Allowing to hook in just before the data sent away to be sent to the client
|
||||
$GLOBALS['PluginManager']->triggerHook('server.module.contactitemmodule.open.after', [
|
||||
'moduleObject' => &$this,
|
||||
'store' => $store,
|
||||
'entryid' => $entryid,
|
||||
'action' => $action,
|
||||
'message' => &$message,
|
||||
'data' => &$data,
|
||||
]);
|
||||
|
||||
$this->addActionData('item', $data);
|
||||
$GLOBALS['bus']->addData($this->getResponseData());
|
||||
}
|
||||
|
||||
/**
|
||||
* Function which saves an item. It sets the right properties for a contact
|
||||
* item (address book properties).
|
||||
*
|
||||
* @param false|resource $store MAPI message store, or false to use the default
|
||||
* @param false|string $parententryid parent folder entry ID, or false to infer it
|
||||
* @param false|string $entryid entry ID of the message, or false for a new item
|
||||
* @param array $action action data sent by the client
|
||||
* @param string $actionType action type that triggered the save
|
||||
*/
|
||||
#[Override]
|
||||
public function save($store, $parententryid, $entryid, $action, $actionType = 'save') {
|
||||
$propertiesToDelete = []; // create an array of properties which should be deleted
|
||||
$isCopyGABToContact = false;
|
||||
// this array is passed to $GLOBALS['operations']->saveMessage() function
|
||||
|
||||
if ($store === false && !$parententryid) {
|
||||
if (isset($action['props']['message_class'])) {
|
||||
$store = $GLOBALS['mapisession']->getDefaultMessageStore();
|
||||
$parententryid = $this->getDefaultFolderEntryID($store, $action['props']['message_class']);
|
||||
}
|
||||
elseif ($entryid) {
|
||||
$data = $this->getStoreParentEntryIdFromEntryId($entryid);
|
||||
$store = $data["store"];
|
||||
$parententryid = $data["parent_entryid"];
|
||||
}
|
||||
}
|
||||
elseif (!$parententryid) {
|
||||
if (isset($action['props']['message_class'])) {
|
||||
$parententryid = $this->getDefaultFolderEntryID($store, $action['props']['message_class']);
|
||||
}
|
||||
}
|
||||
|
||||
if ($store !== false && $parententryid && isset($action['props'])) {
|
||||
if (isset($action['members'])) {
|
||||
$props = $this->prepareDistListProps($action, $propertiesToDelete);
|
||||
}
|
||||
else {
|
||||
$isCopyGABToContact = ($action["message_action"]["action_type"] ?? null) === "copyToContact";
|
||||
$props = $this->prepareContactProps($store, $action, $isCopyGABToContact, $propertiesToDelete);
|
||||
}
|
||||
|
||||
$messageProps = [];
|
||||
|
||||
$result = $GLOBALS['operations']->saveMessage($store, $entryid, $parententryid, $props, $messageProps, [], $action['attachments'] ?? [], $propertiesToDelete);
|
||||
|
||||
if ($result) {
|
||||
$GLOBALS['bus']->notify(bin2hex($parententryid), TABLE_SAVE, $messageProps);
|
||||
|
||||
if ($isCopyGABToContact) {
|
||||
$message = mapi_msgstore_openentry($store, $messageProps[PR_ENTRYID]);
|
||||
$messageProps = mapi_getprops($message, $this->properties);
|
||||
}
|
||||
|
||||
$this->addActionData('update', ['item' => Conversion::mapMAPI2XML($this->properties, $messageProps)]);
|
||||
$GLOBALS['bus']->addData($this->getResponseData());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts the client data of a distribution list, packing its members.
|
||||
*
|
||||
* @param array $action action data sent by the client
|
||||
* @param array $propertiesToDelete receives the properties to remove
|
||||
*
|
||||
* @return array MAPI properties to save
|
||||
*/
|
||||
private function prepareDistListProps($action, &$propertiesToDelete) {
|
||||
$this->properties = $GLOBALS['properties']->getDistListProperties();
|
||||
|
||||
$props = Conversion::mapXML2MAPI($this->properties, $action['props']);
|
||||
|
||||
$members = [];
|
||||
$oneoff_members = [];
|
||||
foreach ($action['members'] as $item) {
|
||||
if (empty($item['email_address'])) {
|
||||
// mapi_parseoneoff fails without an address; OL07 uses Unknown as well
|
||||
$item['email_address'] = 'Unknown';
|
||||
}
|
||||
if (empty($item['address_type']) && in_array($item['distlist_type'], [DL_DIST, DL_DIST_AB])) {
|
||||
$item['address_type'] = 'MAPIPDL';
|
||||
}
|
||||
|
||||
$oneoff = $this->createOneOffEntryId($item['display_name'], $item['address_type'], $item['email_address']);
|
||||
|
||||
if ($item['distlist_type'] == DL_EXTERNAL_MEMBER) {
|
||||
$member = $oneoff;
|
||||
}
|
||||
else {
|
||||
$member = pack('VA16CA*', 0, WAB_GUID, $item['distlist_type'], hex2bin((string) $item['entryid']));
|
||||
}
|
||||
|
||||
$oneoff_members[] = $oneoff;
|
||||
$members[] = $member;
|
||||
}
|
||||
|
||||
if (!empty($members) && !empty($oneoff_members)) {
|
||||
$props[$this->properties['members']] = $members;
|
||||
$props[$this->properties['oneoff_members']] = $oneoff_members;
|
||||
}
|
||||
else {
|
||||
$propertiesToDelete[] = $this->properties['members'];
|
||||
$propertiesToDelete[] = $this->properties['oneoff_members'];
|
||||
}
|
||||
|
||||
return $props;
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts the client data of a contact, deriving one-off entry IDs and
|
||||
* the birthday and anniversary appointments.
|
||||
*
|
||||
* @param resource $store MAPI message store
|
||||
* @param array $action action data sent by the client
|
||||
* @param bool $isCopyGABToContact whether the contact is copied from the address book
|
||||
* @param array $propertiesToDelete receives the properties to remove
|
||||
*
|
||||
* @return array MAPI properties to save
|
||||
*/
|
||||
private function prepareContactProps($store, $action, $isCopyGABToContact, &$propertiesToDelete) {
|
||||
if ($isCopyGABToContact) {
|
||||
$this->copyGABRecordProps($action);
|
||||
}
|
||||
for ($index = 1; $index < 4; ++$index) {
|
||||
if (!empty($action['props']['email_address_' . $index]) && !empty($action['props']['email_address_display_name_' . $index])) {
|
||||
$action['props']['email_address_entryid_' . $index] = bin2hex($this->createOneOffEntryId($action['props']['email_address_display_name_' . $index], $action['props']['email_address_type_' . $index], $action['props']['email_address_' . $index]));
|
||||
}
|
||||
}
|
||||
|
||||
// fax 1 is primary, 2 business, 3 home
|
||||
for ($index = 1; $index < 4; ++$index) {
|
||||
$fax = 'fax_' . $index . '_';
|
||||
if (!empty($action['props'][$fax . 'email_address'])) {
|
||||
$action['props'][$fax . 'original_entryid'] = bin2hex($this->createOneOffEntryId($action['props'][$fax . 'original_display_name'], $action['props'][$fax . 'address_type'], $action['props'][$fax . 'email_address'], MAPI_UNICODE));
|
||||
}
|
||||
else {
|
||||
$propertiesToDelete[] = $this->properties[$fax . 'address_type'];
|
||||
$propertiesToDelete[] = $this->properties[$fax . 'original_display_name'];
|
||||
$propertiesToDelete[] = $this->properties[$fax . 'email_address'];
|
||||
$propertiesToDelete[] = $this->properties[$fax . 'original_entryid'];
|
||||
}
|
||||
}
|
||||
|
||||
if (!empty($action['entryid'])) {
|
||||
$this->collectClearedContactProps($store, $action['props'], $propertiesToDelete);
|
||||
}
|
||||
|
||||
/*
|
||||
* convert all line endings(LF) into CRLF
|
||||
* XML parser will normalize all CR, LF and CRLF into LF
|
||||
* but outlook(windows) uses CRLF as line ending
|
||||
*/
|
||||
foreach (['business_address', 'home_address', 'other_address'] as $address) {
|
||||
if (isset($action['props'][$address])) {
|
||||
$action['props'][$address] = preg_replace('/\r?\n/', "\r\n", (string) $action['props'][$address]);
|
||||
}
|
||||
}
|
||||
|
||||
foreach (self::SPECIAL_DATE_EVENTIDS as $date => $eventid) {
|
||||
if (!empty($action['props'][$date])) {
|
||||
$action['props'][$eventid] = $this->updateAppointments($store, $action, $date);
|
||||
}
|
||||
}
|
||||
|
||||
return Conversion::mapXML2MAPI($this->properties, $action['props']);
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds the properties an existing contact had cleared to the delete list,
|
||||
* removing the appointments of cleared special dates.
|
||||
*
|
||||
* @param resource $store MAPI message store
|
||||
* @param array $props contact properties sent by the client
|
||||
* @param array $propertiesToDelete receives the properties to remove
|
||||
*/
|
||||
private function collectClearedContactProps($store, $props, &$propertiesToDelete) {
|
||||
for ($i = 1; $i < 4; ++$i) {
|
||||
if (isset($props['email_address_' . $i]) && empty($props['email_address_' . $i])) {
|
||||
array_push($propertiesToDelete, $this->properties['email_address_entryid_' . $i]);
|
||||
array_push($propertiesToDelete, $this->properties['email_address_' . $i]);
|
||||
array_push($propertiesToDelete, $this->properties['email_address_display_name_' . $i]);
|
||||
array_push($propertiesToDelete, $this->properties['email_address_display_name_email_' . $i]);
|
||||
array_push($propertiesToDelete, $this->properties['email_address_type_' . $i]);
|
||||
}
|
||||
}
|
||||
|
||||
if (isset($props['address_book_long']) && $props['address_book_long'] === 0) {
|
||||
$propertiesToDelete[] = $this->properties['address_book_mv'];
|
||||
$propertiesToDelete[] = $this->properties['address_book_long'];
|
||||
}
|
||||
|
||||
foreach (self::SPECIAL_DATE_EVENTIDS as $date => $eventid) {
|
||||
if (array_key_exists($date, $props) && empty($props[$date])) {
|
||||
array_push($propertiesToDelete, $this->properties[$date]);
|
||||
array_push($propertiesToDelete, $this->properties[$eventid]);
|
||||
if (!empty($props[$eventid])) {
|
||||
$this->deleteSpecialDateAppointment($store, $props[$eventid]);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Function copy the some property from address book record to contact props.
|
||||
*
|
||||
* @param array $action the action data, sent by the client
|
||||
*/
|
||||
public function copyGABRecordProps(&$action) {
|
||||
$addrbook = $GLOBALS["mapisession"]->getAddressbook();
|
||||
$abitem = mapi_ab_openentry($addrbook, hex2bin((string) $action["message_action"]["source_entryid"]));
|
||||
$abItemProps = mapi_getprops($abitem, [
|
||||
PR_COMPANY_NAME,
|
||||
PR_ASSISTANT,
|
||||
PR_BUSINESS_TELEPHONE_NUMBER,
|
||||
PR_BUSINESS2_TELEPHONE_NUMBER,
|
||||
PR_HOME2_TELEPHONE_NUMBER,
|
||||
PR_STREET_ADDRESS,
|
||||
PR_LOCALITY,
|
||||
PR_STATE_OR_PROVINCE,
|
||||
PR_POSTAL_CODE,
|
||||
PR_COUNTRY,
|
||||
PR_MOBILE_TELEPHONE_NUMBER,
|
||||
]);
|
||||
$action["props"]["company_name"] = $abItemProps[PR_COMPANY_NAME] ?? '';
|
||||
$action["props"]["assistant"] = $abItemProps[PR_ASSISTANT] ?? '';
|
||||
$action["props"]["business_telephone_number"] = $abItemProps[PR_BUSINESS_TELEPHONE_NUMBER] ?? '';
|
||||
$action["props"]["business2_telephone_number"] = $abItemProps[PR_BUSINESS2_TELEPHONE_NUMBER] ?? '';
|
||||
$action["props"]["home2_telephone_number"] = $abItemProps[PR_HOME2_TELEPHONE_NUMBER] ?? '';
|
||||
$action["props"]["home_address_street"] = $abItemProps[PR_STREET_ADDRESS] ?? '';
|
||||
$action["props"]["home_address_city"] = $abItemProps[PR_LOCALITY] ?? '';
|
||||
$action["props"]["home_address_state"] = $abItemProps[PR_STATE_OR_PROVINCE] ?? '';
|
||||
$action["props"]["home_address_postal_code"] = $abItemProps[PR_POSTAL_CODE] ?? '';
|
||||
$action["props"]["home_address_country"] = $abItemProps[PR_COUNTRY] ?? '';
|
||||
|
||||
$action["props"]["cellular_telephone_number"] = $abItemProps[PR_MOBILE_TELEPHONE_NUMBER] ?? '';
|
||||
|
||||
// Set the home_address property value
|
||||
$props = ["street", "city", "state", "postal_code", "country"];
|
||||
$homeAddress = "";
|
||||
foreach ($props as $index => $prop) {
|
||||
if (isset($action["props"]["home_address_" . $prop]) && !empty($action["props"]["home_address_" . $prop])) {
|
||||
$homeAddress .= $action["props"]["home_address_" . $prop] . " ";
|
||||
if ($prop == "street" || $prop == "postal_code") {
|
||||
$homeAddress .= PHP_EOL;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
$action["props"]["home_address"] = $homeAddress;
|
||||
}
|
||||
|
||||
/**
|
||||
* Function which deletes an item. Extended here to also delete corresponding birthday/anniversary
|
||||
* appointments from calendar.
|
||||
*
|
||||
* @param false|resource $store MAPI message store, or false to infer it
|
||||
* @param false|string $parententryid parent folder entry ID, or false to infer it
|
||||
* @param false|string $entryid entry ID of the message, or false when unavailable
|
||||
* @param array $action action data sent by the client
|
||||
*/
|
||||
#[Override]
|
||||
public function delete($store, $parententryid, $entryid, $action) {
|
||||
$message = false;
|
||||
if ($store === false && !$parententryid && $entryid) {
|
||||
$data = $this->getStoreParentEntryIdFromEntryId($entryid);
|
||||
$store = $data["store"];
|
||||
$message = $data["message"];
|
||||
$parententryid = $data["parent_entryid"];
|
||||
}
|
||||
|
||||
if ($store !== false && $entryid) {
|
||||
try {
|
||||
if ($message === false) {
|
||||
$message = $GLOBALS["operations"]->openMessage($store, $entryid);
|
||||
}
|
||||
|
||||
$props = mapi_getprops($message, [$this->properties['anniversary_eventid'], $this->properties['birthday_eventid']]);
|
||||
|
||||
// if any of the appointment entryid exists then delete it
|
||||
if (!empty($props[$this->properties['birthday_eventid']])) {
|
||||
$this->deleteSpecialDateAppointment($store, bin2hex((string) $props[$this->properties['birthday_eventid']]));
|
||||
}
|
||||
|
||||
if (!empty($props[$this->properties['anniversary_eventid']])) {
|
||||
$this->deleteSpecialDateAppointment($store, bin2hex((string) $props[$this->properties['anniversary_eventid']]));
|
||||
}
|
||||
}
|
||||
catch (MAPIException $e) {
|
||||
// if any error occurs in deleting appointments then we shouldn't block deletion of contact item
|
||||
// so ignore errors now
|
||||
$e->setHandled();
|
||||
}
|
||||
|
||||
parent::delete($store, $parententryid, $entryid, $action);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Function which retrieve the store, parent_entryid from record entryid.
|
||||
*
|
||||
* @param $entryid entryid of the message
|
||||
*
|
||||
* @return array which contains store and message object and parent entryid of that message
|
||||
*/
|
||||
public function getStoreParentEntryIdFromEntryId($entryid) {
|
||||
$message = $GLOBALS['mapisession']->openMessage($entryid);
|
||||
$messageStoreInfo = mapi_getprops($message, [PR_STORE_ENTRYID, PR_PARENT_ENTRYID]);
|
||||
$store = $GLOBALS['mapisession']->openMessageStore($messageStoreInfo[PR_STORE_ENTRYID]);
|
||||
$parentEntryid = $messageStoreInfo[PR_PARENT_ENTRYID];
|
||||
|
||||
return ["message" => $message, "store" => $store, "parent_entryid" => $parentEntryid];
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculate the number of minutes from the start of a timestamp's year to its month.
|
||||
*
|
||||
* @param int $timestamp
|
||||
*
|
||||
* @return int
|
||||
*/
|
||||
private static function getMonthOffset($timestamp) {
|
||||
$month = (int) date('m', $timestamp);
|
||||
$year = (int) date('Y', $timestamp);
|
||||
|
||||
$yearStart = new DateTime();
|
||||
$yearStart->setDate($year, 1, 1);
|
||||
$monthStart = clone $yearStart;
|
||||
$monthStart->setDate($year, $month, 1);
|
||||
|
||||
return $monthStart->diff($yearStart)->days * 24 * 60;
|
||||
}
|
||||
|
||||
/**
|
||||
* Function will create/update a yearly recurring appointment on the respective date of birthday or anniversary in user's calendar.
|
||||
*
|
||||
* @param resource $store MAPI message store
|
||||
* @param array $action the action data, sent by the client
|
||||
* @param string $type type of appointment that should be created/updated, valid values are 'birthday' and 'wedding_anniversary'
|
||||
*
|
||||
* @return false|string entry ID of the newly created appointment in hexadecimal form, or false
|
||||
*/
|
||||
public function updateAppointments($store, $action, $type) {
|
||||
$result = false;
|
||||
|
||||
$root = mapi_msgstore_openentry($store);
|
||||
$rootProps = mapi_getprops($root, [PR_IPM_APPOINTMENT_ENTRYID, PR_STORE_ENTRYID]);
|
||||
$parentEntryId = bin2hex((string) $rootProps[PR_IPM_APPOINTMENT_ENTRYID]);
|
||||
$storeEntryId = bin2hex((string) $rootProps[PR_STORE_ENTRYID]);
|
||||
|
||||
$actionProps = $action['props'];
|
||||
$subject = !empty($actionProps['subject']) ? $actionProps['subject'] : _('Untitled');
|
||||
$subject = ($type === 'birthday' ? sprintf(_('%s\'s Birthday'), $subject) : sprintf(_('%s\'s Anniversary'), $subject));
|
||||
|
||||
// UTC time
|
||||
$startDateUTC = $actionProps[$type];
|
||||
$dueDateUTC = $actionProps[$type] + (24 * 60 * 60); // ONE DAY is added to set duedate of item.
|
||||
|
||||
// get local time from UTC time
|
||||
$recur = new Recurrence($store, []);
|
||||
$startDate = $recur->fromGMT($actionProps, $startDateUTC);
|
||||
$dueDate = $recur->fromGMT($actionProps, $dueDateUTC);
|
||||
|
||||
// Find the number of minutes since the start of the year to the given month,
|
||||
// taking leap years into account.
|
||||
$month = self::getMonthOffset($startDate);
|
||||
|
||||
$defAllDayReminder = $GLOBALS['settings']->get('grommunio/v1/contexts/calendar/default_allday_reminder_time', 1080);
|
||||
|
||||
$props = [
|
||||
'message_class' => 'IPM.Appointment',
|
||||
'icon_index' => 1025,
|
||||
'busystatus' => fbFree,
|
||||
'meeting' => olNonMeeting,
|
||||
'object_type' => MAPI_MESSAGE,
|
||||
'message_flags' => MSGFLAG_READ | MSGFLAG_UNSENT,
|
||||
'subject' => $subject,
|
||||
|
||||
'startdate' => $startDateUTC,
|
||||
'duedate' => $dueDateUTC,
|
||||
'commonstart' => $startDateUTC,
|
||||
'commonend' => $dueDateUTC,
|
||||
'alldayevent' => true,
|
||||
'duration' => 1440,
|
||||
'reminder' => true,
|
||||
'reminder_minutes' => $defAllDayReminder,
|
||||
'reminder_time' => $startDateUTC,
|
||||
'flagdueby' => $startDateUTC - ($defAllDayReminder * 60),
|
||||
|
||||
'recurring' => true,
|
||||
'recurring_reset' => true,
|
||||
'startocc' => 0,
|
||||
'endocc' => 1440,
|
||||
'start' => $startDate,
|
||||
'end' => $dueDate,
|
||||
'term' => 35,
|
||||
'everyn' => 1,
|
||||
'subtype' => 2,
|
||||
'type' => 13,
|
||||
'regen' => 0,
|
||||
'month' => $month,
|
||||
'monthday' => date('j', $startDate),
|
||||
'timezone' => $actionProps['timezone'],
|
||||
'timezonedst' => $actionProps['timezonedst'],
|
||||
'dststartmonth' => $actionProps['dststartmonth'],
|
||||
'dststartweek' => $actionProps['dststartweek'],
|
||||
'dststartday' => $actionProps['dststartday'],
|
||||
'dststarthour' => $actionProps['dststarthour'],
|
||||
'dstendmonth' => $actionProps['dstendmonth'],
|
||||
'dstendweek' => $actionProps['dstendweek'],
|
||||
'dstendday' => $actionProps['dstendday'],
|
||||
'dstendhour' => $actionProps['dstendhour'],
|
||||
];
|
||||
|
||||
$data = [];
|
||||
$data['store'] = $storeEntryId;
|
||||
$data['parententryid'] = $parentEntryId;
|
||||
|
||||
$entryid = false;
|
||||
// if entryid is provided then update existing appointment, else create new one
|
||||
if ($type === 'birthday' && !empty($actionProps['birthday_eventid'])) {
|
||||
$entryid = $actionProps['birthday_eventid'];
|
||||
}
|
||||
elseif ($type === 'wedding_anniversary' && !empty($actionProps['anniversary_eventid'])) {
|
||||
$entryid = $actionProps['anniversary_eventid'];
|
||||
}
|
||||
|
||||
if ($entryid !== false) {
|
||||
$data['entryid'] = $entryid;
|
||||
}
|
||||
|
||||
if (isset($action['timezone_iana'])) {
|
||||
$props['timezone_iana'] = $action['timezone_iana'];
|
||||
}
|
||||
|
||||
$data['props'] = $props;
|
||||
|
||||
// Save appointment (saveAppointment takes care of creating/modifying exceptions to recurring
|
||||
// items if necessary)
|
||||
try {
|
||||
$messageProps = $GLOBALS['operations']->saveAppointment($store, hex2bin((string) $entryid), hex2bin($parentEntryId), $data);
|
||||
}
|
||||
catch (MAPIException $e) {
|
||||
// if the appointment is deleted then create a new one
|
||||
if ($e->getCode() == MAPI_E_NOT_FOUND) {
|
||||
$e->setHandled();
|
||||
$messageProps = $GLOBALS['operations']->saveAppointment($store, false, hex2bin($parentEntryId), $data);
|
||||
}
|
||||
else {
|
||||
// The calendar entry is a convenience; the contact is saved regardless.
|
||||
$e->setHandled();
|
||||
error_log(sprintf('Unable to save the %s appointment of a contact: %s', $type, $e->getMessage()));
|
||||
$messageProps = false;
|
||||
}
|
||||
}
|
||||
|
||||
// Notify the bus if the save was OK
|
||||
if ($messageProps && !(is_array($messageProps) && isset($messageProps['error']))) {
|
||||
$GLOBALS['bus']->notify($parentEntryId, TABLE_SAVE, $messageProps);
|
||||
$result = bin2hex((string) $messageProps[PR_ENTRYID]);
|
||||
}
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Function will delete the appointment on the respective date of birthday or anniversary in user's calendar.
|
||||
*
|
||||
* @param resource $store MAPI message store
|
||||
* @param string $entryid entry ID of the message to delete
|
||||
*/
|
||||
public function deleteSpecialDateAppointment($store, $entryid) {
|
||||
$root = mapi_msgstore_openentry($store);
|
||||
$rootProps = mapi_getprops($root, [PR_IPM_APPOINTMENT_ENTRYID, PR_STORE_ENTRYID]);
|
||||
$parentEntryId = $rootProps[PR_IPM_APPOINTMENT_ENTRYID];
|
||||
$storeEntryId = $rootProps[PR_STORE_ENTRYID];
|
||||
|
||||
$props = [];
|
||||
$props[PR_PARENT_ENTRYID] = $parentEntryId;
|
||||
$props[PR_ENTRYID] = hex2bin((string) $entryid);
|
||||
$props[PR_STORE_ENTRYID] = $storeEntryId;
|
||||
|
||||
$result = $GLOBALS['operations']->deleteMessages($store, $parentEntryId, $props[PR_ENTRYID]);
|
||||
|
||||
if ($result) {
|
||||
$GLOBALS['bus']->notify(bin2hex((string) $parentEntryId), TABLE_DELETE, $props);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* This function searches the private contact folders for users and returns an array with data.
|
||||
* Please note that the returning array must be UTF8.
|
||||
*
|
||||
* @param resource $ab The addressbook
|
||||
* @param resource $ab_dir The addressbook container
|
||||
* @param string $searchstr The search query, case is ignored
|
||||
*/
|
||||
public function searchContactsFolders($ab, $ab_dir, $searchstr) {
|
||||
$r = [];
|
||||
$abhtable = mapi_folder_gethierarchytable($ab_dir, MAPI_DEFERRED_ERRORS | CONVENIENT_DEPTH);
|
||||
$abcntfolders = mapi_table_queryallrows($abhtable, [PR_ENTRYID, PR_AB_PROVIDER_ID, PR_DISPLAY_NAME]);
|
||||
$restriction = [
|
||||
RES_CONTENT,
|
||||
[
|
||||
FUZZYLEVEL => FL_SUBSTRING | FL_IGNORECASE,
|
||||
ULPROPTAG => PR_SMTP_ADDRESS,
|
||||
VALUE => [PR_SMTP_ADDRESS => $searchstr],
|
||||
],
|
||||
];
|
||||
// restriction on hierarchy table for PR_AB_PROVIDER_ID
|
||||
// seems not to work, just loop through
|
||||
foreach ($abcntfolders as $abcntfolder) {
|
||||
if ($abcntfolder[PR_AB_PROVIDER_ID] == ZARAFA_CONTACTS_GUID) {
|
||||
$abfldentry = mapi_ab_openentry($ab, $abcntfolder[PR_ENTRYID]);
|
||||
$abfldcontents = mapi_folder_getcontentstable($abfldentry);
|
||||
mapi_table_restrict($abfldcontents, $restriction);
|
||||
$r = mapi_table_queryallrows($abfldcontents, [PR_ENTRYID]);
|
||||
if (is_array($r) && !empty($r)) {
|
||||
return $r;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return $r;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* SPDX-FileCopyrightText: Copyright 2020 - 2026 grommunio GmbH
|
||||
* SPDX-FileCopyrightText: Copyright 2016 Kopano and its licensors
|
||||
* SPDX-FileCopyrightText: Copyright 2005 - 2016 Zarafa B.V. and its licensors
|
||||
* SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
*/
|
||||
|
||||
/**
|
||||
* Contact Module.
|
||||
*/
|
||||
class ContactListModule extends ListModule {
|
||||
/**
|
||||
* Constructor.
|
||||
*
|
||||
* @param int $id unique id
|
||||
* @param array $data list of all actions
|
||||
*/
|
||||
public function __construct($id, $data) {
|
||||
parent::__construct($id, $data);
|
||||
|
||||
$this->properties = $GLOBALS["properties"]->getContactListProperties();
|
||||
|
||||
$this->start = 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates the notifiers for this module,
|
||||
* and register them to the Bus.
|
||||
*/
|
||||
public function createNotifiers() {
|
||||
$entryid = $this->getEntryID();
|
||||
$GLOBALS["bus"]->registerNotifier('contactlistnotifier', $entryid);
|
||||
}
|
||||
|
||||
/**
|
||||
* Executes all the actions in the $data variable.
|
||||
*/
|
||||
#[Override]
|
||||
public function execute() {
|
||||
foreach ($this->data as $actionType => $action) {
|
||||
if (isset($actionType)) {
|
||||
try {
|
||||
$store = $this->getActionStore($action);
|
||||
$entryid = $this->getActionSingleEntryID($action);
|
||||
if ($store === false || is_array($store)) {
|
||||
$this->sendFeedback(false);
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
switch ($actionType) {
|
||||
case "list":
|
||||
$this->getDelegateFolderInfo($store);
|
||||
$this->messageList($store, $entryid, $action, $actionType);
|
||||
break;
|
||||
|
||||
case "search":
|
||||
// @FIXME add handling for private items
|
||||
$this->search($store, $entryid, $action, $actionType);
|
||||
break;
|
||||
|
||||
case "updatesearch":
|
||||
$this->updatesearch($store, $entryid, $action);
|
||||
break;
|
||||
|
||||
case "stopsearch":
|
||||
$this->stopSearch($store, $entryid, $action);
|
||||
break;
|
||||
|
||||
default:
|
||||
$this->handleUnknownActionType($actionType);
|
||||
}
|
||||
}
|
||||
catch (MAPIException $e) {
|
||||
$this->processException($e, $actionType);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+754
@@ -0,0 +1,754 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* SPDX-FileCopyrightText: Copyright 2020 - 2026 grommunio GmbH
|
||||
* SPDX-FileCopyrightText: Copyright 2016 Kopano and its licensors
|
||||
* SPDX-FileCopyrightText: Copyright 2005 - 2016 Zarafa B.V. and its licensors
|
||||
* SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
*/
|
||||
|
||||
require_once __DIR__ . '/../hexutil.php';
|
||||
|
||||
/**
|
||||
* Create Mail ItemModule
|
||||
* Module which opens, creates, saves and deletes an item. It
|
||||
* extends the Module class.
|
||||
*/
|
||||
class CreateMailItemModule extends ItemModule {
|
||||
/**
|
||||
* Constructor.
|
||||
*
|
||||
* @param int $id unique id
|
||||
* @param array $data list of all actions
|
||||
*/
|
||||
public function __construct($id, $data) {
|
||||
parent::__construct($id, $data);
|
||||
|
||||
$this->properties = $GLOBALS['properties']->getMailProperties();
|
||||
$useHtmlPreview = $GLOBALS['settings']->get('grommunio/v1/contexts/mail/use_html_email_preview', USE_HTML_EMAIL_PREVIEW);
|
||||
$this->plaintext = !$useHtmlPreview;
|
||||
}
|
||||
|
||||
/**
|
||||
* Function which saves and/or sends an item.
|
||||
*
|
||||
* @param false|resource $store MAPI message store, or false when unavailable
|
||||
* @param false|string $parententryid parent entry ID of the message
|
||||
* @param false|string $entryid entry ID of the message
|
||||
* @param array $action the action data, sent by the client
|
||||
*/
|
||||
#[Override]
|
||||
public function save($store, $parententryid, $entryid, $action, $actionType = 'save') {
|
||||
$messageProps = [];
|
||||
|
||||
$store = $this->resolveStore($store);
|
||||
if ($store === false) {
|
||||
return;
|
||||
}
|
||||
|
||||
$parententryid = $this->resolveParentEntryId($store, $parententryid, $action);
|
||||
|
||||
$attachments = !empty($action['attachments']) ? $action['attachments'] : [];
|
||||
$recipients = !empty($action['recipients']) ? $action['recipients'] : [];
|
||||
|
||||
$result = $this->applyMessageFlags($store, $entryid, $action, $messageProps);
|
||||
$send = $this->shouldSendMessage($action);
|
||||
$saveChanges = $this->shouldPersistMessage($send, $action, $attachments, $recipients);
|
||||
|
||||
if ($saveChanges) {
|
||||
if ($send) {
|
||||
$this->restoreSendAsPropsFromDraft($store, $entryid, $action);
|
||||
}
|
||||
|
||||
$copyContext = $this->createCopyContext($store, $action, $send);
|
||||
$store = $copyContext['store'];
|
||||
$copyFromMessage = $copyContext['copyFromMessage'];
|
||||
$copyAttachments = $copyContext['copyAttachments'];
|
||||
$copyInlineAttachmentsOnly = $copyContext['copyInlineAttachmentsOnly'];
|
||||
$this->threadingSource = $copyContext['threadingSource'];
|
||||
|
||||
if ($send) {
|
||||
$sendOutcome = $this->handleSend($store, $entryid, $parententryid, $action, $recipients, $messageProps, $copyFromMessage, $copyAttachments, $copyInlineAttachmentsOnly);
|
||||
if ($sendOutcome['aborted']) {
|
||||
return;
|
||||
}
|
||||
$result = $sendOutcome['result'];
|
||||
}
|
||||
else {
|
||||
$draftOutcome = $this->handleDraftSave($store, $entryid, $parententryid, $action, $messageProps, $copyFromMessage, $copyAttachments, $copyInlineAttachmentsOnly);
|
||||
if ($draftOutcome['aborted']) {
|
||||
return;
|
||||
}
|
||||
$result = $draftOutcome['result'];
|
||||
}
|
||||
}
|
||||
|
||||
if ($result === false && isset($action['message_action']['soft_delete'])) {
|
||||
$result = true;
|
||||
}
|
||||
|
||||
if ($result && !$send && isset($messageProps[PR_PARENT_ENTRYID])) {
|
||||
$GLOBALS['bus']->notify(bin2hex($messageProps[PR_PARENT_ENTRYID]), TABLE_SAVE, $messageProps);
|
||||
}
|
||||
|
||||
if ($send) {
|
||||
$this->addActionData('update', ['item' => Conversion::mapMAPI2XML($this->properties, $messageProps)]);
|
||||
}
|
||||
|
||||
$this->sendFeedback($result ? true : false, [], true);
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve the message store that should be used for the save operation.
|
||||
*
|
||||
* @param false|resource $store MAPI message store, or false when unavailable
|
||||
*
|
||||
* @return false|resource resolved MAPI message store, or false when unavailable
|
||||
*/
|
||||
private function resolveStore($store) {
|
||||
if ($store !== false) {
|
||||
return $store;
|
||||
}
|
||||
|
||||
return $GLOBALS['mapisession']->getDefaultMessageStore();
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve parent entry id based on provided data or defaults.
|
||||
*
|
||||
* @param resource $store MAPI message store
|
||||
* @param false|string $parententryid parent entry ID, or false when unspecified
|
||||
*
|
||||
* @return false|string resolved parent entry ID, or false when unavailable
|
||||
*/
|
||||
private function resolveParentEntryId($store, $parententryid, array $action) {
|
||||
if ($parententryid) {
|
||||
return $parententryid;
|
||||
}
|
||||
|
||||
$messageClass = $action['props']['message_class'] ?? '';
|
||||
|
||||
return $this->getDefaultFolderEntryID($store, $messageClass);
|
||||
}
|
||||
|
||||
/**
|
||||
* Apply message flag updates if requested by the client.
|
||||
*
|
||||
* @param mixed $store
|
||||
* @param mixed $entryid
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
private function applyMessageFlags($store, $entryid, array &$action, array &$messageProps) {
|
||||
if (!isset($action['props']['message_flags']) || !$entryid) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$msgAction = $action['message_action'] ?? false;
|
||||
$result = $GLOBALS['operations']->setMessageFlag($store, $entryid, $action['props']['message_flags'], $msgAction, $messageProps);
|
||||
|
||||
unset($action['props']['message_flags']);
|
||||
|
||||
return (bool) $result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Determine whether the current action requests sending the message.
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
private function shouldSendMessage(array $action) {
|
||||
return isset($action['message_action']['send']) ? (bool) $action['message_action']['send'] : false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Decide if the message requires saving based on provided data.
|
||||
*
|
||||
* @param bool $send
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
private function shouldPersistMessage($send, array $action, array $attachments, array $recipients) {
|
||||
return $send || !empty($action['props']) || $this->hasAttachmentChanges($attachments) || !empty($recipients);
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if attachment updates are pending in the attachment state.
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
private function hasAttachmentChanges(array $attachments) {
|
||||
if (!isset($attachments['dialog_attachments'])) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$attachmentState = new AttachmentState();
|
||||
$attachmentState->open();
|
||||
$hasChanges = $attachmentState->isChangesPending($attachments['dialog_attachments']);
|
||||
$attachmentState->close();
|
||||
|
||||
return $hasChanges;
|
||||
}
|
||||
|
||||
/**
|
||||
* Restore the SendAs / on-behalf identity from a previously saved draft.
|
||||
*
|
||||
* The client only transmits properties which changed since the last save,
|
||||
* so a send request following an intermediate (auto)save may no longer
|
||||
* carry the sent_representing_* properties even though the draft was
|
||||
* composed under another identity. Without them both the store selection
|
||||
* in createCopyContext() and the representing-sender handling in
|
||||
* submitMessage() would silently fall back to the logged-in user's own
|
||||
* address. Read the identity back from the stored draft and treat it as
|
||||
* if the client had supplied it.
|
||||
*
|
||||
* @param resource $store store containing the draft
|
||||
* @param false|string $entryid entryid of the draft, false for an unsaved message
|
||||
*/
|
||||
private function restoreSendAsPropsFromDraft($store, $entryid, array &$action) {
|
||||
if (!$entryid) {
|
||||
return;
|
||||
}
|
||||
|
||||
// The presence of any sent_representing_* key expresses client intent,
|
||||
// even with an empty value: the client transmits empty strings when the
|
||||
// user explicitly removes the From identity, and restoring the draft's
|
||||
// identity in that case would send under the address the user just
|
||||
// removed. Only a request which does not mention the identity at all
|
||||
// (unchanged since the last save) may fall back to the stored draft.
|
||||
foreach (['sent_representing_name', 'sent_representing_email_address',
|
||||
'sent_representing_address_type', 'sent_representing_entryid',
|
||||
'sent_representing_search_key', 'sent_representing_smtp_address'] as $propName) {
|
||||
if (array_key_exists($propName, $action['props'] ?? [])) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
$draft = mapi_msgstore_openentry($store, $entryid);
|
||||
$draftProps = mapi_getprops($draft, [
|
||||
PR_SENT_REPRESENTING_NAME,
|
||||
PR_SENT_REPRESENTING_EMAIL_ADDRESS,
|
||||
PR_SENT_REPRESENTING_ADDRTYPE,
|
||||
PR_SENT_REPRESENTING_ENTRYID,
|
||||
PR_SENT_REPRESENTING_SEARCH_KEY,
|
||||
PR_SENT_REPRESENTING_SMTP_ADDRESS,
|
||||
]);
|
||||
}
|
||||
catch (MAPIException $e) {
|
||||
$e->setHandled();
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$smtpAddress = (string) ($draftProps[PR_SENT_REPRESENTING_SMTP_ADDRESS] ?? '');
|
||||
$emailAddress = (string) ($draftProps[PR_SENT_REPRESENTING_EMAIL_ADDRESS] ?? '');
|
||||
$addrType = (string) ($draftProps[PR_SENT_REPRESENTING_ADDRTYPE] ?? '');
|
||||
if (!$GLOBALS['operations']->isEmailAddressLike($smtpAddress)) {
|
||||
$smtpAddress = '';
|
||||
}
|
||||
if ($smtpAddress === '' && strcasecmp($addrType, 'SMTP') === 0 &&
|
||||
$GLOBALS['operations']->isEmailAddressLike($emailAddress)) {
|
||||
$smtpAddress = $emailAddress;
|
||||
}
|
||||
// An EX identity carries an X500 DN - and a draft written by an older
|
||||
// client may even carry a plain display name - in
|
||||
// PR_SENT_REPRESENTING_EMAIL_ADDRESS. Resolve the SMTP form through
|
||||
// the address book, like getMessageProps() does for the client.
|
||||
if ($smtpAddress === '' && !empty($draftProps[PR_SENT_REPRESENTING_ENTRYID])) {
|
||||
$smtpAddress = (string) $GLOBALS['operations']->getEmailAddress(
|
||||
$draftProps[PR_SENT_REPRESENTING_ENTRYID],
|
||||
$draftProps[PR_SENT_REPRESENTING_SEARCH_KEY] ?? false
|
||||
);
|
||||
}
|
||||
// The resolver may hand back an X500 DN when the address book entry
|
||||
// carries no SMTP address; injecting that as a claimed-SMTP identity
|
||||
// would arm the identity guard with a value that self-matches on the
|
||||
// assembled message. Rather inject nothing at all.
|
||||
if (!$GLOBALS['operations']->isEmailAddressLike($smtpAddress)) {
|
||||
return;
|
||||
}
|
||||
|
||||
$action['props']['sent_representing_name'] = (string) ($draftProps[PR_SENT_REPRESENTING_NAME] ?? '') !== '' ?
|
||||
$draftProps[PR_SENT_REPRESENTING_NAME] : $smtpAddress;
|
||||
$action['props']['sent_representing_email_address'] = $smtpAddress;
|
||||
$action['props']['sent_representing_address_type'] = 'SMTP';
|
||||
$action['props']['sent_representing_smtp_address'] = $smtpAddress;
|
||||
if (!empty($draftProps[PR_SENT_REPRESENTING_ENTRYID])) {
|
||||
$action['props']['sent_representing_entryid'] = bin2hex((string) $draftProps[PR_SENT_REPRESENTING_ENTRYID]);
|
||||
}
|
||||
if (!empty($draftProps[PR_SENT_REPRESENTING_SEARCH_KEY])) {
|
||||
$action['props']['sent_representing_search_key'] = bin2hex((string) $draftProps[PR_SENT_REPRESENTING_SEARCH_KEY]);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Prepare context data when the new message should copy content from another message.
|
||||
*
|
||||
* @param mixed $store
|
||||
* @param bool $send
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
/** Source message whose threading headers the response inherits, or false. */
|
||||
private $threadingSource = false;
|
||||
|
||||
/** Persist threading headers with the first save so later sends keep them. */
|
||||
private function withThreadingProperties(array $props, $reply): array {
|
||||
if ($this->threadingSource === false) {
|
||||
return $props;
|
||||
}
|
||||
|
||||
return $GLOBALS['operations']->threadingProperties($this->threadingSource, (bool) $reply, $props);
|
||||
}
|
||||
|
||||
private function createCopyContext($store, array $action, $send) {
|
||||
$context = [
|
||||
'store' => $store,
|
||||
'copyAttachments' => false,
|
||||
'copyFromMessage' => false,
|
||||
'copyInlineAttachmentsOnly' => false,
|
||||
'threadingSource' => false,
|
||||
];
|
||||
|
||||
if (isset($action['message_action']['action_type'])) {
|
||||
$actionType = $action['message_action']['action_type'];
|
||||
$requiresCopy = in_array($actionType, ['reply', 'replyall', 'forward', 'edit_as_new'], true);
|
||||
|
||||
if ($requiresCopy) {
|
||||
$copyFromMessageId = (string) ($action['message_action']['source_entryid'] ?? '');
|
||||
$copyFromStoreId = (string) ($action['message_action']['source_store_entryid'] ?? '');
|
||||
$copyFromAttachNum = !empty($action['message_action']['source_attach_num']) ? $action['message_action']['source_attach_num'] : false;
|
||||
|
||||
$copyStoreBinary = $copyFromStoreId !== '' ? $this->hexToBinOrFalse($copyFromStoreId) : false;
|
||||
$copyMessageBinary = $copyFromMessageId !== '' ? $this->hexToBinOrFalse($copyFromMessageId) : false;
|
||||
$copyFromStore = $copyStoreBinary !== false ? $GLOBALS['mapisession']->openMessageStore($copyStoreBinary) : false;
|
||||
$copyFromMessage = false;
|
||||
|
||||
if ($copyFromStore && $copyMessageBinary !== false) {
|
||||
try {
|
||||
$copyFromMessage = $GLOBALS['operations']->openMessage($copyFromStore, $copyMessageBinary, $copyFromAttachNum);
|
||||
}
|
||||
catch (MAPIException $e) {
|
||||
$copyFromMessage = false;
|
||||
}
|
||||
}
|
||||
|
||||
if ($copyFromStore && $send) {
|
||||
$context['store'] = $copyFromStore;
|
||||
}
|
||||
|
||||
if ($copyFromStore && $copyFromMessage) {
|
||||
parse_smime($copyFromStore, $copyFromMessage);
|
||||
}
|
||||
// Threading headers are inherited even when nothing is copied.
|
||||
$context['threadingSource'] = $copyFromMessage;
|
||||
if (($action['message_action']['browser_decrypted'] ?? false) === true) {
|
||||
// The browser has uploaded the selected decrypted attachments
|
||||
// through the normal attachment pipeline. Copying the source
|
||||
// here would duplicate its opaque encrypted MIME envelope.
|
||||
$copyFromMessage = false;
|
||||
}
|
||||
|
||||
$context['copyAttachments'] = true;
|
||||
$context['copyFromMessage'] = $copyFromMessage;
|
||||
$context['copyInlineAttachmentsOnly'] = in_array($actionType, ['reply', 'replyall'], true);
|
||||
}
|
||||
}
|
||||
elseif (isset($action['props']['sent_representing_email_address'], $action['props']['sent_representing_address_type']) &&
|
||||
strlen(trim($action['props']['sent_representing_email_address'])) !== 0) {
|
||||
$addrType = $action['props']['sent_representing_address_type'];
|
||||
if (strcasecmp($addrType, 'EX') === 0 || strcasecmp($addrType, 'SMTP') === 0) {
|
||||
try {
|
||||
$otherStore = $GLOBALS['mapisession']->addUserStore($action['props']['sent_representing_email_address']);
|
||||
}
|
||||
catch (MAPIException $e) {
|
||||
$e->setTitle(_('Unknown error'));
|
||||
$e->setDisplayMessage(sprintf(_("Unable to add store: '%s'. Please check if you have the necessary permissions."),
|
||||
$action['props']['sent_representing_email_address']));
|
||||
|
||||
throw $e;
|
||||
}
|
||||
if ($otherStore && $send) {
|
||||
$context['store'] = $otherStore;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return $context;
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle the send flow including plugin hooks and recipient processing.
|
||||
*
|
||||
* @param mixed $store
|
||||
* @param mixed $entryid
|
||||
* @param mixed $parententryid
|
||||
* @param mixed $copyFromMessage
|
||||
* @param bool $copyAttachments
|
||||
* @param bool $copyInlineAttachmentsOnly
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
private function handleSend($store, $entryid, $parententryid, array &$action, array $recipients, array &$messageProps, $copyFromMessage, $copyAttachments, $copyInlineAttachmentsOnly) {
|
||||
// Before any work is done, so a replayed request costs nothing.
|
||||
Operations::assertSubmitRateLimit();
|
||||
|
||||
// Keep this check in core: disabled/removed plugins cannot register hooks
|
||||
// or property mappings, but a previously opened compose tab retains intent.
|
||||
if (!empty($action['props']['pgp_sign']) || !empty($action['props']['pgp_encrypt'])) {
|
||||
Operations::assertOpenPgpAvailable($action['props']);
|
||||
}
|
||||
$success = true;
|
||||
$GLOBALS['PluginManager']->triggerHook('server.module.createmailitemmodule.beforesend', [
|
||||
'moduleObject' => $this,
|
||||
'store' => $store,
|
||||
'entryid' => $entryid,
|
||||
'action' => $action,
|
||||
'success' => &$success,
|
||||
'properties' => $this->properties,
|
||||
'messageProps' => $messageProps,
|
||||
'parententryid' => $parententryid,
|
||||
]);
|
||||
|
||||
if (!$success) {
|
||||
return ['result' => false, 'aborted' => true];
|
||||
}
|
||||
|
||||
if (!isset($action['message_action']['action_type']) || $action['message_action']['action_type'] !== 'edit_as_new') {
|
||||
$this->setReplyForwardInfo($action);
|
||||
}
|
||||
|
||||
$savedUnsavedRecipients = [];
|
||||
if ($entryid) {
|
||||
// $store may already have been switched to the delegator's store
|
||||
// while the draft lives in the user's own store.
|
||||
try {
|
||||
$message = $GLOBALS['operations']->openMessage($store, $entryid);
|
||||
}
|
||||
catch (MAPIException $e) {
|
||||
$e->setHandled();
|
||||
|
||||
try {
|
||||
$defaultStore = $GLOBALS['mapisession']->getDefaultMessageStore();
|
||||
if ($defaultStore === false) {
|
||||
$message = false;
|
||||
}
|
||||
else {
|
||||
$message = $GLOBALS['operations']->openMessage($defaultStore, $entryid);
|
||||
}
|
||||
}
|
||||
catch (MAPIException $e) {
|
||||
$e->setHandled();
|
||||
$message = false;
|
||||
}
|
||||
}
|
||||
if ($message) {
|
||||
$savedRecipients = $GLOBALS['operations']->getRecipientsInfo($message);
|
||||
foreach ($savedRecipients as $recipient) {
|
||||
$savedUnsavedRecipients['saved'][] = $recipient['props'];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!empty($recipients['add'])) {
|
||||
foreach ($recipients['add'] as $recipient) {
|
||||
$savedUnsavedRecipients['unsaved'][] = $recipient;
|
||||
}
|
||||
}
|
||||
|
||||
$remove = !empty($recipients['remove']) ? $recipients['remove'] : [];
|
||||
$members = $GLOBALS['operations']->convertLocalDistlistMembersToRecipients($savedUnsavedRecipients, $remove);
|
||||
$action['recipients'] = $action['recipients'] ?? [];
|
||||
$action['recipients']['add'] = $members['add'];
|
||||
$action['recipients']['remove'] = !empty($remove) ? array_merge($action['recipients']['remove'] ?? [], $members['remove']) : $members['remove'];
|
||||
|
||||
$error = $GLOBALS['operations']->submitMessage(
|
||||
$store,
|
||||
$entryid,
|
||||
$this->withThreadingProperties(Conversion::mapXML2MAPI($this->properties, $action['props']), $copyInlineAttachmentsOnly),
|
||||
$messageProps,
|
||||
$action['recipients'] ?? [],
|
||||
$action['attachments'] ?? [],
|
||||
$copyFromMessage,
|
||||
$copyAttachments,
|
||||
false,
|
||||
$copyInlineAttachmentsOnly,
|
||||
isset($action['props']['isHTML']) ? !$action['props']['isHTML'] : false
|
||||
);
|
||||
|
||||
if (!$error) {
|
||||
$GLOBALS['operations']->parseDistListAndAddToRecipientHistory($savedUnsavedRecipients, $remove);
|
||||
if ($entryid) {
|
||||
$props = [];
|
||||
$props[PR_ENTRYID] = $entryid;
|
||||
$props[PR_PARENT_ENTRYID] = $parententryid;
|
||||
$storeProps = mapi_getprops($store, [PR_ENTRYID]);
|
||||
$props[PR_STORE_ENTRYID] = $storeProps[PR_ENTRYID];
|
||||
$GLOBALS['bus']->addData($this->getResponseData());
|
||||
$GLOBALS['bus']->notify(bin2hex($parententryid), TABLE_DELETE, $props);
|
||||
}
|
||||
$this->sendFeedback(true, [], false);
|
||||
|
||||
return ['result' => true, 'aborted' => false];
|
||||
}
|
||||
|
||||
$data = [];
|
||||
$data['type'] = 1;
|
||||
$data['info'] = [];
|
||||
|
||||
if ($error === 'MAPI_E_NO_ACCESS') {
|
||||
$data['info']['title'] = _('Insufficient permissions');
|
||||
$data['info']['display_message'] = _("You don't have the permission to complete this action");
|
||||
}
|
||||
elseif ($error === 'ecQuotaExceeded') {
|
||||
$data['info']['title'] = _('Quota error');
|
||||
$data['info']['display_message'] = _('Send quota limit reached');
|
||||
}
|
||||
elseif ($error === 'SENDAS_IDENTITY_MISMATCH') {
|
||||
$data['info']['title'] = _('Sender address could not be applied');
|
||||
$data['info']['display_message'] = _('The message was not sent because the selected sender address could not be applied. Please try again.');
|
||||
}
|
||||
else {
|
||||
$data['info']['title'] = _('Operation failed');
|
||||
$data['info']['display_message'] = sprintf(_('Email sending failed (%s). Check the log files for more information.'), $error);
|
||||
}
|
||||
$this->addActionData('error', $data);
|
||||
|
||||
return ['result' => false, 'aborted' => false];
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle the draft save flow including attachment and plugin updates.
|
||||
*
|
||||
* @param mixed $store
|
||||
* @param mixed $entryid
|
||||
* @param mixed $parententryid
|
||||
* @param mixed $copyFromMessage
|
||||
* @param bool $copyAttachments
|
||||
* @param bool $copyInlineAttachmentsOnly
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
private function handleDraftSave($store, $entryid, $parententryid, array $action, array &$messageProps, $copyFromMessage, $copyAttachments, $copyInlineAttachmentsOnly) {
|
||||
$propertiesToDelete = [];
|
||||
$mapiProps = $this->withThreadingProperties(Conversion::mapXML2MAPI($this->properties, $action['props']), $copyInlineAttachmentsOnly);
|
||||
if (isset($action['props']['sent_representing_entryid']) && empty($action['props']['sent_representing_entryid'])) {
|
||||
$propertiesToDelete[] = PR_SENT_REPRESENTING_ENTRYID;
|
||||
$propertiesToDelete[] = PR_SENT_REPRESENTING_SEARCH_KEY;
|
||||
// Also drop a previously stored SMTP address, otherwise it would
|
||||
// survive the removal of the From identity on the draft and could
|
||||
// be picked up again as the sending identity.
|
||||
$propertiesToDelete[] = PR_SENT_REPRESENTING_SMTP_ADDRESS;
|
||||
}
|
||||
|
||||
$result = $GLOBALS['operations']->saveMessage(
|
||||
$store,
|
||||
$entryid,
|
||||
$parententryid,
|
||||
$mapiProps,
|
||||
$messageProps,
|
||||
$action['recipients'] ?? [],
|
||||
$action['attachments'] ?? [],
|
||||
$propertiesToDelete,
|
||||
$copyFromMessage,
|
||||
$copyAttachments,
|
||||
false,
|
||||
$copyInlineAttachmentsOnly
|
||||
);
|
||||
|
||||
if (!$result) {
|
||||
return ['result' => false, 'aborted' => false];
|
||||
}
|
||||
|
||||
$props = mapi_getprops($result, [PR_ENTRYID]);
|
||||
$savedMsg = $GLOBALS['operations']->openMessage($store, $props[PR_ENTRYID]);
|
||||
$attachNum = !empty($action['attach_num']) ? $action['attach_num'] : false;
|
||||
$data = [];
|
||||
|
||||
if ($attachNum) {
|
||||
$message = $GLOBALS['operations']->openMessage($store, $props[PR_ENTRYID], $attachNum);
|
||||
if (empty($message)) {
|
||||
return ['result' => false, 'aborted' => true];
|
||||
}
|
||||
$data['item'] = $GLOBALS['operations']->getEmbeddedMessageProps($store, $message, $this->properties, $savedMsg, $attachNum);
|
||||
}
|
||||
else {
|
||||
$data = $GLOBALS['operations']->getMessageProps($store, $savedMsg, $this->properties, $this->plaintext, true);
|
||||
}
|
||||
|
||||
unset($data['props']['body'], $data['props']['html_body'], $data['props']['isHTML']);
|
||||
|
||||
$GLOBALS['PluginManager']->triggerHook('server.module.createmailitemmodule.aftersave', [
|
||||
'data' => &$data,
|
||||
'entryid' => $props[PR_ENTRYID],
|
||||
'action' => $action,
|
||||
'properties' => $this->properties,
|
||||
'messageProps' => $messageProps,
|
||||
'parententryid' => $parententryid,
|
||||
]);
|
||||
|
||||
$this->addActionData('update', ['item' => $data]);
|
||||
|
||||
return ['result' => $result, 'aborted' => false];
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert a hexadecimal string to binary data, returning false when invalid.
|
||||
*
|
||||
* @param string $value
|
||||
*
|
||||
* @return false|string
|
||||
*/
|
||||
private function hexToBinOrFalse($value) {
|
||||
if ($value === '') {
|
||||
return '';
|
||||
}
|
||||
|
||||
if (!is_hex_entryid($value)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return hex2bin($value);
|
||||
}
|
||||
|
||||
/**
|
||||
* Function which is used to get the source message information, which contains the information of
|
||||
* reply/forward and entry id of original mail, where we have to set the reply/forward arrow when
|
||||
* draft(saved mail) is send.
|
||||
*
|
||||
* @param array $action the action data, sent by the client
|
||||
*
|
||||
* @return array|bool false when entryid and source message entryid is missing otherwise array with
|
||||
* source store entryid and source message entryid if message has
|
||||
*/
|
||||
public function getSourceMsgInfo($action) {
|
||||
$metaData = [];
|
||||
if (isset($action["props"]["source_message_info"]) && !empty($action["props"]["source_message_info"])) {
|
||||
if (isset($action["props"]['sent_representing_entryid']) && !empty($action["props"]['sent_representing_entryid'])) {
|
||||
$storeEntryid = hex2bin((string) $action['message_action']['source_store_entryid']);
|
||||
}
|
||||
else {
|
||||
$storeEntryid = hex2bin((string) $action['store_entryid']);
|
||||
}
|
||||
$metaData['source_message_info'] = $action["props"]["source_message_info"];
|
||||
$metaData['storeEntryid'] = $storeEntryid;
|
||||
|
||||
return $metaData;
|
||||
}
|
||||
if (isset($action["entryid"]) && !empty($action["entryid"])) {
|
||||
$storeEntryid = hex2bin((string) $action['store_entryid']);
|
||||
$store = $GLOBALS['mapisession']->openMessageStore($storeEntryid);
|
||||
|
||||
$entryid = hex2bin((string) $action['entryid']);
|
||||
|
||||
try {
|
||||
$message = $GLOBALS['operations']->openMessage($store, $entryid);
|
||||
}
|
||||
catch (MAPIException $e) {
|
||||
$e->setHandled();
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
$messageProps = mapi_getprops($message);
|
||||
|
||||
$props = Conversion::mapMAPI2XML($this->properties, $messageProps);
|
||||
|
||||
$sourceMsgInfo = !empty($props['props']['source_message_info']) ? $props['props']['source_message_info'] : false;
|
||||
if ($sourceMsgInfo === false) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (isset($props["props"]['sent_representing_entryid']) && !empty($props["props"]['sent_representing_entryid'])) {
|
||||
$storeEntryid = $this->getSourceStoreEntryId($props);
|
||||
}
|
||||
|
||||
$metaData['source_message_info'] = $sourceMsgInfo;
|
||||
$metaData['storeEntryid'] = $storeEntryid;
|
||||
|
||||
return $metaData;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Function is used to get the shared or delegate store entryid where
|
||||
* source message was stored, so the reply/forward arrow can be set when
|
||||
* the draft (saved mail) is sent.
|
||||
*
|
||||
* @param array $props the $props data, which get from saved mail
|
||||
*
|
||||
* @return string source store entryid
|
||||
*/
|
||||
public function getSourceStoreEntryId($props) {
|
||||
$sentRepresentingEntryid = $props['props']['sent_representing_entryid'];
|
||||
$user = mapi_ab_openentry($GLOBALS['mapisession']->getAddressbook(), hex2bin((string) $sentRepresentingEntryid));
|
||||
$userProps = mapi_getprops($user, [PR_EMAIL_ADDRESS]);
|
||||
|
||||
return $GLOBALS['mapisession']->getStoreEntryIdOfUser(strtolower((string) $userProps[PR_EMAIL_ADDRESS]));
|
||||
}
|
||||
|
||||
/**
|
||||
* Function is used to set the reply/forward arrow on original mail.
|
||||
*
|
||||
* @param array $action the action data, sent by the client
|
||||
*/
|
||||
public function setReplyForwardInfo($action) {
|
||||
$sourceMsgInfo = $this->getSourceMsgInfo($action);
|
||||
if (isset($sourceMsgInfo['source_message_info']) && $sourceMsgInfo['source_message_info']) {
|
||||
/**
|
||||
* $sourceMsgInfo['source_message_info'] contains a hexadecimal record. The action type occupies
|
||||
* two hexadecimal characters starting at offset 24 (byte 12), and the original message entry ID
|
||||
* begins at offset 48, after the 24-byte metadata prefix.
|
||||
*
|
||||
* Example: 01000E000C00000005010000660000000200000030000000 + record entry ID
|
||||
* Here, 66 represents REPLY; similarly, 67 and 68 represent REPLY ALL and FORWARD, respectively.
|
||||
*/
|
||||
$mailActionType = substr((string) $sourceMsgInfo['source_message_info'], 24, 2);
|
||||
// Get the entry ID of the original message.
|
||||
$originalEntryid = substr((string) $sourceMsgInfo['source_message_info'], 48);
|
||||
$entryid = hex2bin($originalEntryid);
|
||||
|
||||
$store = $GLOBALS['mapisession']->openMessageStore($sourceMsgInfo['storeEntryid']);
|
||||
|
||||
try {
|
||||
// if original mail of reply/forward mail is deleted from inbox then,
|
||||
// it will throw an exception so to handle it we need to write this block in try catch.
|
||||
$message = $GLOBALS['operations']->openMessage($store, $entryid);
|
||||
}
|
||||
catch (MAPIException $e) {
|
||||
$e->setHandled();
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
if ($message) {
|
||||
$messageProps = mapi_getprops($message);
|
||||
$props = Conversion::mapMAPI2XML($this->properties, $messageProps);
|
||||
|
||||
switch ($mailActionType) {
|
||||
case '66': // Reply
|
||||
case '67': // Reply All
|
||||
$props['icon_index'] = 261;
|
||||
break;
|
||||
|
||||
case '68':// Forward
|
||||
$props['icon_index'] = 262;
|
||||
break;
|
||||
}
|
||||
$props['last_verb_executed'] = hexdec($mailActionType);
|
||||
$props['last_verb_execution_time'] = time();
|
||||
$mapiProps = Conversion::mapXML2MAPI($this->properties, $props);
|
||||
$messageActionProps = [];
|
||||
$messageActionResult = $GLOBALS['operations']->saveMessage($store, $mapiProps[PR_ENTRYID], $mapiProps[PR_PARENT_ENTRYID], $mapiProps, $messageActionProps);
|
||||
if ($messageActionResult) {
|
||||
if (isset($messageActionProps[PR_PARENT_ENTRYID])) {
|
||||
$GLOBALS['bus']->notify(bin2hex($messageActionProps[PR_PARENT_ENTRYID]), TABLE_SAVE, $messageActionProps);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,847 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* SPDX-FileCopyrightText: Copyright 2020 - 2026 grommunio GmbH
|
||||
* SPDX-FileCopyrightText: Copyright 2016 Kopano and its licensors
|
||||
* SPDX-FileCopyrightText: Copyright 2005 - 2016 Zarafa B.V. and its licensors
|
||||
* SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
*/
|
||||
|
||||
/**
|
||||
* DelegatesModule
|
||||
* Class can be used to get delegate information of a particular user.
|
||||
* The delegate information can be created/update using this class as well.
|
||||
*/
|
||||
class DelegatesModule extends Module {
|
||||
/**
|
||||
* @var array contains entryid's of all default folders
|
||||
*/
|
||||
private $defaultFolders;
|
||||
|
||||
/**
|
||||
* @var array contains delegate properties from special message (LocalFreebusy)
|
||||
*/
|
||||
private $delegateProps;
|
||||
|
||||
/**
|
||||
* @var false|resource LocalFreeBusy message, or false before it is opened
|
||||
*/
|
||||
private $localFreeBusyMessage;
|
||||
|
||||
/**
|
||||
* @var false|resource FreeBusy folder in IPM_SUBTREE, or false before it is opened
|
||||
*/
|
||||
private $freeBusyFolder;
|
||||
|
||||
/**
|
||||
* @var false|resource default store of the current user, or false before it is opened
|
||||
*/
|
||||
private $defaultStore;
|
||||
|
||||
/**
|
||||
* Constructor.
|
||||
*
|
||||
* @param int $id unique id
|
||||
* @param array $data list of all actions
|
||||
*/
|
||||
public function __construct($id, $data) {
|
||||
$this->defaultFolders = [];
|
||||
$this->delegateProps = [];
|
||||
$this->localFreeBusyMessage = false;
|
||||
$this->freeBusyFolder = false;
|
||||
$this->defaultStore = false;
|
||||
|
||||
parent::__construct($id, $data);
|
||||
}
|
||||
|
||||
/**
|
||||
* Executes all the actions in the $data variable.
|
||||
*/
|
||||
#[Override]
|
||||
public function execute() {
|
||||
$delegatesLock = State::forStore('delegates-write');
|
||||
if (!$delegatesLock->open()) {
|
||||
throw new RuntimeException('Unable to lock the delegate settings');
|
||||
}
|
||||
|
||||
try {
|
||||
$this->executeLocked();
|
||||
}
|
||||
finally {
|
||||
$delegatesLock->close();
|
||||
}
|
||||
}
|
||||
|
||||
private function executeLocked() {
|
||||
foreach ($this->data as $actionType => $action) {
|
||||
if (isset($actionType)) {
|
||||
try {
|
||||
switch ($actionType) {
|
||||
case 'list':
|
||||
$this->delegateList();
|
||||
break;
|
||||
|
||||
case 'open':
|
||||
$this->openDelegate($action);
|
||||
break;
|
||||
|
||||
case 'save':
|
||||
$this->saveDelegates($action);
|
||||
break;
|
||||
|
||||
case 'delete':
|
||||
$this->deleteDelegates($action);
|
||||
break;
|
||||
|
||||
default:
|
||||
$this->handleUnknownActionType($actionType);
|
||||
}
|
||||
}
|
||||
catch (MAPIException $e) {
|
||||
$this->processException($e, $actionType);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* Generic functions to access data */
|
||||
|
||||
/**
|
||||
* Function will return values of the properties PR_DELEGATE_FLAGS, PR_SCHDINFO_DELEGATE_ENTRYIDS and
|
||||
* PR_SCHDINFO_DELEGATE_NAMES from LocalFreeBusyMessage of the user's store.
|
||||
*
|
||||
* @param resource $localFreeBusyMessage (optional) local freebusy message of the user's store
|
||||
*
|
||||
* @return array values of delegate properties
|
||||
*/
|
||||
public function getDelegateProps($localFreeBusyMessage = false) {
|
||||
if (empty($this->delegateProps)) {
|
||||
if ($localFreeBusyMessage === false) {
|
||||
$localFreeBusyMessage = FreeBusy::getLocalFreeBusyMessage($this->getDefaultStore());
|
||||
}
|
||||
|
||||
$this->delegateProps = mapi_getprops($localFreeBusyMessage, [PR_DELEGATE_FLAGS, PR_SCHDINFO_DELEGATE_ENTRYIDS, PR_SCHDINFO_DELEGATE_NAMES]);
|
||||
|
||||
// check if properties exists or not, if not then initialize with default values
|
||||
// this way in caller functions we don't need to check for non-existent properties
|
||||
if (!isset($this->delegateProps[PR_DELEGATE_FLAGS])) {
|
||||
$this->delegateProps[PR_DELEGATE_FLAGS] = [];
|
||||
}
|
||||
|
||||
if (!isset($this->delegateProps[PR_SCHDINFO_DELEGATE_ENTRYIDS])) {
|
||||
$this->delegateProps[PR_SCHDINFO_DELEGATE_ENTRYIDS] = [];
|
||||
}
|
||||
|
||||
if (!isset($this->delegateProps[PR_SCHDINFO_DELEGATE_NAMES])) {
|
||||
$this->delegateProps[PR_SCHDINFO_DELEGATE_NAMES] = [];
|
||||
}
|
||||
}
|
||||
|
||||
return $this->delegateProps;
|
||||
}
|
||||
|
||||
/**
|
||||
* Function will return array of entryids of default folders of the user's store.
|
||||
*
|
||||
* @param resource $store (optional) user's store
|
||||
*
|
||||
* @return array default folder entryids
|
||||
*/
|
||||
public function getDefaultFolders($store = false) {
|
||||
if (empty($this->defaultFolders)) {
|
||||
if ($store === false) {
|
||||
$store = $this->getDefaultStore();
|
||||
}
|
||||
|
||||
// Get root store
|
||||
$root = mapi_msgstore_openentry($store);
|
||||
|
||||
// Get Inbox folder
|
||||
$inbox = mapi_msgstore_getreceivefolder($store);
|
||||
$inboxprops = mapi_getprops($inbox, [PR_ENTRYID]);
|
||||
|
||||
// Get entryids of default folders.
|
||||
$rootStoreProps = mapi_getprops($root, [PR_IPM_APPOINTMENT_ENTRYID, PR_IPM_TASK_ENTRYID, PR_IPM_CONTACT_ENTRYID, PR_IPM_NOTE_ENTRYID, PR_IPM_JOURNAL_ENTRYID]);
|
||||
|
||||
$this->defaultFolders = [
|
||||
'calendar' => $rootStoreProps[PR_IPM_APPOINTMENT_ENTRYID],
|
||||
'tasks' => $rootStoreProps[PR_IPM_TASK_ENTRYID],
|
||||
'inbox' => $inboxprops[PR_ENTRYID],
|
||||
'contacts' => $rootStoreProps[PR_IPM_CONTACT_ENTRYID],
|
||||
'notes' => $rootStoreProps[PR_IPM_NOTE_ENTRYID],
|
||||
'journal' => $rootStoreProps[PR_IPM_JOURNAL_ENTRYID],
|
||||
];
|
||||
}
|
||||
|
||||
return $this->defaultFolders;
|
||||
}
|
||||
|
||||
/**
|
||||
* Function will return index of a particular delegate, this index can be used to get information of
|
||||
* delegate from PR_DELEGATE_FLAGS, PR_SCHDINFO_DELEGATE_ENTRYIDS and
|
||||
* PR_SCHDINFO_DELEGATE_NAMES properties.
|
||||
*
|
||||
* @param string $entryId entryid of delegate
|
||||
*
|
||||
* @return false|int|string index of the delegate information, or false when it is absent
|
||||
*/
|
||||
public function getDelegateIndex($entryId) {
|
||||
$delegateProps = $this->getDelegateProps();
|
||||
|
||||
// Check if user is existing delegate.
|
||||
if (!empty($delegateProps[PR_SCHDINFO_DELEGATE_ENTRYIDS])) {
|
||||
return array_search($entryId, $delegateProps[PR_SCHDINFO_DELEGATE_ENTRYIDS]);
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Function will return resource of the default store of the current logged in user.
|
||||
*
|
||||
* @return resource current user's store
|
||||
*/
|
||||
public function getDefaultStore() {
|
||||
if (!$this->defaultStore) {
|
||||
$this->defaultStore = $GLOBALS['mapisession']->getDefaultMessageStore();
|
||||
}
|
||||
|
||||
return $this->defaultStore;
|
||||
}
|
||||
|
||||
/**
|
||||
* Function will return properties of the user from addressbook based on passed user's entryid.
|
||||
*
|
||||
* @param string $userEntryId entryid of the user from addressbook
|
||||
*
|
||||
* @return array properties of user from addressbook
|
||||
*/
|
||||
public function getUserInfo($userEntryId) {
|
||||
// default return stuff
|
||||
$result = [
|
||||
'display_name' => _('Unknown user/group'),
|
||||
'entryid' => null,
|
||||
];
|
||||
|
||||
// open the addressbook
|
||||
$ab = $GLOBALS['mapisession']->getAddressbook();
|
||||
|
||||
try {
|
||||
// try userid as normal user
|
||||
$user = mapi_ab_openentry($ab, $userEntryId);
|
||||
}
|
||||
catch (MAPIException $e) {
|
||||
if ($e->getCode() === MAPI_E_NOT_FOUND) {
|
||||
$e->setHandled();
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
throw $e;
|
||||
}
|
||||
|
||||
$props = mapi_getprops($user, [PR_DISPLAY_NAME]);
|
||||
$result['display_name'] = $props[PR_DISPLAY_NAME];
|
||||
$result['entryid'] = bin2hex($userEntryId);
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
/* Functions to get delegates information */
|
||||
|
||||
/**
|
||||
* Function will return all the delegates information for current user.
|
||||
*/
|
||||
public function delegateList() {
|
||||
$data = [];
|
||||
$delegates = mapi_getdelegates($GLOBALS['mapisession']->getSession(), 0);
|
||||
if (!empty($delegates)) {
|
||||
$delegateMeetingRule = $this->getDelegateMeetingRule();
|
||||
foreach ($delegates as $username) {
|
||||
// Exact lookup: resolvename substring-matches names, addresses and
|
||||
// aliases, so one delegate could resolve ambiguously and fail the list.
|
||||
try {
|
||||
$userEntryId = nsp_getuserinfo($username)['userid'];
|
||||
}
|
||||
catch (MAPIException $e) {
|
||||
// Stale entry, e.g. a deleted user
|
||||
continue;
|
||||
}
|
||||
array_push($data, $this->getDelegatePermissions($userEntryId, $delegateMeetingRule));
|
||||
}
|
||||
}
|
||||
|
||||
$this->addActionData('list', ['item' => $data]);
|
||||
$GLOBALS['bus']->addData($this->getResponseData());
|
||||
}
|
||||
|
||||
/**
|
||||
* Function will return the permissions assigned for a particular delegate user.
|
||||
*
|
||||
* @param array $delegate the delegate information sent by client
|
||||
*/
|
||||
public function openDelegate($delegate) {
|
||||
// Get permissions of a delegate.
|
||||
$data = $this->getDelegatePermissions(hex2bin((string) $delegate['entryid']));
|
||||
|
||||
$this->addActionData('item', ['item' => $data]);
|
||||
$GLOBALS['bus']->addData($this->getResponseData());
|
||||
}
|
||||
|
||||
/**
|
||||
* Function will return information of a particular delegate from current user's store.
|
||||
*
|
||||
* @param string $userEntryId entryid of the delegate
|
||||
* @param null|array|false $delegateMeetingRule (optional) delegate meeting rule or false when none exists, fetched when null
|
||||
*
|
||||
* @return array delegate information
|
||||
*/
|
||||
public function getDelegatePermissions($userEntryId, $delegateMeetingRule = null) {
|
||||
$delegateProps = $this->getDelegateProps();
|
||||
$delegateIndex = $this->getDelegateIndex($userEntryId);
|
||||
$userinfo = $this->getUserInfo($userEntryId);
|
||||
|
||||
if ($delegateMeetingRule === null) {
|
||||
$delegateMeetingRule = $this->getDelegateMeetingRule();
|
||||
}
|
||||
$ruleUsers = $this->getDelegateMeetingRuleUsers($delegateMeetingRule);
|
||||
|
||||
$delegate = [];
|
||||
$delegate['entryid'] = bin2hex($userEntryId);
|
||||
|
||||
$delegate['props'] = [];
|
||||
$delegate['props']['display_name'] = $userinfo['display_name'];
|
||||
$delegate['props']['can_see_private'] = $delegateIndex !== false && isset($delegateProps[PR_DELEGATE_FLAGS][$delegateIndex]) ? ($delegateProps[PR_DELEGATE_FLAGS][$delegateIndex] == 1) : false;
|
||||
$delegate['props']['has_meeting_rule'] = $this->findDelegateMeetingRuleUser($ruleUsers, $userEntryId) !== false;
|
||||
|
||||
$delegate['props'] = array_merge($delegate['props'], $this->getFolderPermissions($userEntryId));
|
||||
|
||||
return $delegate;
|
||||
}
|
||||
|
||||
/**
|
||||
* Function will return folder permissions of a delegate user.
|
||||
*
|
||||
* @param string $userEntryId entryid of the delegate
|
||||
*
|
||||
* @return array folder permissions of a delegate user
|
||||
*/
|
||||
public function getFolderPermissions($userEntryId) {
|
||||
$delegateRights = [];
|
||||
$store = $this->getDefaultStore();
|
||||
|
||||
foreach ($this->getDefaultFolders($store) as $folderName => $folderEntryId) {
|
||||
$folder = mapi_msgstore_openentry($store, $folderEntryId);
|
||||
|
||||
// Get all users who has permissions
|
||||
$grants = mapi_zarafa_getpermissionrules($folder, ACCESS_TYPE_GRANT);
|
||||
|
||||
// Find current delegate and get permission.
|
||||
foreach ($grants as $id => $grant) {
|
||||
if ($GLOBALS["entryid"]->compareEntryIds(bin2hex($userEntryId), bin2hex((string) $grant['userid']))) {
|
||||
$delegateRights['rights_' . $folderName] = $grant['rights'];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return $delegateRights;
|
||||
}
|
||||
|
||||
/**
|
||||
* Function will return properties of meeting rule that is used to send meeting related messages to delegate.
|
||||
*
|
||||
* @return array|false delegate meeting rule information, or false when no rule exists
|
||||
*/
|
||||
public function getDelegateMeetingRule() {
|
||||
$inbox = mapi_msgstore_getreceivefolder($this->getDefaultStore());
|
||||
$rulesTable = mapi_folder_getrulestable($inbox);
|
||||
// get delegate meeting rule
|
||||
$restriction = [RES_CONTENT,
|
||||
[
|
||||
FUZZYLEVEL => FL_FULLSTRING | FL_IGNORECASE,
|
||||
ULPROPTAG => PR_RULE_PROVIDER,
|
||||
VALUE => [
|
||||
PR_RULE_PROVIDER => 'Schedule+ EMS Interface',
|
||||
],
|
||||
],
|
||||
];
|
||||
mapi_table_restrict($rulesTable, $restriction);
|
||||
// there will be only one rule, so fetch that only
|
||||
$delegateMeetingRule = mapi_table_queryrows($rulesTable, $GLOBALS['properties']->getRulesProperties(), 0, 1);
|
||||
|
||||
return !empty($delegateMeetingRule) ? $delegateMeetingRule[0] : false;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array|false $delegateMeetingRule delegate meeting rule
|
||||
*
|
||||
* @return array recipients of the rule's delegate action
|
||||
*/
|
||||
private function getDelegateMeetingRuleUsers($delegateMeetingRule) {
|
||||
return $delegateMeetingRule !== false ? ($delegateMeetingRule[PR_RULE_ACTIONS][0]['adrlist'] ?? []) : [];
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array $users recipients of the delegate meeting rule
|
||||
* @param string $userEntryId entryid of the delegate
|
||||
*
|
||||
* @return false|int position of the delegate in $users, or false when absent
|
||||
*/
|
||||
private function findDelegateMeetingRuleUser($users, $userEntryId) {
|
||||
foreach ($users as $index => $user) {
|
||||
if (isset($user[PR_ENTRYID]) && $GLOBALS['entryid']->compareEntryIds(bin2hex((string) $user[PR_ENTRYID]), bin2hex($userEntryId))) {
|
||||
return $index;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/* Functions to update delegates information */
|
||||
|
||||
/**
|
||||
* Function which saves delegates information sent from client.
|
||||
*
|
||||
* @param array $delegates the delegates information sent by client
|
||||
*/
|
||||
public function saveDelegates($delegates) {
|
||||
$responseData = [];
|
||||
|
||||
// @FIXME currently client only sends a single delegate in a request, if we can change that to contain
|
||||
// multiple delegates that would be good
|
||||
|
||||
if (is_assoc_array($delegates)) {
|
||||
// wrap single delegate in an array
|
||||
$delegates = [$delegates];
|
||||
}
|
||||
|
||||
for ($index = 0, $len = count($delegates); $index < $len; ++$index) {
|
||||
$delegate = $delegates[$index];
|
||||
$this->setFolderPermissions($delegate);
|
||||
// set properties for delegates on user's freebusy folder
|
||||
array_push($responseData, ['entryid' => $delegate['entryid']]);
|
||||
}
|
||||
$this->setDelegateProps($delegates);
|
||||
// set delegate meeting rule
|
||||
$this->setDelegateMeetingRule($delegates);
|
||||
|
||||
// send response to indicate success
|
||||
if (!empty($responseData)) {
|
||||
$this->addActionData('update', ['item' => $responseData]);
|
||||
$GLOBALS['bus']->addData($this->getResponseData());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Function will update PR_DELEGATE_FLAGS, PR_SCHDINFO_DELEGATE_ENTRYIDS and
|
||||
* PR_SCHDINFO_DELEGATE_NAMES properties in the current user's store.
|
||||
*
|
||||
* @param mixed $delegates
|
||||
*/
|
||||
public function setDelegateProps($delegates) {
|
||||
$localFreeBusyMessage = FreeBusy::getLocalFreeBusyMessage($this->getDefaultStore());
|
||||
$delegateProps = $this->getDelegateProps($localFreeBusyMessage);
|
||||
$len = count($delegates);
|
||||
for ($i = 0; $i < $len; ++$i) {
|
||||
$delegate = $delegates[$i];
|
||||
$len1 = count($delegateProps[PR_SCHDINFO_DELEGATE_ENTRYIDS]);
|
||||
for ($j = 0; $j < $len1; ++$j) {
|
||||
if ($delegateProps[PR_SCHDINFO_DELEGATE_ENTRYIDS][$j] == hex2bin((string) $delegate['entryid'])) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
$delegateProps[PR_SCHDINFO_DELEGATE_ENTRYIDS][$j] = hex2bin((string) $delegate['entryid']);
|
||||
if (isset($delegate['props']['display_name'])) {
|
||||
$delegateProps[PR_SCHDINFO_DELEGATE_NAMES][$j] = $delegate['props']['display_name'];
|
||||
}
|
||||
elseif (!isset($delegateProps[PR_SCHDINFO_DELEGATE_NAMES][$j])) {
|
||||
$addrBook = $GLOBALS['mapisession']->getAddressbook();
|
||||
$user = mapi_ab_openentry($addrBook, hex2bin((string) $delegate['entryid']));
|
||||
if (empty($user)) {
|
||||
$delegateProps[PR_SCHDINFO_DELEGATE_NAMES][$j] = "";
|
||||
}
|
||||
else {
|
||||
$userProps = mapi_getprops($user, [PR_SMTP_ADDRESS]);
|
||||
if (empty($userProps[PR_SMTP_ADDRESS])) {
|
||||
$delegateProps[PR_SCHDINFO_DELEGATE_NAMES][$j] = "";
|
||||
}
|
||||
else {
|
||||
$delegateProps[PR_SCHDINFO_DELEGATE_NAMES][$j] = $userProps[PR_SMTP_ADDRESS];
|
||||
}
|
||||
}
|
||||
}
|
||||
if (isset($delegate['props']['can_see_private'])) {
|
||||
$delegateProps[PR_DELEGATE_FLAGS][$j] = $delegate['props']['can_see_private'];
|
||||
}
|
||||
elseif (!isset($delegateProps[PR_DELEGATE_FLAGS][$j])) {
|
||||
$delegateProps[PR_DELEGATE_FLAGS][$j] = false;
|
||||
}
|
||||
}
|
||||
mapi_setprops($localFreeBusyMessage, $delegateProps);
|
||||
mapi_savechanges($localFreeBusyMessage);
|
||||
// unset the module variable, so subsequent calls will have the updated value
|
||||
unset($this->delegateProps);
|
||||
}
|
||||
|
||||
/**
|
||||
* Function will set folder permissions for a delegate user.
|
||||
*
|
||||
* @param array $delegate delegate information sent from client
|
||||
*/
|
||||
public function setFolderPermissions($delegate) {
|
||||
$store = $this->getDefaultStore();
|
||||
|
||||
// Get all default folders and set permissions.
|
||||
foreach ($this->getDefaultFolders($store) as $folderName => $folderEntryID) {
|
||||
// we need to only modify those permissions which are modified on client
|
||||
if (isset($delegate['props']['rights_' . $folderName]) && $delegate['props']['rights_' . $folderName] !== '') {
|
||||
$folder = mapi_msgstore_openentry($store, $folderEntryID);
|
||||
|
||||
// Set new permissions.
|
||||
$acls = [
|
||||
[
|
||||
'type' => ACCESS_TYPE_GRANT,
|
||||
'userid' => hex2bin((string) $delegate['entryid']),
|
||||
'rights' => $delegate['props']['rights_' . $folderName],
|
||||
'state' => RIGHT_NEW | RIGHT_AUTOUPDATE_DENIED,
|
||||
'memberid' => 0,
|
||||
],
|
||||
];
|
||||
|
||||
mapi_zarafa_setpermissionrules($folder, $acls);
|
||||
mapi_savechanges($folder);
|
||||
|
||||
if ($folderName === 'calendar') {
|
||||
$freeBusyFolder = FreeBusy::getLocalFreeBusyFolder($store);
|
||||
|
||||
if ($freeBusyFolder !== false) {
|
||||
// set permissions on free/busy message
|
||||
$acls[0]['rights'] |= ecRightsDefaultPublic;
|
||||
|
||||
mapi_zarafa_setpermissionrules($freeBusyFolder, $acls);
|
||||
mapi_savechanges($freeBusyFolder);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Function which creates/modifies delegate meeting rule in user store
|
||||
* to send meeting request mails to delegates also.
|
||||
*
|
||||
* @param array $delegates all delegate information
|
||||
*/
|
||||
public function setDelegateMeetingRule($delegates) {
|
||||
$delegateMeetingRule = $this->getDelegateMeetingRule();
|
||||
$users = $this->getDelegateMeetingRuleUsers($delegateMeetingRule);
|
||||
$addrBook = $GLOBALS['mapisession']->getAddressbook();
|
||||
$changed = false;
|
||||
|
||||
foreach ($delegates as $delegate) {
|
||||
// existing delegates only send the flag when the checkbox changed
|
||||
if (!isset($delegate['props']['has_meeting_rule'])) {
|
||||
continue;
|
||||
}
|
||||
$userEntryId = hex2bin((string) $delegate['entryid']);
|
||||
$index = $this->findDelegateMeetingRuleUser($users, $userEntryId);
|
||||
|
||||
if (!$delegate['props']['has_meeting_rule']) {
|
||||
if ($index !== false) {
|
||||
array_splice($users, $index, 1);
|
||||
$changed = true;
|
||||
}
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
$user = mapi_ab_openentry($addrBook, $userEntryId);
|
||||
$userProps = mapi_getprops($user, [PR_ENTRYID, PR_ADDRTYPE, PR_EMAIL_ADDRESS, PR_DISPLAY_NAME, PR_SEARCH_KEY, PR_SMTP_ADDRESS, PR_OBJECT_TYPE, PR_DISPLAY_TYPE, PR_DISPLAY_TYPE_EX]);
|
||||
if (!is_array($userProps)) {
|
||||
continue;
|
||||
}
|
||||
$userProps[PR_RECIPIENT_TYPE] = MAPI_TO;
|
||||
if ($index === false) {
|
||||
$users[] = $userProps;
|
||||
}
|
||||
else {
|
||||
$users[$index] = $userProps;
|
||||
}
|
||||
$changed = true;
|
||||
}
|
||||
|
||||
if (!$changed) {
|
||||
return;
|
||||
}
|
||||
if ($delegateMeetingRule === false) {
|
||||
$this->createDelegateMeetingRule($users);
|
||||
}
|
||||
else {
|
||||
$this->modifyDelegateMeetingRule($delegateMeetingRule, $users);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Function will create a new delegate meeting rule if it is not present in current user's store.
|
||||
*
|
||||
* @param array $usersInfo user properties which should be added in PR_RULE_ACTIONS
|
||||
*/
|
||||
public function createDelegateMeetingRule($usersInfo) {
|
||||
// create new rule
|
||||
$rule = [];
|
||||
|
||||
// no need to pass rule_id when creating new rule
|
||||
$rule[PR_RULE_ACTIONS] = [
|
||||
[
|
||||
'action' => OP_DELEGATE,
|
||||
// don't set this value it will have no effect, its hardcoded to FWD_PRESERVE_SENDER | FWD_DO_NOT_MUNGE_MSG
|
||||
'flavor' => 0,
|
||||
'flags' => 0,
|
||||
'adrlist' => $usersInfo,
|
||||
],
|
||||
];
|
||||
|
||||
$rule[PR_RULE_CONDITION] = [RES_AND,
|
||||
[
|
||||
[RES_CONTENT,
|
||||
[
|
||||
FUZZYLEVEL => FL_PREFIX,
|
||||
ULPROPTAG => PR_MESSAGE_CLASS,
|
||||
VALUE => [PR_MESSAGE_CLASS => 'IPM.Schedule.Meeting'],
|
||||
],
|
||||
],
|
||||
[RES_NOT,
|
||||
[
|
||||
[RES_EXIST,
|
||||
[
|
||||
ULPROPTAG => PR_DELEGATED_BY_RULE,
|
||||
],
|
||||
],
|
||||
],
|
||||
],
|
||||
[RES_OR,
|
||||
[
|
||||
[RES_NOT,
|
||||
[
|
||||
[RES_EXIST,
|
||||
[
|
||||
ULPROPTAG => PR_SENSITIVITY,
|
||||
],
|
||||
],
|
||||
],
|
||||
],
|
||||
[RES_PROPERTY,
|
||||
[
|
||||
RELOP => RELOP_NE,
|
||||
ULPROPTAG => PR_SENSITIVITY,
|
||||
VALUE => [PR_SENSITIVITY => SENSITIVITY_PRIVATE],
|
||||
],
|
||||
],
|
||||
],
|
||||
],
|
||||
],
|
||||
];
|
||||
|
||||
$rule[PR_RULE_NAME] = '';
|
||||
$rule[PR_RULE_PROVIDER_DATA] = ''; // 0 byte binary string
|
||||
$rule[PR_RULE_STATE] = ST_ENABLED;
|
||||
$rule[PR_RULE_LEVEL] = 0;
|
||||
$rule[PR_RULE_SEQUENCE] = 0;
|
||||
$rule[PR_RULE_PROVIDER] = 'Schedule+ EMS Interface';
|
||||
$rule[PR_RULE_USER_FLAGS] = 0;
|
||||
|
||||
$rows = [
|
||||
0 => [
|
||||
'rowflags' => ROW_ADD,
|
||||
'properties' => $rule,
|
||||
],
|
||||
];
|
||||
$inbox = mapi_msgstore_getreceivefolder($this->getDefaultStore());
|
||||
mapi_folder_modifyrules($inbox, $rows);
|
||||
}
|
||||
|
||||
public function modifyDelegateMeetingRule($delegateMeetingRule, $users) {
|
||||
$inbox = mapi_msgstore_getreceivefolder($this->getDefaultStore());
|
||||
if (count($users) > 0) {
|
||||
// update the adrlist in the rule
|
||||
$delegateMeetingRule[PR_RULE_ACTIONS][0]['adrlist'] = $users;
|
||||
|
||||
$rows = [
|
||||
[
|
||||
'rowflags' => ROW_MODIFY,
|
||||
'properties' => $delegateMeetingRule,
|
||||
],
|
||||
];
|
||||
}
|
||||
else {
|
||||
// no users remaining in the rule so delete the rule
|
||||
$rows = [
|
||||
0 => [
|
||||
'rowflags' => ROW_REMOVE,
|
||||
'properties' => $delegateMeetingRule,
|
||||
],
|
||||
];
|
||||
}
|
||||
mapi_folder_modifyrules($inbox, $rows);
|
||||
}
|
||||
|
||||
/* Functions to delete delegates information */
|
||||
|
||||
/**
|
||||
* Function which deletes delegates information sent by client.
|
||||
*
|
||||
* @param array $delegates delegates information sent by client
|
||||
*/
|
||||
public function deleteDelegates($delegates) {
|
||||
if (is_assoc_array($delegates)) {
|
||||
// wrap single delegate in an array
|
||||
$delegates = [$delegates];
|
||||
}
|
||||
foreach ($delegates as $delegate) {
|
||||
// set properties for delegates on user's freebusy folder
|
||||
$this->deleteDelegateProps($delegate);
|
||||
|
||||
// set permissions on user's default folders
|
||||
$this->deleteFolderPermissions($delegate);
|
||||
}
|
||||
// delete delegate meeting rule
|
||||
$this->removeDelegatesFromDelegateMeetingRule($delegates);
|
||||
$this->sendFeedback(true);
|
||||
}
|
||||
|
||||
/**
|
||||
* Function will delete values from PR_DELEGATE_FLAGS, PR_SCHDINFO_DELEGATE_ENTRYIDS and PR_SCHDINFO_DELEGATE_NAMES and save the properties back if its not empty.
|
||||
*
|
||||
* @param array $delegate delegate information sent from client
|
||||
*/
|
||||
public function deleteDelegateProps($delegate) {
|
||||
$localFreeBusyMessage = FreeBusy::getLocalFreeBusyMessage($this->getDefaultStore());
|
||||
$delegateProps = $this->getDelegateProps($localFreeBusyMessage);
|
||||
$delegateIndex = -1;
|
||||
$len = count($delegateProps[PR_SCHDINFO_DELEGATE_ENTRYIDS]);
|
||||
for ($i = 0; $i < $len; ++$i) {
|
||||
if ($delegateProps[PR_SCHDINFO_DELEGATE_ENTRYIDS][$i] == hex2bin((string) $delegate["entryid"])) {
|
||||
$delegateIndex = $i;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if ($delegateIndex == -1) {
|
||||
return;
|
||||
}
|
||||
unset($delegateProps[PR_DELEGATE_FLAGS][$delegateIndex], $delegateProps[PR_SCHDINFO_DELEGATE_ENTRYIDS][$delegateIndex], $delegateProps[PR_SCHDINFO_DELEGATE_NAMES][$delegateIndex]);
|
||||
|
||||
// unset will remove the value but will not regenerate array keys, so we need to
|
||||
// do it here
|
||||
$delegateProps[PR_DELEGATE_FLAGS] = array_values($delegateProps[PR_DELEGATE_FLAGS]);
|
||||
$delegateProps[PR_SCHDINFO_DELEGATE_ENTRYIDS] = array_values($delegateProps[PR_SCHDINFO_DELEGATE_ENTRYIDS]);
|
||||
$delegateProps[PR_SCHDINFO_DELEGATE_NAMES] = array_values($delegateProps[PR_SCHDINFO_DELEGATE_NAMES]);
|
||||
|
||||
if (!empty($delegateProps[PR_SCHDINFO_DELEGATE_ENTRYIDS])) {
|
||||
mapi_setprops($localFreeBusyMessage, $delegateProps);
|
||||
}
|
||||
else {
|
||||
// Delete delegate properties.
|
||||
mapi_deleteprops($localFreeBusyMessage, [PR_DELEGATE_FLAGS, PR_SCHDINFO_DELEGATE_ENTRYIDS, PR_SCHDINFO_DELEGATE_NAMES]);
|
||||
}
|
||||
|
||||
mapi_savechanges($localFreeBusyMessage);
|
||||
|
||||
// unset the module variable, so subsequent calls will have the updated value
|
||||
unset($this->delegateProps);
|
||||
}
|
||||
|
||||
/**
|
||||
* Function which deletes permissions from all default folder for a particular delegate.
|
||||
*
|
||||
* @param array $delegate delegate's information sent by client
|
||||
*/
|
||||
public function deleteFolderPermissions($delegate) {
|
||||
$store = $this->getDefaultStore();
|
||||
|
||||
// Get all default folders and set permissions.
|
||||
foreach ($this->getDefaultFolders($store) as $folderName => $folderEntryID) {
|
||||
$folder = mapi_msgstore_openentry($store, $folderEntryID);
|
||||
|
||||
// delete current acl's
|
||||
$acls = [
|
||||
[
|
||||
'type' => ACCESS_TYPE_GRANT,
|
||||
'userid' => hex2bin((string) $delegate['entryid']),
|
||||
'rights' => ecRightsNone,
|
||||
'state' => RIGHT_DELETED | RIGHT_AUTOUPDATE_DENIED,
|
||||
'memberid' => 0,
|
||||
],
|
||||
];
|
||||
|
||||
mapi_zarafa_setpermissionrules($folder, $acls);
|
||||
|
||||
if ($folderName === 'calendar') {
|
||||
$freeBusyFolder = FreeBusy::getLocalFreeBusyFolder($store);
|
||||
|
||||
if ($freeBusyFolder !== false) {
|
||||
mapi_zarafa_setpermissionrules($freeBusyFolder, $acls);
|
||||
mapi_savechanges($freeBusyFolder);
|
||||
}
|
||||
}
|
||||
|
||||
mapi_savechanges($folder);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Function will remove delegates from delegate meeting rule when the user is deleted from delegate list.
|
||||
*
|
||||
* @param array $delegates all delegate information that are deleted
|
||||
*/
|
||||
public function removeDelegatesFromDelegateMeetingRule($delegates) {
|
||||
$delegateMeetingRule = $this->getDelegateMeetingRule();
|
||||
if ($delegateMeetingRule === false) {
|
||||
return;
|
||||
}
|
||||
$users = $this->getDelegateMeetingRuleUsers($delegateMeetingRule);
|
||||
$changed = false;
|
||||
foreach ($delegates as $delegate) {
|
||||
$index = $this->findDelegateMeetingRuleUser($users, hex2bin((string) $delegate['entryid']));
|
||||
if ($index !== false) {
|
||||
array_splice($users, $index, 1);
|
||||
$changed = true;
|
||||
}
|
||||
}
|
||||
if ($changed) {
|
||||
$this->modifyDelegateMeetingRule($delegateMeetingRule, $users);
|
||||
}
|
||||
}
|
||||
|
||||
/* Functions for exception handling */
|
||||
|
||||
/**
|
||||
* Function does customization of MAPIException based on module data.
|
||||
* like, here it will generate display message based on actionType
|
||||
* for particular exception.
|
||||
*
|
||||
* @param object $e Exception object
|
||||
* @param string $actionType the action type, sent by the client
|
||||
* @param resource $store current user's MAPI store
|
||||
* @param string $parententryid parent entryid of the message
|
||||
* @param string $entryid entryid of the message/folder
|
||||
* @param array $action the action data, sent by the client
|
||||
*/
|
||||
#[Override]
|
||||
public function handleException(&$e, $actionType = null, $store = null, $parententryid = null, $entryid = null, $action = null) {
|
||||
switch ($actionType) {
|
||||
case 'save':
|
||||
$e->setDisplayMessage(_('Could not save delegate information.'));
|
||||
break;
|
||||
|
||||
case 'delete':
|
||||
$e->setDisplayMessage(_('Could not delete delegate.'));
|
||||
break;
|
||||
|
||||
case 'list':
|
||||
$e->setDisplayMessage(_('Can not get list of delegates.'));
|
||||
break;
|
||||
}
|
||||
|
||||
parent::handleException($e, $actionType, $store, $parententryid, $entryid, $action);
|
||||
}
|
||||
}
|
||||
+122
@@ -0,0 +1,122 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* SPDX-FileCopyrightText: Copyright 2020 - 2026 grommunio GmbH
|
||||
* SPDX-FileCopyrightText: Copyright 2016 Kopano and its licensors
|
||||
* SPDX-FileCopyrightText: Copyright 2005 - 2016 Zarafa B.V. and its licensors
|
||||
* SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
*/
|
||||
|
||||
/**
|
||||
* ExpandDistlist Module.
|
||||
*/
|
||||
class ExpandDistlistModule extends Module {
|
||||
private $addrbook;
|
||||
|
||||
/**
|
||||
* Constructor.
|
||||
*
|
||||
* @param mixed $id
|
||||
* @param mixed $data
|
||||
*/
|
||||
public function __construct($id, $data) {
|
||||
parent::__construct($id, $data);
|
||||
|
||||
$this->properties = $GLOBALS["properties"]->getRecipientProperties();
|
||||
}
|
||||
|
||||
/**
|
||||
* Executes all the actions in the $data variable.
|
||||
*/
|
||||
#[Override]
|
||||
public function execute() {
|
||||
foreach ($this->data as $actionType => $action) {
|
||||
if (isset($actionType)) {
|
||||
try {
|
||||
switch ($actionType) {
|
||||
case 'expand':
|
||||
$this->expand($action);
|
||||
break;
|
||||
|
||||
default:
|
||||
$this->handleUnknownActionType($actionType);
|
||||
}
|
||||
}
|
||||
catch (MAPIException $e) {
|
||||
$this->processException($e, $actionType);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Function which expands a distribution list, optionally expands a distribution list in a distribution list.
|
||||
* Duplicate members will not be filtered.
|
||||
*
|
||||
* @param string $entryid entryid of distribution list
|
||||
* @param array $data an array of members in the distribution list
|
||||
* @param bool $isRecurse true if we want to expand a distribution list in distribution lists
|
||||
*
|
||||
* @return array $data an array of members in the distribution list
|
||||
*/
|
||||
public function expandDist($entryid, $data = [], $isRecurse = false) {
|
||||
$heid = bin2hex($entryid);
|
||||
if ($GLOBALS['entryid']->hasAddressBookGUID($heid) || $GLOBALS['entryid']->hasAddressBookRecipientGUID($heid)) {
|
||||
$abentry = mapi_ab_openentry($this->addrbook, $entryid);
|
||||
$table = mapi_folder_getcontentstable($abentry, MAPI_DEFERRED_ERRORS);
|
||||
$rows = mapi_table_queryrows($table, $this->properties, 0, (ABITEMDETAILS_MAX_NUM_DISTLIST_MEMBERS > 0) ? ABITEMDETAILS_MAX_NUM_DISTLIST_MEMBERS : 0x7FFFFFFF);
|
||||
/*
|
||||
* To prevent loading a huge list that the browser cannot handle, it is possible to
|
||||
* limit the maximum number of shown items. Note that when the table doesn't
|
||||
* contain the requested number of rows, it will not give any errors and simply
|
||||
* return what is available.
|
||||
* When the limit is 0 or below, then no limit is applied and we use 0x7fffffff
|
||||
* to indicate we want to have all rows from the table.
|
||||
*/
|
||||
for ($i = 0, $len = count($rows); $i < $len; ++$i) {
|
||||
$memberProps = Conversion::mapMAPI2XML($this->properties, $rows[$i]);
|
||||
$isDistlist = $memberProps['props']['object_type'] == MAPI_DISTLIST;
|
||||
if ($isDistlist && $isRecurse === true) {
|
||||
$data = array_merge($data, $this->expandDist(hex2bin((string) $memberProps['entryid']), [], $isRecurse));
|
||||
}
|
||||
else {
|
||||
$data[] = $memberProps;
|
||||
}
|
||||
}
|
||||
}
|
||||
else {
|
||||
/**
|
||||
* If distribution list was belongs to local/shared folder then
|
||||
* it will expand all members of distribution list.
|
||||
*/
|
||||
$distlistMembers = $GLOBALS['operations']->expandDistList($heid, $isRecurse);
|
||||
$recipients = [];
|
||||
foreach ($distlistMembers as $distlistMember) {
|
||||
$recipients['props'] = $distlistMember;
|
||||
array_push($data, $recipients);
|
||||
}
|
||||
}
|
||||
|
||||
return $data;
|
||||
}
|
||||
|
||||
/**
|
||||
* Function which expand the distribution list, sent by the client. This function is used
|
||||
* when a user wants to replace the distribution list with its members
|
||||
* in the to, cc and bcc field. This function retrieve members of that particular distribution list
|
||||
* and send that list back to the client.
|
||||
*
|
||||
* @param array $action the action data, sent by the client
|
||||
*/
|
||||
public function expand($action) {
|
||||
// Get the distribution list entryid from request
|
||||
$entryid = hex2bin((string) $action["entryid"]);
|
||||
$this->addrbook = $GLOBALS["mapisession"]->getAddressbook();
|
||||
|
||||
if ($entryid) {
|
||||
$data = ["results" => $this->expandDist($entryid, [], $action['recurse'])];
|
||||
$this->addActionData("expand", $data);
|
||||
$GLOBALS["bus"]->addData($this->getResponseData());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,108 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* SPDX-FileCopyrightText: Copyright 2020 - 2026 grommunio GmbH
|
||||
* SPDX-FileCopyrightText: Copyright 2016 Kopano and its licensors
|
||||
* SPDX-FileCopyrightText: Copyright 2005 - 2016 Zarafa B.V. and its licensors
|
||||
* SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
*/
|
||||
|
||||
/**
|
||||
* FreeBusyModule Module.
|
||||
*/
|
||||
class FreeBusyModule extends Module {
|
||||
#[Override]
|
||||
protected function getExecutionLockName() {
|
||||
return null;
|
||||
}
|
||||
|
||||
public function __construct($id, $data) {
|
||||
parent::__construct($id, $data);
|
||||
}
|
||||
|
||||
#[Override]
|
||||
public function execute() {
|
||||
foreach ($this->data as $actionType => $selUser) {
|
||||
if (isset($actionType)) {
|
||||
try {
|
||||
switch ($actionType) {
|
||||
case 'list':
|
||||
$this->addUserData($selUser);
|
||||
break;
|
||||
|
||||
default:
|
||||
$this->handleUnknownActionType($actionType);
|
||||
}
|
||||
}
|
||||
catch (MAPIException $e) {
|
||||
$this->processException($e, $actionType);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* This function will get user info from address book and add freebusy data of the user to
|
||||
* response.
|
||||
*
|
||||
* @param array $selUser User that should be resolved
|
||||
*/
|
||||
public function addUserData($selUser) {
|
||||
$data = [
|
||||
'users' => [],
|
||||
];
|
||||
|
||||
foreach ($selUser['users'] as $fbUser) {
|
||||
// Copy the identifier of the user.
|
||||
$user = [
|
||||
'userid' => $fbUser['userid'],
|
||||
'entryid' => $fbUser['entryid'],
|
||||
];
|
||||
|
||||
// Obtain the Freebusy data for this user
|
||||
$busyArray = $this->getFreeBusyInfo($fbUser['entryid'], $selUser['start'], $selUser['end']);
|
||||
$user['items'] = $busyArray;
|
||||
$data['users'][] = $user;
|
||||
}
|
||||
|
||||
$this->addActionData('list', $data);
|
||||
$GLOBALS['bus']->addData($this->getResponseData());
|
||||
}
|
||||
|
||||
/**
|
||||
* This function will get freebusy data for user based on the timeframe passed in arguments.
|
||||
*
|
||||
* @param string $entryID Entryid of the user for which we need to get freebusy data
|
||||
* @param int $start start offset for freebusy publish range
|
||||
* @param int $end end offset for freebusy publish range
|
||||
*
|
||||
* @return array freebusy blocks for passed publish range
|
||||
*/
|
||||
public function getFreeBusyInfo($entryID, $start, $end) {
|
||||
$result = [];
|
||||
|
||||
try {
|
||||
$fbdata = mapi_getuserfreebusy($GLOBALS['mapisession']->getSession(), hex2bin($entryID), $start, $end);
|
||||
|
||||
foreach ($fbdata['fbevents'] as $event) {
|
||||
$result[] = [
|
||||
'start' => $event['start'],
|
||||
'end' => $event['end'],
|
||||
'status' => $event['busystatus'],
|
||||
];
|
||||
}
|
||||
}
|
||||
catch (Exception $e) {
|
||||
error_log(sprintf("getFreeBusyInfo exception: %s (0x%08X)", $e->getMessage(), $e->getCode()));
|
||||
// -1 is the client's status for an absent answer. fbNoData cannot
|
||||
// say it here, because it shares its value with fbWorkingElsewhere.
|
||||
$result[] = [
|
||||
'start' => $start,
|
||||
'end' => $end,
|
||||
'status' => -1,
|
||||
];
|
||||
}
|
||||
|
||||
return $result;
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,387 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* SPDX-FileCopyrightText: Copyright 2020 - 2026 grommunio GmbH
|
||||
* SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
*/
|
||||
|
||||
require_once BASE_PATH . 'server/includes/core/class.junkrule.php';
|
||||
require_once BASE_PATH . 'server/includes/core/class.junksenderlist.php';
|
||||
|
||||
/**
|
||||
* JunkMailModule Module.
|
||||
*
|
||||
* This class reads and writes the Outlook Junk Email Rule (MS-OXCSPAM). The
|
||||
* IPM.ExtendedRule.Message FAI message in the inbox whose extended rule
|
||||
* condition carries the blocked senders, safe senders and safe recipients
|
||||
* lists. Outlook reads and writes the same message, so both clients see
|
||||
* one set of lists.
|
||||
*/
|
||||
class JunkMailModule extends Module {
|
||||
public const MAX_ENTRIES = 1024;
|
||||
public const MAX_ENTRY_LENGTH = JunkSenderList::MAX_ENTRY_LENGTH;
|
||||
|
||||
/**
|
||||
* Per-request cache of parsed lists.
|
||||
*/
|
||||
private static $cachedLists;
|
||||
|
||||
/**
|
||||
* Executes all the actions in the $data variable.
|
||||
*/
|
||||
#[Override]
|
||||
public function execute() {
|
||||
foreach ($this->data as $actionType => $action) {
|
||||
if (isset($actionType)) {
|
||||
try {
|
||||
switch ($actionType) {
|
||||
case "list":
|
||||
$this->getJunkSettings();
|
||||
break;
|
||||
|
||||
case "save":
|
||||
$this->saveJunkSettings($action);
|
||||
break;
|
||||
|
||||
default:
|
||||
$this->handleUnknownActionType($actionType);
|
||||
}
|
||||
}
|
||||
catch (MAPIException $e) {
|
||||
$this->processException($e, $actionType);
|
||||
}
|
||||
catch (GrommunioException $e) {
|
||||
$this->sendFeedback(false, [
|
||||
"type" => ERROR_GROMMUNIO,
|
||||
"info" => ["display_message" => $e->getDisplayMessage()],
|
||||
]);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Find the Junk Email Rule FAI message in the inbox associated contents.
|
||||
*
|
||||
* @param resource $store MAPI message store
|
||||
*
|
||||
* @return array [message|false, inbox]
|
||||
*/
|
||||
public static function findJunkRule($store) {
|
||||
$inbox = mapi_msgstore_getreceivefolder($store);
|
||||
$table = mapi_folder_getcontentstable($inbox, MAPI_ASSOCIATED);
|
||||
|
||||
mapi_table_restrict($table, [RES_AND, [
|
||||
[RES_CONTENT,
|
||||
[
|
||||
FUZZYLEVEL => FL_FULLSTRING | FL_IGNORECASE,
|
||||
ULPROPTAG => PR_MESSAGE_CLASS,
|
||||
VALUE => [PR_MESSAGE_CLASS => 'IPM.ExtendedRule.Message'],
|
||||
],
|
||||
],
|
||||
[RES_CONTENT,
|
||||
[
|
||||
FUZZYLEVEL => FL_FULLSTRING | FL_IGNORECASE,
|
||||
ULPROPTAG => PR_RULE_MSG_PROVIDER,
|
||||
VALUE => [PR_RULE_MSG_PROVIDER => JunkRule::PROVIDER],
|
||||
],
|
||||
],
|
||||
]]);
|
||||
|
||||
// Newest first, so a duplicate created by a racing client is shadowed
|
||||
// deterministically rather than by table order.
|
||||
mapi_table_sort($table, [PR_LAST_MODIFICATION_TIME => TABLE_SORT_DESCEND], TBL_BATCH);
|
||||
$rows = mapi_table_queryallrows($table, [PR_ENTRYID]);
|
||||
|
||||
if (!empty($rows)) {
|
||||
return [mapi_msgstore_openentry($store, $rows[0][PR_ENTRYID]), $inbox];
|
||||
}
|
||||
|
||||
return [false, $inbox];
|
||||
}
|
||||
|
||||
/**
|
||||
* Read the lists and options. Never creates the rule, because a mailbox without
|
||||
* one simply has empty lists, like a fresh Outlook profile.
|
||||
*/
|
||||
public function getJunkSettings() {
|
||||
$store = $GLOBALS['mapisession']->getDefaultMessageStore();
|
||||
$lists = self::getSenderLists($store);
|
||||
|
||||
$data = [
|
||||
'props' => [
|
||||
'safe_senders' => $lists['safe_senders'],
|
||||
'safe_recipients' => $lists['safe_recipients'],
|
||||
'blocked_senders' => $lists['blocked_senders'],
|
||||
'junk_include_contacts' => $lists['junk_include_contacts'],
|
||||
'migrated_pending' => $lists['migrated_pending'],
|
||||
],
|
||||
];
|
||||
|
||||
$this->addActionData('list', ['item' => [$data]]);
|
||||
$GLOBALS['bus']->addData($this->getResponseData());
|
||||
}
|
||||
|
||||
/**
|
||||
* The parsed lists, cached per request. Entries of the old webapp
|
||||
* safe_senders_list setting are merged into safe_senders (marked by
|
||||
* 'migrated_pending') until a verified save retires the setting.
|
||||
*
|
||||
* @param resource $store MAPI message store
|
||||
*
|
||||
* @return array lists plus options
|
||||
*/
|
||||
public static function getSenderLists($store) {
|
||||
if (isset(self::$cachedLists)) {
|
||||
return self::$cachedLists;
|
||||
}
|
||||
|
||||
$lists = [
|
||||
'safe_senders' => [],
|
||||
'safe_recipients' => [],
|
||||
'blocked_senders' => [],
|
||||
'contacts' => [],
|
||||
'junk_include_contacts' => 0,
|
||||
'migrated_pending' => false,
|
||||
];
|
||||
|
||||
try {
|
||||
[$message] = self::findJunkRule($store);
|
||||
}
|
||||
catch (MAPIException $e) {
|
||||
$e->setHandled();
|
||||
$message = false;
|
||||
}
|
||||
|
||||
if ($message !== false) {
|
||||
$props = mapi_getprops($message, [PR_EXTENDED_RULE_MSG_CONDITION, PR_JUNK_INCLUDE_CONTACTS]);
|
||||
$blob = $props[PR_EXTENDED_RULE_MSG_CONDITION] ?? readMapiPropStream($message, PR_EXTENDED_RULE_MSG_CONDITION);
|
||||
$parsed = is_string($blob) ? JunkRule::parseCondition($blob) : false;
|
||||
if ($parsed !== false) {
|
||||
$lists['safe_senders'] = $parsed['safe_senders'];
|
||||
$lists['safe_recipients'] = $parsed['safe_recipients'];
|
||||
$lists['blocked_senders'] = $parsed['blocked_senders'];
|
||||
$lists['contacts'] = $parsed['contacts'];
|
||||
}
|
||||
$lists['junk_include_contacts'] = ($props[PR_JUNK_INCLUDE_CONTACTS] ?? 0) ? 1 : 0;
|
||||
}
|
||||
|
||||
JunkSenderList::mergeLegacy($GLOBALS['settings']->get('grommunio/v1/contexts/mail/safe_senders_list'), $lists);
|
||||
|
||||
self::$cachedLists = $lists;
|
||||
|
||||
return $lists;
|
||||
}
|
||||
|
||||
/**
|
||||
* Save the lists. Rebuilds the whole condition and actions, verifies the
|
||||
* write by reading it back, and only then retires the old webapp setting.
|
||||
*
|
||||
* @param array $action the action data sent by the client
|
||||
*/
|
||||
public function saveJunkSettings($action) {
|
||||
$props = $action['props'] ?? [];
|
||||
$safeSenders = $this->sanitizeList($props['safe_senders'] ?? null);
|
||||
$safeRecipients = $this->sanitizeList($props['safe_recipients'] ?? null);
|
||||
$blockedSenders = $this->sanitizeList($props['blocked_senders'] ?? null);
|
||||
if ($safeSenders === false || $safeRecipients === false || $blockedSenders === false) {
|
||||
throw new GrommunioException(_("The sender lists could not be saved"));
|
||||
}
|
||||
|
||||
$store = $GLOBALS['mapisession']->getDefaultMessageStore();
|
||||
[$message, $inbox] = self::findJunkRule($store);
|
||||
|
||||
// The lists the client did not send keep their stored value.
|
||||
$current = self::getSenderLists($store);
|
||||
$explicitSafeSenders = $safeSenders !== null;
|
||||
$safeSenders ??= $current['safe_senders'];
|
||||
$safeRecipients ??= $current['safe_recipients'];
|
||||
$blockedSenders ??= $current['blocked_senders'];
|
||||
|
||||
// MS-OXCSPAM v12 §2.2.2.2: The contacts clause must be empty while the
|
||||
// option is off. Outlook repopulates it when re-enabled.
|
||||
$includeContacts = isset($props['junk_include_contacts']) ?
|
||||
(empty($props['junk_include_contacts']) ? 0 : 1) :
|
||||
$current['junk_include_contacts'];
|
||||
|
||||
$condition = JunkRule::buildCondition(
|
||||
$blockedSenders,
|
||||
$safeSenders,
|
||||
$safeRecipients,
|
||||
$includeContacts ? $current['contacts'] : []
|
||||
);
|
||||
$renState = State::forStore('additional-ren-entryids-write');
|
||||
if (!$renState->open()) {
|
||||
throw new RuntimeException('Unable to lock additional folder entryids');
|
||||
}
|
||||
|
||||
try {
|
||||
$actions = JunkRule::buildActions(
|
||||
$this->getJunkFolderEntryId($inbox),
|
||||
$this->getMoveStamp($inbox)
|
||||
);
|
||||
}
|
||||
finally {
|
||||
$renState->close();
|
||||
}
|
||||
|
||||
$writeProps = [
|
||||
PR_EXTENDED_RULE_MSG_CONDITION => $condition,
|
||||
PR_EXTENDED_RULE_MSG_ACTIONS => $actions,
|
||||
// Re-enable on every save. Outlook may have flagged ST_ERROR.
|
||||
PR_RULE_MSG_STATE => JunkRule::RULE_STATE,
|
||||
];
|
||||
if (isset($props['junk_include_contacts'])) {
|
||||
$writeProps[PR_JUNK_INCLUDE_CONTACTS] = $includeContacts;
|
||||
}
|
||||
|
||||
$created = $message === false;
|
||||
if ($created) {
|
||||
$message = mapi_folder_createmessage($inbox, MAPI_ASSOCIATED);
|
||||
$writeProps += [
|
||||
PR_MESSAGE_CLASS => 'IPM.ExtendedRule.Message',
|
||||
PR_RULE_MSG_NAME => JunkRule::RULE_NAME,
|
||||
PR_SUBJECT => JunkRule::RULE_NAME,
|
||||
PR_RULE_MSG_PROVIDER => JunkRule::PROVIDER,
|
||||
PR_RULE_MSG_SEQUENCE => 0,
|
||||
PR_RULE_MSG_LEVEL => 0,
|
||||
PR_RULE_MSG_USER_FLAGS => 0,
|
||||
PR_JUNK_INCLUDE_CONTACTS => $writeProps[PR_JUNK_INCLUDE_CONTACTS] ?? 0,
|
||||
PR_JUNK_THRESHOLD => -1,
|
||||
PR_JUNK_PERMANENTLY_DELETE => 0,
|
||||
PR_JUNK_ADD_RECIPS_TO_SSL => 0,
|
||||
PR_JUNK_PHISHING_ENABLE_LINKS => false,
|
||||
PR_REPORT_TIME => time(),
|
||||
];
|
||||
}
|
||||
|
||||
mapi_setprops($message, $writeProps);
|
||||
mapi_savechanges($message);
|
||||
|
||||
// zcore silently rejects an oversized or non-FAI condition write.
|
||||
// mapi_setprops still succeeds, so the only proof is reading back.
|
||||
$check = mapi_getprops($message, [PR_EXTENDED_RULE_MSG_CONDITION]);
|
||||
$stored = $check[PR_EXTENDED_RULE_MSG_CONDITION] ?? readMapiPropStream($message, PR_EXTENDED_RULE_MSG_CONDITION);
|
||||
if ($stored !== $condition) {
|
||||
if ($created) {
|
||||
// Do not leave an enabled rule without a condition behind.
|
||||
try {
|
||||
$eid = mapi_getprops($message, [PR_ENTRYID]);
|
||||
mapi_folder_deletemessages($inbox, [$eid[PR_ENTRYID]], DELETE_HARD_DELETE);
|
||||
}
|
||||
catch (MAPIException $e) {
|
||||
$e->setHandled();
|
||||
}
|
||||
}
|
||||
|
||||
throw new GrommunioException(_("The sender lists could not be saved"));
|
||||
}
|
||||
|
||||
$this->retireOldSetting($safeSenders, $explicitSafeSenders);
|
||||
self::$cachedLists = null;
|
||||
|
||||
$this->sendFeedback(true);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param mixed $list the client-sent list
|
||||
*
|
||||
* @return null|array|false null when absent, false when invalid
|
||||
*/
|
||||
private function sanitizeList($list) {
|
||||
if ($list === null) {
|
||||
return null;
|
||||
}
|
||||
if (!is_array($list) || count($list) > self::MAX_ENTRIES) {
|
||||
return false;
|
||||
}
|
||||
$out = [];
|
||||
$seen = [];
|
||||
foreach ($list as $entry) {
|
||||
if (!is_string($entry)) {
|
||||
return false;
|
||||
}
|
||||
$entry = trim($entry);
|
||||
if ($entry === '') {
|
||||
continue;
|
||||
}
|
||||
if (!JunkSenderList::isSaneEntry($entry)) {
|
||||
return false;
|
||||
}
|
||||
$lower = strtolower($entry);
|
||||
if (!isset($seen[$lower])) {
|
||||
$seen[$lower] = true;
|
||||
$out[] = $entry;
|
||||
}
|
||||
}
|
||||
|
||||
return $out;
|
||||
}
|
||||
|
||||
/**
|
||||
* The junk folder entryid is PR_ADDITIONAL_REN_ENTRYIDS index 4 on the inbox.
|
||||
*
|
||||
* @param resource $inbox
|
||||
*
|
||||
* @return string 46-byte folder entryid
|
||||
*/
|
||||
private function getJunkFolderEntryId($inbox) {
|
||||
$props = mapi_getprops($inbox, [PR_ADDITIONAL_REN_ENTRYIDS]);
|
||||
$eid = $props[PR_ADDITIONAL_REN_ENTRYIDS][4] ?? '';
|
||||
if (strlen($eid) !== 46) {
|
||||
throw new GrommunioException(_("The sender lists could not be saved"));
|
||||
}
|
||||
|
||||
return $eid;
|
||||
}
|
||||
|
||||
/**
|
||||
* The junk email move stamp is PR_ADDITIONAL_REN_ENTRYIDS index 5 on the
|
||||
* inbox, generated and stored there when absent (MS-OXCSPAM v12 §3.2.4.1).
|
||||
*
|
||||
* @param resource $inbox
|
||||
*
|
||||
* @return int
|
||||
*/
|
||||
private function getMoveStamp($inbox) {
|
||||
$props = mapi_getprops($inbox, [PR_ADDITIONAL_REN_ENTRYIDS]);
|
||||
$entries = $props[PR_ADDITIONAL_REN_ENTRYIDS] ?? [];
|
||||
if (isset($entries[5]) && strlen((string) $entries[5]) === 4) {
|
||||
return unpack('V', $entries[5])[1];
|
||||
}
|
||||
|
||||
$stamp = random_int(1, 0x7FFFFFFF);
|
||||
for ($i = 0; $i <= 5; ++$i) {
|
||||
$entries[$i] ??= '';
|
||||
}
|
||||
$entries[5] = pack('V', $stamp);
|
||||
ksort($entries);
|
||||
mapi_setprops($inbox, [PR_ADDITIONAL_REN_ENTRYIDS => array_values($entries)]);
|
||||
mapi_savechanges($inbox);
|
||||
|
||||
return $stamp;
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete the old webapp setting after a verified save. An explicitly sent
|
||||
* safe senders list was built from the merged view (the client refuses to
|
||||
* save before loading), so deletions in it are deliberate. Otherwise, the
|
||||
* setting is kept until a save covers every remaining entry.
|
||||
*
|
||||
* @param array $safeSenders the just-saved safe senders
|
||||
* @param bool $explicit the client sent the list itself
|
||||
*/
|
||||
private function retireOldSetting($safeSenders, $explicit) {
|
||||
$old = $GLOBALS['settings']->get('grommunio/v1/contexts/mail/safe_senders_list');
|
||||
if (!is_array($old) || empty($old)) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (!$explicit && !JunkSenderList::legacyCoveredBy($old, $safeSenders)) {
|
||||
return;
|
||||
}
|
||||
|
||||
$GLOBALS['settings']->delete('grommunio/v1/contexts/mail/safe_senders_list');
|
||||
$GLOBALS['settings']->saveSettings();
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,474 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* SPDX-FileCopyrightText: Copyright 2020 - 2026 grommunio GmbH
|
||||
* SPDX-FileCopyrightText: Copyright 2016 Kopano and its licensors
|
||||
* SPDX-FileCopyrightText: Copyright 2005 - 2016 Zarafa B.V. and its licensors
|
||||
* SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
*/
|
||||
|
||||
require_once __DIR__ . '/../hexutil.php';
|
||||
|
||||
/**
|
||||
* Mail Module.
|
||||
*/
|
||||
class MailListModule extends ListModule {
|
||||
// Temporary var to store the inbox entryid of the processed store
|
||||
private $_inboxEntryId;
|
||||
|
||||
private $_inbox;
|
||||
|
||||
private $_inboxTotal;
|
||||
|
||||
private $_inboxTotalUnread;
|
||||
|
||||
private $store;
|
||||
|
||||
private $currentActionData;
|
||||
|
||||
// The server drops a contents table together with its folder handle.
|
||||
private $sentItemsFolder;
|
||||
|
||||
/**
|
||||
* Constructor.
|
||||
*
|
||||
* @param int $id unique id
|
||||
* @param array $data list of all actions
|
||||
*/
|
||||
public function __construct($id, $data) {
|
||||
parent::__construct($id, $data);
|
||||
$this->properties = $GLOBALS["properties"]->getMailListProperties();
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if the conversation view may be used. The message list itself is not
|
||||
* affected by this (the client groups the messages by their conversation id),
|
||||
* this only gates the conversationitems action that fetches the sent items
|
||||
* belonging to a conversation.
|
||||
*
|
||||
* @return bool true if the conversation view may be used, false otherwise
|
||||
*/
|
||||
public function useConversationView() {
|
||||
// ENABLE_CONVERSATION_VIEW acts as an administrative kill-switch.
|
||||
return
|
||||
(!defined('ENABLE_CONVERSATION_VIEW') || ENABLE_CONVERSATION_VIEW) &&
|
||||
$GLOBALS['settings']->get('grommunio/v1/contexts/mail/enable_conversation_view') === true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates the notifiers for this module,
|
||||
* and register them to the Bus.
|
||||
*/
|
||||
public function createNotifiers() {
|
||||
$entryid = $this->getEntryID();
|
||||
$GLOBALS["bus"]->registerNotifier('maillistnotifier', $entryid);
|
||||
}
|
||||
|
||||
/**
|
||||
* Executes all the actions in the $data variable.
|
||||
*/
|
||||
#[Override]
|
||||
public function execute() {
|
||||
$GLOBALS['PluginManager']->triggerHook("server.module.maillistmodule.execute.before", ['moduleObject' => &$this]);
|
||||
|
||||
foreach ($this->data as $actionType => $action) {
|
||||
if (isset($actionType)) {
|
||||
try {
|
||||
$this->store = $this->getActionStore($action);
|
||||
$entryid = $this->getActionSingleEntryID($action);
|
||||
if ($this->store === false || is_array($this->store)) {
|
||||
$this->sendFeedback(false);
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
// Reset variables
|
||||
$this->_inbox = null;
|
||||
$this->_inboxEntryId = null;
|
||||
$this->_inboxTotal = null;
|
||||
$this->_inboxTotalUnread = null;
|
||||
|
||||
$this->currentActionData = [
|
||||
'store' => $this->store,
|
||||
'entryid' => $entryid,
|
||||
'actionType' => $actionType,
|
||||
'action' => $action,
|
||||
];
|
||||
|
||||
switch ($actionType) {
|
||||
case "list":
|
||||
case "updatelist":
|
||||
$this->getDelegateFolderInfo($this->store);
|
||||
$this->messageList($this->store, $entryid, $action, $actionType);
|
||||
break;
|
||||
|
||||
case "search":
|
||||
// @FIXME add handling for private items
|
||||
$this->search($this->store, $entryid, $action, $actionType);
|
||||
break;
|
||||
|
||||
case "updatesearch":
|
||||
$this->updatesearch($this->store, $entryid, $action);
|
||||
break;
|
||||
|
||||
case "stopsearch":
|
||||
$this->stopSearch($this->store, $entryid, $action);
|
||||
break;
|
||||
|
||||
case "conversationitems":
|
||||
$this->getDelegateFolderInfo($this->store);
|
||||
$this->getConversationItems($this->store, $action);
|
||||
break;
|
||||
|
||||
case "conversationcounts":
|
||||
$this->getDelegateFolderInfo($this->store);
|
||||
$this->getConversationCounts($this->store, $action);
|
||||
break;
|
||||
|
||||
default:
|
||||
$this->handleUnknownActionType($actionType);
|
||||
}
|
||||
}
|
||||
catch (MAPIException|SearchException $e) {
|
||||
$this->processException($e, $actionType);
|
||||
}
|
||||
}
|
||||
}
|
||||
$GLOBALS['PluginManager']->triggerHook("server.module.maillistmodule.execute.after", ['moduleObject' => &$this]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the Inbox folder of the currently used store if found, NULL otherwise.
|
||||
*
|
||||
* @return resource The inbox folder of the currently used store
|
||||
*/
|
||||
public function getInbox() {
|
||||
if ($this->_inbox === null) {
|
||||
try {
|
||||
$this->_inbox = mapi_msgstore_getreceivefolder($this->store);
|
||||
}
|
||||
catch (MAPIException $e) {
|
||||
// don't propagate this error to parent handlers, if store doesn't support it
|
||||
if ($e->getCode() === MAPI_E_NO_SUPPORT) {
|
||||
$e->setHandled();
|
||||
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return $this->_inbox;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the entryid of the Inbox folder of the currently used store if found, false otherwise.
|
||||
*
|
||||
* @return false|string hexadecimal Inbox entry ID, or false when unavailable
|
||||
*/
|
||||
public function getInboxEntryId() {
|
||||
if ($this->_inboxEntryId === null) {
|
||||
$inbox = $this->getInbox();
|
||||
|
||||
try {
|
||||
$inboxProps = mapi_getprops($inbox, [PR_ENTRYID]);
|
||||
$this->_inboxEntryId = bin2hex((string) $inboxProps[PR_ENTRYID]);
|
||||
}
|
||||
catch (MAPIException $e) {
|
||||
// don't propagate this error to parent handlers, if store doesn't support it
|
||||
if ($e->getCode() === MAPI_E_NO_SUPPORT) {
|
||||
$e->setHandled();
|
||||
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return $this->_inboxEntryId;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the total number of items in the Inbox of the currently used store.
|
||||
*
|
||||
* @param mixed $force
|
||||
*
|
||||
* @return int the number if items in the Inbox folder
|
||||
*/
|
||||
public function getInboxTotal($force = false) {
|
||||
if ($this->_inboxTotal === null || $force) {
|
||||
$inbox = $this->getInbox();
|
||||
$contentcount = mapi_getprops($inbox, [PR_CONTENT_COUNT, PR_CONTENT_UNREAD]);
|
||||
$this->_inboxTotal = $contentcount[PR_CONTENT_COUNT];
|
||||
$this->_inboxTotalUnread = $contentcount[PR_CONTENT_UNREAD];
|
||||
}
|
||||
|
||||
return $this->_inboxTotal;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the number of unread items in the Inbox of the currently used store.
|
||||
*
|
||||
* @param mixed $force
|
||||
*
|
||||
* @return int the number of unread items in the Inbox folder
|
||||
*/
|
||||
public function getInboxTotalUnread($force = false) {
|
||||
if ($this->_inboxTotalUnread === null || $force) {
|
||||
$this->getInboxTotal($force);
|
||||
}
|
||||
|
||||
return $this->_inboxTotalUnread;
|
||||
}
|
||||
|
||||
/**
|
||||
* Opens the contents table of the Sent Items folder of the given store, or
|
||||
* returns false when it is not available. Public stores do not have that
|
||||
* folder. Shared mailboxes can withhold access, where the refusal surfaces
|
||||
* at the folder or at its table, depending on the rights granted. In any
|
||||
* case, these conditions must not turn into an error for the whole request.
|
||||
*
|
||||
* @param resource $store MAPI message store
|
||||
*
|
||||
* @return false|resource Sent Items contents table, or false when unavailable
|
||||
*/
|
||||
protected function openSentItemsTable($store) {
|
||||
$msgstoreProps = mapi_getprops($store, [PR_IPM_SENTMAIL_ENTRYID]);
|
||||
if (!isset($msgstoreProps[PR_IPM_SENTMAIL_ENTRYID])) {
|
||||
return false;
|
||||
}
|
||||
|
||||
try {
|
||||
$this->sentItemsFolder = mapi_msgstore_openentry($store, $msgstoreProps[PR_IPM_SENTMAIL_ENTRYID]);
|
||||
|
||||
return mapi_folder_getcontentstable($this->sentItemsFolder, MAPI_DEFERRED_ERRORS);
|
||||
}
|
||||
catch (MAPIException $e) {
|
||||
$e->setHandled();
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns, for the given list of conversation ids, how many messages of each
|
||||
* conversation are in the Sent Items folder. The client uses this to know
|
||||
* which messages must be presented as a conversation even though only one
|
||||
* of them is in the Inbox (a mail that was replied to).
|
||||
*
|
||||
* @param resource $store MAPI message store
|
||||
* @param array $action the action data, sent by the client
|
||||
*/
|
||||
public function getConversationCounts($store, $action) {
|
||||
$counts = [];
|
||||
$ids = $action['conversation_ids'] ?? [];
|
||||
|
||||
if ($this->useConversationView() && is_array($ids) && !empty($ids)) {
|
||||
$validIds = [];
|
||||
foreach ($ids as $id) {
|
||||
if (is_hex_string($id)) {
|
||||
$validIds[] = $id;
|
||||
// The client asks per loaded page; cap the restriction size.
|
||||
if (count($validIds) >= 500) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
$table = empty($validIds) ? false : $this->openSentItemsTable($store);
|
||||
if ($table !== false) {
|
||||
$subRestrictions = [];
|
||||
foreach ($validIds as $id) {
|
||||
$subRestrictions[] = [
|
||||
RES_PROPERTY,
|
||||
[
|
||||
RELOP => RELOP_EQ,
|
||||
ULPROPTAG => PR_CONVERSATION_ID,
|
||||
VALUE => [PR_CONVERSATION_ID => hex2bin($id)],
|
||||
],
|
||||
];
|
||||
}
|
||||
mapi_table_restrict($table, [RES_OR, $subRestrictions], TBL_BATCH);
|
||||
|
||||
$rows = mapi_table_queryallrows($table, [PR_CONVERSATION_ID, PR_SENSITIVITY]);
|
||||
foreach ($rows as $row) {
|
||||
if (!isset($row[PR_CONVERSATION_ID])) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// getConversationItems() removes private items from the
|
||||
// conversation, so they must not be counted here either.
|
||||
// The count is what the conversation header announces.
|
||||
$props = [];
|
||||
if (isset($row[PR_SENSITIVITY])) {
|
||||
$props['sensitivity'] = $row[PR_SENSITIVITY];
|
||||
}
|
||||
if ($this->checkPrivateItem(['props' => $props])) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$id = bin2hex((string) $row[PR_CONVERSATION_ID]);
|
||||
$counts[$id] = ($counts[$id] ?? 0) + 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
$this->addActionData('conversationcounts', [
|
||||
// Force an object so an empty result is {} instead of [].
|
||||
'counts' => empty($counts) ? new stdClass() : $counts,
|
||||
]);
|
||||
$GLOBALS['bus']->addData($this->getResponseData());
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the messages from the Sent Items folder that belong to the given
|
||||
* conversation, identified by its PR_CONVERSATION_ID. The inbox part of a
|
||||
* conversation is already available to the client through the normal message
|
||||
* list; this action supplies the sent counterparts when the user expands a
|
||||
* conversation.
|
||||
*
|
||||
* @param resource $store MAPI message store
|
||||
* @param array $action the action data, sent by the client
|
||||
*/
|
||||
public function getConversationItems($store, $action) {
|
||||
$data = ['item' => []];
|
||||
$conversationId = $action['conversation_id'] ?? '';
|
||||
$data['conversation_id'] = $conversationId;
|
||||
|
||||
if ($this->useConversationView() && is_hex_string($conversationId)) {
|
||||
$restriction = [
|
||||
RES_PROPERTY,
|
||||
[
|
||||
RELOP => RELOP_EQ,
|
||||
ULPROPTAG => PR_CONVERSATION_ID,
|
||||
VALUE => [PR_CONVERSATION_ID => hex2bin($conversationId)],
|
||||
],
|
||||
];
|
||||
|
||||
$tables = [];
|
||||
$sentTable = $this->openSentItemsTable($store);
|
||||
if ($sentTable !== false) {
|
||||
$tables['sent_items'] = $sentTable;
|
||||
}
|
||||
// The mail list already contains the inbox part of a conversation,
|
||||
// but callers without that context (e.g. the search results
|
||||
// preview) need the complete conversation.
|
||||
if (!empty($action['include_inbox'])) {
|
||||
try {
|
||||
$inbox = mapi_msgstore_getreceivefolder($store);
|
||||
$tables['inbox'] = mapi_folder_getcontentstable($inbox, MAPI_DEFERRED_ERRORS);
|
||||
}
|
||||
catch (MAPIException $e) {
|
||||
$e->setHandled();
|
||||
}
|
||||
}
|
||||
|
||||
foreach ($tables as $folderName => $table) {
|
||||
mapi_table_restrict($table, $restriction, TBL_BATCH);
|
||||
|
||||
$rows = mapi_table_queryallrows($table, $this->properties);
|
||||
foreach ($rows as $row) {
|
||||
$item = Conversion::mapMAPI2XML($this->properties, $row);
|
||||
$item['props']['folder_name'] = $folderName;
|
||||
$data['item'][] = $item;
|
||||
}
|
||||
}
|
||||
|
||||
// Newest first, like the conversation items in the mail list.
|
||||
usort($data['item'], function ($a, $b) {
|
||||
$dateA = $a['props']['message_delivery_time'] ?? $a['props']['client_submit_time'] ?? 0;
|
||||
$dateB = $b['props']['message_delivery_time'] ?? $b['props']['client_submit_time'] ?? 0;
|
||||
|
||||
return $dateB <=> $dateA;
|
||||
});
|
||||
|
||||
$data = $this->filterPrivateItems($data);
|
||||
$data['item'] = array_values($data['item']);
|
||||
}
|
||||
|
||||
$this->addActionData('conversationitems', $data);
|
||||
$GLOBALS['bus']->addData($this->getResponseData());
|
||||
}
|
||||
|
||||
/**
|
||||
* Function does customization of exception based on module data.
|
||||
* like, here it will generate display message based on actionType
|
||||
* for particular exception.
|
||||
*
|
||||
* @param object $e Exception object
|
||||
* @param string $actionType the action type, sent by the client
|
||||
* @param resource $store current user's MAPI store
|
||||
* @param string $parententryid parent entryid of the message
|
||||
* @param string $entryid entryid of the message
|
||||
* @param array $action the action data, sent by the client
|
||||
*/
|
||||
#[Override]
|
||||
public function handleException(&$e, $actionType = null, $store = null, $parententryid = null, $entryid = null, $action = null) {
|
||||
if (is_null($e->displayMessage)) {
|
||||
switch ($actionType) {
|
||||
case "list":
|
||||
if ($e->getCode() == MAPI_E_NO_ACCESS) {
|
||||
$e->setDisplayMessage(_("You have insufficient privileges to see the contents of this folder."));
|
||||
}
|
||||
else {
|
||||
$e->setDisplayMessage(_("Could not load the contents of this folder."));
|
||||
}
|
||||
break;
|
||||
|
||||
case "search":
|
||||
if ($e->getCode() == MAPI_E_NO_ACCESS) {
|
||||
$e->setDisplayMessage(_("You have insufficient privileges to perform search operation in this folder."));
|
||||
}
|
||||
else {
|
||||
$e->setDisplayMessage(_("Error in search, please try again."));
|
||||
}
|
||||
break;
|
||||
|
||||
case "updatesearch":
|
||||
$e->setDisplayMessage(_("Could not update search results."));
|
||||
break;
|
||||
|
||||
case "stopsearch":
|
||||
$e->setDisplayMessage(_("Could not stop search operation."));
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
parent::handleException($e, $actionType, $store, $parententryid, $entryid, $action);
|
||||
}
|
||||
|
||||
/**
|
||||
* Parses the incoming sort request and builds a MAPI sort order.
|
||||
* Overridden to rewrite the sorting for flags. (because the flags that are shown in grommunio Web
|
||||
* are a combination of several properties).
|
||||
*
|
||||
* @param array $action action data sent by the client
|
||||
* @param array|false $map optional property mapping
|
||||
* @param bool $allow_multi_instance whether to sort each multi-value instance as a separate row
|
||||
* @param array|false $properties custom properties, or false to use the module properties
|
||||
*/
|
||||
#[Override]
|
||||
public function parseSortOrder($action, $map = false, $allow_multi_instance = false, $properties = false) {
|
||||
if (isset($action['sort'])) {
|
||||
// Check if the user wants to sort the maillist on flags.
|
||||
// If so, we will rewrite the sorting a little
|
||||
if (is_array($action['sort']) && count($action['sort']) > 0 && $action['sort'][0]['field'] === 'flag_due_by') {
|
||||
$dir = $action['sort'][0]['direction'];
|
||||
$action['sort'] = [
|
||||
[
|
||||
'field' => 'flag_status',
|
||||
'direction' => $dir,
|
||||
],
|
||||
[
|
||||
'field' => 'duedate',
|
||||
'direction' => $dir === 'ASC' ? 'DESC' : 'ASC',
|
||||
],
|
||||
[
|
||||
'field' => 'flag_due_by',
|
||||
'direction' => $dir,
|
||||
],
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
parent::parseSortOrder($action, $map, $allow_multi_instance, $properties);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,641 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* SPDX-FileCopyrightText: Copyright 2020 - 2026 grommunio GmbH
|
||||
* SPDX-FileCopyrightText: Copyright 2016 Kopano and its licensors
|
||||
* SPDX-FileCopyrightText: Copyright 2005 - 2016 Zarafa B.V. and its licensors
|
||||
* SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
*/
|
||||
|
||||
require_once __DIR__ . '/../exceptions/class.SearchException.php';
|
||||
|
||||
/**
|
||||
* Module
|
||||
* Superclass of every module. Many default functions are defined in this class.
|
||||
*/
|
||||
class Module {
|
||||
/**
|
||||
* @var string entryid, which will be registered by the bus object
|
||||
*/
|
||||
public $entryid;
|
||||
|
||||
/**
|
||||
* @var array list of the results, which is send to the client
|
||||
*/
|
||||
public $responseData;
|
||||
|
||||
/**
|
||||
* @var array list of all the errors occurred
|
||||
*/
|
||||
public $errors;
|
||||
|
||||
/**
|
||||
* @var false|State The state object which refers to the statefile
|
||||
*/
|
||||
public $sessionState;
|
||||
|
||||
/**
|
||||
* @var mixed data stored in session for this module
|
||||
*/
|
||||
public $sessionData;
|
||||
|
||||
/**
|
||||
* @var array list of the properties necessary for the module
|
||||
*/
|
||||
public $properties;
|
||||
|
||||
/**
|
||||
* @var array list of the folder list properties
|
||||
*/
|
||||
public $list_properties;
|
||||
|
||||
/**
|
||||
* @var bool whether the session state is shared
|
||||
*/
|
||||
public $_sharedSessionState;
|
||||
|
||||
/**
|
||||
* @var false|State per-module execution lock
|
||||
*/
|
||||
private $sessionExecutionLock = false;
|
||||
|
||||
/**
|
||||
* @var null|string serialized module state loaded before execution
|
||||
*/
|
||||
private $sessionDataSnapshot;
|
||||
|
||||
/**
|
||||
* Constructor.
|
||||
*
|
||||
* @param int $id unique id
|
||||
* @param array $data list of all actions
|
||||
*/
|
||||
public function __construct(public $id, public $data) {
|
||||
$this->errors = [];
|
||||
$this->responseData = [];
|
||||
$this->sessionState = false;
|
||||
$this->sessionData = false;
|
||||
$this->_sharedSessionState = false;
|
||||
$this->sessionDataSnapshot = null;
|
||||
|
||||
$this->createNotifiers();
|
||||
|
||||
// Get the store from $data and set it to properties class.
|
||||
// It is requires for multi server environment where namespace differs.
|
||||
// e.g. 'categories' => -2062020578, 'categories' => -2062610402,
|
||||
if (isset($GLOBALS['properties'])) {
|
||||
$GLOBALS['properties']->setStore($this->getActionStore($this->getActionData($this->data)));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates the notifiers for this module,
|
||||
* and register them to the Bus.
|
||||
*/
|
||||
public function createNotifiers() {}
|
||||
|
||||
/**
|
||||
* Executes all the actions in the $data variable.
|
||||
*/
|
||||
public function execute() {
|
||||
// you must implement this function for each module
|
||||
}
|
||||
|
||||
/**
|
||||
* This will call $handleException of updating the MAPIException based in the module data.
|
||||
* When this is done, $sendFeedback will be called to send the message to the client.
|
||||
*
|
||||
* @param object $e exception object
|
||||
* @param null|string $actionType the action type, sent by the client
|
||||
* @param null|array|false|resource $store MAPI store or stores
|
||||
* @param null|false|string $parententryid parent entryid of the message
|
||||
* @param null|false|string $entryid entryid of the message/folder
|
||||
* @param null|array $action the action data, sent by the client
|
||||
*/
|
||||
public function processException(&$e, $actionType = null, $store = null, $parententryid = null, $entryid = null, $action = null) {
|
||||
$this->handleException($e, $actionType, $store, $parententryid, $entryid, $action);
|
||||
$this->sendFeedback(false, $this->errorDetailsFromException($e));
|
||||
}
|
||||
|
||||
/**
|
||||
* Function does customization of MAPIException based on module data.
|
||||
* like, here it will generate display message based on actionType
|
||||
* for particular exception.
|
||||
*
|
||||
* @param object $e exception object
|
||||
* @param string $actionType the action type, sent by the client
|
||||
* @param resource $store MAPI store containing the message
|
||||
* @param string $parententryid parent entryid of the message
|
||||
* @param string $entryid entryid of the message/folder
|
||||
* @param array $action the action data, sent by the client
|
||||
*/
|
||||
public function handleException(&$e, $actionType = null, $store = null, $parententryid = null, $entryid = null, $action = null) {
|
||||
if (is_null($e->displayMessage)) {
|
||||
switch ($actionType) {
|
||||
case "save":
|
||||
if ($e->getCode() == MAPI_E_NO_ACCESS) {
|
||||
$e->setDisplayMessage(_("You have insufficient privileges to save this message."));
|
||||
}
|
||||
else {
|
||||
$e->setDisplayMessage(_("Could not save message."));
|
||||
}
|
||||
$e->allowToShowDetailsMessage = true;
|
||||
break;
|
||||
|
||||
case "delete":
|
||||
if ($e->getCode() == MAPI_E_NO_ACCESS) {
|
||||
$e->setDisplayMessage(_("You have insufficient privileges to delete this message."));
|
||||
}
|
||||
else {
|
||||
$e->setDisplayMessage(_("Could not delete message."));
|
||||
}
|
||||
break;
|
||||
|
||||
case "cancelMeetingRequest":
|
||||
if ($e->getCode() == MAPI_E_NO_ACCESS) {
|
||||
$e->setDisplayMessage(_("You have insufficient privileges to cancel this Meeting Request."));
|
||||
}
|
||||
else {
|
||||
$e->setDisplayMessage(_("Could not cancel Meeting Request."));
|
||||
}
|
||||
break;
|
||||
|
||||
case "declineMeetingRequest":
|
||||
if ($e->getCode() == MAPI_E_NO_ACCESS) {
|
||||
$e->setDisplayMessage(_("You have insufficient privileges to decline this Meeting Request."));
|
||||
}
|
||||
else {
|
||||
$e->setDisplayMessage(_("Could not decline Meeting Request."));
|
||||
}
|
||||
break;
|
||||
|
||||
case "acceptMeetingRequest":
|
||||
if ($e->getCode() == MAPI_E_NO_ACCESS) {
|
||||
$e->setDisplayMessage(_("You have insufficient privileges to accept this Meeting Request."));
|
||||
}
|
||||
else {
|
||||
$e->setDisplayMessage(_("Could not accept Meeting Request."));
|
||||
}
|
||||
break;
|
||||
|
||||
case "cancelInvitation":
|
||||
if ($e->getCode() == MAPI_E_NO_ACCESS) {
|
||||
$e->setDisplayMessage(_("You have insufficient privileges to cancel Meeting Request invitation."));
|
||||
}
|
||||
else {
|
||||
$e->setDisplayMessage(_("Could not cancel Meeting Request invitations."));
|
||||
}
|
||||
break;
|
||||
|
||||
case "updatesearch":
|
||||
case "stopsearch":
|
||||
case "search":
|
||||
if ($e->getCode() == MAPI_E_NOT_INITIALIZED) {
|
||||
$e->setDisplayMessage(_("You can not continue search operation on this folder."));
|
||||
}
|
||||
else {
|
||||
$e->setDisplayMessage(_("Error in search, please try again."));
|
||||
}
|
||||
break;
|
||||
|
||||
case "expand":
|
||||
$e->setDisplayMessage(_("Error in distribution list expansion."));
|
||||
break;
|
||||
}
|
||||
Log::Write(
|
||||
LOGLEVEL_ERROR,
|
||||
"Module::handleException():" . $actionType . ": " . $e->displayMessage
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get quota information of user store and check for over qouta restrictions,
|
||||
* if any qouta (softquota/hardquota) limit is exceeded then it will simply
|
||||
* return appropriate message string according to quota type(hardquota/softquota).
|
||||
*
|
||||
* @param mixed $store Store object of the store
|
||||
*
|
||||
* @return string short message according to quota type(hardquota/softquota) or a blank string
|
||||
*/
|
||||
public function getOverQuotaMessage($store) {
|
||||
if ($store === false) {
|
||||
$store = $GLOBALS['mapisession']->getDefaultMessageStore();
|
||||
}
|
||||
|
||||
$storeProps = mapi_getprops($store, [PR_QUOTA_WARNING_THRESHOLD, PR_QUOTA_SEND_THRESHOLD, PR_QUOTA_RECEIVE_THRESHOLD, PR_MESSAGE_SIZE_EXTENDED]);
|
||||
|
||||
$quotaDetails = [
|
||||
'store_size' => round($storeProps[PR_MESSAGE_SIZE_EXTENDED] / 1024),
|
||||
'quota_warning' => $storeProps[PR_QUOTA_WARNING_THRESHOLD],
|
||||
'quota_soft' => $storeProps[PR_QUOTA_SEND_THRESHOLD],
|
||||
'quota_hard' => $storeProps[PR_QUOTA_RECEIVE_THRESHOLD],
|
||||
];
|
||||
|
||||
if ($quotaDetails['quota_hard'] !== 0 && $quotaDetails['store_size'] > $quotaDetails['quota_hard']) {
|
||||
return _('The message store has exceeded its hard quota limit.') . '<br/>' .
|
||||
_('To reduce the amount of data in this message store, select some items that you no longer need, delete them and cleanup your Deleted Items folder.');
|
||||
}
|
||||
|
||||
// if hard quota limit doesn't restrict the operation then check for soft qouta limit
|
||||
if ($quotaDetails['quota_soft'] !== 0 && $quotaDetails['store_size'] > $quotaDetails['quota_soft']) {
|
||||
return _('The message store has exceeded its soft quota limit.') . '<br/> ' .
|
||||
_('To reduce the amount of data in this message store, select some items that you no longer need, delete them and cleanup your Deleted Items folder.');
|
||||
}
|
||||
|
||||
return '';
|
||||
}
|
||||
|
||||
/**
|
||||
* sends a success or error message to client based on parameters passed.
|
||||
*
|
||||
* @param bool $success operation completed successfully or not
|
||||
* @param array $data the data array that will be send to the client as a response to success/failure
|
||||
* @param bool $addResponseDataToBus if true then data will be added to bus otherwise data
|
||||
* will be stored in module and later requests can add it to bus
|
||||
*/
|
||||
public function sendFeedback($success = false, $data = [], $addResponseDataToBus = true) {
|
||||
// Send success/error message to client
|
||||
$this->addActionData($success === true ? "success" : "error", $data);
|
||||
|
||||
if ($addResponseDataToBus) {
|
||||
$GLOBALS["bus"]->addData($this->getResponseData());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Function will retrieve error details from exception object based on exception type.
|
||||
* it should also send type of exception with the data. so client can know which type
|
||||
* of exception is generated.
|
||||
*
|
||||
* @param object $exception the exception object which is generated
|
||||
*
|
||||
* @return array error data
|
||||
*/
|
||||
public function errorDetailsFromException($exception) {
|
||||
if (!$exception->isHandled) {
|
||||
if ($exception instanceof MAPIException) {
|
||||
$exception->setHandled();
|
||||
|
||||
return [
|
||||
"type" => ERROR_MAPI,
|
||||
"info" => [
|
||||
"hresult" => $exception->getCode(),
|
||||
"title" => $exception->getTitle(),
|
||||
"hresult_name" => get_mapi_error_name($exception->getCode()),
|
||||
"file" => $exception->getFileLine(),
|
||||
"display_message" => $exception->getDisplayMessage(),
|
||||
"details_message" => $exception->getDetailsMessage(),
|
||||
],
|
||||
];
|
||||
}
|
||||
if ($exception instanceof GrommunioException) {
|
||||
$exception->setHandled();
|
||||
|
||||
return [
|
||||
"type" => ERROR_GROMMUNIO,
|
||||
"info" => [
|
||||
"file" => $exception->getFileLine(),
|
||||
"title" => $exception->getTitle(),
|
||||
"display_message" => $exception->getDisplayMessage(),
|
||||
"original_message" => $exception->getMessage(),
|
||||
],
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
return [];
|
||||
}
|
||||
|
||||
/**
|
||||
* Function which returns an entryid, which is used to register this module. It
|
||||
* searches in the class variable $data for a ParentEntryID or an EntryID.
|
||||
*
|
||||
* @return string an entryid if found, false if entryid not found
|
||||
*/
|
||||
public function getEntryID() {
|
||||
$entryid = false;
|
||||
foreach ($this->data as $action) {
|
||||
if (isset($action["parent_entryid"]) && !empty($action["parent_entryid"])) {
|
||||
$entryid = $action["parent_entryid"];
|
||||
}
|
||||
elseif (isset($action["entryid"]) && !empty($action["entryid"])) {
|
||||
$entryid = $action["entryid"];
|
||||
}
|
||||
}
|
||||
|
||||
return $entryid;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns all the errors, which occurred.
|
||||
*
|
||||
* @return array an array of all the errors, which occurred
|
||||
*/
|
||||
public function getErrors() {
|
||||
return $this->errors;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the response data.
|
||||
*
|
||||
* @return array An array of the response data. This data is send to the client.
|
||||
*/
|
||||
public function getData() {
|
||||
return $this->responseData;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the action data, which will be executed.
|
||||
*
|
||||
* @param array $data array of all the actions
|
||||
*/
|
||||
public function setData($data) {
|
||||
$this->data = $data;
|
||||
}
|
||||
|
||||
/**
|
||||
* Function which returns MAPI Message Store Object. It
|
||||
* searches in the variable $action for a storeid.
|
||||
*
|
||||
* @param array|false $action XML action data, or false when none is present
|
||||
*
|
||||
* @return array<int, false|resource>|false|resource MAPI store or stores, or false when no store ID is present
|
||||
*/
|
||||
public function getActionStore($action) {
|
||||
$store = false;
|
||||
|
||||
try {
|
||||
if (isset($action["store_entryid"]) && !empty($action["store_entryid"])) {
|
||||
if (is_array($action["store_entryid"])) {
|
||||
$store = [];
|
||||
foreach ($action["store_entryid"] as $store_id) {
|
||||
array_push($store, $GLOBALS["mapisession"]->openMessageStore(hex2bin((string) $store_id)));
|
||||
}
|
||||
}
|
||||
elseif (ctype_xdigit((string) $action["store_entryid"])) {
|
||||
$store = $GLOBALS["mapisession"]->openMessageStore(hex2bin((string) $action["store_entryid"]));
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Exception) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return $store;
|
||||
}
|
||||
|
||||
/**
|
||||
* Function which returns a parent entryid. It
|
||||
* searches in the variable $action for a parententryid.
|
||||
*
|
||||
* @param array $action the XML data retrieved from the client
|
||||
*
|
||||
* @return false|string binary parent entry ID, or false when it is not present
|
||||
*/
|
||||
public function getActionParentEntryID($action) {
|
||||
$parententryid = false;
|
||||
|
||||
if (isset($action["parent_entryid"]) && !empty($action["parent_entryid"])) {
|
||||
$parententryid = hex2bin((string) $action["parent_entryid"]);
|
||||
}
|
||||
|
||||
return $parententryid;
|
||||
}
|
||||
|
||||
/**
|
||||
* Function which returns an entryid. It
|
||||
* searches in the variable $action for an entryid.
|
||||
*
|
||||
* @param array $action the XML data retrieved from the client
|
||||
*
|
||||
* @return array<int, false|string>|false|string binary folder entry ID or IDs, or false when absent or invalid
|
||||
*/
|
||||
public function getActionEntryID($action) {
|
||||
$entryid = false;
|
||||
|
||||
if (isset($action["entryid"]) && !empty($action["entryid"])) {
|
||||
if (is_array($action["entryid"])) {
|
||||
$entryid = [];
|
||||
foreach ($action["entryid"] as $action_entryid) {
|
||||
array_push($entryid, hex2bin((string) $action_entryid));
|
||||
}
|
||||
}
|
||||
else {
|
||||
$entryid = hex2bin((string) $action["entryid"]);
|
||||
}
|
||||
}
|
||||
|
||||
return $entryid;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the single entry ID expected by scalar actions.
|
||||
*
|
||||
* Calendar list requests may address several stores and therefore use
|
||||
* getActionEntryID() directly. Other actions accept one item or folder and
|
||||
* reject an array instead of passing it to scalar MAPI calls.
|
||||
*
|
||||
* @param array $action the XML data retrieved from the client
|
||||
*
|
||||
* @return false|string binary entry ID, or false when absent, invalid, or multiple
|
||||
*/
|
||||
protected function getActionSingleEntryID($action) {
|
||||
$entryid = $this->getActionEntryID($action);
|
||||
|
||||
return is_string($entryid) ? $entryid : false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Helper function which used to get the action data from request.
|
||||
*
|
||||
* @param array $data list of all actions
|
||||
*
|
||||
* @return array|false JSON action data, or false when no action is present
|
||||
*/
|
||||
public function getActionData($data) {
|
||||
$actionData = false;
|
||||
foreach ($data as $actionType => $action) {
|
||||
if (isset($actionType)) {
|
||||
$actionData = $action;
|
||||
}
|
||||
}
|
||||
|
||||
return $actionData;
|
||||
}
|
||||
|
||||
/**
|
||||
* Function which adds action data to module, so later it can be retrieved to send.
|
||||
*
|
||||
* @param string $actionType type of action that response data corresponds
|
||||
* @param mixed $data
|
||||
*/
|
||||
public function addActionData($actionType, $data) {
|
||||
if (!isset($this->responseData[$actionType])) {
|
||||
$this->responseData[$actionType] = $data;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Function which returns response data that will be sent to client. If there isn't any data added
|
||||
* to response data then it will return a blank array.
|
||||
*
|
||||
* @return array response data
|
||||
*/
|
||||
public function getResponseData() {
|
||||
if (!empty($this->responseData)) {
|
||||
return
|
||||
[
|
||||
$this->getModuleName() => [
|
||||
$this->id => $this->responseData,
|
||||
],
|
||||
];
|
||||
}
|
||||
|
||||
return [];
|
||||
}
|
||||
|
||||
/**
|
||||
* Function which returns name of the module class.
|
||||
*
|
||||
* @return string module name
|
||||
*/
|
||||
public function getModuleName() {
|
||||
return strtolower(static::class);
|
||||
}
|
||||
|
||||
/**
|
||||
* Resource group whose requests must execute serially, null to run unlocked.
|
||||
*/
|
||||
protected function getExecutionLockName() {
|
||||
return $this->getModuleName();
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialize resources that need the module execution lock.
|
||||
*/
|
||||
protected function afterLoadSessionData() {}
|
||||
|
||||
/**
|
||||
* Function which will handle unknown action type for all modules.
|
||||
*
|
||||
* @param string $actionType action type
|
||||
*/
|
||||
public function handleUnknownActionType($actionType) {
|
||||
$this->sendFeedback(
|
||||
false,
|
||||
[
|
||||
"type" => ERROR_GROMMUNIO,
|
||||
"info" => [
|
||||
"display_message" => _("Could not process request data properly."),
|
||||
"original_message" => sprintf(_("Unknown action type specified - %s"), $actionType),
|
||||
],
|
||||
]
|
||||
);
|
||||
Log::Write(
|
||||
LOGLEVEL_ERROR,
|
||||
"Module::handleUnknownActionType(): ERROR_GROMMUNIO : " . _("Could not process request data properly.")
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Loads sessiondata of the module from state file on disk.
|
||||
*
|
||||
* @param State $sharedState optional shared State object so that
|
||||
* multiple modules can reuse a single lock
|
||||
* and avoid repeated open/serialize/close cycles
|
||||
*/
|
||||
public function loadSessionData($sharedState = null) {
|
||||
if ($sharedState) {
|
||||
$this->sessionState = $sharedState;
|
||||
$this->_sharedSessionState = true;
|
||||
$this->sessionData = $this->sessionState->read($this->getModuleName());
|
||||
$this->sessionDataSnapshot = serialize($this->sessionData);
|
||||
$this->afterLoadSessionData();
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$moduleName = $this->getModuleName();
|
||||
$lockName = $this->getExecutionLockName();
|
||||
if ($lockName === null) {
|
||||
$this->sessionData = null;
|
||||
$this->sessionDataSnapshot = serialize(null);
|
||||
$this->afterLoadSessionData();
|
||||
|
||||
return;
|
||||
}
|
||||
$this->sessionExecutionLock = new State('module-lock-' . hash('sha256', $lockName));
|
||||
if (!$this->sessionExecutionLock->open()) {
|
||||
throw new RuntimeException('Unable to lock module session state');
|
||||
}
|
||||
|
||||
$this->sessionState = new State('module_sessiondata');
|
||||
if (!$this->sessionState->open()) {
|
||||
throw new RuntimeException('Unable to read module session state');
|
||||
}
|
||||
|
||||
try {
|
||||
$this->sessionData = $this->sessionState->read($moduleName);
|
||||
$this->sessionDataSnapshot = serialize($this->sessionData);
|
||||
}
|
||||
finally {
|
||||
$this->sessionState->close();
|
||||
}
|
||||
$this->afterLoadSessionData();
|
||||
}
|
||||
|
||||
/**
|
||||
* Saves sessiondata of the module to the state file on disk.
|
||||
*/
|
||||
public function saveSessionData() {
|
||||
if ($this->_sharedSessionState) {
|
||||
if ($this->sessionData !== false) {
|
||||
$this->sessionState->write($this->getModuleName(), $this->sessionData, false);
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
if ($this->sessionData !== false) {
|
||||
$sessionData = serialize($this->sessionData);
|
||||
if ($sessionData === $this->sessionDataSnapshot) {
|
||||
return;
|
||||
}
|
||||
|
||||
$moduleName = $this->getModuleName();
|
||||
$this->sessionState = new State('module_sessiondata');
|
||||
if (!$this->sessionState->open()) {
|
||||
error_log('Unable to save module session state: ' . $moduleName);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
$currentSessionData = $this->sessionState->read($moduleName);
|
||||
if ($this->sessionDataSnapshot !== null && serialize($currentSessionData) !== $this->sessionDataSnapshot) {
|
||||
error_log('Module session state changed without its execution lock: ' . $moduleName);
|
||||
$this->sessionData = $currentSessionData;
|
||||
$this->sessionDataSnapshot = serialize($currentSessionData);
|
||||
|
||||
return;
|
||||
}
|
||||
$this->sessionState->write($moduleName, $this->sessionData);
|
||||
$this->sessionDataSnapshot = $sessionData;
|
||||
}
|
||||
finally {
|
||||
$this->sessionState->close();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Release this module's execution lock.
|
||||
*/
|
||||
public function closeSessionData() {
|
||||
if (!$this->_sharedSessionState && $this->sessionExecutionLock instanceof State) {
|
||||
$this->sessionExecutionLock->close();
|
||||
$this->sessionExecutionLock = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
+201
@@ -0,0 +1,201 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* SPDX-FileCopyrightText: Copyright 2020 - 2026 grommunio GmbH
|
||||
* SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
*/
|
||||
|
||||
/**
|
||||
* OutOfOfficeSettingsModule Module.
|
||||
*/
|
||||
class OutOfOfficeSettingsModule extends Module {
|
||||
/**
|
||||
* Constructor.
|
||||
*
|
||||
* @param int $id unique id
|
||||
* @param array $data list of all actions
|
||||
*/
|
||||
public function __construct($id, $data) {
|
||||
parent::__construct($id, $data);
|
||||
|
||||
$this->properties = $GLOBALS["properties"]->getOutOfOfficeProperties();
|
||||
}
|
||||
|
||||
/**
|
||||
* Executes all the actions in the $data variable.
|
||||
*/
|
||||
#[Override]
|
||||
public function execute() {
|
||||
foreach ($this->data as $actionType => $action) {
|
||||
if (isset($actionType)) {
|
||||
try {
|
||||
switch ($actionType) {
|
||||
case "list":
|
||||
$this->getOofSettings();
|
||||
break;
|
||||
|
||||
case "save":
|
||||
$this->saveOofSettings($action);
|
||||
break;
|
||||
|
||||
default:
|
||||
$this->handleUnknownActionType($actionType);
|
||||
}
|
||||
}
|
||||
catch (MAPIException|SettingsException $e) {
|
||||
$this->processException($e, $actionType);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Read 'out of office' settings from PR_EC_OUTOFOFFICE_*.
|
||||
*
|
||||
* Internal function to retrieve the 'out of office' settings from the store, these settings are normal properties on the store
|
||||
*/
|
||||
public function getOofSettings() {
|
||||
$otherStores = $this->getOwnerPermissionStores();
|
||||
array_unshift($otherStores, $GLOBALS['mapisession']->getDefaultMessageStore());
|
||||
|
||||
$oofSettings = [];
|
||||
foreach ($otherStores as $storeEntryId => $storeObj) {
|
||||
$externalProps = ['props' => []];
|
||||
$props = mapi_getprops($storeObj, $this->properties);
|
||||
if (!isset($props[PR_EC_OUTOFOFFICE])) {
|
||||
$props[PR_EC_OUTOFOFFICE] = false;
|
||||
}
|
||||
if (!isset($props[PR_EC_OUTOFOFFICE_MSG])) {
|
||||
$props[PR_EC_OUTOFOFFICE_MSG] = '';
|
||||
}
|
||||
if (!isset($props[PR_EC_OUTOFOFFICE_SUBJECT])) {
|
||||
$props[PR_EC_OUTOFOFFICE_SUBJECT] = '';
|
||||
}
|
||||
if (!isset($props[PR_EC_OUTOFOFFICE_FROM])) {
|
||||
$props[PR_EC_OUTOFOFFICE_FROM] = 0;
|
||||
}
|
||||
if (!isset($props[PR_EC_OUTOFOFFICE_UNTIL]) || $props[PR_EC_OUTOFOFFICE_UNTIL] === FUTURE_ENDDATE) {
|
||||
$props[PR_EC_OUTOFOFFICE_UNTIL] = 0;
|
||||
}
|
||||
if (!isset($props[PR_EC_ALLOW_EXTERNAL])) {
|
||||
$props[PR_EC_ALLOW_EXTERNAL] = 0;
|
||||
}
|
||||
if (!isset($props[PR_EC_EXTERNAL_AUDIENCE])) {
|
||||
$props[PR_EC_EXTERNAL_AUDIENCE] = 0;
|
||||
}
|
||||
if (!isset($props[PR_EC_EXTERNAL_REPLY])) {
|
||||
$props[PR_EC_EXTERNAL_REPLY] = '';
|
||||
}
|
||||
if (!isset($props[PR_EC_EXTERNAL_SUBJECT])) {
|
||||
$props[PR_EC_EXTERNAL_SUBJECT] = '';
|
||||
}
|
||||
|
||||
$externalProps['props']['entryid'] = bin2hex((string) $props[PR_MAILBOX_OWNER_ENTRYID]);
|
||||
$externalProps['props']['store_entryid'] = bin2hex((string) $props[PR_ENTRYID]);
|
||||
$externalProps['props']['set'] = $props[PR_EC_OUTOFOFFICE];
|
||||
$externalProps['props']['internal_reply'] = trim((string) $props[PR_EC_OUTOFOFFICE_MSG]);
|
||||
$externalProps['props']['internal_subject'] = trim((string) $props[PR_EC_OUTOFOFFICE_SUBJECT]);
|
||||
$externalProps['props']['from'] = $props[PR_EC_OUTOFOFFICE_FROM];
|
||||
$externalProps['props']['until'] = $props[PR_EC_OUTOFOFFICE_UNTIL];
|
||||
$externalProps['props']['allow_external'] = $props[PR_EC_ALLOW_EXTERNAL];
|
||||
$externalProps['props']['external_audience'] = $props[PR_EC_EXTERNAL_AUDIENCE];
|
||||
$externalProps['props']['external_reply'] = trim((string) $props[PR_EC_EXTERNAL_REPLY]);
|
||||
$externalProps['props']['external_subject'] = trim((string) $props[PR_EC_EXTERNAL_SUBJECT]);
|
||||
|
||||
array_push($oofSettings, $externalProps);
|
||||
}
|
||||
|
||||
// Send success message to client
|
||||
$this->addActionData('list', ['item' => $oofSettings]);
|
||||
|
||||
$GLOBALS["bus"]->addData($this->getResponseData());
|
||||
}
|
||||
|
||||
/**
|
||||
* Function returns array of user stores who has given 'Owner' permission to logged in user.
|
||||
* Internal function to retrieve the shared stores with 'owner' permission.
|
||||
*
|
||||
* @return array array of user stores who has given 'owner' permission
|
||||
*/
|
||||
public function getOwnerPermissionStores() {
|
||||
$stores = $GLOBALS['mapisession']->getOtherUserStore();
|
||||
|
||||
// $sharedOwnerStores array will contains store of users who has given 'owner' permission.
|
||||
// Or store of users which can be fully accessible by default user in case of 'Admin User'.
|
||||
$sharedOwnerStores = [];
|
||||
|
||||
foreach ($stores as $storeEntryId => $storeObj) {
|
||||
try {
|
||||
$subTree = mapi_getprops($storeObj, [PR_IPM_SUBTREE_ENTRYID]);
|
||||
$subtreeObj = mapi_msgstore_openentry($storeObj, $subTree[PR_IPM_SUBTREE_ENTRYID]);
|
||||
}
|
||||
catch (MAPIException $e) {
|
||||
// Skip stores that are inaccessible or where we
|
||||
// don't have rights to open the folder.
|
||||
$e->setHandled();
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
$permission = mapi_getprops($subtreeObj, [PR_RIGHTS]);
|
||||
$hasSufficientPermission = $permission[PR_RIGHTS] & ecRightsSecretary === ecRightsSecretary;
|
||||
|
||||
// If User store's IPM subtree has rights higher than 'secretary' then include that User's store.
|
||||
if ($hasSufficientPermission) {
|
||||
$sharedOwnerStores[$storeEntryId] = $storeObj;
|
||||
}
|
||||
}
|
||||
|
||||
return $sharedOwnerStores;
|
||||
}
|
||||
|
||||
/**
|
||||
* Internal function to save the 'out of office' settings to the correct properties on the store.
|
||||
* On success function will send 'success' feedback to user.
|
||||
*
|
||||
* Writes some properties to the PR_EC_OUTOFOFFICE_* properties
|
||||
*
|
||||
* @param array $action the action data, sent by the client
|
||||
*/
|
||||
public function saveOofSettings($action) {
|
||||
$storeEntryId = $action['store_entryid'];
|
||||
$oofSettings = $action['props'];
|
||||
$store = $GLOBALS['mapisession']->openMessageStore(hex2bin((string) $storeEntryId));
|
||||
$props = Conversion::mapXML2MAPI($this->properties, $oofSettings);
|
||||
$oofProps = mapi_getprops($store, [PR_EC_OUTOFOFFICE, PR_EC_OUTOFOFFICE_FROM, PR_EC_OUTOFOFFICE_UNTIL]);
|
||||
|
||||
// If client sent until value as 0 or User set OOF to true but don't set until
|
||||
// then save FUTURE_ENDDATE as until date. Also when OOF is already ON and User
|
||||
// don't change 'until' field then check if 'until' value is available in User's store
|
||||
// and if not then set until date to FUTURE_ENDDATE.
|
||||
// Note: If we remove PR_EC_OUTOFOFFICE_UNTIL property from User's store,
|
||||
// then gromox is setting past value "1970-01-01 00:00:00" as until date.
|
||||
// To avoid this issue and for OOF to work as expected, we are setting until date as FUTURE_ENDDATE.
|
||||
if (isset($oofSettings['until']) && $oofSettings['until'] === 0 ||
|
||||
!isset($oofSettings['until']) && isset($oofSettings['set']) ||
|
||||
(!isset($oofSettings['until'], $oofSettings['set']) &&
|
||||
(!isset($oofProps[PR_EC_OUTOFOFFICE_UNTIL]) || $oofProps[PR_EC_OUTOFOFFICE_UNTIL] === 0))) {
|
||||
$props[$this->properties['until']] = FUTURE_ENDDATE;
|
||||
}
|
||||
|
||||
// Check if the OOF is set for the future
|
||||
$oofSet = (isset($oofSettings['set']) && $oofSettings['set']) || (!isset($oofSettings['set']) && $oofProps[PR_EC_OUTOFOFFICE]);
|
||||
if ($oofSet && isset($oofSettings['from']) && intval($oofSettings['from']) > time()) {
|
||||
$props[$this->properties['set']] = 2;
|
||||
}
|
||||
// A subject of nothing but spaces counts as none. Gromox then titles
|
||||
// the reply from the incoming subject like Exchange does.
|
||||
foreach (['internal_subject', 'external_subject'] as $subject) {
|
||||
$tag = $this->properties[$subject];
|
||||
if (array_key_exists($tag, $props)) {
|
||||
$props[$tag] = trim((string) $props[$tag]);
|
||||
}
|
||||
}
|
||||
|
||||
if (!empty($props)) {
|
||||
mapi_setprops($store, $props);
|
||||
mapi_savechanges($store);
|
||||
}
|
||||
$this->sendFeedback(true);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,277 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* SPDX-FileCopyrightText: Copyright 2020 - 2026 grommunio GmbH
|
||||
* SPDX-FileCopyrightText: Copyright 2016 Kopano and its licensors
|
||||
* SPDX-FileCopyrightText: Copyright 2005 - 2016 Zarafa B.V. and its licensors
|
||||
* SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
*/
|
||||
|
||||
/**
|
||||
* Reminder ItemModule
|
||||
* Module which saves an item and it
|
||||
* extends the CreateMailItemModule class.
|
||||
*/
|
||||
class ReminderItemModule extends ItemModule {
|
||||
/**
|
||||
* Constructor.
|
||||
*
|
||||
* @param int $id unique id
|
||||
* @param array $data list of all actions
|
||||
*/
|
||||
public function __construct($id, $data) {
|
||||
parent::__construct($id, $data);
|
||||
}
|
||||
|
||||
/**
|
||||
* Set message flags for a flagged mail item.
|
||||
*
|
||||
* @param false|resource $store MAPI message store, or false when unavailable
|
||||
* @param false|string $parententryid binary parent entry ID, or false when absent
|
||||
* @param array|false|string $entryid binary message entry ID or IDs, or false when absent
|
||||
* @param array $action the action data, sent by the client
|
||||
* @param string $actionType the action type which triggered this action
|
||||
*/
|
||||
#[Override]
|
||||
public function save($store, $parententryid, $entryid, $action, $actionType = 'save') {
|
||||
$this->properties = $GLOBALS['properties']->getMailProperties();
|
||||
$result = false;
|
||||
|
||||
if ($store === false) {
|
||||
$store = $GLOBALS['mapisession']->getDefaultMessageStore();
|
||||
}
|
||||
|
||||
if ($store !== false) {
|
||||
// Reference to an array which will be filled with PR_ENTRYID, PR_STORE_ENTRYID and PR_PARENT_ENTRYID of the message
|
||||
$messageProps = [];
|
||||
|
||||
// Set message flags
|
||||
if (isset($action['props'], $action['props']['message_flags']) && $entryid) {
|
||||
$msg_action = $action['message_action'] ?? false;
|
||||
$result = $GLOBALS['operations']->setMessageFlag($store, $entryid, $action['props']['message_flags'], $msg_action, $messageProps);
|
||||
}
|
||||
|
||||
// Feedback for successful save
|
||||
if ($result) {
|
||||
$GLOBALS['bus']->notify(bin2hex($messageProps[PR_PARENT_ENTRYID]), TABLE_SAVE, $messageProps);
|
||||
}
|
||||
|
||||
$this->sendFeedback($result ? true : false, [], true);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Dismiss or snooze a reminder item.
|
||||
*
|
||||
* @param false|resource $store MAPI message store, or false when unavailable
|
||||
* @param false|string $parententryid binary parent entry ID, or false when absent
|
||||
* @param array|false|string $entryid binary message entry ID or IDs, or false when absent
|
||||
* @param array $action the action data, sent by the client
|
||||
*/
|
||||
#[Override]
|
||||
public function delete($store, $parententryid, $entryid, $action) {
|
||||
$this->properties = $GLOBALS["properties"]->getReminderProperties();
|
||||
|
||||
if ($store === false) {
|
||||
$store = $GLOBALS["mapisession"]->getDefaultMessageStore();
|
||||
}
|
||||
|
||||
$subActionType = false;
|
||||
if (isset($action["message_action"], $action["message_action"]["action_type"])) {
|
||||
$subActionType = $action["message_action"]["action_type"];
|
||||
}
|
||||
|
||||
switch ($subActionType) {
|
||||
case "snooze":
|
||||
$entryid = $this->getActionSingleEntryID($action);
|
||||
$this->snoozeItem($store, $entryid, $action);
|
||||
break;
|
||||
|
||||
case "dismiss":
|
||||
$entryid = $this->getActionSingleEntryID($action);
|
||||
$this->dismissItem($store, $entryid);
|
||||
break;
|
||||
|
||||
default:
|
||||
$this->handleUnknownActionType($subActionType);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Snooze a reminder for the requested time.
|
||||
*
|
||||
* @param false|resource $store MAPI message store, or false when unavailable
|
||||
* @param false|string $entryid entryid of the message, or false when absent
|
||||
* @param array $action the action data, sent by the client
|
||||
*/
|
||||
public function snoozeItem($store, $entryid, $action) {
|
||||
if ($store === false || !is_string($entryid) || $entryid === '') {
|
||||
$this->sendFeedback(false);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$result = false;
|
||||
$message = mapi_msgstore_openentry($store, $entryid);
|
||||
if ($message) {
|
||||
$newProps = [PR_ENTRYID => $entryid];
|
||||
$props = mapi_getprops($message, $this->properties);
|
||||
|
||||
$snoozeTime = $GLOBALS["settings"]->get('grommunio/v1/main/reminder/default_snooze_time', 5);
|
||||
if (isset($action["message_action"]["snoozeTime"]) && is_numeric($action["message_action"]["snoozeTime"])) {
|
||||
$snoozeTime = $action["message_action"]["snoozeTime"];
|
||||
}
|
||||
|
||||
$reminderTime = time() + ($snoozeTime * 60);
|
||||
if (class_match_prefix($props[$this->properties["message_class"]], "IPM.Appointment")) {
|
||||
if (isset($props[$this->properties["appointment_recurring"]]) && $props[$this->properties["appointment_recurring"]]) {
|
||||
$recurrence = new Recurrence($store, $message);
|
||||
$nextReminder = $recurrence->getNextReminderTime(time());
|
||||
|
||||
// flagdueby must be the snooze time or the time of the next instance, whichever is earlier
|
||||
if ($reminderTime < $nextReminder) {
|
||||
$newProps[$this->properties["flagdueby"]] = $reminderTime;
|
||||
}
|
||||
else {
|
||||
$newProps[$this->properties["flagdueby"]] = $nextReminder;
|
||||
}
|
||||
}
|
||||
else {
|
||||
$newProps[$this->properties["flagdueby"]] = $reminderTime;
|
||||
}
|
||||
}
|
||||
else {
|
||||
$newProps[$this->properties["flagdueby"]] = $reminderTime;
|
||||
}
|
||||
|
||||
// save props
|
||||
mapi_setprops($message, $newProps);
|
||||
mapi_savechanges($message);
|
||||
|
||||
$result = true;
|
||||
}
|
||||
|
||||
if ($result) {
|
||||
/*
|
||||
* @FIXME: Fix notifications for reminders.
|
||||
* Notifications are currently disabled, because deleting multiple items will notify
|
||||
* hierarchy multiple time but no data is changed with folder item in hierarchy.
|
||||
* so it will push same data again which will lead to an error.
|
||||
*/
|
||||
// $props = mapi_getprops($message, array(PR_ENTRYID, PR_PARENT_ENTRYID, PR_STORE_ENTRYID));
|
||||
// $GLOBALS["bus"]->notify(bin2hex($props[PR_PARENT_ENTRYID]), TABLE_SAVE, $props);
|
||||
}
|
||||
$this->sendFeedback($result);
|
||||
}
|
||||
|
||||
/**
|
||||
* Dismiss a reminder.
|
||||
*
|
||||
* @param false|resource $store MAPI message store, or false when unavailable
|
||||
* @param false|string $entryid entryid of the message, or false when absent
|
||||
*/
|
||||
public function dismissItem($store, $entryid) {
|
||||
if ($store === false || !is_string($entryid) || $entryid === '') {
|
||||
$this->sendFeedback(false);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$result = false;
|
||||
$message = mapi_msgstore_openentry($store, $entryid);
|
||||
if ($message) {
|
||||
$newProps = [];
|
||||
$props = mapi_getprops($message, $this->properties);
|
||||
|
||||
if (class_match_prefix($props[$this->properties["message_class"]], "IPM.Appointment")) {
|
||||
if (isset($props[$this->properties["appointment_recurring"]]) && $props[$this->properties["appointment_recurring"]]) {
|
||||
$recurrence = new Recurrence($store, $message);
|
||||
// check for next reminder after "now" for the next instance
|
||||
$nextReminder = $recurrence->getNextReminderTime(time());
|
||||
if ($nextReminder !== false) {
|
||||
$newProps[$this->properties["flagdueby"]] = $nextReminder;
|
||||
}
|
||||
else {
|
||||
$newProps[$this->properties["reminder"]] = false;
|
||||
}
|
||||
}
|
||||
else {
|
||||
$newProps[$this->properties["reminder"]] = false;
|
||||
}
|
||||
}
|
||||
elseif (class_match_prefix($props[$this->properties["message_class"]], "IPM.Task")) {
|
||||
$newProps[$this->properties["reminder"]] = false;
|
||||
|
||||
if (isset($props[$this->properties['task_recurring']]) && $props[$this->properties['task_recurring']] == 1) {
|
||||
$newProps[$this->properties['task_resetreminder']] = true;
|
||||
}
|
||||
}
|
||||
else {
|
||||
$newProps[$this->properties["reminder"]] = false;
|
||||
}
|
||||
|
||||
// save props
|
||||
mapi_setprops($message, $newProps);
|
||||
mapi_savechanges($message);
|
||||
|
||||
$result = true;
|
||||
}
|
||||
|
||||
if ($result) {
|
||||
/*
|
||||
* @FIXME: Fix notifications for reminders.
|
||||
* Notifications are currently disabled, because deleting multiple items will notify
|
||||
* hierarchy multiple time but no data is changed with folder item in hierarchy.
|
||||
* so it will push same data again which will lead to an error.
|
||||
*/
|
||||
// $props = mapi_getprops($message, array(PR_ENTRYID, PR_PARENT_ENTRYID, PR_STORE_ENTRYID));
|
||||
// $GLOBALS["bus"]->notify(bin2hex($props[PR_PARENT_ENTRYID]), TABLE_SAVE, $props);
|
||||
}
|
||||
$this->sendFeedback($result);
|
||||
}
|
||||
|
||||
/**
|
||||
* Function does customization of exception based on module data.
|
||||
* like, here it will generate display message based on actionType
|
||||
* for particular exception.
|
||||
*
|
||||
* @param object $e Exception object
|
||||
* @param string $actionType the action type, sent by the client
|
||||
* @param resource $store MAPI store containing the message
|
||||
* @param string $parententryid parent entryid of the message
|
||||
* @param string $entryid entryid of the message
|
||||
* @param array $action the action data, sent by the client
|
||||
*/
|
||||
#[Override]
|
||||
public function handleException(&$e, $actionType = null, $store = null, $parententryid = null, $entryid = null, $action = null) {
|
||||
if (is_null($e->displayMessage)) {
|
||||
switch ($actionType) {
|
||||
case 'delete':
|
||||
if (!empty($action['message_action']['action_type'])) {
|
||||
switch ($action['message_action']['action_type']) {
|
||||
case 'snooze':
|
||||
if ($e->getCode() == MAPI_E_STORE_FULL) {
|
||||
$e->setDisplayMessage(_('Cannot snooze the reminder. You may be reminded again.') . '<br />' . $this->getOverQuotaMessage($store));
|
||||
}
|
||||
else {
|
||||
$e->setDisplayMessage(_('Cannot snooze the reminder. You may be reminded again.'));
|
||||
}
|
||||
break;
|
||||
|
||||
case 'dismiss':
|
||||
if ($e->getCode() == MAPI_E_STORE_FULL) {
|
||||
$e->setDisplayMessage(_('Cannot dismiss the reminder. You may be reminded again.') . '<br />' . $this->getOverQuotaMessage($store));
|
||||
}
|
||||
else {
|
||||
$e->setDisplayMessage(_('Cannot dismiss the reminder. You may be reminded again.'));
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
parent::handleException($e, $actionType, $store, $parententryid, $entryid, $action);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,343 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* SPDX-FileCopyrightText: Copyright 2020 - 2026 grommunio GmbH
|
||||
* SPDX-FileCopyrightText: Copyright 2016 Kopano and its licensors
|
||||
* SPDX-FileCopyrightText: Copyright 2005 - 2016 Zarafa B.V. and its licensors
|
||||
* SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
*/
|
||||
|
||||
/**
|
||||
* Reminder Module.
|
||||
*
|
||||
* TODO: add description
|
||||
*/
|
||||
class ReminderListModule extends ListModule {
|
||||
#[Override]
|
||||
protected function getExecutionLockName() {
|
||||
return null;
|
||||
}
|
||||
private $reminderEntryId;
|
||||
|
||||
/**
|
||||
* Constructor.
|
||||
*
|
||||
* @param int $id unique id
|
||||
* @param array $data list of all actions
|
||||
*/
|
||||
public function __construct($id, $data) {
|
||||
parent::__construct($id, $data);
|
||||
|
||||
$this->properties = $GLOBALS["properties"]->getReminderProperties();
|
||||
}
|
||||
|
||||
#[Override]
|
||||
public function execute() {
|
||||
foreach ($this->data as $actionType => $action) {
|
||||
$store = $GLOBALS["mapisession"]->getDefaultMessageStore();
|
||||
$this->reminderEntryId = $this->getReminderFolderEntryId($store);
|
||||
|
||||
if (isset($actionType)) {
|
||||
try {
|
||||
switch ($actionType) {
|
||||
case "list":
|
||||
$this->getReminders();
|
||||
break;
|
||||
|
||||
default:
|
||||
$this->handleUnknownActionType($actionType);
|
||||
}
|
||||
}
|
||||
catch (MAPIException $e) {
|
||||
$this->processException($e, $actionType, $store, null, null, $action);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public function getReminderFolderEntryId($store) {
|
||||
$root = mapi_msgstore_openentry($store);
|
||||
$rootProps = mapi_getprops($root, [PR_REM_ONLINE_ENTRYID]);
|
||||
|
||||
// Reminder folder didn't exist, create one
|
||||
return $rootProps[PR_REM_ONLINE_ENTRYID] ?? $this->createReminderFolder($store);
|
||||
}
|
||||
|
||||
public function createReminderFolder($store) {
|
||||
$storeProps = mapi_getprops($store, [PR_IPM_OUTBOX_ENTRYID, PR_IPM_WASTEBASKET_ENTRYID, PR_IPM_SUBTREE_ENTRYID]);
|
||||
$root = mapi_msgstore_openentry($store);
|
||||
$rootProps = mapi_getprops($root, [PR_ADDITIONAL_REN_ENTRYIDS, PR_IPM_DRAFTS_ENTRYID]);
|
||||
|
||||
$folders = [];
|
||||
/* The list of forbidden folders (MS-OXORMDR v14 §1.1) */
|
||||
if (isset($storeProps[PR_IPM_WASTEBASKET_ENTRYID])) {
|
||||
$folders[] = $storeProps[PR_IPM_WASTEBASKET_ENTRYID];
|
||||
}
|
||||
if (isset($rootProps[PR_ADDITIONAL_REN_ENTRYIDS]) && !empty($rootProps[PR_ADDITIONAL_REN_ENTRYIDS][4])) {
|
||||
$folders[] = $rootProps[PR_ADDITIONAL_REN_ENTRYIDS][4];
|
||||
} // junk mail
|
||||
if (isset($rootProps[PR_IPM_DRAFTS_ENTRYID])) {
|
||||
$folders[] = $rootProps[PR_IPM_DRAFTS_ENTRYID];
|
||||
}
|
||||
if (isset($storeProps[PR_IPM_OUTBOX_ENTRYID])) {
|
||||
$folders[] = $storeProps[PR_IPM_OUTBOX_ENTRYID];
|
||||
}
|
||||
if (isset($rootProps[PR_ADDITIONAL_REN_ENTRYIDS]) && !empty($rootProps[PR_ADDITIONAL_REN_ENTRYIDS][0])) {
|
||||
$folders[] = $rootProps[PR_ADDITIONAL_REN_ENTRYIDS][0];
|
||||
} // conflicts
|
||||
if (isset($rootProps[PR_ADDITIONAL_REN_ENTRYIDS]) && !empty($rootProps[PR_ADDITIONAL_REN_ENTRYIDS][2])) {
|
||||
$folders[] = $rootProps[PR_ADDITIONAL_REN_ENTRYIDS][2];
|
||||
} // local failures
|
||||
if (isset($rootProps[PR_ADDITIONAL_REN_ENTRYIDS]) && !empty($rootProps[PR_ADDITIONAL_REN_ENTRYIDS][3])) {
|
||||
$folders[] = $rootProps[PR_ADDITIONAL_REN_ENTRYIDS][3];
|
||||
} // server failures
|
||||
if (isset($rootProps[PR_ADDITIONAL_REN_ENTRYIDS]) && !empty($rootProps[PR_ADDITIONAL_REN_ENTRYIDS][1])) {
|
||||
$folders[] = $rootProps[PR_ADDITIONAL_REN_ENTRYIDS][1];
|
||||
} // sync issues
|
||||
|
||||
$folderRestriction = [];
|
||||
foreach ($folders as $folder) {
|
||||
$folderRestriction[] = [RES_PROPERTY,
|
||||
[
|
||||
RELOP => RELOP_NE,
|
||||
ULPROPTAG => $this->properties["parent_entryid"],
|
||||
VALUE => [$this->properties["parent_entryid"] => $folder],
|
||||
],
|
||||
];
|
||||
}
|
||||
|
||||
$res =
|
||||
[RES_AND,
|
||||
[
|
||||
[RES_AND,
|
||||
$folderRestriction,
|
||||
],
|
||||
[RES_AND,
|
||||
[
|
||||
[RES_NOT,
|
||||
[
|
||||
[RES_AND,
|
||||
[
|
||||
[RES_EXIST,
|
||||
[
|
||||
ULPROPTAG => $this->properties["message_class"],
|
||||
],
|
||||
],
|
||||
[RES_CONTENT,
|
||||
[
|
||||
FUZZYLEVEL => FL_PREFIX,
|
||||
ULPROPTAG => $this->properties["message_class"],
|
||||
VALUE => [$this->properties["message_class"] => "IPM.Schedule"],
|
||||
],
|
||||
],
|
||||
],
|
||||
],
|
||||
],
|
||||
],
|
||||
[RES_BITMASK,
|
||||
[
|
||||
ULTYPE => BMR_EQZ,
|
||||
ULPROPTAG => $this->properties["message_flags"],
|
||||
ULMASK => MSGFLAG_SUBMIT,
|
||||
],
|
||||
],
|
||||
[RES_OR,
|
||||
[
|
||||
[RES_PROPERTY,
|
||||
[
|
||||
RELOP => RELOP_EQ,
|
||||
ULPROPTAG => $this->properties["reminder"],
|
||||
VALUE => [$this->properties["reminder"] => true],
|
||||
],
|
||||
],
|
||||
[RES_AND,
|
||||
[
|
||||
[RES_EXIST,
|
||||
[
|
||||
ULPROPTAG => $this->properties["recurring"],
|
||||
],
|
||||
],
|
||||
[RES_PROPERTY,
|
||||
[
|
||||
RELOP => RELOP_EQ,
|
||||
ULPROPTAG => $this->properties["recurring"],
|
||||
VALUE => [$this->properties["recurring"] => true],
|
||||
],
|
||||
],
|
||||
],
|
||||
],
|
||||
],
|
||||
],
|
||||
],
|
||||
],
|
||||
],
|
||||
];
|
||||
|
||||
$folder = mapi_folder_createfolder($root, _("Reminders"), "", OPEN_IF_EXISTS, FOLDER_SEARCH);
|
||||
mapi_setprops($folder, [PR_CONTAINER_CLASS => "Outlook.Reminder"]);
|
||||
mapi_savechanges($folder);
|
||||
|
||||
mapi_folder_setsearchcriteria($folder, $res, [$storeProps[PR_IPM_SUBTREE_ENTRYID]], RECURSIVE_SEARCH);
|
||||
$folderProps = mapi_getprops($folder, [PR_ENTRYID]);
|
||||
|
||||
mapi_setprops($root, [PR_REM_ONLINE_ENTRYID => $folderProps[PR_ENTRYID]]);
|
||||
mapi_savechanges($root);
|
||||
|
||||
return $folderProps[PR_ENTRYID];
|
||||
}
|
||||
|
||||
public function getReminders() {
|
||||
$data = [];
|
||||
|
||||
$store = $GLOBALS["mapisession"]->getDefaultMessageStore();
|
||||
|
||||
$restriction = [RES_AND,
|
||||
[
|
||||
[RES_PROPERTY,
|
||||
[
|
||||
RELOP => RELOP_LT,
|
||||
ULPROPTAG => $this->properties["flagdueby"],
|
||||
VALUE => [$this->properties["flagdueby"] => time()],
|
||||
],
|
||||
],
|
||||
[RES_PROPERTY,
|
||||
[
|
||||
RELOP => RELOP_EQ,
|
||||
ULPROPTAG => $this->properties["reminder"],
|
||||
VALUE => true,
|
||||
],
|
||||
],
|
||||
[RES_PROPERTY,
|
||||
[
|
||||
RELOP => RELOP_NE,
|
||||
ULPROPTAG => $this->properties["message_class"],
|
||||
VALUE => "IPM.TaskRequest",
|
||||
],
|
||||
],
|
||||
[RES_PROPERTY,
|
||||
[
|
||||
RELOP => RELOP_NE,
|
||||
ULPROPTAG => $this->properties["message_class"],
|
||||
VALUE => "IPM.TaskRequest.Cancel",
|
||||
],
|
||||
],
|
||||
[RES_PROPERTY,
|
||||
[
|
||||
RELOP => RELOP_NE,
|
||||
ULPROPTAG => $this->properties["message_class"],
|
||||
VALUE => "IPM.TaskRequest.Accept",
|
||||
],
|
||||
],
|
||||
[RES_PROPERTY,
|
||||
[
|
||||
RELOP => RELOP_NE,
|
||||
ULPROPTAG => $this->properties["message_class"],
|
||||
VALUE => "IPM.TaskRequest.Update",
|
||||
],
|
||||
],
|
||||
[RES_PROPERTY,
|
||||
[
|
||||
RELOP => RELOP_NE,
|
||||
ULPROPTAG => $this->properties["message_class"],
|
||||
VALUE => "IPM.TaskRequest.Complete",
|
||||
],
|
||||
],
|
||||
],
|
||||
];
|
||||
|
||||
try {
|
||||
$reminderfolder = mapi_msgstore_openentry($store, $this->reminderEntryId);
|
||||
}
|
||||
catch (MAPIException $e) {
|
||||
// if the reminder folder does not exist, try to recreate it.
|
||||
if ($e->getCode() == MAPI_E_NOT_FOUND) {
|
||||
$e->setHandled();
|
||||
|
||||
$this->reminderEntryId = $this->createReminderFolder($store);
|
||||
$reminderfolder = mapi_msgstore_openentry($store, $this->reminderEntryId);
|
||||
}
|
||||
else {
|
||||
throw $e;
|
||||
}
|
||||
}
|
||||
|
||||
$remindertable = mapi_folder_getcontentstable($reminderfolder, MAPI_DEFERRED_ERRORS);
|
||||
if (!$remindertable) {
|
||||
return false;
|
||||
}
|
||||
|
||||
mapi_table_restrict($remindertable, $restriction, TBL_BATCH);
|
||||
mapi_table_sort($remindertable, [$this->properties["flagdueby"] => TABLE_SORT_DESCEND], TBL_BATCH);
|
||||
|
||||
// reminder store hold only 99 records as
|
||||
// we show 99 notification on client side.
|
||||
$rows = mapi_table_queryrows($remindertable, $this->properties, 0, MAX_NUM_REMINDERS);
|
||||
$data["item"] = [];
|
||||
|
||||
foreach ($rows as $row) {
|
||||
if (isset($row[$this->properties["appointment_recurring"]]) && $row[$this->properties["appointment_recurring"]]) {
|
||||
$recur = new Recurrence($store, $row);
|
||||
|
||||
/**
|
||||
* FlagDueBy == PidLidReminderSignalTime.
|
||||
* FlagDueBy handles whether we should be showing the item; if now() is after FlagDueBy, then we should show a reminder
|
||||
* for this recurrence. However, the item we will show is either the most recent past occurrence (overdue), or the next occurrence, depending
|
||||
* on whether we have reached the next occurrence yet (the reminder_time of the next item is ignored).
|
||||
*
|
||||
* The way we handle this is to get all occurrences between the 'flagdueby' moment and the current time. This will
|
||||
* yield N items (possibly many if it was not dismissed for a long time). We can then take the last item in this list, and this is the item
|
||||
* we will show to the user. The idea here is:
|
||||
*
|
||||
* The item we want to show is the last item in that list (new occurrences that have started up to now should override old ones).
|
||||
*
|
||||
* Add the reminder_minutes (default 15 minutes for calendar, 0 for tasks) to check over the gap between FlagDueBy and the start time of the
|
||||
* occurrence, if "now" would be in between these values.
|
||||
*/
|
||||
$remindertimeinseconds = (int) ($row[$this->properties["reminder_minutes"]] ?? 0) * 60;
|
||||
$flagDueBy = $row[$this->properties["flagdueby"]] ?? null;
|
||||
if (!is_numeric($flagDueBy)) {
|
||||
$flagDueBy = $row[$this->properties["reminder_time"]] ??
|
||||
$row[$this->properties["appointment_startdate"]] ??
|
||||
null;
|
||||
}
|
||||
$flagDueBy = is_numeric($flagDueBy) ? (int) $flagDueBy : null;
|
||||
|
||||
$occurrences = null;
|
||||
if ($flagDueBy !== null) {
|
||||
try {
|
||||
$occurrences = $recur->getItems($flagDueBy, time() + $remindertimeinseconds, 0, true);
|
||||
}
|
||||
catch (RecurrenceException $re) {
|
||||
$re->setHandled();
|
||||
continue;
|
||||
}
|
||||
|
||||
if (empty($occurrences)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// More than one occurrence, use the last one instead of the first one after flagdueby
|
||||
$occ = $occurrences[count($occurrences) - 1];
|
||||
|
||||
// By default, occurrence reminders are enabled. A false reminder value suppresses the popup for this occurrence.
|
||||
if (!(isset($occ[$this->properties['reminder']]) && $occ[$this->properties['reminder']] == 0)) {
|
||||
$row[$this->properties["reminder_time"]] = $occ[$this->properties["appointment_startdate"]];
|
||||
$row[$this->properties["appointment_startdate"]] = $occ[$this->properties["appointment_startdate"]];
|
||||
$row[$this->properties["appointment_enddate"]] = $occ[$this->properties["appointment_startdate"]];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Add the non-bogus rows
|
||||
array_push($data["item"], Conversion::mapMAPI2XML($this->properties, $row));
|
||||
}
|
||||
|
||||
$this->addActionData("list", $data);
|
||||
$GLOBALS["bus"]->addData($this->getResponseData());
|
||||
|
||||
// Trigger the newmailnotifier
|
||||
$GLOBALS["bus"]->notify(REQUEST_ENTRYID, HIERARCHY_UPDATE, ['', '']);
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,618 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* SPDX-FileCopyrightText: Copyright 2020 - 2026 grommunio GmbH
|
||||
* SPDX-FileCopyrightText: Copyright 2016 Kopano and its licensors
|
||||
* SPDX-FileCopyrightText: Copyright 2005 - 2016 Zarafa B.V. and its licensors
|
||||
* SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
*/
|
||||
|
||||
/**
|
||||
* ResolveNames Module.
|
||||
*/
|
||||
class ResolveNamesModule extends Module {
|
||||
#[Override]
|
||||
protected function getExecutionLockName() {
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Constructor.
|
||||
*
|
||||
* @param mixed $id
|
||||
* @param mixed $data
|
||||
*/
|
||||
public function __construct($id, $data) {
|
||||
parent::__construct($id, $data);
|
||||
}
|
||||
|
||||
/**
|
||||
* Executes all the actions in the $data variable.
|
||||
*/
|
||||
#[Override]
|
||||
public function execute() {
|
||||
foreach ($this->data as $actionType => $action) {
|
||||
if (isset($actionType)) {
|
||||
try {
|
||||
switch ($actionType) {
|
||||
case 'checknames':
|
||||
$this->checkNames($action);
|
||||
break;
|
||||
|
||||
default:
|
||||
$this->handleUnknownActionType($actionType);
|
||||
}
|
||||
}
|
||||
catch (MAPIException $e) {
|
||||
$this->processException($e, $actionType);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Function which checks the names, sent by the client. This function is used
|
||||
* when a user wants to sent an email and want to check the names filled in
|
||||
* by the user in the to, cc and bcc field. This function uses the global
|
||||
* user list to check if the names are correct.
|
||||
*
|
||||
* @param array $action the action data, sent by the client
|
||||
*/
|
||||
public function checkNames($action) {
|
||||
if (isset($action['resolverequests'])) {
|
||||
$data = [];
|
||||
$excludeLocalContacts = $action['exclude_local_contacts'] ?? false;
|
||||
$excludeGABGroups = $action['exclude_gab_groups'] ?? false;
|
||||
$resolveRequest = $action['resolverequests'];
|
||||
if (!is_array($resolveRequest)) {
|
||||
$resolveRequest = [$resolveRequest];
|
||||
}
|
||||
|
||||
// open addressbook
|
||||
// When local contacts need to be excluded we have pass true as the first argument
|
||||
// so we will not have any Contact Providers set on the Addressbook resource.
|
||||
$ab = $GLOBALS['mapisession']->getAddressbook($excludeLocalContacts);
|
||||
|
||||
$ab_dir = mapi_ab_openentry($ab);
|
||||
$resolveResponse = [];
|
||||
|
||||
// check names
|
||||
foreach ($resolveRequest as $query) {
|
||||
if (is_array($query) && isset($query['id'])) {
|
||||
$responseEntry = [];
|
||||
$responseEntry['id'] = $query['id'];
|
||||
|
||||
if (!empty($query['display_name']) || !empty($query['email_address'])) {
|
||||
$responseEntry['result'] = $this->searchAddressBook($ab, $ab_dir, $query, $excludeGABGroups);
|
||||
$resolveResponse[] = $responseEntry;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
$data['resolveresponse'] = $resolveResponse;
|
||||
|
||||
$this->addActionData('checknames', $data);
|
||||
$GLOBALS['bus']->addData($this->getResponseData());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* This function searches the addressbook specified for users and returns an array with data
|
||||
* Please note that the returning array must be UTF8.
|
||||
*
|
||||
* @param resource $ab The addressbook
|
||||
* @param resource $ab_dir The addressbook container
|
||||
* @param array $query The search query, case is ignored
|
||||
* @param bool $excludeGABGroups flag to exclude groups from resolving
|
||||
*/
|
||||
public function searchAddressBook($ab, $ab_dir, $query, $excludeGABGroups) {
|
||||
$searchstr = $this->getSearchString($query);
|
||||
if ($searchstr === '') {
|
||||
return [];
|
||||
}
|
||||
// If the address_type is 'EX' then we are resolving something which must be found in
|
||||
// the GAB as an exact match. So add the flag EMS_AB_ADDRESS_LOOKUP to ensure we will not
|
||||
// get multiple results when multiple items have a partial match.
|
||||
$flags = $query['address_type'] === 'EX' ? EMS_AB_ADDRESS_LOOKUP : 0;
|
||||
|
||||
try {
|
||||
// First, try an addressbook lookup
|
||||
$rows = mapi_ab_resolvename($ab, [[PR_DISPLAY_NAME => $searchstr]], $flags);
|
||||
|
||||
// If the lookup succeeded but we should also check for exact hidden matches
|
||||
if (defined('ENABLE_RESOLVE_HIDDEN_USERS') && ENABLE_RESOLVE_HIDDEN_USERS && !($flags & EMS_AB_ADDRESS_LOOKUP)) {
|
||||
$hiddenRows = $this->resolveHiddenExactMatches($ab, $query);
|
||||
if (!empty($hiddenRows)) {
|
||||
$rows = $this->mergeAndDeduplicateRows($rows, $hiddenRows);
|
||||
}
|
||||
}
|
||||
|
||||
$this->searchContactsFolders($ab, $ab_dir, $searchstr, $rows);
|
||||
}
|
||||
catch (MAPIException $e) {
|
||||
if ($e->getCode() == MAPI_E_AMBIGUOUS_RECIP) {
|
||||
$ab_entryid = mapi_ab_getdefaultdir($ab);
|
||||
if ($ab_entryid === false) {
|
||||
throw $e;
|
||||
}
|
||||
$ab_dir = mapi_ab_openentry($ab, $ab_entryid);
|
||||
if ($ab_dir === false) {
|
||||
throw $e;
|
||||
}
|
||||
// Ambiguous, show possibilities:
|
||||
$table = mapi_folder_getcontentstable($ab_dir, MAPI_DEFERRED_ERRORS);
|
||||
$restriction = $this->getAmbigiousContactRestriction($searchstr, $excludeGABGroups, PR_ACCOUNT);
|
||||
|
||||
mapi_table_restrict($table, $restriction, TBL_BATCH);
|
||||
mapi_table_sort($table, [PR_DISPLAY_NAME => TABLE_SORT_ASCEND], TBL_BATCH);
|
||||
|
||||
$rows = mapi_table_queryallrows($table, [PR_ACCOUNT, PR_ADDRTYPE, PR_DISPLAY_NAME, PR_ENTRYID, PR_SEARCH_KEY, PR_OBJECT_TYPE, PR_SMTP_ADDRESS, PR_DISPLAY_TYPE_EX, PR_EMAIL_ADDRESS, PR_OBJECT_TYPE, PR_DISPLAY_TYPE]);
|
||||
|
||||
$rows = array_merge($rows, $this->getAmbigiousContactResolveResults($ab, $searchstr, $excludeGABGroups));
|
||||
|
||||
// Also check for hidden users if enabled and this is an exact match
|
||||
if (defined('ENABLE_RESOLVE_HIDDEN_USERS') && ENABLE_RESOLVE_HIDDEN_USERS) {
|
||||
$hiddenRows = $this->resolveHiddenExactMatches($ab, $query);
|
||||
if (!empty($hiddenRows)) {
|
||||
$rows = $this->mergeAndDeduplicateRows($rows, $hiddenRows);
|
||||
}
|
||||
}
|
||||
}
|
||||
elseif ($e->getCode() == MAPI_E_NOT_FOUND) {
|
||||
$rows = [];
|
||||
|
||||
if (defined('ENABLE_RESOLVE_HIDDEN_USERS') && ENABLE_RESOLVE_HIDDEN_USERS) {
|
||||
$rows = $this->resolveHiddenExactMatches($ab, $query);
|
||||
}
|
||||
|
||||
if (empty($rows) && (($query['address_type'] ?? '') === 'SMTP')) {
|
||||
// If we still can't find anything, and we were searching for a SMTP user
|
||||
// we can generate a oneoff entry which contains the information of the user.
|
||||
// Only for an actual address, else the one-off would be undeliverable.
|
||||
if ($GLOBALS['operations']->isEmailAddressLike($searchstr)) {
|
||||
$entryId = mapi_createoneoff($query['display_name'], 'SMTP', $searchstr);
|
||||
if ($entryId !== false) {
|
||||
$rows[] = [
|
||||
PR_ACCOUNT => $searchstr, PR_ADDRTYPE => 'SMTP', PR_EMAIL_ADDRESS => $searchstr,
|
||||
PR_DISPLAY_NAME => $query['display_name'], PR_DISPLAY_TYPE_EX => DT_REMOTE_MAILUSER, PR_DISPLAY_TYPE => DT_MAILUSER,
|
||||
PR_SMTP_ADDRESS => $searchstr, PR_OBJECT_TYPE => MAPI_MAILUSER,
|
||||
PR_ENTRYID => $entryId,
|
||||
];
|
||||
}
|
||||
}
|
||||
// Check also the user's contacts folders
|
||||
else {
|
||||
$this->searchContactsFolders($ab, $ab_dir, $searchstr, $rows);
|
||||
}
|
||||
}
|
||||
elseif (empty($rows)) {
|
||||
$this->searchContactsFolders($ab, $ab_dir, $searchstr, $rows);
|
||||
}
|
||||
}
|
||||
else {
|
||||
// all other errors should be propagated to higher level exception handlers
|
||||
throw $e;
|
||||
}
|
||||
}
|
||||
|
||||
$items = [];
|
||||
$searchstr = 'smtp:' . strtolower($searchstr);
|
||||
if ($rows) {
|
||||
foreach ($rows as $user_data) {
|
||||
$item = [];
|
||||
|
||||
if (!isset($user_data[PR_ACCOUNT])) {
|
||||
$abitem = mapi_ab_openentry($ab, $user_data[PR_ENTRYID]);
|
||||
$user_data = mapi_getprops($abitem, [PR_ACCOUNT, PR_ADDRTYPE, PR_DISPLAY_NAME, PR_DISPLAY_TYPE_EX, PR_ENTRYID, PR_SEARCH_KEY, PR_EMAIL_ADDRESS, PR_SMTP_ADDRESS, PR_OBJECT_TYPE, PR_DISPLAY_TYPE]);
|
||||
}
|
||||
|
||||
if ($excludeGABGroups && $user_data[PR_OBJECT_TYPE] === MAPI_DISTLIST) {
|
||||
// exclude groups from result
|
||||
continue;
|
||||
}
|
||||
|
||||
$item = [];
|
||||
$item['object_type'] = $user_data[PR_OBJECT_TYPE] ?? MAPI_MAILUSER;
|
||||
$item['entryid'] = isset($user_data[PR_ENTRYID]) ? bin2hex($user_data[PR_ENTRYID]) : '';
|
||||
$item['display_name'] = $user_data[PR_DISPLAY_NAME] ?? '';
|
||||
$item['display_type'] = $user_data[PR_DISPLAY_TYPE] ?? DT_MAILUSER;
|
||||
|
||||
// Test whether the GUID in the entryid is from the Contact Provider
|
||||
if ($GLOBALS['entryid']->hasContactProviderGUID($item['entryid'])) {
|
||||
// The properties for a Distribution List differs from the other objects
|
||||
if ($item['object_type'] == MAPI_DISTLIST) {
|
||||
$item['address_type'] = 'MAPIPDL';
|
||||
// The email_address is empty for DistList, using display name for resolving
|
||||
$item['email_address'] = $item['display_name'];
|
||||
$item['smtp_address'] ??= '';
|
||||
}
|
||||
else {
|
||||
$item['address_type'] = $user_data[PR_ADDRTYPE] ?? 'SMTP';
|
||||
if (isset($user_data['address_type']) && $user_data['address_type'] === 'EX') {
|
||||
$item['email_address'] = $user_data[PR_EMAIL_ADDRESS] ?? '';
|
||||
}
|
||||
else {
|
||||
// Fake being an EX account, since it's actually an SMTP addrtype the email address is in a different property.
|
||||
$item['smtp_address'] = $user_data[PR_EMAIL_ADDRESS] ?? '';
|
||||
// Keep the old scenario happy.
|
||||
$item['email_address'] = $user_data[PR_EMAIL_ADDRESS] ?? '';
|
||||
}
|
||||
}
|
||||
// It can be considered a GAB entry
|
||||
}
|
||||
else {
|
||||
$item['user_name'] = $user_data[PR_ACCOUNT] ?? $item['display_name'];
|
||||
$item['display_type_ex'] = $user_data[PR_DISPLAY_TYPE_EX] ?? MAPI_MAILUSER;
|
||||
$item['email_address'] = $user_data[PR_EMAIL_ADDRESS] ?? '';
|
||||
$item['smtp_address'] = $user_data[PR_SMTP_ADDRESS] ?? $item['email_address'];
|
||||
$item['address_type'] = $user_data[PR_ADDRTYPE] ?? 'SMTP';
|
||||
}
|
||||
|
||||
if (isset($user_data[PR_SEARCH_KEY])) {
|
||||
$item['search_key'] = bin2hex($user_data[PR_SEARCH_KEY]);
|
||||
}
|
||||
else {
|
||||
$emailAddress = $item['smtp_address'] ?? $item['email_address'];
|
||||
$item['search_key'] = bin2hex(strtoupper($item['address_type'] . ':' . $emailAddress)) . '00';
|
||||
}
|
||||
// Check for aliases
|
||||
if (isset($user_data[PR_EMS_AB_PROXY_ADDRESSES]) &&
|
||||
is_array($user_data[PR_EMS_AB_PROXY_ADDRESSES]) &&
|
||||
in_array($searchstr, array_map('strtolower', $user_data[PR_EMS_AB_PROXY_ADDRESSES])) &&
|
||||
!str_ends_with($searchstr, $user_data[PR_SMTP_ADDRESS]) &&
|
||||
$flags === 0) {
|
||||
$item['email_address'] = $item['smtp_address'] = substr($searchstr, 5);
|
||||
$item['display_name'] .= ' <' . $item['smtp_address'] . '>';
|
||||
$item['address_type'] = 'SMTP';
|
||||
}
|
||||
|
||||
array_push($items, $item);
|
||||
}
|
||||
}
|
||||
|
||||
return $items;
|
||||
}
|
||||
|
||||
/**
|
||||
* Pick the string used to resolve a recipient: a plausible email_address
|
||||
* first, Exchange DNs as-is (exact DN match), then smtp_address, then
|
||||
* display name. Legacy non-address values in email_address (e.g. old
|
||||
* account names) would otherwise fuzzy-match unrelated GAB entries.
|
||||
*
|
||||
* @param array $query resolve request sent by the client
|
||||
*
|
||||
* @return string the search string, may be empty
|
||||
*/
|
||||
public function getSearchString($query) {
|
||||
$emailAddress = trim((string) ($query['email_address'] ?? ''));
|
||||
$smtpAddress = trim((string) ($query['smtp_address'] ?? ''));
|
||||
$displayName = trim((string) ($query['display_name'] ?? ''));
|
||||
|
||||
if ($emailAddress !== '' &&
|
||||
($GLOBALS['operations']->isEmailAddressLike($emailAddress) || stripos($emailAddress, '/o=') === 0)) {
|
||||
return $emailAddress;
|
||||
}
|
||||
// Only when a (legacy) email_address was present: an empty one means
|
||||
// the client deliberately asked for display name resolution.
|
||||
if ($emailAddress !== '' && $GLOBALS['operations']->isEmailAddressLike($smtpAddress)) {
|
||||
return $smtpAddress;
|
||||
}
|
||||
if ($displayName !== '') {
|
||||
return $displayName;
|
||||
}
|
||||
|
||||
return $emailAddress;
|
||||
}
|
||||
|
||||
/**
|
||||
* Try to resolve a hidden user by matching the provided query exactly against
|
||||
* common address book properties. Hidden entries are not returned in regular
|
||||
* searches, but the EMS_AB_ADDRESS_LOOKUP flag allows us to perform an exact
|
||||
* lookup that also returns hidden entries.
|
||||
*
|
||||
* @param resource $ab The addressbook
|
||||
* @param array $query Resolve query sent by the client
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
protected function resolveHiddenExactMatches($ab, $query) {
|
||||
if (!defined('ENABLE_RESOLVE_HIDDEN_USERS') || !ENABLE_RESOLVE_HIDDEN_USERS) {
|
||||
return [];
|
||||
}
|
||||
|
||||
$candidates = [];
|
||||
|
||||
if (!empty($query['display_name'])) {
|
||||
$candidates[] = trim((string) $query['display_name']);
|
||||
}
|
||||
|
||||
if (!empty($query['email_address'])) {
|
||||
$candidates[] = trim((string) $query['email_address']);
|
||||
}
|
||||
|
||||
$candidates = array_values(array_unique(array_filter($candidates, 'strlen')));
|
||||
$addressType = strtoupper((string) ($query['address_type'] ?? ''));
|
||||
|
||||
foreach ($candidates as $candidate) {
|
||||
$lookups = [PR_DISPLAY_NAME];
|
||||
|
||||
if ($addressType === 'EX') {
|
||||
$lookups[] = PR_ACCOUNT;
|
||||
}
|
||||
|
||||
if (str_contains($candidate, '@')) {
|
||||
$lookups[] = PR_EMAIL_ADDRESS;
|
||||
$lookups[] = PR_SMTP_ADDRESS;
|
||||
|
||||
if ($addressType !== 'EX') {
|
||||
$lookups[] = PR_ACCOUNT;
|
||||
}
|
||||
}
|
||||
|
||||
foreach (array_unique($lookups) as $property) {
|
||||
$rows = $this->resolveNameByProperty($ab, $property, $candidate);
|
||||
if (!empty($rows)) {
|
||||
return $rows;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return [];
|
||||
}
|
||||
|
||||
/**
|
||||
* Execute an exact resolve against the GAB for the provided property.
|
||||
*
|
||||
* @param resource $ab The addressbook
|
||||
* @param int $property Property tag used for the lookup
|
||||
* @param string $value Search value
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
protected function resolveNameByProperty($ab, $property, $value) {
|
||||
if ($value === '') {
|
||||
return [];
|
||||
}
|
||||
|
||||
try {
|
||||
return mapi_ab_resolvename($ab, [[$property => $value]], EMS_AB_ADDRESS_LOOKUP);
|
||||
}
|
||||
catch (MAPIException $e) {
|
||||
if ($e->getCode() == MAPI_E_NOT_FOUND || $e->getCode() == MAPI_E_AMBIGUOUS_RECIP) {
|
||||
return [];
|
||||
}
|
||||
|
||||
throw $e;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Merge two arrays of rows and remove duplicates based on entryid.
|
||||
* This prevents the same user from appearing multiple times when they're
|
||||
* found through both normal and hidden user resolution.
|
||||
*
|
||||
* @param array $existingRows Existing rows from table/resolve queries
|
||||
* @param array $newRows New rows from hidden user resolution
|
||||
*
|
||||
* @return array Merged array with duplicates removed
|
||||
*/
|
||||
protected function mergeAndDeduplicateRows($existingRows, $newRows) {
|
||||
// Build a map of existing entryids
|
||||
$entryidMap = [];
|
||||
foreach ($existingRows as $row) {
|
||||
if (isset($row[PR_ENTRYID])) {
|
||||
$entryidMap[bin2hex($row[PR_ENTRYID])] = true;
|
||||
}
|
||||
}
|
||||
|
||||
// Add new rows only if they don't already exist
|
||||
foreach ($newRows as $row) {
|
||||
if (isset($row[PR_ENTRYID])) {
|
||||
$entryidHex = bin2hex($row[PR_ENTRYID]);
|
||||
if (!isset($entryidMap[$entryidHex])) {
|
||||
$existingRows[] = $row;
|
||||
$entryidMap[$entryidHex] = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return $existingRows;
|
||||
}
|
||||
|
||||
/**
|
||||
* Used to find multiple entries from the contact folders in the Addressbook when resolving
|
||||
* returned an ambiguous result. It will find the Contact folders in the Addressbook and
|
||||
* apply a restriction to extract the entries.
|
||||
*
|
||||
* @param resource $ab The addressbook
|
||||
* @param string $query The search query, case is ignored
|
||||
* @param bool $excludeGABGroups flag to exclude groups from resolving
|
||||
*/
|
||||
public function getAmbigiousContactResolveResults($ab, $query, $excludeGABGroups) {
|
||||
/* We need to look for the Contact folders at the bottom of the following tree.
|
||||
*
|
||||
* IAddrBook
|
||||
* - Root Container
|
||||
* - HIERARCHY TABLE
|
||||
* - Contacts Folders (Contact Container)
|
||||
* - HIERARCHY TABLE (Contact Container Hierarchy)
|
||||
* - Contact folder 1
|
||||
* - Contact folder 2
|
||||
*/
|
||||
|
||||
$rows = [];
|
||||
$contactFolderRestriction = $this->getAmbigiousContactRestriction($query, $excludeGABGroups, PR_EMAIL_ADDRESS);
|
||||
// Open the AB Root Container by not supplying an entryid
|
||||
$abRootContainer = mapi_ab_openentry($ab);
|
||||
|
||||
// Get the 'Contact Folders'
|
||||
$hierarchyTable = mapi_folder_gethierarchytable($abRootContainer, MAPI_DEFERRED_ERRORS);
|
||||
$abHierarchyRows = mapi_table_queryallrows($hierarchyTable, [PR_AB_PROVIDER_ID, PR_ENTRYID]);
|
||||
$abContactContainerEntryid = null;
|
||||
|
||||
// Look for the 'Contacts Folders'
|
||||
for ($i = 0,$len = count($abHierarchyRows); $i < $len; ++$i) {
|
||||
// Check if the folder matches the Contact Provider GUID
|
||||
if ($abHierarchyRows[$i][PR_AB_PROVIDER_ID] == MUIDZCSAB) {
|
||||
$abContactContainerEntryid = $abHierarchyRows[$i][PR_ENTRYID];
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// Next go into the 'Contacts Folders' and look in the hierarchy table for the Contact folders.
|
||||
if ($abContactContainerEntryid) {
|
||||
// Get the rows from hierarchy table of the 'Contacts Folders'
|
||||
$abContactContainer = mapi_ab_openentry($ab, $abContactContainerEntryid);
|
||||
$abContactContainerHierarchyTable = mapi_folder_gethierarchytable($abContactContainer, MAPI_DEFERRED_ERRORS);
|
||||
$abContactContainerHierarchyRows = mapi_table_queryallrows($abContactContainerHierarchyTable, [PR_DISPLAY_NAME, PR_OBJECT_TYPE, PR_ENTRYID]);
|
||||
|
||||
// Loop through all the contact folders found under the 'Contacts Folders' hierarchy
|
||||
for ($j = 0,$len = count($abContactContainerHierarchyRows); $j < $len; ++$j) {
|
||||
// Open, get contents table, restrict, sort and then merge the result in the list of $rows
|
||||
$abContactFolder = mapi_ab_openentry($ab, $abContactContainerHierarchyRows[$j][PR_ENTRYID]);
|
||||
$abContactFolderTable = mapi_folder_getcontentstable($abContactFolder, MAPI_DEFERRED_ERRORS);
|
||||
|
||||
mapi_table_restrict($abContactFolderTable, $contactFolderRestriction, TBL_BATCH);
|
||||
mapi_table_sort($abContactFolderTable, [PR_DISPLAY_NAME => TABLE_SORT_ASCEND], TBL_BATCH);
|
||||
|
||||
// Go go gadget, merge!
|
||||
$rows = array_merge($rows, mapi_table_queryallrows($abContactFolderTable, [PR_ACCOUNT, PR_DISPLAY_NAME, PR_ENTRYID, PR_OBJECT_TYPE, PR_SMTP_ADDRESS, PR_DISPLAY_TYPE_EX, PR_EMAIL_ADDRESS, PR_OBJECT_TYPE, PR_DISPLAY_TYPE]));
|
||||
}
|
||||
}
|
||||
|
||||
return $rows;
|
||||
}
|
||||
|
||||
/**
|
||||
* Setup the restriction used for resolving in the Contact folders or GAB.
|
||||
*
|
||||
* @param string $query The search query, case is ignored
|
||||
* @param bool $excludeGABGroups flag to exclude groups from resolving
|
||||
* @param int $content the PROPTAG to search in
|
||||
*/
|
||||
public function getAmbigiousContactRestriction($query, $excludeGABGroups, $content) {
|
||||
// only return users from who the displayName or the username starts with $name
|
||||
// TODO: use PR_ANR for this restriction instead of PR_DISPLAY_NAME and $content.
|
||||
$resAnd = [
|
||||
[RES_OR,
|
||||
[
|
||||
[RES_CONTENT,
|
||||
[
|
||||
FUZZYLEVEL => FL_PREFIX | FL_IGNORECASE,
|
||||
ULPROPTAG => PR_DISPLAY_NAME,
|
||||
VALUE => $query,
|
||||
],
|
||||
],
|
||||
[RES_CONTENT,
|
||||
[
|
||||
FUZZYLEVEL => FL_PREFIX | FL_IGNORECASE,
|
||||
ULPROPTAG => $content,
|
||||
VALUE => $query,
|
||||
],
|
||||
],
|
||||
], // RES_OR
|
||||
],
|
||||
];
|
||||
|
||||
// create restrictions based on excludeGABGroups flag
|
||||
if ($excludeGABGroups) {
|
||||
array_push($resAnd, [
|
||||
RES_PROPERTY,
|
||||
[
|
||||
RELOP => RELOP_EQ,
|
||||
ULPROPTAG => PR_OBJECT_TYPE,
|
||||
VALUE => MAPI_MAILUSER,
|
||||
],
|
||||
]);
|
||||
}
|
||||
else {
|
||||
array_push($resAnd, [RES_OR,
|
||||
[
|
||||
[RES_PROPERTY,
|
||||
[
|
||||
RELOP => RELOP_EQ,
|
||||
ULPROPTAG => PR_OBJECT_TYPE,
|
||||
VALUE => MAPI_MAILUSER,
|
||||
],
|
||||
],
|
||||
[RES_PROPERTY,
|
||||
[
|
||||
RELOP => RELOP_EQ,
|
||||
ULPROPTAG => PR_OBJECT_TYPE,
|
||||
VALUE => MAPI_DISTLIST,
|
||||
],
|
||||
],
|
||||
],
|
||||
]);
|
||||
}
|
||||
|
||||
return [RES_AND, $resAnd];
|
||||
}
|
||||
|
||||
/**
|
||||
* Function does customization of exception based on module data.
|
||||
* like, here it will generate display message based on actionType
|
||||
* for particular exception.
|
||||
*
|
||||
* @param object $e Exception object
|
||||
* @param string $actionType the action type, sent by the client
|
||||
* @param resource $store MAPI store containing the message
|
||||
* @param string $parententryid parent entryid of the message
|
||||
* @param string $entryid entryid of the message
|
||||
* @param array $action the action data, sent by the client
|
||||
*/
|
||||
#[Override]
|
||||
public function handleException(&$e, $actionType = null, $store = null, $parententryid = null, $entryid = null, $action = null) {
|
||||
if (is_null($e->displayMessage)) {
|
||||
switch ($actionType) {
|
||||
case 'checknames':
|
||||
if ($e->getCode() == MAPI_E_NO_ACCESS) {
|
||||
$e->setDisplayMessage(_('You have insufficient privileges to perform this action.'));
|
||||
}
|
||||
else {
|
||||
$e->setDisplayMessage(_('Could not resolve user.'));
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
parent::handleException($e, $actionType, $store, $parententryid, $entryid, $action);
|
||||
}
|
||||
|
||||
/**
|
||||
* This function searches the private contact folders for users and returns an array with data.
|
||||
* Please note that the returning array must be UTF8.
|
||||
*
|
||||
* @param resource $ab The addressbook
|
||||
* @param resource $ab_dir The addressbook container
|
||||
* @param string $searchstr The search query, case is ignored
|
||||
* @param array $rows Array of the found contacts
|
||||
*/
|
||||
public function searchContactsFolders($ab, $ab_dir, $searchstr, &$rows) {
|
||||
$abhtable = mapi_folder_gethierarchytable($ab_dir, MAPI_DEFERRED_ERRORS | CONVENIENT_DEPTH);
|
||||
$abcntfolders = mapi_table_queryallrows($abhtable, [PR_ENTRYID, PR_AB_PROVIDER_ID]);
|
||||
$restriction = [
|
||||
RES_CONTENT,
|
||||
[
|
||||
FUZZYLEVEL => FL_SUBSTRING | FL_IGNORECASE,
|
||||
ULPROPTAG => PR_DISPLAY_NAME,
|
||||
VALUE => [PR_DISPLAY_NAME => $searchstr],
|
||||
],
|
||||
];
|
||||
// restriction on hierarchy table for PR_AB_PROVIDER_ID
|
||||
// seems not to work, just loop through
|
||||
foreach ($abcntfolders as $abcntfolder) {
|
||||
if ($abcntfolder[PR_AB_PROVIDER_ID] == ZARAFA_CONTACTS_GUID) {
|
||||
$abfldentry = mapi_ab_openentry($ab, $abcntfolder[PR_ENTRYID]);
|
||||
$abfldcontents = mapi_folder_getcontentstable($abfldentry);
|
||||
mapi_table_restrict($abfldcontents, $restriction);
|
||||
$r = mapi_table_queryallrows($abfldcontents, [PR_ACCOUNT, PR_ADDRTYPE, PR_DISPLAY_NAME, PR_ENTRYID,
|
||||
PR_SEARCH_KEY, PR_OBJECT_TYPE, PR_SMTP_ADDRESS, PR_DISPLAY_TYPE_EX, PR_EMAIL_ADDRESS,
|
||||
PR_OBJECT_TYPE, PR_DISPLAY_TYPE]);
|
||||
if (is_array($r) && !empty($r)) {
|
||||
$rows = array_merge($rows, $r);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+404
@@ -0,0 +1,404 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* SPDX-FileCopyrightText: Copyright 2020 - 2026 grommunio GmbH
|
||||
* SPDX-FileCopyrightText: Copyright 2016 Kopano and its licensors
|
||||
* SPDX-FileCopyrightText: Copyright 2005 - 2016 Zarafa B.V. and its licensors
|
||||
* SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
*/
|
||||
|
||||
/**
|
||||
* RestoreItemsList Module.
|
||||
*/
|
||||
class RestoreItemsListModule extends ListModule {
|
||||
/**
|
||||
* Constructor.
|
||||
*
|
||||
* @param int $id unique id
|
||||
* @param array $data list of all actions
|
||||
*/
|
||||
public function __construct($id, $data) {
|
||||
parent::__construct($id, $data);
|
||||
|
||||
$this->properties = $GLOBALS['properties']->getRestoreItemListProperties();
|
||||
}
|
||||
|
||||
/**
|
||||
* Executes all the actions in the $data variable.
|
||||
*/
|
||||
#[Override]
|
||||
public function execute() {
|
||||
foreach ($this->data as $actionType => $action) {
|
||||
if (isset($actionType)) {
|
||||
try {
|
||||
if (!is_array($action)) {
|
||||
throw new MAPIException(_("Could not process request data properly."), MAPI_E_INVALID_PARAMETER);
|
||||
}
|
||||
$store = $this->getActionStore($action);
|
||||
$parententryid = $this->getActionParentEntryID($action);
|
||||
$folderentryid = $this->getActionSingleEntryID($action);
|
||||
if ($store === false || is_array($store)) {
|
||||
throw new MAPIException(_("Could not process request data properly."), MAPI_E_INVALID_PARAMETER);
|
||||
}
|
||||
|
||||
switch ($actionType) {
|
||||
case "list":
|
||||
case "updatelist":
|
||||
if (!is_string($folderentryid)) {
|
||||
throw new MAPIException(_("Could not process request data properly."), MAPI_E_INVALID_PARAMETER);
|
||||
}
|
||||
if (isset($action["message_action"])) {
|
||||
if (!is_string($action["message_action"]["action_type"] ?? null)) {
|
||||
throw new MAPIException(_("Could not process request data properly."), MAPI_E_INVALID_PARAMETER);
|
||||
}
|
||||
$subActionType = $action["message_action"]["action_type"];
|
||||
|
||||
switch ($subActionType) {
|
||||
case "restoreAll":
|
||||
$this->restoreAll($store, $folderentryid, $action);
|
||||
break;
|
||||
|
||||
case "deleteAll":
|
||||
$this->deleteAll($store, $folderentryid, $action);
|
||||
break;
|
||||
}
|
||||
}
|
||||
else {
|
||||
$this->itemList($store, $folderentryid, $action);
|
||||
}
|
||||
break;
|
||||
|
||||
case "delete":
|
||||
if ($parententryid === false || !is_string($action["message_action"]["action_type"] ?? null)) {
|
||||
throw new MAPIException(_("Could not process request data properly."), MAPI_E_INVALID_PARAMETER);
|
||||
}
|
||||
$itemType = $action["message_action"]["action_type"];
|
||||
|
||||
switch ($itemType) {
|
||||
case "restorefolder":
|
||||
if (!is_string($folderentryid)) {
|
||||
throw new MAPIException(_("Could not process request data properly."), MAPI_E_INVALID_PARAMETER);
|
||||
}
|
||||
$this->restoreFolder($store, $parententryid, $folderentryid);
|
||||
break;
|
||||
|
||||
case "deletefolder":
|
||||
$this->deleteFolder($store, $parententryid, $action);
|
||||
break;
|
||||
|
||||
case "restoremessage":
|
||||
$this->restoreItems($store, $parententryid, $action);
|
||||
break;
|
||||
|
||||
case "deletemessage":
|
||||
$this->deleteItems($store, $parententryid, $action);
|
||||
break;
|
||||
|
||||
default:
|
||||
$this->handleUnknownActionType($itemType);
|
||||
}
|
||||
break;
|
||||
|
||||
default:
|
||||
$this->handleUnknownActionType($actionType);
|
||||
}
|
||||
}
|
||||
catch (MAPIException $e) {
|
||||
$this->processException($e, $actionType);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Function which permanently delete all folder or message items.
|
||||
*
|
||||
* @param resource $store MAPI message store
|
||||
* @param string $folderentryid entry ID of the target folder
|
||||
* @param array $action action data sent by the client
|
||||
*/
|
||||
public function deleteAll($store, $folderentryid, $action) {
|
||||
$folder = mapi_msgstore_openentry($store, $folderentryid);
|
||||
|
||||
// delete all folders.
|
||||
if (isset($action["itemType"]) && $action["itemType"] == "folder") {
|
||||
$table = mapi_folder_gethierarchytable($folder, MAPI_DEFERRED_ERRORS | SHOW_SOFT_DELETES);
|
||||
$restoreItems = array_column(mapi_table_queryallrows($table, [PR_ENTRYID]), PR_ENTRYID);
|
||||
foreach ($restoreItems as $restoreItem) {
|
||||
mapi_folder_deletefolder($folder, $restoreItem, DEL_FOLDERS | DEL_MESSAGES | DELETE_HARD_DELETE);
|
||||
}
|
||||
}
|
||||
else {
|
||||
// delete all messages
|
||||
$table = mapi_folder_getcontentstable($folder, MAPI_DEFERRED_ERRORS | SHOW_SOFT_DELETES);
|
||||
$restoreItems = array_column(mapi_table_queryallrows($table, [PR_ENTRYID]), PR_ENTRYID);
|
||||
mapi_folder_deletemessages($folder, $restoreItems, DELETE_HARD_DELETE);
|
||||
}
|
||||
|
||||
$this->addActionData("list", ["item" => []]);
|
||||
$GLOBALS["bus"]->addData($this->getResponseData());
|
||||
}
|
||||
|
||||
/**
|
||||
* Function used to restore all folders.
|
||||
*
|
||||
* @param resource $store MAPI message store
|
||||
* @param resource $folder folder whose contents need to be restored
|
||||
*
|
||||
* @throws MAPIException
|
||||
*/
|
||||
public function restoreAllFolders($store, $folder) {
|
||||
$table = mapi_folder_gethierarchytable($folder, MAPI_DEFERRED_ERRORS | SHOW_SOFT_DELETES);
|
||||
$rows = mapi_table_queryallrows($table, [PR_ENTRYID, PR_DISPLAY_NAME]);
|
||||
|
||||
foreach ($rows as $row) {
|
||||
$restoreItem = $row[PR_ENTRYID];
|
||||
$name = $row[PR_DISPLAY_NAME] ?? '';
|
||||
|
||||
// a move within the parent only renames, so copy and hard-delete the source
|
||||
try {
|
||||
mapi_folder_copyfolder($folder, $restoreItem, $folder, $name);
|
||||
}
|
||||
catch (MAPIException $e) {
|
||||
if ($e->getCode() != MAPI_E_COLLISION) {
|
||||
throw $e;
|
||||
}
|
||||
$name = $GLOBALS["operations"]->checkFolderNameConflict($store, $folder, $name);
|
||||
mapi_folder_copyfolder($folder, $restoreItem, $folder, $name);
|
||||
}
|
||||
mapi_folder_deletefolder($folder, $restoreItem, DEL_MESSAGES | DEL_FOLDERS | DELETE_HARD_DELETE);
|
||||
}
|
||||
|
||||
// Notify the parent folder.
|
||||
$this->notifyParentFolder($store, $folder, $folder);
|
||||
}
|
||||
|
||||
/**
|
||||
* Restore every message in the given folder.
|
||||
*
|
||||
* @param resource $folder folder whose contents need to be restored
|
||||
*/
|
||||
public function restoreAllItems($folder) {
|
||||
$table = mapi_folder_getcontentstable($folder, MAPI_DEFERRED_ERRORS | SHOW_SOFT_DELETES);
|
||||
$restoreItems = array_column(mapi_table_queryallrows($table, [PR_ENTRYID]), PR_ENTRYID);
|
||||
|
||||
mapi_folder_copymessages($folder, $restoreItems, $folder, MESSAGE_MOVE);
|
||||
|
||||
// as after moving the message/s the entryid gets changed, so need to notify about the folder
|
||||
// so that we can update the folder on parent page.
|
||||
$folderProps = mapi_getprops($folder, [PR_STORE_ENTRYID, PR_ENTRYID]);
|
||||
|
||||
/* when we restore any message from soft deleted system then we are actually copying the item, so at that time entryid of
|
||||
* that particular item gets changed, so to notify client about changes we need to
|
||||
* notify parent folder where we have restored the message
|
||||
*/
|
||||
$props = [];
|
||||
$props[PR_PARENT_ENTRYID] = $folderProps[PR_ENTRYID];
|
||||
$props[PR_STORE_ENTRYID] = $folderProps[PR_STORE_ENTRYID];
|
||||
|
||||
$GLOBALS["bus"]->notify(bin2hex((string) $folderProps[PR_ENTRYID]), TABLE_SAVE, $props);
|
||||
}
|
||||
|
||||
/**
|
||||
* Restore all folders or messages according to the requested item type.
|
||||
*
|
||||
* @param resource $store MAPI message store
|
||||
* @param string $folderentryid entry ID of the target folder
|
||||
* @param array $action action data sent by the client
|
||||
*
|
||||
* @throws MAPIException
|
||||
*/
|
||||
public function restoreAll($store, $folderentryid, $action) {
|
||||
$folder = mapi_msgstore_openentry($store, $folderentryid);
|
||||
|
||||
if (isset($action["itemType"]) && $action["itemType"] == "folder") {
|
||||
$this->restoreAllFolders($store, $folder);
|
||||
}
|
||||
else {
|
||||
$this->restoreAllItems($folder);
|
||||
}
|
||||
|
||||
$this->addActionData("list", ["item" => []]);
|
||||
$GLOBALS["bus"]->addData($this->getResponseData());
|
||||
}
|
||||
|
||||
/**
|
||||
* Function to retrieve the list of messages or folder of particular folder.
|
||||
*
|
||||
* @param resource $store MAPI message store
|
||||
* @param string $entryid entry ID of the folder
|
||||
* @param array $action request data
|
||||
*/
|
||||
public function itemList($store, $entryid, $action) {
|
||||
// Restriction
|
||||
$this->parseRestriction($action);
|
||||
|
||||
// set the this->$sort variable.
|
||||
$this->parseSortOrder($action);
|
||||
|
||||
$limit = $action['restriction']['limit'] ?? $GLOBALS['settings']->get('grommunio/v1/main/page_size', 50);
|
||||
|
||||
$getHierarchy = isset($action["itemType"]) && $action["itemType"] == "folder";
|
||||
|
||||
$data = $GLOBALS["operations"]->getTable(
|
||||
$store,
|
||||
$entryid,
|
||||
$this->properties,
|
||||
$this->sort,
|
||||
$this->start,
|
||||
$limit,
|
||||
$this->restriction,
|
||||
$getHierarchy,
|
||||
MAPI_DEFERRED_ERRORS | SHOW_SOFT_DELETES
|
||||
);
|
||||
|
||||
$this->addActionData("list", $data);
|
||||
$GLOBALS["bus"]->addData($this->getResponseData());
|
||||
}
|
||||
|
||||
/**
|
||||
* Function to delete selected items of particular folder.
|
||||
*
|
||||
* @param resource $store MAPI message store
|
||||
* @param string $parententryid entry ID of the folder containing the item to delete
|
||||
* @param array $items items to delete
|
||||
*/
|
||||
public function deleteItems($store, $parententryid, $items) {
|
||||
if (is_assoc_array($items)) {
|
||||
// wrap single item in an array
|
||||
$items = [$items];
|
||||
}
|
||||
|
||||
$sfolder = mapi_msgstore_openentry($store, $parententryid);
|
||||
|
||||
for ($index = 0, $len = count($items); $index < $len; ++$index) {
|
||||
mapi_folder_deletemessages($sfolder, [hex2bin((string) $items[$index]['entryid'])], DELETE_HARD_DELETE);
|
||||
}
|
||||
$this->sendFeedback(true);
|
||||
}
|
||||
|
||||
/**
|
||||
* Function to restore message present into the selected folder.
|
||||
*
|
||||
* @param resource $store MAPI message store
|
||||
* @param string $parententryid entry ID of the folder containing the item to restore
|
||||
* @param array $items items to restore
|
||||
*/
|
||||
public function restoreItems($store, $parententryid, $items) {
|
||||
if (is_assoc_array($items)) {
|
||||
// wrap single item in an array
|
||||
$items = [$items];
|
||||
}
|
||||
|
||||
$sfolder = mapi_msgstore_openentry($store, $parententryid);
|
||||
|
||||
for ($index = 0, $len = count($items); $index < $len; ++$index) {
|
||||
mapi_folder_copymessages($sfolder, [hex2bin((string) $items[$index]['entryid'])], $sfolder, MESSAGE_MOVE);
|
||||
}
|
||||
|
||||
// as after moving the message/s the entryid gets changed, so need to notify about the folder
|
||||
// so that we can update the folder on parent page.
|
||||
$folderProps = mapi_getprops($sfolder, [PR_STORE_ENTRYID, PR_ENTRYID]);
|
||||
|
||||
/* when we restore any message from soft deleted system then we are actually copying the item, so at that time entryid of
|
||||
* that particular item gets changed, so to notify client about changes we need to
|
||||
* notify parent folder where we have restored the message
|
||||
*/
|
||||
$props = [];
|
||||
$props[PR_PARENT_ENTRYID] = $folderProps[PR_ENTRYID];
|
||||
$props[PR_STORE_ENTRYID] = $folderProps[PR_STORE_ENTRYID];
|
||||
$GLOBALS["bus"]->notify(bin2hex((string) $folderProps[PR_ENTRYID]), TABLE_SAVE, $props);
|
||||
$this->sendFeedback(true);
|
||||
}
|
||||
|
||||
/**
|
||||
* Function to delete selected folders.
|
||||
*
|
||||
* @param resource $store MAPI message store
|
||||
* @param string $parententryid entry ID of the parent folder
|
||||
* @param array $folders folders to delete
|
||||
*/
|
||||
public function deleteFolder($store, $parententryid, $folders) {
|
||||
if (is_assoc_array($folders)) {
|
||||
// wrap single folder in an array
|
||||
$folders = [$folders];
|
||||
}
|
||||
|
||||
$sfolder = mapi_msgstore_openentry($store, $parententryid);
|
||||
|
||||
for ($index = 0, $len = count($folders); $index < $len; ++$index) {
|
||||
mapi_folder_deletefolder($sfolder, hex2bin((string) $folders[$index]['entryid']), DEL_FOLDERS | DEL_MESSAGES | DELETE_HARD_DELETE);
|
||||
}
|
||||
|
||||
$this->sendFeedback(true);
|
||||
}
|
||||
|
||||
/**
|
||||
* Function to restore soft deleted folder of particular folder. The folder
|
||||
* restore action involves two operations: copy the folder marked as deleted
|
||||
* as a new one and then delete the source folder.
|
||||
*
|
||||
* @param resource $store MAPI message store
|
||||
* @param string $parententryid entry ID of the parent folder
|
||||
* @param string $folderentryid entry ID of the folder to restore
|
||||
*/
|
||||
public function restoreFolder($store, $parententryid, $folderentryid) {
|
||||
$sfolder = mapi_msgstore_openentry($store, $parententryid);
|
||||
$folder = mapi_msgstore_openentry($store, $folderentryid, SHOW_SOFT_DELETES);
|
||||
$folderNameProps = mapi_getprops($folder, [PR_DISPLAY_NAME]);
|
||||
|
||||
try {
|
||||
/*
|
||||
* We should first try to copy folder and if it returns MAPI_E_COLLISION then
|
||||
* only we should check for the conflicting folder names and generate a new name
|
||||
* and restore folder with the generated name.
|
||||
*/
|
||||
mapi_folder_copyfolder($sfolder, $folderentryid, $sfolder, $folderNameProps[PR_DISPLAY_NAME]);
|
||||
}
|
||||
catch (MAPIException $e) {
|
||||
if ($e->getCode() == MAPI_E_COLLISION) {
|
||||
$foldername = $GLOBALS["operations"]->checkFolderNameConflict($store, $sfolder, $folderNameProps[PR_DISPLAY_NAME]);
|
||||
mapi_folder_copyfolder($sfolder, $folderentryid, $sfolder, $foldername);
|
||||
}
|
||||
else {
|
||||
// all other errors should be propagated to higher level exception handlers
|
||||
throw $e;
|
||||
}
|
||||
}
|
||||
|
||||
// Reaching this point means the folder was copied successfully.
|
||||
mapi_folder_deletefolder($sfolder, $folderentryid, DEL_MESSAGES | DEL_FOLDERS | DELETE_HARD_DELETE);
|
||||
|
||||
// notify the parent folder
|
||||
$parentFolder = mapi_msgstore_openentry($store, $parententryid);
|
||||
$this->notifyParentFolder($store, $sfolder, $parentFolder);
|
||||
$this->sendFeedback(true);
|
||||
}
|
||||
|
||||
/**
|
||||
* Notify the parent folder about restoration.
|
||||
*
|
||||
* @param resource $store MAPI message store
|
||||
* @param resource $folder folder containing the restored folder
|
||||
* @param resource $parentFolder folder to notify
|
||||
*/
|
||||
public function notifyParentFolder($store, $folder, $parentFolder) {
|
||||
/* when we restore any folder from soft deleted system then we are actually copying the folder, so at that time entryid of
|
||||
* folder gets changed and we don't have notification system to get new entryid, so to notify client about changes we need to
|
||||
* notify all subfolders of parent folder where we have restored the folder
|
||||
*/
|
||||
$hierarchyTable = mapi_folder_gethierarchytable($folder, CONVENIENT_DEPTH | MAPI_DEFERRED_ERRORS);
|
||||
mapi_table_sort($hierarchyTable, [PR_DISPLAY_NAME => TABLE_SORT_ASCEND], TBL_BATCH);
|
||||
|
||||
$subfolders = mapi_table_queryallrows($hierarchyTable, [PR_ENTRYID]);
|
||||
|
||||
foreach ($subfolders as $subfolder) {
|
||||
$folderObject = mapi_msgstore_openentry($store, $subfolder[PR_ENTRYID]);
|
||||
$folderProps = mapi_getprops($folderObject, [PR_ENTRYID, PR_STORE_ENTRYID]);
|
||||
$GLOBALS["bus"]->notify(bin2hex((string) $subfolder[PR_ENTRYID]), OBJECT_SAVE, $folderProps);
|
||||
}
|
||||
|
||||
$folderProps = mapi_getprops($parentFolder, [PR_ENTRYID, PR_STORE_ENTRYID]);
|
||||
$GLOBALS["bus"]->notify(bin2hex((string) $folderProps[PR_ENTRYID]), OBJECT_SAVE, $folderProps);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,372 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* SPDX-FileCopyrightText: Copyright 2020 - 2026 grommunio GmbH
|
||||
* SPDX-FileCopyrightText: Copyright 2016 Kopano and its licensors
|
||||
* SPDX-FileCopyrightText: Copyright 2005 - 2016 Zarafa B.V. and its licensors
|
||||
* SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
*/
|
||||
|
||||
/**
|
||||
* Rules Module
|
||||
* Module will be used to save rules information to rules table.
|
||||
*/
|
||||
class RulesModule extends Module {
|
||||
/**
|
||||
* @var resource rules modification table
|
||||
*/
|
||||
private $rulesFolder;
|
||||
|
||||
/**
|
||||
* Constructor.
|
||||
*
|
||||
* @param int $id unique id
|
||||
* @param array $data list of all actions
|
||||
*/
|
||||
public function __construct($id, $data) {
|
||||
$this->properties = $GLOBALS['properties']->getRulesProperties();
|
||||
$this->rulesFolder = null;
|
||||
|
||||
parent::__construct($id, $data);
|
||||
}
|
||||
|
||||
/**
|
||||
* Executes all the actions in the $data variable.
|
||||
*/
|
||||
#[Override]
|
||||
public function execute() {
|
||||
$locks = [];
|
||||
foreach ($this->storeEntryIds() as $storeEntryId) {
|
||||
$lock = new State('rules-write', 'store_' . hash('sha256', $storeEntryId));
|
||||
if (!$lock->open()) {
|
||||
throw new RuntimeException('Unable to lock the mail filters');
|
||||
}
|
||||
$locks[] = $lock;
|
||||
}
|
||||
|
||||
try {
|
||||
$this->executeLocked();
|
||||
}
|
||||
finally {
|
||||
foreach (array_reverse($locks) as $lock) {
|
||||
$lock->close();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Sorted hex entryids of the stores addressed by this request.
|
||||
*/
|
||||
private function storeEntryIds() {
|
||||
$ids = [];
|
||||
foreach ($this->data as $action) {
|
||||
if (!isset($action[0]) && isset($action['props'])) {
|
||||
$action = [$action];
|
||||
}
|
||||
$id = isset($action[0]) ? ($action[0]['message_action']['store_entryid'] ?? null) : ($action['store_entryid'] ?? null);
|
||||
if (is_string($id) && $id !== '') {
|
||||
$ids[strtolower($id)] = strtolower($id);
|
||||
}
|
||||
}
|
||||
sort($ids);
|
||||
|
||||
return $ids;
|
||||
}
|
||||
|
||||
private function executeLocked() {
|
||||
foreach ($this->data as $actionType => $action) {
|
||||
// The client proxy may send rule data as an indexed array
|
||||
// (multiple rules) or as a single associative array (one
|
||||
// rule, unwrapped by ExtJS). Normalize to indexed form so
|
||||
// the rest of the code can rely on $action[0].
|
||||
if (!isset($action[0]) && isset($action['props'])) {
|
||||
$action = [$action];
|
||||
}
|
||||
|
||||
if (isset($action[0])) {
|
||||
$storeEntryid = $action[0]['message_action']['store_entryid'];
|
||||
}
|
||||
else {
|
||||
$storeEntryid = $action['store_entryid'];
|
||||
}
|
||||
|
||||
$ownStoreEntryId = $GLOBALS['mapisession']->getDefaultMessageStoreEntryId();
|
||||
|
||||
try {
|
||||
if (ENABLE_SHARED_RULES !== true && !$GLOBALS['entryid']->compareEntryIds($storeEntryid, $ownStoreEntryId)) {
|
||||
// When the admin does not allow a user to set rules on the store of other users, but somehow
|
||||
// the user still tries this (probably hacking) we will not allow this
|
||||
throw new MAPIException(_('Setting mail filters on the stores of other users is not allowed.'));
|
||||
}
|
||||
$store = $GLOBALS['mapisession']->openMessageStore(hex2bin((string) $storeEntryid));
|
||||
|
||||
switch ($actionType) {
|
||||
case 'list':
|
||||
$rules = $this->getRules($store);
|
||||
$this->addActionData('list', $rules);
|
||||
$GLOBALS['bus']->addData($this->getResponseData());
|
||||
break;
|
||||
|
||||
case 'save':
|
||||
// When saving the rules, we expect _all_ rules
|
||||
// to have been send. So our first task, is to
|
||||
// delete all existing rules.
|
||||
$this->deleteRules($store);
|
||||
|
||||
// Now can save all rules, note that $action can contain just a store key when
|
||||
// all rules are removed.
|
||||
if (isset($action[0])) {
|
||||
$this->saveRules($store, $action);
|
||||
}
|
||||
|
||||
// delete (outlook) client rules
|
||||
$this->deleteOLClientRules($store);
|
||||
|
||||
// Respond with the full set of rules.
|
||||
$rules = $this->getRules($store);
|
||||
$this->addActionData('update', $rules);
|
||||
$GLOBALS['bus']->addData($this->getResponseData());
|
||||
break;
|
||||
|
||||
default:
|
||||
$this->handleUnknownActionType($actionType);
|
||||
}
|
||||
}
|
||||
catch (MAPIException $e) {
|
||||
$this->processException($e, $actionType);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public function getRulesFolder($store = false) {
|
||||
if ($store === false) {
|
||||
$store = $GLOBALS['mapisession']->getDefaultMessageStore();
|
||||
}
|
||||
if (!$this->rulesFolder) {
|
||||
$this->rulesFolder = mapi_msgstore_getreceivefolder($store);
|
||||
}
|
||||
|
||||
return $this->rulesFolder;
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a restriction to search for rules which have a rule provider
|
||||
* which starts with RuleOrganizer. Outlook will generate some rules
|
||||
* with PR_RULE_PROVIDER RuleOrganizer2 for client-only rules, however
|
||||
* we still want to show these in the client, hence we perform a prefix
|
||||
* search.
|
||||
*
|
||||
* @return array The restriction which should be applied to the RulesTable
|
||||
* to obtain all the rules which should be shown to the user
|
||||
*/
|
||||
public function getRestriction() {
|
||||
return [RES_CONTENT,
|
||||
[
|
||||
FUZZYLEVEL => FL_PREFIX | FL_IGNORECASE,
|
||||
ULPROPTAG => PR_RULE_PROVIDER,
|
||||
VALUE => [
|
||||
PR_RULE_PROVIDER => 'RuleOrganizer',
|
||||
],
|
||||
],
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all rules of a store.
|
||||
*
|
||||
* This function opens the rules table for the specified store, and reads
|
||||
* all rules with PR_RULE_PROVIDER equal to 'RuleOrganizer'. These are the rules
|
||||
* that the user sees when managing rules from Outlook.
|
||||
*
|
||||
* @param resource $store Store in which rules reside
|
||||
*
|
||||
* @return array rules data
|
||||
*/
|
||||
public function getRules($store) {
|
||||
$rules_folder = $this->getRulesFolder($store);
|
||||
$rulesTable = mapi_folder_getrulestable($rules_folder);
|
||||
|
||||
mapi_table_restrict($rulesTable, $this->getRestriction(), TBL_BATCH);
|
||||
mapi_table_sort($rulesTable, [PR_RULE_SEQUENCE => TABLE_SORT_ASCEND], TBL_BATCH);
|
||||
|
||||
$rows = mapi_table_queryallrows($rulesTable, $this->properties);
|
||||
|
||||
$rules = [];
|
||||
|
||||
foreach ($rows as &$row) {
|
||||
$rules[] = Conversion::mapMAPI2XML($this->properties, $row);
|
||||
}
|
||||
unset($row);
|
||||
|
||||
return ['item' => $rules];
|
||||
}
|
||||
|
||||
/**
|
||||
* Function used to delete all the rules the user currently has.
|
||||
*
|
||||
* @param resource $store in which we want to delete the rules
|
||||
*/
|
||||
public function deleteRules($store) {
|
||||
$rules_folder = $this->getRulesFolder($store);
|
||||
$rulesTable = mapi_folder_getrulestable($rules_folder);
|
||||
mapi_table_restrict($rulesTable, $this->getRestriction(), TBL_BATCH);
|
||||
mapi_table_sort($rulesTable, [PR_RULE_SEQUENCE => TABLE_SORT_ASCEND], TBL_BATCH);
|
||||
$rows = mapi_table_queryallrows($rulesTable, $this->properties);
|
||||
|
||||
$rules = [];
|
||||
|
||||
foreach ($rows as &$row) {
|
||||
$rules[] = [
|
||||
'rowflags' => ROW_REMOVE,
|
||||
'properties' => $row,
|
||||
];
|
||||
}
|
||||
|
||||
if (!empty($rules)) {
|
||||
mapi_folder_modifyrules($rules_folder, $rules);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Function will be used to create/update rule in user's rules table.
|
||||
* This function only usee ROW_MODIFY flag to save rules data, Which is correct when modifying existing rules
|
||||
* but for adding new rules Gromox automatically checks existence of rule id and if it si not then
|
||||
* use ROW_ADD flag.
|
||||
*
|
||||
* @param resource $store The store into which the rules must be saved
|
||||
* @param array $rulesData rules data that should be deleted
|
||||
*/
|
||||
public function saveRules($store, $rulesData) {
|
||||
if (is_assoc_array($rulesData)) {
|
||||
// wrap single rule in an array
|
||||
$rulesData = [$rulesData];
|
||||
}
|
||||
|
||||
// save rules in rules table
|
||||
$saveRules = [];
|
||||
for ($index = 0, $len = count($rulesData); $index < $len; ++$index) {
|
||||
$rule = $rulesData[$index];
|
||||
if (!empty($rule['props'])) {
|
||||
$rule += $rule['props'];
|
||||
}
|
||||
|
||||
$rule = Conversion::mapXML2MAPI($this->properties, $rule);
|
||||
|
||||
// Always reset the PR_RULE_ID property, it is going
|
||||
// to be regenerated by the server anyway, so we can safely
|
||||
// discard whatever value the client has given.
|
||||
$rule[PR_RULE_ID] = $index;
|
||||
|
||||
// provide default action and rule if client has not provided
|
||||
if (empty($rule[PR_RULE_ACTIONS])) {
|
||||
$rule[PR_RULE_ACTIONS] = [
|
||||
[
|
||||
'action' => OP_DEFER_ACTION,
|
||||
'dam' => hex2bin('E0C810000120000100000000000000010000000000000001000000360000000200FFFF00000C004352756C65456C656D656E7490010000010000000000000001000000018064000000010000000000000001000000'),
|
||||
],
|
||||
];
|
||||
}
|
||||
|
||||
if (empty($rule[PR_RULE_CONDITION])) {
|
||||
$rule[PR_RULE_CONDITION] = [
|
||||
RES_EXIST,
|
||||
[
|
||||
ULPROPTAG => PR_MESSAGE_CLASS,
|
||||
],
|
||||
];
|
||||
}
|
||||
|
||||
if (empty($rule[PR_RULE_NAME])) {
|
||||
$rule[PR_RULE_NAME] = _('Untitled rule');
|
||||
}
|
||||
|
||||
// generate rule provider data
|
||||
$rule[PR_RULE_PROVIDER_DATA] = pack('VVa*', 1, $rule[PR_RULE_ID], Conversion::UnixTimeToCOleDateTime(time()));
|
||||
|
||||
$saveRules[] = [
|
||||
'rowflags' => ROW_ADD,
|
||||
'properties' => $rule,
|
||||
];
|
||||
}
|
||||
|
||||
if (!empty($saveRules)) {
|
||||
mapi_folder_modifyrules($this->getRulesFolder($store), $saveRules);
|
||||
|
||||
$hresult = mapi_last_hresult();
|
||||
if ($hresult !== NOERROR) {
|
||||
throw new MAPIException(_('Could not save rules.'), $hresult);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Function will delete (outlook) client rules. Outlook maintains client rules
|
||||
* in associated table of inbox, When we create/delete/update rule from webapp
|
||||
* it won't match with outlook's client rules, so it will confuse outlook and
|
||||
* it will ask user to preserve whether client or server side rules, so every time
|
||||
* we save rules we need to remove this outlook generated client rule to remove
|
||||
* ambigiuty.
|
||||
*
|
||||
* @param resource $store (optional) current user's store
|
||||
*/
|
||||
public function deleteOLClientRules($store = false) {
|
||||
if ($store === false) {
|
||||
$store = $GLOBALS['mapisession']->getDefaultMessageStore();
|
||||
}
|
||||
|
||||
$inbox = mapi_msgstore_getreceivefolder($store);
|
||||
|
||||
// get inbox' associatedTable
|
||||
$associatedTable = mapi_folder_getcontentstable($inbox, MAPI_ASSOCIATED);
|
||||
|
||||
mapi_table_restrict(
|
||||
$associatedTable,
|
||||
[RES_CONTENT,
|
||||
[
|
||||
FUZZYLEVEL => FL_FULLSTRING | FL_IGNORECASE,
|
||||
ULPROPTAG => PR_MESSAGE_CLASS,
|
||||
VALUE => [
|
||||
PR_MESSAGE_CLASS => "IPM.RuleOrganizer",
|
||||
],
|
||||
],
|
||||
]
|
||||
);
|
||||
$messages = mapi_table_queryallrows($associatedTable, [PR_ENTRYID]);
|
||||
|
||||
$deleteMessages = [];
|
||||
for ($i = 0, $len = count($messages); $i < $len; ++$i) {
|
||||
array_push($deleteMessages, $messages[$i][PR_ENTRYID]);
|
||||
}
|
||||
|
||||
if (!empty($deleteMessages)) {
|
||||
mapi_folder_deletemessages($inbox, $deleteMessages);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Function does customization of MAPIException based on module data.
|
||||
* like, here it will generate display message based on actionType
|
||||
* for particular exception.
|
||||
*
|
||||
* @param object $e exception object
|
||||
* @param string $actionType the action type, sent by the client
|
||||
* @param resource $store MAPI store containing the message
|
||||
* @param string $parententryid parent entryid of the message
|
||||
* @param string $entryid entryid of the message/folder
|
||||
* @param array $action the action data, sent by the client
|
||||
*/
|
||||
#[Override]
|
||||
public function handleException(&$e, $actionType = null, $store = null, $parententryid = null, $entryid = null, $action = null) {
|
||||
if (is_null($e->displayMessage)) {
|
||||
switch ($actionType) {
|
||||
case 'list':
|
||||
$e->setDisplayMessage(_('Could not load rules.'));
|
||||
break;
|
||||
|
||||
case 'save':
|
||||
$e->setDisplayMessage(_('Could not save rules.'));
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,234 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* SPDX-FileCopyrightText: Copyright 2020 - 2026 grommunio GmbH
|
||||
* SPDX-FileCopyrightText: Copyright 2016 Kopano and its licensors
|
||||
* SPDX-FileCopyrightText: Copyright 2005 - 2016 Zarafa B.V. and its licensors
|
||||
* SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
*/
|
||||
|
||||
/**
|
||||
* Settings Module.
|
||||
*/
|
||||
class SettingsModule extends Module {
|
||||
private const FILES_ACCOUNT_SETTINGS = 'grommunio/v1/plugins/files/accounts';
|
||||
|
||||
/**
|
||||
* Constructor.
|
||||
*
|
||||
* @param int $id unique id
|
||||
* @param array $data list of all actions
|
||||
*/
|
||||
public function __construct($id, $data) {
|
||||
parent::__construct($id, $data);
|
||||
}
|
||||
|
||||
#[Override]
|
||||
protected function getExecutionLockName() {
|
||||
foreach ($this->data as $actionType => $action) {
|
||||
if ($actionType === 'set') {
|
||||
if ($this->settingsTouchFilesAccounts($action['setting'] ?? null, true)) {
|
||||
return 'files';
|
||||
}
|
||||
}
|
||||
elseif (($actionType === 'delete' || $actionType === 'reset') &&
|
||||
$this->settingsTouchFilesAccounts($action['setting'] ?? null, false)) {
|
||||
return 'files';
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check whether a settings action overlaps the Files account tree.
|
||||
*
|
||||
* @param mixed $settings
|
||||
* @param mixed $withValues
|
||||
*/
|
||||
private function settingsTouchFilesAccounts($settings, $withValues) {
|
||||
if ($withValues) {
|
||||
if (isset($settings['path'])) {
|
||||
$settings = [$settings];
|
||||
}
|
||||
if (!is_array($settings)) {
|
||||
return false;
|
||||
}
|
||||
$paths = [];
|
||||
foreach ($settings as $setting) {
|
||||
if (is_array($setting) && isset($setting['path']) && is_string($setting['path'])) {
|
||||
$paths[] = $setting['path'];
|
||||
}
|
||||
}
|
||||
}
|
||||
else {
|
||||
$paths = is_array($settings) ? $settings : [$settings];
|
||||
}
|
||||
|
||||
foreach ($paths as $path) {
|
||||
if (!is_string($path)) {
|
||||
continue;
|
||||
}
|
||||
$path = implode('/', array_values(array_filter(explode('/', $path), static fn ($key) => $key !== '')));
|
||||
if ($path === self::FILES_ACCOUNT_SETTINGS ||
|
||||
str_starts_with($path, self::FILES_ACCOUNT_SETTINGS . '/') ||
|
||||
str_starts_with(self::FILES_ACCOUNT_SETTINGS, $path . '/')) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Executes all the actions in the $data variable.
|
||||
*
|
||||
* All setting mutations (set, delete, reset) are applied first and
|
||||
* then flushed to the MAPI store in a single saveSettings() /
|
||||
* savePersistentSettings() call at the end, avoiding redundant
|
||||
* MAPI round-trips when multiple action types arrive in the same
|
||||
* HTTP request (e.g. a batched delete + set).
|
||||
*/
|
||||
#[Override]
|
||||
public function execute() {
|
||||
$needsSave = false;
|
||||
$needsPersistentSave = false;
|
||||
|
||||
foreach ($this->data as $actionType => $action) {
|
||||
if (isset($actionType)) {
|
||||
try {
|
||||
switch ($actionType) {
|
||||
case "retrieveAll":
|
||||
$this->retrieveAll($actionType);
|
||||
break;
|
||||
|
||||
case "set":
|
||||
if (isset($action["setting"])) {
|
||||
$this->set($action["setting"], false, false);
|
||||
$needsSave = true;
|
||||
}
|
||||
if (isset($action["persistentSetting"])) {
|
||||
$this->set($action["persistentSetting"], true, false);
|
||||
$needsPersistentSave = true;
|
||||
}
|
||||
break;
|
||||
|
||||
case "delete":
|
||||
case "reset":
|
||||
$renState = State::forStore('additional-ren-entryids-write');
|
||||
if (!$renState->open()) {
|
||||
throw new RuntimeException('Unable to lock additional folder entryids');
|
||||
}
|
||||
|
||||
try {
|
||||
$userStore = $GLOBALS['mapisession']->getDefaultMessageStore();
|
||||
$inbox = mapi_msgstore_getreceivefolder($userStore);
|
||||
mapi_deleteprops($inbox, [PR_ADDITIONAL_REN_ENTRYIDS_EX, PR_ADDITIONAL_REN_ENTRYIDS]);
|
||||
}
|
||||
finally {
|
||||
$renState->close();
|
||||
}
|
||||
$this->delete($action["setting"], false);
|
||||
$needsSave = true;
|
||||
break;
|
||||
|
||||
default:
|
||||
$this->handleUnknownActionType($actionType);
|
||||
}
|
||||
}
|
||||
catch (MAPIException|SettingsException $e) {
|
||||
$this->processException($e, $actionType);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Flush all accumulated mutations to the MAPI store in one go.
|
||||
if ($needsSave) {
|
||||
$GLOBALS['settings']->saveSettings();
|
||||
}
|
||||
if ($needsPersistentSave) {
|
||||
$GLOBALS['settings']->savePersistentSettings();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Function will retrieve all settings stored in PR_EC_WEBACCESS_SETTINGS_JSON property
|
||||
* if property is not defined then it will return generate SettingsException but silently ignores it.
|
||||
*
|
||||
* @param mixed $type
|
||||
*/
|
||||
public function retrieveAll($type) {
|
||||
$data = $GLOBALS['settings']->get();
|
||||
|
||||
$this->addActionData($type, $data);
|
||||
$GLOBALS["bus"]->addData($this->getResponseData());
|
||||
}
|
||||
|
||||
/**
|
||||
* Function will set a value of a setting indicated by path of the setting.
|
||||
*
|
||||
* @param mixed $settings Object containing a $path and $value of the setting
|
||||
* which must be modified
|
||||
* @param bool $persistent If true the settings will be stored in the persistent settings
|
||||
* as opposed to the normal settings
|
||||
* @param bool $save If true the settings will be saved to the MAPI store
|
||||
* immediately. Pass false to defer saving (caller is
|
||||
* responsible for calling saveSettings()).
|
||||
*/
|
||||
public function set($settings, $persistent = false, $save = true) {
|
||||
if (isset($settings)) {
|
||||
// we will set the settings but wait with saving until the entire batch has been applied.
|
||||
foreach (isset($settings['path']) ? [$settings] : (array) $settings as $setting) {
|
||||
if (isset($setting['path'], $setting['value'])) {
|
||||
if ((bool) $persistent) {
|
||||
$GLOBALS['settings']->setPersistent($setting['path'], $setting['value']);
|
||||
}
|
||||
else {
|
||||
$GLOBALS['settings']->set($setting['path'], $setting['value']);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if ($save) {
|
||||
// Save the settings to the MAPI store.
|
||||
if ((bool) $persistent) {
|
||||
$GLOBALS['settings']->savePersistentSettings();
|
||||
}
|
||||
else {
|
||||
$GLOBALS['settings']->saveSettings();
|
||||
}
|
||||
}
|
||||
|
||||
// send success notification to client
|
||||
$this->sendFeedback(true);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Function will delete a setting indicated by setting path.
|
||||
*
|
||||
* @param null|string|string[] $path path or paths of the settings to delete
|
||||
* @param bool $save whether to save the settings to the MAPI store immediately
|
||||
*/
|
||||
public function delete($path, $save = true) {
|
||||
if (isset($path)) {
|
||||
// we will delete the settings but wait with saving until the entire batch has been applied.
|
||||
if (is_array($path)) {
|
||||
foreach ($path as $item) {
|
||||
$GLOBALS['settings']->delete($item);
|
||||
}
|
||||
}
|
||||
else {
|
||||
$GLOBALS['settings']->delete($path);
|
||||
}
|
||||
|
||||
if ($save) {
|
||||
// Save the settings to the MAPI store.
|
||||
$GLOBALS['settings']->saveSettings();
|
||||
}
|
||||
|
||||
// send success notification to client
|
||||
$this->sendFeedback(true);
|
||||
}
|
||||
}
|
||||
}
|
||||
Loaded 100 of 1485 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user