forked from tmuras/moodle
-
Notifications
You must be signed in to change notification settings - Fork 0
/
lib.php
2866 lines (2595 loc) · 104 KB
/
lib.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/>.
/**
* This file contains classes used to manage the repository plugins in Moodle
*
* @since 2.0
* @package core_repository
* @copyright 2009 Dongsheng Cai {@link http://dongsheng.org}
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
require_once(dirname(dirname(__FILE__)) . '/config.php');
require_once($CFG->libdir . '/filelib.php');
require_once($CFG->libdir . '/formslib.php');
define('FILE_EXTERNAL', 1);
define('FILE_INTERNAL', 2);
define('FILE_REFERENCE', 4);
define('RENAME_SUFFIX', '_2');
/**
* This class is used to manage repository plugins
*
* A repository_type is a repository plug-in. It can be Box.net, Flick-r, ...
* A repository type can be edited, sorted and hidden. It is mandatory for an
* administrator to create a repository type in order to be able to create
* some instances of this type.
* Coding note:
* - a repository_type object is mapped to the "repository" database table
* - "typename" attibut maps the "type" database field. It is unique.
* - general "options" for a repository type are saved in the config_plugin table
* - when you delete a repository, all instances are deleted, and general
* options are also deleted from database
* - When you create a type for a plugin that can't have multiple instances, a
* instance is automatically created.
*
* @package core_repository
* @copyright 2009 Jerome Mouneyrac
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class repository_type {
/**
* Type name (no whitespace) - A type name is unique
* Note: for a user-friendly type name see get_readablename()
* @var String
*/
private $_typename;
/**
* Options of this type
* They are general options that any instance of this type would share
* e.g. API key
* These options are saved in config_plugin table
* @var array
*/
private $_options;
/**
* Is the repository type visible or hidden
* If false (hidden): no instances can be created, edited, deleted, showned , used...
* @var boolean
*/
private $_visible;
/**
* 0 => not ordered, 1 => first position, 2 => second position...
* A not order type would appear in first position (should never happened)
* @var integer
*/
private $_sortorder;
/**
* Return if the instance is visible in a context
*
* @todo check if the context visibility has been overwritten by the plugin creator
* (need to create special functions to be overvwritten in repository class)
* @param stdClass $context context
* @return bool
*/
public function get_contextvisibility($context) {
global $USER;
if ($context->contextlevel == CONTEXT_COURSE) {
return $this->_options['enablecourseinstances'];
}
if ($context->contextlevel == CONTEXT_USER) {
return $this->_options['enableuserinstances'];
}
//the context is SITE
return true;
}
/**
* repository_type constructor
*
* @param int $typename
* @param array $typeoptions
* @param bool $visible
* @param int $sortorder (don't really need set, it will be during create() call)
*/
public function __construct($typename = '', $typeoptions = array(), $visible = true, $sortorder = 0) {
global $CFG;
//set type attributs
$this->_typename = $typename;
$this->_visible = $visible;
$this->_sortorder = $sortorder;
//set options attribut
$this->_options = array();
$options = repository::static_function($typename, 'get_type_option_names');
//check that the type can be setup
if (!empty($options)) {
//set the type options
foreach ($options as $config) {
if (array_key_exists($config, $typeoptions)) {
$this->_options[$config] = $typeoptions[$config];
}
}
}
//retrieve visibility from option
if (array_key_exists('enablecourseinstances',$typeoptions)) {
$this->_options['enablecourseinstances'] = $typeoptions['enablecourseinstances'];
} else {
$this->_options['enablecourseinstances'] = 0;
}
if (array_key_exists('enableuserinstances',$typeoptions)) {
$this->_options['enableuserinstances'] = $typeoptions['enableuserinstances'];
} else {
$this->_options['enableuserinstances'] = 0;
}
}
/**
* Get the type name (no whitespace)
* For a human readable name, use get_readablename()
*
* @return string the type name
*/
public function get_typename() {
return $this->_typename;
}
/**
* Return a human readable and user-friendly type name
*
* @return string user-friendly type name
*/
public function get_readablename() {
return get_string('pluginname','repository_'.$this->_typename);
}
/**
* Return general options
*
* @return array the general options
*/
public function get_options() {
return $this->_options;
}
/**
* Return visibility
*
* @return bool
*/
public function get_visible() {
return $this->_visible;
}
/**
* Return order / position of display in the file picker
*
* @return int
*/
public function get_sortorder() {
return $this->_sortorder;
}
/**
* Create a repository type (the type name must not already exist)
* @param bool $silent throw exception?
* @return mixed return int if create successfully, return false if
*/
public function create($silent = false) {
global $DB;
//check that $type has been set
$timmedtype = trim($this->_typename);
if (empty($timmedtype)) {
throw new repository_exception('emptytype', 'repository');
}
//set sortorder as the last position in the list
if (!isset($this->_sortorder) || $this->_sortorder == 0 ) {
$sql = "SELECT MAX(sortorder) FROM {repository}";
$this->_sortorder = 1 + $DB->get_field_sql($sql);
}
//only create a new type if it doesn't already exist
$existingtype = $DB->get_record('repository', array('type'=>$this->_typename));
if (!$existingtype) {
//create the type
$newtype = new stdClass();
$newtype->type = $this->_typename;
$newtype->visible = $this->_visible;
$newtype->sortorder = $this->_sortorder;
$plugin_id = $DB->insert_record('repository', $newtype);
//save the options in DB
$this->update_options();
$instanceoptionnames = repository::static_function($this->_typename, 'get_instance_option_names');
//if the plugin type has no multiple instance (e.g. has no instance option name) so it wont
//be possible for the administrator to create a instance
//in this case we need to create an instance
if (empty($instanceoptionnames)) {
$instanceoptions = array();
if (empty($this->_options['pluginname'])) {
// when moodle trying to install some repo plugin automatically
// this option will be empty, get it from language string when display
$instanceoptions['name'] = '';
} else {
// when admin trying to add a plugin manually, he will type a name
// for it
$instanceoptions['name'] = $this->_options['pluginname'];
}
repository::static_function($this->_typename, 'create', $this->_typename, 0, get_system_context(), $instanceoptions);
}
//run plugin_init function
if (!repository::static_function($this->_typename, 'plugin_init')) {
if (!$silent) {
throw new repository_exception('cannotinitplugin', 'repository');
}
}
if(!empty($plugin_id)) {
// return plugin_id if create successfully
return $plugin_id;
} else {
return false;
}
} else {
if (!$silent) {
throw new repository_exception('existingrepository', 'repository');
}
// If plugin existed, return false, tell caller no new plugins were created.
return false;
}
}
/**
* Update plugin options into the config_plugin table
*
* @param array $options
* @return bool
*/
public function update_options($options = null) {
global $DB;
$classname = 'repository_' . $this->_typename;
$instanceoptions = repository::static_function($this->_typename, 'get_instance_option_names');
if (empty($instanceoptions)) {
// update repository instance name if this plugin type doesn't have muliti instances
$params = array();
$params['type'] = $this->_typename;
$instances = repository::get_instances($params);
$instance = array_pop($instances);
if ($instance) {
$DB->set_field('repository_instances', 'name', $options['pluginname'], array('id'=>$instance->id));
}
unset($options['pluginname']);
}
if (!empty($options)) {
$this->_options = $options;
}
foreach ($this->_options as $name => $value) {
set_config($name, $value, $this->_typename);
}
return true;
}
/**
* Update visible database field with the value given as parameter
* or with the visible value of this object
* This function is private.
* For public access, have a look to switch_and_update_visibility()
*
* @param bool $visible
* @return bool
*/
private function update_visible($visible = null) {
global $DB;
if (!empty($visible)) {
$this->_visible = $visible;
}
else if (!isset($this->_visible)) {
throw new repository_exception('updateemptyvisible', 'repository');
}
return $DB->set_field('repository', 'visible', $this->_visible, array('type'=>$this->_typename));
}
/**
* Update database sortorder field with the value given as parameter
* or with the sortorder value of this object
* This function is private.
* For public access, have a look to move_order()
*
* @param int $sortorder
* @return bool
*/
private function update_sortorder($sortorder = null) {
global $DB;
if (!empty($sortorder) && $sortorder!=0) {
$this->_sortorder = $sortorder;
}
//if sortorder is not set, we set it as the ;ast position in the list
else if (!isset($this->_sortorder) || $this->_sortorder == 0 ) {
$sql = "SELECT MAX(sortorder) FROM {repository}";
$this->_sortorder = 1 + $DB->get_field_sql($sql);
}
return $DB->set_field('repository', 'sortorder', $this->_sortorder, array('type'=>$this->_typename));
}
/**
* Change order of the type with its adjacent upper or downer type
* (database fields are updated)
* Algorithm details:
* 1. retrieve all types in an array. This array is sorted by sortorder,
* and the array keys start from 0 to X (incremented by 1)
* 2. switch sortorder values of this type and its adjacent type
*
* @param string $move "up" or "down"
*/
public function move_order($move) {
global $DB;
$types = repository::get_types(); // retrieve all types
// retrieve this type into the returned array
$i = 0;
while (!isset($indice) && $i<count($types)) {
if ($types[$i]->get_typename() == $this->_typename) {
$indice = $i;
}
$i++;
}
// retrieve adjacent indice
switch ($move) {
case "up":
$adjacentindice = $indice - 1;
break;
case "down":
$adjacentindice = $indice + 1;
break;
default:
throw new repository_exception('movenotdefined', 'repository');
}
//switch sortorder of this type and the adjacent type
//TODO: we could reset sortorder for all types. This is not as good in performance term, but
//that prevent from wrong behaviour on a screwed database. As performance are not important in this particular case
//it worth to change the algo.
if ($adjacentindice>=0 && !empty($types[$adjacentindice])) {
$DB->set_field('repository', 'sortorder', $this->_sortorder, array('type'=>$types[$adjacentindice]->get_typename()));
$this->update_sortorder($types[$adjacentindice]->get_sortorder());
}
}
/**
* 1. Change visibility to the value chosen
* 2. Update the type
*
* @param bool $visible
* @return bool
*/
public function update_visibility($visible = null) {
if (is_bool($visible)) {
$this->_visible = $visible;
} else {
$this->_visible = !$this->_visible;
}
return $this->update_visible();
}
/**
* Delete a repository_type (general options are removed from config_plugin
* table, and all instances are deleted)
*
* @param bool $downloadcontents download external contents if exist
* @return bool
*/
public function delete($downloadcontents = false) {
global $DB;
//delete all instances of this type
$params = array();
$params['context'] = array();
$params['onlyvisible'] = false;
$params['type'] = $this->_typename;
$instances = repository::get_instances($params);
foreach ($instances as $instance) {
$instance->delete($downloadcontents);
}
//delete all general options
foreach ($this->_options as $name => $value) {
set_config($name, null, $this->_typename);
}
try {
$DB->delete_records('repository', array('type' => $this->_typename));
} catch (dml_exception $ex) {
return false;
}
return true;
}
}
/**
* This is the base class of the repository class.
*
* To create repository plugin, see: {@link http://docs.moodle.org/dev/Repository_plugins}
* See an example: {@link repository_boxnet}
*
* @package core_repository
* @copyright 2009 Dongsheng Cai {@link http://dongsheng.org}
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
abstract class repository {
/** Timeout in seconds for downloading the external file into moodle */
const GETFILE_TIMEOUT = 30;
/** Timeout in seconds for syncronising the external file size */
const SYNCFILE_TIMEOUT = 1;
/** Timeout in seconds for downloading an image file from external repository during syncronisation */
const SYNCIMAGE_TIMEOUT = 3;
// $disabled can be set to true to disable a plugin by force
// example: self::$disabled = true
/** @var bool force disable repository instance */
public $disabled = false;
/** @var int repository instance id */
public $id;
/** @var stdClass current context */
public $context;
/** @var array repository options */
public $options;
/** @var bool Whether or not the repository instance is editable */
public $readonly;
/** @var int return types */
public $returntypes;
/** @var stdClass repository instance database record */
public $instance;
/**
* Constructor
*
* @param int $repositoryid repository instance id
* @param int|stdClass $context a context id or context object
* @param array $options repository options
* @param int $readonly indicate this repo is readonly or not
*/
public function __construct($repositoryid, $context = SYSCONTEXTID, $options = array(), $readonly = 0) {
global $DB;
$this->id = $repositoryid;
if (is_object($context)) {
$this->context = $context;
} else {
$this->context = context::instance_by_id($context);
}
$this->instance = $DB->get_record('repository_instances', array('id'=>$this->id));
$this->readonly = $readonly;
$this->options = array();
if (is_array($options)) {
// The get_option() method will get stored options in database.
$options = array_merge($this->get_option(), $options);
} else {
$options = $this->get_option();
}
foreach ($options as $n => $v) {
$this->options[$n] = $v;
}
$this->name = $this->get_name();
$this->returntypes = $this->supported_returntypes();
$this->super_called = true;
}
/**
* Get repository instance using repository id
*
* @param int $repositoryid repository ID
* @param stdClass|int $context context instance or context ID
* @param array $options additional repository options
* @return repository
*/
public static function get_repository_by_id($repositoryid, $context, $options = array()) {
global $CFG, $DB;
$sql = 'SELECT i.name, i.typeid, r.type FROM {repository} r, {repository_instances} i WHERE i.id=? AND i.typeid=r.id';
if (!$record = $DB->get_record_sql($sql, array($repositoryid))) {
throw new repository_exception('invalidrepositoryid', 'repository');
} else {
$type = $record->type;
if (file_exists($CFG->dirroot . "/repository/$type/lib.php")) {
require_once($CFG->dirroot . "/repository/$type/lib.php");
$classname = 'repository_' . $type;
$contextid = $context;
if (is_object($context)) {
$contextid = $context->id;
}
$options['type'] = $type;
$options['typeid'] = $record->typeid;
if (empty($options['name'])) {
$options['name'] = $record->name;
}
$repository = new $classname($repositoryid, $contextid, $options);
return $repository;
} else {
throw new repository_exception('invalidplugin', 'repository');
}
}
}
/**
* Get a repository type object by a given type name.
*
* @static
* @param string $typename the repository type name
* @return repository_type|bool
*/
public static function get_type_by_typename($typename) {
global $DB;
if (!$record = $DB->get_record('repository',array('type' => $typename))) {
return false;
}
return new repository_type($typename, (array)get_config($typename), $record->visible, $record->sortorder);
}
/**
* Get the repository type by a given repository type id.
*
* @static
* @param int $id the type id
* @return object
*/
public static function get_type_by_id($id) {
global $DB;
if (!$record = $DB->get_record('repository',array('id' => $id))) {
return false;
}
return new repository_type($record->type, (array)get_config($record->type), $record->visible, $record->sortorder);
}
/**
* Return all repository types ordered by sortorder field
* first repository type in returnedarray[0], second repository type in returnedarray[1], ...
*
* @static
* @param bool $visible can return types by visiblity, return all types if null
* @return array Repository types
*/
public static function get_types($visible=null) {
global $DB, $CFG;
$types = array();
$params = null;
if (!empty($visible)) {
$params = array('visible' => $visible);
}
if ($records = $DB->get_records('repository',$params,'sortorder')) {
foreach($records as $type) {
if (file_exists($CFG->dirroot . '/repository/'. $type->type .'/lib.php')) {
$types[] = new repository_type($type->type, (array)get_config($type->type), $type->visible, $type->sortorder);
}
}
}
return $types;
}
/**
* Checks if user has a capability to view the current repository in current context
*
* @return bool
*/
public final function check_capability() {
$capability = false;
if (preg_match("/^repository_(.*)$/", get_class($this), $matches)) {
$type = $matches[1];
$capability = has_capability('repository/'.$type.':view', $this->context);
}
if (!$capability) {
throw new repository_exception('nopermissiontoaccess', 'repository');
}
}
/**
* Check if file already exists in draft area
*
* @static
* @param int $itemid
* @param string $filepath
* @param string $filename
* @return bool
*/
public static function draftfile_exists($itemid, $filepath, $filename) {
global $USER;
$fs = get_file_storage();
$usercontext = context_user::instance($USER->id);
if ($fs->get_file($usercontext->id, 'user', 'draft', $itemid, $filepath, $filename)) {
return true;
} else {
return false;
}
}
/**
* Parses the 'source' returned by moodle repositories and returns an instance of stored_file
*
* @param string $source
* @return stored_file|null
*/
public static function get_moodle_file($source) {
$params = file_storage::unpack_reference($source, true);
$fs = get_file_storage();
return $fs->get_file($params['contextid'], $params['component'], $params['filearea'],
$params['itemid'], $params['filepath'], $params['filename']);
}
/**
* Repository method to make sure that user can access particular file.
*
* This is checked when user tries to pick the file from repository to deal with
* potential parameter substitutions is request
*
* @param string $source
* @return bool whether the file is accessible by current user
*/
public function file_is_accessible($source) {
if ($this->has_moodle_files()) {
try {
$params = file_storage::unpack_reference($source, true);
} catch (file_reference_exception $e) {
return false;
}
$browser = get_file_browser();
$context = context::instance_by_id($params['contextid']);
$file_info = $browser->get_file_info($context, $params['component'], $params['filearea'],
$params['itemid'], $params['filepath'], $params['filename']);
return !empty($file_info);
}
return true;
}
/**
* This function is used to copy a moodle file to draft area.
*
* It DOES NOT check if the user is allowed to access this file because the actual file
* can be located in the area where user does not have access to but there is an alias
* to this file in the area where user CAN access it.
* {@link file_is_accessible} should be called for alias location before calling this function.
*
* @param string $source The metainfo of file, it is base64 encoded php serialized data
* @param stdClass|array $filerecord contains itemid, filepath, filename and optionally other
* attributes of the new file
* @param int $maxbytes maximum allowed size of file, -1 if unlimited. If size of file exceeds
* the limit, the file_exception is thrown.
* @return array The information about the created file
*/
public function copy_to_area($source, $filerecord, $maxbytes = -1) {
global $USER;
$fs = get_file_storage();
if ($this->has_moodle_files() == false) {
throw new coding_exception('Only repository used to browse moodle files can use repository::copy_to_area()');
}
$user_context = context_user::instance($USER->id);
$filerecord = (array)$filerecord;
// make sure the new file will be created in user draft area
$filerecord['component'] = 'user';
$filerecord['filearea'] = 'draft';
$filerecord['contextid'] = $user_context->id;
$draftitemid = $filerecord['itemid'];
$new_filepath = $filerecord['filepath'];
$new_filename = $filerecord['filename'];
// the file needs to copied to draft area
$stored_file = self::get_moodle_file($source);
if ($maxbytes != -1 && $stored_file->get_filesize() > $maxbytes) {
throw new file_exception('maxbytes');
}
if (repository::draftfile_exists($draftitemid, $new_filepath, $new_filename)) {
// create new file
$unused_filename = repository::get_unused_filename($draftitemid, $new_filepath, $new_filename);
$filerecord['filename'] = $unused_filename;
$fs->create_file_from_storedfile($filerecord, $stored_file);
$event = array();
$event['event'] = 'fileexists';
$event['newfile'] = new stdClass;
$event['newfile']->filepath = $new_filepath;
$event['newfile']->filename = $unused_filename;
$event['newfile']->url = moodle_url::make_draftfile_url($draftitemid, $new_filepath, $unused_filename)->out();
$event['existingfile'] = new stdClass;
$event['existingfile']->filepath = $new_filepath;
$event['existingfile']->filename = $new_filename;
$event['existingfile']->url = moodle_url::make_draftfile_url($draftitemid, $new_filepath, $new_filename)->out();
return $event;
} else {
$fs->create_file_from_storedfile($filerecord, $stored_file);
$info = array();
$info['itemid'] = $draftitemid;
$info['file'] = $new_filename;
$info['title'] = $new_filename;
$info['contextid'] = $user_context->id;
$info['url'] = moodle_url::make_draftfile_url($draftitemid, $new_filepath, $new_filename)->out();
$info['filesize'] = $stored_file->get_filesize();
return $info;
}
}
/**
* Get unused filename by appending suffix
*
* @static
* @param int $itemid
* @param string $filepath
* @param string $filename
* @return string
*/
public static function get_unused_filename($itemid, $filepath, $filename) {
global $USER;
$fs = get_file_storage();
while (repository::draftfile_exists($itemid, $filepath, $filename)) {
$filename = repository::append_suffix($filename);
}
return $filename;
}
/**
* Append a suffix to filename
*
* @static
* @param string $filename
* @return string
*/
public static function append_suffix($filename) {
$pathinfo = pathinfo($filename);
if (empty($pathinfo['extension'])) {
return $filename . RENAME_SUFFIX;
} else {
return $pathinfo['filename'] . RENAME_SUFFIX . '.' . $pathinfo['extension'];
}
}
/**
* Return all types that you a user can create/edit and which are also visible
* Note: Mostly used in order to know if at least one editable type can be set
*
* @static
* @param stdClass $context the context for which we want the editable types
* @return array types
*/
public static function get_editable_types($context = null) {
if (empty($context)) {
$context = get_system_context();
}
$types= repository::get_types(true);
$editabletypes = array();
foreach ($types as $type) {
$instanceoptionnames = repository::static_function($type->get_typename(), 'get_instance_option_names');
if (!empty($instanceoptionnames)) {
if ($type->get_contextvisibility($context)) {
$editabletypes[]=$type;
}
}
}
return $editabletypes;
}
/**
* Return repository instances
*
* @static
* @param array $args Array containing the following keys:
* currentcontext
* context
* onlyvisible
* type
* accepted_types
* return_types
* userid
*
* @return array repository instances
*/
public static function get_instances($args = array()) {
global $DB, $CFG, $USER;
if (isset($args['currentcontext'])) {
$current_context = $args['currentcontext'];
} else {
$current_context = null;
}
if (!empty($args['context'])) {
$contexts = $args['context'];
} else {
$contexts = array();
}
$onlyvisible = isset($args['onlyvisible']) ? $args['onlyvisible'] : true;
$returntypes = isset($args['return_types']) ? $args['return_types'] : 3;
$type = isset($args['type']) ? $args['type'] : null;
$params = array();
$sql = "SELECT i.*, r.type AS repositorytype, r.sortorder, r.visible
FROM {repository} r, {repository_instances} i
WHERE i.typeid = r.id ";
if (!empty($args['disable_types']) && is_array($args['disable_types'])) {
list($types, $p) = $DB->get_in_or_equal($args['disable_types'], SQL_PARAMS_QM, 'param', false);
$sql .= " AND r.type $types";
$params = array_merge($params, $p);
}
if (!empty($args['userid']) && is_numeric($args['userid'])) {
$sql .= " AND (i.userid = 0 or i.userid = ?)";
$params[] = $args['userid'];
}
foreach ($contexts as $context) {
if (empty($firstcontext)) {
$firstcontext = true;
$sql .= " AND ((i.contextid = ?)";
} else {
$sql .= " OR (i.contextid = ?)";
}
$params[] = $context->id;
}
if (!empty($firstcontext)) {
$sql .=')';
}
if ($onlyvisible == true) {
$sql .= " AND (r.visible = 1)";
}
if (isset($type)) {
$sql .= " AND (r.type = ?)";
$params[] = $type;
}
$sql .= " ORDER BY r.sortorder, i.name";
if (!$records = $DB->get_records_sql($sql, $params)) {
$records = array();
}
$repositories = array();
if (isset($args['accepted_types'])) {
$accepted_types = $args['accepted_types'];
if (is_array($accepted_types) && in_array('*', $accepted_types)) {
$accepted_types = '*';
}
} else {
$accepted_types = '*';
}
// Sortorder should be unique, which is not true if we use $record->sortorder
// and there are multiple instances of any repository type
$sortorder = 1;
foreach ($records as $record) {
if (!file_exists($CFG->dirroot . '/repository/'. $record->repositorytype.'/lib.php')) {
continue;
}
require_once($CFG->dirroot . '/repository/'. $record->repositorytype.'/lib.php');
$options['visible'] = $record->visible;
$options['type'] = $record->repositorytype;
$options['typeid'] = $record->typeid;
$options['sortorder'] = $sortorder++;
// tell instance what file types will be accepted by file picker
$classname = 'repository_' . $record->repositorytype;
$repository = new $classname($record->id, $record->contextid, $options, $record->readonly);
$is_supported = true;
if (empty($repository->super_called)) {
// to make sure the super construct is called
debugging('parent::__construct must be called by '.$record->repositorytype.' plugin.');
} else {
// check mimetypes
if ($accepted_types !== '*' and $repository->supported_filetypes() !== '*') {
$accepted_ext = file_get_typegroup('extension', $accepted_types);
$supported_ext = file_get_typegroup('extension', $repository->supported_filetypes());
$valid_ext = array_intersect($accepted_ext, $supported_ext);
$is_supported = !empty($valid_ext);
}
// check return values
if ($returntypes !== 3 and $repository->supported_returntypes() !== 3) {
$type = $repository->supported_returntypes();
if ($type & $returntypes) {
//
} else {
$is_supported = false;
}
}
if (!$onlyvisible || ($repository->is_visible() && !$repository->disabled)) {
// check capability in current context
if (!empty($current_context)) {
$capability = has_capability('repository/'.$record->repositorytype.':view', $current_context);
} else {
$capability = has_capability('repository/'.$record->repositorytype.':view', get_system_context());
}
if ($record->repositorytype == 'coursefiles') {
// coursefiles plugin needs managefiles permission
if (!empty($current_context)) {
$capability = $capability && has_capability('moodle/course:managefiles', $current_context);
} else {
$capability = $capability && has_capability('moodle/course:managefiles', get_system_context());
}
}
if ($is_supported && $capability) {
$repositories[$repository->id] = $repository;
}
}
}
}
return $repositories;
}
/**
* Get single repository instance
*
* @static
* @param integer $id repository id
* @return object repository instance
*/
public static function get_instance($id) {
global $DB, $CFG;
$sql = "SELECT i.*, r.type AS repositorytype, r.visible
FROM {repository} r
JOIN {repository_instances} i ON i.typeid = r.id
WHERE i.id = ?";
if (!$instance = $DB->get_record_sql($sql, array($id))) {
return false;
}
require_once($CFG->dirroot . '/repository/'. $instance->repositorytype.'/lib.php');
$classname = 'repository_' . $instance->repositorytype;
$options['typeid'] = $instance->typeid;
$options['type'] = $instance->repositorytype;
$options['name'] = $instance->name;
$obj = new $classname($instance->id, $instance->contextid, $options, $instance->readonly);
if (empty($obj->super_called)) {