You are here

function ftp_cdn_cron_perform_sync in CDN 5

Implementation of pseudo-hook hook_cdn_cron_perform_sync().

File

sync_plugins/ftp.inc, line 16
FTP synchronization plugin for the CDN integration module.

Code

function ftp_cdn_cron_perform_sync($files, $files_unique, $files_updated, $stats, $settings) {
  extract($settings);
  cdn_log(count($files) . " files will be synchronized.");
  $fs = ftp_connect($host, $port);
  if ($fs && ftp_login($fs, $user, $pass)) {
    cdn_log("Logged on to {$host}:{$port}.");

    // Change directory if necessary.
    if (isset($remote_path) && !empty($remote_path)) {
      if (ftp_chdir($fs, $remote_path)) {
        cdn_log("Changed directory to remote path ({$remote_path}).");
      }
      else {
        cdn_log("Failed to change directory to remote path ({$remote_path}).");

        // Fail immediately, otherwise we'd start uploading files into the
        // root directory!
        return $stats;
      }
    }

    // Sync deletion.
    $stats['deletes'] = _ftp_cdn_cron_sync_deletion($fs, $files_unique);

    // Sync files. Validate only by checking existence and filesize.
    $files_on_server = _ftp_cdn_get_filelist($fs, '.');
    $num = 0;
    $total = count($files_unique);
    foreach ($files as $file => $file_size) {
      $num++;
      $file_size_formatted = number_format($file_size / 1024, 1);

      // If we had to alter the original file, make sure we use that file as
      // the source file. We also have to update the filesize then.
      $source_file = $files_updated[$file];
      if ($file != $source_file) {
        $file_size = filesize($source_file);
      }
      $target_file = $files_unique[$file];
      if (isset($files_on_server[$target_file]) && $files_on_server[$target_file] == $file_size) {
        $stats['exists']++;
        $stats['exists_bytes'] += $file_size;
        cdn_log("[{$num}/{$total}] Already exists: {$target_file} ({$file_size_formatted} KB).");
      }
      else {
        if (_ftp_cdn_cron_create_path($fs, $target_file) && ftp_put($fs, "./{$target_file}", "./{$source_file}", FTP_BINARY)) {
          $stats['uploads']++;
          $stats['uploaded_bytes'] += $file_size;
          cdn_log("[{$num}/{$total}] Uploaded {$target_file} ({$file_size_formatted} KB).");
        }
        else {
          $stats['uploads_failed']++;
          cdn_log("[{$num}/{$total}] Failed to upload {$target_file}.");
        }
      }
    }
    ftp_close($fs);
    cdn_log("Logged out.");
  }
  else {
    cdn_log("Failed to log on to {$host}:{$port}.");
  }
  return $stats;
}