diff --git a/CHANGELOG.md b/CHANGELOG.md index 72d1abf5c..8050cc254 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1033,6 +1033,8 @@ If you are coming from 26.08 or earlier, the database update still has to be run - Tabs for where each email is - Waiting, Sending, Retrying, Failed, Sent and Cancelled - with how many in each, following the search. Each email says where it stands: scheduled for when, tried 2 of 4 and when it is tried next, gave up, not tried again (a bad address), sent when, or cancelled. - What is stopping mail going is at the top: sending not set up, cron switched off or not running, the Mail Queue job switched off, or email waiting longer than it should - with the job's last error. When nothing is, it says when the job last ran. - Retry now starts an email over - a full set of tries, at the next run - for a failed or cancelled one. Cancel is its own status now, rather than Failed. Retry now, Cancel and Delete are on each email's menu and in Bulk Action, done only to the ones they can be, saying how many and why not the rest. + - Why an email failed is kept with it - the mail server's own answer, an address that isn't one, no from address, a domain with no mail server - and shown under its status and searched. Cancelling keeps who cancelled it. The alert for a failed email says why and when it is tried again, and when ITFlow gives up after the last try there is an alert for that too, each opening the Mail Queue on its tab. + - Opening an email shows where it stands and why, who it is to and from, when it was queued, how many tries it has had, when it was sent or last failed, its attachments and calendar file - and the email itself as it will arrive, rather than stripped of its layout. A sent one says what it said was cleared on sending, and why. Retry now, Cancel and Delete are in the window too. ### Bug Fixes @@ -1751,6 +1753,7 @@ If you are coming from 26.08 or earlier, the database update still has to be run - Settings: Tickets, Projects, Quotes, Invoices and billing and Defaults use the frame. New in `functions/settings.php`: `settingsNumbering($kind)`, `settingsNumberInUse()`, `settingsNumberingCheck($kind, $post, $saved)` (prefix and next number checked against the highest in use with that prefix - skipped when both are as saved, so a clash already there doesn't block the rest of the page) and `settingsNumberingFields()` (with `[data-settings-next]` in `js/settings.js`, and `[data-settings-depends-on=name]` to fade fields while a switch is off); `settingsEmailProblem()`; `settingsStartPages()`, `settingsStartPageProblem()` and `settingsNetTerms()`. `settingsSectionStart()` takes the section's element id, so `#reminders`, `#billing-time`, `#billable-expenses` and `#mileage` still work; `settingsSelect()` takes `options_html`, `append` and `search => false`; `settingsSwitch()` takes `id`. `settingsSame()` treats NULL as 0 or empty and ignores Windows line ends; the log names accounts, calendars and categories. Values kept from a refused save are only used for five minutes. These handlers keep a setting that isn't sent (`$_POST + saved`), a switch not sent being off. Defaults' fields are renamed to their columns (`config_start_page`, `config_default_*`). The start page is escaped where it is printed. - Settings: Notifications, Security, Client portal, Single sign-on (`admin/identity_providers.php`), Mail and Logs use the frame. `settingsSearch($query, $limit)` scores settings as Find a setting does, leaving out pages for a module that is off; `agent/ajax.php?global_search` returns them as `settings` for admins and `js/global_search.js` shows them under Settings. Single sign-on's fields are renamed to their columns (`config_azure_client_id`, `config_azure_client_secret`). A field marked `quiet` in `settingsFields()` is logged as changed without its value (the login key). The Logs handler is unchanged; Mail's handlers too. - Mail Queue: new `functions/mail_queue.php` - `MAIL_QUEUE_TRIES` (4), `MAIL_QUEUE_RETRY_MINUTES` (30) and `MAIL_QUEUE_KEEP_DAYS` (90), which `cron/mail_queue.php`'s retry pass and the nightly clean-up now use too; `mailQueueTabs()`, `mailQueueState($row)`, `mailQueueCan($row, $action)`, `mailQueueAct($action, $ids)` and `mailQueueHealth()`. `email_status` 4 is Cancelled - never selected by the worker. Retry now sets status 0, no attempts and no failure time. Handlers: `retry_mail`, `cancel_mail`, `delete_mail` (GET with the CSRF token) and `bulk_retry_emails`, `bulk_cancel_emails`, `bulk_delete_emails`; `send_failed_mail` still works. The worker sets `email_failed_at` on the bad sender, bad recipient and no-MX paths. +- Mail Queue: database 3.3.7 adds `email_queue.email_error` varchar(500) - why it last failed, or "Cancelled by ..."; cleared when sent or retried. The worker writes it on every failure path, through `mailQueueErrorSql()`, which leaves it out until the update has run, so an install between updating its files and its database still sends; `mailQueueErrorColumn()` does the same for reads. The retry pass's bad-recipient path now sets `email_failed_at`, so its backoff counts from that try. An alert (`appNotify`) when the retry pass gives up. The email's window shows the queued HTML in an iframe `srcdoc` with `sandbox="allow-popups allow-popups-to-escape-sandbox"` (no scripts, no same origin) and a `script-src 'none'` policy, instead of HTMLPurifier in the page. - `js/app.js`: the four `tinymce.init()` calls go through `itflowTinyMce`, which does nothing where TinyMCE isn't loaded. ### Library Updates diff --git a/admin/database_updates/3.3.7.php b/admin/database_updates/3.3.7.php new file mode 100644 index 000000000..35724c7a7 --- /dev/null +++ b/admin/database_updates/3.3.7.php @@ -0,0 +1,19 @@ + Mail Queue shows it, rather than only + // in the app logs. Checked first, so the step can run again. + $itflow_exists = mysqli_query($mysqli, "SELECT 1 FROM information_schema.COLUMNS + WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'email_queue' AND COLUMN_NAME = 'email_error' LIMIT 1"); + if (!$itflow_exists || mysqli_num_rows($itflow_exists) === 0) { + mysqli_query($mysqli, "ALTER TABLE `email_queue` ADD `email_error` varchar(500) DEFAULT NULL AFTER `email_failed_at`"); + } + + unset($itflow_exists); diff --git a/admin/mail_queue.php b/admin/mail_queue.php index 87dce8460..cc772fc9d 100644 --- a/admin/mail_queue.php +++ b/admin/mail_queue.php @@ -34,11 +34,12 @@ if (!isset($sortable_columns[$sort])) { $sort = 'email_queued_at'; } -$search = "(email_id LIKE '%$q%' OR email_from LIKE '%$q%' OR email_from_name LIKE '%$q%' OR email_recipient LIKE '%$q%' OR email_recipient_name LIKE '%$q%' OR email_subject LIKE '%$q%') +$search = "(email_id LIKE '%$q%' OR email_from LIKE '%$q%' OR email_from_name LIKE '%$q%' OR email_recipient LIKE '%$q%' OR email_recipient_name LIKE '%$q%' OR email_subject LIKE '%$q%'" + . (mailQueueHasError() ? " OR email_error LIKE '%$q%'" : '') . ") AND DATE(email_queued_at) BETWEEN '$dtf' AND '$dtt'"; $sql = mysqli_query($mysqli, "SELECT SQL_CALC_FOUND_ROWS email_id, email_status, email_attempts, email_from, email_from_name, email_recipient, email_recipient_name, - email_subject, email_queued_at, email_failed_at, email_sent_at, COALESCE(email_attachments, '') <> '' AS has_attachments, COALESCE(email_cal_str, '') <> '' AS has_invite + email_subject, email_queued_at, email_failed_at, email_sent_at, " . mailQueueErrorColumn() . ", COALESCE(email_attachments, '') <> '' AS has_attachments, COALESCE(email_cal_str, '') <> '' AS has_invite FROM email_queue WHERE $search AND {$tabs[$show][2]} ORDER BY {$sortable_columns[$sort]}, email_id DESC @@ -100,7 +101,7 @@ $filtered_dates = isset($_GET['dtf']) && $_GET['dtf'] !== '' && $_GET['dtf'] !==
- +
@@ -198,12 +199,16 @@ $filtered_dates = isset($_GET['dtf']) && $_GET['dtf'] !== '' && $_GET['dtf'] !==
+ +
+
+
> diff --git a/admin/modals/mail_queue/mail_queue_message_view.php b/admin/modals/mail_queue/mail_queue_message_view.php index 45950bbbe..ffb2466f6 100644 --- a/admin/modals/mail_queue/mail_queue_message_view.php +++ b/admin/modals/mail_queue/mail_queue_message_view.php @@ -1,77 +1,149 @@ Mail Queue - one email: where it stands, and why it last + * failed or who cancelled it; who it is to and from; when it was queued, + * tried, sent or given up on; its attachments and calendar file; and what it + * says, until it is sent - that is cleared then (cron/mail_queue.php). The + * email is shown as it will arrive, in a sandboxed frame that runs nothing + * and can't reach this page. Retry now, Cancel and Delete as on its row + * (admin/post/mail_queue.php). + */ + require_once '../../includes/modal_header.php'; -$email_id = intval($_GET['id']); +$email_id = intval($_GET['id'] ?? 0); +$row = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT email_id, email_status, email_attempts, email_from, email_from_name, email_recipient, email_recipient_name, + email_subject, email_content, email_cal_str, email_attachments, email_queued_at, email_failed_at, email_sent_at, " . mailQueueErrorColumn() . " + FROM email_queue WHERE email_id = $email_id LIMIT 1")); -//Initialize the HTML Purifier to prevent XSS -require "../../../libs/htmlpurifier/HTMLPurifier.standalone.php"; - -$purifier_config = HTMLPurifier_Config::createDefault(); -$purifier_config->set('Cache.DefinitionImpl', null); // Disable cache by setting a non-existent directory or an invalid one -$purifier_config->set('URI.AllowedSchemes', ['data' => true, 'src' => true, 'http' => true, 'https' => true]); -$purifier = new HTMLPurifier($purifier_config); - -$sql = mysqli_query($mysqli, "SELECT email_attempts, email_content, email_failed_at, email_from, email_from_name, - email_queued_at, email_recipient, email_recipient_name, email_sent_at, email_status, - email_subject FROM email_queue WHERE email_id = $email_id LIMIT 1"); -$row = mysqli_fetch_assoc($sql); - -$email_from = escapeHtml($row['email_from']); -$email_from_name = escapeHtml($row['email_from_name']); -$email_recipient = escapeHtml($row['email_recipient']); -$email_recipient_name = escapeHtml($row['email_recipient_name']); -$email_subject = escapeHtml($row['email_subject']); -$email_content = $purifier->purify($row['email_content']); -$email_attempts = intval($row['email_attempts']); -$email_queued_at = escapeHtml($row['email_queued_at']); -$email_failed_at = escapeHtml($row['email_failed_at']); -$email_sent_at = escapeHtml($row['email_sent_at']); -$email_status = intval($row['email_status']); -if ($email_status == 0) { - $email_status_display = "
Queued
"; -} elseif($email_status == 1) { - $email_status_display = "
Sending
"; -} elseif($email_status == 2) { - $email_status_display = "
Failed
$email_failed_at"; -} else { - $email_status_display = "
Sent
$email_sent_at"; -} - -// Generate the HTML form content using output buffering. ob_start(); -?> - - - +if (!$row) { ?> + + +no address'; + } + if ($name === '' || strcasecmp($name, $address) === 0) { + return escapeHtml($address); + } + return escapeHtml($name) . ' <' . escapeHtml($address) . '>'; + }; + $attachments = []; + foreach ((array) json_decode((string) $row['email_attachments'], true) as $attachment) { + if (is_array($attachment) && trim((string) ($attachment['name'] ?? '')) !== '') { + $attachments[] = basename((string) $attachment['name']); + } + } + $has_invite = trim((string) $row['email_cal_str']) !== ''; + $content = (string) $row['email_content']; + $subject = trim((string) $row['email_subject']) !== '' ? escapeHtml($row['email_subject']) : '(no subject)'; + + // How many tries, in words + if ($tries > MAIL_QUEUE_TRIES) { + $tries_text = 'Not tried again'; + } elseif ($status === 3) { + $tries_text = $tries > 1 ? "Went on try $tries" : 'Went first time'; + } elseif ($tries > 0) { + $tries_text = "$tries of " . MAIL_QUEUE_TRIES; + } else { + $tries_text = 'Not tried yet'; + } + ?> + + + + + 0) { logApp("Cron-Mail-Queue", "warning", "Recovered $orphaned_emails email(s) left in a sending state by a previous run - queued for retry."); @@ -360,7 +361,8 @@ if (mysqli_num_rows($sql_queue) > 0) { // Check sender if (!filter_var($email_from, FILTER_VALIDATE_EMAIL)) { $email_from_logging = escapeSql($rowq['email_from']); - mysqli_query($mysqli, "UPDATE email_queue SET email_status = 2, email_attempts = 99, email_failed_at = NOW() WHERE email_id = $email_id"); + $why = (trim((string) $email_from) === '' ? 'It has no from address' : "The from address isn't one: $email_from") . ' - the addresses are set in Settings > Mail > From addresses'; + mysqli_query($mysqli, "UPDATE email_queue SET email_status = 2, email_attempts = 99, email_failed_at = NOW()" . mailQueueErrorSql($why) . " WHERE email_id = $email_id"); logApp("Cron-Mail-Queue", "Error", "Failed to send email #$email_id due to invalid sender address: $email_from_logging - check configuration in settings."); appNotify("Mail", "Failed to send email #$email_id due to invalid sender address"); continue; @@ -375,7 +377,7 @@ if (mysqli_num_rows($sql_queue) > 0) { // Basic recipient syntax check if (!filter_var($email_recipient, FILTER_VALIDATE_EMAIL)) { - mysqli_query($mysqli, "UPDATE email_queue SET email_status = 2, email_attempts = 99, email_failed_at = NOW() WHERE email_id = $email_id"); + mysqli_query($mysqli, "UPDATE email_queue SET email_status = 2, email_attempts = 99, email_failed_at = NOW()" . mailQueueErrorSql("The address it is to isn't an email address") . " WHERE email_id = $email_id"); $email_to_logging = escapeSql($email_recipient); $email_subject_logging = escapeSql($rowq['email_subject']); logApp("Cron-Mail-Queue", "Error", "Failed to send email: $email_id to $email_to_logging due to invalid recipient address. Email subject was: $email_subject_logging"); @@ -386,7 +388,8 @@ if (mysqli_num_rows($sql_queue) > 0) { // More intelligent recipient MX check (if not disabled with --no-mx-validation) $domain = escapeSql(substr($email_recipient, strpos($email_recipient, '@') + 1)); if (!in_array('--no-mx-validation', $argv) && !checkdnsrr($domain, 'MX')) { - mysqli_query($mysqli, "UPDATE email_queue SET email_status = 2, email_attempts = 99, email_failed_at = NOW() WHERE email_id = $email_id"); + mysqli_query($mysqli, "UPDATE email_queue SET email_status = 2, email_attempts = 99, email_failed_at = NOW()" + . mailQueueErrorSql('No mail server takes email for ' . substr($email_recipient, strpos($email_recipient, '@') + 1) . ' - it has no MX record') . " WHERE email_id = $email_id"); $email_to_logging = escapeSql($email_recipient); $email_subject_logging = escapeSql($rowq['email_subject']); logApp("Cron-Mail-Queue", "Error", "Failed to send email: $email_id to $email_to_logging due to invalid recipient domain (no MX). Email subject was: $email_subject_logging"); @@ -419,16 +422,17 @@ if (mysqli_num_rows($sql_queue) > 0) { ); // Scrub the body on delivery - it can carry share decryption keys and temporary passwords - mysqli_query($mysqli, "UPDATE email_queue SET email_status = 3, email_sent_at = NOW(), email_attempts = 1, email_content = '', email_cal_str = '', email_attachments = '' WHERE email_id = $email_id"); + mysqli_query($mysqli, "UPDATE email_queue SET email_status = 3, email_sent_at = NOW(), email_attempts = 1, email_content = '', email_cal_str = '', email_attachments = ''" . mailQueueErrorSql(null) . " WHERE email_id = $email_id"); } catch (Exception $e) { - mysqli_query($mysqli, "UPDATE email_queue SET email_status = 2, email_failed_at = NOW(), email_attempts = 1 WHERE email_id = $email_id"); + mysqli_query($mysqli, "UPDATE email_queue SET email_status = 2, email_failed_at = NOW(), email_attempts = 1" . mailQueueErrorSql($e->getMessage()) . " WHERE email_id = $email_id"); $email_recipient_logging = escapeSql($rowq['email_recipient']); $email_subject_logging = escapeSql($rowq['email_subject']); $err = substr("Mailer Error: " . $e->getMessage(), 0, 100) . "..."; - appNotify("Cron-Mail-Queue", "Failed to send email #$email_id to $email_recipient_logging"); + appNotify("Cron-Mail-Queue", "Failed to send email #$email_id to $email_recipient_logging - " . escapeSql(mb_strimwidth(mailQueueErrorText($e->getMessage()), 0, 200, '...')) + . " - it is tried again in " . MAIL_QUEUE_RETRY_MINUTES . " minutes", "/admin/mail_queue.php?show=retrying", 0, $email_id); logApp("Cron-Mail-Queue", "Error", "Failed to send email: $email_id to $email_recipient_logging regarding $email_subject_logging. $err"); } } @@ -469,7 +473,7 @@ if (mysqli_num_rows($sql_failed_queue) > 0) { } if (!filter_var($email_recipient, FILTER_VALIDATE_EMAIL)) { - mysqli_query($mysqli, "UPDATE email_queue SET email_status = 2, email_attempts = $email_attempts WHERE email_id = $email_id"); + mysqli_query($mysqli, "UPDATE email_queue SET email_status = 2, email_attempts = $email_attempts, email_failed_at = NOW()" . mailQueueErrorSql("The address it is to isn't an email address") . " WHERE email_id = $email_id"); continue; } @@ -498,15 +502,21 @@ if (mysqli_num_rows($sql_failed_queue) > 0) { ); // Scrub the body on delivery - it can carry share decryption keys and temporary passwords - mysqli_query($mysqli, "UPDATE email_queue SET email_status = 3, email_sent_at = NOW(), email_attempts = $email_attempts, email_content = '', email_cal_str = '', email_attachments = '' WHERE email_id = $email_id"); + mysqli_query($mysqli, "UPDATE email_queue SET email_status = 3, email_sent_at = NOW(), email_attempts = $email_attempts, email_content = '', email_cal_str = '', email_attachments = ''" . mailQueueErrorSql(null) . " WHERE email_id = $email_id"); } catch (Exception $e) { - mysqli_query($mysqli, "UPDATE email_queue SET email_status = 2, email_failed_at = NOW(), email_attempts = $email_attempts WHERE email_id = $email_id"); + mysqli_query($mysqli, "UPDATE email_queue SET email_status = 2, email_failed_at = NOW(), email_attempts = $email_attempts" . mailQueueErrorSql($e->getMessage()) . " WHERE email_id = $email_id"); $email_recipient_logging = escapeSql($rowf['email_recipient']); $email_subject_logging = escapeSql($rowf['email_subject']); $err = substr("Mailer Error: " . $e->getMessage(), 0, 100) . "..."; + // The last of its tries - nothing more happens to it unless someone retries it + if ($email_attempts >= MAIL_QUEUE_TRIES) { + appNotify("Cron-Mail-Queue", "Gave up on email #$email_id to $email_recipient_logging after $email_attempts tries - " . escapeSql(mb_strimwidth(mailQueueErrorText($e->getMessage()), 0, 200, '...')), + "/admin/mail_queue.php?show=failed", 0, $email_id); + } + logApp("Cron-Mail-Queue", "Error", "Failed to re-send email #$email_id to $email_recipient_logging regarding $email_subject_logging. $err"); } } diff --git a/css/itflow_custom.css b/css/itflow_custom.css index 9f4e97a87..bd06292d4 100644 --- a/css/itflow_custom.css +++ b/css/itflow_custom.css @@ -8400,3 +8400,18 @@ a.itflow-portal-request:focus-visible { [data-settings-depends-on].is-off { opacity: .55; } + +/* ---------- Mail Queue ---------- */ +/* Why an email failed, under its status on the list */ +.itflow-mail-queue-why { + max-width: 22rem; +} +/* The email as it will arrive - its own white page, whatever the theme */ +.itflow-mail-queue-frame { + height: 45vh; + min-height: 18rem; + background: #fff; +} +.itflow-mail-queue-facts dd { + margin-bottom: .35rem; +} diff --git a/db.sql b/db.sql index 5b82828bf..07feb19a9 100644 --- a/db.sql +++ b/db.sql @@ -1479,6 +1479,7 @@ CREATE TABLE `email_queue` ( `email_attachments` text DEFAULT NULL, `email_queued_at` datetime NOT NULL DEFAULT current_timestamp(), `email_failed_at` datetime DEFAULT NULL, + `email_error` varchar(500) DEFAULT NULL, `email_attempts` tinyint(1) NOT NULL DEFAULT 0, `email_sent_at` datetime DEFAULT NULL, PRIMARY KEY (`email_id`), diff --git a/functions/mail_queue.php b/functions/mail_queue.php index 9547f6c7d..23a4b747f 100644 --- a/functions/mail_queue.php +++ b/functions/mail_queue.php @@ -13,7 +13,9 @@ * 3 sent - its body, calendar file and attachments are cleared then, as * they can carry share keys and temporary passwords * 4 cancelled by an admin - never picked up again - * Sent, failed and cancelled email is deleted after 90 days (nightly). + * email_error says why it last failed, or who cancelled it - cleared when it + * is sent or retried. Sent, failed and cancelled email is deleted after 90 + * days (nightly). */ const MAIL_QUEUE_TRIES = 4; @@ -37,10 +39,18 @@ function mailQueueTabs() { /* * Where an email stands, in words - key (as the tabs), label, the badge's - * classes, a line under it and the exact time for its title. $row has - * email_status, email_attempts and its times. + * classes, a line under it, the exact time for its title, and why it failed + * (error). $row has email_status, email_attempts, its times and + * email_error. */ function mailQueueState(array $row) { + $state = mailQueueStateOf($row); + // Why it failed, or who cancelled it - not once it has gone, or while it waits again + $state['error'] = in_array($state['key'], ['retrying', 'failed', 'cancelled'], true) ? mailQueueErrorText($row['email_error'] ?? '') : ''; + return $state; +} + +function mailQueueStateOf(array $row) { $status = intval($row['email_status']); $tries = intval($row['email_attempts']); $when = function ($datetime) { @@ -133,10 +143,12 @@ function mailQueueAct($action, array $email_ids) { $done_list = implode(',', $done); if ($action === 'retry') { // From the start: a full set of tries, at the next run - mysqli_query($mysqli, "UPDATE email_queue SET email_status = 0, email_attempts = 0, email_failed_at = NULL, email_queued_at = LEAST(email_queued_at, NOW()) - WHERE email_id IN ($done_list) AND $where"); + mysqli_query($mysqli, "UPDATE email_queue SET email_status = 0, email_attempts = 0, email_failed_at = NULL, email_queued_at = LEAST(email_queued_at, NOW())" + . mailQueueErrorSql(null) . " WHERE email_id IN ($done_list) AND $where"); } elseif ($action === 'cancel') { - mysqli_query($mysqli, "UPDATE email_queue SET email_status = $cancelled, email_failed_at = NOW() WHERE email_id IN ($done_list) AND $where"); + global $session_name; + mysqli_query($mysqli, "UPDATE email_queue SET email_status = $cancelled, email_failed_at = NOW()" + . mailQueueErrorSql('Cancelled by ' . stripslashes((string) ($session_name ?? 'an admin'))) . " WHERE email_id IN ($done_list) AND $where"); } else { mysqli_query($mysqli, "DELETE FROM email_queue WHERE email_id IN ($done_list) AND $where"); } @@ -191,3 +203,41 @@ function mailQueueHealth() { return ['level' => '', 'key' => 'ok', 'title' => '', 'text' => 'Sent by the Mail Queue job each minute - it last ran ' . $ago($job['cron_job_last_run_at'] ?? null) . '. A failed email is tried ' . (MAIL_QUEUE_TRIES - 1) . ' more times, ' . MAIL_QUEUE_RETRY_MINUTES . ' minutes apart. Email is kept ' . MAIL_QUEUE_KEEP_DAYS . ' days; a sent one without what it said.', 'url' => '', 'action' => '', 'waiting' => 0]; } + +/* Whether email_queue has email_error yet - not until the 3.3.7 update has run. */ +function mailQueueHasError() { + global $mysqli; + static $has = null; + if ($has === null) { + $result = mysqli_query($mysqli, "SHOW COLUMNS FROM email_queue LIKE 'email_error'"); + $has = $result && mysqli_num_rows($result) > 0; + } + return $has; +} + +/* + * Why an email failed, as kept with it - one line, 500 characters at most, + * as the server said it (an address in <> stays). '' for none. + */ +function mailQueueErrorText($error) { + $error = trim(preg_replace('/\s+/u', ' ', (string) $error)); + return mb_strlen($error) > 500 ? mb_substr($error, 0, 497) . '...' : $error; +} + +/* + * The SET clause for why an email failed (or NULL to clear it), to add to an + * UPDATE of email_queue - ", email_error = '...'", or '' before the update + * adding the column has run, so the rest of the UPDATE still happens. + */ +function mailQueueErrorSql($error) { + if (!mailQueueHasError()) { + return ''; + } + $error = $error === null ? '' : mailQueueErrorText($error); + return ', email_error = ' . ($error === '' ? 'NULL' : "'" . escapeSql($error) . "'"); +} + +/* The email_error column for a SELECT - itself, or NULL before the update. */ +function mailQueueErrorColumn() { + return mailQueueHasError() ? 'email_error' : 'NULL AS email_error'; +}