From 9fdc2f703236cb6c7206e38c45a7f63c72fe67d6 Mon Sep 17 00:00:00 2001 From: johnnyq Date: Sun, 18 Oct 2026 15:37:03 -0400 Subject: [PATCH] Document templates stage 1: Admin > Document Templates on the standard list with full search across name, summary and what it says, Active and Archived tabs with counts, sortable Used (documents made from it and for how many clients), Last used and Changed (when and by whom), paging, and a row menu with Edit, New document for a client, Copy, Archive/Restore and Delete; the template page rebuilt on the ticket template page's layout showing what it says made safe with its bracketed words marked and listed as left to fill in, its use and latest documents with their client, who made and last changed it and its images, with New document for a client opening a window that makes one for the client picked and opens it; one shared New/Edit window with icons in front of each field, a summary, and Draft it with AI only when an AI model is set up for documentation; Copy takes copies of its images, Delete takes its image folder and unlinks its documents, and archived templates aren't offered for new documents; migration 3.2.5 adds documents.document_template_id so documents remember their template and its use is counted from the update, and the document page says which template it came from; new functions/document_template.php shared by the admin pages and add_document_from_template, which now takes the template's name and summary when none are given and checks the client exists; the Document from template window shows each template's summary and how often it has been used and can open with one picked, and its Add one in Admin link checks for an admin rather than role id 3; changelog updated --- CHANGELOG.md | 17 +- admin/database_updates/3.2.5.php | 13 + admin/document_template.php | 186 ++++++++++---- admin/document_templates.php | 240 +++++++++++------- .../document_template_add.php | 86 +------ .../document_template_edit.php | 44 ++-- .../document_template_form.php | 97 +++++++ .../document_template_use.php | 72 ++++++ admin/post/document_template.php | 112 ++++---- agent/document.php | 6 +- .../document/document_add_from_template.php | 18 +- agent/post/document.php | 52 ++-- db.sql | 2 + functions.php | 1 + functions/document_template.php | 201 +++++++++++++++ 15 files changed, 800 insertions(+), 347 deletions(-) create mode 100644 admin/database_updates/3.2.5.php create mode 100644 admin/modals/document_template/document_template_form.php create mode 100644 admin/modals/document_template/document_template_use.php create mode 100644 functions/document_template.php diff --git a/CHANGELOG.md b/CHANGELOG.md index 2b98d78af..f0e80b8c8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,9 +6,9 @@ This file documents all notable changes made to ITFlow. ### Upgrading to 26.11 -Update from Maintenance > Update — Queue Update hands the job to cron, which updates the files and applies this release's database changes (2.7.9 to 3.2.4) in the same pass. Nothing else is required. +Update from Maintenance > Update — Queue Update hands the job to cron, which updates the files and applies this release's database changes (2.7.9 to 3.2.5) in the same pass. Nothing else is required. -This is a big release, with forty-five database steps in one go, so take a backup before you update. +This is a big release, with forty-six database steps in one go, so take a backup before you update. The update also clears out data that deletes in older versions left behind, all of it pointing at something that no longer exists: @@ -47,6 +47,8 @@ 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. Documents made from a template before the update don't know which one, so a template's use is counted from the update. + 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. ### Breaking Changes and Notes @@ -523,6 +525,12 @@ If you are coming from 26.08 or earlier, the database update still has to be run - Export and import: Admin > Canned Responses exports every current shared one, the ones picked (archived ones too, if you like), or one from its menu, as a file to import into another ITFlow or keep. Each goes with what it says, the ticket categories it is offered on and what it sets up, and its files unless you leave them out. Importing brings them in shared, matches the categories by name and makes the ones missing, matches the status after the reply by name, and for one already here by name leaves yours, adds the file's as well under a name of its own, or replaces yours with it - keeping how often yours has been used. What comes in is made safe, and a file of a kind a ticket doesn't take is left out and said. - Starter Content has a Canned Responses pack for an MSP: received, waiting on you, following up, resolved, closing with no reply, a remote session, an onsite visit, escalated to the vendor, an internal handover, billable work, password reset, multi-factor sign-in set up again, account unlocked, licence assigned, phishing reported (phishing or safe), a possible security incident, a new starter ready, a leaver done, warranty repair, printer fixed, file restored, a monitoring alert cleared, internet down with the provider, voicemail PIN reset, a quote sent and an invoice question. Each is filled in from the ticket, sets the reply up (who sees it, the status after it, time worked), and the ones for one kind of ticket are offered on its category. Update brings the ones you added before up to the current version. - The New Canned Response button's menu has Import, Export, the report and the starter ones. +- **Document templates** (rebuilt) + - Admin > Document Templates lists what each is for, how many documents have been made from it and for how many clients, when it was last used and when it last changed, and by whom - searched by name, summary or what it says, sorted from the column headings, a page at a time, with Active and Archived tabs. + - A template's page shows what it says, with the words in square brackets left to fill in marked and listed, who made it and last changed it, its images, and the latest documents made from it with their client. New document for a client, from there or the list, makes one for the client you pick and opens it. + - 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. + - 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. - **Assets** - The asset list has: - type icons, colored status pills and OS icons @@ -1496,6 +1504,11 @@ If you are coming from 26.08 or earlier, the database update still has to be run - Export and import: new `functions/canned_response_transfer.php` - `cannedResponsesExport($ids, $archived, $with_files)` (the file's contents: `format` itflow-canned-responses, `version` 1, `responses`, each with `name`, `body`, `categories` by name, `reply_type` - `internal`, `public`, `email` or null - `status` by name, `minutes` and, when exported with them, `files` as `name` and base64 `data`, each up to `CANNED_RESPONSE_TRANSFER_FILE_MAX`), `cannedResponsesExportFileName()`, `cannedResponsesImportRead($contents, &$error)` (checks and tidies a file - the body through `documentHtmlPurify()`, statuses matched to `cannedResponseStatuses()`, files to `TICKET_ATTACHMENT_EXTENSIONS` - and takes the starter pack's array the same way), `cannedResponsesImport($responses, $existing, $only_existing)` (`skip`, `copy` or `replace`, against shared ones only; a response without `files` keeps its own), `cannedResponseImportCategory()`, `cannedResponseAddFileData($id, $name, $bytes)` and `cannedResponsesImportSummary()`. Handlers in `admin/post/canned_response.php`: POST `export_canned_responses` (`canned_response_ids[]`, `archived`, `files`), GET `export_canned_response` and POST `import_canned_responses` (`file`, `existing`), with `admin/modals/canned_response/canned_response_export.php` and `canned_response_import.php`. Audit entries are Canned Response Export and Import. - Starter Content: a pack can say how its ones already here are updated (`update` - `button`, `confirm` - in `starterContentPacks()`), which draws the Update button. New `canned_responses` pack: `starterContentCannedResponses()` in the file format, `starterLoadCannedResponses()` through `cannedResponsesImport()`, and `starterUpdateCannedResponses()` with the `update_starter_canned_responses` handler. - Report: `agent/reports/canned_responses.php` (`client_id`, `agent` - who used it - and the period; `export=csv` by response, `table=agents` by agent), `canned_responses` in `reportCatalog()` under Service Desk. +- Document templates: + - Database 3.2.5: `documents.document_template_id` (indexed; 0 for none) - the template a document was made from. + - New `functions/document_template.php`: `documentTemplateDir()`, `documentTemplateRow($id)` (with `created_by_name` and `updated_by_name`), `documentTemplateUsage($ids)` (`count`, `clients`, `last` - documents not archived), `documentTemplateFields($post, &$error)` (`name`, `description`, `content`), `documentTemplateSave($id, $fields)` (images through `saveBase64Images()`, the unused ones through `cleanupUnusedImages()`; a new one's first save leaves `document_template_updated_at` empty), `documentTemplateCopyImages()`, `documentTemplateCopy($id)`, `documentTemplateDelete($id)` (clears the template from its documents and takes its folder away), `documentTemplateMakeDocument($id, $client_id, $name, $description, $folder_id)` (the template's name and summary when none given), `documentTemplatePreview()`, `documentTemplateBracketsIn()` and `documentTemplateMarkBrackets()`. + - Admin: `admin/document_templates.php` takes `q`, `sort` - `document_template_name`, `used_count`, `last_used` or `changed_at` - `order`, `page` and `show=archived`. `admin/document_template.php` is rebuilt on the ticket template page's layout. `admin/modals/document_template/document_template_form.php` is shared by `document_template_add.php` and `document_template_edit.php` (`id`); new `document_template_use.php` (`id`) posts `add_document_from_template` to `agent/post.php`. `admin/post/document_template.php`: `add_document_template` (redirects to its page), `edit_document_template`, GET `copy_document_template`, `archive_document_template`, `restore_document_template` and `delete_document_template` (`from_page`). Audit entries are Document Template Create, Edit, Archive, Restore and Delete. + - `add_document_from_template` makes the document with `documentTemplateMakeDocument()`, checks the client exists and redirects to `/agent/document.php`. `agent/modals/document/document_add_from_template.php` takes `document_template_id` to pick one, and shows each one's use. - 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/database_updates/3.2.5.php b/admin/database_updates/3.2.5.php new file mode 100644 index 000000000..1a0105596 --- /dev/null +++ b/admin/database_updates/3.2.5.php @@ -0,0 +1,13 @@ +set('Cache.DefinitionImpl', null); // Disable cache by setting a non-existent directory or an invalid one -$purifier_config->set('URI.AllowedSchemes', ['data' => true, 'src' => true, 'http' => true, 'https' => true]); -$purifier = new HTMLPurifier($purifier_config); - -if (isset($_GET['document_template_id'])) { - $document_template_id = intval($_GET['document_template_id']); -} - -$sql_document = mysqli_query($mysqli, "SELECT document_template_content, document_template_created_at, document_template_description, - document_template_name, document_template_updated_at FROM document_templates WHERE document_template_id = $document_template_id LIMIT 1"); - -if (mysqli_num_rows($sql_document) == 0) { - echo "

Nothing to see here

Go Back
"; +$template = documentTemplateRow($_GET['document_template_id'] ?? 0); +if (!$template) { + echo emptyStateHtml(['thing' => 'document templates', 'title' => 'That document template is gone', 'text' => 'It may have been deleted.', 'icon' => 'fa-file-alt', 'filtered' => false, + 'actions' => [['label' => 'Document Templates', 'href' => 'document_templates.php']]]); require_once "../includes/footer.php"; exit(); } -$row = mysqli_fetch_assoc($sql_document); +$document_template_id = intval($template['document_template_id']); +$name = escapeHtml($template['document_template_name']); +$archived = !empty($template['document_template_archived_at']); +$usage = documentTemplateUsage([$document_template_id])[$document_template_id] ?? ['count' => 0, 'clients' => 0, 'last' => null]; +$content = trim((string) $template['document_template_content']) !== '' ? documentTemplateMarkBrackets(documentHtmlPurify($template['document_template_content'])) : ''; +$brackets = documentTemplateBracketsIn($template['document_template_content']); +$images = is_dir(documentTemplateDir($document_template_id)) ? count(glob(documentTemplateDir($document_template_id) . '/*')) : 0; +$csrf = $_SESSION['csrf_token']; -$document_template_name = escapeHtml($row['document_template_name']); -$document_template_description = escapeHtml($row['document_template_description']); -$document_template_content = $purifier->purify($row['document_template_content']); -$document_template_created_at = escapeHtml($row['document_template_created_at']); -$document_template_updated_at = escapeHtml($row['document_template_updated_at']); +// The documents made from it most lately +$recent = []; +$sql = mysqli_query($mysqli, "SELECT document_id, document_name, document_client_id, document_created_at, client_name, user_name FROM documents + LEFT JOIN clients ON client_id = document_client_id + LEFT JOIN users ON user_id = document_created_by AND document_created_by > 0 + WHERE document_template_id = $document_template_id AND document_archived_at IS NULL + ORDER BY document_created_at DESC, document_id DESC LIMIT 10"); +while ($row = mysqli_fetch_assoc($sql)) { + $recent[] = $row; +} + +$edit_url = "modals/document_template/document_template_edit.php?id=$document_template_id"; +$use_url = "modals/document_template/document_template_use.php?id=$document_template_id"; ?> -
-
- -

- -
- +
+
+ +
+

+ +
+ + +
Archived - not offered for new documents
+ +
+
+ + + + +
-
- +
+ +
+
+
+
+

What it says

+ +
+
+ Nothing yet - edit it to write what each document starts with.' ?> +
+
+
+ +
+ +
+

Used

+
+ +
document made from it 1 ? ', for ' . $usage['clients'] . ' clients' : '' ?> - last
+ + +
No documents made from it yet - counting started with this version of ITFlow. Agents start one from Document from template in a client's Files.
+ +
+
+ + +
+

Left to fill in

+
+
+ + [] + +
+
Words in square brackets stay in each document made from it, for whoever writes it to fill in.
+
+
+ + +
+

Details

+
+
+
Made
+
' . escapeHtml($template['created_by_name']) . '
' : '' ?> + +
Last changed
+
' . escapeHtml($template['updated_by_name']) . '
' : '' ?> + +
Images
+
+ +
+
+
diff --git a/admin/document_templates.php b/admin/document_templates.php index 303231675..e78846ee4 100644 --- a/admin/document_templates.php +++ b/admin/document_templates.php @@ -1,143 +1,187 @@ Document Templates - documents ready to start a client's from: a + * runbook, a build sheet, a plan. Each row shows what it is for, how many + * documents have been made from it and for how many clients, when it was + * last used and last changed. A template can be changed, copied as the start + * of another, archived - not offered for new documents, while the documents + * made from it stay - or deleted. The work is in functions/document_template.php; + * the handlers are admin/post/document_template.php. + */ - require_once "includes/inc_all_admin.php"; +// Default Column Sortby Filter +$sort = "document_template_name"; +$order = "ASC"; - $sql = mysqli_query( - $mysqli, - "SELECT SQL_CALC_FOUND_ROWS document_template_content, document_template_created_at, document_template_description, - document_template_id, document_template_name, document_template_updated_at, user_name FROM document_templates - LEFT JOIN users ON document_template_created_by = user_id - WHERE user_name LIKE '%$q%' OR document_template_name LIKE '%$q%' - ORDER BY $sort $order LIMIT $record_from, $record_to" - ); +require_once "includes/inc_all_admin.php"; - $num_rows = mysqli_fetch_row(mysqli_query($mysqli, "SELECT FOUND_ROWS()")); +$show_archived = ($_GET['show'] ?? '') === 'archived'; + +// Only these sort - an unknown column would take the page down +$sortable_columns = [ + 'document_template_name' => "document_template_name $order", + 'used_count' => "used_count $order, document_template_name ASC", + 'last_used' => "last_used IS NULL, last_used $order, document_template_name ASC", + 'changed_at' => "changed_at $order, document_template_name ASC", +]; +if (!isset($sortable_columns[$sort])) { + $sort = 'document_template_name'; +} + +$search = "(document_template_name LIKE '%$q%' OR document_template_description LIKE '%$q%' OR document_template_content LIKE '%$q%')"; + +// Its use is the documents made from it that are not archived - as documentTemplateUsage() counts them +$sql = mysqli_query($mysqli, "SELECT SQL_CALC_FOUND_ROWS document_templates.document_template_id, document_template_name, document_template_description, document_template_content, + document_template_created_at, document_template_updated_at, document_template_archived_at, COALESCE(document_template_updated_at, document_template_created_at) AS changed_at, + COALESCE(updater.user_name, creator.user_name) AS changed_by, + COALESCE(used.used_count, 0) AS used_count, COALESCE(used.client_count, 0) AS client_count, used.last_used + FROM document_templates + LEFT JOIN users creator ON creator.user_id = document_template_created_by AND document_template_created_by > 0 + LEFT JOIN users updater ON updater.user_id = document_template_updated_by AND document_template_updated_by > 0 + LEFT JOIN ( + SELECT document_template_id AS used_template_id, COUNT(*) AS used_count, COUNT(DISTINCT document_client_id) AS client_count, MAX(document_created_at) AS last_used + FROM documents WHERE document_template_id > 0 AND document_archived_at IS NULL GROUP BY document_template_id + ) used ON used.used_template_id = document_templates.document_template_id + WHERE $search AND document_template_archived_at IS " . ($show_archived ? 'NOT NULL' : 'NULL') . " + ORDER BY {$sortable_columns[$sort]}, document_templates.document_template_id ASC + LIMIT $record_from, $record_to"); + +$num_rows = mysqli_fetch_row(mysqli_query($mysqli, "SELECT FOUND_ROWS()")); + +$counts = mysqli_fetch_row(mysqli_query($mysqli, "SELECT COALESCE(SUM(document_template_archived_at IS NULL), 0), COALESCE(SUM(document_template_archived_at IS NOT NULL), 0) FROM document_templates WHERE $search")); + +$sort_link = function ($column, $label) use ($url_query_strings_sort, $sort, $disp, $order_icon) { + return '' + . $label . ($sort === $column ? " $order_icon" : '') . ''; +}; +$pill_url = function ($archived) { + return '?' . http_build_query(array_filter(['q' => $_GET['q'] ?? '', 'show' => $archived ? 'archived' : ''])); +}; + +$add_url = 'modals/document_template/document_template_add.php'; +$csrf = $_SESSION['csrf_token']; ?>
-

Document Templates

+

Document Templates

- +
-
-
- - + +
+
+
+ + +
+
+
- -
- - "> - - - - - - +
+
- - Template Name - - - - Created - - - - Updated - - - Action -
+ "> + + + + + + + - 1 ? ' · ' . $client_count . ' clients' : ''); + $edit_url = "modals/document_template/document_template_edit.php?id=$template_id"; ?> - - + - + + - - - - - +
- -
- -
-
-
-
+
+ +
+ + +
+ + +
Archived
+ + +
- +
- -
+
Not yet' ?>> + +
- +
-
'document templates', 'icon' => 'fa-file-alt', - 'text' => 'Start a client document from one.', - 'actions' => [['label' => 'New Template', 'modal' => 'modals/document_template/document_template_add.php', 'size' => 'xl']], + 'filtered' => $q !== '', + 'archived' => $show_archived, + 'views' => ['show'], + 'text' => 'A document ready to start a client\'s from - a runbook, a build sheet, a plan. Agents start one from Document from template in a client\'s Files. Maintenance > Starter Content has a set for an MSP.', + 'actions' => [['label' => 'New Document Template', 'modal' => $add_url, 'size' => 'xl']], ]; + require_once "../includes/filter_footer.php"; ?> -
- -
-
- - + +if (!$template) { ?> + + +
- +
- + +
+
+ +
+ + +
+
+
+ +
+ + +
+
+
+ + +
+ +
+ + + +
+ Replaces what is in the editor below. +
+ + +
+ + +
+
Words in square brackets - [Client], [Date] - are left in the document for whoever writes it to fill in. Pasted images are kept with the template and copied into each document made from it.
+ + + + diff --git a/admin/modals/document_template/document_template_use.php b/admin/modals/document_template/document_template_use.php new file mode 100644 index 000000000..3aceb1ebc --- /dev/null +++ b/admin/modals/document_template/document_template_use.php @@ -0,0 +1,72 @@ + Document + * Templates and the template's page. It goes in the client's Files, at the + * top level, and opens (add_document_from_template, agent/post/document.php). + */ + +require_once '../../includes/modal_header.php'; + +$template = documentTemplateRow($_GET['id'] ?? 0); + +ob_start(); + +if (!$template || $template['document_template_archived_at']) { ?> + + + + + +
+ + + + + +
+ + Document Templates) - making, changing, + * copying, archiving and deleting them, with their images. The work is in + * functions/document_template.php; a document is made from one by + * add_document_from_template (agent/post/document.php). + */ defined('FROM_POST_HANDLER') || die("Direct file access is not allowed"); -if (isset($_POST['add_document_template'])) { +/* The template a request is for - or back to the list, saying it is gone. */ +function documentTemplateForRequest($document_template_id) { + $row = documentTemplateRow($document_template_id); + if (!$row) { + flashAlert('That document template no longer exists.', 'error'); + redirect('document_templates.php'); + } + return $row; +} + +if (isset($_POST['add_document_template']) || isset($_POST['edit_document_template'])) { validateCSRFToken(); - $name = escapeSql($_POST['name']); - $description = escapeSql($_POST['description']); + $editing = isset($_POST['edit_document_template']); + $document_template_id = $editing ? intval(documentTemplateForRequest($_POST['document_template_id'] ?? 0)['document_template_id']) : 0; - mysqli_query($mysqli,"INSERT INTO document_templates SET document_template_name = '$name', document_template_description = '$description', document_template_content = '', document_template_created_by = $session_user_id"); + $fields = documentTemplateFields($_POST, $error); + if (!$fields) { + flashAlert(escapeHtml($error), 'error'); + redirect(); + } + $document_template_id = documentTemplateSave($document_template_id, $fields); + $name = escapeSql($fields['name']); - $document_template_id = mysqli_insert_id($mysqli); + logAudit("Document Template", $editing ? "Edit" : "Create", "$session_name " . ($editing ? 'edited' : 'created') . " document template $name", 0, $document_template_id); - $processed_content = mysqli_escape_string( - $mysqli, - saveBase64Images( - $_POST['content'], - $_SERVER['DOCUMENT_ROOT'] . "/uploads/document_templates/", - "uploads/document_templates/", - $document_template_id - ) - ); + flashAlert("Document template " . escapeHtml($fields['name']) . " " . ($editing ? 'saved' : 'created')); - // Document template update content - mysqli_query($mysqli,"UPDATE document_templates SET document_template_content = '$processed_content' WHERE document_template_id = $document_template_id"); - - logAudit("Document Template", "Create", "$session_name created document template $name", 0, $document_template_id); - - flashAlert("Document template $name created"); - - redirect(); + // A new one opens on its page + redirect($editing ? null : "document_template.php?document_template_id=$document_template_id"); } -if (isset($_POST['edit_document_template'])) { +if (isset($_GET['copy_document_template'])) { validateCSRFToken(); - $document_template_id = intval($_POST['document_template_id']); - $name = escapeSql($_POST['name']); - $description = escapeSql($_POST['description']); + $row = documentTemplateForRequest($_GET['copy_document_template']); + $new_id = documentTemplateCopy($row['document_template_id']); + $new_name = (string) documentTemplateRow($new_id)['document_template_name']; - $processed_content = saveBase64Images( - $_POST['content'], - $_SERVER['DOCUMENT_ROOT'] . "/uploads/document_templates/", - "uploads/document_templates/", - $document_template_id - ); + logAudit("Document Template", "Create", "$session_name copied document template " . escapeSql($row['document_template_name']) . " as " . escapeSql($new_name), 0, $new_id); - $processed_content_escaped = mysqli_escape_string($mysqli, $processed_content); + flashAlert("Document template " . escapeHtml($row['document_template_name']) . " copied as " . escapeHtml($new_name) . ""); - // CLEAN UP unused images - cleanupUnusedImages( - $processed_content, - $_SERVER['DOCUMENT_ROOT'] . "/uploads/document_templates/" . $document_template_id, - "/uploads/document_templates/" . $document_template_id - ); + redirect("document_template.php?document_template_id=$new_id"); - // Document edit query - mysqli_query($mysqli,"UPDATE document_templates SET document_template_name = '$name', document_template_description = '$description', document_template_content = '$processed_content_escaped', document_template_updated_by = $session_user_id WHERE document_template_id = $document_template_id"); +} - logAudit("Document Template", "Edit", "$session_name edited document template $name", 0, $document_template_id); +if (isset($_GET['archive_document_template']) || isset($_GET['restore_document_template'])) { - flashAlert("Document Template $name edited"); + validateCSRFToken(); + + $archive = isset($_GET['archive_document_template']); + $row = documentTemplateForRequest($archive ? $_GET['archive_document_template'] : $_GET['restore_document_template']); + $document_template_id = intval($row['document_template_id']); + + // Archived, it isn't offered for new documents; the ones made from it stay + mysqli_query($mysqli, "UPDATE document_templates SET document_template_archived_at = " . ($archive ? 'NOW()' : 'NULL') . " WHERE document_template_id = $document_template_id"); + + logAudit("Document Template", $archive ? "Archive" : "Restore", "$session_name " . ($archive ? 'archived' : 'restored') . " document template " . escapeSql($row['document_template_name']), 0, $document_template_id); + + flashAlert("Document template " . escapeHtml($row['document_template_name']) . " " . ($archive ? 'archived' : 'restored'), $archive ? 'error' : 'success'); redirect(); @@ -75,19 +82,16 @@ if (isset($_GET['delete_document_template'])) { validateCSRFToken(); - $document_template_id = intval($_GET['delete_document_template']); + $row = documentTemplateForRequest($_GET['delete_document_template']); - $document_template_name = escapeSql(getFieldById('document_templates', $document_template_id, 'document_template_name')); + // Its images go with it; the documents made from it stay, no longer linked to it + documentTemplateDelete($row['document_template_id']); - mysqli_query($mysqli,"DELETE FROM document_templates WHERE document_template_id = $document_template_id"); + logAudit("Document Template", "Delete", "$session_name deleted document template " . escapeSql($row['document_template_name'])); - // Delete uploads/document_templates/$document_template_id if exists - removeDirectory($_SERVER['DOCUMENT_ROOT'] . "/uploads/document_templates/" . $document_template_id); + flashAlert("Document template " . escapeHtml($row['document_template_name']) . " deleted", 'error'); - logAudit("Document Template", "Delete", "$session_name deleted document template $document_template_name"); - - flashAlert("Document Template $document_template_name deleted", 'error'); - - redirect(); + // From its own page, back to the list + redirect(!empty($_GET['from_page']) ? 'document_templates.php' : null); } diff --git a/agent/document.php b/agent/document.php index b23965553..48f9b9ce6 100644 --- a/agent/document.php +++ b/agent/document.php @@ -15,11 +15,12 @@ require_once "includes/inc_all_client.php"; $document_id = intval($_GET['document_id'] ?? 0); $row = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT document_archived_at, document_client_visible, document_content, document_created_at, - document_description, document_folder_id, document_name, document_updated_at, + document_description, document_folder_id, document_name, document_updated_at, document_template_id, document_template_name, creator.user_name AS created_by_name, updater.user_name AS updated_by_name FROM documents LEFT JOIN users creator ON document_created_by = creator.user_id LEFT JOIN users updater ON document_updated_by = updater.user_id + LEFT JOIN document_templates USING (document_template_id) WHERE document_client_id = $client_id AND document_id = $document_id LIMIT 1")); @@ -88,6 +89,9 @@ $page_title = $row['document_name'];
Updated · Created + + · From template ' . escapeHtml($row['document_template_name']) . '' : escapeHtml($row['document_template_name']) ?> + · earlier version
diff --git a/agent/modals/document/document_add_from_template.php b/agent/modals/document/document_add_from_template.php index 855b7294b..92fafdb96 100644 --- a/agent/modals/document/document_add_from_template.php +++ b/agent/modals/document/document_add_from_template.php @@ -2,7 +2,9 @@ /* * New document from one of the admin's document templates - its content and - * its images, copied, in the folder it was opened from. + * its images, copied, in the folder it was opened from (add_document_from_template, + * functions/document_template.php). Each template is offered with its summary + * and how often it has been used; ?document_template_id picks one. */ require_once '../../../includes/modal_header.php'; @@ -18,8 +20,10 @@ $templates = []; $sql = mysqli_query($mysqli, "SELECT document_template_id, document_template_name, document_template_description FROM document_templates WHERE document_template_archived_at IS NULL ORDER BY document_template_name ASC"); while ($row = mysqli_fetch_assoc($sql)) { - $templates[] = $row; + $templates[intval($row['document_template_id'])] = $row; } +$usage = documentTemplateUsage(array_keys($templates)); +$picked = intval($_GET['document_template_id'] ?? 0); ob_start(); @@ -38,7 +42,7 @@ ob_start();
No document templates yet.
- + Add one in Admin › Document Templates
@@ -50,8 +54,10 @@ ob_start();
@@ -69,7 +75,7 @@ ob_start();
- +
diff --git a/agent/post/document.php b/agent/post/document.php index c6a9792ac..c56d60d83 100644 --- a/agent/post/document.php +++ b/agent/post/document.php @@ -121,53 +121,31 @@ if (isset($_POST['add_document_from_template'])) { enforceUserPermission('module_support', 2); - $client_id = intval($_POST['client_id']); - $document_name = trim($_POST['name'] ?? ''); - $document_description = escapeSql($_POST['description'] ?? ''); + $client_id = intval($_POST['client_id'] ?? 0); $document_template_id = intval($_POST['document_template_id'] ?? 0); enforceClientAccess(); - - $folder = folderOwnedId($_POST['folder'] ?? 0, $client_id); - - $row = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT document_template_content, document_template_name FROM document_templates - WHERE document_template_id = $document_template_id AND document_template_archived_at IS NULL")); - if (!$row) { - flashAlert('That template no longer exists.', 'error'); + if (!mysqli_num_rows(mysqli_query($mysqli, "SELECT 1 FROM clients WHERE client_id = $client_id"))) { + flashAlert('Pick the client it is for.', 'error'); redirect(); } - // No name given - the template's - if ($document_name === '') { - $document_name = $row['document_template_name']; + $folder = folderOwnedId($_POST['folder'] ?? 0, $client_id); + + // A copy of what it says and its images, remembering the template (functions/document_template.php) + $template = documentTemplateRow($document_template_id); + $document_id = documentTemplateMakeDocument($document_template_id, $client_id, $_POST['name'] ?? '', $_POST['description'] ?? '', $folder); + if (!$document_id) { + flashAlert('That template is gone or archived.', 'error'); + redirect(); } - $document_name_sql = escapeSql($document_name); + $document_name = (string) getFieldById('documents', $document_id, 'document_name'); - mysqli_query($mysqli, "INSERT INTO documents SET - document_name = '$document_name_sql', - document_description = '$document_description', - document_content = '', - document_content_raw = '', - document_folder_id = $folder, - document_created_by = $session_user_id, - document_client_id = $client_id"); + logAudit("Document", "Create", "$session_name created document " . escapeSql($document_name) . " from template " . escapeSql($template['document_template_name']), $client_id, $document_id); - $document_id = mysqli_insert_id($mysqli); + flashAlert("Document " . escapeHtml($document_name) . " created from template " . escapeHtml($template['document_template_name']) . ""); - // The template's images come along, and its HTML is pointed at the copies - copyDirectory($_SERVER['DOCUMENT_ROOT'] . "/uploads/document_templates/$document_template_id", $_SERVER['DOCUMENT_ROOT'] . "/uploads/documents/$document_id"); - $processed_html = str_replace("/uploads/document_templates/$document_template_id/", "/uploads/documents/$document_id/", (string) $row['document_template_content']); - - $content = mysqli_real_escape_string($mysqli, $processed_html); - $content_raw = escapeSql(documentContentRaw($document_name, $processed_html)); - - mysqli_query($mysqli, "UPDATE documents SET document_content = '$content', document_content_raw = '$content_raw' WHERE document_id = $document_id"); - - logAudit("Document", "Create", "$session_name created document $document_name_sql from template " . escapeSql($row['document_template_name']), $client_id, $document_id); - - flashAlert("Document $document_name created from template"); - - redirect("document.php?client_id=$client_id&document_id=$document_id"); + redirect("/agent/document.php?client_id=$client_id&document_id=$document_id"); } if (isset($_POST['edit_document'])) { diff --git a/db.sql b/db.sql index 069baa978..bf4df4e59 100644 --- a/db.sql +++ b/db.sql @@ -1334,8 +1334,10 @@ CREATE TABLE `documents` ( `document_created_by` int(11) NOT NULL DEFAULT 0, `document_updated_by` int(11) NOT NULL DEFAULT 0, `document_client_id` int(11) NOT NULL DEFAULT 0, + `document_template_id` int(11) NOT NULL DEFAULT 0, PRIMARY KEY (`document_id`), KEY `document_client_id` (`document_client_id`,`document_archived_at`), + KEY `document_template_id` (`document_template_id`), FULLTEXT KEY `document_content_raw` (`document_content_raw`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci; /*!40101 SET character_set_client = @saved_cs_client */; diff --git a/functions.php b/functions.php index f56d843cd..2b9cecea7 100644 --- a/functions.php +++ b/functions.php @@ -55,6 +55,7 @@ require_once __DIR__ . '/functions/ticket_template.php'; 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/project.php'; require_once __DIR__ . '/functions/service.php'; require_once __DIR__ . '/functions/client_export.php'; diff --git a/functions/document_template.php b/functions/document_template.php new file mode 100644 index 000000000..aa1dafcbc --- /dev/null +++ b/functions/document_template.php @@ -0,0 +1,201 @@ + Document Templates): documents ready + * to start a client's from - a runbook, a build sheet, a plan - with their + * images, kept in uploads/document_templates//. A document made from one + * gets a copy of what it says and its images, and remembers which template it + * came from (documents.document_template_id, from database 3.2.5 on), so each + * template's use is counted. Words in square brackets - [Client], [Date] - are + * left for whoever writes the document to fill in. + * + * Shared by admin/document_templates.php, admin/document_template.php, + * admin/modals/document_template/*, admin/post/document_template.php and the + * New document from a template window and its handler on the agent side + * (agent/modals/document/document_add_from_template.php, agent/post/document.php). + */ + +/** Where a template's images are kept, from the app's root - its folder under uploads/document_templates/. */ +function documentTemplateDir($document_template_id) { + return dirname(__DIR__) . '/uploads/document_templates/' . intval($document_template_id); +} + +/** One template, archived or not, with who made it and last changed it - or null. */ +function documentTemplateRow($document_template_id) { + global $mysqli; + $document_template_id = intval($document_template_id); + if ($document_template_id <= 0) { + return null; + } + $row = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT document_template_id, document_template_name, document_template_description, document_template_content, + document_template_created_at, document_template_updated_at, document_template_archived_at, document_template_created_by, document_template_updated_by, + creator.user_name AS created_by_name, updater.user_name AS updated_by_name + FROM document_templates + LEFT JOIN users creator ON creator.user_id = document_template_created_by AND document_template_created_by > 0 + LEFT JOIN users updater ON updater.user_id = document_template_updated_by AND document_template_updated_by > 0 + WHERE document_template_id = $document_template_id")); + return $row ?: null; +} + +/* + * How the templates have been used - template id => count (documents made from + * it that are not archived), clients (how many clients have one) and last (when + * the latest was made). Ones not used aren't in it. + */ +function documentTemplateUsage(array $document_template_ids) { + global $mysqli; + $ids = array_values(array_filter(array_map('intval', $document_template_ids))); + $usage = []; + if (!$ids) { + return $usage; + } + $sql = mysqli_query($mysqli, "SELECT document_template_id, COUNT(*) AS n, COUNT(DISTINCT document_client_id) AS clients, MAX(document_created_at) AS last + FROM documents WHERE document_template_id IN (" . implode(',', $ids) . ") AND document_archived_at IS NULL GROUP BY document_template_id"); + while ($row = mysqli_fetch_assoc($sql)) { + $usage[intval($row['document_template_id'])] = ['count' => intval($row['n']), 'clients' => intval($row['clients']), 'last' => $row['last']]; + } + return $usage; +} + +/* + * The template window's fields, checked - or null with $error saying why. + * $post: name, description (one line on what it is for) and content (the + * editor's HTML, kept as written - it is made safe where it is shown). + */ +function documentTemplateFields(array $post, &$error = '') { + $error = ''; + $name = trim(preg_replace('/\s+/u', ' ', strip_tags((string) ($post['name'] ?? '')))); + if ($name === '') { + $error = 'A document template needs a name'; + return null; + } + if (mb_strlen($name) > 200) { + $error = 'Keep the name to 200 characters'; + return null; + } + $description = trim(preg_replace('/\s+/u', ' ', strip_tags((string) ($post['description'] ?? '')))); + if (mb_strlen($description) > 500) { + $error = 'Keep the summary to 500 characters'; + return null; + } + return ['name' => $name, 'description' => $description, 'content' => (string) ($post['content'] ?? '')]; +} + +/* + * Save a template's fields (documentTemplateFields()) - a new one with + * $document_template_id 0. Pasted-in images are kept in its folder, and on a + * change the ones it no longer shows are taken away. Its id. + */ +function documentTemplateSave($document_template_id, array $f) { + global $mysqli, $session_user_id; + $document_template_id = intval($document_template_id); + $user_id = intval($session_user_id ?? 0); + $set = "document_template_name = '" . escapeSql($f['name']) . "', document_template_description = '" . escapeSql($f['description']) . "'"; + $new = !$document_template_id; + if ($new) { + // Made first, so its images have a folder named for it + mysqli_query($mysqli, "INSERT INTO document_templates SET $set, document_template_content = '', document_template_created_by = $user_id"); + $document_template_id = intval(mysqli_insert_id($mysqli)); + } + $content = saveBase64Images($f['content'], dirname(__DIR__) . '/uploads/document_templates/', 'uploads/document_templates/', $document_template_id); + cleanupUnusedImages($content, documentTemplateDir($document_template_id), '/uploads/document_templates/' . $document_template_id); + // A new one hasn't been changed yet - its content going in isn't a change + mysqli_query($mysqli, "UPDATE document_templates SET $set, document_template_content = '" . mysqli_real_escape_string($mysqli, $content) . "', + " . ($new ? 'document_template_updated_at = NULL' : "document_template_updated_by = $user_id") . " WHERE document_template_id = $document_template_id"); + return $document_template_id; +} + +/* + * A template's HTML with its images pointed at another folder of copies - for a + * copy of the template, or a document made from it. $to_web is the new + * folder's web path ('/uploads/documents/12/'). + */ +function documentTemplateCopyImages($document_template_id, $to_dir, $to_web, $html) { + $document_template_id = intval($document_template_id); + copyDirectory(documentTemplateDir($document_template_id), $to_dir); + return str_replace("/uploads/document_templates/$document_template_id/", $to_web, (string) $html); +} + +/* A new template starting from this one - "Copy of", with copies of its images. Its id, or 0. */ +function documentTemplateCopy($document_template_id) { + global $mysqli, $session_user_id; + $row = documentTemplateRow($document_template_id); + if (!$row) { + return 0; + } + $user_id = intval($session_user_id ?? 0); + mysqli_query($mysqli, "INSERT INTO document_templates SET document_template_name = '" . escapeSql(mb_substr('Copy of ' . $row['document_template_name'], 0, 200)) . "', + document_template_description = '" . escapeSql((string) $row['document_template_description']) . "', document_template_content = '', document_template_created_by = $user_id"); + $new_id = intval(mysqli_insert_id($mysqli)); + $content = documentTemplateCopyImages($row['document_template_id'], documentTemplateDir($new_id), "/uploads/document_templates/$new_id/", $row['document_template_content']); + mysqli_query($mysqli, "UPDATE document_templates SET document_template_content = '" . mysqli_real_escape_string($mysqli, $content) . "', document_template_updated_at = NULL WHERE document_template_id = $new_id"); + return $new_id; +} + +/* Delete a template and its folder of images. The documents made from it stay, no longer linked to it. */ +function documentTemplateDelete($document_template_id) { + global $mysqli; + $document_template_id = intval($document_template_id); + mysqli_query($mysqli, "DELETE FROM document_templates WHERE document_template_id = $document_template_id"); + mysqli_query($mysqli, "UPDATE documents SET document_template_id = 0 WHERE document_template_id = $document_template_id"); + removeDirectory(documentTemplateDir($document_template_id)); +} + +/* + * Make a client's document from a template - what it says and its images, + * copied, in $folder_id, called $name (the template's when '') - remembering + * the template. The new document's id, or 0 when the template is gone or + * archived. + */ +function documentTemplateMakeDocument($document_template_id, $client_id, $name = '', $description = '', $folder_id = 0) { + global $mysqli, $session_user_id; + $row = documentTemplateRow($document_template_id); + if (!$row || $row['document_template_archived_at']) { + return 0; + } + $template_id = intval($row['document_template_id']); + $client_id = intval($client_id); + $name = trim((string) $name) !== '' ? mb_substr(trim((string) $name), 0, 200) : (string) $row['document_template_name']; + $description = trim((string) $description) !== '' ? trim((string) $description) : (string) $row['document_template_description']; + mysqli_query($mysqli, "INSERT INTO documents SET document_name = '" . escapeSql($name) . "', document_description = '" . escapeSql($description) . "', + document_content = '', document_content_raw = '', document_folder_id = " . intval($folder_id) . ", document_created_by = " . intval($session_user_id ?? 0) . ", + document_client_id = $client_id, document_template_id = $template_id"); + $document_id = intval(mysqli_insert_id($mysqli)); + + // The template's images come along, and its HTML is pointed at the copies + $html = documentTemplateCopyImages($template_id, dirname(__DIR__) . "/uploads/documents/$document_id", "/uploads/documents/$document_id/", $row['document_template_content']); + mysqli_query($mysqli, "UPDATE documents SET document_content = '" . mysqli_real_escape_string($mysqli, $html) . "', + document_content_raw = '" . escapeSql(documentContentRaw($name, $html)) . "' WHERE document_id = $document_id"); + return $document_id; +} + +/* What a template says, as a line of plain text - for the lists. */ +function documentTemplatePreview($html, $length = 160) { + $text = trim(preg_replace('/\s+/u', ' ', html_entity_decode(strip_tags(str_replace('<', ' <', (string) $html)), ENT_QUOTES, 'UTF-8'))); + return mb_strimwidth($text, 0, $length, '...'); +} + +/* The words in square brackets in a template's text - [Client], [Date of visit] - each once, as written first. */ +function documentTemplateBracketsIn($html) { + $text = html_entity_decode(strip_tags(str_replace('<', ' <', (string) $html)), ENT_QUOTES, 'UTF-8'); + preg_match_all('/\[([A-Za-z][A-Za-z0-9 _\-\/\x{00A0}]{0,40})\]/u', $text, $matches); + $found = []; + foreach ($matches[1] as $word) { + $word = trim(preg_replace('/[\s\x{00A0}]+/u', ' ', $word)); + if ($word !== '' && !isset($found[mb_strtolower($word)])) { + $found[mb_strtolower($word)] = $word; + } + } + return array_values($found); +} + +/* A template's HTML (already made safe) with its [words] marked, in its text only - for its page. */ +function documentTemplateMarkBrackets($html) { + $pieces = preg_split('/(<[^>]*>)/', (string) $html, -1, PREG_SPLIT_DELIM_CAPTURE); + foreach ($pieces as $i => $piece) { + if ($i % 2 === 0 && $piece !== '') { + $pieces[$i] = preg_replace('/\[([A-Za-z][A-Za-z0-9 _\-\/]{0,40})\]/', '[$1]', $piece); + } + } + return implode('', $pieces); +}