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