Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save ivanaugustobds/c4759f4596b1f69c9eae81cc9b871903 to your computer and use it in GitHub Desktop.
Save ivanaugustobds/c4759f4596b1f69c9eae81cc9b871903 to your computer and use it in GitHub Desktop.
<?php
$mediaDir = Mage::getBaseDir('media');
$varDir = Mage::getBaseDir('var');
$backupDir = "$varDir/media_unused";
if (!is_dir($backupDir)) {
mkdir($backupDir, 0770, true);
}
$productsImagesDir = "$mediaDir/catalog/product";
$validPaths = array_merge(['-'], range(0, 9));
for ($i = 'a'; $i < 'z'; $i++) {
$validPaths[] = $i;
}
$validPaths[] = 'z';
$imagesInDatabase = [];
$sql = 'SELECT * FROM catalog_product_entity_media_gallery';
$connection = Mage::getSingleton('core/resource')->getConnection('core_read');
foreach ($connection->fetchAll($sql) as $row) {
$imagesInDatabase[] = $row['value'];
}
$pathsLevel1 = array_intersect($validPaths, scandir($productsImagesDir));
foreach ($pathsLevel1 as $pathLevel1) {
$pathsLevel2 = array_intersect($validPaths, scandir("$productsImagesDir/$pathLevel1"));
foreach ($pathsLevel2 as $pathLevel2) {
$imagesAbsolutePath = "$productsImagesDir/$pathLevel1/$pathLevel2";
$images = array_diff(scandir($imagesAbsolutePath), ['.', '..']);
if (!count($images)) {
continue;
}
foreach ($images as $image) {
$imageFilePath = "/$pathLevel1/$pathLevel2/$image";
if (in_array($imageFilePath, $imagesInDatabase)) {
continue;
}
$currentBackupDir = "$backupDir/$pathLevel1/$pathLevel2";
if (!is_dir($currentBackupDir)) {
mkdir($currentBackupDir, 0770, true);
}
rename("$imagesAbsolutePath/$image", "$currentBackupDir/$image");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment