Pasted pictures go with ticket emails as pictures attached inline: emailInlineImages takes each data image out of an email's HTML to uploads/tmp/mail_images, stored once by its hash, and points it at a cid that the mail queue attaches with addEmbeddedImage, so mail programs that show no data images show them and the queue keeps each picture once rather than in every email; Admin Mail Queue shows them back in the message and counts only files as attachments, a meeting request with pictures goes as an attached invite, and nightly removes pictures no queued email uses; 26.11.9 changelog entries

This commit is contained in:
johnnyq
2026-11-16 19:36:00 -05:00
parent 6eb6102dc0
commit 4faa0d91ca
8 changed files with 128 additions and 13 deletions

View File

@@ -829,10 +829,11 @@ function addToMailQueue($data) {
if (empty($attachment['path']) || empty($attachment['name'])) {
continue;
}
// A picture in the message goes in inline, where its cid: points (emailInlineImages())
$attachment_manifest[] = [
'path' => strval($attachment['path']),
'name' => strval($attachment['name'])
];
] + (!empty($attachment['cid']) ? ['cid' => preg_replace('/[^A-Za-z0-9@._-]/', '', (string) $attachment['cid'])] : []);
}
if ($attachment_manifest) {
$attachments = mysqli_escape_string($mysqli, json_encode($attachment_manifest));

View File

@@ -336,6 +336,49 @@ function emailPlainText($html, $limit = 0) {
return $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 <img> 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.
*/
function emailInlineImages($html) {
$images = [];
$html = (string) $html;
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('/<img\b[^>]*>/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
@@ -380,6 +423,8 @@ function emailQueue(array $recipients, $subject, array $email, array $opts = [])
'subject' => (string) $subject, 'html' => $html, 'attachments' => $attachments, 'cal_str' => (string) ($opts['cal_str'] ?? '')];
continue;
}
// Its pictures attached inline, not carried as data
[$html, $images] = emailInlineImages($html);
$data[] = [
'from' => mysqli_real_escape_string($mysqli, (string) $from['email']),
'from_name' => mysqli_real_escape_string($mysqli, (string) $from['name']),
@@ -387,7 +432,7 @@ function emailQueue(array $recipients, $subject, array $email, array $opts = [])
'recipient_name' => mysqli_real_escape_string($mysqli, $name !== '' ? $name : $address),
'subject' => mysqli_real_escape_string($mysqli, (string) $subject),
'body' => mysqli_real_escape_string($mysqli, $html),
'attachments' => $attachments,
'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'])] : [])

View File

@@ -25,6 +25,8 @@ const MAIL_QUEUE_TRIES = 4;
const MAIL_QUEUE_RETRY_MINUTES = 30;
const MAIL_QUEUE_KEEP_DAYS = 90;
const MAIL_QUEUE_CANCELLED = 4;
// Pictures that were in an email as data, kept once each for the queue to attach inline (emailInlineImages()) - the web can't reach uploads/tmp
const MAIL_QUEUE_IMAGE_DIR = 'uploads/tmp/mail_images';
/* The tabs of the list - key => [label, icon, SQL for what is in it]. */
function mailQueueTabs() {
@@ -246,6 +248,67 @@ function mailQueueErrorColumn() {
return mailQueueHasError() ? 'email_error' : 'NULL AS email_error';
}
/*
* What an email's manifest (email_attachments) holds - ['files' => names of the files attached,
* 'images' => [cid => app-relative path] of the pictures that go in its message (emailInlineImages())].
*/
function mailQueueAttachments($json) {
$out = ['files' => [], 'images' => []];
foreach ((array) json_decode((string) $json, true) as $attachment) {
if (!is_array($attachment) || trim((string) ($attachment['name'] ?? '')) === '') {
continue;
}
if (!empty($attachment['cid'])) {
$out['images'][(string) $attachment['cid']] = (string) ($attachment['path'] ?? '');
} else {
$out['files'][] = basename((string) $attachment['name']);
}
}
return $out;
}
/*
* An email's message with its pictures back in it as data, to show in Admin > Mail Queue - the
* message points at them by cid:, as the mail program that gets it reads them. One gone stays a cid:.
*/
function mailQueueShowImages($html, $json) {
$dir = realpath(dirname(__DIR__) . '/' . MAIL_QUEUE_IMAGE_DIR);
foreach (mailQueueAttachments($json)['images'] as $cid => $path) {
$file = $dir ? realpath(dirname(__DIR__) . '/' . $path) : false;
$info = $file && strpos($file, $dir . DIRECTORY_SEPARATOR) === 0 ? @getimagesize($file) : false;
if ($info) {
$html = str_replace('cid:' . $cid, 'data:' . $info['mime'] . ';base64,' . base64_encode((string) file_get_contents($file)), $html);
}
}
return $html;
}
/*
* Delete the pictures no email in the queue points at any more - left a day first, so one saved
* for an email being queued this minute stays (nightly). How many went.
*/
function mailQueueImageCleanup() {
global $mysqli;
$dir = dirname(__DIR__) . '/' . MAIL_QUEUE_IMAGE_DIR;
if (!is_dir($dir)) {
return 0;
}
$kept = [];
$sql = mysqli_query($mysqli, "SELECT email_attachments FROM email_queue WHERE email_attachments LIKE '%mail\\_images%'");
while ($row = mysqli_fetch_row($sql)) {
foreach (mailQueueAttachments($row[0])['images'] as $path) {
$kept[basename($path)] = true;
}
}
$removed = 0;
foreach (glob("$dir/*") ?: [] as $file) {
if (is_file($file) && !isset($kept[basename($file)]) && filemtime($file) < time() - 86400 && @unlink($file)) {
$removed++;
}
}
return $removed;
}
/* Is there an email_sensitive column yet? Database 3.7.1 adds it. */
function mailQueueHasSensitive() {
global $mysqli;