From 8dae372d57778855eaf6518b79433979c1517edb Mon Sep 17 00:00:00 2001 From: johnnyq Date: Wed, 2 Dec 2026 12:57:37 -0500 Subject: [PATCH] Reply type after posting and the reply box on return: a reply's Edit or Change Type offers Internal note, Public note and Email reply, which makes it public and emails it on Save and Email to the To line from its writer by name with their signature and files while the ticket is open, mail is set up, the contact has an address and it hasn't been emailed, counting a newly client-visible note as the first response and giving an unassigned ticket to its writer with a history line; drafts keep their reply type (DB 4.4.0) and coming back to a ticket with a draft or a timer that was already running opens the reply box on the draft's type or the last type picked there, else Internal note, without moving the page (ticketReplyFiles()); 26.12.4 changelog --- CHANGELOG.md | 6 +- admin/database_updates/4.4.0.php | 20 +++++ agent/ajax.php | 4 +- agent/js/ticket_reply_extras.js | 33 ++++++-- agent/modals/ticket/ticket_reply_edit.php | 86 +++++++++++++++++++-- agent/post/ticket.php | 92 ++++++++++++++++++++++- agent/ticket.php | 52 ++++++++++++- db.sql | 1 + functions/ticket_mail_thread.php | 30 +++++--- functions/ticket_reply_draft.php | 39 ++++++++-- 10 files changed, 322 insertions(+), 41 deletions(-) create mode 100644 admin/database_updates/4.4.0.php diff --git a/CHANGELOG.md b/CHANGELOG.md index 207b2a792..d02eb733c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,7 +6,7 @@ This file documents all notable changes made to ITFlow. ### Upgrading to 26.12.4 -Update from Maintenance > Update as usual. This release has two database changes: 4.3.8, which lets ITFlow remind clients before their autopay card expires - a setting for it, and on each saved card when it was last checked with Stripe, which reminders went out and the key in their link - and 4.3.9, which adds the table that keeps email routing rules. +Update from Maintenance > Update as usual. This release has three database changes: 4.3.8, which lets ITFlow remind clients before their autopay card expires - a setting for it, and on each saved card when it was last checked with Stripe, which reminders went out and the key in their link - 4.3.9, which adds the table that keeps email routing rules, and 4.4.0, which keeps the reply type with an unsent reply. ### New Features & Updates @@ -17,6 +17,8 @@ Update from Maintenance > Update as usual. This release has two database changes - Email routing rules, in Admin > Email Routing: pick an address or a domain - alerts@vendor.example, or vendor.example - and, if you like, words its subject has, and say where its new tickets go: a client and a contact, a category, a priority, an agent and a ticket template. A vendor's monitoring alerts about one client go to that client at High priority and land with the technician who looks after them, with the template's tasks already on the ticket. A rule decides the client over the sender's own contact or domain, and takes email even with tickets from unknown senders off. What it leaves as it is comes from its template. When more than one rule fits, the most exact wins - an address before a domain, a subdomain before its domain, and a rule with subject words before one without. Replies to a ticket still go on that ticket, Ignored Senders are still set aside first, and out-of-office replies are never routed. The sender is only answered and copied in when they are the ticket's contact, so a system's address isn't sent "we have your email" or every reply, and nobody at the client is emailed about an alert they didn't send. The agent a rule assigns is told, as when a ticket is assigned by hand. Each rule shows how many tickets it has routed and when the last was, and warns when it takes another client's contacts or domain, when Ignored Senders sets its email aside first, or when its client, contact, category, agent or template has been archived. Try an Email in Settings > Tickets shows which rule an email would meet and what it would do, and Email to ticket links to the page. - An agent's email to a client now comes from them by name: "Tess Tech | PittPC Support", at the ticket mailbox's address, so the client sees who wrote and their reply still goes on the ticket. That's their email replies, resolving a ticket with a note, closing one for no response, and the "your ticket is with" note. ITFlow's automatic emails - we have your email, closed, a booked visit - and emails to your team keep the mailbox's name. Admin > Mail > From addresses shows how it reads. - Try an Email in Settings > Tickets now asks the very questions the mailbox asks, in the same order, from the same code - so what it shows is what happens to the email. An out-of-office is now checked where the mailbox checks it, after the ticket number. +- Change who sees a reply after it's posted: a reply's ⋮ has Edit or Change Type, with Internal note, Public note and Email reply. Email reply makes it public and emails it when you click Save and Email - to the people in its To line, from whoever wrote it by name, with their signature and its files - as the reply box would. It's offered while the ticket isn't closed, mail is set up and the contact has an email address, until the reply has been emailed. A note the client can see now counts as the first response, and a ticket nobody had becomes its writer's, as with a reply from the reply box. The ticket's history says who changed it, and how. +- Coming back to a ticket with a reply on the go opens the reply box for you. An unsent reply - kept as a draft as you type - opens on the type you picked for it (internal note, public note, email or text) with your words in it. A ticket whose timer is still running opens on the type you picked last there in this browser, or Internal note. A timer that only started as you opened the ticket leaves the box shut, and the page isn't moved down to it. ### Bug Fixes @@ -38,6 +40,8 @@ Update from Maintenance > Update as usual. This release has two database changes - Email routing rules (DB 4.3.9, `email_routing_rules`): new `functions/mail_route.php`. A rule is `routing_rule_match` (an address or a domain, cleaned by `mailIgnoreClean()` and matched by `mailIgnoreMatches()`, so a domain takes its subdomains), optional `routing_rule_subject` (case-insensitive, whitespace-collapsed substring), and what it sets: `routing_rule_client_id`, `routing_rule_contact_id`, `routing_rule_category_id`, `routing_rule_priority`, `routing_rule_assigned_to`, `routing_rule_ticket_template_id` - 0 or '' for none - with a note, a hit count and `routing_rule_matched_at`. `mailRouteFind()` takes the most exact match (`mailRouteExactness()`: address, then more domain labels, then longer subject words, then the older rule); `mailRouteFor()` adds `mailRouteTargets()`, which re-checks each target (client and contact not archived and the contact the client's, category, active agent, template not archived) and lists what's `gone`. In `cron/ticket_email_parser.php` the rule is found after the thread, ticket-number and forward steps and never for an out-of-office; with a client it replaces `$picked`/`$domain_row`, its contact is the rule's, else the sender as that client's contact, and a client with no contact gets its own `addTicket()` call before the domain step. `$email['route']` carries the rule, with `quiet` when the sender isn't the ticket's contact (or a website form's visitor, or a new contact at a client's domain), and `$email['sender']` when the ticket's contact isn't the sender. `addTicket()` now sets priority, category, agent and billable from `mailRouteTicketFields()` (the rule's, else the template's), Open when assigned, logs the rule in the ticket history, runs `ticketTemplateFinish(..., true, true)` for the template, notifies and emails the assignee (`ticketMailAssigned()`), and when `quiet` skips the sender CC, the created email and `ticketMailColleaguesNew()`; the from line, audit, forged note and copied-CC exclusion use the sender. A quiet email is never a similar-subject reply (`linkSimilarTicket($new, $similar, 'route')`, whose third argument is now the reason - 'forward' or 'route'), step 6 runs for a routed email whatever `config_ticket_email_parse_unknown_senders` says, and the hit is counted only when a ticket was made. Admin page `admin/email_routing_rules.php` (standard list, search across sender, words, client, contact, category, agent, template and note), modal `admin/modals/email_routing_rule/email_routing_rule.php` (its contact list reloads from `agent/ajax.php?get_client_contacts`), handlers `admin/post/email_routing_rule.php` (`add_routing_rule`, `edit_routing_rule`, `delete_routing_rule`; `mailRouteReach()` for the other-clients warning). `ticketMailTry()` adds an "An email routing rule?" step and `ticketMailTryRoute()` for the outcome. - Agent's name in the From name: `ticketEmailFrom($agent_name = '')` in `functions/ticket.php` now takes the agent's name and gives `ticketEmailFromName($agent_name, $mailbox_name)` - "Agent | Mailbox", the agent alone when the mailbox has no name or the same one, the mailbox's name unchanged without an agent; line breaks, quotes and angle brackets are removed, HTML entities decoded, and it is cut to 255. `ticketMailSend()` reads the agent from its `ticket_reply_id` (`ticketReplyAgentName()`: a Public reply whose `ticket_reply_by` is a `user_type` 1 user) or a new `agent_name` option, which `ticketMailReply()` passes from `$by` when there is no reply id (the email previews). So the reply, `ticketMailResolved()` with a note, `ticketResolveNoResponse()` and the first-response "assigned" note in `ticketStatusMovedByAgent()` carry it; the created, closed, scheduled and client-reply-relay emails and `ticketMailAgents()` don't. No database change. - Where an email goes is decided in one place: `ticketMailDecide(array $in)` in new `functions/ticket_mail_decide.php`, used by `cron/ticket_email_parser.php` and `ticketMailTry()`. It takes raw facts - `from`, `from_name`, `subject`, `visitor` (a website form's Reply-To), `thread_ticket_id` (null when it can't be known), `automatic`, `forged`, `answers_ours` (null when unknown), `unprocessed`, `forward` - and runs steps 1-6 (thread, ticket number, the agent who may be forwarding, the routing rule, the sender's contact or domain, the out-of-office set-aside, similar subject, contact, routed client, client domain, unknown senders), returning `steps` ([question, answer], what Try an Email shows) and an `action` - `reply` (`ticket_id`, `by`), `ticket` (`client_id`, `client_name`, `contact`, `new_contact`, `picked`, `sender`, `similar`, `link_why`, `taken`), `set_aside` or `leave` (`why`, `not_ours`, `answers_unknown`) - with `agent`, `route` and `quiet`. The parser keeps its first checks (own address, bounce, ignored sender, Reply-To, duplicate Message-ID, Unprocessed Email asks), then carries the decision out; when `agent` is set it reads the forward and calls `ticketMailDecide()` again with `forward`, which skips steps 1-2 as before. `ticketMailTry()` keeps its own first checks and turns the decision into an outcome with `ticketMailTryOutcome()`. Changes in behaviour: the similar-subject check compares raw subjects and the CC lookup escapes the sender once (it was escaped twice, missing an address with an apostrophe), an out-of-office that isn't set aside is left in the inbox rather than going on to the similar-subject step, and a reply whose ticket vanished between the lookup and `addReply()` waits in Unprocessed Email instead of becoming a new ticket. +- Reply type after posting: `agent/modals/ticket/ticket_reply_edit.php` offers `Email` beside `Internal` and `Public` (while the ticket isn't closed, `config_smtp_provider` is set, the contact has an email address and `ticket_reply_emailed` isn't 1), with the ticket's To line (`ticketReplyRecipients()`). `edit_ticket_reply` saves it Public, appends the writer's `user_config_signature`, emails it with `ticketMailReply()` (from the writer by name via its `ticket_reply_id`, the To line by `ticketReplyRecipientsPick()`, its files by new `ticketReplyFiles()` in `functions/ticket_mail_thread.php`, which the client-reply relay now uses too) and `smsTicketReplyNotify()`. A reply that becomes Public, or is emailed, sets the first response when there is none and, with `ticketReplyAssigns()`, assigns an unassigned ticket to its writer (the editing agent when the writer isn't an active agent). The history line names the change. Refused emails say why: closed, emailed already, no mail, no contact email. +- Reply drafts keep their type (DB 4.4.0, `ticket_reply_drafts.draft_type`, NULL for older drafts): `ticketReplyDraftSave($ticket_id, $user_id, $html, $type = null)`, `ticketReplyDraft()` returns `type`, `agent/ajax.php?ticket_reply_draft` takes `type`, and `agent/js/ticket_reply_extras.js` sends the picked `public_reply_type` with each save (and beacon), saving again when the type changes with words in the box. `agent/ticket.php` puts `data-draft-type` on the reply form; as the page is drawn the composer opens (the `show` class, no focus or scroll) on the draft's type, or - when `localStorage[ticketId + '-startTime']` was there before the timer script ran - on `localStorage['ticket-reply-type-' + ticketId]`, kept as a type is picked and cleared on Cancel and on sending, else Internal note; a type that can't be used now (email with no contact address, an opted-out text) falls back to Internal note. The reply menu item reads Edit or Change Type. ## [26.12.3] diff --git a/admin/database_updates/4.4.0.php b/admin/database_updates/4.4.0.php new file mode 100644 index 000000000..0ee300d8b --- /dev/null +++ b/admin/database_updates/4.4.0.php @@ -0,0 +1,20 @@ + false]); exit; } - ticketReplyDraftSave($draft_ticket['ticket_id'], $session_user_id, (string) ($_POST['html'] ?? '')); + ticketReplyDraftSave($draft_ticket['ticket_id'], $session_user_id, (string) ($_POST['html'] ?? ''), $_POST['type'] ?? null); $kept = ticketReplyDraft($draft_ticket['ticket_id'], $session_user_id) !== null; echo json_encode(['ok' => true, 'kept' => $kept, 'time' => date('g:i A', strtotime(timezoneToView(date('Y-m-d H:i:s'))))]); exit; diff --git a/agent/js/ticket_reply_extras.js b/agent/js/ticket_reply_extras.js index db93fbdfb..a620628c6 100644 --- a/agent/js/ticket_reply_extras.js +++ b/agent/js/ticket_reply_extras.js @@ -2,9 +2,9 @@ * The ticket page's reply form (agent/ticket.php): * * - Drafts. What is typed is kept as it is written (agent/ajax.php ticket_reply_draft -> - * functions/ticket_reply_draft.php) - a moment after typing stops, and as the page is left - and - * the page puts it back in the reply box next time. Discard it drops it. Sending drops it too, - * on the server. + * functions/ticket_reply_draft.php) - a moment after typing stops, and as the page is left - with how + * it was to go (the reply type picked), and the page puts it back in the reply box next time, open + * on that type. Discard it drops it. Sending drops it too, on the server. * - Files dropped on the reply box go in its Attach files field. * - +15m, +30m and +1h add to Time worked. The timer stops at the new total, as it does when the * time is typed. @@ -56,8 +56,15 @@ var drafts = form.dataset.drafts === '1'; var saveTimer = null; var lastSaved = null; + var lastType = null; var sending = false; + // How it is to go - the reply type picked, '' while none is + function replyType() { + var picked = form.querySelector('input[name="public_reply_type"]:checked'); + return picked ? picked.value : ''; + } + function setStatus(text) { if (status) { status.textContent = text; @@ -67,11 +74,13 @@ function saveDraft() { saveTimer = null; var html = content(); - if (sending || lastSaved === null || html === lastSaved) { + var type = replyType(); + if (sending || lastSaved === null || (html === lastSaved && type === lastType)) { return; } - itflowPost('ajax.php', { ticket_reply_draft: 1, csrf_token: csrf, ticket_id: ticketId, html: html }, function (answer) { + itflowPost('ajax.php', { ticket_reply_draft: 1, csrf_token: csrf, ticket_id: ticketId, html: html, type: type }, function (answer) { lastSaved = html; + lastType = type; var ed = editor(); if (ed && content() === html) { ed.setDirty(false); @@ -100,6 +109,7 @@ var ed = editor(); if (ed) { lastSaved = ed.getContent(); + lastType = replyType(); // SetContent is a canned response or an AI rewrite going in ed.on('input change keyup SetContent Undo Redo', queueSave); return true; @@ -123,6 +133,7 @@ var textarea = document.getElementById('ticket_reply'); if (textarea) { lastSaved = textarea.value; + lastType = replyType(); textarea.addEventListener('input', queueSave); } return; @@ -136,7 +147,7 @@ return; } var html = content(); - if (html === lastSaved) { + if (html === lastSaved && replyType() === lastType) { return; } var data = new FormData(); @@ -144,6 +155,7 @@ data.append('csrf_token', csrf); data.append('ticket_id', ticketId); data.append('html', html); + data.append('type', replyType()); // As a file, past a web application firewall (js/http.js) if (window.itflowFields) { window.itflowFields.pack(data, ['html']); @@ -151,6 +163,15 @@ navigator.sendBeacon('ajax.php', data); }); + // Another type picked, with something written - kept with the draft, so it opens on it next time + form.querySelectorAll('input[name="public_reply_type"]').forEach(function (radio) { + radio.addEventListener('change', function () { + if (hasWords()) { + queueSave(); + } + }); + }); + var discard = form.querySelector('[data-reply-draft-discard]'); if (discard) { discard.addEventListener('click', function (e) { diff --git a/agent/modals/ticket/ticket_reply_edit.php b/agent/modals/ticket/ticket_reply_edit.php index fe3a4e01a..98e503705 100644 --- a/agent/modals/ticket/ticket_reply_edit.php +++ b/agent/modals/ticket/ticket_reply_edit.php @@ -1,15 +1,23 @@ -
-
+
+
> - + > - + + + + +
-
Public replies show in the client portal. Saving here never sends an email.
+
>Only your team can see this.
+
>The client can see this in the portal. No email is sent.
+ + +
+ + + + +
This was emailed to . They keep the email as it was sent - what you change here only changes the ticket. @@ -115,11 +156,42 @@ ob_start();
+ + " . escapeHtml(ticketMentionNames($told)) . " " . (count($told) === 1 ? 'was' : 'were') . " told" : '')); + // The client sees it now - as a reply from the reply box: the ticket's first response, and its writer's when nobody had it + $taken = false; + if ($ticket_reply_type === 'Public' && ($was_type !== 'Public' || $emailed_to)) { + if (empty($row['ticket_first_response_at'])) { + setTicketFirstResponse($ticket_id); + } + if (!intval($row['ticket_assigned_to']) && ticketReplyAssigns()) { + $assign_to = $writer_id && intval($written['user_status']) === 1 && $written['user_archived_at'] === null ? $writer_id : intval($session_user_id); + [$taken] = ticketChangeAssignee($ticket_id, $assign_to); + } + } + + // Its history says who changed who sees it + $whose = $writer_id && $writer_id === intval($session_user_id) ? 'their' : escapeSql($writer_name) . "'s"; + $kind_words = ['Internal' => 'internal note', 'Public' => 'public note']; + if ($emailed_to) { + logTicketHistory($ticket_id, "$session_name " . ($was_type === 'Internal' ? "made $whose internal note public and emailed it" : "emailed $whose public note") . " to $emailed_to " . ($emailed_to === 1 ? 'person' : 'people')); + } elseif ($ticket_reply_type !== $was_type && isset($kind_words[$was_type])) { + logTicketHistory($ticket_id, "$session_name made $whose " . $kind_words[$was_type] . ' ' . ($ticket_reply_type === 'Public' ? 'public' : 'internal')); + } + + logAudit("Ticket", "Reply", "$session_name edited a reply on ticket " . escapeSql(ticketReference($row)) . ($emailed_to ? " and emailed it to $emailed_to" : ''), $client_id, intval($row['ticket_id'])); + + $told_words = $told ? " - " . escapeHtml(ticketMentionNames($told)) . " " . (count($told) === 1 ? 'was' : 'were') . " told" : ''; + // Files too big for the email stay on the ticket - said with the rest, not in place of it + $skipped_words = $files_skipped ? ' - too large to email, so only on the ticket: ' . implode(', ', array_map(function ($file) { + return escapeHtml($file['name']); + }, $files_skipped)) . '' : ''; + $taken_words = $taken ? ' - the ticket is now assigned to ' . escapeHtml($writer_id && $assign_to === $writer_id ? $writer_name : 'you') : ''; + if ($email_refused !== '') { + flashAlert("Reply saved and made public, but not emailed - $email_refused" . $taken_words, 'warning'); + } elseif ($picked_type === 'Email' && !$emailed_to) { + flashAlert("Reply saved and made public, but not emailed - " . (!emailReady() ? 'mail isn\'t set up' : ($email_to === [] ? 'nobody was in To' : 'there\'s no contact or CC with an email address to send it to')) . $taken_words, 'warning'); + } elseif ($emailed_to) { + flashAlert("Reply saved and emailed to $emailed_to " . ($emailed_to === 1 ? 'person' : 'people') . $taken_words . $told_words . $skipped_words, $skipped_words !== '' ? 'warning' : 'success'); + } else { + flashAlert("Reply saved" . ($ticket_reply_type !== $was_type ? ($ticket_reply_type === 'Public' ? ' - the client can see it now, not emailed' : ' - only your team can see it now') : '') . $taken_words . $told_words); + } redirect(); diff --git a/agent/ticket.php b/agent/ticket.php index db1f2baa1..d88a69c32 100644 --- a/agent/ticket.php +++ b/agent/ticket.php @@ -864,7 +864,7 @@ if (isset($_GET['ticket_id'])) {
+ data-undo-seconds=""> @@ -901,7 +901,7 @@ if (isset($_GET['ticket_id'])) {
- Your unsent reply from is kept - pick how to send it to carry on, or discard it. + Your unsent reply from is kept below - carry on with it, or discard it.
@@ -1224,7 +1224,7 @@ if (isset($_GET['ticket_id'])) { - Edit + Edit or Change Type @@ -2381,9 +2381,23 @@ if (isset($ticket_is_open) && empty($ticket_closed_at)) { ?> }); } + // The type picked last on this ticket, in this browser - for coming back to it while its timer runs + const replyTicketId = ; + const replyTypeKey = 'ticket-reply-type-' + replyTicketId; + function rememberReplyType(type) { + try { + if (type === null) { + localStorage.removeItem(replyTypeKey); + } else { + localStorage.setItem(replyTypeKey, type); + } + } catch (e) {} + } + // Only ever opens. Switching Internal -> Public mid-draft must not throw the draft away. replyTypes.forEach(radio => radio.addEventListener('change', () => { showReplyType(radio.value); + rememberReplyType(radio.value); replyComposerCollapse.show(); })); @@ -2401,11 +2415,40 @@ if (isset($ticket_is_open) && empty($ticket_closed_at)) { ?> } }); + /* + * Back on a ticket with a reply on the go - an unsent reply kept as a draft, or its timer running from before this + * page (not one that only started now, with Start the timer on opening a ticket): the reply box is open, on the + * type it was - the draft's, else the one picked last here - and an internal note when neither is known or that + * type can't be used now. Opened as the page is drawn, without moving the page to it or taking the focus. + */ + const replyFormEl = replyComposer.closest('form'); + let replyTimerRunning = false; + let replyTypeRemembered = null; + try { + replyTimerRunning = !!localStorage.getItem(replyTicketId + '-startTime'); + replyTypeRemembered = localStorage.getItem(replyTypeKey); + } catch (e) {} + const replyDraftType = replyFormEl && replyFormEl.dataset.draftType !== undefined ? replyFormEl.dataset.draftType : null; + const replyOpenOn = replyDraftType !== null ? replyDraftType : (replyTimerRunning ? (replyTypeRemembered || '0') : null); + if (replyOpenOn !== null) { + let radio = document.querySelector('input[name="public_reply_type"][value="' + CSS.escape(replyOpenOn) + '"]'); + if (!radio || radio.disabled) { + radio = document.getElementById('public_reply_type_opt0'); + } + if (radio) { + radio.checked = true; + showReplyType(radio.value); + replyComposer.classList.add('show'); + replyComposer.dataset.openedOnReturn = replyDraftType !== null ? 'draft' : 'timer'; + } + } + const cancelReply = document.getElementById('cancelReply'); if (cancelReply) { cancelReply.addEventListener('click', function () { replyComposerCollapse.hide(); replyTypes.forEach(radio => { radio.checked = false; }); + rememberReplyType(null); }); } @@ -2426,7 +2469,10 @@ if (isset($ticket_is_open) && empty($ticket_closed_at)) { ?> replyToProblem.textContent = problem; replyToProblem.hidden = false; replyTo.scrollIntoView({ block: 'nearest' }); + return; } + // On its way - the next visit starts from nothing picked, not this type + rememberReplyType(null); }); } } diff --git a/db.sql b/db.sql index 912a5df9b..9e8f8e7c3 100644 --- a/db.sql +++ b/db.sql @@ -5118,6 +5118,7 @@ CREATE TABLE `ticket_reply_drafts` ( `ticket_id` int(11) NOT NULL, `user_id` int(11) NOT NULL, `draft_body` longtext NOT NULL, + `draft_type` tinyint(1) DEFAULT NULL, `draft_updated_at` datetime NOT NULL DEFAULT current_timestamp(), PRIMARY KEY (`ticket_id`,`user_id`), KEY `draft_updated_at` (`draft_updated_at`) diff --git a/functions/ticket_mail_thread.php b/functions/ticket_mail_thread.php index 02ab0608a..8e0e4432a 100644 --- a/functions/ticket_mail_thread.php +++ b/functions/ticket_mail_thread.php @@ -424,16 +424,7 @@ function ticketMailRelayClientReply($ticket_id, $reply_id, $by, $author_email, a 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)]; - } - } + $attachments = ticketReplyFiles($ticket_id, $reply_id); // 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]), [ @@ -443,3 +434,22 @@ function ticketMailRelayClientReply($ticket_id, $reply_id, $by, $author_email, a 'auto' => 'generated', ]); } + +/* + * A reply's files, to email with it - ['path' (from ITFlow's folder), 'name', 'size'] each: not the email it came in as + * (Original-parsed-email.eml), nor a picture shown inside it, and only those still on disk. + */ +function ticketReplyFiles($ticket_id, $reply_id) { + global $mysqli; + $files = []; + $sql = mysqli_query($mysqli, "SELECT ticket_attachment_name, ticket_attachment_reference_name FROM ticket_attachments + WHERE ticket_attachment_reply_id = " . intval($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 ($sql && ($file = mysqli_fetch_assoc($sql))) { + $path = 'uploads/tickets/' . intval($ticket_id) . '/' . basename((string) $file['ticket_attachment_reference_name']); + if (is_file(dirname(__DIR__) . '/' . $path)) { + $files[] = ['path' => $path, 'name' => (string) $file['ticket_attachment_name'], 'size' => filesize(dirname(__DIR__) . '/' . $path)]; + } + } + return $files; +} diff --git a/functions/ticket_reply_draft.php b/functions/ticket_reply_draft.php index 8ac4b9550..b8ae4fbe0 100644 --- a/functions/ticket_reply_draft.php +++ b/functions/ticket_reply_draft.php @@ -4,10 +4,14 @@ * ITFlow - reply drafts. The reply an agent is writing on a ticket is kept as they type * (agent/js/ticket_reply_extras.js posting to agent/ajax.php), one per agent per ticket, so leaving * the page, closing the browser or being signed out doesn't lose it. The ticket page puts it back - * in the reply box. It goes when the reply is sent (add_ticket_reply), when the agent discards it, + * in the reply box, and opens the box on how it was to go - an internal note, a public note, an email or a text reply + * (4.4.0, draft_type). It goes when the reply is sent (add_ticket_reply), when the agent discards it, * and nightly once it is a month old or its ticket is closed (cron/nightly_tasks.php). */ +/** The reply box's types - public_reply_type - a draft can have. */ +const TICKET_REPLY_DRAFT_TYPES = [0 => 'Internal note', 1 => 'Public note', 2 => 'Email reply', 3 => 'Text reply']; + /** Whether the 4.0.1 update has run - the ticket_reply_drafts table. */ function ticketReplyDraftsReady() { global $mysqli; @@ -24,19 +28,34 @@ function ticketReplyDraftsReady() { return $ready; } -/** An agent's draft on a ticket - ['body' (HTML, as typed), 'updated_at'] - or null. */ +/** Whether the 4.4.0 update has run - a draft keeps how it was to go (draft_type). */ +function ticketReplyDraftTypeReady() { + global $mysqli; + static $ready = null; + if ($ready === null) { + $version = defined('CURRENT_DATABASE_VERSION') ? CURRENT_DATABASE_VERSION + : (string) (mysqli_fetch_row(mysqli_query($mysqli, "SELECT config_current_database_version FROM settings WHERE company_id = 1"))[0] ?? '0'); + $ready = version_compare($version, '4.4.0', '>='); + } + return $ready; +} + +/** An agent's draft on a ticket - ['body' (HTML, as typed), 'type' (public_reply_type, or null), 'updated_at'] - or null. */ function ticketReplyDraft($ticket_id, $user_id) { global $mysqli; if (!ticketReplyDraftsReady()) { return null; } - $row = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT draft_body, draft_updated_at FROM ticket_reply_drafts + $row = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT draft_body, " . (ticketReplyDraftTypeReady() ? 'draft_type' : 'NULL AS draft_type') . ", draft_updated_at FROM ticket_reply_drafts WHERE ticket_id = " . intval($ticket_id) . " AND user_id = " . intval($user_id) . " LIMIT 1")); - return $row ? ['body' => (string) $row['draft_body'], 'updated_at' => $row['draft_updated_at']] : null; + return $row ? ['body' => (string) $row['draft_body'], 'type' => $row['draft_type'] !== null ? intval($row['draft_type']) : null, 'updated_at' => $row['draft_updated_at']] : null; } -/** Keep an agent's draft - made safe first. Nothing worth keeping (no words, no picture) drops it. */ -function ticketReplyDraftSave($ticket_id, $user_id, $html) { +/* + * Keep an agent's draft - made safe first - and how it was to go, $type (public_reply_type; null keeps what it had). + * Nothing worth keeping (no words, no picture) drops it. + */ +function ticketReplyDraftSave($ticket_id, $user_id, $html, $type = null) { global $mysqli; if (!ticketReplyDraftsReady()) { return false; @@ -50,8 +69,12 @@ function ticketReplyDraftSave($ticket_id, $user_id, $html) { $ticket_id = intval($ticket_id); $user_id = intval($user_id); $body = mysqli_real_escape_string($mysqli, $html); - mysqli_query($mysqli, "INSERT INTO ticket_reply_drafts SET ticket_id = $ticket_id, user_id = $user_id, draft_body = '$body', draft_updated_at = NOW() - ON DUPLICATE KEY UPDATE draft_body = '$body', draft_updated_at = NOW()"); + $type_sql = ''; + if (ticketReplyDraftTypeReady() && $type !== null && $type !== '' && isset(TICKET_REPLY_DRAFT_TYPES[intval($type)])) { + $type_sql = ', draft_type = ' . intval($type); + } + mysqli_query($mysqli, "INSERT INTO ticket_reply_drafts SET ticket_id = $ticket_id, user_id = $user_id, draft_body = '$body'$type_sql, draft_updated_at = NOW() + ON DUPLICATE KEY UPDATE draft_body = '$body'$type_sql, draft_updated_at = NOW()"); return true; }