function syncFolderToFtp($host, $username, $password, $remote_backup, $backup_folder)
{
    $ftp = ftp_connect($host);
    // connect to the ftp server
    ftp_login($ftp, $username, $password);
    // login to the ftp server
    ftp_chdir($ftp, $remote_backup);
    // cd into the remote backup folder
    // copy files from folder to remote folder
    $files = glob($backup_folder . '*');
    $c = 0;
    $allc = count($files);
    foreach ($files as $file) {
        $c++;
        $file_name = basename($file);
        echo "\n {$c}/{$allc}: {$file_name}";
        $upload = ftp_nb_put($ftp, $file_name, $file, FTP_BINARY);
        // non-blocking put, uploads the local backup onto the remote server
        while ($upload == FTP_MOREDATA) {
            // Continue uploading...
            $upload = ftp_nb_continue($ftp);
        }
        if ($upload != FTP_FINISHED) {
            echo " ... ERROR";
        } else {
            echo " ... OK";
        }
    }
    ftp_close($ftp);
    // closes the connection
}
Example #2
0
 /**
  * FTP-文件下载
  *
  * @param string  $local_file 本地文件
  * @param string  $ftp_file Ftp文件
  *
  * @return bool
  */
 public function download($local_file, $ftp_file)
 {
     if (empty($local_file) || empty($ftp_file)) {
         return false;
     }
     $ret = ftp_nb_get($this->linkid, $local_file, $ftp_file, FTP_BINARY);
     while ($ret == FTP_MOREDATA) {
         $ret = ftp_nb_continue($this->linkid);
     }
     if ($ret != FTP_FINISHED) {
         return false;
     }
     return true;
 }
Example #3
0
 function put($localFile, $remoteFile = '')
 {
     if ($remoteFile == '') {
         $remoteFile = end(explode('/', $localFile));
     }
     $res = ftp_nb_put($this->ftpR, $remoteFile, $localFile, FTP_BINARY);
     while ($res == FTP_MOREDATA) {
         $res = ftp_nb_continue($this->ftpR);
     }
     if ($res == FTP_FINISHED) {
         return true;
     } elseif ($res == FTP_FAILED) {
         return false;
     }
 }
Example #4
0
 /**
  * Construct the routine that must be run.
  *
  * @param  array  $files  Files to upload
  * @param  array  $options  FTP Connection options.
  *
  * @return  void
  */
 public function __construct($files, $options = [])
 {
     parent::__construct();
     $this->_sig_complete = new SIG_Complete();
     $this->_sig_failure = new SIG_Failure();
     $this->_sig_finished = new SIG_Finished($this);
     $defaults = ['hostname' => null, 'port' => 21, 'timeout' => 90, 'username' => null, 'password' => null, 'secure' => false];
     $this->_files = $files;
     $options += $defaults;
     $this->_options = $options;
     /**
      * Upload Idle process
      */
     $this->_idle = new Process(function () {
         $this->_init_transfers();
         foreach ($this->_uploading as $_key => $_file) {
             $status = ftp_nb_continue($_file[0]);
             if ($status === FTP_MOREDATA) {
                 continue;
             }
             if ($status === FTP_FINISHED) {
                 $this->_sig_complete->set_upload($_file[1]);
                 xp_emit($this->_sig_complete);
                 // Close the FTP connection to that file
                 ftp_close($_file[0]);
                 $this->_uploaded[] = $_file[1];
             } else {
                 $this->_sig_failure->set_upload($_file[1]);
                 xp_emit($this->_sig_failure);
                 // Close the FTP connection to that file
                 ftp_close($_file[0]);
             }
             unset($this->_uploading[$_key]);
         }
         // Cleanup once finished
         if (count($this->_uploading) == 0) {
             xp_emit($this->_sig_finished);
             xp_delete_signal($this);
             xp_delete_signal($this->_sig_complete);
             xp_delete_signal($this->_sig_failure);
         }
     });
     // Init
     xp_emit($this);
 }
Example #5
0
 /**
  * XU_Ftp::download_xu()
  *
  * Download a file
  *
  * @access  public
  * @param   string	$remote_file	Remote filename
  * @param   string	$fid			File ID
  * @param   bool	$max_size		Max file size
  * @return  bool
  */
 public function download_xu($remote_file, $fid, $max_size)
 {
     if (!$this->_is_conn()) {
         return FALSE;
     }
     $result = TRUE;
     // if no filepointer is given, make a temp file and open it for writing
     $tmpfname = tempnam(ROOTPATH . '/temp', "RFT-");
     $l_fp = fopen($tmpfname, "wb");
     // Initate the download
     $i = 0;
     $CI =& get_instance();
     $ret = ftp_nb_fget($this->conn_id, $l_fp, $remote_file, FTP_BINARY);
     while ($ret == FTP_MOREDATA) {
         if ($i % 10 == 0) {
             $fstat = fstat($l_fp);
             $p = $fstat[7];
             $CI->db->where('fid', $fid);
             $CI->db->update('progress', array('progress' => $p, 'curr_time' => time()));
         }
         // Continue downloading...
         $ret = ftp_nb_continue($this->conn_id);
         $i++;
     }
     // Has it finished completly?
     if ($ret != FTP_FINISHED) {
         log_message('error', "FTP TRANSFER FAILED");
         $result = FALSE;
     }
     if ($result === FALSE) {
         if ($this->debug == TRUE) {
             $msg = 'ftp_unable_to_download';
             $this->_error($msg);
         } else {
             $this->error = TRUE;
             $this->error_msg = 'ftp_unable_to_download';
         }
         return FALSE;
     }
     return $tmpfname;
 }
 function isbusy()
 {
     $result = false;
     do {
         if (self::$ret != FTP_MOREDATA) {
             break;
         }
         self::$ret = @ftp_nb_continue(self::$cid);
         switch (self::$ret) {
             case FTP_MOREDATA:
                 clearstatcache();
                 $size = filesize(self::$temp_file);
                 if (self::$size == $size && ++self::$counts > 10) {
                     self::$size = 0;
                     self::$counts = 0;
                     self::close();
                     break 2;
                 }
                 self::$size = $size;
                 return true;
             case FTP_FINISHED:
                 self::$size = 0;
                 self::$counts = 0;
                 rename(self::$temp_file, self::$local_file);
                 self::close();
                 $result = true;
                 break 2;
             default:
                 // FTP_FAILED
                 self::$size = 0;
                 self::$counts = 0;
                 self::halt("Lost connection to FTP server during query");
                 break 2;
         }
     } while (false);
     if (self::$fp) {
         fclose(self::$fp);
         self::$fp = NULL;
     }
     return $result;
 }
Example #7
0
 /**
  * @return int
  */
 public function AsynchronouslyContinue()
 {
     return ftp_nb_continue($this->getFtp());
 }
Example #8
0
 /**
  * Continues retrieving/sending a file (non-blocking)
  * @link http://php.net/ftp_nb_continue
  *
  * @return integer FTPWrapper::FAILED, FTPWrapper::FINISHED or FTPWrapper::MOREDATA
  */
 public function nbContinue()
 {
     return ftp_nb_continue($this->connection->getStream());
 }
Example #9
0
File: FTP.php Project: uda/jaws
 /**
  * This function will upload a file to the ftp-server. You can either specify a
  * absolute path to the remote-file (beginning with "/") or a relative one,
  * which will be completed with the actual directory you selected on the server.
  * You can specify the path from which the file will be uploaded on the local
  * maschine, if the file should be overwritten if it exists (optionally, default
  * is no overwriting) and in which mode (FTP_ASCII or FTP_BINARY) the file
  * should be downloaded (if you do not specify this, the method tries to
  * determine it automatically from the mode-directory or uses the default-mode,
  * set by you).
  * If you give a relative path to the local-file, the script-path is used as
  * basepath.
  *
  * @param string $local_file  The local file to upload
  * @param string $remote_file The absolute or relative path to the file to
  *                            upload to
  * @param bool   $overwrite   (optional) Whether to overwrite existing file
  * @param int    $mode        (optional) Either FTP_ASCII or FTP_BINARY
  * @param int    $options     (optional) Flags describing the behaviour of this
  *                            function. Currently NET_FTP_BLOCKING and 
  *                            NET_FTP_NONBLOCKING are supported, of which
  *                            NET_FTP_NONBLOCKING is the default.
  *
  * @access public
  * @return mixed True on success, otherwise PEAR::Error
  * @see NET_FTP_ERR_LOCALFILENOTEXIST,
  *      NET_FTP_ERR_OVERWRITEREMOTEFILE_FORBIDDEN,
  *      NET_FTP_ERR_UPLOADFILE_FAILED, NET_FTP_NONBLOCKING, NET_FTP_BLOCKING
  */
 function put($local_file, $remote_file, $overwrite = false, $mode = null, $options = 0)
 {
     if ($options & (NET_FTP_BLOCKING | NET_FTP_NONBLOCKING) === (NET_FTP_BLOCKING | NET_FTP_NONBLOCKING)) {
         return $this->raiseError('Bad options given: NET_FTP_NONBLOCKING and ' . 'NET_FTP_BLOCKING can\'t both be set', NET_FTP_ERR_BADOPTIONS);
     }
     $usenb = !($options & NET_FTP_BLOCKING == NET_FTP_BLOCKING);
     if (!isset($mode)) {
         $mode = $this->checkFileExtension($local_file);
     }
     $remote_file = $this->_constructPath($remote_file);
     if (!@file_exists($local_file)) {
         return $this->raiseError("Local file '{$local_file}' does not exist.", NET_FTP_ERR_LOCALFILENOTEXIST);
     }
     if (@ftp_size($this->_handle, $remote_file) != -1 && !$overwrite) {
         return $this->raiseError("Remote file '" . $remote_file . "' exists and may not be overwriten.", NET_FTP_ERR_OVERWRITEREMOTEFILE_FORBIDDEN);
     }
     if (function_exists('ftp_alloc')) {
         ftp_alloc($this->_handle, filesize($local_file));
     }
     if ($usenb && function_exists('ftp_nb_put')) {
         $res = @ftp_nb_put($this->_handle, $remote_file, $local_file, $mode);
         while ($res == FTP_MOREDATA) {
             $this->_announce('nb_put');
             $res = @ftp_nb_continue($this->_handle);
         }
     } else {
         $res = @ftp_put($this->_handle, $remote_file, $local_file, $mode);
     }
     if (!$res) {
         return $this->raiseError("File '{$local_file}' could not be uploaded to '" . $remote_file . "'.", NET_FTP_ERR_UPLOADFILE_FAILED);
     } else {
         return true;
     }
 }
Example #10
0
 public function get($local_file_path, $remote_file_path, $mode = FTP_BINARY, $resume = false, $updraftplus = false)
 {
     $file_last_size = 0;
     if ($resume) {
         if (!($fh = fopen($local_file_path, 'ab'))) {
             return false;
         }
         clearstatcache($local_file_path);
         $file_last_size = filesize($local_file_path);
     } else {
         if (!($fh = fopen($local_file_path, 'wb'))) {
             return false;
         }
     }
     $ret = ftp_nb_fget($this->conn_id, $fh, $remote_file_path, $mode, $file_last_size);
     if (false == $ret) {
         return false;
     }
     while ($ret == FTP_MOREDATA) {
         if ($updraftplus) {
             $file_now_size = filesize($local_file_path);
             if ($file_now_size - $file_last_size > 524288) {
                 $updraftplus->log("FTP fetch: file size is now: " . sprintf("%0.2f", filesize($local_file_path) / 1048576) . " Mb");
                 $file_last_size = $file_now_size;
             }
             clearstatcache($local_file_path);
         }
         $ret = ftp_nb_continue($this->conn_id);
     }
     fclose($fh);
     if ($ret == FTP_FINISHED) {
         if ($updraftplus) {
             $updraftplus->log("FTP fetch: fetch complete");
         }
         return true;
     } else {
         if ($updraftplus) {
             $updraftplus->log("FTP fetch: fetch failed");
         }
         return false;
     }
 }
Example #11
0
function ftp_uploading_compile($ftpFolder, $connect_data, $current_file_uri, $current_file_dir)
{
    $ftp_connect = @ftp_connect($connect_data['ftp_hostname']);
    $ftp_login = @ftp_login($ftp_connect, $connect_data['ftp_username'], $connect_data['ftp_password']);
    if (!$ftp_login) {
        return false;
    } else {
        if (substr($ftpFolder, strlen($ftpFolder) - 1) != "/") {
            $d = ftp_nb_put($ftp_connect, $ftpFolder . '/archive.zip', $current_file_dir, FTP_BINARY);
        } else {
            $d = ftp_nb_put($ftp_connect, $ftpFolder . 'archive.zip', $current_file_dir, FTP_BINARY);
        }
        while ($d == FTP_MOREDATA) {
            $d = ftp_nb_continue($ftp_connect);
        }
        if ($d != FTP_FINISHED) {
            exit(1);
        }
        if (substr($ftpFolder, strlen($ftpFolder) - 1) != "/") {
            $d = ftp_nb_put($ftp_connect, $ftpFolder . '/unziper.php', COMPILER_FOLDER . 'unzip.php', FTP_BINARY);
        } else {
            $d = ftp_nb_put($ftp_connect, $ftpFolder . 'unziper.php', COMPILER_FOLDER . 'unzip.php', FTP_BINARY);
        }
        while ($d == FTP_MOREDATA) {
            $d = ftp_nb_continue($ftp_connect);
        }
        if ($d != FTP_FINISHED) {
            exit(1);
        }
        if (substr($connect_data['site_url'], strlen($connect_data['site_url']) - 1) != "/") {
            $host['unzip'] = $connect_data['site_url'] . '/unziper.php';
            $host['dump'] = $connect_data['site_url'] . '/db_upload.php';
        } else {
            $host['unzip'] = $connect_data['site_url'] . 'unziper.php';
            $host['dump'] = $connect_data['site_url'] . 'db_upload.php';
        }
        $host['link'] = $connect_data['site_url'];
        // close connection
        ftp_close($ftp_connect);
        echo json_encode($host);
        return true;
    }
}
Example #12
0
function get_htaccess($ftp_handle, $dir)
{
    $local_htaccess = tempnam("files", "down");
    $ftp_htaccess = str_replace("//", "/", $dir . '/.htaccess');
    $ret = @ftp_nb_get($ftp_handle, $local_htaccess, $ftp_htaccess, FTP_BINARY);
    while ($ret == FTP_MOREDATA) {
        // Продолжаем загрузку
        $ret = @ftp_nb_continue($ftp_handle);
    }
    @chmod($local_htaccess, 0644);
    $content = @file_get_contents($local_htaccess);
    @unlink($local_htaccess);
    return $content;
}
Example #13
0
<?php

require 'server.inc';
$file = "mediumfile.txt";
$ftp = ftp_connect('127.0.0.1', $port);
ftp_login($ftp, 'user', 'pass');
if (!$ftp) {
    die("Couldn't connect to the server");
}
$local_file = dirname(__FILE__) . DIRECTORY_SEPARATOR . $file;
touch($local_file);
$r = ftp_nb_get($ftp, $local_file, $file, FTP_BINARY);
while ($r == FTP_MOREDATA) {
    $r = ftp_nb_continue($ftp);
}
ftp_close($ftp);
echo file_get_contents($local_file);
error_reporting(0);
@unlink(dirname(__FILE__) . DIRECTORY_SEPARATOR . "mediumfile.txt");
Example #14
0
 public function put($local_file, $remote_file, $overwrite = false, $mode = null, $options = 0)
 {
     if ($options & (FILE_FTP_BLOCKING | FILE_FTP_NONBLOCKING) === (FILE_FTP_BLOCKING | FILE_FTP_NONBLOCKING)) {
         throw new FTPException("Bad options given: FILE_FTP_NONBLOCKING and '. 'FILE_FTP_BLOCKING can't both be set");
     }
     $usenb = !($options & FILE_FTP_BLOCKING == FILE_FTP_BLOCKING);
     if (!isset($mode)) {
         $mode = $this->checkFileExtension($local_file);
     }
     $remote_file = $this->constructPath($remote_file);
     if (!file_exists($local_file)) {
         throw new FTPException("Local file '{$local_file}' does not exist.");
     }
     if (ftp_size($this->handle, $remote_file) != -1 && !$overwrite) {
         throw new FTPException("Remote file '" . $remote_file . "' exists and may not be overwriten.");
     }
     if (function_exists('ftp_alloc')) {
         ftp_alloc($this->handle, filesize($local_file));
     }
     if ($usenb && function_exists('ftp_nb_put')) {
         $res = ftp_nb_put($this->handle, $remote_file, $local_file, $mode);
         while ($res == FTP_MOREDATA) {
             $res = ftp_nb_continue($this->handle);
         }
     } else {
         $res = ftp_put($this->handle, $remote_file, $local_file, $mode);
     }
     if (!$res) {
         throw new FTPException("File '{$local_file}' could not be uploaded to '" . $remote_file . "'.");
     }
     return true;
 }
Example #15
0
 protected function nb_get($localfile, $remotefile, $start = FTP_AUTORESUME)
 {
     clearstatcache();
     if (!file_exists($localfile)) {
         $start = 0;
     }
     $ret = @ftp_nb_get($this->connexion, $localfile, $remotefile, FTP_BINARY, $start);
     while ($ret === FTP_MOREDATA) {
         set_time_limit(20);
         $ret = ftp_nb_continue($this->connexion);
     }
     return $ret;
 }
Example #16
0
 /** Reads the log.
  * This function reads all the remaining log since last read (paying no attention to line returns). It also downloads it from an FTP server if specified.
  * 
  * \return The read data if averything passed correctly, FALSE otherwise. If no data has been read, it returns an empty string.
  */
 public function readLog()
 {
     switch ($this->_logfile['type']) {
         case 'ftp':
             //If we have finished to download the log, we read it and restart downloading
             if ($this->_logfile['state'] == FTP_FINISHED) {
                 $data = '';
                 //We read only if the pointer has changed, i.e. something has been downloaded.
                 if ($this->_logfile['pointer'] != ftell($this->_logfile['fp'])) {
                     fseek($this->_logfile['fp'], $this->_logfile['pointer']);
                     //Reset file pointer to last read position (ftp_nb_fget moves the pointer)
                     $data = '';
                     $read = NULL;
                     while ($read === NULL || $read) {
                         $read = fread($this->_logfile['fp'], 1024);
                         $data .= $read;
                     }
                     $this->_logfile['pointer'] = ftell($this->_logfile['fp']);
                     //Save new pointer position
                 }
                 //Calculation of new global pointer and sending command
                 $totalpointer = $this->_logfile['pointer'] + $this->_logfile['origpointer'];
                 $this->_logfile['state'] = ftp_nb_fget($this->_logfile['ftp'], $this->_logfile['fp'], $this->_logfile['location'], FTP_BINARY, $totalpointer);
                 return $data;
             } elseif ($this->_logfile['state'] == FTP_FAILED) {
                 Leelabot::message('Can\'t read the remote FTP log anymore.', array(), E_WARNING);
                 $this->openLogFile(TRUE);
                 return FALSE;
             } else {
                 $this->_logfile['state'] = ftp_nb_continue($this->_logfile['ftp']);
             }
             break;
         case 'file':
             $data = '';
             $read = NULL;
             while ($read === NULL || $read) {
                 $read = fread($this->_logfile['fp'], 1024);
                 $data .= $read;
             }
             return $data;
             break;
     }
 }
Example #17
0
function start_connect($files)
{
    global $task, $_CONFIG;
    if ($_REQUEST[task] == 'move' || $_REQUEST[task2] == 'move') {
    } else {
        $source_file[0] = "restore/XCloner.php";
        $destination_file[0] = $_REQUEST[ftp_dir] . "/XCloner.php";
        $source_file[1] = "restore/TAR.php";
        $destination_file[1] = $_REQUEST[ftp_dir] . "/TAR.php";
    }
    foreach ($files as $file) {
        $source_file[] = $_CONFIG['clonerPath'] . "/" . $file;
        $destination_file[] = $_REQUEST[ftp_dir] . "/" . $file;
    }
    list($fhost, $fport) = explode(":", $_REQUEST[ftp_server]);
    if ($fport == "") {
        $fport = '21';
    }
    $ftp_timeout = '3600';
    // set up basic connection
    if (!$_CONFIG[secure_ftp]) {
        $conn_id = ftp_connect($fhost, (int) $fport, (int) $ftp_timeout);
        $connect = "Normal";
    } else {
        $conn_id = ftp_ssl_connect($fhost, (int) $fport, (int) $ftp_timeout);
        $connect = "Secure";
    }
    // login with username and password
    $login_result = @ftp_login($conn_id, $_REQUEST[ftp_user], $_REQUEST[ftp_pass]);
    // check connection
    if (!$conn_id || !$login_result) {
        echo "<b  style='color:red'>" . LM_MSG_BACK_2 . "</b>";
        echo "<b  style='color:red'>Attempted to connect to " . $_REQUEST[ftp_server] . " for user " . $_REQUEST[ftp_user] . "</b>";
        return;
    } else {
        #echo "Connected to $_REQUEST[ftp_server], for user $_REQUEST[ftp_user]";
    }
    if ($_CONFIG[system_ftptransfer] == 1) {
        // turn passive mode on
        @ftp_pasv($conn_id, true);
        $mode = "Passive";
    } else {
        // turn passive mode off
        @ftp_pasv($conn_id, false);
        $mode = "Active";
    }
    echo "Connected to {$connect} ftp server <b>{$_REQUEST['ftp_server']} - {$mode} Mode</b><br />";
    for ($i = 0; $i < sizeof($source_file); $i++) {
        echo "<br />Moving source file <b>" . $source_file[$i] . "</b>";
        // upload the file
        if (!$_REQUEST['ftp_inct']) {
            $ret = ftp_put($conn_id, $destination_file[$i], $source_file[$i], FTP_BINARY);
            if ($ret) {
                echo "<br /><b>Upload success to <i>{$destination_file[$i]}</i> ...<br /></b>";
            } else {
                echo "<b style='color:red'>FTP upload has failed for file {$destination_file[$i]} ! Stopping ....<br /></b>";
                return;
            }
        }
        if ($_REQUEST['ftp_inct']) {
            $size = filesize($source_file[$i]);
            $dsize = ftp_size($conn_id, $destination_file[$i]);
            $perc = sprintf("%.2f", $dsize * 100 / $size);
            echo " - uploaded {$perc}% from {$size} bytes <br>";
            $ret = ftp_nb_put($conn_id, $destination_file[$i], $source_file[$i], FTP_BINARY, FTP_AUTORESUME);
            // check upload status
            if ($ret == FTP_FAILED) {
                echo "<b style='color:red'>FTP upload has failed for file {$destination_file[$i]} ! Stopping ....<br /></b>";
                return;
            } else {
                $j = 1;
                while ($ret == FTP_MOREDATA) {
                    // Do whatever you want
                    #echo ". ";
                    // Continue uploading...
                    $ret = ftp_nb_continue($conn_id);
                    if ($j++ % 500 == 0) {
                        @ftp_close($conn_id);
                        echo "<script>\n\t\tvar sURL = unescape('" . $_SERVER[REQUEST_URI] . "');\n\n\t    function refresh()\n\t    {\n\t    //  This version of the refresh function will cause a new\n\t    //  entry in the visitor's history.  It is provided for\n\t    //  those browsers that only support JavaScript 1.0.\n\t    //\n\t    window.location.href = sURL;\n\t    }\n\n\t\tsetTimeout( \"refresh()\", 2*1000 );\n\t\t\n\t\t</script>";
                        return 1;
                        break;
                    }
                }
                if ($ret == FTP_FINISHED) {
                    echo "<b>Upload success to <i>{$destination_file[$i]}</i> ...<br /></b>";
                }
            }
        }
    }
    // close the FTP stream
    @ftp_close($conn_id);
    $redurl = $_REQUEST[ftp_url] . "/XCloner.php";
    if (substr($redurl, 0, 7) != "http://" && substr($redurl, 0, 8) != "https://") {
        $redurl = "http://" . trim($redurl);
    }
    if ($_REQUEST['ftp_inct']) {
        if ($_REQUEST['refresh_done'] != 1) {
            echo "<script>\n\t\tvar sURL = unescape('" . $_SERVER[REQUEST_URI] . "&refresh_done=1');\n\n\t    function refresh()\n\t    {\n\t    //  This version of the refresh function will cause a new\n\t    //  entry in the visitor's history.  It is provided for\n\t    //  those browsers that only support JavaScript 1.0.\n\t    //\n\t    window.location.href = sURL;\n\t    }\n\n\t\tsetTimeout( \"refresh()\", 2*1000 );\n\t\t\n\t\t</script>";
            return 1;
        }
    } else {
        $_REQUEST['refresh_done'] = 1;
    }
    if ($_REQUEST['refresh_done'] == 1) {
        if ($_REQUEST[task] == 'move' || $_REQUEST[task2] == 'move') {
            echo "<br><br><h2>" . LM_MSG_BACK_3 . "</h2>";
            return 1;
        } else {
            echo "<br><br><h2>" . LM_MSG_BACK_4 . " <br /><a href='" . $redurl . "'>click here to continue...</a></h2>";
            return 1;
        }
    }
    return 0;
}
Example #18
0
 /**
  * FTP中文件下载到本地
  *
  * @params array $params 参数 array('local'=>'本地文件路径','remote'=>'远程文件路径','resume'=>'文件指针位置')
  * @params string $msg 
  * @return bool 
  */
 public function pull($params, &$msg)
 {
     if ($this->ftp_extension) {
         $ret = ftp_nb_get($this->conn, $params['local'], $params['remote'], $this->mode, $params['resume']);
         while ($ret == FTP_MOREDATA) {
             $ret = ftp_nb_continue($this->conn);
         }
     } else {
         $ret = $this->ftpclient->download($params['remote'], $params['local'], $this->mode, $params['resume']);
     }
     if ($ret == FTP_FAILED || $ret === false) {
         $msg = app::get('importexport')->_('FTP下载文件失败');
         return false;
     }
     return true;
 }
Example #19
0
File: Ftp.php Project: robeendey/ce
 public function putContents($path, $data)
 {
     $path = $this->path($path);
     // Create stack buffer
     Engine_Stream_Stack::registerWrapper();
     $stack = @fopen('stack://tmp', 'w+');
     if (!$stack) {
         throw new Engine_Vfs_Adapter_Exception(sprintf('Unable to create stack buffer'));
     }
     // Write into stack
     $len = 0;
     do {
         $tmp = @fwrite($stack, substr($data, $len));
         $len += $tmp;
     } while (strlen($data) > $len && $tmp != 0);
     // Get mode
     $mode = $this->getFileMode($path);
     // Non-blocking mode
     if (@function_exists('ftp_nb_fput')) {
         $resource = $this->getResource();
         $res = @ftp_nb_fput($resource, $path, $stack, $mode);
         while ($res == FTP_MOREDATA) {
             //$this->_announce('nb_get');
             $res = @ftp_nb_continue($resource);
         }
         $return = $res === FTP_FINISHED;
     } else {
         $return = @ftp_fput($this->_handle, $path, $stack, $mode);
     }
     // Set umask permission
     try {
         $this->mode($path, $this->getUmask(0666));
     } catch (Exception $e) {
         // Silence
     }
     if (!$return) {
         throw new Engine_Vfs_Adapter_Exception(sprintf('Unable to put contents to "%s"', $path));
     }
     return true;
 }
Example #20
0
 /**
  *
  * 连续获取/发送文件(non-blocking)
  * 以不分块的方式连续获取/发送一个文件。
  *
  * @return int 返回常量 FTP_FAILED 或 FTP_FINISHED 或 FTP_MOREDATA
  */
 public static function nbContinue()
 {
     return ftp_nb_continue(self::$resource);
 }
Example #21
0
 /**
  * @see RemoteDriver::put($mode, $local_file, $remote_file, $asynchronous)
  */
 public function put($local_file, $remote_file = null, $mode = FTP_ASCII, $asynchronous = false)
 {
     $this->connectIfNeeded();
     if (!isset($remote_file) || $remote_file == null || !is_string($remote_file) || trim($remote_file) == "") {
         $remote_file = basename($local_file);
     }
     $this->param = array('remote_file' => $remote_file, 'local_file' => $local_file, 'asynchronous' => $asynchronous);
     if ($asynchronous !== true) {
         if (!ftp_put($this->handle, $remote_file, $local_file, $mode)) {
             throw new FtpException(Yii::t('gftp', 'Could not put file "{local_file}" on "{remote_file}" on server "{host}"', ['host' => $this->host, 'remote_file' => $remote_file, 'local_file' => $local_file]));
         }
     } else {
         $ret = ftp_nb_put($this->handle, $remote_file, $local_file, $mode);
         while ($ret == FTP_MOREDATA) {
             $ret = ftp_nb_continue($this->handle);
         }
         if ($ret !== FTP_FINISHED) {
             throw new FtpException(Yii::t('gftp', 'Could not put file "{local_file}" on "{remote_file}" on server "{host}"', ['host' => $this->host, 'remote_file' => $full_remote_file, 'local_file' => $local_file]));
         }
     }
     return $full_remote_file;
 }
Example #22
0
 function ftp_multi_upload($conn_id, $remoteFileName, $backup_file, $mode, $historyID, $tempArgs, $current_file_num = 0)
 {
     $requestParams = $this->getRequiredData($historyID, "requestParams");
     $task_result = $this->getRequiredData($historyID, "taskResults");
     if (!$remoteFileName) {
         return array('error' => 'Failed to upload file to FTP. Please check your specified path.', 'partial' => 1, 'error_code' => 'failed_to_upload_file_to_ftp');
     }
     $backup_files_base_name = array();
     if (is_array($backup_file)) {
         foreach ($backup_file as $value) {
             $backup_files_base_name[] = basename($value);
         }
     } else {
         $backup_files_base_name = basename($backup_file);
     }
     $backup_files_count = count($backup_file);
     if (is_array($backup_file)) {
         $backup_file = $backup_file[$current_file_num];
     }
     $task_result['task_results'][$historyID]['ftp'] = $backup_files_base_name;
     $task_result['ftp'] = $backup_files_base_name;
     $backup_settings_values = $this->backup_settings_vals;
     /* $upload_loop_break_time = $backup_settings_values['upload_loop_break_time'];
     		$del_host_file = $backup_settings_values['del_host_file']; */
     $upload_loop_break_time = $requestParams['account_info']['upload_loop_break_time'];
     //darkcode changed
     $del_host_file = $requestParams['args']['del_host_file'];
     if (!$upload_loop_break_time) {
         $upload_loop_break_time = 25;
         //safe
     }
     $startTime = microtime(true);
     //get the filesize of the remote file first
     $file_size = ftp_size($conn_id, $remoteFileName);
     if ($file_size != -1) {
         echo "size of {$remoteFileName} is {$file_size} bytes";
     } else {
         $file_size = 0;
     }
     if (!$file_size) {
         $file_size = 0;
     }
     //read the parts local file , if it is a second call start reading the file from the left out part which is at the offset of the remote file's filesize.
     $fp = fopen($backup_file, 'r');
     fseek($fp, $file_size);
     $ret = ftp_nb_fput($conn_id, $remoteFileName, $fp, FTP_BINARY, $file_size);
     if (!$ret || $ret == FTP_FAILED) {
         return array('error' => "FTP upload Error. ftp_nb_fput(): Append/Restart not permitted. This feature is required for multi-call backup upload via FTP to work. Please contact your WP site's hosting provider and ask them to fix the problem. You can try dropbox, Amazon S3 or Google Driver as an alternative to it.", 'partial' => 1, 'error_code' => 'ftp_nb_fput_not_permitted_error');
     }
     $resArray = array('status' => 'partiallyCompleted', 'backupParentHID' => $historyID);
     $result_arr = array();
     $result_arr['status'] = 'partiallyCompleted';
     $result_arr['nextFunc'] = 'ftp_backup';
     $result_arr['ftpArgs'] = $tempArgs;
     $result_arr['current_file_num'] = $current_file_num;
     /*
     1.run the while loop as long as FTP_MOREDATA is set
     2.within the loop if time is greater than specified seconds break the loop and close ftp_con return as "partiallyCompleted" setting nextFunc as ftp_backup.
     3.if ret == FTP_FINISHED , it means the ftpUpload is complete .. return as "completed".
     */
     while ($ret == FTP_MOREDATA) {
         // Do whatever you want
         $endTime = microtime(true);
         $timeTaken = $endTime - $this->iwpScriptStartTime;
         // Continue upload...
         if ($timeTaken > $upload_loop_break_time) {
             echo "being stopped --- " . $file_size;
             $result_arr['timeTaken'] = $timeTaken;
             $result_arr['file_size_written'] = $file_size;
             fclose($fp);
             $this->statusLog($historyID, array('stage' => 'ftpMultiCall', 'status' => 'completed', 'statusMsg' => 'nextCall being stopped --- ', 'nextFunc' => 'ftp_backup', 'task_result' => $task_result, 'responseParams' => $result_arr));
             break;
         } else {
             $ret = ftp_nb_continue($conn_id);
         }
         iwp_mmb_auto_print("ftploop");
     }
     if ($ret != FTP_FINISHED) {
         fclose($fp);
         /* if($del_host_file)
         			{
         				@unlink($backup_file);
         			} */
         return $resArray;
     } else {
         //this is where the backup call ends completing all the uploads
         $current_file_num += 1;
         $result_arr['timeTaken'] = $timeTaken;
         $result_arr['file_size_written'] = $file_size;
         $result_arr['current_file_num'] = $current_file_num;
         if ($current_file_num == $backup_files_count) {
             $result_arr['status'] = 'completed';
             $result_arr['nextFunc'] = 'ftp_backup_over';
             unset($task_result['task_results'][$historyID]['server']);
             $resArray['status'] = 'completed';
         } else {
             $result_arr['status'] = 'partiallyCompleted';
             $resArray['status'] = 'partiallyCompleted';
         }
         $this->statusLog($historyID, array('stage' => 'ftpMultiCall', 'status' => 'completed', 'statusMsg' => 'nextCall', 'nextFunc' => 'ftp_backup', 'task_result' => $task_result, 'responseParams' => $result_arr));
         fclose($fp);
         //checking file size and comparing
         $verificationResult = $this->postUploadVerification($conn_id, $backup_file, $remoteFileName, $type = "ftp");
         if (!$verificationResult) {
             return $this->statusLog($historyID, array('stage' => 'uploadFTP', 'status' => 'error', 'statusMsg' => 'FTP verification failed: File may be corrupted.', 'statusCode' => 'ftp_verification_failed_file_maybe_corrupted'));
         }
         if ($del_host_file) {
             @unlink($backup_file);
             // darkcode testing purpose
         }
         iwp_mmb_print_flush('FTP upload: End');
         return $resArray;
     }
 }
Example #23
0
 public function get($local_file_path, $remote_file_path, $mode = FTP_BINARY, $resume = false, $updraftplus = false)
 {
     $file_last_size = 0;
     if ($resume) {
         if (!($fh = fopen($local_file_path, 'ab'))) {
             return false;
         }
         clearstatcache($local_file_path);
         $file_last_size = filesize($local_file_path);
     } else {
         if (!($fh = fopen($local_file_path, 'wb'))) {
             return false;
         }
     }
     // Implicit FTP, for which we use curl (since PHP's native FTP functions don't handle implicit FTP)
     if ($this->curl_handle) {
         if ($resume) {
             curl_setopt($this->curl_handle, CURLOPT_RESUME_FROM, $resume);
         }
         curl_setopt($this->curl_handle, CURLOPT_NOBODY, false);
         curl_setopt($this->curl_handle, CURLOPT_URL, 'ftps://' . $this->host . '/' . $remote_file_path);
         curl_setopt($this->curl_handle, CURLOPT_UPLOAD, false);
         curl_setopt($this->curl_handle, CURLOPT_FILE, $fh);
         $output = curl_exec($this->curl_handle);
         if ($output) {
             if ($updraftplus) {
                 $updraftplus->log("FTP fetch: fetch complete");
             }
         } else {
             if ($updraftplus) {
                 $updraftplus->log("FTP fetch: fetch failed");
             }
         }
         return $output;
     }
     $ret = ftp_nb_fget($this->conn_id, $fh, $remote_file_path, $mode, $file_last_size);
     if (false == $ret) {
         return false;
     }
     while ($ret == FTP_MOREDATA) {
         if ($updraftplus) {
             $file_now_size = filesize($local_file_path);
             if ($file_now_size - $file_last_size > 524288) {
                 $updraftplus->log("FTP fetch: file size is now: " . sprintf("%0.2f", filesize($local_file_path) / 1048576) . " Mb");
                 $file_last_size = $file_now_size;
             }
             clearstatcache();
         }
         $ret = ftp_nb_continue($this->conn_id);
     }
     fclose($fh);
     if ($ret == FTP_FINISHED) {
         if ($updraftplus) {
             $updraftplus->log("FTP fetch: fetch complete");
         }
         return true;
     } else {
         if ($updraftplus) {
             $updraftplus->log("FTP fetch: fetch failed");
         }
         return false;
     }
 }
Example #24
0
 /**
  * @param $job_object
  * @return bool
  */
 public function job_run_archive(BackWPup_Job $job_object)
 {
     $job_object->substeps_todo = 2 + $job_object->backup_filesize;
     if ($job_object->steps_data[$job_object->step_working]['SAVE_STEP_TRY'] != $job_object->steps_data[$job_object->step_working]['STEP_TRY']) {
         $job_object->log(sprintf(__('%d. Try to send backup file to an FTP server&#160;&hellip;', 'backwpup'), $job_object->steps_data[$job_object->step_working]['STEP_TRY']), E_USER_NOTICE);
     }
     if (!empty($job_object->job['ftpssl'])) {
         //make SSL FTP connection
         if (function_exists('ftp_ssl_connect')) {
             $ftp_conn_id = ftp_ssl_connect($job_object->job['ftphost'], $job_object->job['ftphostport'], $job_object->job['ftptimeout']);
             if ($ftp_conn_id) {
                 $job_object->log(sprintf(__('Connected via explicit SSL-FTP to server: %s', 'backwpup'), $job_object->job['ftphost'] . ':' . $job_object->job['ftphostport']), E_USER_NOTICE);
             } else {
                 $job_object->log(sprintf(__('Cannot connect via explicit SSL-FTP to server: %s', 'backwpup'), $job_object->job['ftphost'] . ':' . $job_object->job['ftphostport']), E_USER_ERROR);
                 return FALSE;
             }
         } else {
             $job_object->log(__('PHP function to connect with explicit SSL-FTP to server does not exist!', 'backwpup'), E_USER_ERROR);
             return TRUE;
         }
     } else {
         //make normal FTP connection if SSL not work
         $ftp_conn_id = ftp_connect($job_object->job['ftphost'], $job_object->job['ftphostport'], $job_object->job['ftptimeout']);
         if ($ftp_conn_id) {
             $job_object->log(sprintf(__('Connected to FTP server: %s', 'backwpup'), $job_object->job['ftphost'] . ':' . $job_object->job['ftphostport']), E_USER_NOTICE);
         } else {
             $job_object->log(sprintf(__('Cannot connect to FTP server: %s', 'backwpup'), $job_object->job['ftphost'] . ':' . $job_object->job['ftphostport']), E_USER_ERROR);
             return FALSE;
         }
     }
     //FTP Login
     $job_object->log(sprintf(__('FTP client command: %s', 'backwpup'), 'USER ' . $job_object->job['ftpuser']), E_USER_NOTICE);
     if ($loginok = @ftp_login($ftp_conn_id, $job_object->job['ftpuser'], BackWPup_Encryption::decrypt($job_object->job['ftppass']))) {
         $job_object->log(sprintf(__('FTP server response: %s', 'backwpup'), 'User ' . $job_object->job['ftpuser'] . ' logged in.'), E_USER_NOTICE);
     } else {
         //if PHP ftp login don't work use raw login
         $return = ftp_raw($ftp_conn_id, 'USER ' . $job_object->job['ftpuser']);
         $job_object->log(sprintf(__('FTP server reply: %s', 'backwpup'), $return[0]), E_USER_NOTICE);
         if (substr(trim($return[0]), 0, 3) <= 400) {
             $job_object->log(sprintf(__('FTP client command: %s', 'backwpup'), 'PASS *******'), E_USER_NOTICE);
             $return = ftp_raw($ftp_conn_id, 'PASS ' . BackWPup_Encryption::decrypt($job_object->job['ftppass']));
             if (substr(trim($return[0]), 0, 3) <= 400) {
                 $job_object->log(sprintf(__('FTP server reply: %s', 'backwpup'), $return[0]), E_USER_NOTICE);
                 $loginok = TRUE;
             } else {
                 $job_object->log(sprintf(__('FTP server reply: %s', 'backwpup'), $return[0]), E_USER_ERROR);
             }
         }
     }
     if (!$loginok) {
         return FALSE;
     }
     //SYSTYPE
     $job_object->log(sprintf(__('FTP client command: %s', 'backwpup'), 'SYST'), E_USER_NOTICE);
     $systype = ftp_systype($ftp_conn_id);
     if ($systype) {
         $job_object->log(sprintf(__('FTP server reply: %s', 'backwpup'), $systype), E_USER_NOTICE);
     } else {
         $job_object->log(sprintf(__('FTP server reply: %s', 'backwpup'), __('Error getting SYSTYPE', 'backwpup')), E_USER_ERROR);
     }
     //set actual ftp dir to ftp dir
     if (empty($job_object->job['ftpdir'])) {
         $job_object->job['ftpdir'] = trailingslashit(ftp_pwd($ftp_conn_id));
     }
     // prepend actual ftp dir if relative dir
     if (substr($job_object->job['ftpdir'], 0, 1) != '/') {
         $job_object->job['ftpdir'] = trailingslashit(ftp_pwd($ftp_conn_id)) . $job_object->job['ftpdir'];
     }
     //test ftp dir and create it if not exists
     if ($job_object->job['ftpdir'] != '/') {
         @ftp_chdir($ftp_conn_id, '/');
         //go to root
         $ftpdirs = explode('/', trim($job_object->job['ftpdir'], '/'));
         foreach ($ftpdirs as $ftpdir) {
             if (empty($ftpdir)) {
                 continue;
             }
             if (!@ftp_chdir($ftp_conn_id, $ftpdir)) {
                 if (@ftp_mkdir($ftp_conn_id, $ftpdir)) {
                     $job_object->log(sprintf(__('FTP Folder "%s" created!', 'backwpup'), $ftpdir), E_USER_NOTICE);
                     ftp_chdir($ftp_conn_id, $ftpdir);
                 } else {
                     $job_object->log(sprintf(__('FTP Folder "%s" cannot be created!', 'backwpup'), $ftpdir), E_USER_ERROR);
                     return FALSE;
                 }
             }
         }
     }
     // Get the current working directory
     $current_ftp_dir = trailingslashit(ftp_pwd($ftp_conn_id));
     if ($job_object->substeps_done == 0) {
         $job_object->log(sprintf(__('FTP current folder is: %s', 'backwpup'), $current_ftp_dir), E_USER_NOTICE);
     }
     //get file size to resume upload
     @clearstatcache();
     $job_object->substeps_done = @ftp_size($ftp_conn_id, $job_object->job['ftpdir'] . $job_object->backup_file);
     if ($job_object->substeps_done == -1) {
         $job_object->substeps_done = 0;
     }
     //PASV
     $job_object->log(sprintf(__('FTP client command: %s', 'backwpup'), 'PASV'), E_USER_NOTICE);
     if ($job_object->job['ftppasv']) {
         if (ftp_pasv($ftp_conn_id, TRUE)) {
             $job_object->log(sprintf(__('FTP server reply: %s', 'backwpup'), __('Entering passive mode', 'backwpup')), E_USER_NOTICE);
         } else {
             $job_object->log(sprintf(__('FTP server reply: %s', 'backwpup'), __('Cannot enter passive mode', 'backwpup')), E_USER_WARNING);
         }
     } else {
         if (ftp_pasv($ftp_conn_id, FALSE)) {
             $job_object->log(sprintf(__('FTP server reply: %s', 'backwpup'), __('Entering normal mode', 'backwpup')), E_USER_NOTICE);
         } else {
             $job_object->log(sprintf(__('FTP server reply: %s', 'backwpup'), __('Cannot enter normal mode', 'backwpup')), E_USER_WARNING);
         }
     }
     if ($job_object->substeps_done < $job_object->backup_filesize) {
         $job_object->log(__('Starting upload to FTP &#160;&hellip;', 'backwpup'), E_USER_NOTICE);
         if ($fp = fopen($job_object->backup_folder . $job_object->backup_file, 'rb')) {
             //go to actual file pos
             fseek($fp, $job_object->substeps_done);
             $ret = ftp_nb_fput($ftp_conn_id, $current_ftp_dir . $job_object->backup_file, $fp, FTP_BINARY, $job_object->substeps_done);
             while ($ret == FTP_MOREDATA) {
                 $job_object->substeps_done = ftell($fp);
                 $job_object->update_working_data();
                 $job_object->do_restart_time();
                 $ret = ftp_nb_continue($ftp_conn_id);
             }
             if ($ret != FTP_FINISHED) {
                 $job_object->log(__('Cannot transfer backup to FTP server!', 'backwpup'), E_USER_ERROR);
                 return FALSE;
             } else {
                 $job_object->substeps_done = $job_object->backup_filesize + 1;
                 $job_object->log(sprintf(__('Backup transferred to FTP server: %s', 'backwpup'), $current_ftp_dir . $job_object->backup_file), E_USER_NOTICE);
                 if (!empty($job_object->job['jobid'])) {
                     BackWPup_Option::update($job_object->job['jobid'], 'lastbackupdownloadurl', "ftp://" . $job_object->job['ftpuser'] . ":" . BackWPup_Encryption::decrypt($job_object->job['ftppass']) . "@" . $job_object->job['ftphost'] . ':' . $job_object->job['ftphostport'] . $current_ftp_dir . $job_object->backup_file);
                 }
             }
             fclose($fp);
         } else {
             $job_object->log(__('Can not open source file for transfer.', 'backwpup'), E_USER_ERROR);
             return FALSE;
         }
     }
     $backupfilelist = array();
     $filecounter = 0;
     $files = array();
     if ($filelist = ftp_nlist($ftp_conn_id, '.')) {
         foreach ($filelist as $file) {
             if (basename($file) != '.' && basename($file) != '..') {
                 if ($job_object->is_backup_archive($file)) {
                     $time = ftp_mdtm($ftp_conn_id, $file);
                     if ($time != -1) {
                         $backupfilelist[$time] = basename($file);
                     } else {
                         $backupfilelist[] = basename($file);
                     }
                 }
                 $files[$filecounter]['folder'] = 'ftp://' . $job_object->job['ftphost'] . ':' . $job_object->job['ftphostport'] . $job_object->job['ftpdir'];
                 $files[$filecounter]['file'] = $job_object->job['ftpdir'] . basename($file);
                 $files[$filecounter]['filename'] = basename($file);
                 $files[$filecounter]['downloadurl'] = 'ftp://' . rawurlencode($job_object->job['ftpuser']) . ':' . rawurlencode(BackWPup_Encryption::decrypt($job_object->job['ftppass'])) . '@' . $job_object->job['ftphost'] . ':' . $job_object->job['ftphostport'] . $job_object->job['ftpdir'] . basename($file);
                 $files[$filecounter]['filesize'] = ftp_size($ftp_conn_id, $file);
                 $files[$filecounter]['time'] = ftp_mdtm($ftp_conn_id, $file);
                 $filecounter++;
             }
         }
     }
     if (!empty($job_object->job['ftpmaxbackups']) && $job_object->job['ftpmaxbackups'] > 0) {
         //Delete old backups
         if (count($backupfilelist) > $job_object->job['ftpmaxbackups']) {
             ksort($backupfilelist);
             $numdeltefiles = 0;
             while ($file = array_shift($backupfilelist)) {
                 if (count($backupfilelist) < $job_object->job['ftpmaxbackups']) {
                     break;
                 }
                 if (ftp_delete($ftp_conn_id, $file)) {
                     //delete files on ftp
                     foreach ($files as $key => $filedata) {
                         if ($filedata['file'] == $job_object->job['ftpdir'] . $file) {
                             unset($files[$key]);
                         }
                     }
                     $numdeltefiles++;
                 } else {
                     $job_object->log(sprintf(__('Cannot delete "%s" on FTP server!', 'backwpup'), $job_object->job['ftpdir'] . $file), E_USER_ERROR);
                 }
             }
             if ($numdeltefiles > 0) {
                 $job_object->log(sprintf(_n('One file deleted on FTP server', '%d files deleted on FTP server', $numdeltefiles, 'backwpup'), $numdeltefiles), E_USER_NOTICE);
             }
         }
     }
     set_site_transient('backwpup_' . $job_object->job['jobid'] . '_ftp', $files, YEAR_IN_SECONDS);
     $job_object->substeps_done++;
     ftp_close($ftp_conn_id);
     return TRUE;
 }
Example #25
0
 /**
  * Continues an unobtrusive file transfer
  *
  * @return integer 0 = Transfer failed (FTP_FAILED) | 1 = Transfer finished (FTP_FINISHED) | 2 = Transfer in progress (FTP_MOREDATA)
  */
 public function continueTransfer()
 {
     if (is_resource($this->cid)) {
         return ftp_nb_continue($this->cid);
     }
 }
Example #26
0
 /**
  * This function will upload a file to the ftp-server. You can either specify a absolute
  * path to the remote-file (beginning with "/") or a relative one, which will be completed
  * with the actual directory you selected on the server. You can specify
  * the path from which the file will be uploaded on the local
  * maschine, if the file should be overwritten if it exists (optionally, default is
  * no overwriting) and in which mode (FTP_ASCII or FTP_BINARY) the file should be
  * downloaded (if you do not specify this, the method tries to determine it automatically
  * from the mode-directory or uses the default-mode, set by you). If you give a relative
  * path to the local-file, the script-path is used as basepath.
  *
  * @access  public
  * @param   string $local_file  The local file to upload
  * @param   string $remote_file The absolute or relative path to the file to upload to
  * @param   bool   $overwrite   (optional) Whether to overwrite existing file
  * @param   int    $mode        (optional) Either FTP_ASCII or FTP_BINARY
  * @return  mixed               True on success, otherwise PEAR::Error
  * @see     NET_FTP_ERR_LOCALFILENOTEXIST, NET_FTP_ERR_OVERWRITEREMOTEFILE_FORBIDDEN, NET_FTP_ERR_UPLOADFILE_FAILED
  */
 function fput($local_handle, $remote_file, $overwrite = false, $mode = null)
 {
     if (!isset($mode)) {
         $mode = FTP_BINARY;
     }
     $remote_file = $this->_construct_path($remote_file);
     if (@ftp_size($this->_handle, $remote_file) != -1 && !$overwrite) {
         return $this->raiseError("Remote file '{$remote_file}' exists and may not be overwriten.", NET_FTP_ERR_OVERWRITEREMOTEFILE_FORBIDDEN);
     }
     if (function_exists('ftp_nb_fput')) {
         $res = @ftp_nb_fput($this->_handle, $remote_file, $local_handle, $mode);
         while ($res == FTP_MOREDATA) {
             $this->_announce('nb_put');
             $res = @ftp_nb_continue($this->_handle);
         }
     } else {
         $res = @ftp_fput($this->_handle, $remote_file, $local_handle, $mode);
     }
     if (!$res) {
         return $this->raiseError("The File could not be uploaded to '{$remote_file}'.", NET_FTP_ERR_UPLOADFILE_FAILED);
     } else {
         return true;
     }
 }
Example #27
0
 /**
  * Download remote file to local file.
  *
  * @throws
  * @param string $remote_file
  * @param string $local_file
  */
 public function get($remote_file, $local_file)
 {
     $lfile = File::exists($local_file);
     if ($lfile && $this->hasCache($remote_file, File::md5($local_file))) {
         $this->_log($remote_file . ' exists');
         return;
     }
     $this->_log("download {$remote_file} as {$local_file}");
     $ret = @ftp_nb_get($this->ftp, $local_file, $remote_file, FTP_BINARY);
     while ($ret === FTP_MOREDATA) {
         $ret = @ftp_nb_continue($this->ftp);
     }
     if ($ret !== FTP_FINISHED) {
         throw new Exception('FTP download failed', "local_file={$local_file} remote_file={$remote_file}");
     }
     $this->cache[$remote_file] = [File::md5($local_file), File::size($local_file), File::lastModified($local_file)];
 }
Example #28
0
 /**
  * This function will upload a file to the ftp-server. You can either specify a
  * absolute path to the remote-file (beginning with "/") or a relative one,
  * which will be completed with the actual directory you selected on the server.
  * You can specify the path from which the file will be uploaded on the local
  * maschine, if the file should be overwritten if it exists (optionally, default
  * is no overwriting) and in which mode (FTP_ASCII or FTP_BINARY) the file
  * should be downloaded (if you do not specify this, the method tries to
  * determine it automatically from the mode-directory or uses the default-mode,
  * set by you).
  * If you give a relative path to the local-file, the script-path is used as
  * basepath.
  *
  * @param string $local_file  The local file to upload
  * @param string $remote_file The absolute or relative path to the file to
  *                            upload to
  * @param bool   $overwrite   (optional) Whether to overwrite existing file
  * @param int    $mode        (optional) Either FTP_ASCII or FTP_BINARY
  *
  * @access public
  * @return mixed True on success, otherwise PEAR::Error
  * @see NET_FTP_ERR_LOCALFILENOTEXIST,
  *      NET_FTP_ERR_OVERWRITEREMOTEFILE_FORBIDDEN,
  *      NET_FTP_ERR_UPLOADFILE_FAILED
  */
 function put($local_file, $remote_file, $overwrite = false, $mode = null)
 {
     if (!isset($mode)) {
         $mode = $this->checkFileExtension($local_file);
     }
     $remote_file = $this->_constructPath($remote_file);
     if (!@file_exists($local_file)) {
         return $this->raiseError("Local file '{$local_file}' does not exist.", NET_FTP_ERR_LOCALFILENOTEXIST);
     }
     if (@ftp_size($this->_handle, $remote_file) != -1 && !$overwrite) {
         return $this->raiseError("Remote file '" . $remote_file . "' exists and may not be overwriten.", NET_FTP_ERR_OVERWRITEREMOTEFILE_FORBIDDEN);
     }
     if (function_exists('ftp_alloc')) {
         ftp_alloc($this->_handle, filesize($local_file));
     }
     if (function_exists('ftp_nb_put')) {
         $res = @ftp_nb_put($this->_handle, $remote_file, $local_file, $mode);
         while ($res == FTP_MOREDATA) {
             $this->_announce('nb_put');
             $res = @ftp_nb_continue($this->_handle);
         }
     } else {
         $res = @ftp_put($this->_handle, $remote_file, $local_file, $mode);
     }
     if (!$res) {
         return $this->raiseError("File '{$local_file}' could not be uploaded to '" . $remote_file . "'.", NET_FTP_ERR_UPLOADFILE_FAILED);
     } else {
         return true;
     }
 }
Example #29
-5
 /**
  * 下载文件
  * 
  */
 public function download($localfile, $remotefile)
 {
     ftp_set_option($this->ftpobj, FTP_AUTOSEEK, FALSE);
     $res = ftp_nb_get($this->ftpobj, $localfile, $remotefile, $this->mode, ftp_size($this->ftpobj, $localfile));
     while ($res == FTP_MOREDATA) {
         $res = ftp_nb_continue($this->ftpobj);
     }
     if ($res != FTP_FINISHED) {
         return FALSE;
     }
     return TRUE;
 }
Example #30
-7
 /**
  * FTP-文件下载
  * @param string $localFile 本地文件
  * @param string $ftpFile Ftp文件
  * @return bool
  */
 public function download($localFile, $ftpFile)
 {
     if (!$localFile || !$ftpFile) {
         return false;
     }
     $ret = ftp_nb_get($this->link, $localFile, $ftpFile, FTP_BINARY);
     while ($ret == FTP_MOREDATA) {
         $ret = ftp_nb_continue($this->link);
     }
     if ($ret != FTP_FINISHED) {
         return false;
     }
     return true;
 }