forked from moodle/moodle
-
Notifications
You must be signed in to change notification settings - Fork 0
/
filelib.php
5017 lines (4457 loc) · 190 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');
/**
* Do not process file merging when working with draft area files.
*/
define('IGNORE_FILE_MERGE', -1);
/**
* 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 (!isset($options['removeorphaneddrafts'])) {
$options['removeorphaneddrafts'] = false; // Don't remove orphaned draft files by default.
}
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 {
// Clean the user drafts area of any files not referenced in the editor text.
if ($options['removeorphaneddrafts']) {
file_remove_editor_orphaned_files($editor);
}
$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->wwwroot/draftfile.php", "\"$CFG->wwwroot/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.
*
* @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
* bool $options.forcehttps Force the user of https
* bool $options.reverse Reverse the behaviour of the function
* mixed $options.includetoken Use a token for authentication. True for current user, int value for other user id.
* string The processed text.
*/
function file_rewrite_pluginfile_urls($text, $file, $contextid, $component, $filearea, $itemid, array $options=null) {
global $CFG, $USER;
$options = (array)$options;
if (!isset($options['forcehttps'])) {
$options['forcehttps'] = false;
}
$baseurl = "{$CFG->wwwroot}/{$file}";
if (!empty($options['includetoken'])) {
$userid = $options['includetoken'] === true ? $USER->id : $options['includetoken'];
$token = get_user_key('core_files', $userid);
$finalfile = basename($file);
$tokenfile = "token{$finalfile}";
$file = substr($file, 0, strlen($file) - strlen($finalfile)) . $tokenfile;
$baseurl = "{$CFG->wwwroot}/{$file}";
if (!$CFG->slasharguments) {
$baseurl .= "?token={$token}&file=";
} else {
$baseurl .= "/{$token}";
}
}
$baseurl .= "/{$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 $USER;
$usercontext = context_user::instance($USER->id);
return file_get_file_area_info($usercontext->id, 'user', 'draft', $draftitemid, $filepath);
}
/**
* Returns information about files in an area.
*
* @param int $contextid context id
* @param string $component component
* @param string $filearea file area name
* @param int $itemid item id or all files if not specified
* @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 area.
* 'filesize' => total size of the files in the area.
* 'foldercount' => number of folders in the area.
* 'filesize_without_references' => total size of the area excluding file references.
* @since Moodle 3.4
*/
function file_get_file_area_info($contextid, $component, $filearea, $itemid = 0, $filepath = '/') {
$fs = get_file_storage();
$results = array(
'filecount' => 0,
'foldercount' => 0,
'filesize' => 0,
'filesize_without_references' => 0
);
$draftfiles = $fs->get_directory_files($contextid, $component, $filearea, $itemid, $filepath, true, 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);
// The call to $file->get_imageinfo() fails with an exception if the file can't be read on the file system.
// We still want to add such files to the list, so the owner can view and delete them if needed. So, we only call
// get_imageinfo() on files that can be read, and we also spoof the file status based on whether it was found.
// We'll use the same status types used by stored_file->get_status(), where 0 = OK. 1 = problem, as these will be
// used by the widget to display a warning about the problem files.
// The value of stored_file->get_status(), and the file record are unaffected by this. It's only superficially set.
$item->status = $fs->get_file_system()->is_file_readable_remotely_by_storedfile($file) ? 0 : 1;
if ($item->status == 0) {
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 all of the files in the draftarea.
*
* @param int $draftitemid The draft item ID
* @param string $filepath path for the uploaded files.
* @return array An array of files associated with this draft item id.
*/
function file_get_all_files_in_draftarea(int $draftitemid, string $filepath = '/') : array {
$files = [];
$draftfiles = file_get_drafarea_files($draftitemid, $filepath);
file_get_drafarea_folders($draftitemid, $filepath, $draftfiles);
if (!empty($draftfiles)) {
foreach ($draftfiles->list as $draftfile) {
if ($draftfile->type == 'file') {
$files[] = $draftfile;
}
}
if (isset($draftfiles->children)) {
foreach ($draftfiles->children as $draftfile) {
$files = array_merge($files, file_get_all_files_in_draftarea($draftitemid, $draftfile->filepath));
}
}
}
return $files;
}
/**
* 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;
}
/**
* Removes those files from the user drafts filearea which are not referenced in the editor text.
*
* @param stdClass $editor The online text editor element from the submitted form data.
*/
function file_remove_editor_orphaned_files($editor) {
global $CFG, $USER;
// Find those draft files included in the text, and generate their hashes.
$context = context_user::instance($USER->id);
$baseurl = $CFG->wwwroot . '/draftfile.php/' . $context->id . '/user/draft/' . $editor['itemid'] . '/';
$pattern = "/" . preg_quote($baseurl, '/') . "(.+?)[\?\"']/";
preg_match_all($pattern, $editor['text'], $matches);
$usedfilehashes = [];
foreach ($matches[1] as $matchedfilename) {
$matchedfilename = urldecode($matchedfilename);
$usedfilehashes[] = \file_storage::get_pathname_hash($context->id, 'user', 'draft', $editor['itemid'], '/',
$matchedfilename);
}
// Now, compare the hashes of all draft files, and remove those which don't match used files.
$fs = get_file_storage();
$files = $fs->get_area_files($context->id, 'user', 'draft', $editor['itemid'], 'id', false);
foreach ($files as $file) {
$tmphash = $file->get_pathnamehash();
if (!in_array($tmphash, $usedfilehashes)) {
$file->delete();
}
}
}
/**
* Finds all draft areas used in a textarea and copies the files into the primary textarea. If a user copies and pastes
* content from another draft area it's possible for a single textarea to reference multiple draft areas.
*
* @category files
* @param int $draftitemid the id of the primary draft area.
* When set to -1 (probably, by a WebService) it won't process file merging, keeping the original state of the file area.
* @param int $usercontextid the user's context id.
* @param string $text some html content that needs to have files copied to the correct draft area.
* @param bool $forcehttps force https urls.
*
* @return string $text html content modified with new draft links
*/
function file_merge_draft_areas($draftitemid, $usercontextid, $text, $forcehttps = false) {
if (is_null($text)) {
return null;
}
// Do not merge files, leave it as it was.
if ($draftitemid === IGNORE_FILE_MERGE) {
return null;
}
$urls = extract_draft_file_urls_from_text($text, $forcehttps, $usercontextid, 'user', 'draft');
// No draft areas to rewrite.
if (empty($urls)) {
return $text;
}
foreach ($urls as $url) {
// Do not process the "home" draft area.
if ($url['itemid'] == $draftitemid) {
continue;
}
// Decode the filename.
$filename = urldecode($url['filename']);
// Copy the file.
file_copy_file_to_file_area($url, $filename, $draftitemid);
// Rewrite draft area.
$text = file_replace_file_area_in_text($url, $draftitemid, $text, $forcehttps);
}
return $text;
}
/**
* Rewrites a file area in arbitrary text.
*
* @param array $file General information about the file.
* @param int $newid The new file area itemid.
* @param string $text The text to rewrite.
* @param bool $forcehttps force https urls.
* @return string The rewritten text.
*/
function file_replace_file_area_in_text($file, $newid, $text, $forcehttps = false) {
global $CFG;
$wwwroot = $CFG->wwwroot;
if ($forcehttps) {
$wwwroot = str_replace('http://', 'https://', $wwwroot);
}
$search = [
$wwwroot,
$file['urlbase'],
$file['contextid'],
$file['component'],
$file['filearea'],
$file['itemid'],
$file['filename']
];
$replace = [
$wwwroot,
$file['urlbase'],
$file['contextid'],
$file['component'],
$file['filearea'],
$newid,
$file['filename']
];
$text = str_ireplace( implode('/', $search), implode('/', $replace), $text);
return $text;
}
/**
* Copies a file from one file area to another.
*
* @param array $file Information about the file to be copied.
* @param string $filename The filename.
* @param int $itemid The new file area.
*/
function file_copy_file_to_file_area($file, $filename, $itemid) {
$fs = get_file_storage();
// Load the current file in the old draft area.
$fileinfo = array(
'component' => $file['component'],
'filearea' => $file['filearea'],
'itemid' => $file['itemid'],
'contextid' => $file['contextid'],
'filepath' => '/',
'filename' => $filename
);
$oldfile = $fs->get_file($fileinfo['contextid'], $fileinfo['component'], $fileinfo['filearea'],
$fileinfo['itemid'], $fileinfo['filepath'], $fileinfo['filename']);