mirror of
https://github.com/postfixadmin/postfixadmin.git
synced 2026-11-20 23:43:26 +03:00
Alias destinations absent from local records previously shared the misleading “maybe UNDELIVERABLE” indicator, including valid external addresses such as Gmail. The indicator now distinguishes “Check local destination” (red) from “External destination” (blue), with short explanatory tooltips. An alias with both kinds of destinations can show both indicators. thanks @TrapoSAMA
2625 lines
83 KiB
PHP
2625 lines
83 KiB
PHP
<?php
|
|
|
|
/**
|
|
* Common re-useable functions for PostfixAdmin.
|
|
* @license GPLv2 or later - see LICENSE.TXT and GPL-LICENSE.TXT
|
|
*/
|
|
|
|
$min_db_version = 1855; # update (at least) before a release with the latest function number in upgrade.php
|
|
|
|
|
|
/**
|
|
* Check if the user already provided a password but not the second factor
|
|
*/
|
|
function authentication_mfa_incomplete(): bool
|
|
{
|
|
if (isset($_SESSION['sessid'])) {
|
|
if (isset($_SESSION['sessid']['mfa_complete'])) {
|
|
if ($_SESSION['sessid']['mfa_complete'] == false) {
|
|
return true;
|
|
}
|
|
}
|
|
}
|
|
return false;
|
|
}
|
|
|
|
/**
|
|
* Action: Check if a session already exists, if not redirect to login.php. Returns current user's login.
|
|
*
|
|
* @param bool $requireMfaComplete - false only for login-mfa.php
|
|
* @return string username (e.g. foo@example.com) or CLI or SETUP.PHP
|
|
*/
|
|
function authentication_get_username(bool $requireMfaComplete = true)
|
|
{
|
|
if (defined('POSTFIXADMIN_CLI')) {
|
|
return 'CLI';
|
|
}
|
|
|
|
if (defined('POSTFIXADMIN_SETUP')) {
|
|
return 'SETUP.PHP';
|
|
}
|
|
|
|
if (!isset($_SESSION['sessid'])) {
|
|
header("Location: login.php");
|
|
exit(0);
|
|
}
|
|
|
|
/**
|
|
* when an mfa user logs in (username+password) but haven't yet done the MFA code, $_SESSION['sessid']['username'] will be populated
|
|
* but the user hasn't finished authentication, so we should not treat them as having logged in.
|
|
*/
|
|
if ($requireMfaComplete && authentication_mfa_incomplete()) {
|
|
header("Location: login-mfa.php");
|
|
exit(0);
|
|
}
|
|
|
|
return $_SESSION['sessid']['username'];
|
|
}
|
|
|
|
|
|
/**
|
|
*
|
|
* Used to determine whether a user has a particular role.
|
|
* @param string $role role-name. (E.g. admin, global-admin or user)
|
|
* @return boolean True if they have the requested role in their session.
|
|
* Note, user < admin < global-admin
|
|
*/
|
|
function authentication_has_role(string $role): bool
|
|
{
|
|
if (isset($_SESSION['sessid'])) {
|
|
if (isset($_SESSION['sessid']['roles'])) {
|
|
if (in_array($role, $_SESSION['sessid']['roles'])) {
|
|
return true;
|
|
}
|
|
}
|
|
}
|
|
return false;
|
|
}
|
|
|
|
/**
|
|
* Used to enforce that $user has a particular role when
|
|
* viewing a page.
|
|
* If they are lacking a role, redirect them to login.php
|
|
*
|
|
* Note, user < admin < global-admin
|
|
* @param string $role
|
|
* @return bool|no-return
|
|
*/
|
|
function authentication_require_role(string $role)
|
|
{
|
|
// redirect to appropriate page?
|
|
if (authentication_has_role($role)) {
|
|
return true;
|
|
}
|
|
|
|
header("Location: login.php");
|
|
exit(0);
|
|
}
|
|
|
|
|
|
/**
|
|
* Initialize a user or admin session
|
|
*
|
|
* @param string $username the user or admin name
|
|
* @param boolean $is_admin true if the user is an admin, false otherwise
|
|
* @return boolean true on success
|
|
*/
|
|
function init_session(string $username, bool $is_admin = false, bool $mfa_complete = false): bool
|
|
{
|
|
$status = session_regenerate_id(true);
|
|
$_SESSION['sessid'] = array();
|
|
$_SESSION['sessid']['roles'] = array();
|
|
$_SESSION['sessid']['mfa_complete'] = false;
|
|
|
|
if ($mfa_complete) {
|
|
$_SESSION['sessid']['roles'][] = $is_admin ? 'admin' : 'user';
|
|
$_SESSION['sessid']['mfa_complete'] = true;
|
|
}
|
|
|
|
$_SESSION['sessid']['username'] = $username;
|
|
|
|
return $status;
|
|
}
|
|
|
|
/**
|
|
* Add an error message for display on the next page that is rendered.
|
|
* @param string|array $string message(s) to show.
|
|
*
|
|
* Stores string in session. Flushed through header template.
|
|
* @return void
|
|
* @see _flash_string()
|
|
*/
|
|
function flash_error($string)
|
|
{
|
|
_flash_string('error', $string);
|
|
}
|
|
|
|
/**
|
|
* Used to display an info message on successful update.
|
|
* @param string|array $string message(s) to show.
|
|
* Stores data in session.
|
|
* @return void
|
|
* @see _flash_string()
|
|
*/
|
|
function flash_info($string)
|
|
{
|
|
_flash_string('info', $string);
|
|
}
|
|
|
|
/**
|
|
* 'Private' method used for flash_info() and flash_error().
|
|
* @param string $type
|
|
* @param array|string $string
|
|
* @retrn void
|
|
*/
|
|
function _flash_string($type, $string)
|
|
{
|
|
if (is_array($string)) {
|
|
foreach ($string as $singlestring) {
|
|
_flash_string($type, $singlestring);
|
|
}
|
|
return;
|
|
}
|
|
|
|
if (!isset($_SESSION['flash'])) {
|
|
$_SESSION['flash'] = array();
|
|
}
|
|
if (!isset($_SESSION['flash'][$type])) {
|
|
$_SESSION['flash'][$type] = array();
|
|
}
|
|
$_SESSION['flash'][$type][] = $string;
|
|
}
|
|
|
|
|
|
/**
|
|
* Action: returns a language selector dropdown with the browser (or cookie) language preselected
|
|
* @return string
|
|
*
|
|
*
|
|
*/
|
|
function language_selector()
|
|
{
|
|
$supported_languages = Languages::$SUPPORTED_LANGUAGES;
|
|
|
|
$current_lang = Languages::check_language();
|
|
|
|
$selector = '<select id="lang" name="lang" xml:lang="en" dir="ltr">';
|
|
|
|
foreach ($supported_languages as $lang => $lang_name) {
|
|
if ($lang == $current_lang) {
|
|
$selected = ' selected="selected"';
|
|
} else {
|
|
$selected = '';
|
|
}
|
|
$selector .= "<option value='$lang'$selected>$lang_name</option>";
|
|
}
|
|
$selector .= "</select>";
|
|
return $selector;
|
|
}
|
|
|
|
|
|
/**
|
|
* Checks if a domain is valid
|
|
* @param string $domain
|
|
* @return string empty if the domain is valid, otherwise string with the errormessage
|
|
*
|
|
* Note: This function can be configured to skip DNS checks for local domains
|
|
* by setting Config::bool('emailcheck_resolve_domain') to false.
|
|
*/
|
|
function check_domain($domain)
|
|
{
|
|
if (!preg_match('/^([-0-9A-Z]+\.)+' . '([-0-9A-Z]){1,13}$/i', ($domain))) {
|
|
$str = sprintf(Config::lang('pInvalidDomainRegex'), htmlentities($domain));
|
|
if (is_string($str)) {
|
|
return $str;
|
|
}
|
|
throw new \InvalidArgumentException("Could not sprintf().");
|
|
}
|
|
|
|
if (Config::bool('emailcheck_resolve_domain') && 'WINDOWS' != (strtoupper(substr(php_uname('s'), 0, 7)))) {
|
|
|
|
// Look for an AAAA, A, or MX record for the domain
|
|
|
|
if (function_exists('checkdnsrr')) {
|
|
$start = microtime(true); # check for slow nameservers, part 1
|
|
|
|
// Check for AAAA (IPv6), A, MX, or NS records
|
|
if (checkdnsrr($domain, 'AAAA') || checkdnsrr($domain, 'A') || checkdnsrr($domain, 'MX')) {
|
|
$retval = '';
|
|
} elseif (checkdnsrr($domain, 'NS')) {
|
|
error_log("DNS is not correctly configured for $domain to send or receive email");
|
|
$retval = '';
|
|
} else {
|
|
$retval = sprintf(Config::lang('pInvalidDomainDNS'), htmlentities($domain));
|
|
}
|
|
|
|
$end = microtime(true); # check for slow nameservers, part 2
|
|
$time_needed = $end - $start;
|
|
|
|
if ($time_needed > 2) {
|
|
error_log("Warning: slow nameserver - lookup for $domain took $time_needed seconds");
|
|
}
|
|
|
|
if (!is_string($retval)) {
|
|
throw new \InvalidArgumentException("could not sprintf()");
|
|
}
|
|
return $retval;
|
|
} else {
|
|
return 'emailcheck_resolve_domain is enabled, but function (checkdnsrr) missing!';
|
|
}
|
|
}
|
|
|
|
return '';
|
|
}
|
|
|
|
/**
|
|
* Checks if a domain is local
|
|
* @param string $domain
|
|
* @return string empty if the domain is valid, otherwise string with the errormessage
|
|
*/
|
|
function check_localaliasonly($domain)
|
|
{
|
|
// If emailcheck_localaliasonly is set to 'YES', disallow aliases to remote servers (but allow aliases on this server)
|
|
if (Config::bool('emailcheck_localaliasonly')) {
|
|
// get the domain part of the e-mail
|
|
list(/*NULL*/, $domain) = explode('@', $domain);
|
|
|
|
// get all domains managed on this system by postfixadmin
|
|
$domains = list_domains();
|
|
|
|
// Only allow local domains to be alias destinations
|
|
if (in_array($domain, $domains)) {
|
|
return '';
|
|
} else {
|
|
// FIXME: Add transaltions
|
|
return sprintf("You may only make aliases to domains hosted on this server. %s is a remote domain name.", htmlentities($domain));
|
|
}
|
|
} else {
|
|
return '';
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Get password expiration value for a domain
|
|
* @param string $domain - a string that may be a domain
|
|
* @return int password expiration value for this domain (DAYS, or zero if not enabled)
|
|
*/
|
|
function get_password_expiration_value(string $domain)
|
|
{
|
|
$table_domain = table_by_key('domain');
|
|
$query = "SELECT password_expiry FROM $table_domain WHERE domain= :domain";
|
|
|
|
$result = db_query_one($query, array('domain' => $domain));
|
|
if (is_array($result) && isset($result['password_expiry'])) {
|
|
return $result['password_expiry'];
|
|
}
|
|
return 0;
|
|
}
|
|
|
|
const PASSWORD_EXPIRATION_MAX_DAYS = 36500;
|
|
const PASSWORD_EXPIRATION_NEVER = '9999-12-31 23:59:59';
|
|
|
|
/**
|
|
* Check whether a stored mailbox expiry represents a non-expiring password.
|
|
*
|
|
* A zero or invalid domain policy disables expiration. The sentinel also
|
|
* remains authoritative when a later domain policy change is non-retroactive.
|
|
*/
|
|
function mailbox_password_expiration_is_never($mailbox_expiry, $domain_policy): bool
|
|
{
|
|
$policy = (string)$domain_policy;
|
|
if (!preg_match('/^[1-9][0-9]*$/D', $policy) || (int)$policy > PASSWORD_EXPIRATION_MAX_DAYS) {
|
|
return true;
|
|
}
|
|
|
|
$expiry = strtotime((string)$mailbox_expiry);
|
|
$never = strtotime(PASSWORD_EXPIRATION_NEVER);
|
|
|
|
return $expiry !== false && $never !== false && $expiry >= $never;
|
|
}
|
|
|
|
/**
|
|
* Return the mailbox expiry timestamp for a password changed now.
|
|
*
|
|
* A domain value of 0 means that passwords do not expire. The database still
|
|
* requires a timestamp, so use the latest portable DATETIME value as a
|
|
* sentinel. The same applies when password expiration is disabled globally.
|
|
*/
|
|
function get_mailbox_password_expiry(string $domain, ?int $now = null): string
|
|
{
|
|
if (!Config::bool('password_expiration')) {
|
|
return PASSWORD_EXPIRATION_NEVER;
|
|
}
|
|
|
|
$value = get_password_expiration_value($domain);
|
|
$value_string = (string)$value;
|
|
|
|
if (!preg_match('/^(0|[1-9][0-9]*)$/D', $value_string)) {
|
|
error_log("Invalid password_expiry value for domain $domain; treating it as no expiration");
|
|
return PASSWORD_EXPIRATION_NEVER;
|
|
}
|
|
|
|
$days = (int)$value_string;
|
|
if ($days === 0) {
|
|
return PASSWORD_EXPIRATION_NEVER;
|
|
}
|
|
|
|
if ($days > PASSWORD_EXPIRATION_MAX_DAYS) {
|
|
error_log("password_expiry value for domain $domain exceeds the supported maximum; treating it as no expiration");
|
|
return PASSWORD_EXPIRATION_NEVER;
|
|
}
|
|
|
|
$base = $now ?? time();
|
|
$expiry = strtotime("+$days days", $base);
|
|
if ($expiry === false) {
|
|
throw new RuntimeException("Unable to calculate password expiry for domain $domain");
|
|
}
|
|
|
|
return date('Y-m-d H:i', $expiry);
|
|
}
|
|
|
|
/**
|
|
* check_email
|
|
* Checks if an email is valid - if it is, return true, else false.
|
|
* @param string $email - a string that may be an email address.
|
|
* @return string empty if it's a valid email address, otherwise string with the errormessage
|
|
*
|
|
* Note: This function validates the email format and checks if the domain part
|
|
* is valid using check_domain(). If the system is configured to support vacations (Config['vacation']) then we'll also support vacation style addresses too.
|
|
*
|
|
* @see check_domain()
|
|
*/
|
|
function check_email(string $email): string
|
|
{
|
|
$ce_email = $email;
|
|
|
|
//strip the vacation domain out if we are using it
|
|
//and change from blah#foo.com@autoreply.foo.com to blah@foo.com
|
|
if (Config::bool('vacation')) {
|
|
$vacation_domain = Config::read_string('vacation_domain');
|
|
$ce_email = preg_replace("/@$vacation_domain\$/", '', $ce_email);
|
|
$ce_email = preg_replace("/#/", '@', $ce_email);
|
|
}
|
|
|
|
// Perform non-domain-part sanity checks
|
|
if (!preg_match('/^[-!#$%&\'*+\\.\/0-9=?A-Z^_{|}~]+' . '@' . '[^@]+$/i', $ce_email)) {
|
|
return "" . Config::lang_f('pInvalidMailRegex', $email);
|
|
}
|
|
|
|
if (function_exists('filter_var')) {
|
|
$check = filter_var($email, FILTER_VALIDATE_EMAIL);
|
|
if (!$check) {
|
|
return "" . Config::lang_f('pInvalidMailRegex', $email);
|
|
}
|
|
}
|
|
// Determine domain name
|
|
$matches = array();
|
|
if (preg_match('|@(.+)$|', $ce_email, $matches)) {
|
|
$domain = $matches[1];
|
|
# check domain name
|
|
return "" . check_domain($domain);
|
|
}
|
|
|
|
return "" . Config::lang_f('pInvalidMailRegex', $email);
|
|
}
|
|
|
|
|
|
/**
|
|
* Clean a string, escaping any meta characters that could be
|
|
* used to disrupt an SQL string. The method of the escaping is dependent on the underlying DB
|
|
* and MAY NOT be just \' ing. (e.g. sqlite and PgSQL change "it's" to "it''s".
|
|
*
|
|
* The PDO quote function surrounds what you pass in with quote marks; for legacy reasons we remove these,
|
|
* but assume the caller will actually add them back in (!).
|
|
*
|
|
* e.g. caller code looks like :
|
|
*
|
|
* <code>
|
|
* $sql = "SELECT * FROM foo WHERE x = '" . escape_string('fish') . "'";
|
|
* </code>
|
|
*
|
|
* @param int|string $string_or_int parameters to escape
|
|
* @return string cleaned data, suitable for use within an SQL statement.
|
|
*/
|
|
function escape_string($string_or_int)
|
|
{
|
|
$link = db_connect();
|
|
$string_or_int = (string)$string_or_int;
|
|
$quoted = $link->quote($string_or_int);
|
|
return trim($quoted, "'");
|
|
}
|
|
|
|
|
|
/**
|
|
* safeget
|
|
* Action: get value from $_GET[$param], or $default if $_GET[$param] is not set
|
|
* Call: $param = safeget('param') # replaces $param = $_GET['param']
|
|
* - or -
|
|
* $param = safeget('param', 'default')
|
|
*
|
|
* @param string $param parameter name.
|
|
* @param string $default (optional) - default value if key is not set.
|
|
* @return string - can only return a string
|
|
*/
|
|
function safeget($param, $default = "")
|
|
{
|
|
$retval = $default;
|
|
if (isset($_GET[$param]) && is_string($_GET[$param])) {
|
|
$retval = $_GET[$param];
|
|
}
|
|
return $retval;
|
|
}
|
|
|
|
/**
|
|
* safepost - similar to safeget() but for $_POST
|
|
* @param string $param parameter name
|
|
* @param string $default (optional) default value (defaults to "")
|
|
* @return string - value in $_POST[$param] or $default - we do not support array like value(s) etc
|
|
* @see safeget()
|
|
*/
|
|
function safepost($param, $default = "")
|
|
{
|
|
$retval = $default;
|
|
if (isset($_POST[$param]) && is_string($_POST[$param])) {
|
|
$retval = $_POST[$param];
|
|
}
|
|
return $retval;
|
|
}
|
|
|
|
/**
|
|
* safecookie
|
|
* @param string $param parameter name
|
|
* @param string $default (optional) default value (defaults to "")
|
|
* @return string value from $_COOKIE[$param] or $default - we do not support array like value(s) etc
|
|
* @see safeget()
|
|
*/
|
|
function safecookie(string $param, $default = ""): string
|
|
{
|
|
$retval = $default;
|
|
if (isset($_COOKIE[$param])) {
|
|
$retval = $_COOKIE[$param];
|
|
}
|
|
return $retval;
|
|
}
|
|
|
|
/**
|
|
* safesession
|
|
* @param string $param
|
|
* @param string $default (optional)
|
|
* @return string value from $_SESSION[$param] or $default
|
|
* @see safeget()
|
|
*/
|
|
function safesession($param, $default = "")
|
|
{
|
|
$retval = $default;
|
|
if (isset($_SESSION[$param]) && is_string($_SESSION[$param])) {
|
|
$retval = $_SESSION[$param];
|
|
}
|
|
return $retval;
|
|
}
|
|
|
|
|
|
/**
|
|
* Action: Get all the properties of a domain.
|
|
* @param string $domain
|
|
* @return array
|
|
*/
|
|
function get_domain_properties($domain)
|
|
{
|
|
$handler = new DomainHandler();
|
|
if (!$handler->init($domain)) {
|
|
throw new Exception("Error: " . join("\n", $handler->errormsg));
|
|
}
|
|
|
|
if (!$handler->view()) {
|
|
throw new Exception("Error: " . join("\n", $handler->errormsg));
|
|
}
|
|
|
|
$result = $handler->result();
|
|
return $result;
|
|
}
|
|
|
|
|
|
/**
|
|
* create_page_browser
|
|
* Action: Get page browser for a long list of mailboxes, aliases etc.
|
|
*
|
|
* @param string $idxfield - database field name to use as title e.g. alias.address
|
|
* @param string $querypart - core part of the query (starting at "FROM") e.g. FROM alias WHERE address like ...
|
|
* @return array
|
|
*/
|
|
function create_page_browser($idxfield, $querypart, $sql_params = [])
|
|
{
|
|
global $CONF;
|
|
$page_size = (int)$CONF['page_size'];
|
|
$label_len = 2;
|
|
$pagebrowser = array();
|
|
|
|
$count_results = 0;
|
|
|
|
if ($page_size < 2) { # will break the page browser
|
|
throw new Exception('$CONF[\'page_size\'] must be 2 or more!');
|
|
}
|
|
|
|
# get number of rows
|
|
$query = "SELECT count(*) as counter FROM (SELECT $idxfield $querypart) AS tmp";
|
|
$result = db_query_one($query, $sql_params);
|
|
if ($result && isset($result['counter'])) {
|
|
$count_results = $result['counter'] - 1; # we start counting at 0, not 1
|
|
}
|
|
|
|
if ($count_results < $page_size) {
|
|
return array(); # only one page - no pagebrowser required
|
|
}
|
|
|
|
# init row counter
|
|
$initcount = "SET @r=-1";
|
|
if (db_pgsql()) {
|
|
$initcount = "CREATE TEMPORARY SEQUENCE rowcount MINVALUE 0";
|
|
}
|
|
if (!db_sqlite()) {
|
|
db_execute($initcount);
|
|
}
|
|
|
|
# get labels for relevant rows (first and last of each page)
|
|
$page_size_zerobase = $page_size - 1;
|
|
$query = "
|
|
SELECT * FROM (
|
|
SELECT $idxfield AS label, @r := @r + 1 AS 'r' $querypart
|
|
) idx WHERE MOD(idx.r, $page_size) IN (0,$page_size_zerobase) OR idx.r = $count_results
|
|
";
|
|
|
|
if (db_pgsql()) {
|
|
$query = "
|
|
SELECT * FROM (
|
|
SELECT $idxfield AS label, nextval('rowcount') AS r $querypart
|
|
) idx WHERE MOD(idx.r, $page_size) IN (0,$page_size_zerobase) OR idx.r = $count_results
|
|
";
|
|
}
|
|
|
|
if (db_sqlite()) {
|
|
$end = $idxfield;
|
|
if (strpos($idxfield, '.') !== false) {
|
|
$bits = explode('.', $idxfield);
|
|
$end = $bits[1];
|
|
}
|
|
$query = "
|
|
WITH idx AS (SELECT * $querypart)
|
|
SELECT $end AS label, (SELECT (COUNT(*) - 1) FROM idx t1 WHERE t1.$end <= t2.$end ) AS r
|
|
FROM idx t2
|
|
WHERE (r % $page_size) IN (0,$page_size_zerobase) OR r = $count_results";
|
|
}
|
|
|
|
# PostgreSQL:
|
|
# http://www.postgresql.org/docs/8.1/static/sql-createsequence.html
|
|
# http://www.postgresonline.com/journal/archives/79-Simulating-Row-Number-in-PostgreSQL-Pre-8.4.html
|
|
# http://www.pg-forum.de/sql/1518-nummerierung-der-abfrageergebnisse.html
|
|
# CREATE TEMPORARY SEQUENCE foo MINVALUE 0 MAXVALUE $page_size_zerobase CYCLE
|
|
# afterwards: DROP SEQUENCE foo
|
|
|
|
$result = db_query_all($query, $sql_params);
|
|
for ($k = 0; $k < count($result); $k += 2) {
|
|
if (isset($result[$k + 1])) {
|
|
$label = substr($result[$k]['label'], 0, $label_len) . '-' . substr($result[$k + 1]['label'], 0, $label_len);
|
|
} else {
|
|
$label = substr($result[$k]['label'], 0, $label_len);
|
|
}
|
|
$pagebrowser[] = $label;
|
|
}
|
|
|
|
if (db_pgsql()) {
|
|
db_execute("DROP SEQUENCE rowcount");
|
|
}
|
|
|
|
return $pagebrowser;
|
|
}
|
|
|
|
|
|
/**
|
|
* Recalculates the quota e.g. from MBs to bytes (divide, /), using config quota_multiplier
|
|
* @param int $quota
|
|
* @return float
|
|
*/
|
|
function divide_quota($quota)
|
|
{
|
|
if ($quota == -1) {
|
|
return $quota;
|
|
}
|
|
$value = round($quota / (int)Config::read_string('quota_multiplier'), 2);
|
|
return $value;
|
|
}
|
|
|
|
|
|
/**
|
|
* Checks if the admin is the owner of the domain (or global-admin)
|
|
*/
|
|
function check_owner(string $username, string $domain): bool
|
|
{
|
|
$table_domain_admins = table_by_key('domain_admins');
|
|
|
|
$result = db_query_all(
|
|
"SELECT 1 FROM $table_domain_admins WHERE username= ? AND (domain = ? OR domain = 'ALL') AND active = ?",
|
|
array($username, $domain, true)
|
|
);
|
|
|
|
if (sizeof($result) == 1 || sizeof($result) == 2) { # "ALL" + specific domain permissions is possible
|
|
# TODO: if superadmin, check if given domain exists in the database
|
|
return true;
|
|
} else {
|
|
if (sizeof($result) > 2) { # more than 2 results means something really strange happened...
|
|
flash_error("Permission check returned multiple results. Please go to 'edit admin' for your username and press the save "
|
|
. "button once to fix the database. If this doesn't help, open a bugreport.");
|
|
}
|
|
return false;
|
|
}
|
|
}
|
|
|
|
|
|
/**
|
|
* List domains for an admin user.
|
|
* @param string $username
|
|
* @return array of domain names.
|
|
*/
|
|
function list_domains_for_admin(string $username): array
|
|
{
|
|
$table_domain = table_by_key('domain');
|
|
$table_domain_admins = table_by_key('domain_admins');
|
|
|
|
$condition = [];
|
|
$pvalues = [];
|
|
|
|
$query = "SELECT $table_domain.domain FROM $table_domain ";
|
|
$condition[] = "$table_domain.domain != 'ALL'";
|
|
|
|
$result = db_query_one("SELECT username FROM $table_domain_admins WHERE username = :username AND domain = 'ALL'", ['username' => $username]);
|
|
if (empty($result)) { # not a superadmin
|
|
$pvalues['username'] = $username;
|
|
$pvalues['active'] = true;
|
|
$pvalues['backupmx'] = false;
|
|
|
|
$query .= " LEFT JOIN $table_domain_admins ON $table_domain.domain=$table_domain_admins.domain ";
|
|
$condition[] = "$table_domain_admins.username = :username ";
|
|
$condition[] = "$table_domain.active = :active "; # TODO: does it really make sense to exclude inactive...
|
|
$condition[] = "$table_domain.backupmx = :backupmx "; # TODO: ... and backupmx domains for non-superadmins?
|
|
}
|
|
|
|
$query .= " WHERE " . join(' AND ', $condition);
|
|
$query .= " ORDER BY $table_domain.domain";
|
|
|
|
$result = db_query_all($query, $pvalues);
|
|
return array_column($result, 'domain');
|
|
}
|
|
|
|
/**
|
|
* List all available domains.
|
|
*
|
|
* @return array
|
|
*/
|
|
function list_domains()
|
|
{
|
|
$list = array();
|
|
|
|
$table_domain = table_by_key('domain');
|
|
$result = db_query_all("SELECT domain FROM $table_domain WHERE domain!='ALL' ORDER BY domain");
|
|
$i = 0;
|
|
foreach ($result as $row) {
|
|
$list[$i] = $row['domain'];
|
|
$i++;
|
|
}
|
|
return $list;
|
|
}
|
|
|
|
|
|
//
|
|
// list_admins
|
|
// Action: Lists all the admins
|
|
// Call: list_admins ()
|
|
//
|
|
// was admin_list_admins
|
|
//
|
|
function list_admins()
|
|
{
|
|
$handler = new AdminHandler();
|
|
|
|
$handler->getList('');
|
|
|
|
return $handler->result();
|
|
}
|
|
|
|
|
|
//
|
|
// encode_header
|
|
// Action: Encode a string according to RFC 1522 for use in headers if it contains 8-bit characters.
|
|
// Call: encode_header (string header, string charset)
|
|
//
|
|
function encode_header($string, $default_charset = "utf-8")
|
|
{
|
|
if (strtolower($default_charset) == 'iso-8859-1') {
|
|
$string = str_replace("\240", ' ', $string);
|
|
}
|
|
|
|
$j = strlen($string);
|
|
$max_l = 75 - strlen($default_charset) - 7;
|
|
$aRet = array();
|
|
$ret = '';
|
|
$iEncStart = $enc_init = false;
|
|
$cur_l = $iOffset = 0;
|
|
|
|
for ($i = 0; $i < $j; ++$i) {
|
|
switch ($string[$i]) {
|
|
case '=':
|
|
case '<':
|
|
case '>':
|
|
case ',':
|
|
case '?':
|
|
case '_':
|
|
if ($iEncStart === false) {
|
|
$iEncStart = $i;
|
|
}
|
|
$cur_l += 3;
|
|
if ($cur_l > ($max_l - 2)) {
|
|
$aRet[] = substr($string, $iOffset, $iEncStart - $iOffset);
|
|
$aRet[] = "=?$default_charset?Q?$ret?=";
|
|
$iOffset = $i;
|
|
$cur_l = 0;
|
|
$ret = '';
|
|
$iEncStart = false;
|
|
} else {
|
|
$ret .= sprintf("=%02X", ord($string[$i]));
|
|
}
|
|
break;
|
|
case '(':
|
|
case ')':
|
|
if ($iEncStart !== false) {
|
|
$aRet[] = substr($string, $iOffset, $iEncStart - $iOffset);
|
|
$aRet[] = "=?$default_charset?Q?$ret?=";
|
|
$iOffset = $i;
|
|
$cur_l = 0;
|
|
$ret = '';
|
|
$iEncStart = false;
|
|
}
|
|
break;
|
|
case ' ':
|
|
if ($iEncStart !== false) {
|
|
$cur_l++;
|
|
if ($cur_l > $max_l) {
|
|
$aRet[] = substr($string, $iOffset, $iEncStart - $iOffset);
|
|
$aRet[] = "=?$default_charset?Q?$ret?=";
|
|
$iOffset = $i;
|
|
$cur_l = 0;
|
|
$ret = '';
|
|
$iEncStart = false;
|
|
} else {
|
|
$ret .= '_';
|
|
}
|
|
}
|
|
break;
|
|
default:
|
|
$k = ord($string[$i]);
|
|
if ($k > 126) {
|
|
if ($iEncStart === false) {
|
|
// do not start encoding in the middle of a string, also take the rest of the word.
|
|
$sLeadString = substr($string, 0, $i);
|
|
$aLeadString = explode(' ', $sLeadString);
|
|
$sToBeEncoded = array_pop($aLeadString);
|
|
$iEncStart = $i - strlen($sToBeEncoded);
|
|
$ret .= $sToBeEncoded;
|
|
$cur_l += strlen($sToBeEncoded);
|
|
}
|
|
$cur_l += 3;
|
|
// first we add the encoded string that reached it's max size
|
|
if ($cur_l > ($max_l - 2)) {
|
|
$aRet[] = substr($string, $iOffset, $iEncStart - $iOffset);
|
|
$aRet[] = "=?$default_charset?Q?$ret?= ";
|
|
$cur_l = 3;
|
|
$ret = '';
|
|
$iOffset = $i;
|
|
$iEncStart = $i;
|
|
}
|
|
$enc_init = true;
|
|
$ret .= sprintf("=%02X", $k);
|
|
} else {
|
|
if ($iEncStart !== false) {
|
|
$cur_l++;
|
|
if ($cur_l > $max_l) {
|
|
$aRet[] = substr($string, $iOffset, $iEncStart - $iOffset);
|
|
$aRet[] = "=?$default_charset?Q?$ret?=";
|
|
$iEncStart = false;
|
|
$iOffset = $i;
|
|
$cur_l = 0;
|
|
$ret = '';
|
|
} else {
|
|
$ret .= $string[$i];
|
|
}
|
|
}
|
|
}
|
|
break;
|
|
# end switch
|
|
}
|
|
}
|
|
if ($enc_init) {
|
|
if ($iEncStart !== false) {
|
|
$aRet[] = substr($string, $iOffset, $iEncStart - $iOffset);
|
|
$aRet[] = "=?$default_charset?Q?$ret?=";
|
|
} else {
|
|
$aRet[] = substr($string, $iOffset);
|
|
}
|
|
$string = implode('', $aRet);
|
|
}
|
|
return $string;
|
|
}
|
|
|
|
|
|
/**
|
|
* Generate a random password of $length characters.
|
|
* @param int $length (optional, default: 12)
|
|
* @return string
|
|
*/
|
|
function generate_password(int $length = 12): string
|
|
{
|
|
// define possible characters
|
|
$possible = "2345678923456789abcdefghijkmnpqrstuvwxyzABCDEFGHIJKLMNPQRSTUVWXYZ"; # skip 0 and 1 to avoid confusion with O and l
|
|
|
|
// add random characters to $password until $length is reached
|
|
$password = "";
|
|
|
|
// note this allows for repeated characters (better entropy)
|
|
for ($i = 0; $i < $length; $i++) {
|
|
$random = random_int(0, strlen($possible) - 1);
|
|
$password .= substr($possible, $random, 1);
|
|
}
|
|
|
|
return $password;
|
|
}
|
|
|
|
|
|
/**
|
|
* Check if a password is strong enough based on the conditions in $CONF['password_validation']
|
|
* @param string $password
|
|
* @return array of error messages, or empty array if the password is ok
|
|
*/
|
|
function validate_password(string $password): array
|
|
{
|
|
$result = array();
|
|
|
|
$config = Config::getInstance()->getAll();
|
|
|
|
$val_conf = $config['password_validation'] ?? [];
|
|
|
|
$minlen = $config['min_password_length'] ?? null;
|
|
|
|
if (is_numeric($minlen) && $minlen > 0) {
|
|
$minlen = (int)$minlen; # used up to 2.3.x -
|
|
$val_conf['/.{' . $minlen . '}/'] = "password_too_short $minlen";
|
|
}
|
|
|
|
foreach ($val_conf as $regex => $message) {
|
|
if (is_callable($message)) {
|
|
$ret = $message($password);
|
|
if (!empty($ret)) {
|
|
$result[] = $ret;
|
|
}
|
|
continue;
|
|
}
|
|
|
|
if (!preg_match($regex, $password)) {
|
|
$msgparts = preg_split("/ /", $message, 2);
|
|
if (count($msgparts) == 1) {
|
|
$result[] = Config::lang($msgparts[0]);
|
|
} else {
|
|
$result[] = sprintf(Config::lang($msgparts[0]), $msgparts[1]);
|
|
}
|
|
}
|
|
}
|
|
|
|
return $result;
|
|
}
|
|
|
|
|
|
/**
|
|
* Create/Validate courier authlib style crypt'ed passwords. (md5, md5raw, crypt, sha1)
|
|
*
|
|
* @param string $pw
|
|
* @param string $pw_db (optional)
|
|
* @return string crypted password - contains {xxx} prefix to identify mechanism.
|
|
*/
|
|
function _pacrypt_authlib($pw, $pw_db)
|
|
{
|
|
global $CONF;
|
|
$flavor = $CONF['authlib_default_flavor'];
|
|
$salt = substr(create_salt(), 0, 2); # courier-authlib supports only two-character salts
|
|
if (preg_match('/^{.*}/', $pw_db)) {
|
|
// we have a flavor in the db -> use it instead of default flavor
|
|
$result = preg_split('/[{}]/', $pw_db, 3); # split at { and/or }
|
|
$flavor = $result[1];
|
|
$salt = substr($result[2], 0, 2);
|
|
}
|
|
|
|
if (stripos($flavor, 'md5raw') === 0) {
|
|
$password = '{' . $flavor . '}' . md5($pw);
|
|
} elseif (stripos($flavor, 'md5') === 0) {
|
|
$password = '{' . $flavor . '}' . base64_encode(md5($pw, true));
|
|
} elseif (stripos($flavor, 'crypt') === 0) {
|
|
$password = '{' . $flavor . '}' . crypt($pw, $salt);
|
|
} elseif (stripos($flavor, 'SHA') === 0) {
|
|
$password = '{' . $flavor . '}' . base64_encode(sha1($pw, true));
|
|
} else {
|
|
throw new Exception("authlib_default_flavor '" . $flavor . "' unknown. Valid flavors are 'md5raw', 'md5', 'SHA' and 'crypt'");
|
|
}
|
|
return $password;
|
|
}
|
|
|
|
/**
|
|
* Uses the doveadm pw command, crypted passwords have a {...} prefix to identify type.
|
|
*
|
|
* @param string $pw - plain text password
|
|
* @param string $pw_db - encrypted password, or '' for generation.
|
|
* @param string $username
|
|
* @return string crypted password
|
|
*/
|
|
function _pacrypt_dovecot($pw, $pw_db = '', $username = '')
|
|
{
|
|
global $CONF;
|
|
|
|
$split_method = preg_split('/:/', $CONF['encrypt']);
|
|
$method = strtoupper($split_method[1]);
|
|
# If $pw_db starts with {method}, change $method accordingly
|
|
if (!empty($pw_db) && preg_match('/^\{([A-Z0-9.-]+)\}.+/', $pw_db, $method_matches)) {
|
|
$method = $method_matches[1];
|
|
}
|
|
if (!preg_match("/^[A-Z0-9.-]+$/", $method)) {
|
|
throw new Exception("invalid dovecot encryption method");
|
|
}
|
|
|
|
$doveadm_options = '';
|
|
|
|
if (strtolower($method) == 'digest-md5') {
|
|
if (empty($username)) {
|
|
throw new Exception("\$CONF['encrypt'] = 'dovecot:digest-md5' require username.");
|
|
}
|
|
$doveadm_options = ' -u ' . escapeshellarg($username);
|
|
}
|
|
|
|
$dovecotpw = "doveadm pw";
|
|
if (!empty($CONF['dovecotpw'])) {
|
|
$dovecotpw = $CONF['dovecotpw'];
|
|
}
|
|
|
|
$nonsaltedtypes = "SHA|SHA1|SHA256|SHA512|CLEAR|CLEARTEXT|PLAIN|PLAIN-TRUNC|CRAM-MD5|HMAC-MD5|PLAIN-MD4|PLAIN-MD5|LDAP-MD5|LANMAN|NTLM|RPA";
|
|
$salted = !preg_match("/^($nonsaltedtypes)(\.B64|\.BASE64|\.HEX)?$/", strtoupper($method));
|
|
|
|
$dovepasstest = '';
|
|
if ($salted && (!empty($pw_db))) {
|
|
# only use -t for salted passwords to be backward compatible with dovecot < 2.1
|
|
$dovepasstest = " -t " . escapeshellarg($pw_db);
|
|
}
|
|
|
|
// pass the password via stdin, so it's not visible in the process table.
|
|
// dovecot uses getpass() twice (except when using -t), so send it twice.
|
|
$stdin = $pw . "\n";
|
|
if (empty($dovepasstest)) {
|
|
$stdin .= $pw . "\n";
|
|
}
|
|
|
|
$exec = Exec::run("$dovecotpw -s {$method}{$dovepasstest}{$doveadm_options}", $stdin);
|
|
|
|
$password = $exec->stdout;
|
|
$stderr_output = $exec->stderr;
|
|
|
|
if ($exec->retval !== 0 || empty($password)) {
|
|
error_log("Failed to read password from $dovecotpw ... exit status: {$exec->retval}, stderr: $stderr_output, password: $password ");
|
|
throw new Exception("$dovecotpw failed, see error log for details");
|
|
}
|
|
|
|
if (empty($dovepasstest)) {
|
|
if (!preg_match('/^\{' . $method . '\}/', $password)) {
|
|
error_log("dovecotpw password encryption failed (method: $method) . stderr: $stderr_output");
|
|
throw new Exception("can't encrypt password with dovecotpw, see error log for details");
|
|
}
|
|
} else {
|
|
if (!preg_match('(verified)', $password)) {
|
|
$password = "Thepasswordcannotbeverified";
|
|
} else {
|
|
$password = rtrim(str_replace('(verified)', '', $password));
|
|
}
|
|
}
|
|
|
|
if (!empty($stderr_output)) {
|
|
error_log("$dovecotpw wrote to stderr but returned a valid result: $stderr_output");
|
|
}
|
|
|
|
if ((!empty($pw_db)) && (substr($pw_db, 0, 1) != '{')) {
|
|
# for backward compability with "old" dovecot passwords that don't have the {method} prefix
|
|
$password = str_replace('{' . $method . '}', '', $password);
|
|
}
|
|
|
|
return rtrim($password);
|
|
}
|
|
|
|
/**
|
|
* Supports DES, MD5, BLOWFISH, SHA256, SHA512 methods.
|
|
*
|
|
* Via config we support an optional prefix (e.g. if you need hashes to start with {SHA256-CRYPT} and optional rounds (hardness) setting.
|
|
*
|
|
* @param string $pw
|
|
* @param string $pw_db (can be empty if setting a new password)
|
|
* @return string crypt'ed password; if it matches $pw_db then $pw is the original password.
|
|
*/
|
|
function _pacrypt_php_crypt($pw, $pw_db)
|
|
{
|
|
$configEncrypt = Config::read_string('encrypt');
|
|
|
|
// use PHPs crypt(), which uses the system's crypt()
|
|
// same algorithms as used in /etc/shadow
|
|
// you can have mixed hash types in the database for authentication, changed passwords get specified hash type
|
|
// the algorithm for a new hash is chosen by feeding a salt with correct magic to crypt()
|
|
// set $CONF['encrypt'] to 'php_crypt' to use the default SHA512 crypt method
|
|
// set $CONF['encrypt'] to 'php_crypt:METHOD' to use another method; methods supported: DES, MD5, BLOWFISH, SHA256, SHA512
|
|
// set $CONF['encrypt'] to 'php_crypt:METHOD:difficulty' where difficulty is between 1000-999999999
|
|
// set $CONF['encrypt'] to 'php_crypt:METHOD:difficulty:PREFIX' to prefix the hash with the {PREFIX} etc.
|
|
// tested on linux
|
|
|
|
$prefix = '';
|
|
|
|
if (strlen($pw_db) > 0) {
|
|
// existing pw provided. send entire password hash as salt for crypt() to figure out
|
|
$salt = $pw_db;
|
|
|
|
// if there was a prefix in the password, use this (override anything given in the config).
|
|
|
|
if (preg_match('/^\{([-A-Z0-9]+)\}(.+)$/', $pw_db, $method_matches)) {
|
|
$salt = $method_matches[2];
|
|
$prefix = "{" . $method_matches[1] . "}";
|
|
}
|
|
} else {
|
|
$salt_method = 'SHA512'; // hopefully a reasonable default (better than MD5)
|
|
$hash_difficulty = '';
|
|
// no pw provided. create new password hash
|
|
if (strpos($configEncrypt, ':') !== false) {
|
|
// use specified hash method
|
|
$spec = explode(':', $configEncrypt);
|
|
$salt_method = $spec[1];
|
|
if (isset($spec[2])) {
|
|
$hash_difficulty = $spec[2];
|
|
}
|
|
if (isset($spec[3])) {
|
|
$prefix = $spec[3]; // hopefully something like {SHA256-CRYPT}
|
|
}
|
|
}
|
|
// create appropriate salt for selected hash method
|
|
$salt = _php_crypt_generate_crypt_salt($salt_method, $hash_difficulty);
|
|
}
|
|
|
|
$password = crypt($pw, $salt);
|
|
|
|
return "{$prefix}{$password}";
|
|
}
|
|
|
|
|
|
/**
|
|
* @param string $hash_type must be one of: MD5, DES, BLOWFISH, SHA256 or SHA512 (default)
|
|
* @param int hash difficulty
|
|
* @return string
|
|
*/
|
|
function _php_crypt_generate_crypt_salt($hash_type = 'SHA512', $hash_difficulty = null)
|
|
{
|
|
// generate a salt (with magic matching chosen hash algorithm) for the PHP crypt() function
|
|
|
|
// most commonly used alphabet
|
|
$alphabet = './0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
|
|
|
|
switch ($hash_type) {
|
|
case 'DES':
|
|
$alphabet = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
|
|
$length = 2;
|
|
$salt = _php_crypt_random_string($alphabet, $length);
|
|
return $salt;
|
|
|
|
case 'MD5':
|
|
$length = 12;
|
|
$algorithm = '1';
|
|
$salt = _php_crypt_random_string($alphabet, $length);
|
|
return sprintf('$%s$%s', $algorithm, $salt);
|
|
|
|
case 'BLOWFISH':
|
|
$length = 22;
|
|
if (empty($hash_difficulty)) {
|
|
$cost = 10;
|
|
} else {
|
|
$cost = (int)$hash_difficulty;
|
|
if ($cost < 4 || $cost > 31) {
|
|
throw new Exception('invalid encrypt difficulty setting "' . $hash_difficulty . '" for ' . $hash_type . ', the valid range is 4-31');
|
|
}
|
|
}
|
|
|
|
$algorithm = '2y'; // bcrypt (2a is a legacy variant with a unicode problem).
|
|
$salt = _php_crypt_random_string($alphabet, $length);
|
|
$hash = sprintf('$%s$%02d$%s', $algorithm, $cost, $salt);
|
|
if (!is_string($hash)) {
|
|
throw new \InvalidArgumentException('Failed to generate crypt salt for ' . $hash_type);
|
|
}
|
|
return $hash;
|
|
|
|
case 'SHA256':
|
|
$length = 16;
|
|
$algorithm = '5';
|
|
if (empty($hash_difficulty)) {
|
|
$rounds = '';
|
|
} else {
|
|
$rounds = (int)$hash_difficulty;
|
|
if ($rounds < 1000 || $rounds > 999999999) {
|
|
throw new Exception('invalid encrypt difficulty setting "' . $hash_difficulty . '" for ' . $hash_type . ', the valid range is 1000-999999999');
|
|
}
|
|
}
|
|
$salt = _php_crypt_random_string($alphabet, $length);
|
|
if (!empty($rounds)) {
|
|
$rounds = sprintf('rounds=%d$', $rounds);
|
|
}
|
|
return sprintf('$%s$%s%s', $algorithm, $rounds, $salt);
|
|
|
|
case 'SHA512':
|
|
$length = 16;
|
|
$algorithm = '6';
|
|
if (empty($hash_difficulty)) {
|
|
$rounds = '';
|
|
} else {
|
|
$rounds = (int)$hash_difficulty;
|
|
if ($rounds < 1000 || $rounds > 999999999) {
|
|
throw new Exception('invalid encrypt difficulty setting "' . $hash_difficulty . '" for ' . $hash_type . ', the valid range is 1000-999999999');
|
|
}
|
|
}
|
|
$salt = _php_crypt_random_string($alphabet, $length);
|
|
if (!empty($rounds)) {
|
|
$rounds = sprintf('rounds=%d$', $rounds);
|
|
}
|
|
return sprintf('$%s$%s%s', $algorithm, $rounds, $salt);
|
|
|
|
default:
|
|
throw new Exception("unknown hash type: '$hash_type'");
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Generates a random string of specified $length from $characters.
|
|
* @param string $characters
|
|
* @param int $length
|
|
* @return string of given $length
|
|
*/
|
|
function _php_crypt_random_string(string $characters, int $length): string
|
|
{
|
|
$string = '';
|
|
for ($p = 0; $p < $length; $p++) {
|
|
$string .= $characters[random_int(0, strlen($characters) - 1)];
|
|
}
|
|
return $string;
|
|
}
|
|
|
|
|
|
/**
|
|
* Encrypt a password, using the apparopriate hashing mechanism as defined in
|
|
* config.inc.php ($CONF['encrypt']).
|
|
*
|
|
* When wanting to compare one pw to another, it's necessary to provide the salt used - hence
|
|
* the second parameter ($pw_db), which is the existing hash from the DB.
|
|
*
|
|
* @param string $pw
|
|
* @param string $pw_db optional encrypted password
|
|
* @param string $username optional, but required when $CONF['encrypt'] = 'dovecot:digest-md5'
|
|
* @return string encrypted password - if this matches $pw_db then the original password is $pw.
|
|
*/
|
|
function pacrypt($pw, $pw_db = "", $username = '')
|
|
{
|
|
global $CONF;
|
|
|
|
$mechanism = strtoupper($CONF['encrypt'] ?? 'CRYPT');
|
|
|
|
// Keep the 3.x md5crypt setting as an alias for MD5-CRYPT. New hashes
|
|
// generated through the alias retain the historical unprefixed format.
|
|
$legacy_md5crypt = $mechanism == 'MD5CRYPT';
|
|
if ($legacy_md5crypt) {
|
|
$mechanism = 'MD5-CRYPT';
|
|
}
|
|
|
|
|
|
if (preg_match('/^PHP_CRYPT:(DES|MD5|BLOWFISH|SHA256|SHA512):?/', $mechanism, $matches)) {
|
|
return _pacrypt_php_crypt($pw, $pw_db);
|
|
}
|
|
|
|
|
|
if ($mechanism == 'PHP_CRYPT') {
|
|
$mechanism = 'CRYPT';
|
|
}
|
|
|
|
|
|
if ($mechanism == 'AUTHLIB') {
|
|
return _pacrypt_authlib($pw, $pw_db);
|
|
}
|
|
|
|
if (!empty($pw_db) && preg_match('/^{([0-9a-z-\.]+)}/i', $pw_db, $matches)) {
|
|
$method_in_hash = $matches[1];
|
|
if ('DOVECOT:' . strtoupper($method_in_hash) == $mechanism || 'COURIER:' . strtoupper($method_in_hash) == $mechanism) {
|
|
// don't try and be clever.
|
|
} elseif ($mechanism != $method_in_hash) {
|
|
error_log("PostfixAdmin: configured to use $mechanism, but asked to crypt password using {$method_in_hash}; are you migrating algorithm/mechanism or is something wrong?");
|
|
$mechanism = $method_in_hash;
|
|
}
|
|
}
|
|
|
|
if ($mechanism == 'MD5RAW') {
|
|
$mechanism = 'COURIER:MD5RAW';
|
|
}
|
|
|
|
// Raw modular crypt hashes do not identify their scheme with a {SCHEME}
|
|
// prefix. Verify them using their own salt regardless of current config.
|
|
if (!empty($pw_db) && preg_match('/^\$(?:1|2[abxy]?|5|6)\$/i', $pw_db)) {
|
|
$mechanism = 'CRYPT';
|
|
}
|
|
|
|
if ($mechanism == 'SHA512.B64') {
|
|
// postfixadmin incorrectly uses this as a SHA512-CRYPT.B64
|
|
$mechanism = 'SHA512-CRYPT.B64';
|
|
|
|
// backwards compatability - see https://github.com/postfixadmin/postfixadmin/issues/58 and https://github.com/postfixadmin/postfixadmin/issues/647
|
|
// if we are configured for SHA512.B64, support existing passwords in MD5-CRYPT format.
|
|
if ($pw_db && strncmp($pw_db, '{MD5-CRYPT}', 11) == 0) {
|
|
$mechanism = 'MD5-CRYPT';
|
|
}
|
|
}
|
|
|
|
if (preg_match('/^DOVECOT:(.*)$/i', $mechanism, $matches)) {
|
|
return _pacrypt_dovecot($pw, $pw_db, $username);
|
|
}
|
|
|
|
if (empty($pw_db)) {
|
|
$pw_db = null;
|
|
}
|
|
|
|
$hasher = new \PostfixAdmin\PasswordHashing\Crypt($mechanism);
|
|
$hashed = $hasher->crypt($pw, $pw_db);
|
|
|
|
if ($legacy_md5crypt && empty($pw_db) && strncmp($hashed, '{MD5-CRYPT}', 11) == 0) {
|
|
return substr($hashed, 11);
|
|
}
|
|
|
|
return $hashed;
|
|
}
|
|
|
|
|
|
/**
|
|
* @return string - should be random, 8 chars long
|
|
*/
|
|
function create_salt()
|
|
{
|
|
return bin2hex(random_bytes(4));
|
|
}
|
|
|
|
/*
|
|
* remove item $item from array $array
|
|
*/
|
|
function remove_from_array($array, $item)
|
|
{
|
|
# array_diff might be faster, but doesn't provide an easy way to know if the value was found or not
|
|
# return array_diff($array, array($item));
|
|
$ret = array_search($item, $array);
|
|
if ($ret === false) {
|
|
$found = 0;
|
|
} else {
|
|
$found = 1;
|
|
unset($array[$ret]);
|
|
}
|
|
return array($found, $array);
|
|
}
|
|
|
|
function enable_socket_crypto($fh)
|
|
{
|
|
stream_set_blocking($fh, true);
|
|
stream_socket_enable_crypto($fh, true, STREAM_CRYPTO_METHOD_TLSv1_2_CLIENT);
|
|
stream_set_blocking($fh, true);
|
|
}
|
|
|
|
/**
|
|
* smtp_mail
|
|
* Action: Send email
|
|
* Call: smtp_mail (string to, string from, string subject, string body]) - or -
|
|
* Call: smtp_mail (string to, string from, string data) - DEPRECATED
|
|
* @param string $to
|
|
* @param string $from
|
|
* @param string $subject_or_data (if called with 4 parameters) or full mail body (if called with 3 parameters)
|
|
* @param ?string $body (optional, but recommended) - mail body (if null, assume $subject_or_data is the entire mail body with headers etc)
|
|
* @return bool - true on success, otherwise false
|
|
*/
|
|
function smtp_mail(string $to, string $from, string $subject_or_data, ?string $body = null): bool
|
|
{
|
|
global $CONF;
|
|
|
|
$server = $CONF['smtp_server'];
|
|
$port = (int)$CONF['smtp_port'];
|
|
$timeout = 30;
|
|
|
|
$helo = !empty($CONF['smtp_client'])
|
|
? $CONF['smtp_client']
|
|
: php_uname('n');
|
|
|
|
$username = $CONF['smtp_username'] ?? '';
|
|
$password = $CONF['admin_smtp_password'] ?? '';
|
|
$type = $CONF['smtp_type'] ?? 'starttls';
|
|
|
|
// Building of SMTP payload
|
|
if ($body === null) {
|
|
// RAW MOD for Broadcast (broadcast-message.php)
|
|
$maildata = $subject_or_data;
|
|
} else {
|
|
// NORMAL MOD (sendmail.php)
|
|
$maildata =
|
|
"To: $to\r\n" .
|
|
"From: $from\r\n" .
|
|
"Subject: " . encode_header($subject_or_data) . "\r\n" .
|
|
"MIME-Version: 1.0\r\n" .
|
|
"Date: " . date('r') . "\r\n" .
|
|
"Content-Type: text/plain; charset=utf-8\r\n" .
|
|
"Content-Transfer-Encoding: 8bit\r\n\r\n" .
|
|
$body;
|
|
}
|
|
|
|
// Connection
|
|
if ($type === 'tls' || $type === 'ssl') {
|
|
$socket = stream_socket_client(
|
|
"ssl://{$server}:{$port}",
|
|
$errno,
|
|
$errstr,
|
|
$timeout,
|
|
STREAM_CLIENT_CONNECT
|
|
);
|
|
} else {
|
|
$socket = fsockopen($server, $port, $errno, $errstr, $timeout);
|
|
}
|
|
|
|
if (!$socket) {
|
|
error_log("smtp_mail(): socket error $errno - $errstr");
|
|
return false;
|
|
}
|
|
|
|
try {
|
|
smtp_require_response($socket, 220);
|
|
|
|
smtp_write($socket, "EHLO $helo\r\n");
|
|
smtp_require_response($socket, 250);
|
|
|
|
if ($type === 'starttls') {
|
|
smtp_write($socket, "STARTTLS\r\n");
|
|
smtp_require_response($socket, 220);
|
|
if (stream_socket_enable_crypto($socket, true, STREAM_CRYPTO_METHOD_TLS_CLIENT) !== true) {
|
|
throw new RuntimeException('STARTTLS negotiation failed');
|
|
}
|
|
smtp_write($socket, "EHLO $helo\r\n");
|
|
smtp_require_response($socket, 250);
|
|
}
|
|
|
|
// AUTH
|
|
smtp_write($socket, "AUTH LOGIN\r\n");
|
|
smtp_require_response($socket, 334);
|
|
smtp_write($socket, base64_encode($username) . "\r\n");
|
|
smtp_require_response($socket, 334);
|
|
smtp_write($socket, base64_encode($password) . "\r\n");
|
|
smtp_require_response($socket, 235);
|
|
|
|
// SMTP FLOW
|
|
smtp_write($socket, "MAIL FROM:<$from>\r\n");
|
|
smtp_require_response($socket, 250);
|
|
smtp_write($socket, "RCPT TO:<$to>\r\n");
|
|
smtp_require_response($socket, 250);
|
|
smtp_write($socket, "DATA\r\n");
|
|
smtp_require_response($socket, 354);
|
|
|
|
smtp_write($socket, $maildata . "\r\n.\r\n");
|
|
smtp_require_response($socket, 250);
|
|
|
|
smtp_write($socket, "QUIT\r\n");
|
|
fclose($socket);
|
|
return true;
|
|
} catch (RuntimeException $e) {
|
|
error_log('smtp_mail(): ' . $e->getMessage());
|
|
fclose($socket);
|
|
return false;
|
|
}
|
|
}
|
|
|
|
//end
|
|
// auxiliary function
|
|
function smtp_expect($socket, $code)
|
|
{
|
|
$response = '';
|
|
while ($line = fgets($socket, 515)) {
|
|
$response .= $line;
|
|
if (preg_match('/^\d{3}\s/', $line)) {
|
|
break;
|
|
}
|
|
}
|
|
|
|
if ((int)substr($response, 0, 3) !== $code) {
|
|
error_log("smtp_mail(): especting $code, received: " . trim($response));
|
|
return false;
|
|
}
|
|
return true;
|
|
}
|
|
|
|
function smtp_require_response($socket, int $code): void
|
|
{
|
|
if (!smtp_expect($socket, $code)) {
|
|
throw new RuntimeException("Unexpected SMTP response; expected $code");
|
|
}
|
|
}
|
|
|
|
function smtp_write($socket, string $data): void
|
|
{
|
|
$remaining = $data;
|
|
while ($remaining !== '') {
|
|
try {
|
|
$written = fwrite($socket, $remaining);
|
|
} catch (Throwable $e) {
|
|
throw new RuntimeException('Failed to write to SMTP connection', 0, $e);
|
|
}
|
|
|
|
if ($written === false || $written === 0) {
|
|
throw new RuntimeException('Failed to write to SMTP connection');
|
|
}
|
|
|
|
$remaining = substr($remaining, $written);
|
|
}
|
|
}
|
|
|
|
//end commit
|
|
/**
|
|
* smtp_get_admin_email
|
|
* Action: Get configured email address or current user if nothing configured
|
|
* Call: smtp_get_admin_email
|
|
* @return string - username/mail address
|
|
*/
|
|
function smtp_get_admin_email(bool $fallback_to_loggedin_user = true)
|
|
{
|
|
$admin_email = Config::read_string('admin_email');
|
|
if (!empty($admin_email)) {
|
|
return $admin_email;
|
|
}
|
|
|
|
if ($fallback_to_loggedin_user) {
|
|
/* may do a redirect to login */
|
|
return authentication_get_username();
|
|
}
|
|
error_log(__FILE__ . " WARNING : Please set a PostfixAdmin admin_email setting in your config.local.php file");
|
|
return "PasswordReset <noreply@example.com>"; // this isn't good.
|
|
}
|
|
|
|
/**
|
|
* smtp_get_admin_password
|
|
* Action: Get smtp password for admin email
|
|
* Call: smtp_get_admin_password
|
|
* @return string - admin smtp password
|
|
*/
|
|
function smtp_get_admin_password()
|
|
{
|
|
return Config::read_string('admin_smtp_password');
|
|
}
|
|
|
|
|
|
//
|
|
// smtp_get_response
|
|
// Action: Get response from mail server
|
|
// Call: smtp_get_response (string FileHandle)
|
|
//
|
|
function smtp_get_response($fh)
|
|
{
|
|
$res = '';
|
|
do {
|
|
$line = fgets($fh, 256);
|
|
$res .= $line;
|
|
} while (preg_match("/^\d\d\d\-/", $line));
|
|
return $res;
|
|
}
|
|
|
|
|
|
/**
|
|
* @return string - PDO DSN for PHP.
|
|
* @throws Exception
|
|
*/
|
|
function db_connection_string()
|
|
{
|
|
global $CONF;
|
|
if (db_mysql()) {
|
|
$socket = false;
|
|
if (Config::has('database_socket')) {
|
|
$socket = Config::read_string('database_socket');
|
|
}
|
|
|
|
$database_name = Config::read_string('database_name');
|
|
|
|
$dsn = 'mysql:';
|
|
if ($socket) {
|
|
$dsn .= "unix_socket={$socket}";
|
|
} else {
|
|
$dsn .= "host={$CONF['database_host']}";
|
|
}
|
|
|
|
if (isset($CONF['database_port'])) {
|
|
$dsn .= ";port={$CONF['database_port']}";
|
|
}
|
|
|
|
$dsn .= ";dbname={$database_name}";
|
|
} elseif (db_sqlite()) {
|
|
$db = $CONF['database_name'];
|
|
|
|
$dsn = "sqlite:{$db}";
|
|
} elseif (db_pgsql()) {
|
|
$dsn = "pgsql:dbname={$CONF['database_name']}";
|
|
if (isset($CONF['database_host'])) {
|
|
$dsn .= ";host={$CONF['database_host']}";
|
|
}
|
|
if (isset($CONF['database_port'])) {
|
|
$dsn .= ";port={$CONF['database_port']}";
|
|
}
|
|
$dsn .= ";options='-c client_encoding=utf8'";
|
|
} else {
|
|
throw new Exception("<p style='color: red'>FATAL Error:<br />Invalid \$CONF['database_type'] <br/>Only: 'pgsql', 'mysql' or 'sqlite' supported. <br/> Please fix your config.inc.php!</p>");
|
|
}
|
|
|
|
return $dsn;
|
|
}
|
|
|
|
/**
|
|
* db_connect
|
|
* Action: Makes a connection to the database if it doesn't exist
|
|
* Call: db_connect ()
|
|
*
|
|
* Return value:
|
|
*
|
|
* @return \PDO
|
|
*/
|
|
function db_connect()
|
|
{
|
|
global $CONF;
|
|
|
|
/* some attempt at not reopening an existing connection */
|
|
static $link;
|
|
if (isset($link) && $link) {
|
|
return $link;
|
|
}
|
|
|
|
$link = false;
|
|
|
|
// throws.
|
|
$dsn = db_connection_string();
|
|
|
|
$options = array(
|
|
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
|
|
PDO::ATTR_TIMEOUT => 5,
|
|
);
|
|
$username_password = true;
|
|
|
|
$queries = array();
|
|
|
|
|
|
if (db_mysql()) {
|
|
if (Config::bool('database_use_ssl')) {
|
|
$options[PDO::MYSQL_ATTR_SSL_KEY] = Config::read_string('database_ssl_key');
|
|
$options[PDO::MYSQL_ATTR_SSL_CA] = Config::read_string('database_ssl_ca');
|
|
$options[PDO::MYSQL_ATTR_SSL_CAPATH] = Config::read_string('database_ssl_ca_path');
|
|
$options[PDO::MYSQL_ATTR_SSL_CERT] = Config::read_string('database_ssl_cert');
|
|
$options[PDO::MYSQL_ATTR_SSL_CIPHER] = Config::read_string('database_ssl_cipher');
|
|
$options = array_filter($options); // remove empty settings.
|
|
|
|
$verify = Config::read('database_ssl_verify_server_cert');
|
|
if ($verify === null) { // undefined
|
|
$verify = true;
|
|
}
|
|
|
|
$options[PDO::MYSQL_ATTR_SSL_VERIFY_SERVER_CERT] = (bool)$verify;
|
|
}
|
|
$queries[] = 'SET NAMES utf8mb4';
|
|
$queries[] = "SET COLLATION_CONNECTION='utf8mb4_general_ci'";
|
|
} elseif (db_sqlite()) {
|
|
$db = $CONF['database_name'];
|
|
|
|
if (!file_exists($db)) {
|
|
$error_text = 'SQLite database missing: ' . $db;
|
|
throw new Exception($error_text);
|
|
}
|
|
|
|
if (!is_writeable($db)) {
|
|
$error_text = 'SQLite database not writeable: ' . $db;
|
|
throw new Exception($error_text);
|
|
}
|
|
|
|
if (!is_writeable(dirname($db))) {
|
|
$error_text = 'The directory the SQLite database is in is not writeable: ' . dirname($db);
|
|
throw new Exception($error_text);
|
|
}
|
|
|
|
$username_password = false;
|
|
} elseif (db_pgsql()) {
|
|
// nothing to do.
|
|
} else {
|
|
throw new Exception("<p style='color: red'>FATAL Error:<br />Invalid \$CONF['database_type']! Please fix your config.inc.php!</p>");
|
|
}
|
|
|
|
if ($username_password) {
|
|
$link = new PDO($dsn, Config::read_string('database_user'), Config::read_string('database_password'), $options);
|
|
} else {
|
|
$link = new PDO($dsn, null, null, $options);
|
|
}
|
|
|
|
if (!empty($queries)) {
|
|
foreach ($queries as $q) {
|
|
$link->exec($q);
|
|
}
|
|
}
|
|
|
|
return $link;
|
|
}
|
|
|
|
/**
|
|
* Returns the appropriate boolean value for the database.
|
|
*
|
|
* @param bool|string $bool
|
|
* @return string|int as appropriate for underlying db platform
|
|
*/
|
|
function db_get_boolean($bool)
|
|
{
|
|
if (!(is_bool($bool) || $bool == '0' || $bool == '1')) {
|
|
error_log("Invalid usage of 'db_get_boolean($bool)'");
|
|
throw new Exception("Invalid usage of 'db_get_boolean($bool)'");
|
|
}
|
|
|
|
if (db_pgsql()) {
|
|
// return either true or false (unquoted strings)
|
|
if ($bool) {
|
|
return 't';
|
|
}
|
|
return 'f';
|
|
} elseif (db_mysql() || db_sqlite()) {
|
|
if ($bool) {
|
|
return 1;
|
|
}
|
|
return 0;
|
|
} else {
|
|
throw new Exception('Unknown value in $CONF[database_type]');
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Returns a query that reports the used quota ("x / y")
|
|
* @param string column containing used quota
|
|
* @param string column containing allowed quota
|
|
* @param string column that will contain "x / y"
|
|
* @return string
|
|
*/
|
|
function db_quota_text($count, $quota, $fieldname)
|
|
{
|
|
if (db_pgsql() || db_sqlite()) {
|
|
// SQLite and PostgreSQL use || to concatenate strings
|
|
return " CASE $quota
|
|
WHEN '-1' THEN (coalesce($count,0) || ' / -')
|
|
WHEN '0' THEN (coalesce($count,0) || ' / " . escape_string(html_entity_decode('∞')) . "')
|
|
ELSE (coalesce($count,0) || ' / ' || $quota)
|
|
END AS $fieldname";
|
|
} else {
|
|
return " CASE $quota
|
|
WHEN '-1' THEN CONCAT(coalesce($count,0), ' / -')
|
|
WHEN '0' THEN CONCAT(coalesce($count,0), ' / ', '" . escape_string(html_entity_decode('∞')) . "')
|
|
ELSE CONCAT(coalesce($count,0), ' / ', $quota)
|
|
END AS $fieldname";
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Returns a query that reports the used quota ("x / y")
|
|
* @param string column containing used quota
|
|
* @param string column containing allowed quota
|
|
* @param string column that will contain "x / y"
|
|
* @return string
|
|
*/
|
|
function db_quota_percent($count, $quota, $fieldname)
|
|
{
|
|
return " CASE $quota
|
|
WHEN '-1' THEN -1
|
|
WHEN '0' THEN -1
|
|
ELSE round(100 * coalesce($count,0) / $quota)
|
|
END AS $fieldname";
|
|
}
|
|
|
|
/**
|
|
* @return boolean true if it's a MySQL database variant.
|
|
*/
|
|
function db_mysql()
|
|
{
|
|
$type = Config::Read('database_type');
|
|
|
|
if ($type == 'mysql' || $type == 'mysqli') {
|
|
return true;
|
|
}
|
|
return false;
|
|
}
|
|
|
|
/**
|
|
* @return bool true if PostgreSQL is used, false otherwise
|
|
*/
|
|
function db_pgsql()
|
|
{
|
|
return Config::read_string('database_type') == 'pgsql';
|
|
}
|
|
|
|
/**
|
|
* returns true if SQLite is used, false otherwise
|
|
*/
|
|
function db_sqlite()
|
|
{
|
|
if (Config::Read('database_type') == 'sqlite') {
|
|
return true;
|
|
} else {
|
|
return false;
|
|
}
|
|
}
|
|
|
|
/**
|
|
* @param string $sql
|
|
* @param array $values
|
|
* @return array
|
|
*/
|
|
function db_query_all(string $sql, array $values = []): array
|
|
{
|
|
$r = db_query($sql, $values);
|
|
return $r['result']->fetchAll(PDO::FETCH_ASSOC);
|
|
}
|
|
|
|
/**
|
|
* Read a per-admin preference from the admin_preferences table.
|
|
*
|
|
* @param string $username - the admin the preference belongs to
|
|
* @param string $key - the preference key
|
|
* @param string $default - value to return if no preference is stored
|
|
* @return string
|
|
*/
|
|
function get_admin_pref(string $username, string $key, string $default = ''): string
|
|
{
|
|
$row = db_query_one(
|
|
"SELECT pref_value FROM " . table_by_key('admin_preferences') . " WHERE username = :username AND pref_key = :pref_key",
|
|
array('username' => $username, 'pref_key' => $key)
|
|
);
|
|
|
|
if (is_array($row) && isset($row['pref_value'])) {
|
|
return $row['pref_value'];
|
|
}
|
|
|
|
return $default;
|
|
}
|
|
|
|
/**
|
|
* Store a per-admin preference (upsert) in the admin_preferences table.
|
|
*
|
|
* @param string $username - the admin the preference belongs to
|
|
* @param string $key - the preference key
|
|
* @param string $value - the preference value
|
|
* @return void
|
|
*/
|
|
function set_admin_pref(string $username, string $key, string $value): void
|
|
{
|
|
# delete + insert rather than an upsert: the syntax for the latter differs between
|
|
# MySQL, PostgreSQL and SQLite, and preferences are written rarely enough that the
|
|
# extra statement does not matter.
|
|
delete_admin_pref($username, $key);
|
|
|
|
db_execute(
|
|
"INSERT INTO " . table_by_key('admin_preferences') . " (username, pref_key, pref_value) VALUES (:username, :pref_key, :pref_value)",
|
|
array('username' => $username, 'pref_key' => $key, 'pref_value' => $value)
|
|
);
|
|
}
|
|
|
|
/**
|
|
* Remove a per-admin preference from the admin_preferences table.
|
|
*
|
|
* @param string $username - the admin the preference belongs to
|
|
* @param string $key - the preference key
|
|
* @return void
|
|
*/
|
|
function delete_admin_pref(string $username, string $key): void
|
|
{
|
|
db_execute(
|
|
"DELETE FROM " . table_by_key('admin_preferences') . " WHERE username = :username AND pref_key = :pref_key",
|
|
array('username' => $username, 'pref_key' => $key)
|
|
);
|
|
}
|
|
|
|
/**
|
|
* @param string $sql
|
|
* @param array $values
|
|
* @return array
|
|
*/
|
|
function db_query_one(string $sql, array $values = []): ?array
|
|
{
|
|
$r = db_query($sql, $values);
|
|
$stmt = $r['result'];
|
|
/* @var PDOStatement $stmt */
|
|
$ret = $stmt->fetch(PDO::FETCH_ASSOC);
|
|
if (is_array($ret)) {
|
|
return $ret;
|
|
}
|
|
// no row?
|
|
return null;
|
|
}
|
|
|
|
|
|
/**
|
|
* @param string $sql e.g. UPDATE foo SET bar = :baz
|
|
* @param array $values - parameters for the prepared statement e.g. ['baz' => 1234]
|
|
* @param bool $throw_exceptions
|
|
* @return int number of rows affected by the query
|
|
*/
|
|
function db_execute(string $sql, array $values = [], bool $throw_exceptions = false): int
|
|
{
|
|
$link = db_connect();
|
|
|
|
try {
|
|
$stmt = $link->prepare($sql);
|
|
|
|
// PDO and PostgreSQL either require us to explicitly bind values as bools, or it seems to work
|
|
// if we pass in 0/1 .... 0/1 is easier?
|
|
foreach ($values as $key => $value) {
|
|
if (is_bool($value)) {
|
|
$values[$key] = (int)$value;
|
|
}
|
|
}
|
|
|
|
$stmt->execute($values);
|
|
} catch (PDOException $e) {
|
|
$error_text = "Invalid query: " . $e->getMessage() . " caused by " . $sql . ' ' . json_encode($values);
|
|
error_log($error_text);
|
|
if ($throw_exceptions) {
|
|
throw $e;
|
|
}
|
|
|
|
return 0;
|
|
}
|
|
|
|
return $stmt->rowCount();
|
|
}
|
|
|
|
/**
|
|
* @param string $sql
|
|
* @param array $values
|
|
* @param bool $ignore_errors - set to true to ignore errors.
|
|
* @return array e.g. ['result' => PDOStatement, 'error' => string ]
|
|
*/
|
|
function db_query(string $sql, array $values = array(), bool $ignore_errors = false): array
|
|
{
|
|
$link = db_connect();
|
|
$error_text = '';
|
|
|
|
$stmt = null;
|
|
try {
|
|
$stmt = $link->prepare($sql);
|
|
|
|
// PDO and PostgreSQL either require us to explicitly bind values as bools, or it seems to work
|
|
// if we pass in 0/1 .... 0/1 is easier?
|
|
foreach ($values as $key => $value) {
|
|
if (is_bool($value)) {
|
|
$values[$key] = (int)$value;
|
|
}
|
|
}
|
|
$stmt->execute($values);
|
|
} catch (PDOException $e) {
|
|
|
|
$error_text = "Invalid query: " . $e->getMessage() . " caused by " . $sql;
|
|
error_log($error_text);
|
|
if (defined('PHPUNIT_TEST')) {
|
|
throw new Exception("SQL query failed: {{{$sql}}} with " . json_encode($values) . ". Error message: " . $e->getMessage());
|
|
}
|
|
if (!$ignore_errors) {
|
|
throw new Exception("DEBUG INFORMATION: " . $e->getMessage() . "<br/> Check your error_log for the failed query");
|
|
}
|
|
}
|
|
|
|
return array(
|
|
"result" => $stmt,
|
|
"error" => $error_text,
|
|
);
|
|
}
|
|
|
|
|
|
/**
|
|
* Delete a row from the specified table.
|
|
*
|
|
* DELETE FROM $table WHERE $where = $delete $aditionalWhere
|
|
*
|
|
* @param string $table
|
|
* @param string $where - should never be a user supplied value
|
|
* @param string $delete
|
|
* @param string $additionalwhere (default '').
|
|
* @return int|mixed rows deleted.
|
|
*/
|
|
function db_delete(string $table, string $where, string $delete, string $additionalwhere = '', array $additional_params = [])
|
|
{
|
|
$table = table_by_key($table);
|
|
|
|
$query = "DELETE FROM $table WHERE $where = ? $additionalwhere";
|
|
|
|
return db_execute($query, array_merge(array($delete), $additional_params));
|
|
}
|
|
|
|
|
|
/**
|
|
* db_insert
|
|
* Action: Inserts a row from a specified table
|
|
* Call: db_insert (string table, array values [, array timestamp])
|
|
*
|
|
* @param string - table name
|
|
* @param array $values - key/value map of data to insert into the table.
|
|
* @param array $timestamp (optional) - array of fields to set to now() - default: array('created', 'modified')
|
|
* @param boolean $throw_exceptions
|
|
* @return int - number of inserted rows
|
|
*/
|
|
function db_insert(string $table, array $values, array $timestamp = array('created', 'modified'), bool $throw_exceptions = false): int
|
|
{
|
|
$table = table_by_key($table);
|
|
|
|
foreach ($timestamp as $key) {
|
|
if (db_sqlite()) {
|
|
$values[$key] = "datetime('now')";
|
|
} else {
|
|
$values[$key] = "now()";
|
|
}
|
|
}
|
|
|
|
$value_string = '';
|
|
$comma = '';
|
|
$prepared_statment_values = $values;
|
|
|
|
foreach ($values as $field => $value) {
|
|
if (in_array($field, $timestamp)) {
|
|
$value_string .= $comma . $value; // see above.
|
|
unset($prepared_statment_values[$field]);
|
|
} else {
|
|
$value_string .= $comma . ":{$field}";
|
|
}
|
|
$comma = ',';
|
|
}
|
|
|
|
return db_execute(
|
|
"INSERT INTO $table (" . implode(",", array_keys($values)) . ") VALUES ($value_string)",
|
|
$prepared_statment_values,
|
|
$throw_exceptions);
|
|
}
|
|
|
|
|
|
/**
|
|
* db_update
|
|
* Action: Updates a specified table
|
|
* Call: db_update (string table, string where_col, string where_value, array values [, array timestamp])
|
|
* @param string $table - table name
|
|
* @param string $where_col - column of WHERE condition
|
|
* @param string $where_value - value of WHERE condition
|
|
* @param array $values - key/value map of data to insert into the table.
|
|
* @param array $timestamp (optional) - array of fields to set to now() - default: array('modified')
|
|
* @return int - number of updated rows
|
|
*/
|
|
function db_update(string $table, string $where_col, string $where_value, array $values, array $timestamp = array('modified'), bool $throw_exceptions = false): int
|
|
{
|
|
$table_key = table_by_key($table);
|
|
|
|
$pvalues = array();
|
|
|
|
$set = array();
|
|
|
|
foreach ($timestamp as $k) {
|
|
if (!isset($values[$k])) {
|
|
$values[$k] = 'x'; // timestamp field not in the values list, add it in so we set it to now() see #469
|
|
}
|
|
}
|
|
|
|
foreach ($values as $key => $value) {
|
|
if (in_array($key, $timestamp)) {
|
|
if (db_sqlite()) {
|
|
$set[] = " $key = datetime('now') ";
|
|
} else {
|
|
$set[] = " $key = now() ";
|
|
}
|
|
continue;
|
|
}
|
|
|
|
$set[] = " $key = :$key ";
|
|
$pvalues[$key] = $value;
|
|
}
|
|
|
|
$pvalues['where'] = $where_value;
|
|
|
|
|
|
$sql = "UPDATE $table_key SET " . implode(",", $set) . " WHERE $where_col = :where";
|
|
|
|
return db_execute($sql, $pvalues, $throw_exceptions);
|
|
}
|
|
|
|
|
|
/**
|
|
* db_log
|
|
* Action: Logs actions from admin
|
|
* Call: db_log (string domain, string action, string data)
|
|
* Possible actions are defined in $LANG["pViewlog_action_$action"]
|
|
*/
|
|
function db_log(string $domain, string $action, string $data): bool
|
|
{
|
|
if (!Config::bool('logging')) {
|
|
return true;
|
|
}
|
|
|
|
$REMOTE_ADDR = getRemoteAddr();
|
|
|
|
$username = authentication_get_username();
|
|
|
|
if (Config::Lang("pViewlog_action_$action") == '') {
|
|
throw new Exception("Invalid log action : $action"); // could do with something better?
|
|
}
|
|
|
|
|
|
$logdata = array(
|
|
'username' => "$username ($REMOTE_ADDR)",
|
|
'domain' => $domain,
|
|
'action' => $action,
|
|
'data' => $data,
|
|
);
|
|
$result = db_insert('log', $logdata, array('timestamp'));
|
|
if ($result != 1) {
|
|
return false;
|
|
} else {
|
|
return true;
|
|
}
|
|
}
|
|
|
|
/**
|
|
* db_in_clause
|
|
* Action: builds and returns the "field in(x, y)" clause for database queries
|
|
* Call: db_in_clause (string field, array values)
|
|
* @param string $field
|
|
* @param array $values
|
|
* @return string
|
|
*/
|
|
function db_in_clause(string $field, array $values, array &$params = []): string
|
|
{
|
|
if (empty($values)) {
|
|
return " 1=0 "; // empty IN clause is invalid SQL, return false predicate
|
|
}
|
|
$placeholders = [];
|
|
foreach (array_values($values) as $i => $value) {
|
|
$key = '_in_' . count($params) . '_' . $i;
|
|
$placeholders[] = ':' . $key;
|
|
$params[$key] = $value;
|
|
}
|
|
return " $field IN (" . implode(",", $placeholders) . ") ";
|
|
}
|
|
|
|
/**
|
|
* Build the log-table domain restriction for viewlog.php.
|
|
*
|
|
* Global admins may view every domain; any other admin is restricted to the
|
|
* domains they manage, so the "All domains" option can never leak log entries
|
|
* belonging to other admins' domains.
|
|
*
|
|
* @param bool $show_all - whether the "All domains" option is selected
|
|
* @param bool $is_global_admin - whether the current admin is a global admin
|
|
* @param string $fDomain - the single selected domain (ignored when $show_all)
|
|
* @param array $allowed_domains - domains the current admin may view
|
|
* @param array &$params - bound query parameters (appended to)
|
|
* @return string - SQL condition for a WHERE clause, or '' for no restriction
|
|
*/
|
|
function viewlog_domain_condition(bool $show_all, bool $is_global_admin, string $fDomain, array $allowed_domains, array &$params): string
|
|
{
|
|
if ($show_all) {
|
|
if ($is_global_admin) {
|
|
return ''; # no restriction - every domain
|
|
}
|
|
return db_in_clause('domain', $allowed_domains, $params);
|
|
}
|
|
|
|
if ($fDomain !== '') {
|
|
$params['domain'] = $fDomain;
|
|
return 'domain = :domain';
|
|
}
|
|
|
|
return '';
|
|
}
|
|
|
|
/**
|
|
* Build normalized pagination items for an alphabetical page browser.
|
|
*
|
|
* @param array<int, string> $pages
|
|
* @param array<string, mixed> $query_params
|
|
* @param array{first?: string, previous?: string, next?: string} $aria_labels
|
|
* @return array<int, array<string, bool|int|string>>
|
|
*/
|
|
function page_browser_pagination(
|
|
array $pages,
|
|
int $offset,
|
|
int $page_size,
|
|
array $query_params,
|
|
string $anchor,
|
|
array $aria_labels = []
|
|
): array {
|
|
if (count($pages) === 0) {
|
|
return [];
|
|
}
|
|
if ($page_size < 1) {
|
|
throw new InvalidArgumentException('Page size must be greater than zero');
|
|
}
|
|
|
|
$current_page = intdiv(max(0, $offset), $page_size);
|
|
$last_page = count($pages) - 1;
|
|
|
|
$url_for_page = static function (int $page) use ($query_params, $page_size, $anchor): string {
|
|
$query_params['limit'] = $page * $page_size;
|
|
$query = http_build_query($query_params, '', '&', PHP_QUERY_RFC3986);
|
|
return '?' . htmlspecialchars($query, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8') . '#' . rawurlencode($anchor);
|
|
};
|
|
|
|
$pagination = [
|
|
[
|
|
'label' => '«',
|
|
'url' => $url_for_page(0),
|
|
'disabled' => $current_page === 0,
|
|
'aria' => $aria_labels['first'] ?? '',
|
|
],
|
|
[
|
|
'label' => '‹',
|
|
'url' => $url_for_page(max(0, $current_page - 1)),
|
|
'disabled' => $current_page === 0,
|
|
'aria' => $aria_labels['previous'] ?? '',
|
|
],
|
|
];
|
|
|
|
foreach ($pages as $page => $label) {
|
|
$pagination[] = [
|
|
'label' => $label,
|
|
'url' => $url_for_page($page),
|
|
'active' => $page === $current_page,
|
|
];
|
|
}
|
|
|
|
$pagination[] = [
|
|
'label' => '›',
|
|
'url' => $url_for_page(min($last_page, $current_page + 1)),
|
|
'disabled' => $current_page >= $last_page,
|
|
'aria' => $aria_labels['next'] ?? '',
|
|
];
|
|
|
|
return $pagination;
|
|
}
|
|
|
|
/**
|
|
* Compute the page numbers to display in a windowed pager.
|
|
*
|
|
* Always includes page 1 and the last page, plus a window of $radius pages on
|
|
* either side of the current page. Gaps between those ranges are represented by
|
|
* a null entry (rendered as an ellipsis). For example current=20, total=50,
|
|
* radius=5 yields: [1, null, 15..25, null, 50].
|
|
*
|
|
* @param int $current - the current page number (1-based)
|
|
* @param int $total_pages - total number of pages
|
|
* @param int $radius - how many pages to show either side of $current
|
|
* @return array<int|null> - ordered page numbers, null marks an ellipsis gap
|
|
*/
|
|
function pagination_window(int $current, int $total_pages, int $radius = 5): array
|
|
{
|
|
if ($total_pages <= 1) {
|
|
return $total_pages == 1 ? [1] : [];
|
|
}
|
|
|
|
$current = max(1, min($current, $total_pages));
|
|
$start = max(1, $current - $radius);
|
|
$end = min($total_pages, $current + $radius);
|
|
|
|
# Only the window itself is built (O(radius)), with page 1 / the last page
|
|
# and ellipsis markers (null) prepended/appended as needed.
|
|
$result = [];
|
|
|
|
if ($start > 1) {
|
|
$result[] = 1;
|
|
if ($start > 2) {
|
|
$result[] = null; # gap between page 1 and the window
|
|
}
|
|
}
|
|
|
|
for ($i = $start; $i <= $end; $i++) {
|
|
$result[] = $i;
|
|
}
|
|
|
|
if ($end < $total_pages) {
|
|
if ($end < $total_pages - 1) {
|
|
$result[] = null; # gap between the window and the last page
|
|
}
|
|
$result[] = $total_pages;
|
|
}
|
|
|
|
return $result;
|
|
}
|
|
|
|
/**
|
|
* db_where_clause
|
|
* Action: builds and returns a WHERE clause for database queries. All given conditions will be AND'ed.
|
|
* Call: db_where_clause (array $conditions, array $struct)
|
|
* @param array $condition - array('field' => 'value', 'field2' => 'value2, ...)
|
|
* @param array $struct - field structure, used for automatic bool conversion
|
|
* @param string $additional_raw_where - raw snippet to include in the WHERE part - typically needs to start with AND
|
|
* @param array $searchmode - operators to use (=, <, > etc.) - defaults to = if not specified for a field (see
|
|
* $allowed_operators for available operators)
|
|
* Note: the $searchmode operator will only be used if a $condition for that field is set.
|
|
* This also means you'll need to set a (dummy) condition for NULL and NOTNULL.
|
|
*/
|
|
function db_where_clause(array $condition, array $struct, $additional_raw_where = '', array $searchmode = array(), array &$params = [])
|
|
{
|
|
if (count($condition) == 0 && trim($additional_raw_where) == '') {
|
|
throw new Exception("db_where_cond: parameter is an empty array!");
|
|
}
|
|
|
|
$allowed_operators = array('<', '>', '>=', '<=', '=', '!=', '<>', 'CONT', 'LIKE', 'NULL', 'NOTNULL');
|
|
$where_parts = array();
|
|
$having_parts = array();
|
|
|
|
foreach ($condition as $field => $value) {
|
|
if (isset($struct[$field]) && $struct[$field]['type'] == 'bool') {
|
|
$value = (bool) $value; # ensure booleans are booleans.
|
|
}
|
|
$operator = '=';
|
|
if (isset($searchmode[$field])) {
|
|
if (in_array($searchmode[$field], $allowed_operators)) {
|
|
$operator = $searchmode[$field];
|
|
|
|
if ($operator == 'CONT') { # CONT - as in "contains"
|
|
$operator = ' LIKE ';
|
|
$value = '%' . $value . '%';
|
|
} elseif ($operator == 'LIKE') { # LIKE -without adding % wildcards (the search value can contain %)
|
|
$operator = ' LIKE ';
|
|
}
|
|
} else {
|
|
throw new Exception('db_where_clause: Invalid searchmode for ' . $field);
|
|
}
|
|
}
|
|
|
|
if ($operator == "NULL") {
|
|
$querypart = $field . ' IS NULL';
|
|
} elseif ($operator == "NOTNULL") {
|
|
$querypart = $field . ' IS NOT NULL';
|
|
} else {
|
|
// might need other types adding here.
|
|
if (db_pgsql() && isset($struct[$field]) && in_array($struct[$field]['type'], array('ts', 'num')) && $value === '') {
|
|
$querypart = $field . $operator . " NULL";
|
|
} else {
|
|
$param_key = '_wh_' . preg_replace('/[^a-zA-Z0-9_]/', '_', $field);
|
|
$querypart = $field . $operator . " :" . $param_key;
|
|
$params[$param_key] = $value;
|
|
}
|
|
}
|
|
|
|
if (!empty($struct[$field]['select'])) {
|
|
$having_parts[$field] = $querypart;
|
|
} else {
|
|
$where_parts[$field] = $querypart;
|
|
}
|
|
}
|
|
$query = ' WHERE 1=1 ';
|
|
$query .= " $additional_raw_where ";
|
|
if (count($where_parts) > 0) {
|
|
$query .= " AND ( " . join(" AND ", $where_parts) . " ) ";
|
|
}
|
|
if (count($having_parts) > 0) {
|
|
$query .= " HAVING ( " . join(" AND ", $having_parts) . " ) ";
|
|
}
|
|
|
|
return $query;
|
|
}
|
|
|
|
/**
|
|
* Convert a programmatic db table name into what may be the actual name.
|
|
*
|
|
* Takes into consideration any CONF database_prefix or database_tables map
|
|
*
|
|
* If it's a MySQL database, then we return the name with backticks around it (`).
|
|
*
|
|
* @param string database table name.
|
|
* @return string - database table name with appropriate prefix (and quoting if MySQL)
|
|
*/
|
|
function table_by_key($table_key)
|
|
{
|
|
global $CONF;
|
|
|
|
$table = $table_key;
|
|
|
|
if (!empty($CONF['database_tables'][$table_key])) {
|
|
$table = $CONF['database_tables'][$table_key];
|
|
}
|
|
|
|
$table = $CONF['database_prefix'] . $table;
|
|
|
|
if (db_mysql()) {
|
|
return "`" . $table . "`";
|
|
}
|
|
|
|
return $table;
|
|
}
|
|
|
|
|
|
/**
|
|
* check if the database layout is up to date
|
|
* returns the current 'version' value from the config table
|
|
* if $error_out is True (default), exit(1) with a message that recommends to run setup.php.
|
|
* @param bool $error_out
|
|
* @return int
|
|
*/
|
|
function check_db_version($error_out = true)
|
|
{
|
|
global $min_db_version;
|
|
|
|
$table = table_by_key('config');
|
|
|
|
$sql = "SELECT value FROM $table WHERE name = 'version'";
|
|
$row = db_query_one($sql);
|
|
if (isset($row['value'])) {
|
|
$dbversion = (int)$row['value'];
|
|
} else {
|
|
db_execute("INSERT INTO $table (name, value) VALUES ('version', '0')");
|
|
$dbversion = 0;
|
|
}
|
|
|
|
if (($dbversion < $min_db_version) && $error_out == true) {
|
|
echo "ERROR: The PostfixAdmin database layout is outdated (you have r$dbversion, but r$min_db_version is expected).\nPlease run setup.php to upgrade the database.\n";
|
|
exit(1);
|
|
}
|
|
|
|
return $dbversion;
|
|
}
|
|
|
|
|
|
/**
|
|
*
|
|
* Action: Return a string of colored 's that indicate
|
|
* the if an alias goto has an error or is sent to
|
|
* addresses list in show_custom_domains
|
|
*
|
|
* @param string $show_alias
|
|
* @param array $allowed_domains Domains authorized for the caller. Domains not listed here are marked as external.
|
|
* @return string
|
|
*/
|
|
function gen_show_status($show_alias, array $allowed_domains)
|
|
{
|
|
global $CONF;
|
|
$table_alias = table_by_key('alias');
|
|
$stat_string = "";
|
|
|
|
$stat_goto = "";
|
|
$stat_result = db_query_one("SELECT goto FROM $table_alias WHERE address=?", array($show_alias));
|
|
|
|
if ($stat_result) {
|
|
$stat_goto = $stat_result['goto'];
|
|
}
|
|
|
|
$delimiter_regex = null;
|
|
|
|
if (!empty($CONF['recipient_delimiter'])) {
|
|
$delimiter = preg_quote($CONF['recipient_delimiter'], "/");
|
|
$delimiter_regex = '/' . $delimiter . '[^' . $delimiter . '@]*@/';
|
|
}
|
|
|
|
// Only inspect destination records within the caller's authorized domains.
|
|
if ($CONF['show_undeliverable'] == 'YES') {
|
|
$destination_status = ['undeliverable' => false, 'external' => false];
|
|
foreach (explode(',', $stat_goto) as $destination) {
|
|
$destination = trim($destination);
|
|
if (strpos($destination, '@') === false) {
|
|
continue;
|
|
}
|
|
[$local_part, $domain] = explode('@', $destination, 2);
|
|
if ($domain == $CONF['vacation_domain'] || in_array($domain, $CONF['show_undeliverable_exceptions'])) {
|
|
continue;
|
|
}
|
|
if (!in_array($domain, $allowed_domains, true)) {
|
|
$destination_status['external'] = true;
|
|
continue;
|
|
}
|
|
|
|
$alias_domain = db_query_one(
|
|
'SELECT target_domain FROM ' . table_by_key('alias_domain') . ' WHERE alias_domain = ? AND active = ?',
|
|
[$domain, true]
|
|
);
|
|
if ($alias_domain) {
|
|
$domain = $alias_domain['target_domain'];
|
|
if (!in_array($domain, $allowed_domains, true)) {
|
|
$destination_status['external'] = true;
|
|
continue;
|
|
}
|
|
$destination = $local_part . '@' . $domain;
|
|
}
|
|
|
|
$sql = "SELECT address FROM $table_alias WHERE address = ? OR address = ?";
|
|
$values = [$destination, '@' . $domain];
|
|
if ($delimiter_regex !== null) {
|
|
$sql .= ' OR address = ?';
|
|
$values[] = preg_replace($delimiter_regex, '@', $destination);
|
|
}
|
|
if (!db_query_one($sql, $values)) {
|
|
$destination_status['undeliverable'] = true;
|
|
}
|
|
}
|
|
foreach ($destination_status as $status => $present) {
|
|
if ($present) {
|
|
$tooltip = htmlspecialchars(Config::lang('pStatus_' . $status . '_tooltip'), ENT_QUOTES, 'UTF-8');
|
|
$color = htmlspecialchars($CONF['show_' . $status . '_color'], ENT_QUOTES, 'UTF-8');
|
|
$stat_string .= "<span role='img' aria-label='$tooltip' title='$tooltip' style='background-color:$color'>" .
|
|
$CONF['show_status_text'] . '</span> ';
|
|
} else {
|
|
$stat_string .= $CONF['show_status_text'] . ' ';
|
|
}
|
|
}
|
|
}
|
|
|
|
// Vacation CHECK
|
|
if (array_key_exists('show_vacation', $CONF) && $CONF['show_vacation'] == 'YES') {
|
|
$stat_result = db_query_one("SELECT * FROM " . table_by_key('vacation') . " WHERE email = ? AND active = ? ", array($show_alias, true));
|
|
if (!empty($stat_result)) {
|
|
$stat_string .= "<span style='background-color:" . $CONF['show_vacation_color'] . "'>" . $CONF['show_status_text'] . "</span> ";
|
|
} else {
|
|
$stat_string .= $CONF['show_status_text'] . " ";
|
|
}
|
|
}
|
|
|
|
// Disabled CHECK
|
|
if (array_key_exists('show_disabled', $CONF) && $CONF['show_disabled'] == 'YES') {
|
|
$stat_result = db_query_one(
|
|
"SELECT * FROM " . table_by_key('mailbox') . " WHERE username = ? AND active = ?",
|
|
array($show_alias, false)
|
|
);
|
|
if (!empty($stat_result)) {
|
|
$stat_string .= "<span style='background-color:" . $CONF['show_disabled_color'] . "'>" . $CONF['show_status_text'] . "</span> ";
|
|
} else {
|
|
$stat_string .= $CONF['show_status_text'] . " ";
|
|
}
|
|
}
|
|
|
|
// Expired CHECK
|
|
if (Config::has('password_expiration') && Config::bool('password_expiration') && Config::bool('show_expired')) {
|
|
$now = 'now()';
|
|
if (db_sqlite()) {
|
|
$now = "datetime('now')";
|
|
}
|
|
|
|
$mailbox_table = table_by_key('mailbox');
|
|
$domain_table = table_by_key('domain');
|
|
$stat_result = db_query_one(
|
|
"SELECT $mailbox_table.username FROM $mailbox_table " .
|
|
"INNER JOIN $domain_table ON $domain_table.domain = $mailbox_table.domain " .
|
|
"WHERE $mailbox_table.username = ? AND $mailbox_table.password_expiry <= $now " .
|
|
"AND $domain_table.password_expiry > 0 AND $mailbox_table.active = ?",
|
|
array($show_alias, true)
|
|
);
|
|
|
|
if (!empty($stat_result)) {
|
|
$stat_string .= "<span style='background-color:" . $CONF['show_expired_color'] . "'>" . $CONF['show_status_text'] . "</span> ";
|
|
} else {
|
|
$stat_string .= $CONF['show_status_text'] . " ";
|
|
}
|
|
}
|
|
|
|
// POP/IMAP CHECK
|
|
if ($CONF['show_popimap'] == 'YES') {
|
|
$stat_delimiter = "";
|
|
if (!empty($CONF['recipient_delimiter']) && isset($delimiter_regex)) {
|
|
$stat_delimiter = ',' . preg_replace($delimiter_regex, "@", $stat_goto);
|
|
}
|
|
|
|
//if the address passed in appears in its own goto field, its POP/IMAP
|
|
# TODO: or not (might also be an alias loop) -> check mailbox table!
|
|
if (preg_match('/,' . $show_alias . ',/', ',' . $stat_goto . $stat_delimiter . ',')) {
|
|
$stat_string .= "<span style='background-color:" . $CONF['show_popimap_color'] .
|
|
"'>" . $CONF['show_status_text'] . "</span> ";
|
|
} else {
|
|
$stat_string .= $CONF['show_status_text'] . " ";
|
|
}
|
|
}
|
|
|
|
// CUSTOM DESTINATION CHECK
|
|
if (count($CONF['show_custom_domains']) > 0) {
|
|
for ($i = 0; $i < sizeof($CONF['show_custom_domains']); $i++) {
|
|
if (preg_match('/^.*' . $CONF['show_custom_domains'][$i] . '.*$/', $stat_goto)) {
|
|
$stat_string .= "<span style='background-color:" . $CONF['show_custom_colors'][$i] .
|
|
"'>" . $CONF['show_status_text'] . "</span> ";
|
|
} else {
|
|
$stat_string .= $CONF['show_status_text'] . " ";
|
|
}
|
|
}
|
|
} else {
|
|
$stat_string .= " ";
|
|
}
|
|
|
|
// $stat_string .= "<span style='background-color:green'> </span> " .
|
|
// "<span style='background-color:blue'> </span> ";
|
|
return $stat_string;
|
|
}
|
|
|
|
/**
|
|
* @return string
|
|
*/
|
|
function getRemoteAddr()
|
|
{
|
|
$REMOTE_ADDR = 'localhost';
|
|
if (isset($_SERVER['REMOTE_ADDR'])) {
|
|
$REMOTE_ADDR = $_SERVER['REMOTE_ADDR'];
|
|
}
|
|
|
|
return $REMOTE_ADDR;
|
|
}
|
|
|
|
|
|
/**
|
|
* @param array $server
|
|
* @return string URL to Postfixadmin - will always end in a '/'
|
|
*/
|
|
function getSiteUrl(array $server = []): string
|
|
{
|
|
$config = Config::getInstance()->getAll();
|
|
|
|
if (isset($config['site_url']) && is_string($config['site_url'])) {
|
|
$url = $config['site_url'];
|
|
if (!empty($url)) {
|
|
return $url;
|
|
}
|
|
}
|
|
|
|
if (empty($server)) {
|
|
$server = $_SERVER;
|
|
}
|
|
|
|
// ideally need to support installation unnder a random prefix
|
|
// - https://example.com/my-postfixadmin-3.1.2/index.php
|
|
// - https://example.com/my-postfixadmin-3.1.2/users/password-recover.php
|
|
// in either case, we want https://example.com/my-postfixadmin-3.1.2/
|
|
|
|
$uri = dirname($server['REQUEST_URI']);
|
|
if (preg_match('!/users/.*.php!', $uri)) {
|
|
$uri = dirname($uri);
|
|
}
|
|
|
|
// ensure it ends with a /
|
|
if (substr($uri, -1, 1) !== '/') {
|
|
$uri = $uri . '/';
|
|
}
|
|
|
|
|
|
$https = isset($server['HTTPS']) && $server['HTTPS'] == 'on' ? 'https' : 'http';
|
|
|
|
if (isset($server['REQUEST_SCHEME'])) {
|
|
$https = $server['REQUEST_SCHEME'];
|
|
}
|
|
|
|
return $https . '://' . $server['HTTP_HOST'] . $uri;
|
|
}
|
|
|
|
/**
|
|
* Return the configured canonical URL used in password-recovery messages.
|
|
*
|
|
* Request headers are deliberately not used here because recovery links carry
|
|
* a credential and must not depend on an untrusted Host value.
|
|
*/
|
|
function getPasswordRecoverySiteUrl(): string
|
|
{
|
|
$url = Config::read_string('site_url');
|
|
$parts = parse_url($url);
|
|
|
|
if ($url === '' || !is_array($parts) || empty($parts['host']) ||
|
|
!isset($parts['scheme']) || !in_array(strtolower($parts['scheme']), ['http', 'https'], true) ||
|
|
isset($parts['user']) || isset($parts['pass']) || isset($parts['query']) || isset($parts['fragment'])) {
|
|
throw new RuntimeException("A valid canonical site_url is required for password recovery");
|
|
}
|
|
|
|
if (!str_ends_with($url, '/')) {
|
|
$url .= '/';
|
|
}
|
|
|
|
return $url;
|
|
}
|
|
|
|
/* vim: set expandtab softtabstop=4 tabstop=4 shiftwidth=4: */
|