PluginProbe ʕ •ᴥ•ʔ
File Manager Pro – Filester / 1.6.1
File Manager Pro – Filester v1.6.1
2.1.2 2.1.1 trunk 1.6.1 1.7.6 1.8 1.8.1 1.8.2 1.8.3 1.8.4 1.8.5 1.8.6 1.8.7 1.8.8 1.8.9 1.9 2.0 2.0.1 2.0.2 2.1.0
filester / includes / File_manager / lib / php / elFinderVolumeFTP.class.php
filester / includes / File_manager / lib / php Last commit date
.tmp 5 years ago editors 5 years ago libs 5 years ago plugins 5 years ago resources 5 years ago MySQLStorage.sql 5 years ago autoload.php 5 years ago elFinder.class.php 5 years ago elFinderConnector.class.php 5 years ago elFinderFlysystemGoogleDriveNetmount.php 5 years ago elFinderPlugin.php 5 years ago elFinderSession.php 5 years ago elFinderSessionInterface.php 5 years ago elFinderVolumeBox.class.php 5 years ago elFinderVolumeDriver.class.php 5 years ago elFinderVolumeDropbox.class.php 5 years ago elFinderVolumeDropbox2.class.php 5 years ago elFinderVolumeFTP.class.php 5 years ago elFinderVolumeGoogleDrive.class.php 5 years ago elFinderVolumeGroup.class.php 5 years ago elFinderVolumeLocalFileSystem.class.php 5 years ago elFinderVolumeMySQL.class.php 5 years ago elFinderVolumeOneDrive.class.php 5 years ago elFinderVolumeTrash.class.php 5 years ago elFinderVolumeTrashMySQL.class.php 5 years ago index.php 5 years ago mime.types 5 years ago
elFinderVolumeFTP.class.php
1808 lines
1 <?php
2
3 /**
4 * Simple elFinder driver for FTP
5 *
6 * @author Dmitry (dio) Levashov
7 * @author Cem (discofever)
8 **/
9 class elFinderVolumeFTP extends elFinderVolumeDriver
10 {
11
12 /**
13 * Driver id
14 * Must be started from letter and contains [a-z0-9]
15 * Used as part of volume id
16 *
17 * @var string
18 **/
19 protected $driverId = 'f';
20
21 /**
22 * FTP Connection Instance
23 *
24 * @var resource a FTP stream
25 **/
26 protected $connect = null;
27
28 /**
29 * Directory for tmp files
30 * If not set driver will try to use tmbDir as tmpDir
31 *
32 * @var string
33 **/
34 protected $tmpPath = '';
35
36 /**
37 * Last FTP error message
38 *
39 * @var string
40 **/
41 protected $ftpError = '';
42
43 /**
44 * FTP server output list as ftp on linux
45 *
46 * @var bool
47 **/
48 protected $ftpOsUnix;
49
50 /**
51 * FTP LIST command option
52 *
53 * @var string
54 */
55 protected $ftpListOption = '-al';
56
57
58 /**
59 * Is connected server Pure FTPd?
60 *
61 * @var bool
62 */
63 protected $isPureFtpd = false;
64
65 /**
66 * Is connected server with FTPS?
67 *
68 * @var bool
69 */
70 protected $isFTPS = false;
71
72 /**
73 * Tmp folder path
74 *
75 * @var string
76 **/
77 protected $tmp = '';
78
79 /**
80 * FTP command `MLST` support
81 *
82 * @var bool
83 */
84 private $MLSTsupprt = false;
85
86 /**
87 * Calling cacheDir() target path with non-MLST
88 *
89 * @var string
90 */
91 private $cacheDirTarget = '';
92
93 /**
94 * Constructor
95 * Extend options with required fields
96 *
97 * @author Dmitry (dio) Levashov
98 * @author Cem (DiscoFever)
99 */
100 public function __construct()
101 {
102 $opts = array(
103 'host' => 'localhost',
104 'user' => '',
105 'pass' => '',
106 'port' => 21,
107 'mode' => 'passive',
108 'ssl' => false,
109 'path' => '/',
110 'timeout' => 20,
111 'owner' => true,
112 'tmbPath' => '',
113 'tmpPath' => '',
114 'separator' => '/',
115 'checkSubfolders' => -1,
116 'dirMode' => 0755,
117 'fileMode' => 0644,
118 'rootCssClass' => 'elfinder-navbar-root-ftp',
119 'ftpListOption' => '-al',
120 );
121 $this->options = array_merge($this->options, $opts);
122 $this->options['mimeDetect'] = 'internal';
123 }
124
125 /**
126 * Prepare
127 * Call from elFinder::netmout() before volume->mount()
128 *
129 * @param $options
130 *
131 * @return array volume root options
132 * @author Naoki Sawada
133 */
134 public function netmountPrepare($options)
135 {
136 if (!empty($_REQUEST['encoding']) && iconv('UTF-8', $_REQUEST['encoding'], '') !== false) {
137 $options['encoding'] = $_REQUEST['encoding'];
138 if (!empty($_REQUEST['locale']) && setlocale(LC_ALL, $_REQUEST['locale'])) {
139 setlocale(LC_ALL, elFinder::$locale);
140 $options['locale'] = $_REQUEST['locale'];
141 }
142 }
143 if (!empty($_REQUEST['FTPS'])) {
144 $options['ssl'] = true;
145 }
146 $options['statOwner'] = true;
147 $options['allowChmodReadOnly'] = true;
148 $options['acceptedName'] = '#^[^/\\?*:|"<>]*[^./\\?*:|"<>]$#';
149 return $options;
150 }
151
152 /*********************************************************************/
153 /* INIT AND CONFIGURE */
154 /*********************************************************************/
155
156 /**
157 * Prepare FTP connection
158 * Connect to remote server and check if credentials are correct, if so, store the connection id in $ftp_conn
159 *
160 * @return bool
161 * @author Dmitry (dio) Levashov
162 * @author Cem (DiscoFever)
163 **/
164 protected function init()
165 {
166 if (!$this->options['host']
167 || !$this->options['port']) {
168 return $this->setError('Required options undefined.');
169 }
170
171 if (!$this->options['user']) {
172 $this->options['user'] = 'anonymous';
173 $this->options['pass'] = '';
174 }
175 if (!$this->options['path']) {
176 $this->options['path'] = '/';
177 }
178
179 // make ney mount key
180 $this->netMountKey = md5(join('-', array('ftp', $this->options['host'], $this->options['port'], $this->options['path'], $this->options['user'])));
181
182 if (!function_exists('ftp_connect')) {
183 return $this->setError('FTP extension not loaded.');
184 }
185
186 // remove protocol from host
187 $scheme = parse_url($this->options['host'], PHP_URL_SCHEME);
188
189 if ($scheme) {
190 $this->options['host'] = substr($this->options['host'], strlen($scheme) + 3);
191 }
192
193 // normalize root path
194 $this->root = $this->options['path'] = $this->_normpath($this->options['path']);
195
196 if (empty($this->options['alias'])) {
197 $this->options['alias'] = $this->options['user'] . '@' . $this->options['host'];
198 if (!empty($this->options['netkey'])) {
199 elFinder::$instance->updateNetVolumeOption($this->options['netkey'], 'alias', $this->options['alias']);
200 }
201 }
202
203 $this->rootName = $this->options['alias'];
204 $this->options['separator'] = '/';
205
206 if (is_null($this->options['syncChkAsTs'])) {
207 $this->options['syncChkAsTs'] = true;
208 }
209
210 if (isset($this->options['ftpListOption'])) {
211 $this->ftpListOption = $this->options['ftpListOption'];
212 }
213
214 return $this->needOnline? $this->connect() : true;
215
216 }
217
218
219 /**
220 * Configure after successfull mount.
221 *
222 * @return void
223 * @throws elFinderAbortException
224 * @author Dmitry (dio) Levashov
225 */
226 protected function configure()
227 {
228 parent::configure();
229
230 if (!empty($this->options['tmpPath'])) {
231 if ((is_dir($this->options['tmpPath']) || mkdir($this->options['tmpPath'], 0755, true)) && is_writable($this->options['tmpPath'])) {
232 $this->tmp = $this->options['tmpPath'];
233 }
234 }
235 if (!$this->tmp && ($tmp = elFinder::getStaticVar('commonTempPath'))) {
236 $this->tmp = $tmp;
237 }
238
239 // fallback of $this->tmp
240 if (!$this->tmp && $this->tmbPathWritable) {
241 $this->tmp = $this->tmbPath;
242 }
243
244 if (!$this->tmp) {
245 $this->disabled[] = 'mkfile';
246 $this->disabled[] = 'paste';
247 $this->disabled[] = 'duplicate';
248 $this->disabled[] = 'upload';
249 $this->disabled[] = 'edit';
250 $this->disabled[] = 'archive';
251 $this->disabled[] = 'extract';
252 }
253
254 // echo $this->tmp;
255
256 }
257
258 /**
259 * Connect to ftp server
260 *
261 * @return bool
262 * @author Dmitry (dio) Levashov
263 **/
264 protected function connect()
265 {
266 $withSSL = empty($this->options['ssl']) ? '' : ' with SSL';
267 if ($withSSL) {
268 if (!function_exists('ftp_ssl_connect') || !($this->connect = ftp_ssl_connect($this->options['host'], $this->options['port'], $this->options['timeout']))) {
269 return $this->setError('Unable to connect to FTP server ' . $this->options['host'] . $withSSL);
270 }
271 $this->isFTPS = true;
272 } else {
273 if (!($this->connect = ftp_connect($this->options['host'], $this->options['port'], $this->options['timeout']))) {
274 return $this->setError('Unable to connect to FTP server ' . $this->options['host']);
275 }
276 }
277 if (!ftp_login($this->connect, $this->options['user'], $this->options['pass'])) {
278 $this->umount();
279 return $this->setError('Unable to login into ' . $this->options['host'] . $withSSL);
280 }
281
282 // try switch utf8 mode
283 if ($this->encoding) {
284 ftp_raw($this->connect, 'OPTS UTF8 OFF');
285 } else {
286 ftp_raw($this->connect, 'OPTS UTF8 ON');
287 }
288
289 $help = ftp_raw($this->connect, 'HELP');
290 $this->isPureFtpd = stripos(implode(' ', $help), 'Pure-FTPd') !== false;
291
292 if (!$this->isPureFtpd) {
293 // switch off extended passive mode - may be usefull for some servers
294 // this command, for pure-ftpd, doesn't work and takes a timeout in some pure-ftpd versions
295 ftp_raw($this->connect, 'epsv4 off');
296 }
297 // enter passive mode if required
298 $pasv = ($this->options['mode'] == 'passive');
299 if (!ftp_pasv($this->connect, $pasv)) {
300 if ($pasv) {
301 $this->options['mode'] = 'active';
302 }
303 }
304
305 // enter root folder
306 if (!ftp_chdir($this->connect, $this->root)
307 || $this->root != ftp_pwd($this->connect)) {
308 $this->umount();
309 return $this->setError('Unable to open root folder.');
310 }
311
312 // check for MLST support
313 $features = ftp_raw($this->connect, 'FEAT');
314 if (!is_array($features)) {
315 $this->umount();
316 return $this->setError('Server does not support command FEAT.');
317 }
318
319 foreach ($features as $feat) {
320 if (strpos(trim($feat), 'MLST') === 0) {
321 $this->MLSTsupprt = true;
322 break;
323 }
324 }
325
326 return true;
327 }
328
329 /**
330 * Call ftp_rawlist with option prefix
331 *
332 * @param string $path
333 *
334 * @return array
335 */
336 protected function ftpRawList($path)
337 {
338 if ($this->isPureFtpd) {
339 $path = str_replace(' ', '\ ', $path);
340 }
341 if ($this->ftpListOption) {
342 $path = $this->ftpListOption . ' ' . $path;
343 }
344 $res = ftp_rawlist($this->connect, $path);
345 if ($res === false) {
346 $res = array();
347 }
348 return $res;
349 }
350
351 /*********************************************************************/
352 /* FS API */
353 /*********************************************************************/
354
355 /**
356 * Close opened connection
357 *
358 * @return void
359 * @author Dmitry (dio) Levashov
360 **/
361 public function umount()
362 {
363 $this->connect && ftp_close($this->connect);
364 }
365
366
367 /**
368 * Parse line from ftp_rawlist() output and return file stat (array)
369 *
370 * @param string $raw line from ftp_rawlist() output
371 * @param $base
372 * @param bool $nameOnly
373 *
374 * @return array
375 * @author Dmitry Levashov
376 */
377 protected function parseRaw($raw, $base, $nameOnly = false)
378 {
379 static $now;
380 static $lastyear;
381
382 if (!$now) {
383 $now = time();
384 $lastyear = date('Y') - 1;
385 }
386
387 $info = preg_split("/\s+/", $raw, 9);
388 $stat = array();
389
390 if (!isset($this->ftpOsUnix)) {
391 $this->ftpOsUnix = !preg_match('/\d/', substr($info[0], 0, 1));
392 }
393 if (!$this->ftpOsUnix) {
394 $info = $this->normalizeRawWindows($raw);
395 }
396
397 if (count($info) < 9 || $info[8] == '.' || $info[8] == '..') {
398 return false;
399 }
400
401 $name = $info[8];
402
403 if (preg_match('|(.+)\-\>(.+)|', $name, $m)) {
404 $name = trim($m[1]);
405 // check recursive processing
406 if ($this->cacheDirTarget && $this->_joinPath($base, $name) !== $this->cacheDirTarget) {
407 return array();
408 }
409 if (!$nameOnly) {
410 $target = trim($m[2]);
411 if (substr($target, 0, 1) !== $this->separator) {
412 $target = $this->getFullPath($target, $base);
413 }
414 $target = $this->_normpath($target);
415 $stat['name'] = $name;
416 $stat['target'] = $target;
417 return $stat;
418 }
419 }
420
421 if ($nameOnly) {
422 return array('name' => $name);
423 }
424
425 if (is_numeric($info[5]) && !$info[6] && !$info[7]) {
426 // by normalizeRawWindows()
427 $stat['ts'] = $info[5];
428 } else {
429 $stat['ts'] = strtotime($info[5] . ' ' . $info[6] . ' ' . $info[7]);
430 if ($stat['ts'] && $stat['ts'] > $now && strpos($info[7], ':') !== false) {
431 $stat['ts'] = strtotime($info[5] . ' ' . $info[6] . ' ' . $lastyear . ' ' . $info[7]);
432 }
433 if (empty($stat['ts'])) {
434 $stat['ts'] = strtotime($info[6] . ' ' . $info[5] . ' ' . $info[7]);
435 if ($stat['ts'] && $stat['ts'] > $now && strpos($info[7], ':') !== false) {
436 $stat['ts'] = strtotime($info[6] . ' ' . $info[5] . ' ' . $lastyear . ' ' . $info[7]);
437 }
438 }
439 }
440
441 if ($this->options['statOwner']) {
442 $stat['owner'] = $info[2];
443 $stat['group'] = $info[3];
444 $stat['perm'] = substr($info[0], 1);
445 //
446 // if not exists owner in LS ftp ==> isowner = true
447 // if is defined as option : 'owner' => true isowner = true
448 //
449 // if exist owner in LS ftp and 'owner' => False isowner = result of owner(file) == user(logged with ftp)
450 //
451 $stat['isowner'] = isset($stat['owner']) ? ($this->options['owner'] ? true : ($stat['owner'] == $this->options['user'])) : true;
452 }
453
454 $owner_computed = isset($stat['isowner']) ? $stat['isowner'] : $this->options['owner'];
455 $perm = $this->parsePermissions($info[0], $owner_computed);
456 $stat['name'] = $name;
457 $stat['mime'] = substr(strtolower($info[0]), 0, 1) == 'd' ? 'directory' : $this->mimetype($stat['name'], true);
458 $stat['size'] = $stat['mime'] == 'directory' ? 0 : $info[4];
459 $stat['read'] = $perm['read'];
460 $stat['write'] = $perm['write'];
461
462 return $stat;
463 }
464
465 /**
466 * Normalize MS-DOS style FTP LIST Raw line
467 *
468 * @param string $raw line from FTP LIST (MS-DOS style)
469 *
470 * @return array
471 * @author Naoki Sawada
472 **/
473 protected function normalizeRawWindows($raw)
474 {
475 $info = array_pad(array(), 9, '');
476 $item = preg_replace('#\s+#', ' ', trim($raw), 3);
477 list($date, $time, $size, $name) = explode(' ', $item, 4);
478 $format = strlen($date) === 8 ? 'm-d-yH:iA' : 'Y-m-dH:i';
479 $dateObj = DateTime::createFromFormat($format, $date . $time);
480 $info[5] = strtotime($dateObj->format('Y-m-d H:i'));
481 $info[8] = $name;
482 if ($size === '<DIR>') {
483 $info[4] = 0;
484 $info[0] = 'drwxr-xr-x';
485 } else {
486 $info[4] = (int)$size;
487 $info[0] = '-rw-r--r--';
488 }
489 return $info;
490 }
491
492 /**
493 * Parse permissions string. Return array(read => true/false, write => true/false)
494 *
495 * @param string $perm permissions string 'rwx' + 'rwx' + 'rwx'
496 * ^ ^ ^
497 * | | +-> others
498 * | +---------> group
499 * +-----------------> owner
500 * The isowner parameter is computed by the caller.
501 * If the owner parameter in the options is true, the user is the actual owner of all objects even if che user used in the ftp Login
502 * is different from the file owner id.
503 * If the owner parameter is false to understand if the user is the file owner we compare the ftp user with the file owner id.
504 * @param Boolean $isowner . Tell if the current user is the owner of the object.
505 *
506 * @return array
507 * @author Dmitry (dio) Levashov
508 * @author Ugo Vierucci
509 */
510 protected function parsePermissions($perm, $isowner = true)
511 {
512 $res = array();
513 $parts = array();
514 for ($i = 0, $l = strlen($perm); $i < $l; $i++) {
515 $parts[] = substr($perm, $i, 1);
516 }
517
518 $read = ($isowner && $parts[1] == 'r') || $parts[4] == 'r' || $parts[7] == 'r';
519
520 return array(
521 'read' => $parts[0] == 'd' ? $read && (($isowner && $parts[3] == 'x') || $parts[6] == 'x' || $parts[9] == 'x') : $read,
522 'write' => ($isowner && $parts[2] == 'w') || $parts[5] == 'w' || $parts[8] == 'w'
523 );
524 }
525
526 /**
527 * Cache dir contents
528 *
529 * @param string $path dir path
530 *
531 * @return void
532 * @author Dmitry Levashov
533 **/
534 protected function cacheDir($path)
535 {
536 $this->dirsCache[$path] = array();
537 $hasDir = false;
538
539 $list = array();
540 $encPath = $this->convEncIn($path);
541 foreach ($this->ftpRawList($encPath) as $raw) {
542 if (($stat = $this->parseRaw($raw, $encPath))) {
543 $list[] = $stat;
544 }
545 }
546 $list = $this->convEncOut($list);
547 $prefix = ($path === $this->separator) ? $this->separator : $path . $this->separator;
548 $targets = array();
549 foreach ($list as $stat) {
550 $p = $prefix . $stat['name'];
551 if (isset($stat['target'])) {
552 // stat later
553 $targets[$stat['name']] = $stat['target'];
554 } else {
555 $stat = $this->updateCache($p, $stat);
556 if (empty($stat['hidden'])) {
557 if (!$hasDir && $stat['mime'] === 'directory') {
558 $hasDir = true;
559 }
560 $this->dirsCache[$path][] = $p;
561 }
562 }
563 }
564 // stat link targets
565 foreach ($targets as $name => $target) {
566 $stat = array();
567 $stat['name'] = $name;
568 $p = $prefix . $name;
569 $cacheDirTarget = $this->cacheDirTarget;
570 $this->cacheDirTarget = $this->convEncIn($target, true);
571 if ($tstat = $this->stat($target)) {
572 $stat['size'] = $tstat['size'];
573 $stat['alias'] = $target;
574 $stat['thash'] = $tstat['hash'];
575 $stat['mime'] = $tstat['mime'];
576 $stat['read'] = $tstat['read'];
577 $stat['write'] = $tstat['write'];
578
579 if (isset($tstat['ts'])) {
580 $stat['ts'] = $tstat['ts'];
581 }
582 if (isset($tstat['owner'])) {
583 $stat['owner'] = $tstat['owner'];
584 }
585 if (isset($tstat['group'])) {
586 $stat['group'] = $tstat['group'];
587 }
588 if (isset($tstat['perm'])) {
589 $stat['perm'] = $tstat['perm'];
590 }
591 if (isset($tstat['isowner'])) {
592 $stat['isowner'] = $tstat['isowner'];
593 }
594 } else {
595
596 $stat['mime'] = 'symlink-broken';
597 $stat['read'] = false;
598 $stat['write'] = false;
599 $stat['size'] = 0;
600
601 }
602 $this->cacheDirTarget = $cacheDirTarget;
603 $stat = $this->updateCache($p, $stat);
604 if (empty($stat['hidden'])) {
605 if (!$hasDir && $stat['mime'] === 'directory') {
606 $hasDir = true;
607 }
608 $this->dirsCache[$path][] = $p;
609 }
610 }
611
612 if (isset($this->sessionCache['subdirs'])) {
613 $this->sessionCache['subdirs'][$path] = $hasDir;
614 }
615 }
616
617 /**
618 * Return ftp transfer mode for file
619 *
620 * @param string $path file path
621 *
622 * @return string
623 * @author Dmitry (dio) Levashov
624 **/
625 protected function ftpMode($path)
626 {
627 return strpos($this->mimetype($path), 'text/') === 0 ? FTP_ASCII : FTP_BINARY;
628 }
629
630 /*********************** paths/urls *************************/
631
632 /**
633 * Return parent directory path
634 *
635 * @param string $path file path
636 *
637 * @return string
638 * @author Naoki Sawada
639 **/
640 protected function _dirname($path)
641 {
642 $parts = explode($this->separator, trim($path, $this->separator));
643 array_pop($parts);
644 return $this->separator . join($this->separator, $parts);
645 }
646
647 /**
648 * Return file name
649 *
650 * @param string $path file path
651 *
652 * @return string
653 * @author Naoki Sawada
654 **/
655 protected function _basename($path)
656 {
657 $parts = explode($this->separator, trim($path, $this->separator));
658 return array_pop($parts);
659 }
660
661 /**
662 * Join dir name and file name and retur full path
663 *
664 * @param string $dir
665 * @param string $name
666 *
667 * @return string
668 * @author Dmitry (dio) Levashov
669 **/
670 protected function _joinPath($dir, $name)
671 {
672 return rtrim($dir, $this->separator) . $this->separator . $name;
673 }
674
675 /**
676 * Return normalized path, this works the same as os.path.normpath() in Python
677 *
678 * @param string $path path
679 *
680 * @return string
681 * @author Troex Nevelin
682 **/
683 protected function _normpath($path)
684 {
685 if (empty($path)) {
686 $path = '.';
687 }
688 // path must be start with /
689 $path = preg_replace('|^\.\/?|', $this->separator, $path);
690 $path = preg_replace('/^([^\/])/', "/$1", $path);
691
692 if ($path[0] === $this->separator) {
693 $initial_slashes = true;
694 } else {
695 $initial_slashes = false;
696 }
697
698 if (($initial_slashes)
699 && (strpos($path, '//') === 0)
700 && (strpos($path, '///') === false)) {
701 $initial_slashes = 2;
702 }
703
704 $initial_slashes = (int)$initial_slashes;
705
706 $comps = explode($this->separator, $path);
707 $new_comps = array();
708 foreach ($comps as $comp) {
709 if (in_array($comp, array('', '.'))) {
710 continue;
711 }
712
713 if (($comp != '..')
714 || (!$initial_slashes && !$new_comps)
715 || ($new_comps && (end($new_comps) == '..'))) {
716 array_push($new_comps, $comp);
717 } elseif ($new_comps) {
718 array_pop($new_comps);
719 }
720 }
721 $comps = $new_comps;
722 $path = implode($this->separator, $comps);
723 if ($initial_slashes) {
724 $path = str_repeat($this->separator, $initial_slashes) . $path;
725 }
726
727 return $path ? $path : '.';
728 }
729
730 /**
731 * Return file path related to root dir
732 *
733 * @param string $path file path
734 *
735 * @return string
736 * @author Dmitry (dio) Levashov
737 **/
738 protected function _relpath($path)
739 {
740 if ($path === $this->root) {
741 return '';
742 } else {
743 if (strpos($path, $this->root) === 0) {
744 return ltrim(substr($path, strlen($this->root)), $this->separator);
745 } else {
746 // for link
747 return $path;
748 }
749 }
750 }
751
752 /**
753 * Convert path related to root dir into real path
754 *
755 * @param string $path file path
756 *
757 * @return string
758 * @author Dmitry (dio) Levashov
759 **/
760 protected function _abspath($path)
761 {
762 if ($path === $this->separator) {
763 return $this->root;
764 } else {
765 if ($path[0] === $this->separator) {
766 // for link
767 return $path;
768 } else {
769 return $this->_joinPath($this->root, $path);
770 }
771 }
772 }
773
774 /**
775 * Return fake path started from root dir
776 *
777 * @param string $path file path
778 *
779 * @return string
780 * @author Dmitry (dio) Levashov
781 **/
782 protected function _path($path)
783 {
784 return $this->rootName . ($path == $this->root ? '' : $this->separator . $this->_relpath($path));
785 }
786
787 /**
788 * Return true if $path is children of $parent
789 *
790 * @param string $path path to check
791 * @param string $parent parent path
792 *
793 * @return bool
794 * @author Dmitry (dio) Levashov
795 **/
796 protected function _inpath($path, $parent)
797 {
798 return $path == $parent || strpos($path, rtrim($parent, $this->separator) . $this->separator) === 0;
799 }
800
801 /***************** file stat ********************/
802 /**
803 * Return stat for given path.
804 * Stat contains following fields:
805 * - (int) size file size in b. required
806 * - (int) ts file modification time in unix time. required
807 * - (string) mime mimetype. required for folders, others - optionally
808 * - (bool) read read permissions. required
809 * - (bool) write write permissions. required
810 * - (bool) locked is object locked. optionally
811 * - (bool) hidden is object hidden. optionally
812 * - (string) alias for symlinks - link target path relative to root path. optionally
813 * - (string) target for symlinks - link target path. optionally
814 * If file does not exists - returns empty array or false.
815 *
816 * @param string $path file path
817 *
818 * @return array|false
819 * @author Dmitry (dio) Levashov
820 **/
821 protected function _stat($path)
822 {
823 $outPath = $this->convEncOut($path);
824 if (isset($this->cache[$outPath])) {
825 return $this->convEncIn($this->cache[$outPath]);
826 } else {
827 $this->convEncIn();
828 }
829 if (!$this->MLSTsupprt) {
830 if ($path === $this->root) {
831 $res = array(
832 'name' => $this->root,
833 'mime' => 'directory',
834 'dirs' => -1
835 );
836 if ($this->needOnline && (($this->ARGS['cmd'] === 'open' && $this->ARGS['target'] === $this->encode($this->root)) || $this->isMyReload())) {
837 $check = array(
838 'ts' => true,
839 'dirs' => true,
840 );
841 $ts = 0;
842 foreach ($this->ftpRawList($path) as $str) {
843 $info = preg_split('/\s+/', $str, 9);
844 if ($info[8] === '.') {
845 $info[8] = 'root';
846 if ($stat = $this->parseRaw(join(' ', $info), $path)) {
847 unset($stat['name']);
848 $res = array_merge($res, $stat);
849 if ($res['ts']) {
850 $ts = 0;
851 unset($check['ts']);
852 }
853 }
854 }
855 if ($check && ($stat = $this->parseRaw($str, $path))) {
856 if (isset($stat['ts']) && !empty($stat['ts'])) {
857 $ts = max($ts, $stat['ts']);
858 }
859 if (isset($stat['dirs']) && $stat['mime'] === 'directory') {
860 $res['dirs'] = 1;
861 unset($stat['dirs']);
862 }
863 if (!$check) {
864 break;
865 }
866 }
867 }
868 if ($ts) {
869 $res['ts'] = $ts;
870 }
871 $this->cache[$outPath] = $res;
872 }
873 return $res;
874 }
875
876 $pPath = $this->_dirname($path);
877 if ($this->_inPath($pPath, $this->root)) {
878 $outPPpath = $this->convEncOut($pPath);
879 if (!isset($this->dirsCache[$outPPpath])) {
880 $parentSubdirs = null;
881 if (isset($this->sessionCache['subdirs']) && isset($this->sessionCache['subdirs'][$outPPpath])) {
882 $parentSubdirs = $this->sessionCache['subdirs'][$outPPpath];
883 }
884 $this->cacheDir($outPPpath);
885 if ($parentSubdirs) {
886 $this->sessionCache['subdirs'][$outPPpath] = $parentSubdirs;
887 }
888 }
889 }
890
891 $stat = $this->convEncIn(isset($this->cache[$outPath]) ? $this->cache[$outPath] : array());
892 if (!$this->mounted) {
893 // dispose incomplete cache made by calling `stat` by 'startPath' option
894 $this->cache = array();
895 }
896 return $stat;
897 }
898 $raw = ftp_raw($this->connect, 'MLST ' . $path);
899 if (is_array($raw) && count($raw) > 1 && substr(trim($raw[0]), 0, 1) == 2) {
900 $parts = explode(';', trim($raw[1]));
901 array_pop($parts);
902 $parts = array_map('strtolower', $parts);
903 $stat = array();
904 $mode = '';
905 foreach ($parts as $part) {
906
907 list($key, $val) = explode('=', $part, 2);
908
909 switch ($key) {
910 case 'type':
911 if (strpos($val, 'dir') !== false) {
912 $stat['mime'] = 'directory';
913 } else if (strpos($val, 'link') !== false) {
914 $stat['mime'] = 'symlink';
915 break(2);
916 } else {
917 $stat['mime'] = $this->mimetype($path);
918 }
919 break;
920
921 case 'size':
922 $stat['size'] = $val;
923 break;
924
925 case 'modify':
926 $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));
927 $stat['ts'] = $ts;
928 break;
929
930 case 'unix.mode':
931 $mode = strval($val);
932 break;
933
934 case 'unix.uid':
935 $stat['owner'] = $val;
936 break;
937
938 case 'unix.gid':
939 $stat['group'] = $val;
940 break;
941
942 case 'perm':
943 $val = strtolower($val);
944 $stat['read'] = (int)preg_match('/e|l|r/', $val);
945 $stat['write'] = (int)preg_match('/w|m|c/', $val);
946 if (!preg_match('/f|d/', $val)) {
947 $stat['locked'] = 1;
948 }
949 break;
950 }
951 }
952
953 if (empty($stat['mime'])) {
954 return array();
955 }
956
957 // do not use MLST to get stat of symlink
958 if ($stat['mime'] === 'symlink') {
959 $this->MLSTsupprt = false;
960 $res = $this->_stat($path);
961 $this->MLSTsupprt = true;
962 return $res;
963 }
964
965 if ($stat['mime'] === 'directory') {
966 $stat['size'] = 0;
967 }
968
969 if ($mode) {
970 $stat['perm'] = '';
971 if ($mode[0] === '0') {
972 $mode = substr($mode, 1);
973 }
974
975 $perm = array();
976 for ($i = 0; $i <= 2; $i++) {
977 $perm[$i] = array(false, false, false);
978 $n = isset($mode[$i]) ? $mode[$i] : 0;
979
980 if ($n - 4 >= 0) {
981 $perm[$i][0] = true;
982 $n = $n - 4;
983 $stat['perm'] .= 'r';
984 } else {
985 $stat['perm'] .= '-';
986 }
987
988 if ($n - 2 >= 0) {
989 $perm[$i][1] = true;
990 $n = $n - 2;
991 $stat['perm'] .= 'w';
992 } else {
993 $stat['perm'] .= '-';
994 }
995
996 if ($n - 1 == 0) {
997 $perm[$i][2] = true;
998 $stat['perm'] .= 'x';
999 } else {
1000 $stat['perm'] .= '-';
1001 }
1002 }
1003
1004 $stat['perm'] = trim($stat['perm']);
1005 //
1006 // if not exists owner in LS ftp ==> isowner = true
1007 // if is defined as option : 'owner' => true isowner = true
1008 //
1009 // if exist owner in LS ftp and 'owner' => False isowner = result of owner(file) == user(logged with ftp)
1010
1011 $owner_computed = isset($stat['owner']) ? ($this->options['owner'] ? true : ($stat['owner'] == $this->options['user'])) : true;
1012
1013 $read = ($owner_computed && $perm[0][0]) || $perm[1][0] || $perm[2][0];
1014
1015 $stat['read'] = $stat['mime'] == 'directory' ? $read && (($owner_computed && $perm[0][2]) || $perm[1][2] || $perm[2][2]) : $read;
1016 $stat['write'] = ($owner_computed && $perm[0][1]) || $perm[1][1] || $perm[2][1];
1017
1018 if ($this->options['statOwner']) {
1019 $stat['isowner'] = $owner_computed;
1020 } else {
1021 unset($stat['owner'], $stat['group'], $stat['perm']);
1022 }
1023 }
1024
1025 return $stat;
1026
1027 }
1028
1029 return array();
1030 }
1031
1032 /**
1033 * Return true if path is dir and has at least one childs directory
1034 *
1035 * @param string $path dir path
1036 *
1037 * @return bool
1038 * @author Dmitry (dio) Levashov
1039 **/
1040 protected function _subdirs($path)
1041 {
1042
1043 foreach ($this->ftpRawList($path) as $str) {
1044 $info = preg_split('/\s+/', $str, 9);
1045 if (!isset($this->ftpOsUnix)) {
1046 $this->ftpOsUnix = !preg_match('/\d/', substr($info[0], 0, 1));
1047 }
1048 if (!$this->ftpOsUnix) {
1049 $info = $this->normalizeRawWindows($str);
1050 }
1051 $name = isset($info[8]) ? trim($info[8]) : '';
1052 if ($name && $name !== '.' && $name !== '..' && substr(strtolower($info[0]), 0, 1) === 'd') {
1053 return true;
1054 }
1055 }
1056 return false;
1057 }
1058
1059 /**
1060 * Return object width and height
1061 * Ususaly used for images, but can be realize for video etc...
1062 *
1063 * @param string $path file path
1064 * @param string $mime file mime type
1065 *
1066 * @return string|false
1067 * @throws ImagickException
1068 * @throws elFinderAbortException
1069 * @author Dmitry (dio) Levashov
1070 */
1071 protected function _dimensions($path, $mime)
1072 {
1073 $ret = false;
1074 if ($imgsize = $this->getImageSize($path, $mime)) {
1075 $ret = array('dim' => $imgsize['dimensions']);
1076 if (!empty($imgsize['url'])) {
1077 $ret['url'] = $imgsize['url'];
1078 }
1079 }
1080 return $ret;
1081 }
1082
1083 /******************** file/dir content *********************/
1084
1085 /**
1086 * Return files list in directory.
1087 *
1088 * @param string $path dir path
1089 *
1090 * @return array
1091 * @author Dmitry (dio) Levashov
1092 * @author Cem (DiscoFever)
1093 **/
1094 protected function _scandir($path)
1095 {
1096 $files = array();
1097
1098 foreach ($this->ftpRawList($path) as $str) {
1099 if (($stat = $this->parseRaw($str, $path, true))) {
1100 $files[] = $this->_joinPath($path, $stat['name']);
1101 }
1102 }
1103
1104 return $files;
1105 }
1106
1107 /**
1108 * Open file and return file pointer
1109 *
1110 * @param string $path file path
1111 * @param string $mode
1112 *
1113 * @return false|resource
1114 * @throws elFinderAbortException
1115 * @internal param bool $write open file for writing
1116 * @author Dmitry (dio) Levashov
1117 */
1118 protected function _fopen($path, $mode = 'rb')
1119 {
1120 // try ftp stream wrapper
1121 if ($this->options['mode'] === 'passive' && ini_get('allow_url_fopen')) {
1122 $url = ($this->isFTPS ? 'ftps' : 'ftp') . '://' . $this->options['user'] . ':' . $this->options['pass'] . '@' . $this->options['host'] . ':' . $this->options['port'] . $path;
1123 if (strtolower($mode[0]) === 'w') {
1124 $context = stream_context_create(array('ftp' => array('overwrite' => true)));
1125 $fp = fopen($url, $mode, false, $context);
1126 } else {
1127 $fp = fopen($url, $mode);
1128 }
1129 if ($fp) {
1130 return $fp;
1131 }
1132 }
1133
1134 if ($this->tmp) {
1135 $local = $this->getTempFile($path);
1136 $fp = fopen($local, 'wb');
1137 $ret = ftp_nb_fget($this->connect, $fp, $path, FTP_BINARY);
1138 while ($ret === FTP_MOREDATA) {
1139 elFinder::extendTimeLimit();
1140 $ret = ftp_nb_continue($this->connect);
1141 }
1142 if ($ret === FTP_FINISHED) {
1143 fclose($fp);
1144 $fp = fopen($local, $mode);
1145 return $fp;
1146 }
1147 fclose($fp);
1148 is_file($local) && unlink($local);
1149 }
1150
1151 return false;
1152 }
1153
1154 /**
1155 * Close opened file
1156 *
1157 * @param resource $fp file pointer
1158 * @param string $path
1159 *
1160 * @return void
1161 * @author Dmitry (dio) Levashov
1162 */
1163 protected function _fclose($fp, $path = '')
1164 {
1165 is_resource($fp) && fclose($fp);
1166 if ($path) {
1167 unlink($this->getTempFile($path));
1168 }
1169 }
1170
1171 /******************** file/dir manipulations *************************/
1172
1173 /**
1174 * Create dir and return created dir path or false on failed
1175 *
1176 * @param string $path parent dir path
1177 * @param string $name new directory name
1178 *
1179 * @return string|bool
1180 * @author Dmitry (dio) Levashov
1181 **/
1182 protected function _mkdir($path, $name)
1183 {
1184 $path = $this->_joinPath($path, $name);
1185 if (ftp_mkdir($this->connect, $path) === false) {
1186 return false;
1187 }
1188
1189 $this->options['dirMode'] && ftp_chmod($this->connect, $this->options['dirMode'], $path);
1190 return $path;
1191 }
1192
1193 /**
1194 * Create file and return it's path or false on failed
1195 *
1196 * @param string $path parent dir path
1197 * @param string $name new file name
1198 *
1199 * @return string|bool
1200 * @author Dmitry (dio) Levashov
1201 **/
1202 protected function _mkfile($path, $name)
1203 {
1204 if ($this->tmp) {
1205 $path = $this->_joinPath($path, $name);
1206 $local = $this->getTempFile();
1207 $res = touch($local) && ftp_put($this->connect, $path, $local, FTP_ASCII);
1208 unlink($local);
1209 return $res ? $path : false;
1210 }
1211 return false;
1212 }
1213
1214 /**
1215 * Create symlink. FTP driver does not support symlinks.
1216 *
1217 * @param string $target link target
1218 * @param string $path symlink path
1219 * @param string $name
1220 *
1221 * @return bool
1222 * @author Dmitry (dio) Levashov
1223 */
1224 protected function _symlink($target, $path, $name)
1225 {
1226 return false;
1227 }
1228
1229 /**
1230 * Copy file into another file
1231 *
1232 * @param string $source source file path
1233 * @param string $targetDir target directory path
1234 * @param string $name new file name
1235 *
1236 * @return bool
1237 * @author Dmitry (dio) Levashov
1238 **/
1239 protected function _copy($source, $targetDir, $name)
1240 {
1241 $res = false;
1242
1243 if ($this->tmp) {
1244 $local = $this->getTempFile();
1245 $target = $this->_joinPath($targetDir, $name);
1246
1247 if (ftp_get($this->connect, $local, $source, FTP_BINARY)
1248 && ftp_put($this->connect, $target, $local, $this->ftpMode($target))) {
1249 $res = $target;
1250 }
1251 unlink($local);
1252 }
1253
1254 return $res;
1255 }
1256
1257 /**
1258 * Move file into another parent dir.
1259 * Return new file path or false.
1260 *
1261 * @param string $source source file path
1262 * @param $targetDir
1263 * @param string $name file name
1264 *
1265 * @return bool|string
1266 * @internal param string $target target dir path
1267 * @author Dmitry (dio) Levashov
1268 */
1269 protected function _move($source, $targetDir, $name)
1270 {
1271 $target = $this->_joinPath($targetDir, $name);
1272 return ftp_rename($this->connect, $source, $target) ? $target : false;
1273 }
1274
1275 /**
1276 * Remove file
1277 *
1278 * @param string $path file path
1279 *
1280 * @return bool
1281 * @author Dmitry (dio) Levashov
1282 **/
1283 protected function _unlink($path)
1284 {
1285 return ftp_delete($this->connect, $path);
1286 }
1287
1288 /**
1289 * Remove dir
1290 *
1291 * @param string $path dir path
1292 *
1293 * @return bool
1294 * @author Dmitry (dio) Levashov
1295 **/
1296 protected function _rmdir($path)
1297 {
1298 return ftp_rmdir($this->connect, $path);
1299 }
1300
1301 /**
1302 * Create new file and write into it from file pointer.
1303 * Return new file path or false on error.
1304 *
1305 * @param resource $fp file pointer
1306 * @param string $dir target dir path
1307 * @param string $name file name
1308 * @param array $stat file stat (required by some virtual fs)
1309 *
1310 * @return bool|string
1311 * @author Dmitry (dio) Levashov
1312 **/
1313 protected function _save($fp, $dir, $name, $stat)
1314 {
1315 $path = $this->_joinPath($dir, $name);
1316 return ftp_fput($this->connect, $path, $fp, $this->ftpMode($path))
1317 ? $path
1318 : false;
1319 }
1320
1321 /**
1322 * Get file contents
1323 *
1324 * @param string $path file path
1325 *
1326 * @return string|false
1327 * @throws elFinderAbortException
1328 * @author Dmitry (dio) Levashov
1329 */
1330 protected function _getContents($path)
1331 {
1332 $contents = '';
1333 if (($fp = $this->_fopen($path))) {
1334 while (!feof($fp)) {
1335 $contents .= fread($fp, 8192);
1336 }
1337 $this->_fclose($fp, $path);
1338 return $contents;
1339 }
1340 return false;
1341 }
1342
1343 /**
1344 * Write a string to a file
1345 *
1346 * @param string $path file path
1347 * @param string $content new file content
1348 *
1349 * @return bool
1350 * @author Dmitry (dio) Levashov
1351 **/
1352 protected function _filePutContents($path, $content)
1353 {
1354 $res = false;
1355
1356 if ($this->tmp) {
1357 $local = $this->getTempFile();
1358
1359 if (file_put_contents($local, $content, LOCK_EX) !== false
1360 && ($fp = fopen($local, 'rb'))) {
1361 $file = $this->stat($this->convEncOut($path, false));
1362 if (!empty($file['thash'])) {
1363 $path = $this->decode($file['thash']);
1364 }
1365 clearstatcache();
1366 $res = ftp_fput($this->connect, $path, $fp, $this->ftpMode($path));
1367 fclose($fp);
1368 }
1369 file_exists($local) && unlink($local);
1370 }
1371
1372 return $res;
1373 }
1374
1375 /**
1376 * Detect available archivers
1377 *
1378 * @return void
1379 * @throws elFinderAbortException
1380 */
1381 protected function _checkArchivers()
1382 {
1383 $this->archivers = $this->getArchivers();
1384 return;
1385 }
1386
1387 /**
1388 * chmod availability
1389 *
1390 * @param string $path
1391 * @param string $mode
1392 *
1393 * @return bool
1394 */
1395 protected function _chmod($path, $mode)
1396 {
1397 $modeOct = is_string($mode) ? octdec($mode) : octdec(sprintf("%04o", $mode));
1398 return ftp_chmod($this->connect, $modeOct, $path);
1399 }
1400
1401 /**
1402 * Extract files from archive
1403 *
1404 * @param string $path archive path
1405 * @param array $arc archiver command and arguments (same as in $this->archivers)
1406 *
1407 * @return true
1408 * @throws elFinderAbortException
1409 * @author Dmitry (dio) Levashov,
1410 * @author Alexey Sukhotin
1411 */
1412 protected function _extract($path, $arc)
1413 {
1414 $dir = $this->tempDir();
1415 if (!$dir) {
1416 return false;
1417 }
1418
1419 $basename = $this->_basename($path);
1420 $localPath = $dir . DIRECTORY_SEPARATOR . $basename;
1421
1422 if (!ftp_get($this->connect, $localPath, $path, FTP_BINARY)) {
1423 //cleanup
1424 $this->rmdirRecursive($dir);
1425 return false;
1426 }
1427
1428 $this->unpackArchive($localPath, $arc);
1429
1430 $this->archiveSize = 0;
1431
1432 // find symlinks and check extracted items
1433 $checkRes = $this->checkExtractItems($dir);
1434 if ($checkRes['symlinks']) {
1435 $this->rmdirRecursive($dir);
1436 return $this->setError(array_merge($this->error, array(elFinder::ERROR_ARC_SYMLINKS)));
1437 }
1438 $this->archiveSize = $checkRes['totalSize'];
1439 if ($checkRes['rmNames']) {
1440 foreach ($checkRes['rmNames'] as $name) {
1441 $this->addError(elFinder::ERROR_SAVE, $name);
1442 }
1443 }
1444
1445 $filesToProcess = self::listFilesInDirectory($dir, true);
1446
1447 // no files - extract error ?
1448 if (empty($filesToProcess)) {
1449 $this->rmdirRecursive($dir);
1450 return false;
1451 }
1452
1453 // check max files size
1454 if ($this->options['maxArcFilesSize'] > 0 && $this->options['maxArcFilesSize'] < $this->archiveSize) {
1455 $this->rmdirRecursive($dir);
1456 return $this->setError(elFinder::ERROR_ARC_MAXSIZE);
1457 }
1458
1459 $extractTo = $this->extractToNewdir; // 'auto', ture or false
1460
1461 // archive contains one item - extract in archive dir
1462 $name = '';
1463 $src = $dir . DIRECTORY_SEPARATOR . $filesToProcess[0];
1464 if (($extractTo === 'auto' || !$extractTo) && count($filesToProcess) === 1 && is_file($src)) {
1465 $name = $filesToProcess[0];
1466 } else if ($extractTo === 'auto' || $extractTo) {
1467 // for several files - create new directory
1468 // create unique name for directory
1469 $src = $dir;
1470 $splits = elFinder::splitFileExtention(basename($path));
1471 $name = $splits[0];
1472 $test = $this->_joinPath(dirname($path), $name);
1473 if ($this->stat($test)) {
1474 $name = $this->uniqueName(dirname($path), $name, '-', false);
1475 }
1476 }
1477
1478 if ($name !== '' && is_file($src)) {
1479 $result = $this->_joinPath(dirname($path), $name);
1480
1481 if (!ftp_put($this->connect, $result, $src, FTP_BINARY)) {
1482 $this->rmdirRecursive($dir);
1483 return false;
1484 }
1485 } else {
1486 $dstDir = $this->_dirname($path);
1487 $result = array();
1488 if (is_dir($src) && $name) {
1489 $target = $this->_joinPath($dstDir, $name);
1490 $_stat = $this->_stat($target);
1491 if ($_stat) {
1492 if (!$this->options['copyJoin']) {
1493 if ($_stat['mime'] === 'directory') {
1494 $this->delTree($target);
1495 } else {
1496 $this->_unlink($target);
1497 }
1498 $_stat = false;
1499 } else {
1500 $dstDir = $target;
1501 }
1502 }
1503 if (!$_stat && (!$dstDir = $this->_mkdir($dstDir, $name))) {
1504 $this->rmdirRecursive($dir);
1505 return false;
1506 }
1507 $result[] = $dstDir;
1508 }
1509 foreach ($filesToProcess as $name) {
1510 $name = rtrim($name, DIRECTORY_SEPARATOR);
1511 $src = $dir . DIRECTORY_SEPARATOR . $name;
1512 if (is_dir($src)) {
1513 $p = dirname($name);
1514 if ($p === '.') {
1515 $p = '';
1516 }
1517 $name = basename($name);
1518 $target = $this->_joinPath($this->_joinPath($dstDir, $p), $name);
1519 $_stat = $this->_stat($target);
1520 if ($_stat) {
1521 if (!$this->options['copyJoin']) {
1522 if ($_stat['mime'] === 'directory') {
1523 $this->delTree($target);
1524 } else {
1525 $this->_unlink($target);
1526 }
1527 $_stat = false;
1528 }
1529 }
1530 if (!$_stat && (!$target = $this->_mkdir($this->_joinPath($dstDir, $p), $name))) {
1531 $this->rmdirRecursive($dir);
1532 return false;
1533 }
1534 } else {
1535 $target = $this->_joinPath($dstDir, $name);
1536 if (!ftp_put($this->connect, $target, $src, FTP_BINARY)) {
1537 $this->rmdirRecursive($dir);
1538 return false;
1539 }
1540 }
1541 $result[] = $target;
1542 }
1543 if (!$result) {
1544 $this->rmdirRecursive($dir);
1545 return false;
1546 }
1547 }
1548
1549 is_dir($dir) && $this->rmdirRecursive($dir);
1550
1551 $this->clearcache();
1552 return $result ? $result : false;
1553 }
1554
1555 /**
1556 * Create archive and return its path
1557 *
1558 * @param string $dir target dir
1559 * @param array $files files names list
1560 * @param string $name archive name
1561 * @param array $arc archiver options
1562 *
1563 * @return string|bool
1564 * @throws elFinderAbortException
1565 * @author Dmitry (dio) Levashov,
1566 * @author Alexey Sukhotin
1567 */
1568 protected function _archive($dir, $files, $name, $arc)
1569 {
1570 // get current directory
1571 $cwd = getcwd();
1572
1573 $tmpDir = $this->tempDir();
1574 if (!$tmpDir) {
1575 return false;
1576 }
1577
1578 //download data
1579 if (!$this->ftp_download_files($dir, $files, $tmpDir)) {
1580 //cleanup
1581 $this->rmdirRecursive($tmpDir);
1582 return false;
1583 }
1584
1585 $remoteArchiveFile = false;
1586 if ($path = $this->makeArchive($tmpDir, $files, $name, $arc)) {
1587 $remoteArchiveFile = $this->_joinPath($dir, $name);
1588 if (!ftp_put($this->connect, $remoteArchiveFile, $path, FTP_BINARY)) {
1589 $remoteArchiveFile = false;
1590 }
1591 }
1592
1593 //cleanup
1594 if (!$this->rmdirRecursive($tmpDir)) {
1595 return false;
1596 }
1597
1598 return $remoteArchiveFile;
1599 }
1600
1601 /**
1602 * Create writable temporary directory and return path to it.
1603 *
1604 * @return string path to the new temporary directory or false in case of error.
1605 */
1606 private function tempDir()
1607 {
1608 $tempPath = tempnam($this->tmp, 'elFinder');
1609 if (!$tempPath) {
1610 $this->setError(elFinder::ERROR_CREATING_TEMP_DIR, $this->tmp);
1611 return false;
1612 }
1613 $success = unlink($tempPath);
1614 if (!$success) {
1615 $this->setError(elFinder::ERROR_CREATING_TEMP_DIR, $this->tmp);
1616 return false;
1617 }
1618 $success = mkdir($tempPath, 0700, true);
1619 if (!$success) {
1620 $this->setError(elFinder::ERROR_CREATING_TEMP_DIR, $this->tmp);
1621 return false;
1622 }
1623 return $tempPath;
1624 }
1625
1626 /**
1627 * Gets an array of absolute remote FTP paths of files and
1628 * folders in $remote_directory omitting symbolic links.
1629 *
1630 * @param $remote_directory string remote FTP path to scan for file and folders recursively
1631 * @param $targets array Array of target item. `null` is to get all of items
1632 *
1633 * @return array of elements each of which is an array of two elements:
1634 * <ul>
1635 * <li>$item['path'] - absolute remote FTP path</li>
1636 * <li>$item['type'] - either 'f' for file or 'd' for directory</li>
1637 * </ul>
1638 */
1639 protected function ftp_scan_dir($remote_directory, $targets = null)
1640 {
1641 $buff = $this->ftpRawList($remote_directory);
1642 $items = array();
1643 if ($targets && is_array($targets)) {
1644 $targets = array_flip($targets);
1645 } else {
1646 $targets = false;
1647 }
1648 foreach ($buff as $str) {
1649 $info = preg_split("/\s+/", $str, 9);
1650 if (!isset($this->ftpOsUnix)) {
1651 $this->ftpOsUnix = !preg_match('/\d/', substr($info[0], 0, 1));
1652 }
1653 if (!$this->ftpOsUnix) {
1654 $info = $this->normalizeRawWindows($str);
1655 }
1656 $type = substr($info[0], 0, 1);
1657 $name = trim($info[8]);
1658 if ($name !== '.' && $name !== '..' && (!$targets || isset($targets[$name]))) {
1659 switch ($type) {
1660 case 'l' : //omit symbolic links
1661 case 'd' :
1662 $remote_file_path = $this->_joinPath($remote_directory, $name);
1663 $item = array();
1664 $item['path'] = $remote_file_path;
1665 $item['type'] = 'd'; // normal file
1666 $items[] = $item;
1667 $items = array_merge($items, $this->ftp_scan_dir($remote_file_path));
1668 break;
1669 default:
1670 $remote_file_path = $this->_joinPath($remote_directory, $name);
1671 $item = array();
1672 $item['path'] = $remote_file_path;
1673 $item['type'] = 'f'; // normal file
1674 $items[] = $item;
1675 }
1676 }
1677 }
1678 return $items;
1679 }
1680
1681 /**
1682 * Downloads specified files from remote directory
1683 * if there is a directory among files it is downloaded recursively (omitting symbolic links).
1684 *
1685 * @param $remote_directory string remote FTP path to a source directory to download from.
1686 * @param array $files list of files to download from remote directory.
1687 * @param $dest_local_directory string destination folder to store downloaded files.
1688 *
1689 * @return bool true on success and false on failure.
1690 */
1691 private function ftp_download_files($remote_directory, array $files, $dest_local_directory)
1692 {
1693 $contents = $this->ftp_scan_dir($remote_directory, $files);
1694 if (!isset($contents)) {
1695 $this->setError(elFinder::ERROR_FTP_DOWNLOAD_FILE, $remote_directory);
1696 return false;
1697 }
1698 $remoteDirLen = strlen($remote_directory);
1699 foreach ($contents as $item) {
1700 $relative_path = substr($item['path'], $remoteDirLen);
1701 $local_path = $dest_local_directory . DIRECTORY_SEPARATOR . $relative_path;
1702 switch ($item['type']) {
1703 case 'd':
1704 $success = mkdir($local_path);
1705 break;
1706 case 'f':
1707 $success = ftp_get($this->connect, $local_path, $item['path'], FTP_BINARY);
1708 break;
1709 default:
1710 $success = true;
1711 }
1712 if (!$success) {
1713 $this->setError(elFinder::ERROR_FTP_DOWNLOAD_FILE, $remote_directory);
1714 return false;
1715 }
1716 }
1717 return true;
1718 }
1719
1720 /**
1721 * Delete local directory recursively.
1722 *
1723 * @param $dirPath string to directory to be erased.
1724 *
1725 * @return bool true on success and false on failure.
1726 * @throws Exception
1727 */
1728 private function deleteDir($dirPath)
1729 {
1730 if (!is_dir($dirPath)) {
1731 $success = unlink($dirPath);
1732 } else {
1733 $success = true;
1734 foreach (array_reverse(elFinderVolumeFTP::listFilesInDirectory($dirPath, false)) as $path) {
1735 $path = $dirPath . DIRECTORY_SEPARATOR . $path;
1736 if (is_link($path)) {
1737 unlink($path);
1738 } else if (is_dir($path)) {
1739 $success = rmdir($path);
1740 } else {
1741 $success = unlink($path);
1742 }
1743 if (!$success) {
1744 break;
1745 }
1746 }
1747 if ($success) {
1748 $success = rmdir($dirPath);
1749 }
1750 }
1751 if (!$success) {
1752 $this->setError(elFinder::ERROR_RM, $dirPath);
1753 return false;
1754 }
1755 return $success;
1756 }
1757
1758 /**
1759 * Returns array of strings containing all files and folders in the specified local directory.
1760 *
1761 * @param $dir
1762 * @param $omitSymlinks
1763 * @param string $prefix
1764 *
1765 * @return array array of files and folders names relative to the $path
1766 * or an empty array if the directory $path is empty,
1767 * <br />
1768 * false if $path is not a directory or does not exist.
1769 * @throws Exception
1770 * @internal param string $path path to directory to scan.
1771 */
1772 private static function listFilesInDirectory($dir, $omitSymlinks, $prefix = '')
1773 {
1774 if (!is_dir($dir)) {
1775 return false;
1776 }
1777 $excludes = array(".", "..");
1778 $result = array();
1779 $files = self::localScandir($dir);
1780 if (!$files) {
1781 return array();
1782 }
1783 foreach ($files as $file) {
1784 if (!in_array($file, $excludes)) {
1785 $path = $dir . DIRECTORY_SEPARATOR . $file;
1786 if (is_link($path)) {
1787 if ($omitSymlinks) {
1788 continue;
1789 } else {
1790 $result[] = $prefix . $file;
1791 }
1792 } else if (is_dir($path)) {
1793 $result[] = $prefix . $file . DIRECTORY_SEPARATOR;
1794 $subs = elFinderVolumeFTP::listFilesInDirectory($path, $omitSymlinks, $prefix . $file . DIRECTORY_SEPARATOR);
1795 if ($subs) {
1796 $result = array_merge($result, $subs);
1797 }
1798
1799 } else {
1800 $result[] = $prefix . $file;
1801 }
1802 }
1803 }
1804 return $result;
1805 }
1806
1807 } // END class
1808