mirrored from git://git.moodle.org/moodle.git
/
file_storage.php
2410 lines (2094 loc) · 96.5 KB
/
file_storage.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/>.
/**
* Core file storage class definition.
*
* @package core_files
* @copyright 2008 Petr Skoda {@link http://skodak.org}
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
defined('MOODLE_INTERNAL') || die();
require_once("$CFG->libdir/filestorage/stored_file.php");
/**
* File storage class used for low level access to stored files.
*
* Only owner of file area may use this class to access own files,
* for example only code in mod/assignment/* may access assignment
* attachments. When some other part of moodle needs to access
* files of modules it has to use file_browser class instead or there
* has to be some callback API.
*
* @package core_files
* @category files
* @copyright 2008 Petr Skoda {@link http://skodak.org}
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
* @since Moodle 2.0
*/
class file_storage {
/** @var string tempdir */
private $tempdir;
/** @var file_system filesystem */
private $filesystem;
/**
* Constructor - do not use directly use {@link get_file_storage()} call instead.
*/
public function __construct() {
// The tempdir must always remain on disk, but shared between all ndoes in a cluster. Its content is not subject
// to the file_system abstraction.
$this->tempdir = make_temp_directory('filestorage');
$this->setup_file_system();
}
/**
* Complete setup procedure for the file_system component.
*
* @return file_system
*/
public function setup_file_system() {
global $CFG;
if ($this->filesystem === null) {
require_once($CFG->libdir . '/filestorage/file_system.php');
if (!empty($CFG->alternative_file_system_class)) {
$class = $CFG->alternative_file_system_class;
} else {
// The default file_system is the filedir.
require_once($CFG->libdir . '/filestorage/file_system_filedir.php');
$class = file_system_filedir::class;
}
$this->filesystem = new $class();
}
return $this->filesystem;
}
/**
* Return the file system instance.
*
* @return file_system
*/
public function get_file_system() {
return $this->filesystem;
}
/**
* Calculates sha1 hash of unique full path name information.
*
* This hash is a unique file identifier - it is used to improve
* performance and overcome db index size limits.
*
* @param int $contextid context ID
* @param string $component component
* @param string $filearea file area
* @param int $itemid item ID
* @param string $filepath file path
* @param string $filename file name
* @return string sha1 hash
*/
public static function get_pathname_hash($contextid, $component, $filearea, $itemid, $filepath, $filename) {
return sha1("/$contextid/$component/$filearea/$itemid".$filepath.$filename);
}
/**
* Does this file exist?
*
* @param int $contextid context ID
* @param string $component component
* @param string $filearea file area
* @param int $itemid item ID
* @param string $filepath file path
* @param string $filename file name
* @return bool
*/
public function file_exists($contextid, $component, $filearea, $itemid, $filepath, $filename) {
$filepath = clean_param($filepath, PARAM_PATH);
$filename = clean_param($filename, PARAM_FILE);
if ($filename === '') {
$filename = '.';
}
$pathnamehash = $this->get_pathname_hash($contextid, $component, $filearea, $itemid, $filepath, $filename);
return $this->file_exists_by_hash($pathnamehash);
}
/**
* Whether or not the file exist
*
* @param string $pathnamehash path name hash
* @return bool
*/
public function file_exists_by_hash($pathnamehash) {
global $DB;
return $DB->record_exists('files', array('pathnamehash'=>$pathnamehash));
}
/**
* Create instance of file class from database record.
*
* @param stdClass $filerecord record from the files table left join files_reference table
* @return stored_file instance of file abstraction class
*/
public function get_file_instance(stdClass $filerecord) {
$storedfile = new stored_file($this, $filerecord);
return $storedfile;
}
/**
* Get converted document.
*
* Get an alternate version of the specified document, if it is possible to convert.
*
* @param stored_file $file the file we want to preview
* @param string $format The desired format - e.g. 'pdf'. Formats are specified by file extension.
* @param boolean $forcerefresh If true, the file will be converted every time (not cached).
* @return stored_file|bool false if unable to create the conversion, stored file otherwise
*/
public function get_converted_document(stored_file $file, $format, $forcerefresh = false) {
debugging('The get_converted_document function has been deprecated and the unoconv functions been removed. '
. 'The file has not been converted. '
. 'Please update your code to use the file conversion API instead.', DEBUG_DEVELOPER);
return false;
}
/**
* Verify the format is supported.
*
* @param string $format The desired format - e.g. 'pdf'. Formats are specified by file extension.
* @return bool - True if the format is supported for input.
*/
protected function is_format_supported_by_unoconv($format) {
debugging('The is_format_supported_by_unoconv function has been deprecated and the unoconv functions been removed. '
. 'Please update your code to use the file conversion API instead.', DEBUG_DEVELOPER);
return false;
}
/**
* Check if the installed version of unoconv is supported.
*
* @return bool true if the present version is supported, false otherwise.
*/
public static function can_convert_documents() {
debugging('The can_convert_documents function has been deprecated and the unoconv functions been removed. '
. 'Please update your code to use the file conversion API instead.', DEBUG_DEVELOPER);
return false;
}
/**
* Regenerate the test pdf and send it direct to the browser.
*/
public static function send_test_pdf() {
debugging('The send_test_pdf function has been deprecated and the unoconv functions been removed. '
. 'Please update your code to use the file conversion API instead.', DEBUG_DEVELOPER);
return false;
}
/**
* Check if unoconv configured path is correct and working.
*
* @return \stdClass an object with the test status and the UNOCONVPATH_ constant message.
*/
public static function test_unoconv_path() {
debugging('The test_unoconv_path function has been deprecated and the unoconv functions been removed. '
. 'Please update your code to use the file conversion API instead.', DEBUG_DEVELOPER);
return false;
}
/**
* Returns an image file that represent the given stored file as a preview
*
* At the moment, only GIF, JPEG and PNG files are supported to have previews. In the
* future, the support for other mimetypes can be added, too (eg. generate an image
* preview of PDF, text documents etc).
*
* @param stored_file $file the file we want to preview
* @param string $mode preview mode, eg. 'thumb'
* @return stored_file|bool false if unable to create the preview, stored file otherwise
*/
public function get_file_preview(stored_file $file, $mode) {
$context = context_system::instance();
$path = '/' . trim($mode, '/') . '/';
$preview = $this->get_file($context->id, 'core', 'preview', 0, $path, $file->get_contenthash());
if (!$preview) {
$preview = $this->create_file_preview($file, $mode);
if (!$preview) {
return false;
}
}
return $preview;
}
/**
* Return an available file name.
*
* This will return the next available file name in the area, adding/incrementing a suffix
* of the file, ie: file.txt > file (1).txt > file (2).txt > etc...
*
* If the file name passed is available without modification, it is returned as is.
*
* @param int $contextid context ID.
* @param string $component component.
* @param string $filearea file area.
* @param int $itemid area item ID.
* @param string $filepath the file path.
* @param string $filename the file name.
* @return string available file name.
* @throws coding_exception if the file name is invalid.
* @since Moodle 2.5
*/
public function get_unused_filename($contextid, $component, $filearea, $itemid, $filepath, $filename) {
global $DB;
// Do not accept '.' or an empty file name (zero is acceptable).
if ($filename == '.' || (empty($filename) && !is_numeric($filename))) {
throw new coding_exception('Invalid file name passed', $filename);
}
// The file does not exist, we return the same file name.
if (!$this->file_exists($contextid, $component, $filearea, $itemid, $filepath, $filename)) {
return $filename;
}
// Trying to locate a file name using the used pattern. We remove the used pattern from the file name first.
$pathinfo = pathinfo($filename);
$basename = $pathinfo['filename'];
$matches = array();
if (preg_match('~^(.+) \(([0-9]+)\)$~', $basename, $matches)) {
$basename = $matches[1];
}
$filenamelike = $DB->sql_like_escape($basename) . ' (%)';
if (isset($pathinfo['extension'])) {
$filenamelike .= '.' . $DB->sql_like_escape($pathinfo['extension']);
}
$filenamelikesql = $DB->sql_like('f.filename', ':filenamelike');
$filenamelen = $DB->sql_length('f.filename');
$sql = "SELECT filename
FROM {files} f
WHERE
f.contextid = :contextid AND
f.component = :component AND
f.filearea = :filearea AND
f.itemid = :itemid AND
f.filepath = :filepath AND
$filenamelikesql
ORDER BY
$filenamelen DESC,
f.filename DESC";
$params = array('contextid' => $contextid, 'component' => $component, 'filearea' => $filearea, 'itemid' => $itemid,
'filepath' => $filepath, 'filenamelike' => $filenamelike);
$results = $DB->get_fieldset_sql($sql, $params, IGNORE_MULTIPLE);
// Loop over the results to make sure we are working on a valid file name. Because 'file (1).txt' and 'file (copy).txt'
// would both be returned, but only the one only containing digits should be used.
$number = 1;
foreach ($results as $result) {
$resultbasename = pathinfo($result, PATHINFO_FILENAME);
$matches = array();
if (preg_match('~^(.+) \(([0-9]+)\)$~', $resultbasename, $matches)) {
$number = $matches[2] + 1;
break;
}
}
// Constructing the new filename.
$newfilename = $basename . ' (' . $number . ')';
if (isset($pathinfo['extension'])) {
$newfilename .= '.' . $pathinfo['extension'];
}
return $newfilename;
}
/**
* Return an available directory name.
*
* This will return the next available directory name in the area, adding/incrementing a suffix
* of the last portion of path, ie: /path/ > /path (1)/ > /path (2)/ > etc...
*
* If the file path passed is available without modification, it is returned as is.
*
* @param int $contextid context ID.
* @param string $component component.
* @param string $filearea file area.
* @param int $itemid area item ID.
* @param string $suggestedpath the suggested file path.
* @return string available file path
* @since Moodle 2.5
*/
public function get_unused_dirname($contextid, $component, $filearea, $itemid, $suggestedpath) {
global $DB;
// Ensure suggestedpath has trailing '/'
$suggestedpath = rtrim($suggestedpath, '/'). '/';
// The directory does not exist, we return the same file path.
if (!$this->file_exists($contextid, $component, $filearea, $itemid, $suggestedpath, '.')) {
return $suggestedpath;
}
// Trying to locate a file path using the used pattern. We remove the used pattern from the path first.
if (preg_match('~^(/.+) \(([0-9]+)\)/$~', $suggestedpath, $matches)) {
$suggestedpath = $matches[1]. '/';
}
$filepathlike = $DB->sql_like_escape(rtrim($suggestedpath, '/')) . ' (%)/';
$filepathlikesql = $DB->sql_like('f.filepath', ':filepathlike');
$filepathlen = $DB->sql_length('f.filepath');
$sql = "SELECT filepath
FROM {files} f
WHERE
f.contextid = :contextid AND
f.component = :component AND
f.filearea = :filearea AND
f.itemid = :itemid AND
f.filename = :filename AND
$filepathlikesql
ORDER BY
$filepathlen DESC,
f.filepath DESC";
$params = array('contextid' => $contextid, 'component' => $component, 'filearea' => $filearea, 'itemid' => $itemid,
'filename' => '.', 'filepathlike' => $filepathlike);
$results = $DB->get_fieldset_sql($sql, $params, IGNORE_MULTIPLE);
// Loop over the results to make sure we are working on a valid file path. Because '/path (1)/' and '/path (copy)/'
// would both be returned, but only the one only containing digits should be used.
$number = 1;
foreach ($results as $result) {
if (preg_match('~ \(([0-9]+)\)/$~', $result, $matches)) {
$number = (int)($matches[1]) + 1;
break;
}
}
return rtrim($suggestedpath, '/'). ' (' . $number . ')/';
}
/**
* Generates a preview image for the stored file
*
* @param stored_file $file the file we want to preview
* @param string $mode preview mode, eg. 'thumb'
* @return stored_file|bool the newly created preview file or false
*/
protected function create_file_preview(stored_file $file, $mode) {
$mimetype = $file->get_mimetype();
if ($mimetype === 'image/gif' or $mimetype === 'image/jpeg' or $mimetype === 'image/png') {
// make a preview of the image
$data = $this->create_imagefile_preview($file, $mode);
} else {
// unable to create the preview of this mimetype yet
return false;
}
if (empty($data)) {
return false;
}
$context = context_system::instance();
$record = array(
'contextid' => $context->id,
'component' => 'core',
'filearea' => 'preview',
'itemid' => 0,
'filepath' => '/' . trim($mode, '/') . '/',
'filename' => $file->get_contenthash(),
);
$imageinfo = getimagesizefromstring($data);
if ($imageinfo) {
$record['mimetype'] = $imageinfo['mime'];
}
return $this->create_file_from_string($record, $data);
}
/**
* Generates a preview for the stored image file
*
* @param stored_file $file the image we want to preview
* @param string $mode preview mode, eg. 'thumb'
* @return string|bool false if a problem occurs, the thumbnail image data otherwise
*/
protected function create_imagefile_preview(stored_file $file, $mode) {
global $CFG;
require_once($CFG->libdir.'/gdlib.php');
if ($mode === 'tinyicon') {
$data = $file->generate_image_thumbnail(24, 24);
} else if ($mode === 'thumb') {
$data = $file->generate_image_thumbnail(90, 90);
} else if ($mode === 'bigthumb') {
$data = $file->generate_image_thumbnail(250, 250);
} else {
throw new file_exception('storedfileproblem', 'Invalid preview mode requested');
}
return $data;
}
/**
* Fetch file using local file id.
*
* Please do not rely on file ids, it is usually easier to use
* pathname hashes instead.
*
* @param int $fileid file ID
* @return stored_file|bool stored_file instance if exists, false if not
*/
public function get_file_by_id($fileid) {
global $DB;
$sql = "SELECT ".self::instance_sql_fields('f', 'r')."
FROM {files} f
LEFT JOIN {files_reference} r
ON f.referencefileid = r.id
WHERE f.id = ?";
if ($filerecord = $DB->get_record_sql($sql, array($fileid))) {
return $this->get_file_instance($filerecord);
} else {
return false;
}
}
/**
* Fetch file using local file full pathname hash
*
* @param string $pathnamehash path name hash
* @return stored_file|bool stored_file instance if exists, false if not
*/
public function get_file_by_hash($pathnamehash) {
global $DB;
$sql = "SELECT ".self::instance_sql_fields('f', 'r')."
FROM {files} f
LEFT JOIN {files_reference} r
ON f.referencefileid = r.id
WHERE f.pathnamehash = ?";
if ($filerecord = $DB->get_record_sql($sql, array($pathnamehash))) {
return $this->get_file_instance($filerecord);
} else {
return false;
}
}
/**
* Fetch locally stored file.
*
* @param int $contextid context ID
* @param string $component component
* @param string $filearea file area
* @param int $itemid item ID
* @param string $filepath file path
* @param string $filename file name
* @return stored_file|bool stored_file instance if exists, false if not
*/
public function get_file($contextid, $component, $filearea, $itemid, $filepath, $filename) {
$filepath = clean_param($filepath, PARAM_PATH);
$filename = clean_param($filename, PARAM_FILE);
if ($filename === '') {
$filename = '.';
}
$pathnamehash = $this->get_pathname_hash($contextid, $component, $filearea, $itemid, $filepath, $filename);
return $this->get_file_by_hash($pathnamehash);
}
/**
* Are there any files (or directories)
*
* @param int $contextid context ID
* @param string $component component
* @param string $filearea file area
* @param bool|int $itemid item id or false if all items
* @param bool $ignoredirs whether or not ignore directories
* @return bool empty
*/
public function is_area_empty($contextid, $component, $filearea, $itemid = false, $ignoredirs = true) {
global $DB;
$params = array('contextid'=>$contextid, 'component'=>$component, 'filearea'=>$filearea);
$where = "contextid = :contextid AND component = :component AND filearea = :filearea";
if ($itemid !== false) {
$params['itemid'] = $itemid;
$where .= " AND itemid = :itemid";
}
if ($ignoredirs) {
$sql = "SELECT 'x'
FROM {files}
WHERE $where AND filename <> '.'";
} else {
$sql = "SELECT 'x'
FROM {files}
WHERE $where AND (filename <> '.' OR filepath <> '/')";
}
return !$DB->record_exists_sql($sql, $params);
}
/**
* Returns all files belonging to given repository
*
* @param int $repositoryid
* @param string $sort A fragment of SQL to use for sorting
*/
public function get_external_files($repositoryid, $sort = '') {
global $DB;
$sql = "SELECT ".self::instance_sql_fields('f', 'r')."
FROM {files} f
LEFT JOIN {files_reference} r
ON f.referencefileid = r.id
WHERE r.repositoryid = ?";
if (!empty($sort)) {
$sql .= " ORDER BY {$sort}";
}
$result = array();
$filerecords = $DB->get_records_sql($sql, array($repositoryid));
foreach ($filerecords as $filerecord) {
$result[$filerecord->pathnamehash] = $this->get_file_instance($filerecord);
}
return $result;
}
/**
* Returns all area files (optionally limited by itemid)
*
* @param int $contextid context ID
* @param string $component component
* @param mixed $filearea file area/s, you cannot specify multiple fileareas as well as an itemid
* @param int $itemid item ID or all files if not specified
* @param string $sort A fragment of SQL to use for sorting
* @param bool $includedirs whether or not include directories
* @param int $updatedsince return files updated since this time
* @param int $limitfrom return a subset of records, starting at this point (optional).
* @param int $limitnum return a subset comprising this many records in total (optional, required if $limitfrom is set).
* @return stored_file[] array of stored_files indexed by pathanmehash
*/
public function get_area_files($contextid, $component, $filearea, $itemid = false, $sort = "itemid, filepath, filename",
$includedirs = true, $updatedsince = 0, $limitfrom = 0, $limitnum = 0) {
global $DB;
list($areasql, $conditions) = $DB->get_in_or_equal($filearea, SQL_PARAMS_NAMED);
$conditions['contextid'] = $contextid;
$conditions['component'] = $component;
if ($itemid !== false && is_array($filearea)) {
throw new coding_exception('You cannot specify multiple fileareas as well as an itemid.');
} else if ($itemid !== false) {
$itemidsql = ' AND f.itemid = :itemid ';
$conditions['itemid'] = $itemid;
} else {
$itemidsql = '';
}
$updatedsincesql = '';
if (!empty($updatedsince)) {
$conditions['time'] = $updatedsince;
$updatedsincesql = 'AND f.timemodified > :time';
}
$includedirssql = '';
if (!$includedirs) {
$includedirssql = 'AND f.filename != :dot';
$conditions['dot'] = '.';
}
if ($limitfrom && !$limitnum) {
throw new coding_exception('If specifying $limitfrom you must also specify $limitnum');
}
$sql = "SELECT ".self::instance_sql_fields('f', 'r')."
FROM {files} f
LEFT JOIN {files_reference} r
ON f.referencefileid = r.id
WHERE f.contextid = :contextid
AND f.component = :component
AND f.filearea $areasql
$includedirssql
$updatedsincesql
$itemidsql";
if (!empty($sort)) {
$sql .= " ORDER BY {$sort}";
}
$result = array();
$filerecords = $DB->get_records_sql($sql, $conditions, $limitfrom, $limitnum);
foreach ($filerecords as $filerecord) {
$result[$filerecord->pathnamehash] = $this->get_file_instance($filerecord);
}
return $result;
}
/**
* Returns array based tree structure of area files
*
* @param int $contextid context ID
* @param string $component component
* @param string $filearea file area
* @param int $itemid item ID
* @return array each dir represented by dirname, subdirs, files and dirfile array elements
*/
public function get_area_tree($contextid, $component, $filearea, $itemid) {
$result = array('dirname'=>'', 'dirfile'=>null, 'subdirs'=>array(), 'files'=>array());
$files = $this->get_area_files($contextid, $component, $filearea, $itemid, '', true);
// first create directory structure
foreach ($files as $hash=>$dir) {
if (!$dir->is_directory()) {
continue;
}
unset($files[$hash]);
if ($dir->get_filepath() === '/') {
$result['dirfile'] = $dir;
continue;
}
$parts = explode('/', trim($dir->get_filepath(),'/'));
$pointer =& $result;
foreach ($parts as $part) {
if ($part === '') {
continue;
}
if (!isset($pointer['subdirs'][$part])) {
$pointer['subdirs'][$part] = array('dirname'=>$part, 'dirfile'=>null, 'subdirs'=>array(), 'files'=>array());
}
$pointer =& $pointer['subdirs'][$part];
}
$pointer['dirfile'] = $dir;
unset($pointer);
}
foreach ($files as $hash=>$file) {
$parts = explode('/', trim($file->get_filepath(),'/'));
$pointer =& $result;
foreach ($parts as $part) {
if ($part === '') {
continue;
}
$pointer =& $pointer['subdirs'][$part];
}
$pointer['files'][$file->get_filename()] = $file;
unset($pointer);
}
$result = $this->sort_area_tree($result);
return $result;
}
/**
* Sorts the result of {@link file_storage::get_area_tree()}.
*
* @param array $tree Array of results provided by {@link file_storage::get_area_tree()}
* @return array of sorted results
*/
protected function sort_area_tree($tree) {
foreach ($tree as $key => &$value) {
if ($key == 'subdirs') {
core_collator::ksort($value, core_collator::SORT_NATURAL);
foreach ($value as $subdirname => &$subtree) {
$subtree = $this->sort_area_tree($subtree);
}
} else if ($key == 'files') {
core_collator::ksort($value, core_collator::SORT_NATURAL);
}
}
return $tree;
}
/**
* Returns all files and optionally directories
*
* @param int $contextid context ID
* @param string $component component
* @param string $filearea file area
* @param int $itemid item ID
* @param int $filepath directory path
* @param bool $recursive include all subdirectories
* @param bool $includedirs include files and directories
* @param string $sort A fragment of SQL to use for sorting
* @return array of stored_files indexed by pathanmehash
*/
public function get_directory_files($contextid, $component, $filearea, $itemid, $filepath, $recursive = false, $includedirs = true, $sort = "filepath, filename") {
global $DB;
if (!$directory = $this->get_file($contextid, $component, $filearea, $itemid, $filepath, '.')) {
return array();
}
$orderby = (!empty($sort)) ? " ORDER BY {$sort}" : '';
if ($recursive) {
$dirs = $includedirs ? "" : "AND filename <> '.'";
$length = core_text::strlen($filepath);
$sql = "SELECT ".self::instance_sql_fields('f', 'r')."
FROM {files} f
LEFT JOIN {files_reference} r
ON f.referencefileid = r.id
WHERE f.contextid = :contextid AND f.component = :component AND f.filearea = :filearea AND f.itemid = :itemid
AND ".$DB->sql_substr("f.filepath", 1, $length)." = :filepath
AND f.id <> :dirid
$dirs
$orderby";
$params = array('contextid'=>$contextid, 'component'=>$component, 'filearea'=>$filearea, 'itemid'=>$itemid, 'filepath'=>$filepath, 'dirid'=>$directory->get_id());
$files = array();
$dirs = array();
$filerecords = $DB->get_records_sql($sql, $params);
foreach ($filerecords as $filerecord) {
if ($filerecord->filename == '.') {
$dirs[$filerecord->pathnamehash] = $this->get_file_instance($filerecord);
} else {
$files[$filerecord->pathnamehash] = $this->get_file_instance($filerecord);
}
}
$result = array_merge($dirs, $files);
} else {
$result = array();
$params = array('contextid'=>$contextid, 'component'=>$component, 'filearea'=>$filearea, 'itemid'=>$itemid, 'filepath'=>$filepath, 'dirid'=>$directory->get_id());
$length = core_text::strlen($filepath);
if ($includedirs) {
$sql = "SELECT ".self::instance_sql_fields('f', 'r')."
FROM {files} f
LEFT JOIN {files_reference} r
ON f.referencefileid = r.id
WHERE f.contextid = :contextid AND f.component = :component AND f.filearea = :filearea
AND f.itemid = :itemid AND f.filename = '.'
AND ".$DB->sql_substr("f.filepath", 1, $length)." = :filepath
AND f.id <> :dirid
$orderby";
$reqlevel = substr_count($filepath, '/') + 1;
$filerecords = $DB->get_records_sql($sql, $params);
foreach ($filerecords as $filerecord) {
if (substr_count($filerecord->filepath, '/') !== $reqlevel) {
continue;
}
$result[$filerecord->pathnamehash] = $this->get_file_instance($filerecord);
}
}
$sql = "SELECT ".self::instance_sql_fields('f', 'r')."
FROM {files} f
LEFT JOIN {files_reference} r
ON f.referencefileid = r.id
WHERE f.contextid = :contextid AND f.component = :component AND f.filearea = :filearea AND f.itemid = :itemid
AND f.filepath = :filepath AND f.filename <> '.'
$orderby";
$filerecords = $DB->get_records_sql($sql, $params);
foreach ($filerecords as $filerecord) {
$result[$filerecord->pathnamehash] = $this->get_file_instance($filerecord);
}
}
return $result;
}
/**
* Delete all area files (optionally limited by itemid).
*
* @param int $contextid context ID
* @param string $component component
* @param string $filearea file area or all areas in context if not specified
* @param int $itemid item ID or all files if not specified
* @return bool success
*/
public function delete_area_files($contextid, $component = false, $filearea = false, $itemid = false) {
global $DB;
$conditions = array('contextid'=>$contextid);
if ($component !== false) {
$conditions['component'] = $component;
}
if ($filearea !== false) {
$conditions['filearea'] = $filearea;
}
if ($itemid !== false) {
$conditions['itemid'] = $itemid;
}
$filerecords = $DB->get_records('files', $conditions);
foreach ($filerecords as $filerecord) {
$this->get_file_instance($filerecord)->delete();
}
return true; // BC only
}
/**
* Delete all the files from certain areas where itemid is limited by an
* arbitrary bit of SQL.
*
* @param int $contextid the id of the context the files belong to. Must be given.
* @param string $component the owning component. Must be given.
* @param string $filearea the file area name. Must be given.
* @param string $itemidstest an SQL fragment that the itemid must match. Used
* in the query like WHERE itemid $itemidstest. Must used named parameters,
* and may not used named parameters called contextid, component or filearea.
* @param array $params any query params used by $itemidstest.
*/
public function delete_area_files_select($contextid, $component,
$filearea, $itemidstest, array $params = null) {
global $DB;
$where = "contextid = :contextid
AND component = :component
AND filearea = :filearea
AND itemid $itemidstest";
$params['contextid'] = $contextid;
$params['component'] = $component;
$params['filearea'] = $filearea;
$filerecords = $DB->get_recordset_select('files', $where, $params);
foreach ($filerecords as $filerecord) {
$this->get_file_instance($filerecord)->delete();
}
$filerecords->close();
}
/**
* Delete all files associated with the given component.
*
* @param string $component the component owning the file
*/
public function delete_component_files($component) {
global $DB;
$filerecords = $DB->get_recordset('files', array('component' => $component));
foreach ($filerecords as $filerecord) {
$this->get_file_instance($filerecord)->delete();
}
$filerecords->close();
}
/**
* Move all the files in a file area from one context to another.
*
* @param int $oldcontextid the context the files are being moved from.
* @param int $newcontextid the context the files are being moved to.
* @param string $component the plugin that these files belong to.
* @param string $filearea the name of the file area.
* @param int $itemid file item ID
* @return int the number of files moved, for information.
*/
public function move_area_files_to_new_context($oldcontextid, $newcontextid, $component, $filearea, $itemid = false) {
// Note, this code is based on some code that Petr wrote in
// forum_move_attachments in mod/forum/lib.php. I moved it here because
// I needed it in the question code too.
$count = 0;
$oldfiles = $this->get_area_files($oldcontextid, $component, $filearea, $itemid, 'id', false);
foreach ($oldfiles as $oldfile) {
$filerecord = new stdClass();
$filerecord->contextid = $newcontextid;
$this->create_file_from_storedfile($filerecord, $oldfile);
$count += 1;
}
if ($count) {
$this->delete_area_files($oldcontextid, $component, $filearea, $itemid);
}
return $count;
}
/**
* Recursively creates directory.
*
* @param int $contextid context ID
* @param string $component component
* @param string $filearea file area
* @param int $itemid item ID
* @param string $filepath file path
* @param int $userid the user ID
* @return bool success
*/
public function create_directory($contextid, $component, $filearea, $itemid, $filepath, $userid = null) {
global $DB;
// validate all parameters, we do not want any rubbish stored in database, right?
if (!is_number($contextid) or $contextid < 1) {
throw new file_exception('storedfileproblem', 'Invalid contextid');
}
$component = clean_param($component, PARAM_COMPONENT);
if (empty($component)) {
throw new file_exception('storedfileproblem', 'Invalid component');
}
$filearea = clean_param($filearea, PARAM_AREA);
if (empty($filearea)) {
throw new file_exception('storedfileproblem', 'Invalid filearea');
}
if (!is_number($itemid) or $itemid < 0) {
throw new file_exception('storedfileproblem', 'Invalid itemid');
}
$filepath = clean_param($filepath, PARAM_PATH);
if (strpos($filepath, '/') !== 0 or strrpos($filepath, '/') !== strlen($filepath)-1) {
// path must start and end with '/'
throw new file_exception('storedfileproblem', 'Invalid file path');
}
$pathnamehash = $this->get_pathname_hash($contextid, $component, $filearea, $itemid, $filepath, '.');
if ($dir_info = $this->get_file_by_hash($pathnamehash)) {
return $dir_info;
}
static $contenthash = null;
if (!$contenthash) {
$this->add_string_to_pool('');
$contenthash = self::hash_from_string('');
}
$now = time();
$dir_record = new stdClass();
$dir_record->contextid = $contextid;
$dir_record->component = $component;
$dir_record->filearea = $filearea;
$dir_record->itemid = $itemid;
$dir_record->filepath = $filepath;
$dir_record->filename = '.';
$dir_record->contenthash = $contenthash;
$dir_record->filesize = 0;
$dir_record->timecreated = $now;