57 lines
1.3 KiB
PHP
57 lines
1.3 KiB
PHP
<?php
|
|
|
|
declare(strict_types=1);
|
|
|
|
$f3 = require __DIR__ . '/bootstrap.php';
|
|
Media::bootstrap($f3->get('DB'));
|
|
|
|
$mode = strtolower(trim((string) ($argv[1] ?? 'list')));
|
|
if (!in_array($mode, ['list', 'delete'], true)) {
|
|
fwrite(STDERR, "Usage: php scripts/clean-orphan-media.php [list|delete]\n");
|
|
exit(1);
|
|
}
|
|
|
|
$directory = rtrim((string) $f3->get('paths.media_dir'), '/\\');
|
|
$knownFiles = [];
|
|
foreach ((new Media())->find(null) ?: [] as $row) {
|
|
$knownFiles[(string) $row->file_name] = true;
|
|
}
|
|
|
|
$orphans = [];
|
|
if (is_dir($directory)) {
|
|
foreach (glob($directory . DIRECTORY_SEPARATOR . '*') ?: [] as $path) {
|
|
if (!is_file($path)) {
|
|
continue;
|
|
}
|
|
|
|
$name = basename($path);
|
|
if (!isset($knownFiles[$name])) {
|
|
$orphans[] = $path;
|
|
}
|
|
}
|
|
}
|
|
|
|
sort($orphans, SORT_NATURAL);
|
|
|
|
if ($mode === 'list') {
|
|
if ($orphans === []) {
|
|
fwrite(STDOUT, "Aucun fichier orphelin.\n");
|
|
exit(0);
|
|
}
|
|
|
|
fwrite(STDOUT, "Fichiers orphelins:\n");
|
|
foreach ($orphans as $path) {
|
|
fwrite(STDOUT, '- ' . basename($path) . PHP_EOL);
|
|
}
|
|
exit(0);
|
|
}
|
|
|
|
$deleted = 0;
|
|
foreach ($orphans as $path) {
|
|
if (@unlink($path)) {
|
|
$deleted++;
|
|
}
|
|
}
|
|
|
|
fwrite(STDOUT, "Fichiers orphelins supprimés : {$deleted}\n");
|