Repository navigation
Network Mapper Shapes and Layers Developer Guide
Part 1 of 2 Β· Part 2: multi-select, connectors, menus and saving Β· the basics this builds on: Network Mapper - Developer Guide Β· what the analyst sees: Network Mapper
Before GH #433 a diagram was CMDB nodes and the lines between them, nothing else. In November 2026 the editor grew everything a draw.io user expects: a node can have its own colour, box size and look; freestanding shapes (rectangles, flowchart symbols, arrows, zones, text, notes) sit beside the nodes; a diagram has pages (tabs) and each page has layers that can be hidden or locked; several things can be selected, aligned and grouped; a connector can join anything (node or shape) and has its own colour, arrowheads and routing; and every item has a right-click menu.
None of it changed the save model described in the basics page: the browser still sends the whole diagram and the server still deletes and re-inserts every row. What is new is that the things which must survive that (which page an item is on, which layer, which group, which shape a connector ends on) are carried as small stable keys chosen by the browser, never as row ids. That idea runs through both parts of this guide.
This part covers the tables, node styling, shapes, and pages and layers. Part 2 covers multi-select and grouping, connectors, the right-click menus, how saving and versions carry all of it, the traps and the tests.
Not covered here: icon libraries and My images (shape_type = 'icon') are in Network Mapper - Icon Libraries - Developer Guide; the article_id columns, the Articles panel and PNG / PDF export are in Network Mapper - Knowledge and Export - Developer Guide.
Key: ποΈ schema Β· π read Β· βοΈ write Β· π REST Β· π₯οΈ UI Β· π§ͺ test
| π¨ | File | What it does |
|---|---|---|
| ποΈ | database/freeitsm.sql |
Fresh-install DDL: the new columns on network_diagram_nodes and network_diagram_connectors, and the tables network_diagram_shapes, network_diagram_pages, network_diagram_layers, with a comment block on each |
| ποΈ | includes/db_verify_schema.php |
The $schema entries DB Verify builds columns from on a grown install |
| ποΈ | api/system/db_verify.php |
Network Mapper foreign keys, the orphan sweep that runs before them, and the one-off relaxing of from_node_id / to_node_id to NULL |
| ποΈ | includes/db_verify_indexes.php |
GENERATED by scripts/gen_db_verify_indexes.php - the uq_net_page and uq_net_layer unique keys and the shape indexes. Never edit by hand |
| π | api/network-mapper/get_diagram.php |
Returns nodes (with colour_override, w, h, style, page_key, layer_key, group_key), connectors (with the shape ends and style), shapes, pages and layers
|
| βοΈ | api/network-mapper/save_diagram.php |
Thin adapter: maps the editor's payload onto NetworkMapperService::saveDiagram() and passes shapes, pages and layers straight through |
| βοΈ | includes/services/network_mapper.php |
NetworkMapperService - replaceContents(), replaceShapes(), replacePages(), sanitiseStyle(), sanitiseConnectorStyle(), keyOf(), groupOf(), and createVersion() copying all of it |
| βοΈ | api/network-mapper/create_version.php |
Calls NetworkMapperService::createVersion() - unchanged, but the service now copies shapes, pages and layers too |
| π | api/v1/resources/network_mapper.php |
The REST resource: GET returns all of it (node look and place, shape ends, shapes, pages, layers), so a read-then-write keeps it - see Part 2 |
| π₯οΈ | assets/js/network-mapper.js |
The editor (one IIFE, window.NM). Every section below lives here |
| π₯οΈ | assets/js/network-mapper-shapes.js |
The shape library (window.NM_SHAPES) and the style renderers nmShapeStyle, nmShapeSvg, nmShapeTextBox, nmShapePreview, nmTextCss, nmNodeBoxCss
|
| π₯οΈ | network-mapper/diagram.php |
Markup and inline CSS: the palette tabs, the page tab bar, the Layers dropdown, the node panel's Colour / Icon size / Box size / Layer / Style rows, the Format panel (#shapeFormatPanel), and the .nm-shape*, .has-colour, .has-style, .nm-ctx-menu, .nm-band rules |
| π₯οΈ | lang/en/network-mapper.php |
The strings, under detail, connector, shapes, menu, select, pages, layers and style (and the same keys in every other locale) |
| π₯οΈ | includes/feature_bingo/cards/network-mapper.php |
The Feature Bingo cards for these features |
| π§ͺ | tests/network-mapper-node-style.php |
Node colour and box size |
| π§ͺ | tests/network-mapper-shapes.php |
Shapes and the style JSON |
| π§ͺ | tests/network-mapper-pages.php |
Pages, layers and group keys |
| π§ͺ | tests/network-mapper-connectors.php |
Connectors with shape ends and their style |
network_diagram_nodes gained eight columns. From database/freeitsm.sql:
-- GH #433: a node's own colour (#rrggbb; NULL = the normal look) and its box size in
-- canvas pixels (NULL = automatic: as wide as the icon, label clamped to two lines).
`colour_override` VARCHAR(20) NULL,
`w` INT NULL,
`h` INT NULL,
-- Shapes: the node's own look as JSON (fill, gradient, border, shadow, opacity,
-- rounded corners, font) - only the keys that differ from the normal look.
-- NetworkMapperService::sanitiseStyle() whitelists every key. NULL = normal.
`style` TEXT NULL,
-- Pages and layers: which page (network_diagram_pages.page_key) and which layer on it
-- (network_diagram_layers.layer_key) the node is on. 0 / 0 = the first page and its
-- first layer, which every diagram has even before it has any page rows.
`page_key` INT NOT NULL DEFAULT 0,
`layer_key` INT NOT NULL DEFAULT 0,
-- A group: nodes and shapes on the same page with the same group_key move and select
-- together (Group / Ungroup in the editor). NULL = not grouped.
`group_key` VARCHAR(40) NULL,Every one of them is NULL or defaults to 0, so a row written before #433 means exactly what it meant before: the normal look, page 0, layer 0, no group. That is why nothing had to be migrated. (article_id arrived in the same series; see the Knowledge page.)
network_diagram_connectors changed shape more than it grew:
-- GH #433: an end is a node (from_node_id / to_node_id) OR a shape (from_shape_uid /
-- to_shape_uid - network_diagram_shapes.uid, stable across saves where row ids are not).
`from_node_id` INT NULL,
`to_node_id` INT NULL,
`from_shape_uid` VARCHAR(20) NULL,
`to_shape_uid` VARCHAR(20) NULL,
`cmdb_relationship_id` INT NULL,
`label` VARCHAR(255) NULL,
`line_style` VARCHAR(20) NULL DEFAULT 'solid',
-- The line's own look as JSON: colour, width, arrowStart, arrowEnd (none / arrow / open /
-- diamond / circle), routing (straight / elbow / curved). NULL = the normal grey arrow.
`style` TEXT NULL,from_node_id and to_node_id used to be NOT NULL. A grown install has the old definition, and the $schema array in includes/db_verify_schema.php only adds missing columns, it never alters one. So api/system/db_verify.php carries a dedicated step:
// GH #433: a connector end can now be a shape, so its node columns may be NULL. Relaxing a
// NOT NULL cannot invalidate an existing row (every one has both nodes), and the foreign keys
// still hold - a NULL has nothing to check.
if ($tableExists('network_diagram_connectors')) {
try {
$cc = $conn->prepare("SELECT column_name, is_nullable FROM information_schema.columns
WHERE table_schema = ? AND table_name = 'network_diagram_connectors' AND column_name IN ('from_node_id', 'to_node_id')");
$cc->execute([$dbName]);
foreach ($cc->fetchAll(PDO::FETCH_NUM) as [$col, $nullable]) {
if (strtoupper($nullable) === 'NO') {
$conn->exec("ALTER TABLE `network_diagram_connectors` MODIFY `$col` INT NULL");Until DB Verify has run, a save with a connector ending on a shape fails on the NOT NULL, and the whole save rolls back. That is the right failure: nothing is half-written.
CREATE TABLE IF NOT EXISTS `network_diagram_shapes` (
`id` INT NOT NULL AUTO_INCREMENT,
`diagram_id` INT NOT NULL,
`shape_type` VARCHAR(40) NOT NULL,
`x` INT NOT NULL DEFAULT 0,
`y` INT NOT NULL DEFAULT 0,
`w` INT NOT NULL DEFAULT 120,
`h` INT NOT NULL DEFAULT 80,
`rotation` INT NOT NULL DEFAULT 0,
`text` TEXT NULL,
`style` TEXT NULL,
`layer` VARCHAR(10) NOT NULL DEFAULT 'back',
`z` INT NOT NULL DEFAULT 0,
-- An icon from an imported icon library (shape_type 'icon'); NULL for drawn shapes, and
-- for an icon whose library was removed (the shape keeps its place, loses the picture).
`icon_id` INT NULL,
`page_key` INT NOT NULL DEFAULT 0, -- as network_diagram_nodes.page_key
`layer_key` INT NOT NULL DEFAULT 0,
`group_key` VARCHAR(40) NULL, -- as network_diagram_nodes.group_key
-- A stable id for connectors to point at (letters, digits, _ and -). Row ids change on
-- every save because shapes are replaced; this does not.
`uid` VARCHAR(20) NULL,Three columns sound alike and are not:
| Column | Means | Values |
|---|---|---|
layer |
Behind or in front of the CMDB nodes and the connector lines |
back / front
|
layer_key |
Which user layer of the page (the Layers panel) | a small number, network_diagram_layers.layer_key
|
z |
Order among shapes | any integer, larger is on top |
shape_type is a free VARCHAR(40), not an ENUM and not a foreign key. The comment above the table says why: an unknown key draws as a rectangle, so the library can grow without a schema change, and a diagram saved by a newer version still opens in an older one.
-- Pages and layers: a diagram has tabs (pages); each page has layers that can be hidden or
-- locked. Items carry page_key / layer_key - small numbers stable across saves and versions
-- (rows are replaced on every save, ids are not stable). A diagram with no rows here is one
-- page with one layer, key 0 / 0. sort orders tabs left to right and layers bottom to top.
CREATE TABLE IF NOT EXISTS `network_diagram_pages` (
`id` INT NOT NULL AUTO_INCREMENT,
`diagram_id` INT NOT NULL,
`page_key` INT NOT NULL DEFAULT 0,
`name` VARCHAR(100) NOT NULL,
`sort` INT NOT NULL DEFAULT 0,
PRIMARY KEY (`id`),
UNIQUE KEY `uq_net_page` (`diagram_id`, `page_key`),
CONSTRAINT `fk_net_page_diag` FOREIGN KEY (`diagram_id`) REFERENCES `network_diagrams` (`id`) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
CREATE TABLE IF NOT EXISTS `network_diagram_layers` (
`id` INT NOT NULL AUTO_INCREMENT,
`diagram_id` INT NOT NULL,
`page_key` INT NOT NULL DEFAULT 0,
`layer_key` INT NOT NULL DEFAULT 0,
`name` VARCHAR(100) NOT NULL,
`sort` INT NOT NULL DEFAULT 0,
`visible` TINYINT(1) NOT NULL DEFAULT 1,
`locked` TINYINT(1) NOT NULL DEFAULT 0,
PRIMARY KEY (`id`),
UNIQUE KEY `uq_net_layer` (`diagram_id`, `page_key`, `layer_key`),Layers are their own table, keyed by (diagram_id, page_key, layer_key), not a JSON column on the page. A layer belongs to a page through page_key, never through network_diagram_pages.id - that id is replaced on every save, so a foreign key to it would break each time. Nothing joins items to these tables in SQL: an item's page_key / layer_key are matched in the browser.
Why the keys and not the ids: every save deletes and re-inserts pages, layers, nodes and shapes, so every id is new after a save. A key is a small number the browser picks (nextPageKey(), addLayer()) and sends back unchanged, so a node saved with page_key = 1, layer_key = 3 still points at the same tab and the same layer after any number of saves and version copies.
visible and locked are saved per layer. Hiding a layer is therefore part of the diagram, not a viewer preference - see "Read-only versions" below for the one exception.
size (small / medium / large) is the old column and now only sets the icon size. The box around the icon is new: w / h NULL means the old automatic box. The editor's model of a node's outer box is nodeExtent():
/** True when the node has its own box size (w/h set), rather than the automatic one. */
function hasBoxSize(n) { return !!(n && (n.w || n.h)); }
/**
* A node's outer box in canvas px: its own size, or the automatic one (icon plus padding, with the
* label hanging about 40px below). Used to frame fit, centre and export.
*/
function nodeExtent(n) {
const sz = NODE_SIZES[n.size] || NODE_SIZES.medium;
return { w: n.w || (sz + NODE_PADDING * 2), h: n.h || (sz + NODE_PADDING * 2 + 40) };
}Fit, Centre, export, rubber-band hit tests, align and distribute all use nodeExtent(). If you add something that needs a node's size, use it too; the icon size alone is wrong for any node with its own box.
buildNodeEl() applies the three looks as classes plus inline values:
if (hasBoxSize(n)) {
// GH #433: its own box - the label gets the full width and is no longer cut to two lines.
el.classList.add('has-size');
el.style.boxSizing = 'border-box';
el.style.width = nodeExtent(n).w + 'px';
if (n.h) el.style.minHeight = n.h + 'px';
}
if (n.colour_override) {
// GH #433: custom properties, not inline border/background, so the selected ring still wins.
el.classList.add('has-colour');
el.style.setProperty('--nmc', n.colour_override);
el.style.setProperty('--nmc-bg', hexToRgba(n.colour_override, 0.12));
}
if (n.style && window.nmNodeBoxCss) {
// GH #433: the node's own fill, border, shadow, corners and opacity (font goes on the label below)
el.classList.add('has-style');
el.style.cssText += window.nmNodeBoxCss(n.style);
}The colour goes through custom properties, and that is deliberate. An inline border-color would beat the stylesheet's .nm-node.selected cyan ring, so a selected coloured node would show no selection. With custom properties the stylesheet in network-mapper/diagram.php decides:
.nm-node.has-colour { border-color: var(--nmc); background: var(--nmc-bg); }
.nm-node.has-colour:hover { border-color: var(--nmc); }
.nm-node.has-colour .nm-node-icon { color: var(--nmc); }
.nm-node.has-colour.selected { border-color: #06b6d4; }
.nm-node.has-size { justify-content: center; } /* icon + name centred as one group in a taller box */.nm-node-icon { color: var(--nmc) } works because the CMDB icons are drawn with currentColor, so one property recolours the picture.
The side panel's eight swatches are NODE_COLOURS, plus an <input type="color"> for anything else; setNodeColour() lower-cases the value. The server is strict about the format and refuses rather than cleans:
// GH #433: a node's own colour and box size - all optional, NULL = the normal look.
$colour = null;
if (isset($n['colour_override']) && trim((string)$n['colour_override']) !== '') {
$colour = strtolower(trim((string)$n['colour_override']));
if (!preg_match('/^#[0-9a-f]{6}$/', $colour)) {
throw new ServiceError('validation', 'invalid_field', "nodes[{$index}]: 'colour_override' must be a colour like #2563eb.");
}
}
$dim = function (string $k) use ($n, $index): ?int {
if (!isset($n[$k]) || $n[$k] === '') return null;
$v = (int)$n[$k];
if ($v < 20 || $v > 2000) {
throw new ServiceError('validation', 'invalid_field', "nodes[{$index}]: '{$k}' must be between 20 and 2000.");
}
return $v;
};Compare that with the style JSON below, which is cleaned, never refused. The colour and box size are typed columns with one right shape, so a wrong value is a bug worth surfacing. The style is a bag of optional keys that will grow, so an unknown key from a newer editor must not block a save.
The bottom-right .nm-resize-handle only exists on the current version (it is part of the same handleHtml as the four edge handles) and only shows on a selected node. startNodeResize() records the starting size and a minimum that still fits the icon:
nodeResize = {
key: nodeKey(n),
start: canvasModelCoords(e),
w: el.offsetWidth,
h: el.offsetHeight,
minW: sz + NODE_PADDING * 2,
minH: sz + NODE_PADDING * 2 + 20,
moved: false
};and onNodeResizeMove() snaps to the 20px node grid and clamps at the server's 2000:
const w = Math.min(2000, Math.max(nodeResize.minW, snap(nodeResize.w + c.x - nodeResize.start.x)));
const h = Math.min(2000, Math.max(nodeResize.minH, snap(nodeResize.h + c.y - nodeResize.start.y)));Changing the icon size can make an own box too small for the new icon, so setNodeIconSize() grows it:
// An own box must still fit the bigger icon.
const ext = NODE_SIZES[size] + NODE_PADDING * 2;
if (n.w && n.w < ext) n.w = snap(ext + GRID / 2);
if (n.h && n.h < ext + 20) n.h = snap(ext + 20 + GRID / 2);In an automatic box the icon sits at NODE_PADDING from the top-left. In an own box it is centred: horizontally by arithmetic (iconOffsetX()), vertically by CSS (.has-size { justify-content: center }), which centres icon and wrapped label together. That vertical position depends on how many lines the label wraps to, which only the browser knows. So syncIconY() reads it back from the drawn element:
function syncIconY(el, n) {
const icon = el ? el.querySelector('.nm-node-icon') : null;
const sz = NODE_SIZES[n.size] || NODE_SIZES.medium;
const iy = (n.h && icon) ? icon.offsetTop : NODE_PADDING;
n._iconY = iy;
if (!el || iy === NODE_PADDING) return;
el.querySelectorAll('.nm-edge-handle').forEach(h => {
const side = h.dataset.side;
h.style.top = (side === 'top' ? iy : side === 'bottom' ? iy + sz : iy + sz / 2) + 'px';
});
}n._iconY is a cache on the node object, never saved (the save payload lists its fields explicitly). nodeIconBBox() uses it, so connector ends and connection dots land on the icon:
const ix = iconOffsetX(n); // GH #433: centred when the box has its own width
const iy = (n._iconY != null) ? n._iconY : pad; // ...and its own height (syncIconY)syncIconY() must run after the element is in the page (offsetTop is 0 on a detached element). renderNodes() and rerenderNode() both append first and call it second; keep that order in any new render path.
The same style editor that formats shapes also formats a node's box and label. NODE_STYLE_SHOWN is what an unstyled node looks like, so the controls start from the truth instead of the shape defaults:
const NODE_STYLE_SHOWN = { fill: 'solid', fillColour: '#ffffff', stroke: 'none', strokeColour: '#64748b', strokeWidth: 1.5,
opacity: 100, shadow: false, rounded: 8, font: 'sans', fontSize: 12, fontColour: '#1f2937', bold: false, italic: false, underline: false, align: 'center' };
function renderNodeStyleEditor(n) {
const box = document.getElementById('ndStyle');
if (!box) return;
renderStyleEditor(box, Object.assign({}, NODE_STYLE_SHOWN, n.style || {}), {
rounded: true, valign: false, editable: canEdit(),
onChange: patch => {
if (!canEdit()) return;
n.style = Object.assign({}, n.style || {}, patch);Note the difference from shapes: a node stores only the keys that were changed (Object.assign({}, n.style || {}, patch)), while a shape stores its full look (see "Adding a shape"). An unstyled node keeps style = NULL and the normal stylesheet look, including dark mode. nmNodeBoxCss() in assets/js/network-mapper-shapes.js turns the keys into CSS, again through custom properties for the border so the selected ring wins:
if (st.stroke === 'none') css += '--nms-bw:0px;';
else if (st.stroke) {
css += '--nms-bs:' + st.stroke + ';';
if (st.strokeWidth != null) css += '--nms-bw:' + (+st.strokeWidth) + 'px;';
if (hex(st.strokeColour)) css += '--nms-bc:' + st.strokeColour + ';';
}
if (st.rounded != null) css += 'border-radius:' + (+st.rounded) + 'px;';
if (st.shadow) css += '--nms-shadow:0 3px 9px rgba(0,0,0,0.28);'; .nm-node.has-style {
border-width: var(--nms-bw, 1.5px);
border-style: var(--nms-bs, solid);
border-color: var(--nms-bc, var(--nmc, transparent));
box-shadow: var(--nms-shadow, none);
}var(--nms-bc, var(--nmc, transparent)) is how the two features combine: a styled border colour wins, otherwise the node's own colour, otherwise none. The font keys go on the label through nmTextCss(), not on the box.
assets/js/network-mapper-shapes.js holds every shape as a definition, registered with add(key, def):
// w/h: the size a shape is dropped at. text(w,h): where its text sits (default: the whole
// shape, inset). rounded: the Rounded corners control applies. style: defaults that differ
// from SHAPE_STYLE below.
const S = {};
const add = (key, def) => { S[key] = def; };
// Basic
add('rectangle', { cat: 'basic', w: 120, h: 70, rounded: true, draw: (w, h, r) => ({ d: rrect(0, 0, w, h, r) }) });
add('rounded_rectangle', { cat: 'basic', w: 120, h: 70, rounded: true, style: { rounded: 12 }, draw: (w, h, r) => ({ d: rrect(0, 0, w, h, r) }) });
add('ellipse', { cat: 'basic', w: 120, h: 80, draw: (w, h) => ({ d: ellipse(0, 0, w, h) }), text: (w, h) => box(w * 0.15, h * 0.15, w * 0.7, h * 0.7) });There are 62 add() calls: 61 drawn shapes in the palette's five groups (basic 18, flow 24, arrows 8, containers 4, text 7) and the special icon in the library group, which is not in NM_SHAPE_CATS and so never shows as a drawn tile:
window.NM_SHAPES = S;
window.NM_SHAPE_CATS = ['basic', 'flow', 'arrows', 'containers', 'text'];Each definition's draw(w, h, r) returns SVG path data for the shape at its real size, not a 100 x 100 picture stretched with a viewBox. The file header gives the reason: stretched, a circle's border would get thicker on the long side and a rounded corner would turn oval. draw() may return three paths:
| Key | Drawn as | Used for |
|---|---|---|
d |
the filled outline, with the shadow filter | every shape |
tail |
a second filled path | supported by nmShapeSvg(), but no shape in the library returns one today |
lines |
unfilled strokes | inner detail: the cylinder's top rim, the swimlane header line, the note's folded corner |
text(w, h) returns the box the text sits in, in the shape's own pixels. A diamond's text sits in its middle 60%; or, summing_junction, collate, sort, line_h and line_v return a zero box, which means "no text". The organic shapes (cloud, heart, document waves) are written once in a 100-wide box and scaled with scaled():
function scaled(tpl, w, h, bh) {
const sx = w / 100, sy = h / (bh || 100);
let i = 0;
return tpl.replace(/-?\d+(\.\d+)?/g, m => f(parseFloat(m) * (i++ % 2 === 0 ? sx : sy)));
}That only works because the templates use absolute commands with numbers in x,y pairs. An arc (A) has seven numbers and would be scaled wrongly, which is why the arcs in the library (rrect, ellipse, cylinder, delay, display, stored_data) are built from w and h directly.
To add a shape: one add() line in a category, plus a name_<key> string under shapes in lang/en/network-mapper.php (without it shapeName() falls back to the key with spaces). No schema change, no server change - the server only checks the key's format.
const SHAPE_STYLE = {
fill: 'solid', fillColour: '#ffffff', fillColour2: '#dbeafe', gradientDir: 'down',
stroke: 'solid', strokeColour: '#64748b', strokeWidth: 1.5,
opacity: 100, shadow: false, rounded: 0,
font: 'sans', fontSize: 13, fontColour: '#1f2937', bold: false, italic: false, underline: false,
align: 'center', valign: 'middle'
}; /** The full style for a shape: library defaults, then the shape type's, then its own. */
window.nmShapeStyle = function (type, style) {
const def = S[type] || S.rectangle;
return Object.assign({}, SHAPE_STYLE, def.style || {}, style || {});
};So a zone is light blue with a dashed blue border because its definition says so, and any key the shape has of its own wins over both.
nmShapeSvg() builds one <svg> per shape. Every value that reaches the markup is either the library's own string or a colour that passed the hex test, which is why it can be built as a string:
window.nmShapeSvg = function (shape, idPrefix) {
const def = S[shape.shape_type] || S.rectangle;
const st = window.nmShapeStyle(shape.shape_type, shape.style);
const w = Math.max(1, shape.w), h = Math.max(1, shape.h);
const g = def.draw(w, h, def.rounded ? (+st.rounded || 0) : 0);
let defs = '';
let fill = 'none';
if (st.fill === 'solid') fill = hex(st.fillColour) || '#ffffff';
if (st.fill === 'gradient') {
const c1 = hex(st.fillColour) || '#ffffff', c2 = hex(st.fillColour2) || '#dbeafe';
const gid = idPrefix + '-g';S[shape.shape_type] || S.rectangle is the "unknown key draws as a rectangle" rule. idPrefix matters: gradients and the shadow filter are referenced by id, and ids are page-global, so two shapes with gradients need different ids. The editor passes 'nms-' + shapeKey(s), the palette passes 'nmpv-' + type.
In the editor, buildShapeEl() wraps the SVG in an absolutely positioned <div class="nm-shape"> with the text, the resize handles and the connection dots:
el.style.left = s.x + 'px';
el.style.top = s.y + 'px';
el.style.width = s.w + 'px';
el.style.height = s.h + 'px';
if (s.rotation) el.style.transform = 'rotate(' + s.rotation + 'deg)';
if (st.opacity != null && +st.opacity < 100) el.style.opacity = String(+st.opacity / 100); const tb = window.nmShapeTextBox ? window.nmShapeTextBox(s) : { x: 0, y: 0, w: s.w, h: s.h };
const editing = key === shapeEditKey;
if ((s.text || editing) && tb.w > 0 && tb.h > 0) {
const jc = st.valign === 'top' ? 'flex-start' : st.valign === 'bottom' ? 'flex-end' : 'center';
html += '<div class="nm-shape-text" style="left:' + tb.x + 'px;top:' + tb.y + 'px;width:' + tb.w + 'px;height:' + tb.h + 'px;justify-content:' + jc + ';">'
+ '<div class="nm-shape-text-inner" style="' + escapeAttr(window.nmTextCss ? window.nmTextCss(st) : '') + '"'
+ (editing ? ' contenteditable="true" spellcheck="true"' : '') + '>' + escapeHtml(s.text || '') + '</div></div>';
}
if (key === selectedShapeKey && canEdit() && !editing) {
['nw', 'n', 'ne', 'e', 'se', 's', 'sw', 'w'].forEach(d => { html += '<div class="nm-shape-handle" data-dir="' + d + '"></div>'; });
}The text is an HTML <div> over the SVG, not an SVG <text>. HTML wraps, SVG text does not; white-space: pre-wrap keeps the analyst's own line breaks. The text is escaped with escapeHtml(); it is the only free text in a shape.
Rotation is a number in the Format panel (spR, step 5, -360 to 360) and nothing else - there is no rotate handle. It is a CSS transform on the shape's <div> with transform-origin: 50% 50%, so the SVG, text and handles all turn together. The model never rotates: x, y, w, h stay the unrotated box. See Traps in Part 2 for what that means for connectors and hit tests.
Eight handles, nw to w. onShapeResizeMove() reads the direction letters, so one function serves all eight:
const r = shapeResize, c = canvasModelCoords(e);
const dx = c.x - r.start.x, dy = c.y - r.start.y, MIN = 10;
let x = r.x, y = r.y, w = r.w, h = r.h;
if (r.dir.indexOf('e') >= 0) w = Math.max(MIN, snapS(r.w + dx));
if (r.dir.indexOf('s') >= 0) h = Math.max(MIN, snapS(r.h + dy));
if (r.dir.indexOf('w') >= 0) { const nx = Math.min(snapS(r.x + dx), r.x + r.w - MIN); w = r.w + (r.x - nx); x = nx; }
if (r.dir.indexOf('n') >= 0) { const ny = Math.min(snapS(r.y + dy), r.y + r.h - MIN); h = r.h + (r.y - ny); y = ny; }A west or north drag moves the left / top edge, so x / y change and the opposite edge stays put; the Math.min(..., r.x + r.w - MIN) stops the edge crossing over. Shapes snap to a 10px grid (SHAPE_GRID), finer than the nodes' 20px GRID, because shapes are used for fine layout (labels, lines) where 20px is too coarse.
Double-click calls startShapeTextEdit(), which sets shapeEditKey and re-renders the shape with contenteditable="true". Three guards keep typing from turning into editor commands:
- the editable
<div>stopsmousedownpropagation, so clicking inside it does not start a drag; - its own
keydownhandler stops propagation, so Delete deletes a character and not the shape; - the document
keydowninbindCanvasEvents()also bails out first:
// GH #433: typing in a shape - its own keys, never a delete of the shape
if (document.activeElement && document.activeElement.isContentEditable) return;Blur commits through commitShapeTextEdit(), which reads innerText (so the browser's own line breaks become \n) and only marks the diagram dirty when the text changed. Escape re-renders without committing. Autosave waits while shapeEditKey is set, because the reload after a save would rebuild the element under the cursor.
From the palette, a click adds it in the middle of the view (addShapeInView()), a drag drops it where it lands (onCanvasDrop() sees kind: 'nm-shape'). Both end in addShapeAt():
const maxZ = shapes.reduce((m, s) => Math.max(m, s.z || 0), 0);
const s = {
id: null, tempId: nextTempShapeId--, shape_type: type, icon_id: iconId,
x: Math.max(0, snapS(cx - w / 2)), y: Math.max(0, snapS(cy - h / 2)),
w: w, h: h, rotation: 0, text: defaultShapeText(type),
style: window.nmShapeStyle(type, {}), // the full look, so later library changes never move it
layer: 'back', z: maxZ + 1, uid: newUid()
};
placeOnPage(s); // GH #433Three things here matter later:
-
style: window.nmShapeStyle(type, {})stores the full resolved look, not just the differences. If a later release changes thezonedefault colour, existing zones keep the colour they were drawn with. -
uid: newUid()gives the shape its connector key at birth (Part 2). -
placeOnPage(s)stamps the current page and the active layer (below).
shapeKey() is 's' + id for a saved shape and 't' + tempId for a new one, the same pattern as nodeKey(). Temp ids count down from -1 in their own counter, nextTempShapeId.
A selected shape opens #shapeFormatPanel (same frame as the node detail panel) through renderShapePanel(): X / Y / W / H / rotation, the Layer select, the Knowledge field, Behind / In front, To front / To back, Duplicate, Delete, then the shared style editor:
renderStyleEditor(document.getElementById('spStyle'), window.nmShapeStyle(s.shape_type, s.style), {
rounded: !!def.rounded, valign: true, editable: ed,
onChange: patch => { patchShapeStyle(patch); },
onRebuild: () => renderShapePanel(),
onReset: () => { s.style = window.nmShapeStyle(s.shape_type, {}); rerenderShape(s); markDirty(); renderShapePanel(); }
});renderStyleEditor(box, st, opts) is one function used by three callers - the shape panel, the node Style section and the multi-selection panel (Part 2). It knows nothing about shapes or nodes; it shows st and reports changes through opts.onChange(patch). opts.onRebuild() exists because some choices show or hide controls (choosing Gradient adds the second colour and the direction), so the editor redraws itself, but a colour picker or a number field must keep focus while it is being used, so those call onChange without a rebuild. The ten quick-style buttons are STYLE_PRESETS; a preset is applied with shadow: false first so a preset without a shadow clears one.
The panel's X / Y / W / H inputs are kept in step during a drag by syncShapePanelGeometry(), which skips the field that has focus so typing is never overwritten.
Two independent controls:
/** To front / to back within the shape's layer, or move it to the other layer. */
function arrangeShape(how) {
const s = findShapeByKey(selectedShapeKey);
if (!s || !canEdit()) return;
if (how === 'front') s.z = shapes.reduce((m, x) => Math.max(m, x.z || 0), 0) + 1;
else if (how === 'back') s.z = shapes.reduce((m, x) => Math.min(m, x.z || 0), 0) - 1;
else if (how === 'layer_front') s.layer = 'front';
else if (how === 'layer_back') s.layer = 'back';layer decides the side of the CMDB nodes, by CSS z-index in network-mapper/diagram.php. The connector SVG is z-index: 1 ("under nodes (z:2) and selected nodes (z:3)"), and:
.nm-shape { position: absolute; z-index: 0; cursor: move; transform-origin: 50% 50%; user-select: none; }
.nm-shape.is-front { z-index: 6; }So a Behind shape is under the lines and the nodes (a zone you draw nodes inside), and an In front shape is over both (a callout over a node). z orders shapes among themselves; renderShapes() sorts by user layer first, then z, and inserts every shape before the first node so DOM order agrees:
function renderShapes() {
if (!elCanvasInner) return;
elCanvasInner.querySelectorAll('.nm-shape').forEach(el => el.remove());
shapes.sort((a, b) => (a.z || 0) - (b.z || 0));
const first = elCanvasInner.querySelector('.nm-node');
// GH #433: this page's visible layers, a higher layer's shapes over a lower one's
visibleShapes().sort((a, b) => (layerRank(a) - layerRank(b)) || ((a.z || 0) - (b.z || 0)))
.forEach(s => elCanvasInner.insertBefore(buildShapeEl(s), first || null));shapes.sort() sorts the model array in place, not a copy. That is load-bearing: the save sends shapes in array order, the server returns ORDER BY z, id, and save() re-finds the selected shape after the reload by its index in that array (Part 2). Do not replace that line with a sorted copy.
z can go negative (To back takes min - 1); the server clamps it to -100000 .. 100000.
replaceShapes() deletes the diagram's shapes and inserts the list it was sent. Bad values are clamped, bad keys refused:
$int = function ($v, int $min, int $max, int $default) {
if ($v === null || $v === '' || !is_numeric($v)) return $default;
return max($min, min($max, (int)round((float)$v)));
};
if (count($shapesIn) > 2000) {
throw new ServiceError('validation', 'invalid_field', 'A diagram can have at most 2000 shapes.');
}
foreach (array_values($shapesIn) as $i => $s) {
if (!is_array($s)) {
throw new ServiceError('validation', 'invalid_field', "shapes[{$i}] must be an object.");
}
$type = strtolower(trim((string)($s['shape_type'] ?? '')));
if (!preg_match('/^[a-z0-9_]{1,40}$/', $type)) {
throw new ServiceError('validation', 'invalid_field', "shapes[{$i}]: 'shape_type' is missing or not a shape key.");
}
$text = isset($s['text']) ? (string)$s['text'] : '';
$text = mb_substr(str_replace("\r\n", "\n", $text), 0, 4000);
$layer = (($s['layer'] ?? 'back') === 'front') ? 'front' : 'back';The shape_type check is a format check only. The server does not know the library (it lives in JavaScript), and does not need to: an unknown key draws as a rectangle.
sanitiseStyle() is the one gate for every style JSON on a node or a shape. It keeps known keys with sane values and drops the rest silently:
$enums = [
'fill' => ['none', 'solid', 'gradient'],
'gradientDir' => ['down', 'right', 'diag', 'radial'],
'stroke' => ['none', 'solid', 'dashed', 'dotted'],
'font' => ['sans', 'serif', 'mono', 'arial', 'verdana', 'tahoma', 'trebuchet', 'georgia', 'times', 'courier', 'comic'],
'align' => ['left', 'center', 'right'],
'valign' => ['top', 'middle', 'bottom'],
];
$colours = ['fillColour', 'fillColour2', 'strokeColour', 'fontColour'];
$numbers = ['strokeWidth' => [0, 20], 'opacity' => [0, 100], 'rounded' => [0, 500], 'fontSize' => [6, 96]];
$bools = ['shadow', 'bold', 'italic', 'underline'];The whitelist is also the security boundary. nmShapeSvg() and nmNodeBoxCss() write style values into markup and CSS; because the server only ever stores enum values, #rrggbb colours, numbers and real booleans, a hand-crafted save cannot inject markup through a style. If you add a style key, add it here and in the JavaScript renderers, and keep its value type this narrow. The font names are keys into FONTS in assets/js/network-mapper-shapes.js, never font-family strings.
replaceShapes() only runs when the caller sends shapes:
// GH #433: shapes are replaced only when the caller sends them, so an API
// caller that only knows about nodes and connectors never wipes them.
if (isset($in['shapes']) && is_array($in['shapes'])) {
self::replaceShapes($conn, $diagramId, $in['shapes'], $articles);
}An absent key keeps the shapes; an empty array clears them. tests/network-mapper-shapes.php proves both.
api/network-mapper/get_diagram.php reads shapes inside two nested try blocks:
// GH #433: freestanding shapes. An install that has not run DB Verify since the
// table arrived simply has none - the diagram still opens.
$shapes = [];
try {
try {
$sstmt = $conn->prepare(
"SELECT id, 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 z, id"
);
$sstmt->execute([$id]);
} catch (PDOException $e) {
// icon_id arrived after the shapes table - an install between the two still opens.
$sstmt = $conn->prepare(
"SELECT id, shape_type, x, y, w, h, rotation, text, style, layer, z, NULL AS icon_id, 0 AS page_key, 0 AS layer_key, NULL AS group_key, NULL AS uid, NULL AS article_idThe outer try covers "no table at all", the inner one "table but missing later columns". The pages and layers read has the same outer guard. The point is that upgrading the code before running DB Verify must never stop a diagram from opening.
let pages = []; // [{page_key, name, sort}]
let layers = []; // [{page_key, layer_key, name, sort, visible, locked}]
let currentPage = 0;
const activeLayers = {}; // page_key -> the layer new items go onnodes and shapes stay flat arrays for the whole diagram; each item carries its own page_key / layer_key. A page is never a container in memory. Everything that asks "which items do I draw" goes through a handful of helpers:
function itemPage(it) { return (it && it.page_key) || 0; }
function itemLayer(it) { return (it && it.layer_key) || 0; }
function pageLayers(pk) {
return layers.filter(l => l.page_key === pk).sort((a, b) => (a.sort - b.sort) || (a.layer_key - b.layer_key));
}
function findLayer(pk, lk) { return layers.find(l => l.page_key === pk && l.layer_key === lk) || null; }
function layerOfItem(it) { return findLayer(itemPage(it), itemLayer(it)); }
/** On the current page and on a visible layer. */
function itemVisible(it) {
if (itemPage(it) !== currentPage) return false;
const l = layerOfItem(it);
return !l || l.visible !== false;
}
function itemLocked(it) { const l = layerOfItem(it); return !!(l && l.locked); } function visibleNodes() { return nodes.filter(itemVisible); }
function visibleShapes() { return shapes.filter(itemVisible); }
function pageNodes() { return nodes.filter(n => itemPage(n) === currentPage); }visibleNodes() (this page, visible layers) and pageNodes() (this page, any layer) are different questions. Rendering, Fit, export, rubber band and Select all use visibleNodes(). The "is this CMDB object already here?" checks use pageNodes(), because a node on a hidden layer is still on the page.
renderNodes() and renderShapes() only build elements for visible items, and renderConnectors() skips a line whose either end is not visible:
if (!from || !to) return; // an end was deleted but the connector lingered - skip silently
if (!itemVisible(from.it) || !itemVisible(to.it)) return; // another page, or a hidden layerSo switching page is just changing currentPage and re-rendering:
function switchPage(pk) {
if (pk === currentPage || !pages.some(p => p.page_key === pk)) return;
clearSelection();
currentPage = pk;
renderNodes();
renderShapes();
renderPageTabs();
renderLayersPanel();
}Because the DOM only holds the current page's visible items, Present and PNG / PDF export get "this page minus hidden layers" for free; html2canvas photographs what is there. The size of the export area is computed from the same helpers in computeExportRect():
if (!visibleNodes().length && !visibleShapes().length) return null;zoomFit() and centreOnPage() use them too. The page tab bar is hidden in Present by CSS (.nm-editor.is-presenting .nm-page-tabs { display: none; }), and Page Up / Page Down still switch pages there, which is how a multi-page diagram is presented. (Export itself is covered in Network Mapper - Knowledge and Export - Developer Guide.)
A diagram saved before #433, or one written through the REST API, has no page or layer rows. ensurePagesLayers() runs after every load and every save reload and makes the model whole:
function ensurePagesLayers() {
if (!pages.length) pages = [{ page_key: 0, name: t('network-mapper.pages.default_name', { n: 1 }), sort: 0 }];
// Items on a page that has no row (an API caller, an older save) still get a tab.
nodes.concat(shapes).forEach(it => {
if (!pages.some(p => p.page_key === itemPage(it))) {
pages.push({ page_key: itemPage(it), name: t('network-mapper.pages.default_name', { n: pages.length + 1 }), sort: pages.length });
}
});
pages.sort((a, b) => (a.sort - b.sort) || (a.page_key - b.page_key));
pages.forEach(p => {
if (!pageLayers(p.page_key).length) {
layers.push({ page_key: p.page_key, layer_key: 0, name: t('network-mapper.layers.default_name', { n: 1 }), sort: 0, visible: true, locked: false });
}
});
// GH #433: every shape has a uid for connectors; a connector whose end is gone is dropped.
shapes.forEach(ensureShapeUid);
connectors = connectors.filter(c => endOf(c, 'from') && endOf(c, 'to'));
// An item on a layer that is gone goes on the page's bottom layer.
nodes.concat(shapes).forEach(it => {
if (!layerOfItem(it)) it.layer_key = pageLayers(itemPage(it))[0].layer_key;
});
if (!pages.some(p => p.page_key === currentPage)) currentPage = pages[0].page_key;
}The rule throughout: never lose an item because its page or layer row is missing. An orphan page key gets a tab; an orphan layer key moves the item to the bottom layer. The default names are made in the analyst's language and only become rows on the next save. Note also the two lines in the middle: this is where connectors with a vanished end are dropped and old shapes get a uid (Part 2).
renderPageTabs() draws one button per page plus + on the current version. Click switches, double-click renames inline (renamePageInline()), right-click opens openPageMenu() with Rename, Duplicate, Move left, Move right and Delete. Page Up / Page Down are in the document keydown, checked before the "typing in a shape" guard so they work everywhere except form fields:
if ((e.key === 'PageDown' || e.key === 'PageUp') && pages.length > 1) { // GH #433: next / previous page
const i = pages.findIndex(p => p.page_key === currentPage) + (e.key === 'PageDown' ? 1 : -1);
if (i >= 0 && i < pages.length) { e.preventDefault(); switchPage(pages[i].page_key); }
return;
}A new page key is always one more than the largest in use, never the count, so deleting page 1 of 0, 1, 2 and adding a page gives 3, not a second 2:
function nextPageKey() { return pages.reduce((m, p) => Math.max(m, p.page_key), -1) + 1; }movePage() swaps two entries and renumbers sort 0..n; page_key never changes, so items do not move with it. deletePage() removes the page's nodes, shapes and layers, and every connector touching any of them:
const gone = new Set(nodes.filter(n => itemPage(n) === pk).map(n => nodeRef(n)));
connectors = connectors.filter(c => !gone.has(c.from_node_id) && !gone.has(c.to_node_id)
&& !shapes.some(sh => itemPage(sh) === pk && touchesShape(c, sh)));It asks for confirmation only when the page has something on it.
Before #433 a CMDB object could be on a diagram once. Now the rule is once per page: the same switch can be on an Overview page and on a Rack page. Every place that hides or skips "already there" was narrowed from nodes to pageNodes():
const onCanvas = new Set(pageNodes().map(n => n.cmdb_object_id)); // GH #433: on this pageThat line is in renderPickerResults(), onPickerKeyDown() and renderRelatedRows(); commitRelatedSelections() builds its existingByCmdb map from pageNodes() the same way, and paste applies the rule too (Part 2). The server does not enforce it at all - replaceContents() accepts the same CI twice anywhere. The rule is an editor convenience, not an invariant, so code reading diagrams must not assume one node per CI per diagram. One consequence: save() re-selects a node after the reload by cmdb_object_id within the current page, because the same object may now be on several pages.
duplicatePage() copies every node on the page, which is fine because the copies land on a new page:
const refMap = new Map();
nodes.filter(n => itemPage(n) === pk).forEach(n => {
const copy = Object.assign({}, n, { id: null, tempId: nextTempId--, page_key: nk,
style: n.style ? JSON.parse(JSON.stringify(n.style)) : null });
refMap.set(nodeRef(n), copy.tempId);
nodes.push(copy);
});
const uidMap = new Map();
shapes.filter(s => itemPage(s) === pk).forEach(s => {
const copy = Object.assign({}, s, { id: null, tempId: nextTempShapeId--, page_key: nk, uid: newUid(),
style: s.style ? JSON.parse(JSON.stringify(s.style)) : null });
if (s.uid) uidMap.set(s.uid, copy.uid);
shapes.push(copy);
});
remapConnectors(connectors.slice(), refMap, uidMap);Object.assign is a shallow copy, so style is deep-copied by hand; without that, restyling a copy would restyle the original. refMap and uidMap translate "old end" to "new end" so remapConnectors() (Part 2) can copy only the connectors whose both ends were copied. connectors.slice() matters: remapConnectors() pushes onto connectors while it iterates the list it was given.
The Layers toolbar button opens #layersDropdown, drawn by renderLayersPanel(). The list is shown top layer first (pageLayers(currentPage).slice().reverse()), as draw.io lists them, while sort counts bottom to top. Each row has show / hide, lock / unlock, the name (double-click to rename), the number of items on it, up, down and delete. A click on the row itself makes it the active layer - where new items go - unless it is locked.
layerAction() handles the buttons:
if (act === 'eye') {
l.visible = l.visible === false;
if (l.visible === false) clearSelection();
if (ed) markDirty(); // a read-only version can still hide a layer to look - it just isn't saved
} else if (!ed) {
return;
} else if (act === 'lock') {
l.locked = !l.locked;
if (l.locked) clearSelection();
markDirty();
} else if (act === 'up' || act === 'down') {
const list = pageLayers(currentPage);
const i = list.indexOf(l), j = i + (act === 'up' ? 1 : -1);
if (j < 0 || j >= list.length) return;
const tmp = list[i]; list[i] = list[j]; list[j] = tmp;
list.forEach((x, k) => { x.sort = k; });
markDirty();Show / hide is the only action allowed on a read-only version: looking at an old version with a layer hidden changes nothing stored, and markDirty() is a no-op there anyway. Hiding or locking clears the selection, so a selected item can never be on a layer that is hidden or locked.
Locked means "can be seen, not picked up". It is enforced twice: CSS removes the items from the mouse entirely,
.nm-node.is-locked, .nm-shape.is-locked { pointer-events: none; }and every JavaScript hit test that does not go through the DOM filters them out by hand - findNodeAt(), findShapeAt(), the rubber band, Select all and groupOf(). A locked shape also gets no connection dots in buildShapeEl(). If you write a new hit test, filter with itemLocked() too.
Where a new item goes is activeLayerKey(), which refuses to put anything on a layer where it would vanish or be stuck:
function activeLayerKey() {
const k = activeLayers[currentPage];
const l = k != null ? findLayer(currentPage, k) : null;
// A new item never lands on a locked or hidden layer - it would vanish or be stuck.
if (l && !l.locked && l.visible !== false) return l.layer_key;
const list = pageLayers(currentPage).filter(x => !x.locked && x.visible !== false);
return list.length ? list[list.length - 1].layer_key : 0;
}
/** Stamps a new item with the current page and the active layer. */
function placeOnPage(it) { it.page_key = currentPage; it.layer_key = activeLayerKey(); return it; }placeOnPage() is called by every path that creates an item: commitPickerSelection(), commitRelatedSelections() and addShapeAt(). Paste sets the same two fields itself. activeLayers is per page and is not saved; on load every page's active layer is the top usable one.
deleteLayer() never deletes items. They move to the layer below, or the one above for the bottom layer:
const i = list.indexOf(l);
const to = list[i > 0 ? i - 1 : 1];Layer order also orders shapes. A shape on a higher user layer draws over one on a lower layer (layerRank() in renderShapes() above), and wins the hit test in findShapeAt(). Each shape's Behind / In front still decides which side of the nodes it is on; layers order shapes within that.
An item moves to another layer through the Layer select in its panel (layerSelectHtml() / bindLayerSelect(), locked layers disabled), the multi-selection panel, or the right-click "Move to layer" sub-menu.
replacePages() cleans rather than refuses, except for one rule: a diagram must have a page.
$pages = [];
foreach (array_values($pagesIn) as $i => $p) {
if (!is_array($p)) continue;
$key = self::keyOf($p['page_key'] ?? $i);
if (isset($pages[$key])) continue;
$name = mb_substr(trim((string)($p['name'] ?? '')), 0, 100);
$pages[$key] = [$name !== '' ? $name : 'Page ' . ($i + 1), (int)($p['sort'] ?? $i)];
}
if (!$pages) {
throw new ServiceError('validation', 'invalid_field', 'A diagram needs at least one page.');
} foreach (array_values($layersIn) as $i => $l) {
if (!is_array($l)) continue;
$pk = self::keyOf($l['page_key'] ?? 0);
$lk = self::keyOf($l['layer_key'] ?? 0);
if (!isset($pages[$pk]) || isset($seen["$pk:$lk"])) continue;
$seen["$pk:$lk"] = true;
$name = mb_substr(trim((string)($l['name'] ?? '')), 0, 100);
$insL->execute([$diagramId, $pk, $lk, $name !== '' ? $name : 'Layer ' . ($lk + 1), (int)($l['sort'] ?? $i),
!isset($l['visible']) || $l['visible'] ? 1 : 0, !empty($l['locked']) ? 1 : 0]);
}A repeated key or a layer of a page that is not in the list is dropped rather than refused, because the unique keys uq_net_page / uq_net_layer would otherwise fail the whole save on an insert. visible defaults to on when missing (!isset(...) ||), locked to off - the safe direction for both. The English fallback names ('Page 1', 'Layer 1') are only reached by an API caller sending empty names; the editor always sends its own translated defaults.
Every item's keys go through keyOf():
/** GH #433: a page or layer key - a small whole number, 0 when missing or odd. */
private static function keyOf($v): int
{
return (is_numeric($v) && (int)$v >= 0 && (int)$v <= 100000) ? (int)$v : 0;
}The server does not check that an item's page_key / layer_key exists in the pages and layers it was sent. A node can be saved on page 7 with no page 7 row. That is allowed on purpose, and ensurePagesLayers() in the browser is what turns it into a tab again on the next load.
Like shapes, pages and layers are only replaced when pages is sent (saveDiagram() checks isset($in['pages'])), and api/network-mapper/save_diagram.php only forwards layers together with pages:
// GH #433: pages (tabs) and their layers.
if (array_key_exists('pages', $data) && is_array($data['pages'])) {
$in['pages'] = $data['pages'];
$in['layers'] = is_array($data['layers'] ?? null) ? $data['layers'] : [];
}Sending pages without layers therefore deletes every layer row; the editor always sends both.
Continue in Part 2: multi-select, connectors, menus and saving - including the Traps and Tests sections for both parts. Back to Network Mapper - Developer Guide.
FreeITSM β an open-source IT Service Management platform Β· github.com/edmozley/freeitsm Β· MIT licence
- Installation
- β° Scheduled tasks (cron jobs)
-
Architecture
- β³ π§Ή Root folder tidy (URL routing)
- β³ π Database Integrity (FKs & constraints)
- β³ π οΈ Database Verification β Developer Guide
- β³ π§© Service Layer (UI + API share code)
- β³ πͺ€ Code traps (the TRAP: comments)
- β³ π Commenting for the Engineering wiki
- β³ π οΈ Engineering wiki scanner - Developer Guide
- β³ π Service-Layer progress
- π€ Contributing (read before a pull request)
- π§ͺ Developer tests
- π PDF exports moved to PDFKit (#254)
- AI Providers
- Internationalisation (i18n)
- Timezones & Time Handling
- π Date & Time Formats
- π± Currencies
- π§ The sidebar (optional module rail)
- π§© Preference templates
- π Display order (modules, Watchtower cards) β Developer Guide
- Theming & Dark Mode
- ποΈ Recent β getting back to what you were doing
- β¨οΈ Command palette (βK)
- π Searching inside tickets
- π Attached documents
-
MobileβFriendly
- β³ π« Mobile: Tickets
- β³ π» Mobile: Assets
- β³ π Mobile: Calendar
- β³ π Mobile: Knowledge
- β³ π¦ Mobile: Service Status
- β³ πΌ Mobile: Watchtower
- β³ π§© Mobile: Problem Management
- β³ π Mobile: Change Management
- β³ πΏ Mobile: Software
- β³ β Mobile: Tasks
- β³ π Mobile: Forms
- β³ π Mobile: Contracts
- β³ π Mobile: Domains
- β³ π Mobile: People
- β³ π Mobile: Projects
- β³ ποΈ Mobile: Files
- β³ π Mobile: LMS
- β³ πΊοΈ Mobile: CMDB
- β³ πΊοΈ Mobile: Network Mapper
- β³ π§ Mobile: Process Mapper
- β³ βοΈ Mobile: Workflow
- β³ π₯οΈ Mobile: System
- β³ π Mobile: Reporting
- β³ π Mobile: System Wiki
- β³ π Mobile: Self-Service Portal
- β³ π§° Mobile: Techniques & Tricks
-
Security
- Layer 1 β which modules you can enter
- β³ π§© Module Access Control
- β³ π οΈ Module Access β Developer Guide
- β³ π Switching modules off
- β³ π οΈ Module availability β Developer Guide
- β³ π Module availability β design (#217)
- Layer 2 β what you can administer
- β³ π Roles & Permissions
- β³ π οΈ Roles β Developer Guide
- β³ π€ Why capabilities are constants
- Layer 3 β the System module
- β³ π Admin Access Control
- Hardening
- β³ π Security review response 2026-08
- β³ π‘οΈ Security hardening 2026-08
- β³ π οΈ Security hardening 2026-08 β Developer Guide
- β³ π‘οΈ Round three β plain English
- β³ π οΈ Round three β Developer Guide
- β³ π‘οΈ CSRF protection (S4) β Developer Guide
- Single Sign-On (SSO)
- ποΈ LDAP & Active Directory
-
π¦ Microsoft Entra ID
- β³ π₯ Importing people and groups
- β³ π» Intune: assets to their primary user
- β³ π’ Organisation chart
- β³ π οΈ Entra directory sync β Developer Guide
- β³ π οΈ Entra import - review (#235)
- β³ π οΈ Entra follow-ups - review (#237-#240)
- β³ π οΈ Intune primary user - review (#236)
- β³ π οΈ Intune after an Entra import - review (#334)
- β³ π οΈ Intune primary user history - review (#338)
- β³ π οΈ Intune asset types - review (#339)
- β³ π οΈ Intune scheduled syncs - review (#344)
- β³ π οΈ Microsoft 365 in Integrations - review (#352)
- β³ π οΈ Organisation chart - reviews (#242, #265)
- π CardDAV contact sync
- Browser Extension
- API Reference
-
π REST API β how it works
- β³ π Script library (PowerShell + Python)
- β³ π Proposal: custom fields, inventory import and change evidence (#194)
- β³ π οΈ Custom fields, evidence + inventory - review (#195-#197)
- β³ π οΈ Long forms in a task's Work view - review (#198)
- β³ π οΈ Empty Procedures fold - review (#247)
- β³ π« REST API: Tickets
- β³ π» REST API: Assets
- β³ π΄ REST API: Problems
- β³ π REST API: Changes
- β³ π REST API: Knowledge
- β³ β REST API: Tasks
- β³ ποΈ REST API: CMDB
- β³ π REST API: Contracts
- β³ ποΈ REST API: Calendar
- β³ πΏ REST API: Software
- β³ π REST API: Domains
- β³ π¦ REST API: Service Status
- β³ βοΈ REST API: Morning Checks
- β³ π REST API: Forms
- β³ βοΈ REST API: Workflow
- β³ π·οΈ REST API: Cost centres
- β³ π’ REST API: Companies
- β³ π REST API: Chart of accounts
- β³ π REST API: Projects
- β³ π‘οΈ API threat protection
- β³ π§βπΌ REST API: Analysts
- β³ πΊοΈ REST API: Network Mapper
- β³ π§ Using the API docs page
- β³ π OpenAPI specification
- β³ β OpenAPI: kept correct
- β³ π οΈ Maintaining the catalogue
- Watchtower
-
Tickets
- β³ Reply subject and replying to one message
- β³ π Live updates
- β³ π οΈ Watching a ticket - Developer Guide (1 of 2)
- β³ βοΈ Ticket address suggestions - Developer Guide
- β³ π οΈ CSAT delay and reminder - Developer Guide
- β³ π οΈ Ticket checklist step types - Developer Guide (1 of 2)
- β³ π οΈ Right-click Attach checklist - Developer Guide
- β³ π οΈ Checklists in the REST API - Developer Guide
- β³ π A ticket's related block and attachments - Developer Guide
- β³ π οΈ Inbox.js map β Developer Guide
- β³ π οΈ Floating windows & the file viewer β Developer Guide
- β³ π οΈ Tickets settings β Developer Guide
- β³ π Simpler ticket and task forms - design (#218)
- β³ ποΈ The ticket workspace
- β³ π Forms on tickets
- β³ π The ticket table
- β³ π Rota copy and paste β Developer Deep Dive
- β³ β Checklists & SOPs
- β³ βοΈ Mandatory fields
- β³ π§Ύ Custom ticket fields
- β³ π·οΈ Ticket categories
- β³ π§Ύ A type for every new ticket
- β³ π₯ Assigning tickets to a team, and escalation
- β³ π’ One board across every company
- β³ π Many companies: searchable lists (#358)
- β³ π Ticket dashboard β Developer Guide
- β³ Mailbox Authentication
- β³ π€ Email send log
- β³ βοΈ Emailed reports
- β³ π Attachment size limits and large emails
-
β³ Basic IMAP mailboxes
- β³ π Basic IMAP without the PHP extension (#257)
- β³ π οΈ Basic IMAP client β Developer Guide
- β³ π§ͺ Basic IMAP client β Testing and verifying
- β³ π οΈ Basic IMAP - Sent copy - Developer Guide (#270)
- β³ π€ PR #400 Sending through a relay without a login
- β³ π οΈ Verifying a mail folder β Developer Guide
- β³ π οΈ Mailbox providers β Developer Guide
- β³ π οΈ How Gmail mail collection works β Developer Guide
- β³ Email rendering & images
- β³ SLA Management
- β³ WhatsApp channel
-
β³
βοΈ Telegram channel - β³ β CSAT company scope and filters β Developer Guide
- β³ π₯ Microsoft Teams channel
- β³ π¨οΈ Mattermost channel
- β³ π¬ Web chat channel
- β³ π£ Slack channel
- β³ π Linking tickets
- β³ β Record previews
- β³ π Ticket notes: internal or shared
- β³ ποΈ Canned responses
- β³ βοΈ Limiting replies to particular senders
- β³ π¨ Telling the analyst a ticket is theirs
- β³ βοΈ Email signatures
- β³ π The public web address
- β³ π’ Ticket numbering
- β³ π Raising a ticket for someone else
- β³ π Merging tickets
- β³ π Confidential tickets
- β³ π₯ Portal managers
- β³ π Who has seen a ticket
- β³ π Reading long tickets
- β³ β¨ Reply Cleanup prompt and history
- β³ β Splitting tickets
- β³ β Selecting several tickets
- β³ ποΈ The folder pane
- β³ π½ Just my tickets, or no closed ones
- β³ π οΈ Snoozing tickets β Developer Guide
- β³ π₯ Collision detection
- β³ β±οΈ Time tracking
- β³ π Case reports - a ticket and its work as one PDF
- β³ π Scheduled work in your own calendar
- Problem Management
-
Tasks
- β³ π οΈ Task ID and hover card - review (#405)
- β³ π οΈ Task ID, Company column and hover card β Developer Guide
- β³ π οΈ Task board and subtasks β Developer Guide
- β³ π§βπ€βπ§ People on a task ("Involved")
- β³ π Repeating tasks
- β³ π Complete history for tasks and tickets - design (#430)
- β³ π’ Moving a task between companies
- π Projects
-
Assets
- β³ π οΈ Asset list by type - review (#340)
- β³ π’ Moving an asset between companies
- β³ π Shared asset locations
- β³ π§βπΌ Assigning assets to analysts
- β³ π Warranty and lease alerts
- β³ π Leases
- β³ π Saved table views
- β³ π¨οΈ Recording anything, and importing it
- β³ π§© Asset type layouts
- β³ π Inventory freshness
- β³ π Linked configuration item
- β³ π Connected assets
- β³ π Asset review
- β³ π Missing information
- β³ π¦ Consumables
-
β³ π·οΈ QR asset labels
- β³ π οΈ QR asset labels β Developer Guide
- β³ π Asset label designer - design (#229)
- β³ π· Asset scanning β Developer Guide
- β³ π οΈ Asset tag numbering β Developer Guide
- β³ π οΈ Asset reconciliation β Developer Guide
- β³ π οΈ Reconciliation, tags + labels - review (#164)
- β³ π Who holds what, and handover documents
- β³ π₯οΈ The inventory agent (PowerShell)
- β³ ποΈ Proxmox VE servers
- β³ βοΈ VMware Cloud Director servers
- β³ πͺ Hyper-V and Failover Clusters
- β³ π Linking equipment to tickets
- β³ βοΈ Follow-up tasks on a ticket
- Knowledge
- Change Management
- Calendar
- Morning Checks
- Reporting
- Software
-
Forms
- β³ π¨ The form designer β Developer Guide
- β³ π Layout & the grid β Developer Guide
- β³ ποΈ Collections β grouping submissions
- β³ π Submissions as PDFs
- β³ β‘ What happens next β a form's own actions
- β³ π οΈ Sections & conditional logic β Developer Guide
- β³ π οΈ Lookup fields β Developer Guide
- β³ π οΈ Calculated totals β Developer Guide
-
β³ π‘οΈ Catalogue request approvals
- β³ π οΈ Catalogue approvals β Developer Guide
- β³ π οΈ Approval steps and chains β Developer Guide
- β³ π οΈ Portal approvals β Developer Guide
- β³ π οΈ Approvers change a request's answers β Developer Guide
- β³ π Catalogue group approvals β design (#220)
- β³ π Catalogue as a shop β design (#348)
- β³ π Financial approvals - design (#160)
- People
- Starters & leavers
- Domains
-
ποΈ Files
-
β³ π οΈ Files - Developer Guide
- β³ Versions
- β³ Save to Files
- β³ Storage: server folder or S3
- β³ π S3 storage - PR review
- β³ ποΈ Recycle bin
- β³ π Thumbnails and gallery - design (#424)
- β³ π Recycle bin - design
- β³ π Recycle bin - PR review
- β³ π Deleting or moving a folder
- β³ π Storage series - follow-ups
- β³ π οΈ Floating windows & the file viewer β Developer Guide
-
β³ π οΈ Files - Developer Guide
- Contracts
- Service Status
- π Notifications
- π¨ War Room
-
Self-Service Portal
- β³ π¨ Branding the portal
- β³ π What people can do
- β³ π Help Centre
- β³ πͺ Landing page
- β³ π¨ Login screen designer
- β³ π οΈ Back to your page after sign-in - review (#407)
- β³ π οΈ Back to your page after sign-in β Developer Guide
- β³ π Request catalogue
- β³ π Portal privacy
- β³ π₯ Portal managers
- β³ π Contact details
- β³ π οΈ Developer guide
- LMS
- Process Mapper
-
CMDB
- β³ π§± Designing your CMDB
- β³ π οΈ CMDB β Developer Guide
- β³ π οΈ Impact analysis β Developer Guide
- β³ π οΈ Data quality β Developer Guide
- β³ π οΈ Record references β Developer Guide
- β³ π οΈ CMDB assistant - Developer Guide
- β³ π Linked assets
- β³ π Linking an asset to its CI - design (#201)
- β³ π Discovery and redundancy-aware impact - design (#199)
- β³ π οΈ Relationship wording - review (#297)
- Network Mapper
-
Workflows
- β³ π Branches: If / Otherwise and Choose by value
- β³ π οΈ Workflow engine β Developer Guide
- β³ π οΈ Workflows for tasks β Developer Guide
- β³ π οΈ Workflow notes on a ticket β Developer Guide
- β³ π οΈ Workflow category routing β Developer Guide
- β³ π Workflows in order, child tickets - design (#304)
- β³ β° Time-Based Triggers
- β³ πͺ Webhooks
- β³ π¬ Webhook Message Formats
- β³ π HTTPS Certificates & CA Bundles
- β³ π οΈ SSL Verification β the Global Setting
- β³ π Workflow & Webhook Pitfalls
- Issue trackers (Jira, Azure DevOps)
- π‘ Zabbix (monitoring)
- π¬ Microsoft Teams alerts
- π 3CX (phone system)
-
System
- β³ π οΈ System cards by topic - review (#347)
- β³ π¦ Microsoft 365 (Entra ID and Intune)
- β³ π οΈ Preferences β Developer Guide
- β³ ποΈ Settings on one page
- β³ π§Ή Maintenance
- β³ πΎ Storage usage
- β³ βοΈ Emailed reports
- β³ π Finding people in the Analysts list
- β³ πͺ When an analyst leaves
- β³ π οΈ System β Branding β Developer Guide
- β³ π©Ί Page health (D019) β Developer Guide
- β³ β Feature Bingo
- β³ π Locations
- β³ π·οΈ Cost centres
- β³ π Chart of accounts
- β³ π· Photo Album
- β³ Demo Data
- β³ π οΈ Demo Data β Developer Guide
-
Overview
- β³ π Progress tracker
- β³ Concepts & vocabulary
- β³ Email routing & mailboxes
- β³ Settings: global vs per-company
- β³ Users & self-service
- β³ Staff cross-company access
- β³ One company supporting another
- β³ π’ One board across every company
- β³ Worked examples
- β³ Pitfalls & gotchas
- β³ Scope: what it's for
- β³ π οΈ Developer Guide (make a module multi-company)
- β³ ποΈ Case study: CMDB (a linked graph)
- β³ π§ͺ Test harness (prove it's isolated)
- What this is
-
π Bugs resolved
- β³ π» #436 Intune Last seen not updating
- β³ π #429 Trust duration ignored
- β³ π #423 Knowledge PDF lost formatting
- β³ π§Ύ #427 SOP checklist picker always empty
- β³ π #425 Label beside left a wide gap
- β³ π #422 Calendar Open in inbox link
- β³ π #420 Lookup answers unusable after submit
- β³ π #413 Reading pane too narrow on tablets
- β³ π± #412 Sign-in card cramped on phones
- β³ π§ #411 Header buttons out of reach
- β³ π± #386 Project stuck in an old currency
- β³ π₯οΈ #393 Header ran off the screen
- β³ π±οΈ #395 Ticket flyouts ran off the bottom
- β³ π PR #401 Change editor used hardcoded priorities
- β³ π Knowledge drafts could not be published
- β³ π§© #392 Project dialogs shared element ids
- β³ πΌοΈ #391 Knowledge images from your computer
- β³ π #375 REST API wall-clock times
- β³ π #374 Calendar popup ran off the screen
- β³ π’ #373 All companies: Changes, CMDB, Starters
- β³ π’ #356 Assets People and All companies
- β³ π #366 LMS demo data would not import
- β³ π #362/#365 Team handover showed only a name
- β³ π #365 The bell credited the wrong person
- β³ ποΈ #369 Inbox empty until Database Verification
- β³ πͺ #360 Links opened inside the ticket
- β³ π #354 Workspace Links missed tasks
- β³ π Two access fixes (5.9.1)
- β³ π Task company checks in the API (5.5.0)
- β³ π Asset holders through the API (5.4.0)
- β³ π Files folder delete did not check inside (5.4.0)
- β³ π The Intune tab did not check the company
- β³ π #332 Files viewer would not open
- β³ π #333 Note attachments downloaded
- β³ πͺ #326/#327 Form webhook Full record
- β³ π #325 Form PDF download failed
- β³ π Small fixes in 5.1.0
- β³ π CMDB relationships read backwards (5.1.0)
- β³ π #301 CSAT delay was never applied
- β³ π #281 Comments imported from Jira never arrived
- β³ π #288 A change failed to open with Enforce approvals on
- β³ π Long non-Latin articles never got an embedding
- β³ π« #280 Email lookups scanned the whole table
- β³ β #266 Dragging a task told nobody
- β³ π #255 Article previews showed HTML codes
- β³ π #252 A link to a Knowledge article did not open
- β³ π #254 PDFs could not print Polish
- β³ π #250 Clicking a folder left the open article on screen
- β³ π« #260 The dashboard cog did nothing
- β³ π« #248 A department rule never matched on four routes
- β³ π A directory account could be matched to someone else
- β³ π« #244 Reply went to the assigned analyst
- β³ π Mailbox sign-in was not checked
- β³ π Four weaknesses around signing in
- β³ π A lookup answer could name any record
- β³ π« #227 A mailbox could not be deleted
- β³ π« #226 A picture on a note could not be closed
- β³ π» #222 The Assets page never loaded in 4.3.0
- β³ βοΈ #214 A "contains" condition did not match capitals
- β³ βοΈ #216 A workflow email from a chosen mailbox always failed
- β³ π³ The Docker image was missing PHP extensions
- β³ π A failed DNS lookup read as a missing record
- β³ π A link could change data
- β³ π Access outlived its removal
- β³ π Knowledge articles could run scripts
- β³ π Knowledge writes ignored permissions
- β³ π Company boundaries (Oct 2026)
- β³ π Smaller gaps (Oct 2026)
- β³ π Escaped text could leave its attribute
- β³ π Task descriptions were not cleaned
- β³ π Task documents ignored company scope
- β³ π Repeating tasks ignored company scope
- β³ π¬ #183 Mailbox checks overlapped
- β³ π #188 Transfer lock shown off when unknown
- β³ β #184 Subtask names and Overdue
- β³ π§© #186 Teams: the buttons did nothing
- β³ π Text in a change could run script
- β³ π AI settings changed without the AI permission
- β³ πͺ #178 Deleting an analyst failed
- β³ π« A team with no departments showed 0 tickets
- β³ π Projects: adding a phase did nothing on Save
- β³ π Leavers could still sign in
- β³ πΌοΈ Logo and courses broke on Apache with PHP-FPM
- β³ π’ Chat tickets ignored your ticket numbering
- β³ π Dates shown as a dash, or in server time
- β³ π Assets β Users showed people from other companies
- β³ π Restricted analysts could read other modules' data
- β³ πΌοΈ Replies with a picture in the thread failed to send
- β³ π Reply attachments never reached the customer
- β³ π οΈ Outbound email attachments β Developer Guide
- β³ π A global SSO provider was missing from the portal
- β³ π Behind a proxy, the SSO redirect said http
- β³ βοΈ The portal tagline moved when you saved it
- β³ π¨ The portal settings screen forgot what you saved
- β³ π‘οΈ The approvals inbox said "Error" and nothing else
- β³ π A table's answers were missing from the PDF
- β³ β A single-select column let you tick every option
- β³ π The portal ignored a form's field widths
- β³ π The tasks board stopped taking clicks
- β³ ποΈ #121 The index list is out of date after upgrading
- β³ π #133 The calendar subscription was empty
- β³ π #131 Tasks always reopened on the board
- β³ π₯ #129 Every page returned HTTP 500 after upgrading
- β³ π³ #127 A PHP warning above the System page
- β³ π #126 Notes stamped with the server's clock
- β³ π Storing every date in UTC
- β³ πͺ The portal was down for everyone signed in
- β³ βοΈ #120 Workflow notes could never be written
- β³ βοΈ #123 Three errors when running Database Verification
- β³ π #122 The description box was a stub in the corner
- β³ π£ Demo data deleted real accounts
- β³ π #117 Sign-in redirected to the wrong address
- β³ π¨ #108 The priority dot was invisible
- β³ β±οΈ #116 Time logged from the right-click menu
- β³ π #114 API keys refused by our own guard
- β³ ποΈ #110 Assigning a task told nobody
- β³ πͺ #107 Signed out while still working
- β³ π #103 "Share with Requester" reached nobody
- β³ π #102 Search found nothing for hyphens
- β³ πͺ #101 Source code editor opened behind
- β³ βοΈ #88 Subtasks could not be ticked off
- β³ π» #84 Asset deep link selected nothing
- β³ π« #79 A new ticket arrived with no status
- β³ π§ #79 A ticket from email did not say so
- β³ π #78 Bell opened to nothing
- β³ π¬ #77 Mail only collected from Inbox
- β³ π #74 The default password could not be changed
- β³ π¦ #70 Renaming an impact level
- β³ π€ #67 App-only mailboxes could not send
- β³ π #45 Verify only ever worked for Microsoft
- β³ π #45 IMAP reported as not authenticated
- β³ βοΈ An email template stopped escaping itself
- β³ π The portal dashboard showed the wrong time
- β³ π’ The folder said 99 and the list showed 96