File: /var/www/limestate-api/crons/garbage_collector.php
<?php
/* ARGV */
$env = 'production';
$unitId = false;
$verbose = false;
$limit = false;
if (isset($argv)) {
array_shift($argv);
if (count($argv) > 0) {
foreach ($argv as $value) {
switch($value) {
case '-v':
$verbose = true;
break;
case '-l':
$limit = 10000;
break;
default:
$env = $value;
break;
}
}
}
}
define('APPLICATION_ENV', $env);
define('ROOT', realpath(__DIR__ . '/..') . '/');
date_default_timezone_set('Europe/Moscow');
require_once(ROOT . 'config.php');
require_once(ROOT . 'lib/autoloader.php');
$db = Db_Driver::getInstance();
Output::title('Демон удаляет не используемые изображения из системы');
$uploadsDir = ROOT . 'uploads';
$totalClear = $filesChecked = $filesRemoved = 0;
function removeFile($relativePath) {
global $totalClear, $filesRemoved;
$fullPath = ROOT . $relativePath;
if (file_exists($fullPath)) {
$totalClear += filesize($fullPath);
$filesRemoved++;
unlink($fullPath);
} else {
return false;
}
return true;
}
function humanFilesize($size, $precision = 2) {
$units = array('B','kB','MB','GB','TB','PB','EB','ZB','YB');
$step = 1024;
$i = 0;
while (($size / $step) > 0.9) {
$size = $size / $step;
$i++;
}
return round($size, $precision).$units[$i];
}
function checkDirectory($path) {
global $db, $filesChecked, $limit, $filesRemoved;
$files = scandir($path);
foreach($files as $file) {
if (in_array($file, ['.', '..'])) continue;
$filePath = $path . '/' . $file;
if (is_dir($filePath)) {
checkDirectory($filePath);
} else {
$relativePath = str_replace(ROOT, '', $filePath);
echo $relativePath . PHP_EOL;
$filesChecked++;
$attachment = $db->select()->from(Attachment::$table_name . ' a')
->where('a.file = ? OR a.file_thumb = ?', [$relativePath, $relativePath])
->fetchRow();
if (empty($attachment)) {
echo ' - no attachment for file: '
. (removeFile($relativePath) ? 'removed' : 'not removed')
. PHP_EOL;
} else {
// Пока остановимся на такой проверке
}
echo PHP_EOL;
}
if ($limit && $filesRemoved >= $limit) {
break;
}
}
}
checkDirectory($uploadsDir);
echo PHP_EOL;
echo 'File checked: ' . $filesChecked . PHP_EOL;
echo 'File removed: ' . $filesRemoved . PHP_EOL;
echo 'Total space freed: ' . humanFilesize($totalClear, 2) . PHP_EOL;
echo PHP_EOL;
Output::success('Завершено');