Files
itflow/functions/ticket_mail_thread.php

446 lines
23 KiB
PHP

<?php
/*
* ITFlow - one email conversation per ticket.
*
* Every email to a client about a ticket has the same subject - its number in brackets, then its
* subject: "[TCK-12] Printer offline" (ticketEmailSubject()) - so a mail program keeps them
* together, where a subject that changed with each email ("Ticket update - ...", "Ticket resolved
* - ... | (pending closure)") split them up. Each carries the headers a conversation is kept
* together by: a Message-ID of its own, and In-Reply-To and References naming the emails before it
* on the ticket (ticketMailHeaders()).
*
* Those Message-IDs are kept with the ticket (ticket_mail_threads, database 4.2.6) - ITFlow's own,
* and the client's: the email that raised it, each reply. So the Ticket Email Parser finds the
* ticket an email answers by its In-Reply-To and References first (ticketMailHeaderTicket()) -
* a reply whose subject was changed, or a reply to all on the client's first email that never had
* a number - then by the number in its subject, with whatever prefix the ticket was given
* (ticketMailSubjectTicket()), as a prefix changed later left older tickets unanswerable.
*
* A merged ticket's conversation goes with it to the ticket it was merged into (ticketMergeInto()).
*/
/** The most Message-IDs an email's References names - the first on the ticket, and the latest. */
const TICKET_MAIL_REFERENCES = 10;
/** Whether the 4.2.6 update has run - ticket_mail_threads, and the mail queue's copied-in people and headers. */
function ticketMailThreadReady() {
global $mysqli;
static $ready = null;
if ($ready === null) {
if (defined('CURRENT_DATABASE_VERSION')) {
$version = CURRENT_DATABASE_VERSION;
} else {
$result = mysqli_query($mysqli, "SELECT config_current_database_version FROM settings WHERE company_id = 1");
$version = $result && ($row = mysqli_fetch_row($result)) ? (string) $row[0] : '0';
}
$ready = version_compare($version, '4.2.6', '>=');
}
return $ready;
}
/** The subject of every email to a client about a ticket - "[TCK-12] Printer offline". $row has ticket_prefix, ticket_number and ticket_subject, raw. */
function ticketEmailSubject(array $row) {
return '[' . ticketReference($row) . '] ' . trim((string) ($row['ticket_subject'] ?? ''));
}
/*
* The ticket settings for its emails, read once - copy: one email, the CCs copied in (else
* one each); relay: a client's reply goes on to the CCs who didn't have it. Both on until
* the 4.2.6 update has made them, as they are by default after it.
*/
function ticketMailSettings() {
global $mysqli;
static $settings = null;
if ($settings === null) {
$row = ticketMailThreadReady() ? mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT config_ticket_email_copy, config_ticket_email_relay FROM settings WHERE company_id = 1")) : null;
$settings = ['copy' => intval($row['config_ticket_email_copy'] ?? 0) === 1, 'relay' => intval($row['config_ticket_email_relay'] ?? 0) === 1];
}
return $settings;
}
/*
* A Message-ID as kept - without its <>, trimmed, '' when it isn't one (no @, a space, too long).
*/
function ticketMailIdClean($message_id) {
$message_id = trim(trim((string) $message_id), '<>');
if ($message_id === '' || strlen($message_id) > 255 || strpos($message_id, '@') === false || preg_match('/[\s<>"]/', $message_id)) {
return '';
}
return $message_id;
}
/** The Message-IDs in a header - In-Reply-To or References - in the order they are written, each once, cleaned (ticketMailIdClean()). */
function ticketMailIdsIn($header) {
$ids = [];
// In <>, as they should be - or, from a mail program that leaves them off, each word with an @
if (preg_match_all('/<([^<>\s]+)>/', (string) $header, $matches) || preg_match_all('/([^<>\s]+@[^<>\s]+)/', (string) $header, $matches)) {
foreach ($matches[1] as $message_id) {
$message_id = ticketMailIdClean($message_id);
if ($message_id !== '' && !in_array($message_id, $ids, true)) {
$ids[] = $message_id;
}
}
}
return $ids;
}
/** Keep a Message-ID with a ticket - $ours for an email ITFlow sent. Once a ticket. */
function ticketMailKeepId($ticket_id, $message_id, $ours = false) {
global $mysqli;
$ticket_id = intval($ticket_id);
$message_id = ticketMailIdClean($message_id);
if (!$ticket_id || $message_id === '' || !ticketMailThreadReady()) {
return;
}
mysqli_query($mysqli, "INSERT IGNORE INTO ticket_mail_threads SET mail_thread_ticket_id = $ticket_id, mail_thread_message_id = '" . mysqli_real_escape_string($mysqli, $message_id) . "', mail_thread_ours = " . ($ours ? 1 : 0));
}
/** The ticket a Message-ID is kept with - an email it has already, ITFlow's own or the client's. ticket_id, or 0. */
function ticketMailIdTicket($message_id) {
global $mysqli;
$message_id = ticketMailIdClean($message_id);
if ($message_id === '' || !ticketMailThreadReady()) {
return 0;
}
return intval(mysqli_fetch_row(mysqli_query($mysqli, "SELECT mail_thread_ticket_id FROM ticket_mail_threads JOIN tickets ON ticket_id = mail_thread_ticket_id
WHERE mail_thread_message_id = '" . mysqli_real_escape_string($mysqli, $message_id) . "' ORDER BY mail_thread_id DESC LIMIT 1"))[0] ?? 0);
}
/*
* Where a ticket's conversation stands, for the next email about it - ['in_reply_to' => the latest
* Message-ID on it, 'references' => the first and the latest few (TICKET_MAIL_REFERENCES), oldest
* first]. $answering, the Message-ID of the email being answered - a reply to a closed ticket -
* is the one it replies to. Empty before any email.
*/
function ticketMailThread($ticket_id, $answering = '') {
global $mysqli;
$ids = [];
if (ticketMailThreadReady()) {
$ticket_id = intval($ticket_id);
$first = mysqli_fetch_row(mysqli_query($mysqli, "SELECT mail_thread_message_id FROM ticket_mail_threads WHERE mail_thread_ticket_id = $ticket_id ORDER BY mail_thread_id LIMIT 1"));
$latest = mysqli_fetch_all(mysqli_query($mysqli, "SELECT mail_thread_message_id FROM ticket_mail_threads WHERE mail_thread_ticket_id = $ticket_id
ORDER BY mail_thread_id DESC LIMIT " . (TICKET_MAIL_REFERENCES - 1)));
$ids = array_reverse(array_column($latest, 0));
if ($first && !in_array($first[0], $ids, true)) {
array_unshift($ids, $first[0]);
}
}
$answering = ticketMailIdClean($answering);
if ($answering !== '') {
$ids = array_values(array_diff($ids, [$answering]));
$ids[] = $answering;
$ids = array_slice($ids, -TICKET_MAIL_REFERENCES);
}
return ['in_reply_to' => $ids ? end($ids) : '', 'references' => $ids];
}
/*
* The headers of one email about a ticket, from $from_email - a new Message-ID, kept with the
* ticket, and In-Reply-To and References from where its conversation stood as the email was
* written ($thread, ticketMailThread()). [header => value], for emailQueue()'s headers.
*/
function ticketMailHeaders($ticket_id, $from_email, array $thread) {
global $config_base_url;
$from_email = (string) $from_email;
$domain = strtolower(trim(substr($from_email, strrpos($from_email, '@') !== false ? strrpos($from_email, '@') + 1 : strlen($from_email))));
if (!preg_match('/^[a-z0-9.-]+\.[a-z]{2,}$/', $domain)) {
$domain = preg_replace('/[^a-z0-9.-]/', '', strtolower((string) parse_url('https://' . $config_base_url, PHP_URL_HOST))) ?: 'itflow.invalid';
}
$message_id = 'itflow.' . intval($ticket_id) . '.' . bin2hex(random_bytes(10)) . '@' . $domain;
ticketMailKeepId($ticket_id, $message_id, true);
$headers = ['Message-ID' => "<$message_id>"];
if (!empty($thread['in_reply_to'])) {
$headers['In-Reply-To'] = '<' . $thread['in_reply_to'] . '>';
$headers['References'] = implode(' ', array_map(function ($id) {
return "<$id>";
}, $thread['references']));
}
return $headers;
}
/*
* The ticket an email answers, by its headers - the first of the Message-IDs in its In-Reply-To,
* then in its References from the latest back, that is kept with a ticket (ticketMailKeepId()).
* ticket_id, or 0.
*/
function ticketMailHeaderTicket($in_reply_to, $references) {
global $mysqli;
if (!ticketMailThreadReady()) {
return 0;
}
$ids = array_values(array_unique(array_merge(ticketMailIdsIn($in_reply_to), array_reverse(ticketMailIdsIn($references)))));
$ids = array_slice($ids, 0, 50);
if (!$ids) {
return 0;
}
$found = [];
$sql = mysqli_query($mysqli, "SELECT mail_thread_message_id, mail_thread_ticket_id FROM ticket_mail_threads JOIN tickets ON ticket_id = mail_thread_ticket_id
WHERE mail_thread_message_id IN ('" . implode("', '", array_map(function ($id) use ($mysqli) { return mysqli_real_escape_string($mysqli, $id); }, $ids)) . "') ORDER BY mail_thread_id DESC");
while ($row = mysqli_fetch_row($sql)) {
$found[strtolower($row[0])] = $found[strtolower($row[0])] ?? intval($row[1]);
}
foreach ($ids as $message_id) {
if (isset($found[strtolower($message_id)])) {
return $found[strtolower($message_id)];
}
}
return 0;
}
/*
* The ticket whose number is in a subject in brackets - "[TCK-12]", "Re: [ABC-0042] ..." - with the
* prefix that ticket was given, whatever the prefix is now. The first in the subject that is a
* ticket. ['ticket_id', 'reference'] or null.
*/
function ticketMailSubjectTicket($subject) {
global $mysqli;
if (!preg_match_all('/\[([^\[\]\s]{1,40})\]/', (string) $subject, $matches)) {
return null;
}
foreach ($matches[1] as $token) {
// Where the prefix ends and the number starts - each split of the digits at its end, as a prefix can end in one
if (!preg_match('/\d+$/', $token, $digits)) {
continue;
}
$splits = [];
for ($i = 0, $n = strlen($digits[0]); $i < $n && count($splits) < 10; $i++) {
$number = intval(substr($digits[0], $i));
if ($number > 0 && $number <= 2147483647) {
$splits[$number][] = substr($token, 0, strlen($token) - $n + $i);
}
}
if (!$splits) {
continue;
}
$sql = mysqli_query($mysqli, "SELECT ticket_id, ticket_prefix, ticket_number FROM tickets WHERE ticket_number IN (" . implode(',', array_keys($splits)) . ") ORDER BY ticket_id DESC");
while ($row = mysqli_fetch_assoc($sql)) {
foreach ($splits[intval($row['ticket_number'])] ?? [] as $prefix) {
if (strcasecmp(trim((string) $row['ticket_prefix']), $prefix) === 0) {
return ['ticket_id' => intval($row['ticket_id']), 'reference' => ticketReference($row)];
}
}
}
}
return null;
}
/*
* The people an email to a ticket was also to or copied to ($addresses, its To and Cc) made the
* ticket's CCs, so the rest of the conversation reaches them as it reaches whoever wrote it.
* Never whoever sent it ($sender), the ticket's contact, an agent, one of ITFlow's own addresses or
* another address at your own domain (emailOwnDomain()), nor a no-reply address. The ones added.
*/
function ticketMailCopiedCcs($ticket_id, array $addresses, $sender) {
global $mysqli;
$ticket_id = intval($ticket_id);
$contact_email = strtolower(trim((string) (mysqli_fetch_row(mysqli_query($mysqli, "SELECT contact_email FROM tickets
JOIN contacts ON contact_id = ticket_contact_id WHERE ticket_id = $ticket_id"))[0] ?? '')));
$sender = strtolower(trim((string) $sender));
$emails = [];
foreach (ticketCcEmails($addresses) as $email) {
if ($email === $sender || $email === $contact_email || emailOwnAddress($email) || emailOwnDomain($email)
|| preg_match('/do[\W_]*not[\W_]*reply|no[\W_]*reply/i', $email)) {
continue;
}
if (mysqli_num_rows(mysqli_query($mysqli, "SELECT 1 FROM users WHERE user_email = '" . escapeSql($email) . "' AND user_type = 1 AND user_archived_at IS NULL LIMIT 1"))) {
continue;
}
$emails[] = $email;
}
return ticketAddCcs($ticket_id, array_slice($emails, 0, 20));
}
/*
* The contact an email from $email is from, when it is one - ['contact' => row (contact_id, contact_name, contact_email,
* contact_client_id, client_name) or null, 'others' => the other clients it is a contact at, [client_id => name],
* 'why' => how the one was picked]. An address can be a contact at more than one client - someone who works for two,
* a shared mailbox - and its email went to whichever the database gave first. Now: the client whose domain it is
* ($domain, Domains), else the one they last raised a ticket at, else the first they were added to.
*/
function ticketMailSenderContact($email, $domain = '') {
global $mysqli;
$email = trim((string) $email);
$none = ['contact' => null, 'others' => [], 'why' => ''];
if ($email === '') {
return $none;
}
$email_sql = escapeSql($email);
$domain_sql = escapeSql(strtolower(trim((string) $domain)));
$rows = [];
$sql = mysqli_query($mysqli, "SELECT contact_id, contact_name, contact_email, contact_client_id, client_name,
(SELECT 1 FROM domains WHERE domain_client_id = contact_client_id AND domain_name = '$domain_sql' AND domain_archived_at IS NULL LIMIT 1) AS at_domain,
(SELECT MAX(ticket_created_at) FROM tickets WHERE ticket_contact_id = contact_id) AS last_ticket
FROM contacts LEFT JOIN clients ON client_id = contact_client_id
WHERE contact_email = '$email_sql' AND contact_archived_at IS NULL
ORDER BY at_domain DESC, last_ticket DESC, contact_id");
while ($row = mysqli_fetch_assoc($sql)) {
$rows[] = $row;
}
if (!$rows) {
return $none;
}
$contact = $rows[0];
$others = [];
foreach (array_slice($rows, 1) as $row) {
if (intval($row['contact_client_id']) !== intval($contact['contact_client_id'])) {
$others[intval($row['contact_client_id'])] = (string) ($row['client_name'] ?? 'a client');
}
}
$why = !empty($contact['at_domain']) ? 'whose domain it is' : (!empty($contact['last_ticket']) ? 'where they last raised a ticket' : 'where they were added first');
return ['contact' => $contact, 'others' => $others, 'why' => $others ? $why : ''];
}
/*
* Say on a ticket raised by an email from $email - a contact at more than one client ($picked, ticketMailSenderContact()) -
* which client it went to and why, and the others, so an agent moves it when it is for one of those. An internal note.
*/
function ticketMailSenderContactNote($ticket_id, $email, array $picked) {
global $mysqli;
$ticket_id = intval($ticket_id);
if (!$ticket_id || empty($picked['others']) || empty($picked['contact'])) {
return 0;
}
$client = (string) ($picked['contact']['client_name'] ?? 'a client');
$others = array_values($picked['others']);
$list = count($others) === 1 ? $others[0] : implode(', ', array_slice($others, 0, -1)) . ' and ' . end($others);
$note = '<b>' . escapeHtml($email) . ' is a contact at ' . escapeHtml($list) . ' too</b> - this ticket went to ' . escapeHtml($client)
. ', ' . escapeHtml($picked['why']) . '.<br><i>If it is for ' . escapeHtml(count($others) === 1 ? $others[0] : 'one of the others') . ', change its client.</i>';
mysqli_query($mysqli, "INSERT INTO ticket_replies SET ticket_reply = '" . mysqli_real_escape_string($mysqli, $note) . "', ticket_reply_type = 'Internal',
ticket_reply_time_worked = '00:00:00', ticket_reply_by = 0, ticket_reply_ticket_id = $ticket_id");
$note_id = intval(mysqli_insert_id($mysqli));
logTicketHistory($ticket_id, escapeSql("$email is a contact at more than one client - it went to $client, " . $picked['why'] . ' - noted'));
return $note_id;
}
/*
* Which of $addresses (an email's To and Cc) are the client's on ticket $ticket_id - its contact, one of its CCs, or
* another of the client's contacts - for an agent's email that went to them too. Lower-case, as given.
*/
function ticketMailClientAddresses($ticket_id, array $addresses) {
global $mysqli;
$ticket_id = intval($ticket_id);
$row = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT ticket_client_id, contact_email FROM tickets LEFT JOIN contacts ON contact_id = ticket_contact_id WHERE ticket_id = $ticket_id"));
if (!$row) {
return [];
}
$client_id = intval($row['ticket_client_id']);
$found = [];
foreach (array_unique(array_map('strtolower', array_map('trim', array_map('strval', $addresses)))) as $email) {
if ($email === '' || emailOwnAddress($email)) {
continue;
}
$email_sql = escapeSql($email);
if (strtolower(trim((string) $row['contact_email'])) === $email
|| mysqli_num_rows(mysqli_query($mysqli, "SELECT 1 FROM ticket_ccs WHERE ticket_cc_ticket_id = $ticket_id AND ticket_cc_email = '$email_sql' LIMIT 1"))
|| ($client_id && mysqli_num_rows(mysqli_query($mysqli, "SELECT 1 FROM contacts WHERE contact_email = '$email_sql' AND contact_client_id = $client_id AND contact_archived_at IS NULL LIMIT 1")))) {
$found[] = $email;
}
}
return $found;
}
/** Why an emailed file with the extension $extension isn't added to a ticket - it isn't one of TICKET_ATTACHMENT_EXTENSIONS. */
function ticketMailFileTypeWhy($extension) {
$extension = strtolower(trim((string) $extension));
return $extension === '' ? 'its name has no file type' : "ITFlow doesn't take .$extension files";
}
/*
* Say on a ticket which files with an email weren't added to it - $dropped [['name', 'why'], ...], a kind
* ITFlow doesn't take (ticketMailFileTypeWhy()) or too big - in an internal note, as they used to be in
* the audit log alone. They are still in the email as it came, kept with the ticket. The note's id, or 0.
*/
function ticketMailFilesLeftOut($ticket_id, array $dropped) {
global $mysqli;
$ticket_id = intval($ticket_id);
$items = [];
foreach ($dropped as $file) {
$name = trim((string) ($file['name'] ?? ''));
$items[] = '<li>' . escapeHtml($name !== '' ? $name : 'A file with no name') . ' - ' . escapeHtml((string) ($file['why'] ?? '')) . '</li>';
}
if (!$ticket_id || !$items) {
return 0;
}
$count = count($items);
$note = '<b>' . ($count === 1 ? 'A file with the email was' : "$count files with the email were") . ' not added to the ticket</b><ul>' . implode('', $items) . '</ul>'
. "<i>They are in the email as it came - Original-parsed-email.eml on this ticket - and in the mailbox's ITFlow folder.</i>";
mysqli_query($mysqli, "INSERT INTO ticket_replies SET ticket_reply = '" . mysqli_real_escape_string($mysqli, $note) . "', ticket_reply_type = 'Internal',
ticket_reply_time_worked = '00:00:00', ticket_reply_by = 0, ticket_reply_ticket_id = $ticket_id");
$note_id = intval(mysqli_insert_id($mysqli));
logTicketHistory($ticket_id, $count === 1 ? "A file with an email wasn't added - noted" : "$count files with an email weren't added - noted");
return $note_id;
}
/*
* Say on a ticket made from an email that the email failed its sender checks - $why (ticketMailSenderCheck()),
* $from the address it says it is from, $copied the people it copied in, who weren't added. An internal note,
* as the ticket is made all the same, so nothing is lost. The note's id.
*/
function ticketMailForgedNote($ticket_id, $why, $from, array $copied = []) {
global $mysqli;
$ticket_id = intval($ticket_id);
if (!$ticket_id) {
return 0;
}
$note = '<b>This email failed its sender checks</b> - ' . escapeHtml($why) . '. It may not be from ' . escapeHtml($from) . '.<br>'
. "<i>It was made a ticket so nothing is lost, but its sender wasn't answered" . ($copied ? ' and the people it copied in (' . escapeHtml(implode(', ', $copied)) . ') weren\'t added' : '')
. '. Check with the client before acting on it.</i>';
mysqli_query($mysqli, "INSERT INTO ticket_replies SET ticket_reply = '" . mysqli_real_escape_string($mysqli, $note) . "', ticket_reply_type = 'Internal',
ticket_reply_time_worked = '00:00:00', ticket_reply_by = 0, ticket_reply_ticket_id = $ticket_id");
$note_id = intval(mysqli_insert_id($mysqli));
logTicketHistory($ticket_id, escapeSql("The email it came from failed its sender checks - it may not be from $from"));
return $note_id;
}
/*
* A client's reply - by email, text or in the portal - passed on to the people an agent's reply goes to
* (the ticket's To line, ticketReplyRecipients()) who didn't have it: not whoever wrote it, nor
* anyone it was already to or copied to ($had, addresses), nor the agents, who have their own email
* of it. When client replies are passed on (Admin > Settings > Tickets). $reply_id is the reply,
* as saved; $by who wrote it (raw); $answering the email's Message-ID. How many it went to.
*/
function ticketMailRelayClientReply($ticket_id, $reply_id, $by, $author_email, array $had = [], $answering = '') {
global $mysqli;
if (!emailReady() || !ticketMailSettings()['relay']) {
return 0;
}
$row = ticketRow($ticket_id);
$reply_id = intval($reply_id);
$reply = $reply_id ? mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT ticket_reply, ticket_reply_type FROM ticket_replies WHERE ticket_reply_id = $reply_id AND ticket_reply_ticket_id = " . intval($ticket_id))) : null;
if (!$row || !$reply || $reply['ticket_reply_type'] !== 'Client') {
return 0;
}
$skip = array_flip(array_map(function ($email) {
return strtolower(trim((string) $email));
}, array_merge($had, [$author_email])));
$recipients = [];
foreach (ticketReplyRecipients($ticket_id) as $email => $person) {
if ($person['send'] && $person['group'] !== 'agent' && !isset($skip[$email])) {
$recipients[] = $email;
}
}
if (!$recipients) {
return 0;
}
// Its files, as an agent's reply sends them - not the email itself, kept beside it
$attachments = [];
$sql = mysqli_query($mysqli, "SELECT ticket_attachment_name, ticket_attachment_reference_name FROM ticket_attachments
WHERE ticket_attachment_reply_id = $reply_id AND ticket_attachment_ticket_id = " . intval($ticket_id) . " AND ticket_attachment_name <> 'Original-parsed-email.eml'"
. (ticketPicturesReady() ? ' AND ticket_attachment_inline = 0' : ''));
while ($file = mysqli_fetch_assoc($sql)) {
$path = 'uploads/tickets/' . intval($ticket_id) . '/' . basename((string) $file['ticket_attachment_reference_name']);
if (is_file(dirname(__DIR__) . '/' . $path)) {
$attachments[] = ['path' => $path, 'name' => (string) $file['ticket_attachment_name'], 'size' => filesize(dirname(__DIR__) . '/' . $path)];
}
}
// What they wrote - without the "Email from: ... :-" line the email parser puts on what it saves
$message = (string) preg_replace('#^\s*<i>\s*Email from:.*?</i>(\s*<br\s*/?>)*#is', '', (string) $reply['ticket_reply']);
return ticketMailSend($ticket_id, ticketEmailContent($row, 'client_reply', ['message' => $message, 'skip' => (string) $reply['ticket_reply'], 'by' => (string) $by]), [
'recipients' => ticketReplyRecipientsPick($ticket_id, $recipients, false),
'attachments' => filterEmailableAttachments($attachments)['send'],
'answering' => $answering,
'auto' => 'generated',
]);
}