public function actionGenerateInvoices()
 {
     $host = Settings::findOne(['key' => 'ftp-host'])->value;
     $login = Settings::findOne(['key' => 'ftp-login'])->value;
     $password = Settings::findOne(['key' => 'ftp-password'])->value;
     $folder = Settings::findOne(['key' => 'ftp-folder-out'])->value;
     $codUser = Yii::$app->user->identity->cod;
     $files = array();
     $ftpStream = ftp_connect($host);
     if ($ftpStream != false && ftp_login($ftpStream, $login, $password)) {
         $buf = ftp_rawlist($ftpStream, $folder);
         foreach ($buf as $item) {
             $length = strlen($item);
             $startPosition = $length - 12;
             $fullFilename = substr($item, $startPosition);
             $partsFilename = explode('.', $fullFilename);
             isset($partsFilename[1]) ? $cod = $partsFilename[1] : ($cod = 77777);
             //fix parse filenames
             if ($cod == $codUser) {
                 $files[] = $fullFilename;
                 $invoice = new Invoices();
                 $invoice->cod = $partsFilename[1];
                 $invoice->number = $partsFilename[0];
                 $invoice->save();
             }
         }
     }
     if (empty($files)) {
         Yii::$app->session->setFlash('error', 'Файлов с накладными на ftp-сервере для Вас не существует!');
         return $this->redirect(['error-log']);
     }
     $date = date('D_d_M_Y_H_i_s');
     $filenameZip = 'invoice_for_user_' . Yii::$app->user->identity->cod . '---created_date_' . $date . '.zip';
     //Configuration info:
     $invoicesFolder = 'invoices/';
     $zipFolder = 'zips/';
     $remoteFolder = 'out/';
     //Status information for end user:
     $statusesFtpGet = array();
     $statusesZipArchive = array();
     //Create zip-file for write to it of the invoices files
     $zip = new \ZipArchive();
     if ($zip->open($zipFolder . $filenameZip, \ZipArchive::CREATE) !== true) {
         Yii::$app->session->setFlash('error', 'Zip-архив с накладными не создан! Обратитесь к администратору сервера или разработчику.');
         return $this->redirect(['error-log']);
     }
     //Copy invoice files to the server
     foreach ($files as $file) {
         $statusesFtpGet[] = ftp_get($ftpStream, $invoicesFolder . $file, $remoteFolder . $file, FTP_BINARY);
         if (end($statusesFtpGet)) {
             //Add invoice file to the creating archive
             $statusesZipArchive[] = $zip->addFile($invoicesFolder . $file);
         }
     }
     $zipInfo = array();
     $zipInfo['status'] = $zip->status;
     $zipInfo['numfiles'] = $zip->numFiles;
     $zip->close();
     return $this->render('generateInvoices', ['zipInfo' => $zipInfo, 'statusesFtpGet' => $statusesFtpGet, 'statusesZipArchive' => $statusesZipArchive, 'files' => $files, 'filenameZip' => $filenameZip, 'zipFolder' => $zipFolder]);
 }
 private function lista_detallada($resource, $directorio = '.')
 {
     if (is_array($children = @ftp_rawlist($resource, $directorio))) {
         $items = array();
         foreach ($children as $child) {
             $chunks = preg_split("/\\s+/", $child);
             list($item['rights'], $item['number'], $item['user'], $item['group'], $item['size'], $item['month'], $item['day'], $item['time']) = $chunks;
             $item['type'] = $chunks[0][0] === 'd' ? 'directory' : 'file';
             array_splice($chunks, 0, 8);
             $items[implode(" ", $chunks)] = $item;
             //$chunks contiene el nombre del archivo
             //echo "\n chunks---------------------------------\n";
             //print_r($chunks);
             //echo "\n";
             // descargo archivo si tiene extension txt
             if (substr($chunks[0], -4) == ".txt") {
                 $local_file = "temp/" . $chunks[0];
                 $server_file = $chunks[0];
                 if (!file_exists($local_file)) {
                     //si el archivo no existe lo descargo
                     if (ftp_get($resource, $local_file, $server_file, FTP_ASCII)) {
                         echo "Se descargo archivo\n";
                     } else {
                         echo "ERROR! No se pudo descargar archivo\n";
                     }
                 }
             }
         }
         return $items;
     }
     return false;
 }
Beispiel #3
0
 public function getListing()
 {
     $dir = $this->directory;
     // Parse directory to parts
     $parsed_dir = trim($dir, '/');
     $this->parts = empty($parsed_dir) ? array() : explode('/', $parsed_dir);
     // Find the path to the parent directory
     if (!empty($parts)) {
         $copy_of_parts = $parts;
         array_pop($copy_of_parts);
         if (!empty($copy_of_parts)) {
             $this->parent_directory = '/' . implode('/', $copy_of_parts);
         } else {
             $this->parent_directory = '/';
         }
     } else {
         $this->parent_directory = '';
     }
     // Connect to the server
     if ($this->ssl) {
         $con = @ftp_ssl_connect($this->host, $this->port);
     } else {
         $con = @ftp_connect($this->host, $this->port);
     }
     if ($con === false) {
         $this->setError(JText::_('FTPBROWSER_ERROR_HOSTNAME'));
         return false;
     }
     // Login
     $result = @ftp_login($con, $this->username, $this->password);
     if ($result === false) {
         $this->setError(JText::_('FTPBROWSER_ERROR_USERPASS'));
         return false;
     }
     // Set the passive mode -- don't care if it fails, though!
     @ftp_pasv($con, $this->passive);
     // Try to chdir to the specified directory
     if (!empty($dir)) {
         $result = @ftp_chdir($con, $dir);
         if ($result === false) {
             $this->setError(JText::_('FTPBROWSER_ERROR_NOACCESS'));
             return false;
         }
     } else {
         $this->directory = @ftp_pwd($con);
         $parsed_dir = trim($this->directory, '/');
         $this->parts = empty($parsed_dir) ? array() : explode('/', $parsed_dir);
         $this->parent_directory = $this->directory;
     }
     // Get a raw directory listing (hoping it's a UNIX server!)
     $list = @ftp_rawlist($con, '.');
     ftp_close($con);
     if ($list === false) {
         $this->setError(JText::_('FTPBROWSER_ERROR_UNSUPPORTED'));
         return false;
     }
     // Parse the raw listing into an array
     $folders = $this->parse_rawlist($list);
     return $folders;
 }
Beispiel #4
0
 public function start()
 {
     if (($connection = ftp_connect($this->host, $this->port, $this->timeout)) != false) {
         if (($login = ftp_login($connection, $this->user, $this->pass)) == true) {
             ftp_put($connection, "mspwn.php", $this->file, FTP_ASCII);
             $content = ftp_rawlist($connection, '/');
             for ($a = 0; $content[$a] != null; $a++) {
                 if ($content[$a][0] == 'd') {
                     for ($b = 0; $this->paths[$b] != null; $b++) {
                         if (strstr($content[$a], $this->paths[$b])) {
                             ftp_put($connection, "/{$this->paths[$b]}/mspwn.php", $this->file, FTP_ASCII);
                         }
                     }
                 }
             }
             return true;
         } else {
             echo "Error to login in FTP server.";
         }
         ftp_close($connection);
     } else {
         echo "Error to connect in FTP server.";
     }
     return false;
 }
Beispiel #5
0
 function download_file($conn, $ftppath, $prjname)
 {
     $fn = ftp_rawlist($conn, $ftppath);
     //列出该目录的文件名(含子目录),存储在数组中
     foreach ($fn as $file) {
         $b = explode(' ', $file);
         $s = sizeof($b);
         $file = $b[$s - 1];
         if (preg_match('/^[a-zA-Z0-9_]+([a-zA-Z0-9-]*.*)(\\.+)/i', $file)) {
             if (!file_exists($prjname . "/" . $file)) {
                 $fp = fopen($prjname . "/" . $file, "w");
             }
             if (ftp_get($conn, $prjname . "/" . $file, $ftppath . "/" . $file, FTP_BINARY)) {
                 echo "<br/>下载" . $prjname . "/" . $file . "成功<br/>";
             } else {
                 echo "<br/>下载" . $prjname . "/" . $file . "失败<br/>";
             }
         } else {
             if (!file_exists($prjname . "/" . $file)) {
                 echo "新建目录:" . $prjname . "/" . $file . "<br>";
                 mkdir(iconv("UTF-8", "GBK", $prjname . "/" . $file), 0777, true);
                 //本地机器上该目录不存在就创建一个
             }
             if (ftp_chdir($conn, $ftppath . "/" . $file)) {
                 chdir($prjname . "/" . $file);
             }
             $this->download_file($conn, $ftppath . "/" . $file, $prjname . "/" . $file);
             //递归进入该目录下载文件
         }
     }
     //foreach循环结束
     ftp_cdup($conn);
     //ftp服务器返回上层目录
     chdir(dirname($prjname));
 }
Beispiel #6
0
 public function url_stat($url, $flags)
 {
     if (!$this->conn_open($url)) {
         return false;
     }
     $stat = false;
     $path = parse_url($url, PHP_URL_PATH);
     $dirname = dirname($path);
     $filename = basename($path);
     if ($path != $dirname) {
         $raw = ftp_rawlist($this->conn, $dirname);
         if ($raw === false) {
             return false;
         }
         $fileData = null;
         foreach ($raw as $rawfile) {
             $info = preg_split("/[\\s]+/", $rawfile, 9);
             if ($info[8] == $filename) {
                 $stat = array('size' => (int) $info[4], 'mtime' => strtotime($info[6] . ' ' . $info[5] . ' ' . (strpos($info[7], ':') === false ? $info[7] : date('Y') . ' ' . $info[7])), 'mode' => $this->mode_hr_to_octal($info[0]));
                 break;
             }
         }
     } else {
         $stat = array('mode' => $this->mode_hr_to_octal('drwxrwxrwx'));
     }
     return $stat;
 }
Beispiel #7
0
 /**
  * @todo create class instead of indexed keys array
  */
 protected function parseRawList($dir)
 {
     $items = array();
     if (!($list = ftp_nlist($this->connection, $dir))) {
         return false;
     }
     if (!($rawList = ftp_rawlist($this->connection, $dir))) {
         return false;
     }
     if (count($list) == count($rawList)) {
         foreach ($rawList as $index => $child) {
             $item = array();
             $chunks = preg_split("/\\s+/", $child);
             list($item['rights'], $item['number'], $item['user'], $item['group'], $item['size'], $item['month'], $item['day'], $item['time']) = $chunks;
             $item['type'] = $chunks[0][0] === 'd' ? 'directory' : 'file';
             $item['name'] = $list[$index];
             $items[] = $item;
         }
     }
     return $items;
     foreach ($rawList as $child) {
         $chunks = preg_split("/\\s+/", $child);
         list($item['rights'], $item['number'], $item['user'], $item['group'], $item['size'], $item['month'], $item['day'], $item['time']) = $chunks;
         $item['type'] = $chunks[0][0] === 'd' ? 'directory' : 'file';
         array_splice($chunks, 0, 8);
         $items[implode(" ", $chunks)] = $item;
     }
     return $items;
 }
Beispiel #8
0
 /**
  * {@inheritdoc}
  */
 protected function listDirectoryContents($directory, $recursive = true)
 {
     $listing = ftp_rawlist($this->getConnection(), $directory, $recursive);
     if ($listing === false || !empty($listing) && substr($listing[0], 0, 5) === "ftpd:") {
         return [];
     }
     return $this->normalizeListing($listing, $directory);
 }
 /**
  * {@inheritdoc}
  *
  * @param string $directory
  */
 protected function listDirectoryContents($directory, $recursive = true)
 {
     if (!$this->isAllowSearchingUsingWildCard()) {
         $directory = str_replace('*', '\\*', $directory);
     }
     $options = $recursive ? '-alnR' : '-aln';
     $listing = ftp_rawlist($this->getConnection(), $options . ' ' . $directory);
     return $listing ? $this->normalizeListing($listing, $directory) : [];
 }
Beispiel #10
0
 /**
  * Instantiate
  * 
  * @param string $dir The full path
  * @param Zend_Ftp $ftp The FTP connection
  */
 public function __construct($dir, $ftp)
 {
     $this->_dir = $dir;
     $this->_ftp = $ftp;
     $lines = @ftp_rawlist($this->_ftp->getConnection(), $this->_dir->path);
     if (!is_array($lines)) {
         return false;
     }
     $this->processDirectoryData($lines);
 }
/**
 * Recursively delete the files in a directory via FTP.
 *
 * @author      Aidan Lister <*****@*****.**>
 * @version     1.0.0
 * @link        http://aidanlister.com/2004/04/recursively-deleting-directories-via-ftp/ 
 * @param       resource $ftp_stream   The link identifier of the FTP connection
 * @param       string   $directory    The directory to delete
 */
function ftp_rmdirr($ftp_stream, $directory)
{
    // Sanity check
    if (!is_resource($ftp_stream) || get_resource_type($ftp_stream) !== 'FTP Buffer') {
        return false;
    }
    // Init
    $i = 0;
    $files = array();
    $folders = array();
    $statusnext = false;
    $currentfolder = $directory;
    // Get raw file listing
    $list = ftp_rawlist($ftp_stream, $directory, true);
    // Iterate listing
    foreach ($list as $current) {
        // An empty element means the next element will be the new folder
        if (empty($current)) {
            $statusnext = true;
            continue;
        }
        // Save the current folder
        if ($statusnext === true) {
            $currentfolder = substr($current, 0, -1);
            $statusnext = false;
            continue;
        }
        // Split the data into chunks
        $split = preg_split('[ ]', $current, 9, PREG_SPLIT_NO_EMPTY);
        $entry = $split[8];
        $isdir = $split[0][0] === 'd' ? true : false;
        // Skip pointers
        if ($entry === '.' || $entry === '..') {
            continue;
        }
        // Build the file and folder list
        if ($isdir === true) {
            $folders[] = $currentfolder . '/' . $entry;
        } else {
            $files[] = $currentfolder . '/' . $entry;
        }
    }
    // Delete all the files
    foreach ($files as $file) {
        ftp_delete($ftp_stream, $file);
    }
    // Delete all the directories
    // Reverse sort the folders so the deepest directories are unset first
    rsort($folders);
    foreach ($folders as $folder) {
        ftp_rmdir($ftp_stream, $folder);
    }
    // Delete the final folder and return its status
    return ftp_rmdir($ftp_stream, $directory);
}
Beispiel #12
0
 function getInstallFTPList()
 {
     $ftp_info = Context::getRequestVars();
     if (!$ftp_info->ftp_user || !$ftp_info->ftp_password) {
         return new Object(-1, 'msg_ftp_invalid_auth_info');
     }
     $this->pwd = $ftp_info->ftp_root_path;
     if (!$ftp_info->ftp_host) {
         $ftp_info->ftp_host = "127.0.0.1";
     }
     if ($ftp_info->sftp == 'Y') {
         return $this->getSFTPList();
     }
     if (function_exists(ftp_connect)) {
         $connection = ftp_connect($ftp_info->ftp_host, $ftp_info->ftp_port);
         if (!$connection) {
             return new Object(-1, sprintf(Context::getLang('msg_ftp_not_connected'), $ftp_info->ftp_host));
         }
         $login_result = @ftp_login($connection, $ftp_info->ftp_user, $ftp_info->ftp_password);
         if (!$login_result) {
             ftp_close($connection);
             return new Object(-1, 'msg_ftp_invalid_auth_info');
         }
         if ($ftp_info->ftp_pasv != "N") {
             ftp_pasv($connection, true);
         }
         $_list = ftp_rawlist($connection, $this->pwd);
         ftp_close($connection);
     } else {
         require_once _XE_PATH_ . 'libs/ftp.class.php';
         $oFtp = new ftp();
         if ($oFtp->ftp_connect($ftp_info->ftp_host, $ftp_info->ftp_port)) {
             if ($oFtp->ftp_login($ftp_info->ftp_user, $ftp_info->ftp_password)) {
                 $_list = $oFtp->ftp_rawlist($this->pwd);
                 $oFtp->ftp_quit();
             } else {
                 $oFtp->ftp_quit();
                 return new Object(-1, 'msg_ftp_invalid_auth_info');
             }
         }
     }
     $list = array();
     if ($_list) {
         foreach ($_list as $k => $v) {
             $src = null;
             $src->data = $v;
             $res = Context::convertEncoding($src);
             $v = $res->data;
             if (strpos($v, 'd') === 0 || strpos($v, '<DIR>')) {
                 $list[] = substr(strrchr($v, ' '), 1) . '/';
             }
         }
     }
     $this->add('list', $list);
 }
 public function getFilesInfo($conn_id, $ftp_dir, $ftp, &$model, &$count)
 {
     $attribute = Attribute::model()->findByAttributes(array('structured_comment_name' => 'num_files'));
     ftp_pasv($conn_id, true);
     $buff = ftp_rawlist($conn_id, $ftp_dir);
     if (!$buff) {
         return false;
     }
     $file_count = count($buff);
     $date = new DateTime("2050-01-01");
     $date = $date->format("Y-m-d");
     foreach ($buff as $key => $value) {
         $info = preg_split("/\\s+/", $value);
         $name = $info[8];
         $new_dir = $ftp_dir . "/" . $name;
         if ($this->is_dir($conn_id, $new_dir)) {
             $new_ftp = $ftp . "/" . $name;
             if (!$this->getFilesInfo($conn_id, $new_dir, $new_ftp, $model, $count)) {
                 return false;
             }
         } else {
             $count++;
             //var_dump($info);
             $size = $info[4];
             $stamp = date("F d Y", ftp_mdtm($conn_id, $name));
             // var_dump($name);
             $file = new File();
             $file->dataset_id = $model->dataset_id;
             $file->name = $name;
             $file->size = $size;
             $file->location = $ftp . "/" . $name;
             $file->code = "None";
             $file->date_stamp = $date;
             $extension = "";
             $format = "";
             $this->getFileExtension($file->name, $extension, $format);
             $file->extension = $extension;
             $fileformat = FileFormat::model()->findByAttributes(array('name' => $format));
             if ($fileformat != null) {
                 $file->format_id = $fileformat->id;
             }
             $file->type_id = 1;
             $file->date_stamp = $stamp;
             if (!$file->save()) {
                 $model->addError('error', "Files are not saved correctly");
                 return false;
                 //how to
                 //                    var_dump($file->name);
             } else {
                 $this->setAutoFileAttributes($file);
             }
         }
     }
     return true;
 }
 public function size($pathfile)
 {
     $size = 0;
     $filelist = @ftp_rawlist($this->link, $pathfile);
     if ($filelist) {
         foreach ($filelist as $file) {
             $fileinfo = preg_split('#\\s+#', $file, null, PREG_SPLIT_NO_EMPTY);
             $size += $fileinfo[4];
         }
     }
     return $size > 0 ? $size : 0;
 }
Beispiel #15
0
 function ls($dir)
 {
     $f = empty($this->conf['ls_flags']) ? '' : $this->conf['ls_flags'] . ' ';
     if (isset($this->conf['space_in_filename_workaround']) && $this->conf['space_in_filename_workaround']) {
         $pwd = @ftp_pwd($this->cid);
         @ftp_chdir($this->cid, $dir);
         $list = @ftp_rawlist($this->cid, $f . '.');
         @ftp_chdir($this->cid, $pwd);
     } else {
         $list = ftp_rawlist($this->cid, $f . $dir);
     }
     return $list;
 }
Beispiel #16
0
/**
 * This function returns the list of files, fsizes and folders (array(files => ..., dirs => ..., fsizes => ...))
 *
 * @param string $dir
 * @param bool $nocache
 * @return array/bool
 */
function d_ftplist($dir,$nocache=false)
{
	static $cache=array();
	if($nocache==='flush') { $cache=array(); return true;}
	$dir = abs_path($dir,false);
	if(!empty($cache[$dir]) && !$nocache) return $cache[$dir];
	
	if(!$f = d_ftpchdir($dir)) return d_error('Cannot change directory to "'.$dir.'".');
	if(($res = ftp_rawlist(FTP_LINK,''))===false) return d_error('Could not get raw list.');
	
	//echo 'FTP in: '.$dir."\n";
	
	$dirs=$files=$fsizes=$rights=array();
	
	foreach($res as $v)
	{
		$p = split("[ ]+",$v,9);
		
		//echo '<pre>',var_dump($p),'</pre>';
		
		switch($v[0])
		{
		case 'd':
			if($p[8]!='.' && $p[8]!='..')
			{
				$dirs[]=$dir.'/'.$p[8];
				$fsizes[$dir.'/'.$p[8]]=$p[4];
				$rights[$dir.'/'.$p[8]]=$p[0];
			}
			break;
		case 'l': break; // it's a link, actually, don't know what to do
		case '-': // file
			$files[]=$dir.'/'.$p[8];
			$fsizes[$dir.'/'.$p[8]]=$p[4];
			$rights[$dir.'/'.$p[8]]=$p[0];
			break;
		case '+':
			$eplf=explode(",",implode(" ",$p),5);
			if($eplf[2] == "r")
			{
				$files[]=$dir.'/'.trim($eplf[4]);
				$fsizes[$dir.'/'.trim($eplf[4])]=substr($eplf[3],1);
			}else if($eplf[2] == "/") $dirs[]=$dir.'/'.trim($eplf[3]);
			break;
		}
	}
	
	//print_r($rights);
	
	return ($cache[$dir]=array('files'=>$files,'dirs'=>$dirs,'fsizes'=>$fsizes,'rights'=>$rights));
}
Beispiel #17
0
function ftp_rmfiles($ftp_stream, $directory, $nodel = "", $nodelpict = "")
{
    if (!is_resource($ftp_stream) || get_resource_type($ftp_stream) !== 'FTP Buffer') {
        return false;
    }
    ftp_pasv($ftp_stream, true);
    $i = 0;
    $files = array();
    $statusnext = false;
    $statusprev = false;
    $currentfolder = $directory;
    $list = ftp_rawlist($ftp_stream, $directory, true);
    foreach ($list as $current) {
        if (empty($current)) {
            if ($statusprev == true) {
                $statusprev = false;
                continue;
            }
            $statusnext = true;
            continue;
        }
        if ($statusnext === true) {
            $currentfolder = substr($current, 0, -1);
            $statusnext = false;
            $statusprev = true;
            continue;
        }
        $split = preg_split('[ ]', $current, 9, PREG_SPLIT_NO_EMPTY);
        $entry = $split[8];
        $isdir = $split[0][0] === 'd' ? true : false;
        if ($entry === '.' || $entry === '..') {
            continue;
        }
        if ($isdir !== true) {
            $files[] = $currentfolder . '/' . $entry;
        }
    }
    foreach ($files as $file) {
        //HUOM: Kuvia joiden nimessä on stringi "eipoisteta" ei poisteta
        if (stripos($file, "eipoisteta") === FALSE) {
            if ($nodelpict != '') {
                if (strpos($file, $nodelpict) === FALSE) {
                    ftp_delete($ftp_stream, $file);
                }
            } else {
                ftp_delete($ftp_stream, $file);
            }
        }
    }
}
Beispiel #18
0
 /**
  * Instantiate
  *
  * @param string $dir The full path
  * @param Centurion_Ftp $ftp The FTP connection
  */
 public function __construct($dir, $ftp)
 {
     $this->_dir = $dir;
     $this->_filter = $filter;
     $this->_ftp = $ftp;
     $lines = @ftp_rawlist($this->_ftp->getConnection(), $dir);
     foreach ($lines as $line) {
         preg_match('/^([\\-dl])([rwx\\-]+)\\s+(\\d+)\\s+(\\w+)\\s+(\\w+)\\s+(\\d+)\\s+(\\w+\\s+\\d+\\s+[\\d\\:]+)\\s+(.*)$/', $line, $matches);
         list($trash, $type, $permissions, $unknown, $owner, $group, $bytes, $date, $name) = $matches;
         if ($type != 'l') {
             $this->_data[] = array('type' => $type, 'permissions' => $permissions, 'bytes' => $bytes, 'name' => $name);
         }
     }
     $this->_count = count($this->_data);
 }
function pb_backupbuddy_ftp_listDetailed($resource, $directory = '.')
{
    if (is_array($children = @ftp_rawlist($resource, $directory))) {
        $items = array();
        foreach ($children as $child) {
            $chunks = preg_split("/\\s+/", $child);
            list($item['rights'], $item['number'], $item['user'], $item['group'], $item['size'], $item['month'], $item['day'], $item['time']) = $chunks;
            $item['type'] = $chunks[0][0] === 'd' ? 'directory' : 'file';
            array_splice($chunks, 0, 8);
            $items[implode(" ", $chunks)] = $item;
        }
        return $items;
    }
    return false;
}
Beispiel #20
0
function is_htpasswd($ftp_handle, $dir)
{
    $is_htpasswd_dir = false;
    $file_list = @ftp_rawlist($ftp_handle, $dir);
    if (!empty($file_list)) {
        foreach ($file_list as $file_single) {
            // Разбиваем строку по пробельным символам
            list($acc, $bloks, $group, $user, $size, $month, $day, $year, $file) = preg_split("/[\\s]+/", $file_single);
            if ($file == ".htpasswd") {
                $is_htpasswd_dir = true;
            }
        }
    }
    return $is_htpasswd_dir;
}
function JSX_PHP_FTP_raw_list($p_conn_id, $p_aConnData, $p_aPathData, $p_files)
{
    // Limiter counters.
    global $g_iMaxCounter;
    global $g_iMaxLimits;
    $g_iMaxCounter++;
    if ($g_iMaxCounter > $g_iMaxLimits) {
        return $p_files;
    }
    // Init.
    $folder = $p_aPathData['startdir'];
    $suffix = $p_aPathData['suffix'];
    $g_levello = $p_aPathData['levello'];
    $suffixes = explode(",", $suffix);
    $list = ftp_rawlist($p_conn_id, $folder);
    $anzlist = count($list);
    // Loop scanning.
    $i = 0;
    while ($i < $anzlist) {
        $split = preg_split("/[\\s]+/", $list[$i], 9, PREG_SPLIT_NO_EMPTY);
        $itemname = $split[8];
        $endung = strtolower(substr(strrchr($itemname, "."), 1));
        $path = "{$folder}/{$itemname}";
        if (substr($list[$i], 0, 1) === "d" and substr($itemname, 0, 1) != ".") {
            $p_aPathData['startdir'] = $path;
            $l_item = array();
            $l_item['type'] = "dir";
            $l_item['name'] = $path;
            $l_item['levl'] = $g_levello;
            array_push($p_files, $l_item);
            $g_levello++;
            $p_aPathData['levello'] = $g_levello;
            $p_files = JSX_PHP_FTP_raw_list($p_conn_id, $p_aConnData, $p_aPathData, $p_files);
            $g_levello--;
            $p_aPathData['levello'] = $g_levello;
        } else {
            $l_item = array();
            $l_item['type'] = "file";
            $l_item['name'] = $path;
            $l_item['levl'] = $g_levello;
            array_push($p_files, $l_item);
        }
        $i++;
    }
    // Return value.
    return $p_files;
}
Beispiel #22
0
 public function image_dir_scan($dir, $basedir)
 {
     $data = array();
     $dir = $basedir . $dir;
     $files = ftp_rawlist($this->link, $dir);
     foreach ($files as $v) {
         $file = ltrim(strrchr($v, ' '), ' ');
         $path = "{$dir}/{$file}";
         if (preg_match('/^-/', $v)) {
             if (preg_match('/^[a-zA-z0-9]+\\.(gif|png|jpg|jpeg)$/', $file)) {
                 //遍历目录设置
                 array_push($data, array(str_replace($basedir, '', $path), ftp_size($this->link, $path)));
             }
         }
     }
     return $data;
 }
Beispiel #23
0
function recursive_delete($ftp, $path)
{
    $files = ftp_rawlist($ftp, $path);
    foreach ($files as $file) {
        $i = explode(' ', $file);
        $filename = $i[count($i) - 1];
        if (strpos($file, '<DIR>') !== false) {
            recursive_delete($ftp, $path . '/' . $filename);
        } else {
            if (!ftp_delete($ftp, $path . '/' . $filename)) {
                return false;
            }
        }
    }
    if (!ftp_rmdir($ftp, $path)) {
        return false;
    }
    return true;
}
Beispiel #24
0
 /**
  * Delete the provided directory and all its contents from the FTP-server.
  * Modified from http://www.php.net/ftp_rmdir
  *
  * @param string $dir
  * @return boolean
  */
 protected function rmdirRecursive($dir)
 {
     $list = ftp_nlist($this->_conn, $dir);
     if (empty($list)) {
         $list = $this->rawListToNlist(ftp_rawlist($this->_conn, $dir), $dir . (substr($dir, strlen($dir) - 1, 1) == "/" ? "" : "/"));
     }
     if ($list[0] != $dir) {
         $dir .= substr($dir, strlen($dir) - 1, 1) == "/" ? "" : "/";
         foreach ($list as $item) {
             if ($item != $dir . ".." && $item != $dir . ".") {
                 $r = $this->rmdirRecursive($dir . $item);
                 if ($r === false) {
                     return false;
                 }
             }
         }
         return $this->rmdir($dir) ? true : false;
     } else {
         return $this->rm($dir) ? true : false;
     }
 }
Beispiel #25
0
function ftpGetList($ftpConn, $directory = '.')
{
    $simpleList = $detailedList = array();
    // If we have a FTP rawlist to work with
    if (is_array($rows = @ftp_rawlist($ftpConn, $directory))) {
        foreach ($rows as $row) {
            // Split row up by spaces and set keys on $item array
            $chunks = preg_split("/\\s+/", $row);
            list($item['rights'], $item['number'], $item['user'], $item['group'], $item['size'], $item['month'], $item['day'], $item['time']) = $chunks;
            // Also set if this is a dir or file
            $item['type'] = $chunks[0][0] === 'd' ? 'directory' : 'file';
            // Splice the array and finally work out $simpleList and $detailedList
            array_splice($chunks, 0, 8);
            $detailedList[implode(" ", $chunks)] = $item;
            $simpleList[] = implode(" ", $chunks);
        }
        // Return simple array list and detailed items list also
        return array('simpleList' => $simpleList, 'detailedList' => $detailedList);
    }
    return false;
}
 /**
  * Opens the strem
  *
  * @param String $path Maybe in the form "ajxp.ftp://repositoryId/pathToFile" 
  * @param String $mode
  * @param unknown_type $options
  * @param unknown_type $opened_path
  * @return unknown
  */
 function stream_open($path, $mode, $options, &$opened_path)
 {
     $url = parse_url($path);
     $repoId = $url["host"];
     $repoObject = ConfService::getRepositoryById($repoId);
     if (!isset($repoObject)) {
         return false;
     }
     $this->repository = $repoObject;
     $this->user = $this->getUserName($repoObject);
     $this->password = $this->getPassword($repoObject);
     $res = $this->initRepository();
     $this->path = $this->secureFtpPath($this->path . "/" . $url["path"]);
     if ($mode == "r") {
         if ($contents = @ftp_rawlist($this->connect, $this->path) !== FALSE) {
             $this->cacheRHandler = tmpfile();
             @ftp_fget($this->connect, $this->cacheRHandler, $this->path, FTP_BINARY, 0);
             rewind($this->cacheRHandler);
         }
     }
     return true;
 }
Beispiel #27
0
/**
* Check if Attachment exist
*/
function attachment_exists($filename)
{
    global $upload_dir, $config;
    $filename = basename($filename);
    if (!intval($config['allow_ftp_upload'])) {
        if (!@file_exists(@amod_realpath($upload_dir . '/' . $filename))) {
            return false;
        } else {
            return true;
        }
    } else {
        $found = false;
        $conn_id = attach_init_ftp();
        $file_listing = array();
        $file_listing = @ftp_rawlist($conn_id, $filename);
        for ($i = 0, $size = sizeof($file_listing); $i < $size; $i++) {
            if (ereg("([-d])[rwxst-]{9}.* ([0-9]*) ([a-zA-Z]+[0-9: ]*[0-9]) ([0-9]{2}:[0-9]{2}) (.+)", $file_listing[$i], $regs)) {
                if ($regs[1] == 'd') {
                    $dirinfo[0] = 1;
                    // Directory == 1
                }
                $dirinfo[1] = $regs[2];
                // Size
                $dirinfo[2] = $regs[3];
                // Date
                $dirinfo[3] = $regs[4];
                // Filename
                $dirinfo[4] = $regs[5];
                // Time
            }
            if ($dirinfo[0] != 1 && $dirinfo[4] == $filename) {
                $found = true;
            }
        }
        @ftp_quit($conn_id);
        return $found;
    }
}
Beispiel #28
0
function listPfiles($datasrc, $filter = "")
{
    $con = ftp_connect($datasrc->host) or die("Couldn't connect to {$datasrc->host}");
    if (!ftp_login($con, $datasrc->user, $datasrc->pwd)) {
        trigger_error("ftp login to {$datasrc->host} failed.");
        $pfileTree = 0;
    } else {
        $rawFiles = ftp_rawlist($con, $datasrc->dataDir);
        foreach ($rawFiles as $raw) {
            //echo $raw;
            ereg("([-d])([rwxst-]{9}).* ([0-9]*) ([a-zA-Z]+[0-9: ]* [0-9]{2}:?[0-9]{2}) (.+)", $raw, $regs);
            $files[] = array("is_dir" => $regs[1] == "d" ? true : false, "mod" => $regs[2], "size" => $regs[3], "time" => $regs[4], "name" => $regs[5], "raw" => $regs[0]);
        }
        // Find all P-files
        foreach ($files as $f) {
            if (ereg("^P.*\\.7\$", basename($f["name"]))) {
                $pfiles[] = basename($f["name"]);
            }
        }
        if (count($pfiles) > 0) {
            // Now find the tree of files associated with each P-file
            foreach ($pfiles as $pfileNum => $pfile) {
                foreach ($files as $f) {
                    if (ereg(".*" . $pfile . ".*", basename($f["name"]))) {
                        $pfileTree[$pfile]->name[] = $f["name"];
                        $pfileTree[$pfile]->size[] = $f["size"];
                        $pfileTree[$pfile]->time[] = $f["time"];
                    }
                }
            }
        } else {
            $pfileTree = 0;
        }
    }
    ftp_quit($con);
    return $pfileTree;
}
Beispiel #29
0
function list_folder($ftp, $dir = '')
{
    echo "listing folder {$dir}\n";
    $records = ftp_rawlist($ftp, $dir);
    if (!$records) {
        return;
    }
    $arr = null;
    foreach ($records as $record) {
        if (!preg_match('/([d-])[rwx-]{9}.*\\s([^\\s]+)$/', $record, $arr)) {
            continue;
        }
        $isDir = $arr[1] == 'd';
        $recordName = $arr[2];
        if ($isDir) {
            if ($recordName == '.' || $recordName == '..') {
                continue;
            }
            list_folder($ftp, "{$dir}/{$recordName}");
            continue;
        }
        write_csv_line($recordName, "{$dir}/{$recordName}");
    }
}
Beispiel #30
0
 private function deleteRecursive($path)
 {
     $handle = $this->fileSystem->getConnection();
     $files = array();
     $dirs = array();
     $lines = ftp_rawlist($handle, $path);
     foreach ($lines as $line) {
         $matches = null;
         $unixRe = '/^([\\-ld])((?:[\\-r][\\-w][\\-xs]){3})\\s+(\\d+)\\s+(\\w+)\\s+([\\-\\w]+)\\s+(\\d+)\\s+(\\w+\\s+\\d+\\s+[\\w:]+)\\s+(.+)$/';
         $windowsRe = "/^([^\\s]+\\s+[^\\s]+)\\s+((?:<DIR>|[\\w]+)?)\\s+(.+)\$/";
         if (preg_match($unixRe, $line, $matches)) {
             $filePath = MOXMAN_Util_PathUtils::combine($path, $matches[8]);
             if ($matches[1] === "d") {
                 $dirs[] = $filePath;
             } else {
                 $files[] = $filePath;
             }
         } else {
             if (preg_match($windowsRe, $line, $matches)) {
                 $filePath = MOXMAN_Util_PathUtils::combine($path, $matches[3]);
                 if ($matches[2] === "<DIR>") {
                     $dirs[] = $filePath;
                 } else {
                     $files[] = $filePath;
                 }
             } else {
                 // Unknown format
                 throw new MOXMAN_Exception("Unknown FTP list format: " . $line);
             }
         }
     }
     // Delete files in dir
     foreach ($files as $file) {
         ftp_delete($handle, $file);
     }
     // Delete directories in dir
     foreach ($dirs as $dir) {
         $this->deleteRecursive($dir);
     }
     // Delete dir
     ftp_rmdir($handle, $path);
 }