diff --git a/CHANGELOG.md b/CHANGELOG.md index 68522cb4b..b5ef33427 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 twelve 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, 4.2.6 keeps each ticket's email conversation together, 4.2.7 lets a reply from a CC say who sent it, 4.2.8 renames the watchers table for CCs, 4.2.9 lets the mail queue go at a pace your mail host takes, 4.3.0 lets contacts unsubscribe from bulk email, 4.3.1 encrypts the mail passwords and tokens, 4.3.2 keeps the email the ticket mailbox couldn't take, for your team to sort, and 4.3.3 adds Undo send and Reply-To for ticket emails. 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. Watchers are called CCs now. Emails about a ticket go to its contact with the CCs copied in, rather than one each - Admin > Settings > Tickets has the switch, under Emails about a ticket. On nginx, where ITFlow's .htaccess files aren't read, add `location ^~ /uploads/mail_unprocessed/ { deny all; }` beside the other private folders - it holds copies of the email kept for Unprocessed Email. Emailed and texted replies now wait 10 seconds on the ticket page, with Undo, before they go - Admin > Settings > Tickets sets how long, or turns it off. Ticket emails sent from another address than the mailbox ITFlow reads now ask for replies at that mailbox (Reply-To) - turn that off in the same place if the From address is an alias of that mailbox and you'd rather clients only saw it. +Update from Maintenance > Update as usual - this release has thirteen 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, 4.2.6 keeps each ticket's email conversation together, 4.2.7 lets a reply from a CC say who sent it, 4.2.8 renames the watchers table for CCs, 4.2.9 lets the mail queue go at a pace your mail host takes, 4.3.0 lets contacts unsubscribe from bulk email, 4.3.1 encrypts the mail passwords and tokens, 4.3.2 keeps the email the ticket mailbox couldn't take, for your team to sort, 4.3.3 adds Undo send and Reply-To for ticket emails, and 4.3.4 lets the links in emails stop working once they're done with and keeps your own wording for the emails about a ticket. 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. Watchers are called CCs now. Emails about a ticket go to its contact with the CCs copied in, rather than one each - Admin > Settings > Tickets has the switch, under Emails about a ticket. On nginx, where ITFlow's .htaccess files aren't read, add `location ^~ /uploads/mail_unprocessed/ { deny all; }` beside the other private folders - it holds copies of the email kept for Unprocessed Email. Emailed and texted replies now wait 10 seconds on the ticket page, with Undo, before they go - Admin > Settings > Tickets sets how long, or turns it off. Ticket emails sent from another address than the mailbox ITFlow reads now ask for replies at that mailbox (Reply-To) - turn that off in the same place if the From address is an alias of that mailbox and you'd rather clients only saw it. The links in emails that open a ticket, an invoice or a quote without signing in now stop working 90 days after it is done - a ticket closed, an invoice paid, a quote answered or run out - so after the update, links to ones done longer ago than that no longer open them. The client portal still shows them, and Admin > Settings > Security sets how long, or keeps them working as before. ### Security @@ -83,6 +83,8 @@ Update from Maintenance > Update as usual - this release has twelve database cha - From Unprocessed Email an email can be opened (as text - nothing in it loads), made a ticket at the client you pick - for one of their contacts, or with the sender made a contact there first - added to a ticket, with the sender made a CC on it if you like, tried again (after making them a contact, say), dismissed, or downloaded as a .eml file. Try Again and Dismiss also work on several at once. The ticket or reply is made within a minute, as any email is, attachments and all, and the email shows which ticket it went on. Sorted and dismissed email is kept 30 days, and email nobody sorts 90. - Undo send: an emailed or texted reply waits a few seconds under the reply box - "Emailing it in 10 seconds" - with Undo and Send now. Undo leaves it in the reply box, as it was, to change or send later: nothing about it has happened yet - no email, no status change, no time added. Escape undoes it too, and leaving the page while it waits asks first. Admin > Settings > Tickets, Emails about a ticket, sets how long - 5, 10 (to start), 20 or 30 seconds - or turns it off. A public or internal note goes at once, as before. - Replies to ticket emails come back: an email about a ticket sent from another address than the mailbox ITFlow reads - a no-reply address, or one that isn't delivered there - asks for replies at that mailbox (Reply-To), where a client's reply used to go to the From address and be lost if nobody read it. Admin > Settings > Tickets says which addresses it uses, and turns it off for a From address that is an alias of the mailbox. +- Links in emails stop working once they're done with: the link that opens a ticket, an invoice or a quote without signing in - in its emails, forwarded on or kept for years - stops working 90 days after the ticket is closed, the invoice paid in full, or the quote accepted, declined, invoiced or run out. Open tickets, unpaid invoices and quotes waiting for an answer always work, a reopened ticket's link works again, and emailing an invoice or quote again counts from then. An expired link says so and points to the client portal, where they're shown as always. On an invoice or a quote, Copy Client Link says Expired once it has. Admin > Settings > Security, Links in emails, sets 30, 60, 90 (to start), 180 days or a year - or never, as before. +- Your own wording for the emails about a ticket to clients: Admin > Settings > Mail > Previews has Edit Wording on each of the 13 - ticket opened, their email became a ticket, scheduled ticket, reply, resolved, closed, a client's reply passed on, added as a CC, new ticket at their company, approval needed, work booked, booked work cancelled and replied to a closed ticket. Change its subject, heading, opening and closing text, with words in square brackets filled in as it goes, as in canned responses - [Ticket], [Subject], [First Name], [Client], [Agent], [Company] and each email's own, such as [By] and [When]. The preview shows it at once, the list marks the ones you changed, and Use ITFlow's Wording puts one back. The subject always starts with the ticket's number, so replies still find it. ### Bug Fixes @@ -166,6 +168,7 @@ Update from Maintenance > Update as usual - this release has twelve database cha - Mail review stage 7a: database 4.3.1 widens config_smtp_password, config_imap_password and config_mail_oauth_client_secret to varchar(500) and encrypts what is saved. functions/mail_secret.php seals MAIL_SECRET_COLUMNS (the two passwords, the OAuth secret, refresh and access tokens, and config_mail_graph_token) with secretSeal($plain, 'mail') as RMM and identity provider secrets are - but keeps a value as typed when there is no key, as mail would otherwise stop. mailSecretOpen() reads an unsealed value as it is, so nothing breaks before it is sealed: load_global_settings.php, cron/mail_queue.php, cron/nightly_tasks.php and mailGraphToken() open them; settingsWrite() seals secret-kind mail columns; every token write (the parser's two refreshes, persistMailOauthTokens(), the Microsoft callback, the Test OAuth refresh, mailGraphToken()) goes through mailSecretSql(). mailSecretsSealAll() runs in the update and nightly; mailSecretProblem() is the Admin > Settings > Mail warning. Remote pictures: ticketHtmlForAgents($purifier, $html) purifies and then ticketRemoteImagesHold() moves an http(s) or // img src to data-remote-src (a blank GIF and .itflow-remote-image in its place) and a style with a remote url() to data-remote-style - in agent/ticket.php, the quick look and ticketWorkOrderHtml(); ticketRemoteImagesNote() and js/app.js show the note and put them back. login.php drops the SMTP host, port, encryption, username and password it loaded but never used. - Mail review stage 7b: database 4.3.2 adds email_unprocessed. functions/mail_unprocessed.php keeps an email the parser couldn't take - mailUnprocessedKeep($raw, $meta, $reason) writes its MIME to uploads/mail_unprocessed (denied to the web, as uploads/backups) and a row, one per Message-ID - and mailUnprocessedDecide() records an agent's ticket, reply, retry or dismiss (agent/email_unprocessed.php, agent/post/email_unprocessed.php). cron/ticket_email_parser.php appends mailUnprocessedAsked() to the run as MailUnprocessedMessage (functions/mail_unprocessed_message.php), a FileMessage whose move() is mailUnprocessedDone() with the ticket it went on and whose flags do nothing: a ticket or reply ask skips steps 1 to 6 for addTicket() at the chosen contact or client (or a new contact, as the domain match makes one) or addReply() on the chosen ticket (the sender added through ticketAddCcs() first, if asked); a retry goes the usual way. mailUnprocessedLeave() takes the unprocessed and exception branches - kept, then marked seen and moved to the ITFlow folder; flagged and unread as before when it can't be kept; an ask that fails waits again with the reason. mailUnprocessedCleanup() runs nightly. - Mail review stage 7c: database 4.3.3 adds settings.config_ticket_reply_undo_seconds (0, 5, 10, 20 or 30 - TICKET_REPLY_UNDO_CHOICES) and config_ticket_reply_to_read, read by ticketReplySendSettings() (functions/ticket_reply_send.php). Undo send is the ticket page alone: #ticketReplyForm's data-undo-seconds, and agent/js/ticket_reply_extras.js holds an emailed or texted reply's submit in a window listener - after the form's own checks and the canned response check on the document - with the reply card inert and the [data-reply-hold] bar, then requestSubmit()s it with holdOk, cannedSendAnyway and noTimeOk set; agent/post/ticket.php is unchanged. emailQueue() puts Reply-To (ticketMailReplyToRead(): email to ticket on, the setting on, the IMAP username an address and not From) in a thread email's headers; MAIL_QUEUE_HEADERS lets one bare address through and sendQueueEmail() gives it to addReplyTo(), so Graph's large-email draft carries it too. +- Mail review stage 7d: database 4.3.4 adds settings.config_guest_link_days (GUEST_LINK_DAYS_CHOICES, 90) and email_templates. functions/guest_link.php: guestLinkDoneAt() - ticket_closed_at; a Paid invoice's last unarchived payment (else its Paid history, else invoice_updated_at); an Accepted, Declined or Invoiced quote's history for it, or the end of quote_expire for one unanswered - later of that and the last history line with 'emailed' in it; guestLinkExpired() adds the days. ticketByGuestKey() returns null for an expired link, setting its new &$expired, so the guest ticket page, its attachments, its posts and its calendar file all refuse it; guest_view_invoice.php, guest_view_quote.php, the guest PDF exports (410) and the quote upload check it too, and guestLinkExpiredHtml() is the page; agent/invoice.php and agent/quote.php mark Copy Client Link Expired. functions/email_template.php: EMAIL_TEMPLATES (the 13 Tickets - to clients preview keys, with ITFlow's wording in placeholders), emailTemplateApply() replaces title, intro (paragraphs) and after where saved, filling [Placeholders] from emailTemplateValues() (ticketPlaceholderValues() and the email's own; empty when there is nothing), and puts the subject in template_subject for emailTemplateSubject(), which prefixes [REF] when it isn't in it. Applied in ticketEmailContent() (not the stranger's subject, nor Resolve - no response's intro), ticketMailSend(), ticketMailCcsAdded(), ticketMailColleaguesNew(), ticketMailTaskApproval() (the client's only) and ticketMailClosedReply(). admin/modals/email_template/email_template_edit.php and admin/post/email_template.php (save_email_template, reset_email_template - a part sent back as the default is NULL); mail_preview.php answers template and edited. ## [26.12.2] diff --git a/admin/database_updates/4.3.4.php b/admin/database_updates/4.3.4.php new file mode 100644 index 000000000..b4500a481 --- /dev/null +++ b/admin/database_updates/4.3.4.php @@ -0,0 +1,32 @@ + array_values(array_unique($others)), 'calendar' => !empty($email['cal_str']), 'html' => $email['html'] ?? '', + // Its wording can be changed - one of the emails about a ticket to clients (functions/email_template.php) + 'template' => isset(EMAIL_TEMPLATES[(string) ($_GET['email'] ?? '')]) && emailTemplateReady(), + 'edited' => emailTemplateEdited((string) ($_GET['email'] ?? '')), 'error' => $email ? '' : ($preview['error'] !== '' ? 'It could not be made: ' . $preview['error'] : 'Nothing would be sent with the sample records.'), ]); diff --git a/admin/modals/email_template/email_template_edit.php b/admin/modals/email_template/email_template_edit.php new file mode 100644 index 000000000..6761a7eb0 --- /dev/null +++ b/admin/modals/email_template/email_template_edit.php @@ -0,0 +1,99 @@ + Settings > Mail > Previews. Each field starts with the wording it sends + * now - yours, or ITFlow's own - and the words in square brackets are filled in as it goes. Saved by + * save_email_template (admin/post/email_template.php); Use ITFlow's Wording puts all of it back. + */ + +require_once '../../includes/modal_header.php'; + +$key = (string) ($_GET['key'] ?? ''); +if (!isset(EMAIL_TEMPLATES[$key]) || !emailTemplateReady()) { + echo json_encode(['error' => !emailTemplateReady() ? 'Your own wording arrives with the 4.3.4 database update.' : "That email's wording can't be changed."]); + exit; +} + +$label = (string) (emailPreviewCatalog()[$key]['label'] ?? $key); +$saved = emailTemplatesSaved()[$key] ?? []; +$value = function ($part) use ($key, $saved) { + return escapeHtml($saved[$part] ?? emailTemplateDefault($key, $part)); +}; +$edited = emailTemplateEdited($key); +$reference = escapeHtml(($config_ticket_prefix ?? 'TCK-') . '123'); + +ob_start(); + +?> + +
+ + + + +
+ + Settings > Mail > Previews, Edit Wording (admin/modals/email_template/email_template_edit.php): + * save_email_template keeps your own subject, heading, opening and closing text for one of the emails about a ticket + * to clients (functions/email_template.php) - each part sent back as ITFlow's own words, or a subject or heading left + * empty, is kept as none, so it follows ITFlow's own; an opening or closing text left empty leaves it out. + * reset_email_template puts all of it back to ITFlow's own. Both go back to the email's preview. + */ + +defined('FROM_POST_HANDLER') || die("Direct file access is not allowed"); + +if (isset($_POST['save_email_template']) || isset($_POST['reset_email_template'])) { + + validateCSRFToken(); + + $key = (string) ($_POST['email_template_key'] ?? ''); + if (!isset(EMAIL_TEMPLATES[$key]) || !emailTemplateReady()) { + flashAlert("That email's wording can't be changed", 'error'); + redirect('settings_mail.php?tab=previews'); + } + $label = (string) (emailPreviewCatalog()[$key]['label'] ?? $key); + $back = 'settings_mail.php?tab=previews&email=' . rawurlencode($key); + $key_sql = escapeSql($key); + + if (isset($_POST['reset_email_template'])) { + mysqli_query($mysqli, "DELETE FROM email_templates WHERE email_template_key = '$key_sql'"); + logAudit("Settings", "Edit", "$session_name put the wording of the email " . escapeSql($label) . " back to ITFlow's own"); + flashAlert("" . escapeHtml($label) . " uses ITFlow's own wording again"); + redirect($back); + } + + $set = []; + foreach (EMAIL_TEMPLATE_PARTS as $part => $length) { + $text = str_replace("\r", '', (string) ($_POST["email_template_$part"] ?? '')); + // One line for the subject and heading; trailing spaces off every line + $text = in_array($part, ['subject', 'title'], true) ? trim(preg_replace('/\s+/u', ' ', $text)) : trim(preg_replace('/[ \t]+$/m', '', $text)); + $text = mb_substr($text, 0, $length); + $own = $text === emailTemplateDefault($key, $part) || ($text === '' && in_array($part, ['subject', 'title'], true)); + $set[$part] = $own ? null : $text; + } + + if (count(array_filter($set, function ($text) { return $text !== null; })) === 0) { + mysqli_query($mysqli, "DELETE FROM email_templates WHERE email_template_key = '$key_sql'"); + } else { + // Kept as typed - it is plain text, escaped as each email is made (emailHtml()) + $sql = function ($text) use ($mysqli) { + return $text === null ? 'NULL' : "'" . mysqli_real_escape_string($mysqli, $text) . "'"; + }; + $columns = "email_template_subject = {$sql($set['subject'])}, email_template_title = {$sql($set['title'])}, email_template_intro = {$sql($set['intro'])}, + email_template_after = {$sql($set['after'])}, email_template_updated_by = " . intval($session_user_id) . ", email_template_updated_at = NOW()"; + mysqli_query($mysqli, "INSERT INTO email_templates SET email_template_key = '$key_sql', $columns ON DUPLICATE KEY UPDATE $columns"); + } + + logAudit("Settings", "Edit", "$session_name changed the wording of the email " . escapeSql($label)); + flashAlert("Wording saved for " . escapeHtml($label) . " - the preview shows it"); + + redirect($back); + +} diff --git a/admin/post/settings_security.php b/admin/post/settings_security.php index 591f9001e..a300e90fa 100644 --- a/admin/post/settings_security.php +++ b/admin/post/settings_security.php @@ -4,8 +4,9 @@ * Admin > Settings > Security (admin/settings_security.php): * edit_security_settings saves the sign-in page's message and login key, how * long a browser is remembered, whether passkeys sign people in, when admins - * hear of failed sign-ins, whether the API takes a key in the address, and - * shared links. A login key required with none set - which would leave + * hear of failed sign-ins, whether the API takes a key in the address, + * shared links, and how long the links in emails work once a ticket, invoice + * or quote is done. A login key required with none set - which would leave * agents no way in but the database - is refused, as is a key that couldn't * be typed into an address, or a time out of range. Nothing is saved then. * A choice not offered settles to the usual one. @@ -20,7 +21,9 @@ if (isset($_POST['edit_security_settings'])) { $before = settingsCurrent(array_merge(['config_login_message', 'config_login_key_required', 'config_login_key_secret', 'config_login_remember_me_expire', 'config_login_alert_failures', 'config_api_key_in_address', 'config_share_max_hours', 'config_share_require_protection'], // Passkeys, once the database has them (functions/passkey.php) - passkeysReady() ? ['config_login_passkeys'] : [])); + passkeysReady() ? ['config_login_passkeys'] : [], + // How long a done ticket's, invoice's or quote's link works (functions/guest_link.php) + guestLinkReady() ? ['config_guest_link_days'] : [])); // What was sent, and what is saved for anything that wasn't - a switch not sent is off $in = $_POST + array_map(function ($value) { return (string) $value; }, $before); @@ -38,6 +41,9 @@ if (isset($_POST['edit_security_settings'])) { if (array_key_exists('config_login_passkeys', $before)) { $after['config_login_passkeys'] = empty($_POST['config_login_passkeys']) ? 0 : 1; } + if (array_key_exists('config_guest_link_days', $before)) { + $after['config_guest_link_days'] = intval($in['config_guest_link_days']); + } $errors = []; if ($after['config_login_key_secret'] !== '' && !preg_match('/^\w{3,99}$/', $after['config_login_key_secret'])) { @@ -56,6 +62,9 @@ if (isset($_POST['edit_security_settings'])) { if (!isset(shareMaxOptions()[$after['config_share_max_hours']])) { $after['config_share_max_hours'] = 720; } + if (isset($after['config_guest_link_days']) && !isset(GUEST_LINK_DAYS_CHOICES[$after['config_guest_link_days']])) { + $after['config_guest_link_days'] = GUEST_LINK_DAYS_DEFAULT; + } if ($errors) { settingsRefuse('security', $errors); } diff --git a/admin/settings_mail.php b/admin/settings_mail.php index a87728d7d..0e3a94d37 100644 --- a/admin/settings_mail.php +++ b/admin/settings_mail.php @@ -4,7 +4,8 @@ * Admin > Settings > Mail - sending (an SMTP server, or Google Workspace / * Microsoft 365 by OAuth), receiving the mailbox email to ticket reads, the * OAuth app both share, the addresses and names emails come from, tests, and - * a preview of every email ITFlow sends. Each tab's form saves on its own + * a preview of every email ITFlow sends - with Edit Wording on the emails about a ticket to clients + * (functions/email_template.php). Each tab's form saves on its own * (admin/post/settings_mail.php), with the frame's save bar. Passwords, the * OAuth secret and its refresh token are never put back into the page: left * empty, they stay as saved. @@ -461,7 +462,7 @@ if (!$config_module_enable_ticketing) { $preview_entry) { ?> @@ -480,6 +481,10 @@ if (!$config_module_enable_ticketing) {
Calendar file attached
+ +
@@ -558,6 +563,9 @@ if (!$config_module_enable_ticketing) { 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 edit = card.querySelector('[data-preview-edit]'); + edit.classList.toggle('d-none', !data.template); + edit.setAttribute('data-modal-url', data.template ? 'modals/email_template/email_template_edit.php?key=' + encodeURIComponent(key) : ''); var error = card.querySelector('[data-preview-error]'); error.textContent = data.error || ''; error.classList.toggle('d-none', !data.error); diff --git a/admin/settings_security.php b/admin/settings_security.php index f3d8db543..0a4786286 100644 --- a/admin/settings_security.php +++ b/admin/settings_security.php @@ -69,6 +69,13 @@ echo settingsPageStart('security'); 'A shared password or secure note opens only with a passphrase the agent gives, or a code emailed to the person it is for.']) ?> + + + 'fa-link', + 'help' => 'This long after a ticket is closed, an invoice paid in full, or a quote accepted, declined, invoiced or run out. Open tickets, unpaid invoices and quotes still waiting always work, a ticket reopened works again, and emailing an invoice or quote again counts from then. The client portal always shows them.']) ?> + + +
diff --git a/agent/invoice.php b/agent/invoice.php index cbba9fab6..412823198 100644 --- a/agent/invoice.php +++ b/agent/invoice.php @@ -75,6 +75,8 @@ $billed_trips = $can_see_expenses ? tripsOnInvoice($invoice_id) : []; $unbilled_trips = $can_bill_expenses ? count(tripUnbilled($client_id)) : 0; $can_unbill_trips = $can_edit && tripCanUnbill($status); $guest_url = billingGuestUrl('invoice', $invoice); +// Done long enough ago, its link no longer opens it - emailing it again does (functions/guest_link.php) +$guest_expired = guestLinkExpired('invoice', $invoice['invoice_id']); // Hardware sold on it, and how much of it is on the client's assets (functions/products.php) $can_see_assets = lookupUserPermission('module_support') >= 1; $hardware = $can_see_assets ? productInvoiceHardware($invoice_id) : []; @@ -237,8 +239,8 @@ echo agentBannersHtml($client_id); Packing Slip - - Copy Client Link + > + Copy Client Link Expired View as Client diff --git a/agent/quote.php b/agent/quote.php index 6094a190d..11854fb67 100644 --- a/agent/quote.php +++ b/agent/quote.php @@ -57,6 +57,8 @@ $can_delete = lookupUserPermission('module_sales') >= 3; $can_edit_lines = billingCanEditItems('quote', $quote); $mail_ready = !empty($config_smtp_provider) && billingEmailableContacts('quote', $client_id) > 0; $guest_url = billingGuestUrl('quote', $quote); +// Done long enough ago, its link no longer opens it - emailing it again does (functions/guest_link.php) +$guest_expired = guestLinkExpired('quote', $quote['quote_id']); $csrf = $_SESSION['csrf_token']; // The ticket it was raised from, and what the client sent back with their answer @@ -187,8 +189,8 @@ echo agentBannersHtml($client_id); Print - - Copy Client Link + > + Copy Client Link Expired View as Client diff --git a/db.sql b/db.sql index e215fb5f5..6e44d8a50 100644 --- a/db.sql +++ b/db.sql @@ -1785,6 +1785,25 @@ CREATE TABLE `email_queue` ( ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci; /*!40101 SET character_set_client = @saved_cs_client */; +-- +-- Table structure for table `email_templates` +-- + +DROP TABLE IF EXISTS `email_templates`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8mb4 */; +CREATE TABLE `email_templates` ( + `email_template_key` varchar(50) NOT NULL, + `email_template_subject` varchar(255) DEFAULT NULL, + `email_template_title` varchar(255) DEFAULT NULL, + `email_template_intro` text DEFAULT NULL, + `email_template_after` text DEFAULT NULL, + `email_template_updated_by` int(11) NOT NULL DEFAULT 0, + `email_template_updated_at` datetime DEFAULT NULL, + PRIMARY KEY (`email_template_key`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + -- -- Table structure for table `email_unprocessed` -- @@ -4247,6 +4266,7 @@ CREATE TABLE `settings` ( `config_manager_ticket_category_id` int(11) NOT NULL DEFAULT 0, `config_share_max_hours` int(11) NOT NULL DEFAULT 720, `config_share_require_protection` tinyint(1) NOT NULL DEFAULT 0, + `config_guest_link_days` smallint(5) NOT NULL DEFAULT 90, `config_login_alert_failures` int(11) NOT NULL DEFAULT 10, `config_api_key_in_address` tinyint(1) NOT NULL DEFAULT 0, `config_app_log_retention` int(11) NOT NULL DEFAULT 90, diff --git a/functions.php b/functions.php index 1b7d1e6d1..879d3421a 100644 --- a/functions.php +++ b/functions.php @@ -150,6 +150,8 @@ require_once __DIR__ . '/functions/mail_queue.php'; require_once __DIR__ . '/functions/mail_secret.php'; require_once __DIR__ . '/functions/mail_unprocessed.php'; require_once __DIR__ . '/functions/ticket_reply_send.php'; +require_once __DIR__ . '/functions/guest_link.php'; +require_once __DIR__ . '/functions/email_template.php'; require_once __DIR__ . '/functions/mail_graph.php'; require_once __DIR__ . '/functions/purchase_orders.php'; require_once __DIR__ . '/functions/kb.php'; diff --git a/functions/email_template.php b/functions/email_template.php new file mode 100644 index 000000000..cd17a3ab9 --- /dev/null +++ b/functions/email_template.php @@ -0,0 +1,239 @@ + Settings > + * Mail > Previews, each changed there with Edit Wording (admin/modals/email_template/email_template_edit.php, + * admin/post/email_template.php). Database 4.3.4, table email_templates, by its preview's key. + * + * Each can have its own subject, heading, opening text and closing text - plain text with the words in square brackets + * filled in, as canned responses are: [Ticket], [Subject], [Contact], [First Name], [Client], [Agent], [Company], + * [Status], [Priority], and the email's own (EMAIL_TEMPLATES' extra) - [By], [When], [Task] and so on. A part not + * changed - NULL, or saved as ITFlow's own words - is ITFlow's own, as before. The opening and closing text can be + * left empty to leave them out; a blank line starts a new paragraph. The message, the summary, the button and the + * earlier messages are always there. + * + * The subject of every email about a ticket starts with its number in brackets - [TCK-123] - however it is worded, so + * a reply finds its ticket and the client's mail program keeps them together. To someone who isn't a contact, the + * "we have your email" answer keeps its fixed subject, and [Subject] is left empty in it: anyone can send an email + * that says it is from someone else, and their words would go to that person. + * + * Applied by emailTemplateApply() where each is made - ticketEmailContent(), ticketMailCcsAdded(), + * ticketMailColleaguesNew(), ticketMailTaskApproval() and ticketMailClosedReply() (functions/ticket.php) - and the + * subject by emailTemplateSubject(). The default words here are ITFlow's own, written with the placeholders - kept in + * step with those functions by hand. + */ + +const EMAIL_TEMPLATE_PLACEHOLDERS = [ + 'Ticket' => 'its number - TCK-123', + 'Subject' => "the ticket's subject", + 'Contact' => "the contact's name", + 'First Name' => "the contact's first name", + 'Client' => "the client's name", + 'Agent' => 'the agent it is assigned to', + 'Company' => 'your company', + 'Status' => "the ticket's status", + 'Priority' => "the ticket's priority", +]; + +const EMAIL_TEMPLATES = [ + 'ticket_created' => [ + 'title' => 'We have opened a ticket for you', + 'intro' => 'We have opened ticket [Ticket] for you. We will keep you posted here - to add anything, just reply to this email.', + ], + 'ticket_created_email' => [ + 'title' => 'We have your email', + 'intro' => 'Thank you - it is ticket [Ticket] now, and we will reply to you here. To add anything, just reply to this email.', + 'note' => 'To someone who isn\'t a contact, the subject is always [TCK-123] We have your email, and [Subject] is left out - anyone can send an email that says it is from someone else.', + ], + 'ticket_created_scheduled' => [ + 'title' => 'A scheduled ticket was opened for you', + 'intro' => 'Ticket [Ticket] was opened for you, as scheduled. We will keep you posted here - to add anything, just reply to this email.', + ], + 'ticket_reply' => [ + 'title' => '[Subject]', + 'intro' => 'There is a new reply on your ticket [Ticket].', + 'after' => 'To answer, just reply to this email.', + 'extra' => ['By' => 'who replied'], + ], + 'ticket_resolved' => [ + 'title' => 'Your ticket is resolved', + 'intro' => "We have marked ticket [Ticket] resolved.\n\nIf that sorts it, there is nothing more to do - it closes by itself after [Closes After]. If not, reply to this email or reopen it and tell us what is still wrong.", + 'extra' => ['By' => 'who resolved it', 'Closes After' => 'how long until it closes by itself - 3 days'], + 'note' => 'Resolve - no response sends the agent\'s message in place of the opening text.', + ], + 'ticket_closed' => [ + 'title' => 'Your ticket is closed', + 'intro' => 'Ticket [Ticket] is closed. We hope it was sorted the way you wanted.', + 'after' => 'Need more help with this? Raise a new ticket - a reply to this email isn\'t acted on, as the ticket is closed.', + ], + 'ticket_client_reply' => [ + 'title' => '[Subject]', + 'intro' => '[By] replied on ticket [Ticket].', + 'after' => 'To answer, just reply to this email.', + 'extra' => ['By' => 'who replied'], + ], + 'ticket_cc' => [ + 'title' => 'You were added to a ticket', + 'intro' => '[By] added you to ticket [Ticket] for [Client], so you will get its updates. To add anything, just reply to this email.', + 'extra' => ['By' => 'who added them'], + ], + 'ticket_colleague_new' => [ + 'title' => 'New ticket at [Client]', + 'intro' => '[Raised By] raised a ticket at [Client].', + 'extra' => ['Raised By' => 'who raised it - We, when it was your team'], + ], + 'ticket_approval' => [ + 'subject' => 'Ticket task approval required - [Subject]', + 'title' => 'Your approval is needed', + 'intro' => '[By] needs your approval for a task on ticket [Ticket] before the work goes ahead.', + 'after' => 'Want to know more first? Just reply to this email.', + 'extra' => ['By' => 'who asked', 'Task' => 'the task to approve'], + ], + 'ticket_scheduled' => [ + 'title' => 'Your ticket is booked in', + 'intro' => 'We have booked the work on ticket [Ticket] for [When]. The calendar file with this email adds it to your calendar.', + 'extra' => ['When' => 'when it is booked for', 'Where' => 'where - the site\'s address, or Remote'], + ], + 'ticket_schedule_cancelled' => [ + 'title' => 'The booked work is cancelled', + 'intro' => 'The work booked on ticket [Ticket] is cancelled - the calendar file with this email takes it out of your calendar. We will be in touch to book it again.', + ], + 'ticket_closed_reply' => [ + 'title' => 'That ticket is closed', + 'intro' => "You replied to ticket [Ticket] - \"[Subject]\" - which is closed. Your reply is kept with it, but the ticket isn't reopened, so nobody will act on it.\n\nTo raise a new ticket, send a new email to [Support Email].", + 'extra' => ['Support Email' => 'the ticket mailbox\'s address'], + ], +]; + +/** The parts of a template, and the longest each may be. */ +const EMAIL_TEMPLATE_PARTS = ['subject' => 255, 'title' => 255, 'intro' => 5000, 'after' => 5000]; + +/** Whether the 4.3.4 update has run - email_templates is there. */ +function emailTemplateReady() { + return function_exists('guestLinkReady') && guestLinkReady(); +} + +/** A template's own default words for $part - its subject, heading, opening or closing text - with the placeholders. */ +function emailTemplateDefault($key, $part) { + if (!isset(EMAIL_TEMPLATES[$key])) { + return ''; + } + if ($part === 'subject') { + return EMAIL_TEMPLATES[$key]['subject'] ?? '[Subject]'; + } + return (string) (EMAIL_TEMPLATES[$key][$part] ?? ''); +} + +/** The wording saved for every template - key => [part => text, or null for ITFlow's own], read once. */ +function emailTemplatesSaved($reload = false) { + global $mysqli; + static $saved = null; + if ($saved === null || $reload) { + $saved = []; + if (emailTemplateReady()) { + $sql = mysqli_query($mysqli, "SELECT email_template_key, email_template_subject, email_template_title, email_template_intro, email_template_after FROM email_templates"); + while ($sql && ($row = mysqli_fetch_assoc($sql))) { + $saved[(string) $row['email_template_key']] = ['subject' => $row['email_template_subject'], 'title' => $row['email_template_title'], + 'intro' => $row['email_template_intro'], 'after' => $row['email_template_after']]; + } + } + } + return $saved; +} + +/** Whether a template has any wording of your own. */ +function emailTemplateEdited($key) { + return !empty(array_filter(emailTemplatesSaved()[$key] ?? [], function ($text) { return $text !== null; })); +} + +/** The placeholders a template takes - name => what it becomes. */ +function emailTemplatePlaceholders($key) { + return EMAIL_TEMPLATE_PLACEHOLDERS + (array) (EMAIL_TEMPLATES[$key]['extra'] ?? []); +} + +/* + * The values for a ticket's placeholders - lower case name => raw text - with $extra (name => value) for the email's + * own. Every one a template takes is there, empty when there is nothing to put in, so none is left showing. + */ +function emailTemplateValues(array $ticket, array $extra = []) { + global $mysqli; + $values = ticketPlaceholderValues($ticket['ticket_id'] ?? 0); + $contact = trim((string) ($ticket['contact_name'] ?? $values['contact'] ?? '')); + $agent = trim((string) ($ticket['user_name'] ?? '')); + if ($agent === '' && intval($ticket['ticket_assigned_to'] ?? 0)) { + $agent = (string) (mysqli_fetch_row(mysqli_query($mysqli, "SELECT user_name FROM users WHERE user_id = " . intval($ticket['ticket_assigned_to'])))[0] ?? ''); + } + $out = [ + 'ticket' => ticketReference($ticket), + 'subject' => (string) ($ticket['ticket_subject'] ?? ''), + 'contact' => $contact, + 'first name' => $contact !== '' ? preg_split('/\s+/u', $contact)[0] : '', + 'client' => (string) ($ticket['client_name'] ?? $values['client'] ?? ''), + 'agent' => $agent, + 'company' => (string) (billingCompany()['company_name'] ?? ''), + 'status' => (string) ($ticket['ticket_status_name'] ?? ''), + 'priority' => (string) ($ticket['ticket_priority'] ?? ''), + ]; + foreach ($extra as $name => $value) { + $out[strtolower($name)] = (string) $value; + } + return $out; +} + +/* $text with the placeholders of $values filled in, whatever their case - each name in square brackets. Raw text. */ +function emailTemplateFill($text, array $values) { + if (!$values) { + return (string) $text; + } + $names = array_map(function ($name) { + return implode('\s+', array_map(function ($word) { return preg_quote($word, '/'); }, preg_split('/\s+/', $name))); + }, array_keys($values)); + return preg_replace_callback('/\[(' . implode('|', $names) . ')\]/iu', function ($match) use ($values) { + return $values[strtolower(preg_replace('/\s+/u', ' ', $match[1]))] ?? $match[0]; + }, (string) $text); +} + +/* Paragraphs - a blank line between them - each trimmed, the empty ones dropped. */ +function emailTemplateParagraphs($text) { + return array_values(array_filter(array_map('trim', preg_split('/\n\s*\n/', str_replace("\r", '', (string) $text))), function ($paragraph) { + return $paragraph !== ''; + })); +} + +/* + * $email (emailHtml()'s fields) with your own wording for template $key, where you changed it: the heading, the + * opening text (intro) and the closing text (after), filled in from $values (emailTemplateValues()). $skip names parts + * not to change. The subject goes in $email['template_subject'], for emailTemplateSubject(). + */ +function emailTemplateApply($key, array $email, array $values, array $skip = []) { + $saved = emailTemplatesSaved()[$key] ?? null; + if (!$saved) { + return $email; + } + if ($saved['title'] !== null && trim($saved['title']) !== '' && !in_array('title', $skip, true)) { + $email['title'] = trim(emailTemplateFill($saved['title'], $values)); + } + foreach (['intro', 'after'] as $part) { + if ($saved[$part] !== null && !in_array($part, $skip, true)) { + $email[$part] = emailTemplateParagraphs(emailTemplateFill($saved[$part], $values)); + } + } + if ($saved['subject'] !== null && trim($saved['subject']) !== '' && !in_array('subject', $skip, true)) { + $email['template_subject'] = trim(preg_replace('/\s+/u', ' ', emailTemplateFill($saved['subject'], $values))); + } + return $email; +} + +/* + * The subject of an email about a ticket ($ticket): your own (emailTemplateApply()'s template_subject in $email), with + * the ticket's number in brackets first when it hasn't it already - else $built_in. Takes template_subject out of $email. + */ +function emailTemplateSubject(array $ticket, array &$email, $built_in) { + $subject = trim((string) ($email['template_subject'] ?? '')); + unset($email['template_subject']); + if ($subject === '') { + return (string) $built_in; + } + $reference = '[' . ticketReference($ticket) . ']'; + return mb_stripos($subject, $reference) !== false ? $subject : "$reference $subject"; +} diff --git a/functions/guest_link.php b/functions/guest_link.php new file mode 100644 index 000000000..c5451336b --- /dev/null +++ b/functions/guest_link.php @@ -0,0 +1,113 @@ + Settings > Security, 4.3.4) after the thing is done: + * a ticket after it was closed (ticket_closed_at) - reopened, it works again + * an invoice after it was paid in full - its last payment + * a quote after it was accepted, declined or invoiced, or ran out (quote_expire) without an answer + * Emailed again since, it counts from then - a paid invoice sent again works for as long again. An open ticket, an + * unpaid invoice and a quote still waiting for an answer always work. 0 days keeps them all working, as before. + * + * Checked by ticketByGuestKey() (functions/ticket.php) for every guest ticket page and action, and by the guest + * invoice and quote pages and their PDFs (guest/). An expired link says so (guestLinkExpiredHtml()), and where the + * client portal is on, points there - signed in, they see it as ever. + */ + +const GUEST_LINK_DAYS_CHOICES = [0 => 'Never - they keep working', 30 => '30 days', 60 => '60 days', 90 => '90 days', 180 => '180 days', 365 => 'A year']; +const GUEST_LINK_DAYS_DEFAULT = 90; + +/** Whether the 4.3.4 update has run - the setting is there. */ +function guestLinkReady() { + 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.3.4', '>='); + } + return $ready; +} + +/** How many days a done ticket's, invoice's or quote's link keeps working - 0 for always. */ +function guestLinkDays() { + global $mysqli; + static $days = null; + if ($days === null) { + $days = guestLinkReady() ? intval(mysqli_fetch_row(mysqli_query($mysqli, "SELECT config_guest_link_days FROM settings WHERE company_id = 1"))[0] ?? 0) : 0; + $days = isset(GUEST_LINK_DAYS_CHOICES[$days]) ? $days : GUEST_LINK_DAYS_DEFAULT; + } + return $days; +} + +/* + * When a ticket ('ticket'), invoice or quote ($id) was done, for its link - 'Y-m-d H:i:s', or '' while it isn't + * (an open ticket, an unpaid invoice, a quote waiting for an answer). Emailed since, then. + */ +function guestLinkDoneAt($type, $id) { + global $mysqli; + $id = intval($id); + $done = ''; + if ($type === 'ticket') { + $done = (string) (mysqli_fetch_row(mysqli_query($mysqli, "SELECT ticket_closed_at FROM tickets WHERE ticket_id = $id"))[0] ?? ''); + return $done; + } + if ($type === 'invoice') { + $row = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT invoice_status, invoice_updated_at, invoice_created_at FROM invoices WHERE invoice_id = $id")); + if (!$row || $row['invoice_status'] !== 'Paid') { + return ''; + } + // Its last payment - else the history saying it was paid, else when it last changed + $done = (string) (mysqli_fetch_row(mysqli_query($mysqli, "SELECT MAX(payment_created_at) FROM payments WHERE payment_invoice_id = $id AND payment_archived_at IS NULL"))[0] ?? ''); + if ($done === '') { + $done = (string) (mysqli_fetch_row(mysqli_query($mysqli, "SELECT MAX(history_created_at) FROM history WHERE history_invoice_id = $id AND history_status = 'Paid'"))[0] ?? ''); + } + $done = $done !== '' ? $done : (string) ($row['invoice_updated_at'] ?: $row['invoice_created_at']); + $history = "history_invoice_id = $id"; + } elseif ($type === 'quote') { + $row = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT quote_status, quote_expire, quote_updated_at, quote_created_at FROM quotes WHERE quote_id = $id")); + if (!$row) { + return ''; + } + if (in_array($row['quote_status'], ['Accepted', 'Declined', 'Invoiced'], true)) { + $done = (string) (mysqli_fetch_row(mysqli_query($mysqli, "SELECT MAX(history_created_at) FROM history WHERE history_quote_id = $id + AND history_recurring_invoice_id = 0 AND history_status IN ('Accepted', 'Declined', 'Cancelled', 'Invoiced')"))[0] ?? ''); + $done = $done !== '' ? $done : (string) ($row['quote_updated_at'] ?: $row['quote_created_at']); + } elseif (!empty($row['quote_expire']) && strtotime($row['quote_expire']) < strtotime('today')) { + // Ran out without an answer - at the end of its last day + $done = date('Y-m-d 23:59:59', strtotime($row['quote_expire'])); + } else { + return ''; + } + $history = "history_quote_id = $id AND history_recurring_invoice_id = 0"; + } else { + return ''; + } + // Emailed again since - it counts from then + $emailed = (string) (mysqli_fetch_row(mysqli_query($mysqli, "SELECT MAX(history_created_at) FROM history WHERE $history AND history_description LIKE '%emailed%'"))[0] ?? ''); + return $emailed !== '' && strtotime($emailed) > strtotime($done) ? $emailed : $done; +} + +/** Whether a ticket's, invoice's or quote's link has stopped working - done, and that long ago. */ +function guestLinkExpired($type, $id) { + $days = guestLinkDays(); + if ($days <= 0) { + return false; + } + $done = guestLinkDoneAt($type, $id); + return $done !== '' && strtotime($done) + $days * 86400 < time(); +} + +/* The page an expired link opens - what it was for, and where to see it now: the client portal, when it is on. */ +function guestLinkExpiredHtml($type) { + global $config_client_portal_enable, $config_base_url; + $what = ['ticket' => 'ticket', 'invoice' => 'invoice', 'quote' => 'quote'][$type] ?? 'link'; + $icon = ['ticket' => 'fa-life-ring', 'invoice' => 'fa-file-invoice-dollar', 'quote' => 'fa-comment-dollar'][$type] ?? 'fa-link'; + $portal = !empty($config_client_portal_enable); + $text = "Links to a $what stop working a while after it is done, so an old email can't open it. " + . ($portal ? 'Sign in to the client portal to see it, or ask us for a new link.' : 'Ask us if you need it again.'); + return '
' + . '

This ' . $what . ' link has expired

' . escapeHtml($text) . '

' + . ($portal ? '
Client portal' : '') + . '
'; +} diff --git a/functions/settings.php b/functions/settings.php index 930bd9402..aab5d3b85 100644 --- a/functions/settings.php +++ b/functions/settings.php @@ -422,6 +422,8 @@ function settingsFields() { 'config_login_alert_failures' => ['page' => 'security', 'section' => 'Failed sign-ins', 'label' => 'Tell admins', 'kind' => 'select', 'options' => 'sign_in_alerts', 'words' => 'failed login brute force lockout alert'], 'config_api_key_in_address' => ['page' => 'security', 'section' => 'API keys', 'label' => 'Take API keys in the address', 'words' => 'api key address url query string api_key header x-api-key access log'] + $on_off, 'config_share_max_hours' => ['page' => 'security', 'section' => 'Shared links', 'label' => 'Longest a shared link can last', 'kind' => 'select', 'options' => 'share_max', 'words' => 'share link expiry guest'], + 'config_guest_link_days' => ['page' => 'security', 'section' => 'Links in emails', 'label' => 'Links stop working', 'kind' => 'select', 'options' => GUEST_LINK_DAYS_CHOICES, + 'words' => 'guest link url key expire expiry old email ticket invoice quote public link stop working days'], 'config_share_require_protection' => ['page' => 'security', 'section' => 'Shared links', 'label' => 'Shared passwords need a passphrase or code', 'words' => 'share passphrase code protect'] + $on_off, // Client portal diff --git a/functions/ticket.php b/functions/ticket.php index 95663f0c5..a76574a49 100644 --- a/functions/ticket.php +++ b/functions/ticket.php @@ -357,10 +357,19 @@ function ticketEmailUrl(array $row) { * on, so it is compared here, whole and case for case: MySQL's = would let * another case or trailing spaces match. */ -function ticketByGuestKey($ticket_id, $url_key) { +function ticketByGuestKey($ticket_id, $url_key, &$expired = null) { + $expired = false; $row = ticketRow($ticket_id); $key = (string) ($row['ticket_url_key'] ?? ''); - return $row && $key !== '' && is_string($url_key) && hash_equals($key, $url_key) ? $row : null; + if (!$row || $key === '' || !is_string($url_key) || !hash_equals($key, $url_key)) { + return null; + } + // Closed long enough ago, the link has stopped working (functions/guest_link.php) - $expired says so + if (guestLinkExpired('ticket', $row['ticket_id'])) { + $expired = true; + return null; + } + return $row; } /** @@ -701,6 +710,25 @@ function ticketEmailContent(array $row, $kind, array $opts = []) { $email['summary'] = $summary; $email['history'] = ticketEmailHistory($row, ['request' => false, 'label' => 'Replies so far']); } + + // Your own wording for it, where you changed it (functions/email_template.php) - to someone who isn't a contact, never + // their subject; Resolve - no response's message is its opening + $template = [ + 'created' => ['agent' => 'ticket_created', 'email' => 'ticket_created_email', 'scheduled' => 'ticket_created_scheduled'][(string) ($opts['how'] ?? 'agent')] ?? '', + 'reply' => 'ticket_reply', 'client_reply' => 'ticket_client_reply', 'resolved' => 'ticket_resolved', 'closed' => 'ticket_closed', 'cc' => 'ticket_cc', + 'scheduled' => !empty($opts['cancelled']) ? 'ticket_schedule_cancelled' : 'ticket_scheduled', + ][$kind] ?? ''; + if ($template !== '' && emailTemplateReady()) { + $hours = intval($config_ticket_autoclose_hours); + $stranger = $kind === 'created' && !empty($opts['stranger']); + $values = emailTemplateValues($stranger ? ['ticket_subject' => ''] + $row : $row, [ + 'By' => $by, + 'Closes After' => $hours > 0 ? ($hours % 24 === 0 ? ($hours / 24) . ' day' . ($hours === 24 ? '' : 's') : "$hours hours") : '', + 'When' => (string) ($opts['when'] ?? ''), + 'Where' => !empty($row['ticket_onsite']) ? (trim((string) ($opts['where'] ?? '')) !== '' ? (string) $opts['where'] : 'Onsite') : 'Remote', + ]); + $email = emailTemplateApply($template, $email, $values, array_merge($stranger ? ['subject'] : [], !empty($opts['no_response']) ? ['intro'] : [])); + } return ticketEmailPreview($email); } @@ -794,7 +822,9 @@ function ticketMailSend($ticket_id, array $email, array $opts = []) { return (($b['group'] ?? '') === 'contact') <=> (($a['group'] ?? '') === 'contact'); }); $to_contact = ($recipients[0]['group'] ?? '') === 'contact'; - return count(emailQueue($recipients, (string) ($opts['subject'] ?? ticketEmailSubject($row)), $email, ['from' => ticketEmailFrom(), 'attachments' => $opts['attachments'] ?? [], 'cal_str' => $opts['cal_str'] ?? '', + // Your own subject for it, when you changed it (emailTemplateSubject(), functions/email_template.php) - a fixed one ($opts) first + $templated = emailTemplateSubject($row, $email, ticketEmailSubject($row)); + return count(emailQueue($recipients, (string) ($opts['subject'] ?? $templated), $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 @@ -862,10 +892,7 @@ function ticketMailColleaguesNew($ticket_id) { $sent = 0; foreach (ticketColleagueRecipients($ticket_id, 'created') as $email => $colleague) { $url = $colleague['portal'] ? "https://$config_base_url/client/ticket.php?id=$ticket_id" : ticketEmailUrl($ticket); - $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.' : '.'), - ]], ticketEmailSubject($ticket), [ + $content = [ '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'] . '.'], @@ -874,7 +901,16 @@ 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, 'thread' => $ticket_id, 'auto' => 'generated'])); + ]; + // Your own wording for it, where you changed it (functions/email_template.php) + if (emailTemplateReady()) { + $content = emailTemplateApply('ticket_colleague_new', $content, emailTemplateValues($ticket, ['Raised By' => $raised_by])); + } + $subject = emailTemplateSubject($ticket, $content, ticketEmailSubject($ticket)); + $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.' : '.'), + ]], $subject, $content, ['from' => ticketEmailFrom(), 'ticket_id' => $ticket_id, 'thread' => $ticket_id, 'auto' => 'generated'])); } return $sent; } @@ -1059,9 +1095,11 @@ function ticketMailCcsAdded($ticket_id, array $emails, $by) { return 0; } $company_name = (string) (billingCompany()['company_name'] ?? 'us'); + $email = ticketEmailContent($row, 'cc', ['by' => (string) $by]); + $subject = emailTemplateSubject($row, $email, ticketEmailSubject($row)); return count(emailQueue(array_map(function ($cc_email) use ($row, $company_name) { return ['email' => $cc_email, 'greet' => '', 'footnote' => "You get this because you are copied in on ticket " . ticketReference($row) . " - ask $company_name if you would like to stop."]; - }, $emails), ticketEmailSubject($row), ticketEmailContent($row, 'cc', ['by' => (string) $by]), ['from' => ticketEmailFrom(), 'thread' => intval($row['ticket_id'])])); + }, $emails), $subject, $email, ['from' => ticketEmailFrom(), 'thread' => intval($row['ticket_id'])])); } /* ------------------------------------------------------------ Emails about a ticket, to agents */ @@ -1365,7 +1403,7 @@ function ticketMailTaskApproval($approval_id, $by) { 'footnote' => $type === 'any' ? "You get this as the contact on ticket $reference." : "You get this as a $type contact for " . $row['client_name'] . "."]; } } - return count(emailQueue($recipients, "Ticket task approval required - [$reference] - " . $row['ticket_subject'], [ + $email = [ 'marker' => true, 'kind' => 'Approval needed', 'tone' => 'warning', 'preview' => "$by needs your approval - " . $approval['task_name'], 'title' => 'Your approval is needed', 'intro' => ["$by needs your approval for a task on ticket $reference before the work goes ahead."], @@ -1374,7 +1412,13 @@ function ticketMailTaskApproval($approval_id, $by) { 'after' => ['Want to know more first? Just reply to this email.'], 'contact' => ticketEmailContactLine(), 'office' => officeTicketFoot($row), - ], ['from' => ticketEmailFrom(), 'sensitive' => true])); + ]; + // Your own wording for the client's, where you changed it (functions/email_template.php) + if ($approval['approval_scope'] === 'client' && emailTemplateReady()) { + $email = emailTemplateApply('ticket_approval', $email, emailTemplateValues($row, ['By' => $by, 'Task' => (string) $approval['task_name']])); + } + $subject = emailTemplateSubject($row, $email, "Ticket task approval required - [$reference] - " . $row['ticket_subject']); + return count(emailQueue($recipients, $subject, $email, ['from' => ticketEmailFrom(), 'sensitive' => true])); } /* @@ -1390,14 +1434,21 @@ function ticketMailClosedReply($ticket_id, $from_email, $answering = '') { return 0; } $support = ticketEmailFrom()['email']; - return count(emailQueue([['email' => (string) $from_email, 'greet' => '', 'footnote' => 'You get this because you replied to a closed ticket.']], ticketEmailSubject($closed), [ + $email = [ 'kind' => 'Ticket closed', 'tone' => 'warning', 'preview' => 'That ticket is closed, so nobody will act on your reply - raise a new ticket instead', 'title' => 'That ticket is closed', 'intro' => ["You replied to ticket " . ticketReference($closed) . " - \"" . $closed['ticket_subject'] . "\" - which is closed. Your reply is kept with it, but the ticket isn't reopened, so nobody will act on it.", "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(), 'thread' => intval($closed['ticket_id']), 'answering' => (string) $answering, 'auto' => 'replied'])); + ]; + // Your own wording for it, where you changed it (functions/email_template.php) + if (emailTemplateReady()) { + $email = emailTemplateApply('ticket_closed_reply', $email, emailTemplateValues($closed, ['Support Email' => $support])); + } + $subject = emailTemplateSubject($closed, $email, ticketEmailSubject($closed)); + return count(emailQueue([['email' => (string) $from_email, 'greet' => '', 'footnote' => 'You get this because you replied to a closed ticket.']], $subject, $email, + ['from' => ticketEmailFrom(), 'thread' => intval($closed['ticket_id']), 'answering' => (string) $answering, 'auto' => 'replied'])); } /* diff --git a/guest/guest_post.php b/guest/guest_post.php index 21286b15a..af90781f6 100644 --- a/guest/guest_post.php +++ b/guest/guest_post.php @@ -227,6 +227,10 @@ if (isset($_GET['export_quote_pdf'])) { http_response_code(404); exit('That quote is not available.'); } + if (guestLinkExpired('quote', $quote['quote_id'])) { + http_response_code(410); + exit('This quote link has expired.'); + } billingPdfSend(billingPdf('quote', $quote)); @@ -240,6 +244,10 @@ if (isset($_GET['export_invoice_pdf'])) { http_response_code(404); exit('That invoice is not available.'); } + if (guestLinkExpired('invoice', $invoice['invoice_id'])) { + http_response_code(410); + exit('This invoice link has expired.'); + } billingPdfSend(billingPdf('invoice', $invoice)); @@ -253,7 +261,7 @@ if (isset($_POST['guest_quote_upload_file'])) { // Select only the necessary fields $sql = mysqli_query($mysqli, "SELECT quote_id FROM quotes WHERE quote_id = $quote_id AND quote_url_key = '$url_key'"); - if (mysqli_num_rows($sql) == 1) { + if (mysqli_num_rows($sql) == 1 && !guestLinkExpired('quote', $quote_id)) { // Each PDF to the client's Client Uploads and onto the quote - functions/billing.php, shared with the client portal if (!empty($_FILES['file'])) { diff --git a/guest/guest_view_invoice.php b/guest/guest_view_invoice.php index 0c7e1bcf8..017b10f83 100644 --- a/guest/guest_view_invoice.php +++ b/guest/guest_view_invoice.php @@ -19,6 +19,13 @@ if (!$invoice || (string) $invoice['invoice_url_key'] === '' || !hash_equals((st exit(); } +// Paid long enough ago - its link has stopped working (functions/guest_link.php) +if (guestLinkExpired('invoice', $invoice['invoice_id'])) { + echo guestLinkExpiredHtml('invoice'); + require_once $_SERVER['DOCUMENT_ROOT'] . '/includes/footer.php'; + exit(); +} + $invoice_id = intval($invoice['invoice_id']); $client_id = intval($invoice['client_id']); $number = billingNumber('invoice', $invoice); diff --git a/guest/guest_view_quote.php b/guest/guest_view_quote.php index 8aa8dbdd6..a10d5be68 100644 --- a/guest/guest_view_quote.php +++ b/guest/guest_view_quote.php @@ -20,6 +20,13 @@ if (!$quote || (string) $quote['quote_url_key'] === '' || !hash_equals((string) exit(); } +// Answered, or ran out, long enough ago - its link has stopped working (functions/guest_link.php) +if (guestLinkExpired('quote', $quote['quote_id'])) { + echo guestLinkExpiredHtml('quote'); + require_once $_SERVER['DOCUMENT_ROOT'] . '/includes/footer.php'; + exit(); +} + $quote_id = intval($quote['quote_id']); $number = billingNumber('quote', $quote); $status = (string) $quote['quote_status']; diff --git a/guest/guest_view_ticket.php b/guest/guest_view_ticket.php index 7fa199e73..495f86611 100644 --- a/guest/guest_view_ticket.php +++ b/guest/guest_view_ticket.php @@ -48,7 +48,7 @@ $brand_html = $company['logo_url'] !== '' : '' . '' . escapeHtml($session_company_name) . ''; -$found = ticketByGuestKey($_GET['ticket_id'] ?? 0, $_GET['url_key'] ?? ''); +$found = ticketByGuestKey($_GET['ticket_id'] ?? 0, $_GET['url_key'] ?? '', $link_expired); $ticket_id = $found ? intval($found['ticket_id']) : 0; $ticket = $ticket_id ? mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT " . portalTicketColumnsSql() . ", tickets.ticket_details, tickets.ticket_feedback, tickets.ticket_url_key, @@ -64,6 +64,16 @@ $ticket = $ticket_id ? mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT " . port LEFT JOIN locations ON location_id = IF(tickets.ticket_location_id > 0, tickets.ticket_location_id, contacts.contact_location_id) AND location_client_id = tickets.ticket_client_id WHERE tickets.ticket_id = $ticket_id LIMIT 1")) : null; +if (!$ticket && $link_expired) { + // Closed long enough ago - its link has stopped working (functions/guest_link.php) + ?> +
+
+