Location: PHPKode > scripts > SimpleSiteAudit > ftp_scan.php
<?php
/*
  _, _ _, _ __, _,  __,    _, _ ___ __,    _, _,_ __, _ ___  
 (_  | |\/| |_) |   |_    (_  |  |  |_    / \ | | | \ |  |   
 , ) | |  | |   | , |     , ) |  |  |     |~| | | | / |  |   
  ~  ~ ~  ~ ~   ~~~ ~~~    ~  ~  ~  ~~~   ~ ~ `~' ~~  ~  ~   v1.5.2 Multisite
 * 
 * Copyright (C) 2012 Terry Heffernan. All rights reserved.
 * Technical support: http://simplesiteaudit.terryheffernan.net
 */

 /*
   if( !ini_get('safe_mode') ){
      set_time_limit(30); // 30 secs should cover most sites. This may be your default already.
   }
*/

error_reporting (E_ALL ^ E_NOTICE);
// Start page-load timer    
$time = microtime();
$time = explode(' ', $time);
$time = $time[1] + $time[0];
$start = $time;
$files = array();
$startdir = "";

if($_GET['server']){
$ftp_server = trim($_GET['server']); // Leave
}

$logs_dir = '../../logs'; // Do not change
$db_file = $logs_dir.'/'.$ftp_server.'/db_settings.txt';

if(file_exists($db_file)){
  $db_settings = file($db_file);
}else{
  echo 'Before you run this file, please save the database settings. Run the file, index1.php';
  exit(0);
}

$db_server = trim($db_settings[0]); // database Server 
$db_user = trim($db_settings[1]);  // mysql user name
$db_pass = trim($db_settings[2]);  // mysql password
$db_name = trim($db_settings[3]);   // Name of database
        
    $key = 'hide@address.com@hide@address.com';         
    $decrypt = rtrim(mcrypt_decrypt(MCRYPT_RIJNDAEL_256, md5($key), base64_decode($db_pass), MCRYPT_MODE_CBC, md5(md5($key))), "\0");
    $db_pass = trim($decrypt);

if($ftp_server != "" && $ftp_server != null && $db_server != ""/* && $is_table_empty() > 0*/){
    $con = mysql_connect($db_server,$db_user,$db_pass)or die(mysql_error());
    mysql_select_db($db_name, $con)or die(mysql_error());
    
    $settings_table = 'ssa_'.str_replace('-','_',str_replace('.','_',$ftp_server)).'_settings';
    $result = mysql_query("SELECT FTP_user,FTP_pass,root_dir FROM $settings_table") or die(mysql_error());

    while($row = mysql_fetch_array($result)) 
    {
       $ftp_user = $row[FTP_user];
       $ftp_pw = $row[FTP_pass];
       $root_dir = $row[root_dir];
    }
    mysql_close($con)or die(mysql_error());
}

if(is_table_empty($settings_table,$db_server,$db_user,$db_pass,$db_name) > 0){
     $key = 'hide@address.com@hide@address.com';
     $decrypted = rtrim(mcrypt_decrypt(MCRYPT_RIJNDAEL_256, md5($key), base64_decode($ftp_pw), MCRYPT_MODE_CBC, md5(md5($key))), "\0");
     $ftp_pw = trim($decrypted);
}else{
     'Wrong FTP password';
     exit();
}

$date = date ("hide@address.com:i:s");

build_lists($ftp_server, $ftp_user, $ftp_pw,$db_server,$db_user,$db_pass,$startdir,$db_name,$date,$root_dir);

// Show page-load time.
$time = microtime();
$time = explode(' ', $time);
$time = $time[1] + $time[0];
$finish = $time;
$total_time = round(($finish - $start), 4);

echo '. Page loaded in ' . $total_time . ' seconds.';

/*
 *------------------------------------------------------------------------------
 *--------------------------------- Functions ----------------------------------
 *------------------------------------------------------------------------------
 */

function build_lists($ftp_server, $ftp_user, $ftp_pw ,$db_server,$db_user,$db_pass,$startdir,$db_name,$date,$root_dir){

    $con = mysql_connect($db_server,$db_user,$db_pass)or die(mysql_error());
    mysql_select_db($db_name, $con)or die(mysql_error());
    
    $site_table = 'ssa_'.stripslashes(str_replace('-','_',str_replace('.','_',$ftp_server))).'_site';
    $result = mysql_query("SELECT * FROM $site_table") or die(mysql_error());

    while($row = mysql_fetch_array($result)) 
    {
       $email_subject = $row[email_subj];
       $skipfiles = $row[skip_files];
       $skipdir = $row[skip_dir];
       $email_alert_addr = $row[email_alert];
       $email_header = $row[email_header];
       $email_from_addr = $row[from_addr];
       $excludes = explode(',',$skipfiles);
       $skip_dir = explode(',',$skipdir);
    }
    mysql_close($con)or die(mysql_error());
    
    $email_subject = $email_subject.' - '.$ftp_server; //email subject text
    $email_text = $email_header.' - '.$ftp_server."\r\n\n";

    // make FTP connection
    $conn_id = @ftp_connect($ftp_server) OR die("Unable to establish an FTP connection");
    @ftp_login($conn_id, $ftp_user, $ftp_pw) OR die("ftp-login failed - User name or password not correct");
    @ftp_pasv ( $conn_id, true ) or die("Unable to set FTP passive mode."); //Use passive mode for client-side action
    $file_list = raw_list($root_dir,$conn_id,$db_server,$db_user,$db_name,$db_pass,$ftp_server);

    ftp_close($conn_id);
    
    $newlist_prefix = 'ssa_'.str_replace('-','_',str_replace('.','_',$ftp_server)).'_newlist';
    $log_prefix = 'ssa_'.str_replace('-','_',str_replace('.','_',$ftp_server)).'_log';
    $con = mysql_connect($db_server,$db_user,$db_pass)or die(mysql_error());
    mysql_select_db($db_name, $con)or die(mysql_error());

    $oldlist = array();
    $oldlist = oldlist($newlist_prefix);

    if(!empty($oldlist)){
        $first_run = 'N';
    }else{
        $first_run = 'Y';
    }

    mysql_query("TRUNCATE TABLE  `$newlist_prefix`") or die('Unable to empty the table:<br> '.mysql_error()); 

        echo 'SSA v1.5.1 Multisite - Script run on '.$ftp_server.' on '.$date."\r\n";

        foreach ($file_list as $value) {
            $perms = $value[0];
            $size  = $value[4];
            $month = $value[5];
            $day   = $value[6];
            $year  = $value[7];
            $file_name  = $value[8];
            $path  = $value[9];

         if($file_name != "" && !in_array($file_name,$excludes)){

                if(strpos($year, ':')){
                    $time = $year;
                }

          mysql_query("INSERT INTO $newlist_prefix
                  (path,
                  filename,
                  size,
                  date,
                  time,
                  perms) 
                     VALUES ('$path',
                  '$file_name',
                  '$size',
                  '$day$month',
                  '$time',
                  '$perms')")or die(mysql_error()); 
          }
        }

        $newlist = newlist($newlist_prefix);

        if(!empty($oldlist) && is_array($newlist)){

            $diff = array_diff_key($oldlist,$newlist);

            foreach($diff as $key=>$value){
                
                $len = strlen($value[perms]);
                $remove_dirs = substr($perms,$len-10,1);
                $start = str_replace('./',"", $value[path]);
                $start = str_replace(':',"", $start);

                print 'File missing: '.$key.' - Last seen: '.$value[date].' at '.$value[time]."\r\n";
                $email_text .= 'File missing: '.$key."\r\n".'Last seen: '.$value[date].' at '.$value[time]."\r\n\n";
                    mysql_query("INSERT INTO $log_prefix
                    (status,
                        file,
                        date,
                        time,
                        old_perms,
                        new_perms,
                        old_size,
                        new_size,
                        last_run) 
                        VALUES ('Missing',
                            '$key',
                            '$value[date]',
                            '$value[time]',
                            '',
                            '',
                            '',
                            '',
                            '$date')")or die(mysql_error()); 
              }
        }

        $i = 0;
        foreach ($file_list as $value) {
            $perms = $value[0];
            $size  = $value[4];
            $month = $value[5];
            $day   = $value[6];
            $year  = $value[7];
            $file_name  = $value[8];
            $path  = $value[9];

                        
         if($file_name != ""){

                if(strpos($year, ':')){
                    $time = $year;
                }    
            $resultB = mysql_query("SELECT * FROM $newlist_prefix WHERE path = '$path' AND filename = '$file_name' ")or die(mysql_error());
            $row2 = mysql_fetch_row($resultB);                          
            $file = trim($path.'/'.$file_name);

            $size_newlist = $newlist[$file][size];
            $size_oldlist = $oldlist[$file][size];
            $new_perms = convert_perms($newlist[$file][perms]);
            $old_perms = convert_perms($oldlist[$file][perms]);

            if(!in_array($file_name,$excludes)){
            
                if($size_newlist != $size_oldlist && $newlist[$file][path] != "" && $oldlist[$file][path] != ""){
                    print 'File modified: '.$file.' - Date '.$row2[4].' Time: '.$row2[5].' Old file size = '.$size_oldlist.'bytes. New file size = '.$size_newlist.'bytes'."\r\n";
                    $email_text .= 'File modified: '.$file."\r\n".'Date '.$row2[4].' Time: '.$row2[5].' Old file size = '.$size_oldlist.'bytes. New file size = '.$size_newlist."bytes.\r\n\n";
                    mysql_query("INSERT INTO $log_prefix
                        (status,
                            file,
                            date,
                            time,
                            old_perms,
                            new_perms,
                            old_size,
                            new_size,
                            last_run) 
                            VALUES ('Modified',
                                '$file',
                                '$row2[4]',
                                '$row2[5]',
                                '$old_perms',
                                '$new_perms',
                                '$size_oldlist',
                                '$size_newlist',
                                '$date')")or die(mysql_error()); 
                    $i++;
                }
                if(!empty($diff)){
                    $i++;
                }
                if(!empty($oldlist) && $newlist[$file][path] != "" && $oldlist[$file][path] == ""){
                    print 'File added: '.$file.' - Date added: '.$row2[4].' Time added: '.$row2[5]."\r\n";
                    $email_text .= 'File added: '.$file."\r\n".'Date: '.$row2[4].' Time: '.$row2[5]."\r\n\n";
                    mysql_query("INSERT INTO $log_prefix
                        (status,
                            file,
                            date,
                            time,
                            old_perms,
                            new_perms,
                            old_size,
                            new_size,
                            last_run) 
                            VALUES ('Added',
                                '$file',
                                '$row2[4]',
                                '$row2[5]',
                                '',
                                '$new_perms',
                                '$size_oldlist',
                                '$size_newlist',
                                '$date')")or die(mysql_error()); 
                    $i++;
                }  
                if($newlist[$file][perms] != $oldlist[$file][perms] && $newlist[$file][path] != "" && $oldlist[$file][path] != ""){

                    print 'File permissions changed: '.$file.' - Old perms: '.$old_perms.' New perms: '.$new_perms."\r\n";
                    $email_text .= 'File permissions changed: '.$file."\r\n".'Old perms: '.$old_perms.' New perms: '.$new_perms."\r\n\n";
                    mysql_query("INSERT INTO $log_prefix
                        (status,
                            file,
                            date,
                            time,
                            old_perms,
                            new_perms,
                            old_size,
                            new_size,
                            last_run) 
                            VALUES ('Permissions',
                                '$file',
                                '$row2[4]',
                                '$row2[5]',
                                '$old_perms',
                                '$new_perms',
                                '$size_oldlist',
                                '$size_newlist',
                                '$date')")or die(mysql_error()); 
                    $i++;
                }
            }
         }
        }// end foreach loop

        if($i == 0 && $first_run == 'N'){
          echo 'NO CHANGES FOUND';
        }

        if($first_run == 'Y'){
          echo 'First run completed - All current website files have been added to the database';
        }

        if($i > 0){
            // Send email
            $headers = 'From: '.$email_from_addr . "\r\n" . 'X-Mailer: PHP/' . phpversion();
            mail($email_alert_addr, $email_subject, $email_text, $headers); //Simple mail function for alert. 
        }

        // Close mysql connection
        mysql_close($con)or die(mysql_error());
}

function oldlist($newlist_prefix){
    $oldlist = array();
    $old_list = mysql_query("SELECT * FROM $newlist_prefix") or die(mysql_error());
    $a = 0;
    while($row = mysql_fetch_array($old_list)){
        $key = $row['path'].'/'.$row['filename'];
            $oldlist[$key][id] = $row['id'];
            $oldlist[$key][path] = $key;
            $oldlist[$key][size] = $row['size'];
            $oldlist[$key][date] = $row['date'];
            $oldlist[$key][time] = $row['time'];
            $oldlist[$key][perms] = $row['perms'];
            $a++;
    }
    return $oldlist;
}

function newlist($newlist_prefix){
    $newlist = array();
    $new_list = mysql_query("SELECT * FROM $newlist_prefix") or die(mysql_error());
    $a = 0;
    while($row = mysql_fetch_array($new_list)){
        $key = $row['path'].'/'.$row['filename'];
            $newlist[$key][id] = $row['id'];
            $newlist[$key][path] = $key;
            $newlist[$key][size] = $row['size'];
            $newlist[$key][date] = $row['date'];
            $newlist[$key][time] = $row['time'];
            $newlist[$key][perms] = $row['perms'];
            $a++;
    }
    return $newlist;
}

function convert_perms($perms){
    $permissions = $perms;  // or whatever
      $mode = 0;

      if ($permissions[1] == 'r') $mode += 0400;
      if ($permissions[2] == 'w') $mode += 0200;
      if ($permissions[3] == 'x') $mode += 0100;
      else if ($permissions[3] == 's') $mode += 04100;
      else if ($permissions[3] == 'S') $mode += 04000;

      if ($permissions[4] == 'r') $mode += 040;
      if ($permissions[5] == 'w') $mode += 020;
      if ($permissions[6] == 'x') $mode += 010;
      else if ($permissions[6] == 's') $mode += 02010;
      else if ($permissions[6] == 'S') $mode += 02000;

      if ($permissions[7] == 'r') $mode += 04;
      if ($permissions[8] == 'w') $mode += 02;
      if ($permissions[9] == 'x') $mode += 01;
      else if ($permissions[9] == 't') $mode += 01001;
      else if ($permissions[9] == 'T') $mode += 01000;
      
      $octal = sprintf('%o', $mode, $mode);
      return $octal;
    
}

function is_table_empty($table_name,$db_server,$db_user,$db_pass,$db_name){
    
    $con = mysql_connect($db_server,$db_user,$db_pass)or die('no connection to database: '.mysql_error());
    mysql_select_db($db_name, $con)or die(mysql_error());
    
    $x = "SELECT COUNT(*) FROM $table_name"; 
    $result = mysql_query($x) or die(mysql_error()); 
    $total_rows = mysql_fetch_row($result);
    //mysql_close($con)or die(mysql_error()); 
    return $total_rows[0];    
}

#********************************************************************* 
# rawlist in recursive form (without parameter true!!!) 
#********************************************************************* 
function raw_list($folder,$conn_id,$db_server,$db_user,$db_name,$db_pass,$ftp_server){ 

  Global $files;

    $list     = ftp_rawlist($conn_id, $folder);
    $file_count  = count($list); 
    $site_table = 'ssa_'.stripslashes(str_replace('-','_',str_replace('.','_',$ftp_server))).'_site';

    $con = mysql_connect($db_server,$db_user,$db_pass)or die(mysql_error());
    mysql_select_db($db_name, $con)or die(mysql_error());
    $result = mysql_query("SELECT * FROM $site_table") or die('MySQL query failed<br>'.mysql_error());

    while($row = mysql_fetch_array($result)){
       $skip_dir = $row[skip_dir];
    }

    $site_table = 'ssa_'.stripslashes(str_replace('-','_',str_replace('.','_',$ftp_server))).'_site';    
    $skipdir = explode(',',$skip_dir);
    mysql_close($con)or die(mysql_error());

    $i = 0;
    while ($i < $file_count){ 
      $split    = preg_split("/[\s]+/", $list[$i], 9, PREG_SPLIT_NO_EMPTY);
      array_push($split, $folder);

      $ItemName = $split[8]; 
      $path     = $folder.'/'.$ItemName;
      $path_array = explode('/',$path);

     if (substr($list[$i],0,1) === "d" && !array_intersect($path_array,$skipdir) && $ItemName != "." && $ItemName != ".."){
         raw_list($path,$conn_id,$db_server,$db_user,$db_name,$db_pass,$ftp_server); 
     }elseif (substr($list[$i],0,1) != "d" && !array_intersect($path_array,$skipdir) && $ItemName != "." && $ItemName != ".."){ 
         array_push($files, $split);
     }
      $i++; 
    }
    return $files; 
}
?>
Return current item: SimpleSiteAudit