git subrepo commit (merge) mailcow/src/mailcow-dockerized

subrepo:
  subdir:   "mailcow/src/mailcow-dockerized"
  merged:   "81fb18894"
upstream:
  origin:   "https://github.com/mailcow/mailcow-dockerized.git"
  branch:   "master"
  commit:   "4ca02ecee"
git-subrepo:
  version:  "0.4.6"
  origin:   "???"
  commit:   "???"

Update to upstream 2026-10.  Local patches re-applied by hand
(no Unbound DNS for containers, IPv6 off by default, fake-MySQL
stubs in dockerapi, Postfix overrides, no .env symlink); dropped
the unused dovecot and clamd Dockerfile patches.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Change-Id: I2c2c194d1d436b841358685f5f94aef09eb19ae8
diff --git a/mailcow/src/mailcow-dockerized/data/web/inc/functions.mailbox.inc.php b/mailcow/src/mailcow-dockerized/data/web/inc/functions.mailbox.inc.php
index 00c11de..37ccbd8 100644
--- a/mailcow/src/mailcow-dockerized/data/web/inc/functions.mailbox.inc.php
+++ b/mailcow/src/mailcow-dockerized/data/web/inc/functions.mailbox.inc.php
@@ -4,9 +4,15 @@
   global $redis;

   global $lang;

   global $MAILBOX_DEFAULT_ATTRIBUTES;

+  global $iam_settings;

+

   $_data_log = $_data;

   !isset($_data_log['password']) ?: $_data_log['password'] = '*';

   !isset($_data_log['password2']) ?: $_data_log['password2'] = '*';

+

+  // Track mailboxes affected by alias operations for incremental SOGo updates

+  $update_sogo_mailboxes = array();

+

   switch ($_action) {

     case 'add':

       switch ($_type) {

@@ -35,19 +41,29 @@
           else {

             $username = $_SESSION['mailcow_cc_username'];

           }

-          if (isset($_data["validity"]) && !filter_var($_data["validity"], FILTER_VALIDATE_INT, array('options' => array('min_range' => 1, 'max_range' => 87600)))) {

-            $_SESSION['return'][] = array(

-              'type' => 'danger',

-              'log' => array(__FUNCTION__, $_action, $_type, $_data_log, $_attr),

-              'msg' => 'validity_missing'

-            );

-            return false;

+          if (isset($_data["validity"])) {

+            if (!filter_var($_data["validity"], FILTER_VALIDATE_INT, array('options' => array('min_range' => 1, 'max_range' => 87600)))) {

+              $_SESSION['return'][] = array(

+                'type' => 'danger',

+                'log' => array(__FUNCTION__, $_action, $_type, $_data_log, $_attr),

+                'msg' => 'validity_missing'

+              );

+              return false;

+            }

           }

           else {

             // Default to 1 yr

             $_data["validity"] = 8760;

           }

+          if (isset($_data["permanent"]) && filter_var($_data["permanent"], FILTER_VALIDATE_BOOL)) {

+            $permanent = 1;

+          }

+          else {

+            $permanent = 0;

+          }

           $domain = $_data['domain'];

+          // spamalias.description is NOT NULL, an absent description must not become a null insert

+          $description = $_data['description'] ?? '';

           $valid_domains[] = mailbox('get', 'mailbox_details', $username)['domain'];

           $valid_alias_domains = user_get_alias_details($username)['alias_domains'];

           if (!empty($valid_alias_domains)) {

@@ -62,12 +78,14 @@
             return false;

           }

           $validity = strtotime("+" . $_data["validity"] . " hour");

-          $stmt = $pdo->prepare("INSERT INTO `spamalias` (`address`, `goto`, `validity`) VALUES

-            (:address, :goto, :validity)");

+          $stmt = $pdo->prepare("INSERT INTO `spamalias` (`address`, `description`, `goto`, `validity`, `permanent`) VALUES

+            (:address, :description, :goto, :validity, :permanent)");

           $stmt->execute(array(

             ':address' => readable_random_string(rand(rand(3, 9), rand(3, 9))) . '.' . readable_random_string(rand(rand(3, 9), rand(3, 9))) . '@' . $domain,

+            ':description' => $description,

             ':goto' => $username,

-            ':validity' => $validity

+            ':validity' => $validity,

+            ':permanent' => $permanent

           ));

           $_SESSION['return'][] = array(

             'type' => 'success',

@@ -184,6 +202,7 @@
             'msg' => 'global_filter_written'

           );

           return true;

+        break;

         case 'filter':

           $sieve = new Sieve\SieveParser();

           if (!isset($_SESSION['acl']['filters']) || $_SESSION['acl']['filters'] != "1" ) {

@@ -679,15 +698,17 @@
           return true;

         break;

         case 'alias':

-          $addresses  = array_map('trim', preg_split( "/( |,|;|\n)/", $_data['address']));

-          $gotos      = array_map('trim', preg_split( "/( |,|;|\n)/", $_data['goto']));

-          $active = intval($_data['active']);

-          $sogo_visible = intval($_data['sogo_visible']);

-          $goto_null = intval($_data['goto_null']);

-          $goto_spam = intval($_data['goto_spam']);

-          $goto_ham = intval($_data['goto_ham']);

+          $addresses       = array_map('trim', preg_split( "/( |,|;|\n)/", $_data['address']));

+          $gotos           = array_map('trim', preg_split( "/( |,|;|\n)/", $_data['goto']));

+          $internal        = intval($_data['internal']);

+          $active          = intval($_data['active']);

+          $sender_allowed  = intval($_data['sender_allowed']);

+          $sogo_visible    = intval($_data['sogo_visible']);

+          $goto_null       = intval($_data['goto_null']);

+          $goto_spam       = intval($_data['goto_spam']);

+          $goto_ham        = intval($_data['goto_ham']);

           $private_comment = $_data['private_comment'];

-          $public_comment = $_data['public_comment'];

+          $public_comment  = $_data['public_comment'];

           if (strlen($private_comment) > 160 | strlen($public_comment) > 160){

             $_SESSION['return'][] = array(

               'type' => 'danger',

@@ -729,6 +750,18 @@
               $goto_domain = idn_to_ascii(substr(strstr($goto, '@'), 1), 0, INTL_IDNA_VARIANT_UTS46);

               $goto_local_part = strstr($goto, '@', true);

               $goto = $goto_local_part.'@'.$goto_domain;

+              // Deny external goto domains: global switch (all roles) overrides the per-DA ACL

+              if (($GLOBALS['ALIAS_DISABLE_EXTERNAL_DOMAINS'] === true ||

+                  (isset($_SESSION['acl']['alias_external_goto']) && $_SESSION['acl']['alias_external_goto'] != "1")) &&

+                  !is_local_mailcow_domain($goto_domain)) {

+                $_SESSION['return'][] = array(

+                  'type' => 'danger',

+                  'log' => array(__FUNCTION__, $_action, $_type, $_data_log, $_attr),

+                  'msg' => array('external_goto_denied', htmlspecialchars($goto))

+                );

+                unset($gotos[$i]);

+                continue;

+              }

               $stmt = $pdo->prepare("SELECT `username` FROM `mailbox`

                 WHERE `kind` REGEXP 'location|thing|group'

                   AND `username`= :goto");

@@ -837,8 +870,8 @@
               );

               continue;

             }

-            $stmt = $pdo->prepare("INSERT INTO `alias` (`address`, `public_comment`, `private_comment`, `goto`, `domain`, `sogo_visible`, `active`)

-              VALUES (:address, :public_comment, :private_comment, :goto, :domain, :sogo_visible, :active)");

+            $stmt = $pdo->prepare("INSERT INTO `alias` (`address`, `public_comment`, `private_comment`, `goto`, `domain`, `sogo_visible`, `internal`, `sender_allowed`, `active`)

+              VALUES (:address, :public_comment, :private_comment, :goto, :domain, :sogo_visible, :internal, :sender_allowed, :active)");

             if (!filter_var($address, FILTER_VALIDATE_EMAIL) === true) {

               $stmt->execute(array(

                 ':address' => '@'.$domain,

@@ -848,6 +881,8 @@
                 ':goto' => $goto,

                 ':domain' => $domain,

                 ':sogo_visible' => $sogo_visible,

+                ':internal' => $internal,

+                ':sender_allowed' => $sender_allowed,

                 ':active' => $active

               ));

             }

@@ -859,6 +894,8 @@
                 ':goto' => $goto,

                 ':domain' => $domain,

                 ':sogo_visible' => $sogo_visible,

+                ':internal' => $internal,

+                ':sender_allowed' => $sender_allowed,

                 ':active' => $active

               ));

             }

@@ -868,6 +905,17 @@
               'log' => array(__FUNCTION__, $_action, $_type, $_data_log, $_attr),

               'msg' => array('alias_added', $address, $id)

             );

+

+            // Track affected mailboxes for SOGo update

+            if (!empty($goto)) {

+              $gotos = array_map('trim', explode(',', $goto));

+              foreach ($gotos as $g) {

+                if (filter_var($g, FILTER_VALIDATE_EMAIL) &&

+                    !in_array($g, array('null@localhost', 'spam@localhost', 'ham@localhost'))) {

+                  $update_sogo_mailboxes[] = $g;

+                }

+              }

+            }

           }

         break;

         case 'alias_domain':

@@ -1002,6 +1050,7 @@
           $local_part   = strtolower(trim($_data['local_part']));

           $domain       = idn_to_ascii(strtolower(trim($_data['domain'])), 0, INTL_IDNA_VARIANT_UTS46);

           $username     = $local_part . '@' . $domain;

+          $authsource   = 'mailcow';

           if (!filter_var($username, FILTER_VALIDATE_EMAIL)) {

             $_SESSION['return'][] = array(

               'type' => 'danger',

@@ -1018,15 +1067,19 @@
             );

             return false;

           }

+          if ($_data['authsource'] == "mailcow" ||

+              in_array($_data['authsource'], array('keycloak', 'generic-oidc', 'ldap')) && $iam_settings['authsource'] == $_data['authsource']){

+            $authsource = $_data['authsource'];

+          }

           if (empty($name)) {

             $name = $local_part;

           }

           $template_attr = null;

           if ($_data['template']){

-            $template_attr = mailbox('get', 'mailbox_templates', $_data['template'])['attributes'];

+            $template_attr = mailbox('get', 'mailbox_templates', $_data['template'], $_extra)['attributes'];

           }

           if (empty($template_attr)) {

-            $template_attr = mailbox('get', 'mailbox_templates')[0]['attributes'];

+            $template_attr = mailbox('get', 'mailbox_templates', null, $_extra)[0]['attributes'];

           }

           $MAILBOX_DEFAULT_ATTRIBUTES = array_merge($MAILBOX_DEFAULT_ATTRIBUTES, $template_attr);

 

@@ -1035,7 +1088,12 @@
           $name         = ltrim(rtrim($_data['name'], '>'), '<');

           $tags         = (isset($_data['tags'])) ? $_data['tags'] : $MAILBOX_DEFAULT_ATTRIBUTES['tags'];

           $quota_m      = (isset($_data['quota'])) ? intval($_data['quota']) : intval($MAILBOX_DEFAULT_ATTRIBUTES['quota']) / 1024 ** 2;

-          if ((!isset($_SESSION['acl']['unlimited_quota']) || $_SESSION['acl']['unlimited_quota'] != "1") && $quota_m === 0) {

+          if ($authsource != 'mailcow'){

+            $password = '';

+            $password2 = '';

+            $password_hashed = '';

+          }

+          if (!hasACLAccess("unlimited_quota") && $quota_m === 0) {

             $_SESSION['return'][] = array(

               'type' => 'danger',

               'log' => array(__FUNCTION__, $_action, $_type, $_data_log, $_attr),

@@ -1050,9 +1108,12 @@
             $_data['pop3_access'] = (in_array('pop3', $_data['protocol_access'])) ? 1 : 0;

             $_data['smtp_access'] = (in_array('smtp', $_data['protocol_access'])) ? 1 : 0;

             $_data['sieve_access'] = (in_array('sieve', $_data['protocol_access'])) ? 1 : 0;

+            $_data['eas_access'] = (in_array('eas', $_data['protocol_access'])) ? 1 : 0;

+            $_data['dav_access'] = (in_array('dav', $_data['protocol_access'])) ? 1 : 0;

           }

           $active = (isset($_data['active'])) ? intval($_data['active']) : intval($MAILBOX_DEFAULT_ATTRIBUTES['active']);

           $force_pw_update = (isset($_data['force_pw_update'])) ? intval($_data['force_pw_update']) : intval($MAILBOX_DEFAULT_ATTRIBUTES['force_pw_update']);

+          $force_tfa = (isset($_data['force_tfa'])) ? intval($_data['force_tfa']) : intval($MAILBOX_DEFAULT_ATTRIBUTES['force_tfa']);

           $tls_enforce_in = (isset($_data['tls_enforce_in'])) ? intval($_data['tls_enforce_in']) : intval($MAILBOX_DEFAULT_ATTRIBUTES['tls_enforce_in']);

           $tls_enforce_out = (isset($_data['tls_enforce_out'])) ? intval($_data['tls_enforce_out']) : intval($MAILBOX_DEFAULT_ATTRIBUTES['tls_enforce_out']);

           $sogo_access = (isset($_data['sogo_access'])) ? intval($_data['sogo_access']) : intval($MAILBOX_DEFAULT_ATTRIBUTES['sogo_access']);

@@ -1060,13 +1121,32 @@
           $pop3_access = (isset($_data['pop3_access'])) ? intval($_data['pop3_access']) : intval($MAILBOX_DEFAULT_ATTRIBUTES['pop3_access']);

           $smtp_access = (isset($_data['smtp_access'])) ? intval($_data['smtp_access']) : intval($MAILBOX_DEFAULT_ATTRIBUTES['smtp_access']);

           $sieve_access = (isset($_data['sieve_access'])) ? intval($_data['sieve_access']) : intval($MAILBOX_DEFAULT_ATTRIBUTES['sieve_access']);

+          $eas_access = (isset($_data['eas_access'])) ? intval($_data['eas_access']) : intval($MAILBOX_DEFAULT_ATTRIBUTES['eas_access']);

+          $dav_access = (isset($_data['dav_access'])) ? intval($_data['dav_access']) : intval($MAILBOX_DEFAULT_ATTRIBUTES['dav_access']);

           $relayhost = (isset($_data['relayhost'])) ? intval($_data['relayhost']) : 0;

           $quarantine_notification = (isset($_data['quarantine_notification'])) ? strval($_data['quarantine_notification']) : strval($MAILBOX_DEFAULT_ATTRIBUTES['quarantine_notification']);

           $quarantine_category = (isset($_data['quarantine_category'])) ? strval($_data['quarantine_category']) : strval($MAILBOX_DEFAULT_ATTRIBUTES['quarantine_category']);

+          // Validate quarantine_category

+          if (!in_array($quarantine_category, array('add_header', 'reject', 'all'))) {

+            $_SESSION['return'][] = array(

+              'type' => 'danger',

+              'log' => array(__FUNCTION__, $_action, $_type, $_data_log, $_attr),

+              'msg' => 'quarantine_category_invalid'

+            );

+            return false;

+          }

           $quota_b    = ($quota_m * 1048576);

+          $attribute_hash = (!empty($_data['attribute_hash'])) ? $_data['attribute_hash'] : '';

+          if (in_array($authsource, array('keycloak', 'generic-oidc', 'ldap'))){

+            $force_pw_update = 0;

+          }

+          if ($authsource == 'generic-oidc'){

+            $force_tfa = 0;

+          }

           $mailbox_attrs = json_encode(

             array(

               'force_pw_update' => strval($force_pw_update),

+              'force_tfa' => strval($force_tfa),

               'tls_enforce_in' => strval($tls_enforce_in),

               'tls_enforce_out' => strval($tls_enforce_out),

               'sogo_access' => strval($sogo_access),

@@ -1074,11 +1154,14 @@
               'pop3_access' => strval($pop3_access),

               'smtp_access' => strval($smtp_access),

               'sieve_access' => strval($sieve_access),

+              'eas_access' => strval($eas_access),

+              'dav_access' => strval($dav_access),

               'relayhost' => strval($relayhost),

               'passwd_update' => time(),

               'mailbox_format' => strval($MAILBOX_DEFAULT_ATTRIBUTES['mailbox_format']),

               'quarantine_notification' => strval($quarantine_notification),

-              'quarantine_category' => strval($quarantine_category)

+              'quarantine_category' => strval($quarantine_category),

+              'attribute_hash' => $attribute_hash

             )

           );

           if (!is_valid_domain_name($domain)) {

@@ -1153,10 +1236,12 @@
             );

             return false;

           }

-          if (password_check($password, $password2) !== true) {

-            return false;

+          if ($authsource == 'mailcow'){

+            if (password_check($password, $password2) !== true) {

+              return false;

+            }

+            $password_hashed = hash_password($password);

           }

-          $password_hashed = hash_password($password);

           if ($MailboxData['count'] >= $DomainData['mailboxes']) {

             $_SESSION['return'][] = array(

               'type' => 'danger',

@@ -1182,8 +1267,8 @@
             );

             return false;

           }

-          $stmt = $pdo->prepare("INSERT INTO `mailbox` (`username`, `password`, `name`, `quota`, `local_part`, `domain`, `attributes`, `active`)

-            VALUES (:username, :password_hashed, :name, :quota_b, :local_part, :domain, :mailbox_attrs, :active)");

+          $stmt = $pdo->prepare("INSERT INTO `mailbox` (`username`, `password`, `name`, `quota`, `local_part`, `domain`, `attributes`, `authsource`, `active`)

+            VALUES (:username, :password_hashed, :name, :quota_b, :local_part, :domain, :mailbox_attrs, :authsource, :active)");

           $stmt->execute(array(

             ':username' => $username,

             ':password_hashed' => $password_hashed,

@@ -1192,6 +1277,7 @@
             ':local_part' => $local_part,

             ':domain' => $domain,

             ':mailbox_attrs' => $mailbox_attrs,

+            ':authsource' => $authsource,

             ':active' => $active

           ));

           $stmt = $pdo->prepare("UPDATE `mailbox` SET

@@ -1200,6 +1286,14 @@
           $stmt->execute(array(

             ':username' => $username

           ));

+          // save delimiter_action

+          if (isset($_data['tagged_mail_handler'])) {

+            mailbox('edit', 'delimiter_action', array(

+              'username' => $username,

+              'tagged_mail_handler' => $_data['tagged_mail_handler']

+            ));

+          }

+

           // save tags

           foreach($tags as $index => $tag){

             if (empty($tag)) continue;

@@ -1211,11 +1305,14 @@
               );

               break;

             }

-            $stmt = $pdo->prepare("INSERT INTO `tags_mailbox` (`username`, `tag_name`) VALUES (:username, :tag_name)");

-            $stmt->execute(array(

-              ':username' => $username,

-              ':tag_name' => $tag,

-            ));

+            try {

+              $stmt = $pdo->prepare("INSERT INTO `tags_mailbox` (`username`, `tag_name`) VALUES (:username, :tag_name)");

+              $stmt->execute(array(

+                ':username' => $username,

+                ':tag_name' => $tag,

+              ));

+            } catch (Exception $e) {

+            }

           }

           $stmt = $pdo->prepare("INSERT INTO `quota2` (`username`, `bytes`, `messages`)

             VALUES (:username, '0', '0') ON DUPLICATE KEY UPDATE `bytes` = '0', `messages` = '0';");

@@ -1232,7 +1329,7 @@
             ':active' => $active

           ));

 

-          

+

           if (isset($_data['acl'])) {

             $_data['acl'] = (array)$_data['acl'];

             $_data['spam_alias'] = (in_array('spam_alias', $_data['acl'])) ? 1 : 0;

@@ -1249,6 +1346,7 @@
             $_data['quarantine_notification'] = (in_array('quarantine_notification', $_data['acl'])) ? 1 : 0;

             $_data['quarantine_category'] = (in_array('quarantine_category', $_data['acl'])) ? 1 : 0;

             $_data['app_passwds'] = (in_array('app_passwds', $_data['acl'])) ? 1 : 0;

+            $_data['pw_reset'] = (in_array('pw_reset', $_data['acl'])) ? 1 : 0;

           } else {

             $_data['spam_alias'] = intval($MAILBOX_DEFAULT_ATTRIBUTES['acl_spam_alias']);

             $_data['tls_policy'] = intval($MAILBOX_DEFAULT_ATTRIBUTES['acl_tls_policy']);

@@ -1263,15 +1361,16 @@
             $_data['quarantine_attachments'] = intval($MAILBOX_DEFAULT_ATTRIBUTES['acl_quarantine_attachments']);

             $_data['quarantine_notification'] = intval($MAILBOX_DEFAULT_ATTRIBUTES['acl_quarantine_notification']);

             $_data['quarantine_category'] = intval($MAILBOX_DEFAULT_ATTRIBUTES['acl_quarantine_category']);

-            $_data['app_passwds'] = intval($MAILBOX_DEFAULT_ATTRIBUTES['acl_app_passwds']);     

+            $_data['app_passwds'] = intval($MAILBOX_DEFAULT_ATTRIBUTES['acl_app_passwds']);

+            $_data['pw_reset'] = intval($MAILBOX_DEFAULT_ATTRIBUTES['acl_pw_reset']);

           }

 

           try {

-            $stmt = $pdo->prepare("INSERT INTO `user_acl` 

+            $stmt = $pdo->prepare("INSERT INTO `user_acl`

               (`username`, `spam_alias`, `tls_policy`, `spam_score`, `spam_policy`, `delimiter_action`, `syncjobs`, `eas_reset`, `sogo_profile_reset`,

-                `pushover`, `quarantine`, `quarantine_attachments`, `quarantine_notification`, `quarantine_category`, `app_passwds`) 

+                `pushover`, `quarantine`, `quarantine_attachments`, `quarantine_notification`, `quarantine_category`, `app_passwds`, `pw_reset`)

               VALUES (:username, :spam_alias, :tls_policy, :spam_score, :spam_policy, :delimiter_action, :syncjobs, :eas_reset, :sogo_profile_reset,

-                :pushover, :quarantine, :quarantine_attachments, :quarantine_notification, :quarantine_category, :app_passwds) ");

+                :pushover, :quarantine, :quarantine_attachments, :quarantine_notification, :quarantine_category, :app_passwds, :pw_reset) ");

             $stmt->execute(array(

               ':username' => $username,

               ':spam_alias' => $_data['spam_alias'],

@@ -1287,7 +1386,8 @@
               ':quarantine_attachments' => $_data['quarantine_attachments'],

               ':quarantine_notification' => $_data['quarantine_notification'],

               ':quarantine_category' => $_data['quarantine_category'],

-              ':app_passwds' => $_data['app_passwds']

+              ':app_passwds' => $_data['app_passwds'],

+              ':pw_reset' => $_data['pw_reset']

             ));

           }

           catch (PDOException $e) {

@@ -1306,16 +1406,129 @@
               'object' => $username,

               'rl_frame' => $_data['rl_frame'],

               'rl_value' => $_data['rl_value']

-            ));

+            ), $_extra);

           }

 

-          update_sogo_static_view($username);

+          // Track affected mailboxes for SOGo update

+          $update_sogo_mailboxes[] = $username;

           $_SESSION['return'][] = array(

             'type' => 'success',

             'log' => array(__FUNCTION__, $_action, $_type, $_data_log, $_attr),

             'msg' => array('mailbox_added', htmlspecialchars($username))

           );

-          return true;

+        break;

+        case 'mailbox_from_template':

+          $stmt = $pdo->prepare("SELECT * FROM `templates`

+          WHERE `template` = :template AND type = 'mailbox'");

+          $stmt->execute(array(

+            ":template" => $_data['template']

+          ));

+          $mbox_template_data = $stmt->fetch(PDO::FETCH_ASSOC);

+          if (empty($mbox_template_data)){

+            $_SESSION['return'][] =  array(

+              'type' => 'danger',

+              'log' => array(__FUNCTION__, $_action, $_type, $_data_log, $_attr),

+              'msg' => 'template_missing'

+            );

+            return false;

+          }

+

+          $attribute_hash = sha1(json_encode($mbox_template_data["attributes"]));

+          $mbox_template_data = json_decode($mbox_template_data["attributes"], true);

+          $mbox_template_data['domain'] = $_data['domain'];

+          $mbox_template_data['name'] = $_data['name'];

+          $mbox_template_data['local_part'] = $_data['local_part'];

+          $mbox_template_data['authsource'] = $_data['authsource'];

+          $mbox_template_data['attribute_hash'] = $attribute_hash;

+          $mbox_template_data['quota'] = intval($mbox_template_data['quota'] / 1048576);

+

+          $mailbox_attributes = array('acl' => array());

+          foreach ($mbox_template_data as $key => $value){

+            switch (true) {

+              case (strpos($key, 'acl_') === 0 && $value != 0):

+                array_push($mailbox_attributes['acl'], str_replace('acl_' , '', $key));

+              break;

+              default:

+                $mailbox_attributes[$key] = $value;

+              break;

+            }

+          }

+

+          return mailbox('add', 'mailbox', $mailbox_attributes);

+        break;

+        case 'mta_sts':

+          $domain       = idn_to_ascii(strtolower(trim($_data['domain'])), 0, INTL_IDNA_VARIANT_UTS46);

+          $version      = strtolower($_data['version']);

+          $mode         = strtolower($_data['mode']);

+          $mx           = explode(",", preg_replace('/\s+/', '', $_data['mx']));

+          $max_age      = intval($_data['max_age']);

+          $active       = (intval($_data['active']) == 1) ? 1 : 0;

+          $id           = date('YmdHis');

+

+          if (!hasDomainAccess($_SESSION['mailcow_cc_username'], $_SESSION['mailcow_cc_role'], $domain)) {

+            $_SESSION['return'][] = array(

+              'type' => 'danger',

+              'log' => array(__FUNCTION__, $_action, $_type, $_data, $_attr),

+              'msg' => 'access_denied'

+            );

+            return false;

+          }

+          if (empty($version) || !in_array($version, array('stsv1'))) {

+            $_SESSION['return'][] = array(

+              'type' => 'danger',

+              'log' => array(__FUNCTION__, $_action, $_type, $_data, $_attr),

+              'msg' => array('version_invalid', htmlspecialchars($domain))

+            );

+            return false;

+          }

+          if (empty($mode) || !in_array($mode, array('enforce', 'testing', 'none'))) {

+            $_SESSION['return'][] = array(

+              'type' => 'danger',

+              'log' => array(__FUNCTION__, $_action, $_type, $_data, $_attr),

+              'msg' => array('mode_invalid', htmlspecialchars($domain))

+            );

+            return false;

+          }

+          if (empty($max_age) || $max_age < 0 || $max_age > 31536000) {

+            $_SESSION['return'][] = array(

+              'type' => 'danger',

+              'log' => array(__FUNCTION__, $_action, $_type, $_data, $_attr),

+              'msg' => array('max_age_invalid', htmlspecialchars($domain))

+            );

+            return false;

+          }

+          foreach ($mx as $index => $mx_domain) {

+            $mx_domain = idn_to_ascii(strtolower(trim($mx_domain)), 0, INTL_IDNA_VARIANT_UTS46);

+            if (!is_valid_domain_name($mx_domain, array('allow_wildcard' => true))) {

+              $_SESSION['return'][] = array(

+                'type' => 'danger',

+                'log' => array(__FUNCTION__, $_action, $_type, $_data, $_attr),

+                'msg' => array('mx_invalid', htmlspecialchars($mx_domain))

+              );

+              return false;

+            }

+          }

+

+          try {

+            $stmt = $pdo->prepare("INSERT INTO `mta_sts` (`id`, `domain`, `version`, `mode`, `mx`, `max_age`, `active`)

+              VALUES (:id, :domain, :version, :mode, :mx, :max_age, :active)");

+            $stmt->execute(array(

+              ':id' => $id,

+              ':domain' => $domain,

+              ':version' => $version,

+              ':mode' => $mode,

+              ':mx' => implode(",", $mx),

+              ':max_age' => $max_age,

+              ':active' => $active

+            ));

+          } catch (PDOException $e) {

+            $_SESSION['return'][] = array(

+              'type' => 'danger',

+              'log' => array(__FUNCTION__, $_action, $_type, $_data),

+              'msg' => $e->getMessage()

+            );

+            return false;

+          }

         break;

         case 'resource':

           $domain             = idn_to_ascii(strtolower(trim($_data['domain'])), 0, INTL_IDNA_VARIANT_UTS46);

@@ -1428,6 +1641,9 @@
             'log' => array(__FUNCTION__, $_action, $_type, $_data_log, $_attr),

             'msg' => array('resource_added', htmlspecialchars($name))

           );

+

+          // Track affected mailboxes for SOGo update

+          $update_sogo_mailboxes[] = $name;

         break;

         case 'domain_templates':

           if ($_SESSION['mailcow_cc_role'] != "admin") {

@@ -1463,7 +1679,7 @@
             );

             return false;

           }

-          

+

           // check attributes

           $attr = array();

           $attr['tags']                       = (isset($_data['tags'])) ? $_data['tags'] : array();

@@ -1538,11 +1754,22 @@
           $attr = array();

           $attr["quota"]                       = isset($_data['quota']) ? intval($_data['quota']) * 1048576 : 0;

           $attr['tags']                        = (isset($_data['tags'])) ? $_data['tags'] : array();

+          $attr["tagged_mail_handler"]         = (!empty($_data['tagged_mail_handler'])) ? $_data['tagged_mail_handler'] : strval($MAILBOX_DEFAULT_ATTRIBUTES['tagged_mail_handler']);

           $attr["quarantine_notification"]     = (!empty($_data['quarantine_notification'])) ? $_data['quarantine_notification'] : strval($MAILBOX_DEFAULT_ATTRIBUTES['quarantine_notification']);

           $attr["quarantine_category"]         = (!empty($_data['quarantine_category'])) ? $_data['quarantine_category'] : strval($MAILBOX_DEFAULT_ATTRIBUTES['quarantine_category']);

+          // Validate quarantine_category

+          if (!in_array($attr["quarantine_category"], array('add_header', 'reject', 'all'))) {

+            $_SESSION['return'][] = array(

+              'type' => 'danger',

+              'log' => array(__FUNCTION__, $_action, $_type, $_data_log, $_extra),

+              'msg' => 'quarantine_category_invalid'

+            );

+            return false;

+          }

           $attr["rl_frame"]                    = (!empty($_data['rl_frame'])) ? $_data['rl_frame'] : "s";

           $attr["rl_value"]                    = (!empty($_data['rl_value'])) ? $_data['rl_value'] : "";

           $attr["force_pw_update"]             = isset($_data['force_pw_update']) ? intval($_data['force_pw_update']) : intval($MAILBOX_DEFAULT_ATTRIBUTES['force_pw_update']);

+          $attr["force_tfa"]                   = isset($_data['force_tfa']) ? intval($_data['force_tfa']) : intval($MAILBOX_DEFAULT_ATTRIBUTES['force_tfa']);

           $attr["sogo_access"]                 = isset($_data['sogo_access']) ? intval($_data['sogo_access']) : intval($MAILBOX_DEFAULT_ATTRIBUTES['sogo_access']);

           $attr["active"]                      = isset($_data['active']) ? intval($_data['active']) : 1;

           $attr["tls_enforce_in"]              = isset($_data['tls_enforce_in']) ? intval($_data['tls_enforce_in']) : intval($MAILBOX_DEFAULT_ATTRIBUTES['tls_enforce_in']);

@@ -1553,12 +1780,16 @@
             $attr['pop3_access'] = (in_array('pop3', $_data['protocol_access'])) ? 1 : 0;

             $attr['smtp_access'] = (in_array('smtp', $_data['protocol_access'])) ? 1 : 0;

             $attr['sieve_access'] = (in_array('sieve', $_data['protocol_access'])) ? 1 : 0;

-          }   

+            $attr['eas_access'] = (in_array('eas', $_data['protocol_access'])) ? 1 : 0;

+            $attr['dav_access'] = (in_array('dav', $_data['protocol_access'])) ? 1 : 0;

+          }

           else {

             $attr['imap_access'] = intval($MAILBOX_DEFAULT_ATTRIBUTES['imap_access']);

             $attr['pop3_access'] = intval($MAILBOX_DEFAULT_ATTRIBUTES['pop3_access']);

             $attr['smtp_access'] = intval($MAILBOX_DEFAULT_ATTRIBUTES['smtp_access']);

             $attr['sieve_access'] = intval($MAILBOX_DEFAULT_ATTRIBUTES['sieve_access']);

+            $attr['eas_access'] = intval($MAILBOX_DEFAULT_ATTRIBUTES['eas_access']);

+            $attr['dav_access'] = intval($MAILBOX_DEFAULT_ATTRIBUTES['dav_access']);

           }

           if (isset($_data['acl'])) {

             $_data['acl'] = (array)$_data['acl'];

@@ -1576,6 +1807,7 @@
             $attr['acl_quarantine_notification'] = (in_array('quarantine_notification', $_data['acl'])) ? 1 : 0;

             $attr['acl_quarantine_category'] = (in_array('quarantine_category', $_data['acl'])) ? 1 : 0;

             $attr['acl_app_passwds'] = (in_array('app_passwds', $_data['acl'])) ? 1 : 0;

+            $attr['acl_pw_reset'] = (in_array('pw_reset', $_data['acl'])) ? 1 : 0;

           } else {

             $_data['acl'] = (array)$_data['acl'];

             $attr['acl_spam_alias'] = 0;

@@ -1682,7 +1914,7 @@
           else {

             $usernames = $_data['username'];

           }

-          if (!isset($_SESSION['acl']['tls_policy']) || $_SESSION['acl']['tls_policy'] != "1" ) {

+          if (!hasACLAccess("tls_policy")) {

             $_SESSION['return'][] = array(

               'type' => 'danger',

               'log' => array(__FUNCTION__, $_action, $_type, $_data_log, $_attr),

@@ -1691,7 +1923,7 @@
             return false;

           }

           foreach ($usernames as $username) {

-            if (!filter_var($username, FILTER_VALIDATE_EMAIL) || !hasMailboxObjectAccess($_SESSION['mailcow_cc_username'], $_SESSION['mailcow_cc_role'], $username)) {

+            if (!hasMailboxObjectAccess($_SESSION['mailcow_cc_username'], $_SESSION['mailcow_cc_role'], $username)) {

               $_SESSION['return'][] = array(

                 'type' => 'danger',

                 'log' => array(__FUNCTION__, $_action, $_type, $_data_log, $_attr),

@@ -1699,7 +1931,7 @@
               );

               continue;

             }

-            $is_now = mailbox('get', 'tls_policy', $username);

+            $is_now = mailbox('get', 'tls_policy', $username, $_extra);

             if (!empty($is_now)) {

               $tls_enforce_in = (isset($_data['tls_enforce_in'])) ? intval($_data['tls_enforce_in']) : $is_now['tls_enforce_in'];

               $tls_enforce_out = (isset($_data['tls_enforce_out'])) ? intval($_data['tls_enforce_out']) : $is_now['tls_enforce_out'];

@@ -1736,7 +1968,7 @@
           else {

             $usernames = $_data['username'];

           }

-          if (!isset($_SESSION['acl']['quarantine_notification']) || $_SESSION['acl']['quarantine_notification'] != "1" ) {

+          if (!hasACLAccess("quarantine_notification")) {

             $_SESSION['return'][] = array(

               'type' => 'danger',

               'log' => array(__FUNCTION__, $_action, $_type, $_data_log, $_attr),

@@ -1745,7 +1977,7 @@
             return false;

           }

           foreach ($usernames as $username) {

-            if (!filter_var($username, FILTER_VALIDATE_EMAIL) || !hasMailboxObjectAccess($_SESSION['mailcow_cc_username'], $_SESSION['mailcow_cc_role'], $username)) {

+            if (!hasMailboxObjectAccess($_SESSION['mailcow_cc_username'], $_SESSION['mailcow_cc_role'], $username)) {

               $_SESSION['return'][] = array(

                 'type' => 'danger',

                 'log' => array(__FUNCTION__, $_action, $_type, $_data_log, $_attr),

@@ -1753,7 +1985,7 @@
               );

               continue;

             }

-            $is_now = mailbox('get', 'quarantine_notification', $username);

+            $is_now = mailbox('get', 'quarantine_notification', $username, $_extra);

             if (!empty($is_now)) {

               $quarantine_notification = (isset($_data['quarantine_notification'])) ? $_data['quarantine_notification'] : $is_now['quarantine_notification'];

             }

@@ -1795,7 +2027,7 @@
           else {

             $usernames = $_data['username'];

           }

-          if (!isset($_SESSION['acl']['quarantine_category']) || $_SESSION['acl']['quarantine_category'] != "1" ) {

+          if (!hasACLAccess("quarantine_category")) {

             $_SESSION['return'][] = array(

               'type' => 'danger',

               'log' => array(__FUNCTION__, $_action, $_type, $_data_log, $_attr),

@@ -1804,7 +2036,7 @@
             return false;

           }

           foreach ($usernames as $username) {

-            if (!filter_var($username, FILTER_VALIDATE_EMAIL) || !hasMailboxObjectAccess($_SESSION['mailcow_cc_username'], $_SESSION['mailcow_cc_role'], $username)) {

+            if (!hasMailboxObjectAccess($_SESSION['mailcow_cc_username'], $_SESSION['mailcow_cc_role'], $username)) {

               $_SESSION['return'][] = array(

                 'type' => 'danger',

                 'log' => array(__FUNCTION__, $_action, $_type, $_data_log, $_attr),

@@ -1812,7 +2044,7 @@
               );

               continue;

             }

-            $is_now = mailbox('get', 'quarantine_category', $username);

+            $is_now = mailbox('get', 'quarantine_category', $username, $_extra);

             if (!empty($is_now)) {

               $quarantine_category = (isset($_data['quarantine_category'])) ? $_data['quarantine_category'] : $is_now['quarantine_category'];

             }

@@ -1863,6 +2095,14 @@
             return false;

           }

           foreach ($usernames as $username) {

+            if (!hasMailboxObjectAccess($_SESSION['mailcow_cc_username'], $_SESSION['mailcow_cc_role'], $username)) {

+              $_SESSION['return'][] = array(

+                'type' => 'danger',

+                'log' => array(__FUNCTION__, $_action, $_type, $_data_log, $_attr),

+                'msg' => 'access_denied'

+              );

+              continue;

+            }

             if ($_data['spam_score'] == "default") {

               $stmt = $pdo->prepare("DELETE FROM `filterconf` WHERE `object` = :username

                 AND (`option` = 'lowspamlevel' OR `option` = 'highspamlevel')");

@@ -1941,15 +2181,23 @@
               );

               continue;

             }

-            if (empty($_data['validity'])) {

+            if (empty($_data['validity']) && empty($_data['permanent'])) {

               continue;

             }

-            $validity = round((int)time() + ($_data['validity'] * 3600));

-            $stmt = $pdo->prepare("UPDATE `spamalias` SET `validity` = :validity WHERE

+            if (isset($_data['permanent']) && filter_var($_data['permanent'], FILTER_VALIDATE_BOOL)) {

+              $permanent = 1;

+              $validity = 0;

+            }

+            else if (isset($_data['validity'])) {

+              $permanent = 0;

+              $validity = round((int)time() + ($_data['validity'] * 3600));

+            }

+            $stmt = $pdo->prepare("UPDATE `spamalias` SET `validity` = :validity, `permanent` = :permanent WHERE

               `address` = :address");

             $stmt->execute(array(

               ':address' => $address,

-              ':validity' => $validity

+              ':validity' => $validity,

+              ':permanent' => $permanent

             ));

             $_SESSION['return'][] = array(

               'type' => 'success',

@@ -2104,7 +2352,7 @@
                 );

                 return false;

               }

-  

+

               // check if param is whitelisted

               if (!in_array(strtolower($param), $GLOBALS["IMAPSYNC_OPTIONS"]["whitelist"])){

                 // bad option

@@ -2322,7 +2570,9 @@
           foreach ($ids as $id) {

             $is_now = mailbox('get', 'alias_details', $id);

             if (!empty($is_now)) {

+              $internal = (isset($_data['internal'])) ? intval($_data['internal']) : $is_now['internal'];

               $active = (isset($_data['active'])) ? intval($_data['active']) : $is_now['active'];

+              $sender_allowed = (isset($_data['sender_allowed'])) ? intval($_data['sender_allowed']) : $is_now['sender_allowed'];

               $sogo_visible = (isset($_data['sogo_visible'])) ? intval($_data['sogo_visible']) : $is_now['sogo_visible'];

               $goto_null = (isset($_data['goto_null'])) ? intval($_data['goto_null']) : 0;

               $goto_spam = (isset($_data['goto_spam'])) ? intval($_data['goto_spam']) : 0;

@@ -2477,6 +2727,19 @@
                   unset($gotos[$i]);

                   continue;

                 }

+                // Deny external goto domains: global switch (all roles) overrides the per-DA ACL

+                $goto_domain = idn_to_ascii(substr(strstr($goto, '@'), 1), 0, INTL_IDNA_VARIANT_UTS46);

+                if (($GLOBALS['ALIAS_DISABLE_EXTERNAL_DOMAINS'] === true ||

+                    (isset($_SESSION['acl']['alias_external_goto']) && $_SESSION['acl']['alias_external_goto'] != "1")) &&

+                    !is_local_mailcow_domain($goto_domain)) {

+                  $_SESSION['return'][] = array(

+                    'type' => 'danger',

+                    'log' => array(__FUNCTION__, $_action, $_type, $_data_log, $_attr),

+                    'msg' => array('external_goto_denied', htmlspecialchars($goto))

+                  );

+                  unset($gotos[$i]);

+                  continue;

+                }

                 if ($goto == $address) {

                   $_SESSION['return'][] = array(

                     'type' => 'danger',

@@ -2507,6 +2770,8 @@
                 `domain` = :domain,

                 `goto` = :goto,

                 `sogo_visible`= :sogo_visible,

+                `internal`= :internal,

+                `sender_allowed`= :sender_allowed,

                 `active`= :active

                   WHERE `id` = :id");

               $stmt->execute(array(

@@ -2516,6 +2781,8 @@
                 ':domain' => $domain,

                 ':goto' => $goto,

                 ':sogo_visible' => $sogo_visible,

+                ':internal' => $internal,

+                ':sender_allowed' => $sender_allowed,

                 ':active' => $active,

                 ':id' => $is_now['id']

               ));

@@ -2525,6 +2792,28 @@
               'log' => array(__FUNCTION__, $_action, $_type, $_data_log, $_attr),

               'msg' => array('alias_modified', htmlspecialchars($address))

             );

+

+            // Track affected mailboxes for SOGo update (both old and new goto addresses)

+            // Old goto: to remove alias from their view

+            if (!empty($is_now['goto'])) {

+              $old_gotos = array_map('trim', explode(',', $is_now['goto']));

+              foreach ($old_gotos as $g) {

+                if (filter_var($g, FILTER_VALIDATE_EMAIL) &&

+                    !in_array($g, array('null@localhost', 'spam@localhost', 'ham@localhost'))) {

+                  $update_sogo_mailboxes[] = $g;

+                }

+              }

+            }

+            // New goto: to add alias to their view

+            if (!empty($goto)) {

+              $new_gotos = array_map('trim', explode(',', $goto));

+              foreach ($new_gotos as $g) {

+                if (filter_var($g, FILTER_VALIDATE_EMAIL) &&

+                    !in_array($g, array('null@localhost', 'spam@localhost', 'ham@localhost'))) {

+                  $update_sogo_mailboxes[] = $g;

+                }

+              }

+            }

           }

         break;

         case 'domain':

@@ -2797,11 +3086,11 @@
             // check name

             if ($is_now["template"] == "Default" && $is_now["template"] != $_data["template"]){

               // keep template name of Default template

-              $_data["template"]                   = $is_now["template"]; 

+              $_data["template"]                   = $is_now["template"];

             }

             else {

-              $_data["template"]                   = (isset($_data["template"])) ? $_data["template"] : $is_now["template"]; 

-            }   

+              $_data["template"]                   = (isset($_data["template"])) ? $_data["template"] : $is_now["template"];

+            }

             // check attributes

             $attr = array();

             $attr['tags']                       = (isset($_data['tags'])) ? $_data['tags'] : array();

@@ -2828,10 +3117,10 @@
               ":id" => $id ,

               ":template" => $_data["template"] ,

               ":attributes" => json_encode($attr)

-            )); 

+            ));

           }

 

-  

+

           $_SESSION['return'][] = array(

             'type' => 'success',

             'log' => array(__FUNCTION__, $_action, $_type, $_data_log, $_attr),

@@ -2856,30 +3145,48 @@
               );

               continue;

             }

-            $is_now = mailbox('get', 'mailbox_details', $username);

+            $is_now = mailbox('get', 'mailbox_details', $username, $_extra);

             if (isset($_data['protocol_access'])) {

               $_data['protocol_access'] = (array)$_data['protocol_access'];

               $_data['imap_access'] = (in_array('imap', $_data['protocol_access'])) ? 1 : 0;

               $_data['pop3_access'] = (in_array('pop3', $_data['protocol_access'])) ? 1 : 0;

               $_data['smtp_access'] = (in_array('smtp', $_data['protocol_access'])) ? 1 : 0;

               $_data['sieve_access'] = (in_array('sieve', $_data['protocol_access'])) ? 1 : 0;

+              $_data['eas_access'] = (in_array('eas', $_data['protocol_access'])) ? 1 : 0;

+              $_data['dav_access'] = (in_array('dav', $_data['protocol_access'])) ? 1 : 0;

             }

             if (!empty($is_now)) {

-              $active     = (isset($_data['active'])) ? intval($_data['active']) : $is_now['active'];

+              $active               = (isset($_data['active'])) ? intval($_data['active']) : $is_now['active'];

               (int)$force_pw_update = (isset($_data['force_pw_update'])) ? intval($_data['force_pw_update']) : intval($is_now['attributes']['force_pw_update']);

-              (int)$sogo_access = (isset($_data['sogo_access']) && isset($_SESSION['acl']['sogo_access']) && $_SESSION['acl']['sogo_access'] == "1") ? intval($_data['sogo_access']) : intval($is_now['attributes']['sogo_access']);

-              (int)$imap_access = (isset($_data['imap_access']) && isset($_SESSION['acl']['protocol_access']) && $_SESSION['acl']['protocol_access'] == "1") ? intval($_data['imap_access']) : intval($is_now['attributes']['imap_access']);

-              (int)$pop3_access = (isset($_data['pop3_access']) && isset($_SESSION['acl']['protocol_access']) && $_SESSION['acl']['protocol_access'] == "1") ? intval($_data['pop3_access']) : intval($is_now['attributes']['pop3_access']);

-              (int)$smtp_access = (isset($_data['smtp_access']) && isset($_SESSION['acl']['protocol_access']) && $_SESSION['acl']['protocol_access'] == "1") ? intval($_data['smtp_access']) : intval($is_now['attributes']['smtp_access']);

-              (int)$sieve_access = (isset($_data['sieve_access']) && isset($_SESSION['acl']['protocol_access']) && $_SESSION['acl']['protocol_access'] == "1") ? intval($_data['sieve_access']) : intval($is_now['attributes']['sieve_access']);

-              (int)$relayhost = (isset($_data['relayhost']) && isset($_SESSION['acl']['mailbox_relayhost']) && $_SESSION['acl']['mailbox_relayhost'] == "1") ? intval($_data['relayhost']) : intval($is_now['attributes']['relayhost']);

-              (int)$quota_m = (isset_has_content($_data['quota'])) ? intval($_data['quota']) : ($is_now['quota'] / 1048576);

-              $name       = (!empty($_data['name'])) ? ltrim(rtrim($_data['name'], '>'), '<') : $is_now['name'];

-              $domain     = $is_now['domain'];

-              $quota_b    = $quota_m * 1048576;

-              $password   = (!empty($_data['password'])) ? $_data['password'] : null;

-              $password2  = (!empty($_data['password2'])) ? $_data['password2'] : null;

-              $tags       = (is_array($_data['tags']) ? $_data['tags'] : array());

+              (int)$force_tfa       = (isset($_data['force_tfa'])) ? intval($_data['force_tfa']) : intval($is_now['attributes']['force_tfa']);

+              (int)$sogo_access     = (isset($_data['sogo_access']) && hasACLAccess("sogo_access")) ? intval($_data['sogo_access']) : intval($is_now['attributes']['sogo_access']);

+              (int)$imap_access     = (isset($_data['imap_access']) && hasACLAccess("protocol_access")) ? intval($_data['imap_access']) : intval($is_now['attributes']['imap_access']);

+              (int)$pop3_access     = (isset($_data['pop3_access']) && hasACLAccess("protocol_access")) ? intval($_data['pop3_access']) : intval($is_now['attributes']['pop3_access']);

+              (int)$smtp_access     = (isset($_data['smtp_access']) && hasACLAccess("protocol_access")) ? intval($_data['smtp_access']) : intval($is_now['attributes']['smtp_access']);

+              (int)$sieve_access    = (isset($_data['sieve_access']) && hasACLAccess("protocol_access")) ? intval($_data['sieve_access']) : intval($is_now['attributes']['sieve_access']);

+              (int)$eas_access     = (isset($_data['eas_access']) && hasACLAccess("protocol_access")) ? intval($_data['eas_access']) : intval($is_now['attributes']['eas_access']);

+              (int)$dav_access    = (isset($_data['dav_access']) && hasACLAccess("protocol_access")) ? intval($_data['dav_access']) : intval($is_now['attributes']['dav_access']);

+              (int)$relayhost       = (isset($_data['relayhost']) && hasACLAccess("mailbox_relayhost")) ? intval($_data['relayhost']) : intval($is_now['attributes']['relayhost']);

+              (int)$quota_m         = (isset_has_content($_data['quota'])) ? intval($_data['quota']) : ($is_now['quota'] / 1048576);

+              $name                 = (!empty($_data['name'])) ? ltrim(rtrim($_data['name'], '>'), '<') : $is_now['name'];

+              $domain               = $is_now['domain'];

+              $quota_b              = $quota_m * 1048576;

+              $password             = (!empty($_data['password'])) ? $_data['password'] : null;

+              $password2            = (!empty($_data['password2'])) ? $_data['password2'] : null;

+              $tags                 = (is_array($_data['tags']) ? $_data['tags'] : array());

+              $attribute_hash       = (!empty($_data['attribute_hash'])) ? $_data['attribute_hash'] : '';

+              $authsource           = $is_now['authsource'];

+              if ($_data['authsource'] == "mailcow" ||

+                  in_array($_data['authsource'], array('keycloak', 'generic-oidc', 'ldap')) && $iam_settings['authsource'] == $_data['authsource']){

+                $authsource = $_data['authsource'];

+              }

+              if (in_array($authsource, array('keycloak', 'generic-oidc', 'ldap'))){

+                $force_pw_update = 0;

+              }

+              if ($authsource == 'generic-oidc'){

+                $force_tfa = 0;

+              }

+              $pw_recovery_email    = (isset($_data['pw_recovery_email']) && $authsource == 'mailcow') ? $_data['pw_recovery_email'] : $is_now['attributes']['recovery_email'];

             }

             else {

               $_SESSION['return'][] = array(

@@ -2890,7 +3197,7 @@
               continue;

             }

             // if already 0 == ok

-            if ((!isset($_SESSION['acl']['unlimited_quota']) || $_SESSION['acl']['unlimited_quota'] != "1") && ($quota_m == 0 && $is_now['quota'] != 0)) {

+            if (!hasACLAccess("unlimited_quota") && ($quota_m == 0 && $is_now['quota'] != 0)) {

               $_SESSION['return'][] = array(

                 'type' => 'danger',

                 'log' => array(__FUNCTION__, $_action, $_type, $_data_log, $_attr),

@@ -2906,7 +3213,7 @@
               );

               continue;

             }

-            $DomainData = mailbox('get', 'domain_details', $domain);

+            $DomainData = mailbox('get', 'domain_details', $domain, $_extra);

             if ($quota_m > ($is_now['max_new_quota'] / 1048576)) {

               $_SESSION['return'][] = array(

                 'type' => 'danger',

@@ -2925,7 +3232,7 @@
             }

             $extra_acls = array();

             if (isset($_data['extended_sender_acl'])) {

-              if (!isset($_SESSION['acl']['extend_sender_acl']) || $_SESSION['acl']['extend_sender_acl'] != "1" ) {

+              if (!hasACLAccess("extend_sender_acl")) {

                 $_SESSION['return'][] = array(

                   'type' => 'danger',

                   'log' => array(__FUNCTION__, $_action, $_type, $_data_log, $_attr),

@@ -2995,9 +3302,10 @@
             }

             if (isset($_data['sender_acl'])) {

               // Get sender_acl items set by admin

+              $current_sender_acls = mailbox('get', 'sender_acl_handles', $username);

               $sender_acl_admin = array_merge(

-                mailbox('get', 'sender_acl_handles', $username)['sender_acl_domains']['ro'],

-                mailbox('get', 'sender_acl_handles', $username)['sender_acl_addresses']['ro']

+                $current_sender_acls['sender_acl_domains']['ro'],

+                $current_sender_acls['sender_acl_addresses']['ro']

               );

               // Get sender_acl items from POST array

               // Set sender_acl_domain_admin to empty array if sender_acl contains "default" to trigger a reset

@@ -3085,16 +3393,25 @@
                 $stmt->execute(array(

                   ':username' => $username

                 ));

-                $fixed_sender_aliases = mailbox('get', 'sender_acl_handles', $username)['fixed_sender_aliases'];

+                $sender_acl_handles = mailbox('get', 'sender_acl_handles', $username);

+                $fixed_sender_aliases_allowed = $sender_acl_handles['fixed_sender_aliases_allowed'];

+                $fixed_sender_aliases_blocked = $sender_acl_handles['fixed_sender_aliases_blocked'];

+

                 foreach ($sender_acl_merged as $sender_acl) {

                   $domain = ltrim($sender_acl, '@');

                   if (is_valid_domain_name($domain)) {

                     $sender_acl = '@' . $domain;

                   }

-                  // Don't add if allowed by alias

-                  if (in_array($sender_acl, $fixed_sender_aliases)) {

+

+                  // Always add to sender_acl table to create explicit permission

+                  // Skip only if it's in allowed list (would be redundant)

+                  // But DO add if it's in blocked list (creates override)

+                  if (in_array($sender_acl, $fixed_sender_aliases_allowed)) {

+                    // Skip: already allowed by sender_allowed=1, no need for sender_acl entry

                     continue;

                   }

+

+                  // Add to sender_acl (either override for blocked aliases, or grant for selectable ones)

                   $stmt = $pdo->prepare("INSERT INTO `sender_acl` (`send_as`, `logged_in_as`)

                     VALUES (:sender_acl, :username)");

                   $stmt->execute(array(

@@ -3118,7 +3435,7 @@
               $stmt = $pdo->prepare("UPDATE `mailbox` SET

                   `password` = :password_hashed,

                   `attributes` = JSON_SET(`attributes`, '$.passwd_update', NOW())

-                    WHERE `username` = :username");

+                    WHERE `username` = :username AND authsource = 'mailcow'");

               $stmt->execute(array(

                 ':password_hashed' => $password_hashed,

                 ':username' => $username

@@ -3132,31 +3449,60 @@
               ':address' => $username,

               ':active' => $active

             ));

-            $stmt = $pdo->prepare("UPDATE `mailbox` SET

-                `active` = :active,

-                `name`= :name,

-                `quota` = :quota_b,

-                `attributes` = JSON_SET(`attributes`, '$.force_pw_update', :force_pw_update),

-                `attributes` = JSON_SET(`attributes`, '$.sogo_access', :sogo_access),

-                `attributes` = JSON_SET(`attributes`, '$.imap_access', :imap_access),

-                `attributes` = JSON_SET(`attributes`, '$.sieve_access', :sieve_access),

-                `attributes` = JSON_SET(`attributes`, '$.pop3_access', :pop3_access),

-                `attributes` = JSON_SET(`attributes`, '$.relayhost', :relayhost),

-                `attributes` = JSON_SET(`attributes`, '$.smtp_access', :smtp_access)

-                  WHERE `username` = :username");

-            $stmt->execute(array(

-              ':active' => $active,

-              ':name' => $name,

-              ':quota_b' => $quota_b,

-              ':force_pw_update' => $force_pw_update,

-              ':sogo_access' => $sogo_access,

-              ':imap_access' => $imap_access,

-              ':pop3_access' => $pop3_access,

-              ':sieve_access' => $sieve_access,

-              ':smtp_access' => $smtp_access,

-              ':relayhost' => $relayhost,

-              ':username' => $username

-            ));

+            try {

+              $stmt = $pdo->prepare("UPDATE `mailbox` SET

+                  `active` = :active,

+                  `name`= :name,

+                  `quota` = :quota_b,

+                  `authsource` = :authsource,

+                  `attributes` = JSON_SET(`attributes`, '$.force_pw_update', :force_pw_update),

+                  `attributes` = JSON_SET(`attributes`, '$.force_tfa', :force_tfa),

+                  `attributes` = JSON_SET(`attributes`, '$.sogo_access', :sogo_access),

+                  `attributes` = JSON_SET(`attributes`, '$.imap_access', :imap_access),

+                  `attributes` = JSON_SET(`attributes`, '$.sieve_access', :sieve_access),

+                  `attributes` = JSON_SET(`attributes`, '$.pop3_access', :pop3_access),

+                  `attributes` = JSON_SET(`attributes`, '$.relayhost', :relayhost),

+                  `attributes` = JSON_SET(`attributes`, '$.smtp_access', :smtp_access),

+                  `attributes` = JSON_SET(`attributes`, '$.eas_access', :eas_access),

+                  `attributes` = JSON_SET(`attributes`, '$.dav_access', :dav_access),

+                  `attributes` = JSON_SET(`attributes`, '$.recovery_email', :recovery_email),

+                  `attributes` = JSON_SET(`attributes`, '$.attribute_hash', :attribute_hash)

+                    WHERE `username` = :username");

+              $stmt->execute(array(

+                ':active' => $active,

+                ':name' => $name,

+                ':quota_b' => $quota_b,

+                ':attribute_hash' => $attribute_hash,

+                ':force_pw_update' => $force_pw_update,

+                ':force_tfa' => $force_tfa,

+                ':sogo_access' => $sogo_access,

+                ':imap_access' => $imap_access,

+                ':pop3_access' => $pop3_access,

+                ':sieve_access' => $sieve_access,

+                ':smtp_access' => $smtp_access,

+                ':eas_access' => $eas_access,

+                ':dav_access' => $dav_access,

+                ':recovery_email' => $pw_recovery_email,

+                ':relayhost' => $relayhost,

+                ':username' => $username,

+                ':authsource' => $authsource

+              ));

+            }

+            catch (PDOException $e) {

+              $_SESSION['return'][] = array(

+                'type' => 'danger',

+                'log' => array(__FUNCTION__, $_action, $_type, $_data_log, $_attr),

+                'msg' => $e->getMessage()

+              );

+              return false;

+            }

+            // save delimiter_action

+            if (isset($_data['tagged_mail_handler'])) {

+              mailbox('edit', 'delimiter_action', array(

+                'username' => $username,

+                'tagged_mail_handler' => $_data['tagged_mail_handler']

+              ));

+            }

             // save tags

             foreach($tags as $index => $tag){

               if (empty($tag)) continue;

@@ -3168,21 +3514,289 @@
                 );

                 break;

               }

-              $stmt = $pdo->prepare("INSERT INTO `tags_mailbox` (`username`, `tag_name`) VALUES (:username, :tag_name)");

-              $stmt->execute(array(

-                ':username' => $username,

-                ':tag_name' => $tag,

-              ));

+              try {

+                $stmt = $pdo->prepare("INSERT INTO `tags_mailbox` (`username`, `tag_name`) VALUES (:username, :tag_name)");

+                $stmt->execute(array(

+                  ':username' => $username,

+                  ':tag_name' => $tag,

+                ));

+              } catch (Exception $e) {

+              }

             }

-            

+

             $_SESSION['return'][] = array(

               'type' => 'success',

               'log' => array(__FUNCTION__, $_action, $_type, $_data_log, $_attr),

               'msg' => array('mailbox_modified', $username)

             );

 

-            update_sogo_static_view($username);

+            // Track affected mailboxes for SOGo update

+            $update_sogo_mailboxes[] = $username;

           }

+        break;

+        case 'mailbox_rename':

+          $domain = $_data['domain'];

+          $old_local_part = $_data['old_local_part'];

+          $old_username = $old_local_part . "@" . $domain;

+          $new_local_part = $_data['new_local_part'];

+          $new_username = $new_local_part . "@" . $domain;

+          $create_alias = intval($_data['create_alias']);

+

+          if (!filter_var($old_username, FILTER_VALIDATE_EMAIL)) {

+            $_SESSION['return'][] = array(

+              'type' => 'danger',

+              'log' => array(__FUNCTION__, $_action, $_type, $_data_log, $_attr),

+              'msg' => array('username_invalid', $old_username)

+            );

+            return false;

+          }

+          if (!filter_var($new_username, FILTER_VALIDATE_EMAIL)) {

+            $_SESSION['return'][] = array(

+              'type' => 'danger',

+              'log' => array(__FUNCTION__, $_action, $_type, $_data_log, $_attr),

+              'msg' => array('username_invalid', $new_username)

+            );

+            return false;

+          }

+

+          $is_now = mailbox('get', 'mailbox_details', $old_username);

+          if (empty($is_now) || ($is_now['active'] != '1' && $is_now['active'] != '2')) {

+            $_SESSION['return'][] = array(

+              'type' => 'danger',

+              'log' => array(__FUNCTION__, $_action, $_type, $_data_log, $_attr),

+              'msg' => 'access_denied'

+            );

+            return false;

+          }

+

+          if (!hasDomainAccess($_SESSION['mailcow_cc_username'], $_SESSION['mailcow_cc_role'], $is_now['domain'])) {

+            $_SESSION['return'][] = array(

+              'type' => 'danger',

+              'log' => array(__FUNCTION__, $_action, $_type, $_data_log, $_attr),

+              'msg' => 'access_denied'

+            );

+            return false;

+          }

+

+          // get imap acls

+          try {

+            $exec_fields = array(

+              'cmd' => 'doveadm',

+              'task' => 'get_acl',

+              'id' => $old_username

+            );

+            $imap_acls = json_decode(docker('post', 'dovecot-mailcow', 'exec', $exec_fields), true);

+            // delete imap acls

+            foreach ($imap_acls as $imap_acl) {

+              $exec_fields = array(

+                'cmd' => 'doveadm',

+                'task' => 'delete_acl',

+                'user' => $imap_acl['user'],

+                'mailbox' => $imap_acl['mailbox'],

+                'id' => $imap_acl['id']

+              );

+              docker('post', 'dovecot-mailcow', 'exec', $exec_fields);

+            }

+          } catch (Exception $e) {

+            $_SESSION['return'][] = array(

+              'type' => 'danger',

+              'log' => array(__FUNCTION__, $_action, $_type, $_data_log, $_attr),

+              'msg' => $e->getMessage()

+            );

+            return false;

+          }

+

+          // rename username in sql

+          try {

+            $pdo->beginTransaction();

+            $pdo->exec('SET FOREIGN_KEY_CHECKS = 0');

+

+            // Update username in mailbox table

+            $pdo->prepare('UPDATE mailbox SET username = :new_username, local_part = :new_local_part WHERE username = :old_username')

+              ->execute([

+                ':new_username' => $new_username,

+                ':new_local_part' => $new_local_part,

+                ':old_username' => $old_username

+              ]);

+

+            $pdo->prepare("UPDATE alias SET address = :new_username, goto = :new_username2 WHERE address = :old_username")

+            ->execute([

+              ':new_username' => $new_username,

+              ':new_username2' => $new_username,

+              ':old_username' => $old_username

+            ]);

+

+            // Update the username in all related tables

+            $tables = [

+              'tags_mailbox' => ['username'],

+              'sieve_filters' => ['username'],

+              'app_passwd' => ['mailbox'],

+              'user_acl' => ['username'],

+              'da_acl' => ['username'],

+              'quota2' => ['username'],

+              'quota2replica' => ['username'],

+              'pushover' => ['username'],

+              'alias' => ['goto'],

+              "imapsync" => ['user2'],

+              'bcc_maps' => ['local_dest', 'bcc_dest'],

+              'recipient_maps' => ['old_dest', 'new_dest'],

+              'sender_acl' => ['logged_in_as', 'send_as']

+            ];

+            foreach ($tables as $table => $columns) {

+              foreach ($columns as $column) {

+                $stmt = $pdo->prepare("UPDATE $table SET $column = :new_username WHERE $column = :old_username")

+                  ->execute([

+                    ':new_username' => $new_username,

+                    ':old_username' => $old_username

+                  ]);

+              }

+            }

+

+            // Update c_uid, c_name and mail in _sogo_static_view table

+            $pdo->prepare("UPDATE _sogo_static_view SET c_uid = :new_username, c_name = :new_username2, mail = :new_username3 WHERE c_uid = :old_username")

+              ->execute([

+                ':new_username' => $new_username,

+                ':new_username2' => $new_username,

+                ':new_username3' => $new_username,

+                ':old_username' => $old_username

+              ]);

+

+            // Re-enable foreign key checks

+            $pdo->exec('SET FOREIGN_KEY_CHECKS = 1');

+            $pdo->commit();

+          } catch (PDOException $e) {

+            // Rollback the transaction if something goes wrong

+            $pdo->rollBack();

+            $_SESSION['return'][] = array(

+              'type' => 'danger',

+              'log' => array(__FUNCTION__, $_action, $_type, $_data_log, $_attr),

+              'msg' => $e->getMessage()

+            );

+            return false;

+          }

+

+          // move maildir

+          $exec_fields = array(

+            'cmd' => 'maildir',

+            'task' => 'move',

+            'old_maildir' => $domain . '/' . $old_local_part,

+            'new_maildir' => $domain . '/' . $new_local_part

+          );

+          if (getenv("CLUSTERMODE") == "replication") {

+            // broadcast to each dovecot container

+            docker('broadcast', 'dovecot-mailcow', 'exec', $exec_fields);

+          } else {

+            docker('post', 'dovecot-mailcow', 'exec', $exec_fields);

+          }

+

+          // rename username in sogo

+          $exec_fields = array(

+            'cmd' => 'sogo',

+            'task' => 'rename_user',

+            'old_username' => $old_username,

+            'new_username' => $new_username

+          );

+          docker('post', 'sogo-mailcow', 'exec', $exec_fields);

+

+          // set imap acls

+          foreach ($imap_acls as $imap_acl) {

+            $user_id = ($imap_acl['id'] == $old_username) ? $new_username : $imap_acl['id'];

+            $user = ($imap_acl['user'] == $old_username) ? $new_username : $imap_acl['user'];

+            $exec_fields = array(

+              'cmd' => 'doveadm',

+              'task' => 'set_acl',

+              'user' => $user,

+              'mailbox' => $imap_acl['mailbox'],

+              'id' => $user_id,

+              'rights' => $imap_acl['rights']

+            );

+            docker('post', 'dovecot-mailcow', 'exec', $exec_fields);

+          }

+

+          // create alias

+          if ($create_alias == 1) {

+            mailbox("add", "alias", array(

+              "address" => $old_username,

+              "goto" => $new_username,

+              "active" => 1,

+              "sogo_visible" => 1,

+              "private_comment" => sprintf($lang['success']['mailbox_renamed'], $old_username, $new_username)

+            ));

+          }

+

+          $_SESSION['return'][] = array(

+            'type' => 'success',

+            'log' => array(__FUNCTION__, $_action, $_type, $_data_log, $_attr),

+            'msg' => array('mailbox_renamed', $old_username, $new_username)

+          );

+        break;

+        case 'mailbox_from_template':

+          $stmt = $pdo->prepare("SELECT * FROM `templates`

+          WHERE `template` = :template AND type = 'mailbox'");

+          $stmt->execute(array(

+            ":template" => $_data['template']

+          ));

+          $mbox_template_data = $stmt->fetch(PDO::FETCH_ASSOC);

+          if (empty($mbox_template_data)){

+            $_SESSION['return'][] =  array(

+              'type' => 'danger',

+              'log' => array(__FUNCTION__, $_action, $_type, $_data_log, $_attr),

+              'msg' => 'template_missing'

+            );

+            return false;

+          }

+

+          $attribute_hash = sha1(json_encode($mbox_template_data["attributes"]));

+          $is_now = mailbox('get', 'mailbox_details', $_data['username']);

+          $name = ltrim(rtrim($_data['name'], '>'), '<');

+          if ($is_now['attributes']['attribute_hash'] == $attribute_hash && $is_now['name'] == $name)

+            return true;

+

+          $mbox_template_data = json_decode($mbox_template_data["attributes"], true);

+          $mbox_template_data['attribute_hash'] = $attribute_hash;

+          $mbox_template_data['name'] = $name;

+          $quarantine_attributes = array('username' => $_data['username']);

+          $tls_attributes = array('username' => $_data['username']);

+          $ratelimit_attributes = array('object' => $_data['username']);

+          $acl_attributes = array('username' => $_data['username'], 'user_acl' => array());

+          $mailbox_attributes = array('username' => $_data['username']);

+          foreach ($mbox_template_data as $key => $value){

+            switch (true) {

+              case (strpos($key, 'quarantine_') === 0):

+                $quarantine_attributes[$key] = $value;

+              break;

+              case (strpos($key, 'tls_') === 0):

+                if ($value == null)

+                  $value = 0;

+                $tls_attributes[$key] = $value;

+              break;

+              case (strpos($key, 'rl_') === 0):

+                $ratelimit_attributes[$key] = $value;

+              break;

+              case (strpos($key, 'acl_') === 0 && $value != 0):

+                array_push($acl_attributes['user_acl'], str_replace('acl_' , '', $key));

+              break;

+              default:

+                $mailbox_attributes[$key] = $value;

+              break;

+            }

+          }

+

+          $mailbox_attributes['quota'] = intval($mailbox_attributes['quota'] / 1048576);

+          $result = mailbox('edit', 'mailbox', $mailbox_attributes);

+          if ($result === false) return $result;

+          $result = mailbox('edit', 'tls_policy', $tls_attributes);

+          if ($result === false) return $result;

+          $result = mailbox('edit', 'quarantine_notification', $quarantine_attributes);

+          if ($result === false) return $result;

+          $result = mailbox('edit', 'quarantine_category', $quarantine_attributes);

+          if ($result === false) return $result;

+          $result = ratelimit('edit', 'mailbox', $ratelimit_attributes);

+          if ($result === false) return $result;

+          $result = acl('edit', 'user', $acl_attributes);

+          if ($result === false) return $result;

+

+          $_SESSION['return'] = array();

           return true;

         break;

         case 'mailbox_templates':

@@ -3217,20 +3831,31 @@
             // check name

             if ($is_now["template"] == "Default" && $is_now["template"] != $_data["template"]){

               // keep template name of Default template

-              $_data["template"]                   = $is_now["template"]; 

+              $_data["template"]                   = $is_now["template"];

             }

             else {

-              $_data["template"]                   = (isset($_data["template"])) ? $_data["template"] : $is_now["template"]; 

-            }   

+              $_data["template"]                   = (isset($_data["template"])) ? $_data["template"] : $is_now["template"];

+            }

             // check attributes

             $attr = array();

             $attr["quota"]                       = isset($_data['quota']) ? intval($_data['quota']) * 1048576 : 0;

             $attr['tags']                        = (isset($_data['tags'])) ? $_data['tags'] : $is_now['tags'];

+            $attr["tagged_mail_handler"]         = (!empty($_data['tagged_mail_handler'])) ? $_data['tagged_mail_handler'] : $is_now['tagged_mail_handler'];

             $attr["quarantine_notification"]     = (!empty($_data['quarantine_notification'])) ? $_data['quarantine_notification'] : $is_now['quarantine_notification'];

             $attr["quarantine_category"]         = (!empty($_data['quarantine_category'])) ? $_data['quarantine_category'] : $is_now['quarantine_category'];

+            // Validate quarantine_category

+            if (!in_array($attr["quarantine_category"], array('add_header', 'reject', 'all'))) {

+              $_SESSION['return'][] = array(

+                'type' => 'danger',

+                'log' => array(__FUNCTION__, $_action, $_type, $_data_log, $_extra),

+                'msg' => 'quarantine_category_invalid'

+              );

+              continue;

+            }

             $attr["rl_frame"]                    = (!empty($_data['rl_frame'])) ? $_data['rl_frame'] : $is_now['rl_frame'];

             $attr["rl_value"]                    = (!empty($_data['rl_value'])) ? $_data['rl_value'] : $is_now['rl_value'];

             $attr["force_pw_update"]             = isset($_data['force_pw_update']) ? intval($_data['force_pw_update']) : $is_now['force_pw_update'];

+            $attr["force_tfa"]                   = isset($_data['force_tfa']) ? intval($_data['force_tfa']) : $is_now['force_tfa'];

             $attr["sogo_access"]                 = isset($_data['sogo_access']) ? intval($_data['sogo_access']) : $is_now['sogo_access'];

             $attr["active"]                      = isset($_data['active']) ? intval($_data['active']) : $is_now['active'];

             $attr["tls_enforce_in"]              = isset($_data['tls_enforce_in']) ? intval($_data['tls_enforce_in']) : $is_now['tls_enforce_in'];

@@ -3241,11 +3866,13 @@
               $attr['pop3_access'] = (in_array('pop3', $_data['protocol_access'])) ? 1 : 0;

               $attr['smtp_access'] = (in_array('smtp', $_data['protocol_access'])) ? 1 : 0;

               $attr['sieve_access'] = (in_array('sieve', $_data['protocol_access'])) ? 1 : 0;

-            }          

-            else { 

+              $attr['eas_access'] = (in_array('eas', $_data['protocol_access'])) ? 1 : 0;

+              $attr['dav_access'] = (in_array('dav', $_data['protocol_access'])) ? 1 : 0;

+            }

+            else {

               foreach ($is_now as $key => $value){

                 $attr[$key] = $is_now[$key];

-              }    

+              }

             }

             if (isset($_data['acl'])) {

               $_data['acl'] = (array)$_data['acl'];

@@ -3263,10 +3890,11 @@
               $attr['acl_quarantine_notification'] = (in_array('quarantine_notification', $_data['acl'])) ? 1 : 0;

               $attr['acl_quarantine_category'] = (in_array('quarantine_category', $_data['acl'])) ? 1 : 0;

               $attr['acl_app_passwds'] = (in_array('app_passwds', $_data['acl'])) ? 1 : 0;

-            } else {    

+              $attr['acl_pw_reset'] = (in_array('pw_reset', $_data['acl'])) ? 1 : 0;

+            } else {

               foreach ($is_now as $key => $value){

                 $attr[$key] = $is_now[$key];

-              }        

+              }

             }

 

 

@@ -3278,7 +3906,7 @@
               ":id" => $id ,

               ":template" => $_data["template"] ,

               ":attributes" => json_encode($attr)

-            )); 

+            ));

           }

 

 

@@ -3307,7 +3935,7 @@
               );

               continue;

             }

-            $is_now = mailbox('get', 'mailbox_details', $mailbox);            

+            $is_now = mailbox('get', 'mailbox_details', $mailbox);

             if(!empty($is_now)){

               if (!hasDomainAccess($_SESSION['mailcow_cc_username'], $_SESSION['mailcow_cc_role'], $is_now['domain'])) {

                 $_SESSION['return'][] = array(

@@ -3334,15 +3962,134 @@
             $stmt->execute(array(

               ":username" => $mailbox,

               ":custom_attributes" => json_encode($attributes)

-            ));             

-            

+            ));

+

             $_SESSION['return'][] = array(

               'type' => 'success',

               'log' => array(__FUNCTION__, $_action, $_type, $_data_log, $_attr),

               'msg' => array('mailbox_modified', $mailbox)

             );

           }

-          

+

+          return true;

+        break;

+        case 'mta_sts':

+          if (!is_array($_data['domains'])) {

+            $domains = array();

+            $domains[] = $_data['domains'];

+          }

+          else {

+            $domains = $_data['domains'];

+          }

+

+          foreach ($domains as $domain) {

+            $domain       = idn_to_ascii(strtolower(trim($domain)), 0, INTL_IDNA_VARIANT_UTS46);

+

+            if (!hasDomainAccess($_SESSION['mailcow_cc_username'], $_SESSION['mailcow_cc_role'], $domain)) {

+              $_SESSION['return'][] = array(

+                'type' => 'danger',

+                'log' => array(__FUNCTION__, $_action, $_type, $_data, $_attr),

+                'msg' => 'access_denied'

+              );

+              continue;

+            }

+

+            $is_now = mailbox('get', 'mta_sts', $domain);

+            if (!empty($is_now)) {

+              $version               = (isset($_data['version'])) ? strtolower($_data['version']) : $is_now['version'];

+              $active                = (isset($_data['active'])) ? intval($_data['active']) : $is_now['active'];

+              $active                = ($active == 1) ? 1 : 0;

+              $mode                  = (isset($_data['mode'])) ? strtolower($_data['mode']) : $is_now['mode'];

+              $mx                    = (isset($_data['mx'])) ? explode(",", preg_replace('/\s+/', '', $_data['mx'])) : $is_now['mx'];

+              $max_age               = (isset($_data['max_age'])) ? intval($_data['max_age']) : $is_now['max_age'];

+

+              // Update ID if neccesary

+              if ($version != strtolower($is_now['version']) ||

+                  $mode != strtolower($is_now['mode']) ||

+                  $mx != $is_now['mx'] ||

+                  $max_age != $is_now['max_age']) {

+                $id           = date('YmdHis');

+              } else {

+                $id           = $is_now['id'];

+              }

+

+            } else {

+              $_SESSION['return'][] = array(

+                'type' => 'danger',

+                'log' => array(__FUNCTION__, $_action, $_type, $_data_log, $_attr),

+                'msg' => 'access_denied'

+              );

+              continue;

+            }

+

+            if (empty($version) || !in_array($version, array('stsv1'))) {

+              $_SESSION['return'][] = array(

+                'type' => 'danger',

+                'log' => array(__FUNCTION__, $_action, $_type, $_data, $_attr),

+                'msg' => array('version_invalid', htmlspecialchars($version))

+              );

+              continue;

+            }

+            if (empty($mode) || !in_array($mode, array('enforce', 'testing', 'none'))) {

+              $_SESSION['return'][] = array(

+                'type' => 'danger',

+                'log' => array(__FUNCTION__, $_action, $_type, $_data, $_attr),

+                'msg' => array('mode_invalid', htmlspecialchars($domain))

+              );

+              continue;

+            }

+            if (empty($max_age) || $max_age < 0 || $max_age > 31557600) {

+              $_SESSION['return'][] = array(

+                'type' => 'danger',

+                'log' => array(__FUNCTION__, $_action, $_type, $_data, $_attr),

+                'msg' => array('max_age_invalid', htmlspecialchars($domain))

+              );

+              continue;

+            }

+            foreach ($mx as $index => $mx_domain) {

+              $mx_domain = idn_to_ascii(strtolower(trim($mx_domain)), 0, INTL_IDNA_VARIANT_UTS46);

+              $invalid_mx = false;

+              if (!is_valid_domain_name($mx_domain, array('allow_wildcard' => true))) {

+                $invalid_mx = $mx_domain;

+                break;

+              }

+            }

+            if ($invalid_mx) {

+              $_SESSION['return'][] = array(

+                'type' => 'danger',

+                'log' => array(__FUNCTION__, $_action, $_type, $_data, $_attr),

+                'msg' => array('mx_invalid', htmlspecialchars($invalid_mx))

+              );

+              continue;

+            }

+

+            try {

+              $stmt = $pdo->prepare("UPDATE `mta_sts` SET `id` = :id, `version` = :version, `mode` = :mode, `mx` = :mx, `max_age` = :max_age, `active` = :active WHERE `domain` = :domain");

+              $stmt->execute(array(

+                ':id' => $id,

+                ':domain' => $domain,

+                ':version' => $version,

+                ':mode' => $mode,

+                ':mx' => implode(",", $mx),

+                ':max_age' => $max_age,

+                ':active' => $active

+              ));

+            } catch (PDOException $e) {

+              $_SESSION['return'][] = array(

+                'type' => 'danger',

+                'log' => array(__FUNCTION__, $_action, $_type, $_data),

+                'msg' => $e->getMessage()

+              );

+              continue;

+            }

+

+            $_SESSION['return'][] = array(

+              'type' => 'success',

+              'log' => array(__FUNCTION__, $_action, $_type, $_data, $_attr),

+              'msg' => array('object_modified', $domain)

+            );

+          }

+

           return true;

         break;

         case 'resource':

@@ -3422,9 +4169,12 @@
               'log' => array(__FUNCTION__, $_action, $_type, $_data_log, $_attr),

               'msg' => array('resource_modified', htmlspecialchars($name))

             );

+

+            // Track affected mailboxes for SOGo update

+            $update_sogo_mailboxes[] = $name;

           }

         break;

-        case 'domain_wide_footer':  

+        case 'domain_wide_footer':

           if (!is_array($_data['domains'])) {

             $domains = array();

             $domains[] = $_data['domains'];

@@ -3550,13 +4300,22 @@
           $data['sender_acl_addresses']['rw']             = array();

           $data['sender_acl_addresses']['selectable']     = array();

           $data['fixed_sender_aliases']                   = array();

+          $data['fixed_sender_aliases_allowed']           = array();

+          $data['fixed_sender_aliases_blocked']           = array();

           $data['external_sender_aliases']                = array();

-          // Fixed addresses

-          $stmt = $pdo->prepare("SELECT `address` FROM `alias` WHERE `goto` REGEXP :goto AND `address` NOT LIKE '@%'");

-          $stmt->execute(array(':goto' => '(^|,)'.$_data.'($|,)'));

+          // Fixed addresses - split by sender_allowed status

+          $stmt = $pdo->prepare("SELECT `address`, `sender_allowed` FROM `alias` WHERE `goto` REGEXP :goto AND `address` NOT LIKE '@%'");

+          $stmt->execute(array(':goto' => '(^|,)'.preg_quote($_data, '/').'($|,)'));

           $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

           while ($row = array_shift($rows)) {

+            // Keep old array for backward compatibility

             $data['fixed_sender_aliases'][] = $row['address'];

+            // Split into allowed/blocked for proper display

+            if ($row['sender_allowed'] == '1') {

+              $data['fixed_sender_aliases_allowed'][] = $row['address'];

+            } else {

+              $data['fixed_sender_aliases_blocked'][] = $row['address'];

+            }

           }

           $stmt = $pdo->prepare("SELECT CONCAT(`local_part`, '@', `alias_domain`.`alias_domain`) AS `alias_domain_alias` FROM `mailbox`, `alias_domain`

             WHERE `alias_domain`.`target_domain` = `mailbox`.`domain`

@@ -3677,7 +4436,7 @@
 

             // prepend domain to array

             $params = array();

-            foreach ($tags as $key => $val){ 

+            foreach ($tags as $key => $val){

               array_push($params, '%'.$_data.'%');

               array_push($params, '%'.$val.'%');

             }

@@ -3686,7 +4445,7 @@
 

             $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

             while($row = array_shift($rows)) {

-              if (hasDomainAccess($_SESSION['mailcow_cc_username'], $_SESSION['mailcow_cc_role'], explode('@', $row['username'])[1])) 

+              if (hasDomainAccess($_SESSION['mailcow_cc_username'], $_SESSION['mailcow_cc_role'], explode('@', $row['username'])[1]))

                 $mailboxes[] = $row['username'];

             }

           }

@@ -3986,12 +4745,15 @@
           }

           $stmt = $pdo->prepare("SELECT `address`,

             `goto`,

+            `description`,

             `validity`,

             `created`,

-            `modified`

+            `modified`,

+            `permanent`

               FROM `spamalias`

                 WHERE `goto` = :username

-                  AND `validity` >= :unixnow");

+                  AND (`validity` >= :unixnow

+                    OR `permanent` != 0)");

           $stmt->execute(array(':username' => $_data, ':unixnow' => time()));

           $tladata = $stmt->fetchAll(PDO::FETCH_ASSOC);

           return $tladata;

@@ -4110,8 +4872,10 @@
             `address`,

             `public_comment`,

             `private_comment`,

+            `internal`,

             `active`,

             `sogo_visible`,

+            `sender_allowed`,

             `created`,

             `modified`

               FROM `alias`

@@ -4140,10 +4904,12 @@
           $aliasdata['goto'] = $row['goto'];

           $aliasdata['address'] = $row['address'];

           (!filter_var($aliasdata['address'], FILTER_VALIDATE_EMAIL)) ? $aliasdata['is_catch_all'] = 1 : $aliasdata['is_catch_all'] = 0;

+          $aliasdata['internal'] = $row['internal'];

           $aliasdata['active'] = $row['active'];

           $aliasdata['active_int'] = $row['active'];

           $aliasdata['sogo_visible'] = $row['sogo_visible'];

           $aliasdata['sogo_visible_int'] = $row['sogo_visible'];

+          $aliasdata['sender_allowed'] = $row['sender_allowed'];

           $aliasdata['created'] = $row['created'];

           $aliasdata['modified'] = $row['modified'];

           if (!hasDomainAccess($_SESSION['mailcow_cc_username'], $_SESSION['mailcow_cc_role'], $aliasdata['domain'])) {

@@ -4241,7 +5007,7 @@
             while($row = array_shift($rows)) {

               if ($_SESSION['mailcow_cc_role'] == "admin")

                 $domains[] = $row['domain'];

-              elseif (hasDomainAccess($_SESSION['mailcow_cc_username'], $_SESSION['mailcow_cc_role'], $row['domain'])) 

+              elseif (hasDomainAccess($_SESSION['mailcow_cc_username'], $_SESSION['mailcow_cc_role'], $row['domain']))

                 $domains[] = $row['domain'];

             }

           } else {

@@ -4401,19 +5167,19 @@
           }

           $_data = (isset($_data)) ? intval($_data) : null;

 

-          if (isset($_data)){          

-            $stmt = $pdo->prepare("SELECT * FROM `templates` 

+          if (isset($_data)){

+            $stmt = $pdo->prepare("SELECT * FROM `templates`

               WHERE `id` = :id AND type = :type");

             $stmt->execute(array(

               ":id" => $_data,

               ":type" => "domain"

             ));

             $row = $stmt->fetch(PDO::FETCH_ASSOC);

-  

+

             if (empty($row)){

               return false;

             }

-  

+

             $row["attributes"] = json_decode($row["attributes"], true);

             return $row;

           }

@@ -4421,11 +5187,11 @@
             $stmt = $pdo->prepare("SELECT * FROM `templates` WHERE `type` =  'domain'");

             $stmt->execute();

             $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

-  

+

             if (empty($rows)){

               return false;

             }

-  

+

             foreach($rows as $key => $row){

               $rows[$key]["attributes"] = json_decode($row["attributes"], true);

             }

@@ -4448,6 +5214,7 @@
               `mailbox`.`quota`,

               `mailbox`.`created`,

               `mailbox`.`modified`,

+              `mailbox`.`authsource`,

               `quota2`.`bytes`,

               `attributes`,

               `custom_attributes`,

@@ -4469,6 +5236,7 @@
               `mailbox`.`quota`,

               `mailbox`.`created`,

               `mailbox`.`modified`,

+              `mailbox`.`authsource`,

               `quota2replica`.`bytes`,

               `attributes`,

               `custom_attributes`,

@@ -4498,6 +5266,7 @@
           $mailboxdata['percent_in_use'] = ($row['quota'] == 0) ? '- ' : round((intval($row['bytes']) / intval($row['quota'])) * 100);

           $mailboxdata['created'] = $row['created'];

           $mailboxdata['modified'] = $row['modified'];

+          $mailboxdata['authsource'] = ($row['authsource']) ? $row['authsource'] : 'mailcow';

 

           if ($mailboxdata['percent_in_use'] === '- ') {

             $mailboxdata['percent_class'] = "info";

@@ -4528,6 +5297,9 @@
             else if ($SaslLogs['service'] == 'pop3') {

               $last_pop3_login = strtotime($SaslLogs['datetime']);

             }

+			      else if ($SaslLogs['service'] == 'SSO') {

+              $last_sso_login = strtotime($SaslLogs['datetime']);

+            }

           }

           if (!isset($last_imap_login) || $GLOBALS['SHOW_LAST_LOGIN'] === false) {

             $last_imap_login = 0;

@@ -4538,9 +5310,13 @@
           if (!isset($last_pop3_login) || $GLOBALS['SHOW_LAST_LOGIN'] === false) {

             $last_pop3_login = 0;

           }

+		      if (!isset($last_sso_login) || $GLOBALS['SHOW_LAST_LOGIN'] === false) {

+            $last_sso_login = 0;

+          }

           $mailboxdata['last_imap_login'] = $last_imap_login;

           $mailboxdata['last_smtp_login'] = $last_smtp_login;

           $mailboxdata['last_pop3_login'] = $last_pop3_login;

+          $mailboxdata['last_sso_login'] = $last_sso_login;

 

           if (!isset($_extra) || $_extra != 'reduced') {

             $rl = ratelimit('get', 'mailbox', $_data);

@@ -4554,7 +5330,7 @@
             $stmt = $pdo->prepare("SELECT COALESCE(SUM(`quota`), 0) as `in_use` FROM `mailbox` WHERE (`kind` = '' OR `kind` = NULL) AND `domain` = :domain AND `username` != :username");

             $stmt->execute(array(':domain' => $row['domain'], ':username' => $_data));

             $MailboxUsage = $stmt->fetch(PDO::FETCH_ASSOC);

-            $stmt = $pdo->prepare("SELECT IFNULL(COUNT(`address`), 0) AS `sa_count` FROM `spamalias` WHERE `goto` = :address AND `validity` >= :unixnow");

+            $stmt = $pdo->prepare("SELECT IFNULL(COUNT(`address`), 0) AS `sa_count` FROM `spamalias` WHERE `goto` = :address AND (`validity` >= :unixnow OR `permanent` != 0)");

             $stmt->execute(array(':address' => $_data, ':unixnow' => time()));

             $SpamaliasUsage = $stmt->fetch(PDO::FETCH_ASSOC);

             $mailboxdata['max_new_quota'] = ($DomainQuota['quota'] * 1048576) - $MailboxUsage['in_use'];

@@ -4572,6 +5348,14 @@
               $mailboxdata['rl_scope'] = 'domain';

             }

             $mailboxdata['is_relayed'] = $row['backupmx'];

+            // Internal send-as ACL for this mailbox, mirrors the sender_acl field accepted by edit/mailbox

+            $mailboxdata['sender_acl'] = array();

+            $stmt = $pdo->prepare("SELECT `send_as` FROM `sender_acl` WHERE `logged_in_as` = :username AND `external` = '0'");

+            $stmt->execute(array(':username' => $_data));

+            $sender_acl_rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

+            foreach ($sender_acl_rows as $sender_acl_row) {

+              $mailboxdata['sender_acl'][] = $sender_acl_row['send_as'];

+            }

           }

           $stmt = $pdo->prepare("SELECT `tag_name`

             FROM `tags_mailbox` WHERE `username`= :username");

@@ -4586,24 +5370,24 @@
           return $mailboxdata;

         break;

         case 'mailbox_templates':

-          if ($_SESSION['mailcow_cc_role'] != "admin" && $_SESSION['mailcow_cc_role'] != "domainadmin") {

+          if ($_SESSION['mailcow_cc_role'] != "admin" && $_SESSION['mailcow_cc_role'] != "domainadmin" && $_SESSION['access_all_exception'] != "1") {

             return false;

           }

           $_data = (isset($_data)) ? intval($_data) : null;

 

-          if (isset($_data)){          

-            $stmt = $pdo->prepare("SELECT * FROM `templates` 

+          if (isset($_data)){

+            $stmt = $pdo->prepare("SELECT * FROM `templates`

               WHERE `id` = :id AND type = :type");

             $stmt->execute(array(

               ":id" => $_data,

               ":type" => "mailbox"

             ));

             $row = $stmt->fetch(PDO::FETCH_ASSOC);

-  

+

             if (empty($row)){

               return false;

             }

-  

+

             $row["attributes"] = json_decode($row["attributes"], true);

             return $row;

           }

@@ -4622,6 +5406,20 @@
             return $rows;

           }

         break;

+        case 'mta_sts':

+          $stmt = $pdo->prepare("SELECT * FROM `mta_sts` WHERE `domain` = :domain");

+          $stmt->execute(array(

+            ':domain' => $_data,

+          ));

+          $row = $stmt->fetch(PDO::FETCH_ASSOC);

+          if (empty($row)){

+            return [];

+          }

+          $row['mx'] = explode(',', $row['mx']);

+          $row['version'] = strtoupper(substr($row['version'], 0, 3)) . substr($row['version'], 3);

+

+          return $row;

+        break;

         case 'resource_details':

           $resourcedata = array();

           if (!hasMailboxObjectAccess($_SESSION['mailcow_cc_username'], $_SESSION['mailcow_cc_role'], $_data)) {

@@ -4885,8 +5683,11 @@
             $stmt->execute(array(

               ':username' => $username

             ));

-            $stmt = $pdo->prepare("DELETE FROM `sogo_acl` WHERE `c_object` LIKE '%/" . $username . "/%' OR `c_uid` = :username");

+            // bind LIKE pattern + escape LIKE wildcards so the value matches literally (no SQLi, no over-match)

+            $c_object_like = '%/' . addcslashes($username, '\\%_') . '/%';

+            $stmt = $pdo->prepare("DELETE FROM `sogo_acl` WHERE `c_object` LIKE :c_object_like OR `c_uid` = :username");

             $stmt->execute(array(

+              ':c_object_like' => $c_object_like,

               ':username' => $username

             ));

             $stmt = $pdo->prepare("DELETE FROM `sogo_store` WHERE `c_folder_id` IN (SELECT `c_folder_id` FROM `sogo_folder_info` WHERE `c_path2` = :username)");

@@ -5007,6 +5808,10 @@
             $stmt->execute(array(

               ':domain' => $domain,

             ));

+            $stmt = $pdo->prepare("DELETE FROM `mta_sts` WHERE `domain` = :domain");

+            $stmt->execute(array(

+              ':domain' => $domain,

+            ));

             $stmt = $pdo->query("DELETE FROM `admin` WHERE `superadmin` = 0 AND `username` NOT IN (SELECT `username`FROM `domain_admins`);");

             $stmt = $pdo->query("DELETE FROM `da_acl` WHERE `username` NOT IN (SELECT `username`FROM `domain_admins`);");

             try {

@@ -5045,7 +5850,7 @@
             $ids = $_data['ids'];

           }

 

-          

+

           foreach ($ids as $id) {

             // delete template

             $stmt = $pdo->prepare("DELETE FROM `templates`

@@ -5082,6 +5887,18 @@
               );

               continue;

             }

+

+            // Track affected mailboxes for SOGo update (capture before deletion)

+            if (!empty($alias_data['goto'])) {

+              $gotos = array_map('trim', explode(',', $alias_data['goto']));

+              foreach ($gotos as $g) {

+                if (filter_var($g, FILTER_VALIDATE_EMAIL) &&

+                    !in_array($g, array('null@localhost', 'spam@localhost', 'ham@localhost'))) {

+                  $update_sogo_mailboxes[] = $g;

+                }

+              }

+            }

+

             $stmt = $pdo->prepare("DELETE FROM `alias` WHERE `id` = :id");

             $stmt->execute(array(

               ':id' => $alias_data['id']

@@ -5212,25 +6029,6 @@
                 'msg' => 'Could not move maildir to garbage collector: variables local_part and/or domain empty'

               );

             }

-            if (strtolower(getenv('SKIP_SOLR')) == 'n') {

-              $curl = curl_init();

-              curl_setopt($curl, CURLOPT_URL, 'http://solr:8983/solr/dovecot-fts/update?commit=true');

-              curl_setopt($curl, CURLOPT_HTTPHEADER,array('Content-Type: text/xml'));

-              curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);

-              curl_setopt($curl, CURLOPT_POST, 1);

-              curl_setopt($curl, CURLOPT_POSTFIELDS, '<delete><query>user:' . $username . '</query></delete>');

-              curl_setopt($curl, CURLOPT_TIMEOUT, 30);

-              $response = curl_exec($curl);

-              if ($response === false) {

-                $err = curl_error($curl);

-                $_SESSION['return'][] = array(

-                  'type' => 'warning',

-                  'log' => array(__FUNCTION__, $_action, $_type, $_data_log, $_attr),

-                  'msg' => 'Could not remove Solr index: ' . print_r($err, true)

-                );

-              }

-              curl_close($curl);

-            }

             $stmt = $pdo->prepare("DELETE FROM `alias` WHERE `goto` = :username");

             $stmt->execute(array(

               ':username' => $username

@@ -5285,8 +6083,11 @@
             $stmt->execute(array(

               ':username' => $username

             ));

-            $stmt = $pdo->prepare("DELETE FROM `sogo_acl` WHERE `c_object` LIKE '%/" . str_replace('%', '\%', $username) . "/%' OR `c_uid` = :username");

+            // bind LIKE pattern + escape LIKE wildcards so the value matches literally (no SQLi, no over-match)

+            $c_object_like = '%/' . addcslashes($username, '\\%_') . '/%';

+            $stmt = $pdo->prepare("DELETE FROM `sogo_acl` WHERE `c_object` LIKE :c_object_like OR `c_uid` = :username");

             $stmt->execute(array(

+              ':c_object_like' => $c_object_like,

               ':username' => $username

             ));

             $stmt = $pdo->prepare("DELETE FROM `sogo_store` WHERE `c_folder_id` IN (SELECT `c_folder_id` FROM `sogo_folder_info` WHERE `c_path2` = :username)");

@@ -5331,7 +6132,7 @@
             ));

             $stmt = $pdo->prepare("SELECT `address`, `goto` FROM `alias`

                 WHERE `goto` REGEXP :username");

-            $stmt->execute(array(':username' => '(^|,)'.$username.'($|,)'));

+            $stmt->execute(array(':username' => '(^|,)'.preg_quote($username, '/').'($|,)'));

             $GotoData = $stmt->fetchAll(PDO::FETCH_ASSOC);

             foreach ($GotoData as $gotos) {

               $goto_exploded = explode(',', $gotos['goto']);

@@ -5358,15 +6159,16 @@
               );

               continue;

             }

-            

-            update_sogo_static_view($username);

+

             $_SESSION['return'][] = array(

               'type' => 'success',

               'log' => array(__FUNCTION__, $_action, $_type, $_data_log, $_attr),

               'msg' => array('mailbox_removed', htmlspecialchars($username))

             );

+

+            // Track affected mailboxes for SOGo update

+            $update_sogo_mailboxes[] = $username;

           }

-          return true;

         break;

         case 'mailbox_templates':

           if ($_SESSION['mailcow_cc_role'] != "admin") {

@@ -5385,7 +6187,7 @@
             $ids = $_data['ids'];

           }

 

-          

+

           foreach ($ids as $id) {

             // delete template

             $stmt = $pdo->prepare("DELETE FROM `templates`

@@ -5394,7 +6196,7 @@
               ":id" => $id,

               ":type" => "mailbox",

               ":template" => "Default"

-            )); 

+            ));

           }

 

           $_SESSION['return'][] = array(

@@ -5441,8 +6243,11 @@
             $stmt->execute(array(

               ':username' => $name

             ));

-            $stmt = $pdo->prepare("DELETE FROM `sogo_acl` WHERE `c_object` LIKE '%/" . $name . "/%' OR `c_uid` = :username");

+            // bind LIKE pattern + escape LIKE wildcards so the value matches literally (no SQLi, no over-match)

+            $c_object_like = '%/' . addcslashes($name, '\\%_') . '/%';

+            $stmt = $pdo->prepare("DELETE FROM `sogo_acl` WHERE `c_object` LIKE :c_object_like OR `c_uid` = :username");

             $stmt->execute(array(

+              ':c_object_like' => $c_object_like,

               ':username' => $name

             ));

             $stmt = $pdo->prepare("DELETE FROM `sogo_store` WHERE `c_folder_id` IN (SELECT `c_folder_id` FROM `sogo_folder_info` WHERE `c_path2` = :username)");

@@ -5466,9 +6271,12 @@
               'log' => array(__FUNCTION__, $_action, $_type, $_data_log, $_attr),

               'msg' => array('resource_removed', htmlspecialchars($name))

             );

+

+            // Track affected mailboxes for SOGo update

+            $update_sogo_mailboxes[] = $name;

           }

         break;

-        case 'tags_domain':    

+        case 'tags_domain':

           if (!is_array($_data['domain'])) {

             $domains = array();

             $domains[] = $_data['domain'];

@@ -5481,7 +6289,7 @@
 

 

           $wasModified = false;

-          foreach ($domains as $domain) {            

+          foreach ($domains as $domain) {

             if (!is_valid_domain_name($domain)) {

               $_SESSION['return'][] = array(

                 'type' => 'danger',

@@ -5498,7 +6306,7 @@
               );

               return false;

             }

-            

+

             foreach($tags as $tag){

               // delete tag

               $wasModified = true;

@@ -5553,7 +6361,7 @@
             // delete tags

             foreach($tags as $tag){

               $wasModified = true;

-              

+

               $stmt = $pdo->prepare("DELETE FROM `tags_mailbox` WHERE `username` = :username AND `tag_name` = :tag_name");

               $stmt->execute(array(

                 ':username' => $username,

@@ -5572,7 +6380,29 @@
       }

     break;

   }

-  if ($_action != 'get' && in_array($_type, array('domain', 'alias', 'alias_domain', 'resource')) && getenv('SKIP_SOGO') != "y") {

-    update_sogo_static_view();

+  if ($_action != 'get' && in_array($_type, array('domain', 'alias', 'alias_domain', 'resource', 'mailbox')) && getenv('SKIP_SOGO') != "y") {

+    try {

+      if (($_type == 'alias' || $_type == 'resource' || $_type == 'mailbox') && !empty($update_sogo_mailboxes)) {

+        // INCREMENTAL UPDATE: Update only affected mailboxes/resources

+        $update_sogo_mailboxes = array_unique($update_sogo_mailboxes);

+        foreach ($update_sogo_mailboxes as $mailbox) {

+          update_sogo_static_view($mailbox);

+        }

+      }

+      else {

+        // FULL REBUILD: For domain and alias_domain operations or if no tracked mailboxes

+        // Domain operations affect all mailboxes

+        // Alias_domain operations affect entire target domain

+        update_sogo_static_view();

+      }

+    }catch (PDOException $e) {

+      $_SESSION['return'][] = array(

+        'type' => 'success',

+        'log' => array(__FUNCTION__, $_action, $_type, $_data_log, $_attr),

+        'msg' => $e->getMessage()

+      );

+    }

   }

+

+  return true;

 }