From 89645add5ef45fbafd08add2ba5905d0b0f46565 Mon Sep 17 00:00:00 2001 From: johnnyq Date: Tue, 1 Dec 2026 11:52:00 -0500 Subject: [PATCH] Shared support mailbox: with From unknown senders too off the email parser moves out of the inbox only what is ITFlow's, leaving flagged in the inbox a bounce or delay notice that is not about a ticket, an email ITFlow sent or a contact, a stranger's out-of-office reply that answers no email ITFlow sent, and email from the mailbox's own address that ITFlow did not send, which is still never a ticket; ITFlow's own email is told by its Message-ID, the mail queue, a ticket number in the subject or a ticket email it answers; nothing changes with unknown senders on; Try an Email says what is left; 26.12.3 changelog --- CHANGELOG.md | 9 ++-- cron/ticket_email_parser.php | 96 +++++++++++++++++++++++++---------- functions/email.php | 18 +++++++ functions/mail_queue.php | 29 +++++++---- functions/ticket_mail_try.php | 16 ++++-- 5 files changed, 126 insertions(+), 42 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 1105b7698..2045fb5d5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -63,8 +63,8 @@ Update from Maintenance > Update as usual - this release has fourteen database c - 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 CC, become its CCs - 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 CC'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 the agent it's assigned to gets a notice, or the admins when nobody has it or it's about no ticket, where every agent got one. 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. +- A bounce is read whether or not unknown senders are let in - with them off, when it is about a ticket, an email ITFlow sent or a contact: 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 the agent it's assigned to gets a notice, or the admins when nobody has it or it's about no ticket, where every agent got one. 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 - or left in the inbox when it is a stranger's and unknown senders are off. - 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 CC. - 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 - to the agent it was assigned to, or the admins when nobody had it. The ticket isn't reopened. The client or CC is told it is closed, as before - but not someone with no part in the ticket, who learned nothing from a number they guessed. @@ -86,6 +86,7 @@ Update from Maintenance > Update as usual - this release has fourteen database c - 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. - Ignored senders: Admin > Ignored Senders lists the addresses and domains whose email the ticket mailbox sets aside - no ticket, no reply on one, no answer and nothing in Unprocessed Email. Newsletters, spam that gets through and noisy systems go straight to the mailbox's ITFlow folder. A domain takes its subdomains too, each shows how many emails it set aside and when the last came, and saving one that would set aside a contact's or a client's email says so. A mail server's bounce is still read, and Try an Email shows the step. +- A support mailbox shared with other email: with From unknown senders too off, ITFlow takes out of the inbox only what is its own - email from contacts and clients' domains, replies to tickets, and bounces, delay notices and out-of-office replies that are about a ticket, an email ITFlow sent or a contact. The rest stays in the inbox, flagged so it isn't looked at again: a stranger's email, their out-of-office to an email someone sent from the mailbox by hand, a bounce for such an email (nobody gets a notice about it), and email from the mailbox's own address that ITFlow didn't send - a scanner emailing itself, a note to self - which is still never a ticket. With unknown senders on the mailbox is all ITFlow's, and everything is taken as before. - Bounces come back to the email they were about: a reply on a ticket says "Email to ... bounced" with what the mail server said, where it said it was emailed, and an invoice's or quote's history says its email bounced. The Mail Queue has a Bounced tab, and the email's window shows the mail server's reason. Each email ITFlow sends now has its own Message-ID, so the bounce finds it - one sent before the update is found by its address and subject. A bounce from an address the email wasn't sent to - someone's mail sent on to another mailbox - says where it came back from, and on an email to several people nobody is singled out for it. ### Bug Fixes @@ -96,7 +97,7 @@ Update from Maintenance > Update as usual - this release has fourteen database c - A client page opened without a client in its address, such as an old bookmark to a client's overview, was a blank page. It now says That client isn't here, as it does for a client that's been deleted, with the menu and a way back to Clients. - The notice that white-labelling was turned off opens Admin > Settings > Modules, instead of a page that isn't there. - The old Access Modules page, already off the Admin menu, is gone. What each role can do is set on the role, in Admin > Roles. -- A client who CCs your support mailbox no longer adds it to the ticket's CCs. As one, every email about the ticket went back into the mailbox, came back in as a note and reopened the ticket - a resolved ticket reopened a minute later. Mail from ITFlow's own addresses is now set aside in the ITFlow folder without a ticket, and nothing about a ticket is emailed to them, so a support mailbox already on a ticket's CCs stops getting copies too. +- A client who CCs your support mailbox no longer adds it to the ticket's CCs. As one, every email about the ticket went back into the mailbox, came back in as a note and reopened the ticket - a resolved ticket reopened a minute later. Mail from ITFlow's own addresses is never a ticket - ITFlow's own email come back is set aside in the ITFlow folder - and nothing about a ticket is emailed to them, so a support mailbox already on a ticket's CCs stops getting copies too. - Email new tickets to (Admin > Settings > Tickets) can't be the mailbox ITFlow reads tickets from any more: each notice could come back in as a new email and raise another ticket, whose notice raised another, every minute. One saved before isn't emailed. - Email someone opened before ITFlow got to it - Outlook marks an email read as soon as it shows it - is made a ticket now, when it came in the last hour. It used to stay in the mailbox for good. Read email older than that, such as what was there when the mailbox was connected, is left alone. - Emails to the ticket mailbox wait there while a database update is waiting to run, and come in once it has. Before, an email that came in during an update could fail and stay in the mailbox for good. @@ -171,7 +172,7 @@ Update from Maintenance > Update as usual - this release has fourteen database c - 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. -- Mail review stage 8: database 4.3.5 adds email_ignored_senders and email_queue.email_message_id (indexed, filled in from email_headers), email_about, email_bounced_at and email_bounce. functions/mail_ignore.php: mailIgnoreClean() takes an address or a domain (@ or *@ in front allowed), mailIgnoreFind() matches the From address - an address rule before a domain one, a domain matching its subdomains - and cron/ticket_email_parser.php sets the email aside (seen, moved, mailIgnoreHit()) after the bounce check, unless it is a MailUnprocessedMessage asked to make a ticket or reply; ticketMailTry() has the step. Admin > Ignored Senders (admin/email_ignored_senders.php, modals/email_ignored_sender/, admin/post/email_ignored_sender.php). The parser leaves email from someone who isn't a contact at a domain no client has (unknown senders off), or whose sender checks failed, in the inbox flagged as before 7b - mailUnprocessedLeave() keeps only an email that was taken and failed, or an agent's ask; ticketMailTry() says Left in the inbox. emailQueue() gives every email a Message-ID (emailMessageId()) where the conversation gave none and takes about (invoice:N, quote:N - billingEmailQueue()'s about, passed by every invoice and quote send); addToMailQueue() keeps both. addBounce() calls mailQueueBounced(): the sent row by email_message_id, else the last week's sent to a failed address with the bounce's subject, marked with {address: why}, and a billing email's history written. mailQueueStateOf() has bounced (status 3 with email_bounced_at), mailQueueTabs() a Bounced tab, ticketReplyEmailStates() marks each bounced recipient and the key bounced, and ticketReplyEmailHtml() says so. A report naming an address that isn't on the email, or nobody: on an email to one person it is theirs ("address: why"); on one to several the named address is kept in email_bounce as it is, nobody on it is marked, and the reply has elsewhere => [address or '' => why]. A billing email's history is written the first time and for each address more. .gitignore leaves out uploads/mail_unprocessed and uploads/kb, as the other upload folders. +- Mail review stage 8: database 4.3.5 adds email_ignored_senders and email_queue.email_message_id (indexed, filled in from email_headers), email_about, email_bounced_at and email_bounce. functions/mail_ignore.php: mailIgnoreClean() takes an address or a domain (@ or *@ in front allowed), mailIgnoreFind() matches the From address - an address rule before a domain one, a domain matching its subdomains - and cron/ticket_email_parser.php sets the email aside (seen, moved, mailIgnoreHit()) after the bounce check, unless it is a MailUnprocessedMessage asked to make a ticket or reply; ticketMailTry() has the step. Admin > Ignored Senders (admin/email_ignored_senders.php, modals/email_ignored_sender/, admin/post/email_ignored_sender.php). The parser leaves email from someone who isn't a contact at a domain no client has (unknown senders off), or whose sender checks failed, in the inbox flagged as before 7b - mailUnprocessedLeave() keeps only an email that was taken and failed, or an agent's ask; ticketMailTry() says Left in the inbox. emailQueue() gives every email a Message-ID (emailMessageId()) where the conversation gave none and takes about (invoice:N, quote:N - billingEmailQueue()'s about, passed by every invoice and quote send); addToMailQueue() keeps both. addBounce() calls mailQueueBounced(): the sent row by email_message_id, else the last week's sent to a failed address with the bounce's subject, marked with {address: why}, and a billing email's history written. mailQueueStateOf() has bounced (status 3 with email_bounced_at), mailQueueTabs() a Bounced tab, ticketReplyEmailStates() marks each bounced recipient and the key bounced, and ticketReplyEmailHtml() says so. A report naming an address that isn't on the email, or nobody: on an email to one person it is theirs ("address: why"); on one to several the named address is kept in email_bounce as it is, nobody on it is marked, and the reply has elsewhere => [address or '' => why]. A billing email's history is written the first time and for each address more. With config_ticket_email_parse_unknown_senders off the parser moves only what is ITFlow's: addBounce() takes $take_all and returns whether it was (a ticket by Message-ID or subject, emailMessageIdOurs() - itflow..@ or itflow.q.@, or in email_queue - mailQueueBounceRow(), the find split from mailQueueBounced(), or a contact's address), the own-address step moves only an email with ITFlow's Message-ID, a ticket's number in its subject or a ticket's email that it answers, and an auto-reply answering no ticket is set aside only from a contact, a client's domain or in answer to an ITFlow Message-ID (In-Reply-To, References); the rest is flagged and left, as a stranger's email is. .gitignore leaves out uploads/mail_unprocessed and uploads/kb, as the other upload folders. ## [26.12.2] diff --git a/cron/ticket_email_parser.php b/cron/ticket_email_parser.php index 55887c762..062211c76 100644 --- a/cron/ticket_email_parser.php +++ b/cron/ticket_email_parser.php @@ -250,18 +250,19 @@ function addTicket($contact_id, $contact_name, $contact_email, $client_id, $date * nobody has it or it is about no ticket (ticketNotifyOwner()). The email in the mail queue is marked Bounced * (mailQueueBounced(), functions/mail_queue.php) - an agent's reply says so, and an invoice's or quote's history. A report * that an email is only delayed is set aside. + * + * Whether it was ITFlow's to take: always when $take_all - unknown senders are let in, so everything in the mailbox is. + * Otherwise only a bounce about a ticket, an email ITFlow sent (its Message-ID, or in the mail queue) or a contact's + * address. One for an email someone sent from the mailbox by hand is none of those: false, nothing done, and the parser + * leaves it in the inbox. */ -function addBounce($message, array $headers, $from_email, $subject) { +function addBounce($message, array $headers, $from_email, $subject, $take_all = true) { 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']); @@ -269,6 +270,24 @@ function addBounce($message, array $headers, $from_email, $subject) { $numbered = ticketMailSubjectTicket($bounce['subject']) ?: ticketMailSubjectTicket(stripslashes($subject)); $ticket_id = intval($numbered['ticket_id'] ?? 0); } + + // ITFlow's, or someone else's (above) + if (!$take_all && !$ticket_id && !emailMessageIdOurs($bounce['message_id']) && !mailQueueBounceRow($bounce['message_id'], $bounce['failed'], $bounce['subject'])) { + $contacts = 0; + foreach (array_keys($bounce['failed']) as $failed) { + $contacts += intval(mysqli_fetch_row(mysqli_query($mysqli, "SELECT COUNT(*) FROM contacts WHERE LOWER(contact_email) = '" . escapeSql(strtolower((string) $failed)) . "' AND contact_archived_at IS NULL"))[0] ?? 0); + } + if (!$contacts) { + logApp("Cron-Email-Parser", "info", "Email parser left a mail server's report from $from_email ($subject) in the inbox - it isn't about a ticket, an email ITFlow sent or a contact"); + return false; + } + } + + 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 true; + } + $ticket = $ticket_id ? ticketRow($ticket_id) : null; $client_id = intval($ticket['ticket_client_id'] ?? 0); @@ -293,6 +312,7 @@ function addBounce($message, array $headers, $from_email, $subject) { } ticketNotifyOwner($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)))); + return true; } /* @@ -998,12 +1018,22 @@ foreach ($messages as $message) { $subject = escapeSql(mb_substr((string)$message->subject() ?: 'No Subject', 0, 500)); // ITFlow's own email come back - a copy to a CC that is this mailbox, a notice sent to it. Taken, it would - // go on the ticket as a note and reopen it, or raise a ticket that sends another, round and round + // go on the ticket as a note and reopen it, or raise a ticket that sends another, round and round. Never a ticket, + // then - and when unknown senders aren't let in, only what ITFlow sent is moved: by its Message-ID + // (emailMessageIdOurs()), or, where a mail relay gave it another, a ticket's number in its subject or a ticket's + // email that it answers. A scanner emailing the mailbox as itself, or a note to self, stays in the inbox, flagged if (in_array(strtolower(stripslashes($from_email)), $own_addresses, true)) { - logApp("Cron-Email-Parser", "info", "Email parser skipped an email from ITFlow's own address $from_email ($subject) - mail it sent came back to this mailbox"); - $processed_count++; - $message->markSeen(); - $message->move($targetFolderPath); + if ($config_ticket_email_parse_unknown_senders || $message instanceof MailUnprocessedMessage || emailMessageIdOurs(ticketMailIdClean((string) $message->messageId())) + || ticketMailSubjectTicket(stripslashes($subject)) + || ticketMailHeaderTicket((string) ($message->header('In-Reply-To')?->getRawValue() ?? ''), (string) ($message->header('References')?->getRawValue() ?? ''))) { + logApp("Cron-Email-Parser", "info", "Email parser skipped an email from ITFlow's own address $from_email ($subject) - mail it sent came back to this mailbox"); + $processed_count++; + $message->markSeen(); + $message->move($targetFolderPath); + } else { + $unprocessed_count++; + $message->markFlagged(); + } continue; } @@ -1013,10 +1043,15 @@ foreach ($messages as $message) { // "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); + // With unknown senders not let in, one that isn't about ITFlow's email stays in the inbox, flagged (addBounce()) + if (addBounce($message, $headers, $from_email, $subject, $config_ticket_email_parse_unknown_senders || $message instanceof MailUnprocessedMessage)) { + $processed_count++; + $message->markSeen(); + $message->move($targetFolderPath); + } else { + $unprocessed_count++; + $message->markFlagged(); + } continue; } @@ -1208,15 +1243,6 @@ foreach ($messages as $message) { $email_processed = addReply($from_email, $date, $subject, $subject_ticket['ticket_id'], $message_body, $attachments, $original_message_file, $email); } - // 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 && !$asked_only && $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 a CC on 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. // The sender's contact - at the client whose domain it is, when they are one at more than one (ticketMailSenderContact()) - // or the client whose domain it is. A website form's ($answer) is never a contact: its client only $picked = ticketMailSenderContact($from_raw, $from_domain); @@ -1226,6 +1252,24 @@ foreach ($messages as $message) { $domain_row = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT domain_client_id, domain_name FROM domains WHERE domain_name = '" . escapeSql($from_domain) . "' AND domain_archived_at IS NULL LIMIT 1")); $domain_row = $domain_row && strcasecmp($from_domain, $domain_row['domain_name']) === 0 ? $domain_row : null; } + + // An automatic reply - an out-of-office - that answers no ticket is set aside: it isn't a ticket, and isn't answered. + // With unknown senders not let in, a stranger's is ITFlow's only when it answers an email ITFlow sent: an + // out-of-office to an email someone sent from the mailbox by hand goes on, and is left in the inbox as a stranger's is + if (!$email_processed && !$asked_only && $automatic === 'auto-reply') { + $answers_ours = false; + foreach (ticketMailIdsIn($in_reply_to . ' ' . $references) as $answered_id) { + $answers_ours = $answers_ours || emailMessageIdOurs($answered_id); + } + if ($config_ticket_email_parse_unknown_senders || $contact_row || ($domain_row && $forged === '') || $answers_ours || $message instanceof MailUnprocessedMessage) { + 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 a CC on 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 && !$asked_only && strlen(trim($subject)) > 10) { $contact_id = $contact_row && !$answer ? intval($contact_row['contact_id']) : 0; @@ -1334,9 +1378,9 @@ foreach ($messages as $message) { ); } } else { - // Not taken. From someone who isn't a contact, at a domain no client has (or not who it says) - not ITFlow's: left - // in the inbox as it is, flagged so it isn't looked at again, for whoever reads the mailbox. One that failed - kept - // for agents to sort (Tickets > Unprocessed Email), and out of the inbox like the rest + // Not taken. From someone who isn't a contact, at a domain no client has (or not who it says) - their out-of-office + // too - not ITFlow's: left in the inbox as it is, flagged so it isn't looked at again, for whoever reads the mailbox. + // One that failed - kept for agents to sort (Tickets > Unprocessed Email), and out of the inbox like the rest $unprocessed_count++; $not_ours = false; if ($asked_failed !== '') { diff --git a/functions/email.php b/functions/email.php index 06e737ec6..8263e3985 100644 --- a/functions/email.php +++ b/functions/email.php @@ -668,6 +668,24 @@ function emailMessageId($from_email) { return 'itflow.q.' . bin2hex(random_bytes(12)) . '@' . $domain; } +/* + * Whether a Message-ID is one ITFlow gave an email it sent - by how they are made (a ticket's itflow..@, + * ticketMailHeaders(); the rest itflow.q.@, emailMessageId()), or kept in the mail queue. The email parser + * tells ITFlow's own email, come back or bounced, from what someone sent from the mailbox by hand by it. + */ +function emailMessageIdOurs($message_id) { + global $mysqli; + $message_id = trim((string) $message_id, "<> \t\r\n"); + if ($message_id === '' || strlen($message_id) > 255) { + return false; + } + if (preg_match('/^itflow\.(?:q|\d+)\.[0-9a-f]{16,}@/i', $message_id)) { + return true; + } + return mailQueueBounceReady() + && (bool) mysqli_fetch_row(mysqli_query($mysqli, "SELECT 1 FROM email_queue WHERE email_message_id = '" . mysqli_real_escape_string($mysqli, $message_id) . "' LIMIT 1")); +} + /* * $text cut to the $length characters a column of the mail queue holds - its subject and names (255) - * with an ellipsis. A ticket's subject can be 500 characters, and an email about one too long for diff --git a/functions/mail_queue.php b/functions/mail_queue.php index 9d8f9aa43..f96da49ad 100644 --- a/functions/mail_queue.php +++ b/functions/mail_queue.php @@ -201,16 +201,11 @@ function mailQueueBounceColumns() { } /* - * A mail server's bounce (addBounce(), cron/ticket_email_parser.php) for the email it was about - found by its Message-ID - * ($message_id, cleaned), else the latest sent in the last week to one of the addresses it failed for, with its subject - * ($subject, raw) - only ones that went (Sent). $failed is [address => why]. Marked Bounced, for those addresses - and a - * billing email's history says so, once for each address. The row as it was, or null when none is found. - * - * A report often names an address the email wasn't sent to - their mail is sent on to another mailbox, or the address is - * an alias - or names nobody. On an email to one person it is theirs, saying where it came back from. On one to several, - * which of them it was for can't be told: nobody on it is marked, and the address the report names is kept as it is. + * The sent email a mail server's bounce is about - by its Message-ID ($message_id, cleaned), else the latest sent in the + * last week to one of the addresses it failed for ($failed, [address => why]) with its subject ($subject, raw). Its row, + * or null - nothing is marked (mailQueueBounced() does that). */ -function mailQueueBounced($message_id, array $failed, $subject = '') { +function mailQueueBounceRow($message_id, array $failed, $subject = '') { global $mysqli; if (!mailQueueBounceReady()) { return null; @@ -227,6 +222,22 @@ function mailQueueBounced($message_id, array $failed, $subject = '') { $row = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT $columns FROM email_queue WHERE email_status = 3 AND email_sent_at > NOW() - INTERVAL 7 DAY AND email_subject = '" . mysqli_real_escape_string($mysqli, emailFit((string) $subject)) . "' AND LOWER(email_recipient) IN ($addresses) ORDER BY email_id DESC LIMIT 1")); } + return $row ?: null; +} + +/* + * A mail server's bounce (addBounce(), cron/ticket_email_parser.php) for the email it was about - found by its Message-ID + * ($message_id, cleaned), else the latest sent in the last week to one of the addresses it failed for, with its subject + * ($subject, raw) - only ones that went (Sent). $failed is [address => why]. Marked Bounced, for those addresses - and a + * billing email's history says so, once for each address. The row as it was, or null when none is found. + * + * A report often names an address the email wasn't sent to - their mail is sent on to another mailbox, or the address is + * an alias - or names nobody. On an email to one person it is theirs, saying where it came back from. On one to several, + * which of them it was for can't be told: nobody on it is marked, and the address the report names is kept as it is. + */ +function mailQueueBounced($message_id, array $failed, $subject = '') { + global $mysqli; + $row = mailQueueBounceRow($message_id, $failed, $subject); if (!$row) { return null; } diff --git a/functions/ticket_mail_try.php b/functions/ticket_mail_try.php index b3eba0198..a3bf7df88 100644 --- a/functions/ticket_mail_try.php +++ b/functions/ticket_mail_try.php @@ -6,7 +6,8 @@ * this address with this subject - without doing any of it. It asks the same * questions in the same order, against the same records: * - * 0. ITFlow's own email come back (emailOwnAddresses()) is skipped; + * 0. ITFlow's own email come back (emailOwnAddresses()) is skipped - anything else from one of those addresses is left + * in the inbox when unknown senders aren't let in; * - a mail server's bounce (ticketMailIsBounce() - here, by its address alone) is read as one, * whatever the settings - never a ticket; * - an ignored sender (mailIgnoreFind(), functions/mail_ignore.php) is set aside; @@ -55,7 +56,8 @@ function ticketMailTry($from_email, $subject, $auto_reply = false) { if (emailOwnAddress($from_email)) { $steps[] = ['From one of ITFlow\'s own addresses?', 'Yes']; - return $end('fa-sync-alt', 'secondary', 'Skipped', 'It is ITFlow\'s own email come back - a copy to this mailbox, or a notice sent to it - so it is moved to the ITFlow folder without a ticket. Taken, it would reopen the ticket, or raise one that sends another.'); + return $end('fa-sync-alt', 'secondary', 'Never a ticket', 'ITFlow\'s own email come back - a copy to this mailbox, or a notice sent to it - is moved to the ITFlow folder: taken, it would reopen the ticket, or raise one that sends another. ' + . ($config_ticket_email_parse_unknown_senders ? 'So is anything else from the address.' : 'Anything else from the address - a scanner emailing the mailbox as itself, a note to self - is left in the inbox, flagged.')); } $steps[] = ['From one of ITFlow\'s own addresses?', 'No']; @@ -63,7 +65,8 @@ function ticketMailTry($from_email, $subject, $auto_reply = false) { 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 the agent it is assigned to gets a notice - the admins, when nobody has it. A notice that an email is only delayed is set aside.'); + '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 the agent it is assigned to gets a notice - the admins, when nobody has it. A notice that an email is only delayed is set aside.' + . ($config_ticket_email_parse_unknown_senders ? '' : ' One that isn\'t about a ticket, an email ITFlow sent or a contact - for an email someone sent from the mailbox by hand - is left in the inbox, flagged.')); } $steps[] = ['A mail server saying an email couldn\'t be delivered?', 'No']; @@ -85,6 +88,13 @@ function ticketMailTry($from_email, $subject, $auto_reply = false) { 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.'); } + // A stranger's, with unknown senders not let in: ITFlow's only when it answers an email ITFlow sent - by its headers + $auto_known = $config_ticket_email_parse_unknown_senders || ticketMailSenderContact($from_email, $domain)['contact'] + || ($domain !== '' && mysqli_num_rows(mysqli_query($mysqli, "SELECT 1 FROM domains WHERE domain_name = '" . escapeSql($domain) . "' AND domain_archived_at IS NULL LIMIT 1"))); + if (!$auto_known) { + return $end('fa-inbox', 'warning', 'Left in the inbox - unless it answers an email ITFlow sent', + 'It answers no ticket, and is from someone who isn\'t a contact, at a domain no client has. One answering an email ITFlow sent - an invoice, say - is moved to the ITFlow folder; an out-of-office to an email someone sent from the mailbox by hand stays in the inbox, flagged.'); + } 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.'); }