'#0d6efd', 'success' => '#198754', 'warning' => '#b35c00', 'danger' => '#c42b37', 'secondary' => '#5c636a']; /* * The line at the top of an email people reply to. cron/ticket_email_parser.php * keeps only what is above it in a reply, so it goes first - before anything * a mail program quotes back. */ const EMAIL_REPLY_MARKER = '##- Please type your reply above this line -##'; /** * One email as HTML. $email, every value raw - it is escaped here, but for * message.html, which is HTML: * marker true for an email people reply to - the reply line goes first * preview the line an inbox shows beside the subject (hidden in the email) * kind the small heading - Invoice, Ticket update, Resolved * tone its colour - primary, success, warning, danger or secondary * title the heading * name who it is to - "Hello Name,"; '' greets nobody by name ("Hello,"), null not at all * intro paragraphs before the summary * content HTML someone wrote that is the email itself - a bulk email, say - made safe * (emailMessageHtml()) and shown as it is, not quoted * note the agent's own words, kept as typed * message ['html' => what someone wrote, as HTML, 'by' => who, 'when' => when, 'label' => the line over it] * summary label => value; strong names the label to make stand out * lines a table - ['head' => [...], 'align' => [...], 'rows' => [[cell, ...]]], a cell * plain text or ['text' => ..., 'url' => ..., 'tone' => danger] * callout a paragraph that stands out, in the tone's colour * button ['label' => ..., 'url' => ..., 'show_url' => true to print the address under it, * for a link that has to be copied whole] * after paragraphs after the button, smaller * history earlier messages, under a rule at the end - ['label' => the heading, 'items' => [...]], * each item ['by', 'org', 'action', 'when', 'text' => plain text, 'client' => true for * the client's side] or ['gap' => how many are left out here] (ticketEmailHistory()) * contact the foot's contact line, in place of the company's phone, email and website * office ['address', 'contact'] - the foot of another office (officeTicketFoot()), in place * of the company's address and contact line; null for the company's own * footnote a line under the card - why they got it * unsubscribe a link after it to leave email like this - the email sent to many (contactUnsubscribeUrl()) */ function emailHtml(array $email) { global $config_base_url; $e = function ($value) { return htmlspecialchars((string) $value, ENT_QUOTES, 'UTF-8'); }; $tones = EMAIL_TONES; $accent = $tones[$email['tone'] ?? 'primary'] ?? $tones['primary']; $text = '#212529'; $muted = '#6c757d'; $line = '#e5e7eb'; $font = "font-family:-apple-system,'Segoe UI',Roboto,Helvetica,Arial,sans-serif;"; $company = billingCompany(); $company_name = (string) ($company['company_name'] ?? ''); $paragraph = function ($text_value) use ($e, $text) { return '

' . nl2br($e($text_value)) . '

'; }; $logo = !empty($company['logo_url']) && !empty($config_base_url) ? '' . $e($company_name) . '' : '
' . $e($company_name) . '
'; $body = ''; if (array_key_exists('name', $email) && $email['name'] !== null) { $body .= $paragraph(trim((string) $email['name']) !== '' ? 'Hello ' . $email['name'] . ',' : 'Hello,'); } foreach ((array) ($email['intro'] ?? []) as $text_value) { $body .= $paragraph($text_value); } if (trim(strip_tags((string) ($email['content'] ?? ''), '')) !== '') { $body .= '
' . emailMessageHtml($email['content']) . '
'; } if (trim((string) ($email['note'] ?? '')) !== '') { $body .= '' . '
' . $e(trim($email['note'])) . '
'; } if (!empty($email['message']['html']) && trim(strip_tags((string) $email['message']['html'], '')) !== '') { $by = trim((string) ($email['message']['by'] ?? '')); $label = (string) ($email['message']['label'] ?? ($by !== '' ? "$by wrote" : '')); $when = trim((string) ($email['message']['when'] ?? '')); $head = $label !== '' || $when !== '' ? '
' . $e($label) . '' . ($when !== '' ? ($label !== '' ? ' · ' : '') . $e($when) : '') . '
' : ''; $body .= '' . '
' . $head . '
' . emailMessageHtml($email['message']['html']) . '
'; } if (!empty($email['summary'])) { $rows = ''; $strong = (string) ($email['strong'] ?? ''); $first = true; foreach ($email['summary'] as $label => $value) { $big = $label === $strong; // The figure that matters stands out - with a rule above it when it closes the box $rule = $big && !$first ? 'border-top:1px solid ' . $line . ';padding-top:11px;' : ''; $rows .= '' . $e($label) . '' . '' . $e($value) . ''; $first = false; } $body .= '' . '
' . $rows . '
'; } if (!empty($email['lines']['rows'])) { $align = (array) ($email['lines']['align'] ?? []); $head = ''; foreach ((array) $email['lines']['head'] as $i => $heading) { $head .= '' . $e($heading) . ''; } $rows = ''; foreach ($email['lines']['rows'] as $cells) { $rows .= ''; foreach (array_values($cells) as $i => $cell) { $cell = is_array($cell) ? $cell : ['text' => $cell]; $color = !empty($cell['tone']) ? ($tones[$cell['tone']] ?? $text) : $text; $content = !empty($cell['url']) ? '' . $e($cell['text']) . '' : $e($cell['text']); $rows .= '' . $content . ''; } $rows .= ''; } $body .= '' . $head . '' . $rows . '
'; } if (trim((string) ($email['callout'] ?? '')) !== '') { $body .= '

' . nl2br($e(trim($email['callout']))) . '

'; } if (!empty($email['button']['url'])) { $body .= '
' . '' . $e($email['button']['label']) . '' . '
'; if (!empty($email['button']['show_url'])) { $body .= '

Or copy this into your browser: ' . $e($email['button']['url']) . '

'; } } foreach ((array) ($email['after'] ?? []) as $text_value) { $body .= '

' . nl2br($e($text_value)) . '

'; } // The earlier messages, quietly, after everything else - a grey edge for the client's side, blue for yours if (!empty($email['history']['items'])) { $items = ''; foreach ($email['history']['items'] as $item) { if (isset($item['gap'])) { $gap = intval($item['gap']); $items .= '

··· ' . $gap . ' earlier ' . ($gap === 1 ? 'message' : 'messages') . ' - see the ticket

'; continue; } $meta = '' . $e($item['by'] ?? '') . ''; foreach (['org', 'action', 'when'] as $part) { if (trim((string) ($item[$part] ?? '')) !== '') { $meta .= ' · ' . $e($item[$part]); } } $items .= '' . '
' . '
' . $meta . '
' . '
' . nl2br($e($item['text'] ?? '')) . '
' . '
'; } $body .= '
' . '
' . $e($email['history']['label'] ?? 'Earlier messages') . '
' . $items . '
'; } $office = is_array($email['office'] ?? null) ? $email['office'] : null; $contact = $office ? (string) ($office['contact'] ?? '') : (array_key_exists('contact', $email) ? (string) $email['contact'] : implode(' · ', array_filter([$company['phone_display'] ?? '', $company['company_email'] ?? '', $company['company_website'] ?? '']))); $foot = array_filter([ $company_name, $office ? (string) ($office['address'] ?? '') : formatAddress($company['company_address'] ?? '', $company['company_city'] ?? '', $company['company_state'] ?? '', $company['company_zip'] ?? '', $company['company_country'] ?? '', ', '), $contact, ]); // The reply line - first, so a reply quoting this email is cut off cleanly $marker = !empty($email['marker']) ? '
' . EMAIL_REPLY_MARKER . '
' : ''; $preview = trim((string) ($email['preview'] ?? '')) !== '' ? '
' . $e($email['preview']) . str_repeat('‌ ', 40) . '
' : ''; return '' . '' . $e($email['title'] ?? '') . '' . '' . '
' . ($marker !== '' ? '
' . $marker . '
' : '') . $preview . '' . '' . '' . '' . '
' . $logo . '
' . (trim((string) ($email['kind'] ?? '')) !== '' ? '
' . $e($email['kind']) . '
' : '') . '

' . $e($email['title'] ?? '') . '

' . $body . '
' . implode('
', array_map($e, $foot)) . '
' . (!empty($email['footnote']) || !empty($email['unsubscribe']) ? '
' . $e($email['footnote'] ?? '') . (!empty($email['unsubscribe']) ? (!empty($email['footnote']) ? ' ' : '') . 'Unsubscribe' : '') . '
' : '') . '
'; } /** The mail settings, read once, as saved - cron scripts load their own copies, or none. */ function emailSettings() { global $mysqli; static $row = null; if ($row === null) { $row = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT config_smtp_provider, config_mail_from_email, config_mail_from_name, config_ticket_from_email, config_ticket_from_name FROM settings WHERE company_id = 1")) ?: []; } return $row; } /** Can mail go out - is a mail provider set up (Admin > Mail)? Always, while emails are being captured for a preview. */ function emailReady() { return emailCapturing() || !empty(emailSettings()['config_smtp_provider']); } /* * Capturing - for the previews in Admin > Mail (functions/email_preview.php). * While it is on, emailQueue() keeps what it would have queued instead of * queuing it, as if mail were set up. */ function emailCaptureStart() { $GLOBALS['itflow_email_capture'] = []; } function emailCapturing() { return isset($GLOBALS['itflow_email_capture']) && is_array($GLOBALS['itflow_email_capture']); } /** Stop capturing - what was captured: [['to', 'to_name', 'cc', 'from', 'from_name', 'subject', 'html', 'attachments', 'cal_str'], ...]. */ function emailCaptureStop() { $captured = $GLOBALS['itflow_email_capture'] ?? []; unset($GLOBALS['itflow_email_capture']); return is_array($captured) ? $captured : []; } /** * The mailboxes ITFlow sends from (Admin > Mail), as saved - for a pick of * which one an email comes from. key => ['label', 'email', 'name'], the ones * with an address. */ function emailMailboxes() { $system = emailFrom(); $invoice = billingEmailFrom('invoice'); $quote = billingEmailFrom('quote'); $ticket = emailFrom('ticket'); $boxes = [ 'system' => ['label' => 'System'] + $system, 'ticket' => ['label' => 'Tickets'] + $ticket, 'invoice' => ['label' => 'Invoices'] + $invoice, 'quote' => ['label' => 'Quotes'] + $quote, ]; $seen = []; foreach ($boxes as $key => $box) { $same = strtolower($box['email']) . '|' . $box['name']; if (!filter_var($box['email'], FILTER_VALIDATE_EMAIL) || isset($seen[$same])) { unset($boxes[$key]); } $seen[$same] = true; } return $boxes; } /** * ITFlow's own addresses, lower case - the mailboxes it sends from (emailMailboxes()) and the one * it reads (Admin > Mail > Receiving). Mail from one of them is ITFlow's own come back - a copy to a * CC that is the ticket mailbox, say - so the ticket mailbox reader skips it, and nothing about * a ticket is sent to one (emailOwnAddress()). */ function emailOwnAddresses() { global $mysqli; static $own = null; if ($own === null) { $own = []; $reads = (string) (mysqli_fetch_row(mysqli_query($mysqli, "SELECT config_imap_username FROM settings WHERE company_id = 1"))[0] ?? ''); foreach (array_merge(array_column(emailMailboxes(), 'email'), [$reads]) as $address) { $address = strtolower(trim((string) $address)); if (filter_var($address, FILTER_VALIDATE_EMAIL)) { $own[$address] = true; } } $own = array_keys($own); } return $own; } /** Whether $email is one of ITFlow's own addresses (emailOwnAddresses()). */ function emailOwnAddress($email) { return in_array(strtolower(trim((string) $email)), emailOwnAddresses(), true); } /* * The public domains that hand out addresses to anyone - an address at one of them isn't one of * yours just because ITFlow's own mailbox is there too (emailOwnDomain()). */ const EMAIL_PUBLIC_DOMAINS = ['gmail.com', 'googlemail.com', 'outlook.com', 'hotmail.com', 'live.com', 'msn.com', 'yahoo.com', 'ymail.com', 'aol.com', 'icloud.com', 'me.com', 'mac.com', 'proton.me', 'protonmail.com', 'pm.me', 'gmx.com', 'gmx.net', 'zoho.com', 'mail.com', 'fastmail.com', 'yandex.com']; /* * Whether $email is at the domain of one of ITFlow's own addresses (emailOwnAddresses()) - another * of your own mailboxes, or another name for the ticket mailbox - unless that domain is a public * one anyone has an address at (EMAIL_PUBLIC_DOMAINS). */ function emailOwnDomain($email) { static $domains = null; if ($domains === null) { $domains = []; foreach (emailOwnAddresses() as $address) { $domain = substr($address, strrpos($address, '@') + 1); if (!in_array($domain, EMAIL_PUBLIC_DOMAINS, true)) { $domains[$domain] = true; } } } $email = strtolower(trim((string) $email)); $at = strrpos($email, '@'); return $at !== false && isset($domains[substr($email, $at + 1)]); } /* * Whether ITFlow reads tickets from $email - email-to-ticket is on and it is the Receiving username, * or the ticket mailbox, which Admin > Mail says to make the same one. A notice sent there would be * read back in as an email to it. */ function emailReadMailbox($email) { global $mysqli; $email = strtolower(trim((string) $email)); $row = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT config_ticket_email_parse, config_imap_provider, config_imap_username, config_ticket_from_email FROM settings WHERE company_id = 1")) ?: []; if ($email === '' || !intval($row['config_ticket_email_parse'] ?? 0) || trim((string) ($row['config_imap_provider'] ?? '')) === '') { return false; } return in_array($email, [strtolower(trim((string) $row['config_imap_username'])), strtolower(trim((string) $row['config_ticket_from_email']))], true); } /** * Who an email comes from, read from the settings as saved (cron scripts keep * SQL-escaped copies): system - the mailbox for everything else (Admin > * Mail), or ticket - the ticket mailbox. ['email' => ..., 'name' => ...]. */ function emailFrom($which = 'system') { $row = emailSettings(); if ($which === 'ticket') { return ['email' => (string) ($row['config_ticket_from_email'] ?? ''), 'name' => (string) ($row['config_ticket_from_name'] ?? '')]; } return ['email' => (string) ($row['config_mail_from_email'] ?? ''), 'name' => (string) ($row['config_mail_from_name'] ?? '')]; } /* * HTML someone wrote - a ticket reply, the details of a ticket - made safe to * put in an email (documentHtmlPurify()), its images and links pointed at * this install when they were saved without it, and the reply line taken out * so it can't cut a later reply short. */ function emailMessageHtml($html) { global $config_base_url; $html = str_replace(EMAIL_REPLY_MARKER, '', (string) $html); $html = documentHtmlPurify($html); if (!empty($config_base_url)) { $base = 'https://' . $config_base_url; $html = preg_replace('/\b(src|href)="\/(?!\/)/i', '$1="' . $base . '/', $html) ?? $html; } // Images no wider than the card, paragraphs closer together than a mail program's default - a // tag at a time. A lookahead across the tag ran out of PCRE's backtracking (pcre.backtrack_limit, // a million) on a pasted picture of 750 KB or more, whose data is that long, and the whole // message was lost return preg_replace_callback('/<(img|p)\b([^>]*)>/i', function ($m) { if (preg_match('/\sstyle\s*=/i', $m[2])) { return $m[0]; } return '<' . $m[1] . ' style="' . (strtolower($m[1]) === 'img' ? 'max-width:100%;height:auto;' : 'margin:0 0 10px;') . '"' . $m[2] . '>'; }, $html) ?? $html; } /* * HTML someone wrote as plain text - for an inbox's preview line and an * email's earlier messages: line breaks kept, pictures dropped (a message * that was only a picture says so), the reply line taken out, and with * $limit, cut at a word near that many characters with an ellipsis. */ function emailPlainText($html, $limit = 0) { $html = str_replace(EMAIL_REPLY_MARKER, '', (string) $html); $html = preg_replace('#<(script|style|title|head)\b[^>]*>.*?#is', '', $html); $pictures = preg_match_all('##i', '##i', '##i', '#]*>#i'], ["\n", "\n\n", "\n", '- '], $html); $text = html_entity_decode(strip_tags($html), ENT_QUOTES | ENT_HTML5, 'UTF-8'); // Non-breaking and zero-width spaces too - unless the text isn't valid UTF-8, where /u gives up $text = preg_replace("/[ \t\x{00A0}\x{200B}\x{200C}]+/u", ' ', $text) ?? preg_replace("/[ \t]+/", ' ', $text); $text = trim((string) preg_replace(["/ *\n */", "/\n{3,}/"], ["\n", "\n\n"], $text)); if ($text === '' && $pictures) { return $pictures === 1 ? '[A picture]' : "[$pictures pictures]"; } if ($limit > 0 && mb_strlen($text) > $limit) { $cut = mb_substr($text, 0, $limit); $space = mb_strrpos($cut, ' '); $text = rtrim($space !== false && $space > $limit * 0.6 ? mb_substr($cut, 0, $space) : $cut, " \n,.;:-") . '…'; } return $text; } /* * What someone wrote in an email reply to a ticket, without the email of ours * they are answering - HTML in and out, for cron/ticket_email_parser.php. * Usually that is everything above EMAIL_REPLY_MARKER. When nothing they * wrote is above it - they typed below the line, or their mail program puts * a reply under the email it quotes - it is what follows the quote: after the * blockquote the line is in, or, in a plain text reply, the lines not quoted * with ">". Words on both sides are both kept. When none of that has * anything - they typed into the quote, where their words can't be told from * ours, or wrote nothing - the whole email is kept, with a note saying so, * rather than nothing. */ function emailReplyText($html) { $html = (string) $html; if (!preg_match('/(?:]*>\s*)?(?:>\s*)*##-\s*Please\s+type\s+your\s+reply\s+above\s+this\s+line\s*-##(?:\s*<\/i>)?/is', $html, $m, PREG_OFFSET_CAPTURE)) { return $html; } $above = substr($html, 0, $m[0][1]); $below = substr($html, $m[0][1] + strlen($m[0][0])); // What follows the quote the line is in $after = ''; $open = preg_match_all('//i', $above); if ($open > 0 && preg_match_all('/<(\/?)blockquote\b[^>]*>/i', $below, $tags, PREG_SET_ORDER | PREG_OFFSET_CAPTURE)) { foreach ($tags as $tag) { $open += $tag[1][0] === '/' ? -1 : 1; if ($open === 0) { $after = substr($below, $tag[0][1] + strlen($tag[0][0])); break; } } } elseif (strpos($m[0][0], '>') !== false) { // A plain text reply quoting the line with ">" - its lines that aren't quoted $lines = preg_split('/\s*|\r\n|\n|\r/i', $below); $after = implode('
', array_filter($lines, function ($line) { return !preg_match('/^\s*(>|>)/', strip_tags($line)); })); } $kept = array_values(array_filter([emailReplyHasText($above) ? $above : '', emailReplyHasText($after) ? $after : ''])); if ($kept) { return implode('

', $kept); } return '

Nothing was written above the reply line, so here is the whole email, in case they wrote into it:

' . $above . $below; } /* * Whether HTML from an email reply has anything someone wrote in it - not * just what mail programs put around a quote: who wrote it and when ("On ... * wrote:"), Outlook's From, Sent, To and Subject, "Original Message", lines * quoted with ">", "Sent from my iPhone". A picture counts. */ function emailReplyHasText($html) { $text = emailPlainText($html); $text = preg_replace([ '/\bOn\b[^\n]{0,200}(?:\n[^\n]{0,200}){0,2}?\bwrote:/iu', '/^\s*-+\s*Original Message\s*-+\s*$/imu', '/^\s*(From|Sent|Date|To|Cc|Subject)\s*:.*$/imu', '/^\s*Sent from my\b.*$/imu', '/^\s*>.*$/mu', ], '', $text) ?? $text; return trim((string) preg_replace('/[\s\x{00A0}\x{200B}]+/u', '', $text)) !== ''; } /* * The pictures in an email's HTML as data - pasted into a ticket reply, say - taken out to files * the mail queue attaches inline, each pointing at its cid: instead. Gmail, among others, * shows no picture carried as data, and the queue keeps each picture once rather than a copy in * every email. [html, [['path', 'name', 'cid'], ...]]. A tag at a time, as a scan through a * large picture's data runs out of PCRE's backtracking (emailMessageHtml()); a picture that isn't * one, or can't be saved, stays as it was. With $ticket ['id' => ticket id, 'internal' => bool] * the ticket's own pictures, kept as its files, go in too (ticketPicturesAsData()) - only those * its client can see, unless 'internal' (an email to agents). */ function emailInlineImages($html, array $ticket = []) { $images = []; $html = (string) $html; if (!empty($ticket['id'])) { $html = ticketPicturesAsData($html, intval($ticket['id']), !empty($ticket['internal'])); } if (stripos($html, 'data:image/') === false) { return [$html, []]; } $types = [IMAGETYPE_PNG => 'png', IMAGETYPE_JPEG => 'jpg', IMAGETYPE_GIF => 'gif', IMAGETYPE_WEBP => 'webp']; $out = preg_replace_callback('/]*>/i', function ($tag) use (&$images, $types) { if (!preg_match('/\ssrc\s*=\s*(["\'])data:image\/[a-z+.-]+;base64,([A-Za-z0-9+\/=\s]+)\1/i', $tag[0], $m)) { return $tag[0]; } $data = base64_decode(preg_replace('/\s+/', '', $m[2]), true); $info = $data !== false ? @getimagesizefromstring($data) : false; $ext = $info ? ($types[$info[2]] ?? '') : ''; if ($ext === '') { return $tag[0]; } $hash = hash('sha256', $data); $path = MAIL_QUEUE_IMAGE_DIR . "/$hash.$ext"; $file = dirname(__DIR__) . '/' . $path; if (!is_file($file)) { if (!is_dir(dirname($file))) { @mkdir(dirname($file), 0775, true); } if (@file_put_contents($file, $data) === false) { return $tag[0]; } } $cid = substr($hash, 0, 32) . '@itflow'; $images[$cid] = ['path' => $path, 'name' => 'picture-' . substr($hash, 0, 8) . ".$ext", 'cid' => $cid]; return str_replace($m[0], ' src=' . $m[1] . 'cid:' . $cid . $m[1], $tag[0]); }, $html); return $out === null ? [$html, []] : [$out, array_values($images)]; } /** * Queue an email - one per recipient, each greeted by name, each address once. * $recipients: [['email' => ..., 'name' => ..., 'greet' => name to greet (or * '' for "Hello,", null for none), 'footnote' => why they get it, 'unsubscribe' => * a link to leave email like it (emailHtml()), 'headers' => its own - List-Unsubscribe], * ...] - unsubscribe and headers only on an email of its own, not one copied (together). * $email is emailHtml()'s, its values raw. $opts: * from ['email' => ..., 'name' => ...] - the system mailbox (emailFrom()) when not given * attachments [['path' => app-relative, 'name' => ...], ...] * cal_str a calendar file (iCalendar) to go with it - an invite or its cancellation * queued_at when to send it, 'Y-m-d H:i:s' - now when not given * always queue it even without mail set up, to go once it is - billing's Send * windows have always done that (billingEmailQueue()) * ticket_reply_id the agent's ticket reply it carries - kept with each email * (email_queue.email_ticket_reply_id), so the conversation says who * it went to and whether it went (ticketReplyEmailed()) * sensitive it carries a link or code that opens something - a shared login, an * invite, a password link, a signing or approval link - so the mail queue * clears what it said once it has gone (email_queue.email_sensitive) * ticket_id the ticket its message comes from - the pictures the ticket's client can * see go in it (emailInlineImages()). An email to agents built by * ticketAgentEmailContent() says its own ticket, in $email['ticket_pictures'], * and has an internal note's pictures too * together one email to the first recipient, everyone else copied in (Cc) - greeted as * the first is, with together_footnote as why they get it. Before the 4.2.6 * update, which gives the queue somewhere to keep them, one each * thread the ticket whose conversation it is in - it gets a Message-ID of its own and * In-Reply-To and References naming the emails before it (ticketMailHeaders()), * and answering, the Message-ID of the email it answers, when it answers one. From * another address than the mailbox ITFlow reads, it asks for replies there * (Reply-To, ticketMailReplyToRead()) * auto replied (an automatic answer to an email) or generated (sent by ITFlow by * itself) - headers saying so, so it isn't answered (ticketMailAutoHeaders()) * bulk an email to many - the contacts or clients list's Email - which the mail queue * sends after everything else (email_queue.email_bulk) * about what a billing email is about - invoice:12, quote:7 (email_queue.email_about) - so * a bounce goes in its history (mailQueueBounced()) * Each email has a Message-ID of its own (email_queue.email_message_id, 4.3.5) - a ticket's from its * conversation, the rest made here (emailMessageId()) - so a bounce finds the email it was about. * Who it was queued to, "Name (email)" - the copied in too: only those that went in the queue * (addToMailQueue()). Nothing is queued without mail set up. The subject is cut to fit (emailFit()). */ function emailQueue(array $recipients, $subject, array $email, array $opts = []) { global $mysqli; if (!emailReady() && empty($opts['always'])) { return []; } $from = $opts['from'] ?? emailFrom(); // To fit the queue's columns (emailFit()) $subject = emailFit($subject); $queued_at = !empty($opts['queued_at']) && strtotime((string) $opts['queued_at']) ? date('Y-m-d H:i:s', strtotime((string) $opts['queued_at'])) : ''; $attachments = array_values(array_filter((array) ($opts['attachments'] ?? []))); // The ticket whose pictures its message may carry (functions/ticket_pictures.php) $pictures = !empty($opts['ticket_id']) ? ['id' => intval($opts['ticket_id']), 'internal' => false] : (array) ($email['ticket_pictures'] ?? []); unset($email['ticket_pictures']); // Each address once, and only an address $people = []; foreach ($recipients as $recipient) { $address = trim((string) ($recipient['email'] ?? '')); if (filter_var($address, FILTER_VALIDATE_EMAIL) && !isset($people[strtolower($address)])) { $people[strtolower($address)] = ['email' => $address, 'name' => (string) ($recipient['name'] ?? '')] + $recipient; } } $people = array_values($people); $together = !empty($opts['together']) && count($people) > 1 && ticketMailThreadReady(); // Where the ticket's conversation stands as it is written - each email answers that $thread_id = intval($opts['thread'] ?? 0); $thread = $thread_id && ticketMailThreadReady() ? ticketMailThread($thread_id, (string) ($opts['answering'] ?? '')) : null; // Replies to the mailbox ITFlow reads, when it is sent from another address (functions/ticket_reply_send.php) $reply_to = $thread_id ? ticketMailReplyToRead((string) $from['email']) : ''; $auto_headers = !empty($opts['auto']) ? ticketMailAutoHeaders((string) $opts['auto']) : []; $sent = []; foreach ($together ? [$people[0]] : $people as $recipient) { $address = $recipient['email']; $name = $recipient['name']; $cc = $together ? array_slice($people, 1) : []; $footnote = $together && isset($opts['together_footnote']) ? $opts['together_footnote'] : ($recipient['footnote'] ?? null); $html = emailHtml(array_merge($email, [ 'name' => array_key_exists('greet', $recipient) ? $recipient['greet'] : $name, ], $footnote !== null ? ['footnote' => $footnote] : [], !empty($recipient['unsubscribe']) && !$together ? ['unsubscribe' => (string) $recipient['unsubscribe']] : [])); // Its own headers - a List-Unsubscribe for its link - with the conversation's and the automatic ones $headers = ($thread !== null ? ticketMailHeaders($thread_id, (string) $from['email'], $thread) : []) + $auto_headers + (!$together ? (array) ($recipient['headers'] ?? []) : []) + ($reply_to !== '' ? ['Reply-To' => $reply_to] : []); // Its own Message-ID, for a bounce to find it by - a ticket's conversation made one already if (!isset($headers['Message-ID']) && mailQueueBounceReady()) { $headers['Message-ID'] = '<' . emailMessageId((string) $from['email']) . '>'; } $went = []; foreach (array_merge([$recipient], $cc) as $person) { $went[strtolower($person['email'])] = $person['name'] !== '' ? $person['name'] . ' (' . $person['email'] . ')' : $person['email']; } $cc_list = array_map(function ($person) { return ['email' => $person['email'], 'name' => $person['name']]; }, $cc); if (emailCapturing()) { $GLOBALS['itflow_email_capture'][] = ['to' => $address, 'to_name' => $name, 'cc' => $cc_list, 'from' => (string) $from['email'], 'from_name' => (string) $from['name'], 'subject' => (string) $subject, 'html' => $html, 'attachments' => $attachments, 'cal_str' => (string) ($opts['cal_str'] ?? '')]; $sent += $went; continue; } // Its pictures attached inline, not carried as data [$html, $images] = emailInlineImages($html, $pictures); $row = [ 'from' => mysqli_real_escape_string($mysqli, (string) $from['email']), 'from_name' => mysqli_real_escape_string($mysqli, emailFit($from['name'])), 'recipient' => mysqli_real_escape_string($mysqli, $address), 'recipient_name' => mysqli_real_escape_string($mysqli, emailFit($name !== '' ? $name : $address)), 'subject' => mysqli_real_escape_string($mysqli, (string) $subject), 'body' => mysqli_real_escape_string($mysqli, $html), 'attachments' => array_merge($attachments, $images), ] + (!empty($opts['cal_str']) ? ['cal_str' => (string) $opts['cal_str']] : []) + ($queued_at !== '' ? ['queued_at' => $queued_at] : []) + (intval($opts['ticket_reply_id'] ?? 0) > 0 && ticketReplyEmailReady() ? ['ticket_reply_id' => intval($opts['ticket_reply_id'])] : []) + (!empty($opts['sensitive']) ? ['sensitive' => 1] : []) + (!empty($opts['bulk']) ? ['bulk' => 1] : []) + (!empty($opts['about']) ? ['about' => (string) $opts['about']] : []) + ($cc_list ? ['cc' => $cc_list] : []) + ($headers ? ['headers' => $headers] : []); // Each on its own, so who it went to is only those queued - one that couldn't be is logged (addToMailQueue()) if (addToMailQueue([$row]) === 1) { $sent += $went; } } return array_values($sent); } /* * A new Message-ID - without its <> - at the domain of $from_email, or else ITFlow's own address: itflow.q.@domain. * The conversation of a ticket makes its own (ticketMailHeaders()). */ function emailMessageId($from_email) { 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'; } return 'itflow.q.' . bin2hex(random_bytes(12)) . '@' . $domain; } /* * $text cut to the $length characters a column of the mail queue holds - its subject and names (255) - * with an ellipsis. A ticket's subject can be 500 characters, and an email about one too long for * email_subject failed to queue under strict SQL mode, MariaDB's default. */ function emailFit($text, $length = 255) { $text = (string) $text; return mb_strlen($text) > $length ? rtrim(mb_substr($text, 0, $length - 1)) . '…' : $text; } /** The test email in Admin > Mail, from one of the mailboxes - system, ticket, invoice or quote. Who it went to - [] when it didn't. */ function emailTestSend($to, $mailbox) { $box = ['ticket' => emailFrom('ticket'), 'invoice' => billingEmailFrom('invoice'), 'quote' => billingEmailFrom('quote')][$mailbox] ?? emailFrom(); $which = ['system' => 'the system mailbox', 'ticket' => 'the ticket mailbox', 'invoice' => 'the invoice mailbox', 'quote' => 'the quote mailbox'][$mailbox] ?? 'the system mailbox'; return emailQueue([['email' => trim((string) $to), 'greet' => '', 'footnote' => 'You get this because someone sent a test from Admin > Mail in ITFlow.']], 'Test email from ITFlow', [ 'kind' => 'Test', 'tone' => 'success', 'preview' => "A test from $which", 'title' => 'Mail is working', 'intro' => ["This is a test email from ITFlow, sent from $which. If you are reading this, it worked."], 'summary' => ['From' => trim($box['name'] . ' <' . $box['email'] . '>'), 'To' => trim((string) $to), 'Sent' => date('D, M j, Y g:i A')], ], ['from' => ['email' => $box['email'], 'name' => $box['name']]]); } /* * Who an email to many goes to (emailBulkSend()), from contact rows - contact_id, contact_email, contact_name, client_name, * and contactBounceColumns() and contactUnsubscribeColumns() - each address once, with why they get it and their link to * leave. Left out and counted: an address that bounced (Email bounced - it only bounces again, and a run of bounces * counts against your domain), one that left this email (contactUnsubscribed()), no address, and the same one again. * ['recipients' => [...], 'out' => ['bounced' => n, 'unsubscribed' => n, 'none' => n, 'again' => n]]. */ function emailBulkRecipients(array $rows) { $company_name = (string) (billingCompany()['company_name'] ?? ''); $recipients = []; $out = ['bounced' => 0, 'unsubscribed' => 0, 'none' => 0, 'again' => 0]; // Left by any contact with the address - at another client, or added since (contactUnsubscribedAddresses()) $left = contactUnsubscribedAddresses(array_column($rows, 'contact_email')); $seen = []; foreach ($rows as $row) { $address = trim((string) ($row['contact_email'] ?? '')); $key = strtolower($address); if (!filter_var($address, FILTER_VALIDATE_EMAIL)) { $out['none']++; continue; } if (isset($seen[$key])) { $out['again']++; continue; } $seen[$key] = true; if (contactUnsubscribed($row) !== null || isset($left[$key])) { $out['unsubscribed']++; } elseif (contactBounce($row) !== null) { $out['bounced']++; } else { $link = contactUnsubscribeUrl($row['contact_id'] ?? 0, $address); $recipients[$key] = ['email' => $address, 'name' => (string) ($row['contact_name'] ?? ''), 'footnote' => "You received this as a contact for " . ($row['client_name'] ?? 'a client') . " with $company_name.", 'unsubscribe' => $link, // Mail programs show their own Unsubscribe from it, and leave with one click (RFC 8058) - guest/unsubscribe.php 'headers' => $link !== '' ? ['List-Unsubscribe' => "<$link>", 'List-Unsubscribe-Post' => 'List-Unsubscribe=One-Click'] : []]; } } return ['recipients' => array_values($recipients), 'out' => $out]; } /* * Send an email from the contacts or clients list (agent/includes/bulk_email_fields.php) to the contacts in $rows * (emailBulkRecipients()) - then say what happened, and who was left out, and go back. Refuses without mail set up, * a mailbox, a subject or a message. Send at is typed on the agent's own clock (Account > Preferences) and kept on * the company's, which the mail queue goes by - it was taken as the company's, hours out for an agent elsewhere. */ function emailBulkPost(array $rows) { global $session_name; $mailbox = (string) ($_POST['mailbox'] ?? ''); $subject = trim((string) ($_POST['subject'] ?? '')); $body = (string) ($_POST['body'] ?? ''); $at = trim((string) ($_POST['queued_at'] ?? '')); $at = $at !== '' ? timezoneFromView($at) : ''; $queued_at = $at !== '' && strtotime($at) ? date('Y-m-d H:i:s', strtotime($at)) : ''; if (!emailReady()) { flashAlert('Outgoing mail is not set up, so nothing was sent', 'error'); redirect(); } if (!isset(emailMailboxes()[$mailbox])) { flashAlert('Pick the mailbox it comes from', 'error'); redirect(); } if ($subject === '' || trim(strip_tags($body, '')) === '') { flashAlert('Give it a subject and a message - nothing was sent', 'error'); redirect(); } $picked = emailBulkRecipients($rows); $out = $picked['out']; $left_out = array_filter([ $out['bounced'] ? $out['bounced'] . ' marked Email bounced' : '', $out['unsubscribed'] ? $out['unsubscribed'] . ' unsubscribed' : '', $out['none'] + $out['again'] ? ($out['none'] + $out['again']) . ' with no email address, or the same one' : '', ]); $sent = $picked['recipients'] ? emailBulkSend($picked['recipients'], $mailbox, $_POST['mail_from_name'] ?? '', $subject, $body, !empty($_POST['greet']), $queued_at) : []; $count = count($sent); if (!$count) { flashAlert('Nothing was sent' . ($left_out ? ' - left out: ' . implode(', ', $left_out) : ' - none of them has an email address'), 'error'); redirect(); } $later = $queued_at !== '' && strtotime($queued_at) > time(); $later_view = $later ? ' to go ' . date('M j, Y g:i A', strtotime(timezoneToView($queued_at))) . (timezoneShifted() ? ' ' . timezoneAbbr(timezoneView()) : '') : ''; logAudit("Bulk Mail", "Send", "$session_name sent " . escapeSql($subject) . " to $count " . ($count === 1 ? 'contact' : 'contacts') . " via bulk mail" . ($later ? escapeSql(' to go ' . date('M j, Y g:i A', strtotime($queued_at))) : '') . ($left_out ? escapeSql(' - left out: ' . implode(', ', $left_out)) : '')); flashAlert("$count email" . ($count === 1 ? '' : 's') . " queued" . escapeHtml($later_view) . ($left_out ? ' - left out: ' . escapeHtml(implode(', ', $left_out)) : '')); redirect(); } /* * An email an agent writes to many contacts - Email on the contacts or clients * list - in the email look, with the logo and the company's details. Each * $recipients entry: email, name, footnote (why they get it), and unsubscribe and * headers (emailBulkRecipients() - the link to leave, List-Unsubscribe). $body is the * agent's HTML; $greet starts it "Hello Name,"; $from_name '' keeps the * mailbox's own; $queued_at when to send ('' for now). Who it was queued to. */ function emailBulkSend(array $recipients, $mailbox, $from_name, $subject, $body, $greet = false, $queued_at = '') { $boxes = emailMailboxes(); // A preview shows it before any mailbox is set up $box = $boxes[$mailbox] ?? (emailCapturing() ? emailFrom() : null); if (!$box) { return []; } $from_name = trim((string) $from_name); if (!$greet) { $recipients = array_map(function ($recipient) { return ['greet' => null] + $recipient; }, $recipients); } return emailQueue($recipients, trim((string) $subject), [ 'title' => trim((string) $subject), 'preview' => mb_substr(trim(preg_replace('/\s+/', ' ', html_entity_decode(strip_tags((string) $body), ENT_QUOTES, 'UTF-8'))), 0, 140), 'content' => (string) $body, ], ['from' => ['email' => $box['email'], 'name' => $from_name !== '' ? $from_name : $box['name']], 'queued_at' => $queued_at, 'bulk' => true]); }