weekly release 3.1.2+
[moodle.git] / repository / lib.php
blob5d0d905be5b8a60e2bf7bc704211c3cb4de06031
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
20 * @since Moodle 2.0
21 * @package core_repository
22 * @copyright 2009 Dongsheng Cai {@link http://dongsheng.org}
23 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
26 defined('MOODLE_INTERNAL') || die();
27 require_once($CFG->libdir . '/filelib.php');
28 require_once($CFG->libdir . '/formslib.php');
30 define('FILE_EXTERNAL', 1);
31 define('FILE_INTERNAL', 2);
32 define('FILE_REFERENCE', 4);
33 define('RENAME_SUFFIX', '_2');
35 /**
36 * This class is used to manage repository plugins
38 * A repository_type is a repository plug-in. It can be Box.net, Flick-r, ...
39 * A repository type can be edited, sorted and hidden. It is mandatory for an
40 * administrator to create a repository type in order to be able to create
41 * some instances of this type.
42 * Coding note:
43 * - a repository_type object is mapped to the "repository" database table
44 * - "typename" attibut maps the "type" database field. It is unique.
45 * - general "options" for a repository type are saved in the config_plugin table
46 * - when you delete a repository, all instances are deleted, and general
47 * options are also deleted from database
48 * - When you create a type for a plugin that can't have multiple instances, a
49 * instance is automatically created.
51 * @package core_repository
52 * @copyright 2009 Jerome Mouneyrac
53 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
55 class repository_type implements cacheable_object {
58 /**
59 * Type name (no whitespace) - A type name is unique
60 * Note: for a user-friendly type name see get_readablename()
61 * @var String
63 private $_typename;
66 /**
67 * Options of this type
68 * They are general options that any instance of this type would share
69 * e.g. API key
70 * These options are saved in config_plugin table
71 * @var array
73 private $_options;
76 /**
77 * Is the repository type visible or hidden
78 * If false (hidden): no instances can be created, edited, deleted, showned , used...
79 * @var boolean
81 private $_visible;
84 /**
85 * 0 => not ordered, 1 => first position, 2 => second position...
86 * A not order type would appear in first position (should never happened)
87 * @var integer
89 private $_sortorder;
91 /**
92 * Return if the instance is visible in a context
94 * @todo check if the context visibility has been overwritten by the plugin creator
95 * (need to create special functions to be overvwritten in repository class)
96 * @param stdClass $context context
97 * @return bool
99 public function get_contextvisibility($context) {
100 global $USER;
102 if ($context->contextlevel == CONTEXT_COURSE) {
103 return $this->_options['enablecourseinstances'];
106 if ($context->contextlevel == CONTEXT_USER) {
107 return $this->_options['enableuserinstances'];
110 //the context is SITE
111 return true;
117 * repository_type constructor
119 * @param int $typename
120 * @param array $typeoptions
121 * @param bool $visible
122 * @param int $sortorder (don't really need set, it will be during create() call)
124 public function __construct($typename = '', $typeoptions = array(), $visible = true, $sortorder = 0) {
125 global $CFG;
127 //set type attributs
128 $this->_typename = $typename;
129 $this->_visible = $visible;
130 $this->_sortorder = $sortorder;
132 //set options attribut
133 $this->_options = array();
134 $options = repository::static_function($typename, 'get_type_option_names');
135 //check that the type can be setup
136 if (!empty($options)) {
137 //set the type options
138 foreach ($options as $config) {
139 if (array_key_exists($config, $typeoptions)) {
140 $this->_options[$config] = $typeoptions[$config];
145 //retrieve visibility from option
146 if (array_key_exists('enablecourseinstances',$typeoptions)) {
147 $this->_options['enablecourseinstances'] = $typeoptions['enablecourseinstances'];
148 } else {
149 $this->_options['enablecourseinstances'] = 0;
152 if (array_key_exists('enableuserinstances',$typeoptions)) {
153 $this->_options['enableuserinstances'] = $typeoptions['enableuserinstances'];
154 } else {
155 $this->_options['enableuserinstances'] = 0;
161 * Get the type name (no whitespace)
162 * For a human readable name, use get_readablename()
164 * @return string the type name
166 public function get_typename() {
167 return $this->_typename;
171 * Return a human readable and user-friendly type name
173 * @return string user-friendly type name
175 public function get_readablename() {
176 return get_string('pluginname','repository_'.$this->_typename);
180 * Return general options
182 * @return array the general options
184 public function get_options() {
185 return $this->_options;
189 * Return visibility
191 * @return bool
193 public function get_visible() {
194 return $this->_visible;
198 * Return order / position of display in the file picker
200 * @return int
202 public function get_sortorder() {
203 return $this->_sortorder;
207 * Create a repository type (the type name must not already exist)
208 * @param bool $silent throw exception?
209 * @return mixed return int if create successfully, return false if
211 public function create($silent = false) {
212 global $DB;
214 //check that $type has been set
215 $timmedtype = trim($this->_typename);
216 if (empty($timmedtype)) {
217 throw new repository_exception('emptytype', 'repository');
220 //set sortorder as the last position in the list
221 if (!isset($this->_sortorder) || $this->_sortorder == 0 ) {
222 $sql = "SELECT MAX(sortorder) FROM {repository}";
223 $this->_sortorder = 1 + $DB->get_field_sql($sql);
226 //only create a new type if it doesn't already exist
227 $existingtype = $DB->get_record('repository', array('type'=>$this->_typename));
228 if (!$existingtype) {
229 //create the type
230 $newtype = new stdClass();
231 $newtype->type = $this->_typename;
232 $newtype->visible = $this->_visible;
233 $newtype->sortorder = $this->_sortorder;
234 $plugin_id = $DB->insert_record('repository', $newtype);
235 //save the options in DB
236 $this->update_options();
238 $instanceoptionnames = repository::static_function($this->_typename, 'get_instance_option_names');
240 //if the plugin type has no multiple instance (e.g. has no instance option name) so it wont
241 //be possible for the administrator to create a instance
242 //in this case we need to create an instance
243 if (empty($instanceoptionnames)) {
244 $instanceoptions = array();
245 if (empty($this->_options['pluginname'])) {
246 // when moodle trying to install some repo plugin automatically
247 // this option will be empty, get it from language string when display
248 $instanceoptions['name'] = '';
249 } else {
250 // when admin trying to add a plugin manually, he will type a name
251 // for it
252 $instanceoptions['name'] = $this->_options['pluginname'];
254 repository::static_function($this->_typename, 'create', $this->_typename, 0, context_system::instance(), $instanceoptions);
256 //run plugin_init function
257 if (!repository::static_function($this->_typename, 'plugin_init')) {
258 $this->update_visibility(false);
259 if (!$silent) {
260 throw new repository_exception('cannotinitplugin', 'repository');
264 cache::make('core', 'repositories')->purge();
265 if(!empty($plugin_id)) {
266 // return plugin_id if create successfully
267 return $plugin_id;
268 } else {
269 return false;
272 } else {
273 if (!$silent) {
274 throw new repository_exception('existingrepository', 'repository');
276 // If plugin existed, return false, tell caller no new plugins were created.
277 return false;
283 * Update plugin options into the config_plugin table
285 * @param array $options
286 * @return bool
288 public function update_options($options = null) {
289 global $DB;
290 $classname = 'repository_' . $this->_typename;
291 $instanceoptions = repository::static_function($this->_typename, 'get_instance_option_names');
292 if (empty($instanceoptions)) {
293 // update repository instance name if this plugin type doesn't have muliti instances
294 $params = array();
295 $params['type'] = $this->_typename;
296 $instances = repository::get_instances($params);
297 $instance = array_pop($instances);
298 if ($instance) {
299 $DB->set_field('repository_instances', 'name', $options['pluginname'], array('id'=>$instance->id));
301 unset($options['pluginname']);
304 if (!empty($options)) {
305 $this->_options = $options;
308 foreach ($this->_options as $name => $value) {
309 set_config($name, $value, $this->_typename);
312 cache::make('core', 'repositories')->purge();
313 return true;
317 * Update visible database field with the value given as parameter
318 * or with the visible value of this object
319 * This function is private.
320 * For public access, have a look to switch_and_update_visibility()
322 * @param bool $visible
323 * @return bool
325 private function update_visible($visible = null) {
326 global $DB;
328 if (!empty($visible)) {
329 $this->_visible = $visible;
331 else if (!isset($this->_visible)) {
332 throw new repository_exception('updateemptyvisible', 'repository');
335 cache::make('core', 'repositories')->purge();
336 return $DB->set_field('repository', 'visible', $this->_visible, array('type'=>$this->_typename));
340 * Update database sortorder field with the value given as parameter
341 * or with the sortorder value of this object
342 * This function is private.
343 * For public access, have a look to move_order()
345 * @param int $sortorder
346 * @return bool
348 private function update_sortorder($sortorder = null) {
349 global $DB;
351 if (!empty($sortorder) && $sortorder!=0) {
352 $this->_sortorder = $sortorder;
354 //if sortorder is not set, we set it as the ;ast position in the list
355 else if (!isset($this->_sortorder) || $this->_sortorder == 0 ) {
356 $sql = "SELECT MAX(sortorder) FROM {repository}";
357 $this->_sortorder = 1 + $DB->get_field_sql($sql);
360 cache::make('core', 'repositories')->purge();
361 return $DB->set_field('repository', 'sortorder', $this->_sortorder, array('type'=>$this->_typename));
365 * Change order of the type with its adjacent upper or downer type
366 * (database fields are updated)
367 * Algorithm details:
368 * 1. retrieve all types in an array. This array is sorted by sortorder,
369 * and the array keys start from 0 to X (incremented by 1)
370 * 2. switch sortorder values of this type and its adjacent type
372 * @param string $move "up" or "down"
374 public function move_order($move) {
375 global $DB;
377 $types = repository::get_types(); // retrieve all types
379 // retrieve this type into the returned array
380 $i = 0;
381 while (!isset($indice) && $i<count($types)) {
382 if ($types[$i]->get_typename() == $this->_typename) {
383 $indice = $i;
385 $i++;
388 // retrieve adjacent indice
389 switch ($move) {
390 case "up":
391 $adjacentindice = $indice - 1;
392 break;
393 case "down":
394 $adjacentindice = $indice + 1;
395 break;
396 default:
397 throw new repository_exception('movenotdefined', 'repository');
400 //switch sortorder of this type and the adjacent type
401 //TODO: we could reset sortorder for all types. This is not as good in performance term, but
402 //that prevent from wrong behaviour on a screwed database. As performance are not important in this particular case
403 //it worth to change the algo.
404 if ($adjacentindice>=0 && !empty($types[$adjacentindice])) {
405 $DB->set_field('repository', 'sortorder', $this->_sortorder, array('type'=>$types[$adjacentindice]->get_typename()));
406 $this->update_sortorder($types[$adjacentindice]->get_sortorder());
411 * 1. Change visibility to the value chosen
412 * 2. Update the type
414 * @param bool $visible
415 * @return bool
417 public function update_visibility($visible = null) {
418 if (is_bool($visible)) {
419 $this->_visible = $visible;
420 } else {
421 $this->_visible = !$this->_visible;
423 return $this->update_visible();
428 * Delete a repository_type (general options are removed from config_plugin
429 * table, and all instances are deleted)
431 * @param bool $downloadcontents download external contents if exist
432 * @return bool
434 public function delete($downloadcontents = false) {
435 global $DB;
437 //delete all instances of this type
438 $params = array();
439 $params['context'] = array();
440 $params['onlyvisible'] = false;
441 $params['type'] = $this->_typename;
442 $instances = repository::get_instances($params);
443 foreach ($instances as $instance) {
444 $instance->delete($downloadcontents);
447 //delete all general options
448 foreach ($this->_options as $name => $value) {
449 set_config($name, null, $this->_typename);
452 cache::make('core', 'repositories')->purge();
453 try {
454 $DB->delete_records('repository', array('type' => $this->_typename));
455 } catch (dml_exception $ex) {
456 return false;
458 return true;
462 * Prepares the repository type to be cached. Implements method from cacheable_object interface.
464 * @return array
466 public function prepare_to_cache() {
467 return array(
468 'typename' => $this->_typename,
469 'typeoptions' => $this->_options,
470 'visible' => $this->_visible,
471 'sortorder' => $this->_sortorder
476 * Restores repository type from cache. Implements method from cacheable_object interface.
478 * @return array
480 public static function wake_from_cache($data) {
481 return new repository_type($data['typename'], $data['typeoptions'], $data['visible'], $data['sortorder']);
486 * This is the base class of the repository class.
488 * To create repository plugin, see: {@link http://docs.moodle.org/dev/Repository_plugins}
489 * See an example: {@link repository_boxnet}
491 * @package core_repository
492 * @copyright 2009 Dongsheng Cai {@link http://dongsheng.org}
493 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
495 abstract class repository implements cacheable_object {
497 * Timeout in seconds for downloading the external file into moodle
498 * @deprecated since Moodle 2.7, please use $CFG->repositorygetfiletimeout instead
500 const GETFILE_TIMEOUT = 30;
503 * Timeout in seconds for syncronising the external file size
504 * @deprecated since Moodle 2.7, please use $CFG->repositorysyncfiletimeout instead
506 const SYNCFILE_TIMEOUT = 1;
509 * Timeout in seconds for downloading an image file from external repository during syncronisation
510 * @deprecated since Moodle 2.7, please use $CFG->repositorysyncimagetimeout instead
512 const SYNCIMAGE_TIMEOUT = 3;
514 // $disabled can be set to true to disable a plugin by force
515 // example: self::$disabled = true
516 /** @var bool force disable repository instance */
517 public $disabled = false;
518 /** @var int repository instance id */
519 public $id;
520 /** @var stdClass current context */
521 public $context;
522 /** @var array repository options */
523 public $options;
524 /** @var bool Whether or not the repository instance is editable */
525 public $readonly;
526 /** @var int return types */
527 public $returntypes;
528 /** @var stdClass repository instance database record */
529 public $instance;
530 /** @var string Type of repository (webdav, google_docs, dropbox, ...). Read from $this->get_typename(). */
531 protected $typename;
534 * Constructor
536 * @param int $repositoryid repository instance id
537 * @param int|stdClass $context a context id or context object
538 * @param array $options repository options
539 * @param int $readonly indicate this repo is readonly or not
541 public function __construct($repositoryid, $context = SYSCONTEXTID, $options = array(), $readonly = 0) {
542 global $DB;
543 $this->id = $repositoryid;
544 if (is_object($context)) {
545 $this->context = $context;
546 } else {
547 $this->context = context::instance_by_id($context);
549 $cache = cache::make('core', 'repositories');
550 if (($this->instance = $cache->get('i:'. $this->id)) === false) {
551 $this->instance = $DB->get_record_sql("SELECT i.*, r.type AS repositorytype, r.sortorder, r.visible
552 FROM {repository} r, {repository_instances} i
553 WHERE i.typeid = r.id and i.id = ?", array('id' => $this->id));
554 $cache->set('i:'. $this->id, $this->instance);
556 $this->readonly = $readonly;
557 $this->options = array();
559 if (is_array($options)) {
560 // The get_option() method will get stored options in database.
561 $options = array_merge($this->get_option(), $options);
562 } else {
563 $options = $this->get_option();
565 foreach ($options as $n => $v) {
566 $this->options[$n] = $v;
568 $this->name = $this->get_name();
569 $this->returntypes = $this->supported_returntypes();
570 $this->super_called = true;
574 * Get repository instance using repository id
576 * Note that this function does not check permission to access repository contents
578 * @throws repository_exception
580 * @param int $repositoryid repository instance ID
581 * @param context|int $context context instance or context ID where this repository will be used
582 * @param array $options additional repository options
583 * @return repository
585 public static function get_repository_by_id($repositoryid, $context, $options = array()) {
586 global $CFG, $DB;
587 $cache = cache::make('core', 'repositories');
588 if (!is_object($context)) {
589 $context = context::instance_by_id($context);
591 $cachekey = 'rep:'. $repositoryid. ':'. $context->id. ':'. serialize($options);
592 if ($repository = $cache->get($cachekey)) {
593 return $repository;
596 if (!$record = $cache->get('i:'. $repositoryid)) {
597 $sql = "SELECT i.*, r.type AS repositorytype, r.visible, r.sortorder
598 FROM {repository_instances} i
599 JOIN {repository} r ON r.id = i.typeid
600 WHERE i.id = ?";
601 if (!$record = $DB->get_record_sql($sql, array($repositoryid))) {
602 throw new repository_exception('invalidrepositoryid', 'repository');
604 $cache->set('i:'. $record->id, $record);
607 $type = $record->repositorytype;
608 if (file_exists($CFG->dirroot . "/repository/$type/lib.php")) {
609 require_once($CFG->dirroot . "/repository/$type/lib.php");
610 $classname = 'repository_' . $type;
611 $options['type'] = $type;
612 $options['typeid'] = $record->typeid;
613 $options['visible'] = $record->visible;
614 if (empty($options['name'])) {
615 $options['name'] = $record->name;
617 $repository = new $classname($repositoryid, $context, $options, $record->readonly);
618 if (empty($repository->super_called)) {
619 // to make sure the super construct is called
620 debugging('parent::__construct must be called by '.$type.' plugin.');
622 $cache->set($cachekey, $repository);
623 return $repository;
624 } else {
625 throw new repository_exception('invalidplugin', 'repository');
630 * Returns the type name of the repository.
632 * @return string type name of the repository.
633 * @since Moodle 2.5
635 public function get_typename() {
636 if (empty($this->typename)) {
637 $matches = array();
638 if (!preg_match("/^repository_(.*)$/", get_class($this), $matches)) {
639 throw new coding_exception('The class name of a repository should be repository_<typeofrepository>, '.
640 'e.g. repository_dropbox');
642 $this->typename = $matches[1];
644 return $this->typename;
648 * Get a repository type object by a given type name.
650 * @static
651 * @param string $typename the repository type name
652 * @return repository_type|bool
654 public static function get_type_by_typename($typename) {
655 global $DB;
656 $cache = cache::make('core', 'repositories');
657 if (($repositorytype = $cache->get('typename:'. $typename)) === false) {
658 $repositorytype = null;
659 if ($record = $DB->get_record('repository', array('type' => $typename))) {
660 $repositorytype = new repository_type($record->type, (array)get_config($record->type), $record->visible, $record->sortorder);
661 $cache->set('typeid:'. $record->id, $repositorytype);
663 $cache->set('typename:'. $typename, $repositorytype);
665 return $repositorytype;
669 * Get the repository type by a given repository type id.
671 * @static
672 * @param int $id the type id
673 * @return object
675 public static function get_type_by_id($id) {
676 global $DB;
677 $cache = cache::make('core', 'repositories');
678 if (($repositorytype = $cache->get('typeid:'. $id)) === false) {
679 $repositorytype = null;
680 if ($record = $DB->get_record('repository', array('id' => $id))) {
681 $repositorytype = new repository_type($record->type, (array)get_config($record->type), $record->visible, $record->sortorder);
682 $cache->set('typename:'. $record->type, $repositorytype);
684 $cache->set('typeid:'. $id, $repositorytype);
686 return $repositorytype;
690 * Return all repository types ordered by sortorder field
691 * first repository type in returnedarray[0], second repository type in returnedarray[1], ...
693 * @static
694 * @param bool $visible can return types by visiblity, return all types if null
695 * @return array Repository types
697 public static function get_types($visible=null) {
698 global $DB, $CFG;
699 $cache = cache::make('core', 'repositories');
700 if (!$visible) {
701 $typesnames = $cache->get('types');
702 } else {
703 $typesnames = $cache->get('typesvis');
705 $types = array();
706 if ($typesnames === false) {
707 $typesnames = array();
708 $vistypesnames = array();
709 if ($records = $DB->get_records('repository', null ,'sortorder')) {
710 foreach($records as $type) {
711 if (($repositorytype = $cache->get('typename:'. $type->type)) === false) {
712 // Create new instance of repository_type.
713 if (file_exists($CFG->dirroot . '/repository/'. $type->type .'/lib.php')) {
714 $repositorytype = new repository_type($type->type, (array)get_config($type->type), $type->visible, $type->sortorder);
715 $cache->set('typeid:'. $type->id, $repositorytype);
716 $cache->set('typename:'. $type->type, $repositorytype);
719 if ($repositorytype) {
720 if (empty($visible) || $repositorytype->get_visible()) {
721 $types[] = $repositorytype;
722 $vistypesnames[] = $repositorytype->get_typename();
724 $typesnames[] = $repositorytype->get_typename();
728 $cache->set('types', $typesnames);
729 $cache->set('typesvis', $vistypesnames);
730 } else {
731 foreach ($typesnames as $typename) {
732 $types[] = self::get_type_by_typename($typename);
735 return $types;
739 * Checks if user has a capability to view the current repository.
741 * @return bool true when the user can, otherwise throws an exception.
742 * @throws repository_exception when the user does not meet the requirements.
744 public final function check_capability() {
745 global $USER;
747 // The context we are on.
748 $currentcontext = $this->context;
750 // Ensure that the user can view the repository in the current context.
751 $can = has_capability('repository/'.$this->get_typename().':view', $currentcontext);
753 // Context in which the repository has been created.
754 $repocontext = context::instance_by_id($this->instance->contextid);
756 // Prevent access to private repositories when logged in as.
757 if ($can && \core\session\manager::is_loggedinas()) {
758 if ($this->contains_private_data() || $repocontext->contextlevel == CONTEXT_USER) {
759 $can = false;
763 // We are going to ensure that the current context was legit, and reliable to check
764 // the capability against. (No need to do that if we already cannot).
765 if ($can) {
766 if ($repocontext->contextlevel == CONTEXT_USER) {
767 // The repository is a user instance, ensure we're the right user to access it!
768 if ($repocontext->instanceid != $USER->id) {
769 $can = false;
771 } else if ($repocontext->contextlevel == CONTEXT_COURSE) {
772 // The repository is a course one. Let's check that we are on the right course.
773 if (in_array($currentcontext->contextlevel, array(CONTEXT_COURSE, CONTEXT_MODULE, CONTEXT_BLOCK))) {
774 $coursecontext = $currentcontext->get_course_context();
775 if ($coursecontext->instanceid != $repocontext->instanceid) {
776 $can = false;
778 } else {
779 // We are on a parent context, therefore it's legit to check the permissions
780 // in the current context.
782 } else {
783 // Nothing to check here, system instances can have different permissions on different
784 // levels. We do not want to prevent URL hack here, because it does not make sense to
785 // prevent a user to access a repository in a context if it's accessible in another one.
789 if ($can) {
790 return true;
793 throw new repository_exception('nopermissiontoaccess', 'repository');
797 * Check if file already exists in draft area.
799 * @static
800 * @param int $itemid of the draft area.
801 * @param string $filepath path to the file.
802 * @param string $filename file name.
803 * @return bool
805 public static function draftfile_exists($itemid, $filepath, $filename) {
806 global $USER;
807 $fs = get_file_storage();
808 $usercontext = context_user::instance($USER->id);
809 return $fs->file_exists($usercontext->id, 'user', 'draft', $itemid, $filepath, $filename);
813 * Parses the moodle file reference and returns an instance of stored_file
815 * @param string $reference reference to the moodle internal file as retruned by
816 * {@link repository::get_file_reference()} or {@link file_storage::pack_reference()}
817 * @return stored_file|null
819 public static function get_moodle_file($reference) {
820 $params = file_storage::unpack_reference($reference, true);
821 $fs = get_file_storage();
822 return $fs->get_file($params['contextid'], $params['component'], $params['filearea'],
823 $params['itemid'], $params['filepath'], $params['filename']);
827 * Repository method to make sure that user can access particular file.
829 * This is checked when user tries to pick the file from repository to deal with
830 * potential parameter substitutions is request
832 * @param string $source source of the file, returned by repository as 'source' and received back from user (not cleaned)
833 * @return bool whether the file is accessible by current user
835 public function file_is_accessible($source) {
836 if ($this->has_moodle_files()) {
837 $reference = $this->get_file_reference($source);
838 try {
839 $params = file_storage::unpack_reference($reference, true);
840 } catch (file_reference_exception $e) {
841 return false;
843 $browser = get_file_browser();
844 $context = context::instance_by_id($params['contextid']);
845 $file_info = $browser->get_file_info($context, $params['component'], $params['filearea'],
846 $params['itemid'], $params['filepath'], $params['filename']);
847 return !empty($file_info);
849 return true;
853 * This function is used to copy a moodle file to draft area.
855 * It DOES NOT check if the user is allowed to access this file because the actual file
856 * can be located in the area where user does not have access to but there is an alias
857 * to this file in the area where user CAN access it.
858 * {@link file_is_accessible} should be called for alias location before calling this function.
860 * @param string $source The metainfo of file, it is base64 encoded php serialized data
861 * @param stdClass|array $filerecord contains itemid, filepath, filename and optionally other
862 * attributes of the new file
863 * @param int $maxbytes maximum allowed size of file, -1 if unlimited. If size of file exceeds
864 * the limit, the file_exception is thrown.
865 * @param int $areamaxbytes the maximum size of the area. A file_exception is thrown if the
866 * new file will reach the limit.
867 * @return array The information about the created file
869 public function copy_to_area($source, $filerecord, $maxbytes = -1, $areamaxbytes = FILE_AREA_MAX_BYTES_UNLIMITED) {
870 global $USER;
871 $fs = get_file_storage();
873 if ($this->has_moodle_files() == false) {
874 throw new coding_exception('Only repository used to browse moodle files can use repository::copy_to_area()');
877 $user_context = context_user::instance($USER->id);
879 $filerecord = (array)$filerecord;
880 // make sure the new file will be created in user draft area
881 $filerecord['component'] = 'user';
882 $filerecord['filearea'] = 'draft';
883 $filerecord['contextid'] = $user_context->id;
884 $draftitemid = $filerecord['itemid'];
885 $new_filepath = $filerecord['filepath'];
886 $new_filename = $filerecord['filename'];
888 // the file needs to copied to draft area
889 $stored_file = self::get_moodle_file($source);
890 if ($maxbytes != -1 && $stored_file->get_filesize() > $maxbytes) {
891 $maxbytesdisplay = display_size($maxbytes);
892 throw new file_exception('maxbytesfile', (object) array('file' => $filerecord['filename'],
893 'size' => $maxbytesdisplay));
895 // Validate the size of the draft area.
896 if (file_is_draft_area_limit_reached($draftitemid, $areamaxbytes, $stored_file->get_filesize())) {
897 throw new file_exception('maxareabytes');
900 if (repository::draftfile_exists($draftitemid, $new_filepath, $new_filename)) {
901 // create new file
902 $unused_filename = repository::get_unused_filename($draftitemid, $new_filepath, $new_filename);
903 $filerecord['filename'] = $unused_filename;
904 $fs->create_file_from_storedfile($filerecord, $stored_file);
905 $event = array();
906 $event['event'] = 'fileexists';
907 $event['newfile'] = new stdClass;
908 $event['newfile']->filepath = $new_filepath;
909 $event['newfile']->filename = $unused_filename;
910 $event['newfile']->url = moodle_url::make_draftfile_url($draftitemid, $new_filepath, $unused_filename)->out();
911 $event['existingfile'] = new stdClass;
912 $event['existingfile']->filepath = $new_filepath;
913 $event['existingfile']->filename = $new_filename;
914 $event['existingfile']->url = moodle_url::make_draftfile_url($draftitemid, $new_filepath, $new_filename)->out();
915 return $event;
916 } else {
917 $fs->create_file_from_storedfile($filerecord, $stored_file);
918 $info = array();
919 $info['itemid'] = $draftitemid;
920 $info['file'] = $new_filename;
921 $info['title'] = $new_filename;
922 $info['contextid'] = $user_context->id;
923 $info['url'] = moodle_url::make_draftfile_url($draftitemid, $new_filepath, $new_filename)->out();
924 $info['filesize'] = $stored_file->get_filesize();
925 return $info;
930 * Get an unused filename from the current draft area.
932 * Will check if the file ends with ([0-9]) and increase the number.
934 * @static
935 * @param int $itemid draft item ID.
936 * @param string $filepath path to the file.
937 * @param string $filename name of the file.
938 * @return string an unused file name.
940 public static function get_unused_filename($itemid, $filepath, $filename) {
941 global $USER;
942 $contextid = context_user::instance($USER->id)->id;
943 $fs = get_file_storage();
944 return $fs->get_unused_filename($contextid, 'user', 'draft', $itemid, $filepath, $filename);
948 * Append a suffix to filename.
950 * @static
951 * @param string $filename
952 * @return string
953 * @deprecated since 2.5
955 public static function append_suffix($filename) {
956 debugging('The function repository::append_suffix() has been deprecated. Use repository::get_unused_filename() instead.',
957 DEBUG_DEVELOPER);
958 $pathinfo = pathinfo($filename);
959 if (empty($pathinfo['extension'])) {
960 return $filename . RENAME_SUFFIX;
961 } else {
962 return $pathinfo['filename'] . RENAME_SUFFIX . '.' . $pathinfo['extension'];
967 * Return all types that you a user can create/edit and which are also visible
968 * Note: Mostly used in order to know if at least one editable type can be set
970 * @static
971 * @param stdClass $context the context for which we want the editable types
972 * @return array types
974 public static function get_editable_types($context = null) {
976 if (empty($context)) {
977 $context = context_system::instance();
980 $types= repository::get_types(true);
981 $editabletypes = array();
982 foreach ($types as $type) {
983 $instanceoptionnames = repository::static_function($type->get_typename(), 'get_instance_option_names');
984 if (!empty($instanceoptionnames)) {
985 if ($type->get_contextvisibility($context)) {
986 $editabletypes[]=$type;
990 return $editabletypes;
994 * Return repository instances
996 * @static
997 * @param array $args Array containing the following keys:
998 * currentcontext : instance of context (default system context)
999 * context : array of instances of context (default empty array)
1000 * onlyvisible : bool (default true)
1001 * type : string return instances of this type only
1002 * accepted_types : string|array return instances that contain files of those types (*, web_image, .pdf, ...)
1003 * return_types : int combination of FILE_INTERNAL & FILE_EXTERNAL & FILE_REFERENCE.
1004 * 0 means every type. The default is FILE_INTERNAL | FILE_EXTERNAL.
1005 * userid : int if specified, instances belonging to other users will not be returned
1007 * @return array repository instances
1009 public static function get_instances($args = array()) {
1010 global $DB, $CFG, $USER;
1012 // Fill $args attributes with default values unless specified
1013 if (!isset($args['currentcontext']) || !($args['currentcontext'] instanceof context)) {
1014 $current_context = context_system::instance();
1015 } else {
1016 $current_context = $args['currentcontext'];
1018 $args['currentcontext'] = $current_context->id;
1019 $contextids = array();
1020 if (!empty($args['context'])) {
1021 foreach ($args['context'] as $context) {
1022 $contextids[] = $context->id;
1025 $args['context'] = $contextids;
1026 if (!isset($args['onlyvisible'])) {
1027 $args['onlyvisible'] = true;
1029 if (!isset($args['return_types'])) {
1030 $args['return_types'] = FILE_INTERNAL | FILE_EXTERNAL;
1032 if (!isset($args['type'])) {
1033 $args['type'] = null;
1035 if (empty($args['disable_types']) || !is_array($args['disable_types'])) {
1036 $args['disable_types'] = null;
1038 if (empty($args['userid']) || !is_numeric($args['userid'])) {
1039 $args['userid'] = null;
1041 if (!isset($args['accepted_types']) || (is_array($args['accepted_types']) && in_array('*', $args['accepted_types']))) {
1042 $args['accepted_types'] = '*';
1044 ksort($args);
1045 $cachekey = 'all:'. serialize($args);
1047 // Check if we have cached list of repositories with the same query
1048 $cache = cache::make('core', 'repositories');
1049 if (($cachedrepositories = $cache->get($cachekey)) !== false) {
1050 // convert from cacheable_object_array to array
1051 $repositories = array();
1052 foreach ($cachedrepositories as $repository) {
1053 $repositories[$repository->id] = $repository;
1055 return $repositories;
1058 // Prepare DB SQL query to retrieve repositories
1059 $params = array();
1060 $sql = "SELECT i.*, r.type AS repositorytype, r.sortorder, r.visible
1061 FROM {repository} r, {repository_instances} i
1062 WHERE i.typeid = r.id ";
1064 if ($args['disable_types']) {
1065 list($types, $p) = $DB->get_in_or_equal($args['disable_types'], SQL_PARAMS_NAMED, 'distype', false);
1066 $sql .= " AND r.type $types";
1067 $params = array_merge($params, $p);
1070 if ($args['userid']) {
1071 $sql .= " AND (i.userid = 0 or i.userid = :userid)";
1072 $params['userid'] = $args['userid'];
1075 if ($args['context']) {
1076 list($ctxsql, $p2) = $DB->get_in_or_equal($args['context'], SQL_PARAMS_NAMED, 'ctx');
1077 $sql .= " AND i.contextid $ctxsql";
1078 $params = array_merge($params, $p2);
1081 if ($args['onlyvisible'] == true) {
1082 $sql .= " AND r.visible = 1";
1085 if ($args['type'] !== null) {
1086 $sql .= " AND r.type = :type";
1087 $params['type'] = $args['type'];
1089 $sql .= " ORDER BY r.sortorder, i.name";
1091 if (!$records = $DB->get_records_sql($sql, $params)) {
1092 $records = array();
1095 $repositories = array();
1096 // Sortorder should be unique, which is not true if we use $record->sortorder
1097 // and there are multiple instances of any repository type
1098 $sortorder = 1;
1099 foreach ($records as $record) {
1100 $cache->set('i:'. $record->id, $record);
1101 if (!file_exists($CFG->dirroot . '/repository/'. $record->repositorytype.'/lib.php')) {
1102 continue;
1104 $repository = self::get_repository_by_id($record->id, $current_context);
1105 $repository->options['sortorder'] = $sortorder++;
1107 $is_supported = true;
1109 // check mimetypes
1110 if ($args['accepted_types'] !== '*' and $repository->supported_filetypes() !== '*') {
1111 $accepted_ext = file_get_typegroup('extension', $args['accepted_types']);
1112 $supported_ext = file_get_typegroup('extension', $repository->supported_filetypes());
1113 $valid_ext = array_intersect($accepted_ext, $supported_ext);
1114 $is_supported = !empty($valid_ext);
1116 // Check return values.
1117 if (!empty($args['return_types']) && !($repository->supported_returntypes() & $args['return_types'])) {
1118 $is_supported = false;
1121 if (!$args['onlyvisible'] || ($repository->is_visible() && !$repository->disabled)) {
1122 // check capability in current context
1123 $capability = has_capability('repository/'.$record->repositorytype.':view', $current_context);
1124 if ($record->repositorytype == 'coursefiles') {
1125 // coursefiles plugin needs managefiles permission
1126 $capability = $capability && has_capability('moodle/course:managefiles', $current_context);
1128 if ($is_supported && $capability) {
1129 $repositories[$repository->id] = $repository;
1133 $cache->set($cachekey, new cacheable_object_array($repositories));
1134 return $repositories;
1138 * Get single repository instance for administrative actions
1140 * Do not use this function to access repository contents, because it
1141 * does not set the current context
1143 * @see repository::get_repository_by_id()
1145 * @static
1146 * @param integer $id repository instance id
1147 * @return repository
1149 public static function get_instance($id) {
1150 return self::get_repository_by_id($id, context_system::instance());
1154 * Call a static function. Any additional arguments than plugin and function will be passed through.
1156 * @static
1157 * @param string $plugin repository plugin name
1158 * @param string $function function name
1159 * @return mixed
1161 public static function static_function($plugin, $function) {
1162 global $CFG;
1164 //check that the plugin exists
1165 $typedirectory = $CFG->dirroot . '/repository/'. $plugin . '/lib.php';
1166 if (!file_exists($typedirectory)) {
1167 //throw new repository_exception('invalidplugin', 'repository');
1168 return false;
1171 $args = func_get_args();
1172 if (count($args) <= 2) {
1173 $args = array();
1174 } else {
1175 array_shift($args);
1176 array_shift($args);
1179 require_once($typedirectory);
1180 return call_user_func_array(array('repository_' . $plugin, $function), $args);
1184 * Scan file, throws exception in case of infected file.
1186 * Please note that the scanning engine must be able to access the file,
1187 * permissions of the file are not modified here!
1189 * @static
1190 * @deprecated since Moodle 3.0
1191 * @param string $thefile
1192 * @param string $filename name of the file
1193 * @param bool $deleteinfected
1195 public static function antivir_scan_file($thefile, $filename, $deleteinfected) {
1196 debugging('Please upgrade your code to use \core\antivirus\manager::scan_file instead', DEBUG_DEVELOPER);
1197 \core\antivirus\manager::scan_file($thefile, $filename, $deleteinfected);
1201 * Repository method to serve the referenced file
1203 * @see send_stored_file
1205 * @param stored_file $storedfile the file that contains the reference
1206 * @param int $lifetime Number of seconds before the file should expire from caches (null means $CFG->filelifetime)
1207 * @param int $filter 0 (default)=no filtering, 1=all files, 2=html files only
1208 * @param bool $forcedownload If true (default false), forces download of file rather than view in browser/plugin
1209 * @param array $options additional options affecting the file serving
1211 public function send_file($storedfile, $lifetime=null , $filter=0, $forcedownload=false, array $options = null) {
1212 if ($this->has_moodle_files()) {
1213 $fs = get_file_storage();
1214 $params = file_storage::unpack_reference($storedfile->get_reference(), true);
1215 $srcfile = null;
1216 if (is_array($params)) {
1217 $srcfile = $fs->get_file($params['contextid'], $params['component'], $params['filearea'],
1218 $params['itemid'], $params['filepath'], $params['filename']);
1220 if (empty($options)) {
1221 $options = array();
1223 if (!isset($options['filename'])) {
1224 $options['filename'] = $storedfile->get_filename();
1226 if (!$srcfile) {
1227 send_file_not_found();
1228 } else {
1229 send_stored_file($srcfile, $lifetime, $filter, $forcedownload, $options);
1231 } else {
1232 throw new coding_exception("Repository plugin must implement send_file() method.");
1237 * Return human readable reference information
1239 * @param string $reference value of DB field files_reference.reference
1240 * @param int $filestatus status of the file, 0 - ok, 666 - source missing
1241 * @return string
1243 public function get_reference_details($reference, $filestatus = 0) {
1244 if ($this->has_moodle_files()) {
1245 $fileinfo = null;
1246 $params = file_storage::unpack_reference($reference, true);
1247 if (is_array($params)) {
1248 $context = context::instance_by_id($params['contextid'], IGNORE_MISSING);
1249 if ($context) {
1250 $browser = get_file_browser();
1251 $fileinfo = $browser->get_file_info($context, $params['component'], $params['filearea'], $params['itemid'], $params['filepath'], $params['filename']);
1254 if (empty($fileinfo)) {
1255 if ($filestatus == 666) {
1256 if (is_siteadmin() || ($context && has_capability('moodle/course:managefiles', $context))) {
1257 return get_string('lostsource', 'repository',
1258 $params['contextid']. '/'. $params['component']. '/'. $params['filearea']. '/'. $params['itemid']. $params['filepath']. $params['filename']);
1259 } else {
1260 return get_string('lostsource', 'repository', '');
1263 return get_string('undisclosedsource', 'repository');
1264 } else {
1265 return $fileinfo->get_readable_fullname();
1268 return '';
1272 * Cache file from external repository by reference
1273 * {@link repository::get_file_reference()}
1274 * {@link repository::get_file()}
1275 * Invoked at MOODLE/repository/repository_ajax.php
1277 * @param string $reference this reference is generated by
1278 * repository::get_file_reference()
1279 * @param stored_file $storedfile created file reference
1281 public function cache_file_by_reference($reference, $storedfile) {
1285 * Return the source information
1287 * The result of the function is stored in files.source field. It may be analysed
1288 * when the source file is lost or repository may use it to display human-readable
1289 * location of reference original.
1291 * This method is called when file is picked for the first time only. When file
1292 * (either copy or a reference) is already in moodle and it is being picked
1293 * again to another file area (also as a copy or as a reference), the value of
1294 * files.source is copied.
1296 * @param string $source source of the file, returned by repository as 'source' and received back from user (not cleaned)
1297 * @return string|null
1299 public function get_file_source_info($source) {
1300 if ($this->has_moodle_files()) {
1301 $reference = $this->get_file_reference($source);
1302 return $this->get_reference_details($reference, 0);
1304 return $source;
1308 * Move file from download folder to file pool using FILE API
1310 * @todo MDL-28637
1311 * @static
1312 * @param string $thefile file path in download folder
1313 * @param stdClass $record
1314 * @return array containing the following keys:
1315 * icon
1316 * file
1317 * id
1318 * url
1320 public static function move_to_filepool($thefile, $record) {
1321 global $DB, $CFG, $USER, $OUTPUT;
1323 // scan for viruses if possible, throws exception if problem found
1324 // TODO: MDL-28637 this repository_no_delete is a bloody hack!
1325 \core\antivirus\manager::scan_file($thefile, $record->filename, empty($CFG->repository_no_delete));
1327 $fs = get_file_storage();
1328 // If file name being used.
1329 if (repository::draftfile_exists($record->itemid, $record->filepath, $record->filename)) {
1330 $draftitemid = $record->itemid;
1331 $new_filename = repository::get_unused_filename($draftitemid, $record->filepath, $record->filename);
1332 $old_filename = $record->filename;
1333 // Create a tmp file.
1334 $record->filename = $new_filename;
1335 $newfile = $fs->create_file_from_pathname($record, $thefile);
1336 $event = array();
1337 $event['event'] = 'fileexists';
1338 $event['newfile'] = new stdClass;
1339 $event['newfile']->filepath = $record->filepath;
1340 $event['newfile']->filename = $new_filename;
1341 $event['newfile']->url = moodle_url::make_draftfile_url($draftitemid, $record->filepath, $new_filename)->out();
1343 $event['existingfile'] = new stdClass;
1344 $event['existingfile']->filepath = $record->filepath;
1345 $event['existingfile']->filename = $old_filename;
1346 $event['existingfile']->url = moodle_url::make_draftfile_url($draftitemid, $record->filepath, $old_filename)->out();
1347 return $event;
1349 if ($file = $fs->create_file_from_pathname($record, $thefile)) {
1350 if (empty($CFG->repository_no_delete)) {
1351 $delete = unlink($thefile);
1352 unset($CFG->repository_no_delete);
1354 return array(
1355 'url'=>moodle_url::make_draftfile_url($file->get_itemid(), $file->get_filepath(), $file->get_filename())->out(),
1356 'id'=>$file->get_itemid(),
1357 'file'=>$file->get_filename(),
1358 'icon' => $OUTPUT->pix_url(file_extension_icon($thefile, 32))->out(),
1360 } else {
1361 return null;
1366 * Builds a tree of files This function is then called recursively.
1368 * @static
1369 * @todo take $search into account, and respect a threshold for dynamic loading
1370 * @param file_info $fileinfo an object returned by file_browser::get_file_info()
1371 * @param string $search searched string
1372 * @param bool $dynamicmode no recursive call is done when in dynamic mode
1373 * @param array $list the array containing the files under the passed $fileinfo
1374 * @return int the number of files found
1376 public static function build_tree($fileinfo, $search, $dynamicmode, &$list) {
1377 global $CFG, $OUTPUT;
1379 $filecount = 0;
1380 $children = $fileinfo->get_children();
1382 foreach ($children as $child) {
1383 $filename = $child->get_visible_name();
1384 $filesize = $child->get_filesize();
1385 $filesize = $filesize ? display_size($filesize) : '';
1386 $filedate = $child->get_timemodified();
1387 $filedate = $filedate ? userdate($filedate) : '';
1388 $filetype = $child->get_mimetype();
1390 if ($child->is_directory()) {
1391 $path = array();
1392 $level = $child->get_parent();
1393 while ($level) {
1394 $params = $level->get_params();
1395 $path[] = array($params['filepath'], $level->get_visible_name());
1396 $level = $level->get_parent();
1399 $tmp = array(
1400 'title' => $child->get_visible_name(),
1401 'size' => 0,
1402 'date' => $filedate,
1403 'path' => array_reverse($path),
1404 'thumbnail' => $OUTPUT->pix_url(file_folder_icon(90))->out(false)
1407 //if ($dynamicmode && $child->is_writable()) {
1408 // $tmp['children'] = array();
1409 //} else {
1410 // if folder name matches search, we send back all files contained.
1411 $_search = $search;
1412 if ($search && stristr($tmp['title'], $search) !== false) {
1413 $_search = false;
1415 $tmp['children'] = array();
1416 $_filecount = repository::build_tree($child, $_search, $dynamicmode, $tmp['children']);
1417 if ($search && $_filecount) {
1418 $tmp['expanded'] = 1;
1423 if (!$search || $_filecount || (stristr($tmp['title'], $search) !== false)) {
1424 $filecount += $_filecount;
1425 $list[] = $tmp;
1428 } else { // not a directory
1429 // skip the file, if we're in search mode and it's not a match
1430 if ($search && (stristr($filename, $search) === false)) {
1431 continue;
1433 $params = $child->get_params();
1434 $source = serialize(array($params['contextid'], $params['component'], $params['filearea'], $params['itemid'], $params['filepath'], $params['filename']));
1435 $list[] = array(
1436 'title' => $filename,
1437 'size' => $filesize,
1438 'date' => $filedate,
1439 //'source' => $child->get_url(),
1440 'source' => base64_encode($source),
1441 'icon'=>$OUTPUT->pix_url(file_file_icon($child, 24))->out(false),
1442 'thumbnail'=>$OUTPUT->pix_url(file_file_icon($child, 90))->out(false),
1444 $filecount++;
1448 return $filecount;
1452 * Display a repository instance list (with edit/delete/create links)
1454 * @static
1455 * @param stdClass $context the context for which we display the instance
1456 * @param string $typename if set, we display only one type of instance
1458 public static function display_instances_list($context, $typename = null) {
1459 global $CFG, $USER, $OUTPUT;
1461 $output = $OUTPUT->box_start('generalbox');
1462 //if the context is SYSTEM, so we call it from administration page
1463 $admin = ($context->id == SYSCONTEXTID) ? true : false;
1464 if ($admin) {
1465 $baseurl = new moodle_url('/'.$CFG->admin.'/repositoryinstance.php', array('sesskey'=>sesskey()));
1466 $output .= $OUTPUT->heading(get_string('siteinstances', 'repository'));
1467 } else {
1468 $baseurl = new moodle_url('/repository/manage_instances.php', array('contextid'=>$context->id, 'sesskey'=>sesskey()));
1471 $namestr = get_string('name');
1472 $pluginstr = get_string('plugin', 'repository');
1473 $settingsstr = get_string('settings');
1474 $deletestr = get_string('delete');
1475 // Retrieve list of instances. In administration context we want to display all
1476 // instances of a type, even if this type is not visible. In course/user context we
1477 // want to display only visible instances, but for every type types. The repository::get_instances()
1478 // third parameter displays only visible type.
1479 $params = array();
1480 $params['context'] = array($context);
1481 $params['currentcontext'] = $context;
1482 $params['return_types'] = 0;
1483 $params['onlyvisible'] = !$admin;
1484 $params['type'] = $typename;
1485 $instances = repository::get_instances($params);
1486 $instancesnumber = count($instances);
1487 $alreadyplugins = array();
1489 $table = new html_table();
1490 $table->head = array($namestr, $pluginstr, $settingsstr, $deletestr);
1491 $table->align = array('left', 'left', 'center','center');
1492 $table->data = array();
1494 $updowncount = 1;
1496 foreach ($instances as $i) {
1497 $settings = '';
1498 $delete = '';
1500 $type = repository::get_type_by_id($i->options['typeid']);
1502 if ($type->get_contextvisibility($context)) {
1503 if (!$i->readonly) {
1505 $settingurl = new moodle_url($baseurl);
1506 $settingurl->param('type', $i->options['type']);
1507 $settingurl->param('edit', $i->id);
1508 $settings .= html_writer::link($settingurl, $settingsstr);
1510 $deleteurl = new moodle_url($baseurl);
1511 $deleteurl->param('delete', $i->id);
1512 $deleteurl->param('type', $i->options['type']);
1513 $delete .= html_writer::link($deleteurl, $deletestr);
1517 $type = repository::get_type_by_id($i->options['typeid']);
1518 $table->data[] = array(format_string($i->name), $type->get_readablename(), $settings, $delete);
1520 //display a grey row if the type is defined as not visible
1521 if (isset($type) && !$type->get_visible()) {
1522 $table->rowclasses[] = 'dimmed_text';
1523 } else {
1524 $table->rowclasses[] = '';
1527 if (!in_array($i->name, $alreadyplugins)) {
1528 $alreadyplugins[] = $i->name;
1531 $output .= html_writer::table($table);
1532 $instancehtml = '<div>';
1533 $addable = 0;
1535 //if no type is set, we can create all type of instance
1536 if (!$typename) {
1537 $instancehtml .= '<h3>';
1538 $instancehtml .= get_string('createrepository', 'repository');
1539 $instancehtml .= '</h3><ul>';
1540 $types = repository::get_editable_types($context);
1541 foreach ($types as $type) {
1542 if (!empty($type) && $type->get_visible()) {
1543 // If the user does not have the permission to view the repository, it won't be displayed in
1544 // the list of instances. Hiding the link to create new instances will prevent the
1545 // user from creating them without being able to find them afterwards, which looks like a bug.
1546 if (!has_capability('repository/'.$type->get_typename().':view', $context)) {
1547 continue;
1549 $instanceoptionnames = repository::static_function($type->get_typename(), 'get_instance_option_names');
1550 if (!empty($instanceoptionnames)) {
1551 $baseurl->param('new', $type->get_typename());
1552 $instancehtml .= '<li><a href="'.$baseurl->out().'">'.get_string('createxxinstance', 'repository', get_string('pluginname', 'repository_'.$type->get_typename())). '</a></li>';
1553 $baseurl->remove_params('new');
1554 $addable++;
1558 $instancehtml .= '</ul>';
1560 } else {
1561 $instanceoptionnames = repository::static_function($typename, 'get_instance_option_names');
1562 if (!empty($instanceoptionnames)) { //create a unique type of instance
1563 $addable = 1;
1564 $baseurl->param('new', $typename);
1565 $output .= $OUTPUT->single_button($baseurl, get_string('createinstance', 'repository'), 'get');
1566 $baseurl->remove_params('new');
1570 if ($addable) {
1571 $instancehtml .= '</div>';
1572 $output .= $instancehtml;
1575 $output .= $OUTPUT->box_end();
1577 //print the list + creation links
1578 print($output);
1582 * Prepare file reference information
1584 * @param string $source source of the file, returned by repository as 'source' and received back from user (not cleaned)
1585 * @return string file reference, ready to be stored
1587 public function get_file_reference($source) {
1588 if ($source && $this->has_moodle_files()) {
1589 $params = @json_decode(base64_decode($source), true);
1590 if (!is_array($params) || empty($params['contextid'])) {
1591 throw new repository_exception('invalidparams', 'repository');
1593 $params = array(
1594 'component' => empty($params['component']) ? '' : clean_param($params['component'], PARAM_COMPONENT),
1595 'filearea' => empty($params['filearea']) ? '' : clean_param($params['filearea'], PARAM_AREA),
1596 'itemid' => empty($params['itemid']) ? 0 : clean_param($params['itemid'], PARAM_INT),
1597 'filename' => empty($params['filename']) ? null : clean_param($params['filename'], PARAM_FILE),
1598 'filepath' => empty($params['filepath']) ? null : clean_param($params['filepath'], PARAM_PATH),
1599 'contextid' => clean_param($params['contextid'], PARAM_INT)
1601 // Check if context exists.
1602 if (!context::instance_by_id($params['contextid'], IGNORE_MISSING)) {
1603 throw new repository_exception('invalidparams', 'repository');
1605 return file_storage::pack_reference($params);
1607 return $source;
1611 * Get a unique file path in which to save the file.
1613 * The filename returned will be removed at the end of the request and
1614 * should not be relied upon to exist in subsequent requests.
1616 * @param string $filename file name
1617 * @return file path
1619 public function prepare_file($filename) {
1620 if (empty($filename)) {
1621 $filename = 'file';
1623 return sprintf('%s/%s', make_request_directory(), $filename);
1627 * Does this repository used to browse moodle files?
1629 * @return bool
1631 public function has_moodle_files() {
1632 return false;
1636 * Return file URL, for most plugins, the parameter is the original
1637 * url, but some plugins use a file id, so we need this function to
1638 * convert file id to original url.
1640 * @param string $url the url of file
1641 * @return string
1643 public function get_link($url) {
1644 return $url;
1648 * Downloads a file from external repository and saves it in temp dir
1650 * Function get_file() must be implemented by repositories that support returntypes
1651 * FILE_INTERNAL or FILE_REFERENCE. It is invoked to pick up the file and copy it
1652 * to moodle. This function is not called for moodle repositories, the function
1653 * {@link repository::copy_to_area()} is used instead.
1655 * This function can be overridden by subclass if the files.reference field contains
1656 * not just URL or if request should be done differently.
1658 * @see curl
1659 * @throws file_exception when error occured
1661 * @param string $url the content of files.reference field, in this implementaion
1662 * it is asssumed that it contains the string with URL of the file
1663 * @param string $filename filename (without path) to save the downloaded file in the
1664 * temporary directory, if omitted or file already exists the new filename will be generated
1665 * @return array with elements:
1666 * path: internal location of the file
1667 * url: URL to the source (from parameters)
1669 public function get_file($url, $filename = '') {
1670 global $CFG;
1672 $path = $this->prepare_file($filename);
1673 $c = new curl;
1675 $result = $c->download_one($url, null, array('filepath' => $path, 'timeout' => $CFG->repositorygetfiletimeout));
1676 if ($result !== true) {
1677 throw new moodle_exception('errorwhiledownload', 'repository', '', $result);
1679 return array('path'=>$path, 'url'=>$url);
1683 * Downloads the file from external repository and saves it in moodle filepool.
1684 * This function is different from {@link repository::sync_reference()} because it has
1685 * bigger request timeout and always downloads the content.
1687 * This function is invoked when we try to unlink the file from the source and convert
1688 * a reference into a true copy.
1690 * @throws exception when file could not be imported
1692 * @param stored_file $file
1693 * @param int $maxbytes throw an exception if file size is bigger than $maxbytes (0 means no limit)
1695 public function import_external_file_contents(stored_file $file, $maxbytes = 0) {
1696 if (!$file->is_external_file()) {
1697 // nothing to import if the file is not a reference
1698 return;
1699 } else if ($file->get_repository_id() != $this->id) {
1700 // error
1701 debugging('Repository instance id does not match');
1702 return;
1703 } else if ($this->has_moodle_files()) {
1704 // files that are references to local files are already in moodle filepool
1705 // just validate the size
1706 if ($maxbytes > 0 && $file->get_filesize() > $maxbytes) {
1707 $maxbytesdisplay = display_size($maxbytes);
1708 throw new file_exception('maxbytesfile', (object) array('file' => $file->get_filename(),
1709 'size' => $maxbytesdisplay));
1711 return;
1712 } else {
1713 if ($maxbytes > 0 && $file->get_filesize() > $maxbytes) {
1714 // note that stored_file::get_filesize() also calls synchronisation
1715 $maxbytesdisplay = display_size($maxbytes);
1716 throw new file_exception('maxbytesfile', (object) array('file' => $file->get_filename(),
1717 'size' => $maxbytesdisplay));
1719 $fs = get_file_storage();
1720 $contentexists = $fs->content_exists($file->get_contenthash());
1721 if ($contentexists && $file->get_filesize() && $file->get_contenthash() === sha1('')) {
1722 // even when 'file_storage::content_exists()' returns true this may be an empty
1723 // content for the file that was not actually downloaded
1724 $contentexists = false;
1726 if (!$file->get_status() && $contentexists) {
1727 // we already have the content in moodle filepool and it was synchronised recently.
1728 // Repositories may overwrite it if they want to force synchronisation anyway!
1729 return;
1730 } else {
1731 // attempt to get a file
1732 try {
1733 $fileinfo = $this->get_file($file->get_reference());
1734 if (isset($fileinfo['path'])) {
1735 list($contenthash, $filesize, $newfile) = $fs->add_file_to_pool($fileinfo['path']);
1736 // set this file and other similar aliases synchronised
1737 $file->set_synchronized($contenthash, $filesize);
1738 } else {
1739 throw new moodle_exception('errorwhiledownload', 'repository', '', '');
1741 } catch (Exception $e) {
1742 if ($contentexists) {
1743 // better something than nothing. We have a copy of file. It's sync time
1744 // has expired but it is still very likely that it is the last version
1745 } else {
1746 throw($e);
1754 * Return size of a file in bytes.
1756 * @param string $source encoded and serialized data of file
1757 * @return int file size in bytes
1759 public function get_file_size($source) {
1760 // TODO MDL-33297 remove this function completely?
1761 $browser = get_file_browser();
1762 $params = unserialize(base64_decode($source));
1763 $contextid = clean_param($params['contextid'], PARAM_INT);
1764 $fileitemid = clean_param($params['itemid'], PARAM_INT);
1765 $filename = clean_param($params['filename'], PARAM_FILE);
1766 $filepath = clean_param($params['filepath'], PARAM_PATH);
1767 $filearea = clean_param($params['filearea'], PARAM_AREA);
1768 $component = clean_param($params['component'], PARAM_COMPONENT);
1769 $context = context::instance_by_id($contextid);
1770 $file_info = $browser->get_file_info($context, $component, $filearea, $fileitemid, $filepath, $filename);
1771 if (!empty($file_info)) {
1772 $filesize = $file_info->get_filesize();
1773 } else {
1774 $filesize = null;
1776 return $filesize;
1780 * Return is the instance is visible
1781 * (is the type visible ? is the context enable ?)
1783 * @return bool
1785 public function is_visible() {
1786 $type = repository::get_type_by_id($this->options['typeid']);
1787 $instanceoptions = repository::static_function($type->get_typename(), 'get_instance_option_names');
1789 if ($type->get_visible()) {
1790 //if the instance is unique so it's visible, otherwise check if the instance has a enabled context
1791 if (empty($instanceoptions) || $type->get_contextvisibility(context::instance_by_id($this->instance->contextid))) {
1792 return true;
1796 return false;
1800 * Can the instance be edited by the current user?
1802 * The property $readonly must not be used within this method because
1803 * it only controls if the options from self::get_instance_option_names()
1804 * can be edited.
1806 * @return bool true if the user can edit the instance.
1807 * @since Moodle 2.5
1809 public final function can_be_edited_by_user() {
1810 global $USER;
1812 // We need to be able to explore the repository.
1813 try {
1814 $this->check_capability();
1815 } catch (repository_exception $e) {
1816 return false;
1819 $repocontext = context::instance_by_id($this->instance->contextid);
1820 if ($repocontext->contextlevel == CONTEXT_USER && $repocontext->instanceid != $USER->id) {
1821 // If the context of this instance is a user context, we need to be this user.
1822 return false;
1823 } else if ($repocontext->contextlevel == CONTEXT_MODULE && !has_capability('moodle/course:update', $repocontext)) {
1824 // We need to have permissions on the course to edit the instance.
1825 return false;
1826 } else if ($repocontext->contextlevel == CONTEXT_SYSTEM && !has_capability('moodle/site:config', $repocontext)) {
1827 // Do not meet the requirements for the context system.
1828 return false;
1831 return true;
1835 * Return the name of this instance, can be overridden.
1837 * @return string
1839 public function get_name() {
1840 if ($name = $this->instance->name) {
1841 return $name;
1842 } else {
1843 return get_string('pluginname', 'repository_' . $this->get_typename());
1848 * Is this repository accessing private data?
1850 * This function should return true for the repositories which access external private
1851 * data from a user. This is the case for repositories such as Dropbox, Google Docs or Box.net
1852 * which authenticate the user and then store the auth token.
1854 * Of course, many repositories store 'private data', but we only want to set
1855 * contains_private_data() to repositories which are external to Moodle and shouldn't be accessed
1856 * to by the users having the capability to 'login as' someone else. For instance, the repository
1857 * 'Private files' is not considered as private because it's part of Moodle.
1859 * You should not set contains_private_data() to true on repositories which allow different types
1860 * of instances as the levels other than 'user' are, by definition, not private. Also
1861 * the user instances will be protected when they need to.
1863 * @return boolean True when the repository accesses private external data.
1864 * @since Moodle 2.5
1866 public function contains_private_data() {
1867 return true;
1871 * What kind of files will be in this repository?
1873 * @return array return '*' means this repository support any files, otherwise
1874 * return mimetypes of files, it can be an array
1876 public function supported_filetypes() {
1877 // return array('text/plain', 'image/gif');
1878 return '*';
1882 * Tells how the file can be picked from this repository
1884 * Maximum value is FILE_INTERNAL | FILE_EXTERNAL | FILE_REFERENCE
1886 * @return int
1888 public function supported_returntypes() {
1889 return (FILE_INTERNAL | FILE_EXTERNAL);
1893 * Provide repository instance information for Ajax
1895 * @return stdClass
1897 final public function get_meta() {
1898 global $CFG, $OUTPUT;
1899 $meta = new stdClass();
1900 $meta->id = $this->id;
1901 $meta->name = format_string($this->get_name());
1902 $meta->type = $this->get_typename();
1903 $meta->icon = $OUTPUT->pix_url('icon', 'repository_'.$meta->type)->out(false);
1904 $meta->supported_types = file_get_typegroup('extension', $this->supported_filetypes());
1905 $meta->return_types = $this->supported_returntypes();
1906 $meta->sortorder = $this->options['sortorder'];
1907 return $meta;
1911 * Create an instance for this plug-in
1913 * @static
1914 * @param string $type the type of the repository
1915 * @param int $userid the user id
1916 * @param stdClass $context the context
1917 * @param array $params the options for this instance
1918 * @param int $readonly whether to create it readonly or not (defaults to not)
1919 * @return mixed
1921 public static function create($type, $userid, $context, $params, $readonly=0) {
1922 global $CFG, $DB;
1923 $params = (array)$params;
1924 require_once($CFG->dirroot . '/repository/'. $type . '/lib.php');
1925 $classname = 'repository_' . $type;
1926 if ($repo = $DB->get_record('repository', array('type'=>$type))) {
1927 $record = new stdClass();
1928 $record->name = $params['name'];
1929 $record->typeid = $repo->id;
1930 $record->timecreated = time();
1931 $record->timemodified = time();
1932 $record->contextid = $context->id;
1933 $record->readonly = $readonly;
1934 $record->userid = $userid;
1935 $id = $DB->insert_record('repository_instances', $record);
1936 cache::make('core', 'repositories')->purge();
1937 $options = array();
1938 $configs = call_user_func($classname . '::get_instance_option_names');
1939 if (!empty($configs)) {
1940 foreach ($configs as $config) {
1941 if (isset($params[$config])) {
1942 $options[$config] = $params[$config];
1943 } else {
1944 $options[$config] = null;
1949 if (!empty($id)) {
1950 unset($options['name']);
1951 $instance = repository::get_instance($id);
1952 $instance->set_option($options);
1953 return $id;
1954 } else {
1955 return null;
1957 } else {
1958 return null;
1963 * delete a repository instance
1965 * @param bool $downloadcontents
1966 * @return bool
1968 final public function delete($downloadcontents = false) {
1969 global $DB;
1970 if ($downloadcontents) {
1971 $this->convert_references_to_local();
1973 cache::make('core', 'repositories')->purge();
1974 try {
1975 $DB->delete_records('repository_instances', array('id'=>$this->id));
1976 $DB->delete_records('repository_instance_config', array('instanceid'=>$this->id));
1977 } catch (dml_exception $ex) {
1978 return false;
1980 return true;
1984 * Delete all the instances associated to a context.
1986 * This method is intended to be a callback when deleting
1987 * a course or a user to delete all the instances associated
1988 * to their context. The usual way to delete a single instance
1989 * is to use {@link self::delete()}.
1991 * @param int $contextid context ID.
1992 * @param boolean $downloadcontents true to convert references to hard copies.
1993 * @return void
1995 final public static function delete_all_for_context($contextid, $downloadcontents = true) {
1996 global $DB;
1997 $repoids = $DB->get_fieldset_select('repository_instances', 'id', 'contextid = :contextid', array('contextid' => $contextid));
1998 if ($downloadcontents) {
1999 foreach ($repoids as $repoid) {
2000 $repo = repository::get_repository_by_id($repoid, $contextid);
2001 $repo->convert_references_to_local();
2004 cache::make('core', 'repositories')->purge();
2005 $DB->delete_records_list('repository_instances', 'id', $repoids);
2006 $DB->delete_records_list('repository_instance_config', 'instanceid', $repoids);
2010 * Hide/Show a repository
2012 * @param string $hide
2013 * @return bool
2015 final public function hide($hide = 'toggle') {
2016 global $DB;
2017 if ($entry = $DB->get_record('repository', array('id'=>$this->id))) {
2018 if ($hide === 'toggle' ) {
2019 if (!empty($entry->visible)) {
2020 $entry->visible = 0;
2021 } else {
2022 $entry->visible = 1;
2024 } else {
2025 if (!empty($hide)) {
2026 $entry->visible = 0;
2027 } else {
2028 $entry->visible = 1;
2031 return $DB->update_record('repository', $entry);
2033 return false;
2037 * Save settings for repository instance
2038 * $repo->set_option(array('api_key'=>'f2188bde132', 'name'=>'dongsheng'));
2040 * @param array $options settings
2041 * @return bool
2043 public function set_option($options = array()) {
2044 global $DB;
2046 if (!empty($options['name'])) {
2047 $r = new stdClass();
2048 $r->id = $this->id;
2049 $r->name = $options['name'];
2050 $DB->update_record('repository_instances', $r);
2051 unset($options['name']);
2053 foreach ($options as $name=>$value) {
2054 if ($id = $DB->get_field('repository_instance_config', 'id', array('name'=>$name, 'instanceid'=>$this->id))) {
2055 $DB->set_field('repository_instance_config', 'value', $value, array('id'=>$id));
2056 } else {
2057 $config = new stdClass();
2058 $config->instanceid = $this->id;
2059 $config->name = $name;
2060 $config->value = $value;
2061 $DB->insert_record('repository_instance_config', $config);
2064 cache::make('core', 'repositories')->purge();
2065 return true;
2069 * Get settings for repository instance.
2071 * @param string $config a specific option to get.
2072 * @return mixed returns an array of options. If $config is not empty, then it returns that option,
2073 * or null if the option does not exist.
2075 public function get_option($config = '') {
2076 global $DB;
2077 $cache = cache::make('core', 'repositories');
2078 if (($entries = $cache->get('ops:'. $this->id)) === false) {
2079 $entries = $DB->get_records('repository_instance_config', array('instanceid' => $this->id));
2080 $cache->set('ops:'. $this->id, $entries);
2083 $ret = array();
2084 foreach($entries as $entry) {
2085 $ret[$entry->name] = $entry->value;
2088 if (!empty($config)) {
2089 if (isset($ret[$config])) {
2090 return $ret[$config];
2091 } else {
2092 return null;
2094 } else {
2095 return $ret;
2100 * Filter file listing to display specific types
2102 * @param array $value
2103 * @return bool
2105 public function filter(&$value) {
2106 $accepted_types = optional_param_array('accepted_types', '', PARAM_RAW);
2107 if (isset($value['children'])) {
2108 if (!empty($value['children'])) {
2109 $value['children'] = array_filter($value['children'], array($this, 'filter'));
2111 return true; // always return directories
2112 } else {
2113 if ($accepted_types == '*' or empty($accepted_types)
2114 or (is_array($accepted_types) and in_array('*', $accepted_types))) {
2115 return true;
2116 } else {
2117 foreach ($accepted_types as $ext) {
2118 if (preg_match('#'.$ext.'$#i', $value['title'])) {
2119 return true;
2124 return false;
2128 * Given a path, and perhaps a search, get a list of files.
2130 * See details on {@link http://docs.moodle.org/dev/Repository_plugins}
2132 * @param string $path this parameter can a folder name, or a identification of folder
2133 * @param string $page the page number of file list
2134 * @return array the list of files, including meta infomation, containing the following keys
2135 * manage, url to manage url
2136 * client_id
2137 * login, login form
2138 * repo_id, active repository id
2139 * login_btn_action, the login button action
2140 * login_btn_label, the login button label
2141 * total, number of results
2142 * perpage, items per page
2143 * page
2144 * pages, total pages
2145 * issearchresult, is it a search result?
2146 * list, file list
2147 * path, current path and parent path
2149 public function get_listing($path = '', $page = '') {
2154 * Prepare the breadcrumb.
2156 * @param array $breadcrumb contains each element of the breadcrumb.
2157 * @return array of breadcrumb elements.
2158 * @since Moodle 2.3.3
2160 protected static function prepare_breadcrumb($breadcrumb) {
2161 global $OUTPUT;
2162 $foldericon = $OUTPUT->pix_url(file_folder_icon(24))->out(false);
2163 $len = count($breadcrumb);
2164 for ($i = 0; $i < $len; $i++) {
2165 if (is_array($breadcrumb[$i]) && !isset($breadcrumb[$i]['icon'])) {
2166 $breadcrumb[$i]['icon'] = $foldericon;
2167 } else if (is_object($breadcrumb[$i]) && !isset($breadcrumb[$i]->icon)) {
2168 $breadcrumb[$i]->icon = $foldericon;
2171 return $breadcrumb;
2175 * Prepare the file/folder listing.
2177 * @param array $list of files and folders.
2178 * @return array of files and folders.
2179 * @since Moodle 2.3.3
2181 protected static function prepare_list($list) {
2182 global $OUTPUT;
2183 $foldericon = $OUTPUT->pix_url(file_folder_icon(24))->out(false);
2185 // Reset the array keys because non-numeric keys will create an object when converted to JSON.
2186 $list = array_values($list);
2188 $len = count($list);
2189 for ($i = 0; $i < $len; $i++) {
2190 if (is_object($list[$i])) {
2191 $file = (array)$list[$i];
2192 $converttoobject = true;
2193 } else {
2194 $file =& $list[$i];
2195 $converttoobject = false;
2197 if (isset($file['size'])) {
2198 $file['size'] = (int)$file['size'];
2199 $file['size_f'] = display_size($file['size']);
2201 if (isset($file['license']) && get_string_manager()->string_exists($file['license'], 'license')) {
2202 $file['license_f'] = get_string($file['license'], 'license');
2204 if (isset($file['image_width']) && isset($file['image_height'])) {
2205 $a = array('width' => $file['image_width'], 'height' => $file['image_height']);
2206 $file['dimensions'] = get_string('imagesize', 'repository', (object)$a);
2208 foreach (array('date', 'datemodified', 'datecreated') as $key) {
2209 if (!isset($file[$key]) && isset($file['date'])) {
2210 $file[$key] = $file['date'];
2212 if (isset($file[$key])) {
2213 // must be UNIX timestamp
2214 $file[$key] = (int)$file[$key];
2215 if (!$file[$key]) {
2216 unset($file[$key]);
2217 } else {
2218 $file[$key.'_f'] = userdate($file[$key], get_string('strftimedatetime', 'langconfig'));
2219 $file[$key.'_f_s'] = userdate($file[$key], get_string('strftimedatetimeshort', 'langconfig'));
2223 $isfolder = (array_key_exists('children', $file) || (isset($file['type']) && $file['type'] == 'folder'));
2224 $filename = null;
2225 if (isset($file['title'])) {
2226 $filename = $file['title'];
2228 else if (isset($file['fullname'])) {
2229 $filename = $file['fullname'];
2231 if (!isset($file['mimetype']) && !$isfolder && $filename) {
2232 $file['mimetype'] = get_mimetype_description(array('filename' => $filename));
2234 if (!isset($file['icon'])) {
2235 if ($isfolder) {
2236 $file['icon'] = $foldericon;
2237 } else if ($filename) {
2238 $file['icon'] = $OUTPUT->pix_url(file_extension_icon($filename, 24))->out(false);
2242 // Recursively loop over children.
2243 if (isset($file['children'])) {
2244 $file['children'] = self::prepare_list($file['children']);
2247 // Convert the array back to an object.
2248 if ($converttoobject) {
2249 $list[$i] = (object)$file;
2252 return $list;
2256 * Prepares list of files before passing it to AJAX, makes sure data is in the correct
2257 * format and stores formatted values.
2259 * @param array|stdClass $listing result of get_listing() or search() or file_get_drafarea_files()
2260 * @return array
2262 public static function prepare_listing($listing) {
2263 $wasobject = false;
2264 if (is_object($listing)) {
2265 $listing = (array) $listing;
2266 $wasobject = true;
2269 // Prepare the breadcrumb, passed as 'path'.
2270 if (isset($listing['path']) && is_array($listing['path'])) {
2271 $listing['path'] = self::prepare_breadcrumb($listing['path']);
2274 // Prepare the listing of objects.
2275 if (isset($listing['list']) && is_array($listing['list'])) {
2276 $listing['list'] = self::prepare_list($listing['list']);
2279 // Convert back to an object.
2280 if ($wasobject) {
2281 $listing = (object) $listing;
2283 return $listing;
2287 * Search files in repository
2288 * When doing global search, $search_text will be used as
2289 * keyword.
2291 * @param string $search_text search key word
2292 * @param int $page page
2293 * @return mixed see {@link repository::get_listing()}
2295 public function search($search_text, $page = 0) {
2296 $list = array();
2297 $list['list'] = array();
2298 return false;
2302 * Logout from repository instance
2303 * By default, this function will return a login form
2305 * @return string
2307 public function logout(){
2308 return $this->print_login();
2312 * To check whether the user is logged in.
2314 * @return bool
2316 public function check_login(){
2317 return true;
2322 * Show the login screen, if required
2324 * @return string
2326 public function print_login(){
2327 return $this->get_listing();
2331 * Show the search screen, if required
2333 * @return string
2335 public function print_search() {
2336 global $PAGE;
2337 $renderer = $PAGE->get_renderer('core', 'files');
2338 return $renderer->repository_default_searchform();
2342 * For oauth like external authentication, when external repository direct user back to moodle,
2343 * this function will be called to set up token and token_secret
2345 public function callback() {
2349 * is it possible to do glboal search?
2351 * @return bool
2353 public function global_search() {
2354 return false;
2358 * Defines operations that happen occasionally on cron
2360 * @return bool
2362 public function cron() {
2363 return true;
2367 * function which is run when the type is created (moodle administrator add the plugin)
2369 * @return bool success or fail?
2371 public static function plugin_init() {
2372 return true;
2376 * Edit/Create Admin Settings Moodle form
2378 * @param moodleform $mform Moodle form (passed by reference)
2379 * @param string $classname repository class name
2381 public static function type_config_form($mform, $classname = 'repository') {
2382 $instnaceoptions = call_user_func(array($classname, 'get_instance_option_names'), $mform, $classname);
2383 if (empty($instnaceoptions)) {
2384 // this plugin has only one instance
2385 // so we need to give it a name
2386 // it can be empty, then moodle will look for instance name from language string
2387 $mform->addElement('text', 'pluginname', get_string('pluginname', 'repository'), array('size' => '40'));
2388 $mform->addElement('static', 'pluginnamehelp', '', get_string('pluginnamehelp', 'repository'));
2389 $mform->setType('pluginname', PARAM_TEXT);
2394 * Validate Admin Settings Moodle form
2396 * @static
2397 * @param moodleform $mform Moodle form (passed by reference)
2398 * @param array $data array of ("fieldname"=>value) of submitted data
2399 * @param array $errors array of ("fieldname"=>errormessage) of errors
2400 * @return array array of errors
2402 public static function type_form_validation($mform, $data, $errors) {
2403 return $errors;
2408 * Edit/Create Instance Settings Moodle form
2410 * @param moodleform $mform Moodle form (passed by reference)
2412 public static function instance_config_form($mform) {
2416 * Return names of the general options.
2417 * By default: no general option name
2419 * @return array
2421 public static function get_type_option_names() {
2422 return array('pluginname');
2426 * Return names of the instance options.
2427 * By default: no instance option name
2429 * @return array
2431 public static function get_instance_option_names() {
2432 return array();
2436 * Validate repository plugin instance form
2438 * @param moodleform $mform moodle form
2439 * @param array $data form data
2440 * @param array $errors errors
2441 * @return array errors
2443 public static function instance_form_validation($mform, $data, $errors) {
2444 return $errors;
2448 * Create a shorten filename
2450 * @param string $str filename
2451 * @param int $maxlength max file name length
2452 * @return string short filename
2454 public function get_short_filename($str, $maxlength) {
2455 if (core_text::strlen($str) >= $maxlength) {
2456 return trim(core_text::substr($str, 0, $maxlength)).'...';
2457 } else {
2458 return $str;
2463 * Overwrite an existing file
2465 * @param int $itemid
2466 * @param string $filepath
2467 * @param string $filename
2468 * @param string $newfilepath
2469 * @param string $newfilename
2470 * @return bool
2472 public static function overwrite_existing_draftfile($itemid, $filepath, $filename, $newfilepath, $newfilename) {
2473 global $USER;
2474 $fs = get_file_storage();
2475 $user_context = context_user::instance($USER->id);
2476 if ($file = $fs->get_file($user_context->id, 'user', 'draft', $itemid, $filepath, $filename)) {
2477 if ($tempfile = $fs->get_file($user_context->id, 'user', 'draft', $itemid, $newfilepath, $newfilename)) {
2478 // Remember original file source field.
2479 $source = @unserialize($file->get_source());
2480 // Remember the original sortorder.
2481 $sortorder = $file->get_sortorder();
2482 if ($tempfile->is_external_file()) {
2483 // New file is a reference. Check that existing file does not have any other files referencing to it
2484 if (isset($source->original) && $fs->search_references_count($source->original)) {
2485 return (object)array('error' => get_string('errordoublereference', 'repository'));
2488 // delete existing file to release filename
2489 $file->delete();
2490 // create new file
2491 $newfile = $fs->create_file_from_storedfile(array('filepath'=>$filepath, 'filename'=>$filename), $tempfile);
2492 // Preserve original file location (stored in source field) for handling references
2493 if (isset($source->original)) {
2494 if (!($newfilesource = @unserialize($newfile->get_source()))) {
2495 $newfilesource = new stdClass();
2497 $newfilesource->original = $source->original;
2498 $newfile->set_source(serialize($newfilesource));
2500 $newfile->set_sortorder($sortorder);
2501 // remove temp file
2502 $tempfile->delete();
2503 return true;
2506 return false;
2510 * Updates a file in draft filearea.
2512 * This function can only update fields filepath, filename, author, license.
2513 * If anything (except filepath) is updated, timemodified is set to current time.
2514 * If filename or filepath is updated the file unconnects from it's origin
2515 * and therefore all references to it will be converted to copies when
2516 * filearea is saved.
2518 * @param int $draftid
2519 * @param string $filepath path to the directory containing the file, or full path in case of directory
2520 * @param string $filename name of the file, or '.' in case of directory
2521 * @param array $updatedata array of fields to change (only filename, filepath, license and/or author can be updated)
2522 * @throws moodle_exception if for any reason file can not be updated (file does not exist, target already exists, etc.)
2524 public static function update_draftfile($draftid, $filepath, $filename, $updatedata) {
2525 global $USER;
2526 $fs = get_file_storage();
2527 $usercontext = context_user::instance($USER->id);
2528 // make sure filename and filepath are present in $updatedata
2529 $updatedata = $updatedata + array('filepath' => $filepath, 'filename' => $filename);
2530 $filemodified = false;
2531 if (!$file = $fs->get_file($usercontext->id, 'user', 'draft', $draftid, $filepath, $filename)) {
2532 if ($filename === '.') {
2533 throw new moodle_exception('foldernotfound', 'repository');
2534 } else {
2535 throw new moodle_exception('filenotfound', 'error');
2538 if (!$file->is_directory()) {
2539 // This is a file
2540 if ($updatedata['filepath'] !== $filepath || $updatedata['filename'] !== $filename) {
2541 // Rename/move file: check that target file name does not exist.
2542 if ($fs->file_exists($usercontext->id, 'user', 'draft', $draftid, $updatedata['filepath'], $updatedata['filename'])) {
2543 throw new moodle_exception('fileexists', 'repository');
2545 if (($filesource = @unserialize($file->get_source())) && isset($filesource->original)) {
2546 unset($filesource->original);
2547 $file->set_source(serialize($filesource));
2549 $file->rename($updatedata['filepath'], $updatedata['filename']);
2550 // timemodified is updated only when file is renamed and not updated when file is moved.
2551 $filemodified = $filemodified || ($updatedata['filename'] !== $filename);
2553 if (array_key_exists('license', $updatedata) && $updatedata['license'] !== $file->get_license()) {
2554 // Update license and timemodified.
2555 $file->set_license($updatedata['license']);
2556 $filemodified = true;
2558 if (array_key_exists('author', $updatedata) && $updatedata['author'] !== $file->get_author()) {
2559 // Update author and timemodified.
2560 $file->set_author($updatedata['author']);
2561 $filemodified = true;
2563 // Update timemodified:
2564 if ($filemodified) {
2565 $file->set_timemodified(time());
2567 } else {
2568 // This is a directory - only filepath can be updated for a directory (it was moved).
2569 if ($updatedata['filepath'] === $filepath) {
2570 // nothing to update
2571 return;
2573 if ($fs->file_exists($usercontext->id, 'user', 'draft', $draftid, $updatedata['filepath'], '.')) {
2574 // bad luck, we can not rename if something already exists there
2575 throw new moodle_exception('folderexists', 'repository');
2577 $xfilepath = preg_quote($filepath, '|');
2578 if (preg_match("|^$xfilepath|", $updatedata['filepath'])) {
2579 // we can not move folder to it's own subfolder
2580 throw new moodle_exception('folderrecurse', 'repository');
2583 // If directory changed the name, update timemodified.
2584 $filemodified = (basename(rtrim($file->get_filepath(), '/')) !== basename(rtrim($updatedata['filepath'], '/')));
2586 // Now update directory and all children.
2587 $files = $fs->get_area_files($usercontext->id, 'user', 'draft', $draftid);
2588 foreach ($files as $f) {
2589 if (preg_match("|^$xfilepath|", $f->get_filepath())) {
2590 $path = preg_replace("|^$xfilepath|", $updatedata['filepath'], $f->get_filepath());
2591 if (($filesource = @unserialize($f->get_source())) && isset($filesource->original)) {
2592 // unset original so the references are not shown any more
2593 unset($filesource->original);
2594 $f->set_source(serialize($filesource));
2596 $f->rename($path, $f->get_filename());
2597 if ($filemodified && $f->get_filepath() === $updatedata['filepath'] && $f->get_filename() === $filename) {
2598 $f->set_timemodified(time());
2606 * Delete a temp file from draft area
2608 * @param int $draftitemid
2609 * @param string $filepath
2610 * @param string $filename
2611 * @return bool
2613 public static function delete_tempfile_from_draft($draftitemid, $filepath, $filename) {
2614 global $USER;
2615 $fs = get_file_storage();
2616 $user_context = context_user::instance($USER->id);
2617 if ($file = $fs->get_file($user_context->id, 'user', 'draft', $draftitemid, $filepath, $filename)) {
2618 $file->delete();
2619 return true;
2620 } else {
2621 return false;
2626 * Find all external files in this repo and import them
2628 public function convert_references_to_local() {
2629 $fs = get_file_storage();
2630 $files = $fs->get_external_files($this->id);
2631 foreach ($files as $storedfile) {
2632 $fs->import_external_file($storedfile);
2637 * Function repository::reset_caches() is deprecated, cache is handled by MUC now.
2638 * @deprecated since Moodle 2.6 MDL-42016 - please do not use this function any more.
2640 public static function reset_caches() {
2641 throw new coding_exception('Function repository::reset_caches() can not be used any more, cache is handled by MUC now.');
2645 * Function repository::sync_external_file() is deprecated. Use repository::sync_reference instead
2647 * @deprecated since Moodle 2.6 MDL-42016 - please do not use this function any more.
2648 * @see repository::sync_reference()
2650 public static function sync_external_file($file, $resetsynchistory = false) {
2651 throw new coding_exception('Function repository::sync_external_file() can not be used any more. ' .
2652 'Use repository::sync_reference instead.');
2656 * Performs synchronisation of an external file if the previous one has expired.
2658 * This function must be implemented for external repositories supporting
2659 * FILE_REFERENCE, it is called for existing aliases when their filesize,
2660 * contenthash or timemodified are requested. It is not called for internal
2661 * repositories (see {@link repository::has_moodle_files()}), references to
2662 * internal files are updated immediately when source is modified.
2664 * Referenced files may optionally keep their content in Moodle filepool (for
2665 * thumbnail generation or to be able to serve cached copy). In this
2666 * case both contenthash and filesize need to be synchronized. Otherwise repositories
2667 * should use contenthash of empty file and correct filesize in bytes.
2669 * Note that this function may be run for EACH file that needs to be synchronised at the
2670 * moment. If anything is being downloaded or requested from external sources there
2671 * should be a small timeout. The synchronisation is performed to update the size of
2672 * the file and/or to update image and re-generated image preview. There is nothing
2673 * fatal if syncronisation fails but it is fatal if syncronisation takes too long
2674 * and hangs the script generating a page.
2676 * Note: If you wish to call $file->get_filesize(), $file->get_contenthash() or
2677 * $file->get_timemodified() make sure that recursion does not happen.
2679 * Called from {@link stored_file::sync_external_file()}
2681 * @uses stored_file::set_missingsource()
2682 * @uses stored_file::set_synchronized()
2683 * @param stored_file $file
2684 * @return bool false when file does not need synchronisation, true if it was synchronised
2686 public function sync_reference(stored_file $file) {
2687 if ($file->get_repository_id() != $this->id) {
2688 // This should not really happen because the function can be called from stored_file only.
2689 return false;
2692 if ($this->has_moodle_files()) {
2693 // References to local files need to be synchronised only once.
2694 // Later they will be synchronised automatically when the source is changed.
2695 if ($file->get_referencelastsync()) {
2696 return false;
2698 $fs = get_file_storage();
2699 $params = file_storage::unpack_reference($file->get_reference(), true);
2700 if (!is_array($params) || !($storedfile = $fs->get_file($params['contextid'],
2701 $params['component'], $params['filearea'], $params['itemid'], $params['filepath'],
2702 $params['filename']))) {
2703 $file->set_missingsource();
2704 } else {
2705 $file->set_synchronized($storedfile->get_contenthash(), $storedfile->get_filesize(), 0, $storedfile->get_timemodified());
2707 return true;
2710 return false;
2714 * Build draft file's source field
2716 * {@link file_restore_source_field_from_draft_file()}
2717 * XXX: This is a hack for file manager (MDL-28666)
2718 * For newly created draft files we have to construct
2719 * source filed in php serialized data format.
2720 * File manager needs to know the original file information before copying
2721 * to draft area, so we append these information in mdl_files.source field
2723 * @param string $source
2724 * @return string serialised source field
2726 public static function build_source_field($source) {
2727 $sourcefield = new stdClass;
2728 $sourcefield->source = $source;
2729 return serialize($sourcefield);
2733 * Prepares the repository to be cached. Implements method from cacheable_object interface.
2735 * @return array
2737 public function prepare_to_cache() {
2738 return array(
2739 'class' => get_class($this),
2740 'id' => $this->id,
2741 'ctxid' => $this->context->id,
2742 'options' => $this->options,
2743 'readonly' => $this->readonly
2748 * Restores the repository from cache. Implements method from cacheable_object interface.
2750 * @return array
2752 public static function wake_from_cache($data) {
2753 $classname = $data['class'];
2754 return new $classname($data['id'], $data['ctxid'], $data['options'], $data['readonly']);
2758 * Gets a file relative to this file in the repository and sends it to the browser.
2759 * Used to allow relative file linking within a repository without creating file records
2760 * for linked files
2762 * Repositories that overwrite this must be very careful - see filesystem repository for example.
2764 * @param stored_file $mainfile The main file we are trying to access relative files for.
2765 * @param string $relativepath the relative path to the file we are trying to access.
2768 public function send_relative_file(stored_file $mainfile, $relativepath) {
2769 // This repository hasn't implemented this so send_file_not_found.
2770 send_file_not_found();
2774 * helper function to check if the repository supports send_relative_file.
2776 * @return true|false
2778 public function supports_relative_file() {
2779 return false;
2783 * Helper function to indicate if this repository uses post requests for uploading files.
2785 * @deprecated since Moodle 3.2, 3.1.1, 3.0.5
2786 * @return bool
2788 public function uses_post_requests() {
2789 debugging('The method repository::uses_post_requests() is deprecated and must not be used anymore.', DEBUG_DEVELOPER);
2790 return false;
2795 * Exception class for repository api
2797 * @since Moodle 2.0
2798 * @package core_repository
2799 * @copyright 2009 Dongsheng Cai {@link http://dongsheng.org}
2800 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2802 class repository_exception extends moodle_exception {
2806 * This is a class used to define a repository instance form
2808 * @since Moodle 2.0
2809 * @package core_repository
2810 * @copyright 2009 Dongsheng Cai {@link http://dongsheng.org}
2811 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2813 final class repository_instance_form extends moodleform {
2814 /** @var stdClass repository instance */
2815 protected $instance;
2816 /** @var string repository plugin type */
2817 protected $plugin;
2820 * Added defaults to moodle form
2822 protected function add_defaults() {
2823 $mform =& $this->_form;
2824 $strrequired = get_string('required');
2826 $mform->addElement('hidden', 'edit', ($this->instance) ? $this->instance->id : 0);
2827 $mform->setType('edit', PARAM_INT);
2828 $mform->addElement('hidden', 'new', $this->plugin);
2829 $mform->setType('new', PARAM_ALPHANUMEXT);
2830 $mform->addElement('hidden', 'plugin', $this->plugin);
2831 $mform->setType('plugin', PARAM_PLUGIN);
2832 $mform->addElement('hidden', 'typeid', $this->typeid);
2833 $mform->setType('typeid', PARAM_INT);
2834 $mform->addElement('hidden', 'contextid', $this->contextid);
2835 $mform->setType('contextid', PARAM_INT);
2837 $mform->addElement('text', 'name', get_string('name'), 'maxlength="100" size="30"');
2838 $mform->addRule('name', $strrequired, 'required', null, 'client');
2839 $mform->setType('name', PARAM_TEXT);
2843 * Define moodle form elements
2845 public function definition() {
2846 global $CFG;
2847 // type of plugin, string
2848 $this->plugin = $this->_customdata['plugin'];
2849 $this->typeid = $this->_customdata['typeid'];
2850 $this->contextid = $this->_customdata['contextid'];
2851 $this->instance = (isset($this->_customdata['instance'])
2852 && is_subclass_of($this->_customdata['instance'], 'repository'))
2853 ? $this->_customdata['instance'] : null;
2855 $mform =& $this->_form;
2857 $this->add_defaults();
2859 // Add instance config options.
2860 $result = repository::static_function($this->plugin, 'instance_config_form', $mform);
2861 if ($result === false) {
2862 // Remove the name element if no other config options.
2863 $mform->removeElement('name');
2865 if ($this->instance) {
2866 $data = array();
2867 $data['name'] = $this->instance->name;
2868 if (!$this->instance->readonly) {
2869 // and set the data if we have some.
2870 foreach ($this->instance->get_instance_option_names() as $config) {
2871 if (!empty($this->instance->options[$config])) {
2872 $data[$config] = $this->instance->options[$config];
2873 } else {
2874 $data[$config] = '';
2878 $this->set_data($data);
2881 if ($result === false) {
2882 $mform->addElement('cancel');
2883 } else {
2884 $this->add_action_buttons(true, get_string('save','repository'));
2889 * Validate moodle form data
2891 * @param array $data form data
2892 * @param array $files files in form
2893 * @return array errors
2895 public function validation($data, $files) {
2896 global $DB;
2897 $errors = array();
2898 $plugin = $this->_customdata['plugin'];
2899 $instance = (isset($this->_customdata['instance'])
2900 && is_subclass_of($this->_customdata['instance'], 'repository'))
2901 ? $this->_customdata['instance'] : null;
2903 if (!$instance) {
2904 $errors = repository::static_function($plugin, 'instance_form_validation', $this, $data, $errors);
2905 } else {
2906 $errors = $instance->instance_form_validation($this, $data, $errors);
2909 $sql = "SELECT count('x')
2910 FROM {repository_instances} i, {repository} r
2911 WHERE r.type=:plugin AND r.id=i.typeid AND i.name=:name AND i.contextid=:contextid";
2912 $params = array('name' => $data['name'], 'plugin' => $this->plugin, 'contextid' => $this->contextid);
2913 if ($instance) {
2914 $sql .= ' AND i.id != :instanceid';
2915 $params['instanceid'] = $instance->id;
2917 if ($DB->count_records_sql($sql, $params) > 0) {
2918 $errors['name'] = get_string('erroruniquename', 'repository');
2921 return $errors;
2926 * This is a class used to define a repository type setting form
2928 * @since Moodle 2.0
2929 * @package core_repository
2930 * @copyright 2009 Dongsheng Cai {@link http://dongsheng.org}
2931 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2933 final class repository_type_form extends moodleform {
2934 /** @var stdClass repository instance */
2935 protected $instance;
2936 /** @var string repository plugin name */
2937 protected $plugin;
2938 /** @var string action */
2939 protected $action;
2942 * Definition of the moodleform
2944 public function definition() {
2945 global $CFG;
2946 // type of plugin, string
2947 $this->plugin = $this->_customdata['plugin'];
2948 $this->instance = (isset($this->_customdata['instance'])
2949 && is_a($this->_customdata['instance'], 'repository_type'))
2950 ? $this->_customdata['instance'] : null;
2952 $this->action = $this->_customdata['action'];
2953 $this->pluginname = $this->_customdata['pluginname'];
2954 $mform =& $this->_form;
2955 $strrequired = get_string('required');
2957 $mform->addElement('hidden', 'action', $this->action);
2958 $mform->setType('action', PARAM_TEXT);
2959 $mform->addElement('hidden', 'repos', $this->plugin);
2960 $mform->setType('repos', PARAM_PLUGIN);
2962 // let the plugin add its specific fields
2963 $classname = 'repository_' . $this->plugin;
2964 require_once($CFG->dirroot . '/repository/' . $this->plugin . '/lib.php');
2965 //add "enable course/user instances" checkboxes if multiple instances are allowed
2966 $instanceoptionnames = repository::static_function($this->plugin, 'get_instance_option_names');
2968 $result = call_user_func(array($classname, 'type_config_form'), $mform, $classname);
2970 if (!empty($instanceoptionnames)) {
2971 $sm = get_string_manager();
2972 $component = 'repository';
2973 if ($sm->string_exists('enablecourseinstances', 'repository_' . $this->plugin)) {
2974 $component .= ('_' . $this->plugin);
2976 $mform->addElement('checkbox', 'enablecourseinstances', get_string('enablecourseinstances', $component));
2977 $mform->setType('enablecourseinstances', PARAM_BOOL);
2979 $component = 'repository';
2980 if ($sm->string_exists('enableuserinstances', 'repository_' . $this->plugin)) {
2981 $component .= ('_' . $this->plugin);
2983 $mform->addElement('checkbox', 'enableuserinstances', get_string('enableuserinstances', $component));
2984 $mform->setType('enableuserinstances', PARAM_BOOL);
2987 // set the data if we have some.
2988 if ($this->instance) {
2989 $data = array();
2990 $option_names = call_user_func(array($classname,'get_type_option_names'));
2991 if (!empty($instanceoptionnames)){
2992 $option_names[] = 'enablecourseinstances';
2993 $option_names[] = 'enableuserinstances';
2996 $instanceoptions = $this->instance->get_options();
2997 foreach ($option_names as $config) {
2998 if (!empty($instanceoptions[$config])) {
2999 $data[$config] = $instanceoptions[$config];
3000 } else {
3001 $data[$config] = '';
3004 // XXX: set plugin name for plugins which doesn't have muliti instances
3005 if (empty($instanceoptionnames)){
3006 $data['pluginname'] = $this->pluginname;
3008 $this->set_data($data);
3011 $this->add_action_buttons(true, get_string('save','repository'));
3015 * Validate moodle form data
3017 * @param array $data moodle form data
3018 * @param array $files
3019 * @return array errors
3021 public function validation($data, $files) {
3022 $errors = array();
3023 $plugin = $this->_customdata['plugin'];
3024 $instance = (isset($this->_customdata['instance'])
3025 && is_subclass_of($this->_customdata['instance'], 'repository'))
3026 ? $this->_customdata['instance'] : null;
3027 if (!$instance) {
3028 $errors = repository::static_function($plugin, 'type_form_validation', $this, $data, $errors);
3029 } else {
3030 $errors = $instance->type_form_validation($this, $data, $errors);
3033 return $errors;
3038 * Generate all options needed by filepicker
3040 * @param array $args including following keys
3041 * context
3042 * accepted_types
3043 * return_types
3045 * @return array the list of repository instances, including meta infomation, containing the following keys
3046 * externallink
3047 * repositories
3048 * accepted_types
3050 function initialise_filepicker($args) {
3051 global $CFG, $USER, $PAGE, $OUTPUT;
3052 static $templatesinitialized = array();
3053 require_once($CFG->libdir . '/licenselib.php');
3055 $return = new stdClass();
3056 $licenses = array();
3057 if (!empty($CFG->licenses)) {
3058 $array = explode(',', $CFG->licenses);
3059 foreach ($array as $license) {
3060 $l = new stdClass();
3061 $l->shortname = $license;
3062 $l->fullname = get_string($license, 'license');
3063 $licenses[] = $l;
3066 if (!empty($CFG->sitedefaultlicense)) {
3067 $return->defaultlicense = $CFG->sitedefaultlicense;
3070 $return->licenses = $licenses;
3072 $return->author = fullname($USER);
3074 if (empty($args->context)) {
3075 $context = $PAGE->context;
3076 } else {
3077 $context = $args->context;
3079 $disable_types = array();
3080 if (!empty($args->disable_types)) {
3081 $disable_types = $args->disable_types;
3084 $user_context = context_user::instance($USER->id);
3086 list($context, $course, $cm) = get_context_info_array($context->id);
3087 $contexts = array($user_context, context_system::instance());
3088 if (!empty($course)) {
3089 // adding course context
3090 $contexts[] = context_course::instance($course->id);
3092 $externallink = (int)get_config(null, 'repositoryallowexternallinks');
3093 $repositories = repository::get_instances(array(
3094 'context'=>$contexts,
3095 'currentcontext'=> $context,
3096 'accepted_types'=>$args->accepted_types,
3097 'return_types'=>$args->return_types,
3098 'disable_types'=>$disable_types
3101 $return->repositories = array();
3103 if (empty($externallink)) {
3104 $return->externallink = false;
3105 } else {
3106 $return->externallink = true;
3109 $return->userprefs = array();
3110 $return->userprefs['recentrepository'] = get_user_preferences('filepicker_recentrepository', '');
3111 $return->userprefs['recentlicense'] = get_user_preferences('filepicker_recentlicense', '');
3112 $return->userprefs['recentviewmode'] = get_user_preferences('filepicker_recentviewmode', '');
3114 user_preference_allow_ajax_update('filepicker_recentrepository', PARAM_INT);
3115 user_preference_allow_ajax_update('filepicker_recentlicense', PARAM_SAFEDIR);
3116 user_preference_allow_ajax_update('filepicker_recentviewmode', PARAM_INT);
3119 // provided by form element
3120 $return->accepted_types = file_get_typegroup('extension', $args->accepted_types);
3121 $return->return_types = $args->return_types;
3122 $templates = array();
3123 foreach ($repositories as $repository) {
3124 $meta = $repository->get_meta();
3125 // Please note that the array keys for repositories are used within
3126 // JavaScript a lot, the key NEEDS to be the repository id.
3127 $return->repositories[$repository->id] = $meta;
3128 // Register custom repository template if it has one
3129 if(method_exists($repository, 'get_upload_template') && !array_key_exists('uploadform_' . $meta->type, $templatesinitialized)) {
3130 $templates['uploadform_' . $meta->type] = $repository->get_upload_template();
3131 $templatesinitialized['uploadform_' . $meta->type] = true;
3134 if (!array_key_exists('core', $templatesinitialized)) {
3135 // we need to send each filepicker template to the browser just once
3136 $fprenderer = $PAGE->get_renderer('core', 'files');
3137 $templates = array_merge($templates, $fprenderer->filepicker_js_templates());
3138 $templatesinitialized['core'] = true;
3140 if (sizeof($templates)) {
3141 $PAGE->requires->js_init_call('M.core_filepicker.set_templates', array($templates), true);
3143 return $return;