Skip to content

Instantly share code, notes, and snippets.

@eriksimonic
Created June 21, 2015 20:47
Show Gist options
  • Save eriksimonic/6b52f2675dbed6b9cf54 to your computer and use it in GitHub Desktop.
Save eriksimonic/6b52f2675dbed6b9cf54 to your computer and use it in GitHub Desktop.
Detect obsolete images in media/catalog/product
<?php
/**
* Created by PhpStorm.
* User: Admin
* Date: 20. 06. 2015
* Time: 15:21
*/
///catalog_product_entity_media_gallery
ini_set('display_errors', 1);
umask(0);
require_once(getcwd() . '/app/Mage.php');
Mage::app()->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID);
class CheckImages
{
static $tableName = null;
static $core_read = null;
private function CheckIfExists($image)
{
if (!isset(self::$tableName))
self::$tableName = Mage::getSingleton('core/resource')->getTableName('catalog/product_attribute_media_gallery');
if (null == self::$core_read)
self::$core_read = Mage::getSingleton('core/resource')->getConnection('core_read');
$tableName = self::$tableName;
$query = "SELECT count(1) as `c` FROM `{$tableName}` WHERE `value` = :image";
return (int)self::$core_read->fetchAll($query, array(
':image' => $image
))[0]['c'] !== 0;
}
private function TraverseTree($root)
{
// Data structure to hold names of subfolders to be
// examined for files.
$dirs = array(20);
$files = array();
if (!is_dir($root)) {
throw new Exception("Root dir dows not exists");
}
array_push($dirs, $root);
while (count($dirs) > 0)
{
$currentDir = array_pop($dirs);
$subDirs = array_diff(scandir($currentDir), array('.', '..'));
$currentDir = rtrim($currentDir, DS);
foreach ($subDirs as $d)
{
$dir_x = $currentDir . DS . $d ;
if (is_dir($dir_x))
{
array_push($dirs, $dir_x );
}
else if (is_file($dir_x))
{
$files[] = DS . str_replace($root, '', $dir_x);// substr( ) strlen( $root ), $dir_x;
}
}
}
return $files;
}
private function CheckMediaCatalog()
{
$base_dir = getcwd() . "/media/catalog/product/";
echo "Enumerating media catalog: \n";
$response = self::TraverseTree($base_dir);
echo "Media enumerated found: {count($response)} \n";
foreach($response as $r)
{
if(self::CheckIfExists($r) === false)
{
echo rtrim( $base_dir , DS ) . $r . "\n";
}
}
}
public function CheckAll()
{
self::CheckMediaCatalog();
}
}
$v = new CheckImages();
$v->CheckAll();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment