Files
Rodrigo Cortés Cano ff0ae9ddbe Clarify alias destination status indicators (#1150)
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
2026-10-03 11:20:28 +01:00

615 lines
27 KiB
PHP

<?php
# $Id$
/**
* Handlers User level alias actions - e.g. add alias, get aliases, update etc.
*/
class AliasHandler extends PFAHandler
{
protected string $db_table = 'alias';
protected string $id_field = 'address';
protected ?string $domain_field = 'domain';
protected ?string $user_field = 'address';
protected array $searchfields = array('address', 'goto');
/**
*
* @public
*/
public $return = null;
protected function initStruct()
{
# hide 'goto_mailbox' if $this->new
# (for existing aliases, init() hides it for non-mailbox aliases)
$mbgoto = 1 - $this->new;
$this->struct = array(
# field name allow display in... type $PALANG label $PALANG description default / ...
# editing? form list
'status' => self::pacol(0, 0, 0, 'html', '' , '' , '', array(), 1),
'address' => self::pacol($this->new, 1, 1, 'mail', 'alias' , 'pCreate_alias_catchall_text'),
'localpart' => self::pacol($this->new, 0, 0, 'text', 'alias' , 'pCreate_alias_catchall_text' , '',
/*options*/ array(),
/*not_in_db*/ 1),
'domain' => self::pacol($this->new, 0, 1, 'enum', 'domain' , '' , '',
/*options*/ $this->allowed_domains),
'description' => self::pacol(1, 1, 1, 'text', 'description' , ''),
'goto' => self::pacol(1, 1, 1, 'txtl', 'to' , 'pEdit_alias_help' , array()),
'goto_default' => self::pacol($this->new, $this->new, 0, 'bool', 'alias_goto_default' , '' , 0,
# ticking this stores the 'goto' value of the alias being created as the default for
# the next one (see postSave()). webformConfig() fills options['stored'] with the
# value that is currently stored, which editform.tpl displays next to the checkbox.
/*options*/ array('stored' => ''),
/*not_in_db*/ 1),
'is_mailbox' => self::pacol(0, 0, 1, 'int', '' , '' , 0 ,
# technically 'is_mailbox' is bool, but the automatic bool conversion breaks the query. Flagging it as int avoids this problem.
# Maybe having a vbool type (without the automatic conversion) would be cleaner - we'll see if we need it.
/*options*/ array(),
/*not_in_db*/ 0,
/*dont_write_to_db*/ 1,
/*select*/ 'coalesce(__is_mailbox,0) as is_mailbox'),
/*extrafrom set via set_is_mailbox_extrafrom() */
'__mailbox_username' => self::pacol(0, 0, 1, 'vtxt', '' , '' , 0), # filled via is_mailbox
'goto_mailbox' => self::pacol($mbgoto, $mbgoto,$mbgoto,'bool', 'pEdit_alias_forward_and_store' , '' , 0,
/*options*/ array(),
/*not_in_db*/ 1), # read_from_db_postprocess() sets the value
'on_vacation' => self::pacol(1, 0, 1, 'bool', 'pUsersMenu_vacation' , '' , 0 ,
/*options*/ array(),
/*not_in_db*/ 1), # read_from_db_postprocess() sets the value - TODO: read active flag from vacation table instead?
'created' => self::pacol(0, 0, 0, 'ts', 'created' , ''),
'modified' => self::pacol(0, 0, 1, 'ts', 'last_modified' , ''),
'active' => self::pacol(1, 1, 1, 'bool', 'active' , '' , 1),
'_can_edit' => self::pacol(0, 0, 1, 'vnum', '' , '' , 0, array(), 0, 0, '1 as _can_edit'),
'_can_delete' => self::pacol(0, 0, 1, 'vnum', '' , '' , 0, array(), 0, 0, ($this->is_admin ? '1' : '0') . ' as _can_delete'), # read_from_db_postprocess() updates the value
# aliases listed in $CONF[default_aliases] are read-only for domain admins if $CONF[special_alias_control] is NO.
);
# Users may only change their forwarding targets and whether mail is
# also delivered locally. Administrative alias fields stay read-only.
if (!$this->is_admin) {
$this->struct['address']['editable'] = 0;
$this->struct['address']['display_in_form'] = 1;
$this->struct['address']['label'] = Config::lang('pOverview_mailbox_username');
$this->struct['address']['desc'] = '';
# Keep the user list focused on the only editable forwarding data.
foreach (['domain', 'description', 'on_vacation', 'modified', 'active'] as $field) {
$this->struct[$field]['display_in_list'] = 0;
}
$this->struct['description']['editable'] = 0;
$this->struct['description']['display_in_form'] = 0;
$this->struct['active']['editable'] = 0;
$this->struct['active']['display_in_form'] = 0;
}
$this->set_is_mailbox_extrafrom();
}
/*
* set $this->struct['is_mailbox']['extrafrom'] based on the search conditions.
* If a listing for a specific domain is requested, optimize the subquery to only return mailboxes from that domain.
* This doesn't change the result of the main query, but improves the performance a lot on setups with lots of mailboxes.
* When using this function to optimize the is_mailbox extrafrom, don't forget to reset it to the default value
* (all domains for this admin) afterwards.
*/
private function set_is_mailbox_extrafrom($condition = array(), $searchmode = array())
{
$extrafrom = 'LEFT JOIN ( ' .
' SELECT 1 as __is_mailbox, username as __mailbox_username ' .
' FROM ' . table_by_key('mailbox') .
' WHERE username IS NOT NULL ';
// Note: extrafrom is a raw SQL string stored in struct with no mechanism to attach params.
// Values here are internal (allowed_domains from session), not user input, so escape_string is acceptable.
if (isset($condition['domain']) && !isset($searchmode['domain']) && in_array($condition['domain'], $this->allowed_domains)) {
$v = array_map('escape_string', array($condition['domain']));
$extrafrom .= " AND $this->domain_field IN ('" . implode("','", $v) . "') ";
} else {
$v = array_map('escape_string', $this->allowed_domains);
$extrafrom .= " AND $this->domain_field IN ('" . implode("','", $v) . "') ";
}
$extrafrom .= ' ) AS __mailbox ON __mailbox_username = address';
$this->struct['is_mailbox']['extrafrom'] = $extrafrom;
}
protected function initMsg()
{
$this->msg['error_already_exists'] = 'email_address_already_exists';
$this->msg['error_does_not_exist'] = 'alias_does_not_exist';
$this->msg['confirm_delete'] = 'confirm_delete_alias';
$this->msg['list_header'] = 'pOverview_alias_title';
if ($this->new) {
$this->msg['logname'] = 'create_alias';
$this->msg['store_error'] = 'pCreate_alias_result_error';
$this->msg['successmessage'] = 'pCreate_alias_result_success';
} else {
$this->msg['logname'] = 'edit_alias';
$this->msg['store_error'] = 'pEdit_alias_result_error';
$this->msg['successmessage'] = 'alias_updated';
}
if (!$this->is_admin) {
$this->msg['can_create'] = false;
}
}
public function webformConfig()
{
if ($this->new) { # the webform will display a localpart field + domain dropdown on $new
$this->struct['address']['display_in_form'] = 0;
$this->struct['localpart']['display_in_form'] = 1;
$this->struct['domain']['display_in_form'] = 1;
# prefill the 'goto' ("To") field from the default this admin stored when creating
# an earlier alias. This reuses the generic field-default mechanism, so the form
# itself needs no special casing.
$current_user = $this->preference_owner();
if ($current_user != '') {
$stored = get_admin_pref($current_user, 'alias_goto_default', '');
if ($stored !== '') {
$this->struct['goto']['default'] = explode(',', $stored);
# displayed next to the checkbox, together with a button to delete it again
$this->struct['goto_default']['options']['stored'] = join(', ', explode(',', $stored));
}
}
}
if ($this->is_admin && Config::bool('show_status')) {
$this->struct['status']['display_in_list'] = 1;
$this->struct['status']['label'] = ' ';
}
$listview = $this->is_admin ? 'list-virtual.php' : 'users/main.php';
$formtitle_edit = $this->is_admin ? 'pEdit_alias_welcome' : 'pUsersMenu_edit_alias';
return array(
# $PALANG labels
'formtitle_create' => 'pMain_create_alias',
'formtitle_edit' => $formtitle_edit,
'create_button' => 'add_alias',
# various settings
'required_role' => 'admin',
'listview' => $listview,
'early_init' => 0,
'prefill' => array('domain'),
'user_hardcoded_field' => 'address',
);
}
/**
* AliasHandler needs some special handling in init() and therefore overloads the function.
* It also calls parent::init()
*/
public function init(string $id): bool
{
if (!$this->is_admin) {
if (!Config::bool('edit_alias') || strtolower($id) !== strtolower($this->username)) {
$this->errormsg[] = Config::lang_f('pEdit_alias_result_error', $id);
return false;
}
}
$bits = explode('@', $id);
if (sizeof($bits) == 2) {
$local_part = $bits[0];
$domain = $bits[1];
if ($local_part == '*') { # catchall - postfix expects '@domain', not '*@domain'
$id = '@' . $domain;
}
}
$retval = parent::init($id);
if (!$retval) {
return false;
} # parent::init() failed, no need to continue
# hide 'goto_mailbox' for non-mailbox aliases
# parent::init called view() before, so we can rely on having $this->result filled
# (only validate_new_id() is called from parent::init and could in theory change $this->result)
if ($this->new || $this->result['is_mailbox'] == 0) {
$this->struct['goto_mailbox']['editable'] = 0;
$this->struct['goto_mailbox']['display_in_form'] = 0;
$this->struct['goto_mailbox']['display_in_list'] = 0;
}
if (!$this->new && $this->result['is_mailbox'] && $this->admin_username != '' && !authentication_has_role('global-admin')) {
# domain admins are not allowed to change mailbox alias $CONF['alias_control_admin'] = NO
# TODO: apply the same restriction to superadmins?
if (!Config::bool('alias_control_admin')) {
# TODO: make translateable
$this->errormsg[] = "Domain administrators do not have the ability to edit user's aliases (check config.inc.php - alias_control_admin)";
return false;
}
}
return $retval;
}
protected function domain_from_id()
{
list(/*NULL*/, $domain) = explode('@', $this->id);
return $domain;
}
protected function validate_new_id()
{
if (!$this->is_admin) {
$this->errormsg[$this->id_field] = Config::lang_f('edit_not_allowed', $this->id);
return false;
}
if ($this->id == '') {
$this->errormsg[$this->id_field] = Config::lang('pCreate_alias_address_text_error1');
return false;
}
list($local_part, $domain) = explode('@', $this->id);
# TODO: already checked in set() - does it make sense to check it here also? Only advantage: it's an early check
# if (!in_array($domain, $this->allowed_domains)) {
# $this->errormsg[] = Config::lang('pCreate_alias_address_text_error1');
# return false;
# }
if ($local_part != '') { # catchall
$email_check = check_email($this->id);
if ($email_check != '') {
$this->errormsg[$this->id_field] = $email_check;
return false;
}
}
if (!$this->create_allowed($domain)) {
$this->errormsg[$this->id_field] = Config::lang('pCreate_alias_address_text_error3');
return false;
}
return true;
}
/**
* check number of existing aliases for this domain - is one more allowed?
*/
private function create_allowed($domain)
{
if ($this->called_by == 'MailboxHandler') {
return true;
} # always allow creating an alias for a mailbox
$limit = get_domain_properties($domain);
if ($limit['aliases'] == 0) {
return true;
} # unlimited
if ($limit['aliases'] < 0) {
return false;
} # disabled
if ($limit['alias_count'] >= $limit['aliases']) {
return false;
}
return true;
}
/**
* merge localpart and domain to address
* called by edit.php (if id_field is editable and hidden in editform) _before_ ->init
*/
public function mergeId($values)
{
if ($this->struct['localpart']['display_in_form'] == 1 && $this->struct['domain']['display_in_form']) { # webform mode - combine to 'address' field
if (empty($values['localpart']) || empty($values['domain'])) { # localpart or domain not set
return "";
}
if ($values['localpart'] == '*') {
$values['localpart'] = '';
} # catchall
return $values['localpart'] . '@' . $values['domain'];
} else {
return $values[$this->id_field];
}
}
protected function setmore(array $values)
{
if ($this->new) {
if ($this->struct['address']['display_in_form'] == 1) { # default mode - split off 'domain' field from 'address' # TODO: do this unconditional?
list(/*NULL*/, $domain) = explode('@', $values['address']);
$this->values['domain'] = $domain;
}
}
if (! $this->new) { # edit mode - preserve vacation and mailbox alias if they were included before
$old_ah = new AliasHandler();
if (!$old_ah->init($this->id)) {
$this->errormsg[] = $old_ah->errormsg[0];
} elseif (!$old_ah->view()) {
$this->errormsg[] = $old_ah->errormsg[0];
} else {
$oldvalues = $old_ah->result();
if (!isset($values['goto'])) { # no new value given?
$values['goto'] = $oldvalues['goto'];
}
# Internal vacation targets are managed exclusively by the
# vacation flow. Ignore submitted copies and add the target
# back only when the stored vacation state says it is active.
$values['goto'] = array_values(array_unique($values['goto']));
$values['goto'] = array_values(array_diff($values['goto'], [$this->getVacationAlias()]));
if (!isset($values['on_vacation'])) { # no new value given?
$values['on_vacation'] = $oldvalues['on_vacation'];
}
if ($values['on_vacation']) {
$values['goto'][] = $this->getVacationAlias();
}
if ($oldvalues['is_mailbox']) { # alias belongs to a mailbox - add/keep mailbox to/in goto
if (!isset($values['goto_mailbox'])) { # no new value given?
$values['goto_mailbox'] = $oldvalues['goto_mailbox'];
}
if ($values['goto_mailbox']) {
$values['goto'][] = $this->id;
# if the alias points to the mailbox, don't display the "empty goto" error message
if (isset($this->errormsg['goto']) && $this->errormsg['goto'] == Config::lang('pEdit_alias_goto_text_error1')) {
unset($this->errormsg['goto']);
}
}
}
}
}
$this->values['goto'] = join(',', $values['goto']);
}
/**
* the admin_preferences row the logged-in user owns.
* For admins the login is stored in $this->admin_username; $this->username is only
* set for (non-admin) mailbox users - fall back to whichever of the two is filled.
* @return string - empty if no user is logged in (e.g. called from a script)
*/
private function preference_owner(): string
{
return $this->admin_username != '' ? $this->admin_username : $this->username;
}
protected function postSave(): bool
{
# TODO: if alias belongs to a mailbox, update mailbox active status
# store this admin's default for the alias 'goto' field if they ticked the box.
# Only on $new: 'goto_default' is not displayed when editing an existing alias, and
# aliases created by MailboxHandler never set it, so both leave the stored value alone.
# Deleting it again is handled by delete-preference.php.
if ($this->new && !empty($this->values['goto_default'])) {
$current_user = $this->preference_owner();
if ($current_user != '') {
set_admin_pref($current_user, 'alias_goto_default', $this->values['goto']);
}
}
return true;
}
protected function read_from_db_postprocess($db_result)
{
foreach ($db_result as $key => $_) {
# split comma-separated 'goto' into an array
$goto = $db_result[$key]['goto'] ?? null;
if (is_string($goto)) {
$db_result[$key]['goto'] = explode(',', $goto);
}
# Vacation enabled?
list($db_result[$key]['on_vacation'], $db_result[$key]['goto']) = remove_from_array($db_result[$key]['goto'], $this->getVacationAlias());
# if it is a mailbox, does the alias point to the mailbox?
if ($db_result[$key]['is_mailbox']) {
# this intentionally does not match mailbox targets with recipient delimiter.
# if it would, we would have to make goto_mailbox a text instead of a bool (which would annoy 99% of the users)
list($db_result[$key]['goto_mailbox'], $db_result[$key]['goto']) = remove_from_array($db_result[$key]['goto'], $key);
} else { # not a mailbox
$db_result[$key]['goto_mailbox'] = 0;
}
# editing a default alias (postmaster@ etc.) is only allowed if special_alias_control is allowed or if the user is a superadmin
$tmp = preg_split('/\@/', $db_result[$key]['address']);
if (!$this->is_superadmin && !Config::bool('special_alias_control') && array_key_exists($tmp[0], Config::read_array('default_aliases'))) {
$db_result[$key]['_can_edit'] = 0;
$db_result[$key]['_can_delete'] = 0;
}
if ($this->struct['status']['display_in_list'] && Config::bool('show_status')) {
$db_result[$key]['status'] = gen_show_status($db_result[$key]['address'], $this->allowed_domains);
}
}
return $db_result;
}
private function condition_ignore_mailboxes($condition, $searchmode)
{
# only list aliases that do not belong to mailboxes
if (is_array($condition)) {
$condition['__mailbox_username'] = 1;
$searchmode['__mailbox_username'] = 'NULL';
} else {
if ($condition != '') {
$condition = " ( $condition ) AND ";
}
$condition = " $condition __mailbox_username IS NULL ";
}
return array($condition, $searchmode);
}
public function getList($condition, $searchmode = array(), $limit = -1, $offset = -1): bool
{
# Admin alias lists intentionally exclude mailbox aliases. A user must
# see their own mailbox alias, with PFAHandler::$user_field providing
# the ownership restriction.
if ($this->is_admin) {
list($condition, $searchmode) = $this->condition_ignore_mailboxes($condition, $searchmode);
}
$this->set_is_mailbox_extrafrom($condition, $searchmode);
$result = parent::getList($condition, $searchmode, $limit, $offset);
$this->set_is_mailbox_extrafrom(); # reset to default
return $result;
}
public function getPagebrowser($condition, $searchmode = array())
{
if ($this->is_admin) {
list($condition, $searchmode) = $this->condition_ignore_mailboxes($condition, $searchmode);
}
$this->set_is_mailbox_extrafrom($condition, $searchmode);
$result = parent::getPagebrowser($condition, $searchmode);
$this->set_is_mailbox_extrafrom(); # reset to default
return $result;
}
protected function _validate_goto($field, $val)
{
if (count($val) == 0) {
# empty is ok for mailboxes - this is checked in setmore() which can clear the error message
$this->errormsg[$field] = Config::lang('pEdit_alias_goto_text_error1');
return false;
}
$errors = array();
foreach ($val as $singlegoto) {
# setmore() removes this internal target and restores it only from
# the stored vacation state, so it must not be validated as a
# user-managed external destination first.
if (!$this->new && $singlegoto === $this->getVacationAlias()) {
continue;
}
if (substr($this->id, 0, 1) == '@' && substr($singlegoto, 0, 1) == '@') { # domain-wide forward - check only the domain part
# only allowed if $this->id is a catchall
# Note: alias domains are better, but we should keep this way supported for backward compatibility
# and because alias domains can't forward to external domains
list(/*NULL*/, $domain) = explode('@', $singlegoto);
$domain_check = check_domain($domain);
if ($domain_check != '') {
$errors[] = "$singlegoto: $domain_check";
}
$localaliasonly_check = check_localaliasonly($domain);
if ($localaliasonly_check != '') {
$errors[] = "$singlegoto: $localaliasonly_check";
}
} else {
$email_check = check_email($singlegoto);
// preg_match -> allows for redirect to a local system account.
if ($email_check != '' && !preg_match('/^[a-z0-9]+$/', $singlegoto)) {
$errors[] = "$singlegoto: $email_check";
}
$localaliasonly_check = check_localaliasonly($singlegoto);
if ($localaliasonly_check != '') {
$errors[] = "$singlegoto: $localaliasonly_check";
}
}
if ($this->called_by != "MailboxHandler" && $this->id == $singlegoto) {
// The MailboxHandler needs to create an alias that points to itself (for the mailbox)
// Otherwise, disallow such aliases as they cause severe trouble in the mail system
$errors[] = "$singlegoto: " . Config::Lang('alias_points_to_itself');
}
}
if (count($errors)) {
$this->errormsg[$field] = join(" ", $errors); # TODO: find a way to display multiple error messages per field
return false;
} else {
return true;
}
}
/**
* on $this->new, set localpart based on address
*/
protected function _missing_localpart()
{
if (isset($this->RAWvalues['address'])) {
$parts = explode('@', $this->RAWvalues['address']);
if (count($parts) == 2) {
$this->RAWvalues['localpart'] = $parts[0];
}
}
}
/**
* on $this->new, set domain based on address
*/
protected function _missing_domain()
{
if (isset($this->RAWvalues['address'])) {
$parts = explode('@', $this->RAWvalues['address']);
if (count($parts) == 2) {
$this->RAWvalues['domain'] = $parts[1];
}
}
}
/**
* Returns the vacation alias for this user.
* i.e. if this user's username was roger@example.com, and the autoreply domain was set to
* autoreply.fish.net in config.inc.php we'd return roger#example.com@autoreply.fish.net
*
* @return string an email alias.
*/
protected function getVacationAlias()
{
$vacation_goto = str_replace('@', '#', $this->id ?? '');
return $vacation_goto . '@' . Config::read_string('vacation_domain');
}
/**
* @return boolean
*/
public function delete()
{
if (! $this->view()) {
$this->errormsg[] = Config::Lang('alias_does_not_exist');
return false;
}
if ($this->result['is_mailbox']) {
$this->errormsg[] = Config::Lang('mailbox_alias_cant_be_deleted');
return false;
}
if (!$this->can_delete) {
$this->errormsg[] = Config::Lang_f('protected_alias_cant_be_deleted', $this->id);
return false;
}
db_delete('alias', 'address', $this->id);
list(/*NULL*/, $domain) = explode('@', $this->id);
db_log($domain, 'delete_alias', $this->id);
$this->infomsg[] = Config::Lang_f('pDelete_delete_success', $this->id);
return true;
}
}
/* vim: set expandtab softtabstop=4 tabstop=4 shiftwidth=4: */