decor-6-site/site/plugins/image-usage-indicator/index.php

83 lines
2.9 KiB
PHP
Raw Normal View History

<?php
/**
* Plugin: image-usage-indicator
*
* Exposes an API route that scans all content files for file:// UUID references,
* and returns which images (by filename) are actually used on a given page.
*
* Used by index.js to add visual badges in the panel files section.
*/
Kirby::plugin('smart-forests/image-usage-indicator', [
'api' => [
'routes' => [
[
'pattern' => 'smart-forests/image-usage/(:any)',
'method' => 'GET',
'action' => function (string $encodedId) {
$kirby = kirby();
// Panel encodes page IDs with + instead of /
$pageId = str_replace('+', '/', rawurldecode($encodedId));
$page = $kirby->page($pageId);
if (!$page) {
return ['error' => 'Page not found: ' . $pageId];
}
// Build UUID → filename map for all files on this page
$uuidMap = [];
foreach ($page->files() as $file) {
$uuid = $file->content()->get('uuid')->value();
if ($uuid) {
$uuidMap[$uuid] = $file->filename();
}
}
if (empty($uuidMap)) {
return (object)[];
}
// Scan all content .txt files once for file:// UUID references
$usedUuids = [];
$contentRoot = $kirby->root('content');
$iter = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator(
$contentRoot,
RecursiveDirectoryIterator::SKIP_DOTS
)
);
foreach ($iter as $fsFile) {
// Stop early when all UUIDs are accounted for
if (count($usedUuids) === count($uuidMap)) {
break;
}
if ($fsFile->getExtension() !== 'txt') {
continue;
}
$content = file_get_contents($fsFile->getPathname());
foreach ($uuidMap as $uuid => $_) {
if (!isset($usedUuids[$uuid]) && strpos($content, 'file://' . $uuid) !== false) {
$usedUuids[$uuid] = true;
}
}
}
// Return filename => isUsed boolean
$result = [];
foreach ($uuidMap as $uuid => $filename) {
$result[$filename] = isset($usedUuids[$uuid]);
}
return $result;
}
]
]
]
]);