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