MDL-41580 SCORM: allow imsmanifest.xml to be used in file system repos
[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 }
0601e0ee 254 repository::static_function($this->_typename, 'create', $this->_typename, 0, context_system::instance(), $instanceoptions);
7a3b93c1 255 }
60c366e8 256 //run plugin_init function
257 if (!repository::static_function($this->_typename, 'plugin_init')) {
9b64ec4d 258 $this->update_visibility(false);
60c366e8 259 if (!$silent) {
260 throw new repository_exception('cannotinitplugin', 'repository');
261 }
262 }
263
118ca9e9 264 cache::make('core', 'repositories')->purge();
a75c78d3 265 if(!empty($plugin_id)) {
266 // return plugin_id if create successfully
267 return $plugin_id;
268 } else {
269 return false;
270 }
948c2860 271
7a3b93c1 272 } else {
a75c78d3 273 if (!$silent) {
274 throw new repository_exception('existingrepository', 'repository');
275 }
276 // If plugin existed, return false, tell caller no new plugins were created.
277 return false;
a6600395 278 }
279 }
280
281
282 /**
283 * Update plugin options into the config_plugin table
67233725 284 *
a6600395 285 * @param array $options
67233725 286 * @return bool
a6600395 287 */
7a3b93c1 288 public function update_options($options = null) {
a5adfa26
DC
289 global $DB;
290 $classname = 'repository_' . $this->_typename;
291 $instanceoptions = repository::static_function($this->_typename, 'get_instance_option_names');
292 if (empty($instanceoptions)) {
293 // update repository instance name if this plugin type doesn't have muliti instances
294 $params = array();
295 $params['type'] = $this->_typename;
296 $instances = repository::get_instances($params);
297 $instance = array_pop($instances);
298 if ($instance) {
299 $DB->set_field('repository_instances', 'name', $options['pluginname'], array('id'=>$instance->id));
300 }
301 unset($options['pluginname']);
302 }
303
7a3b93c1 304 if (!empty($options)) {
a6600395 305 $this->_options = $options;
306 }
307
308 foreach ($this->_options as $name => $value) {
a5adfa26 309 set_config($name, $value, $this->_typename);
a6600395 310 }
311
118ca9e9 312 cache::make('core', 'repositories')->purge();
a6600395 313 return true;
314 }
315
316 /**
317 * Update visible database field with the value given as parameter
318 * or with the visible value of this object
319 * This function is private.
320 * For public access, have a look to switch_and_update_visibility()
67233725
DC
321 *
322 * @param bool $visible
323 * @return bool
a6600395 324 */
7a3b93c1 325 private function update_visible($visible = null) {
a6600395 326 global $DB;
327
7a3b93c1 328 if (!empty($visible)) {
a6600395 329 $this->_visible = $visible;
330 }
7a3b93c1 331 else if (!isset($this->_visible)) {
a6600395 332 throw new repository_exception('updateemptyvisible', 'repository');
333 }
334
118ca9e9 335 cache::make('core', 'repositories')->purge();
a6600395 336 return $DB->set_field('repository', 'visible', $this->_visible, array('type'=>$this->_typename));
337 }
338
339 /**
340 * Update database sortorder field with the value given as parameter
341 * or with the sortorder value of this object
342 * This function is private.
343 * For public access, have a look to move_order()
67233725
DC
344 *
345 * @param int $sortorder
346 * @return bool
a6600395 347 */
7a3b93c1 348 private function update_sortorder($sortorder = null) {
a6600395 349 global $DB;
350
7a3b93c1 351 if (!empty($sortorder) && $sortorder!=0) {
a6600395 352 $this->_sortorder = $sortorder;
353 }
354 //if sortorder is not set, we set it as the ;ast position in the list
7a3b93c1 355 else if (!isset($this->_sortorder) || $this->_sortorder == 0 ) {
a6600395 356 $sql = "SELECT MAX(sortorder) FROM {repository}";
357 $this->_sortorder = 1 + $DB->get_field_sql($sql);
358 }
359
118ca9e9 360 cache::make('core', 'repositories')->purge();
a6600395 361 return $DB->set_field('repository', 'sortorder', $this->_sortorder, array('type'=>$this->_typename));
362 }
363
364 /**
365 * Change order of the type with its adjacent upper or downer type
366 * (database fields are updated)
367 * Algorithm details:
368 * 1. retrieve all types in an array. This array is sorted by sortorder,
369 * and the array keys start from 0 to X (incremented by 1)
370 * 2. switch sortorder values of this type and its adjacent type
67233725 371 *
a6600395 372 * @param string $move "up" or "down"
373 */
374 public function move_order($move) {
375 global $DB;
a6600395 376
dbc01944 377 $types = repository::get_types(); // retrieve all types
7a3b93c1 378
67233725 379 // retrieve this type into the returned array
7a3b93c1 380 $i = 0;
381 while (!isset($indice) && $i<count($types)) {
382 if ($types[$i]->get_typename() == $this->_typename) {
a6600395 383 $indice = $i;
384 }
385 $i++;
386 }
387
67233725 388 // retrieve adjacent indice
a6600395 389 switch ($move) {
390 case "up":
391 $adjacentindice = $indice - 1;
7a3b93c1 392 break;
a6600395 393 case "down":
394 $adjacentindice = $indice + 1;
7a3b93c1 395 break;
a6600395 396 default:
7a3b93c1 397 throw new repository_exception('movenotdefined', 'repository');
a6600395 398 }
399
400 //switch sortorder of this type and the adjacent type
401 //TODO: we could reset sortorder for all types. This is not as good in performance term, but
402 //that prevent from wrong behaviour on a screwed database. As performance are not important in this particular case
403 //it worth to change the algo.
7a3b93c1 404 if ($adjacentindice>=0 && !empty($types[$adjacentindice])) {
a6600395 405 $DB->set_field('repository', 'sortorder', $this->_sortorder, array('type'=>$types[$adjacentindice]->get_typename()));
406 $this->update_sortorder($types[$adjacentindice]->get_sortorder());
407 }
408 }
409
410 /**
79698344 411 * 1. Change visibility to the value chosen
a6600395 412 * 2. Update the type
67233725
DC
413 *
414 * @param bool $visible
415 * @return bool
a6600395 416 */
79698344
MD
417 public function update_visibility($visible = null) {
418 if (is_bool($visible)) {
419 $this->_visible = $visible;
420 } else {
421 $this->_visible = !$this->_visible;
422 }
a6600395 423 return $this->update_visible();
424 }
425
426
427 /**
eb239694 428 * Delete a repository_type (general options are removed from config_plugin
429 * table, and all instances are deleted)
67233725
DC
430 *
431 * @param bool $downloadcontents download external contents if exist
432 * @return bool
a6600395 433 */
67233725 434 public function delete($downloadcontents = false) {
a6600395 435 global $DB;
46dd6bb0 436
437 //delete all instances of this type
6f2cd52a
DC
438 $params = array();
439 $params['context'] = array();
440 $params['onlyvisible'] = false;
441 $params['type'] = $this->_typename;
442 $instances = repository::get_instances($params);
7a3b93c1 443 foreach ($instances as $instance) {
67233725 444 $instance->delete($downloadcontents);
46dd6bb0 445 }
446
eb239694 447 //delete all general options
7a3b93c1 448 foreach ($this->_options as $name => $value) {
eb239694 449 set_config($name, null, $this->_typename);
450 }
451
118ca9e9 452 cache::make('core', 'repositories')->purge();
67233725
DC
453 try {
454 $DB->delete_records('repository', array('type' => $this->_typename));
455 } catch (dml_exception $ex) {
456 return false;
457 }
458 return true;
a6600395 459 }
118ca9e9
MG
460
461 /**
462 * Prepares the repository type to be cached. Implements method from cacheable_object interface.
463 *
464 * @return array
465 */
466 public function prepare_to_cache() {
467 return array(
468 'typename' => $this->_typename,
469 'typeoptions' => $this->_options,
470 'visible' => $this->_visible,
471 'sortorder' => $this->_sortorder
472 );
473 }
474
475 /**
476 * Restores repository type from cache. Implements method from cacheable_object interface.
477 *
478 * @return array
479 */
480 public static function wake_from_cache($data) {
481 return new repository_type($data['typename'], $data['typeoptions'], $data['visible'], $data['sortorder']);
482 }
a6600395 483}
484
a6600395 485/**
67233725 486 * This is the base class of the repository class.
8d419e59 487 *
67233725
DC
488 * To create repository plugin, see: {@link http://docs.moodle.org/dev/Repository_plugins}
489 * See an example: {@link repository_boxnet}
8d419e59 490 *
72a56555 491 * @package core_repository
67233725 492 * @copyright 2009 Dongsheng Cai {@link http://dongsheng.org}
6f2cd52a 493 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
a6600395 494 */
118ca9e9 495abstract class repository implements cacheable_object {
72a56555
MG
496 /** Timeout in seconds for downloading the external file into moodle */
497 const GETFILE_TIMEOUT = 30;
498 /** Timeout in seconds for syncronising the external file size */
499 const SYNCFILE_TIMEOUT = 1;
500 /** Timeout in seconds for downloading an image file from external repository during syncronisation */
501 const SYNCIMAGE_TIMEOUT = 3;
502
efe018b4 503 // $disabled can be set to true to disable a plugin by force
504 // example: self::$disabled = true
67233725 505 /** @var bool force disable repository instance */
efe018b4 506 public $disabled = false;
67233725 507 /** @var int repository instance id */
4a65c39a 508 public $id;
67233725 509 /** @var stdClass current context */
4a65c39a 510 public $context;
67233725 511 /** @var array repository options */
4a65c39a 512 public $options;
67233725 513 /** @var bool Whether or not the repository instance is editable */
948c2860 514 public $readonly;
67233725 515 /** @var int return types */
41076c58 516 public $returntypes;
67233725 517 /** @var stdClass repository instance database record */
a5adfa26 518 public $instance;
31581ae6
FM
519 /** @var string Type of repository (webdav, google_docs, dropbox, ...). Read from $this->get_typename(). */
520 protected $typename;
521
a0ff4137 522 /**
67233725 523 * Constructor
a0ff4137 524 *
67233725
DC
525 * @param int $repositoryid repository instance id
526 * @param int|stdClass $context a context id or context object
e35194be 527 * @param array $options repository options
67233725 528 * @param int $readonly indicate this repo is readonly or not
a0ff4137 529 */
e35194be 530 public function __construct($repositoryid, $context = SYSCONTEXTID, $options = array(), $readonly = 0) {
a5adfa26 531 global $DB;
a0ff4137 532 $this->id = $repositoryid;
be85f7ab 533 if (is_object($context)) {
e35194be
DC
534 $this->context = $context;
535 } else {
d197ea43 536 $this->context = context::instance_by_id($context);
e35194be 537 }
118ca9e9
MG
538 $cache = cache::make('core', 'repositories');
539 if (($this->instance = $cache->get('i:'. $this->id)) === false) {
540 $this->instance = $DB->get_record_sql("SELECT i.*, r.type AS repositorytype, r.sortorder, r.visible
541 FROM {repository} r, {repository_instances} i
542 WHERE i.typeid = r.id and i.id = ?", array('id' => $this->id));
543 $cache->set('i:'. $this->id, $this->instance);
544 }
a0ff4137
DC
545 $this->readonly = $readonly;
546 $this->options = array();
e35194be 547
a0ff4137 548 if (is_array($options)) {
67233725 549 // The get_option() method will get stored options in database.
a0ff4137
DC
550 $options = array_merge($this->get_option(), $options);
551 } else {
552 $options = $this->get_option();
553 }
554 foreach ($options as $n => $v) {
555 $this->options[$n] = $v;
556 }
557 $this->name = $this->get_name();
558 $this->returntypes = $this->supported_returntypes();
559 $this->super_called = true;
560 }
1cf56396 561
67233725
DC
562 /**
563 * Get repository instance using repository id
564 *
cfb71351
MG
565 * Note that this function does not check permission to access repository contents
566 *
567 * @throws repository_exception
568 *
569 * @param int $repositoryid repository instance ID
570 * @param context|int $context context instance or context ID where this repository will be used
6dc82385 571 * @param array $options additional repository options
67233725
DC
572 * @return repository
573 */
6dc82385 574 public static function get_repository_by_id($repositoryid, $context, $options = array()) {
67233725 575 global $CFG, $DB;
118ca9e9 576 $cache = cache::make('core', 'repositories');
cfb71351
MG
577 if (!is_object($context)) {
578 $context = context::instance_by_id($context);
579 }
118ca9e9
MG
580 $cachekey = 'rep:'. $repositoryid. ':'. $context->id. ':'. serialize($options);
581 if ($repository = $cache->get($cachekey)) {
582 return $repository;
583 }
67233725 584
118ca9e9
MG
585 if (!$record = $cache->get('i:'. $repositoryid)) {
586 $sql = "SELECT i.*, r.type AS repositorytype, r.visible, r.sortorder
587 FROM {repository_instances} i
588 JOIN {repository} r ON r.id = i.typeid
589 WHERE i.id = ?";
590 if (!$record = $DB->get_record_sql($sql, array($repositoryid))) {
591 throw new repository_exception('invalidrepositoryid', 'repository');
592 }
593 $cache->set('i:'. $record->id, $record);
594 }
67233725 595
118ca9e9
MG
596 $type = $record->repositorytype;
597 if (file_exists($CFG->dirroot . "/repository/$type/lib.php")) {
598 require_once($CFG->dirroot . "/repository/$type/lib.php");
599 $classname = 'repository_' . $type;
600 $options['type'] = $type;
601 $options['typeid'] = $record->typeid;
602 $options['visible'] = $record->visible;
603 if (empty($options['name'])) {
604 $options['name'] = $record->name;
605 }
606 $repository = new $classname($repositoryid, $context, $options, $record->readonly);
607 if (empty($repository->super_called)) {
608 // to make sure the super construct is called
609 debugging('parent::__construct must be called by '.$type.' plugin.');
67233725 610 }
118ca9e9
MG
611 $cache->set($cachekey, $repository);
612 return $repository;
613 } else {
614 throw new repository_exception('invalidplugin', 'repository');
67233725
DC
615 }
616 }
617
31581ae6
FM
618 /**
619 * Returns the type name of the repository.
620 *
621 * @return string type name of the repository.
622 * @since 2.5
623 */
624 public function get_typename() {
625 if (empty($this->typename)) {
626 $matches = array();
627 if (!preg_match("/^repository_(.*)$/", get_class($this), $matches)) {
628 throw new coding_exception('The class name of a repository should be repository_<typeofrepository>, '.
629 'e.g. repository_dropbox');
630 }
631 $this->typename = $matches[1];
632 }
633 return $this->typename;
634 }
635
dbc01944 636 /**
e35194be 637 * Get a repository type object by a given type name.
67233725
DC
638 *
639 * @static
e35194be
DC
640 * @param string $typename the repository type name
641 * @return repository_type|bool
dbc01944 642 */
643 public static function get_type_by_typename($typename) {
644 global $DB;
118ca9e9
MG
645 $cache = cache::make('core', 'repositories');
646 if (($repositorytype = $cache->get('typename:'. $typename)) === false) {
647 $repositorytype = null;
648 if ($record = $DB->get_record('repository', array('type' => $typename))) {
649 $repositorytype = new repository_type($record->type, (array)get_config($record->type), $record->visible, $record->sortorder);
650 $cache->set('typeid:'. $record->id, $repositorytype);
651 }
652 $cache->set('typename:'. $typename, $repositorytype);
dbc01944 653 }
118ca9e9 654 return $repositorytype;
dbc01944 655 }
656
657 /**
e35194be 658 * Get the repository type by a given repository type id.
67233725
DC
659 *
660 * @static
8e0946bf
DC
661 * @param int $id the type id
662 * @return object
dbc01944 663 */
664 public static function get_type_by_id($id) {
665 global $DB;
118ca9e9
MG
666 $cache = cache::make('core', 'repositories');
667 if (($repositorytype = $cache->get('typeid:'. $id)) === false) {
668 $repositorytype = null;
669 if ($record = $DB->get_record('repository', array('id' => $id))) {
670 $repositorytype = new repository_type($record->type, (array)get_config($record->type), $record->visible, $record->sortorder);
671 $cache->set('typename:'. $record->type, $repositorytype);
672 }
673 $cache->set('typeid:'. $id, $repositorytype);
dbc01944 674 }
118ca9e9 675 return $repositorytype;
dbc01944 676 }
677
678 /**
e35194be
DC
679 * Return all repository types ordered by sortorder field
680 * first repository type in returnedarray[0], second repository type in returnedarray[1], ...
67233725
DC
681 *
682 * @static
683 * @param bool $visible can return types by visiblity, return all types if null
dbc01944 684 * @return array Repository types
685 */
686 public static function get_types($visible=null) {
489d8a75 687 global $DB, $CFG;
118ca9e9
MG
688 $cache = cache::make('core', 'repositories');
689 if (!$visible) {
690 $typesnames = $cache->get('types');
691 } else {
692 $typesnames = $cache->get('typesvis');
dbc01944 693 }
118ca9e9
MG
694 $types = array();
695 if ($typesnames === false) {
696 $typesnames = array();
697 $vistypesnames = array();
698 if ($records = $DB->get_records('repository', null ,'sortorder')) {
699 foreach($records as $type) {
700 if (($repositorytype = $cache->get('typename:'. $type->type)) === false) {
701 // Create new instance of repository_type.
702 if (file_exists($CFG->dirroot . '/repository/'. $type->type .'/lib.php')) {
703 $repositorytype = new repository_type($type->type, (array)get_config($type->type), $type->visible, $type->sortorder);
704 $cache->set('typeid:'. $type->id, $repositorytype);
705 $cache->set('typename:'. $type->type, $repositorytype);
706 }
707 }
708 if ($repositorytype) {
709 if (empty($visible) || $repositorytype->get_visible()) {
710 $types[] = $repositorytype;
711 $vistypesnames[] = $repositorytype->get_typename();
712 }
713 $typesnames[] = $repositorytype->get_typename();
714 }
489d8a75 715 }
dbc01944 716 }
118ca9e9
MG
717 $cache->set('types', $typesnames);
718 $cache->set('typesvis', $vistypesnames);
719 } else {
720 foreach ($typesnames as $typename) {
721 $types[] = self::get_type_by_typename($typename);
722 }
dbc01944 723 }
dbc01944 724 return $types;
725 }
726
727 /**
31581ae6 728 * Checks if user has a capability to view the current repository.
67233725 729 *
31581ae6
FM
730 * @return bool true when the user can, otherwise throws an exception.
731 * @throws repository_exception when the user does not meet the requirements.
dbc01944 732 */
6dc82385 733 public final function check_capability() {
31581ae6
FM
734 global $USER;
735
e42861d4
FM
736 // The context we are on.
737 $currentcontext = $this->context;
738
31581ae6 739 // Ensure that the user can view the repository in the current context.
e42861d4 740 $can = has_capability('repository/'.$this->get_typename().':view', $currentcontext);
31581ae6
FM
741
742 // Context in which the repository has been created.
743 $repocontext = context::instance_by_id($this->instance->contextid);
744
745 // Prevent access to private repositories when logged in as.
746 if ($can && session_is_loggedinas()) {
747 if ($this->contains_private_data() || $repocontext->contextlevel == CONTEXT_USER) {
748 $can = false;
749 }
6dc82385 750 }
31581ae6 751
e42861d4
FM
752 // We are going to ensure that the current context was legit, and reliable to check
753 // the capability against. (No need to do that if we already cannot).
31581ae6 754 if ($can) {
e42861d4
FM
755 if ($repocontext->contextlevel == CONTEXT_USER) {
756 // The repository is a user instance, ensure we're the right user to access it!
757 if ($repocontext->instanceid != $USER->id) {
758 $can = false;
759 }
760 } else if ($repocontext->contextlevel == CONTEXT_COURSE) {
761 // The repository is a course one. Let's check that we are on the right course.
762 if (in_array($currentcontext->contextlevel, array(CONTEXT_COURSE, CONTEXT_MODULE, CONTEXT_BLOCK))) {
763 $coursecontext = $currentcontext->get_course_context();
764 if ($coursecontext->instanceid != $repocontext->instanceid) {
765 $can = false;
766 }
767 } else {
768 // We are on a parent context, therefore it's legit to check the permissions
769 // in the current context.
770 }
31581ae6 771 } else {
e42861d4
FM
772 // Nothing to check here, system instances can have different permissions on different
773 // levels. We do not want to prevent URL hack here, because it does not make sense to
774 // prevent a user to access a repository in a context if it's accessible in another one.
31581ae6
FM
775 }
776 }
777
778 if ($can) {
779 return true;
dbc01944 780 }
31581ae6
FM
781
782 throw new repository_exception('nopermissiontoaccess', 'repository');
dbc01944 783 }
784
f392caba 785 /**
d7d69396 786 * Check if file already exists in draft area.
f392caba 787 *
67233725 788 * @static
d7d69396
FM
789 * @param int $itemid of the draft area.
790 * @param string $filepath path to the file.
791 * @param string $filename file name.
67233725 792 * @return bool
f392caba
DC
793 */
794 public static function draftfile_exists($itemid, $filepath, $filename) {
795 global $USER;
796 $fs = get_file_storage();
21c08c63 797 $usercontext = context_user::instance($USER->id);
d7d69396 798 return $fs->file_exists($usercontext->id, 'user', 'draft', $itemid, $filepath, $filename);
f392caba
DC
799 }
800
c0e8f211
MG
801 /**
802 * Parses the 'source' returned by moodle repositories and returns an instance of stored_file
803 *
804 * @param string $source
805 * @return stored_file|null
806 */
807 public static function get_moodle_file($source) {
1bd01747
MG
808 $params = file_storage::unpack_reference($source, true);
809 $fs = get_file_storage();
810 return $fs->get_file($params['contextid'], $params['component'], $params['filearea'],
811 $params['itemid'], $params['filepath'], $params['filename']);
812 }
813
814 /**
815 * Repository method to make sure that user can access particular file.
816 *
817 * This is checked when user tries to pick the file from repository to deal with
818 * potential parameter substitutions is request
819 *
820 * @param string $source
821 * @return bool whether the file is accessible by current user
822 */
823 public function file_is_accessible($source) {
824 if ($this->has_moodle_files()) {
825 try {
826 $params = file_storage::unpack_reference($source, true);
827 } catch (file_reference_exception $e) {
828 return false;
c0e8f211 829 }
1bd01747 830 $browser = get_file_browser();
6dc82385 831 $context = context::instance_by_id($params['contextid']);
1bd01747
MG
832 $file_info = $browser->get_file_info($context, $params['component'], $params['filearea'],
833 $params['itemid'], $params['filepath'], $params['filename']);
834 return !empty($file_info);
c0e8f211 835 }
1bd01747 836 return true;
c0e8f211
MG
837 }
838
f392caba 839 /**
1bd01747
MG
840 * This function is used to copy a moodle file to draft area.
841 *
842 * It DOES NOT check if the user is allowed to access this file because the actual file
843 * can be located in the area where user does not have access to but there is an alias
844 * to this file in the area where user CAN access it.
845 * {@link file_is_accessible} should be called for alias location before calling this function.
f392caba 846 *
1bd01747 847 * @param string $source The metainfo of file, it is base64 encoded php serialized data
2dfa16ef
MG
848 * @param stdClass|array $filerecord contains itemid, filepath, filename and optionally other
849 * attributes of the new file
850 * @param int $maxbytes maximum allowed size of file, -1 if unlimited. If size of file exceeds
851 * the limit, the file_exception is thrown.
68acd115
FM
852 * @param int $areamaxbytes the maximum size of the area. A file_exception is thrown if the
853 * new file will reach the limit.
1bd01747 854 * @return array The information about the created file
f392caba 855 */
68acd115 856 public function copy_to_area($source, $filerecord, $maxbytes = -1, $areamaxbytes = FILE_AREA_MAX_BYTES_UNLIMITED) {
2dfa16ef 857 global $USER;
67233725 858 $fs = get_file_storage();
f392caba
DC
859
860 if ($this->has_moodle_files() == false) {
67233725 861 throw new coding_exception('Only repository used to browse moodle files can use repository::copy_to_area()');
f392caba
DC
862 }
863
2dfa16ef
MG
864 $user_context = context_user::instance($USER->id);
865
866 $filerecord = (array)$filerecord;
867 // make sure the new file will be created in user draft area
868 $filerecord['component'] = 'user';
869 $filerecord['filearea'] = 'draft';
870 $filerecord['contextid'] = $user_context->id;
871 $draftitemid = $filerecord['itemid'];
872 $new_filepath = $filerecord['filepath'];
873 $new_filename = $filerecord['filename'];
f392caba 874
f392caba 875 // the file needs to copied to draft area
1bd01747
MG
876 $stored_file = self::get_moodle_file($source);
877 if ($maxbytes != -1 && $stored_file->get_filesize() > $maxbytes) {
2dfa16ef
MG
878 throw new file_exception('maxbytes');
879 }
68acd115
FM
880 // Validate the size of the draft area.
881 if (file_is_draft_area_limit_reached($draftitemid, $areamaxbytes, $stored_file->get_filesize())) {
882 throw new file_exception('maxareabytes');
883 }
f392caba
DC
884
885 if (repository::draftfile_exists($draftitemid, $new_filepath, $new_filename)) {
886 // create new file
887 $unused_filename = repository::get_unused_filename($draftitemid, $new_filepath, $new_filename);
2dfa16ef 888 $filerecord['filename'] = $unused_filename;
1bd01747 889 $fs->create_file_from_storedfile($filerecord, $stored_file);
f392caba
DC
890 $event = array();
891 $event['event'] = 'fileexists';
892 $event['newfile'] = new stdClass;
893 $event['newfile']->filepath = $new_filepath;
894 $event['newfile']->filename = $unused_filename;
895 $event['newfile']->url = moodle_url::make_draftfile_url($draftitemid, $new_filepath, $unused_filename)->out();
896 $event['existingfile'] = new stdClass;
897 $event['existingfile']->filepath = $new_filepath;
898 $event['existingfile']->filename = $new_filename;
1bd01747 899 $event['existingfile']->url = moodle_url::make_draftfile_url($draftitemid, $new_filepath, $new_filename)->out();
f392caba
DC
900 return $event;
901 } else {
1bd01747 902 $fs->create_file_from_storedfile($filerecord, $stored_file);
f392caba
DC
903 $info = array();
904 $info['itemid'] = $draftitemid;
1bd01747
MG
905 $info['file'] = $new_filename;
906 $info['title'] = $new_filename;
f392caba 907 $info['contextid'] = $user_context->id;
1bd01747
MG
908 $info['url'] = moodle_url::make_draftfile_url($draftitemid, $new_filepath, $new_filename)->out();
909 $info['filesize'] = $stored_file->get_filesize();
f392caba
DC
910 return $info;
911 }
912 }
913
914 /**
d7d69396
FM
915 * Get an unused filename from the current draft area.
916 *
917 * Will check if the file ends with ([0-9]) and increase the number.
f392caba 918 *
67233725 919 * @static
d7d69396
FM
920 * @param int $itemid draft item ID.
921 * @param string $filepath path to the file.
922 * @param string $filename name of the file.
923 * @return string an unused file name.
f392caba
DC
924 */
925 public static function get_unused_filename($itemid, $filepath, $filename) {
926 global $USER;
d7d69396 927 $contextid = context_user::instance($USER->id)->id;
f392caba 928 $fs = get_file_storage();
d7d69396 929 return $fs->get_unused_filename($contextid, 'user', 'draft', $itemid, $filepath, $filename);
f392caba
DC
930 }
931
932 /**
d7d69396 933 * Append a suffix to filename.
f392caba 934 *
67233725 935 * @static
f392caba
DC
936 * @param string $filename
937 * @return string
d7d69396 938 * @deprecated since 2.5
f392caba 939 */
061eeed5 940 public static function append_suffix($filename) {
d7d69396
FM
941 debugging('The function repository::append_suffix() has been deprecated. Use repository::get_unused_filename() instead.',
942 DEBUG_DEVELOPER);
f392caba
DC
943 $pathinfo = pathinfo($filename);
944 if (empty($pathinfo['extension'])) {
945 return $filename . RENAME_SUFFIX;
946 } else {
947 return $pathinfo['filename'] . RENAME_SUFFIX . '.' . $pathinfo['extension'];
948 }
949 }
950
dbc01944 951 /**
952 * Return all types that you a user can create/edit and which are also visible
953 * Note: Mostly used in order to know if at least one editable type can be set
67233725
DC
954 *
955 * @static
956 * @param stdClass $context the context for which we want the editable types
dbc01944 957 * @return array types
958 */
959 public static function get_editable_types($context = null) {
960
961 if (empty($context)) {
0601e0ee 962 $context = context_system::instance();
dbc01944 963 }
964
965 $types= repository::get_types(true);
966 $editabletypes = array();
967 foreach ($types as $type) {
968 $instanceoptionnames = repository::static_function($type->get_typename(), 'get_instance_option_names');
969 if (!empty($instanceoptionnames)) {
5363905a 970 if ($type->get_contextvisibility($context)) {
dbc01944 971 $editabletypes[]=$type;
972 }
973 }
974 }
975 return $editabletypes;
976 }
977
978 /**
979 * Return repository instances
92a89068 980 *
67233725 981 * @static
92a89068 982 * @param array $args Array containing the following keys:
118ca9e9
MG
983 * currentcontext : instance of context (default system context)
984 * context : array of instances of context (default empty array)
985 * onlyvisible : bool (default true)
986 * type : string return instances of this type only
987 * accepted_types : string|array return instances that contain files of those types (*, web_image, .pdf, ...)
5ab1b982
FM
988 * return_types : int combination of FILE_INTERNAL & FILE_EXTERNAL & FILE_REFERENCE.
989 * 0 means every type. The default is FILE_INTERNAL | FILE_EXTERNAL.
118ca9e9 990 * userid : int if specified, instances belonging to other users will not be returned
92a89068 991 *
dbc01944 992 * @return array repository instances
993 */
6f2cd52a 994 public static function get_instances($args = array()) {
dbc01944 995 global $DB, $CFG, $USER;
996
118ca9e9
MG
997 // Fill $args attributes with default values unless specified
998 if (!isset($args['currentcontext']) || !($args['currentcontext'] instanceof context)) {
999 $current_context = context_system::instance();
6f2cd52a 1000 } else {
118ca9e9 1001 $current_context = $args['currentcontext'];
6f2cd52a 1002 }
118ca9e9
MG
1003 $args['currentcontext'] = $current_context->id;
1004 $contextids = array();
6f2cd52a 1005 if (!empty($args['context'])) {
118ca9e9
MG
1006 foreach ($args['context'] as $context) {
1007 $contextids[] = $context->id;
1008 }
1009 }
1010 $args['context'] = $contextids;
1011 if (!isset($args['onlyvisible'])) {
1012 $args['onlyvisible'] = true;
1013 }
1014 if (!isset($args['return_types'])) {
5ab1b982 1015 $args['return_types'] = FILE_INTERNAL | FILE_EXTERNAL;
118ca9e9
MG
1016 }
1017 if (!isset($args['type'])) {
1018 $args['type'] = null;
1019 }
1020 if (empty($args['disable_types']) || !is_array($args['disable_types'])) {
1021 $args['disable_types'] = null;
6f2cd52a 1022 }
118ca9e9
MG
1023 if (empty($args['userid']) || !is_numeric($args['userid'])) {
1024 $args['userid'] = null;
1025 }
1026 if (!isset($args['accepted_types']) || (is_array($args['accepted_types']) && in_array('*', $args['accepted_types']))) {
1027 $args['accepted_types'] = '*';
1028 }
1029 ksort($args);
1030 $cachekey = 'all:'. serialize($args);
6f2cd52a 1031
118ca9e9
MG
1032 // Check if we have cached list of repositories with the same query
1033 $cache = cache::make('core', 'repositories');
1034 if (($cachedrepositories = $cache->get($cachekey)) !== false) {
1035 // convert from cacheable_object_array to array
1036 $repositories = array();
1037 foreach ($cachedrepositories as $repository) {
1038 $repositories[$repository->id] = $repository;
1039 }
1040 return $repositories;
1041 }
6f2cd52a 1042
118ca9e9 1043 // Prepare DB SQL query to retrieve repositories
dbc01944 1044 $params = array();
a090554a
PS
1045 $sql = "SELECT i.*, r.type AS repositorytype, r.sortorder, r.visible
1046 FROM {repository} r, {repository_instances} i
1047 WHERE i.typeid = r.id ";
dbc01944 1048
118ca9e9
MG
1049 if ($args['disable_types']) {
1050 list($types, $p) = $DB->get_in_or_equal($args['disable_types'], SQL_PARAMS_NAMED, 'distype', false);
a090554a 1051 $sql .= " AND r.type $types";
227dfa43
DC
1052 $params = array_merge($params, $p);
1053 }
1054
118ca9e9
MG
1055 if ($args['userid']) {
1056 $sql .= " AND (i.userid = 0 or i.userid = :userid)";
1057 $params['userid'] = $args['userid'];
dbc01944 1058 }
227dfa43 1059
118ca9e9
MG
1060 if ($args['context']) {
1061 list($ctxsql, $p2) = $DB->get_in_or_equal($args['context'], SQL_PARAMS_NAMED, 'ctx');
1062 $sql .= " AND i.contextid $ctxsql";
1063 $params = array_merge($params, $p2);
dbc01944 1064 }
1065
118ca9e9
MG
1066 if ($args['onlyvisible'] == true) {
1067 $sql .= " AND r.visible = 1";
dbc01944 1068 }
1069
118ca9e9
MG
1070 if ($args['type'] !== null) {
1071 $sql .= " AND r.type = :type";
1072 $params['type'] = $args['type'];
dbc01944 1073 }
a090554a 1074 $sql .= " ORDER BY r.sortorder, i.name";
50a5cf09 1075
6f2cd52a
DC
1076 if (!$records = $DB->get_records_sql($sql, $params)) {
1077 $records = array();
dbc01944 1078 }
1079
6f2cd52a 1080 $repositories = array();
fdb0322d
DS
1081 // Sortorder should be unique, which is not true if we use $record->sortorder
1082 // and there are multiple instances of any repository type
1083 $sortorder = 1;
6f2cd52a 1084 foreach ($records as $record) {
118ca9e9 1085 $cache->set('i:'. $record->id, $record);
e35194be 1086 if (!file_exists($CFG->dirroot . '/repository/'. $record->repositorytype.'/lib.php')) {
062d21cd
DC
1087 continue;
1088 }
118ca9e9 1089 $repository = self::get_repository_by_id($record->id, $current_context);
cfb71351 1090 $repository->options['sortorder'] = $sortorder++;
6f2cd52a 1091
014c1ca0 1092 $is_supported = true;
dbc01944 1093
118ca9e9
MG
1094 // check mimetypes
1095 if ($args['accepted_types'] !== '*' and $repository->supported_filetypes() !== '*') {
1096 $accepted_ext = file_get_typegroup('extension', $args['accepted_types']);
1097 $supported_ext = file_get_typegroup('extension', $repository->supported_filetypes());
1098 $valid_ext = array_intersect($accepted_ext, $supported_ext);
1099 $is_supported = !empty($valid_ext);
1100 }
5ab1b982
FM
1101 // Check return values.
1102 if (!empty($args['return_types']) && !($repository->supported_returntypes() & $args['return_types'])) {
118ca9e9
MG
1103 $is_supported = false;
1104 }
d3959c26 1105
118ca9e9
MG
1106 if (!$args['onlyvisible'] || ($repository->is_visible() && !$repository->disabled)) {
1107 // check capability in current context
1108 $capability = has_capability('repository/'.$record->repositorytype.':view', $current_context);
1109 if ($record->repositorytype == 'coursefiles') {
1110 // coursefiles plugin needs managefiles permission
1111 $capability = $capability && has_capability('moodle/course:managefiles', $current_context);
1112 }
1113 if ($is_supported && $capability) {
1114 $repositories[$repository->id] = $repository;
014c1ca0 1115 }
dbc01944 1116 }
1117 }
118ca9e9 1118 $cache->set($cachekey, new cacheable_object_array($repositories));
6f2cd52a 1119 return $repositories;
dbc01944 1120 }
1121
1122 /**
cfb71351
MG
1123 * Get single repository instance for administrative actions
1124 *
1125 * Do not use this function to access repository contents, because it
1126 * does not set the current context
1127 *
f6812f57 1128 * @see repository::get_repository_by_id()
67233725
DC
1129 *
1130 * @static
cfb71351
MG
1131 * @param integer $id repository instance id
1132 * @return repository
dbc01944 1133 */
1134 public static function get_instance($id) {
cfb71351 1135 return self::get_repository_by_id($id, context_system::instance());
dbc01944 1136 }
1137
1138 /**
e35194be 1139 * Call a static function. Any additional arguments than plugin and function will be passed through.
67233725
DC
1140 *
1141 * @static
1142 * @param string $plugin repository plugin name
a1070d3f 1143 * @param string $function function name
2b8beee3 1144 * @return mixed
dbc01944 1145 */
1146 public static function static_function($plugin, $function) {
1147 global $CFG;
1148
1149 //check that the plugin exists
e35194be 1150 $typedirectory = $CFG->dirroot . '/repository/'. $plugin . '/lib.php';
dbc01944 1151 if (!file_exists($typedirectory)) {
f1cfe56e 1152 //throw new repository_exception('invalidplugin', 'repository');
1153 return false;
dbc01944 1154 }
1155
dbc01944 1156 $args = func_get_args();
1157 if (count($args) <= 2) {
1158 $args = array();
e35194be 1159 } else {
dbc01944 1160 array_shift($args);
1161 array_shift($args);
1162 }
1163
1164 require_once($typedirectory);
81bdfdb9 1165 return call_user_func_array(array('repository_' . $plugin, $function), $args);
dbc01944 1166 }
1167
23bfe0a4
PS
1168 /**
1169 * Scan file, throws exception in case of infected file.
1170 *
1171 * Please note that the scanning engine must be able to access the file,
1172 * permissions of the file are not modified here!
1173 *
1174 * @static
1175 * @param string $thefile
1176 * @param string $filename name of the file
1177 * @param bool $deleteinfected
23bfe0a4
PS
1178 */
1179 public static function antivir_scan_file($thefile, $filename, $deleteinfected) {
1180 global $CFG;
1181
1182 if (!is_readable($thefile)) {
1183 // this should not happen
1184 return;
1185 }
1186
1187 if (empty($CFG->runclamonupload) or empty($CFG->pathtoclam)) {
1188 // clam not enabled
1189 return;
1190 }
1191
1192 $CFG->pathtoclam = trim($CFG->pathtoclam);
1193
1194 if (!file_exists($CFG->pathtoclam) or !is_executable($CFG->pathtoclam)) {
1195 // misconfigured clam - use the old notification for now
1196 require("$CFG->libdir/uploadlib.php");
1197 $notice = get_string('clamlost', 'moodle', $CFG->pathtoclam);
1198 clam_message_admins($notice);
1199 return;
1200 }
1201
ef7dd02c
RK
1202 $clamparam = ' --stdout ';
1203 // If we are dealing with clamdscan, clamd is likely run as a different user
1204 // that might not have permissions to access your file.
1205 // To make clamdscan work, we use --fdpass parameter that passes the file
1206 // descriptor permissions to clamd, which allows it to scan given file
1207 // irrespective of directory and file permissions.
1208 if (basename($CFG->pathtoclam) == 'clamdscan') {
1209 $clamparam .= '--fdpass ';
1210 }
23bfe0a4 1211 // execute test
ef7dd02c 1212 $cmd = escapeshellcmd($CFG->pathtoclam).$clamparam.escapeshellarg($thefile);
23bfe0a4
PS
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 1587 $params['currentcontext'] = $context;
5ab1b982 1588 $params['return_types'] = 0;
6f2cd52a
DC
1589 $params['onlyvisible'] = !$admin;
1590 $params['type'] = $typename;
1591 $instances = repository::get_instances($params);
dbc01944 1592 $instancesnumber = count($instances);
1593 $alreadyplugins = array();
1594
55400db0 1595 $table = new html_table();
79698344 1596 $table->head = array($namestr, $pluginstr, $settingsstr, $deletestr);
dbc01944 1597 $table->align = array('left', 'left', 'center','center');
1598 $table->data = array();
1599
1600 $updowncount = 1;
1601
1602 foreach ($instances as $i) {
1603 $settings = '';
1604 $delete = '';
5363905a
DC
1605
1606 $type = repository::get_type_by_id($i->options['typeid']);
1607
1608 if ($type->get_contextvisibility($context)) {
1609 if (!$i->readonly) {
1610
67233725
DC
1611 $settingurl = new moodle_url($baseurl);
1612 $settingurl->param('type', $i->options['type']);
1613 $settingurl->param('edit', $i->id);
1614 $settings .= html_writer::link($settingurl, $settingsstr);
5363905a 1615
67233725
DC
1616 $deleteurl = new moodle_url($baseurl);
1617 $deleteurl->param('delete', $i->id);
1618 $deleteurl->param('type', $i->options['type']);
1619 $delete .= html_writer::link($deleteurl, $deletestr);
5363905a 1620 }
dbc01944 1621 }
1622
a3d8df25 1623 $type = repository::get_type_by_id($i->options['typeid']);
8655fb96 1624 $table->data[] = array(format_string($i->name), $type->get_readablename(), $settings, $delete);
dbc01944 1625
1626 //display a grey row if the type is defined as not visible
1627 if (isset($type) && !$type->get_visible()) {
704ac344 1628 $table->rowclasses[] = 'dimmed_text';
dbc01944 1629 } else {
704ac344 1630 $table->rowclasses[] = '';
dbc01944 1631 }
1632
1633 if (!in_array($i->name, $alreadyplugins)) {
1634 $alreadyplugins[] = $i->name;
1635 }
1636 }
16be8974 1637 $output .= html_writer::table($table);
dbc01944 1638 $instancehtml = '<div>';
1639 $addable = 0;
1640
1641 //if no type is set, we can create all type of instance
1642 if (!$typename) {
1643 $instancehtml .= '<h3>';
1644 $instancehtml .= get_string('createrepository', 'repository');
1645 $instancehtml .= '</h3><ul>';
1646 $types = repository::get_editable_types($context);
1647 foreach ($types as $type) {
1648 if (!empty($type) && $type->get_visible()) {
2c869550
FM
1649 // If the user does not have the permission to view the repository, it won't be displayed in
1650 // the list of instances. Hiding the link to create new instances will prevent the
1651 // user from creating them without being able to find them afterwards, which looks like a bug.
1652 if (!has_capability('repository/'.$type->get_typename().':view', $context)) {
1653 continue;
1654 }
dbc01944 1655 $instanceoptionnames = repository::static_function($type->get_typename(), 'get_instance_option_names');
1656 if (!empty($instanceoptionnames)) {
e35194be
DC
1657 $baseurl->param('new', $type->get_typename());
1658 $instancehtml .= '<li><a href="'.$baseurl->out().'">'.get_string('createxxinstance', 'repository', get_string('pluginname', 'repository_'.$type->get_typename())). '</a></li>';
1659 $baseurl->remove_params('new');
dbc01944 1660 $addable++;
1661 }
1662 }
1663 }
1664 $instancehtml .= '</ul>';
1665
1666 } else {
1667 $instanceoptionnames = repository::static_function($typename, 'get_instance_option_names');
1668 if (!empty($instanceoptionnames)) { //create a unique type of instance
1669 $addable = 1;
e35194be 1670 $baseurl->param('new', $typename);
67233725 1671 $output .= $OUTPUT->single_button($baseurl, get_string('createinstance', 'repository'), 'get');
e35194be 1672 $baseurl->remove_params('new');
dbc01944 1673 }
1674 }
1675
1676 if ($addable) {
1677 $instancehtml .= '</div>';
1678 $output .= $instancehtml;
1679 }
1680
50a5cf09 1681 $output .= $OUTPUT->box_end();
dbc01944 1682
1683 //print the list + creation links
1684 print($output);
1685 }
1cf56396 1686
67233725
DC
1687 /**
1688 * Prepare file reference information
1689 *
1690 * @param string $source
1691 * @return string file referece
1692 */
1693 public function get_file_reference($source) {
0b2bfbd1
MG
1694 if ($this->has_moodle_files() && ($this->supported_returntypes() & FILE_REFERENCE)) {
1695 $params = file_storage::unpack_reference($source);
1696 if (!is_array($params)) {
1697 throw new repository_exception('invalidparams', 'repository');
1698 }
1699 return file_storage::pack_reference($params);
1700 }
67233725
DC
1701 return $source;
1702 }
72a56555 1703
c425472d 1704 /**
e35194be 1705 * Decide where to save the file, can be overwriten by subclass
67233725
DC
1706 *
1707 * @param string $filename file name
1708 * @return file path
c425472d 1709 */
a560785f 1710 public function prepare_file($filename) {
c425472d 1711 global $CFG;
72a56555
MG
1712 $dir = make_temp_directory('download/'.get_class($this).'/');
1713 while (empty($filename) || file_exists($dir.$filename)) {
1714 $filename = uniqid('', true).'_'.time().'.tmp';
c425472d 1715 }
a560785f 1716 return $dir.$filename;
a53d4f45 1717 }
1718
67233725
DC
1719 /**
1720 * Does this repository used to browse moodle files?
1721 *
1722 * @return bool
1723 */
1724 public function has_moodle_files() {
1725 return false;
1726 }
1727
99d52655
DC
1728 /**
1729 * Return file URL, for most plugins, the parameter is the original
1730 * url, but some plugins use a file id, so we need this function to
1731 * convert file id to original url.
1732 *
1733 * @param string $url the url of file
8e0946bf 1734 * @return string
99d52655
DC
1735 */
1736 public function get_link($url) {
1737 return $url;
1738 }
1739
a53d4f45 1740 /**
72a56555 1741 * Downloads a file from external repository and saves it in temp dir
a53d4f45 1742 *
72a56555
MG
1743 * Function get_file() must be implemented by repositories that support returntypes
1744 * FILE_INTERNAL or FILE_REFERENCE. It is invoked to pick up the file and copy it
1745 * to moodle. This function is not called for moodle repositories, the function
1746 * {@link repository::copy_to_area()} is used instead.
1747 *
1748 * This function can be overridden by subclass if the files.reference field contains
1749 * not just URL or if request should be done differently.
1750 *
1751 * @see curl
1752 * @throws file_exception when error occured
1753 *
1754 * @param string $url the content of files.reference field, in this implementaion
1755 * it is asssumed that it contains the string with URL of the file
1756 * @param string $filename filename (without path) to save the downloaded file in the
1757 * temporary directory, if omitted or file already exists the new filename will be generated
0b2bfbd1
MG
1758 * @return array with elements:
1759 * path: internal location of the file
1760 * url: URL to the source (from parameters)
a53d4f45 1761 */
a560785f 1762 public function get_file($url, $filename = '') {
41076c58 1763 $path = $this->prepare_file($filename);
41076c58 1764 $c = new curl;
72a56555
MG
1765 $result = $c->download_one($url, null, array('filepath' => $path, 'timeout' => self::GETFILE_TIMEOUT));
1766 if ($result !== true) {
1767 throw new moodle_exception('errorwhiledownload', 'repository', '', $result);
0b2bfbd1 1768 }
1dce6261 1769 return array('path'=>$path, 'url'=>$url);
82669dc4 1770 }
1cf56396 1771
bc6f241c
MG
1772 /**
1773 * Downloads the file from external repository and saves it in moodle filepool.
1774 * This function is different from {@link repository::sync_external_file()} because it has
1775 * bigger request timeout and always downloads the content.
1776 *
1777 * This function is invoked when we try to unlink the file from the source and convert
1778 * a reference into a true copy.
1779 *
1780 * @throws exception when file could not be imported
1781 *
1782 * @param stored_file $file
1783 * @param int $maxbytes throw an exception if file size is bigger than $maxbytes (0 means no limit)
1784 */
1785 public function import_external_file_contents(stored_file $file, $maxbytes = 0) {
1786 if (!$file->is_external_file()) {
1787 // nothing to import if the file is not a reference
1788 return;
1789 } else if ($file->get_repository_id() != $this->id) {
1790 // error
1791 debugging('Repository instance id does not match');
1792 return;
1793 } else if ($this->has_moodle_files()) {
1794 // files that are references to local files are already in moodle filepool
1795 // just validate the size
1796 if ($maxbytes > 0 && $file->get_filesize() > $maxbytes) {
1797 throw new file_exception('maxbytes');
1798 }
1799 return;
1800 } else {
1801 if ($maxbytes > 0 && $file->get_filesize() > $maxbytes) {
1802 // note that stored_file::get_filesize() also calls synchronisation
1803 throw new file_exception('maxbytes');
1804 }
1805 $fs = get_file_storage();
1806 $contentexists = $fs->content_exists($file->get_contenthash());
1807 if ($contentexists && $file->get_filesize() && $file->get_contenthash() === sha1('')) {
1808 // even when 'file_storage::content_exists()' returns true this may be an empty
1809 // content for the file that was not actually downloaded
1810 $contentexists = false;
1811 }
1812 $now = time();
1813 if ($file->get_referencelastsync() + $file->get_referencelifetime() >= $now &&
1814 !$file->get_status() &&
1815 $contentexists) {
1816 // we already have the content in moodle filepool and it was synchronised recently.
1817 // Repositories may overwrite it if they want to force synchronisation anyway!
1818 return;
1819 } else {
1820 // attempt to get a file
1821 try {
1822 $fileinfo = $this->get_file($file->get_reference());
1823 if (isset($fileinfo['path'])) {
1824 list($contenthash, $filesize, $newfile) = $fs->add_file_to_pool($fileinfo['path']);
1825 // set this file and other similar aliases synchronised
1826 $lifetime = $this->get_reference_file_lifetime($file->get_reference());
1827 $file->set_synchronized($contenthash, $filesize, 0, $lifetime);
1828 } else {
1829 throw new moodle_exception('errorwhiledownload', 'repository', '', '');
1830 }
1831 } catch (Exception $e) {
1832 if ($contentexists) {
1833 // better something than nothing. We have a copy of file. It's sync time
1834 // has expired but it is still very likely that it is the last version
1835 } else {
1836 throw($e);
1837 }
1838 }
1839 }
1840 }
1841 }
1842
c0d60b3a
AKA
1843 /**
1844 * Return size of a file in bytes.
1845 *
1846 * @param string $source encoded and serialized data of file
67233725 1847 * @return int file size in bytes
c0d60b3a
AKA
1848 */
1849 public function get_file_size($source) {
2dfa16ef 1850 // TODO MDL-33297 remove this function completely?
c0d60b3a
AKA
1851 $browser = get_file_browser();
1852 $params = unserialize(base64_decode($source));
1853 $contextid = clean_param($params['contextid'], PARAM_INT);
1854 $fileitemid = clean_param($params['itemid'], PARAM_INT);
1855 $filename = clean_param($params['filename'], PARAM_FILE);
1856 $filepath = clean_param($params['filepath'], PARAM_PATH);
aff24313
PS
1857 $filearea = clean_param($params['filearea'], PARAM_AREA);
1858 $component = clean_param($params['component'], PARAM_COMPONENT);
d197ea43 1859 $context = context::instance_by_id($contextid);
c0d60b3a
AKA
1860 $file_info = $browser->get_file_info($context, $component, $filearea, $fileitemid, $filepath, $filename);
1861 if (!empty($file_info)) {
1862 $filesize = $file_info->get_filesize();
1863 } else {
1864 $filesize = null;
1865 }
1866 return $filesize;
1867 }
1868
f48fb4d6 1869 /**
1870 * Return is the instance is visible
1871 * (is the type visible ? is the context enable ?)
67233725
DC
1872 *
1873 * @return bool
f48fb4d6 1874 */
dbc01944 1875 public function is_visible() {
7d554b64 1876 $type = repository::get_type_by_id($this->options['typeid']);
dbc01944 1877 $instanceoptions = repository::static_function($type->get_typename(), 'get_instance_option_names');
f48fb4d6 1878
1879 if ($type->get_visible()) {
1880 //if the instance is unique so it's visible, otherwise check if the instance has a enabled context
f6812f57 1881 if (empty($instanceoptions) || $type->get_contextvisibility(context::instance_by_id($this->instance->contextid))) {
f48fb4d6 1882 return true;
1883 }
1884 }
1885
1886 return false;
1887 }
1888
89a9d21a
FM
1889 /**
1890 * Can the instance be edited by the current user?
1891 *
1892 * The property $readonly must not be used within this method because
1893 * it only controls if the options from self::get_instance_option_names()
1894 * can be edited.
1895 *
1896 * @return bool true if the user can edit the instance.
1897 * @since 2.5
1898 */
1899 public final function can_be_edited_by_user() {
1900 global $USER;
1901
1902 // We need to be able to explore the repository.
1903 try {
1904 $this->check_capability();
1905 } catch (repository_exception $e) {
1906 return false;
1907 }
1908
1909 $repocontext = context::instance_by_id($this->instance->contextid);
1910 if ($repocontext->contextlevel == CONTEXT_USER && $repocontext->instanceid != $USER->id) {
1911 // If the context of this instance is a user context, we need to be this user.
1912 return false;
1913 } else if ($repocontext->contextlevel == CONTEXT_MODULE && !has_capability('moodle/course:update', $repocontext)) {
1914 // We need to have permissions on the course to edit the instance.
1915 return false;
1916 } else if ($repocontext->contextlevel == CONTEXT_SYSTEM && !has_capability('moodle/site:config', $repocontext)) {
1917 // Do not meet the requirements for the context system.
1918 return false;
1919 }
1920
1921 return true;
1922 }
1923
eb239694 1924 /**
66dc47bc 1925 * Return the name of this instance, can be overridden.
67233725 1926 *
2b8beee3 1927 * @return string
eb239694 1928 */
7a3b93c1 1929 public function get_name() {
31581ae6 1930 if ($name = $this->instance->name) {
a5adfa26 1931 return $name;
d31af46a 1932 } else {
31581ae6 1933 return get_string('pluginname', 'repository_' . $this->get_typename());
d31af46a 1934 }
1935 }
aa754fe3 1936
31581ae6
FM
1937 /**
1938 * Is this repository accessing private data?
1939 *
1940 * This function should return true for the repositories which access external private
1941 * data from a user. This is the case for repositories such as Dropbox, Google Docs or Box.net
1942 * which authenticate the user and then store the auth token.
1943 *
1944 * Of course, many repositories store 'private data', but we only want to set
1945 * contains_private_data() to repositories which are external to Moodle and shouldn't be accessed
1946 * to by the users having the capability to 'login as' someone else. For instance, the repository
1947 * 'Private files' is not considered as private because it's part of Moodle.
1948 *
1949 * You should not set contains_private_data() to true on repositories which allow different types
1950 * of instances as the levels other than 'user' are, by definition, not private. Also
1951 * the user instances will be protected when they need to.
1952 *
1953 * @return boolean True when the repository accesses private external data.
1954 * @since 2.5
1955 */
1956 public function contains_private_data() {
1957 return true;
1958 }
1959
b318bb6d 1960 /**
67233725
DC
1961 * What kind of files will be in this repository?
1962 *
b318bb6d 1963 * @return array return '*' means this repository support any files, otherwise
1964 * return mimetypes of files, it can be an array
1965 */
014c1ca0 1966 public function supported_filetypes() {
b318bb6d 1967 // return array('text/plain', 'image/gif');
1968 return '*';
1969 }
1970
1971 /**
c8161eec 1972 * Tells how the file can be picked from this repository
67233725 1973 *
c8161eec
MG
1974 * Maximum value is FILE_INTERNAL | FILE_EXTERNAL | FILE_REFERENCE
1975 *
1976 * @return int
b318bb6d 1977 */
41076c58 1978 public function supported_returntypes() {
c8161eec 1979 return (FILE_INTERNAL | FILE_EXTERNAL);
92eaeca5 1980 }
b318bb6d 1981
82669dc4 1982 /**
3f24ea1e 1983 * Provide repository instance information for Ajax
67233725
DC
1984 *
1985 * @return stdClass
82669dc4 1986 */
7d554b64 1987 final public function get_meta() {
c82d7320 1988 global $CFG, $OUTPUT;
6bdfef5d 1989 $meta = new stdClass();
7d554b64 1990 $meta->id = $this->id;
102f9286 1991 $meta->name = format_string($this->get_name());
31581ae6 1992 $meta->type = $this->get_typename();
c82d7320 1993 $meta->icon = $OUTPUT->pix_url('icon', 'repository_'.$meta->type)->out(false);
559276b1 1994 $meta->supported_types = file_get_typegroup('extension', $this->supported_filetypes());
6f2cd52a 1995 $meta->return_types = $this->supported_returntypes();
36ef6643 1996 $meta->sortorder = $this->options['sortorder'];
7d554b64 1997 return $meta;
4a65c39a 1998 }
1cf56396 1999
b1339e98 2000 /**
2001 * Create an instance for this plug-in
67233725
DC
2002 *
2003 * @static
8dcd5deb 2004 * @param string $type the type of the repository
67233725
DC
2005 * @param int $userid the user id
2006 * @param stdClass $context the context
8dcd5deb 2007 * @param array $params the options for this instance
67233725 2008 * @param int $readonly whether to create it readonly or not (defaults to not)
2b8beee3 2009 * @return mixed
b1339e98 2010 */
49d20def 2011 public static function create($type, $userid, $context, $params, $readonly=0) {
b1339e98 2012 global $CFG, $DB;
2013 $params = (array)$params;
e35194be 2014 require_once($CFG->dirroot . '/repository/'. $type . '/lib.php');
b1339e98 2015 $classname = 'repository_' . $type;
3023078f 2016 if ($repo = $DB->get_record('repository', array('type'=>$type))) {
6bdfef5d 2017 $record = new stdClass();
3023078f 2018 $record->name = $params['name'];
2019 $record->typeid = $repo->id;
2020 $record->timecreated = time();
2021 $record->timemodified = time();
2022 $record->contextid = $context->id;
948c2860 2023 $record->readonly = $readonly;
3023078f 2024 $record->userid = $userid;
2025 $id = $DB->insert_record('repository_instances', $record);
118ca9e9 2026 cache::make('core', 'repositories')->purge();
0a6221f9 2027 $options = array();
edb50637 2028 $configs = call_user_func($classname . '::get_instance_option_names');
1e08b5cf 2029 if (!empty($configs)) {
2030 foreach ($configs as $config) {
14b2d8d8
DC
2031 if (isset($params[$config])) {
2032 $options[$config] = $params[$config];
2033 } else {
2034 $options[$config] = null;
2035 }
1e08b5cf 2036 }
3023078f 2037 }
3a01a46a 2038
3023078f 2039 if (!empty($id)) {
2040 unset($options['name']);
dbc01944 2041 $instance = repository::get_instance($id);
3023078f 2042 $instance->set_option($options);
2043 return $id;
2044 } else {
2045 return null;
b1339e98 2046 }
b1339e98 2047 } else {
2048 return null;
2049 }
2050 }
8dcd5deb 2051
82669dc4 2052 /**
4a65c39a 2053 * delete a repository instance
67233725
DC
2054 *
2055 * @param bool $downloadcontents
2056 * @return bool
82669dc4 2057 */
67233725 2058 final public function delete($downloadcontents = false) {
4a65c39a 2059 global $DB;
67233725
DC
2060 if ($downloadcontents) {
2061 $this->convert_references_to_local();
2062 }
118ca9e9 2063 cache::make('core', 'repositories')->purge();
67233725
DC
2064 try {
2065 $DB->delete_records('repository_instances', array('id'=>$this->id));
2066 $DB->delete_records('repository_instance_config', array('instanceid'=>$this->id));
2067 } catch (dml_exception $ex) {
2068 return false;
2069 }
4a65c39a 2070 return true;
2071 }
8dcd5deb 2072
d802435e
FM
2073 /**
2074 * Delete all the instances associated to a context.
2075 *
2076 * This method is intended to be a callback when deleting
2077 * a course or a user to delete all the instances associated
2078 * to their context. The usual way to delete a single instance
2079 * is to use {@link self::delete()}.
2080 *
2081 * @param int $contextid context ID.
2082 * @param boolean $downloadcontents true to convert references to hard copies.
2083 * @return void
2084 */
2085 final public static function delete_all_for_context($contextid, $downloadcontents = true) {
2086 global $DB;
2087 $repoids = $DB->get_fieldset_select('repository_instances', 'id', 'contextid = :contextid', array('contextid' => $contextid));
2088 if ($downloadcontents) {
2089 foreach ($repoids as $repoid) {
2090 $repo = repository::get_repository_by_id($repoid, $contextid);
2091 $repo->convert_references_to_local();
2092 }
2093 }
2094 cache::make('core', 'repositories')->purge();
2095 $DB->delete_records_list('repository_instances', 'id', $repoids);
2096 $DB->delete_records_list('repository_instance_config', 'instanceid', $repoids);
2097 }
2098
4a65c39a 2099 /**
2100 * Hide/Show a repository
67233725 2101 *
8dcd5deb 2102 * @param string $hide
67233725 2103 * @return bool
4a65c39a 2104 */
7a3b93c1 2105 final public function hide($hide = 'toggle') {
4a65c39a 2106 global $DB;
2107 if ($entry = $DB->get_record('repository', array('id'=>$this->id))) {
2108 if ($hide === 'toggle' ) {
2109 if (!empty($entry->visible)) {
2110 $entry->visible = 0;
2111 } else {
2112 $entry->visible = 1;
2113 }
2114 } else {
2115 if (!empty($hide)) {
2116 $entry->visible = 0;
2117 } else {
2118 $entry->visible = 1;
2119 }
2120 }
2121 return $DB->update_record('repository', $entry);
2122 }
2123 return false;
2124 }
1cf56396 2125
1cf56396 2126 /**
4a65c39a 2127 * Save settings for repository instance
8dcd5deb 2128 * $repo->set_option(array('api_key'=>'f2188bde132', 'name'=>'dongsheng'));
67233725 2129 *
8dcd5deb 2130 * @param array $options settings
67233725 2131 * @return bool
1cf56396 2132 */
7a3b93c1 2133 public function set_option($options = array()) {
4a65c39a 2134 global $DB;
7a3b93c1 2135
122defc5 2136 if (!empty($options['name'])) {
a27ab6fd 2137 $r = new stdClass();
122defc5 2138 $r->id = $this->id;
2139 $r->name = $options['name'];
2140 $DB->update_record('repository_instances', $r);
2141 unset($options['name']);
2142 }
27051e43 2143 foreach ($options as $name=>$value) {
2144 if ($id = $DB->get_field('repository_instance_config', 'id', array('name'=>$name, 'instanceid'=>$this->id))) {
f685e830 2145 $DB->set_field('repository_instance_config', 'value', $value, array('id'=>$id));
27051e43 2146 } else {
a27ab6fd 2147 $config = new stdClass();
27051e43 2148 $config->instanceid = $this->id;
2149 $config->name = $name;
2150 $config->value = $value;
f685e830 2151 $DB->insert_record('repository_instance_config', $config);
27051e43 2152 }
4a65c39a 2153 }
118ca9e9 2154 cache::make('core', 'repositories')->purge();
f685e830 2155 return true;
1cf56396 2156 }
1cf56396 2157
4a65c39a 2158 /**
a76efbca 2159 * Get settings for repository instance.
67233725 2160 *
a76efbca
FM
2161 * @param string $config a specific option to get.
2162 * @return mixed returns an array of options. If $config is not empty, then it returns that option,
2163 * or null if the option does not exist.
4a65c39a 2164 */
7a3b93c1 2165 public function get_option($config = '') {
4a65c39a 2166 global $DB;
118ca9e9
MG
2167 $cache = cache::make('core', 'repositories');
2168 if (($entries = $cache->get('ops:'. $this->id)) === false) {
2169 $entries = $DB->get_records('repository_instance_config', array('instanceid' => $this->id));
2170 $cache->set('ops:'. $this->id, $entries);
2171 }
a76efbca 2172
27051e43 2173 $ret = array();
7a3b93c1 2174 foreach($entries as $entry) {
27051e43 2175 $ret[$entry->name] = $entry->value;
4a65c39a 2176 }
a76efbca 2177
4a65c39a 2178 if (!empty($config)) {
9e6aa5ec 2179 if (isset($ret[$config])) {
75003899 2180 return $ret[$config];
9e6aa5ec
DC
2181 } else {
2182 return null;
2183 }
4a65c39a 2184 } else {
2185 return $ret;
2186 }
2187 }
bf1fccf0 2188
67233725
DC
2189 /**
2190 * Filter file listing to display specific types
2191 *
2192 * @param array $value
2193 * @return bool
2194 */
c167aa26 2195 public function filter(&$value) {
18bd7573 2196 $accepted_types = optional_param_array('accepted_types', '', PARAM_RAW);
b81ebefd 2197 if (isset($value['children'])) {
b81ebefd 2198 if (!empty($value['children'])) {
b81ebefd 2199 $value['children'] = array_filter($value['children'], array($this, 'filter'));
537d44e8 2200 }
559276b1 2201 return true; // always return directories
c167aa26 2202 } else {
46ee50dc 2203 if ($accepted_types == '*' or empty($accepted_types)
2204 or (is_array($accepted_types) and in_array('*', $accepted_types))) {
559276b1
MG
2205 return true;
2206 } else {
e5635827
MG
2207 foreach ($accepted_types as $ext) {
2208 if (preg_match('#'.$ext.'$#i', $value['title'])) {
559276b1 2209 return true;
c167aa26 2210 }
2211 }
2212 }
2213 }
559276b1 2214 return false;
c167aa26 2215 }
2216
4a65c39a 2217 /**
2218 * Given a path, and perhaps a search, get a list of files.
2219 *
67233725 2220 * See details on {@link http://docs.moodle.org/dev/Repository_plugins}
f7639c37 2221 *
67233725
DC
2222 * @param string $path this parameter can a folder name, or a identification of folder
2223 * @param string $page the page number of file list
1a6195b4
DC
2224 * @return array the list of files, including meta infomation, containing the following keys
2225 * manage, url to manage url
2226 * client_id
2227 * login, login form
2228 * repo_id, active repository id
2229 * login_btn_action, the login button action
2230 * login_btn_label, the login button label
2231 * total, number of results
2232 * perpage, items per page
2233 * page
2234 * pages, total pages
29199e56 2235 * issearchresult, is it a search result?
1a6195b4
DC
2236 * list, file list
2237 * path, current path and parent path
4a65c39a 2238 */
9d6aa286 2239 public function get_listing($path = '', $page = '') {
2240 }
1cf56396 2241
8136753a 2242
fbd508b4 2243 /**
8136753a 2244 * Prepare the breadcrumb.
5bdf63cc 2245 *
8136753a
FM
2246 * @param array $breadcrumb contains each element of the breadcrumb.
2247 * @return array of breadcrumb elements.
2248 * @since 2.3.3
5bdf63cc 2249 */
8136753a 2250 protected static function prepare_breadcrumb($breadcrumb) {
5bdf63cc 2251 global $OUTPUT;
8136753a
FM
2252 $foldericon = $OUTPUT->pix_url(file_folder_icon(24))->out(false);
2253 $len = count($breadcrumb);
2254 for ($i = 0; $i < $len; $i++) {
2255 if (is_array($breadcrumb[$i]) && !isset($breadcrumb[$i]['icon'])) {
2256 $breadcrumb[$i]['icon'] = $foldericon;
2257 } else if (is_object($breadcrumb[$i]) && !isset($breadcrumb[$i]->icon)) {
2258 $breadcrumb[$i]->icon = $foldericon;
9213f547
MG
2259 }
2260 }
8136753a
FM
2261 return $breadcrumb;
2262 }
9213f547 2263
8136753a
FM
2264 /**
2265 * Prepare the file/folder listing.
2266 *
2267 * @param array $list of files and folders.
2268 * @return array of files and folders.
2269 * @since 2.3.3
2270 */
2271 protected static function prepare_list($list) {
2272 global $OUTPUT;
2273 $foldericon = $OUTPUT->pix_url(file_folder_icon(24))->out(false);
2274
2275 // Reset the array keys because non-numeric keys will create an object when converted to JSON.
2276 $list = array_values($list);
2277
2278 $len = count($list);
2279 for ($i = 0; $i < $len; $i++) {
2280 if (is_object($list[$i])) {
2281 $file = (array)$list[$i];
e709ddd2
MG
2282 $converttoobject = true;
2283 } else {
8136753a 2284 $file =& $list[$i];
e709ddd2
MG
2285 $converttoobject = false;
2286 }
b92241f2
MG
2287 if (isset($file['size'])) {
2288 $file['size'] = (int)$file['size'];
2289 $file['size_f'] = display_size($file['size']);
2290 }
8136753a 2291 if (isset($file['license']) && get_string_manager()->string_exists($file['license'], 'license')) {
b92241f2
MG
2292 $file['license_f'] = get_string($file['license'], 'license');
2293 }
2294 if (isset($file['image_width']) && isset($file['image_height'])) {
dd1f051e
MG
2295 $a = array('width' => $file['image_width'], 'height' => $file['image_height']);
2296 $file['dimensions'] = get_string('imagesize', 'repository', (object)$a);
5bdf63cc
MG
2297 }
2298 foreach (array('date', 'datemodified', 'datecreated') as $key) {
b92241f2
MG
2299 if (!isset($file[$key]) && isset($file['date'])) {
2300 $file[$key] = $file['date'];
5bdf63cc 2301 }
b92241f2 2302 if (isset($file[$key])) {
5bdf63cc 2303 // must be UNIX timestamp
b92241f2
MG
2304 $file[$key] = (int)$file[$key];
2305 if (!$file[$key]) {
2306 unset($file[$key]);
5bdf63cc 2307 } else {
b92241f2
MG
2308 $file[$key.'_f'] = userdate($file[$key], get_string('strftimedatetime', 'langconfig'));
2309 $file[$key.'_f_s'] = userdate($file[$key], get_string('strftimedatetimeshort', 'langconfig'));
5bdf63cc
MG
2310 }
2311 }
2312 }
e709ddd2
MG
2313 $isfolder = (array_key_exists('children', $file) || (isset($file['type']) && $file['type'] == 'folder'));
2314 $filename = null;
2315 if (isset($file['title'])) {
2316 $filename = $file['title'];
2317 }
2318 else if (isset($file['fullname'])) {
2319 $filename = $file['fullname'];
2320 }
2321 if (!isset($file['mimetype']) && !$isfolder && $filename) {
559276b1 2322 $file['mimetype'] = get_mimetype_description(array('filename' => $filename));
5bdf63cc 2323 }
e709ddd2
MG
2324 if (!isset($file['icon'])) {
2325 if ($isfolder) {
8136753a 2326 $file['icon'] = $foldericon;
e709ddd2 2327 } else if ($filename) {
559276b1 2328 $file['icon'] = $OUTPUT->pix_url(file_extension_icon($filename, 24))->out(false);
5bdf63cc
MG
2329 }
2330 }
8136753a
FM
2331
2332 // Recursively loop over children.
2333 if (isset($file['children'])) {
2334 $file['children'] = self::prepare_list($file['children']);
2335 }
2336
2337 // Convert the array back to an object.
e709ddd2 2338 if ($converttoobject) {
8136753a 2339 $list[$i] = (object)$file;
e709ddd2 2340 }
5bdf63cc 2341 }
8136753a
FM
2342 return $list;
2343 }
2344
2345 /**
2346 * Prepares list of files before passing it to AJAX, makes sure data is in the correct
2347 * format and stores formatted values.
2348 *
2349 * @param array|stdClass $listing result of get_listing() or search() or file_get_drafarea_files()
2350 * @return array
2351 */
2352 public static function prepare_listing($listing) {
2353 $wasobject = false;
2354 if (is_object($listing)) {
2355 $listing = (array) $listing;
2356 $wasobject = true;
2357 }
2358
2359 // Prepare the breadcrumb, passed as 'path'.
2360 if (isset($listing['path']) && is_array($listing['path'])) {
2361 $listing['path'] = self::prepare_breadcrumb($listing['path']);
2362 }
2363
2364 // Prepare the listing of objects.
2365 if (isset($listing['list']) && is_array($listing['list'])) {
2366 $listing['list'] = self::prepare_list($listing['list']);
2367 }
2368
2369 // Convert back to an object.
2370 if ($wasobject) {
2371 $listing = (object) $listing;
2372 }
5bdf63cc
MG
2373 return $listing;
2374 }
2375
2376 /**
2377 * Search files in repository
2378 * When doing global search, $search_text will be used as
2379 * keyword.
353d5cf3 2380 *
67233725
DC
2381 * @param string $search_text search key word
2382 * @param int $page page
72a56555 2383 * @return mixed see {@link repository::get_listing()}
fbd508b4 2384 */
68a7c9a6 2385 public function search($search_text, $page = 0) {
353d5cf3 2386 $list = array();
2387 $list['list'] = array();
2388 return false;
fbd508b4 2389 }
2390
d68c527f 2391 /**
2392 * Logout from repository instance
2393 * By default, this function will return a login form
2394 *
2395 * @return string
2396 */
2397 public function logout(){
2398 return $this->print_login();
2399 }
2400
2401 /**
2402 * To check whether the user is logged in.
2403 *
67233725 2404 * @return bool
d68c527f 2405 */
2406 public function check_login(){
2407 return true;
2408 }
2409
1cf56396 2410
4a65c39a 2411 /**
2412 * Show the login screen, if required
67233725
DC
2413 *
2414 * @return string
4a65c39a 2415 */
1d66f2b2 2416 public function print_login(){
2417 return $this->get_listing();
2418 }
1cf56396 2419
4a65c39a 2420 /**
2421 * Show the search screen, if required
67233725
DC
2422 *
2423 * @return string
4a65c39a 2424 */
a560785f 2425 public function print_search() {
b5e7b638 2426 global $PAGE;
d1d18691 2427 $renderer = $PAGE->get_renderer('core', 'files');
b5e7b638 2428 return $renderer->repository_default_searchform();
2b9feb5f 2429 }
4a65c39a 2430
3e123368
DC
2431 /**
2432 * For oauth like external authentication, when external repository direct user back to moodle,
a1070d3f 2433 * this function will be called to set up token and token_secret
3e123368
DC
2434 */
2435 public function callback() {
2436 }
2437
455860ce 2438 /**
2439 * is it possible to do glboal search?
67233725
DC
2440 *
2441 * @return bool
455860ce 2442 */
7a3b93c1 2443 public function global_search() {
455860ce 2444 return false;
2445 }
2446
8dcd5deb 2447 /**
a6600395 2448 * Defines operations that happen occasionally on cron
67233725
DC
2449 *
2450 * @return bool
8dcd5deb 2451 */
a6600395 2452 public function cron() {
2453 return true;
2454 }
2455
7892948d 2456 /**
83a018ed 2457 * function which is run when the type is created (moodle administrator add the plugin)
67233725
DC
2458 *
2459 * @return bool success or fail?
7892948d 2460 */
f1cfe56e 2461 public static function plugin_init() {
3e0794ed 2462 return true;
7892948d 2463 }
2464
a6600395 2465 /**
06e65e1e 2466 * Edit/Create Admin Settings Moodle form
67233725
DC
2467 *
2468 * @param moodleform $mform Moodle form (passed by reference)
8e5af6cf 2469 * @param string $classname repository class name
a6600395 2470 */
68a7c9a6 2471 public static function type_config_form($mform, $classname = 'repository') {
8e5af6cf 2472 $instnaceoptions = call_user_func(array($classname, 'get_instance_option_names'), $mform, $classname);
a5adfa26
DC
2473 if (empty($instnaceoptions)) {
2474 // this plugin has only one instance
2475 // so we need to give it a name
2476 // it can be empty, then moodle will look for instance name from language string
2477 $mform->addElement('text', 'pluginname', get_string('pluginname', 'repository'), array('size' => '40'));
2478 $mform->addElement('static', 'pluginnamehelp', '', get_string('pluginnamehelp', 'repository'));
102f9286 2479 $mform->setType('pluginname', PARAM_TEXT);
a5adfa26 2480 }
4a65c39a 2481 }
dbc01944 2482
84ee73ee
RK
2483 /**
2484 * Validate Admin Settings Moodle form
67233725
DC
2485 *
2486 * @static
2487 * @param moodleform $mform Moodle form (passed by reference)
2488 * @param array $data array of ("fieldname"=>value) of submitted data
2489 * @param array $errors array of ("fieldname"=>errormessage) of errors
84ee73ee
RK
2490 * @return array array of errors
2491 */
2492 public static function type_form_validation($mform, $data, $errors) {
2493 return $errors;
2494 }
2495
2496
6f2cd52a 2497 /**
06e65e1e 2498 * Edit/Create Instance Settings Moodle form
67233725
DC
2499 *
2500 * @param moodleform $mform Moodle form (passed by reference)
a6600395 2501 */
4a126f17 2502 public static function instance_config_form($mform) {
a6600395 2503 }
4a65c39a 2504
a6600395 2505 /**
67233725 2506 * Return names of the general options.
a6600395 2507 * By default: no general option name
67233725 2508 *
a6600395 2509 * @return array
2510 */
1b79955a 2511 public static function get_type_option_names() {
a5adfa26 2512 return array('pluginname');
a6600395 2513 }
2514
2515 /**
67233725 2516 * Return names of the instance options.
a6600395 2517 * By default: no instance option name
67233725 2518 *
a6600395 2519 * @return array
2520 */
7a3b93c1 2521 public static function get_instance_option_names() {
a6600395 2522 return array();
8b65d45c 2523 }
e35194be 2524
67233725
DC
2525 /**
2526 * Validate repository plugin instance form
2527 *
2528 * @param moodleform $mform moodle form
2529 * @param array $data form data
2530 * @param array $errors errors
2531 * @return array errors
2532 */
6b172cdc
DC
2533 public static function instance_form_validation($mform, $data, $errors) {
2534 return $errors;
2535 }
2536
67233725
DC
2537 /**
2538 * Create a shorten filename
2539 *
2540 * @param string $str filename
2541 * @param int $maxlength max file name length
2542 * @return string short filename
2543 */
f00340e2 2544 public function get_short_filename($str, $maxlength) {
2f1e464a
PS
2545 if (core_text::strlen($str) >= $maxlength) {
2546 return trim(core_text::substr($str, 0, $maxlength)).'...';
f00340e2
DC
2547 } else {
2548 return $str;
2549 }
2550 }
f392caba
DC
2551
2552 /**
2553 * Overwrite an existing file
2554 *
2555 * @param int $itemid
2556 * @param string $filepath
2557 * @param string $filename
2558 * @param string $newfilepath
2559 * @param string $newfilename
67233725 2560 * @return bool
f392caba 2561 */
061eeed5 2562 public static function overwrite_existing_draftfile($itemid, $filepath, $filename, $newfilepath, $newfilename) {
f392caba
DC
2563 global $USER;
2564 $fs = get_file_storage();
21c08c63 2565 $user_context = context_user::instance($USER->id);
f392caba
DC
2566 if ($file = $fs->get_file($user_context->id, 'user', 'draft', $itemid, $filepath, $filename)) {
2567 if ($tempfile = $fs->get_file($user_context->id, 'user', 'draft', $itemid, $newfilepath, $newfilename)) {
0ab3070c
MG
2568 // Remember original file source field.
2569 $source = @unserialize($file->get_source());
e9e32b1d
MG
2570 if ($tempfile->is_external_file()) {
2571 // New file is a reference. Check that existing file does not have any other files referencing to it
e9e32b1d
MG
2572 if (isset($source->original) && $fs->search_references_count($source->original)) {
2573 return (object)array('error' => get_string('errordoublereference', 'repository'));
2574 }
2575 }
f392caba
DC
2576 // delete existing file to release filename
2577 $file->delete();
2578 // create new file
2579 $newfile = $fs->create_file_from_storedfile(array('filepath'=>$filepath, 'filename'=>$filename), $tempfile);
0ab3070c
MG
2580 // Preserve original file location (stored in source field) for handling references
2581 if (isset($source->original)) {
2582 if (!($newfilesource = @unserialize($newfile->get_source()))) {
2583 $newfilesource = new stdClass();
2584 }
2585 $newfilesource->original = $source->original;
2586 $newfile->set_source(serialize($newfilesource));
2587 }
f392caba
DC
2588 // remove temp file
2589 $tempfile->delete();
2590 return true;
2591 }
2592 }
2593 return false;
2594 }
2595
f7c588d2
MG
2596 /**
2597 * Updates a file in draft filearea.
2598 *
2599 * This function can only update fields filepath, filename, author, license.
2600 * If anything (except filepath) is updated, timemodified is set to current time.
2601 * If filename or filepath is updated the file unconnects from it's origin
2602 * and therefore all references to it will be converted to copies when
2603 * filearea is saved.
2604 *
2605 * @param int $draftid
2606 * @param string $filepath path to the directory containing the file, or full path in case of directory
2607 * @param string $filename name of the file, or '.' in case of directory
2608 * @param array $updatedata array of fields to change (only filename, filepath, license and/or author can be updated)
2609 * @throws moodle_exception if for any reason file can not be updated (file does not exist, target already exists, etc.)
2610 */
2611 public static function update_draftfile($draftid, $filepath, $filename, $updatedata) {
2612 global $USER;
2613 $fs = get_file_storage();
2614 $usercontext = context_user::instance($USER->id);
2615 // make sure filename and filepath are present in $updatedata
2616 $updatedata = $updatedata + array('filepath' => $filepath, 'filename' => $filename);
2617 $filemodified = false;
2618 if (!$file = $fs->get_file($usercontext->id, 'user', 'draft', $draftid, $filepath, $filename)) {
2619 if ($filename === '.') {
2620 throw new moodle_exception('foldernotfound', 'repository');
2621 } else {
2622 throw new moodle_exception('filenotfound', 'error');
2623 }
2624 }
2625 if (!$file->is_directory()) {
2626 // This is a file
2627 if ($updatedata['filepath'] !== $filepath || $updatedata['filename'] !== $filename) {
2628 // Rename/move file: check that target file name does not exist.
2629 if ($fs->file_exists($usercontext->id, 'user', 'draft', $draftid, $updatedata['filepath'], $updatedata['filename'])) {
2630 throw new moodle_exception('fileexists', 'repository');
2631 }
2632 if (($filesource = @unserialize($file->get_source())) && isset($filesource->original)) {
2633 unset($filesource->original);
2634 $file->set_source(serialize($filesource));
2635 }
2636 $file->rename($updatedata['filepath'], $updatedata['filename']);
2637 // timemodified is updated only when file is renamed and not updated when file is moved.
2638 $filemodified = $filemodified || ($updatedata['filename'] !== $filename);
2639 }
2640 if (array_key_exists('license', $updatedata) && $updatedata['license'] !== $file->get_license()) {
2641 // Update license and timemodified.
2642 $file->set_license($updatedata['license']);
2643 $filemodified = true;
2644 }
2645 if (array_key_exists('author', $updatedata) && $updatedata['author'] !== $file->get_author()) {
2646 // Update author and timemodified.
2647 $file->set_author($updatedata['author']);
2648 $filemodified = true;
2649 }
2650 // Update timemodified:
2651 if ($filemodified) {
2652 $file->set_timemodified(time());
2653 }
2654 } else {
2655 // This is a directory - only filepath can be updated for a directory (it was moved).
2656 if ($updatedata['filepath'] === $filepath) {
2657 // nothing to update
2658 return;
2659 }
2660 if ($fs->file_exists($usercontext->id, 'user', 'draft', $draftid, $updatedata['filepath'], '.')) {
2661 // bad luck, we can not rename if something already exists there
2662 throw new moodle_exception('folderexists', 'repository');
2663 }
2664 $xfilepath = preg_quote($filepath, '|');
2665 if (preg_match("|^$xfilepath|", $updatedata['filepath'])) {
2666 // we can not move folder to it's own subfolder
2667 throw new moodle_exception('folderrecurse', 'repository');
2668 }
2669
2670 // If directory changed the name, update timemodified.
2671 $filemodified = (basename(rtrim($file->get_filepath(), '/')) !== basename(rtrim($updatedata['filepath'], '/')));
2672
2673 // Now update directory and all children.
2674 $files = $fs->get_area_files($usercontext->id, 'user', 'draft', $draftid);
2675 foreach ($files as $f) {
2676 if (preg_match("|^$xfilepath|", $f->get_filepath())) {
2677 $path = preg_replace("|^$xfilepath|", $updatedata['filepath'], $f->get_filepath());
2678 if (($filesource = @unserialize($f->get_source())) && isset($filesource->original)) {
2679 // unset original so the references are not shown any more
2680 unset($filesource->original);
2681 $f->set_source(serialize($filesource));
2682 }
2683 $f->rename($path, $f->get_filename());
2684 if ($filemodified && $f->get_filepath() === $updatedata['filepath'] && $f->get_filename() === $filename) {
2685 $f->set_timemodified(time());
2686 }
2687 }
2688 }
2689 }
2690 }
2691
f392caba
DC
2692 /**
2693 * Delete a temp file from draft area
2694 *
2695 * @param int $draftitemid
2696 * @param string $filepath
2697 * @param string $filename
67233725 2698 * @return bool
f392caba 2699 */
061eeed5 2700 public static function delete_tempfile_from_draft($draftitemid, $filepath, $filename) {
f392caba
DC
2701 global $USER;
2702 $fs = get_file_storage();
21c08c63 2703 $user_context = context_user::instance($USER->id);
f392caba
DC
2704 if ($file = $fs->get_file($user_context->id, 'user', 'draft', $draftitemid, $filepath, $filename)) {
2705 $file->delete();
2706 return true;
2707 } else {
2708 return false;
2709 }
2710 }
67233725
DC
2711
2712 /**
2713 * Find all external files in this repo and import them
2714 */
2715 public function convert_references_to_local() {
2716 $fs = get_file_storage();
2717 $files = $fs->get_external_files($this->id);
2718 foreach ($files as $storedfile) {
2719 $fs->import_external_file($storedfile);
2720 }
2721 }
2722
6fd1cf05
MG
2723 /**
2724 * Called from phpunit between tests, resets whatever was cached
2725 */
2726 public static function reset_caches() {
2727 self::sync_external_file(null, true);
2728 }
67233725
DC
2729
2730 /**
2d222a32 2731 * Performs synchronisation of reference to an external file if the previous one has expired.
67233725
DC
2732 *
2733 * @param stored_file $file
6fd1cf05 2734 * @param bool $resetsynchistory whether to reset all history of sync (used by phpunit)
67233725
DC
2735 * @return bool success
2736 */
6fd1cf05 2737 public static function sync_external_file($file, $resetsynchistory = false) {
67233725 2738 global $DB;
6fd1cf05 2739 // TODO MDL-25290 static should be replaced with MUC code.
0b2bfbd1 2740 static $synchronized = array();
6fd1cf05
MG
2741 if ($resetsynchistory) {
2742 $synchronized = array();
2743 }
67233725
DC
2744
2745 $fs = get_file_storage();
2746
6fd1cf05 2747 if (!$file || !$file->get_referencefileid()) {
0b2bfbd1
MG
2748 return false;
2749 }
2750 if (array_key_exists($file->get_id(), $synchronized)) {
2751 return $synchronized[$file->get_id()];
2752 }
2753
2754 // remember that we already cached in current request to prevent from querying again
2755 $synchronized[$file->get_id()] = false;
2756
67233725
DC
2757 if (!$reference = $DB->get_record('files_reference', array('id'=>$file->get_referencefileid()))) {
2758 return false;
2759 }
2760
2761 if (!empty($reference->lastsync) and ($reference->lastsync + $reference->lifetime > time())) {
0b2bfbd1
MG
2762 $synchronized[$file->get_id()] = true;
2763 return true;
67233725
DC
2764 }
2765
2766 if (!$repository = self::get_repository_by_id($reference->repositoryid, SYSCONTEXTID)) {
2767 return false;
2768 }
2769
2770 if (!$repository->sync_individual_file($file)) {
2771 return false;
2772 }
2773
2d222a32 2774 $lifetime = $repository->get_reference_file_lifetime($reference);
67233725
DC
2775 $fileinfo = $repository->get_file_by_reference($reference);
2776 if ($fileinfo === null) {
2777 // does not exist any more - set status to missing
2d222a32 2778 $file->set_missingsource($lifetime);
0b2bfbd1 2779 $synchronized[$file->get_id()] = true;
67233725 2780 return true;
67233725
DC
2781 }
2782
2783 $contenthash = null;
2784 $filesize = null;
2d222a32
MG
2785 if (!empty($fileinfo->filesize)) {
2786 // filesize returned
2787 if (!empty($fileinfo->contenthash) && $fs->content_exists($fileinfo->contenthash)) {
2788 // contenthash is specified and valid
2789 $contenthash = $fileinfo->contenthash;
2790 } else if ($fileinfo->filesize == $file->get_filesize()) {
2791 // we don't know the new contenthash but the filesize did not change,
2792 // assume the contenthash did not change either
2793 $contenthash = $file->get_contenthash();
2794 } else {
2795 // we can't save empty contenthash so generate contenthash from empty string
2796 $fs->add_string_to_pool('');
2797 $contenthash = sha1('');
2798 }
67233725
DC
2799 $filesize = $fileinfo->filesize;
2800 } else if (!empty($fileinfo->filepath)) {
2801 // File path returned
2802 list($contenthash, $filesize, $newfile) = $fs->add_file_to_pool($fileinfo->filepath);
2803 } else if (!empty($fileinfo->handle) && is_resource($fileinfo->handle)) {
2804 // File handle returned
2805 $contents = '';
2806 while (!feof($fileinfo->handle)) {
2807 $contents .= fread($handle, 8192);
2808 }
2809 fclose($fileinfo->handle);
2810 list($contenthash, $filesize, $newfile) = $fs->add_string_to_pool($content);
2811 } else if (isset($fileinfo->content)) {
2812 // File content returned
2813 list($contenthash, $filesize, $newfile) = $fs->add_string_to_pool($fileinfo->content);
2814 }
2815
2816 if (!isset($contenthash) or !isset($filesize)) {
2817 return false;
2818 }
2819
67233725 2820 // update files table
2d222a32 2821 $file->set_synchronized($contenthash, $filesize, 0, $lifetime);
0b2bfbd1 2822 $synchronized[$file->get_id()] = true;
67233725
DC
2823 return true;
2824 }
d6453211
DC
2825
2826 /**
2827 * Build draft file's source field
2828 *
2829 * {@link file_restore_source_field_from_draft_file()}
2830 * XXX: This is a hack for file manager (MDL-28666)
2831 * For newly created draft files we have to construct
2832 * source filed in php serialized data format.
2833 * File manager needs to know the original file information before copying
2834 * to draft area, so we append these information in mdl_files.source field
2835 *
2836 * @param string $source
2837 * @return string serialised source field
2838 */
2839 public static function build_source_field($source) {
2840 $sourcefield = new stdClass;
2841 $sourcefield->source = $source;
2842 return serialize($sourcefield);
2843 }
118ca9e9
MG
2844
2845 /**
2846 * Prepares the repository to be cached. Implements method from cacheable_object interface.
2847 *
2848 * @return array
2849 */
2850 public function prepare_to_cache() {
2851 return array(
2852 'class' => get_class($this),
2853 'id' => $this->id,
2854 'ctxid' => $this->context->id,
2855 'options' => $this->options,
2856 'readonly' => $this->readonly
2857 );
2858 }
2859
2860 /**
2861 * Restores the repository from cache. Implements method from cacheable_object interface.
2862 *
2863 * @return array
2864 */
2865 public static function wake_from_cache($data) {
2866 $classname = $data['class'];
2867 return new $classname($data['id'], $data['ctxid'], $data['options'], $data['readonly']);
2868 }
361a47d4
DM
2869
2870 /**
2871 * Gets a file relative to this file in the repository and sends it to the browser.
2872 * Used to allow relative file linking within a repository without creating file records
2873 * for linked files
2874 *
2875 * Repositories that overwrite this must be very careful - see filesystem repository for example.
2876 *
2877 * @param stored_file $mainfile The main file we are trying to access relative files for.
2878 * @param string $relativepath the relative path to the file we are trying to access.
2879 *
2880 */
2881 public function send_relative_file(stored_file $mainfile, $relativepath) {
2882 // This repository hasn't implemented this so send_file_not_found.
2883 send_file_not_found();
2884 }
2885
2886 /**
2887 * helper function to check if the repository supports send_relative_file.
2888 *
2889 * @return true|false
2890 */
2891 public function supports_relative_file() {
2892 return false;
2893 }
8b65d45c 2894}
837ebb78 2895
2896/**
6f2cd52a
DC
2897 * Exception class for repository api
2898 *
2899 * @since 2.0
72a56555 2900 * @package core_repository
67233725 2901 * @copyright 2009 Dongsheng Cai {@link http://dongsheng.org}
6f2cd52a 2902 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
837ebb78 2903 */
4a65c39a 2904class repository_exception extends moodle_exception {
8b65d45c 2905}
4ed43890 2906
8dcd5deb 2907/**
6f2cd52a
DC
2908 * This is a class used to define a repository instance form
2909 *
2910 * @since 2.0
72a56555 2911 * @package core_repository
67233725 2912 * @copyright 2009 Dongsheng Cai {@link http://dongsheng.org}
6f2cd52a 2913 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
8dcd5deb 2914 */
a6600395 2915final class repository_instance_form extends moodleform {
67233725 2916 /** @var stdClass repository instance */
4a65c39a 2917 protected $instance;
67233725 2918 /** @var string repository plugin type */
4a65c39a 2919 protected $plugin;
67233725
DC
2920
2921 /**
2922 * Added defaults to moodle form
2923 */
49d20def 2924 protected function add_defaults() {
4a65c39a 2925 $mform =& $this->_form;
2926 $strrequired = get_string('required');
2927
2928 $mform->addElement('hidden', 'edit', ($this->instance) ? $this->instance->id : 0);
d18e0fe6 2929 $mform->setType('edit', PARAM_INT);
4a65c39a 2930 $mform->addElement('hidden', 'new', $this->plugin);
405aca35 2931 $mform->setType('new', PARAM_ALPHANUMEXT);
4a65c39a 2932 $mform->addElement('hidden', 'plugin', $this->plugin);
aff24313 2933 $mform->setType('plugin', PARAM_PLUGIN);
27051e43 2934 $mform->addElement('hidden', 'typeid', $this->typeid);
d18e0fe6 2935 $mform->setType('typeid', PARAM_INT);
faaa613d 2936 $mform->addElement('hidden', 'contextid', $this->contextid);
d18e0fe6 2937 $mform->setType('contextid', PARAM_INT);
4a65c39a 2938
2939 $mform->addElement('text', 'name', get_string('name'), 'maxlength="100" size="30"');
2940 $mform->addRule('name', $strrequired, 'required', null, 'client');
102f9286 2941 $mform->setType('name', PARAM_TEXT);
49d20def 2942 }
4a65c39a 2943
67233725
DC
2944 /**
2945 * Define moodle form elements
2946 */
49d20def
DC
2947 public function definition() {
2948 global $CFG;
2949 // type of plugin, string
2950 $this->plugin = $this->_customdata['plugin'];
2951 $this->typeid = $this->_customdata['typeid'];
2952 $this->contextid = $this->_customdata['contextid'];
2953 $this->instance = (isset($this->_customdata['instance'])
2954 && is_subclass_of($this->_customdata['instance'], 'repository'))
2955 ? $this->_customdata['instance'] : null;
2956
2957 $mform =& $this->_form;
1e97f196 2958
49d20def 2959 $this->add_defaults();
4a126f17
DP
2960
2961 // Add instance config options.
2962 $result = repository::static_function($this->plugin, 'instance_config_form', $mform);
2963 if ($result === false) {
2964 // Remove the name element if no other config options.
2965 $mform->removeElement('name');
2966 }
2967 if ($this->instance) {
f48fb4d6 2968 $data = array();
2969 $data['name'] = $this->instance->name;
2970 if (!$this->instance->readonly) {
f48fb4d6 2971 // and set the data if we have some.
1e97f196 2972 foreach ($this->instance->get_instance_option_names() as $config) {
a3d8df25 2973 if (!empty($this->instance->options[$config])) {
2974 $data[$config] = $this->instance->options[$config];
1e97f196 2975 } else {
2976 $data[$config] = '';
2977 }
27051e43 2978 }
4a65c39a 2979 }
f48fb4d6 2980 $this->set_data($data);
1e97f196 2981 }
2982
49d20def
DC
2983 if ($result === false) {
2984 $mform->addElement('cancel');
2985 } else {
2986 $this->add_action_buttons(true, get_string('save','repository'));
2987 }
4a65c39a 2988 }
2989
67233725
DC
2990 /**
2991 * Validate moodle form data
2992 *
2993 * @param array $data form data
2994 * @param array $files files in form
2995 * @return array errors
2996 */
58eb9b9f 2997 public function validation($data, $files) {
4a65c39a 2998 global $DB;
4a65c39a 2999 $errors = array();
6b172cdc
DC
3000 $plugin = $this->_customdata['plugin'];
3001 $instance = (isset($this->_customdata['instance'])
3002 && is_subclass_of($this->_customdata['instance'], 'repository'))
3003 ? $this->_customdata['instance'] : null;
157fd8aa 3004
6b172cdc
DC
3005 if (!$instance) {
3006 $errors = repository::static_function($plugin, 'instance_form_validation', $this, $data, $errors);
3007 } else {
3008 $errors = $instance->instance_form_validation($this, $data, $errors);
3009 }
3010
a090554a
PS
3011 $sql = "SELECT count('x')
3012 FROM {repository_instances} i, {repository} r
f23d95ef
FM
3013 WHERE r.type=:plugin AND r.id=i.typeid AND i.name=:name AND i.contextid=:contextid";
3014 $params = array('name' => $data['name'], 'plugin' => $this->plugin, 'contextid' => $this->contextid);
157fd8aa
FM
3015 if ($instance) {
3016 $sql .= ' AND i.id != :instanceid';
3017 $params['instanceid'] = $instance->id;
3018 }
f23d95ef 3019 if ($DB->count_records_sql($sql, $params) > 0) {
6b172cdc 3020 $errors['name'] = get_string('erroruniquename', 'repository');
4a65c39a 3021 }
3022
4a65c39a 3023 return $errors;
3024 }
3025}
a6600395 3026
a6600395 3027/**
6f2cd52a
DC
3028 * This is a class used to define a repository type setting form
3029 *
3030 * @since 2.0
72a56555 3031 * @package core_repository
67233725 3032 * @copyright 2009 Dongsheng Cai {@link http://dongsheng.org}
6f2cd52a 3033 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
a6600395 3034 */
c295f9ff 3035final class repository_type_form extends moodleform {
67233725 3036 /** @var stdClass repository instance */
a6600395 3037 protected $instance;
67233725 3038 /** @var string repository plugin name */
a6600395 3039 protected $plugin;
67233725 3040 /** @var string action */
79698344 3041 protected $action;
a6600395 3042
3043 /**
3044 * Definition of the moodleform
a6600395 3045 */
3046 public function definition() {
3047 global $CFG;
3048 // type of plugin, string
3049 $this->plugin = $this->_customdata['plugin'];
3050 $this->instance = (isset($this->_customdata['instance'])
3051 && is_a($this->_customdata['instance'], 'repository_type'))
3052 ? $this->_customdata['instance'] : null;
3053
79698344 3054 $this->action = $this->_customdata['action'];
a5adfa26 3055 $this->pluginname = $this->_customdata['pluginname'];
a6600395 3056 $mform =& $this->_form;
3057 $strrequired = get_string('required');
4d5948f1 3058
79698344
MD
3059 $mform->addElement('hidden', 'action', $this->action);
3060 $mform->setType('action', PARAM_TEXT);
3061 $mform->addElement('hidden', 'repos', $this->plugin);
aff24313 3062 $mform->setType('repos', PARAM_PLUGIN);
8f943eba 3063
06e65e1e 3064 // let the plugin add its specific fields
a5adfa26
DC
3065 $classname = 'repository_' . $this->plugin;
3066 require_once($CFG->dirroot . '/repository/' . $this->plugin . '/lib.php');
f48fb4d6 3067 //add "enable course/user instances" checkboxes if multiple instances are allowed
dbc01944 3068 $instanceoptionnames = repository::static_function($this->plugin, 'get_instance_option_names');
8e5af6cf
DC
3069
3070 $result = call_user_func(array($classname, 'type_config_form'), $mform, $classname);
3071
a5adfa26 3072 if (!empty($instanceoptionnames)) {
8e5af6cf
DC
3073 $sm = get_string_manager();
3074 $component = 'repository';
3075 if ($sm->string_exists('enablecourseinstances', 'repository_' . $this->plugin)) {
3076 $component .= ('_' . $this->plugin);
3077 }
3078 $mform->addElement('checkbox', 'enablecourseinstances', get_string('enablecourseinstances', $component));
1fe56a2a 3079 $mform->setType('enablecourseinstances', PARAM_BOOL);
8e5af6cf
DC
3080
3081 $component = 'repository';
3082 if ($sm->string_exists('enableuserinstances', 'repository_' . $this->plugin)) {
3083 $component .= ('_' . $this->plugin);
3084 }
3085 $mform->addElement('checkbox', 'enableuserinstances', get_string('enableuserinstances', $component));
1fe56a2a 3086 $mform->setType('enableuserinstances', PARAM_BOOL);
f48fb4d6 3087 }
3088
3089 // set the data if we have some.
a6600395 3090 if ($this->instance) {
3091 $data = array();
1b79955a 3092 $option_names = call_user_func(array($classname,'get_type_option_names'));
f48fb4d6 3093 if (!empty($instanceoptionnames)){
3094 $option_names[] = 'enablecourseinstances';
3095 $option_names[] = 'enableuserinstances';
3096 }
3097
a6600395 3098 $instanceoptions = $this->instance->get_options();
3099 foreach ($option_names as $config) {
3100 if (!empty($instanceoptions[$config])) {
3101 $data[$config] = $instanceoptions[$config];
3102 } else {
3103 $data[$config] = '';
3104 }
3105 }
a5adfa26
DC
3106 // XXX: set plugin name for plugins which doesn't have muliti instances
3107 if (empty($instanceoptionnames)){
3108 $data['pluginname'] = $this->pluginname;
3109 }
a6600395 3110 $this->set_data($data);
3111 }
dbc01944 3112
46dd6bb0 3113 $this->add_action_buttons(true, get_string('save','repository'));
a6600395 3114 }
84ee73ee 3115
67233725
DC
3116 /**
3117 * Validate moodle form data
3118 *
3119 * @param array $data moodle form data
3120 * @param array $files
3121 * @return array errors
3122 */
58eb9b9f 3123 public function validation($data, $files) {
84ee73ee
RK
3124 $errors = array();
3125 $plugin = $this->_customdata['plugin'];
3126 $instance = (isset($this->_customdata['instance'])
3127 && is_subclass_of($this->_customdata['instance'], 'repository'))
3128 ? $this->_customdata['instance'] : null;
3129 if (!$instance) {
3130 $errors = repository::static_function($plugin, 'type_form_validation', $this, $data, $errors);
3131 } else {
3132 $errors = $instance->type_form_validation($this, $data, $errors);
3133 }
3134
3135 return $errors;
3136 }
a6600395 3137}
3138
8e0946bf
DC
3139/**
3140 * Generate all options needed by filepicker
3141 *
67233725 3142 * @param array $args including following keys
8e0946bf
DC
3143 * context
3144 * accepted_types
3145 * return_types
3146 *
3147 * @return array the list of repository instances, including meta infomation, containing the following keys
3148 * externallink
3149 * repositories
3150 * accepted_types
3151 */
99eaca9d 3152function initialise_filepicker($args) {
a28c9253 3153 global $CFG, $USER, $PAGE, $OUTPUT;
ec3eaa2c 3154 static $templatesinitialized = array();
1dce6261 3155 require_once($CFG->libdir . '/licenselib.php');
4f0c2d00 3156
6bdfef5d 3157 $return = new stdClass();
d1d4813f 3158 $licenses = array();
4f0c2d00
PS
3159 if (!empty($CFG->licenses)) {
3160 $array = explode(',', $CFG->licenses);
3161 foreach ($array as $license) {
6bdfef5d 3162 $l = new stdClass();
4f0c2d00
PS
3163 $l->shortname = $license;
3164 $l->fullname = get_string($license, 'license');
3165 $licenses[] = $l;
3166 }
d1d4813f 3167 }
308d948b
DC
3168 if (!empty($CFG->sitedefaultlicense)) {
3169 $return->defaultlicense = $CFG->sitedefaultlicense;
3170 }
1dce6261 3171
1dce6261
DC
3172 $return->licenses = $licenses;
3173
3174 $return->author = fullname($USER);
3175
99eaca9d
DC
3176 if (empty($args->context)) {
3177 $context = $PAGE->context;
e189ec00 3178 } else {
99eaca9d
DC
3179 $context = $args->context;
3180 }
6bf197b3
DC
3181 $disable_types = array();
3182 if (!empty($args->disable_types)) {
3183 $disable_types = $args->disable_types;
3184 }
99eaca9d 3185
21c08c63 3186 $user_context = context_user::instance($USER->id);
99eaca9d 3187
bf413f6f 3188 list($context, $course, $cm) = get_context_info_array($context->id);
0601e0ee 3189 $contexts = array($user_context, context_system::instance());
bf413f6f
DC
3190 if (!empty($course)) {
3191 // adding course context
21c08c63 3192 $contexts[] = context_course::instance($course->id);
bf413f6f 3193 }
99eaca9d
DC
3194 $externallink = (int)get_config(null, 'repositoryallowexternallinks');
3195 $repositories = repository::get_instances(array(
bf413f6f 3196 'context'=>$contexts,
99eaca9d 3197 'currentcontext'=> $context,
ea1780ad 3198 'accepted_types'=>$args->accepted_types,
6bf197b3
DC
3199 'return_types'=>$args->return_types,
3200 'disable_types'=>$disable_types
99eaca9d
DC
3201 ));
3202
3203 $return->repositories = array();
3204
3205 if (empty($externallink)) {
3206 $return->externallink = false;
3207 } else {
3208 $return->externallink = true;
3209 }
3210
837eef2e
DP
3211 $return->userprefs = array();
3212 $return->userprefs['recentrepository'] = get_user_preferences('filepicker_recentrepository', '');
3213 $return->userprefs['recentlicense'] = get_user_preferences('filepicker_recentlicense', '');
3214 $return->userprefs['recentviewmode'] = get_user_preferences('filepicker_recentviewmode', '');
3215
3216 user_preference_allow_ajax_update('filepicker_recentrepository', PARAM_INT);
3217 user_preference_allow_ajax_update('filepicker_recentlicense', PARAM_SAFEDIR);
3218 user_preference_allow_ajax_update('filepicker_recentviewmode', PARAM_INT);
3219
3220
99eaca9d 3221 // provided by form element
559276b1 3222 $return->accepted_types = file_get_typegroup('extension', $args->accepted_types);
766514a0 3223 $return->return_types = $args->return_types;
013cf287 3224 $templates = array();
99eaca9d
DC
3225 foreach ($repositories as $repository) {
3226 $meta = $repository->get_meta();
6b37c2b0
SH
3227 // Please note that the array keys for repositories are used within
3228 // JavaScript a lot, the key NEEDS to be the repository id.
b0985814 3229 $return->repositories[$repository->id] = $meta;
013cf287 3230 // Register custom repository template if it has one
ec3eaa2c
PN
3231 if(method_exists($repository, 'get_upload_template') && !array_key_exists('uploadform_' . $meta->type, $templatesinitialized)) {
3232 $templates['uploadform_' . $meta->type] = $repository->get_upload_template();
3233 $templatesinitialized['uploadform_' . $meta->type] = true;
013cf287 3234 }
99eaca9d 3235 }
ec3eaa2c
PN
3236 if (!array_key_exists('core', $templatesinitialized)) {
3237 // we need to send each filepicker template to the browser just once
d1d18691 3238 $fprenderer = $PAGE->get_renderer('core', 'files');
013cf287 3239 $templates = array_merge($templates, $fprenderer->filepicker_js_templates());
ec3eaa2c
PN
3240 $templatesinitialized['core'] = true;
3241 }
3242 if (sizeof($templates)) {
d1d18691 3243 $PAGE->requires->js_init_call('M.core_filepicker.set_templates', array($templates), true);
d1d18691 3244 }
99eaca9d 3245 return $return;
e189ec00 3246}