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
524 * @param array $options additional repository options
527 public static function get_repository_by_id($repositoryid, $context, $options = array()) {
530 $sql = 'SELECT i.name, i.typeid, r.type FROM {repository} r, {repository_instances} i WHERE i.id=? AND i.typeid=r.id';
532 if (!$record = $DB->get_record_sql($sql, array($repositoryid))) {
533 throw new repository_exception('invalidrepositoryid', 'repository');
535 $type = $record->type
;
536 if (file_exists($CFG->dirroot
. "/repository/$type/lib.php")) {
537 require_once($CFG->dirroot
. "/repository/$type/lib.php");
538 $classname = 'repository_' . $type;
539 $contextid = $context;
540 if (is_object($context)) {
541 $contextid = $context->id
;
543 $options['type'] = $type;
544 $options['typeid'] = $record->typeid
;
545 if (empty($options['name'])) {
546 $options['name'] = $record->name
;
548 $repository = new $classname($repositoryid, $contextid, $options);
551 throw new repository_exception('invalidplugin', 'repository');
557 * Get a repository type object by a given type name.
560 * @param string $typename the repository type name
561 * @return repository_type|bool
563 public static function get_type_by_typename($typename) {
566 if (!$record = $DB->get_record('repository',array('type' => $typename))) {
570 return new repository_type($typename, (array)get_config($typename), $record->visible
, $record->sortorder
);
574 * Get the repository type by a given repository type id.
577 * @param int $id the type id
580 public static function get_type_by_id($id) {
583 if (!$record = $DB->get_record('repository',array('id' => $id))) {
587 return new repository_type($record->type
, (array)get_config($record->type
), $record->visible
, $record->sortorder
);
591 * Return all repository types ordered by sortorder field
592 * first repository type in returnedarray[0], second repository type in returnedarray[1], ...
595 * @param bool $visible can return types by visiblity, return all types if null
596 * @return array Repository types
598 public static function get_types($visible=null) {
603 if (!empty($visible)) {
604 $params = array('visible' => $visible);
606 if ($records = $DB->get_records('repository',$params,'sortorder')) {
607 foreach($records as $type) {
608 if (file_exists($CFG->dirroot
. '/repository/'. $type->type
.'/lib.php')) {
609 $types[] = new repository_type($type->type
, (array)get_config($type->type
), $type->visible
, $type->sortorder
);
618 * Checks if user has a capability to view the current repository in current context
622 public final function check_capability() {
624 if (preg_match("/^repository_(.*)$/", get_class($this), $matches)) {
626 $capability = has_capability('repository/'.$type.':view', $this->context
);
629 throw new repository_exception('nopermissiontoaccess', 'repository');
634 * Check if file already exists in draft area
638 * @param string $filepath
639 * @param string $filename
642 public static function draftfile_exists($itemid, $filepath, $filename) {
644 $fs = get_file_storage();
645 $usercontext = get_context_instance(CONTEXT_USER
, $USER->id
);
646 if ($fs->get_file($usercontext->id
, 'user', 'draft', $itemid, $filepath, $filename)) {
654 * Parses the 'source' returned by moodle repositories and returns an instance of stored_file
656 * @param string $source
657 * @return stored_file|null
659 public static function get_moodle_file($source) {
660 $params = file_storage
::unpack_reference($source, true);
661 $fs = get_file_storage();
662 return $fs->get_file($params['contextid'], $params['component'], $params['filearea'],
663 $params['itemid'], $params['filepath'], $params['filename']);
667 * Repository method to make sure that user can access particular file.
669 * This is checked when user tries to pick the file from repository to deal with
670 * potential parameter substitutions is request
672 * @param string $source
673 * @return bool whether the file is accessible by current user
675 public function file_is_accessible($source) {
676 if ($this->has_moodle_files()) {
678 $params = file_storage
::unpack_reference($source, true);
679 } catch (file_reference_exception
$e) {
682 $browser = get_file_browser();
683 $context = context
::instance_by_id($params['contextid']);
684 $file_info = $browser->get_file_info($context, $params['component'], $params['filearea'],
685 $params['itemid'], $params['filepath'], $params['filename']);
686 return !empty($file_info);
692 * This function is used to copy a moodle file to draft area.
694 * It DOES NOT check if the user is allowed to access this file because the actual file
695 * can be located in the area where user does not have access to but there is an alias
696 * to this file in the area where user CAN access it.
697 * {@link file_is_accessible} should be called for alias location before calling this function.
699 * @param string $source The metainfo of file, it is base64 encoded php serialized data
700 * @param stdClass|array $filerecord contains itemid, filepath, filename and optionally other
701 * attributes of the new file
702 * @param int $maxbytes maximum allowed size of file, -1 if unlimited. If size of file exceeds
703 * the limit, the file_exception is thrown.
704 * @return array The information about the created file
706 public function copy_to_area($source, $filerecord, $maxbytes = -1) {
708 $fs = get_file_storage();
710 if ($this->has_moodle_files() == false) {
711 throw new coding_exception('Only repository used to browse moodle files can use repository::copy_to_area()');
714 $user_context = context_user
::instance($USER->id
);
716 $filerecord = (array)$filerecord;
717 // make sure the new file will be created in user draft area
718 $filerecord['component'] = 'user';
719 $filerecord['filearea'] = 'draft';
720 $filerecord['contextid'] = $user_context->id
;
721 $draftitemid = $filerecord['itemid'];
722 $new_filepath = $filerecord['filepath'];
723 $new_filename = $filerecord['filename'];
725 // the file needs to copied to draft area
726 $stored_file = self
::get_moodle_file($source);
727 if ($maxbytes != -1 && $stored_file->get_filesize() > $maxbytes) {
728 throw new file_exception('maxbytes');
731 if (repository
::draftfile_exists($draftitemid, $new_filepath, $new_filename)) {
733 $unused_filename = repository
::get_unused_filename($draftitemid, $new_filepath, $new_filename);
734 $filerecord['filename'] = $unused_filename;
735 $fs->create_file_from_storedfile($filerecord, $stored_file);
737 $event['event'] = 'fileexists';
738 $event['newfile'] = new stdClass
;
739 $event['newfile']->filepath
= $new_filepath;
740 $event['newfile']->filename
= $unused_filename;
741 $event['newfile']->url
= moodle_url
::make_draftfile_url($draftitemid, $new_filepath, $unused_filename)->out();
742 $event['existingfile'] = new stdClass
;
743 $event['existingfile']->filepath
= $new_filepath;
744 $event['existingfile']->filename
= $new_filename;
745 $event['existingfile']->url
= moodle_url
::make_draftfile_url($draftitemid, $new_filepath, $new_filename)->out();
748 $fs->create_file_from_storedfile($filerecord, $stored_file);
750 $info['itemid'] = $draftitemid;
751 $info['file'] = $new_filename;
752 $info['title'] = $new_filename;
753 $info['contextid'] = $user_context->id
;
754 $info['url'] = moodle_url
::make_draftfile_url($draftitemid, $new_filepath, $new_filename)->out();
755 $info['filesize'] = $stored_file->get_filesize();
761 * Get unused filename by appending suffix
765 * @param string $filepath
766 * @param string $filename
769 public static function get_unused_filename($itemid, $filepath, $filename) {
771 $fs = get_file_storage();
772 while (repository
::draftfile_exists($itemid, $filepath, $filename)) {
773 $filename = repository
::append_suffix($filename);
779 * Append a suffix to filename
782 * @param string $filename
785 public static function append_suffix($filename) {
786 $pathinfo = pathinfo($filename);
787 if (empty($pathinfo['extension'])) {
788 return $filename . RENAME_SUFFIX
;
790 return $pathinfo['filename'] . RENAME_SUFFIX
. '.' . $pathinfo['extension'];
795 * Return all types that you a user can create/edit and which are also visible
796 * Note: Mostly used in order to know if at least one editable type can be set
799 * @param stdClass $context the context for which we want the editable types
800 * @return array types
802 public static function get_editable_types($context = null) {
804 if (empty($context)) {
805 $context = get_system_context();
808 $types= repository
::get_types(true);
809 $editabletypes = array();
810 foreach ($types as $type) {
811 $instanceoptionnames = repository
::static_function($type->get_typename(), 'get_instance_option_names');
812 if (!empty($instanceoptionnames)) {
813 if ($type->get_contextvisibility($context)) {
814 $editabletypes[]=$type;
818 return $editabletypes;
822 * Return repository instances
825 * @param array $args Array containing the following keys:
834 * @return array repository instances
836 public static function get_instances($args = array()) {
837 global $DB, $CFG, $USER;
839 if (isset($args['currentcontext'])) {
840 $current_context = $args['currentcontext'];
842 $current_context = null;
845 if (!empty($args['context'])) {
846 $contexts = $args['context'];
851 $onlyvisible = isset($args['onlyvisible']) ?
$args['onlyvisible'] : true;
852 $returntypes = isset($args['return_types']) ?
$args['return_types'] : 3;
853 $type = isset($args['type']) ?
$args['type'] : null;
856 $sql = "SELECT i.*, r.type AS repositorytype, r.sortorder, r.visible
857 FROM {repository} r, {repository_instances} i
858 WHERE i.typeid = r.id ";
860 if (!empty($args['disable_types']) && is_array($args['disable_types'])) {
861 list($types, $p) = $DB->get_in_or_equal($args['disable_types'], SQL_PARAMS_QM
, 'param', false);
862 $sql .= " AND r.type $types";
863 $params = array_merge($params, $p);
866 if (!empty($args['userid']) && is_numeric($args['userid'])) {
867 $sql .= " AND (i.userid = 0 or i.userid = ?)";
868 $params[] = $args['userid'];
871 foreach ($contexts as $context) {
872 if (empty($firstcontext)) {
873 $firstcontext = true;
874 $sql .= " AND ((i.contextid = ?)";
876 $sql .= " OR (i.contextid = ?)";
878 $params[] = $context->id
;
881 if (!empty($firstcontext)) {
885 if ($onlyvisible == true) {
886 $sql .= " AND (r.visible = 1)";
890 $sql .= " AND (r.type = ?)";
893 $sql .= " ORDER BY r.sortorder, i.name";
895 if (!$records = $DB->get_records_sql($sql, $params)) {
899 $repositories = array();
900 if (isset($args['accepted_types'])) {
901 $accepted_types = $args['accepted_types'];
903 $accepted_types = '*';
905 // Sortorder should be unique, which is not true if we use $record->sortorder
906 // and there are multiple instances of any repository type
908 foreach ($records as $record) {
909 if (!file_exists($CFG->dirroot
. '/repository/'. $record->repositorytype
.'/lib.php')) {
912 require_once($CFG->dirroot
. '/repository/'. $record->repositorytype
.'/lib.php');
913 $options['visible'] = $record->visible
;
914 $options['type'] = $record->repositorytype
;
915 $options['typeid'] = $record->typeid
;
916 $options['sortorder'] = $sortorder++
;
917 // tell instance what file types will be accepted by file picker
918 $classname = 'repository_' . $record->repositorytype
;
920 $repository = new $classname($record->id
, $record->contextid
, $options, $record->readonly
);
922 $is_supported = true;
924 if (empty($repository->super_called
)) {
925 // to make sure the super construct is called
926 debugging('parent::__construct must be called by '.$record->repositorytype
.' plugin.');
929 if ($accepted_types !== '*' and $repository->supported_filetypes() !== '*') {
930 $accepted_ext = file_get_typegroup('extension', $accepted_types);
931 $supported_ext = file_get_typegroup('extension', $repository->supported_filetypes());
932 $valid_ext = array_intersect($accepted_ext, $supported_ext);
933 $is_supported = !empty($valid_ext);
935 // check return values
936 if ($returntypes !== 3 and $repository->supported_returntypes() !== 3) {
937 $type = $repository->supported_returntypes();
938 if ($type & $returntypes) {
941 $is_supported = false;
945 if (!$onlyvisible ||
($repository->is_visible() && !$repository->disabled
)) {
946 // check capability in current context
947 if (!empty($current_context)) {
948 $capability = has_capability('repository/'.$record->repositorytype
.':view', $current_context);
950 $capability = has_capability('repository/'.$record->repositorytype
.':view', get_system_context());
952 if ($record->repositorytype
== 'coursefiles') {
953 // coursefiles plugin needs managefiles permission
954 if (!empty($current_context)) {
955 $capability = $capability && has_capability('moodle/course:managefiles', $current_context);
957 $capability = $capability && has_capability('moodle/course:managefiles', get_system_context());
960 if ($is_supported && $capability) {
961 $repositories[$repository->id
] = $repository;
966 return $repositories;
970 * Get single repository instance
973 * @param integer $id repository id
974 * @return object repository instance
976 public static function get_instance($id) {
978 $sql = "SELECT i.*, r.type AS repositorytype, r.visible
980 JOIN {repository_instances} i ON i.typeid = r.id
983 if (!$instance = $DB->get_record_sql($sql, array($id))) {
986 require_once($CFG->dirroot
. '/repository/'. $instance->repositorytype
.'/lib.php');
987 $classname = 'repository_' . $instance->repositorytype
;
988 $options['typeid'] = $instance->typeid
;
989 $options['type'] = $instance->repositorytype
;
990 $options['name'] = $instance->name
;
991 $obj = new $classname($instance->id
, $instance->contextid
, $options, $instance->readonly
);
992 if (empty($obj->super_called
)) {
993 debugging('parent::__construct must be called by '.$classname.' plugin.');
999 * Call a static function. Any additional arguments than plugin and function will be passed through.
1002 * @param string $plugin repository plugin name
1003 * @param string $function funciton name
1006 public static function static_function($plugin, $function) {
1009 //check that the plugin exists
1010 $typedirectory = $CFG->dirroot
. '/repository/'. $plugin . '/lib.php';
1011 if (!file_exists($typedirectory)) {
1012 //throw new repository_exception('invalidplugin', 'repository');
1017 if (is_object($plugin) ||
is_array($plugin)) {
1018 $plugin = (object)$plugin;
1019 $pname = $plugin->name
;
1024 $args = func_get_args();
1025 if (count($args) <= 2) {
1032 require_once($typedirectory);
1033 return call_user_func_array(array('repository_' . $plugin, $function), $args);
1037 * Scan file, throws exception in case of infected file.
1039 * Please note that the scanning engine must be able to access the file,
1040 * permissions of the file are not modified here!
1043 * @param string $thefile
1044 * @param string $filename name of the file
1045 * @param bool $deleteinfected
1047 public static function antivir_scan_file($thefile, $filename, $deleteinfected) {
1050 if (!is_readable($thefile)) {
1051 // this should not happen
1055 if (empty($CFG->runclamonupload
) or empty($CFG->pathtoclam
)) {
1060 $CFG->pathtoclam
= trim($CFG->pathtoclam
);
1062 if (!file_exists($CFG->pathtoclam
) or !is_executable($CFG->pathtoclam
)) {
1063 // misconfigured clam - use the old notification for now
1064 require("$CFG->libdir/uploadlib.php");
1065 $notice = get_string('clamlost', 'moodle', $CFG->pathtoclam
);
1066 clam_message_admins($notice);
1070 // do NOT mess with permissions here, the calling party is responsible for making
1071 // sure the scanner engine can access the files!
1074 $cmd = escapeshellcmd($CFG->pathtoclam
).' --stdout '.escapeshellarg($thefile);
1075 exec($cmd, $output, $return);
1078 // perfect, no problem found
1081 } else if ($return == 1) {
1083 if ($deleteinfected) {
1086 throw new moodle_exception('virusfounduser', 'moodle', '', array('filename'=>$filename));
1090 require("$CFG->libdir/uploadlib.php");
1091 $notice = get_string('clamfailed', 'moodle', get_clam_error_code($return));
1092 $notice .= "\n\n". implode("\n", $output);
1093 clam_message_admins($notice);
1094 if ($CFG->clamfailureonupload
=== 'actlikevirus') {
1095 if ($deleteinfected) {
1098 throw new moodle_exception('virusfounduser', 'moodle', '', array('filename'=>$filename));
1106 * Repository method to serve the referenced file
1108 * @see send_stored_file
1110 * @param stored_file $storedfile the file that contains the reference
1111 * @param int $lifetime Number of seconds before the file should expire from caches (default 24 hours)
1112 * @param int $filter 0 (default)=no filtering, 1=all files, 2=html files only
1113 * @param bool $forcedownload If true (default false), forces download of file rather than view in browser/plugin
1114 * @param array $options additional options affecting the file serving
1116 public function send_file($storedfile, $lifetime=86400 , $filter=0, $forcedownload=false, array $options = null) {
1117 if ($this->has_moodle_files()) {
1118 $fs = get_file_storage();
1119 $params = file_storage
::unpack_reference($storedfile->get_reference(), true);
1121 if (is_array($params)) {
1122 $srcfile = $fs->get_file($params['contextid'], $params['component'], $params['filearea'],
1123 $params['itemid'], $params['filepath'], $params['filename']);
1125 if (empty($options)) {
1128 if (!isset($options['filename'])) {
1129 $options['filename'] = $storedfile->get_filename();
1132 send_file_not_found();
1134 send_stored_file($srcfile, $lifetime, $filter, $forcedownload, $options);
1137 throw new coding_exception("Repository plugin must implement send_file() method.");
1142 * Return reference file life time
1144 * @param string $ref
1147 public function get_reference_file_lifetime($ref) {
1149 return 60 * 60 * 24;
1153 * Decide whether or not the file should be synced
1155 * @param stored_file $storedfile
1158 public function sync_individual_file(stored_file
$storedfile) {
1163 * Return human readable reference information
1164 * {@link stored_file::get_reference()}
1166 * @param string $reference
1167 * @param int $filestatus status of the file, 0 - ok, 666 - source missing
1170 public function get_reference_details($reference, $filestatus = 0) {
1171 if ($this->has_moodle_files()) {
1173 $params = file_storage
::unpack_reference($reference, true);
1174 if (is_array($params)) {
1175 $context = get_context_instance_by_id($params['contextid']);
1177 $browser = get_file_browser();
1178 $fileinfo = $browser->get_file_info($context, $params['component'], $params['filearea'], $params['itemid'], $params['filepath'], $params['filename']);
1181 if (empty($fileinfo)) {
1182 if ($filestatus == 666) {
1183 if (is_siteadmin() ||
($context && has_capability('moodle/course:managefiles', $context))) {
1184 return get_string('lostsource', 'repository',
1185 $params['contextid']. '/'. $params['component']. '/'. $params['filearea']. '/'. $params['itemid']. $params['filepath']. $params['filename']);
1187 return get_string('lostsource', 'repository', '');
1190 return get_string('undisclosedsource', 'repository');
1192 return $fileinfo->get_readable_fullname();
1199 * Cache file from external repository by reference
1200 * {@link repository::get_file_reference()}
1201 * {@link repository::get_file()}
1202 * Invoked at MOODLE/repository/repository_ajax.php
1204 * @param string $reference this reference is generated by
1205 * repository::get_file_reference()
1206 * @param stored_file $storedfile created file reference
1208 public function cache_file_by_reference($reference, $storedfile) {
1212 * Returns information about file in this repository by reference
1213 * {@link repository::get_file_reference()}
1214 * {@link repository::get_file()}
1216 * Returns null if file not found or is not readable
1218 * @param stdClass $reference file reference db record
1219 * @return stdClass|null contains one of the following:
1220 * - 'contenthash' and 'filesize'
1225 public function get_file_by_reference($reference) {
1226 if ($this->has_moodle_files() && isset($reference->reference
)) {
1227 $fs = get_file_storage();
1228 $params = file_storage
::unpack_reference($reference->reference
, true);
1229 if (!is_array($params) ||
!($storedfile = $fs->get_file($params['contextid'],
1230 $params['component'], $params['filearea'], $params['itemid'], $params['filepath'],
1231 $params['filename']))) {
1234 return (object)array(
1235 'contenthash' => $storedfile->get_contenthash(),
1236 'filesize' => $storedfile->get_filesize()
1243 * Return the source information
1245 * @param stdClass $url
1246 * @return string|null
1248 public function get_file_source_info($url) {
1249 if ($this->has_moodle_files()) {
1250 return $this->get_reference_details($url, 0);
1256 * Move file from download folder to file pool using FILE API
1260 * @param string $thefile file path in download folder
1261 * @param stdClass $record
1262 * @return array containing the following keys:
1268 public static function move_to_filepool($thefile, $record) {
1269 global $DB, $CFG, $USER, $OUTPUT;
1271 // scan for viruses if possible, throws exception if problem found
1272 self
::antivir_scan_file($thefile, $record->filename
, empty($CFG->repository_no_delete
)); //TODO: MDL-28637 this repository_no_delete is a bloody hack!
1274 $fs = get_file_storage();
1275 // If file name being used.
1276 if (repository
::draftfile_exists($record->itemid
, $record->filepath
, $record->filename
)) {
1277 $draftitemid = $record->itemid
;
1278 $new_filename = repository
::get_unused_filename($draftitemid, $record->filepath
, $record->filename
);
1279 $old_filename = $record->filename
;
1280 // Create a tmp file.
1281 $record->filename
= $new_filename;
1282 $newfile = $fs->create_file_from_pathname($record, $thefile);
1284 $event['event'] = 'fileexists';
1285 $event['newfile'] = new stdClass
;
1286 $event['newfile']->filepath
= $record->filepath
;
1287 $event['newfile']->filename
= $new_filename;
1288 $event['newfile']->url
= moodle_url
::make_draftfile_url($draftitemid, $record->filepath
, $new_filename)->out();
1290 $event['existingfile'] = new stdClass
;
1291 $event['existingfile']->filepath
= $record->filepath
;
1292 $event['existingfile']->filename
= $old_filename;
1293 $event['existingfile']->url
= moodle_url
::make_draftfile_url($draftitemid, $record->filepath
, $old_filename)->out();;
1296 if ($file = $fs->create_file_from_pathname($record, $thefile)) {
1297 if (empty($CFG->repository_no_delete
)) {
1298 $delete = unlink($thefile);
1299 unset($CFG->repository_no_delete
);
1302 'url'=>moodle_url
::make_draftfile_url($file->get_itemid(), $file->get_filepath(), $file->get_filename())->out(),
1303 'id'=>$file->get_itemid(),
1304 'file'=>$file->get_filename(),
1305 'icon' => $OUTPUT->pix_url(file_extension_icon($thefile, 32))->out(),
1313 * Builds a tree of files This function is then called recursively.
1316 * @todo take $search into account, and respect a threshold for dynamic loading
1317 * @param file_info $fileinfo an object returned by file_browser::get_file_info()
1318 * @param string $search searched string
1319 * @param bool $dynamicmode no recursive call is done when in dynamic mode
1320 * @param array $list the array containing the files under the passed $fileinfo
1321 * @returns int the number of files found
1324 public static function build_tree($fileinfo, $search, $dynamicmode, &$list) {
1325 global $CFG, $OUTPUT;
1328 $children = $fileinfo->get_children();
1330 foreach ($children as $child) {
1331 $filename = $child->get_visible_name();
1332 $filesize = $child->get_filesize();
1333 $filesize = $filesize ?
display_size($filesize) : '';
1334 $filedate = $child->get_timemodified();
1335 $filedate = $filedate ?
userdate($filedate) : '';
1336 $filetype = $child->get_mimetype();
1338 if ($child->is_directory()) {
1340 $level = $child->get_parent();
1342 $params = $level->get_params();
1343 $path[] = array($params['filepath'], $level->get_visible_name());
1344 $level = $level->get_parent();
1348 'title' => $child->get_visible_name(),
1350 'date' => $filedate,
1351 'path' => array_reverse($path),
1352 'thumbnail' => $OUTPUT->pix_url(file_folder_icon(90))->out(false)
1355 //if ($dynamicmode && $child->is_writable()) {
1356 // $tmp['children'] = array();
1358 // if folder name matches search, we send back all files contained.
1360 if ($search && stristr($tmp['title'], $search) !== false) {
1363 $tmp['children'] = array();
1364 $_filecount = repository
::build_tree($child, $_search, $dynamicmode, $tmp['children']);
1365 if ($search && $_filecount) {
1366 $tmp['expanded'] = 1;
1371 if (!$search ||
$_filecount ||
(stristr($tmp['title'], $search) !== false)) {
1372 $filecount +
= $_filecount;
1376 } else { // not a directory
1377 // skip the file, if we're in search mode and it's not a match
1378 if ($search && (stristr($filename, $search) === false)) {
1381 $params = $child->get_params();
1382 $source = serialize(array($params['contextid'], $params['component'], $params['filearea'], $params['itemid'], $params['filepath'], $params['filename']));
1384 'title' => $filename,
1385 'size' => $filesize,
1386 'date' => $filedate,
1387 //'source' => $child->get_url(),
1388 'source' => base64_encode($source),
1389 'icon'=>$OUTPUT->pix_url(file_file_icon($child, 24))->out(false),
1390 'thumbnail'=>$OUTPUT->pix_url(file_file_icon($child, 90))->out(false),
1400 * Display a repository instance list (with edit/delete/create links)
1403 * @param stdClass $context the context for which we display the instance
1404 * @param string $typename if set, we display only one type of instance
1406 public static function display_instances_list($context, $typename = null) {
1407 global $CFG, $USER, $OUTPUT;
1409 $output = $OUTPUT->box_start('generalbox');
1410 //if the context is SYSTEM, so we call it from administration page
1411 $admin = ($context->id
== SYSCONTEXTID
) ?
true : false;
1413 $baseurl = new moodle_url('/'.$CFG->admin
.'/repositoryinstance.php', array('sesskey'=>sesskey()));
1414 $output .= $OUTPUT->heading(get_string('siteinstances', 'repository'));
1416 $baseurl = new moodle_url('/repository/manage_instances.php', array('contextid'=>$context->id
, 'sesskey'=>sesskey()));
1419 $namestr = get_string('name');
1420 $pluginstr = get_string('plugin', 'repository');
1421 $settingsstr = get_string('settings');
1422 $deletestr = get_string('delete');
1423 //retrieve list of instances. In administration context we want to display all
1424 //instances of a type, even if this type is not visible. In course/user context we
1425 //want to display only visible instances, but for every type types. The repository::get_instances()
1426 //third parameter displays only visible type.
1428 $params['context'] = array($context, get_system_context());
1429 $params['currentcontext'] = $context;
1430 $params['onlyvisible'] = !$admin;
1431 $params['type'] = $typename;
1432 $instances = repository
::get_instances($params);
1433 $instancesnumber = count($instances);
1434 $alreadyplugins = array();
1436 $table = new html_table();
1437 $table->head
= array($namestr, $pluginstr, $settingsstr, $deletestr);
1438 $table->align
= array('left', 'left', 'center','center');
1439 $table->data
= array();
1443 foreach ($instances as $i) {
1447 $type = repository
::get_type_by_id($i->options
['typeid']);
1449 if ($type->get_contextvisibility($context)) {
1450 if (!$i->readonly
) {
1452 $settingurl = new moodle_url($baseurl);
1453 $settingurl->param('type', $i->options
['type']);
1454 $settingurl->param('edit', $i->id
);
1455 $settings .= html_writer
::link($settingurl, $settingsstr);
1457 $deleteurl = new moodle_url($baseurl);
1458 $deleteurl->param('delete', $i->id
);
1459 $deleteurl->param('type', $i->options
['type']);
1460 $delete .= html_writer
::link($deleteurl, $deletestr);
1464 $type = repository
::get_type_by_id($i->options
['typeid']);
1465 $table->data
[] = array(format_string($i->name
), $type->get_readablename(), $settings, $delete);
1467 //display a grey row if the type is defined as not visible
1468 if (isset($type) && !$type->get_visible()) {
1469 $table->rowclasses
[] = 'dimmed_text';
1471 $table->rowclasses
[] = '';
1474 if (!in_array($i->name
, $alreadyplugins)) {
1475 $alreadyplugins[] = $i->name
;
1478 $output .= html_writer
::table($table);
1479 $instancehtml = '<div>';
1482 //if no type is set, we can create all type of instance
1484 $instancehtml .= '<h3>';
1485 $instancehtml .= get_string('createrepository', 'repository');
1486 $instancehtml .= '</h3><ul>';
1487 $types = repository
::get_editable_types($context);
1488 foreach ($types as $type) {
1489 if (!empty($type) && $type->get_visible()) {
1490 $instanceoptionnames = repository
::static_function($type->get_typename(), 'get_instance_option_names');
1491 if (!empty($instanceoptionnames)) {
1492 $baseurl->param('new', $type->get_typename());
1493 $instancehtml .= '<li><a href="'.$baseurl->out().'">'.get_string('createxxinstance', 'repository', get_string('pluginname', 'repository_'.$type->get_typename())). '</a></li>';
1494 $baseurl->remove_params('new');
1499 $instancehtml .= '</ul>';
1502 $instanceoptionnames = repository
::static_function($typename, 'get_instance_option_names');
1503 if (!empty($instanceoptionnames)) { //create a unique type of instance
1505 $baseurl->param('new', $typename);
1506 $output .= $OUTPUT->single_button($baseurl, get_string('createinstance', 'repository'), 'get');
1507 $baseurl->remove_params('new');
1512 $instancehtml .= '</div>';
1513 $output .= $instancehtml;
1516 $output .= $OUTPUT->box_end();
1518 //print the list + creation links
1523 * Prepare file reference information
1525 * @param string $source
1526 * @return string file referece
1528 public function get_file_reference($source) {
1529 if ($this->has_moodle_files() && ($this->supported_returntypes() & FILE_REFERENCE
)) {
1530 $params = file_storage
::unpack_reference($source);
1531 if (!is_array($params)) {
1532 throw new repository_exception('invalidparams', 'repository');
1534 return file_storage
::pack_reference($params);
1539 * Decide where to save the file, can be overwriten by subclass
1541 * @param string $filename file name
1544 public function prepare_file($filename) {
1546 if (!file_exists($CFG->tempdir
.'/download')) {
1547 mkdir($CFG->tempdir
.'/download/', $CFG->directorypermissions
, true);
1549 if (is_dir($CFG->tempdir
.'/download')) {
1550 $dir = $CFG->tempdir
.'/download/';
1552 if (empty($filename)) {
1553 $filename = uniqid('repo', true).'_'.time().'.tmp';
1555 if (file_exists($dir.$filename)) {
1556 $filename = uniqid('m').$filename;
1558 return $dir.$filename;
1562 * Does this repository used to browse moodle files?
1566 public function has_moodle_files() {
1571 * Return file URL, for most plugins, the parameter is the original
1572 * url, but some plugins use a file id, so we need this function to
1573 * convert file id to original url.
1575 * @param string $url the url of file
1578 public function get_link($url) {
1583 * Download a file, this function can be overridden by subclass. {@link curl}
1585 * @param string $url the url of file
1586 * @param string $filename save location
1587 * @return array with elements:
1588 * path: internal location of the file
1589 * url: URL to the source (from parameters)
1591 public function get_file($url, $filename = '') {
1593 $path = $this->prepare_file($filename);
1594 $fp = fopen($path, 'w');
1596 $result = $c->download(array(array('url'=>$url, 'file'=>$fp)));
1597 // Close file handler.
1599 if (empty($result)) {
1603 return array('path'=>$path, 'url'=>$url);
1607 * Return size of a file in bytes.
1609 * @param string $source encoded and serialized data of file
1610 * @return int file size in bytes
1612 public function get_file_size($source) {
1613 // TODO MDL-33297 remove this function completely?
1614 $browser = get_file_browser();
1615 $params = unserialize(base64_decode($source));
1616 $contextid = clean_param($params['contextid'], PARAM_INT
);
1617 $fileitemid = clean_param($params['itemid'], PARAM_INT
);
1618 $filename = clean_param($params['filename'], PARAM_FILE
);
1619 $filepath = clean_param($params['filepath'], PARAM_PATH
);
1620 $filearea = clean_param($params['filearea'], PARAM_AREA
);
1621 $component = clean_param($params['component'], PARAM_COMPONENT
);
1622 $context = get_context_instance_by_id($contextid);
1623 $file_info = $browser->get_file_info($context, $component, $filearea, $fileitemid, $filepath, $filename);
1624 if (!empty($file_info)) {
1625 $filesize = $file_info->get_filesize();
1633 * Return is the instance is visible
1634 * (is the type visible ? is the context enable ?)
1638 public function is_visible() {
1639 $type = repository
::get_type_by_id($this->options
['typeid']);
1640 $instanceoptions = repository
::static_function($type->get_typename(), 'get_instance_option_names');
1642 if ($type->get_visible()) {
1643 //if the instance is unique so it's visible, otherwise check if the instance has a enabled context
1644 if (empty($instanceoptions) ||
$type->get_contextvisibility($this->context
)) {
1653 * Return the name of this instance, can be overridden.
1657 public function get_name() {
1659 if ( $name = $this->instance
->name
) {
1662 return get_string('pluginname', 'repository_' . $this->options
['type']);
1667 * What kind of files will be in this repository?
1669 * @return array return '*' means this repository support any files, otherwise
1670 * return mimetypes of files, it can be an array
1672 public function supported_filetypes() {
1673 // return array('text/plain', 'image/gif');
1678 * Tells how the file can be picked from this repository
1680 * Maximum value is FILE_INTERNAL | FILE_EXTERNAL | FILE_REFERENCE
1684 public function supported_returntypes() {
1685 return (FILE_INTERNAL | FILE_EXTERNAL
);
1689 * Provide repository instance information for Ajax
1693 final public function get_meta() {
1694 global $CFG, $OUTPUT;
1695 $meta = new stdClass();
1696 $meta->id
= $this->id
;
1697 $meta->name
= format_string($this->get_name());
1698 $meta->type
= $this->options
['type'];
1699 $meta->icon
= $OUTPUT->pix_url('icon', 'repository_'.$meta->type
)->out(false);
1700 $meta->supported_types
= file_get_typegroup('extension', $this->supported_filetypes());
1701 $meta->return_types
= $this->supported_returntypes();
1702 $meta->sortorder
= $this->options
['sortorder'];
1707 * Create an instance for this plug-in
1710 * @param string $type the type of the repository
1711 * @param int $userid the user id
1712 * @param stdClass $context the context
1713 * @param array $params the options for this instance
1714 * @param int $readonly whether to create it readonly or not (defaults to not)
1717 public static function create($type, $userid, $context, $params, $readonly=0) {
1719 $params = (array)$params;
1720 require_once($CFG->dirroot
. '/repository/'. $type . '/lib.php');
1721 $classname = 'repository_' . $type;
1722 if ($repo = $DB->get_record('repository', array('type'=>$type))) {
1723 $record = new stdClass();
1724 $record->name
= $params['name'];
1725 $record->typeid
= $repo->id
;
1726 $record->timecreated
= time();
1727 $record->timemodified
= time();
1728 $record->contextid
= $context->id
;
1729 $record->readonly
= $readonly;
1730 $record->userid
= $userid;
1731 $id = $DB->insert_record('repository_instances', $record);
1733 $configs = call_user_func($classname . '::get_instance_option_names');
1734 if (!empty($configs)) {
1735 foreach ($configs as $config) {
1736 if (isset($params[$config])) {
1737 $options[$config] = $params[$config];
1739 $options[$config] = null;
1745 unset($options['name']);
1746 $instance = repository
::get_instance($id);
1747 $instance->set_option($options);
1758 * delete a repository instance
1760 * @param bool $downloadcontents
1763 final public function delete($downloadcontents = false) {
1765 if ($downloadcontents) {
1766 $this->convert_references_to_local();
1769 $DB->delete_records('repository_instances', array('id'=>$this->id
));
1770 $DB->delete_records('repository_instance_config', array('instanceid'=>$this->id
));
1771 } catch (dml_exception
$ex) {
1778 * Hide/Show a repository
1780 * @param string $hide
1783 final public function hide($hide = 'toggle') {
1785 if ($entry = $DB->get_record('repository', array('id'=>$this->id
))) {
1786 if ($hide === 'toggle' ) {
1787 if (!empty($entry->visible
)) {
1788 $entry->visible
= 0;
1790 $entry->visible
= 1;
1793 if (!empty($hide)) {
1794 $entry->visible
= 0;
1796 $entry->visible
= 1;
1799 return $DB->update_record('repository', $entry);
1805 * Save settings for repository instance
1806 * $repo->set_option(array('api_key'=>'f2188bde132', 'name'=>'dongsheng'));
1808 * @param array $options settings
1811 public function set_option($options = array()) {
1814 if (!empty($options['name'])) {
1815 $r = new stdClass();
1817 $r->name
= $options['name'];
1818 $DB->update_record('repository_instances', $r);
1819 unset($options['name']);
1821 foreach ($options as $name=>$value) {
1822 if ($id = $DB->get_field('repository_instance_config', 'id', array('name'=>$name, 'instanceid'=>$this->id
))) {
1823 $DB->set_field('repository_instance_config', 'value', $value, array('id'=>$id));
1825 $config = new stdClass();
1826 $config->instanceid
= $this->id
;
1827 $config->name
= $name;
1828 $config->value
= $value;
1829 $DB->insert_record('repository_instance_config', $config);
1836 * Get settings for repository instance
1838 * @param string $config
1839 * @return array Settings
1841 public function get_option($config = '') {
1843 $entries = $DB->get_records('repository_instance_config', array('instanceid'=>$this->id
));
1845 if (empty($entries)) {
1848 foreach($entries as $entry) {
1849 $ret[$entry->name
] = $entry->value
;
1851 if (!empty($config)) {
1852 if (isset($ret[$config])) {
1853 return $ret[$config];
1863 * Filter file listing to display specific types
1865 * @param array $value
1868 public function filter(&$value) {
1869 $accepted_types = optional_param_array('accepted_types', '', PARAM_RAW
);
1870 if (isset($value['children'])) {
1871 if (!empty($value['children'])) {
1872 $value['children'] = array_filter($value['children'], array($this, 'filter'));
1874 return true; // always return directories
1876 if ($accepted_types == '*' or empty($accepted_types)
1877 or (is_array($accepted_types) and in_array('*', $accepted_types))) {
1880 foreach ($accepted_types as $ext) {
1881 if (preg_match('#'.$ext.'$#i', $value['title'])) {
1891 * Given a path, and perhaps a search, get a list of files.
1893 * See details on {@link http://docs.moodle.org/dev/Repository_plugins}
1895 * @param string $path this parameter can a folder name, or a identification of folder
1896 * @param string $page the page number of file list
1897 * @return array the list of files, including meta infomation, containing the following keys
1898 * manage, url to manage url
1901 * repo_id, active repository id
1902 * login_btn_action, the login button action
1903 * login_btn_label, the login button label
1904 * total, number of results
1905 * perpage, items per page
1907 * pages, total pages
1908 * issearchresult, is it a search result?
1910 * path, current path and parent path
1912 public function get_listing($path = '', $page = '') {
1916 * Prepares list of files before passing it to AJAX, makes sure data is in the correct
1917 * format and stores formatted values.
1919 * @param array|stdClass $listing result of get_listing() or search() or file_get_drafarea_files()
1922 public static function prepare_listing($listing) {
1925 $defaultfoldericon = $OUTPUT->pix_url(file_folder_icon(24))->out(false);
1926 // prepare $listing['path'] or $listing->path
1927 if (is_array($listing) && isset($listing['path']) && is_array($listing['path'])) {
1928 $path = &$listing['path'];
1929 } else if (is_object($listing) && isset($listing->path
) && is_array($listing->path
)) {
1930 $path = &$listing->path
;
1933 $len = count($path);
1934 for ($i=0; $i<$len; $i++
) {
1935 if (is_array($path[$i]) && !isset($path[$i]['icon'])) {
1936 $path[$i]['icon'] = $defaultfoldericon;
1937 } else if (is_object($path[$i]) && !isset($path[$i]->icon
)) {
1938 $path[$i]->icon
= $defaultfoldericon;
1943 // prepare $listing['list'] or $listing->list
1944 if (is_array($listing) && isset($listing['list']) && is_array($listing['list'])) {
1945 $listing['list'] = array_values($listing['list']); // convert to array
1946 $files = &$listing['list'];
1947 } else if (is_object($listing) && isset($listing->list) && is_array($listing->list)) {
1948 $listing->list = array_values($listing->list); // convert to array
1949 $files = &$listing->list;
1953 $len = count($files);
1954 for ($i=0; $i<$len; $i++
) {
1955 if (is_object($files[$i])) {
1956 $file = (array)$files[$i];
1957 $converttoobject = true;
1959 $file = & $files[$i];
1960 $converttoobject = false;
1962 if (isset($file['size'])) {
1963 $file['size'] = (int)$file['size'];
1964 $file['size_f'] = display_size($file['size']);
1966 if (isset($file['license']) &&
1967 get_string_manager()->string_exists($file['license'], 'license')) {
1968 $file['license_f'] = get_string($file['license'], 'license');
1970 if (isset($file['image_width']) && isset($file['image_height'])) {
1971 $a = array('width' => $file['image_width'], 'height' => $file['image_height']);
1972 $file['dimensions'] = get_string('imagesize', 'repository', (object)$a);
1974 foreach (array('date', 'datemodified', 'datecreated') as $key) {
1975 if (!isset($file[$key]) && isset($file['date'])) {
1976 $file[$key] = $file['date'];
1978 if (isset($file[$key])) {
1979 // must be UNIX timestamp
1980 $file[$key] = (int)$file[$key];
1984 $file[$key.'_f'] = userdate($file[$key], get_string('strftimedatetime', 'langconfig'));
1985 $file[$key.'_f_s'] = userdate($file[$key], get_string('strftimedatetimeshort', 'langconfig'));
1989 $isfolder = (array_key_exists('children', $file) ||
(isset($file['type']) && $file['type'] == 'folder'));
1991 if (isset($file['title'])) {
1992 $filename = $file['title'];
1994 else if (isset($file['fullname'])) {
1995 $filename = $file['fullname'];
1997 if (!isset($file['mimetype']) && !$isfolder && $filename) {
1998 $file['mimetype'] = get_mimetype_description(array('filename' => $filename));
2000 if (!isset($file['icon'])) {
2002 $file['icon'] = $defaultfoldericon;
2003 } else if ($filename) {
2004 $file['icon'] = $OUTPUT->pix_url(file_extension_icon($filename, 24))->out(false);
2007 if ($converttoobject) {
2008 $files[$i] = (object)$file;
2015 * Search files in repository
2016 * When doing global search, $search_text will be used as
2019 * @param string $search_text search key word
2020 * @param int $page page
2021 * @return mixed {@see repository::get_listing}
2023 public function search($search_text, $page = 0) {
2025 $list['list'] = array();
2030 * Logout from repository instance
2031 * By default, this function will return a login form
2035 public function logout(){
2036 return $this->print_login();
2040 * To check whether the user is logged in.
2044 public function check_login(){
2050 * Show the login screen, if required
2054 public function print_login(){
2055 return $this->get_listing();
2059 * Show the search screen, if required
2063 public function print_search() {
2065 $renderer = $PAGE->get_renderer('core', 'files');
2066 return $renderer->repository_default_searchform();
2070 * For oauth like external authentication, when external repository direct user back to moodle,
2071 * this funciton will be called to set up token and token_secret
2073 public function callback() {
2077 * is it possible to do glboal search?
2081 public function global_search() {
2086 * Defines operations that happen occasionally on cron
2090 public function cron() {
2095 * function which is run when the type is created (moodle administrator add the plugin)
2097 * @return bool success or fail?
2099 public static function plugin_init() {
2104 * Edit/Create Admin Settings Moodle form
2106 * @param moodleform $mform Moodle form (passed by reference)
2107 * @param string $classname repository class name
2109 public static function type_config_form($mform, $classname = 'repository') {
2110 $instnaceoptions = call_user_func(array($classname, 'get_instance_option_names'), $mform, $classname);
2111 if (empty($instnaceoptions)) {
2112 // this plugin has only one instance
2113 // so we need to give it a name
2114 // it can be empty, then moodle will look for instance name from language string
2115 $mform->addElement('text', 'pluginname', get_string('pluginname', 'repository'), array('size' => '40'));
2116 $mform->addElement('static', 'pluginnamehelp', '', get_string('pluginnamehelp', 'repository'));
2117 $mform->setType('pluginname', PARAM_TEXT
);
2122 * Validate Admin Settings Moodle form
2125 * @param moodleform $mform Moodle form (passed by reference)
2126 * @param array $data array of ("fieldname"=>value) of submitted data
2127 * @param array $errors array of ("fieldname"=>errormessage) of errors
2128 * @return array array of errors
2130 public static function type_form_validation($mform, $data, $errors) {
2136 * Edit/Create Instance Settings Moodle form
2138 * @param moodleform $mform Moodle form (passed by reference)
2140 public static function instance_config_form($mform) {
2144 * Return names of the general options.
2145 * By default: no general option name
2149 public static function get_type_option_names() {
2150 return array('pluginname');
2154 * Return names of the instance options.
2155 * By default: no instance option name
2159 public static function get_instance_option_names() {
2164 * Validate repository plugin instance form
2166 * @param moodleform $mform moodle form
2167 * @param array $data form data
2168 * @param array $errors errors
2169 * @return array errors
2171 public static function instance_form_validation($mform, $data, $errors) {
2176 * Create a shorten filename
2178 * @param string $str filename
2179 * @param int $maxlength max file name length
2180 * @return string short filename
2182 public function get_short_filename($str, $maxlength) {
2183 if (textlib
::strlen($str) >= $maxlength) {
2184 return trim(textlib
::substr($str, 0, $maxlength)).'...';
2191 * Overwrite an existing file
2193 * @param int $itemid
2194 * @param string $filepath
2195 * @param string $filename
2196 * @param string $newfilepath
2197 * @param string $newfilename
2200 public static function overwrite_existing_draftfile($itemid, $filepath, $filename, $newfilepath, $newfilename) {
2202 $fs = get_file_storage();
2203 $user_context = get_context_instance(CONTEXT_USER
, $USER->id
);
2204 if ($file = $fs->get_file($user_context->id
, 'user', 'draft', $itemid, $filepath, $filename)) {
2205 if ($tempfile = $fs->get_file($user_context->id
, 'user', 'draft', $itemid, $newfilepath, $newfilename)) {
2206 // delete existing file to release filename
2209 $newfile = $fs->create_file_from_storedfile(array('filepath'=>$filepath, 'filename'=>$filename), $tempfile);
2211 $tempfile->delete();
2219 * Delete a temp file from draft area
2221 * @param int $draftitemid
2222 * @param string $filepath
2223 * @param string $filename
2226 public static function delete_tempfile_from_draft($draftitemid, $filepath, $filename) {
2228 $fs = get_file_storage();
2229 $user_context = get_context_instance(CONTEXT_USER
, $USER->id
);
2230 if ($file = $fs->get_file($user_context->id
, 'user', 'draft', $draftitemid, $filepath, $filename)) {
2239 * Find all external files in this repo and import them
2241 public function convert_references_to_local() {
2242 $fs = get_file_storage();
2243 $files = $fs->get_external_files($this->id
);
2244 foreach ($files as $storedfile) {
2245 $fs->import_external_file($storedfile);
2250 * Called from phpunit between tests, resets whatever was cached
2252 public static function reset_caches() {
2253 self
::sync_external_file(null, true);
2257 * Call to request proxy file sync with repository source.
2259 * @param stored_file $file
2260 * @param bool $resetsynchistory whether to reset all history of sync (used by phpunit)
2261 * @return bool success
2263 public static function sync_external_file($file, $resetsynchistory = false) {
2265 // TODO MDL-25290 static should be replaced with MUC code.
2266 static $synchronized = array();
2267 if ($resetsynchistory) {
2268 $synchronized = array();
2271 $fs = get_file_storage();
2273 if (!$file ||
!$file->get_referencefileid()) {
2276 if (array_key_exists($file->get_id(), $synchronized)) {
2277 return $synchronized[$file->get_id()];
2280 // remember that we already cached in current request to prevent from querying again
2281 $synchronized[$file->get_id()] = false;
2283 if (!$reference = $DB->get_record('files_reference', array('id'=>$file->get_referencefileid()))) {
2287 if (!empty($reference->lastsync
) and ($reference->lastsync +
$reference->lifetime
> time())) {
2288 $synchronized[$file->get_id()] = true;
2292 if (!$repository = self
::get_repository_by_id($reference->repositoryid
, SYSCONTEXTID
)) {
2296 if (!$repository->sync_individual_file($file)) {
2300 $fileinfo = $repository->get_file_by_reference($reference);
2301 if ($fileinfo === null) {
2302 // does not exist any more - set status to missing
2303 $file->set_missingsource();
2304 //TODO: purge content from pool if we set some other content hash and it is no used any more
2305 $synchronized[$file->get_id()] = true;
2309 $contenthash = null;
2311 if (!empty($fileinfo->contenthash
)) {
2312 // contenthash returned, file already in moodle
2313 $contenthash = $fileinfo->contenthash
;
2314 $filesize = $fileinfo->filesize
;
2315 } else if (!empty($fileinfo->filepath
)) {
2316 // File path returned
2317 list($contenthash, $filesize, $newfile) = $fs->add_file_to_pool($fileinfo->filepath
);
2318 } else if (!empty($fileinfo->handle
) && is_resource($fileinfo->handle
)) {
2319 // File handle returned
2321 while (!feof($fileinfo->handle
)) {
2322 $contents .= fread($handle, 8192);
2324 fclose($fileinfo->handle
);
2325 list($contenthash, $filesize, $newfile) = $fs->add_string_to_pool($content);
2326 } else if (isset($fileinfo->content
)) {
2327 // File content returned
2328 list($contenthash, $filesize, $newfile) = $fs->add_string_to_pool($fileinfo->content
);
2331 if (!isset($contenthash) or !isset($filesize)) {
2335 // update files table
2336 $file->set_synchronized($contenthash, $filesize);
2337 $synchronized[$file->get_id()] = true;
2342 * Build draft file's source field
2344 * {@link file_restore_source_field_from_draft_file()}
2345 * XXX: This is a hack for file manager (MDL-28666)
2346 * For newly created draft files we have to construct
2347 * source filed in php serialized data format.
2348 * File manager needs to know the original file information before copying
2349 * to draft area, so we append these information in mdl_files.source field
2351 * @param string $source
2352 * @return string serialised source field
2354 public static function build_source_field($source) {
2355 $sourcefield = new stdClass
;
2356 $sourcefield->source
= $source;
2357 return serialize($sourcefield);
2362 * Exception class for repository api
2365 * @package repository
2366 * @category repository
2367 * @copyright 2009 Dongsheng Cai {@link http://dongsheng.org}
2368 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2370 class repository_exception
extends moodle_exception
{
2374 * This is a class used to define a repository instance form
2377 * @package repository
2378 * @category repository
2379 * @copyright 2009 Dongsheng Cai {@link http://dongsheng.org}
2380 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2382 final class repository_instance_form
extends moodleform
{
2383 /** @var stdClass repository instance */
2384 protected $instance;
2385 /** @var string repository plugin type */
2389 * Added defaults to moodle form
2391 protected function add_defaults() {
2392 $mform =& $this->_form
;
2393 $strrequired = get_string('required');
2395 $mform->addElement('hidden', 'edit', ($this->instance
) ?
$this->instance
->id
: 0);
2396 $mform->setType('edit', PARAM_INT
);
2397 $mform->addElement('hidden', 'new', $this->plugin
);
2398 $mform->setType('new', PARAM_FORMAT
);
2399 $mform->addElement('hidden', 'plugin', $this->plugin
);
2400 $mform->setType('plugin', PARAM_PLUGIN
);
2401 $mform->addElement('hidden', 'typeid', $this->typeid
);
2402 $mform->setType('typeid', PARAM_INT
);
2403 $mform->addElement('hidden', 'contextid', $this->contextid
);
2404 $mform->setType('contextid', PARAM_INT
);
2406 $mform->addElement('text', 'name', get_string('name'), 'maxlength="100" size="30"');
2407 $mform->addRule('name', $strrequired, 'required', null, 'client');
2408 $mform->setType('name', PARAM_TEXT
);
2412 * Define moodle form elements
2414 public function definition() {
2416 // type of plugin, string
2417 $this->plugin
= $this->_customdata
['plugin'];
2418 $this->typeid
= $this->_customdata
['typeid'];
2419 $this->contextid
= $this->_customdata
['contextid'];
2420 $this->instance
= (isset($this->_customdata
['instance'])
2421 && is_subclass_of($this->_customdata
['instance'], 'repository'))
2422 ?
$this->_customdata
['instance'] : null;
2424 $mform =& $this->_form
;
2426 $this->add_defaults();
2428 // Add instance config options.
2429 $result = repository
::static_function($this->plugin
, 'instance_config_form', $mform);
2430 if ($result === false) {
2431 // Remove the name element if no other config options.
2432 $mform->removeElement('name');
2434 if ($this->instance
) {
2436 $data['name'] = $this->instance
->name
;
2437 if (!$this->instance
->readonly
) {
2438 // and set the data if we have some.
2439 foreach ($this->instance
->get_instance_option_names() as $config) {
2440 if (!empty($this->instance
->options
[$config])) {
2441 $data[$config] = $this->instance
->options
[$config];
2443 $data[$config] = '';
2447 $this->set_data($data);
2450 if ($result === false) {
2451 $mform->addElement('cancel');
2453 $this->add_action_buttons(true, get_string('save','repository'));
2458 * Validate moodle form data
2460 * @param array $data form data
2461 * @param array $files files in form
2462 * @return array errors
2464 public function validation($data, $files) {
2467 $plugin = $this->_customdata
['plugin'];
2468 $instance = (isset($this->_customdata
['instance'])
2469 && is_subclass_of($this->_customdata
['instance'], 'repository'))
2470 ?
$this->_customdata
['instance'] : null;
2472 $errors = repository
::static_function($plugin, 'instance_form_validation', $this, $data, $errors);
2474 $errors = $instance->instance_form_validation($this, $data, $errors);
2477 $sql = "SELECT count('x')
2478 FROM {repository_instances} i, {repository} r
2479 WHERE r.type=:plugin AND r.id=i.typeid AND i.name=:name";
2480 if ($DB->count_records_sql($sql, array('name' => $data['name'], 'plugin' => $data['plugin'])) > 1) {
2481 $errors['name'] = get_string('erroruniquename', 'repository');
2489 * This is a class used to define a repository type setting form
2492 * @package repository
2493 * @category repository
2494 * @copyright 2009 Dongsheng Cai {@link http://dongsheng.org}
2495 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2497 final class repository_type_form
extends moodleform
{
2498 /** @var stdClass repository instance */
2499 protected $instance;
2500 /** @var string repository plugin name */
2502 /** @var string action */
2506 * Definition of the moodleform
2508 public function definition() {
2510 // type of plugin, string
2511 $this->plugin
= $this->_customdata
['plugin'];
2512 $this->instance
= (isset($this->_customdata
['instance'])
2513 && is_a($this->_customdata
['instance'], 'repository_type'))
2514 ?
$this->_customdata
['instance'] : null;
2516 $this->action
= $this->_customdata
['action'];
2517 $this->pluginname
= $this->_customdata
['pluginname'];
2518 $mform =& $this->_form
;
2519 $strrequired = get_string('required');
2521 $mform->addElement('hidden', 'action', $this->action
);
2522 $mform->setType('action', PARAM_TEXT
);
2523 $mform->addElement('hidden', 'repos', $this->plugin
);
2524 $mform->setType('repos', PARAM_PLUGIN
);
2526 // let the plugin add its specific fields
2527 $classname = 'repository_' . $this->plugin
;
2528 require_once($CFG->dirroot
. '/repository/' . $this->plugin
. '/lib.php');
2529 //add "enable course/user instances" checkboxes if multiple instances are allowed
2530 $instanceoptionnames = repository
::static_function($this->plugin
, 'get_instance_option_names');
2532 $result = call_user_func(array($classname, 'type_config_form'), $mform, $classname);
2534 if (!empty($instanceoptionnames)) {
2535 $sm = get_string_manager();
2536 $component = 'repository';
2537 if ($sm->string_exists('enablecourseinstances', 'repository_' . $this->plugin
)) {
2538 $component .= ('_' . $this->plugin
);
2540 $mform->addElement('checkbox', 'enablecourseinstances', get_string('enablecourseinstances', $component));
2542 $component = 'repository';
2543 if ($sm->string_exists('enableuserinstances', 'repository_' . $this->plugin
)) {
2544 $component .= ('_' . $this->plugin
);
2546 $mform->addElement('checkbox', 'enableuserinstances', get_string('enableuserinstances', $component));
2549 // set the data if we have some.
2550 if ($this->instance
) {
2552 $option_names = call_user_func(array($classname,'get_type_option_names'));
2553 if (!empty($instanceoptionnames)){
2554 $option_names[] = 'enablecourseinstances';
2555 $option_names[] = 'enableuserinstances';
2558 $instanceoptions = $this->instance
->get_options();
2559 foreach ($option_names as $config) {
2560 if (!empty($instanceoptions[$config])) {
2561 $data[$config] = $instanceoptions[$config];
2563 $data[$config] = '';
2566 // XXX: set plugin name for plugins which doesn't have muliti instances
2567 if (empty($instanceoptionnames)){
2568 $data['pluginname'] = $this->pluginname
;
2570 $this->set_data($data);
2573 $this->add_action_buttons(true, get_string('save','repository'));
2577 * Validate moodle form data
2579 * @param array $data moodle form data
2580 * @param array $files
2581 * @return array errors
2583 public function validation($data, $files) {
2585 $plugin = $this->_customdata
['plugin'];
2586 $instance = (isset($this->_customdata
['instance'])
2587 && is_subclass_of($this->_customdata
['instance'], 'repository'))
2588 ?
$this->_customdata
['instance'] : null;
2590 $errors = repository
::static_function($plugin, 'type_form_validation', $this, $data, $errors);
2592 $errors = $instance->type_form_validation($this, $data, $errors);
2600 * Generate all options needed by filepicker
2602 * @param array $args including following keys
2607 * @return array the list of repository instances, including meta infomation, containing the following keys
2612 function initialise_filepicker($args) {
2613 global $CFG, $USER, $PAGE, $OUTPUT;
2614 static $templatesinitialized;
2615 require_once($CFG->libdir
. '/licenselib.php');
2617 $return = new stdClass();
2618 $licenses = array();
2619 if (!empty($CFG->licenses
)) {
2620 $array = explode(',', $CFG->licenses
);
2621 foreach ($array as $license) {
2622 $l = new stdClass();
2623 $l->shortname
= $license;
2624 $l->fullname
= get_string($license, 'license');
2628 if (!empty($CFG->sitedefaultlicense
)) {
2629 $return->defaultlicense
= $CFG->sitedefaultlicense
;
2632 $return->licenses
= $licenses;
2634 $return->author
= fullname($USER);
2636 if (empty($args->context
)) {
2637 $context = $PAGE->context
;
2639 $context = $args->context
;
2641 $disable_types = array();
2642 if (!empty($args->disable_types
)) {
2643 $disable_types = $args->disable_types
;
2646 $user_context = get_context_instance(CONTEXT_USER
, $USER->id
);
2648 list($context, $course, $cm) = get_context_info_array($context->id
);
2649 $contexts = array($user_context, get_system_context());
2650 if (!empty($course)) {
2651 // adding course context
2652 $contexts[] = get_context_instance(CONTEXT_COURSE
, $course->id
);
2654 $externallink = (int)get_config(null, 'repositoryallowexternallinks');
2655 $repositories = repository
::get_instances(array(
2656 'context'=>$contexts,
2657 'currentcontext'=> $context,
2658 'accepted_types'=>$args->accepted_types
,
2659 'return_types'=>$args->return_types
,
2660 'disable_types'=>$disable_types
2663 $return->repositories
= array();
2665 if (empty($externallink)) {
2666 $return->externallink
= false;
2668 $return->externallink
= true;
2671 $return->userprefs
= array();
2672 $return->userprefs
['recentrepository'] = get_user_preferences('filepicker_recentrepository', '');
2673 $return->userprefs
['recentlicense'] = get_user_preferences('filepicker_recentlicense', '');
2674 $return->userprefs
['recentviewmode'] = get_user_preferences('filepicker_recentviewmode', '');
2676 user_preference_allow_ajax_update('filepicker_recentrepository', PARAM_INT
);
2677 user_preference_allow_ajax_update('filepicker_recentlicense', PARAM_SAFEDIR
);
2678 user_preference_allow_ajax_update('filepicker_recentviewmode', PARAM_INT
);
2681 // provided by form element
2682 $return->accepted_types
= file_get_typegroup('extension', $args->accepted_types
);
2683 $return->return_types
= $args->return_types
;
2684 foreach ($repositories as $repository) {
2685 $meta = $repository->get_meta();
2686 // Please note that the array keys for repositories are used within
2687 // JavaScript a lot, the key NEEDS to be the repository id.
2688 $return->repositories
[$repository->id
] = $meta;
2690 if (!$templatesinitialized) {
2691 // we need to send filepicker templates to the browser just once
2692 $fprenderer = $PAGE->get_renderer('core', 'files');
2693 $templates = $fprenderer->filepicker_js_templates();
2694 $PAGE->requires
->js_init_call('M.core_filepicker.set_templates', array($templates), true);
2695 $templatesinitialized = true;
2700 * Small function to walk an array to attach repository ID
2702 * @param array $value
2703 * @param string $key
2706 function repository_attach_id(&$value, $key, $id){
2707 $value['repo_id'] = $id;