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\n php_flag engine off\n\n"); @file_put_contents("$dir/index.php", " '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); }