on-demand release 2.3dev
[moodle.git] / repository / lib.php
CommitLineData
12c79bfd 1<?php
6f2cd52a
DC
2// This file is part of Moodle - http://moodle.org/
3//
4// Moodle is free software: you can redistribute it and/or modify
5// it under the terms of the GNU General Public License as published by
6// the Free Software Foundation, either version 3 of the License, or
7// (at your option) any later version.
8//
9// Moodle is distributed in the hope that it will be useful,
10// but WITHOUT ANY WARRANTY; without even the implied warranty of
11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12// GNU General Public License for more details.
13//
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/>.
16
aca64b79 17/**
6f2cd52a
DC
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
20 *
21 * @since 2.0
67233725
DC
22 * @package repository
23 * @copyright 2009 Dongsheng Cai {@link http://dongsheng.org}
24 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
aca64b79 25 */
26
19add4c0 27require_once(dirname(dirname(__FILE__)) . '/config.php');
c19f8e7d 28require_once($CFG->libdir . '/filelib.php');
29require_once($CFG->libdir . '/formslib.php');
41076c58 30
67233725
DC
31define('FILE_EXTERNAL', 1);
32define('FILE_INTERNAL', 2);
33define('FILE_REFERENCE', 4);
f392caba 34define('RENAME_SUFFIX', '_2');
41076c58 35
a6600395 36/**
6f2cd52a
DC
37 * This class is used to manage repository plugins
38 *
a6600395 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.
a6600395 43 * Coding note:
44 * - a repository_type object is mapped to the "repository" database table
45 * - "typename" attibut maps the "type" database field. It is unique.
46 * - general "options" for a repository type are saved in the config_plugin table
eb239694 47 * - when you delete a repository, all instances are deleted, and general
48 * options are also deleted from database
a6600395 49 * - When you create a type for a plugin that can't have multiple instances, a
50 * instance is automatically created.
6f2cd52a 51 *
67233725 52 * @package repository
6f2cd52a
DC
53 * @copyright 2009 Jerome Mouneyrac
54 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
a6600395 55 */
56class repository_type {
57
58
59 /**
60 * Type name (no whitespace) - A type name is unique
61 * Note: for a user-friendly type name see get_readablename()
62 * @var String
63 */
64 private $_typename;
65
66
67 /**
68 * Options of this type
69 * They are general options that any instance of this type would share
70 * e.g. API key
71 * These options are saved in config_plugin table
72 * @var array
73 */
7a3b93c1 74 private $_options;
a6600395 75
76
77 /**
78 * Is the repository type visible or hidden
79 * If false (hidden): no instances can be created, edited, deleted, showned , used...
80 * @var boolean
81 */
7a3b93c1 82 private $_visible;
a6600395 83
84
85 /**
86 * 0 => not ordered, 1 => first position, 2 => second position...
87 * A not order type would appear in first position (should never happened)
88 * @var integer
89 */
90 private $_sortorder;
91
67233725 92 /**
f48fb4d6 93 * Return if the instance is visible in a context
67233725
DC
94 *
95 * @todo check if the context visibility has been overwritten by the plugin creator
f48fb4d6 96 * (need to create special functions to be overvwritten in repository class)
67233725
DC
97 * @param stdClass $context context
98 * @return bool
f48fb4d6 99 */
5363905a
DC
100 public function get_contextvisibility($context) {
101 global $USER;
dbc01944 102
5363905a 103 if ($context->contextlevel == CONTEXT_COURSE) {
f48fb4d6 104 return $this->_options['enablecourseinstances'];
105 }
106
5363905a 107 if ($context->contextlevel == CONTEXT_USER) {
f48fb4d6 108 return $this->_options['enableuserinstances'];
109 }
110
111 //the context is SITE
112 return true;
113 }
dbc01944 114
f48fb4d6 115
116
a6600395 117 /**
118 * repository_type constructor
67233725
DC
119 *
120 * @param int $typename
a6600395 121 * @param array $typeoptions
67233725
DC
122 * @param bool $visible
123 * @param int $sortorder (don't really need set, it will be during create() call)
a6600395 124 */
a642bf6f 125 public function __construct($typename = '', $typeoptions = array(), $visible = true, $sortorder = 0) {
a6600395 126 global $CFG;
127
128 //set type attributs
129 $this->_typename = $typename;
130 $this->_visible = $visible;
131 $this->_sortorder = $sortorder;
46dd6bb0 132
a6600395 133 //set options attribut
134 $this->_options = array();
a5adfa26 135 $options = repository::static_function($typename, 'get_type_option_names');
a6600395 136 //check that the type can be setup
06e65e1e 137 if (!empty($options)) {
a6600395 138 //set the type options
139 foreach ($options as $config) {
a5adfa26 140 if (array_key_exists($config, $typeoptions)) {
7a3b93c1 141 $this->_options[$config] = $typeoptions[$config];
a6600395 142 }
143 }
144 }
f48fb4d6 145
146 //retrieve visibility from option
147 if (array_key_exists('enablecourseinstances',$typeoptions)) {
148 $this->_options['enablecourseinstances'] = $typeoptions['enablecourseinstances'];
9f7c761a 149 } else {
150 $this->_options['enablecourseinstances'] = 0;
f48fb4d6 151 }
dbc01944 152
f48fb4d6 153 if (array_key_exists('enableuserinstances',$typeoptions)) {
154 $this->_options['enableuserinstances'] = $typeoptions['enableuserinstances'];
9f7c761a 155 } else {
156 $this->_options['enableuserinstances'] = 0;
f48fb4d6 157 }
dbc01944 158
a6600395 159 }
160
161 /**
162 * Get the type name (no whitespace)
163 * For a human readable name, use get_readablename()
67233725
DC
164 *
165 * @return string the type name
a6600395 166 */
7a3b93c1 167 public function get_typename() {
a6600395 168 return $this->_typename;
169 }
170
171 /**
172 * Return a human readable and user-friendly type name
67233725 173 *
a6600395 174 * @return string user-friendly type name
175 */
7a3b93c1 176 public function get_readablename() {
614d18d2 177 return get_string('pluginname','repository_'.$this->_typename);
a6600395 178 }
179
180 /**
181 * Return general options
67233725 182 *
a6600395 183 * @return array the general options
184 */
7a3b93c1 185 public function get_options() {
a6600395 186 return $this->_options;
187 }
188
189 /**
190 * Return visibility
67233725
DC
191 *
192 * @return bool
a6600395 193 */
7a3b93c1 194 public function get_visible() {
a6600395 195 return $this->_visible;
196 }
197
198 /**
199 * Return order / position of display in the file picker
67233725
DC
200 *
201 * @return int
a6600395 202 */
7a3b93c1 203 public function get_sortorder() {
a6600395 204 return $this->_sortorder;
205 }
206
207 /**
208 * Create a repository type (the type name must not already exist)
67233725 209 * @param bool $silent throw exception?
a75c78d3 210 * @return mixed return int if create successfully, return false if
a6600395 211 */
a75c78d3 212 public function create($silent = false) {
a6600395 213 global $DB;
214
215 //check that $type has been set
216 $timmedtype = trim($this->_typename);
217 if (empty($timmedtype)) {
7a3b93c1 218 throw new repository_exception('emptytype', 'repository');
a6600395 219 }
220
221 //set sortorder as the last position in the list
7a3b93c1 222 if (!isset($this->_sortorder) || $this->_sortorder == 0 ) {
a6600395 223 $sql = "SELECT MAX(sortorder) FROM {repository}";
224 $this->_sortorder = 1 + $DB->get_field_sql($sql);
225 }
226
227 //only create a new type if it doesn't already exist
228 $existingtype = $DB->get_record('repository', array('type'=>$this->_typename));
7a3b93c1 229 if (!$existingtype) {
230 //create the type
6bdfef5d 231 $newtype = new stdClass();
7a3b93c1 232 $newtype->type = $this->_typename;
233 $newtype->visible = $this->_visible;
234 $newtype->sortorder = $this->_sortorder;
a75c78d3 235 $plugin_id = $DB->insert_record('repository', $newtype);
7a3b93c1 236 //save the options in DB
237 $this->update_options();
238
a5adfa26
DC
239 $instanceoptionnames = repository::static_function($this->_typename, 'get_instance_option_names');
240
edb50637 241 //if the plugin type has no multiple instance (e.g. has no instance option name) so it wont
7a3b93c1 242 //be possible for the administrator to create a instance
243 //in this case we need to create an instance
edb50637 244 if (empty($instanceoptionnames)) {
7a3b93c1 245 $instanceoptions = array();
a5adfa26
DC
246 if (empty($this->_options['pluginname'])) {
247 // when moodle trying to install some repo plugin automatically
248 // this option will be empty, get it from language string when display
249 $instanceoptions['name'] = '';
250 } else {
251 // when admin trying to add a plugin manually, he will type a name
252 // for it
253 $instanceoptions['name'] = $this->_options['pluginname'];
254 }
dbc01944 255 repository::static_function($this->_typename, 'create', $this->_typename, 0, get_system_context(), $instanceoptions);
7a3b93c1 256 }
60c366e8 257 //run plugin_init function
258 if (!repository::static_function($this->_typename, 'plugin_init')) {
259 if (!$silent) {
260 throw new repository_exception('cannotinitplugin', 'repository');
261 }
262 }
263
a75c78d3 264 if(!empty($plugin_id)) {
265 // return plugin_id if create successfully
266 return $plugin_id;
267 } else {
268 return false;
269 }
948c2860 270
7a3b93c1 271 } else {
a75c78d3 272 if (!$silent) {
273 throw new repository_exception('existingrepository', 'repository');
274 }
275 // If plugin existed, return false, tell caller no new plugins were created.
276 return false;
a6600395 277 }
278 }
279
280
281 /**
282 * Update plugin options into the config_plugin table
67233725 283 *
a6600395 284 * @param array $options
67233725 285 * @return bool
a6600395 286 */
7a3b93c1 287 public function update_options($options = null) {
a5adfa26
DC
288 global $DB;
289 $classname = 'repository_' . $this->_typename;
290 $instanceoptions = repository::static_function($this->_typename, 'get_instance_option_names');
291 if (empty($instanceoptions)) {
292 // update repository instance name if this plugin type doesn't have muliti instances
293 $params = array();
294 $params['type'] = $this->_typename;
295 $instances = repository::get_instances($params);
296 $instance = array_pop($instances);
297 if ($instance) {
298 $DB->set_field('repository_instances', 'name', $options['pluginname'], array('id'=>$instance->id));
299 }
300 unset($options['pluginname']);
301 }
302
7a3b93c1 303 if (!empty($options)) {
a6600395 304 $this->_options = $options;
305 }
306
307 foreach ($this->_options as $name => $value) {
a5adfa26 308 set_config($name, $value, $this->_typename);
a6600395 309 }
310
311 return true;
312 }
313
314 /**
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()
67233725
DC
319 *
320 * @param bool $visible
321 * @return bool
a6600395 322 */
7a3b93c1 323 private function update_visible($visible = null) {
a6600395 324 global $DB;
325
7a3b93c1 326 if (!empty($visible)) {
a6600395 327 $this->_visible = $visible;
328 }
7a3b93c1 329 else if (!isset($this->_visible)) {
a6600395 330 throw new repository_exception('updateemptyvisible', 'repository');
331 }
332
333 return $DB->set_field('repository', 'visible', $this->_visible, array('type'=>$this->_typename));
334 }
335
336 /**
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()
67233725
DC
341 *
342 * @param int $sortorder
343 * @return bool
a6600395 344 */
7a3b93c1 345 private function update_sortorder($sortorder = null) {
a6600395 346 global $DB;
347
7a3b93c1 348 if (!empty($sortorder) && $sortorder!=0) {
a6600395 349 $this->_sortorder = $sortorder;
350 }
351 //if sortorder is not set, we set it as the ;ast position in the list
7a3b93c1 352 else if (!isset($this->_sortorder) || $this->_sortorder == 0 ) {
a6600395 353 $sql = "SELECT MAX(sortorder) FROM {repository}";
354 $this->_sortorder = 1 + $DB->get_field_sql($sql);
355 }
356
357 return $DB->set_field('repository', 'sortorder', $this->_sortorder, array('type'=>$this->_typename));
358 }
359
360 /**
361 * Change order of the type with its adjacent upper or downer type
362 * (database fields are updated)
363 * Algorithm details:
364 * 1. retrieve all types in an array. This array is sorted by sortorder,
365 * and the array keys start from 0 to X (incremented by 1)
366 * 2. switch sortorder values of this type and its adjacent type
67233725 367 *
a6600395 368 * @param string $move "up" or "down"
369 */
370 public function move_order($move) {
371 global $DB;
a6600395 372
dbc01944 373 $types = repository::get_types(); // retrieve all types
7a3b93c1 374
67233725 375 // retrieve this type into the returned array
7a3b93c1 376 $i = 0;
377 while (!isset($indice) && $i<count($types)) {
378 if ($types[$i]->get_typename() == $this->_typename) {
a6600395 379 $indice = $i;
380 }
381 $i++;
382 }
383
67233725 384 // retrieve adjacent indice
a6600395 385 switch ($move) {
386 case "up":
387 $adjacentindice = $indice - 1;
7a3b93c1 388 break;
a6600395 389 case "down":
390 $adjacentindice = $indice + 1;
7a3b93c1 391 break;
a6600395 392 default:
7a3b93c1 393 throw new repository_exception('movenotdefined', 'repository');
a6600395 394 }
395
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.
7a3b93c1 400 if ($adjacentindice>=0 && !empty($types[$adjacentindice])) {
a6600395 401 $DB->set_field('repository', 'sortorder', $this->_sortorder, array('type'=>$types[$adjacentindice]->get_typename()));
402 $this->update_sortorder($types[$adjacentindice]->get_sortorder());
403 }
404 }
405
406 /**
79698344 407 * 1. Change visibility to the value chosen
a6600395 408 * 2. Update the type
67233725
DC
409 *
410 * @param bool $visible
411 * @return bool
a6600395 412 */
79698344
MD
413 public function update_visibility($visible = null) {
414 if (is_bool($visible)) {
415 $this->_visible = $visible;
416 } else {
417 $this->_visible = !$this->_visible;
418 }
a6600395 419 return $this->update_visible();
420 }
421
422
423 /**
eb239694 424 * Delete a repository_type (general options are removed from config_plugin
425 * table, and all instances are deleted)
67233725
DC
426 *
427 * @param bool $downloadcontents download external contents if exist
428 * @return bool
a6600395 429 */
67233725 430 public function delete($downloadcontents = false) {
a6600395 431 global $DB;
46dd6bb0 432
433 //delete all instances of this type
6f2cd52a
DC
434 $params = array();
435 $params['context'] = array();
436 $params['onlyvisible'] = false;
437 $params['type'] = $this->_typename;
438 $instances = repository::get_instances($params);
7a3b93c1 439 foreach ($instances as $instance) {
67233725 440 $instance->delete($downloadcontents);
46dd6bb0 441 }
442
eb239694 443 //delete all general options
7a3b93c1 444 foreach ($this->_options as $name => $value) {
eb239694 445 set_config($name, null, $this->_typename);
446 }
447
67233725
DC
448 try {
449 $DB->delete_records('repository', array('type' => $this->_typename));
450 } catch (dml_exception $ex) {
451 return false;
452 }
453 return true;
a6600395 454 }
455}
456
a6600395 457/**
67233725 458 * This is the base class of the repository class.
8d419e59 459 *
67233725
DC
460 * To create repository plugin, see: {@link http://docs.moodle.org/dev/Repository_plugins}
461 * See an example: {@link repository_boxnet}
8d419e59 462 *
67233725
DC
463 * @package repository
464 * @category repository
465 * @copyright 2009 Dongsheng Cai {@link http://dongsheng.org}
6f2cd52a 466 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
a6600395 467 */
fca079c5 468abstract class repository {
efe018b4 469 // $disabled can be set to true to disable a plugin by force
470 // example: self::$disabled = true
67233725 471 /** @var bool force disable repository instance */
efe018b4 472 public $disabled = false;
67233725 473 /** @var int repository instance id */
4a65c39a 474 public $id;
67233725 475 /** @var stdClass current context */
4a65c39a 476 public $context;
67233725 477 /** @var array repository options */
4a65c39a 478 public $options;
67233725 479 /** @var bool Whether or not the repository instance is editable */
948c2860 480 public $readonly;
67233725 481 /** @var int return types */
41076c58 482 public $returntypes;
67233725 483 /** @var stdClass repository instance database record */
a5adfa26 484 public $instance;
a0ff4137 485 /**
67233725 486 * Constructor
a0ff4137 487 *
67233725
DC
488 * @param int $repositoryid repository instance id
489 * @param int|stdClass $context a context id or context object
e35194be 490 * @param array $options repository options
67233725 491 * @param int $readonly indicate this repo is readonly or not
a0ff4137 492 */
e35194be 493 public function __construct($repositoryid, $context = SYSCONTEXTID, $options = array(), $readonly = 0) {
a5adfa26 494 global $DB;
a0ff4137 495 $this->id = $repositoryid;
be85f7ab 496 if (is_object($context)) {
e35194be
DC
497 $this->context = $context;
498 } else {
499 $this->context = get_context_instance_by_id($context);
500 }
a5adfa26 501 $this->instance = $DB->get_record('repository_instances', array('id'=>$this->id));
a0ff4137
DC
502 $this->readonly = $readonly;
503 $this->options = array();
e35194be 504
a0ff4137 505 if (is_array($options)) {
67233725 506 // The get_option() method will get stored options in database.
a0ff4137
DC
507 $options = array_merge($this->get_option(), $options);
508 } else {
509 $options = $this->get_option();
510 }
511 foreach ($options as $n => $v) {
512 $this->options[$n] = $v;
513 }
514 $this->name = $this->get_name();
515 $this->returntypes = $this->supported_returntypes();
516 $this->super_called = true;
517 }
1cf56396 518
67233725
DC
519 /**
520 * Get repository instance using repository id
521 *
522 * @param int $repositoryid repository ID
523 * @param stdClass|int $context context instance or context ID
524 * @return repository
525 */
526 public static function get_repository_by_id($repositoryid, $context) {
527 global $CFG, $DB;
528
529 $sql = 'SELECT i.name, i.typeid, r.type FROM {repository} r, {repository_instances} i WHERE i.id=? AND i.typeid=r.id';
530
531 if (!$record = $DB->get_record_sql($sql, array($repositoryid))) {
532 throw new repository_exception('invalidrepositoryid', 'repository');
533 } else {
534 $type = $record->type;
535 if (file_exists($CFG->dirroot . "/repository/$type/lib.php")) {
536 require_once($CFG->dirroot . "/repository/$type/lib.php");
537 $classname = 'repository_' . $type;
538 $contextid = $context;
539 if (is_object($context)) {
540 $contextid = $context->id;
541 }
542 $repository = new $classname($repositoryid, $contextid, array('type'=>$type));
543 return $repository;
544 } else {
545 throw new moodle_exception('error');
546 }
547 }
548 }
549
dbc01944 550 /**
e35194be 551 * Get a repository type object by a given type name.
67233725
DC
552 *
553 * @static
e35194be
DC
554 * @param string $typename the repository type name
555 * @return repository_type|bool
dbc01944 556 */
557 public static function get_type_by_typename($typename) {
558 global $DB;
559
560 if (!$record = $DB->get_record('repository',array('type' => $typename))) {
561 return false;
562 }
563
564 return new repository_type($typename, (array)get_config($typename), $record->visible, $record->sortorder);
565 }
566
567 /**
e35194be 568 * Get the repository type by a given repository type id.
67233725
DC
569 *
570 * @static
8e0946bf
DC
571 * @param int $id the type id
572 * @return object
dbc01944 573 */
574 public static function get_type_by_id($id) {
575 global $DB;
576
577 if (!$record = $DB->get_record('repository',array('id' => $id))) {
578 return false;
579 }
580
581 return new repository_type($record->type, (array)get_config($record->type), $record->visible, $record->sortorder);
582 }
583
584 /**
e35194be
DC
585 * Return all repository types ordered by sortorder field
586 * first repository type in returnedarray[0], second repository type in returnedarray[1], ...
67233725
DC
587 *
588 * @static
589 * @param bool $visible can return types by visiblity, return all types if null
dbc01944 590 * @return array Repository types
591 */
592 public static function get_types($visible=null) {
489d8a75 593 global $DB, $CFG;
dbc01944 594
595 $types = array();
596 $params = null;
597 if (!empty($visible)) {
598 $params = array('visible' => $visible);
599 }
600 if ($records = $DB->get_records('repository',$params,'sortorder')) {
601 foreach($records as $type) {
e35194be 602 if (file_exists($CFG->dirroot . '/repository/'. $type->type .'/lib.php')) {
489d8a75
DC
603 $types[] = new repository_type($type->type, (array)get_config($type->type), $type->visible, $type->sortorder);
604 }
dbc01944 605 }
606 }
607
608 return $types;
609 }
610
611 /**
e35194be 612 * To check if the context id is valid
67233725
DC
613 *
614 * @static
e35194be 615 * @param int $contextid
67233725
DC
616 * @param stdClass $instance
617 * @return bool
dbc01944 618 */
be85f7ab 619 public static function check_capability($contextid, $instance) {
e35194be 620 $context = get_context_instance_by_id($contextid);
be85f7ab
DC
621 $capability = has_capability('repository/'.$instance->type.':view', $context);
622 if (!$capability) {
623 throw new repository_exception('nopermissiontoaccess', 'repository');
dbc01944 624 }
dbc01944 625 }
626
f392caba
DC
627 /**
628 * Check if file already exists in draft area
629 *
67233725 630 * @static
f392caba
DC
631 * @param int $itemid
632 * @param string $filepath
633 * @param string $filename
67233725 634 * @return bool
f392caba
DC
635 */
636 public static function draftfile_exists($itemid, $filepath, $filename) {
637 global $USER;
638 $fs = get_file_storage();
639 $usercontext = get_context_instance(CONTEXT_USER, $USER->id);
640 if ($fs->get_file($usercontext->id, 'user', 'draft', $itemid, $filepath, $filename)) {
641 return true;
642 } else {
643 return false;
644 }
645 }
646
f392caba
DC
647 /**
648 * This function is used to copy a moodle file to draft area
649 *
f392caba 650 * @param string $encoded The metainfo of file, it is base64 encoded php serialized data
2dfa16ef
MG
651 * @param stdClass|array $filerecord contains itemid, filepath, filename and optionally other
652 * attributes of the new file
653 * @param int $maxbytes maximum allowed size of file, -1 if unlimited. If size of file exceeds
654 * the limit, the file_exception is thrown.
f392caba
DC
655 * @return array The information of file
656 */
2dfa16ef
MG
657 public function copy_to_area($encoded, $filerecord, $maxbytes = -1) {
658 global $USER;
67233725
DC
659 $fs = get_file_storage();
660 $browser = get_file_browser();
f392caba
DC
661
662 if ($this->has_moodle_files() == false) {
67233725 663 throw new coding_exception('Only repository used to browse moodle files can use repository::copy_to_area()');
f392caba
DC
664 }
665
f392caba 666 $params = unserialize(base64_decode($encoded));
2dfa16ef
MG
667 $user_context = context_user::instance($USER->id);
668
669 $filerecord = (array)$filerecord;
670 // make sure the new file will be created in user draft area
671 $filerecord['component'] = 'user';
672 $filerecord['filearea'] = 'draft';
673 $filerecord['contextid'] = $user_context->id;
674 $draftitemid = $filerecord['itemid'];
675 $new_filepath = $filerecord['filepath'];
676 $new_filename = $filerecord['filename'];
f392caba
DC
677
678 $contextid = clean_param($params['contextid'], PARAM_INT);
679 $fileitemid = clean_param($params['itemid'], PARAM_INT);
680 $filename = clean_param($params['filename'], PARAM_FILE);
681 $filepath = clean_param($params['filepath'], PARAM_PATH);;
aff24313
PS
682 $filearea = clean_param($params['filearea'], PARAM_AREA);
683 $component = clean_param($params['component'], PARAM_COMPONENT);
f392caba
DC
684
685 $context = get_context_instance_by_id($contextid);
686 // the file needs to copied to draft area
687 $file_info = $browser->get_file_info($context, $component, $filearea, $fileitemid, $filepath, $filename);
2dfa16ef
MG
688 if ($maxbytes !== -1 && $file_info->get_filesize() > $maxbytes) {
689 throw new file_exception('maxbytes');
690 }
f392caba
DC
691
692 if (repository::draftfile_exists($draftitemid, $new_filepath, $new_filename)) {
693 // create new file
694 $unused_filename = repository::get_unused_filename($draftitemid, $new_filepath, $new_filename);
2dfa16ef
MG
695 $filerecord['filename'] = $unused_filename;
696 $file_info->copy_to_storage($filerecord);
f392caba
DC
697 $event = array();
698 $event['event'] = 'fileexists';
699 $event['newfile'] = new stdClass;
700 $event['newfile']->filepath = $new_filepath;
701 $event['newfile']->filename = $unused_filename;
702 $event['newfile']->url = moodle_url::make_draftfile_url($draftitemid, $new_filepath, $unused_filename)->out();
703 $event['existingfile'] = new stdClass;
704 $event['existingfile']->filepath = $new_filepath;
705 $event['existingfile']->filename = $new_filename;
2dfa16ef 706 $event['existingfile']->url = moodle_url::make_draftfile_url($draftitemid, $new_filepath, $new_filename)->out();;
f392caba
DC
707 return $event;
708 } else {
2dfa16ef 709 $file_info->copy_to_storage($filerecord);
f392caba
DC
710 $info = array();
711 $info['itemid'] = $draftitemid;
2dfa16ef 712 $info['file'] = $new_filename;
f392caba
DC
713 $info['title'] = $new_filename;
714 $info['contextid'] = $user_context->id;
715 $info['url'] = moodle_url::make_draftfile_url($draftitemid, $new_filepath, $new_filename)->out();;
716 $info['filesize'] = $file_info->get_filesize();
717 return $info;
718 }
719 }
720
721 /**
722 * Get unused filename by appending suffix
723 *
67233725 724 * @static
f392caba
DC
725 * @param int $itemid
726 * @param string $filepath
727 * @param string $filename
728 * @return string
729 */
730 public static function get_unused_filename($itemid, $filepath, $filename) {
731 global $USER;
732 $fs = get_file_storage();
733 while (repository::draftfile_exists($itemid, $filepath, $filename)) {
734 $filename = repository::append_suffix($filename);
735 }
736 return $filename;
737 }
738
739 /**
740 * Append a suffix to filename
741 *
67233725 742 * @static
f392caba
DC
743 * @param string $filename
744 * @return string
745 */
061eeed5 746 public static function append_suffix($filename) {
f392caba
DC
747 $pathinfo = pathinfo($filename);
748 if (empty($pathinfo['extension'])) {
749 return $filename . RENAME_SUFFIX;
750 } else {
751 return $pathinfo['filename'] . RENAME_SUFFIX . '.' . $pathinfo['extension'];
752 }
753 }
754
dbc01944 755 /**
756 * Return all types that you a user can create/edit and which are also visible
757 * Note: Mostly used in order to know if at least one editable type can be set
67233725
DC
758 *
759 * @static
760 * @param stdClass $context the context for which we want the editable types
dbc01944 761 * @return array types
762 */
763 public static function get_editable_types($context = null) {
764
765 if (empty($context)) {
766 $context = get_system_context();
767 }
768
769 $types= repository::get_types(true);
770 $editabletypes = array();
771 foreach ($types as $type) {
772 $instanceoptionnames = repository::static_function($type->get_typename(), 'get_instance_option_names');
773 if (!empty($instanceoptionnames)) {
5363905a 774 if ($type->get_contextvisibility($context)) {
dbc01944 775 $editabletypes[]=$type;
776 }
777 }
778 }
779 return $editabletypes;
780 }
781
782 /**
783 * Return repository instances
92a89068 784 *
67233725 785 * @static
92a89068
PL
786 * @param array $args Array containing the following keys:
787 * currentcontext
788 * context
789 * onlyvisible
790 * type
791 * accepted_types
8e0946bf 792 * return_types
92a89068
PL
793 * userid
794 *
dbc01944 795 * @return array repository instances
796 */
6f2cd52a 797 public static function get_instances($args = array()) {
dbc01944 798 global $DB, $CFG, $USER;
799
6f2cd52a
DC
800 if (isset($args['currentcontext'])) {
801 $current_context = $args['currentcontext'];
802 } else {
803 $current_context = null;
804 }
805
806 if (!empty($args['context'])) {
807 $contexts = $args['context'];
808 } else {
809 $contexts = array();
810 }
811
812 $onlyvisible = isset($args['onlyvisible']) ? $args['onlyvisible'] : true;
e35194be 813 $returntypes = isset($args['return_types']) ? $args['return_types'] : 3;
6f2cd52a 814 $type = isset($args['type']) ? $args['type'] : null;
6f2cd52a 815
dbc01944 816 $params = array();
a090554a
PS
817 $sql = "SELECT i.*, r.type AS repositorytype, r.sortorder, r.visible
818 FROM {repository} r, {repository_instances} i
819 WHERE i.typeid = r.id ";
dbc01944 820
227dfa43 821 if (!empty($args['disable_types']) && is_array($args['disable_types'])) {
cf717dc2 822 list($types, $p) = $DB->get_in_or_equal($args['disable_types'], SQL_PARAMS_QM, 'param', false);
a090554a 823 $sql .= " AND r.type $types";
227dfa43
DC
824 $params = array_merge($params, $p);
825 }
826
6f2cd52a 827 if (!empty($args['userid']) && is_numeric($args['userid'])) {
a090554a 828 $sql .= " AND (i.userid = 0 or i.userid = ?)";
6f2cd52a 829 $params[] = $args['userid'];
dbc01944 830 }
227dfa43 831
dbc01944 832 foreach ($contexts as $context) {
833 if (empty($firstcontext)) {
834 $firstcontext = true;
a090554a 835 $sql .= " AND ((i.contextid = ?)";
dbc01944 836 } else {
a090554a 837 $sql .= " OR (i.contextid = ?)";
dbc01944 838 }
839 $params[] = $context->id;
840 }
841
842 if (!empty($firstcontext)) {
843 $sql .=')';
844 }
845
846 if ($onlyvisible == true) {
a090554a 847 $sql .= " AND (r.visible = 1)";
dbc01944 848 }
849
850 if (isset($type)) {
a090554a 851 $sql .= " AND (r.type = ?)";
dbc01944 852 $params[] = $type;
853 }
a090554a 854 $sql .= " ORDER BY r.sortorder, i.name";
50a5cf09 855
6f2cd52a
DC
856 if (!$records = $DB->get_records_sql($sql, $params)) {
857 $records = array();
dbc01944 858 }
859
6f2cd52a 860 $repositories = array();
1e0b0415
DC
861 if (isset($args['accepted_types'])) {
862 $accepted_types = $args['accepted_types'];
863 } else {
864 $accepted_types = '*';
865 }
fdb0322d
DS
866 // Sortorder should be unique, which is not true if we use $record->sortorder
867 // and there are multiple instances of any repository type
868 $sortorder = 1;
6f2cd52a 869 foreach ($records as $record) {
e35194be 870 if (!file_exists($CFG->dirroot . '/repository/'. $record->repositorytype.'/lib.php')) {
062d21cd
DC
871 continue;
872 }
e35194be 873 require_once($CFG->dirroot . '/repository/'. $record->repositorytype.'/lib.php');
6f2cd52a 874 $options['visible'] = $record->visible;
6f2cd52a
DC
875 $options['type'] = $record->repositorytype;
876 $options['typeid'] = $record->typeid;
fdb0322d 877 $options['sortorder'] = $sortorder++;
c167aa26 878 // tell instance what file types will be accepted by file picker
6f2cd52a
DC
879 $classname = 'repository_' . $record->repositorytype;
880
881 $repository = new $classname($record->id, $record->contextid, $options, $record->readonly);
882
014c1ca0 883 $is_supported = true;
dbc01944 884
271bd2e0 885 if (empty($repository->super_called)) {
6f2cd52a
DC
886 // to make sure the super construct is called
887 debugging('parent::__construct must be called by '.$record->repositorytype.' plugin.');
271bd2e0 888 } else {
6f2cd52a 889 // check mimetypes
99eaca9d 890 if ($accepted_types !== '*' and $repository->supported_filetypes() !== '*') {
559276b1
MG
891 $accepted_ext = file_get_typegroup('extension', $accepted_types);
892 $supported_ext = file_get_typegroup('extension', $repository->supported_filetypes());
893 $valid_ext = array_intersect($accepted_ext, $supported_ext);
894 $is_supported = !empty($valid_ext);
014c1ca0 895 }
6f2cd52a 896 // check return values
41076c58
DC
897 if ($returntypes !== 3 and $repository->supported_returntypes() !== 3) {
898 $type = $repository->supported_returntypes();
899 if ($type & $returntypes) {
900 //
901 } else {
902 $is_supported = false;
271bd2e0 903 }
014c1ca0 904 }
d3959c26 905
271bd2e0 906 if (!$onlyvisible || ($repository->is_visible() && !$repository->disabled)) {
6f2cd52a
DC
907 // check capability in current context
908 if (!empty($current_context)) {
909 $capability = has_capability('repository/'.$record->repositorytype.':view', $current_context);
910 } else {
6f2cd52a
DC
911 $capability = has_capability('repository/'.$record->repositorytype.':view', get_system_context());
912 }
d3959c26
DC
913 if ($record->repositorytype == 'coursefiles') {
914 // coursefiles plugin needs managefiles permission
1fbbf893
PS
915 if (!empty($current_context)) {
916 $capability = $capability && has_capability('moodle/course:managefiles', $current_context);
917 } else {
918 $capability = $capability && has_capability('moodle/course:managefiles', get_system_context());
919 }
d3959c26 920 }
c86dde2e 921 if ($is_supported && $capability) {
99eaca9d 922 $repositories[$repository->id] = $repository;
271bd2e0 923 }
014c1ca0 924 }
dbc01944 925 }
926 }
6f2cd52a 927 return $repositories;
dbc01944 928 }
929
930 /**
931 * Get single repository instance
67233725
DC
932 *
933 * @static
dbc01944 934 * @param integer $id repository id
935 * @return object repository instance
936 */
937 public static function get_instance($id) {
938 global $DB, $CFG;
a090554a
PS
939 $sql = "SELECT i.*, r.type AS repositorytype, r.visible
940 FROM {repository} r
941 JOIN {repository_instances} i ON i.typeid = r.id
942 WHERE i.id = ?";
dbc01944 943
a090554a 944 if (!$instance = $DB->get_record_sql($sql, array($id))) {
dbc01944 945 return false;
946 }
e35194be 947 require_once($CFG->dirroot . '/repository/'. $instance->repositorytype.'/lib.php');
dbc01944 948 $classname = 'repository_' . $instance->repositorytype;
949 $options['typeid'] = $instance->typeid;
950 $options['type'] = $instance->repositorytype;
951 $options['name'] = $instance->name;
271bd2e0 952 $obj = new $classname($instance->id, $instance->contextid, $options, $instance->readonly);
953 if (empty($obj->super_called)) {
954 debugging('parent::__construct must be called by '.$classname.' plugin.');
955 }
956 return $obj;
dbc01944 957 }
958
959 /**
e35194be 960 * Call a static function. Any additional arguments than plugin and function will be passed through.
67233725
DC
961 *
962 * @static
963 * @param string $plugin repository plugin name
964 * @param string $function funciton name
2b8beee3 965 * @return mixed
dbc01944 966 */
967 public static function static_function($plugin, $function) {
968 global $CFG;
969
970 //check that the plugin exists
e35194be 971 $typedirectory = $CFG->dirroot . '/repository/'. $plugin . '/lib.php';
dbc01944 972 if (!file_exists($typedirectory)) {
f1cfe56e 973 //throw new repository_exception('invalidplugin', 'repository');
974 return false;
dbc01944 975 }
976
977 $pname = null;
978 if (is_object($plugin) || is_array($plugin)) {
979 $plugin = (object)$plugin;
980 $pname = $plugin->name;
981 } else {
982 $pname = $plugin;
983 }
984
985 $args = func_get_args();
986 if (count($args) <= 2) {
987 $args = array();
e35194be 988 } else {
dbc01944 989 array_shift($args);
990 array_shift($args);
991 }
992
993 require_once($typedirectory);
81bdfdb9 994 return call_user_func_array(array('repository_' . $plugin, $function), $args);
dbc01944 995 }
996
23bfe0a4
PS
997 /**
998 * Scan file, throws exception in case of infected file.
999 *
1000 * Please note that the scanning engine must be able to access the file,
1001 * permissions of the file are not modified here!
1002 *
1003 * @static
1004 * @param string $thefile
1005 * @param string $filename name of the file
1006 * @param bool $deleteinfected
23bfe0a4
PS
1007 */
1008 public static function antivir_scan_file($thefile, $filename, $deleteinfected) {
1009 global $CFG;
1010
1011 if (!is_readable($thefile)) {
1012 // this should not happen
1013 return;
1014 }
1015
1016 if (empty($CFG->runclamonupload) or empty($CFG->pathtoclam)) {
1017 // clam not enabled
1018 return;
1019 }
1020
1021 $CFG->pathtoclam = trim($CFG->pathtoclam);
1022
1023 if (!file_exists($CFG->pathtoclam) or !is_executable($CFG->pathtoclam)) {
1024 // misconfigured clam - use the old notification for now
1025 require("$CFG->libdir/uploadlib.php");
1026 $notice = get_string('clamlost', 'moodle', $CFG->pathtoclam);
1027 clam_message_admins($notice);
1028 return;
1029 }
1030
1031 // do NOT mess with permissions here, the calling party is responsible for making
1032 // sure the scanner engine can access the files!
1033
1034 // execute test
1035 $cmd = escapeshellcmd($CFG->pathtoclam).' --stdout '.escapeshellarg($thefile);
1036 exec($cmd, $output, $return);
1037
1038 if ($return == 0) {
1039 // perfect, no problem found
1040 return;
1041
1042 } else if ($return == 1) {
1043 // infection found
1044 if ($deleteinfected) {
1045 unlink($thefile);
1046 }
1047 throw new moodle_exception('virusfounduser', 'moodle', '', array('filename'=>$filename));
1048
1049 } else {
1050 //unknown problem
1051 require("$CFG->libdir/uploadlib.php");
1052 $notice = get_string('clamfailed', 'moodle', get_clam_error_code($return));
1053 $notice .= "\n\n". implode("\n", $output);
1054 clam_message_admins($notice);
1055 if ($CFG->clamfailureonupload === 'actlikevirus') {
1056 if ($deleteinfected) {
1057 unlink($thefile);
1058 }
1059 throw new moodle_exception('virusfounduser', 'moodle', '', array('filename'=>$filename));
1060 } else {
1061 return;
1062 }
1063 }
1064 }
1065
67233725
DC
1066 /**
1067 * Repository method to serve file
1068 *
1069 * @param stored_file $storedfile
1070 * @param int $lifetime Number of seconds before the file should expire from caches (default 24 hours)
1071 * @param int $filter 0 (default)=no filtering, 1=all files, 2=html files only
1072 * @param bool $forcedownload If true (default false), forces download of file rather than view in browser/plugin
1073 * @param array $options additional options affecting the file serving
1074 */
1075 public function send_file($storedfile, $lifetime=86400 , $filter=0, $forcedownload=false, array $options = null) {
61506a0a 1076 throw new coding_exception("Repository plugin must implement send_file() method.");
67233725
DC
1077 }
1078
1079 /**
1080 * Return reference file life time
1081 *
1082 * @param string $ref
1083 * @return int
1084 */
1085 public function get_reference_file_lifetime($ref) {
1086 // One day
1087 return 60 * 60 * 24;
1088 }
1089
1090 /**
1091 * Decide whether or not the file should be synced
1092 *
1093 * @param stored_file $storedfile
1094 * @return bool
1095 */
1096 public function sync_individual_file(stored_file $storedfile) {
1097 return true;
1098 }
1099
1100 /**
1101 * Return human readable reference information
1102 * {@link stored_file::get_reference()}
1103 *
1104 * @param string $reference
1105 * @return string|null
1106 */
1107 public function get_reference_details($reference) {
1108 return null;
1109 }
1110
1111 /**
1112 * Cache file from external repository by reference
1113 * {@link repository::get_file_reference()}
1114 * {@link repository::get_file()}
1115 * Invoked at MOODLE/repository/repository_ajax.php
1116 *
1117 * @param string $reference this reference is generated by
1118 * repository::get_file_reference()
1119 * @param stored_file $storedfile created file reference
1120 */
6dd299be 1121 public function cache_file_by_reference($reference, $storedfile) {
67233725
DC
1122 }
1123
1124 /**
1125 * Get file from external repository by reference
1126 * {@link repository::get_file_reference()}
1127 * {@link repository::get_file()}
1128 *
1129 * @param stdClass $reference file reference db record
1130 * @return stdClass|null|false
1131 */
1132 public function get_file_by_reference($reference) {
1133 return null;
1134 }
1135
dbc01944 1136 /**
1137 * Move file from download folder to file pool using FILE API
67233725
DC
1138 *
1139 * @todo MDL-28637
1140 * @static
8e0946bf 1141 * @param string $thefile file path in download folder
67233725 1142 * @param stdClass $record
1a6195b4
DC
1143 * @return array containing the following keys:
1144 * icon
1145 * file
1146 * id
1147 * url
dbc01944 1148 */
14469892 1149 public static function move_to_filepool($thefile, $record) {
390baf46 1150 global $DB, $CFG, $USER, $OUTPUT;
23bfe0a4
PS
1151
1152 // scan for viruses if possible, throws exception if problem found
1153 self::antivir_scan_file($thefile, $record->filename, empty($CFG->repository_no_delete)); //TODO: MDL-28637 this repository_no_delete is a bloody hack!
1154
dbc01944 1155 $fs = get_file_storage();
67233725
DC
1156 // If file name being used.
1157 if (repository::draftfile_exists($record->itemid, $record->filepath, $record->filename)) {
f392caba
DC
1158 $draftitemid = $record->itemid;
1159 $new_filename = repository::get_unused_filename($draftitemid, $record->filepath, $record->filename);
1160 $old_filename = $record->filename;
67233725 1161 // Create a tmp file.
f392caba
DC
1162 $record->filename = $new_filename;
1163 $newfile = $fs->create_file_from_pathname($record, $thefile);
1164 $event = array();
1165 $event['event'] = 'fileexists';
1166 $event['newfile'] = new stdClass;
1167 $event['newfile']->filepath = $record->filepath;
1168 $event['newfile']->filename = $new_filename;
1169 $event['newfile']->url = moodle_url::make_draftfile_url($draftitemid, $record->filepath, $new_filename)->out();
1170
1171 $event['existingfile'] = new stdClass;
1172 $event['existingfile']->filepath = $record->filepath;
1173 $event['existingfile']->filename = $old_filename;
1174 $event['existingfile']->url = moodle_url::make_draftfile_url($draftitemid, $record->filepath, $old_filename)->out();;
1175 return $event;
b423b4af 1176 }
14469892 1177 if ($file = $fs->create_file_from_pathname($record, $thefile)) {
88b126a5 1178 if (empty($CFG->repository_no_delete)) {
99eaca9d 1179 $delete = unlink($thefile);
88b126a5 1180 unset($CFG->repository_no_delete);
1181 }
64f93798 1182 return array(
50a8bd6c 1183 'url'=>moodle_url::make_draftfile_url($file->get_itemid(), $file->get_filepath(), $file->get_filename())->out(),
64f93798
PS
1184 'id'=>$file->get_itemid(),
1185 'file'=>$file->get_filename(),
1186 'icon' => $OUTPUT->pix_url(file_extension_icon($thefile, 32))->out(),
1187 );
dbc01944 1188 } else {
1189 return null;
1190 }
1191 }
1192
dbc01944 1193 /**
67233725 1194 * Builds a tree of files This function is then called recursively.
dbc01944 1195 *
67233725
DC
1196 * @static
1197 * @todo take $search into account, and respect a threshold for dynamic loading
1198 * @param file_info $fileinfo an object returned by file_browser::get_file_info()
1199 * @param string $search searched string
1200 * @param bool $dynamicmode no recursive call is done when in dynamic mode
1201 * @param array $list the array containing the files under the passed $fileinfo
dbc01944 1202 * @returns int the number of files found
1203 *
dbc01944 1204 */
1205 public static function build_tree($fileinfo, $search, $dynamicmode, &$list) {
390baf46 1206 global $CFG, $OUTPUT;
dbc01944 1207
1208 $filecount = 0;
1209 $children = $fileinfo->get_children();
1210
1211 foreach ($children as $child) {
1212 $filename = $child->get_visible_name();
1213 $filesize = $child->get_filesize();
1214 $filesize = $filesize ? display_size($filesize) : '';
1215 $filedate = $child->get_timemodified();
1216 $filedate = $filedate ? userdate($filedate) : '';
1217 $filetype = $child->get_mimetype();
1218
1219 if ($child->is_directory()) {
1220 $path = array();
1221 $level = $child->get_parent();
1222 while ($level) {
1223 $params = $level->get_params();
64f93798 1224 $path[] = array($params['filepath'], $level->get_visible_name());
dbc01944 1225 $level = $level->get_parent();
1226 }
1227
1228 $tmp = array(
1229 'title' => $child->get_visible_name(),
1230 'size' => 0,
1231 'date' => $filedate,
1232 'path' => array_reverse($path),
559276b1 1233 'thumbnail' => $OUTPUT->pix_url(file_folder_icon(90))->out(false)
dbc01944 1234 );
1235
1236 //if ($dynamicmode && $child->is_writable()) {
1237 // $tmp['children'] = array();
1238 //} else {
1239 // if folder name matches search, we send back all files contained.
1240 $_search = $search;
1241 if ($search && stristr($tmp['title'], $search) !== false) {
1242 $_search = false;
1243 }
1244 $tmp['children'] = array();
1245 $_filecount = repository::build_tree($child, $_search, $dynamicmode, $tmp['children']);
1246 if ($search && $_filecount) {
1247 $tmp['expanded'] = 1;
1248 }
1249
1250 //}
1251
fc3ec2ca 1252 if (!$search || $_filecount || (stristr($tmp['title'], $search) !== false)) {
dbc01944 1253 $filecount += $_filecount;
1254 $list[] = $tmp;
1255 }
1256
1257 } else { // not a directory
1258 // skip the file, if we're in search mode and it's not a match
1259 if ($search && (stristr($filename, $search) === false)) {
1260 continue;
1261 }
1262 $params = $child->get_params();
64f93798 1263 $source = serialize(array($params['contextid'], $params['component'], $params['filearea'], $params['itemid'], $params['filepath'], $params['filename']));
dbc01944 1264 $list[] = array(
1265 'title' => $filename,
1266 'size' => $filesize,
1267 'date' => $filedate,
1268 //'source' => $child->get_url(),
1269 'source' => base64_encode($source),
559276b1
MG
1270 'icon'=>$OUTPUT->pix_url(file_file_icon($child, 24))->out(false),
1271 'thumbnail'=>$OUTPUT->pix_url(file_file_icon($child, 90))->out(false),
dbc01944 1272 );
1273 $filecount++;
1274 }
1275 }
1276
1277 return $filecount;
1278 }
1279
dbc01944 1280 /**
1281 * Display a repository instance list (with edit/delete/create links)
67233725
DC
1282 *
1283 * @static
1284 * @param stdClass $context the context for which we display the instance
dbc01944 1285 * @param string $typename if set, we display only one type of instance
1286 */
1287 public static function display_instances_list($context, $typename = null) {
50a5cf09 1288 global $CFG, $USER, $OUTPUT;
dbc01944 1289
50a5cf09 1290 $output = $OUTPUT->box_start('generalbox');
dbc01944 1291 //if the context is SYSTEM, so we call it from administration page
1292 $admin = ($context->id == SYSCONTEXTID) ? true : false;
1293 if ($admin) {
e35194be
DC
1294 $baseurl = new moodle_url('/'.$CFG->admin.'/repositoryinstance.php', array('sesskey'=>sesskey()));
1295 $output .= $OUTPUT->heading(get_string('siteinstances', 'repository'));
dbc01944 1296 } else {
e35194be 1297 $baseurl = new moodle_url('/repository/manage_instances.php', array('contextid'=>$context->id, 'sesskey'=>sesskey()));
dbc01944 1298 }
1299
1300 $namestr = get_string('name');
1301 $pluginstr = get_string('plugin', 'repository');
1302 $settingsstr = get_string('settings');
1303 $deletestr = get_string('delete');
dbc01944 1304 //retrieve list of instances. In administration context we want to display all
1305 //instances of a type, even if this type is not visible. In course/user context we
92eaeca5 1306 //want to display only visible instances, but for every type types. The repository::get_instances()
dbc01944 1307 //third parameter displays only visible type.
6f2cd52a
DC
1308 $params = array();
1309 $params['context'] = array($context, get_system_context());
1310 $params['currentcontext'] = $context;
1311 $params['onlyvisible'] = !$admin;
1312 $params['type'] = $typename;
1313 $instances = repository::get_instances($params);
dbc01944 1314 $instancesnumber = count($instances);
1315 $alreadyplugins = array();
1316
55400db0 1317 $table = new html_table();
79698344 1318 $table->head = array($namestr, $pluginstr, $settingsstr, $deletestr);
dbc01944 1319 $table->align = array('left', 'left', 'center','center');
1320 $table->data = array();
1321
1322 $updowncount = 1;
1323
1324 foreach ($instances as $i) {
1325 $settings = '';
1326 $delete = '';
5363905a
DC
1327
1328 $type = repository::get_type_by_id($i->options['typeid']);
1329
1330 if ($type->get_contextvisibility($context)) {
1331 if (!$i->readonly) {
1332
67233725
DC
1333 $settingurl = new moodle_url($baseurl);
1334 $settingurl->param('type', $i->options['type']);
1335 $settingurl->param('edit', $i->id);
1336 $settings .= html_writer::link($settingurl, $settingsstr);
5363905a 1337
67233725
DC
1338 $deleteurl = new moodle_url($baseurl);
1339 $deleteurl->param('delete', $i->id);
1340 $deleteurl->param('type', $i->options['type']);
1341 $delete .= html_writer::link($deleteurl, $deletestr);
5363905a 1342 }
dbc01944 1343 }
1344
a3d8df25 1345 $type = repository::get_type_by_id($i->options['typeid']);
79698344 1346 $table->data[] = array($i->name, $type->get_readablename(), $settings, $delete);
dbc01944 1347
1348 //display a grey row if the type is defined as not visible
1349 if (isset($type) && !$type->get_visible()) {
704ac344 1350 $table->rowclasses[] = 'dimmed_text';
dbc01944 1351 } else {
704ac344 1352 $table->rowclasses[] = '';
dbc01944 1353 }
1354
1355 if (!in_array($i->name, $alreadyplugins)) {
1356 $alreadyplugins[] = $i->name;
1357 }
1358 }
16be8974 1359 $output .= html_writer::table($table);
dbc01944 1360 $instancehtml = '<div>';
1361 $addable = 0;
1362
1363 //if no type is set, we can create all type of instance
1364 if (!$typename) {
1365 $instancehtml .= '<h3>';
1366 $instancehtml .= get_string('createrepository', 'repository');
1367 $instancehtml .= '</h3><ul>';
1368 $types = repository::get_editable_types($context);
1369 foreach ($types as $type) {
1370 if (!empty($type) && $type->get_visible()) {
1371 $instanceoptionnames = repository::static_function($type->get_typename(), 'get_instance_option_names');
1372 if (!empty($instanceoptionnames)) {
e35194be
DC
1373 $baseurl->param('new', $type->get_typename());
1374 $instancehtml .= '<li><a href="'.$baseurl->out().'">'.get_string('createxxinstance', 'repository', get_string('pluginname', 'repository_'.$type->get_typename())). '</a></li>';
1375 $baseurl->remove_params('new');
dbc01944 1376 $addable++;
1377 }
1378 }
1379 }
1380 $instancehtml .= '</ul>';
1381
1382 } else {
1383 $instanceoptionnames = repository::static_function($typename, 'get_instance_option_names');
1384 if (!empty($instanceoptionnames)) { //create a unique type of instance
1385 $addable = 1;
e35194be 1386 $baseurl->param('new', $typename);
67233725 1387 $output .= $OUTPUT->single_button($baseurl, get_string('createinstance', 'repository'), 'get');
e35194be 1388 $baseurl->remove_params('new');
dbc01944 1389 }
1390 }
1391
1392 if ($addable) {
1393 $instancehtml .= '</div>';
1394 $output .= $instancehtml;
1395 }
1396
50a5cf09 1397 $output .= $OUTPUT->box_end();
dbc01944 1398
1399 //print the list + creation links
1400 print($output);
1401 }
1cf56396 1402
67233725
DC
1403 /**
1404 * Prepare file reference information
1405 *
1406 * @param string $source
1407 * @return string file referece
1408 */
1409 public function get_file_reference($source) {
1410 return $source;
1411 }
c425472d 1412 /**
e35194be 1413 * Decide where to save the file, can be overwriten by subclass
67233725
DC
1414 *
1415 * @param string $filename file name
1416 * @return file path
c425472d 1417 */
a560785f 1418 public function prepare_file($filename) {
c425472d 1419 global $CFG;
7aa06e6d
TL
1420 if (!file_exists($CFG->tempdir.'/download')) {
1421 mkdir($CFG->tempdir.'/download/', $CFG->directorypermissions, true);
1e28c767 1422 }
7aa06e6d
TL
1423 if (is_dir($CFG->tempdir.'/download')) {
1424 $dir = $CFG->tempdir.'/download/';
1e28c767 1425 }
a560785f 1426 if (empty($filename)) {
cedc3d33 1427 $filename = uniqid('repo', true).'_'.time().'.tmp';
84df43de 1428 }
a560785f 1429 if (file_exists($dir.$filename)) {
1430 $filename = uniqid('m').$filename;
c425472d 1431 }
a560785f 1432 return $dir.$filename;
a53d4f45 1433 }
1434
67233725
DC
1435 /**
1436 * Does this repository used to browse moodle files?
1437 *
1438 * @return bool
1439 */
1440 public function has_moodle_files() {
1441 return false;
1442 }
1443
99d52655
DC
1444 /**
1445 * Return file URL, for most plugins, the parameter is the original
1446 * url, but some plugins use a file id, so we need this function to
1447 * convert file id to original url.
1448 *
1449 * @param string $url the url of file
8e0946bf 1450 * @return string
99d52655
DC
1451 */
1452 public function get_link($url) {
1453 return $url;
1454 }
1455
a53d4f45 1456 /**
67233725 1457 * Download a file, this function can be overridden by subclass. {@link curl}
a53d4f45 1458 *
a53d4f45 1459 * @param string $url the url of file
a560785f 1460 * @param string $filename save location
a53d4f45 1461 * @return string the location of the file
a53d4f45 1462 */
a560785f 1463 public function get_file($url, $filename = '') {
a53d4f45 1464 global $CFG;
41076c58
DC
1465 $path = $this->prepare_file($filename);
1466 $fp = fopen($path, 'w');
1467 $c = new curl;
1468 $c->download(array(array('url'=>$url, 'file'=>$fp)));
67233725
DC
1469 // Close file handler.
1470 fclose($fp);
1dce6261 1471 return array('path'=>$path, 'url'=>$url);
82669dc4 1472 }
1cf56396 1473
c0d60b3a
AKA
1474 /**
1475 * Return size of a file in bytes.
1476 *
1477 * @param string $source encoded and serialized data of file
67233725 1478 * @return int file size in bytes
c0d60b3a
AKA
1479 */
1480 public function get_file_size($source) {
2dfa16ef 1481 // TODO MDL-33297 remove this function completely?
c0d60b3a
AKA
1482 $browser = get_file_browser();
1483 $params = unserialize(base64_decode($source));
1484 $contextid = clean_param($params['contextid'], PARAM_INT);
1485 $fileitemid = clean_param($params['itemid'], PARAM_INT);
1486 $filename = clean_param($params['filename'], PARAM_FILE);
1487 $filepath = clean_param($params['filepath'], PARAM_PATH);
aff24313
PS
1488 $filearea = clean_param($params['filearea'], PARAM_AREA);
1489 $component = clean_param($params['component'], PARAM_COMPONENT);
c0d60b3a
AKA
1490 $context = get_context_instance_by_id($contextid);
1491 $file_info = $browser->get_file_info($context, $component, $filearea, $fileitemid, $filepath, $filename);
1492 if (!empty($file_info)) {
1493 $filesize = $file_info->get_filesize();
1494 } else {
1495 $filesize = null;
1496 }
1497 return $filesize;
1498 }
1499
f48fb4d6 1500 /**
1501 * Return is the instance is visible
1502 * (is the type visible ? is the context enable ?)
67233725
DC
1503 *
1504 * @return bool
f48fb4d6 1505 */
dbc01944 1506 public function is_visible() {
7d554b64 1507 $type = repository::get_type_by_id($this->options['typeid']);
dbc01944 1508 $instanceoptions = repository::static_function($type->get_typename(), 'get_instance_option_names');
f48fb4d6 1509
1510 if ($type->get_visible()) {
1511 //if the instance is unique so it's visible, otherwise check if the instance has a enabled context
5363905a 1512 if (empty($instanceoptions) || $type->get_contextvisibility($this->context)) {
f48fb4d6 1513 return true;
1514 }
1515 }
1516
1517 return false;
1518 }
1519
eb239694 1520 /**
66dc47bc 1521 * Return the name of this instance, can be overridden.
67233725 1522 *
2b8beee3 1523 * @return string
eb239694 1524 */
7a3b93c1 1525 public function get_name() {
d31af46a 1526 global $DB;
a5adfa26
DC
1527 if ( $name = $this->instance->name ) {
1528 return $name;
d31af46a 1529 } else {
a5adfa26 1530 return get_string('pluginname', 'repository_' . $this->options['type']);
d31af46a 1531 }
1532 }
aa754fe3 1533
b318bb6d 1534 /**
67233725
DC
1535 * What kind of files will be in this repository?
1536 *
b318bb6d 1537 * @return array return '*' means this repository support any files, otherwise
1538 * return mimetypes of files, it can be an array
1539 */
014c1ca0 1540 public function supported_filetypes() {
b318bb6d 1541 // return array('text/plain', 'image/gif');
1542 return '*';
1543 }
1544
1545 /**
67233725
DC
1546 * Does it return a file url or a item_id
1547 *
b318bb6d 1548 * @return string
1549 */
41076c58 1550 public function supported_returntypes() {
67233725 1551 return (FILE_INTERNAL | FILE_EXTERNAL | FILE_REFERENCE);
92eaeca5 1552 }
b318bb6d 1553
82669dc4 1554 /**
3f24ea1e 1555 * Provide repository instance information for Ajax
67233725
DC
1556 *
1557 * @return stdClass
82669dc4 1558 */
7d554b64 1559 final public function get_meta() {
c82d7320 1560 global $CFG, $OUTPUT;
6bdfef5d 1561 $meta = new stdClass();
7d554b64 1562 $meta->id = $this->id;
1563 $meta->name = $this->get_name();
1564 $meta->type = $this->options['type'];
c82d7320 1565 $meta->icon = $OUTPUT->pix_url('icon', 'repository_'.$meta->type)->out(false);
559276b1 1566 $meta->supported_types = file_get_typegroup('extension', $this->supported_filetypes());
6f2cd52a 1567 $meta->return_types = $this->supported_returntypes();
36ef6643 1568 $meta->sortorder = $this->options['sortorder'];
7d554b64 1569 return $meta;
4a65c39a 1570 }
1cf56396 1571
b1339e98 1572 /**
1573 * Create an instance for this plug-in
67233725
DC
1574 *
1575 * @static
8dcd5deb 1576 * @param string $type the type of the repository
67233725
DC
1577 * @param int $userid the user id
1578 * @param stdClass $context the context
8dcd5deb 1579 * @param array $params the options for this instance
67233725 1580 * @param int $readonly whether to create it readonly or not (defaults to not)
2b8beee3 1581 * @return mixed
b1339e98 1582 */
49d20def 1583 public static function create($type, $userid, $context, $params, $readonly=0) {
b1339e98 1584 global $CFG, $DB;
1585 $params = (array)$params;
e35194be 1586 require_once($CFG->dirroot . '/repository/'. $type . '/lib.php');
b1339e98 1587 $classname = 'repository_' . $type;
3023078f 1588 if ($repo = $DB->get_record('repository', array('type'=>$type))) {
6bdfef5d 1589 $record = new stdClass();
3023078f 1590 $record->name = $params['name'];
1591 $record->typeid = $repo->id;
1592 $record->timecreated = time();
1593 $record->timemodified = time();
1594 $record->contextid = $context->id;
948c2860 1595 $record->readonly = $readonly;
3023078f 1596 $record->userid = $userid;
1597 $id = $DB->insert_record('repository_instances', $record);
0a6221f9 1598 $options = array();
edb50637 1599 $configs = call_user_func($classname . '::get_instance_option_names');
1e08b5cf 1600 if (!empty($configs)) {
1601 foreach ($configs as $config) {
14b2d8d8
DC
1602 if (isset($params[$config])) {
1603 $options[$config] = $params[$config];
1604 } else {
1605 $options[$config] = null;
1606 }
1e08b5cf 1607 }
3023078f 1608 }
3a01a46a 1609
3023078f 1610 if (!empty($id)) {
1611 unset($options['name']);
dbc01944 1612 $instance = repository::get_instance($id);
3023078f 1613 $instance->set_option($options);
1614 return $id;
1615 } else {
1616 return null;
b1339e98 1617 }
b1339e98 1618 } else {
1619 return null;
1620 }
1621 }
8dcd5deb 1622
82669dc4 1623 /**
4a65c39a 1624 * delete a repository instance
67233725
DC
1625 *
1626 * @param bool $downloadcontents
1627 * @return bool
82669dc4 1628 */
67233725 1629 final public function delete($downloadcontents = false) {
4a65c39a 1630 global $DB;
67233725
DC
1631 if ($downloadcontents) {
1632 $this->convert_references_to_local();
1633 }
1634 try {
1635 $DB->delete_records('repository_instances', array('id'=>$this->id));
1636 $DB->delete_records('repository_instance_config', array('instanceid'=>$this->id));
1637 } catch (dml_exception $ex) {
1638 return false;
1639 }
4a65c39a 1640 return true;
1641 }
8dcd5deb 1642
4a65c39a 1643 /**
1644 * Hide/Show a repository
67233725 1645 *
8dcd5deb 1646 * @param string $hide
67233725 1647 * @return bool
4a65c39a 1648 */
7a3b93c1 1649 final public function hide($hide = 'toggle') {
4a65c39a 1650 global $DB;
1651 if ($entry = $DB->get_record('repository', array('id'=>$this->id))) {
1652 if ($hide === 'toggle' ) {
1653 if (!empty($entry->visible)) {
1654 $entry->visible = 0;
1655 } else {
1656 $entry->visible = 1;
1657 }
1658 } else {
1659 if (!empty($hide)) {
1660 $entry->visible = 0;
1661 } else {
1662 $entry->visible = 1;
1663 }
1664 }
1665 return $DB->update_record('repository', $entry);
1666 }
1667 return false;
1668 }
1cf56396 1669
1cf56396 1670 /**
4a65c39a 1671 * Save settings for repository instance
8dcd5deb 1672 * $repo->set_option(array('api_key'=>'f2188bde132', 'name'=>'dongsheng'));
67233725 1673 *
8dcd5deb 1674 * @param array $options settings
67233725 1675 * @return bool
1cf56396 1676 */
7a3b93c1 1677 public function set_option($options = array()) {
4a65c39a 1678 global $DB;
7a3b93c1 1679
122defc5 1680 if (!empty($options['name'])) {
a27ab6fd 1681 $r = new stdClass();
122defc5 1682 $r->id = $this->id;
1683 $r->name = $options['name'];
1684 $DB->update_record('repository_instances', $r);
1685 unset($options['name']);
1686 }
27051e43 1687 foreach ($options as $name=>$value) {
1688 if ($id = $DB->get_field('repository_instance_config', 'id', array('name'=>$name, 'instanceid'=>$this->id))) {
f685e830 1689 $DB->set_field('repository_instance_config', 'value', $value, array('id'=>$id));
27051e43 1690 } else {
a27ab6fd 1691 $config = new stdClass();
27051e43 1692 $config->instanceid = $this->id;
1693 $config->name = $name;
1694 $config->value = $value;
f685e830 1695 $DB->insert_record('repository_instance_config', $config);
27051e43 1696 }
4a65c39a 1697 }
f685e830 1698 return true;
1cf56396 1699 }
1cf56396 1700
4a65c39a 1701 /**
1702 * Get settings for repository instance
67233725 1703 *
2b8beee3 1704 * @param string $config
4a65c39a 1705 * @return array Settings
1706 */
7a3b93c1 1707 public function get_option($config = '') {
4a65c39a 1708 global $DB;
27051e43 1709 $entries = $DB->get_records('repository_instance_config', array('instanceid'=>$this->id));
1710 $ret = array();
1711 if (empty($entries)) {
1712 return $ret;
4a65c39a 1713 }
7a3b93c1 1714 foreach($entries as $entry) {
27051e43 1715 $ret[$entry->name] = $entry->value;
4a65c39a 1716 }
1717 if (!empty($config)) {
9e6aa5ec 1718 if (isset($ret[$config])) {
75003899 1719 return $ret[$config];
9e6aa5ec
DC
1720 } else {
1721 return null;
1722 }
4a65c39a 1723 } else {
1724 return $ret;
1725 }
1726 }
bf1fccf0 1727
67233725
DC
1728 /**
1729 * Filter file listing to display specific types
1730 *
1731 * @param array $value
1732 * @return bool
1733 */
c167aa26 1734 public function filter(&$value) {
18bd7573 1735 $accepted_types = optional_param_array('accepted_types', '', PARAM_RAW);
b81ebefd 1736 if (isset($value['children'])) {
b81ebefd 1737 if (!empty($value['children'])) {
b81ebefd 1738 $value['children'] = array_filter($value['children'], array($this, 'filter'));
537d44e8 1739 }
559276b1 1740 return true; // always return directories
c167aa26 1741 } else {
46ee50dc 1742 if ($accepted_types == '*' or empty($accepted_types)
1743 or (is_array($accepted_types) and in_array('*', $accepted_types))) {
559276b1
MG
1744 return true;
1745 } else {
e5635827
MG
1746 foreach ($accepted_types as $ext) {
1747 if (preg_match('#'.$ext.'$#i', $value['title'])) {
559276b1 1748 return true;
c167aa26 1749 }
1750 }
1751 }
1752 }
559276b1 1753 return false;
c167aa26 1754 }
1755
4a65c39a 1756 /**
1757 * Given a path, and perhaps a search, get a list of files.
1758 *
67233725 1759 * See details on {@link http://docs.moodle.org/dev/Repository_plugins}
f7639c37 1760 *
67233725
DC
1761 * @param string $path this parameter can a folder name, or a identification of folder
1762 * @param string $page the page number of file list
1a6195b4
DC
1763 * @return array the list of files, including meta infomation, containing the following keys
1764 * manage, url to manage url
1765 * client_id
1766 * login, login form
1767 * repo_id, active repository id
1768 * login_btn_action, the login button action
1769 * login_btn_label, the login button label
1770 * total, number of results
1771 * perpage, items per page
1772 * page
1773 * pages, total pages
29199e56 1774 * issearchresult, is it a search result?
1a6195b4
DC
1775 * list, file list
1776 * path, current path and parent path
4a65c39a 1777 */
9d6aa286 1778 public function get_listing($path = '', $page = '') {
1779 }
1cf56396 1780
fbd508b4 1781 /**
5bdf63cc 1782 * Prepares list of files before passing it to AJAX, makes sure data is in the correct
dd1f051e 1783 * format and stores formatted values.
5bdf63cc 1784 *
e709ddd2 1785 * @param array|stdClass $listing result of get_listing() or search() or file_get_drafarea_files()
5bdf63cc
MG
1786 * @return array
1787 */
1788 public static function prepare_listing($listing) {
1789 global $OUTPUT;
9213f547
MG
1790
1791 $defaultfoldericon = $OUTPUT->pix_url(file_folder_icon(24))->out(false);
1792 // prepare $listing['path'] or $listing->path
09cb95f8 1793 if (is_array($listing) && isset($listing['path']) && is_array($listing['path'])) {
9213f547 1794 $path = &$listing['path'];
0479a287 1795 } else if (is_object($listing) && isset($listing->path) && is_array($listing->path)) {
9213f547
MG
1796 $path = &$listing->path;
1797 }
1798 if (isset($path)) {
1799 $len = count($path);
1800 for ($i=0; $i<$len; $i++) {
1801 if (is_array($path[$i]) && !isset($path[$i]['icon'])) {
1802 $path[$i]['icon'] = $defaultfoldericon;
1803 } else if (is_object($path[$i]) && !isset($path[$i]->icon)) {
1804 $path[$i]->icon = $defaultfoldericon;
1805 }
1806 }
1807 }
1808
1809 // prepare $listing['list'] or $listing->list
0479a287 1810 if (is_array($listing) && isset($listing['list']) && is_array($listing['list'])) {
dd1f051e 1811 $listing['list'] = array_values($listing['list']); // convert to array
e709ddd2 1812 $files = &$listing['list'];
0479a287 1813 } else if (is_object($listing) && isset($listing->list) && is_array($listing->list)) {
dd1f051e 1814 $listing->list = array_values($listing->list); // convert to array
e709ddd2
MG
1815 $files = &$listing->list;
1816 } else {
5bdf63cc
MG
1817 return $listing;
1818 }
e709ddd2 1819 $len = count($files);
5bdf63cc 1820 for ($i=0; $i<$len; $i++) {
e709ddd2
MG
1821 if (is_object($files[$i])) {
1822 $file = (array)$files[$i];
1823 $converttoobject = true;
1824 } else {
1825 $file = & $files[$i];
1826 $converttoobject = false;
1827 }
b92241f2
MG
1828 if (isset($file['size'])) {
1829 $file['size'] = (int)$file['size'];
1830 $file['size_f'] = display_size($file['size']);
1831 }
1832 if (isset($file['license']) &&
1833 get_string_manager()->string_exists($file['license'], 'license')) {
1834 $file['license_f'] = get_string($file['license'], 'license');
1835 }
1836 if (isset($file['image_width']) && isset($file['image_height'])) {
dd1f051e
MG
1837 $a = array('width' => $file['image_width'], 'height' => $file['image_height']);
1838 $file['dimensions'] = get_string('imagesize', 'repository', (object)$a);
5bdf63cc
MG
1839 }
1840 foreach (array('date', 'datemodified', 'datecreated') as $key) {
b92241f2
MG
1841 if (!isset($file[$key]) && isset($file['date'])) {
1842 $file[$key] = $file['date'];
5bdf63cc 1843 }
b92241f2 1844 if (isset($file[$key])) {
5bdf63cc 1845 // must be UNIX timestamp
b92241f2
MG
1846 $file[$key] = (int)$file[$key];
1847 if (!$file[$key]) {
1848 unset($file[$key]);
5bdf63cc 1849 } else {
b92241f2
MG
1850 $file[$key.'_f'] = userdate($file[$key], get_string('strftimedatetime', 'langconfig'));
1851 $file[$key.'_f_s'] = userdate($file[$key], get_string('strftimedatetimeshort', 'langconfig'));
5bdf63cc
MG
1852 }
1853 }
1854 }
e709ddd2
MG
1855 $isfolder = (array_key_exists('children', $file) || (isset($file['type']) && $file['type'] == 'folder'));
1856 $filename = null;
1857 if (isset($file['title'])) {
1858 $filename = $file['title'];
1859 }
1860 else if (isset($file['fullname'])) {
1861 $filename = $file['fullname'];
1862 }
1863 if (!isset($file['mimetype']) && !$isfolder && $filename) {
559276b1 1864 $file['mimetype'] = get_mimetype_description(array('filename' => $filename));
5bdf63cc 1865 }
e709ddd2
MG
1866 if (!isset($file['icon'])) {
1867 if ($isfolder) {
9213f547 1868 $file['icon'] = $defaultfoldericon;
e709ddd2 1869 } else if ($filename) {
559276b1 1870 $file['icon'] = $OUTPUT->pix_url(file_extension_icon($filename, 24))->out(false);
5bdf63cc
MG
1871 }
1872 }
e709ddd2
MG
1873 if ($converttoobject) {
1874 $files[$i] = (object)$file;
1875 }
5bdf63cc
MG
1876 }
1877 return $listing;
1878 }
1879
1880 /**
1881 * Search files in repository
1882 * When doing global search, $search_text will be used as
1883 * keyword.
353d5cf3 1884 *
67233725
DC
1885 * @param string $search_text search key word
1886 * @param int $page page
1887 * @return mixed {@see repository::get_listing}
fbd508b4 1888 */
68a7c9a6 1889 public function search($search_text, $page = 0) {
353d5cf3 1890 $list = array();
1891 $list['list'] = array();
1892 return false;
fbd508b4 1893 }
1894
d68c527f 1895 /**
1896 * Logout from repository instance
1897 * By default, this function will return a login form
1898 *
1899 * @return string
1900 */
1901 public function logout(){
1902 return $this->print_login();
1903 }
1904
1905 /**
1906 * To check whether the user is logged in.
1907 *
67233725 1908 * @return bool
d68c527f 1909 */
1910 public function check_login(){
1911 return true;
1912 }
1913
1cf56396 1914
4a65c39a 1915 /**
1916 * Show the login screen, if required
67233725
DC
1917 *
1918 * @return string
4a65c39a 1919 */
1d66f2b2 1920 public function print_login(){
1921 return $this->get_listing();
1922 }
1cf56396 1923
4a65c39a 1924 /**
1925 * Show the search screen, if required
67233725
DC
1926 *
1927 * @return string
4a65c39a 1928 */
a560785f 1929 public function print_search() {
b5e7b638 1930 global $PAGE;
d1d18691 1931 $renderer = $PAGE->get_renderer('core', 'files');
b5e7b638 1932 return $renderer->repository_default_searchform();
2b9feb5f 1933 }
4a65c39a 1934
3e123368
DC
1935 /**
1936 * For oauth like external authentication, when external repository direct user back to moodle,
1937 * this funciton will be called to set up token and token_secret
1938 */
1939 public function callback() {
1940 }
1941
455860ce 1942 /**
1943 * is it possible to do glboal search?
67233725
DC
1944 *
1945 * @return bool
455860ce 1946 */
7a3b93c1 1947 public function global_search() {
455860ce 1948 return false;
1949 }
1950
8dcd5deb 1951 /**
a6600395 1952 * Defines operations that happen occasionally on cron
67233725
DC
1953 *
1954 * @return bool
8dcd5deb 1955 */
a6600395 1956 public function cron() {
1957 return true;
1958 }
1959
7892948d 1960 /**
83a018ed 1961 * function which is run when the type is created (moodle administrator add the plugin)
67233725
DC
1962 *
1963 * @return bool success or fail?
7892948d 1964 */
f1cfe56e 1965 public static function plugin_init() {
3e0794ed 1966 return true;
7892948d 1967 }
1968
a6600395 1969 /**
06e65e1e 1970 * Edit/Create Admin Settings Moodle form
67233725
DC
1971 *
1972 * @param moodleform $mform Moodle form (passed by reference)
8e5af6cf 1973 * @param string $classname repository class name
a6600395 1974 */
68a7c9a6 1975 public static function type_config_form($mform, $classname = 'repository') {
8e5af6cf 1976 $instnaceoptions = call_user_func(array($classname, 'get_instance_option_names'), $mform, $classname);
a5adfa26
DC
1977 if (empty($instnaceoptions)) {
1978 // this plugin has only one instance
1979 // so we need to give it a name
1980 // it can be empty, then moodle will look for instance name from language string
1981 $mform->addElement('text', 'pluginname', get_string('pluginname', 'repository'), array('size' => '40'));
1982 $mform->addElement('static', 'pluginnamehelp', '', get_string('pluginnamehelp', 'repository'));
1983 }
4a65c39a 1984 }
dbc01944 1985
84ee73ee
RK
1986 /**
1987 * Validate Admin Settings Moodle form
67233725
DC
1988 *
1989 * @static
1990 * @param moodleform $mform Moodle form (passed by reference)
1991 * @param array $data array of ("fieldname"=>value) of submitted data
1992 * @param array $errors array of ("fieldname"=>errormessage) of errors
84ee73ee
RK
1993 * @return array array of errors
1994 */
1995 public static function type_form_validation($mform, $data, $errors) {
1996 return $errors;
1997 }
1998
1999
6f2cd52a 2000 /**
06e65e1e 2001 * Edit/Create Instance Settings Moodle form
67233725
DC
2002 *
2003 * @param moodleform $mform Moodle form (passed by reference)
a6600395 2004 */
8c4a4687 2005 public function instance_config_form($mform) {
a6600395 2006 }
4a65c39a 2007
a6600395 2008 /**
67233725 2009 * Return names of the general options.
a6600395 2010 * By default: no general option name
67233725 2011 *
a6600395 2012 * @return array
2013 */
1b79955a 2014 public static function get_type_option_names() {
a5adfa26 2015 return array('pluginname');
a6600395 2016 }
2017
2018 /**
67233725 2019 * Return names of the instance options.
a6600395 2020 * By default: no instance option name
67233725 2021 *
a6600395 2022 * @return array
2023 */
7a3b93c1 2024 public static function get_instance_option_names() {
a6600395 2025 return array();
8b65d45c 2026 }
e35194be 2027
67233725
DC
2028 /**
2029 * Validate repository plugin instance form
2030 *
2031 * @param moodleform $mform moodle form
2032 * @param array $data form data
2033 * @param array $errors errors
2034 * @return array errors
2035 */
6b172cdc
DC
2036 public static function instance_form_validation($mform, $data, $errors) {
2037 return $errors;
2038 }
2039
67233725
DC
2040 /**
2041 * Create a shorten filename
2042 *
2043 * @param string $str filename
2044 * @param int $maxlength max file name length
2045 * @return string short filename
2046 */
f00340e2 2047 public function get_short_filename($str, $maxlength) {
138c7678
PS
2048 if (textlib::strlen($str) >= $maxlength) {
2049 return trim(textlib::substr($str, 0, $maxlength)).'...';
f00340e2
DC
2050 } else {
2051 return $str;
2052 }
2053 }
f392caba
DC
2054
2055 /**
2056 * Overwrite an existing file
2057 *
2058 * @param int $itemid
2059 * @param string $filepath
2060 * @param string $filename
2061 * @param string $newfilepath
2062 * @param string $newfilename
67233725 2063 * @return bool
f392caba 2064 */
061eeed5 2065 public static function overwrite_existing_draftfile($itemid, $filepath, $filename, $newfilepath, $newfilename) {
f392caba
DC
2066 global $USER;
2067 $fs = get_file_storage();
2068 $user_context = get_context_instance(CONTEXT_USER, $USER->id);
2069 if ($file = $fs->get_file($user_context->id, 'user', 'draft', $itemid, $filepath, $filename)) {
2070 if ($tempfile = $fs->get_file($user_context->id, 'user', 'draft', $itemid, $newfilepath, $newfilename)) {
2071 // delete existing file to release filename
2072 $file->delete();
2073 // create new file
2074 $newfile = $fs->create_file_from_storedfile(array('filepath'=>$filepath, 'filename'=>$filename), $tempfile);
2075 // remove temp file
2076 $tempfile->delete();
2077 return true;
2078 }
2079 }
2080 return false;
2081 }
2082
2083 /**
2084 * Delete a temp file from draft area
2085 *
2086 * @param int $draftitemid
2087 * @param string $filepath
2088 * @param string $filename
67233725 2089 * @return bool
f392caba 2090 */
061eeed5 2091 public static function delete_tempfile_from_draft($draftitemid, $filepath, $filename) {
f392caba
DC
2092 global $USER;
2093 $fs = get_file_storage();
2094 $user_context = get_context_instance(CONTEXT_USER, $USER->id);
2095 if ($file = $fs->get_file($user_context->id, 'user', 'draft', $draftitemid, $filepath, $filename)) {
2096 $file->delete();
2097 return true;
2098 } else {
2099 return false;
2100 }
2101 }
67233725
DC
2102
2103 /**
2104 * Find all external files in this repo and import them
2105 */
2106 public function convert_references_to_local() {
2107 $fs = get_file_storage();
2108 $files = $fs->get_external_files($this->id);
2109 foreach ($files as $storedfile) {
2110 $fs->import_external_file($storedfile);
2111 }
2112 }
2113
2114
2115
2116 /**
2117 * Call to request proxy file sync with repository source.
2118 *
2119 * @param stored_file $file
2120 * @return bool success
2121 */
2122 public static function sync_external_file(stored_file $file) {
2123 global $DB;
2124
2125 $fs = get_file_storage();
2126
2127 if (!$reference = $DB->get_record('files_reference', array('id'=>$file->get_referencefileid()))) {
2128 return false;
2129 }
2130
2131 if (!empty($reference->lastsync) and ($reference->lastsync + $reference->lifetime > time())) {
2132 return false;
2133 }
2134
2135 if (!$repository = self::get_repository_by_id($reference->repositoryid, SYSCONTEXTID)) {
2136 return false;
2137 }
2138
2139 if (!$repository->sync_individual_file($file)) {
2140 return false;
2141 }
2142
2143 $fileinfo = $repository->get_file_by_reference($reference);
2144 if ($fileinfo === null) {
2145 // does not exist any more - set status to missing
2146 $sql = "UPDATE {files} SET status = :missing WHERE referencefileid = :referencefileid";
2147 $params = array('referencefileid'=>$reference->id, 'missing'=>666);
2148 $DB->execute($sql, $params);
2149 //TODO: purge content from pool if we set some other content hash and it is no used any more
2150 return true;
2151 } else if ($fileinfo === false) {
2152 // error
2153 return false;
2154 }
2155
2156 $contenthash = null;
2157 $filesize = null;
2158 if (!empty($fileinfo->contenthash)) {
2159 // contenthash returned, file already in moodle
2160 $contenthash = $fileinfo->contenthash;
2161 $filesize = $fileinfo->filesize;
2162 } else if (!empty($fileinfo->filepath)) {
2163 // File path returned
2164 list($contenthash, $filesize, $newfile) = $fs->add_file_to_pool($fileinfo->filepath);
2165 } else if (!empty($fileinfo->handle) && is_resource($fileinfo->handle)) {
2166 // File handle returned
2167 $contents = '';
2168 while (!feof($fileinfo->handle)) {
2169 $contents .= fread($handle, 8192);
2170 }
2171 fclose($fileinfo->handle);
2172 list($contenthash, $filesize, $newfile) = $fs->add_string_to_pool($content);
2173 } else if (isset($fileinfo->content)) {
2174 // File content returned
2175 list($contenthash, $filesize, $newfile) = $fs->add_string_to_pool($fileinfo->content);
2176 }
2177
2178 if (!isset($contenthash) or !isset($filesize)) {
2179 return false;
2180 }
2181
2182 $now = time();
2183 // update files table
2184 $sql = "UPDATE {files} SET contenthash = :contenthash, filesize = :filesize, referencelastsync = :now, referencelifetime = :lifetime, timemodified = :now2 WHERE referencefileid = :referencefileid AND contenthash <> :contenthash2";
2185 $params = array('contenthash'=>$contenthash, 'filesize'=>$filesize, 'now'=>$now, 'lifetime'=>$reference->lifetime,
2186 'now2'=>$now, 'referencefileid'=>$reference->id, 'contenthash2'=>$contenthash);
2187 $DB->execute($sql, $params);
2188
2189 $DB->set_field('files_reference', 'lastsync', $now, array('id'=>$reference->id));
2190
2191 return true;
2192 }
8b65d45c 2193}
837ebb78 2194
2195/**
6f2cd52a
DC
2196 * Exception class for repository api
2197 *
2198 * @since 2.0
67233725
DC
2199 * @package repository
2200 * @category repository
2201 * @copyright 2009 Dongsheng Cai {@link http://dongsheng.org}
6f2cd52a 2202 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
837ebb78 2203 */
4a65c39a 2204class repository_exception extends moodle_exception {
8b65d45c 2205}
4ed43890 2206
8dcd5deb 2207/**
6f2cd52a
DC
2208 * This is a class used to define a repository instance form
2209 *
2210 * @since 2.0
67233725
DC
2211 * @package repository
2212 * @category repository
2213 * @copyright 2009 Dongsheng Cai {@link http://dongsheng.org}
6f2cd52a 2214 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
8dcd5deb 2215 */
a6600395 2216final class repository_instance_form extends moodleform {
67233725 2217 /** @var stdClass repository instance */
4a65c39a 2218 protected $instance;
67233725 2219 /** @var string repository plugin type */
4a65c39a 2220 protected $plugin;
67233725
DC
2221
2222 /**
2223 * Added defaults to moodle form
2224 */
49d20def 2225 protected function add_defaults() {
4a65c39a 2226 $mform =& $this->_form;
2227 $strrequired = get_string('required');
2228
2229 $mform->addElement('hidden', 'edit', ($this->instance) ? $this->instance->id : 0);
d18e0fe6 2230 $mform->setType('edit', PARAM_INT);
4a65c39a 2231 $mform->addElement('hidden', 'new', $this->plugin);
d18e0fe6 2232 $mform->setType('new', PARAM_FORMAT);
4a65c39a 2233 $mform->addElement('hidden', 'plugin', $this->plugin);
aff24313 2234 $mform->setType('plugin', PARAM_PLUGIN);
27051e43 2235 $mform->addElement('hidden', 'typeid', $this->typeid);
d18e0fe6 2236 $mform->setType('typeid', PARAM_INT);
faaa613d 2237 $mform->addElement('hidden', 'contextid', $this->contextid);
d18e0fe6 2238 $mform->setType('contextid', PARAM_INT);
4a65c39a 2239
2240 $mform->addElement('text', 'name', get_string('name'), 'maxlength="100" size="30"');
2241 $mform->addRule('name', $strrequired, 'required', null, 'client');
49d20def 2242 }
4a65c39a 2243
67233725
DC
2244 /**
2245 * Define moodle form elements
2246 */
49d20def
DC
2247 public function definition() {
2248 global $CFG;
2249 // type of plugin, string
2250 $this->plugin = $this->_customdata['plugin'];
2251 $this->typeid = $this->_customdata['typeid'];
2252 $this->contextid = $this->_customdata['contextid'];
2253 $this->instance = (isset($this->_customdata['instance'])
2254 && is_subclass_of($this->_customdata['instance'], 'repository'))
2255 ? $this->_customdata['instance'] : null;
2256
2257 $mform =& $this->_form;
1e97f196 2258
49d20def 2259 $this->add_defaults();
f48fb4d6 2260 //add fields
2261 if (!$this->instance) {
dbc01944 2262 $result = repository::static_function($this->plugin, 'instance_config_form', $mform);
49d20def
DC
2263 if ($result === false) {
2264 $mform->removeElement('name');
2265 }
2266 } else {
f48fb4d6 2267 $data = array();
2268 $data['name'] = $this->instance->name;
2269 if (!$this->instance->readonly) {
2270 $result = $this->instance->instance_config_form($mform);
49d20def
DC
2271 if ($result === false) {
2272 $mform->removeElement('name');
2273 }
f48fb4d6 2274 // and set the data if we have some.
1e97f196 2275 foreach ($this->instance->get_instance_option_names() as $config) {
a3d8df25 2276 if (!empty($this->instance->options[$config])) {
2277 $data[$config] = $this->instance->options[$config];
1e97f196 2278 } else {
2279 $data[$config] = '';
2280 }
27051e43 2281 }
4a65c39a 2282 }
f48fb4d6 2283 $this->set_data($data);
1e97f196 2284 }
2285
49d20def
DC
2286 if ($result === false) {
2287 $mform->addElement('cancel');
2288 } else {
2289 $this->add_action_buttons(true, get_string('save','repository'));
2290 }
4a65c39a 2291 }
2292
67233725
DC
2293 /**
2294 * Validate moodle form data
2295 *
2296 * @param array $data form data
2297 * @param array $files files in form
2298 * @return array errors
2299 */
58eb9b9f 2300 public function validation($data, $files) {
4a65c39a 2301 global $DB;
4a65c39a 2302 $errors = array();
6b172cdc
DC
2303 $plugin = $this->_customdata['plugin'];
2304 $instance = (isset($this->_customdata['instance'])
2305 && is_subclass_of($this->_customdata['instance'], 'repository'))
2306 ? $this->_customdata['instance'] : null;
2307 if (!$instance) {
2308 $errors = repository::static_function($plugin, 'instance_form_validation', $this, $data, $errors);
2309 } else {
2310 $errors = $instance->instance_form_validation($this, $data, $errors);
2311 }
2312
a090554a
PS
2313 $sql = "SELECT count('x')
2314 FROM {repository_instances} i, {repository} r
2315 WHERE r.type=:plugin AND r.id=i.typeid AND i.name=:name";
09bff8e8 2316 if ($DB->count_records_sql($sql, array('name' => $data['name'], 'plugin' => $data['plugin'])) > 1) {
6b172cdc 2317 $errors['name'] = get_string('erroruniquename', 'repository');
4a65c39a 2318 }
2319
4a65c39a 2320 return $errors;
2321 }
2322}
a6600395 2323
a6600395 2324/**
6f2cd52a
DC
2325 * This is a class used to define a repository type setting form
2326 *
2327 * @since 2.0
67233725
DC
2328 * @package repository
2329 * @category repository
2330 * @copyright 2009 Dongsheng Cai {@link http://dongsheng.org}
6f2cd52a 2331 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
a6600395 2332 */
c295f9ff 2333final class repository_type_form extends moodleform {
67233725 2334 /** @var stdClass repository instance */
a6600395 2335 protected $instance;
67233725 2336 /** @var string repository plugin name */
a6600395 2337 protected $plugin;
67233725 2338 /** @var string action */
79698344 2339 protected $action;
a6600395 2340
2341 /**
2342 * Definition of the moodleform
a6600395 2343 */
2344 public function definition() {
2345 global $CFG;
2346 // type of plugin, string
2347 $this->plugin = $this->_customdata['plugin'];
2348 $this->instance = (isset($this->_customdata['instance'])
2349 && is_a($this->_customdata['instance'], 'repository_type'))
2350 ? $this->_customdata['instance'] : null;
2351
79698344 2352 $this->action = $this->_customdata['action'];
a5adfa26 2353 $this->pluginname = $this->_customdata['pluginname'];
a6600395 2354 $mform =& $this->_form;
2355 $strrequired = get_string('required');
4d5948f1 2356
79698344
MD
2357 $mform->addElement('hidden', 'action', $this->action);
2358 $mform->setType('action', PARAM_TEXT);
2359 $mform->addElement('hidden', 'repos', $this->plugin);
aff24313 2360 $mform->setType('repos', PARAM_PLUGIN);
8f943eba 2361
06e65e1e 2362 // let the plugin add its specific fields
a5adfa26
DC
2363 $classname = 'repository_' . $this->plugin;
2364 require_once($CFG->dirroot . '/repository/' . $this->plugin . '/lib.php');
f48fb4d6 2365 //add "enable course/user instances" checkboxes if multiple instances are allowed
dbc01944 2366 $instanceoptionnames = repository::static_function($this->plugin, 'get_instance_option_names');
8e5af6cf
DC
2367
2368 $result = call_user_func(array($classname, 'type_config_form'), $mform, $classname);
2369
a5adfa26 2370 if (!empty($instanceoptionnames)) {
8e5af6cf
DC
2371 $sm = get_string_manager();
2372 $component = 'repository';
2373 if ($sm->string_exists('enablecourseinstances', 'repository_' . $this->plugin)) {
2374 $component .= ('_' . $this->plugin);
2375 }
2376 $mform->addElement('checkbox', 'enablecourseinstances', get_string('enablecourseinstances', $component));
2377
2378 $component = 'repository';
2379 if ($sm->string_exists('enableuserinstances', 'repository_' . $this->plugin)) {
2380 $component .= ('_' . $this->plugin);
2381 }
2382 $mform->addElement('checkbox', 'enableuserinstances', get_string('enableuserinstances', $component));
f48fb4d6 2383 }
2384
2385 // set the data if we have some.
a6600395 2386 if ($this->instance) {
2387 $data = array();
1b79955a 2388 $option_names = call_user_func(array($classname,'get_type_option_names'));
f48fb4d6 2389 if (!empty($instanceoptionnames)){
2390 $option_names[] = 'enablecourseinstances';
2391 $option_names[] = 'enableuserinstances';
2392 }
2393
a6600395 2394 $instanceoptions = $this->instance->get_options();
2395 foreach ($option_names as $config) {
2396 if (!empty($instanceoptions[$config])) {
2397 $data[$config] = $instanceoptions[$config];
2398 } else {
2399 $data[$config] = '';
2400 }
2401 }
a5adfa26
DC
2402 // XXX: set plugin name for plugins which doesn't have muliti instances
2403 if (empty($instanceoptionnames)){
2404 $data['pluginname'] = $this->pluginname;
2405 }
a6600395 2406 $this->set_data($data);
2407 }
dbc01944 2408
46dd6bb0 2409 $this->add_action_buttons(true, get_string('save','repository'));
a6600395 2410 }
84ee73ee 2411
67233725
DC
2412 /**
2413 * Validate moodle form data
2414 *
2415 * @param array $data moodle form data
2416 * @param array $files
2417 * @return array errors
2418 */
58eb9b9f 2419 public function validation($data, $files) {
84ee73ee
RK
2420 $errors = array();
2421 $plugin = $this->_customdata['plugin'];
2422 $instance = (isset($this->_customdata['instance'])
2423 && is_subclass_of($this->_customdata['instance'], 'repository'))
2424 ? $this->_customdata['instance'] : null;
2425 if (!$instance) {
2426 $errors = repository::static_function($plugin, 'type_form_validation', $this, $data, $errors);
2427 } else {
2428 $errors = $instance->type_form_validation($this, $data, $errors);
2429 }
2430
2431 return $errors;
2432 }
a6600395 2433}
2434
8e0946bf
DC
2435/**
2436 * Generate all options needed by filepicker
2437 *
67233725 2438 * @param array $args including following keys
8e0946bf
DC
2439 * context
2440 * accepted_types
2441 * return_types
2442 *
2443 * @return array the list of repository instances, including meta infomation, containing the following keys
2444 * externallink
2445 * repositories
2446 * accepted_types
2447 */
99eaca9d 2448function initialise_filepicker($args) {
a28c9253 2449 global $CFG, $USER, $PAGE, $OUTPUT;
d1d18691 2450 static $templatesinitialized;
1dce6261 2451 require_once($CFG->libdir . '/licenselib.php');
4f0c2d00 2452
6bdfef5d 2453 $return = new stdClass();
d1d4813f 2454 $licenses = array();
4f0c2d00
PS
2455 if (!empty($CFG->licenses)) {
2456 $array = explode(',', $CFG->licenses);
2457 foreach ($array as $license) {
6bdfef5d 2458 $l = new stdClass();
4f0c2d00
PS
2459 $l->shortname = $license;
2460 $l->fullname = get_string($license, 'license');
2461 $licenses[] = $l;
2462 }
d1d4813f 2463 }
308d948b
DC
2464 if (!empty($CFG->sitedefaultlicense)) {
2465 $return->defaultlicense = $CFG->sitedefaultlicense;
2466 }
1dce6261 2467
1dce6261
DC
2468 $return->licenses = $licenses;
2469
2470 $return->author = fullname($USER);
2471
99eaca9d
DC
2472 if (empty($args->context)) {
2473 $context = $PAGE->context;
e189ec00 2474 } else {
99eaca9d
DC
2475 $context = $args->context;
2476 }
6bf197b3
DC
2477 $disable_types = array();
2478 if (!empty($args->disable_types)) {
2479 $disable_types = $args->disable_types;
2480 }
99eaca9d 2481
e189ec00 2482 $user_context = get_context_instance(CONTEXT_USER, $USER->id);
99eaca9d 2483
bf413f6f
DC
2484 list($context, $course, $cm) = get_context_info_array($context->id);
2485 $contexts = array($user_context, get_system_context());
2486 if (!empty($course)) {
2487 // adding course context
2488 $contexts[] = get_context_instance(CONTEXT_COURSE, $course->id);
2489 }
99eaca9d
DC
2490 $externallink = (int)get_config(null, 'repositoryallowexternallinks');
2491 $repositories = repository::get_instances(array(
bf413f6f 2492 'context'=>$contexts,
99eaca9d 2493 'currentcontext'=> $context,
ea1780ad 2494 'accepted_types'=>$args->accepted_types,
6bf197b3
DC
2495 'return_types'=>$args->return_types,
2496 'disable_types'=>$disable_types
99eaca9d
DC
2497 ));
2498
2499 $return->repositories = array();
2500
2501 if (empty($externallink)) {
2502 $return->externallink = false;
2503 } else {
2504 $return->externallink = true;
2505 }
2506
99eaca9d 2507 // provided by form element
559276b1 2508 $return->accepted_types = file_get_typegroup('extension', $args->accepted_types);
766514a0 2509 $return->return_types = $args->return_types;
99eaca9d
DC
2510 foreach ($repositories as $repository) {
2511 $meta = $repository->get_meta();
6b37c2b0
SH
2512 // Please note that the array keys for repositories are used within
2513 // JavaScript a lot, the key NEEDS to be the repository id.
b0985814 2514 $return->repositories[$repository->id] = $meta;
99eaca9d 2515 }
d1d18691
MG
2516 if (!$templatesinitialized) {
2517 // we need to send filepicker templates to the browser just once
2518 $fprenderer = $PAGE->get_renderer('core', 'files');
2519 $templates = $fprenderer->filepicker_js_templates();
2520 $PAGE->requires->js_init_call('M.core_filepicker.set_templates', array($templates), true);
2521 $templatesinitialized = true;
2522 }
99eaca9d 2523 return $return;
e189ec00 2524}
f392caba
DC
2525/**
2526 * Small function to walk an array to attach repository ID
67233725 2527 *
f392caba
DC
2528 * @param array $value
2529 * @param string $key
2530 * @param int $id
2531 */
2532function repository_attach_id(&$value, $key, $id){
2533 $value['repo_id'] = $id;
2534}