='); } 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 watchers copied in (else * one each); relay: a client's reply goes on to the watchers 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 watchers, 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 ticketMailCopiedWatchers($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 (ticketWatcherEmails($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 ticketAddWatchers($ticket_id, array_slice($emails, 0, 20)); } /* * 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*\s*Email from:.*?(\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', ]); }