mirror of
https://github.com/itflow-org/itflow
synced 2026-12-02 00:59:03 +00:00
Mail review stage 7b: email the ticket mailbox couldn't take is kept in Tickets > Unprocessed Email and moved to the ITFlow folder instead of left flagged in the inbox (database 4.3.2), where agents view it, make a ticket at a client for a contact or a new contact, add it to a ticket with the sender as a CC if wanted, try it again, dismiss it or download it, the email parser making the ticket or reply on its next run; the tickets list says how many are waiting; sorted ones are kept 30 days and unsorted 90; 26.12.3 changelog
This commit is contained in:
@@ -6,7 +6,7 @@ This file documents all notable changes made to ITFlow.
|
||||
|
||||
### Upgrading to 26.12.3
|
||||
|
||||
Update from Maintenance > Update as usual - this release has ten database changes: 4.2.2 adds a table for passkeys and a setting to turn them on or off, 4.2.3 lets a document keep the Markdown it was written in, 4.2.4 lets a ticket keep its pictures as files, 4.2.5 adds identity providers, 4.2.6 keeps each ticket's email conversation together, 4.2.7 lets a reply from a CC say who sent it, 4.2.8 renames the watchers table for CCs, 4.2.9 lets the mail queue go at a pace your mail host takes, 4.3.0 lets contacts unsubscribe from bulk email, and 4.3.1 encrypts the mail passwords and tokens. The client portal's Microsoft 365 single sign-on becomes the first identity provider, for client contacts, and keeps its redirect address, so nothing changes in Microsoft Entra. Nothing else is required: passkeys are on, and no one has one until they add it. Pictures already inside tickets move to files in the background afterwards - the new Ticket Pictures job in Maintenance > Cron does a batch a minute, so an install with years of emailed screenshots may take a while, and tickets work as usual meanwhile. A passkey is made for your ITFlow's address (the one in config.php) and only works there, over HTTPS - if you move ITFlow to a new address, everyone adds theirs again. Watchers are called CCs now. Emails about a ticket go to its contact with the CCs copied in, rather than one each - Admin > Settings > Tickets has the switch, under Emails about a ticket.
|
||||
Update from Maintenance > Update as usual - this release has eleven database changes: 4.2.2 adds a table for passkeys and a setting to turn them on or off, 4.2.3 lets a document keep the Markdown it was written in, 4.2.4 lets a ticket keep its pictures as files, 4.2.5 adds identity providers, 4.2.6 keeps each ticket's email conversation together, 4.2.7 lets a reply from a CC say who sent it, 4.2.8 renames the watchers table for CCs, 4.2.9 lets the mail queue go at a pace your mail host takes, 4.3.0 lets contacts unsubscribe from bulk email, 4.3.1 encrypts the mail passwords and tokens, and 4.3.2 keeps the email the ticket mailbox couldn't take, for your team to sort. The client portal's Microsoft 365 single sign-on becomes the first identity provider, for client contacts, and keeps its redirect address, so nothing changes in Microsoft Entra. Nothing else is required: passkeys are on, and no one has one until they add it. Pictures already inside tickets move to files in the background afterwards - the new Ticket Pictures job in Maintenance > Cron does a batch a minute, so an install with years of emailed screenshots may take a while, and tickets work as usual meanwhile. A passkey is made for your ITFlow's address (the one in config.php) and only works there, over HTTPS - if you move ITFlow to a new address, everyone adds theirs again. Watchers are called CCs now. Emails about a ticket go to its contact with the CCs copied in, rather than one each - Admin > Settings > Tickets has the switch, under Emails about a ticket. On nginx, where ITFlow's .htaccess files aren't read, add `location ^~ /uploads/mail_unprocessed/ { deny all; }` beside the other private folders - it holds copies of the email kept for Unprocessed Email.
|
||||
|
||||
### Security
|
||||
|
||||
@@ -79,6 +79,8 @@ Update from Maintenance > Update as usual - this release has ten database change
|
||||
- Email-to-ticket and website forms: a contact form's email comes from the website (wordpress@, a no-reply address) with the visitor in Reply-To. The visitor is the one answered now, and the ticket's CC, so your replies reach them - the website was, and the visitor never heard back. It's the ticket of the client whose domain the website is on, else a ticket with no client, and the website isn't made a contact. An email whose Reply-To is someone else at the same domain is taken as theirs. Anyone else's email is from them, whatever its Reply-To says.
|
||||
- A client's reply on a ticket nobody is assigned goes to the new-ticket address in Admin > Settings > Tickets, or to the admins in the bell when there isn't one. It reopened the ticket, but nobody was told.
|
||||
- An agent who answers the client's email from their own mailbox - reply to all, with the support address copied in - has it on the ticket as their reply, not an internal note: the client has it, so it shows as emailed to them and counts as the ticket's first response, and the ticket is theirs when nobody had it, as a reply from the ticket does. Nothing more is sent. An email only to the support address is still their internal note.
|
||||
- Unprocessed Email: email the ticket mailbox couldn't make a ticket from - someone who isn't a contact, at a domain no client has, while unknown senders aren't let in, or one that failed - is kept in Tickets > Unprocessed Email (in the menu beside New Ticket) and moved to the mailbox's ITFlow folder, where it used to stay in the inbox flagged and unread for someone to find. The tickets list says how many are waiting. Each shows who it is from, its subject, a line of what it says and why it wasn't taken.
|
||||
- From Unprocessed Email an email can be opened (as text - nothing in it loads), made a ticket at the client you pick - for one of their contacts, or with the sender made a contact there first - added to a ticket, with the sender made a CC on it if you like, tried again (after making them a contact, say), dismissed, or downloaded as a .eml file. Try Again and Dismiss also work on several at once. The ticket or reply is made within a minute, as any email is, attachments and all, and the email shows which ticket it went on. Sorted and dismissed email is kept 30 days, and email nobody sorts 90.
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
@@ -160,6 +162,7 @@ Update from Maintenance > Update as usual - this release has ten database change
|
||||
- Mail review stage 5: cron/ticket_email_parser.php - an email with no From address is from '' rather than itflow-guest@example.com: addReply() takes it as a stranger's ($no_sender) and addTicket() makes no CC and sends no answer. contactBounceClearEmail() runs after ticketMailSenderCheck(), and only when it didn't fail. ticketMailReplyTo() (functions/ticket_mail_auto.php) reads Reply-To: one at From's domain is taken as the sender ($via, shown as "sent by"); else, when ticketMailSystemSender() says From is a no-reply or website address (TICKET_MAIL_SYSTEM_SENDERS) or there is none, it is $answer - steps 4 to 6 raise the ticket with contact_id 0 for it at the From contact's or domain's client, or none. addTicket() makes the sender a CC whenever there is no contact (was: no client), answers anyone not a contact through ticketMailCreated()'s new $stranger (no Subject row and no button - its last parameter was the subject), and skips ticketMailColleaguesNew() for a forged ticket or one with no contact. ticketMailSenderContact() (functions/ticket_mail_thread.php) picks the contact for steps 3 and 4 by the From domain's client, then the latest ticket, then contact_id, and ticketMailSenderContactNote() notes the others; Try an Email uses it. An agent's email whose To or Cc has the ticket's contact, a CC or another of the client's contacts (ticketMailClientAddresses()) is a Public reply - addReplyAgentToClient() fills ticket_reply_emailed_to, calls setTicketFirstResponse(), assigns it through ticketChangeAssignee() under ticketReplyAssigns() or moves New to Open, and fires reply_reply_agent_public. ticketNotifyOwner() (functions/ticket.php) puts a bell notice with the assigned agent or the admins (appNotifyUsers(), functions/logging.php) - for bounces and closed-ticket replies, where appNotify() told every agent - and ticketMailAssigneeReplied() goes to ticketMailUnassignedReplied() on a ticket nobody has: the new-ticket address, else that notice. That covers portal and text replies too.
|
||||
- Mail review stage 6: database 4.3.0 adds contacts.contact_unsubscribed_at and settings.config_mail_unsubscribe_secret. functions/contact_unsubscribe.php signs each contact's link with an HMAC of the contact id and address (contactUnsubscribeToken(), the key made on first use), and contactUnsubscribeSet() takes every contact with the address out or back in; contactUnsubscribedAddresses() is checked at send time, so a contact added since at another client is out too. guest/unsubscribe.php asks on GET, acts on its form's POST, and takes RFC 8058's List-Unsubscribe=One-Click POST with no page. emailBulkRecipients() (functions/email.php) builds the recipients from contact rows - the bounced, the unsubscribed, no address and the same address left out and counted - each with an unsubscribe link (emailHtml()'s new unsubscribe field) and its own List-Unsubscribe and List-Unsubscribe-Post headers (emailQueue() recipients' headers, let through by MAIL_QUEUE_HEADERS); emailBulkPost() now takes contact rows and converts Send at with timezoneFromView(). sendQueueEmail() sets the envelope sender per email - setFrom(..., false) with Sender reset, as PHPMailer's setFrom() kept the first email's From as Sender for the whole kept-alive connection - and for email_bulk passes mailQueueReturnPath(), the read mailbox when ticket parsing is on, the provider isn't Graph sending, the SMTP username is empty or that mailbox, and the domains align; a MAIL FROM refusal sends it again from the From address and sets mailQueueReturnPathRefused() for the run. mailQueueBouncesTo() tells the Email window.
|
||||
- Mail review stage 7a: database 4.3.1 widens config_smtp_password, config_imap_password and config_mail_oauth_client_secret to varchar(500) and encrypts what is saved. functions/mail_secret.php seals MAIL_SECRET_COLUMNS (the two passwords, the OAuth secret, refresh and access tokens, and config_mail_graph_token) with secretSeal($plain, 'mail') as RMM and identity provider secrets are - but keeps a value as typed when there is no key, as mail would otherwise stop. mailSecretOpen() reads an unsealed value as it is, so nothing breaks before it is sealed: load_global_settings.php, cron/mail_queue.php, cron/nightly_tasks.php and mailGraphToken() open them; settingsWrite() seals secret-kind mail columns; every token write (the parser's two refreshes, persistMailOauthTokens(), the Microsoft callback, the Test OAuth refresh, mailGraphToken()) goes through mailSecretSql(). mailSecretsSealAll() runs in the update and nightly; mailSecretProblem() is the Admin > Settings > Mail warning. Remote pictures: ticketHtmlForAgents($purifier, $html) purifies and then ticketRemoteImagesHold() moves an http(s) or // img src to data-remote-src (a blank GIF and .itflow-remote-image in its place) and a style with a remote url() to data-remote-style - in agent/ticket.php, the quick look and ticketWorkOrderHtml(); ticketRemoteImagesNote() and js/app.js show the note and put them back. login.php drops the SMTP host, port, encryption, username and password it loaded but never used.
|
||||
- Mail review stage 7b: database 4.3.2 adds email_unprocessed. functions/mail_unprocessed.php keeps an email the parser couldn't take - mailUnprocessedKeep($raw, $meta, $reason) writes its MIME to uploads/mail_unprocessed (denied to the web, as uploads/backups) and a row, one per Message-ID - and mailUnprocessedDecide() records an agent's ticket, reply, retry or dismiss (agent/email_unprocessed.php, agent/post/email_unprocessed.php). cron/ticket_email_parser.php appends mailUnprocessedAsked() to the run as MailUnprocessedMessage (functions/mail_unprocessed_message.php), a FileMessage whose move() is mailUnprocessedDone() with the ticket it went on and whose flags do nothing: a ticket or reply ask skips steps 1 to 6 for addTicket() at the chosen contact or client (or a new contact, as the domain match makes one) or addReply() on the chosen ticket (the sender added through ticketAddCcs() first, if asked); a retry goes the usual way. mailUnprocessedLeave() takes the unprocessed and exception branches - kept, then marked seen and moved to the ITFlow folder; flagged and unread as before when it can't be kept; an ask that fails waits again with the reason. mailUnprocessedCleanup() runs nightly.
|
||||
|
||||
## [26.12.2]
|
||||
|
||||
|
||||
41
admin/database_updates/4.3.2.php
Normal file
41
admin/database_updates/4.3.2.php
Normal file
@@ -0,0 +1,41 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* ITFlow - Database update to version 4.3.2 (from 4.3.1)
|
||||
* Included by admin/database_updates.php - do not access directly
|
||||
*
|
||||
* Email the ticket mailbox couldn't take - from someone who isn't a contact, at a domain no client has, with
|
||||
* unknown senders off, or one that failed - is kept for agents to sort (functions/mail_unprocessed.php), where it
|
||||
* was left flagged in the mailbox, out of sight:
|
||||
* email_unprocessed - the email (its file under uploads/mail_unprocessed/), why it wasn't taken, what an agent
|
||||
* asked for (a ticket, a reply on one, another try, or dismissed) and what came of it
|
||||
*
|
||||
* 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_unprocessed` (
|
||||
`email_unprocessed_id` int(11) NOT NULL AUTO_INCREMENT,
|
||||
`email_unprocessed_message_id` varchar(255) NOT NULL DEFAULT '',
|
||||
`email_unprocessed_from_email` varchar(255) NOT NULL DEFAULT '',
|
||||
`email_unprocessed_from_name` varchar(255) NOT NULL DEFAULT '',
|
||||
`email_unprocessed_subject` varchar(500) NOT NULL DEFAULT '',
|
||||
`email_unprocessed_preview` varchar(500) NOT NULL DEFAULT '',
|
||||
`email_unprocessed_received_at` datetime DEFAULT NULL,
|
||||
`email_unprocessed_reason` varchar(500) NOT NULL DEFAULT '',
|
||||
`email_unprocessed_file` varchar(255) NOT NULL DEFAULT '',
|
||||
`email_unprocessed_action` varchar(20) NOT NULL DEFAULT '',
|
||||
`email_unprocessed_action_client_id` int(11) NOT NULL DEFAULT 0,
|
||||
`email_unprocessed_action_contact_id` int(11) NOT NULL DEFAULT 0,
|
||||
`email_unprocessed_action_ticket_id` int(11) NOT NULL DEFAULT 0,
|
||||
`email_unprocessed_action_add` tinyint(1) NOT NULL DEFAULT 0,
|
||||
`email_unprocessed_action_by` int(11) NOT NULL DEFAULT 0,
|
||||
`email_unprocessed_action_at` datetime DEFAULT NULL,
|
||||
`email_unprocessed_done_at` datetime DEFAULT NULL,
|
||||
`email_unprocessed_ticket_id` int(11) NOT NULL DEFAULT 0,
|
||||
`email_unprocessed_created_at` datetime NOT NULL DEFAULT current_timestamp(),
|
||||
PRIMARY KEY (`email_unprocessed_id`),
|
||||
KEY `email_unprocessed_done_at` (`email_unprocessed_done_at`, `email_unprocessed_action`),
|
||||
KEY `email_unprocessed_message_id` (`email_unprocessed_message_id`)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci");
|
||||
@@ -42,7 +42,7 @@ ob_start();
|
||||
</div>
|
||||
<form autocomplete="off" id="ticketMailTryForm">
|
||||
<div class="modal-body">
|
||||
<p class="small text-body-secondary">What the support mailbox would do with an email - a reply on a ticket, a new ticket and for whom, or left in the mailbox - and why. Nothing is made or sent.</p>
|
||||
<p class="small text-body-secondary">What the support mailbox would do with an email - a reply on a ticket, a new ticket and for whom, or kept for your team to sort - and why. Nothing is made or sent.</p>
|
||||
<div class="mb-3">
|
||||
<label class="form-label">From <strong class="text-danger">*</strong></label>
|
||||
<div class="input-group">
|
||||
|
||||
@@ -33,11 +33,11 @@ echo settingsPageStart('ticket');
|
||||
<?php } ?>
|
||||
<?= settingsSwitch('config_ticket_email_parse', $config_ticket_email_parse) ?>
|
||||
<div data-settings-depends-on="config_ticket_email_parse">
|
||||
<?= settingsSwitch('config_ticket_email_parse_unknown_senders', $config_ticket_email_parse_unknown_senders, ['help' => 'From someone who isn\'t a contact, at a domain no client has - otherwise those are left in the mailbox, flagged and unread.']) ?>
|
||||
<?= settingsSwitch('config_ticket_email_parse_unknown_senders', $config_ticket_email_parse_unknown_senders, ['help' => 'From someone who isn\'t a contact, at a domain no client has - otherwise those wait in Tickets > Unprocessed Email for your team to sort.']) ?>
|
||||
<?php // What an email from someone with some subject would become, without sending one (functions/ticket_mail_try.php) ?>
|
||||
<div class="d-flex flex-wrap align-items-center gap-2 mt-2">
|
||||
<button type="button" class="btn btn-sm btn-outline-secondary ajax-modal" data-modal-url="modals/ticket_mail/ticket_mail_try.php" data-ticket-mail-try><i class="fas fa-vial me-2"></i>Try an Email</button>
|
||||
<span class="small text-body-secondary">What an email from someone would become - a reply, a ticket, or left in the mailbox - and why. Uses the saved settings.</span>
|
||||
<span class="small text-body-secondary">What an email from someone would become - a reply, a ticket, or kept for your team to sort - and why. Uses the saved settings.</span>
|
||||
</div>
|
||||
</div>
|
||||
<?= settingsSectionEnd() ?>
|
||||
|
||||
223
agent/email_unprocessed.php
Normal file
223
agent/email_unprocessed.php
Normal file
@@ -0,0 +1,223 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* Tickets > Unprocessed Email - email the ticket mailbox couldn't take (functions/mail_unprocessed.php): from someone
|
||||
* who isn't a contact, at a domain no client has, while unknown senders aren't let in - or one that failed. Each can
|
||||
* be opened, made a ticket, added to a ticket, tried again or dismissed (agent/post/email_unprocessed.php); the first
|
||||
* three are done by the email parser within a minute. The pills pick To sort, Sorted and Dismissed.
|
||||
*/
|
||||
|
||||
// Default Column Sortby Filter
|
||||
$sort = "email_unprocessed_received_at";
|
||||
$order = "DESC";
|
||||
|
||||
require_once "includes/inc_all.php";
|
||||
|
||||
enforceUserPermission('module_support');
|
||||
|
||||
$page_title = 'Unprocessed Email';
|
||||
$can_edit = lookupUserPermission('module_support') >= 2;
|
||||
|
||||
if (!mailUnprocessedReady()) {
|
||||
echo '<div class="alert alert-info">This list arrives with the 4.3.2 database update - <a href="/admin/update.php">Maintenance > Update</a>.</div>';
|
||||
require_once "../includes/footer.php";
|
||||
exit;
|
||||
}
|
||||
|
||||
$tabs = [
|
||||
'waiting' => ['To sort', 'fa-inbox', "email_unprocessed_done_at IS NULL"],
|
||||
'sorted' => ['Sorted', 'fa-check', "email_unprocessed_done_at IS NOT NULL AND email_unprocessed_action <> 'dismiss'"],
|
||||
'dismissed' => ['Dismissed', 'fa-times', "email_unprocessed_action = 'dismiss'"],
|
||||
];
|
||||
$show = (string) ($_GET['show'] ?? 'waiting');
|
||||
$show = isset($tabs[$show]) ? $show : 'waiting';
|
||||
|
||||
// Only these sort - an unknown column would take the page down
|
||||
$sortable_columns = [
|
||||
'email_unprocessed_received_at' => "email_unprocessed_received_at $order",
|
||||
'email_unprocessed_from_email' => "email_unprocessed_from_email $order, email_unprocessed_received_at DESC",
|
||||
'email_unprocessed_subject' => "email_unprocessed_subject $order, email_unprocessed_received_at DESC",
|
||||
];
|
||||
if (!isset($sortable_columns[$sort])) {
|
||||
$sort = 'email_unprocessed_received_at';
|
||||
}
|
||||
|
||||
$search = "(email_unprocessed_from_email LIKE '%$q%' OR email_unprocessed_from_name LIKE '%$q%' OR email_unprocessed_subject LIKE '%$q%' OR email_unprocessed_preview LIKE '%$q%' OR email_unprocessed_reason LIKE '%$q%')";
|
||||
|
||||
$sql = mysqli_query($mysqli, "SELECT SQL_CALC_FOUND_ROWS email_unprocessed.*, ticket_prefix, ticket_number, ticket_client_id, user_name AS asked_by
|
||||
FROM email_unprocessed
|
||||
LEFT JOIN tickets ON ticket_id = email_unprocessed_ticket_id
|
||||
LEFT JOIN users ON user_id = email_unprocessed_action_by
|
||||
WHERE $search AND {$tabs[$show][2]}
|
||||
ORDER BY {$sortable_columns[$sort]}, email_unprocessed_id DESC
|
||||
LIMIT $record_from, $record_to");
|
||||
|
||||
$num_rows = mysqli_fetch_row(mysqli_query($mysqli, "SELECT FOUND_ROWS()"));
|
||||
|
||||
// How many in each tab, as searched
|
||||
$count_sql = [];
|
||||
foreach ($tabs as $key => [, , $where]) {
|
||||
$count_sql[] = "COALESCE(SUM($where), 0)";
|
||||
}
|
||||
$counts = array_combine(array_keys($tabs), array_map('intval', mysqli_fetch_row(mysqli_query($mysqli, "SELECT " . implode(', ', $count_sql) . " FROM email_unprocessed WHERE $search"))));
|
||||
|
||||
$pill_url = function ($show) {
|
||||
return '?' . http_build_query(array_filter(['q' => $_GET['q'] ?? '', 'show' => $show]));
|
||||
};
|
||||
$csrf = $_SESSION['csrf_token'];
|
||||
|
||||
?>
|
||||
|
||||
<div class="card">
|
||||
<div class="card-header bg-dark py-2">
|
||||
<h3 class="card-title mt-2"><i class="fas fa-fw fa-envelope-open-text me-2"></i>Unprocessed Email</h3>
|
||||
<div class="card-tools">
|
||||
<a class="btn btn-outline-light" href="tickets.php"><i class="fas fa-life-ring"></i><span class="d-none d-lg-inline ms-2">Tickets</span></a>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="card-header py-3">
|
||||
<form autocomplete="off">
|
||||
<input type="hidden" name="show" value="<?= escapeHtml($show) ?>">
|
||||
<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 unprocessed email..." title="Who it is from, its subject or what it says">
|
||||
<button class="btn btn-dark" title="Search"><i class="fas fa-search"></i></button>
|
||||
</div>
|
||||
</div>
|
||||
<div class="col-lg-7 col-md-6">
|
||||
<div class="d-flex justify-content-end gap-2">
|
||||
<?php if ($can_edit && $show === 'waiting') { ?>
|
||||
<div class="dropdown" id="bulkActionButton" hidden>
|
||||
<button class="btn btn-secondary dropdown-toggle" type="button" data-bs-toggle="dropdown">
|
||||
<i class="fas fa-fw fa-layer-group me-2"></i>Bulk Action (<span id="selectedCount">0</span>)
|
||||
</button>
|
||||
<div class="dropdown-menu dropdown-menu-end">
|
||||
<button class="dropdown-item" type="submit" form="bulkActions" name="bulk_unprocessed_email" value="retry" title="As any email is taken - within a minute">
|
||||
<i class="fas fa-fw fa-redo-alt text-secondary me-2"></i>Try Again
|
||||
</button>
|
||||
<div class="dropdown-divider"></div>
|
||||
<button class="dropdown-item" type="submit" form="bulkActions" name="bulk_unprocessed_email" value="dismiss">
|
||||
<i class="fas fa-fw fa-times text-secondary me-2"></i>Dismiss
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<?php } ?>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</form>
|
||||
<nav class="nav nav-pills itflow-asset-tabs flex-nowrap overflow-auto mt-2" aria-label="Which email">
|
||||
<?php foreach ($tabs as $key => [$label, $icon]) { ?>
|
||||
<a class="nav-link text-nowrap <?= $show === $key ? 'active' : '' ?>" href="<?= escapeHtml($pill_url($key)) ?>" data-unprocessed-tab="<?= $key ?>">
|
||||
<i class="fas fa-fw <?= $icon ?> me-1"></i><?= $label ?> <span class="badge rounded-pill ms-1 <?= $key === 'waiting' && $show !== 'waiting' && $counts[$key] ? 'text-bg-warning' : '' ?>"><?= $counts[$key] ?></span>
|
||||
</a>
|
||||
<?php } ?>
|
||||
</nav>
|
||||
<div class="small text-body-secondary mt-2"><i class="fas fa-fw fa-info-circle me-1"></i>Email the ticket mailbox couldn't make a ticket from by itself. A ticket made here, or a reply added, is made by the email parser within a minute. Sorted and dismissed email is kept <?= MAIL_UNPROCESSED_KEEP_DAYS ?> days.</div>
|
||||
</div>
|
||||
|
||||
<form id="bulkActions" action="post.php" method="post">
|
||||
<input type="hidden" name="csrf_token" value="<?= $csrf ?>">
|
||||
<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>
|
||||
<?php if ($can_edit && $show === 'waiting') { ?>
|
||||
<th class="checkbox-column border-end">
|
||||
<div class="form-check">
|
||||
<input class="form-check-input" id="selectAllCheckbox" type="checkbox" title="Select all on this page">
|
||||
</div>
|
||||
</th>
|
||||
<?php } ?>
|
||||
<th><?= sortLink('email_unprocessed_from_email', 'From') ?></th>
|
||||
<th class="d-none d-md-table-cell"><?= sortLink('email_unprocessed_subject', 'Subject') ?></th>
|
||||
<th class="d-none d-lg-table-cell"><?= sortLink('email_unprocessed_received_at', 'Received') ?></th>
|
||||
<th></th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<?php while ($row = mysqli_fetch_assoc($sql)) {
|
||||
$id = intval($row['email_unprocessed_id']);
|
||||
$state = mailUnprocessedState($row);
|
||||
$subject = trim((string) $row['email_unprocessed_subject']) !== '' ? escapeHtml($row['email_unprocessed_subject']) : '<span class="text-body-secondary">(no subject)</span>';
|
||||
$from_name = trim((string) $row['email_unprocessed_from_name']);
|
||||
$from_email = (string) $row['email_unprocessed_from_email'];
|
||||
$view = 'data-modal-size="lg" data-modal-url="modals/email_unprocessed/email_unprocessed_view.php?id=' . $id . '"';
|
||||
$waiting = $state['key'] === 'waiting';
|
||||
?>
|
||||
<tr data-unprocessed-id="<?= $id ?>" data-unprocessed-state="<?= $state['key'] ?>">
|
||||
<?php if ($can_edit && $show === 'waiting') { ?>
|
||||
<td class="checkbox-column bg-light border-end">
|
||||
<?php if ($waiting) { ?>
|
||||
<div class="form-check">
|
||||
<input class="form-check-input bulk-select" type="checkbox" name="email_unprocessed_ids[]" value="<?= $id ?>" aria-label="Select email <?= $id ?>">
|
||||
</div>
|
||||
<?php } ?>
|
||||
</td>
|
||||
<?php } ?>
|
||||
<td class="min-w-0">
|
||||
<div class="text-break"><?= $from_name !== '' ? escapeHtml($from_name) . ' <span class="small text-body-secondary">' . escapeHtml($from_email) . '</span>' : ($from_email !== '' ? escapeHtml($from_email) : '<span class="text-body-secondary">No sender address</span>') ?></div>
|
||||
<div class="d-md-none small"><a class="ajax-modal" href="#" <?= $view ?>><?= $subject ?></a></div>
|
||||
<div class="small mt-1">
|
||||
<span class="badge rounded-pill <?= $state['badge'] ?>" data-unprocessed-status><?= escapeHtml($state['label']) ?></span>
|
||||
<?php if ($state['detail'] !== '') { ?><span class="text-body-secondary"><?= escapeHtml($state['detail']) ?></span><?php } ?>
|
||||
<?php if (intval($row['email_unprocessed_ticket_id']) && $row['ticket_number'] !== null) { ?>
|
||||
<a href="ticket.php?<?= intval($row['ticket_client_id']) ? 'client_id=' . intval($row['ticket_client_id']) . '&' : '' ?>ticket_id=<?= intval($row['email_unprocessed_ticket_id']) ?>" data-unprocessed-ticket><?= escapeHtml($row['ticket_prefix'] . $row['ticket_number']) ?></a>
|
||||
<?php } ?>
|
||||
<?php if ($row['asked_by'] !== null && $state['key'] !== 'waiting') { ?><span class="text-body-secondary">by <?= escapeHtml($row['asked_by']) ?></span><?php } ?>
|
||||
</div>
|
||||
</td>
|
||||
<td class="d-none d-md-table-cell min-w-0">
|
||||
<a class="ajax-modal fw-semibold text-body" href="#" <?= $view ?>><?= $subject ?></a>
|
||||
<?php if (trim((string) $row['email_unprocessed_preview']) !== '') { ?>
|
||||
<div class="small text-body-secondary text-truncate" style="max-width: 40rem"><?= escapeHtml($row['email_unprocessed_preview']) ?></div>
|
||||
<?php } ?>
|
||||
<?php if ($waiting && trim((string) $row['email_unprocessed_reason']) !== '') { ?>
|
||||
<div class="small text-warning-emphasis" data-unprocessed-reason><?= escapeHtml($row['email_unprocessed_reason']) ?></div>
|
||||
<?php } ?>
|
||||
</td>
|
||||
<td class="d-none d-lg-table-cell text-nowrap small" title="<?= escapeHtml(date('M j, Y g:i:s A', strtotime((string) $row['email_unprocessed_received_at']))) ?>">
|
||||
<?= escapeHtml(date('M j, g:i A', strtotime((string) $row['email_unprocessed_received_at']))) ?>
|
||||
<div class="text-body-secondary"><?= escapeHtml(timeAgo($row['email_unprocessed_received_at'])) ?></div>
|
||||
</td>
|
||||
<td class="text-end">
|
||||
<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="#" <?= $view ?>><i class="fas fa-fw fa-envelope-open text-secondary me-2"></i>View</a>
|
||||
<?php if ($can_edit && $waiting) { ?>
|
||||
<a class="dropdown-item ajax-modal" href="#" data-modal-url="modals/email_unprocessed/email_unprocessed_ticket.php?id=<?= $id ?>" data-unprocessed-make><i class="fas fa-fw fa-plus text-secondary me-2"></i>Make a Ticket</a>
|
||||
<a class="dropdown-item ajax-modal" href="#" data-modal-url="modals/email_unprocessed/email_unprocessed_reply.php?id=<?= $id ?>" data-unprocessed-add><i class="fas fa-fw fa-reply text-secondary me-2"></i>Add to a Ticket</a>
|
||||
<a class="dropdown-item" href="post.php?unprocessed_email=retry&id=<?= $id ?>&csrf_token=<?= $csrf ?>" title="As any email is taken - after making them a contact, say" data-unprocessed-retry><i class="fas fa-fw fa-redo-alt text-secondary me-2"></i>Try Again</a>
|
||||
<div class="dropdown-divider"></div>
|
||||
<a class="dropdown-item" href="post.php?unprocessed_email=dismiss&id=<?= $id ?>&csrf_token=<?= $csrf ?>" data-unprocessed-dismiss><i class="fas fa-fw fa-times text-secondary me-2"></i>Dismiss</a>
|
||||
<?php } ?>
|
||||
<a class="dropdown-item" href="post.php?download_unprocessed_email=<?= $id ?>"><i class="fas fa-fw fa-download text-secondary me-2"></i>Download .eml</a>
|
||||
</div>
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
<?php } ?>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</form>
|
||||
|
||||
<?php
|
||||
$empty_state = [
|
||||
'thing' => 'emails',
|
||||
'views' => ['show'],
|
||||
'icon' => 'fa-envelope-open-text',
|
||||
'title' => ['waiting' => 'Nothing to sort', 'sorted' => 'Nothing sorted lately', 'dismissed' => 'Nothing dismissed lately'][$show],
|
||||
'text' => 'Email the ticket mailbox can\'t make a ticket from by itself waits here - from someone who isn\'t a contact, at a domain no client has, say.',
|
||||
];
|
||||
?>
|
||||
<?php require_once "../includes/filter_footer.php"; ?>
|
||||
</div>
|
||||
|
||||
<script src="<?= staticFileUrl('/js/bulk_actions.js') ?>"></script>
|
||||
|
||||
<?php
|
||||
require_once "../includes/footer.php";
|
||||
77
agent/js/email_unprocessed_modal.js
Normal file
77
agent/js/email_unprocessed_modal.js
Normal file
@@ -0,0 +1,77 @@
|
||||
// Tickets > Unprocessed Email > Make a Ticket (agent/modals/email_unprocessed/email_unprocessed_ticket.php): the contact
|
||||
// picker follows the client picked - the one in data-selected picked when it is theirs - and "make the sender a contact"
|
||||
// shows only while the contact is Nobody.
|
||||
//
|
||||
// Wrapped in an IIFE because a modal can be opened, closed and opened again in one page load, which re-runs this file.
|
||||
|
||||
(function () {
|
||||
|
||||
const clientSelect = document.getElementById('unprocessedClientSelect');
|
||||
const contactSelect = document.getElementById('unprocessedContactSelect');
|
||||
const addBox = document.getElementById('unprocessedAddContact');
|
||||
|
||||
function syncAdd() {
|
||||
if (addBox && contactSelect) {
|
||||
addBox.hidden = contactSelect.value !== '' && contactSelect.value !== '0';
|
||||
}
|
||||
}
|
||||
|
||||
function loadContacts(clientId) {
|
||||
if (!contactSelect) {
|
||||
return;
|
||||
}
|
||||
const wanted = contactSelect.dataset.selected || '0';
|
||||
contactSelect.dataset.selected = '0';
|
||||
contactSelect.innerHTML = '';
|
||||
contactSelect.add(new Option('- Nobody -', '0'));
|
||||
contactSelect.value = '0';
|
||||
syncAdd();
|
||||
if (!clientId || clientId === '0') {
|
||||
return;
|
||||
}
|
||||
itflowGet('ajax.php', {get_client_contacts: 'true', client_id: clientId}, function (data) {
|
||||
let contacts = [];
|
||||
try {
|
||||
contacts = JSON.parse(data).contacts || [];
|
||||
} catch (e) {
|
||||
contacts = [];
|
||||
}
|
||||
contacts.forEach(function (contact) {
|
||||
const option = new Option(contact.contact_name, contact.contact_id);
|
||||
const details = [];
|
||||
if (contact.contact_email) {
|
||||
details.push(contact.contact_email);
|
||||
}
|
||||
if (contact.contact_primary == '1') {
|
||||
details.push('Primary');
|
||||
}
|
||||
option.dataset.description = details.join(' · ');
|
||||
option.dataset.keywords = contact.contact_email || '';
|
||||
if (contact.contact_photo_url) {
|
||||
option.dataset.image = contact.contact_photo_url;
|
||||
} else {
|
||||
option.dataset.initials = contact.contact_initials;
|
||||
option.dataset.shape = 'circle';
|
||||
option.dataset.tone = contact.contact_tone || 'secondary';
|
||||
option.dataset.soft = '1';
|
||||
}
|
||||
contactSelect.add(option);
|
||||
});
|
||||
if (contacts.some(function (contact) { return String(contact.contact_id) === wanted; })) {
|
||||
contactSelect.value = wanted;
|
||||
}
|
||||
syncAdd();
|
||||
});
|
||||
}
|
||||
|
||||
if (clientSelect) {
|
||||
clientSelect.addEventListener('change', function () {
|
||||
loadContacts(clientSelect.value);
|
||||
});
|
||||
loadContacts(clientSelect.value);
|
||||
}
|
||||
if (contactSelect) {
|
||||
contactSelect.addEventListener('change', syncAdd);
|
||||
}
|
||||
|
||||
})();
|
||||
85
agent/modals/email_unprocessed/email_unprocessed_reply.php
Normal file
85
agent/modals/email_unprocessed/email_unprocessed_reply.php
Normal file
@@ -0,0 +1,85 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* Tickets > Unprocessed Email > Add to a Ticket - the ticket it goes on: an open one, or one closed in the last 30
|
||||
* days. Asked of the email parser (agent/post/email_unprocessed.php), which adds it as it would a reply to the ticket -
|
||||
* a client reply from a contact or CC, else a note only your team sees. The sender can be made a CC on the ticket
|
||||
* first, so it is their reply and they hear back.
|
||||
*/
|
||||
|
||||
require_once '../../../includes/modal_header.php';
|
||||
|
||||
enforceUserPermission('module_support', 2);
|
||||
|
||||
$row = mailUnprocessedReady() ? mailUnprocessedRow($_GET['id'] ?? 0) : null;
|
||||
if (!$row || $row['email_unprocessed_done_at'] !== null) {
|
||||
echo json_encode(['error' => $row ? 'That email was sorted already.' : "That email isn't there any more."]);
|
||||
exit;
|
||||
}
|
||||
|
||||
$id = intval($row['email_unprocessed_id']);
|
||||
$from_email = trim((string) $row['email_unprocessed_from_email']);
|
||||
$from_name = trim((string) $row['email_unprocessed_from_name']);
|
||||
$can_add = filter_var($from_email, FILTER_VALIDATE_EMAIL) !== false;
|
||||
|
||||
// Open tickets, and ones closed lately - the newest first
|
||||
$sql_tickets = mysqli_query($mysqli, "SELECT ticket_id, ticket_prefix, ticket_number, ticket_subject, ticket_closed_at, ticket_status_name, client_name, contact_name, contact_email FROM tickets
|
||||
LEFT JOIN ticket_statuses ON ticket_status_id = ticket_status
|
||||
LEFT JOIN clients ON client_id = ticket_client_id
|
||||
LEFT JOIN contacts ON contact_id = ticket_contact_id
|
||||
WHERE (ticket_closed_at IS NULL OR ticket_closed_at > NOW() - INTERVAL 30 DAY) " . clientScopeSql('ticket_client_id') . "
|
||||
ORDER BY ticket_closed_at IS NOT NULL, ticket_id DESC LIMIT 2000");
|
||||
|
||||
ob_start();
|
||||
|
||||
?>
|
||||
|
||||
<div class="modal-header bg-dark">
|
||||
<h5 class="modal-title"><i class="fas fa-fw fa-reply me-2"></i>Add to a Ticket</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">
|
||||
<input type="hidden" name="csrf_token" value="<?= $_SESSION['csrf_token'] ?>">
|
||||
<input type="hidden" name="email_unprocessed_id" value="<?= $id ?>">
|
||||
<div class="modal-body">
|
||||
|
||||
<div class="alert alert-info small">
|
||||
From <strong><?= escapeHtml($from_name !== '' ? $from_name : ($from_email !== '' ? $from_email : 'no sender address')) ?></strong><?= $from_name !== '' && $from_email !== '' ? ' <' . escapeHtml($from_email) . '>' : '' ?>
|
||||
- <?= escapeHtml(trim((string) $row['email_unprocessed_subject']) !== '' ? $row['email_unprocessed_subject'] : '(no subject)') ?><br>
|
||||
It is added to the ticket as a reply would be, within a minute - from someone who isn't a contact or CC, as a note only your team sees.
|
||||
</div>
|
||||
|
||||
<div class="mb-3">
|
||||
<label class="form-label">Ticket <strong class="text-danger">*</strong></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="ticket_id" required data-placeholder="Search by number, subject or client">
|
||||
<option value="">- Pick the ticket -</option>
|
||||
<?php while ($ticket = mysqli_fetch_assoc($sql_tickets)) {
|
||||
$details = array_filter([(string) $ticket['client_name'], $ticket['ticket_closed_at'] ? 'Closed' : (string) $ticket['ticket_status_name'], (string) $ticket['contact_name']]);
|
||||
?>
|
||||
<option value="<?= intval($ticket['ticket_id']) ?>" data-description="<?= escapeHtml(implode(' · ', $details)) ?>" data-keywords="<?= escapeHtml(trim($ticket['ticket_number'] . ' ' . $ticket['client_name'] . ' ' . $ticket['contact_email'])) ?>"><?= escapeHtml(ticketReference($ticket) . ' - ' . $ticket['ticket_subject']) ?></option>
|
||||
<?php } ?>
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<?php if ($can_add) { ?>
|
||||
<div class="form-check">
|
||||
<input class="form-check-input" type="checkbox" id="unprocessedAddCcCheck" name="make_cc" value="1">
|
||||
<label class="form-check-label" for="unprocessedAddCcCheck">
|
||||
Make <?= escapeHtml($from_email) ?> a CC on the ticket
|
||||
</label>
|
||||
<div class="form-text">So it goes on as their reply - reopening the ticket - and they hear back.</div>
|
||||
</div>
|
||||
<?php } ?>
|
||||
|
||||
</div>
|
||||
<div class="modal-footer">
|
||||
<button type="submit" name="unprocessed_email_reply" class="btn btn-primary fw-bold"><i class="fas fa-check me-2"></i>Add to Ticket</button>
|
||||
<button type="button" class="btn btn-light" data-bs-dismiss="modal"><i class="fas fa-times me-2"></i>Cancel</button>
|
||||
</div>
|
||||
</form>
|
||||
|
||||
<?php
|
||||
require_once '../../../includes/modal_footer.php';
|
||||
98
agent/modals/email_unprocessed/email_unprocessed_ticket.php
Normal file
98
agent/modals/email_unprocessed/email_unprocessed_ticket.php
Normal file
@@ -0,0 +1,98 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* Tickets > Unprocessed Email > Make a Ticket - the client it is for, and the contact: one of theirs, the sender made
|
||||
* a contact there first, or nobody. Asked of the email parser (agent/post/email_unprocessed.php), which makes the
|
||||
* ticket from the email as it would any other - its text, attachments and the rest. A sender who is a contact already
|
||||
* (an email that failed) starts picked.
|
||||
*/
|
||||
|
||||
require_once '../../../includes/modal_header.php';
|
||||
|
||||
enforceUserPermission('module_support', 2);
|
||||
|
||||
$row = mailUnprocessedReady() ? mailUnprocessedRow($_GET['id'] ?? 0) : null;
|
||||
if (!$row || $row['email_unprocessed_done_at'] !== null) {
|
||||
echo json_encode(['error' => $row ? 'That email was sorted already.' : "That email isn't there any more."]);
|
||||
exit;
|
||||
}
|
||||
|
||||
$id = intval($row['email_unprocessed_id']);
|
||||
$from_email = trim((string) $row['email_unprocessed_from_email']);
|
||||
$from_name = trim((string) $row['email_unprocessed_from_name']);
|
||||
$can_add = filter_var($from_email, FILTER_VALIDATE_EMAIL) !== false;
|
||||
|
||||
// A sender who is a contact already starts picked - their client and them
|
||||
$known = $from_email !== '' ? mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT contact_id, contact_client_id FROM contacts
|
||||
LEFT JOIN clients ON client_id = contact_client_id
|
||||
WHERE contact_email = '" . escapeSql($from_email) . "' AND contact_archived_at IS NULL AND client_archived_at IS NULL " . clientScopeSql('contact_client_id') . "
|
||||
ORDER BY contact_primary DESC, contact_id LIMIT 1")) : null;
|
||||
$client_id = intval($known['contact_client_id'] ?? 0);
|
||||
$contact_id = intval($known['contact_id'] ?? 0);
|
||||
|
||||
ob_start();
|
||||
|
||||
?>
|
||||
|
||||
<div class="modal-header bg-dark">
|
||||
<h5 class="modal-title"><i class="fas fa-fw fa-plus me-2"></i>Make a Ticket</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" id="unprocessedTicketForm">
|
||||
<input type="hidden" name="csrf_token" value="<?= $_SESSION['csrf_token'] ?>">
|
||||
<input type="hidden" name="email_unprocessed_id" value="<?= $id ?>">
|
||||
<div class="modal-body">
|
||||
|
||||
<div class="alert alert-info small">
|
||||
From <strong><?= escapeHtml($from_name !== '' ? $from_name : ($from_email !== '' ? $from_email : 'no sender address')) ?></strong><?= $from_name !== '' && $from_email !== '' ? ' <' . escapeHtml($from_email) . '>' : '' ?>
|
||||
- <?= escapeHtml(trim((string) $row['email_unprocessed_subject']) !== '' ? $row['email_unprocessed_subject'] : '(no subject)') ?><br>
|
||||
The ticket is made from the email, its attachments too, within a minute.
|
||||
</div>
|
||||
|
||||
<div class="mb-3">
|
||||
<label class="form-label">Client <strong class="text-danger">*</strong></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="client_id" id="unprocessedClientSelect" required>
|
||||
<option value="">- Select a client -</option>
|
||||
<?php
|
||||
$sql = mysqli_query($mysqli, "SELECT client_id, client_name, client_abbreviation FROM clients WHERE client_archived_at IS NULL AND (client_lead = 0 OR client_id = $client_id) " . clientScopeSql('clients.client_id') . " ORDER BY client_name ASC");
|
||||
while ($client = mysqli_fetch_assoc($sql)) { ?>
|
||||
<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>
|
||||
|
||||
<div class="mb-3">
|
||||
<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="contact_id" id="unprocessedContactSelect" data-selected="<?= $contact_id ?>">
|
||||
<option value="0">- Nobody -</option>
|
||||
</select>
|
||||
<?= quickAddButton('contact', 0) ?>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<?php if ($can_add) { ?>
|
||||
<div class="form-check" id="unprocessedAddContact">
|
||||
<input class="form-check-input" type="checkbox" id="unprocessedAddContactCheck" name="make_contact" value="1" <?= $contact_id ? '' : 'checked' ?>>
|
||||
<label class="form-check-label" for="unprocessedAddContactCheck">
|
||||
Make <?= escapeHtml($from_email) ?> a contact at the client, for the ticket
|
||||
</label>
|
||||
<div class="form-text">So their replies go on the ticket, and they hear back about it.</div>
|
||||
</div>
|
||||
<?php } ?>
|
||||
|
||||
</div>
|
||||
<div class="modal-footer">
|
||||
<button type="submit" name="unprocessed_email_ticket" class="btn btn-primary fw-bold"><i class="fas fa-check me-2"></i>Make Ticket</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 src="<?= staticFileUrl('/agent/js/email_unprocessed_modal.js') ?>"></script>
|
||||
|
||||
<?php
|
||||
require_once '../../../includes/modal_footer.php';
|
||||
89
agent/modals/email_unprocessed/email_unprocessed_view.php
Normal file
89
agent/modals/email_unprocessed/email_unprocessed_view.php
Normal file
@@ -0,0 +1,89 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* Tickets > Unprocessed Email > View - the email as it came, from its copy (mailUnprocessedRead(),
|
||||
* functions/mail_unprocessed.php): who it is from and to, why it wasn't taken, its text, attachments and headers.
|
||||
* Shown as text - nothing in it runs or loads. Make a Ticket and Add to a Ticket open their own windows.
|
||||
*/
|
||||
|
||||
require_once '../../../includes/modal_header.php';
|
||||
|
||||
enforceUserPermission('module_support');
|
||||
|
||||
$row = mailUnprocessedReady() ? mailUnprocessedRow($_GET['id'] ?? 0) : null;
|
||||
if (!$row) {
|
||||
echo json_encode(['error' => "That email isn't there any more."]);
|
||||
exit;
|
||||
}
|
||||
|
||||
$id = intval($row['email_unprocessed_id']);
|
||||
$state = mailUnprocessedState($row);
|
||||
$email = mailUnprocessedRead($row);
|
||||
$can_edit = lookupUserPermission('module_support') >= 2 && $state['key'] === 'waiting';
|
||||
$subject = trim((string) $row['email_unprocessed_subject']) !== '' ? escapeHtml($row['email_unprocessed_subject']) : '(no subject)';
|
||||
|
||||
ob_start();
|
||||
|
||||
?>
|
||||
|
||||
<div class="modal-header bg-dark">
|
||||
<h5 class="modal-title text-truncate"><i class="fas fa-fw fa-envelope-open-text me-2"></i><?= $subject ?></h5>
|
||||
<button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
|
||||
</div>
|
||||
<div class="modal-body" data-unprocessed-view="<?= $id ?>">
|
||||
|
||||
<div class="d-flex flex-wrap align-items-center gap-2 mb-3">
|
||||
<span class="badge rounded-pill <?= $state['badge'] ?>"><?= escapeHtml($state['label']) ?></span>
|
||||
<?php if ($state['key'] === 'waiting' && trim((string) $row['email_unprocessed_reason']) !== '') { ?>
|
||||
<span class="small text-warning-emphasis" data-unprocessed-reason><i class="fas fa-fw fa-exclamation-triangle me-1"></i><?= escapeHtml($row['email_unprocessed_reason']) ?></span>
|
||||
<?php } elseif ($state['detail'] !== '') { ?>
|
||||
<span class="small text-body-secondary"><?= escapeHtml($state['detail']) ?></span>
|
||||
<?php } ?>
|
||||
</div>
|
||||
|
||||
<?php if ($email['missing']) { ?>
|
||||
<div class="alert alert-warning small mb-0">Its copy is missing, so only what was noted when it came is shown.</div>
|
||||
<dl class="row small mt-3 mb-0">
|
||||
<dt class="col-sm-2">From</dt><dd class="col-sm-10 text-break"><?= escapeHtml(trim($row['email_unprocessed_from_name'] . ' <' . $row['email_unprocessed_from_email'] . '>')) ?></dd>
|
||||
<dt class="col-sm-2">Received</dt><dd class="col-sm-10"><?= escapeHtml($row['email_unprocessed_received_at']) ?></dd>
|
||||
</dl>
|
||||
<?php if (trim((string) $row['email_unprocessed_preview']) !== '') { ?>
|
||||
<div class="border rounded p-3 small text-break" style="white-space: pre-wrap"><?= escapeHtml($row['email_unprocessed_preview']) ?></div>
|
||||
<?php } ?>
|
||||
<?php } elseif ($email['too_big']) { ?>
|
||||
<div class="alert alert-warning small mb-0">It is too big to show here - download it to open it in your email program.</div>
|
||||
<?php } else { ?>
|
||||
<dl class="row small mb-2" data-unprocessed-fields>
|
||||
<?php foreach ($email['fields'] as $label => $value) { ?>
|
||||
<dt class="col-sm-2 text-body-secondary fw-normal"><?= escapeHtml($label) ?></dt>
|
||||
<dd class="col-sm-10 text-break mb-1"><?= escapeHtml($value) ?></dd>
|
||||
<?php } ?>
|
||||
</dl>
|
||||
<?php if ($email['attachments']) { ?>
|
||||
<div class="small mb-3" data-unprocessed-attachments>
|
||||
<i class="fas fa-fw fa-paperclip text-body-secondary me-1"></i><?= implode(', ', array_map('escapeHtml', $email['attachments'])) ?>
|
||||
</div>
|
||||
<?php } ?>
|
||||
<div class="border rounded p-3 small text-break overflow-auto" style="white-space: pre-wrap; max-height: 50vh" data-unprocessed-text><?= $email['text'] !== '' ? escapeHtml($email['text']) : '<span class="text-body-secondary">It has no text to show.</span>' ?></div>
|
||||
<details class="mt-3 small">
|
||||
<summary class="text-body-secondary">Headers</summary>
|
||||
<pre class="mt-2 mb-0 p-2 bg-body-tertiary rounded small overflow-auto" style="max-height: 30vh"><?= escapeHtml($email['headers']) ?></pre>
|
||||
</details>
|
||||
<?php } ?>
|
||||
|
||||
</div>
|
||||
<div class="modal-footer">
|
||||
<?php if ($can_edit) { ?>
|
||||
<button type="button" class="btn btn-primary fw-bold ajax-modal" data-modal-url="modals/email_unprocessed/email_unprocessed_ticket.php?id=<?= $id ?>"><i class="fas fa-plus me-2"></i>Make a Ticket</button>
|
||||
<button type="button" class="btn btn-outline-primary ajax-modal" data-modal-url="modals/email_unprocessed/email_unprocessed_reply.php?id=<?= $id ?>"><i class="fas fa-reply me-2"></i>Add to a Ticket</button>
|
||||
<a class="btn btn-outline-secondary" href="post.php?unprocessed_email=retry&id=<?= $id ?>&csrf_token=<?= $_SESSION['csrf_token'] ?>" title="As any email is taken - after making them a contact, say"><i class="fas fa-redo-alt me-2"></i>Try Again</a>
|
||||
<a class="btn btn-outline-danger" href="post.php?unprocessed_email=dismiss&id=<?= $id ?>&csrf_token=<?= $_SESSION['csrf_token'] ?>"><i class="fas fa-times me-2"></i>Dismiss</a>
|
||||
<?php } ?>
|
||||
<?php if (!$email['missing']) { ?>
|
||||
<a class="btn btn-light" href="post.php?download_unprocessed_email=<?= $id ?>"><i class="fas fa-download me-2"></i>Download</a>
|
||||
<?php } ?>
|
||||
<button type="button" class="btn btn-light" data-bs-dismiss="modal"><i class="fas fa-times me-2"></i>Close</button>
|
||||
</div>
|
||||
|
||||
<?php
|
||||
require_once '../../../includes/modal_footer.php';
|
||||
158
agent/post/email_unprocessed.php
Normal file
158
agent/post/email_unprocessed.php
Normal file
@@ -0,0 +1,158 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* ITFlow - POST handlers for Tickets > Unprocessed Email (agent/email_unprocessed.php, functions/mail_unprocessed.php):
|
||||
* Make a Ticket, Add to a Ticket, Try Again and Dismiss - one at a time or Bulk Action - and Download .eml. A ticket, a
|
||||
* reply or a try again is asked of the email parser, which takes the email from its copy within a minute.
|
||||
*/
|
||||
|
||||
defined('FROM_POST_HANDLER') || die("Direct file access is not allowed");
|
||||
|
||||
/* The email to act on, still waiting - or a message and back to the list */
|
||||
function unprocessedEmailForRequest($id) {
|
||||
$row = mailUnprocessedReady() ? mailUnprocessedRow($id) : null;
|
||||
if (!$row) {
|
||||
flashAlert("That email isn't there any more", 'error');
|
||||
redirect('email_unprocessed.php');
|
||||
}
|
||||
if ($row['email_unprocessed_done_at'] !== null) {
|
||||
flashAlert("That email was sorted already", 'error');
|
||||
redirect('email_unprocessed.php');
|
||||
}
|
||||
return $row;
|
||||
}
|
||||
|
||||
/* Who it is from, for the messages and the audit log - escaped for HTML */
|
||||
function unprocessedEmailFrom(array $row) {
|
||||
$from = trim((string) $row['email_unprocessed_from_email']);
|
||||
return escapeHtml($from !== '' ? $from : 'no sender address');
|
||||
}
|
||||
|
||||
// Make a Ticket - at the client picked, for the contact picked, or the sender made a contact there first
|
||||
if (isset($_POST['unprocessed_email_ticket'])) {
|
||||
|
||||
validateCSRFToken();
|
||||
enforceUserPermission('module_support', 2);
|
||||
|
||||
$row = unprocessedEmailForRequest($_POST['email_unprocessed_id'] ?? 0);
|
||||
$client_id = intval($_POST['client_id'] ?? 0);
|
||||
$contact_id = intval($_POST['contact_id'] ?? 0);
|
||||
$add = !empty($_POST['make_contact']) && !$contact_id;
|
||||
|
||||
if (!$client_id || !mysqli_num_rows(mysqli_query($mysqli, "SELECT 1 FROM clients WHERE client_id = $client_id AND client_archived_at IS NULL"))) {
|
||||
flashAlert("Pick the client the ticket is for", 'error');
|
||||
redirect();
|
||||
}
|
||||
enforceClientAccess($client_id);
|
||||
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"))) {
|
||||
flashAlert("That contact isn't at the client picked", 'error');
|
||||
redirect();
|
||||
}
|
||||
if ($add && !filter_var((string) $row['email_unprocessed_from_email'], FILTER_VALIDATE_EMAIL)) {
|
||||
flashAlert("The sender can't be made a contact - the email has no address it can be answered at", 'error');
|
||||
redirect();
|
||||
}
|
||||
|
||||
mailUnprocessedDecide([$row['email_unprocessed_id']], 'ticket', ['client_id' => $client_id, 'contact_id' => $contact_id, 'add' => $add], $session_user_id);
|
||||
|
||||
$client_name = escapeSql((string) getFieldById('clients', $client_id, 'client_name'));
|
||||
logAudit("Email", "Unprocessed", "$session_name asked for a ticket at $client_name from the email from " . escapeSql((string) $row['email_unprocessed_from_email']), $client_id);
|
||||
flashAlert("A ticket at <strong>" . escapeHtml(stripslashes($client_name)) . "</strong> is being made from the email from " . unprocessedEmailFrom($row) . " - within a minute");
|
||||
|
||||
redirect();
|
||||
|
||||
}
|
||||
|
||||
// Add to a Ticket - on the ticket picked, the sender made a CC on it if asked
|
||||
if (isset($_POST['unprocessed_email_reply'])) {
|
||||
|
||||
validateCSRFToken();
|
||||
enforceUserPermission('module_support', 2);
|
||||
|
||||
$row = unprocessedEmailForRequest($_POST['email_unprocessed_id'] ?? 0);
|
||||
$ticket = ticketForRequest($_POST['ticket_id'] ?? 0, 2);
|
||||
$add = !empty($_POST['make_cc']);
|
||||
|
||||
if ($add && !filter_var((string) $row['email_unprocessed_from_email'], FILTER_VALIDATE_EMAIL)) {
|
||||
flashAlert("The sender can't be made a CC - the email has no address it can be answered at", 'error');
|
||||
redirect();
|
||||
}
|
||||
|
||||
mailUnprocessedDecide([$row['email_unprocessed_id']], 'reply', ['ticket_id' => intval($ticket['ticket_id']), 'add' => $add], $session_user_id);
|
||||
|
||||
$reference = escapeSql(ticketReference($ticket));
|
||||
logAudit("Email", "Unprocessed", "$session_name asked for the email from " . escapeSql((string) $row['email_unprocessed_from_email']) . " to be added to ticket $reference", intval($ticket['ticket_client_id']), intval($ticket['ticket_id']));
|
||||
flashAlert("The email from " . unprocessedEmailFrom($row) . " is being added to <strong>" . escapeHtml(ticketReference($ticket)) . "</strong> - within a minute");
|
||||
|
||||
redirect();
|
||||
|
||||
}
|
||||
|
||||
// Try Again or Dismiss - one, from its menu
|
||||
if (isset($_GET['unprocessed_email'])) {
|
||||
|
||||
validateCSRFToken();
|
||||
enforceUserPermission('module_support', 2);
|
||||
|
||||
$action = (string) $_GET['unprocessed_email'];
|
||||
if (!in_array($action, ['retry', 'dismiss'], true)) {
|
||||
redirect('email_unprocessed.php');
|
||||
}
|
||||
$row = unprocessedEmailForRequest($_GET['id'] ?? 0);
|
||||
|
||||
mailUnprocessedDecide([$row['email_unprocessed_id']], $action, [], $session_user_id);
|
||||
|
||||
logAudit("Email", "Unprocessed", "$session_name " . ($action === 'retry' ? 'tried again' : 'dismissed') . " the email from " . escapeSql((string) $row['email_unprocessed_from_email']));
|
||||
flashAlert($action === 'retry' ? "The email from " . unprocessedEmailFrom($row) . " is being tried again - within a minute"
|
||||
: "The email from " . unprocessedEmailFrom($row) . " was dismissed", $action === 'retry' ? 'success' : 'error');
|
||||
|
||||
redirect();
|
||||
|
||||
}
|
||||
|
||||
// Bulk Action - Try Again or Dismiss the ones ticked
|
||||
if (isset($_POST['bulk_unprocessed_email'])) {
|
||||
|
||||
validateCSRFToken();
|
||||
enforceUserPermission('module_support', 2);
|
||||
|
||||
$action = (string) $_POST['bulk_unprocessed_email'];
|
||||
$ids = array_map('intval', (array) ($_POST['email_unprocessed_ids'] ?? []));
|
||||
if (!in_array($action, ['retry', 'dismiss'], true) || !$ids) {
|
||||
flashAlert("Tick the emails first", 'error');
|
||||
redirect();
|
||||
}
|
||||
|
||||
$count = count(mailUnprocessedDecide($ids, $action, [], $session_user_id));
|
||||
|
||||
logAudit("Email", "Unprocessed", "$session_name " . ($action === 'retry' ? 'tried again' : 'dismissed') . " $count unprocessed email(s)");
|
||||
flashAlert($action === 'retry' ? "<strong>$count</strong> email(s) are being tried again - within a minute" : "<strong>$count</strong> email(s) dismissed", $action === 'retry' ? 'success' : 'error');
|
||||
|
||||
redirect();
|
||||
|
||||
}
|
||||
|
||||
// Download .eml - the email as it came
|
||||
if (isset($_GET['download_unprocessed_email'])) {
|
||||
|
||||
enforceUserPermission('module_support');
|
||||
|
||||
$row = mailUnprocessedReady() ? mailUnprocessedRow($_GET['download_unprocessed_email']) : null;
|
||||
$path = $row ? mailUnprocessedPath($row['email_unprocessed_file']) : '';
|
||||
if ($path === '' || !is_file($path)) {
|
||||
flashAlert("That email's copy isn't there any more", 'error');
|
||||
redirect('email_unprocessed.php');
|
||||
}
|
||||
|
||||
$name = trim(preg_replace('/[^A-Za-z0-9_-]+/', '_', (string) $row['email_unprocessed_subject']), '_');
|
||||
$name = ($name !== '' ? mb_substr($name, 0, 60) : 'email') . '-' . intval($row['email_unprocessed_id']);
|
||||
|
||||
header('Content-Type: message/rfc822');
|
||||
header("Content-Disposition: attachment; filename=\"$name.eml\"");
|
||||
header('Content-Length: ' . filesize($path));
|
||||
header('X-Content-Type-Options: nosniff');
|
||||
header('Cache-Control: no-store');
|
||||
readfile($path);
|
||||
exit;
|
||||
|
||||
}
|
||||
@@ -286,8 +286,19 @@ $export_extra = [
|
||||
'dtt' => $date_filter_active ? $dtt : '',
|
||||
];
|
||||
|
||||
// Email the ticket mailbox couldn't take, waiting to be sorted (Tickets > Unprocessed Email) - not on a client's tickets
|
||||
$unprocessed_waiting = $client_url ? 0 : mailUnprocessedWaiting();
|
||||
|
||||
?>
|
||||
|
||||
<?php if ($unprocessed_waiting && $can_edit) { ?>
|
||||
<div class="alert alert-warning d-flex align-items-center gap-2 py-2 small" data-unprocessed-banner>
|
||||
<i class="fas fa-fw fa-envelope-open-text"></i>
|
||||
<span><strong><?= $unprocessed_waiting ?></strong> email<?= $unprocessed_waiting === 1 ? '' : 's' ?> the ticket mailbox couldn't make a ticket from <?= $unprocessed_waiting === 1 ? 'is' : 'are' ?> waiting to be sorted.</span>
|
||||
<a class="alert-link ms-auto text-nowrap" href="email_unprocessed.php">Sort <?= $unprocessed_waiting === 1 ? 'it' : 'them' ?></a>
|
||||
</div>
|
||||
<?php } ?>
|
||||
|
||||
<div class="card">
|
||||
<div class="card-header bg-dark py-2">
|
||||
<h3 class="card-title mt-2"><i class="fas fa-fw fa-life-ring me-2"></i>Tickets</h3>
|
||||
@@ -303,6 +314,12 @@ $export_extra = [
|
||||
<a class="dropdown-item" href="recurring_tickets.php<?= $client_url ? '?' . rtrim($client_url, '&') : '' ?>">
|
||||
<i class="fas fa-fw fa-redo-alt me-2"></i>Recurring Tickets
|
||||
</a>
|
||||
<?php if (!$client_url && mailUnprocessedReady()) { ?>
|
||||
<a class="dropdown-item d-flex align-items-center" href="email_unprocessed.php" data-unprocessed-link>
|
||||
<i class="fas fa-fw fa-envelope-open-text me-2"></i>Unprocessed Email
|
||||
<?php if ($unprocessed_waiting) { ?><span class="badge rounded-pill text-bg-warning ms-auto ps-2"><?= $unprocessed_waiting ?></span><?php } ?>
|
||||
</a>
|
||||
<?php } ?>
|
||||
<a class="dropdown-item ajax-modal" href="#"
|
||||
data-modal-url="<?= buildExportModalUrl('modals/ticket/ticket_export.php', ['client_id', 'client', 'status', 'billing', 'category', 'priority', 'assigned', 'sla', 'project', 'tags', 'q'], $export_extra) ?>">
|
||||
<i class="fas fa-fw fa-download me-2"></i>Export
|
||||
|
||||
@@ -185,6 +185,9 @@ mysqli_query($mysqli, "DELETE FROM email_queue WHERE email_queued_at < CURDATE()
|
||||
// Mail passwords and tokens still saved as typed - while config.php had no backup key - encrypted once it has one (functions/mail_secret.php)
|
||||
mailSecretsSealAll();
|
||||
|
||||
// Unprocessed email (Tickets > Unprocessed Email) sorted or dismissed a month ago, and ones nobody sorted in three - their copies too (functions/mail_unprocessed.php)
|
||||
mailUnprocessedCleanup();
|
||||
|
||||
// Clean-up the PDFs made to go with billing emails - sent or given up on by now
|
||||
billingEmailPdfCleanup(7);
|
||||
|
||||
|
||||
@@ -602,6 +602,38 @@ function addReplyAgentToClient($ticket_id, $reply_id, $user_id, array $to_client
|
||||
triggerCustomAction('reply_reply_agent_public', $ticket_id);
|
||||
}
|
||||
|
||||
/*
|
||||
* An email the parser couldn't take - kept for agents to sort (mailUnprocessedKeep(), functions/mail_unprocessed.php), $why
|
||||
* it wasn't, and moved to the ITFlow folder ($folder) like the rest. One kept already - an agent's ask that couldn't be
|
||||
* done - waits again, saying why. When it can't be kept - before the 4.3.2 update, or the copy can't be written - it is
|
||||
* left flagged and unread in the mailbox, as it always was.
|
||||
*/
|
||||
function mailUnprocessedLeave($message, $why, $folder) {
|
||||
$raw = (string) $message;
|
||||
$from = $message->from();
|
||||
$text = trim(preg_replace('/\s+/', ' ', (string) ($message->text() ?: strip_tags((string) $message->html()))));
|
||||
$date = $message->date();
|
||||
$meta = [
|
||||
'message_id' => ticketMailIdClean((string) $message->messageId()),
|
||||
'from_email' => (string) ($from?->email() ?? ''),
|
||||
'from_name' => (string) ($from?->name() ?? ''),
|
||||
'subject' => (string) ($message->subject() ?? ''),
|
||||
'received_at' => $date ? $date->setTimezone(date_default_timezone_get())->format('Y-m-d H:i:s') : '',
|
||||
'preview' => mb_substr($text, 0, 300),
|
||||
];
|
||||
if ($message instanceof MailUnprocessedMessage) {
|
||||
mailUnprocessedKeep($raw, $meta, $why, $message->uid());
|
||||
return;
|
||||
}
|
||||
if (mailUnprocessedKeep($raw, $meta, $why)) {
|
||||
$message->markSeen();
|
||||
$message->move($folder);
|
||||
return;
|
||||
}
|
||||
$message->markFlagged();
|
||||
$message->unmarkSeen();
|
||||
}
|
||||
|
||||
/** ------------------------------------------------------------------
|
||||
* OAuth helpers + provider guard
|
||||
* ------------------------------------------------------------------ */
|
||||
@@ -921,6 +953,18 @@ if (count($messages) < $max_emails_per_run) {
|
||||
}
|
||||
}
|
||||
|
||||
// The email kept for agents to sort that one asked about (Tickets > Unprocessed Email, functions/mail_unprocessed.php) - made
|
||||
// a ticket, added to one or tried again, taken from its copy as an email in the mailbox is
|
||||
require_once "../functions/mail_unprocessed_message.php";
|
||||
foreach (mailUnprocessedAsked(20) as $asked_row) {
|
||||
$asked_path = mailUnprocessedPath($asked_row['email_unprocessed_file']);
|
||||
if ($asked_path === '' || !is_file($asked_path)) {
|
||||
mailUnprocessedKeep('', [], 'Its copy is missing, so it can\'t be taken - it is in the mailbox\'s ITFlow folder', $asked_row['email_unprocessed_id']);
|
||||
continue;
|
||||
}
|
||||
$messages[] = new MailUnprocessedMessage($asked_row, (string) file_get_contents($asked_path));
|
||||
}
|
||||
|
||||
// ITFlow's own addresses - mail from one of them is its own come back (emailOwnAddresses())
|
||||
$own_addresses = emailOwnAddresses();
|
||||
|
||||
@@ -1003,6 +1047,9 @@ foreach ($messages as $message) {
|
||||
if ($email_message_id !== '' && ($seen_ticket_id = ticketMailIdTicket($email_message_id))) {
|
||||
logApp("Cron-Email-Parser", "info", "Email parser skipped a second copy of an email from $from_email ($subject) - it is on ticket ID $seen_ticket_id already");
|
||||
$processed_count++;
|
||||
if ($message instanceof MailUnprocessedMessage) {
|
||||
$message->ticket_id = intval($seen_ticket_id);
|
||||
}
|
||||
$message->markSeen();
|
||||
$message->move($targetFolderPath);
|
||||
continue;
|
||||
@@ -1084,21 +1131,66 @@ foreach ($messages as $message) {
|
||||
|
||||
$email['dropped'] = $dropped;
|
||||
|
||||
// What an agent asked for an email kept for them (Tickets > Unprocessed Email) - a ticket, or a reply on one - is all that
|
||||
// is done with it. Tried again, it goes the usual way. One that can't be done waits again, saying why ($asked_failed)
|
||||
$asked = $message instanceof MailUnprocessedMessage ? $message->asked() : '';
|
||||
$asked_only = in_array($asked, ['reply', 'ticket'], true);
|
||||
$asked_failed = '';
|
||||
if ($asked === 'reply') {
|
||||
$asked_ticket = ticketRow(intval($message->row['email_unprocessed_action_ticket_id']));
|
||||
if (!$asked_ticket) {
|
||||
$asked_failed = 'The ticket it was to go on is gone';
|
||||
} else {
|
||||
$asked_from = $answer ? stripslashes($answer['email']) : stripslashes($from_email);
|
||||
// The sender made a CC, so it is their reply - else a note from someone who isn't on the ticket
|
||||
if (intval($message->row['email_unprocessed_action_add']) && filter_var($asked_from, FILTER_VALIDATE_EMAIL)) {
|
||||
ticketAddCcs(intval($asked_ticket['ticket_id']), [$asked_from]);
|
||||
}
|
||||
$email_processed = addReply($answer ? $answer['email'] : $from_email, $date, $subject, intval($asked_ticket['ticket_id']), $message_body, $attachments, $original_message_file, $email);
|
||||
$message->ticket_id = intval($asked_ticket['ticket_id']);
|
||||
}
|
||||
} elseif ($asked === 'ticket') {
|
||||
$asked_client_id = intval($message->row['email_unprocessed_action_client_id']);
|
||||
$asked_contact = intval($message->row['email_unprocessed_action_contact_id'])
|
||||
? mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT contact_id, contact_name, contact_email, contact_client_id FROM contacts WHERE contact_id = " . intval($message->row['email_unprocessed_action_contact_id']) . " AND contact_archived_at IS NULL"))
|
||||
: null;
|
||||
$asked_name = $answer ? $answer['name'] : $from_name;
|
||||
$asked_email = $answer ? $answer['email'] : $from_email;
|
||||
if ($asked_client_id && !mysqli_num_rows(mysqli_query($mysqli, "SELECT 1 FROM clients WHERE client_id = $asked_client_id AND client_archived_at IS NULL"))) {
|
||||
$asked_failed = 'The client it was to go to is gone, or archived';
|
||||
} elseif ($asked_contact) {
|
||||
$email_processed = addTicket(intval($asked_contact['contact_id']), escapeSql($asked_contact['contact_name']), escapeSql($asked_contact['contact_email']), intval($asked_contact['contact_client_id']),
|
||||
$date, $subject, $message_body, $attachments, $original_message_file, $email);
|
||||
} elseif ($asked_client_id && intval($message->row['email_unprocessed_action_add']) && stripslashes($asked_email) !== '') {
|
||||
// The sender made a contact at the client first - their name cut to the column's 200 characters, escaped once
|
||||
$new_contact_name = mysqli_real_escape_string($mysqli, rtrim(mb_substr(stripslashes($asked_name === 'Unknown' ? $asked_email : $asked_name), 0, 200)));
|
||||
mysqli_query($mysqli, "INSERT INTO contacts SET contact_name = '$new_contact_name', contact_email = '" . mysqli_real_escape_string($mysqli, mb_substr(stripslashes($asked_email), 0, 200)) . "',
|
||||
contact_notes = 'Added from Unprocessed Email.', contact_client_id = $asked_client_id");
|
||||
$new_contact_id = intval(mysqli_insert_id($mysqli));
|
||||
logAudit("Contact", "Create", "Email parser: created contact $new_contact_name from an unprocessed email", $asked_client_id, $new_contact_id);
|
||||
triggerCustomAction('contact_create', $new_contact_id);
|
||||
$email_processed = addTicket($new_contact_id, $new_contact_name, mysqli_real_escape_string($mysqli, mb_substr(stripslashes($asked_email), 0, 200)), $asked_client_id,
|
||||
$date, $subject, $message_body, $attachments, $original_message_file, $email);
|
||||
} else {
|
||||
$email_processed = addTicket(0, $asked_name, $asked_email, $asked_client_id, $date, $subject, $message_body, $attachments, $original_message_file, $email);
|
||||
}
|
||||
}
|
||||
|
||||
// 1. A reply in a ticket's conversation - it answers one of the emails on the ticket, by its In-Reply-To or
|
||||
// References - whatever its subject says (functions/ticket_mail_thread.php)
|
||||
$thread_ticket_id = ticketMailHeaderTicket($in_reply_to, $references);
|
||||
$thread_ticket_id = !in_array($asked, ['reply', 'ticket'], true) ? ticketMailHeaderTicket($in_reply_to, $references) : 0;
|
||||
if ($thread_ticket_id) {
|
||||
$email['threaded'] = true;
|
||||
$email_processed = addReply($from_email, $date, $subject, $thread_ticket_id, $message_body, $attachments, $original_message_file, $email);
|
||||
}
|
||||
|
||||
// 2. Reply to existing ticket with the number in subject - with the prefix that ticket was given
|
||||
if (!$email_processed && ($subject_ticket = ticketMailSubjectTicket(stripslashes($subject)))) {
|
||||
if (!$email_processed && !$asked_only && ($subject_ticket = ticketMailSubjectTicket(stripslashes($subject)))) {
|
||||
$email_processed = addReply($from_email, $date, $subject, $subject_ticket['ticket_id'], $message_body, $attachments, $original_message_file, $email);
|
||||
}
|
||||
|
||||
// An automatic reply - an out-of-office - that answers no ticket is set aside: it isn't a ticket, and isn't answered
|
||||
if (!$email_processed && $automatic === 'auto-reply') {
|
||||
if (!$email_processed && !$asked_only && $automatic === 'auto-reply') {
|
||||
logApp("Cron-Email-Parser", "info", "Email parser set aside an automatic reply from $from_email ($subject) - it answers no ticket");
|
||||
$email_processed = true;
|
||||
}
|
||||
@@ -1116,7 +1208,7 @@ foreach ($messages as $message) {
|
||||
$domain_row = $domain_row && strcasecmp($from_domain, $domain_row['domain_name']) === 0 ? $domain_row : null;
|
||||
}
|
||||
$similar_ticket_id = 0;
|
||||
if (!$email_processed && strlen(trim($subject)) > 10) {
|
||||
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);
|
||||
$from_email_esc = mysqli_real_escape_string($mysqli, $from_email);
|
||||
@@ -1153,7 +1245,7 @@ foreach ($messages as $message) {
|
||||
|
||||
// 4. A known, registered contact? A website form sent as one - an address made a contact before - is for that
|
||||
// contact's client, from its visitor
|
||||
if (!$email_processed && $contact_row) {
|
||||
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);
|
||||
@@ -1167,7 +1259,7 @@ foreach ($messages as $message) {
|
||||
|
||||
// 5. A known domain? Not a forged one: anyone could make themselves a client's contact by saying they are from its domain.
|
||||
// A website form's is the client's ticket, from its visitor - the site isn't made a contact
|
||||
if (!$email_processed && $domain_row && mb_strlen($from_raw) <= 200 && $forged === '') {
|
||||
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);
|
||||
@@ -1188,7 +1280,7 @@ foreach ($messages as $message) {
|
||||
|
||||
// 6. Unknown sender allowed? A ticket with no client - a mail server's bounce never gets here. A website form's from its
|
||||
// visitor; one with no sender address from nobody, answered by nobody
|
||||
if (!$email_processed && $config_ticket_email_parse_unknown_senders) {
|
||||
if (!$email_processed && !$asked_only && $config_ticket_email_parse_unknown_senders) {
|
||||
$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);
|
||||
@@ -1203,6 +1295,10 @@ foreach ($messages as $message) {
|
||||
// Flag/move based on processing result
|
||||
if ($email_processed) {
|
||||
$processed_count++; // increment first so a move failure doesn't hide the success
|
||||
// One an agent asked about is sorted - on the ticket it went on
|
||||
if ($message instanceof MailUnprocessedMessage) {
|
||||
$message->ticket_id = intval(($email_message_id !== '' ? ticketMailIdTicket($email_message_id) : 0) ?: (is_int($email_processed) ? $email_processed : $message->ticket_id));
|
||||
}
|
||||
try {
|
||||
$message->markSeen();
|
||||
// Move to the top-level "ITFlow" folder
|
||||
@@ -1219,22 +1315,28 @@ foreach ($messages as $message) {
|
||||
);
|
||||
}
|
||||
} else {
|
||||
// Not taken - kept for agents to sort (Tickets > Unprocessed Email), and out of the inbox like the rest
|
||||
$unprocessed_count++;
|
||||
try {
|
||||
$message->markFlagged();
|
||||
$message->unmarkSeen();
|
||||
} catch (\Throwable $e) {
|
||||
logApp("Cron-Email-Parser", "warning", "Flag update failed: ".$e->getMessage());
|
||||
if ($asked_failed !== '') {
|
||||
$why = $asked_failed;
|
||||
} elseif ($asked_only) {
|
||||
$why = 'It couldn\'t be ' . ($asked === 'reply' ? 'added to the ticket' : 'made a ticket') . ' - try again, or pick something else';
|
||||
} elseif ($config_ticket_email_parse_unknown_senders || $contact_row) {
|
||||
$why = 'It couldn\'t be made a ticket';
|
||||
} elseif ($domain_row && $forged !== '') {
|
||||
$why = "Its sender checks failed - $forged - so it isn't taken as from the client whose domain it is from";
|
||||
} else {
|
||||
$why = 'From someone who isn\'t a contact, at a domain no client has';
|
||||
}
|
||||
mailUnprocessedLeave($message, $why, $targetFolderPath);
|
||||
}
|
||||
|
||||
} catch (\Throwable $e) {
|
||||
// One bad message must not kill the whole run - flag it for manual attention and continue
|
||||
// One bad message must not kill the whole run - kept for agents to sort, saying why, and on with the next
|
||||
$unprocessed_count++;
|
||||
logApp("Cron-Email-Parser", "warning", "Email parser failed to process message UID " . $message->uid() . ": " . $e->getMessage());
|
||||
try {
|
||||
$message->markFlagged();
|
||||
$message->unmarkSeen();
|
||||
mailUnprocessedLeave($message, 'It couldn\'t be taken: ' . $e->getMessage(), $targetFolderPath);
|
||||
} catch (\Throwable $e2) {
|
||||
// ignore
|
||||
}
|
||||
@@ -1262,8 +1364,9 @@ $execution_time = $script_end_time - $script_start_time;
|
||||
$execution_time_formatted = number_format($execution_time, 2);
|
||||
|
||||
// What the run did, for whoever runs it by hand - not App Logs, where it was an entry a minute
|
||||
// while mail came in. Each email processed is a ticket or a reply; one that isn't is left
|
||||
// flagged and unread in the inbox, and one that failed outright was logged above
|
||||
// while mail came in. Each email processed is a ticket or a reply; one that isn't is kept for agents to sort
|
||||
// (Tickets > Unprocessed Email) - or left flagged and unread in the inbox before the 4.3.2 update - and one that failed
|
||||
// outright was logged above
|
||||
echo "Processed Emails: $processed_count\n";
|
||||
echo "Unprocessed Emails: $unprocessed_count\n";
|
||||
echo "Took $execution_time_formatted seconds\n";
|
||||
|
||||
33
db.sql
33
db.sql
@@ -1785,6 +1785,39 @@ CREATE TABLE `email_queue` (
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;
|
||||
/*!40101 SET character_set_client = @saved_cs_client */;
|
||||
|
||||
--
|
||||
-- Table structure for table `email_unprocessed`
|
||||
--
|
||||
|
||||
DROP TABLE IF EXISTS `email_unprocessed`;
|
||||
/*!40101 SET @saved_cs_client = @@character_set_client */;
|
||||
/*!40101 SET character_set_client = utf8mb4 */;
|
||||
CREATE TABLE `email_unprocessed` (
|
||||
`email_unprocessed_id` int(11) NOT NULL AUTO_INCREMENT,
|
||||
`email_unprocessed_message_id` varchar(255) NOT NULL DEFAULT '',
|
||||
`email_unprocessed_from_email` varchar(255) NOT NULL DEFAULT '',
|
||||
`email_unprocessed_from_name` varchar(255) NOT NULL DEFAULT '',
|
||||
`email_unprocessed_subject` varchar(500) NOT NULL DEFAULT '',
|
||||
`email_unprocessed_preview` varchar(500) NOT NULL DEFAULT '',
|
||||
`email_unprocessed_received_at` datetime DEFAULT NULL,
|
||||
`email_unprocessed_reason` varchar(500) NOT NULL DEFAULT '',
|
||||
`email_unprocessed_file` varchar(255) NOT NULL DEFAULT '',
|
||||
`email_unprocessed_action` varchar(20) NOT NULL DEFAULT '',
|
||||
`email_unprocessed_action_client_id` int(11) NOT NULL DEFAULT 0,
|
||||
`email_unprocessed_action_contact_id` int(11) NOT NULL DEFAULT 0,
|
||||
`email_unprocessed_action_ticket_id` int(11) NOT NULL DEFAULT 0,
|
||||
`email_unprocessed_action_add` tinyint(1) NOT NULL DEFAULT 0,
|
||||
`email_unprocessed_action_by` int(11) NOT NULL DEFAULT 0,
|
||||
`email_unprocessed_action_at` datetime DEFAULT NULL,
|
||||
`email_unprocessed_done_at` datetime DEFAULT NULL,
|
||||
`email_unprocessed_ticket_id` int(11) NOT NULL DEFAULT 0,
|
||||
`email_unprocessed_created_at` datetime NOT NULL DEFAULT current_timestamp(),
|
||||
PRIMARY KEY (`email_unprocessed_id`),
|
||||
KEY `email_unprocessed_done_at` (`email_unprocessed_done_at`,`email_unprocessed_action`),
|
||||
KEY `email_unprocessed_message_id` (`email_unprocessed_message_id`)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;
|
||||
/*!40101 SET character_set_client = @saved_cs_client */;
|
||||
|
||||
--
|
||||
-- Table structure for table `expense_import_rules`
|
||||
--
|
||||
|
||||
@@ -148,6 +148,7 @@ require_once __DIR__ . '/functions/getting_started.php';
|
||||
require_once __DIR__ . '/functions/settings.php';
|
||||
require_once __DIR__ . '/functions/mail_queue.php';
|
||||
require_once __DIR__ . '/functions/mail_secret.php';
|
||||
require_once __DIR__ . '/functions/mail_unprocessed.php';
|
||||
require_once __DIR__ . '/functions/mail_graph.php';
|
||||
require_once __DIR__ . '/functions/purchase_orders.php';
|
||||
require_once __DIR__ . '/functions/kb.php';
|
||||
|
||||
246
functions/mail_unprocessed.php
Normal file
246
functions/mail_unprocessed.php
Normal file
@@ -0,0 +1,246 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* ITFlow - email the ticket mailbox couldn't take (database 4.3.2, email_unprocessed). From someone who isn't a
|
||||
* contact, at a domain no client has, while email from unknown senders isn't taken - or one that failed - was left
|
||||
* flagged and unread in the mailbox, where nobody in ITFlow saw it. Now the email parser (cron/ticket_email_parser.php)
|
||||
* keeps a copy (uploads/mail_unprocessed/) and moves it to the mailbox's ITFlow folder like the rest, and it waits on
|
||||
* Tickets > Unprocessed Email (agent/email_unprocessed.php) for someone to sort:
|
||||
*
|
||||
* ticket make it a ticket - for a client, with the sender made a contact there or not, or for no client
|
||||
* reply add it to a ticket - the sender made a CC on it or not
|
||||
* retry take it again as any email is - after the sender is made a contact, say, or unknown senders let in
|
||||
* dismiss nothing - spam, or nothing to act on
|
||||
*
|
||||
* The first three are done by the parser on its next run, within a minute, from the copy - the same as an email in
|
||||
* the mailbox, so a ticket made this way is answered, numbered and noted as any other. One it still can't take
|
||||
* waits again, saying why. Sorted and dismissed ones are kept MAIL_UNPROCESSED_KEEP_DAYS, then forgotten, file and all.
|
||||
*/
|
||||
|
||||
const MAIL_UNPROCESSED_DIR = 'uploads/mail_unprocessed';
|
||||
const MAIL_UNPROCESSED_KEEP_DAYS = 30;
|
||||
const MAIL_UNPROCESSED_ACTIONS = ['ticket' => 'Make a ticket', 'reply' => 'Add to a ticket', 'retry' => 'Try again', 'dismiss' => 'Dismiss'];
|
||||
|
||||
/** Whether the 4.3.2 update has run. */
|
||||
function mailUnprocessedReady() {
|
||||
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.2', '>=');
|
||||
}
|
||||
return $ready;
|
||||
}
|
||||
|
||||
/** Where its copy is kept - the full path, or '' for a name that isn't one of ours. */
|
||||
function mailUnprocessedPath($file) {
|
||||
$file = (string) $file;
|
||||
return preg_match('/^[A-Za-z0-9_-]+\.eml$/', $file) ? dirname(__DIR__) . '/' . MAIL_UNPROCESSED_DIR . '/' . $file : '';
|
||||
}
|
||||
|
||||
/*
|
||||
* Keep an email the parser couldn't take - $raw its MIME, $meta what it is (message_id, from_email, from_name, subject,
|
||||
* received_at 'Y-m-d H:i:s', preview), $reason why, in words. One kept already ($id, an agent's ask that failed) waits
|
||||
* again with the new reason; the same email again (its Message-ID) is the one row. Its id, or 0 when it couldn't be kept
|
||||
* - the parser then leaves it flagged in the mailbox, as before.
|
||||
*/
|
||||
function mailUnprocessedKeep($raw, array $meta, $reason, $id = 0) {
|
||||
global $mysqli;
|
||||
if (!mailUnprocessedReady()) {
|
||||
return 0;
|
||||
}
|
||||
$reason_sql = escapeSql(mb_substr((string) $reason, 0, 500));
|
||||
$id = intval($id);
|
||||
if (!$id && trim((string) ($meta['message_id'] ?? '')) !== '') {
|
||||
$id = intval(mysqli_fetch_row(mysqli_query($mysqli, "SELECT email_unprocessed_id FROM email_unprocessed
|
||||
WHERE email_unprocessed_message_id = '" . escapeSql(mb_substr((string) $meta['message_id'], 0, 255)) . "' AND email_unprocessed_done_at IS NULL LIMIT 1"))[0] ?? 0);
|
||||
}
|
||||
if ($id) {
|
||||
mysqli_query($mysqli, "UPDATE email_unprocessed SET email_unprocessed_reason = '$reason_sql', email_unprocessed_action = '', email_unprocessed_done_at = NULL
|
||||
WHERE email_unprocessed_id = $id");
|
||||
return $id;
|
||||
}
|
||||
$dir = dirname(__DIR__) . '/' . MAIL_UNPROCESSED_DIR;
|
||||
if (!is_dir($dir)) {
|
||||
@mkdir($dir, 0750, true);
|
||||
}
|
||||
// Never opened straight from the web - as uploads/backups (shipped, and put back if it went)
|
||||
if (!is_file("$dir/.htaccess")) {
|
||||
@file_put_contents("$dir/.htaccess", "Require all denied\nOptions -ExecCGI -Indexes\n<IfModule mod_php.c>\n php_flag engine off\n</IfModule>\n");
|
||||
@file_put_contents("$dir/index.php", "<?php // Silence is golden\n");
|
||||
}
|
||||
$file = randomString(40) . '.eml';
|
||||
if (@file_put_contents("$dir/$file", (string) $raw) === false) {
|
||||
return 0;
|
||||
}
|
||||
$text = function ($key, $length) use ($meta) {
|
||||
return escapeSql(mb_substr(trim((string) ($meta[$key] ?? '')), 0, $length));
|
||||
};
|
||||
$received = !empty($meta['received_at']) && strtotime((string) $meta['received_at']) ? "'" . date('Y-m-d H:i:s', strtotime((string) $meta['received_at'])) . "'" : 'NOW()';
|
||||
mysqli_query($mysqli, "INSERT INTO email_unprocessed SET email_unprocessed_message_id = '" . $text('message_id', 255) . "', email_unprocessed_from_email = '" . $text('from_email', 255) . "',
|
||||
email_unprocessed_from_name = '" . $text('from_name', 255) . "', email_unprocessed_subject = '" . $text('subject', 500) . "', email_unprocessed_preview = '" . $text('preview', 500) . "',
|
||||
email_unprocessed_received_at = $received, email_unprocessed_reason = '$reason_sql', email_unprocessed_file = '$file'");
|
||||
return intval(mysqli_insert_id($mysqli));
|
||||
}
|
||||
|
||||
/** A row by its id - null when there is none. */
|
||||
function mailUnprocessedRow($id) {
|
||||
global $mysqli;
|
||||
if (!mailUnprocessedReady()) {
|
||||
return null;
|
||||
}
|
||||
return mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT * FROM email_unprocessed WHERE email_unprocessed_id = " . intval($id))) ?: null;
|
||||
}
|
||||
|
||||
/*
|
||||
* What an agent asks for, for the emails $ids still waiting - $action one of MAIL_UNPROCESSED_ACTIONS; $opts client_id,
|
||||
* contact_id, add (make the sender a contact, or a CC), ticket_id. A dismissed one is done at once; the rest wait for
|
||||
* the parser. The ones asked for.
|
||||
*/
|
||||
function mailUnprocessedDecide(array $ids, $action, array $opts, $user_id) {
|
||||
global $mysqli;
|
||||
$ids = array_values(array_filter(array_map('intval', $ids)));
|
||||
if (!$ids || !isset(MAIL_UNPROCESSED_ACTIONS[$action]) || !mailUnprocessedReady()) {
|
||||
return [];
|
||||
}
|
||||
$list = implode(',', $ids);
|
||||
$done = $action === 'dismiss' ? 'NOW()' : 'NULL';
|
||||
mysqli_query($mysqli, "UPDATE email_unprocessed SET email_unprocessed_action = '$action',
|
||||
email_unprocessed_action_client_id = " . intval($opts['client_id'] ?? 0) . ", email_unprocessed_action_contact_id = " . intval($opts['contact_id'] ?? 0) . ",
|
||||
email_unprocessed_action_ticket_id = " . intval($opts['ticket_id'] ?? 0) . ", email_unprocessed_action_add = " . (!empty($opts['add']) ? 1 : 0) . ",
|
||||
email_unprocessed_action_by = " . intval($user_id) . ", email_unprocessed_action_at = NOW(), email_unprocessed_done_at = $done
|
||||
WHERE email_unprocessed_id IN ($list) AND email_unprocessed_done_at IS NULL");
|
||||
$asked = [];
|
||||
$sql = mysqli_query($mysqli, "SELECT email_unprocessed_id FROM email_unprocessed WHERE email_unprocessed_id IN ($list) AND email_unprocessed_action = '$action'");
|
||||
while ($row = mysqli_fetch_row($sql)) {
|
||||
$asked[] = intval($row[0]);
|
||||
}
|
||||
return $asked;
|
||||
}
|
||||
|
||||
/* The ones an agent asked the parser to take - ticket, reply or retry, not done - oldest ask first. */
|
||||
function mailUnprocessedAsked($limit = 20) {
|
||||
global $mysqli;
|
||||
if (!mailUnprocessedReady()) {
|
||||
return [];
|
||||
}
|
||||
$rows = [];
|
||||
$sql = mysqli_query($mysqli, "SELECT * FROM email_unprocessed WHERE email_unprocessed_done_at IS NULL AND email_unprocessed_action IN ('ticket', 'reply', 'retry')
|
||||
ORDER BY email_unprocessed_action_at, email_unprocessed_id LIMIT " . max(1, intval($limit)));
|
||||
while ($row = mysqli_fetch_assoc($sql)) {
|
||||
$rows[] = $row;
|
||||
}
|
||||
return $rows;
|
||||
}
|
||||
|
||||
/* Done - taken by the parser, $ticket_id the ticket it went on (0 when it went on none: set aside, a bounce). */
|
||||
function mailUnprocessedDone($id, $ticket_id = 0) {
|
||||
global $mysqli;
|
||||
mysqli_query($mysqli, "UPDATE email_unprocessed SET email_unprocessed_done_at = NOW(), email_unprocessed_ticket_id = " . intval($ticket_id) . " WHERE email_unprocessed_id = " . intval($id));
|
||||
}
|
||||
|
||||
/** How many wait for someone - not done, not asked for. */
|
||||
function mailUnprocessedWaiting() {
|
||||
global $mysqli;
|
||||
if (!mailUnprocessedReady()) {
|
||||
return 0;
|
||||
}
|
||||
return intval(mysqli_fetch_row(mysqli_query($mysqli, "SELECT COUNT(*) FROM email_unprocessed WHERE email_unprocessed_done_at IS NULL AND email_unprocessed_action = ''"))[0] ?? 0);
|
||||
}
|
||||
|
||||
/*
|
||||
* A row's state - ['key', 'label', 'badge', 'detail']: waiting (for someone), asked (for the parser - within a minute),
|
||||
* done (a ticket, or set aside) or dismissed.
|
||||
*/
|
||||
function mailUnprocessedState(array $row) {
|
||||
$action = (string) $row['email_unprocessed_action'];
|
||||
if ($action === 'dismiss') {
|
||||
return ['key' => 'dismissed', 'label' => 'Dismissed', 'badge' => 'text-bg-secondary', 'detail' => ''];
|
||||
}
|
||||
if (!empty($row['email_unprocessed_done_at'])) {
|
||||
return ['key' => 'done', 'label' => 'Sorted', 'badge' => 'text-bg-success', 'detail' => intval($row['email_unprocessed_ticket_id']) ? '' : 'Set aside - it needed no ticket'];
|
||||
}
|
||||
if ($action !== '') {
|
||||
return ['key' => 'asked', 'label' => MAIL_UNPROCESSED_ACTIONS[$action] ?? 'Asked', 'badge' => 'text-bg-info', 'detail' => 'Within a minute'];
|
||||
}
|
||||
return ['key' => 'waiting', 'label' => 'To sort', 'badge' => 'text-bg-warning', 'detail' => ''];
|
||||
}
|
||||
|
||||
/*
|
||||
* The email from its copy, to show - ['fields' => [label => value], 'text', 'headers', 'attachments' => [names],
|
||||
* 'missing' => bool, 'too_big' => bool].
|
||||
*/
|
||||
function mailUnprocessedRead(array $row) {
|
||||
$path = mailUnprocessedPath($row['email_unprocessed_file'] ?? '');
|
||||
$out = ['fields' => [], 'text' => '', 'headers' => '', 'attachments' => [], 'missing' => $path === '' || !is_file($path), 'too_big' => false];
|
||||
if ($out['missing']) {
|
||||
return $out;
|
||||
}
|
||||
if (filesize($path) > 25 * 1024 * 1024) {
|
||||
$out['too_big'] = true;
|
||||
return $out;
|
||||
}
|
||||
$raw = (string) file_get_contents($path);
|
||||
require_once dirname(__DIR__) . '/libs/vendor/autoload.php'; // ImapEngine
|
||||
$out['headers'] = preg_split("/\r?\n\r?\n/", $raw, 2)[0] ?? '';
|
||||
try {
|
||||
$message = new \DirectoryTree\ImapEngine\FileMessage($raw);
|
||||
$people = function ($addresses) {
|
||||
return implode(', ', array_map(function ($address) {
|
||||
$name = trim((string) $address->name());
|
||||
return $name !== '' ? "$name <" . $address->email() . '>' : (string) $address->email();
|
||||
}, array_filter((array) $addresses)));
|
||||
};
|
||||
$from = $message->from();
|
||||
$reply_to = $message->replyTo();
|
||||
$out['fields'] = array_filter([
|
||||
'From' => $from ? $people([$from]) : '',
|
||||
'Reply-To' => $reply_to ? $people([$reply_to]) : '',
|
||||
'To' => $people($message->to()),
|
||||
'Cc' => $people($message->cc()),
|
||||
'Date' => $message->date() ? $message->date()->format('Y-m-d H:i:s T') : '',
|
||||
'Subject' => (string) $message->subject(),
|
||||
], function ($value) { return $value !== ''; });
|
||||
$text = (string) $message->text();
|
||||
if (trim($text) === '' && $message->html()) {
|
||||
$html = preg_replace('/<(style|script|head)\b[^>]*>.*?<\/\1>/is', '', (string) $message->html());
|
||||
$html = preg_replace('/<(br|\/p|\/div|\/tr|\/li|\/h[1-6])[^>]*>/i', "\n", $html);
|
||||
$text = html_entity_decode(strip_tags($html), ENT_QUOTES, 'UTF-8');
|
||||
}
|
||||
$out['text'] = trim(preg_replace("/\n{3,}/", "\n\n", str_replace("\r", '', $text)));
|
||||
foreach ($message->attachments() as $part) {
|
||||
$out['attachments'][] = (string) ($part->filename() ?: 'attachment');
|
||||
}
|
||||
} catch (Throwable $e) {
|
||||
$out['text'] = '';
|
||||
}
|
||||
return $out;
|
||||
}
|
||||
|
||||
/*
|
||||
* The nightly clean-up: sorted and dismissed ones MAIL_UNPROCESSED_KEEP_DAYS after, and ones nobody sorted three times
|
||||
* as long - their copies too. How many went.
|
||||
*/
|
||||
function mailUnprocessedCleanup() {
|
||||
global $mysqli;
|
||||
if (!mailUnprocessedReady()) {
|
||||
return 0;
|
||||
}
|
||||
$days = MAIL_UNPROCESSED_KEEP_DAYS;
|
||||
$sql = mysqli_query($mysqli, "SELECT email_unprocessed_id, email_unprocessed_file FROM email_unprocessed
|
||||
WHERE (email_unprocessed_done_at IS NOT NULL AND email_unprocessed_done_at < NOW() - INTERVAL $days DAY)
|
||||
OR (email_unprocessed_done_at IS NULL AND email_unprocessed_created_at < NOW() - INTERVAL " . ($days * 3) . " DAY)");
|
||||
$ids = [];
|
||||
while ($row = mysqli_fetch_assoc($sql)) {
|
||||
$path = mailUnprocessedPath($row['email_unprocessed_file']);
|
||||
if ($path !== '' && is_file($path)) {
|
||||
@unlink($path);
|
||||
}
|
||||
$ids[] = intval($row['email_unprocessed_id']);
|
||||
}
|
||||
if ($ids) {
|
||||
mysqli_query($mysqli, "DELETE FROM email_unprocessed WHERE email_unprocessed_id IN (" . implode(',', $ids) . ")");
|
||||
}
|
||||
return count($ids);
|
||||
}
|
||||
46
functions/mail_unprocessed_message.php
Normal file
46
functions/mail_unprocessed_message.php
Normal file
@@ -0,0 +1,46 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* An email kept for agents to sort (functions/mail_unprocessed.php), taken by the email parser from its copy when an
|
||||
* agent asks - as ImapEngine reads it, with what the parser does to a mailbox's email done to its row instead: moved
|
||||
* (taken) is sorted, with the ticket it went on ($ticket_id). Required by cron/ticket_email_parser.php after ImapEngine.
|
||||
*/
|
||||
|
||||
use DirectoryTree\ImapEngine\FileMessage;
|
||||
|
||||
class MailUnprocessedMessage extends FileMessage {
|
||||
|
||||
public array $row;
|
||||
public int $ticket_id = 0;
|
||||
|
||||
public function __construct(array $row, $mime) {
|
||||
parent::__construct((string) $mime);
|
||||
$this->row = $row;
|
||||
}
|
||||
|
||||
/* What the agent asked for - ticket, reply or retry */
|
||||
public function asked(): string {
|
||||
return (string) $this->row['email_unprocessed_action'];
|
||||
}
|
||||
|
||||
/* Its row's id, for the logs as a mailbox email's UID is */
|
||||
public function uid(): int {
|
||||
return intval($this->row['email_unprocessed_id']);
|
||||
}
|
||||
|
||||
/* The raw body (all after the headers) - the parser's last resort for an email with no text or HTML part */
|
||||
public function body(): string {
|
||||
$parts = preg_split("/\r?\n\r?\n/", $this->contents, 2);
|
||||
return $parts[1] ?? '';
|
||||
}
|
||||
|
||||
/* Read, flagged - nothing to mark: it is in no mailbox */
|
||||
public function flag(BackedEnum|string $flag, string $operation, bool $expunge = false): void {
|
||||
}
|
||||
|
||||
/* Taken - sorted, on the ticket it went on */
|
||||
public function move(string $folder, bool $expunge = false): ?int {
|
||||
mailUnprocessedDone($this->uid(), $this->ticket_id);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -24,7 +24,7 @@
|
||||
* domain it is, else where they last raised a ticket (ticketMailSenderContact());
|
||||
* 5. an address at a client's domain - a new contact, and a ticket;
|
||||
* 6. anyone else - a ticket with no client when unknown senders are let in,
|
||||
* else left in the mailbox, flagged.
|
||||
* else kept in Tickets > Unprocessed Email (functions/mail_unprocessed.php).
|
||||
*
|
||||
* Kept in step with the parser by hand - change one, change the other. A Reply-To (ticketMailReplyTo())
|
||||
* can't be typed in here.
|
||||
@@ -150,8 +150,8 @@ function ticketMailTry($from_email, $subject, $auto_reply = false) {
|
||||
// 6. Anyone else
|
||||
if (!$config_ticket_email_parse_unknown_senders) {
|
||||
$steps[] = ['Tickets from unknown senders?', 'Off'];
|
||||
return ['steps' => $steps, 'outcome' => ['fa-flag', 'warning', 'Left in the mailbox, flagged',
|
||||
'Unread and flagged for someone to look at. Turn on Tickets from unknown senders to make them tickets with no client.']];
|
||||
return ['steps' => $steps, 'outcome' => ['fa-envelope-open-text', 'warning', 'Kept for your team to sort',
|
||||
'It waits in Tickets > Unprocessed Email, where it can be made a ticket at a client, added to a ticket or dismissed. Turn on Tickets from unknown senders to make them tickets with no client.']];
|
||||
}
|
||||
$steps[] = ['Tickets from unknown senders?', 'On'];
|
||||
return ['steps' => $steps, 'outcome' => ['fa-plus-circle', 'success', 'A new ticket with no client',
|
||||
|
||||
5
uploads/mail_unprocessed/.htaccess
Normal file
5
uploads/mail_unprocessed/.htaccess
Normal file
@@ -0,0 +1,5 @@
|
||||
Require all denied
|
||||
Options -ExecCGI -Indexes
|
||||
<IfModule mod_php.c>
|
||||
php_flag engine off
|
||||
</IfModule>
|
||||
1
uploads/mail_unprocessed/index.php
Normal file
1
uploads/mail_unprocessed/index.php
Normal file
@@ -0,0 +1 @@
|
||||
<?php // Silence is golden
|
||||
Reference in New Issue
Block a user