forked from moodle/moodle
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfilelib.php
2114 lines (1914 loc) · 82 KB
/
filelib.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 //$Id$
define('BYTESERVING_BOUNDARY', 's1k2o3d4a5k6s7'); //unique string constant
require_once("$CFG->libdir/file/file_exceptions.php");
require_once("$CFG->libdir/file/file_storage.php");
require_once("$CFG->libdir/file/file_browser.php");
require_once("$CFG->libdir/packer/zip_packer.php");
function get_file_url($path, $options=null, $type='coursefile') {
global $CFG, $HTTPSPAGEREQUIRED;
$path = str_replace('//', '/', $path);
$path = trim($path, '/'); // no leading and trailing slashes
// type of file
switch ($type) {
case 'questionfile':
$url = $CFG->wwwroot."/question/exportfile.php";
break;
case 'rssfile':
$url = $CFG->wwwroot."/rss/file.php";
break;
case 'user':
if (!empty($HTTPSPAGEREQUIRED)) {
$wwwroot = $CFG->httpswwwroot;
}
else {
$wwwroot = $CFG->wwwroot;
}
$url = $wwwroot."/user/pix.php";
break;
case 'usergroup':
$url = $CFG->wwwroot."/user/grouppix.php";
break;
case 'httpscoursefile':
$url = $CFG->httpswwwroot."/file.php";
break;
case 'coursefile':
default:
$url = $CFG->wwwroot."/file.php";
}
if ($CFG->slasharguments) {
$parts = explode('/', $path);
$parts = array_map('rawurlencode', $parts);
$path = implode('/', $parts);
$ffurl = $url.'/'.$path;
$separator = '?';
} else {
$path = rawurlencode('/'.$path);
$ffurl = $url.'?file='.$path;
$separator = '&';
}
if ($options) {
foreach ($options as $name=>$value) {
$ffurl = $ffurl.$separator.$name.'='.$value;
$separator = '&';
}
}
return $ffurl;
}
/**
* Returns empty user upload draft area information
* @return int draftareaid
*/
function file_get_new_draftitemid() {
global $DB, $USER;
if (isguestuser() or !isloggedin()) {
// guests and not-logged-in users can not be allowed to upload anything!
print_error('noguest');
}
$contextid = get_context_instance(CONTEXT_USER, $USER->id)->id;
$filearea = 'user_draft';
$fs = get_file_storage();
$draftitemid = rand(1, 999999999);
while ($files = $fs->get_area_files($contextid, $filearea, $draftitemid)) {
$draftitemid = rand(1, 999999999);
}
return $draftitemid;
}
/**
* Creates new draft area if not exists yet and copies files there
* @param int &$draftitemid
* @param int $contextid
* @param string $filearea
* @param int $itemid (null menas no existing files yet)
* @param bool subdirs allow directory structure
* @param string $text usually html text with embedded links to draft area
* @param boolean $forcehttps force https
* @return string text with relative links starting with @@PLUGINFILE@@
*/
function file_prepare_draftarea(&$draftitemid, $contextid, $filearea, $itemid, $subdirs=false, $text=null, $forcehttps=false) {
global $CFG, $USER;
$usercontext = get_context_instance(CONTEXT_USER, $USER->id);
$fs = get_file_storage();
if (empty($draftitemid)) {
// create a new area and copy existing files into
$draftitemid = file_get_new_draftitemid();
$file_record = array('contextid'=>$usercontext->id, 'filearea'=>'user_draft', 'itemid'=>$draftitemid);
if (!is_null($itemid) and $files = $fs->get_area_files($contextid, $filearea, $itemid)) {
foreach ($files as $file) {
if (!$subdirs and ($file->is_directory() or $file->get_filepath() !== '/')) {
continue;
}
$fs->create_file_from_storedfile($file_record, $file);
}
}
} else {
// nothing to do
}
if (is_null($text)) {
return null;
}
/// relink embedded files - editor can not handle @@PLUGINFILE@@ !
if ($CFG->slasharguments) {
$draftbase = "$CFG->wwwroot/draftfile.php/$usercontext->id/user_draft/$draftitemid/";
} else {
$draftbase = "$CFG->wwwroot/draftfile.php?file=/$usercontext->id/user_draft/$draftitemid/";
}
if ($forcehttps) {
$draftbase = str_replace('http://', 'https://', $draftbase);
}
$text = str_replace('@@PLUGINFILE@@/', $draftbase);
return $text;
}
/**
* Returns information about files in draft area
* @param <type> $draftitemid
* @return array TODO: count=>n
*/
function get_draftarea_info($draftitemid) {
global $CFG, $USER;
$usercontext = get_context_instance(CONTEXT_USER, $USER->id);
$fs = get_file_storage();
// number of files
$draftfiles = $fs->get_area_files($usercontext->id, 'user_draft', $draftitemid, 'id', false);
return array('filecount'=>count($draftfiles));
}
/**
* Converts absolute links in text and merges draft files to target area.
* @param int $draftitemid
* @param int $contextid
* @param string $filearea
* @param int $itemid
* @param bool subdirs allow directory structure
* @param string $text usually html text with embedded links to draft area
* @param boolean $forcehttps force https
* @return string text with relative links starting with @@PLUGINFILE@@
*/
function file_convert_draftarea($draftitemid, $contextid, $filearea, $itemid, $subdirs=false, $text=null, $forcehttps=false) {
global $CFG, $USER;
$usercontext = get_context_instance(CONTEXT_USER, $USER->id);
$fs = get_file_storage();
$draftfiles = $fs->get_area_files($usercontext->id, 'user_draft', $draftitemid, 'id');
$oldfiles = $fs->get_area_files($contextid, $filearea, $itemid, 'id');
if (count($draftfiles) < 2) {
// means there are no files - one file means root dir only ;-)
$fs->delete_area_files($contextid, $filearea, $itemid);
} else if (count($oldfiles) < 2) {
// there were no files before - one file means root dir only ;-)
$fs->delete_area_files($contextid, $filearea, $itemid);
$file_record = array('contextid'=>$contextid, 'filearea'=>$filearea, 'itemid'=>$itemid);
foreach ($draftfiles as $file) {
if (!$subdirs and $file->get_filepath() !== '/') {
continue;
}
$fs->create_file_from_storedfile($file_record, $file);
}
} else {
// we have to merge old and new files - we want to keep file ids for files that were not changed
$file_record = array('contextid'=>$contextid, 'filearea'=>$filearea, 'itemid'=>$itemid);
foreach ($draftfiles as $file) {
if (!$subdirs and $file->get_filepath() !== '/') {
continue;
}
$newhash = sha1($contextid.$filearea.$itemid.$file->get_filepath().$file->get_filename());
if (isset($oldfiles[$newhash])) {
$oldfile = $oldfiles[$newhash];
unset($oldfiles[$newhash]); // do not delete afterwards
if (!$file->is_directory()) {
if ($file->get_contenthash() === $oldfile->get_contenthash()) {
// file was not changed at all
continue;
} else {
// file changed, delete the original
$oldfile->delete();
}
}
}
$fs->create_file_from_storedfile($file_record, $file);
}
// cleanup deleted files and dirs
foreach ($oldfiles as $file) {
$file->delete();
}
}
// purge the draft area
$fs->delete_area_files($usercontext->id, 'user_draft', $draftitemid);
if (is_null($text)) {
return null;
}
/// relink embedded files if text submitted - no absolute links allowed in database!
if ($CFG->slasharguments) {
$draftbase = "$CFG->wwwroot/draftfile.php/$usercontext->id/user_draft/$draftitemid/";
} else {
$draftbase = "$CFG->wwwroot/draftfile.php?file=/$usercontext->id/user_draft/$draftitemid/";
}
if ($forcehttps) {
$draftbase = str_replace('http://', 'https://', $draftbase);
}
$text = str_ireplace($draftbase, '@@PLUGINFILE@@/');
return $text;
}
/**
* Returns description of upload error
* @param int $errorcode found in $_FILES['filename.ext']['error']
* @return error description string, '' if ok
*/
function file_get_upload_error($errorcode) {
switch ($errorcode) {
case 0: // UPLOAD_ERR_OK - no error
$errmessage = '';
break;
case 1: // UPLOAD_ERR_INI_SIZE
$errmessage = get_string('uploadserverlimit');
break;
case 2: // UPLOAD_ERR_FORM_SIZE
$errmessage = get_string('uploadformlimit');
break;
case 3: // UPLOAD_ERR_PARTIAL
$errmessage = get_string('uploadpartialfile');
break;
case 4: // UPLOAD_ERR_NO_FILE
$errmessage = get_string('uploadnofilefound');
break;
// Note: there is no error with a value of 5
case 6: // UPLOAD_ERR_NO_TMP_DIR
$errmessage = get_string('uploadnotempdir');
break;
case 7: // UPLOAD_ERR_CANT_WRITE
$errmessage = get_string('uploadcantwrite');
break;
case 8: // UPLOAD_ERR_EXTENSION
$errmessage = get_string('uploadextension');
break;
default:
$errmessage = get_string('uploadproblem');
}
return $errmessage;
}
/**
* Fetches content of file from Internet (using proxy if defined). Uses cURL extension if present.
* Due to security concerns only downloads from http(s) sources are supported.
*
* @param string $url file url starting with http(s)://
* @param array $headers http headers, null if none. If set, should be an
* associative array of header name => value pairs.
* @param array $postdata array means use POST request with given parameters
* @param bool $fullresponse return headers, responses, etc in a similar way snoopy does
* (if false, just returns content)
* @param int $timeout timeout for complete download process including all file transfer
* (default 5 minutes)
* @param int $connecttimeout timeout for connection to server; this is the timeout that
* usually happens if the remote server is completely down (default 20 seconds);
* may not work when using proxy
* @param bool $skipcertverify If true, the peer's SSL certificate will not be checked. Only use this when already in a trusted location.
* @return mixed false if request failed or content of the file as string if ok.
*/
function download_file_content($url, $headers=null, $postdata=null, $fullresponse=false, $timeout=300, $connecttimeout=20, $skipcertverify=false) {
global $CFG;
// some extra security
$newlines = array("\r", "\n");
if (is_array($headers) ) {
foreach ($headers as $key => $value) {
$headers[$key] = str_replace($newlines, '', $value);
}
}
$url = str_replace($newlines, '', $url);
if (!preg_match('|^https?://|i', $url)) {
if ($fullresponse) {
$response = new object();
$response->status = 0;
$response->headers = array();
$response->response_code = 'Invalid protocol specified in url';
$response->results = '';
$response->error = 'Invalid protocol specified in url';
return $response;
} else {
return false;
}
}
// check if proxy (if used) should be bypassed for this url
$proxybypass = is_proxybypass( $url );
if (!extension_loaded('curl') or ($ch = curl_init($url)) === false) {
require_once($CFG->libdir.'/snoopy/Snoopy.class.inc');
$snoopy = new Snoopy();
$snoopy->read_timeout = $timeout;
$snoopy->_fp_timeout = $connecttimeout;
if (!$proxybypass) {
$snoopy->proxy_host = $CFG->proxyhost;
$snoopy->proxy_port = $CFG->proxyport;
if (!empty($CFG->proxyuser) and !empty($CFG->proxypassword)) {
// this will probably fail, but let's try it anyway
$snoopy->proxy_user = $CFG->proxyuser;
$snoopy->proxy_password = $CFG->proxypassword;
}
}
if (is_array($headers) ) {
$client->rawheaders = $headers;
}
if (is_array($postdata)) {
$fetch = @$snoopy->fetch($url, $postdata); // use more specific debug code bellow
} else {
$fetch = @$snoopy->fetch($url); // use more specific debug code bellow
}
if ($fetch) {
if ($fullresponse) {
//fix header line endings
foreach ($snoopy->headers as $key=>$unused) {
$snoopy->headers[$key] = trim($snoopy->headers[$key]);
}
$response = new object();
$response->status = $snoopy->status;
$response->headers = $snoopy->headers;
$response->response_code = trim($snoopy->response_code);
$response->results = $snoopy->results;
$response->error = $snoopy->error;
return $response;
} else if ($snoopy->status != 200) {
debugging("Snoopy request for \"$url\" failed, http response code: ".$snoopy->response_code, DEBUG_ALL);
return false;
} else {
return $snoopy->results;
}
} else {
if ($fullresponse) {
$response = new object();
$response->status = $snoopy->status;
$response->headers = array();
$response->response_code = $snoopy->response_code;
$response->results = '';
$response->error = $snoopy->error;
return $response;
} else {
debugging("Snoopy request for \"$url\" failed with: ".$snoopy->error, DEBUG_ALL);
return false;
}
}
}
// set extra headers
if (is_array($headers) ) {
$headers2 = array();
foreach ($headers as $key => $value) {
$headers2[] = "$key: $value";
}
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers2);
}
if ($skipcertverify) {
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
}
// use POST if requested
if (is_array($postdata)) {
foreach ($postdata as $k=>$v) {
$postdata[$k] = urlencode($k).'='.urlencode($v);
}
$postdata = implode('&', $postdata);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postdata);
}
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $connecttimeout);
curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
if (!ini_get('open_basedir') and !ini_get('safe_mode')) {
// TODO: add version test for '7.10.5'
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_MAXREDIRS, 5);
}
if (!empty($CFG->proxyhost) and !$proxybypass) {
// SOCKS supported in PHP5 only
if (!empty($CFG->proxytype) and ($CFG->proxytype == 'SOCKS5')) {
if (defined('CURLPROXY_SOCKS5')) {
curl_setopt($ch, CURLOPT_PROXYTYPE, CURLPROXY_SOCKS5);
} else {
curl_close($ch);
if ($fullresponse) {
$response = new object();
$response->status = '0';
$response->headers = array();
$response->response_code = 'SOCKS5 proxy is not supported in PHP4';
$response->results = '';
$response->error = 'SOCKS5 proxy is not supported in PHP4';
return $response;
} else {
debugging("SOCKS5 proxy is not supported in PHP4.", DEBUG_ALL);
return false;
}
}
}
curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, false);
if (empty($CFG->proxyport)) {
curl_setopt($ch, CURLOPT_PROXY, $CFG->proxyhost);
} else {
curl_setopt($ch, CURLOPT_PROXY, $CFG->proxyhost.':'.$CFG->proxyport);
}
if (!empty($CFG->proxyuser) and !empty($CFG->proxypassword)) {
curl_setopt($ch, CURLOPT_PROXYUSERPWD, $CFG->proxyuser.':'.$CFG->proxypassword);
if (defined('CURLOPT_PROXYAUTH')) {
// any proxy authentication if PHP 5.1
curl_setopt($ch, CURLOPT_PROXYAUTH, CURLAUTH_BASIC | CURLAUTH_NTLM);
}
}
}
$data = curl_exec($ch);
// try to detect encoding problems
if ((curl_errno($ch) == 23 or curl_errno($ch) == 61) and defined('CURLOPT_ENCODING')) {
curl_setopt($ch, CURLOPT_ENCODING, 'none');
$data = curl_exec($ch);
}
if (curl_errno($ch)) {
$error = curl_error($ch);
$error_no = curl_errno($ch);
curl_close($ch);
if ($fullresponse) {
$response = new object();
if ($error_no == 28) {
$response->status = '-100'; // mimic snoopy
} else {
$response->status = '0';
}
$response->headers = array();
$response->response_code = $error;
$response->results = '';
$response->error = $error;
return $response;
} else {
debugging("cURL request for \"$url\" failed with: $error ($error_no)", DEBUG_ALL);
return false;
}
} else {
$info = curl_getinfo($ch);
curl_close($ch);
if (empty($info['http_code'])) {
// for security reasons we support only true http connections (Location: file:// exploit prevention)
$response = new object();
$response->status = '0';
$response->headers = array();
$response->response_code = 'Unknown cURL error';
$response->results = ''; // do NOT change this!
$response->error = 'Unknown cURL error';
} else {
// strip redirect headers and get headers array and content
$data = explode("\r\n\r\n", $data, $info['redirect_count'] + 2);
$results = array_pop($data);
$headers = array_pop($data);
$headers = explode("\r\n", trim($headers));
$response = new object();;
$response->status = (string)$info['http_code'];
$response->headers = $headers;
$response->response_code = $headers[0];
$response->results = $results;
$response->error = '';
}
if ($fullresponse) {
return $response;
} else if ($info['http_code'] != 200) {
debugging("cURL request for \"$url\" failed, HTTP response code: ".$response->response_code, DEBUG_ALL);
return false;
} else {
return $response->results;
}
}
}
/**
* @return List of information about file types based on extensions.
* Associative array of extension (lower-case) to associative array
* from 'element name' to data. Current element names are 'type' and 'icon'.
* Unknown types should use the 'xxx' entry which includes defaults.
*/
function get_mimetypes_array() {
static $mimearray = array (
'xxx' => array ('type'=>'document/unknown', 'icon'=>'unknown.gif'),
'3gp' => array ('type'=>'video/quicktime', 'icon'=>'video.gif'),
'ai' => array ('type'=>'application/postscript', 'icon'=>'image.gif'),
'aif' => array ('type'=>'audio/x-aiff', 'icon'=>'audio.gif'),
'aiff' => array ('type'=>'audio/x-aiff', 'icon'=>'audio.gif'),
'aifc' => array ('type'=>'audio/x-aiff', 'icon'=>'audio.gif'),
'applescript' => array ('type'=>'text/plain', 'icon'=>'text.gif'),
'asc' => array ('type'=>'text/plain', 'icon'=>'text.gif'),
'asm' => array ('type'=>'text/plain', 'icon'=>'text.gif'),
'au' => array ('type'=>'audio/au', 'icon'=>'audio.gif'),
'avi' => array ('type'=>'video/x-ms-wm', 'icon'=>'avi.gif'),
'bmp' => array ('type'=>'image/bmp', 'icon'=>'image.gif'),
'c' => array ('type'=>'text/plain', 'icon'=>'text.gif'),
'cct' => array ('type'=>'shockwave/director', 'icon'=>'flash.gif'),
'cpp' => array ('type'=>'text/plain', 'icon'=>'text.gif'),
'cs' => array ('type'=>'application/x-csh', 'icon'=>'text.gif'),
'css' => array ('type'=>'text/css', 'icon'=>'text.gif'),
'csv' => array ('type'=>'text/csv', 'icon'=>'excel.gif'),
'dv' => array ('type'=>'video/x-dv', 'icon'=>'video.gif'),
'dmg' => array ('type'=>'application/octet-stream', 'icon'=>'dmg.gif'),
'doc' => array ('type'=>'application/msword', 'icon'=>'word.gif'),
'docx' => array ('type'=>'application/vnd.openxmlformats-officedocument.wordprocessingml.document', 'icon'=>'docx.gif'),
'docm' => array ('type'=>'application/vnd.ms-word.document.macroEnabled.12', 'icon'=>'docm.gif'),
'dotx' => array ('type'=>'application/vnd.openxmlformats-officedocument.wordprocessingml.template', 'icon'=>'dotx.gif'),
'dotm' => array ('type'=>'application/vnd.ms-word.template.macroEnabled.12', 'icon'=>'dotm.gif'),
'dcr' => array ('type'=>'application/x-director', 'icon'=>'flash.gif'),
'dif' => array ('type'=>'video/x-dv', 'icon'=>'video.gif'),
'dir' => array ('type'=>'application/x-director', 'icon'=>'flash.gif'),
'dxr' => array ('type'=>'application/x-director', 'icon'=>'flash.gif'),
'eps' => array ('type'=>'application/postscript', 'icon'=>'pdf.gif'),
'fdf' => array ('type'=>'application/pdf', 'icon'=>'pdf.gif'),
'flv' => array ('type'=>'video/x-flv', 'icon'=>'video.gif'),
'gif' => array ('type'=>'image/gif', 'icon'=>'image.gif'),
'gtar' => array ('type'=>'application/x-gtar', 'icon'=>'zip.gif'),
'tgz' => array ('type'=>'application/g-zip', 'icon'=>'zip.gif'),
'gz' => array ('type'=>'application/g-zip', 'icon'=>'zip.gif'),
'gzip' => array ('type'=>'application/g-zip', 'icon'=>'zip.gif'),
'h' => array ('type'=>'text/plain', 'icon'=>'text.gif'),
'hpp' => array ('type'=>'text/plain', 'icon'=>'text.gif'),
'hqx' => array ('type'=>'application/mac-binhex40', 'icon'=>'zip.gif'),
'htc' => array ('type'=>'text/x-component', 'icon'=>'text.gif'),
'html' => array ('type'=>'text/html', 'icon'=>'html.gif'),
'xhtml'=> array ('type'=>'application/xhtml+xml', 'icon'=>'html.gif'),
'htm' => array ('type'=>'text/html', 'icon'=>'html.gif'),
'ico' => array ('type'=>'image/vnd.microsoft.icon', 'icon'=>'image.gif'),
'ics' => array ('type'=>'text/calendar', 'icon'=>'text.gif'),
'isf' => array ('type'=>'application/inspiration', 'icon'=>'isf.gif'),
'ist' => array ('type'=>'application/inspiration.template', 'icon'=>'isf.gif'),
'java' => array ('type'=>'text/plain', 'icon'=>'text.gif'),
'jcb' => array ('type'=>'text/xml', 'icon'=>'jcb.gif'),
'jcl' => array ('type'=>'text/xml', 'icon'=>'jcl.gif'),
'jcw' => array ('type'=>'text/xml', 'icon'=>'jcw.gif'),
'jmt' => array ('type'=>'text/xml', 'icon'=>'jmt.gif'),
'jmx' => array ('type'=>'text/xml', 'icon'=>'jmx.gif'),
'jpe' => array ('type'=>'image/jpeg', 'icon'=>'image.gif'),
'jpeg' => array ('type'=>'image/jpeg', 'icon'=>'image.gif'),
'jpg' => array ('type'=>'image/jpeg', 'icon'=>'image.gif'),
'jqz' => array ('type'=>'text/xml', 'icon'=>'jqz.gif'),
'js' => array ('type'=>'application/x-javascript', 'icon'=>'text.gif'),
'latex'=> array ('type'=>'application/x-latex', 'icon'=>'text.gif'),
'm' => array ('type'=>'text/plain', 'icon'=>'text.gif'),
'mov' => array ('type'=>'video/quicktime', 'icon'=>'video.gif'),
'movie'=> array ('type'=>'video/x-sgi-movie', 'icon'=>'video.gif'),
'm3u' => array ('type'=>'audio/x-mpegurl', 'icon'=>'audio.gif'),
'mp3' => array ('type'=>'audio/mp3', 'icon'=>'audio.gif'),
'mp4' => array ('type'=>'video/mp4', 'icon'=>'video.gif'),
'mpeg' => array ('type'=>'video/mpeg', 'icon'=>'video.gif'),
'mpe' => array ('type'=>'video/mpeg', 'icon'=>'video.gif'),
'mpg' => array ('type'=>'video/mpeg', 'icon'=>'video.gif'),
'odt' => array ('type'=>'application/vnd.oasis.opendocument.text', 'icon'=>'odt.gif'),
'ott' => array ('type'=>'application/vnd.oasis.opendocument.text-template', 'icon'=>'odt.gif'),
'oth' => array ('type'=>'application/vnd.oasis.opendocument.text-web', 'icon'=>'odt.gif'),
'odm' => array ('type'=>'application/vnd.oasis.opendocument.text-master', 'icon'=>'odm.gif'),
'odg' => array ('type'=>'application/vnd.oasis.opendocument.graphics', 'icon'=>'odg.gif'),
'otg' => array ('type'=>'application/vnd.oasis.opendocument.graphics-template', 'icon'=>'odg.gif'),
'odp' => array ('type'=>'application/vnd.oasis.opendocument.presentation', 'icon'=>'odp.gif'),
'otp' => array ('type'=>'application/vnd.oasis.opendocument.presentation-template', 'icon'=>'odp.gif'),
'ods' => array ('type'=>'application/vnd.oasis.opendocument.spreadsheet', 'icon'=>'ods.gif'),
'ots' => array ('type'=>'application/vnd.oasis.opendocument.spreadsheet-template', 'icon'=>'ods.gif'),
'odc' => array ('type'=>'application/vnd.oasis.opendocument.chart', 'icon'=>'odc.gif'),
'odf' => array ('type'=>'application/vnd.oasis.opendocument.formula', 'icon'=>'odf.gif'),
'odb' => array ('type'=>'application/vnd.oasis.opendocument.database', 'icon'=>'odb.gif'),
'odi' => array ('type'=>'application/vnd.oasis.opendocument.image', 'icon'=>'odi.gif'),
'pct' => array ('type'=>'image/pict', 'icon'=>'image.gif'),
'pdf' => array ('type'=>'application/pdf', 'icon'=>'pdf.gif'),
'php' => array ('type'=>'text/plain', 'icon'=>'text.gif'),
'pic' => array ('type'=>'image/pict', 'icon'=>'image.gif'),
'pict' => array ('type'=>'image/pict', 'icon'=>'image.gif'),
'png' => array ('type'=>'image/png', 'icon'=>'image.gif'),
'pps' => array ('type'=>'application/vnd.ms-powerpoint', 'icon'=>'powerpoint.gif'),
'ppt' => array ('type'=>'application/vnd.ms-powerpoint', 'icon'=>'powerpoint.gif'),
'pptx' => array ('type'=>'application/vnd.openxmlformats-officedocument.presentationml.presentation', 'icon'=>'pptx.gif'),
'pptm' => array ('type'=>'application/vnd.ms-powerpoint.presentation.macroEnabled.12', 'icon'=>'pptm.gif'),
'potx' => array ('type'=>'application/vnd.openxmlformats-officedocument.presentationml.template', 'icon'=>'potx.gif'),
'potm' => array ('type'=>'application/vnd.ms-powerpoint.template.macroEnabled.12', 'icon'=>'potm.gif'),
'ppam' => array ('type'=>'application/vnd.ms-powerpoint.addin.macroEnabled.12', 'icon'=>'ppam.gif'),
'ppsx' => array ('type'=>'application/vnd.openxmlformats-officedocument.presentationml.slideshow', 'icon'=>'ppsx.gif'),
'ppsm' => array ('type'=>'application/vnd.ms-powerpoint.slideshow.macroEnabled.12', 'icon'=>'ppsm.gif'),
'ps' => array ('type'=>'application/postscript', 'icon'=>'pdf.gif'),
'qt' => array ('type'=>'video/quicktime', 'icon'=>'video.gif'),
'ra' => array ('type'=>'audio/x-realaudio', 'icon'=>'audio.gif'),
'ram' => array ('type'=>'audio/x-pn-realaudio', 'icon'=>'audio.gif'),
'rhb' => array ('type'=>'text/xml', 'icon'=>'xml.gif'),
'rm' => array ('type'=>'audio/x-pn-realaudio', 'icon'=>'audio.gif'),
'rtf' => array ('type'=>'text/rtf', 'icon'=>'text.gif'),
'rtx' => array ('type'=>'text/richtext', 'icon'=>'text.gif'),
'sh' => array ('type'=>'application/x-sh', 'icon'=>'text.gif'),
'sit' => array ('type'=>'application/x-stuffit', 'icon'=>'zip.gif'),
'smi' => array ('type'=>'application/smil', 'icon'=>'text.gif'),
'smil' => array ('type'=>'application/smil', 'icon'=>'text.gif'),
'sqt' => array ('type'=>'text/xml', 'icon'=>'xml.gif'),
'svg' => array ('type'=>'image/svg+xml', 'icon'=>'image.gif'),
'svgz' => array ('type'=>'image/svg+xml', 'icon'=>'image.gif'),
'swa' => array ('type'=>'application/x-director', 'icon'=>'flash.gif'),
'swf' => array ('type'=>'application/x-shockwave-flash', 'icon'=>'flash.gif'),
'swfl' => array ('type'=>'application/x-shockwave-flash', 'icon'=>'flash.gif'),
'sxw' => array ('type'=>'application/vnd.sun.xml.writer', 'icon'=>'odt.gif'),
'stw' => array ('type'=>'application/vnd.sun.xml.writer.template', 'icon'=>'odt.gif'),
'sxc' => array ('type'=>'application/vnd.sun.xml.calc', 'icon'=>'odt.gif'),
'stc' => array ('type'=>'application/vnd.sun.xml.calc.template', 'icon'=>'odt.gif'),
'sxd' => array ('type'=>'application/vnd.sun.xml.draw', 'icon'=>'odt.gif'),
'std' => array ('type'=>'application/vnd.sun.xml.draw.template', 'icon'=>'odt.gif'),
'sxi' => array ('type'=>'application/vnd.sun.xml.impress', 'icon'=>'odt.gif'),
'sti' => array ('type'=>'application/vnd.sun.xml.impress.template', 'icon'=>'odt.gif'),
'sxg' => array ('type'=>'application/vnd.sun.xml.writer.global', 'icon'=>'odt.gif'),
'sxm' => array ('type'=>'application/vnd.sun.xml.math', 'icon'=>'odt.gif'),
'tar' => array ('type'=>'application/x-tar', 'icon'=>'zip.gif'),
'tif' => array ('type'=>'image/tiff', 'icon'=>'image.gif'),
'tiff' => array ('type'=>'image/tiff', 'icon'=>'image.gif'),
'tex' => array ('type'=>'application/x-tex', 'icon'=>'text.gif'),
'texi' => array ('type'=>'application/x-texinfo', 'icon'=>'text.gif'),
'texinfo' => array ('type'=>'application/x-texinfo', 'icon'=>'text.gif'),
'tsv' => array ('type'=>'text/tab-separated-values', 'icon'=>'text.gif'),
'txt' => array ('type'=>'text/plain', 'icon'=>'text.gif'),
'wav' => array ('type'=>'audio/wav', 'icon'=>'audio.gif'),
'wmv' => array ('type'=>'video/x-ms-wmv', 'icon'=>'avi.gif'),
'asf' => array ('type'=>'video/x-ms-asf', 'icon'=>'avi.gif'),
'xdp' => array ('type'=>'application/pdf', 'icon'=>'pdf.gif'),
'xfd' => array ('type'=>'application/pdf', 'icon'=>'pdf.gif'),
'xfdf' => array ('type'=>'application/pdf', 'icon'=>'pdf.gif'),
'xls' => array ('type'=>'application/vnd.ms-excel', 'icon'=>'excel.gif'),
'xlsx' => array ('type'=>'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', 'icon'=>'xlsx.gif'),
'xlsm' => array ('type'=>'application/vnd.ms-excel.sheet.macroEnabled.12', 'icon'=>'xlsm.gif'),
'xltx' => array ('type'=>'application/vnd.openxmlformats-officedocument.spreadsheetml.template', 'icon'=>'xltx.gif'),
'xltm' => array ('type'=>'application/vnd.ms-excel.template.macroEnabled.12', 'icon'=>'xltm.gif'),
'xlsb' => array ('type'=>'application/vnd.ms-excel.sheet.binary.macroEnabled.12', 'icon'=>'xlsb.gif'),
'xlam' => array ('type'=>'application/vnd.ms-excel.addin.macroEnabled.12', 'icon'=>'xlam.gif'),
'xml' => array ('type'=>'application/xml', 'icon'=>'xml.gif'),
'xsl' => array ('type'=>'text/xml', 'icon'=>'xml.gif'),
'zip' => array ('type'=>'application/zip', 'icon'=>'zip.gif')
);
return $mimearray;
}
/**
* Obtains information about a filetype based on its extension. Will
* use a default if no information is present about that particular
* extension.
* @param string $element Desired information (usually 'icon'
* for icon filename or 'type' for MIME type)
* @param string $filename Filename we're looking up
* @return string Requested piece of information from array
*/
function mimeinfo($element, $filename) {
$mimeinfo = get_mimetypes_array();
if (eregi('\.([a-z0-9]+)$', $filename, $match)) {
if (isset($mimeinfo[strtolower($match[1])][$element])) {
return $mimeinfo[strtolower($match[1])][$element];
} else {
return $mimeinfo['xxx'][$element]; // By default
}
} else {
return $mimeinfo['xxx'][$element]; // By default
}
}
/**
* Obtains information about a filetype based on the MIME type rather than
* the other way around.
* @param string $element Desired information (usually 'icon')
* @param string $mimetype MIME type we're looking up
* @return string Requested piece of information from array
*/
function mimeinfo_from_type($element, $mimetype) {
$mimeinfo = get_mimetypes_array();
foreach($mimeinfo as $values) {
if($values['type']==$mimetype) {
if(isset($values[$element])) {
return $values[$element];
}
break;
}
}
return $mimeinfo['xxx'][$element]; // Default
}
/**
* Get information about a filetype based on the icon file.
* @param string $element Desired information (usually 'icon')
* @param string $icon Icon file path.
* @param boolean $all return all matching entries (defaults to false - last match)
* @return string Requested piece of information from array
*/
function mimeinfo_from_icon($element, $icon, $all=false) {
$mimeinfo = get_mimetypes_array();
if (preg_match("/\/(.*)/", $icon, $matches)) {
$icon = $matches[1];
}
$info = array($mimeinfo['xxx'][$element]); // Default
foreach($mimeinfo as $values) {
if($values['icon']==$icon) {
if(isset($values[$element])) {
$info[] = $values[$element];
}
//No break, for example for 'excel.gif' we don't want 'csv'!
}
}
if ($all) {
return $info;
}
return array_pop($info); // Return last match (mimicking behaviour/comment inside foreach loop)
}
/**
* Obtains descriptions for file types (e.g. 'Microsoft Word document') from the
* mimetypes.php language file.
* @param string $mimetype MIME type (can be obtained using the mimeinfo function)
* @param bool $capitalise If true, capitalises first character of result
* @return string Text description
*/
function get_mimetype_description($mimetype,$capitalise=false) {
$result=get_string($mimetype,'mimetypes');
// Surrounded by square brackets indicates that there isn't a string for that
// (maybe there is a better way to find this out?)
if(strpos($result,'[')===0) {
$result=get_string('document/unknown','mimetypes');
}
if($capitalise) {
$result=ucfirst($result);
}
return $result;
}
/**
* Reprot file is not found or not accessible
* @return does not return, terminates script
*/
function send_file_not_found() {
global $CFG, $COURSE;
header('HTTP/1.0 404 not found');
print_error('filenotfound', 'error', $CFG->wwwroot.'/course/view.php?id='.$COURSE->id); //this is not displayed on IIS??
}
/**
* Handles the sending of temporary file to user, download is forced.
* File is deleted after abort or succesful sending.
* @param string $path path to file, preferably from moodledata/temp/something; or content of file itself
* @param string $filename proposed file name when saving file
* @param bool $path is content of file
* @return does not return, script terminated
*/
function send_temp_file($path, $filename, $pathisstring=false) {
global $CFG;
// close session - not needed anymore
@session_write_close();
if (!$pathisstring) {
if (!file_exists($path)) {
header('HTTP/1.0 404 not found');
print_error('filenotfound', 'error', $CFG->wwwroot.'/');
}
// executed after normal finish or abort
@register_shutdown_function('send_temp_file_finished', $path);
}
//IE compatibiltiy HACK!
if (ini_get('zlib.output_compression')) {
ini_set('zlib.output_compression', 'Off');
}
// if user is using IE, urlencode the filename so that multibyte file name will show up correctly on popup
if (check_browser_version('MSIE')) {
$filename = urlencode($filename);
}
$filesize = $pathisstring ? strlen($path) : filesize($path);
@header('Content-Disposition: attachment; filename='.$filename);
@header('Content-Length: '.$filesize);
if (strpos($CFG->wwwroot, 'https://') === 0) { //https sites - watch out for IE! KB812935 and KB316431
@header('Cache-Control: max-age=10');
@header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
@header('Pragma: ');
} else { //normal http - prevent caching at all cost
@header('Cache-Control: private, must-revalidate, pre-check=0, post-check=0, max-age=0');
@header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
@header('Pragma: no-cache');
}
@header('Accept-Ranges: none'); // Do not allow byteserving
while (@ob_end_flush()); //flush the buffers - save memory and disable sid rewrite
if ($pathisstring) {
echo $path;
} else {
@readfile($path);
}
die; //no more chars to output
}
/**
* Internal callnack function used by send_temp_file()
*/
function send_temp_file_finished($path) {
if (file_exists($path)) {
@unlink($path);
}
}
/**
* Handles the sending of file data to the user's browser, including support for
* byteranges etc.
* @param string $path Path of file on disk (including real filename), or actual content of file as string
* @param string $filename Filename to send
* @param int $lifetime Number of seconds before the file should expire from caches (default 24 hours)
* @param int $filter 0 (default)=no filtering, 1=all files, 2=html files only
* @param bool $pathisstring If true (default false), $path is the content to send and not the pathname
* @param bool $forcedownload If true (default false), forces download of file rather than view in browser/plugin
* @param string $mimetype Include to specify the MIME type; leave blank to have it guess the type from $filename
* @param bool $dontdie - return control to caller afterwards. this is not recommended and only used for cleanup tasks.
* if this is passed as true, ignore_user_abort is called. if you don't want your processing to continue on cancel,
* you must detect this case when control is returned using connection_aborted. Please not that session is closed
* and should not be reopened.
* @return no return or void, script execution stopped unless $dontdie is true
*/
function send_file($path, $filename, $lifetime = 'default' , $filter=0, $pathisstring=false, $forcedownload=false, $mimetype='', $dontdie=false) {
global $CFG, $COURSE, $SESSION;
if ($dontdie) {
ignore_user_abort(true);
}
// MDL-11789, apply $CFG->filelifetime here
if ($lifetime === 'default') {
if (!empty($CFG->filelifetime)) {
$lifetime = $CFG->filelifetime;
} else {
$lifetime = 86400;
}
}
session_write_close(); // unlock session during fileserving
// Use given MIME type if specified, otherwise guess it using mimeinfo.
// IE, Konqueror and Opera open html file directly in browser from web even when directed to save it to disk :-O
// only Firefox saves all files locally before opening when content-disposition: attachment stated
$isFF = check_browser_version('Firefox', '1.5'); // only FF > 1.5 properly tested
$mimetype = ($forcedownload and !$isFF) ? 'application/x-forcedownload' :
($mimetype ? $mimetype : mimeinfo('type', $filename));
$lastmodified = $pathisstring ? time() : filemtime($path);
$filesize = $pathisstring ? strlen($path) : filesize($path);
/* - MDL-13949
//Adobe Acrobat Reader XSS prevention
if ($mimetype=='application/pdf' or mimeinfo('type', $filename)=='application/pdf') {
//please note that it prevents opening of pdfs in browser when http referer disabled
//or file linked from another site; browser caching of pdfs is now disabled too
if (!empty($_SERVER['HTTP_RANGE'])) {
//already byteserving
$lifetime = 1; // >0 needed for byteserving
} else if (empty($_SERVER['HTTP_REFERER']) or strpos($_SERVER['HTTP_REFERER'], $CFG->wwwroot)!==0) {
$mimetype = 'application/x-forcedownload';
$forcedownload = true;
$lifetime = 0;
} else {
$lifetime = 1; // >0 needed for byteserving
}
}
*/
//IE compatibiltiy HACK!
if (ini_get('zlib.output_compression')) {
ini_set('zlib.output_compression', 'Off');
}
//try to disable automatic sid rewrite in cookieless mode
@ini_set("session.use_trans_sid", "false");
//do not put '@' before the next header to detect incorrect moodle configurations,
//error should be better than "weird" empty lines for admins/users
//TODO: should we remove all those @ before the header()? Are all of the values supported on all servers?
header('Last-Modified: '. gmdate('D, d M Y H:i:s', $lastmodified) .' GMT');
// if user is using IE, urlencode the filename so that multibyte file name will show up correctly on popup
if (check_browser_version('MSIE')) {
$filename = rawurlencode($filename);
}
if ($forcedownload) {
@header('Content-Disposition: attachment; filename="'.$filename.'"');
} else {
@header('Content-Disposition: inline; filename="'.$filename.'"');
}
if ($lifetime > 0) {
@header('Cache-Control: max-age='.$lifetime);
@header('Expires: '. gmdate('D, d M Y H:i:s', time() + $lifetime) .' GMT');
@header('Pragma: ');
if (empty($CFG->disablebyteserving) && !$pathisstring && $mimetype != 'text/plain' && $mimetype != 'text/html') {
@header('Accept-Ranges: bytes');
if (!empty($_SERVER['HTTP_RANGE']) && strpos($_SERVER['HTTP_RANGE'],'bytes=') !== FALSE) {
// byteserving stuff - for acrobat reader and download accelerators
// see: http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.35
// inspired by: http://www.coneural.org/florian/papers/04_byteserving.php
$ranges = false;
if (preg_match_all('/(\d*)-(\d*)/', $_SERVER['HTTP_RANGE'], $ranges, PREG_SET_ORDER)) {
foreach ($ranges as $key=>$value) {
if ($ranges[$key][1] == '') {
//suffix case
$ranges[$key][1] = $filesize - $ranges[$key][2];
$ranges[$key][2] = $filesize - 1;
} else if ($ranges[$key][2] == '' || $ranges[$key][2] > $filesize - 1) {
//fix range length
$ranges[$key][2] = $filesize - 1;
}