From e57faeeb3a31a2be672a8e221423c7c83d1630ff Mon Sep 17 00:00:00 2001 From: johnnyq Date: Mon, 30 Nov 2026 18:22:59 -0500 Subject: [PATCH] Mail review stage 5: a website form's email is answered at the visitor in its Reply-To, who becomes the ticket's CC under the client whose domain the site is on or none, and Reply-To at the sender's own domain is taken as the sender; someone who isn't a contact is answered without their subject or the ticket's link, and a forged ticket or one with no contact no longer emails the client's colleagues; a client's reply on a ticket nobody is assigned goes to the new-ticket address or the admins, and bounce and closed-ticket notices go to the assigned agent or the admins instead of every agent; an email with no From is from nobody rather than itflow-guest@example.com; a forged email no longer clears Email bounced; an address that is a contact at two clients goes to the one whose domain it is or where they last raised a ticket, with a note; an agent's emailed reply that went to the client is their public reply and the first response; 26.12.3 changelog --- CHANGELOG.md | 14 +- admin/settings_notification.php | 2 +- admin/settings_ticket.php | 2 +- cron/ticket_email_parser.php | 272 ++++++++++++++++++++----------- functions/logging.php | 20 +++ functions/ticket.php | 68 ++++++-- functions/ticket_mail_auto.php | 43 +++++ functions/ticket_mail_thread.php | 89 ++++++++++ functions/ticket_mail_try.php | 38 +++-- 9 files changed, 422 insertions(+), 126 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 91a64856a..7601df830 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -57,15 +57,18 @@ Update from Maintenance > Update as usual - this release has eight database chan - 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 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. +- 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. - 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. 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. +- 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. - Mail queue: email goes out at a pace your mail host takes - 30 a minute to start, set under Pace in Admin > Settings > Mail, Sending - over one connection - password links and invites first, email from the contacts or clients list last. A host's limit doesn't lose email any more: the rest wait their turn. A failed email is tried again over about eight hours, sooner at first. An address the mail server says doesn't exist isn't tried again, and its contact shows Email bounced; turned away for any other reason - the server's own rules, a full mailbox - an email is tried again. A mail server ITFlow can't reach or sign in to costs no email a try - it waits, and goes once it can. Admins hear about the queue once an hour at most, where every agent got a notice for each failed email. - Every email has a plain text part beside its HTML, and names the machine sending it by ITFlow's own address rather than the server's own name ("vm", say) - both counted against an email with spam filters. -- Email-to-ticket checks who an email is really from, by what your mail server found as it arrived (SPF, DKIM and DMARC). An email that failed - DMARC for a domain that asks for forged email to be rejected or quarantined, or SPF with nothing else passing - is treated as from a stranger, whoever it says it's from: a reply is an internal note saying which check failed and reopens nothing, adds nobody and goes to nobody; a new email still makes a ticket, with a note, but copies nobody in and gets no answer; and it never makes a contact. An email that says it's from one of your agents isn't taken as their note. A domain that asks nothing of forged email (DMARC p=none) is taken as before. -- Email-to-ticket: someone who isn't a contact is answered "[TCK-123] We have your email", without their own subject. Anyone can send an email that says it's from someone else, and the answer carried their words to that person from your mailbox. +- Email-to-ticket checks who an email is really from, by what your mail server found as it arrived (SPF, DKIM and DMARC). An email that failed - DMARC for a domain that asks for forged email to be rejected or quarantined, or SPF with nothing else passing - is treated as from a stranger, whoever it says it's from: a reply is an internal note saying which check failed and reopens nothing, adds nobody and goes to nobody; a new email still makes a ticket, with a note, but copies nobody in, gets no answer and isn't emailed to the client's colleagues who hear about new tickets; it never makes a contact; and it doesn't clear an address's Email bounced. An email that says it's from one of your agents isn't taken as their note. A domain that asks nothing of forged email (DMARC p=none) is taken as before. +- Email-to-ticket: someone who isn't a contact is answered "[TCK-123] We have your email", without their own subject or a link to the ticket, which shows what they wrote. Anyone can send an email that says it's from someone else, and the answer carried their words to that person from your mailbox. +- Email-to-ticket and website forms: a contact form's email comes from the website (wordpress@, a no-reply address) with the visitor in Reply-To. The visitor is the one answered now, and the ticket's CC, so your replies reach them - the website was, and the visitor never heard back. It's the ticket of the client whose domain the website is on, else a ticket with no client, and the website isn't made a contact. An email whose Reply-To is someone else at the same domain is taken as theirs. Anyone else's email is from them, whatever its Reply-To says. +- A client's reply on a ticket nobody is assigned goes to the new-ticket address in Admin > Settings > Tickets, or to the admins in the bell when there isn't one. It reopened the ticket, but nobody was told. +- An agent who answers the client's email from their own mailbox - reply to all, with the support address copied in - has it on the ticket as their reply, not an internal note: the client has it, so it shows as emailed to them and counts as the ticket's first response, and the ticket is theirs when nobody had it, as a reply from the ticket does. Nothing more is sent. An email only to the support address is still their internal note. ### Bug Fixes @@ -88,6 +91,8 @@ Update from Maintenance > Update as usual - this release has eight database chan - Files with an email: they're taken by the same list as files you attach yourself, so a client's .pptx, .msg, .odt, .mov or .mp4 is added to the ticket rather than left out - and iPhone photos (.heic), scans (.tif), forwarded emails (.eml), .xlsm, .ppt, .rtf and .log files can now be attached anywhere tickets take files. A file that still isn't added - another kind, or over 15 MB - is named in an internal note on the ticket, where it used to be in the audit log alone. - Email-to-ticket: a name with an apostrophe got a stray backslash - a contact made from an email at a client's domain was saved as O\'Brien, and the "Email from" line of an emailed ticket showed it the same way. A new contact's name is cut to fit, too, where a very long one left the email flagged in the mailbox. - Mail queue: an email whose To address went but one of the people copied in was turned away was sent to everyone again, up to three more times. It goes once now, and says who was turned away. +- Email-to-ticket: an email with no sender address was answered at itflow-guest@example.com, which was also made the ticket's CC - each email to it failed in the mail queue. It's from nobody now: a ticket with no client when unknown senders are let in, saying it has no sender address, with nobody answered or copied in, and on a ticket an internal note that reopens nothing - it matched a contact with no email address before. +- Email-to-ticket: an address that's a contact at more than one client - someone who works for two, a shared mailbox - raised its tickets at whichever client the database gave first. It's the client whose domain it's at now, else the one they last raised a ticket at, and a note on the ticket names the others, to change its client if it's theirs. ### Developer Updates @@ -141,6 +146,7 @@ Update from Maintenance > Update as usual - this release has eight database chan - Mail review stage 2: cron/mail_queue.php sends what is due - waiting, and failed ones whose wait is over - in one query, at most mailQueuePerMinute() a run (settings.config_mail_send_per_minute, database 4.2.9), ORDER BY email_bulk (4.2.9, emailQueue()'s bulk, set by emailBulkSend()), over one PHPMailer kept open (SMTPKeepAlive, mailQueueMailer()). MailQueueSmtp keeps each refused recipient's code: everyone refused for good (5xx) - email_attempts 99 and contactBounceMark(); some refused - sent, and they're named in email_error; refused for now (4xx) - tried again. A connection or sign-in failure (MailQueueUnreachable) puts the email back as it was and ends the run with cronJobStop(..., 1); two failures in a row end it for the minute. MAIL_QUEUE_RETRY_MINUTES gives way to MAIL_QUEUE_RETRY_AFTER - 5, 10, 20, 40, 60, 120 and 240 minutes (mailQueueRetryMinutes(), mailQueueRetryDueSql()) - and MAIL_QUEUE_TRIES is 8. Each failed email's appNotify() to every agent gives way to one mailQueueNotifyAdmins() for the run, an hour apart at most. PHPMailer's Hostname is mailQueueHostname(), its AltBody mailQueueTextPart(). sendQueueEmail() takes the run's mailer and answers with who the mail server took and turned away. - Mail review stage 3: ticketMailSenderCheck() (functions/ticket_mail_auto.php) reads the topmost Authentication-Results - the receiving server's - and answers why it failed, or '': dmarc=fail with p= or policy= reject or quarantine, or Microsoft 365's action reject, oreject or quarantine; or spf=fail with no dkim=pass and no dmarc result; never with arc=pass or compauth=pass. Only a failure is acted on, so a pass a sender writes in gains nothing. cron/ticket_email_parser.php keeps it as the email's forged: addReply() makes a forged email a stranger's, with its own note, history and audit line; addTicket() takes $email (copied, message_id, automatic, dropped, forged) in place of its last four arguments, writes ticketMailForgedNote() (functions/ticket_mail_thread.php) and leaves out the copied-in CCs, the client-less ticket's CC and the answer for a forged one; the domain match makes no contact from one. ticketMailCreated() takes a subject, as ticketMailSend()'s subject; a client-less emailed ticket is answered "[REF] We have your email". - Mail review stage 4: a failed email is still being tried while it is under MAIL_QUEUE_TRIES and its last try is within MAIL_QUEUE_GIVE_UP_HOURS (24) - mailQueueRetryingSql(), mailQueueFailedSql() and mailQueueRetrying(), for the job, the tabs, an email's state, Cancel and the summary - so one given up on before the tries went from 4 to 8 stays Failed rather than being sent again, and Failed gives its own count of tries. mailQueueRefusedForGood() decides which refused recipients are for good: the enhanced codes 5.1.1, 5.1.2, 5.1.3, 5.1.6 and 5.1.10, or 550, 551 or 553 naming an unknown recipient from a server that gives none (MailQueueSmtp keeps code_ex). Any other refusal is tried again and counts toward the two-in-a-row stop. mailQueueNotifyAdmins() counts dismissed notices toward its hour. The job orders by email_bulk, then email_sensitive DESC. +- Mail review stage 5: cron/ticket_email_parser.php - an email with no From address is from '' rather than itflow-guest@example.com: addReply() takes it as a stranger's ($no_sender) and addTicket() makes no CC and sends no answer. contactBounceClearEmail() runs after ticketMailSenderCheck(), and only when it didn't fail. ticketMailReplyTo() (functions/ticket_mail_auto.php) reads Reply-To: one at From's domain is taken as the sender ($via, shown as "sent by"); else, when ticketMailSystemSender() says From is a no-reply or website address (TICKET_MAIL_SYSTEM_SENDERS) or there is none, it is $answer - steps 4 to 6 raise the ticket with contact_id 0 for it at the From contact's or domain's client, or none. addTicket() makes the sender a CC whenever there is no contact (was: no client), answers anyone not a contact through ticketMailCreated()'s new $stranger (no Subject row and no button - its last parameter was the subject), and skips ticketMailColleaguesNew() for a forged ticket or one with no contact. ticketMailSenderContact() (functions/ticket_mail_thread.php) picks the contact for steps 3 and 4 by the From domain's client, then the latest ticket, then contact_id, and ticketMailSenderContactNote() notes the others; Try an Email uses it. An agent's email whose To or Cc has the ticket's contact, a CC or another of the client's contacts (ticketMailClientAddresses()) is a Public reply - addReplyAgentToClient() fills ticket_reply_emailed_to, calls setTicketFirstResponse(), assigns it through ticketChangeAssignee() under ticketReplyAssigns() or moves New to Open, and fires reply_reply_agent_public. ticketNotifyOwner() (functions/ticket.php) puts a bell notice with the assigned agent or the admins (appNotifyUsers(), functions/logging.php) - for bounces and closed-ticket replies, where appNotify() told every agent - and ticketMailAssigneeReplied() goes to ticketMailUnassignedReplied() on a ticket nobody has: the new-ticket address, else that notice. That covers portal and text replies too. ## [26.12.2] diff --git a/admin/settings_notification.php b/admin/settings_notification.php index de7c6343f..cb19340f0 100644 --- a/admin/settings_notification.php +++ b/admin/settings_notification.php @@ -30,7 +30,7 @@ echo settingsPageStart('notification'); Tickets.') ?> 'In the bell, for the agent a ticket or recurring ticket is assigned to - when someone else assigns it.']) ?> 'The email to that agent, with the ticket - or a list of them, when several are assigned at once.']) ?> - 'The agent a ticket is assigned to is always emailed the client\'s replies. This is the copy to the other agents helping on it.']) ?> + 'The agent a ticket is assigned to is always emailed the client\'s replies - on a ticket nobody has, the new-ticket address in Tickets is, or the admins get a notice in the bell. This is the copy to the other agents helping on it.']) ?> diff --git a/admin/settings_ticket.php b/admin/settings_ticket.php index 6ced016f9..6540844d2 100644 --- a/admin/settings_ticket.php +++ b/admin/settings_ticket.php @@ -66,7 +66,7 @@ echo settingsPageStart('ticket'); 'fa-bell', 'type' => 'email', 'maxlength' => 200, - 'placeholder' => 'techs@company.com', 'help' => 'A team mailbox or list works best - not the one ITFlow reads tickets from, as each notice would come back as an email. Empty, nobody is emailed.']) ?> + 'placeholder' => 'techs@company.com', 'help' => 'Each new ticket, and a client\'s reply on a ticket nobody is assigned. A team mailbox or list works best - not the one ITFlow reads tickets from, as each notice would come back as an email. Empty, nobody is emailed, and the admins get those replies in the bell.']) ?>
AI triage needs an AI model for Tickets, or one for everything - AI Providers.
diff --git a/cron/ticket_email_parser.php b/cron/ticket_email_parser.php index d5e0135b0..3c07ce17b 100644 --- a/cron/ticket_email_parser.php +++ b/cron/ticket_email_parser.php @@ -92,10 +92,14 @@ $read_mail_minutes = 60; // Mail someone opened before this got to it * dropped its files too big to take, named on the ticket with any of a kind it doesn't take * forged why the mail server that took it found it forged (ticketMailSenderCheck()), '' when it didn't: * still a ticket, so nothing is lost, but with a note saying so - nobody it copied in is - * added, its sender isn't answered, and a ticket with no client doesn't copy them in - * One from someone who isn't a contact - a ticket with no client - is answered without its own subject: - * anyone can send an email from someone else's address, and the answer carried their words to them. - * The new ticket's id. + * added, its sender isn't answered, a ticket with no contact doesn't copy them in, and the + * client's colleagues who hear about new tickets aren't emailed its subject + * via the address it was sent from, when it is taken as from its Reply-To (ticketMailReplyTo()) - + * shown beside who it is from + * picked the sender is a contact at more than one client (ticketMailSenderContact()) - said in a note + * One from someone who isn't a contact ($contact_id 0) is answered without its own subject or a link to the + * ticket: anyone can send an email from someone else's address, and the answer carried their words to them. + * One with no sender address ($contact_email '') is answered by nobody. The new ticket's id. */ function addTicket($contact_id, $contact_name, $contact_email, $client_id, $date, $subject, $message, $attachments, $original_message_file, array $email = []) { 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; @@ -110,6 +114,7 @@ function addTicket($contact_id, $contact_name, $contact_email, $client_id, $date $automatic = (string) ($email['automatic'] ?? ''); $dropped = (array) ($email['dropped'] ?? []); $forged = (string) ($email['forged'] ?? ''); + $via = (string) ($email['via'] ?? ''); // Atomically increment and get the new ticket number mysqli_query($mysqli, " @@ -134,7 +139,9 @@ function addTicket($contact_id, $contact_name, $contact_email, $client_id, $date // Convert newlines to
$message = nl2br($message); // Wrap final formatted message - $message = "Email from: " . escapeHtml($contact_name_raw) . " <" . escapeHtml($contact_email_raw) . "> at $date:-

$message
"; + $from_line = $contact_email_raw !== '' ? "" . escapeHtml($contact_name_raw) . " <" . escapeHtml($contact_email_raw) . ">" : 'No sender address'; + $from_line .= $via !== '' ? ' - sent by ' . escapeHtml($via) : ''; + $message = "Email from: $from_line at $date:-

$message
"; $ticket_prefix_esc = mysqli_real_escape_string($mysqli, $config_ticket_prefix); $message_esc = mysqli_real_escape_string($mysqli, $message); @@ -194,11 +201,15 @@ function addTicket($contact_id, $contact_name, $contact_email, $client_id, $date ticketMailForgedNote($id, $forged, $contact_email_raw, $copied); } + // From a contact at more than one client - which it went to, and the others + ticketMailSenderContactNote($id, $contact_email_raw, (array) ($email['picked'] ?? [])); + // The files that weren't added, said on the ticket - not only in the audit log ticketMailFilesLeftOut($id, $dropped); - // The person whose email raised a ticket with no client is its CC, so its emails reach them - not when it was forged - if ($client_id == 0 && $forged === '' && !preg_match($bad_pattern, $contact_email_esc)) { + // The person whose email raised a ticket with no contact is its CC, so its emails reach them - a website form's visitor, at + // a client's domain or none - not when it was forged + if (!$contact_id && $forged === '' && $contact_email_raw !== '' && !preg_match($bad_pattern, $contact_email_esc)) { mysqli_query($mysqli, "INSERT INTO ticket_ccs SET ticket_cc_email = '$contact_email_esc', ticket_cc_ticket_id = $id"); } @@ -210,19 +221,21 @@ function addTicket($contact_id, $contact_name, $contact_email, $client_id, $date // 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, it was forged, or they have had a few answers this hour - // already. Someone who isn't a contact is told without their own subject (above) + // already. Someone who isn't a contact is told without their own subject or the ticket's link (above) $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 && $automatic === '' && $forged === '' - && ticketMailAnswersLeft($contact_email_raw) && ($new = ticketRow($id))) { - ticketMailCreated($id, [], false, 'email', [['email' => $contact_email_raw, 'name' => $contact_name_raw]], - $client_id ? null : '[' . ticketReference($new) . '] We have your email'); + if ($config_ticket_client_general_notifications == 1 && $contact_email_raw !== '' && !preg_match($bad_pattern, $contact_email) && $contact_wants && $automatic === '' && $forged === '' + && ticketMailAnswersLeft($contact_email_raw)) { + ticketMailCreated($id, [], false, 'email', [['email' => $contact_email_raw, 'name' => $contact_name_raw]], !$contact_id); } // The new-ticket address (Admin > Ticket), when there is one ticketMailNewTicketAddress($id, 'email'); - // The client's primary and technical contacts who asked to hear about new tickets - ticketMailColleaguesNew($id); + // The client's primary and technical contacts who asked to hear about new tickets - not of a forged one, whose subject + // would go to them from your own mailbox, nor of one from someone who isn't a contact (a form on the client's website) + if ($forged === '' && $contact_id) { + ticketMailColleaguesNew($id); + } triggerCustomAction('ticket_create', $id); @@ -233,8 +246,8 @@ function addTicket($contact_id, $contact_name, $contact_email, $client_id, $date * 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. + * about a ticket, else by the number in its subject - and the agent it is assigned to gets a notice, or the admins when + * nobody has it or it is about no ticket (ticketNotifyOwner()). A report that an email is only delayed is set aside. */ function addBounce($message, array $headers, $from_email, $subject) { global $mysqli; @@ -273,9 +286,8 @@ function addBounce($message, array $headers, $from_email, $subject) { 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); + 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)))); } /* @@ -304,12 +316,15 @@ function linkSimilarTicket($new_id, $similar_id) { * 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) + * via the address it was sent from, when it is taken as from its Reply-To (ticketMailReplyTo()) * * Who it is from decides what it is: the ticket's contact, another of the client's contacts, or one of its CCs - * (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. + * (the person whose email raised a ticket with no contact is one) - a client reply, which reopens the ticket; one + * of your agents - their own internal note, or their reply to the client when it went to the client too (a reply + * to all on the client's email), which the client has: public, and the ticket's first response; anyone else, or + * no sender address at all - 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, $allowed_extensions; @@ -317,6 +332,8 @@ function addReply($from_email, $date, $subject, $ticket_id, $message, $attachmen $automatic = (string) ($email['automatic'] ?? ''); $from_name = trim(stripslashes((string) ($email['from_name'] ?? ''))); $from_name = $from_name === 'Unknown' ? '' : $from_name; + $via = (string) ($email['via'] ?? ''); + $no_sender = trim(stripslashes((string) $from_email)) === ''; // 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) @@ -331,7 +348,9 @@ function addReply($from_email, $date, $subject, $ticket_id, $message, $attachmen $message = nl2br($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) . ' <' . escapeHtml(stripslashes($from_email)) . '>' : escapeHtml(stripslashes($from_email)); + $from_line = $no_sender ? 'No sender address' + : ($from_name !== '' ? '' . escapeHtml($from_name) . ' <' . escapeHtml(stripslashes($from_email)) . '>' : escapeHtml(stripslashes($from_email))); + $from_line .= $via !== '' ? ' - sent by ' . escapeHtml($via) : ''; $message = "Email from: $from_line at $date:-

$message
"; $from_email_esc = mysqli_real_escape_string($mysqli, $from_email); @@ -350,12 +369,14 @@ function addReply($from_email, $date, $subject, $ticket_id, $message, $attachmen $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), CC, agent or stranger + // Who wrote it - contact (the ticket's, or another of the client's), CC, agent or stranger. No sender address is a stranger's: + // matched, it was any contact or agent with no email address $who = 'stranger'; $reply_by = 0; - if (trim((string) $row['contact_email']) !== '' && strcasecmp(trim((string) $row['contact_email']), stripslashes($from_email)) === 0) { + if ($no_sender) { + $who = 'stranger'; + } elseif (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")))) { @@ -375,11 +396,16 @@ function addReply($from_email, $date, $subject, $ticket_id, $message, $attachmen } $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)); + $by_name = $who === 'contact' ? (string) getFieldById('contacts', $reply_by, 'contact_name') : ($from_name !== '' ? $from_name : ($no_sender ? 'Someone with no address' : stripslashes($from_email))); - // What it is on the ticket: a client reply from the client or a CC; a note from an agent, a stranger, an automatic - // reply, or anything on a closed ticket - $type = in_array($who, ['contact', 'cc'], true) && $automatic !== 'auto-reply' && !$closed ? 'Client' : 'Internal'; + // An agent's email that went to the client too - they answered the client's email with reply to all, the ticket's + // address copied in. The client has it: it is the agent's reply, not a note only your team sees + $to_client = $who === 'agent' && !$closed && $automatic === '' + ? ticketMailClientAddresses($ticket_id, array_diff((array) ($email['had'] ?? []), [strtolower(stripslashes($from_email))])) : []; + + // What it is on the ticket: a client reply from the client or a CC; an agent's reply when it went to the client; a note + // from an agent, a stranger, an automatic reply, or anything on a closed ticket + $type = in_array($who, ['contact', 'cc'], true) && $automatic !== 'auto-reply' && !$closed ? 'Client' : ($to_client ? 'Public' : 'Internal'); $notes = []; if ($automatic === 'auto-reply') { $notes[] = 'An automatic reply - the ticket was not reopened'; @@ -390,7 +416,7 @@ function addReply($from_email, $date, $subject, $ticket_id, $message, $attachmen $notes[] = "Its sender checks failed: $forged - so it may not be from " . stripslashes($from_email) . ($closed || $automatic === 'auto-reply' ? '' : '. The ticket was not reopened') . ', nobody it copied in was added' . ($attachments ? ", and the email's " . count($attachments) . " attachment(s) were not added - it is in the mailbox's ITFlow folder" : ''); } elseif ($stranger) { - $notes[] = 'From someone who is not a contact, CC or agent' . ($closed || $automatic === 'auto-reply' ? '' : ' - the ticket was not reopened') + $notes[] = ($no_sender ? 'It has no sender address' : 'From someone who is not a contact, CC 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) { @@ -459,18 +485,25 @@ function addReply($from_email, $date, $subject, $ticket_id, $message, $attachmen return true; } - // A closed ticket isn't reopened. Agents are told it is on it, and the client or CC 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) + // A closed ticket isn't reopened. The agent it was assigned to is told it is on it - or the admins, when nobody had it + // (ticketNotifyOwner()) - and the client or CC 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"); + $who_esc = $no_sender ? 'An email with no sender address' : $from_email_esc; + ticketNotifyOwner(ticketRow($ticket_id), "Email parser: $who_esc replied to closed ticket $ticket_reference_esc - it is on the ticket as a note, and the ticket was not reopened"); + logTicketHistory($ticket_id, "$who_esc replied after it was closed - kept as a note"); if (in_array($who, ['contact', 'cc'], true) && $automatic === '' && ticketMailAnswersLeft(stripslashes($from_email))) { ticketMailClosedReply($ticket_id, stripslashes($from_email), (string) ($email['message_id'] ?? '')); } return true; } + if ($who === 'agent' && $to_client) { + addReplyAgentToClient($ticket_id, $reply_id, $reply_by, $to_client, $ticket_status, $row); + logAudit("Ticket", "Edit", "Email parser: Agent $from_email_esc replied to the client on ticket $ticket_reference_esc ($subject) by email", $client_id, $ticket_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); @@ -498,8 +531,9 @@ function addReply($from_email, $date, $subject, $ticket_id, $message, $attachmen return true; } if ($stranger) { - logTicketHistory($ticket_id, "$from_email_esc (not a contact, CC or agent) emailed - kept as an internal note, the ticket was not reopened"); - logAudit("Ticket", "Edit", "Email parser: $from_email_esc (not a contact, CC or agent) emailed ticket $ticket_reference_esc ($subject) - kept as an internal note", $client_id, $ticket_id); + $stranger_esc = $no_sender ? 'An email with no sender address' : "$from_email_esc (not a contact, CC or agent)"; + logTicketHistory($ticket_id, "$stranger_esc emailed - kept as an internal note, the ticket was not reopened"); + logAudit("Ticket", "Edit", "Email parser: $stranger_esc emailed ticket $ticket_reference_esc ($subject) - kept as an internal note", $client_id, $ticket_id); return true; } @@ -530,6 +564,44 @@ function addReply($from_email, $date, $subject, $ticket_id, $message, $attachmen return true; } +/* + * An agent's email to ticket $ticket_id that went to the client too - $to_client, the client's addresses it was to or + * copied to (ticketMailClientAddresses()) - saved as their public reply, $reply_id. Nothing is sent: the client has it. + * Kept with who it went to, as a reply sent from the ticket is; it is the ticket's first response; a New ticket is Open; + * and one nobody had is theirs, as a reply from the ticket page makes it (Admin > Settings > Tickets). + */ +function addReplyAgentToClient($ticket_id, $reply_id, $user_id, array $to_client, $ticket_status, array $row) { + global $mysqli; + $ticket_id = intval($ticket_id); + $user_id = intval($user_id); + if (ticketReplyEmailReady()) { + $to = array_map(function ($email) { + return ['email' => $email, 'name' => '']; + }, $to_client); + mysqli_query($mysqli, "UPDATE ticket_replies SET ticket_reply_emailed = 1, ticket_reply_emailed_to = '" . escapeSql(json_encode($to, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES)) . "', + ticket_reply_updated_at = ticket_reply_updated_at WHERE ticket_reply_id = " . intval($reply_id)); + } + setTicketFirstResponse($ticket_id); + + $agent_name = (string) getFieldById('users', $user_id, 'user_name'); + logTicketHistory($ticket_id, escapeSql("$agent_name replied to " . implode(', ', $to_client) . " by email, the ticket's address copied in - added as their reply")); + + // As if from the ticket page, by the agent - so the history and audit log name them, and they aren't told of their own doing + $session = [$GLOBALS['session_name'] ?? null, $GLOBALS['session_user_id'] ?? null]; + $GLOBALS['session_name'] = escapeSql($agent_name); + $GLOBALS['session_user_id'] = $user_id; + if (!intval($row['ticket_assigned_to'] ?? 0) && ticketReplyAssigns()) { + ticketChangeAssignee($ticket_id, $user_id); + } elseif (intval($ticket_status) === TICKET_STATUS_NEW) { + mysqli_query($mysqli, "UPDATE tickets SET ticket_status = " . TICKET_STATUS_OPEN . " WHERE ticket_id = $ticket_id AND ticket_status = " . TICKET_STATUS_NEW); + syncTicketSlaClock($ticket_id); + logTicketHistory($ticket_id, escapeSql("$agent_name set the status to " . getTicketStatusName(TICKET_STATUS_OPEN))); + } + [$GLOBALS['session_name'], $GLOBALS['session_user_id']] = $session; + + triggerCustomAction('reply_reply_agent_public', $ticket_id); +} + /** ------------------------------------------------------------------ * OAuth helpers + provider guard * ------------------------------------------------------------------ */ @@ -861,16 +933,15 @@ foreach ($messages as $message) { try { $email_processed = false; - // From + // From - with no address, '': a stranger's, which nobody is answered at. It was itflow-guest@example.com, made the + // ticket's CC and answered, each email failing in the mail queue $from_addr = $message->from(); // ?Address - $from_email = escapeSql($from_addr?->email() ?: 'itflow-guest@example.com'); + $from_raw = trim((string) ($from_addr?->email() ?? '')); + $from_raw = preg_match('/^[^@\s]+@[^@\s]+$/', $from_raw) ? $from_raw : ''; + $from_email = escapeSql($from_raw); $from_name = escapeSql($from_addr?->name() ?: 'Unknown'); - $from_domain = explode("@", $from_email); - $from_domain = escapeSql(end($from_domain)); - - // Mail from an address that bounced before - it works again (functions/contact_bounce.php) - contactBounceClearEmail(stripslashes($from_email)); + $from_domain = $from_raw !== '' ? strtolower(substr($from_raw, strrpos($from_raw, "@") + 1)) : ''; // Subject // ticket_subject holds 500 characters - a longer one failed the insert and the email was tried again every run @@ -904,6 +975,28 @@ foreach ($messages as $message) { // anyone: one that fails is a stranger's on a ticket, and makes no contact, adds no CCs and gets no answer $forged = ticketMailSenderCheck($headers); + // Mail from an address that bounced before - it works again (functions/contact_bounce.php). Not when it was forged: it + // was cleared before the check, so anyone could clear an address's mark by sending as it + if ($forged === '' && $from_raw !== '') { + contactBounceClearEmail($from_raw); + } + + // Its Reply-To (ticketMailReplyTo()) - someone at the domain it is from that it was sent for, taken as from them; or a + // website form's visitor, From the site: the one answered and made the ticket's CC ($answer), never a contact by it + $via = ''; + $answer = null; + $reply_addr = $message->replyTo(); + if ($reply_to = ticketMailReplyTo($reply_addr?->email(), $reply_addr?->name(), $from_raw)) { + $via = $from_raw; + if ($reply_to['same_domain']) { + $from_raw = $reply_to['email']; + $from_email = escapeSql($from_raw); + $from_name = escapeSql($reply_to['name'] !== '' ? $reply_to['name'] : 'Unknown'); + } else { + $answer = ['email' => escapeSql($reply_to['email']), 'name' => escapeSql($reply_to['name'] !== '' ? $reply_to['name'] : 'Unknown')]; + } + } + // 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 $email_message_id = ticketMailIdClean((string) $message->messageId()); @@ -937,7 +1030,7 @@ foreach ($messages as $message) { $in_reply_to = (string) ($message->header('In-Reply-To')?->getRawValue() ?? ''); $references = (string) ($message->header('References')?->getRawValue() ?? ''); $email = ['message_id' => $email_message_id, 'from_name' => $from_name, 'copied' => $copied, 'had' => array_values(array_unique(array_filter($had))), 'threaded' => false, - 'automatic' => $automatic, 'forged' => $forged]; + 'automatic' => $automatic, 'forged' => $forged, 'via' => $via]; // Date (string) $dateObj = $message->date(); // ?CarbonInterface @@ -1012,30 +1105,21 @@ foreach ($messages as $message) { // 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 + // (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); + $contact_row = $picked['contact']; + $domain_row = null; + if (!$contact_row && $from_domain !== '') { + $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; + } $similar_ticket_id = 0; if (!$email_processed && strlen(trim($subject)) > 10) { - $contact_id = 0; - $client_id = 0; - - // First: check if sender is a registered contact + $contact_id = $contact_row && !$answer ? intval($contact_row['contact_id']) : 0; + $client_id = $contact_row ? intval($contact_row['contact_client_id']) : intval($domain_row['domain_client_id'] ?? 0); $from_email_esc = mysqli_real_escape_string($mysqli, $from_email); - $contact_sql = mysqli_query($mysqli, "SELECT * FROM contacts WHERE contact_email = '$from_email_esc' AND contact_archived_at IS NULL LIMIT 1"); - $contact_row = mysqli_fetch_assoc($contact_sql); - - if ($contact_row) { - $contact_id = intval($contact_row['contact_id']); - $client_id = intval($contact_row['contact_client_id']); - } else { - // Else: check if sender domain is registered - $from_domain_esc = mysqli_real_escape_string($mysqli, $from_domain); - $domain_sql = mysqli_query($mysqli, "SELECT domain_client_id, domain_name FROM domains WHERE domain_name = '$from_domain_esc' AND domain_archived_at IS NULL LIMIT 1"); - $domain_row = mysqli_fetch_assoc($domain_sql); - - if ($domain_row && $from_domain == $domain_row['domain_name']) { - $client_id = intval($domain_row['domain_client_id']); - } - } // If we found either a contact or a domain, check recent tickets for a matching subject if ($client_id) { @@ -1054,8 +1138,8 @@ foreach ($messages as $message) { if ($percent >= 95) { $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_ccs WHERE ticket_cc_ticket_id = $similar_id AND ticket_cc_email = '$from_email_esc' LIMIT 1")); + $theirs = !$answer && (($contact_id && $contact_id === intval($rowt['ticket_contact_id'])) + || mysqli_num_rows(mysqli_query($mysqli, "SELECT 1 FROM ticket_ccs WHERE ticket_cc_ticket_id = $similar_id AND ticket_cc_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 { @@ -1067,32 +1151,27 @@ foreach ($messages as $message) { } } - // 4. A known, registered contact? - if (!$email_processed) { - $from_email_esc = mysqli_real_escape_string($mysqli, $from_email); - $any_contact_sql = mysqli_query($mysqli, "SELECT * FROM contacts WHERE contact_email = '$from_email_esc' AND contact_archived_at IS NULL LIMIT 1"); - $rowc = mysqli_fetch_assoc($any_contact_sql); - - if ($rowc) { - $contact_name = escapeSql($rowc['contact_name']); - $contact_id = intval($rowc['contact_id']); - $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, $email); + // 4. A known, registered contact? A website form sent as one - an address made a contact before - is for that + // contact's client, from its visitor + if (!$email_processed && $contact_row) { + $client_id = intval($contact_row['contact_client_id']); + if ($answer) { + $email_processed = addTicket(0, $answer['name'], $answer['email'], $client_id, $date, $subject, $message_body, $attachments, $original_message_file, $email); + } else { + $contact_name = escapeSql($contact_row['contact_name']); + $contact_id = intval($contact_row['contact_id']); + $contact_email = escapeSql($contact_row['contact_email']); + $email_processed = addTicket($contact_id, $contact_name, $contact_email, $client_id, $date, $subject, $message_body, $attachments, $original_message_file, $email + ['picked' => $picked]); } } - // 5. A known domain? - if (!$email_processed) { - $from_domain_esc = mysqli_real_escape_string($mysqli, $from_domain); - $domain_sql = mysqli_query($mysqli, "SELECT domain_client_id, domain_name FROM domains WHERE domain_name = '$from_domain_esc' AND domain_archived_at IS NULL LIMIT 1"); - $rowd = mysqli_fetch_assoc($domain_sql); - - // Not a forged one: anyone could make themselves a client's contact by saying they are from its domain - if ($rowd && $from_domain == $rowd['domain_name'] && mb_strlen(stripslashes($from_email)) <= 200 && $forged === '') { - $client_id = intval($rowd['domain_client_id']); - + // 5. A known domain? Not a forged one: anyone could make themselves a client's contact by saying they are from its domain. + // A website form's is the client's ticket, from its visitor - the site isn't made a contact + if (!$email_processed && $domain_row && mb_strlen($from_raw) <= 200 && $forged === '') { + $client_id = intval($domain_row['domain_client_id']); + if ($answer) { + $email_processed = addTicket(0, $answer['name'], $answer['email'], $client_id, $date, $subject, $message_body, $attachments, $original_message_file, $email); + } else { // Create a new contact - its name cut to the 200 characters the column holds, and escaped once: $from_name and // $from_email come SQL-escaped, and escaped again, an O'Brien was saved as O\'Brien $contact_name = mysqli_real_escape_string($mysqli, rtrim(mb_substr(stripslashes($from_name), 0, 200))); @@ -1107,9 +1186,12 @@ foreach ($messages as $message) { } } - // 6. Unknown sender allowed? A ticket with no client - a mail server's bounce never gets here + // 6. Unknown sender allowed? A ticket with no client - a mail server's bounce never gets here. A website form's from its + // visitor; one with no sender address from nobody, answered by nobody 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, $email); + $email_processed = $answer + ? addTicket(0, $answer['name'], $answer['email'], 0, $date, $subject, $message_body, $attachments, $original_message_file, $email) + : addTicket(0, $from_name, $from_email, 0, $date, $subject, $message_body, $attachments, $original_message_file, $email); } // A new ticket whose subject is almost that of another's at the client, from someone else - linked as related diff --git a/functions/logging.php b/functions/logging.php index 371a802df..f92d48e1f 100644 --- a/functions/logging.php +++ b/functions/logging.php @@ -80,6 +80,26 @@ function appNotify($type, $details, $action = null, $client_id = 0, $entity_id = } } +/* appNotify() for the agents $user_ids only - $details SQL-escaped, as there. How many were told. */ +function appNotifyUsers(array $user_ids, $type, $details, $action = '', $client_id = 0, $entity_id = 0) { + global $mysqli; + + $type = logSqlText($type, 200); + $details = logSqlText($details, 1000); + $action = logSqlText((string) $action, 250); + $client_id = intval($client_id); + $entity_id = intval($entity_id); + + $told = 0; + foreach (array_unique(array_map('intval', $user_ids)) as $user_id) { + if ($user_id > 0) { + mysqli_query($mysqli, "INSERT INTO notifications SET notification_type = '$type', notification = '$details', notification_action = '$action', notification_client_id = $client_id, notification_entity_id = $entity_id, notification_user_id = $user_id"); + $told++; + } + } + return $told; +} + function logAudit($type, $action, $description, $client_id = 0, $entity_id = 0) { global $mysqli, $session_user_agent, $session_ip, $session_user_id; diff --git a/functions/ticket.php b/functions/ticket.php index 463c3f5a8..95663f0c5 100644 --- a/functions/ticket.php +++ b/functions/ticket.php @@ -577,7 +577,8 @@ function ticketEmailExcerpt($html, $limit = 700) { * What an email about a ticket says - emailHtml()'s fields (functions/email.php), * all but who it is to and why they get it, which ticketMailSend() adds for * each. $row is ticketRow(). $kind and its $opts: - * created it was opened - how: agent (the default), email (the reply to an emailed one) or scheduled + * created it was opened - how: agent (the default), email (the reply to an emailed one) or scheduled; + * stranger (email): to someone who isn't a contact - without its subject or the ticket's link * reply an agent's reply - message (its HTML), by (who wrote it) * client_reply a client's reply, passed on to the people following the ticket who didn't have * it (ticketMailRelayClientReply()) - message (its HTML), by (who wrote it), skip (the @@ -613,7 +614,11 @@ function ticketEmailContent(array $row, $kind, array $opts = []) { if ($how === 'email') { $email['title'] = 'We have your email'; $email['intro'] = ["Thank you - it is ticket $reference now, and we will reply to you here. To add anything, just reply to this email."]; - // Never their own words back: the sender of an email can be forged, and an echo would carry whatever it said to them + // Never their own words back: the sender of an email can be forged, and an echo would carry whatever it said to them. + // To someone who isn't a contact (stranger) not even its subject, nor the link to the ticket, which shows the lot + if (!empty($opts['stranger'])) { + unset($summary['Subject'], $email['button']); + } } else { $email['title'] = $how === 'scheduled' ? 'A scheduled ticket was opened for you' : 'We have opened a ticket for you'; $email['intro'] = [($how === 'scheduled' ? "Ticket $reference was opened for you, as scheduled." : "We have opened ticket $reference for you.") @@ -622,7 +627,9 @@ function ticketEmailContent(array $row, $kind, array $opts = []) { } $email['summary'] = $summary + ['Priority' => (string) $row['ticket_priority']] + $sla['summary']; $email['callout'] = $sla['callout']; - $email['button']['label'] = 'View your ticket'; + if (isset($email['button'])) { + $email['button']['label'] = 'View your ticket'; + } } elseif ($kind === 'reply') { $email['kind'] = 'Ticket update'; $email['title'] = $subject; @@ -875,18 +882,21 @@ function ticketMailColleaguesNew($ticket_id) { /* * The "a ticket was created for you" email - to its contact, and its CCs * unless $to_ccs is false; or to $to (ticketMailSend()'s) in their - * place. $how agent, email or scheduled (ticketEmailContent()). + * place. $how agent, email or scheduled (ticketEmailContent()). $stranger: + * an emailed ticket from someone who isn't a contact, answered without + * their own words - "[TCK-123] We have your email", with no subject in it + * and no link to the ticket, which shows the lot. */ -function ticketMailCreated($ticket_id, $attachments = [], $to_ccs = true, $how = 'agent', ?array $to = null, ?string $subject = null) { +function ticketMailCreated($ticket_id, $attachments = [], $to_ccs = true, $how = 'agent', ?array $to = null, bool $stranger = false) { $row = ticketRow($ticket_id); 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). - // $subject in place of the ticket's - an emailed ticket from someone who isn't a contact is answered without their own words - return ticketMailSend($row['ticket_id'], ticketEmailContent($row, 'created', ['how' => $how]), + // 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) + $stranger = $stranger && $how === 'email'; + return ticketMailSend($row['ticket_id'], ticketEmailContent($row, 'created', ['how' => $how, 'stranger' => $stranger]), ['attachments' => $attachments, 'to_ccs' => $to_ccs, 'kind' => 'created'] + ($to !== null ? ['to' => $to] : []) + ($how === 'email' ? ['auto' => 'replied'] : []) - + ($subject !== null ? ['subject' => $subject] : [])); + + ($stranger ? ['subject' => '[' . ticketReference($row) . '] We have your email'] : [])); } /* @@ -1056,6 +1066,23 @@ function ticketMailCcsAdded($ticket_id, array $emails, $by) { /* ------------------------------------------------------------ Emails about a ticket, to agents */ +/* + * A notice in the bell about ticket $row (ticketRow(), or null for none) for whoever looks after it - the agent it is + * assigned to, or the admins (signInAdmins()) when nobody has it or there is no ticket. $details SQL-escaped, as + * appNotify()'s. What the ticket mailbox found - a bounce, a reply to a closed ticket - went to every agent, one + * notice an email each. How many were told. + */ +function ticketNotifyOwner(?array $row, $details) { + global $mysqli; + $user_id = intval($row['ticket_assigned_to'] ?? 0); + if ($user_id && !mysqli_num_rows(mysqli_query($mysqli, "SELECT 1 FROM users WHERE user_id = $user_id AND user_type = 1 AND user_status = 1 AND user_archived_at IS NULL"))) { + $user_id = 0; + } + $client_id = intval($row['ticket_client_id'] ?? 0); + return appNotifyUsers($user_id ? [$user_id] : array_keys(signInAdmins()), 'Ticket', $details, + $row ? '/agent/' . ticketUrl($row['ticket_id'], $client_id) : '', $client_id, intval($row['ticket_id'] ?? 0)); +} + /** Where an agent opens a ticket - in ITFlow. */ function ticketAgentUrl(array $row) { global $config_base_url; @@ -1198,13 +1225,17 @@ function ticketMailNewTicketAddress($ticket_id, $how) { $subject, ticketAgentEmailContent($row, 'new', ['how' => $how])); } -/** Tell the agent a ticket is assigned to that the client replied - and the agents helping on it - $how portal or email, $reply its HTML, $by who. */ +/* + * Tell the agent a ticket is assigned to that the client replied - and the agents helping on it - $how portal, email or + * text, $reply its HTML, $by who. On a ticket nobody has, the new-ticket address (Admin > Ticket) is emailed, or the admins + * get a notice in the bell when there is none: the reply reopened the ticket, and nobody was told. + */ function ticketMailAssigneeReplied($ticket_id, $how, $reply, $by) { global $config_app_name; $row = ticketRow($ticket_id); $agent = $row ? ticketMailAgent($row['ticket_assigned_to']) : null; if (!$agent) { - return 0; + return $row ? ticketMailUnassignedReplied($row, $how, $reply, $by) : 0; } return ticketMailAgents([$agent + ['footnote' => 'You get this as the agent ' . ticketReference($row) . ' is assigned to.']], ($config_app_name ?: 'ITFlow') . " - Ticket updated - [" . ticketReference($row) . "] " . $row['ticket_subject'], @@ -1212,6 +1243,21 @@ function ticketMailAssigneeReplied($ticket_id, $how, $reply, $by) { + ticketHelpersMailReplied($row, $agent, $how, $reply, $by); } +/* A client's reply on ticket $row, which nobody is assigned (ticketMailAssigneeReplied()) - to the new-ticket address, else the admins' bell. */ +function ticketMailUnassignedReplied(array $row, $how, $reply, $by) { + global $mysqli, $config_app_name; + $reference = ticketReference($row); + $address = (string) (mysqli_fetch_row(mysqli_query($mysqli, "SELECT config_ticket_new_ticket_notification_email FROM settings WHERE company_id = 1"))[0] ?? ''); + if (filter_var($address, FILTER_VALIDATE_EMAIL) && !emailReadMailbox($address)) { + $email = ticketAgentEmailContent($row, 'replied', ['how' => $how, 'message' => (string) $reply, 'by' => (string) $by]); + $email['intro'][] = 'Nobody is assigned it.'; + return ticketMailAgents([['email' => $address, 'greet' => '', 'footnote' => "You get this at the new-ticket address in Admin > Ticket, as nobody is assigned $reference."]], + ($config_app_name ?: 'ITFlow') . " - Ticket updated - [$reference] " . $row['ticket_subject'], $email); + } + $by = trim((string) $by) !== '' ? trim((string) $by) : 'The client'; + return ticketNotifyOwner($row, escapeSql("$by replied to $reference - " . $row['ticket_subject'] . " - which nobody is assigned")); +} + /** * Is this email or notice to your team switched on (Admin > Settings > * Notifications, Emails to your team - database 3.9.1)? $key assigned_app diff --git a/functions/ticket_mail_auto.php b/functions/ticket_mail_auto.php index 0a2338f71..59e2ffc6d 100644 --- a/functions/ticket_mail_auto.php +++ b/functions/ticket_mail_auto.php @@ -112,6 +112,49 @@ function ticketMailBounceSender($email) { return $local !== '' && in_array(preg_replace('/\+.*$/', '', $local), TICKET_MAIL_BOUNCE_SENDERS, true); } +/** The names a website or its server sends a form's email as, before the @ - WordPress's own, the web server's, a form's. */ +const TICKET_MAIL_SYSTEM_SENDERS = ['wordpress', 'www-data', 'apache', 'nginx', 'httpd', 'nobody', 'webform', 'webforms', 'form', 'forms', 'form-submission', 'form-submissions']; + +/* + * Whether an address is one nobody reads - a no-reply address, or a website's or its server's own + * (TICKET_MAIL_SYSTEM_SENDERS), which a contact form sends its email as. No address at all is one too. + */ +function ticketMailSystemSender($email) { + $email = strtolower(trim((string) $email)); + if ($email === '' || preg_match('/do[\W_]*not[\W_]*reply|no[\W_]*reply/i', $email)) { + return true; + } + $local = substr($email, 0, (int) strrpos($email, '@')); + return $local !== '' && in_array(preg_replace('/\+.*$/', '', $local), TICKET_MAIL_SYSTEM_SENDERS, true); +} + +/* + * Who an email asks to be answered at - its Reply-To ($reply_email, $reply_name, raw) - when that is the + * one to take it from. A website's contact form sends its email from the site (wordpress@...), with the + * visitor in Reply-To, and the site was made the ticket's sender, CC and the one answered: the visitor + * never heard back. Taken when it is a good address, not ITFlow's own nor the sender's, and: + * same_domain at the domain the email is from ($from_email) - someone there it was sent for: the email + * is taken as theirs, as their domain is the one checked (ticketMailSenderCheck()) + * else the sender is one nobody reads (ticketMailSystemSender()) - only answered there, and made + * the ticket's CC: anyone can write any Reply-To, so it never makes them a client's contact + * Otherwise null - a person's email is from them, whatever its Reply-To says. ['email', 'name', 'same_domain']. + */ +function ticketMailReplyTo($reply_email, $reply_name, $from_email) { + $reply_email = strtolower(trim((string) $reply_email)); + $from_email = strtolower(trim((string) $from_email)); + if ($reply_email === '' || $reply_email === $from_email || mb_strlen($reply_email) > 200 || !filter_var($reply_email, FILTER_VALIDATE_EMAIL) + || emailOwnAddress($reply_email) || ticketMailSystemSender($reply_email) || ticketMailBounceSender($reply_email)) { + return null; + } + $reply_domain = substr($reply_email, strrpos($reply_email, '@') + 1); + $from_domain = $from_email !== '' && strpos($from_email, '@') !== false ? substr($from_email, strrpos($from_email, '@') + 1) : ''; + $same_domain = $from_domain !== '' && $from_domain === $reply_domain; + if (!$same_domain && !ticketMailSystemSender($from_email)) { + return null; + } + return ['email' => $reply_email, 'name' => trim((string) $reply_name), 'same_domain' => $same_domain]; +} + /* * What kind of email no person wrote this is - 'auto-reply', 'automated' or '' (a person wrote it). * $headers as ticketMailHeaderMap(). diff --git a/functions/ticket_mail_thread.php b/functions/ticket_mail_thread.php index 015680027..02ab0608a 100644 --- a/functions/ticket_mail_thread.php +++ b/functions/ticket_mail_thread.php @@ -251,6 +251,95 @@ function ticketMailCopiedCcs($ticket_id, array $addresses, $sender) { return ticketAddCcs($ticket_id, array_slice($emails, 0, 20)); } +/* + * The contact an email from $email is from, when it is one - ['contact' => row (contact_id, contact_name, contact_email, + * contact_client_id, client_name) or null, 'others' => the other clients it is a contact at, [client_id => name], + * 'why' => how the one was picked]. An address can be a contact at more than one client - someone who works for two, + * a shared mailbox - and its email went to whichever the database gave first. Now: the client whose domain it is + * ($domain, Domains), else the one they last raised a ticket at, else the first they were added to. + */ +function ticketMailSenderContact($email, $domain = '') { + global $mysqli; + $email = trim((string) $email); + $none = ['contact' => null, 'others' => [], 'why' => '']; + if ($email === '') { + return $none; + } + $email_sql = escapeSql($email); + $domain_sql = escapeSql(strtolower(trim((string) $domain))); + $rows = []; + $sql = mysqli_query($mysqli, "SELECT contact_id, contact_name, contact_email, contact_client_id, client_name, + (SELECT 1 FROM domains WHERE domain_client_id = contact_client_id AND domain_name = '$domain_sql' AND domain_archived_at IS NULL LIMIT 1) AS at_domain, + (SELECT MAX(ticket_created_at) FROM tickets WHERE ticket_contact_id = contact_id) AS last_ticket + FROM contacts LEFT JOIN clients ON client_id = contact_client_id + WHERE contact_email = '$email_sql' AND contact_archived_at IS NULL + ORDER BY at_domain DESC, last_ticket DESC, contact_id"); + while ($row = mysqli_fetch_assoc($sql)) { + $rows[] = $row; + } + if (!$rows) { + return $none; + } + $contact = $rows[0]; + $others = []; + foreach (array_slice($rows, 1) as $row) { + if (intval($row['contact_client_id']) !== intval($contact['contact_client_id'])) { + $others[intval($row['contact_client_id'])] = (string) ($row['client_name'] ?? 'a client'); + } + } + $why = !empty($contact['at_domain']) ? 'whose domain it is' : (!empty($contact['last_ticket']) ? 'where they last raised a ticket' : 'where they were added first'); + return ['contact' => $contact, 'others' => $others, 'why' => $others ? $why : '']; +} + +/* + * Say on a ticket raised by an email from $email - a contact at more than one client ($picked, ticketMailSenderContact()) - + * which client it went to and why, and the others, so an agent moves it when it is for one of those. An internal note. + */ +function ticketMailSenderContactNote($ticket_id, $email, array $picked) { + global $mysqli; + $ticket_id = intval($ticket_id); + if (!$ticket_id || empty($picked['others']) || empty($picked['contact'])) { + return 0; + } + $client = (string) ($picked['contact']['client_name'] ?? 'a client'); + $others = array_values($picked['others']); + $list = count($others) === 1 ? $others[0] : implode(', ', array_slice($others, 0, -1)) . ' and ' . end($others); + $note = '' . escapeHtml($email) . ' is a contact at ' . escapeHtml($list) . ' too - this ticket went to ' . escapeHtml($client) + . ', ' . escapeHtml($picked['why']) . '.
If it is for ' . escapeHtml(count($others) === 1 ? $others[0] : 'one of the others') . ', change its client.'; + 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"); + $note_id = intval(mysqli_insert_id($mysqli)); + logTicketHistory($ticket_id, escapeSql("$email is a contact at more than one client - it went to $client, " . $picked['why'] . ' - noted')); + return $note_id; +} + +/* + * Which of $addresses (an email's To and Cc) are the client's on ticket $ticket_id - its contact, one of its CCs, or + * another of the client's contacts - for an agent's email that went to them too. Lower-case, as given. + */ +function ticketMailClientAddresses($ticket_id, array $addresses) { + global $mysqli; + $ticket_id = intval($ticket_id); + $row = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT ticket_client_id, contact_email FROM tickets LEFT JOIN contacts ON contact_id = ticket_contact_id WHERE ticket_id = $ticket_id")); + if (!$row) { + return []; + } + $client_id = intval($row['ticket_client_id']); + $found = []; + foreach (array_unique(array_map('strtolower', array_map('trim', array_map('strval', $addresses)))) as $email) { + if ($email === '' || emailOwnAddress($email)) { + continue; + } + $email_sql = escapeSql($email); + if (strtolower(trim((string) $row['contact_email'])) === $email + || mysqli_num_rows(mysqli_query($mysqli, "SELECT 1 FROM ticket_ccs WHERE ticket_cc_ticket_id = $ticket_id AND ticket_cc_email = '$email_sql' LIMIT 1")) + || ($client_id && mysqli_num_rows(mysqli_query($mysqli, "SELECT 1 FROM contacts WHERE contact_email = '$email_sql' AND contact_client_id = $client_id AND contact_archived_at IS NULL LIMIT 1")))) { + $found[] = $email; + } + } + return $found; +} + /** Why an emailed file with the extension $extension isn't added to a ticket - it isn't one of TICKET_ATTACHMENT_EXTENSIONS. */ function ticketMailFileTypeWhy($extension) { $extension = strtolower(trim((string) $extension)); diff --git a/functions/ticket_mail_try.php b/functions/ticket_mail_try.php index 9da330be2..dc6c8d920 100644 --- a/functions/ticket_mail_try.php +++ b/functions/ticket_mail_try.php @@ -20,12 +20,14 @@ * 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 from its contact or a CC, 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; + * 4. a contact's address - a new ticket for their client: at more than one client, the one whose + * domain it is, else where they last raised a ticket (ticketMailSenderContact()); * 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, * else left in the mailbox, flagged. * - * Kept in step with the parser by hand - change one, change the other. + * Kept in step with the parser by hand - change one, change the other. A Reply-To (ticketMailReplyTo()) + * can't be typed in here. */ /* @@ -60,7 +62,7 @@ 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 agents get a notice. 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.'); } $steps[] = ['A mail server saying an email couldn\'t be delivered?', 'No']; @@ -89,9 +91,9 @@ function ticketMailTry($from_email, $subject, $auto_reply = false) { ? 'No - there is no ticket with the number in brackets, so it carries on' : 'No - it would be [' . $config_ticket_prefix . '123] somewhere in it']; - // The sender: a contact, or the client whose domain it is - $contact = $from_email !== '' ? mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT contact_id, contact_name, contact_client_id, client_name FROM contacts - LEFT JOIN clients ON client_id = contact_client_id WHERE contact_email = '$from_sql' AND contact_archived_at IS NULL LIMIT 1")) : null; + // The sender: a contact - at the client whose domain it is, when they are one at more than one - or the client whose domain it is + $picked = ticketMailSenderContact($from_email, $domain); + $contact = $picked['contact']; $domain_row = $domain !== '' ? mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT domain_client_id, domain_name, client_name FROM domains LEFT JOIN clients ON client_id = domain_client_id WHERE domain_name = '" . escapeSql($domain) . "' AND domain_archived_at IS NULL LIMIT 1")) : null; if ($domain_row && $domain_row['domain_name'] !== $domain) { @@ -129,9 +131,11 @@ function ticketMailTry($from_email, $subject, $auto_reply = false) { // 4. A contact if ($contact) { - $steps[] = ['A contact\'s address?', 'Yes - ' . $contact['contact_name'] . ($contact['client_name'] !== null ? ', ' . $contact['client_name'] : '')]; + $others = $picked['others'] ? ' - and at ' . implode(', ', $picked['others']) . ' too, so it goes to ' . ($contact['client_name'] ?? 'no client') . ', ' . $picked['why'] : ''; + $steps[] = ['A contact\'s address?', 'Yes - ' . $contact['contact_name'] . ($contact['client_name'] !== null ? ', ' . $contact['client_name'] : '') . $others]; 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) . $linked]]; + 'From ' . $contact['contact_name'] . ', with the subject as its subject and the email as its details. ' . ($picked['others'] ? 'A note on it names the other clients they are a contact at. ' : '') + . ticketMailTryNoReply($from_email) . $linked]]; } $steps[] = ['A contact\'s address?', 'No']; @@ -151,7 +155,7 @@ function ticketMailTry($from_email, $subject, $auto_reply = false) { } $steps[] = ['Tickets from unknown senders?', 'On']; 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 CC, so replies reach them. ' . ticketMailTryNoReply($from_email)]]; + 'Open for an agent to give it a client. The sender is added as a CC, so replies reach them. ' . ticketMailTryNoReply($from_email, true)]]; } /* @@ -175,7 +179,7 @@ function ticketMailTryReply($from_email, $ticket_id) { || mysqli_num_rows(mysqli_query($mysqli, "SELECT 1 FROM ticket_ccs WHERE ticket_cc_ticket_id = " . intval($ticket['ticket_id']) . " AND ticket_cc_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' + 'Closed tickets aren\'t reopened by email: it is kept on the ticket as an internal note, and the agent it was assigned to gets a notice - the admins, when nobody had it' . ($known ? '. The sender is told it is closed, and how to raise a new ticket.' : '. The sender isn\'t a contact or CC, so nobody is told - a guessed number would tell them its subject.')]; } $reopens = ticketMailTryReopens($ticket['ticket_status']); @@ -188,7 +192,7 @@ function ticketMailTryReply($from_email, $ticket_id) { } $agent = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT user_name FROM users WHERE user_email = '$from_sql' AND user_type = 1 AND user_status = 1 AND user_archived_at IS NULL LIMIT 1")); if ($agent) { - return ['fa-sticky-note', 'info', "An internal note on $on", 'From ' . $agent['user_name'] . ', one of your agents - as their own note. Nothing is reopened.']; + return ['fa-sticky-note', 'info', "An internal note on $on", 'From ' . $agent['user_name'] . ', one of your agents - as their own note. Nothing is reopened. When the email went to the client too - a reply to all on their email - it is their reply to the client instead, and the ticket\'s first response.']; } $cc = mysqli_num_rows(mysqli_query($mysqli, "SELECT 1 FROM ticket_ccs WHERE ticket_cc_ticket_id = " . intval($ticket['ticket_id']) . " AND ticket_cc_email = '$from_sql' LIMIT 1")); if ($cc) { @@ -215,11 +219,17 @@ function ticketMailTryStatusName($status_id) { return $row ? $row[0] : 'status ' . intval($status_id); } -/** Whether the sender is emailed the new ticket - not a no-reply address, and only while that email is on. */ -function ticketMailTryNoReply($from_email) { +/* + * Whether the sender is emailed the new ticket - not a no-reply address, and only while that email is on. $stranger: + * not a contact, so without their own subject or the ticket's link. + */ +function ticketMailTryNoReply($from_email, $stranger = false) { global $config_ticket_client_general_notifications; if (preg_match("/do[\W_]*not[\W_]*reply|no[\W_]*reply/i", $from_email)) { return 'It\'s a no-reply address, so nobody is emailed back.'; } - return intval($config_ticket_client_general_notifications) === 1 ? 'They\'re emailed its number.' : 'Emails to clients about new tickets are off, so they aren\'t emailed.'; + if (intval($config_ticket_client_general_notifications) !== 1) { + return 'Emails to clients about new tickets are off, so they aren\'t emailed.'; + } + return $stranger ? 'They\'re emailed its number - not its subject or a link to it, as anyone can send an email as someone else.' : 'They\'re emailed its number.'; }