diff --git a/CHANGELOG.md b/CHANGELOG.md index dec743b06..291611932 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,7 +6,7 @@ This file documents all notable changes made to ITFlow. ### Upgrading to 26.12.5 -Update from Maintenance > Update as usual. This release has one database change, 4.4.2, which keeps when a cron job was last started by something other than cron.php. +Update from Maintenance > Update as usual. This release has two database changes: 4.4.2 keeps when a cron job was last started by something other than cron.php, and 4.4.3 lets Knowledge Base articles be written in Markdown. - If ITFlow was installed with the install script before 26.08, `/etc/cron.d/itflow` may still have a line for each job besides the `cron.php` one - the 26.08 upgrade asked for them to come out. Maintenance > Cron now lists any it finds, with the file and line. Take them out: `cron.php` runs every job. Until then they step aside while `cron.php` is running, so nothing runs twice. - Cron started as root - a crontab line for root, or `php cron/cron.php` typed in a root shell - now runs as the user that owns ITFlow's files, so what it makes is that user's. @@ -16,6 +16,7 @@ Update from Maintenance > Update as usual. This release has one database change, - Cron leaves alone the jobs that have nothing to do on your ITFlow - what they work with is switched off or isn't set up: AI Triage, Text Messages, RMM Sync and RMM Alerts, the Ticket Email Parser with email to ticket off or no mailbox, the Mail Queue with no mail server, Payment Provider Fees without Stripe, the Update Check on an install that isn't a git checkout, and Manager Check-in and Managed Instances when there's nothing connected. Before, each one started every minute only to stop itself. Maintenance > Cron shows them as **Not in use**, with why under each; they start by themselves once that changes, and **Run Now** still runs them. Cron Watch doesn't email about them falling behind. - An API / service account no longer takes a seat on the agent user limit - the one your hosting provider sets, or one set for your installation. Nobody signs in as it: it's the login an integration's API keys act as. You can add one, enable one or restore one when every seat is taken, and Admin > Users shows the seats without them. Turning one back into an agent who signs in takes a seat, so there has to be one free. A hosted instance's manager sees it the same way: its seats taken leave API accounts out, and its list of agents marks them. - Unlock your credentials with a passkey. When a passkey sign-in leaves them locked although your passkey opens them - signing in by scanning a QR code with your phone, or some password managers' autofill - the Unlock window offers **Unlock with a Passkey** before your password, with any passkey of yours that opens them. It's there while passkeys are on in Admin > Settings > Security. +- Knowledge Base articles can be written in Markdown, as documents can. New and Edit Article have the same **Rich text** / **Markdown** switch and Markdown toolbar with Write and Preview, and switching either way converts what's written. A new article starts the way you wrote last. Saved versions keep their Markdown, so putting one back brings back what was written then. **Import Markdown Files**, in the New Article menu, makes each .md file an article - a draft for agents only, in the category you pick - and **Export** on an article now has **Markdown (.md)** beside PDF. A document written in Markdown copied into the Knowledge Base arrives in Markdown, and with Write up for the Knowledge Base in Markdown the AI's draft comes in as Markdown. The client portal, the public help center, search, ticket replies and PDFs show a Markdown article like any other. - Password managers fill your password in the Unlock window. Bitwarden and the like offer the ITFlow password they keep for signing in, as they do on the sign-in page - handy where your passkey can't open your credentials itself, as with passkeys kept in Bitwarden. ### Bug Fixes @@ -31,6 +32,7 @@ Update from Maintenance > Update as usual. This release has one database change, - Cron jobs can declare `'not_in_use' => function () { ... }` in `includes/cron_jobs.php`, returning why the job has nothing to do on this install or `''` (`cronJobNotInUse()`, which counts a check that throws as in use; `cronJobSettings()` reads the settings the checks need once a request). `cron/cron.php` reads every job's row and Run Now flag once a cycle and skips a job not in use before its lock and claim - registering its row the first time (`cronJobRegister()`, split out of `cronJobClaim()`) - unless it is asked to Run Now. `cronHealthJobs()` leaves such jobs out, so Cron Watch neither waits on nor flags them, and `admin/cron.php` shows them in a new `unused` state. Checks added for `manager_checkin`, `mail_queue`, `sms_queue`, `rmm_sync`, `rmm_alerts`, `ticket_email_parser`, `ai_triage`, `managed_instances`, `payment_provider_fees` and `update_check`, each the same condition its script stops on. `aiTriageNotInUse()` (`functions/ai_ticket.php`) is new, and `cron/ai_triage.php` now stops on it too. CONTRIBUTING.md has the rule. - Cron and runs outside it (database 4.4.2, `cron_jobs.cron_job_outside_at`): `cron/includes/cron_lock.php` gains `cronLockFile()`, `cronLockHolder()`, `cronLockFileProblem()`, `cronLockDispatchBeat()`, `cronLockOutsideFile()`, `cronLockAttended()` and `cronLockRunAsOwner()`, run first: started as root on an install whose `cron/cron.php` is another user's, it calls `posix_initgroups()`, `posix_setgid()` and `posix_setuid()` to become that user, or exits saying how to run it. `cronLockAcquire($path, $stamp)` returns null for a lock file it can't open (it used to `die()`, ending the dispatch at that job), and writes `direct` or `terminal` into the file while a run on its own holds it. The dispatcher touches the heartbeat file each cycle; a run on its own without a terminal on STDIN (`stream_isatty()`) while it is under 180 seconds old exits 0, quietly, and touches its `.outside` file. The dispatcher records that file's time, or a lock found held by a `direct` run, as `cron_job_outside_at` (`cronJobNoteOutside()`, at most every ten minutes), and fails a job whose lock can't be opened with `cronLockFileProblem()` as its error (`cronJobLockFailed()`, logged to App Logs once). `functions/cron_health.php`: `cronStrayLines()` reads `/etc/crontab` and the `/etc/cron.d` files cron would read for lines that run this install's job scripts on their own (anything in `cron/` but `cron.php`, and the old `scripts/cron*.php` and `cron_*.php`), `cronStrayText()`, `cronStrayWhat()`, `cronOutsideJobs()` (the last `CRON_HEALTH_OUTSIDE_HOURS`, 26), `cronOutsideReady()` and `cronFilesOwner()`; `cronHealthProblems()` adds a `stray` problem and an `outside` one per job the lines don't cover, and doesn't call a job overdue while it is run outside. `health.php` leaves both kinds out, so an uptime monitor doesn't go red for them. Maintenance > Cron has a card for the lines (`data-cron-stray`, `data-cron-stray-line`) and a note on each job run outside (`data-cron-outside`); Debug's Background jobs adds Old cron lines. CONTRIBUTING.md has the rule. - Passkeys sealed to the vault after they were added (`functions/passkey.php`, no database change): `login_passkey.php` keeps a passkey's PRF result for the session when it has no `passkey_vault` that opens with it - `passkeySealKeep()`, AES-256-GCM in `$_SESSION['passkey_seal']` with its key in the httponly `passkey_seal_key` cookie, set as `user_encryption_session_key` is - and once the vault opens, `vaultUnlock()` or the new `vaultUnlockPasskey()` seals the vault key to it (`passkeySealKept()`, checked to open before `passkey_vault` is written; the kept secret is dropped either way, and logout clears the cookie). `vaultUnlockPasskey()` checks an assertion for the new `unlock` challenge purpose against the signed-in agent's own passkeys - `passkeyVerify($post, $purpose, $user_id)`, which `passkeyVerifySignIn()` now wraps - and opens the vault with its PRF result; a passkey whose copy doesn't open with it keeps that result for the password to seal. `passkeyUnlockOptions()`, `passkeyVaultCount()` and `passkeySealPending()` feed the Unlock window (`includes/footer.php`, `[data-vault-unlock-passkey]`), and `agent/ajax.php` adds `vault_unlock_passkey_options` and `vault_unlock_passkey` (POST, CSRF). `js/passkey.js` handles the button, runs once per page (`window.itflowPasskeys`) and fires `itflow:vault-unlocked` on `#vaultUnlockModal`, which `js/credentials.js` now listens for. A passkey that doesn't unlock is logged as Login / Unlock Failed. `vaultLockedReason()` for a passkey sign-in now reads "your passkey sign-in didn't open them". The Unlock window's form drops `autocomplete="off"` and carries the agent's email in a hidden `autocomplete="username"` field (as `join.php` does), so password managers match it to the sign-in they keep. +- Knowledge Base articles in Markdown (database 4.4.3): `kb_articles.kb_article_markdown` and `kb_article_versions.kb_article_version_markdown` (NULL for rich text), with `kbMarkdownReady()`, `kbMarkdownSql()` and `kbMarkdownSet()` in `functions/kb.php`. `kbArticleFields()` reads `format` and `markdown`; `kbArticleSave()` takes `markdown` and stores `kb_article_content` as `markdownToHtml()` of it, so every reader of `kb_article_content` is unchanged; `kbKeepVersion()`, the version restore, `copy_kb_article` and `kbArticleFromDocument()` carry it (with picture paths moved to the new article's folder). `markdownSaveImages()` takes a third `$folder` ('kb' for `uploads/kb//`). `includes/document_editors.php` takes `$document_editor_rich_class` and `$document_editor_markdown_ready`, which `agent/modals/kb/kb_article_form.php` sets to keep `.tinymce` and `kbMarkdownReady()`. New: `export_kb_article_markdown` and `import_markdown_kb_articles` in `agent/post/kb.php` and `agent/modals/kb/kb_import_markdown.php`. The write-up from a ticket uses `itflowDocumentFormat.putHtml()` when its form is in Markdown. ## [26.12.4] diff --git a/admin/database_updates/4.4.3.php b/admin/database_updates/4.4.3.php new file mode 100644 index 000000000..67096ab2a --- /dev/null +++ b/admin/database_updates/4.4.3.php @@ -0,0 +1,29 @@ +New Article - + + diff --git a/agent/kb_article.php b/agent/kb_article.php index 4c80740de..ac8ed8061 100644 --- a/agent/kb_article.php +++ b/agent/kb_article.php @@ -6,7 +6,7 @@ * page: a header card with the actions, the article beside a column with its * category, who can read it, its review, how its readers found it, what they * said didn't help and its versions; its files under it. It can be taken as - * a PDF, and reviewed by AI (modals/kb/kb_article_review.php). + * a PDF or a Markdown file, and reviewed by AI (modals/kb/kb_article_review.php). * * Open to anyone who can read Support; changing it takes Support edit, like * the handlers behind it (agent/post/kb.php). @@ -98,6 +98,7 @@ $page_title = $row['kb_article_title']; Updated · Written · earlier version + · Markdown
@@ -116,8 +117,17 @@ $page_title = $row['kb_article_title']; Review with AI - - PDF +
- +
Saving keeps what it says now in the article's versions, so it can be put back.
diff --git a/agent/modals/kb/kb_article_from_ticket.php b/agent/modals/kb/kb_article_from_ticket.php index 148a22846..d9ab37023 100644 --- a/agent/modals/kb/kb_article_from_ticket.php +++ b/agent/modals/kb/kb_article_from_ticket.php @@ -9,7 +9,8 @@ * people and its systems left out - an article is for every client. Without * it, the window starts with the ticket's subject and what was asked, and the * steps are written here. add_kb_article (agent/post/kb.php) creates it, and - * the ticket's history says it was written up. + * the ticket's history says it was written up. Written in Markdown - the + * agent's way of writing last time - the AI's draft goes in as Markdown. */ require_once '../../../includes/modal_header.php'; @@ -107,15 +108,22 @@ ob_start(); } form.querySelector('[name="title"]').value = answer.title; form.querySelector('[name="summary"]').value = answer.description; + var done = function () { + say('success', 'fa-check-circle', 'Written by AI from the ticket' + (answer.removed ? ' - ' + answer.removed + ' password' + (answer.removed === 1 ? '' : 's') + ' or key' + (answer.removed === 1 ? '' : 's') + ' left out as [removed]' : '') + '. Read it through for anything about the client, then create it.'); + status.setAttribute('data-kb-from-ticket-ready', ''); + save.disabled = false; + }; + // The form in Markdown (includes/document_editors.php) - the draft made Markdown + if (window.itflowDocumentFormat && itflowDocumentFormat.isMarkdown(form)) { + return itflowDocumentFormat.putHtml(form, answer.html).then(done); + } editor(function (ed) { if (ed) { ed.setContent(answer.html); } else { textarea.value = answer.html; } - say('success', 'fa-check-circle', 'Written by AI from the ticket' + (answer.removed ? ' - ' + answer.removed + ' password' + (answer.removed === 1 ? '' : 's') + ' or key' + (answer.removed === 1 ? '' : 's') + ' left out as [removed]' : '') + '. Read it through for anything about the client, then create it.'); - status.setAttribute('data-kb-from-ticket-ready', ''); - save.disabled = false; + done(); }); }) .catch(function (error) { diff --git a/agent/modals/kb/kb_import_markdown.php b/agent/modals/kb/kb_import_markdown.php new file mode 100644 index 000000000..7fff2a6e8 --- /dev/null +++ b/agent/modals/kb/kb_import_markdown.php @@ -0,0 +1,65 @@ + $kb_closed])); +} + +$kb_import_category = kbCategoryId($_GET['category'] ?? 0); + +ob_start(); + +?> + + +
+ + + +
+ + false, 'content' => '', ] + kbAudienceFields($row)); + // In Markdown when it is written in it $content = (string) $row['kb_article_content']; + $markdown = $row['kb_article_markdown'] ?? null; $from = kbArticleDir($row['kb_article_id']); if (is_dir($from)) { copyDirectory($from, kbArticleDir($kb_article_id)); $content = str_replace('/uploads/kb/' . intval($row['kb_article_id']) . '/', "/uploads/kb/$kb_article_id/", $content); + $markdown = $markdown === null ? null : str_replace('/uploads/kb/' . intval($row['kb_article_id']) . '/', "/uploads/kb/$kb_article_id/", $markdown); kbArticleCopyFileRows($row['kb_article_id'], $kb_article_id); } mysqli_query($mysqli, "UPDATE kb_articles SET kb_article_content = '" . mysqli_real_escape_string($mysqli, $content) . "', kb_article_content_raw = '" . escapeSql(kbArticleContentRaw('Copy of ' . $row['kb_article_title'], (string) $row['kb_article_summary'], $content)) . "' + " . kbMarkdownSet($markdown) . " WHERE kb_article_id = $kb_article_id"); mysqli_query($mysqli, "INSERT INTO kb_article_tags (kb_article_id, tag_id) SELECT $kb_article_id, tag_id FROM kb_article_tags WHERE kb_article_id = " . intval($row['kb_article_id'])); @@ -214,7 +218,8 @@ if (isset($_GET['copy_kb_article'])) { if (isset($_POST['restore_kb_article_version'])) { $kb_article_version_id = intval($_POST['kb_article_version_id'] ?? 0); - $version = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT kb_article_version_title, kb_article_version_summary, kb_article_version_content, kb_article_version_kb_article_id + $version = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT kb_article_version_title, kb_article_version_summary, kb_article_version_content, + " . kbMarkdownSql('kb_article_version_markdown') . ", kb_article_version_kb_article_id FROM kb_article_versions WHERE kb_article_version_id = $kb_article_version_id")); if (!$version) { flashAlert('That version no longer exists.', 'error'); @@ -223,7 +228,7 @@ if (isset($_POST['restore_kb_article_version'])) { $row = kbArticleForHandler($version['kb_article_version_kb_article_id']); $kb_article_id = intval($row['kb_article_id']); - // What it says now becomes a version itself + // What it says now becomes a version itself - and it is back in the way it was written then, Markdown or rich text kbArticleSave([ 'title' => $version['kb_article_version_title'], 'summary' => (string) $version['kb_article_version_summary'], @@ -231,6 +236,7 @@ if (isset($_POST['restore_kb_article_version'])) { 'review_months' => intval($row['kb_article_review_months']), 'published' => !empty($row['kb_article_published_at']), 'content' => (string) $version['kb_article_version_content'], + 'markdown' => $version['kb_article_version_markdown'], ] + kbAudienceFields($row), $row); logAudit("Knowledge Base", "Edit", "$session_name put back an earlier version of article " . escapeSql($version['kb_article_version_title']), 0, $kb_article_id); @@ -469,3 +475,98 @@ if (isset($_GET['export_kb_article'])) { require_once '../functions/document_pdf.php'; billingPdfSend(documentPdfRender(documentPdfKbArticle($row))); } + +/* + * An article as a Markdown file (documentMarkdownFile(), functions/markdown.php) - as it was + * written when it is in Markdown, its rich text made Markdown otherwise - with its title on top. + */ +if (isset($_GET['export_kb_article_markdown'])) { + + validateCSRFToken(); + $kb_closed = kbClosedText(1); + if ($kb_closed !== '') { + flashAlert(escapeHtml($kb_closed), 'error'); + redirect(); + } + $row = kbArticleForHandler($_GET['export_kb_article_markdown'], false); + + logAudit("Knowledge Base", "Export", "$session_name downloaded article " . escapeSql($row['kb_article_title']) . " as Markdown", 0, intval($row['kb_article_id'])); + + $file_name = trim(preg_replace('/[^A-Za-z0-9 ._-]/', '', $row['kb_article_title'])) ?: 'Article'; + header('Content-Type: text/markdown; charset=UTF-8'); + header('Content-Disposition: attachment; filename="' . $file_name . '.md"; filename*=UTF-8\'\'' . rawurlencode(trim($row['kb_article_title']) . '.md')); + header('X-Content-Type-Options: nosniff'); + echo documentMarkdownFile($row['kb_article_title'], $row['kb_article_content'], $row['kb_article_markdown'] ?? null); + exit; +} + +/* + * Markdown files made into articles (agent/modals/kb/kb_import_markdown.php) - one each, written + * in Markdown, as drafts for agents only, in the category picked. Each is named by the title in + * its front matter or the heading it starts with, else its file name (markdownImportSplit()). + */ +if (isset($_POST['import_markdown_kb_articles'])) { + + if (!kbMarkdownReady()) { + flashAlert('Markdown files can\'t be imported here yet - run the database update from Maintenance > Update first.', 'error'); + redirect(); + } + $category_id = kbCategoryId($_POST['category_id'] ?? 0); + + $files = $_FILES['files'] ?? null; + $count = is_array($files['name'] ?? null) ? count($files['name']) : 0; + $imported = []; + $skipped = []; + for ($i = 0; $i < $count && count($imported) < 50; $i++) { + $original = basename((string) $files['name'][$i]); + if ($files['error'][$i] === UPLOAD_ERR_NO_FILE) { + continue; + } + if ($files['error'][$i] !== UPLOAD_ERR_OK || !is_uploaded_file($files['tmp_name'][$i])) { + $skipped[] = "$original (it didn't upload)"; + continue; + } + if (!preg_match('/\.(md|markdown|mdown|mkd)$/i', $original)) { + $skipped[] = "$original (not a .md file)"; + continue; + } + if ($files['size'][$i] > 5 * 1024 * 1024) { + $skipped[] = "$original (over 5 MB)"; + continue; + } + $text = (string) file_get_contents($files['tmp_name'][$i]); + if (!mb_check_encoding($text, 'UTF-8')) { + $skipped[] = "$original (not UTF-8 text)"; + continue; + } + + [$title, $markdown] = markdownImportSplit($text, preg_replace('/\.(md|markdown|mdown|mkd)$/i', '', $original)); + $kb_article_id = kbArticleSave([ + 'title' => $title, + 'summary' => '', + 'category_id' => $category_id, + 'review_months' => 12, + 'published' => false, + 'content' => '', + 'markdown' => $markdown, + 'visibility' => 'agents', + 'all_clients' => false, + 'client_tag_ids' => [], + 'client_ids' => [], + ]); + + logAudit("Knowledge Base", "Create", "$session_name imported a draft of article " . escapeSql($title) . " from " . escapeSql($original), 0, $kb_article_id); + $imported[] = [$kb_article_id, $title]; + } + + if (!$imported) { + flashAlert('Nothing was imported' . ($skipped ? ': ' . escapeHtml(implode(', ', $skipped)) : ' - pick the .md files to import.'), 'error'); + redirect(); + } + + $what = count($imported) === 1 ? 'Article ' . escapeHtml($imported[0][1]) . ' imported as a draft' : count($imported) . ' articles imported as drafts'; + flashAlert($what . ($skipped ? ' - left out ' . escapeHtml(implode(', ', $skipped)) : ''), $skipped ? 'warning' : 'success'); + + // One goes straight to it; several, to the drafts + redirect(count($imported) === 1 ? "kb_article.php?kb_article_id={$imported[0][0]}" : 'kb.php?show=drafts'); +} diff --git a/db.sql b/db.sql index 0ad8d4dba..cfc7aeddb 100644 --- a/db.sql +++ b/db.sql @@ -2257,6 +2257,7 @@ CREATE TABLE `kb_article_versions` ( `kb_article_version_title` varchar(200) NOT NULL, `kb_article_version_summary` varchar(255) DEFAULT NULL, `kb_article_version_content` longtext NOT NULL, + `kb_article_version_markdown` longtext DEFAULT NULL, `kb_article_version_created_at` datetime NOT NULL DEFAULT current_timestamp(), `kb_article_version_created_by` int(11) NOT NULL DEFAULT 0, `kb_article_version_kb_article_id` int(11) NOT NULL, @@ -2278,6 +2279,7 @@ CREATE TABLE `kb_articles` ( `kb_article_summary` varchar(255) DEFAULT NULL, `kb_article_content` longtext NOT NULL, `kb_article_content_raw` longtext NOT NULL, + `kb_article_markdown` longtext DEFAULT NULL, `kb_article_category_id` int(11) NOT NULL DEFAULT 0, `kb_article_published_at` datetime DEFAULT NULL, `kb_article_visibility` varchar(20) NOT NULL DEFAULT 'agents', diff --git a/functions/kb.php b/functions/kb.php index ad3cef02b..4399b516c 100644 --- a/functions/kb.php +++ b/functions/kb.php @@ -13,7 +13,15 @@ * An article has a title, a line saying what it is for, a category (Admin > * Categories, the 'kb' kind), tags (the kb_article kind) and its content - the * editor's HTML, purified wherever it is shown (documentHtmlPurify()). Without - * a publish date it is a draft. Each edit keeps what it said before as a + * a publish date it is a draft. + * + * Written in Markdown (database 4.4.3, kbMarkdownReady()), as a document can + * be (functions/markdown.php, includes/document_editors.php): what was written + * is kept in kb_article_markdown, and kb_article_content is the HTML made from + * it each time it is saved - so everywhere an article is shown, searched, put + * in a reply or made a PDF stays as it is. It switches either way, versions + * keep their Markdown, .md files are imported as articles, and an article + * downloads as one. Each edit keeps what it said before as a * version. When it says how often, it is due for review that long after it was * last made, edited or reviewed - an edit counts, as it does for documents. * @@ -56,6 +64,36 @@ function kbPublicOn() { return kbOn() && intval($GLOBALS['config_kb_public_enable']) === 1; } +/** Can articles be written in Markdown - the database at 4.4.3? */ +function kbMarkdownReady() { + global $mysqli; + static $ready = null; + if ($ready === null) { + if (defined('CURRENT_DATABASE_VERSION')) { + $version = CURRENT_DATABASE_VERSION; + } else { + $result = mysqli_query($mysqli, "SELECT config_current_database_version FROM settings WHERE company_id = 1"); + $version = $result && ($row = mysqli_fetch_row($result)) ? (string) $row[0] : '0'; + } + $ready = version_compare($version, '4.4.3', '>='); + } + return $ready; +} + +/** The column to SELECT for what a Markdown article (or version) says - NULL before 4.4.3. */ +function kbMarkdownSql($column = 'kb_article_markdown') { + return kbMarkdownReady() ? $column : "NULL AS $column"; +} + +/** ", kb_article_markdown = ..." for an UPDATE or INSERT - NULL for rich text, nothing before 4.4.3. */ +function kbMarkdownSet($markdown, $column = 'kb_article_markdown') { + global $mysqli; + if (!kbMarkdownReady()) { + return ''; + } + return ", $column = " . ($markdown === null ? 'NULL' : "'" . mysqli_real_escape_string($mysqli, (string) $markdown) . "'"); +} + /* The published articles a client's portal shows, as a WHERE condition on kb_articles. */ function kbClientSql($client_id) { $client_id = intval($client_id); @@ -263,7 +301,7 @@ function kbClosedText($level = 1) { function kbArticleRow($kb_article_id) { global $mysqli; $kb_article_id = intval($kb_article_id); - return mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT kb_article_id, kb_article_title, kb_article_summary, kb_article_content, kb_article_category_id, + return mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT kb_article_id, kb_article_title, kb_article_summary, kb_article_content, " . kbMarkdownSql() . ", kb_article_category_id, kb_article_published_at, kb_article_visibility, kb_article_all_clients, kb_article_review_months, kb_article_reviewed_at, kb_article_reviewed_by, " . (kbFeedbackReady() ? 'kb_article_views' : '0 AS kb_article_views') . ", kb_article_created_at, kb_article_created_by, kb_article_updated_at, kb_article_updated_by, kb_article_archived_at, @@ -280,7 +318,9 @@ function kbArticleRow($kb_article_id) { /* * An article's fields from a form - title (required), summary, category_id, * review_months, published (on or off) and content - as [fields, error]. A - * category must be a Knowledge Base one; anything else counts as none. + * category must be a Knowledge Base one; anything else counts as none. Written + * in Markdown (format, includes/document_editors.php), markdown is what was + * written and content is made from it on saving; otherwise markdown is null. */ function kbArticleFields(array $in) { $title = trim((string) ($in['title'] ?? '')); @@ -296,6 +336,7 @@ function kbArticleFields(array $in) { } $category_id = kbCategoryId($in['category_id'] ?? 0); $review_months = intval($in['review_months'] ?? 0); + $markdown = kbMarkdownReady() && ($in['format'] ?? '') === 'markdown' ? str_replace(["\r\n", "\r"], "\n", (string) ($in['markdown'] ?? '')) : null; // Who can read it - clients need a way to be picked $visibility = isset(KB_VISIBILITY[$in['visibility'] ?? '']) ? (string) $in['visibility'] : 'agents'; @@ -315,7 +356,8 @@ function kbArticleFields(array $in) { 'category_id' => $category_id, 'review_months' => isset(KB_REVIEW_MONTHS[$review_months]) ? $review_months : 0, 'published' => !empty($in['published']), - 'content' => (string) ($in['content'] ?? ''), + 'content' => $markdown === null ? (string) ($in['content'] ?? '') : '', + 'markdown' => $markdown, 'visibility' => $visibility, 'all_clients' => $all_clients, 'client_tag_ids' => $client_tag_ids, @@ -372,7 +414,7 @@ function kbArticleDir($kb_article_id) { return dirname(__DIR__) . '/uploads/kb/' . intval($kb_article_id); } -/** Keep what an article says now as a version, before it changes. */ +/** Keep what an article says now as a version, before it changes - its Markdown too, when it is written in it. */ function kbKeepVersion(array $row) { global $mysqli; $by = intval($row['kb_article_updated_by']) ?: intval($row['kb_article_created_by']); @@ -380,7 +422,8 @@ function kbKeepVersion(array $row) { mysqli_query($mysqli, "INSERT INTO kb_article_versions SET kb_article_version_title = '" . escapeSql($row['kb_article_title']) . "', kb_article_version_summary = '" . escapeSql((string) $row['kb_article_summary']) . "', - kb_article_version_content = '" . mysqli_real_escape_string($mysqli, (string) $row['kb_article_content']) . "', + kb_article_version_content = '" . mysqli_real_escape_string($mysqli, (string) $row['kb_article_content']) . "' + " . kbMarkdownSet($row['kb_article_markdown'] ?? null, 'kb_article_version_markdown') . ", kb_article_version_created_at = '$at', kb_article_version_created_by = $by, kb_article_version_kb_article_id = " . intval($row['kb_article_id'])); @@ -389,11 +432,14 @@ function kbKeepVersion(array $row) { /* * Save an article - a new one ($row null), or a change to $row, which keeps * what it said before as a version when its words change. Images pasted into - * the editor go into its folder. Its id. + * the editor go into its folder. With markdown (a string - null or left out + * for rich text) its content is the HTML made from that, and pictures pasted + * into the Markdown go into its folder too. Its id. */ function kbArticleSave(array $f, $row = null) { global $mysqli, $session_user_id; $user_id = intval($session_user_id ?? 0); + $markdown = kbMarkdownReady() && isset($f['markdown']) ? str_replace(["\r\n", "\r"], "\n", (string) $f['markdown']) : null; if ($row === null) { mysqli_query($mysqli, "INSERT INTO kb_articles SET kb_article_title = '" . escapeSql($f['title']) . "', kb_article_content = '', kb_article_content_raw = '', kb_article_created_by = $user_id"); @@ -401,18 +447,26 @@ function kbArticleSave(array $f, $row = null) { $published_sql = $f['published'] ? 'NOW()' : 'NULL'; } else { $kb_article_id = intval($row['kb_article_id']); - if ($f['title'] !== $row['kb_article_title'] || $f['summary'] !== (string) $row['kb_article_summary'] || $f['content'] !== (string) $row['kb_article_content']) { + $was_markdown = $row['kb_article_markdown'] ?? null; + $words_changed = $markdown !== null ? $markdown !== $was_markdown : ($was_markdown !== null || $f['content'] !== (string) $row['kb_article_content']); + if ($words_changed || $f['title'] !== $row['kb_article_title'] || $f['summary'] !== (string) $row['kb_article_summary']) { kbKeepVersion($row); } // Published stays when it was - its date is when it first went out $published_sql = $f['published'] ? ($row['kb_article_published_at'] ? 'kb_article_published_at' : 'NOW()') : 'NULL'; } - $content = saveBase64Images($f['content'], dirname(__DIR__) . '/uploads/kb/', 'uploads/kb/', $kb_article_id); + if ($markdown !== null) { + $markdown = markdownSaveImages($markdown, $kb_article_id, 'kb'); + $content = markdownToHtml($markdown); + } else { + $content = saveBase64Images($f['content'], dirname(__DIR__) . '/uploads/kb/', 'uploads/kb/', $kb_article_id); + } mysqli_query($mysqli, "UPDATE kb_articles SET kb_article_title = '" . escapeSql($f['title']) . "', kb_article_summary = " . ($f['summary'] !== '' ? "'" . escapeSql($f['summary']) . "'" : 'NULL') . ", kb_article_content = '" . mysqli_real_escape_string($mysqli, $content) . "', - kb_article_content_raw = '" . escapeSql(kbArticleContentRaw($f['title'], $f['summary'], $content)) . "', + kb_article_content_raw = '" . escapeSql(kbArticleContentRaw($f['title'], $f['summary'], $content)) . "' + " . kbMarkdownSet($markdown) . ", kb_article_category_id = " . intval($f['category_id']) . ", kb_article_review_months = " . intval($f['review_months']) . ", kb_article_published_at = $published_sql, @@ -533,13 +587,14 @@ function kbArticleDelete($kb_article_id) { /* * A new draft article from a client's document - its name, description and - * content, with copies of its images. The caller has checked the document's - * client. The article's id, or 0. + * content, with copies of its images. A document written in Markdown makes an + * article written in Markdown. The caller has checked the document's client. + * The article's id, or 0. */ function kbArticleFromDocument($document_id) { global $mysqli; $document_id = intval($document_id); - $doc = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT document_name, document_description, document_content FROM documents WHERE document_id = $document_id")); + $doc = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT document_name, document_description, document_content, " . documentMarkdownSql() . " FROM documents WHERE document_id = $document_id")); if (!$doc) { return 0; } @@ -553,12 +608,15 @@ function kbArticleFromDocument($document_id) { ]); $from = dirname(__DIR__) . "/uploads/documents/$document_id"; $content = (string) $doc['document_content']; + $markdown = $doc['document_markdown'] ?? null; if (is_dir($from)) { copyDirectory($from, kbArticleDir($kb_article_id)); $content = str_replace("/uploads/documents/$document_id/", "/uploads/kb/$kb_article_id/", $content); + $markdown = $markdown === null ? null : str_replace("/uploads/documents/$document_id/", "/uploads/kb/$kb_article_id/", $markdown); } mysqli_query($mysqli, "UPDATE kb_articles SET kb_article_content = '" . mysqli_real_escape_string($mysqli, $content) . "', kb_article_content_raw = '" . escapeSql(kbArticleContentRaw($doc['document_name'], (string) $doc['document_description'], $content)) . "' + " . kbMarkdownSet($markdown) . " WHERE kb_article_id = $kb_article_id"); return $kb_article_id; } diff --git a/functions/markdown.php b/functions/markdown.php index 5c38082cb..4e3be559e 100644 --- a/functions/markdown.php +++ b/functions/markdown.php @@ -201,17 +201,19 @@ function htmlToMarkdown($html, &$notes = null) { /** * Pictures pasted into a Markdown document arrive as data - each is saved under * uploads/documents//, as a picture pasted into the rich text editor is, and the - * Markdown points at the file instead. + * Markdown points at the file instead. A Knowledge Base article's go under uploads/kb// + * ($folder 'kb'). */ -function markdownSaveImages($markdown, $document_id) { +function markdownSaveImages($markdown, $document_id, $folder = 'documents') { $document_id = intval($document_id); - return preg_replace_callback('#data:image/(png|jpe?g|gif|webp);base64,([A-Za-z0-9+/=\r\n]+)#i', function ($m) use ($document_id) { + $folder = $folder === 'kb' ? 'kb' : 'documents'; + return preg_replace_callback('#data:image/(png|jpe?g|gif|webp);base64,([A-Za-z0-9+/=\r\n]+)#i', function ($m) use ($document_id, $folder) { $binary = base64_decode(preg_replace('/\s+/', '', $m[2]), true); if ($binary === false || $binary === '' || @getimagesizefromstring($binary) === false) { return $m[0]; } $ext = strtolower($m[1]) === 'jpeg' ? 'jpg' : strtolower($m[1]); - $dir = dirname(__DIR__) . "/uploads/documents/$document_id"; + $dir = dirname(__DIR__) . "/uploads/$folder/$document_id"; if (!is_dir($dir) && !mkdir($dir, 0775, true) && !is_dir($dir)) { return $m[0]; } @@ -219,7 +221,7 @@ function markdownSaveImages($markdown, $document_id) { if (file_put_contents("$dir/$filename", $binary) === false) { return $m[0]; } - return "/uploads/documents/$document_id/$filename"; + return "/uploads/$folder/$document_id/$filename"; }, (string) $markdown); } diff --git a/includes/document_editors.php b/includes/document_editors.php index d4028223e..9368593a1 100644 --- a/includes/document_editors.php +++ b/includes/document_editors.php @@ -7,14 +7,19 @@ * switched either way as it is written (js/document_markdown.js). The form posts format, with * content or markdown (documentPostedContent()). * - * Used by New and Edit Document (agent/modals/document/document_form.php) and New Document in the - * client portal (client/document_add.php). Expects the escaped $document_content, and + * Used by New and Edit Document (agent/modals/document/document_form.php), New Document in the + * client portal (client/document_add.php) and New and Edit Article in the Knowledge Base + * (agent/modals/kb/kb_article_form.php). Expects the escaped $document_content, and * $document_markdown - what a Markdown document says, raw, or unset or null for rich text. With * $document_format_remember it starts in the way of writing used last in this browser; with * $document_editor_required something has to be written in it (js/portal.js checks). + * $document_editor_rich_class is the rich text editor's (tinymce-document unless set - an article + * keeps its own, tinymce), and $document_editor_markdown_ready whether Markdown can be saved + * where this posts (documentMarkdownReady() unless set - kbMarkdownReady() for an article). */ -$document_markdown_ready = documentMarkdownReady(); +$document_markdown_ready = isset($document_editor_markdown_ready) ? (bool) $document_editor_markdown_ready : documentMarkdownReady(); +$document_rich_class = in_array($document_editor_rich_class ?? '', ['tinymce', 'tinymce-document'], true) ? $document_editor_rich_class : 'tinymce-document'; $document_is_markdown = $document_markdown_ready && isset($document_markdown) && $document_markdown !== null; $document_format_uid = bin2hex(random_bytes(4)); $document_editor_required = !empty($document_editor_required); @@ -34,7 +39,7 @@ $document_editor_required = !empty($document_editor_required);
> - +