diff --git a/CHANGELOG.md b/CHANGELOG.md index a4e106be6..1105b7698 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -86,7 +86,7 @@ Update from Maintenance > Update as usual - this release has fourteen database c - Links in emails stop working once they're done with: the link that opens a ticket, an invoice or a quote without signing in - in its emails, forwarded on or kept for years - stops working 90 days after the ticket is closed, the invoice paid in full, or the quote accepted, declined, invoiced or run out. Open tickets, unpaid invoices and quotes waiting for an answer always work, a reopened ticket's link works again, and emailing an invoice or quote again counts from then. An expired link says so and points to the client portal, where they're shown as always. On an invoice or a quote, Copy Client Link says Expired once it has. Admin > Settings > Security, Links in emails, sets 30, 60, 90 (to start), 180 days or a year - or never, as before. - Your own wording for the emails about a ticket to clients: Admin > Settings > Mail > Previews has Edit Wording on each of the 13 - ticket opened, their email became a ticket, scheduled ticket, reply, resolved, closed, a client's reply passed on, added as a CC, new ticket at their company, approval needed, work booked, booked work cancelled and replied to a closed ticket. Change its subject, heading, opening and closing text, with words in square brackets filled in as it goes, as in canned responses - [Ticket], [Subject], [First Name], [Client], [Agent], [Company] and each email's own, such as [By] and [When]. The preview shows it at once, the list marks the ones you changed, and Use ITFlow's Wording puts one back. The subject always starts with the ticket's number, so replies still find it. - Ignored senders: Admin > Ignored Senders lists the addresses and domains whose email the ticket mailbox sets aside - no ticket, no reply on one, no answer and nothing in Unprocessed Email. Newsletters, spam that gets through and noisy systems go straight to the mailbox's ITFlow folder. A domain takes its subdomains too, each shows how many emails it set aside and when the last came, and saving one that would set aside a contact's or a client's email says so. A mail server's bounce is still read, and Try an Email shows the step. -- Bounces come back to the email they were about: a reply on a ticket says "Email to ... bounced" with what the mail server said, where it said it was emailed, and an invoice's or quote's history says its email bounced. The Mail Queue has a Bounced tab, and the email's window shows the mail server's reason. Each email ITFlow sends now has its own Message-ID, so the bounce finds it - one sent before the update is found by its address and subject. +- Bounces come back to the email they were about: a reply on a ticket says "Email to ... bounced" with what the mail server said, where it said it was emailed, and an invoice's or quote's history says its email bounced. The Mail Queue has a Bounced tab, and the email's window shows the mail server's reason. Each email ITFlow sends now has its own Message-ID, so the bounce finds it - one sent before the update is found by its address and subject. A bounce from an address the email wasn't sent to - someone's mail sent on to another mailbox - says where it came back from, and on an email to several people nobody is singled out for it. ### Bug Fixes @@ -171,7 +171,7 @@ Update from Maintenance > Update as usual - this release has fourteen database c - Mail review stage 7b: database 4.3.2 adds email_unprocessed. functions/mail_unprocessed.php keeps an email the parser couldn't take - mailUnprocessedKeep($raw, $meta, $reason) writes its MIME to uploads/mail_unprocessed (denied to the web, as uploads/backups) and a row, one per Message-ID - and mailUnprocessedDecide() records an agent's ticket, reply, retry or dismiss (agent/email_unprocessed.php, agent/post/email_unprocessed.php). cron/ticket_email_parser.php appends mailUnprocessedAsked() to the run as MailUnprocessedMessage (functions/mail_unprocessed_message.php), a FileMessage whose move() is mailUnprocessedDone() with the ticket it went on and whose flags do nothing: a ticket or reply ask skips steps 1 to 6 for addTicket() at the chosen contact or client (or a new contact, as the domain match makes one) or addReply() on the chosen ticket (the sender added through ticketAddCcs() first, if asked); a retry goes the usual way. mailUnprocessedLeave() takes the unprocessed and exception branches - kept, then marked seen and moved to the ITFlow folder; flagged and unread as before when it can't be kept; an ask that fails waits again with the reason. mailUnprocessedCleanup() runs nightly. - Mail review stage 7c: database 4.3.3 adds settings.config_ticket_reply_undo_seconds (0, 5, 10, 20 or 30 - TICKET_REPLY_UNDO_CHOICES) and config_ticket_reply_to_read, read by ticketReplySendSettings() (functions/ticket_reply_send.php). Undo send is the ticket page alone: #ticketReplyForm's data-undo-seconds, and agent/js/ticket_reply_extras.js holds an emailed or texted reply's submit in a window listener - after the form's own checks and the canned response check on the document - with the reply card inert and the [data-reply-hold] bar, then requestSubmit()s it with holdOk, cannedSendAnyway and noTimeOk set; agent/post/ticket.php is unchanged. emailQueue() puts Reply-To (ticketMailReplyToRead(): email to ticket on, the setting on, the IMAP username an address and not From) in a thread email's headers; MAIL_QUEUE_HEADERS lets one bare address through and sendQueueEmail() gives it to addReplyTo(), so Graph's large-email draft carries it too. - Mail review stage 7d: database 4.3.4 adds settings.config_guest_link_days (GUEST_LINK_DAYS_CHOICES, 90) and email_templates. functions/guest_link.php: guestLinkDoneAt() - ticket_closed_at; a Paid invoice's last unarchived payment (else its Paid history, else invoice_updated_at); an Accepted, Declined or Invoiced quote's history for it, or the end of quote_expire for one unanswered - later of that and the last history line with 'emailed' in it; guestLinkExpired() adds the days. ticketByGuestKey() returns null for an expired link, setting its new &$expired, so the guest ticket page, its attachments, its posts and its calendar file all refuse it; guest_view_invoice.php, guest_view_quote.php, the guest PDF exports (410) and the quote upload check it too, and guestLinkExpiredHtml() is the page; agent/invoice.php and agent/quote.php mark Copy Client Link Expired. functions/email_template.php: EMAIL_TEMPLATES (the 13 Tickets - to clients preview keys, with ITFlow's wording in placeholders), emailTemplateApply() replaces title, intro (paragraphs) and after where saved, filling [Placeholders] from emailTemplateValues() (ticketPlaceholderValues() and the email's own; empty when there is nothing), and puts the subject in template_subject for emailTemplateSubject(), which prefixes [REF] when it isn't in it. Applied in ticketEmailContent() (not the stranger's subject, nor Resolve - no response's intro), ticketMailSend(), ticketMailCcsAdded(), ticketMailColleaguesNew(), ticketMailTaskApproval() (the client's only) and ticketMailClosedReply(). admin/modals/email_template/email_template_edit.php and admin/post/email_template.php (save_email_template, reset_email_template - a part sent back as the default is NULL); mail_preview.php answers template and edited. -- Mail review stage 8: database 4.3.5 adds email_ignored_senders and email_queue.email_message_id (indexed, filled in from email_headers), email_about, email_bounced_at and email_bounce. functions/mail_ignore.php: mailIgnoreClean() takes an address or a domain (@ or *@ in front allowed), mailIgnoreFind() matches the From address - an address rule before a domain one, a domain matching its subdomains - and cron/ticket_email_parser.php sets the email aside (seen, moved, mailIgnoreHit()) after the bounce check, unless it is a MailUnprocessedMessage asked to make a ticket or reply; ticketMailTry() has the step. Admin > Ignored Senders (admin/email_ignored_senders.php, modals/email_ignored_sender/, admin/post/email_ignored_sender.php). The parser leaves email from someone who isn't a contact at a domain no client has (unknown senders off), or whose sender checks failed, in the inbox flagged as before 7b - mailUnprocessedLeave() keeps only an email that was taken and failed, or an agent's ask; ticketMailTry() says Left in the inbox. emailQueue() gives every email a Message-ID (emailMessageId()) where the conversation gave none and takes about (invoice:N, quote:N - billingEmailQueue()'s about, passed by every invoice and quote send); addToMailQueue() keeps both. addBounce() calls mailQueueBounced(): the sent row by email_message_id, else the last week's sent to a failed address with the bounce's subject, marked with {address: why}, and a billing email's history written. mailQueueStateOf() has bounced (status 3 with email_bounced_at), mailQueueTabs() a Bounced tab, ticketReplyEmailStates() marks each bounced recipient and the key bounced, and ticketReplyEmailHtml() says so. .gitignore leaves out uploads/mail_unprocessed and uploads/kb, as the other upload folders. +- Mail review stage 8: database 4.3.5 adds email_ignored_senders and email_queue.email_message_id (indexed, filled in from email_headers), email_about, email_bounced_at and email_bounce. functions/mail_ignore.php: mailIgnoreClean() takes an address or a domain (@ or *@ in front allowed), mailIgnoreFind() matches the From address - an address rule before a domain one, a domain matching its subdomains - and cron/ticket_email_parser.php sets the email aside (seen, moved, mailIgnoreHit()) after the bounce check, unless it is a MailUnprocessedMessage asked to make a ticket or reply; ticketMailTry() has the step. Admin > Ignored Senders (admin/email_ignored_senders.php, modals/email_ignored_sender/, admin/post/email_ignored_sender.php). The parser leaves email from someone who isn't a contact at a domain no client has (unknown senders off), or whose sender checks failed, in the inbox flagged as before 7b - mailUnprocessedLeave() keeps only an email that was taken and failed, or an agent's ask; ticketMailTry() says Left in the inbox. emailQueue() gives every email a Message-ID (emailMessageId()) where the conversation gave none and takes about (invoice:N, quote:N - billingEmailQueue()'s about, passed by every invoice and quote send); addToMailQueue() keeps both. addBounce() calls mailQueueBounced(): the sent row by email_message_id, else the last week's sent to a failed address with the bounce's subject, marked with {address: why}, and a billing email's history written. mailQueueStateOf() has bounced (status 3 with email_bounced_at), mailQueueTabs() a Bounced tab, ticketReplyEmailStates() marks each bounced recipient and the key bounced, and ticketReplyEmailHtml() says so. A report naming an address that isn't on the email, or nobody: on an email to one person it is theirs ("address: why"); on one to several the named address is kept in email_bounce as it is, nobody on it is marked, and the reply has elsewhere => [address or '' => why]. A billing email's history is written the first time and for each address more. .gitignore leaves out uploads/mail_unprocessed and uploads/kb, as the other upload folders. ## [26.12.2] diff --git a/functions/mail_ignore.php b/functions/mail_ignore.php index aca7367dd..ba08e209f 100644 --- a/functions/mail_ignore.php +++ b/functions/mail_ignore.php @@ -34,7 +34,8 @@ function mailIgnoreClean($input) { if (filter_var($input, FILTER_VALIDATE_EMAIL) && mb_strlen($input) <= 255) { return ['match' => $input, 'kind' => 'address']; } - if (preg_match('/^(?=.{3,253}$)([a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,63}$/', $input)) { + // Its last part letters, or an international one as mail servers write it (xn--p1ai) + if (preg_match('/^(?=.{3,253}$)([a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+(?:[a-z]{2,63}|xn--[a-z0-9-]{1,59})$/D', $input)) { return ['match' => $input, 'kind' => 'domain']; } return null; @@ -142,6 +143,7 @@ function mailIgnoreAdd(array $rule, $note, $user_id) { } mysqli_query($mysqli, "INSERT INTO email_ignored_senders SET ignored_sender_match = '$match_sql', ignored_sender_note = '" . escapeSql(mb_substr(trim((string) $note), 0, 255)) . "', ignored_sender_created_by = " . intval($user_id)); + $id = intval(mysqli_insert_id($mysqli)); mailIgnoreRules(true); - return intval(mysqli_insert_id($mysqli)); + return $id; } diff --git a/functions/mail_queue.php b/functions/mail_queue.php index 1465585bf..9d8f9aa43 100644 --- a/functions/mail_queue.php +++ b/functions/mail_queue.php @@ -204,14 +204,18 @@ function mailQueueBounceColumns() { * 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. The row as it was, or null when none is found. + * 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; if (!mailQueueBounceReady()) { return null; } - $columns = "email_id, email_recipient, email_cc, email_subject, email_about, email_ticket_reply_id, email_bounce"; + $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")); @@ -226,30 +230,43 @@ function mailQueueBounced($message_id, array $failed, $subject = '') { if (!$row) { return null; } - // Who it bounced for - the addresses it was to that the report names, or everyone on it when it names none - $on_it = array_merge([strtolower((string) $row['email_recipient'])], array_map(function ($person) { + // 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'] ?? ''))); - $bounce = (array) json_decode((string) ($row['email_bounce'] ?? ''), true); - foreach ($failed ?: array_fill_keys($on_it, '') as $address => $why) { + }, 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); } } - if (!$bounce) { - $bounce = array_fill_keys($on_it, ''); + // 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($bounce, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES)) . "' + 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 - if (preg_match('/^(invoice|quote):(\d+)$/', (string) $row['email_about'], $about) && function_exists('billingLog')) { + // 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 !== '') { - $why = implode('; ', array_filter($bounce)); - billingLog($about[1], intval($about[2]), $status, 'Email to ' . implode(', ', array_keys($bounce)) . ' bounced' . ($why !== '' ? ' - ' . mb_strimwidth($why, 0, 300, '...') : '')); + $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; diff --git a/functions/ticket.php b/functions/ticket.php index 65d6bbcf2..6e89b5831 100644 --- a/functions/ticket.php +++ b/functions/ticket.php @@ -1032,7 +1032,10 @@ function ticketReplyEmailed($reply_id, $emailed = true) { * and ticket_reply_emailed_to. Reply id => ['to' => [['email', 'name', 'state' * => mailQueueState(), or null once the queue has cleared it]], 'key' => sent, * waiting (still to go, or being tried again), failed, cancelled, or gone (the - * queue no longer has them - kept 90 days)], for each reply emailed. + * queue no longer has them - kept 90 days)], for each reply emailed. An email + * that bounced for an address it wasn't sent to - someone's mail sent on - or + * for nobody the report names, when it went to several (mailQueueBounced()): + * 'elsewhere' => [address, or '' => why], and the key is bounced. */ function ticketReplyEmailStates(array $rows) { global $mysqli; @@ -1063,6 +1066,14 @@ function ticketReplyEmailStates(array $rows) { // Those copied in went, or didn't, with it $people = array_merge([['email' => (string) $email['email_recipient'], 'name' => (string) $email['email_recipient_name'] !== (string) $email['email_recipient'] ? (string) $email['email_recipient_name'] : '']], mailQueueCc($email['email_cc'])); + if ($state['key'] === 'bounced') { + // For an address that isn't on it, or nobody it could name - which of them it was for can't be told + $on_it = array_flip(array_map(function ($person) { return strtolower($person['email']); }, $people)); + $others = array_diff_key($state['bounce'], $on_it); + if ($others || !array_intersect_key($state['bounce'], $on_it)) { + $states[$reply_id]['elsewhere'] = ($states[$reply_id]['elsewhere'] ?? []) + array_map('mailQueueErrorText', $others ?: ['' => '']); + } + } foreach ($people as $person) { $address = strtolower($person['email']); $person_state = $state; @@ -1091,7 +1102,8 @@ function ticketReplyEmailStates(array $rows) { } else { $key = 'sent'; } - $states[$reply_id] = ['to' => array_values($state['to']), 'key' => $key]; + $elsewhere = (array) ($state['elsewhere'] ?? []); + $states[$reply_id] = ['to' => array_values($state['to']), 'key' => $key === 'sent' && $elsewhere ? 'bounced' : $key] + ($elsewhere ? ['elsewhere' => $elsewhere] : []); } return $states; } @@ -1873,7 +1885,7 @@ function ticketReplyEmailHtml($reply_id, array $state, $queue_url = '') { break; case 'bounced': [$icon, $text, $title] = ['fa-reply text-danger', $bounced === count($to) ? "Email to $first bounced" - : "Emailed to $first · $bounced bounced", 'Bounced']; + : "Emailed to $first · " . ($bounced ? "$bounced bounced" : 'a bounce came back') . "", 'Bounced']; break; default: [$icon, $text, $title] = ['fa-paper-plane', "Emailed to $first", '']; @@ -1894,9 +1906,16 @@ function ticketReplyEmailHtml($reply_id, array $state, $queue_url = '') { . ''; } $gone = !array_filter(array_column($to, 'state')); + // It came back for an address it wasn't sent to, or for nobody it named (ticketReplyEmailStates()) + $elsewhere = ''; + foreach ((array) ($state['elsewhere'] ?? []) as $address => $why) { + $elsewhere .= '
' . ((string) $address !== '' + ? 'It came back from ' . escapeHtml($address) . ', which it wasn\'t sent to - one of them has their mail sent on there' . ((string) $why !== '' ? ': ' . escapeHtml($why) : '.') + : 'A bounce came back for this email that doesn\'t say who it couldn\'t reach.') . '
'; + } $panel = '
' . '
' - . '' + . '' . $elsewhere . ($gone ? '
The mail queue keeps email ' . MAIL_QUEUE_KEEP_DAYS . ' days, so whether each one went is no longer known.
' : '') . ($queue_url !== '' ? 'This ticket\'s email in the Mail Queue' : '') . '
'; diff --git a/functions/ticket_mail_try.php b/functions/ticket_mail_try.php index 0492eb2dc..b3eba0198 100644 --- a/functions/ticket_mail_try.php +++ b/functions/ticket_mail_try.php @@ -163,7 +163,7 @@ function ticketMailTry($from_email, $subject, $auto_reply = false) { if (!$config_ticket_email_parse_unknown_senders) { $steps[] = ['Tickets from unknown senders?', 'Off']; return ['steps' => $steps, 'outcome' => ['fa-inbox', 'warning', 'Left in the inbox', - 'ITFlow leaves it in the mailbox\'s inbox, flagged, and doesn\'t look at it again. Make the sender a contact, add their domain to a client, or turn on Tickets from unknown senders to have email like it taken.']]; + 'ITFlow leaves it in the mailbox\'s inbox, flagged, and doesn\'t look at it again. Make the sender a contact, add their domain to a client, or turn on From unknown senders too, to have email like it taken - and clear the flag on one already there to have it taken as well.']]; } $steps[] = ['Tickets from unknown senders?', 'On']; return ['steps' => $steps, 'outcome' => ['fa-plus-circle', 'success', 'A new ticket with no client',