Files
tinker_tickets/scripts/cleanup_orphan_uploads.php
T
jaredandClaude Sonnet 5 dcf9b0cfa1
Lint / PHP (phpcs PSR-12) (push) Successful in 17s
Lint / JS (eslint) (push) Successful in 7s
Lint / PHP requirements (version + extensions) (push) Successful in 20s
Lint / Notify on failure (push) Skipped
Security / PHP Security (semgrep) (push) Successful in 1m8s
Lint / Deploy (push) Successful in 2s
Generate real resized thumbnails for image attachments (#98)
The attachment grid's <img> thumbnail pointed at the same
download_attachment.php URL as the full-size original, so previewing a
multi-MB photo attachment cost a full multi-MB download just to render a
small grid preview. loading="lazy" only deferred off-screen images; it
never reduced per-image transfer size.

Generate a resized JPEG thumbnail (longest side capped at 300px) via GD
at upload time, from the same metadata-stripped image stripImageMetadata()
already produces, reusing its decompression-bomb guard (~40MP decode cap).
Store the thumbnail's filename in a new nullable ticket_attachments.
thumbnail_filename column (migration 005); NULL means no thumbnail exists
(non-image, GD unavailable, or an attachment predating this change) and
callers fall back to the full-size original.

download_attachment.php serves the thumbnail when requested via
?thumb=1 and one exists, falling back to the original otherwise. The
attachments grid now requests thumb=1 for its <img> preview; the
lightbox link is unchanged and still opens the full-size original.
delete_attachment.php removes the thumbnail file alongside the original,
and cleanup_orphan_uploads.php's orphan lookup now also matches
thumbnail_filename so generated thumbnails aren't swept up as orphans.

Verified against real MariaDB + GD: a 1600x1200 test JPEG produced a
300x225 thumbnail at ~1.8KB vs. the 52KB original (~29x smaller);
confirmed the serving logic picks the thumbnail for image attachments
with one, falls back to the original for a non-image attachment even
when thumb=1 is requested, and that the updated orphan-cleanup lookup
matches both the original and thumbnail filename (and correctly finds
neither for an unrelated filename).

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0117oBw2jN4kALYeS8HPq4zV
2026-09-11 22:17:35 -04:00

146 lines
4.5 KiB
PHP

#!/usr/bin/env php
<?php
/**
* Orphan Upload Cleanup
*
* Removes files under uploads/<ticketId>/ that have NO matching row in
* ticket_attachments (e.g. leftovers from a failed DB insert). Intended to be
* run from cron:
* 0 4 * * * /usr/bin/php /path/to/scripts/cleanup_orphan_uploads.php >> /var/log/orphan_uploads.log 2>&1
*
* SAFETY:
* - Only files older than a grace period (GRACE_SECONDS, default 24h) are
* considered, so a freshly written file whose DB row has not been inserted
* yet (in-flight upload) is never deleted.
* - Only 9-digit ticket directories are scanned. uploads/avatars/ (and any
* other non-ticket directory) is skipped entirely.
* - A file is deleted only when no ticket_attachments row references its
* stored filename (looked up with a prepared statement).
*
* Usage:
* php cleanup_orphan_uploads.php # delete orphaned files past grace period
* php cleanup_orphan_uploads.php --dry-run # report only, delete nothing
*/
// Prevent web access
if (php_sapi_name() !== 'cli') {
http_response_code(403);
exit('CLI access only');
}
require_once dirname(__DIR__) . '/config/config.php';
require_once dirname(__DIR__) . '/helpers/Database.php';
/** Files younger than this (seconds) are never touched — protects in-flight uploads. */
const GRACE_SECONDS = 86400;
$dryRun = in_array('--dry-run', $argv, true);
function logMessage($message)
{
echo '[' . date('Y-m-d H:i:s') . '] ' . $message . "\n";
}
$uploadDir = $GLOBALS['config']['UPLOAD_DIR'] ?? (dirname(__DIR__) . '/uploads');
$uploadRoot = realpath($uploadDir);
if ($uploadRoot === false || !is_dir($uploadRoot)) {
logMessage("Upload directory not found: {$uploadDir}");
exit(0);
}
logMessage('Starting orphan upload cleanup' . ($dryRun ? ' (DRY RUN)' : ''));
try {
$conn = Database::getConnection();
} catch (Exception $e) {
logMessage('FATAL ERROR: could not connect to database: ' . $e->getMessage());
exit(1);
}
// Prepared lookup: does any attachment row reference this stored filename,
// either as the original file or as its generated preview thumbnail? Both
// are globally unique (uniqid-derived), so filename alone is sufficient and
// safe — a match in any ticket means the file is a real, referenced file.
$lookup = $conn->prepare('SELECT 1 FROM ticket_attachments WHERE filename = ? OR thumbnail_filename = ? LIMIT 1');
if ($lookup === false) {
logMessage('FATAL ERROR: could not prepare lookup statement: ' . $conn->error);
exit(1);
}
$now = time();
$scanned = 0;
$orphaned = 0;
$deleted = 0;
$skippedTooNew = 0;
$errors = 0;
foreach (new DirectoryIterator($uploadRoot) as $entry) {
if ($entry->isDot() || !$entry->isDir() || $entry->isLink()) {
continue;
}
// Ticket directories are 9-digit ticket IDs. Skip avatars/ and anything else.
$dirName = $entry->getFilename();
if (!preg_match('/^\d{9}$/', $dirName)) {
continue;
}
foreach (new DirectoryIterator($entry->getPathname()) as $file) {
if ($file->isDot() || !$file->isFile() || $file->isLink()) {
continue;
}
$scanned++;
$filename = $file->getFilename();
// Never touch files younger than the grace period (in-flight uploads).
$age = $now - $file->getMTime();
if ($age < GRACE_SECONDS) {
$skippedTooNew++;
continue;
}
// Keep the file if any attachment row references it (as the
// original or as its thumbnail).
$lookup->bind_param('ss', $filename, $filename);
$lookup->execute();
$hasRow = $lookup->get_result()->num_rows > 0;
if ($hasRow) {
continue;
}
$orphaned++;
$path = $file->getPathname();
if ($dryRun) {
logMessage("WOULD DELETE orphan: {$dirName}/{$filename}");
continue;
}
if (@unlink($path)) {
$deleted++;
logMessage("Deleted orphan: {$dirName}/{$filename}");
} else {
$errors++;
logMessage("ERROR: could not delete: {$dirName}/{$filename}");
}
}
}
$lookup->close();
Database::close();
logMessage('Cleanup complete' . ($dryRun ? ' (DRY RUN — nothing deleted)' : '') . ':');
logMessage(" - Scanned: {$scanned} files");
logMessage(" - Orphaned: {$orphaned} files");
logMessage(" - Deleted: {$deleted} files");
logMessage(" - Skipped (too new): {$skippedTooNew} files");
if ($errors > 0) {
logMessage(" - Errors: {$errors} files");
}
exit($errors > 0 ? 1 : 0);