<?php 

set_time_limit(0);

$log = new LogBuffer();

$ftp_host = "192.168.2.200";
$ftp_user = "guestupload";
$ftp_pass = "guestupload";
$ftp_path = "pub/Installazione_ES";
$ftp_mask = "*_evserv.zip";
$ftp_action = "check";
$ftp_force = "no";
$ftp_unzip = "no";

if(isset($_REQUEST['submit']))
{
  $ftp_host = array_get($_REQUEST, 'ftp_host');
  $ftp_user = array_get($_REQUEST, 'ftp_user');
  $ftp_pass = array_get($_REQUEST, 'ftp_pass');
  $ftp_path = array_get($_REQUEST, 'ftp_path');
  $ftp_mask = array_get($_REQUEST, 'ftp_mask');
  $ftp_action = array_get($_REQUEST, 'ftp_action');
  $ftp_force = array_get($_REQUEST, 'ftp_force', 'no');
  $ftp_unzip = array_get($_REQUEST, 'ftp_unzip', 'no');

  $ftp = new FtpClient($ftp_host);

  if($ftp->isOpen())
  {
    $log->log("FTP CONNECTED TO {$ftp_host}");
    if($ftp->login($ftp_user, $ftp_pass))
    {
      $log->log("FTP LOGGED IN WITH USER {$ftp_user}");
      $files = $ftp->nlist($ftp_path.'/'.$ftp_mask);
      if($files !== false)
      {
        $log->log("FTP NLIST SUCCESS, FOUND ".count($files)." FILES!");
        sort($files);
        $remotePath = array_last($files);
        if($remotePath != null)
        {
          $filename = basename($remotePath);
          $time = $ftp->getFileTime($remotePath);
          $size = $ftp->getFileSize($remotePath);
          $log->log("LAST UPDATE {$remotePath}, Time={$time}, Size={$size} (".formatBytes($size).")");
          $space = disk_free_space(app()->runtimePath);
          $log->log("FREE SPACE ON DISK: {$space} (".formatBytes($space).")");
          if($ftp_action == 'download')
          {
            if($space >= $size)
            {
              $localPath = pathCombine(app()->runtimePath,$filename);
              $log->log("FILE WILL BE DOWNLOADED TO {$localPath}");
              $resumePos = fileExists($localPath) ? filesize($localPath) : 0;

              $downloadResult = false;
              $downloadTime = new StopWatch();
              if($resumePos == $size && $ftp_force != "yes")
              {
                $log->log("FILE ALREADY HERE!!");
                $downloadResult = true;
                $restSize = 0;
              }
              else
              {
                $log->log("DOWNLOADING FROM SERVER...");
                if($ftp_force == "yes")
                {
                  $log->log("DOWNLOAD FORCED");
                  $resumePos = 0;
                }
                $restSize = $size - $resumePos;
                if($resumePos > 0)
                {
                  $log->log("(DOWNLOAD RESUMED FROM {$resumePos} bytes OF {$size})");
                }
                $downloadResult = $ftp->download($remotePath, $localPath, $resumePos);
              }
              $downloadTime = $downloadTime->elapsed();

              if($downloadResult)
              {
                $speed = $restSize / $downloadTime;

                $log->log("DOWNLOAD SUCCESS (size=<b>".formatBytes($restSize)."</b> elapsed=<b>".round($downloadTime,2)." s</b>, speed=<b>".formatBytes($speed)."/s</b>)!");
                $log->log("TESTING ZIP ARCHIVE...");
                $testResult = ziptest($localPath);
                $log->log("...TEST RESULT {$testResult}");
                if($testResult != "OK")
                {
                  $deleteResult = _2str(unlink($localPath));
                  $log->log("FILE CORRUPTED, HAS BEEN DELETED ({$deleteResult})");
                }
                else
                {
                  $log->log("ZIP FILE DOWNLOADED CORRECTLY!");
                  if($ftp_unzip == "yes")
                  {
                    $root = realpath(app()->basePath."\\..\\..");
                    $folderName = basename_wo_ext($localPath);
                    $root = pathCombine($root, $folderName);
                    $log->log("UNZIPPING TO {$root}");
                    $unzipResult = _2str(unzip($localPath, $root.""));
                    $log->log("UNZIP RESULT: {$unzipResult}");
                  }
                }
              }
              else $log->log("DOWNLOAD FAILED!");
            }
            else $log->log("NO MORE FREE SPACE ON DRIVE!");
          }// fine download
        }
        else $log->log("LAST UPDATE NOT FOUND!");
      }
      else $log->log("FTP NLIST FAILED!");
    }
    else $log->log("FTP LOGIN FAILED!");
  }
  else $log->log("FTP CONNECT TO ftp://{$ftp_user}@{$ftp_host}/{$ftp_path} FAILED!");
}

?>
<form method="post">
  <label for="ftp_host">ftp_host</label><input id="ftp_host"
    name="ftp_host" type="text" value="<?php echo($ftp_host); ?>" />(for
  example: hq.kria.biz) <label for="ftp_user">ftp_user</label><input
    id="ftp_user" name="ftp_user" type="text"
    value="<?php echo($ftp_user); ?>" /> <label for="ftp_pass">ftp_user</label><input
    id="ftp_pass" name="ftp_pass" type="password"
    value="<?php echo($ftp_pass); ?>" /> <label for="ftp_path">ftp_path</label><input
    id="ftp_path" name="ftp_path" type="text"
    value="<?php echo($ftp_path); ?>" /> <label for="ftp_mask">ftp_mask</label><input
    id="ftp_mask" name="ftp_mask" type="text"
    value="<?php echo($ftp_mask); ?>" /> <label for="ftp_action">ftp_action</label><select
    name="ftp_action" id="ftp_action">
    <option value="check">check</option>
    <option value="download">download</option>
  </select>
  <div
    style="border: 1px solid gray; border-radius: 10px; margin: 5px 5px 5px 5px; padding: 15px 15px 15px 15px;">
    <b>Download Action Options</b><br />
    <label  style="display: inline;"for="ftp_force">ftp_force</label>
    <input id="ftp_force" name="ftp_force" type="checkbox" value="yes" /> 
      <label  style="display: inline;" for="ftp_unzip">ftp_unzip</label>
      <input  style="display: inline;" id="ftp_unzip" name="ftp_unzip" type="checkbox" value="yes" />
  </div>
  <input type="submit" name="submit" value="submit" />
</form>
<?php if(!$log->isEmpty()) echo("<hr /><pre>$log</pre>"); ?>

