MDL-34346 Cache retrieved repositories
[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 18 * This file contains classes used to manage the repository plugins in Moodle
6f2cd52a
DC
19 *
20 * @since 2.0
72a56555 21 * @package core_repository
67233725
DC
22 * @copyright 2009 Dongsheng Cai {@link http://dongsheng.org}
23 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
aca64b79 24 */
25
e56de3a4 26defined('MOODLE_INTERNAL') || die();
c19f8e7d 27require_once($CFG->libdir . '/filelib.php');
28require_once($CFG->libdir . '/formslib.php');
41076c58 29
67233725
DC
30define('FILE_EXTERNAL', 1);
31define('FILE_INTERNAL', 2);
32define('FILE_REFERENCE', 4);
f392caba 33define('RENAME_SUFFIX', '_2');
41076c58 34
a6600395 35/**
6f2cd52a
DC
36 * This class is used to manage repository plugins
37 *
a6600395 38 * A repository_type is a repository plug-in. It can be Box.net, Flick-r, ...
39 * A repository type can be edited, sorted and hidden. It is mandatory for an
40 * administrator to create a repository type in order to be able to create
41 * some instances of this type.
a6600395 42 * Coding note:
43 * - a repository_type object is mapped to the "repository" database table
44 * - "typename" attibut maps the "type" database field. It is unique.
45 * - general "options" for a repository type are saved in the config_plugin table
eb239694 46 * - when you delete a repository, all instances are deleted, and general
47 * options are also deleted from database
a6600395 48 * - When you create a type for a plugin that can't have multiple instances, a
49 * instance is automatically created.
6f2cd52a 50 *
72a56555 51 * @package core_repository
6f2cd52a
DC
52 * @copyright 2009 Jerome Mouneyrac
53 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
a6600395 54 */
118ca9e9 55class repository_type implements cacheable_object {
a6600395 56
57
58 /**
59 * Type name (no whitespace) - A type name is unique
60 * Note: for a user-friendly type name see get_readablename()
61 * @var String
62 */
63 private $_typename;
64
65
66 /**
67 * Options of this type
68 * They are general options that any instance of this type would share
69 * e.g. API key
70 * These options are saved in config_plugin table
71 * @var array
72 */
7a3b93c1 73 private $_options;
a6600395 74
75
76 /**
77 * Is the repository type visible or hidden
78 * If false (hidden): no instances can be created, edited, deleted, showned , used...
79 * @var boolean
80 */
7a3b93c1 81 private $_visible;
a6600395 82
83
84 /**
85 * 0 => not ordered, 1 => first position, 2 => second position...
86 * A not order type would appear in first position (should never happened)
87 * @var integer
88 */
89 private $_sortorder;
90
67233725 91 /**
f48fb4d6 92 * Return if the instance is visible in a context
67233725
DC
93 *
94 * @todo check if the context visibility has been overwritten by the plugin creator
f48fb4d6 95 * (need to create special functions to be overvwritten in repository class)
67233725
DC
96 * @param stdClass $context context
97 * @return bool
f48fb4d6 98 */
5363905a
DC
99 public function get_contextvisibility($context) {
100 global $USER;
dbc01944 101
5363905a 102 if ($context->contextlevel == CONTEXT_COURSE) {
f48fb4d6 103 return $this->_options['enablecourseinstances'];
104 }
105
5363905a 106 if ($context->contextlevel == CONTEXT_USER) {
f48fb4d6 107 return $this->_options['enableuserinstances'];
108 }
109
110 //the context is SITE
111 return true;
112 }
dbc01944 113
f48fb4d6 114
115
a6600395 116 /**
117 * repository_type constructor
67233725
DC
118 *
119 * @param int $typename
a6600395 120 * @param array $typeoptions
67233725
DC
121 * @param bool $visible
122 * @param int $sortorder (don't really need set, it will be during create() call)
a6600395 123 */
a642bf6f 124 public function __construct($typename = '', $typeoptions = array(), $visible = true, $sortorder = 0) {
a6600395 125 global $CFG;
126
127 //set type attributs
128 $this->_typename = $typename;
129 $this->_visible = $visible;
130 $this->_sortorder = $sortorder;
46dd6bb0 131
a6600395 132 //set options attribut
133 $this->_options = array();
a5adfa26 134 $options = repository::static_function($typename, 'get_type_option_names');
a6600395 135 //check that the type can be setup
06e65e1e 136 if (!empty($options)) {
a6600395 137 //set the type options
138 foreach ($options as $config) {
a5adfa26 139 if (array_key_exists($config, $typeoptions)) {
7a3b93c1 140 $this->_options[$config] = $typeoptions[$config];
a6600395 141 }
142 }
143 }
f48fb4d6 144
145 //retrieve visibility from option
146 if (array_key_exists('enablecourseinstances',$typeoptions)) {
147 $this->_options['enablecourseinstances'] = $typeoptions['enablecourseinstances'];
9f7c761a 148 } else {
149 $this->_options['enablecourseinstances'] = 0;
f48fb4d6 150 }
dbc01944 151
f48fb4d6 152 if (array_key_exists('enableuserinstances',$typeoptions)) {
153 $this->_options['enableuserinstances'] = $typeoptions['enableuserinstances'];
9f7c761a 154 } else {
155 $this->_options['enableuserinstances'] = 0;
f48fb4d6 156 }
dbc01944 157
a6600395 158 }
159
160 /**
161 * Get the type name (no whitespace)
162 * For a human readable name, use get_readablename()
67233725
DC
163 *
164 * @return string the type name
a6600395 165 */
7a3b93c1 166 public function get_typename() {
a6600395 167 return $this->_typename;
168 }
169
170 /**
171 * Return a human readable and user-friendly type name
67233725 172 *
a6600395 173 * @return string user-friendly type name
174 */
7a3b93c1 175 public function get_readablename() {
614d18d2 176 return get_string('pluginname','repository_'.$this->_typename);
a6600395 177 }
178
179 /**
180 * Return general options
67233725 181 *
a6600395 182 * @return array the general options
183 */
7a3b93c1 184 public function get_options() {
a6600395 185 return $this->_options;
186 }
187
188 /**
189 * Return visibility
67233725
DC
190 *
191 * @return bool
a6600395 192 */
7a3b93c1 193 public function get_visible() {
a6600395 194 return $this->_visible;
195 }
196
197 /**
198 * Return order / position of display in the file picker
67233725
DC
199 *
200 * @return int
a6600395 201 */
7a3b93c1 202 public function get_sortorder() {
a6600395 203 return $this->_sortorder;
204 }
205
206 /**
207 * Create a repository type (the type name must not already exist)
67233725 208 * @param bool $silent throw exception?
a75c78d3 209 * @return mixed return int if create successfully, return false if
a6600395 210 */
a75c78d3 211 public function create($silent = false) {
a6600395 212 global $DB;
213
214 //check that $type has been set
215 $timmedtype = trim($this->_typename);
216 if (empty($timmedtype)) {
7a3b93c1 217 throw new repository_exception('emptytype', 'repository');
a6600395 218 }
219
220 //set sortorder as the last position in the list
7a3b93c1 221 if (!isset($this->_sortorder) || $this->_sortorder == 0 ) {
a6600395 222 $sql = "SELECT MAX(sortorder) FROM {repository}";
223 $this->_sortorder = 1 + $DB->get_field_sql($sql);
224 }
225
226 //only create a new type if it doesn't already exist
227 $existingtype = $DB->get_record('repository', array('type'=>$this->_typename));
7a3b93c1 228 if (!$existingtype) {
229 //create the type
6bdfef5d 230 $newtype = new stdClass();
7a3b93c1 231 $newtype->type = $this->_typename;
232 $newtype->visible = $this->_visible;
233 $newtype->sortorder = $this->_sortorder;
a75c78d3 234 $plugin_id = $DB->insert_record('repository', $newtype);
7a3b93c1 235 //save the options in DB
236 $this->update_options();
237
a5adfa26
DC
238 $instanceoptionnames = repository::static_function($this->_typename, 'get_instance_option_names');
239
edb50637 240 //if the plugin type has no multiple instance (e.g. has no instance option name) so it wont
7a3b93c1 241 //be possible for the administrator to create a instance
242 //in this case we need to create an instance
edb50637 243 if (empty($instanceoptionnames)) {
7a3b93c1 244 $instanceoptions = array();
a5adfa26
DC
245 if (empty($this->_options['pluginname'])) {
246 // when moodle trying to install some repo plugin automatically
247 // this option will be empty, get it from language string when display
248 $instanceoptions['name'] = '';
249 } else {
250 // when admin trying to add a plugin manually, he will type a name
251 // for it
252 $instanceoptions['name'] = $this->_options['pluginname'];
253 }
dbc01944 254 repository::static_function($this->_typename, 'create', $this->_typename, 0, get_system_context(), $instanceoptions);
7a3b93c1 255 }
60c366e8 256 //run plugin_init function
257 if (!repository::static_function($this->_typename, 'plugin_init')) {
258 if (!$silent) {
259 throw new repository_exception('cannotinitplugin', 'repository');
260 }
261 }
262
118ca9e9 263 cache::make('core', 'repositories')->purge();
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
118ca9e9 311 cache::make('core', 'repositories')->purge();
a6600395 312 return true;
313 }
314
315 /**
316 * Update visible database field with the value given as parameter
317 * or with the visible value of this object
318 * This function is private.
319 * For public access, have a look to switch_and_update_visibility()
67233725
DC
320 *
321 * @param bool $visible
322 * @return bool
a6600395 323 */
7a3b93c1 324 private function update_visible($visible = null) {
a6600395 325 global $DB;
326
7a3b93c1 327 if (!empty($visible)) {
a6600395 328 $this->_visible = $visible;
329 }
7a3b93c1 330 else if (!isset($this->_visible)) {
a6600395 331 throw new repository_exception('updateemptyvisible', 'repository');
332 }
333
118ca9e9 334 cache::make('core', 'repositories')->purge();
a6600395 335 return $DB->set_field('repository', 'visible', $this->_visible, array('type'=>$this->_typename));
336 }
337
338 /**
339 * Update database sortorder field with the value given as parameter
340 * or with the sortorder value of this object
341 * This function is private.
342 * For public access, have a look to move_order()
67233725
DC
343 *
344 * @param int $sortorder
345 * @return bool
a6600395 346 */
7a3b93c1 347 private function update_sortorder($sortorder = null) {
a6600395 348 global $DB;
349
7a3b93c1 350 if (!empty($sortorder) && $sortorder!=0) {
a6600395 351 $this->_sortorder = $sortorder;
352 }
353 //if sortorder is not set, we set it as the ;ast position in the list
7a3b93c1 354 else if (!isset($this->_sortorder) || $this->_sortorder == 0 ) {
a6600395 355 $sql = "SELECT MAX(sortorder) FROM {repository}";
356 $this->_sortorder = 1 + $DB->get_field_sql($sql);
357 }
358
118ca9e9 359 cache::make('core', 'repositories')->purge();
a6600395 360 return $DB->set_field('repository', 'sortorder', $this->_sortorder, array('type'=>$this->_typename));
361 }
362
363 /**
364 * Change order of the type with its adjacent upper or downer type
365 * (database fields are updated)
366 * Algorithm details:
367 * 1. retrieve all types in an array. This array is sorted by sortorder,
368 * and the array keys start from 0 to X (incremented by 1)
369 * 2. switch sortorder values of this type and its adjacent type
67233725 370 *
a6600395 371 * @param string $move "up" or "down"
372 */
373 public function move_order($move) {
374 global $DB;
a6600395 375
dbc01944 376 $types = repository::get_types(); // retrieve all types
7a3b93c1 377
67233725 378 // retrieve this type into the returned array
7a3b93c1 379 $i = 0;
380 while (!isset($indice) && $i<count($types)) {
381 if ($types[$i]->get_typename() == $this->_typename) {
a6600395 382 $indice = $i;
383 }
384 $i++;
385 }
386
67233725 387 // retrieve adjacent indice
a6600395 388 switch ($move) {
389 case "up":
390 $adjacentindice = $indice - 1;
7a3b93c1 391 break;
a6600395 392 case "down":
393 $adjacentindice = $indice + 1;
7a3b93c1 394 break;
a6600395 395 default:
7a3b93c1 396 throw new repository_exception('movenotdefined', 'repository');
a6600395 397 }
398
399 //switch sortorder of this type and the adjacent type
400 //TODO: we could reset sortorder for all types. This is not as good in performance term, but
401 //that prevent from wrong behaviour on a screwed database. As performance are not important in this particular case
402 //it worth to change the algo.
7a3b93c1 403 if ($adjacentindice>=0 && !empty($types[$adjacentindice])) {
a6600395 404 $DB->set_field('repository', 'sortorder', $this->_sortorder, array('type'=>$types[$adjacentindice]->get_typename()));
405 $this->update_sortorder($types[$adjacentindice]->get_sortorder());
406 }
407 }
408
409 /**
79698344 410 * 1. Change visibility to the value chosen
a6600395 411 * 2. Update the type
67233725
DC
412 *
413 * @param bool $visible
414 * @return bool
a6600395 415 */
79698344
MD
416 public function update_visibility($visible = null) {
417 if (is_bool($visible)) {
418 $this->_visible = $visible;
419 } else {
420 $this->_visible = !$this->_visible;
421 }
a6600395 422 return $this->update_visible();
423 }
424
425
426 /**
eb239694 427 * Delete a repository_type (general options are removed from config_plugin
428 * table, and all instances are deleted)
67233725
DC
429 *
430 * @param bool $downloadcontents download external contents if exist
431 * @return bool
a6600395 432 */
67233725 433 public function delete($downloadcontents = false) {
a6600395 434 global $DB;
46dd6bb0 435
436 //delete all instances of this type
6f2cd52a
DC
437 $params = array();
438 $params['context'] = array();
439 $params['onlyvisible'] = false;
440 $params['type'] = $this->_typename;
441 $instances = repository::get_instances($params);
7a3b93c1 442 foreach ($instances as $instance) {
67233725 443 $instance->delete($downloadcontents);
46dd6bb0 444 }
445
eb239694 446 //delete all general options
7a3b93c1 447 foreach ($this->_options as $name => $value) {
eb239694 448 set_config($name, null, $this->_typename);
449 }
450
118ca9e9 451 cache::make('core', 'repositories')->purge();
67233725
DC
452 try {
453 $DB->delete_records('repository', array('type' => $this->_typename));
454 } catch (dml_exception $ex) {
455 return false;
456 }
457 return true;
a6600395 458 }
118ca9e9
MG
459
460 /**
461 * Prepares the repository type to be cached. Implements method from cacheable_object interface.
462 *
463 * @return array
464 */
465 public function prepare_to_cache() {
466 return array(
467 'typename' => $this->_typename,
468 'typeoptions' => $this->_options,
469 'visible' => $this->_visible,
470 'sortorder' => $this->_sortorder
471 );
472 }
473
474 /**
475 * Restores repository type from cache. Implements method from cacheable_object interface.
476 *
477 * @return array
478 */
479 public static function wake_from_cache($data) {
480 return new repository_type($data['typename'], $data['typeoptions'], $data['visible'], $data['sortorder']);
481 }
a6600395 482}
483
a6600395 484/**
67233725 485 * This is the base class of the repository class.
8d419e59 486 *
67233725
DC
487 * To create repository plugin, see: {@link http://docs.moodle.org/dev/Repository_plugins}
488 * See an example: {@link repository_boxnet}
8d419e59 489 *
72a56555 490 * @package core_repository
67233725 491 * @copyright 2009 Dongsheng Cai {@link http://dongsheng.org}
6f2cd52a 492 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
a6600395 493 */
118ca9e9 494abstract class repository implements cacheable_object {
72a56555
MG
495 /** Timeout in seconds for downloading the external file into moodle */
496 const GETFILE_TIMEOUT = 30;
497 /** Timeout in seconds for syncronising the external file size */
498 const SYNCFILE_TIMEOUT = 1;
499 /** Timeout in seconds for downloading an image file from external repository during syncronisation */
500 const SYNCIMAGE_TIMEOUT = 3;
501
efe018b4 502 // $disabled can be set to true to disable a plugin by force
503 // example: self::$disabled = true
67233725 504 /** @var bool force disable repository instance */
efe018b4 505 public $disabled = false;
67233725 506 /** @var int repository instance id */
4a65c39a 507 public $id;
67233725 508 /** @var stdClass current context */
4a65c39a 509 public $context;
67233725 510 /** @var array repository options */
4a65c39a 511 public $options;
67233725 512 /** @var bool Whether or not the repository instance is editable */
948c2860 513 public $readonly;
67233725 514 /** @var int return types */
41076c58 515 public $returntypes;
67233725 516 /** @var stdClass repository instance database record */
a5adfa26 517 public $instance;
31581ae6
FM
518 /** @var string Type of repository (webdav, google_docs, dropbox, ...). Read from $this->get_typename(). */
519 protected $typename;
520
a0ff4137 521 /**
67233725 522 * Constructor
a0ff4137 523 *
67233725
DC
524 * @param int $repositoryid repository instance id
525 * @param int|stdClass $context a context id or context object
e35194be 526 * @param array $options repository options
67233725 527 * @param int $readonly indicate this repo is readonly or not
a0ff4137 528 */
e35194be 529 public function __construct($repositoryid, $context = SYSCONTEXTID, $options = array(), $readonly = 0) {
a5adfa26 530 global $DB;
a0ff4137 531 $this->id = $repositoryid;
be85f7ab 532 if (is_object($context)) {
e35194be
DC
533 $this->context = $context;
534 } else {
d197ea43 535 $this->context = context::instance_by_id($context);
e35194be 536 }
118ca9e9
MG
537 $cache = cache::make('core', 'repositories');
538 if (($this->instance = $cache->get('i:'. $this->id)) === false) {
539 $this->instance = $DB->get_record_sql("SELECT i.*, r.type AS repositorytype, r.sortorder, r.visible
540 FROM {repository} r, {repository_instances} i
541 WHERE i.typeid = r.id and i.id = ?", array('id' => $this->id));
542 $cache->set('i:'. $this->id, $this->instance);
543 }
a0ff4137
DC
544 $this->readonly = $readonly;
545 $this->options = array();
e35194be 546
a0ff4137 547 if (is_array($options)) {
67233725 548 // The get_option() method will get stored options in database.
a0ff4137
DC
549 $options = array_merge($this->get_option(), $options);
550 } else {
551 $options = $this->get_option();
552 }
553 foreach ($options as $n => $v) {
554 $this->options[$n] = $v;
555 }
556 $this->name = $this->get_name();
557 $this->returntypes = $this->supported_returntypes();
558 $this->super_called = true;
559 }
1cf56396 560
67233725
DC
561 /**
562 * Get repository instance using repository id
563 *
cfb71351
MG
564 * Note that this function does not check permission to access repository contents
565 *
566 * @throws repository_exception
567 *
568 * @param int $repositoryid repository instance ID
569 * @param context|int $context context instance or context ID where this repository will be used
6dc82385 570 * @param array $options additional repository options
67233725
DC
571 * @return repository
572 */
6dc82385 573 public static function get_repository_by_id($repositoryid, $context, $options = array()) {
67233725 574 global $CFG, $DB;
118ca9e9 575 $cache = cache::make('core', 'repositories');
cfb71351
MG
576 if (!is_object($context)) {
577 $context = context::instance_by_id($context);
578 }
118ca9e9
MG
579 $cachekey = 'rep:'. $repositoryid. ':'. $context->id. ':'. serialize($options);
580 if ($repository = $cache->get($cachekey)) {
581 return $repository;
582 }
67233725 583
118ca9e9
MG
584 if (!$record = $cache->get('i:'. $repositoryid)) {
585 $sql = "SELECT i.*, r.type AS repositorytype, r.visible, r.sortorder
586 FROM {repository_instances} i
587 JOIN {repository} r ON r.id = i.typeid
588 WHERE i.id = ?";
589 if (!$record = $DB->get_record_sql($sql, array($repositoryid))) {
590 throw new repository_exception('invalidrepositoryid', 'repository');
591 }
592 $cache->set('i:'. $record->id, $record);
593 }
67233725 594
118ca9e9
MG
595 $type = $record->repositorytype;
596 if (file_exists($CFG->dirroot . "/repository/$type/lib.php")) {
597 require_once($CFG->dirroot . "/repository/$type/lib.php");
598 $classname = 'repository_' . $type;
599 $options['type'] = $type;
600 $options['typeid'] = $record->typeid;
601 $options['visible'] = $record->visible;
602 if (empty($options['name'])) {
603 $options['name'] = $record->name;
604 }
605 $repository = new $classname($repositoryid, $context, $options, $record->readonly);
606 if (empty($repository->super_called)) {
607 // to make sure the super construct is called
608 debugging('parent::__construct must be called by '.$type.' plugin.');
67233725 609 }
118ca9e9
MG
610 $cache->set($cachekey, $repository);
611 return $repository;
612 } else {
613 throw new repository_exception('invalidplugin', 'repository');
67233725
DC
614 }
615 }
616
31581ae6
FM
617 /**
618 * Returns the type name of the repository.
619 *
620 * @return string type name of the repository.
621 * @since 2.5
622 */
623 public function get_typename() {
624 if (empty($this->typename)) {
625 $matches = array();
626 if (!preg_match("/^repository_(.*)$/", get_class($this), $matches)) {
627 throw new coding_exception('The class name of a repository should be repository_<typeofrepository>, '.
628 'e.g. repository_dropbox');
629 }
630 $this->typename = $matches[1];
631 }
632 return $this->typename;
633 }
634
dbc01944 635 /**
e35194be 636 * Get a repository type object by a given type name.
67233725
DC
637 *
638 * @static
e35194be
DC
639 * @param string $typename the repository type name
640 * @return repository_type|bool
dbc01944 641 */
642 public static function get_type_by_typename($typename) {
643 global $DB;
118ca9e9
MG
644 $cache = cache::make('core', 'repositories');
645 if (($repositorytype = $cache->get('typename:'. $typename)) === false) {
646 $repositorytype = null;
647 if ($record = $DB->get_record('repository', array('type' => $typename))) {
648 $repositorytype = new repository_type($record->type, (array)get_config($record->type), $record->visible, $record->sortorder);
649 $cache->set('typeid:'. $record->id, $repositorytype);
650 }
651 $cache->set('typename:'. $typename, $repositorytype);
dbc01944 652 }
118ca9e9 653 return $repositorytype;
dbc01944 654 }
655
656 /**
e35194be 657 * Get the repository type by a given repository type id.
67233725
DC
658 *
659 * @static
8e0946bf
DC
660 * @param int $id the type id
661 * @return object
dbc01944 662 */
663 public static function get_type_by_id($id) {
664 global $DB;
118ca9e9
MG
665 $cache = cache::make('core', 'repositories');
666 if (($repositorytype = $cache->get('typeid:'. $id)) === false) {
667 $repositorytype = null;
668 if ($record = $DB->get_record('repository', array('id' => $id))) {
669 $repositorytype = new repository_type($record->type, (array)get_config($record->type), $record->visible, $record->sortorder);
670 $cache->set('typename:'. $record->type, $repositorytype);
671 }
672 $cache->set('typeid:'. $id, $repositorytype);
dbc01944 673 }
118ca9e9 674 return $repositorytype;
dbc01944 675 }
676
677 /**
e35194be
DC
678 * Return all repository types ordered by sortorder field
679 * first repository type in returnedarray[0], second repository type in returnedarray[1], ...
67233725
DC
680 *
681 * @static
682 * @param bool $visible can return types by visiblity, return all types if null
dbc01944 683 * @return array Repository types
684 */
685 public static function get_types($visible=null) {
489d8a75 686 global $DB, $CFG;
118ca9e9
MG
687 $cache = cache::make('core', 'repositories');
688 if (!$visible) {
689 $typesnames = $cache->get('types');
690 } else {
691 $typesnames = $cache->get('typesvis');
dbc01944 692 }
118ca9e9
MG
693 $types = array();
694 if ($typesnames === false) {
695 $typesnames = array();
696 $vistypesnames = array();
697 if ($records = $DB->get_records('repository', null ,'sortorder')) {
698 foreach($records as $type) {
699 if (($repositorytype = $cache->get('typename:'. $type->type)) === false) {
700 // Create new instance of repository_type.
701 if (file_exists($CFG->dirroot . '/repository/'. $type->type .'/lib.php')) {
702 $repositorytype = new repository_type($type->type, (array)get_config($type->type), $type->visible, $type->sortorder);
703 $cache->set('typeid:'. $type->id, $repositorytype);
704 $cache->set('typename:'. $type->type, $repositorytype);
705 }
706 }
707 if ($repositorytype) {
708 if (empty($visible) || $repositorytype->get_visible()) {
709 $types[] = $repositorytype;
710 $vistypesnames[] = $repositorytype->get_typename();
711 }
712 $typesnames[] = $repositorytype->get_typename();
713 }
489d8a75 714 }
dbc01944 715 }
118ca9e9
MG
716 $cache->set('types', $typesnames);
717 $cache->set('typesvis', $vistypesnames);
718 } else {
719 foreach ($typesnames as $typename) {
720 $types[] = self::get_type_by_typename($typename);
721 }
dbc01944 722 }
dbc01944 723 return $types;
724 }
725
726 /**
31581ae6 727 * Checks if user has a capability to view the current repository.
67233725 728 *
31581ae6
FM
729 * @return bool true when the user can, otherwise throws an exception.
730 * @throws repository_exception when the user does not meet the requirements.
dbc01944 731 */
6dc82385 732 public final function check_capability() {
31581ae6
FM
733 global $USER;
734
e42861d4
FM
735 // The context we are on.
736 $currentcontext = $this->context;
737
31581ae6 738 // Ensure that the user can view the repository in the current context.
e42861d4 739 $can = has_capability('repository/'.$this->get_typename().':view', $currentcontext);
31581ae6
FM
740
741 // Context in which the repository has been created.
742 $repocontext = context::instance_by_id($this->instance->contextid);
743
744 // Prevent access to private repositories when logged in as.
745 if ($can && session_is_loggedinas()) {
746 if ($this->contains_private_data() || $repocontext->contextlevel == CONTEXT_USER) {
747 $can = false;
748 }
6dc82385 749 }
31581ae6 750
e42861d4
FM
751 // We are going to ensure that the current context was legit, and reliable to check
752 // the capability against. (No need to do that if we already cannot).
31581ae6 753 if ($can) {
e42861d4
FM
754 if ($repocontext->contextlevel == CONTEXT_USER) {
755 // The repository is a user instance, ensure we're the right user to access it!
756 if ($repocontext->instanceid != $USER->id) {
757 $can = false;
758 }
759 } else if ($repocontext->contextlevel == CONTEXT_COURSE) {
760 // The repository is a course one. Let's check that we are on the right course.
761 if (in_array($currentcontext->contextlevel, array(CONTEXT_COURSE, CONTEXT_MODULE, CONTEXT_BLOCK))) {
762 $coursecontext = $currentcontext->get_course_context();
763 if ($coursecontext->instanceid != $repocontext->instanceid) {
764 $can = false;
765 }
766 } else {
767 // We are on a parent context, therefore it's legit to check the permissions
768 // in the current context.
769 }
31581ae6 770 } else {
e42861d4
FM
771 // Nothing to check here, system instances can have different permissions on different
772 // levels. We do not want to prevent URL hack here, because it does not make sense to
773 // prevent a user to access a repository in a context if it's accessible in another one.
31581ae6
FM
774 }
775 }
776
777 if ($can) {
778 return true;
dbc01944 779 }
31581ae6
FM
780
781 throw new repository_exception('nopermissiontoaccess', 'repository');
dbc01944 782 }
783
f392caba 784 /**
d7d69396 785 * Check if file already exists in draft area.
f392caba 786 *
67233725 787 * @static
d7d69396
FM
788 * @param int $itemid of the draft area.
789 * @param string $filepath path to the file.
790 * @param string $filename file name.
67233725 791 * @return bool
f392caba
DC
792 */
793 public static function draftfile_exists($itemid, $filepath, $filename) {
794 global $USER;
795 $fs = get_file_storage();
21c08c63 796 $usercontext = context_user::instance($USER->id);
d7d69396 797 return $fs->file_exists($usercontext->id, 'user', 'draft', $itemid, $filepath, $filename);
f392caba
DC
798 }
799
c0e8f211
MG
800 /**
801 * Parses the 'source' returned by moodle repositories and returns an instance of stored_file
802 *
803 * @param string $source
804 * @return stored_file|null
805 */
806 public static function get_moodle_file($source) {
1bd01747
MG
807 $params = file_storage::unpack_reference($source, true);
808 $fs = get_file_storage();
809 return $fs->get_file($params['contextid'], $params['component'], $params['filearea'],
810 $params['itemid'], $params['filepath'], $params['filename']);
811 }
812
813 /**
814 * Repository method to make sure that user can access particular file.
815 *
816 * This is checked when user tries to pick the file from repository to deal with
817 * potential parameter substitutions is request
818 *
819 * @param string $source
820 * @return bool whether the file is accessible by current user
821 */
822 public function file_is_accessible($source) {
823 if ($this->has_moodle_files()) {
824 try {
825 $params = file_storage::unpack_reference($source, true);
826 } catch (file_reference_exception $e) {
827 return false;
c0e8f211 828 }
1bd01747 829 $browser = get_file_browser();
6dc82385 830 $context = context::instance_by_id($params['contextid']);
1bd01747
MG
831 $file_info = $browser->get_file_info($context, $params['component'], $params['filearea'],
832 $params['itemid'], $params['filepath'], $params['filename']);
833 return !empty($file_info);
c0e8f211 834 }
1bd01747 835 return true;
c0e8f211
MG
836 }
837
f392caba 838 /**
1bd01747
MG
839 * This function is used to copy a moodle file to draft area.
840 *
841 * It DOES NOT check if the user is allowed to access this file because the actual file
842 * can be located in the area where user does not have access to but there is an alias
843 * to this file in the area where user CAN access it.
844 * {@link file_is_accessible} should be called for alias location before calling this function.
f392caba 845 *
1bd01747 846 * @param string $source The metainfo of file, it is base64 encoded php serialized data
2dfa16ef
MG
847 * @param stdClass|array $filerecord contains itemid, filepath, filename and optionally other
848 * attributes of the new file
849 * @param int $maxbytes maximum allowed size of file, -1 if unlimited. If size of file exceeds
850 * the limit, the file_exception is thrown.
68acd115
FM
851 * @param int $areamaxbytes the maximum size of the area. A file_exception is thrown if the
852 * new file will reach the limit.
1bd01747 853 * @return array The information about the created file
f392caba 854 */
68acd115 855 public function copy_to_area($source, $filerecord, $maxbytes = -1, $areamaxbytes = FILE_AREA_MAX_BYTES_UNLIMITED) {
2dfa16ef 856 global $USER;
67233725 857 $fs = get_file_storage();
f392caba
DC
858
859 if ($this->has_moodle_files() == false) {
67233725 860 throw new coding_exception('Only repository used to browse moodle files can use repository::copy_to_area()');
f392caba
DC
861 }
862
2dfa16ef
MG
863 $user_context = context_user::instance($USER->id);
864
865 $filerecord = (array)$filerecord;
866 // make sure the new file will be created in user draft area
867 $filerecord['component'] = 'user';
868 $filerecord['filearea'] = 'draft';
869 $filerecord['contextid'] = $user_context->id;
870 $draftitemid = $filerecord['itemid'];
871 $new_filepath = $filerecord['filepath'];
872 $new_filename = $filerecord['filename'];
f392caba 873
f392caba 874 // the file needs to copied to draft area
1bd01747
MG
875 $stored_file = self::get_moodle_file($source);
876 if ($maxbytes != -1 && $stored_file->get_filesize() > $maxbytes) {
2dfa16ef
MG
877 throw new file_exception('maxbytes');
878 }
68acd115
FM
879 // Validate the size of the draft area.
880 if (file_is_draft_area_limit_reached($draftitemid, $areamaxbytes, $stored_file->get_filesize())) {
881 throw new file_exception('maxareabytes');
882 }
f392caba
DC
883
884 if (repository::draftfile_exists($draftitemid, $new_filepath, $new_filename)) {
885 // create new file
886 $unused_filename = repository::get_unused_filename($draftitemid, $new_filepath, $new_filename);
2dfa16ef 887 $filerecord['filename'] = $unused_filename;
1bd01747 888 $fs->create_file_from_storedfile($filerecord, $stored_file);
f392caba
DC
889 $event = array();
890 $event['event'] = 'fileexists';
891 $event['newfile'] = new stdClass;
892 $event['newfile']->filepath = $new_filepath;
893 $event['newfile']->filename = $unused_filename;
894 $event['newfile']->url = moodle_url::make_draftfile_url($draftitemid, $new_filepath, $unused_filename)->out();
895 $event['existingfile'] = new stdClass;
896 $event['existingfile']->filepath = $new_filepath;
897 $event['existingfile']->filename = $new_filename;
1bd01747 898 $event['existingfile']->url = moodle_url::make_draftfile_url($draftitemid, $new_filepath, $new_filename)->out();
f392caba
DC
899 return $event;
900 } else {
1bd01747 901 $fs->create_file_from_storedfile($filerecord, $stored_file);
f392caba
DC
902 $info = array();
903 $info['itemid'] = $draftitemid;
1bd01747
MG
904 $info['file'] = $new_filename;
905 $info['title'] = $new_filename;
f392caba 906 $info['contextid'] = $user_context->id;
1bd01747
MG
907 $info['url'] = moodle_url::make_draftfile_url($draftitemid, $new_filepath, $new_filename)->out();
908 $info['filesize'] = $stored_file->get_filesize();
f392caba
DC
909 return $info;
910 }
911 }
912
913 /**
d7d69396
FM
914 * Get an unused filename from the current draft area.
915 *
916 * Will check if the file ends with ([0-9]) and increase the number.
f392caba 917 *
67233725 918 * @static
d7d69396
FM
919 * @param int $itemid draft item ID.
920 * @param string $filepath path to the file.
921 * @param string $filename name of the file.
922 * @return string an unused file name.
f392caba
DC
923 */
924 public static function get_unused_filename($itemid, $filepath, $filename) {
925 global $USER;
d7d69396 926 $contextid = context_user::instance($USER->id)->id;
f392caba 927 $fs = get_file_storage();
d7d69396 928 return $fs->get_unused_filename($contextid, 'user', 'draft', $itemid, $filepath, $filename);
f392caba
DC
929 }
930
931 /**
d7d69396 932 * Append a suffix to filename.
f392caba 933 *
67233725 934 * @static
f392caba
DC
935 * @param string $filename
936 * @return string
d7d69396 937 * @deprecated since 2.5
f392caba 938 */
061eeed5 939 public static function append_suffix($filename) {
d7d69396
FM
940 debugging('The function repository::append_suffix() has been deprecated. Use repository::get_unused_filename() instead.',
941 DEBUG_DEVELOPER);
f392caba
DC
942 $pathinfo = pathinfo($filename);
943 if (empty($pathinfo['extension'])) {
944 return $filename . RENAME_SUFFIX;
945 } else {
946 return $pathinfo['filename'] . RENAME_SUFFIX . '.' . $pathinfo['extension'];
947 }
948 }
949
dbc01944 950 /**
951 * Return all types that you a user can create/edit and which are also visible
952 * Note: Mostly used in order to know if at least one editable type can be set
67233725
DC
953 *
954 * @static
955 * @param stdClass $context the context for which we want the editable types
dbc01944 956 * @return array types
957 */
958 public static function get_editable_types($context = null) {
959
960 if (empty($context)) {
961 $context = get_system_context();
962 }
963
964 $types= repository::get_types(true);
965 $editabletypes = array();
966 foreach ($types as $type) {
967 $instanceoptionnames = repository::static_function($type->get_typename(), 'get_instance_option_names');
968 if (!empty($instanceoptionnames)) {
5363905a 969 if ($type->get_contextvisibility($context)) {
dbc01944 970 $editabletypes[]=$type;
971 }
972 }
973 }
974 return $editabletypes;
975 }
976
977 /**
978 * Return repository instances
92a89068 979 *
67233725 980 * @static
92a89068 981 * @param array $args Array containing the following keys:
118ca9e9
MG
982 * currentcontext : instance of context (default system context)
983 * context : array of instances of context (default empty array)
984 * onlyvisible : bool (default true)
985 * type : string return instances of this type only
986 * accepted_types : string|array return instances that contain files of those types (*, web_image, .pdf, ...)
987 * return_types : int combination of FILE_INTERNAL & FILE_EXTERNAL & FILE_REFERENCE
988 * userid : int if specified, instances belonging to other users will not be returned
92a89068 989 *
dbc01944 990 * @return array repository instances
991 */
6f2cd52a 992 public static function get_instances($args = array()) {
dbc01944 993 global $DB, $CFG, $USER;
994
118ca9e9
MG
995 // Fill $args attributes with default values unless specified
996 if (!isset($args['currentcontext']) || !($args['currentcontext'] instanceof context)) {
997 $current_context = context_system::instance();
6f2cd52a 998 } else {
118ca9e9 999 $current_context = $args['currentcontext'];
6f2cd52a 1000 }
118ca9e9
MG
1001 $args['currentcontext'] = $current_context->id;
1002 $contextids = array();
6f2cd52a 1003 if (!empty($args['context'])) {
118ca9e9
MG
1004 foreach ($args['context'] as $context) {
1005 $contextids[] = $context->id;
1006 }
1007 }
1008 $args['context'] = $contextids;
1009 if (!isset($args['onlyvisible'])) {
1010 $args['onlyvisible'] = true;
1011 }
1012 if (!isset($args['return_types'])) {
1013 $args['return_types'] = 3;
1014 }
1015 if (!isset($args['type'])) {
1016 $args['type'] = null;
1017 }
1018 if (empty($args['disable_types']) || !is_array($args['disable_types'])) {
1019 $args['disable_types'] = null;
6f2cd52a 1020 }
118ca9e9
MG
1021 if (empty($args['userid']) || !is_numeric($args['userid'])) {
1022 $args['userid'] = null;
1023 }
1024 if (!isset($args['accepted_types']) || (is_array($args['accepted_types']) && in_array('*', $args['accepted_types']))) {
1025 $args['accepted_types'] = '*';
1026 }
1027 ksort($args);
1028 $cachekey = 'all:'. serialize($args);
6f2cd52a 1029
118ca9e9
MG
1030 // Check if we have cached list of repositories with the same query
1031 $cache = cache::make('core', 'repositories');
1032 if (($cachedrepositories = $cache->get($cachekey)) !== false) {
1033 // convert from cacheable_object_array to array
1034 $repositories = array();
1035 foreach ($cachedrepositories as $repository) {
1036 $repositories[$repository->id] = $repository;
1037 }
1038 return $repositories;
1039 }
6f2cd52a 1040
118ca9e9 1041 // Prepare DB SQL query to retrieve repositories
dbc01944 1042 $params = array();
a090554a
PS
1043 $sql = "SELECT i.*, r.type AS repositorytype, r.sortorder, r.visible
1044 FROM {repository} r, {repository_instances} i
1045 WHERE i.typeid = r.id ";
dbc01944 1046
118ca9e9
MG
1047 if ($args['disable_types']) {
1048 list($types, $p) = $DB->get_in_or_equal($args['disable_types'], SQL_PARAMS_NAMED, 'distype', false);
a090554a 1049 $sql .= " AND r.type $types";
227dfa43
DC
1050 $params = array_merge($params, $p);
1051 }
1052
118ca9e9
MG
1053 if ($args['userid']) {
1054 $sql .= " AND (i.userid = 0 or i.userid = :userid)";
1055 $params['userid'] = $args['userid'];
dbc01944 1056 }
227dfa43 1057
118ca9e9
MG
1058 if ($args['context']) {
1059 list($ctxsql, $p2) = $DB->get_in_or_equal($args['context'], SQL_PARAMS_NAMED, 'ctx');
1060 $sql .= " AND i.contextid $ctxsql";
1061 $params = array_merge($params, $p2);
dbc01944 1062 }
1063
118ca9e9
MG
1064 if ($args['onlyvisible'] == true) {
1065 $sql .= " AND r.visible = 1";
dbc01944 1066 }
1067
118ca9e9
MG
1068 if ($args['type'] !== null) {
1069 $sql .= " AND r.type = :type";
1070 $params['type'] = $args['type'];
dbc01944 1071 }
a090554a 1072 $sql .= " ORDER BY r.sortorder, i.name";
50a5cf09 1073
6f2cd52a
DC
1074 if (!$records = $DB->get_records_sql($sql, $params)) {
1075 $records = array();
dbc01944 1076 }
1077
6f2cd52a 1078 $repositories = array();
fdb0322d
DS
1079 // Sortorder should be unique, which is not true if we use $record->sortorder
1080 // and there are multiple instances of any repository type
1081 $sortorder = 1;
6f2cd52a 1082 foreach ($records as $record) {
118ca9e9 1083 $cache->set('i:'. $record->id, $record);
e35194be 1084 if (!file_exists($CFG->dirroot . '/repository/'. $record->repositorytype.'/lib.php')) {
062d21cd
DC
1085 continue;
1086 }
118ca9e9 1087 $repository = self::get_repository_by_id($record->id, $current_context);
cfb71351 1088 $repository->options['sortorder'] = $sortorder++;
6f2cd52a 1089
014c1ca0 1090 $is_supported = true;
dbc01944 1091
118ca9e9
MG
1092 // check mimetypes
1093 if ($args['accepted_types'] !== '*' and $repository->supported_filetypes() !== '*') {
1094 $accepted_ext = file_get_typegroup('extension', $args['accepted_types']);
1095 $supported_ext = file_get_typegroup('extension', $repository->supported_filetypes());
1096 $valid_ext = array_intersect($accepted_ext, $supported_ext);
1097 $is_supported = !empty($valid_ext);
1098 }
1099 // check return values
1100 if (!($repository->supported_returntypes() & $args['return_types'])) {
1101 $is_supported = false;
1102 }
d3959c26 1103
118ca9e9
MG
1104 if (!$args['onlyvisible'] || ($repository->is_visible() && !$repository->disabled)) {
1105 // check capability in current context
1106 $capability = has_capability('repository/'.$record->repositorytype.':view', $current_context);
1107 if ($record->repositorytype == 'coursefiles') {
1108 // coursefiles plugin needs managefiles permission
1109 $capability = $capability && has_capability('moodle/course:managefiles', $current_context);
1110 }
1111 if ($is_supported && $capability) {
1112 $repositories[$repository->id] = $repository;
014c1ca0 1113 }
dbc01944 1114 }
1115 }
118ca9e9 1116 $cache->set($cachekey, new cacheable_object_array($repositories));
6f2cd52a 1117 return $repositories;
dbc01944 1118 }
1119
1120 /**
cfb71351
MG
1121 * Get single repository instance for administrative actions
1122 *
1123 * Do not use this function to access repository contents, because it
1124 * does not set the current context
1125 *
1126 * @see rpository::get_repository_by_id()
67233725
DC
1127 *
1128 * @static
cfb71351
MG
1129 * @param integer $id repository instance id
1130 * @return repository
dbc01944 1131 */
1132 public static function get_instance($id) {
cfb71351 1133 return self::get_repository_by_id($id, context_system::instance());
dbc01944 1134 }
1135
1136 /**
e35194be 1137 * Call a static function. Any additional arguments than plugin and function will be passed through.
67233725
DC
1138 *
1139 * @static
1140 * @param string $plugin repository plugin name
1141 * @param string $function funciton name
2b8beee3 1142 * @return mixed
dbc01944 1143 */
1144 public static function static_function($plugin, $function) {
1145 global $CFG;
1146
1147 //check that the plugin exists
e35194be 1148 $typedirectory = $CFG->dirroot . '/repository/'. $plugin . '/lib.php';
dbc01944 1149 if (!file_exists($typedirectory)) {
f1cfe56e 1150 //throw new repository_exception('invalidplugin', 'repository');
1151 return false;
dbc01944 1152 }
1153
1154 $pname = null;
1155 if (is_object($plugin) || is_array($plugin)) {
1156 $plugin = (object)$plugin;
1157 $pname = $plugin->name;
1158 } else {
1159 $pname = $plugin;
1160 }
1161
1162 $args = func_get_args();
1163 if (count($args) <= 2) {
1164 $args = array();
e35194be 1165 } else {
dbc01944 1166 array_shift($args);
1167 array_shift($args);
1168 }
1169
1170 require_once($typedirectory);
81bdfdb9 1171 return call_user_func_array(array('repository_' . $plugin, $function), $args);
dbc01944 1172 }
1173
23bfe0a4
PS
1174 /**
1175 * Scan file, throws exception in case of infected file.
1176 *
1177 * Please note that the scanning engine must be able to access the file,
1178 * permissions of the file are not modified here!
1179 *
1180 * @static
1181 * @param string $thefile
1182 * @param string $filename name of the file
1183 * @param bool $deleteinfected
23bfe0a4
PS
1184 */
1185 public static function antivir_scan_file($thefile, $filename, $deleteinfected) {
1186 global $CFG;
1187
1188 if (!is_readable($thefile)) {
1189 // this should not happen
1190 return;
1191 }
1192
1193 if (empty($CFG->runclamonupload) or empty($CFG->pathtoclam)) {
1194 // clam not enabled
1195 return;
1196 }
1197
1198 $CFG->pathtoclam = trim($CFG->pathtoclam);
1199
1200 if (!file_exists($CFG->pathtoclam) or !is_executable($CFG->pathtoclam)) {
1201 // misconfigured clam - use the old notification for now
1202 require("$CFG->libdir/uploadlib.php");
1203 $notice = get_string('clamlost', 'moodle', $CFG->pathtoclam);
1204 clam_message_admins($notice);
1205 return;
1206 }
1207
1208 // do NOT mess with permissions here, the calling party is responsible for making
1209 // sure the scanner engine can access the files!
1210
1211 // execute test
1212 $cmd = escapeshellcmd($CFG->pathtoclam).' --stdout '.escapeshellarg($thefile);
1213 exec($cmd, $output, $return);
1214
1215 if ($return == 0) {
1216 // perfect, no problem found
1217 return;
1218
1219 } else if ($return == 1) {
1220 // infection found
1221 if ($deleteinfected) {
1222 unlink($thefile);
1223 }
1224 throw new moodle_exception('virusfounduser', 'moodle', '', array('filename'=>$filename));
1225
1226 } else {
1227 //unknown problem
1228 require("$CFG->libdir/uploadlib.php");
1229 $notice = get_string('clamfailed', 'moodle', get_clam_error_code($return));
1230 $notice .= "\n\n". implode("\n", $output);
1231 clam_message_admins($notice);
1232 if ($CFG->clamfailureonupload === 'actlikevirus') {
1233 if ($deleteinfected) {
1234 unlink($thefile);
1235 }
1236 throw new moodle_exception('virusfounduser', 'moodle', '', array('filename'=>$filename));
1237 } else {
1238 return;
1239 }
1240 }
1241 }
1242
67233725 1243 /**
0b2bfbd1 1244 * Repository method to serve the referenced file
67233725 1245 *
0b2bfbd1
MG
1246 * @see send_stored_file
1247 *
1248 * @param stored_file $storedfile the file that contains the reference
67233725
DC
1249 * @param int $lifetime Number of seconds before the file should expire from caches (default 24 hours)
1250 * @param int $filter 0 (default)=no filtering, 1=all files, 2=html files only
1251 * @param bool $forcedownload If true (default false), forces download of file rather than view in browser/plugin
1252 * @param array $options additional options affecting the file serving
1253 */
1254 public function send_file($storedfile, $lifetime=86400 , $filter=0, $forcedownload=false, array $options = null) {
0b2bfbd1
MG
1255 if ($this->has_moodle_files()) {
1256 $fs = get_file_storage();
1257 $params = file_storage::unpack_reference($storedfile->get_reference(), true);
1258 $srcfile = null;
1259 if (is_array($params)) {
1260 $srcfile = $fs->get_file($params['contextid'], $params['component'], $params['filearea'],
1261 $params['itemid'], $params['filepath'], $params['filename']);
1262 }
1263 if (empty($options)) {
1264 $options = array();
1265 }
1266 if (!isset($options['filename'])) {
1267 $options['filename'] = $storedfile->get_filename();
1268 }
1269 if (!$srcfile) {
1270 send_file_not_found();
1271 } else {
1272 send_stored_file($srcfile, $lifetime, $filter, $forcedownload, $options);
1273 }
1274 } else {
1275 throw new coding_exception("Repository plugin must implement send_file() method.");
1276 }
67233725
DC
1277 }
1278
1279 /**
1280 * Return reference file life time
1281 *
1282 * @param string $ref
1283 * @return int
1284 */
1285 public function get_reference_file_lifetime($ref) {
1286 // One day
1287 return 60 * 60 * 24;
1288 }
1289
1290 /**
1291 * Decide whether or not the file should be synced
1292 *
1293 * @param stored_file $storedfile
1294 * @return bool
1295 */
1296 public function sync_individual_file(stored_file $storedfile) {
1297 return true;
1298 }
1299
1300 /**
1301 * Return human readable reference information
67233725 1302 *
59cb7598 1303 * @param string $reference value of DB field files_reference.reference
0b2bfbd1
MG
1304 * @param int $filestatus status of the file, 0 - ok, 666 - source missing
1305 * @return string
67233725 1306 */
0b2bfbd1
MG
1307 public function get_reference_details($reference, $filestatus = 0) {
1308 if ($this->has_moodle_files()) {
1309 $fileinfo = null;
1310 $params = file_storage::unpack_reference($reference, true);
1311 if (is_array($params)) {
5fbe2118 1312 $context = context::instance_by_id($params['contextid'], IGNORE_MISSING);
0b2bfbd1
MG
1313 if ($context) {
1314 $browser = get_file_browser();
1315 $fileinfo = $browser->get_file_info($context, $params['component'], $params['filearea'], $params['itemid'], $params['filepath'], $params['filename']);
1316 }
1317 }
1318 if (empty($fileinfo)) {
1319 if ($filestatus == 666) {
1320 if (is_siteadmin() || ($context && has_capability('moodle/course:managefiles', $context))) {
1321 return get_string('lostsource', 'repository',
1322 $params['contextid']. '/'. $params['component']. '/'. $params['filearea']. '/'. $params['itemid']. $params['filepath']. $params['filename']);
1323 } else {
1324 return get_string('lostsource', 'repository', '');
1325 }
1326 }
1327 return get_string('undisclosedsource', 'repository');
1328 } else {
1329 return $fileinfo->get_readable_fullname();
1330 }
1331 }
1332 return '';
67233725
DC
1333 }
1334
1335 /**
1336 * Cache file from external repository by reference
1337 * {@link repository::get_file_reference()}
1338 * {@link repository::get_file()}
1339 * Invoked at MOODLE/repository/repository_ajax.php
1340 *
1341 * @param string $reference this reference is generated by
1342 * repository::get_file_reference()
1343 * @param stored_file $storedfile created file reference
1344 */
6dd299be 1345 public function cache_file_by_reference($reference, $storedfile) {
67233725
DC
1346 }
1347
1348 /**
0b2bfbd1 1349 * Returns information about file in this repository by reference
67233725 1350 *
2d222a32
MG
1351 * This function must be implemented for repositories supporting FILE_REFERENCE, it is called
1352 * for existing aliases when the lifetime of the previous syncronisation has expired.
0b2bfbd1 1353 *
2d222a32
MG
1354 * Returns null if file not found or is not readable or timeout occured during request.
1355 * Note that this function may be run for EACH file that needs to be synchronised at the
1356 * moment. If anything is being downloaded or requested from external sources there
1357 * should be a small timeout. The synchronisation is performed to update the size of
1358 * the file and/or to update image and re-generated image preview. There is nothing
1359 * fatal if syncronisation fails but it is fatal if syncronisation takes too long
1360 * and hangs the script generating a page.
0b2bfbd1 1361 *
2d222a32
MG
1362 * If get_file_by_reference() returns filesize just the record in {files} table is being updated.
1363 * If filepath, handle or content are returned - the file is also stored in moodle filepool
1364 * (recommended for images to generate the thumbnails). For non-image files it is not
1365 * recommended to download them to moodle during syncronisation since it may take
1366 * unnecessary long time.
1367 *
1368 * @param stdClass $reference record from DB table {files_reference}
0b2bfbd1 1369 * @return stdClass|null contains one of the following:
2d222a32 1370 * - 'filesize' and optionally 'contenthash'
0b2bfbd1
MG
1371 * - 'filepath'
1372 * - 'handle'
1373 * - 'content'
67233725
DC
1374 */
1375 public function get_file_by_reference($reference) {
0b2bfbd1
MG
1376 if ($this->has_moodle_files() && isset($reference->reference)) {
1377 $fs = get_file_storage();
1378 $params = file_storage::unpack_reference($reference->reference, true);
1379 if (!is_array($params) || !($storedfile = $fs->get_file($params['contextid'],
1380 $params['component'], $params['filearea'], $params['itemid'], $params['filepath'],
1381 $params['filename']))) {
1382 return null;
1383 }
1384 return (object)array(
1385 'contenthash' => $storedfile->get_contenthash(),
1386 'filesize' => $storedfile->get_filesize()
1387 );
1388 }
67233725
DC
1389 return null;
1390 }
1391
d6453211
DC
1392 /**
1393 * Return the source information
1394 *
59cb7598
MG
1395 * The result of the function is stored in files.source field. It may be analysed
1396 * when the source file is lost or repository may use it to display human-readable
1397 * location of reference original.
1398 *
1399 * This method is called when file is picked for the first time only. When file
1400 * (either copy or a reference) is already in moodle and it is being picked
1401 * again to another file area (also as a copy or as a reference), the value of
1402 * files.source is copied.
1403 *
1404 * @param string $source the value that repository returned in listing as 'source'
d6453211
DC
1405 * @return string|null
1406 */
59cb7598 1407 public function get_file_source_info($source) {
83d2700e 1408 if ($this->has_moodle_files()) {
59cb7598 1409 return $this->get_reference_details($source, 0);
83d2700e 1410 }
59cb7598 1411 return $source;
d6453211
DC
1412 }
1413
dbc01944 1414 /**
1415 * Move file from download folder to file pool using FILE API
67233725
DC
1416 *
1417 * @todo MDL-28637
1418 * @static
8e0946bf 1419 * @param string $thefile file path in download folder
67233725 1420 * @param stdClass $record
1a6195b4
DC
1421 * @return array containing the following keys:
1422 * icon
1423 * file
1424 * id
1425 * url
dbc01944 1426 */
14469892 1427 public static function move_to_filepool($thefile, $record) {
390baf46 1428 global $DB, $CFG, $USER, $OUTPUT;
23bfe0a4
PS
1429
1430 // scan for viruses if possible, throws exception if problem found
1431 self::antivir_scan_file($thefile, $record->filename, empty($CFG->repository_no_delete)); //TODO: MDL-28637 this repository_no_delete is a bloody hack!
1432
dbc01944 1433 $fs = get_file_storage();
67233725
DC
1434 // If file name being used.
1435 if (repository::draftfile_exists($record->itemid, $record->filepath, $record->filename)) {
f392caba
DC
1436 $draftitemid = $record->itemid;
1437 $new_filename = repository::get_unused_filename($draftitemid, $record->filepath, $record->filename);
1438 $old_filename = $record->filename;
67233725 1439 // Create a tmp file.
f392caba
DC
1440 $record->filename = $new_filename;
1441 $newfile = $fs->create_file_from_pathname($record, $thefile);
1442 $event = array();
1443 $event['event'] = 'fileexists';
1444 $event['newfile'] = new stdClass;
1445 $event['newfile']->filepath = $record->filepath;
1446 $event['newfile']->filename = $new_filename;
1447 $event['newfile']->url = moodle_url::make_draftfile_url($draftitemid, $record->filepath, $new_filename)->out();
1448
1449 $event['existingfile'] = new stdClass;
1450 $event['existingfile']->filepath = $record->filepath;
1451 $event['existingfile']->filename = $old_filename;
0e35ba6f 1452 $event['existingfile']->url = moodle_url::make_draftfile_url($draftitemid, $record->filepath, $old_filename)->out();
f392caba 1453 return $event;
b423b4af 1454 }
14469892 1455 if ($file = $fs->create_file_from_pathname($record, $thefile)) {
88b126a5 1456 if (empty($CFG->repository_no_delete)) {
99eaca9d 1457 $delete = unlink($thefile);
88b126a5 1458 unset($CFG->repository_no_delete);
1459 }
64f93798 1460 return array(
50a8bd6c 1461 'url'=>moodle_url::make_draftfile_url($file->get_itemid(), $file->get_filepath(), $file->get_filename())->out(),
64f93798
PS
1462 'id'=>$file->get_itemid(),
1463 'file'=>$file->get_filename(),
1464 'icon' => $OUTPUT->pix_url(file_extension_icon($thefile, 32))->out(),
1465 );
dbc01944 1466 } else {
1467 return null;
1468 }
1469 }
1470
dbc01944 1471 /**
67233725 1472 * Builds a tree of files This function is then called recursively.
dbc01944 1473 *
67233725
DC
1474 * @static
1475 * @todo take $search into account, and respect a threshold for dynamic loading
1476 * @param file_info $fileinfo an object returned by file_browser::get_file_info()
1477 * @param string $search searched string
1478 * @param bool $dynamicmode no recursive call is done when in dynamic mode
1479 * @param array $list the array containing the files under the passed $fileinfo
72a56555 1480 * @return int the number of files found
dbc01944 1481 */
1482 public static function build_tree($fileinfo, $search, $dynamicmode, &$list) {
390baf46 1483 global $CFG, $OUTPUT;
dbc01944 1484
1485 $filecount = 0;
1486 $children = $fileinfo->get_children();
1487
1488 foreach ($children as $child) {
1489 $filename = $child->get_visible_name();
1490 $filesize = $child->get_filesize();
1491 $filesize = $filesize ? display_size($filesize) : '';
1492 $filedate = $child->get_timemodified();
1493 $filedate = $filedate ? userdate($filedate) : '';
1494 $filetype = $child->get_mimetype();
1495
1496 if ($child->is_directory()) {
1497 $path = array();
1498 $level = $child->get_parent();
1499 while ($level) {
1500 $params = $level->get_params();
64f93798 1501 $path[] = array($params['filepath'], $level->get_visible_name());
dbc01944 1502 $level = $level->get_parent();
1503 }
1504
1505 $tmp = array(
1506 'title' => $child->get_visible_name(),
1507 'size' => 0,
1508 'date' => $filedate,
1509 'path' => array_reverse($path),
559276b1 1510 'thumbnail' => $OUTPUT->pix_url(file_folder_icon(90))->out(false)
dbc01944 1511 );
1512
1513 //if ($dynamicmode && $child->is_writable()) {
1514 // $tmp['children'] = array();
1515 //} else {
1516 // if folder name matches search, we send back all files contained.
1517 $_search = $search;
1518 if ($search && stristr($tmp['title'], $search) !== false) {
1519 $_search = false;
1520 }
1521 $tmp['children'] = array();
1522 $_filecount = repository::build_tree($child, $_search, $dynamicmode, $tmp['children']);
1523 if ($search && $_filecount) {
1524 $tmp['expanded'] = 1;
1525 }
1526
1527 //}
1528
fc3ec2ca 1529 if (!$search || $_filecount || (stristr($tmp['title'], $search) !== false)) {
dbc01944 1530 $filecount += $_filecount;
1531 $list[] = $tmp;
1532 }
1533
1534 } else { // not a directory
1535 // skip the file, if we're in search mode and it's not a match
1536 if ($search && (stristr($filename, $search) === false)) {
1537 continue;
1538 }
1539 $params = $child->get_params();
64f93798 1540 $source = serialize(array($params['contextid'], $params['component'], $params['filearea'], $params['itemid'], $params['filepath'], $params['filename']));
dbc01944 1541 $list[] = array(
1542 'title' => $filename,
1543 'size' => $filesize,
1544 'date' => $filedate,
1545 //'source' => $child->get_url(),
1546 'source' => base64_encode($source),
559276b1
MG
1547 'icon'=>$OUTPUT->pix_url(file_file_icon($child, 24))->out(false),
1548 'thumbnail'=>$OUTPUT->pix_url(file_file_icon($child, 90))->out(false),
dbc01944 1549 );
1550 $filecount++;
1551 }
1552 }
1553
1554 return $filecount;
1555 }
1556
dbc01944 1557 /**
1558 * Display a repository instance list (with edit/delete/create links)
67233725
DC
1559 *
1560 * @static
1561 * @param stdClass $context the context for which we display the instance
dbc01944 1562 * @param string $typename if set, we display only one type of instance
1563 */
1564 public static function display_instances_list($context, $typename = null) {
50a5cf09 1565 global $CFG, $USER, $OUTPUT;
dbc01944 1566
50a5cf09 1567 $output = $OUTPUT->box_start('generalbox');
dbc01944 1568 //if the context is SYSTEM, so we call it from administration page
1569 $admin = ($context->id == SYSCONTEXTID) ? true : false;
1570 if ($admin) {
e35194be
DC
1571 $baseurl = new moodle_url('/'.$CFG->admin.'/repositoryinstance.php', array('sesskey'=>sesskey()));
1572 $output .= $OUTPUT->heading(get_string('siteinstances', 'repository'));
dbc01944 1573 } else {
e35194be 1574 $baseurl = new moodle_url('/repository/manage_instances.php', array('contextid'=>$context->id, 'sesskey'=>sesskey()));
dbc01944 1575 }
1576
1577 $namestr = get_string('name');
1578 $pluginstr = get_string('plugin', 'repository');
1579 $settingsstr = get_string('settings');
1580 $deletestr = get_string('delete');
89a9d21a
FM
1581 // Retrieve list of instances. In administration context we want to display all
1582 // instances of a type, even if this type is not visible. In course/user context we
1583 // want to display only visible instances, but for every type types. The repository::get_instances()
1584 // third parameter displays only visible type.
6f2cd52a 1585 $params = array();
89a9d21a 1586 $params['context'] = array($context);
6f2cd52a
DC
1587 $params['currentcontext'] = $context;
1588 $params['onlyvisible'] = !$admin;
1589 $params['type'] = $typename;
1590 $instances = repository::get_instances($params);
dbc01944 1591 $instancesnumber = count($instances);
1592 $alreadyplugins = array();
1593
55400db0 1594 $table = new html_table();
79698344 1595 $table->head = array($namestr, $pluginstr, $settingsstr, $deletestr);
dbc01944 1596 $table->align = array('left', 'left', 'center','center');
1597 $table->data = array();
1598
1599 $updowncount = 1;
1600
1601 foreach ($instances as $i) {
1602 $settings = '';
1603 $delete = '';
5363905a
DC
1604
1605 $type = repository::get_type_by_id($i->options['typeid']);
1606
1607 if ($type->get_contextvisibility($context)) {
1608 if (!$i->readonly) {
1609
67233725
DC
1610 $settingurl = new moodle_url($baseurl);
1611 $settingurl->param('type', $i->options['type']);
1612 $settingurl->param('edit', $i->id);
1613 $settings .= html_writer::link($settingurl, $settingsstr);
5363905a 1614
67233725
DC
1615 $deleteurl = new moodle_url($baseurl);
1616 $deleteurl->param('delete', $i->id);
1617 $deleteurl->param('type', $i->options['type']);
1618 $delete .= html_writer::link($deleteurl, $deletestr);
5363905a 1619 }
dbc01944 1620 }
1621
a3d8df25 1622 $type = repository::get_type_by_id($i->options['typeid']);
8655fb96 1623 $table->data[] = array(format_string($i->name), $type->get_readablename(), $settings, $delete);
dbc01944 1624
1625 //display a grey row if the type is defined as not visible
1626 if (isset($type) && !$type->get_visible()) {
704ac344 1627 $table->rowclasses[] = 'dimmed_text';
dbc01944 1628 } else {
704ac344 1629 $table->rowclasses[] = '';
dbc01944 1630 }
1631
1632 if (!in_array($i->name, $alreadyplugins)) {
1633 $alreadyplugins[] = $i->name;
1634 }
1635 }
16be8974 1636 $output .= html_writer::table($table);
dbc01944 1637 $instancehtml = '<div>';
1638 $addable = 0;
1639
1640 //if no type is set, we can create all type of instance
1641 if (!$typename) {
1642 $instancehtml .= '<h3>';
1643 $instancehtml .= get_string('createrepository', 'repository');
1644 $instancehtml .= '</h3><ul>';
1645 $types = repository::get_editable_types($context);
1646 foreach ($types as $type) {
1647 if (!empty($type) && $type->get_visible()) {
2c869550
FM
1648 // If the user does not have the permission to view the repository, it won't be displayed in
1649 // the list of instances. Hiding the link to create new instances will prevent the
1650 // user from creating them without being able to find them afterwards, which looks like a bug.
1651 if (!has_capability('repository/'.$type->get_typename().':view', $context)) {
1652 continue;
1653 }
dbc01944 1654 $instanceoptionnames = repository::static_function($type->get_typename(), 'get_instance_option_names');
1655 if (!empty($instanceoptionnames)) {
e35194be
DC
1656 $baseurl->param('new', $type->get_typename());
1657 $instancehtml .= '<li><a href="'.$baseurl->out().'">'.get_string('createxxinstance', 'repository', get_string('pluginname', 'repository_'.$type->get_typename())). '</a></li>';
1658 $baseurl->remove_params('new');
dbc01944 1659 $addable++;
1660 }
1661 }
1662 }
1663 $instancehtml .= '</ul>';
1664
1665 } else {
1666 $instanceoptionnames = repository::static_function($typename, 'get_instance_option_names');
1667 if (!empty($instanceoptionnames)) { //create a unique type of instance
1668 $addable = 1;
e35194be 1669 $baseurl->param('new', $typename);
67233725 1670 $output .= $OUTPUT->single_button($baseurl, get_string('createinstance', 'repository'), 'get');
e35194be 1671 $baseurl->remove_params('new');
dbc01944 1672 }
1673 }
1674
1675 if ($addable) {
1676 $instancehtml .= '</div>';
1677 $output .= $instancehtml;
1678 }
1679
50a5cf09 1680 $output .= $OUTPUT->box_end();
dbc01944 1681
1682 //print the list + creation links
1683 print($output);
1684 }
1cf56396 1685
67233725
DC
1686 /**
1687 * Prepare file reference information
1688 *
1689 * @param string $source
1690 * @return string file referece
1691 */
1692 public function get_file_reference($source) {
0b2bfbd1
MG
1693 if ($this->has_moodle_files() && ($this->supported_returntypes() & FILE_REFERENCE)) {
1694 $params = file_storage::unpack_reference($source);
1695 if (!is_array($params)) {
1696 throw new repository_exception('invalidparams', 'repository');
1697 }
1698 return file_storage::pack_reference($params);
1699 }
67233725
DC
1700 return $source;
1701 }
72a56555 1702
c425472d 1703 /**
e35194be 1704 * Decide where to save the file, can be overwriten by subclass
67233725
DC
1705 *
1706 * @param string $filename file name
1707 * @return file path
c425472d 1708 */
a560785f 1709 public function prepare_file($filename) {
c425472d 1710 global $CFG;
72a56555
MG
1711 $dir = make_temp_directory('download/'.get_class($this).'/');
1712 while (empty($filename) || file_exists($dir.$filename)) {
1713 $filename = uniqid('', true).'_'.time().'.tmp';
c425472d 1714 }
a560785f 1715 return $dir.$filename;
a53d4f45 1716 }
1717
67233725
DC
1718 /**
1719 * Does this repository used to browse moodle files?
1720 *
1721 * @return bool
1722 */
1723 public function has_moodle_files() {
1724 return false;
1725 }
1726
99d52655
DC
1727 /**
1728 * Return file URL, for most plugins, the parameter is the original
1729 * url, but some plugins use a file id, so we need this function to
1730 * convert file id to original url.
1731 *
1732 * @param string $url the url of file
8e0946bf 1733 * @return string
99d52655
DC
1734 */
1735 public function get_link($url) {
1736 return $url;
1737 }
1738
a53d4f45 1739 /**
72a56555 1740 * Downloads a file from external repository and saves it in temp dir
a53d4f45 1741 *
72a56555
MG
1742 * Function get_file() must be implemented by repositories that support returntypes
1743 * FILE_INTERNAL or FILE_REFERENCE. It is invoked to pick up the file and copy it
1744 * to moodle. This function is not called for moodle repositories, the function
1745 * {@link repository::copy_to_area()} is used instead.
1746 *
1747 * This function can be overridden by subclass if the files.reference field contains
1748 * not just URL or if request should be done differently.
1749 *
1750 * @see curl
1751 * @throws file_exception when error occured
1752 *
1753 * @param string $url the content of files.reference field, in this implementaion
1754 * it is asssumed that it contains the string with URL of the file
1755 * @param string $filename filename (without path) to save the downloaded file in the
1756 * temporary directory, if omitted or file already exists the new filename will be generated
0b2bfbd1
MG
1757 * @return array with elements:
1758 * path: internal location of the file
1759 * url: URL to the source (from parameters)
a53d4f45 1760 */
a560785f 1761 public function get_file($url, $filename = '') {
41076c58 1762 $path = $this->prepare_file($filename);
41076c58 1763 $c = new curl;
72a56555
MG
1764 $result = $c->download_one($url, null, array('filepath' => $path, 'timeout' => self::GETFILE_TIMEOUT));
1765 if ($result !== true) {
1766 throw new moodle_exception('errorwhiledownload', 'repository', '', $result);
0b2bfbd1 1767 }
1dce6261 1768 return array('path'=>$path, 'url'=>$url);
82669dc4 1769 }
1cf56396 1770
bc6f241c
MG
1771 /**
1772 * Downloads the file from external repository and saves it in moodle filepool.
1773 * This function is different from {@link repository::sync_external_file()} because it has
1774 * bigger request timeout and always downloads the content.
1775 *
1776 * This function is invoked when we try to unlink the file from the source and convert
1777 * a reference into a true copy.
1778 *
1779 * @throws exception when file could not be imported
1780 *
1781 * @param stored_file $file
1782 * @param int $maxbytes throw an exception if file size is bigger than $maxbytes (0 means no limit)
1783 */
1784 public function import_external_file_contents(stored_file $file, $maxbytes = 0) {
1785 if (!$file->is_external_file()) {
1786 // nothing to import if the file is not a reference
1787 return;
1788 } else if ($file->get_repository_id() != $this->id) {
1789 // error
1790 debugging('Repository instance id does not match');
1791 return;
1792 } else if ($this->has_moodle_files()) {
1793 // files that are references to local files are already in moodle filepool
1794 // just validate the size
1795 if ($maxbytes > 0 && $file->get_filesize() > $maxbytes) {
1796 throw new file_exception('maxbytes');
1797 }
1798 return;
1799 } else {
1800 if ($maxbytes > 0 && $file->get_filesize() > $maxbytes) {
1801 // note that stored_file::get_filesize() also calls synchronisation
1802 throw new file_exception('maxbytes');
1803 }
1804 $fs = get_file_storage();
1805 $contentexists = $fs->content_exists($file->get_contenthash());
1806 if ($contentexists && $file->get_filesize() && $file->get_contenthash() === sha1('')) {
1807 // even when 'file_storage::content_exists()' returns true this may be an empty
1808 // content for the file that was not actually downloaded
1809 $contentexists = false;
1810 }
1811 $now = time();
1812 if ($file->get_referencelastsync() + $file->get_referencelifetime() >= $now &&
1813 !$file->get_status() &&
1814 $contentexists) {
1815 // we already have the content in moodle filepool and it was synchronised recently.
1816 // Repositories may overwrite it if they want to force synchronisation anyway!
1817 return;
1818 } else {
1819 // attempt to get a file
1820 try {
1821 $fileinfo = $this->get_file($file->get_reference());
1822 if (isset($fileinfo['path'])) {
1823 list($contenthash, $filesize, $newfile) = $fs->add_file_to_pool($fileinfo['path']);
1824 // set this file and other similar aliases synchronised
1825 $lifetime = $this->get_reference_file_lifetime($file->get_reference());
1826 $file->set_synchronized($contenthash, $filesize, 0, $lifetime);
1827 } else {
1828 throw new moodle_exception('errorwhiledownload', 'repository', '', '');
1829 }
1830 } catch (Exception $e) {
1831 if ($contentexists) {
1832 // better something than nothing. We have a copy of file. It's sync time
1833 // has expired but it is still very likely that it is the last version
1834 } else {
1835 throw($e);
1836 }
1837 }
1838 }
1839 }
1840 }
1841
c0d60b3a
AKA
1842 /**
1843 * Return size of a file in bytes.
1844 *
1845 * @param string $source encoded and serialized data of file
67233725 1846 * @return int file size in bytes
c0d60b3a
AKA
1847 */
1848 public function get_file_size($source) {
2dfa16ef 1849 // TODO MDL-33297 remove this function completely?
c0d60b3a
AKA
1850 $browser = get_file_browser();
1851 $params = unserialize(base64_decode($source));
1852 $contextid = clean_param($params['contextid'], PARAM_INT);
1853 $fileitemid = clean_param($params['itemid'], PARAM_INT);
1854 $filename = clean_param($params['filename'], PARAM_FILE);
1855 $filepath = clean_param($params['filepath'], PARAM_PATH);
aff24313
PS
1856 $filearea = clean_param($params['filearea'], PARAM_AREA);
1857 $component = clean_param($params['component'], PARAM_COMPONENT);
d197ea43 1858 $context = context::instance_by_id($contextid);
c0d60b3a
AKA
1859 $file_info = $browser->get_file_info($context, $component, $filearea, $fileitemid, $filepath, $filename);
1860 if (!empty($file_info)) {
1861 $filesize = $file_info->get_filesize();
1862 } else {
1863 $filesize = null;
1864 }
1865 return $filesize;
1866 }
1867
f48fb4d6 1868 /**
1869 * Return is the instance is visible
1870 * (is the type visible ? is the context enable ?)
67233725
DC
1871 *
1872 * @return bool
f48fb4d6 1873 */
dbc01944 1874 public function is_visible() {
7d554b64 1875 $type = repository::get_type_by_id($this->options['typeid']);
dbc01944 1876 $instanceoptions = repository::static_function($type->get_typename(), 'get_instance_option_names');
f48fb4d6 1877
1878 if ($type->get_visible()) {
1879 //if the instance is unique so it's visible, otherwise check if the instance has a enabled context
5363905a 1880 if (empty($instanceoptions) || $type->get_contextvisibility($this->context)) {
f48fb4d6 1881 return true;
1882 }
1883 }
1884
1885 return false;
1886 }
1887
89a9d21a
FM
1888 /**
1889 * Can the instance be edited by the current user?
1890 *
1891 * The property $readonly must not be used within this method because
1892 * it only controls if the options from self::get_instance_option_names()
1893 * can be edited.
1894 *
1895 * @return bool true if the user can edit the instance.
1896 * @since 2.5
1897 */
1898 public final function can_be_edited_by_user() {
1899 global $USER;
1900
1901 // We need to be able to explore the repository.
1902 try {
1903 $this->check_capability();
1904 } catch (repository_exception $e) {
1905 return false;
1906 }
1907
1908 $repocontext = context::instance_by_id($this->instance->contextid);
1909 if ($repocontext->contextlevel == CONTEXT_USER && $repocontext->instanceid != $USER->id) {
1910 // If the context of this instance is a user context, we need to be this user.
1911 return false;
1912 } else if ($repocontext->contextlevel == CONTEXT_MODULE && !has_capability('moodle/course:update', $repocontext)) {
1913 // We need to have permissions on the course to edit the instance.
1914 return false;
1915 } else if ($repocontext->contextlevel == CONTEXT_SYSTEM && !has_capability('moodle/site:config', $repocontext)) {
1916 // Do not meet the requirements for the context system.
1917 return false;
1918 }
1919
1920 return true;
1921 }
1922
eb239694 1923 /**
66dc47bc 1924 * Return the name of this instance, can be overridden.
67233725 1925 *
2b8beee3 1926 * @return string
eb239694 1927 */
7a3b93c1 1928 public function get_name() {
31581ae6 1929 if ($name = $this->instance->name) {
a5adfa26 1930 return $name;
d31af46a 1931 } else {
31581ae6 1932 return get_string('pluginname', 'repository_' . $this->get_typename());
d31af46a 1933 }
1934 }
aa754fe3 1935
31581ae6
FM
1936 /**
1937 * Is this repository accessing private data?
1938 *
1939 * This function should return true for the repositories which access external private
1940 * data from a user. This is the case for repositories such as Dropbox, Google Docs or Box.net
1941 * which authenticate the user and then store the auth token.
1942 *
1943 * Of course, many repositories store 'private data', but we only want to set
1944 * contains_private_data() to repositories which are external to Moodle and shouldn't be accessed
1945 * to by the users having the capability to 'login as' someone else. For instance, the repository
1946 * 'Private files' is not considered as private because it's part of Moodle.
1947 *
1948 * You should not set contains_private_data() to true on repositories which allow different types
1949 * of instances as the levels other than 'user' are, by definition, not private. Also
1950 * the user instances will be protected when they need to.
1951 *
1952 * @return boolean True when the repository accesses private external data.
1953 * @since 2.5
1954 */
1955 public function contains_private_data() {
1956 return true;
1957 }
1958
b318bb6d 1959 /**
67233725
DC
1960 * What kind of files will be in this repository?
1961 *
b318bb6d 1962 * @return array return '*' means this repository support any files, otherwise
1963 * return mimetypes of files, it can be an array
1964 */
014c1ca0 1965 public function supported_filetypes() {
b318bb6d 1966 // return array('text/plain', 'image/gif');
1967 return '*';
1968 }
1969
1970 /**
c8161eec 1971 * Tells how the file can be picked from this repository
67233725 1972 *
c8161eec
MG
1973 * Maximum value is FILE_INTERNAL | FILE_EXTERNAL | FILE_REFERENCE
1974 *
1975 * @return int
b318bb6d 1976 */
41076c58 1977 public function supported_returntypes() {
c8161eec 1978 return (FILE_INTERNAL | FILE_EXTERNAL);
92eaeca5 1979 }
b318bb6d 1980
82669dc4 1981 /**
3f24ea1e 1982 * Provide repository instance information for Ajax
67233725
DC
1983 *
1984 * @return stdClass
82669dc4 1985 */
7d554b64 1986 final public function get_meta() {
c82d7320 1987 global $CFG, $OUTPUT;
6bdfef5d 1988 $meta = new stdClass();
7d554b64 1989 $meta->id = $this->id;
102f9286 1990 $meta->name = format_string($this->get_name());
31581ae6 1991 $meta->type = $this->get_typename();
c82d7320 1992 $meta->icon = $OUTPUT->pix_url('icon', 'repository_'.$meta->type)->out(false);
559276b1 1993 $meta->supported_types = file_get_typegroup('extension', $this->supported_filetypes());
6f2cd52a 1994 $meta->return_types = $this->supported_returntypes();
36ef6643 1995 $meta->sortorder = $this->options['sortorder'];
7d554b64 1996 return $meta;
4a65c39a 1997 }
1cf56396 1998
b1339e98 1999 /**
2000 * Create an instance for this plug-in
67233725
DC
2001 *
2002 * @static
8dcd5deb 2003 * @param string $type the type of the repository
67233725
DC
2004 * @param int $userid the user id
2005 * @param stdClass $context the context
8dcd5deb 2006 * @param array $params the options for this instance
67233725 2007 * @param int $readonly whether to create it readonly or not (defaults to not)
2b8beee3 2008 * @return mixed
b1339e98 2009 */
49d20def 2010 public static function create($type, $userid, $context, $params, $readonly=0) {
b1339e98 2011 global $CFG, $DB;
2012 $params = (array)$params;
e35194be 2013 require_once($CFG->dirroot . '/repository/'. $type . '/lib.php');
b1339e98 2014 $classname = 'repository_' . $type;
3023078f 2015 if ($repo = $DB->get_record('repository', array('type'=>$type))) {
6bdfef5d 2016 $record = new stdClass();
3023078f 2017 $record->name = $params['name'];
2018 $record->typeid = $repo->id;
2019 $record->timecreated = time();
2020 $record->timemodified = time();
2021 $record->contextid = $context->id;
948c2860 2022 $record->readonly = $readonly;
3023078f 2023 $record->userid = $userid;
2024 $id = $DB->insert_record('repository_instances', $record);
118ca9e9 2025 cache::make('core', 'repositories')->purge();
0a6221f9 2026 $options = array();
edb50637 2027 $configs = call_user_func($classname . '::get_instance_option_names');
1e08b5cf 2028 if (!empty($configs)) {
2029 foreach ($configs as $config) {
14b2d8d8
DC
2030 if (isset($params[$config])) {
2031 $options[$config] = $params[$config];
2032 } else {
2033 $options[$config] = null;
2034 }
1e08b5cf 2035 }
3023078f 2036 }
3a01a46a 2037
3023078f 2038 if (!empty($id)) {
2039 unset($options['name']);
dbc01944 2040 $instance = repository::get_instance($id);
3023078f 2041 $instance->set_option($options);
2042 return $id;
2043 } else {
2044 return null;
b1339e98 2045 }
b1339e98 2046 } else {
2047 return null;
2048 }
2049 }
8dcd5deb 2050
82669dc4 2051 /**
4a65c39a 2052 * delete a repository instance
67233725
DC
2053 *
2054 * @param bool $downloadcontents
2055 * @return bool
82669dc4 2056 */
67233725 2057 final public function delete($downloadcontents = false) {
4a65c39a 2058 global $DB;
67233725
DC
2059 if ($downloadcontents) {
2060 $this->convert_references_to_local();
2061 }
118ca9e9 2062 cache::make('core', 'repositories')->purge();
67233725
DC
2063 try {
2064 $DB->delete_records('repository_instances', array('id'=>$this->id));
2065 $DB->delete_records('repository_instance_config', array('instanceid'=>$this->id));
2066 } catch (dml_exception $ex) {
2067 return false;
2068 }
4a65c39a 2069 return true;
2070 }
8dcd5deb 2071
4a65c39a 2072 /**
2073 * Hide/Show a repository
67233725 2074 *
8dcd5deb 2075 * @param string $hide
67233725 2076 * @return bool
4a65c39a 2077 */
7a3b93c1 2078 final public function hide($hide = 'toggle') {
4a65c39a 2079 global $DB;
2080 if ($entry = $DB->get_record('repository', array('id'=>$this->id))) {
2081 if ($hide === 'toggle' ) {
2082 if (!empty($entry->visible)) {
2083 $entry->visible = 0;
2084 } else {
2085 $entry->visible = 1;
2086 }
2087 } else {
2088 if (!empty($hide)) {
2089 $entry->visible = 0;
2090 } else {
2091 $entry->visible = 1;
2092 }
2093 }
2094 return $DB->update_record('repository', $entry);
2095 }
2096 return false;
2097 }
1cf56396 2098
1cf56396 2099 /**
4a65c39a 2100 * Save settings for repository instance
8dcd5deb 2101 * $repo->set_option(array('api_key'=>'f2188bde132', 'name'=>'dongsheng'));
67233725 2102 *
8dcd5deb 2103 * @param array $options settings
67233725 2104 * @return bool
1cf56396 2105 */
7a3b93c1 2106 public function set_option($options = array()) {
4a65c39a 2107 global $DB;
7a3b93c1 2108
122defc5 2109 if (!empty($options['name'])) {
a27ab6fd 2110 $r = new stdClass();
122defc5 2111 $r->id = $this->id;
2112 $r->name = $options['name'];
2113 $DB->update_record('repository_instances', $r);
2114 unset($options['name']);
2115 }
27051e43 2116 foreach ($options as $name=>$value) {
2117 if ($id = $DB->get_field('repository_instance_config', 'id', array('name'=>$name, 'instanceid'=>$this->id))) {
f685e830 2118 $DB->set_field('repository_instance_config', 'value', $value, array('id'=>$id));
27051e43 2119 } else {
a27ab6fd 2120 $config = new stdClass();
27051e43 2121 $config->instanceid = $this->id;
2122 $config->name = $name;
2123 $config->value = $value;
f685e830 2124 $DB->insert_record('repository_instance_config', $config);
27051e43 2125 }
4a65c39a 2126 }
118ca9e9 2127 cache::make('core', 'repositories')->purge();
f685e830 2128 return true;
1cf56396 2129 }
1cf56396 2130
4a65c39a 2131 /**
2132 * Get settings for repository instance
67233725 2133 *
2b8beee3 2134 * @param string $config
4a65c39a 2135 * @return array Settings
2136 */
7a3b93c1 2137 public function get_option($config = '') {
4a65c39a 2138 global $DB;
118ca9e9
MG
2139 $cache = cache::make('core', 'repositories');
2140 if (($entries = $cache->get('ops:'. $this->id)) === false) {
2141 $entries = $DB->get_records('repository_instance_config', array('instanceid' => $this->id));
2142 $cache->set('ops:'. $this->id, $entries);
2143 }
27051e43 2144 $ret = array();
2145 if (empty($entries)) {
2146 return $ret;
4a65c39a 2147 }
7a3b93c1 2148 foreach($entries as $entry) {
27051e43 2149 $ret[$entry->name] = $entry->value;
4a65c39a 2150 }
2151 if (!empty($config)) {
9e6aa5ec 2152 if (isset($ret[$config])) {
75003899 2153 return $ret[$config];
9e6aa5ec
DC
2154 } else {
2155 return null;
2156 }
4a65c39a 2157 } else {
2158 return $ret;
2159 }
2160 }
bf1fccf0 2161
67233725
DC
2162 /**
2163 * Filter file listing to display specific types
2164 *
2165 * @param array $value
2166 * @return bool
2167 */
c167aa26 2168 public function filter(&$value) {
18bd7573 2169 $accepted_types = optional_param_array('accepted_types', '', PARAM_RAW);
b81ebefd 2170 if (isset($value['children'])) {
b81ebefd 2171 if (!empty($value['children'])) {
b81ebefd 2172 $value['children'] = array_filter($value['children'], array($this, 'filter'));
537d44e8 2173 }
559276b1 2174 return true; // always return directories
c167aa26 2175 } else {
46ee50dc 2176 if ($accepted_types == '*' or empty($accepted_types)
2177 or (is_array($accepted_types) and in_array('*', $accepted_types))) {
559276b1
MG
2178 return true;
2179 } else {
e5635827
MG
2180 foreach ($accepted_types as $ext) {
2181 if (preg_match('#'.$ext.'$#i', $value['title'])) {
559276b1 2182 return true;
c167aa26 2183 }
2184 }
2185 }
2186 }
559276b1 2187 return false;
c167aa26 2188 }
2189
4a65c39a 2190 /**
2191 * Given a path, and perhaps a search, get a list of files.
2192 *
67233725 2193 * See details on {@link http://docs.moodle.org/dev/Repository_plugins}
f7639c37 2194 *
67233725
DC
2195 * @param string $path this parameter can a folder name, or a identification of folder
2196 * @param string $page the page number of file list
1a6195b4
DC
2197 * @return array the list of files, including meta infomation, containing the following keys
2198 * manage, url to manage url
2199 * client_id
2200 * login, login form
2201 * repo_id, active repository id
2202 * login_btn_action, the login button action
2203 * login_btn_label, the login button label
2204 * total, number of results
2205 * perpage, items per page
2206 * page
2207 * pages, total pages
29199e56 2208 * issearchresult, is it a search result?
1a6195b4
DC
2209 * list, file list
2210 * path, current path and parent path
4a65c39a 2211 */
9d6aa286 2212 public function get_listing($path = '', $page = '') {
2213 }
1cf56396 2214
8136753a 2215
fbd508b4 2216 /**
8136753a 2217 * Prepare the breadcrumb.
5bdf63cc 2218 *
8136753a
FM
2219 * @param array $breadcrumb contains each element of the breadcrumb.
2220 * @return array of breadcrumb elements.
2221 * @since 2.3.3
5bdf63cc 2222 */
8136753a 2223 protected static function prepare_breadcrumb($breadcrumb) {
5bdf63cc 2224 global $OUTPUT;
8136753a
FM
2225 $foldericon = $OUTPUT->pix_url(file_folder_icon(24))->out(false);
2226 $len = count($breadcrumb);
2227 for ($i = 0; $i < $len; $i++) {
2228 if (is_array($breadcrumb[$i]) && !isset($breadcrumb[$i]['icon'])) {
2229 $breadcrumb[$i]['icon'] = $foldericon;
2230 } else if (is_object($breadcrumb[$i]) && !isset($breadcrumb[$i]->icon)) {
2231 $breadcrumb[$i]->icon = $foldericon;
9213f547
MG
2232 }
2233 }
8136753a
FM
2234 return $breadcrumb;
2235 }
9213f547 2236
8136753a
FM
2237 /**
2238 * Prepare the file/folder listing.
2239 *
2240 * @param array $list of files and folders.
2241 * @return array of files and folders.
2242 * @since 2.3.3
2243 */
2244 protected static function prepare_list($list) {
2245 global $OUTPUT;
2246 $foldericon = $OUTPUT->pix_url(file_folder_icon(24))->out(false);
2247
2248 // Reset the array keys because non-numeric keys will create an object when converted to JSON.
2249 $list = array_values($list);
2250
2251 $len = count($list);
2252 for ($i = 0; $i < $len; $i++) {
2253 if (is_object($list[$i])) {
2254 $file = (array)$list[$i];
e709ddd2
MG
2255 $converttoobject = true;
2256 } else {
8136753a 2257 $file =& $list[$i];
e709ddd2
MG
2258 $converttoobject = false;
2259 }
b92241f2
MG
2260 if (isset($file['size'])) {
2261 $file['size'] = (int)$file['size'];
2262 $file['size_f'] = display_size($file['size']);
2263 }
8136753a 2264 if (isset($file['license']) && get_string_manager()->string_exists($file['license'], 'license')) {
b92241f2
MG
2265 $file['license_f'] = get_string($file['license'], 'license');
2266 }
2267 if (isset($file['image_width']) && isset($file['image_height'])) {
dd1f051e
MG
2268 $a = array('width' => $file['image_width'], 'height' => $file['image_height']);
2269 $file['dimensions'] = get_string('imagesize', 'repository', (object)$a);
5bdf63cc
MG
2270 }
2271 foreach (array('date', 'datemodified', 'datecreated') as $key) {
b92241f2
MG
2272 if (!isset($file[$key]) && isset($file['date'])) {
2273 $file[$key] = $file['date'];
5bdf63cc 2274 }
b92241f2 2275 if (isset($file[$key])) {
5bdf63cc 2276 // must be UNIX timestamp
b92241f2
MG
2277 $file[$key] = (int)$file[$key];
2278 if (!$file[$key]) {
2279 unset($file[$key]);
5bdf63cc 2280 } else {
b92241f2
MG
2281 $file[$key.'_f'] = userdate($file[$key], get_string('strftimedatetime', 'langconfig'));
2282 $file[$key.'_f_s'] = userdate($file[$key], get_string('strftimedatetimeshort', 'langconfig'));
5bdf63cc
MG
2283 }
2284 }
2285 }
e709ddd2
MG
2286 $isfolder = (array_key_exists('children', $file) || (isset($file['type']) && $file['type'] == 'folder'));
2287 $filename = null;
2288 if (isset($file['title'])) {
2289 $filename = $file['title'];
2290 }
2291 else if (isset($file['fullname'])) {
2292 $filename = $file['fullname'];
2293 }
2294 if (!isset($file['mimetype']) && !$isfolder && $filename) {
559276b1 2295 $file['mimetype'] = get_mimetype_description(array('filename' => $filename));
5bdf63cc 2296 }
e709ddd2
MG
2297 if (!isset($file['icon'])) {
2298 if ($isfolder) {
8136753a 2299 $file['icon'] = $foldericon;
e709ddd2 2300 } else if ($filename) {
559276b1 2301 $file['icon'] = $OUTPUT->pix_url(file_extension_icon($filename, 24))->out(false);
5bdf63cc
MG
2302 }
2303 }
8136753a
FM
2304
2305 // Recursively loop over children.
2306 if (isset($file['children'])) {
2307 $file['children'] = self::prepare_list($file['children']);
2308 }
2309
2310 // Convert the array back to an object.
e709ddd2 2311 if ($converttoobject) {
8136753a 2312 $list[$i] = (object)$file;
e709ddd2 2313 }
5bdf63cc 2314 }
8136753a
FM
2315 return $list;
2316 }
2317
2318 /**
2319 * Prepares list of files before passing it to AJAX, makes sure data is in the correct
2320 * format and stores formatted values.
2321 *
2322 * @param array|stdClass $listing result of get_listing() or search() or file_get_drafarea_files()
2323 * @return array
2324 */
2325 public static function prepare_listing($listing) {
2326 $wasobject = false;
2327 if (is_object($listing)) {
2328 $listing = (array) $listing;
2329 $wasobject = true;
2330 }
2331
2332 // Prepare the breadcrumb, passed as 'path'.
2333 if (isset($listing['path']) && is_array($listing['path'])) {
2334 $listing['path'] = self::prepare_breadcrumb($listing['path']);
2335 }
2336
2337 // Prepare the listing of objects.
2338 if (isset($listing['list']) && is_array($listing['list'])) {
2339 $listing['list'] = self::prepare_list($listing['list']);
2340 }
2341
2342 // Convert back to an object.
2343 if ($wasobject) {
2344 $listing = (object) $listing;
2345 }
5bdf63cc
MG
2346 return $listing;
2347 }
2348
2349 /**
2350 * Search files in repository
2351 * When doing global search, $search_text will be used as
2352 * keyword.
353d5cf3 2353 *
67233725
DC
2354 * @param string $search_text search key word
2355 * @param int $page page
72a56555 2356 * @return mixed see {@link repository::get_listing()}
fbd508b4 2357 */
68a7c9a6 2358 public function search($search_text, $page = 0) {
353d5cf3 2359 $list = array();
2360 $list['list'] = array();
2361 return false;
fbd508b4 2362 }
2363
d68c527f 2364 /**
2365 * Logout from repository instance
2366 * By default, this function will return a login form
2367 *
2368 * @return string
2369 */
2370 public function logout(){
2371 return $this->print_login();
2372 }
2373
2374 /**
2375 * To check whether the user is logged in.
2376 *
67233725 2377 * @return bool
d68c527f 2378 */
2379 public function check_login(){
2380 return true;
2381 }
2382
1cf56396 2383
4a65c39a 2384 /**
2385 * Show the login screen, if required
67233725
DC
2386 *
2387 * @return string
4a65c39a 2388 */
1d66f2b2 2389 public function print_login(){
2390 return $this->get_listing();
2391 }
1cf56396 2392
4a65c39a 2393 /**
2394 * Show the search screen, if required
67233725
DC
2395 *
2396 * @return string
4a65c39a 2397 */
a560785f 2398 public function print_search() {
b5e7b638 2399 global $PAGE;
d1d18691 2400 $renderer = $PAGE->get_renderer('core', 'files');
b5e7b638 2401 return $renderer->repository_default_searchform();
2b9feb5f 2402 }
4a65c39a 2403
3e123368
DC
2404 /**
2405 * For oauth like external authentication, when external repository direct user back to moodle,
2406 * this funciton will be called to set up token and token_secret
2407 */
2408 public function callback() {
2409 }
2410
455860ce 2411 /**
2412 * is it possible to do glboal search?
67233725
DC
2413 *
2414 * @return bool
455860ce 2415 */
7a3b93c1 2416 public function global_search() {
455860ce 2417 return false;
2418 }
2419
8dcd5deb 2420 /**
a6600395 2421 * Defines operations that happen occasionally on cron
67233725
DC
2422 *
2423 * @return bool
8dcd5deb 2424 */
a6600395 2425 public function cron() {
2426 return true;
2427 }
2428
7892948d 2429 /**
83a018ed 2430 * function which is run when the type is created (moodle administrator add the plugin)
67233725
DC
2431 *
2432 * @return bool success or fail?
7892948d 2433 */
f1cfe56e 2434 public static function plugin_init() {
3e0794ed 2435 return true;
7892948d 2436 }
2437
a6600395 2438 /**
06e65e1e 2439 * Edit/Create Admin Settings Moodle form
67233725
DC
2440 *
2441 * @param moodleform $mform Moodle form (passed by reference)
8e5af6cf 2442 * @param string $classname repository class name
a6600395 2443 */
68a7c9a6 2444 public static function type_config_form($mform, $classname = 'repository') {
8e5af6cf 2445 $instnaceoptions = call_user_func(array($classname, 'get_instance_option_names'), $mform, $classname);
a5adfa26
DC
2446 if (empty($instnaceoptions)) {
2447 // this plugin has only one instance
2448 // so we need to give it a name
2449 // it can be empty, then moodle will look for instance name from language string
2450 $mform->addElement('text', 'pluginname', get_string('pluginname', 'repository'), array('size' => '40'));
2451 $mform->addElement('static', 'pluginnamehelp', '', get_string('pluginnamehelp', 'repository'));
102f9286 2452 $mform->setType('pluginname', PARAM_TEXT);
a5adfa26 2453 }
4a65c39a 2454 }
dbc01944 2455
84ee73ee
RK
2456 /**
2457 * Validate Admin Settings Moodle form
67233725
DC
2458 *
2459 * @static
2460 * @param moodleform $mform Moodle form (passed by reference)
2461 * @param array $data array of ("fieldname"=>value) of submitted data
2462 * @param array $errors array of ("fieldname"=>errormessage) of errors
84ee73ee
RK
2463 * @return array array of errors
2464 */
2465 public static function type_form_validation($mform, $data, $errors) {
2466 return $errors;
2467 }
2468
2469
6f2cd52a 2470 /**
06e65e1e 2471 * Edit/Create Instance Settings Moodle form
67233725
DC
2472 *
2473 * @param moodleform $mform Moodle form (passed by reference)
a6600395 2474 */
4a126f17 2475 public static function instance_config_form($mform) {
a6600395 2476 }
4a65c39a 2477
a6600395 2478 /**
67233725 2479 * Return names of the general options.
a6600395 2480 * By default: no general option name
67233725 2481 *
a6600395 2482 * @return array
2483 */
1b79955a 2484 public static function get_type_option_names() {
a5adfa26 2485 return array('pluginname');
a6600395 2486 }
2487
2488 /**
67233725 2489 * Return names of the instance options.
a6600395 2490 * By default: no instance option name
67233725 2491 *
a6600395 2492 * @return array
2493 */
7a3b93c1 2494 public static function get_instance_option_names() {
a6600395 2495 return array();
8b65d45c 2496 }
e35194be 2497
67233725
DC
2498 /**
2499 * Validate repository plugin instance form
2500 *
2501 * @param moodleform $mform moodle form
2502 * @param array $data form data
2503 * @param array $errors errors
2504 * @return array errors
2505 */
6b172cdc
DC
2506 public static function instance_form_validation($mform, $data, $errors) {
2507 return $errors;
2508 }
2509
67233725
DC
2510 /**
2511 * Create a shorten filename
2512 *
2513 * @param string $str filename
2514 * @param int $maxlength max file name length
2515 * @return string short filename
2516 */
f00340e2 2517 public function get_short_filename($str, $maxlength) {
138c7678
PS
2518 if (textlib::strlen($str) >= $maxlength) {
2519 return trim(textlib::substr($str, 0, $maxlength)).'...';
f00340e2
DC
2520 } else {
2521 return $str;
2522 }
2523 }
f392caba
DC
2524
2525 /**
2526 * Overwrite an existing file
2527 *
2528 * @param int $itemid
2529 * @param string $filepath
2530 * @param string $filename
2531 * @param string $newfilepath
2532 * @param string $newfilename
67233725 2533 * @return bool
f392caba 2534 */
061eeed5 2535 public static function overwrite_existing_draftfile($itemid, $filepath, $filename, $newfilepath, $newfilename) {
f392caba
DC
2536 global $USER;
2537 $fs = get_file_storage();
21c08c63 2538 $user_context = context_user::instance($USER->id);
f392caba
DC
2539 if ($file = $fs->get_file($user_context->id, 'user', 'draft', $itemid, $filepath, $filename)) {
2540 if ($tempfile = $fs->get_file($user_context->id, 'user', 'draft', $itemid, $newfilepath, $newfilename)) {
2541 // delete existing file to release filename
2542 $file->delete();
2543 // create new file
2544 $newfile = $fs->create_file_from_storedfile(array('filepath'=>$filepath, 'filename'=>$filename), $tempfile);
2545 // remove temp file
2546 $tempfile->delete();
2547 return true;
2548 }
2549 }
2550 return false;
2551 }
2552
2553 /**
2554 * Delete a temp file from draft area
2555 *
2556 * @param int $draftitemid
2557 * @param string $filepath
2558 * @param string $filename
67233725 2559 * @return bool
f392caba 2560 */
061eeed5 2561 public static function delete_tempfile_from_draft($draftitemid, $filepath, $filename) {
f392caba
DC
2562 global $USER;
2563 $fs = get_file_storage();
21c08c63 2564 $user_context = context_user::instance($USER->id);
f392caba
DC
2565 if ($file = $fs->get_file($user_context->id, 'user', 'draft', $draftitemid, $filepath, $filename)) {
2566 $file->delete();
2567 return true;
2568 } else {
2569 return false;
2570 }
2571 }
67233725
DC
2572
2573 /**
2574 * Find all external files in this repo and import them
2575 */
2576 public function convert_references_to_local() {
2577 $fs = get_file_storage();
2578 $files = $fs->get_external_files($this->id);
2579 foreach ($files as $storedfile) {
2580 $fs->import_external_file($storedfile);
2581 }
2582 }
2583
6fd1cf05
MG
2584 /**
2585 * Called from phpunit between tests, resets whatever was cached
2586 */
2587 public static function reset_caches() {
2588 self::sync_external_file(null, true);
2589 }
67233725
DC
2590
2591 /**
2d222a32 2592 * Performs synchronisation of reference to an external file if the previous one has expired.
67233725
DC
2593 *
2594 * @param stored_file $file
6fd1cf05 2595 * @param bool $resetsynchistory whether to reset all history of sync (used by phpunit)
67233725
DC
2596 * @return bool success
2597 */
6fd1cf05 2598 public static function sync_external_file($file, $resetsynchistory = false) {
67233725 2599 global $DB;
6fd1cf05 2600 // TODO MDL-25290 static should be replaced with MUC code.
0b2bfbd1 2601 static $synchronized = array();
6fd1cf05
MG
2602 if ($resetsynchistory) {
2603 $synchronized = array();
2604 }
67233725
DC
2605
2606 $fs = get_file_storage();
2607
6fd1cf05 2608 if (!$file || !$file->get_referencefileid()) {
0b2bfbd1
MG
2609 return false;
2610 }
2611 if (array_key_exists($file->get_id(), $synchronized)) {
2612 return $synchronized[$file->get_id()];
2613 }
2614
2615 // remember that we already cached in current request to prevent from querying again
2616 $synchronized[$file->get_id()] = false;
2617
67233725
DC
2618 if (!$reference = $DB->get_record('files_reference', array('id'=>$file->get_referencefileid()))) {
2619 return false;
2620 }
2621
2622 if (!empty($reference->lastsync) and ($reference->lastsync + $reference->lifetime > time())) {
0b2bfbd1
MG
2623 $synchronized[$file->get_id()] = true;
2624 return true;
67233725
DC
2625 }
2626
2627 if (!$repository = self::get_repository_by_id($reference->repositoryid, SYSCONTEXTID)) {
2628 return false;
2629 }
2630
2631 if (!$repository->sync_individual_file($file)) {
2632 return false;
2633 }
2634
2d222a32 2635 $lifetime = $repository->get_reference_file_lifetime($reference);
67233725
DC
2636 $fileinfo = $repository->get_file_by_reference($reference);
2637 if ($fileinfo === null) {
2638 // does not exist any more - set status to missing
2d222a32 2639 $file->set_missingsource($lifetime);
0b2bfbd1 2640 $synchronized[$file->get_id()] = true;
67233725 2641 return true;
67233725
DC
2642 }
2643
2644 $contenthash = null;
2645 $filesize = null;
2d222a32
MG
2646 if (!empty($fileinfo->filesize)) {
2647 // filesize returned
2648 if (!empty($fileinfo->contenthash) && $fs->content_exists($fileinfo->contenthash)) {
2649 // contenthash is specified and valid
2650 $contenthash = $fileinfo->contenthash;
2651 } else if ($fileinfo->filesize == $file->get_filesize()) {
2652 // we don't know the new contenthash but the filesize did not change,
2653 // assume the contenthash did not change either
2654 $contenthash = $file->get_contenthash();
2655 } else {
2656 // we can't save empty contenthash so generate contenthash from empty string
2657 $fs->add_string_to_pool('');
2658 $contenthash = sha1('');
2659 }
67233725
DC
2660 $filesize = $fileinfo->filesize;
2661 } else if (!empty($fileinfo->filepath)) {
2662 // File path returned
2663 list($contenthash, $filesize, $newfile) = $fs->add_file_to_pool($fileinfo->filepath);
2664 } else if (!empty($fileinfo->handle) && is_resource($fileinfo->handle)) {
2665 // File handle returned
2666 $contents = '';
2667 while (!feof($fileinfo->handle)) {
2668 $contents .= fread($handle, 8192);
2669 }
2670 fclose($fileinfo->handle);
2671 list($contenthash, $filesize, $newfile) = $fs->add_string_to_pool($content);
2672 } else if (isset($fileinfo->content)) {
2673 // File content returned
2674 list($contenthash, $filesize, $newfile) = $fs->add_string_to_pool($fileinfo->content);
2675 }
2676
2677 if (!isset($contenthash) or !isset($filesize)) {
2678 return false;
2679 }
2680
67233725 2681 // update files table
2d222a32 2682 $file->set_synchronized($contenthash, $filesize, 0, $lifetime);
0b2bfbd1 2683 $synchronized[$file->get_id()] = true;
67233725
DC
2684 return true;
2685 }
d6453211
DC
2686
2687 /**
2688 * Build draft file's source field
2689 *
2690 * {@link file_restore_source_field_from_draft_file()}
2691 * XXX: This is a hack for file manager (MDL-28666)
2692 * For newly created draft files we have to construct
2693 * source filed in php serialized data format.
2694 * File manager needs to know the original file information before copying
2695 * to draft area, so we append these information in mdl_files.source field
2696 *
2697 * @param string $source
2698 * @return string serialised source field
2699 */
2700 public static function build_source_field($source) {
2701 $sourcefield = new stdClass;
2702 $sourcefield->source = $source;
2703 return serialize($sourcefield);
2704 }
118ca9e9
MG
2705
2706 /**
2707 * Prepares the repository to be cached. Implements method from cacheable_object interface.
2708 *
2709 * @return array
2710 */
2711 public function prepare_to_cache() {
2712 return array(
2713 'class' => get_class($this),
2714 'id' => $this->id,
2715 'ctxid' => $this->context->id,
2716 'options' => $this->options,
2717 'readonly' => $this->readonly
2718 );
2719 }
2720
2721 /**
2722 * Restores the repository from cache. Implements method from cacheable_object interface.
2723 *
2724 * @return array
2725 */
2726 public static function wake_from_cache($data) {
2727 $classname = $data['class'];
2728 return new $classname($data['id'], $data['ctxid'], $data['options'], $data['readonly']);
2729 }
8b65d45c 2730}
837ebb78 2731
2732/**
6f2cd52a
DC
2733 * Exception class for repository api
2734 *
2735 * @since 2.0
72a56555 2736 * @package core_repository
67233725 2737 * @copyright 2009 Dongsheng Cai {@link http://dongsheng.org}
6f2cd52a 2738 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
837ebb78 2739 */
4a65c39a 2740class repository_exception extends moodle_exception {
8b65d45c 2741}
4ed43890 2742
8dcd5deb 2743/**
6f2cd52a
DC
2744 * This is a class used to define a repository instance form
2745 *
2746 * @since 2.0
72a56555 2747 * @package core_repository
67233725 2748 * @copyright 2009 Dongsheng Cai {@link http://dongsheng.org}
6f2cd52a 2749 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
8dcd5deb 2750 */
a6600395 2751final class repository_instance_form extends moodleform {
67233725 2752 /** @var stdClass repository instance */
4a65c39a 2753 protected $instance;
67233725 2754 /** @var string repository plugin type */
4a65c39a 2755 protected $plugin;
67233725
DC
2756
2757 /**
2758 * Added defaults to moodle form
2759 */
49d20def 2760 protected function add_defaults() {
4a65c39a 2761 $mform =& $this->_form;
2762 $strrequired = get_string('required');
2763
2764 $mform->addElement('hidden', 'edit', ($this->instance) ? $this->instance->id : 0);
d18e0fe6 2765 $mform->setType('edit', PARAM_INT);
4a65c39a 2766 $mform->addElement('hidden', 'new', $this->plugin);
405aca35 2767 $mform->setType('new', PARAM_ALPHANUMEXT);
4a65c39a 2768 $mform->addElement('hidden', 'plugin', $this->plugin);
aff24313 2769 $mform->setType('plugin', PARAM_PLUGIN);
27051e43 2770 $mform->addElement('hidden', 'typeid', $this->typeid);
d18e0fe6 2771 $mform->setType('typeid', PARAM_INT);
faaa613d 2772 $mform->addElement('hidden', 'contextid', $this->contextid);
d18e0fe6 2773 $mform->setType('contextid', PARAM_INT);
4a65c39a 2774
2775 $mform->addElement('text', 'name', get_string('name'), 'maxlength="100" size="30"');
2776 $mform->addRule('name', $strrequired, 'required', null, 'client');
102f9286 2777 $mform->setType('name', PARAM_TEXT);
49d20def 2778 }
4a65c39a 2779
67233725
DC
2780 /**
2781 * Define moodle form elements
2782 */
49d20def
DC
2783 public function definition() {
2784 global $CFG;
2785 // type of plugin, string
2786 $this->plugin = $this->_customdata['plugin'];
2787 $this->typeid = $this->_customdata['typeid'];
2788 $this->contextid = $this->_customdata['contextid'];
2789 $this->instance = (isset($this->_customdata['instance'])
2790 && is_subclass_of($this->_customdata['instance'], 'repository'))
2791 ? $this->_customdata['instance'] : null;
2792
2793 $mform =& $this->_form;
1e97f196 2794
49d20def 2795 $this->add_defaults();
4a126f17
DP
2796
2797 // Add instance config options.
2798 $result = repository::static_function($this->plugin, 'instance_config_form', $mform);
2799 if ($result === false) {
2800 // Remove the name element if no other config options.
2801 $mform->removeElement('name');
2802 }
2803 if ($this->instance) {
f48fb4d6 2804 $data = array();
2805 $data['name'] = $this->instance->name;
2806 if (!$this->instance->readonly) {
f48fb4d6 2807 // and set the data if we have some.
1e97f196 2808 foreach ($this->instance->get_instance_option_names() as $config) {
a3d8df25 2809 if (!empty($this->instance->options[$config])) {
2810 $data[$config] = $this->instance->options[$config];
1e97f196 2811 } else {
2812 $data[$config] = '';
2813 }
27051e43 2814 }
4a65c39a 2815 }
f48fb4d6 2816 $this->set_data($data);
1e97f196 2817 }
2818
49d20def
DC
2819 if ($result === false) {
2820 $mform->addElement('cancel');
2821 } else {
2822 $this->add_action_buttons(true, get_string('save','repository'));
2823 }
4a65c39a 2824 }
2825
67233725
DC
2826 /**
2827 * Validate moodle form data
2828 *
2829 * @param array $data form data
2830 * @param array $files files in form
2831 * @return array errors
2832 */
58eb9b9f 2833 public function validation($data, $files) {
4a65c39a 2834 global $DB;
4a65c39a 2835 $errors = array();
6b172cdc
DC
2836 $plugin = $this->_customdata['plugin'];
2837 $instance = (isset($this->_customdata['instance'])
2838 && is_subclass_of($this->_customdata['instance'], 'repository'))
2839 ? $this->_customdata['instance'] : null;
2840 if (!$instance) {
2841 $errors = repository::static_function($plugin, 'instance_form_validation', $this, $data, $errors);
2842 } else {
2843 $errors = $instance->instance_form_validation($this, $data, $errors);
2844 }
2845
a090554a
PS
2846 $sql = "SELECT count('x')
2847 FROM {repository_instances} i, {repository} r
2848 WHERE r.type=:plugin AND r.id=i.typeid AND i.name=:name";
09bff8e8 2849 if ($DB->count_records_sql($sql, array('name' => $data['name'], 'plugin' => $data['plugin'])) > 1) {
6b172cdc 2850 $errors['name'] = get_string('erroruniquename', 'repository');
4a65c39a 2851 }
2852
4a65c39a 2853 return $errors;
2854 }
2855}
a6600395 2856
a6600395 2857/**
6f2cd52a
DC
2858 * This is a class used to define a repository type setting form
2859 *
2860 * @since 2.0
72a56555 2861 * @package core_repository
67233725 2862 * @copyright 2009 Dongsheng Cai {@link http://dongsheng.org}
6f2cd52a 2863 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
a6600395 2864 */
c295f9ff 2865final class repository_type_form extends moodleform {
67233725 2866 /** @var stdClass repository instance */
a6600395 2867 protected $instance;
67233725 2868 /** @var string repository plugin name */
a6600395 2869 protected $plugin;
67233725 2870 /** @var string action */
79698344 2871 protected $action;
a6600395 2872
2873 /**
2874 * Definition of the moodleform
a6600395 2875 */
2876 public function definition() {
2877 global $CFG;
2878 // type of plugin, string
2879 $this->plugin = $this->_customdata['plugin'];
2880 $this->instance = (isset($this->_customdata['instance'])
2881 && is_a($this->_customdata['instance'], 'repository_type'))
2882 ? $this->_customdata['instance'] : null;
2883
79698344 2884 $this->action = $this->_customdata['action'];
a5adfa26 2885 $this->pluginname = $this->_customdata['pluginname'];
a6600395 2886 $mform =& $this->_form;
2887 $strrequired = get_string('required');
4d5948f1 2888
79698344
MD
2889 $mform->addElement('hidden', 'action', $this->action);
2890 $mform->setType('action', PARAM_TEXT);
2891 $mform->addElement('hidden', 'repos', $this->plugin);
aff24313 2892 $mform->setType('repos', PARAM_PLUGIN);
8f943eba 2893
06e65e1e 2894 // let the plugin add its specific fields
a5adfa26
DC
2895 $classname = 'repository_' . $this->plugin;
2896 require_once($CFG->dirroot . '/repository/' . $this->plugin . '/lib.php');
f48fb4d6 2897 //add "enable course/user instances" checkboxes if multiple instances are allowed
dbc01944 2898 $instanceoptionnames = repository::static_function($this->plugin, 'get_instance_option_names');
8e5af6cf
DC
2899
2900 $result = call_user_func(array($classname, 'type_config_form'), $mform, $classname);
2901
a5adfa26 2902 if (!empty($instanceoptionnames)) {
8e5af6cf
DC
2903 $sm = get_string_manager();
2904 $component = 'repository';
2905 if ($sm->string_exists('enablecourseinstances', 'repository_' . $this->plugin)) {
2906 $component .= ('_' . $this->plugin);
2907 }
2908 $mform->addElement('checkbox', 'enablecourseinstances', get_string('enablecourseinstances', $component));
2909
2910 $component = 'repository';
2911 if ($sm->string_exists('enableuserinstances', 'repository_' . $this->plugin)) {
2912 $component .= ('_' . $this->plugin);
2913 }
2914 $mform->addElement('checkbox', 'enableuserinstances', get_string('enableuserinstances', $component));
f48fb4d6 2915 }
2916
2917 // set the data if we have some.
a6600395 2918 if ($this->instance) {
2919 $data = array();
1b79955a 2920 $option_names = call_user_func(array($classname,'get_type_option_names'));
f48fb4d6 2921 if (!empty($instanceoptionnames)){
2922 $option_names[] = 'enablecourseinstances';
2923 $option_names[] = 'enableuserinstances';
2924 }
2925
a6600395 2926 $instanceoptions = $this->instance->get_options();
2927 foreach ($option_names as $config) {
2928 if (!empty($instanceoptions[$config])) {
2929 $data[$config] = $instanceoptions[$config];
2930 } else {
2931 $data[$config] = '';
2932 }
2933 }
a5adfa26
DC
2934 // XXX: set plugin name for plugins which doesn't have muliti instances
2935 if (empty($instanceoptionnames)){
2936 $data['pluginname'] = $this->pluginname;
2937 }
a6600395 2938 $this->set_data($data);
2939 }
dbc01944 2940
46dd6bb0 2941 $this->add_action_buttons(true, get_string('save','repository'));
a6600395 2942 }
84ee73ee 2943
67233725
DC
2944 /**
2945 * Validate moodle form data
2946 *
2947 * @param array $data moodle form data
2948 * @param array $files
2949 * @return array errors
2950 */
58eb9b9f 2951 public function validation($data, $files) {
84ee73ee
RK
2952 $errors = array();
2953 $plugin = $this->_customdata['plugin'];
2954 $instance = (isset($this->_customdata['instance'])
2955 && is_subclass_of($this->_customdata['instance'], 'repository'))
2956 ? $this->_customdata['instance'] : null;
2957 if (!$instance) {
2958 $errors = repository::static_function($plugin, 'type_form_validation', $this, $data, $errors);
2959 } else {
2960 $errors = $instance->type_form_validation($this, $data, $errors);
2961 }
2962
2963 return $errors;
2964 }
a6600395 2965}
2966
8e0946bf
DC
2967/**
2968 * Generate all options needed by filepicker
2969 *
67233725 2970 * @param array $args including following keys
8e0946bf
DC
2971 * context
2972 * accepted_types
2973 * return_types
2974 *
2975 * @return array the list of repository instances, including meta infomation, containing the following keys
2976 * externallink
2977 * repositories
2978 * accepted_types
2979 */
99eaca9d 2980function initialise_filepicker($args) {
a28c9253 2981 global $CFG, $USER, $PAGE, $OUTPUT;
ec3eaa2c 2982 static $templatesinitialized = array();
1dce6261 2983 require_once($CFG->libdir . '/licenselib.php');
4f0c2d00 2984
6bdfef5d 2985 $return = new stdClass();
d1d4813f 2986 $licenses = array();
4f0c2d00
PS
2987 if (!empty($CFG->licenses)) {
2988 $array = explode(',', $CFG->licenses);
2989 foreach ($array as $license) {
6bdfef5d 2990 $l = new stdClass();
4f0c2d00
PS
2991 $l->shortname = $license;
2992 $l->fullname = get_string($license, 'license');
2993 $licenses[] = $l;
2994 }
d1d4813f 2995 }
308d948b
DC
2996 if (!empty($CFG->sitedefaultlicense)) {
2997 $return->defaultlicense = $CFG->sitedefaultlicense;
2998 }
1dce6261 2999
1dce6261
DC
3000 $return->licenses = $licenses;
3001
3002 $return->author = fullname($USER);
3003
99eaca9d
DC
3004 if (empty($args->context)) {
3005 $context = $PAGE->context;
e189ec00 3006 } else {
99eaca9d
DC
3007 $context = $args->context;
3008 }
6bf197b3
DC
3009 $disable_types = array();
3010 if (!empty($args->disable_types)) {
3011 $disable_types = $args->disable_types;
3012 }
99eaca9d 3013
21c08c63 3014 $user_context = context_user::instance($USER->id);
99eaca9d 3015
bf413f6f
DC
3016 list($context, $course, $cm) = get_context_info_array($context->id);
3017 $contexts = array($user_context, get_system_context());
3018 if (!empty($course)) {
3019 // adding course context
21c08c63 3020 $contexts[] = context_course::instance($course->id);
bf413f6f 3021 }
99eaca9d
DC
3022 $externallink = (int)get_config(null, 'repositoryallowexternallinks');
3023 $repositories = repository::get_instances(array(
bf413f6f 3024 'context'=>$contexts,
99eaca9d 3025 'currentcontext'=> $context,
ea1780ad 3026 'accepted_types'=>$args->accepted_types,
6bf197b3
DC
3027 'return_types'=>$args->return_types,
3028 'disable_types'=>$disable_types
99eaca9d
DC
3029 ));
3030
3031 $return->repositories = array();
3032
3033 if (empty($externallink)) {
3034 $return->externallink = false;
3035 } else {
3036 $return->externallink = true;
3037 }
3038
837eef2e
DP
3039 $return->userprefs = array();
3040 $return->userprefs['recentrepository'] = get_user_preferences('filepicker_recentrepository', '');
3041 $return->userprefs['recentlicense'] = get_user_preferences('filepicker_recentlicense', '');
3042 $return->userprefs['recentviewmode'] = get_user_preferences('filepicker_recentviewmode', '');
3043
3044 user_preference_allow_ajax_update('filepicker_recentrepository', PARAM_INT);
3045 user_preference_allow_ajax_update('filepicker_recentlicense', PARAM_SAFEDIR);
3046 user_preference_allow_ajax_update('filepicker_recentviewmode', PARAM_INT);
3047
3048
99eaca9d 3049 // provided by form element
559276b1 3050 $return->accepted_types = file_get_typegroup('extension', $args->accepted_types);
766514a0 3051 $return->return_types = $args->return_types;
013cf287 3052 $templates = array();
99eaca9d
DC
3053 foreach ($repositories as $repository) {
3054 $meta = $repository->get_meta();
6b37c2b0
SH
3055 // Please note that the array keys for repositories are used within
3056 // JavaScript a lot, the key NEEDS to be the repository id.
b0985814 3057 $return->repositories[$repository->id] = $meta;
013cf287 3058 // Register custom repository template if it has one
ec3eaa2c
PN
3059 if(method_exists($repository, 'get_upload_template') && !array_key_exists('uploadform_' . $meta->type, $templatesinitialized)) {
3060 $templates['uploadform_' . $meta->type] = $repository->get_upload_template();
3061 $templatesinitialized['uploadform_' . $meta->type] = true;
013cf287 3062 }
99eaca9d 3063 }
ec3eaa2c
PN
3064 if (!array_key_exists('core', $templatesinitialized)) {
3065 // we need to send each filepicker template to the browser just once
d1d18691 3066 $fprenderer = $PAGE->get_renderer('core', 'files');
013cf287 3067 $templates = array_merge($templates, $fprenderer->filepicker_js_templates());
ec3eaa2c
PN
3068 $templatesinitialized['core'] = true;
3069 }
3070 if (sizeof($templates)) {
d1d18691 3071 $PAGE->requires->js_init_call('M.core_filepicker.set_templates', array($templates), true);
d1d18691 3072 }
99eaca9d 3073 return $return;
e189ec00 3074}
72a56555 3075
f392caba
DC
3076/**
3077 * Small function to walk an array to attach repository ID
67233725 3078 *
f392caba
DC
3079 * @param array $value
3080 * @param string $key
3081 * @param int $id
3082 */
3083function repository_attach_id(&$value, $key, $id){
3084 $value['repo_id'] = $id;
3085}