forked from moodle/moodle
-
Notifications
You must be signed in to change notification settings - Fork 0
/
filelib.php
2855 lines (2605 loc) · 105 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
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Functions for file handling.
*
* @package moodlecore
* @subpackage file
* @copyright 1999 onwards Martin Dougiamas (http://dougiamas.com)
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
/** @var string unique string constant. */
define('BYTESERVING_BOUNDARY', 's1k2o3d4a5k6s7');
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");
/**
* Given a physical path to a file, returns the URL through which it can be reached in Moodle.
*
* @global object
* @global string
* @param string $path Physical path to a file
* @param array $options associative array of GET variables to append to the URL
* @param string $type (questionfile|rssfile|user|usergroup|httpscoursefile|coursefile)
* @return string URL to file
*/
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);
foreach ($parts as $key => $part) {
/// anchor dash character should not be encoded
$subparts = explode('#', $part);
$subparts = array_map('rawurlencode', $subparts);
$parts[$key] = implode('#', $subparts);
}
$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;
}
/**
* Encodes file serving url
*
* @todo decide if we really need this
* @global object
* @param string $urlbase
* @param string $path /filearea/itemid/dir/dir/file.exe
* @param bool $forcedownload
* @param bool $https https url required
* @return string encoded file url
*/
function file_encode_url($urlbase, $path, $forcedownload=false, $https=false) {
global $CFG;
if ($CFG->slasharguments) {
$parts = explode('/', $path);
$parts = array_map('rawurlencode', $parts);
$path = implode('/', $parts);
$return = $urlbase.$path;
if ($forcedownload) {
$return .= '?forcedownload=1';
}
} else {
$path = rawurlencode($path);
$return = $urlbase.'?file='.$path;
if ($forcedownload) {
$return .= '&forcedownload=1';
}
}
if ($https) {
$return = str_replace('http://', 'https://', $return);
}
return $return;
}
/**
* Prepares 'editor' formslib element from data in database
*
* The passed $data record must contain field foobar, foobarformat and optionally foobartrust. This
* function then copies the embeded files into draft area (assigning itemids automatically),
* creates the form element foobar_editor and rewrites the URLs so the embeded images can be
* displayed.
* In your mform definition, you must have an 'editor' element called foobar_editor. Then you call
* your mform's set_data() supplying the object returned by this function.
*
* @param object $data database field that holds the html text with embeded media
* @param string $field the name of the database field that holds the html text with embeded media
* @param array $options editor options (like maxifiles, maxbytes etc.)
* @param object $context context of the editor
* @param string $filearea file area name
* @param int $itemid item id, required if item exists
* @return object modified data object
*/
function file_prepare_standard_editor($data, $field, array $options, $context=null, $filearea=null, $itemid=null) {
$options = (array)$options;
if (!isset($options['trusttext'])) {
$options['trusttext'] = false;
}
if (!isset($options['forcehttps'])) {
$options['forcehttps'] = false;
}
if (!isset($options['subdirs'])) {
$options['subdirs'] = false;
}
if (!isset($options['maxfiles'])) {
$options['maxfiles'] = 0; // no files by default
}
if (!isset($options['noclean'])) {
$options['noclean'] = false;
}
if (is_null($itemid) or is_null($context)) {
$contextid = null;
$itemid = null;
if (!isset($data->{$field})) {
$data->{$field} = '';
}
if (!isset($data->{$field.'format'})) {
$data->{$field.'format'} = FORMAT_HTML; // TODO: use better default based on user preferences and browser capabilities
}
if (!$options['noclean']) {
$data->{$field} = clean_text($data->{$field}, $data->{$field.'format'});
}
} else {
if ($options['trusttext']) {
// noclean ignored if trusttext enabled
if (!isset($data->{$field.'trust'})) {
$data->{$field.'trust'} = 0;
}
$data = trusttext_pre_edit($data, $field, $context);
} else {
if (!$options['noclean']) {
$data->{$field} = clean_text($data->{$field}, $data->{$field.'format'});
}
}
$contextid = $context->id;
}
if ($options['maxfiles'] != 0) {
$draftid_editor = file_get_submitted_draft_itemid($field);
$currenttext = file_prepare_draft_area($draftid_editor, $contextid, $filearea, $itemid, $options, $data->{$field});
$data->{$field.'_editor'} = array('text'=>$currenttext, 'format'=>$data->{$field.'format'}, 'itemid'=>$draftid_editor);
} else {
$data->{$field.'_editor'} = array('text'=>$data->{$field}, 'format'=>$data->{$field.'format'}, 'itemid'=>0);
}
return $data;
}
/**
* Prepares the content of the 'editor' form element with embeded media files to be saved in database
*
* This function moves files from draft area to the destination area and
* encodes URLs to the draft files so they can be safely saved into DB. The
* form has to contain the 'editor' element named foobar_editor, where 'foobar'
* is the name of the database field to hold the wysiwyg editor content. The
* editor data comes as an array with text, format and itemid properties. This
* function automatically adds $data properties foobar, foobarformat and
* foobartrust, where foobar has URL to embeded files encoded.
*
* @param object $data raw data submitted by the form
* @param string $field name of the database field containing the html with embeded media files
* @param array $options editor options (trusttext, subdirs, maxfiles, maxbytes etc.)
* @param object $context context, required for existing data
* @param string $filearea file area name
* @param int $itemid item id, required if item exists
* @return object modified data object
*/
function file_postupdate_standard_editor($data, $field, array $options, $context, $filearea=null, $itemid=null) {
$options = (array)$options;
if (!isset($options['trusttext'])) {
$options['trusttext'] = false;
}
if (!isset($options['forcehttps'])) {
$options['forcehttps'] = false;
}
if (!isset($options['subdirs'])) {
$options['subdirs'] = false;
}
if (!isset($options['maxfiles'])) {
$options['maxfiles'] = 0; // no files by default
}
if (!isset($options['maxbytes'])) {
$options['maxbytes'] = 0; // unlimited
}
if ($options['trusttext']) {
$data->{$field.'trust'} = trusttext_trusted($context);
} else {
$data->{$field.'trust'} = 0;
}
$editor = $data->{$field.'_editor'};
if ($options['maxfiles'] == 0 or is_null($filearea) or is_null($itemid)) {
$data->{$field} = $editor['text'];
} else {
$data->{$field} = file_save_draft_area_files($editor['itemid'], $context->id, $filearea, $itemid, $options, $editor['text'], $options['forcehttps']);
}
$data->{$field.'format'} = $editor['format'];
return $data;
}
/**
* Saves text and files modified by Editor formslib element
*
* @param object $data $database entry field
* @param string $field name of data field
* @param array $options various options
* @param object $context context - must already exist
* @param string $filearea file area name
* @param int $itemid must already exist, usually means data is in db
* @return object modified data obejct
*/
function file_prepare_standard_filemanager($data, $field, array $options, $context=null, $filearea=null, $itemid=null) {
$options = (array)$options;
if (!isset($options['subdirs'])) {
$options['subdirs'] = false;
}
if (is_null($itemid) or is_null($context)) {
$itemid = null;
$contextid = null;
} else {
$contextid = $context->id;
}
$draftid_editor = file_get_submitted_draft_itemid($field.'_filemanager');
file_prepare_draft_area($draftid_editor, $contextid, $filearea, $itemid, $options);
$data->{$field.'_filemanager'} = $draftid_editor;
return $data;
}
/**
* Saves files modified by File manager formslib element
*
* @param object $data $database entry field
* @param string $field name of data field
* @param array $options various options
* @param object $context context - must already exist
* @param string $filearea file area name
* @param int $itemid must already exist, usually means data is in db
* @return object modified data obejct
*/
function file_postupdate_standard_filemanager($data, $field, array $options, $context, $filearea, $itemid) {
$options = (array)$options;
if (!isset($options['subdirs'])) {
$options['subdirs'] = false;
}
if (!isset($options['maxfiles'])) {
$options['maxfiles'] = -1; // unlimited
}
if (!isset($options['maxbytes'])) {
$options['maxbytes'] = 0; // unlimited
}
if (empty($data->{$field.'_filemanager'})) {
$data->$field = '';
} else {
file_save_draft_area_files($data->{$field.'_filemanager'}, $context->id, $filearea, $itemid, $options);
$fs = get_file_storage();
if ($fs->get_area_files($context->id, $filearea, $itemid)) {
$data->$field = '1'; // TODO: this is an ugly hack
} else {
$data->$field = '';
}
}
return $data;
}
/**
*
* @global object
* @global object
* @return int a random but available draft itemid that can be used to create a new draft
* file area.
*/
function file_get_unused_draft_itemid() {
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;
}
/**
* Initialise a draft file area from a real one by copying the files. A draft
* area will be created if one does not already exist. Normally you should
* get $draftitemid by calling file_get_submitted_draft_itemid('elementname');
*
* @global object
* @global object
* @param int &$draftitemid the id of the draft area to use, or 0 to create a new one, in which case this parameter is updated.
* @param integer $contextid This parameter and the next two identify the file area to copy files from.
* @param string $filearea helps indentify the file area.
* @param integer $itemid helps identify the file area. Can be null if there are no files yet.
* @param array $options text and file options ('subdirs'=>false, 'forcehttps'=>false)
* @param string $text some html content that needs to have embedded links rewritten to point to the draft area.
* @return string if $text was passed in, the rewritten $text is returned. Otherwise NULL.
*/
function file_prepare_draft_area(&$draftitemid, $contextid, $filearea, $itemid, array $options=null, $text=null) {
global $CFG, $USER;
$options = (array)$options;
if (!isset($options['subdirs'])) {
$options['subdirs'] = false;
}
if (!isset($options['forcehttps'])) {
$options['forcehttps'] = false;
}
$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_unused_draft_itemid();
$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 (!$options['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@@ !
return file_rewrite_pluginfile_urls($text, 'draftfile.php', $usercontext->id, 'user_draft', $draftitemid, $options);
}
/**
* Convert encoded URLs in $text from the @@PLUGINFILE@@/... form to an actual URL.
*
* @global object
* @param string $text The content that may contain ULRs in need of rewriting.
* @param string $file The script that should be used to serve these files. pluginfile.php, draftfile.php, etc.
* @param integer $contextid This parameter and the next two identify the file area to use.
* @param string $filearea helps indentify the file area.
* @param integer $itemid helps identify the file area.
* @param array $options text and file options ('forcehttps'=>false)
* @return string the processed text.
*/
function file_rewrite_pluginfile_urls($text, $file, $contextid, $filearea, $itemid, array $options=null) {
global $CFG;
$options = (array)$options;
if (!isset($options['forcehttps'])) {
$options['forcehttps'] = false;
}
if (!$CFG->slasharguments) {
$file = $file . '?file=';
}
$baseurl = "$CFG->wwwroot/$file/$contextid/$filearea/";
if ($itemid !== null) {
$baseurl .= "$itemid/";
}
if ($options['forcehttps']) {
$baseurl = str_replace('http://', 'https://', $baseurl);
}
return str_replace('@@PLUGINFILE@@/', $baseurl, $text);
}
/**
* Returns information about files in a draft area.
*
* @global object
* @global object
* @param integer $draftitemid the draft area item id.
* @return array with the following entries:
* 'filecount' => number of files in the draft area.
* (more information will be added as needed).
*/
function file_get_draft_area_info($draftitemid) {
global $CFG, $USER;
$usercontext = get_context_instance(CONTEXT_USER, $USER->id);
$fs = get_file_storage();
$results = array();
// The number of files
$draftfiles = $fs->get_area_files($usercontext->id, 'user_draft', $draftitemid, 'id', false);
$results['filecount'] = count($draftfiles);
return $results;
}
/**
* Convert any string to a valid filepath
* @param string $str
* @return string path
*/
function file_correct_filepath($str) {
return '/'.trim($str, './@#$ ').'/';
}
/**
* Generate a folder tree of currect draft area recursively
* @param int $itemid
* @param string $filepath
* @param mixed $data
*/
function file_get_draft_area_folders($draftitemid, $filepath, &$data) {
global $USER, $OUTPUT, $CFG;
$data->children = array();
$context = get_context_instance(CONTEXT_USER, $USER->id);
$fs = get_file_storage();
if ($files = $fs->get_directory_files($context->id, 'user_draft', $draftitemid, $filepath, false)) {
foreach ($files as $file) {
if ($file->is_directory()) {
$item = new stdclass;
$item->filepath = $file->get_filepath();
$foldername = explode('/', trim($item->filepath, '/'));
$item->fullname = trim(array_pop($foldername), '/');
$item->id = uniqid();
file_get_draft_area_folders($draftitemid, $item->filepath, $item);
$data->children[] = $item;
} else {
continue;
}
}
}
}
/**
* Listing all files (including folders) in current path (draft area)
* used by file manager
* @param int $draftitemid
* @param string $filepath
* @return mixed
*/
function file_get_draft_area_files($draftitemid, $filepath = '/') {
global $USER, $OUTPUT, $CFG;
$context = get_context_instance(CONTEXT_USER, $USER->id);
$fs = get_file_storage();
$data = new stdclass;
$data->path = array();
$data->path[] = array('name'=>get_string('files'), 'path'=>'/');
// will be used to build breadcrumb
$trail = '';
if ($filepath !== '/') {
$filepath = file_correct_filepath($filepath);
$parts = explode('/', $filepath);
foreach ($parts as $part) {
if ($part != '' && $part != null) {
$trail .= ('/'.$part.'/');
$data->path[] = array('name'=>$part, 'path'=>$trail);
}
}
}
$list = array();
if ($files = $fs->get_directory_files($context->id, 'user_draft', $draftitemid, $filepath, false)) {
foreach ($files as $file) {
$item = new stdclass;
$item->filename = $file->get_filename();
$item->filepath = $file->get_filepath();
$item->fullname = trim($item->filename, '/');
$filesize = $file->get_filesize();
$item->filesize = $filesize ? display_size($filesize) : '';
$icon = mimeinfo_from_type('icon', $file->get_mimetype());
$icon = str_replace('.gif', '', $icon);
$item->icon = $OUTPUT->pix_url('f/' . $icon);
if ($icon == 'zip') {
$item->type = 'zip';
} else {
$item->type = 'file';
}
if ($file->is_directory()) {
$item->filesize = 0;
$item->icon = $OUTPUT->pix_url('f/folder');
$item->type = 'folder';
$foldername = explode('/', trim($item->filepath, '/'));
$item->fullname = trim(array_pop($foldername), '/');
} else {
$item->url = $CFG->wwwroot . '/draftfile.php/' . $context->id .'/user_draft/'.$draftitemid.$item->filepath.$item->fullname;
}
$list[] = $item;
}
}
$data->itemid = $draftitemid;
$data->list = $list;
return $data;
}
/**
* Returns draft area itemid for a given element.
*
* @param string $elname name of formlib editor element, or a hidden form field that stores the draft area item id, etc.
* @return inteter the itemid, or 0 if there is not one yet.
*/
function file_get_submitted_draft_itemid($elname) {
$param = optional_param($elname, 0, PARAM_INT);
if ($param) {
require_sesskey();
}
if (is_array($param)) {
if (!empty($param['itemid'])) {
$param = $param['itemid'];
} else {
debugging('Missing itemid, maybe caused by unset maxfiles option', DEBUG_DEVELOPER);
return false;
}
}
return $param;
}
/**
* Saves files from a draft file area to a real one (merging the list of files).
* Can rewrite URLs in some content at the same time if desired.
*
* @global object
* @global object
* @param integer $draftitemid the id of the draft area to use. Normally obtained
* from file_get_submitted_draft_itemid('elementname') or similar.
* @param integer $contextid This parameter and the next two identify the file area to save to.
* @param string $filearea indentifies the file area.
* @param integer $itemid helps identifies the file area.
* @param array $options area options (subdirs=>false, maxfiles=-1, maxbytes=0)
* @param string $text some html content that needs to have embedded links rewritten
* to the @@PLUGINFILE@@ form for saving in the database.
* @param boolean $forcehttps force https urls.
* @return string if $text was passed in, the rewritten $text is returned. Otherwise NULL.
*/
function file_save_draft_area_files($draftitemid, $contextid, $filearea, $itemid, array $options=null, $text=null, $forcehttps=false) {
global $CFG, $USER;
$usercontext = get_context_instance(CONTEXT_USER, $USER->id);
$fs = get_file_storage();
$options = (array)$options;
if (!isset($options['subdirs'])) {
$options['subdirs'] = false;
}
if (!isset($options['maxfiles'])) {
$options['maxfiles'] = -1; // unlimited
}
if (!isset($options['maxbytes'])) {
$options['maxbytes'] = 0; // unlimited
}
$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) {
$filecount = 0;
// there were no files before - one file means root dir only ;-)
$file_record = array('contextid'=>$contextid, 'filearea'=>$filearea, 'itemid'=>$itemid);
foreach ($draftfiles as $file) {
if (!$options['subdirs']) {
if ($file->get_filepath() !== '/' or $file->is_directory()) {
continue;
}
}
if ($options['maxbytes'] and $options['maxbytes'] < $file->get_filesize()) {
// oversized file - should not get here at all
continue;
}
if ($options['maxfiles'] != -1 and $options['maxfiles'] <= $filecount) {
// more files - should not get here at all
break;
}
if (!$file->is_directory()) {
$filecount++;
}
$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);
$newhashes = array();
foreach ($draftfiles as $file) {
$newhash = sha1($contextid.$filearea.$itemid.$file->get_filepath().$file->get_filename());
$newhashes[$newhash] = $file;
}
$filecount = 0;
foreach ($oldfiles as $file) {
$oldhash = $file->get_pathnamehash();
if (isset($newhashes[$oldhash])) {
if (!$file->is_directory()) {
$filecount++;
}
// unchanged file already there
unset($newhashes[$oldhash]);
} else {
// delete files not needed any more
$file->delete();
}
}
// now add new files
foreach ($newhashes as $file) {
if (!$options['subdirs']) {
if ($file->get_filepath() !== '/' or $file->is_directory()) {
continue;
}
}
if ($options['maxbytes'] and $options['maxbytes'] < $file->get_filesize()) {
// oversized file - should not get here at all
continue;
}
if ($options['maxfiles'] != -1 and $options['maxfiles'] <= $filecount) {
// more files - should not get here at all
break;
}
if (!$file->is_directory()) {
$filecount++;
}
$fs->create_file_from_storedfile($file_record, $file);
}
}
// 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@@/', $text);
return $text;
}
/**
* Returns description of upload error
*
* @param int $errorcode found in $_FILES['filename.ext']['error']
* @return string 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.
*
* @global object
* @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 (!$ch = curl_init($url)) {
debugging('Can not init curl.');
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)) {
$data = array();
foreach ($postdata as $k=>$v) {
if (is_array($v)) {
foreach ($v as $sk=>$sv) {
if (is_array($sv)) {
foreach ($sv as $ssk=>$ssv) {
$data[] = urlencode($k).'['.urlencode($sk).']['.urlencode($ssk).']='.urlencode($ssv);
}
} else {
$data[] = urlencode($k).'['.urlencode($sk).']='.urlencode($sv);
}
}
} else {
$data[] = urlencode($k).'='.urlencode($v);
}
}
$postdata = implode('&', $data);
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;