Skip to content

Instantly share code, notes, and snippets.

@liamcmitchell
Last active December 12, 2015 02:08
Show Gist options
  • Save liamcmitchell/4696595 to your computer and use it in GitHub Desktop.
Save liamcmitchell/4696595 to your computer and use it in GitHub Desktop.
Drush script to repair a Drupal 6 files table that has mixed file directory paths. This usually happens when the files dir is never set and the site is moved or access from more than one path via symlinks. Do not use if the files are actually in mixed directories. Usage: drush php-script repair-files-table.php
#!/usr/bin/env drush
<?php
// Check site is bootstrapped
$self_record = drush_sitealias_get_record('@self');
if (!empty($self_record)) {
$count = 0;
$regex = '|^sites/(.*)/files|';
$files_dir = file_directory_path();
// Loop over all rows
$result = db_query("SELECT * FROM {files} WHERE 1");
while ($row = db_fetch_object($result)) {
// Only repair rows that need fixing and match the regex
if (strpos($row->filepath, $files_dir) !== 0
&& preg_match($regex, $row->filepath)) {
// Correct path
$filepath = preg_replace($regex, $files_dir, $row->filepath);
// Log new path (accessible using --debug flag)
dlm($filepath);
// Update DB, any errors appear in drush output
db_query("UPDATE {files} SET filepath = '%s' WHERE fid = '%d'", $filepath, $row->fid);
$count++;
}
}
if ($count) {
drupal_flush_all_caches();
}
drush_log($count.' rows repaired.', 'ok');
}
else {
drush_log('No bootstrapped site.', 'error');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment