One decision for where an email goes: ticketMailDecide() in functions/ticket_mail_decide.php runs the thread, ticket number, forwarding agent, routing rule, contact and domain, out-of-office, similar subject, contact, routed client, domain and unknown sender steps once and returns the decision with its steps, the email parser carries it out and Try an Email shows it so the two can no longer disagree, a CC whose address has an apostrophe is found again on a same-subject reply, an out-of-office is checked after the ticket number in Try an Email as the mailbox does, and an out-of-office that isn't set aside is left in the inbox; 26.12.4 changelog

This commit is contained in:
johnnyq
2026-12-02 12:34:31 -05:00
parent 6e0c87e9dc
commit a28838e52d
5 changed files with 381 additions and 341 deletions

View File

@@ -16,6 +16,7 @@ Update from Maintenance > Update as usual. This release has two database changes
- Autopay that doesn't go through - a declined or expired card, or a card that's gone - sends your team an Autopay Failed notification with Stripe's reason. Before, it was only in the invoice's history.
- Email routing rules, in Admin > Email Routing: pick an address or a domain - alerts@vendor.example, or vendor.example - and, if you like, words its subject has, and say where its new tickets go: a client and a contact, a category, a priority, an agent and a ticket template. A vendor's monitoring alerts about one client go to that client at High priority and land with the technician who looks after them, with the template's tasks already on the ticket. A rule decides the client over the sender's own contact or domain, and takes email even with tickets from unknown senders off. What it leaves as it is comes from its template. When more than one rule fits, the most exact wins - an address before a domain, a subdomain before its domain, and a rule with subject words before one without. Replies to a ticket still go on that ticket, Ignored Senders are still set aside first, and out-of-office replies are never routed. The sender is only answered and copied in when they are the ticket's contact, so a system's address isn't sent "we have your email" or every reply, and nobody at the client is emailed about an alert they didn't send. The agent a rule assigns is told, as when a ticket is assigned by hand. Each rule shows how many tickets it has routed and when the last was, and warns when it takes another client's contacts or domain, when Ignored Senders sets its email aside first, or when its client, contact, category, agent or template has been archived. Try an Email in Settings > Tickets shows which rule an email would meet and what it would do, and Email to ticket links to the page.
- An agent's email to a client now comes from them by name: "Tess Tech | PittPC Support", at the ticket mailbox's address, so the client sees who wrote and their reply still goes on the ticket. That's their email replies, resolving a ticket with a note, closing one for no response, and the "your ticket is with" note. ITFlow's automatic emails - we have your email, closed, a booked visit - and emails to your team keep the mailbox's name. Admin > Mail > From addresses shows how it reads.
- Try an Email in Settings > Tickets now asks the very questions the mailbox asks, in the same order, from the same code - so what it shows is what happens to the email. An out-of-office is now checked where the mailbox checks it, after the ticket number.
### Bug Fixes
@@ -24,6 +25,7 @@ Update from Maintenance > Update as usual. This release has two database changes
- The two-step code can be typed up to five minutes after the password, up from two - time to find the phone and the right account in the authenticator app.
- A password manager or phone that fills in the two-step code and sends the form itself signs you in, instead of going back to the email and password.
- A client's email that one of your agents forwards to the ticket mailbox is now a ticket for that client, from the person who sent it, instead of a ticket for your own company or none at all. What the agent wrote above it is their internal note on the ticket, and its history says who forwarded it. Someone at a client's domain who isn't a contact yet is added as one; anyone else gets a ticket with no client for an agent to sort out - even with tickets from unknown senders off - and isn't sent anything or copied in. This works for forwards from Gmail, Outlook (desktop, the web and the new Outlook), Apple Mail and Thunderbird, and for an email forwarded as an attachment. A reply that quotes a client's email, an email with a ticket number in its subject, and an agent forwarding a colleague's email are taken as before, and Try an Email in Settings > Tickets says how an agent's forwards are read.
- A reply by email from someone copied in on a ticket whose address has an apostrophe - d'arcy@example.com - with the ticket's subject but not its number, goes on the ticket as their reply, instead of making a new one.
### Developer Updates
@@ -35,6 +37,7 @@ Update from Maintenance > Update as usual. This release has two database changes
- Forwarded client emails: new `functions/ticket_mail_forward.php`. In `cron/ticket_email_parser.php`, after the thread and ticket-number steps and before `ticketMailSenderContact()`, an email from an active agent (`ticketMailForwardAgent()`) that isn't forged, automatic or answered at its Reply-To goes to `ticketMailForwarded($html, $text, $subject, $attachments)`. It looks for the first header block - a From line with an address and a Sent, Date, To or Subject line beside it, with English and common European labels - below a forward line (Gmail's, Thunderbird's, Apple Mail's), or anywhere when the subject is a forward (`TICKET_MAIL_FORWARD_ONLY`); Outlook's `-----Original Message-----` and underscore line only count with a forward subject, as its replies have them too. The HTML is split at `gmail_quote`, `moz-forward-container`, `divRplyFwdMsg`/`appendonsend`, Outlook's bordered header div, `blockquote type="cite"` or the forward line, as long as the part from there holds the sender, else the text part is split; a single `message/rfc822` attachment is parsed with MailMimeParser, its cid pictures inlined. When the forwarded sender isn't one of your addresses, your domain or an agent (`ticketMailForwardFromClient()`), the parser takes its sender, subject (`ticketMailForwardSubject()`) and body and sets `$email['forward'] = ['agent', 'note']`. A forward is never a similar-subject reply (it is linked as related, `linkSimilarTicket(..., true)`), a contact it creates says who forwarded it, and step 6 runs for it whatever `config_ticket_email_parse_unknown_senders` says. `addTicket()` adds "forwarded by" to the from line and audit entry, calls `ticketMailForwardNote()` (an Internal reply by the agent, when there is a note, and a history line), and doesn't CC or answer a forwarded sender with no contact. Parser attachments now carry `mime`. `ticketMailTry()` adds a "From one of your agents?" step.
- Email routing rules (DB 4.3.9, `email_routing_rules`): new `functions/mail_route.php`. A rule is `routing_rule_match` (an address or a domain, cleaned by `mailIgnoreClean()` and matched by `mailIgnoreMatches()`, so a domain takes its subdomains), optional `routing_rule_subject` (case-insensitive, whitespace-collapsed substring), and what it sets: `routing_rule_client_id`, `routing_rule_contact_id`, `routing_rule_category_id`, `routing_rule_priority`, `routing_rule_assigned_to`, `routing_rule_ticket_template_id` - 0 or '' for none - with a note, a hit count and `routing_rule_matched_at`. `mailRouteFind()` takes the most exact match (`mailRouteExactness()`: address, then more domain labels, then longer subject words, then the older rule); `mailRouteFor()` adds `mailRouteTargets()`, which re-checks each target (client and contact not archived and the contact the client's, category, active agent, template not archived) and lists what's `gone`. In `cron/ticket_email_parser.php` the rule is found after the thread, ticket-number and forward steps and never for an out-of-office; with a client it replaces `$picked`/`$domain_row`, its contact is the rule's, else the sender as that client's contact, and a client with no contact gets its own `addTicket()` call before the domain step. `$email['route']` carries the rule, with `quiet` when the sender isn't the ticket's contact (or a website form's visitor, or a new contact at a client's domain), and `$email['sender']` when the ticket's contact isn't the sender. `addTicket()` now sets priority, category, agent and billable from `mailRouteTicketFields()` (the rule's, else the template's), Open when assigned, logs the rule in the ticket history, runs `ticketTemplateFinish(..., true, true)` for the template, notifies and emails the assignee (`ticketMailAssigned()`), and when `quiet` skips the sender CC, the created email and `ticketMailColleaguesNew()`; the from line, audit, forged note and copied-CC exclusion use the sender. A quiet email is never a similar-subject reply (`linkSimilarTicket($new, $similar, 'route')`, whose third argument is now the reason - 'forward' or 'route'), step 6 runs for a routed email whatever `config_ticket_email_parse_unknown_senders` says, and the hit is counted only when a ticket was made. Admin page `admin/email_routing_rules.php` (standard list, search across sender, words, client, contact, category, agent, template and note), modal `admin/modals/email_routing_rule/email_routing_rule.php` (its contact list reloads from `agent/ajax.php?get_client_contacts`), handlers `admin/post/email_routing_rule.php` (`add_routing_rule`, `edit_routing_rule`, `delete_routing_rule`; `mailRouteReach()` for the other-clients warning). `ticketMailTry()` adds an "An email routing rule?" step and `ticketMailTryRoute()` for the outcome.
- Agent's name in the From name: `ticketEmailFrom($agent_name = '')` in `functions/ticket.php` now takes the agent's name and gives `ticketEmailFromName($agent_name, $mailbox_name)` - "Agent | Mailbox", the agent alone when the mailbox has no name or the same one, the mailbox's name unchanged without an agent; line breaks, quotes and angle brackets are removed, HTML entities decoded, and it is cut to 255. `ticketMailSend()` reads the agent from its `ticket_reply_id` (`ticketReplyAgentName()`: a Public reply whose `ticket_reply_by` is a `user_type` 1 user) or a new `agent_name` option, which `ticketMailReply()` passes from `$by` when there is no reply id (the email previews). So the reply, `ticketMailResolved()` with a note, `ticketResolveNoResponse()` and the first-response "assigned" note in `ticketStatusMovedByAgent()` carry it; the created, closed, scheduled and client-reply-relay emails and `ticketMailAgents()` don't. No database change.
- Where an email goes is decided in one place: `ticketMailDecide(array $in)` in new `functions/ticket_mail_decide.php`, used by `cron/ticket_email_parser.php` and `ticketMailTry()`. It takes raw facts - `from`, `from_name`, `subject`, `visitor` (a website form's Reply-To), `thread_ticket_id` (null when it can't be known), `automatic`, `forged`, `answers_ours` (null when unknown), `unprocessed`, `forward` - and runs steps 1-6 (thread, ticket number, the agent who may be forwarding, the routing rule, the sender's contact or domain, the out-of-office set-aside, similar subject, contact, routed client, client domain, unknown senders), returning `steps` ([question, answer], what Try an Email shows) and an `action` - `reply` (`ticket_id`, `by`), `ticket` (`client_id`, `client_name`, `contact`, `new_contact`, `picked`, `sender`, `similar`, `link_why`, `taken`), `set_aside` or `leave` (`why`, `not_ours`, `answers_unknown`) - with `agent`, `route` and `quiet`. The parser keeps its first checks (own address, bounce, ignored sender, Reply-To, duplicate Message-ID, Unprocessed Email asks), then carries the decision out; when `agent` is set it reads the forward and calls `ticketMailDecide()` again with `forward`, which skips steps 1-2 as before. `ticketMailTry()` keeps its own first checks and turns the decision into an outcome with `ticketMailTryOutcome()`. Changes in behaviour: the similar-subject check compares raw subjects and the CC lookup escapes the sender once (it was escaped twice, missing an address with an apostrophe), an out-of-office that isn't set aside is left in the inbox rather than going on to the similar-subject step, and a reply whose ticket vanished between the lookup and `addReply()` waits in Unprocessed Email instead of becoming a new ticket.
## [26.12.3]

View File

@@ -1288,176 +1288,89 @@ foreach ($messages as $message) {
}
}
// 1. A reply in a ticket's conversation - it answers one of the emails on the ticket, by its In-Reply-To or
// References - whatever its subject says (functions/ticket_mail_thread.php)
$thread_ticket_id = !in_array($asked, ['reply', 'ticket'], true) ? ticketMailHeaderTicket($in_reply_to, $references) : 0;
if ($thread_ticket_id) {
$email['threaded'] = true;
$email_processed = addReply($from_email, $date, $subject, $thread_ticket_id, $message_body, $attachments, $original_message_file, $email);
}
// 2. Reply to existing ticket with the number in subject - with the prefix that ticket was given
if (!$email_processed && !$asked_only && ($subject_ticket = ticketMailSubjectTicket(stripslashes($subject)))) {
$email_processed = addReply($from_email, $date, $subject, $subject_ticket['ticket_id'], $message_body, $attachments, $original_message_file, $email);
}
// A client's email one of your agents forwarded to the mailbox - the client's, not the agent's: from here on it is from
// whoever the forwarded part says, so it goes to the client whose email it is, and what the agent wrote above it is
// their note on the ticket (functions/ticket_mail_forward.php). It was a ticket for your own company, or none.
// Not a forged one - anyone can write an agent's address in a From line - nor a reply to a ticket (above): an agent's
// email with a ticket's number is their note on it, as always. A colleague's email forwarded is the agent's, as before
// Where it goes - a reply on a ticket, a ticket, set aside or left - decided by ticketMailDecide()
// (functions/ticket_mail_decide.php), the same steps Try an Email shows, and done here. An agent's email that forwards a
// client's is read from the forwarded part (functions/ticket_mail_forward.php) and decided again, as the client's: it goes
// to the client whose email it is, and what the agent wrote above it is their note on the ticket. Not a forged one - anyone
// can write an agent's address in a From line - nor a reply to a ticket: an agent's email with a ticket's number is their
// note on it, as always. A colleague's email forwarded is the agent's, as before
$decision = null;
$forward = null;
if (!$email_processed && !$asked_only && $forged === '' && $automatic === '' && !$answer
&& ($forward_agent = ticketMailForwardAgent($from_raw))) {
$forward = ticketMailForwarded(!empty($message_body_html) ? $message_body : '', (string) $message_body_text, stripslashes($subject), $attachments);
if ($forward && ticketMailForwardFromClient($forward['email'])) {
logApp("Cron-Email-Parser", "info", escapeSql("Email parser took an email " . $forward_agent['user_name'] . " forwarded (" . stripslashes($subject) . ") as from " . $forward['email']));
$from_raw = $forward['email'];
$from_email = escapeSql($from_raw);
$from_name = escapeSql($forward['name'] !== '' ? $forward['name'] : 'Unknown');
$from_domain = strtolower(substr($from_raw, strrpos($from_raw, '@') + 1));
$subject = escapeSql(mb_substr($forward['subject'], 0, 500));
if ($forward['html'] !== '') {
$message_body = $forward['html'];
}
$via = '';
$email['via'] = '';
$email['from_name'] = $from_name;
$email['forward'] = ['agent' => $forward_agent, 'note' => $forward['note']];
} else {
$forward = null;
}
}
// An email routing rule (Admin > Email Routing, functions/mail_route.php) - the most exact one for its sender and subject
// sets up the ticket it raises, and the client it is for over the sender's own contact or domain. Not an out-of-office,
// which is only ever a note on what it answers; a reply to a ticket was matched above
$route = null;
if (!$email_processed && !$asked_only && $automatic !== 'auto-reply') {
$route = mailRouteFor($from_raw, stripslashes($subject));
if ($route && $route['gone']) {
logApp("Cron-Email-Parser", "warning", escapeSql("The email routing rule for " . $route['name'] . " names what isn't there any more - " . implode(', ', $route['gone']) . " - fix it in Admin > Email Routing"));
}
}
// 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;
}
// Routed to a client: the rule's, over the sender's own contact or domain. Its contact is the rule's, else the sender
// when they are one of that client's contacts, else nobody. A website form's is from its visitor, as ever
$route_client_id = $route && $route['client'] ? intval($route['client']['client_id']) : 0;
if ($route_client_id) {
$picked = ['contact' => null, 'others' => [], 'why' => ''];
$domain_row = null;
$contact_row = null;
if (!$answer) {
$contact_row = $route['contact'] ?: (mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT contact_id, contact_name, contact_email, contact_client_id FROM contacts
WHERE contact_client_id = $route_client_id AND contact_email = '" . escapeSql($from_raw) . "' AND contact_archived_at IS NULL LIMIT 1")) ?: null);
}
}
// A routed email's sender is answered and copied in only as the ticket's contact - who they are, or who they will be
// as a new contact at a client's domain: a system's address isn't sent "we have your email" and every reply after it
$route_email = [];
if ($route) {
$route_sender_is_contact = $answer || ($contact_row && strcasecmp((string) $contact_row['contact_email'], $from_raw) === 0) || ($domain_row && $forged === '');
$route_email = ['route' => $route + ['quiet' => !$route_sender_is_contact]];
if ($contact_row && strcasecmp((string) $contact_row['contact_email'], $from_raw) !== 0) {
$route_email['sender'] = ['name' => stripslashes($from_name), 'email' => $from_raw];
}
}
// 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') {
if (!$asked_only) {
// An out-of-office that answers an email ITFlow sent is ITFlow's to take, whoever it is from
$answers_ours = false;
foreach (ticketMailIdsIn($in_reply_to . ' ' . $references) as $answered_id) {
$answers_ours = $answers_ours || emailMessageIdOurs($answered_id);
if ($automatic === 'auto-reply') {
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;
}
}
$facts = ['from' => $from_raw, 'from_name' => stripslashes($from_name), 'subject' => stripslashes($subject),
'visitor' => $answer ? ['email' => stripslashes($answer['email']), 'name' => stripslashes($answer['name'])] : null,
'thread_ticket_id' => ticketMailHeaderTicket($in_reply_to, $references), 'automatic' => $automatic, 'forged' => $forged,
'answers_ours' => $answers_ours, 'unprocessed' => $message instanceof MailUnprocessedMessage];
$decision = ticketMailDecide($facts);
// 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;
$client_id = $route_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);
// If we found either a contact or a domain, check recent tickets for a matching subject
if ($client_id) {
$recent_tickets_sql = mysqli_query($mysqli,
"SELECT ticket_id, ticket_subject, ticket_contact_id
FROM tickets
WHERE ticket_client_id = $client_id AND ticket_resolved_at IS NULL
AND ticket_created_at >= DATE_SUB(NOW(), INTERVAL 7 DAY)"
);
while ($rowt = mysqli_fetch_assoc($recent_tickets_sql)) {
$existing_subject = $rowt['ticket_subject'];
// Calculate similarity percentage
similar_text(strtolower($subject), strtolower($existing_subject), $percent);
if ($percent >= 95) {
$similar_id = intval($rowt['ticket_id']);
// Forwarded by an agent, it is a ticket of its own however alike - their note goes with a ticket. So is a
// routed one whose sender isn't the ticket's contact: a system's alerts aren't the client's replies
$theirs = !$answer && !$forward && !($route_email['route']['quiet'] ?? false) && (($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 {
$similar_ticket_id = $similar_id;
}
break;
if ($decision['agent']) {
$forward_agent = $decision['agent'];
$forward = ticketMailForwarded(!empty($message_body_html) ? $message_body : '', (string) $message_body_text, stripslashes($subject), $attachments);
if ($forward && ticketMailForwardFromClient($forward['email'])) {
logApp("Cron-Email-Parser", "info", escapeSql("Email parser took an email " . $forward_agent['user_name'] . " forwarded (" . stripslashes($subject) . ") as from " . $forward['email']));
$from_raw = $forward['email'];
$from_email = escapeSql($from_raw);
$from_name = escapeSql($forward['name'] !== '' ? $forward['name'] : 'Unknown');
$from_domain = strtolower(substr($from_raw, strrpos($from_raw, '@') + 1));
$subject = escapeSql(mb_substr($forward['subject'], 0, 500));
if ($forward['html'] !== '') {
$message_body = $forward['html'];
}
$via = '';
$email['via'] = '';
$email['from_name'] = $from_name;
$email['forward'] = ['agent' => $forward_agent, 'note' => $forward['note']];
$decision = ticketMailDecide(['from' => $from_raw, 'from_name' => stripslashes($from_name), 'subject' => stripslashes($subject), 'forward' => $forward_agent] + $facts);
} else {
$forward = null;
}
}
}
// 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 && !$asked_only && $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 + $route_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] + $route_email);
$route = $decision['route'] ?? null;
if ($route && $route['gone']) {
logApp("Cron-Email-Parser", "warning", escapeSql("The email routing rule for " . $route['name'] . " names what isn't there any more - " . implode(', ', $route['gone']) . " - fix it in Admin > Email Routing"));
}
// 1-3. A reply on a ticket - in its conversation, with its number in the subject, or with almost the same subject as an
// open ticket of theirs from the last week
if ($decision && $decision['action'] === 'reply') {
$email['threaded'] = $decision['by'] === 'thread';
$email_processed = addReply($from_email, $date, $subject, $decision['ticket_id'], $message_body, $attachments, $original_message_file, $email);
}
// An out-of-office that answers no ticket - set aside: it isn't a ticket, and isn't answered
if ($decision && $decision['action'] === 'set_aside') {
logApp("Cron-Email-Parser", "info", "Email parser set aside an automatic reply from $from_email ($subject) - it answers no ticket");
$email_processed = true;
}
// 4-6. A ticket - a contact's, a routed client's, a new contact's at a client's domain, or nobody's - from its sender, or a
// website form's visitor. Set up by its routing rule, saying on it which client the sender is a contact at as well
if ($decision && $decision['action'] === 'ticket') {
$client_id = intval($decision['client_id']);
$set_up = [];
if ($route) {
$set_up['route'] = $route + ['quiet' => $decision['quiet']];
}
if ($decision['sender']) {
$set_up['sender'] = $decision['sender'];
}
if ($decision['picked']) {
$set_up['picked'] = $decision['picked'];
}
}
// Routed to a client with no contact for it - from its sender, or a website form's visitor
if (!$email_processed && !$asked_only && $route_client_id) {
$email_processed = $answer
? addTicket(0, $answer['name'], $answer['email'], $route_client_id, $date, $subject, $message_body, $attachments, $original_message_file, $email + $route_email)
: addTicket(0, $from_name, $from_email, $route_client_id, $date, $subject, $message_body, $attachments, $original_message_file, $email + $route_email);
}
// 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 && !$asked_only && $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 + $route_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
$email_processed = addTicket(0, $answer['name'], $answer['email'], $client_id, $date, $subject, $message_body, $attachments, $original_message_file, $email + $set_up);
} elseif ($decision['new_contact']) {
// A new contact at the client whose domain it is - 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)));
$contact_email = $from_email;
$contact_notes = $forward ? escapeSql('Added from an email ' . $email['forward']['agent']['user_name'] . ' forwarded.') : 'Added automatically via email parsing.';
@@ -1467,28 +1380,25 @@ foreach ($messages as $message) {
logAudit("Contact", "Create", "Email parser: created contact $contact_name", $client_id, $contact_id);
triggerCustomAction('contact_create', $contact_id);
$email_processed = addTicket($contact_id, $contact_name, $contact_email, $client_id, $date, $subject, $message_body, $attachments, $original_message_file, $email + $route_email);
$email_processed = addTicket($contact_id, $contact_name, $contact_email, $client_id, $date, $subject, $message_body, $attachments, $original_message_file, $email + $set_up);
} elseif ($decision['contact']) {
$contact = $decision['contact'];
$email_processed = addTicket(intval($contact['contact_id']), escapeSql($contact['contact_name']), escapeSql($contact['contact_email']), $client_id, $date, $subject, $message_body,
$attachments, $original_message_file, $email + $set_up);
} else {
$email_processed = addTicket(0, $from_name, $from_email, $client_id, $date, $subject, $message_body, $attachments, $original_message_file, $email + $set_up);
}
}
// 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. One an agent forwarded is always taken: they
// sent it in to be a ticket, and give it its client. So is one a routing rule takes - it was set up to
if (!$email_processed && !$asked_only && ($config_ticket_email_parse_unknown_senders || $forward || $route)) {
$email_processed = $answer
? addTicket(0, $answer['name'], $answer['email'], 0, $date, $subject, $message_body, $attachments, $original_message_file, $email + $route_email)
: addTicket(0, $from_name, $from_email, 0, $date, $subject, $message_body, $attachments, $original_message_file, $email + $route_email);
}
// Almost the subject of another of the client's tickets, from someone else - linked as related
if ($decision['similar'] && is_int($email_processed) && $email_processed > 0) {
linkSimilarTicket($email_processed, intval($decision['similar']['ticket_id']), $decision['link_why']);
}
// A new ticket whose subject is almost that of another's at the client, from someone else - linked as related
if ($similar_ticket_id && is_int($email_processed) && $email_processed > 0) {
linkSimilarTicket($email_processed, $similar_ticket_id, $forward ? 'forward' : ($route_email['route']['quiet'] ?? false ? 'route' : ''));
}
// A routing rule raised a ticket - counted on its rule, with when
if ($route && is_int($email_processed) && $email_processed > 0) {
mailRouteHit($route['rule']['routing_rule_id']);
logApp("Cron-Email-Parser", "info", escapeSql("Email parser routed an email from $from_raw (" . stripslashes($subject) . ") by the rule for " . $route['name'] . " - " . mailRouteSummary($route)));
// A routing rule raised it - counted on its rule, with when
if ($route && is_int($email_processed) && $email_processed > 0) {
mailRouteHit($route['rule']['routing_rule_id']);
logApp("Cron-Email-Parser", "info", escapeSql("Email parser routed an email from $from_raw (" . stripslashes($subject) . ") by the rule for " . $route['name'] . " - " . mailRouteSummary($route)));
}
}
@@ -1524,14 +1434,12 @@ foreach ($messages as $message) {
$why = $asked_failed;
} elseif ($asked_only) {
$why = 'It couldn\'t be ' . ($asked === 'reply' ? 'added to the ticket' : 'made a ticket') . ' - try again, or pick something else';
} elseif ($config_ticket_email_parse_unknown_senders || $contact_row) {
$why = 'It couldn\'t be made a ticket';
} elseif ($domain_row && $forged !== '') {
$why = "Its sender checks failed - $forged - so it isn't taken as from the client whose domain it is from";
$not_ours = true;
} elseif ($decision && $decision['action'] === 'leave') {
// Nobody's - a stranger's, or not who it says (ticketMailDecide())
$why = $decision['why'];
$not_ours = $decision['not_ours'];
} else {
$why = 'From someone who isn\'t a contact, at a domain no client has';
$not_ours = true;
$why = 'It couldn\'t be made a ticket';
}
if ($not_ours && !($message instanceof MailUnprocessedMessage)) {
$message->markFlagged();

View File

@@ -89,6 +89,7 @@ require_once __DIR__ . '/functions/ticket_link.php';
require_once __DIR__ . '/functions/ticket_pictures.php';
require_once __DIR__ . '/functions/ticket_mail_thread.php';
require_once __DIR__ . '/functions/ticket_mail_forward.php';
require_once __DIR__ . '/functions/ticket_mail_decide.php';
require_once __DIR__ . '/functions/ticket_mail_auto.php';
require_once __DIR__ . '/functions/user_timezone.php';
require_once __DIR__ . '/functions/dispatch.php';

View File

@@ -0,0 +1,224 @@
<?php
/*
* ITFlow - where an email to the ticket mailbox goes: the one place it is decided, for the Ticket Email Parser
* (cron/ticket_email_parser.php), which then does it, and for Try an Email (functions/ticket_mail_try.php), which shows
* it. Asked in this order, each answer kept as a step:
*
* 1. a reply in a ticket's conversation, by its In-Reply-To or References (ticketMailHeaderTicket()) - a reply on it.
* Try an Email has no headers to read, so it says so and goes on;
* 2. a ticket number in [brackets] in the subject, with the prefix that ticket was given (ticketMailSubjectTicket()) -
* a reply on it;
* - from one of your agents, and not forged, automatic or a website form's - the parser reads a forward in it
* (functions/ticket_mail_forward.php) and asks again as from whoever it forwards;
* - an email routing rule (mailRouteFor(), functions/mail_route.php) - how the ticket is set up, and its client over
* the sender's contact or domain. Never an out-of-office;
* - 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;
* - an out-of-office that answers no ticket - set aside, when it is ITFlow's to take; else left in the inbox;
* 3. a subject almost the same as an open ticket of the client's from the last week - a reply on it from its contact or
* a CC; from anyone else, and from a forward or a system a rule routed, a ticket of its own, linked as related;
* 4. a contact - their client's ticket - or routed to a client, the rule's client's;
* 5. an address at a client's domain - a new contact and their ticket. Not a forged one;
* 6. anyone else - a ticket with no client when unknown senders are let in, an agent forwarded it or a rule took it;
* else left in the inbox, flagged.
*
* Before any of this the parser has dealt with ITFlow's own email come back, a mail server's bounce, an ignored sender,
* a second copy of an email and what an agent asked for in Unprocessed Email - Try an Email asks those itself, as they
* hang on what is in the email.
*/
/*
* Where an email goes. $in, raw - none of it SQL-escaped:
* from the sender's address ('' for none) - its Reply-To's, when that is someone at the same domain
* from_name their name
* subject its subject
* visitor ['email', 'name'] - a website form's visitor, its Reply-To at another domain - or null
* thread_ticket_id the ticket whose emails it answers, 0 for none - null when that can't be known (Try an Email)
* automatic '', 'auto-reply' (an out-of-office) or 'automated' (a system or a list) - ticketMailAutomaticKind()
* forged why the mail server found it forged, '' when it didn't - ticketMailSenderCheck()
* answers_ours an out-of-office answering an email ITFlow sent, by its headers - null when that can't be known
* unprocessed tried again from Unprocessed Email, so ITFlow's to take
* forward the agent who forwarded it, ['user_id', 'user_name'] - the sender is whoever it forwards
*
* What it found - ['steps' => [[question, answer], ...], 'action' => ...] and for each action:
* reply 'ticket_id', 'by' - thread, number or similar
* ticket 'client_id', 'client_name', 'contact' (the ticket's contact - contact_id, contact_name, contact_email,
* contact_client_id - or null), 'new_contact' (the sender made a contact at the client first), 'picked'
* (ticketMailSenderContact(), at more than one client - for the note saying so), 'sender' (['name',
* 'email'] when the contact isn't who sent it), 'similar' (the ticket it is linked to as related, or null)
* and 'link_why' ('', forward or route), 'taken' (for one with no client: unknown, forward or route)
* set_aside an out-of-office that answers no ticket
* leave 'why', and 'not_ours' - left in the inbox, flagged, for whoever reads it
* With every action: 'agent' (the sender is an agent, and it may be a forward - the parser reads it, Try an Email says so),
* 'route' (the rule, mailRouteFor(), or null) and 'quiet' (routed, and the sender isn't the ticket's contact: not
* answered or copied in).
*/
function ticketMailDecide(array $in) {
global $mysqli, $config_ticket_email_parse_unknown_senders, $config_ticket_prefix;
$from = strtolower(trim((string) ($in['from'] ?? '')));
$from = preg_match('/^[^@\s]+@[^@\s]+$/', $from) ? $from : '';
$domain = $from !== '' ? substr($from, strrpos($from, '@') + 1) : '';
$subject = (string) ($in['subject'] ?? '');
$visitor = !empty($in['visitor']) ? (array) $in['visitor'] : null;
$automatic = (string) ($in['automatic'] ?? '');
$forged = (string) ($in['forged'] ?? '');
$forward = !empty($in['forward']) ? (array) $in['forward'] : null;
$thread_ticket_id = array_key_exists('thread_ticket_id', $in) && $in['thread_ticket_id'] === null ? null : intval($in['thread_ticket_id'] ?? 0);
$from_sql = escapeSql($from);
$out = ['steps' => [], 'action' => 'leave', 'agent' => null, 'route' => null, 'quiet' => false, 'ticket_id' => 0, 'by' => '',
'client_id' => 0, 'client_name' => null, 'contact' => null, 'new_contact' => false, 'picked' => [], 'sender' => null,
'similar' => null, 'link_why' => '', 'taken' => '', 'why' => '', 'not_ours' => false, 'answers_unknown' => false];
$step = function ($question, $answer) use (&$out) {
$out['steps'][] = [$question, $answer];
};
if ($forward) {
$step('Forwarded by one of your agents?', 'Yes - by ' . $forward['user_name'] . ', so it is read as from ' . ($from !== '' ? $from : 'whoever it forwards') . ', a ticket of its own');
} else {
// 1. A reply in a ticket's conversation
if ($thread_ticket_id === null) {
$step('A reply to one of a ticket\'s emails?', 'Not known here - an email answering one is matched by its headers first, whatever its subject says');
} elseif ($thread_ticket_id) {
$step('A reply to one of a ticket\'s emails?', 'Yes - ' . ticketReference(ticketRow($thread_ticket_id) ?: ['ticket_prefix' => '', 'ticket_number' => $thread_ticket_id]));
return ['action' => 'reply', 'ticket_id' => $thread_ticket_id, 'by' => 'thread'] + $out;
} else {
$step('A reply to one of a ticket\'s emails?', 'No');
}
// 2. A ticket number in the subject, with the prefix that ticket was given
$numbered = ticketMailSubjectTicket($subject);
if ($numbered) {
$step('A ticket number in the subject?', 'Yes - ' . $numbered['reference']);
return ['action' => 'reply', 'ticket_id' => intval($numbered['ticket_id']), 'by' => 'number'] + $out;
}
$step('A ticket number in the subject?', preg_match('/\[[^\[\]\s]{0,40}\d\]/', $subject)
? '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');
// An agent's - a forward of a client's email is read as from the client (the parser asks again, as from them)
if ($forged === '' && $automatic === '' && !$visitor && ($agent = ticketMailForwardAgent($from))) {
$out['agent'] = $agent;
$step('From one of your agents?', 'Yes - ' . $agent['user_name'] . '. A client\'s email they forward to the mailbox is read as from the client: its sender, subject and text go the steps below,'
. ' and what ' . $agent['user_name'] . ' wrote above it is their internal note on the ticket. One from someone who isn\'t a client\'s is a ticket with no client even when tickets from unknown senders are off, and they aren\'t answered or copied in. Anything else from them goes on as from them');
}
}
// An email routing rule - never for an out-of-office
$route = $automatic !== 'auto-reply' ? mailRouteFor($from, $subject) : null;
if (mailRouteReady() && $automatic !== 'auto-reply') {
$step('An email routing rule?', $route ? 'Yes - ' . $route['name'] . ': ' . mailRouteSummary($route) . ($route['gone'] ? ' - but ' . implode(', ', $route['gone']) : '') : 'No');
}
$out['route'] = $route;
// 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, $domain);
$contact = $picked['contact'];
$domain_row = null;
if (!$contact && $domain !== '') {
$domain_row = 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;
$domain_row = $domain_row && strcasecmp($domain, (string) $domain_row['domain_name']) === 0 ? $domain_row : null;
}
// 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; else it is left in the inbox as a stranger's is
if ($automatic === 'auto-reply') {
$ours = $config_ticket_email_parse_unknown_senders || $contact || ($domain_row && $forged === '') || !empty($in['answers_ours']) || !empty($in['unprocessed']);
if ($ours) {
$step('An out-of-office or other automatic reply?', 'Yes - it answers no ticket, so it is set aside');
return ['action' => 'set_aside'] + $out;
}
$step('An out-of-office or other automatic reply?', array_key_exists('answers_ours', $in) && $in['answers_ours'] === null
? 'Yes - from someone who isn\'t a contact, at a domain no client has: set aside if it answers an email ITFlow sent, by its headers, else left in the inbox'
: 'Yes - from someone who isn\'t a contact, at a domain no client has, and it answers nothing ITFlow sent');
return ['action' => 'leave', 'not_ours' => true, 'answers_unknown' => array_key_exists('answers_ours', $in) && $in['answers_ours'] === null,
'why' => $domain_row && $forged !== '' ? "Its sender checks failed - $forged - so it isn't taken as from the client whose domain it is from" : 'From someone who isn\'t a contact, at a domain no client has'] + $out;
}
$step('An out-of-office or other automatic reply?', $automatic === 'automated' ? 'No - sent by a system or a list: taken, but never answered' : 'No');
// Routed to a client: the rule's, over the sender's own contact or domain. Its contact is the rule's, else the sender when
// they are one of that client's contacts, else nobody. A website form's is from its visitor, as ever
$route_client = $route && $route['client'] ? $route['client'] : null;
if ($route_client) {
$picked = ['contact' => null, 'others' => [], 'why' => ''];
$domain_row = null;
$contact = null;
if (!$visitor) {
$contact = $route['contact'] ? $route['contact'] + ['client_name' => $route_client['client_name']] : (mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT contact_id, contact_name, contact_email, contact_client_id, client_name
FROM contacts LEFT JOIN clients ON client_id = contact_client_id WHERE contact_client_id = " . intval($route_client['client_id']) . " AND contact_email = '$from_sql' AND contact_archived_at IS NULL LIMIT 1")) ?: null);
}
}
// A routed email's sender is answered and copied in only as the ticket's contact - who they are, or who they will be as a
// new contact at a client's domain: a system's address isn't sent "we have your email" and every reply after it
$sender_is_contact = $contact && strtolower((string) $contact['contact_email']) === $from;
$out['quiet'] = $route && !($visitor || $sender_is_contact || ($domain_row && $forged === ''));
if ($contact && !$sender_is_contact && !$visitor) {
$out['sender'] = ['name' => (string) ($in['from_name'] ?? ''), 'email' => $from];
}
// 3. Almost the same subject as an open ticket of the client's from the last week - a reply on it from its contact or a CC.
// From anyone else at the client it is a ticket of its own, linked to that one as related - and from an agent's forward, a
// website form or a system a rule routed, always
$client_id = $route_client ? intval($route_client['client_id']) : ($contact ? intval($contact['contact_client_id']) : intval($domain_row['domain_client_id'] ?? 0));
if ($client_id && mb_strlen(trim($subject)) > 10) {
$sql = mysqli_query($mysqli, "SELECT ticket_id, ticket_prefix, ticket_number, ticket_subject, ticket_contact_id FROM tickets
WHERE ticket_client_id = $client_id AND ticket_resolved_at IS NULL AND ticket_created_at >= DATE_SUB(NOW(), INTERVAL 7 DAY)");
while ($row = mysqli_fetch_assoc($sql)) {
similar_text(mb_strtolower($subject), mb_strtolower((string) $row['ticket_subject']), $percent);
if ($percent >= 95) {
$out['similar'] = $row;
break;
}
}
}
if ($out['similar']) {
$similar = $out['similar'];
$theirs = !$visitor && !$forward && !$out['quiet'] && (($contact && !$out['sender'] && intval($contact['contact_id']) === intval($similar['ticket_contact_id']))
|| ($from !== '' && mysqli_num_rows(mysqli_query($mysqli, "SELECT 1 FROM ticket_ccs WHERE ticket_cc_ticket_id = " . intval($similar['ticket_id']) . " AND ticket_cc_email = '$from_sql' LIMIT 1"))));
if ($theirs) {
$step('The same subject as an open ticket of theirs from the last week?', 'Yes - ' . ticketReference($similar));
return ['action' => 'reply', 'ticket_id' => intval($similar['ticket_id']), 'by' => 'similar', 'similar' => null] + $out;
}
$step('The same subject as an open ticket of theirs from the last week?', 'Yes - ' . ticketReference($similar) . ', but '
. ($forward ? 'a forward is a ticket of its own' : ($out['quiet'] ? 'a routed email from someone who isn\'t its contact is a ticket of its own' : 'someone else\'s')) . ', so it carries on');
$out['link_why'] = $forward ? 'forward' : ($out['quiet'] ? 'route' : '');
} else {
$step('The same subject as an open ticket of theirs from the last week?', $client_id ? 'No' : 'No - they aren\'t a client\'s');
}
// Routed to a client: its ticket, whoever the sender is
if ($route_client) {
return ['action' => 'ticket', 'client_id' => intval($route_client['client_id']), 'client_name' => (string) $route_client['client_name'], 'contact' => $contact] + $out;
}
// 4. A contact - a website form sent as one (an address made a contact before) is that contact's client's, from its visitor
if ($contact) {
$others = $picked['others'] ? ' - and at ' . implode(', ', $picked['others']) . ' too, so it goes to ' . ($contact['client_name'] ?? 'no client') . ', ' . $picked['why'] : '';
$step('A contact\'s address?', 'Yes - ' . $contact['contact_name'] . ($contact['client_name'] !== null ? ', ' . $contact['client_name'] : '') . $others);
return ['action' => 'ticket', 'client_id' => intval($contact['contact_client_id']), 'client_name' => $contact['client_name'] ?? null,
'contact' => $visitor ? null : $contact, 'picked' => $visitor ? [] : $picked] + $out;
}
$step('A contact\'s address?', 'No');
// 5. A client's domain - not a forged one: anyone could make themselves a client's contact by saying they are from its domain
if ($domain_row && $forged === '' && mb_strlen($from) <= 200) {
$step('At a client\'s domain?', 'Yes - ' . $domain . ', ' . $domain_row['client_name']);
return ['action' => 'ticket', 'client_id' => intval($domain_row['domain_client_id']), 'client_name' => $domain_row['client_name'], 'new_contact' => !$visitor] + $out;
}
$step('At a client\'s domain?', $domain_row ? "Yes - but its sender checks failed ($forged), so it isn't taken as the client's" : ($domain !== '' ? 'No - no client has ' . $domain : 'No'));
// 6. Anyone else - taken when unknown senders are let in, an agent forwarded it, or a rule took it
if ($route || $forward || $config_ticket_email_parse_unknown_senders) {
if (!$route && !$forward) {
$step('Tickets from unknown senders?', 'On');
}
return ['action' => 'ticket', 'taken' => $route ? 'route' : ($forward ? 'forward' : 'unknown')] + $out;
}
$step('Tickets from unknown senders?', 'Off');
return ['action' => 'leave', 'not_ours' => true, 'why' => $domain_row && $forged !== ''
? "Its sender checks failed - $forged - so it isn't taken as from the client whose domain it is from"
: 'From someone who isn\'t a contact, at a domain no client has'] + $out;
}

View File

@@ -1,39 +1,20 @@
<?php
/*
* ITFlow - Try an email (Admin > Settings > Tickets, Email to ticket): what the
* Ticket Email Parser (cron/ticket_email_parser.php) would do with an email from
* this address with this subject - without doing any of it. It asks the same
* questions in the same order, against the same records:
* ITFlow - Try an email (Admin > Settings > Tickets, Email to ticket): what the Ticket Email Parser
* (cron/ticket_email_parser.php) would do with an email from this address with this subject - without doing any of it.
* What happens to an email that gets past the first checks is decided by ticketMailDecide() (functions/ticket_mail_decide.php)
* for both - the same steps, in the same order, against the same records - so this can't say one thing while the parser
* does another. Asked here first, as the parser does before it, by what an email typed in can show:
*
* 0. ITFlow's own email come back (emailOwnAddresses()) is skipped - anything else from one of those addresses is left
* - email to ticket off - nothing is read;
* - 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;
* 1. an automatic reply (out of office) is a note on the ticket it answers, or set aside;
* - an email answering one of a ticket's emails, by its In-Reply-To or
* References - a reply on that ticket, whatever its subject. An email
* typed in here has no such headers, so this says so and goes on;
* 2. a ticket number in [brackets] in the subject, with the prefix that
* ticket was given (ticketMailSubjectTicket()) - a reply on that ticket,
* as whoever sent it is to the ticket (its contact or another of the
* client's, an agent, a CC, or a stranger), or a closed one turned away;
* - a client's email an agent forwarded is read as from the client it forwards (ticketMailForwarded()) - only
* said here, where there is no email to read;
* - an email routing rule (mailRouteFor(), functions/mail_route.php) sets the ticket up, and the client it is for
* over the sender's contact or domain;
* 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: 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 inbox, flagged.
* - a mail server's bounce (ticketMailIsBounce() - here, by its address alone) is read as one, whatever the settings;
* - an ignored sender (mailIgnoreFind(), functions/mail_ignore.php) is set aside.
*
* Kept in step with the parser by hand - change one, change the other. A Reply-To (ticketMailReplyTo())
* can't be typed in here.
* An email typed in has no headers - it answers no email (In-Reply-To, References), has no Reply-To and no sender checks -
* and no text, so a forward in it can't be read: each is said where it would count.
*/
/*
@@ -43,12 +24,10 @@
* ticketMailAutomaticKind() reads).
*/
function ticketMailTry($from_email, $subject, $auto_reply = false) {
global $mysqli, $config_ticket_email_parse, $config_ticket_email_parse_unknown_senders, $config_ticket_prefix;
global $config_ticket_email_parse, $config_ticket_email_parse_unknown_senders;
$from_email = strtolower(trim((string) $from_email));
$subject = mb_substr(trim((string) $subject) !== '' ? trim((string) $subject) : 'No Subject', 0, 500);
$from_sql = escapeSql($from_email);
$domain = substr(strrchr($from_email, '@') ?: '', 1);
$steps = [];
$end = function ($icon, $tone, $title, $text = '') use (&$steps) {
return ['steps' => $steps, 'outcome' => [$icon, $tone, $title, $text]];
@@ -85,139 +64,64 @@ function ticketMailTry($from_email, $subject, $auto_reply = false) {
$steps[] = ['An ignored sender?', 'No'];
}
if ($auto_reply) {
$steps[] = ['An automatic reply?', 'Yes'];
$answered = ticketMailSubjectTicket($subject);
if ($answered) {
return $end('fa-robot', 'secondary', 'An internal note on ' . $answered['reference'],
'Out-of-office and other automatic replies go on the ticket they answer as a note, to read - it isn\'t reopened, nothing is passed on, and nobody is answered, so two systems can\'t answer each other forever.');
// Where it goes from here - decided as the parser decides it
$decision = ticketMailDecide(['from' => $from_email, 'from_name' => '', 'subject' => $subject, 'thread_ticket_id' => null,
'automatic' => $auto_reply ? 'auto-reply' : '', 'forged' => '', 'answers_ours' => null]);
return ['steps' => array_merge($steps, $decision['steps']), 'outcome' => ticketMailTryOutcome($decision, $from_email, $auto_reply)];
}
/*
* Where an email ends up, from ticketMailDecide() - [icon, tone, title, text] - for an email from $from_email.
* $auto_reply: it says it is an out-of-office.
*/
function ticketMailTryOutcome(array $decision, $from_email, $auto_reply = false) {
global $config_ticket_email_parse_unknown_senders;
$route = $decision['route'];
$route_text = $route ? ticketMailTryRoute($route, $decision['quiet']) : '';
$linked = $decision['similar'] ? ' It is linked to ' . ticketReference($decision['similar']) . ' as related, as its subject is almost the same, in case it is the same thing.' : '';
if ($decision['action'] === 'reply') {
if ($auto_reply) {
return ['fa-robot', 'secondary', 'An internal note on ' . ticketReference(ticketRow($decision['ticket_id']) ?: ['ticket_prefix' => '', 'ticket_number' => $decision['ticket_id']]),
'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 ticketMailTryReply($from_email, $decision['ticket_id']) ?? ['fa-question-circle', 'warning', 'A reply on a ticket that is gone', 'The ticket isn\'t there any more.'];
}
if ($decision['action'] === 'set_aside') {
return ['fa-forward', 'secondary', 'Set aside', 'It answers no ticket, so it is moved to the ITFlow folder without one, and isn\'t answered.'];
}
if ($decision['action'] === 'leave') {
if ($decision['answers_unknown']) {
return ['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.');
}
$steps[] = ['An automatic reply?', 'No'];
// A reply to one of a ticket's emails - by its headers, which an email typed in here hasn't got
$steps[] = ['A reply to one of a ticket\'s emails?', 'Not known here - an email answering one is matched by its headers first, whatever its subject says'];
// 2. A ticket number in the subject, with the prefix that ticket was given
$numbered = ticketMailSubjectTicket($subject);
if ($numbered) {
$steps[] = ['A ticket number in the subject?', 'Yes - ' . $numbered['reference']];
return ['steps' => $steps, 'outcome' => ticketMailTryReply($from_email, $numbered['ticket_id'])];
}
$steps[] = ['A ticket number in the subject?', preg_match('/\[[^\[\]\s]{0,40}\d\]/', $subject)
? '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'];
// An agent's: a client's email they forward is read as from the client - said, as there is no email here to read
if ($forward_agent = ticketMailForwardAgent($from_email)) {
$steps[] = ['From one of your agents?', 'Yes - ' . $forward_agent['user_name'] . '. A client\'s email they forward to the mailbox is read as from the client: its sender, subject and text go the steps below,'
. ' and what ' . $forward_agent['user_name'] . ' wrote above it is their internal note on the ticket. One from someone who isn\'t a client\'s is a ticket with no client even when tickets from unknown senders are off, and they aren\'t answered or copied in. Anything else from them goes on as from them'];
return ['fa-inbox', 'warning', 'Left in the inbox',
'ITFlow leaves it in the mailbox\'s inbox, flagged, and doesn\'t look at it again. Make the sender a contact, add their domain to a client, or turn on From unknown senders too, to have email like it taken - and clear the flag on one already there to have it taken as well.'];
}
// An email routing rule (Admin > Email Routing)
$route = mailRouteFor($from_email, $subject);
if (mailRouteReady()) {
$steps[] = ['An email routing rule?', $route ? 'Yes - ' . $route['name'] . ': ' . mailRouteSummary($route) . ($route['gone'] ? ' - but ' . implode(', ', $route['gone']) : '') : 'No'];
}
// 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) {
$domain_row = null;
}
// Routed to a client - the rule's contact, else the sender as one of that client's contacts, else none
$route_client = $route && $route['client'] ? $route['client'] : null;
if ($route_client) {
$picked = ['contact' => null, 'others' => [], 'why' => ''];
$domain_row = null;
$contact = $route['contact'] ? $route['contact'] + ['client_name' => $route_client['client_name']] : (mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT contact_id, contact_name, contact_email, contact_client_id, client_name
FROM contacts LEFT JOIN clients ON client_id = contact_client_id WHERE contact_client_id = " . intval($route_client['client_id']) . " AND contact_email = '$from_sql' AND contact_archived_at IS NULL LIMIT 1")) ?: null);
}
// Its sender answered only as the ticket's contact
$route_quiet = $route && !(($contact && strtolower((string) $contact['contact_email']) === $from_email) || $domain_row);
$route_text = $route ? ticketMailTryRoute($route, $route_quiet) : '';
// 3. Almost the same subject as an open ticket of theirs from the last week - a reply from its contact or a CC; from
// anyone else at the client, a ticket of its own linked to it
$client_id = $route_client ? intval($route_client['client_id']) : ($contact ? intval($contact['contact_client_id']) : ($domain_row ? intval($domain_row['domain_client_id']) : 0));
$similar = null;
if (strlen(escapeSql($subject)) > 10 && $client_id) {
$sql = mysqli_query($mysqli, "SELECT ticket_id, ticket_prefix, ticket_number, ticket_subject, ticket_contact_id FROM tickets WHERE ticket_client_id = $client_id AND ticket_resolved_at IS NULL
AND ticket_created_at >= DATE_SUB(NOW(), INTERVAL 7 DAY)");
while ($row = mysqli_fetch_assoc($sql)) {
similar_text(strtolower(escapeSql($subject)), strtolower($row['ticket_subject']), $percent);
if ($percent >= 95) {
$similar = $row;
break;
}
}
}
$linked = '';
if ($similar) {
$theirs = !$route_quiet && (($contact && intval($contact['contact_id']) === intval($similar['ticket_contact_id']))
|| mysqli_num_rows(mysqli_query($mysqli, "SELECT 1 FROM ticket_ccs WHERE ticket_cc_ticket_id = " . intval($similar['ticket_id']) . " AND ticket_cc_email = '$from_sql' LIMIT 1")));
if ($theirs && ($reply = ticketMailTryReply($from_email, intval($similar['ticket_id'])))) {
$steps[] = ['The same subject as an open ticket of theirs from the last week?', 'Yes - ' . ticketReference($similar)];
return ['steps' => $steps, 'outcome' => $reply];
}
$steps[] = ['The same subject as an open ticket of theirs from the last week?', 'Yes - ' . ticketReference($similar) . ', but someone else\'s, so it carries on'];
$linked = ' It is linked to ' . ticketReference($similar) . ' as related, as its subject is almost the same, in case it is the same thing.';
} else {
$steps[] = ['The same subject as an open ticket of theirs from the last week?', $client_id ? 'No' : 'No - they aren\'t a client\'s'];
}
// Routed to a client: its ticket, whoever the sender is
if ($route_client) {
// A ticket - routed to a client, a contact's, a new contact's, or nobody's
$contact = $decision['contact'];
if ($route && $route['client']) {
$contact_text = $contact ? (strtolower((string) $contact['contact_email']) === $from_email ? 'From ' . $contact['contact_name'] . ', its contact. ' : 'From ' . $from_email . ', with ' . $contact['contact_name'] . ' as its contact. ')
: 'From ' . $from_email . ', with no contact - they aren\'t one of ' . $route_client['client_name'] . '\'s. ';
return ['steps' => $steps, 'outcome' => ['fa-route', 'success', 'A new ticket for ' . $route_client['client_name'],
$contact_text . 'The subject is its subject and the email its details. ' . $route_text . ($route_quiet ? '' : ' ' . ticketMailTryNoReply($from_email)) . $linked]];
: 'From ' . $from_email . ', with no contact - they aren\'t one of ' . $decision['client_name'] . '\'s. ';
return ['fa-route', 'success', 'A new ticket for ' . $decision['client_name'],
$contact_text . 'The subject is its subject and the email its details. ' . $route_text . ($decision['quiet'] ? '' : ' ' . ticketMailTryNoReply($from_email)) . $linked];
}
// 4. A contact
if ($contact) {
$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. ' . ($picked['others'] ? 'A note on it names the other clients they are a contact at. ' : '')
. ($route_text !== '' ? $route_text . ' ' : '') . ticketMailTryNoReply($from_email) . $linked]];
return ['fa-plus-circle', 'success', 'A new ticket for ' . ($decision['client_name'] ?? 'no client'),
'From ' . $contact['contact_name'] . ', with the subject as its subject and the email as its details. ' . (!empty($decision['picked']['others']) ? 'A note on it names the other clients they are a contact at. ' : '')
. ($route_text !== '' ? $route_text . ' ' : '') . ticketMailTryNoReply($from_email) . $linked];
}
$steps[] = ['A contact\'s address?', 'No'];
// 5. A client's domain
if ($domain_row) {
$steps[] = ['At a client\'s domain?', 'Yes - ' . $domain . ', ' . $domain_row['client_name']];
return ['steps' => $steps, 'outcome' => ['fa-plus-circle', 'success', 'A new contact and ticket for ' . $domain_row['client_name'],
'The sender is added as a contact of ' . $domain_row['client_name'] . ' with the name in their email, and the ticket is theirs. ' . ($route_text !== '' ? $route_text . ' ' : '') . ticketMailTryNoReply($from_email) . $linked]];
if ($decision['new_contact']) {
return ['fa-plus-circle', 'success', 'A new contact and ticket for ' . $decision['client_name'],
'The sender is added as a contact of ' . $decision['client_name'] . ' with the name in their email, and the ticket is theirs. ' . ($route_text !== '' ? $route_text . ' ' : '') . ticketMailTryNoReply($from_email) . $linked];
}
$steps[] = ['At a client\'s domain?', $domain !== '' ? 'No - no client has ' . $domain : 'No'];
// 6. Anyone else - a routing rule takes theirs whatever the setting
if ($route) {
return ['steps' => $steps, 'outcome' => ['fa-route', 'success', 'A new ticket with no client',
'The routing rule takes it even with tickets from unknown senders ' . ($config_ticket_email_parse_unknown_senders ? 'on' : 'off') . ' - open for an agent to give it a client. ' . $route_text]];
if ($decision['taken'] === 'route') {
return ['fa-route', 'success', 'A new ticket with no client',
'The routing rule takes it even with tickets from unknown senders ' . ($config_ticket_email_parse_unknown_senders ? 'on' : 'off') . ' - open for an agent to give it a client. ' . $route_text];
}
if (!$config_ticket_email_parse_unknown_senders) {
$steps[] = ['Tickets from unknown senders?', 'Off'];
return ['steps' => $steps, 'outcome' => ['fa-inbox', 'warning', 'Left in the inbox',
'ITFlow leaves it in the mailbox\'s inbox, flagged, and doesn\'t look at it again. Make the sender a contact, add their domain to a client, or turn on From unknown senders too, to have email like it taken - and clear the flag on one already there to have it taken as well.']];
}
$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, true)]];
return ['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, true)];
}
/*