diff --git a/CHANGELOG.md b/CHANGELOG.md index e8c63854b..abf23386b 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 five database changes: 4.2.2 adds a table for passkeys and a setting to turn them on or off, 4.2.3 lets a document keep the Markdown it was written in, 4.2.4 lets a ticket keep its pictures as files, 4.2.5 adds identity providers, and 4.2.6 keeps each ticket's email conversation together. The client portal's Microsoft 365 single sign-on becomes the first identity provider, for client contacts, and keeps its redirect address, so nothing changes in Microsoft Entra. Nothing else is required: passkeys are on, and no one has one until they add it. Pictures already inside tickets move to files in the background afterwards - the new Ticket Pictures job in Maintenance > Cron does a batch a minute, so an install with years of emailed screenshots may take a while, and tickets work as usual meanwhile. A passkey is made for your ITFlow's address (the one in config.php) and only works there, over HTTPS - if you move ITFlow to a new address, everyone adds theirs again. Emails about a ticket now go to its contact with the watchers copied in, rather than one each - Admin > Settings > Tickets has the switch, under Emails about a ticket. +Update from Maintenance > Update as usual - this release has six 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, and 4.2.7 lets a reply from a watcher say who sent it. The client portal's Microsoft 365 single sign-on becomes the first identity provider, for client contacts, and keeps its redirect address, so nothing changes in Microsoft Entra. Nothing else is required: passkeys are on, and no one has one until they add it. Pictures already inside tickets move to files in the background afterwards - the new Ticket Pictures job in Maintenance > Cron does a batch a minute, so an install with years of emailed screenshots may take a while, and tickets work as usual meanwhile. A passkey is made for your ITFlow's address (the one in config.php) and only works there, over HTTPS - if you move ITFlow to a new address, everyone adds theirs again. Emails about a ticket now go to its contact with the watchers copied in, rather than one each - Admin > Settings > Tickets has the switch, under Emails about a ticket. ### New Features & Updates @@ -54,6 +54,12 @@ Update from Maintenance > Update as usual - this release has five database chang - A client's reply goes on to the watchers: when the client replies by email, text or in the portal, the people an agent's reply would go to get it too, with its files - not anyone it was already to or copied to. By email, only a reply to one of the ticket's emails is passed on, as anyone can put a ticket number in a subject. It can be switched off in the same place. - Whoever the client also emails, or copies in, follows the ticket: the other people in To and Cc on the email that raises a ticket, and on a reply from the client or a watcher, become its watchers - never your own addresses, anyone else at your domain or your agents. The ticket's history says who. - An email that lands in the support mailbox twice - sent to two of your addresses that both go to it - makes one ticket. +- A watcher's reply by email is the client's reply now, named on the ticket, rather than an internal note headed "Contact email mismatch". It reopens the ticket and goes on to the contact and anyone else following it who wasn't on it, as the contact's reply does. The same goes for the person whose email raised a ticket with no client - before, their replies could only ever be notes. +- A bounce is read whatever your settings: the contacts it failed for are marked Email bounced, the ticket the email was about gets a note saying who it couldn't reach and what their mail server said - found by the email that bounced, so a bounce from Microsoft 365 or Gmail finds it too - and agents get a notice. It never makes a ticket. A bounce used to be read only with From unknown senders too on, and otherwise sat flagged in the mailbox. A notice that an email is only delayed is set aside. +- An out-of-office reply to a ticket's email is an internal note on the ticket, to read - it doesn't reopen it, and agents don't get a notice each time. One that answers no ticket is set aside, as before. +- Email sent by a system, a mailing list or a newsletter still makes tickets - alerts emailed in keep working - but is never answered: no "we have your email", no "that ticket is closed". ITFlow's own automatic emails say they are automatic, so the other side's out-of-office doesn't answer them, and no one address gets more than five of them an hour - so two systems can't keep answering each other. +- Two people at a client raising the same problem in the same week - "Printer not working" - get a ticket each, linked as related, rather than the second email landing on the first person's ticket. It's still a reply on the ticket from its contact or a watcher. +- A reply to a closed ticket is kept on it as an internal note instead of left in the mailbox, and the notice says so. The ticket isn't reopened. The client or watcher is told it is closed, as before - but not someone with no part in the ticket, who learned nothing from a number they guessed. ### Bug Fixes @@ -69,6 +75,7 @@ Update from Maintenance > Update as usual - this release has five database chang - An email to a domain whose mail server couldn't be found is tried again like any other failed email, and a domain with no MX record that takes mail at its own address is found. One failed lookup used to fail the email for good. - After the ticket prefix was changed (Admin > Settings > Tickets), a reply to an older ticket - its number with the old prefix - became a new ticket. It finds its ticket now, and so does a number written with zeros in front. - A reply to an email of a ticket that was merged into another goes on the ticket it was merged into, rather than being turned away as a reply to a closed ticket. +- Email from an address with "mta", "daemon" or "bounce" anywhere in it - jmtaylor@, say - was taken for a mail server: it raised no ticket from an unknown sender, and a reply to a closed ticket wasn't answered. Only a mail server's own address, or a bounce report, counts now. ### Developer Updates @@ -112,6 +119,9 @@ Update from Maintenance > Update as usual - this release has five database chang - ticketMailSend($ticket_id, $email, $opts) no longer takes a subject: ticketEmailSubject() is the subject of every client email about a ticket, ticketMailWatchersAdded(), ticketMailColleaguesNew() and ticketMailClosedReply($ticket_id, $from_email, $answering) included - not the task approval email. ticketMailCreated() lost its $subject_prefix argument. Its recipients carry a group, and the contact goes first. ticketReplyEmailed() and ticketReplyEmailStates() count email_cc; ticketReplyRecipientsPick() takes $remember (false keeps nothing in ticket_mail_choices) and returns each one's group. - ticketMailRelayClientReply() (client/post.php, functions/sms.php, and the parser for a reply matched by its headers) sends ticketEmailContent()'s client_reply kind to the To line's people (ticketReplyRecipients() send) less the author, the email's From, To and Cc, and agents. ticketMailCopiedWatchers() (the parser's addTicket(), and addReply() unless from a stranger or an agent) adds To and Cc less ITFlow's own addresses, emailOwnDomain() (functions/email.php - their domains, not EMAIL_PUBLIC_DOMAINS), agents and no-reply addresses. addReply() takes a ticket id and $email (message_id, copied, had, threaded). settings.config_ticket_email_copy and config_ticket_email_relay, both 1 (ticketMailSettings()). - Admin > Mail Queue shows and searches email_cc, the email's window has a Cc line, and Admin > Mail previews show one (admin/mail_preview.php cc) and have a Client's reply, passed on. +- functions/ticket_mail_auto.php: ticketMailHeaderMap() (lower-case name => raw value), ticketMailIsBounce() (multipart/report with report-type=delivery-status, X-Failed-Recipients, or a TICKET_MAIL_BOUNCE_SENDERS local part - replacing the /daemon|postmaster|bounce|mta/i pattern), ticketMailAutomaticKind() (auto-reply: Auto-Submitted auto-replied, Precedence auto_reply, X-Autoreply, X-Autorespond, or an "Automatic reply:"/"Out of Office:" subject with X-Auto-Response-Suppress or a [ticket number]; automated: any other Auto-Submitted but no, Precedence bulk/list/junk, List-Id, List-Unsubscribe), ticketMailBounceRead() (each message/delivery-status block's Final-Recipient, Action, Status and Diagnostic-Code, the returned message/rfc822 or text/rfc822-headers Message-ID and Subject, X-Failed-Recipients as a fallback), ticketMailAutoHeaders() and ticketMailAnswersLeft() (TICKET_MAIL_ANSWERS_AN_HOUR, counted from email_headers like auto-replied). +- cron/ticket_email_parser.php: bounces go to addBounce() right after the own-address check, and step 6 is now only unknown senders. addReply() sorts the sender into contact (the ticket's or the client's), agent, watcher or stranger, takes $email from_name and automatic, keeps a closed ticket's or an automatic reply's email as an Internal note (ticket_reply_by 0), and answers only a contact or watcher, never anything automatic, within ticketMailAnswersLeft(). addTicket() returns the ticket id, takes $automatic and acknowledges only a person's email; the fuzzy step replies only for the ticket's contact or a watcher and otherwise links the new ticket with linkSimilarTicket() (ticketLinkTogether(), as The email parser). emailQueue() and ticketMailSend() take auto (replied or generated); MAIL_QUEUE_HEADERS is now name => pattern and allows Auto-Submitted and X-Auto-Response-Suppress. The ack ("how" email), ticketMailClosedReply(), ticketMailColleaguesNew() and ticketMailRelayClientReply() send them. +- Database 4.2.7: ticket_replies.ticket_reply_from_name and ticket_reply_from_email, set on a client reply from a watcher (ticketReplyFromReady()). ticketReplyAuthorSql() selects COALESCE(contact_name, ticket_reply_from_name, ticket_reply_from_email) AS contact_name in every reply query that names a client reply - the ticket page, quick look, split, pulse, project and email history, AI summaries, the portal and the guest page. Try an Email (functions/ticket_mail_try.php) follows: a bounce address first, automatic replies as a note or set aside, watchers as client replies, closed tickets as notes, and near-same subjects from someone else linked. ## [26.12.2] diff --git a/admin/database_updates/4.2.7.php b/admin/database_updates/4.2.7.php new file mode 100644 index 000000000..47238e20d --- /dev/null +++ b/admin/database_updates/4.2.7.php @@ -0,0 +1,28 @@ + 'Client' AND ticket_reply_by = user_id LEFT JOIN contacts ON ticket_reply_type = 'Client' AND ticket_reply_by = contact_id @@ -1180,7 +1180,7 @@ if (isset($_GET['ticket_pulse'])) { $pulse['replies'] = []; $since_reply = intval($_GET['since_reply'] ?? 0); if ($since_reply > 0 && $pulse_ids) { - $sql = mysqli_query($mysqli, "SELECT ticket_reply_id, ticket_reply, tickets.ticket_id, ticket_prefix, ticket_number, ticket_subject, ticket_client_id, contact_name + $sql = mysqli_query($mysqli, "SELECT ticket_reply_id, ticket_reply, tickets.ticket_id, ticket_prefix, ticket_number, ticket_subject, ticket_client_id, " . ticketReplyAuthorSql() . " FROM ticket_replies JOIN tickets ON ticket_reply_ticket_id = tickets.ticket_id LEFT JOIN contacts ON ticket_reply_by = contact_id diff --git a/agent/modals/ticket/ticket.php b/agent/modals/ticket/ticket.php index 57052a3b5..f30bd3490 100644 --- a/agent/modals/ticket/ticket.php +++ b/agent/modals/ticket/ticket.php @@ -67,7 +67,7 @@ $also_open_shares = count($also_open_shares) > 1 ? 'contact or asset' : ($also_o $tasks = ticketTaskCounts([$ticket_id])[$ticket_id] ?? null; $replies = []; -$sql_replies = mysqli_query($mysqli, "SELECT ticket_reply_id, ticket_reply, ticket_reply_type, ticket_reply_created_at, ticket_reply_by, user_name, contact_name +$sql_replies = mysqli_query($mysqli, "SELECT ticket_reply_id, ticket_reply, ticket_reply_type, ticket_reply_created_at, ticket_reply_by, user_name, " . ticketReplyAuthorSql() . " FROM ticket_replies LEFT JOIN users ON ticket_reply_type <> 'Client' AND ticket_reply_by = user_id LEFT JOIN contacts ON ticket_reply_type = 'Client' AND ticket_reply_by = contact_id diff --git a/agent/modals/ticket/ticket_reply_split.php b/agent/modals/ticket/ticket_reply_split.php index d2afd2f25..a806fd721 100644 --- a/agent/modals/ticket/ticket_reply_split.php +++ b/agent/modals/ticket/ticket_reply_split.php @@ -11,7 +11,7 @@ require_once '../../../includes/modal_header.php'; enforceUserPermission('module_support', 2); $ticket_reply_id = intval($_GET['id'] ?? 0); -$reply = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT ticket_reply, ticket_reply_type, ticket_reply_ticket_id, ticket_reply_created_at, contact_name +$reply = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT ticket_reply, ticket_reply_type, ticket_reply_ticket_id, ticket_reply_created_at, " . ticketReplyAuthorSql() . " FROM ticket_replies LEFT JOIN contacts ON contact_id = ticket_reply_by WHERE ticket_reply_id = $ticket_reply_id AND ticket_reply_archived_at IS NULL")); if (!$reply || $reply['ticket_reply_type'] !== 'Client') { diff --git a/agent/ticket.php b/agent/ticket.php index d8115a637..aa185186a 100644 --- a/agent/ticket.php +++ b/agent/ticket.php @@ -271,7 +271,7 @@ if (isset($_GET['ticket_id'])) { ))['user_names']); // Get ticket replies - with whether each of yours was emailed, and who to - $sql_ticket_replies = mysqli_query($mysqli, "SELECT contact_name, contact_photo, ticket_reply, ticket_reply_by, ticket_reply_created_at, ticket_reply_id, + $sql_ticket_replies = mysqli_query($mysqli, "SELECT " . ticketReplyAuthorSql() . ", contact_photo, ticket_reply, ticket_reply_by, ticket_reply_created_at, ticket_reply_id, ticket_reply_time_worked, ticket_reply_type, ticket_reply_updated_at, user_avatar, user_id, user_name, " . (ticketWorkTimesReady() ? 'ticket_reply_work_start, ticket_reply_work_end,' : 'NULL AS ticket_reply_work_start, NULL AS ticket_reply_work_end,') . " " . (ticketReplyEmailReady() ? 'ticket_reply_emailed, ticket_reply_emailed_to' : 'NULL AS ticket_reply_emailed, NULL AS ticket_reply_emailed_to') . " diff --git a/client/ticket.php b/client/ticket.php index 95fbc2e8e..db9e731c0 100644 --- a/client/ticket.php +++ b/client/ticket.php @@ -82,7 +82,7 @@ while ($row = mysqli_fetch_assoc($sql)) { // The conversation, oldest first $replies = mysqli_query($mysqli, "SELECT ticket_reply_id, ticket_reply, ticket_reply_type, ticket_reply_by, ticket_reply_created_at, - contact_name, contact_photo, user_id, user_name, user_avatar + " . ticketReplyAuthorSql() . ", contact_photo, user_id, user_name, user_avatar FROM ticket_replies LEFT JOIN users ON ticket_reply_type != 'Client' AND ticket_reply_by = user_id LEFT JOIN contacts ON ticket_reply_type = 'Client' AND ticket_reply_by = contact_id diff --git a/cron/ticket_email_parser.php b/cron/ticket_email_parser.php index 50e7f8103..89433deae 100644 --- a/cron/ticket_email_parser.php +++ b/cron/ticket_email_parser.php @@ -78,9 +78,11 @@ $read_mail_minutes = 60; // Mail someone opened before this got to it /* * A new ticket from an email. $copied - the people it was also to or copied to, made its watchers * (ticketMailCopiedWatchers()); $message_id its Message-ID, kept with the ticket so a reply to it - - * or to all on it, before the ticket's number was ever sent - finds it (functions/ticket_mail_thread.php). + * or to all on it, before the ticket's number was ever sent - finds it (functions/ticket_mail_thread.php); + * $automatic 'automated' for one sent by a system or a list, which isn't answered (functions/ticket_mail_auto.php). + * The new ticket's id. */ -function addTicket($contact_id, $contact_name, $contact_email, $client_id, $date, $subject, $message, $attachments, $original_message_file, $copied, $message_id = '') { +function addTicket($contact_id, $contact_name, $contact_email, $client_id, $date, $subject, $message, $attachments, $original_message_file, $copied, $message_id = '', $automatic = '') { global $mysqli, $config_app_name, $company_name, $company_phone, $config_ticket_prefix, $config_ticket_client_general_notifications, $config_base_url, $config_ticket_from_name, $config_ticket_from_email, $config_ticket_default_billable, $allowed_extensions; $bad_pattern = "/do[\W_]*not[\W_]*reply|no[\W_]*reply/i"; // Email addresses to ignore @@ -169,9 +171,11 @@ function addTicket($contact_id, $contact_name, $contact_email, $client_id, $date // The people it was also to or copied to are its watchers - not your own addresses or agents (ticketMailCopiedWatchers()) ticketMailCopiedWatchers($id, $copied, stripslashes($contact_email)); - // The sender is told it is a ticket now - unless they asked for replies only (Your account in the client portal) + // The sender is told it is a ticket now - unless they asked for replies only (Your account in the client portal), it was + // sent by a system or a list, whose answer could be answered back, or they have had a few answers this hour already $contact_wants = !$contact_id || ticketContactWantsEmail(getFieldById('contacts', intval($contact_id), 'contact_ticket_emails'), 'created'); - if ($config_ticket_client_general_notifications == 1 && !preg_match($bad_pattern, $contact_email) && $contact_wants && ($new = ticketRow($id))) { + if ($config_ticket_client_general_notifications == 1 && !preg_match($bad_pattern, $contact_email) && $contact_wants && $automatic === '' + && ticketMailAnswersLeft(stripslashes($contact_email)) && ($new = ticketRow($id))) { ticketMailCreated($id, [], false, 'email', [['email' => stripslashes($contact_email), 'name' => stripslashes($contact_name)]]); } @@ -183,49 +187,114 @@ function addTicket($contact_id, $contact_name, $contact_email, $client_id, $date triggerCustomAction('ticket_create', $id); - return true; + return intval($id); +} + +/* + * A mail server's report that an email couldn't be delivered (ticketMailIsBounce()) - never a ticket, never answered. + * The addresses it failed for are marked on their contacts ("Email bounced", functions/contact_bounce.php), the ticket + * the email was about gets a note - found by the Message-ID of the email that bounced, as ITFlow keeps each it sends + * about a ticket, else by the number in its subject - and agents get a notice. A report that an email is only delayed + * is set aside. + */ +function addBounce($message, array $headers, $from_email, $subject) { + global $mysqli; + $parts = []; + foreach ($message->parse()->getAllParts() as $part) { + $parts[] = [(string) $part->getContentType(), (string) ($part->getContent() ?? '')]; + } + $bounce = ticketMailBounceRead($parts, (string) ($headers['x-failed-recipients'] ?? ''), (string) ($message->text() ?? '')); + if ($bounce['delayed']) { + logApp("Cron-Email-Parser", "info", "Email parser set aside a delivery delay notice from $from_email ($subject) - the email is still being tried"); + return; + } + + // The ticket the email was about + $ticket_id = ticketMailIdTicket($bounce['message_id']); + if (!$ticket_id) { + $numbered = ticketMailSubjectTicket($bounce['subject']) ?: ticketMailSubjectTicket(stripslashes($subject)); + $ticket_id = intval($numbered['ticket_id'] ?? 0); + } + $ticket = $ticket_id ? ticketRow($ticket_id) : null; + $client_id = intval($ticket['ticket_client_id'] ?? 0); + + // The contacts with each address show "Email bounced" until mail comes from it again + foreach ($bounce['failed'] as $failed => $why) { + foreach (contactBounceMark($failed, $why) as $bounced_contact_id => [$bounced_name, $bounced_client_id]) { + logAudit("Contact", "Edit", "Email parser: mail to " . escapeSql($bounced_name) . " bounced - marked on the contact", $bounced_client_id, $bounced_contact_id); + } + } + $to = $bounce['failed'] ? implode(', ', array_keys($bounce['failed'])) : 'someone it doesn\'t name'; + $why = implode('; ', array_filter($bounce['failed'])); + + if ($ticket) { + $note = 'An email about this ticket couldn\'t be delivered
To: ' . escapeHtml($to) . ($why !== '' ? '
The mail server said: ' . escapeHtml($why) : '') + . '
From ' . escapeHtml(stripslashes($from_email)) . ' - the report is in the mailbox\'s ITFlow folder'; + mysqli_query($mysqli, "INSERT INTO ticket_replies SET ticket_reply = '" . mysqli_real_escape_string($mysqli, $note) . "', ticket_reply_type = 'Internal', + ticket_reply_time_worked = '00:00:00', ticket_reply_by = 0, ticket_reply_ticket_id = $ticket_id"); + logTicketHistory($ticket_id, escapeSql("An email to $to couldn't be delivered - noted")); + } + appNotify("Ticket", escapeSql("Email parser: an email to $to bounced" . ($ticket ? ' - ' . ticketReference($ticket) . ' has a note' : '') + . ($why !== '' ? ". The mail server said: " . mb_strimwidth($why, 0, 300, '...') : '') . ". Subject: " . ($bounce['subject'] !== '' ? $bounce['subject'] : stripslashes($subject))), + $ticket ? "/agent/ticket.php?ticket_id=$ticket_id" . ($client_id ? "&client_id=$client_id" : '') : '', $client_id, $ticket_id); +} + +/* + * A new ticket whose subject is almost that of $similar_id - an open ticket of the client's from the last week - raised by + * someone who isn't its contact or watching it: kept as a ticket of its own, linked to that one as related + * (functions/ticket_link.php), so an agent sees both and can merge them. + */ +function linkSimilarTicket($new_id, $similar_id) { + $session_name = $GLOBALS['session_name'] ?? null; + $GLOBALS['session_name'] = 'The email parser'; + ticketLinkTogether([intval($new_id), intval($similar_id)]); + $GLOBALS['session_name'] = $session_name; + $similar = ticketRow($similar_id); + if ($similar) { + logTicketHistory(intval($new_id), escapeSql("Its subject is almost the same as " . ticketReference($similar) . "'s, from someone else at the client - linked as related, in case it is the same thing")); + } } /* * An email on ticket $ticket_id. $email, about the email: * message_id its Message-ID, kept with the ticket (functions/ticket_mail_thread.php) + * from_name the name in its From line * copied the people it was also to or copied to, made watchers when it is from the client or a watcher * had everyone it was from, to and copied to - a client's reply goes on to the rest (ticketMailRelayClientReply()) * threaded it answers one of the ticket's emails (its In-Reply-To or References) - only then is a client's * reply passed on, as anyone can put a ticket number in a subject + * automatic auto-reply (an out-of-office) or automated (a system, a list) - never answered or passed on + * (functions/ticket_mail_auto.php) + * + * Who it is from decides what it is: the ticket's contact, another of the client's contacts, or one of its watchers + * (the person whose email raised a ticket with no client is one) - a client reply, which reopens the ticket; one + * of your agents - their own internal note; anyone else - an internal note with a warning, which reopens nothing + * and takes no attachments. An automatic reply is a note that reopens nothing, and an email to a closed ticket is + * kept on it as a note - it isn't reopened. */ function addReply($from_email, $date, $subject, $ticket_id, $message, $attachments, $original_message_file = null, array $email = []) { - global $mysqli, $config_app_name, $company_name, $company_phone, $config_ticket_prefix, $config_base_url, $config_ticket_from_name, $config_ticket_from_email, $allowed_extensions; + global $mysqli, $allowed_extensions; - $ticket_reply_type = 'Client'; - // $message contains the raw HTML body from IMAP + $automatic = (string) ($email['automatic'] ?? ''); + $from_name = trim(stripslashes((string) ($email['from_name'] ?? ''))); + $from_name = $from_name === 'Unknown' ? '' : $from_name; // 1) What they wrote, without the email of ours they quote - above the reply line, or below it when // that's where they wrote (emailReplyText(), functions/email.php) $message = emailReplyText($message); - // 2) Clean up the remaining message - - // Remove DOCTYPE and meta tags + // 2) Clean up the remaining message - no DOCTYPE, meta, html, head or body, and its line breaks as
$message = preg_replace('/]*>/i', '', $message); $message = preg_replace('/]*>/i', '', $message); - - // Remove , , and their closing tags $message = preg_replace('/<\/?(html|head|body)[^>]*>/i', '', $message); - - // Trim leading/trailing whitespace $message = trim($message); - - // Normalize line breaks to spaces $message = preg_replace('/\r\n|\r|\n/', ' ', $message); - - // Convert to
for HTML display $message = nl2br($message); - // 3) Final wrapper - $message = "Email from: $from_email at $date:-

$message
"; + // 3) Who it is from and when, above it - by name too, when the email gives one + $from_line = $from_name !== '' ? '' . escapeHtml($from_name) . ' <' . $from_email . '>' : $from_email; + $message = "Email from: $from_line at $date:-

$message
"; - $message_esc = mysqli_real_escape_string($mysqli, $message); $from_email_esc = mysqli_real_escape_string($mysqli, $from_email); $row = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT ticket_id, ticket_prefix, ticket_number, ticket_subject, ticket_status, ticket_contact_id, ticket_client_id, contact_email, client_name @@ -233,160 +302,171 @@ function addReply($from_email, $date, $subject, $ticket_id, $message, $attachmen LEFT JOIN contacts on tickets.ticket_contact_id = contacts.contact_id LEFT JOIN clients on tickets.ticket_client_id = clients.client_id WHERE ticket_id = " . intval($ticket_id) . " LIMIT 1")); - - if ($row) { - $ticket_id = intval($row['ticket_id']); - // Its own reference, with the prefix it was given - for the logs - $ticket_reference_esc = escapeSql(ticketReference($row)); - $ticket_status = escapeSql($row['ticket_status']); - $ticket_reply_contact = intval($row['ticket_contact_id']); - $ticket_contact_email = escapeSql($row['contact_email']); - $client_id = intval($row['ticket_client_id']); - if ($client_id) { - $client_uri = "&client_id=$client_id"; - } else { - $client_uri = ''; - } - - if ($ticket_status == 5) { - appNotify("Ticket", "Email parser: $from_email attempted to re-open ticket $ticket_reference_esc (ID $ticket_id) - check inbox manually to see email", "/agent/ticket.php?ticket_id=$ticket_id$client_uri", $client_id); - - // They are told it didn't reach anyone, and how to raise a new one - never a mail server's - // own bounce (the pattern new tickets use), whose answer would only bounce again - if (!preg_match("/daemon|postmaster|bounce|mta/i", $from_email)) { - ticketMailClosedReply($ticket_id, stripslashes($from_email), (string) ($email['message_id'] ?? '')); - } - return true; - } - - // Who wrote it: the ticket's contact or another of the client's contacts - a client reply; a - // watcher - an internal note with the mismatch warning, as before; one of your agents (answering - // an email about the ticket) - their own internal note, which reopens nothing; or anyone else. - // Anyone can put a ticket number in a subject, so a stranger's email is kept as an internal note - // that doesn't reopen the ticket, and their attachments are not added. - $stranger = false; - $agent_reply = false; - if (empty($ticket_contact_email) || $ticket_contact_email !== $from_email) { - $from_email_esc2 = mysqli_real_escape_string($mysqli, $from_email); - $row2 = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT contact_id FROM contacts WHERE contact_email = '$from_email_esc2' AND contact_client_id = $client_id LIMIT 1")); - if ($row2) { - $ticket_reply_contact = intval($row2['contact_id']); - } else { - $ticket_reply_type = 'Internal'; - $agent_row = mysqli_fetch_row(mysqli_query($mysqli, "SELECT user_id FROM users WHERE user_email = '$from_email_esc2' AND user_type = 1 AND user_status = 1 AND user_archived_at IS NULL LIMIT 1")); - if ($agent_row) { - $agent_reply = true; - $ticket_reply_contact = intval($agent_row[0]); // an internal note is by an agent, as on the ticket page - } else { - $stranger = !mysqli_num_rows(mysqli_query($mysqli, "SELECT 1 FROM ticket_watchers WHERE watcher_ticket_id = $ticket_id AND watcher_email = '$from_email_esc2' LIMIT 1")); - $ticket_reply_contact = '0'; - $message = ($stranger - ? "WARNING: From someone who is not a contact, watcher or agent - the ticket was not reopened" - . ($attachments ? ", and the email's " . count($attachments) . " attachment(s) were not added - it is in the mailbox's ITFlow folder" : '') . "
" - : "WARNING: Contact email mismatch
") . $message; - $message_esc = mysqli_real_escape_string($mysqli, $message); - } - } - } - - mysqli_query($mysqli, "INSERT INTO ticket_replies SET ticket_reply = '$message_esc', ticket_reply_type = '$ticket_reply_type', ticket_reply_time_worked = '00:00:00', ticket_reply_by = $ticket_reply_contact, ticket_reply_ticket_id = $ticket_id"); - $reply_id = mysqli_insert_id($mysqli); - - // In the ticket's conversation - the next email about it answers this one (functions/ticket_mail_thread.php) - ticketMailKeepId($ticket_id, (string) ($email['message_id'] ?? '')); - - // The email's pictures kept as the ticket's files, not inside the reply (functions/ticket_pictures.php) - ticketPicturesSaveReply($reply_id); - - $ticket_dir = "../uploads/tickets/" . $ticket_id . "/"; - mkdirMissing($ticket_dir); - - foreach ($stranger ? [] : $attachments as $attachment) { - $att_name = $attachment['name']; - $att_extension = strtolower(pathinfo($att_name, PATHINFO_EXTENSION)); - - if (in_array($att_extension, $allowed_extensions)) { - $att_saved_filename = md5(uniqid(rand(), true)) . '.' . $att_extension; - $att_saved_path = $ticket_dir . $att_saved_filename; - file_put_contents($att_saved_path, $attachment['content']); - - // Escaped once, and cut to the 255 characters the column holds - $ticket_attachment_name = escapeSql(mb_substr($att_name, 0, 255)); - $ticket_attachment_reference_name = escapeSql($att_saved_filename); - - $ticket_attachment_name_esc = $ticket_attachment_name; - $ticket_attachment_reference_name_esc = mysqli_real_escape_string($mysqli, $ticket_attachment_reference_name); - mysqli_query($mysqli, "INSERT INTO ticket_attachments SET ticket_attachment_name = '$ticket_attachment_name_esc', ticket_attachment_reference_name = '$ticket_attachment_reference_name_esc', ticket_attachment_reply_id = $reply_id, ticket_attachment_ticket_id = $ticket_id"); - } else { - $ticket_attachment_name_esc = mysqli_real_escape_string($mysqli, $att_name); - logAudit("Ticket", "Edit", "Email parser: Blocked attachment $ticket_attachment_name_esc from Client contact $from_email_esc for ticket $ticket_reference_esc", $client_id, $ticket_id); - } - } - - // The email as it came, kept with the reply as a new ticket keeps it - the reply line trims what - // shows on the ticket, and The email as it arrived shows the rest (agent/modals/ticket/ticket_email_source.php). - // Not a stranger's, whose attachments aren't taken either. - if (!$stranger && $original_message_file && is_file("../uploads/tmp/$original_message_file")) { - rename("../uploads/tmp/$original_message_file", $ticket_dir . $original_message_file); - $original_message_file_esc = mysqli_real_escape_string($mysqli, $original_message_file); - mysqli_query($mysqli, "INSERT INTO ticket_attachments SET ticket_attachment_name = 'Original-parsed-email.eml', ticket_attachment_reference_name = '$original_message_file_esc', ticket_attachment_reply_id = $reply_id, ticket_attachment_ticket_id = $ticket_id"); - } - - if ($agent_reply) { - logTicketHistory($ticket_id, "$from_email_esc (an agent) emailed - added as their internal note"); - logAudit("Ticket", "Edit", "Email parser: Agent $from_email_esc added an internal note to ticket $ticket_reference_esc ($subject)", $client_id, $ticket_id); - return true; - } - - // The people the client or a watcher also wrote to, or copied in, follow the ticket from now on - as - // they would have in a conversation by email. Not a stranger's: anyone can put a number in a subject - if (!$stranger && ($watching = ticketMailCopiedWatchers($ticket_id, (array) ($email['copied'] ?? []), stripslashes($from_email)))) { - logTicketHistory($ticket_id, escapeSql(implode(', ', $watching)) . (count($watching) === 1 ? ' is' : ' are') . " watching now - copied in on an email from $from_email_esc"); - } - - // The agent it is assigned to, with what they wrote - a stranger's as plain text - $replied_by = intval($ticket_reply_contact) ? (string) getFieldById('contacts', intval($ticket_reply_contact), 'contact_name') : ''; - $mail_reply = (string) getFieldById('ticket_replies', $reply_id, 'ticket_reply'); - if ($stranger) { - $mail_reply = nl2br(escapeHtml(trim(html_entity_decode(strip_tags(preg_replace('//i', "\n", $mail_reply)), ENT_QUOTES, 'UTF-8')))); - } - ticketMailAssigneeReplied($ticket_id, 'email', $mail_reply, $replied_by !== '' ? $replied_by : stripslashes($from_email)); - - if ($stranger) { - logTicketHistory($ticket_id, "$from_email_esc (not a contact, watcher or agent) emailed - kept as an internal note, the ticket was not reopened"); - logAudit("Ticket", "Edit", "Email parser: $from_email_esc (not a contact, watcher or agent) emailed ticket $ticket_reference_esc ($subject) - kept as an internal note", $client_id, $ticket_id); - return true; - } - - // A client's reply goes on to the people following the ticket who weren't on the email - only one that answers an - // email of the ticket's: a ticket number in a subject is all a forged email needs, and this would carry its words - // to them from your own mailbox (ticketMailRelayClientReply()) - if ($ticket_reply_type === 'Client' && !empty($email['threaded'])) { - ticketMailRelayClientReply($ticket_id, $reply_id, $replied_by !== '' ? $replied_by : stripslashes($from_email), stripslashes($from_email), - (array) ($email['had'] ?? []), (string) ($email['message_id'] ?? '')); - } - - // Back to Open - unless it is in a status of your own set to stay put when the client replies (Scheduled, say) - $new_ticket_status = ticketStatusAfterClientReply($ticket_status); - mysqli_query($mysqli, "UPDATE tickets SET ticket_status = $new_ticket_status, ticket_resolved_at = NULL WHERE ticket_id = $ticket_id AND ticket_client_id = $client_id LIMIT 1"); - // A resolved ticket's resolution clock runs again - an open one keeps its alerts, so a warning isn't sent twice - if (intval($ticket_status) === TICKET_STATUS_RESOLVED) { - resetTicketResolutionSla($ticket_id); - } else { - syncTicketSlaClock($ticket_id); - } - - // Only record the reopen when the ticket was not already open - if (intval($ticket_status) !== $new_ticket_status) { - logTicketHistory($ticket_id, "$from_email_esc replied by email, reopening the ticket"); - } - - logAudit("Ticket", "Edit", "Email parser: Client contact $from_email_esc updated ticket $ticket_reference_esc ($subject)", $client_id, $ticket_id); - triggerCustomAction('ticket_reply_client', $ticket_id); - return true; - } else { + if (!$row) { return false; } + + $ticket_id = intval($row['ticket_id']); + // Its own reference, with the prefix it was given - for the logs + $ticket_reference_esc = escapeSql(ticketReference($row)); + $ticket_status = intval($row['ticket_status']); + $client_id = intval($row['ticket_client_id']); + $client_uri = $client_id ? "&client_id=$client_id" : ''; + + // Who wrote it - contact (the ticket's, or another of the client's), watcher, agent or stranger + $who = 'stranger'; + $reply_by = 0; + if (trim((string) $row['contact_email']) !== '' && strcasecmp(trim((string) $row['contact_email']), stripslashes($from_email)) === 0) { + $who = 'contact'; + $reply_by = intval($row['ticket_contact_id']); + } elseif ($client_id && ($contact_row = mysqli_fetch_row(mysqli_query($mysqli, "SELECT contact_id FROM contacts WHERE contact_email = '$from_email_esc' AND contact_client_id = $client_id AND contact_archived_at IS NULL LIMIT 1")))) { + $who = 'contact'; + $reply_by = intval($contact_row[0]); + } elseif ($agent_row = mysqli_fetch_row(mysqli_query($mysqli, "SELECT user_id FROM users WHERE user_email = '$from_email_esc' AND user_type = 1 AND user_status = 1 AND user_archived_at IS NULL LIMIT 1"))) { + $who = 'agent'; + $reply_by = intval($agent_row[0]); // an internal note is by an agent, as on the ticket page + } elseif (mysqli_num_rows(mysqli_query($mysqli, "SELECT 1 FROM ticket_watchers WHERE watcher_ticket_id = $ticket_id AND watcher_email = '$from_email_esc' LIMIT 1"))) { + $who = 'watcher'; + } + $stranger = $who === 'stranger'; + $closed = $ticket_status === TICKET_STATUS_CLOSED; + $by_name = $who === 'contact' ? (string) getFieldById('contacts', $reply_by, 'contact_name') : ($from_name !== '' ? $from_name : stripslashes($from_email)); + + // What it is on the ticket: a client reply from the client or a watcher; a note from an agent, a stranger, an automatic + // reply, or anything on a closed ticket + $type = in_array($who, ['contact', 'watcher'], true) && $automatic !== 'auto-reply' && !$closed ? 'Client' : 'Internal'; + $notes = []; + if ($automatic === 'auto-reply') { + $notes[] = 'An automatic reply - the ticket was not reopened'; + } elseif ($closed) { + $notes[] = 'A reply to the ticket after it was closed - it was not reopened'; + } + if ($stranger) { + $notes[] = 'From someone who is not a contact, watcher or agent' . ($closed || $automatic === 'auto-reply' ? '' : ' - the ticket was not reopened') + . ($attachments ? ", and the email's " . count($attachments) . " attachment(s) were not added - it is in the mailbox's ITFlow folder" : ''); + } + if ($notes) { + $message = '' . escapeHtml(implode('. ', $notes)) . '
' . $message; + } + $message_esc = mysqli_real_escape_string($mysqli, $message); + if ($type === 'Internal') { + $reply_by = $who === 'agent' ? $reply_by : 0; + } + + // Who a client reply from someone who isn't a contact came from - there is no contact to name (4.2.7) + $from_sql = ''; + if ($type === 'Client' && $who === 'watcher' && ticketReplyFromReady()) { + $from_sql = ", ticket_reply_from_name = " . ($from_name !== '' ? "'" . mysqli_real_escape_string($mysqli, mb_substr($from_name, 0, 200)) . "'" : 'NULL') + . ", ticket_reply_from_email = '" . mysqli_real_escape_string($mysqli, mb_substr(stripslashes($from_email), 0, 255)) . "'"; + } + mysqli_query($mysqli, "INSERT INTO ticket_replies SET ticket_reply = '$message_esc', ticket_reply_type = '$type', ticket_reply_time_worked = '00:00:00', ticket_reply_by = $reply_by$from_sql, ticket_reply_ticket_id = $ticket_id"); + $reply_id = mysqli_insert_id($mysqli); + + // In the ticket's conversation - the next email about it answers this one (functions/ticket_mail_thread.php) + ticketMailKeepId($ticket_id, (string) ($email['message_id'] ?? '')); + + // The email's pictures kept as the ticket's files, not inside the reply (functions/ticket_pictures.php) + ticketPicturesSaveReply($reply_id); + + // Its attachments, and the email as it came - not a stranger's, nor an automatic reply's + $ticket_dir = "../uploads/tickets/" . $ticket_id . "/"; + mkdirMissing($ticket_dir); + $take_files = !$stranger && $automatic !== 'auto-reply'; + foreach ($take_files ? $attachments : [] as $attachment) { + $att_name = $attachment['name']; + $att_extension = strtolower(pathinfo($att_name, PATHINFO_EXTENSION)); + + if (in_array($att_extension, $allowed_extensions)) { + $att_saved_filename = md5(uniqid(rand(), true)) . '.' . $att_extension; + $att_saved_path = $ticket_dir . $att_saved_filename; + file_put_contents($att_saved_path, $attachment['content']); + + // Escaped once, and cut to the 255 characters the column holds + $ticket_attachment_name_esc = escapeSql(mb_substr($att_name, 0, 255)); + $ticket_attachment_reference_name_esc = mysqli_real_escape_string($mysqli, escapeSql($att_saved_filename)); + mysqli_query($mysqli, "INSERT INTO ticket_attachments SET ticket_attachment_name = '$ticket_attachment_name_esc', ticket_attachment_reference_name = '$ticket_attachment_reference_name_esc', ticket_attachment_reply_id = $reply_id, ticket_attachment_ticket_id = $ticket_id"); + } else { + $ticket_attachment_name_esc = mysqli_real_escape_string($mysqli, $att_name); + logAudit("Ticket", "Edit", "Email parser: Blocked attachment $ticket_attachment_name_esc from $from_email_esc for ticket $ticket_reference_esc", $client_id, $ticket_id); + } + } + + // The email as it came, kept with the reply as a new ticket keeps it - the reply line trims what + // shows on the ticket, and The email as it arrived shows the rest (agent/modals/ticket/ticket_email_source.php) + if ($take_files && $original_message_file && is_file("../uploads/tmp/$original_message_file")) { + rename("../uploads/tmp/$original_message_file", $ticket_dir . $original_message_file); + $original_message_file_esc = mysqli_real_escape_string($mysqli, $original_message_file); + mysqli_query($mysqli, "INSERT INTO ticket_attachments SET ticket_attachment_name = 'Original-parsed-email.eml', ticket_attachment_reference_name = '$original_message_file_esc', ticket_attachment_reply_id = $reply_id, ticket_attachment_ticket_id = $ticket_id"); + } + + // An automatic reply - an out-of-office - is there to read, and that is all + if ($automatic === 'auto-reply') { + logTicketHistory($ticket_id, "$from_email_esc sent an automatic reply - kept as a note"); + return true; + } + + // A closed ticket isn't reopened. Agents are told it is on it, and the client or watcher that nobody will act on it - + // not a stranger (a guessed number would tell them the ticket's subject), an agent, or anything automatic, whose + // answer would only be answered, and not more than a few times an hour (functions/ticket_mail_auto.php) + if ($closed) { + appNotify("Ticket", "Email parser: $from_email replied to closed ticket $ticket_reference_esc - it is on the ticket as a note, and the ticket was not reopened", "/agent/ticket.php?ticket_id=$ticket_id$client_uri", $client_id, $ticket_id); + logTicketHistory($ticket_id, "$from_email_esc replied after it was closed - kept as a note"); + if (in_array($who, ['contact', 'watcher'], true) && $automatic === '' && ticketMailAnswersLeft(stripslashes($from_email))) { + ticketMailClosedReply($ticket_id, stripslashes($from_email), (string) ($email['message_id'] ?? '')); + } + return true; + } + + if ($who === 'agent') { + logTicketHistory($ticket_id, "$from_email_esc (an agent) emailed - added as their internal note"); + logAudit("Ticket", "Edit", "Email parser: Agent $from_email_esc added an internal note to ticket $ticket_reference_esc ($subject)", $client_id, $ticket_id); + return true; + } + + // The people the client or a watcher also wrote to, or copied in, follow the ticket from now on - as + // they would have in a conversation by email. Not a stranger's: anyone can put a number in a subject + if (!$stranger && ($watching = ticketMailCopiedWatchers($ticket_id, (array) ($email['copied'] ?? []), stripslashes($from_email)))) { + logTicketHistory($ticket_id, escapeSql(implode(', ', $watching)) . (count($watching) === 1 ? ' is' : ' are') . " watching now - copied in on an email from $from_email_esc"); + } + + // The agent it is assigned to, with what they wrote - a stranger's as plain text + $mail_reply = (string) getFieldById('ticket_replies', $reply_id, 'ticket_reply'); + if ($stranger) { + $mail_reply = nl2br(escapeHtml(trim(html_entity_decode(strip_tags(preg_replace('//i', "\n", $mail_reply)), ENT_QUOTES, 'UTF-8')))); + } + ticketMailAssigneeReplied($ticket_id, 'email', $mail_reply, $by_name); + + if ($stranger) { + logTicketHistory($ticket_id, "$from_email_esc (not a contact, watcher or agent) emailed - kept as an internal note, the ticket was not reopened"); + logAudit("Ticket", "Edit", "Email parser: $from_email_esc (not a contact, watcher or agent) emailed ticket $ticket_reference_esc ($subject) - kept as an internal note", $client_id, $ticket_id); + return true; + } + + // A client's reply goes on to the people following the ticket who weren't on the email - only one that answers an + // email of the ticket's: a ticket number in a subject is all a forged email needs, and this would carry its words + // to them from your own mailbox (ticketMailRelayClientReply()). Nothing automatic + if (!empty($email['threaded']) && $automatic === '') { + ticketMailRelayClientReply($ticket_id, $reply_id, $by_name, stripslashes($from_email), (array) ($email['had'] ?? []), (string) ($email['message_id'] ?? '')); + } + + // Back to Open - unless it is in a status of your own set to stay put when the client replies (Scheduled, say) + $new_ticket_status = ticketStatusAfterClientReply($ticket_status); + mysqli_query($mysqli, "UPDATE tickets SET ticket_status = $new_ticket_status, ticket_resolved_at = NULL WHERE ticket_id = $ticket_id AND ticket_client_id = $client_id LIMIT 1"); + // A resolved ticket's resolution clock runs again - an open one keeps its alerts, so a warning isn't sent twice + if ($ticket_status === TICKET_STATUS_RESOLVED) { + resetTicketResolutionSla($ticket_id); + } else { + syncTicketSlaClock($ticket_id); + } + + // Only record the reopen when the ticket was not already open + if ($ticket_status !== intval($new_ticket_status)) { + logTicketHistory($ticket_id, "$from_email_esc replied by email, reopening the ticket"); + } + + logAudit("Ticket", "Edit", "Email parser: " . ($who === 'watcher' ? 'Watcher' : 'Client contact') . " $from_email_esc updated ticket $ticket_reference_esc ($subject)", $client_id, $ticket_id); + triggerCustomAction('ticket_reply_client', $ticket_id); + return true; } /** ------------------------------------------------------------------ @@ -745,24 +825,19 @@ foreach ($messages as $message) { continue; } - // Skip vacation/out-of-office auto-responders to prevent mail loops (RFC 3834) - // Some* NDRs use "auto-generated" and are still handled by the NDR logic below - // Todo: Combine with the NDR logic so we can update the ticket too - $auto_submitted = strtolower((string)($message->header('Auto-Submitted')?->getValue() ?? '')); - $precedence = strtolower((string)($message->header('Precedence')?->getValue() ?? '')); - if (str_starts_with($auto_submitted, 'auto-replied') || $precedence === 'auto_reply') { - logApp("Cron-Email-Parser", "info", "Email parser skipped auto-responder from $from_email ($subject)"); - appNotify( - "Mail", - "Email parser: Skipped auto-responder message from $from_email. Subject: $subject", - "", - 0 - ); + // What kind of email it is - a mail server's bounce, an automatic reply, or one sent by a system or a list - by its + // headers (functions/ticket_mail_auto.php). A bounce is read now, whatever the settings: it is never a ticket and + // never answered. It used to be read only with unknown senders on, as the last step, and an address with "mta", + // "daemon" or "bounce" anywhere in it was taken for a mail server + $headers = ticketMailHeaderMap($message); + if (ticketMailIsBounce($headers, stripslashes($from_email))) { + addBounce($message, $headers, $from_email, $subject); $processed_count++; $message->markSeen(); $message->move($targetFolderPath); continue; } + $automatic = ticketMailAutomaticKind($headers, stripslashes($subject)); // The same email a second time - sent to two of your addresses that both land in this mailbox, say - is on its // ticket already, kept by its Message-ID (functions/ticket_mail_thread.php). Taken again, it was a second ticket @@ -796,7 +871,8 @@ foreach ($messages as $message) { // Where it is in an email conversation - the Message-IDs it answers $in_reply_to = (string) ($message->header('In-Reply-To')?->getRawValue() ?? ''); $references = (string) ($message->header('References')?->getRawValue() ?? ''); - $email = ['message_id' => $email_message_id, 'copied' => $copied, 'had' => array_values(array_unique(array_filter($had))), 'threaded' => false]; + $email = ['message_id' => $email_message_id, 'from_name' => $from_name, 'copied' => $copied, 'had' => array_values(array_unique(array_filter($had))), 'threaded' => false, + 'automatic' => $automatic]; // Date (string) $dateObj = $message->date(); // ?CarbonInterface @@ -859,7 +935,16 @@ foreach ($messages as $message) { $email_processed = addReply($from_email, $date, $subject, $subject_ticket['ticket_id'], $message_body, $attachments, $original_message_file, $email); } - // 3. Fuzzy duplicate check using a known contact/domain and similar_text subject + // An automatic reply - an out-of-office - that answers no ticket is set aside: it isn't a ticket, and isn't answered + if (!$email_processed && $automatic === 'auto-reply') { + logApp("Cron-Email-Parser", "info", "Email parser set aside an automatic reply from $from_email ($subject) - it answers no ticket"); + $email_processed = true; + } + + // 3. Almost the same subject as an open ticket of the sender's client from the last week - a reply on it when they are + // its contact or watching it. From anyone else at the client it is a ticket of its own, linked to that one as related + // (linkSimilarTicket()): two people with "Printer not working" in a week used to land on one ticket + $similar_ticket_id = 0; if (!$email_processed && strlen(trim($subject)) > 10) { $contact_id = 0; $client_id = 0; @@ -886,7 +971,7 @@ foreach ($messages as $message) { // If we found either a contact or a domain, check recent tickets for a matching subject if ($client_id) { $recent_tickets_sql = mysqli_query($mysqli, - "SELECT ticket_id, ticket_subject + "SELECT ticket_id, ticket_subject, ticket_contact_id FROM tickets WHERE ticket_client_id = $client_id AND ticket_resolved_at IS NULL AND ticket_created_at >= DATE_SUB(NOW(), INTERVAL 7 DAY)" @@ -899,8 +984,14 @@ foreach ($messages as $message) { similar_text(strtolower($subject), strtolower($existing_subject), $percent); if ($percent >= 95) { - // Treat as a reply/duplicate - $email_processed = addReply($from_email, $date, $subject, intval($rowt['ticket_id']), $message_body, $attachments, $original_message_file, $email); + $similar_id = intval($rowt['ticket_id']); + $theirs = ($contact_id && $contact_id === intval($rowt['ticket_contact_id'])) + || mysqli_num_rows(mysqli_query($mysqli, "SELECT 1 FROM ticket_watchers WHERE watcher_ticket_id = $similar_id AND watcher_email = '$from_email_esc' LIMIT 1")); + if ($theirs) { + $email_processed = addReply($from_email, $date, $subject, $similar_id, $message_body, $attachments, $original_message_file, $email); + } else { + $similar_ticket_id = $similar_id; + } break; } } @@ -919,7 +1010,7 @@ foreach ($messages as $message) { $contact_email = escapeSql($rowc['contact_email']); $client_id = intval($rowc['contact_client_id']); - $email_processed = addTicket($contact_id, $contact_name, $contact_email, $client_id, $date, $subject, $message_body, $attachments, $original_message_file, $copied, $email_message_id); + $email_processed = addTicket($contact_id, $contact_name, $contact_email, $client_id, $date, $subject, $message_body, $attachments, $original_message_file, $copied, $email_message_id, $automatic); } } @@ -941,113 +1032,18 @@ foreach ($messages as $message) { logAudit("Contact", "Create", "Email parser: created contact " . mysqli_real_escape_string($mysqli, $contact_name), $client_id, $contact_id); triggerCustomAction('contact_create', $contact_id); - $email_processed = addTicket($contact_id, $contact_name, $contact_email, $client_id, $date, $subject, $message_body, $attachments, $original_message_file, $copied, $email_message_id); + $email_processed = addTicket($contact_id, $contact_name, $contact_email, $client_id, $date, $subject, $message_body, $attachments, $original_message_file, $copied, $email_message_id, $automatic); } } - // 6. Unknown sender allowed? + // 6. Unknown sender allowed? A ticket with no client - a mail server's bounce never gets here if (!$email_processed && $config_ticket_email_parse_unknown_senders) { + $email_processed = addTicket(0, $from_name, $from_email, 0, $date, $subject, $message_body, $attachments, $original_message_file, $copied, $email_message_id, $automatic); + } - $bad_from_pattern = "/daemon|postmaster|bounce|mta/i"; // Stop NDRs with bad subjects raising new tickets - if (!preg_match($bad_from_pattern, $from_email)) { - $email_processed = addTicket(0, $from_name, $from_email, 0, $date, $subject, $message_body, $attachments, $original_message_file, $copied, $email_message_id); - - } else { - - // Probably an NDR message without a ticket ref in the subject - - $failed_recipient = null; - $diagnostic_code = null; - $status_code = null; - $original_subject = null; - $original_to = null; - - // ImapEngine: walk the parsed MIME parts to find DSN info - foreach ($message->parse()->getAllParts() as $part) { - - $ctype = strtolower((string)$part->getContentType()); - $body = $part->getContent() ?? ''; - - // 1. Delivery status block - if (strpos($ctype, 'delivery-status') !== false) { - - if (preg_match('/Final-Recipient:\s*rfc822;\s*(.+)/i', $body, $m)) { - $failed_recipient = escapeSql(trim($m[1])); - } - - if (preg_match('/Diagnostic-Code:\s*(.+)/i', $body, $m)) { - $diagnostic_code = escapeSql(trim($m[1])); - } - - if (preg_match('/Status:\s*([0-9\.]+)/i', $body, $m)) { - $status_code = escapeSql(trim($m[1])); - } - } - - // 2. Original message headers - if (strpos($ctype, 'message/rfc822') !== false) { - - if (preg_match('/^To:\s*(.+)$/mi', $body, $m)) { - $original_to = escapeSql(trim($m[1])); - } - - if (preg_match('/^Subject:\s*(.+)$/mi', $body, $m)) { - $original_subject = escapeSql(trim($m[1])); - } - } - } - - // 3. Fallback: extract diagnostic from human-readable text/plain - if (!$diagnostic_code) { - $text = $message->text() ?? ''; - - // Exim puts diagnostics on an indented line - if (preg_match('/\n\s{2,}(.+)/', $text, $m)) { - $diagnostic_code = escapeSql(trim($m[1])); - } - } - - // Fallbacks - $failed_recipient = $failed_recipient ?: 'unknown recipient'; - $diagnostic_code = $diagnostic_code ?: 'unknown diagnostic code'; - $status_code = $status_code ?: 'unknown status code'; - $original_subject = $original_subject ?: $subject; - - appNotify( - "Ticket", - "Email parser: NDR - Message to $failed_recipient bounced. Subject: $original_subject Diagnostics: $status_code / $diagnostic_code - check ITFlow folder manually to see email", - "", - 0 - ); - - // The contacts with that address show "Email bounced" until mail comes from it again (functions/contact_bounce.php) - foreach (contactBounceMark(stripslashes($failed_recipient), stripslashes("$status_code - $diagnostic_code")) as $bounced_contact_id => [$bounced_name, $bounced_client_id]) { - logAudit("Contact", "Edit", "Email parser: mail to " . escapeSql($bounced_name) . " bounced - marked on the contact", $bounced_client_id, $bounced_contact_id); - } - - // If the original subject has a ticket, add the NDR there too - if ($bounced_ticket = ticketMailSubjectTicket(stripslashes($original_subject))) { - - // Craft a clean bounce message - $reply_body = "Email delivery failed.\n". - "Recipient: $failed_recipient\n". - "Status: $status_code\n". - "Diagnostic: $diagnostic_code\n"; - - // No attachments - addReply( - $from_email, - $date, - $original_subject, - $bounced_ticket['ticket_id'], - $reply_body, - [] - ); - - } - - $email_processed = true; - } + // A new ticket whose subject is almost that of another's at the client, from someone else - linked as related + if ($similar_ticket_id && is_int($email_processed) && $email_processed > 0) { + linkSimilarTicket($email_processed, $similar_ticket_id); } diff --git a/db.sql b/db.sql index 2946d5a5c..6e3fca767 100644 --- a/db.sql +++ b/db.sql @@ -4960,6 +4960,8 @@ CREATE TABLE `ticket_replies` ( `ticket_reply_updated_at` datetime DEFAULT NULL ON UPDATE current_timestamp(), `ticket_reply_archived_at` datetime DEFAULT NULL, `ticket_reply_by` int(11) NOT NULL, + `ticket_reply_from_name` varchar(200) DEFAULT NULL, + `ticket_reply_from_email` varchar(255) DEFAULT NULL, `ticket_reply_ticket_id` int(11) NOT NULL, PRIMARY KEY (`ticket_reply_id`), KEY `ticket_reply_ticket_id` (`ticket_reply_ticket_id`,`ticket_reply_archived_at`), diff --git a/functions.php b/functions.php index f1cf04209..4aee1aafa 100644 --- a/functions.php +++ b/functions.php @@ -86,6 +86,7 @@ require_once __DIR__ . '/functions/ticket_helpers.php'; require_once __DIR__ . '/functions/ticket_link.php'; require_once __DIR__ . '/functions/ticket_pictures.php'; require_once __DIR__ . '/functions/ticket_mail_thread.php'; +require_once __DIR__ . '/functions/ticket_mail_auto.php'; require_once __DIR__ . '/functions/user_timezone.php'; require_once __DIR__ . '/functions/dispatch.php'; require_once __DIR__ . '/functions/project_tickets.php'; diff --git a/functions/ai_ticket.php b/functions/ai_ticket.php index db389c932..2cf4e801f 100644 --- a/functions/ai_ticket.php +++ b/functions/ai_ticket.php @@ -99,7 +99,7 @@ function aiTicketContext($ticket_id, $internal = true) { // The conversation - who each reply is from, and whether the client saw it $replies = []; - $sql = mysqli_query($mysqli, "SELECT ticket_reply, ticket_reply_type, ticket_reply_created_at, user_name, contact_name + $sql = mysqli_query($mysqli, "SELECT ticket_reply, ticket_reply_type, ticket_reply_created_at, user_name, " . ticketReplyAuthorSql() . " FROM ticket_replies LEFT JOIN users ON ticket_reply_type <> 'Client' AND user_id = ticket_reply_by LEFT JOIN contacts ON ticket_reply_type = 'Client' AND contact_id = ticket_reply_by diff --git a/functions/email.php b/functions/email.php index e4192d90b..bdf5404ba 100644 --- a/functions/email.php +++ b/functions/email.php @@ -551,6 +551,8 @@ function emailInlineImages($html, array $ticket = []) { * thread the ticket whose conversation it is in - it gets a Message-ID of its own and * In-Reply-To and References naming the emails before it (ticketMailHeaders()), * and answering, the Message-ID of the email it answers, when it answers one + * auto replied (an automatic answer to an email) or generated (sent by ITFlow by + * itself) - headers saying so, so it isn't answered (ticketMailAutoHeaders()) * Who it was queued to, "Name (email)" - the copied in too. Nothing is queued without mail set up. */ function emailQueue(array $recipients, $subject, array $email, array $opts = []) { @@ -578,6 +580,7 @@ function emailQueue(array $recipients, $subject, array $email, array $opts = []) // Where the ticket's conversation stands as it is written - each email answers that $thread_id = intval($opts['thread'] ?? 0); $thread = $thread_id && ticketMailThreadReady() ? ticketMailThread($thread_id, (string) ($opts['answering'] ?? '')) : null; + $auto_headers = !empty($opts['auto']) ? ticketMailAutoHeaders((string) $opts['auto']) : []; $data = []; $sent = []; @@ -615,7 +618,7 @@ function emailQueue(array $recipients, $subject, array $email, array $opts = []) + (intval($opts['ticket_reply_id'] ?? 0) > 0 && ticketReplyEmailReady() ? ['ticket_reply_id' => intval($opts['ticket_reply_id'])] : []) + (!empty($opts['sensitive']) ? ['sensitive' => 1] : []) + ($cc_list ? ['cc' => $cc_list] : []) - + ($thread !== null ? ['headers' => ticketMailHeaders($thread_id, (string) $from['email'], $thread)] : []); + + ($thread !== null || $auto_headers ? ['headers' => ($thread !== null ? ticketMailHeaders($thread_id, (string) $from['email'], $thread) : []) + $auto_headers] : []); } if ($data) { addToMailQueue($data); diff --git a/functions/mail_queue.php b/functions/mail_queue.php index a6aa9caa2..cf2d391a7 100644 --- a/functions/mail_queue.php +++ b/functions/mail_queue.php @@ -306,18 +306,28 @@ function mailQueueCc($json) { return $out; } -/** The headers an email may carry (email_headers) - the ones that keep a conversation together, nothing else. */ -const MAIL_QUEUE_HEADERS = ['Message-ID', 'In-Reply-To', 'References']; +/* + * The headers an email may carry (email_headers), each with what its value must look like - the ones + * that keep a conversation together, and the ones that say an email was sent by ITFlow itself + * (ticketMailAutoHeaders()). Nothing else. + */ +const MAIL_QUEUE_HEADERS = [ + 'Message-ID' => '/^<[^<>\s]+@[^<>\s]+>$/', + 'In-Reply-To' => '/^<[^<>\s]+@[^<>\s]+>$/', + 'References' => '/^(<[^<>\s]+@[^<>\s]+>)( <[^<>\s]+@[^<>\s]+>)*$/', + 'Auto-Submitted' => '/^auto-(replied|generated)$/', + 'X-Auto-Response-Suppress' => '/^[A-Za-z]+(, ?[A-Za-z]+)*$/', +]; /* - * An email's own headers (email_headers, emailQueue()'s thread) - [name => value] of those it may - * carry (MAIL_QUEUE_HEADERS), each a list of and nothing else, on one line. + * An email's own headers (email_headers, emailQueue()'s thread and auto) - [name => value] of those + * it may carry (MAIL_QUEUE_HEADERS), each as it must look, on one line. */ function mailQueueHeaders($json) { $out = []; foreach ((array) json_decode((string) $json, true) as $name => $value) { $value = trim(preg_replace('/[\r\n\t ]+/', ' ', (string) $value)); - if (in_array($name, MAIL_QUEUE_HEADERS, true) && $value !== '' && strlen($value) <= 4000 && preg_match('/^(<[^<>\s]+@[^<>\s]+>)( <[^<>\s]+@[^<>\s]+>)*$/', $value)) { + if (isset(MAIL_QUEUE_HEADERS[$name]) && $value !== '' && strlen($value) <= 4000 && preg_match(MAIL_QUEUE_HEADERS[$name], $value)) { $out[$name] = $value; } } diff --git a/functions/project.php b/functions/project.php index 357abd487..c556626c4 100644 --- a/functions/project.php +++ b/functions/project.php @@ -461,7 +461,7 @@ function projectActivity($project_id, $limit = 20) { $project_id = intval($project_id); $sql = mysqli_query($mysqli, "SELECT ticket_reply_id, ticket_reply, ticket_reply_type, ticket_reply_time_worked, ticket_reply_created_at, ticket_id, ticket_prefix, ticket_number, ticket_subject, ticket_client_id, ticket_resolved_at, ticket_closed_at, - user_name, user_avatar, contact_name + user_name, user_avatar, " . ticketReplyAuthorSql() . " FROM ticket_replies JOIN tickets ON ticket_id = ticket_reply_ticket_id LEFT JOIN users ON ticket_reply_type <> 'Client' AND user_id = ticket_reply_by diff --git a/functions/ticket.php b/functions/ticket.php index 603bbd075..ea8aefc44 100644 --- a/functions/ticket.php +++ b/functions/ticket.php @@ -471,7 +471,7 @@ function ticketEmailHistory(array $row, array $opts = []) { $items = []; $left_out = 0; if ($opts['replies'] ?? true) { - $sql = mysqli_query($mysqli, "SELECT ticket_reply, ticket_reply_type, ticket_reply_created_at, contact_name, user_name FROM ticket_replies + $sql = mysqli_query($mysqli, "SELECT ticket_reply, ticket_reply_type, ticket_reply_created_at, " . ticketReplyAuthorSql() . ", user_name FROM ticket_replies LEFT JOIN users ON ticket_reply_type != 'Client' AND user_id = ticket_reply_by LEFT JOIN contacts ON ticket_reply_type = 'Client' AND contact_id = ticket_reply_by WHERE ticket_reply_ticket_id = $ticket_id AND ticket_reply_archived_at IS NULL AND ticket_reply_type IN ('Public', 'Client') @@ -627,7 +627,7 @@ function ticketEmailContent(array $row, $kind, array $opts = []) { $email['intro'] = ["Ticket $reference is closed. We hope it was sorted the way you wanted."]; $email['summary'] = $summary; $email['button']['label'] = 'Tell us how we did'; - $email['after'] = ['Need more help with this? Raise a new ticket - replies to this email do not reach us.']; + $email['after'] = ['Need more help with this? Raise a new ticket - a reply to this email isn\'t acted on, as the ticket is closed.']; $email['history'] = ticketEmailHistory($row, ['limit' => 3, 'label' => 'The conversation']); } elseif ($kind === 'scheduled') { $cancelled = !empty($opts['cancelled']); @@ -696,6 +696,7 @@ function ticketEmailPreview(array $email) { * ticket_reply_id the agent's reply it carries - each email is kept with it * (emailQueue()), for ticketReplyEmailed() * answering the Message-ID of the email it answers, when it answers one + * auto replied or generated - one of ITFlow's own automatic emails (emailQueue()'s auto) */ function ticketMailSend($ticket_id, array $email, array $opts = []) { global $mysqli; @@ -751,7 +752,7 @@ function ticketMailSend($ticket_id, array $email, array $opts = []) { 'together_footnote' => $to_contact ? "You get this as the contact on ticket $reference with $company_name, or copied in as someone following it - ask $company_name if you would like to stop." : "You get this because you are following ticket $reference with $company_name - ask $company_name if you would like to stop.", - 'thread' => $ticket_id, 'answering' => (string) ($opts['answering'] ?? '')])); + 'thread' => $ticket_id, 'answering' => (string) ($opts['answering'] ?? ''), 'auto' => (string) ($opts['auto'] ?? '')])); } /** Whether a ticket's contact gets an email of this $kind - no 'created' or 'closed' email for one who asked for replies only. */ @@ -825,7 +826,7 @@ function ticketMailColleaguesNew($ticket_id) { 'button' => ['label' => $colleague['portal'] ? 'View it in the portal' : 'View the ticket', 'url' => $url], 'contact' => ticketEmailContactLine(), 'office' => officeTicketFoot($ticket), - ], ['from' => ticketEmailFrom(), 'ticket_id' => $ticket_id, 'thread' => $ticket_id])); + ], ['from' => ticketEmailFrom(), 'ticket_id' => $ticket_id, 'thread' => $ticket_id, 'auto' => 'generated'])); } return $sent; } @@ -840,8 +841,9 @@ function ticketMailCreated($ticket_id, $attachments = [], $to_watchers = true, $ if (!$row) { return 0; } + // Emailed in, it is an automatic answer to that email - which says so, so the other side doesn't answer it (functions/ticket_mail_auto.php) return ticketMailSend($row['ticket_id'], ticketEmailContent($row, 'created', ['how' => $how]), - ['attachments' => $attachments, 'to_watchers' => $to_watchers, 'kind' => 'created'] + ($to !== null ? ['to' => $to] : [])); + ['attachments' => $attachments, 'to_watchers' => $to_watchers, 'kind' => 'created'] + ($to !== null ? ['to' => $to] : []) + ($how === 'email' ? ['auto' => 'replied'] : [])); } /* @@ -863,6 +865,31 @@ function ticketMailReply($ticket_id, $reply_html, $by, $resolved = false, $attac return $sent; } +/** Whether the 4.2.7 update has run - a client reply by email from someone who isn't a contact keeps who it came from. */ +function ticketReplyFromReady() { + global $mysqli; + static $ready = null; + if ($ready === null) { + if (defined('CURRENT_DATABASE_VERSION')) { + $version = CURRENT_DATABASE_VERSION; + } else { + $result = mysqli_query($mysqli, "SELECT config_current_database_version FROM settings WHERE company_id = 1"); + $version = $result && ($row = mysqli_fetch_row($result)) ? (string) $row[0] : '0'; + } + $ready = version_compare($version, '4.2.7', '>='); + } + return $ready; +} + +/* + * Who wrote a reply, for a SELECT joined to contacts on its ticket_reply_by - as contact_name: the + * contact, or for a client reply from someone who isn't one - a watcher, the person whose email + * raised a ticket with no client - the name and then the address it came from (4.2.7). + */ +function ticketReplyAuthorSql() { + return ticketReplyFromReady() ? "COALESCE(contact_name, NULLIF(ticket_reply_from_name, ''), ticket_reply_from_email) AS contact_name" : 'contact_name'; +} + /** Whether the 3.4.8 update has run - a reply keeps whether it was emailed and who to, and the mail queue which reply an email carried. */ function ticketReplyEmailReady() { global $mysqli; @@ -1263,7 +1290,8 @@ function ticketMailTaskApproval($approval_id, $by) { /* * Tell someone who replied to a closed ticket by email that it is closed, so - * their reply reached nobody - and how to raise a new one. $from_email raw; + * nobody will act on their reply - it is kept on the ticket as a note, but the + * ticket isn't reopened - and how to raise a new one. $from_email raw; * $answering the Message-ID of their reply, which this answers in the ticket's * conversation. */ @@ -1274,13 +1302,13 @@ function ticketMailClosedReply($ticket_id, $from_email, $answering = '') { } $support = ticketEmailFrom()['email']; return count(emailQueue([['email' => (string) $from_email, 'greet' => '', 'footnote' => 'You get this because you replied to a closed ticket.']], ticketEmailSubject($closed), [ - 'kind' => 'Ticket closed', 'tone' => 'warning', 'preview' => 'Your reply did not reach us - raise a new ticket instead', + '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, so your reply won't reach us.", "To raise a new ticket, send a new email to $support."], + '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])); + ], ['from' => ticketEmailFrom(), 'thread' => intval($closed['ticket_id']), 'answering' => (string) $answering, 'auto' => 'replied'])); } /* @@ -1886,7 +1914,7 @@ function ticketLastReplies(array $ticket_ids) { return []; } $sql = mysqli_query($mysqli, "SELECT ticket_reply_ticket_id, ticket_reply_type, ticket_reply_created_at, ticket_reply_by, - contact_name, contact_photo, contact_client_id, user_name, user_avatar + " . ticketReplyAuthorSql() . ", contact_photo, contact_client_id, user_name, user_avatar FROM ticket_replies LEFT JOIN users ON ticket_reply_type <> 'Client' AND ticket_reply_by = user_id LEFT JOIN contacts ON ticket_reply_type = 'Client' AND ticket_reply_by = contact_id diff --git a/functions/ticket_mail_auto.php b/functions/ticket_mail_auto.php new file mode 100644 index 000000000..a59d6e2b7 --- /dev/null +++ b/functions/ticket_mail_auto.php @@ -0,0 +1,177 @@ + Settings > Tickets says: the addresses it + * failed for are marked on their contacts, and the ticket the email was about gets + * a note. Never a ticket of its own, and never answered. + * auto-reply an out-of-office or other automatic answer (ticketMailAutomaticKind()) - an + * internal note on the ticket it answers, which it doesn't reopen; set aside + * when it answers none. + * automated sent by a system, a list or a newsletter - taken as usual, so alerts emailed + * in still make tickets, but never answered: no "we have your email", no + * closed-ticket answer, nothing passed on. + * A mail server or a robot that answers each email it gets would otherwise answer ITFlow's + * answer, and so on, every minute (RFC 3834). + * + * Going out, ITFlow's own automatic emails - the "we have your email", the closed-ticket answer, + * a client's reply passed on, a colleague's new-ticket email - say so (ticketMailAutoHeaders()), + * so the other side's out-of-office doesn't answer them, and no one address gets more than + * TICKET_MAIL_ANSWERS_AN_HOUR answers an hour (ticketMailAnswersLeft()). + */ + +/** The most automatic answers - "we have your email", "that ticket is closed" - one address gets in an hour. */ +const TICKET_MAIL_ANSWERS_AN_HOUR = 5; + +/** The mail servers' own names for themselves, before the @ - an email from one is a bounce. */ +const TICKET_MAIL_BOUNCE_SENDERS = ['mailer-daemon', 'mailer_daemon', 'maildaemon', 'mail-daemon', 'postmaster', 'mailerdaemon']; + +/* + * An email's headers, for the questions below - lower-case name => value (the first of each), + * from ImapEngine's message ($message->headers()). + */ +function ticketMailHeaderMap($message) { + $map = []; + foreach ($message->headers() as $header) { + $name = strtolower((string) $header->getName()); + if (!isset($map[$name])) { + $map[$name] = trim((string) $header->getRawValue()); + } + } + return $map; +} + +/* + * Whether an email is a mail server's report that an email couldn't be delivered: a delivery + * status report (multipart/report; report-type=delivery-status), an X-Failed-Recipients header + * (Exim), or from MAILER-DAEMON or postmaster. Only the part before the @ - an address with + * "mta", "daemon" or "bounce" anywhere in it used to count, so jmtaylor@ was a mail server. + */ +function ticketMailIsBounce(array $headers, $from_email) { + $type = strtolower((string) ($headers['content-type'] ?? '')); + if (strpos($type, 'multipart/report') !== false && preg_match('/report-type\s*=\s*"?delivery-status/', $type)) { + return true; + } + if (trim((string) ($headers['x-failed-recipients'] ?? '')) !== '') { + return true; + } + return ticketMailBounceSender($from_email); +} + +/** Whether an address is a mail server's own (TICKET_MAIL_BOUNCE_SENDERS), going by the part before the @. */ +function ticketMailBounceSender($email) { + $email = strtolower(trim((string) $email)); + $local = substr($email, 0, (int) strrpos($email, '@')); + return $local !== '' && in_array(preg_replace('/\+.*$/', '', $local), TICKET_MAIL_BOUNCE_SENDERS, true); +} + +/* + * What kind of email no person wrote this is - 'auto-reply', 'automated' or '' (a person wrote it). + * $headers as ticketMailHeaderMap(). + * auto-reply Auto-Submitted: auto-replied, Precedence: auto_reply, X-Autoreply or X-Autorespond - + * or a subject starting "Automatic reply:" or "Out of Office:" when it also asks not to + * be answered (X-Auto-Response-Suppress) or answers a ticket's email ([TCK-123]), as a + * person may well start a subject "Out of office:" + * automated Auto-Submitted anything but "no", Precedence bulk, list or junk, or a mailing list's + * List-Id or List-Unsubscribe + */ +function ticketMailAutomaticKind(array $headers, $subject) { + $submitted = strtolower(trim((string) ($headers['auto-submitted'] ?? ''))); + $precedence = strtolower(trim((string) ($headers['precedence'] ?? ''))); + if (strpos($submitted, 'auto-replied') === 0 || $precedence === 'auto_reply' || isset($headers['x-autoreply']) || isset($headers['x-autorespond'])) { + return 'auto-reply'; + } + if (preg_match('/^\s*(automatic reply|auto[- ]?reply|autoreply|out of (the )?office( auto ?reply)?)\s*:/i', (string) $subject) + && (isset($headers['x-auto-response-suppress']) || preg_match('/\[[^\[\]\s]{0,40}\d\]/', (string) $subject))) { + return 'auto-reply'; + } + if (($submitted !== '' && $submitted !== 'no') || in_array($precedence, ['bulk', 'list', 'junk'], true) || isset($headers['list-id']) || isset($headers['list-unsubscribe'])) { + return 'automated'; + } + return ''; +} + +/* + * What a bounce says, from its parts' text - each part [content type, content]: + * failed the addresses it failed for - Action: failed in its delivery status, else + * X-Failed-Recipients - [email => 'status - diagnostic'] + * delayed true when every address in it is only delayed - not a failure yet + * message_id the Message-ID of the email that bounced, from the copy or headers it returns + * subject that email's subject + * $failed_header is X-Failed-Recipients, $text the bounce's own text, for a diagnostic when its + * delivery status gives none. + */ +function ticketMailBounceRead(array $parts, $failed_header = '', $text = '') { + $out = ['failed' => [], 'delayed' => false, 'message_id' => '', 'subject' => '']; + $actions = []; + foreach ($parts as [$type, $content]) { + $type = strtolower((string) $type); + $content = (string) $content; + if (strpos($type, 'delivery-status') !== false) { + // A block per recipient after the one about the whole report - split on blank lines + foreach (preg_split('/\r?\n\s*\r?\n/', $content) as $block) { + if (!preg_match('/^(?:Final|Original)-Recipient:\s*[^;\r\n]*;\s*]+@[^\s>]+)>?/mi', $block, $m)) { + continue; + } + $email = strtolower(trim($m[1])); + $action = preg_match('/^Action:\s*(\S+)/mi', $block, $a) ? strtolower($a[1]) : 'failed'; + $actions[] = $action; + if ($action !== 'failed') { + continue; + } + $status = preg_match('/^Status:\s*([0-9.]+)/mi', $block, $s) ? $s[1] : ''; + // A diagnostic can run on over indented lines + $diagnostic = preg_match('/^Diagnostic-Code:\s*(.+(?:\r?\n[ \t]+.+)*)/mi', $block, $d) ? trim(preg_replace('/\s+/', ' ', preg_replace('/^[^;]*;\s*/', '', $d[1]))) : ''; + $out['failed'][$email] = trim($status . ($status !== '' && $diagnostic !== '' ? ' - ' : '') . mb_substr($diagnostic, 0, 400)); + } + } elseif (strpos($type, 'message/rfc822') !== false || strpos($type, 'rfc822-headers') !== false) { + $head = preg_split('/\r?\n\r?\n/', $content, 2)[0]; + // Folded header lines unfolded + $head = preg_replace('/\r?\n[ \t]+/', ' ', $head); + if ($out['message_id'] === '' && preg_match('/^Message-ID:\s*(<[^>\s]+>)/mi', $head, $m)) { + $out['message_id'] = trim($m[1], '<>'); + } + if ($out['subject'] === '' && preg_match('/^Subject:\s*(.+)$/mi', $head, $m)) { + $out['subject'] = trim(iconv_mime_decode($m[1], ICONV_MIME_DECODE_CONTINUE_ON_ERROR, 'UTF-8') ?: $m[1]); + } + } + } + // Exim and others that say who in a header instead + if (!$out['failed'] && !$actions) { + foreach (preg_split('/[\s,]+/', (string) $failed_header) as $email) { + if (filter_var(trim($email, '<>'), FILTER_VALIDATE_EMAIL)) { + $diagnostic = preg_match('/\n\s{2,}(\S.+)/', (string) $text, $d) ? trim($d[1]) : ''; + $out['failed'][strtolower(trim($email, '<>'))] = mb_substr($diagnostic, 0, 400); + } + } + } + $out['delayed'] = !$out['failed'] && $actions && !array_diff($actions, ['delayed']); + return $out; +} + +/* + * The headers of one of ITFlow's own automatic emails - $kind 'replied' for an answer to an email + * ("we have your email", "that ticket is closed"), 'generated' for one sent by itself (a client's + * reply passed on). They tell the other side's mail server and out-of-office not to answer it. + */ +function ticketMailAutoHeaders($kind) { + return ['Auto-Submitted' => $kind === 'replied' ? 'auto-replied' : 'auto-generated', 'X-Auto-Response-Suppress' => 'OOF, AutoReply']; +} + +/* + * Whether $email may be sent one more automatic answer this hour - fewer than + * TICKET_MAIL_ANSWERS_AN_HOUR queued to it already (an answer carries Auto-Submitted: auto-replied). + * A sender that emails every minute, or answers each answer, is answered five times, not forever. + */ +function ticketMailAnswersLeft($email) { + global $mysqli; + if (!ticketMailThreadReady()) { + return true; + } + $count = intval(mysqli_fetch_row(mysqli_query($mysqli, "SELECT COUNT(*) FROM email_queue WHERE email_recipient = '" . mysqli_real_escape_string($mysqli, trim((string) $email)) . "' + AND email_queued_at >= NOW() - INTERVAL 1 HOUR AND email_headers LIKE '%auto-replied%'"))[0] ?? 0); + return $count < TICKET_MAIL_ANSWERS_AN_HOUR; +} diff --git a/functions/ticket_mail_thread.php b/functions/ticket_mail_thread.php index 440e4b7d3..5f650cd4d 100644 --- a/functions/ticket_mail_thread.php +++ b/functions/ticket_mail_thread.php @@ -298,5 +298,6 @@ function ticketMailRelayClientReply($ticket_id, $reply_id, $by, $author_email, a 'recipients' => ticketReplyRecipientsPick($ticket_id, $recipients, false), 'attachments' => filterEmailableAttachments($attachments)['send'], 'answering' => $answering, + 'auto' => 'generated', ]); } diff --git a/functions/ticket_mail_try.php b/functions/ticket_mail_try.php index 666be30d9..bf17d4af7 100644 --- a/functions/ticket_mail_try.php +++ b/functions/ticket_mail_try.php @@ -7,7 +7,9 @@ * questions in the same order, against the same records: * * 0. ITFlow's own email come back (emailOwnAddresses()) is skipped; - * 1. an automatic reply (out of office) is skipped; + * - a mail server's bounce (ticketMailIsBounce() - here, by its address alone) is read as one, + * whatever the settings - never a ticket; + * 1. an automatic reply (out of office) is a note on the ticket it answers, or set aside; * - an email answering one of a ticket's emails, by its In-Reply-To or * References - a reply on that ticket, whatever its subject. An email * typed in here has no such headers, so this says so and goes on; @@ -16,12 +18,12 @@ * as whoever sent it is to the ticket (its contact or another of the * client's, an agent, a watcher, or a stranger), or a closed one turned away; * 3. a subject almost the same as an open ticket of the sender's client from - * the last 7 days - a reply on that ticket; + * the last 7 days - a reply on that ticket from its contact or a watcher, and + * from anyone else at the client a new ticket linked to it as related; * 4. a contact's address - a new ticket for their client; * 5. an address at a client's domain - a new contact, and a ticket; - * 6. anyone else - a ticket with no client when unknown senders are let in - * (a mail server's bounce is read as one instead), else left in the - * mailbox, flagged. + * 6. anyone else - a ticket with no client when unknown senders are let in, + * else left in the mailbox, flagged. * * Kept in step with the parser by hand - change one, change the other. */ @@ -29,7 +31,8 @@ /* * The steps it went through, each [question, answer], and where it ended up: * ['steps', 'outcome' => [icon, tone, title, text]]. $auto_reply is the email - * saying it is an automatic reply (Auto-Submitted: auto-replied). + * saying it is an automatic reply (Auto-Submitted: auto-replied, and the others + * ticketMailAutomaticKind() reads). */ function ticketMailTry($from_email, $subject, $auto_reply = false) { global $mysqli, $config_ticket_email_parse, $config_ticket_email_parse_unknown_senders, $config_ticket_prefix; @@ -53,9 +56,23 @@ function ticketMailTry($from_email, $subject, $auto_reply = false) { } $steps[] = ['From one of ITFlow\'s own addresses?', 'No']; + // A mail server's bounce - here by its address, as an email typed in has no headers or report in it + if (ticketMailBounceSender($from_email)) { + $steps[] = ['A mail server saying an email couldn\'t be delivered?', 'Yes - from ' . $from_email]; + return $end('fa-envelope-open-text', 'info', 'Read as a bounce', + 'Never a ticket, and never answered - whatever the settings. The contacts with the address it failed for are marked Email bounced, the ticket the email was about gets a note, and agents get a notice. A notice that an email is only delayed is set aside.'); + } + $steps[] = ['A mail server saying an email couldn\'t be delivered?', 'No']; + if ($auto_reply) { $steps[] = ['An automatic reply?', 'Yes']; - return $end('fa-forward', 'secondary', 'Skipped', 'Out-of-office and other automatic replies are moved to the ITFlow folder without a ticket, so two systems can\'t answer each other forever. Agents get a notice.'); + $answered = ticketMailSubjectTicket($subject); + if ($answered) { + return $end('fa-robot', 'secondary', 'An internal note on ' . $answered['reference'], + 'Out-of-office and other automatic replies go on the ticket they answer as a note, to read - it isn\'t reopened, nothing is passed on, and nobody is answered, so two systems can\'t answer each other forever.'); + } + return $end('fa-forward', 'secondary', 'Set aside', + 'It answers no ticket, so it is moved to the ITFlow folder without one, and isn\'t answered.'); } $steps[] = ['An automatic reply?', 'No']; @@ -81,11 +98,12 @@ function ticketMailTry($from_email, $subject, $auto_reply = false) { $domain_row = null; } - // 3. Almost the same subject as an open ticket of theirs from the last week + // 3. Almost the same subject as an open ticket of theirs from the last week - a reply from its contact or a watcher; from + // anyone else at the client, a ticket of its own linked to it $client_id = $contact ? intval($contact['contact_client_id']) : ($domain_row ? intval($domain_row['domain_client_id']) : 0); $similar = null; if (strlen(escapeSql($subject)) > 10 && $client_id) { - $sql = mysqli_query($mysqli, "SELECT ticket_id, ticket_prefix, ticket_number, ticket_subject FROM tickets WHERE ticket_client_id = $client_id AND ticket_resolved_at IS NULL + $sql = mysqli_query($mysqli, "SELECT ticket_id, ticket_prefix, ticket_number, ticket_subject, ticket_contact_id FROM tickets WHERE ticket_client_id = $client_id AND ticket_resolved_at IS NULL AND ticket_created_at >= DATE_SUB(NOW(), INTERVAL 7 DAY)"); while ($row = mysqli_fetch_assoc($sql)) { similar_text(strtolower(escapeSql($subject)), strtolower($row['ticket_subject']), $percent); @@ -95,17 +113,25 @@ function ticketMailTry($from_email, $subject, $auto_reply = false) { } } } - if ($similar && ($reply = ticketMailTryReply($from_email, intval($similar['ticket_id'])))) { - $steps[] = ['The same subject as an open ticket of theirs from the last week?', 'Yes - ' . ticketReference($similar)]; - return ['steps' => $steps, 'outcome' => $reply]; + $linked = ''; + if ($similar) { + $theirs = ($contact && intval($contact['contact_id']) === intval($similar['ticket_contact_id'])) + || mysqli_num_rows(mysqli_query($mysqli, "SELECT 1 FROM ticket_watchers WHERE watcher_ticket_id = " . intval($similar['ticket_id']) . " AND watcher_email = '$from_sql' LIMIT 1")); + if ($theirs && ($reply = ticketMailTryReply($from_email, intval($similar['ticket_id'])))) { + $steps[] = ['The same subject as an open ticket of theirs from the last week?', 'Yes - ' . ticketReference($similar)]; + return ['steps' => $steps, 'outcome' => $reply]; + } + $steps[] = ['The same subject as an open ticket of theirs from the last week?', 'Yes - ' . ticketReference($similar) . ', but someone else\'s, so it carries on']; + $linked = ' It is linked to ' . ticketReference($similar) . ' as related, as its subject is almost the same, in case it is the same thing.'; + } else { + $steps[] = ['The same subject as an open ticket of theirs from the last week?', $client_id ? 'No' : 'No - they aren\'t a client\'s']; } - $steps[] = ['The same subject as an open ticket of theirs from the last week?', $client_id ? 'No' : 'No - they aren\'t a client\'s']; // 4. A contact if ($contact) { $steps[] = ['A contact\'s address?', 'Yes - ' . $contact['contact_name'] . ($contact['client_name'] !== null ? ', ' . $contact['client_name'] : '')]; return ['steps' => $steps, 'outcome' => ['fa-plus-circle', 'success', 'A new ticket for ' . ($contact['client_name'] ?? 'no client'), - 'From ' . $contact['contact_name'] . ', with the subject as its subject and the email as its details. ' . ticketMailTryNoReply($from_email)]]; + 'From ' . $contact['contact_name'] . ', with the subject as its subject and the email as its details. ' . ticketMailTryNoReply($from_email) . $linked]]; } $steps[] = ['A contact\'s address?', 'No']; @@ -113,7 +139,7 @@ function ticketMailTry($from_email, $subject, $auto_reply = false) { if ($domain_row) { $steps[] = ['At a client\'s domain?', 'Yes - ' . $domain . ', ' . $domain_row['client_name']]; return ['steps' => $steps, 'outcome' => ['fa-plus-circle', 'success', 'A new contact and ticket for ' . $domain_row['client_name'], - 'The sender is added as a contact of ' . $domain_row['client_name'] . ' with the name in their email, and the ticket is theirs. ' . ticketMailTryNoReply($from_email)]]; + 'The sender is added as a contact of ' . $domain_row['client_name'] . ' with the name in their email, and the ticket is theirs. ' . ticketMailTryNoReply($from_email) . $linked]]; } $steps[] = ['At a client\'s domain?', $domain !== '' ? 'No - no client has ' . $domain : 'No']; @@ -124,10 +150,6 @@ function ticketMailTry($from_email, $subject, $auto_reply = false) { 'Unread and flagged for someone to look at. Turn on Tickets from unknown senders to make them tickets with no client.']]; } $steps[] = ['Tickets from unknown senders?', 'On']; - if (preg_match('/daemon|postmaster|bounce|mta/i', $from_email)) { - return ['steps' => $steps, 'outcome' => ['fa-envelope-open-text', 'info', 'Read as a bounce', - 'From a mail server, so it is read as a message that couldn\'t be delivered: agents get a notice, the contacts with the address it bounced from are marked, and a ticket number in the original subject gets the bounce as a note. No ticket is made.']]; - } return ['steps' => $steps, 'outcome' => ['fa-plus-circle', 'success', 'A new ticket with no client', 'Open for an agent to give it a client. The sender is added as a watcher, so replies reach them. ' . ticketMailTryNoReply($from_email)]]; } @@ -147,11 +169,15 @@ function ticketMailTryReply($from_email, $ticket_id) { } $reference = ticketReference($ticket); $on = $reference . ' - ' . $ticket['ticket_subject'] . ($ticket['client_name'] !== null ? ' (' . $ticket['client_name'] . ')' : ''); - if (intval($ticket['ticket_status']) === 5) { - return ['fa-ban', 'warning', "Not added - $reference is closed", - 'Closed tickets aren\'t reopened by email. Agents get a notice to look at it in the mailbox' . (preg_match('/daemon|postmaster|bounce|mta/i', $from_email) ? '' : ', and the sender is told and how to raise a new one') . '.']; - } $client_id = intval($ticket['ticket_client_id']); + $known = (strtolower((string) $ticket['contact_email']) === $from_email && $from_email !== '') + || ($client_id && mysqli_num_rows(mysqli_query($mysqli, "SELECT 1 FROM contacts WHERE contact_email = '$from_sql' AND contact_client_id = $client_id AND contact_archived_at IS NULL LIMIT 1"))) + || mysqli_num_rows(mysqli_query($mysqli, "SELECT 1 FROM ticket_watchers WHERE watcher_ticket_id = " . intval($ticket['ticket_id']) . " AND watcher_email = '$from_sql' LIMIT 1")); + if (intval($ticket['ticket_status']) === TICKET_STATUS_CLOSED) { + return ['fa-ban', 'warning', "A note on $reference - it is closed", + 'Closed tickets aren\'t reopened by email: it is kept on the ticket as an internal note, and agents get a notice' + . ($known ? '. The sender is told it is closed, and how to raise a new ticket.' : '. The sender isn\'t a contact or watcher, so nobody is told - a guessed number would tell them its subject.')]; + } $reopens = ticketMailTryReopens($ticket['ticket_status']); if (strtolower((string) $ticket['contact_email']) === $from_email && $from_email !== '') { return ['fa-reply', 'success', "A reply on $on", 'From its contact, ' . $ticket['contact_name'] . ', as the client\'s reply. ' . $reopens]; @@ -166,7 +192,7 @@ function ticketMailTryReply($from_email, $ticket_id) { } $watcher = mysqli_num_rows(mysqli_query($mysqli, "SELECT 1 FROM ticket_watchers WHERE watcher_ticket_id = " . intval($ticket['ticket_id']) . " AND watcher_email = '$from_sql' LIMIT 1")); if ($watcher) { - return ['fa-sticky-note', 'info', "An internal note on $on", 'From one of its watchers, marked as not from its contact. ' . $reopens]; + return ['fa-reply', 'success', "A reply on $on", 'From one of its watchers, as the client\'s reply. ' . $reopens]; } return ['fa-user-secret', 'warning', "An internal note on $on, with a warning", 'From someone who isn\'t a contact, a watcher or an agent - anyone can put a ticket number in a subject - so it is kept as a note marked as from a stranger, the ticket isn\'t reopened, and its attachments aren\'t added.']; diff --git a/guest/guest_view_ticket.php b/guest/guest_view_ticket.php index 353b12adf..720e28dc2 100644 --- a/guest/guest_view_ticket.php +++ b/guest/guest_view_ticket.php @@ -123,7 +123,7 @@ while ($row = mysqli_fetch_assoc($sql)) { // The conversation, oldest first $replies = mysqli_query($mysqli, "SELECT ticket_reply_id, ticket_reply, ticket_reply_type, ticket_reply_created_at, - contact_name, contact_photo, user_id, user_name, user_avatar + " . ticketReplyAuthorSql() . ", contact_photo, user_id, user_name, user_avatar FROM ticket_replies LEFT JOIN users ON ticket_reply_type != 'Client' AND ticket_reply_by = user_id LEFT JOIN contacts ON ticket_reply_type = 'Client' AND ticket_reply_by = contact_id