Files
itflow/functions/ticket_mail_forward.php

306 lines
18 KiB
PHP

<?php
/*
* ITFlow - a client's email an agent forwarded to the ticket mailbox (cron/ticket_email_parser.php).
*
* Forwarded, it comes from the agent, and was taken as theirs: a ticket for your own company - the agent is a
* contact of it, or your domain is its - or one with no client, or nothing at all. Read from the forwarded part
* instead, it is the client's: the ticket goes to the client whose email it is, by the same steps as one they
* sent themselves - a contact, then a client's domain, then nobody's - and what the agent wrote above it is a
* note on the ticket by them, not something the client reads.
*
* Inline forwards are found by the header block that starts the forwarded part - a From line with an address,
* and a Sent, Date, To or Subject line beside it - after a line that says it is a forward ("---------- Forwarded
* message ---------", "Begin forwarded message:", "-------- Forwarded Message --------"), or in an email whose subject
* says it is one (Fwd:, FW:, WG:...). Outlook's forwards have no such line - its line of underscores and "-----Original
* Message-----" are in its replies too, so a reply that quotes a client's email isn't taken for one. That is Gmail,
* Outlook (desktop, the web and the new one), Apple Mail, Thunderbird and most others, in English and the usual European
* languages. An email forwarded as an attachment is read from the attached email.
*/
// What starts a forwarded email's subject - Fwd:, FW: and their other languages (Wg:, Tr:, Rv:, Enc:, Doorst:, Vs:,
// Vb:, Pd:), and the reply ones after them, as "Fwd: RE: Printer" - all left out of the ticket's subject
const TICKET_MAIL_FORWARD_SUBJECT = '/^\s*(?:(?:fwd?|fw|wg|tr|rv|enc|doorst|vs|vb|pd|re|aw|sv|antw|ref|r)\s*(?:\[\d+\])?\s*:\s*)+/iu';
const TICKET_MAIL_FORWARD_ONLY = '/^\s*(?:fwd?|fw|wg|tr|rv|enc|doorst|vs|vb|pd)\s*(?:\[\d+\])?\s*:/iu';
// A line that says a forwarded email starts below it - Gmail's, Thunderbird's and Apple Mail's, in their languages
const TICKET_MAIL_FORWARD_MARKERS = [
'/^\s*-{2,}\s*(?:forwarded message|weitergeleitete nachricht|message transf(?:é|e)r(?:é|e)|mensaje reenviado|messaggio inoltrato|doorgestuurd bericht|vidarebefordrat meddelande|videresendt (?:meddelelse|melding)|wiadomo(?:ś|s)(?:ć|c) przekazana|mensagem encaminhada)\s*-{2,}\s*$/iu',
'/^\s*(?:begin forwarded message|anfang der weitergeleiteten nachricht|d(?:é|e)but du message (?:r(?:é|e)exp(?:é|e)di(?:é|e)|r(?:é|e)envoy(?:é|e)|transf(?:é|e)r(?:é|e))|inicio del mensaje reenviado|inizio messaggio inoltrato)\s*:\s*$/iu',
];
// A line above an email quoted in a forward or in a reply alike - Outlook's "-----Original Message-----" and its line of
// underscores: where it starts, in an email whose subject says it is a forward, and nothing more - a reply quotes the same
const TICKET_MAIL_FORWARD_QUOTE_MARKERS = [
'/^\s*-{2,}\s*(?:original message|urspr(?:ü|ue)ngliche nachricht|message d\'origine|mensaje original|messaggio originale|oorspronkelijk bericht|ursprungligt meddelande|oprindelig meddelelse|opprinnelig melding|oryginalna wiadomo(?:ś|s)(?:ć|c)|mensagem original)\s*-{2,}\s*$/iu',
'/^\s*_{10,}\s*$/',
];
// The From line of a forwarded email's header block, and the lines beside it that make it one
const TICKET_MAIL_FORWARD_FROM = '/^[\s>*]*(?:from|von|de|da|van|fr(?:å|a)n|fra|od|l(?:ä|a)hett(?:ä|a)j(?:ä|a)|felad(?:ó|o)|от|kimden)\s*:\**\s*(.+)$/iu';
const TICKET_MAIL_FORWARD_LABEL = '/^[\s>*]*(?:sent|date|to|subject|cc|gesendet|datum|an|betreff|envoy(?:é|e)|(?:à|a)|objet|enviado|fecha|para|asunto|inviato|data|oggetto|verzonden|aan|onderwerp|skickat|till|(?:ä|a)mne|sendt|til|emne|wys(?:ł|l)ano|do|temat|l(?:ä|a)hetetty|vastaanottaja|aihe|elk(?:ü|u)ldve|c(?:í|i)mzett|t(?:á|a)rgy|отправлено|кому|тема|g(?:ö|o)nderildi|kime|konu|assunto)\s*:/iu';
const TICKET_MAIL_FORWARD_SUBJECT_LABEL = '/^[\s>*]*(?:subject|betreff|objet|asunto|oggetto|onderwerp|(?:ä|a)mne|emne|temat|aihe|t(?:á|a)rgy|тема|konu|assunto)\s*:\**\s*(.*)$/iu';
/** The active agent whose address $email is - ['user_id', 'user_name'] - or null. */
function ticketMailForwardAgent($email) {
global $mysqli;
$email = strtolower(trim((string) $email));
if ($email === '' || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
return null;
}
$row = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT user_id, user_name FROM users WHERE user_email = '" . escapeSql($email) . "'
AND user_type = 1 AND user_status = 1 AND user_archived_at IS NULL LIMIT 1"));
return $row ? ['user_id' => intval($row['user_id']), 'user_name' => (string) $row['user_name']] : null;
}
/** A forwarded email's subject without its Fwd: and Re: - "Fwd: RE: Printer offline" is "Printer offline". */
function ticketMailForwardSubject($subject) {
$subject = trim((string) preg_replace(TICKET_MAIL_FORWARD_SUBJECT, '', (string) $subject));
return $subject !== '' ? $subject : 'No Subject';
}
/** An email's HTML as text, a line for each line it shows - for finding the forwarded part's header block. */
function ticketMailForwardText($html) {
$html = (string) $html;
$html = preg_replace('#<(script|style|head)\b[^>]*>.*?</\1>#is', '', $html) ?? $html;
$html = preg_replace('#<img\b[^>]*>#i', '', $html) ?? $html;
$html = preg_replace('#<br\s*/?>#i', "\n", $html);
$html = preg_replace('#<hr\b[^>]*>#i', "\n__________\n", $html);
$html = preg_replace('#</(p|div|tr|li|h[1-6]|blockquote|table|pre)>#i', "\n", $html);
$text = html_entity_decode(strip_tags($html), ENT_QUOTES | ENT_HTML5, 'UTF-8');
return str_replace(["\r\n", "\r", "\xC2\xA0"], ["\n", "\n", ' '], $text);
}
/** The address and name in a header line's value - "Priya <p@x.com>", "Priya [mailto:p@x.com]", "p@x.com" - or null. */
function ticketMailForwardAddress($value) {
$value = trim((string) $value);
if (!preg_match('/[A-Z0-9._%+\'-]+@[A-Z0-9.-]+\.[A-Z]{2,}/i', $value, $m)) {
return null;
}
$email = strtolower($m[0]);
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
return null;
}
// The name is what comes before the address, its brackets and quotes taken off
$name = trim((string) preg_replace('/\s*(?:<|\[mailto:|\(|&lt;|mailto:)?\s*' . preg_quote($m[0], '/') . '.*$/i', '', $value));
$name = trim($name, " \t\"'<>[]*,");
if ($name === '' || strcasecmp($name, $email) === 0) {
$name = '';
}
return ['email' => $email, 'name' => mb_substr($name, 0, 200)];
}
/*
* The header block a forwarded email starts with, in $text: ['email', 'name', 'subject', 'line' => the line it
* starts at, 'marker' => the line above it that starts what was forwarded, or -1]. The first one from the top, the one
* forwarded last. $forwarded: the subject says it is a forward (Fwd:, FW:), so a block with no line saying so counts too -
* Outlook's has none, or one a reply has as well. Null without one.
*/
function ticketMailForwardBlock($text, $forwarded) {
$lines = explode("\n", str_replace(["\r\n", "\r"], "\n", (string) $text));
$count = count($lines);
$marker = -1;
$marker_says = false;
for ($i = 0; $i < $count; $i++) {
$line = $lines[$i];
foreach ([[TICKET_MAIL_FORWARD_MARKERS, true], [TICKET_MAIL_FORWARD_QUOTE_MARKERS, false]] as [$patterns, $says]) {
foreach ($patterns as $pattern) {
if (preg_match($pattern, $line)) {
$marker = $i;
$marker_says = $says;
continue 3;
}
}
}
if (!preg_match(TICKET_MAIL_FORWARD_FROM, $line, $m) || !($who = ticketMailForwardAddress($m[1]))) {
continue;
}
// A header block: another header line beside the From one, not blank lines apart - and a line above saying it
// is a forward, or a subject that does
$start = $i;
$labels = 0;
$subject = '';
for ($j = $i - 1; $j >= max(0, $i - 5) && trim($lines[$j]) !== ''; $j--) {
if (preg_match(TICKET_MAIL_FORWARD_LABEL, $lines[$j])) {
$labels++;
$start = $j;
}
}
for ($j = $i + 1; $j < min($count, $i + 7) && trim($lines[$j]) !== ''; $j++) {
if (preg_match(TICKET_MAIL_FORWARD_LABEL, $lines[$j])) {
$labels++;
}
}
for ($j = $start; $j < min($count, $i + 7); $j++) {
if (preg_match(TICKET_MAIL_FORWARD_SUBJECT_LABEL, $lines[$j], $s)) {
$subject = trim($s[1]);
break;
}
}
$near_marker = $marker >= 0 && $start - $marker <= 4;
if ($labels && (($near_marker && $marker_says) || $forwarded)) {
return $who + ['subject' => $subject, 'line' => $start, 'marker' => $near_marker ? $marker : -1];
}
}
return null;
}
/*
* Where the forwarded part starts in an email's HTML - the agent's note above it, the client's email from it - or
* -1. The containers mail apps put a forward in (Gmail's gmail_quote, Thunderbird's moz-forward-container,
* Outlook's divRplyFwdMsg and its bordered header, Apple Mail's quote), or the tag holding the line that says
* it is a forward. Only where the part from there has the forwarded email's sender in it.
*/
function ticketMailForwardHtmlSplit($html, $sender_email) {
$html = (string) $html;
$starts = [];
foreach ([
'#<div\b[^>]*\bclass=["\'][^"\']*\b(?:gmail_quote|moz-forward-container)\b#i',
'#<div\b[^>]*\bid=["\'](?:divRplyFwdMsg|appendonsend)["\']#i',
'#<div\b[^>]*style=["\'][^"\']*border-top:\s*solid\s+\#?[0-9a-f]{3,6}\s+1(?:\.0)?pt#i',
'#<blockquote\b[^>]*\btype=["\']cite["\']#i',
] as $pattern) {
if (preg_match($pattern, $html, $m, PREG_OFFSET_CAPTURE)) {
$starts[] = $m[0][1];
}
}
// The tag holding a line that says it is a forward
foreach (['#-{2,}\s*(?:forwarded message|original message|weitergeleitete nachricht|urspr(?:ü|ue)ngliche nachricht|message transf(?:é|e)r(?:é|e)|mensaje reenviado|messaggio inoltrato|doorgestuurd bericht)\s*-{2,}#iu',
'#begin forwarded message\s*:#i'] as $pattern) {
if (preg_match($pattern, $html, $m, PREG_OFFSET_CAPTURE)) {
$before = substr($html, 0, $m[0][1]);
$open = $m[0][1];
if (preg_match_all('#<(?!/)(?:div|p|span|blockquote|font|td|b|strong)\b#i', $before, $tags, PREG_OFFSET_CAPTURE)) {
$open = end($tags[0])[1];
}
$starts[] = $open;
}
}
sort($starts);
foreach (array_unique($starts) as $start) {
if (stripos(html_entity_decode(strip_tags(substr($html, $start)), ENT_QUOTES | ENT_HTML5, 'UTF-8'), $sender_email) !== false) {
// The line Outlook draws above it goes with it, not at the foot of the agent's note
if (preg_match('#<hr\b[^>]*>\s*$#i', substr($html, 0, $start), $hr, PREG_OFFSET_CAPTURE)) {
$start = $hr[0][1];
}
return $start;
}
}
return -1;
}
/** Whether a piece of an email's HTML says anything - not only line breaks, spaces and empty tags. */
function ticketMailForwardSaysSomething($html) {
$text = html_entity_decode(strip_tags(preg_replace('#<(script|style|head)\b[^>]*>.*?</\1>#is', '', (string) $html)), ENT_QUOTES | ENT_HTML5, 'UTF-8');
return trim(str_replace("\xC2\xA0", ' ', $text)) !== '' || preg_match('#<img\b#i', (string) $html);
}
/*
* The client's email an agent forwarded - from $html (the email's HTML, its pictures already in it) and $text (its
* plain text part), or an email attached to it ($attachments: ['name', 'content', 'mime']): ['email', 'name' => who
* it is from, 'subject' => its own subject, for the ticket, 'html' => it, the ticket's details, 'note' => what the
* agent wrote above it ('' when nothing), 'how' => 'inline' or 'attached', 'attachment' => the attached one's index].
* Null when nothing in it is forwarded. $subject is the email's own.
*/
function ticketMailForwarded($html, $text, $subject, array $attachments = []) {
$html = (string) $html;
$text = (string) $text;
$forwarded = (bool) preg_match(TICKET_MAIL_FORWARD_ONLY, (string) $subject);
// Inline: the plain text part first, as the sender's app wrote it, then the HTML read as text
$block = null;
$in_text = false;
if (trim($text) !== '' && ($block = ticketMailForwardBlock($text, $forwarded))) {
$in_text = true;
} elseif ($html !== '') {
$block = ticketMailForwardBlock(ticketMailForwardText($html), $forwarded);
}
if ($block) {
$subject_out = ticketMailForwardSubject($block['subject'] !== '' ? $block['subject'] : $subject);
$split = $html !== '' ? ticketMailForwardHtmlSplit($html, $block['email']) : -1;
if ($split >= 0) {
$note = substr($html, 0, $split);
return ['email' => $block['email'], 'name' => $block['name'], 'subject' => $subject_out, 'html' => substr($html, $split),
'note' => ticketMailForwardSaysSomething($note) ? $note : '', 'how' => 'inline', 'attachment' => -1];
}
// No container to split the HTML at - the plain text, split at its header block (or the line above it)
$source = $in_text ? $text : ticketMailForwardText($html);
$lines = explode("\n", str_replace(["\r\n", "\r"], "\n", $source));
$from_line = $block['marker'] >= 0 ? $block['marker'] : $block['line'];
$note = trim(implode("\n", array_slice($lines, 0, $from_line)));
$original = trim(implode("\n", array_slice($lines, $from_line)));
return ['email' => $block['email'], 'name' => $block['name'], 'subject' => $subject_out, 'html' => nl2br(escapeHtml($original)),
'note' => $note !== '' ? nl2br(escapeHtml($note)) : '', 'how' => 'inline', 'attachment' => -1];
}
// Forwarded as an attachment - Outlook's Forward as Attachment, or an .eml dragged in: one attached email, read
$attached = [];
foreach ($attachments as $index => $attachment) {
$mime = strtolower((string) ($attachment['mime'] ?? ''));
if ($mime === 'message/rfc822' || strtolower(pathinfo((string) ($attachment['name'] ?? ''), PATHINFO_EXTENSION)) === 'eml') {
$attached[] = $index;
}
}
if (count($attached) !== 1 || !class_exists('\ZBateson\MailMimeParser\Message')) {
return null;
}
try {
$inner = \ZBateson\MailMimeParser\Message::from((string) $attachments[$attached[0]]['content'], false);
$from = $inner->getHeader('From');
$who = $from ? ticketMailForwardAddress(trim(($from->getPersonName() ?? '') . ' <' . ($from->getEmail() ?? '') . '>')) : null;
if (!$who) {
return null;
}
if ($from->getPersonName()) {
$who['name'] = mb_substr(trim((string) $from->getPersonName()), 0, 200);
}
$inner_html = (string) $inner->getHtmlContent();
$inner_text = (string) $inner->getTextContent();
$body = $inner_html !== '' ? $inner_html : ($inner_text !== '' ? nl2br(escapeHtml($inner_text)) : '');
// Its pictures, in it as the email showed them
foreach ($inner->getAllAttachmentParts() as $part) {
$cid = trim((string) $part->getContentId(), '<>');
$type = strtolower((string) $part->getContentType());
if ($cid !== '' && str_starts_with($type, 'image/') && $inner_html !== '') {
$body = str_replace(["cid:$cid", "cid:<$cid>"], "data:$type;base64," . base64_encode((string) $part->getBinaryContentStream()), $body);
}
}
} catch (\Throwable $e) {
return null;
}
$note = $html !== '' ? $html : ($text !== '' ? nl2br(escapeHtml($text)) : '');
return ['email' => $who['email'], 'name' => $who['name'], 'subject' => ticketMailForwardSubject((string) ($inner->getSubject() ?? '') !== '' ? $inner->getSubject() : $subject),
'html' => $body, 'note' => ticketMailForwardSaysSomething($note) ? $note : '', 'how' => 'attached', 'attachment' => $attached[0]];
}
/*
* Whether a forwarded email's sender is a client's - not one of your own addresses, an agent, or someone at your own
* domain: an agent forwarding a colleague's email, or a notice ITFlow sent, is theirs as before.
*/
function ticketMailForwardFromClient($email) {
$email = strtolower(trim((string) $email));
return $email !== '' && !emailOwnAddress($email) && !emailOwnDomain($email) && !ticketMailForwardAgent($email);
}
/*
* The agent's note on a ticket raised from an email they forwarded - what they wrote above it, as an internal note by
* them - and the ticket's history saying who forwarded it. $note is HTML ('' when they wrote nothing).
*/
function ticketMailForwardNote($ticket_id, array $agent, $note, $from_email) {
global $mysqli;
$ticket_id = intval($ticket_id);
if (!$ticket_id) {
return 0;
}
$note_id = 0;
$note = trim((string) $note);
if ($note !== '') {
$note = preg_replace(['#<head\b[^>]*>.*?</head>#is', '/<!DOCTYPE[^>]*>/i', '/<meta[^>]*>/i', '/<\/?(html|head|body)[^>]*>/i'], '', $note) ?? $note;
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 = " . intval($agent['user_id']) . ", ticket_reply_ticket_id = $ticket_id");
$note_id = intval(mysqli_insert_id($mysqli));
}
logTicketHistory($ticket_id, escapeSql("Raised from an email from $from_email that " . $agent['user_name'] . " forwarded to the ticket mailbox" . ($note_id ? ' - their note is on the ticket' : '')));
return $note_id;
}