Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
53 changes: 46 additions & 7 deletions lib/editor.assets.php
Original file line number Diff line number Diff line change
Expand Up @@ -210,6 +210,46 @@ function wm_asset_image_users($name, $kind = null, $references = null) {
}
return array_values(array_unique($users));
}
/**
* Encode a relative images/ path as the preview URL the editor JavaScript accepts.
*
* @param string $path Relative configuration path such as images/objects/<name>.
*
* @return string The per-segment rawurlencoded URL, or '' outside images/.
*/
function wm_asset_image_url($path) {
if (!is_string($path) || strpos($path, 'images/') !== 0) return '';
return implode('/', array_map('rawurlencode', explode('/', $path)));
}
/**
* Scan one image library with the rules shared by the selectors and the library dialog.
*
* An entry is a readable regular file (symlinks to one included) named .png, .gif, .jpg
* or .jpeg whose content is a PNG, JPEG or GIF raster. Symlinks are listed with
* managed=false so selectors keep offering them while library management refuses them.
*
* @param string $kind The objects or backgrounds library.
* @param string|null $root Optional plugin directory; defaults to this plugin.
*
* @return array[] Entries {kind, name, url, path, width, height, managed} in filename order.
*/
function wm_asset_library_images($kind, $root = null) {
// Raises the shared invalid-category error for anything but the two libraries.
if (!in_array($kind, ['objects', 'backgrounds'], true)) wm_asset_directory($kind);
$parent = ($root ?? dirname(__DIR__)) . '/images';
$dir = $parent . '/' . $kind;
$linkedDir = is_link($parent) || is_link($dir);
$images = [];
foreach ((is_dir($dir) ? scandir($dir) : false) ?: [] as $name) {
$path = $dir . '/' . $name;
if (!is_file($path) || !is_readable($path) || !preg_match('/\.(png|gif|jpe?g)$/iD', $name)) continue;
$size = @getimagesize($path);
if (!$size || !in_array($size[2], [IMAGETYPE_PNG, IMAGETYPE_JPEG, IMAGETYPE_GIF], true)) continue;
$relative = 'images/' . $kind . '/' . $name;
$images[] = ['kind' => $kind, 'name' => $name, 'url' => wm_asset_image_url($relative), 'path' => $relative, 'width' => $size[0], 'height' => $size[1], 'managed' => !$linkedDir && !is_link($path)];
}
return $images;
}
/**
* List image metadata using one shared configuration reference index.
*
Expand All @@ -221,14 +261,13 @@ function wm_asset_image_list($references = null) {
$result = [];
$references = $references ?? wm_asset_image_reference_index();
foreach (['objects', 'backgrounds'] as $kind) {
$dir = wm_asset_directory($kind);
foreach (scandir($dir) ?: [] as $name) {
$path = $dir . '/' . $name;
if (!is_file($path) || is_link($path) || !is_readable($path) || !preg_match('/\.(png|gif|jpe?g)$/iD', $name)) continue;
$size = @getimagesize($path);
if (!$size || !in_array($size[2], [IMAGETYPE_PNG, IMAGETYPE_JPEG, IMAGETYPE_GIF], true)) continue;
// Rejects a symlinked library before any entry is offered for management.
wm_asset_directory($kind);
foreach (wm_asset_library_images($kind) as $image) {
if (!$image['managed']) continue;
$name = $image['name'];
$users = wm_asset_image_users($name, $kind, $references);
$result[] = ['width' => $size ? $size[0] : null, 'height' => $size ? $size[1] : null, 'users' => $users, 'kind' => $kind, 'name' => $name, 'url' => 'images/' . $kind . '/' . rawurlencode($name), 'deletable' => !$users && (bool) preg_match('/^[A-Za-z0-9_.-]+\.(png|gif|jpe?g)$/iD', $name) && strpos($name, '..') === false];
$result[] = ['width' => $image['width'], 'height' => $image['height'], 'users' => $users, 'kind' => $kind, 'name' => $name, 'url' => $image['url'], 'deletable' => !$users && (bool) preg_match('/^[A-Za-z0-9_.-]+\.(png|gif|jpe?g)$/iD', $name) && strpos($name, '..') === false];
}
}
return $result;
Expand Down
75 changes: 54 additions & 21 deletions lib/editor.inc.php
Original file line number Diff line number Diff line change
Expand Up @@ -700,38 +700,71 @@ function extract_with_validation($array, $paramarray, $prefix = '') {
}

/**
* @param mixed $imagedir
* @return mixed
* List the relative configuration paths of one image library.
*
* @param string $imagedir The objects or backgrounds library.
* @return string[] Paths such as images/objects/<name>, in filename order.
*/
function get_imagelist($imagedir) {
global $config;

$imagelist = [];
require_once __DIR__ . '/editor.assets.php';

$imdir = $config['base_path'] . '/plugins/weathermap/images/' . $imagedir;
return array_column(wm_asset_library_images($imagedir, $config['base_path'] . '/plugins/weathermap'), 'path');
}

if (is_dir($imdir)) {
$n = 0;
$dh = opendir($imdir);
/**
* Build editor selector entries from a library plus images the map already uses.
*
* Used paths missing from the library (for example outside images/) keep their
* value; their preview URL is empty unless they sit under images/.
*
* @param string $kind The objects or backgrounds library.
* @param string[] $used Image paths referenced by the map.
* @param string|null $root Optional plugin directory; defaults to the installed plugin.
* @return array[] Entries {kind, name, url, path} sorted by path.
*/
function wm_editor_image_options($kind, $used = [], $root = null) {
global $config;

if ($dh) {
while ($file = readdir($dh)) {
$realfile = $imdir . '/' . $file;
$uri = "images/$imagedir/$file";

if (is_file($realfile) && is_readable($realfile) && (preg_match('/\.(gif|jpe?g|png)$/i', $file))) {
$size = @getimagesize($realfile);
if (!$size || !in_array($size[2], [IMAGETYPE_PNG, IMAGETYPE_JPEG, IMAGETYPE_GIF], true)) continue;
$imagelist[] = $uri;
$n++;
}
}
require_once __DIR__ . '/editor.assets.php';

closedir($dh);
$entries = [];
$paths = [];

foreach (wm_asset_library_images($kind, $root ?? $config['base_path'] . '/plugins/weathermap') as $image) {
$entries[] = ['kind' => $kind, 'name' => $image['name'], 'url' => $image['url'], 'path' => $image['path']];
$paths[$image['path']] = true;
}

foreach ($used as $image) {
if (!is_string($image) || isset($paths[$image])) {
continue;
}

$entries[] = ['kind' => $kind, 'name' => basename($image), 'url' => wm_asset_image_url($image), 'path' => $image];
$paths[$image] = true;
}

return ($imagelist);
// Same comparison as the sort() the editor applied to the plain path list.
usort($entries, function ($a, $b) {
return $a['path'] <=> $b['path'];
});

return $entries;
}

/**
* Render one selector option whose preview source is the entry's encoded URL.
*
* @param array $entry Entry from wm_editor_image_options().
* @param string|null $selected Path to mark selected, or null for none.
* @return string The option element.
*/
function wm_editor_image_option($entry, $selected = null) {
$display = ucfirst(str_replace(['.png', '.gif', '.jpg'], '', basename($entry['path'])));

return wm_editor_option($display, ['selected' => $selected !== null && $entry['path'] == $selected, 'data-description' => $display, 'data-imagesrc' => $entry['url'], 'value' => $entry['path']]);
}

/**
Expand Down
55 changes: 55 additions & 0 deletions tests/Browser/EditorImageOptionsTest.cjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
// Browser half of the editor image-option contract: the server markup pinned by
// tests/E2E/EditorImageOptionsFixtureTest.php, previewed through the real wmEditorImageSrc().
const {JSDOM}=require('jsdom');
const jquery=require('jquery');
const fs=require('node:fs');
const path=require('node:path');
const assert=require('node:assert/strict');
const markup=fs.readFileSync(path.join(__dirname,'fixtures/editor-image-options.html'),'utf8');
const dom=new JSDOM('<form>'+markup+'</form>',{runScripts:'outside-only',pretendToBeVisual:true,url:'https://example.test/cacti/plugins/weathermap/weathermap-cacti-plugin-editor.php'});
const w=dom.window,$=jquery(w);w.$=w.jQuery=$;w.selectedNode='images/objects/core router.png';
const inc=fs.readFileSync(path.join(__dirname,'../../lib/editor.inc.php'),'utf8');
w.wmEditorText={};
for(const match of inc.matchAll(/'(icon[A-Za-z]+)' => __\('([^']+)'/g))w.wmEditorText[match[1]]=match[2];
// Evaluate the whole editor scripts the page includes, in page order, so the
// check does not depend on which file declares wmEditorImageSrc(). editor.js
// runs initJS() on DOM ready; this check needs only the picker functions.
for(const name of ['editor.js','editor.dialogs.js','editor.picker.js','editor.compact.js','editor.assets.js']){
const file=path.join(__dirname,'../../js',name);
if(fs.existsSync(file))w.eval(fs.readFileSync(file,'utf8'));
}
w.initJS=()=>{};
const base='https://example.test/cacti/plugins/weathermap/';
const expected={
node_iconfilename:[
['/srv/icons/outside.png',''],
['images/../setup.png',''],
['images/objects/%2e%2e/%2e%2e/setup.png',base+'images/objects/%252e%252e/%252e%252e/setup.png'],
['images/objects/100%.png',base+'images/objects/100%25.png'],
['images/objects/café.png',base+'images/objects/caf%C3%A9.png'],
['images/objects/core router.png',base+'images/objects/core%20router.png'],
['images/objects/custom folder/site.png',base+'images/objects/custom%20folder/site.png'],
['images/objects/router.png',base+'images/objects/router.png'],
['images/objects/site#2.png',base+'images/objects/site%232.png'],
],
map_bgfile:[
['images/backgrounds/plain.gif',base+'images/backgrounds/plain.gif'],
['images/backgrounds/world map.jpg',base+'images/backgrounds/world%20map.jpg'],
],
};
for(const [id,rows] of Object.entries(expected)){
const options=$('#'+id+' option').toArray();
assert.deepEqual(options.map(o=>o.value),rows.map(r=>r[0]),id+' values keep the configuration paths in server order');
options.forEach((option,i)=>{
const imagesrc=option.getAttribute('data-imagesrc');
assert.equal(w.wmEditorImageSrc(imagesrc),rows[i][1],id+' preview for '+option.value);
// The server already sends the canonical encoding, so the browser resolves it unchanged.
if(rows[i][1])assert.equal(rows[i][1],base+imagesrc,'server url is the preview path for '+option.value);
});
}
assert.equal($('#map_bgfile').val(),'images/backgrounds/world map.jpg','selected background survives encoding');
w.wmNodeIconPicker();
const previews=$('.wm-icon-choice').toArray().map(b=>{const img=b.querySelector('img');return img?img.src:'';});
assert.deepEqual(previews,expected.node_iconfilename.map(r=>r[1]),'icon picker renders exactly the accepted previews');
assert.equal($('#node_iconfilename').val(),'images/objects/core router.png');
console.log('Editor image option previews PASS');
2 changes: 2 additions & 0 deletions tests/Browser/fixtures/editor-image-options.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
<select id="node_iconfilename" aria-label="Icon"><option data-description="Outside" data-imagesrc="" value="/srv/icons/outside.png">Outside</option><option data-description="Setup" data-imagesrc="images/../setup.png" value="images/../setup.png">Setup</option><option data-description="Setup" data-imagesrc="images/objects/%252e%252e/%252e%252e/setup.png" value="images/objects/%2e%2e/%2e%2e/setup.png">Setup</option><option data-description="100%" data-imagesrc="images/objects/100%25.png" value="images/objects/100%.png">100%</option><option data-description="Café" data-imagesrc="images/objects/caf%C3%A9.png" value="images/objects/café.png">Café</option><option data-description="Core router" data-imagesrc="images/objects/core%20router.png" value="images/objects/core router.png">Core router</option><option data-description="Site" data-imagesrc="images/objects/custom%20folder/site.png" value="images/objects/custom folder/site.png">Site</option><option data-description="Router" data-imagesrc="images/objects/router.png" value="images/objects/router.png">Router</option><option data-description="Site#2" data-imagesrc="images/objects/site%232.png" value="images/objects/site#2.png">Site#2</option></select>
<select id="map_bgfile" aria-label="Background"><option data-description="Plain" data-imagesrc="images/backgrounds/plain.gif" value="images/backgrounds/plain.gif">Plain</option><option selected data-description="World map" data-imagesrc="images/backgrounds/world%20map.jpg" value="images/backgrounds/world map.jpg">World map</option></select>
15 changes: 8 additions & 7 deletions tests/E2E/EditorImageOptionListsTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@

beforeAll(function () {
require_once __DIR__ . '/../../lib/editor.inc.php';
require_once __DIR__ . '/../../lib/editor.assets.php';
});

/**
Expand Down Expand Up @@ -78,7 +79,7 @@ function wm_option_lists_file($code) {
* @param array<int, string> $backgrounds Background image file names.
* @param array<int, string> $used Image paths the map already uses.
*
* @return array{0: array<int, string>, 1: array<int, string>}
* @return array{0: array<int, array>, 1: array<int, array>} Entries from wm_editor_image_options().
*/
function wm_option_lists_build(array $objects, array $backgrounds, array $used) {
global $config;
Expand All @@ -98,7 +99,7 @@ function wm_option_lists_build(array $objects, array $backgrounds, array $used)
$config['base_path'] = $base;
$map = (object) ['used_images' => $used];

$code = wm_option_lists_file(wm_option_lists_code("\$image_list = get_imagelist('objects');", 'sort($image_list);'));
$code = wm_option_lists_file(wm_option_lists_code("\$image_list = wm_editor_image_options('objects'", "\$backgd_list = wm_editor_image_options('backgrounds');"));

try {
include $code;
Expand Down Expand Up @@ -195,13 +196,13 @@ function wm_option_lists_label($path) {
->and($options[0])->toBe(['attributes' => ['data-description' => 'Label Only Icon', 'data-imagesrc' => '', 'value' => '--NONE--'], 'text' => 'Label Only'])
->and($options[1])->toBe(['attributes' => ['data-description' => 'Special Purpose Icon', 'data-imagesrc' => '', 'value' => '--AICON--'], 'text' => 'Special Icon (AICON)']);

foreach ($image_list as $index => $im) {
foreach (array_column($image_list, 'path') as $index => $im) {
$label = wm_option_lists_label($im);
expect($options[$index + 2])->toBe(['attributes' => ['data-description' => $label, 'data-imagesrc' => $im, 'value' => $im], 'text' => $label]);
expect($options[$index + 2])->toBe(['attributes' => ['data-description' => $label, 'data-imagesrc' => wm_asset_image_url($im), 'value' => $im], 'text' => $label]);
}

foreach ($files as $file) {
expect($image_list)->toContain('images/objects/' . $file);
expect(array_column($image_list, 'path'))->toContain('images/objects/' . $file);
}
})->with('hostile image names');

Expand All @@ -215,9 +216,9 @@ function wm_option_lists_label($path) {
expect($options)->toHaveCount(count($backgd_list) + 1)
->and($options[0])->toBe(['attributes' => ['data-description' => 'Use Map Background Colour', 'data-imagesrc' => '', 'value' => '--NONE--'], 'text' => '--NO BACKGROUND--']);

foreach ($backgd_list as $index => $im) {
foreach (array_column($backgd_list, 'path') as $index => $im) {
$label = wm_option_lists_label($im);
$expected = ['data-description' => $label, 'data-imagesrc' => $im, 'value' => $im];
$expected = ['data-description' => $label, 'data-imagesrc' => wm_asset_image_url($im), 'value' => $im];

if ($im === $current) {
$expected = ['selected' => 'selected'] + $expected;
Expand Down
58 changes: 58 additions & 0 deletions tests/E2E/EditorImageOptionsFixtureTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
<?php
/*
+-------------------------------------------------------------------------+
| Copyright (C) 2004-2026 The Cacti Group |
+-------------------------------------------------------------------------+
| Cacti: The Complete RRDtool-based Graphing Solution |
+-------------------------------------------------------------------------+
*/

/*
* Server half of the editor image-option contract. The editor page renders its
* icon and background selectors with wm_editor_image_options() and
* wm_editor_image_option(); this test drives both against a real images/
* tree and pins the markup in tests/Browser/fixtures/editor-image-options.html.
* tests/Browser/EditorImageOptionsTest.cjs loads that same file into jsdom with
* the real wmEditorImageSrc(). The PHP container has no Node.js, so the file is
* the hand-off; set WM_UPDATE_FIXTURES=1 to rewrite it after a deliberate change.
*/

beforeAll(function (): void {
require_once __DIR__ . '/../../lib/editor.assets.php';
require_once __DIR__ . '/../../lib/editor.inc.php';
require_once __DIR__ . '/../Helpers/ImageLibraryFixture.php';
});

it('renders the editor image selectors that the browser fixture pins', function (): void {
$root = wm_fixture_plugin_root();

try {
foreach (['router.png', 'core router.png', '100%.png', 'site#2.png', 'café.png'] as $name) {
wm_fixture_raster($root . '/images/objects/' . $name);
}
file_put_contents($root . '/images/objects/broken.png', 'not an image');
wm_fixture_raster($root . '/images/objects/vector.svg');
wm_fixture_raster($root . '/images/backgrounds/world map.jpg', 'jpeg');
wm_fixture_raster($root . '/images/backgrounds/plain.gif', 'gif');

$used = ['images/objects/router.png', 'images/objects/custom folder/site.png', '/srv/icons/outside.png', 'images/objects/%2e%2e/%2e%2e/setup.png', 'images/../setup.png'];

$render = function ($entries, $selected = null) {
return implode('', array_map(fn ($entry) => wm_editor_image_option($entry, $selected), $entries));
};
$markup = '<select id="node_iconfilename" aria-label="Icon">' . $render(wm_editor_image_options('objects', $used, $root)) . "</select>\n"
. '<select id="map_bgfile" aria-label="Background">' . $render(wm_editor_image_options('backgrounds', [], $root), 'images/backgrounds/world map.jpg') . "</select>\n";
} finally {
wm_fixture_remove($root);
}

$fixture = dirname(__DIR__) . '/Browser/fixtures/editor-image-options.html';

if (getenv('WM_UPDATE_FIXTURES') === '1') {
file_put_contents($fixture, $markup);
}

expect(file_get_contents($fixture))->toBe($markup);
expect($markup)->not->toContain('broken.png');
expect($markup)->not->toContain('vector.svg');
});
51 changes: 51 additions & 0 deletions tests/Helpers/ImageLibraryFixture.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
<?php
/*
+-------------------------------------------------------------------------+
| Copyright (C) 2004-2026 The Cacti Group |
+-------------------------------------------------------------------------+
| Cacti: The Complete RRDtool-based Graphing Solution |
+-------------------------------------------------------------------------+
*/

/**
* Write a small raster in the requested format.
*
* @param string $path Destination file.
* @param string $format png, gif or jpeg.
*
* @return void
*/
function wm_fixture_raster($path, $format = 'png') {
$image = imagecreatetruecolor(4, 3);
imagefill($image, 0, 0, imagecolorallocate($image, 40, 120, 200));
if ($format === 'gif') imagegif($image, $path);
elseif ($format === 'jpeg') imagejpeg($image, $path);
else imagepng($image, $path);
}
/**
* Create a temporary plugin directory whose images/ libraries exist but are empty.
*
* @return string The temporary plugin root.
*/
function wm_fixture_plugin_root() {
$root = sys_get_temp_dir() . '/wm-image-library-' . bin2hex(random_bytes(6));
mkdir($root . '/images/objects', 0777, true);
mkdir($root . '/images/backgrounds');
return $root;
}
/**
* Remove a fixture tree without following symlinks.
*
* @param string $root Directory created by wm_fixture_plugin_root().
*
* @return void
*/
function wm_fixture_remove($root) {
if (!is_dir($root) || is_link($root)) return;
$entries = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($root, FilesystemIterator::SKIP_DOTS), RecursiveIteratorIterator::CHILD_FIRST);
foreach ($entries as $entry) {
if (!$entry->isLink()) @chmod($entry->getPathname(), 0700);
if ($entry->isDir() && !$entry->isLink()) rmdir($entry->getPathname()); else unlink($entry->getPathname());
}
rmdir($root);
}
Loading
Loading