From 42ea7e58a59020c015db115897c07cbacf4745b3 Mon Sep 17 00:00:00 2001 From: johnnyq Date: Mon, 30 Nov 2026 13:08:24 -0500 Subject: [PATCH] Keep a ticket's emails in one conversation: every client email about a ticket has the subject [TCK-123] and its subject and carries Message-ID, In-Reply-To and References, kept per ticket in ticket_mail_threads, and the email parser finds a reply's ticket by those headers first, then by the number in brackets with the prefix that ticket was given; one email goes to the contact with the watchers and colleagues copied in, switchable in Admin, Settings, Tickets; a client's reply by email, text or portal is passed on to the people following the ticket who weren't on it, by email only when it answers one of the ticket's emails; others in To and Cc on a client's or watcher's email become watchers, never your own domain or agents; the same email twice makes one ticket and a merged ticket's replies go to the ticket it went into; database 4.2.6; 26.12.3 changelog entries --- CHANGELOG.md | 14 +- admin/database_updates/4.2.6.php | 53 +++ admin/mail_preview.php | 4 +- admin/mail_queue.php | 7 +- .../mail_queue/mail_queue_message_view.php | 8 +- admin/post/settings_ticket.php | 9 +- admin/settings_mail.php | 3 + admin/settings_ticket.php | 11 +- agent/post/ticket.php | 8 +- agent/ticket.php | 2 +- api/v1/tickets/create.php | 2 +- client/post.php | 3 + cron/mail_queue.php | 42 ++- cron/ticket_email_parser.php | 142 +++++--- db.sql | 25 ++ functions.php | 1 + functions/app.php | 9 +- functions/email.php | 82 ++++- functions/email_preview.php | 26 +- functions/mail_queue.php | 38 +++ functions/settings.php | 4 + functions/sms.php | 4 + functions/ticket.php | 123 ++++--- functions/ticket_mail_thread.php | 302 ++++++++++++++++++ functions/ticket_mail_try.php | 45 +-- functions/ticket_reply_recipients.php | 23 +- functions/ticket_status.php | 3 +- 27 files changed, 831 insertions(+), 162 deletions(-) create mode 100644 admin/database_updates/4.2.6.php create mode 100644 functions/ticket_mail_thread.php diff --git a/CHANGELOG.md b/CHANGELOG.md index d34a0dca1..e8c63854b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,7 +6,7 @@ This file documents all notable changes made to ITFlow. ### Upgrading to 26.12.3 -Update from Maintenance > Update as usual - this release has four database changes: 4.2.2 adds a table for passkeys and a setting to turn them on or off, 4.2.3 lets a document keep the Markdown it was written in, 4.2.4 lets a ticket keep its pictures as files, and 4.2.5 adds identity providers. The client portal's Microsoft 365 single sign-on becomes the first identity provider, for client contacts, and keeps its redirect address, so nothing changes in Microsoft Entra. Nothing else is required: passkeys are on, and no one has one until they add it. Pictures already inside tickets move to files in the background afterwards - the new Ticket Pictures job in Maintenance > Cron does a batch a minute, so an install with years of emailed screenshots may take a while, and tickets work as usual meanwhile. A passkey is made for your ITFlow's address (the one in config.php) and only works there, over HTTPS - if you move ITFlow to a new address, everyone adds theirs again. +Update from Maintenance > Update as usual - this release has five database changes: 4.2.2 adds a table for passkeys and a setting to turn them on or off, 4.2.3 lets a document keep the Markdown it was written in, 4.2.4 lets a ticket keep its pictures as files, 4.2.5 adds identity providers, and 4.2.6 keeps each ticket's email conversation together. The client portal's Microsoft 365 single sign-on becomes the first identity provider, for client contacts, and keeps its redirect address, so nothing changes in Microsoft Entra. Nothing else is required: passkeys are on, and no one has one until they add it. Pictures already inside tickets move to files in the background afterwards - the new Ticket Pictures job in Maintenance > Cron does a batch a minute, so an install with years of emailed screenshots may take a while, and tickets work as usual meanwhile. A passkey is made for your ITFlow's address (the one in config.php) and only works there, over HTTPS - if you move ITFlow to a new address, everyone adds theirs again. Emails about a ticket now go to its contact with the watchers copied in, rather than one each - Admin > Settings > Tickets has the switch, under Emails about a ticket. ### New Features & Updates @@ -49,6 +49,11 @@ Update from Maintenance > Update as usual - this release has four database chang - A recurring expense has Expense, and Client & reference, like a one-off expense. - The icon pickers in the tag, category, link and asset type windows show three rows and scroll, starting on the icon picked. - Invoicing a ticket on a new invoice gives the invoice the ticket's number and subject as its scope, without asking - change it on the invoice. Making a quote from a ticket has a smaller description box. +- A ticket's emails stay together as one conversation in the client's inbox. Each has the same subject from the first to the last - its number in brackets, then its subject: [TCK-123] Printer offline - where it used to change with each email ("Ticket update - ...", "Ticket resolved - ... | (pending closure)"), and each carries the headers mail programs keep a conversation together by. A reply finds its ticket by those headers first, so one whose subject was changed still lands on it, and so does a reply to all on the client's first email, sent before anyone had the ticket's number. +- One email, with the watchers copied in: an email about a ticket goes to its contact with the watchers, and the colleagues who asked for every update, copied in (Cc), so they see who else has it and a reply to all reaches everyone. The To line on an email reply works the same way - the contact in To, everyone else copied in. Switch it off under Admin > Settings > Tickets, Emails about a ticket, for an email each as before. +- A client's reply goes on to the watchers: when the client replies by email, text or in the portal, the people an agent's reply would go to get it too, with its files - not anyone it was already to or copied to. By email, only a reply to one of the ticket's emails is passed on, as anyone can put a ticket number in a subject. It can be switched off in the same place. +- Whoever the client also emails, or copies in, follows the ticket: the other people in To and Cc on the email that raises a ticket, and on a reply from the client or a watcher, become its watchers - never your own addresses, anyone else at your domain or your agents. The ticket's history says who. +- An email that lands in the support mailbox twice - sent to two of your addresses that both go to it - makes one ticket. ### Bug Fixes @@ -62,6 +67,8 @@ Update from Maintenance > Update as usual - this release has four database chang - Email new tickets to (Admin > Settings > Tickets) can't be the mailbox ITFlow reads tickets from any more: each notice could come back in as a new email and raise another ticket, whose notice raised another, every minute. One saved before isn't emailed. - Email someone opened before ITFlow got to it - Outlook marks an email read as soon as it shows it - is made a ticket now, when it came in the last hour. It used to stay in the mailbox for good. Read email older than that, such as what was there when the mailbox was connected, is left alone. - An email to a domain whose mail server couldn't be found is tried again like any other failed email, and a domain with no MX record that takes mail at its own address is found. One failed lookup used to fail the email for good. +- After the ticket prefix was changed (Admin > Settings > Tickets), a reply to an older ticket - its number with the old prefix - became a new ticket. It finds its ticket now, and so does a number written with zeros in front. +- A reply to an email of a ticket that was merged into another goes on the ticket it was merged into, rather than being turned away as a reply to a closed ticket. ### Developer Updates @@ -100,6 +107,11 @@ Update from Maintenance > Update as usual - this release has four database chang - Mail loop: emailOwnAddresses() (functions/email.php - the From mailboxes and config_imap_username) is skipped by cron/ticket_email_parser.php before anything else (moved to the ITFlow folder, App Logs info), left out of CC watchers there and in ticketAddWatchers(), filtered out of ticketMailSend()'s recipients and ticketColleagueRecipients(), and not offered in the reply To line (ticketReplyRecipients()). emailReadMailbox() - the Receiving username or the ticket mailbox, while email-to-ticket is on - is refused for config_ticket_new_ticket_notification_email and skipped by ticketMailNewTicketAddress(). Try an Email (functions/ticket_mail_try.php) asks the same first. - Read mail: the parser's unseen query is followed, when it has room, by seen() unflagged() since(yesterday) newest(), kept when the Date header is within $read_mail_minutes (60). MailGraphMessageQuery (functions/mail_graph_mailbox.php) now honours seen(), unseen(), since() and newest() - isRead eq true, receivedDateTime desc. - cron/mail_queue.php: mailQueueDomainProblem() (functions/mail_queue.php - MX, else A or AAAA, once a domain a run) is a normal failed try in the send path (attempts 1, not 99) and is asked again in the retry path before each send; --no-mx-validation still skips it. +- functions/ticket_mail_thread.php, database 4.2.6: ticket_mail_threads keeps each Message-ID of a ticket's emails - the client's, and ITFlow's (mail_thread_ours 1, itflow..@). ticketMailHeaders() gives a queued email its Message-ID, In-Reply-To (the latest kept) and References (the first and the latest, 10 at most). In cron/ticket_email_parser.php, ticketMailHeaderTicket() matches In-Reply-To, then References latest first, before the subject; ticketMailSubjectTicket() matches [] against each ticket's own ticket_prefix, trying each split of the trailing digits, in place of the config prefix regex there, in the bounce path and in Try an Email; ticketMailIdTicket() skips an email whose Message-ID is kept already. ticketMergeInto() moves the merged ticket's rows; deleting a ticket deletes them (ON DELETE CASCADE). 4.2.6 also indexes tickets.ticket_number, which every email with a number in brackets is looked up by. +- emailQueue() takes together (one email to the first recipient, the rest in email_queue.email_cc as JSON, with together_footnote) and thread (a ticket id, with answering). addToMailQueue() writes email_cc and email_headers as JSON with mysqli_real_escape_string(), as escapeSql() strips <...>. sendQueueEmail() in cron/mail_queue.php takes them: addCC(), MessageID, and addCustomHeader() for MAIL_QUEUE_HEADERS only (mailQueueHeaders() - Message-ID, In-Reply-To, References, each a list of ). Development mode names the Cc in the subject. A large Microsoft Graph email sent as a draft (mailGraphSendLarge()) goes without In-Reply-To and References. +- ticketMailSend($ticket_id, $email, $opts) no longer takes a subject: ticketEmailSubject() is the subject of every client email about a ticket, ticketMailWatchersAdded(), ticketMailColleaguesNew() and ticketMailClosedReply($ticket_id, $from_email, $answering) included - not the task approval email. ticketMailCreated() lost its $subject_prefix argument. Its recipients carry a group, and the contact goes first. ticketReplyEmailed() and ticketReplyEmailStates() count email_cc; ticketReplyRecipientsPick() takes $remember (false keeps nothing in ticket_mail_choices) and returns each one's group. +- ticketMailRelayClientReply() (client/post.php, functions/sms.php, and the parser for a reply matched by its headers) sends ticketEmailContent()'s client_reply kind to the To line's people (ticketReplyRecipients() send) less the author, the email's From, To and Cc, and agents. ticketMailCopiedWatchers() (the parser's addTicket(), and addReply() unless from a stranger or an agent) adds To and Cc less ITFlow's own addresses, emailOwnDomain() (functions/email.php - their domains, not EMAIL_PUBLIC_DOMAINS), agents and no-reply addresses. addReply() takes a ticket id and $email (message_id, copied, had, threaded). settings.config_ticket_email_copy and config_ticket_email_relay, both 1 (ticketMailSettings()). +- Admin > Mail Queue shows and searches email_cc, the email's window has a Cc line, and Admin > Mail previews show one (admin/mail_preview.php cc) and have a Client's reply, passed on. ## [26.12.2] diff --git a/admin/database_updates/4.2.6.php b/admin/database_updates/4.2.6.php new file mode 100644 index 000000000..8e03d8986 --- /dev/null +++ b/admin/database_updates/4.2.6.php @@ -0,0 +1,53 @@ + Mail > Previews, as JSON - its subject, who it is - * from and to, and its HTML - made on sample records that are thrown away + * from, to and copied to, and its HTML - made on sample records that are thrown away * again (emailPreview(), functions/email_preview.php). */ @@ -41,6 +41,8 @@ echo json_encode([ 'subject' => $email['subject'] ?? '', 'from' => $email ? ($email['from'] !== '' ? $person($email['from_name'], $email['from']) : 'No address yet - set it under From Addresses') : '', 'to' => $email ? $person($email['to_name'], $email['to']) : '', + // Copied in on it - a ticket's watchers, on one email with its contact (emailQueue()'s together) + 'cc' => $email ? array_map(function ($copied) use ($person) { return $person($copied['name'], $copied['email']); }, $email['cc'] ?? []) : [], 'also' => array_values(array_unique($others)), 'calendar' => !empty($email['cal_str']), 'html' => $email['html'] ?? '', diff --git a/admin/mail_queue.php b/admin/mail_queue.php index aa938755e..d2648502d 100644 --- a/admin/mail_queue.php +++ b/admin/mail_queue.php @@ -35,10 +35,10 @@ if (!isset($sortable_columns[$sort])) { } $search = "(email_id LIKE '%$q%' OR email_from LIKE '%$q%' OR email_from_name LIKE '%$q%' OR email_recipient LIKE '%$q%' OR email_recipient_name LIKE '%$q%' OR email_subject LIKE '%$q%'" - . (mailQueueHasError() ? " OR email_error LIKE '%$q%'" : '') . ") + . (mailQueueHasError() ? " OR email_error LIKE '%$q%'" : '') . (ticketMailThreadReady() ? " OR email_cc LIKE '%$q%'" : '') . ") AND DATE(email_queued_at) BETWEEN '$dtf' AND '$dtt'"; -$sql = mysqli_query($mysqli, "SELECT SQL_CALC_FOUND_ROWS email_id, email_status, email_attempts, email_from, email_from_name, email_recipient, email_recipient_name, +$sql = mysqli_query($mysqli, "SELECT SQL_CALC_FOUND_ROWS email_id, email_status, email_attempts, email_from, email_from_name, email_recipient, email_recipient_name, " . (ticketMailThreadReady() ? 'email_cc' : "'' AS email_cc") . ", email_subject, email_queued_at, email_failed_at, email_sent_at, " . mailQueueErrorColumn() . ", email_attachments, COALESCE(email_cal_str, '') <> '' AS has_invite, email_content = '' AS email_cleared FROM email_queue WHERE $search AND {$tabs[$show][2]} @@ -203,6 +203,9 @@ $filtered_dates = isset($_GET['dtf']) && $_GET['dtf'] !== '' && $_GET['dtf'] !==
+ +
+ copied in
+
diff --git a/admin/modals/mail_queue/mail_queue_message_view.php b/admin/modals/mail_queue/mail_queue_message_view.php index dfd0c87a6..84cb75d32 100644 --- a/admin/modals/mail_queue/mail_queue_message_view.php +++ b/admin/modals/mail_queue/mail_queue_message_view.php @@ -2,7 +2,7 @@ /* * Maintenance > Mail Queue - one email: where it stands, and why it last - * failed or who cancelled it; who it is to and from; when it was queued, + * failed or who cancelled it; who it is to, copied to and from; when it was queued, * tried, sent or given up on; its attachments and calendar file; and what it * says - unless it carried a link or code that opens something, cleared once it * has gone (functions/mail_queue.php). The @@ -14,7 +14,7 @@ require_once '../../includes/modal_header.php'; $email_id = intval($_GET['id'] ?? 0); -$row = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT email_id, email_status, email_attempts, email_from, email_from_name, email_recipient, email_recipient_name, +$row = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT email_id, email_status, email_attempts, email_from, email_from_name, email_recipient, email_recipient_name, " . (ticketMailThreadReady() ? 'email_cc' : "'' AS email_cc") . ", email_subject, email_content, email_content = '' AS email_cleared, email_cal_str, email_attachments, email_queued_at, email_failed_at, email_sent_at, " . mailQueueErrorColumn() . " FROM email_queue WHERE email_id = $email_id LIMIT 1")); @@ -88,6 +88,10 @@ if (!$row) { ?>
To
+ +
Cc
+
+
From
Queued
diff --git a/admin/post/settings_ticket.php b/admin/post/settings_ticket.php index 7670b6e74..c04bfb97a 100644 --- a/admin/post/settings_ticket.php +++ b/admin/post/settings_ticket.php @@ -2,7 +2,7 @@ /* * Admin > Settings > Tickets (admin/settings_ticket.php): - * edit_ticket_settings saves the numbering, email and text to ticket, who hears of a + * edit_ticket_settings saves the numbering, email to ticket, the emails about a ticket, text to ticket, who hears of a * new ticket and whether AI triages it, whether the first agent to reply to an * unassigned ticket is assigned it, what a quick ticket starts with, the timer * and billing, the messages to clients, closing and the tickets page. A next @@ -23,6 +23,7 @@ if (isset($_POST['edit_ticket_settings'])) { 'config_ticket_new_ticket_notification_email', 'config_ticket_timer_autostart', 'config_ticket_default_billable', 'config_ticket_autoclose_hours', 'config_ticket_default_view', 'config_ticket_ordering', 'config_ticket_moving_columns'], aiTriageReady() ? ['config_ticket_ai_triage'] : [], version_compare((string) CURRENT_DATABASE_VERSION, '4.0.9', '>=') ? ['config_ticket_reply_assigns'] : [], + ticketMailThreadReady() ? ['config_ticket_email_copy', 'config_ticket_email_relay'] : [], settingsColumnExists($mysqli, 'config_ticket_sms_parse') ? ['config_ticket_sms_parse', 'config_ticket_sms_unknown_senders', 'config_ticket_sms_acknowledge'] : [], ticketStatusReplyReady() ? ['config_ticket_assigned_message'] : [], ticketNoResponseReady() ? ['config_ticket_no_response_message'] : [], quickTicketReady() ? ['config_quick_ticket_on', 'config_quick_ticket_assign', 'config_quick_ticket_status', 'config_quick_ticket_priority', 'config_quick_ticket_category', @@ -47,6 +48,12 @@ if (isset($_POST['edit_ticket_settings'])) { if (array_key_exists('config_ticket_reply_assigns', $before)) { $after['config_ticket_reply_assigns'] = empty($_POST['config_ticket_reply_assigns']) ? 0 : 1; } + // Emails about a ticket - once the database has them + if (array_key_exists('config_ticket_email_copy', $before)) { + foreach (['config_ticket_email_copy', 'config_ticket_email_relay'] as $switch) { + $after[$switch] = empty($_POST[$switch]) ? 0 : 1; + } + } // Text to ticket - once the database has it if (array_key_exists('config_ticket_sms_parse', $before)) { foreach (['config_ticket_sms_parse', 'config_ticket_sms_unknown_senders', 'config_ticket_sms_acknowledge'] as $switch) { diff --git a/admin/settings_mail.php b/admin/settings_mail.php index 931f7059f..d38af53ed 100644 --- a/admin/settings_mail.php +++ b/admin/settings_mail.php @@ -463,6 +463,7 @@ if (!$config_module_enable_ticketing) {
From
To
+
Cc
Calendar file attached
@@ -540,6 +541,8 @@ if (!$config_module_enable_ticketing) { card.querySelector('[data-preview-from]').textContent = data.from || '-'; card.querySelector('[data-preview-to]').textContent = data.to || data.to_who || '-'; card.querySelector('[data-preview-also]').textContent = data.also && data.also.length ? '(and ' + data.also.join(', ') + ')' : ''; + card.querySelector('[data-preview-cc]').textContent = data.cc && data.cc.length ? data.cc.join(', ') : ''; + card.querySelector('[data-preview-cc-line]').classList.toggle('d-none', !(data.cc && data.cc.length)); card.querySelector('[data-preview-when]').textContent = 'Sent when: ' + (data.when || ''); card.querySelector('[data-preview-calendar]').classList.toggle('d-none', !data.calendar); var error = card.querySelector('[data-preview-error]'); diff --git a/admin/settings_ticket.php b/admin/settings_ticket.php index 69b2a58e0..49ec679b2 100644 --- a/admin/settings_ticket.php +++ b/admin/settings_ticket.php @@ -2,7 +2,8 @@ /* * Admin > Settings > Tickets - how tickets are numbered, made from email - * (cron/ticket_email_parser.php, reading the mailbox in Mail > Receiving) and + * (cron/ticket_email_parser.php, reading the mailbox in Mail > Receiving), who + * the emails about one go to (functions/ticket_mail_thread.php), made * from texts (functions/sms.php, once texting is set up in Text Messaging), * timed and billed, who hears about new ones, when resolved ones close, and * how the tickets page opens, and whether AI triages new tickets @@ -41,6 +42,14 @@ echo settingsPageStart('ticket');
+ + [' . escapeHtml($config_ticket_prefix) . '123] Subject, the same from the first to the last, and carries the headers a mail program keeps a conversation together by - so they stay together in the client\'s inbox, and a reply finds its ticket even when its subject was changed.') ?> + 'An email about a ticket goes to its contact with the watchers, and the colleagues who asked for every update, copied in (Cc) - everyone sees who else has it, and a reply to all reaches them. Off, each gets an email of their own.']) ?> + 'When the client replies - by email, text or in the portal - the people an agent\'s reply would go to get it too, with its files, unless it was already to them. By email, only a reply to one of the ticket\'s emails: anyone can put a ticket number in a subject.']) ?> + + + Text Messaging.') ?> diff --git a/agent/post/ticket.php b/agent/post/ticket.php index b737d383d..9d0ba8528 100644 --- a/agent/post/ticket.php +++ b/agent/post/ticket.php @@ -167,7 +167,7 @@ if (isset($_POST['add_ticket'])) { // E-mail the client and the watchers - a quick ticket's contact only when its setting says so if (intval($config_ticket_client_general_notifications) === 1) { if (!$quick_ticket || quickTicketSettings()['email_client']) { - ticketMailCreated($ticket_id, 'Ticket Created', $emailable_attachments['send']); + ticketMailCreated($ticket_id, $emailable_attachments['send']); } ticketMailColleaguesNew($ticket_id); } @@ -377,7 +377,7 @@ if (isset($_POST['edit_ticket'])) { // Let the contact know about it, when asked if ($notify && $contact_id && empty($row['ticket_closed_at'])) { - ticketMailCreated($ticket_id, 'Ticket Created -', [], false); + ticketMailCreated($ticket_id, [], false); } // Custom action/notif handler @@ -442,7 +442,7 @@ if (isset($_POST['edit_ticket_contact'])) { // Let the new contact know about it, when asked if ($notify && $contact_id && empty($row['ticket_closed_at'])) { - ticketMailCreated($ticket_id, 'Ticket Created -', [], false); + ticketMailCreated($ticket_id, [], false); } triggerCustomAction('ticket_update', $ticket_id); @@ -1572,7 +1572,7 @@ if (isset($_POST['split_ticket_reply'])) { // The client is told about the new ticket, as for any other if (intval($config_ticket_client_general_notifications) === 1) { - ticketMailCreated($new_id, 'Ticket Created', []); + ticketMailCreated($new_id, []); } triggerCustomAction('ticket_create', $new_id); if ($assigned_to) { diff --git a/agent/ticket.php b/agent/ticket.php index d0f227841..d8115a637 100644 --- a/agent/ticket.php +++ b/agent/ticket.php @@ -939,7 +939,7 @@ if (isset($_GET['ticket_id'])) { -
Who's in To is kept for this ticket - its next email reply starts with the same people.
+
Who's in To is kept for this ticket - its next email reply starts with the same people.
diff --git a/api/v1/tickets/create.php b/api/v1/tickets/create.php index 8ffda946e..2dc95e05c 100644 --- a/api/v1/tickets/create.php +++ b/api/v1/tickets/create.php @@ -157,7 +157,7 @@ if (!empty($subject) && $client_exists) { // Who hears about it, as when it's raised in ITFlow - the contact too, unless it's for the team only if ($notify_team) { if ($notify && intval($config_ticket_client_general_notifications) === 1) { - ticketMailCreated($insert_id, 'Ticket Created'); + ticketMailCreated($insert_id); ticketMailColleaguesNew($insert_id); } ticketMailNewTicketAddress($insert_id, 'api'); diff --git a/client/post.php b/client/post.php index 65e72f12a..1830bd6c3 100644 --- a/client/post.php +++ b/client/post.php @@ -267,6 +267,9 @@ if (isset($_POST['add_ticket_comment'])) { // Store any attached files against this reply saveTicketAttachments($ticket_id, $ticket_reply_id, 'file'); + // On to the people following the ticket, with its files - as an agent's reply goes to them (functions/ticket_mail_thread.php) + ticketMailRelayClientReply($ticket_id, $ticket_reply_id, stripslashes($session_contact_name), stripslashes($session_contact_email)); + // Custom action/notif handler triggerCustomAction('ticket_reply_client', $ticket_id); diff --git a/cron/mail_queue.php b/cron/mail_queue.php index ae1d338fe..3d4328847 100644 --- a/cron/mail_queue.php +++ b/cron/mail_queue.php @@ -220,13 +220,20 @@ function sendQueueEmail( string $oauth_tenant_id, string $oauth_refresh_token, string $oauth_access_token, - string $oauth_access_token_expires_at + string $oauth_access_token_expires_at, + string $cc_json = '', + string $headers_json = '' ) { - // Development mode: to the test inbox instead, its real recipient at the front of the subject (functions/dev_mode.php) + // The people copied in, and the headers that keep a ticket's conversation together (functions/mail_queue.php) + $cc = mailQueueCc($cc_json); + $headers = mailQueueHeaders($headers_json); + + // Development mode: to the test inbox instead, its real recipients at the front of the subject (functions/dev_mode.php) if (devModeOn()) { - $subject = '[DEV to ' . $to_email . '] ' . $subject; + $subject = '[DEV to ' . $to_email . ($cc ? ', cc ' . implode(', ', array_column($cc, 'email')) : '') . '] ' . $subject; $to_email = devModeMailTo(); $to_name = ''; + $cc = []; } // Google and Microsoft each expose exactly one XOAUTH2 SMTP endpoint, so the @@ -305,10 +312,24 @@ function sendQueueEmail( // Recipients & content $mail->setFrom($from_email, $from_name); $mail->addAddress($to_email, $to_name); + foreach ($cc as $person) { + $mail->addCC($person['email'], $person['name']); + } $mail->isHTML(true); $mail->Subject = $subject; $mail->Body = $html_body; + // Its own Message-ID, and the emails it answers - a mail program keeps a ticket's emails together by them, and a + // reply names them back, so the email parser finds its ticket whatever its subject says. A big email sent through + // Microsoft Graph as a draft goes without the last two (mailGraphSendLarge()) - its subject still finds the ticket + foreach ($headers as $name => $value) { + if ($name === 'Message-ID') { + $mail->MessageID = $value; + } else { + $mail->addCustomHeader($name, $value); + } + } + // A meeting invitation or cancellation goes in as its own text/calendar part // beside the HTML - the way calendar apps send them, and the only way Outlook // shows one as a meeting rather than a file. Only a meeting does: one with an @@ -404,8 +425,11 @@ if ($orphaned_emails > 0) { /** ======================================================================= * SEND: status = 0 (Queued) * ======================================================================= */ +// The copied in and the headers - once the 4.2.6 update has made their columns +$thread_columns = ticketMailThreadReady() ? 'email_cc, email_headers' : "'' AS email_cc, '' AS email_headers"; + $sql_queue = mysqli_query($mysqli, "SELECT email_attachments, email_cal_str, email_content, email_from, email_from_name, email_id, - email_recipient, email_recipient_name, email_subject FROM email_queue WHERE email_status = 0 AND email_queued_at <= NOW()"); + email_recipient, email_recipient_name, email_subject, $thread_columns FROM email_queue WHERE email_status = 0 AND email_queued_at <= NOW()"); if (mysqli_num_rows($sql_queue) > 0) { while ($rowq = mysqli_fetch_assoc($sql_queue)) { @@ -480,7 +504,9 @@ if (mysqli_num_rows($sql_queue) > 0) { (string)$config_mail_oauth_tenant_id, (string)$config_mail_oauth_refresh_token, (string)$config_mail_oauth_access_token, - (string)$config_mail_oauth_access_token_expires_at + (string)$config_mail_oauth_access_token_expires_at, + (string)$rowq['email_cc'], + (string)$rowq['email_headers'] ); // Sent - one with a link or code that opens something is cleared now (mailQueueSentSql()) @@ -511,7 +537,7 @@ if (mysqli_num_rows($sql_queue) > 0) { $sql_failed_queue = mysqli_query( $mysqli, "SELECT email_attachments, email_attempts, email_cal_str, email_content, email_from, - email_from_name, email_id, email_recipient, email_recipient_name, email_subject FROM email_queue + email_from_name, email_id, email_recipient, email_recipient_name, email_subject, $thread_columns FROM email_queue WHERE email_status = 2 AND email_attempts < " . MAIL_QUEUE_TRIES . " AND email_failed_at <= NOW() - INTERVAL " . MAIL_QUEUE_RETRY_MINUTES . " MINUTE" @@ -567,7 +593,9 @@ if (mysqli_num_rows($sql_failed_queue) > 0) { (string)$config_mail_oauth_tenant_id, (string)$config_mail_oauth_refresh_token, (string)$config_mail_oauth_access_token, - (string)$config_mail_oauth_access_token_expires_at + (string)$config_mail_oauth_access_token_expires_at, + (string)$rowf['email_cc'], + (string)$rowf['email_headers'] ); // Sent - one with a link or code that opens something is cleared now (mailQueueSentSql()) diff --git a/cron/ticket_email_parser.php b/cron/ticket_email_parser.php index 8503a4704..50e7f8103 100644 --- a/cron/ticket_email_parser.php +++ b/cron/ticket_email_parser.php @@ -75,7 +75,12 @@ $read_mail_minutes = 60; // Mail someone opened before this got to it /** ------------------------------------------------------------------ * Ticket / Reply helpers (unchanged) * ------------------------------------------------------------------ */ -function addTicket($contact_id, $contact_name, $contact_email, $client_id, $date, $subject, $message, $attachments, $original_message_file, $ccs) { +/* + * A new ticket from an email. $copied - the people it was also to or copied to, made its watchers + * (ticketMailCopiedWatchers()); $message_id its Message-ID, kept with the ticket so a reply to it - + * or to all on it, before the ticket's number was ever sent - finds it (functions/ticket_mail_thread.php). + */ +function addTicket($contact_id, $contact_name, $contact_email, $client_id, $date, $subject, $message, $attachments, $original_message_file, $copied, $message_id = '') { global $mysqli, $config_app_name, $company_name, $company_phone, $config_ticket_prefix, $config_ticket_client_general_notifications, $config_base_url, $config_ticket_from_name, $config_ticket_from_email, $config_ticket_default_billable, $allowed_extensions; $bad_pattern = "/do[\W_]*not[\W_]*reply|no[\W_]*reply/i"; // Email addresses to ignore @@ -115,6 +120,9 @@ function addTicket($contact_id, $contact_name, $contact_email, $client_id, $date $id = mysqli_insert_id($mysqli); applyTicketSla($id); + // The email it came from is the first in its conversation - the email saying it is a ticket now answers it + ticketMailKeepId($id, $message_id); + // The email's pictures kept as the ticket's files, not inside its text (functions/ticket_pictures.php) ticketPicturesSaveTicket($id); @@ -158,18 +166,13 @@ function addTicket($contact_id, $contact_name, $contact_email, $client_id, $date mysqli_query($mysqli, "INSERT INTO ticket_watchers SET watcher_email = '$contact_email_esc', watcher_ticket_id = $id"); } - // Add CCs as ticket watchers - foreach ($ccs as $cc) { - if (filter_var($cc, FILTER_VALIDATE_EMAIL) && !preg_match($bad_pattern, $cc)) { - $cc_esc = mysqli_real_escape_string($mysqli, $cc); - mysqli_query($mysqli, "INSERT INTO ticket_watchers SET watcher_email = '$cc_esc', watcher_ticket_id = $id"); - } - } + // The people it was also to or copied to are its watchers - not your own addresses or agents (ticketMailCopiedWatchers()) + ticketMailCopiedWatchers($id, $copied, stripslashes($contact_email)); // The sender is told it is a ticket now - unless they asked for replies only (Your account in the client portal) $contact_wants = !$contact_id || ticketContactWantsEmail(getFieldById('contacts', intval($contact_id), 'contact_ticket_emails'), 'created'); if ($config_ticket_client_general_notifications == 1 && !preg_match($bad_pattern, $contact_email) && $contact_wants && ($new = ticketRow($id))) { - ticketMailCreated($id, 'Ticket created -', [], false, 'email', [['email' => stripslashes($contact_email), 'name' => stripslashes($contact_name)]]); + ticketMailCreated($id, [], false, 'email', [['email' => stripslashes($contact_email), 'name' => stripslashes($contact_name)]]); } // The new-ticket address (Admin > Ticket), when there is one @@ -183,7 +186,15 @@ function addTicket($contact_id, $contact_name, $contact_email, $client_id, $date return true; } -function addReply($from_email, $date, $subject, $ticket_number, $message, $attachments, $original_message_file = null) { +/* + * An email on ticket $ticket_id. $email, about the email: + * message_id its Message-ID, kept with the ticket (functions/ticket_mail_thread.php) + * copied the people it was also to or copied to, made watchers when it is from the client or a watcher + * had everyone it was from, to and copied to - a client's reply goes on to the rest (ticketMailRelayClientReply()) + * threaded it answers one of the ticket's emails (its In-Reply-To or References) - only then is a client's + * reply passed on, as anyone can put a ticket number in a subject + */ +function addReply($from_email, $date, $subject, $ticket_id, $message, $attachments, $original_message_file = null, array $email = []) { global $mysqli, $config_app_name, $company_name, $company_phone, $config_ticket_prefix, $config_base_url, $config_ticket_from_name, $config_ticket_from_email, $allowed_extensions; $ticket_reply_type = 'Client'; @@ -214,18 +225,19 @@ function addReply($from_email, $date, $subject, $ticket_number, $message, $attac // 3) Final wrapper $message = "Email from: $from_email at $date:-

$message
"; - $ticket_number_esc = intval($ticket_number); $message_esc = mysqli_real_escape_string($mysqli, $message); $from_email_esc = mysqli_real_escape_string($mysqli, $from_email); - $row = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT ticket_id, ticket_subject, ticket_status, ticket_contact_id, ticket_client_id, contact_email, client_name + $row = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT ticket_id, ticket_prefix, ticket_number, ticket_subject, ticket_status, ticket_contact_id, ticket_client_id, contact_email, client_name FROM tickets LEFT JOIN contacts on tickets.ticket_contact_id = contacts.contact_id LEFT JOIN clients on tickets.ticket_client_id = clients.client_id - WHERE ticket_number = $ticket_number_esc LIMIT 1")); + WHERE ticket_id = " . intval($ticket_id) . " LIMIT 1")); if ($row) { $ticket_id = intval($row['ticket_id']); + // Its own reference, with the prefix it was given - for the logs + $ticket_reference_esc = escapeSql(ticketReference($row)); $ticket_status = escapeSql($row['ticket_status']); $ticket_reply_contact = intval($row['ticket_contact_id']); $ticket_contact_email = escapeSql($row['contact_email']); @@ -237,15 +249,12 @@ function addReply($from_email, $date, $subject, $ticket_number, $message, $attac } if ($ticket_status == 5) { - $config_ticket_prefix_esc = mysqli_real_escape_string($mysqli, $config_ticket_prefix); - $ticket_number_esc2 = mysqli_real_escape_string($mysqli, $ticket_number); - - appNotify("Ticket", "Email parser: $from_email attempted to re-open ticket $config_ticket_prefix_esc$ticket_number_esc2 (ID $ticket_id) - check inbox manually to see email", "/agent/ticket.php?ticket_id=$ticket_id$client_uri", $client_id); + appNotify("Ticket", "Email parser: $from_email attempted to re-open ticket $ticket_reference_esc (ID $ticket_id) - check inbox manually to see email", "/agent/ticket.php?ticket_id=$ticket_id$client_uri", $client_id); // They are told it didn't reach anyone, and how to raise a new one - never a mail server's // own bounce (the pattern new tickets use), whose answer would only bounce again if (!preg_match("/daemon|postmaster|bounce|mta/i", $from_email)) { - ticketMailClosedReply($ticket_id, stripslashes($from_email)); + ticketMailClosedReply($ticket_id, stripslashes($from_email), (string) ($email['message_id'] ?? '')); } return true; } @@ -283,6 +292,9 @@ function addReply($from_email, $date, $subject, $ticket_number, $message, $attac mysqli_query($mysqli, "INSERT INTO ticket_replies SET ticket_reply = '$message_esc', ticket_reply_type = '$ticket_reply_type', ticket_reply_time_worked = '00:00:00', ticket_reply_by = $ticket_reply_contact, ticket_reply_ticket_id = $ticket_id"); $reply_id = mysqli_insert_id($mysqli); + // In the ticket's conversation - the next email about it answers this one (functions/ticket_mail_thread.php) + ticketMailKeepId($ticket_id, (string) ($email['message_id'] ?? '')); + // The email's pictures kept as the ticket's files, not inside the reply (functions/ticket_pictures.php) ticketPicturesSaveReply($reply_id); @@ -307,7 +319,7 @@ function addReply($from_email, $date, $subject, $ticket_number, $message, $attac mysqli_query($mysqli, "INSERT INTO ticket_attachments SET ticket_attachment_name = '$ticket_attachment_name_esc', ticket_attachment_reference_name = '$ticket_attachment_reference_name_esc', ticket_attachment_reply_id = $reply_id, ticket_attachment_ticket_id = $ticket_id"); } else { $ticket_attachment_name_esc = mysqli_real_escape_string($mysqli, $att_name); - logAudit("Ticket", "Edit", "Email parser: Blocked attachment $ticket_attachment_name_esc from Client contact $from_email_esc for ticket $config_ticket_prefix$ticket_number_esc", $client_id, $ticket_id); + logAudit("Ticket", "Edit", "Email parser: Blocked attachment $ticket_attachment_name_esc from Client contact $from_email_esc for ticket $ticket_reference_esc", $client_id, $ticket_id); } } @@ -322,10 +334,16 @@ function addReply($from_email, $date, $subject, $ticket_number, $message, $attac if ($agent_reply) { logTicketHistory($ticket_id, "$from_email_esc (an agent) emailed - added as their internal note"); - logAudit("Ticket", "Edit", "Email parser: Agent $from_email_esc added an internal note to ticket $config_ticket_prefix$ticket_number_esc ($subject)", $client_id, $ticket_id); + logAudit("Ticket", "Edit", "Email parser: Agent $from_email_esc added an internal note to ticket $ticket_reference_esc ($subject)", $client_id, $ticket_id); return true; } + // The people the client or a watcher also wrote to, or copied in, follow the ticket from now on - as + // they would have in a conversation by email. Not a stranger's: anyone can put a number in a subject + if (!$stranger && ($watching = ticketMailCopiedWatchers($ticket_id, (array) ($email['copied'] ?? []), stripslashes($from_email)))) { + logTicketHistory($ticket_id, escapeSql(implode(', ', $watching)) . (count($watching) === 1 ? ' is' : ' are') . " watching now - copied in on an email from $from_email_esc"); + } + // The agent it is assigned to, with what they wrote - a stranger's as plain text $replied_by = intval($ticket_reply_contact) ? (string) getFieldById('contacts', intval($ticket_reply_contact), 'contact_name') : ''; $mail_reply = (string) getFieldById('ticket_replies', $reply_id, 'ticket_reply'); @@ -336,10 +354,18 @@ function addReply($from_email, $date, $subject, $ticket_number, $message, $attac if ($stranger) { logTicketHistory($ticket_id, "$from_email_esc (not a contact, watcher or agent) emailed - kept as an internal note, the ticket was not reopened"); - logAudit("Ticket", "Edit", "Email parser: $from_email_esc (not a contact, watcher or agent) emailed ticket $config_ticket_prefix$ticket_number_esc ($subject) - kept as an internal note", $client_id, $ticket_id); + logAudit("Ticket", "Edit", "Email parser: $from_email_esc (not a contact, watcher or agent) emailed ticket $ticket_reference_esc ($subject) - kept as an internal note", $client_id, $ticket_id); return true; } + // A client's reply goes on to the people following the ticket who weren't on the email - only one that answers an + // email of the ticket's: a ticket number in a subject is all a forged email needs, and this would carry its words + // to them from your own mailbox (ticketMailRelayClientReply()) + if ($ticket_reply_type === 'Client' && !empty($email['threaded'])) { + ticketMailRelayClientReply($ticket_id, $reply_id, $replied_by !== '' ? $replied_by : stripslashes($from_email), stripslashes($from_email), + (array) ($email['had'] ?? []), (string) ($email['message_id'] ?? '')); + } + // Back to Open - unless it is in a status of your own set to stay put when the client replies (Scheduled, say) $new_ticket_status = ticketStatusAfterClientReply($ticket_status); mysqli_query($mysqli, "UPDATE tickets SET ticket_status = $new_ticket_status, ticket_resolved_at = NULL WHERE ticket_id = $ticket_id AND ticket_client_id = $client_id LIMIT 1"); @@ -355,7 +381,7 @@ function addReply($from_email, $date, $subject, $ticket_number, $message, $attac logTicketHistory($ticket_id, "$from_email_esc replied by email, reopening the ticket"); } - logAudit("Ticket", "Edit", "Email parser: Client contact $from_email_esc updated ticket $config_ticket_prefix$ticket_number_esc ($subject)", $client_id, $ticket_id); + logAudit("Ticket", "Edit", "Email parser: Client contact $from_email_esc updated ticket $ticket_reference_esc ($subject)", $client_id, $ticket_id); triggerCustomAction('ticket_reply_client', $ticket_id); return true; } else { @@ -738,22 +764,40 @@ foreach ($messages as $message) { continue; } + // The same email a second time - sent to two of your addresses that both land in this mailbox, say - is on its + // ticket already, kept by its Message-ID (functions/ticket_mail_thread.php). Taken again, it was a second ticket + $email_message_id = ticketMailIdClean((string) $message->messageId()); + if ($email_message_id !== '' && ($seen_ticket_id = ticketMailIdTicket($email_message_id))) { + logApp("Cron-Email-Parser", "info", "Email parser skipped a second copy of an email from $from_email ($subject) - it is on ticket ID $seen_ticket_id already"); + $processed_count++; + $message->markSeen(); + $message->move($targetFolderPath); + continue; + } + // Save original message as .eml (ImapEngine: raw headers + raw body) mkdirMissing('../uploads/tmp/'); $original_message_file = "processed-eml-" . randomString(200) . ".eml"; $raw_message = (string)$message; // head + body, CRLF separated file_put_contents("../uploads/tmp/{$original_message_file}", $raw_message); - // CC (deduplicated, excluding the sender) - and ITFlow's own addresses: this mailbox CC'd beside a tech made a - // watcher would get every email about the ticket, each come back as a note that reopened it - $ccs = array(); - foreach ($message->cc() as $cc_addr) { - $cc_mail = strtolower($cc_addr->email()); - if ($cc_mail && $cc_mail !== strtolower($from_email) && !in_array($cc_mail, $ccs) && !in_array($cc_mail, $own_addresses, true)) { - $ccs[] = $cc_mail; + // Who else it was to or copied to (deduplicated, excluding the sender) - and not ITFlow's own addresses: this + // mailbox CC'd beside a tech made a watcher would get every email about the ticket, each come back as a note + $copied = array(); + $had = [strtolower(stripslashes($from_email))]; + foreach (array_merge($message->to(), $message->cc()) as $copied_addr) { + $copied_mail = strtolower((string) $copied_addr->email()); + $had[] = $copied_mail; + if ($copied_mail && $copied_mail !== strtolower($from_email) && !in_array($copied_mail, $copied) && !in_array($copied_mail, $own_addresses, true)) { + $copied[] = $copied_mail; } } + // Where it is in an email conversation - the Message-IDs it answers + $in_reply_to = (string) ($message->header('In-Reply-To')?->getRawValue() ?? ''); + $references = (string) ($message->header('References')?->getRawValue() ?? ''); + $email = ['message_id' => $email_message_id, 'copied' => $copied, 'had' => array_values(array_unique(array_filter($had))), 'threaded' => false]; + // Date (string) $dateObj = $message->date(); // ?CarbonInterface $date = escapeSql($dateObj ? $dateObj->setTimezone(date_default_timezone_get())->format('Y-m-d H:i:s') : date('Y-m-d H:i:s')); @@ -802,13 +846,20 @@ foreach ($messages as $message) { } } - // 1. Reply to existing ticket with the number in subject - if (preg_match("/\[" . preg_quote($config_ticket_prefix, '/') . "(\d+)\]/", $subject, $ticket_number_matches)) { - $ticket_number = intval($ticket_number_matches[1]); - $email_processed = addReply($from_email, $date, $subject, $ticket_number, $message_body, $attachments, $original_message_file); + // 1. A reply in a ticket's conversation - it answers one of the emails on the ticket, by its In-Reply-To or + // References - whatever its subject says (functions/ticket_mail_thread.php) + $thread_ticket_id = ticketMailHeaderTicket($in_reply_to, $references); + if ($thread_ticket_id) { + $email['threaded'] = true; + $email_processed = addReply($from_email, $date, $subject, $thread_ticket_id, $message_body, $attachments, $original_message_file, $email); } - // 2. Fuzzy duplicate check using a known contact/domain and similar_text subject + // 2. Reply to existing ticket with the number in subject - with the prefix that ticket was given + if (!$email_processed && ($subject_ticket = ticketMailSubjectTicket(stripslashes($subject)))) { + $email_processed = addReply($from_email, $date, $subject, $subject_ticket['ticket_id'], $message_body, $attachments, $original_message_file, $email); + } + + // 3. Fuzzy duplicate check using a known contact/domain and similar_text subject if (!$email_processed && strlen(trim($subject)) > 10) { $contact_id = 0; $client_id = 0; @@ -835,14 +886,13 @@ foreach ($messages as $message) { // If we found either a contact or a domain, check recent tickets for a matching subject if ($client_id) { $recent_tickets_sql = mysqli_query($mysqli, - "SELECT ticket_id, ticket_number, ticket_subject + "SELECT ticket_id, ticket_subject FROM tickets WHERE ticket_client_id = $client_id AND ticket_resolved_at IS NULL AND ticket_created_at >= DATE_SUB(NOW(), INTERVAL 7 DAY)" ); while ($rowt = mysqli_fetch_assoc($recent_tickets_sql)) { - $ticket_number = intval($rowt['ticket_number']); $existing_subject = $rowt['ticket_subject']; // Calculate similarity percentage @@ -850,14 +900,14 @@ foreach ($messages as $message) { if ($percent >= 95) { // Treat as a reply/duplicate - $email_processed = addReply($from_email, $date, $subject, $ticket_number, $message_body, $attachments, $original_message_file); + $email_processed = addReply($from_email, $date, $subject, intval($rowt['ticket_id']), $message_body, $attachments, $original_message_file, $email); break; } } } } - // 3. A known, registered contact? + // 4. A known, registered contact? if (!$email_processed) { $from_email_esc = mysqli_real_escape_string($mysqli, $from_email); $any_contact_sql = mysqli_query($mysqli, "SELECT * FROM contacts WHERE contact_email = '$from_email_esc' AND contact_archived_at IS NULL LIMIT 1"); @@ -869,11 +919,11 @@ foreach ($messages as $message) { $contact_email = escapeSql($rowc['contact_email']); $client_id = intval($rowc['contact_client_id']); - $email_processed = addTicket($contact_id, $contact_name, $contact_email, $client_id, $date, $subject, $message_body, $attachments, $original_message_file, $ccs); + $email_processed = addTicket($contact_id, $contact_name, $contact_email, $client_id, $date, $subject, $message_body, $attachments, $original_message_file, $copied, $email_message_id); } } - // 4. A known domain? + // 5. A known domain? if (!$email_processed) { $from_domain_esc = mysqli_real_escape_string($mysqli, $from_domain); $domain_sql = mysqli_query($mysqli, "SELECT domain_client_id, domain_name FROM domains WHERE domain_name = '$from_domain_esc' AND domain_archived_at IS NULL LIMIT 1"); @@ -891,16 +941,16 @@ foreach ($messages as $message) { logAudit("Contact", "Create", "Email parser: created contact " . mysqli_real_escape_string($mysqli, $contact_name), $client_id, $contact_id); triggerCustomAction('contact_create', $contact_id); - $email_processed = addTicket($contact_id, $contact_name, $contact_email, $client_id, $date, $subject, $message_body, $attachments, $original_message_file, $ccs); + $email_processed = addTicket($contact_id, $contact_name, $contact_email, $client_id, $date, $subject, $message_body, $attachments, $original_message_file, $copied, $email_message_id); } } - // 5. Unknown sender allowed? + // 6. Unknown sender allowed? if (!$email_processed && $config_ticket_email_parse_unknown_senders) { $bad_from_pattern = "/daemon|postmaster|bounce|mta/i"; // Stop NDRs with bad subjects raising new tickets if (!preg_match($bad_from_pattern, $from_email)) { - $email_processed = addTicket(0, $from_name, $from_email, 0, $date, $subject, $message_body, $attachments, $original_message_file, $ccs); + $email_processed = addTicket(0, $from_name, $from_email, 0, $date, $subject, $message_body, $attachments, $original_message_file, $copied, $email_message_id); } else { @@ -976,9 +1026,7 @@ foreach ($messages as $message) { } // If the original subject has a ticket, add the NDR there too - if (preg_match("/\[" . preg_quote($config_ticket_prefix, '/') . "(\d+)\]/", $original_subject, $ticket_number_matches)) { - - $ticket_number = intval($ticket_number_matches[1]); + if ($bounced_ticket = ticketMailSubjectTicket(stripslashes($original_subject))) { // Craft a clean bounce message $reply_body = "Email delivery failed.\n". @@ -991,7 +1039,7 @@ foreach ($messages as $message) { $from_email, $date, $original_subject, - $ticket_number, + $bounced_ticket['ticket_id'], $reply_body, [] ); diff --git a/db.sql b/db.sql index 1970646eb..2946d5a5c 100644 --- a/db.sql +++ b/db.sql @@ -1762,12 +1762,14 @@ CREATE TABLE `email_queue` ( `email_status` tinyint(1) NOT NULL DEFAULT 0, `email_recipient` varchar(255) NOT NULL, `email_recipient_name` varchar(255) DEFAULT NULL, + `email_cc` text DEFAULT NULL, `email_from` varchar(255) NOT NULL, `email_from_name` varchar(255) NOT NULL, `email_subject` varchar(255) NOT NULL, `email_content` longtext NOT NULL, `email_cal_str` text DEFAULT NULL, `email_attachments` text DEFAULT NULL, + `email_headers` text DEFAULT NULL, `email_queued_at` datetime NOT NULL DEFAULT current_timestamp(), `email_failed_at` datetime DEFAULT NULL, `email_error` varchar(500) DEFAULT NULL, @@ -4114,6 +4116,8 @@ CREATE TABLE `settings` ( `config_sms_visit_reminder_hours` int(11) NOT NULL DEFAULT 24, `config_sms_client_invoices` tinyint(1) NOT NULL DEFAULT 1, `config_ticket_client_general_notifications` tinyint(1) NOT NULL DEFAULT 1, + `config_ticket_email_copy` tinyint(1) NOT NULL DEFAULT 1, + `config_ticket_email_relay` tinyint(1) NOT NULL DEFAULT 1, `config_ticket_autoclose_hours` int(5) NOT NULL DEFAULT 72, `config_ticket_new_ticket_notification_email` varchar(200) DEFAULT NULL, `config_ticket_ai_triage` tinyint(1) NOT NULL DEFAULT 0, @@ -4900,6 +4904,26 @@ CREATE TABLE `ticket_mail_choices` ( ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci; /*!40101 SET character_set_client = @saved_cs_client */; +-- +-- Table structure for table `ticket_mail_threads` +-- + +DROP TABLE IF EXISTS `ticket_mail_threads`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8mb4 */; +CREATE TABLE `ticket_mail_threads` ( + `mail_thread_id` int(11) NOT NULL AUTO_INCREMENT, + `mail_thread_ticket_id` int(11) NOT NULL, + `mail_thread_message_id` varchar(255) NOT NULL, + `mail_thread_ours` tinyint(1) NOT NULL DEFAULT 0, + `mail_thread_created_at` datetime NOT NULL DEFAULT current_timestamp(), + PRIMARY KEY (`mail_thread_id`), + UNIQUE KEY `mail_thread_message_id` (`mail_thread_message_id`,`mail_thread_ticket_id`), + KEY `mail_thread_ticket_id` (`mail_thread_ticket_id`), + CONSTRAINT `ticket_mail_threads_ibfk_1` FOREIGN KEY (`mail_thread_ticket_id`) REFERENCES `tickets` (`ticket_id`) ON DELETE CASCADE +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + -- -- Table structure for table `ticket_reads` -- @@ -5195,6 +5219,7 @@ CREATE TABLE `tickets` ( PRIMARY KEY (`ticket_id`), KEY `ticket_response_due_at` (`ticket_response_due_at`), KEY `ticket_resolution_due_at` (`ticket_resolution_due_at`), + KEY `ticket_number` (`ticket_number`), KEY `ticket_client_id` (`ticket_client_id`,`ticket_archived_at`), KEY `ticket_project_id` (`ticket_project_id`), KEY `ticket_template_id` (`ticket_template_id`), diff --git a/functions.php b/functions.php index bcdd58544..f1cf04209 100644 --- a/functions.php +++ b/functions.php @@ -85,6 +85,7 @@ require_once __DIR__ . '/functions/ticket.php'; require_once __DIR__ . '/functions/ticket_helpers.php'; require_once __DIR__ . '/functions/ticket_link.php'; require_once __DIR__ . '/functions/ticket_pictures.php'; +require_once __DIR__ . '/functions/ticket_mail_thread.php'; require_once __DIR__ . '/functions/user_timezone.php'; require_once __DIR__ . '/functions/dispatch.php'; require_once __DIR__ . '/functions/project_tickets.php'; diff --git a/functions/app.php b/functions/app.php index 4ba4d4bb6..a92b60964 100644 --- a/functions/app.php +++ b/functions/app.php @@ -853,8 +853,15 @@ function addToMailQueue($data) { $ticket_reply_sql = !empty($email['ticket_reply_id']) ? ', email_ticket_reply_id = ' . intval($email['ticket_reply_id']) : ''; // One with a link or code that opens something, cleared once it has gone (emailQueue()'s sensitive) - once the 3.7.1 update has made the column $sensitive_sql = !empty($email['sensitive']) && mailQueueHasSensitive() ? ', email_sensitive = 1' : ''; + // The people copied in, and the conversation's headers (emailQueue()'s together and thread) - once the 4.2.6 update has made the columns + $thread_sql = ''; + if (ticketMailThreadReady()) { + // As they are - escapeSql() would take a Message-ID's <...> for a tag + $thread_sql = (!empty($email['cc']) ? ", email_cc = '" . mysqli_real_escape_string($mysqli, json_encode(array_values((array) $email['cc']), JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES)) . "'" : '') + . (!empty($email['headers']) ? ", email_headers = '" . mysqli_real_escape_string($mysqli, json_encode((array) $email['headers'], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES)) . "'" : ''); + } - mysqli_query($mysqli, "INSERT INTO email_queue SET email_recipient = '$recipient', email_recipient_name = '$recipient_name', email_from = '$from', email_from_name = '$from_name', email_subject = '$subject', email_content = '$body', email_queued_at = $queued_at, email_cal_str = '$cal_str', email_attachments = '$attachments'$ticket_reply_sql$sensitive_sql"); + mysqli_query($mysqli, "INSERT INTO email_queue SET email_recipient = '$recipient', email_recipient_name = '$recipient_name', email_from = '$from', email_from_name = '$from_name', email_subject = '$subject', email_content = '$body', email_queued_at = $queued_at, email_cal_str = '$cal_str', email_attachments = '$attachments'$ticket_reply_sql$sensitive_sql$thread_sql"); } return true; diff --git a/functions/email.php b/functions/email.php index 269c5e294..e4192d90b 100644 --- a/functions/email.php +++ b/functions/email.php @@ -8,8 +8,9 @@ * the card saying why they got it. * * emailHtml() draws one; emailQueue() queues it for each recipient, greeting - * each by name. Billing (functions/billing_email.php), tickets - * (functions/ticket.php) and the rest say what goes in it. + * each by name - or one email with the rest copied in, as a ticket's are. + * Billing (functions/billing_email.php), tickets (functions/ticket.php) and + * the rest say what goes in it. */ /** The colour of each tone - the card's top edge, its heading and its button. */ @@ -239,7 +240,7 @@ function emailCapturing() { return isset($GLOBALS['itflow_email_capture']) && is_array($GLOBALS['itflow_email_capture']); } -/** Stop capturing - what was captured: [['to', 'to_name', 'from', 'from_name', 'subject', 'html', 'attachments', 'cal_str'], ...]. */ +/** Stop capturing - what was captured: [['to', 'to_name', 'cc', 'from', 'from_name', 'subject', 'html', 'attachments', 'cal_str'], ...]. */ function emailCaptureStop() { $captured = $GLOBALS['itflow_email_capture'] ?? []; unset($GLOBALS['itflow_email_capture']); @@ -301,6 +302,34 @@ function emailOwnAddress($email) { return in_array(strtolower(trim((string) $email)), emailOwnAddresses(), true); } +/* + * The public domains that hand out addresses to anyone - an address at one of them isn't one of + * yours just because ITFlow's own mailbox is there too (emailOwnDomain()). + */ +const EMAIL_PUBLIC_DOMAINS = ['gmail.com', 'googlemail.com', 'outlook.com', 'hotmail.com', 'live.com', 'msn.com', 'yahoo.com', 'ymail.com', 'aol.com', + 'icloud.com', 'me.com', 'mac.com', 'proton.me', 'protonmail.com', 'pm.me', 'gmx.com', 'gmx.net', 'zoho.com', 'mail.com', 'fastmail.com', 'yandex.com']; + +/* + * Whether $email is at the domain of one of ITFlow's own addresses (emailOwnAddresses()) - another + * of your own mailboxes, or another name for the ticket mailbox - unless that domain is a public + * one anyone has an address at (EMAIL_PUBLIC_DOMAINS). + */ +function emailOwnDomain($email) { + static $domains = null; + if ($domains === null) { + $domains = []; + foreach (emailOwnAddresses() as $address) { + $domain = substr($address, strrpos($address, '@') + 1); + if (!in_array($domain, EMAIL_PUBLIC_DOMAINS, true)) { + $domains[$domain] = true; + } + } + } + $email = strtolower(trim((string) $email)); + $at = strrpos($email, '@'); + return $at !== false && isset($domains[substr($email, $at + 1)]); +} + /* * Whether ITFlow reads tickets from $email - email-to-ticket is on and it is the Receiving username, * or the ticket mailbox, which Admin > Mail says to make the same one. A notice sent there would be @@ -516,7 +545,13 @@ function emailInlineImages($html, array $ticket = []) { * see go in it (emailInlineImages()). An email to agents built by * ticketAgentEmailContent() says its own ticket, in $email['ticket_pictures'], * and has an internal note's pictures too - * Who it was queued to, "Name (email)". Nothing is queued without mail set up. + * together one email to the first recipient, everyone else copied in (Cc) - greeted as + * the first is, with together_footnote as why they get it. Before the 4.2.6 + * update, which gives the queue somewhere to keep them, one each + * thread the ticket whose conversation it is in - it gets a Message-ID of its own and + * In-Reply-To and References naming the emails before it (ticketMailHeaders()), + * and answering, the Message-ID of the email it answers, when it answers one + * Who it was queued to, "Name (email)" - the copied in too. Nothing is queued without mail set up. */ function emailQueue(array $recipients, $subject, array $email, array $opts = []) { global $mysqli; @@ -529,20 +564,39 @@ function emailQueue(array $recipients, $subject, array $email, array $opts = []) // The ticket whose pictures its message may carry (functions/ticket_pictures.php) $pictures = !empty($opts['ticket_id']) ? ['id' => intval($opts['ticket_id']), 'internal' => false] : (array) ($email['ticket_pictures'] ?? []); unset($email['ticket_pictures']); - $data = []; - $sent = []; + + // Each address once, and only an address + $people = []; foreach ($recipients as $recipient) { $address = trim((string) ($recipient['email'] ?? '')); - if (!filter_var($address, FILTER_VALIDATE_EMAIL) || isset($sent[strtolower($address)])) { - continue; + if (filter_var($address, FILTER_VALIDATE_EMAIL) && !isset($people[strtolower($address)])) { + $people[strtolower($address)] = ['email' => $address, 'name' => (string) ($recipient['name'] ?? '')] + $recipient; } - $name = (string) ($recipient['name'] ?? ''); + } + $people = array_values($people); + $together = !empty($opts['together']) && count($people) > 1 && ticketMailThreadReady(); + // Where the ticket's conversation stands as it is written - each email answers that + $thread_id = intval($opts['thread'] ?? 0); + $thread = $thread_id && ticketMailThreadReady() ? ticketMailThread($thread_id, (string) ($opts['answering'] ?? '')) : null; + + $data = []; + $sent = []; + foreach ($together ? [$people[0]] : $people as $recipient) { + $address = $recipient['email']; + $name = $recipient['name']; + $cc = $together ? array_slice($people, 1) : []; + $footnote = $together && isset($opts['together_footnote']) ? $opts['together_footnote'] : ($recipient['footnote'] ?? null); $html = emailHtml(array_merge($email, [ 'name' => array_key_exists('greet', $recipient) ? $recipient['greet'] : $name, - ], isset($recipient['footnote']) ? ['footnote' => $recipient['footnote']] : [])); - $sent[strtolower($address)] = $name !== '' ? "$name ($address)" : $address; + ], $footnote !== null ? ['footnote' => $footnote] : [])); + foreach (array_merge([$recipient], $cc) as $person) { + $sent[strtolower($person['email'])] = $person['name'] !== '' ? $person['name'] . ' (' . $person['email'] . ')' : $person['email']; + } + $cc_list = array_map(function ($person) { + return ['email' => $person['email'], 'name' => $person['name']]; + }, $cc); if (emailCapturing()) { - $GLOBALS['itflow_email_capture'][] = ['to' => $address, 'to_name' => $name, 'from' => (string) $from['email'], 'from_name' => (string) $from['name'], + $GLOBALS['itflow_email_capture'][] = ['to' => $address, 'to_name' => $name, 'cc' => $cc_list, 'from' => (string) $from['email'], 'from_name' => (string) $from['name'], 'subject' => (string) $subject, 'html' => $html, 'attachments' => $attachments, 'cal_str' => (string) ($opts['cal_str'] ?? '')]; continue; } @@ -559,7 +613,9 @@ function emailQueue(array $recipients, $subject, array $email, array $opts = []) ] + (!empty($opts['cal_str']) ? ['cal_str' => (string) $opts['cal_str']] : []) + ($queued_at !== '' ? ['queued_at' => $queued_at] : []) + (intval($opts['ticket_reply_id'] ?? 0) > 0 && ticketReplyEmailReady() ? ['ticket_reply_id' => intval($opts['ticket_reply_id'])] : []) - + (!empty($opts['sensitive']) ? ['sensitive' => 1] : []); + + (!empty($opts['sensitive']) ? ['sensitive' => 1] : []) + + ($cc_list ? ['cc' => $cc_list] : []) + + ($thread !== null ? ['headers' => ticketMailHeaders($thread_id, (string) $from['email'], $thread)] : []); } if ($data) { addToMailQueue($data); diff --git a/functions/email_preview.php b/functions/email_preview.php index 87cbb7ac2..6a76b3485 100644 --- a/functions/email_preview.php +++ b/functions/email_preview.php @@ -165,34 +165,42 @@ function emailPreviewCatalog() { }; return [ // ---- Tickets, to clients - 'ticket_created' => ['group' => 'Tickets - to clients', 'label' => 'Ticket opened for them', 'to' => 'The contact and the watchers', 'when' => 'An agent opens a ticket for a contact', + 'ticket_created' => ['group' => 'Tickets - to clients', 'label' => 'Ticket opened for them', 'to' => 'The contact, with the watchers copied in', 'when' => 'An agent opens a ticket for a contact', 'run' => function ($s) { - ticketMailCreated($s['ticket'], 'Ticket Created -'); + ticketMailCreated($s['ticket']); }], 'ticket_created_email' => ['group' => 'Tickets - to clients', 'label' => 'Their email became a ticket', 'to' => 'Whoever emailed', 'when' => 'The email parser makes a ticket from an email', 'run' => function ($s) { - ticketMailCreated($s['ticket'], 'Ticket created -', [], false, 'email', [['email' => $s['alex_email'], 'name' => $s['alex_name']]]); + ticketMailCreated($s['ticket'], [], false, 'email', [['email' => $s['alex_email'], 'name' => $s['alex_name']]]); }], - 'ticket_created_scheduled' => ['group' => 'Tickets - to clients', 'label' => 'Scheduled ticket raised', 'to' => 'The contact and the watchers', 'when' => 'A recurring ticket raises its ticket', + 'ticket_created_scheduled' => ['group' => 'Tickets - to clients', 'label' => 'Scheduled ticket raised', 'to' => 'The contact', 'when' => 'A recurring ticket raises its ticket', 'pick' => 'contact', 'run' => function ($s) { recurringTicketRaise($s['recurring'], 'Preview'); }], - 'ticket_reply' => ['group' => 'Tickets - to clients', 'label' => 'Reply', 'to' => 'The contact and the watchers', 'when' => 'An agent replies publicly', + 'ticket_reply' => ['group' => 'Tickets - to clients', 'label' => 'Reply', 'to' => 'The contact, with the watchers copied in', 'when' => 'An agent replies publicly', 'run' => function ($s) { ticketMailReply($s['ticket'], $s['reply'], $s['by']); }], - 'ticket_resolved' => ['group' => 'Tickets - to clients', 'label' => 'Resolved', 'to' => 'The contact and the watchers', 'when' => 'An agent resolves a ticket', + 'ticket_resolved' => ['group' => 'Tickets - to clients', 'label' => 'Resolved', 'to' => 'The contact, with the watchers copied in', 'when' => 'An agent resolves a ticket', 'run' => function ($s) { global $mysqli; mysqli_query($mysqli, "UPDATE tickets SET ticket_status = 4, ticket_resolved_at = NOW() WHERE ticket_id = " . intval($s['ticket'])); ticketMailReply($s['ticket'], $s['reply'], $s['by'], true); }], - 'ticket_closed' => ['group' => 'Tickets - to clients', 'label' => 'Closed', 'to' => 'The contact and the watchers', 'when' => 'A ticket is closed, by an agent or after it was resolved', + 'ticket_closed' => ['group' => 'Tickets - to clients', 'label' => 'Closed', 'to' => 'The contact, with the watchers copied in', 'when' => 'A ticket is closed, by an agent or after it was resolved', 'run' => function ($s) { global $mysqli; mysqli_query($mysqli, "UPDATE tickets SET ticket_status = 5, ticket_resolved_at = NOW(), ticket_closed_at = NOW() WHERE ticket_id = " . intval($s['ticket'])); ticketMailClosed($s['ticket']); }], + 'ticket_client_reply' => ['group' => 'Tickets - to clients', 'label' => 'Client\'s reply, passed on', 'to' => 'The people following the ticket who weren\'t on it', + 'when' => 'The client replies by email, text or in the portal (Admin > Settings > Tickets)', + 'run' => function ($s) { + global $mysqli; + $reply_id = intval(mysqli_fetch_row(mysqli_query($mysqli, "SELECT ticket_reply_id FROM ticket_replies WHERE ticket_reply_ticket_id = " . intval($s['ticket']) . " + AND ticket_reply_type = 'Client' ORDER BY ticket_reply_id DESC LIMIT 1"))[0] ?? 0); + ticketMailRelayClientReply($s['ticket'], $reply_id, $s['alex_name'], $s['alex_email']); + }], 'ticket_watcher' => ['group' => 'Tickets - to clients', 'label' => 'Made a watcher', 'to' => 'The new watcher', 'when' => 'An agent adds a watcher and asks to tell them', 'run' => function ($s) { ticketMailWatchersAdded($s['ticket'], [$s['jamie_email']], $s['by']); @@ -205,9 +213,9 @@ function emailPreviewCatalog() { 'run' => function ($s) { ticketMailTaskApproval($s['approval'], $s['by']); }], - 'ticket_scheduled' => ['group' => 'Tickets - to clients', 'label' => 'Work booked', 'to' => 'The contact and the watchers, with a calendar file', 'when' => 'An agent schedules the work', + 'ticket_scheduled' => ['group' => 'Tickets - to clients', 'label' => 'Work booked', 'to' => 'The contact, with the watchers copied in and a calendar file', 'when' => 'An agent schedules the work', 'pick' => 'contact', 'run' => $ticket_schedule], - 'ticket_schedule_cancelled' => ['group' => 'Tickets - to clients', 'label' => 'Booked work cancelled', 'to' => 'The contact and the watchers, with a calendar file', 'when' => 'An agent cancels the scheduled work', + 'ticket_schedule_cancelled' => ['group' => 'Tickets - to clients', 'label' => 'Booked work cancelled', 'to' => 'The contact, with the watchers copied in and a calendar file', 'when' => 'An agent cancels the scheduled work', 'pick' => 'contact', 'run' => function ($s) use ($ticket_schedule) { $ticket_schedule($s); emailCaptureStart(); // only the cancellation diff --git a/functions/mail_queue.php b/functions/mail_queue.php index 625fea4b4..a6aa9caa2 100644 --- a/functions/mail_queue.php +++ b/functions/mail_queue.php @@ -21,6 +21,11 @@ * 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. */ const MAIL_QUEUE_TRIES = 4; @@ -286,6 +291,39 @@ function mailQueueAttachments($json) { 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) - the ones that keep a conversation together, nothing else. */ +const MAIL_QUEUE_HEADERS = ['Message-ID', 'In-Reply-To', 'References']; + +/* + * An email's own headers (email_headers, emailQueue()'s thread) - [name => value] of those it may + * carry (MAIL_QUEUE_HEADERS), each a list of and nothing else, 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 (in_array($name, MAIL_QUEUE_HEADERS, true) && $value !== '' && strlen($value) <= 4000 && preg_match('/^(<[^<>\s]+@[^<>\s]+>)( <[^<>\s]+@[^<>\s]+>)*$/', $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:. diff --git a/functions/settings.php b/functions/settings.php index 19ee63f4d..f07a17497 100644 --- a/functions/settings.php +++ b/functions/settings.php @@ -264,6 +264,10 @@ function settingsFields() { 'config_ticket_next_number' => ['page' => 'ticket', 'section' => 'Numbering', 'label' => 'Next ticket number', 'words' => 'ticket number counter'], 'config_ticket_email_parse' => ['page' => 'ticket', 'section' => 'Email to ticket', 'label' => 'Turn emails into tickets', 'words' => 'email to ticket parser parse inbound imap mailbox'] + $on_off, 'config_ticket_email_parse_unknown_senders' => ['page' => 'ticket', 'section' => 'Email to ticket', 'label' => 'From unknown senders too', 'words' => 'unknown senders domains anyone email'] + $on_off, + 'config_ticket_email_copy' => ['page' => 'ticket', 'section' => 'Emails about a ticket', 'label' => 'One email, with the watchers copied in', + 'words' => 'cc copy copied watchers one email each separate recipients reply all'] + $on_off, + 'config_ticket_email_relay' => ['page' => 'ticket', 'section' => 'Emails about a ticket', 'label' => 'Pass a client\'s reply on to the watchers', + 'words' => 'relay forward client reply watchers copied notify pass on'] + $on_off, 'config_ticket_sms_parse' => ['page' => 'ticket', 'section' => 'Text to ticket', 'label' => 'Turn texts into tickets', 'words' => 'text sms message mobile phone skyetel to ticket'] + $on_off, 'config_ticket_sms_unknown_senders' => ['page' => 'ticket', 'section' => 'Text to ticket', 'label' => 'From unknown numbers too', 'words' => 'text sms unknown numbers anyone'] + $on_off, 'config_ticket_sms_acknowledge' => ['page' => 'ticket', 'section' => 'Text to ticket', 'label' => 'Text back the ticket number', 'words' => 'text sms acknowledge reply confirm number'] + $on_off, diff --git a/functions/sms.php b/functions/sms.php index 31b1ffd1b..ac2189edc 100644 --- a/functions/sms.php +++ b/functions/sms.php @@ -1012,6 +1012,10 @@ function smsTicketReply(int $message_id, array $conversation, string $from, stri notification_action = '" . escapeSql('/agent/' . ticketUrl($ticket_id, $client_id)) . "', notification_client_id = $client_id, notification_user_id = $assigned"); } ticketMailAssigneeReplied($ticket_id, 'text', $html, $who); + // On to the people following the ticket by email - from one of the client's contacts (functions/ticket_mail_thread.php) + if ($contact_id) { + ticketMailRelayClientReply($ticket_id, $reply_id, $who, (string) getFieldById('contacts', $contact_id, 'contact_email')); + } triggerCustomAction('ticket_reply_client', $ticket_id); return $reply_id; } diff --git a/functions/ticket.php b/functions/ticket.php index ea8d86ee6..603bbd075 100644 --- a/functions/ticket.php +++ b/functions/ticket.php @@ -401,6 +401,11 @@ function ticketMergeInto($child, $parent, $comment, $move_replies = false) { // So do its related tickets (functions/ticket_link.php) ticketLinkCarry($ticket_id, $parent_id); + // And its email conversation - a reply to one of its emails lands on the ticket it was merged into (functions/ticket_mail_thread.php) + if (ticketMailThreadReady()) { + mysqli_query($mysqli, "UPDATE IGNORE ticket_mail_threads SET mail_thread_ticket_id = $parent_id WHERE mail_thread_ticket_id = $ticket_id"); + } + logTicketHistory($ticket_id, "$session_name merged this ticket into $parent_reference and closed it"); logTicketHistory($parent_id, "$session_name merged $child_reference into this ticket"); logAudit("Ticket", "Merge", "$session_name merged ticket $child_reference into $parent_reference", intval($child['ticket_client_id']), $ticket_id); @@ -534,6 +539,9 @@ function ticketEmailExcerpt($html, $limit = 700) { * each. $row is ticketRow(). $kind and its $opts: * created it was opened - how: agent (the default), email (the reply to an emailed one) or scheduled * reply an agent's reply - message (its HTML), by (who wrote it) + * client_reply a client's reply, passed on to the people following the ticket who didn't have + * it (ticketMailRelayClientReply()) - message (its HTML), by (who wrote it), skip (the + * reply as saved, left out of the earlier messages) * resolved marked resolved, pending closure - message (the agent's note, HTML, or ''), by, * no_response (true: the message is the email - Resolve - no response) * closed closed - asking how we did @@ -583,6 +591,14 @@ function ticketEmailContent(array $row, $kind, array $opts = []) { $email['summary'] = $summary; $email['after'] = ['To answer, just reply to this email.']; $email['history'] = ticketEmailHistory($row, ['skip' => (string) ($opts['message'] ?? '')]); + } elseif ($kind === 'client_reply') { + $email['kind'] = 'Ticket update'; + $email['title'] = $subject; + $email['intro'] = ["$by replied on ticket $reference."]; + $email['message'] = ['html' => (string) ($opts['message'] ?? ''), 'label' => "$by wrote"]; + $email['summary'] = $summary; + $email['after'] = ['To answer, just reply to this email.']; + $email['history'] = ticketEmailHistory($row, ['skip' => (string) ($opts['skip'] ?? $opts['message'] ?? '')]); } elseif ($kind === 'resolved') { $hours = intval($config_ticket_autoclose_hours); $closes = $hours > 0 ? ' - it closes by itself after ' . ($hours % 24 === 0 ? ($hours / 24) . ' day' . ($hours === 24 ? '' : 's') : "$hours hours") : ''; @@ -660,14 +676,17 @@ function ticketEmailPreview(array $email) { /* * Queue an email about a ticket (ticketEmailContent()) to its contact, when * $to_contact and the address is good, and to every watcher, each told why - * they get it. $subject is raw. Nothing is queued without a mail provider. - * How many were queued. $opts: + * they get it. Nothing is queued without a mail provider. Its subject is the + * ticket's (ticketEmailSubject()), and it goes in the ticket's conversation + * (functions/ticket_mail_thread.php). One email, the contact's, with everyone + * else copied in - unless Admin > Settings > Tickets says one each. + * How many it went to. $opts: * attachments files to send with it ([['path', 'name'], ...]) * to_contact false leaves the contact out * to_watchers false is the contact alone - no watchers, no colleagues * to [['email', 'name'], ...] in place of the contact - the sender of an emailed ticket * recipients emailQueue()'s list in place of everyone - the To line's people - * (ticketReplyRecipientsPick()) + * (ticketReplyRecipientsPick()), each with its group * kind created, closed or update (the default): a contact who asked * for replies only gets no created or closed email * (ticketContactWantsEmail()), and the client's primary and @@ -676,8 +695,9 @@ function ticketEmailPreview(array $email) { * (ticketColleagueRecipients()) * ticket_reply_id the agent's reply it carries - each email is kept with it * (emailQueue()), for ticketReplyEmailed() + * answering the Message-ID of the email it answers, when it answers one */ -function ticketMailSend($ticket_id, $subject, array $email, array $opts = []) { +function ticketMailSend($ticket_id, array $email, array $opts = []) { global $mysqli; if (!emailReady()) { return 0; @@ -685,7 +705,7 @@ function ticketMailSend($ticket_id, $subject, array $email, array $opts = []) { $ticket_id = intval($ticket_id); $kind = (string) ($opts['kind'] ?? 'update'); $to_watchers = $opts['to_watchers'] ?? true; - $row = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT ticket_prefix, ticket_number, contact_name, contact_email, contact_ticket_emails + $row = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT ticket_prefix, ticket_number, ticket_subject, contact_name, contact_email, contact_ticket_emails FROM tickets LEFT JOIN contacts ON contact_id = ticket_contact_id WHERE ticket_id = $ticket_id")); if (!$row) { return 0; @@ -698,29 +718,40 @@ function ticketMailSend($ticket_id, $subject, array $email, array $opts = []) { $to_watchers = false; } elseif (isset($opts['to'])) { foreach ((array) $opts['to'] as $to) { - $recipients[] = ['email' => $to['email'], 'name' => (string) ($to['name'] ?? ''), 'footnote' => "You get this because you emailed $company_name."]; + $recipients[] = ['email' => $to['email'], 'name' => (string) ($to['name'] ?? ''), 'group' => 'contact', 'footnote' => "You get this because you emailed $company_name."]; } } elseif (($opts['to_contact'] ?? true) && ticketContactWantsEmail($row['contact_ticket_emails'] ?? 'all', $kind)) { - $recipients[] = ['email' => (string) $row['contact_email'], 'name' => (string) $row['contact_name'], 'footnote' => "You get this as the contact on ticket $reference with $company_name."]; + $recipients[] = ['email' => (string) $row['contact_email'], 'name' => (string) $row['contact_name'], 'group' => 'contact', 'footnote' => "You get this as the contact on ticket $reference with $company_name."]; } if ($to_watchers) { $sql = mysqli_query($mysqli, "SELECT watcher_email FROM ticket_watchers WHERE watcher_ticket_id = $ticket_id"); while ($watcher = mysqli_fetch_assoc($sql)) { - $recipients[] = ['email' => trim((string) $watcher['watcher_email']), 'greet' => '', 'footnote' => "You get this because you are watching ticket $reference - ask $company_name if you would like to stop."]; + $recipients[] = ['email' => trim((string) $watcher['watcher_email']), 'greet' => '', 'group' => 'watcher', 'footnote' => "You get this because you are watching ticket $reference - ask $company_name if you would like to stop."]; } // A new ticket reaches them by ticketMailColleaguesNew(), in an email of its own if ($kind !== 'created') { foreach (ticketColleagueRecipients($ticket_id, $kind) as $address => $colleague) { - $recipients[] = ['email' => $address, 'name' => $colleague['name'], 'footnote' => "You get this because you asked for every update on " . $colleague['client_name'] . "'s tickets - change that under Your account in the client portal."]; + $recipients[] = ['email' => $address, 'name' => $colleague['name'], 'group' => 'colleague', 'footnote' => "You get this because you asked for every update on " . $colleague['client_name'] . "'s tickets - change that under Your account in the client portal."]; } } } - // Never to one of ITFlow's own addresses - a watcher that is the ticket mailbox would read it back in (emailOwnAddresses()) + // Never to one of ITFlow's own addresses - a watcher that is the ticket mailbox would read it back in (emailOwnAddresses()) - and + // only to an address $recipients = array_values(array_filter($recipients, function ($recipient) { - return !emailOwnAddress($recipient['email'] ?? ''); + return filter_var(trim((string) ($recipient['email'] ?? '')), FILTER_VALIDATE_EMAIL) && !emailOwnAddress($recipient['email']); })); - return count(emailQueue($recipients, $subject, $email, ['from' => ticketEmailFrom(), 'attachments' => $opts['attachments'] ?? [], 'cal_str' => $opts['cal_str'] ?? '', - 'ticket_reply_id' => intval($opts['ticket_reply_id'] ?? 0), 'ticket_id' => intval($ticket_id)])); + // One email: to the contact when they are on it - else whoever is first - with the rest copied in + usort($recipients, function ($a, $b) { + return (($b['group'] ?? '') === 'contact') <=> (($a['group'] ?? '') === 'contact'); + }); + $to_contact = ($recipients[0]['group'] ?? '') === 'contact'; + return count(emailQueue($recipients, ticketEmailSubject($row), $email, ['from' => ticketEmailFrom(), 'attachments' => $opts['attachments'] ?? [], 'cal_str' => $opts['cal_str'] ?? '', + 'ticket_reply_id' => intval($opts['ticket_reply_id'] ?? 0), 'ticket_id' => $ticket_id, + 'together' => ticketMailSettings()['copy'], + 'together_footnote' => $to_contact + ? "You get this as the contact on ticket $reference with $company_name, or copied in as someone following it - ask $company_name if you would like to stop." + : "You get this because you are following ticket $reference with $company_name - ask $company_name if you would like to stop.", + 'thread' => $ticket_id, 'answering' => (string) ($opts['answering'] ?? '')])); } /** Whether a ticket's contact gets an email of this $kind - no 'created' or 'closed' email for one who asked for replies only. */ @@ -785,7 +816,7 @@ function ticketMailColleaguesNew($ticket_id) { $sent += count(emailQueue([[ 'email' => $email, 'name' => $colleague['name'], 'footnote' => "You get this because you asked to hear about new tickets at " . $colleague['client_name'] . ($colleague['portal'] ? ' - change that under Your account in the client portal.' : '.'), - ]], "New ticket - [$reference] - " . $ticket['ticket_subject'], [ + ]], ticketEmailSubject($ticket), [ 'kind' => 'New ticket', 'tone' => 'primary', 'preview' => ($echo ? preg_replace('/\s+/', ' ', emailPlainText($ticket['ticket_details'], 140)) : '') ?: "$reference - " . $ticket['ticket_subject'], 'title' => "New ticket at " . $colleague['client_name'], 'intro' => ["$raised_by raised a ticket at " . $colleague['client_name'] . '.'], @@ -794,7 +825,7 @@ function ticketMailColleaguesNew($ticket_id) { 'button' => ['label' => $colleague['portal'] ? 'View it in the portal' : 'View the ticket', 'url' => $url], 'contact' => ticketEmailContactLine(), 'office' => officeTicketFoot($ticket), - ], ['from' => ticketEmailFrom(), 'ticket_id' => $ticket_id])); + ], ['from' => ticketEmailFrom(), 'ticket_id' => $ticket_id, 'thread' => $ticket_id])); } return $sent; } @@ -804,12 +835,12 @@ function ticketMailColleaguesNew($ticket_id) { * unless $to_watchers is false; or to $to (ticketMailSend()'s) in their * place. $how agent, email or scheduled (ticketEmailContent()). */ -function ticketMailCreated($ticket_id, $subject_prefix, $attachments = [], $to_watchers = true, $how = 'agent', ?array $to = null) { +function ticketMailCreated($ticket_id, $attachments = [], $to_watchers = true, $how = 'agent', ?array $to = null) { $row = ticketRow($ticket_id); if (!$row) { return 0; } - return ticketMailSend($row['ticket_id'], "$subject_prefix [" . ticketReference($row) . "] - " . $row['ticket_subject'], ticketEmailContent($row, 'created', ['how' => $how]), + return ticketMailSend($row['ticket_id'], ticketEmailContent($row, 'created', ['how' => $how]), ['attachments' => $attachments, 'to_watchers' => $to_watchers, 'kind' => 'created'] + ($to !== null ? ['to' => $to] : [])); } @@ -826,8 +857,7 @@ function ticketMailReply($ticket_id, $reply_html, $by, $resolved = false, $attac ticketReplyEmailed($reply_id, false); return 0; } - $sent = ticketMailSend($row['ticket_id'], ($resolved ? 'Ticket resolved' : 'Ticket update') . " - [" . ticketReference($row) . "] - " . $row['ticket_subject'] . ($resolved ? ' | (pending closure)' : ''), - ticketEmailContent($row, $resolved ? 'resolved' : 'reply', ['message' => (string) $reply_html, 'by' => (string) $by]), + $sent = ticketMailSend($row['ticket_id'], ticketEmailContent($row, $resolved ? 'resolved' : 'reply', ['message' => (string) $reply_html, 'by' => (string) $by]), ['attachments' => $attachments, 'ticket_reply_id' => intval($reply_id)] + ($to !== null ? ['recipients' => $to] : [])); ticketReplyEmailed($reply_id, $sent > 0); return $sent; @@ -863,10 +893,14 @@ function ticketReplyEmailed($reply_id, $emailed = true) { } $to = []; if ($emailed) { - $sql = mysqli_query($mysqli, "SELECT email_recipient, email_recipient_name FROM email_queue WHERE email_ticket_reply_id = $reply_id ORDER BY email_id"); + // The copied in too (email_cc, 4.2.6) + $sql = mysqli_query($mysqli, "SELECT email_recipient, email_recipient_name, " . (ticketMailThreadReady() ? 'email_cc' : "'' AS email_cc") . " FROM email_queue WHERE email_ticket_reply_id = $reply_id ORDER BY email_id"); while ($row = mysqli_fetch_assoc($sql)) { $to[strtolower($row['email_recipient'])] = ['email' => (string) $row['email_recipient'], 'name' => (string) $row['email_recipient_name'] !== (string) $row['email_recipient'] ? (string) $row['email_recipient_name'] : '']; + foreach (mailQueueCc($row['email_cc']) as $person) { + $to[strtolower($person['email'])] = $to[strtolower($person['email'])] ?? $person; + } } } $json = $to ? "'" . escapeSql(json_encode(array_values($to), JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES)) . "'" : 'NULL'; @@ -902,16 +936,23 @@ function ticketReplyEmailStates(array $rows) { if (!$states || !ticketReplyEmailReady()) { return array_map(function ($state) { $state['to'] = array_values($state['to']); return $state; }, $states); } - $sql = mysqli_query($mysqli, "SELECT email_ticket_reply_id, email_recipient, email_recipient_name, email_status, email_attempts, email_queued_at, email_failed_at, email_sent_at, email_error + $sql = mysqli_query($mysqli, "SELECT email_ticket_reply_id, email_recipient, email_recipient_name, " . (ticketMailThreadReady() ? 'email_cc' : "'' AS email_cc") . ", + email_status, email_attempts, email_queued_at, email_failed_at, email_sent_at, email_error FROM email_queue WHERE email_ticket_reply_id IN (" . implode(',', array_keys($states)) . ") ORDER BY email_id"); while ($sql && ($email = mysqli_fetch_assoc($sql))) { $reply_id = intval($email['email_ticket_reply_id']); - $address = strtolower((string) $email['email_recipient']); - $states[$reply_id]['to'][$address] = [ - 'email' => (string) $email['email_recipient'], - 'name' => $states[$reply_id]['to'][$address]['name'] ?? ((string) $email['email_recipient_name'] !== (string) $email['email_recipient'] ? (string) $email['email_recipient_name'] : ''), - 'state' => mailQueueState($email), - ]; + $state = mailQueueState($email); + // 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'])); + foreach ($people as $person) { + $address = strtolower($person['email']); + $states[$reply_id]['to'][$address] = [ + 'email' => $person['email'], + 'name' => $states[$reply_id]['to'][$address]['name'] ?? $person['name'], + 'state' => $state, + ]; + } } foreach ($states as $reply_id => $state) { $keys = array_filter(array_map(function ($recipient) { return $recipient['state']['key'] ?? null; }, $state['to'])); @@ -931,7 +972,7 @@ function ticketReplyEmailStates(array $rows) { return $states; } -/** Tell people just made watchers of a ticket - $emails, by $by (raw). How many it went to. */ +/** Tell people just made watchers of a ticket - $emails, by $by (raw), each an email of their own in its conversation. How many it went to. */ function ticketMailWatchersAdded($ticket_id, array $emails, $by) { $row = ticketRow($ticket_id); if (!$row || !$emails) { @@ -940,7 +981,7 @@ function ticketMailWatchersAdded($ticket_id, array $emails, $by) { $company_name = (string) (billingCompany()['company_name'] ?? 'us'); return count(emailQueue(array_map(function ($watcher_email) use ($row, $company_name) { return ['email' => $watcher_email, 'greet' => '', 'footnote' => "You get this because you are watching ticket " . ticketReference($row) . " - ask $company_name if you would like to stop."]; - }, $emails), "Ticket Notification - [" . ticketReference($row) . "] - " . $row['ticket_subject'], ticketEmailContent($row, 'watcher', ['by' => (string) $by]), ['from' => ticketEmailFrom()])); + }, $emails), ticketEmailSubject($row), ticketEmailContent($row, 'watcher', ['by' => (string) $by]), ['from' => ticketEmailFrom(), 'thread' => intval($row['ticket_id'])])); } /* ------------------------------------------------------------ Emails about a ticket, to agents */ @@ -1222,22 +1263,24 @@ function ticketMailTaskApproval($approval_id, $by) { /* * Tell someone who replied to a closed ticket by email that it is closed, so - * their reply reached nobody - and how to raise a new one. $from_email raw. + * their reply reached nobody - and how to raise a new one. $from_email raw; + * $answering the Message-ID of their reply, which this answers in the ticket's + * conversation. */ -function ticketMailClosedReply($ticket_id, $from_email) { +function ticketMailClosedReply($ticket_id, $from_email, $answering = '') { $closed = ticketRow($ticket_id); if (!$closed) { return 0; } $support = ticketEmailFrom()['email']; - return count(emailQueue([['email' => (string) $from_email, 'greet' => '', 'footnote' => 'You get this because you replied to a closed ticket.']], "Action required: This ticket is already closed", [ + return count(emailQueue([['email' => (string) $from_email, 'greet' => '', 'footnote' => 'You get this because you replied to a closed ticket.']], ticketEmailSubject($closed), [ 'kind' => 'Ticket closed', 'tone' => 'warning', 'preview' => 'Your reply did not reach us - raise a new ticket instead', 'title' => 'That ticket is closed', 'intro' => ["You replied to ticket " . ticketReference($closed) . " - \"" . $closed['ticket_subject'] . "\" - which is closed, so your reply won't reach us.", "To raise a new ticket, send a new email to $support."], 'button' => ['label' => 'Email us', 'url' => "mailto:$support"], 'contact' => ticketEmailContactLine(), 'office' => officeTicketFoot($closed), - ], ['from' => ticketEmailFrom()])); + ], ['from' => ticketEmailFrom(), 'thread' => intval($closed['ticket_id']), 'answering' => (string) $answering])); } /* @@ -1586,8 +1629,7 @@ function ticketResolveNoResponse(array $row, $message) { $sent = 0; $ticket = ticketRow($ticket_id); if ($ticket && intval($config_ticket_client_general_notifications) === 1) { - $sent = ticketMailSend($ticket_id, "Ticket resolved - [" . ticketReference($ticket) . "] - " . $ticket['ticket_subject'] . " | (pending closure)", - ticketEmailContent($ticket, 'resolved', ['message' => $html, 'by' => stripslashes((string) ($session_name ?? '')), 'no_response' => true]), ['ticket_reply_id' => $reply_id]); + $sent = ticketMailSend($ticket_id, ticketEmailContent($ticket, 'resolved', ['message' => $html, 'by' => stripslashes((string) ($session_name ?? '')), 'no_response' => true]), ['ticket_reply_id' => $reply_id]); } ticketReplyEmailed($reply_id, $sent > 0); return $sent; @@ -1613,8 +1655,7 @@ function ticketMailClosed($ticket_id) { if (!$row || ticketIsNoResponse($row)) { return 0; } - return ticketMailSend($row['ticket_id'], "Ticket closed - [" . ticketReference($row) . "] - " . $row['ticket_subject'] . " | (do not reply)", - ticketEmailContent($row, 'closed'), ['kind' => 'closed']); + return ticketMailSend($row['ticket_id'], ticketEmailContent($row, 'closed'), ['kind' => 'closed']); } /* @@ -1691,8 +1732,7 @@ function ticketMailResolved($ticket_id, $note = '', $reply_id = 0) { ticketReplyEmailed($reply_id, false); return 0; } - $sent = ticketMailSend($row['ticket_id'], "Ticket resolved - [" . ticketReference($row) . "] - " . $row['ticket_subject'] . " | (pending closure)", - ticketEmailContent($row, 'resolved', ['message' => (string) $note, 'by' => stripslashes((string) ($session_name ?? ''))]), ['ticket_reply_id' => intval($reply_id)]); + $sent = ticketMailSend($row['ticket_id'], ticketEmailContent($row, 'resolved', ['message' => (string) $note, 'by' => stripslashes((string) ($session_name ?? ''))]), ['ticket_reply_id' => intval($reply_id)]); ticketReplyEmailed($reply_id, $sent > 0); return $sent; } @@ -2134,8 +2174,7 @@ function recurringTicketRaise($recurring_ticket_id, $by = 'Cron') { // The client is told (when general notifications are on) - the contact alone $new = ticketRow($ticket_id); if (intval($config_ticket_client_general_notifications) === 1 && $new) { - ticketMailSend($ticket_id, "Ticket created - [" . ticketReference($new) . "] - " . $new['ticket_subject'] . " (scheduled)", - ticketEmailContent($new, 'created', ['how' => 'scheduled']), ['kind' => 'created', 'to_watchers' => false]); + ticketMailSend($ticket_id, ticketEmailContent($new, 'created', ['how' => 'scheduled']), ['kind' => 'created', 'to_watchers' => false]); } // The new-ticket address (Admin > Ticket), when there is one @@ -2395,7 +2434,7 @@ function ticketMailSchedule($row, $cal_str, $cancelled, $when_text, $start = nul ticketAgentEmailContent($ticket, 'scheduled', ['when' => $start ? timezoneWhenFor($start, $end, $ticket['ticket_assigned_to']) : $when_text] + $opts), ['from' => ticketEmailFrom(), 'cal_str' => $cal_str]); } if ($tell_client && intval($config_ticket_client_general_notifications) === 1) { - ticketMailSend($ticket['ticket_id'], $subject, ticketEmailContent($ticket, 'scheduled', $opts), ['cal_str' => $cal_str]); + ticketMailSend($ticket['ticket_id'], ticketEmailContent($ticket, 'scheduled', $opts), ['cal_str' => $cal_str]); } } diff --git a/functions/ticket_mail_thread.php b/functions/ticket_mail_thread.php new file mode 100644 index 000000000..440e4b7d3 --- /dev/null +++ b/functions/ticket_mail_thread.php @@ -0,0 +1,302 @@ +='); + } + return $ready; +} + +/** The subject of every email to a client about a ticket - "[TCK-12] Printer offline". $row has ticket_prefix, ticket_number and ticket_subject, raw. */ +function ticketEmailSubject(array $row) { + return '[' . ticketReference($row) . '] ' . trim((string) ($row['ticket_subject'] ?? '')); +} + +/* + * The ticket settings for its emails, read once - copy: one email, the watchers copied in (else + * one each); relay: a client's reply goes on to the watchers who didn't have it. Both on until + * the 4.2.6 update has made them, as they are by default after it. + */ +function ticketMailSettings() { + global $mysqli; + static $settings = null; + if ($settings === null) { + $row = ticketMailThreadReady() ? mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT config_ticket_email_copy, config_ticket_email_relay FROM settings WHERE company_id = 1")) : null; + $settings = ['copy' => intval($row['config_ticket_email_copy'] ?? 0) === 1, 'relay' => intval($row['config_ticket_email_relay'] ?? 0) === 1]; + } + return $settings; +} + +/* + * A Message-ID as kept - without its <>, trimmed, '' when it isn't one (no @, a space, too long). + */ +function ticketMailIdClean($message_id) { + $message_id = trim(trim((string) $message_id), '<>'); + if ($message_id === '' || strlen($message_id) > 255 || strpos($message_id, '@') === false || preg_match('/[\s<>"]/', $message_id)) { + return ''; + } + return $message_id; +} + +/** The Message-IDs in a header - In-Reply-To or References - in the order they are written, each once, cleaned (ticketMailIdClean()). */ +function ticketMailIdsIn($header) { + $ids = []; + // In <>, as they should be - or, from a mail program that leaves them off, each word with an @ + if (preg_match_all('/<([^<>\s]+)>/', (string) $header, $matches) || preg_match_all('/([^<>\s]+@[^<>\s]+)/', (string) $header, $matches)) { + foreach ($matches[1] as $message_id) { + $message_id = ticketMailIdClean($message_id); + if ($message_id !== '' && !in_array($message_id, $ids, true)) { + $ids[] = $message_id; + } + } + } + return $ids; +} + +/** Keep a Message-ID with a ticket - $ours for an email ITFlow sent. Once a ticket. */ +function ticketMailKeepId($ticket_id, $message_id, $ours = false) { + global $mysqli; + $ticket_id = intval($ticket_id); + $message_id = ticketMailIdClean($message_id); + if (!$ticket_id || $message_id === '' || !ticketMailThreadReady()) { + return; + } + mysqli_query($mysqli, "INSERT IGNORE INTO ticket_mail_threads SET mail_thread_ticket_id = $ticket_id, mail_thread_message_id = '" . mysqli_real_escape_string($mysqli, $message_id) . "', mail_thread_ours = " . ($ours ? 1 : 0)); +} + +/** The ticket a Message-ID is kept with - an email it has already, ITFlow's own or the client's. ticket_id, or 0. */ +function ticketMailIdTicket($message_id) { + global $mysqli; + $message_id = ticketMailIdClean($message_id); + if ($message_id === '' || !ticketMailThreadReady()) { + return 0; + } + return intval(mysqli_fetch_row(mysqli_query($mysqli, "SELECT mail_thread_ticket_id FROM ticket_mail_threads JOIN tickets ON ticket_id = mail_thread_ticket_id + WHERE mail_thread_message_id = '" . mysqli_real_escape_string($mysqli, $message_id) . "' ORDER BY mail_thread_id DESC LIMIT 1"))[0] ?? 0); +} + +/* + * Where a ticket's conversation stands, for the next email about it - ['in_reply_to' => the latest + * Message-ID on it, 'references' => the first and the latest few (TICKET_MAIL_REFERENCES), oldest + * first]. $answering, the Message-ID of the email being answered - a reply to a closed ticket - + * is the one it replies to. Empty before any email. + */ +function ticketMailThread($ticket_id, $answering = '') { + global $mysqli; + $ids = []; + if (ticketMailThreadReady()) { + $ticket_id = intval($ticket_id); + $first = mysqli_fetch_row(mysqli_query($mysqli, "SELECT mail_thread_message_id FROM ticket_mail_threads WHERE mail_thread_ticket_id = $ticket_id ORDER BY mail_thread_id LIMIT 1")); + $latest = mysqli_fetch_all(mysqli_query($mysqli, "SELECT mail_thread_message_id FROM ticket_mail_threads WHERE mail_thread_ticket_id = $ticket_id + ORDER BY mail_thread_id DESC LIMIT " . (TICKET_MAIL_REFERENCES - 1))); + $ids = array_reverse(array_column($latest, 0)); + if ($first && !in_array($first[0], $ids, true)) { + array_unshift($ids, $first[0]); + } + } + $answering = ticketMailIdClean($answering); + if ($answering !== '') { + $ids = array_values(array_diff($ids, [$answering])); + $ids[] = $answering; + $ids = array_slice($ids, -TICKET_MAIL_REFERENCES); + } + return ['in_reply_to' => $ids ? end($ids) : '', 'references' => $ids]; +} + +/* + * The headers of one email about a ticket, from $from_email - a new Message-ID, kept with the + * ticket, and In-Reply-To and References from where its conversation stood as the email was + * written ($thread, ticketMailThread()). [header => value], for emailQueue()'s headers. + */ +function ticketMailHeaders($ticket_id, $from_email, array $thread) { + global $config_base_url; + $from_email = (string) $from_email; + $domain = strtolower(trim(substr($from_email, strrpos($from_email, '@') !== false ? strrpos($from_email, '@') + 1 : strlen($from_email)))); + if (!preg_match('/^[a-z0-9.-]+\.[a-z]{2,}$/', $domain)) { + $domain = preg_replace('/[^a-z0-9.-]/', '', strtolower((string) parse_url('https://' . $config_base_url, PHP_URL_HOST))) ?: 'itflow.invalid'; + } + $message_id = 'itflow.' . intval($ticket_id) . '.' . bin2hex(random_bytes(10)) . '@' . $domain; + ticketMailKeepId($ticket_id, $message_id, true); + $headers = ['Message-ID' => "<$message_id>"]; + if (!empty($thread['in_reply_to'])) { + $headers['In-Reply-To'] = '<' . $thread['in_reply_to'] . '>'; + $headers['References'] = implode(' ', array_map(function ($id) { + return "<$id>"; + }, $thread['references'])); + } + return $headers; +} + +/* + * The ticket an email answers, by its headers - the first of the Message-IDs in its In-Reply-To, + * then in its References from the latest back, that is kept with a ticket (ticketMailKeepId()). + * ticket_id, or 0. + */ +function ticketMailHeaderTicket($in_reply_to, $references) { + global $mysqli; + if (!ticketMailThreadReady()) { + return 0; + } + $ids = array_values(array_unique(array_merge(ticketMailIdsIn($in_reply_to), array_reverse(ticketMailIdsIn($references))))); + $ids = array_slice($ids, 0, 50); + if (!$ids) { + return 0; + } + $found = []; + $sql = mysqli_query($mysqli, "SELECT mail_thread_message_id, mail_thread_ticket_id FROM ticket_mail_threads JOIN tickets ON ticket_id = mail_thread_ticket_id + WHERE mail_thread_message_id IN ('" . implode("', '", array_map(function ($id) use ($mysqli) { return mysqli_real_escape_string($mysqli, $id); }, $ids)) . "') ORDER BY mail_thread_id DESC"); + while ($row = mysqli_fetch_row($sql)) { + $found[strtolower($row[0])] = $found[strtolower($row[0])] ?? intval($row[1]); + } + foreach ($ids as $message_id) { + if (isset($found[strtolower($message_id)])) { + return $found[strtolower($message_id)]; + } + } + return 0; +} + +/* + * The ticket whose number is in a subject in brackets - "[TCK-12]", "Re: [ABC-0042] ..." - with the + * prefix that ticket was given, whatever the prefix is now. The first in the subject that is a + * ticket. ['ticket_id', 'reference'] or null. + */ +function ticketMailSubjectTicket($subject) { + global $mysqli; + if (!preg_match_all('/\[([^\[\]\s]{1,40})\]/', (string) $subject, $matches)) { + return null; + } + foreach ($matches[1] as $token) { + // Where the prefix ends and the number starts - each split of the digits at its end, as a prefix can end in one + if (!preg_match('/\d+$/', $token, $digits)) { + continue; + } + $splits = []; + for ($i = 0, $n = strlen($digits[0]); $i < $n && count($splits) < 10; $i++) { + $number = intval(substr($digits[0], $i)); + if ($number > 0 && $number <= 2147483647) { + $splits[$number][] = substr($token, 0, strlen($token) - $n + $i); + } + } + if (!$splits) { + continue; + } + $sql = mysqli_query($mysqli, "SELECT ticket_id, ticket_prefix, ticket_number FROM tickets WHERE ticket_number IN (" . implode(',', array_keys($splits)) . ") ORDER BY ticket_id DESC"); + while ($row = mysqli_fetch_assoc($sql)) { + foreach ($splits[intval($row['ticket_number'])] ?? [] as $prefix) { + if (strcasecmp(trim((string) $row['ticket_prefix']), $prefix) === 0) { + return ['ticket_id' => intval($row['ticket_id']), 'reference' => ticketReference($row)]; + } + } + } + } + return null; +} + +/* + * The people an email to a ticket was also to or copied to ($addresses, its To and Cc) made the + * ticket's watchers, so the rest of the conversation reaches them as it reaches whoever wrote it. + * Never whoever sent it ($sender), the ticket's contact, an agent, one of ITFlow's own addresses or + * another address at your own domain (emailOwnDomain()), nor a no-reply address. The ones added. + */ +function ticketMailCopiedWatchers($ticket_id, array $addresses, $sender) { + global $mysqli; + $ticket_id = intval($ticket_id); + $contact_email = strtolower(trim((string) (mysqli_fetch_row(mysqli_query($mysqli, "SELECT contact_email FROM tickets + JOIN contacts ON contact_id = ticket_contact_id WHERE ticket_id = $ticket_id"))[0] ?? ''))); + $sender = strtolower(trim((string) $sender)); + $emails = []; + foreach (ticketWatcherEmails($addresses) as $email) { + if ($email === $sender || $email === $contact_email || emailOwnAddress($email) || emailOwnDomain($email) + || preg_match('/do[\W_]*not[\W_]*reply|no[\W_]*reply/i', $email)) { + continue; + } + if (mysqli_num_rows(mysqli_query($mysqli, "SELECT 1 FROM users WHERE user_email = '" . escapeSql($email) . "' AND user_type = 1 AND user_archived_at IS NULL LIMIT 1"))) { + continue; + } + $emails[] = $email; + } + return ticketAddWatchers($ticket_id, array_slice($emails, 0, 20)); +} + +/* + * A client's reply - by email, text or in the portal - passed on to the people an agent's reply goes to + * (the ticket's To line, ticketReplyRecipients()) who didn't have it: not whoever wrote it, nor + * anyone it was already to or copied to ($had, addresses), nor the agents, who have their own email + * of it. When client replies are passed on (Admin > Settings > Tickets). $reply_id is the reply, + * as saved; $by who wrote it (raw); $answering the email's Message-ID. How many it went to. + */ +function ticketMailRelayClientReply($ticket_id, $reply_id, $by, $author_email, array $had = [], $answering = '') { + global $mysqli; + if (!emailReady() || !ticketMailSettings()['relay']) { + return 0; + } + $row = ticketRow($ticket_id); + $reply_id = intval($reply_id); + $reply = $reply_id ? mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT ticket_reply, ticket_reply_type FROM ticket_replies WHERE ticket_reply_id = $reply_id AND ticket_reply_ticket_id = " . intval($ticket_id))) : null; + if (!$row || !$reply || $reply['ticket_reply_type'] !== 'Client') { + return 0; + } + $skip = array_flip(array_map(function ($email) { + return strtolower(trim((string) $email)); + }, array_merge($had, [$author_email]))); + $recipients = []; + foreach (ticketReplyRecipients($ticket_id) as $email => $person) { + if ($person['send'] && $person['group'] !== 'agent' && !isset($skip[$email])) { + $recipients[] = $email; + } + } + if (!$recipients) { + return 0; + } + // Its files, as an agent's reply sends them - not the email itself, kept beside it + $attachments = []; + $sql = mysqli_query($mysqli, "SELECT ticket_attachment_name, ticket_attachment_reference_name FROM ticket_attachments + WHERE ticket_attachment_reply_id = $reply_id AND ticket_attachment_ticket_id = " . intval($ticket_id) . " AND ticket_attachment_name <> 'Original-parsed-email.eml'" + . (ticketPicturesReady() ? ' AND ticket_attachment_inline = 0' : '')); + while ($file = mysqli_fetch_assoc($sql)) { + $path = 'uploads/tickets/' . intval($ticket_id) . '/' . basename((string) $file['ticket_attachment_reference_name']); + if (is_file(dirname(__DIR__) . '/' . $path)) { + $attachments[] = ['path' => $path, 'name' => (string) $file['ticket_attachment_name'], 'size' => filesize(dirname(__DIR__) . '/' . $path)]; + } + } + // What they wrote - without the "Email from: ... :-" line the email parser puts on what it saves + $message = (string) preg_replace('#^\s*\s*Email from:.*?(\s*)*#is', '', (string) $reply['ticket_reply']); + return ticketMailSend($ticket_id, ticketEmailContent($row, 'client_reply', ['message' => $message, 'skip' => (string) $reply['ticket_reply'], 'by' => (string) $by]), [ + 'recipients' => ticketReplyRecipientsPick($ticket_id, $recipients, false), + 'attachments' => filterEmailableAttachments($attachments)['send'], + 'answering' => $answering, + ]); +} diff --git a/functions/ticket_mail_try.php b/functions/ticket_mail_try.php index af0a39761..666be30d9 100644 --- a/functions/ticket_mail_try.php +++ b/functions/ticket_mail_try.php @@ -8,7 +8,11 @@ * * 0. ITFlow's own email come back (emailOwnAddresses()) is skipped; * 1. an automatic reply (out of office) is skipped; - * 2. a ticket number in [brackets] in the subject - a reply on that ticket, + * - an email answering one of a ticket's emails, by its In-Reply-To or + * References - a reply on that ticket, whatever its subject. An email + * typed in here has no such headers, so this says so and goes on; + * 2. a ticket number in [brackets] in the subject, with the prefix that + * 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 watcher, or a stranger), or a closed one turned away; * 3. a subject almost the same as an open ticket of the sender's client from @@ -55,17 +59,18 @@ function ticketMailTry($from_email, $subject, $auto_reply = false) { } $steps[] = ['An automatic reply?', 'No']; - // 2. A ticket number in the subject - if (preg_match("/\[" . preg_quote($config_ticket_prefix, '/') . "(\d+)\]/", $subject, $m)) { - $reply = ticketMailTryReply($from_email, intval($m[1])); - if ($reply) { - $steps[] = ['A ticket number in the subject?', 'Yes - ' . $config_ticket_prefix . intval($m[1])]; - return ['steps' => $steps, 'outcome' => $reply]; - } - $steps[] = ['A ticket number in the subject?', $config_ticket_prefix . intval($m[1]) . ', but there is no such ticket - carries on']; - } else { - $steps[] = ['A ticket number in the subject?', 'No - it would be [' . $config_ticket_prefix . '123] somewhere in it']; + // A reply to one of a ticket's emails - by its headers, which an email typed in here hasn't got + $steps[] = ['A reply to one of a ticket\'s emails?', 'Not known here - an email answering one is matched by its headers first, whatever its subject says']; + + // 2. A ticket number in the subject, with the prefix that ticket was given + $numbered = ticketMailSubjectTicket($subject); + if ($numbered) { + $steps[] = ['A ticket number in the subject?', 'Yes - ' . $numbered['reference']]; + return ['steps' => $steps, 'outcome' => ticketMailTryReply($from_email, $numbered['ticket_id'])]; } + $steps[] = ['A ticket number in the subject?', preg_match('/\[[^\[\]\s]{0,40}\d\]/', $subject) + ? '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']; // The sender: a contact, or the client whose domain it is $contact = $from_email !== '' ? mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT contact_id, contact_name, contact_client_id, client_name FROM contacts @@ -80,7 +85,7 @@ function ticketMailTry($from_email, $subject, $auto_reply = false) { $client_id = $contact ? intval($contact['contact_client_id']) : ($domain_row ? intval($domain_row['domain_client_id']) : 0); $similar = null; if (strlen(escapeSql($subject)) > 10 && $client_id) { - $sql = mysqli_query($mysqli, "SELECT ticket_number, ticket_subject FROM tickets WHERE ticket_client_id = $client_id AND ticket_resolved_at IS NULL + $sql = mysqli_query($mysqli, "SELECT ticket_id, ticket_prefix, ticket_number, ticket_subject FROM tickets WHERE ticket_client_id = $client_id AND ticket_resolved_at IS NULL AND ticket_created_at >= DATE_SUB(NOW(), INTERVAL 7 DAY)"); while ($row = mysqli_fetch_assoc($sql)) { similar_text(strtolower(escapeSql($subject)), strtolower($row['ticket_subject']), $percent); @@ -90,8 +95,8 @@ function ticketMailTry($from_email, $subject, $auto_reply = false) { } } } - if ($similar && ($reply = ticketMailTryReply($from_email, intval($similar['ticket_number'])))) { - $steps[] = ['The same subject as an open ticket of theirs from the last week?', 'Yes - ' . $config_ticket_prefix . intval($similar['ticket_number'])]; + if ($similar && ($reply = ticketMailTryReply($from_email, intval($similar['ticket_id'])))) { + $steps[] = ['The same subject as an open ticket of theirs from the last week?', 'Yes - ' . ticketReference($similar)]; return ['steps' => $steps, 'outcome' => $reply]; } $steps[] = ['The same subject as an open ticket of theirs from the last week?', $client_id ? 'No' : 'No - they aren\'t a client\'s']; @@ -128,19 +133,19 @@ function ticketMailTry($from_email, $subject, $auto_reply = false) { } /* - * What a reply by email to ticket $ticket_number from $from_email would do (addReply() + * What a reply by email to ticket $ticket_id from $from_email would do (addReply() * in the parser) - [icon, tone, title, text] - or null when there is no such ticket. */ -function ticketMailTryReply($from_email, $ticket_number) { - global $mysqli, $config_ticket_prefix; +function ticketMailTryReply($from_email, $ticket_id) { + global $mysqli; $from_sql = escapeSql($from_email); - $ticket = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT ticket_id, ticket_number, ticket_subject, ticket_status, ticket_client_id, contact_email, contact_name, client_name + $ticket = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT ticket_id, ticket_prefix, ticket_number, ticket_subject, ticket_status, ticket_client_id, contact_email, contact_name, client_name FROM tickets LEFT JOIN contacts ON contact_id = ticket_contact_id LEFT JOIN clients ON client_id = ticket_client_id - WHERE ticket_number = " . intval($ticket_number) . " LIMIT 1")); + WHERE ticket_id = " . intval($ticket_id) . " LIMIT 1")); if (!$ticket) { return null; } - $reference = $config_ticket_prefix . intval($ticket['ticket_number']); + $reference = ticketReference($ticket); $on = $reference . ' - ' . $ticket['ticket_subject'] . ($ticket['client_name'] !== null ? ' (' . $ticket['client_name'] . ')' : ''); if (intval($ticket['ticket_status']) === 5) { return ['fa-ban', 'warning', "Not added - $reference is closed", diff --git a/functions/ticket_reply_recipients.php b/functions/ticket_reply_recipients.php index 84e73ffdf..c5df482c8 100644 --- a/functions/ticket_reply_recipients.php +++ b/functions/ticket_reply_recipients.php @@ -8,10 +8,13 @@ * colleagues who asked for every update (ticketMailSend()). The To line starts * with those same people; the agent it's assigned to, the client's other * contacts and any address typed in can be added, and anyone taken out. Whoever - * is in it gets the email, each told why. What was changed is kept for the + * is in it gets the email. A client's reply goes on to them too, those who + * didn't have it (ticketMailRelayClientReply()). What was changed is kept for the * ticket (ticket_mail_choices, 3.7.5), so its next email reply starts from the * same people - an address typed in stays while it stays in To. Moving the - * ticket to another client forgets it (ticketReplyRecipientsForget()). + * ticket to another client forgets it (ticketReplyRecipientsForget()). The + * email goes to the contact with the rest copied in (Cc), unless Admin > + * Settings > Tickets says one each (ticketMailSend()). * * Bulk replies, the API, and every other email about the ticket still go to * the usual people. @@ -133,10 +136,13 @@ function ticketReplyRecipients($ticket_id) { /** * The people posted in a ticket's To line ($posted, the addresses), kept for * the ticket where that differs from the usual, as emailQueue() takes them - - * each greeted by name and told why they get it. Anything that isn't an email - * address is left out, and past TICKET_REPLY_TO_MOST. + * each greeted by name, told why they get it, and with their group (the + * contact goes first in To, the rest copied in - ticketMailSend()). Anything + * that isn't an email address is left out, and past TICKET_REPLY_TO_MOST. + * $remember false keeps nothing for the ticket - a client's reply passed on + * to some of them (ticketMailRelayClientReply()). */ -function ticketReplyRecipientsPick($ticket_id, array $posted) { +function ticketReplyRecipientsPick($ticket_id, array $posted, $remember = true) { global $mysqli, $session_user_id; $ticket_id = intval($ticket_id); $list = ticketReplyRecipients($ticket_id); @@ -154,13 +160,15 @@ function ticketReplyRecipientsPick($ticket_id, array $posted) { return []; } $keep = []; - foreach (array_keys($list + $picked) as $email) { + foreach ($remember ? array_keys($list + $picked) : [] as $email) { $send = isset($picked[$email]); if ($send !== !empty($list[$email]['default'])) { $keep[] = "($ticket_id, '" . escapeSql($email) . "', " . ($send ? 1 : 0) . ", " . intval($session_user_id) . ")"; } } - mysqli_query($mysqli, "DELETE FROM ticket_mail_choices WHERE mail_choice_ticket_id = $ticket_id"); + if ($remember) { + mysqli_query($mysqli, "DELETE FROM ticket_mail_choices WHERE mail_choice_ticket_id = $ticket_id"); + } if ($keep) { mysqli_query($mysqli, "INSERT INTO ticket_mail_choices (mail_choice_ticket_id, mail_choice_email, mail_choice_send, mail_choice_by) VALUES " . implode(', ', array_slice($keep, 0, 200))); } @@ -183,6 +191,7 @@ function ticketReplyRecipientsPick($ticket_id, array $posted) { 'name' => $person['name'], 'greet' => in_array($person['group'], ['watcher', 'added'], true) ? '' : $person['name'], 'footnote' => $why[$person['group']] ?? "You get this because $company_name copied you in on ticket $reference.", + 'group' => $person['group'], ]; } return $recipients; diff --git a/functions/ticket_status.php b/functions/ticket_status.php index cb890acc1..321961317 100644 --- a/functions/ticket_status.php +++ b/functions/ticket_status.php @@ -531,8 +531,7 @@ function ticketStatusMovedByAgent($ticket_id, $from_status, $to_status) { $reply_id = intval(mysqli_insert_id($mysqli)); $sent = 0; if (intval($config_ticket_client_general_notifications) === 1) { - $sent = ticketMailSend($ticket_id, ($agent_name !== '' ? 'Ticket assigned' : 'Ticket update') . " - [" . ticketReference($ticket) . "] - " . $ticket['ticket_subject'], - ticketEmailContent($ticket, 'assigned', ['message' => $html, 'agent' => $agent_name]), ['ticket_reply_id' => $reply_id]); + $sent = ticketMailSend($ticket_id, ticketEmailContent($ticket, 'assigned', ['message' => $html, 'agent' => $agent_name]), ['ticket_reply_id' => $reply_id]); } if ($sent < 1) { // Nobody got it - a note saying they were told would be wrong