forked from Studio-42/elFinder
-
Notifications
You must be signed in to change notification settings - Fork 0
/
elFinder.class.php
2907 lines (2628 loc) · 82.5 KB
/
elFinder.class.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/**
* elFinder - file manager for web.
* Core class.
*
* @package elfinder
* @author Dmitry (dio) Levashov
* @author Troex Nevelin
* @author Alexey Sukhotin
**/
class elFinder {
/**
* API version number
*
* @var string
**/
protected $version = '2.1';
/**
* Storages (root dirs)
*
* @var array
**/
protected $volumes = array();
/**
* Network mount drivers
*
* @var array
*/
public static $netDrivers = array();
/**
* elFinder global locale
*
* @var string
*/
public static $locale = '';
/**
* elFinderVolumeDriver default mime.type file path
*
* @var string
*/
public static $defaultMimefile = '';
/**
* elFinder session wrapper object
*
* @var elFinderSessionInterface
*/
protected $session;
/**
* elFinder global sessionCacheKey
*
* @deprecated
* @var string
*/
public static $sessionCacheKey = '';
/**
* Is session closed
*
* @deprecated
* @var bool
*/
private static $sessionClosed = false;
/**
* elFinder base64encodeSessionData
* elFinder save session data as `UTF-8`
* If the session storage mechanism of the system does not allow `UTF-8`
* And it must be `true` option 'base64encodeSessionData' of elFinder
*
* @var bool
*/
protected static $base64encodeSessionData = false;
/**
* elFinder common tempraly path
*
* @var string
**/
protected static $commonTempPath = '';
/**
* Session key of net mount volumes
*
* @deprecated
* @var string
*/
protected $netVolumesSessionKey = '';
/**
* Mounted volumes count
* Required to create unique volume id
*
* @var int
**/
public static $volumesCnt = 1;
/**
* Default root (storage)
*
* @var elFinderStorageDriver
**/
protected $default = null;
/**
* Commands and required arguments list
*
* @var array
**/
protected $commands = array(
'open' => array('target' => false, 'tree' => false, 'init' => false, 'mimes' => false, 'compare' => false),
'ls' => array('target' => true, 'mimes' => false, 'intersect' => false),
'tree' => array('target' => true),
'parents' => array('target' => true),
'tmb' => array('targets' => true),
'file' => array('target' => true, 'download' => false),
'zipdl' => array('targets' => true, 'download' => false),
'size' => array('targets' => true),
'mkdir' => array('target' => true, 'name' => false, 'dirs' => false),
'mkfile' => array('target' => true, 'name' => true, 'mimes' => false),
'rm' => array('targets' => true),
'rename' => array('target' => true, 'name' => true, 'mimes' => false),
'duplicate' => array('targets' => true, 'suffix' => false),
'paste' => array('dst' => true, 'targets' => true, 'cut' => false, 'mimes' => false, 'renames' => false, 'hashes' => false, 'suffix' => false),
'upload' => array('target' => true, 'FILES' => true, 'mimes' => false, 'html' => false, 'upload' => false, 'name' => false, 'upload_path' => false, 'chunk' => false, 'cid' => false, 'node' => false, 'renames' => false, 'hashes' => false, 'suffix' => false),
'get' => array('target' => true, 'conv' => false),
'put' => array('target' => true, 'content' => '', 'mimes' => false),
'archive' => array('targets' => true, 'type' => true, 'mimes' => false, 'name' => false),
'extract' => array('target' => true, 'mimes' => false, 'makedir' => false),
'search' => array('q' => true, 'mimes' => false, 'target' => false),
'info' => array('targets' => true, 'compare' => false),
'dim' => array('target' => true),
'resize' => array('target' => true, 'width' => true, 'height' => true, 'mode' => false, 'x' => false, 'y' => false, 'degree' => false, 'quality' => false),
'netmount' => array('protocol' => true, 'host' => true, 'path' => false, 'port' => false, 'user' => false, 'pass' => false, 'alias' => false, 'options' => false),
'url' => array('target' => true, 'options' => false),
'callback' => array('node' => true, 'json' => false, 'bind' => false, 'done' => false),
'chmod' => array('targets' => true, 'mode' => true)
);
/**
* Plugins instance
*
* @var array
**/
protected $plugins = array();
/**
* Commands listeners
*
* @var array
**/
protected $listeners = array();
/**
* script work time for debug
*
* @var string
**/
protected $time = 0;
/**
* Is elFinder init correctly?
*
* @var bool
**/
protected $loaded = false;
/**
* Send debug to client?
*
* @var string
**/
protected $debug = false;
/**
* Call `session_write_close()` before exec command?
*
* @var bool
*/
protected $sessionCloseEarlier = true;
/**
* SESSION use commands @see __construct()
*
* @var array
*/
protected $sessionUseCmds = array();
/**
* session expires timeout
*
* @var int
**/
protected $timeout = 0;
/**
* Temp dir path for Upload
*
* @var string
*/
protected $uploadTempPath = '';
/**
* Max allowed archive files size (0 - no limit)
*
* @var integer
*/
protected $maxArcFilesSize = 0;
/**
* undocumented class variable
*
* @var string
**/
protected $uploadDebug = '';
/**
* Errors from not mounted volumes
*
* @var array
**/
public $mountErrors = array();
/**
* URL for callback output window for CORS
* redirect to this URL when callback output
*
* @var string URL
*/
protected $callbackWindowURL = '';
// Errors messages
const ERROR_UNKNOWN = 'errUnknown';
const ERROR_UNKNOWN_CMD = 'errUnknownCmd';
const ERROR_CONF = 'errConf';
const ERROR_CONF_NO_JSON = 'errJSON';
const ERROR_CONF_NO_VOL = 'errNoVolumes';
const ERROR_INV_PARAMS = 'errCmdParams';
const ERROR_OPEN = 'errOpen';
const ERROR_DIR_NOT_FOUND = 'errFolderNotFound';
const ERROR_FILE_NOT_FOUND = 'errFileNotFound'; // 'File not found.'
const ERROR_TRGDIR_NOT_FOUND = 'errTrgFolderNotFound'; // 'Target folder "$1" not found.'
const ERROR_NOT_DIR = 'errNotFolder';
const ERROR_NOT_FILE = 'errNotFile';
const ERROR_PERM_DENIED = 'errPerm';
const ERROR_LOCKED = 'errLocked'; // '"$1" is locked and can not be renamed, moved or removed.'
const ERROR_EXISTS = 'errExists'; // 'File named "$1" already exists.'
const ERROR_INVALID_NAME = 'errInvName'; // 'Invalid file name.'
const ERROR_MKDIR = 'errMkdir';
const ERROR_MKFILE = 'errMkfile';
const ERROR_RENAME = 'errRename';
const ERROR_COPY = 'errCopy';
const ERROR_MOVE = 'errMove';
const ERROR_COPY_FROM = 'errCopyFrom';
const ERROR_COPY_TO = 'errCopyTo';
const ERROR_COPY_ITSELF = 'errCopyInItself';
const ERROR_REPLACE = 'errReplace'; // 'Unable to replace "$1".'
const ERROR_RM = 'errRm'; // 'Unable to remove "$1".'
const ERROR_RM_SRC = 'errRmSrc'; // 'Unable remove source file(s)'
const ERROR_MKOUTLINK = 'errMkOutLink'; // 'Unable to create a link to outside the volume root.'
const ERROR_UPLOAD = 'errUpload'; // 'Upload error.'
const ERROR_UPLOAD_FILE = 'errUploadFile'; // 'Unable to upload "$1".'
const ERROR_UPLOAD_NO_FILES = 'errUploadNoFiles'; // 'No files found for upload.'
const ERROR_UPLOAD_TOTAL_SIZE = 'errUploadTotalSize'; // 'Data exceeds the maximum allowed size.'
const ERROR_UPLOAD_FILE_SIZE = 'errUploadFileSize'; // 'File exceeds maximum allowed size.'
const ERROR_UPLOAD_FILE_MIME = 'errUploadMime'; // 'File type not allowed.'
const ERROR_UPLOAD_TRANSFER = 'errUploadTransfer'; // '"$1" transfer error.'
const ERROR_UPLOAD_TEMP = 'errUploadTemp'; // 'Unable to make temporary file for upload.'
const ERROR_ACCESS_DENIED = 'errAccess';
const ERROR_NOT_REPLACE = 'errNotReplace'; // Object "$1" already exists at this location and can not be replaced with object of another type.
const ERROR_SAVE = 'errSave';
const ERROR_EXTRACT = 'errExtract';
const ERROR_ARCHIVE = 'errArchive';
const ERROR_NOT_ARCHIVE = 'errNoArchive';
const ERROR_ARCHIVE_TYPE = 'errArcType';
const ERROR_ARC_SYMLINKS = 'errArcSymlinks';
const ERROR_ARC_MAXSIZE = 'errArcMaxSize';
const ERROR_RESIZE = 'errResize';
const ERROR_UNSUPPORT_TYPE = 'errUsupportType';
const ERROR_CONV_UTF8 = 'errConvUTF8';
const ERROR_NOT_UTF8_CONTENT = 'errNotUTF8Content';
const ERROR_NETMOUNT = 'errNetMount';
const ERROR_NETUNMOUNT = 'errNetUnMount';
const ERROR_NETMOUNT_NO_DRIVER = 'errNetMountNoDriver';
const ERROR_NETMOUNT_FAILED = 'errNetMountFailed';
const ERROR_SESSION_EXPIRES = 'errSessionExpires';
const ERROR_CREATING_TEMP_DIR = 'errCreatingTempDir';
const ERROR_FTP_DOWNLOAD_FILE = 'errFtpDownloadFile';
const ERROR_FTP_UPLOAD_FILE = 'errFtpUploadFile';
const ERROR_FTP_MKDIR = 'errFtpMkdir';
const ERROR_ARCHIVE_EXEC = 'errArchiveExec';
const ERROR_EXTRACT_EXEC = 'errExtractExec';
const ERROR_SEARCH_TIMEOUT = 'errSearchTimeout'; // 'Timed out while searching "$1". Search result is partial.'
const ERROR_REAUTH_REQUIRE = 'errReauthRequire'; // 'Re-authorization is required.'
/**
* Constructor
*
* @param array elFinder and roots configurations
* @author Dmitry (dio) Levashov
*/
public function __construct($opts) {
if (! interface_exists('elFinderSessionInterface')) {
include_once dirname(__FILE__).'/elFinderSessionInterface.php';
}
// session handler
if (!empty($opts['session']) && $opts['session'] instanceof elFinderSessionInterface) {
$this->session = $opts['session'];
} else {
$sessionOpts = array(
'base64encode' => !empty($opts['base64encodeSessionData']),
'keys' => array(
'default' => !empty($opts['sessionCacheKey']) ? $opts['sessionCacheKey'] : 'elFinderCaches',
'netvolume' => !empty($opts['netVolumesSessionKey'])? $opts['netVolumesSessionKey'] : 'elFinderNetVolumes'
)
);
if (! class_exists('elFinderSession')) {
include_once dirname(__FILE__) . '/elFinderSession.php';
}
$this->session = new elFinderSession($sessionOpts);
}
// try session start | restart
$this->session->start();
$sessionUseCmds = array();
if (isset($opts['sessionUseCmds']) && is_array($opts['sessionUseCmds'])) {
$sessionUseCmds = $opts['sessionUseCmds'];
}
// set self::$volumesCnt by HTTP header "X-elFinder-VolumesCntStart"
if (isset($_SERVER['HTTP_X_ELFINDER_VOLUMESCNTSTART']) && ($volumesCntStart = intval($_SERVER['HTTP_X_ELFINDER_VOLUMESCNTSTART']))) {
self::$volumesCnt = $volumesCntStart;
}
$this->time = $this->utime();
$this->debug = (isset($opts['debug']) && $opts['debug'] ? true : false);
$this->sessionCloseEarlier = isset($opts['sessionCloseEarlier'])? (bool)$opts['sessionCloseEarlier'] : true;
$this->sessionUseCmds = array_flip($sessionUseCmds);
$this->timeout = (isset($opts['timeout']) ? $opts['timeout'] : 0);
$this->uploadTempPath = (isset($opts['uploadTempPath']) ? $opts['uploadTempPath'] : '');
$this->callbackWindowURL = (isset($opts['callbackWindowURL']) ? $opts['callbackWindowURL'] : '');
elFinder::$commonTempPath = (isset($opts['commonTempPath']) ? $opts['commonTempPath'] : './.tmp');
if (!is_writable(elFinder::$commonTempPath)) {
elFinder::$commonTempPath = '';
}
$this->maxArcFilesSize = isset($opts['maxArcFilesSize'])? intval($opts['maxArcFilesSize']) : 0;
// deprecated settings
$this->netVolumesSessionKey = !empty($opts['netVolumesSessionKey'])? $opts['netVolumesSessionKey'] : 'elFinderNetVolumes';
self::$sessionCacheKey = !empty($opts['sessionCacheKey']) ? $opts['sessionCacheKey'] : 'elFinderCaches';
// check session cache
$_optsMD5 = md5(json_encode($opts['roots']));
if ($this->session->get('_optsMD5') !== $_optsMD5) {
$this->session->set('_optsMD5', $_optsMD5);
}
// setlocale and global locale regists to elFinder::locale
self::$locale = !empty($opts['locale']) ? $opts['locale'] : 'en_US.UTF-8';
if (false === @setlocale(LC_ALL, self::$locale)) {
self::$locale = setlocale(LC_ALL, '');
}
// set defaultMimefile
elFinder::$defaultMimefile = (isset($opts['defaultMimefile']) ? $opts['defaultMimefile'] : '');
// bind events listeners
if (!empty($opts['bind']) && is_array($opts['bind'])) {
$_req = $_SERVER["REQUEST_METHOD"] == 'POST' ? $_POST : $_GET;
$_reqCmd = isset($_req['cmd']) ? $_req['cmd'] : '';
foreach ($opts['bind'] as $cmd => $handlers) {
$doRegist = (strpos($cmd, '*') !== false);
if (! $doRegist) {
$_getcmd = create_function('$cmd', 'list($ret) = explode(\'.\', $cmd);return trim($ret);');
$doRegist = ($_reqCmd && in_array($_reqCmd, array_map($_getcmd, explode(' ', $cmd))));
}
if ($doRegist) {
if (! is_array($handlers) || is_object($handlers[0])) {
$handlers = array($handlers);
}
foreach($handlers as $handler) {
if ($handler) {
if (is_string($handler) && strpos($handler, '.')) {
list($_domain, $_name, $_method) = array_pad(explode('.', $handler), 3, '');
if (strcasecmp($_domain, 'plugin') === 0) {
if ($plugin = $this->getPluginInstance($_name, isset($opts['plugin'][$_name])? $opts['plugin'][$_name] : array())
and method_exists($plugin, $_method)) {
$this->bind($cmd, array($plugin, $_method));
}
}
} else {
$this->bind($cmd, $handler);
}
}
}
}
}
}
if (!isset($opts['roots']) || !is_array($opts['roots'])) {
$opts['roots'] = array();
}
// check for net volumes stored in session
$netVolumes = $this->getNetVolumes();
foreach ($netVolumes as $key => $root) {
if (! isset($root['id'])) {
// given fixed unique id
if (! $root['id'] = $this->getNetVolumeUniqueId($netVolumes)) {
$this->mountErrors[] = 'Netmount Driver "'.$root['driver'].'" : Could\'t given volume id.';
continue;
}
}
$opts['roots'][$key] = $root;
}
// "mount" volumes
foreach ($opts['roots'] as $i => $o) {
$class = 'elFinderVolume'.(isset($o['driver']) ? $o['driver'] : '');
if (class_exists($class)) {
$volume = new $class();
try {
if ($this->maxArcFilesSize && (empty($o['maxArcFilesSize']) || $this->maxArcFilesSize < $o['maxArcFilesSize'])) {
$o['maxArcFilesSize'] = $this->maxArcFilesSize;
}
// pass session handler
$volume->setSession($this->session);
if ($volume->mount($o)) {
// unique volume id (ends on "_") - used as prefix to files hash
$id = $volume->id();
$this->volumes[$id] = $volume;
if ((!$this->default || $volume->root() !== $volume->defaultPath()) && $volume->isReadable()) {
$this->default = $this->volumes[$id];
}
} else {
$this->removeNetVolume($i, $volume);
$this->mountErrors[] = 'Driver "'.$class.'" : '.implode(' ', $volume->error());
}
} catch (Exception $e) {
$this->removeNetVolume($i, $volume);
$this->mountErrors[] = 'Driver "'.$class.'" : '.$e->getMessage();
}
} else {
$this->mountErrors[] = 'Driver "'.$class.'" does not exists';
}
}
// if at least one readable volume - ii desu >_<
$this->loaded = !empty($this->default);
}
/**
* Return elFinder session wrapper instance
*
* @return object elFinderSessionInterface
**/
public function getSession() {
return $this->session;
}
/**
* Return true if fm init correctly
*
* @return bool
* @author Dmitry (dio) Levashov
**/
public function loaded() {
return $this->loaded;
}
/**
* Return version (api) number
*
* @return string
* @author Dmitry (dio) Levashov
**/
public function version() {
return $this->version;
}
/**
* Add handler to elFinder command
*
* @param string command name
* @param string|array callback name or array(object, method)
* @return elFinder
* @author Dmitry (dio) Levashov
**/
public function bind($cmd, $handler) {
$allCmds = array_keys($this->commands);
$cmds = array();
foreach(explode(' ', $cmd) as $_cmd) {
if ($_cmd !== '') {
if ($all = strpos($_cmd, '*') !== false) {
list(, $sub) = array_pad(explode('.', $_cmd), 2, '');
if ($sub) {
$sub = str_replace('\'', '\\\'', $sub);
$addSub = create_function('$cmd', 'return $cmd . \'.\' . trim(\'' . $sub . '\');');
$cmds = array_merge($cmds, array_map($addSub, $allCmds));
} else {
$cmds = array_merge($cmds, $allCmds);
}
} else {
$cmds[] = $_cmd;
}
}
}
$cmds = array_unique($cmds);
foreach ($cmds as $cmd) {
if (!isset($this->listeners[$cmd])) {
$this->listeners[$cmd] = array();
}
if (is_callable($handler)) {
$this->listeners[$cmd][] = $handler;
}
}
return $this;
}
/**
* Remove event (command exec) handler
*
* @param string command name
* @param string|array callback name or array(object, method)
* @return elFinder
* @author Dmitry (dio) Levashov
**/
public function unbind($cmd, $handler) {
if (!empty($this->listeners[$cmd])) {
foreach ($this->listeners[$cmd] as $i => $h) {
if ($h === $handler) {
unset($this->listeners[$cmd][$i]);
return $this;
}
}
}
return $this;
}
/**
* Return true if command exists
*
* @param string command name
* @return bool
* @author Dmitry (dio) Levashov
**/
public function commandExists($cmd) {
return $this->loaded && isset($this->commands[$cmd]) && method_exists($this, $cmd);
}
/**
* Return root - file's owner (public func of volume())
*
* @param string file hash
* @return elFinderStorageDriver
* @author Naoki Sawada
*/
public function getVolume($hash) {
return $this->volume($hash);
}
/**
* Return command required arguments info
*
* @param string command name
* @return array
* @author Dmitry (dio) Levashov
**/
public function commandArgsList($cmd) {
return $this->commandExists($cmd) ? $this->commands[$cmd] : array();
}
private function session_expires() {
if (! $last = $this->session->get(':LAST_ACTIVITY')) {
$this->session->set(':LAST_ACTIVITY', time());
return false;
}
if ( ($this->timeout > 0) && (time() - $last > $this->timeout) ) {
return true;
}
$this->session->set(':LAST_ACTIVITY', time());
return false;
}
/**
* Exec command and return result
*
* @param string $cmd command name
* @param array $args command arguments
* @return array
* @author Dmitry (dio) Levashov
**/
public function exec($cmd, $args) {
if (!$this->loaded) {
return array('error' => $this->error(self::ERROR_CONF, self::ERROR_CONF_NO_VOL));
}
if ($this->session_expires()) {
return array('error' => $this->error(self::ERROR_SESSION_EXPIRES));
}
if (!$this->commandExists($cmd)) {
return array('error' => $this->error(self::ERROR_UNKNOWN_CMD));
}
if (!empty($args['mimes']) && is_array($args['mimes'])) {
foreach ($this->volumes as $id => $v) {
$this->volumes[$id]->setMimesFilter($args['mimes']);
}
}
// call pre handlers for this command
$args['sessionCloseEarlier'] = isset($this->sessionUseCmds[$cmd])? false : $this->sessionCloseEarlier;
if (!empty($this->listeners[$cmd.'.pre'])) {
$volume = isset($args['target'])? $this->volume($args['target']) : false;
foreach ($this->listeners[$cmd.'.pre'] as $handler) {
call_user_func_array($handler, array($cmd, &$args, $this, $volume));
}
}
// unlock session data for multiple access
if ($this->sessionCloseEarlier && $args['sessionCloseEarlier']) {
$this->session->close();
// deprecated property
elFinder::$sessionClosed = true;
}
if (substr(PHP_OS,0,3) === 'WIN') {
// set time out
if (($_max_execution_time = ini_get('max_execution_time')) && $_max_execution_time < 300) {
@set_time_limit(300);
}
}
try {
$result = $this->$cmd($args);
} catch (Exception $e) {
$result = array(
'error' => htmlspecialchars($e->getMessage()),
'sync' => true
);
}
if (isset($result['removed'])) {
foreach ($this->volumes as $volume) {
$result['removed'] = array_merge($result['removed'], $volume->removed());
$volume->resetRemoved();
}
}
// call handlers for this command
if (!empty($this->listeners[$cmd])) {
foreach ($this->listeners[$cmd] as $handler) {
if (call_user_func_array($handler,array($cmd,&$result,$args,$this))) {
// handler return true to force sync client after command completed
$result['sync'] = true;
}
}
}
// replace removed files info with removed files hashes
if (!empty($result['removed'])) {
$removed = array();
foreach ($result['removed'] as $file) {
$removed[] = $file['hash'];
}
$result['removed'] = array_unique($removed);
}
// remove hidden files and filter files by mimetypes
if (!empty($result['added'])) {
$result['added'] = $this->filter($result['added']);
}
// remove hidden files and filter files by mimetypes
if (!empty($result['changed'])) {
$result['changed'] = $this->filter($result['changed']);
}
if ($this->debug || !empty($args['debug'])) {
$result['debug'] = array(
'connector' => 'php',
'phpver' => PHP_VERSION,
'time' => $this->utime() - $this->time,
'memory' => (function_exists('memory_get_peak_usage') ? ceil(memory_get_peak_usage()/1024).'Kb / ' : '').ceil(memory_get_usage()/1024).'Kb / '.ini_get('memory_limit'),
'upload' => $this->uploadDebug,
'volumes' => array(),
'mountErrors' => $this->mountErrors
);
foreach ($this->volumes as $id => $volume) {
$result['debug']['volumes'][] = $volume->debug();
}
}
foreach ($this->volumes as $volume) {
$volume->umount();
}
if (!empty($result['callback'])) {
$result['callback']['json'] = json_encode($result);
$this->callback($result['callback']);
} else {
return $result;
}
//TODO: Add return statement here
}
/**
* Return file real path
*
* @param string $hash file hash
* @return string
* @author Dmitry (dio) Levashov
**/
public function realpath($hash) {
if (($volume = $this->volume($hash)) == false) {
return false;
}
return $volume->realpath($hash);
}
/**
* Return network volumes config.
*
* @return array
* @author Dmitry (dio) Levashov
*/
protected function getNetVolumes() {
if ($data = $this->session->get('netvolume', array())) {
return $data;
}
return array();
}
/**
* Save network volumes config.
*
* @param array $volumes volumes config
* @return void
* @author Dmitry (dio) Levashov
*/
protected function saveNetVolumes($volumes) {
$this->session->set('netvolume', $volumes);
}
/**
* Remove netmount volume
*
* @param string $key netvolume key
* @param object $volume volume driver instance
* @return bool
*/
protected function removeNetVolume($key, $volume) {
$netVolumes = $this->getNetVolumes();
$res = true;
if (is_object($volume) && method_exists($volume, 'netunmount')) {
$res = $volume->netunmount($netVolumes, $key);
}
if ($res) {
if (is_string($key) && isset($netVolumes[$key])) {
unset($netVolumes[$key]);
$this->saveNetVolumes($netVolumes);
return true;
}
}
return false;
}
/**
* Get plugin instance & set to $this->plugins
*
* @param string $name Plugin name (dirctory name)
* @param array $opts Plugin options (optional)
* @return object | bool Plugin object instance Or false
* @author Naoki Sawada
*/
protected function getPluginInstance($name, $opts = array()) {
$key = strtolower($name);
if (! isset($this->plugins[$key])) {
$p_file = dirname(__FILE__) . DIRECTORY_SEPARATOR . 'plugins' . DIRECTORY_SEPARATOR . $name . DIRECTORY_SEPARATOR . 'plugin.php';
if (is_file($p_file)) {
require_once $p_file;
$class = 'elFinderPlugin' . $name;
$this->plugins[$key] = new $class($opts);
} else {
$this->plugins[$key] = false;
}
}
return $this->plugins[$key];
}
/***************************************************************************/
/* commands */
/***************************************************************************/
/**
* Normalize error messages
*
* @return array
* @author Dmitry (dio) Levashov
**/
public function error() {
$errors = array();
foreach (func_get_args() as $msg) {
if (is_array($msg)) {
$errors = array_merge($errors, $msg);
} else {
$errors[] = $msg;
}
}
return count($errors) ? $errors : array(self::ERROR_UNKNOWN);
}
protected function netmount($args) {
$options = array();
$protocol = $args['protocol'];
if ($protocol === 'netunmount') {
if (! empty($args['user']) && $volume = $this->volume($args['user'])) {
if ($this->removeNetVolume($args['host'], $volume)) {
return array('removed' => array(array('hash' => $volume->root())));
}
}
return array('sync' => true, 'error' => $this->error(self::ERROR_NETUNMOUNT));
}
$driver = isset(self::$netDrivers[$protocol]) ? self::$netDrivers[$protocol] : '';
$class = 'elFinderVolume'.$driver;
if (!class_exists($class)) {
return array('error' => $this->error(self::ERROR_NETMOUNT, $args['host'], self::ERROR_NETMOUNT_NO_DRIVER));
}
if (!$args['path']) {
$args['path'] = '/';
}
foreach ($args as $k => $v) {
if ($k != 'options' && $k != 'protocol' && $v) {
$options[$k] = $v;
}
}
if (is_array($args['options'])) {
foreach ($args['options'] as $key => $value) {
$options[$key] = $value;
}
}
$volume = new $class();
// pass session handler
$volume->setSession($this->session);
if (method_exists($volume, 'netmountPrepare')) {
$options = $volume->netmountPrepare($options);
if (isset($options['exit'])) {
if ($options['exit'] === 'callback') {
$this->callback($options['out']);
}
return $options;
}
}
$netVolumes = $this->getNetVolumes();
if (! isset($options['id'])) {
// given fixed unique id
if (! $options['id'] = $this->getNetVolumeUniqueId($netVolumes)) {
return array('error' => $this->error(self::ERROR_NETMOUNT, $args['host'], 'Could\'t given volume id.'));
}
}
if ($volume->mount($options)) {
if (! $key = @ $volume->netMountKey) {
$key = md5($protocol . '-' . join('-', $options));
}
if (isset($netVolumes[$key])) {
$volume->umount();
return array('error' => $this->error(self::ERROR_EXISTS, isset($options['alias'])? $options['alias'] : $options['path']));
}
$options['driver'] = $driver;
$options['netkey'] = $key;
$netVolumes[$key] = $options;
$this->saveNetVolumes($netVolumes);
$rootstat = $volume->file($volume->root());
$rootstat['netkey'] = $key;
return array('added' => array($rootstat));
} else {
$this->removeNetVolume(null, $volume);
return array('error' => $this->error(self::ERROR_NETMOUNT, $args['host'], implode(' ', $volume->error())));
}
}
/**
* "Open" directory
* Return array with following elements
* - cwd - opened dir info
* - files - opened dir content [and dirs tree if $args[tree]]
* - api - api version (if $args[init])
* - uplMaxSize - if $args[init]
* - error - on failed
*
* @param array command arguments
* @return array
* @author Dmitry (dio) Levashov
**/
protected function open($args) {
$target = $args['target'];
$init = !empty($args['init']);
$tree = !empty($args['tree']);
$volume = $this->volume($target);
$cwd = $volume ? $volume->dir($target) : false;
$hash = $init ? 'default folder' : '#'.$target;
$sleep = 0;
$compare = '';
// on init request we can get invalid dir hash -
// dir which can not be opened now, but remembered by client,
// so open default dir
if ((!$cwd || !$cwd['read']) && $init) {
$volume = $this->default;
$cwd = $volume->dir($volume->defaultPath());
}
if (!$cwd) {
return array('error' => $this->error(self::ERROR_OPEN, $hash, self::ERROR_DIR_NOT_FOUND));
}
if (!$cwd['read']) {
return array('error' => $this->error(self::ERROR_OPEN, $hash, self::ERROR_PERM_DENIED));
}
$files = array();
// get other volume root
if ($tree) {
foreach ($this->volumes as $id => $v) {
$files[] = $v->file($v->root());
}
}
// get current working directory files list
if (($ls = $volume->scandir($cwd['hash'])) === false) {
return array('error' => $this->error(self::ERROR_OPEN, $cwd['name'], $volume->error()));
}
// long polling mode
if ($args['compare']) {
$sleep = max(1, (int)$volume->getOption('lsPlSleep'));
$standby = (int)$volume->getOption('plStandby');
if ($standby > 0 && $sleep > $standby) {
$standby = $sleep;
}
$limit = max(0, floor($standby / $sleep)) + 1;
$timelimit = ini_get('max_execution_time');
do {
$timelimit && @ set_time_limit($timelimit + $sleep);
$_mtime = 0;
foreach($ls as $_f) {
$_mtime = max($_mtime, $_f['ts']);
}
$compare = strval(count($ls)).':'.strval($_mtime);
if ($compare !== $args['compare']) {
break;
}
if (--$limit) {
sleep($sleep);
$volume->clearstatcache();
if (($ls = $volume->scandir($cwd['hash'])) === false) {
break;
}
}
} while($limit);
if ($ls === false) {
return array('error' => $this->error(self::ERROR_OPEN, $cwd['name'], $volume->error()));
}
}
if ($ls) {
if ($files) {
$files = array_merge($files, $ls);
} else {