Files
itflow/functions/mail_route.php

259 lines
13 KiB
PHP

<?php
/*
* Email routing rules - an address or a domain, with words its subject has, whose new tickets by email go where the rule
* says (database 4.3.9, email_routing_rules): a client and a contact, a category, a priority, an agent and a ticket
* template. Alerts from a vendor's system to the client they are about, at the priority they need, with the agent who
* looks after them.
*
* A rule decides who the ticket is for over the sender's own contact or domain - a client's system sending as a contact
* of another, say. Replies to a ticket (its emails' headers, a ticket number in the subject) still go on it, ignored
* senders are set aside first, and an out-of-office is never routed. What a rule leaves as it is comes from its
* template, when it has one, and else as any email's ticket. The sender is answered and copied in only when they are the
* ticket's contact - a system's address is never sent "we have your email" or every reply - and a rule takes email even
* with tickets from unknown senders off.
*
* When more than one rule takes an email, the most exact one routes it: an address before a domain, a subdomain before
* its domain, a rule with subject words before one without, and the longer words first. Kept in Admin > 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']) {
// With their alternate email, so email from it is theirs as well (contactHasEmail(), functions/contact.php)
$out['contact'] = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT contact_id, contact_name, contact_email, " . contactEmailAltColumn() . ", 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 $other AND " . contactEmailMatchSql($match)))[0] ?? 0);
return $out;
}
$like = escapeSql(str_replace(['\\', '%', '_'], ['\\\\', '\%', '\_'], $match));
// Their email or their alternate one (functions/contact.php)
$out['contacts'] = intval(mysqli_fetch_row(mysqli_query($mysqli, "SELECT COUNT(*) FROM contacts WHERE contact_archived_at IS NULL $other AND " . contactEmailMatchSql($match)))[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.' : '';
}