-
Notifications
You must be signed in to change notification settings - Fork 62
Expand file tree
/
Copy pathfilesystem.class.php
More file actions
2923 lines (2734 loc) · 142 KB
/
Copy pathfilesystem.class.php
File metadata and controls
2923 lines (2734 loc) · 142 KB
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
/**
* File for filesystem classes
*
* @package eFront
*/
//This file cannot be called directly, only included.
if (str_replace(DIRECTORY_SEPARATOR, "/", __FILE__) == $_SERVER['SCRIPT_FILENAME']) {
exit;
}
/**
* EfrontFileException class
*
* This class extends Exception class and is used to issue errors regarding files and filesystem
*
* @package eFront
* @since 3.5.0
*/
class EfrontFileException extends Exception
{
//Note: values from 1 to 8 are upload errors
const NO_ERROR = 0;
const ILLEGAL_FILE_NAME = 101;
const FILE_NOT_EXIST = 102;
const ILLEGAL_PATH = 103;
const FILE_IN_BLACK_LIST = 104;
const FILE_NOT_IN_WHITE_LIST = 105;
const GENERAL_ERROR = 106;
const FILE_ALREADY_EXISTS = 107;
const DIRECTORY_ALREADY_EXISTS = 108;
const FILE_DELETED = 109;
const ERROR_CREATE_ZIP = 110;
const ERROR_OPEN_ZIP = 111;
const UNKNOWN_COMPRESSION = 112;
const DIRECTORY_NOT_EXIST = 113;
const NOT_LESSON_FILE = 114;
const UNAUTHORIZED_ACTION = 115;
const NOT_APPROPRIATE_TYPE = 116;
const ERROR_ZIP_PROCESSING = 117;
const CANNOT_CREATE_DIR = 118;
const NOT_WRITABLE_ERROR = 119;
const UNKNOWN_ERROR = 199;
const DATABASE_ERROR = 301;
}
/**
* Class for files in Efront file system
*
* @since 3.5.0
* @package eFront
*/
class EfrontFile extends ArrayObject
{
/**
* An array of mime types
*
* @since 3.5.0
* @var array
* @access public
* @static
*/
public static $mimeTypes = array (
'bmp' => 'image/bmp',
'cgm' => 'image/cgm',
'djv' => 'image/vnd.djvu',
'djvu' => 'image/vnd.djvu',
'flv' => 'application/flv',
'gif' => 'image/gif',
'ico' => 'image/x-icon',
'ief' => 'image/ief',
'jp2' => 'image/jp2',
'jpe' => 'image/jpeg',
'jpeg' => 'image/jpeg',
'jpg' => 'image/jpeg',
'mac' => 'image/x-macpaint',
'pbm' => 'image/x-portable-bitmap',
'pct' => 'image/pict',
'pgm' => 'image/x-portable-graymap',
'pic' => 'image/pict',
'pict' => 'image/pict',
'png' => 'image/png',
'pnm' => 'image/x-portable-anymap',
'pnt' => 'image/x-macpaint',
'pntg' => 'image/x-macpaint',
'ppm' => 'image/x-portable-pixmap',
'qti' => 'image/x-quicktime',
'qtif' => 'image/x-quicktime',
'ras' => 'image/x-cmu-raster',
'rgb' => 'image/x-rgb',
'svg' => 'image/svg+xml',
'tif' => 'image/tiff',
'tiff' => 'image/tiff',
'wbmp' => 'image/vnd.wap.wbmp',
'xbm' => 'image/x-xbitmap',
'xpm' => 'image/x-xpixmap',
'xwd' => 'image/x-xwindowdump',
'asc' => 'text/plain',
'css' => 'text/css',
'etx' => 'text/x-setext',
'htc' => 'text/x-component',
'htm' => 'text/html',
'html' => 'text/html',
'ics' => 'text/calendar',
'ifb' => 'text/calendar',
'rtf' => 'text/rtf',
'rtx' => 'text/richtext',
'sgm' => 'text/sgml',
'sgml' => 'text/sgml',
'tsv' => 'text/tab-separated-values',
'txt' => 'text/plain',
'wml' => 'text/vnd.wap.wml',
'wmls' => 'text/vnd.wap.wmlscript',
'kar' => 'audio/midi',
'm3u' => 'audio/x-mpegurl',
'm4a' => 'audio/mp4a-latm',
'm4b' => 'audio/mp4a-latm',
'm4p' => 'audio/mp4a-latm',
'mid' => 'audio/midi',
'midi' => 'audio/midi',
'mp2' => 'audio/mpeg',
'mp3' => 'audio/mpeg',
'mpga' => 'audio/mpeg',
'ra' => 'audio/x-pn-realaudio',
'ram' => 'audio/x-pn-realaudio',
'snd' => 'audio/basic',
'wav' => 'audio/x-wav',
'aif' => 'audio/x-aiff',
'aifc' => 'audio/x-aiff',
'aiff' => 'audio/x-aiff',
'au' => 'audio/basic',
'avi' => 'video/x-msvideo',
'mov' => 'video/quicktime',
'movie' => 'video/x-sgi-movie',
'mp4' => 'video/mp4',
'mpe' => 'video/mpeg',
'mpeg' => 'video/mpeg',
'mpg' => 'video/mpeg',
'm4u' => 'video/vnd.mpegurl',
'm4v' => 'video/x-m4v',
'dif' => 'video/x-dv',
'dv' => 'video/x-dv',
'mxu' => 'video/vnd.mpegurl',
'qt' => 'video/quicktime',
'wmv' => 'video/x-ms-wmv',
'iges' => 'model/iges',
'igs' => 'model/iges',
'mesh' => 'model/mesh',
'msh' => 'model/mesh',
'silo' => 'model/mesh',
'vrml' => 'model/vrml',
'wrl' => 'model/vrml',
'xyz' => 'chemical/x-xyz',
'pdb' => 'chemical/x-pdb',
'ice' => 'x-conference/x-cooltalk',
'ai' => 'application/postscript',
'atom' => 'application/atom+xml',
'bcpio' => 'application/x-bcpio',
'bin' => 'application/octet-stream',
'cdf' => 'application/x-netcdf',
'class' => 'application/octet-stream',
'cpio' => 'application/x-cpio',
'cpt' => 'application/mac-compactpro',
'csh' => 'application/x-csh',
'csv' => 'application/text',
'dcr' => 'application/x-director',
'dir' => 'application/x-director',
'dll' => 'application/octet-stream',
'dmg' => 'application/octet-stream',
'dms' => 'application/octet-stream',
'doc' => 'application/msword',
'dtd' => 'application/xml-dtd',
'dvi' => 'application/x-dvi',
'dxr' => 'application/x-director',
'eps' => 'application/postscript',
'exe' => 'application/octet-stream',
'ez' => 'application/andrew-inset',
'gram' => 'application/srgs',
'grxml' => 'application/srgs+xml',
'gtar' => 'application/x-gtar',
'hdf' => 'application/x-hdf',
'hqx' => 'application/mac-binhex40',
'jnlp' => 'application/x-java-jnlp-file',
'js' => 'application/x-javascript',
'latex' => 'application/x-latex',
'lha' => 'application/octet-stream',
'lzh' => 'application/octet-stream',
'man' => 'application/x-troff-man',
'mathml' => 'application/mathml+xml',
'me' => 'application/x-troff-me',
'mif' => 'application/vnd.mif',
'ms' => 'application/x-troff-ms',
'nc' => 'application/x-netcdf',
'oda' => 'application/oda',
'ogg' => 'application/ogg',
'pdf' => 'application/pdf',
'pgn' => 'application/x-chess-pgn',
'ppt' => 'application/vnd.ms-powerpoint',
'ps' => 'application/postscript',
'rdf' => 'application/rdf+xml',
'rm' => 'application/vnd.rn-realmedia',
'roff' => 'application/x-troff',
'sh' => 'application/x-sh',
'shar' => 'application/x-shar',
'sit' => 'application/x-stuffit',
'skd' => 'application/x-koan',
'skm' => 'application/x-koan',
'skp' => 'application/x-koan',
'skt' => 'application/x-koan',
'smi' => 'application/smil',
'smil' => 'application/smil',
'so' => 'application/octet-stream',
'spl' => 'application/x-futuresplash',
'src' => 'application/x-wais-source',
'sv4cpio' => 'application/x-sv4cpio',
'sv4crc' => 'application/x-sv4crc',
'swf' => 'application/x-shockwave-flash',
't' => 'application/x-troff',
'tar' => 'application/x-tar',
'tcl' => 'application/x-tcl',
'tex' => 'application/x-tex',
'texi' => 'application/x-texinfo',
'texinfo' => 'application/x-texinfo',
'tr' => 'application/x-troff',
'ustar' => 'application/x-ustar',
'vcd' => 'application/x-cdlink',
'vxml' => 'application/voicexml+xml',
'wbmxl' => 'application/vnd.wap.wbxml',
'wmlc' => 'application/vnd.wap.wmlc',
'wmlsc' => 'application/vnd.wap.wmlscriptc',
'xht' => 'application/xhtml+xml',
'xhtml' => 'application/xhtml+xml',
'xls' => 'application/vnd.ms-excel',
'xml' => 'application/xml',
'xsl' => 'application/xml',
'xslt' => 'application/xslt+xml',
'xul' => 'application/vnd.mozilla.xul+xml',
'zip' => 'application/zip');
/**
* Class constructor
*
* The class constructor instantiates the object based on the $file parameter.
* $file may be either:
* - an array with file attributes
* - a file id
* - the full path to a physical file
* - The full path to a file, even if it doesn't have a corresponding database representation
* <br/>Example:
* <code>
* $result = eF_getTableData("files", "*", "id=43");
* $file = new EfrontFile($result[0]); //Instantiate object using array of values
* $file = new EfrontFile(43); //Instantiate object using id
* $file = new EfrontFile('/var/www/test.txt'); //Instantiate object using path
* </code>
*
* @param mixed $file The file information, either an array, an id or a path string
* @since 3.5.0
* @access public
*/
function __construct($file) {
if (is_array($file)) { //Instantiate object based on the given array
$file['path'] = EfrontDirectory :: normalize($file['path']);
if (strpos($file['path'], G_ROOTPATH) === false) {
$file['path'] = G_ROOTPATH.$file['path'];
}
$fileArray = $file;
} else {
if (eF_checkParameter($file, 'id')) { //Instantiate object based on id
$result = eF_getTableData("files", "*", "id=".$file, "id");
} elseif (eF_checkParameter($file, 'path')) { //id-based instantiation failed; Check if the full path is specified
$file = EfrontDirectory :: normalize($file);
$result = eF_getTableData("files", "*", "path='".str_replace(G_ROOTPATH, '', eF_addSlashes(EfrontDirectory :: normalize($file)))."'", "id"); //eF_addSlashes for files containing '
} else {
throw new EfrontFileException(_ILLEGALPATH.': '.$file, EfrontFileException :: ILLEGAL_PATH);
}
if (sizeof($result) > 0) {
if (sizeof($result) > 1) { //if for some reason there is more than 1 database entries for the same file, keep only the latest (based on id)
for ($i = 0; $i < sizeof($result) - 1; $i++) {
eF_deleteTableData("files", "id=".$result[$i]['id']);
EfrontSearch :: removeText('files', $result[$i]['id'], 'data');
//unlink($result[$i]['file']);
}
$fileArray = $result[$i];
} else {
$fileArray = $result[0];
}
$fileArray['path'] = G_ROOTPATH.$fileArray['path'];
} else {
if (is_file($file) && strpos($file, G_ROOTPATH) !== false) { //Create object without database information
$fileArray = array('id' => -1, //Set 'id' to -1, meaning this file has not a database representation
'path' => $file);
} else if (strpos($file, G_ROOTPATH) === false) {
throw new EfrontFileException(_ILLEGALPATH.': '.$file, EfrontFileException :: ILLEGAL_PATH);
} else {
throw new EfrontFileException(_FILEDOESNOTEXIST.': '.$file, EfrontFileException :: FILE_NOT_EXIST);
}
}
}
//Append extra useful (derived) information to the array: name, extension, size, mime type
$fileArray['name'] = EfrontFile :: decode(basename($fileArray['path']));
$fileArray['directory'] = dirname($fileArray['path']);
$fileArray['extension'] = pathinfo($fileArray['path'], PATHINFO_EXTENSION);
$fileArray['size'] = round(filesize($fileArray['path'])/1024, 2);
$fileArray['timestamp'] = filemtime($fileArray['path']);
$fileArray['type'] = 'file';
$fileArray['physical_name'] = basename($fileArray['path']);
foreach ($pathParts = explode("/", $fileArray['path']) as $key => $value) {
$pathParts[$key] = urlencode($value);
}
$fileArray['url_path'] = implode("/", $pathParts);
//$fileArray['original_name'] != $fileArray['physical_name'] ? $fileArray['renamed'] = true : $fileArray['renamed'] = false; //If the physical file name is different than the original name, it means that the file is renamed
isset(EfrontFile :: $mimeTypes[strtolower($fileArray['extension'])]) ? $fileArray['mime_type'] = EfrontFile :: $mimeTypes[strtolower($fileArray['extension'])] : $fileArray['mime_type'] = 'application/'.$fileArray['extension'];
parent :: __construct($fileArray); //Create an ArrayObject from the given array
if (!is_file($this['path'])) { //If the file does not actually exist, then delete it from database and issue exception
if ($this['id'] != -1) {
eF_deleteTableData("files", "id=".$this['id']);
EfrontSearch :: removeText('files', $this['id'], 'data');
}
throw new EfrontFileException(_FILEDOESNOTEXIST.': '.$this['path'], EfrontFileException :: FILE_DELETED);
} elseif ( strpos($this['path'], G_ROOTPATH) === false ) {
throw new EfrontFileException(_ILLEGALPATH.': '.$this['path'], EfrontFileException :: ILLEGAL_PATH); //The file must be inside root path, otherwise it is illegal
}
}
/**
* Delete file
*
* This function deletes the file. It first unlinks (if it exists)
* the physical file, and then deletes its entry from the database.
* <br/>Example:
* <code>
* $file = new EfrontFile(34); //Instantiate file
* $file -> delete(); //Delete file
* </code>
*
* @return boolean True if the file was deleted
* @since 3.5.0
* @access public
*/
public function delete() {
if (is_file($this['path']) && !unlink($this['path'])) { //If the file exists but could not be deleted, throw an exception. This way, even files that their equivalent physical file does not exist, may be deleted.
throw new EfrontFileException(_CANNOTDELETEFILE, EfrontFileException :: GENERAL_ERROR);
}
if ($this['id'] != -1) {
eF_deleteTableData("files", "path = '".str_replace(G_ROOTPATH, '', eF_addSlashes($this['path']))."' or id=".$this['id']); //Delete database representation of the file
EfrontSearch :: removeText('files', $this['id'], 'data');
}
return true;
}
/**
* Copy file
*
* This function is used to copy the current file to a new
* destination. If a file with the same name exists in the
* destination and $overwrite is true, it will be overwritten
* <br/>Example:
* <code>
* $file = new EfrontFile(43); //Instantiate file object
* $file -> copy('/var/www/'); //Copy file to /var/www/
* $file -> copy('/var/www/', true); //Copy file to /var/www/ and overwrite if it already exists
* </code>
* If the file being copied doesn't have a corresponding database representation,
* the new file won't have one either. Otherwise, a database entry will be created
* for the new file (An EfrontFile object corresponds to a file without DB representation
* when the id is -1)
*
* @param string $destinationPath The destination directory
* @param boolean $overwrite If true, overwrite existing file with the same name
* @return EfrontFile The copied file
* @since 3.5.0
* @access public
*/
public function copy($destinationPath, $overwrite = true) {
$destinationPath = EfrontDirectory :: normalize($destinationPath);
$parentDirectory = new EfrontDirectory(dirname($destinationPath)); //This way we check integrity of destination
if (is_dir($destinationPath)) { //If $destinationPath is a directory, it means that the target file name was not specified, so append the current
$destinationPath = $destinationPath.'/'.$this['physical_name'];
}
if (!$overwrite && is_file($destinationPath)) {
throw new EfrontFileException(_CANNOTCOPYFILE.': '.$destinationPath.', '._FILEALREADYEXISTS, EfrontFileException :: FILE_ALREADY_EXISTS);//Use plain Exception rather than EfrontFileException, since the latter is caught right from the following catch block
}
if (copy($this['path'], $destinationPath)) {
if ($this['id'] != -1) {
$fields = array("path" => str_replace(G_ROOTPATH, '', $destinationPath), //Database entry for copied file
"users_LOGIN" => isset($_SESSION['s_login']) ? $_SESSION['s_login'] : $this['users_LOGIN'],
"timestamp" => time(),
"description" => $this['description'],
"groups_ID" => $this['groups_ID'],
"access" => $this['access'],
"metadata" => $this['metadata']);
$fileId = eF_insertTableData("files", $fields);
if ($fileId) {
$fileMetadataArray = unserialize($this['metadata']);
foreach ($fileMetadataArray as $key => $value) {
EfrontSearch :: insertText($value, $fileId, "files", "data");
}
}
}
$file = new EfrontFile($destinationPath);
return $file;
} else {
//eF_deleteTableData("files", "id=$fileid"); //If copy failed, delete empty table entry
throw new EfrontFileException(_CANNOTCOPYFILE, EfrontFileException :: UNKNOWN_ERROR);
}
}
/**
* Move file
*
* This function is equivalent to copy(), except that it deletes the original
* file after copying it.
* <br/>Example:
* <code>
* $file = new EfrontFile(43); //Instantiate file object
* $file -> rename('/var/www/'); //Move file to /var/www/
* $file -> rename('/var/www/', true); //Move file to /var/www/ and overwrite if it already exists
* </code>
*
* @param string $destinationPath The destination directory
* @param boolean $overwrite If true, overwrite existing file with the same name
* @return EfrontFile The copied file
* @since 3.5.0
* @access public
*/
public function rename($destinationPath, $overwrite = false) {
if (eF_checkParameter($destinationPath, 'path') === false) {
throw new EfrontFileException(_ILLEGALFILENAME, EfrontFileException :: ILLEGAL_FILE_NAME);
}
$destinationPath = EfrontDirectory :: normalize($destinationPath);
$parentDirectory = new EfrontDirectory(dirname($destinationPath)); //This way we check integrity of destination
FileSystemTree::checkFile($destinationPath);
if (!$overwrite && (is_file($destinationPath))) {
throw new EfrontFileException(_CANNOTMOVEFILE.': '.$this['name'].', '._FILEALREADYEXISTS, EfrontFileException :: FILE_ALREADY_EXISTS);//Use plain Exception rather than EfrontFileException, since the latter is caught right from the following catch block
}
if ($this['path'] != $destinationPath) {
if (copy($this['path'], $destinationPath)) { //rename() acts as a move() function as well
unlink($this['path']);
$this['path'] = $destinationPath;
if ($this['id'] != -1) {
$this -> persist();
}
$this -> refresh();
} else {
throw new EfrontFileException(_CANNOTMOVEFILE, EfrontFileException :: UNKNOWN_ERROR);
}
}
}
/**
* Persist file values
*
* This function is used to persist any changed values
* of the file.
* <br/>Example:
* <code>
* $file = new EfrontFile(43); //Instantiate file object
* $file -> file['description'] = 'New description'; //Change a file's property
* $file -> persist(); //Persist changes
* </code>
*
* @return boolean true if everything is ok
* @since 3.5.0
* @access public
*/
public function persist() {
$fields = array('path' => str_replace(G_ROOTPATH, '', $this['path']),
'description' => $this['description'],
'groups_ID' => $this['groups_ID'],
'access' => $this['access'],
'shared' => $this['shared'],
'metadata' => $this['metadata']);
$ok = eF_updateTableData("files", $fields, "id=".$this['id']);
EfrontSearch :: removeText('files', $this['id'], 'data');
$fileMetadataArray = unserialize($this['metadata']);
foreach ($fileMetadataArray as $key => $value) {
EfrontSearch :: insertText($value, $this['id'], "files", "data");
}
return $ok;
}
/**
* Refresh object properties
*
* This function is used to refresh the object properties. It is useful
* for when some function outside the object, has updated the object properties
* This function does not apply to EfrontFile objects that don't have a database
* representation
* <br/>Example:
* <code>
* $file = new EfrontFile(432); //Instantiate object for file with id 432
* eF_updateTableData("files", array("original_name" => "new_name"), "id=".$file['id']); //Change the file attributes without using the object. This way, the $file object becomes outdated
* $file -> refresh(); //Refresh $file properties
* </code>
*
* @since 3.5.0
* @access public
*/
public function refresh() {
if ($this['id'] != -1) {
$result = eF_getTableData("files", "*", "id=".$this['id']);
$this['path'] = G_ROOTPATH.$result[0]['path'];
$this['description'] = $result[0]['description'];
$this['groups_ID'] = $result[0]['groups_ID'];
$this['access'] = $result[0]['access'];
$this['shared'] = $result[0]['shared'];
$this['metadata'] = $result[0]['metadata'];
}
$this['name'] = EfrontFile :: decode(basename($this['path']));
$this['directory'] = dirname($this['path']);
$this['extension'] = pathinfo($this['path'], PATHINFO_EXTENSION);
$this['size'] = round(filesize($this['path'])/1024, 2);
$this['timestamp'] = filemtime($this['path']);
$this['type'] = 'file';
$this['physical_name'] = basename($this['path']);
foreach ($pathParts = explode("/", $this['path']) as $key => $value) {
$pathParts[$key] = urlencode($value);
}
$this['url_path'] = implode("/", $pathParts);
}
/**
* Compress file
*
* @param string $zipName The name if the compressed file
* @param boolean $decode Whether the file name should be decoded
* @return EfrontFile The compressed file
* @since 3.6.1
* @access public
*/
public function compress($zipName = false, $decode = false) {
if (!$zipName) {
$zipName = $this['path'].'.zip';
} else {
$zipName = $this['directory'].'/'.(EfrontFile :: encode(basename($zipName)));
}
try { //This way we delete the file, if it already exists
$file = new EfrontFile($zipName);
$file -> delete();
} catch (Exception $e) {}
if ($GLOBALS['configuration']['zip_method'] == 'system') {
$dir = getcwd();
chdir($this['directory']);
$response = exec('zip -r "'.$zipName.'" '.$this['name'].' 2>&1', $output, $code);
chdir($dir);
if ($code != 0) {
throw new EfrontFileException(_COMMANDFAILEDWITHOUTPUT.': '.$response.". "._PERHAPSDONTSUPPORTZIP, EfrontFileException :: ERROR_ZIP_PROCESSING);
}
return new EfrontFile($zipName);
} else {
$zip = new ZipArchive;
if ($zip -> open($zipName, ZIPARCHIVE::CREATE ) === true) {
if ($decode) {
$zip -> addFile($this['path'], EfrontFile :: decode($this['name']));
} else {
$zip -> addFile($this['path'], $this['name']);
}
$zip -> close();
return new EfrontFile($zipName);
} else {
throw new EfrontFileException(_CANNOTOPENCOMPRESSEDFILE.': '.$this['path'], EfrontFileException :: ERROR_OPEN_ZIP);
}
}
}
/**
* Uncompress file
*
* This function is used to uncompress the current file.
* The uncompressed files will have a database representation, unless $addDb is set to false.
* The function supports zip and tar.gz files
* <br/>Example:
* <code>
* $file = new EfrontFile('/var/www/test.zip');
* $uncompressedFiles = $file -> uncompress();
* </code>
*
* @param boolean $addDB Whether to create a database representation for the extracted files
* @return array An array of EfrontFile objects or file paths (depending on wheter a database representation exists)
* @since 3.5.0
* @access public
*/
public function uncompress($addDB = true) {
if ($this['extension'] == 'zip') {
if ($GLOBALS['configuration']['zip_method'] == 'system') {
$blackList = explode(",", $GLOBALS['configuration']['file_black_list']);
$blackList[] = 'php';
$blackList[] = 'htaccess';
$blackList = '-x "*.'.implode('" "*.', $blackList).'"';
if ($GLOBALS['configuration']['file_white_list']) {
$whiteList = '"*.'.implode('" "*.', explode(",", $GLOBALS['configuration']['file_white_list'])).'"';
} else {
$whiteList = '';
}
if (defined("NO_CHECK_FILE_INTEGRITY") && NO_CHECK_FILE_INTEGRITY) {
$blackList = $whiteList = '';
}
$response = exec('unzip -qqο "'.$this['path'].'" '.$whiteList.' '.$blackList.' -d "'.$this['directory'].'" 2>&1', $output, $code);
if (stripos($response, 'caution') === false && stripos($response, 'warning') === false && $code != 0) {
throw new EfrontFileException(_COMMANDFAILEDWITHOUTPUT.': '.$response.". "._PERHAPSDONTSUPPORTZIP, EfrontFileException :: ERROR_ZIP_PROCESSING);
}
} else {
$zip = new ZipArchive;
if ($zip -> open($this['path']) === true && $zip -> extractTo($this['directory'])) {
for ($i = 0; $i < $zip -> numFiles; $i++) {
$file = $this['directory'].'/'.$zip -> getNameIndex($i);
try { //If the file is not allowed, then append to its extension '.ext'
FileSystemTree::checkFile($file);
} catch (EfrontFileException $e) {
$fileObj = new EfrontFile($file);
$fileObj -> rename($this['directory'].'/'.$zip -> getNameIndex($i).'.ext', true);
$file = $fileObj['path'];
}
$zipFiles[] = $file;
}
if ($this['id'] != -1 && $addDB) {
$importedFiles = FileSystemTree :: importFiles($zipFiles, $options);
return $importedFiles;
} else {
return $zipFiles;
}
} else {
throw new EfrontFileException(_CANNOTOPENCOMPRESSEDFILE.': '.$this['path'], EfrontFileException :: ERROR_OPEN_ZIP);
}
}
}
}
/**
* List contents of compressed file
*
* This function is used to list the contents of a compressed file.
* It returns an array with the file names contained in the archive
* <br/>Example:
* <code>
* $file = new EfrontFile('mydata.zip');
* $file -> listContents(); //Returns an array where values are the file names, along with their directory offset
* </code>
*
* @return array The contents of the compressed file
* @access public
* @since 3.6.0
*/
public function listContents() {
if ($this['extension'] == 'zip') {
$zipFiles = array();
if ($GLOBALS['configuration']['zip_method'] == 'system') {
//@todo: Implement for system calls as well
$tempfile = tempnam(dirname($this['path']), time());
$response = exec('unzip -qql "'.$this['path'].'" | awk \'{print $4}\' > "'.$tempfile.'" 2>&1', $output, $code);
if ($code != 0) {
throw new EfrontFileException(_COMMANDFAILEDWITHOUTPUT.': '.$response.". "._PERHAPSDONTSUPPORTZIP, EfrontFileException :: ERROR_ZIP_PROCESSING);
}
foreach (file($tempfile) as $value) {
$zipFiles[] = trim($value);
}
unlink($tempfile);
return $zipFiles;
} else {
$zip = new ZipArchive;
if ($zip -> open($this['path'])) {
for ($i = 0; $i < $zip -> numFiles; $i++) {
$zipFiles[] = $zip -> getNameIndex($i);
}
return $zipFiles;
} else {
throw new EfrontFileException(_CANNOTOPENCOMPRESSEDFILE.': '.$this['path'], EfrontFileException :: ERROR_OPEN_ZIP);
}
}
} else {
throw new EFrontFileException(_UNSUPPORTEDFILETYPE.': '.$this['extension'], EfrontFileException :: UNKNOWN_COMPRESSION);
}
}
/**
* Get the image for the file type
*
* This function returns the url to an image representing the current
* file type.
* <br/>Example:
* <code>
* echo $file -> getTypeImage(); //Returns something like 'images/16x16/zip.png' if it's a zip file
* </code>
*
* @return string The url to the image representing the file type
* @since 3.5.0
* @access public
*/
public function getTypeImage() {
if (is_file(G_DEFAULTIMAGESPATH.'file_types/'.$this['extension'].'.png') || is_file(G_IMAGESPATH.'file_types/'.$this['extension'].'.png')) {
$image = 'images/file_types/'.$this['extension'].'.png';
} else {
$image = 'images/file_types/unknown.png';
}
return $image;
}
/**
* Share file
*
* This function is used to make the current file available to the lesson's
* students. A file can be made available to a single lesson only.
* <br/>Example:
* <code>
* $file = new EfrontFile(43);
* $file -> share(); //The file is now visible to the shared files list
* $file -> unshare(); //The file was made hidden again
* </code>
*
* @param int $lessonId A specific lesson to share this file for
* @since 3.5.0
* @access public
*/
public function share($lessonId = false) {
if (!$lessonId) {
$result = eF_getTableData("lessons", "share_folder", "id=".$_SESSION['s_lessons_ID']);
$lessonId = !$result[0]['share_folder'] ? $_SESSION['s_lessons_ID'] : $result[0]['share_folder'];
}
if ($lessonId) {
if ($this['id'] == -1) { //If the file does not have a database representation, create one for it
$newList = FileSystemTree :: importFiles($this['path']);
$this['id'] = key($newList);
$this -> refresh();
}
$this['shared'] = $lessonId;
$this -> persist();
} else {
throw new EfrontFileException(_CANNOTSHAREFILE.': '.$this['path'], EfrontFileException :: NOT_LESSON_FILE);
}
}
/**
* Unshare file
*
* This function is used to make the current file unavailable to the lesson's
* students. It must belong to a lesson (that is, it must have a lesson id)
* in order to do so.
* <br/>Example:
* <code>
* $file = new EfrontFile(43);
* $file -> share(); //The file is now visible to the shared files list
* $file -> unshare(); //The file was made hidden again
* </code>
*
* @since 3.5.0
* @access public
*/
public function unshare() {
$this['shared'] = 0;
$this -> persist();
}
/**
* Print a link with tooltip
*
* This function is used to print a file link with a popup tooltip
* containing information on this file. The link must be provided
* and optionally the information.
* <br/>Example:
* <code>
* $link = 'view_file.php?file=23';
* echo $file -> toHTMLTooltipLink($link);
* </code>
*
* @param string $link The link to print
* @param boolean $preview Whether to display link in a preview panel
* @since 3.5.0
* @access public
*/
public function toHTMLTooltipLink($link, $preview = true, $tableId = 'filesTable') {
$classes[] = 'info'; //This array holds the link css classes
if (!$link) {
$link = 'javascript:void(0)';
$classes[] = 'inactiveLink';
}
$tooltipString =
<a href = "'.$link.'" class = "'.implode(" ", $classes).'" style = "vertical-align:middle;" '.($preview ? 'onclick = "eF_js_showDivPopup(event, \''._PREVIEW.'\', 2, \'preview_table_'.$tableId.'\')" target = "PREVIEW_FRAME"' : '').'>
'.$this -> offsetGet('name').
<span class = "tooltipSpan">';
foreach ($this as $key => $value) {
if ($value) {
switch ($key) {
//case 'path' : $tooltipString .= '<div style = "white-space:nowrap"><strong>'._PHYSICALNAME."</strong>: ".basename($value)."<br/></div>"; break;
case 'users_LOGIN' : $tooltipString .= '<strong>'._USER."</strong>: $value<br/>"; break;
case 'timestamp' : $tooltipString .= '<strong>'._LASTMODIFIED."</strong>: ".formatTimestamp($value, 'time_nosec')."<br/>"; break;
//case 'shared' : $tooltipString .= '<strong>'._SHARED."</strong>: $value<br/>"; break;
case 'mime_type' : $tooltipString .= '<strong>'._MIMETYPE."</strong>: $value<br/>"; break;
default: break;
}
}
}
$tooltipString .= '</span></a>';
return $tooltipString;
}
/**
* Encode file name
*
* This function is used to encode the given name, based on the current
* configuration options.
* <br/>Example:
* <code>
* $name = 'some name'; //The name to encode
* $newName = EfrontFile :: encode($name); //Encodeded version of name
* </code>
* A little word about the need of encoding:
* Throughut eFront UTF-8 is used as encoding. When uploading a file, for example, its name is encoded
* in UTF-8, and with this name is stored in the filesystem. This does not cause any problems, when the
* OS is UTF8-aware, for example in most Linux distributions. However, for Windows installations, this
* causes major side-effects: The file name is messed up. On the other hand, when trying to access the file,
* the encoding is still in UTF8, so that many browsers, for example FireFox, have no problem in accessing
* the file, using its initial, UTF8-encoded, correct name. Unfortunately, Internet Explorer (6,7) cannot access
* the file at all.
* So when using a windows server, we must encode non-latin characters in order to be able to access any
* uploaded files with international characters. The most (if not the only) convenient encoding is UTF7-IMAP, which is a
* version of UTF-7 without the filesystem incompatible characters (see http://tools.ietf.org/html/rfc3501#section-5.1.3)
* If we are sure that only the native windows language will be used for file names, there is a somewhat better solution
* than using UTF7-IMAP (which scrambles the file names in the file system). We could use the native windows encoding.
* For example, for greek, the native windows encoding is windows-1253 (ISO-8859-7 is also supported). So, instead of
* UTF7-IMAP, we select this encoding and everything works like a charm. Except for filenames with characters other
* than latin and greek, of course.
*
* @param string $name The filename to encode
* @return string The encoded file name
* @since 3.5.0
* @access public
* @static
*/
public static function encode($name) {
$newName = $name;
if ($GLOBALS['configuration']['file_encoding']) {
if (in_array($GLOBALS['configuration']['file_encoding'], mb_list_encodings())) {
$newName = mb_convert_encoding($name, $GLOBALS['configuration']['file_encoding'], "UTF-8");
} else {
$newName = mb_convert_encoding($name, "UTF7-IMAP", "UTF-8");
}
}
return $newName;
}
/**
* Decode filename
*
* This function is the opposite of encode() and is used to convert a file name
* back to UTF8
* <br/>Example:
* <code>
* $name = EfrontFile :: decode($encodedName);
* </code>
*
* @param string $name The encoded name
* @return string The decoded name
* @since 3.5.0
* @access public
* @static
* @see EfrontFile :: encode()
*/
public static function decode($name) {
$newName = $name;
if ($GLOBALS['configuration']['file_encoding']) {
if (in_array($GLOBALS['configuration']['file_encoding'], mb_list_encodings())) {
$newName = mb_convert_encoding($name, "UTF-8", $GLOBALS['configuration']['file_encoding']);
} else {
$newName = mb_convert_encoding($name, "UTF-8", "UTF7-IMAP");
}
}
return $newName;
}
/**
* Send file to browser
*
* This function reads a file from disk and outputs it to the client, sending appropriate headers
* @param boolena $attachment Whether to send as an attachment or inline
* @since 3.6.3
* @access public
*/
public function sendFile($attachment = false) {
session_write_close(); //to allow the browser proceeding to other pages as well
if ($attachment) {
$browser = detectBrowser();
//because of #834
if ($browser != 'firefox') {
$this['name'] = urlencode(str_replace(" ", "_", $this['name']));
} else {
$this['name'] = str_replace(" ", "_", $this['name']);
}
header("Content-Description: File Transfer");
header("Content-Type: application/octet-stream");
header('Content-Disposition: attachment; filename="'.$this['name'].'"');
header("Content-Transfer-Encoding: binary");
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
header("Content-Type: application/force-download");
header("Content-Type: application/download");
if (defined('NO_OUTPUT_BUFFERING') || !$GLOBALS['configuration']['gz_handler']) {
//This does not cooperate well with gzhandler
header("Content-Length: ".filesize($this['path']));
}
} else {
header("Content-Description: File Transfer");
header("Content-Type: {$this['mime_type']}");
header('Content-Disposition: inline; filename="'.$this['name'].'"');
header("Content-Transfer-Encoding: binary");
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
}
// readfile($this['path']);
$this -> readfileChunked($this['path']);
exit;
}
/**
* http://www.php.net/manual/en/function.readfile.php
*
* @see readfile
*/
private function readfileChunked($filename,$retbytes=true) {
$chunksize = 1*(1024*1024); // how many bytes per chunk
$buffer = '';
$cnt =0;
// $handle = fopen($filename, 'rb');
$handle = fopen($filename, 'rb');
if ($handle === false) {
return false;
}
while (!feof($handle)) {
$buffer = fread($handle, $chunksize);
echo $buffer;
ob_flush();
flush();
if ($retbytes) {
$cnt += strlen($buffer);
}
}
$status = fclose($handle);
if ($retbytes && $status) {
return $cnt; // return num. bytes delivered like readfile() does.
}
return $status;
}
}
/**
* Class for directories in Efront file system
*
* @since 3.5.0
* @package eFront
*/
class EfrontDirectory extends ArrayObject
{
/**
* Class constructor
*
* The class constructor instantiates the object based on the $directory parameter.
* $directory may be either:
* - an array with directory attributes
* - a directory id
* - the full path to a physical directory
* - the full path to a directory using its original directory name
* <br/>Example:
* <code>