-
Notifications
You must be signed in to change notification settings - Fork 1.4k
/
elFinder.class.php
5275 lines (4811 loc) 路 178 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 float
**/
protected static $ApiVersion = 2.1;
/**
* API version number
*
* @deprecated
* @var string
**/
protected $version;
/**
* API revision that this connector supports all functions
*
* @var integer
*/
protected static $ApiRevision = 57;
/**
* Storages (root dirs)
*
* @var array
**/
protected $volumes = array();
/**
* elFinder instance
*
* @var object
*/
public static $instance = null;
/**
* Current request args
*
* @var array
*/
public static $currentArgs = 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 = '';
/**
* A file save destination path when a temporary content URL is required
* on a network volume or the like
* It can be overwritten by volume route setting
*
* @var string
*/
public static $tmpLinkPath = '';
/**
* A file save destination URL when a temporary content URL is required
* on a network volume or the like
* It can be overwritten by volume route setting
*
* @var string
*/
public static $tmpLinkUrl = '';
/**
* Temporary content URL lifetime (seconds)
*
* @var integer
*/
public static $tmpLinkLifeTime = 3600;
/**
* MIME type list handled as a text file
*
* @var array
*/
public static $textMimes = array(
'application/dash+xml',
'application/docbook+xml',
'application/javascript',
'application/json',
'application/plt',
'application/sat',
'application/sql',
'application/step',
'application/vnd.hp-hpgl',
'application/x-awk',
'application/x-config',
'application/x-csh',
'application/x-empty',
'application/x-mpegurl',
'application/x-perl',
'application/x-php',
'application/x-web-config',
'application/xhtml+xml',
'application/xml',
'audio/x-mp3-playlist',
'image/cgm',
'image/svg+xml',
'image/vnd.dxf',
'model/iges'
);
/**
* Maximum memory size to be extended during GD processing
* (0: not expanded, -1: unlimited or memory size notation)
*
* @var integer|string
*/
public static $memoryLimitGD = 0;
/**
* Path of current request flag file for abort check
*
* @var string
*/
protected static $abortCheckFile = null;
/**
* 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
* WARNING: When enabling this option, if saving the data passed from the user directly to the session variable,
* it make vulnerable to the object injection attack, so use it carefully.
* see https://github.com/Studio-42/elFinder/issues/2345
*
* @var bool
*/
protected static $base64encodeSessionData = false;
/**
* elFinder common tempraly path
*
* @var string
* @default "./.tmp" or sys_get_temp_dir()
**/
protected static $commonTempPath = '';
/**
* Callable function for URL upload filter
* The first argument is a URL and the second argument is an instance of the elFinder class
* A filter should be return true (to allow) / false (to disallow)
*
* @var callable
* @default null
*/
protected $urlUploadFilter = null;
/**
* Connection flag files path that connection check of current request
*
* @var string
* @default value of $commonTempPath
*/
protected static $connectionFlagsPath = '';
/**
* Additional volume root options for network mounting volume
*
* @var array
*/
protected $optionsNetVolumes = array();
/**
* 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 elFinderVolumeDriver
**/
protected $default = null;
/**
* Commands and required arguments list
*
* @var array
**/
protected $commands = array(
'abort' => array('id' => true),
'archive' => array('targets' => true, 'type' => true, 'mimes' => false, 'name' => false),
'callback' => array('node' => true, 'json' => false, 'bind' => false, 'done' => false),
'chmod' => array('targets' => true, 'mode' => true),
'dim' => array('target' => true, 'substitute' => false),
'duplicate' => array('targets' => true, 'suffix' => false),
'editor' => array('name' => true, 'method' => true, 'args' => false),
'extract' => array('target' => true, 'mimes' => false, 'makedir' => false),
'file' => array('target' => true, 'download' => false, 'cpath' => false, 'onetime' => false),
'get' => array('target' => true, 'conv' => false),
'info' => array('targets' => true, 'compare' => false),
'ls' => array('target' => true, 'mimes' => false, 'intersect' => false),
'mkdir' => array('target' => true, 'name' => false, 'dirs' => false),
'mkfile' => array('target' => true, 'name' => true, 'mimes' => false),
'netmount' => array('protocol' => true, 'host' => true, 'path' => false, 'port' => false, 'user' => false, 'pass' => false, 'alias' => false, 'options' => false),
'open' => array('target' => false, 'tree' => false, 'init' => false, 'mimes' => false, 'compare' => false),
'parents' => array('target' => true, 'until' => false),
'paste' => array('dst' => true, 'targets' => true, 'cut' => false, 'mimes' => false, 'renames' => false, 'hashes' => false, 'suffix' => false),
'put' => array('target' => true, 'content' => '', 'mimes' => false, 'encoding' => false),
'rename' => array('target' => true, 'name' => true, 'mimes' => false, 'targets' => false, 'q' => false),
'resize' => array('target' => true, 'width' => false, 'height' => false, 'mode' => false, 'x' => false, 'y' => false, 'degree' => false, 'quality' => false, 'bg' => false),
'rm' => array('targets' => true),
'search' => array('q' => true, 'mimes' => false, 'target' => false, 'type' => false),
'size' => array('targets' => true),
'subdirs' => array('targets' => true),
'tmb' => array('targets' => true),
'tree' => array('target' => true),
'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, 'mtime' => false, 'overwrite' => false, 'contentSaveId' => false),
'url' => array('target' => true, 'options' => false),
'zipdl' => array('targets' => true, 'download' => false)
);
/**
* 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 = '';
/**
* Max allowed numbar of targets (0 - no limit)
*
* @var integer
*/
public $maxTargets = 1000;
/**
* Errors from PHP
*
* @var array
**/
public static $phpErrors = array();
/**
* Errors from not mounted volumes
*
* @var array
**/
public $mountErrors = array();
/**
* Archivers cache
*
* @var array
*/
public static $archivers = array();
/**
* URL for callback output window for CORS
* redirect to this URL when callback output
*
* @var string URL
*/
protected $callbackWindowURL = '';
/**
* hash of items to unlock on command completion
*
* @var array hashes
*/
protected $autoUnlocks = array();
/**
* Item locking expiration (seconds)
* Default: 3600 secs
*
* @var integer
*/
protected $itemLockExpire = 3600;
/**
* Additional request querys
*
* @var array|null
*/
protected $customData = null;
/**
* Ids to remove of session var "urlContentSaveIds" for contents uploading by URL
*
* @var array
*/
protected $removeContentSaveIds = array();
/**
* Flag of throw Error on exec()
*
* @var boolean
*/
protected $throwErrorOnExec = false;
/**
* Default params of toastParams
*
* @var array
*/
protected $toastParamsDefault = array(
'mode' => 'warning',
'prefix' => ''
);
/**
* Toast params of runtime notification
*
* @var array
*/
private $toastParams = array();
/**
* Toast messages of runtime notification
*
* @var array
*/
private $toastMessages = array();
/**
* Optional UTF-8 encoder
*
* @var callable || null
*/
private $utf8Encoder = null;
/**
* Seekable URL file pointer ids - for getStreamByUrl()
*
* @var array
*/
private static $seekableUrlFps = array();
// Errors messages
const ERROR_ACCESS_DENIED = 'errAccess';
const ERROR_ARC_MAXSIZE = 'errArcMaxSize';
const ERROR_ARC_SYMLINKS = 'errArcSymlinks';
const ERROR_ARCHIVE = 'errArchive';
const ERROR_ARCHIVE_EXEC = 'errArchiveExec';
const ERROR_ARCHIVE_TYPE = 'errArcType';
const ERROR_CONF = 'errConf';
const ERROR_CONF_NO_JSON = 'errJSON';
const ERROR_CONF_NO_VOL = 'errNoVolumes';
const ERROR_CONV_UTF8 = 'errConvUTF8';
const ERROR_COPY = 'errCopy';
const ERROR_COPY_FROM = 'errCopyFrom';
const ERROR_COPY_ITSELF = 'errCopyInItself';
const ERROR_COPY_TO = 'errCopyTo';
const ERROR_CREATING_TEMP_DIR = 'errCreatingTempDir';
const ERROR_DIR_NOT_FOUND = 'errFolderNotFound';
const ERROR_EXISTS = 'errExists'; // 'File named "$1" already exists.'
const ERROR_EXTRACT = 'errExtract';
const ERROR_EXTRACT_EXEC = 'errExtractExec';
const ERROR_FILE_NOT_FOUND = 'errFileNotFound'; // 'File not found.'
const ERROR_FTP_DOWNLOAD_FILE = 'errFtpDownloadFile';
const ERROR_FTP_MKDIR = 'errFtpMkdir';
const ERROR_FTP_UPLOAD_FILE = 'errFtpUploadFile';
const ERROR_INV_PARAMS = 'errCmdParams';
const ERROR_INVALID_DIRNAME = 'errInvDirname'; // 'Invalid folder name.'
const ERROR_INVALID_NAME = 'errInvName'; // 'Invalid file name.'
const ERROR_LOCKED = 'errLocked'; // '"$1" is locked and can not be renamed, moved or removed.'
const ERROR_MAX_TARGTES = 'errMaxTargets'; // 'Max number of selectable items is $1.'
const ERROR_MKDIR = 'errMkdir';
const ERROR_MKFILE = 'errMkfile';
const ERROR_MKOUTLINK = 'errMkOutLink'; // 'Unable to create a link to outside the volume root.'
const ERROR_MOVE = 'errMove';
const ERROR_NETMOUNT = 'errNetMount';
const ERROR_NETMOUNT_FAILED = 'errNetMountFailed';
const ERROR_NETMOUNT_NO_DRIVER = 'errNetMountNoDriver';
const ERROR_NETUNMOUNT = 'errNetUnMount';
const ERROR_NOT_ARCHIVE = 'errNoArchive';
const ERROR_NOT_DIR = 'errNotFolder';
const ERROR_NOT_FILE = 'errNotFile';
const ERROR_NOT_REPLACE = 'errNotReplace'; // Object "$1" already exists at this location and can not be replaced with object of another type.
const ERROR_NOT_UTF8_CONTENT = 'errNotUTF8Content';
const ERROR_OPEN = 'errOpen';
const ERROR_PERM_DENIED = 'errPerm';
const ERROR_REAUTH_REQUIRE = 'errReauthRequire'; // 'Re-authorization is required.'
const ERROR_RENAME = 'errRename';
const ERROR_REPLACE = 'errReplace'; // 'Unable to replace "$1".'
const ERROR_RESIZE = 'errResize';
const ERROR_RESIZESIZE = 'errResizeSize';
const ERROR_RM = 'errRm'; // 'Unable to remove "$1".'
const ERROR_RM_SRC = 'errRmSrc'; // 'Unable remove source file(s)'
const ERROR_SAVE = 'errSave';
const ERROR_SEARCH_TIMEOUT = 'errSearchTimeout'; // 'Timed out while searching "$1". Search result is partial.'
const ERROR_SESSION_EXPIRES = 'errSessionExpires';
const ERROR_TRGDIR_NOT_FOUND = 'errTrgFolderNotFound'; // 'Target folder "$1" not found.'
const ERROR_UNKNOWN = 'errUnknown';
const ERROR_UNKNOWN_CMD = 'errUnknownCmd';
const ERROR_UNSUPPORT_TYPE = 'errUsupportType';
const ERROR_UPLOAD = 'errUpload'; // 'Upload error.'
const ERROR_UPLOAD_FILE = 'errUploadFile'; // 'Unable to upload "$1".'
const ERROR_UPLOAD_FILE_MIME = 'errUploadMime'; // 'File type not allowed.'
const ERROR_UPLOAD_FILE_SIZE = 'errUploadFileSize'; // 'File exceeds maximum allowed size.'
const ERROR_UPLOAD_NO_FILES = 'errUploadNoFiles'; // 'No files found for upload.'
const ERROR_UPLOAD_TEMP = 'errUploadTemp'; // 'Unable to make temporary file for upload.'
const ERROR_UPLOAD_TOTAL_SIZE = 'errUploadTotalSize'; // 'Data exceeds the maximum allowed size.'
const ERROR_UPLOAD_TRANSFER = 'errUploadTransfer'; // '"$1" transfer error.'
/**
* Constructor
*
* @param array elFinder and roots configurations
*
* @author Dmitry (dio) Levashov
*/
public function __construct($opts)
{
// set default_charset
if (version_compare(PHP_VERSION, '5.6', '>=')) {
if (($_val = ini_get('iconv.internal_encoding')) && strtoupper($_val) !== 'UTF-8') {
ini_set('iconv.internal_encoding', '');
}
if (($_val = ini_get('mbstring.internal_encoding')) && strtoupper($_val) !== 'UTF-8') {
ini_set('mbstring.internal_encoding', '');
}
if (($_val = ini_get('internal_encoding')) && strtoupper($_val) !== 'UTF-8') {
ini_set('internal_encoding', '');
}
} else {
if (function_exists('iconv_set_encoding') && strtoupper(iconv_get_encoding('internal_encoding')) !== 'UTF-8') {
iconv_set_encoding('internal_encoding', 'UTF-8');
}
if (function_exists('mb_internal_encoding') && strtoupper(mb_internal_encoding()) !== 'UTF-8') {
mb_internal_encoding('UTF-8');
}
}
ini_set('default_charset', 'UTF-8');
// define accept constant of server commands path
!defined('ELFINDER_TAR_PATH') && define('ELFINDER_TAR_PATH', 'tar');
!defined('ELFINDER_GZIP_PATH') && define('ELFINDER_GZIP_PATH', 'gzip');
!defined('ELFINDER_BZIP2_PATH') && define('ELFINDER_BZIP2_PATH', 'bzip2');
!defined('ELFINDER_XZ_PATH') && define('ELFINDER_XZ_PATH', 'xz');
!defined('ELFINDER_ZIP_PATH') && define('ELFINDER_ZIP_PATH', 'zip');
!defined('ELFINDER_UNZIP_PATH') && define('ELFINDER_UNZIP_PATH', 'unzip');
!defined('ELFINDER_RAR_PATH') && define('ELFINDER_RAR_PATH', 'rar');
// Create archive in RAR4 format even when using RAR5 library (true or false)
!defined('ELFINDER_RAR_MA4') && define('ELFINDER_RAR_MA4', false);
!defined('ELFINDER_UNRAR_PATH') && define('ELFINDER_UNRAR_PATH', 'unrar');
!defined('ELFINDER_7Z_PATH') && define('ELFINDER_7Z_PATH', (substr(PHP_OS, 0, 3) === 'WIN') ? '7z' : '7za');
!defined('ELFINDER_CONVERT_PATH') && define('ELFINDER_CONVERT_PATH', 'convert');
!defined('ELFINDER_IDENTIFY_PATH') && define('ELFINDER_IDENTIFY_PATH', 'identify');
!defined('ELFINDER_EXIFTRAN_PATH') && define('ELFINDER_EXIFTRAN_PATH', 'exiftran');
!defined('ELFINDER_JPEGTRAN_PATH') && define('ELFINDER_JPEGTRAN_PATH', 'jpegtran');
!defined('ELFINDER_FFMPEG_PATH') && define('ELFINDER_FFMPEG_PATH', 'ffmpeg');
!defined('ELFINDER_DISABLE_ZIPEDITOR') && define('ELFINDER_DISABLE_ZIPEDITOR', false);
// enable(true)/disable(false) handling postscript on ImageMagick
// Should be `false` as long as there is a Ghostscript vulnerability
// see https://artifex.com/news/ghostscript-security-resolved/
!defined('ELFINDER_IMAGEMAGICK_PS') && define('ELFINDER_IMAGEMAGICK_PS', false);
// for backward compat
$this->version = (string)self::$ApiVersion;
// set error handler of WARNING, NOTICE
$errLevel = E_WARNING | E_NOTICE | E_USER_WARNING | E_USER_NOTICE | E_STRICT | E_RECOVERABLE_ERROR;
if (defined('E_DEPRECATED')) {
$errLevel |= E_DEPRECATED | E_USER_DEPRECATED;
}
set_error_handler('elFinder::phpErrorHandler', $errLevel);
// Associative array of file pointers to close at the end of script: ['temp file pointer' => true]
$GLOBALS['elFinderTempFps'] = array();
// Associative array of files to delete at the end of script: ['temp file path' => true]
$GLOBALS['elFinderTempFiles'] = array();
// regist Shutdown function
register_shutdown_function(array('elFinder', 'onShutdown'));
// convert PATH_INFO to GET query
if (!empty($_SERVER['PATH_INFO'])) {
$_ps = explode('/', trim($_SERVER['PATH_INFO'], '/'));
if (!isset($_GET['cmd'])) {
$_cmd = $_ps[0];
if (isset($this->commands[$_cmd])) {
$_GET['cmd'] = $_cmd;
$_i = 1;
foreach (array_keys($this->commands[$_cmd]) as $_k) {
if (isset($_ps[$_i])) {
if (!isset($_GET[$_k])) {
$_GET[$_k] = $_ps[$_i++];
}
} else {
break;
}
}
}
}
}
// set elFinder instance
elFinder::$instance = $this;
// setup debug mode
$this->debug = (isset($opts['debug']) && $opts['debug'] ? true : false);
if ($this->debug) {
error_reporting(defined('ELFINDER_DEBUG_ERRORLEVEL') ? ELFINDER_DEBUG_ERRORLEVEL : -1);
ini_set('display_errors', '1');
// clear output buffer and stop output filters
while (ob_get_level() && ob_end_clean()) {
}
}
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();
// 'netmount' added to handle requests synchronously on unmount
$sessionUseCmds = array('netmount');
if (isset($opts['sessionUseCmds']) && is_array($opts['sessionUseCmds'])) {
$sessionUseCmds = array_merge($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->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'] : '');
$this->maxTargets = (isset($opts['maxTargets']) ? intval($opts['maxTargets']) : $this->maxTargets);
elFinder::$commonTempPath = (isset($opts['commonTempPath']) ? realpath($opts['commonTempPath']) : dirname(__FILE__) . '/.tmp');
if (!is_writable(elFinder::$commonTempPath)) {
elFinder::$commonTempPath = sys_get_temp_dir();
if (!is_writable(elFinder::$commonTempPath)) {
elFinder::$commonTempPath = '';
}
}
if (isset($opts['connectionFlagsPath']) && is_writable($opts['connectionFlagsPath'] = realpath($opts['connectionFlagsPath']))) {
elFinder::$connectionFlagsPath = $opts['connectionFlagsPath'];
} else {
elFinder::$connectionFlagsPath = elFinder::$commonTempPath;
}
if (!empty($opts['tmpLinkPath'])) {
elFinder::$tmpLinkPath = realpath($opts['tmpLinkPath']);
}
if (!empty($opts['tmpLinkUrl'])) {
elFinder::$tmpLinkUrl = $opts['tmpLinkUrl'];
}
if (!empty($opts['tmpLinkLifeTime'])) {
elFinder::$tmpLinkLifeTime = $opts['tmpLinkLifeTime'];
}
if (!empty($opts['textMimes']) && is_array($opts['textMimes'])) {
elfinder::$textMimes = $opts['textMimes'];
}
if (!empty($opts['urlUploadFilter'])) {
$this->urlUploadFilter = $opts['urlUploadFilter'];
}
$this->maxArcFilesSize = isset($opts['maxArcFilesSize']) ? intval($opts['maxArcFilesSize']) : 0;
$this->optionsNetVolumes = (isset($opts['optionsNetVolumes']) && is_array($opts['optionsNetVolumes'])) ? $opts['optionsNetVolumes'] : array();
if (isset($opts['itemLockExpire'])) {
$this->itemLockExpire = intval($opts['itemLockExpire']);
}
// 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'] : (substr(PHP_OS, 0, 3) === 'WIN' ? 'C' : 'en_US.UTF-8');
if (false === setlocale(LC_ALL, self::$locale)) {
self::$locale = setlocale(LC_ALL, '0');
}
// set defaultMimefile
elFinder::$defaultMimefile = isset($opts['defaultMimefile']) ? $opts['defaultMimefile'] : '';
// set memoryLimitGD
elFinder::$memoryLimitGD = isset($opts['memoryLimitGD']) ? $opts['memoryLimitGD'] : 0;
// set flag of throwErrorOnExec
// `true` need `try{}` block for `$connector->run();`
$this->throwErrorOnExec = !empty($opts['throwErrorOnExec']);
// set archivers
elFinder::$archivers = isset($opts['archivers']) && is_array($opts['archivers']) ? $opts['archivers'] : array();
// set utf8Encoder
if (isset($opts['utf8Encoder']) && is_callable($opts['utf8Encoder'])) {
$this->utf8Encoder = $opts['utf8Encoder'];
}
// 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) {
$doRegist = ($_reqCmd && in_array($_reqCmd, array_map('self::getCmdOfBind', explode(' ', $cmd))));
}
if ($doRegist) {
// for backward compatibility
if (!is_array($handlers)) {
$handlers = array($handlers);
} else {
if (count($handlers) === 2 && is_callable($handlers)) {
$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();
}
// try to enable elFinderVolumeFlysystemZipArchiveNetmount to zip editing
if (empty(elFinder::$netDrivers['ziparchive'])) {
elFinder::$netDrivers['ziparchive'] = 'FlysystemZipArchiveNetmount';
}
// 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;
}
}
$root['_isNetVolume'] = true;
$opts['roots'][$key] = $root;
}
// "mount" volumes
foreach ($opts['roots'] as $i => $o) {
$class = 'elFinderVolume' . (isset($o['driver']) ? $o['driver'] : '');
if (class_exists($class)) {
/* @var elFinderVolumeDriver $volume */
$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 (!$this->default) {
$volume->setNeedOnline(true);
}
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 = $volume;
}
} else {
if (!empty($o['_isNetVolume'])) {
$this->removeNetVolume($i, $volume);
}
$this->mountErrors[] = 'Driver "' . $class . '" : ' . implode(' ', $volume->error());
}
} catch (Exception $e) {
if (!empty($o['_isNetVolume'])) {
$this->removeNetVolume($i, $volume);
}
$this->mountErrors[] = 'Driver "' . $class . '" : ' . $e->getMessage();
}
} else {
if (!empty($o['_isNetVolume'])) {
$this->removeNetVolume($i, $volume);
}
$this->mountErrors[] = 'Driver "' . $class . '" does not exist';
}
}
// if at least one readable volume - ii desu >_<
$this->loaded = !empty($this->default);
// restore error handler for now
restore_error_handler();
}
/**
* Return elFinder session wrapper instance
*
* @return 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 self::$ApiVersion;
}
/**
* Return revision (api) number
*
* @return string
* @author Naoki Sawada
**/
public function revision()
{
return self::$ApiRevision;
}
/**
* 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);
$subs = array_fill(0, count($allCmds), $sub);
$cmds = array_merge($cmds, array_map(array('elFinder', 'addSubToBindName'), $allCmds, $subs));
} 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;
}
/**
* Trigger binded functions
*
* @param string $cmd binded command name
* @param array $vars variables to pass to listeners
* @param array $errors array into which the error is written
*/
public function trigger($cmd, $vars, &$errors)
{
if (!empty($this->listeners[$cmd])) {
foreach ($this->listeners[$cmd] as $handler) {
$_res = call_user_func_array($handler, $vars);
if ($_res && is_array($_res)) {
$_err = !empty($_res['error'])? $_res['error'] : (!empty($_res['warning'])? $_res['warning'] : null);
if ($_err) {
if (is_array($_err)) {
$errors = array_merge($errors, $_err);
} else {
$errors[] = (string)$_err;
}
if ($_res['error']) {
throw elFinderTriggerException();
}
}
}
}
}
}
/**
* Return true if command exists