2 // This file is part of Moodle - http://moodle.org/
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.
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/>.
18 * This file contains classes used to manage the repository plugins in Moodle
19 * and was introduced as part of the changes occuring in Moodle 2.0
23 * @copyright 2009 Dongsheng Cai {@link http://dongsheng.org}
24 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
27 require_once(dirname(dirname(__FILE__)) . '/config.php');
28 require_once($CFG->libdir . '/filelib.php');
29 require_once($CFG->libdir . '/formslib.php');
31 define('FILE_EXTERNAL', 1);
32 define('FILE_INTERNAL', 2);
33 define('FILE_REFERENCE', 4);
34 define('RENAME_SUFFIX', '_2');
37 * This class is used to manage repository plugins
39 * A repository_type is a repository plug-in. It can be Box.net, Flick-r, ...
40 * A repository type can be edited, sorted and hidden. It is mandatory for an
41 * administrator to create a repository type in order to be able to create
42 * some instances of this type.
44 * - a repository_type object is mapped to the "repository" database table
45 * - "typename" attibut maps the "type" database field. It is unique.
46 * - general "options" for a repository type are saved in the config_plugin table
47 * - when you delete a repository, all instances are deleted, and general
48 * options are also deleted from database
49 * - When you create a type for a plugin that can't have multiple instances, a
50 * instance is automatically created.
53 * @copyright 2009 Jerome Mouneyrac
54 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
56 class repository_type {
60 * Type name (no whitespace) - A type name is unique
61 * Note: for a user-friendly type name see get_readablename()
68 * Options of this type
69 * They are general options that any instance of this type would share
71 * These options are saved in config_plugin table
78 * Is the repository type visible or hidden
79 * If false (hidden): no instances can be created, edited, deleted, showned , used...
86 * 0 => not ordered, 1 => first position, 2 => second position...
87 * A not order type would appear in first position (should never happened)
93 * Return if the instance is visible in a context
95 * @todo check if the context visibility has been overwritten by the plugin creator
96 * (need to create special functions to be overvwritten in repository class)
97 * @param stdClass $context context
100 public function get_contextvisibility($context) {
103 if ($context->contextlevel == CONTEXT_COURSE) {
104 return $this->_options['enablecourseinstances'];
107 if ($context->contextlevel == CONTEXT_USER) {
108 return $this->_options['enableuserinstances'];
111 //the context is SITE
118 * repository_type constructor
120 * @param int $typename
121 * @param array $typeoptions
122 * @param bool $visible
123 * @param int $sortorder (don't really need set, it will be during create() call)
125 public function __construct($typename = '', $typeoptions = array(), $visible = true, $sortorder = 0) {
129 $this->_typename = $typename;
130 $this->_visible = $visible;
131 $this->_sortorder = $sortorder;
133 //set options attribut
134 $this->_options = array();
135 $options = repository::static_function($typename, 'get_type_option_names');
136 //check that the type can be setup
137 if (!empty($options)) {
138 //set the type options
139 foreach ($options as $config) {
140 if (array_key_exists($config, $typeoptions)) {
141 $this->_options[$config] = $typeoptions[$config];
146 //retrieve visibility from option
147 if (array_key_exists('enablecourseinstances',$typeoptions)) {
148 $this->_options['enablecourseinstances'] = $typeoptions['enablecourseinstances'];
150 $this->_options['enablecourseinstances'] = 0;
153 if (array_key_exists('enableuserinstances',$typeoptions)) {
154 $this->_options['enableuserinstances'] = $typeoptions['enableuserinstances'];
156 $this->_options['enableuserinstances'] = 0;
162 * Get the type name (no whitespace)
163 * For a human readable name, use get_readablename()
165 * @return string the type name
167 public function get_typename() {
168 return $this->_typename;
172 * Return a human readable and user-friendly type name
174 * @return string user-friendly type name
176 public function get_readablename() {
177 return get_string('pluginname','repository_'.$this->_typename);
181 * Return general options
183 * @return array the general options
185 public function get_options() {
186 return $this->_options;
194 public function get_visible() {
195 return $this->_visible;
199 * Return order / position of display in the file picker
203 public function get_sortorder() {
204 return $this->_sortorder;
208 * Create a repository type (the type name must not already exist)
209 * @param bool $silent throw exception?
210 * @return mixed return int if create successfully, return false if
212 public function create($silent = false) {
215 //check that $type has been set
216 $timmedtype = trim($this->_typename);
217 if (empty($timmedtype)) {
218 throw new repository_exception('emptytype', 'repository');
221 //set sortorder as the last position in the list
222 if (!isset($this->_sortorder) || $this->_sortorder == 0 ) {
223 $sql = "SELECT MAX(sortorder) FROM {repository}";
224 $this->_sortorder = 1 + $DB->get_field_sql($sql);
227 //only create a new type if it doesn't already exist
228 $existingtype = $DB->get_record('repository', array('type'=>$this->_typename));
229 if (!$existingtype) {
231 $newtype = new stdClass();
232 $newtype->type = $this->_typename;
233 $newtype->visible = $this->_visible;
234 $newtype->sortorder = $this->_sortorder;
235 $plugin_id = $DB->insert_record('repository', $newtype);
236 //save the options in DB
237 $this->update_options();
239 $instanceoptionnames = repository::static_function($this->_typename, 'get_instance_option_names');
241 //if the plugin type has no multiple instance (e.g. has no instance option name) so it wont
242 //be possible for the administrator to create a instance
243 //in this case we need to create an instance
244 if (empty($instanceoptionnames)) {
245 $instanceoptions = array();
246 if (empty($this->_options['pluginname'])) {
247 // when moodle trying to install some repo plugin automatically
248 // this option will be empty, get it from language string when display
249 $instanceoptions['name'] = '';
251 // when admin trying to add a plugin manually, he will type a name
253 $instanceoptions['name'] = $this->_options['pluginname'];
255 repository::static_function($this->_typename, 'create', $this->_typename, 0, get_system_context(), $instanceoptions);
257 //run plugin_init function
258 if (!repository::static_function($this->_typename, 'plugin_init')) {
260 throw new repository_exception('cannotinitplugin', 'repository');
264 if(!empty($plugin_id)) {
265 // return plugin_id if create successfully
273 throw new repository_exception('existingrepository', 'repository');
275 // If plugin existed, return false, tell caller no new plugins were created.
282 * Update plugin options into the config_plugin table
284 * @param array $options
287 public function update_options($options = null) {
289 $classname = 'repository_' . $this->_typename;
290 $instanceoptions = repository::static_function($this->_typename, 'get_instance_option_names');
291 if (empty($instanceoptions)) {
292 // update repository instance name if this plugin type doesn't have muliti instances
294 $params['type'] = $this->_typename;
295 $instances = repository::get_instances($params);
296 $instance = array_pop($instances);
298 $DB->set_field('repository_instances', 'name', $options['pluginname'], array('id'=>$instance->id));
300 unset($options['pluginname']);
303 if (!empty($options)) {
304 $this->_options = $options;
307 foreach ($this->_options as $name => $value) {
308 set_config($name, $value, $this->_typename);
315 * Update visible database field with the value given as parameter
316 * or with the visible value of this object
317 * This function is private.
318 * For public access, have a look to switch_and_update_visibility()
320 * @param bool $visible
323 private function update_visible($visible = null) {
326 if (!empty($visible)) {
327 $this->_visible = $visible;
329 else if (!isset($this->_visible)) {
330 throw new repository_exception('updateemptyvisible', 'repository');
333 return $DB->set_field('repository', 'visible', $this->_visible, array('type'=>$this->_typename));
337 * Update database sortorder field with the value given as parameter
338 * or with the sortorder value of this object
339 * This function is private.
340 * For public access, have a look to move_order()
342 * @param int $sortorder
345 private function update_sortorder($sortorder = null) {
348 if (!empty($sortorder) && $sortorder!=0) {
349 $this->_sortorder = $sortorder;
351 //if sortorder is not set, we set it as the ;ast position in the list
352 else if (!isset($this->_sortorder) || $this->_sortorder == 0 ) {
353 $sql = "SELECT MAX(sortorder) FROM {repository}";
354 $this->_sortorder = 1 + $DB->get_field_sql($sql);
357 return $DB->set_field('repository', 'sortorder', $this->_sortorder, array('type'=>$this->_typename));
361 * Change order of the type with its adjacent upper or downer type
362 * (database fields are updated)
364 * 1. retrieve all types in an array. This array is sorted by sortorder,
365 * and the array keys start from 0 to X (incremented by 1)
366 * 2. switch sortorder values of this type and its adjacent type
368 * @param string $move "up" or "down"
370 public function move_order($move) {
373 $types = repository::get_types(); // retrieve all types
375 // retrieve this type into the returned array
377 while (!isset($indice) && $i<count($types)) {
378 if ($types[$i]->get_typename() == $this->_typename) {
384 // retrieve adjacent indice
387 $adjacentindice = $indice - 1;
390 $adjacentindice = $indice + 1;
393 throw new repository_exception('movenotdefined', 'repository');
396 //switch sortorder of this type and the adjacent type
397 //TODO: we could reset sortorder for all types. This is not as good in performance term, but
398 //that prevent from wrong behaviour on a screwed database. As performance are not important in this particular case
399 //it worth to change the algo.
400 if ($adjacentindice>=0 && !empty($types[$adjacentindice])) {
401 $DB->set_field('repository', 'sortorder', $this->_sortorder, array('type'=>$types[$adjacentindice]->get_typename()));
402 $this->update_sortorder($types[$adjacentindice]->get_sortorder());
407 * 1. Change visibility to the value chosen
410 * @param bool $visible
413 public function update_visibility($visible = null) {
414 if (is_bool($visible)) {
415 $this->_visible = $visible;
417 $this->_visible = !$this->_visible;
419 return $this->update_visible();
424 * Delete a repository_type (general options are removed from config_plugin
425 * table, and all instances are deleted)
427 * @param bool $downloadcontents download external contents if exist
430 public function delete($downloadcontents = false) {
433 //delete all instances of this type
435 $params['context'] = array();
436 $params['onlyvisible'] = false;
437 $params['type'] = $this->_typename;
438 $instances = repository::get_instances($params);
439 foreach ($instances as $instance) {
440 $instance->delete($downloadcontents);
443 //delete all general options
444 foreach ($this->_options as $name => $value) {
445 set_config($name, null, $this->_typename);
449 $DB->delete_records('repository', array('type' => $this->_typename));
450 } catch (dml_exception $ex) {
458 * This is the base class of the repository class.
460 * To create repository plugin, see: {@link http://docs.moodle.org/dev/Repository_plugins}
461 * See an example: {@link repository_boxnet}
463 * @package repository
464 * @category repository
465 * @copyright 2009 Dongsheng Cai {@link http://dongsheng.org}
466 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
468 abstract class repository {
469 // $disabled can be set to true to disable a plugin by force
470 // example: self::$disabled = true
471 /** @var bool force disable repository instance */
472 public $disabled = false;
473 /** @var int repository instance id */
475 /** @var stdClass current context */
477 /** @var array repository options */
479 /** @var bool Whether or not the repository instance is editable */
481 /** @var int return types */
483 /** @var stdClass repository instance database record */
488 * @param int $repositoryid repository instance id
489 * @param int|stdClass $context a context id or context object
490 * @param array $options repository options
491 * @param int $readonly indicate this repo is readonly or not
493 public function __construct($repositoryid, $context = SYSCONTEXTID, $options = array(), $readonly = 0) {
495 $this->id = $repositoryid;
496 if (is_object($context)) {
497 $this->context = $context;
499 $this->context = get_context_instance_by_id($context);
501 $this->instance = $DB->get_record('repository_instances', array('id'=>$this->id));
502 $this->readonly = $readonly;
503 $this->options = array();
505 if (is_array($options)) {
506 // The get_option() method will get stored options in database.
507 $options = array_merge($this->get_option(), $options);
509 $options = $this->get_option();
511 foreach ($options as $n => $v) {
512 $this->options[$n] = $v;
514 $this->name = $this->get_name();
515 $this->returntypes = $this->supported_returntypes();
516 $this->super_called = true;
520 * Get repository instance using repository id
522 * @param int $repositoryid repository ID
523 * @param stdClass|int $context context instance or context ID
526 public static function get_repository_by_id($repositoryid, $context) {
529 $sql = 'SELECT i.name, i.typeid, r.type FROM {repository} r, {repository_instances} i WHERE i.id=? AND i.typeid=r.id';
531 if (!$record = $DB->get_record_sql($sql, array($repositoryid))) {
532 throw new repository_exception('invalidrepositoryid', 'repository');
534 $type = $record->type;
535 if (file_exists($CFG->dirroot . "/repository/$type/lib.php")) {
536 require_once($CFG->dirroot . "/repository/$type/lib.php");
537 $classname = 'repository_' . $type;
538 $contextid = $context;
539 if (is_object($context)) {
540 $contextid = $context->id;
542 $repository = new $classname($repositoryid, $contextid, array('type'=>$type));
545 throw new moodle_exception('error');
551 * Get a repository type object by a given type name.
554 * @param string $typename the repository type name
555 * @return repository_type|bool
557 public static function get_type_by_typename($typename) {
560 if (!$record = $DB->get_record('repository',array('type' => $typename))) {
564 return new repository_type($typename, (array)get_config($typename), $record->visible, $record->sortorder);
568 * Get the repository type by a given repository type id.
571 * @param int $id the type id
574 public static function get_type_by_id($id) {
577 if (!$record = $DB->get_record('repository',array('id' => $id))) {
581 return new repository_type($record->type, (array)get_config($record->type), $record->visible, $record->sortorder);
585 * Return all repository types ordered by sortorder field
586 * first repository type in returnedarray[0], second repository type in returnedarray[1], ...
589 * @param bool $visible can return types by visiblity, return all types if null
590 * @return array Repository types
592 public static function get_types($visible=null) {
597 if (!empty($visible)) {
598 $params = array('visible' => $visible);
600 if ($records = $DB->get_records('repository',$params,'sortorder')) {
601 foreach($records as $type) {
602 if (file_exists($CFG->dirroot . '/repository/'. $type->type .'/lib.php')) {
603 $types[] = new repository_type($type->type, (array)get_config($type->type), $type->visible, $type->sortorder);
612 * To check if the context id is valid
615 * @param int $contextid
616 * @param stdClass $instance
619 public static function check_capability($contextid, $instance) {
620 $context = get_context_instance_by_id($contextid);
621 $capability = has_capability('repository/'.$instance->type.':view', $context);
623 throw new repository_exception('nopermissiontoaccess', 'repository');
628 * Check if file already exists in draft area
632 * @param string $filepath
633 * @param string $filename
636 public static function draftfile_exists($itemid, $filepath, $filename) {
638 $fs = get_file_storage();
639 $usercontext = get_context_instance(CONTEXT_USER, $USER->id);
640 if ($fs->get_file($usercontext->id, 'user', 'draft', $itemid, $filepath, $filename)) {
648 * Parses the 'source' returned by moodle repositories and returns an instance of stored_file
650 * @param string $source
651 * @return stored_file|null
653 public static function get_moodle_file($source) {
654 $params = file_storage::unpack_reference($source, true);
655 $fs = get_file_storage();
656 return $fs->get_file($params['contextid'], $params['component'], $params['filearea'],
657 $params['itemid'], $params['filepath'], $params['filename']);
661 * Repository method to make sure that user can access particular file.
663 * This is checked when user tries to pick the file from repository to deal with
664 * potential parameter substitutions is request
666 * @param string $source
667 * @return bool whether the file is accessible by current user
669 public function file_is_accessible($source) {
670 if ($this->has_moodle_files()) {
672 $params = file_storage::unpack_reference($source, true);
673 } catch (file_reference_exception $e) {
676 $browser = get_file_browser();
677 $context = get_context_instance_by_id($params['contextid']);
678 $file_info = $browser->get_file_info($context, $params['component'], $params['filearea'],
679 $params['itemid'], $params['filepath'], $params['filename']);
680 return !empty($file_info);
686 * This function is used to copy a moodle file to draft area.
688 * It DOES NOT check if the user is allowed to access this file because the actual file
689 * can be located in the area where user does not have access to but there is an alias
690 * to this file in the area where user CAN access it.
691 * {@link file_is_accessible} should be called for alias location before calling this function.
693 * @param string $source The metainfo of file, it is base64 encoded php serialized data
694 * @param stdClass|array $filerecord contains itemid, filepath, filename and optionally other
695 * attributes of the new file
696 * @param int $maxbytes maximum allowed size of file, -1 if unlimited. If size of file exceeds
697 * the limit, the file_exception is thrown.
698 * @return array The information about the created file
700 public function copy_to_area($source, $filerecord, $maxbytes = -1) {
702 $fs = get_file_storage();
704 if ($this->has_moodle_files() == false) {
705 throw new coding_exception('Only repository used to browse moodle files can use repository::copy_to_area()');
708 $user_context = context_user::instance($USER->id);
710 $filerecord = (array)$filerecord;
711 // make sure the new file will be created in user draft area
712 $filerecord['component'] = 'user';
713 $filerecord['filearea'] = 'draft';
714 $filerecord['contextid'] = $user_context->id;
715 $draftitemid = $filerecord['itemid'];
716 $new_filepath = $filerecord['filepath'];
717 $new_filename = $filerecord['filename'];
719 // the file needs to copied to draft area
720 $stored_file = self::get_moodle_file($source);
721 if ($maxbytes != -1 && $stored_file->get_filesize() > $maxbytes) {
722 throw new file_exception('maxbytes');
725 if (repository::draftfile_exists($draftitemid, $new_filepath, $new_filename)) {
727 $unused_filename = repository::get_unused_filename($draftitemid, $new_filepath, $new_filename);
728 $filerecord['filename'] = $unused_filename;
729 $fs->create_file_from_storedfile($filerecord, $stored_file);
731 $event['event'] = 'fileexists';
732 $event['newfile'] = new stdClass;
733 $event['newfile']->filepath = $new_filepath;
734 $event['newfile']->filename = $unused_filename;
735 $event['newfile']->url = moodle_url::make_draftfile_url($draftitemid, $new_filepath, $unused_filename)->out();
736 $event['existingfile'] = new stdClass;
737 $event['existingfile']->filepath = $new_filepath;
738 $event['existingfile']->filename = $new_filename;
739 $event['existingfile']->url = moodle_url::make_draftfile_url($draftitemid, $new_filepath, $new_filename)->out();
742 $fs->create_file_from_storedfile($filerecord, $stored_file);
744 $info['itemid'] = $draftitemid;
745 $info['file'] = $new_filename;
746 $info['title'] = $new_filename;
747 $info['contextid'] = $user_context->id;
748 $info['url'] = moodle_url::make_draftfile_url($draftitemid, $new_filepath, $new_filename)->out();
749 $info['filesize'] = $stored_file->get_filesize();
755 * Get unused filename by appending suffix
759 * @param string $filepath
760 * @param string $filename
763 public static function get_unused_filename($itemid, $filepath, $filename) {
765 $fs = get_file_storage();
766 while (repository::draftfile_exists($itemid, $filepath, $filename)) {
767 $filename = repository::append_suffix($filename);
773 * Append a suffix to filename
776 * @param string $filename
779 public static function append_suffix($filename) {
780 $pathinfo = pathinfo($filename);
781 if (empty($pathinfo['extension'])) {
782 return $filename . RENAME_SUFFIX;
784 return $pathinfo['filename'] . RENAME_SUFFIX . '.' . $pathinfo['extension'];
789 * Return all types that you a user can create/edit and which are also visible
790 * Note: Mostly used in order to know if at least one editable type can be set
793 * @param stdClass $context the context for which we want the editable types
794 * @return array types
796 public static function get_editable_types($context = null) {
798 if (empty($context)) {
799 $context = get_system_context();
802 $types= repository::get_types(true);
803 $editabletypes = array();
804 foreach ($types as $type) {
805 $instanceoptionnames = repository::static_function($type->get_typename(), 'get_instance_option_names');
806 if (!empty($instanceoptionnames)) {
807 if ($type->get_contextvisibility($context)) {
808 $editabletypes[]=$type;
812 return $editabletypes;
816 * Return repository instances
819 * @param array $args Array containing the following keys:
828 * @return array repository instances
830 public static function get_instances($args = array()) {
831 global $DB, $CFG, $USER;
833 if (isset($args['currentcontext'])) {
834 $current_context = $args['currentcontext'];
836 $current_context = null;
839 if (!empty($args['context'])) {
840 $contexts = $args['context'];
845 $onlyvisible = isset($args['onlyvisible']) ? $args['onlyvisible'] : true;
846 $returntypes = isset($args['return_types']) ? $args['return_types'] : 3;
847 $type = isset($args['type']) ? $args['type'] : null;
850 $sql = "SELECT i.*, r.type AS repositorytype, r.sortorder, r.visible
851 FROM {repository} r, {repository_instances} i
852 WHERE i.typeid = r.id ";
854 if (!empty($args['disable_types']) && is_array($args['disable_types'])) {
855 list($types, $p) = $DB->get_in_or_equal($args['disable_types'], SQL_PARAMS_QM, 'param', false);
856 $sql .= " AND r.type $types";
857 $params = array_merge($params, $p);
860 if (!empty($args['userid']) && is_numeric($args['userid'])) {
861 $sql .= " AND (i.userid = 0 or i.userid = ?)";
862 $params[] = $args['userid'];
865 foreach ($contexts as $context) {
866 if (empty($firstcontext)) {
867 $firstcontext = true;
868 $sql .= " AND ((i.contextid = ?)";
870 $sql .= " OR (i.contextid = ?)";
872 $params[] = $context->id;
875 if (!empty($firstcontext)) {
879 if ($onlyvisible == true) {
880 $sql .= " AND (r.visible = 1)";
884 $sql .= " AND (r.type = ?)";
887 $sql .= " ORDER BY r.sortorder, i.name";
889 if (!$records = $DB->get_records_sql($sql, $params)) {
893 $repositories = array();
894 if (isset($args['accepted_types'])) {
895 $accepted_types = $args['accepted_types'];
897 $accepted_types = '*';
899 // Sortorder should be unique, which is not true if we use $record->sortorder
900 // and there are multiple instances of any repository type
902 foreach ($records as $record) {
903 if (!file_exists($CFG->dirroot . '/repository/'. $record->repositorytype.'/lib.php')) {
906 require_once($CFG->dirroot . '/repository/'. $record->repositorytype.'/lib.php');
907 $options['visible'] = $record->visible;
908 $options['type'] = $record->repositorytype;
909 $options['typeid'] = $record->typeid;
910 $options['sortorder'] = $sortorder++;
911 // tell instance what file types will be accepted by file picker
912 $classname = 'repository_' . $record->repositorytype;
914 $repository = new $classname($record->id, $record->contextid, $options, $record->readonly);
916 $is_supported = true;
918 if (empty($repository->super_called)) {
919 // to make sure the super construct is called
920 debugging('parent::__construct must be called by '.$record->repositorytype.' plugin.');
923 if ($accepted_types !== '*' and $repository->supported_filetypes() !== '*') {
924 $accepted_ext = file_get_typegroup('extension', $accepted_types);
925 $supported_ext = file_get_typegroup('extension', $repository->supported_filetypes());
926 $valid_ext = array_intersect($accepted_ext, $supported_ext);
927 $is_supported = !empty($valid_ext);
929 // check return values
930 if ($returntypes !== 3 and $repository->supported_returntypes() !== 3) {
931 $type = $repository->supported_returntypes();
932 if ($type & $returntypes) {
935 $is_supported = false;
939 if (!$onlyvisible || ($repository->is_visible() && !$repository->disabled)) {
940 // check capability in current context
941 if (!empty($current_context)) {
942 $capability = has_capability('repository/'.$record->repositorytype.':view', $current_context);
944 $capability = has_capability('repository/'.$record->repositorytype.':view', get_system_context());
946 if ($record->repositorytype == 'coursefiles') {
947 // coursefiles plugin needs managefiles permission
948 if (!empty($current_context)) {
949 $capability = $capability && has_capability('moodle/course:managefiles', $current_context);
951 $capability = $capability && has_capability('moodle/course:managefiles', get_system_context());
954 if ($is_supported && $capability) {
955 $repositories[$repository->id] = $repository;
960 return $repositories;
964 * Get single repository instance
967 * @param integer $id repository id
968 * @return object repository instance
970 public static function get_instance($id) {
972 $sql = "SELECT i.*, r.type AS repositorytype, r.visible
974 JOIN {repository_instances} i ON i.typeid = r.id
977 if (!$instance = $DB->get_record_sql($sql, array($id))) {
980 require_once($CFG->dirroot . '/repository/'. $instance->repositorytype.'/lib.php');
981 $classname = 'repository_' . $instance->repositorytype;
982 $options['typeid'] = $instance->typeid;
983 $options['type'] = $instance->repositorytype;
984 $options['name'] = $instance->name;
985 $obj = new $classname($instance->id, $instance->contextid, $options, $instance->readonly);
986 if (empty($obj->super_called)) {
987 debugging('parent::__construct must be called by '.$classname.' plugin.');
993 * Call a static function. Any additional arguments than plugin and function will be passed through.
996 * @param string $plugin repository plugin name
997 * @param string $function funciton name
1000 public static function static_function($plugin, $function) {
1003 //check that the plugin exists
1004 $typedirectory = $CFG->dirroot . '/repository/'. $plugin . '/lib.php';
1005 if (!file_exists($typedirectory)) {
1006 //throw new repository_exception('invalidplugin', 'repository');
1011 if (is_object($plugin) || is_array($plugin)) {
1012 $plugin = (object)$plugin;
1013 $pname = $plugin->name;
1018 $args = func_get_args();
1019 if (count($args) <= 2) {
1026 require_once($typedirectory);
1027 return call_user_func_array(array('repository_' . $plugin, $function), $args);
1031 * Scan file, throws exception in case of infected file.
1033 * Please note that the scanning engine must be able to access the file,
1034 * permissions of the file are not modified here!
1037 * @param string $thefile
1038 * @param string $filename name of the file
1039 * @param bool $deleteinfected
1041 public static function antivir_scan_file($thefile, $filename, $deleteinfected) {
1044 if (!is_readable($thefile)) {
1045 // this should not happen
1049 if (empty($CFG->runclamonupload) or empty($CFG->pathtoclam)) {
1054 $CFG->pathtoclam = trim($CFG->pathtoclam);
1056 if (!file_exists($CFG->pathtoclam) or !is_executable($CFG->pathtoclam)) {
1057 // misconfigured clam - use the old notification for now
1058 require("$CFG->libdir/uploadlib.php");
1059 $notice = get_string('clamlost', 'moodle', $CFG->pathtoclam);
1060 clam_message_admins($notice);
1064 // do NOT mess with permissions here, the calling party is responsible for making
1065 // sure the scanner engine can access the files!
1068 $cmd = escapeshellcmd($CFG->pathtoclam).' --stdout '.escapeshellarg($thefile);
1069 exec($cmd, $output, $return);
1072 // perfect, no problem found
1075 } else if ($return == 1) {
1077 if ($deleteinfected) {
1080 throw new moodle_exception('virusfounduser', 'moodle', '', array('filename'=>$filename));
1084 require("$CFG->libdir/uploadlib.php");
1085 $notice = get_string('clamfailed', 'moodle', get_clam_error_code($return));
1086 $notice .= "\n\n". implode("\n", $output);
1087 clam_message_admins($notice);
1088 if ($CFG->clamfailureonupload === 'actlikevirus') {
1089 if ($deleteinfected) {
1092 throw new moodle_exception('virusfounduser', 'moodle', '', array('filename'=>$filename));
1100 * Repository method to serve the referenced file
1102 * @see send_stored_file
1104 * @param stored_file $storedfile the file that contains the reference
1105 * @param int $lifetime Number of seconds before the file should expire from caches (default 24 hours)
1106 * @param int $filter 0 (default)=no filtering, 1=all files, 2=html files only
1107 * @param bool $forcedownload If true (default false), forces download of file rather than view in browser/plugin
1108 * @param array $options additional options affecting the file serving
1110 public function send_file($storedfile, $lifetime=86400 , $filter=0, $forcedownload=false, array $options = null) {
1111 if ($this->has_moodle_files()) {
1112 $fs = get_file_storage();
1113 $params = file_storage::unpack_reference($storedfile->get_reference(), true);
1115 if (is_array($params)) {
1116 $srcfile = $fs->get_file($params['contextid'], $params['component'], $params['filearea'],
1117 $params['itemid'], $params['filepath'], $params['filename']);
1119 if (empty($options)) {
1122 if (!isset($options['filename'])) {
1123 $options['filename'] = $storedfile->get_filename();
1126 send_file_not_found();
1128 send_stored_file($srcfile, $lifetime, $filter, $forcedownload, $options);
1131 throw new coding_exception("Repository plugin must implement send_file() method.");
1136 * Return reference file life time
1138 * @param string $ref
1141 public function get_reference_file_lifetime($ref) {
1143 return 60 * 60 * 24;
1147 * Decide whether or not the file should be synced
1149 * @param stored_file $storedfile
1152 public function sync_individual_file(stored_file $storedfile) {
1157 * Return human readable reference information
1158 * {@link stored_file::get_reference()}
1160 * @param string $reference
1161 * @param int $filestatus status of the file, 0 - ok, 666 - source missing
1164 public function get_reference_details($reference, $filestatus = 0) {
1165 if ($this->has_moodle_files()) {
1167 $params = file_storage::unpack_reference($reference, true);
1168 if (is_array($params)) {
1169 $context = get_context_instance_by_id($params['contextid']);
1171 $browser = get_file_browser();
1172 $fileinfo = $browser->get_file_info($context, $params['component'], $params['filearea'], $params['itemid'], $params['filepath'], $params['filename']);
1175 if (empty($fileinfo)) {
1176 if ($filestatus == 666) {
1177 if (is_siteadmin() || ($context && has_capability('moodle/course:managefiles', $context))) {
1178 return get_string('lostsource', 'repository',
1179 $params['contextid']. '/'. $params['component']. '/'. $params['filearea']. '/'. $params['itemid']. $params['filepath']. $params['filename']);
1181 return get_string('lostsource', 'repository', '');
1184 return get_string('undisclosedsource', 'repository');
1186 return $fileinfo->get_readable_fullname();
1193 * Cache file from external repository by reference
1194 * {@link repository::get_file_reference()}
1195 * {@link repository::get_file()}
1196 * Invoked at MOODLE/repository/repository_ajax.php
1198 * @param string $reference this reference is generated by
1199 * repository::get_file_reference()
1200 * @param stored_file $storedfile created file reference
1202 public function cache_file_by_reference($reference, $storedfile) {
1206 * Returns information about file in this repository by reference
1207 * {@link repository::get_file_reference()}
1208 * {@link repository::get_file()}
1210 * Returns null if file not found or is not readable
1212 * @param stdClass $reference file reference db record
1213 * @return stdClass|null contains one of the following:
1214 * - 'contenthash' and 'filesize'
1219 public function get_file_by_reference($reference) {
1220 if ($this->has_moodle_files() && isset($reference->reference)) {
1221 $fs = get_file_storage();
1222 $params = file_storage::unpack_reference($reference->reference, true);
1223 if (!is_array($params) || !($storedfile = $fs->get_file($params['contextid'],
1224 $params['component'], $params['filearea'], $params['itemid'], $params['filepath'],
1225 $params['filename']))) {
1228 return (object)array(
1229 'contenthash' => $storedfile->get_contenthash(),
1230 'filesize' => $storedfile->get_filesize()
1237 * Return the source information
1239 * @param stdClass $url
1240 * @return string|null
1242 public function get_file_source_info($url) {
1243 if ($this->has_moodle_files()) {
1244 return $this->get_reference_details($url, 0);
1250 * Move file from download folder to file pool using FILE API
1254 * @param string $thefile file path in download folder
1255 * @param stdClass $record
1256 * @return array containing the following keys:
1262 public static function move_to_filepool($thefile, $record) {
1263 global $DB, $CFG, $USER, $OUTPUT;
1265 // scan for viruses if possible, throws exception if problem found
1266 self::antivir_scan_file($thefile, $record->filename, empty($CFG->repository_no_delete)); //TODO: MDL-28637 this repository_no_delete is a bloody hack!
1268 $fs = get_file_storage();
1269 // If file name being used.
1270 if (repository::draftfile_exists($record->itemid, $record->filepath, $record->filename)) {
1271 $draftitemid = $record->itemid;
1272 $new_filename = repository::get_unused_filename($draftitemid, $record->filepath, $record->filename);
1273 $old_filename = $record->filename;
1274 // Create a tmp file.
1275 $record->filename = $new_filename;
1276 $newfile = $fs->create_file_from_pathname($record, $thefile);
1278 $event['event'] = 'fileexists';
1279 $event['newfile'] = new stdClass;
1280 $event['newfile']->filepath = $record->filepath;
1281 $event['newfile']->filename = $new_filename;
1282 $event['newfile']->url = moodle_url::make_draftfile_url($draftitemid, $record->filepath, $new_filename)->out();
1284 $event['existingfile'] = new stdClass;
1285 $event['existingfile']->filepath = $record->filepath;
1286 $event['existingfile']->filename = $old_filename;
1287 $event['existingfile']->url = moodle_url::make_draftfile_url($draftitemid, $record->filepath, $old_filename)->out();;
1290 if ($file = $fs->create_file_from_pathname($record, $thefile)) {
1291 if (empty($CFG->repository_no_delete)) {
1292 $delete = unlink($thefile);
1293 unset($CFG->repository_no_delete);
1296 'url'=>moodle_url::make_draftfile_url($file->get_itemid(), $file->get_filepath(), $file->get_filename())->out(),
1297 'id'=>$file->get_itemid(),
1298 'file'=>$file->get_filename(),
1299 'icon' => $OUTPUT->pix_url(file_extension_icon($thefile, 32))->out(),
1307 * Builds a tree of files This function is then called recursively.
1310 * @todo take $search into account, and respect a threshold for dynamic loading
1311 * @param file_info $fileinfo an object returned by file_browser::get_file_info()
1312 * @param string $search searched string
1313 * @param bool $dynamicmode no recursive call is done when in dynamic mode
1314 * @param array $list the array containing the files under the passed $fileinfo
1315 * @returns int the number of files found
1318 public static function build_tree($fileinfo, $search, $dynamicmode, &$list) {
1319 global $CFG, $OUTPUT;
1322 $children = $fileinfo->get_children();
1324 foreach ($children as $child) {
1325 $filename = $child->get_visible_name();
1326 $filesize = $child->get_filesize();
1327 $filesize = $filesize ? display_size($filesize) : '';
1328 $filedate = $child->get_timemodified();
1329 $filedate = $filedate ? userdate($filedate) : '';
1330 $filetype = $child->get_mimetype();
1332 if ($child->is_directory()) {
1334 $level = $child->get_parent();
1336 $params = $level->get_params();
1337 $path[] = array($params['filepath'], $level->get_visible_name());
1338 $level = $level->get_parent();
1342 'title' => $child->get_visible_name(),
1344 'date' => $filedate,
1345 'path' => array_reverse($path),
1346 'thumbnail' => $OUTPUT->pix_url(file_folder_icon(90))->out(false)
1349 //if ($dynamicmode && $child->is_writable()) {
1350 // $tmp['children'] = array();
1352 // if folder name matches search, we send back all files contained.
1354 if ($search && stristr($tmp['title'], $search) !== false) {
1357 $tmp['children'] = array();
1358 $_filecount = repository::build_tree($child, $_search, $dynamicmode, $tmp['children']);
1359 if ($search && $_filecount) {
1360 $tmp['expanded'] = 1;
1365 if (!$search || $_filecount || (stristr($tmp['title'], $search) !== false)) {
1366 $filecount += $_filecount;
1370 } else { // not a directory
1371 // skip the file, if we're in search mode and it's not a match
1372 if ($search && (stristr($filename, $search) === false)) {
1375 $params = $child->get_params();
1376 $source = serialize(array($params['contextid'], $params['component'], $params['filearea'], $params['itemid'], $params['filepath'], $params['filename']));
1378 'title' => $filename,
1379 'size' => $filesize,
1380 'date' => $filedate,
1381 //'source' => $child->get_url(),
1382 'source' => base64_encode($source),
1383 'icon'=>$OUTPUT->pix_url(file_file_icon($child, 24))->out(false),
1384 'thumbnail'=>$OUTPUT->pix_url(file_file_icon($child, 90))->out(false),
1394 * Display a repository instance list (with edit/delete/create links)
1397 * @param stdClass $context the context for which we display the instance
1398 * @param string $typename if set, we display only one type of instance
1400 public static function display_instances_list($context, $typename = null) {
1401 global $CFG, $USER, $OUTPUT;
1403 $output = $OUTPUT->box_start('generalbox');
1404 //if the context is SYSTEM, so we call it from administration page
1405 $admin = ($context->id == SYSCONTEXTID) ? true : false;
1407 $baseurl = new moodle_url('/'.$CFG->admin.'/repositoryinstance.php', array('sesskey'=>sesskey()));
1408 $output .= $OUTPUT->heading(get_string('siteinstances', 'repository'));
1410 $baseurl = new moodle_url('/repository/manage_instances.php', array('contextid'=>$context->id, 'sesskey'=>sesskey()));
1413 $namestr = get_string('name');
1414 $pluginstr = get_string('plugin', 'repository');
1415 $settingsstr = get_string('settings');
1416 $deletestr = get_string('delete');
1417 //retrieve list of instances. In administration context we want to display all
1418 //instances of a type, even if this type is not visible. In course/user context we
1419 //want to display only visible instances, but for every type types. The repository::get_instances()
1420 //third parameter displays only visible type.
1422 $params['context'] = array($context, get_system_context());
1423 $params['currentcontext'] = $context;
1424 $params['onlyvisible'] = !$admin;
1425 $params['type'] = $typename;
1426 $instances = repository::get_instances($params);
1427 $instancesnumber = count($instances);
1428 $alreadyplugins = array();
1430 $table = new html_table();
1431 $table->head = array($namestr, $pluginstr, $settingsstr, $deletestr);
1432 $table->align = array('left', 'left', 'center','center');
1433 $table->data = array();
1437 foreach ($instances as $i) {
1441 $type = repository::get_type_by_id($i->options['typeid']);
1443 if ($type->get_contextvisibility($context)) {
1444 if (!$i->readonly) {
1446 $settingurl = new moodle_url($baseurl);
1447 $settingurl->param('type', $i->options['type']);
1448 $settingurl->param('edit', $i->id);
1449 $settings .= html_writer::link($settingurl, $settingsstr);
1451 $deleteurl = new moodle_url($baseurl);
1452 $deleteurl->param('delete', $i->id);
1453 $deleteurl->param('type', $i->options['type']);
1454 $delete .= html_writer::link($deleteurl, $deletestr);
1458 $type = repository::get_type_by_id($i->options['typeid']);
1459 $table->data[] = array(format_string($i->name), $type->get_readablename(), $settings, $delete);
1461 //display a grey row if the type is defined as not visible
1462 if (isset($type) && !$type->get_visible()) {
1463 $table->rowclasses[] = 'dimmed_text';
1465 $table->rowclasses[] = '';
1468 if (!in_array($i->name, $alreadyplugins)) {
1469 $alreadyplugins[] = $i->name;
1472 $output .= html_writer::table($table);
1473 $instancehtml = '<div>';
1476 //if no type is set, we can create all type of instance
1478 $instancehtml .= '<h3>';
1479 $instancehtml .= get_string('createrepository', 'repository');
1480 $instancehtml .= '</h3><ul>';
1481 $types = repository::get_editable_types($context);
1482 foreach ($types as $type) {
1483 if (!empty($type) && $type->get_visible()) {
1484 $instanceoptionnames = repository::static_function($type->get_typename(), 'get_instance_option_names');
1485 if (!empty($instanceoptionnames)) {
1486 $baseurl->param('new', $type->get_typename());
1487 $instancehtml .= '<li><a href="'.$baseurl->out().'">'.get_string('createxxinstance', 'repository', get_string('pluginname', 'repository_'.$type->get_typename())). '</a></li>';
1488 $baseurl->remove_params('new');
1493 $instancehtml .= '</ul>';
1496 $instanceoptionnames = repository::static_function($typename, 'get_instance_option_names');
1497 if (!empty($instanceoptionnames)) { //create a unique type of instance
1499 $baseurl->param('new', $typename);
1500 $output .= $OUTPUT->single_button($baseurl, get_string('createinstance', 'repository'), 'get');
1501 $baseurl->remove_params('new');
1506 $instancehtml .= '</div>';
1507 $output .= $instancehtml;
1510 $output .= $OUTPUT->box_end();
1512 //print the list + creation links
1517 * Prepare file reference information
1519 * @param string $source
1520 * @return string file referece
1522 public function get_file_reference($source) {
1523 if ($this->has_moodle_files() && ($this->supported_returntypes() & FILE_REFERENCE)) {
1524 $params = file_storage::unpack_reference($source);
1525 if (!is_array($params)) {
1526 throw new repository_exception('invalidparams', 'repository');
1528 return file_storage::pack_reference($params);
1533 * Decide where to save the file, can be overwriten by subclass
1535 * @param string $filename file name
1538 public function prepare_file($filename) {
1540 if (!file_exists($CFG->tempdir.'/download')) {
1541 mkdir($CFG->tempdir.'/download/', $CFG->directorypermissions, true);
1543 if (is_dir($CFG->tempdir.'/download')) {
1544 $dir = $CFG->tempdir.'/download/';
1546 if (empty($filename)) {
1547 $filename = uniqid('repo', true).'_'.time().'.tmp';
1549 if (file_exists($dir.$filename)) {
1550 $filename = uniqid('m').$filename;
1552 return $dir.$filename;
1556 * Does this repository used to browse moodle files?
1560 public function has_moodle_files() {
1565 * Return file URL, for most plugins, the parameter is the original
1566 * url, but some plugins use a file id, so we need this function to
1567 * convert file id to original url.
1569 * @param string $url the url of file
1572 public function get_link($url) {
1577 * Download a file, this function can be overridden by subclass. {@link curl}
1579 * @param string $url the url of file
1580 * @param string $filename save location
1581 * @return array with elements:
1582 * path: internal location of the file
1583 * url: URL to the source (from parameters)
1585 public function get_file($url, $filename = '') {
1587 $path = $this->prepare_file($filename);
1588 $fp = fopen($path, 'w');
1590 $result = $c->download(array(array('url'=>$url, 'file'=>$fp)));
1591 // Close file handler.
1593 if (empty($result)) {
1597 return array('path'=>$path, 'url'=>$url);
1601 * Return size of a file in bytes.
1603 * @param string $source encoded and serialized data of file
1604 * @return int file size in bytes
1606 public function get_file_size($source) {
1607 // TODO MDL-33297 remove this function completely?
1608 $browser = get_file_browser();
1609 $params = unserialize(base64_decode($source));
1610 $contextid = clean_param($params['contextid'], PARAM_INT);
1611 $fileitemid = clean_param($params['itemid'], PARAM_INT);
1612 $filename = clean_param($params['filename'], PARAM_FILE);
1613 $filepath = clean_param($params['filepath'], PARAM_PATH);
1614 $filearea = clean_param($params['filearea'], PARAM_AREA);
1615 $component = clean_param($params['component'], PARAM_COMPONENT);
1616 $context = get_context_instance_by_id($contextid);
1617 $file_info = $browser->get_file_info($context, $component, $filearea, $fileitemid, $filepath, $filename);
1618 if (!empty($file_info)) {
1619 $filesize = $file_info->get_filesize();
1627 * Return is the instance is visible
1628 * (is the type visible ? is the context enable ?)
1632 public function is_visible() {
1633 $type = repository::get_type_by_id($this->options['typeid']);
1634 $instanceoptions = repository::static_function($type->get_typename(), 'get_instance_option_names');
1636 if ($type->get_visible()) {
1637 //if the instance is unique so it's visible, otherwise check if the instance has a enabled context
1638 if (empty($instanceoptions) || $type->get_contextvisibility($this->context)) {
1647 * Return the name of this instance, can be overridden.
1651 public function get_name() {
1653 if ( $name = $this->instance->name ) {
1656 return get_string('pluginname', 'repository_' . $this->options['type']);
1661 * What kind of files will be in this repository?
1663 * @return array return '*' means this repository support any files, otherwise
1664 * return mimetypes of files, it can be an array
1666 public function supported_filetypes() {
1667 // return array('text/plain', 'image/gif');
1672 * Tells how the file can be picked from this repository
1674 * Maximum value is FILE_INTERNAL | FILE_EXTERNAL | FILE_REFERENCE
1678 public function supported_returntypes() {
1679 return (FILE_INTERNAL | FILE_EXTERNAL);
1683 * Provide repository instance information for Ajax
1687 final public function get_meta() {
1688 global $CFG, $OUTPUT;
1689 $meta = new stdClass();
1690 $meta->id = $this->id;
1691 $meta->name = format_string($this->get_name());
1692 $meta->type = $this->options['type'];
1693 $meta->icon = $OUTPUT->pix_url('icon', 'repository_'.$meta->type)->out(false);
1694 $meta->supported_types = file_get_typegroup('extension', $this->supported_filetypes());
1695 $meta->return_types = $this->supported_returntypes();
1696 $meta->sortorder = $this->options['sortorder'];
1701 * Create an instance for this plug-in
1704 * @param string $type the type of the repository
1705 * @param int $userid the user id
1706 * @param stdClass $context the context
1707 * @param array $params the options for this instance
1708 * @param int $readonly whether to create it readonly or not (defaults to not)
1711 public static function create($type, $userid, $context, $params, $readonly=0) {
1713 $params = (array)$params;
1714 require_once($CFG->dirroot . '/repository/'. $type . '/lib.php');
1715 $classname = 'repository_' . $type;
1716 if ($repo = $DB->get_record('repository', array('type'=>$type))) {
1717 $record = new stdClass();
1718 $record->name = $params['name'];
1719 $record->typeid = $repo->id;
1720 $record->timecreated = time();
1721 $record->timemodified = time();
1722 $record->contextid = $context->id;
1723 $record->readonly = $readonly;
1724 $record->userid = $userid;
1725 $id = $DB->insert_record('repository_instances', $record);
1727 $configs = call_user_func($classname . '::get_instance_option_names');
1728 if (!empty($configs)) {
1729 foreach ($configs as $config) {
1730 if (isset($params[$config])) {
1731 $options[$config] = $params[$config];
1733 $options[$config] = null;
1739 unset($options['name']);
1740 $instance = repository::get_instance($id);
1741 $instance->set_option($options);
1752 * delete a repository instance
1754 * @param bool $downloadcontents
1757 final public function delete($downloadcontents = false) {
1759 if ($downloadcontents) {
1760 $this->convert_references_to_local();
1763 $DB->delete_records('repository_instances', array('id'=>$this->id));
1764 $DB->delete_records('repository_instance_config', array('instanceid'=>$this->id));
1765 } catch (dml_exception $ex) {
1772 * Hide/Show a repository
1774 * @param string $hide
1777 final public function hide($hide = 'toggle') {
1779 if ($entry = $DB->get_record('repository', array('id'=>$this->id))) {
1780 if ($hide === 'toggle' ) {
1781 if (!empty($entry->visible)) {
1782 $entry->visible = 0;
1784 $entry->visible = 1;
1787 if (!empty($hide)) {
1788 $entry->visible = 0;
1790 $entry->visible = 1;
1793 return $DB->update_record('repository', $entry);
1799 * Save settings for repository instance
1800 * $repo->set_option(array('api_key'=>'f2188bde132', 'name'=>'dongsheng'));
1802 * @param array $options settings
1805 public function set_option($options = array()) {
1808 if (!empty($options['name'])) {
1809 $r = new stdClass();
1811 $r->name = $options['name'];
1812 $DB->update_record('repository_instances', $r);
1813 unset($options['name']);
1815 foreach ($options as $name=>$value) {
1816 if ($id = $DB->get_field('repository_instance_config', 'id', array('name'=>$name, 'instanceid'=>$this->id))) {
1817 $DB->set_field('repository_instance_config', 'value', $value, array('id'=>$id));
1819 $config = new stdClass();
1820 $config->instanceid = $this->id;
1821 $config->name = $name;
1822 $config->value = $value;
1823 $DB->insert_record('repository_instance_config', $config);
1830 * Get settings for repository instance
1832 * @param string $config
1833 * @return array Settings
1835 public function get_option($config = '') {
1837 $entries = $DB->get_records('repository_instance_config', array('instanceid'=>$this->id));
1839 if (empty($entries)) {
1842 foreach($entries as $entry) {
1843 $ret[$entry->name] = $entry->value;
1845 if (!empty($config)) {
1846 if (isset($ret[$config])) {
1847 return $ret[$config];
1857 * Filter file listing to display specific types
1859 * @param array $value
1862 public function filter(&$value) {
1863 $accepted_types = optional_param_array('accepted_types', '', PARAM_RAW);
1864 if (isset($value['children'])) {
1865 if (!empty($value['children'])) {
1866 $value['children'] = array_filter($value['children'], array($this, 'filter'));
1868 return true; // always return directories
1870 if ($accepted_types == '*' or empty($accepted_types)
1871 or (is_array($accepted_types) and in_array('*', $accepted_types))) {
1874 foreach ($accepted_types as $ext) {
1875 if (preg_match('#'.$ext.'$#i', $value['title'])) {
1885 * Given a path, and perhaps a search, get a list of files.
1887 * See details on {@link http://docs.moodle.org/dev/Repository_plugins}
1889 * @param string $path this parameter can a folder name, or a identification of folder
1890 * @param string $page the page number of file list
1891 * @return array the list of files, including meta infomation, containing the following keys
1892 * manage, url to manage url
1895 * repo_id, active repository id
1896 * login_btn_action, the login button action
1897 * login_btn_label, the login button label
1898 * total, number of results
1899 * perpage, items per page
1901 * pages, total pages
1902 * issearchresult, is it a search result?
1904 * path, current path and parent path
1906 public function get_listing($path = '', $page = '') {
1910 * Prepares list of files before passing it to AJAX, makes sure data is in the correct
1911 * format and stores formatted values.
1913 * @param array|stdClass $listing result of get_listing() or search() or file_get_drafarea_files()
1916 public static function prepare_listing($listing) {
1919 $defaultfoldericon = $OUTPUT->pix_url(file_folder_icon(24))->out(false);
1920 // prepare $listing['path'] or $listing->path
1921 if (is_array($listing) && isset($listing['path']) && is_array($listing['path'])) {
1922 $path = &$listing['path'];
1923 } else if (is_object($listing) && isset($listing->path) && is_array($listing->path)) {
1924 $path = &$listing->path;
1927 $len = count($path);
1928 for ($i=0; $i<$len; $i++) {
1929 if (is_array($path[$i]) && !isset($path[$i]['icon'])) {
1930 $path[$i]['icon'] = $defaultfoldericon;
1931 } else if (is_object($path[$i]) && !isset($path[$i]->icon)) {
1932 $path[$i]->icon = $defaultfoldericon;
1937 // prepare $listing['list'] or $listing->list
1938 if (is_array($listing) && isset($listing['list']) && is_array($listing['list'])) {
1939 $listing['list'] = array_values($listing['list']); // convert to array
1940 $files = &$listing['list'];
1941 } else if (is_object($listing) && isset($listing->list) && is_array($listing->list)) {
1942 $listing->list = array_values($listing->list); // convert to array
1943 $files = &$listing->list;
1947 $len = count($files);
1948 for ($i=0; $i<$len; $i++) {
1949 if (is_object($files[$i])) {
1950 $file = (array)$files[$i];
1951 $converttoobject = true;
1953 $file = & $files[$i];
1954 $converttoobject = false;
1956 if (isset($file['size'])) {
1957 $file['size'] = (int)$file['size'];
1958 $file['size_f'] = display_size($file['size']);
1960 if (isset($file['license']) &&
1961 get_string_manager()->string_exists($file['license'], 'license')) {
1962 $file['license_f'] = get_string($file['license'], 'license');
1964 if (isset($file['image_width']) && isset($file['image_height'])) {
1965 $a = array('width' => $file['image_width'], 'height' => $file['image_height']);
1966 $file['dimensions'] = get_string('imagesize', 'repository', (object)$a);
1968 foreach (array('date', 'datemodified', 'datecreated') as $key) {
1969 if (!isset($file[$key]) && isset($file['date'])) {
1970 $file[$key] = $file['date'];
1972 if (isset($file[$key])) {
1973 // must be UNIX timestamp
1974 $file[$key] = (int)$file[$key];
1978 $file[$key.'_f'] = userdate($file[$key], get_string('strftimedatetime', 'langconfig'));
1979 $file[$key.'_f_s'] = userdate($file[$key], get_string('strftimedatetimeshort', 'langconfig'));
1983 $isfolder = (array_key_exists('children', $file) || (isset($file['type']) && $file['type'] == 'folder'));
1985 if (isset($file['title'])) {
1986 $filename = $file['title'];
1988 else if (isset($file['fullname'])) {
1989 $filename = $file['fullname'];
1991 if (!isset($file['mimetype']) && !$isfolder && $filename) {
1992 $file['mimetype'] = get_mimetype_description(array('filename' => $filename));
1994 if (!isset($file['icon'])) {
1996 $file['icon'] = $defaultfoldericon;
1997 } else if ($filename) {
1998 $file['icon'] = $OUTPUT->pix_url(file_extension_icon($filename, 24))->out(false);
2001 if ($converttoobject) {
2002 $files[$i] = (object)$file;
2009 * Search files in repository
2010 * When doing global search, $search_text will be used as
2013 * @param string $search_text search key word
2014 * @param int $page page
2015 * @return mixed {@see repository::get_listing}
2017 public function search($search_text, $page = 0) {
2019 $list['list'] = array();
2024 * Logout from repository instance
2025 * By default, this function will return a login form
2029 public function logout(){
2030 return $this->print_login();
2034 * To check whether the user is logged in.
2038 public function check_login(){
2044 * Show the login screen, if required
2048 public function print_login(){
2049 return $this->get_listing();
2053 * Show the search screen, if required
2057 public function print_search() {
2059 $renderer = $PAGE->get_renderer('core', 'files');
2060 return $renderer->repository_default_searchform();
2064 * For oauth like external authentication, when external repository direct user back to moodle,
2065 * this funciton will be called to set up token and token_secret
2067 public function callback() {
2071 * is it possible to do glboal search?
2075 public function global_search() {
2080 * Defines operations that happen occasionally on cron
2084 public function cron() {
2089 * function which is run when the type is created (moodle administrator add the plugin)
2091 * @return bool success or fail?
2093 public static function plugin_init() {
2098 * Edit/Create Admin Settings Moodle form
2100 * @param moodleform $mform Moodle form (passed by reference)
2101 * @param string $classname repository class name
2103 public static function type_config_form($mform, $classname = 'repository') {
2104 $instnaceoptions = call_user_func(array($classname, 'get_instance_option_names'), $mform, $classname);
2105 if (empty($instnaceoptions)) {
2106 // this plugin has only one instance
2107 // so we need to give it a name
2108 // it can be empty, then moodle will look for instance name from language string
2109 $mform->addElement('text', 'pluginname', get_string('pluginname', 'repository'), array('size' => '40'));
2110 $mform->addElement('static', 'pluginnamehelp', '', get_string('pluginnamehelp', 'repository'));
2111 $mform->setType('pluginname', PARAM_TEXT);
2116 * Validate Admin Settings Moodle form
2119 * @param moodleform $mform Moodle form (passed by reference)
2120 * @param array $data array of ("fieldname"=>value) of submitted data
2121 * @param array $errors array of ("fieldname"=>errormessage) of errors
2122 * @return array array of errors
2124 public static function type_form_validation($mform, $data, $errors) {
2130 * Edit/Create Instance Settings Moodle form
2132 * @param moodleform $mform Moodle form (passed by reference)
2134 public static function instance_config_form($mform) {
2138 * Return names of the general options.
2139 * By default: no general option name
2143 public static function get_type_option_names() {
2144 return array('pluginname');
2148 * Return names of the instance options.
2149 * By default: no instance option name
2153 public static function get_instance_option_names() {
2158 * Validate repository plugin instance form
2160 * @param moodleform $mform moodle form
2161 * @param array $data form data
2162 * @param array $errors errors
2163 * @return array errors
2165 public static function instance_form_validation($mform, $data, $errors) {
2170 * Create a shorten filename
2172 * @param string $str filename
2173 * @param int $maxlength max file name length
2174 * @return string short filename
2176 public function get_short_filename($str, $maxlength) {
2177 if (textlib::strlen($str) >= $maxlength) {
2178 return trim(textlib::substr($str, 0, $maxlength)).'...';
2185 * Overwrite an existing file
2187 * @param int $itemid
2188 * @param string $filepath
2189 * @param string $filename
2190 * @param string $newfilepath
2191 * @param string $newfilename
2194 public static function overwrite_existing_draftfile($itemid, $filepath, $filename, $newfilepath, $newfilename) {
2196 $fs = get_file_storage();
2197 $user_context = get_context_instance(CONTEXT_USER, $USER->id);
2198 if ($file = $fs->get_file($user_context->id, 'user', 'draft', $itemid, $filepath, $filename)) {
2199 if ($tempfile = $fs->get_file($user_context->id, 'user', 'draft', $itemid, $newfilepath, $newfilename)) {
2200 // delete existing file to release filename
2203 $newfile = $fs->create_file_from_storedfile(array('filepath'=>$filepath, 'filename'=>$filename), $tempfile);
2205 $tempfile->delete();
2213 * Delete a temp file from draft area
2215 * @param int $draftitemid
2216 * @param string $filepath
2217 * @param string $filename
2220 public static function delete_tempfile_from_draft($draftitemid, $filepath, $filename) {
2222 $fs = get_file_storage();
2223 $user_context = get_context_instance(CONTEXT_USER, $USER->id);
2224 if ($file = $fs->get_file($user_context->id, 'user', 'draft', $draftitemid, $filepath, $filename)) {
2233 * Find all external files in this repo and import them
2235 public function convert_references_to_local() {
2236 $fs = get_file_storage();
2237 $files = $fs->get_external_files($this->id);
2238 foreach ($files as $storedfile) {
2239 $fs->import_external_file($storedfile);
2244 * Called from phpunit between tests, resets whatever was cached
2246 public static function reset_caches() {
2247 self::sync_external_file(null, true);
2251 * Call to request proxy file sync with repository source.
2253 * @param stored_file $file
2254 * @param bool $resetsynchistory whether to reset all history of sync (used by phpunit)
2255 * @return bool success
2257 public static function sync_external_file($file, $resetsynchistory = false) {
2259 // TODO MDL-25290 static should be replaced with MUC code.
2260 static $synchronized = array();
2261 if ($resetsynchistory) {
2262 $synchronized = array();
2265 $fs = get_file_storage();
2267 if (!$file || !$file->get_referencefileid()) {
2270 if (array_key_exists($file->get_id(), $synchronized)) {
2271 return $synchronized[$file->get_id()];
2274 // remember that we already cached in current request to prevent from querying again
2275 $synchronized[$file->get_id()] = false;
2277 if (!$reference = $DB->get_record('files_reference', array('id'=>$file->get_referencefileid()))) {
2281 if (!empty($reference->lastsync) and ($reference->lastsync + $reference->lifetime > time())) {
2282 $synchronized[$file->get_id()] = true;
2286 if (!$repository = self::get_repository_by_id($reference->repositoryid, SYSCONTEXTID)) {
2290 if (!$repository->sync_individual_file($file)) {
2294 $fileinfo = $repository->get_file_by_reference($reference);
2295 if ($fileinfo === null) {
2296 // does not exist any more - set status to missing
2297 $file->set_missingsource();
2298 //TODO: purge content from pool if we set some other content hash and it is no used any more
2299 $synchronized[$file->get_id()] = true;
2303 $contenthash = null;
2305 if (!empty($fileinfo->contenthash)) {
2306 // contenthash returned, file already in moodle
2307 $contenthash = $fileinfo->contenthash;
2308 $filesize = $fileinfo->filesize;
2309 } else if (!empty($fileinfo->filepath)) {
2310 // File path returned
2311 list($contenthash, $filesize, $newfile) = $fs->add_file_to_pool($fileinfo->filepath);
2312 } else if (!empty($fileinfo->handle) && is_resource($fileinfo->handle)) {
2313 // File handle returned
2315 while (!feof($fileinfo->handle)) {
2316 $contents .= fread($handle, 8192);
2318 fclose($fileinfo->handle);
2319 list($contenthash, $filesize, $newfile) = $fs->add_string_to_pool($content);
2320 } else if (isset($fileinfo->content)) {
2321 // File content returned
2322 list($contenthash, $filesize, $newfile) = $fs->add_string_to_pool($fileinfo->content);
2325 if (!isset($contenthash) or !isset($filesize)) {
2329 // update files table
2330 $file->set_synchronized($contenthash, $filesize);
2331 $synchronized[$file->get_id()] = true;
2336 * Build draft file's source field
2338 * {@link file_restore_source_field_from_draft_file()}
2339 * XXX: This is a hack for file manager (MDL-28666)
2340 * For newly created draft files we have to construct
2341 * source filed in php serialized data format.
2342 * File manager needs to know the original file information before copying
2343 * to draft area, so we append these information in mdl_files.source field
2345 * @param string $source
2346 * @return string serialised source field
2348 public static function build_source_field($source) {
2349 $sourcefield = new stdClass;
2350 $sourcefield->source = $source;
2351 return serialize($sourcefield);
2356 * Exception class for repository api
2359 * @package repository
2360 * @category repository
2361 * @copyright 2009 Dongsheng Cai {@link http://dongsheng.org}
2362 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2364 class repository_exception extends moodle_exception {
2368 * This is a class used to define a repository instance form
2371 * @package repository
2372 * @category repository
2373 * @copyright 2009 Dongsheng Cai {@link http://dongsheng.org}
2374 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2376 final class repository_instance_form extends moodleform {
2377 /** @var stdClass repository instance */
2378 protected $instance;
2379 /** @var string repository plugin type */
2383 * Added defaults to moodle form
2385 protected function add_defaults() {
2386 $mform =& $this->_form;
2387 $strrequired = get_string('required');
2389 $mform->addElement('hidden', 'edit', ($this->instance) ? $this->instance->id : 0);
2390 $mform->setType('edit', PARAM_INT);
2391 $mform->addElement('hidden', 'new', $this->plugin);
2392 $mform->setType('new', PARAM_FORMAT);
2393 $mform->addElement('hidden', 'plugin', $this->plugin);
2394 $mform->setType('plugin', PARAM_PLUGIN);
2395 $mform->addElement('hidden', 'typeid', $this->typeid);
2396 $mform->setType('typeid', PARAM_INT);
2397 $mform->addElement('hidden', 'contextid', $this->contextid);
2398 $mform->setType('contextid', PARAM_INT);
2400 $mform->addElement('text', 'name', get_string('name'), 'maxlength="100" size="30"');
2401 $mform->addRule('name', $strrequired, 'required', null, 'client');
2402 $mform->setType('name', PARAM_TEXT);
2406 * Define moodle form elements
2408 public function definition() {
2410 // type of plugin, string
2411 $this->plugin = $this->_customdata['plugin'];
2412 $this->typeid = $this->_customdata['typeid'];
2413 $this->contextid = $this->_customdata['contextid'];
2414 $this->instance = (isset($this->_customdata['instance'])
2415 && is_subclass_of($this->_customdata['instance'], 'repository'))
2416 ? $this->_customdata['instance'] : null;
2418 $mform =& $this->_form;
2420 $this->add_defaults();
2422 // Add instance config options.
2423 $result = repository::static_function($this->plugin, 'instance_config_form', $mform);
2424 if ($result === false) {
2425 // Remove the name element if no other config options.
2426 $mform->removeElement('name');
2428 if ($this->instance) {
2430 $data['name'] = $this->instance->name;
2431 if (!$this->instance->readonly) {
2432 // and set the data if we have some.
2433 foreach ($this->instance->get_instance_option_names() as $config) {
2434 if (!empty($this->instance->options[$config])) {
2435 $data[$config] = $this->instance->options[$config];
2437 $data[$config] = '';
2441 $this->set_data($data);
2444 if ($result === false) {
2445 $mform->addElement('cancel');
2447 $this->add_action_buttons(true, get_string('save','repository'));
2452 * Validate moodle form data
2454 * @param array $data form data
2455 * @param array $files files in form
2456 * @return array errors
2458 public function validation($data, $files) {
2461 $plugin = $this->_customdata['plugin'];
2462 $instance = (isset($this->_customdata['instance'])
2463 && is_subclass_of($this->_customdata['instance'], 'repository'))
2464 ? $this->_customdata['instance'] : null;
2466 $errors = repository::static_function($plugin, 'instance_form_validation', $this, $data, $errors);
2468 $errors = $instance->instance_form_validation($this, $data, $errors);
2471 $sql = "SELECT count('x')
2472 FROM {repository_instances} i, {repository} r
2473 WHERE r.type=:plugin AND r.id=i.typeid AND i.name=:name";
2474 if ($DB->count_records_sql($sql, array('name' => $data['name'], 'plugin' => $data['plugin'])) > 1) {
2475 $errors['name'] = get_string('erroruniquename', 'repository');
2483 * This is a class used to define a repository type setting form
2486 * @package repository
2487 * @category repository
2488 * @copyright 2009 Dongsheng Cai {@link http://dongsheng.org}
2489 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2491 final class repository_type_form extends moodleform {
2492 /** @var stdClass repository instance */
2493 protected $instance;
2494 /** @var string repository plugin name */
2496 /** @var string action */
2500 * Definition of the moodleform
2502 public function definition() {
2504 // type of plugin, string
2505 $this->plugin = $this->_customdata['plugin'];
2506 $this->instance = (isset($this->_customdata['instance'])
2507 && is_a($this->_customdata['instance'], 'repository_type'))
2508 ? $this->_customdata['instance'] : null;
2510 $this->action = $this->_customdata['action'];
2511 $this->pluginname = $this->_customdata['pluginname'];
2512 $mform =& $this->_form;
2513 $strrequired = get_string('required');
2515 $mform->addElement('hidden', 'action', $this->action);
2516 $mform->setType('action', PARAM_TEXT);
2517 $mform->addElement('hidden', 'repos', $this->plugin);
2518 $mform->setType('repos', PARAM_PLUGIN);
2520 // let the plugin add its specific fields
2521 $classname = 'repository_' . $this->plugin;
2522 require_once($CFG->dirroot . '/repository/' . $this->plugin . '/lib.php');
2523 //add "enable course/user instances" checkboxes if multiple instances are allowed
2524 $instanceoptionnames = repository::static_function($this->plugin, 'get_instance_option_names');
2526 $result = call_user_func(array($classname, 'type_config_form'), $mform, $classname);
2528 if (!empty($instanceoptionnames)) {
2529 $sm = get_string_manager();
2530 $component = 'repository';
2531 if ($sm->string_exists('enablecourseinstances', 'repository_' . $this->plugin)) {
2532 $component .= ('_' . $this->plugin);
2534 $mform->addElement('checkbox', 'enablecourseinstances', get_string('enablecourseinstances', $component));
2536 $component = 'repository';
2537 if ($sm->string_exists('enableuserinstances', 'repository_' . $this->plugin)) {
2538 $component .= ('_' . $this->plugin);
2540 $mform->addElement('checkbox', 'enableuserinstances', get_string('enableuserinstances', $component));
2543 // set the data if we have some.
2544 if ($this->instance) {
2546 $option_names = call_user_func(array($classname,'get_type_option_names'));
2547 if (!empty($instanceoptionnames)){
2548 $option_names[] = 'enablecourseinstances';
2549 $option_names[] = 'enableuserinstances';
2552 $instanceoptions = $this->instance->get_options();
2553 foreach ($option_names as $config) {
2554 if (!empty($instanceoptions[$config])) {
2555 $data[$config] = $instanceoptions[$config];
2557 $data[$config] = '';
2560 // XXX: set plugin name for plugins which doesn't have muliti instances
2561 if (empty($instanceoptionnames)){
2562 $data['pluginname'] = $this->pluginname;
2564 $this->set_data($data);
2567 $this->add_action_buttons(true, get_string('save','repository'));
2571 * Validate moodle form data
2573 * @param array $data moodle form data
2574 * @param array $files
2575 * @return array errors
2577 public function validation($data, $files) {
2579 $plugin = $this->_customdata['plugin'];
2580 $instance = (isset($this->_customdata['instance'])
2581 && is_subclass_of($this->_customdata['instance'], 'repository'))
2582 ? $this->_customdata['instance'] : null;
2584 $errors = repository::static_function($plugin, 'type_form_validation', $this, $data, $errors);
2586 $errors = $instance->type_form_validation($this, $data, $errors);
2594 * Generate all options needed by filepicker
2596 * @param array $args including following keys
2601 * @return array the list of repository instances, including meta infomation, containing the following keys
2606 function initialise_filepicker($args) {
2607 global $CFG, $USER, $PAGE, $OUTPUT;
2608 static $templatesinitialized;
2609 require_once($CFG->libdir . '/licenselib.php');
2611 $return = new stdClass();
2612 $licenses = array();
2613 if (!empty($CFG->licenses)) {
2614 $array = explode(',', $CFG->licenses);
2615 foreach ($array as $license) {
2616 $l = new stdClass();
2617 $l->shortname = $license;
2618 $l->fullname = get_string($license, 'license');
2622 if (!empty($CFG->sitedefaultlicense)) {
2623 $return->defaultlicense = $CFG->sitedefaultlicense;
2626 $return->licenses = $licenses;
2628 $return->author = fullname($USER);
2630 if (empty($args->context)) {
2631 $context = $PAGE->context;
2633 $context = $args->context;
2635 $disable_types = array();
2636 if (!empty($args->disable_types)) {
2637 $disable_types = $args->disable_types;
2640 $user_context = get_context_instance(CONTEXT_USER, $USER->id);
2642 list($context, $course, $cm) = get_context_info_array($context->id);
2643 $contexts = array($user_context, get_system_context());
2644 if (!empty($course)) {
2645 // adding course context
2646 $contexts[] = get_context_instance(CONTEXT_COURSE, $course->id);
2648 $externallink = (int)get_config(null, 'repositoryallowexternallinks');
2649 $repositories = repository::get_instances(array(
2650 'context'=>$contexts,
2651 'currentcontext'=> $context,
2652 'accepted_types'=>$args->accepted_types,
2653 'return_types'=>$args->return_types,
2654 'disable_types'=>$disable_types
2657 $return->repositories = array();
2659 if (empty($externallink)) {
2660 $return->externallink = false;
2662 $return->externallink = true;
2665 $return->userprefs = array();
2666 $return->userprefs['recentrepository'] = get_user_preferences('filepicker_recentrepository', '');
2667 $return->userprefs['recentlicense'] = get_user_preferences('filepicker_recentlicense', '');
2668 $return->userprefs['recentviewmode'] = get_user_preferences('filepicker_recentviewmode', '');
2670 user_preference_allow_ajax_update('filepicker_recentrepository', PARAM_INT);
2671 user_preference_allow_ajax_update('filepicker_recentlicense', PARAM_SAFEDIR);
2672 user_preference_allow_ajax_update('filepicker_recentviewmode', PARAM_INT);
2675 // provided by form element
2676 $return->accepted_types = file_get_typegroup('extension', $args->accepted_types);
2677 $return->return_types = $args->return_types;
2678 foreach ($repositories as $repository) {
2679 $meta = $repository->get_meta();
2680 // Please note that the array keys for repositories are used within
2681 // JavaScript a lot, the key NEEDS to be the repository id.
2682 $return->repositories[$repository->id] = $meta;
2684 if (!$templatesinitialized) {
2685 // we need to send filepicker templates to the browser just once
2686 $fprenderer = $PAGE->get_renderer('core', 'files');
2687 $templates = $fprenderer->filepicker_js_templates();
2688 $PAGE->requires->js_init_call('M.core_filepicker.set_templates', array($templates), true);
2689 $templatesinitialized = true;
2694 * Small function to walk an array to attach repository ID
2696 * @param array $value
2697 * @param string $key
2700 function repository_attach_id(&$value, $key, $id){
2701 $value['repo_id'] = $id;