Skip to content

Knowledge Folder Soft Delete Developer Guide

Ed Mozley edited this page Dec 1, 2026 · 1 revision

Knowledge - folder soft delete, resizable panel and folder totals: Developer Guide

How a Knowledge folder can be deleted while articles from it sit in the Recycle Bin, what keeps an upgraded install working before Database Verification, and two smaller pieces from the same batch: the resizable folder panel and folder totals.

Built by @Dr4inder in PRs #492, #471 and #482; review: Knowledge batch - PR review. User page: Knowledge · Knowledge - folders and security. The access model these pieces sit on: Knowledge - folders and security: Developer Guide.


1. 📁 The files involved

Colour key: 🗄️ schema · ⚙️ engine · 🔌 API · 🖥️ UI · 🧪 tests

🎨 File What it does
🗄️ database/freeitsm.sql, includes/db_verify_schema.php knowledge_folders.is_deleted, after inherit_permissions
⚙️ includes/knowledge/visibility.php knowledgeFoldersHaveDeletedFlag(), knowledgeLiveFolderSql() - the readiness probe
⚙️ includes/services/knowledge_transfer.php KnowledgeTransferService::deleteFolder(), restoreFolderPath(); object() refuses a deleted folder; revision() ignores the flag
⚙️ includes/services/knowledge.php restoreArticle() now runs in a transaction and revives the folder path; resolveFolderId() refuses a deleted destination
🔌 api/knowledge/folders.php delete calls the service; non-GET requests run in a transaction with the response buffered
🔌 api/knowledge/permissions.php, api/v1/resources/knowledge_transfer.php live folders only
🖥️ assets/js/knowledge.js folderAction() moves you to the parent after deleting the folder you are in; restoreArticle() reloads folders; initSidebarResize(); folderTotal()
🖥️ knowledge/index.php, assets/css/knowledge.css #kbSidebarResize and its styles
🧪 tests/knowledge-folder-recycle-bin.php, tests/knowledge-folder-recycle-browser.php the service and the screen
🧪 tests/knowledge-sidebar-resize.php, tests/knowledge-folder-totals.php the panel and the totals, in Chrome

2. 🗑️ Why a deleted folder is kept

Before #492 a folder had to be empty of every article - and an article in the Recycle Bin still has its folder_id. So after deleting everything in a folder, it looked empty and Delete still said "That folder still has articles in it".

Deleting the row for real was not an option: the recycled articles would point at a folder that no longer exists, so Restore would have nowhere to put them, and the folder's knowledge_acl rows - which may be the only thing keeping a restricted article private - would go with it. So the folder stays as a row, flagged:

`inherit_permissions` TINYINT(1) NOT NULL DEFAULT 1,
`is_deleted`          TINYINT(1) NOT NULL DEFAULT 0, -- GH #492: hidden, but kept so recycled articles keep their path and access rules.

A deleted folder keeps its id, parent, ACL rows and owner. It is left out of every folder list (UI, REST, Permission exceptions), cannot be opened, renamed, moved into or given permissions, and is no longer a valid destination for an article.


3. ⚙️ Deleting a folder

KnowledgeTransferService::deleteFolder() - one transaction, with locking reads so a writer that committed while this request waited for the lock is seen:

self::transaction($conn, static function () use ($conn, $ctx, $id) {
    self::object($conn, $ctx, 'folder', $id, true);
    // Locking reads see a writer that committed while we waited for the folder lock.
    $st = $conn->prepare('SELECT id FROM knowledge_articles WHERE folder_id = ? AND (is_archived = 0 OR is_archived IS NULL) LIMIT 1 FOR UPDATE');
    ...
    $st = $conn->prepare('SELECT id FROM knowledge_folders WHERE parent_id = ? AND is_deleted = 0 LIMIT 1 FOR UPDATE');
    ...
    $conn->prepare('UPDATE knowledge_folders SET is_deleted = 1, modified_datetime = UTC_TIMESTAMP() WHERE id = ?')->execute([$id]);
    $conn->prepare('DELETE FROM knowledge_shortcuts WHERE folder_id = ?')->execute([$id]);
    knowledgeAuditLog($conn, 'folder', $id, 'delete', $ctx->actorId, null);
});
  • What still blocks it: any article not in the Recycle Bin - including drafts and articles this analyst cannot read (the count is not filtered by visibility, so a folder never looks empty to someone who cannot see what is in it) - and any live subfolder. A deleted subfolder does not block it.
  • Shortcuts in the folder go. A shortcut is only a pointer, and a pointer in a folder nobody can open is clutter. The articles they point at are untouched.
  • ACL rows stay. That is the point.

api/knowledge/folders.php now runs every non-GET request in a transaction and buffers the output, so a request that fails part-way rolls back and answers with the error only:

ob_start();
try {
    $conn = connectToDatabase();
    if ($method !== 'GET') $conn->beginTransaction();
    switch ($action) { ... }
    if ($conn->inTransaction()) $conn->commit();
    $response = ob_get_clean();
    echo $response;
} catch (ServiceError $e) {
    ob_end_clean();
    if (isset($conn) && $conn->inTransaction()) $conn->rollBack();
    ...

requireFolderAccess() there throws ServiceError instead of echoing and exiting, so it rolls back too.


4. ♻️ Restoring an article revives its folder path

KnowledgeService::restoreArticle() locks the article, checks access, then calls restoreFolderPath() before clearing is_archived - all in one transaction:

public static function restoreFolderPath(PDO $conn, ActorContext $ctx, ?int $folderId): void
{
    // Before Database Verification no folder can have been deleted, so there is nothing to revive.
    if (!knowledgeFoldersHaveDeletedFlag($conn)) return;
    $seen = [];
    while ($folderId !== null) {
        if (isset($seen[$folderId])) throw new ServiceError('conflict', 'invalid_folder_path', ...);
        $seen[$folderId] = true;
        $st = $conn->prepare('SELECT parent_id, is_deleted FROM knowledge_folders WHERE id = ? FOR UPDATE');
        ...
        if ((int)$folder['is_deleted']) {
            $conn->prepare('UPDATE knowledge_folders SET is_deleted = 0, modified_datetime = UTC_TIMESTAMP() WHERE id = ?')->execute([$folderId]);
            knowledgeAuditLog($conn, 'folder', $folderId, 'restore', $ctx->actorId, null);
        }
        $folderId = $folder['parent_id'] === null ? null : (int)$folder['parent_id'];
    }
}

It walks up to the root, reviving every deleted ancestor, so the article comes back exactly where it was with the same inherited permissions. $seen stops a corrupt parent loop; a missing ancestor row refuses the restore rather than putting the article somewhere else.

revision() unsets is_deleted before hashing a folder, so adding the column does not change every folder's revision token on upgrade (a migration script holding an expected_revision would otherwise get a conflict for nothing).


5. 🔴 The readiness probe

The column arrives with Database Verification; the code arrives with the upgrade, before anyone has run it. As merged, #492 wrote is_deleted = 0 straight into the folder list, so on an upgraded-but-not-verified install every Knowledge folder request failed. Every "live folders only" clause now goes through one helper:

function knowledgeFoldersHaveDeletedFlag(PDO $conn): bool
{
    static $has = null;
    if ($has !== null) return $has;
    try {
        $conn->query('SELECT is_deleted FROM knowledge_folders LIMIT 0');
        $has = true;
    } catch (PDOException $e) {
        $has = false;
    }
    return $has;
}

/** " AND <alias>.is_deleted = 0", or nothing before Database Verification has added the column. */
function knowledgeLiveFolderSql(PDO $conn, string $alias = ''): string
Where Use
api/knowledge/folders.php handleList, requireFolderAccess, handleExceptions (alias f)
api/knowledge/permissions.php requireObject() for a folder
api/v1/resources/knowledge_transfer.php GET /knowledge/folders
includes/services/knowledge.php resolveFolderId() - a destination for an article
includes/services/knowledge_transfer.php object() reads $row['is_deleted'] ?? 0 (its SELECT * has no column yet)

Before verification, deleteFolder() refuses with "Folders cannot be deleted until an administrator runs Database Verification", and restoreFolderPath() returns at once - no folder can have been deleted yet.

TRAP: a new query on knowledge_folders that should skip deleted folders uses knowledgeLiveFolderSql(), never a bare is_deleted = 0. Listed in Code traps.

Known: the count in includes/analyst_lifecycle.php (folders an analyst owns) includes deleted folders. It is a reassignment hint, so the overcount is harmless.


6. ↔️ The resizable folder panel (#471)

initSidebarResize() in knowledge.js wires #kbSidebarResize, a role="separator" with tabindex="0" between the panel and the main pane - the same pattern as the ticket table's column dividers: pointer capture for the drag, Left/Right in 24px steps, Home/End for the limits, aria-valuenow/min/max kept up to date.

  • Limits: 200px to min(560, half the container). A narrower window clamps the shown width without overwriting the preference, so widening the window brings it back.
  • Storage: localStorage['knowledge_sidebar_width'], per browser. Saved once when a drag ends and on each key press - not on every pointermove (the PR wrote it dozens of times per drag; changed when merging):
const save = () => {
    try { localStorage.setItem(storageKey, String(preferredWidth)); } catch (e) { /* kept for this visit */ }
};
const stop = () => {
    if (!drag) return;
    const id = drag.id;
    drag = null;
    save();
    ...
  • Below 769px the splitter does nothing; the phone layout is untouched.
  • Hover mode: the "open on hover" panel now also stays open on :focus-within, so tabbing into the folder list or typing in the search box does not collapse it under you. That is a small behaviour change, kept on purpose.

tests/knowledge-sidebar-resize.php drives the real splitter in Chrome; it throws if initSidebarResize() or #kbSidebarResize cannot be found, so a rename fails loudly instead of testing an empty page.


7. 🔢 Folder totals (#482)

function folderTotal(folder) {
    return folderChildren(folder.id).reduce((n, child) => n + folderTotal(child), folder.article_count);
}

It adds up kbFolders, the list api/knowledge/folders.php has already filtered to the folders this analyst may see - so a total never counts a folder they cannot open, and the endpoint is unchanged. Used by the sidebar tree, the Tree layout, folder cards and the Details folder row (where #483 moved the count beside the name, unbolded).

⚠️ The Knowledge tests pull functions out of knowledge.js by regex into a test page. A renderer that starts calling a new helper (as these did with folderTotal) breaks every test whose function list lacks it - add it to the list.


8. 🧪 Testing this

Test What it proves
tests/knowledge-folder-recycle-bin.php delete blocked by live articles (also unreadable ones and drafts) and live subfolders; allowed with only recycled articles; a deleted ancestor still protects the article; a denied reader cannot restore; restore revives the whole path with identity and permissions intact; a deleted folder is gone from the list and refused as a REST target, a parent and an article destination; revision tokens unchanged by the column; everything rolled back
tests/knowledge-folder-recycle-browser.php deleting the folder you are in moves you to its parent (or the root) and updates the URL; a refused delete leaves the screen alone; restore refreshes the tree, tags and bin
tests/knowledge-sidebar-resize.php drag, keys, limits, saved width, narrow-window clamp
tests/knowledge-folder-totals.php totals in every view, unreadable folders not counted

The browser tests need a test install (FREEITSM_TEST_URL); never run them against real data.


Related pages

FreeITSM

Getting Started

Modules

Multi-tenancy (planned)

Responses to feedback

Blue sky thinking

Bugs resolved

Pull requests

Links

Clone this wiki locally