示例#1
0
 /**
  * {@inheritdoc}
  */
 public function getMetadata($path)
 {
     if (empty($path) || !($object = ftp_raw($this->getConnection(), 'STAT ' . $path)) || count($object) < 3) {
         return false;
     }
     if (substr($object[1], 0, 5) === "ftpd:") {
         return false;
     }
     return $this->normalizeObject($object[1], '');
 }
 /** This method retrieves the FTP server features as described in RFC2389
     A decent FTP server support MLST command to list file using UTF-8 encoding
     @return an array of features (see code) */
 function getServerFeatures()
 {
     $features = @ftp_raw($this->connect, "FEAT");
     // Check the answer code
     if (!$this->checkCode($features)) {
         return array("list" => "LIST", "charset" => $this->repository->getOption("CHARSET"));
     }
     $retArray = array("list" => "LIST", "charset" => $this->repository->getOption("CHARSET"));
     // Ok, find out the encoding used
     foreach ($features as $feature) {
         if (strstr($feature, "UTF8") !== FALSE) {
             // See http://wiki.filezilla-project.org/Character_Set for an explaination
             @ftp_raw($this->connect, "OPTS UTF-8 ON");
             $retArray['charset'] = "UTF-8";
             return $retArray;
         }
     }
     // In the future version, we should also use MLST as it standardize the listing format
     return $retArray;
 }
 /**
  * Connect to ftp server
  *
  * @return bool
  * @author Dmitry (dio) Levashov
  * @author Naoki Sawada
  **/
 protected function connect()
 {
     if (!($this->connect = ftp_connect($this->options['host'], $this->options['port'], $this->options['timeout']))) {
         return $this->setError('Unable to connect to FTP server ' . $this->options['host']);
     }
     if (!ftp_login($this->connect, $this->options['user'], $this->options['pass'])) {
         $this->umount();
         return $this->setError('Unable to login into ' . $this->options['host']);
     }
     // try switch utf8 mode
     if ($this->encoding) {
         @ftp_exec($this->connect, 'OPTS UTF8 OFF');
     } else {
         @ftp_exec($this->connect, 'OPTS UTF8 ON');
     }
     // switch off extended passive mode - may be usefull for some servers
     @ftp_exec($this->connect, 'epsv4 off');
     // enter passive mode if required
     ftp_pasv($this->connect, $this->options['mode'] == 'passive');
     // enter root folder
     if (!@ftp_chdir($this->connect, $this->root) || $this->root != ftp_pwd($this->connect)) {
         if (empty($this->options['is_local']) || !$this->setLocalRoot()) {
             $this->umount();
             return $this->setError('Unable to open root folder.');
         }
     }
     // check for MLST support
     $features = ftp_raw($this->connect, 'FEAT');
     if (!is_array($features)) {
         $this->umount();
         return $this->setError('Server does not support command FEAT.');
     }
     foreach ($features as $feat) {
         if (strpos(trim($feat), 'MLST') === 0) {
             $this->MLSTsupprt = true;
             break;
         }
     }
     return true;
 }
示例#4
0
 function put($file, $content, $resume_pos = 0)
 {
     $mode = FTP_BINARY;
     if (!$file) {
         return false;
     }
     $path = $this->dir . $file;
     $tmp = tmpfile();
     if (fwrite($tmp, $content) === false) {
         $this->ftp_log[] = 'can\'t write to filesystem';
         return false;
     }
     rewind($tmp);
     $this->chdir(dirname($path));
     if ($resume_pos) {
         ftp_raw($this->conn_id, "REST " . $resume_pos);
     }
     $result = ftp_fput($this->conn_id, basename_safe($path), $tmp, $mode);
     //try deleting first
     if ($result === false) {
         $items = $this->parse_raw_list(dirname($file));
         $perms = 0;
         foreach ($items as $v) {
             if ($v['name'] == basename($file)) {
                 $perms = $v['permsn'];
             }
         }
         //delete before save otherwise save does not work on some servers
         $this->delete($file);
         if ($perms) {
             $this->chmod(intval($perms, 8), $file);
         }
         if ($resume_pos) {
             ftp_raw($this->conn_id, "REST " . $resume_pos);
         }
         $result = ftp_fput($this->conn_id, basename_safe($path), $tmp, $mode);
     }
     fclose($tmp);
     return $result;
 }
 /**
  * Return stat for given path.
  * Stat contains following fields:
  * - (int)    size    file size in b. required
  * - (int)    ts      file modification time in unix time. required
  * - (string) mime    mimetype. required for folders, others - optionally
  * - (bool)   read    read permissions. required
  * - (bool)   write   write permissions. required
  * - (bool)   locked  is object locked. optionally
  * - (bool)   hidden  is object hidden. optionally
  * - (string) alias   for symlinks - link target path relative to root path. optionally
  * - (string) target  for symlinks - link target path. optionally
  *
  * If file does not exists - returns empty array or false.
  *
  * @param  string  $path    file path 
  * @return array|false
  * @author Dmitry (dio) Levashov
  **/
 protected function _stat($path)
 {
     $raw = ftp_raw($this->connect, 'MLST ' . $path);
     if (is_array($raw) && count($raw) > 1 && substr(trim($raw[0]), 0, 1) == 2) {
         $parts = explode(';', trim($raw[1]));
         array_pop($parts);
         $parts = array_map('strtolower', $parts);
         $stat = array();
         // debug($parts);
         foreach ($parts as $part) {
             list($key, $val) = explode('=', $part);
             switch ($key) {
                 case 'type':
                     $stat['mime'] = strpos($val, 'dir') !== false ? 'directory' : $this->mimetype($path);
                     break;
                 case 'size':
                     $stat['size'] = $val;
                     break;
                 case 'modify':
                     $ts = mktime(intval(substr($val, 8, 2)), intval(substr($val, 10, 2)), intval(substr($val, 12, 2)), intval(substr($val, 4, 2)), intval(substr($val, 6, 2)), substr($val, 0, 4));
                     $stat['ts'] = $ts;
                     // $stat['date'] = $this->formatDate($ts);
                     break;
                 case 'unix.mode':
                     $stat['chmod'] = $val;
                     break;
                 case 'perm':
                     $val = strtolower($val);
                     $stat['read'] = (int) preg_match('/e|l|r/', $val);
                     $stat['write'] = (int) preg_match('/w|m|c/', $val);
                     if (!preg_match('/f|d/', $val)) {
                         $stat['locked'] = 1;
                     }
                     break;
             }
         }
         if (empty($stat['mime'])) {
             return array();
         }
         if ($stat['mime'] == 'directory') {
             $stat['size'] = 0;
         }
         if (isset($stat['chmod'])) {
             $stat['perm'] = '';
             if ($stat['chmod'][0] == 0) {
                 $stat['chmod'] = substr($stat['chmod'], 1);
             }
             for ($i = 0; $i <= 2; $i++) {
                 $perm[$i] = array(false, false, false);
                 $n = isset($stat['chmod'][$i]) ? $stat['chmod'][$i] : 0;
                 if ($n - 4 >= 0) {
                     $perm[$i][0] = true;
                     $n = $n - 4;
                     $stat['perm'] .= 'r';
                 } else {
                     $stat['perm'] .= '-';
                 }
                 if ($n - 2 >= 0) {
                     $perm[$i][1] = true;
                     $n = $n - 2;
                     $stat['perm'] .= 'w';
                 } else {
                     $stat['perm'] .= '-';
                 }
                 if ($n - 1 == 0) {
                     $perm[$i][2] = true;
                     $stat['perm'] .= 'x';
                 } else {
                     $stat['perm'] .= '-';
                 }
                 $stat['perm'] .= ' ';
             }
             $stat['perm'] = trim($stat['perm']);
             $owner = $this->options['owner'];
             $read = $owner && $perm[0][0] || $perm[1][0] || $perm[2][0];
             $stat['read'] = $stat['mime'] == 'directory' ? $read && ($owner && $perm[0][2] || $perm[1][2] || $perm[2][2]) : $read;
             $stat['write'] = $owner && $perm[0][1] || $perm[1][1] || $perm[2][1];
             unset($stat['chmod']);
         }
         return $stat;
     }
     return array();
 }
 /** This method retrieves the FTP server features as described in RFC2389
  *	A decent FTP server support MLST command to list file using UTF-8 encoding
  *  @return an array of features (see code)
  */
 protected function getServerFeatures()
 {
     $link = $this->createFTPLink();
     $features = @ftp_raw($link, "FEAT");
     // Check the answer code
     if (isset($features[0]) && $features[0][0] != "2") {
         //ftp_close($link);
         return array("list" => "LIST", "charset" => $this->repoCharset);
     }
     $retArray = array("list" => "LIST", "charset" => $this->repoCharset);
     // Ok, find out the encoding used
     foreach ($features as $feature) {
         if (strstr($feature, "UTF8") !== FALSE) {
             // See http://wiki.filezilla-project.org/Character_Set for an explaination
             @ftp_raw($link, "OPTS UTF-8 ON");
             $retArray['charset'] = "UTF-8";
             //ftp_close($link);
             return $retArray;
         }
     }
     // In the future version, we should also use MLST as it standardize the listing format
     return $retArray;
 }
示例#7
0
 /**
  * Sends an arbitrary command to the FTP server.
  *
  * @param string    $command       FTP command to execute.
  *
  * @return string[] The server's response as an array of strings. No parsing is performed on the response string and not determine if the command succeeded.
  *
  * @throws FtpException If command execution fails.
  */
 public function raw($command)
 {
     $this->connectIfNeeded();
     $this->param = $command;
     $res = ftp_raw($this->handle, $command);
     return $res;
 }
示例#8
0
 function ftp_mlsd($directory)
 {
     require SYSTEM_ROOT . '/config.remote.php';
     if (!self::islogin()) {
         if (!self::login()) {
             return false;
         }
     }
     if (!@ftp_chdir(self::$cid, $directory)) {
         return false;
     }
     $ret = ftp_raw(self::$cid, 'PASV');
     if (!count($ret)) {
         return false;
     }
     if (!preg_match('/^227.*\\(([0-9]+,[0-9]+,[0-9]+,[0-9]+),([0-9]+),([0-9]+)\\)$/', $ret[0], $matches)) {
         return false;
     }
     $conn_IP = str_replace(',', '.', $matches[1]);
     $conn_Port = intval($matches[2]) * 256 + intval($matches[3]);
     $socket = @fsockopen($conn_IP, $conn_Port, $errno, $errstr, $ftp_timeout);
     if (!$socket) {
         return false;
     }
     stream_set_timeout($socket, $ftp_timeout);
     ftp_raw(self::$cid, 'MLSD');
     $s = '';
     while (!feof($socket)) {
         $s .= fread($socket, 1024);
         $stream_meta_data = stream_get_meta_data($socket);
         if ($stream_meta_data['timed_out']) {
             fclose($socket);
             return false;
         }
     }
     fclose($socket);
     $files = array();
     foreach (explode("\n", $s) as $line) {
         if (!$line) {
             continue;
         }
         $file = array();
         $elements = explode(';', $line, 8);
         $cnt = count($elements);
         if ($cnt > 0) {
             $cnt--;
             $file['filename'] = trim($elements[$cnt]);
             for ($i = 0; $i < $cnt; $i++) {
                 if ($i < $cnt) {
                     $attribute = explode('=', $elements[$i]);
                     $file[$attribute[0]] = $attribute[1];
                 }
             }
         }
         $files[] = $file;
     }
     return $files;
 }
示例#9
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;
 }
示例#10
0
 /**
  * Sends an arbitrary command to a FTP server
  *
  * @param  string  $command The command that is send to the server.
  * @return mixed  The server response as string or array
  */
 public function executeRawCommand($command)
 {
     if (is_resource($this->cid)) {
         return ftp_raw($this->cid, $command);
     }
 }
示例#11
0
function woo_ce_cron_export( $gui = '', $type = '', $is_scheduled = false ) {

	global $export;

	$export = new stdClass;
	$export->cron = ( $is_scheduled ? 0 : 1 );
	$export->scheduled_export = ( $is_scheduled ? 1 : 0 );
	$export->start_time = time();
	$export->idle_memory_start = woo_ce_current_memory_usage();
	$export->error = '';

	$bits = '';
	$type = ( isset( $_GET['type'] ) ? $_GET['type'] : $type );
	if( empty( $type ) ) {
		if( $gui == 'gui' ) {
			$output = sprintf( '<p>%s</p>', __( 'No export type was provided.', 'woo_ce' ) );
		} else {
			error_log( sprintf( '[store-exporter-deluxe] -: Error: %s', __( 'No export type was provided', 'woo_ce' ) ) );
			return false;
		}
	} else {
		$types = array_keys( woo_ce_return_export_types() );
		$export->type = $type;
		// Check that export is in the list of available exports
		if( !in_array( $export->type, $types ) ) {
			if( $gui == 'gui' ) {
				$output = '<p>' . __( 'An invalid export type was provided.', 'woo_ce' ) . '</p>';
			} else {
				error_log( sprintf( '[store-exporter-deluxe] -: Error: %s', __( 'An invalid export type was provided', 'woo_ce' ) ) );
				return false;
			}
		} else {
			$export->export_format = ( isset( $_GET['format'] ) ? sanitize_text_field( $_GET['format'] ) : woo_ce_get_option( 'export_format', 'csv' ) );

			// Override the export format if outputting to screen in friendly design
			if( $gui == 'gui' && in_array( $export->export_format, array( 'csv', 'xls', 'xlsx' ) ) )
				$export->export_format = 'csv';

			// Override the export format if this is a scheduled export
			if( $export->scheduled_export )
				$export->export_format = woo_ce_get_option( 'auto_format', 'csv' );

			// Override the export format if the single order Transient is set
			$single_export_format = get_transient( WOO_CD_PREFIX . '_single_export_format' );
			if( $single_export_format !== false )
				$export->export_format = $single_export_format;
			unset( $single_export_format );

			$export->delimiter = ( isset( $_GET['delimiter'] ) ? sanitize_text_field( $_GET['delimiter'] ) : woo_ce_get_option( 'delimiter', ',' ) );
			if( $export->delimiter == '' || $export->delimiter == false ) {
				error_log( '[store-exporter-deluxe] Warning: Delimiter export option was corrupted, defaulted to ,' );
				$export->delimiter = ',';
				woo_ce_update_option( 'delimiter', ',' );
			} else if( $export->delimiter == 'TAB' ) {
				$export->delimiter = "\t";
			}
			$export->category_separator = ( isset( $_GET['category_separator'] ) ? sanitize_text_field( $_GET['category_separator'] ) : woo_ce_get_option( 'category_separator', '|' ) );
			// Override for line break (LF) support in Category Separator
			if( $export->category_separator == 'LF' )
				$export->category_separator = "\n";
			$export->bom = ( isset( $_GET['bom'] ) ? absint( $_GET['bom'] ) : woo_ce_get_option( 'bom', 1 ) );
			$export->encoding = ( isset( $_GET['encoding'] ) ? sanitize_text_field( $_GET['encoding'] ) : woo_ce_get_option( 'encoding', 'UTF-8' ) );
			$export->timeout = woo_ce_get_option( 'timeout', 600 );
			$export->escape_formatting = ( isset( $_GET['escape_formatting'] ) ? sanitize_text_field( $_GET['escape_formatting'] ) : woo_ce_get_option( 'escape_formatting', 'all' ) );
			$export->header_formatting = ( isset( $_GET['header_formatting'] ) ? absint( $_GET['header_formatting'] ) : woo_ce_get_option( 'header_formatting', 1 ) );
			$export->date_format = woo_ce_get_option( 'date_format', 'd/m/Y' );
			$export->order_items = ( isset( $_GET['order_items'] ) ? sanitize_text_field( $_GET['order_items'] ) : woo_ce_get_option( 'order_items_formatting', 'unique' ) );
			$export->order_items_types = ( isset( $_GET['order_items_types'] ) ? sanitize_text_field( $_GET['order_items_types'] ) : woo_ce_get_option( 'order_items_types', false ) );
			$export->upsell_formatting = woo_ce_get_option( 'upsell_formatting', 1 );
			$export->crosssell_formatting = woo_ce_get_option( 'crosssell_formatting', 1 );
			$export->gallery_formatting = woo_ce_get_option( 'gallery_formatting', 0 );
			$export->gallery_unique = woo_ce_get_option( 'gallery_unique', 0 );
			$export->max_product_gallery = woo_ce_get_option( 'max_product_gallery', 3 );
			$export->filename = woo_ce_generate_filename( $export->type );
			switch( $export->export_format ) {

				case 'csv':
					$php_excel_format = 'SED_CSV';
					$file_extension = 'csv';
					$post_mime_type = 'text/csv';
					break;

				case 'xls':
					$php_excel_format = 'Excel5';
					$file_extension = 'xls';
					$post_mime_type = 'application/vnd.ms-excel';
					break;

				case 'xlsx':
					$php_excel_format = 'Excel2007';
					$file_extension = 'xlsx';
					$post_mime_type = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
					break;

				case 'xml':
					$file_extension = 'xml';
					$post_mime_type = 'application/xml';
					break;

				case 'rss':
					$file_extension = 'xml';
					$post_mime_type = 'application/rss+xml';
					break;

				default:
					error_log( sprintf( '[store-exporter-deluxe] -: Warning: %s', __( 'An invalid export format was provided', 'woo_ce' ) ) );
					return;
					break;

			}
			$export->filename = $export->filename . '.' . $file_extension;
			$export->limit_volume = ( isset( $_GET['limit'] ) ? absint( $_GET['limit'] ) : -1 );
			$export->offset = ( isset( $_GET['offset'] ) ? absint( $_GET['offset'] ) : 0 );
			// Select all export fields for CRON export
			$export->fields = woo_ce_cron_export_fields( $export->type, $export->scheduled_export );
			// Grab to value if response is e-mail or remote POST
			if( in_array( $gui, array( 'email', 'post' ) ) ) {
				if( $gui == 'email' )
					$export->to = ( isset( $_GET['to'] ) ? sanitize_email( $_GET['to'] ) : woo_ce_get_option( 'email_to', '' ) );
				else if( $gui == 'post' )
					$export->to = ( isset( $_GET['to'] ) ? esc_url_raw( $_GET['to'] ) : woo_ce_get_option( 'post_to', '' ) );
			}
			$export = woo_ce_check_cron_export_arguments( $export );

			$export->args = array(
				'limit_volume' => $export->limit_volume,
				'offset' => $export->offset,
				'encoding' => $export->encoding,
				'date_format' => $export->date_format,
				'order_items' => $export->order_items,
				'order_items_types' => $export->order_items_types
			);

			$orderby = ( isset( $_GET['orderby'] ) ? sanitize_text_field( $_GET['orderby'] ) : null );
			$order = ( isset( $_GET['order'] ) ? sanitize_text_field( $_GET['order'] ) : null );
			switch( $export->type ) {

				case 'product':
					$export->args['product_orderby'] = $orderby;
					$export->args['product_order'] = $order;
					if( $export->scheduled_export ) {
						$product_filter_type = woo_ce_get_option( 'auto_product_type', false );
						$product_filter_status = woo_ce_get_option( 'auto_product_status', false );
						$product_filter_stock = woo_ce_get_option( 'auto_product_stock', false );
						$product_filter_category = woo_ce_get_option( 'auto_product_category', false );
						$product_filter_tag = woo_ce_get_option( 'auto_product_tag', false );
						$export->args['product_type'] = ( !empty( $product_filter_type ) ? $product_filter_type : false );
						$export->args['product_status'] = ( !empty( $product_filter_status ) ? $product_filter_status : false );
						$export->args['product_stock'] = ( !empty( $product_filter_stock ) ? $product_filter_stock : false );
						$export->args['product_categories'] = ( !empty( $product_filter_category ) ? $product_filter_category : false );
						$export->args['product_tags'] = ( !empty( $product_filter_tag ) ? $product_filter_tag : false );
					} else {
						$export->args['product_status'] = ( isset( $_GET['product_status'] ) ? sanitize_text_field( $_GET['product_status'] ) : null );
						$export->args['product_stock'] = ( isset( $_GET['stock_status'] ) ? sanitize_text_field( $_GET['stock_status'] ) : null );
					}
					break;

				case 'category':
					$export->args['category_orderby'] = $orderby;
					$export->args['category_order'] = $order;
					break;

				case 'tag':
					$export->args['tag_orderby'] = $orderby;
					$export->args['tag_order'] = $order;
					break;

				case 'order':
					$export->args['order_orderby'] = $orderby;
					$export->args['order_order'] = $order;
					$export->args['order_ids'] = ( isset( $_GET['order_ids'] ) ? sanitize_text_field( $_GET['order_ids'] ) : null );

					// Override Filter Orders by Order ID if a single order transient is set
					$single_export_order_ids = get_transient( WOO_CD_PREFIX . '_single_export_order_ids' );
					if( $single_export_order_ids !== false )
						$export->args['order_ids'] = sanitize_text_field( $single_export_order_ids );
					unset( $single_export_order_ids );

					if( $export->scheduled_export ) {

						// Scheduled export engine

						// Order Status
						$order_filter_status = woo_ce_get_option( 'auto_order_status', '' );
						$export->args['order_status'] = ( !empty( $order_filter_status ) ? (array)$order_filter_status : array() );
						// Order Date
						$order_dates_filter = woo_ce_get_option( 'auto_order_date', false );
						if( $order_dates_filter ) {
							$export->args['order_dates_filter'] = $order_dates_filter;
							switch( $order_dates_filter ) {

								case 'manual':
									$order_filter_dates_from = woo_ce_get_option( 'auto_order_dates_from', false );
									$order_filter_dates_to = woo_ce_get_option( 'auto_order_dates_to', false );
									$export->args['order_dates_from'] = ( !empty( $order_filter_dates_from ) ? sanitize_text_field( $order_filter_dates_from ) : false );
									$export->args['order_dates_to'] = ( !empty( $order_filter_dates_to ) ? sanitize_text_field( $order_filter_dates_to ) : false );
									break;

								case 'variable':
									$order_filter_date_variable = woo_ce_get_option( 'auto_order_date_variable', false );
									$order_filter_date_variable_length = woo_ce_get_option( 'auto_order_date_variable_length', false );
									$export->args['order_dates_filter_variable'] = ( !empty( $order_filter_date_variable ) ? absint( $order_filter_date_variable ) : false );
									$export->args['order_dates_filter_variable_length'] = ( !empty( $order_filter_date_variable_length ) ? sanitize_text_field( $order_filter_date_variable_length ) : false );
									break;

							}
						}
						// Product
						$order_filter_product = woo_ce_get_option( 'auto_order_product', '' );
						$export->args['order_product'] = ( !empty( $order_filter_product ) ? (array)$order_filter_product : array() );
						// Billing Country
						$order_filter_billing_country = woo_ce_get_option( 'auto_order_billing_country', false );
						$export->args['order_billing_country'] = ( !empty( $order_filter_billing_country ) ? array_map( 'sanitize_text_field', $order_filter_billing_country ) : false );
						// Shipping Country
						$order_filter_shipping_country = woo_ce_get_option( 'auto_order_shipping_country', false );
						$export->args['order_shipping_country'] = ( !empty( $order_filter_shipping_country ) ? array_map( 'sanitize_text_field', $order_filter_shipping_country ) : false );
						// Payment Gateway
						$order_filter_payment = woo_ce_get_option( 'auto_order_payment', array() );
						$export->args['order_payment'] = ( !empty( $order_filter_payment ) ? array_map( 'sanitize_text_field', $order_filter_payment ) : false );
						// Shipping Method
						$order_filter_shipping = woo_ce_get_option( 'auto_order_shipping', array() );
						$export->args['order_shipping'] = ( !empty( $order_filter_shipping ) ? array_map( 'sanitize_text_field', $order_filter_shipping ) : false );
					} else {

						// CRON export engine

						// Order Status
						if( isset( $_GET['order_status'] ) ) {
							$order_filter_status = sanitize_text_field( $_GET['order_status'] );
							$order_filter_status = explode( ',', $order_filter_status );
							$export->args['order_status'] = $order_filter_status;
						}
						// Product
						if( isset( $_GET['order_product'] ) ) {
							$order_filter_product = sanitize_text_field( $_GET['order_product'] );
							$order_filter_product = explode( ',', $order_filter_product );
							$export->args['order_product'] = $order_filter_product;
						}
						// Order Date
						if( isset( $_GET['order_date_from'] ) && isset( $_GET['order_date_to'] ) ) {
							$order_filter_dates_from = $_GET['order_date_from'];
							$order_filter_dates_to = $_GET['order_date_to'];
							$export->args['order_dates_filter'] = 'manual';
							$export->args['order_dates_from'] = ( !empty( $order_filter_dates_from ) ? sanitize_text_field( $order_filter_dates_from ) : false );
							$export->args['order_dates_to'] = ( !empty( $order_filter_dates_to ) ? sanitize_text_field( $order_filter_dates_to ) : false );
						}
						// Billing Country
						if( isset( $_GET['billing_country'] ) ) {
							$order_filter_billing_country = sanitize_text_field( $_GET['billing_country'] );
							$order_filter_billing_country = explode( ',', $order_filter_billing_country );
							$export->args['order_billing_country'] = ( !empty( $order_filter_billing_country ) ? $order_filter_billing_country : false );
						}
						// Shipping Country
						if( isset( $_GET['shipping_country'] ) ) {
							$order_filter_shipping_country = sanitize_text_field( $_GET['shipping_country'] );
							$order_filter_shipping_country = explode( ',', $order_filter_shipping_country );
							$export->args['order_shipping_country'] = ( !empty( $order_filter_shipping_country ) ? $order_filter_shipping_country : false );
						}
						// Payment Gateway
						if( isset( $_GET['payment_gateway'] ) ) {
							$order_filter_payment = sanitize_text_field( $_GET['order_payment'] );
							$order_filter_payment = explode( ',', $order_filter_payment );
							$export->args['order_payment'] = ( !empty( $order_filter_payment ) ? $order_filter_payment : false );
						}
						// Shipping Method
						if( isset( $_GET['shipping_method'] ) ) {
							$order_filter_shipping = sanitize_text_field( $_GET['shipping_method'] );
							$order_filter_shipping = explode( ',', $order_filter_shipping );
							$export->args['order_shipping'] = ( !empty( $order_filter_shipping ) ? $order_filter_shipping : false );
						}
					}
					break;

				case 'subscription':
					$export->args['subscription_orderby'] = $orderby;
					$export->args['subscription_order'] = $order;
					break;

				case 'product_vendor':
					$export->args['product_vendor_orderby'] = $orderby;
					$export->args['product_vendor_order'] = $order;
					break;

				case 'commission':
					// Commission Date
					$commission_dates_filter = woo_ce_get_option( 'auto_commission_date', false );
					if( $commission_dates_filter ) {
						$export->args['commission_dates_filter'] = $commission_dates_filter;
						switch( $commission_dates_filter ) {

							case 'manual':
								$commission_filter_dates_from = woo_ce_get_option( 'auto_commission_dates_from', false );
								$commission_filter_dates_to = woo_ce_get_option( 'auto_commission_date_to', false );
								$export->args['commission_dates_from'] = ( !empty( $commission_filter_dates_from ) ? sanitize_text_field( $commission_filter_dates_from ) : false );
								$export->args['commission_dates_to'] = ( !empty( $commission_filter_dates_to ) ? sanitize_text_field( $commission_filter_dates_to ) : false );
								break;

							case 'variable':
								$commission_filter_date_variable = woo_ce_get_option( 'auto_commission_date_variable', false );
								$commission_filter_date_variable_length = woo_ce_get_option( 'auto_commission_date_variable_length', false );
								$export->args['commission_dates_filter_variable'] = ( !empty( $commission_filter_date_variable ) ? absint( $commission_filter_date_variable ) : false );
								$export->args['commission_dates_filter_variable_length'] = ( !empty( $commission_filter_date_variable_length ) ? sanitize_text_field( $commission_filter_date_variable_length ) : false );
								break;

						}
					}
					break;

				case 'shipping_class':
					$export->args['shipping_class_orderby'] = $orderby;
					$export->args['shipping_class_order'] = $order;
					break;

			}
			$export->filename = woo_ce_generate_filename( $export->type ) . '.' . $file_extension;
			// Let's spin up PHPExcel for supported Export Types and Export Formats
			if( in_array( $export->export_format, array( 'csv', 'xls', 'xlsx' ) ) ) {
				// Check if we are using PHPExcel or not for supported Export Types
				$dataset = woo_ce_export_dataset( $export->type );
				if( !empty( $dataset ) ) {
					// Check that PHPExcel is where we think it is
					if( file_exists( WOO_CD_PATH . 'classes/PHPExcel.php' ) ) {
						// Check if PHPExcel has already been loaded
						if( !class_exists( 'PHPExcel' ) ) {
							include_once( WOO_CD_PATH . 'classes/PHPExcel.php' );
						} else {
							error_log( sprintf( '[store-exporter-deluxe] %s: Warning: %s', $export->filename, __( 'The PHPExcel library was already loaded by another WordPress Plugin, if there\'s issues with your export file you know where to look.', 'woo_ce' ) ) );
						}
						$excel = new PHPExcel();
						$excel->setActiveSheetIndex( 0 );
						$excel->getActiveSheet()->setTitle( ucfirst( $export->type ) );
						$row = 1;
						// Skip headers if Heading Formatting is turned off
						if( $export->header_formatting ) {
							$col = 0;
							foreach( $export->columns as $column ) {
								$excel->getActiveSheet()->setCellValueByColumnAndRow( $col, $row, $column );
								$excel->getActiveSheet()->getCellByColumnAndRow( $col, $row )->getStyle()->getFont()->setBold( true );
								$excel->getActiveSheet()->getColumnDimensionByColumn( $col )->setAutoSize( true );
								$col++;
							}
							$row = 2;
						}
						foreach( $dataset as $data ) {
							$col = 0;
							foreach( array_keys( $export->fields ) as $field ) {
								$excel->getActiveSheet()->getCellByColumnAndRow( $col, $row )->getStyle()->getFont()->setBold( false );
								if( $export->encoding == 'UTF-8' ) {
									if( woo_ce_detect_value_string( ( isset( $data->$field ) ? $data->$field : null ) ) ) {
										// Treat this cell as a string
										$excel->getActiveSheet()->getCellByColumnAndRow( $col, $row )->setValueExplicit( ( isset( $data->$field ) ? wp_specialchars_decode( $data->$field ) : '' ), PHPExcel_Cell_DataType::TYPE_STRING );
									} else {
										$excel->getActiveSheet()->getCellByColumnAndRow( $col, $row )->setValue( ( isset( $data->$field ) ? wp_specialchars_decode( $data->$field ) : '' ) );
									}
								} else {
									// PHPExcel only deals with UTF-8 regardless of encoding type
									if( woo_ce_detect_value_string( ( isset( $data->$field ) ? $data->$field : null ) ) ) {
										// Treat this cell as a string
										$excel->getActiveSheet()->getCellByColumnAndRow( $col, $row )->setValueExplicit( ( isset( $data->$field ) ? utf8_encode( wp_specialchars_decode( $data->$field ) ) : '' ), PHPExcel_Cell_DataType::TYPE_STRING );
									} else {
										$excel->getActiveSheet()->getCellByColumnAndRow( $col, $row )->setValue( ( isset( $data->$field ) ? utf8_encode( wp_specialchars_decode( $data->$field ) ) : '' ) );
									}
								}
								$col++;
							}
							$row++;
						}
						switch( $export->export_format ) {

							case 'csv':
								// We need to load this after the PHPExcel Class has been created
								woo_cd_load_phpexcel_sed_csv_writer();
								break;

						}
						$objWriter = PHPExcel_IOFactory::createWriter( $excel, $php_excel_format );
						switch( $export->export_format ) {

							case 'csv':
								$objWriter->setUseBOM( true );
								// Check if we're using a non-standard delimiter
								if( $export->delimiter != ',' )
									$objWriter->setDelimiter( $export->delimiter );
								break;

							case 'xlsx':
								$objWriter->setPreCalculateFormulas( false );
								break;

						}
						if( in_array( $gui, array( 'raw' ) ) ) {
							$objWriter->save( 'php://output' );
						} else {
							// Save to file and insert to WordPress Media
							$temp_filename = tempnam( apply_filters( 'woo_ce_sys_get_temp_dir', sys_get_temp_dir() ), 'tmp' );
							// Check if we were given a temporary filename
							if( $temp_filename == false ) {
								$message = sprintf( __( 'We could not create a temporary export file in %s, ensure that WordPress can read and write files here and try again.', 'woo_ce' ), apply_filters( 'woo_ce_sys_get_temp_dir', sys_get_temp_dir() ) );
								error_log( sprintf( '[store-exporter-deluxe] %s: Error: %s', $export->filename, $message ) );
							} else {
								$objWriter->save( $temp_filename );
								$bits = file_get_contents( $temp_filename );
							}
							unlink( $temp_filename );
						}

						// Clean up PHPExcel
						$excel->disconnectWorksheets();
						unset( $objWriter, $excel );

					} else {
						error_log( sprintf( '[store-exporter-deluxe] %s: Error: %s', $export->filename, __( 'We couldn\'t load the PHPExcel library, this file should be present.' ) ) );
					}
				}
			// Run the default engine for the XML and RSS export formats
			} else if( in_array( $export->export_format, array( 'xml', 'rss' ) ) ) {
				// Check if SimpleXMLElement is present
				if( class_exists( 'SED_SimpleXMLElement' ) ) {
					if( $export->export_format == 'xml' ) {
						$xml = new SED_SimpleXMLElement( sprintf( apply_filters( 'woo_ce_export_xml_first_line', '<?xml version="1.0" encoding="%s"?><%s/>' ), esc_attr( $export->encoding ), esc_attr( apply_filters( 'woo_ce_export_xml_store_node', 'store' ) ) ) );
						if( woo_ce_get_option( 'xml_attribute_url', 1 ) )
							$xml->addAttribute( 'url', get_site_url() );
						if( woo_ce_get_option( 'xml_attribute_date', 1 ) )
							$xml->addAttribute( 'date', date( 'Y-m-d' ) );
						if( woo_ce_get_option( 'xml_attribute_time', 0 ) )
							$xml->addAttribute( 'time', date( 'H:i:s' ) );
						if( woo_ce_get_option( 'xml_attribute_title', 1 ) )
							$xml->addAttribute( 'name', htmlspecialchars( get_bloginfo( 'name' ) ) );
						if( woo_ce_get_option( 'xml_attribute_export', 1 ) )
							$xml->addAttribute( 'export', htmlspecialchars( $export->type ) );
						if( woo_ce_get_option( 'xml_attribute_orderby', 1 ) )
							$xml->addAttribute( 'orderby', $orderby );
						if( woo_ce_get_option( 'xml_attribute_order', 1 ) )
							$xml->addAttribute( 'order', $order );
						if( woo_ce_get_option( 'xml_attribute_limit', 1 ) )
							$xml->addAttribute( 'limit', $export->limit_volume );
						if( woo_ce_get_option( 'xml_attribute_offset', 1 ) )
							$xml->addAttribute( 'offset', $export->offset );
						$xml = woo_ce_export_dataset( $export->type, $xml );
					} else if( $export->export_format == 'rss' ) {
						$xml = new SED_SimpleXMLElement( sprintf( apply_filters( 'woo_ce_export_rss_first_line', '<?xml version="1.0" encoding="%s"?><rss version="2.0"%s/>' ), esc_attr( $export->encoding ), ' xmlns:g="http://base.google.com/ns/1.0"' ) );
						$child = $xml->addChild( apply_filters( 'woo_ce_export_rss_channel_node', 'channel' ) );
						$child->addChild( 'title', woo_ce_get_option( 'rss_title', '' ) );
						$child->addChild( 'link', woo_ce_get_option( 'rss_link', '' ) );
						$child->addChild( 'description', woo_ce_get_option( 'rss_description', '' ) );
						$bits = woo_ce_export_dataset( $export->type, $child );
					}
					$bits = woo_ce_format_xml( $xml );
				} else {
					$bits = false;
					error_log( '[store-exporter-deluxe] Error: The SimpleXMLElement class does not exist for XML file generation' );
				}
			}
			if( !empty( $bits ) ) {
				$output = '<p>' . __( 'Export completed successfully.', 'woo_ce' ) . '</p>';
				if( $gui == 'gui' )
					$output .= '<textarea readonly="readonly">' . esc_textarea( str_replace( '<br />', "\n", $bits ) ) . '</textarea>';
			} else {
				if( $gui == 'gui' ) {
					$output = sprintf( '<p>%s</p>', __( 'No export entries were found.', 'woo_ce' ) );
				} else {
					error_log( sprintf( '[store-exporter-deluxe] %s: Warning: %s', $export->filename, __( 'No export entries were found', 'woo_ce' ) ) );
					return false;
				}
			}
		}
	}

	// Return raw export to browser without file headers
	if( $gui == 'raw' && !empty( $bits ) ) {
		return $bits;
	// Return export as file download to browser
	} else if( $gui == 'download' && !empty( $bits ) ) {
		woo_ce_generate_file_headers( $post_mime_type );
		if( defined( 'DOING_AJAX' ) || get_transient( WOO_CD_PREFIX . '_single_export_format' ) !== false )
			echo $bits;
		else
			return $bits;
	// HTTP Post export contents to remote URL
	} else if( $gui == 'post' && !empty( $bits ) ) {
		$args = apply_filters( 'woo_ce_cron_export_post_args', array(
			'method'      => 'POST',
			'timeout'     => 60,
			'redirection' => 0,
			'httpversion' => '1.0',
			'sslverify'   => false,
			'blocking'    => true,
			'headers'     => array(
				'accept'       => $post_mime_type,
				'content-type' => $post_mime_type
			),
			'body'        => $bits,
			'cookies'     => array(),
			'user-agent'  => sprintf( 'WordPress/%s', $GLOBALS['wp_version'] ),
		) );
		$response = wp_remote_post( $export->to, $args );
		if( is_wp_error( $response ) ) {
			error_log( sprintf( '[store-exporter-deluxe] %s: Error: %s', $export->filename, $response->get_error_message() ) );
			return false;
		} else {
			error_log( sprintf( '[store-exporter-deluxe] %s: Success: %s', $export->filename, sprintf( __( 'Remote POST sent to %s', 'woo_ce' ), $export->to ) ) );
		}
	// Output to screen in friendly design with on-screen error responses
	} else if( $gui == 'gui' ) {
		if( file_exists( WOO_CD_PATH . 'templates/admin/cron.php' ) ) {
			include_once( WOO_CD_PATH . 'templates/admin/cron.php' );
		} else {
			error_log( sprintf( '[store-exporter-deluxe] %s: Error: %s', $export->filename, __( 'Could not load template file within /templates/admin/cron.php', 'woo_ce' ) ) );
		}
		if( isset( $output ) )
			echo $output;
		echo '
	</body>
</html>';
	// Save export file to WordPress Media before sending/saving/etc. action
	} else if( in_array( $gui, array( 'gui', 'archive', 'url', 'file', 'email', 'ftp' ) ) ) {
		$upload = false;
		if( $export->filename && !empty( $bits ) ) {
			$post_ID = woo_ce_save_file_attachment( $export->filename, $post_mime_type );
			$upload = wp_upload_bits( $export->filename, null, $bits );
			if( ( $post_ID == false ) || $upload['error'] ) {
				wp_delete_attachment( $post_ID, true );
				error_log( sprintf( '[store-exporter-deluxe] %s: Error: %s', $export->filename, $upload['error'] ) );
				return false;
			}
			if( file_exists( ABSPATH . 'wp-admin/includes/image.php' ) ) {
				include_once( ABSPATH . 'wp-admin/includes/image.php' );
				$attach_data = wp_generate_attachment_metadata( $post_ID, $upload['file'] );
				wp_update_attachment_metadata( $post_ID, $attach_data );
				update_attached_file( $post_ID, $upload['file'] );
				if( !empty( $post_ID ) ) {
					woo_ce_save_file_guid( $post_ID, $export->type, $upload['url'] );
					woo_ce_save_file_details( $post_ID );
				}
			} else {
				error_log( sprintf( '[store-exporter-deluxe] %s: Error: %s', $export->filename, __( 'Could not load image.php within /wp-admin/includes/image.php', 'woo_ce' ) ) );
			}
		}
		// Return URL to export file
		if( $gui == 'url' )
			return $upload['url'];
		// Return system path to export file
		if( $gui == 'file' )
			return $upload['file'];
		// E-mail export file to preferred address or WordPress site owner address
		if( $gui == 'email' ) {

			global $woocommerce;

			$mailer = $woocommerce->mailer();
			$subject = woo_ce_cron_email_subject( $export->type, $export->filename );
			$attachment = $upload['file'];
			$email_heading = sprintf( __( 'Export: %s', 'woo_ce' ), ucwords( $export->type ) );
			$recipient_name = apply_filters( 'woo_ce_email_recipient_name', __( 'there', 'woo_ce' ) );
			$email_contents = apply_filters( 'woo_ce_email_contents', wpautop( __( 'Please find attached your export ready to review.', 'woo_ce' ) ) );

			// Buffer
			ob_start();

			// Get mail template
			if( file_exists( WOO_CD_PATH . 'templates/emails/scheduled_export.php' ) ) {
				include_once( WOO_CD_PATH . 'templates/emails/scheduled_export.php' );
			} else {
				echo wpautop( sprintf( __( 'Hi %s', 'woo_ce' ), $recipient_name ) );
				echo $email_contents;
				error_log( sprintf( '[store-exporter-deluxe] %s: Error: %s', $export->filename, sprintf( __( 'Could not load template file %s within %s, defaulted to hard coded template.', 'woo_ce' ), 'scheduled_export.php', '/templates/emails/...' ) ) );
			}

			// Get contents
			$message = ob_get_clean();

			// Send the mail using WooCommerce mailer
			if( function_exists( 'woocommerce_mail' ) ) {
				woocommerce_mail( $export->to, $subject, $message, null, $attachment );
			} else {
				// Default to wp_mail()
				add_filter( 'wp_mail_content_type', 'woo_ce_set_html_content_type' );
				wp_mail( $export->to, $subject, $message, null, $attachment );
				remove_filter( 'wp_mail_content_type', 'woo_ce_set_html_content_type' );
			}
			// Delete the export file regardless of whether e-mail was successful or not
			wp_delete_attachment( $post_ID, true );
			error_log( sprintf( '[store-exporter-deluxe] %s: Success: %s', $export->filename, sprintf( __( 'Scheduled export e-mail of %s sent to %s', 'woo_ce' ), $export->filename, $export->to ) ) );

		}
		if( $gui == 'ftp' ) {

			// Load up our FTP/SFTP resources
			$host = woo_ce_get_option( 'auto_ftp_method_host', '' );
			if( !empty( $host ) )
				$host = woo_ce_format_ftp_host( $host );
			$port = woo_ce_get_option( 'auto_ftp_method_port', '' );
			$port = ( !empty( $port ) ? absint( $port ) : false );
			$user = woo_ce_get_option( 'auto_ftp_method_user', '' );
			$pass = woo_ce_get_option( 'auto_ftp_method_pass', '' );
			$path = woo_ce_get_option( 'auto_ftp_method_path', '' );
			$filename = woo_ce_get_option( 'auto_ftp_method_filename', '' );
			// Switch to fixed export filename if provided
			if( !empty( $filename ) )
				$export->filename = woo_ce_generate_filename( $export->type, $filename ) . '.' . $file_extension;

			// Check what protocol are we using; FTP or SFTP?
			$protocol = woo_ce_get_option( 'auto_ftp_method_protocol', 'ftp' );
			switch( $protocol ) {

				case 'ftp':
				default:
					// Check if ftp_connect() is available
					if( function_exists( 'ftp_connect' ) ) {
						$passive = woo_ce_get_option( 'auto_ftp_method_passive', '' );
						$timeout = woo_ce_get_option( 'auto_ftp_method_timeout', '' );
						if( $connection = @ftp_connect( $host, $port ) ) {
							// Update the FTP timeout if available and if a timeout was provided at export
							$remote_timeout = ftp_get_option( $connection, FTP_TIMEOUT_SEC );
							$timeout = absint( $timeout );
							if( $remote_timeout !== false && !empty( $timeout ) ) {
								// Compare the server timeout and the timeout provided at export
								if( $remote_timeout <> $timeout ) {
									if( ftp_set_option( $connection, FTP_TIMEOUT_SEC, $timeout ) == false )
										error_log( sprintf( '[store-exporter-deluxe] %s: Warning: %s', $export->filename, sprintf( __( 'Could not change the FTP server timeout on %s', 'woo_ce' ), $host ) ) );
								}
							}
							unset( $remote_timeout );
							if( ftp_login( $connection, $user, $pass ) ) {
								// Check if Transfer Mode is set to Auto/Pasive and if passive mode is available
								if( in_array( $passive, array( 'auto', 'passive' ) ) ) {
									$features = ftp_raw( $connection, 'FEAT' );
									if( !empty( $features ) ) {
										if( in_array( 'PASV', $features ) ) {
											if( ftp_pasv( $connection, true ) == false )
												error_log( sprintf( '[store-exporter-deluxe] %s: Warning: %s', 'woo_ce', $export->filename, sprintf( __( 'Could not switch to FTP passive mode on %s', 'woo_ce' ), $host ) ) );
										}
									}
								}
								// Change directory if neccesary
								if( !empty( $directory ) ) {
									$current_directory  = ftp_pwd( $connection );
									if( $current_directory !== false && @ftp_chdir( $connection, $path ) )
										ftp_chdir( $connection, $path );
								}
								if( ftp_put( $connection, sprintf( '%s/%s', $path, $export->filename ), $upload['file'], FTP_ASCII ) ) {
									error_log( sprintf( '[store-exporter-deluxe] %s: Success: %s', $export->filename, sprintf( __( 'Scheduled export of %s to %s via FTP uploaded', 'woo_ce' ), $export->filename, $path ) ) );
								} else {
									$export->error = sprintf( __( 'There was a problem uploading %s to %s via FTP, response: %s', 'woo_ce' ), $export->filename, $path, woo_ce_error_get_last_message() );
									error_log( sprintf( '[store-exporter-deluxe] %s: Error: %s', $export->filename, $export->error ) );
								}
							} else {
								$export->error = sprintf( __( 'Login incorrect for user %s on FTP server at %s, response: %s', 'woo_ce' ), $user, $host, woo_ce_error_get_last_message() );
								error_log( sprintf( '[store-exporter-deluxe] %s: Error: %s', $export->filename, $export->error ) );
							}
						} else {
							$export->error = sprintf( __( 'There was a problem connecting to %s via FTP', 'woo_ce' ), $host );
							error_log( sprintf( '[store-exporter-deluxe] %s: Error: %s', $export->filename, $export->error ) );
						}
					} else {
						$export->error = __( 'The function ftp_connect() is disabled within your WordPress site, cannot upload to FTP server', 'woo_ce' );
						error_log( __( '[store-exporter-deluxe] %s: Error: %s', 'woo_ce' ), $export->filename, $export->error );
					}
					break;

				case 'sftp':
					// Check if ssh2_connect() is available
					if( function_exists( 'ssh2_connect' ) ) {
						if( $connection = @ssh2_connect( $host, $port ) ) {
							if( ssh2_auth_password( $connection, $user, $pass ) ) {
								// Initialize SFTP subsystem
								if( $session = ssh2_sftp( $connection ) ) {
									if( $handle = fopen( sprintf( 'ssh2.sftp://%s/%s/%s', $session, $path, $export->filename ), 'w+' ) ) {
										error_log( sprintf( '[store-exporter-deluxe] %s: Success: %s', $export->filename, sprintf( __( 'Scheduled export of %s to %s via SFTP uploaded', 'woo_ce' ), $export->filename, $path ) ) );
									} else {
										$export->error = sprintf( __( 'There was a problem uploading %s to %s via SFTP', 'woo_ce' ), $export->filename, $path );
										error_log( sprintf( '[store-exporter-deluxe] %s: Error: %s', $export->filename, $export->error ) );
									}
								} else {
									$export->error = sprintf( __( 'Could not initialize SFTP subsystem on SFTP server at %s', 'woo_ce' ), $host );
									error_log( sprintf( '[store-exporter-deluxe] %s: Error: %s', $export->filename, $export->error ) );
								}
							} else {
								$export->error = sprintf( __( 'Login incorrect for user %s on SFTP server at %s', 'woo_ce' ), $user, $host );
								error_log( sprintf( '[store-exporter-deluxe] %s: Error: %s', $export->filename, $export->error ) );
							}
						} else {
							$export->error = sprintf( __( 'There was a problem connecting to %s via SFTP', 'woo_ce' ), $host );
							error_log( sprintf( '[store-exporter-deluxe] %s: Error: %s', $export->filename, $export->error ) );
						}
					} else {
						$export->error = __( 'The function ssh2_connect() is disabled within your WordPress site, cannot upload to SFTP server', 'woo_ce' );
						error_log( sprintf( __( '[store-exporter-deluxe] %s: Error: %s', 'woo_ce' ), $export->filename, $export->error ) );
					}
					break;

			}
			// Delete the export file regardless of whether upload was successful or not
			wp_delete_attachment( $post_ID, true );
		}
	}

	// Only include scheduled exports to the Recent Scheduled Exports list
	if( $export->scheduled_export ) {
		$recent_exports = woo_ce_get_option( 'recent_scheduled_exports', array() );
		if( empty( $recent_exports ) )
			$recent_exports = array();
		$size = count( $recent_exports );
		// Get the limit from the WordPress Dashboard widget
		if( !$widget_options = get_option( 'woo_ce_recent_scheduled_export_widget_options', array() ) ) {
			$widget_options = array(
				'number' => 5
			);
		}

		// Check if we have maxed out our recent scheduled exports
		if( $size >= $widget_options['number'] )
			array_shift( $recent_exports );
		$post_ID = ( isset( $post_ID ) ? $post_ID : 0 );
		$recent_exports[] = array(
			'post_id' => ( empty( $export->error ) ? $post_ID : 0 ),
			'name' => $export->filename,
			'date' => time(),
			'method' => $gui,
			'error' => $export->error
		);
		woo_ce_update_option( 'recent_scheduled_exports', $recent_exports );
	}

	delete_option( WOO_CD_PREFIX . '_exported' );

	// If the CRON process gets this far, pass on the good news!
	return true;

}
示例#12
0
             if (function_exists('ftp_ssl_connect') and $jobvalue['ftpssl']) {
                 //make SSL FTP connection
                 $ftp_conn_id = ftp_ssl_connect($jobvalue['ftphost'], $jobvalue['ftphostport'], 10);
             } elseif (!$jobvalue['ftpssl']) {
                 //make normal FTP conection if SSL not work
                 $ftp_conn_id = ftp_connect($jobvalue['ftphost'], $jobvalue['ftphostport'], 10);
             }
             $loginok = false;
             if ($ftp_conn_id) {
                 //FTP Login
                 if (@ftp_login($ftp_conn_id, $jobvalue['ftpuser'], backwpup_base64($jobvalue['ftppass']))) {
                     $loginok = true;
                 } else {
                     //if PHP ftp login don't work use raw login
                     ftp_raw($ftp_conn_id, 'USER ' . $jobvalue['ftpuser']);
                     $return = ftp_raw($ftp_conn_id, 'PASS ' . backwpup_base64($jobvalue['ftppass']));
                     if (substr(trim($return[0]), 0, 3) <= 400) {
                         $loginok = true;
                     }
                 }
             }
             if ($loginok) {
                 ftp_pasv($ftp_conn_id, $jobvalue['ftppasv']);
                 ftp_delete($ftp_conn_id, $backupfile);
             } else {
                 $backwpup_message .= 'FTP: ' . __('Login failure!', 'backwpup') . '<br />';
             }
         }
     }
 }
 delete_transient('backwpup_backups_chache');
	protected function _exec($cmd, $function = "_exec") {
		if(!$this->ready) {
			$this->pushError($function, 'Connect first');
			return false;
		}
		if($this->LocalEcho) {
			echo "PUT > ".$cmd.self::CRLF;
		}
		$this->ftp_data_sock = ftp_raw($this->ftp_control_sock, $cmd);
		$this->lastaction = time();
		return $this->_readMsg($function);
	}
示例#14
0
function backwpup_get_backup_files($jobid, $dest)
{
    global $backwpup_message;
    if (empty($jobid) or !in_array(strtoupper($dest), explode(',', strtoupper(BACKWPUP_DESTS))) and $dest != 'FOLDER') {
        return false;
    }
    $jobs = get_option('backwpup_jobs');
    //Load jobs
    $jobvalue = $jobs[$jobid];
    $filecounter = 0;
    $files = array();
    //Get files/filinfo in backup folder
    if ($dest == 'FOLDER' and !empty($jobvalue['backupdir']) and is_dir($jobvalue['backupdir'])) {
        if ($dir = opendir($jobvalue['backupdir'])) {
            while (($file = readdir($dir)) !== false) {
                if (substr($file, 0, 1) == '.') {
                    continue;
                }
                if (is_file($jobvalue['backupdir'] . $file)) {
                    $files[$filecounter]['JOBID'] = $jobid;
                    $files[$filecounter]['DEST'] = $dest;
                    $files[$filecounter]['folder'] = $jobvalue['backupdir'];
                    $files[$filecounter]['file'] = $jobvalue['backupdir'] . $file;
                    $files[$filecounter]['filename'] = $file;
                    $files[$filecounter]['downloadurl'] = backwpup_admin_url('admin.php') . '?page=backwpupbackups&action=download&file=' . $jobvalue['backupdir'] . $file;
                    $files[$filecounter]['filesize'] = filesize($jobvalue['backupdir'] . $file);
                    $files[$filecounter]['time'] = filemtime($jobvalue['backupdir'] . $file);
                    $filecounter++;
                }
            }
            closedir($dir);
        }
    }
    //Get files/filinfo from Dropbox
    if ($dest == 'DROPBOX' and !empty($jobvalue['dropetoken']) and !empty($jobvalue['dropesecret'])) {
        require_once realpath(dirname(__FILE__) . '/../libs/dropbox.php');
        try {
            $dropbox = new backwpup_Dropbox('dropbox');
            $dropbox->setOAuthTokens($jobvalue['dropetoken'], $jobvalue['dropesecret']);
            $contents = $dropbox->metadata($jobvalue['dropedir']);
            if (is_array($contents)) {
                foreach ($contents['contents'] as $object) {
                    if ($object['is_dir'] != true) {
                        $files[$filecounter]['JOBID'] = $jobid;
                        $files[$filecounter]['DEST'] = $dest;
                        $files[$filecounter]['folder'] = "https://api-content.dropbox.com/1/files/" . $jobvalue['droperoot'] . "/" . dirname($object['path']) . "/";
                        $files[$filecounter]['file'] = $object['path'];
                        $files[$filecounter]['filename'] = basename($object['path']);
                        $files[$filecounter]['downloadurl'] = backwpup_admin_url('admin.php') . '?page=backwpupbackups&action=downloaddropbox&file=' . $object['path'] . '&jobid=' . $jobid;
                        $files[$filecounter]['filesize'] = $object['bytes'];
                        $files[$filecounter]['time'] = strtotime($object['modified']);
                        $filecounter++;
                    }
                }
            }
        } catch (Exception $e) {
            $backwpup_message .= 'DROPBOX: ' . $e->getMessage() . '<br />';
        }
    }
    //Get files/filinfo from Sugarsync
    if ($dest == 'SUGARSYNC' and !empty($jobvalue['sugarrefreshtoken'])) {
        if (!class_exists('SugarSync')) {
            require_once dirname(__FILE__) . '/../libs/sugarsync.php';
        }
        if (class_exists('SugarSync')) {
            try {
                $sugarsync = new SugarSync($jobvalue['sugarrefreshtoken']);
                $dirid = $sugarsync->chdir($jobvalue['sugardir'], $jobvalue['sugarroot']);
                $user = $sugarsync->user();
                $dir = $sugarsync->showdir($dirid);
                $getfiles = $sugarsync->getcontents('file');
                if (is_object($getfiles)) {
                    foreach ($getfiles->file as $getfile) {
                        $files[$filecounter]['JOBID'] = $jobid;
                        $files[$filecounter]['DEST'] = $dest;
                        $files[$filecounter]['folder'] = 'https://' . $user->nickname . '.sugarsync.com/' . $dir;
                        $files[$filecounter]['file'] = (string) $getfile->ref;
                        $files[$filecounter]['filename'] = utf8_decode((string) $getfile->displayName);
                        $files[$filecounter]['downloadurl'] = backwpup_admin_url('admin.php') . '?page=backwpupbackups&action=downloadsugarsync&file=' . (string) $getfile->ref . '&jobid=' . $jobid;
                        $files[$filecounter]['filesize'] = (int) $getfile->size;
                        $files[$filecounter]['time'] = strtotime((string) $getfile->lastModified);
                        $filecounter++;
                    }
                }
            } catch (Exception $e) {
                $backwpup_message .= 'SUGARSYNC: ' . $e->getMessage() . '<br />';
            }
        }
    }
    //Get files/filinfo from S3
    if ($dest == 'S3' and !empty($jobvalue['awsAccessKey']) and !empty($jobvalue['awsSecretKey']) and !empty($jobvalue['awsBucket'])) {
        if (!class_exists('AmazonS3')) {
            require_once dirname(__FILE__) . '/../libs/aws/sdk.class.php';
        }
        if (class_exists('AmazonS3')) {
            try {
                $s3 = new AmazonS3(array('key' => $jobvalue['awsAccessKey'], 'secret' => $jobvalue['awsSecretKey'], 'certificate_authority' => true));
                if (($contents = $s3->list_objects($jobvalue['awsBucket'], array('prefix' => $jobvalue['awsdir']))) !== false) {
                    foreach ($contents->body->Contents as $object) {
                        $files[$filecounter]['JOBID'] = $jobid;
                        $files[$filecounter]['DEST'] = $dest;
                        $files[$filecounter]['folder'] = "https://" . $jobvalue['awsBucket'] . ".s3.amazonaws.com/" . dirname((string) $object->Key) . '/';
                        $files[$filecounter]['file'] = (string) $object->Key;
                        $files[$filecounter]['filename'] = basename($object->Key);
                        $files[$filecounter]['downloadurl'] = backwpup_admin_url('admin.php') . '?page=backwpupbackups&action=downloads3&file=' . $object->Key . '&jobid=' . $jobid;
                        $files[$filecounter]['filesize'] = (string) $object->Size;
                        $files[$filecounter]['time'] = strtotime($object->LastModified);
                        $filecounter++;
                    }
                }
            } catch (Exception $e) {
                $backwpup_message .= 'Amazon S3: ' . $e->getMessage() . '<br />';
            }
        }
    }
    //Get files/filinfo from Google Storage
    if ($dest == 'GSTORAGE' and !empty($jobvalue['GStorageAccessKey']) and !empty($jobvalue['GStorageSecret']) and !empty($jobvalue['GStorageBucket'])) {
        if (!class_exists('AmazonS3')) {
            require_once dirname(__FILE__) . '/../libs/aws/sdk.class.php';
        }
        if (class_exists('AmazonS3')) {
            try {
                $gstorage = new AmazonS3(array('key' => $jobvalue['GStorageAccessKey'], 'secret' => $jobvalue['GStorageSecret'], 'certificate_authority' => true));
                $gstorage->set_hostname('storage.googleapis.com');
                $gstorage->allow_hostname_override(false);
                if (($contents = $gstorage->list_objects($jobvalue['GStorageBucket'], array('prefix' => $jobvalue['GStoragedir']))) !== false) {
                    foreach ($contents->body->Contents as $object) {
                        $files[$filecounter]['JOBID'] = $jobid;
                        $files[$filecounter]['DEST'] = $dest;
                        $files[$filecounter]['folder'] = "https://storage.cloud.google.com/" . $jobvalue['GStorageBucket'] . "/" . dirname((string) $object->Key) . '/';
                        $files[$filecounter]['file'] = (string) $object->Key;
                        $files[$filecounter]['filename'] = basename($object->Key);
                        $files[$filecounter]['downloadurl'] = "https://storage.cloud.google.com/" . $jobvalue['GStorageBucket'] . "/" . (string) $object->Key;
                        $files[$filecounter]['filesize'] = (string) $object->Size;
                        $files[$filecounter]['time'] = strtotime($object->LastModified);
                        $filecounter++;
                    }
                }
            } catch (Exception $e) {
                $backwpup_message .= sprintf(__('GStorage API: %s', 'backwpup'), $e->getMessage()) . '<br />';
            }
        }
    }
    //Get files/filinfo from Microsoft Azure
    if ($dest == 'MSAZURE' and !empty($jobvalue['msazureHost']) and !empty($jobvalue['msazureAccName']) and !empty($jobvalue['msazureKey']) and !empty($jobvalue['msazureContainer'])) {
        if (!class_exists('Microsoft_WindowsAzure_Storage_Blob')) {
            require_once dirname(__FILE__) . '/../libs/Microsoft/WindowsAzure/Storage/Blob.php';
        }
        if (class_exists('Microsoft_WindowsAzure_Storage_Blob')) {
            try {
                $storageClient = new Microsoft_WindowsAzure_Storage_Blob($jobvalue['msazureHost'], $jobvalue['msazureAccName'], $jobvalue['msazureKey']);
                $blobs = $storageClient->listBlobs($jobvalue['msazureContainer'], $jobvalue['msazuredir']);
                if (is_array($blobs)) {
                    foreach ($blobs as $blob) {
                        $files[$filecounter]['JOBID'] = $jobid;
                        $files[$filecounter]['DEST'] = $dest;
                        $files[$filecounter]['folder'] = "https://" . $jobvalue['msazureAccName'] . '.' . $jobvalue['msazureHost'] . "/" . $jobvalue['msazureContainer'] . "/" . dirname($blob->Name) . "/";
                        $files[$filecounter]['file'] = $blob->Name;
                        $files[$filecounter]['filename'] = basename($blob->Name);
                        $files[$filecounter]['downloadurl'] = backwpup_admin_url('admin.php') . '?page=backwpupbackups&action=downloadmsazure&file=' . $blob->Name . '&jobid=' . $jobid;
                        $files[$filecounter]['filesize'] = $blob->size;
                        $files[$filecounter]['time'] = strtotime($blob->lastmodified);
                        $filecounter++;
                    }
                }
            } catch (Exception $e) {
                $backwpup_message .= 'MSAZURE: ' . $e->getMessage() . '<br />';
            }
        }
    }
    //Get files/filinfo from RSC
    if ($dest == 'RSC' and !empty($jobvalue['rscUsername']) and !empty($jobvalue['rscAPIKey']) and !empty($jobvalue['rscContainer'])) {
        if (!class_exists('CF_Authentication')) {
            require_once dirname(__FILE__) . '/../libs/rackspace/cloudfiles.php';
        }
        if (class_exists('CF_Authentication')) {
            try {
                $auth = new CF_Authentication($jobvalue['rscUsername'], $jobvalue['rscAPIKey']);
                $auth->ssl_use_cabundle();
                if ($auth->authenticate()) {
                    $conn = new CF_Connection($auth);
                    $conn->ssl_use_cabundle();
                    $backwpupcontainer = $conn->get_container($jobvalue['rscContainer']);
                    $contents = $backwpupcontainer->get_objects(0, NULL, NULL, $jobvalue['rscdir']);
                    foreach ($contents as $object) {
                        $files[$filecounter]['JOBID'] = $jobid;
                        $files[$filecounter]['DEST'] = $dest;
                        $files[$filecounter]['folder'] = "RSC://" . $jobvalue['rscContainer'] . "/" . dirname($object->name) . "/";
                        $files[$filecounter]['file'] = $object->name;
                        $files[$filecounter]['filename'] = basename($object->name);
                        $files[$filecounter]['downloadurl'] = backwpup_admin_url('admin.php') . '?page=backwpupbackups&action=downloadrsc&file=' . $object->name . '&jobid=' . $jobid;
                        $files[$filecounter]['filesize'] = $object->content_length;
                        $files[$filecounter]['time'] = strtotime($object->last_modified);
                        $filecounter++;
                    }
                }
            } catch (Exception $e) {
                $backwpup_message .= 'RSC: ' . $e->getMessage() . '<br />';
            }
        }
    }
    //Get files/filinfo from FTP
    if ($dest == 'FTP' and !empty($jobvalue['ftphost']) and function_exists('ftp_connect') and !empty($jobvalue['ftpuser']) and !empty($jobvalue['ftppass'])) {
        if (function_exists('ftp_ssl_connect') and $jobvalue['ftpssl']) {
            //make SSL FTP connection
            $ftp_conn_id = ftp_ssl_connect($jobvalue['ftphost'], $jobvalue['ftphostport'], 10);
        } elseif (!$jobvalue['ftpssl']) {
            //make normal FTP conection if SSL not work
            $ftp_conn_id = ftp_connect($jobvalue['ftphost'], $jobvalue['ftphostport'], 10);
        }
        $loginok = false;
        if ($ftp_conn_id) {
            //FTP Login
            if (@ftp_login($ftp_conn_id, $jobvalue['ftpuser'], backwpup_base64($jobvalue['ftppass']))) {
                $loginok = true;
            } else {
                //if PHP ftp login don't work use raw login
                ftp_raw($ftp_conn_id, 'USER ' . $jobvalue['ftpuser']);
                $return = ftp_raw($ftp_conn_id, 'PASS ' . backwpup_base64($jobvalue['ftppass']));
                if (substr(trim($return[0]), 0, 3) <= 400) {
                    $loginok = true;
                }
            }
        }
        if ($loginok) {
            ftp_chdir($ftp_conn_id, $jobvalue['ftpdir']);
            $currentftpdir = rtrim(ftp_pwd($ftp_conn_id), '/') . '/';
            ftp_pasv($ftp_conn_id, $jobvalue['ftppasv']);
            if ($ftpfilelist = ftp_nlist($ftp_conn_id, $currentftpdir)) {
                foreach ($ftpfilelist as $ftpfiles) {
                    if (substr(basename($ftpfiles), 0, 1) == '.') {
                        continue;
                    }
                    $files[$filecounter]['JOBID'] = $jobid;
                    $files[$filecounter]['DEST'] = $dest;
                    $files[$filecounter]['folder'] = "ftp://" . $jobvalue['ftphost'] . ':' . $jobvalue['ftphostport'] . dirname($ftpfiles) . "/";
                    $files[$filecounter]['file'] = $ftpfiles;
                    $files[$filecounter]['filename'] = basename($ftpfiles);
                    $files[$filecounter]['downloadurl'] = "ftp://" . rawurlencode($jobvalue['ftpuser']) . ":" . rawurlencode(backwpup_base64($jobvalue['ftppass'])) . "@" . $jobvalue['ftphost'] . ':' . $jobvalue['ftphostport'] . $ftpfiles;
                    $files[$filecounter]['filesize'] = ftp_size($ftp_conn_id, $ftpfiles);
                    $files[$filecounter]['time'] = ftp_mdtm($ftp_conn_id, $ftpfiles);
                    $filecounter++;
                }
            }
        } else {
            $backwpup_message .= 'FTP: ' . __('Login failure!', 'backwpup') . '<br />';
        }
        $donefolders[] = $jobvalue['ftphost'] . '|' . $jobvalue['ftpuser'] . '|' . $jobvalue['ftpdir'];
    }
    return $files;
}
示例#15
0
文件: Session.php 项目: robik/cFTP
 /**
  * Sends an arbitrary command to the FTP server
  *
  * @param string $command Command to execute
  * 
  * @return array Response
  */
 public function doCommand($command)
 {
     return @ftp_raw($this->handle, $command);
 }
示例#16
0
文件: 001.php 项目: badlamer/hhvm
<?php

require 'server.inc';
$ftp = ftp_connect('127.0.0.1', $port);
if (!$ftp) {
    die("Couldn't connect to the server");
}
var_dump(ftp_login($ftp, 'user', 'pass'));
var_dump(ftp_raw($ftp, 'HELP'));
var_dump(ftp_raw($ftp, 'HELP HELP'));
var_dump(ftp_close($ftp));
示例#17
0
 /**
  * FTP Login
  */
 function login()
 {
     if ($this->ftps) {
         $result = array_pop(ftp_raw($this->conn_id, 'USER ' . $this->username));
         if (preg_match('/^331/', $result)) {
             $result = array_pop(ftp_raw($this->conn_id, 'PASS ' . $this->password));
             return preg_match('/^230/', $result);
         } else {
             $result = $this->conn_id = @ftp_ssl_connect($this->hostname, $this->port);
             if (FALSE === $result) {
                 if ($this->debug == TRUE) {
                     $this->_error('ftp_unable_to_connect');
                 }
                 $this->errmsg = '指定されたFTPサーバーに、接続できません。FTPサーバー名をご確認下さい。<br />もしくは、FTP接続の制限が考えられます。';
                 $this->errmsg .= '<br />また、FTPS のアクセスができない可能性もありますので、チェックを外してみてください。';
                 return FALSE;
             }
             $this->isConnectable = true;
             return @ftp_login($this->conn_id, $this->username, $this->password);
         }
     } else {
         echo '<!-- ftp:';
         var_dump($this->conn_id, $this->username, $this->password);
         echo ' -->';
         return @ftp_login($this->conn_id, $this->username, $this->password);
     }
 }
示例#18
0
function gs_hylafax_authfile_put($authfile)
{
    # connect to fax server
    #
    $con_id = @ftp_connect(gs_get_conf('GS_FAX_HYLAFAX_HOST'), gs_get_conf('GS_FAX_HYLAFAX_PORT'), gs_get_conf('GS_FAX_HYLAFAX_TIMEOUT', 20));
    if (!$con_id) {
        return new GsError('Failed to connect to HylaFax server.');
    }
    # log in as admin user
    #
    if (!@ftp_login($con_id, gs_get_conf('GS_FAX_HYLAFAX_ADMIN'), gs_get_conf('GS_FAX_HYLAFAX_PASS'))) {
        return new GsError('Failed to log in at HylaFax server.');
    }
    # go into admin mode
    #
    if (!@ftp_raw($con_id, 'admin ' . gs_get_conf('GS_FAX_HYLAFAX_PASS'))) {
        return new GsError('Failed to switch to admin mode at HylaFax server.');
    }
    # put the local authfile to fax server
    #
    # HylaFax convention: absolute path, relative to Hylafax dir (/var/spool/hylafax/)
    if (!@ftp_put($con_id, '/etc/hosts.hfaxd', $authfile, FTP_BINARY)) {
        return new GsError('Failed to push authfile to HylaFax server.');
    }
    # close connection
    #
    if (@ftp_close($con_id)) {
        return true;
    } else {
        return new GsError('Error.');
    }
}
 private function isFTPConnected()
 {
     if ($this->link_id) {
         if (ftp_raw($this->link_id, 'NOOP')) {
             return true;
         }
     }
     return false;
 }
示例#20
0
文件: Ftp.php 项目: knplabs/gaufrette
 /**
  * Opens the adapter's ftp connection.
  *
  * @throws RuntimeException if could not connect
  */
 private function connect()
 {
     // open ftp connection
     if (!$this->ssl) {
         $this->connection = ftp_connect($this->host, $this->port);
     } else {
         if (function_exists('ftp_ssl_connect')) {
             $this->connection = ftp_ssl_connect($this->host, $this->port);
         } else {
             throw new \RuntimeException('This Server Has No SSL-FTP Available.');
         }
     }
     if (!$this->connection) {
         throw new \RuntimeException(sprintf('Could not connect to \'%s\' (port: %s).', $this->host, $this->port));
     }
     $username = $this->username ?: 'anonymous';
     $password = $this->password ?: '';
     // login ftp user
     if (!@ftp_login($this->connection, $username, $password)) {
         $this->close();
         throw new \RuntimeException(sprintf('Could not login as %s.', $username));
     }
     // switch to passive mode if needed
     if ($this->passive && !ftp_pasv($this->connection, true)) {
         $this->close();
         throw new \RuntimeException('Could not turn passive mode on.');
     }
     // enable utf8 mode if configured
     if ($this->utf8 == true) {
         ftp_raw($this->connection, "OPTS UTF8 ON");
     }
     // ensure the adapter's directory exists
     if ('/' !== $this->directory) {
         try {
             $this->ensureDirectoryExists($this->directory, $this->create);
         } catch (\RuntimeException $e) {
             $this->close();
             throw $e;
         }
         // change the current directory for the adapter's directory
         if (!ftp_chdir($this->connection, $this->directory)) {
             $this->close();
             throw new \RuntimeException(sprintf('Could not change current directory for the \'%s\' directory.', $this->directory));
         }
     }
 }
示例#21
0
文件: ftp.php 项目: luozhanhong/share
 /**
  *
  * 发送到FTP服务器的任意命令
  *
  * @param string $command
  * @return array
  */
 public static function raw($command)
 {
     return ftp_raw(self::$resource, $command);
 }
示例#22
0
 /**
  * Sends an arbitrary command to the server
  * @link http://php.net/ftp_raw
  *
  * @param  string $command The command to execute
  * @return array  Server's response as an array of strings
  */
 public function raw($command)
 {
     return ftp_raw($this->connection->getStream(), $command);
 }
示例#23
0
 /**
  * ftp_raw wrapper
  *
  * @param string $cmd
  * @return mixed
  */
 public function raw($cmd)
 {
     $this->checkConnected();
     return @ftp_raw($this->_conn, $cmd);
 }
 /** This method retrieves the FTP server features as described in RFC2389
  *	A decent FTP server support MLST command to list file using UTF-8 encoding
  *  @return an array of features (see code)
  */
 protected function getServerFeatures()
 {
     $link = $this->createFTPLink();
     if (ConfService::getRepositoryById($this->repositoryId)->getOption("CREATE") == true) {
         // Test if root exists and create it otherwise
         $serverPath = AJXP_Utils::securePath($this->path . "/");
         $testCd = @ftp_chdir($link, $serverPath);
         if ($testCd !== true) {
             $res = @ftp_mkdir($link, $serverPath);
             if (!$res) {
                 throw new Exception("Cannot create path on remote server!");
             }
         }
     }
     $features = @ftp_raw($link, "FEAT");
     // Check the answer code
     if (isset($features[0]) && $features[0][0] != "2") {
         //ftp_close($link);
         return array("list" => "LIST", "charset" => $this->repoCharset);
     }
     $retArray = array("list" => "LIST", "charset" => $this->repoCharset);
     // Ok, find out the encoding used
     foreach ($features as $feature) {
         if (strstr($feature, "UTF8") !== FALSE) {
             // See http://wiki.filezilla-project.org/Character_Set for an explaination
             @ftp_raw($link, "OPTS UTF-8 ON");
             $retArray['charset'] = "UTF-8";
             //ftp_close($link);
             return $retArray;
         }
     }
     // In the future version, we should also use MLST as it standardize the listing format
     return $retArray;
 }
示例#25
0
 /**
  * Sends MDTM command
  *
  * @param string $remote_file
  * @param integer $mtime
  * @return boolean
  */
 function _mdtm($remote_file, $mtime)
 {
     $command = sprintf('MDTM %s %s', date('YmdHis', $mtime), $remote_file);
     return @ftp_raw($this->_ftp, $command);
 }
示例#26
0
 /**
  * Get the size of the remote file.
  *
  * @param   string  $remote  FTP path to file whose size to get
  *
  * @return  mixed  number of bytes or false on error
  *
  * @since   3.6.0
  */
 public function size($remote)
 {
     if (FTP_NATIVE) {
         $size = ftp_size($this->_conn, $remote);
         // In case ftp_size fails, try the SIZE command directly.
         if ($size === -1) {
             $response = ftp_raw($this->_conn, 'SIZE ' . $remote);
             $responseCode = substr($response[0], 0, 3);
             $responseMessage = substr($response[0], 4);
             if ($responseCode != '213') {
                 throw new RuntimeException(JText::_('JLIB_CLIENT_ERROR_JFTP_SIZE_BAD_RESPONSE'), 35);
             }
             $size = (int) $responseMessage;
         }
         return $size;
     }
     // Start passive mode
     if (!$this->_passive()) {
         throw new RuntimeException(JText::_('JLIB_CLIENT_ERROR_JFTP_SIZE_PASSIVE'), 36);
     }
     // Send size command to the FTP server
     if (!$this->_putCmd('SIZE ' . $remote, array(213))) {
         @fclose($this->_dataconn);
         throw new RuntimeException(JText::sprintf('JLIB_CLIENT_ERROR_JFTP_BAD_RESPONSE_SIZE', $this->_response, $remote), 35);
     }
     return (int) substr($this->_responseMsg, 4);
 }
示例#27
0
 public function login($username, $password)
 {
     if ($this->proxyhost) {
         $username .= "@" . $this->host;
         if ($this->proxyuser) {
             $username .= ' ' . $this->proxyuser;
         }
     }
     $retry = 3;
     $done = false;
     while (!$done && $retry-- > 0) {
         $ret = ftp_raw($this->connexion, "USER " . $username);
         if (is_array($ret) && $password) {
             $ret = ftp_raw($this->connexion, "PASS " . $password);
         }
         if (is_array($ret) && $this->proxypwd) {
             $ret = ftp_raw($this->connexion, "ACCT " . $this->proxypwd);
         }
         if (is_array($ret)) {
             $done = true;
         }
     }
     if (!$done) {
         throw new Exception('Impossible de s\'authentifier sur le serveur FTP');
     }
     return $this;
 }
示例#28
0
function net2ftp_module_printBody()
{
    // --------------
    // This function prints the raw FTP command screen
    // --------------
    // -------------------------------------------------------------------------
    // Global variables
    // -------------------------------------------------------------------------
    global $net2ftp_settings, $net2ftp_globals, $net2ftp_messages, $net2ftp_result, $net2ftp_output;
    if (isset($_POST["command"]) == true) {
        $command = $_POST["command"];
    } else {
        $command = "CWD {$directory_html}\nPWD\n";
    }
    // -------------------------------------------------------------------------
    // Variables
    // -------------------------------------------------------------------------
    // Title
    $title = __("Send arbitrary FTP commands");
    // Form name, back and forward buttons
    $formname = "RawForm";
    $back_onclick = "document.forms['" . $formname . "'].state.value='advanced';document.forms['" . $formname . "'].screen.value='1';document.forms['" . $formname . "'].submit();";
    $forward_onclick = "document.forms['" . $formname . "'].submit();";
    // Open connection
    setStatus(2, 10, __("Connecting to the FTP server"));
    $conn_id = ftp_openconnection();
    if ($net2ftp_result["success"] == false) {
        return false;
    }
    // Explode list of commands to an array
    $command_exploded = explode("\n", $command);
    // Remove the empty lines
    $new_command_nr = 0;
    for ($command_nr = 0; $command_nr < sizeof($command_exploded); $command_nr++) {
        if (trim($command_exploded[$command_nr]) != "") {
            $command_exploded_trimmed[$new_command_nr] = trim($command_exploded[$command_nr]);
            $new_command_nr++;
        }
    }
    // Send arbitrary FTP command
    $command_total = sizeof($command_exploded_trimmed);
    for ($command_nr = 0; $command_nr < $command_total; $command_nr++) {
        setStatus($command_nr + 1, $command_total, __("Sending FTP command %1\$s of %2\$s", $command_nr + 1, $command_total));
        $ftp_raw_result[$command_nr] = ftp_raw($conn_id, trim($command_exploded_trimmed[$command_nr]));
    }
    // Close connection
    ftp_closeconnection($conn_id);
    // Get the messages
    for ($command_nr = 0; $command_nr < sizeof($command_exploded_trimmed); $command_nr++) {
        for ($line_nr = 0; $line_nr < sizeof($ftp_raw_result[$command_nr]); $line_nr++) {
            $net2ftp_output["ftp_raw"][] = $ftp_raw_result[$command_nr][$line_nr] . "\n";
        }
    }
    // -------------------------------------------------------------------------
    // Print the output
    // -------------------------------------------------------------------------
    require_once $net2ftp_globals["application_skinsdir"] . "/" . $net2ftp_globals["skin"] . "/manage.template.php";
}
 /**
  * Return stat for given path.
  * Stat contains following fields:
  * - (int)    size    file size in b. required
  * - (int)    ts      file modification time in unix time. required
  * - (string) mime    mimetype. required for folders, others - optionally
  * - (bool)   read    read permissions. required
  * - (bool)   write   write permissions. required
  * - (bool)   locked  is object locked. optionally
  * - (bool)   hidden  is object hidden. optionally
  * - (string) alias   for symlinks - link target path relative to root path. optionally
  * - (string) target  for symlinks - link target path. optionally
  *
  * If file does not exists - returns empty array or false.
  *
  * @param  string  $path    file path 
  * @return array|false
  * @author Dmitry (dio) Levashov
  **/
 protected function _stat($path)
 {
     $outPath = $this->convEncOut($path);
     if (isset($this->cache[$outPath])) {
         return $this->convEncIn($this->cache[$outPath]);
     } else {
         $this->convEncIn();
     }
     if (!$this->MLSTsupprt) {
         if ($path == $this->root && ($path === $this->systemRoot || !$this->isMyReload())) {
             $res = array('name' => $this->root, 'mime' => 'directory', 'dirs' => $this->_subdirs($path));
             if ($this->isMyReload()) {
                 $ts = 0;
                 foreach (ftp_rawlist($this->connect, $path) as $str) {
                     if ($stat = $this->parseRaw($str, $path)) {
                         $ts = max($ts, $stat['ts']);
                     }
                 }
                 if ($ts) {
                     $res['ts'] = $ts;
                 }
             }
             return $res;
         }
         $this->cacheDir($this->convEncOut($this->_dirname($path)));
         $stat = $this->convEncIn(isset($this->cache[$outPath]) ? $this->cache[$outPath] : array());
         if (!$this->mounted) {
             // dispose incomplete cache made by calling `stat` by 'startPath' option
             $this->cache = array();
         }
         return $stat;
     }
     $raw = ftp_raw($this->connect, 'MLST ' . $path);
     if (is_array($raw) && count($raw) > 1 && substr(trim($raw[0]), 0, 1) == 2) {
         $parts = explode(';', trim($raw[1]));
         array_pop($parts);
         $parts = array_map('strtolower', $parts);
         $stat = array();
         foreach ($parts as $part) {
             list($key, $val) = explode('=', $part);
             switch ($key) {
                 case 'type':
                     $stat['mime'] = strpos($val, 'dir') !== false ? 'directory' : $this->mimetype($path);
                     break;
                 case 'size':
                     $stat['size'] = $val;
                     break;
                 case 'modify':
                     $ts = mktime(intval(substr($val, 8, 2)), intval(substr($val, 10, 2)), intval(substr($val, 12, 2)), intval(substr($val, 4, 2)), intval(substr($val, 6, 2)), substr($val, 0, 4));
                     $stat['ts'] = $ts;
                     break;
                 case 'unix.mode':
                     $stat['chmod'] = $val;
                     break;
                 case 'perm':
                     $val = strtolower($val);
                     $stat['read'] = (int) preg_match('/e|l|r/', $val);
                     $stat['write'] = (int) preg_match('/w|m|c/', $val);
                     if (!preg_match('/f|d/', $val)) {
                         $stat['locked'] = 1;
                     }
                     break;
             }
         }
         if (empty($stat['mime'])) {
             return array();
         }
         if ($stat['mime'] == 'directory') {
             $stat['size'] = 0;
         }
         if (isset($stat['chmod'])) {
             $stat['perm'] = '';
             if ($stat['chmod'][0] == 0) {
                 $stat['chmod'] = substr($stat['chmod'], 1);
             }
             for ($i = 0; $i <= 2; $i++) {
                 $perm[$i] = array(false, false, false);
                 $n = isset($stat['chmod'][$i]) ? $stat['chmod'][$i] : 0;
                 if ($n - 4 >= 0) {
                     $perm[$i][0] = true;
                     $n = $n - 4;
                     $stat['perm'] .= 'r';
                 } else {
                     $stat['perm'] .= '-';
                 }
                 if ($n - 2 >= 0) {
                     $perm[$i][1] = true;
                     $n = $n - 2;
                     $stat['perm'] .= 'w';
                 } else {
                     $stat['perm'] .= '-';
                 }
                 if ($n - 1 == 0) {
                     $perm[$i][2] = true;
                     $stat['perm'] .= 'x';
                 } else {
                     $stat['perm'] .= '-';
                 }
                 $stat['perm'] .= ' ';
             }
             $stat['perm'] = trim($stat['perm']);
             $owner = $this->options['owner'];
             $read = $owner && $perm[0][0] || $perm[1][0] || $perm[2][0];
             $stat['read'] = $stat['mime'] == 'directory' ? $read && ($owner && $perm[0][2] || $perm[1][2] || $perm[2][2]) : $read;
             $stat['write'] = $owner && $perm[0][1] || $perm[1][1] || $perm[2][1];
             unset($stat['chmod']);
         }
         return $stat;
     }
     return array();
 }
示例#30
0
 /**
  * 执行命令
  * @access public
  * @param string $command
  * @return array
  */
 public function exec($command)
 {
     return @ftp_raw($this->link, $command);
 }