That old version was very inefficient. Here is one using a prepared statement that only makes one massive query per search term. You need to install the DirWalker extra first. It's very fast, but if the site is huge, it could time out. I would recommend renaming the orphaned images with an 'ORPHAN' prefix and waiting a while to delete them.
Note: This script may identify thumbnails as orphans when they're not.
Steps:
1. Install the DirWalker extra
2. Create a resource with this tag:
3. Create a snippet called OrphanImages with the code section below.
4. View the resource
5. Donate at
Bob's Guides
/* OrphanImages snippet */
/* Modify the next line as necessary; the search is recursive, so it will cover the dir.
specified, and all directories under it */
$imageDirectory = MODX_ASSETS_PATH . 'images';
require_once MODX_CORE_PATH . 'components/dirwalker/model/dirwalker/dirwalker.class.php';
/* Get all the files */
$dw = new DirWalker();
$dw->dirWalk($imageDirectory, true);
$files = $dw->getFiles();
/* Create Query */
$objects = array(
$modx->getTableName('modResource') => 'content',
$modx->getTableName('modChunk') => 'snippet',
$modx->getTableName('modSnippet') => 'snippet',
$modx->getTableName('modPlugin') => 'plugincode',
$modx->getTableName('modTemplate') => 'content',
$modx->getTableName('modTemplateVarResource') => 'value',
$modx->getTableName('modTemplateVar') => 'default_text',
);
$string = '';
$s = array();
foreach($objects as $table => $fieldName) {
$s[] = "(SELECT $fieldName FROM $table WHERE $fieldName LIKE :s)";
}
$string = implode(' UNION ', $s);
/* Prepare Query and bind $s param */
$sql = $modx->prepare($string);
$sql->bindParam("s", $searchTerm);
/* Execute query once for each file */
$output = '';
foreach($files as $path => $searchTerm) {
$searchTerm = "%" . $searchTerm . "%";
$sql->execute();
$count = $sql->rowCount();
$msg = $count? 'IN USE ' : '<span style="color:red">ORPHAN </span>';
$output .= "\n<br>" . $msg . $path . " Count: " . $count;
}
return $output;
[ed. note: BobRay last edited this post 8 years, 6 months ago.]