Uso: $ftp = new Ftp('servidorFtp','usuario','password'); Subir archivo: $ok = $ftp->upload('carpetaDestino','archivoOrigen','archivoDestino'); Descargar archivo: $ok = $ftp->downLoad('archivoDelServidor','archivoLocal'); Cerrar sesion: $ftp->close(); Obtener eventuales errores: $array = $ftp->getErrores();
Author: Sergio Pérez (sergio.perez@albatronic.com)
Example #1
0
 public function testFailure()
 {
     $ftp = new Ftp("chc-deaf.org.ua");
     $ftp->login("chc-deaf", "moskvich408");
     $this->assertFalse($ftp->push_file("/file/maxim3.jpg", "../maxim3.jpg", "jpg2"));
     $this->assertFalse($ftp->push_file("/file/maxim3.jpg", "../maxim3.jpg", "doc"));
 }
Example #2
0
 /**
  * Returns a new Ftp object. If you do not define the "file" parameter,
  *
  *     $ftp = static::factory('group');
  *
  * @param   string  Ftp filename
  * @param   array   array of values
  * @return  Ftp
  */
 public static function factory($config = 'default', $connect = true)
 {
     $ftp = new Ftp($config);
     // Unless told not to, connect automatically
     $connect === true and $ftp->connect();
     return $ftp;
 }
Example #3
0
 public function upload()
 {
     if (!$this->input['video_id']) {
         $this->errorOutput(NOID);
     }
     $sql = " SELECT video_base_path,video_path,video_filename,id FROM " . DB_PREFIX . "vodinfo WHERE id IN (" . $this->input['video_id'] . ")";
     $q = $this->db->query($sql);
     $video = array();
     while ($r = $this->db->fetch_array($q)) {
         $video[] = $r;
     }
     //实例化ftp,并连接
     $ftp_config = array('hostname' => $this->input['hostname'], 'username' => $this->input['username'], 'password' => $this->input['password']);
     $ftp = new Ftp();
     if (!$ftp->connect($ftp_config)) {
         $this->errorOutput('CAN NOT CONNECT FTP SERVER');
     }
     foreach ($video as $k => $v) {
         $target_dir = date('Y', TIMENOW) . '/' . date('m', TIMENOW) . '/' . TIMENOW . hg_rand_num(6) . '/';
         $target_path = $target_dir . $v['video_filename'];
         $video_filepath = $v['video_base_path'] . $v['video_path'] . $v['video_filename'];
         if (!$ftp->mkdir($target_dir)) {
             $this->errorOutput('CAN NOT MAKE DIR');
         }
         if (!$ftp->upload($video_filepath, $target_path)) {
             $this->errorOutput('CAN NOT UPLOAD FILE');
         }
         $pathinfo = pathinfo($target_path);
         $filename = basename($pathinfo['basename'], '.' . $pathinfo['extension']);
         $this->addItem(array('path' => $target_path, 'id' => $v['id'], 'dir' => $pathinfo['dirname'], 'filename' => $filename));
     }
     $this->output();
 }
Example #4
0
 /**
  * Updates a particular model.
  * If update is successful, the browser will be redirected to the 'view' page.
  * @param integer $id the ID of the model to be updated
  */
 public function actionUpdate($id)
 {
     $model = $this->loadModel($id);
     $menu = $model->attributes;
     if (isset($_POST['FrontMenu'])) {
         $model->attributes = $_POST['FrontMenu'];
         foreach ($this->uploadArr as $column) {
             $file = CUploadedFile::getInstance($model, $column);
             //获取表单名为filename的上传信息
             if ($file) {
                 $model->{$column} = $this->uploadIcon($file);
                 if ($menu[$column]) {
                     $ftp = new Ftp();
                     $res = $ftp->delete_file('common/frontmenu/' . $menu[$column]);
                     $ftp->close();
                 }
             } else {
                 unset($model->{$column});
             }
         }
         if (!$model->ParentID) {
             $model->ParentID = 0;
         }
         if ($model->save()) {
             $this->freshMenuCache();
             $this->redirect(array('admin'));
         }
     }
     $this->render('update', array('model' => $model));
 }
Example #5
0
 /**
  * Ist für den Abgleich der Bestellungen im Cronjob.
  */
 public function update()
 {
     global $selectline, $oxid, $ftp;
     $this->set_log('Cronjob: ' . date('d.m.Y H:i:s') . "\r\n");
     try {
         $ftp = new Ftp();
         $ftp->connect($oxid['ftp_host']);
         $ftp->login($oxid['ftp_user'], $oxid['ftp_password']);
         $ftp->close();
     } catch (Exception $e) {
         $this->set_log('SelectConnect konnte keine Verbindung zum FTP-Server herstellen!');
         exit;
     }
     if (!oxid_userlogin()) {
         $this->set_log('SelectConnect konnte sich nicht bei Oxid einloggen!');
         exit;
     }
     if (!$this->is_current_update_process()) {
         $this->set_log("Cronjob wurde gestartet \r\n");
         $this->set_lock_file();
         $last_update = $this->get_last_update();
         $this->set_log("Bestellungen werden in Selectline importiert \r\n");
         $orders = $oxid['db']->get_results("SELECT * FROM " . $oxid['table_order'] . " WHERE OXFOLDER  = '" . $oxid['get_order_status'] . "' ORDER BY OXORDERNR");
         if ($orders) {
             foreach ($orders as $order) {
                 $order_products = $oxid['db']->get_results("SELECT * FROM " . $oxid['table_orderarticles'] . " WHERE OXORDERID = '" . $order->OXID . "' ");
                 $order->products = $order_products;
                 $order_payment = $oxid['db']->get_row("SELECT * FROM " . $oxid['table_payments'] . " WHERE ('" . $order->OXPAYMENTTYPE . "' = OXID)");
                 $order->payment = $order_payment;
                 $this->set_order_to_selectline($order, true);
                 $oxid['db']->query("UPDATE " . $oxid['table_order'] . " SET OXFOLDER = '" . $oxid['set_order_status'] . "', OXEXPORT = 1 WHERE `OXID` = '" . $order->OXID . "' ");
             }
         }
         $this->set_log("Bestellungstatus wird abgeglichen \r\n");
         $orders = $selectline['db']->get_results("SELECT * FROM " . $selectline['table_orders'] . " WHERE [Belegtyp] = '" . $selectline['filter_order_invoice'] . "' AND [BearbeitetAm] >= CONVERT(datetime, '" . $last_update->format('d.m.Y H:i:s') . "',104)");
         if ($orders) {
             foreach ($orders as $order) {
                 $tracking_id = $this->get_tracking_id_from_selectline($order);
                 $updateArray = array('OXBILLNR' => $order->Belegnummer, 'OXBILLDATE' => $order->Datum->format('Y-m-d'), 'OXSENDDATE' => $order->Datum->format('Y-m-d H:i:s'), 'OXFOLDER' => $oxid['order_status_finish']);
                 if ($tracking_id !== NULL) {
                     $updateArray['OXTRACKCODE'] = $tracking_id;
                 }
                 //print_r($this->format_update_query($oxid['table_order'], $updateArray, array('OXORDERNR' => str_replace('OX', '', $order->IhrAuftrag))));
                 $oxid['db']->query($this->format_update_query($oxid['table_order'], $updateArray, array('OXORDERNR' => str_replace('OX', '', $order->IhrAuftrag))));
                 $this->set_log("Bestellung " . $order->IhrAuftrag . "/" . $order->Belegnummer . " - Status: FINISHED - Tracking: " . $tracking_id . " \r\n");
             }
         }
         $this->set_last_update();
         $this->remove_lock_file();
         $this->set_log("Cron wurde beendet \r\n");
         $this->set_log("\r\n##################################\r\n\r\n");
     } else {
         print_r('Error: Es läuft bereits Update-Prozess.');
     }
 }
Example #6
0
 /**
  * Download test.
  * @return void
  */
 public function testDownload()
 {
     $ftp = new Ftp();
     // Opens an FTP connection to the specified host
     $ftp->connect('ftp.nettephp.com');
     $ftp->pasv(TRUE);
     // Login with username and password
     $ftp->login('*****@*****.**', 'anonymous');
     // Download file 'README' to local temporary file
     $temp = tmpfile();
     $ftp->fget($temp, 'README', Ftp::ASCII);
     // echo file
     fseek($temp, 0);
     $this->assertEquals("Nette Framework rocks!", stream_get_contents($temp));
 }
function get_ftp_content($source, $target)
{
    $result = false;
    $config = array('hostname' => FTP_HOST, 'username' => FTP_USER, 'password' => FTP_PASSWORD, 'port' => FTP_PORT, 'timeout' => FTP_TIMEOUT);
    $ftp = new Ftp();
    $ftp->connect($config);
    if ($ftp->existsFile($source)) {
        $result = $ftp->download($source, $target);
    } else {
        access_log('log', 'No documents.');
        //clear_file();
    }
    $ftp->close();
    return $result;
}
Example #8
0
 /**
  * @param string $ftp_dsn ftp://user:pass@localhost/
  */
 public function __construct($ftp_dsn)
 {
     $ftp = Ftp::parse_dsn($ftp_dsn);
     foreach ($ftp as $k => $v) {
         $this->{$k} = $v;
     }
 }
Example #9
0
 public function __construct($connection = '')
 {
     if ($connection) {
         $this->ftpCon = Ftp::connection($connection);
     } else {
         $this->ftpCon = Ftp::connection();
     }
 }
 /**
  * @param DatabaseBackupFile $file
  * @return ResultObject[]
  */
 public function process(DatabaseBackupFile $file)
 {
     $d = $file->getBackupDate();
     $results = [];
     foreach ($this->uploadsCredentials as $credentials) {
         $result = new ResultObject();
         // empty ResultObject means all is OK
         $backupPath = $credentials['path'] . '/' . $d->format('Y') . '/' . $d->format('F');
         $entireFilePath = $backupPath . '/' . $file->getFileName();
         try {
             $ftp = new \Ftp();
             $ftp->connect($credentials['host']);
             $ftp->login($credentials['username'], $credentials['password']);
             if (!$ftp->fileExists($backupPath)) {
                 $ftp->mkDirRecursive($backupPath);
             }
             $ftp->put($entireFilePath, $file->getFilePath(), FTP_BINARY);
             $ftp->close();
         } catch (\FtpException $e) {
             $this->logger->addCritical(sprintf('Uploading backup file\'s failed. %s', $e));
             $result->addError('Zálohu se nepodařilo nahrát na: ' . $credentials['host'], 'error');
         }
         $results[] = $result;
     }
     return $results;
 }
Example #11
0
 private static function loadLibs()
 {
     if (is_file('config/libs' . PHP)) {
         self::$libs = unserialize(include $root . '/config/libs' . PHP);
     } else {
         self::$libsInfo = self::getlibsInfo();
         self::$libs = Ftp::getFilesFromYaml(self::$libsInfo);
     }
 }
Example #12
0
 private function moveTableClasses()
 {
     if ($this->getOptionsValue('generate-table') === true) {
         if (!Misc::isEmpty($to = $this->getOptionsValue('table-dir'))) {
             $from = $this->getOptionsValue('models-path');
             $to = $from . '/' . $to;
             $opt = array('suffix' => 'Table' . self::getOptionsValue('suffix'));
             Ftp::moveFiles($from, $to, false, false, $opt);
         }
     }
 }
Example #13
0
/**
 * 
 * @param type $from
 * @return type 
 */
function getFtpFiles($from)
{
    $info = pathinfo($from);
    $name = trim($info['basename']);
    $ftpCon = new Ftp(FTP_HOST, FTP_USER, FTP_PASS, FTP_PORT);
    $content_download = FALSE;
    $connected = $ftpCon->login_r(null, null, FTP_CONN_RETRIES);
    if ($connected === TRUE) {
        $to = TMP_QR_DIR . "/" . $name;
        $downloaded = $ftpCon->bajar_r($from, $to, FTP_CONN_RETRIES);
        if ($downloaded === TRUE) {
            $content_download = TRUE;
        } else {
            $content_download = FALSE;
        }
    } else {
        $content_download = FALSE;
    }
    $ftpCon->logout();
    return $content_download;
}
Example #14
0
 private function globalChecks($file, $content, $name)
 {
     if (is_file('apps/controllers/' . $file)) {
         exit("This application already exists.\n");
     }
     if (!file_put_contents("apps/controllers/{$file}", $content)) {
         exit("The file apps/controllers/{$file} can't be created.\n");
     }
     if (!Ftp::makeDir('apps/views/' . $name)) {
         exit("The file apps/views/{$name} can't be created.");
     }
 }
Example #15
0
 public function action_ajax_test_ftp()
 {
     // is ajax
     if (!\Input::is_ajax()) {
         \Response::redirect(\Uri::create('admin'));
     }
     // check permission
     if (\Model_AccountLevelPermission::checkAdminPermission('config_global', 'config_global') == false) {
         \Session::set_flash('form_status', array('form_status' => 'error', 'form_status_message' => \Lang::get('admin_permission_denied', array('page' => \Uri::string()))));
         return null;
     }
     if (\Input::method() == 'POST') {
         // get post value and test connection
         $config['hostname'] = trim(\Input::post('hostname'));
         $config['username'] = trim(\Input::post('username'));
         $config['password'] = trim(\Input::post('password'));
         $config['port'] = (int) trim(\Input::post('port'));
         $config['passive'] = trim(\Input::post('passive')) == 'true' ? true : false;
         $config['ssl_mode'] = false;
         $config['debug'] = false;
         $basepath = trim(\Input::post('basepath'));
         // connect to ftp
         $ftp = \Ftp::forge($config);
         $ftp->connect();
         $ftp->change_dir($basepath);
         $files = $ftp->list_files();
         $ftp->close();
         $output = array();
         if ($files !== false) {
             $output['form_status'] = 'success';
             $output['form_status_message'] = \Lang::get('config_ftp_connected_check_basepath_from_dir_structure_below');
             natsort($files);
             $output['list_files'] = '<ul>';
             foreach ($files as $file) {
                 $output['list_files'] .= '<li>' . $file . '</li>';
             }
             $output['list_files'] .= '</ul>';
         } else {
             // got false from list_files means cannot connect
             $output['form_status'] = 'error';
             $output['form_status_message'] = \Lang::get('config_ftp_could_not_connect_to_server');
         }
         // clear no use variables
         unset($basepath, $config, $file, $files, $ftp);
         // send out json values
         $response = new \Response();
         $response->set_header('Content-Type', 'application/json');
         $response->body(json_encode($output));
         return $response;
     }
 }
Example #16
0
 public function getTasks()
 {
     $tasks = array();
     $list = Ftp::getFilesFromYaml($this->tasksDirs);
     foreach ($list as $name => $path) {
         $Tmp = new $name();
         if (!$Tmp->hasName()) {
             $Tmp->setName($name);
         }
         if (!$Tmp->hasDescription()) {
             $Tmp->setDescription(_('No descriptions.'));
         }
         $new_name = $Tmp->hasNamespace() ? $Tmp->getNamespace() . ':' : null;
         $new_name .= $Tmp->getName();
         $tasks[$new_name] = $Tmp;
     }
     return $tasks;
 }
Example #17
0
 /**
  * Recursive deletes path.
  * @param  string
  * @return void
  */
 private function purge($path, $onlyContent = FALSE)
 {
     static $counter;
     echo str_pad(str_repeat('.', $counter++ % 40), 40), "\r";
     if (!$onlyContent && $this->ftp->tryDelete($path)) {
         return;
     }
     foreach ((array) $this->ftp->nlist($path) as $file) {
         if ($file != NULL && !preg_match('#(^|/)\\.+$#', $file)) {
             // intentionally ==
             $file = strpos($file, '/') === FALSE ? "{$path}/{$file}" : $file;
             if ($file !== $path) {
                 $this->purge($file);
             }
         }
     }
     if (!$onlyContent) {
         $this->ftp->tryRmdir($path);
     }
 }
Example #18
0
 private function checkUploadError($file)
 {
     if (!isset($file['error'])) {
         $this->addError(_('Unknown error.'));
     } else {
         if ($file['error'] === UPLOAD_ERR_NO_FILE) {
             $this->addError(_('No Files has been uploaded.'));
         } else {
             if ($file['error'] === UPLOAD_ERR_PARTIAL) {
                 $this->addError(_('The file has been partially uploaded.'));
             } else {
                 if ($file['error'] === UPLOAD_ERR_INI_SIZE) {
                     $error = _("You can’t upload a file bigger than %d octets.");
                     $max = Ftp::octetConverter(ini_get('upload_max_filesize'));
                     $this->addError(sprintf($error, $max));
                 } else {
                     if ($file['error'] === UPLOAD_ERR_FORM_SIZE) {
                         $this->addError(_("The file’s size is bigger than the maximum size " . "specified in the form."));
                     } else {
                         if ($file['error'] === UPLOAD_ERR_NO_TMP_DIR) {
                             $this->addError(_('The temporary directory is missing.'));
                         } else {
                             if ($file['error'] === UPLOAD_ERR_CANT_WRITE) {
                                 $this->addError(_("The file can’t be wrote on the disk."));
                             } else {
                                 if ($file['error'] === UPLOAD_ERR_EXTEMSION) {
                                     $this->addError(_('The file’s extention is not allowed.'));
                                 } else {
                                     $this->addError(_('Unknown error.'));
                                 }
                             }
                         }
                     }
                 }
             }
         }
     }
 }
Example #19
0
function file_remote_delete($file)
{
    global $_W;
    if (empty($file)) {
        return true;
    }
    if ($_W['setting']['remote']['type'] == '1') {
        require IA_ROOT . '/framework/library/ftp/ftp.php';
        $ftp_config = array('hostname' => $_W['setting']['remote']['ftp']['host'], 'username' => $_W['setting']['remote']['ftp']['username'], 'password' => $_W['setting']['remote']['ftp']['password'], 'port' => $_W['setting']['remote']['ftp']['port'], 'ssl' => $_W['setting']['remote']['ftp']['ssl'], 'passive' => $_W['setting']['remote']['ftp']['pasv'], 'timeout' => $_W['setting']['remote']['ftp']['timeout'], 'rootdir' => $_W['setting']['remote']['ftp']['dir']);
        $ftp = new Ftp($ftp_config);
        if (true === $ftp->connect()) {
            if ($ftp->delete_file($file)) {
                return true;
            } else {
                return error(1, '删除附件失败,请检查配置并重新删除');
            }
        } else {
            return error(1, '删除附件失败,请检查配置并重新删除');
        }
    } elseif ($_W['setting']['remote']['type'] == '2') {
        require IA_ROOT . '/framework/library/alioss/sdk.class.php';
        $oss = new ALIOSS($_W['setting']['remote']['alioss']['key'], $_W['setting']['remote']['alioss']['secret'], $_W['setting']['remote']['alioss']['ossurl']);
        $response = $oss->delete_object($_W['setting']['remote']['alioss']['bucket'], $file);
        if ($response->status == 204) {
            return true;
        } else {
            return error(1, '删除oss远程文件失败');
        }
    }
    return true;
}
Example #20
0
 public static function editscheme($params)
 {
     $organID = Yii::app()->user->getOrganID();
     $time = $_SERVER['REQUEST_TIME'];
     //更新报价单
     $quoID = self::ifsendquo(array('inqid' => $params['inqid']));
     $quodatas['UpdateTime'] = $time;
     $quodatas['Title'] = $params['quoname'];
     $result = Yii::app()->papdb->createCommand()->update('pap_quotation', $quodatas, 'QuoID=' . $quoID);
     $SchID = $params['schid'];
     $datas['TotalFee'] = $params['quoprices'];
     $datas['GoodFee'] = $params['totalprices'];
     $datas['ShipFee'] = $params['shipprices'];
     $datas['ShipFee'] = $params['shipprices'];
     $datas['UpdateTime'] = $time;
     //保存附件
     if ($params['fileurl']) {
         $datas['FileName'] = $params['filename'];
         $datas['FileUrl'] = $params['fileurl'];
         //删除之前附件
         $quo_data = PapQuotationScheme::model()->findByPk($SchID);
         if (!empty($quo_data['FileName'])) {
             $ftp = new Ftp();
             $res = $ftp->delete_file($quo_data->FileUrl);
             $ftp->close();
         }
     }
     $result = Yii::app()->papdb->createCommand()->update('pap_quotation_scheme', $datas, 'SchID=:SchID', array(':SchID' => $SchID));
     //获取商品信息
     $goodsinfo = array();
     $goodsids = explode(',', $params['quoids']);
     $goodsnum = explode(',', $params['quonum']);
     $goodsprice = explode(',', $params['quoprice']);
     //获取以前的商品信息
     $oldgoodsinfo = PapQuotationGoods::model()->findAll('SchID=' . $SchID);
     $newgoodsinfo = array();
     foreach ($goodsids as $key => $v) {
         if ($v) {
             $newgoodsinfo[$key]['GoodsID'] = $goodsids[$key];
             $newgoodsinfo[$key]['Num'] = $goodsnum[$key];
             $newgoodsinfo[$key]['Price'] = $goodsprice[$key];
             $version = QuotationService::getgoodsversion($goodsids[$key]);
             $newgoodsinfo[$key]['Version'] = $version ? $version : 0;
         }
     }
     $insertid = array();
     //将报价单商品插入报价单商品表中
     if ($SchID) {
         foreach ($newgoodsinfo as $nkey => $new) {
             $newids[] = $new['GoodsID'];
         }
         if ($oldgoodsinfo) {
             foreach ($oldgoodsinfo as $okey => $old) {
                 $oldids[] = $old['GoodsID'];
             }
         } else {
             $oldids = array();
         }
         foreach ($oldids as $id) {
             if (!in_array($id, $newids)) {
                 //删除商品
                 $delcount = Yii::app()->papdb->createCommand()->delete('pap_quotation_goods', 'SchID=:SchID and GoodsID=:goodsid', array(':SchID' => $SchID, ':goodsid' => $id));
             }
         }
         foreach ($newids as $key => $id) {
             if (in_array($id, $oldids)) {
                 //更新商品
                 $update['Num'] = $newgoodsinfo[$key]['Num'];
                 $update['Price'] = $newgoodsinfo[$key]['Price'];
                 $update['Version'] = $newgoodsinfo[$key]['Version'];
                 $result = Yii::app()->papdb->createCommand()->update('pap_quotation_goods', $update, 'SchID=:SchID and GoodsID=:goodsid', array(':SchID' => $SchID, ':goodsid' => $id));
                 if ($result == 1) {
                     $res = 1;
                 }
             } else {
                 //插入商品
                 $goodsdatas['SchID'] = $SchID;
                 $goodsdatas['GoodsID'] = $newgoodsinfo[$key]['GoodsID'];
                 $goodsdatas['Num'] = $newgoodsinfo[$key]['Num'];
                 $goodsdatas['Price'] = $newgoodsinfo[$key]['Price'];
                 $goodsdatas['Version'] = $newgoodsinfo[$key]['Version'];
                 $result = Yii::app()->papdb->createCommand()->insert('pap_quotation_goods', $goodsdatas);
                 $insertid[] = Yii::app()->papdb->getLastInsertID();
             }
         }
     }
     if ($res = 1 || count($insertid) > 0 || $delcount > 0) {
         echo json_encode(array('count' => 1, 'schid' => $SchID, 'success' => true));
     } else {
         echo json_encode(array('count' => 0));
     }
 }
Example #21
0
 $from = $video->getContent();
 $bajado = $ftpCon->bajar($from, $to);
 if ($bajado !== TRUE) {
     $bajado = $ftpCon->bajar($from, $to);
 }
 if ($bajado !== TRUE) {
     $bajado = $ftpCon->bajar($from, $to);
 }
 if ($bajado !== TRUE) {
     $bajado = $ftpCon->bajar($from, $to);
 }
 if ($bajado === TRUE) {
     $to = $tmpDir . "/preview_tmp.gif";
     $from = $video->getPreview();
     $log .= "\tdescargando preview {$from} > {$to}\n";
     $ftpConUSA = new Ftp(FTP_USA, FTP_USA_USR, FTP_USA_PWD);
     $connectUSA = $ftpConUSA->login();
     if ($conectado !== TRUE) {
         $connectUSA = $ftpConUSA->login();
     }
     if ($conectado !== TRUE) {
         $connectUSA = $ftpConUSA->login();
     }
     if ($conectado !== TRUE) {
         $connectUSA = $ftpConUSA->login();
     }
     $bajado = $ftpConUSA->bajar($from, $to);
     if ($bajado !== TRUE) {
         $bajado = $ftpConUSA->bajar($from, $to);
     }
     if ($bajado !== TRUE) {
Example #22
0
/**
 * Copies files using FTP access
 *
 * @param string $source Absolute path (non-ftp) to source dir/file
 * @param string $destination Absolute path (non-ftp) to destination dir/file
 * @param array $ftp_access
 *      array(
 *          'hostname',
 *          'username',
 *          'password',
 *          'directory'
 *      )
 * @return bool true if all files were copied or (string) Error message
 */
function fn_copy_by_ftp($source, $destination, $ftp_access)
{
    try {
        $ftp = new Ftp();
        $ftp->connect($ftp_access['hostname']);
        $ftp->login($ftp_access['username'], $ftp_access['password']);
        $ftp->chdir($ftp_access['directory']);
        $files = $ftp->nlist('');
        if (!empty($files) && in_array('config.php', $files)) {
            $ftp_destination = str_replace(Registry::get('config.dir.root'), '', $destination);
            if (is_file($source)) {
                // File
                try {
                    $file = ltrim($ftp_destination, '/');
                    $ftp->put($file, $source, FTP_BINARY);
                } catch (FtpException $e) {
                    throw new FtpException('ftp_access_denied' . ':' . $e->getMessage());
                }
            } else {
                // Dir
                $ftp->chdir($ftp_access['directory'] . $ftp_destination);
                $struct = fn_get_dir_contents($source, false, true, '', '', true);
                foreach ($struct as $file) {
                    $dir = dirname($file);
                    if (!$ftp->isDir($dir)) {
                        try {
                            $ftp->mkDirRecursive($dir);
                        } catch (FtpException $e) {
                            throw new FtpException('ftp_access_denied' . ':' . $e->getMessage());
                        }
                    }
                    try {
                        $ftp->put($file, $source . $file, FTP_BINARY);
                    } catch (FtpException $e) {
                        throw new FtpException('ftp_access_denied' . ':' . $e->getMessage());
                    }
                }
            }
            return true;
        } else {
            throw new FtpException('ftp_directory_is_incorrect');
        }
    } catch (FtpException $e) {
        return __('invalid_ftp_access') . ': ' . $e->getMessage();
    }
    return false;
}
Example #23
0
 public function testSSlConnection()
 {
     $ftp = new Ftp("ftphost", "username", "password");
     $ftp->setFtpWrapper($this->getMockFunctions());
     $ftp->connectSSL();
     $file = $ftp->putFileFromPath(__DIR__ . '/../fixtures/foo');
     $this->assertInstanceOf('FtpLib\\File', $file);
     $file->delete();
 }
Example #24
0
 /**
  * 公司信息保存
  */
 public function actionSavedealerorgan()
 {
     $OrganID = Yii::app()->user->getOrganID();
     $Organ = Yii::app()->request->getParam("Organ");
     $arr = Yii::app()->request->getParam("telPhone");
     $TelPhone = "";
     foreach ($arr as $key => $val) {
         if (empty($val)) {
             continue;
         }
         $TelPhone .= $val . ",";
     }
     $model = Organ::model()->findByPK($OrganID);
     if (empty($model)) {
         $model = new Organ();
     }
     //保存organ数据
     $model->attributes = $Organ;
     $model->TelPhone = trim($TelPhone, ',');
     //判断基本信息是否为空,为空则不提交
     if ($Organ) {
         //接收删除图片的地址
         $photoId = Yii::app()->request->getParam("photoId");
         //判断是否删除图片
         if (!empty($photoId)) {
             $imageids = explode(',', $photoId);
             foreach ($imageids as $imageid) {
                 $picture = OrganPhoto::model()->find('Path=:img AND OrganID=:OrganID', array(':img' => $imageid, ':OrganID' => $OrganID));
                 //判断该图片路径是否存在数据库中
                 if (empty($picture)) {
                     $ftp = new Ftp();
                     $res = $ftp->delete_file($imageid);
                     $ftp->close();
                 } else {
                     OrganPhoto::model()->deleteAll('Path=:img AND OrganID=:OrganID', array(':img' => $imageid, ':OrganID' => $OrganID));
                     $ftp = new Ftp();
                     $res = $ftp->delete_file($picture->Path);
                     $ftp->close();
                 }
             }
         }
         //接收上传图片地址
         $goodsImages = Yii::app()->request->getParam("goodsImages");
         //判断是否有上传图片
         if (!empty($goodsImages)) {
             $imglegth = count($goodsImages);
             for ($i = 0; $i < $imglegth; $i++) {
                 $goodsImg = new OrganPhoto();
                 $goodsImg->OrganID = $OrganID;
                 $goodsImg->Path = $goodsImages[$i];
                 $goodsImg->save();
             }
         }
         //判断是否上传营业执照
         $BLPoto = Yii::app()->request->getParam("BLPoto");
         if ($model->BLPoto != $BLPoto) {
             if (!empty($model->BLPoto)) {
                 $ftp = new Ftp();
                 $res = $ftp->delete_file($model->BLPoto);
                 $ftp->close();
             }
             $model->BLPoto = $BLPoto;
         }
         //接收dealer数据
         $dealer = Yii::app()->request->getParam("Dealer");
         //保存dealer数据
         $dealermodel = Dealer::model()->find("OrganID=:organid", array(":organid" => $OrganID));
         if (empty($dealermodel)) {
             //判断是否第一次添加
             $dealermodel = new Dealer();
             $dealermodel->OrganID = $OrganID;
         }
         $dealermodel->SaleMoney = $dealer['SaleMoney'];
         $dealermodel->SaleDomain = $dealer['SaleDomain'];
         $dealermodel->ShopArea = $dealer['ShopArea'];
         if ($dealermodel->save() && $model->save()) {
             //保存成功
             $this->redirect(array('index'));
         } else {
             var_dump($dealermodel->errors);
             var_dump($model->errors);
             die;
         }
     }
 }
Example #25
0
 private function generateThumbnail()
 {
     $ftpCon = new Ftp(FTP_USA, FTP_USA_USR, FTP_USA_PWD);
     $connected = $ftpCon->login_r(null, null, FTP_CONN_RETRIES);
     if (!$connected) {
         return false;
     }
     $from = str_replace("%RESOLUTION%", PREVIEW_WIDTH . "x" . PREVIEW_HEIGHT, $this->getPreview());
     $from = str_replace("contenido", "netuy", $from);
     $from = "/www.wazzup.com.uy" . $from;
     $this->thumbnailFilename = "thumbnail" . str_replace(" ", "_", sanitizeString($this->title)) . ".gif";
     $tmp = $this->dirToWrite . "/" . $this->thumbnailFilename;
     //echo "thumb $from => $tmp";
     $bajado = $ftpCon->bajar_r($from, $tmp, FTP_DOWN_RETRIES);
     return $bajado;
 }
Example #26
0
 $wallpaper = new migWallpaper($dbc, $debug, $catLvl, $webCat, $rating);
 try {
     $wallpaper->loadContent($contentId);
 } catch (Exception $e) {
     $log .= "loadContent: " . $e->getMessage() . "\n";
 }
 $wallpaper->setTag($catmig);
 $wallpaper->setSubTag($subcatmig);
 //$wallpaper->setKeywords($keywords[$i]);
 //$wallpaper->setShortDesc($shortDesc[$i]);
 // $wallpaper->setLongDesc($longDesc[$i]);
 try {
     $content_download = FALSE;
     // descargo contenido por FTP
     $log .= "\tdescargando contenido...\n";
     $ftpCon = new Ftp();
     $retries = 0;
     $conectado = $ftpCon->login_r(null, null, FTP_CONN_RETRIES);
     $todos = true;
     if ($conectado === TRUE) {
         $result = $wallpaper->downloadContent($ftpCon);
         foreach ($result as $size => $data) {
             $status = $data['status'];
             $__contentId = $data['id'];
             $todos = $todos && $status;
             $statusStr = $status ? "fue bajada correctamente" : "no fue encontrada";
             $statusColor = $status ? "black" : "red";
             $content_download = $content_download || $status;
             echo "<font color=\"{$statusColor}\">La imagen ({$__contentId}) con tama&ntilde;o {$size} {$statusStr} </font><br>\n";
         }
     } else {
Example #27
0
 /**
  * Upload files with FTP
  *
  * @param
  *        	string|array The name of the config group to use, or a configuration array.
  * @param
  *        	bool Automatically connect to this server.
  */
 public static function with_ftp($config = 'default', $connect = true)
 {
     if (static::$with_ftp = \Ftp::forge($config, $connect)) {
         // if we have an ftp object, activate the move callback
         static::$upload->setConfig('moveCallback', '\\Upload\\move_callback');
     } else {
         // creating the ftp object failed, disable the callback
         static::$upload->setConfig('moveCallback', null);
     }
 }
Example #28
0
 /**
  * Upload files with Ftp
  *
  * @param   string|array  The name of the config group to use, or a configuration array.
  * @param   bool          Automatically connect to this server.
  */
 public static function with_ftp($config = 'default', $connect = true)
 {
     static::$with_ftp = \Ftp::forge($config, $connect);
 }
Example #29
0
$xmlContent .= '<asset xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">' . "\n";
foreach ($listaIds as $contentId) {
    $contentId = trim($contentId);
    $log .= "\tprocessando {$contentId}\n";
    $realtone = new druttRealtone($dbc, $debug);
    try {
        $realtone->loadContent($contentId);
    } catch (Exception $e) {
        $log .= "loadContent: " . $e->getMessage() . "\n";
    }
    try {
        $content_download = FALSE;
        $realtone->setTag($catdrutt);
        // descargo contenido por FTP
        $log .= "\tdescargando contenido...\n";
        $ftpCon = new Ftp();
        $conectado = $ftpCon->login();
        if ($conectado !== TRUE) {
            $conectado = $ftpCon->login();
        }
        if ($conectado !== TRUE) {
            $conectado = $ftpCon->login();
        }
        if ($conectado !== TRUE) {
            $conectado = $ftpCon->login();
        }
        if ($conectado === TRUE) {
            $to = $tmpDir . "/" . $realtone->getContentFilename();
            $from = $realtone->getContent();
            $bajado = $ftpCon->bajar($from, $to);
            if ($bajado !== TRUE) {
Example #30
0
$xmlContent = XMl_HEADER;
foreach ($listaIds as $contentId) {
    $contentId = trim($contentId);
    $log .= "\tprocesando {$contentId}\n";
    $wallpaper = new migWallpaper($dbc, $debug);
    try {
        $wallpaper->loadContent($contentId);
    } catch (Exception $e) {
        $log .= "loadContent: " . $e->getMessage() . "\n";
    }
    try {
        $content_download = FALSE;
        $wallpaper->setTag($catmig);
        // descargo contenido por FTP
        $log .= "\tdescargando contenido...\n";
        $ftpCon = new Ftp();
        $retries = 0;
        $conectado = $ftpCon->login_r(null, null, FTP_CONN_RETRIES);
        if ($conectado === TRUE) {
            $to = TMP_DIR_WP . "/" . $wallpaper->getContentFilename();
            $from = $wallpaper->getContent();
            $bajado = $ftpCon->bajar_r($from, $to, FTP_DOWN_RETRIES);
            if ($bajado === TRUE) {
                $log .= "\tdescargando preview (gif)...\n";
                $to = TMP_DIR_WP . "/preview_tmp.gif";
                $from = $wallpaper->getPreview();
                $bajado = $ftpCon->bajar_r($from, $to, FTP_DOWN_RETRIES);
                if ($bajado === TRUE) {
                    $origen_file = $to;
                    $destino_file = TMP_DIR_WP . "/" . $wallpaper->getPreviewFilename();
                    $width = 100;