diff --git a/CHANGELOG.md b/CHANGELOG.md
index 919822e9d..16aca3724 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -21,6 +21,7 @@ Update from Maintenance > Update as usual. This release has one database change,
- Two-step sign-in no longer says "Your MFA session expired" right after the code is typed. The code boxes send the code on its sixth digit, so pressing Enter out of habit - or a password manager or phone keyboard sending it too, or a double click on Verify & Sign In - sent it a second time, and that second copy signed you out. Each form on the sign-in page now goes once, a second copy that still gets through takes you into ITFlow, and a wrong code sent twice says the code is wrong.
- The two-step code can be typed up to five minutes after the password, up from two - time to find the phone and the right account in the authenticator app.
- A password manager or phone that fills in the two-step code and sends the form itself signs you in, instead of going back to the email and password.
+- A client's email that one of your agents forwards to the ticket mailbox is now a ticket for that client, from the person who sent it, instead of a ticket for your own company or none at all. What the agent wrote above it is their internal note on the ticket, and its history says who forwarded it. Someone at a client's domain who isn't a contact yet is added as one; anyone else gets a ticket with no client for an agent to sort out - even with tickets from unknown senders off - and isn't sent anything or copied in. This works for forwards from Gmail, Outlook (desktop, the web and the new Outlook), Apple Mail and Thunderbird, and for an email forwarded as an attachment. A reply that quotes a client's email, an email with a ticket number in its subject, and an agent forwarding a colleague's email are taken as before, and Try an Email in Settings > Tickets says how an agent's forwards are read.
### Developer Updates
@@ -29,6 +30,7 @@ Update from Maintenance > Update as usual. This release has one database change,
- `js/login_prevent_resubmit.js` lets each form on the sign-in page submit once (until the page comes back from history, or 10 seconds), and `js/otp_input.js` does the same for any form with a `data-otp-submit` code field - turning on MFA, the client portal's two-step setup and shared-link codes.
- Saved cards expiring (DB 4.3.8): new `functions/card_expiry.php`. `cardExpiryNightly($now = null)`, called from `cron/nightly_tasks.php` before autopay, reads back from Stripe (`cardRefresh()`, PaymentMethods retrieve) up to `CARD_EXPIRY_CHECK_LIMIT` (200) cards a night whose expiry is from 6 months ago to next month and that weren't checked in 20 hours, keeping Stripe's brand, last four and expiry in `saved_payment_description` and stamping `saved_payment_checked_at`. It then finds cards on autopay for active recurring invoices (`cardAutopayCards()`) and, for an expiry within 30 days of its month starting (stage 1) or in or past its month (stage 2), emails the billing recipients (`billingMailCardExpiring()`), notifies the team (`Card Expiring`) and logs each recurring invoice's history, recording `saved_payment_reminded_expiry`, `saved_payment_reminded` and a random `saved_payment_update_key` that both stages' links share. `settings.config_invoice_card_expiry_reminders` (default 1) and `client_reminders` gate the email only. `guest/guest_card_update.php?card=&key=` reuses `js/guest_autopay_stripe.js` (its form's `data-checkout-url` now picks the endpoint): `guest_ajax.php?guest_card_update_checkout` starts a setup-mode Checkout Session on the client's Stripe customer (`cardUpdateCheckoutStart()`), and `guest_post.php?guest_card_update_done` runs `cardUpdateFinish()`, which checks the session's mode, card and customer first, saves the new card, repoints every `recurring_payments` row of the client's that used the old card, clears the key, and sends `billingMailCardUpdated()`. `billingCardParts()` gains `expires` (yyyymm), `billingStripeChargeSaved()` reads an expired-looking card back from Stripe before refusing it, and `autopayFailedNotify()` in `functions/billing_pay.php` sends the `Autopay Failed` notification from the nightly autopay's failure branches.
- Texts: `smsInboxBulk($action, $ids, $user_id)` in `functions/sms.php` runs an action from `SMS_INBOX_BULK` (dismiss, spam, clear, not_spam, delete => the status it takes texts from and the permission it needs) on the ticked inbound texts, or with `$ids` null on the whole tab, inside `clientScopeSql()`. Spam and not spam block or unblock the numbers and move every text from them, as the single actions do. Clearing a code sets it to dismissed with its body, code and media wiped, so the text log's search can't find its words. `agent/post/texts.php` takes `bulk_texts` (with `sms_message_ids[]`) and `bulk_texts_all`, plus `sms_clear_code` for one code. `agent/texts.php` uses the standard `js/bulk_actions.js` select-all and Bulk Action button.
+- Forwarded client emails: new `functions/ticket_mail_forward.php`. In `cron/ticket_email_parser.php`, after the thread and ticket-number steps and before `ticketMailSenderContact()`, an email from an active agent (`ticketMailForwardAgent()`) that isn't forged, automatic or answered at its Reply-To goes to `ticketMailForwarded($html, $text, $subject, $attachments)`. It looks for the first header block - a From line with an address and a Sent, Date, To or Subject line beside it, with English and common European labels - below a forward line (Gmail's, Thunderbird's, Apple Mail's), or anywhere when the subject is a forward (`TICKET_MAIL_FORWARD_ONLY`); Outlook's `-----Original Message-----` and underscore line only count with a forward subject, as its replies have them too. The HTML is split at `gmail_quote`, `moz-forward-container`, `divRplyFwdMsg`/`appendonsend`, Outlook's bordered header div, `blockquote type="cite"` or the forward line, as long as the part from there holds the sender, else the text part is split; a single `message/rfc822` attachment is parsed with MailMimeParser, its cid pictures inlined. When the forwarded sender isn't one of your addresses, your domain or an agent (`ticketMailForwardFromClient()`), the parser takes its sender, subject (`ticketMailForwardSubject()`) and body and sets `$email['forward'] = ['agent', 'note']`. A forward is never a similar-subject reply (it is linked as related, `linkSimilarTicket(..., true)`), a contact it creates says who forwarded it, and step 6 runs for it whatever `config_ticket_email_parse_unknown_senders` says. `addTicket()` adds "forwarded by" to the from line and audit entry, calls `ticketMailForwardNote()` (an Internal reply by the agent, when there is a note, and a history line), and doesn't CC or answer a forwarded sender with no contact. Parser attachments now carry `mime`. `ticketMailTry()` adds a "From one of your agents?" step.
## [26.12.3]
diff --git a/cron/ticket_email_parser.php b/cron/ticket_email_parser.php
index 062211c76..5e0b38876 100644
--- a/cron/ticket_email_parser.php
+++ b/cron/ticket_email_parser.php
@@ -97,6 +97,8 @@ $read_mail_minutes = 60; // Mail someone opened before this got to it
* via the address it was sent from, when it is taken as from its Reply-To (ticketMailReplyTo()) -
* shown beside who it is from
* picked the sender is a contact at more than one client (ticketMailSenderContact()) - said in a note
+ * forward an agent forwarded it - ['agent' => ['user_id', 'user_name'], 'note' => what they wrote above it, HTML]
+ * (functions/ticket_mail_forward.php): named beside who it is from, their note on the ticket by them
* One from someone who isn't a contact ($contact_id 0) is answered without its own subject or a link to the
* ticket: anyone can send an email from someone else's address, and the answer carried their words to them.
* One with no sender address ($contact_email '') is answered by nobody. The new ticket's id.
@@ -115,6 +117,7 @@ function addTicket($contact_id, $contact_name, $contact_email, $client_id, $date
$dropped = (array) ($email['dropped'] ?? []);
$forged = (string) ($email['forged'] ?? '');
$via = (string) ($email['via'] ?? '');
+ $forward = (array) ($email['forward'] ?? []);
// Atomically increment and get the new ticket number
mysqli_query($mysqli, "
@@ -141,6 +144,7 @@ function addTicket($contact_id, $contact_name, $contact_email, $client_id, $date
// Wrap final formatted message
$from_line = $contact_email_raw !== '' ? "" . escapeHtml($contact_name_raw) . " <" . escapeHtml($contact_email_raw) . ">" : 'No sender address';
$from_line .= $via !== '' ? ' - sent by ' . escapeHtml($via) : '';
+ $from_line .= $forward ? ' - forwarded by ' . escapeHtml($forward['agent']['user_name']) : '';
$message = "Email from: $from_line at $date:-
", "Priya [mailto:p@x.com]", "p@x.com" - or null. */ +function ticketMailForwardAddress($value) { + $value = trim((string) $value); + if (!preg_match('/[A-Z0-9._%+\'-]+@[A-Z0-9.-]+\.[A-Z]{2,}/i', $value, $m)) { + return null; + } + $email = strtolower($m[0]); + if (!filter_var($email, FILTER_VALIDATE_EMAIL)) { + return null; + } + // The name is what comes before the address, its brackets and quotes taken off + $name = trim((string) preg_replace('/\s*(?:<|\[mailto:|\(|<|mailto:)?\s*' . preg_quote($m[0], '/') . '.*$/i', '', $value)); + $name = trim($name, " \t\"'<>[]*,"); + if ($name === '' || strcasecmp($name, $email) === 0) { + $name = ''; + } + return ['email' => $email, 'name' => mb_substr($name, 0, 200)]; +} + +/* + * The header block a forwarded email starts with, in $text: ['email', 'name', 'subject', 'line' => the line it + * starts at, 'marker' => the line above it that starts what was forwarded, or -1]. The first one from the top, the one + * forwarded last. $forwarded: the subject says it is a forward (Fwd:, FW:), so a block with no line saying so counts too - + * Outlook's has none, or one a reply has as well. Null without one. + */ +function ticketMailForwardBlock($text, $forwarded) { + $lines = explode("\n", str_replace(["\r\n", "\r"], "\n", (string) $text)); + $count = count($lines); + $marker = -1; + $marker_says = false; + for ($i = 0; $i < $count; $i++) { + $line = $lines[$i]; + foreach ([[TICKET_MAIL_FORWARD_MARKERS, true], [TICKET_MAIL_FORWARD_QUOTE_MARKERS, false]] as [$patterns, $says]) { + foreach ($patterns as $pattern) { + if (preg_match($pattern, $line)) { + $marker = $i; + $marker_says = $says; + continue 3; + } + } + } + if (!preg_match(TICKET_MAIL_FORWARD_FROM, $line, $m) || !($who = ticketMailForwardAddress($m[1]))) { + continue; + } + // A header block: another header line beside the From one, not blank lines apart - and a line above saying it + // is a forward, or a subject that does + $start = $i; + $labels = 0; + $subject = ''; + for ($j = $i - 1; $j >= max(0, $i - 5) && trim($lines[$j]) !== ''; $j--) { + if (preg_match(TICKET_MAIL_FORWARD_LABEL, $lines[$j])) { + $labels++; + $start = $j; + } + } + for ($j = $i + 1; $j < min($count, $i + 7) && trim($lines[$j]) !== ''; $j++) { + if (preg_match(TICKET_MAIL_FORWARD_LABEL, $lines[$j])) { + $labels++; + } + } + for ($j = $start; $j < min($count, $i + 7); $j++) { + if (preg_match(TICKET_MAIL_FORWARD_SUBJECT_LABEL, $lines[$j], $s)) { + $subject = trim($s[1]); + break; + } + } + $near_marker = $marker >= 0 && $start - $marker <= 4; + if ($labels && (($near_marker && $marker_says) || $forwarded)) { + return $who + ['subject' => $subject, 'line' => $start, 'marker' => $near_marker ? $marker : -1]; + } + } + return null; +} + +/* + * Where the forwarded part starts in an email's HTML - the agent's note above it, the client's email from it - or + * -1. The containers mail apps put a forward in (Gmail's gmail_quote, Thunderbird's moz-forward-container, + * Outlook's divRplyFwdMsg and its bordered header, Apple Mail's quote), or the tag holding the line that says + * it is a forward. Only where the part from there has the forwarded email's sender in it. + */ +function ticketMailForwardHtmlSplit($html, $sender_email) { + $html = (string) $html; + $starts = []; + foreach ([ + '#
]*\btype=["\']cite["\']#i', + ] as $pattern) { + if (preg_match($pattern, $html, $m, PREG_OFFSET_CAPTURE)) { + $starts[] = $m[0][1]; + } + } + // The tag holding a line that says it is a forward + foreach (['#-{2,}\s*(?:forwarded message|original message|weitergeleitete nachricht|urspr(?:ü|ue)ngliche nachricht|message transf(?:é|e)r(?:é|e)|mensaje reenviado|messaggio inoltrato|doorgestuurd bericht)\s*-{2,}#iu', + '#begin forwarded message\s*:#i'] as $pattern) { + if (preg_match($pattern, $html, $m, PREG_OFFSET_CAPTURE)) { + $before = substr($html, 0, $m[0][1]); + $open = $m[0][1]; + if (preg_match_all('#<(?!/)(?:div|p|span|blockquote|font|td|b|strong)\b#i', $before, $tags, PREG_OFFSET_CAPTURE)) { + $open = end($tags[0])[1]; + } + $starts[] = $open; + } + } + sort($starts); + foreach (array_unique($starts) as $start) { + if (stripos(html_entity_decode(strip_tags(substr($html, $start)), ENT_QUOTES | ENT_HTML5, 'UTF-8'), $sender_email) !== false) { + // The line Outlook draws above it goes with it, not at the foot of the agent's note + if (preg_match('#
]*>\s*$#i', substr($html, 0, $start), $hr, PREG_OFFSET_CAPTURE)) { + $start = $hr[0][1]; + } + return $start; + } + } + return -1; +} + +/** Whether a piece of an email's HTML says anything - not only line breaks, spaces and empty tags. */ +function ticketMailForwardSaysSomething($html) { + $text = html_entity_decode(strip_tags(preg_replace('#<(script|style|head)\b[^>]*>.*?\1>#is', '', (string) $html)), ENT_QUOTES | ENT_HTML5, 'UTF-8'); + return trim(str_replace("\xC2\xA0", ' ', $text)) !== '' || preg_match('#who + * it is from, 'subject' => its own subject, for the ticket, 'html' => it, the ticket's details, 'note' => what the + * agent wrote above it ('' when nothing), 'how' => 'inline' or 'attached', 'attachment' => the attached one's index]. + * Null when nothing in it is forwarded. $subject is the email's own. + */ +function ticketMailForwarded($html, $text, $subject, array $attachments = []) { + $html = (string) $html; + $text = (string) $text; + $forwarded = (bool) preg_match(TICKET_MAIL_FORWARD_ONLY, (string) $subject); + + // Inline: the plain text part first, as the sender's app wrote it, then the HTML read as text + $block = null; + $in_text = false; + if (trim($text) !== '' && ($block = ticketMailForwardBlock($text, $forwarded))) { + $in_text = true; + } elseif ($html !== '') { + $block = ticketMailForwardBlock(ticketMailForwardText($html), $forwarded); + } + if ($block) { + $subject_out = ticketMailForwardSubject($block['subject'] !== '' ? $block['subject'] : $subject); + $split = $html !== '' ? ticketMailForwardHtmlSplit($html, $block['email']) : -1; + if ($split >= 0) { + $note = substr($html, 0, $split); + return ['email' => $block['email'], 'name' => $block['name'], 'subject' => $subject_out, 'html' => substr($html, $split), + 'note' => ticketMailForwardSaysSomething($note) ? $note : '', 'how' => 'inline', 'attachment' => -1]; + } + // No container to split the HTML at - the plain text, split at its header block (or the line above it) + $source = $in_text ? $text : ticketMailForwardText($html); + $lines = explode("\n", str_replace(["\r\n", "\r"], "\n", $source)); + $from_line = $block['marker'] >= 0 ? $block['marker'] : $block['line']; + $note = trim(implode("\n", array_slice($lines, 0, $from_line))); + $original = trim(implode("\n", array_slice($lines, $from_line))); + return ['email' => $block['email'], 'name' => $block['name'], 'subject' => $subject_out, 'html' => nl2br(escapeHtml($original)), + 'note' => $note !== '' ? nl2br(escapeHtml($note)) : '', 'how' => 'inline', 'attachment' => -1]; + } + + // Forwarded as an attachment - Outlook's Forward as Attachment, or an .eml dragged in: one attached email, read + $attached = []; + foreach ($attachments as $index => $attachment) { + $mime = strtolower((string) ($attachment['mime'] ?? '')); + if ($mime === 'message/rfc822' || strtolower(pathinfo((string) ($attachment['name'] ?? ''), PATHINFO_EXTENSION)) === 'eml') { + $attached[] = $index; + } + } + if (count($attached) !== 1 || !class_exists('\ZBateson\MailMimeParser\Message')) { + return null; + } + try { + $inner = \ZBateson\MailMimeParser\Message::from((string) $attachments[$attached[0]]['content'], false); + $from = $inner->getHeader('From'); + $who = $from ? ticketMailForwardAddress(trim(($from->getPersonName() ?? '') . ' <' . ($from->getEmail() ?? '') . '>')) : null; + if (!$who) { + return null; + } + if ($from->getPersonName()) { + $who['name'] = mb_substr(trim((string) $from->getPersonName()), 0, 200); + } + $inner_html = (string) $inner->getHtmlContent(); + $inner_text = (string) $inner->getTextContent(); + $body = $inner_html !== '' ? $inner_html : ($inner_text !== '' ? nl2br(escapeHtml($inner_text)) : ''); + // Its pictures, in it as the email showed them + foreach ($inner->getAllAttachmentParts() as $part) { + $cid = trim((string) $part->getContentId(), '<>'); + $type = strtolower((string) $part->getContentType()); + if ($cid !== '' && str_starts_with($type, 'image/') && $inner_html !== '') { + $body = str_replace(["cid:$cid", "cid:<$cid>"], "data:$type;base64," . base64_encode((string) $part->getBinaryContentStream()), $body); + } + } + } catch (\Throwable $e) { + return null; + } + $note = $html !== '' ? $html : ($text !== '' ? nl2br(escapeHtml($text)) : ''); + return ['email' => $who['email'], 'name' => $who['name'], 'subject' => ticketMailForwardSubject((string) ($inner->getSubject() ?? '') !== '' ? $inner->getSubject() : $subject), + 'html' => $body, 'note' => ticketMailForwardSaysSomething($note) ? $note : '', 'how' => 'attached', 'attachment' => $attached[0]]; +} + +/* + * Whether a forwarded email's sender is a client's - not one of your own addresses, an agent, or someone at your own + * domain: an agent forwarding a colleague's email, or a notice ITFlow sent, is theirs as before. + */ +function ticketMailForwardFromClient($email) { + $email = strtolower(trim((string) $email)); + return $email !== '' && !emailOwnAddress($email) && !emailOwnDomain($email) && !ticketMailForwardAgent($email); +} + +/* + * The agent's note on a ticket raised from an email they forwarded - what they wrote above it, as an internal note by + * them - and the ticket's history saying who forwarded it. $note is HTML ('' when they wrote nothing). + */ +function ticketMailForwardNote($ticket_id, array $agent, $note, $from_email) { + global $mysqli; + $ticket_id = intval($ticket_id); + if (!$ticket_id) { + return 0; + } + $note_id = 0; + $note = trim((string) $note); + if ($note !== '') { + $note = preg_replace(['#]*>.*?#is', '/]*>/i', '/]*>/i', '/<\/?(html|head|body)[^>]*>/i'], '', $note) ?? $note; + mysqli_query($mysqli, "INSERT INTO ticket_replies SET ticket_reply = '" . mysqli_real_escape_string($mysqli, $note) . "', ticket_reply_type = 'Internal', + ticket_reply_time_worked = '00:00:00', ticket_reply_by = " . intval($agent['user_id']) . ", ticket_reply_ticket_id = $ticket_id"); + $note_id = intval(mysqli_insert_id($mysqli)); + } + logTicketHistory($ticket_id, escapeSql("Raised from an email from $from_email that " . $agent['user_name'] . " forwarded to the ticket mailbox" . ($note_id ? ' - their note is on the ticket' : ''))); + return $note_id; +} diff --git a/functions/ticket_mail_try.php b/functions/ticket_mail_try.php index a3bf7df88..60b74c70f 100644 --- a/functions/ticket_mail_try.php +++ b/functions/ticket_mail_try.php @@ -19,6 +19,8 @@ * ticket was given (ticketMailSubjectTicket()) - a reply on that ticket, * as whoever sent it is to the ticket (its contact or another of the * client's, an agent, a CC, or a stranger), or a closed one turned away; + * - a client's email an agent forwarded is read as from the client it forwards (ticketMailForwarded()) - only + * said here, where there is no email to read; * 3. a subject almost the same as an open ticket of the sender's client from * the last 7 days - a reply on that ticket from its contact or a CC, and * from anyone else at the client a new ticket linked to it as related; @@ -113,6 +115,12 @@ function ticketMailTry($from_email, $subject, $auto_reply = false) { ? 'No - there is no ticket with the number in brackets, so it carries on' : 'No - it would be [' . $config_ticket_prefix . '123] somewhere in it']; + // An agent's: a client's email they forward is read as from the client - said, as there is no email here to read + if ($forward_agent = ticketMailForwardAgent($from_email)) { + $steps[] = ['From one of your agents?', 'Yes - ' . $forward_agent['user_name'] . '. A client\'s email they forward to the mailbox is read as from the client: its sender, subject and text go the steps below,' + . ' and what ' . $forward_agent['user_name'] . ' wrote above it is their internal note on the ticket. One from someone who isn\'t a client\'s is a ticket with no client even when tickets from unknown senders are off, and they aren\'t answered or copied in. Anything else from them goes on as from them']; + } + // The sender: a contact - at the client whose domain it is, when they are one at more than one - or the client whose domain it is $picked = ticketMailSenderContact($from_email, $domain); $contact = $picked['contact'];