/) marked inline, and the text points at it: * * * * Kept inside the text as data, a few screenshots made a reply megabytes long, and every page * that read the ticket - the tickets list too - slowed with it. An inline picture shows where it * was put, and is left out of the ticket's list of files (ticketAttachmentsListedSql()). * * The text keeps the agent's address for a picture, which the agent's pages show as it is. The * client portal and the guest page put their own in its place (ticketPicturesHtml()), and an * email carries the picture itself (ticketPicturesAsData(), emailInlineImages()). Pictures kept * as data from before - or by something that doesn't make them files, a recurring ticket's or a * template's - move to files a batch a minute (ticketPicturesSweep(), cron/ticket_pictures.php). * * All of it once the 4.2.4 update has made ticket_attachments.ticket_attachment_inline - before * that, pictures stay as data, as they were. */ /* The kinds of picture kept as files - any other (an SVG, say) stays as it was */ const TICKET_PICTURE_TYPES = [IMAGETYPE_PNG => 'png', IMAGETYPE_JPEG => 'jpg', IMAGETYPE_GIF => 'gif', IMAGETYPE_WEBP => 'webp']; /* Has the 4.2.4 update made ticket_attachments.ticket_attachment_inline? */ function ticketPicturesReady() { global $mysqli; static $ready = null; if ($ready === null) { if (defined('CURRENT_DATABASE_VERSION')) { $version = CURRENT_DATABASE_VERSION; } else { $result = mysqli_query($mysqli, "SELECT config_current_database_version FROM settings WHERE company_id = 1"); $version = $result && ($row = mysqli_fetch_row($result)) ? (string) $row[0] : '0'; } $ready = version_compare($version, '4.2.4', '>='); } return $ready; } /* For a query of the files a ticket lists - not its inline pictures */ function ticketAttachmentsListedSql() { return ticketPicturesReady() ? ' AND ticket_attachment_inline = 0' : ''; } /* Is this attachment row (with ticket_attachment_inline, when there is one) a picture in a ticket's text? */ function ticketAttachmentIsPicture(array $row) { return ticketPicturesReady() && intval($row['ticket_attachment_inline'] ?? 0) === 1; } /* How many pictures this run couldn't keep as files - left as data - with $add counted on (the Ticket Pictures cron job says so) */ function ticketPicturesFailed($add = 0) { static $failed = 0; $failed += intval($add); return $failed; } /* A picture's address in a ticket's text, as it goes in the HTML */ function ticketPictureUrl($attachment_id) { return '/agent/ticket_attachment.php?attachment_id=' . intval($attachment_id) . '&action=view'; } /* A picture's address, matched - relative, or with this ITFlow's address in front, never another site's - id in [1] */ function ticketPicturePattern() { global $config_base_url; $site = !empty($config_base_url) ? '|https?://' . preg_quote((string) $config_base_url, '#') : ''; return '#(?:(?<=["\'\s=])' . $site . ')/agent/ticket_attachment\.php\?attachment_id=(\d+)(?:&(?:amp;)?(?:action|thumb)=[a-z0-9]*)*#i'; } /* The attachment ids of the pictures a text points at */ function ticketPictureIds($html) { $html = (string) $html; if (stripos($html, 'ticket_attachment.php') === false || !preg_match_all(ticketPicturePattern(), $html, $m)) { return []; } return array_values(array_unique(array_map('intval', $m[1]))); } /* * The pictures in $html kept as data made the ticket's files - against $reply_id, or the ticket * itself when null - each pointing at its file instead. A tag at a time, as a scan through * a large picture's data runs out of PCRE's backtracking (emailInlineImages()); one that isn't a * picture of a kind kept (TICKET_PICTURE_TYPES), or can't be saved, stays as it was. [html, how many]. */ function ticketPicturesFromData($html, $ticket_id, $reply_id = null) { global $mysqli; $html = (string) $html; $ticket_id = intval($ticket_id); if (!$ticket_id || stripos($html, 'data:image/') === false) { return [$html, 0]; } $dir = dirname(__DIR__) . "/uploads/tickets/$ticket_id/"; $reply_sql = $reply_id ? intval($reply_id) : 'NULL'; $saved = 0; $out = preg_replace_callback('/]*>/i', function ($tag) use ($dir, $ticket_id, $reply_sql, &$saved, $mysqli) { if (!preg_match('/\ssrc\s*=\s*(["\'])data:image\/[a-z0-9+.-]+;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 ? (TICKET_PICTURE_TYPES[$info[2]] ?? '') : ''; if ($ext === '') { return $tag[0]; } // Left as data when it can't be saved - the folder not writable by the user PHP runs as, say $reference = randomString(32) . ".$ext"; if ((!is_dir($dir) && !@mkdir($dir, 0775, true)) || @file_put_contents($dir . $reference, $data) === false) { ticketPicturesFailed(1); return $tag[0]; } $name = 'picture-' . substr(hash('sha256', $data), 0, 8) . ".$ext"; try { $attachment_id = mysqli_query($mysqli, "INSERT INTO ticket_attachments SET ticket_attachment_name = '$name', ticket_attachment_reference_name = '$reference', ticket_attachment_inline = 1, ticket_attachment_reply_id = $reply_sql, ticket_attachment_ticket_id = $ticket_id") ? intval(mysqli_insert_id($mysqli)) : 0; } catch (mysqli_sql_exception $e) { $attachment_id = 0; } if (!$attachment_id) { @unlink($dir . $reference); ticketPicturesFailed(1); return $tag[0]; } $saved++; return str_replace($m[0], ' src=' . $m[1] . ticketPictureUrl($attachment_id) . $m[1], $tag[0]); }, $html); return $out === null ? [$html, 0] : [$out, $saved]; } /* * Each picture's given alt text - one without any, or with the address that HTMLPurifier * puts in when there is none (copied from a page that showed it), says Picture. That is what an * email shows while its pictures are off. */ function ticketPicturesAlt($html) { $html = (string) $html; if (stripos($html, 'ticket_attachment.php') === false) { return $html; } $out = preg_replace_callback('/]*>/i', function ($tag) { if (stripos($tag[0], 'ticket_attachment.php') === false) { return $tag[0]; } if (preg_match('/\salt\s*=\s*(["\'])[^"\']*ticket_attachment\.php[^"\']*\1/i', $tag[0], $m)) { return str_replace($m[0], ' alt="Picture"', $tag[0]); } return preg_match('/\salt\s*=/i', $tag[0]) ? $tag[0] : preg_replace('/^ * address] for a copy kept elsewhere (a client export) - its pictures pointing at that place's * own address for them. Before HTMLPurifier, which keeps them. */ function ticketPicturesHtml($html, $for, array $ticket = []) { $html = (string) $html; if (stripos($html, 'ticket_attachment.php') === false) { return $html; } $out = preg_replace_callback(ticketPicturePattern(), function ($m) use ($for, $ticket) { $id = intval($m[1]); if (is_array($for)) { return isset($for[$id]) ? escapeHtml($for[$id]) : $m[0]; } if ($for === 'client') { return '/client/ticket_attachment.php?attachment_id=' . $id . '&action=view'; } if ($for === 'guest') { return '/guest/guest_ticket_attachment.php?ticket_id=' . intval($ticket['ticket_id'] ?? 0) . '&url_key=' . rawurlencode((string) ($ticket['ticket_url_key'] ?? '')) . '&attachment_id=' . $id . '&action=view'; } return $m[0]; }, $html); return $out ?? $html; } /* * A ticket's text with its own pictures in it as data - for an email (emailInlineImages() makes * them its inline pictures) or a page that can't link to them (a task approval). Only the ticket's * pictures, and with $internal false only those the client can see: on the ticket itself or a * reply that isn't an internal note or archived. Any other stays as it was. */ function ticketPicturesAsData($html, $ticket_id, $internal = false) { global $mysqli; $ids = ticketPictureIds($html); $ticket_id = intval($ticket_id); if (!$ids || !$ticket_id || !ticketPicturesReady()) { return (string) $html; } $sql = mysqli_query($mysqli, "SELECT ticket_attachment_id, ticket_attachment_reference_name FROM ticket_attachments LEFT JOIN ticket_replies ON ticket_reply_id = ticket_attachment_reply_id WHERE ticket_attachment_id IN (" . implode(',', $ids) . ") AND ticket_attachment_ticket_id = $ticket_id AND ticket_attachment_inline = 1" . ($internal ? '' : " AND (ticket_attachment_reply_id IS NULL OR (ticket_reply_type != 'Internal' AND ticket_reply_archived_at IS NULL))")); $dir = realpath(dirname(__DIR__) . "/uploads/tickets/$ticket_id"); $data = []; while ($row = mysqli_fetch_assoc($sql)) { $file = $dir ? realpath($dir . '/' . basename((string) $row['ticket_attachment_reference_name'])) : false; $info = $file && strpos($file, $dir . DIRECTORY_SEPARATOR) === 0 ? @getimagesize($file) : false; if ($info && isset(TICKET_PICTURE_TYPES[$info[2]])) { $data[intval($row['ticket_attachment_id'])] = 'data:' . $info['mime'] . ';base64,' . base64_encode((string) file_get_contents($file)); } } if (!$data) { return (string) $html; } $out = preg_replace_callback(ticketPicturePattern(), function ($m) use ($data) { return $data[intval($m[1])] ?? $m[0]; }, (string) $html); return $out ?? (string) $html; } /* * Pictures still kept as data in tickets' details and replies made files - the tickets, then the * replies, in order, from where the last run got to (settings.config_ticket_pictures_ticket_id and * config_ticket_pictures_reply_id), for up to $seconds. Once through, each run looks at what is * newer, so a picture something kept as data - a recurring ticket's, say - is a file a minute * later. ['moved' => pictures, 'texts' => details and replies changed, 'behind' => more to do, * 'failed' => pictures left as data, as they couldn't be saved]. */ function ticketPicturesSweep($seconds = 25) { global $mysqli; if (!ticketPicturesReady()) { return null; } $deadline = microtime(true) + $seconds; $state = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT config_ticket_pictures_ticket_id, config_ticket_pictures_reply_id FROM settings WHERE company_id = 1")); $moved = $texts = 0; $behind = false; foreach ([ 'ticket' => ['tickets', 'ticket_id', 'ticket_details', 'config_ticket_pictures_ticket_id'], 'reply' => ['ticket_replies', 'ticket_reply_id', 'ticket_reply', 'config_ticket_pictures_reply_id'], ] as $kind => [$table, $key, $column, $setting]) { $from = intval($state[$setting] ?? 0); $last = intval(mysqli_fetch_row(mysqli_query($mysqli, "SELECT COALESCE(MAX($key), 0) FROM $table"))[0] ?? 0); // Past the newest there is - the table was emptied (a demo's reset, say) - so from the start if ($from > $last) { $from = 0; } while ($from < $last && microtime(true) < $deadline) { $to = min($from + 500, $last); // The ids read up front - once a query has failed and been caught, fetching on from a result still open throws it again $ids = array_map('intval', array_column(mysqli_fetch_all(mysqli_query($mysqli, "SELECT $key FROM $table WHERE $key > $from AND $key <= $to AND $column LIKE '%data:image/%' ORDER BY $key")), 0)); foreach ($ids as $id) { if (microtime(true) >= $deadline) { // Back to just before the one there was no time for $to = $id - 1; break; } // One that fails is left as it is, not tried every run ahead of all the others try { $moved += ticketPicturesSaveText($kind, $id); } catch (Throwable $e) { ticketPicturesFailed(1); } $texts++; } $from = $to; mysqli_query($mysqli, "UPDATE settings SET $setting = $from WHERE company_id = 1"); } if ($from < $last) { $behind = true; } } return ['moved' => $moved, 'texts' => $texts, 'behind' => $behind, 'failed' => ticketPicturesFailed()]; }