From c8fa1ba3b457d1fbcf70110fb8a23e460eeb4666 Mon Sep 17 00:00:00 2001 From: johnnyq Date: Tue, 17 Nov 2026 17:54:20 -0500 Subject: [PATCH] Tickets: Email reply has a To line starting with the contact, watchers and colleagues who asked for every update, where the assigned agent, the client's other contacts or a typed address can be added and anyone taken out, and the choice is kept per ticket for its next email reply; moving a ticket to another client takes off watchers who are neither agents nor the new client's contacts; database 3.7.5 adds ticket_mail_choices; 26.11.9 changelog entries --- CHANGELOG.md | 5 +- admin/database_updates/3.7.5.php | 31 ++++ agent/post/ticket.php | 22 ++- agent/ticket.php | 71 +++++++++- db.sql | 18 +++ functions.php | 1 + functions/ticket.php | 21 ++- functions/ticket_reply_recipients.php | 196 ++++++++++++++++++++++++++ 8 files changed, 352 insertions(+), 13 deletions(-) create mode 100644 admin/database_updates/3.7.5.php create mode 100644 functions/ticket_reply_recipients.php diff --git a/CHANGELOG.md b/CHANGELOG.md index eee287db6..0b37d2bc4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,7 +6,7 @@ This file documents all notable changes made to ITFlow. ### Upgrading -Update from Maintenance > Update — Queue Update hands the job to cron, which updates the files and applies this release's eight database changes (3.6.6 to 3.7.4) in the same pass. They add four tables for RMM providers and their alerts, a setting for device actions and one for API keys in the address, a column marking the emails the mail queue clears once sent, a column and a table for agent banners, two columns for ticket statuses with a setting for the "ticket assigned" message, and a column on tickets with a setting for the "no response" message, and change nothing that is there. Nothing else is required. This release has eleven security fixes - see Security. On Apache, ITFlow's own .htaccess now sends security headers: if you show ITFlow inside a frame on another website, it will now refuse to load there. On nginx, add the same headers to your server block if you want them - see Developer Updates. +Update from Maintenance > Update — Queue Update hands the job to cron, which updates the files and applies this release's nine database changes (3.6.6 to 3.7.5) in the same pass. They add four tables for RMM providers and their alerts, a setting for device actions and one for API keys in the address, a column marking the emails the mail queue clears once sent, a column and a table for agent banners, two columns for ticket statuses with a setting for the "ticket assigned" message, a column on tickets with a setting for the "no response" message, and a table for who a ticket's email replies go to, and change nothing that is there. Nothing else is required. This release has eleven security fixes - see Security. On Apache, ITFlow's own .htaccess now sends security headers: if you show ITFlow inside a frame on another website, it will now refuse to load there. On nginx, add the same headers to your server block if you want them - see Developer Updates. ### Security @@ -82,6 +82,7 @@ Update from Maintenance > Update — Queue Update hands the job to cron, which u - Ticket Statuses: When the client replies can move a ticket to another status - a "Client responded" status, say, so the tickets with a new answer from the client stand out. It can be set on New, Open, On Hold and Resolved as well as your own statuses, for replies by email, in the portal or by text; back to Open is still the default. From Mountaineer IT's build of ITFlow. - Ticket Statuses: a status can count as the first response. An agent moving a ticket nobody has answered yet into it - setting it by hand or in a reply, or assigning a new ticket, which opens it - meets (or misses) the SLA's response target then. It can count quietly, or once the contact and watchers are emailed a "ticket assigned" message, kept on the ticket as a public note - an "Assigned" status, say. The message is set in Admin > Settings > Tickets, under Messages to clients. A client's own reply moving a ticket never counts. From Mountaineer IT's build of ITFlow. - Tickets: Resolve - no response, on the arrow beside a ticket's Resolve button, is for a client who never answered after several tries. It shows the message from Admin > Settings > Tickets filled in for the ticket, to change before it goes; the message goes on the ticket as a public note and, with client emails on, to the contact and watchers in place of the usual "resolved" words. The ticket is resolved and closes on its own as usual, but without the email asking how we did. If they reply before then, it reopens. From Mountaineer IT's build of ITFlow. +- Tickets: Email reply has a To line. It starts with the contact, the watchers and anyone at the client who asked for every update on their company's tickets; the technician it's assigned to, the client's other contacts or any email address typed in can be added, and anyone taken out. Everyone in To gets the email, each told why. What was changed is kept for the ticket, so its next email reply starts with the same people - taking a watcher out of To doesn't stop them watching. A reply sent to several tickets at once still goes to each one's contact and watchers. From Mountaineer IT's build of ITFlow. ### Bug Fixes @@ -124,6 +125,7 @@ Update from Maintenance > Update — Queue Update hands the job to cron, which u - Assets: moving assets to another client logged "created asset (via transfer)" without the asset's name. Found by Mountaineer IT. - New client: the duplicate warning took % and _ in the name you typed as wildcards, so a name with them in it could warn of a duplicate that isn't one. Found by Mountaineer IT. - Admin > Access Modules: the page stopped part way when sorted by a column it doesn't have, and its New Module button, and Edit and Delete on the AI module, went nowhere. Those are gone - modules are built in. Found by Mountaineer IT. +- Tickets: moving a ticket to another client left the old client's watchers on it, so they kept getting its emails. Watchers who aren't on your team or contacts at the new client now come off it, and the ticket's history says how many. Found by Mountaineer IT. ### Developer Updates @@ -194,6 +196,7 @@ Update from Maintenance > Update — Queue Update hands the job to cron, which u - `add_ticket` (`agent/post/ticket.php`) takes `status`, one of `ticketPickableStatuses()` (else New, or Open when assigned, as before), into the INSERT, so `applyTicketSla()` starts the SLA clock paused for a status that pauses it. `schedule` and `onsite` are booked with `ticketSetSchedule()` after the ticket's own emails; a `schedule` that `ticketScheduleValue()` can't read turns the form away before anything is saved. From Mountaineer IT's build of ITFlow. - Database 3.7.3: `ticket_statuses.ticket_status_reply_status_id` - 0, or the status a client's reply moves a ticket in it to; `ticketStatusAfterClientReply()` takes it while it is one of `ticketStatusReplyTargets()`, so a target switched off falls back, and deleting a status clears it from the others - and `ticket_status_first_response` (0, 1 or 2, `TICKET_STATUS_FIRST_RESPONSE`), and `settings.config_ticket_assigned_message` (NULL is `TICKET_ASSIGNED_MESSAGE`). The status form posts `client_reply` as `1`, `0` or `to-`, and `first_response`. `ticketStatusMovedByAgent($ticket_id, $from, $to)` is called where an agent moves a ticket - `ticketChangeStatus()`, `ticketChangeAssignee()`, `add_ticket`, `add_ticket_reply`, `bulk_ticket_reply`, `bulk_assign_ticket`, taking a text as a ticket and `ticket_replies/create`, not API ticket creation. With the email it inserts the message, filled by `cannedResponsePlaceholders()`, as a public note and sends it with `ticketEmailContent()`'s new `assigned` kind, keeping the note and calling `setTicketFirstResponse()` only when `ticketMailSend()` queued one. From Mountaineer IT's build of ITFlow. - Database 3.7.4: `tickets.ticket_no_response_at`, the `ticket_resolved_at` of a resolution that was "no response" - `ticketIsNoResponse()` while the two match, so a reopen and a later resolve leave it behind - and `settings.config_ticket_no_response_message` (NULL is `TICKET_NO_RESPONSE_MESSAGE`). `resolve_ticket_no_response` (`agent/post/ticket.php`, window `agent/modals/ticket/ticket_resolve_no_response.php`) checks the ticket is open with its tasks done, and `ticketResolveNoResponse()` inserts the message as a public note, calls `ticketResolve()` and sends `ticketEmailContent()`'s `resolved` kind with `no_response`, the message in place of its words. `ticketMailClosed()` sends nothing for such a ticket. The Resolve button is a group with a split arrow, and the group carries `data-ticket-resolve`, so ticking a task swaps it whole. From Mountaineer IT's build of ITFlow. +- Database 3.7.5: `ticket_mail_choices` - per ticket, the addresses put in or taken out of the To line where that differs from the default (the contact, watchers and `ticketColleagueRecipients()` in; the assigned agent, the client's other contacts and typed addresses out), going with the ticket. `functions/ticket_reply_recipients.php`: `ticketReplyRecipients()` lists who the To line offers, `ticketReplyRecipientsPick()` keeps the posted choice and returns `emailQueue()` recipients with why each gets it, `ticketReplyRecipientsForget()` clears it. `add_ticket_reply` sends to them when `email_to_shown` is posted with `email_to[]`, through `ticketMailReply()`'s new `$to` and `ticketMailSend()`'s `recipients` option; without it - the bulk reply, the API, an older form - to the contact and watchers as before. `change_client_ticket` takes off watchers who are neither agents nor the new client's contacts, and forgets the ticket's choices. From Mountaineer IT's build of ITFlow. ## [26.11.8] diff --git a/admin/database_updates/3.7.5.php b/admin/database_updates/3.7.5.php new file mode 100644 index 000000000..8496cd2d8 --- /dev/null +++ b/admin/database_updates/3.7.5.php @@ -0,0 +1,31 @@ +$emailed_to " . ($emailed_to === 1 ? 'person' : 'people')); } else { // They chose to email it - say plainly that it didn't go - flashAlert("Reply added to ticket $reference_html but not emailed - " . (emailReady() ? 'there\'s no contact or watcher with an email address to send it to' : 'mail isn\'t set up'), 'warning'); + flashAlert("Reply added to ticket $reference_html but not emailed - " . (!emailReady() ? 'mail isn\'t set up' : ($email_to === [] ? 'nobody was in To' : 'there\'s no contact or watcher with an email address to send it to')), 'warning'); } } else { @@ -1460,6 +1465,13 @@ if (isset($_POST['change_client_ticket'])) { mysqli_query($mysqli, "UPDATE tickets SET ticket_client_id = $client_id, ticket_contact_id = $contact_id, ticket_asset_id = 0, ticket_location_id = 0, ticket_vendor_id = $vendor_id, ticket_project_id = $project_id WHERE ticket_id = $ticket_id LIMIT 1"); mysqli_query($mysqli, "DELETE FROM ticket_assets WHERE ticket_id = $ticket_id"); + // Nobody at the old client hears about it any more: its watchers come off - all but our own + // agents and the new client's contacts - and its email replies' To line starts again + mysqli_query($mysqli, "DELETE FROM ticket_watchers WHERE watcher_ticket_id = $ticket_id + AND watcher_email NOT IN (SELECT user_email FROM users WHERE user_type = 1 AND user_archived_at IS NULL AND user_email IS NOT NULL) + AND watcher_email NOT IN (SELECT contact_email FROM contacts WHERE contact_client_id = $client_id AND contact_archived_at IS NULL AND contact_email IS NOT NULL)"); + $watchers_off = max(0, mysqli_affected_rows($mysqli)); + ticketReplyRecipientsForget($ticket_id); // The driving for it goes with it - not to the old client's site mysqli_query($mysqli, "UPDATE trips SET trip_client_id = $client_id, trip_location_id = 0 WHERE trip_ticket_id = $ticket_id"); applyTicketSla($ticket_id); @@ -1467,13 +1479,15 @@ if (isset($_POST['change_client_ticket'])) { $old_client_name = $old_client_id ? (string) getFieldById('clients', $old_client_id, 'client_name') : 'no client'; $new_client_name = (string) getFieldById('clients', $client_id, 'client_name'); - logTicketHistory($ticket_id, "$session_name moved the ticket from " . escapeSql($old_client_name) . " to " . escapeSql($new_client_name)); + logTicketHistory($ticket_id, "$session_name moved the ticket from " . escapeSql($old_client_name) . " to " . escapeSql($new_client_name) + . ($watchers_off ? " - $watchers_off watcher" . ($watchers_off === 1 ? '' : 's') . " of the old client taken off" : '')); logAudit("Ticket", "Change", "$session_name moved ticket " . escapeSql(ticketReference($row)) . " from " . escapeSql($old_client_name) . " to " . escapeSql($new_client_name), $client_id, $ticket_id); triggerCustomAction('ticket_update', $ticket_id); - flashAlert("Ticket " . escapeHtml(ticketReference($row)) . " moved to " . escapeHtml($new_client_name) . ""); + flashAlert("Ticket " . escapeHtml(ticketReference($row)) . " moved to " . escapeHtml($new_client_name) . "" + . ($watchers_off ? " - $watchers_off watcher" . ($watchers_off === 1 ? '' : 's') . " of the old client taken off" : '')); redirect(ticketUrl($ticket_id, $client_id)); diff --git a/agent/ticket.php b/agent/ticket.php index 0e0b2868a..630cb4085 100644 --- a/agent/ticket.php +++ b/agent/ticket.php @@ -451,6 +451,8 @@ if (isset($_GET['ticket_id'])) { // An emailed reply needs an address to go to and mail set up to send it - // without mail configured the option used to save as public and email nobody $can_email_reply = !empty($contact_email) && !empty($config_smtp_provider); + // Who it goes to - the To line, kept for the ticket (functions/ticket_reply_recipients.php) + $reply_to = $can_email_reply && $can_edit_ticket && $ticket_is_open && ticketReplyRecipientsReady() ? ticketReplyRecipients($ticket_id) : []; // A text reply - to its contact's mobile, or the number texting on it (functions/sms.php) $sms_recipient = smsTicketRecipient($ticket); @@ -839,7 +841,11 @@ if (isset($_GET['ticket_id'])) {
- + + + @@ -853,6 +859,27 @@ if (isset($_GET['ticket_id'])) {
+ + + + + if (replySubmitLabel) { replySubmitLabel.textContent = replySubmitLabels[type] || 'Send'; } + // The To line is for an email reply - and only then is it sent with the reply + if (replyTo) { + replyTo.hidden = type !== '2'; + replyTo.querySelector('[name="email_to_shown"]').disabled = type !== '2'; + replyToProblem.hidden = true; + } + } + + // What's wrong with the To line, if anything - nobody in it, or something that isn't an email address + const replyTo = document.getElementById('replyTo'); + const replyToSelect = document.getElementById('replyToSelect'); + const replyToProblem = document.getElementById('replyToProblem'); + function replyToCheck() { + if (!replyTo || replyTo.hidden) { + return ''; + } + const picked = Array.from(replyToSelect.selectedOptions).map(option => option.value.trim()); + const wrong = picked.filter(value => !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value)); + if (!picked.length) { + return 'Put someone in To - or pick Public note to post it without an email.'; + } + if (wrong.length) { + return 'Not an email address: ' + wrong.join(', ') + ' - take it out of To, or type the whole address.'; + } + return ''; + } + if (replyToSelect) { + replyToSelect.addEventListener('change', function () { + if (!replyToProblem.hidden) { + const problem = replyToCheck(); + replyToProblem.textContent = problem; + replyToProblem.hidden = problem === ''; + } + }); } // Only ever opens. Switching Internal -> Public mid-draft must not throw the draft away. @@ -2140,6 +2201,14 @@ if (isset($ticket_is_open) && empty($ticket_closed_at)) { ?> replyForm.addEventListener('submit', function (e) { if (!replyComposer.classList.contains('show')) { e.preventDefault(); + return; + } + const problem = replyToCheck(); + if (problem) { + e.preventDefault(); + replyToProblem.textContent = problem; + replyToProblem.hidden = false; + replyTo.scrollIntoView({ block: 'nearest' }); } }); } diff --git a/db.sql b/db.sql index 994313edc..e3ce236bd 100644 --- a/db.sql +++ b/db.sql @@ -4053,6 +4053,24 @@ CREATE TABLE `ticket_history` ( ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci; /*!40101 SET character_set_client = @saved_cs_client */; +-- +-- Table structure for table `ticket_mail_choices` +-- + +DROP TABLE IF EXISTS `ticket_mail_choices`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8mb4 */; +CREATE TABLE `ticket_mail_choices` ( + `mail_choice_ticket_id` int(11) NOT NULL, + `mail_choice_email` varchar(255) NOT NULL, + `mail_choice_send` tinyint(1) NOT NULL DEFAULT 0, + `mail_choice_by` int(11) NOT NULL DEFAULT 0, + `mail_choice_updated_at` datetime NOT NULL DEFAULT current_timestamp() ON UPDATE current_timestamp(), + PRIMARY KEY (`mail_choice_ticket_id`,`mail_choice_email`), + CONSTRAINT `ticket_mail_choices_ibfk_1` FOREIGN KEY (`mail_choice_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_replies` -- diff --git a/functions.php b/functions.php index dfe6cefa0..6f38648c8 100644 --- a/functions.php +++ b/functions.php @@ -108,6 +108,7 @@ require_once __DIR__ . '/functions/rmm.php'; require_once __DIR__ . '/functions/rmm_tactical.php'; require_once __DIR__ . '/functions/client_onboarding.php'; require_once __DIR__ . '/functions/ticket_mention.php'; +require_once __DIR__ . '/functions/ticket_reply_recipients.php'; require_once __DIR__ . '/functions/getting_started.php'; require_once __DIR__ . '/functions/settings.php'; require_once __DIR__ . '/functions/mail_queue.php'; diff --git a/functions/ticket.php b/functions/ticket.php index fe1dce71b..c85e0e6ed 100644 --- a/functions/ticket.php +++ b/functions/ticket.php @@ -578,6 +578,8 @@ function ticketEmailPreview(array $email) { * 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()) * 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 @@ -603,7 +605,10 @@ function ticketMailSend($ticket_id, $subject, array $email, array $opts = []) { $reference = ticketReference($row); $company_name = (string) (billingCompany()['company_name'] ?? 'us'); $recipients = []; - if (isset($opts['to'])) { + if (isset($opts['recipients'])) { + $recipients = (array) $opts['recipients']; + $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."]; } @@ -716,19 +721,21 @@ function ticketMailCreated($ticket_id, $subject_prefix, $attachments = [], $to_w } /* - * A public reply on a ticket, to its contact and watchers - $reply_html as - * saved (with the signature), $by who wrote it (raw). $resolved when the - * reply resolved it. $reply_id, the reply in ticket_replies, has who it went - * to kept with it (ticketReplyEmailed()). How many it went to. + * A public reply on a ticket, to its contact and watchers - or the people in + * its To line, $to (ticketReplyRecipientsPick()) - $reply_html as saved (with + * the signature), $by who wrote it (raw). $resolved when the reply resolved + * it. $reply_id, the reply in ticket_replies, has who it went to kept with it + * (ticketReplyEmailed()). How many it went to. */ -function ticketMailReply($ticket_id, $reply_html, $by, $resolved = false, $attachments = [], $reply_id = 0) { +function ticketMailReply($ticket_id, $reply_html, $by, $resolved = false, $attachments = [], $reply_id = 0, ?array $to = null) { $row = ticketRow($ticket_id); if (!$row) { 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]), ['attachments' => $attachments, 'ticket_reply_id' => intval($reply_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; } diff --git a/functions/ticket_reply_recipients.php b/functions/ticket_reply_recipients.php new file mode 100644 index 000000000..6f4b26533 --- /dev/null +++ b/functions/ticket_reply_recipients.php @@ -0,0 +1,196 @@ + 'Contact on the ticket', + 'watcher' => 'Watcher', + 'colleague' => 'Asked for every update', + 'agent' => 'Assigned agent', + 'client' => 'Contact at the client', + 'added' => 'Added before', +]; + +/** Whether the 3.7.5 update has run - ticket_mail_choices. Until it has, an email reply goes to the usual people. */ +function ticketReplyRecipientsReady() { + global $mysqli; + static $ready = null; + if ($ready === null) { + if (defined('CURRENT_DATABASE_VERSION')) { + $version = CURRENT_DATABASE_VERSION; + } else { + $result = mysqli_query($mysqli, "SELECT config_current_database_version FROM settings WHERE company_id = 1"); + $version = $result && ($row = mysqli_fetch_row($result)) ? (string) $row[0] : '0'; + } + $ready = version_compare($version, '3.7.5', '>='); + } + return $ready; +} + +/** + * Everyone the To line offers on a ticket, in order: [email (lower case) => [ + * 'name' their name, or '' + * 'group' contact, watcher, colleague, agent, client or added (TICKET_REPLY_TO_GROUPS) + * 'default' in To unless someone changed it - the contact, watchers and colleagues + * 'send' in To now - the default, or what was kept for the ticket + * 'look' their picture or initials, as picker option attributes (selectOptionData()) + * ]]. Each address once, under the first thing it is. + */ +function ticketReplyRecipients($ticket_id) { + global $mysqli; + $ticket_id = intval($ticket_id); + $ticket = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT ticket_client_id, ticket_contact_id, ticket_assigned_to FROM tickets WHERE ticket_id = $ticket_id")); + if (!$ticket) { + return []; + } + $client_id = intval($ticket['ticket_client_id']); + $list = []; + $add = function ($email, $name, $group, $default, $look = '') use (&$list) { + $email = strtolower(trim((string) $email)); + if ($email === '' || strlen($email) > 255 || !filter_var($email, FILTER_VALIDATE_EMAIL) || isset($list[$email])) { + return; + } + $list[$email] = ['name' => trim((string) $name), 'group' => $group, 'default' => $default, 'send' => $default, 'look' => $look]; + }; + + // The client's contacts, for their names and pictures wherever they turn up + $contacts = []; + $sql = mysqli_query($mysqli, "SELECT contact_id, contact_name, contact_email, contact_photo FROM contacts + WHERE " . ($client_id ? "contact_client_id = $client_id AND contact_archived_at IS NULL" : "0") . " AND contact_email != '' + OR contact_id = " . intval($ticket['ticket_contact_id']) . " + ORDER BY contact_primary DESC, contact_name LIMIT 1000"); + while ($row = mysqli_fetch_assoc($sql)) { + $contacts[strtolower(trim((string) $row['contact_email']))] = $row + ['look' => selectOptionContact($client_id, $row['contact_name'], $row['contact_photo'], '', $row['contact_id'])]; + } + $contact_named = function ($email, $name, $group, $default) use ($add, $contacts) { + $known = $contacts[strtolower(trim((string) $email))] ?? null; + $add($email, $known ? $known['contact_name'] : $name, $group, $default, $known ? $known['look'] : ''); + }; + + foreach ($contacts as $email => $contact) { + if (intval($contact['contact_id']) === intval($ticket['ticket_contact_id'])) { + $add($email, $contact['contact_name'], 'contact', true, $contact['look']); + } + } + $sql = mysqli_query($mysqli, "SELECT watcher_name, watcher_email FROM ticket_watchers WHERE watcher_ticket_id = $ticket_id ORDER BY watcher_id"); + while ($row = mysqli_fetch_assoc($sql)) { + $contact_named($row['watcher_email'], (string) $row['watcher_name'], 'watcher', true); + } + foreach (ticketColleagueRecipients($ticket_id, 'update') as $email => $colleague) { + $contact_named($email, $colleague['name'], 'colleague', true); + } + $assigned = intval($ticket['ticket_assigned_to']); + if ($assigned) { + $row = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT user_id, user_name, user_email, user_avatar FROM users + WHERE user_id = $assigned AND user_type = 1 AND user_status = 1 AND user_archived_at IS NULL LIMIT 1")); + if ($row) { + $add($row['user_email'], $row['user_name'], 'agent', false, selectOptionUser($row['user_id'], $row['user_name'], $row['user_avatar'])); + } + } + foreach ($contacts as $email => $contact) { + $add($email, $contact['contact_name'], 'client', false, $contact['look']); + } + + // What was changed for this ticket - and the addresses typed in, still in To + if (ticketReplyRecipientsReady()) { + $sql = mysqli_query($mysqli, "SELECT mail_choice_email, mail_choice_send FROM ticket_mail_choices WHERE mail_choice_ticket_id = $ticket_id ORDER BY mail_choice_updated_at, mail_choice_email"); + while ($row = mysqli_fetch_assoc($sql)) { + $email = strtolower((string) $row['mail_choice_email']); + $send = intval($row['mail_choice_send']) === 1; + if (isset($list[$email])) { + $list[$email]['send'] = $send; + } elseif ($send) { + $add($email, '', 'added', false); + if (isset($list[$email])) { + $list[$email]['send'] = true; + } + } + } + } + return $list; +} + +/** + * 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. + */ +function ticketReplyRecipientsPick($ticket_id, array $posted) { + global $mysqli, $session_user_id; + $ticket_id = intval($ticket_id); + $list = ticketReplyRecipients($ticket_id); + $picked = []; + foreach ($posted as $email) { + $email = strtolower(trim((string) $email)); + if ($email !== '' && strlen($email) <= 255 && filter_var($email, FILTER_VALIDATE_EMAIL) && count($picked) < TICKET_REPLY_TO_MOST) { + $picked[$email] = true; + } + } + + // Kept only where it differs from the usual - so an address typed in is kept while it's in To. + // Nobody in To sends nothing, and changes nothing + if (!$picked) { + return []; + } + $keep = []; + foreach (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 ($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))); + } + + $row = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT ticket_prefix, ticket_number, client_name FROM tickets LEFT JOIN clients ON client_id = ticket_client_id WHERE ticket_id = $ticket_id")); + $reference = $row ? ticketReference($row) : ''; + $client_name = trim((string) ($row['client_name'] ?? '')) !== '' ? (string) $row['client_name'] : 'your company'; + $company_name = (string) (billingCompany()['company_name'] ?? 'us'); + $why = [ + 'contact' => "You get this as the contact on ticket $reference with $company_name.", + 'watcher' => "You get this because you are watching ticket $reference - ask $company_name if you would like to stop.", + 'colleague' => "You get this because you asked for every update on $client_name's tickets - change that under Your account in the client portal.", + 'agent' => "You get this because ticket $reference is assigned to you.", + ]; + $recipients = []; + foreach (array_keys($picked) as $email) { + $person = $list[$email] ?? ['name' => '', 'group' => 'added']; + $recipients[] = [ + 'email' => $email, + '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.", + ]; + } + return $recipients; +} + +/** A ticket moved to another client - what its To line kept goes, so it starts again from the new client's people. */ +function ticketReplyRecipientsForget($ticket_id) { + global $mysqli; + if (ticketReplyRecipientsReady()) { + mysqli_query($mysqli, "DELETE FROM ticket_mail_choices WHERE mail_choice_ticket_id = " . intval($ticket_id)); + } +}