Knowledge Versions Developer Guide - edmozley/freeitsm GitHub Wiki
5.17.0. Raised by @Dr4inder in #465. The user's view: Knowledge - ยง Versions (5.17.0).
Save as new version has kept old versions of an article in knowledge_article_versions for a long time, but only the REST API could read them. 5.17.0 adds the screen: Versions in an article's โฏ menu lists them, opens one, compares any two word by word, and puts one back with Restore. A setting, Knowledge โ Settings โ Versions โ Keep a version, can make every save that changes the title or text keep a version. No schema change - the table already existed; the setting is a system_settings row read as off when absent.
| File | What |
|---|---|
includes/services/knowledge.php |
autoVersionOn(), listVersions(), getVersion(), restoreVersion(); the auto-version rule in saveArticleData()
|
api/knowledge/versions.php |
New. The screen's endpoint: list, one version, restore |
includes/knowledge/audit.php |
New audit action version_restore
|
knowledge/index.php |
The Versions item in the โฏ menu (#kbArticleVersionsBtn) and the window (#kbVersionsModal) |
assets/js/knowledge.js (v91) |
openArticleVersions(), kbVersionsSelect(), kbVersionsShow(), kbVersionText(), kbDiffWords(), kbDiff(), kbVersionsRestore()
|
assets/css/knowledge.css (v37) |
.kb-versions-* (the window), .kb-diff-* (added and removed words) |
knowledge/settings/manifest.php, knowledge/settings/index.php
|
The Versions tab (KNOWLEDGE_MANAGE, setting key knowledge_auto_version) |
lang/en/knowledge.php |
knowledge.versions.*, knowledge.settings.versions_*, audit.action_version_restore (Earlier version restored) |
api/v1/resources/knowledge.php |
Unchanged - the REST list and get of versions were already there |
tests/knowledge-versions.php |
New. See Tests |
CREATE TABLE IF NOT EXISTS `knowledge_article_versions` (
`id` INT NOT NULL AUTO_INCREMENT,
`article_id` INT NOT NULL,
`version` INT NOT NULL,
`title` VARCHAR(255) NOT NULL,
`body` LONGTEXT NULL,
`saved_by_id` INT NOT NULL,
`saved_datetime` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`id`),
CONSTRAINT `fk_kav_article` FOREIGN KEY (`article_id`) REFERENCES `knowledge_articles` (`id`),
CONSTRAINT `fk_kav_saved_by` FOREIGN KEY (`saved_by_id`) REFERENCES `analysts` (`id`)
) ...A versioned save copies the article row as it is before the save into this table, under the number it has then, and bumps the article's number:
if ($saveAsVersion) {
$conn->prepare(
"INSERT INTO knowledge_article_versions (article_id, version, title, body, saved_by_id, saved_datetime)
SELECT id, version, title, body, ?, UTC_TIMESTAMP() FROM knowledge_articles WHERE id = ?"
)->execute([$ctx->actorId, $articleId]);
$updates[] = 'version = version + 1';
}-
The article row is always the current version.
knowledge_articles.versionis its number; the table holds only the earlier ones. An article at version 3 has rows for 1 and 2. -
TRAP:
saved_by_idis the person who made the NEXT version. The row for version 2 records who saved the change that replaced it, and when. It is shown beside the version in the list as "who saved it and when" - which is when that text stopped being current. - There is no unique key on
(article_id, version), sogetVersion()takes the newest row for a number (ORDER BY id DESC LIMIT 1).
/** GH #465: Knowledge -> Settings -> Versions - keep a version on every save that changes the text. */
public static function autoVersionOn(PDO $conn): bool
{
...
return $st->fetchColumn() === '1';In saveArticleData(), on an update:
$saveAsVersion = !empty($in['save_as_version']);
// GH #465: Knowledge -> Settings -> Versions can keep a version on EVERY save that
// changes the title or the text. Off by default - only "Save as new version" keeps
// one, as before. Needs a person to file it under (saved_by_id is an analyst).
if (!$saveAsVersion && $ctx->actorId > 0 && self::autoVersionOn($conn)
&& ($newTitle !== (string)$current['title'] || $newBody !== (string)$current['body'])) {
$saveAsVersion = true;
}-
Off by default (no row, or any value but
'1'): only Save as new version keeps one, as before 5.17.0. - Only when the title or the body changes. A save that changes the owner, review date, folder, tags or audience keeps nothing, so the list is not filled with copies of the same text.
-
TRAP: only with an analyst actor (
$ctx->actorId > 0).saved_by_idisNOT NULLand a foreign key toanalysts; a system or workflow save (actor 0) would make the insert fail and take the whole save down with it. Such saves never auto-version. - The comparison is on the stored HTML, so a change of formatting alone does keep a version, even though the comparison on screen (below) shows no difference.
The setting is saved by the Versions tab through api/settings/save_system_settings.php. The tab is in the manifest with cap => KNOWLEDGE_MANAGE and setting_keys => ['knowledge_auto_version'], like the Display tab.
$out = [[
'version' => (int)($cur['version'] ?? 1),
'title' => (string)$cur['title'],
'is_current' => true,
'saved_at' => $cur['modified_datetime'] ?? null,
'saved_by' => null, // the article row does not record who saved it last
]];
foreach ($st->fetchAll(PDO::FETCH_ASSOC) as $v) {
$out[] = ['version' => (int)$v['version'], 'title' => (string)$v['title'], 'is_current' => false,
'saved_at' => $v['saved_datetime'], 'saved_by' => $v['saved_by']];
}The current text comes first (is_current), then the saved ones newest first. getVersion() answers the current version from the article row and any other from the table; a number that is neither is not_found.
Who may see them: both start with loadArticleRow() (404 if gone) and assertCanAccessArticle() - the company check and knowledgeCanRead(), the same check that guards a save. Someone who cannot read the article gets Article not found, not a "forbidden" that would say it exists. The endpoint itself needs only a session and the Knowledge module (requireModuleAccessJson('knowledge')), exactly like api/knowledge/knowledge_save.php.
-
TRAP: never offer versions more widely than the article. An old version can hold text that was taken out on purpose - a password pasted by mistake, a name that should not be there. Anyone who may read and save the article may see its versions; nobody else. That is why the Versions item in the โฏ menu is not hidden like History and Permissions (which need
kbCanManagePerms): the people who can open the menu on an article are the people who can save it.
public static function restoreVersion(PDO $conn, ActorContext $ctx, int $articleId, int $version): array
{
$v = self::getVersion($conn, $ctx, $articleId, $version);
if ($v['is_current']) throw new ServiceError('validation', 'invalid_field', 'That is already the current version.');
$res = self::saveArticle($conn, $ctx, ['id' => $articleId, 'title' => $v['title'], 'body_html' => $v['body_html'], 'save_as_version' => true]);
require_once __DIR__ . '/../knowledge/audit.php';
knowledgeAuditLog($conn, 'article', $articleId, 'version_restore', $ctx->actorId > 0 ? $ctx->actorId : null, ['version' => $version]);
$res['version'] = (int)$conn->query('SELECT version FROM knowledge_articles WHERE id = ' . (int)$articleId)->fetchColumn();
return $res;
}A restore is an ordinary save with save_as_version, so it gets everything a save gets: the FOR UPDATE lock on the article row, the embedded-picture size check (assertEmbeddedWithinLimit()), the access check again inside the transaction, the refusal for an article in the recycle bin, the edit audit row, the search re-index, the embedding and the knowledge.updated workflow event. Nothing about saving had to be written twice.
-
Nothing is ever lost.
save_as_versioncopies the current text into the table first, so restoring version 1 of an article at version 2 leaves version 2 in the list and makes the article version 3, holding version 1's text. A restore can itself be undone. -
Only the title and the text come back. The save sends
titleandbody_htmlalone, and an update only changes the keys it is sent - owner, review date, folder, tags, audience and access stay as they are now. A version row does not hold them anyway. -
The audit row -
version_restore, with{"version": N}(the version put back), shown in the article's History as Earlier version restored. It is written aftersaveArticle()has committed, next to the ordinaryeditrow the save writes.KNOWLEDGE_AUDIT_ACTIONSlists it; an action missing from that list is refused and logged, not stored. - No
expected_revisionis sent, so a restore is not refused when someone else saved in between - and loses nothing either, because their text is what gets kept as a version first.
| Request | Answer |
|---|---|
GET ?article_id=N |
{success, versions: [...]} - listVersions()
|
GET ?article_id=N&version=V |
{success, version: {version, title, body_html, is_current}} - getVersion()
|
POST {action: 'restore', article_id, version} |
{success, article_id, version} - the article's new version number |
A thin adapter: ActorContext::fromSession(), csrfRequireWriteMethod() on the POST, a ServiceError message passed back as error. It loads includes/encryption.php because a restore is a save and the embedding step needs decryptValue().
GET /knowledge/articles/{id}/versions and GET /knowledge/articles/{id}/versions/{version} (apiKnowledgeVersionsList(), apiKnowledgeVersionsGet()) existed before 5.17.0 and are unchanged. They read the table directly, so they differ from the screen's endpoint:
- the list holds only the saved versions - the current one is the article itself (
GET /knowledge/articles/{id}); - asking for the current version's number is a 404;
-
saved_byis{id, name}andsaved_atan ISO date.
There is no REST restore endpoint yet. A script can do the same thing by reading a version and saving its title and body_html with save_as_version: true, but it will not write the version_restore audit row.
openArticleVersions() resets kbVersions = { list: [], selected: null, cache: {} }, opens #kbVersionsModal and fetches the list. It selects the newest saved version when there is one, so the window opens on the usual question - what changed since then:
kbVersionsSelect(kbVersions.list.length > 1 ? kbVersions.list[1].version : kbVersions.list[0].version);| Function | Does |
|---|---|
kbVersionsRenderList() |
the list on the left; with only the current version, it and No earlier versions yet |
kbVersionsSelect(version) |
marks the row, fills Compare with with every other version, hides Restore on the current one. A saved version is compared with the current text; the current one with the version before it |
kbVersionsLoad(version) |
fetches one version, once - kept in kbVersions.cache
|
kbVersionsShow() |
Compare with set to Nothing - show this version: the version as it reads, through kbSafeBody(). Otherwise the comparison |
kbVersionsRestore() |
asks with kbConfirm(), posts the restore, closes the window and reopens the article with viewArticle()
|
In a comparison the older version is always the left-hand side of the difference, whichever was selected, so green always means "added later":
const [older, newer] = Number(other) < kbVersions.selected ? [b, a] : [a, b];
const titleDiff = kbDiffWords(older.title, newer.title);
const bodyDiff = kbDiffWords(kbVersionText(older.body_html), kbVersionText(newer.body_html));function kbVersionText(html) {
const div = document.createElement('div');
div.innerHTML = kbSafeBody(html || '');
div.querySelectorAll('img').forEach(img => img.replaceWith(document.createTextNode(' [' + (img.getAttribute('alt') || window.t('knowledge.versions.picture')) + '] ')));
div.querySelectorAll('p, div, li, tr, h1, h2, h3, h4, h5, h6, pre, blockquote, br').forEach(el => el.after(document.createTextNode('\n')));
return (div.textContent || '').replace(/[ \t ]+/g, ' ').replace(/ *\n */g, '\n').replace(/\n{3,}/g, '\n\n').trim();
}One line per paragraph, heading, list item or table row; a picture becomes its alt text in brackets. What #465 asked for is what the text says, so bold, a colour or a table border changing shows nothing - and when only that changed, the window says The text is the same in both - only formatting or pictures changed.
-
TRAP: sanitise before
innerHTML, even on a detacheddiv. An<img onerror>in an old version fires as soon as the browser parses it, attached to the page or not.kbSafeBody()runs the body throughsafeHtmlFragment()first (and fails closed to escaped text). An old version is stored HTML like the current text and gets the same treatment. - The output goes into
<div class="kb-diff">withwhite-space: pre-wrap, so the line breaks of the plain text are the layout.
kbDiffWords(a, b) splits both texts into words and the runs of whitespace between them (/\s+|[^\s]+/g), runs kbDiff() on the two token lists, escapes every token and wraps added runs in <ins class="kb-diff-add"> and removed ones in <del class="kb-diff-del">. It returns { html, changed }.
kbDiff(a, b) is Myers' O(ND) algorithm: it walks the diagonals k for each edit distance d, keeping the furthest x reached on each in a Map, and stores a copy of that map per d in trace; once both ends are reached it walks trace backwards to recover the edits, then joins neighbours with the same operation so the markup is runs of words, not single tokens. It returns [[op, text]] with op -1 removed, 0 the same, +1 added.
Two bail-outs keep a big comparison from freezing the browser:
// Too different to be worth the work: show it all as replaced.
if (max > 40000) return [[-1, a.join('')], [1, b.join('')]];
...
if (d > 3000) return [[-1, a.join('')], [1, b.join('')]]; // a rewrite, not an edit-
More than 40,000 tokens between the two (
n + m- words and the spaces between them count separately, so about 10,000 words in each text): no comparison at all - the whole old text struck through, the whole new text added. -
More than 3,000 edits: the same. Myers is fast when the texts are close and slow when they are not, and the
tracegrows with every step; past 3,000 differences it is a rewrite, and a word-by-word list of it helps nobody.
The colours are theme tokens - --success-bg / --success-text and --danger-bg / --danger-text - and <del> keeps its strike-through, so a change still reads without colour. Below 768px the list stacks above the version (.kb-versions-layout { flex-direction: column; }).
tests/knowledge-versions.php - 10 checks against a test database (FREEITSM_TEST_DATABASE), through KnowledgeService as an administrator, with processing => 'suppress' so no embedding or workflow runs. It makes a ZZ article and deletes it, and puts knowledge_auto_version back as it was:
- setting off: only Save as new version kept one - the list is the current (2) and one saved (1)
- version 1 is the text as it was before that save; the current version is the article itself
- restore: version 1's title and text are back, as version 3, and the text it replaced was kept first as version 2
- the restore is in the article's audit with the version number
- restoring the current version is refused; a version that does not exist is
not_found - setting on: an ordinary save that changes the text keeps a version; a save that changes neither title nor text does not
The comparison (kbVersionText(), kbDiff()) has no test of its own.
- Knowledge - the user's view
- REST API: Knowledge - the versions endpoints
-
Knowledge - folders and security: Developer Guide -
knowledgeCanRead()andassertCanAccessArticle() - Knowledge - reading and lists: Developer Guide