Skip to content

Network Mapper Knowledge and Export Developer Guide

Ed Mozley edited this page Nov 24, 2026 · 2 revisions

Network Mapper - Knowledge links and Export: Developer Guide

GH #433 Β· November 2026 Β· commits 46932b933 (Knowledge articles on diagrams, changelog #3168) and 16ec16c0a (PNG / PDF to Download or Save to Files, changelog #3169)

The basics of the editor (the window.NM module, the three original tables, whole-diagram saves, versions) are on Network Mapper - Developer Guide. This page does not repeat them. Shapes, pages, layers and groups are on Network Mapper - Shapes and Layers - Developer Guide, and the icon libraries and My images on Network Mapper - Icon Libraries - Developer Guide.

In plain words

Knowledge links. A node or a shape on a diagram can point at ONE Knowledge article (the runbook for that switch). A small book in its corner opens the article, and in Present a plain click on the item does the same. The diagram as a whole can also have a list of related articles (the Articles button on the toolbar), and every article lists back the diagrams that use it, under Network diagrams when it is read in Knowledge. The one rule that shapes all the code: a diagram never shows an article's title to someone Knowledge would not show the article to. An article the viewer cannot read is still drawn, as "An article you don't have access to", with its id and no title, so nobody quietly deletes a colleague's link they cannot see.

Export. PNG and PDF used to download straight away. Now they open a two-item menu: Download, or Save to Files. Save to Files reuses the shared dialog from Save to Files - Developer Guide, which learned a new source: a file the page has just made in the browser (SaveToFiles.open({ blob, name })). The server takes only export formats (PNG, JPEG, PDF, CSV, XLSX), checks the bytes match the name, and then saves exactly as any other save into Files: Files module, Upload on the folder, the same name-clash choices as an upload. Any other page with an export can offer the same thing in about five lines (see Adding Save to Files to another page's export).

Files

Key: πŸ—„οΈ schema Β· πŸ“– read Β· ✏️ write Β· πŸ”— cross-module Β· πŸ–₯️ UI Β· πŸ”’ security Β· πŸ§ͺ test

Knowledge articles on diagrams

🎨 File What it does
πŸ—„οΈ database/freeitsm.sql article_id (+ index + FK ON DELETE SET NULL) on network_diagram_nodes and network_diagram_shapes; the new network_diagram_articles table
πŸ—„οΈ includes/db_verify_schema.php The same columns and table for DB Verify to add
πŸ—„οΈ includes/db_verify_indexes.php ix_net_node_article, ix_net_shape_article, uq_net_diag_article, ix_net_diag_article (GENERATED - never hand-edited)
πŸ—„οΈ api/system/db_verify.php The five new foreign keys, and the orphan clean-up that runs before they are added
πŸ“–βœοΈπŸ”’ includes/services/network_articles.php NetworkArticleService - every rule about which article ids may be read, shown, saved, added and listed back
✏️ includes/services/network_mapper.php createDiagram() / saveDiagram() call allowedForSave() before the transaction; replaceContents() / replaceShapes() keep only allowed ids; createVersion() copies article_id and calls copyRelated()
✏️ api/network-mapper/save_diagram.php Passes each node's article_id through to the service
πŸ“– api/network-mapper/get_diagram.php Returns article_id on every node and shape, plus articles (related, titles) and can_read_knowledge
πŸ“–βœοΈ api/network-mapper/articles.php GET ?q= (picker), GET ?article_id= (the Knowledge side), POST {action: add / remove} (related list)
πŸ”’ includes/knowledge/visibility.php knowledgeVisibilitySql(), KnowledgeViewer::forAnalyst() - Knowledge's own read rule, used for every title
πŸ–₯️ assets/js/network-mapper.js (v=19) kbRelated, kbTitles, canReadKb, addKbMark(), renderKbField(), openArticlePicker(), the Articles dropdown, Present-mode click, right-click items, article_id in the save payload
πŸ–₯️ network-mapper/diagram.php The Articles toolbar button and dropdown, the Article line in the node panel, the #articlePickerModal, the .nm-kb-* CSS
πŸ–₯️ network-mapper/help.php One more help paragraph
πŸ”— assets/js/knowledge.js (v=75) kbMountDiagrams() - the "Network diagrams" card under an article
πŸ”— knowledge/index.php window.KB_SHOW_DIAGRAMS - true only for someone with the Network Mapper module
πŸ”— includes/analyst_lifecycle.php network_diagram_articles.created_by_analyst_id registered as history
πŸ”— includes/feature_bingo/cards/network-mapper.php Card network-mapper.articles - "Diagrams that link to Knowledge"
πŸ–₯️ lang/en/network-mapper.php, lang/en/knowledge.php (and 22 other locales) network-mapper.kb.*, network-mapper.menu.open_article / link_article, knowledge.diagrams.*
πŸ§ͺ tests/network-mapper-articles.php 15 checks plus clean-up - see Tests

Export to Download or Save to Files

🎨 File What it does
πŸ–₯️ assets/js/network-mapper.js (v=20) exportMenu(), deliverExport(), exportPng(mode) (canvas.toBlob), exportPdf(mode) (doc.output('blob'))
πŸ–₯️ network-mapper/diagram.php Buttons call NM.exportMenu(event, 'png' / 'pdf'); window.NM_FILES; loads assets/js/save-to-files.js (?v=3) and assets/css/save-to-files.css (?v=1)
πŸ”—πŸ–₯️ assets/js/save-to-files.js (v=3) SaveToFiles.open({ blob, name }) and sendExport() - a multipart POST
πŸ–₯️ assets/css/save-to-files.css The dialog's look (unchanged)
βœοΈπŸ”’ api/files/save_from.php The new multipart branch: is_uploaded_file(), then FilesSave::saveExport()
βœοΈπŸ”’ includes/services/files_save.php FilesSave::EXPORT_TYPES and FilesSave::saveExport(); filesStoreLocalFile() does the write
πŸ”’ includes/files/acl.php FilesAcl::level() / FilesAcl::UPLOAD - the folder check
πŸ”’ assets/js/csrf.js Adds X-CSRF-Token to the fetch() POST, so sendExport() needs nothing of its own
πŸ”— includes/documents_panel.php, tickets/index.php Cache-buster for assets/js/save-to-files.js bumped to ?v=3 (see Traps)
πŸ–₯️ lang/en/network-mapper.php (and 22 other locales) network-mapper.help.export_tip
πŸ§ͺ tests/files-save-export.php 9 checks plus clean-up - see Tests

Part 1 - Knowledge articles on diagrams

The schema

Two kinds of link, two shapes of storage.

One article per item is a nullable column on the item. From database/freeitsm.sql:

CREATE TABLE IF NOT EXISTS `network_diagram_nodes` (
    ...
    -- A Knowledge article the node links to (click in Present; the book marker or right-click menu in the editor).
    -- Who may read it is Knowledge's own rule - the diagram never shows a title past it.
    `article_id`     INT NULL,
    `is_demo`           TINYINT(1) NOT NULL DEFAULT 0,   -- set by the demo data importer (#1297)
    PRIMARY KEY (`id`),
    KEY `ix_net_node_diag` (`diagram_id`),
    KEY `ix_net_node_cmdb` (`cmdb_object_id`),
    KEY `ix_net_node_article` (`article_id`),
    CONSTRAINT `fk_net_node_diag` FOREIGN KEY (`diagram_id`) REFERENCES `network_diagrams` (`id`) ON DELETE CASCADE,
    CONSTRAINT `fk_net_node_cmdb` FOREIGN KEY (`cmdb_object_id`) REFERENCES `cmdb_objects` (`id`) ON DELETE CASCADE,
    CONSTRAINT `fk_net_node_article` FOREIGN KEY (`article_id`) REFERENCES `knowledge_articles` (`id`) ON DELETE SET NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
    `article_id`     INT NULL,                 -- as network_diagram_nodes.article_id
    ...
    KEY `ix_net_shape_article` (`article_id`),
    CONSTRAINT `fk_net_shape_diag` FOREIGN KEY (`diagram_id`) REFERENCES `network_diagrams` (`id`) ON DELETE CASCADE,
    CONSTRAINT `fk_net_shape_article` FOREIGN KEY (`article_id`) REFERENCES `knowledge_articles` (`id`) ON DELETE SET NULL

ON DELETE SET NULL is the point: when an article is deleted for good, the switch stays on the diagram and only loses its book. The item is the diagram's content; the link is a decoration on it.

Many related articles per diagram is its own table:

-- GH #433: Knowledge articles related to a diagram as a whole ("Articles" in the editor), and
-- listed back on the article as "Network diagrams". One row per diagram VERSION - a new
-- version copies them. Titles are only ever shown through Knowledge's own read rule.
CREATE TABLE IF NOT EXISTS `network_diagram_articles` (
    `id`                    INT NOT NULL AUTO_INCREMENT,
    `diagram_id`            INT NOT NULL,
    `article_id`            INT NOT NULL,
    `created_by_analyst_id` INT NULL,
    `created_datetime`      DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
    PRIMARY KEY (`id`),
    UNIQUE KEY `uq_net_diag_article` (`diagram_id`, `article_id`),
    KEY `ix_net_diag_article` (`article_id`),
    CONSTRAINT `fk_net_da_diag` FOREIGN KEY (`diagram_id`) REFERENCES `network_diagrams` (`id`) ON DELETE CASCADE,
    CONSTRAINT `fk_net_da_article` FOREIGN KEY (`article_id`) REFERENCES `knowledge_articles` (`id`) ON DELETE CASCADE,
    CONSTRAINT `fk_net_da_analyst` FOREIGN KEY (`created_by_analyst_id`) REFERENCES `analysts` (`id`) ON DELETE SET NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
  • uq_net_diag_article makes "add it twice" a no-op: addRelated() uses INSERT IGNORE, so a double click or two people adding the same article at once leaves one row.
  • ix_net_diag_article serves the reverse lookup, "which diagrams use article N", which the unique key (diagram first) cannot.
  • Both FKs to the diagram and the article CASCADE, because a row in this table is nothing but the link. The author FK is SET NULL: the link outlives the analyst who made it.
  • id order is the display order. forDiagram() reads ORDER BY id, so the list shows in the order articles were added.

DB Verify

includes/db_verify_schema.php lists the columns so an existing install gets them:

        'group_key'      => 'VARCHAR(40) NULL',         // GH #433: Group / Ungroup
        'article_id'     => 'INT NULL',                 // GH #433: a linked Knowledge article
    // GH #433: Knowledge articles related to a diagram (includes/services/network_articles.php)
    'network_diagram_articles' => [
        'id'                    => 'INT NOT NULL AUTO_INCREMENT',
        'diagram_id'            => 'INT NOT NULL',
        'article_id'            => 'INT NOT NULL',
        'created_by_analyst_id' => 'INT NULL',
        'created_datetime'      => 'DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP',
    ],

A foreign key cannot be added while a row points at something that is gone, so api/system/db_verify.php cleans orphans first, using the same semantics the FK will have (SET NULL on the items, DELETE on the link rows):

            // GH #433: an article that is gone stops being linked (SET NULL / CASCADE semantics).
            if ($tableExists('knowledge_articles')) {
                foreach (['network_diagram_nodes', 'network_diagram_shapes'] as $nt) {
                    if ($tableExists($nt) && $colExists($nt, 'article_id')) {
                        $conn->exec("UPDATE $nt x LEFT JOIN knowledge_articles a ON a.id = x.article_id SET x.article_id = NULL WHERE x.article_id IS NOT NULL AND a.id IS NULL");
                    }
                }
                if ($tableExists('network_diagram_articles')) {
                    $conn->exec("DELETE x FROM network_diagram_articles x LEFT JOIN knowledge_articles a ON a.id = x.article_id WHERE a.id IS NULL");
                    $conn->exec("DELETE x FROM network_diagram_articles x LEFT JOIN network_diagrams d ON d.id = x.diagram_id WHERE d.id IS NULL");
                    $conn->exec("UPDATE network_diagram_articles x LEFT JOIN analysts an ON an.id = x.created_by_analyst_id SET x.created_by_analyst_id = NULL WHERE x.created_by_analyst_id IS NOT NULL AND an.id IS NULL");
                }
            }

Then the keys themselves, in the same list as every other Network Mapper FK:

        ['network_diagram_nodes',      'fk_net_node_article', "ALTER TABLE network_diagram_nodes ADD CONSTRAINT fk_net_node_article FOREIGN KEY (article_id) REFERENCES knowledge_articles (id) ON DELETE SET NULL"],
        ['network_diagram_shapes',     'fk_net_shape_article', "ALTER TABLE network_diagram_shapes ADD CONSTRAINT fk_net_shape_article FOREIGN KEY (article_id) REFERENCES knowledge_articles (id) ON DELETE SET NULL"],
        ['network_diagram_articles',   'fk_net_da_diag',     "ALTER TABLE network_diagram_articles ADD CONSTRAINT fk_net_da_diag FOREIGN KEY (diagram_id) REFERENCES network_diagrams (id) ON DELETE CASCADE"],
        ['network_diagram_articles',   'fk_net_da_article',  "ALTER TABLE network_diagram_articles ADD CONSTRAINT fk_net_da_article FOREIGN KEY (article_id) REFERENCES knowledge_articles (id) ON DELETE CASCADE"],
        ['network_diagram_articles',   'fk_net_da_analyst',  "ALTER TABLE network_diagram_articles ADD CONSTRAINT fk_net_da_analyst FOREIGN KEY (created_by_analyst_id) REFERENCES analysts (id) ON DELETE SET NULL"],

The four indexes live in includes/db_verify_indexes.php, which is generated from database/freeitsm.sql by its script. Run the script; do not type them in.

Analyst lifecycle

created_by_analyst_id is an analyst reference, so it is registered in analystReferenceRegistry() in includes/analyst_lifecycle.php:

        ['network_diagram_articles', 'created_by_analyst_id', 'history'],   // GH #433

history is the lifecycle's "who did what" category: the reference is kept and still credited to the analyst, and a row here means the analyst cannot be hard-deleted (Deactivate or Anonymise instead). Registering it is what makes the leaver screens and tests/analyst-lifecycle.php know the column exists. The FK's ON DELETE SET NULL is only the database's safety net if a row is ever removed some other way. See Analysts Leaving for the user side.

The visibility rule

Everything in this feature reads titles through one function, NetworkArticleService::readable(), and that function asks Knowledge, never its own SQL:

    public static function readable(PDO $conn, int $analystId, array $ids): array
    {
        return array_map(fn($r) => $r['title'], self::readableRows($conn, $analystId, $ids));
    }

    public static function readableRows(PDO $conn, int $analystId, array $ids): array
    {
        $ids = array_values(array_unique(array_filter(array_map('intval', $ids), fn($i) => $i > 0)));
        if (!$ids || $analystId <= 0 || !analystCanAccessModule($conn, $analystId, 'knowledge')) return [];
        [$vis, $args] = knowledgeVisibilitySql($conn, KnowledgeViewer::forAnalyst($conn, $analystId), 'a', ['lifecycle' => 'any']);
        $ph = implode(',', array_fill(0, count($ids), '?'));
        $st = $conn->prepare("SELECT a.id, a.title, a.is_published, a.is_archived FROM knowledge_articles a WHERE a.id IN ($ph)" . $vis);
        $st->execute(array_merge($ids, $args));
        $out = [];
        foreach ($st->fetchAll(PDO::FETCH_ASSOC) as $r) $out[(int)$r['id']] = ['title' => (string)$r['title'], 'state' => self::stateOf($r)];
        return $out;
    }

    private static function stateOf(array $r): string
    {
        if ((int)($r['is_archived'] ?? 0) === 1) return 'archived';
        return (int)($r['is_published'] ?? 1) === 1 ? 'live' : 'draft';
    }

Why it is built this way:

  • No Knowledge module, no titles at all. analystCanAccessModule($conn, $analystId, 'knowledge') is checked first. Someone who only has Network Mapper sees every link as "An article you don't have access to". This matters because diagrams are install-wide: everyone with Network Mapper opens the same diagram.
  • knowledgeVisibilitySql() is the same clause the Knowledge list uses - with one deliberate difference: lifecycle => 'any'. The default, live (published and not archived), is right for a list of articles to read and wrong for a link that already exists: an analyst opens drafts (with their Draft badge) and archived articles in Knowledge, so calling them "no access" on a diagram was untrue. Lifting the lifecycle lifts nothing else - the clause still applies the company scope (tenant_id IS NULL means shared with every company in Knowledge), the audience rung, and the folder access lists. Re-deriving any of that here would be the classic way for two readers of one table to disagree. The design of that clause, and why knowledgeCanRead() is built on it, is on Knowledge folders and security - Developer Guide.
  • The administrator floor applies. knowledgeVisibilitySql() is called without no_admin_floor, so an analyst with Cap::KNOWLEDGE_MANAGE passes the access-list part and sees every title. This is a list read, so (as in Knowledge's own list) no admin_override audit row is written; the audit row belongs to knowledgeCanRead(), the single-article open, which Knowledge itself does when the person actually opens the article.
  • One query for all ids. A diagram can carry dozens of links; IN (...) plus the visibility clause keeps it to one round trip.
  • The answer is a map of readable ids only. An id the viewer cannot read is simply missing. Callers turn "missing" into null, never into a title.
  • The state travels with the title. forDiagram() adds states ({id: 'draft' | 'archived'}, published ones left out) and search() gives each row a state; the editor's kbLabel() appends " (Draft)" / " (Archived)" (network-mapper.kb.state_draft / state_archived, in every language), so a reader knows before clicking.

NetworkArticleService, method by method

includes/services/network_articles.php. It pulls in includes/knowledge/visibility.php itself, so any caller gets the rule by including the service.

idsOnDiagram() - every article this version links to

    public static function idsOnDiagram(PDO $conn, int $diagramId): array
    {
        $ids = [];
        foreach (["SELECT article_id FROM network_diagram_nodes WHERE diagram_id = ? AND article_id IS NOT NULL",
                  "SELECT article_id FROM network_diagram_shapes WHERE diagram_id = ? AND article_id IS NOT NULL",
                  "SELECT article_id FROM network_diagram_articles WHERE diagram_id = ?"] as $sql) {
            try {
                $st = $conn->prepare($sql);
                $st->execute([$diagramId]);
                foreach ($st->fetchAll(PDO::FETCH_COLUMN) as $id) $ids[(int)$id] = true;
            } catch (PDOException $e) {
                // the column or table is not there yet
            }
        }
        return array_keys($ids);
    }

Three sources, one de-duplicated set (array keys). Each query has its own try, so an install that has the table but not yet the column (DB Verify not run since upgrading) still opens its diagrams. That fallback pattern runs right through this file.

allowedForSave() - the save rule

    public static function allowedForSave(PDO $conn, int $analystId, int $diagramId, array $wanted): array
    {
        $wanted = array_values(array_unique(array_filter(array_map('intval', $wanted), fn($i) => $i > 0)));
        if (!$wanted) return [];
        $allowed = array_fill_keys(self::idsOnDiagram($conn, $diagramId), true);
        $new = array_values(array_filter($wanted, fn($i) => !isset($allowed[$i])));
        foreach (array_keys(self::readable($conn, $analystId, $new)) as $id) $allowed[$id] = true;
        return $allowed;
    }

A save sends every node and shape, each with its article_id. Two things must both be true:

  1. A colleague's link survives my save. Ann links the core switch to a Restricted runbook. Bob, who cannot read it, moves a box and saves. The whole diagram is replaced on save, so if the rule were "keep only what the saver can read", Bob's save would silently strip Ann's link. So anything already on the diagram is allowed, readable or not.
  2. A typed-in id is not accepted. Bob crafts a save request with article_id: 999 on a shape, where 999 is a Restricted article he cannot read. He would then see "An article you don't have access to" on the diagram, which is harmless, but it would also put the article on its "Network diagrams" list, and let him pin someone else's private document onto a public diagram. So a new id is allowed only if the saver can read it.

Only the new ids go to readable(), which keeps the query small on a big diagram where nothing changed.

It must run before the transaction. The save deletes and re-inserts every node and shape, so once the replace has started, idsOnDiagram() would return nothing and rule 1 would quietly fail. NetworkMapperService computes it first, in both createDiagram() (diagram id 0, so only readable ids are allowed) and saveDiagram():

        // GH #433: which article links this save may keep (see NetworkArticleService::allowedForSave).
        $articles = NetworkArticleService::allowedForSave($conn, (int)$ctx->actorId, $diagramId, array_merge(
            array_map(fn($x) => is_array($x) ? (int)($x['article_id'] ?? 0) : 0, is_array($in['nodes'] ?? null) ? $in['nodes'] : []),
            array_map(fn($x) => is_array($x) ? (int)($x['article_id'] ?? 0) : 0, is_array($in['shapes'] ?? null) ? $in['shapes'] : [])));
        $conn->beginTransaction();

The is_array() guards are there because $in is untrusted JSON: a node that is a string, or nodes that is not a list, must not throw before the real validation runs.

The allowed set is then passed into the two replace functions, and each row keeps its id only if it is in the set:

            $insertNode->execute([$diagramId, $objectId, $x, $y, $size, $icon, $colour, $w, $h, $style,
                                  self::keyOf($n['page_key'] ?? 0), self::keyOf($n['layer_key'] ?? 0), self::groupOf($n['group_key'] ?? null),
                                  isset($articles[(int)($n['article_id'] ?? 0)]) ? (int)$n['article_id'] : null]);   // GH #433
                (is_string($s['uid'] ?? null) && preg_match('/^[A-Za-z0-9_-]{1,20}$/', $s['uid'])) ? $s['uid'] : null,
                isset($articles[(int)($s['article_id'] ?? 0)]) ? (int)$s['article_id'] : null,   // GH #433

A refused id is not an error, it saves as "no article". That matches how the rest of replaceShapes() treats bad input (an icon_id that does not exist also saves as no icon): the save of a big diagram should not fail because one field on one shape was wrong.

api/network-mapper/save_diagram.php had to pass the field through, because it rebuilds each node before calling the service:

                'group_key'     => $n['group_key'] ?? null,
                'article_id'    => $n['article_id'] ?? null,   // GH #433: a linked Knowledge article
                'ref'           => (string)$ref,

forDiagram() - what the editor is sent

    public static function forDiagram(PDO $conn, int $analystId, int $diagramId): array
    {
        $related = [];
        try {
            $st = $conn->prepare("SELECT article_id FROM network_diagram_articles WHERE diagram_id = ? ORDER BY id");
            $st->execute([$diagramId]);
            $related = array_map('intval', $st->fetchAll(PDO::FETCH_COLUMN));
        } catch (PDOException $e) {
            $related = [];
        }
        $all = self::idsOnDiagram($conn, $diagramId);
        $can = self::readable($conn, $analystId, $all);
        $titles = [];
        foreach ($all as $id) $titles[(string)$id] = $can[$id] ?? null;
        return ['related' => $related, 'titles' => $titles];
    }

related is just ids, in order. titles has a key for every linked article, with the title or null. The JS never has to ask "do I know this id?": a key with null means "linked, but not for you", and the server has not sent the title. The keys are strings so the JSON is an object, not a list.

addRelated() / removeRelated() - the related list

    public static function addRelated(PDO $conn, ActorContext $ctx, int $diagramId, int $articleId): void
    {
        self::requireCurrent($conn, $diagramId);
        if (!self::readable($conn, (int)$ctx->actorId, [$articleId])) {
            throw new ServiceError('not_found', 'not_found', 'Article not found.');
        }
        $conn->prepare("INSERT IGNORE INTO network_diagram_articles (diagram_id, article_id, created_by_analyst_id, created_datetime)
                        VALUES (?, ?, ?, UTC_TIMESTAMP())")->execute([$diagramId, $articleId, $ctx->actorId ?: null]);
    }

    public static function removeRelated(PDO $conn, int $diagramId, int $articleId): void
    {
        self::requireCurrent($conn, $diagramId);
        $conn->prepare("DELETE FROM network_diagram_articles WHERE diagram_id = ? AND article_id = ?")->execute([$diagramId, $articleId]);
    }
  • Add needs read access; remove does not. You may only add an article you can read, but you may take any link off, including one you cannot read. That is how an ordinary diagram edit already works: anyone who can edit the diagram can delete a box.
  • "Not readable" and "does not exist" are the same not_found. An id cannot be probed to learn whether a Restricted article exists.
  • These write straight away, not on Save. The related list is not part of the diagram payload, so a related-list change cannot be lost to "leave without saving", and it cannot collide with someone else's unsaved canvas.
  • Current version only, through requireCurrent():
    private static function requireCurrent(PDO $conn, int $diagramId): void
    {
        $st = $conn->prepare("SELECT (SELECT COUNT(*) FROM network_diagrams c WHERE c.parent_diagram_id = d.id) FROM network_diagrams d WHERE d.id = ?");
        $st->execute([$diagramId]);
        $children = $st->fetchColumn();
        if ($children === false) throw new ServiceError('not_found', 'not_found', 'Diagram not found.');
        if ((int)$children > 0) throw new ServiceError('conflict', 'conflict', 'This is a historical version (read-only).');
    }

One query tells "no such diagram" (fetchColumn() is false, no row) apart from "historical version" (a row with children). A version with a child is frozen history, as everywhere else in the module.

copyRelated() - new versions

    public static function copyRelated(PDO $conn, int $fromId, int $toId): void
    {
        try {
            $conn->prepare("INSERT INTO network_diagram_articles (diagram_id, article_id, created_by_analyst_id, created_datetime)
                            SELECT ?, article_id, created_by_analyst_id, created_datetime FROM network_diagram_articles WHERE diagram_id = ?")
                 ->execute([$toId, $fromId]);
        } catch (PDOException $e) {
            // table not there yet
        }
    }

NetworkMapperService::createVersion() calls it inside its transaction, right after copying pages and layers. It copies the original author and time, so "who added this" stays true across versions. Item links travel with the items in the same function:

                "INSERT INTO network_diagram_nodes (diagram_id, cmdb_object_id, x, y, size, icon_override, colour_override, w, h, style, page_key, layer_key, group_key, article_id) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"
            ...
                                      (int)($n['page_key'] ?? 0), (int)($n['layer_key'] ?? 0), $n['group_key'] ?? null,
                                      isset($n['article_id']) ? (int)$n['article_id'] : null]);
                "INSERT INTO network_diagram_shapes (diagram_id, shape_type, x, y, w, h, rotation, text, style, layer, z, icon_id, page_key, layer_key, group_key, uid, article_id)
                 SELECT ?, shape_type, x, y, w, h, rotation, text, style, layer, z, icon_id, page_key, layer_key, group_key, uid, article_id FROM network_diagram_shapes WHERE diagram_id = ? ORDER BY id"

Versioning is a server-side copy, not a save, so allowedForSave() is not involved: every link is copied, readable by the person making the version or not. That is rule 1 again (a colleague's link survives).

search() - the picker

    public static function search(PDO $conn, int $analystId, string $q): array
    {
        if ($analystId <= 0 || !analystCanAccessModule($conn, $analystId, 'knowledge')) return [];
        [$vis, $args] = knowledgeVisibilitySql($conn, KnowledgeViewer::forAnalyst($conn, $analystId), 'a', ['lifecycle' => 'unarchived']);
        $q = trim($q);
        $where = '';
        if ($q !== '') {
            $where = ' AND a.title LIKE ?';
            $args[] = '%' . str_replace(['\\', '%', '_'], ['\\\\', '\\%', '\\_'], $q) . '%';
        }
        $st = $conn->prepare("SELECT a.id, a.title, a.is_published, a.is_archived FROM knowledge_articles a WHERE 1 = 1" . $vis . $where . "
                               ORDER BY " . ($q !== '' ? 'a.title' : 'COALESCE(a.modified_datetime, a.created_datetime) DESC') . " LIMIT 40");
        $st->execute($args);
        return array_map(fn($r) => ['id' => (int)$r['id'], 'title' => (string)$r['title'], 'state' => self::stateOf($r)], $st->fetchAll(PDO::FETCH_ASSOC));
    }
  • The picker can only offer what Knowledge would list for this person, so a Restricted article cannot even be found by title.
  • lifecycle => 'unarchived': drafts are offered (a runbook is often linked while it is still being written) and marked Draft in the list; archived articles are not offered - an existing link to one keeps working, but nobody should pick one new.
  • %, _ and \ in what was typed are escaped, so typing 100% searches for that text rather than "anything starting 100".
  • With nothing typed it shows the 40 most recently changed articles, which is usually the one just written for this diagram.
  • The ORDER BY is one of two fixed strings, never built from input.

diagramsForArticle() - the way back

    public static function diagramsForArticle(PDO $conn, int $analystId, int $articleId): array
    {
        if ($articleId <= 0 || !analystCanAccessModule($conn, $analystId, 'network-mapper')) return [];
        if (!self::readable($conn, $analystId, [$articleId])) return [];
        $how = [];
        foreach (['related' => "SELECT diagram_id FROM network_diagram_articles WHERE article_id = ?",
                  'item'    => "SELECT diagram_id FROM network_diagram_nodes WHERE article_id = ?
                                UNION SELECT diagram_id FROM network_diagram_shapes WHERE article_id = ?"] as $kind => $sql) {
            try {
                $st = $conn->prepare($sql);
                $st->execute($kind === 'item' ? [$articleId, $articleId] : [$articleId]);
                foreach ($st->fetchAll(PDO::FETCH_COLUMN) as $d) $how[(int)$d] = $how[(int)$d] ?? $kind;
            } catch (PDOException $e) {
                // not there yet
            }
        }
        if (!$how) return [];
        $ph = implode(',', array_fill(0, count($how), '?'));
        $st = $conn->prepare("SELECT d.id, d.title, d.version_label FROM network_diagrams d
                               WHERE d.id IN ($ph) AND NOT EXISTS (SELECT 1 FROM network_diagrams c WHERE c.parent_diagram_id = d.id)
                               ORDER BY d.title");
        $st->execute(array_keys($how));
        return array_map(fn($r) => ['id' => (int)$r['id'], 'title' => (string)$r['title'], 'version_label' => $r['version_label'],
                                    'how' => $how[(int)$r['id']]], $st->fetchAll(PDO::FETCH_ASSOC));
    }
  • Two gates. The reader needs the Network Mapper module (otherwise the list would name diagrams in a module they cannot open), and must be able to read the article (otherwise the endpoint becomes a way to learn which diagrams use a Restricted article, by id).
  • Current versions only (NOT EXISTS a child). Every version keeps its own copy of the links, so without that filter one diagram with five versions would be listed five times.
  • how is related or item. Related is checked first and ?? keeps the first answer, so a diagram that does both is shown as "Related to the diagram".

The endpoint: api/network-mapper/articles.php

A thin adapter. The order of the checks is the interesting part:

    if ($method === 'GET' && isset($_GET['article_id'])) {
        echo json_encode(['success' => true, 'diagrams' => NetworkArticleService::diagramsForArticle($conn, $analystId, (int)$_GET['article_id'])]);
        exit;
    }

    requireModuleAccessJson('network-mapper');

    if ($method === 'GET') {
        echo json_encode(['success' => true, 'can_read' => analystCanAccessModule($conn, $analystId, 'knowledge'),
                          'articles' => NetworkArticleService::search($conn, $analystId, (string)($_GET['q'] ?? ''))]);
        exit;
    }

GET ?article_id= is answered before requireModuleAccessJson('network-mapper'), because it is called from the Knowledge reader, by people who may not have Network Mapper. For them the answer must be an empty list, not a 403 that the Knowledge page would have to handle. The service already returns [] without the module, so nothing leaks. Everything after that line is Network Mapper's own and needs the module.

The POST half:

    $data = json_decode(file_get_contents('php://input'), true) ?: [];
    $action = (string)($data['action'] ?? '');
    $diagramId = (int)($data['diagram_id'] ?? 0);
    $articleId = (int)($data['article_id'] ?? 0);
    if ($action === 'add') {
        NetworkArticleService::addRelated($conn, ActorContext::fromSession($conn), $diagramId, $articleId);
    } elseif ($action === 'remove') {
        NetworkArticleService::removeRelated($conn, $diagramId, $articleId);
    } else {
        http_response_code(400);
        echo json_encode(['success' => false, 'error' => 'Unknown action']);
        exit;
    }
    echo json_encode(['success' => true] + NetworkArticleService::forDiagram($conn, $analystId, $diagramId));

Both actions answer with the fresh forDiagram() result, so the editor replaces its list and titles from the server instead of guessing what changed. The CSRF token comes from assets/js/csrf.js, which adds X-CSRF-Token to every same-origin fetch().

api/network-mapper/get_diagram.php

Nodes and shapes now select article_id and cast it:

        $n['article_id'] = $n['article_id'] !== null ? (int)$n['article_id'] : null;   // GH #433
            $s['article_id'] = $s['article_id'] !== null ? (int)$s['article_id'] : null;

The shapes query already had an "older install" fallback; it gains NULL AS article_id so an install between upgrades still opens. Then the two new keys in the answer:

    // GH #433: Knowledge articles - the related list, and a title for each linked article that
    // this analyst may read (null = linked, but not one they can read: no title is sent).
    $articles = ['related' => [], 'titles' => new stdClass()];
    try {
        require_once '../../includes/services/network_articles.php';
        $articles = NetworkArticleService::forDiagram($conn, (int)$_SESSION['analyst_id'], $id);
        if (!$articles['titles']) $articles['titles'] = new stdClass();
    } catch (Exception $e) {
        // Knowledge not set up on this install - the diagram still opens
    }

    echo json_encode(['success' => true, 'diagram' => $d, 'nodes' => $nodes, 'connectors' => $conns, 'shapes' => $shapes, 'pages' => $pages, 'layers' => $layers,
                      'articles' => $articles, 'can_read_knowledge' => analystCanAccessModule($conn, (int)$_SESSION['analyst_id'], 'knowledge')]);
  • new stdClass() makes an empty titles encode as {}. An empty PHP array would encode as [], and the JS would then treat it as a list.
  • The whole block is in a try: a missing Knowledge table must not stop a diagram opening.
  • can_read_knowledge is "has the Knowledge module". The editor uses it to decide whether to offer the picker at all.

The editor (assets/js/network-mapper.js)

State

    let kbRelated = [];      // article ids related to this diagram, in the order added
    let kbTitles = {};       // article id -> title, or null when linked but not readable by this analyst
    let canReadKb = false;   // has the Knowledge module - the picker needs it
    let kbPick = null;       // the picker's callback while it is open
    let kbTimer = null, kbSeq = 0;

Filled in loadDiagram():

            kbRelated = (data.articles && data.articles.related) || [];   // GH #433: Knowledge articles
            kbTitles = (data.articles && data.articles.titles && !Array.isArray(data.articles.titles)) ? data.articles.titles : {};
            canReadKb = !!data.can_read_knowledge;
            renderArticlesPanel();

The !Array.isArray() is the second half of the stdClass trick: if anything ever sends [], the editor still gets an object.

Two helpers decide every label on screen:

    function kbTitle(id) { const v = kbTitles[id]; return typeof v === 'string' ? v : null; }
    function kbLabel(id) { const v = kbTitle(id); return v !== null ? v : t('network-mapper.kb.no_access'); }

kbTitle() returns null both for "not readable" and "never heard of it", so an id the editor has no title for is always treated as unreadable. Nothing can draw a title the server did not send.

Opening an article

    function openArticle(id) {
        if (!id) return;
        if (kbTitle(id) === null) { if (window.showToast) showToast(t('network-mapper.kb.no_access'), 'error'); return; }
        window.open('../knowledge/?article=' + encodeURIComponent(id), '_blank', 'noopener');
    }

It opens Knowledge in a new tab, so the diagram (and any unsaved work) stays put. Knowledge checks the article again when it opens; the kbTitle() check here only saves a pointless tab.

The book marker

    function addKbMark(el, it) {
        if (!it.article_id) return;
        el.classList.add('has-article');
        const b = document.createElement('button');
        b.type = 'button';
        b.className = 'nm-kb-mark' + (kbTitle(it.article_id) === null ? ' is-hidden-article' : '');
        b.title = kbLabel(it.article_id);
        b.setAttribute('aria-label', kbLabel(it.article_id));
        b.innerHTML = KB_BOOK;
        b.addEventListener('mousedown', e => { e.stopPropagation(); e.preventDefault(); });
        b.addEventListener('click', e => { e.stopPropagation(); openArticle(it.article_id); });
        el.appendChild(b);
    }

It is called at the end of both renderNode() and renderShape(). The mousedown handler stops the event reaching the node, whose own mousedown would select it and start a drag. An unreadable article gets a grey book (.is-hidden-article). The CSS in network-mapper/diagram.php keeps it out of exports:

        .nm-kb-mark {
            position: absolute; top: -9px; right: -9px; z-index: 3; width: 20px; height: 20px; padding: 0;
            display: flex; align-items: center; justify-content: center; border-radius: 50%; cursor: pointer;
            border: 1px solid var(--nm-accent, #06b6d4); background: var(--surface, #fff); color: var(--nm-accent, #06b6d4);
            box-shadow: 0 1px 3px rgba(0, 0, 0, .15);
        }
        .nm-kb-mark.is-hidden-article { border-color: var(--border, #e5e7eb); color: var(--text-faint, #9ca3af); }
        .nm-canvas-inner.is-exporting .nm-kb-mark { display: none; }
        .nm-editor.is-presenting .has-article { cursor: pointer; }

Present mode

In Present, a plain click on a linked item opens the article. It is the first thing the node and shape mousedown handlers check:

        if (isPresenting() && n.article_id) { e.preventDefault(); openArticle(n.article_id); return; }   // GH #433
        if (isPresenting() && s.article_id) { e.preventDefault(); openArticle(s.article_id); return; }   // GH #433

The Article line in the node and shape panels

    function renderKbField(host, it) {
        if (!host) return;
        host._kbItem = it;
        const ed = canEdit();
        const id = it.article_id;
        const btn = (act, label) => '<button type="button" class="nm-detail-icon-btn" data-kb="' + act + '">' + escapeHtml(label) + '</button>';
        let html;
        if (id) {
            const title = kbTitle(id);
            html = '<span class="nm-kb-name' + (title === null ? ' is-hidden-article' : '') + '" title="' + escapeAttr(kbLabel(id)) + '">' + escapeHtml(kbLabel(id)) + '</span>'
                + (title !== null ? btn('open', t('network-mapper.kb.open')) : '')
                + (ed && canReadKb ? btn('change', t('network-mapper.kb.change')) : '')
                + (ed ? btn('remove', t('network-mapper.kb.remove')) : '');
        } else if (ed && canReadKb) {
            html = btn('change', t('network-mapper.kb.link'));
        } else {
            html = '<span class="nm-kb-none">' + escapeHtml(t('network-mapper.kb.none')) + '</span>';
        }
        host.innerHTML = html;
        host.querySelectorAll('[data-kb]').forEach(b => b.addEventListener('click', () => {
            if (b.dataset.kb === 'open') openArticle(id);
            else if (b.dataset.kb === 'remove') setItemArticle(it, null);
            else openArticlePicker(a => setItemArticle(it, a));
        }));
    }

The buttons follow the same rules as the server: Open only for a readable article, Change and Link only with the Knowledge module (the picker would be empty otherwise), Remove for anyone who can edit, readable or not. host._kbItem remembers which item the panel is showing, so setItemArticle() can refresh the right panel:

    function setItemArticle(it, a) {
        it.article_id = a ? a.id : null;
        if (a) kbTitles[a.id] = a.title;
        if (nodes.includes(it)) { rerenderNode(it); renderConnectors(); } else { rerenderShape(it); }
        markDirty();
        ['ndArticle', 'spArticle'].forEach(id => { const h = document.getElementById(id); if (h && h._kbItem === it) renderKbField(h, it); });
    }

An item link is part of the diagram, so it is saved by Save (markDirty()), not straight away. The title from the picker goes into kbTitles so the book shows it before the next load. The save payload carries it:

                        page_key: itemPage(n), layer_key: itemLayer(n), group_key: n.group_key || null,
                        article_id: n.article_id || null                // GH #433

The picker

    function onArticleSearchInput(v) { clearTimeout(kbTimer); kbTimer = setTimeout(() => searchArticles(v), 200); }
    async function searchArticles(q) {
        const box = document.getElementById('articleResults');
        const seq = ++kbSeq;
        try {
            const r = await fetch(API + 'articles.php?q=' + encodeURIComponent(q || ''), { credentials: 'same-origin' });
            const d = await r.json();
            if (seq !== kbSeq) return;   // a newer search has started
            if (!d.success) throw new Error(d.error || 'failed');
            const list = d.articles || [];
            box.innerHTML = list.length
                ? list.map(a => '<div class="nm-picker-row" data-id="' + a.id + '"><span class="nm-picker-name">' + KB_BOOK + escapeHtml(a.title) + '</span></div>').join('')
                : '<div class="nm-picker-empty">' + escapeHtml(t('network-mapper.kb.no_results')) + '</div>';
            box.querySelectorAll('.nm-picker-row').forEach(row => row.addEventListener('click', () => {
                const a = list.find(x => x.id === +row.dataset.id);
                const cb = kbPick;
                closeArticlePicker();
                if (cb && a) cb(a);
            }));
        } catch (e) {
            box.innerHTML = '<div class="nm-picker-empty">' + escapeHtml(e.message) + '</div>';
        }
    }
  • A 200 ms debounce, and kbSeq so a slow early answer cannot overwrite a later one.
  • One picker serves three callers (item panel, right-click menu, related list) through the kbPick callback. It is copied to cb before closeArticlePicker() clears it.
  • The modal is #articlePickerModal in network-mapper/diagram.php; Escape in its search box closes it.

The Articles toolbar dropdown

    function renderArticlesPanel() {
        const lab = document.getElementById('articlesBtnCount');
        if (lab) lab.textContent = String(kbRelated.length);
        const dd = document.getElementById('articlesDropdown');
        if (!dd || dd.style.display === 'none') return;
        const ed = !!(diagram && diagram.is_current);
        dd.innerHTML = '<div class="nm-layers-head">' + escapeHtml(t('network-mapper.kb.related_title')) + '</div>'
            + (kbRelated.length ? kbRelated.map(id => '<div class="nm-kb-row">'
                    + (kbTitle(id) !== null
                        ? '<a href="../knowledge/?article=' + encodeURIComponent(id) + '" target="_blank" rel="noopener">' + KB_BOOK + '<span>' + escapeHtml(kbTitle(id)) + '</span></a>'
                        : '<span class="is-hidden-article">' + KB_BOOK + '<span>' + escapeHtml(t('network-mapper.kb.no_access')) + '</span></span>')
                    + (ed ? '<button type="button" class="nm-layer-ico nm-layer-del" data-del="' + id + '" title="' + escapeAttr(t('network-mapper.kb.remove')) + '">&times;</button>' : '')
                    + '</div>').join('')
                : '<div class="nm-kb-empty">' + escapeHtml(t('network-mapper.kb.related_empty')) + '</div>')
            + (ed && canReadKb ? '<button type="button" class="nm-layers-add" id="kbRelAdd">+ ' + escapeHtml(t('network-mapper.kb.related_add')) + '</button>' : '')
            + (!canReadKb ? '<div class="nm-layers-hint">' + escapeHtml(t('network-mapper.kb.no_knowledge')) + '</div>' : '')
            + '<div class="nm-layers-hint">' + escapeHtml(t('network-mapper.kb.related_hint')) + '</div>';
        ...
    }

It borrows the Layers dropdown's look (.nm-layers-head, .nm-layers-add, .nm-layer-del). The count on the button is updated even when the dropdown is closed. Edit rights here are diagram.is_current, not canEdit(), because the related list is written straight to the server and the server's rule is "current version", whatever the editor's lock or Present state.

Changes go straight to the endpoint and the list is rebuilt from its answer:

    async function relatedPost(action, articleId) {
        try {
            const r = await fetch(API + 'articles.php', { method: 'POST', credentials: 'same-origin', headers: { 'Content-Type': 'application/json' },
                                                         body: JSON.stringify({ action: action, diagram_id: diagramId, article_id: articleId }) });
            const d = await r.json();
            if (!d.success) throw new Error(d.error || 'failed');
            kbRelated = d.related || [];
            kbTitles = Object.assign({}, kbTitles, d.titles || {});
            const dd = document.getElementById('articlesDropdown');
            if (dd) dd.style.display = '';
            renderArticlesPanel();
        } catch (e) {
            if (window.showToast) showToast(e.message, 'error');
        }
    }

Object.assign merges rather than replaces the titles, so a title picked for an unsaved item link (which the server does not know about yet) is kept. The click-outside handler in init() leaves the dropdown open while the picker modal is in use:

            const aDd = document.getElementById('articlesDropdown'), aBtn = document.getElementById('articlesBtn');   // GH #433
            if (aDd && aDd.style.display !== 'none' && !(aBtn && aBtn.contains(e.target)) && !aDd.contains(e.target)
                && !e.target.closest('#articlePickerModal')) closeArticlesPanel();

Right-click menus

Both the node and the shape menu gain two items:

                { label: M('open_article'), disabled: !n.article_id || kbTitle(n.article_id) === null, act: () => openArticle(n.article_id) },
                { label: M('link_article'), disabled: !ed || !canReadKb, act: () => openArticlePicker(a => setItemArticle(n, a)) },

Same rules again: Open needs a readable link, Link needs edit rights and the Knowledge module.

Public surface

    window.NM = {
        toggleArticlesPanel, closeArticlePicker, onArticleSearchInput,   // GH #433: Knowledge articles
        init,
        ...

Only what the inline onclick / oninput handlers in network-mapper/diagram.php need.

The Knowledge side

knowledge/index.php tells the page whether to ask at all:

window.KB_SHOW_DIAGRAMS = <?php echo analystCanAccessModule(connectToDatabase(), (int)$_SESSION['analyst_id'], 'network-mapper') ? 'true' : 'false'; ?>;   // GH #433

renderArticleDetail() in assets/js/knowledge.js adds <div id="kbDiagrams"> after the Projects card and mounts it:

    // GH #433: the network diagrams that use this article - linked from the diagram's side.
    if (window.KB_SHOW_DIAGRAMS) kbMountDiagrams(document.getElementById('kbDiagrams'), currentArticle.id);
async function kbMountDiagrams(host, articleId) {
    if (!host) return;
    host.innerHTML = '';
    host.hidden = true;
    try {
        const r = await fetch('../api/network-mapper/articles.php?article_id=' + encodeURIComponent(articleId), { credentials: 'same-origin' });
        const d = await r.json();
        const rows = (d && d.success && d.diagrams) || [];
        if (!rows.length || !currentArticle || currentArticle.id !== articleId) return;
        const how = x => window.t(x.how === 'related' ? 'knowledge.diagrams.related' : 'knowledge.diagrams.item');
        host.innerHTML = '<div class="pl-card"><div class="pl-head"><span class="pl-title">' + escapeHtml(window.t('knowledge.diagrams.title'))
            + ' <span class="pl-count">' + rows.length + '</span></span></div><div class="pl-body"><ul class="pl-list">'
            + rows.map(x => '<li class="pl-row"><a class="pl-main" href="../network-mapper/diagram.php?id=' + encodeURIComponent(x.id) + '">'
                + '<span class="pl-dot" style="background:var(--nm-accent, #06b6d4)"></span>'
                + '<span class="pl-text"><span class="pl-name">' + escapeHtml(x.title) + '</span>'
                + '<span class="pl-sub">' + (x.version_label ? escapeHtml(x.version_label) + ' &middot; ' : '') + escapeHtml(how(x)) + '</span></span></a></li>').join('')
            + '</ul></div></div>';
        host.hidden = false;
    } catch (e) {
        // not shown - the article reads the same without it
    }
}
  • It reuses the pl-* card classes from the Projects card (assets/js/project-links.js), so the two read as one family.
  • currentArticle.id !== articleId guards against a slow answer arriving after the reader has moved to another article.
  • Nothing at all is drawn when there are no diagrams, and any error is swallowed: the card is a bonus, never a reason the article fails to show.
  • The link is to the diagram id the server returned, which is always the current version.

Part 2 - Export to Download or Save to Files

The menu (assets/js/network-mapper.js)

The toolbar buttons in network-mapper/diagram.php now call the menu:

<button class="nm-btn secondary nm-export-btn" id="exportPngBtn" onclick="NM.exportMenu(event, 'png')" ...>
<button class="nm-btn secondary nm-export-btn" id="exportPdfBtn" onclick="NM.exportMenu(event, 'pdf')" ...>
    function exportMenu(e, kind) {
        const run = kind === 'pdf' ? exportPdf : exportPng;
        if (!e || !window.NM_FILES || !window.SaveToFiles) { run('download'); return; }   // no button to anchor a menu to: just download
        e.stopPropagation();
        const r = e.currentTarget.getBoundingClientRect();
        showCtxMenu(r.left, r.bottom + 4, [
            { label: t('common.documents.download'), act: () => run('download') },
            { label: t('common.save_to_files.title'), act: () => run('files') }
        ]);
    }
  • Without the Files module, nothing changes: the button downloads, exactly as before. window.NM_FILES is set by the page from the module check, so nobody is offered a dialog that would only say "no access".
  • The menu is the editor's own right-click menu (showCtxMenu()), placed under the button. No new widget, and it closes the same way as every other menu.
  • stopPropagation() stops the document click handler closing the menu in the same click that opened it.
  • Both labels are existing shared strings (common.documents.download, common.save_to_files.title), so they match the Documents panel word for word in every language.

network-mapper/diagram.php loads the pieces:

    <link rel="stylesheet" href="../assets/css/save-to-files.css?v=1">   <?php /* PNG / PDF -> Save to Files */ ?>
    <script>window.NM_FILES = <?php echo analystCanAccessModule(connectToDatabase(), (int)$_SESSION['analyst_id'], 'files') ? 'true' : 'false'; ?>;</script>   <?php /* exports can go to Files */ ?>
    <script src="../assets/js/save-to-files.js?v=3"></script>

Making a Blob instead of a download

Before, PNG went out as canvas.toDataURL() on an <a download>, and PDF through doc.save(). Neither gives you the bytes. Both now produce a Blob and hand it to one function:

    async function exportPng(mode) {
        const result = await captureCanvas();
        if (!result) return;
        const blob = await new Promise(res => result.canvas.toBlob(res, 'image/png'));
        if (!blob) return;
        deliverExport(blob, exportFilename('png'), mode, 'network-mapper.toast.png_exported');
    }
        doc.addImage(result.canvas.toDataURL('image/png'), 'PNG', 0, 0, pageW, pageH);
        deliverExport(await doc.output('blob'), exportFilename('pdf'), mode, 'network-mapper.toast.pdf_exported');

canvas.toBlob() is callback-only, hence the Promise wrapper. It can hand back null (a canvas too large for the browser), which is checked. doc.output('blob') is the shared PDF writer's way to get the finished file without saving it (see PDF writer - Developer Guide).

    function deliverExport(blob, name, mode, toastKey) {
        if (mode === 'files' && window.SaveToFiles) {
            window.SaveToFiles.open({ blob: blob, name: name });
            return;
        }
        // Browser-native download via a one-shot <a download> click
        const url = URL.createObjectURL(blob);
        const link = document.createElement('a');
        link.download = name;
        link.href = url;
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        setTimeout(() => URL.revokeObjectURL(url), 10000);
        if (window.showToast) showToast(t(toastKey), 'success');
    }
  • One path for both formats, so the download and the save always get the same file and the same name (exportFilename(): the title and version, slugged).
  • The download now uses an object URL instead of a data URL. A large diagram at scale: 2 makes a data URL of many megabytes; an object URL is a short pointer. It is revoked after 10 seconds, long enough for the browser to start the download.
  • No toast on the Files path: the dialog says "Saved as ..." itself.

The dialog: SaveToFiles.open({ blob, name })

assets/js/save-to-files.js keeps one dialog for every source. The new kind of call carries the bytes instead of a source and id:

 *   window.SaveToFiles.open({ source: 'email_attachment' | 'document', id, name, ticket: bool })
 *   window.SaveToFiles.open({ blob, name })   something the page has just made - a diagram's
 *                                             PNG or PDF, a report (export formats only:
 *                                             FilesSave::saveExport)

The folder list, the filter box, the default folder and the name-clash buttons are all unchanged. Only the send differs:

    function sendExport(o, folderId, onConflict) {
        var fd = new FormData();
        fd.append('source', 'export');
        fd.append('name', o.name || 'export');
        fd.append('folder_id', String(folderId));
        fd.append('on_conflict', onConflict || 'ask');
        fd.append('file', o.blob, o.name || 'export');
        return fetch(API, { method: 'POST', credentials: 'same-origin', body: fd })
            .then(function (r) { return r.json(); })
            .then(function (j) { if (!j.success) throw new Error(j.error || 'Error'); return j; });
    }
                (o.blob ? sendExport(o, parseInt(sel.value, 10), onConflict)
                        : call({ source: o.source, id: o.id, folder_id: parseInt(sel.value, 10), ticket_folder: !!(tick && tick.checked), on_conflict: onConflict || 'ask' }))
  • Multipart, not JSON, because the body is a file. No Content-Type header is set: the browser must write it, with the multipart boundary.
  • On a name clash the server answers {conflict: true, choices, default} and the dialog asks, then calls send(choice) again. With a blob that means the bytes are sent again with the choice; nothing is held on the server between the two requests. A diagram export is small enough that this is simpler than a staged upload.
  • The answer has the same shape as the other sources (item_id, name, open_url), so the "Saved as ... Open in Files" line works unchanged.
  • The "In a folder for this ticket" box only appears for o.ticket, so an export never sees it.
  • CSRF: assets/js/csrf.js adds X-CSRF-Token to this fetch() like any other same-origin POST, so sendExport() does nothing special. csrfRequireWriteMethod() in the endpoint refuses anything that is not a POST.

The endpoint: api/files/save_from.php

    csrfRequireWriteMethod();
    if (isset($_FILES['file'])) {
        // Something the page made in the browser - sent with the request, not held here yet.
        $f = $_FILES['file'];
        if (($f['error'] ?? UPLOAD_ERR_NO_FILE) !== UPLOAD_ERR_OK || !is_uploaded_file($f['tmp_name'])) filesApiFail('The file did not arrive.');
        try {
            $r = FilesSave::saveExport($conn, $analystId, $f['tmp_name'], (string)($_POST['name'] ?? $f['name'] ?? ''),
                                       (int)($_POST['folder_id'] ?? 0), (string)($_POST['on_conflict'] ?? 'ask'));
            if (!empty($r['item_id'])) $r['open_url'] = BASE_URL . 'files/?item=' . (int)$r['item_id'];
            filesApiOk($r);
        } catch (ServiceError $e) {
            filesApiFail($e->getMessage(), $e->kind === 'forbidden' ? 403 : ($e->kind === 'not_found' ? 404 : 200));
        }
    }
  • is_uploaded_file() proves the path really is PHP's temp file for this request. Without it, any path string reaching saveExport() could be read off the server's disk and copied into Files.
  • The endpoint is still a Files endpoint: includes/files/api_bootstrap.php signs the request in and runs requireModuleAccessJson('files') before anything here.
  • The error mapping is the same as the existing JSON branch, so the dialog shows the server's sentence either way.

The rule: FilesSave::saveExport()

includes/services/files_save.php:

    /** Export formats a page may save straight into Files, by extension => what the bytes must start with. */
    public const EXPORT_TYPES = [
        'png'  => "\x89PNG\r\n\x1a\n",
        'jpg'  => "\xFF\xD8\xFF",
        'jpeg' => "\xFF\xD8\xFF",
        'pdf'  => '%PDF-',
        'xlsx' => "PK\x03\x04",
        'csv'  => '',            // text: checked below instead
    ];
    public static function saveExport(PDO $conn, int $analystId, string $localPath, string $name, int $folderId, string $onConflict = 'ask'): array
    {
        if (!analystCanAccessModule($conn, $analystId, 'files')) throw new ServiceError('forbidden', 'forbidden', 'You do not have access to Files.');
        if (FilesAcl::level($conn, $analystId, $folderId) < FilesAcl::UPLOAD) throw new ServiceError('forbidden', 'forbidden', 'You cannot save into that folder - it needs Upload.');
        $ext = strtolower(pathinfo($name, PATHINFO_EXTENSION));
        $bad = new ServiceError('validation', 'invalid_field', 'Only a PNG, JPEG, PDF, CSV or Excel export can be saved this way.');
        if (!array_key_exists($ext, self::EXPORT_TYPES) || !is_file($localPath)) throw $bad;
        $head = (string)file_get_contents($localPath, false, null, 0, 4096);
        $magic = self::EXPORT_TYPES[$ext];
        if ($magic !== '' && strncmp($head, $magic, strlen($magic)) !== 0) throw $bad;
        // text, not a binary renamed .csv - the whole file, not just its first 4 KB
        if ($ext === 'csv' && ($head === '' || self::fileHas($localPath, ["\0"]) !== [])) throw $bad;
        // TRAP: "PK\x03\x04" starts EVERY zip - a .docx, a .jar or any archive. A workbook also names
        // [Content_Types].xml and xl/workbook.xml in its entries (stored uncompressed in the zip's headers).
        if ($ext === 'xlsx' && count(self::fileHas($localPath, ['[Content_Types].xml', 'xl/workbook.xml'])) !== 2) throw $bad;
        return filesStoreLocalFile($conn, $analystId, $folderId, $localPath, $name, $onConflict) + ['folder_id' => $folderId];
    }

Why a whitelist, and why the bytes

The other two sources copy a file FreeITSM already holds, so the server can check where it came from (the ticket, the document's record). An export arrives from the browser: the server has no record of it and cannot know the page really made it. Without limits this endpoint would be a second Upload, one without the Files page's own screen, its upload rules or its audit wording, and anything (an .html page, an .svg with script, an .exe) could be written into any folder the person can upload to, under any name. So:

  • Only formats a page exports. Images, PDF, CSV and Excel: the things a report or diagram produces. Anything else, including .html, .svg and .exe, is refused whatever it holds. Real uploads still go through Files.
  • The bytes must be what the name says. Each binary format starts with fixed magic bytes. HTML renamed x.png fails the PNG check, so a file cannot be smuggled in under an innocent extension and later opened by the viewer as something else. Only the first 4 KB is read, which is plenty for a signature.
  • CSV has no signature, so it is checked the other way round: it must not be empty and must not contain a NUL byte, which plain text never does and almost every binary does. That stops an executable renamed .csv. The NUL check reads the whole file (fileHas(), below) - until 5.11.0 it read only the first 4 KB, so a binary behind 4 KB of commas got through.
  • An .xlsx is a zip, and PK\x03\x04 starts every zip - a Word file, a .jar, any archive. So a workbook must also name the two entries every workbook has, [Content_Types].xml and xl/workbook.xml. Entry names are stored uncompressed in a zip's headers, so they can be found in the bytes without the zip extension:
    private static function fileHas(string $path, array $needles): array
    {
        $found = [];
        $keep = max(array_map('strlen', $needles)) - 1;
        $fh = fopen($path, 'rb');
        if (!$fh) return [];
        $tail = '';
        while (!feof($fh) && count($found) < count($needles)) {
            $chunk = $tail . (string)fread($fh, 1048576);
            foreach ($needles as $n) {
                if (!in_array($n, $found, true) && strpos($chunk, $n) !== false) $found[] = $n;
            }
            $tail = $keep > 0 ? substr($chunk, -$keep) : '';
        }
        fclose($fh);
        return $found;
    }

The chunk overlap ($keep, one byte less than the longest needle) is what finds a name split across two 1 MB reads.

  • After that, it is an ordinary save. The Files module, Upload (FilesAcl::UPLOAD) on the folder, and then filesStoreLocalFile(): the same name cleaning, the same largest-upload limit, Overwrite needing Modify, the Files -> Settings -> Versions choices, the audit row (upload or new_version) and the storage move queue as a ticket attachment saved into Files. That function and its TRAP are on Save to Files - Developer Guide.
  • The checks run in order of cost: module, then folder, then extension, then reading bytes. A refused folder never causes a file read.
  • One message for every format failure. "Not a format" and "bytes do not match" are the same error, so the endpoint does not tell anyone which check they nearly passed.

Adding Save to Files to another page's export

Any page that builds a file in the browser can offer the same choice. The server side needs nothing new as long as the format is in EXPORT_TYPES.

In the page's PHP:

<link rel="stylesheet" href="../assets/css/save-to-files.css?v=1">
<script>window.MY_FILES = <?php echo analystCanAccessModule(connectToDatabase(), (int)$_SESSION['analyst_id'], 'files') ? 'true' : 'false'; ?>;</script>
<script src="../assets/js/save-to-files.js?v=3"></script>

Where the export used to download:

const blob = new Blob([csvText], { type: 'text/csv' });   // or canvas.toBlob(), or doc.output('blob')
const name = 'asset-register-2026-11-24.csv';            // the extension decides the check
if (window.MY_FILES && window.SaveToFiles) window.SaveToFiles.open({ blob: blob, name: name });
else { /* the existing download */ }

That is the whole of it. The dialog lists the folders the person can upload to, handles the name clash, and links to the saved file. Things to know:

  • The extension in name must match the bytes. A CSV called .xlsx is refused. An XLSX must be a real workbook (PK\x03\x04, plus [Content_Types].xml and xl/workbook.xml among its entries).
  • Offer it only with the Files module, as exportMenu() does with window.NM_FILES. The server refuses anyway; the check just avoids a dead end.
  • A new format means a new line in FilesSave::EXPORT_TYPES with its magic bytes, the wording of the $bad message, and a positive and negative check in tests/files-save-export.php. Do not add a text format other than CSV without its own text check, and never add html, svg, js or anything a browser would run.
  • Load assets/js/save-to-files.js at the same ?v= as every other page that loads it (see Traps).

Traps

  • TRAP: allowedForSave() must run before the save's transaction starts. It reads what is on the diagram now. Once replaceContents() / replaceShapes() have deleted the rows, "already linked" is empty, and every save by someone who cannot read a colleague's article silently strips that link. Both createDiagram() and saveDiagram() compute $articles before beginTransaction().
  • TRAP: every title must come from readable(). Do not add a JOIN knowledge_articles to api/network-mapper/get_diagram.php or anywhere else to "save a query". The title is the one thing that must not reach someone Knowledge would not show the article to.
  • TRAP: an empty titles must encode as {}. api/network-mapper/get_diagram.php swaps in new stdClass(), and loadDiagram() checks !Array.isArray(). An empty PHP array is [] in JSON, and [] with numeric keys set on it later behaves differently.
  • TRAP: GET articles.php?article_id= sits above requireModuleAccessJson('network-mapper') on purpose. The Knowledge reader calls it for people who may not have Network Mapper; they must get {success: true, diagrams: []}, not a 403. Do not move the module check up.
  • TRAP: knowledgeVisibilitySql()'s default lifecycle is live. Every call in includes/services/network_articles.php passes one on purpose: any for links that already exist (readableRows()), unarchived for the picker (search()). A new call that leaves it out brings back the 5.10 bug where a linked draft or archived article read "An article you don't have access to" - even to its author.
  • TRAP: the related list writes straight away; item links wait for Save. They look alike on screen. An item link set and then abandoned with "leave without saving" is lost; a related article is not.
  • TRAP: the book's mousedown must stop propagation. Without it, clicking the book selects the node and starts a drag. The .is-exporting rule keeps the book out of PNG and PDF exports; a new decoration on items needs the same rule.
  • TRAP: assets/js/save-to-files.js is loaded once per page: if (window.SaveToFiles) return;. The Documents panel (includes/documents_panel.php) and tickets/index.php load it too. If one page loads two different ?v= values, whichever loads first wins, and v=2 has no blob support. When the file changes, bump every ?v= together (grep for assets/js/save-to-files.js?v=).
  • TRAP: the export branch of api/files/save_from.php is chosen by the presence of $_FILES['file'], not by the source=export field, which the server does not read. A multipart POST with a file always goes to saveExport().
  • TRAP: filesStoreLocalFile() writes a Files item the way api/files/upload.php's finish step does (bytes, rows, queueIfMoved, keep-N / overwrite). This is the existing TRAP in includes/services/files_save.php; exports go through it too, so a change to either path is a change to three callers now.
  • TRAP: on a name clash the blob is sent twice. The first request asks; the choice resends the whole file. Fine for a diagram; a page that exports something very large should keep that in mind (the largest-upload limit in Files -> Settings applies to each request).

Tests

Both are CLI scripts that refuse to run over the web, need FREEITSM_TEST_DATABASE set to the database the install's config.php uses (they skip otherwise), and clean up after themselves in finally.

FREEITSM_TEST_DATABASE=<throwaway db> FREEITSM_TEST_URL=http://localhost/<that install> php tests/network-mapper-articles.php
FREEITSM_TEST_DATABASE=<throwaway db> FREEITSM_TEST_URL=http://localhost/<that install> php tests/files-save-export.php

tests/network-mapper-articles.php

It works as an ordinary analyst (not an administrator) who has both Knowledge and Network Mapper and does not hold Cap::KNOWLEDGE_MANAGE, because a Knowledge manager passes the administrator floor and would see everything, proving nothing. It skips if no such analyst exists. It makes two ZZ articles, one open and one Restricted with no grants, and a ZZ diagram.

Who can read what

  1. POSITIVE CONTROL: readable() returns the open article with its title. Without this, the next check could pass because nothing is readable at all.
  2. ...but not the Restricted one.
  3. search('ZZ ') offers the open article and not the Restricted one.
  4. A draft and an archived article are readable, with their titles and states (readableRows()), not "no access".
  5. ...while a Restricted draft is still not readable: the lifecycle is lifted, not the permission.
  6. The picker offers the draft (state draft) but not the archived article, and the open one as live.

Related articles 7. The analyst can addRelated() the open article; adding the Restricted one throws, and the related list is just the open one. 8. After a colleague's row for the Restricted article is put straight into network_diagram_articles, forDiagram() for the analyst has both ids in titles, the Restricted one with null. 9. ...and the analyst may still removeRelated() it. 10. A linked draft and a linked archived article come back from forDiagram() with their titles and states, and a published one has no state. 11. ...and the draft lists the diagram back on its own page (diagramsForArticle()).

Links on shapes and nodes 12. A save by the analyst with two shapes keeps the open article's link and drops the Restricted id typed into the request. 13. After a colleague links the Restricted article to that shape (direct UPDATE), the analyst's next save keeps it. 14. A node keeps its article through saveDiagram() (when the database has a CMDB object to use).

Versions and the way back 15. createVersion() copies the related list. 16. ...and every shape's and node's article_id. 17. diagramsForArticle() for the open article lists only the new current version, not the old one. 18. ...and for the Restricted article lists nothing to the analyst who cannot read it. 19. addRelated() on the old version throws (historical, read-only).

When the article goes 20. Deleting the Restricted article removes its network_diagram_articles rows (CASCADE) and sets article_id to NULL on the shapes in both versions (SET NULL); the shapes themselves stay.

Then cleaned up: no ZZ % article rows left.

tests/files-save-export.php

It makes a top-level ZZ folder with its own permissions (Full for the administrator only, inherit_permissions = 0) and calls FilesSave::saveExport() directly. Skips if Files is off.

  1. POSITIVE CONTROL: a real 1x1 PNG is saved, with the name it was given.
  2. ...and a PDF (%PDF-1.4).
  3. ...and a CSV.
  4. Saving the same PNG name again answers conflict with choices, exactly as an upload does.
  5. HTML with a <script> renamed .png is refused.
  6. A PDF renamed .png is refused: the bytes must match the name, not just be some allowed format.
  7. A format that is not an export (.html, .svg, .exe) is refused even when it holds valid PNG bytes.
  8. A binary (an MZ header with NULs) renamed .csv is refused.
  9. ...even when the binary part starts after 4 KB of CSV text (the whole file is checked).
  10. POSITIVE CONTROL: a workbook (a real zip from ZipArchive when the extension is there) saves as .xlsx.
  11. A Word file renamed .xlsx is refused - it starts PK like every zip.
  12. ...and so is any other zip.
  13. A folder that does not exist is refused.

Then cleaned up: the stored bytes deleted from the active store, the version, item, permission and folder rows removed, and the temp files unlinked.

No automated test covers the browser half (the menu, toBlob(), the dialog opening with the blob); check it by hand after changing exportMenu(), deliverExport() or assets/js/save-to-files.js.


See also: Network Mapper - Developer Guide Β· Network Mapper - Shapes and Layers - Developer Guide Β· Network Mapper - Icon Libraries - Developer Guide Β· Network Mapper Β· Save to Files - Developer Guide Β· Files - Developer Guide Β· Knowledge folders and security - Developer Guide Β· CSRF Protection - Developer Guide Β· PDF writer - Developer Guide Β· Developer Tests: Knowledge Β· Analysts Leaving

FreeITSM

Getting Started

Modules

Multi-tenancy (planned)

Responses to feedback

Blue sky thinking

Bugs resolved

Pull requests

Links

Clone this wiki locally