Document and Knowledge Base article PDFs with the letterhead look: logo and company details on the first page, the name with the client, folder and last update, a running header on later pages, a footer with the company, Confidential or Knowledge Base, the date and page numbers, tables with lines, shaded code, checklist boxes, symbols the old font could not draw, and headings as bookmarks; WebP pictures now show in document PDFs and the client documentation PDF; 26.12.3 changelog entries

This commit is contained in:
johnnyq
2026-11-29 13:13:36 -05:00
parent 08f4c74253
commit fcdb014786
5 changed files with 433 additions and 36 deletions

View File

@@ -20,6 +20,7 @@ Update from Maintenance > Update as usual - this release has three database chan
- Markdown files: the menu beside Upload on a client's Files has Import Markdown Files, which makes a document from each .md file picked, named by the heading it starts with or its file name. A document's page has a Markdown button beside PDF, which downloads it as a .md file - rich text documents too.
- Markdown pasted into a document's rich text editor - copied from GitHub, VS Code, Obsidian or an AI chat - goes in as formatting. Ctrl+Shift+V pastes it as it is.
- A document's page is easier to read: headings in proportion to the text with room between sections, and tables, code and quotes that look part of it. Under its name are its folder, its template, Markdown when it's written in it, and its review - due, or when it's next due - whose menu has Mark Reviewed and how often. The buttons are Edit, Share and Export (PDF, Markdown or Print), with the rest in the ⋮ menu, now including Template. Beside it, Contents marks the section you're reading, and Linked, Versions and History are tabs of one card: Linked shows each kind of record with its count, opening to the list.
- A document's PDF, and a Knowledge Base article's, look like your invoices and the documentation PDF: your logo and company details at the top, then its name with the client, its folder (an article's category) and when it was last updated and by whom, and its summary. Each later page has the client and the name at the top, and every page your company, Confidential (Knowledge Base for an article) and the date at the foot, with the page number. Tables have lines, code is shaded, a checklist shows its boxes, symbols such as ✓ and → show, and a document with headings has them as bookmarks beside the PDF.
- Pictures in tickets are kept as files: a screenshot pasted or dropped into a ticket, a reply or a note - by your team, in the client portal or through the API - and the pictures in a client's email are kept with the ticket as files instead of inside its text. A ticket full of screenshots opens quickly, and so do the tickets list and the client portal. Pictures show where they were put and stay out of the ticket's list of files, and emails carry them as before.
- Pictures already inside tickets move to files in the background - the new Ticket Pictures job in Maintenance > Cron does a batch every minute until every ticket is done, then keeps an eye on new ones.
- Taking a picture out of a reply or the ticket's details when editing it, or redacting it, deletes it - it no longer opens from an old link. Redact now takes a picture selected on its own, as well as text.
@@ -29,6 +30,7 @@ Update from Maintenance > Update as usual - this release has three database chan
- Documents created or edited through the API no longer get extra backslashes added before quotes and line breaks, and changing only a document's name through the API no longer changes what it says.
- Deleting a client deletes its tickets' attachments and pictures, files and all, and their tasks, watchers and history, instead of leaving them behind.
- Pictures saved as WebP show in a client's documentation PDF and a document's PDF instead of being left out.
### Developer Updates
@@ -48,6 +50,7 @@ Update from Maintenance > Update as usual - this release has three database chan
- ticketPicturesHtml() points the pictures at /client/ticket_attachment.php in the portal, /guest/guest_ticket_attachment.php on the guest page and at the files in a client export; ticketPicturesAsData() puts a ticket's pictures back as data for an email and the task approval page. emailQueue() takes opts ticket_id (the pictures the client can see), and ticketAgentEmailContent() sets $email['ticket_pictures'] for agents' emails (internal notes' too), which emailInlineImages() turns into inline cid: pictures as before. ticketAttachmentsListedSql() keeps inline pictures out of the attachment lists; opening one isn't audit logged.
- New cron job ticket_pictures (cron/ticket_pictures.php, every minute): ticketPicturesSweep() goes through tickets then replies whose text has data:image/, 500 ids at a time, for up to 25 seconds a run.
- A picture that can't be saved - the folder not writable, the attachment row not going in - stays as data in the text; ticketPicturesFailed() counts them, ticketPicturesSweep() carries on past a ticket or reply that fails, and the Ticket Pictures job logs a warning (Cron-Ticket-Pictures) when there were any. bulk_add_client_ticket keeps its pictures as files straight away; deleting a client deletes its tickets with ticketDeleteForGood().
- functions/document_pdf.php: DocumentPdf (TCPDF) and documentPdfRender() draw the document and Knowledge Base article PDFs (export_document in agent/post/document.php, export_kb_article in agent/post/kb.php), from documentPdfDocument() / documentPdfKbArticle(), and are sent with billingPdfSend(). documentPdfParts() splits the purified HTML at its top-level headings (inside a Markdown document's wrapper) for the bookmarks, and puts table lines, header cells and code shading in inline styles, which TCPDF reads where it ignores the style block. clientExportPdfImages() is clientExportPdfDocumentHtml()'s image step on its own, for uploads/documents or uploads/kb, and now turns a WebP picture into a PNG.
## [26.12.2]

View File

@@ -446,23 +446,10 @@ if (isset($_GET['export_document'])) {
logAudit("Document", "Export", "$session_name exported document " . escapeSql($row['document_name']), $client_id, $document_id);
require_once('../libs/TCPDF/tcpdf.php');
$pdf = new TCPDF();
$pdf->SetCreator(PDF_CREATOR);
$pdf->SetAuthor($session_name);
$pdf->SetTitle($row['document_name']);
$pdf->AddPage();
$pdf->SetFont('helvetica', '', 12);
// A Markdown checklist's boxes as [x] and [ ] - the PDF's font has no box characters
$pdf_content = preg_replace_callback('#<span class="itflow-task( is-done)?">[^<]*</span>#', function ($m) {
return empty($m[1]) ? '[ ]' : '[x]';
}, $row['document_content']);
$pdf->writeHTML('<h1>' . escapeHtml($row['document_name']) . '</h1>' . $pdf_content, true, false, true, false, '');
// The PDF is the response - nothing may follow it
$pdf->Output(preg_replace('/[^A-Za-z0-9 ._-]/', '', $row['document_name']) . '.pdf', 'I');
exit;
// With the company's letterhead, page numbers and its headings as bookmarks (functions/document_pdf.php)
require_once '../libs/TCPDF/tcpdf.php';
require_once '../functions/document_pdf.php';
billingPdfSend(documentPdfRender(documentPdfDocument($row)));
}

View File

@@ -464,20 +464,8 @@ if (isset($_GET['export_kb_article'])) {
logAudit("Knowledge Base", "Export", "$session_name exported article " . escapeSql($row['kb_article_title']) . " as a PDF", 0, intval($row['kb_article_id']));
// With the company's letterhead, page numbers and its headings as bookmarks (functions/document_pdf.php)
require_once '../libs/TCPDF/tcpdf.php';
$pdf = new TCPDF();
$pdf->SetCreator(PDF_CREATOR);
$pdf->SetAuthor($session_name);
$pdf->SetTitle($row['kb_article_title']);
$pdf->setPrintHeader(false);
$pdf->AddPage();
$pdf->SetFont('helvetica', '', 11);
$summary = trim((string) $row['kb_article_summary']);
$pdf->writeHTML('<h1>' . escapeHtml($row['kb_article_title']) . '</h1>' . ($summary !== '' ? '<p><i>' . escapeHtml($summary) . '</i></p>' : '')
. documentHtmlPurify((string) $row['kb_article_content']), true, false, true, false, '');
// The PDF is the response - nothing may follow it
$pdf->Output(preg_replace('/[^A-Za-z0-9 ._-]/', '', $row['kb_article_title']) . '.pdf', 'I');
exit;
require_once '../functions/document_pdf.php';
billingPdfSend(documentPdfRender(documentPdfKbArticle($row)));
}

View File

@@ -1021,25 +1021,42 @@ function clientExportPdfFacts(array $facts, $label_width = 26) {
* page.
*/
function clientExportPdfDocumentHtml($html, $document_id) {
$html = documentHtmlPurify($html);
return clientExportPdfImages(documentHtmlPurify($html), $document_id);
}
/**
* The images of purified HTML made fit for TCPDF, as above - its own from
* uploads/<$folder>/<id>/ (documents, or kb for an article) inlined, a WebP
* one as a PNG, any other dropped. Also for a document's or an article's own
* PDF (functions/document_pdf.php).
*/
function clientExportPdfImages($html, $id, $folder = 'documents') {
if (stripos($html, '<img') === false) {
return $html;
}
$base = realpath(__DIR__ . '/../uploads/documents/' . intval($document_id));
return preg_replace_callback('/<img\b[^>]*>/i', function ($match) use ($base) {
$folder = $folder === 'kb' ? 'kb' : 'documents';
$base = realpath(__DIR__ . "/../uploads/$folder/" . intval($id));
return preg_replace_callback('/<img\b[^>]*>/i', function ($match) use ($base, $folder) {
$tag = $match[0];
$src = preg_match('/\bsrc\s*=\s*"([^"]*)"/i', $tag, $m) ? html_entity_decode($m[1], ENT_QUOTES, 'UTF-8') : '';
$alt = preg_match('/\balt\s*=\s*"([^"]*)"/i', $tag, $m) ? $m[1] : '';
$data = null;
if (preg_match('#^data:image/(png|jpe?g|gif);base64,(.+)$#is', $src, $m)) {
$data = base64_decode($m[2], true) ?: null;
} elseif ($base && preg_match('#^/?uploads/documents/\d+/([^/?\#]+)$#', $src, $m)) {
} elseif ($base && preg_match('#^/?uploads/' . $folder . '/\d+/([^/?\#]+)$#', $src, $m)) {
$path = realpath($base . '/' . rawurldecode($m[1]));
if ($path && strpos($path, $base . DIRECTORY_SEPARATOR) === 0 && is_file($path)) {
$data = file_get_contents($path);
}
}
$info = $data ? @getimagesizefromstring($data) : false;
// A WebP one as a PNG, which TCPDF can draw
if ($info && $info[2] === IMAGETYPE_WEBP && function_exists('imagewebp') && ($image = @imagecreatefromstring($data))) {
ob_start();
imagepng($image);
$data = ob_get_clean();
$info = @getimagesizefromstring($data);
}
if (!$info || !in_array($info[2], [IMAGETYPE_PNG, IMAGETYPE_JPEG, IMAGETYPE_GIF], true)) {
return $alt !== '' ? '<i>[' . $alt . ']</i>' : '<i>[image]</i>';
}

402
functions/document_pdf.php Normal file
View File

@@ -0,0 +1,402 @@
<?php
/*
* A document's PDF, and a Knowledge Base article's - loaded by the PDF
* handlers in agent/post/document.php and agent/post/kb.php once TCPDF
* itself is, as a class has to follow the one it extends.
*
* The look of an invoice and of the documentation export: on the first page
* the accent band, the logo and who it is from, then the title, where it is
* kept and when it was last updated, and what it says. Later pages have a
* running header with the client (Knowledge Base, for an article) and the
* title, and every page a footer with the company, Confidential (Knowledge
* Base for an article, as one can be public), the date and "Page 2 of 5".
* A document with headings has them as the PDF's bookmarks.
*
* TCPDF's own Error() kills the request; this one throws, so what TCPDF
* cannot draw is printed as plain text instead.
*/
class DocumentPdf extends TCPDF {
public $running_left = '';
public $running_right = '';
public $footer_label = '';
public function __construct(...$args) {
parent::__construct(...$args);
// Leave the page mode to the bookmarks, which open beside the PDF -
// TCPDF would otherwise write a second, conflicting /PageMode
$this->PageMode = '';
}
public function Header() {
// The first page has the accent band, as an invoice does
if ($this->getPage() <= 1) {
$this->SetFillColor(13, 110, 253);
$this->Rect(0, 0, $this->getPageWidth(), 2.5, 'F');
return;
}
$margins = $this->getMargins();
$width = $this->getPageWidth() - $margins['left'] - $margins['right'];
$this->SetY(9);
$this->SetFont('dejavusans', '', 7.5);
$this->SetTextColor(108, 117, 125);
$this->Cell($width * 0.4, 4, $this->running_left, 0, 0, 'L', false, '', 1);
$this->Cell($width * 0.6, 4, $this->running_right, 0, 1, 'R', false, '', 1);
$this->SetDrawColor(222, 226, 230);
$this->SetLineWidth(0.2);
$this->Line($margins['left'], 14, $this->getPageWidth() - $margins['right'], 14);
}
public function Footer() {
$margins = $this->getMargins();
$width = $this->getPageWidth() - $margins['left'] - $margins['right'];
$this->SetY(-14);
$this->SetDrawColor(222, 226, 230);
$this->SetLineWidth(0.2);
$this->Line($margins['left'], $this->GetY() - 1.5, $this->getPageWidth() - $margins['right'], $this->GetY() - 1.5);
$this->SetFont('dejavusans', '', 7);
$this->SetTextColor(108, 117, 125);
$this->Cell($width * 0.75, 4, $this->footer_label, 0, 0, 'L');
$this->Cell($width * 0.25, 4, 'Page ' . $this->getAliasNumPage() . ' of ' . $this->getAliasNbPages(), 0, 0, 'R');
}
public function Error($msg) {
throw new Exception('TCPDF: ' . $msg);
}
}
/** What goes in a document's PDF - for documentPdfRender(), from documentForHandler()'s row. */
function documentPdfDocument(array $row) {
global $mysqli;
$client_id = intval($row['document_client_id']);
$client = mysqli_fetch_row(mysqli_query($mysqli, "SELECT client_name FROM clients WHERE client_id = $client_id"));
$tree = folderTree($client_id);
$folder_id = intval($row['document_folder_id']);
$by_id = intval($row['document_updated_by']) ?: intval($row['document_created_by']);
$by = $by_id ? mysqli_fetch_row(mysqli_query($mysqli, "SELECT user_name FROM users WHERE user_id = $by_id")) : null;
return [
'kind' => 'document',
'id' => intval($row['document_id']),
'title' => (string) $row['document_name'],
'description' => (string) $row['document_description'],
'html' => (string) $row['document_content'],
'client' => (string) ($client[0] ?? ''),
'place' => isset($tree[$folder_id]) ? implode(' / ', array_column(folderPath($tree, $folder_id), 'folder_name')) : '',
'updated' => $row['document_updated_at'] ?: $row['document_created_at'],
'by' => (string) ($by[0] ?? ''),
];
}
/** What goes in a Knowledge Base article's PDF - for documentPdfRender(), from kbArticleRow(). */
function documentPdfKbArticle(array $row) {
return [
'kind' => 'kb',
'id' => intval($row['kb_article_id']),
'title' => (string) $row['kb_article_title'],
'description' => trim((string) $row['kb_article_summary']),
'html' => (string) $row['kb_article_content'],
'client' => '',
'place' => (string) ($row['category_name'] ?? ''),
'updated' => $row['kb_article_updated_at'] ?: $row['kb_article_created_at'],
'by' => (string) (($row['kb_article_updated_at'] ? $row['updated_by_name'] : $row['created_by_name']) ?? ''),
];
}
/** How what it says looks in the PDF - TCPDF reads a style block with each piece it draws. */
function documentPdfStyle() {
return '<style>
h1 { font-size: 14pt; color: #212529; }
h2 { font-size: 12pt; color: #212529; }
h3 { font-size: 10.5pt; color: #212529; }
h4, h5, h6 { font-size: 9.5pt; color: #212529; }
a { color: #0a58ca; text-decoration: none; }
blockquote { color: #495057; }
span.itflow-task { color: #6c757d; }
</style>';
}
/*
* What it says, ready for TCPDF and split at its headings into [heading's
* text, bookmark level, HTML] - so each heading can be a bookmark where it
* falls. Only headings at the top of the document (or of the one wrapper a
* Markdown document has) split it; one inside a table or a list stays where
* it is. Two or more headings are needed - with fewer, or HTML that won't
* parse, it is one piece with no heading.
*
* TCPDF takes some looks only from an element's own style, not the style
* block: a table's lines and header cells (unless it was made without
* lines, border="0"), and code's typeface and shading.
*/
function documentPdfParts($html) {
$whole = [['', 0, $html]];
if (trim($html) === '') {
return $whole;
}
$dom = new DOMDocument();
$errors = libxml_use_internal_errors(true);
$loaded = $dom->loadHTML('<?xml encoding="utf-8"?><div>' . $html . '</div>', LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD | LIBXML_PARSEHUGE | LIBXML_NONET);
libxml_clear_errors();
libxml_use_internal_errors($errors);
$root = $loaded ? $dom->getElementsByTagName('div')->item(0) : null;
if (!$root) {
return $whole;
}
$style = function (DOMElement $element, $css) {
$element->setAttribute('style', $css . $element->getAttribute('style'));
};
foreach (iterator_to_array($dom->getElementsByTagName('table')) as $table) {
// Its own rows - not those of a table inside one - each kept whole on a page
$rows = [];
foreach ($table->childNodes as $child) {
$name = strtolower($child->nodeName);
if ($name === 'tr') {
$rows[] = $child;
} elseif (in_array($name, ['thead', 'tbody', 'tfoot'], true)) {
foreach ($child->childNodes as $row) {
if (strtolower($row->nodeName) === 'tr') {
$rows[] = $row;
}
}
}
}
foreach ($rows as $row) {
$row->setAttribute('nobr', 'true');
}
$border = trim($table->getAttribute('border'));
if ($border !== '' && intval($border) === 0 && strpos(' ' . $table->getAttribute('class') . ' ', ' table-bordered ') === false) {
continue;
}
$table->removeAttribute('border');
$table->setAttribute('cellspacing', '0');
if (!$table->hasAttribute('cellpadding')) {
$table->setAttribute('cellpadding', '4');
}
foreach ($rows as $row) {
foreach ($row->childNodes as $cell) {
$name = strtolower($cell->nodeName);
if ($name === 'td' || $name === 'th') {
$style($cell, 'border:0.3px solid #adb5bd;' . ($name === 'th' ? 'background-color:#f1f3f5;font-weight:bold;' : ''));
}
}
}
}
foreach (iterator_to_array($dom->getElementsByTagName('pre')) as $pre) {
$style($pre, 'font-family:dejavusansmono;font-size:8pt;background-color:#f1f3f5;');
// Without the line break a Markdown code block ends with, drawn as an empty line
$last = $pre->lastChild;
while ($last && $last->nodeType === XML_ELEMENT_NODE && $last->lastChild) {
$last = $last->lastChild;
}
if ($last && $last->nodeType === XML_TEXT_NODE) {
$last->nodeValue = rtrim($last->nodeValue, "\r\n");
}
}
foreach (iterator_to_array($dom->getElementsByTagName('code')) as $code) {
$style($code, 'font-family:dejavusansmono;font-size:8.5pt;');
}
// A task list without bullets as well as its boxes
foreach (iterator_to_array($dom->getElementsByTagName('ul')) as $list) {
$items = 0;
$tasks = 0;
foreach ($list->childNodes as $item) {
if (strtolower($item->nodeName) === 'li') {
$items++;
$first = $item->firstChild;
while ($first && $first->nodeType === XML_TEXT_NODE && trim($first->nodeValue) === '') {
$first = $first->nextSibling;
}
$tasks += $first && $first->nodeType === XML_ELEMENT_NODE && strpos(' ' . $first->getAttribute('class') . ' ', ' itflow-task ') !== false ? 1 : 0;
}
}
if ($items && $tasks === $items) {
$style($list, 'list-style-type:none;');
}
}
// The line breaks between blocks - Markdown's - which TCPDF draws as space
$blocks = '/^(address|blockquote|dd|div|dl|dt|h[1-6]|hr|li|ol|p|pre|table|tbody|td|tfoot|th|thead|tr|ul)$/';
foreach (iterator_to_array((new DOMXPath($dom))->query('//text()[normalize-space(.) = ""]')) as $space) {
$parent = strtolower($space->parentNode->nodeName);
$near = [$space->previousSibling, $space->nextSibling];
$by_block = false;
foreach ($near as $node) {
$by_block = $by_block || ($node && $node->nodeType === XML_ELEMENT_NODE && preg_match($blocks, strtolower($node->nodeName)));
}
if ($parent !== 'pre' && ($by_block || preg_match($blocks, $parent) && !$space->previousSibling || preg_match($blocks, $parent) && !$space->nextSibling)) {
$space->parentNode->removeChild($space);
}
}
// Into a lone wrapper - a Markdown document's <div class="itflow-markdown">
while (true) {
$elements = [];
$text = '';
foreach ($root->childNodes as $node) {
if ($node->nodeType === XML_ELEMENT_NODE) {
$elements[] = $node;
} else {
$text .= $node->textContent;
}
}
if (count($elements) !== 1 || strtolower($elements[0]->nodeName) !== 'div' || trim($text) !== '') {
break;
}
$root = $elements[0];
}
$parts = [];
$levels = [];
$current = ['', 0, ''];
foreach ($root->childNodes as $node) {
$tag = $node->nodeType === XML_ELEMENT_NODE ? strtolower($node->nodeName) : '';
$heading = preg_match('/^h([1-6])$/', $tag, $m) ? trim(preg_replace('/\s+/u', ' ', $node->textContent)) : '';
if ($heading !== '') {
if ($current[2] !== '' || $current[0] !== '') {
$parts[] = $current;
}
$current = [$heading, intval($m[1]), ''];
$levels[] = intval($m[1]);
}
$current[2] .= $dom->saveHTML($node);
}
$parts[] = $current;
if (count($levels) < 2) {
// One piece, with the looks above
return [['', 0, implode('', array_column($parts, 2))]];
}
// Under the title, at 1: the document's biggest heading, and each smaller one a level further in
$top = min($levels);
foreach ($parts as &$part) {
$part[1] = $part[0] !== '' ? 1 + $part[1] - $top : 0;
}
return $parts;
}
/** Draw a document or an article (documentPdfDocument(), documentPdfKbArticle()) - ['name' => file name, 'data' => the PDF]. */
function documentPdfRender(array $item) {
$company = billingCompany();
$kb = $item['kind'] === 'kb';
$e = function ($value) {
return htmlspecialchars((string) $value, ENT_QUOTES, 'UTF-8');
};
$grey = '#6c757d';
$title = (string) $item['title'];
// Letter for North America, A4 everywhere else
$format = in_array($company['company_country'] ?? '', ['United States', 'USA', 'US', 'Canada'], true) ? 'LETTER' : 'A4';
$pdf = new DocumentPdf('P', 'mm', $format, true, 'UTF-8', false);
$pdf->SetCreator('ITFlow');
$pdf->SetAuthor((string) ($company['company_name'] ?? ''));
$pdf->SetTitle($title);
$pdf->SetSubject($kb ? 'Knowledge Base' : (string) $item['client']);
$pdf->SetMargins(16, 20, 16);
$pdf->SetHeaderMargin(8);
$pdf->SetFooterMargin(12);
$pdf->SetAutoPageBreak(true, 20);
$pdf->setFontSubsetting(true);
$pdf->setImageScale(1.6);
$pdf->running_left = $kb ? 'Knowledge Base' : (string) $item['client'];
$pdf->running_right = mb_strimwidth($title, 0, 90, '…', 'UTF-8');
$pdf->footer_label = implode(' · ', array_filter([(string) ($company['company_name'] ?? ''), $kb ? 'Knowledge Base' : 'Confidential', date('M j, Y')]));
$margins = $pdf->getMargins();
$width = $pdf->getPageWidth() - $margins['left'] - $margins['right'];
// By reference: a rolled-back document swaps the object out from under it
$write = function ($html) use (&$pdf) {
$pdf->SetFont('dejavusans', '', 9);
$pdf->SetTextColor(33, 37, 41);
$pdf->writeHTML(documentPdfStyle() . $html, true, false, true, false, '');
};
$pdf->AddPage();
$pdf->SetY(12);
// Who it is from
$from_lines = array_filter([
formatAddress($company['company_address'] ?? '', $company['company_city'] ?? '', $company['company_state'] ?? '', $company['company_zip'] ?? '', $company['company_country'] ?? '', ', '),
implode(' · ', array_filter([$company['company_email'] ?? '', $company['phone_display'] ?? '', $company['company_website'] ?? ''])),
]);
$logo = !empty($company['logo_path']) && @getimagesize($company['logo_path']) ? '<img src="' . $e($company['logo_path']) . '" height="38"><br>' : '';
$letterhead = function ($logo) use (&$pdf, $company, $from_lines, $kb, $e, $grey) {
$pdf->SetFont('dejavusans', '', 8.5);
$pdf->SetTextColor(33, 37, 41);
$pdf->writeHTML('<table cellpadding="0" cellspacing="0" width="100%"><tr>
<td width="62%">' . $logo . '<span style="font-size:11pt; font-weight:bold;">' . $e($company['company_name'] ?? '') . '</span><br><span style="font-size:7.5pt; color:' . $grey . ';">' . nl2br($e(implode("\n", $from_lines))) . '</span></td>
<td width="38%" align="right"><span style="font-size:8pt; color:#0a58ca; font-weight:bold; letter-spacing:2px;">' . ($kb ? 'KNOWLEDGE BASE' : 'DOCUMENT') . '</span><br>
<span style="font-size:7.5pt; color:' . $grey . ';">' . $e(date('M j, Y')) . '</span></td>
</tr></table>', true, false, true, false, '');
};
// A logo TCPDF cannot read leaves it without one
$pdf->startTransaction();
try {
$letterhead($logo);
$pdf->commitTransaction();
} catch (Throwable $error) {
$pdf = $pdf->rollbackTransaction();
$letterhead('');
}
$pdf->Ln(6);
// The title, where it is kept and when it was last updated
$parts = documentPdfParts(documentHtmlPurify((string) $item['html']));
$bookmarks = count($parts) > 1;
if ($bookmarks) {
$pdf->Bookmark($title, 0, -1, '', 'B', [33, 37, 41]);
}
// Lined up with the letterhead and the text, without a cell's padding
$padding = $pdf->getCellPaddings();
$pdf->setCellPaddings(0, 0, 0, 0);
$pdf->SetFont('dejavusans', 'B', 17);
$pdf->SetTextColor(33, 37, 41);
$pdf->MultiCell($width, 8, $title, 0, 'L', false, 1);
$pdf->SetDrawColor(13, 110, 253);
$pdf->SetLineWidth(0.6);
$pdf->Line($pdf->GetX(), $pdf->GetY() + 0.5, $pdf->GetX() + 18, $pdf->GetY() + 0.5);
$pdf->Ln(2.5);
$updated = $item['updated'] ? 'Updated ' . date('M j, Y', strtotime($item['updated'])) . ($item['by'] !== '' ? ' by ' . $item['by'] : '') : '';
$about = implode(' · ', array_filter([(string) $item['client'], (string) $item['place'], $updated]));
if ($about !== '') {
$pdf->SetFont('dejavusans', '', 8);
$pdf->SetTextColor(108, 117, 125);
$pdf->MultiCell($width, 4, $about, 0, 'L', false, 1);
}
if ($item['description'] !== '') {
$pdf->Ln(1);
$pdf->SetFont('dejavusans', 'I', 9);
$pdf->SetTextColor(73, 80, 87);
$pdf->MultiCell($width, 4.5, $item['description'], 0, 'L', false, 1);
}
$pdf->setCellPaddings($padding['L'], $padding['T'], $padding['R'], $padding['B']);
$pdf->Ln(3);
// What it says, a bookmark at each heading - as plain text when TCPDF can't draw it
$pdf->startTransaction();
try {
foreach ($parts as [$heading, $level, $html]) {
if ($heading !== '') {
// A heading near the foot of a page goes over to the next with what follows it,
// and otherwise - but at the top of a page - has room above it, as TCPDF gives
// none to the first thing it draws
if ($pdf->GetY() > $pdf->getPageHeight() - 50) {
$pdf->AddPage();
} elseif ($pdf->GetY() > $margins['top'] + 12) {
$pdf->Ln($level > 1 ? 2 : 3.5);
}
if ($bookmarks) {
$pdf->Bookmark($heading, $level, -1, '', '', [33, 37, 41]);
}
}
$write(clientExportPdfImages($html, $item['id'], $kb ? 'kb' : 'documents'));
}
$pdf->commitTransaction();
} catch (Throwable $error) {
$pdf = $pdf->rollbackTransaction();
$write('<p style="color:' . $grey . ';"><i>This ' . ($kb ? 'article' : 'document') . ' has formatting the PDF cannot show, so here is its text.</i></p>'
. nl2br($e(clientExportText((string) $item['html']))));
}
$name = trim(preg_replace('/[^A-Za-z0-9 ._-]/', '', $title));
return ['name' => ($name !== '' ? $name : ($kb ? 'Article' : 'Document')) . '.pdf', 'data' => $pdf->Output('', 'S')];
}