diff --git a/CHANGELOG.md b/CHANGELOG.md
index 16aca3724..70aeaa0e4 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -6,7 +6,7 @@ This file documents all notable changes made to ITFlow.
### Upgrading to 26.12.4
-Update from Maintenance > Update as usual. This release has one database change, 4.3.8, which lets ITFlow remind clients before their autopay card expires: a setting for it, and on each saved card when it was last checked with Stripe, which reminders went out and the key in their link.
+Update from Maintenance > Update as usual. This release has two database changes: 4.3.8, which lets ITFlow remind clients before their autopay card expires - a setting for it, and on each saved card when it was last checked with Stripe, which reminders went out and the key in their link - and 4.3.9, which adds the table that keeps email routing rules.
### New Features & Updates
@@ -14,6 +14,7 @@ Update from Maintenance > Update as usual. This release has one database change,
- Cards on autopay that are about to expire: a month before the month a card expires, and again in that month, the client's primary and billing contacts get an email with an Add your new card button that needs no sign-in. The new card takes the old one's place on every recurring invoice it paid, with who changed it and what they agreed to in each one's history. Your team gets a Card Expiring notification each time, and one when a client adds their new card. A card that already ran out in the last 60 days gets one email saying so. Turn the emails off with Email clients before their autopay card expires in Settings > Invoices > Paid online; a client left out of reminders isn't emailed either, and the team is still told.
- Saved cards are checked with Stripe each night when they expire soon or have lately, so a card the bank replaced shows its new expiry and nobody is asked about it. Admin > Payment Providers > Saved Cards says when each card was checked, and when the team was told it is running out.
- 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.
### Bug Fixes
@@ -31,6 +32,7 @@ Update from Maintenance > Update as usual. This release has one database change,
- Saved cards expiring (DB 4.3.8): new `functions/card_expiry.php`. `cardExpiryNightly($now = null)`, called from `cron/nightly_tasks.php` before autopay, reads back from Stripe (`cardRefresh()`, PaymentMethods retrieve) up to `CARD_EXPIRY_CHECK_LIMIT` (200) cards a night whose expiry is from 6 months ago to next month and that weren't checked in 20 hours, keeping Stripe's brand, last four and expiry in `saved_payment_description` and stamping `saved_payment_checked_at`. It then finds cards on autopay for active recurring invoices (`cardAutopayCards()`) and, for an expiry within 30 days of its month starting (stage 1) or in or past its month (stage 2), emails the billing recipients (`billingMailCardExpiring()`), notifies the team (`Card Expiring`) and logs each recurring invoice's history, recording `saved_payment_reminded_expiry`, `saved_payment_reminded` and a random `saved_payment_update_key` that both stages' links share. `settings.config_invoice_card_expiry_reminders` (default 1) and `client_reminders` gate the email only. `guest/guest_card_update.php?card=&key=` reuses `js/guest_autopay_stripe.js` (its form's `data-checkout-url` now picks the endpoint): `guest_ajax.php?guest_card_update_checkout` starts a setup-mode Checkout Session on the client's Stripe customer (`cardUpdateCheckoutStart()`), and `guest_post.php?guest_card_update_done` runs `cardUpdateFinish()`, which checks the session's mode, card and customer first, saves the new card, repoints every `recurring_payments` row of the client's that used the old card, clears the key, and sends `billingMailCardUpdated()`. `billingCardParts()` gains `expires` (yyyymm), `billingStripeChargeSaved()` reads an expired-looking card back from Stripe before refusing it, and `autopayFailedNotify()` in `functions/billing_pay.php` sends the `Autopay Failed` notification from the nightly autopay's failure branches.
- Texts: `smsInboxBulk($action, $ids, $user_id)` in `functions/sms.php` runs an action from `SMS_INBOX_BULK` (dismiss, spam, clear, not_spam, delete => the status it takes texts from and the permission it needs) on the ticked inbound texts, or with `$ids` null on the whole tab, inside `clientScopeSql()`. Spam and not spam block or unblock the numbers and move every text from them, as the single actions do. Clearing a code sets it to dismissed with its body, code and media wiped, so the text log's search can't find its words. `agent/post/texts.php` takes `bulk_texts` (with `sms_message_ids[]`) and `bulk_texts_all`, plus `sms_clear_code` for one code. `agent/texts.php` uses the standard `js/bulk_actions.js` select-all and Bulk Action button.
- 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.
## [26.12.3]
diff --git a/admin/database_updates/4.3.9.php b/admin/database_updates/4.3.9.php
new file mode 100644
index 000000000..b3078a116
--- /dev/null
+++ b/admin/database_updates/4.3.9.php
@@ -0,0 +1,36 @@
+ Email Routing): a client and a contact, a category, a priority, an
+ * agent and a ticket template - 0 or '' for each it leaves as it is - with why, who added it, and how many emails
+ * it routed and when the last was
+ *
+ * Re-runnable: the table is made only where it isn't there.
+ */
+
+defined('FROM_DB_UPDATER') || die("Direct file access is not allowed");
+
+ mysqli_query($mysqli, "CREATE TABLE IF NOT EXISTS `email_routing_rules` (
+ `routing_rule_id` int(11) NOT NULL AUTO_INCREMENT,
+ `routing_rule_match` varchar(255) NOT NULL,
+ `routing_rule_subject` varchar(255) NOT NULL DEFAULT '',
+ `routing_rule_client_id` int(11) NOT NULL DEFAULT 0,
+ `routing_rule_contact_id` int(11) NOT NULL DEFAULT 0,
+ `routing_rule_category_id` int(11) NOT NULL DEFAULT 0,
+ `routing_rule_priority` varchar(20) NOT NULL DEFAULT '',
+ `routing_rule_assigned_to` int(11) NOT NULL DEFAULT 0,
+ `routing_rule_ticket_template_id` int(11) NOT NULL DEFAULT 0,
+ `routing_rule_note` varchar(255) NOT NULL DEFAULT '',
+ `routing_rule_matches` int(11) NOT NULL DEFAULT 0,
+ `routing_rule_matched_at` datetime DEFAULT NULL,
+ `routing_rule_created_by` int(11) NOT NULL DEFAULT 0,
+ `routing_rule_created_at` datetime NOT NULL DEFAULT current_timestamp(),
+ `routing_rule_updated_at` datetime DEFAULT NULL ON UPDATE current_timestamp(),
+ PRIMARY KEY (`routing_rule_id`),
+ KEY `routing_rule_match` (`routing_rule_match`),
+ KEY `routing_rule_client_id` (`routing_rule_client_id`)
+ ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci");
diff --git a/admin/email_routing_rules.php b/admin/email_routing_rules.php
new file mode 100644
index 000000000..40f487608
--- /dev/null
+++ b/admin/email_routing_rules.php
@@ -0,0 +1,203 @@
+ Email Routing - email routing rules (functions/mail_route.php): an address or a domain, with words its subject
+ * has, whose new tickets by email go to a client and a contact, with a category, a priority, an agent and a ticket
+ * template. Each with why, who added it, and how many emails it routed and the last. New and edit in
+ * modals/email_routing_rule/email_routing_rule.php; the handlers are admin/post/email_routing_rule.php.
+ */
+
+// Default Column Sortby Filter
+$sort = "routing_rule_match";
+$order = "ASC";
+
+require_once "includes/inc_all_admin.php";
+
+if (!mailRouteReady()) { ?>
+
+ "routing_rule_match $order, routing_rule_subject ASC",
+ 'client_name' => "client_name IS NULL, client_name $order, routing_rule_match ASC",
+ 'routing_rule_matches' => "routing_rule_matches $order, routing_rule_match ASC",
+ 'routing_rule_matched_at' => "routing_rule_matched_at IS NULL, routing_rule_matched_at $order, routing_rule_match ASC",
+ 'routing_rule_created_at' => "routing_rule_created_at $order, routing_rule_match ASC",
+];
+if (!isset($sortable_columns[$sort])) {
+ $sort = 'routing_rule_match';
+}
+
+$sql = mysqli_query($mysqli, "SELECT SQL_CALC_FOUND_ROWS email_routing_rules.*, client_name, client_archived_at, contact_name, contact_archived_at, contact_client_id,
+ category_name, category_archived_at, agent.user_name AS agent_name, agent.user_status AS agent_status, agent.user_archived_at AS agent_archived_at,
+ ticket_template_name, ticket_template_archived_at, creator.user_name AS creator_name
+ FROM email_routing_rules
+ LEFT JOIN clients ON client_id = routing_rule_client_id
+ LEFT JOIN contacts ON contact_id = routing_rule_contact_id
+ LEFT JOIN categories ON category_id = routing_rule_category_id
+ LEFT JOIN users agent ON agent.user_id = routing_rule_assigned_to
+ LEFT JOIN ticket_templates ON ticket_template_id = routing_rule_ticket_template_id
+ LEFT JOIN users creator ON creator.user_id = routing_rule_created_by
+ WHERE (routing_rule_match LIKE '%$q%' OR routing_rule_subject LIKE '%$q%' OR routing_rule_note LIKE '%$q%' OR client_name LIKE '%$q%' OR contact_name LIKE '%$q%'
+ OR category_name LIKE '%$q%' OR agent.user_name LIKE '%$q%' OR ticket_template_name LIKE '%$q%')
+ ORDER BY {$sortable_columns[$sort]}
+ LIMIT $record_from, $record_to");
+$num_rows = mysqli_fetch_row(mysqli_query($mysqli, "SELECT FOUND_ROWS()"));
+
+?>
+
+
+
+
Email Routing
+
+
+
+
+
+
+
+ A new ticket by email from these addresses and domains goes where the rule says - to its client, over the sender's own contact or domain, with its
+ category, priority, agent and template. Replies to a ticket still go on it, and Ignored Senders are set aside first.
+ The sender is answered and copied in only when they are the ticket's contact. When more than one rule takes an email, the most exact routes it: an address
+ before a domain, and a rule with subject words before one without. Try an Email shows what one would do.
+
+ = $domain ? 'Everyone at this domain and its subdomains' : 'This address' ?>,
+ with “= escapeHtml($row['routing_rule_subject']) ?>” in the subject
+
+
+ 'routing rules',
+ 'icon' => 'fa-route',
+ 'text' => 'Send the new tickets from an address or a domain to a client, with a category, priority, agent or template - a vendor\'s alerts about one client, a monitoring system, a form.',
+ 'actions' => [['label' => 'New Routing Rule', 'modal' => 'modals/email_routing_rule/email_routing_rule.php', 'size' => 'lg']],
+ ];
+ require_once "../includes/filter_footer.php";
+ ?>
+
+
= settingsSectionEnd() ?>
diff --git a/cron/ticket_email_parser.php b/cron/ticket_email_parser.php
index 5e0b38876..652234d51 100644
--- a/cron/ticket_email_parser.php
+++ b/cron/ticket_email_parser.php
@@ -99,6 +99,10 @@ $read_mail_minutes = 60; // Mail someone opened before this got to it
* picked the sender is a contact at more than one client (ticketMailSenderContact()) - said in a note
* forward an agent forwarded it - ['agent' => ['user_id', 'user_name'], 'note' => what they wrote above it, HTML]
* (functions/ticket_mail_forward.php): named beside who it is from, their note on the ticket by them
+ * route an email routing rule took it (mailRouteFor(), functions/mail_route.php) - its priority, category, agent
+ * and template set the ticket up, its history says which rule, and with 'quiet' (the sender isn't the
+ * ticket's contact) nobody at the client is emailed and the sender isn't copied in
+ * sender ['name', 'email'] who it is from, raw, when that isn't the ticket's contact - a rule's contact
* 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.
@@ -118,6 +122,23 @@ function addTicket($contact_id, $contact_name, $contact_email, $client_id, $date
$forged = (string) ($email['forged'] ?? '');
$via = (string) ($email['via'] ?? '');
$forward = (array) ($email['forward'] ?? []);
+ $route = (array) ($email['route'] ?? []);
+ $quiet = $route && !empty($route['quiet']);
+ // Who it is from - the ticket's contact, unless a routing rule gave it another
+ $sender = (array) ($email['sender'] ?? []);
+ $from_name_raw = $sender ? (string) $sender['name'] : $contact_name_raw;
+ $from_email_raw = $sender ? (string) $sender['email'] : $contact_email_raw;
+
+ // Set up as a routing rule says - its own, else its template's - or as any email's ticket. Open once it has an agent
+ $priority = 'Medium';
+ $category_id = 0;
+ $assigned_to = 0;
+ $billable = intval($config_ticket_default_billable) === 1 ? 1 : 0;
+ if ($route) {
+ [$priority, $category_id, $assigned_to, $billable] = mailRouteTicketFields($route, $billable);
+ }
+ $status = $assigned_to ? TICKET_STATUS_OPEN : TICKET_STATUS_NEW;
+ $priority_esc = escapeSql($priority);
// Atomically increment and get the new ticket number
mysqli_query($mysqli, "
@@ -142,7 +163,7 @@ function addTicket($contact_id, $contact_name, $contact_email, $client_id, $date
// Convert newlines to
$message = nl2br($message);
// Wrap final formatted message
- $from_line = $contact_email_raw !== '' ? "" . escapeHtml($contact_name_raw) . " <" . escapeHtml($contact_email_raw) . ">" : 'No sender address';
+ $from_line = $from_email_raw !== '' ? "" . escapeHtml($from_name_raw) . " <" . escapeHtml($from_email_raw) . ">" : 'No sender address';
$from_line .= $via !== '' ? ' - sent by ' . escapeHtml($via) : '';
$from_line .= $forward ? ' - forwarded by ' . escapeHtml($forward['agent']['user_name']) : '';
$message = "Email from: $from_line at $date:-
$message
";
@@ -150,14 +171,24 @@ function addTicket($contact_id, $contact_name, $contact_email, $client_id, $date
$ticket_prefix_esc = mysqli_real_escape_string($mysqli, $config_ticket_prefix);
$message_esc = mysqli_real_escape_string($mysqli, $message);
$contact_email_esc = mysqli_real_escape_string($mysqli, $contact_email_raw);
+ $from_email_esc = mysqli_real_escape_string($mysqli, $from_email_raw);
$client_id = intval($client_id);
$url_key = randomString(32);
- mysqli_query($mysqli, "INSERT INTO tickets SET ticket_prefix = '$ticket_prefix_esc', ticket_number = $ticket_number, ticket_source = 'Email', ticket_subject = '$subject', ticket_details = '$message_esc', ticket_priority = 'Medium', ticket_status = 1, ticket_billable = $config_ticket_default_billable, ticket_created_by = 0, ticket_contact_id = $contact_id, ticket_url_key = '$url_key', ticket_client_id = $client_id");
+ mysqli_query($mysqli, "INSERT INTO tickets SET ticket_prefix = '$ticket_prefix_esc', ticket_number = $ticket_number, ticket_source = 'Email', ticket_subject = '$subject', ticket_details = '$message_esc', ticket_priority = '$priority_esc', ticket_category = $category_id, ticket_status = $status, ticket_billable = $billable, ticket_created_by = 0, ticket_assigned_to = $assigned_to, ticket_contact_id = $contact_id, ticket_url_key = '$url_key', ticket_client_id = $client_id");
$id = mysqli_insert_id($mysqli);
applyTicketSla($id);
+ // Routed - its history says by which rule and what it set, and its template's tasks, tags and due time are added
+ if ($route) {
+ logTicketHistory($id, escapeSql('Routed by the email routing rule for ' . $route['name'] . ' - ' . mailRouteSummary($route)));
+ if ($route['template']) {
+ ticketTemplateFinish($id, $route['template']['ticket_template_id'], true, true, null,
+ 'Raised from template ' . $route['template']['ticket_template_name'] . ' by the email routing rule for ' . $route['name']);
+ }
+ }
+
// The email it came from is the first in its conversation - the email saying it is a ticket now answers it
ticketMailKeepId($id, $message_id);
@@ -165,8 +196,9 @@ function addTicket($contact_id, $contact_name, $contact_email, $client_id, $date
ticketPicturesSaveTicket($id);
// Logging
- logAudit("Ticket", "Create", "Email parser: Client contact $contact_email_esc created ticket $ticket_prefix_esc$ticket_number ($subject) ($id)"
- . ($forward ? escapeSql(' - from an email ' . $forward['agent']['user_name'] . ' forwarded') : ''), $client_id, $id);
+ logAudit("Ticket", "Create", "Email parser: Client contact $from_email_esc created ticket $ticket_prefix_esc$ticket_number ($subject) ($id)"
+ . ($forward ? escapeSql(' - from an email ' . $forward['agent']['user_name'] . ' forwarded') : '')
+ . ($route ? escapeSql(' - routed by the rule for ' . $route['name']) : ''), $client_id, $id);
mkdirMissing('../uploads/tickets/');
$att_dir = "../uploads/tickets/" . $id . "/";
@@ -196,19 +228,19 @@ function addTicket($contact_id, $contact_name, $contact_email, $client_id, $date
mysqli_query($mysqli, "INSERT INTO ticket_attachments SET ticket_attachment_name = '$ticket_attachment_name_esc', ticket_attachment_reference_name = '$ticket_attachment_reference_name_esc', ticket_attachment_ticket_id = $id");
} else {
$ticket_attachment_name_esc = mysqli_real_escape_string($mysqli, $att_name);
- logAudit("Ticket", "Edit", "Email parser: Blocked attachment $ticket_attachment_name_esc from Client contact $contact_email_esc for ticket $ticket_prefix_esc$ticket_number", $client_id, $id);
+ logAudit("Ticket", "Edit", "Email parser: Blocked attachment $ticket_attachment_name_esc from Client contact $from_email_esc for ticket $ticket_prefix_esc$ticket_number", $client_id, $id);
$dropped[] = ['name' => $att_name, 'why' => ticketMailFileTypeWhy($att_extension)];
}
}
// Found forged by the mail server that took it - said first, before anything else on the ticket
if ($forged !== '') {
- ticketMailForgedNote($id, $forged, $contact_email_raw, $copied);
+ ticketMailForgedNote($id, $forged, $from_email_raw, $copied);
}
// Forwarded by an agent - what they wrote above it, their note on the ticket, and the history saying who
if ($forward) {
- ticketMailForwardNote($id, $forward['agent'], (string) ($forward['note'] ?? ''), $contact_email_raw);
+ ticketMailForwardNote($id, $forward['agent'], (string) ($forward['note'] ?? ''), $from_email_raw);
}
// From a contact at more than one client - which it went to, and the others
@@ -220,15 +252,16 @@ function addTicket($contact_id, $contact_name, $contact_email, $client_id, $date
// 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, nor when an agent forwarded it: someone who isn't a client's, sent
// in to be looked at - a phishing email, a vendor's - is only answered once an agent gives the ticket its contact
+ // A routed one's sender is only answered as the ticket's contact - a system's address isn't copied in on every reply
$forward_stranger = $forward && !$contact_id;
- if (!$contact_id && $forged === '' && !$forward_stranger && $contact_email_raw !== '' && !preg_match($bad_pattern, $contact_email_esc)) {
+ if (!$contact_id && $forged === '' && !$forward_stranger && !$quiet && $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");
}
// The people it was also to or copied to are its CCs - not your own addresses or agents (ticketMailCopiedCcs()), and none
// from a forged email, whose sender could copy themselves in on every reply
if ($forged === '') {
- ticketMailCopiedCcs($id, $copied, $contact_email_raw);
+ ticketMailCopiedCcs($id, $copied, $from_email_raw);
}
// The sender is told it is a ticket now - unless they asked for replies only (Your account in the client portal), it was
@@ -236,7 +269,7 @@ function addTicket($contact_id, $contact_name, $contact_email, $client_id, $date
// 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 && $contact_email_raw !== '' && !preg_match($bad_pattern, $contact_email) && $contact_wants && $automatic === '' && $forged === ''
- && !$forward_stranger && ticketMailAnswersLeft($contact_email_raw)) {
+ && !$forward_stranger && !$quiet && ticketMailAnswersLeft($contact_email_raw)) {
ticketMailCreated($id, [], false, 'email', [['email' => $contact_email_raw, 'name' => $contact_name_raw]], !$contact_id);
}
@@ -244,13 +277,24 @@ function addTicket($contact_id, $contact_name, $contact_email, $client_id, $date
ticketMailNewTicketAddress($id, 'email');
// 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) {
+ // 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),
+ // nor of one a routing rule sent them that their contact didn't send - a system's alert
+ if ($forged === '' && $contact_id && !$quiet) {
ticketMailColleaguesNew($id);
}
triggerCustomAction('ticket_create', $id);
+ // The agent a routing rule (or its template) gave it hears about it, as when it is assigned by hand
+ if ($assigned_to) {
+ $row = ticketRow($id);
+ $by = 'The email routing rule for ' . $route['name'];
+ ticketTeamNotifyOn('assigned_app') && mysqli_query($mysqli, "INSERT INTO notifications SET notification_type = 'Ticket', notification = '"
+ . escapeSql('Ticket ' . ticketReference($row) . ' - ' . $row['ticket_subject'] . ' has been assigned to you by the email routing rule for ' . $route['name']) . "',
+ notification_action = '" . escapeSql('/agent/' . ticketUrl($id, $client_id)) . "', notification_client_id = $client_id, notification_user_id = $assigned_to");
+ ticketMailAssigned($assigned_to, [$id], $by);
+ }
+
return intval($id);
}
@@ -332,14 +376,15 @@ function addBounce($message, array $headers, $from_email, $subject, $take_all =
* someone who isn't its contact or a CC on it: kept as a ticket of its own, linked to that one as related
* (functions/ticket_link.php), so an agent sees both and can merge them.
*/
-function linkSimilarTicket($new_id, $similar_id, $forwarded = false) {
+function linkSimilarTicket($new_id, $similar_id, $why = '') {
$session_name = $GLOBALS['session_name'] ?? null;
$GLOBALS['session_name'] = 'The email parser';
ticketLinkTogether([intval($new_id), intval($similar_id)]);
$GLOBALS['session_name'] = $session_name;
$similar = ticketRow($similar_id);
if ($similar) {
- logTicketHistory(intval($new_id), escapeSql("Its subject is almost the same as " . ticketReference($similar) . "'s, " . ($forwarded ? 'and an email an agent forwarded is a ticket of its own' : 'from someone else at the client')
+ $whys = ['forward' => 'and an email an agent forwarded is a ticket of its own', 'route' => 'and an email a routing rule sends is a ticket of its own'];
+ logTicketHistory(intval($new_id), escapeSql("Its subject is almost the same as " . ticketReference($similar) . "'s, " . ($whys[$why] ?? 'from someone else at the client')
. " - linked as related, in case it is the same thing"));
}
}
@@ -1284,6 +1329,17 @@ foreach ($messages as $message) {
}
}
+ // 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);
@@ -1294,6 +1350,29 @@ foreach ($messages as $message) {
$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
@@ -1314,7 +1393,7 @@ foreach ($messages as $message) {
$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 = $contact_row ? intval($contact_row['contact_client_id']) : intval($domain_row['domain_client_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
@@ -1334,8 +1413,9 @@ foreach ($messages as $message) {
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
- $theirs = !$answer && !$forward && (($contact_id && $contact_id === intval($rowt['ticket_contact_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);
@@ -1353,21 +1433,28 @@ foreach ($messages as $message) {
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);
+ $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]);
+ $email_processed = addTicket($contact_id, $contact_name, $contact_email, $client_id, $date, $subject, $message_body, $attachments, $original_message_file, $email + ['picked' => $picked] + $route_email);
}
}
+ // 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);
+ $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
@@ -1380,22 +1467,28 @@ 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);
+ $email_processed = addTicket($contact_id, $contact_name, $contact_email, $client_id, $date, $subject, $message_body, $attachments, $original_message_file, $email + $route_email);
}
}
// 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
- if (!$email_processed && !$asked_only && ($config_ticket_email_parse_unknown_senders || $forward)) {
+ // 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)
- : addTicket(0, $from_name, $from_email, 0, $date, $subject, $message_body, $attachments, $original_message_file, $email);
+ ? 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);
}
// 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, (bool) $forward);
+ 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)));
}
diff --git a/db.sql b/db.sql
index 3da81043e..912a5df9b 100644
--- a/db.sql
+++ b/db.sql
@@ -1775,6 +1775,35 @@ CREATE TABLE `email_ignored_senders` (
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
+--
+-- Table structure for table `email_routing_rules`
+--
+
+DROP TABLE IF EXISTS `email_routing_rules`;
+/*!40101 SET @saved_cs_client = @@character_set_client */;
+/*!40101 SET character_set_client = utf8mb4 */;
+CREATE TABLE `email_routing_rules` (
+ `routing_rule_id` int(11) NOT NULL AUTO_INCREMENT,
+ `routing_rule_match` varchar(255) NOT NULL,
+ `routing_rule_subject` varchar(255) NOT NULL DEFAULT '',
+ `routing_rule_client_id` int(11) NOT NULL DEFAULT 0,
+ `routing_rule_contact_id` int(11) NOT NULL DEFAULT 0,
+ `routing_rule_category_id` int(11) NOT NULL DEFAULT 0,
+ `routing_rule_priority` varchar(20) NOT NULL DEFAULT '',
+ `routing_rule_assigned_to` int(11) NOT NULL DEFAULT 0,
+ `routing_rule_ticket_template_id` int(11) NOT NULL DEFAULT 0,
+ `routing_rule_note` varchar(255) NOT NULL DEFAULT '',
+ `routing_rule_matches` int(11) NOT NULL DEFAULT 0,
+ `routing_rule_matched_at` datetime DEFAULT NULL,
+ `routing_rule_created_by` int(11) NOT NULL DEFAULT 0,
+ `routing_rule_created_at` datetime NOT NULL DEFAULT current_timestamp(),
+ `routing_rule_updated_at` datetime DEFAULT NULL ON UPDATE current_timestamp(),
+ PRIMARY KEY (`routing_rule_id`),
+ KEY `routing_rule_match` (`routing_rule_match`),
+ KEY `routing_rule_client_id` (`routing_rule_client_id`)
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;
+/*!40101 SET character_set_client = @saved_cs_client */;
+
--
-- Table structure for table `email_queue`
--
diff --git a/functions.php b/functions.php
index c02a542bc..f5788b9e4 100644
--- a/functions.php
+++ b/functions.php
@@ -156,6 +156,7 @@ require_once __DIR__ . '/functions/ticket_reply_send.php';
require_once __DIR__ . '/functions/guest_link.php';
require_once __DIR__ . '/functions/email_template.php';
require_once __DIR__ . '/functions/mail_ignore.php';
+require_once __DIR__ . '/functions/mail_route.php';
require_once __DIR__ . '/functions/mail_graph.php';
require_once __DIR__ . '/functions/purchase_orders.php';
require_once __DIR__ . '/functions/kb.php';
diff --git a/functions/mail_route.php b/functions/mail_route.php
new file mode 100644
index 000000000..450fef4e7
--- /dev/null
+++ b/functions/mail_route.php
@@ -0,0 +1,257 @@
+ Email Routing
+ * (admin/email_routing_rules.php). Checked by cron/ticket_email_parser.php (mailRouteFor()) and by Try an Email
+ * (functions/ticket_mail_try.php).
+ */
+
+/** Whether the 4.3.9 update has run - email_routing_rules is there. */
+function mailRouteReady() {
+ global $mysqli;
+ static $ready = null;
+ if ($ready === null) {
+ $version = defined('CURRENT_DATABASE_VERSION') ? CURRENT_DATABASE_VERSION
+ : (string) (mysqli_fetch_row(mysqli_query($mysqli, "SELECT config_current_database_version FROM settings WHERE company_id = 1"))[0] ?? '0');
+ $ready = version_compare($version, '4.3.9', '>=');
+ }
+ return $ready;
+}
+
+/** Every rule - id => row - read once a run. $reload reads them again. */
+function mailRouteRules($reload = false) {
+ global $mysqli;
+ static $rules = null;
+ if ($rules === null || $reload) {
+ $rules = [];
+ if (mailRouteReady()) {
+ $sql = mysqli_query($mysqli, "SELECT * FROM email_routing_rules ORDER BY routing_rule_id");
+ while ($sql && ($row = mysqli_fetch_assoc($sql))) {
+ $rules[intval($row['routing_rule_id'])] = $row;
+ }
+ }
+ }
+ return $rules;
+}
+
+/** Subject words as kept - trimmed, spaces made one, at most 255 characters. '' for any subject. */
+function mailRouteSubjectClean($subject) {
+ return mb_substr(trim((string) preg_replace('/\s+/u', ' ', (string) $subject)), 0, 255);
+}
+
+/** Whether a rule takes an email from $email with $subject - its sender (mailIgnoreMatches()), and its words in the subject, any case. */
+function mailRouteMatches(array $rule, $email, $subject) {
+ if (!mailIgnoreMatches($rule['routing_rule_match'], $email)) {
+ return false;
+ }
+ $words = (string) $rule['routing_rule_subject'];
+ return $words === '' || mb_stripos(preg_replace('/\s+/u', ' ', (string) $subject), $words) !== false;
+}
+
+/*
+ * How exact a rule is, for sorting - the larger first: an address before a domain, a longer domain (a subdomain) before
+ * a shorter, subject words before none, longer words before shorter, and the older rule last of all.
+ */
+function mailRouteExactness(array $rule) {
+ $match = (string) $rule['routing_rule_match'];
+ return [strpos($match, '@') !== false ? 1 : 0, substr_count($match, '.'), mb_strlen((string) $rule['routing_rule_subject']), -intval($rule['routing_rule_id'])];
+}
+
+/** The rule that routes an email from $email with $subject - its row, the most exact of those that take it - or null. */
+function mailRouteFind($email, $subject) {
+ $best = null;
+ foreach (mailRouteRules() as $rule) {
+ if (mailRouteMatches($rule, $email, $subject) && ($best === null || mailRouteExactness($rule) > mailRouteExactness($best))) {
+ $best = $rule;
+ }
+ }
+ return $best;
+}
+
+/** A rule routed an email - counted, with when. */
+function mailRouteHit($id) {
+ global $mysqli;
+ mysqli_query($mysqli, "UPDATE email_routing_rules SET routing_rule_matches = routing_rule_matches + 1, routing_rule_matched_at = NOW() WHERE routing_rule_id = " . intval($id));
+}
+
+/*
+ * What a rule sets, as it stands now - each checked, as what it named may have been archived since:
+ * client the client's row (client_id, client_name), not archived - null when it sets none, or it is gone
+ * contact the contact's row (contact_id, contact_name, contact_email, contact_client_id), of that client, not
+ * archived - null when it sets none
+ * category_id a ticket category's id, 0 for none
+ * priority a priority, '' for none
+ * assigned_to an active agent's id, 0 for none; agent_name theirs
+ * template the ticket template's row, not archived - null when it sets none
+ * gone what it named that isn't there any more, as words - for the rule's page, Try an Email and the app log
+ */
+function mailRouteTargets(array $rule) {
+ global $mysqli;
+ $out = ['client' => null, 'contact' => null, 'category_id' => 0, 'category_name' => '', 'priority' => '', 'assigned_to' => 0, 'agent_name' => '',
+ 'template' => null, 'gone' => []];
+
+ $client_id = intval($rule['routing_rule_client_id']);
+ if ($client_id) {
+ $out['client'] = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT client_id, client_name FROM clients WHERE client_id = $client_id AND client_archived_at IS NULL LIMIT 1")) ?: null;
+ if (!$out['client']) {
+ $out['gone'][] = 'its client is archived or deleted';
+ }
+ }
+ $contact_id = intval($rule['routing_rule_contact_id']);
+ if ($contact_id && $out['client']) {
+ $out['contact'] = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT contact_id, contact_name, contact_email, contact_client_id FROM contacts
+ WHERE contact_id = $contact_id AND contact_client_id = $client_id AND contact_archived_at IS NULL LIMIT 1")) ?: null;
+ if (!$out['contact']) {
+ $out['gone'][] = 'its contact is archived or deleted';
+ }
+ }
+ $category_id = intval($rule['routing_rule_category_id']);
+ if ($category_id) {
+ $category = mysqli_fetch_row(mysqli_query($mysqli, "SELECT category_name FROM categories WHERE category_id = $category_id AND category_type = 'Ticket' AND category_archived_at IS NULL LIMIT 1"));
+ if ($category) {
+ $out['category_id'] = $category_id;
+ $out['category_name'] = (string) $category[0];
+ } else {
+ $out['gone'][] = 'its category is archived or deleted';
+ }
+ }
+ $priority = (string) $rule['routing_rule_priority'];
+ $out['priority'] = in_array($priority, TICKET_PRIORITIES, true) ? $priority : '';
+ $assigned_to = intval($rule['routing_rule_assigned_to']);
+ if ($assigned_to) {
+ $agent = mysqli_fetch_row(mysqli_query($mysqli, "SELECT user_name FROM users WHERE user_id = $assigned_to AND user_type = 1 AND user_status = 1 AND user_archived_at IS NULL LIMIT 1"));
+ if ($agent) {
+ $out['assigned_to'] = $assigned_to;
+ $out['agent_name'] = (string) $agent[0];
+ } else {
+ $out['gone'][] = 'its agent is disabled or archived';
+ }
+ }
+ $template_id = intval($rule['routing_rule_ticket_template_id']);
+ if ($template_id) {
+ $template = ticketTemplateRow($template_id);
+ if ($template && empty($template['ticket_template_archived_at'])) {
+ $out['template'] = $template;
+ } else {
+ $out['gone'][] = 'its ticket template is archived or deleted';
+ }
+ }
+ return $out;
+}
+
+/*
+ * The rule that routes an email from $email with $subject, and what it sets (mailRouteTargets()) - ['rule' => its row,
+ * 'name' => the rule in words] + the targets - or null when none takes it.
+ */
+function mailRouteFor($email, $subject) {
+ if (!mailRouteReady()) {
+ return null;
+ }
+ $rule = mailRouteFind($email, $subject);
+ if (!$rule) {
+ return null;
+ }
+ return ['rule' => $rule, 'name' => mailRouteName($rule)] + mailRouteTargets($rule);
+}
+
+/** A rule in words - "alerts@vendor.example", "@vendor.example with "Backup failed" in the subject". */
+function mailRouteName(array $rule) {
+ $match = (string) $rule['routing_rule_match'];
+ $name = strpos($match, '@') === false ? "@$match" : $match;
+ return $name . ((string) $rule['routing_rule_subject'] !== '' ? ' with "' . $rule['routing_rule_subject'] . '" in the subject' : '');
+}
+
+/*
+ * What a rule sets, in words - "Kestrel Precision (Gregor Lind), Monitoring, High, assigned to Tess Tech, template Server
+ * Down" - from mailRouteTargets(). Raw text.
+ */
+function mailRouteSummary(array $targets) {
+ $parts = [];
+ if ($targets['client']) {
+ $parts[] = $targets['client']['client_name'] . ($targets['contact'] ? ' (' . $targets['contact']['contact_name'] . ')' : '');
+ }
+ if ($targets['category_name'] !== '') {
+ $parts[] = 'category ' . $targets['category_name'];
+ }
+ if ($targets['priority'] !== '') {
+ $parts[] = $targets['priority'] . ' priority';
+ }
+ if ($targets['agent_name'] !== '') {
+ $parts[] = 'assigned to ' . $targets['agent_name'];
+ }
+ if ($targets['template']) {
+ $parts[] = 'template ' . $targets['template']['ticket_template_name'];
+ }
+ return $parts ? implode(', ', $parts) : 'nothing it names is there any more';
+}
+
+/*
+ * How a ticket from email is set up with a rule - [priority, category_id, assigned_to, billable] - the rule's, else its
+ * template's, else as any email's ticket ($billable the default).
+ */
+function mailRouteTicketFields(array $route, $billable) {
+ $template = $route['template'] ?? null;
+ $priority = $route['priority'] !== '' ? $route['priority'] : ($template ? ticketPriority($template['ticket_template_priority'] ?? '') : 'Medium');
+ $category_id = $route['category_id'] ?: ($template ? ticketCategoryId($template['ticket_template_category_id']) : 0);
+ $assigned_to = $route['assigned_to'] ?: ($template ? ticketAgentId($template['ticket_template_assigned_to']) : 0);
+ if ($template && $template['ticket_template_billable'] !== null) {
+ $billable = intval($template['ticket_template_billable']) ? 1 : 0;
+ }
+ return [$priority, intval($category_id), intval($assigned_to), intval($billable) ? 1 : 0];
+}
+
+/*
+ * Who a rule's address or domain also takes that it may not be meant to - its contacts at other clients than $client_id
+ * (or at any, when it routes to none) and other clients whose domain it is: their new tickets by email go where the rule
+ * says. ['contacts' => how many, 'clients' => names]. For the warning on saving one.
+ */
+function mailRouteReach($match, $client_id = 0) {
+ global $mysqli;
+ $match = strtolower((string) $match);
+ $client_id = intval($client_id);
+ $out = ['contacts' => 0, 'clients' => []];
+ if ($match === '' || !$client_id) {
+ return $out;
+ }
+ $match_sql = escapeSql($match);
+ $other = "AND contact_client_id <> $client_id";
+ if (strpos($match, '@') !== false) {
+ $out['contacts'] = intval(mysqli_fetch_row(mysqli_query($mysqli, "SELECT COUNT(*) FROM contacts WHERE contact_archived_at IS NULL AND LOWER(contact_email) = '$match_sql' $other"))[0] ?? 0);
+ return $out;
+ }
+ $like = escapeSql(str_replace(['\\', '%', '_'], ['\\\\', '\%', '\_'], $match));
+ $out['contacts'] = intval(mysqli_fetch_row(mysqli_query($mysqli, "SELECT COUNT(*) FROM contacts WHERE contact_archived_at IS NULL $other
+ AND (LOWER(contact_email) LIKE '%@$like' OR LOWER(contact_email) LIKE '%.$like')"))[0] ?? 0);
+ $sql = mysqli_query($mysqli, "SELECT DISTINCT client_name FROM domains JOIN clients ON client_id = domain_client_id
+ WHERE domain_archived_at IS NULL AND client_archived_at IS NULL AND client_id <> $client_id AND (LOWER(domain_name) = '$match_sql' OR LOWER(domain_name) LIKE '%.$like')
+ ORDER BY client_name LIMIT 5");
+ while ($sql && ($row = mysqli_fetch_row($sql))) {
+ $out['clients'][] = (string) $row[0];
+ }
+ return $out;
+}
+
+/* The warning for a rule that takes other clients' contacts' or domains' email - '' when it takes none. HTML. */
+function mailRouteReachText(array $reach, $client_name) {
+ $parts = [];
+ if ($reach['contacts']) {
+ $parts[] = $reach['contacts'] . ' contact' . ($reach['contacts'] === 1 ? '' : 's') . ' of other clients';
+ }
+ if ($reach['clients']) {
+ $parts[] = 'the domain of ' . implode(', ', array_map('escapeHtml', $reach['clients']));
+ }
+ return $parts ? 'It takes the email of ' . implode(' and ', $parts) . ' - their new tickets by email go to ' . escapeHtml($client_name) . ' instead.' : '';
+}
diff --git a/functions/ticket_mail_try.php b/functions/ticket_mail_try.php
index 60b74c70f..188c06f49 100644
--- a/functions/ticket_mail_try.php
+++ b/functions/ticket_mail_try.php
@@ -21,6 +21,8 @@
* 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;
@@ -121,6 +123,12 @@ function ticketMailTry($from_email, $subject, $auto_reply = false) {
. ' 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'];
}
+ // 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'];
@@ -130,9 +138,21 @@ function ticketMailTry($from_email, $subject, $auto_reply = false) {
$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 = $contact ? intval($contact['contact_client_id']) : ($domain_row ? intval($domain_row['domain_client_id']) : 0);
+ $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
@@ -147,8 +167,8 @@ function ticketMailTry($from_email, $subject, $auto_reply = false) {
}
$linked = '';
if ($similar) {
- $theirs = ($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"));
+ $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];
@@ -159,13 +179,21 @@ function ticketMailTry($from_email, $subject, $auto_reply = false) {
$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) {
+ $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]];
+ }
+
// 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. ' : '')
- . ticketMailTryNoReply($from_email) . $linked]];
+ . ($route_text !== '' ? $route_text . ' ' : '') . ticketMailTryNoReply($from_email) . $linked]];
}
$steps[] = ['A contact\'s address?', 'No'];
@@ -173,11 +201,15 @@ function ticketMailTry($from_email, $subject, $auto_reply = false) {
if ($domain_row) {
$steps[] = ['At a client\'s domain?', 'Yes - ' . $domain . ', ' . $domain_row['client_name']];
return ['steps' => $steps, 'outcome' => ['fa-plus-circle', 'success', 'A new contact and ticket for ' . $domain_row['client_name'],
- 'The sender is added as a contact of ' . $domain_row['client_name'] . ' with the name in their email, and the ticket is theirs. ' . ticketMailTryNoReply($from_email) . $linked]];
+ '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]];
}
$steps[] = ['At a client\'s domain?', $domain !== '' ? 'No - no client has ' . $domain : 'No'];
- // 6. Anyone else
+ // 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 (!$config_ticket_email_parse_unknown_senders) {
$steps[] = ['Tickets from unknown senders?', 'Off'];
return ['steps' => $steps, 'outcome' => ['fa-inbox', 'warning', 'Left in the inbox',
@@ -188,6 +220,25 @@ function ticketMailTry($from_email, $subject, $auto_reply = false) {
'Open for an agent to give it a client. The sender is added as a CC, so replies reach them. ' . ticketMailTryNoReply($from_email, true)]];
}
+/*
+ * What a routing rule does to the ticket, as sentences - how it is set up (its own, else its template's), and with $quiet
+ * that nobody at the client is emailed. Raw text.
+ */
+function ticketMailTryRoute(array $route, $quiet) {
+ global $config_ticket_default_billable;
+ [$priority, $category_id, $assigned_to] = mailRouteTicketFields($route, $config_ticket_default_billable);
+ $agent = $assigned_to ? (string) (getFieldById('users', $assigned_to, 'user_name') ?? '') : '';
+ $category = $category_id ? (string) (getFieldById('categories', $category_id, 'category_name') ?? '') : '';
+ $text = 'The routing rule makes it ' . $priority . ' priority' . ($category !== '' ? ", in $category" : '') . ($agent !== '' ? ", and assigns it to $agent, who is told - so it starts Open" : '') . '.';
+ if ($route['template']) {
+ $text .= ' Template ' . $route['template']['ticket_template_name'] . ' adds its tasks, tags and due time.';
+ }
+ if ($quiet) {
+ $text .= ' The sender isn\'t its contact, so nobody at the client is emailed that it is a ticket, and the sender isn\'t copied in on its replies.';
+ }
+ return $text;
+}
+
/*
* What a reply by email to ticket $ticket_id from $from_email would do (addReply()
* in the parser) - [icon, tone, title, text] - or null when there is no such ticket.