Cleaning up the old images in your Drupal 7 Drealty realtor site

3 years 2 months ago

Update, this is an old method not using drush.  The best way to do this is actually use the routine Drealty provides:

drush -u admin rets-purge-inactive

However, if you want some code that just cleans up the images for now:

Drealty is an amazing module that makes getting a realtor website up relatively easy given a valid RETS feed.  I recently finished coding using Drealty, Leaflet, and other great open source modules.  The site keeps about 150,000 properties updated on the site every 3 hours.  However, there is a glaring issue, that I have been entitling "the gathering threat."

The site is being hosted on a GoDaddy VPS which has limited file space.  About a week ago I started getting automated emails saying that the space was filling up.  87%, 88%, 89%.. etc.  The Dreality module doesnt clear the images from the server after a listing becomes inactive.  Given enough time with any Drealty site on a server with limited storage space the site will eventually break.

Here is the code I used to fix it.  I will have to run it every couple months.  Feel free to use/modify this code to clean up the old images in your drealty site.

$i = 0; //set counter
$debug = 0; //turn on to see the files being deleted
$sql = "SELECT fid,filename FROM `drup_drealty_listing` left join drup_field_data_field_images on entity_id = id left join drup_file_managed on fid = field_images_fid WHERE active = 0 and drup_file_managed.uid <= 1";

$result = db_query($sql);
echo 'TOTAL: '.$result->rowCount()."<br>";

foreach ($result as $record) {
  if ($i < 10000){ //10,000 at a time seems to be doable
    $daid = $record->fid;
    $dafilename = $record->filename;

    if ($debug){
      echo $daid." | ";
      echo $dafilename."<br>";

    $path = 'sites/default/files';

    if (file_exists($path."/".$dafilename)) {
      if ($debug){
        echo "file deleted from ".$path."<br>";
      unlink($path."/".$dafilename); //delete it

    //clean up the other styles if they are there
    $path = 'sites/default/files/styles';
    $results = scandir($path);

    foreach ($results as $result) {
      if ($result === '.' or $result === '..') continue;
        if (is_dir($path . '/' . $result)) {
        $fulldir = $path . '/' . $result."/public/";

        if (file_exists($fulldir.$dafilename)) {
          if ($debug){
            echo "file deleted from ".$fulldir."<br>";


    //update user id so it doesnt happen the next time
    $sql = "update drup_file_managed set uid = 2 where fid = '".$daid."'";

    $i = $i + 1;
    if ($debug){
      echo $sql."<br>";
      echo "<br>";
echo "Did ".$i." records.";