=');
}
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 = '' . escapeHtml($email) . ' is a contact at ' . escapeHtml($list) . ' too - this ticket went to ' . escapeHtml($client)
. ', ' . escapeHtml($picked['why']) . '.
If it is for ' . escapeHtml(count($others) === 1 ? $others[0] : 'one of the others') . ', change its client.';
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[] = '