='); } 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)); } /** 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[] = '