msft-trns/cleanup.php
2026-03-02 17:21:57 +00:00

70 lines
No EOL
2.2 KiB
PHP

<?php
/**
* Document cleanup script
* Removes files older than 24 hours from source and translated documents folders
*/
// Include the logger
require_once 'logger.php';
function cleanupOldFiles() {
logMessage('Starting cleanup process', 'CLEANUP');
// Define directories
$sourceDir = __DIR__ . '/local_storage/source-documents/';
$translatedDir = __DIR__ . '/local_storage/translated-documents/';
// Current timestamp
$now = time();
// 24 hours in seconds
$dayInSeconds = 24 * 60 * 60;
// Cutoff time (24 hours ago)
$cutoffTime = $now - $dayInSeconds;
// Files removed counter
$removedCount = 0;
// Function to clean a directory
$cleanDirectory = function($directory) use ($cutoffTime, &$removedCount) {
if (!is_dir($directory)) {
logMessage("Directory not found: $directory", 'CLEANUP');
return;
}
$files = scandir($directory);
foreach ($files as $file) {
// Skip . and .. and hidden files
if ($file[0] === '.') {
continue;
}
$filePath = $directory . $file;
if (is_file($filePath)) {
$fileModTime = filemtime($filePath);
if ($fileModTime < $cutoffTime) {
// File is older than 24 hours, delete it
if (unlink($filePath)) {
logMessage("Deleted old file: $file (modified: " . date('Y-m-d H:i:s', $fileModTime) . ")", 'CLEANUP');
$removedCount++;
} else {
logMessage("Failed to delete file: $file", 'CLEANUP');
}
}
}
}
};
// Clean both directories
$cleanDirectory($sourceDir);
$cleanDirectory($translatedDir);
logMessage("Cleanup completed. Removed $removedCount old files.", 'CLEANUP');
return $removedCount;
}
// Execute cleanup if script is called directly
if (basename(__FILE__) == basename($_SERVER['SCRIPT_FILENAME'])) {
$removed = cleanupOldFiles();
echo "Cleanup completed. Removed $removed old files.\n";
}