diff --git a/admin/post/document_template.php b/admin/post/document_template.php
index bfe7f00d..f0754308 100644
--- a/admin/post/document_template.php
+++ b/admin/post/document_template.php
@@ -40,18 +40,24 @@ if (isset($_POST['edit_document_template'])) {
$name = sanitizeInput($_POST['name']);
$description = sanitizeInput($_POST['description']);
- $processed_content = mysqli_escape_string(
- $mysqli,
- saveBase64Images(
- $_POST['content'],
- $_SERVER['DOCUMENT_ROOT'] . "/uploads/document_templates/",
- "uploads/document_templates/",
- $document_template_id
- )
+ $processed_content = saveBase64Images(
+ $_POST['content'],
+ $_SERVER['DOCUMENT_ROOT'] . "/uploads/document_templates/",
+ "uploads/document_templates/",
+ $document_template_id
+ );
+
+ $processed_content_escaped = mysqli_escape_string($mysqli, $processed_content);
+
+ // CLEAN UP unused images
+ cleanupUnusedImages(
+ $processed_content,
+ $_SERVER['DOCUMENT_ROOT'] . "/uploads/document_templates/" . $document_template_id,
+ "/uploads/document_templates/" . $document_template_id
);
// Document edit query
- mysqli_query($mysqli,"UPDATE document_templates SET document_template_name = '$name', document_template_description = '$description', document_template_content = '$processed_content', document_template_updated_by = $session_user_id WHERE document_template_id = $document_template_id");
+ mysqli_query($mysqli,"UPDATE document_templates SET document_template_name = '$name', document_template_description = '$description', document_template_content = '$processed_content_escaped', document_template_updated_by = $session_user_id WHERE document_template_id = $document_template_id");
logAction("Document Template", "Edit", "$session_name edited document template $name", 0, $document_template_id);
diff --git a/functions.php b/functions.php
index 380b7388..dd8b91c4 100644
--- a/functions.php
+++ b/functions.php
@@ -1752,3 +1752,39 @@ function saveBase64Images(string $html, string $baseFsPath, string $baseWebPath,
return $html;
}
+
+function cleanupUnusedImages(string $html, string $folderFsPath, string $folderWebPath) {
+
+ $folderFsPath = rtrim($folderFsPath, '/\\') . '/';
+ $folderWebPath = rtrim($folderWebPath, '/\\') . '/';
+
+ if (!is_dir($folderFsPath)) {
+ return; // no folder = nothing to delete
+ }
+
+ // 1. Get all files currently on disk
+ $filesOnDisk = glob($folderFsPath . "*");
+
+ // 2. Find all
+ preg_match_all('/
]+src=["\']([^"\']+)["\']/i', $html, $matches);
+ $htmlImagePaths = $matches[1] ?? [];
+
+ // Normalize paths: keep only filenames belonging to this template folder
+ $referencedFiles = [];
+
+ foreach ($htmlImagePaths as $src) {
+ if (strpos($src, $folderWebPath) !== false) {
+ $filename = basename($src);
+ $referencedFiles[] = $filename;
+ }
+ }
+
+ // 3. Delete any physical file not referenced in the HTML
+ foreach ($filesOnDisk as $filePath) {
+ $filename = basename($filePath);
+
+ if (!in_array($filename, $referencedFiles)) {
+ unlink($filePath);
+ }
+ }
+}