MDL-42285 Behat: Automate MDLQA-93 - A teacher can delete questions from the question...
[moodle.git] / repository / lib.php
blob6a7669f384157b1f2584e34973328b603c2a2243
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 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 {
496 /** Timeout in seconds for downloading the external file into moodle */
497 const GETFILE_TIMEOUT = 30;
498 /** Timeout in seconds for syncronising the external file size */
499 const SYNCFILE_TIMEOUT = 1;
500 /** Timeout in seconds for downloading an image file from external repository during syncronisation */
501 const SYNCIMAGE_TIMEOUT = 3;
503 // $disabled can be set to true to disable a plugin by force
504 // example: self::$disabled = true
505 /** @var bool force disable repository instance */
506 public $disabled = false;
507 /** @var int repository instance id */
508 public $id;
509 /** @var stdClass current context */
510 public $context;
511 /** @var array repository options */
512 public $options;
513 /** @var bool Whether or not the repository instance is editable */
514 public $readonly;
515 /** @var int return types */
516 public $returntypes;
517 /** @var stdClass repository instance database record */
518 public $instance;
519 /** @var string Type of repository (webdav, google_docs, dropbox, ...). Read from $this->get_typename(). */
520 protected $typename;
523 * Constructor
525 * @param int $repositoryid repository instance id
526 * @param int|stdClass $context a context id or context object
527 * @param array $options repository options
528 * @param int $readonly indicate this repo is readonly or not
530 public function __construct($repositoryid, $context = SYSCONTEXTID, $options = array(), $readonly = 0) {
531 global $DB;
532 $this->id = $repositoryid;
533 if (is_object($context)) {
534 $this->context = $context;
535 } else {
536 $this->context = context::instance_by_id($context);
538 $cache = cache::make('core', 'repositories');
539 if (($this->instance = $cache->get('i:'. $this->id)) === false) {
540 $this->instance = $DB->get_record_sql("SELECT i.*, r.type AS repositorytype, r.sortorder, r.visible
541 FROM {repository} r, {repository_instances} i
542 WHERE i.typeid = r.id and i.id = ?", array('id' => $this->id));
543 $cache->set('i:'. $this->id, $this->instance);
545 $this->readonly = $readonly;
546 $this->options = array();
548 if (is_array($options)) {
549 // The get_option() method will get stored options in database.
550 $options = array_merge($this->get_option(), $options);
551 } else {
552 $options = $this->get_option();
554 foreach ($options as $n => $v) {
555 $this->options[$n] = $v;
557 $this->name = $this->get_name();
558 $this->returntypes = $this->supported_returntypes();
559 $this->super_called = true;
563 * Magic method for non-existing (usually deprecated) class methods.
565 * @param string $name
566 * @param array $arguments
567 * @return mixed
568 * @throws coding_exception
570 public function __call($name, $arguments) {
571 if ($name === 'sync_individual_file') {
572 // Method repository::sync_individual_file() was deprecated in Moodle 2.6.
573 // See repository::sync_reference().
574 debugging('Function repository::sync_individual_file() is deprecated.', DEBUG_DEVELOPER);
575 return true;
576 } else if ($name === 'get_file_by_reference') {
577 // Method repository::get_file_by_reference() was deprecated in Moodle 2.6.
578 // See repository::sync_reference().
579 debugging('Function repository::get_file_by_reference() is deprecated.', DEBUG_DEVELOPER);
580 return null;
581 } else if ($name === 'get_reference_file_lifetime') {
582 // Method repository::get_file_by_reference() was deprecated in Moodle 2.6.
583 // See repository::sync_reference().
584 debugging('Function repository::get_reference_file_lifetime() is deprecated.', DEBUG_DEVELOPER);
585 return 24 * 60 * 60;
586 } else {
587 throw new coding_exception('Tried to call unknown method '.get_class($this).'::'.$name);
592 * Get repository instance using repository id
594 * Note that this function does not check permission to access repository contents
596 * @throws repository_exception
598 * @param int $repositoryid repository instance ID
599 * @param context|int $context context instance or context ID where this repository will be used
600 * @param array $options additional repository options
601 * @return repository
603 public static function get_repository_by_id($repositoryid, $context, $options = array()) {
604 global $CFG, $DB;
605 $cache = cache::make('core', 'repositories');
606 if (!is_object($context)) {
607 $context = context::instance_by_id($context);
609 $cachekey = 'rep:'. $repositoryid. ':'. $context->id. ':'. serialize($options);
610 if ($repository = $cache->get($cachekey)) {
611 return $repository;
614 if (!$record = $cache->get('i:'. $repositoryid)) {
615 $sql = "SELECT i.*, r.type AS repositorytype, r.visible, r.sortorder
616 FROM {repository_instances} i
617 JOIN {repository} r ON r.id = i.typeid
618 WHERE i.id = ?";
619 if (!$record = $DB->get_record_sql($sql, array($repositoryid))) {
620 throw new repository_exception('invalidrepositoryid', 'repository');
622 $cache->set('i:'. $record->id, $record);
625 $type = $record->repositorytype;
626 if (file_exists($CFG->dirroot . "/repository/$type/lib.php")) {
627 require_once($CFG->dirroot . "/repository/$type/lib.php");
628 $classname = 'repository_' . $type;
629 $options['type'] = $type;
630 $options['typeid'] = $record->typeid;
631 $options['visible'] = $record->visible;
632 if (empty($options['name'])) {
633 $options['name'] = $record->name;
635 $repository = new $classname($repositoryid, $context, $options, $record->readonly);
636 if (empty($repository->super_called)) {
637 // to make sure the super construct is called
638 debugging('parent::__construct must be called by '.$type.' plugin.');
640 $cache->set($cachekey, $repository);
641 return $repository;
642 } else {
643 throw new repository_exception('invalidplugin', 'repository');
648 * Returns the type name of the repository.
650 * @return string type name of the repository.
651 * @since 2.5
653 public function get_typename() {
654 if (empty($this->typename)) {
655 $matches = array();
656 if (!preg_match("/^repository_(.*)$/", get_class($this), $matches)) {
657 throw new coding_exception('The class name of a repository should be repository_<typeofrepository>, '.
658 'e.g. repository_dropbox');
660 $this->typename = $matches[1];
662 return $this->typename;
666 * Get a repository type object by a given type name.
668 * @static
669 * @param string $typename the repository type name
670 * @return repository_type|bool
672 public static function get_type_by_typename($typename) {
673 global $DB;
674 $cache = cache::make('core', 'repositories');
675 if (($repositorytype = $cache->get('typename:'. $typename)) === false) {
676 $repositorytype = null;
677 if ($record = $DB->get_record('repository', array('type' => $typename))) {
678 $repositorytype = new repository_type($record->type, (array)get_config($record->type), $record->visible, $record->sortorder);
679 $cache->set('typeid:'. $record->id, $repositorytype);
681 $cache->set('typename:'. $typename, $repositorytype);
683 return $repositorytype;
687 * Get the repository type by a given repository type id.
689 * @static
690 * @param int $id the type id
691 * @return object
693 public static function get_type_by_id($id) {
694 global $DB;
695 $cache = cache::make('core', 'repositories');
696 if (($repositorytype = $cache->get('typeid:'. $id)) === false) {
697 $repositorytype = null;
698 if ($record = $DB->get_record('repository', array('id' => $id))) {
699 $repositorytype = new repository_type($record->type, (array)get_config($record->type), $record->visible, $record->sortorder);
700 $cache->set('typename:'. $record->type, $repositorytype);
702 $cache->set('typeid:'. $id, $repositorytype);
704 return $repositorytype;
708 * Return all repository types ordered by sortorder field
709 * first repository type in returnedarray[0], second repository type in returnedarray[1], ...
711 * @static
712 * @param bool $visible can return types by visiblity, return all types if null
713 * @return array Repository types
715 public static function get_types($visible=null) {
716 global $DB, $CFG;
717 $cache = cache::make('core', 'repositories');
718 if (!$visible) {
719 $typesnames = $cache->get('types');
720 } else {
721 $typesnames = $cache->get('typesvis');
723 $types = array();
724 if ($typesnames === false) {
725 $typesnames = array();
726 $vistypesnames = array();
727 if ($records = $DB->get_records('repository', null ,'sortorder')) {
728 foreach($records as $type) {
729 if (($repositorytype = $cache->get('typename:'. $type->type)) === false) {
730 // Create new instance of repository_type.
731 if (file_exists($CFG->dirroot . '/repository/'. $type->type .'/lib.php')) {
732 $repositorytype = new repository_type($type->type, (array)get_config($type->type), $type->visible, $type->sortorder);
733 $cache->set('typeid:'. $type->id, $repositorytype);
734 $cache->set('typename:'. $type->type, $repositorytype);
737 if ($repositorytype) {
738 if (empty($visible) || $repositorytype->get_visible()) {
739 $types[] = $repositorytype;
740 $vistypesnames[] = $repositorytype->get_typename();
742 $typesnames[] = $repositorytype->get_typename();
746 $cache->set('types', $typesnames);
747 $cache->set('typesvis', $vistypesnames);
748 } else {
749 foreach ($typesnames as $typename) {
750 $types[] = self::get_type_by_typename($typename);
753 return $types;
757 * Checks if user has a capability to view the current repository.
759 * @return bool true when the user can, otherwise throws an exception.
760 * @throws repository_exception when the user does not meet the requirements.
762 public final function check_capability() {
763 global $USER;
765 // The context we are on.
766 $currentcontext = $this->context;
768 // Ensure that the user can view the repository in the current context.
769 $can = has_capability('repository/'.$this->get_typename().':view', $currentcontext);
771 // Context in which the repository has been created.
772 $repocontext = context::instance_by_id($this->instance->contextid);
774 // Prevent access to private repositories when logged in as.
775 if ($can && \core\session\manager::is_loggedinas()) {
776 if ($this->contains_private_data() || $repocontext->contextlevel == CONTEXT_USER) {
777 $can = false;
781 // We are going to ensure that the current context was legit, and reliable to check
782 // the capability against. (No need to do that if we already cannot).
783 if ($can) {
784 if ($repocontext->contextlevel == CONTEXT_USER) {
785 // The repository is a user instance, ensure we're the right user to access it!
786 if ($repocontext->instanceid != $USER->id) {
787 $can = false;
789 } else if ($repocontext->contextlevel == CONTEXT_COURSE) {
790 // The repository is a course one. Let's check that we are on the right course.
791 if (in_array($currentcontext->contextlevel, array(CONTEXT_COURSE, CONTEXT_MODULE, CONTEXT_BLOCK))) {
792 $coursecontext = $currentcontext->get_course_context();
793 if ($coursecontext->instanceid != $repocontext->instanceid) {
794 $can = false;
796 } else {
797 // We are on a parent context, therefore it's legit to check the permissions
798 // in the current context.
800 } else {
801 // Nothing to check here, system instances can have different permissions on different
802 // levels. We do not want to prevent URL hack here, because it does not make sense to
803 // prevent a user to access a repository in a context if it's accessible in another one.
807 if ($can) {
808 return true;
811 throw new repository_exception('nopermissiontoaccess', 'repository');
815 * Check if file already exists in draft area.
817 * @static
818 * @param int $itemid of the draft area.
819 * @param string $filepath path to the file.
820 * @param string $filename file name.
821 * @return bool
823 public static function draftfile_exists($itemid, $filepath, $filename) {
824 global $USER;
825 $fs = get_file_storage();
826 $usercontext = context_user::instance($USER->id);
827 return $fs->file_exists($usercontext->id, 'user', 'draft', $itemid, $filepath, $filename);
831 * Parses the 'source' returned by moodle repositories and returns an instance of stored_file
833 * @param string $source
834 * @return stored_file|null
836 public static function get_moodle_file($source) {
837 $params = file_storage::unpack_reference($source, true);
838 $fs = get_file_storage();
839 return $fs->get_file($params['contextid'], $params['component'], $params['filearea'],
840 $params['itemid'], $params['filepath'], $params['filename']);
844 * Repository method to make sure that user can access particular file.
846 * This is checked when user tries to pick the file from repository to deal with
847 * potential parameter substitutions is request
849 * @param string $source
850 * @return bool whether the file is accessible by current user
852 public function file_is_accessible($source) {
853 if ($this->has_moodle_files()) {
854 try {
855 $params = file_storage::unpack_reference($source, true);
856 } catch (file_reference_exception $e) {
857 return false;
859 $browser = get_file_browser();
860 $context = context::instance_by_id($params['contextid']);
861 $file_info = $browser->get_file_info($context, $params['component'], $params['filearea'],
862 $params['itemid'], $params['filepath'], $params['filename']);
863 return !empty($file_info);
865 return true;
869 * This function is used to copy a moodle file to draft area.
871 * It DOES NOT check if the user is allowed to access this file because the actual file
872 * can be located in the area where user does not have access to but there is an alias
873 * to this file in the area where user CAN access it.
874 * {@link file_is_accessible} should be called for alias location before calling this function.
876 * @param string $source The metainfo of file, it is base64 encoded php serialized data
877 * @param stdClass|array $filerecord contains itemid, filepath, filename and optionally other
878 * attributes of the new file
879 * @param int $maxbytes maximum allowed size of file, -1 if unlimited. If size of file exceeds
880 * the limit, the file_exception is thrown.
881 * @param int $areamaxbytes the maximum size of the area. A file_exception is thrown if the
882 * new file will reach the limit.
883 * @return array The information about the created file
885 public function copy_to_area($source, $filerecord, $maxbytes = -1, $areamaxbytes = FILE_AREA_MAX_BYTES_UNLIMITED) {
886 global $USER;
887 $fs = get_file_storage();
889 if ($this->has_moodle_files() == false) {
890 throw new coding_exception('Only repository used to browse moodle files can use repository::copy_to_area()');
893 $user_context = context_user::instance($USER->id);
895 $filerecord = (array)$filerecord;
896 // make sure the new file will be created in user draft area
897 $filerecord['component'] = 'user';
898 $filerecord['filearea'] = 'draft';
899 $filerecord['contextid'] = $user_context->id;
900 $draftitemid = $filerecord['itemid'];
901 $new_filepath = $filerecord['filepath'];
902 $new_filename = $filerecord['filename'];
904 // the file needs to copied to draft area
905 $stored_file = self::get_moodle_file($source);
906 if ($maxbytes != -1 && $stored_file->get_filesize() > $maxbytes) {
907 throw new file_exception('maxbytes');
909 // Validate the size of the draft area.
910 if (file_is_draft_area_limit_reached($draftitemid, $areamaxbytes, $stored_file->get_filesize())) {
911 throw new file_exception('maxareabytes');
914 if (repository::draftfile_exists($draftitemid, $new_filepath, $new_filename)) {
915 // create new file
916 $unused_filename = repository::get_unused_filename($draftitemid, $new_filepath, $new_filename);
917 $filerecord['filename'] = $unused_filename;
918 $fs->create_file_from_storedfile($filerecord, $stored_file);
919 $event = array();
920 $event['event'] = 'fileexists';
921 $event['newfile'] = new stdClass;
922 $event['newfile']->filepath = $new_filepath;
923 $event['newfile']->filename = $unused_filename;
924 $event['newfile']->url = moodle_url::make_draftfile_url($draftitemid, $new_filepath, $unused_filename)->out();
925 $event['existingfile'] = new stdClass;
926 $event['existingfile']->filepath = $new_filepath;
927 $event['existingfile']->filename = $new_filename;
928 $event['existingfile']->url = moodle_url::make_draftfile_url($draftitemid, $new_filepath, $new_filename)->out();
929 return $event;
930 } else {
931 $fs->create_file_from_storedfile($filerecord, $stored_file);
932 $info = array();
933 $info['itemid'] = $draftitemid;
934 $info['file'] = $new_filename;
935 $info['title'] = $new_filename;
936 $info['contextid'] = $user_context->id;
937 $info['url'] = moodle_url::make_draftfile_url($draftitemid, $new_filepath, $new_filename)->out();
938 $info['filesize'] = $stored_file->get_filesize();
939 return $info;
944 * Get an unused filename from the current draft area.
946 * Will check if the file ends with ([0-9]) and increase the number.
948 * @static
949 * @param int $itemid draft item ID.
950 * @param string $filepath path to the file.
951 * @param string $filename name of the file.
952 * @return string an unused file name.
954 public static function get_unused_filename($itemid, $filepath, $filename) {
955 global $USER;
956 $contextid = context_user::instance($USER->id)->id;
957 $fs = get_file_storage();
958 return $fs->get_unused_filename($contextid, 'user', 'draft', $itemid, $filepath, $filename);
962 * Append a suffix to filename.
964 * @static
965 * @param string $filename
966 * @return string
967 * @deprecated since 2.5
969 public static function append_suffix($filename) {
970 debugging('The function repository::append_suffix() has been deprecated. Use repository::get_unused_filename() instead.',
971 DEBUG_DEVELOPER);
972 $pathinfo = pathinfo($filename);
973 if (empty($pathinfo['extension'])) {
974 return $filename . RENAME_SUFFIX;
975 } else {
976 return $pathinfo['filename'] . RENAME_SUFFIX . '.' . $pathinfo['extension'];
981 * Return all types that you a user can create/edit and which are also visible
982 * Note: Mostly used in order to know if at least one editable type can be set
984 * @static
985 * @param stdClass $context the context for which we want the editable types
986 * @return array types
988 public static function get_editable_types($context = null) {
990 if (empty($context)) {
991 $context = context_system::instance();
994 $types= repository::get_types(true);
995 $editabletypes = array();
996 foreach ($types as $type) {
997 $instanceoptionnames = repository::static_function($type->get_typename(), 'get_instance_option_names');
998 if (!empty($instanceoptionnames)) {
999 if ($type->get_contextvisibility($context)) {
1000 $editabletypes[]=$type;
1004 return $editabletypes;
1008 * Return repository instances
1010 * @static
1011 * @param array $args Array containing the following keys:
1012 * currentcontext : instance of context (default system context)
1013 * context : array of instances of context (default empty array)
1014 * onlyvisible : bool (default true)
1015 * type : string return instances of this type only
1016 * accepted_types : string|array return instances that contain files of those types (*, web_image, .pdf, ...)
1017 * return_types : int combination of FILE_INTERNAL & FILE_EXTERNAL & FILE_REFERENCE.
1018 * 0 means every type. The default is FILE_INTERNAL | FILE_EXTERNAL.
1019 * userid : int if specified, instances belonging to other users will not be returned
1021 * @return array repository instances
1023 public static function get_instances($args = array()) {
1024 global $DB, $CFG, $USER;
1026 // Fill $args attributes with default values unless specified
1027 if (!isset($args['currentcontext']) || !($args['currentcontext'] instanceof context)) {
1028 $current_context = context_system::instance();
1029 } else {
1030 $current_context = $args['currentcontext'];
1032 $args['currentcontext'] = $current_context->id;
1033 $contextids = array();
1034 if (!empty($args['context'])) {
1035 foreach ($args['context'] as $context) {
1036 $contextids[] = $context->id;
1039 $args['context'] = $contextids;
1040 if (!isset($args['onlyvisible'])) {
1041 $args['onlyvisible'] = true;
1043 if (!isset($args['return_types'])) {
1044 $args['return_types'] = FILE_INTERNAL | FILE_EXTERNAL;
1046 if (!isset($args['type'])) {
1047 $args['type'] = null;
1049 if (empty($args['disable_types']) || !is_array($args['disable_types'])) {
1050 $args['disable_types'] = null;
1052 if (empty($args['userid']) || !is_numeric($args['userid'])) {
1053 $args['userid'] = null;
1055 if (!isset($args['accepted_types']) || (is_array($args['accepted_types']) && in_array('*', $args['accepted_types']))) {
1056 $args['accepted_types'] = '*';
1058 ksort($args);
1059 $cachekey = 'all:'. serialize($args);
1061 // Check if we have cached list of repositories with the same query
1062 $cache = cache::make('core', 'repositories');
1063 if (($cachedrepositories = $cache->get($cachekey)) !== false) {
1064 // convert from cacheable_object_array to array
1065 $repositories = array();
1066 foreach ($cachedrepositories as $repository) {
1067 $repositories[$repository->id] = $repository;
1069 return $repositories;
1072 // Prepare DB SQL query to retrieve repositories
1073 $params = array();
1074 $sql = "SELECT i.*, r.type AS repositorytype, r.sortorder, r.visible
1075 FROM {repository} r, {repository_instances} i
1076 WHERE i.typeid = r.id ";
1078 if ($args['disable_types']) {
1079 list($types, $p) = $DB->get_in_or_equal($args['disable_types'], SQL_PARAMS_NAMED, 'distype', false);
1080 $sql .= " AND r.type $types";
1081 $params = array_merge($params, $p);
1084 if ($args['userid']) {
1085 $sql .= " AND (i.userid = 0 or i.userid = :userid)";
1086 $params['userid'] = $args['userid'];
1089 if ($args['context']) {
1090 list($ctxsql, $p2) = $DB->get_in_or_equal($args['context'], SQL_PARAMS_NAMED, 'ctx');
1091 $sql .= " AND i.contextid $ctxsql";
1092 $params = array_merge($params, $p2);
1095 if ($args['onlyvisible'] == true) {
1096 $sql .= " AND r.visible = 1";
1099 if ($args['type'] !== null) {
1100 $sql .= " AND r.type = :type";
1101 $params['type'] = $args['type'];
1103 $sql .= " ORDER BY r.sortorder, i.name";
1105 if (!$records = $DB->get_records_sql($sql, $params)) {
1106 $records = array();
1109 $repositories = array();
1110 // Sortorder should be unique, which is not true if we use $record->sortorder
1111 // and there are multiple instances of any repository type
1112 $sortorder = 1;
1113 foreach ($records as $record) {
1114 $cache->set('i:'. $record->id, $record);
1115 if (!file_exists($CFG->dirroot . '/repository/'. $record->repositorytype.'/lib.php')) {
1116 continue;
1118 $repository = self::get_repository_by_id($record->id, $current_context);
1119 $repository->options['sortorder'] = $sortorder++;
1121 $is_supported = true;
1123 // check mimetypes
1124 if ($args['accepted_types'] !== '*' and $repository->supported_filetypes() !== '*') {
1125 $accepted_ext = file_get_typegroup('extension', $args['accepted_types']);
1126 $supported_ext = file_get_typegroup('extension', $repository->supported_filetypes());
1127 $valid_ext = array_intersect($accepted_ext, $supported_ext);
1128 $is_supported = !empty($valid_ext);
1130 // Check return values.
1131 if (!empty($args['return_types']) && !($repository->supported_returntypes() & $args['return_types'])) {
1132 $is_supported = false;
1135 if (!$args['onlyvisible'] || ($repository->is_visible() && !$repository->disabled)) {
1136 // check capability in current context
1137 $capability = has_capability('repository/'.$record->repositorytype.':view', $current_context);
1138 if ($record->repositorytype == 'coursefiles') {
1139 // coursefiles plugin needs managefiles permission
1140 $capability = $capability && has_capability('moodle/course:managefiles', $current_context);
1142 if ($is_supported && $capability) {
1143 $repositories[$repository->id] = $repository;
1147 $cache->set($cachekey, new cacheable_object_array($repositories));
1148 return $repositories;
1152 * Get single repository instance for administrative actions
1154 * Do not use this function to access repository contents, because it
1155 * does not set the current context
1157 * @see repository::get_repository_by_id()
1159 * @static
1160 * @param integer $id repository instance id
1161 * @return repository
1163 public static function get_instance($id) {
1164 return self::get_repository_by_id($id, context_system::instance());
1168 * Call a static function. Any additional arguments than plugin and function will be passed through.
1170 * @static
1171 * @param string $plugin repository plugin name
1172 * @param string $function function name
1173 * @return mixed
1175 public static function static_function($plugin, $function) {
1176 global $CFG;
1178 //check that the plugin exists
1179 $typedirectory = $CFG->dirroot . '/repository/'. $plugin . '/lib.php';
1180 if (!file_exists($typedirectory)) {
1181 //throw new repository_exception('invalidplugin', 'repository');
1182 return false;
1185 $args = func_get_args();
1186 if (count($args) <= 2) {
1187 $args = array();
1188 } else {
1189 array_shift($args);
1190 array_shift($args);
1193 require_once($typedirectory);
1194 return call_user_func_array(array('repository_' . $plugin, $function), $args);
1198 * Scan file, throws exception in case of infected file.
1200 * Please note that the scanning engine must be able to access the file,
1201 * permissions of the file are not modified here!
1203 * @static
1204 * @param string $thefile
1205 * @param string $filename name of the file
1206 * @param bool $deleteinfected
1208 public static function antivir_scan_file($thefile, $filename, $deleteinfected) {
1209 global $CFG;
1211 if (!is_readable($thefile)) {
1212 // this should not happen
1213 return;
1216 if (empty($CFG->runclamonupload) or empty($CFG->pathtoclam)) {
1217 // clam not enabled
1218 return;
1221 $CFG->pathtoclam = trim($CFG->pathtoclam);
1223 if (!file_exists($CFG->pathtoclam) or !is_executable($CFG->pathtoclam)) {
1224 // misconfigured clam - use the old notification for now
1225 require("$CFG->libdir/uploadlib.php");
1226 $notice = get_string('clamlost', 'moodle', $CFG->pathtoclam);
1227 clam_message_admins($notice);
1228 return;
1231 $clamparam = ' --stdout ';
1232 // If we are dealing with clamdscan, clamd is likely run as a different user
1233 // that might not have permissions to access your file.
1234 // To make clamdscan work, we use --fdpass parameter that passes the file
1235 // descriptor permissions to clamd, which allows it to scan given file
1236 // irrespective of directory and file permissions.
1237 if (basename($CFG->pathtoclam) == 'clamdscan') {
1238 $clamparam .= '--fdpass ';
1240 // execute test
1241 $cmd = escapeshellcmd($CFG->pathtoclam).$clamparam.escapeshellarg($thefile);
1242 exec($cmd, $output, $return);
1244 if ($return == 0) {
1245 // perfect, no problem found
1246 return;
1248 } else if ($return == 1) {
1249 // infection found
1250 if ($deleteinfected) {
1251 unlink($thefile);
1253 throw new moodle_exception('virusfounduser', 'moodle', '', array('filename'=>$filename));
1255 } else {
1256 //unknown problem
1257 require("$CFG->libdir/uploadlib.php");
1258 $notice = get_string('clamfailed', 'moodle', get_clam_error_code($return));
1259 $notice .= "\n\n". implode("\n", $output);
1260 clam_message_admins($notice);
1261 if ($CFG->clamfailureonupload === 'actlikevirus') {
1262 if ($deleteinfected) {
1263 unlink($thefile);
1265 throw new moodle_exception('virusfounduser', 'moodle', '', array('filename'=>$filename));
1266 } else {
1267 return;
1273 * Repository method to serve the referenced file
1275 * @see send_stored_file
1277 * @param stored_file $storedfile the file that contains the reference
1278 * @param int $lifetime Number of seconds before the file should expire from caches (default 24 hours)
1279 * @param int $filter 0 (default)=no filtering, 1=all files, 2=html files only
1280 * @param bool $forcedownload If true (default false), forces download of file rather than view in browser/plugin
1281 * @param array $options additional options affecting the file serving
1283 public function send_file($storedfile, $lifetime=86400 , $filter=0, $forcedownload=false, array $options = null) {
1284 if ($this->has_moodle_files()) {
1285 $fs = get_file_storage();
1286 $params = file_storage::unpack_reference($storedfile->get_reference(), true);
1287 $srcfile = null;
1288 if (is_array($params)) {
1289 $srcfile = $fs->get_file($params['contextid'], $params['component'], $params['filearea'],
1290 $params['itemid'], $params['filepath'], $params['filename']);
1292 if (empty($options)) {
1293 $options = array();
1295 if (!isset($options['filename'])) {
1296 $options['filename'] = $storedfile->get_filename();
1298 if (!$srcfile) {
1299 send_file_not_found();
1300 } else {
1301 send_stored_file($srcfile, $lifetime, $filter, $forcedownload, $options);
1303 } else {
1304 throw new coding_exception("Repository plugin must implement send_file() method.");
1309 * Return human readable reference information
1311 * @param string $reference value of DB field files_reference.reference
1312 * @param int $filestatus status of the file, 0 - ok, 666 - source missing
1313 * @return string
1315 public function get_reference_details($reference, $filestatus = 0) {
1316 if ($this->has_moodle_files()) {
1317 $fileinfo = null;
1318 $params = file_storage::unpack_reference($reference, true);
1319 if (is_array($params)) {
1320 $context = context::instance_by_id($params['contextid'], IGNORE_MISSING);
1321 if ($context) {
1322 $browser = get_file_browser();
1323 $fileinfo = $browser->get_file_info($context, $params['component'], $params['filearea'], $params['itemid'], $params['filepath'], $params['filename']);
1326 if (empty($fileinfo)) {
1327 if ($filestatus == 666) {
1328 if (is_siteadmin() || ($context && has_capability('moodle/course:managefiles', $context))) {
1329 return get_string('lostsource', 'repository',
1330 $params['contextid']. '/'. $params['component']. '/'. $params['filearea']. '/'. $params['itemid']. $params['filepath']. $params['filename']);
1331 } else {
1332 return get_string('lostsource', 'repository', '');
1335 return get_string('undisclosedsource', 'repository');
1336 } else {
1337 return $fileinfo->get_readable_fullname();
1340 return '';
1344 * Cache file from external repository by reference
1345 * {@link repository::get_file_reference()}
1346 * {@link repository::get_file()}
1347 * Invoked at MOODLE/repository/repository_ajax.php
1349 * @param string $reference this reference is generated by
1350 * repository::get_file_reference()
1351 * @param stored_file $storedfile created file reference
1353 public function cache_file_by_reference($reference, $storedfile) {
1357 * Return the source information
1359 * The result of the function is stored in files.source field. It may be analysed
1360 * when the source file is lost or repository may use it to display human-readable
1361 * location of reference original.
1363 * This method is called when file is picked for the first time only. When file
1364 * (either copy or a reference) is already in moodle and it is being picked
1365 * again to another file area (also as a copy or as a reference), the value of
1366 * files.source is copied.
1368 * @param string $source the value that repository returned in listing as 'source'
1369 * @return string|null
1371 public function get_file_source_info($source) {
1372 if ($this->has_moodle_files()) {
1373 return $this->get_reference_details($source, 0);
1375 return $source;
1379 * Move file from download folder to file pool using FILE API
1381 * @todo MDL-28637
1382 * @static
1383 * @param string $thefile file path in download folder
1384 * @param stdClass $record
1385 * @return array containing the following keys:
1386 * icon
1387 * file
1388 * id
1389 * url
1391 public static function move_to_filepool($thefile, $record) {
1392 global $DB, $CFG, $USER, $OUTPUT;
1394 // scan for viruses if possible, throws exception if problem found
1395 self::antivir_scan_file($thefile, $record->filename, empty($CFG->repository_no_delete)); //TODO: MDL-28637 this repository_no_delete is a bloody hack!
1397 $fs = get_file_storage();
1398 // If file name being used.
1399 if (repository::draftfile_exists($record->itemid, $record->filepath, $record->filename)) {
1400 $draftitemid = $record->itemid;
1401 $new_filename = repository::get_unused_filename($draftitemid, $record->filepath, $record->filename);
1402 $old_filename = $record->filename;
1403 // Create a tmp file.
1404 $record->filename = $new_filename;
1405 $newfile = $fs->create_file_from_pathname($record, $thefile);
1406 $event = array();
1407 $event['event'] = 'fileexists';
1408 $event['newfile'] = new stdClass;
1409 $event['newfile']->filepath = $record->filepath;
1410 $event['newfile']->filename = $new_filename;
1411 $event['newfile']->url = moodle_url::make_draftfile_url($draftitemid, $record->filepath, $new_filename)->out();
1413 $event['existingfile'] = new stdClass;
1414 $event['existingfile']->filepath = $record->filepath;
1415 $event['existingfile']->filename = $old_filename;
1416 $event['existingfile']->url = moodle_url::make_draftfile_url($draftitemid, $record->filepath, $old_filename)->out();
1417 return $event;
1419 if ($file = $fs->create_file_from_pathname($record, $thefile)) {
1420 if (empty($CFG->repository_no_delete)) {
1421 $delete = unlink($thefile);
1422 unset($CFG->repository_no_delete);
1424 return array(
1425 'url'=>moodle_url::make_draftfile_url($file->get_itemid(), $file->get_filepath(), $file->get_filename())->out(),
1426 'id'=>$file->get_itemid(),
1427 'file'=>$file->get_filename(),
1428 'icon' => $OUTPUT->pix_url(file_extension_icon($thefile, 32))->out(),
1430 } else {
1431 return null;
1436 * Builds a tree of files This function is then called recursively.
1438 * @static
1439 * @todo take $search into account, and respect a threshold for dynamic loading
1440 * @param file_info $fileinfo an object returned by file_browser::get_file_info()
1441 * @param string $search searched string
1442 * @param bool $dynamicmode no recursive call is done when in dynamic mode
1443 * @param array $list the array containing the files under the passed $fileinfo
1444 * @return int the number of files found
1446 public static function build_tree($fileinfo, $search, $dynamicmode, &$list) {
1447 global $CFG, $OUTPUT;
1449 $filecount = 0;
1450 $children = $fileinfo->get_children();
1452 foreach ($children as $child) {
1453 $filename = $child->get_visible_name();
1454 $filesize = $child->get_filesize();
1455 $filesize = $filesize ? display_size($filesize) : '';
1456 $filedate = $child->get_timemodified();
1457 $filedate = $filedate ? userdate($filedate) : '';
1458 $filetype = $child->get_mimetype();
1460 if ($child->is_directory()) {
1461 $path = array();
1462 $level = $child->get_parent();
1463 while ($level) {
1464 $params = $level->get_params();
1465 $path[] = array($params['filepath'], $level->get_visible_name());
1466 $level = $level->get_parent();
1469 $tmp = array(
1470 'title' => $child->get_visible_name(),
1471 'size' => 0,
1472 'date' => $filedate,
1473 'path' => array_reverse($path),
1474 'thumbnail' => $OUTPUT->pix_url(file_folder_icon(90))->out(false)
1477 //if ($dynamicmode && $child->is_writable()) {
1478 // $tmp['children'] = array();
1479 //} else {
1480 // if folder name matches search, we send back all files contained.
1481 $_search = $search;
1482 if ($search && stristr($tmp['title'], $search) !== false) {
1483 $_search = false;
1485 $tmp['children'] = array();
1486 $_filecount = repository::build_tree($child, $_search, $dynamicmode, $tmp['children']);
1487 if ($search && $_filecount) {
1488 $tmp['expanded'] = 1;
1493 if (!$search || $_filecount || (stristr($tmp['title'], $search) !== false)) {
1494 $filecount += $_filecount;
1495 $list[] = $tmp;
1498 } else { // not a directory
1499 // skip the file, if we're in search mode and it's not a match
1500 if ($search && (stristr($filename, $search) === false)) {
1501 continue;
1503 $params = $child->get_params();
1504 $source = serialize(array($params['contextid'], $params['component'], $params['filearea'], $params['itemid'], $params['filepath'], $params['filename']));
1505 $list[] = array(
1506 'title' => $filename,
1507 'size' => $filesize,
1508 'date' => $filedate,
1509 //'source' => $child->get_url(),
1510 'source' => base64_encode($source),
1511 'icon'=>$OUTPUT->pix_url(file_file_icon($child, 24))->out(false),
1512 'thumbnail'=>$OUTPUT->pix_url(file_file_icon($child, 90))->out(false),
1514 $filecount++;
1518 return $filecount;
1522 * Display a repository instance list (with edit/delete/create links)
1524 * @static
1525 * @param stdClass $context the context for which we display the instance
1526 * @param string $typename if set, we display only one type of instance
1528 public static function display_instances_list($context, $typename = null) {
1529 global $CFG, $USER, $OUTPUT;
1531 $output = $OUTPUT->box_start('generalbox');
1532 //if the context is SYSTEM, so we call it from administration page
1533 $admin = ($context->id == SYSCONTEXTID) ? true : false;
1534 if ($admin) {
1535 $baseurl = new moodle_url('/'.$CFG->admin.'/repositoryinstance.php', array('sesskey'=>sesskey()));
1536 $output .= $OUTPUT->heading(get_string('siteinstances', 'repository'));
1537 } else {
1538 $baseurl = new moodle_url('/repository/manage_instances.php', array('contextid'=>$context->id, 'sesskey'=>sesskey()));
1541 $namestr = get_string('name');
1542 $pluginstr = get_string('plugin', 'repository');
1543 $settingsstr = get_string('settings');
1544 $deletestr = get_string('delete');
1545 // Retrieve list of instances. In administration context we want to display all
1546 // instances of a type, even if this type is not visible. In course/user context we
1547 // want to display only visible instances, but for every type types. The repository::get_instances()
1548 // third parameter displays only visible type.
1549 $params = array();
1550 $params['context'] = array($context);
1551 $params['currentcontext'] = $context;
1552 $params['return_types'] = 0;
1553 $params['onlyvisible'] = !$admin;
1554 $params['type'] = $typename;
1555 $instances = repository::get_instances($params);
1556 $instancesnumber = count($instances);
1557 $alreadyplugins = array();
1559 $table = new html_table();
1560 $table->head = array($namestr, $pluginstr, $settingsstr, $deletestr);
1561 $table->align = array('left', 'left', 'center','center');
1562 $table->data = array();
1564 $updowncount = 1;
1566 foreach ($instances as $i) {
1567 $settings = '';
1568 $delete = '';
1570 $type = repository::get_type_by_id($i->options['typeid']);
1572 if ($type->get_contextvisibility($context)) {
1573 if (!$i->readonly) {
1575 $settingurl = new moodle_url($baseurl);
1576 $settingurl->param('type', $i->options['type']);
1577 $settingurl->param('edit', $i->id);
1578 $settings .= html_writer::link($settingurl, $settingsstr);
1580 $deleteurl = new moodle_url($baseurl);
1581 $deleteurl->param('delete', $i->id);
1582 $deleteurl->param('type', $i->options['type']);
1583 $delete .= html_writer::link($deleteurl, $deletestr);
1587 $type = repository::get_type_by_id($i->options['typeid']);
1588 $table->data[] = array(format_string($i->name), $type->get_readablename(), $settings, $delete);
1590 //display a grey row if the type is defined as not visible
1591 if (isset($type) && !$type->get_visible()) {
1592 $table->rowclasses[] = 'dimmed_text';
1593 } else {
1594 $table->rowclasses[] = '';
1597 if (!in_array($i->name, $alreadyplugins)) {
1598 $alreadyplugins[] = $i->name;
1601 $output .= html_writer::table($table);
1602 $instancehtml = '<div>';
1603 $addable = 0;
1605 //if no type is set, we can create all type of instance
1606 if (!$typename) {
1607 $instancehtml .= '<h3>';
1608 $instancehtml .= get_string('createrepository', 'repository');
1609 $instancehtml .= '</h3><ul>';
1610 $types = repository::get_editable_types($context);
1611 foreach ($types as $type) {
1612 if (!empty($type) && $type->get_visible()) {
1613 // If the user does not have the permission to view the repository, it won't be displayed in
1614 // the list of instances. Hiding the link to create new instances will prevent the
1615 // user from creating them without being able to find them afterwards, which looks like a bug.
1616 if (!has_capability('repository/'.$type->get_typename().':view', $context)) {
1617 continue;
1619 $instanceoptionnames = repository::static_function($type->get_typename(), 'get_instance_option_names');
1620 if (!empty($instanceoptionnames)) {
1621 $baseurl->param('new', $type->get_typename());
1622 $instancehtml .= '<li><a href="'.$baseurl->out().'">'.get_string('createxxinstance', 'repository', get_string('pluginname', 'repository_'.$type->get_typename())). '</a></li>';
1623 $baseurl->remove_params('new');
1624 $addable++;
1628 $instancehtml .= '</ul>';
1630 } else {
1631 $instanceoptionnames = repository::static_function($typename, 'get_instance_option_names');
1632 if (!empty($instanceoptionnames)) { //create a unique type of instance
1633 $addable = 1;
1634 $baseurl->param('new', $typename);
1635 $output .= $OUTPUT->single_button($baseurl, get_string('createinstance', 'repository'), 'get');
1636 $baseurl->remove_params('new');
1640 if ($addable) {
1641 $instancehtml .= '</div>';
1642 $output .= $instancehtml;
1645 $output .= $OUTPUT->box_end();
1647 //print the list + creation links
1648 print($output);
1652 * Prepare file reference information
1654 * @param string $source
1655 * @return string file referece
1657 public function get_file_reference($source) {
1658 if ($this->has_moodle_files() && ($this->supported_returntypes() & FILE_REFERENCE)) {
1659 $params = file_storage::unpack_reference($source);
1660 if (!is_array($params)) {
1661 throw new repository_exception('invalidparams', 'repository');
1663 return file_storage::pack_reference($params);
1665 return $source;
1669 * Decide where to save the file, can be overwriten by subclass
1671 * @param string $filename file name
1672 * @return file path
1674 public function prepare_file($filename) {
1675 global $CFG;
1676 $dir = make_temp_directory('download/'.get_class($this).'/');
1677 while (empty($filename) || file_exists($dir.$filename)) {
1678 $filename = uniqid('', true).'_'.time().'.tmp';
1680 return $dir.$filename;
1684 * Does this repository used to browse moodle files?
1686 * @return bool
1688 public function has_moodle_files() {
1689 return false;
1693 * Return file URL, for most plugins, the parameter is the original
1694 * url, but some plugins use a file id, so we need this function to
1695 * convert file id to original url.
1697 * @param string $url the url of file
1698 * @return string
1700 public function get_link($url) {
1701 return $url;
1705 * Downloads a file from external repository and saves it in temp dir
1707 * Function get_file() must be implemented by repositories that support returntypes
1708 * FILE_INTERNAL or FILE_REFERENCE. It is invoked to pick up the file and copy it
1709 * to moodle. This function is not called for moodle repositories, the function
1710 * {@link repository::copy_to_area()} is used instead.
1712 * This function can be overridden by subclass if the files.reference field contains
1713 * not just URL or if request should be done differently.
1715 * @see curl
1716 * @throws file_exception when error occured
1718 * @param string $url the content of files.reference field, in this implementaion
1719 * it is asssumed that it contains the string with URL of the file
1720 * @param string $filename filename (without path) to save the downloaded file in the
1721 * temporary directory, if omitted or file already exists the new filename will be generated
1722 * @return array with elements:
1723 * path: internal location of the file
1724 * url: URL to the source (from parameters)
1726 public function get_file($url, $filename = '') {
1727 $path = $this->prepare_file($filename);
1728 $c = new curl;
1729 $result = $c->download_one($url, null, array('filepath' => $path, 'timeout' => self::GETFILE_TIMEOUT));
1730 if ($result !== true) {
1731 throw new moodle_exception('errorwhiledownload', 'repository', '', $result);
1733 return array('path'=>$path, 'url'=>$url);
1737 * Downloads the file from external repository and saves it in moodle filepool.
1738 * This function is different from {@link repository::sync_reference()} because it has
1739 * bigger request timeout and always downloads the content.
1741 * This function is invoked when we try to unlink the file from the source and convert
1742 * a reference into a true copy.
1744 * @throws exception when file could not be imported
1746 * @param stored_file $file
1747 * @param int $maxbytes throw an exception if file size is bigger than $maxbytes (0 means no limit)
1749 public function import_external_file_contents(stored_file $file, $maxbytes = 0) {
1750 if (!$file->is_external_file()) {
1751 // nothing to import if the file is not a reference
1752 return;
1753 } else if ($file->get_repository_id() != $this->id) {
1754 // error
1755 debugging('Repository instance id does not match');
1756 return;
1757 } else if ($this->has_moodle_files()) {
1758 // files that are references to local files are already in moodle filepool
1759 // just validate the size
1760 if ($maxbytes > 0 && $file->get_filesize() > $maxbytes) {
1761 throw new file_exception('maxbytes');
1763 return;
1764 } else {
1765 if ($maxbytes > 0 && $file->get_filesize() > $maxbytes) {
1766 // note that stored_file::get_filesize() also calls synchronisation
1767 throw new file_exception('maxbytes');
1769 $fs = get_file_storage();
1770 $contentexists = $fs->content_exists($file->get_contenthash());
1771 if ($contentexists && $file->get_filesize() && $file->get_contenthash() === sha1('')) {
1772 // even when 'file_storage::content_exists()' returns true this may be an empty
1773 // content for the file that was not actually downloaded
1774 $contentexists = false;
1776 if (!$file->get_status() && $contentexists) {
1777 // we already have the content in moodle filepool and it was synchronised recently.
1778 // Repositories may overwrite it if they want to force synchronisation anyway!
1779 return;
1780 } else {
1781 // attempt to get a file
1782 try {
1783 $fileinfo = $this->get_file($file->get_reference());
1784 if (isset($fileinfo['path'])) {
1785 list($contenthash, $filesize, $newfile) = $fs->add_file_to_pool($fileinfo['path']);
1786 // set this file and other similar aliases synchronised
1787 $file->set_synchronized($contenthash, $filesize);
1788 } else {
1789 throw new moodle_exception('errorwhiledownload', 'repository', '', '');
1791 } catch (Exception $e) {
1792 if ($contentexists) {
1793 // better something than nothing. We have a copy of file. It's sync time
1794 // has expired but it is still very likely that it is the last version
1795 } else {
1796 throw($e);
1804 * Return size of a file in bytes.
1806 * @param string $source encoded and serialized data of file
1807 * @return int file size in bytes
1809 public function get_file_size($source) {
1810 // TODO MDL-33297 remove this function completely?
1811 $browser = get_file_browser();
1812 $params = unserialize(base64_decode($source));
1813 $contextid = clean_param($params['contextid'], PARAM_INT);
1814 $fileitemid = clean_param($params['itemid'], PARAM_INT);
1815 $filename = clean_param($params['filename'], PARAM_FILE);
1816 $filepath = clean_param($params['filepath'], PARAM_PATH);
1817 $filearea = clean_param($params['filearea'], PARAM_AREA);
1818 $component = clean_param($params['component'], PARAM_COMPONENT);
1819 $context = context::instance_by_id($contextid);
1820 $file_info = $browser->get_file_info($context, $component, $filearea, $fileitemid, $filepath, $filename);
1821 if (!empty($file_info)) {
1822 $filesize = $file_info->get_filesize();
1823 } else {
1824 $filesize = null;
1826 return $filesize;
1830 * Return is the instance is visible
1831 * (is the type visible ? is the context enable ?)
1833 * @return bool
1835 public function is_visible() {
1836 $type = repository::get_type_by_id($this->options['typeid']);
1837 $instanceoptions = repository::static_function($type->get_typename(), 'get_instance_option_names');
1839 if ($type->get_visible()) {
1840 //if the instance is unique so it's visible, otherwise check if the instance has a enabled context
1841 if (empty($instanceoptions) || $type->get_contextvisibility(context::instance_by_id($this->instance->contextid))) {
1842 return true;
1846 return false;
1850 * Can the instance be edited by the current user?
1852 * The property $readonly must not be used within this method because
1853 * it only controls if the options from self::get_instance_option_names()
1854 * can be edited.
1856 * @return bool true if the user can edit the instance.
1857 * @since 2.5
1859 public final function can_be_edited_by_user() {
1860 global $USER;
1862 // We need to be able to explore the repository.
1863 try {
1864 $this->check_capability();
1865 } catch (repository_exception $e) {
1866 return false;
1869 $repocontext = context::instance_by_id($this->instance->contextid);
1870 if ($repocontext->contextlevel == CONTEXT_USER && $repocontext->instanceid != $USER->id) {
1871 // If the context of this instance is a user context, we need to be this user.
1872 return false;
1873 } else if ($repocontext->contextlevel == CONTEXT_MODULE && !has_capability('moodle/course:update', $repocontext)) {
1874 // We need to have permissions on the course to edit the instance.
1875 return false;
1876 } else if ($repocontext->contextlevel == CONTEXT_SYSTEM && !has_capability('moodle/site:config', $repocontext)) {
1877 // Do not meet the requirements for the context system.
1878 return false;
1881 return true;
1885 * Return the name of this instance, can be overridden.
1887 * @return string
1889 public function get_name() {
1890 if ($name = $this->instance->name) {
1891 return $name;
1892 } else {
1893 return get_string('pluginname', 'repository_' . $this->get_typename());
1898 * Is this repository accessing private data?
1900 * This function should return true for the repositories which access external private
1901 * data from a user. This is the case for repositories such as Dropbox, Google Docs or Box.net
1902 * which authenticate the user and then store the auth token.
1904 * Of course, many repositories store 'private data', but we only want to set
1905 * contains_private_data() to repositories which are external to Moodle and shouldn't be accessed
1906 * to by the users having the capability to 'login as' someone else. For instance, the repository
1907 * 'Private files' is not considered as private because it's part of Moodle.
1909 * You should not set contains_private_data() to true on repositories which allow different types
1910 * of instances as the levels other than 'user' are, by definition, not private. Also
1911 * the user instances will be protected when they need to.
1913 * @return boolean True when the repository accesses private external data.
1914 * @since 2.5
1916 public function contains_private_data() {
1917 return true;
1921 * What kind of files will be in this repository?
1923 * @return array return '*' means this repository support any files, otherwise
1924 * return mimetypes of files, it can be an array
1926 public function supported_filetypes() {
1927 // return array('text/plain', 'image/gif');
1928 return '*';
1932 * Tells how the file can be picked from this repository
1934 * Maximum value is FILE_INTERNAL | FILE_EXTERNAL | FILE_REFERENCE
1936 * @return int
1938 public function supported_returntypes() {
1939 return (FILE_INTERNAL | FILE_EXTERNAL);
1943 * Provide repository instance information for Ajax
1945 * @return stdClass
1947 final public function get_meta() {
1948 global $CFG, $OUTPUT;
1949 $meta = new stdClass();
1950 $meta->id = $this->id;
1951 $meta->name = format_string($this->get_name());
1952 $meta->type = $this->get_typename();
1953 $meta->icon = $OUTPUT->pix_url('icon', 'repository_'.$meta->type)->out(false);
1954 $meta->supported_types = file_get_typegroup('extension', $this->supported_filetypes());
1955 $meta->return_types = $this->supported_returntypes();
1956 $meta->sortorder = $this->options['sortorder'];
1957 return $meta;
1961 * Create an instance for this plug-in
1963 * @static
1964 * @param string $type the type of the repository
1965 * @param int $userid the user id
1966 * @param stdClass $context the context
1967 * @param array $params the options for this instance
1968 * @param int $readonly whether to create it readonly or not (defaults to not)
1969 * @return mixed
1971 public static function create($type, $userid, $context, $params, $readonly=0) {
1972 global $CFG, $DB;
1973 $params = (array)$params;
1974 require_once($CFG->dirroot . '/repository/'. $type . '/lib.php');
1975 $classname = 'repository_' . $type;
1976 if ($repo = $DB->get_record('repository', array('type'=>$type))) {
1977 $record = new stdClass();
1978 $record->name = $params['name'];
1979 $record->typeid = $repo->id;
1980 $record->timecreated = time();
1981 $record->timemodified = time();
1982 $record->contextid = $context->id;
1983 $record->readonly = $readonly;
1984 $record->userid = $userid;
1985 $id = $DB->insert_record('repository_instances', $record);
1986 cache::make('core', 'repositories')->purge();
1987 $options = array();
1988 $configs = call_user_func($classname . '::get_instance_option_names');
1989 if (!empty($configs)) {
1990 foreach ($configs as $config) {
1991 if (isset($params[$config])) {
1992 $options[$config] = $params[$config];
1993 } else {
1994 $options[$config] = null;
1999 if (!empty($id)) {
2000 unset($options['name']);
2001 $instance = repository::get_instance($id);
2002 $instance->set_option($options);
2003 return $id;
2004 } else {
2005 return null;
2007 } else {
2008 return null;
2013 * delete a repository instance
2015 * @param bool $downloadcontents
2016 * @return bool
2018 final public function delete($downloadcontents = false) {
2019 global $DB;
2020 if ($downloadcontents) {
2021 $this->convert_references_to_local();
2023 cache::make('core', 'repositories')->purge();
2024 try {
2025 $DB->delete_records('repository_instances', array('id'=>$this->id));
2026 $DB->delete_records('repository_instance_config', array('instanceid'=>$this->id));
2027 } catch (dml_exception $ex) {
2028 return false;
2030 return true;
2034 * Delete all the instances associated to a context.
2036 * This method is intended to be a callback when deleting
2037 * a course or a user to delete all the instances associated
2038 * to their context. The usual way to delete a single instance
2039 * is to use {@link self::delete()}.
2041 * @param int $contextid context ID.
2042 * @param boolean $downloadcontents true to convert references to hard copies.
2043 * @return void
2045 final public static function delete_all_for_context($contextid, $downloadcontents = true) {
2046 global $DB;
2047 $repoids = $DB->get_fieldset_select('repository_instances', 'id', 'contextid = :contextid', array('contextid' => $contextid));
2048 if ($downloadcontents) {
2049 foreach ($repoids as $repoid) {
2050 $repo = repository::get_repository_by_id($repoid, $contextid);
2051 $repo->convert_references_to_local();
2054 cache::make('core', 'repositories')->purge();
2055 $DB->delete_records_list('repository_instances', 'id', $repoids);
2056 $DB->delete_records_list('repository_instance_config', 'instanceid', $repoids);
2060 * Hide/Show a repository
2062 * @param string $hide
2063 * @return bool
2065 final public function hide($hide = 'toggle') {
2066 global $DB;
2067 if ($entry = $DB->get_record('repository', array('id'=>$this->id))) {
2068 if ($hide === 'toggle' ) {
2069 if (!empty($entry->visible)) {
2070 $entry->visible = 0;
2071 } else {
2072 $entry->visible = 1;
2074 } else {
2075 if (!empty($hide)) {
2076 $entry->visible = 0;
2077 } else {
2078 $entry->visible = 1;
2081 return $DB->update_record('repository', $entry);
2083 return false;
2087 * Save settings for repository instance
2088 * $repo->set_option(array('api_key'=>'f2188bde132', 'name'=>'dongsheng'));
2090 * @param array $options settings
2091 * @return bool
2093 public function set_option($options = array()) {
2094 global $DB;
2096 if (!empty($options['name'])) {
2097 $r = new stdClass();
2098 $r->id = $this->id;
2099 $r->name = $options['name'];
2100 $DB->update_record('repository_instances', $r);
2101 unset($options['name']);
2103 foreach ($options as $name=>$value) {
2104 if ($id = $DB->get_field('repository_instance_config', 'id', array('name'=>$name, 'instanceid'=>$this->id))) {
2105 $DB->set_field('repository_instance_config', 'value', $value, array('id'=>$id));
2106 } else {
2107 $config = new stdClass();
2108 $config->instanceid = $this->id;
2109 $config->name = $name;
2110 $config->value = $value;
2111 $DB->insert_record('repository_instance_config', $config);
2114 cache::make('core', 'repositories')->purge();
2115 return true;
2119 * Get settings for repository instance.
2121 * @param string $config a specific option to get.
2122 * @return mixed returns an array of options. If $config is not empty, then it returns that option,
2123 * or null if the option does not exist.
2125 public function get_option($config = '') {
2126 global $DB;
2127 $cache = cache::make('core', 'repositories');
2128 if (($entries = $cache->get('ops:'. $this->id)) === false) {
2129 $entries = $DB->get_records('repository_instance_config', array('instanceid' => $this->id));
2130 $cache->set('ops:'. $this->id, $entries);
2133 $ret = array();
2134 foreach($entries as $entry) {
2135 $ret[$entry->name] = $entry->value;
2138 if (!empty($config)) {
2139 if (isset($ret[$config])) {
2140 return $ret[$config];
2141 } else {
2142 return null;
2144 } else {
2145 return $ret;
2150 * Filter file listing to display specific types
2152 * @param array $value
2153 * @return bool
2155 public function filter(&$value) {
2156 $accepted_types = optional_param_array('accepted_types', '', PARAM_RAW);
2157 if (isset($value['children'])) {
2158 if (!empty($value['children'])) {
2159 $value['children'] = array_filter($value['children'], array($this, 'filter'));
2161 return true; // always return directories
2162 } else {
2163 if ($accepted_types == '*' or empty($accepted_types)
2164 or (is_array($accepted_types) and in_array('*', $accepted_types))) {
2165 return true;
2166 } else {
2167 foreach ($accepted_types as $ext) {
2168 if (preg_match('#'.$ext.'$#i', $value['title'])) {
2169 return true;
2174 return false;
2178 * Given a path, and perhaps a search, get a list of files.
2180 * See details on {@link http://docs.moodle.org/dev/Repository_plugins}
2182 * @param string $path this parameter can a folder name, or a identification of folder
2183 * @param string $page the page number of file list
2184 * @return array the list of files, including meta infomation, containing the following keys
2185 * manage, url to manage url
2186 * client_id
2187 * login, login form
2188 * repo_id, active repository id
2189 * login_btn_action, the login button action
2190 * login_btn_label, the login button label
2191 * total, number of results
2192 * perpage, items per page
2193 * page
2194 * pages, total pages
2195 * issearchresult, is it a search result?
2196 * list, file list
2197 * path, current path and parent path
2199 public function get_listing($path = '', $page = '') {
2204 * Prepare the breadcrumb.
2206 * @param array $breadcrumb contains each element of the breadcrumb.
2207 * @return array of breadcrumb elements.
2208 * @since 2.3.3
2210 protected static function prepare_breadcrumb($breadcrumb) {
2211 global $OUTPUT;
2212 $foldericon = $OUTPUT->pix_url(file_folder_icon(24))->out(false);
2213 $len = count($breadcrumb);
2214 for ($i = 0; $i < $len; $i++) {
2215 if (is_array($breadcrumb[$i]) && !isset($breadcrumb[$i]['icon'])) {
2216 $breadcrumb[$i]['icon'] = $foldericon;
2217 } else if (is_object($breadcrumb[$i]) && !isset($breadcrumb[$i]->icon)) {
2218 $breadcrumb[$i]->icon = $foldericon;
2221 return $breadcrumb;
2225 * Prepare the file/folder listing.
2227 * @param array $list of files and folders.
2228 * @return array of files and folders.
2229 * @since 2.3.3
2231 protected static function prepare_list($list) {
2232 global $OUTPUT;
2233 $foldericon = $OUTPUT->pix_url(file_folder_icon(24))->out(false);
2235 // Reset the array keys because non-numeric keys will create an object when converted to JSON.
2236 $list = array_values($list);
2238 $len = count($list);
2239 for ($i = 0; $i < $len; $i++) {
2240 if (is_object($list[$i])) {
2241 $file = (array)$list[$i];
2242 $converttoobject = true;
2243 } else {
2244 $file =& $list[$i];
2245 $converttoobject = false;
2247 if (isset($file['size'])) {
2248 $file['size'] = (int)$file['size'];
2249 $file['size_f'] = display_size($file['size']);
2251 if (isset($file['license']) && get_string_manager()->string_exists($file['license'], 'license')) {
2252 $file['license_f'] = get_string($file['license'], 'license');
2254 if (isset($file['image_width']) && isset($file['image_height'])) {
2255 $a = array('width' => $file['image_width'], 'height' => $file['image_height']);
2256 $file['dimensions'] = get_string('imagesize', 'repository', (object)$a);
2258 foreach (array('date', 'datemodified', 'datecreated') as $key) {
2259 if (!isset($file[$key]) && isset($file['date'])) {
2260 $file[$key] = $file['date'];
2262 if (isset($file[$key])) {
2263 // must be UNIX timestamp
2264 $file[$key] = (int)$file[$key];
2265 if (!$file[$key]) {
2266 unset($file[$key]);
2267 } else {
2268 $file[$key.'_f'] = userdate($file[$key], get_string('strftimedatetime', 'langconfig'));
2269 $file[$key.'_f_s'] = userdate($file[$key], get_string('strftimedatetimeshort', 'langconfig'));
2273 $isfolder = (array_key_exists('children', $file) || (isset($file['type']) && $file['type'] == 'folder'));
2274 $filename = null;
2275 if (isset($file['title'])) {
2276 $filename = $file['title'];
2278 else if (isset($file['fullname'])) {
2279 $filename = $file['fullname'];
2281 if (!isset($file['mimetype']) && !$isfolder && $filename) {
2282 $file['mimetype'] = get_mimetype_description(array('filename' => $filename));
2284 if (!isset($file['icon'])) {
2285 if ($isfolder) {
2286 $file['icon'] = $foldericon;
2287 } else if ($filename) {
2288 $file['icon'] = $OUTPUT->pix_url(file_extension_icon($filename, 24))->out(false);
2292 // Recursively loop over children.
2293 if (isset($file['children'])) {
2294 $file['children'] = self::prepare_list($file['children']);
2297 // Convert the array back to an object.
2298 if ($converttoobject) {
2299 $list[$i] = (object)$file;
2302 return $list;
2306 * Prepares list of files before passing it to AJAX, makes sure data is in the correct
2307 * format and stores formatted values.
2309 * @param array|stdClass $listing result of get_listing() or search() or file_get_drafarea_files()
2310 * @return array
2312 public static function prepare_listing($listing) {
2313 $wasobject = false;
2314 if (is_object($listing)) {
2315 $listing = (array) $listing;
2316 $wasobject = true;
2319 // Prepare the breadcrumb, passed as 'path'.
2320 if (isset($listing['path']) && is_array($listing['path'])) {
2321 $listing['path'] = self::prepare_breadcrumb($listing['path']);
2324 // Prepare the listing of objects.
2325 if (isset($listing['list']) && is_array($listing['list'])) {
2326 $listing['list'] = self::prepare_list($listing['list']);
2329 // Convert back to an object.
2330 if ($wasobject) {
2331 $listing = (object) $listing;
2333 return $listing;
2337 * Search files in repository
2338 * When doing global search, $search_text will be used as
2339 * keyword.
2341 * @param string $search_text search key word
2342 * @param int $page page
2343 * @return mixed see {@link repository::get_listing()}
2345 public function search($search_text, $page = 0) {
2346 $list = array();
2347 $list['list'] = array();
2348 return false;
2352 * Logout from repository instance
2353 * By default, this function will return a login form
2355 * @return string
2357 public function logout(){
2358 return $this->print_login();
2362 * To check whether the user is logged in.
2364 * @return bool
2366 public function check_login(){
2367 return true;
2372 * Show the login screen, if required
2374 * @return string
2376 public function print_login(){
2377 return $this->get_listing();
2381 * Show the search screen, if required
2383 * @return string
2385 public function print_search() {
2386 global $PAGE;
2387 $renderer = $PAGE->get_renderer('core', 'files');
2388 return $renderer->repository_default_searchform();
2392 * For oauth like external authentication, when external repository direct user back to moodle,
2393 * this function will be called to set up token and token_secret
2395 public function callback() {
2399 * is it possible to do glboal search?
2401 * @return bool
2403 public function global_search() {
2404 return false;
2408 * Defines operations that happen occasionally on cron
2410 * @return bool
2412 public function cron() {
2413 return true;
2417 * function which is run when the type is created (moodle administrator add the plugin)
2419 * @return bool success or fail?
2421 public static function plugin_init() {
2422 return true;
2426 * Edit/Create Admin Settings Moodle form
2428 * @param moodleform $mform Moodle form (passed by reference)
2429 * @param string $classname repository class name
2431 public static function type_config_form($mform, $classname = 'repository') {
2432 $instnaceoptions = call_user_func(array($classname, 'get_instance_option_names'), $mform, $classname);
2433 if (empty($instnaceoptions)) {
2434 // this plugin has only one instance
2435 // so we need to give it a name
2436 // it can be empty, then moodle will look for instance name from language string
2437 $mform->addElement('text', 'pluginname', get_string('pluginname', 'repository'), array('size' => '40'));
2438 $mform->addElement('static', 'pluginnamehelp', '', get_string('pluginnamehelp', 'repository'));
2439 $mform->setType('pluginname', PARAM_TEXT);
2444 * Validate Admin Settings Moodle form
2446 * @static
2447 * @param moodleform $mform Moodle form (passed by reference)
2448 * @param array $data array of ("fieldname"=>value) of submitted data
2449 * @param array $errors array of ("fieldname"=>errormessage) of errors
2450 * @return array array of errors
2452 public static function type_form_validation($mform, $data, $errors) {
2453 return $errors;
2458 * Edit/Create Instance Settings Moodle form
2460 * @param moodleform $mform Moodle form (passed by reference)
2462 public static function instance_config_form($mform) {
2466 * Return names of the general options.
2467 * By default: no general option name
2469 * @return array
2471 public static function get_type_option_names() {
2472 return array('pluginname');
2476 * Return names of the instance options.
2477 * By default: no instance option name
2479 * @return array
2481 public static function get_instance_option_names() {
2482 return array();
2486 * Validate repository plugin instance form
2488 * @param moodleform $mform moodle form
2489 * @param array $data form data
2490 * @param array $errors errors
2491 * @return array errors
2493 public static function instance_form_validation($mform, $data, $errors) {
2494 return $errors;
2498 * Create a shorten filename
2500 * @param string $str filename
2501 * @param int $maxlength max file name length
2502 * @return string short filename
2504 public function get_short_filename($str, $maxlength) {
2505 if (core_text::strlen($str) >= $maxlength) {
2506 return trim(core_text::substr($str, 0, $maxlength)).'...';
2507 } else {
2508 return $str;
2513 * Overwrite an existing file
2515 * @param int $itemid
2516 * @param string $filepath
2517 * @param string $filename
2518 * @param string $newfilepath
2519 * @param string $newfilename
2520 * @return bool
2522 public static function overwrite_existing_draftfile($itemid, $filepath, $filename, $newfilepath, $newfilename) {
2523 global $USER;
2524 $fs = get_file_storage();
2525 $user_context = context_user::instance($USER->id);
2526 if ($file = $fs->get_file($user_context->id, 'user', 'draft', $itemid, $filepath, $filename)) {
2527 if ($tempfile = $fs->get_file($user_context->id, 'user', 'draft', $itemid, $newfilepath, $newfilename)) {
2528 // Remember original file source field.
2529 $source = @unserialize($file->get_source());
2530 // Remember the original sortorder.
2531 $sortorder = $file->get_sortorder();
2532 if ($tempfile->is_external_file()) {
2533 // New file is a reference. Check that existing file does not have any other files referencing to it
2534 if (isset($source->original) && $fs->search_references_count($source->original)) {
2535 return (object)array('error' => get_string('errordoublereference', 'repository'));
2538 // delete existing file to release filename
2539 $file->delete();
2540 // create new file
2541 $newfile = $fs->create_file_from_storedfile(array('filepath'=>$filepath, 'filename'=>$filename), $tempfile);
2542 // Preserve original file location (stored in source field) for handling references
2543 if (isset($source->original)) {
2544 if (!($newfilesource = @unserialize($newfile->get_source()))) {
2545 $newfilesource = new stdClass();
2547 $newfilesource->original = $source->original;
2548 $newfile->set_source(serialize($newfilesource));
2550 $newfile->set_sortorder($sortorder);
2551 // remove temp file
2552 $tempfile->delete();
2553 return true;
2556 return false;
2560 * Updates a file in draft filearea.
2562 * This function can only update fields filepath, filename, author, license.
2563 * If anything (except filepath) is updated, timemodified is set to current time.
2564 * If filename or filepath is updated the file unconnects from it's origin
2565 * and therefore all references to it will be converted to copies when
2566 * filearea is saved.
2568 * @param int $draftid
2569 * @param string $filepath path to the directory containing the file, or full path in case of directory
2570 * @param string $filename name of the file, or '.' in case of directory
2571 * @param array $updatedata array of fields to change (only filename, filepath, license and/or author can be updated)
2572 * @throws moodle_exception if for any reason file can not be updated (file does not exist, target already exists, etc.)
2574 public static function update_draftfile($draftid, $filepath, $filename, $updatedata) {
2575 global $USER;
2576 $fs = get_file_storage();
2577 $usercontext = context_user::instance($USER->id);
2578 // make sure filename and filepath are present in $updatedata
2579 $updatedata = $updatedata + array('filepath' => $filepath, 'filename' => $filename);
2580 $filemodified = false;
2581 if (!$file = $fs->get_file($usercontext->id, 'user', 'draft', $draftid, $filepath, $filename)) {
2582 if ($filename === '.') {
2583 throw new moodle_exception('foldernotfound', 'repository');
2584 } else {
2585 throw new moodle_exception('filenotfound', 'error');
2588 if (!$file->is_directory()) {
2589 // This is a file
2590 if ($updatedata['filepath'] !== $filepath || $updatedata['filename'] !== $filename) {
2591 // Rename/move file: check that target file name does not exist.
2592 if ($fs->file_exists($usercontext->id, 'user', 'draft', $draftid, $updatedata['filepath'], $updatedata['filename'])) {
2593 throw new moodle_exception('fileexists', 'repository');
2595 if (($filesource = @unserialize($file->get_source())) && isset($filesource->original)) {
2596 unset($filesource->original);
2597 $file->set_source(serialize($filesource));
2599 $file->rename($updatedata['filepath'], $updatedata['filename']);
2600 // timemodified is updated only when file is renamed and not updated when file is moved.
2601 $filemodified = $filemodified || ($updatedata['filename'] !== $filename);
2603 if (array_key_exists('license', $updatedata) && $updatedata['license'] !== $file->get_license()) {
2604 // Update license and timemodified.
2605 $file->set_license($updatedata['license']);
2606 $filemodified = true;
2608 if (array_key_exists('author', $updatedata) && $updatedata['author'] !== $file->get_author()) {
2609 // Update author and timemodified.
2610 $file->set_author($updatedata['author']);
2611 $filemodified = true;
2613 // Update timemodified:
2614 if ($filemodified) {
2615 $file->set_timemodified(time());
2617 } else {
2618 // This is a directory - only filepath can be updated for a directory (it was moved).
2619 if ($updatedata['filepath'] === $filepath) {
2620 // nothing to update
2621 return;
2623 if ($fs->file_exists($usercontext->id, 'user', 'draft', $draftid, $updatedata['filepath'], '.')) {
2624 // bad luck, we can not rename if something already exists there
2625 throw new moodle_exception('folderexists', 'repository');
2627 $xfilepath = preg_quote($filepath, '|');
2628 if (preg_match("|^$xfilepath|", $updatedata['filepath'])) {
2629 // we can not move folder to it's own subfolder
2630 throw new moodle_exception('folderrecurse', 'repository');
2633 // If directory changed the name, update timemodified.
2634 $filemodified = (basename(rtrim($file->get_filepath(), '/')) !== basename(rtrim($updatedata['filepath'], '/')));
2636 // Now update directory and all children.
2637 $files = $fs->get_area_files($usercontext->id, 'user', 'draft', $draftid);
2638 foreach ($files as $f) {
2639 if (preg_match("|^$xfilepath|", $f->get_filepath())) {
2640 $path = preg_replace("|^$xfilepath|", $updatedata['filepath'], $f->get_filepath());
2641 if (($filesource = @unserialize($f->get_source())) && isset($filesource->original)) {
2642 // unset original so the references are not shown any more
2643 unset($filesource->original);
2644 $f->set_source(serialize($filesource));
2646 $f->rename($path, $f->get_filename());
2647 if ($filemodified && $f->get_filepath() === $updatedata['filepath'] && $f->get_filename() === $filename) {
2648 $f->set_timemodified(time());
2656 * Delete a temp file from draft area
2658 * @param int $draftitemid
2659 * @param string $filepath
2660 * @param string $filename
2661 * @return bool
2663 public static function delete_tempfile_from_draft($draftitemid, $filepath, $filename) {
2664 global $USER;
2665 $fs = get_file_storage();
2666 $user_context = context_user::instance($USER->id);
2667 if ($file = $fs->get_file($user_context->id, 'user', 'draft', $draftitemid, $filepath, $filename)) {
2668 $file->delete();
2669 return true;
2670 } else {
2671 return false;
2676 * Find all external files in this repo and import them
2678 public function convert_references_to_local() {
2679 $fs = get_file_storage();
2680 $files = $fs->get_external_files($this->id);
2681 foreach ($files as $storedfile) {
2682 $fs->import_external_file($storedfile);
2687 * Method deprecated, cache is handled by MUC now.
2688 * @deprecated since 2.6
2690 public static function reset_caches() {
2691 debugging('Function repository::reset_caches() is deprecated.', DEBUG_DEVELOPER);
2695 * Method deprecated
2696 * @deprecated since 2.6
2697 * @see repository::sync_reference()
2699 public static function sync_external_file($file, $resetsynchistory = false) {
2700 debugging('Function repository::sync_external_file() is deprecated.',
2701 DEBUG_DEVELOPER);
2702 if ($resetsynchistory || !$file || !$file->get_repository_id() ||
2703 !($repository = self::get_repository_by_id($file->get_repository_id(), SYSCONTEXTID))) {
2704 return false;
2706 return $repository->sync_reference($file);
2710 * Performs synchronisation of an external file if the previous one has expired.
2712 * This function must be implemented for external repositories supporting
2713 * FILE_REFERENCE, it is called for existing aliases when their filesize,
2714 * contenthash or timemodified are requested. It is not called for internal
2715 * repositories (see {@link repository::has_moodle_files()}), references to
2716 * internal files are updated immediately when source is modified.
2718 * Referenced files may optionally keep their content in Moodle filepool (for
2719 * thumbnail generation or to be able to serve cached copy). In this
2720 * case both contenthash and filesize need to be synchronized. Otherwise repositories
2721 * should use contenthash of empty file and correct filesize in bytes.
2723 * Note that this function may be run for EACH file that needs to be synchronised at the
2724 * moment. If anything is being downloaded or requested from external sources there
2725 * should be a small timeout. The synchronisation is performed to update the size of
2726 * the file and/or to update image and re-generated image preview. There is nothing
2727 * fatal if syncronisation fails but it is fatal if syncronisation takes too long
2728 * and hangs the script generating a page.
2730 * Note: If you wish to call $file->get_filesize(), $file->get_contenthash() or
2731 * $file->get_timemodified() make sure that recursion does not happen.
2733 * Called from {@link stored_file::sync_external_file()}
2735 * @uses stored_file::set_missingsource()
2736 * @uses stored_file::set_synchronized()
2737 * @param stored_file $file
2738 * @return bool false when file does not need synchronisation, true if it was synchronised
2740 public function sync_reference(stored_file $file) {
2741 if ($file->get_repository_id() != $this->id) {
2742 // This should not really happen because the function can be called from stored_file only.
2743 return false;
2746 if ($this->has_moodle_files()) {
2747 // References to local files need to be synchronised only once.
2748 // Later they will be synchronised automatically when the source is changed.
2749 if ($file->get_referencelastsync()) {
2750 return false;
2752 $fs = get_file_storage();
2753 $params = file_storage::unpack_reference($file->get_reference(), true);
2754 if (!is_array($params) || !($storedfile = $fs->get_file($params['contextid'],
2755 $params['component'], $params['filearea'], $params['itemid'], $params['filepath'],
2756 $params['filename']))) {
2757 $file->set_missingsource();
2758 } else {
2759 $file->set_synchronized($storedfile->get_contenthash(), $storedfile->get_filesize());
2761 return true;
2764 // Backward compatibility (Moodle 2.3-2.5) implementation that calls
2765 // methods repository::get_reference_file_lifetime(), repository::sync_individual_file()
2766 // and repository::get_file_by_reference(). These methods are removed from the
2767 // base repository class but may still be implemented by the child classes.
2769 // THIS IS NOT A GOOD EXAMPLE of implementation. For good examples see the overwriting methods.
2771 if (!method_exists($this, 'get_file_by_reference')) {
2772 // Function get_file_by_reference() is not implemented. No synchronisation.
2773 return false;
2776 // Check if the previous sync result is still valid.
2777 if (method_exists($this, 'get_reference_file_lifetime')) {
2778 $lifetime = $this->get_reference_file_lifetime($file->get_reference());
2779 } else {
2780 // Default value that was hardcoded in Moodle 2.3 - 2.5.
2781 $lifetime = 60 * 60 * 24;
2783 if (($lastsynced = $file->get_referencelastsync()) && $lastsynced + $lifetime >= time()) {
2784 return false;
2787 $cache = cache::make('core', 'repositories');
2788 if (($lastsyncresult = $cache->get('sync:'.$file->get_referencefileid())) !== false) {
2789 if ($lastsyncresult === true) {
2790 // We are in the process of synchronizing this reference.
2791 // Avoid recursion when calling $file->get_filesize() and $file->get_contenthash().
2792 return false;
2793 } else {
2794 // We have synchronised the same reference inside this request already.
2795 // It looks like the object $file was created before the synchronisation and contains old data.
2796 if (!empty($lastsyncresult['missing'])) {
2797 $file->set_missingsource();
2798 } else {
2799 $cache->set('sync:'.$file->get_referencefileid(), true);
2800 if ($file->get_contenthash() != $lastsyncresult['contenthash'] ||
2801 $file->get_filesize() != $lastsyncresult['filesize']) {
2802 $file->set_synchronized($lastsyncresult['contenthash'], $lastsyncresult['filesize']);
2804 $cache->set('sync:'.$file->get_referencefileid(), $lastsyncresult);
2806 return true;
2810 // Weird function sync_individual_file() that was present in API in 2.3 - 2.5, default value was true.
2811 if (method_exists($this, 'sync_individual_file') && !$this->sync_individual_file($file)) {
2812 return false;
2815 // Set 'true' into the cache to indicate that file is in the process of synchronisation.
2816 $cache->set('sync:'.$file->get_referencefileid(), true);
2818 // Create object with the structure that repository::get_file_by_reference() expects.
2819 $reference = new stdClass();
2820 $reference->id = $file->get_referencefileid();
2821 $reference->reference = $file->get_reference();
2822 $reference->referencehash = sha1($file->get_reference());
2823 $reference->lastsync = $file->get_referencelastsync();
2824 $reference->lifetime = $lifetime;
2826 $fileinfo = $this->get_file_by_reference($reference);
2828 $contenthash = null;
2829 $filesize = null;
2830 $fs = get_file_storage();
2831 if (!empty($fileinfo->filesize)) {
2832 // filesize returned
2833 if (!empty($fileinfo->contenthash) && $fs->content_exists($fileinfo->contenthash)) {
2834 // contenthash is specified and valid
2835 $contenthash = $fileinfo->contenthash;
2836 } else if ($fileinfo->filesize == $file->get_filesize()) {
2837 // we don't know the new contenthash but the filesize did not change,
2838 // assume the contenthash did not change either
2839 $contenthash = $file->get_contenthash();
2840 } else {
2841 // we can't save empty contenthash so generate contenthash from empty string
2842 list($contenthash, $unused1, $unused2) = $fs->add_string_to_pool('');
2844 $filesize = $fileinfo->filesize;
2845 } else if (!empty($fileinfo->filepath)) {
2846 // File path returned
2847 list($contenthash, $filesize, $newfile) = $fs->add_file_to_pool($fileinfo->filepath);
2848 } else if (!empty($fileinfo->handle) && is_resource($fileinfo->handle)) {
2849 // File handle returned
2850 $contents = '';
2851 while (!feof($fileinfo->handle)) {
2852 $contents .= fread($fileinfo->handle, 8192);
2854 fclose($fileinfo->handle);
2855 list($contenthash, $filesize, $newfile) = $fs->add_string_to_pool($contents);
2856 } else if (isset($fileinfo->content)) {
2857 // File content returned
2858 list($contenthash, $filesize, $newfile) = $fs->add_string_to_pool($fileinfo->content);
2861 if (!isset($contenthash) or !isset($filesize)) {
2862 $file->set_missingsource(null);
2863 $cache->set('sync:'.$file->get_referencefileid(), array('missing' => true));
2864 } else {
2865 // update files table
2866 $file->set_synchronized($contenthash, $filesize);
2867 $cache->set('sync:'.$file->get_referencefileid(),
2868 array('contenthash' => $contenthash, 'filesize' => $filesize));
2871 return true;
2875 * Build draft file's source field
2877 * {@link file_restore_source_field_from_draft_file()}
2878 * XXX: This is a hack for file manager (MDL-28666)
2879 * For newly created draft files we have to construct
2880 * source filed in php serialized data format.
2881 * File manager needs to know the original file information before copying
2882 * to draft area, so we append these information in mdl_files.source field
2884 * @param string $source
2885 * @return string serialised source field
2887 public static function build_source_field($source) {
2888 $sourcefield = new stdClass;
2889 $sourcefield->source = $source;
2890 return serialize($sourcefield);
2894 * Prepares the repository to be cached. Implements method from cacheable_object interface.
2896 * @return array
2898 public function prepare_to_cache() {
2899 return array(
2900 'class' => get_class($this),
2901 'id' => $this->id,
2902 'ctxid' => $this->context->id,
2903 'options' => $this->options,
2904 'readonly' => $this->readonly
2909 * Restores the repository from cache. Implements method from cacheable_object interface.
2911 * @return array
2913 public static function wake_from_cache($data) {
2914 $classname = $data['class'];
2915 return new $classname($data['id'], $data['ctxid'], $data['options'], $data['readonly']);
2919 * Gets a file relative to this file in the repository and sends it to the browser.
2920 * Used to allow relative file linking within a repository without creating file records
2921 * for linked files
2923 * Repositories that overwrite this must be very careful - see filesystem repository for example.
2925 * @param stored_file $mainfile The main file we are trying to access relative files for.
2926 * @param string $relativepath the relative path to the file we are trying to access.
2929 public function send_relative_file(stored_file $mainfile, $relativepath) {
2930 // This repository hasn't implemented this so send_file_not_found.
2931 send_file_not_found();
2935 * helper function to check if the repository supports send_relative_file.
2937 * @return true|false
2939 public function supports_relative_file() {
2940 return false;
2945 * Exception class for repository api
2947 * @since 2.0
2948 * @package core_repository
2949 * @copyright 2009 Dongsheng Cai {@link http://dongsheng.org}
2950 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2952 class repository_exception extends moodle_exception {
2956 * This is a class used to define a repository instance form
2958 * @since 2.0
2959 * @package core_repository
2960 * @copyright 2009 Dongsheng Cai {@link http://dongsheng.org}
2961 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2963 final class repository_instance_form extends moodleform {
2964 /** @var stdClass repository instance */
2965 protected $instance;
2966 /** @var string repository plugin type */
2967 protected $plugin;
2970 * Added defaults to moodle form
2972 protected function add_defaults() {
2973 $mform =& $this->_form;
2974 $strrequired = get_string('required');
2976 $mform->addElement('hidden', 'edit', ($this->instance) ? $this->instance->id : 0);
2977 $mform->setType('edit', PARAM_INT);
2978 $mform->addElement('hidden', 'new', $this->plugin);
2979 $mform->setType('new', PARAM_ALPHANUMEXT);
2980 $mform->addElement('hidden', 'plugin', $this->plugin);
2981 $mform->setType('plugin', PARAM_PLUGIN);
2982 $mform->addElement('hidden', 'typeid', $this->typeid);
2983 $mform->setType('typeid', PARAM_INT);
2984 $mform->addElement('hidden', 'contextid', $this->contextid);
2985 $mform->setType('contextid', PARAM_INT);
2987 $mform->addElement('text', 'name', get_string('name'), 'maxlength="100" size="30"');
2988 $mform->addRule('name', $strrequired, 'required', null, 'client');
2989 $mform->setType('name', PARAM_TEXT);
2993 * Define moodle form elements
2995 public function definition() {
2996 global $CFG;
2997 // type of plugin, string
2998 $this->plugin = $this->_customdata['plugin'];
2999 $this->typeid = $this->_customdata['typeid'];
3000 $this->contextid = $this->_customdata['contextid'];
3001 $this->instance = (isset($this->_customdata['instance'])
3002 && is_subclass_of($this->_customdata['instance'], 'repository'))
3003 ? $this->_customdata['instance'] : null;
3005 $mform =& $this->_form;
3007 $this->add_defaults();
3009 // Add instance config options.
3010 $result = repository::static_function($this->plugin, 'instance_config_form', $mform);
3011 if ($result === false) {
3012 // Remove the name element if no other config options.
3013 $mform->removeElement('name');
3015 if ($this->instance) {
3016 $data = array();
3017 $data['name'] = $this->instance->name;
3018 if (!$this->instance->readonly) {
3019 // and set the data if we have some.
3020 foreach ($this->instance->get_instance_option_names() as $config) {
3021 if (!empty($this->instance->options[$config])) {
3022 $data[$config] = $this->instance->options[$config];
3023 } else {
3024 $data[$config] = '';
3028 $this->set_data($data);
3031 if ($result === false) {
3032 $mform->addElement('cancel');
3033 } else {
3034 $this->add_action_buttons(true, get_string('save','repository'));
3039 * Validate moodle form data
3041 * @param array $data form data
3042 * @param array $files files in form
3043 * @return array errors
3045 public function validation($data, $files) {
3046 global $DB;
3047 $errors = array();
3048 $plugin = $this->_customdata['plugin'];
3049 $instance = (isset($this->_customdata['instance'])
3050 && is_subclass_of($this->_customdata['instance'], 'repository'))
3051 ? $this->_customdata['instance'] : null;
3053 if (!$instance) {
3054 $errors = repository::static_function($plugin, 'instance_form_validation', $this, $data, $errors);
3055 } else {
3056 $errors = $instance->instance_form_validation($this, $data, $errors);
3059 $sql = "SELECT count('x')
3060 FROM {repository_instances} i, {repository} r
3061 WHERE r.type=:plugin AND r.id=i.typeid AND i.name=:name AND i.contextid=:contextid";
3062 $params = array('name' => $data['name'], 'plugin' => $this->plugin, 'contextid' => $this->contextid);
3063 if ($instance) {
3064 $sql .= ' AND i.id != :instanceid';
3065 $params['instanceid'] = $instance->id;
3067 if ($DB->count_records_sql($sql, $params) > 0) {
3068 $errors['name'] = get_string('erroruniquename', 'repository');
3071 return $errors;
3076 * This is a class used to define a repository type setting form
3078 * @since 2.0
3079 * @package core_repository
3080 * @copyright 2009 Dongsheng Cai {@link http://dongsheng.org}
3081 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3083 final class repository_type_form extends moodleform {
3084 /** @var stdClass repository instance */
3085 protected $instance;
3086 /** @var string repository plugin name */
3087 protected $plugin;
3088 /** @var string action */
3089 protected $action;
3092 * Definition of the moodleform
3094 public function definition() {
3095 global $CFG;
3096 // type of plugin, string
3097 $this->plugin = $this->_customdata['plugin'];
3098 $this->instance = (isset($this->_customdata['instance'])
3099 && is_a($this->_customdata['instance'], 'repository_type'))
3100 ? $this->_customdata['instance'] : null;
3102 $this->action = $this->_customdata['action'];
3103 $this->pluginname = $this->_customdata['pluginname'];
3104 $mform =& $this->_form;
3105 $strrequired = get_string('required');
3107 $mform->addElement('hidden', 'action', $this->action);
3108 $mform->setType('action', PARAM_TEXT);
3109 $mform->addElement('hidden', 'repos', $this->plugin);
3110 $mform->setType('repos', PARAM_PLUGIN);
3112 // let the plugin add its specific fields
3113 $classname = 'repository_' . $this->plugin;
3114 require_once($CFG->dirroot . '/repository/' . $this->plugin . '/lib.php');
3115 //add "enable course/user instances" checkboxes if multiple instances are allowed
3116 $instanceoptionnames = repository::static_function($this->plugin, 'get_instance_option_names');
3118 $result = call_user_func(array($classname, 'type_config_form'), $mform, $classname);
3120 if (!empty($instanceoptionnames)) {
3121 $sm = get_string_manager();
3122 $component = 'repository';
3123 if ($sm->string_exists('enablecourseinstances', 'repository_' . $this->plugin)) {
3124 $component .= ('_' . $this->plugin);
3126 $mform->addElement('checkbox', 'enablecourseinstances', get_string('enablecourseinstances', $component));
3127 $mform->setType('enablecourseinstances', PARAM_BOOL);
3129 $component = 'repository';
3130 if ($sm->string_exists('enableuserinstances', 'repository_' . $this->plugin)) {
3131 $component .= ('_' . $this->plugin);
3133 $mform->addElement('checkbox', 'enableuserinstances', get_string('enableuserinstances', $component));
3134 $mform->setType('enableuserinstances', PARAM_BOOL);
3137 // set the data if we have some.
3138 if ($this->instance) {
3139 $data = array();
3140 $option_names = call_user_func(array($classname,'get_type_option_names'));
3141 if (!empty($instanceoptionnames)){
3142 $option_names[] = 'enablecourseinstances';
3143 $option_names[] = 'enableuserinstances';
3146 $instanceoptions = $this->instance->get_options();
3147 foreach ($option_names as $config) {
3148 if (!empty($instanceoptions[$config])) {
3149 $data[$config] = $instanceoptions[$config];
3150 } else {
3151 $data[$config] = '';
3154 // XXX: set plugin name for plugins which doesn't have muliti instances
3155 if (empty($instanceoptionnames)){
3156 $data['pluginname'] = $this->pluginname;
3158 $this->set_data($data);
3161 $this->add_action_buttons(true, get_string('save','repository'));
3165 * Validate moodle form data
3167 * @param array $data moodle form data
3168 * @param array $files
3169 * @return array errors
3171 public function validation($data, $files) {
3172 $errors = array();
3173 $plugin = $this->_customdata['plugin'];
3174 $instance = (isset($this->_customdata['instance'])
3175 && is_subclass_of($this->_customdata['instance'], 'repository'))
3176 ? $this->_customdata['instance'] : null;
3177 if (!$instance) {
3178 $errors = repository::static_function($plugin, 'type_form_validation', $this, $data, $errors);
3179 } else {
3180 $errors = $instance->type_form_validation($this, $data, $errors);
3183 return $errors;
3188 * Generate all options needed by filepicker
3190 * @param array $args including following keys
3191 * context
3192 * accepted_types
3193 * return_types
3195 * @return array the list of repository instances, including meta infomation, containing the following keys
3196 * externallink
3197 * repositories
3198 * accepted_types
3200 function initialise_filepicker($args) {
3201 global $CFG, $USER, $PAGE, $OUTPUT;
3202 static $templatesinitialized = array();
3203 require_once($CFG->libdir . '/licenselib.php');
3205 $return = new stdClass();
3206 $licenses = array();
3207 if (!empty($CFG->licenses)) {
3208 $array = explode(',', $CFG->licenses);
3209 foreach ($array as $license) {
3210 $l = new stdClass();
3211 $l->shortname = $license;
3212 $l->fullname = get_string($license, 'license');
3213 $licenses[] = $l;
3216 if (!empty($CFG->sitedefaultlicense)) {
3217 $return->defaultlicense = $CFG->sitedefaultlicense;
3220 $return->licenses = $licenses;
3222 $return->author = fullname($USER);
3224 if (empty($args->context)) {
3225 $context = $PAGE->context;
3226 } else {
3227 $context = $args->context;
3229 $disable_types = array();
3230 if (!empty($args->disable_types)) {
3231 $disable_types = $args->disable_types;
3234 $user_context = context_user::instance($USER->id);
3236 list($context, $course, $cm) = get_context_info_array($context->id);
3237 $contexts = array($user_context, context_system::instance());
3238 if (!empty($course)) {
3239 // adding course context
3240 $contexts[] = context_course::instance($course->id);
3242 $externallink = (int)get_config(null, 'repositoryallowexternallinks');
3243 $repositories = repository::get_instances(array(
3244 'context'=>$contexts,
3245 'currentcontext'=> $context,
3246 'accepted_types'=>$args->accepted_types,
3247 'return_types'=>$args->return_types,
3248 'disable_types'=>$disable_types
3251 $return->repositories = array();
3253 if (empty($externallink)) {
3254 $return->externallink = false;
3255 } else {
3256 $return->externallink = true;
3259 $return->userprefs = array();
3260 $return->userprefs['recentrepository'] = get_user_preferences('filepicker_recentrepository', '');
3261 $return->userprefs['recentlicense'] = get_user_preferences('filepicker_recentlicense', '');
3262 $return->userprefs['recentviewmode'] = get_user_preferences('filepicker_recentviewmode', '');
3264 user_preference_allow_ajax_update('filepicker_recentrepository', PARAM_INT);
3265 user_preference_allow_ajax_update('filepicker_recentlicense', PARAM_SAFEDIR);
3266 user_preference_allow_ajax_update('filepicker_recentviewmode', PARAM_INT);
3269 // provided by form element
3270 $return->accepted_types = file_get_typegroup('extension', $args->accepted_types);
3271 $return->return_types = $args->return_types;
3272 $templates = array();
3273 foreach ($repositories as $repository) {
3274 $meta = $repository->get_meta();
3275 // Please note that the array keys for repositories are used within
3276 // JavaScript a lot, the key NEEDS to be the repository id.
3277 $return->repositories[$repository->id] = $meta;
3278 // Register custom repository template if it has one
3279 if(method_exists($repository, 'get_upload_template') && !array_key_exists('uploadform_' . $meta->type, $templatesinitialized)) {
3280 $templates['uploadform_' . $meta->type] = $repository->get_upload_template();
3281 $templatesinitialized['uploadform_' . $meta->type] = true;
3284 if (!array_key_exists('core', $templatesinitialized)) {
3285 // we need to send each filepicker template to the browser just once
3286 $fprenderer = $PAGE->get_renderer('core', 'files');
3287 $templates = array_merge($templates, $fprenderer->filepicker_js_templates());
3288 $templatesinitialized['core'] = true;
3290 if (sizeof($templates)) {
3291 $PAGE->requires->js_init_call('M.core_filepicker.set_templates', array($templates), true);
3293 return $return;