mirror of
https://github.com/itflow-org/itflow
synced 2026-12-03 09:39:02 +00:00
Email routing rules: Admin > Email Routing sends the new tickets by email from an address or a domain, optionally only those with given words in the subject, to a client and contact with a category, priority, assigned agent and ticket template, the most exact rule winning and a rule deciding the client over the sender's own contact or domain, taking email even with unknown senders off, answering and copying in the sender only when they are the ticket's contact, telling the assigned agent, skipping what has been archived, and warning on save about other clients' contacts or domains and ignored senders, while replies, ignored senders and out-of-office replies are handled as before; Try an Email shows the rule (DB 4.3.9, functions/mail_route.php, admin/email_routing_rules.php); 26.12.4 changelog
This commit is contained in:
@@ -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]
|
||||
|
||||
|
||||
36
admin/database_updates/4.3.9.php
Normal file
36
admin/database_updates/4.3.9.php
Normal file
@@ -0,0 +1,36 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* ITFlow - Database update to version 4.3.9 (from 4.3.8)
|
||||
* Included by admin/database_updates.php - do not access directly
|
||||
*
|
||||
* email_routing_rules - an address or a domain, with words its subject has, whose new tickets by email go where the
|
||||
* rule says (functions/mail_route.php, Admin > 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");
|
||||
203
admin/email_routing_rules.php
Normal file
203
admin/email_routing_rules.php
Normal file
@@ -0,0 +1,203 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* Admin > 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()) { ?>
|
||||
<div class="alert alert-warning">Email routing needs the database update - <a href="update.php" class="alert-link">Maintenance > Update</a>.</div>
|
||||
<?php require_once "../includes/footer.php";
|
||||
return;
|
||||
}
|
||||
|
||||
// Only these sort - an unknown column would take the page down
|
||||
$sortable_columns = [
|
||||
'routing_rule_match' => "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()"));
|
||||
|
||||
?>
|
||||
|
||||
<div class="card" data-routing-rules>
|
||||
<div class="card-header bg-dark py-2">
|
||||
<h3 class="card-title mt-2"><i class="fas fa-fw fa-route me-2"></i>Email Routing</h3>
|
||||
<div class="card-tools">
|
||||
<button type="button" class="btn btn-primary ajax-modal" data-modal-size="lg" data-modal-url="modals/email_routing_rule/email_routing_rule.php">
|
||||
<i class="fas fa-plus"></i><span class="d-none d-lg-inline ms-2">New Routing Rule</span>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="card-header py-3">
|
||||
<p class="small text-body-secondary mb-3">
|
||||
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 <a href="email_ignored_senders.php">Ignored Senders</a> 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. <a href="settings_ticket.php#section-email">Try an Email</a> shows what one would do.
|
||||
</p>
|
||||
<form autocomplete="off">
|
||||
<div class="row g-2 align-items-center">
|
||||
<div class="col-lg-5 col-md-6">
|
||||
<div class="input-group">
|
||||
<input type="search" class="form-control" name="q" value="<?php if (isset($q)) { echo stripslashes(escapeHtml($q)); } ?>" placeholder="Search routing rules..." title="An address, a domain, subject words, a client, a category, an agent, a template, or why">
|
||||
<button class="btn btn-dark" title="Search"><i class="fas fa-search"></i></button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<div class="table-responsive">
|
||||
<table class="table table-hover align-middle mb-0">
|
||||
<thead class="table-light text-nowrap <?php if ($num_rows[0] == 0) { echo "d-none"; } ?>">
|
||||
<tr>
|
||||
<th class="ps-3"><?= sortLink('routing_rule_match', 'Sender') ?></th>
|
||||
<th><?= sortLink('client_name', 'Goes to') ?></th>
|
||||
<th class="d-none d-md-table-cell">Sets</th>
|
||||
<th><?= sortLink('routing_rule_matches', 'Routed') ?></th>
|
||||
<th class="d-none d-lg-table-cell"><?= sortLink('routing_rule_matched_at', 'Last') ?></th>
|
||||
<th class="d-none d-xl-table-cell"><?= sortLink('routing_rule_created_at', 'Added') ?></th>
|
||||
<th></th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<?php while ($row = mysqli_fetch_assoc($sql)) {
|
||||
$id = intval($row['routing_rule_id']);
|
||||
$match = (string) $row['routing_rule_match'];
|
||||
$domain = strpos($match, '@') === false;
|
||||
$edit = 'data-modal-size="lg" data-modal-url="modals/email_routing_rule/email_routing_rule.php?id=' . $id . '"';
|
||||
$note = trim((string) $row['routing_rule_note']);
|
||||
|
||||
// What it names that isn't there any more - skipped when it routes, and said here
|
||||
$gone = [];
|
||||
$client_ok = intval($row['routing_rule_client_id']) && $row['client_name'] !== null && $row['client_archived_at'] === null;
|
||||
if (intval($row['routing_rule_client_id']) && !$client_ok) {
|
||||
$gone[] = 'Client archived or deleted';
|
||||
}
|
||||
$contact_ok = intval($row['routing_rule_contact_id']) && $row['contact_name'] !== null && $row['contact_archived_at'] === null
|
||||
&& intval($row['contact_client_id']) === intval($row['routing_rule_client_id']);
|
||||
if (intval($row['routing_rule_contact_id']) && !$contact_ok) {
|
||||
$gone[] = 'Contact archived or deleted';
|
||||
}
|
||||
$sets = [];
|
||||
if (intval($row['routing_rule_category_id'])) {
|
||||
if ($row['category_name'] !== null && $row['category_archived_at'] === null) {
|
||||
$sets[] = '<span class="badge text-bg-light border fw-normal" title="Category"><i class="fas fa-fw fa-layer-group me-1 text-body-secondary"></i>' . escapeHtml($row['category_name']) . '</span>';
|
||||
} else {
|
||||
$gone[] = 'Category archived or deleted';
|
||||
}
|
||||
}
|
||||
if ((string) $row['routing_rule_priority'] !== '') {
|
||||
$sets[] = '<span class="badge text-bg-' . ticketPriorityColor($row['routing_rule_priority']) . '" title="Priority">' . escapeHtml($row['routing_rule_priority']) . '</span>';
|
||||
}
|
||||
if (intval($row['routing_rule_assigned_to'])) {
|
||||
if ($row['agent_name'] !== null && intval($row['agent_status']) === 1 && $row['agent_archived_at'] === null) {
|
||||
$sets[] = '<span class="badge text-bg-light border fw-normal" title="Assigned to"><i class="fas fa-fw fa-user-check me-1 text-body-secondary"></i>' . escapeHtml($row['agent_name']) . '</span>';
|
||||
} else {
|
||||
$gone[] = 'Agent disabled or archived';
|
||||
}
|
||||
}
|
||||
if (intval($row['routing_rule_ticket_template_id'])) {
|
||||
if ($row['ticket_template_name'] !== null && $row['ticket_template_archived_at'] === null) {
|
||||
$sets[] = '<span class="badge text-bg-light border fw-normal" title="Ticket template"><i class="fas fa-fw fa-life-ring me-1 text-body-secondary"></i>' . escapeHtml($row['ticket_template_name']) . '</span>';
|
||||
} else {
|
||||
$gone[] = 'Template archived or deleted';
|
||||
}
|
||||
}
|
||||
?>
|
||||
<tr data-routing-rule="<?= escapeHtml($match) ?>">
|
||||
<td class="ps-3 min-w-0">
|
||||
<a class="ajax-modal fw-semibold text-body text-break" href="#" <?= $edit ?>><?= escapeHtml($domain ? "@$match" : $match) ?></a>
|
||||
<div class="small text-body-secondary text-break">
|
||||
<?= $domain ? 'Everyone at this domain and its subdomains' : 'This address' ?><?php if ((string) $row['routing_rule_subject'] !== '') { ?>,
|
||||
with <strong class="text-body">“<?= escapeHtml($row['routing_rule_subject']) ?>”</strong> in the subject<?php } ?>
|
||||
</div>
|
||||
<?php if ($note !== '') { ?>
|
||||
<div class="small text-body-tertiary text-break"><i class="fas fa-fw fa-sticky-note me-1"></i><?= escapeHtml($note) ?></div>
|
||||
<?php } ?>
|
||||
</td>
|
||||
<td class="small min-w-0">
|
||||
<?php if ($client_ok) { ?>
|
||||
<a class="text-body fw-semibold text-break" href="/agent/client_overview.php?client_id=<?= intval($row['routing_rule_client_id']) ?>"><?= escapeHtml($row['client_name']) ?></a>
|
||||
<?php if ($contact_ok) { ?><div class="text-body-secondary text-break"><i class="fas fa-fw fa-user me-1"></i><?= escapeHtml($row['contact_name']) ?></div><?php } ?>
|
||||
<?php } else { ?>
|
||||
<span class="text-body-secondary" title="Its client is found from the sender, as for any email">Whoever it's from</span>
|
||||
<?php } ?>
|
||||
<div class="d-md-none mt-1 d-flex flex-wrap gap-1"><?= implode('', $sets) ?></div>
|
||||
</td>
|
||||
<td class="d-none d-md-table-cell">
|
||||
<div class="d-flex flex-wrap gap-1"><?= $sets ? implode('', $sets) : '<span class="small text-body-tertiary">-</span>' ?></div>
|
||||
<?php if ($gone) { ?>
|
||||
<div class="small text-danger mt-1" data-routing-gone><i class="fas fa-fw fa-exclamation-triangle me-1"></i><?= escapeHtml(implode(', ', $gone)) ?> - skipped until it's fixed</div>
|
||||
<?php } ?>
|
||||
</td>
|
||||
<td data-routing-count><?= number_format(intval($row['routing_rule_matches'])) ?> <span class="small text-body-secondary">ticket<?= intval($row['routing_rule_matches']) === 1 ? '' : 's' ?></span></td>
|
||||
<td class="d-none d-lg-table-cell small text-nowrap text-body-secondary"><?= $row['routing_rule_matched_at'] ? escapeHtml(timeAgo($row['routing_rule_matched_at'])) : 'Never' ?></td>
|
||||
<td class="d-none d-xl-table-cell small text-nowrap text-body-secondary">
|
||||
<?= escapeHtml(date('M j, Y', strtotime((string) $row['routing_rule_created_at']))) ?>
|
||||
<?php if ($row['creator_name'] !== null) { ?><div><?= escapeHtml($row['creator_name']) ?></div><?php } ?>
|
||||
</td>
|
||||
<td class="text-end pe-3">
|
||||
<div class="dropdown dropstart">
|
||||
<button class="btn btn-sm btn-light" title="More actions" type="button" data-bs-toggle="dropdown"><i class="fas fa-fw fa-ellipsis-v"></i></button>
|
||||
<div class="dropdown-menu">
|
||||
<a class="dropdown-item ajax-modal" href="#" <?= $edit ?>><i class="fas fa-fw fa-edit text-secondary me-2"></i>Edit</a>
|
||||
<div class="dropdown-divider"></div>
|
||||
<a class="dropdown-item text-danger confirm-link" href="post.php?delete_routing_rule=<?= $id ?>&csrf_token=<?= $_SESSION['csrf_token'] ?>" data-routing-delete>
|
||||
<i class="fas fa-fw fa-trash me-2"></i>Delete
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
<?php } ?>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<?php
|
||||
$empty_state = [
|
||||
'thing' => '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";
|
||||
?>
|
||||
</div>
|
||||
|
||||
<?php
|
||||
require_once "../includes/footer.php";
|
||||
@@ -103,6 +103,14 @@
|
||||
</a>
|
||||
</li>
|
||||
<?php } ?>
|
||||
<?php if ($config_module_enable_ticketing && mailRouteReady()) { ?>
|
||||
<li class="nav-item">
|
||||
<a href="/admin/email_routing_rules.php" class="nav-link <?= (basename($_SERVER['PHP_SELF']) == 'email_routing_rules.php' ? 'active' : '') ?>">
|
||||
<i class="nav-icon fas fa-route"></i>
|
||||
<p>Email Routing</p>
|
||||
</a>
|
||||
</li>
|
||||
<?php } ?>
|
||||
<?php if ($config_module_enable_ticketing && mailIgnoreReady()) { ?>
|
||||
<li class="nav-item">
|
||||
<a href="/admin/email_ignored_senders.php" class="nav-link <?= (basename($_SERVER['PHP_SELF']) == 'email_ignored_senders.php' ? 'active' : '') ?>">
|
||||
|
||||
227
admin/modals/email_routing_rule/email_routing_rule.php
Normal file
227
admin/modals/email_routing_rule/email_routing_rule.php
Normal file
@@ -0,0 +1,227 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* New Routing Rule, and Edit - 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 (functions/mail_route.php). One that
|
||||
* takes other clients' contacts' or domains' email says so here, and again on saving. Picking a client fetches its
|
||||
* contacts (agent/ajax.php get_client_contacts). Saved by add_routing_rule and edit_routing_rule
|
||||
* (admin/post/email_routing_rule.php).
|
||||
*/
|
||||
|
||||
require_once '../../includes/modal_header.php';
|
||||
|
||||
if (!mailRouteReady()) {
|
||||
echo json_encode(['error' => 'Email routing needs the database update.']);
|
||||
exit;
|
||||
}
|
||||
|
||||
$id = intval($_GET['id'] ?? 0);
|
||||
$row = $id ? mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT * FROM email_routing_rules WHERE routing_rule_id = $id")) : null;
|
||||
if ($id && !$row) {
|
||||
echo json_encode(['error' => "That routing rule isn't there any more."]);
|
||||
exit;
|
||||
}
|
||||
$match = (string) ($row['routing_rule_match'] ?? '');
|
||||
$client_id = intval($row['routing_rule_client_id'] ?? 0);
|
||||
$contact_id = intval($row['routing_rule_contact_id'] ?? 0);
|
||||
$category_id = intval($row['routing_rule_category_id'] ?? 0);
|
||||
$priority = (string) ($row['routing_rule_priority'] ?? '');
|
||||
$assigned_to = intval($row['routing_rule_assigned_to'] ?? 0);
|
||||
$template_id = intval($row['routing_rule_ticket_template_id'] ?? 0);
|
||||
$client_name = $client_id ? (string) (getFieldById('clients', $client_id, 'client_name') ?? '') : '';
|
||||
$reach = $row && $client_id ? mailRouteReachText(mailRouteReach($match, $client_id), $client_name) : '';
|
||||
$ignored = $row ? mailIgnoreFind(strpos($match, '@') === false ? "someone@$match" : $match) : null;
|
||||
|
||||
ob_start();
|
||||
|
||||
?>
|
||||
<div class="modal-header bg-dark">
|
||||
<h5 class="modal-title"><i class="fas fa-fw fa-route me-2"></i><?= $row ? 'Routing Rule' : 'New Routing Rule' ?></h5>
|
||||
<button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
|
||||
</div>
|
||||
<form action="post.php" method="post" autocomplete="off" data-routing-rule-form>
|
||||
<input type="hidden" name="csrf_token" value="<?= $_SESSION['csrf_token'] ?>">
|
||||
<?php if ($row) { ?><input type="hidden" name="routing_rule_id" value="<?= $id ?>"><?php } ?>
|
||||
<div class="modal-body">
|
||||
|
||||
<?php if ($ignored) { ?>
|
||||
<div class="alert alert-warning small py-2" data-routing-ignored><i class="fas fa-fw fa-eye-slash me-1"></i>Email from <?= escapeHtml($ignored['ignored_sender_match']) ?> is set aside by <a href="email_ignored_senders.php" class="alert-link">Ignored Senders</a> before any rule - this one never routes it.</div>
|
||||
<?php } ?>
|
||||
<?php if ($reach !== '') { ?>
|
||||
<div class="alert alert-warning small py-2" data-routing-reach><i class="fas fa-fw fa-exclamation-triangle me-1"></i><?= $reach ?></div>
|
||||
<?php } ?>
|
||||
|
||||
<h6 class="text-body-secondary small text-uppercase fw-semibold mb-2">Email it takes</h6>
|
||||
<div class="row g-3 mb-4">
|
||||
<div class="col-md-6">
|
||||
<label class="form-label" for="routingRuleMatch">Address or domain <strong class="text-danger">*</strong></label>
|
||||
<div class="input-group">
|
||||
<span class="input-group-text"><i class="fas fa-fw fa-at"></i></span>
|
||||
<input type="text" class="form-control" id="routingRuleMatch" name="routing_rule_match" maxlength="255" required
|
||||
value="<?= escapeHtml($match) ?>" placeholder="alerts@vendor.example, or vendor.example" <?= $row ? '' : 'autofocus' ?>>
|
||||
</div>
|
||||
<div class="form-text">A domain takes everyone there, and at its subdomains.</div>
|
||||
</div>
|
||||
<div class="col-md-6">
|
||||
<label class="form-label" for="routingRuleSubject">Subject has</label>
|
||||
<div class="input-group">
|
||||
<span class="input-group-text"><i class="fas fa-fw fa-heading"></i></span>
|
||||
<input type="text" class="form-control" id="routingRuleSubject" name="routing_rule_subject" maxlength="255"
|
||||
value="<?= escapeHtml($row['routing_rule_subject'] ?? '') ?>" placeholder="Backup failed">
|
||||
</div>
|
||||
<div class="form-text">Words in its subject, in any case - or leave it empty for any subject.</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<h6 class="text-body-secondary small text-uppercase fw-semibold mb-2">The ticket it raises</h6>
|
||||
<div class="row g-3">
|
||||
<div class="col-md-6">
|
||||
<label class="form-label">Client</label>
|
||||
<div class="input-group">
|
||||
<span class="input-group-text"><i class="fas fa-fw fa-user-friends"></i></span>
|
||||
<select class="form-select select2" name="routing_rule_client_id" data-routing-client>
|
||||
<option value="0">- Whoever it's from -</option>
|
||||
<?php
|
||||
$sql_clients = mysqli_query($mysqli, "SELECT client_id, client_name, client_abbreviation FROM clients WHERE (client_archived_at IS NULL OR client_id = $client_id)" . clientNotLeadSql($client_id) . " ORDER BY client_name ASC");
|
||||
while ($client = mysqli_fetch_assoc($sql_clients)) { ?>
|
||||
<option value="<?= intval($client['client_id']) ?>" <?= intval($client['client_id']) === $client_id ? 'selected' : '' ?><?= selectOptionClient($client['client_id'], $client['client_name'], $client['client_abbreviation'] ?? '') ?>><?= escapeHtml($client['client_name']) ?></option>
|
||||
<?php } ?>
|
||||
</select>
|
||||
</div>
|
||||
<div class="form-text">Over the sender's own contact or domain. Left as it is, the client is found from who it's from.</div>
|
||||
</div>
|
||||
<div class="col-md-6">
|
||||
<label class="form-label">Contact</label>
|
||||
<div class="input-group">
|
||||
<span class="input-group-text"><i class="fas fa-fw fa-user"></i></span>
|
||||
<select class="form-select select2" name="routing_rule_contact_id" data-routing-contact <?= $client_id ? '' : 'disabled' ?>>
|
||||
<option value="0"><?= $client_id ? '- The sender, if they\'re one -' : '- Pick a client first -' ?></option>
|
||||
<?php
|
||||
if ($client_id) {
|
||||
$sql_contacts = mysqli_query($mysqli, "SELECT contact_id, contact_name, contact_title, contact_photo FROM contacts WHERE contact_client_id = $client_id
|
||||
AND (contact_archived_at IS NULL OR contact_id = $contact_id) ORDER BY contact_primary DESC, contact_technical DESC, contact_name ASC");
|
||||
while ($contact = mysqli_fetch_assoc($sql_contacts)) { ?>
|
||||
<option value="<?= intval($contact['contact_id']) ?>" <?= intval($contact['contact_id']) === $contact_id ? 'selected' : '' ?><?= selectOptionContact($client_id, $contact['contact_name'], $contact['contact_photo'] ?? '', $contact['contact_title'] ?? '', $contact['contact_id']) ?>><?= escapeHtml($contact['contact_name']) ?></option>
|
||||
<?php }
|
||||
} ?>
|
||||
</select>
|
||||
</div>
|
||||
<div class="form-text">Only they are emailed about it. A sender who isn't the contact isn't answered or copied in.</div>
|
||||
</div>
|
||||
<div class="col-md-6">
|
||||
<label class="form-label">Category</label>
|
||||
<div class="input-group">
|
||||
<span class="input-group-text"><i class="fas fa-fw fa-layer-group"></i></span>
|
||||
<select class="form-select select2" name="routing_rule_category_id">
|
||||
<option value="0">- Leave as it is -</option>
|
||||
<?= categoryOptionsHtml('Ticket', $category_id ?: null) ?>
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
<div class="col-md-6">
|
||||
<label class="form-label">Priority</label>
|
||||
<div class="input-group">
|
||||
<span class="input-group-text"><i class="fas fa-fw fa-thermometer-half"></i></span>
|
||||
<select class="form-select select2" name="routing_rule_priority">
|
||||
<option value="">- Leave as it is -</option>
|
||||
<?php foreach (TICKET_PRIORITIES as $level) { ?>
|
||||
<option value="<?= $level ?>" <?= $priority === $level ? 'selected' : '' ?><?= selectOptionPriority($level) ?>><?= $level ?></option>
|
||||
<?php } ?>
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
<div class="col-md-6">
|
||||
<label class="form-label">Assign to</label>
|
||||
<div class="input-group">
|
||||
<span class="input-group-text"><i class="fas fa-fw fa-user-check"></i></span>
|
||||
<select class="form-select select2" name="routing_rule_assigned_to">
|
||||
<option value="0">- Leave as it is -</option>
|
||||
<?php
|
||||
$sql_agents = mysqli_query($mysqli, "SELECT user_id, user_name, user_avatar FROM users WHERE user_type = 1" . serviceAccountsOutSql() . " AND user_status = 1 AND (user_archived_at IS NULL OR user_id = $assigned_to) ORDER BY user_name ASC");
|
||||
while ($agent = mysqli_fetch_assoc($sql_agents)) { ?>
|
||||
<option value="<?= intval($agent['user_id']) ?>" <?= intval($agent['user_id']) === $assigned_to ? 'selected' : '' ?><?= selectOptionUser($agent['user_id'], $agent['user_name'], $agent['user_avatar'] ?? '') ?>><?= escapeHtml($agent['user_name']) ?></option>
|
||||
<?php } ?>
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
<div class="col-md-6">
|
||||
<label class="form-label">Ticket template</label>
|
||||
<div class="input-group">
|
||||
<span class="input-group-text"><i class="fas fa-fw fa-life-ring"></i></span>
|
||||
<select class="form-select select2" name="routing_rule_ticket_template_id">
|
||||
<option value="0">- None -</option>
|
||||
<?php
|
||||
$sql_templates = mysqli_query($mysqli, "SELECT ticket_template_id, ticket_template_name FROM ticket_templates WHERE ticket_template_archived_at IS NULL OR ticket_template_id = $template_id ORDER BY ticket_template_name ASC");
|
||||
while ($template = mysqli_fetch_assoc($sql_templates)) { ?>
|
||||
<option value="<?= intval($template['ticket_template_id']) ?>" <?= intval($template['ticket_template_id']) === $template_id ? 'selected' : '' ?>><?= escapeHtml($template['ticket_template_name']) ?></option>
|
||||
<?php } ?>
|
||||
</select>
|
||||
</div>
|
||||
<div class="form-text">Its tasks, tags and due time - and its category, priority and agent, where the rule leaves them.</div>
|
||||
</div>
|
||||
<div class="col-12">
|
||||
<label class="form-label" for="routingRuleNote">Why</label>
|
||||
<div class="input-group">
|
||||
<span class="input-group-text"><i class="fas fa-fw fa-sticky-note"></i></span>
|
||||
<input type="text" class="form-control" id="routingRuleNote" name="routing_rule_note" maxlength="255"
|
||||
value="<?= escapeHtml($row['routing_rule_note'] ?? '') ?>" placeholder="Backup alerts for Kestrel's servers">
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
</div>
|
||||
<div class="modal-footer">
|
||||
<button type="submit" name="<?= $row ? 'edit_routing_rule' : 'add_routing_rule' ?>" class="btn btn-primary fw-bold"><i class="fas fa-check me-2"></i><?= $row ? 'Save' : 'Add Rule' ?></button>
|
||||
<button type="button" class="btn btn-light" data-bs-dismiss="modal"><i class="fas fa-times me-2"></i>Cancel</button>
|
||||
</div>
|
||||
</form>
|
||||
|
||||
<script>
|
||||
(function () {
|
||||
// The contacts of the client picked - fetched for it, the list emptied for none
|
||||
const form = document.querySelector('[data-routing-rule-form]');
|
||||
const client = form && form.querySelector('[data-routing-client]');
|
||||
const contact = form && form.querySelector('[data-routing-contact]');
|
||||
if (!client || !contact) {
|
||||
return;
|
||||
}
|
||||
let asked = 0;
|
||||
client.addEventListener('change', function () {
|
||||
const mine = ++asked;
|
||||
contact.innerHTML = '';
|
||||
contact.add(new Option(client.value !== '0' ? "- The sender, if they're one -" : '- Pick a client first -', '0'));
|
||||
contact.value = '0';
|
||||
contact.disabled = client.value === '0';
|
||||
if (client.value === '0') {
|
||||
return;
|
||||
}
|
||||
itflowGet('/agent/ajax.php', {get_client_contacts: 'true', client_id: client.value}, function (data) {
|
||||
if (mine !== asked) {
|
||||
return;
|
||||
}
|
||||
let contacts = [];
|
||||
try {
|
||||
contacts = JSON.parse(data).contacts || [];
|
||||
} catch (e) {
|
||||
contacts = [];
|
||||
}
|
||||
contacts.forEach(function (row) {
|
||||
const option = new Option(row.contact_name, row.contact_id);
|
||||
option.dataset.description = row.contact_title || '';
|
||||
if (row.contact_photo_url) {
|
||||
option.dataset.image = row.contact_photo_url;
|
||||
} else {
|
||||
option.dataset.initials = row.contact_initials;
|
||||
option.dataset.shape = 'circle';
|
||||
option.dataset.tone = row.contact_tone || 'secondary';
|
||||
option.dataset.soft = '1';
|
||||
}
|
||||
contact.add(option);
|
||||
});
|
||||
});
|
||||
});
|
||||
})();
|
||||
</script>
|
||||
|
||||
<?php
|
||||
require_once '../../../includes/modal_footer.php';
|
||||
126
admin/post/email_routing_rule.php
Normal file
126
admin/post/email_routing_rule.php
Normal file
@@ -0,0 +1,126 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* Admin > Email Routing (admin/email_routing_rules.php, functions/mail_route.php): add_routing_rule and edit_routing_rule
|
||||
* keep an address or a domain, with words its subject has, and where its new tickets by email go - a client and a
|
||||
* contact, a category, a priority, an agent and a ticket template - and why. An address or domain that isn't one, a rule
|
||||
* there already for it and those words, or one that sets nothing, comes back saying so. Each thing it names is checked
|
||||
* against what exists: the client's own contact, an active agent, a template not archived. One that takes other
|
||||
* clients' contacts' or domains' email, or that Ignored Senders sets aside first, is saved, saying so.
|
||||
* delete_routing_rule deletes it.
|
||||
*/
|
||||
|
||||
defined('FROM_POST_HANDLER') || die("Direct file access is not allowed");
|
||||
|
||||
if (isset($_POST['add_routing_rule']) || isset($_POST['edit_routing_rule'])) {
|
||||
|
||||
validateCSRFToken();
|
||||
|
||||
if (!mailRouteReady()) {
|
||||
flashAlert("Email routing needs the database update", 'error');
|
||||
redirect('email_routing_rules.php');
|
||||
}
|
||||
|
||||
$editing = isset($_POST['edit_routing_rule']);
|
||||
$id = $editing ? intval($_POST['routing_rule_id'] ?? 0) : 0;
|
||||
if ($editing && !mysqli_num_rows(mysqli_query($mysqli, "SELECT 1 FROM email_routing_rules WHERE routing_rule_id = $id"))) {
|
||||
flashAlert("That routing rule isn't there any more", 'error');
|
||||
redirect('email_routing_rules.php');
|
||||
}
|
||||
|
||||
$rule = mailIgnoreClean($_POST['routing_rule_match'] ?? '');
|
||||
if (!$rule) {
|
||||
flashAlert("<strong>" . escapeHtml(trim((string) ($_POST['routing_rule_match'] ?? ''))) . "</strong> isn't an email address or a domain", 'error');
|
||||
redirect();
|
||||
}
|
||||
$subject = mailRouteSubjectClean($_POST['routing_rule_subject'] ?? '');
|
||||
$note = mb_substr(trim((string) ($_POST['routing_rule_note'] ?? '')), 0, 255);
|
||||
|
||||
// What it sets - each one that exists, else left as it is
|
||||
$client_id = intval($_POST['routing_rule_client_id'] ?? 0);
|
||||
$client_name = '';
|
||||
if ($client_id) {
|
||||
$client = mysqli_fetch_row(mysqli_query($mysqli, "SELECT client_name FROM clients WHERE client_id = $client_id AND client_archived_at IS NULL LIMIT 1"));
|
||||
$client_id = $client ? $client_id : 0;
|
||||
$client_name = $client ? (string) $client[0] : '';
|
||||
}
|
||||
$contact_id = $client_id ? intval($_POST['routing_rule_contact_id'] ?? 0) : 0;
|
||||
if ($contact_id && !mysqli_num_rows(mysqli_query($mysqli, "SELECT 1 FROM contacts WHERE contact_id = $contact_id AND contact_client_id = $client_id AND contact_archived_at IS NULL LIMIT 1"))) {
|
||||
$contact_id = 0;
|
||||
}
|
||||
$category_id = ticketCategoryId($_POST['routing_rule_category_id'] ?? 0);
|
||||
$priority = in_array($_POST['routing_rule_priority'] ?? '', TICKET_PRIORITIES, true) ? (string) $_POST['routing_rule_priority'] : '';
|
||||
$assigned_to = ticketAgentId($_POST['routing_rule_assigned_to'] ?? 0);
|
||||
$template_id = intval($_POST['routing_rule_ticket_template_id'] ?? 0);
|
||||
if ($template_id) {
|
||||
$template = ticketTemplateRow($template_id);
|
||||
$template_id = $template && empty($template['ticket_template_archived_at']) ? $template_id : 0;
|
||||
}
|
||||
|
||||
if (!$client_id && !$category_id && $priority === '' && !$assigned_to && !$template_id) {
|
||||
flashAlert("Pick what the rule sets - a client, a category, a priority, an agent or a template", 'error');
|
||||
redirect();
|
||||
}
|
||||
|
||||
$match_sql = escapeSql($rule['match']);
|
||||
$subject_sql = escapeSql($subject);
|
||||
if (mysqli_num_rows(mysqli_query($mysqli, "SELECT 1 FROM email_routing_rules WHERE routing_rule_match = '$match_sql' AND routing_rule_subject = '$subject_sql' AND routing_rule_id <> $id"))) {
|
||||
flashAlert("There's a rule for <strong>" . escapeHtml($rule['match']) . "</strong>" . ($subject !== '' ? " with “" . escapeHtml($subject) . "” in the subject" : '') . " already", 'error');
|
||||
redirect();
|
||||
}
|
||||
|
||||
$set = "routing_rule_match = '$match_sql', routing_rule_subject = '$subject_sql', routing_rule_client_id = $client_id, routing_rule_contact_id = $contact_id,
|
||||
routing_rule_category_id = $category_id, routing_rule_priority = '" . escapeSql($priority) . "', routing_rule_assigned_to = $assigned_to,
|
||||
routing_rule_ticket_template_id = $template_id, routing_rule_note = '" . escapeSql($note) . "'";
|
||||
if ($editing) {
|
||||
mysqli_query($mysqli, "UPDATE email_routing_rules SET $set WHERE routing_rule_id = $id");
|
||||
} else {
|
||||
mysqli_query($mysqli, "INSERT INTO email_routing_rules SET $set, routing_rule_created_by = " . intval($session_user_id));
|
||||
$id = intval(mysqli_insert_id($mysqli));
|
||||
}
|
||||
mailRouteRules(true);
|
||||
|
||||
$saved = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT * FROM email_routing_rules WHERE routing_rule_id = $id"));
|
||||
$name = mailRouteName($saved);
|
||||
$summary = mailRouteSummary(mailRouteTargets($saved));
|
||||
|
||||
// Said on saving: other clients' email it takes, and an ignored sender that takes it first
|
||||
$warnings = [];
|
||||
if ($client_id) {
|
||||
$reach = mailRouteReachText(mailRouteReach($rule['match'], $client_id), $client_name);
|
||||
if ($reach !== '') {
|
||||
$warnings[] = $reach;
|
||||
}
|
||||
}
|
||||
$ignored = mailIgnoreFind($rule['kind'] === 'domain' ? "someone@" . $rule['match'] : $rule['match']);
|
||||
if ($ignored) {
|
||||
$warnings[] = 'Ignored Senders sets aside email from ' . escapeHtml($ignored['ignored_sender_match']) . ' first, so this rule never routes it.';
|
||||
}
|
||||
|
||||
logAudit("Settings", $editing ? "Edit" : "Create", escapeSql("$session_name " . ($editing ? 'changed' : 'added') . " the email routing rule for $name: $summary"));
|
||||
flashAlert("New tickets by email from <strong>" . escapeHtml($name) . "</strong>: " . escapeHtml($summary) . ($warnings ? ' - ' . implode(' ', $warnings) : ''), $warnings ? 'warning' : 'success');
|
||||
|
||||
redirect();
|
||||
|
||||
}
|
||||
|
||||
if (isset($_GET['delete_routing_rule'])) {
|
||||
|
||||
validateCSRFToken();
|
||||
|
||||
$id = intval($_GET['delete_routing_rule']);
|
||||
$row = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT * FROM email_routing_rules WHERE routing_rule_id = $id"));
|
||||
if (!$row) {
|
||||
flashAlert("That routing rule isn't there any more", 'error');
|
||||
redirect();
|
||||
}
|
||||
|
||||
mysqli_query($mysqli, "DELETE FROM email_routing_rules WHERE routing_rule_id = $id");
|
||||
$name = mailRouteName($row);
|
||||
|
||||
logAudit("Settings", "Delete", escapeSql("$session_name deleted the email routing rule for $name"));
|
||||
flashAlert("Email from <strong>" . escapeHtml($name) . "</strong> isn't routed any more", 'error');
|
||||
|
||||
redirect();
|
||||
|
||||
}
|
||||
@@ -46,6 +46,13 @@ echo settingsPageStart('ticket');
|
||||
<span class="small text-body-secondary">Addresses and domains whose email is set aside - no ticket, and no answer.</span>
|
||||
</div>
|
||||
<?php } ?>
|
||||
<?php if (mailRouteReady()) {
|
||||
$route_count = count(mailRouteRules()); ?>
|
||||
<div class="d-flex flex-wrap align-items-center gap-2 mt-2" data-routing-rules-link>
|
||||
<a class="btn btn-sm btn-outline-secondary" href="email_routing_rules.php"><i class="fas fa-route me-2"></i>Email Routing<?= $route_count ? " ($route_count)" : '' ?></a>
|
||||
<span class="small text-body-secondary">Send an address's or a domain's new tickets to a client, with a category, priority, agent or template - alerts from a vendor's system, say.</span>
|
||||
</div>
|
||||
<?php } ?>
|
||||
</div>
|
||||
<?= settingsSectionEnd() ?>
|
||||
|
||||
|
||||
@@ -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 <br>
|
||||
$message = nl2br($message);
|
||||
// Wrap final formatted message
|
||||
$from_line = $contact_email_raw !== '' ? "<b>" . escapeHtml($contact_name_raw) . "</b> <" . escapeHtml($contact_email_raw) . ">" : '<b>No sender address</b>';
|
||||
$from_line = $from_email_raw !== '' ? "<b>" . escapeHtml($from_name_raw) . "</b> <" . escapeHtml($from_email_raw) . ">" : '<b>No sender address</b>';
|
||||
$from_line .= $via !== '' ? ' - sent by ' . escapeHtml($via) : '';
|
||||
$from_line .= $forward ? ' - forwarded by ' . escapeHtml($forward['agent']['user_name']) : '';
|
||||
$message = "<i>Email from: $from_line at $date:-</i> <br><br><div style='line-height:1.5;'>$message</div>";
|
||||
@@ -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)));
|
||||
}
|
||||
|
||||
|
||||
|
||||
29
db.sql
29
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`
|
||||
--
|
||||
|
||||
@@ -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';
|
||||
|
||||
257
functions/mail_route.php
Normal file
257
functions/mail_route.php
Normal file
@@ -0,0 +1,257 @@
|
||||
<?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']) {
|
||||
$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.' : '';
|
||||
}
|
||||
@@ -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.
|
||||
|
||||
Reference in New Issue
Block a user