Merge branch 'MDL-33122-master' of git://github.com/ankitagarwal/moodle
[moodle.git] / repository / lib.php
blobbb6c4eb4d9f5f71f7cd1e24d22f7b5a962412233
1 <?php
2 // This file is part of Moodle - http://moodle.org/
3 //
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
8 //
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
17 /**
18 * This file contains classes used to manage the repository plugins in Moodle
19 * and was introduced as part of the changes occuring in Moodle 2.0
21 * @since 2.0
22 * @package repository
23 * @copyright 2009 Dongsheng Cai {@link http://dongsheng.org}
24 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
27 require_once(dirname(dirname(__FILE__)) . '/config.php');
28 require_once($CFG->libdir . '/filelib.php');
29 require_once($CFG->libdir . '/formslib.php');
31 define('FILE_EXTERNAL', 1);
32 define('FILE_INTERNAL', 2);
33 define('FILE_REFERENCE', 4);
34 define('RENAME_SUFFIX', '_2');
36 /**
37 * This class is used to manage repository plugins
39 * A repository_type is a repository plug-in. It can be Box.net, Flick-r, ...
40 * A repository type can be edited, sorted and hidden. It is mandatory for an
41 * administrator to create a repository type in order to be able to create
42 * some instances of this type.
43 * Coding note:
44 * - a repository_type object is mapped to the "repository" database table
45 * - "typename" attibut maps the "type" database field. It is unique.
46 * - general "options" for a repository type are saved in the config_plugin table
47 * - when you delete a repository, all instances are deleted, and general
48 * options are also deleted from database
49 * - When you create a type for a plugin that can't have multiple instances, a
50 * instance is automatically created.
52 * @package repository
53 * @copyright 2009 Jerome Mouneyrac
54 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
56 class repository_type {
59 /**
60 * Type name (no whitespace) - A type name is unique
61 * Note: for a user-friendly type name see get_readablename()
62 * @var String
64 private $_typename;
67 /**
68 * Options of this type
69 * They are general options that any instance of this type would share
70 * e.g. API key
71 * These options are saved in config_plugin table
72 * @var array
74 private $_options;
77 /**
78 * Is the repository type visible or hidden
79 * If false (hidden): no instances can be created, edited, deleted, showned , used...
80 * @var boolean
82 private $_visible;
85 /**
86 * 0 => not ordered, 1 => first position, 2 => second position...
87 * A not order type would appear in first position (should never happened)
88 * @var integer
90 private $_sortorder;
92 /**
93 * Return if the instance is visible in a context
95 * @todo check if the context visibility has been overwritten by the plugin creator
96 * (need to create special functions to be overvwritten in repository class)
97 * @param stdClass $context context
98 * @return bool
100 public function get_contextvisibility($context) {
101 global $USER;
103 if ($context->contextlevel == CONTEXT_COURSE) {
104 return $this->_options['enablecourseinstances'];
107 if ($context->contextlevel == CONTEXT_USER) {
108 return $this->_options['enableuserinstances'];
111 //the context is SITE
112 return true;
118 * repository_type constructor
120 * @param int $typename
121 * @param array $typeoptions
122 * @param bool $visible
123 * @param int $sortorder (don't really need set, it will be during create() call)
125 public function __construct($typename = '', $typeoptions = array(), $visible = true, $sortorder = 0) {
126 global $CFG;
128 //set type attributs
129 $this->_typename = $typename;
130 $this->_visible = $visible;
131 $this->_sortorder = $sortorder;
133 //set options attribut
134 $this->_options = array();
135 $options = repository::static_function($typename, 'get_type_option_names');
136 //check that the type can be setup
137 if (!empty($options)) {
138 //set the type options
139 foreach ($options as $config) {
140 if (array_key_exists($config, $typeoptions)) {
141 $this->_options[$config] = $typeoptions[$config];
146 //retrieve visibility from option
147 if (array_key_exists('enablecourseinstances',$typeoptions)) {
148 $this->_options['enablecourseinstances'] = $typeoptions['enablecourseinstances'];
149 } else {
150 $this->_options['enablecourseinstances'] = 0;
153 if (array_key_exists('enableuserinstances',$typeoptions)) {
154 $this->_options['enableuserinstances'] = $typeoptions['enableuserinstances'];
155 } else {
156 $this->_options['enableuserinstances'] = 0;
162 * Get the type name (no whitespace)
163 * For a human readable name, use get_readablename()
165 * @return string the type name
167 public function get_typename() {
168 return $this->_typename;
172 * Return a human readable and user-friendly type name
174 * @return string user-friendly type name
176 public function get_readablename() {
177 return get_string('pluginname','repository_'.$this->_typename);
181 * Return general options
183 * @return array the general options
185 public function get_options() {
186 return $this->_options;
190 * Return visibility
192 * @return bool
194 public function get_visible() {
195 return $this->_visible;
199 * Return order / position of display in the file picker
201 * @return int
203 public function get_sortorder() {
204 return $this->_sortorder;
208 * Create a repository type (the type name must not already exist)
209 * @param bool $silent throw exception?
210 * @return mixed return int if create successfully, return false if
212 public function create($silent = false) {
213 global $DB;
215 //check that $type has been set
216 $timmedtype = trim($this->_typename);
217 if (empty($timmedtype)) {
218 throw new repository_exception('emptytype', 'repository');
221 //set sortorder as the last position in the list
222 if (!isset($this->_sortorder) || $this->_sortorder == 0 ) {
223 $sql = "SELECT MAX(sortorder) FROM {repository}";
224 $this->_sortorder = 1 + $DB->get_field_sql($sql);
227 //only create a new type if it doesn't already exist
228 $existingtype = $DB->get_record('repository', array('type'=>$this->_typename));
229 if (!$existingtype) {
230 //create the type
231 $newtype = new stdClass();
232 $newtype->type = $this->_typename;
233 $newtype->visible = $this->_visible;
234 $newtype->sortorder = $this->_sortorder;
235 $plugin_id = $DB->insert_record('repository', $newtype);
236 //save the options in DB
237 $this->update_options();
239 $instanceoptionnames = repository::static_function($this->_typename, 'get_instance_option_names');
241 //if the plugin type has no multiple instance (e.g. has no instance option name) so it wont
242 //be possible for the administrator to create a instance
243 //in this case we need to create an instance
244 if (empty($instanceoptionnames)) {
245 $instanceoptions = array();
246 if (empty($this->_options['pluginname'])) {
247 // when moodle trying to install some repo plugin automatically
248 // this option will be empty, get it from language string when display
249 $instanceoptions['name'] = '';
250 } else {
251 // when admin trying to add a plugin manually, he will type a name
252 // for it
253 $instanceoptions['name'] = $this->_options['pluginname'];
255 repository::static_function($this->_typename, 'create', $this->_typename, 0, get_system_context(), $instanceoptions);
257 //run plugin_init function
258 if (!repository::static_function($this->_typename, 'plugin_init')) {
259 if (!$silent) {
260 throw new repository_exception('cannotinitplugin', 'repository');
264 if(!empty($plugin_id)) {
265 // return plugin_id if create successfully
266 return $plugin_id;
267 } else {
268 return false;
271 } else {
272 if (!$silent) {
273 throw new repository_exception('existingrepository', 'repository');
275 // If plugin existed, return false, tell caller no new plugins were created.
276 return false;
282 * Update plugin options into the config_plugin table
284 * @param array $options
285 * @return bool
287 public function update_options($options = null) {
288 global $DB;
289 $classname = 'repository_' . $this->_typename;
290 $instanceoptions = repository::static_function($this->_typename, 'get_instance_option_names');
291 if (empty($instanceoptions)) {
292 // update repository instance name if this plugin type doesn't have muliti instances
293 $params = array();
294 $params['type'] = $this->_typename;
295 $instances = repository::get_instances($params);
296 $instance = array_pop($instances);
297 if ($instance) {
298 $DB->set_field('repository_instances', 'name', $options['pluginname'], array('id'=>$instance->id));
300 unset($options['pluginname']);
303 if (!empty($options)) {
304 $this->_options = $options;
307 foreach ($this->_options as $name => $value) {
308 set_config($name, $value, $this->_typename);
311 return true;
315 * Update visible database field with the value given as parameter
316 * or with the visible value of this object
317 * This function is private.
318 * For public access, have a look to switch_and_update_visibility()
320 * @param bool $visible
321 * @return bool
323 private function update_visible($visible = null) {
324 global $DB;
326 if (!empty($visible)) {
327 $this->_visible = $visible;
329 else if (!isset($this->_visible)) {
330 throw new repository_exception('updateemptyvisible', 'repository');
333 return $DB->set_field('repository', 'visible', $this->_visible, array('type'=>$this->_typename));
337 * Update database sortorder field with the value given as parameter
338 * or with the sortorder value of this object
339 * This function is private.
340 * For public access, have a look to move_order()
342 * @param int $sortorder
343 * @return bool
345 private function update_sortorder($sortorder = null) {
346 global $DB;
348 if (!empty($sortorder) && $sortorder!=0) {
349 $this->_sortorder = $sortorder;
351 //if sortorder is not set, we set it as the ;ast position in the list
352 else if (!isset($this->_sortorder) || $this->_sortorder == 0 ) {
353 $sql = "SELECT MAX(sortorder) FROM {repository}";
354 $this->_sortorder = 1 + $DB->get_field_sql($sql);
357 return $DB->set_field('repository', 'sortorder', $this->_sortorder, array('type'=>$this->_typename));
361 * Change order of the type with its adjacent upper or downer type
362 * (database fields are updated)
363 * Algorithm details:
364 * 1. retrieve all types in an array. This array is sorted by sortorder,
365 * and the array keys start from 0 to X (incremented by 1)
366 * 2. switch sortorder values of this type and its adjacent type
368 * @param string $move "up" or "down"
370 public function move_order($move) {
371 global $DB;
373 $types = repository::get_types(); // retrieve all types
375 // retrieve this type into the returned array
376 $i = 0;
377 while (!isset($indice) && $i<count($types)) {
378 if ($types[$i]->get_typename() == $this->_typename) {
379 $indice = $i;
381 $i++;
384 // retrieve adjacent indice
385 switch ($move) {
386 case "up":
387 $adjacentindice = $indice - 1;
388 break;
389 case "down":
390 $adjacentindice = $indice + 1;
391 break;
392 default:
393 throw new repository_exception('movenotdefined', 'repository');
396 //switch sortorder of this type and the adjacent type
397 //TODO: we could reset sortorder for all types. This is not as good in performance term, but
398 //that prevent from wrong behaviour on a screwed database. As performance are not important in this particular case
399 //it worth to change the algo.
400 if ($adjacentindice>=0 && !empty($types[$adjacentindice])) {
401 $DB->set_field('repository', 'sortorder', $this->_sortorder, array('type'=>$types[$adjacentindice]->get_typename()));
402 $this->update_sortorder($types[$adjacentindice]->get_sortorder());
407 * 1. Change visibility to the value chosen
408 * 2. Update the type
410 * @param bool $visible
411 * @return bool
413 public function update_visibility($visible = null) {
414 if (is_bool($visible)) {
415 $this->_visible = $visible;
416 } else {
417 $this->_visible = !$this->_visible;
419 return $this->update_visible();
424 * Delete a repository_type (general options are removed from config_plugin
425 * table, and all instances are deleted)
427 * @param bool $downloadcontents download external contents if exist
428 * @return bool
430 public function delete($downloadcontents = false) {
431 global $DB;
433 //delete all instances of this type
434 $params = array();
435 $params['context'] = array();
436 $params['onlyvisible'] = false;
437 $params['type'] = $this->_typename;
438 $instances = repository::get_instances($params);
439 foreach ($instances as $instance) {
440 $instance->delete($downloadcontents);
443 //delete all general options
444 foreach ($this->_options as $name => $value) {
445 set_config($name, null, $this->_typename);
448 try {
449 $DB->delete_records('repository', array('type' => $this->_typename));
450 } catch (dml_exception $ex) {
451 return false;
453 return true;
458 * This is the base class of the repository class.
460 * To create repository plugin, see: {@link http://docs.moodle.org/dev/Repository_plugins}
461 * See an example: {@link repository_boxnet}
463 * @package repository
464 * @category repository
465 * @copyright 2009 Dongsheng Cai {@link http://dongsheng.org}
466 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
468 abstract class repository {
469 // $disabled can be set to true to disable a plugin by force
470 // example: self::$disabled = true
471 /** @var bool force disable repository instance */
472 public $disabled = false;
473 /** @var int repository instance id */
474 public $id;
475 /** @var stdClass current context */
476 public $context;
477 /** @var array repository options */
478 public $options;
479 /** @var bool Whether or not the repository instance is editable */
480 public $readonly;
481 /** @var int return types */
482 public $returntypes;
483 /** @var stdClass repository instance database record */
484 public $instance;
486 * Constructor
488 * @param int $repositoryid repository instance id
489 * @param int|stdClass $context a context id or context object
490 * @param array $options repository options
491 * @param int $readonly indicate this repo is readonly or not
493 public function __construct($repositoryid, $context = SYSCONTEXTID, $options = array(), $readonly = 0) {
494 global $DB;
495 $this->id = $repositoryid;
496 if (is_object($context)) {
497 $this->context = $context;
498 } else {
499 $this->context = get_context_instance_by_id($context);
501 $this->instance = $DB->get_record('repository_instances', array('id'=>$this->id));
502 $this->readonly = $readonly;
503 $this->options = array();
505 if (is_array($options)) {
506 // The get_option() method will get stored options in database.
507 $options = array_merge($this->get_option(), $options);
508 } else {
509 $options = $this->get_option();
511 foreach ($options as $n => $v) {
512 $this->options[$n] = $v;
514 $this->name = $this->get_name();
515 $this->returntypes = $this->supported_returntypes();
516 $this->super_called = true;
520 * Get repository instance using repository id
522 * @param int $repositoryid repository ID
523 * @param stdClass|int $context context instance or context ID
524 * @return repository
526 public static function get_repository_by_id($repositoryid, $context) {
527 global $CFG, $DB;
529 $sql = 'SELECT i.name, i.typeid, r.type FROM {repository} r, {repository_instances} i WHERE i.id=? AND i.typeid=r.id';
531 if (!$record = $DB->get_record_sql($sql, array($repositoryid))) {
532 throw new repository_exception('invalidrepositoryid', 'repository');
533 } else {
534 $type = $record->type;
535 if (file_exists($CFG->dirroot . "/repository/$type/lib.php")) {
536 require_once($CFG->dirroot . "/repository/$type/lib.php");
537 $classname = 'repository_' . $type;
538 $contextid = $context;
539 if (is_object($context)) {
540 $contextid = $context->id;
542 $repository = new $classname($repositoryid, $contextid, array('type'=>$type));
543 return $repository;
544 } else {
545 throw new moodle_exception('error');
551 * Get a repository type object by a given type name.
553 * @static
554 * @param string $typename the repository type name
555 * @return repository_type|bool
557 public static function get_type_by_typename($typename) {
558 global $DB;
560 if (!$record = $DB->get_record('repository',array('type' => $typename))) {
561 return false;
564 return new repository_type($typename, (array)get_config($typename), $record->visible, $record->sortorder);
568 * Get the repository type by a given repository type id.
570 * @static
571 * @param int $id the type id
572 * @return object
574 public static function get_type_by_id($id) {
575 global $DB;
577 if (!$record = $DB->get_record('repository',array('id' => $id))) {
578 return false;
581 return new repository_type($record->type, (array)get_config($record->type), $record->visible, $record->sortorder);
585 * Return all repository types ordered by sortorder field
586 * first repository type in returnedarray[0], second repository type in returnedarray[1], ...
588 * @static
589 * @param bool $visible can return types by visiblity, return all types if null
590 * @return array Repository types
592 public static function get_types($visible=null) {
593 global $DB, $CFG;
595 $types = array();
596 $params = null;
597 if (!empty($visible)) {
598 $params = array('visible' => $visible);
600 if ($records = $DB->get_records('repository',$params,'sortorder')) {
601 foreach($records as $type) {
602 if (file_exists($CFG->dirroot . '/repository/'. $type->type .'/lib.php')) {
603 $types[] = new repository_type($type->type, (array)get_config($type->type), $type->visible, $type->sortorder);
608 return $types;
612 * To check if the context id is valid
614 * @static
615 * @param int $contextid
616 * @param stdClass $instance
617 * @return bool
619 public static function check_capability($contextid, $instance) {
620 $context = get_context_instance_by_id($contextid);
621 $capability = has_capability('repository/'.$instance->type.':view', $context);
622 if (!$capability) {
623 throw new repository_exception('nopermissiontoaccess', 'repository');
628 * Check if file already exists in draft area
630 * @static
631 * @param int $itemid
632 * @param string $filepath
633 * @param string $filename
634 * @return bool
636 public static function draftfile_exists($itemid, $filepath, $filename) {
637 global $USER;
638 $fs = get_file_storage();
639 $usercontext = get_context_instance(CONTEXT_USER, $USER->id);
640 if ($fs->get_file($usercontext->id, 'user', 'draft', $itemid, $filepath, $filename)) {
641 return true;
642 } else {
643 return false;
648 * This function is used to copy a moodle file to draft area
650 * @param string $encoded The metainfo of file, it is base64 encoded php serialized data
651 * @param int $draftitemid itemid
652 * @param string $new_filepath the new path in draft area
653 * @param string $new_filename The intended name of file
654 * @return array The information of file
656 public function copy_to_area($encoded, $draftitemid, $new_filepath, $new_filename) {
657 global $USER, $DB;
658 $fs = get_file_storage();
659 $browser = get_file_browser();
661 if ($this->has_moodle_files() == false) {
662 throw new coding_exception('Only repository used to browse moodle files can use repository::copy_to_area()');
666 $params = unserialize(base64_decode($encoded));
667 $user_context = get_context_instance(CONTEXT_USER, $USER->id);
669 $contextid = clean_param($params['contextid'], PARAM_INT);
670 $fileitemid = clean_param($params['itemid'], PARAM_INT);
671 $filename = clean_param($params['filename'], PARAM_FILE);
672 $filepath = clean_param($params['filepath'], PARAM_PATH);;
673 $filearea = clean_param($params['filearea'], PARAM_AREA);
674 $component = clean_param($params['component'], PARAM_COMPONENT);
676 $context = get_context_instance_by_id($contextid);
677 // the file needs to copied to draft area
678 $file_info = $browser->get_file_info($context, $component, $filearea, $fileitemid, $filepath, $filename);
680 if (repository::draftfile_exists($draftitemid, $new_filepath, $new_filename)) {
681 // create new file
682 $unused_filename = repository::get_unused_filename($draftitemid, $new_filepath, $new_filename);
683 $file_info->copy_to_storage($user_context->id, 'user', 'draft', $draftitemid, $new_filepath, $unused_filename);
684 $event = array();
685 $event['event'] = 'fileexists';
686 $event['newfile'] = new stdClass;
687 $event['newfile']->filepath = $new_filepath;
688 $event['newfile']->filename = $unused_filename;
689 $event['newfile']->url = moodle_url::make_draftfile_url($draftitemid, $new_filepath, $unused_filename)->out();
690 $event['existingfile'] = new stdClass;
691 $event['existingfile']->filepath = $new_filepath;
692 $event['existingfile']->filename = $new_filename;
693 $event['existingfile']->url = moodle_url::make_draftfile_url($draftitemid, $filepath, $filename)->out();;
694 return $event;
695 } else {
696 $file_info->copy_to_storage($user_context->id, 'user', 'draft', $draftitemid, $new_filepath, $new_filename);
697 $info = array();
698 $info['itemid'] = $draftitemid;
699 $info['title'] = $new_filename;
700 $info['contextid'] = $user_context->id;
701 $info['url'] = moodle_url::make_draftfile_url($draftitemid, $new_filepath, $new_filename)->out();;
702 $info['filesize'] = $file_info->get_filesize();
703 return $info;
708 * Get unused filename by appending suffix
710 * @static
711 * @param int $itemid
712 * @param string $filepath
713 * @param string $filename
714 * @return string
716 public static function get_unused_filename($itemid, $filepath, $filename) {
717 global $USER;
718 $fs = get_file_storage();
719 while (repository::draftfile_exists($itemid, $filepath, $filename)) {
720 $filename = repository::append_suffix($filename);
722 return $filename;
726 * Append a suffix to filename
728 * @static
729 * @param string $filename
730 * @return string
732 public static function append_suffix($filename) {
733 $pathinfo = pathinfo($filename);
734 if (empty($pathinfo['extension'])) {
735 return $filename . RENAME_SUFFIX;
736 } else {
737 return $pathinfo['filename'] . RENAME_SUFFIX . '.' . $pathinfo['extension'];
742 * Return all types that you a user can create/edit and which are also visible
743 * Note: Mostly used in order to know if at least one editable type can be set
745 * @static
746 * @param stdClass $context the context for which we want the editable types
747 * @return array types
749 public static function get_editable_types($context = null) {
751 if (empty($context)) {
752 $context = get_system_context();
755 $types= repository::get_types(true);
756 $editabletypes = array();
757 foreach ($types as $type) {
758 $instanceoptionnames = repository::static_function($type->get_typename(), 'get_instance_option_names');
759 if (!empty($instanceoptionnames)) {
760 if ($type->get_contextvisibility($context)) {
761 $editabletypes[]=$type;
765 return $editabletypes;
769 * Return repository instances
771 * @static
772 * @param array $args Array containing the following keys:
773 * currentcontext
774 * context
775 * onlyvisible
776 * type
777 * accepted_types
778 * return_types
779 * userid
781 * @return array repository instances
783 public static function get_instances($args = array()) {
784 global $DB, $CFG, $USER;
786 if (isset($args['currentcontext'])) {
787 $current_context = $args['currentcontext'];
788 } else {
789 $current_context = null;
792 if (!empty($args['context'])) {
793 $contexts = $args['context'];
794 } else {
795 $contexts = array();
798 $onlyvisible = isset($args['onlyvisible']) ? $args['onlyvisible'] : true;
799 $returntypes = isset($args['return_types']) ? $args['return_types'] : 3;
800 $type = isset($args['type']) ? $args['type'] : null;
802 $params = array();
803 $sql = "SELECT i.*, r.type AS repositorytype, r.sortorder, r.visible
804 FROM {repository} r, {repository_instances} i
805 WHERE i.typeid = r.id ";
807 if (!empty($args['disable_types']) && is_array($args['disable_types'])) {
808 list($types, $p) = $DB->get_in_or_equal($args['disable_types'], SQL_PARAMS_QM, 'param', false);
809 $sql .= " AND r.type $types";
810 $params = array_merge($params, $p);
813 if (!empty($args['userid']) && is_numeric($args['userid'])) {
814 $sql .= " AND (i.userid = 0 or i.userid = ?)";
815 $params[] = $args['userid'];
818 foreach ($contexts as $context) {
819 if (empty($firstcontext)) {
820 $firstcontext = true;
821 $sql .= " AND ((i.contextid = ?)";
822 } else {
823 $sql .= " OR (i.contextid = ?)";
825 $params[] = $context->id;
828 if (!empty($firstcontext)) {
829 $sql .=')';
832 if ($onlyvisible == true) {
833 $sql .= " AND (r.visible = 1)";
836 if (isset($type)) {
837 $sql .= " AND (r.type = ?)";
838 $params[] = $type;
840 $sql .= " ORDER BY r.sortorder, i.name";
842 if (!$records = $DB->get_records_sql($sql, $params)) {
843 $records = array();
846 $repositories = array();
847 if (isset($args['accepted_types'])) {
848 $accepted_types = $args['accepted_types'];
849 } else {
850 $accepted_types = '*';
852 // Sortorder should be unique, which is not true if we use $record->sortorder
853 // and there are multiple instances of any repository type
854 $sortorder = 1;
855 foreach ($records as $record) {
856 if (!file_exists($CFG->dirroot . '/repository/'. $record->repositorytype.'/lib.php')) {
857 continue;
859 require_once($CFG->dirroot . '/repository/'. $record->repositorytype.'/lib.php');
860 $options['visible'] = $record->visible;
861 $options['type'] = $record->repositorytype;
862 $options['typeid'] = $record->typeid;
863 $options['sortorder'] = $sortorder++;
864 // tell instance what file types will be accepted by file picker
865 $classname = 'repository_' . $record->repositorytype;
867 $repository = new $classname($record->id, $record->contextid, $options, $record->readonly);
869 $is_supported = true;
871 if (empty($repository->super_called)) {
872 // to make sure the super construct is called
873 debugging('parent::__construct must be called by '.$record->repositorytype.' plugin.');
874 } else {
875 // check mimetypes
876 if ($accepted_types !== '*' and $repository->supported_filetypes() !== '*') {
877 $accepted_ext = file_get_typegroup('extension', $accepted_types);
878 $supported_ext = file_get_typegroup('extension', $repository->supported_filetypes());
879 $valid_ext = array_intersect($accepted_ext, $supported_ext);
880 $is_supported = !empty($valid_ext);
882 // check return values
883 if ($returntypes !== 3 and $repository->supported_returntypes() !== 3) {
884 $type = $repository->supported_returntypes();
885 if ($type & $returntypes) {
887 } else {
888 $is_supported = false;
892 if (!$onlyvisible || ($repository->is_visible() && !$repository->disabled)) {
893 // check capability in current context
894 if (!empty($current_context)) {
895 $capability = has_capability('repository/'.$record->repositorytype.':view', $current_context);
896 } else {
897 $capability = has_capability('repository/'.$record->repositorytype.':view', get_system_context());
899 if ($record->repositorytype == 'coursefiles') {
900 // coursefiles plugin needs managefiles permission
901 if (!empty($current_context)) {
902 $capability = $capability && has_capability('moodle/course:managefiles', $current_context);
903 } else {
904 $capability = $capability && has_capability('moodle/course:managefiles', get_system_context());
907 if ($is_supported && $capability) {
908 $repositories[$repository->id] = $repository;
913 return $repositories;
917 * Get single repository instance
919 * @static
920 * @param integer $id repository id
921 * @return object repository instance
923 public static function get_instance($id) {
924 global $DB, $CFG;
925 $sql = "SELECT i.*, r.type AS repositorytype, r.visible
926 FROM {repository} r
927 JOIN {repository_instances} i ON i.typeid = r.id
928 WHERE i.id = ?";
930 if (!$instance = $DB->get_record_sql($sql, array($id))) {
931 return false;
933 require_once($CFG->dirroot . '/repository/'. $instance->repositorytype.'/lib.php');
934 $classname = 'repository_' . $instance->repositorytype;
935 $options['typeid'] = $instance->typeid;
936 $options['type'] = $instance->repositorytype;
937 $options['name'] = $instance->name;
938 $obj = new $classname($instance->id, $instance->contextid, $options, $instance->readonly);
939 if (empty($obj->super_called)) {
940 debugging('parent::__construct must be called by '.$classname.' plugin.');
942 return $obj;
946 * Call a static function. Any additional arguments than plugin and function will be passed through.
948 * @static
949 * @param string $plugin repository plugin name
950 * @param string $function funciton name
951 * @return mixed
953 public static function static_function($plugin, $function) {
954 global $CFG;
956 //check that the plugin exists
957 $typedirectory = $CFG->dirroot . '/repository/'. $plugin . '/lib.php';
958 if (!file_exists($typedirectory)) {
959 //throw new repository_exception('invalidplugin', 'repository');
960 return false;
963 $pname = null;
964 if (is_object($plugin) || is_array($plugin)) {
965 $plugin = (object)$plugin;
966 $pname = $plugin->name;
967 } else {
968 $pname = $plugin;
971 $args = func_get_args();
972 if (count($args) <= 2) {
973 $args = array();
974 } else {
975 array_shift($args);
976 array_shift($args);
979 require_once($typedirectory);
980 return call_user_func_array(array('repository_' . $plugin, $function), $args);
984 * Scan file, throws exception in case of infected file.
986 * Please note that the scanning engine must be able to access the file,
987 * permissions of the file are not modified here!
989 * @static
990 * @param string $thefile
991 * @param string $filename name of the file
992 * @param bool $deleteinfected
994 public static function antivir_scan_file($thefile, $filename, $deleteinfected) {
995 global $CFG;
997 if (!is_readable($thefile)) {
998 // this should not happen
999 return;
1002 if (empty($CFG->runclamonupload) or empty($CFG->pathtoclam)) {
1003 // clam not enabled
1004 return;
1007 $CFG->pathtoclam = trim($CFG->pathtoclam);
1009 if (!file_exists($CFG->pathtoclam) or !is_executable($CFG->pathtoclam)) {
1010 // misconfigured clam - use the old notification for now
1011 require("$CFG->libdir/uploadlib.php");
1012 $notice = get_string('clamlost', 'moodle', $CFG->pathtoclam);
1013 clam_message_admins($notice);
1014 return;
1017 // do NOT mess with permissions here, the calling party is responsible for making
1018 // sure the scanner engine can access the files!
1020 // execute test
1021 $cmd = escapeshellcmd($CFG->pathtoclam).' --stdout '.escapeshellarg($thefile);
1022 exec($cmd, $output, $return);
1024 if ($return == 0) {
1025 // perfect, no problem found
1026 return;
1028 } else if ($return == 1) {
1029 // infection found
1030 if ($deleteinfected) {
1031 unlink($thefile);
1033 throw new moodle_exception('virusfounduser', 'moodle', '', array('filename'=>$filename));
1035 } else {
1036 //unknown problem
1037 require("$CFG->libdir/uploadlib.php");
1038 $notice = get_string('clamfailed', 'moodle', get_clam_error_code($return));
1039 $notice .= "\n\n". implode("\n", $output);
1040 clam_message_admins($notice);
1041 if ($CFG->clamfailureonupload === 'actlikevirus') {
1042 if ($deleteinfected) {
1043 unlink($thefile);
1045 throw new moodle_exception('virusfounduser', 'moodle', '', array('filename'=>$filename));
1046 } else {
1047 return;
1053 * Repository method to serve file
1055 * @param stored_file $storedfile
1056 * @param int $lifetime Number of seconds before the file should expire from caches (default 24 hours)
1057 * @param int $filter 0 (default)=no filtering, 1=all files, 2=html files only
1058 * @param bool $forcedownload If true (default false), forces download of file rather than view in browser/plugin
1059 * @param array $options additional options affecting the file serving
1061 public function send_file($storedfile, $lifetime=86400 , $filter=0, $forcedownload=false, array $options = null) {
1062 throw new coding_exception("Repository plugin must implement send_file() method.");
1066 * Return reference file life time
1068 * @param string $ref
1069 * @return int
1071 public function get_reference_file_lifetime($ref) {
1072 // One day
1073 return 60 * 60 * 24;
1077 * Decide whether or not the file should be synced
1079 * @param stored_file $storedfile
1080 * @return bool
1082 public function sync_individual_file(stored_file $storedfile) {
1083 return true;
1087 * Return human readable reference information
1088 * {@link stored_file::get_reference()}
1090 * @param string $reference
1091 * @return string|null
1093 public function get_reference_details($reference) {
1094 return null;
1098 * Cache file from external repository by reference
1099 * {@link repository::get_file_reference()}
1100 * {@link repository::get_file()}
1101 * Invoked at MOODLE/repository/repository_ajax.php
1103 * @param string $reference this reference is generated by
1104 * repository::get_file_reference()
1105 * @param stored_file $storedfile created file reference
1107 public function cache_file_by_reference($reference, $storedfile) {
1111 * Get file from external repository by reference
1112 * {@link repository::get_file_reference()}
1113 * {@link repository::get_file()}
1115 * @param stdClass $reference file reference db record
1116 * @return stdClass|null|false
1118 public function get_file_by_reference($reference) {
1119 return null;
1123 * Move file from download folder to file pool using FILE API
1125 * @todo MDL-28637
1126 * @static
1127 * @param string $thefile file path in download folder
1128 * @param stdClass $record
1129 * @return array containing the following keys:
1130 * icon
1131 * file
1132 * id
1133 * url
1135 public static function move_to_filepool($thefile, $record) {
1136 global $DB, $CFG, $USER, $OUTPUT;
1138 // scan for viruses if possible, throws exception if problem found
1139 self::antivir_scan_file($thefile, $record->filename, empty($CFG->repository_no_delete)); //TODO: MDL-28637 this repository_no_delete is a bloody hack!
1141 $fs = get_file_storage();
1142 // If file name being used.
1143 if (repository::draftfile_exists($record->itemid, $record->filepath, $record->filename)) {
1144 $draftitemid = $record->itemid;
1145 $new_filename = repository::get_unused_filename($draftitemid, $record->filepath, $record->filename);
1146 $old_filename = $record->filename;
1147 // Create a tmp file.
1148 $record->filename = $new_filename;
1149 $newfile = $fs->create_file_from_pathname($record, $thefile);
1150 $event = array();
1151 $event['event'] = 'fileexists';
1152 $event['newfile'] = new stdClass;
1153 $event['newfile']->filepath = $record->filepath;
1154 $event['newfile']->filename = $new_filename;
1155 $event['newfile']->url = moodle_url::make_draftfile_url($draftitemid, $record->filepath, $new_filename)->out();
1157 $event['existingfile'] = new stdClass;
1158 $event['existingfile']->filepath = $record->filepath;
1159 $event['existingfile']->filename = $old_filename;
1160 $event['existingfile']->url = moodle_url::make_draftfile_url($draftitemid, $record->filepath, $old_filename)->out();;
1161 return $event;
1163 if ($file = $fs->create_file_from_pathname($record, $thefile)) {
1164 if (empty($CFG->repository_no_delete)) {
1165 $delete = unlink($thefile);
1166 unset($CFG->repository_no_delete);
1168 return array(
1169 'url'=>moodle_url::make_draftfile_url($file->get_itemid(), $file->get_filepath(), $file->get_filename())->out(),
1170 'id'=>$file->get_itemid(),
1171 'file'=>$file->get_filename(),
1172 'icon' => $OUTPUT->pix_url(file_extension_icon($thefile, 32))->out(),
1174 } else {
1175 return null;
1180 * Builds a tree of files This function is then called recursively.
1182 * @static
1183 * @todo take $search into account, and respect a threshold for dynamic loading
1184 * @param file_info $fileinfo an object returned by file_browser::get_file_info()
1185 * @param string $search searched string
1186 * @param bool $dynamicmode no recursive call is done when in dynamic mode
1187 * @param array $list the array containing the files under the passed $fileinfo
1188 * @returns int the number of files found
1191 public static function build_tree($fileinfo, $search, $dynamicmode, &$list) {
1192 global $CFG, $OUTPUT;
1194 $filecount = 0;
1195 $children = $fileinfo->get_children();
1197 foreach ($children as $child) {
1198 $filename = $child->get_visible_name();
1199 $filesize = $child->get_filesize();
1200 $filesize = $filesize ? display_size($filesize) : '';
1201 $filedate = $child->get_timemodified();
1202 $filedate = $filedate ? userdate($filedate) : '';
1203 $filetype = $child->get_mimetype();
1205 if ($child->is_directory()) {
1206 $path = array();
1207 $level = $child->get_parent();
1208 while ($level) {
1209 $params = $level->get_params();
1210 $path[] = array($params['filepath'], $level->get_visible_name());
1211 $level = $level->get_parent();
1214 $tmp = array(
1215 'title' => $child->get_visible_name(),
1216 'size' => 0,
1217 'date' => $filedate,
1218 'path' => array_reverse($path),
1219 'thumbnail' => $OUTPUT->pix_url(file_folder_icon(90))->out(false)
1222 //if ($dynamicmode && $child->is_writable()) {
1223 // $tmp['children'] = array();
1224 //} else {
1225 // if folder name matches search, we send back all files contained.
1226 $_search = $search;
1227 if ($search && stristr($tmp['title'], $search) !== false) {
1228 $_search = false;
1230 $tmp['children'] = array();
1231 $_filecount = repository::build_tree($child, $_search, $dynamicmode, $tmp['children']);
1232 if ($search && $_filecount) {
1233 $tmp['expanded'] = 1;
1238 if (!$search || $_filecount || (stristr($tmp['title'], $search) !== false)) {
1239 $filecount += $_filecount;
1240 $list[] = $tmp;
1243 } else { // not a directory
1244 // skip the file, if we're in search mode and it's not a match
1245 if ($search && (stristr($filename, $search) === false)) {
1246 continue;
1248 $params = $child->get_params();
1249 $source = serialize(array($params['contextid'], $params['component'], $params['filearea'], $params['itemid'], $params['filepath'], $params['filename']));
1250 $list[] = array(
1251 'title' => $filename,
1252 'size' => $filesize,
1253 'date' => $filedate,
1254 //'source' => $child->get_url(),
1255 'source' => base64_encode($source),
1256 'icon'=>$OUTPUT->pix_url(file_file_icon($child, 24))->out(false),
1257 'thumbnail'=>$OUTPUT->pix_url(file_file_icon($child, 90))->out(false),
1259 $filecount++;
1263 return $filecount;
1267 * Display a repository instance list (with edit/delete/create links)
1269 * @static
1270 * @param stdClass $context the context for which we display the instance
1271 * @param string $typename if set, we display only one type of instance
1273 public static function display_instances_list($context, $typename = null) {
1274 global $CFG, $USER, $OUTPUT;
1276 $output = $OUTPUT->box_start('generalbox');
1277 //if the context is SYSTEM, so we call it from administration page
1278 $admin = ($context->id == SYSCONTEXTID) ? true : false;
1279 if ($admin) {
1280 $baseurl = new moodle_url('/'.$CFG->admin.'/repositoryinstance.php', array('sesskey'=>sesskey()));
1281 $output .= $OUTPUT->heading(get_string('siteinstances', 'repository'));
1282 } else {
1283 $baseurl = new moodle_url('/repository/manage_instances.php', array('contextid'=>$context->id, 'sesskey'=>sesskey()));
1286 $namestr = get_string('name');
1287 $pluginstr = get_string('plugin', 'repository');
1288 $settingsstr = get_string('settings');
1289 $deletestr = get_string('delete');
1290 //retrieve list of instances. In administration context we want to display all
1291 //instances of a type, even if this type is not visible. In course/user context we
1292 //want to display only visible instances, but for every type types. The repository::get_instances()
1293 //third parameter displays only visible type.
1294 $params = array();
1295 $params['context'] = array($context, get_system_context());
1296 $params['currentcontext'] = $context;
1297 $params['onlyvisible'] = !$admin;
1298 $params['type'] = $typename;
1299 $instances = repository::get_instances($params);
1300 $instancesnumber = count($instances);
1301 $alreadyplugins = array();
1303 $table = new html_table();
1304 $table->head = array($namestr, $pluginstr, $settingsstr, $deletestr);
1305 $table->align = array('left', 'left', 'center','center');
1306 $table->data = array();
1308 $updowncount = 1;
1310 foreach ($instances as $i) {
1311 $settings = '';
1312 $delete = '';
1314 $type = repository::get_type_by_id($i->options['typeid']);
1316 if ($type->get_contextvisibility($context)) {
1317 if (!$i->readonly) {
1319 $settingurl = new moodle_url($baseurl);
1320 $settingurl->param('type', $i->options['type']);
1321 $settingurl->param('edit', $i->id);
1322 $settings .= html_writer::link($settingurl, $settingsstr);
1324 $deleteurl = new moodle_url($baseurl);
1325 $deleteurl->param('delete', $i->id);
1326 $deleteurl->param('type', $i->options['type']);
1327 $delete .= html_writer::link($deleteurl, $deletestr);
1331 $type = repository::get_type_by_id($i->options['typeid']);
1332 $table->data[] = array($i->name, $type->get_readablename(), $settings, $delete);
1334 //display a grey row if the type is defined as not visible
1335 if (isset($type) && !$type->get_visible()) {
1336 $table->rowclasses[] = 'dimmed_text';
1337 } else {
1338 $table->rowclasses[] = '';
1341 if (!in_array($i->name, $alreadyplugins)) {
1342 $alreadyplugins[] = $i->name;
1345 $output .= html_writer::table($table);
1346 $instancehtml = '<div>';
1347 $addable = 0;
1349 //if no type is set, we can create all type of instance
1350 if (!$typename) {
1351 $instancehtml .= '<h3>';
1352 $instancehtml .= get_string('createrepository', 'repository');
1353 $instancehtml .= '</h3><ul>';
1354 $types = repository::get_editable_types($context);
1355 foreach ($types as $type) {
1356 if (!empty($type) && $type->get_visible()) {
1357 $instanceoptionnames = repository::static_function($type->get_typename(), 'get_instance_option_names');
1358 if (!empty($instanceoptionnames)) {
1359 $baseurl->param('new', $type->get_typename());
1360 $instancehtml .= '<li><a href="'.$baseurl->out().'">'.get_string('createxxinstance', 'repository', get_string('pluginname', 'repository_'.$type->get_typename())). '</a></li>';
1361 $baseurl->remove_params('new');
1362 $addable++;
1366 $instancehtml .= '</ul>';
1368 } else {
1369 $instanceoptionnames = repository::static_function($typename, 'get_instance_option_names');
1370 if (!empty($instanceoptionnames)) { //create a unique type of instance
1371 $addable = 1;
1372 $baseurl->param('new', $typename);
1373 $output .= $OUTPUT->single_button($baseurl, get_string('createinstance', 'repository'), 'get');
1374 $baseurl->remove_params('new');
1378 if ($addable) {
1379 $instancehtml .= '</div>';
1380 $output .= $instancehtml;
1383 $output .= $OUTPUT->box_end();
1385 //print the list + creation links
1386 print($output);
1390 * Prepare file reference information
1392 * @param string $source
1393 * @return string file referece
1395 public function get_file_reference($source) {
1396 return $source;
1399 * Decide where to save the file, can be overwriten by subclass
1401 * @param string $filename file name
1402 * @return file path
1404 public function prepare_file($filename) {
1405 global $CFG;
1406 if (!file_exists($CFG->tempdir.'/download')) {
1407 mkdir($CFG->tempdir.'/download/', $CFG->directorypermissions, true);
1409 if (is_dir($CFG->tempdir.'/download')) {
1410 $dir = $CFG->tempdir.'/download/';
1412 if (empty($filename)) {
1413 $filename = uniqid('repo', true).'_'.time().'.tmp';
1415 if (file_exists($dir.$filename)) {
1416 $filename = uniqid('m').$filename;
1418 return $dir.$filename;
1422 * Does this repository used to browse moodle files?
1424 * @return bool
1426 public function has_moodle_files() {
1427 return false;
1431 * Return file URL, for most plugins, the parameter is the original
1432 * url, but some plugins use a file id, so we need this function to
1433 * convert file id to original url.
1435 * @param string $url the url of file
1436 * @return string
1438 public function get_link($url) {
1439 return $url;
1443 * Download a file, this function can be overridden by subclass. {@link curl}
1445 * @param string $url the url of file
1446 * @param string $filename save location
1447 * @return string the location of the file
1449 public function get_file($url, $filename = '') {
1450 global $CFG;
1451 $path = $this->prepare_file($filename);
1452 $fp = fopen($path, 'w');
1453 $c = new curl;
1454 $c->download(array(array('url'=>$url, 'file'=>$fp)));
1455 // Close file handler.
1456 fclose($fp);
1457 return array('path'=>$path, 'url'=>$url);
1461 * Return size of a file in bytes.
1463 * @param string $source encoded and serialized data of file
1464 * @return int file size in bytes
1466 public function get_file_size($source) {
1467 $browser = get_file_browser();
1468 $params = unserialize(base64_decode($source));
1469 $contextid = clean_param($params['contextid'], PARAM_INT);
1470 $fileitemid = clean_param($params['itemid'], PARAM_INT);
1471 $filename = clean_param($params['filename'], PARAM_FILE);
1472 $filepath = clean_param($params['filepath'], PARAM_PATH);
1473 $filearea = clean_param($params['filearea'], PARAM_AREA);
1474 $component = clean_param($params['component'], PARAM_COMPONENT);
1475 $context = get_context_instance_by_id($contextid);
1476 $file_info = $browser->get_file_info($context, $component, $filearea, $fileitemid, $filepath, $filename);
1477 if (!empty($file_info)) {
1478 $filesize = $file_info->get_filesize();
1479 } else {
1480 $filesize = null;
1482 return $filesize;
1486 * Return is the instance is visible
1487 * (is the type visible ? is the context enable ?)
1489 * @return bool
1491 public function is_visible() {
1492 $type = repository::get_type_by_id($this->options['typeid']);
1493 $instanceoptions = repository::static_function($type->get_typename(), 'get_instance_option_names');
1495 if ($type->get_visible()) {
1496 //if the instance is unique so it's visible, otherwise check if the instance has a enabled context
1497 if (empty($instanceoptions) || $type->get_contextvisibility($this->context)) {
1498 return true;
1502 return false;
1506 * Return the name of this instance, can be overridden.
1508 * @return string
1510 public function get_name() {
1511 global $DB;
1512 if ( $name = $this->instance->name ) {
1513 return $name;
1514 } else {
1515 return get_string('pluginname', 'repository_' . $this->options['type']);
1520 * What kind of files will be in this repository?
1522 * @return array return '*' means this repository support any files, otherwise
1523 * return mimetypes of files, it can be an array
1525 public function supported_filetypes() {
1526 // return array('text/plain', 'image/gif');
1527 return '*';
1531 * Does it return a file url or a item_id
1533 * @return string
1535 public function supported_returntypes() {
1536 return (FILE_INTERNAL | FILE_EXTERNAL | FILE_REFERENCE);
1540 * Provide repository instance information for Ajax
1542 * @return stdClass
1544 final public function get_meta() {
1545 global $CFG, $OUTPUT;
1546 $meta = new stdClass();
1547 $meta->id = $this->id;
1548 $meta->name = $this->get_name();
1549 $meta->type = $this->options['type'];
1550 $meta->icon = $OUTPUT->pix_url('icon', 'repository_'.$meta->type)->out(false);
1551 $meta->supported_types = file_get_typegroup('extension', $this->supported_filetypes());
1552 $meta->return_types = $this->supported_returntypes();
1553 $meta->sortorder = $this->options['sortorder'];
1554 return $meta;
1558 * Create an instance for this plug-in
1560 * @static
1561 * @param string $type the type of the repository
1562 * @param int $userid the user id
1563 * @param stdClass $context the context
1564 * @param array $params the options for this instance
1565 * @param int $readonly whether to create it readonly or not (defaults to not)
1566 * @return mixed
1568 public static function create($type, $userid, $context, $params, $readonly=0) {
1569 global $CFG, $DB;
1570 $params = (array)$params;
1571 require_once($CFG->dirroot . '/repository/'. $type . '/lib.php');
1572 $classname = 'repository_' . $type;
1573 if ($repo = $DB->get_record('repository', array('type'=>$type))) {
1574 $record = new stdClass();
1575 $record->name = $params['name'];
1576 $record->typeid = $repo->id;
1577 $record->timecreated = time();
1578 $record->timemodified = time();
1579 $record->contextid = $context->id;
1580 $record->readonly = $readonly;
1581 $record->userid = $userid;
1582 $id = $DB->insert_record('repository_instances', $record);
1583 $options = array();
1584 $configs = call_user_func($classname . '::get_instance_option_names');
1585 if (!empty($configs)) {
1586 foreach ($configs as $config) {
1587 if (isset($params[$config])) {
1588 $options[$config] = $params[$config];
1589 } else {
1590 $options[$config] = null;
1595 if (!empty($id)) {
1596 unset($options['name']);
1597 $instance = repository::get_instance($id);
1598 $instance->set_option($options);
1599 return $id;
1600 } else {
1601 return null;
1603 } else {
1604 return null;
1609 * delete a repository instance
1611 * @param bool $downloadcontents
1612 * @return bool
1614 final public function delete($downloadcontents = false) {
1615 global $DB;
1616 if ($downloadcontents) {
1617 $this->convert_references_to_local();
1619 try {
1620 $DB->delete_records('repository_instances', array('id'=>$this->id));
1621 $DB->delete_records('repository_instance_config', array('instanceid'=>$this->id));
1622 } catch (dml_exception $ex) {
1623 return false;
1625 return true;
1629 * Hide/Show a repository
1631 * @param string $hide
1632 * @return bool
1634 final public function hide($hide = 'toggle') {
1635 global $DB;
1636 if ($entry = $DB->get_record('repository', array('id'=>$this->id))) {
1637 if ($hide === 'toggle' ) {
1638 if (!empty($entry->visible)) {
1639 $entry->visible = 0;
1640 } else {
1641 $entry->visible = 1;
1643 } else {
1644 if (!empty($hide)) {
1645 $entry->visible = 0;
1646 } else {
1647 $entry->visible = 1;
1650 return $DB->update_record('repository', $entry);
1652 return false;
1656 * Save settings for repository instance
1657 * $repo->set_option(array('api_key'=>'f2188bde132', 'name'=>'dongsheng'));
1659 * @param array $options settings
1660 * @return bool
1662 public function set_option($options = array()) {
1663 global $DB;
1665 if (!empty($options['name'])) {
1666 $r = new stdClass();
1667 $r->id = $this->id;
1668 $r->name = $options['name'];
1669 $DB->update_record('repository_instances', $r);
1670 unset($options['name']);
1672 foreach ($options as $name=>$value) {
1673 if ($id = $DB->get_field('repository_instance_config', 'id', array('name'=>$name, 'instanceid'=>$this->id))) {
1674 $DB->set_field('repository_instance_config', 'value', $value, array('id'=>$id));
1675 } else {
1676 $config = new stdClass();
1677 $config->instanceid = $this->id;
1678 $config->name = $name;
1679 $config->value = $value;
1680 $DB->insert_record('repository_instance_config', $config);
1683 return true;
1687 * Get settings for repository instance
1689 * @param string $config
1690 * @return array Settings
1692 public function get_option($config = '') {
1693 global $DB;
1694 $entries = $DB->get_records('repository_instance_config', array('instanceid'=>$this->id));
1695 $ret = array();
1696 if (empty($entries)) {
1697 return $ret;
1699 foreach($entries as $entry) {
1700 $ret[$entry->name] = $entry->value;
1702 if (!empty($config)) {
1703 if (isset($ret[$config])) {
1704 return $ret[$config];
1705 } else {
1706 return null;
1708 } else {
1709 return $ret;
1714 * Filter file listing to display specific types
1716 * @param array $value
1717 * @return bool
1719 public function filter(&$value) {
1720 $accepted_types = optional_param_array('accepted_types', '', PARAM_RAW);
1721 if (isset($value['children'])) {
1722 if (!empty($value['children'])) {
1723 $value['children'] = array_filter($value['children'], array($this, 'filter'));
1725 return true; // always return directories
1726 } else {
1727 if ($accepted_types == '*' or empty($accepted_types)
1728 or (is_array($accepted_types) and in_array('*', $accepted_types))) {
1729 return true;
1730 } else {
1731 $extensions = file_get_typegroup('extension', $accepted_types);
1732 foreach ($extensions as $ext) {
1733 if (preg_match('#\.'.$ext.'$#i', $value['title'])) {
1734 return true;
1739 return false;
1743 * Given a path, and perhaps a search, get a list of files.
1745 * See details on {@link http://docs.moodle.org/dev/Repository_plugins}
1747 * @param string $path this parameter can a folder name, or a identification of folder
1748 * @param string $page the page number of file list
1749 * @return array the list of files, including meta infomation, containing the following keys
1750 * manage, url to manage url
1751 * client_id
1752 * login, login form
1753 * repo_id, active repository id
1754 * login_btn_action, the login button action
1755 * login_btn_label, the login button label
1756 * total, number of results
1757 * perpage, items per page
1758 * page
1759 * pages, total pages
1760 * issearchresult, is it a search result?
1761 * list, file list
1762 * path, current path and parent path
1764 public function get_listing($path = '', $page = '') {
1768 * Prepares list of files before passing it to AJAX, makes sure data is in the correct
1769 * format and stores formatted values.
1771 * @param array|stdClass $listing result of get_listing() or search() or file_get_drafarea_files()
1772 * @return array
1774 public static function prepare_listing($listing) {
1775 global $OUTPUT;
1776 if (is_array($listing) && isset($listing['list']) && is_array(($listing['list']))) {
1777 $listing['list'] = array_values($listing['list']); // convert to array
1778 $files = &$listing['list'];
1779 } else if (is_object($listing) && isset($listing->list) && is_array(($listing->list))) {
1780 $listing->list = array_values($listing->list); // convert to array
1781 $files = &$listing->list;
1782 } else {
1783 return $listing;
1785 $len = count($files);
1786 for ($i=0; $i<$len; $i++) {
1787 if (is_object($files[$i])) {
1788 $file = (array)$files[$i];
1789 $converttoobject = true;
1790 } else {
1791 $file = & $files[$i];
1792 $converttoobject = false;
1794 if (isset($file['size'])) {
1795 $file['size'] = (int)$file['size'];
1796 $file['size_f'] = display_size($file['size']);
1798 if (isset($file['license']) &&
1799 get_string_manager()->string_exists($file['license'], 'license')) {
1800 $file['license_f'] = get_string($file['license'], 'license');
1802 if (isset($file['image_width']) && isset($file['image_height'])) {
1803 $a = array('width' => $file['image_width'], 'height' => $file['image_height']);
1804 $file['dimensions'] = get_string('imagesize', 'repository', (object)$a);
1806 foreach (array('date', 'datemodified', 'datecreated') as $key) {
1807 if (!isset($file[$key]) && isset($file['date'])) {
1808 $file[$key] = $file['date'];
1810 if (isset($file[$key])) {
1811 // must be UNIX timestamp
1812 $file[$key] = (int)$file[$key];
1813 if (!$file[$key]) {
1814 unset($file[$key]);
1815 } else {
1816 $file[$key.'_f'] = userdate($file[$key], get_string('strftimedatetime', 'langconfig'));
1817 $file[$key.'_f_s'] = userdate($file[$key], get_string('strftimedatetimeshort', 'langconfig'));
1821 $isfolder = (array_key_exists('children', $file) || (isset($file['type']) && $file['type'] == 'folder'));
1822 $filename = null;
1823 if (isset($file['title'])) {
1824 $filename = $file['title'];
1826 else if (isset($file['fullname'])) {
1827 $filename = $file['fullname'];
1829 if (!isset($file['mimetype']) && !$isfolder && $filename) {
1830 $file['mimetype'] = get_mimetype_description(array('filename' => $filename));
1832 if (!isset($file['icon'])) {
1833 if ($isfolder) {
1834 $file['icon'] = $OUTPUT->pix_url(file_folder_icon(24))->out(false);
1835 } else if ($filename) {
1836 $file['icon'] = $OUTPUT->pix_url(file_extension_icon($filename, 24))->out(false);
1839 if ($converttoobject) {
1840 $files[$i] = (object)$file;
1843 return $listing;
1847 * Search files in repository
1848 * When doing global search, $search_text will be used as
1849 * keyword.
1851 * @param string $search_text search key word
1852 * @param int $page page
1853 * @return mixed {@see repository::get_listing}
1855 public function search($search_text, $page = 0) {
1856 $list = array();
1857 $list['list'] = array();
1858 return false;
1862 * Logout from repository instance
1863 * By default, this function will return a login form
1865 * @return string
1867 public function logout(){
1868 return $this->print_login();
1872 * To check whether the user is logged in.
1874 * @return bool
1876 public function check_login(){
1877 return true;
1882 * Show the login screen, if required
1884 * @return string
1886 public function print_login(){
1887 return $this->get_listing();
1891 * Show the search screen, if required
1893 * @return string
1895 public function print_search() {
1896 global $PAGE;
1897 $renderer = $PAGE->get_renderer('core', 'files');
1898 return $renderer->repository_default_searchform();
1902 * For oauth like external authentication, when external repository direct user back to moodle,
1903 * this funciton will be called to set up token and token_secret
1905 public function callback() {
1909 * is it possible to do glboal search?
1911 * @return bool
1913 public function global_search() {
1914 return false;
1918 * Defines operations that happen occasionally on cron
1920 * @return bool
1922 public function cron() {
1923 return true;
1927 * function which is run when the type is created (moodle administrator add the plugin)
1929 * @return bool success or fail?
1931 public static function plugin_init() {
1932 return true;
1936 * Edit/Create Admin Settings Moodle form
1938 * @param moodleform $mform Moodle form (passed by reference)
1939 * @param string $classname repository class name
1941 public static function type_config_form($mform, $classname = 'repository') {
1942 $instnaceoptions = call_user_func(array($classname, 'get_instance_option_names'), $mform, $classname);
1943 if (empty($instnaceoptions)) {
1944 // this plugin has only one instance
1945 // so we need to give it a name
1946 // it can be empty, then moodle will look for instance name from language string
1947 $mform->addElement('text', 'pluginname', get_string('pluginname', 'repository'), array('size' => '40'));
1948 $mform->addElement('static', 'pluginnamehelp', '', get_string('pluginnamehelp', 'repository'));
1953 * Validate Admin Settings Moodle form
1955 * @static
1956 * @param moodleform $mform Moodle form (passed by reference)
1957 * @param array $data array of ("fieldname"=>value) of submitted data
1958 * @param array $errors array of ("fieldname"=>errormessage) of errors
1959 * @return array array of errors
1961 public static function type_form_validation($mform, $data, $errors) {
1962 return $errors;
1967 * Edit/Create Instance Settings Moodle form
1969 * @param moodleform $mform Moodle form (passed by reference)
1971 public function instance_config_form($mform) {
1975 * Return names of the general options.
1976 * By default: no general option name
1978 * @return array
1980 public static function get_type_option_names() {
1981 return array('pluginname');
1985 * Return names of the instance options.
1986 * By default: no instance option name
1988 * @return array
1990 public static function get_instance_option_names() {
1991 return array();
1995 * Validate repository plugin instance form
1997 * @param moodleform $mform moodle form
1998 * @param array $data form data
1999 * @param array $errors errors
2000 * @return array errors
2002 public static function instance_form_validation($mform, $data, $errors) {
2003 return $errors;
2007 * Create a shorten filename
2009 * @param string $str filename
2010 * @param int $maxlength max file name length
2011 * @return string short filename
2013 public function get_short_filename($str, $maxlength) {
2014 if (textlib::strlen($str) >= $maxlength) {
2015 return trim(textlib::substr($str, 0, $maxlength)).'...';
2016 } else {
2017 return $str;
2022 * Overwrite an existing file
2024 * @param int $itemid
2025 * @param string $filepath
2026 * @param string $filename
2027 * @param string $newfilepath
2028 * @param string $newfilename
2029 * @return bool
2031 public static function overwrite_existing_draftfile($itemid, $filepath, $filename, $newfilepath, $newfilename) {
2032 global $USER;
2033 $fs = get_file_storage();
2034 $user_context = get_context_instance(CONTEXT_USER, $USER->id);
2035 if ($file = $fs->get_file($user_context->id, 'user', 'draft', $itemid, $filepath, $filename)) {
2036 if ($tempfile = $fs->get_file($user_context->id, 'user', 'draft', $itemid, $newfilepath, $newfilename)) {
2037 // delete existing file to release filename
2038 $file->delete();
2039 // create new file
2040 $newfile = $fs->create_file_from_storedfile(array('filepath'=>$filepath, 'filename'=>$filename), $tempfile);
2041 // remove temp file
2042 $tempfile->delete();
2043 return true;
2046 return false;
2050 * Delete a temp file from draft area
2052 * @param int $draftitemid
2053 * @param string $filepath
2054 * @param string $filename
2055 * @return bool
2057 public static function delete_tempfile_from_draft($draftitemid, $filepath, $filename) {
2058 global $USER;
2059 $fs = get_file_storage();
2060 $user_context = get_context_instance(CONTEXT_USER, $USER->id);
2061 if ($file = $fs->get_file($user_context->id, 'user', 'draft', $draftitemid, $filepath, $filename)) {
2062 $file->delete();
2063 return true;
2064 } else {
2065 return false;
2070 * Find all external files in this repo and import them
2072 public function convert_references_to_local() {
2073 $fs = get_file_storage();
2074 $files = $fs->get_external_files($this->id);
2075 foreach ($files as $storedfile) {
2076 $fs->import_external_file($storedfile);
2083 * Call to request proxy file sync with repository source.
2085 * @param stored_file $file
2086 * @return bool success
2088 public static function sync_external_file(stored_file $file) {
2089 global $DB;
2091 $fs = get_file_storage();
2093 if (!$reference = $DB->get_record('files_reference', array('id'=>$file->get_referencefileid()))) {
2094 return false;
2097 if (!empty($reference->lastsync) and ($reference->lastsync + $reference->lifetime > time())) {
2098 return false;
2101 if (!$repository = self::get_repository_by_id($reference->repositoryid, SYSCONTEXTID)) {
2102 return false;
2105 if (!$repository->sync_individual_file($file)) {
2106 return false;
2109 $fileinfo = $repository->get_file_by_reference($reference);
2110 if ($fileinfo === null) {
2111 // does not exist any more - set status to missing
2112 $sql = "UPDATE {files} SET status = :missing WHERE referencefileid = :referencefileid";
2113 $params = array('referencefileid'=>$reference->id, 'missing'=>666);
2114 $DB->execute($sql, $params);
2115 //TODO: purge content from pool if we set some other content hash and it is no used any more
2116 return true;
2117 } else if ($fileinfo === false) {
2118 // error
2119 return false;
2122 $contenthash = null;
2123 $filesize = null;
2124 if (!empty($fileinfo->contenthash)) {
2125 // contenthash returned, file already in moodle
2126 $contenthash = $fileinfo->contenthash;
2127 $filesize = $fileinfo->filesize;
2128 } else if (!empty($fileinfo->filepath)) {
2129 // File path returned
2130 list($contenthash, $filesize, $newfile) = $fs->add_file_to_pool($fileinfo->filepath);
2131 } else if (!empty($fileinfo->handle) && is_resource($fileinfo->handle)) {
2132 // File handle returned
2133 $contents = '';
2134 while (!feof($fileinfo->handle)) {
2135 $contents .= fread($handle, 8192);
2137 fclose($fileinfo->handle);
2138 list($contenthash, $filesize, $newfile) = $fs->add_string_to_pool($content);
2139 } else if (isset($fileinfo->content)) {
2140 // File content returned
2141 list($contenthash, $filesize, $newfile) = $fs->add_string_to_pool($fileinfo->content);
2144 if (!isset($contenthash) or !isset($filesize)) {
2145 return false;
2148 $now = time();
2149 // update files table
2150 $sql = "UPDATE {files} SET contenthash = :contenthash, filesize = :filesize, referencelastsync = :now, referencelifetime = :lifetime, timemodified = :now2 WHERE referencefileid = :referencefileid AND contenthash <> :contenthash2";
2151 $params = array('contenthash'=>$contenthash, 'filesize'=>$filesize, 'now'=>$now, 'lifetime'=>$reference->lifetime,
2152 'now2'=>$now, 'referencefileid'=>$reference->id, 'contenthash2'=>$contenthash);
2153 $DB->execute($sql, $params);
2155 $DB->set_field('files_reference', 'lastsync', $now, array('id'=>$reference->id));
2157 return true;
2162 * Exception class for repository api
2164 * @since 2.0
2165 * @package repository
2166 * @category repository
2167 * @copyright 2009 Dongsheng Cai {@link http://dongsheng.org}
2168 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2170 class repository_exception extends moodle_exception {
2174 * This is a class used to define a repository instance form
2176 * @since 2.0
2177 * @package repository
2178 * @category repository
2179 * @copyright 2009 Dongsheng Cai {@link http://dongsheng.org}
2180 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2182 final class repository_instance_form extends moodleform {
2183 /** @var stdClass repository instance */
2184 protected $instance;
2185 /** @var string repository plugin type */
2186 protected $plugin;
2189 * Added defaults to moodle form
2191 protected function add_defaults() {
2192 $mform =& $this->_form;
2193 $strrequired = get_string('required');
2195 $mform->addElement('hidden', 'edit', ($this->instance) ? $this->instance->id : 0);
2196 $mform->setType('edit', PARAM_INT);
2197 $mform->addElement('hidden', 'new', $this->plugin);
2198 $mform->setType('new', PARAM_FORMAT);
2199 $mform->addElement('hidden', 'plugin', $this->plugin);
2200 $mform->setType('plugin', PARAM_PLUGIN);
2201 $mform->addElement('hidden', 'typeid', $this->typeid);
2202 $mform->setType('typeid', PARAM_INT);
2203 $mform->addElement('hidden', 'contextid', $this->contextid);
2204 $mform->setType('contextid', PARAM_INT);
2206 $mform->addElement('text', 'name', get_string('name'), 'maxlength="100" size="30"');
2207 $mform->addRule('name', $strrequired, 'required', null, 'client');
2211 * Define moodle form elements
2213 public function definition() {
2214 global $CFG;
2215 // type of plugin, string
2216 $this->plugin = $this->_customdata['plugin'];
2217 $this->typeid = $this->_customdata['typeid'];
2218 $this->contextid = $this->_customdata['contextid'];
2219 $this->instance = (isset($this->_customdata['instance'])
2220 && is_subclass_of($this->_customdata['instance'], 'repository'))
2221 ? $this->_customdata['instance'] : null;
2223 $mform =& $this->_form;
2225 $this->add_defaults();
2226 //add fields
2227 if (!$this->instance) {
2228 $result = repository::static_function($this->plugin, 'instance_config_form', $mform);
2229 if ($result === false) {
2230 $mform->removeElement('name');
2232 } else {
2233 $data = array();
2234 $data['name'] = $this->instance->name;
2235 if (!$this->instance->readonly) {
2236 $result = $this->instance->instance_config_form($mform);
2237 if ($result === false) {
2238 $mform->removeElement('name');
2240 // and set the data if we have some.
2241 foreach ($this->instance->get_instance_option_names() as $config) {
2242 if (!empty($this->instance->options[$config])) {
2243 $data[$config] = $this->instance->options[$config];
2244 } else {
2245 $data[$config] = '';
2249 $this->set_data($data);
2252 if ($result === false) {
2253 $mform->addElement('cancel');
2254 } else {
2255 $this->add_action_buttons(true, get_string('save','repository'));
2260 * Validate moodle form data
2262 * @param array $data form data
2263 * @param array $files files in form
2264 * @return array errors
2266 public function validation($data, $files) {
2267 global $DB;
2268 $errors = array();
2269 $plugin = $this->_customdata['plugin'];
2270 $instance = (isset($this->_customdata['instance'])
2271 && is_subclass_of($this->_customdata['instance'], 'repository'))
2272 ? $this->_customdata['instance'] : null;
2273 if (!$instance) {
2274 $errors = repository::static_function($plugin, 'instance_form_validation', $this, $data, $errors);
2275 } else {
2276 $errors = $instance->instance_form_validation($this, $data, $errors);
2279 $sql = "SELECT count('x')
2280 FROM {repository_instances} i, {repository} r
2281 WHERE r.type=:plugin AND r.id=i.typeid AND i.name=:name";
2282 if ($DB->count_records_sql($sql, array('name' => $data['name'], 'plugin' => $data['plugin'])) > 1) {
2283 $errors['name'] = get_string('erroruniquename', 'repository');
2286 return $errors;
2291 * This is a class used to define a repository type setting form
2293 * @since 2.0
2294 * @package repository
2295 * @category repository
2296 * @copyright 2009 Dongsheng Cai {@link http://dongsheng.org}
2297 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2299 final class repository_type_form extends moodleform {
2300 /** @var stdClass repository instance */
2301 protected $instance;
2302 /** @var string repository plugin name */
2303 protected $plugin;
2304 /** @var string action */
2305 protected $action;
2308 * Definition of the moodleform
2310 public function definition() {
2311 global $CFG;
2312 // type of plugin, string
2313 $this->plugin = $this->_customdata['plugin'];
2314 $this->instance = (isset($this->_customdata['instance'])
2315 && is_a($this->_customdata['instance'], 'repository_type'))
2316 ? $this->_customdata['instance'] : null;
2318 $this->action = $this->_customdata['action'];
2319 $this->pluginname = $this->_customdata['pluginname'];
2320 $mform =& $this->_form;
2321 $strrequired = get_string('required');
2323 $mform->addElement('hidden', 'action', $this->action);
2324 $mform->setType('action', PARAM_TEXT);
2325 $mform->addElement('hidden', 'repos', $this->plugin);
2326 $mform->setType('repos', PARAM_PLUGIN);
2328 // let the plugin add its specific fields
2329 $classname = 'repository_' . $this->plugin;
2330 require_once($CFG->dirroot . '/repository/' . $this->plugin . '/lib.php');
2331 //add "enable course/user instances" checkboxes if multiple instances are allowed
2332 $instanceoptionnames = repository::static_function($this->plugin, 'get_instance_option_names');
2334 $result = call_user_func(array($classname, 'type_config_form'), $mform, $classname);
2336 if (!empty($instanceoptionnames)) {
2337 $sm = get_string_manager();
2338 $component = 'repository';
2339 if ($sm->string_exists('enablecourseinstances', 'repository_' . $this->plugin)) {
2340 $component .= ('_' . $this->plugin);
2342 $mform->addElement('checkbox', 'enablecourseinstances', get_string('enablecourseinstances', $component));
2344 $component = 'repository';
2345 if ($sm->string_exists('enableuserinstances', 'repository_' . $this->plugin)) {
2346 $component .= ('_' . $this->plugin);
2348 $mform->addElement('checkbox', 'enableuserinstances', get_string('enableuserinstances', $component));
2351 // set the data if we have some.
2352 if ($this->instance) {
2353 $data = array();
2354 $option_names = call_user_func(array($classname,'get_type_option_names'));
2355 if (!empty($instanceoptionnames)){
2356 $option_names[] = 'enablecourseinstances';
2357 $option_names[] = 'enableuserinstances';
2360 $instanceoptions = $this->instance->get_options();
2361 foreach ($option_names as $config) {
2362 if (!empty($instanceoptions[$config])) {
2363 $data[$config] = $instanceoptions[$config];
2364 } else {
2365 $data[$config] = '';
2368 // XXX: set plugin name for plugins which doesn't have muliti instances
2369 if (empty($instanceoptionnames)){
2370 $data['pluginname'] = $this->pluginname;
2372 $this->set_data($data);
2375 $this->add_action_buttons(true, get_string('save','repository'));
2379 * Validate moodle form data
2381 * @param array $data moodle form data
2382 * @param array $files
2383 * @return array errors
2385 public function validation($data, $files) {
2386 $errors = array();
2387 $plugin = $this->_customdata['plugin'];
2388 $instance = (isset($this->_customdata['instance'])
2389 && is_subclass_of($this->_customdata['instance'], 'repository'))
2390 ? $this->_customdata['instance'] : null;
2391 if (!$instance) {
2392 $errors = repository::static_function($plugin, 'type_form_validation', $this, $data, $errors);
2393 } else {
2394 $errors = $instance->type_form_validation($this, $data, $errors);
2397 return $errors;
2402 * Generate all options needed by filepicker
2404 * @param array $args including following keys
2405 * context
2406 * accepted_types
2407 * return_types
2409 * @return array the list of repository instances, including meta infomation, containing the following keys
2410 * externallink
2411 * repositories
2412 * accepted_types
2414 function initialise_filepicker($args) {
2415 global $CFG, $USER, $PAGE, $OUTPUT;
2416 static $templatesinitialized;
2417 require_once($CFG->libdir . '/licenselib.php');
2419 $return = new stdClass();
2420 $licenses = array();
2421 if (!empty($CFG->licenses)) {
2422 $array = explode(',', $CFG->licenses);
2423 foreach ($array as $license) {
2424 $l = new stdClass();
2425 $l->shortname = $license;
2426 $l->fullname = get_string($license, 'license');
2427 $licenses[] = $l;
2430 if (!empty($CFG->sitedefaultlicense)) {
2431 $return->defaultlicense = $CFG->sitedefaultlicense;
2434 $return->licenses = $licenses;
2436 $return->author = fullname($USER);
2438 if (empty($args->context)) {
2439 $context = $PAGE->context;
2440 } else {
2441 $context = $args->context;
2443 $disable_types = array();
2444 if (!empty($args->disable_types)) {
2445 $disable_types = $args->disable_types;
2448 $user_context = get_context_instance(CONTEXT_USER, $USER->id);
2450 list($context, $course, $cm) = get_context_info_array($context->id);
2451 $contexts = array($user_context, get_system_context());
2452 if (!empty($course)) {
2453 // adding course context
2454 $contexts[] = get_context_instance(CONTEXT_COURSE, $course->id);
2456 $externallink = (int)get_config(null, 'repositoryallowexternallinks');
2457 $repositories = repository::get_instances(array(
2458 'context'=>$contexts,
2459 'currentcontext'=> $context,
2460 'accepted_types'=>$args->accepted_types,
2461 'return_types'=>$args->return_types,
2462 'disable_types'=>$disable_types
2465 $return->repositories = array();
2467 if (empty($externallink)) {
2468 $return->externallink = false;
2469 } else {
2470 $return->externallink = true;
2473 // provided by form element
2474 $return->accepted_types = file_get_typegroup('extension', $args->accepted_types);
2475 $return->return_types = $args->return_types;
2476 foreach ($repositories as $repository) {
2477 $meta = $repository->get_meta();
2478 // Please note that the array keys for repositories are used within
2479 // JavaScript a lot, the key NEEDS to be the repository id.
2480 $return->repositories[$repository->id] = $meta;
2482 if (!$templatesinitialized) {
2483 // we need to send filepicker templates to the browser just once
2484 $fprenderer = $PAGE->get_renderer('core', 'files');
2485 $templates = $fprenderer->filepicker_js_templates();
2486 $PAGE->requires->js_init_call('M.core_filepicker.set_templates', array($templates), true);
2487 $templatesinitialized = true;
2489 return $return;
2492 * Small function to walk an array to attach repository ID
2494 * @param array $value
2495 * @param string $key
2496 * @param int $id
2498 function repository_attach_id(&$value, $key, $id){
2499 $value['repo_id'] = $id;