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