Files
itflow/functions/mail_unprocessed.php

247 lines
12 KiB
PHP

<?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);
}