forked from moodle/moodle
-
Notifications
You must be signed in to change notification settings - Fork 1
/
filelib.php
4721 lines (4200 loc) · 178 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 core_files
* @copyright 1999 onwards Martin Dougiamas (http://dougiamas.com)
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
defined('MOODLE_INTERNAL') || die();
/**
* BYTESERVING_BOUNDARY - string unique string constant.
*/
define('BYTESERVING_BOUNDARY', 's1k2o3d4a5k6s7');
/**
* Unlimited area size constant
*/
define('FILE_AREA_MAX_BYTES_UNLIMITED', -1);
require_once("$CFG->libdir/filestorage/file_exceptions.php");
require_once("$CFG->libdir/filestorage/file_storage.php");
require_once("$CFG->libdir/filestorage/zip_packer.php");
require_once("$CFG->libdir/filebrowser/file_browser.php");
/**
* Encodes file serving url
*
* @deprecated use moodle_url factory methods instead
*
* @todo MDL-31071 deprecate this function
* @global stdClass $CFG
* @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;
//TODO: deprecate this
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;
}
/**
* Detects if area contains subdirs,
* this is intended for file areas that are attached to content
* migrated from 1.x where subdirs were allowed everywhere.
*
* @param context $context
* @param string $component
* @param string $filearea
* @param string $itemid
* @return bool
*/
function file_area_contains_subdirs(context $context, $component, $filearea, $itemid) {
global $DB;
if (!isset($itemid)) {
// Not initialised yet.
return false;
}
// Detect if any directories are already present, this is necessary for content upgraded from 1.x.
$select = "contextid = :contextid AND component = :component AND filearea = :filearea AND itemid = :itemid AND filepath <> '/' AND filename = '.'";
$params = array('contextid'=>$context->id, 'component'=>$component, 'filearea'=>$filearea, 'itemid'=>$itemid);
return $DB->record_exists_select('files', $select, $params);
}
/**
* 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 embedded files into draft area (assigning itemids automatically),
* creates the form element foobar_editor and rewrites the URLs so the embedded 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.
*
* @category files
* @param stdClass $data database field that holds the html text with embedded media
* @param string $field the name of the database field that holds the html text with embedded media
* @param array $options editor options (like maxifiles, maxbytes etc.)
* @param stdClass $context context of the editor
* @param string $component
* @param string $filearea file area name
* @param int $itemid item id, required if item exists
* @return stdClass modified data object
*/
function file_prepare_standard_editor($data, $field, array $options, $context=null, $component=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;
}
//sanity check for passed context. This function doesn't expect $option['context'] to be set
//But this function is called before creating editor hence, this is one of the best places to check
//if context is used properly. This check notify developer that they missed passing context to editor.
if (isset($context) && !isset($options['context'])) {
//if $context is not null then make sure $option['context'] is also set.
debugging('Context for editor is not set in editoroptions. Hence editor will not respect editor filters', DEBUG_DEVELOPER);
} else if (isset($options['context']) && isset($context)) {
//If both are passed then they should be equal.
if ($options['context']->id != $context->id) {
$exceptionmsg = 'Editor context ['.$options['context']->id.'] is not equal to passed context ['.$context->id.']';
throw new coding_exception($exceptionmsg);
}
}
if (is_null($itemid) or is_null($context)) {
$contextid = null;
$itemid = null;
if (!isset($data)) {
$data = new stdClass();
}
if (!isset($data->{$field})) {
$data->{$field} = '';
}
if (!isset($data->{$field.'format'})) {
$data->{$field.'format'} = editors_get_preferred_format();
}
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, $component, $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 embedded 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 embedded files encoded.
*
* @category files
* @param stdClass $data raw data submitted by the form
* @param string $field name of the database field containing the html with embedded media files
* @param array $options editor options (trusttext, subdirs, maxfiles, maxbytes etc.)
* @param stdClass $context context, required for existing data
* @param string $component file component
* @param string $filearea file area name
* @param int $itemid item id, required if item exists
* @return stdClass modified data object
*/
function file_postupdate_standard_editor($data, $field, array $options, $context, $component=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['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) or empty($editor['itemid'])) {
$data->{$field} = $editor['text'];
} else {
$data->{$field} = file_save_draft_area_files($editor['itemid'], $context->id, $component, $filearea, $itemid, $options, $editor['text'], $options['forcehttps']);
}
$data->{$field.'format'} = $editor['format'];
return $data;
}
/**
* Saves text and files modified by Editor formslib element
*
* @category files
* @param stdClass $data $database entry field
* @param string $field name of data field
* @param array $options various options
* @param stdClass $context context - must already exist
* @param string $component
* @param string $filearea file area name
* @param int $itemid must already exist, usually means data is in db
* @return stdClass modified data obejct
*/
function file_prepare_standard_filemanager($data, $field, array $options, $context=null, $component=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, $component, $filearea, $itemid, $options);
$data->{$field.'_filemanager'} = $draftid_editor;
return $data;
}
/**
* Saves files modified by File manager formslib element
*
* @todo MDL-31073 review this function
* @category files
* @param stdClass $data $database entry field
* @param string $field name of data field
* @param array $options various options
* @param stdClass $context context - must already exist
* @param string $component
* @param string $filearea file area name
* @param int $itemid must already exist, usually means data is in db
* @return stdClass modified data obejct
*/
function file_postupdate_standard_filemanager($data, $field, array $options, $context, $component, $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, $component, $filearea, $itemid, $options);
$fs = get_file_storage();
if ($fs->get_area_files($context->id, $component, $filearea, $itemid)) {
$data->$field = '1'; // TODO: this is an ugly hack (skodak)
} else {
$data->$field = '';
}
}
return $data;
}
/**
* Generate a draft itemid
*
* @category files
* @global moodle_database $DB
* @global stdClass $USER
* @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 = context_user::instance($USER->id)->id;
$fs = get_file_storage();
$draftitemid = rand(1, 999999999);
while ($files = $fs->get_area_files($contextid, 'user', 'draft', $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');
*
* @category files
* @global stdClass $CFG
* @global stdClass $USER
* @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 int $contextid This parameter and the next two identify the file area to copy files from.
* @param string $component
* @param string $filearea helps indentify the file area.
* @param int $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|null returns string if $text was passed in, the rewritten $text is returned. Otherwise NULL.
*/
function file_prepare_draft_area(&$draftitemid, $contextid, $component, $filearea, $itemid, array $options=null, $text=null) {
global $CFG, $USER, $CFG;
$options = (array)$options;
if (!isset($options['subdirs'])) {
$options['subdirs'] = false;
}
if (!isset($options['forcehttps'])) {
$options['forcehttps'] = false;
}
$usercontext = context_user::instance($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, 'component'=>'user', 'filearea'=>'draft', 'itemid'=>$draftitemid);
if (!is_null($itemid) and $files = $fs->get_area_files($contextid, $component, $filearea, $itemid)) {
foreach ($files as $file) {
if ($file->is_directory() and $file->get_filepath() === '/') {
// we need a way to mark the age of each draft area,
// by not copying the root dir we force it to be created automatically with current timestamp
continue;
}
if (!$options['subdirs'] and ($file->is_directory() or $file->get_filepath() !== '/')) {
continue;
}
$draftfile = $fs->create_file_from_storedfile($file_record, $file);
// XXX: This is a hack for file manager (MDL-28666)
// File manager needs to know the original file information before copying
// to draft area, so we append these information in mdl_files.source field
// {@link file_storage::search_references()}
// {@link file_storage::search_references_count()}
$sourcefield = $file->get_source();
$newsourcefield = new stdClass;
$newsourcefield->source = $sourcefield;
$original = new stdClass;
$original->contextid = $contextid;
$original->component = $component;
$original->filearea = $filearea;
$original->itemid = $itemid;
$original->filename = $file->get_filename();
$original->filepath = $file->get_filepath();
$newsourcefield->original = file_storage::pack_reference($original);
$draftfile->set_source(serialize($newsourcefield));
// End of file manager hack
}
}
if (!is_null($text)) {
// at this point there should not be any draftfile links yet,
// because this is a new text from database that should still contain the @@pluginfile@@ links
// this happens when developers forget to post process the text
$text = str_replace("\"$CFG->httpswwwroot/draftfile.php", "\"$CFG->httpswwwroot/brokenfile.php#", $text);
}
} 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.
* Passing a new option reverse = true in the $options var will make the function to convert actual URLs in $text to encoded URLs
* in the @@PLUGINFILE@@ form.
*
* @category files
* @global stdClass $CFG
* @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 int $contextid This parameter and the next two identify the file area to use.
* @param string $component
* @param string $filearea helps identify the file area.
* @param int $itemid helps identify the file area.
* @param array $options text and file options ('forcehttps'=>false), use reverse = true to reverse the behaviour of the function.
* @return string the processed text.
*/
function file_rewrite_pluginfile_urls($text, $file, $contextid, $component, $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/$component/$filearea/";
if ($itemid !== null) {
$baseurl .= "$itemid/";
}
if ($options['forcehttps']) {
$baseurl = str_replace('http://', 'https://', $baseurl);
}
if (!empty($options['reverse'])) {
return str_replace($baseurl, '@@PLUGINFILE@@/', $text);
} else {
return str_replace('@@PLUGINFILE@@/', $baseurl, $text);
}
}
/**
* Returns information about files in a draft area.
*
* @global stdClass $CFG
* @global stdClass $USER
* @param int $draftitemid the draft area item id.
* @param string $filepath path to the directory from which the information have to be retrieved.
* @return array with the following entries:
* 'filecount' => number of files in the draft area.
* 'filesize' => total size of the files in the draft area.
* 'foldercount' => number of folders in the draft area.
* 'filesize_without_references' => total size of the area excluding file references.
* (more information will be added as needed).
*/
function file_get_draft_area_info($draftitemid, $filepath = '/') {
global $CFG, $USER;
$usercontext = context_user::instance($USER->id);
$fs = get_file_storage();
$results = array(
'filecount' => 0,
'foldercount' => 0,
'filesize' => 0,
'filesize_without_references' => 0
);
if ($filepath != '/') {
$draftfiles = $fs->get_directory_files($usercontext->id, 'user', 'draft', $draftitemid, $filepath, true, true);
} else {
$draftfiles = $fs->get_area_files($usercontext->id, 'user', 'draft', $draftitemid, 'id', true);
}
foreach ($draftfiles as $file) {
if ($file->is_directory()) {
$results['foldercount'] += 1;
} else {
$results['filecount'] += 1;
}
$filesize = $file->get_filesize();
$results['filesize'] += $filesize;
if (!$file->is_external_file()) {
$results['filesize_without_references'] += $filesize;
}
}
return $results;
}
/**
* Returns whether a draft area has exceeded/will exceed its size limit.
*
* Please note that the unlimited value for $areamaxbytes is -1 {@link FILE_AREA_MAX_BYTES_UNLIMITED}, not 0.
*
* @param int $draftitemid the draft area item id.
* @param int $areamaxbytes the maximum size allowed in this draft area.
* @param int $newfilesize the size that would be added to the current area.
* @param bool $includereferences true to include the size of the references in the area size.
* @return bool true if the area will/has exceeded its limit.
* @since Moodle 2.4
*/
function file_is_draft_area_limit_reached($draftitemid, $areamaxbytes, $newfilesize = 0, $includereferences = false) {
if ($areamaxbytes != FILE_AREA_MAX_BYTES_UNLIMITED) {
$draftinfo = file_get_draft_area_info($draftitemid);
$areasize = $draftinfo['filesize_without_references'];
if ($includereferences) {
$areasize = $draftinfo['filesize'];
}
if ($areasize + $newfilesize > $areamaxbytes) {
return true;
}
}
return false;
}
/**
* Get used space of files
* @global moodle_database $DB
* @global stdClass $USER
* @return int total bytes
*/
function file_get_user_used_space() {
global $DB, $USER;
$usercontext = context_user::instance($USER->id);
$sql = "SELECT SUM(files1.filesize) AS totalbytes FROM {files} files1
JOIN (SELECT contenthash, filename, MAX(id) AS id
FROM {files}
WHERE contextid = ? AND component = ? AND filearea != ?
GROUP BY contenthash, filename) files2 ON files1.id = files2.id";
$params = array('contextid'=>$usercontext->id, 'component'=>'user', 'filearea'=>'draft');
$record = $DB->get_record_sql($sql, $params);
return (int)$record->totalbytes;
}
/**
* Convert any string to a valid filepath
* @todo review this function
* @param string $str
* @return string path
*/
function file_correct_filepath($str) { //TODO: what is this? (skodak) - No idea (Fred)
if ($str == '/' or empty($str)) {
return '/';
} else {
return '/'.trim($str, '/').'/';
}
}
/**
* Generate a folder tree of draft area of current USER recursively
*
* @todo MDL-31073 use normal return value instead, this does not fit the rest of api here (skodak)
* @param int $draftitemid
* @param string $filepath
* @param mixed $data
*/
function file_get_drafarea_folders($draftitemid, $filepath, &$data) {
global $USER, $OUTPUT, $CFG;
$data->children = array();
$context = context_user::instance($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->sortorder = $file->get_sortorder();
$item->filepath = $file->get_filepath();
$foldername = explode('/', trim($item->filepath, '/'));
$item->fullname = trim(array_pop($foldername), '/');
$item->id = uniqid();
file_get_drafarea_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 stdClass
*/
function file_get_drafarea_files($draftitemid, $filepath = '/') {
global $USER, $OUTPUT, $CFG;
$context = context_user::instance($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();
$maxlength = 12;
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->size = $filesize ? $filesize : null;
$item->filesize = $filesize ? display_size($filesize) : '';
$item->sortorder = $file->get_sortorder();
$item->author = $file->get_author();
$item->license = $file->get_license();
$item->datemodified = $file->get_timemodified();
$item->datecreated = $file->get_timecreated();
$item->isref = $file->is_external_file();
if ($item->isref && $file->get_status() == 666) {
$item->originalmissing = true;
}
// find the file this draft file was created from and count all references in local
// system pointing to that file
$source = @unserialize($file->get_source());
if (isset($source->original)) {
$item->refcount = $fs->search_references_count($source->original);
}
if ($file->is_directory()) {
$item->filesize = 0;
$item->icon = $OUTPUT->image_url(file_folder_icon(24))->out(false);
$item->type = 'folder';
$foldername = explode('/', trim($item->filepath, '/'));
$item->fullname = trim(array_pop($foldername), '/');
$item->thumbnail = $OUTPUT->image_url(file_folder_icon(90))->out(false);
} else {
// do NOT use file browser here!
$item->mimetype = get_mimetype_description($file);
if (file_extension_in_typegroup($file->get_filename(), 'archive')) {
$item->type = 'zip';
} else {
$item->type = 'file';
}
$itemurl = moodle_url::make_draftfile_url($draftitemid, $item->filepath, $item->filename);
$item->url = $itemurl->out();
$item->icon = $OUTPUT->image_url(file_file_icon($file, 24))->out(false);
$item->thumbnail = $OUTPUT->image_url(file_file_icon($file, 90))->out(false);
if ($imageinfo = $file->get_imageinfo()) {
$item->realthumbnail = $itemurl->out(false, array('preview' => 'thumb', 'oid' => $file->get_timemodified()));
$item->realicon = $itemurl->out(false, array('preview' => 'tinyicon', 'oid' => $file->get_timemodified()));
$item->image_width = $imageinfo['width'];
$item->image_height = $imageinfo['height'];
}
}
$list[] = $item;
}
}
$data->itemid = $draftitemid;
$data->list = $list;
return $data;
}
/**
* Returns draft area itemid for a given element.
*
* @category files
* @param string $elname name of formlib editor element, or a hidden form field that stores the draft area item id, etc.
* @return int the itemid, or 0 if there is not one yet.
*/
function file_get_submitted_draft_itemid($elname) {
// this is a nasty hack, ideally all new elements should use arrays here or there should be a new parameter
if (!isset($_REQUEST[$elname])) {
return 0;
}
if (is_array($_REQUEST[$elname])) {
$param = optional_param_array($elname, 0, PARAM_INT);
if (!empty($param['itemid'])) {
$param = $param['itemid'];
} else {
debugging('Missing itemid, maybe caused by unset maxfiles option', DEBUG_DEVELOPER);
return false;
}
} else {
$param = optional_param($elname, 0, PARAM_INT);
}
if ($param) {
require_sesskey();
}
return $param;
}
/**
* Restore the original source field from draft files
*
* Do not use this function because it makes field files.source inconsistent
* for draft area files. This function will be deprecated in 2.6
*
* @param stored_file $storedfile This only works with draft files
* @return stored_file
*/
function file_restore_source_field_from_draft_file($storedfile) {
$source = @unserialize($storedfile->get_source());
if (!empty($source)) {
if (is_object($source)) {
$restoredsource = $source->source;
$storedfile->set_source($restoredsource);
} else {
throw new moodle_exception('invalidsourcefield', 'error');
}
}
return $storedfile;
}
/**
* 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.
*
* @category files
* @global stdClass $USER
* @param int $draftitemid the id of the draft area to use. Normally obtained
* from file_get_submitted_draft_itemid('elementname') or similar.
* @param int $contextid This parameter and the next two identify the file area to save to.
* @param string $component
* @param string $filearea indentifies the file area.
* @param int $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 bool $forcehttps force https urls.
* @return string|null if $text was passed in, the rewritten $text is returned. Otherwise NULL.
*/
function file_save_draft_area_files($draftitemid, $contextid, $component, $filearea, $itemid, array $options=null, $text=null, $forcehttps=false) {
global $USER;
$usercontext = context_user::instance($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'] == USER_CAN_IGNORE_FILE_SIZE_LIMITS) {
$options['maxbytes'] = 0; // unlimited
}
if (!isset($options['areamaxbytes'])) {
$options['areamaxbytes'] = FILE_AREA_MAX_BYTES_UNLIMITED; // Unlimited.
}
$allowreferences = true;
if (isset($options['return_types']) && !($options['return_types'] & (FILE_REFERENCE | FILE_CONTROLLED_LINK))) {
// we assume that if $options['return_types'] is NOT specified, we DO allow references.
// this is not exactly right. BUT there are many places in code where filemanager options
// are not passed to file_save_draft_area_files()
$allowreferences = false;
}
// Check if the draft area has exceeded the authorised limit. This should never happen as validation
// should have taken place before, unless the user is doing something nauthly. If so, let's just not save
// anything at all in the next area.
if (file_is_draft_area_limit_reached($draftitemid, $options['areamaxbytes'])) {
return null;
}
$draftfiles = $fs->get_area_files($usercontext->id, 'user', 'draft', $draftitemid, 'id');
$oldfiles = $fs->get_area_files($contextid, $component, $filearea, $itemid, 'id');
// One file in filearea means it is empty (it has only top-level directory '.').
if (count($draftfiles) > 1 || count($oldfiles) > 1) {
// we have to merge old and new files - we want to keep file ids for files that were not changed
// we change time modified for all new and changed files, we keep time created as is
$newhashes = array();
$filecount = 0;
foreach ($draftfiles as $file) {
if (!$options['subdirs'] && $file->get_filepath() !== '/') {
continue;
}
if (!$allowreferences && $file->is_external_file()) {
continue;
}
if (!$file->is_directory()) {
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
continue;
}
$filecount++;
}
$newhash = $fs->get_pathname_hash($contextid, $component, $filearea, $itemid, $file->get_filepath(), $file->get_filename());
$newhashes[$newhash] = $file;
}
// Loop through oldfiles and decide which we need to delete and which to update.
// After this cycle the array $newhashes will only contain the files that need to be added.
foreach ($oldfiles as $oldfile) {
$oldhash = $oldfile->get_pathnamehash();
if (!isset($newhashes[$oldhash])) {
// delete files not needed any more - deleted by user
$oldfile->delete();
continue;
}
$newfile = $newhashes[$oldhash];
// Now we know that we have $oldfile and $newfile for the same path.
// Let's check if we can update this file or we need to delete and create.
if ($newfile->is_directory()) {
// Directories are always ok to just update.
} else if (($source = @unserialize($newfile->get_source())) && isset($source->original)) {
// File has the 'original' - we need to update the file (it may even have not been changed at all).
$original = file_storage::unpack_reference($source->original);
if ($original['filename'] !== $oldfile->get_filename() || $original['filepath'] !== $oldfile->get_filepath()) {
// Very odd, original points to another file. Delete and create file.
$oldfile->delete();
continue;
}
} else {
// The same file name but absence of 'original' means that file was deteled and uploaded again.
// By deleting and creating new file we properly manage all existing references.
$oldfile->delete();
continue;
}
// status changed, we delete old file, and create a new one
if ($oldfile->get_status() != $newfile->get_status()) {
// file was changed, use updated with new timemodified data
$oldfile->delete();
// This file will be added later
continue;
}
// Updated author
if ($oldfile->get_author() != $newfile->get_author()) {
$oldfile->set_author($newfile->get_author());
}
// Updated license
if ($oldfile->get_license() != $newfile->get_license()) {
$oldfile->set_license($newfile->get_license());
}
// Updated file source
// Field files.source for draftarea files contains serialised object with source and original information.
// We only store the source part of it for non-draft file area.
$newsource = $newfile->get_source();
if ($source = @unserialize($newfile->get_source())) {
$newsource = $source->source;
}
if ($oldfile->get_source() !== $newsource) {
$oldfile->set_source($newsource);
}
// Updated sort order
if ($oldfile->get_sortorder() != $newfile->get_sortorder()) {
$oldfile->set_sortorder($newfile->get_sortorder());
}
// Update file timemodified
if ($oldfile->get_timemodified() != $newfile->get_timemodified()) {
$oldfile->set_timemodified($newfile->get_timemodified());
}
// Replaced file content
if (!$oldfile->is_directory() &&
($oldfile->get_contenthash() != $newfile->get_contenthash() ||
$oldfile->get_filesize() != $newfile->get_filesize() ||
$oldfile->get_referencefileid() != $newfile->get_referencefileid() ||
$oldfile->get_userid() != $newfile->get_userid())) {
$oldfile->replace_file_with($newfile);
}
// unchanged file or directory - we keep it as is
unset($newhashes[$oldhash]);
}
// Add fresh file or the file which has changed status
// the size and subdirectory tests are extra safety only, the UI should prevent it
foreach ($newhashes as $file) {
$file_record = array('contextid'=>$contextid, 'component'=>$component, 'filearea'=>$filearea, 'itemid'=>$itemid, 'timemodified'=>time());
if ($source = @unserialize($file->get_source())) {
// Field files.source for draftarea files contains serialised object with source and original information.
// We only store the source part of it for non-draft file area.
$file_record['source'] = $source->source;
}
if ($file->is_external_file()) {
$repoid = $file->get_repository_id();
if (!empty($repoid)) {
$context = context::instance_by_id($contextid, MUST_EXIST);
$repo = repository::get_repository_by_id($repoid, $context);
$file_record['repositoryid'] = $repoid;
// This hook gives the repo a place to do some house cleaning, and update the $reference before it's saved
// to the file store. E.g. transfer ownership of the file to a system account etc.
$reference = $repo->reference_file_selected($file->get_reference(), $context, $component, $filearea, $itemid);
$file_record['reference'] = $reference;
}
}
$fs->create_file_from_storedfile($file_record, $file);
}
}
// note: do not purge the draft area - we clean up areas later in cron,
// the reason is that user might press submit twice and they would loose the files,
// also sometimes we might want to use hacks that save files into two different areas
if (is_null($text)) {
return null;
} else {
return file_rewrite_urls_to_pluginfile($text, $draftitemid, $forcehttps);
}
}
/**
* Convert the draft file area URLs in some content to @@PLUGINFILE@@ tokens
* ready to be saved in the database. Normally, this is done automatically by
* {@link file_save_draft_area_files()}.
*
* @category files
* @param string $text the content to process.
* @param int $draftitemid the draft file area the content was using.
* @param bool $forcehttps whether the content contains https URLs. Default false.
* @return string the processed content.
*/
function file_rewrite_urls_to_pluginfile($text, $draftitemid, $forcehttps = false) {
global $CFG, $USER;
$usercontext = context_user::instance($USER->id);
$wwwroot = $CFG->wwwroot;
if ($forcehttps) {