Skip to content

Knowledge In Tickets Developer Guide

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

Knowledge in tickets - Developer Guide

Knowledge articles in ticket replies and notes, and the record of which articles a ticket used - after 5.19.0, asked for in #467 by @Dr4inder. User side: Tickets - Knowledge articles in replies and notes, Knowledge - Used in tickets.

An analyst used to open Knowledge in another tab, copy the analyst address and paste it into a reply - an address the requester cannot open. And nothing recorded which articles solved which tickets. Now the reply editor browses Knowledge as the requester sees it, a note can insert an article, and each article a ticket used is recorded and counted on the article.


1. πŸ“ The files

File Role
includes/knowledge/ticket_articles.php Every rule: ticketArticleIdsInHtml(), ticketArticlesRecord(), ticketArticlesUnlink(), ticketArticlesFor(), ticketArticleTickets(), ticketRequesterKnowledgeTenant(), ticketArticleSearch()
api/tickets/ticket_articles.php The ticket side: list, search (for=requester or analyst), link and unlink by hand
api/knowledge/article_tickets.php The article side: total and the scoped list
api/tickets/send_email.php, api/tickets/save_note.php Record what a sent reply / saved note links
assets/js/kb-article-link-picker.js The TinyMCE article browser (#450), now with an optional searchUrl
assets/js/inbox.js Reply editor file_picker_callback; loadTicketArticles(), renderTicketArticles(), openLinkArticlePicker(), removeTicketArticle(); the note's toggleNoteArticlePicker(), searchNoteArticles(), insertNoteArticle()
assets/js/knowledge.js kbLoadTickets() - Used in N tickets under an article
tickets/index.php The note modal's Article row; the picker's strings (only knowledge.editor.link_picker_*, not the whole namespace)
Purges permanently_delete_ticket.php, empty_trash.php, the D002 debug tool, KnowledgeService::purgeArticle(), knowledge_archive.php, REST knowledge purge
Test tests/ticket-knowledge-articles.php (12)

2. πŸ—„οΈ The table

CREATE TABLE IF NOT EXISTS `ticket_knowledge_articles` (
    `id`               INT NOT NULL AUTO_INCREMENT,
    `ticket_id`        INT NOT NULL,
    `article_id`       INT NOT NULL,
    `source`           VARCHAR(10) NOT NULL DEFAULT 'manual',
    `created_by_id`    INT NULL,
    `created_datetime` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
    PRIMARY KEY (`id`),
    UNIQUE KEY `uq_ticket_knowledge_article` (`ticket_id`, `article_id`),
    KEY `idx_ticket_knowledge_articles_article` (`article_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

Once per ticket and article; source keeps the first way it arrived (a later link of the same pair is INSERT IGNOREd). No foreign keys, like the other link tables; the purges in Β§1 delete the rows, and every read joins both tables, so an orphan could never show.

3. πŸ”Ž Recording what was sent, not what was picked

The obvious design - remember the ids the picker inserted and post them with the reply - would record an article the analyst inserted and then deleted, and miss one pasted by hand. So the server reads the body it actually sent:

function ticketArticleIdsInHtml(string $body): array
{
    $ids = [];
    $body = html_entity_decode($body, ENT_QUOTES | ENT_HTML5, 'UTF-8');   // & in an href
    if (preg_match_all('~help-centre\.php\?(?:[^"\'\s<>]*&)?id=(\d+)~i', $body, $m)) foreach ($m[1] as $id) $ids[] = (int)$id;
    if (preg_match_all('~knowledge/(?:index\.php)?\?(?:[^"\'\s<>]*&)?article=(\d+)~i', $body, $m)) foreach ($m[1] as $id) $ids[] = (int)$id;
    return array_values(array_unique(array_filter($ids, fn($i) => $i > 0)));
}

⚠️ TRAP: match the article pages only. A bare ?id=N would catch every ticket, task and asset link in a body. html_entity_decode first, or an href with &amp;article= is missed. Any host counts: the address is what was sent, and a moved install's old links still name the article.

It runs after the reply has gone and been saved:

    // GH #467: the Knowledge articles this reply links to are recorded on the ticket.
    // Read from what was sent, so an article taken out before sending does not count.
    if ($ticketId) {
        require_once __DIR__ . '/../../includes/knowledge/ticket_articles.php';
        ticketArticlesRecord($conn, (int)$ticketId, ticketArticleIdsInHtml((string)$body), 'reply', (int)$_SESSION['analyst_id']);
    }

ticketArticlesRecord() never throws - a failure is logged, and must not fail a reply that has already been sent. It ignores ids that are not articles.

4. πŸ‘€ The requester's view, in the reply

A reply is read by the requester, so the picker must not offer what they cannot open. The company is the requester's own (users.tenant_id), else the ticket's:

function ticketRequesterKnowledgeTenant(PDO $conn, int $ticketId): ?int
{
    $s = $conn->prepare("SELECT user_id, tenant_id FROM tickets WHERE id = ?");
    $s->execute([$ticketId]);
    $t = $s->fetch(PDO::FETCH_ASSOC);
    if (!$t) return null;
    if ($t['user_id']) {
        $u = portalUserTenantId($conn, (int)$t['user_id']);
        if ($u !== null) return $u;
    }
    return $t['tenant_id'] !== null ? (int)$t['tenant_id'] : null;
}

and the search uses the portal's own scope for that company - the same function the Help Centre uses, so the two cannot disagree:

    if ($for === 'requester') {
        [$where, $params] = portalKnowledgeScope($conn, ticketRequesterKnowledgeTenant($conn, $ticketId), 'a');
    } else {
        // knowledgeVisibilitySql gives " AND ..." (or nothing); the portal scope gives a bare fragment.
        [$vis, $params] = knowledgeVisibilitySql($conn, KnowledgeViewer::forAnalyst($conn, $analystId), 'a', ['lifecycle' => 'unarchived']);
        $where = '1=1' . $vis;
    }

⚠️ portalKnowledgeScope() returns a bare fragment (no leading AND); knowledgeVisibilitySql() returns " AND ..." or nothing. Hence the '1=1' . on the analyst branch.

Both kinds of address are absolute (publicAbsoluteUrl()): a reply is read in a mail client, a note is plain text someone may copy. The editor side only has to choose the search:

        ...(ticketModuleOn('knowledge') && typeof kbOpenArticleLinkPicker === 'function' ? {
            file_picker_types: 'file',
            file_picker_callback: (callback, value, meta) => {
                const tid = currentEmail && currentEmail.ticket_id;
                kbOpenArticleLinkPicker(emailEditor, callback, meta, tid ? {
                    searchUrl: q => API_BASE + 'ticket_articles.php?pick=1&for=requester&ticket_id=' + encodeURIComponent(tid) + '&q=' + encodeURIComponent(q),
                    href: article => article.url
                } : {
                    api: '../api/knowledge/',
                    href: article => new URL('../knowledge/?article=' + article.id, location.href).href
                });
            }
        } : {}),

On a ticket the picker lists the requester's articles; in a new email with no ticket it falls back to Knowledge's own list. The note has no TinyMCE, so its Article button has a small search of its own; it asks for requester when Share with the requester is ticked and analyst otherwise, and puts Title - address back where the caret was (the range is saved when the box opens, because typing in the search box moves the focus).

5. πŸ” Reading it back

  • On the ticket: a title only for an article the analyst may read (knowledgeCanRead); otherwise An article you cannot open, with no link. Linking by hand checks the same.
  • On the article: the total counts every ticket outside the bin; the list is only the tickets the reader may open - departments are access:
    require_once __DIR__ . '/../ticket_department_scope.php';
    [$scope, $sp] = ticketScopeFilter($conn, $analystId, 't');
    $s = $conn->prepare("SELECT t.id, t.ticket_number, t.subject, ts.name AS status, l.source, l.created_datetime
                           FROM ticket_knowledge_articles l
                           JOIN tickets t ON t.id = l.ticket_id
                      LEFT JOIN ticket_statuses ts ON ts.id = t.status_id
                          WHERE l.article_id = ? AND t.deleted_datetime IS NULL" . $scope . "
                          ORDER BY l.created_datetime DESC, l.id DESC
                          LIMIT " . (int)$limit);
    $s->execute(array_merge([$articleId], $sp));
  • Every endpoint needs Tickets and/or Knowledge (requireModuleAccessJson) and the ticket check (analystCanAccessTicket).

6. 🧭 Decisions

Decision Why Who
Reply picker = what the requester can read, full portal address the request's acceptance criteria; an internal article must never reach a customer Requester
Note picker follows Share with the requester a shared note is read in the portal, so it needs the portal address and the requester's view Me
Record from the sent body, not the picker counts pasted links, ignores removed ones Me
Total counts every ticket; the list is scoped "used in 40 tickets" is a number about the article, not about any one ticket Requester (suggested), me
Gap analysis left as it is optional in the request; needs its own design (what "covered" means when the article did not actually solve it) Me - offered as a follow-up
No setting nothing changes until someone uses the picker or links an article Me

7. βœ… Tests

tests/ticket-knowledge-articles.php - see Developer tests: Knowledge.

FreeITSM

Getting Started

Modules

Multi-tenancy (planned)

Responses to feedback

Blue sky thinking

Bugs resolved

Pull requests

Links

Clone this wiki locally