mirror of
https://github.com/itflow-org/itflow
synced 2026-12-02 00:59:03 +00:00
265 lines
15 KiB
PHP
265 lines
15 KiB
PHP
<?php
|
|
|
|
/*
|
|
* ITFlow - email no person wrote, coming into the ticket mailbox and going out of ITFlow.
|
|
*
|
|
* Coming in (cron/ticket_email_parser.php), an email is one of:
|
|
* bounce a mail server saying an email couldn't be delivered (ticketMailIsBounce()) - read
|
|
* before anything else, whatever Admin > Settings > Tickets says: the addresses it
|
|
* failed for are marked on their contacts, and the ticket the email was about gets
|
|
* a note. Never a ticket of its own, and never answered.
|
|
* auto-reply an out-of-office or other automatic answer (ticketMailAutomaticKind()) - an
|
|
* internal note on the ticket it answers, which it doesn't reopen; set aside
|
|
* when it answers none.
|
|
* automated sent by a system, a list or a newsletter - taken as usual, so alerts emailed
|
|
* in still make tickets, but never answered: no "we have your email", no
|
|
* closed-ticket answer, nothing passed on.
|
|
* A mail server or a robot that answers each email it gets would otherwise answer ITFlow's
|
|
* answer, and so on, every minute (RFC 3834).
|
|
*
|
|
* Going out, ITFlow's own automatic emails - the "we have your email", the closed-ticket answer,
|
|
* a client's reply passed on, a colleague's new-ticket email - say so (ticketMailAutoHeaders()),
|
|
* so the other side's out-of-office doesn't answer them, and no one address gets more than
|
|
* TICKET_MAIL_ANSWERS_AN_HOUR answers an hour (ticketMailAnswersLeft()).
|
|
*/
|
|
|
|
/** The most automatic answers - "we have your email", "that ticket is closed" - one address gets in an hour. */
|
|
const TICKET_MAIL_ANSWERS_AN_HOUR = 5;
|
|
|
|
/** The mail servers' own names for themselves, before the @ - an email from one is a bounce. */
|
|
const TICKET_MAIL_BOUNCE_SENDERS = ['mailer-daemon', 'mailer_daemon', 'maildaemon', 'mail-daemon', 'postmaster', 'mailerdaemon'];
|
|
|
|
/*
|
|
* An email's headers, for the questions below - lower-case name => value (the first of each),
|
|
* from ImapEngine's message ($message->headers()).
|
|
*/
|
|
function ticketMailHeaderMap($message) {
|
|
$map = [];
|
|
foreach ($message->headers() as $header) {
|
|
$name = strtolower((string) $header->getName());
|
|
if (!isset($map[$name])) {
|
|
$map[$name] = trim((string) $header->getRawValue());
|
|
}
|
|
}
|
|
return $map;
|
|
}
|
|
|
|
/*
|
|
* Whether the mail server that took an email found it forged, by its Authentication-Results header -
|
|
* the topmost, which that server adds last: a sender's own is below it, and ITFlow only acts on a
|
|
* failure, so one saying "pass" gains them nothing. Failed is:
|
|
* dmarc=fail, from a domain that asks for its forged email to be rejected or quarantined (p=reject or
|
|
* quarantine, or Microsoft 365's action reject, oreject or quarantine) - one with p=none hasn't
|
|
* asked, and many such domains' own email fails too
|
|
* spf=fail (not softfail), with no DKIM signature passing and no DMARC result
|
|
* and never when the server vouched for it anyway - arc=pass, or Microsoft 365's compauth=pass.
|
|
* '' when it didn't fail - or no server checked - else why, in words ("DMARC failed for example.com,
|
|
* which asks for forged email to be rejected").
|
|
*/
|
|
function ticketMailSenderCheck(array $headers) {
|
|
$results = strtolower(preg_replace('/\s+/', ' ', (string) ($headers['authentication-results'] ?? '')));
|
|
if ($results === '') {
|
|
return '';
|
|
}
|
|
$verdicts = [];
|
|
$dmarc_part = '';
|
|
foreach (explode(';', $results) as $part) {
|
|
if (preg_match('/^\s*(dkim|spf|dmarc|arc|compauth)\s*=\s*([a-z]+)/', $part, $m)) {
|
|
$verdicts[$m[1]][] = $m[2];
|
|
if ($m[1] === 'dmarc') {
|
|
$dmarc_part = $part;
|
|
}
|
|
}
|
|
}
|
|
$said = function ($method, $result) use ($verdicts) {
|
|
return in_array($result, $verdicts[$method] ?? [], true);
|
|
};
|
|
if ($said('arc', 'pass') || $said('compauth', 'pass')) {
|
|
return '';
|
|
}
|
|
$domain = preg_match('/header\.from=([a-z0-9.-]+)/', $results, $m) ? $m[1] : '';
|
|
if ($said('dmarc', 'fail') && preg_match('/\b(p|policy)=(reject|quarantine)\b|\baction=(oreject|reject|quarantine|pct\.reject|pct\.quarantine)\b/', $dmarc_part, $policy)) {
|
|
$asks = ($policy[2] ?? '') !== '' ? $policy[2] : str_replace(['pct.', 'oreject'], ['', 'reject'], $policy[3]);
|
|
return 'DMARC failed' . ($domain !== '' ? " for $domain" : '') . ", which asks for forged email to be " . ($asks === 'quarantine' ? 'quarantined' : 'rejected');
|
|
}
|
|
if ($said('spf', 'fail') && !$said('dkim', 'pass') && !isset($verdicts['dmarc'])) {
|
|
return 'SPF failed - it came from a server ' . ($domain !== '' ? $domain : 'its domain') . ' says doesn\'t send its email - and no DKIM signature passed';
|
|
}
|
|
return '';
|
|
}
|
|
|
|
/*
|
|
* Whether an email is a mail server's report that an email couldn't be delivered: a delivery
|
|
* status report (multipart/report; report-type=delivery-status), an X-Failed-Recipients header
|
|
* (Exim), or from MAILER-DAEMON or postmaster. Only the part before the @ - an address with
|
|
* "mta", "daemon" or "bounce" anywhere in it used to count, so jmtaylor@ was a mail server.
|
|
*/
|
|
function ticketMailIsBounce(array $headers, $from_email) {
|
|
$type = strtolower((string) ($headers['content-type'] ?? ''));
|
|
if (strpos($type, 'multipart/report') !== false && preg_match('/report-type\s*=\s*"?delivery-status/', $type)) {
|
|
return true;
|
|
}
|
|
if (trim((string) ($headers['x-failed-recipients'] ?? '')) !== '') {
|
|
return true;
|
|
}
|
|
return ticketMailBounceSender($from_email);
|
|
}
|
|
|
|
/** Whether an address is a mail server's own (TICKET_MAIL_BOUNCE_SENDERS), going by the part before the @. */
|
|
function ticketMailBounceSender($email) {
|
|
$email = strtolower(trim((string) $email));
|
|
$local = substr($email, 0, (int) strrpos($email, '@'));
|
|
return $local !== '' && in_array(preg_replace('/\+.*$/', '', $local), TICKET_MAIL_BOUNCE_SENDERS, true);
|
|
}
|
|
|
|
/** The names a website or its server sends a form's email as, before the @ - WordPress's own, the web server's, a form's. */
|
|
const TICKET_MAIL_SYSTEM_SENDERS = ['wordpress', 'www-data', 'apache', 'nginx', 'httpd', 'nobody', 'webform', 'webforms', 'form', 'forms', 'form-submission', 'form-submissions'];
|
|
|
|
/*
|
|
* Whether an address is one nobody reads - a no-reply address, or a website's or its server's own
|
|
* (TICKET_MAIL_SYSTEM_SENDERS), which a contact form sends its email as. No address at all is one too.
|
|
*/
|
|
function ticketMailSystemSender($email) {
|
|
$email = strtolower(trim((string) $email));
|
|
if ($email === '' || preg_match('/do[\W_]*not[\W_]*reply|no[\W_]*reply/i', $email)) {
|
|
return true;
|
|
}
|
|
$local = substr($email, 0, (int) strrpos($email, '@'));
|
|
return $local !== '' && in_array(preg_replace('/\+.*$/', '', $local), TICKET_MAIL_SYSTEM_SENDERS, true);
|
|
}
|
|
|
|
/*
|
|
* Who an email asks to be answered at - its Reply-To ($reply_email, $reply_name, raw) - when that is the
|
|
* one to take it from. A website's contact form sends its email from the site (wordpress@...), with the
|
|
* visitor in Reply-To, and the site was made the ticket's sender, CC and the one answered: the visitor
|
|
* never heard back. Taken when it is a good address, not ITFlow's own nor the sender's, and:
|
|
* same_domain at the domain the email is from ($from_email) - someone there it was sent for: the email
|
|
* is taken as theirs, as their domain is the one checked (ticketMailSenderCheck())
|
|
* else the sender is one nobody reads (ticketMailSystemSender()) - only answered there, and made
|
|
* the ticket's CC: anyone can write any Reply-To, so it never makes them a client's contact
|
|
* Otherwise null - a person's email is from them, whatever its Reply-To says. ['email', 'name', 'same_domain'].
|
|
*/
|
|
function ticketMailReplyTo($reply_email, $reply_name, $from_email) {
|
|
$reply_email = strtolower(trim((string) $reply_email));
|
|
$from_email = strtolower(trim((string) $from_email));
|
|
if ($reply_email === '' || $reply_email === $from_email || mb_strlen($reply_email) > 200 || !filter_var($reply_email, FILTER_VALIDATE_EMAIL)
|
|
|| emailOwnAddress($reply_email) || ticketMailSystemSender($reply_email) || ticketMailBounceSender($reply_email)) {
|
|
return null;
|
|
}
|
|
$reply_domain = substr($reply_email, strrpos($reply_email, '@') + 1);
|
|
$from_domain = $from_email !== '' && strpos($from_email, '@') !== false ? substr($from_email, strrpos($from_email, '@') + 1) : '';
|
|
$same_domain = $from_domain !== '' && $from_domain === $reply_domain;
|
|
if (!$same_domain && !ticketMailSystemSender($from_email)) {
|
|
return null;
|
|
}
|
|
return ['email' => $reply_email, 'name' => trim((string) $reply_name), 'same_domain' => $same_domain];
|
|
}
|
|
|
|
/*
|
|
* What kind of email no person wrote this is - 'auto-reply', 'automated' or '' (a person wrote it).
|
|
* $headers as ticketMailHeaderMap().
|
|
* auto-reply Auto-Submitted: auto-replied, Precedence: auto_reply, X-Autoreply or X-Autorespond -
|
|
* or a subject starting "Automatic reply:" or "Out of Office:" when it also asks not to
|
|
* be answered (X-Auto-Response-Suppress) or answers a ticket's email ([TCK-123]), as a
|
|
* person may well start a subject "Out of office:"
|
|
* automated Auto-Submitted anything but "no", Precedence bulk, list or junk, or a mailing list's
|
|
* List-Id or List-Unsubscribe
|
|
*/
|
|
function ticketMailAutomaticKind(array $headers, $subject) {
|
|
$submitted = strtolower(trim((string) ($headers['auto-submitted'] ?? '')));
|
|
$precedence = strtolower(trim((string) ($headers['precedence'] ?? '')));
|
|
if (strpos($submitted, 'auto-replied') === 0 || $precedence === 'auto_reply' || isset($headers['x-autoreply']) || isset($headers['x-autorespond'])) {
|
|
return 'auto-reply';
|
|
}
|
|
if (preg_match('/^\s*(automatic reply|auto[- ]?reply|autoreply|out of (the )?office( auto ?reply)?)\s*:/i', (string) $subject)
|
|
&& (isset($headers['x-auto-response-suppress']) || preg_match('/\[[^\[\]\s]{0,40}\d\]/', (string) $subject))) {
|
|
return 'auto-reply';
|
|
}
|
|
if (($submitted !== '' && $submitted !== 'no') || in_array($precedence, ['bulk', 'list', 'junk'], true) || isset($headers['list-id']) || isset($headers['list-unsubscribe'])) {
|
|
return 'automated';
|
|
}
|
|
return '';
|
|
}
|
|
|
|
/*
|
|
* What a bounce says, from its parts' text - each part [content type, content]:
|
|
* failed the addresses it failed for - Action: failed in its delivery status, else
|
|
* X-Failed-Recipients - [email => 'status - diagnostic']
|
|
* delayed true when every address in it is only delayed - not a failure yet
|
|
* message_id the Message-ID of the email that bounced, from the copy or headers it returns
|
|
* subject that email's subject
|
|
* $failed_header is X-Failed-Recipients, $text the bounce's own text, for a diagnostic when its
|
|
* delivery status gives none.
|
|
*/
|
|
function ticketMailBounceRead(array $parts, $failed_header = '', $text = '') {
|
|
$out = ['failed' => [], 'delayed' => false, 'message_id' => '', 'subject' => ''];
|
|
$actions = [];
|
|
foreach ($parts as [$type, $content]) {
|
|
$type = strtolower((string) $type);
|
|
$content = (string) $content;
|
|
if (strpos($type, 'delivery-status') !== false) {
|
|
// A block per recipient after the one about the whole report - split on blank lines
|
|
foreach (preg_split('/\r?\n\s*\r?\n/', $content) as $block) {
|
|
if (!preg_match('/^(?:Final|Original)-Recipient:\s*[^;\r\n]*;\s*<?([^\s>]+@[^\s>]+)>?/mi', $block, $m)) {
|
|
continue;
|
|
}
|
|
$email = strtolower(trim($m[1]));
|
|
$action = preg_match('/^Action:\s*(\S+)/mi', $block, $a) ? strtolower($a[1]) : 'failed';
|
|
$actions[] = $action;
|
|
if ($action !== 'failed') {
|
|
continue;
|
|
}
|
|
$status = preg_match('/^Status:\s*([0-9.]+)/mi', $block, $s) ? $s[1] : '';
|
|
// A diagnostic can run on over indented lines
|
|
$diagnostic = preg_match('/^Diagnostic-Code:\s*(.+(?:\r?\n[ \t]+.+)*)/mi', $block, $d) ? trim(preg_replace('/\s+/', ' ', preg_replace('/^[^;]*;\s*/', '', $d[1]))) : '';
|
|
$out['failed'][$email] = trim($status . ($status !== '' && $diagnostic !== '' ? ' - ' : '') . mb_substr($diagnostic, 0, 400));
|
|
}
|
|
} elseif (strpos($type, 'message/rfc822') !== false || strpos($type, 'rfc822-headers') !== false) {
|
|
$head = preg_split('/\r?\n\r?\n/', $content, 2)[0];
|
|
// Folded header lines unfolded
|
|
$head = preg_replace('/\r?\n[ \t]+/', ' ', $head);
|
|
if ($out['message_id'] === '' && preg_match('/^Message-ID:\s*(<[^>\s]+>)/mi', $head, $m)) {
|
|
$out['message_id'] = trim($m[1], '<>');
|
|
}
|
|
if ($out['subject'] === '' && preg_match('/^Subject:\s*(.+)$/mi', $head, $m)) {
|
|
$out['subject'] = trim(iconv_mime_decode($m[1], ICONV_MIME_DECODE_CONTINUE_ON_ERROR, 'UTF-8') ?: $m[1]);
|
|
}
|
|
}
|
|
}
|
|
// Exim and others that say who in a header instead
|
|
if (!$out['failed'] && !$actions) {
|
|
foreach (preg_split('/[\s,]+/', (string) $failed_header) as $email) {
|
|
if (filter_var(trim($email, '<>'), FILTER_VALIDATE_EMAIL)) {
|
|
$diagnostic = preg_match('/\n\s{2,}(\S.+)/', (string) $text, $d) ? trim($d[1]) : '';
|
|
$out['failed'][strtolower(trim($email, '<>'))] = mb_substr($diagnostic, 0, 400);
|
|
}
|
|
}
|
|
}
|
|
$out['delayed'] = !$out['failed'] && $actions && !array_diff($actions, ['delayed']);
|
|
return $out;
|
|
}
|
|
|
|
/*
|
|
* The headers of one of ITFlow's own automatic emails - $kind 'replied' for an answer to an email
|
|
* ("we have your email", "that ticket is closed"), 'generated' for one sent by itself (a client's
|
|
* reply passed on). They tell the other side's mail server and out-of-office not to answer it.
|
|
*/
|
|
function ticketMailAutoHeaders($kind) {
|
|
return ['Auto-Submitted' => $kind === 'replied' ? 'auto-replied' : 'auto-generated', 'X-Auto-Response-Suppress' => 'OOF, AutoReply'];
|
|
}
|
|
|
|
/*
|
|
* Whether $email may be sent one more automatic answer this hour - fewer than
|
|
* TICKET_MAIL_ANSWERS_AN_HOUR queued to it already (an answer carries Auto-Submitted: auto-replied).
|
|
* A sender that emails every minute, or answers each answer, is answered five times, not forever.
|
|
*/
|
|
function ticketMailAnswersLeft($email) {
|
|
global $mysqli;
|
|
if (!ticketMailThreadReady()) {
|
|
return true;
|
|
}
|
|
$count = intval(mysqli_fetch_row(mysqli_query($mysqli, "SELECT COUNT(*) FROM email_queue WHERE email_recipient = '" . mysqli_real_escape_string($mysqli, trim((string) $email)) . "'
|
|
AND email_queued_at >= NOW() - INTERVAL 1 HOUR AND email_headers LIKE '%auto-replied%'"))[0] ?? 0);
|
|
return $count < TICKET_MAIL_ANSWERS_AN_HOUR;
|
|
}
|