From 5a3f4ba6f5db0c5f9e0e7007733a51597db82f25 Mon Sep 17 00:00:00 2001 From: johnnyq Date: Sun, 18 Oct 2026 19:50:42 -0400 Subject: [PATCH] Document templates stage 4, export, import, starter pack and report: Admin > Document Templates gets a menu beside New with Import, Export, the report and the starter pack, and each template page gets an Export link; the file carries each template's summary, its text with images embedded, its fill-ins and review interval, leaving who should have one to each install; importing a template already there by name can leave it, add the file's copy alongside or replace it (keeping its documents and who should have one), new ones come in required of no one, content goes through the HTML purifier, and images that only point at the other install's uploads are left out with the message saying how many; the MSP starter pack is rebuilt as 14 templates (Asset Inventory and Vendors and Escalation new) that fill in from the client, pull in its sites, networks, equipment, servers, domains, licenses, vendors and contacts as tables, ask for the rest with typed fill-ins, set 6 or 12 month reviews on the ones that go stale, and are required of no one out of the box; Update on Starter Content now covers document templates, bringing older starter templates up to the new versions while keeping their documents and who should have one; new Document Templates report under Clients & Documentation by template (documents made in the period against the period before, current documents, clients with one, coverage of the clients it is required of, documents due a review) and by client (what each should have, has and is missing, and documents due), filtered by client or by the agent who made them, each table exportable as CSV, and client-restricted users seeing only their clients; no database change; changelog updated --- CHANGELOG.md | 8 +- admin/document_template.php | 1 + admin/document_templates.php | 26 +- .../document_template_export.php | 55 +++ .../document_template_import.php | 54 +++ admin/post/document_template.php | 66 +++- admin/post/starter_content.php | 20 + admin/post/starter_content_model.php | 352 +++++++++++++++--- admin/starter_content.php | 7 +- agent/reports/document_templates.php | 264 +++++++++++++ functions.php | 1 + functions/document_template_transfer.php | 222 +++++++++++ functions/reports.php | 4 + 13 files changed, 1009 insertions(+), 71 deletions(-) create mode 100644 admin/modals/document_template/document_template_export.php create mode 100644 admin/modals/document_template/document_template_import.php create mode 100644 agent/reports/document_templates.php create mode 100644 functions/document_template_transfer.php diff --git a/CHANGELOG.md b/CHANGELOG.md index c151d39e2..cd431e59f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -47,7 +47,7 @@ Ticket templates keep their subject, details and tasks, and set nothing else on Canned responses keep their names, what they say and their ticket category. One whose category had been deleted is offered on every ticket, as it already was. How often each is used is counted from the update. None sets up anything on the reply until you give it a reply type, status or time worked on its Sets up tab. Every canned response already there is shared - offered to everyone, as before - and none has files. -Document templates keep their names, summaries, what they say and their images. Words in square brackets already in them are now filled in when a document is made: [Client], [Site], [Contact], [Date] and the others listed under New Features (Document templates) from the client, and the rest are asked for as plain, optional text until you set them up on the template's page - one left blank stays as it is, as before. Documents made from a template before the update don't know which one, so a template's use is counted from the update - link one to its template from the document's page to count it. No template is required of anyone, and none asks for reviews, until you set it up on its page. +Document templates keep their names, summaries, what they say and their images. Words in square brackets already in them are now filled in when a document is made: [Client], [Site], [Contact], [Date] and the others listed under New Features (Document templates) from the client, and the rest are asked for as plain, optional text until you set them up on the template's page - one left blank stays as it is, as before. Documents made from a template before the update don't know which one, so a template's use is counted from the update - link one to its template from the document's page to count it. No template is required of anyone, and none asks for reviews, until you set it up on its page. The starter document templates you added from Maintenance > Starter Content stay as they are; Update on that page brings them up to the new versions, which fill in from the client, ask for what they need and are reviewed on a schedule. If you are coming from 26.08 or earlier, the database update still has to be run from the command line one time, exactly as described under Upgrading to 26.09 below. @@ -537,6 +537,9 @@ If you are coming from 26.08 or earlier, the database update still has to be run - A client's Files lists the documents it should have across the top, each a click from making it, and its overview counts them under Documents missing. Document from template lists them first. - Reviews: a template can say its documents are reviewed every 3 or 6 months, every year or every 2 years. A document is due once it hasn't been edited or marked as reviewed for that long. It says so on its page - Review due, or when the next review is and who last reviewed it - with Mark reviewed. Files marks the ones due and has a Review due tab listing them from every folder, the client's overview counts them, and the template's page and the list show how many are due. An archived template's documents aren't counted. - A document can be linked to the template it counts as made from, from its page - one written before the template, say - so it counts towards who has one and is reviewed as the template says. What it says stays as it is. + - Export and import: Admin > Document Templates exports every current template, the ones picked, or one from its page, as a file to import into another ITFlow or keep. Each goes with its summary, what it says and its images, its fill-ins and how often its documents are reviewed - not who should have one, which is each install's own call. Importing, one already here by name is left as it is, added as well under a name of its own, or replaced - keeping its documents and who should have one. A new one comes in required of no one. + - The starter document templates on Maintenance > Starter Content are rebuilt - fourteen of them, with Asset Inventory and Vendors and Escalation new - filled in from the client, with its sites, networks, equipment, servers, domains, licenses, vendors and contacts as tables, asking for the rest (a circuit type from a list, a start date, a required hostname), and the ones that go stale reviewed every 6 or 12 months. Who should have each is left to you. Update brings the ones added from an earlier version up to this one. + - A Document Templates report (Reports > Clients & Documentation): for each template, the documents made from it in the period against the period before, its current documents and the clients with one, how many of the clients it is required of have one, and its documents due a review; and by client, the templates each should have a document from, the ones missing and the documents due. For one client, or the documents one agent made, and exported by template or by client. - Templates can be copied (with their images), archived - not offered for new documents, while the documents made from them stay - restored and deleted. A document made from one remembers it, and its page says which template it came from. - The template window has its icons, a summary, and Draft it with AI when an AI model is set up for documentation. A draft uses the placeholders and tables of records, and puts what else is to be filled in in square brackets. - Document from template in a client's Files shows each template's summary and how often it has been used. A document made with no name or summary given takes the template's. @@ -1527,6 +1530,9 @@ If you are coming from 26.08 or earlier, the database update still has to be run - `functions/document_template.php`: `DOCUMENT_TEMPLATE_REQUIRED_NONE`, `_EVERY` and `_TAGGED`, `DOCUMENT_TEMPLATE_REVIEW_MONTHS`; `documentTemplateRequiredTags($ids)`, `documentTemplateSetRequired($id, $required, $tag_ids, $months)` (leaves `document_template_updated_at` alone), `documentTemplateScopeSql($required, $tag_ids)` (SQL on clients - current, not leads), `documentTemplateScopeText()`, `documentTemplateCoverage($id, $required, $tag_ids)` (`clients`, `covered`, `missing`), `documentTemplatesMissingFor($client_id)`, `documentReviewedAtSql()` (the latest of made, edited and reviewed), `documentReviewDueSql()` (on documents joined to document_templates), `documentsReviewDue($where)`, `documentTemplateDueCounts($ids)`, `documentReviewState($row)` (`last`, `reviewed`, `next`, `due`) and `documentTemplateMakeForClients($id, $client_ids, $answers, $skip_existing)`. `documentTemplateRow()` returns the two new columns; `documentTemplateCopy()` copies the review period and tags, not required; `documentTemplateDelete()` no longer touches its documents' `document_updated_at`. - Admin: new `admin/modals/document_template/document_template_required.php` (`id`) and `document_template_use_several.php` (`id`, `missing=1`); `document_template_use.php` takes `client_id`; `admin/document_templates.php` takes `show=required`. `admin/post/document_template.php`: `save_document_template_required` (`required`, `tags[]`, `review_months`) and `make_documents_from_template` (`client_ids[]`, `skip_existing`, `fill_ins`; a Document Create audit entry per document, under its client). - Agent: `agent/post/document.php` - GET `mark_document_reviewed` and POST `set_document_template` (`document_template_id`, 0 for none; an archived one only if it is already the one), both Support at edit level, neither touching `document_updated_at`; new `agent/modals/document/document_template_link.php` (`id`). `agent/files.php` takes `type=due`. `clientOverviewAttention()` adds Documents missing and Document reviews due. + - New `functions/document_template_transfer.php`: `DOCUMENT_TEMPLATE_FILE_FORMAT` (`itflow-document-templates`), `DOCUMENT_TEMPLATE_FILE_VERSION` (1) and `DOCUMENT_TEMPLATE_TRANSFER_IMAGE_MAX`; `documentTemplateInlineImages()` (a template's own images as data URIs), `documentTemplatesExport($ids, $archived)` (`name`, `description`, `content`, `fill_ins`, `review_months`), `documentTemplatesExportFileName()`, `documentTemplatesImportRead($contents, &$error)` (through `documentHtmlPurify()`; an image pointing at `/uploads/` dropped and counted), `documentTemplatesImport($templates, $existing, $only_existing)` (`skip`, `copy` or `replace`, through `documentTemplateSave()` so data images land in the template's folder; `added`, `replaced`, `skipped`, `images`, `ids`) and `documentTemplatesImportSummary()`. New `admin/modals/document_template/document_template_export.php` and `document_template_import.php`; `admin/post/document_template.php`: POST `export_document_templates` (`document_template_ids[]`, `archived`), GET `export_document_template`, POST `import_document_templates` (`file`, `existing`); Document Template Export and Import audit entries. + - Starter Content: `starterContentDocumentTemplates()` is in the file format and loads through `documentTemplatesImport()`; new `starterUpdateDocumentTemplates()` and the `update_starter_document_templates` handler, with the pack's `update` entry. + - Report: `agent/reports/document_templates.php` (`client_id`, `agent` - who made them - and the period; `export=csv` by template, `table=clients` by client), `document_templates` in `reportCatalog()` under Clients & Documentation. - Empty states: every list page sets `$empty_state` before including `includes/filter_footer.php`, and `includes/inc_empty_state.php` draws it with `emptyStateHtml()` (`functions/format.php`) when the list has nothing - `thing`, `icon`, `title`, `text`, `actions` (`label`, `modal` or `href`, `size`, `icon`; the first is the main one), `archived`, `view`, `filtered`, `views`, `match_title`, `match_text` and `clear_url`. `emptyStateFiltered($views)` reads the GET string for a search or filter, leaving out paging, sorting, `client_id`, `archived` and the page's views, and `emptyStateClearUrl($views)` is the page without them. `emptyStatePill($pills, $key, $default, $good)` builds a pill's own state from the page's pill array (`label`, `icon`, `title`, `alarm`), with a tick for `alarm` pills and the keys in `$good`. Files, notifications and racks call `emptyStateHtml()` in their own layout; files and notifications set `$empty_state_skip`. A page that sets nothing still gets one, worded from `$page_title`. The pages' own empty blocks (`.itflow-asset-empty` under a list) are gone. CSS: `.itflow-empty-state` with `-icon` (a grey round tile), `-title`, `-text` and `-actions`. - Removed unused helpers and files: - `credentialLink()`, `projectLink()`, `linkCounts()`, `assetContactAvatar()`, `clientOverviewPersonInitials()`, and `getMonthlyTax()` and `getQuarterlyTax()`, which looked a tax up by name diff --git a/admin/document_template.php b/admin/document_template.php index 75246bfd3..19130e071 100644 --- a/admin/document_template.php +++ b/admin/document_template.php @@ -98,6 +98,7 @@ $required_url = "modals/document_template/document_template_required.php?id=$doc + + + diff --git a/functions.php b/functions.php index 2b9cecea7..5259cbfcd 100644 --- a/functions.php +++ b/functions.php @@ -56,6 +56,7 @@ require_once __DIR__ . '/functions/ticket_template_transfer.php'; require_once __DIR__ . '/functions/canned_response.php'; require_once __DIR__ . '/functions/canned_response_transfer.php'; require_once __DIR__ . '/functions/document_template.php'; +require_once __DIR__ . '/functions/document_template_transfer.php'; require_once __DIR__ . '/functions/project.php'; require_once __DIR__ . '/functions/service.php'; require_once __DIR__ . '/functions/client_export.php'; diff --git a/functions/document_template_transfer.php b/functions/document_template_transfer.php new file mode 100644 index 000000000..28cb7264c --- /dev/null +++ b/functions/document_template_transfer.php @@ -0,0 +1,222 @@ + Document Templates exports them + * (export_document_templates) and imports them (import_document_templates); + * the MSP starter pack on Maintenance > Starter Content is loaded the same way. + * + * The file is JSON: {"format": "itflow-document-templates", "version": 1, + * "exported_at", "templates": [...]}. Each template carries its name, summary, + * what it says - its images in it, as data - the fill-ins set up on it, and + * how often the documents made from it are reviewed. Not who should have one: + * that is the call of the install it goes into - a new one comes in required + * of no one, and one replaced keeps its own. + */ + +const DOCUMENT_TEMPLATE_FILE_FORMAT = 'itflow-document-templates'; +const DOCUMENT_TEMPLATE_FILE_VERSION = 1; + +/** The largest image that goes into an export, in bytes - bigger ones stay behind. */ +const DOCUMENT_TEMPLATE_TRANSFER_IMAGE_MAX = 5 * 1024 * 1024; + +/* A template's HTML with its own images in it as data - for a file. How many were too big or gone, in $left_out. */ +function documentTemplateInlineImages($document_template_id, $html, &$left_out = 0) { + $document_template_id = intval($document_template_id); + $dir = documentTemplateDir($document_template_id); + return preg_replace_callback('/(]*?\bsrc=)(["\'])\/?uploads\/document_templates\/' . $document_template_id . '\/([^"\'\/]+)\2/i', function ($match) use ($dir, &$left_out) { + $path = $dir . '/' . basename($match[3]); + $info = is_file($path) && filesize($path) <= DOCUMENT_TEMPLATE_TRANSFER_IMAGE_MAX ? @getimagesize($path) : false; + if (!$info || !in_array($info['mime'], ['image/png', 'image/jpeg', 'image/gif', 'image/webp'], true)) { + $left_out++; + return $match[0]; + } + return $match[1] . $match[2] . 'data:' . $info['mime'] . ';base64,' . base64_encode((string) file_get_contents($path)) . $match[2]; + }, (string) $html); +} + +/* + * Templates as a file's contents (an array, for json_encode()) - the ones in + * $ids, or every current one when $ids is empty, and the archived ones too + * with $archived. + */ +function documentTemplatesExport(array $ids = [], $archived = false) { + global $mysqli; + $ids = array_values(array_filter(array_map('intval', $ids))); + $where = $ids ? 'document_template_id IN (' . implode(',', $ids) . ')' : ($archived ? '1 = 1' : 'document_template_archived_at IS NULL'); + $rows = []; + $sql = mysqli_query($mysqli, "SELECT document_template_id, document_template_name, document_template_description, document_template_content, document_template_review_months + FROM document_templates WHERE $where ORDER BY document_template_name ASC, document_template_id ASC"); + while ($row = mysqli_fetch_assoc($sql)) { + $rows[intval($row['document_template_id'])] = $row; + } + $fill_ins = documentTemplateFillInRowsFor(array_keys($rows)); + + $templates = []; + foreach ($rows as $id => $row) { + $templates[] = [ + 'name' => (string) $row['document_template_name'], + 'description' => (string) $row['document_template_description'], + 'content' => documentTemplateInlineImages($id, $row['document_template_content']), + 'fill_ins' => array_map(function ($fill_in) { + return ['name' => $fill_in['name'], 'type' => $fill_in['type'], 'options' => $fill_in['options'], 'required' => $fill_in['required'], 'help' => $fill_in['help']]; + }, $fill_ins[$id] ?? []), + 'review_months' => intval($row['document_template_review_months']), + ]; + } + return ['format' => DOCUMENT_TEMPLATE_FILE_FORMAT, 'version' => DOCUMENT_TEMPLATE_FILE_VERSION, 'exported_at' => date('c'), 'templates' => $templates]; +} + +/** A file name for an export - its one template's name, or the date. */ +function documentTemplatesExportFileName(array $export) { + $templates = $export['templates'] ?? []; + if (count($templates) === 1) { + $slug = trim(preg_replace('/[^a-z0-9]+/', '-', strtolower($templates[0]['name'])), '-'); + return 'document-template-' . ($slug !== '' ? substr($slug, 0, 60) : 'export') . '.json'; + } + return 'document-templates-' . date('Y-m-d') . '.json'; +} + +/* One line of text from a file, tidied - no markup, no runs of spaces, no longer than $max. */ +function documentTemplateFileText($value, $max) { + return is_scalar($value) ? trim(mb_substr(preg_replace('/\s+/u', ' ', strip_tags((string) $value)), 0, $max)) : ''; +} + +/* + * A file's templates, read and checked - from what export wrote, or the + * starter pack. Each made safe: text tidied, what it says through the HTML + * purifier (images in it as data kept when they are images; ones pointing at + * another install's uploads taken out, counted in 'images_dropped'), fill-ins + * with a name that can be one, a type that is one and a list with two + * choices (else plain text), each once, and a review period that is one. + * Null with $error saying why the file can't be used. + */ +function documentTemplatesImportRead($contents, &$error = '') { + $data = is_array($contents) ? $contents : json_decode((string) $contents, true); + if (!is_array($data) || ($data['format'] ?? '') !== DOCUMENT_TEMPLATE_FILE_FORMAT || !isset($data['templates']) || !is_array($data['templates'])) { + $error = "That isn't a document templates file - export one from Admin > Document Templates."; + return null; + } + if (intval($data['version'] ?? 0) > DOCUMENT_TEMPLATE_FILE_VERSION) { + $error = 'That file was made by a newer version of ITFlow - update this one first.'; + return null; + } + if (count($data['templates']) > 500) { + $error = 'That file holds more than 500 document templates - split it up.'; + return null; + } + + $templates = []; + foreach ($data['templates'] as $t) { + $name = is_array($t) ? documentTemplateFileText($t['name'] ?? '', 200) : ''; + if ($name === '') { + continue; + } + // An image carried as data with no alt would get one made of its data + $content = is_scalar($t['content'] ?? null) ? preg_replace('/]*\balt=)(?=[^>]*\bsrc=["\']data:)/i', ']*?\bsrc=(["\'])\/?uploads\/[^"\']*\1[^>]*>/i', '', $content, -1, $dropped); + + $fill_ins = []; + foreach (array_slice(is_array($t['fill_ins'] ?? null) ? $t['fill_ins'] : [], 0, 100) as $f) { + $fill_in_name = is_array($f) ? documentFillInName(documentTemplateFileText($f['name'] ?? '', 50)) : ''; + if ($fill_in_name === '' || isset($fill_ins[strtolower($fill_in_name)])) { + continue; + } + $type = is_string($f['type'] ?? null) && isset(TICKET_FILL_IN_TYPES[$f['type']]) ? $f['type'] : 'text'; + $options = $type === 'list' ? ticketFillInOptions(is_array($f['options'] ?? null) ? implode("\n", array_filter($f['options'], 'is_scalar')) : (string) ($f['options'] ?? '')) : []; + if ($type === 'list' && count($options) < 2) { + $type = 'text'; + $options = []; + } + $fill_ins[strtolower($fill_in_name)] = ['name' => $fill_in_name, 'type' => $type, 'options' => $options, 'required' => !empty($f['required']), + 'help' => documentTemplateFileText($f['help'] ?? '', 255)]; + } + + $review_months = intval($t['review_months'] ?? 0); + $templates[] = [ + 'name' => $name, + 'description' => documentTemplateFileText($t['description'] ?? '', 500), + 'content' => $content, + 'fill_ins' => array_values($fill_ins), + 'review_months' => isset(DOCUMENT_TEMPLATE_REVIEW_MONTHS[$review_months]) ? $review_months : 0, + 'images_dropped' => $dropped, + ]; + } + if (!$templates) { + $error = 'There are no document templates in that file.'; + return null; + } + return $templates; +} + +/* + * Bring in templates read by documentTemplatesImportRead(). One whose name is + * already here is skipped ($existing 'skip'), added under a name of its own + * ('copy') or has everything in the file put in its place ('replace') - its + * name, summary, what it says and its images, its fill-ins and how often its + * documents are reviewed. Its documents stay made from it, and who should + * have one stays as it was; a new one is required of no one. $only_existing: + * bring in only the ones already here (to update them). ['added', 'replaced', + * 'skipped', 'images' left out, 'ids' of those added or replaced]. + */ +function documentTemplatesImport(array $templates, $existing = 'skip', $only_existing = false) { + global $mysqli; + $counts = ['added' => 0, 'replaced' => 0, 'skipped' => 0, 'images' => 0, 'ids' => []]; + $here = []; + $sql = mysqli_query($mysqli, "SELECT document_template_id, document_template_name FROM document_templates ORDER BY document_template_id"); + while ($row = mysqli_fetch_assoc($sql)) { + $here[mb_strtolower($row['document_template_name'])] = $here[mb_strtolower($row['document_template_name'])] ?? intval($row['document_template_id']); + } + + foreach ($templates as $t) { + $id = $here[mb_strtolower($t['name'])] ?? 0; + if (($only_existing && !$id) || ($id && $existing === 'skip')) { + $counts['skipped']++; + continue; + } + $name = $t['name']; + if ($id && $existing === 'copy') { + for ($n = 2; isset($here[mb_strtolower($name)]); $n++) { + $name = mb_substr($t['name'], 0, 190) . " ($n)"; + } + $id = 0; + } + $replacing = $id > 0; + + // What it says, its images kept in its own folder + $saved = documentTemplateSave($id, ['name' => $name, 'description' => $t['description'], 'content' => $t['content']]); + $here[mb_strtolower($name)] = $saved; + + // Its fill-ins are the file's + mysqli_query($mysqli, "DELETE FROM document_template_fill_ins WHERE document_fill_in_document_template_id = $saved"); + foreach (array_values($t['fill_ins']) as $order => $f) { + mysqli_query($mysqli, "INSERT INTO document_template_fill_ins SET document_fill_in_document_template_id = $saved, document_fill_in_name = '" . escapeSql($f['name']) . "', + document_fill_in_type = '" . escapeSql($f['type']) . "', document_fill_in_options = " . ($f['options'] ? "'" . escapeSql(implode("\n", $f['options'])) . "'" : 'NULL') . ", + document_fill_in_required = " . ($f['required'] ? 1 : 0) . ", document_fill_in_help = " . ($f['help'] !== '' ? "'" . escapeSql($f['help']) . "'" : 'NULL') . ", + document_fill_in_order = " . ($order + 1)); + } + mysqli_query($mysqli, "UPDATE document_templates SET document_template_review_months = " . intval($t['review_months']) . ", document_template_updated_at = document_template_updated_at + WHERE document_template_id = $saved"); + + $counts['images'] += intval($t['images_dropped']); + $counts[$replacing ? 'replaced' : 'added']++; + $counts['ids'][] = $saved; + } + return $counts; +} + +/* What an import did, in words - for its message. HTML. */ +function documentTemplatesImportSummary(array $counts) { + $parts = []; + foreach (['added' => 'added', 'replaced' => 'replaced', 'skipped' => 'already here, left as they were'] as $key => $word) { + if ($counts[$key]) { + $parts[] = '' . $counts[$key] . ' ' . $word; + } + } + return ucfirst(implode(', ', $parts) ?: 'nothing brought in') + . ($counts['images'] ? '. Left out ' . $counts['images'] . ' image' . ($counts['images'] === 1 ? '' : 's') . " the file only pointed at, without carrying - too big, or gone where it came from" : '') + . '.'; +} diff --git a/functions/reports.php b/functions/reports.php index 546f4b53f..1f85b271a 100644 --- a/functions/reports.php +++ b/functions/reports.php @@ -176,6 +176,10 @@ function reportCatalog() { 'title' => 'Documentation Coverage', 'icon' => 'fa-tasks', 'module' => 'module_support', 'feature' => ['itdoc'], 'description' => 'What is documented for each client, and what is missing.', ], + 'document_templates' => [ + 'title' => 'Document Templates', 'icon' => 'fa-file-alt', 'module' => 'module_support', 'feature' => ['itdoc'], + 'description' => 'How often each document template is used, how many of the clients that should have a document from one do, and the documents due a review - by template and by client.', + ], 'credential_rotation' => [ 'title' => 'Credential Rotation', 'icon' => 'fa-key', 'module' => 'module_credential', 'feature' => ['itdoc'], 'description' => 'Passwords that have not changed in a while, oldest first.',