Files
itflow/functions/mail_queue.php

764 lines
40 KiB
PHP

<?php
/*
* ITFlow - the mail queue (email_queue), as Maintenance > Mail Queue shows it.
*
* Everything ITFlow sends is queued (emailQueue(), functions/email.php) and
* sent by the Mail Queue cron job (cron/mail_queue.php). An email's
* email_status is where it is:
* 0 waiting - or scheduled, while its email_queued_at is still ahead
* 1 being sent this minute
* 2 failed - tried again after a wait that grows (MAIL_QUEUE_RETRY_AFTER, about eight
* hours in all) until it has had MAIL_QUEUE_TRIES, and not once its last try is
* MAIL_QUEUE_GIVE_UP_HOURS behind it (mailQueueRetryingSql()); 99 tries means it isn't
* tried again - an address the mail server said doesn't exist (mailQueueRefusedForGood()).
* A domain with no mail server is a failed try like any other (mailQueueDomainProblem()),
* as a lookup can fail for a moment
* 3 sent - it keeps what it said, its calendar file and attachments, except
* one that carried a link or code that opens something (email_sensitive:
* a shared login, an invite, a password link, a signing or approval link),
* cleared as it goes - and a failed or cancelled one like it a day after
* it was queued (nightly, mailQueueClearSensitive())
* 4 cancelled by an admin - never picked up again
* A sent email that came back - a mail server's bounce for it (mailQueueBounced(), 4.3.5) - is Bounced: still 3, with
* email_bounced_at and email_bounce, who it bounced for and why ({"address": "why"}).
* 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).
*
* An email about a ticket can go to one person with others copied in (email_cc), and carries the
* headers that keep its conversation together (email_headers - mailQueueHeaders()). The address
* it is to is the one whose domain is checked before each try; a mail server turns away the
* copied-in itself.
*
* The job sends at most config_mail_send_per_minute a run (database 4.2.9 - 30 until then) over one
* connection - one with a link or code that opens something (email_sensitive: a password link, an invite) first,
* as someone is waiting for it, and bulk email (email_bulk) after everything else - and stops for the minute when the mail
* server turns two away in a row for now - a host's limit - so the rest wait their turn rather than
* use up their tries. A mail server it can't reach or sign in to costs no email a try.
*/
// Minutes before each try again - after the first failed try, the second... about eight hours in all
const MAIL_QUEUE_RETRY_AFTER = [5, 10, 20, 40, 60, 120, 240];
const MAIL_QUEUE_TRIES = 8;
// A failed email isn't picked up again by itself once its last try is this far behind it - the longest wait is 4 hours.
// An email given up on before the tries went from 4 to 8 has fewer than 8, and was sent again, however old
const MAIL_QUEUE_GIVE_UP_HOURS = 24;
const MAIL_QUEUE_KEEP_DAYS = 90;
const MAIL_QUEUE_CANCELLED = 4;
// Pictures that were in an email as data, kept once each for the queue to attach inline (emailInlineImages()) - the web can't reach uploads/tmp
const MAIL_QUEUE_IMAGE_DIR = 'uploads/tmp/mail_images';
/*
* Why mail can't go to $recipient's domain - '' when it can: it has a mail server (MX), or, with
* none, an address of its own (A or AAAA), which takes its mail (RFC 5321). Asked before each try
* (cron/mail_queue.php), so a lookup that failed for a moment is asked again on the next try
* rather than ending the email.
*/
/** Minutes between an email's failed try $attempts (1, 2...) and its next (MAIL_QUEUE_RETRY_AFTER). */
function mailQueueRetryMinutes($attempts) {
$after = MAIL_QUEUE_RETRY_AFTER;
return $after[max(0, min(count($after), intval($attempts)) - 1)];
}
/* SQL - a failed email whose wait for its next try is over (mailQueueRetryMinutes()), for its email_failed_at and email_attempts. */
function mailQueueRetryDueSql() {
$cases = '';
foreach (MAIL_QUEUE_RETRY_AFTER as $i => $minutes) {
$cases .= ' WHEN ' . ($i + 1) . " THEN $minutes";
}
$last = MAIL_QUEUE_RETRY_AFTER[count(MAIL_QUEUE_RETRY_AFTER) - 1];
return "email_failed_at <= NOW() - INTERVAL (CASE email_attempts$cases ELSE $last END) MINUTE";
}
/* SQL - a failed email still being tried: under MAIL_QUEUE_TRIES, and its last try within MAIL_QUEUE_GIVE_UP_HOURS. */
function mailQueueRetryingSql() {
return "(email_status = 2 AND email_attempts < " . MAIL_QUEUE_TRIES . " AND email_failed_at >= NOW() - INTERVAL " . MAIL_QUEUE_GIVE_UP_HOURS . " HOUR)";
}
/* SQL - a failed email given up on: out of tries, not tried again (99), or its last try too long ago (mailQueueRetryingSql()). */
function mailQueueFailedSql() {
return "(email_status = 2 AND (email_attempts >= " . MAIL_QUEUE_TRIES . " OR email_failed_at IS NULL OR email_failed_at < NOW() - INTERVAL " . MAIL_QUEUE_GIVE_UP_HOURS . " HOUR))";
}
/* Whether a failed email ($row - email_status, email_attempts, email_failed_at) is still being tried (mailQueueRetryingSql()). */
function mailQueueRetrying(array $row) {
$failed = (string) ($row['email_failed_at'] ?? '');
return intval($row['email_status']) === 2 && intval($row['email_attempts']) < MAIL_QUEUE_TRIES
&& $failed !== '' && strtotime($failed) >= time() - MAIL_QUEUE_GIVE_UP_HOURS * 3600;
}
/*
* Whether a mail server's refusal of a recipient says the address doesn't exist - for good, so the email isn't tried
* again and the contact shows Email bounced. Only the enhanced codes for a recipient's address (RFC 3463): 5.1.1 no
* such mailbox, 5.1.2 no such domain, 5.1.3 not an address, 5.1.6 moved with nowhere to forward to, 5.1.10 a domain
* that takes no mail (RFC 7505) - or, from a server that gives no enhanced code, 550, 551 or 553 saying there is no
* such recipient. Any other refusal is tried again: the server's own policy (5.7.x - a relay that won't send for
* you), a full mailbox (5.2.2), a sending quota. Every 5xx used to count, and marked real contacts bounced.
*/
function mailQueueRefusedForGood($code, $code_ex, $detail) {
$code_ex = trim((string) $code_ex);
if ($code_ex !== '') {
return in_array($code_ex, ['5.1.1', '5.1.2', '5.1.3', '5.1.6', '5.1.10'], true);
}
return in_array(trim((string) $code), ['550', '551', '553'], true)
&& preg_match("/user unknown|unknown user|no such (user|mailbox|recipient|address)|does ?n[o']?t exist|recipient (not found|unknown)|unknown recipient|mailbox not found|invalid (recipient|mailbox)/i", (string) $detail) === 1;
}
/*
* The envelope sender (Return-Path) of an email from $from_email - where a mail server sends its bounce - for email
* sent to many (email_bulk): the mailbox ITFlow reads (Admin > Mail, Receiving), so its bounces come back and are read
* - the contacts marked Email bounced, and left out of the next one (functions/contact_bounce.php). They went to the
* From mailbox, which nobody may read. '' leaves it the From address, as always - unless it can be done safely:
* - email to ticket is on, reading a mailbox with an address that isn't the From address
* - it goes by SMTP: Microsoft Graph has no envelope sender of its own
* - ITFlow signs in to the mail server as that mailbox, or doesn't sign in - a mail server takes no other sender
* from a mailbox (Microsoft 365's SendAsDenied)
* - it is at the From address's domain, or one above or below it - else the email fails DMARC for its domain
* A mail server that turns it away all the same is sent the From address for the rest of the run (cron/mail_queue.php).
*/
function mailQueueReturnPath($from_email) {
global $mysqli;
static $settings = null;
if ($settings === null) {
$settings = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT config_ticket_email_parse, config_imap_provider, config_imap_username, config_smtp_provider, config_smtp_username, config_mail_from_email
FROM settings WHERE company_id = 1")) ?: [];
}
$reads = strtolower(trim((string) ($settings['config_imap_username'] ?? '')));
$from = strtolower(trim((string) $from_email));
if (!intval($settings['config_ticket_email_parse'] ?? 0) || trim((string) ($settings['config_imap_provider'] ?? '')) === '' || !filter_var($reads, FILTER_VALIDATE_EMAIL) || $reads === $from) {
return '';
}
$provider = (string) ($settings['config_smtp_provider'] ?? '');
if ($provider === '' || ($provider === 'microsoft_oauth' && !empty(mailGraphState()['send']))) {
return '';
}
// Who ITFlow signs in as - the OAuth providers sign in as the system mailbox when no username is saved (mailQueueMailer())
$signs_in = strtolower(trim((string) ($settings['config_smtp_username'] ?? '')));
if ($signs_in === '' && in_array($provider, ['google_oauth', 'microsoft_oauth'], true)) {
$signs_in = strtolower(trim((string) ($settings['config_mail_from_email'] ?? '')));
}
if ($signs_in !== '' && $signs_in !== $reads) {
return '';
}
$reads_domain = substr($reads, strrpos($reads, '@') + 1);
$from_domain = strpos($from, '@') !== false ? substr($from, strrpos($from, '@') + 1) : '';
$aligned = $from_domain !== '' && ($reads_domain === $from_domain || str_ends_with($reads_domain, ".$from_domain") || str_ends_with($from_domain, ".$reads_domain"));
return $aligned && !mailQueueReturnPathRefused() ? $reads : '';
}
/* Whether the mail server turned the Return-Path (mailQueueReturnPath()) away this run - $refused true says it did. */
function mailQueueReturnPathRefused($refused = null) {
static $was = false;
if ($refused !== null) {
$was = (bool) $refused;
}
return $was;
}
/*
* Where the bounces of email sent to many from $from_email go - the mailbox ITFlow reads, where they are read
* (mailQueueReturnPath()), or the From mailbox itself. For the Email window. ['address', 'read' => bool].
*/
function mailQueueBouncesTo($from_email) {
global $mysqli;
$return_path = mailQueueReturnPath($from_email);
if ($return_path !== '') {
return ['address' => $return_path, 'read' => true];
}
$row = mysqli_fetch_row(mysqli_query($mysqli, "SELECT config_ticket_email_parse, config_imap_provider, config_imap_username FROM settings WHERE company_id = 1"));
$read = $row && intval($row[0]) && trim((string) $row[1]) !== '' && strcasecmp(trim((string) $row[2]), trim((string) $from_email)) === 0;
return ['address' => trim((string) $from_email), 'read' => $read];
}
/* Whether the 4.2.9 update has run - the sending pace (config_mail_send_per_minute) and bulk email (email_bulk). */
function mailQueuePaceReady() {
global $mysqli;
static $ready = null;
if ($ready === null) {
$version = defined('CURRENT_DATABASE_VERSION') ? CURRENT_DATABASE_VERSION
: (string) (mysqli_fetch_row(mysqli_query($mysqli, "SELECT config_current_database_version FROM settings WHERE company_id = 1"))[0] ?? '0');
$ready = version_compare($version, '4.2.9', '>=');
}
return $ready;
}
/** Whether the 4.3.5 update has run - each email keeps its Message-ID and whether it bounced. */
function mailQueueBounceReady() {
global $mysqli;
static $ready = null;
if ($ready === null) {
$version = defined('CURRENT_DATABASE_VERSION') ? CURRENT_DATABASE_VERSION
: (string) (mysqli_fetch_row(mysqli_query($mysqli, "SELECT config_current_database_version FROM settings WHERE company_id = 1"))[0] ?? '0');
$ready = version_compare($version, '4.3.5', '>=');
}
return $ready;
}
/** The SELECT columns for whether an email bounced - NULL before the 4.3.5 update. With its leading comma. */
function mailQueueBounceColumns() {
return mailQueueBounceReady() ? ', email_bounced_at, email_bounce' : ', NULL AS email_bounced_at, NULL AS email_bounce';
}
/*
* The sent email a mail server's bounce is about - by its Message-ID ($message_id, cleaned), else the latest sent in the
* last week to one of the addresses it failed for ($failed, [address => why]) with its subject ($subject, raw). Its row,
* or null - nothing is marked (mailQueueBounced() does that).
*/
function mailQueueBounceRow($message_id, array $failed, $subject = '') {
global $mysqli;
if (!mailQueueBounceReady()) {
return null;
}
$columns = "email_id, email_recipient, email_cc, email_subject, email_about, email_ticket_reply_id, email_bounced_at, email_bounce";
$row = null;
if (trim((string) $message_id) !== '') {
$row = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT $columns FROM email_queue WHERE email_status = 3 AND email_message_id = '" . mysqli_real_escape_string($mysqli, (string) $message_id) . "' ORDER BY email_id DESC LIMIT 1"));
}
if (!$row && $failed && trim((string) $subject) !== '') {
$addresses = implode(',', array_map(function ($address) use ($mysqli) {
return "'" . mysqli_real_escape_string($mysqli, strtolower((string) $address)) . "'";
}, array_keys($failed)));
$row = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT $columns FROM email_queue WHERE email_status = 3 AND email_sent_at > NOW() - INTERVAL 7 DAY
AND email_subject = '" . mysqli_real_escape_string($mysqli, emailFit((string) $subject)) . "' AND LOWER(email_recipient) IN ($addresses) ORDER BY email_id DESC LIMIT 1"));
}
return $row ?: null;
}
/*
* A mail server's bounce (addBounce(), cron/ticket_email_parser.php) for the email it was about - found by its Message-ID
* ($message_id, cleaned), else the latest sent in the last week to one of the addresses it failed for, with its subject
* ($subject, raw) - only ones that went (Sent). $failed is [address => why]. Marked Bounced, for those addresses - and a
* billing email's history says so, once for each address. The row as it was, or null when none is found.
*
* A report often names an address the email wasn't sent to - their mail is sent on to another mailbox, or the address is
* an alias - or names nobody. On an email to one person it is theirs, saying where it came back from. On one to several,
* which of them it was for can't be told: nobody on it is marked, and the address the report names is kept as it is.
*/
function mailQueueBounced($message_id, array $failed, $subject = '') {
global $mysqli;
$row = mailQueueBounceRow($message_id, $failed, $subject);
if (!$row) {
return null;
}
// Who it bounced for - the addresses it was to that the report names
$on_it = array_values(array_unique(array_merge([strtolower((string) $row['email_recipient'])], array_map(function ($person) {
return strtolower((string) $person['email']);
}, mailQueueCc($row['email_cc'] ?? '')))));
$was = (array) json_decode((string) ($row['email_bounce'] ?? ''), true);
$bounce = $was;
$elsewhere = [];
foreach ($failed as $address => $why) {
$address = strtolower((string) $address);
if (in_array($address, $on_it, true)) {
$bounce[$address] = mailQueueErrorText($why);
} elseif ($address !== '') {
$elsewhere[$address] = mailQueueErrorText($why);
}
}
// It names an address the email didn't go to, or nobody (above)
if ($elsewhere || !$failed) {
if (count($on_it) > 1) {
$bounce += $elsewhere;
} elseif (($bounce[$on_it[0]] ?? '') === '') {
$bounce[$on_it[0]] = implode('; ', array_map(function ($address, $why) {
return $why !== '' ? "$address: $why" : "It came back from $address";
}, array_keys($elsewhere), $elsewhere));
}
}
mysqli_query($mysqli, "UPDATE email_queue SET email_bounced_at = NOW(), email_bounce = '" . mysqli_real_escape_string($mysqli, json_encode((object) $bounce, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES)) . "'
WHERE email_id = " . intval($row['email_id']));
// A billing email - its history says it bounced: the first time, and for each address more
$new = array_diff_key($bounce, $was);
if (preg_match('/^(invoice|quote):(\d+)$/', (string) $row['email_about'], $about) && function_exists('billingLog') && (empty($row['email_bounced_at']) || $new)) {
$status = (string) (mysqli_fetch_row(mysqli_query($mysqli, $about[1] === 'invoice'
? "SELECT invoice_status FROM invoices WHERE invoice_id = " . intval($about[2]) : "SELECT quote_status FROM quotes WHERE quote_id = " . intval($about[2])))[0] ?? '');
if ($status !== '') {
$told = $new ?: $bounce;
$why = implode('; ', array_filter($told));
billingLog($about[1], intval($about[2]), $status, ($told ? 'Email to ' . implode(', ', array_keys($told)) : 'Its email') . ' bounced' . ($why !== '' ? ' - ' . mb_strimwidth($why, 0, 300, '...') : ''));
}
}
return $row;
}
/* The most emails the queue sends a minute (Admin > Settings > Mail, Sending) - 30 before the 4.2.9 update. */
function mailQueuePerMinute() {
global $mysqli;
if (!mailQueuePaceReady()) {
return 30;
}
$per_minute = intval(mysqli_fetch_row(mysqli_query($mysqli, "SELECT config_mail_send_per_minute FROM settings WHERE company_id = 1"))[0] ?? 30);
return max(1, min(1000, $per_minute));
}
/*
* The name the queue gives its mail server for this machine (SMTP HELO) and puts in a Message-ID of
* its own - the host of ITFlow's address (config.php), or else that of $from_email. PHPMailer took
* the machine's own name, "vm" or a container's, which spam filters count against an email.
*/
function mailQueueHostname($from_email = '') {
global $config_base_url;
foreach ([(string) parse_url('https://' . trim((string) $config_base_url), PHP_URL_HOST), substr((string) $from_email, strrpos((string) $from_email, '@') !== false ? strrpos((string) $from_email, '@') + 1 : strlen((string) $from_email))] as $host) {
$host = strtolower(trim($host, '[] '));
if (preg_match('/^(?=.{4,253}$)([a-z0-9]([a-z0-9-]*[a-z0-9])?\.)+[a-z]{2,63}$/', $host)) {
return $host;
}
}
return '';
}
/*
* An email's plain text part, beside its HTML - the reply line first when it has one, so a reply in
* plain text is cut cleanly too (emailReplyText()); each link as its words and address; a table's cells
* apart; and not the hidden line an inbox shows beside the subject. An email of HTML alone counts against it
* with spam filters, and a mail program that shows only text showed its HTML.
*/
function mailQueueTextPart($html) {
$html = (string) $html;
$marker = strpos($html, EMAIL_REPLY_MARKER) !== false;
$html = preg_replace('#<div style="display:none[^"]*"[^>]*>.*?</div>#is', '', $html) ?? $html;
$html = preg_replace_callback('#<a\b[^>]*\bhref\s*=\s*(["\'])(https?://[^"\']+)\1[^>]*>(.*?)</a>#is', function ($m) {
$label = trim(html_entity_decode(strip_tags($m[3]), ENT_QUOTES | ENT_HTML5, 'UTF-8'));
$url = html_entity_decode($m[2], ENT_QUOTES | ENT_HTML5, 'UTF-8');
return htmlspecialchars($label === '' || $label === $url ? $url : "$label: $url", ENT_QUOTES, 'UTF-8');
}, $html) ?? $html;
$html = preg_replace('#</t[dh]\s*>#i', ' $0', $html) ?? $html;
$text = emailPlainText($html);
return ($marker ? EMAIL_REPLY_MARKER . "\n\n" : '') . $text;
}
/*
* Tell the admins about the mail queue - $text, and where to look ($action). Once an hour at most: an
* admin told in the last hour isn't told again - read or not, as one dismissed came back the next minute
* while a mail server was down. It used to tell every agent, once an email.
*/
function mailQueueNotifyAdmins($text, $action = '/admin/mail_queue.php') {
global $mysqli;
$text_sql = logSqlText($text, 1000);
$action_sql = logSqlText($action, 250);
$sql = mysqli_query($mysqli, "SELECT user_id FROM users JOIN user_roles ON role_id = user_role_id
WHERE role_is_admin = 1 AND user_type = 1" . serviceAccountsOutSql() . " AND user_status = 1 AND user_archived_at IS NULL
AND user_id NOT IN (SELECT notification_user_id FROM notifications WHERE notification_type = 'Mail Queue'
AND notification_timestamp >= NOW() - INTERVAL 1 HOUR)");
$told = 0;
while ($row = mysqli_fetch_row($sql)) {
mysqli_query($mysqli, "INSERT INTO notifications SET notification_type = 'Mail Queue', notification = '$text_sql', notification_action = '$action_sql', notification_user_id = " . intval($row[0]));
$told++;
}
return $told;
}
function mailQueueDomainProblem($recipient) {
static $asked = []; // each domain once a run - a queue of email to one client asks once
$recipient = (string) $recipient;
$domain = strtolower(trim(substr($recipient, strrpos($recipient, '@') + 1)));
if (!isset($asked[$domain])) {
$asked[$domain] = $domain === '' || checkdnsrr($domain, 'MX') || checkdnsrr($domain, 'A') || checkdnsrr($domain, 'AAAA')
? '' : "No mail server takes email for $domain - it has no MX record, and no address either";
}
return $asked[$domain];
}
/* The tabs of the list - key => [label, icon, SQL for what is in it]. */
function mailQueueTabs() {
return [
'' => ['All', 'fa-inbox', '1 = 1'],
'waiting' => ['Waiting', 'fa-hourglass-half', 'email_status = 0'],
'sending' => ['Sending', 'fa-paper-plane', 'email_status = 1'],
'retrying' => ['Retrying', 'fa-redo-alt', mailQueueRetryingSql()],
'failed' => ['Failed', 'fa-exclamation-circle', mailQueueFailedSql()],
'sent' => ['Sent', 'fa-check', 'email_status = 3' . (mailQueueBounceReady() ? ' AND email_bounced_at IS NULL' : '')],
] + (mailQueueBounceReady() ? ['bounced' => ['Bounced', 'fa-reply', 'email_status = 3 AND email_bounced_at IS NOT NULL']] : []) + [
'cancelled' => ['Cancelled', 'fa-ban', 'email_status = ' . MAIL_QUEUE_CANCELLED],
];
}
/*
* Where an email stands, in words - key (as the tabs), label, the badge's
* 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. Bounced: what the mail server said, for whom
$state['error'] = in_array($state['key'], ['retrying', 'failed', 'cancelled'], true) ? mailQueueErrorText($row['email_error'] ?? '') : '';
if ($state['key'] === 'bounced') {
$state['error'] = mailQueueErrorText(implode('; ', array_map(function ($address, $why) {
return $why !== '' ? "$address: $why" : $address;
}, array_keys($state['bounce']), $state['bounce'])));
}
return $state;
}
function mailQueueStateOf(array $row) {
$status = intval($row['email_status']);
$tries = intval($row['email_attempts']);
$when = function ($datetime) {
return $datetime ? date('M j, Y g:i A', strtotime($datetime)) : '';
};
$queued = (string) $row['email_queued_at'];
$failed = (string) ($row['email_failed_at'] ?? '');
if ($status === 0 && $queued !== '' && strtotime($queued) > time()) {
return ['key' => 'waiting', 'label' => 'Scheduled', 'badge' => 'text-bg-info', 'icon' => 'fa-calendar-alt',
'detail' => 'Goes ' . date('M j, g:i A', strtotime($queued)), 'title' => 'Not before ' . $when($queued)];
}
if ($status === 0) {
return ['key' => 'waiting', 'label' => 'Waiting', 'badge' => 'text-bg-primary', 'icon' => 'fa-hourglass-half',
'detail' => 'Queued ' . timeAgo($queued), 'title' => 'Queued ' . $when($queued)];
}
if ($status === 1) {
return ['key' => 'sending', 'label' => 'Sending', 'badge' => 'text-bg-warning', 'icon' => 'fa-paper-plane',
'detail' => 'Going now', 'title' => ''];
}
if (mailQueueRetrying($row)) {
$next = strtotime($failed) + mailQueueRetryMinutes($tries) * 60;
return ['key' => 'retrying', 'label' => 'Retrying', 'badge' => 'text-bg-warning', 'icon' => 'fa-redo-alt',
'detail' => 'Tried ' . max(1, $tries) . ' of ' . MAIL_QUEUE_TRIES . ' · next ' . ($next > time() ? 'about ' . date('g:i A', $next) : 'any minute'),
'title' => $failed !== '' ? 'Last failed ' . $when($failed) : ''];
}
if ($status === 2) {
return ['key' => 'failed', 'label' => 'Failed', 'badge' => 'text-bg-danger', 'icon' => 'fa-exclamation-circle',
'detail' => ($tries > MAIL_QUEUE_TRIES ? 'Not tried again' : 'Gave up after ' . max(1, $tries) . ' ' . ($tries === 1 ? 'try' : 'tries')) . ($failed !== '' ? ' · ' . timeAgo($failed) : ''),
'title' => $failed !== '' ? 'Failed ' . $when($failed) : ''];
}
if ($status === 3 && !empty($row['email_bounced_at'])) {
$bounced = (string) $row['email_bounced_at'];
return ['key' => 'bounced', 'label' => 'Bounced', 'badge' => 'text-bg-danger', 'icon' => 'fa-reply',
'detail' => 'Came back ' . timeAgo($bounced), 'title' => 'Sent, then bounced ' . $when($bounced),
'bounce' => (array) json_decode((string) ($row['email_bounce'] ?? ''), true)];
}
if ($status === 3) {
$sent = (string) ($row['email_sent_at'] ?? '');
return ['key' => 'sent', 'label' => 'Sent', 'badge' => 'text-bg-success', 'icon' => 'fa-check',
'detail' => $sent !== '' ? 'Sent ' . timeAgo($sent) : '', 'title' => $sent !== '' ? 'Sent ' . $when($sent) : ''];
}
return ['key' => 'cancelled', 'label' => 'Cancelled', 'badge' => 'text-bg-secondary', 'icon' => 'fa-ban',
'detail' => $failed !== '' ? 'Cancelled ' . timeAgo($failed) : '', 'title' => $failed !== '' ? 'Cancelled ' . $when($failed) : ''];
}
/*
* What can be done with an email: retry (anything that didn't go - sent mail
* has been cleared, and one going now is left alone), cancel (one still to
* be sent or tried again) and delete (anything not going this minute).
*/
function mailQueueCan(array $row, $action) {
$status = intval($row['email_status']);
$tries = intval($row['email_attempts']);
switch ($action) {
case 'retry':
// Not one whose link was cleared - there is nothing left to send
return ($status === 2 || $status === MAIL_QUEUE_CANCELLED) && empty($row['email_cleared']);
case 'cancel':
return $status === 0 || mailQueueRetrying($row);
case 'delete':
return $status !== 1;
}
return false;
}
/*
* Retry, cancel or delete emails - each only where it can be done
* (mailQueueCan()), checked again in the UPDATE so one the worker took
* meanwhile is left alone. The ids it was done to.
*/
function mailQueueAct($action, array $email_ids) {
global $mysqli;
$ids = array_values(array_unique(array_filter(array_map('intval', $email_ids))));
if (!$ids) {
return [];
}
$list = implode(',', $ids);
$cancelled = MAIL_QUEUE_CANCELLED;
$where = [
'retry' => "email_status IN (2, $cancelled) AND email_content <> ''",
'cancel' => "(email_status = 0 OR " . mailQueueRetryingSql() . ")",
'delete' => 'email_status <> 1',
][$action] ?? null;
if ($where === null) {
return [];
}
$done = [];
$sql = mysqli_query($mysqli, "SELECT email_id FROM email_queue WHERE email_id IN ($list) AND $where");
while ($row = mysqli_fetch_row($sql)) {
$done[] = intval($row[0]);
}
if (!$done) {
return [];
}
$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())"
. mailQueueErrorSql(null) . " WHERE email_id IN ($done_list) AND $where");
} elseif ($action === 'cancel') {
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");
}
return $done;
}
/*
* Whether the queue is moving - the first thing in the way, as level
* (danger/warning), title, text and where to put it right; or, when nothing
* is, level '' and a line on how it runs. $waiting is how many are due and
* have waited more than ten minutes.
*/
function mailQueueHealth() {
global $mysqli, $config_smtp_provider;
$settings = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT config_enable_cron, config_cron_last_dispatch_at FROM settings WHERE company_id = 1")) ?: [];
$job = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT cron_job_enabled, cron_job_last_run_at, cron_job_last_error, cron_job_last_error_at FROM cron_jobs WHERE cron_job_name = 'mail_queue'")) ?: null;
$stuck = mysqli_fetch_row(mysqli_query($mysqli, "SELECT COUNT(*), MIN(email_queued_at) FROM email_queue
WHERE email_status = 0 AND email_queued_at <= NOW() - INTERVAL 10 MINUTE"));
$waiting = intval($stuck[0] ?? 0);
$oldest = $stuck[1] ?? null;
$heard = $settings['config_cron_last_dispatch_at'] ?? null;
$ago = function ($datetime) {
if (!$datetime) {
return 'never';
}
return abs(time() - strtotime($datetime)) < 60 ? 'less than a minute ago' : timeAgo($datetime);
};
$held = $waiting ? " $waiting " . ($waiting === 1 ? 'email has' : 'emails have') . ' been waiting since ' . date('M j, g:i A', strtotime($oldest)) . '.' : '';
if (empty($config_smtp_provider)) {
return ['level' => 'danger', 'key' => 'smtp', 'title' => 'Mail sending is off', 'text' => 'Nothing in the queue goes until it is set up.' . $held,
'url' => 'settings_mail.php?tab=sending', 'action' => 'Set up sending', 'waiting' => $waiting];
}
if (empty($settings['config_enable_cron'])) {
return ['level' => 'danger', 'key' => 'cron_off', 'title' => 'Cron is switched off', 'text' => 'No job runs, so no email is sent.' . $held,
'url' => 'cron.php', 'action' => 'Maintenance > Cron', 'waiting' => $waiting];
}
if (!$heard || time() - strtotime($heard) >= 300) {
return ['level' => 'danger', 'key' => 'cron_stopped', 'title' => 'Cron isn\'t running', 'text' => 'ITFlow last heard from it ' . $ago($heard) . ', so no email is being sent.' . $held,
'url' => 'cron.php', 'action' => 'See how to set it up', 'waiting' => $waiting];
}
if ($job && !intval($job['cron_job_enabled'])) {
return ['level' => 'warning', 'key' => 'job_off', 'title' => 'The Mail Queue job is switched off', 'text' => 'Cron is running, but this job isn\'t.' . $held,
'url' => 'cron.php', 'action' => 'Maintenance > Cron', 'waiting' => $waiting];
}
if ($waiting) {
$error = $job && $job['cron_job_last_error'] && $job['cron_job_last_error_at'] && strtotime($job['cron_job_last_error_at']) > time() - 3600
? ' Its last error: ' . mb_strimwidth((string) $job['cron_job_last_error'], 0, 200, '...') : '';
return ['level' => 'warning', 'key' => 'slow', 'title' => 'Email is waiting longer than it should', 'text' => trim($held) . ' The Mail Queue job last ran ' . $ago($job['cron_job_last_run_at'] ?? null) . '.' . $error,
'url' => 'cron.php', 'action' => 'Maintenance > Cron', 'waiting' => $waiting];
}
return ['level' => '', 'key' => 'ok', 'title' => '', 'text' => 'Sent by the Mail Queue job each minute, up to ' . mailQueuePerMinute() . ' a minute - password links and invites first, bulk email last. It last ran '
. $ago($job['cron_job_last_run_at'] ?? null) . '. A failed email is tried ' . (MAIL_QUEUE_TRIES - 1) . ' more times over about '
. round(array_sum(MAIL_QUEUE_RETRY_AFTER) / 60) . ' hours, and one the mail server turns away for good isn\'t tried again. Email is kept ' . MAIL_QUEUE_KEEP_DAYS . ' days - with what it said, apart from one with a link or code that opens something, cleared once it has gone.', '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';
}
/*
* What an email's manifest (email_attachments) holds - ['files' => names of the files attached,
* 'images' => [cid => app-relative path] of the pictures that go in its message (emailInlineImages())].
*/
function mailQueueAttachments($json) {
$out = ['files' => [], 'images' => []];
foreach ((array) json_decode((string) $json, true) as $attachment) {
if (!is_array($attachment) || trim((string) ($attachment['name'] ?? '')) === '') {
continue;
}
if (!empty($attachment['cid'])) {
$out['images'][(string) $attachment['cid']] = (string) ($attachment['path'] ?? '');
} else {
$out['files'][] = basename((string) $attachment['name']);
}
}
return $out;
}
/*
* The people copied in on an email (email_cc, emailQueue()'s together) - [['email', 'name'], ...],
* each an address.
*/
function mailQueueCc($json) {
$out = [];
foreach ((array) json_decode((string) $json, true) as $person) {
$email = trim((string) ($person['email'] ?? ''));
if (is_array($person) && filter_var($email, FILTER_VALIDATE_EMAIL)) {
$out[] = ['email' => $email, 'name' => trim((string) ($person['name'] ?? ''))];
}
}
return $out;
}
/*
* The headers an email may carry (email_headers), each with what its value must look like - the ones
* that keep a conversation together, and the ones that say an email was sent by ITFlow itself
* (ticketMailAutoHeaders()). Nothing else.
*/
const MAIL_QUEUE_HEADERS = [
'Message-ID' => '/^<[^<>\s]+@[^<>\s]+>$/',
'In-Reply-To' => '/^<[^<>\s]+@[^<>\s]+>$/',
'References' => '/^(<[^<>\s]+@[^<>\s]+>)( <[^<>\s]+@[^<>\s]+>)*$/',
'Auto-Submitted' => '/^auto-(replied|generated)$/',
'X-Auto-Response-Suppress' => '/^[A-Za-z]+(, ?[A-Za-z]+)*$/',
// Bulk email's link to leave, which mail programs show as their own Unsubscribe - one click (RFC 8058, functions/contact_unsubscribe.php)
'List-Unsubscribe' => '/^<https:\/\/[^<>\s]+>$/',
'List-Unsubscribe-Post' => '/^List-Unsubscribe=One-Click$/',
// A ticket's email from another address than the mailbox ITFlow reads asks for replies there - one address (functions/ticket_reply_send.php)
'Reply-To' => '/^[^<>\s@,;:"()\[\]\\\\]+@[^<>\s@,;:"()\[\]\\\\]+$/',
];
/*
* An email's own headers (email_headers, emailQueue()'s thread and auto) - [name => value] of those
* it may carry (MAIL_QUEUE_HEADERS), each as it must look, on one line.
*/
function mailQueueHeaders($json) {
$out = [];
foreach ((array) json_decode((string) $json, true) as $name => $value) {
$value = trim(preg_replace('/[\r\n\t ]+/', ' ', (string) $value));
if (isset(MAIL_QUEUE_HEADERS[$name]) && $value !== '' && strlen($value) <= 4000 && preg_match(MAIL_QUEUE_HEADERS[$name], $value)) {
$out[$name] = $value;
}
}
return $out;
}
/*
* An email's message with its pictures back in it as data, to show in Admin > Mail Queue - the
* message points at them by cid:, as the mail program that gets it reads them. One gone stays a cid:.
*/
function mailQueueShowImages($html, $json) {
$dir = realpath(dirname(__DIR__) . '/' . MAIL_QUEUE_IMAGE_DIR);
foreach (mailQueueAttachments($json)['images'] as $cid => $path) {
$file = $dir ? realpath(dirname(__DIR__) . '/' . $path) : false;
$info = $file && strpos($file, $dir . DIRECTORY_SEPARATOR) === 0 ? @getimagesize($file) : false;
if ($info) {
$html = str_replace('cid:' . $cid, 'data:' . $info['mime'] . ';base64,' . base64_encode((string) file_get_contents($file)), $html);
}
}
return $html;
}
/*
* Delete the pictures no email in the queue points at any more - left a day first, so one saved
* for an email being queued this minute stays (nightly). How many went.
*/
function mailQueueImageCleanup() {
global $mysqli;
$dir = dirname(__DIR__) . '/' . MAIL_QUEUE_IMAGE_DIR;
if (!is_dir($dir)) {
return 0;
}
$kept = [];
$sql = mysqli_query($mysqli, "SELECT email_attachments FROM email_queue WHERE email_attachments LIKE '%mail\\_images%'");
while ($row = mysqli_fetch_row($sql)) {
foreach (mailQueueAttachments($row[0])['images'] as $path) {
$kept[basename($path)] = true;
}
}
$removed = 0;
foreach (glob("$dir/*") ?: [] as $file) {
if (is_file($file) && !isset($kept[basename($file)]) && filemtime($file) < time() - 86400 && @unlink($file)) {
$removed++;
}
}
return $removed;
}
/* Is there an email_sensitive column yet? Database 3.7.1 adds it. */
function mailQueueHasSensitive() {
global $mysqli;
static $has = null;
if ($has === null) {
$result = mysqli_query($mysqli, "SHOW COLUMNS FROM email_queue LIKE 'email_sensitive'");
$has = $result && mysqli_num_rows($result) > 0;
}
return $has;
}
/*
* What an email that has gone keeps, for the UPDATE that marks it sent (cron/mail_queue.php):
* everything, unless it carried a link or code that opens something - then what it said, its
* calendar file and attachments are cleared. Before the update that says which those are,
* every one is cleared, as all were.
*/
function mailQueueSentSql() {
if (!mailQueueHasSensitive()) {
return ", email_content = '', email_cal_str = '', email_attachments = ''";
}
return ", email_content = IF(email_sensitive = 1, '', email_content), email_cal_str = IF(email_sensitive = 1, '', email_cal_str),"
. " email_attachments = IF(email_sensitive = 1, '', email_attachments)";
}
/*
* Clear what a failed or cancelled email with a link or code said, a day after it was queued
* - its tries are long over, and a new one is a new link anyway (nightly). How many.
*/
function mailQueueClearSensitive() {
global $mysqli;
if (!mailQueueHasSensitive()) {
return 0;
}
mysqli_query($mysqli, "UPDATE email_queue SET email_content = '', email_cal_str = '', email_attachments = ''
WHERE email_sensitive = 1 AND email_status IN (2, " . MAIL_QUEUE_CANCELLED . ") AND email_content <> '' AND email_queued_at < NOW() - INTERVAL 1 DAY");
return mysqli_affected_rows($mysqli);
}
/*
* The mail queue at a glance, for the pages that point to it - how many are
* waiting (due now), retrying, and given up on in the last day and the last
* week, and when one was last sent. Read once a request.
*/
function mailQueueSummary() {
global $mysqli;
static $summary = null;
if ($summary !== null) {
return $summary;
}
$row = mysqli_fetch_row(mysqli_query($mysqli, "SELECT
COALESCE(SUM(email_status = 0 AND email_queued_at <= NOW()), 0),
COALESCE(SUM(" . mailQueueRetryingSql() . "), 0),
COALESCE(SUM(" . mailQueueFailedSql() . " AND email_failed_at >= NOW() - INTERVAL 1 DAY), 0),
COALESCE(SUM(" . mailQueueFailedSql() . " AND email_failed_at >= NOW() - INTERVAL 7 DAY), 0),
MAX(CASE WHEN email_status = 3 THEN email_sent_at END)
FROM email_queue WHERE email_queued_at >= NOW() - INTERVAL " . MAIL_QUEUE_KEEP_DAYS . " DAY"));
$summary = ['waiting' => intval($row[0] ?? 0), 'retrying' => intval($row[1] ?? 0), 'failed_day' => intval($row[2] ?? 0), 'failed_week' => intval($row[3] ?? 0), 'last_sent' => $row[4] ?? null];
return $summary;
}