Forked from aleron75/shell_delete_unused_images
Last active
February 17, 2020 18:51
-
-
Save colinmollenhour/a6700e27c4df82c50062109c5c9c7582 to your computer and use it in GitHub Desktop.
Delete no more used Product Images on Magento
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
require_once 'abstract.php'; | |
class Mage_Shell_CheckImages extends Mage_Shell_Abstract | |
{ | |
const CATALOG_PRODUCT = '/catalog/product'; | |
const CACHE = '/cache/'; | |
public function run() | |
{ | |
if ($this->getArg('help')) { | |
echo $this->usageHelp(); | |
return; | |
} | |
$media = Mage::getBaseDir('media'); | |
$debug = $this->getArg('debug'); | |
$dryrun = $this->getArg('dry') ? true : false ; | |
$includeCache = $this->getArg('cache'); | |
$imagesOnDb = array(); | |
$imagesOnDisk = array(); | |
$setup = new Mage_Core_Model_Resource_Setup('core_setup'); | |
/** @var Varien_Db_Adapter_Pdo_Mysql $connection */ | |
$connection = $setup->getConnection(); | |
$sql = "SELECT DISTINCT value | |
FROM ( | |
SELECT value | |
FROM `{$setup->getTable('catalog_product_entity_media_gallery')}` | |
WHERE attribute_id | |
IN (SELECT attribute_id FROM `{$setup->getTable('eav_attribute')}` WHERE `attribute_code` in ('media_gallery') AND entity_type_id = 4) | |
UNION | |
SELECT value | |
FROM `{$setup->getTable('catalog_product_entity_varchar')}` | |
WHERE attribute_id | |
IN (SELECT attribute_id FROM `{$setup->getTable('eav_attribute')}` WHERE `attribute_code` in ('image','small_image','thumbnail') AND entity_type_id = 4) | |
) AS T"; | |
$result = $connection->query($sql); | |
foreach ($result->fetchAll() as $rec) { | |
$imagesOnDb[$rec['value']] = 1; | |
} | |
$imagesOnDb = array_keys($imagesOnDb); | |
if ($debug) print_r(array_slice($imagesOnDb, 0, 100)); | |
if ($debug) echo $media . "/*\n"; | |
$skip = strlen($media . self::CATALOG_PRODUCT); | |
foreach (glob($media . self::CATALOG_PRODUCT . '/?/?/*.*', GLOB_MARK) as $img) { | |
$imagesOnDisk[] = substr($img, $skip); | |
} | |
if ($debug) print_r(array_slice($imagesOnDisk, 0, 100)); | |
$imagesToDelete = array_diff($imagesOnDisk, $imagesOnDb); | |
if ($debug) { | |
print_r($imagesToDelete); | |
} else { | |
foreach ($imagesToDelete as $x) { | |
if ($dryrun) { | |
echo 'rm '.$media . self::CATALOG_PRODUCT . $x.PHP_EOL; | |
} else { | |
@unlink($media . self::CATALOG_PRODUCT . $x); | |
} | |
} | |
} | |
if ($debug) { | |
echo "\r\n"; | |
} | |
} | |
public function usageHelp() | |
{ | |
return <<<USAGE | |
Usage: php -f check_images.php | |
debug debug mode | |
cache remove cache images too | |
dry dryrun | |
USAGE; | |
} | |
} | |
$shell = new Mage_Shell_CheckImages(); | |
$shell->run(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment