Skip to content

Instantly share code, notes, and snippets.

@Da-Fecto
Created September 8, 2013 13:12
Show Gist options
  • Save Da-Fecto/6484624 to your computer and use it in GitHub Desktop.
Save Da-Fecto/6484624 to your computer and use it in GitHub Desktop.
Clean orphaned files processwire. code from Ryan Cramer
<pre><?php
ini_set('max_execution_time', 60*5); // 5 minutes, increase as needed
include("./index.php");
$dir = new DirectoryIterator(wire('config')->paths->files);
foreach($dir as $file) {
if($file->isDot() || !$file->isDir()) continue;
$id = $file->getFilename();
if(!ctype_digit("$id")) continue;
$page = wire('pages')->get((int) $id);
if(!$page->id) {
echo "Orphaned directory: " . wire('config')->urls->files . "$id/" . $file->getBasename() . "\n";
continue;
}
// determine which files are valid for the page
$valid = array();
foreach($page->template->fieldgroup as $field) {
if($field->type instanceof FieldtypeFile) {
foreach($page->get($field->name) as $file) {
$valid[] = $file->basename;
if($field->type instanceof FieldtypeImage) {
foreach($file->getVariations() as $f) {
$valid[] = $f->basename;
}
}
}
}
}
// now find all the files present on the page
// identify those that are not part of our $valid array
$d = new DirectoryIterator($page->filesManager->path);
foreach($d as $f) {
if($f->isDot() || !$f->isFile()) continue;
if(!in_array($f->getFilename(), $valid)) {
echo "Orphaned file: " . wire('config')->urls->files . "$id/" . $f->getBasename() . "\n";
// unlink($f->getPathname());
}
}
wire('pages')->uncache($page); // just in case we need the memory
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment