Merge branch 'MDL-31000-master-3' of git://git.luns.net.uk/moodle
[moodle.git] / repository / lib.php
CommitLineData
12c79bfd 1<?php
1cf56396 2
6f2cd52a
DC
3// This file is part of Moodle - http://moodle.org/
4//
5// Moodle is free software: you can redistribute it and/or modify
6// it under the terms of the GNU General Public License as published by
7// the Free Software Foundation, either version 3 of the License, or
8// (at your option) any later version.
9//
10// Moodle is distributed in the hope that it will be useful,
11// but WITHOUT ANY WARRANTY; without even the implied warranty of
12// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13// GNU General Public License for more details.
14//
15// You should have received a copy of the GNU General Public License
16// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
17
1cf56396 18
aca64b79 19/**
6f2cd52a
DC
20 * This file contains classes used to manage the repository plugins in Moodle
21 * and was introduced as part of the changes occuring in Moodle 2.0
22 *
23 * @since 2.0
5d354ded 24 * @package core
6f2cd52a 25 * @subpackage repository
5d354ded
PS
26 * @copyright 2009 Dongsheng Cai <dongsheng@moodle.com>
27 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
aca64b79 28 */
29
19add4c0 30require_once(dirname(dirname(__FILE__)) . '/config.php');
c19f8e7d 31require_once($CFG->libdir . '/filelib.php');
32require_once($CFG->libdir . '/formslib.php');
41076c58
DC
33
34define('FILE_EXTERNAL', 1);
35define('FILE_INTERNAL', 2);
f392caba 36define('RENAME_SUFFIX', '_2');
41076c58 37
a6600395 38/**
6f2cd52a
DC
39 * This class is used to manage repository plugins
40 *
a6600395 41 * A repository_type is a repository plug-in. It can be Box.net, Flick-r, ...
42 * A repository type can be edited, sorted and hidden. It is mandatory for an
43 * administrator to create a repository type in order to be able to create
44 * some instances of this type.
a6600395 45 * Coding note:
46 * - a repository_type object is mapped to the "repository" database table
47 * - "typename" attibut maps the "type" database field. It is unique.
48 * - general "options" for a repository type are saved in the config_plugin table
eb239694 49 * - when you delete a repository, all instances are deleted, and general
50 * options are also deleted from database
a6600395 51 * - When you create a type for a plugin that can't have multiple instances, a
52 * instance is automatically created.
6f2cd52a
DC
53 *
54 * @package moodlecore
55 * @subpackage repository
56 * @copyright 2009 Jerome Mouneyrac
57 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
a6600395 58 */
59class repository_type {
60
61
62 /**
63 * Type name (no whitespace) - A type name is unique
64 * Note: for a user-friendly type name see get_readablename()
65 * @var String
66 */
67 private $_typename;
68
69
70 /**
71 * Options of this type
72 * They are general options that any instance of this type would share
73 * e.g. API key
74 * These options are saved in config_plugin table
75 * @var array
76 */
7a3b93c1 77 private $_options;
a6600395 78
79
80 /**
81 * Is the repository type visible or hidden
82 * If false (hidden): no instances can be created, edited, deleted, showned , used...
83 * @var boolean
84 */
7a3b93c1 85 private $_visible;
a6600395 86
87
88 /**
89 * 0 => not ordered, 1 => first position, 2 => second position...
90 * A not order type would appear in first position (should never happened)
91 * @var integer
92 */
93 private $_sortorder;
94
f48fb4d6 95 /**
96 * Return if the instance is visible in a context
97 * TODO: check if the context visibility has been overwritten by the plugin creator
98 * (need to create special functions to be overvwritten in repository class)
5363905a 99 * @param objet $context - context
f48fb4d6 100 * @return boolean
101 */
5363905a
DC
102 public function get_contextvisibility($context) {
103 global $USER;
dbc01944 104
5363905a 105 if ($context->contextlevel == CONTEXT_COURSE) {
f48fb4d6 106 return $this->_options['enablecourseinstances'];
107 }
108
5363905a 109 if ($context->contextlevel == CONTEXT_USER) {
f48fb4d6 110 return $this->_options['enableuserinstances'];
111 }
112
113 //the context is SITE
114 return true;
115 }
dbc01944 116
f48fb4d6 117
118
a6600395 119 /**
120 * repository_type constructor
2b8beee3 121 * @global object $CFG
a6600395 122 * @param integer $typename
123 * @param array $typeoptions
124 * @param boolean $visible
125 * @param integer $sortorder (don't really need set, it will be during create() call)
126 */
a642bf6f 127 public function __construct($typename = '', $typeoptions = array(), $visible = true, $sortorder = 0) {
a6600395 128 global $CFG;
129
130 //set type attributs
131 $this->_typename = $typename;
132 $this->_visible = $visible;
133 $this->_sortorder = $sortorder;
46dd6bb0 134
a6600395 135 //set options attribut
136 $this->_options = array();
a5adfa26 137 $options = repository::static_function($typename, 'get_type_option_names');
a6600395 138 //check that the type can be setup
06e65e1e 139 if (!empty($options)) {
a6600395 140 //set the type options
141 foreach ($options as $config) {
a5adfa26 142 if (array_key_exists($config, $typeoptions)) {
7a3b93c1 143 $this->_options[$config] = $typeoptions[$config];
a6600395 144 }
145 }
146 }
f48fb4d6 147
148 //retrieve visibility from option
149 if (array_key_exists('enablecourseinstances',$typeoptions)) {
150 $this->_options['enablecourseinstances'] = $typeoptions['enablecourseinstances'];
9f7c761a 151 } else {
152 $this->_options['enablecourseinstances'] = 0;
f48fb4d6 153 }
dbc01944 154
f48fb4d6 155 if (array_key_exists('enableuserinstances',$typeoptions)) {
156 $this->_options['enableuserinstances'] = $typeoptions['enableuserinstances'];
9f7c761a 157 } else {
158 $this->_options['enableuserinstances'] = 0;
f48fb4d6 159 }
dbc01944 160
a6600395 161 }
162
163 /**
164 * Get the type name (no whitespace)
165 * For a human readable name, use get_readablename()
166 * @return String the type name
167 */
7a3b93c1 168 public function get_typename() {
a6600395 169 return $this->_typename;
170 }
171
172 /**
173 * Return a human readable and user-friendly type name
174 * @return string user-friendly type name
175 */
7a3b93c1 176 public function get_readablename() {
614d18d2 177 return get_string('pluginname','repository_'.$this->_typename);
a6600395 178 }
179
180 /**
181 * Return general options
182 * @return array the general options
183 */
7a3b93c1 184 public function get_options() {
a6600395 185 return $this->_options;
186 }
187
188 /**
189 * Return visibility
190 * @return boolean
191 */
7a3b93c1 192 public function get_visible() {
a6600395 193 return $this->_visible;
194 }
195
196 /**
197 * Return order / position of display in the file picker
198 * @return integer
199 */
7a3b93c1 200 public function get_sortorder() {
a6600395 201 return $this->_sortorder;
202 }
203
204 /**
205 * Create a repository type (the type name must not already exist)
a75c78d3 206 * @param boolean throw exception?
207 * @return mixed return int if create successfully, return false if
208 * any errors
a6600395 209 * @global object $DB
210 */
a75c78d3 211 public function create($silent = false) {
a6600395 212 global $DB;
213
214 //check that $type has been set
215 $timmedtype = trim($this->_typename);
216 if (empty($timmedtype)) {
7a3b93c1 217 throw new repository_exception('emptytype', 'repository');
a6600395 218 }
219
220 //set sortorder as the last position in the list
7a3b93c1 221 if (!isset($this->_sortorder) || $this->_sortorder == 0 ) {
a6600395 222 $sql = "SELECT MAX(sortorder) FROM {repository}";
223 $this->_sortorder = 1 + $DB->get_field_sql($sql);
224 }
225
226 //only create a new type if it doesn't already exist
227 $existingtype = $DB->get_record('repository', array('type'=>$this->_typename));
7a3b93c1 228 if (!$existingtype) {
229 //create the type
6bdfef5d 230 $newtype = new stdClass();
7a3b93c1 231 $newtype->type = $this->_typename;
232 $newtype->visible = $this->_visible;
233 $newtype->sortorder = $this->_sortorder;
a75c78d3 234 $plugin_id = $DB->insert_record('repository', $newtype);
7a3b93c1 235 //save the options in DB
236 $this->update_options();
237
a5adfa26
DC
238 $instanceoptionnames = repository::static_function($this->_typename, 'get_instance_option_names');
239
edb50637 240 //if the plugin type has no multiple instance (e.g. has no instance option name) so it wont
7a3b93c1 241 //be possible for the administrator to create a instance
242 //in this case we need to create an instance
edb50637 243 if (empty($instanceoptionnames)) {
7a3b93c1 244 $instanceoptions = array();
a5adfa26
DC
245 if (empty($this->_options['pluginname'])) {
246 // when moodle trying to install some repo plugin automatically
247 // this option will be empty, get it from language string when display
248 $instanceoptions['name'] = '';
249 } else {
250 // when admin trying to add a plugin manually, he will type a name
251 // for it
252 $instanceoptions['name'] = $this->_options['pluginname'];
253 }
dbc01944 254 repository::static_function($this->_typename, 'create', $this->_typename, 0, get_system_context(), $instanceoptions);
7a3b93c1 255 }
60c366e8 256 //run plugin_init function
257 if (!repository::static_function($this->_typename, 'plugin_init')) {
258 if (!$silent) {
259 throw new repository_exception('cannotinitplugin', 'repository');
260 }
261 }
262
a75c78d3 263 if(!empty($plugin_id)) {
264 // return plugin_id if create successfully
265 return $plugin_id;
266 } else {
267 return false;
268 }
948c2860 269
7a3b93c1 270 } else {
a75c78d3 271 if (!$silent) {
272 throw new repository_exception('existingrepository', 'repository');
273 }
274 // If plugin existed, return false, tell caller no new plugins were created.
275 return false;
a6600395 276 }
277 }
278
279
280 /**
281 * Update plugin options into the config_plugin table
282 * @param array $options
283 * @return boolean
284 */
7a3b93c1 285 public function update_options($options = null) {
a5adfa26
DC
286 global $DB;
287 $classname = 'repository_' . $this->_typename;
288 $instanceoptions = repository::static_function($this->_typename, 'get_instance_option_names');
289 if (empty($instanceoptions)) {
290 // update repository instance name if this plugin type doesn't have muliti instances
291 $params = array();
292 $params['type'] = $this->_typename;
293 $instances = repository::get_instances($params);
294 $instance = array_pop($instances);
295 if ($instance) {
296 $DB->set_field('repository_instances', 'name', $options['pluginname'], array('id'=>$instance->id));
297 }
298 unset($options['pluginname']);
299 }
300
7a3b93c1 301 if (!empty($options)) {
a6600395 302 $this->_options = $options;
303 }
304
305 foreach ($this->_options as $name => $value) {
a5adfa26 306 set_config($name, $value, $this->_typename);
a6600395 307 }
308
309 return true;
310 }
311
312 /**
313 * Update visible database field with the value given as parameter
314 * or with the visible value of this object
315 * This function is private.
316 * For public access, have a look to switch_and_update_visibility()
317 * @global object $DB
318 * @param boolean $visible
319 * @return boolean
320 */
7a3b93c1 321 private function update_visible($visible = null) {
a6600395 322 global $DB;
323
7a3b93c1 324 if (!empty($visible)) {
a6600395 325 $this->_visible = $visible;
326 }
7a3b93c1 327 else if (!isset($this->_visible)) {
a6600395 328 throw new repository_exception('updateemptyvisible', 'repository');
329 }
330
331 return $DB->set_field('repository', 'visible', $this->_visible, array('type'=>$this->_typename));
332 }
333
334 /**
335 * Update database sortorder field with the value given as parameter
336 * or with the sortorder value of this object
337 * This function is private.
338 * For public access, have a look to move_order()
339 * @global object $DB
340 * @param integer $sortorder
341 * @return boolean
342 */
7a3b93c1 343 private function update_sortorder($sortorder = null) {
a6600395 344 global $DB;
345
7a3b93c1 346 if (!empty($sortorder) && $sortorder!=0) {
a6600395 347 $this->_sortorder = $sortorder;
348 }
349 //if sortorder is not set, we set it as the ;ast position in the list
7a3b93c1 350 else if (!isset($this->_sortorder) || $this->_sortorder == 0 ) {
a6600395 351 $sql = "SELECT MAX(sortorder) FROM {repository}";
352 $this->_sortorder = 1 + $DB->get_field_sql($sql);
353 }
354
355 return $DB->set_field('repository', 'sortorder', $this->_sortorder, array('type'=>$this->_typename));
356 }
357
358 /**
359 * Change order of the type with its adjacent upper or downer type
360 * (database fields are updated)
361 * Algorithm details:
362 * 1. retrieve all types in an array. This array is sorted by sortorder,
363 * and the array keys start from 0 to X (incremented by 1)
364 * 2. switch sortorder values of this type and its adjacent type
365 * @global object $DB
366 * @param string $move "up" or "down"
367 */
368 public function move_order($move) {
369 global $DB;
a6600395 370
dbc01944 371 $types = repository::get_types(); // retrieve all types
7a3b93c1 372
373 /// retrieve this type into the returned array
374 $i = 0;
375 while (!isset($indice) && $i<count($types)) {
376 if ($types[$i]->get_typename() == $this->_typename) {
a6600395 377 $indice = $i;
378 }
379 $i++;
380 }
381
7a3b93c1 382 /// retrieve adjacent indice
a6600395 383 switch ($move) {
384 case "up":
385 $adjacentindice = $indice - 1;
7a3b93c1 386 break;
a6600395 387 case "down":
388 $adjacentindice = $indice + 1;
7a3b93c1 389 break;
a6600395 390 default:
7a3b93c1 391 throw new repository_exception('movenotdefined', 'repository');
a6600395 392 }
393
394 //switch sortorder of this type and the adjacent type
395 //TODO: we could reset sortorder for all types. This is not as good in performance term, but
396 //that prevent from wrong behaviour on a screwed database. As performance are not important in this particular case
397 //it worth to change the algo.
7a3b93c1 398 if ($adjacentindice>=0 && !empty($types[$adjacentindice])) {
a6600395 399 $DB->set_field('repository', 'sortorder', $this->_sortorder, array('type'=>$types[$adjacentindice]->get_typename()));
400 $this->update_sortorder($types[$adjacentindice]->get_sortorder());
401 }
402 }
403
404 /**
79698344
MD
405 * 1. Change visibility to the value chosen
406 *
a6600395 407 * 2. Update the type
2b8beee3 408 * @return boolean
a6600395 409 */
79698344
MD
410 public function update_visibility($visible = null) {
411 if (is_bool($visible)) {
412 $this->_visible = $visible;
413 } else {
414 $this->_visible = !$this->_visible;
415 }
a6600395 416 return $this->update_visible();
417 }
418
419
420 /**
eb239694 421 * Delete a repository_type (general options are removed from config_plugin
422 * table, and all instances are deleted)
a6600395 423 * @global object $DB
424 * @return boolean
425 */
7a3b93c1 426 public function delete() {
a6600395 427 global $DB;
46dd6bb0 428
429 //delete all instances of this type
6f2cd52a
DC
430 $params = array();
431 $params['context'] = array();
432 $params['onlyvisible'] = false;
433 $params['type'] = $this->_typename;
434 $instances = repository::get_instances($params);
7a3b93c1 435 foreach ($instances as $instance) {
46dd6bb0 436 $instance->delete();
437 }
438
eb239694 439 //delete all general options
7a3b93c1 440 foreach ($this->_options as $name => $value) {
eb239694 441 set_config($name, null, $this->_typename);
442 }
443
a6600395 444 return $DB->delete_records('repository', array('type' => $this->_typename));
445 }
446}
447
a6600395 448/**
8d419e59 449 * This is the base class of the repository class
450 *
451 * To use repository plugin, see:
728ebac7 452 * http://docs.moodle.org/dev/Repository_How_to_Create_Plugin
8d419e59 453 * class repository is an abstract class, some functions must be implemented in subclass.
e35194be 454 * See an example: repository/boxnet/lib.php
8d419e59 455 *
456 * A few notes:
457 * // for ajax file picker, this will print a json string to tell file picker
458 * // how to build a login form
459 * $repo->print_login();
460 * // for ajax file picker, this will return a files list.
461 * $repo->get_listing();
462 * // this function will be used for non-javascript version.
463 * $repo->print_listing();
464 * // print a search box
465 * $repo->print_search();
466 *
6f2cd52a
DC
467 * @package moodlecore
468 * @subpackage repository
469 * @copyright 2009 Dongsheng Cai <dongsheng@moodle.com>
470 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
a6600395 471 */
fca079c5 472abstract class repository {
efe018b4 473 // $disabled can be set to true to disable a plugin by force
474 // example: self::$disabled = true
475 public $disabled = false;
4a65c39a 476 public $id;
be85f7ab 477 /** @var object current context */
4a65c39a 478 public $context;
479 public $options;
948c2860 480 public $readonly;
41076c58 481 public $returntypes;
a5adfa26
DC
482 /** @var object repository instance database record */
483 public $instance;
a0ff4137
DC
484 /**
485 * 1. Initialize context and options
486 * 2. Accept necessary parameters
487 *
e35194be
DC
488 * @param integer $repositoryid repository instance id
489 * @param integer|object a context id or context object
490 * @param array $options repository options
a0ff4137 491 */
e35194be 492 public function __construct($repositoryid, $context = SYSCONTEXTID, $options = array(), $readonly = 0) {
a5adfa26 493 global $DB;
a0ff4137 494 $this->id = $repositoryid;
be85f7ab 495 if (is_object($context)) {
e35194be
DC
496 $this->context = $context;
497 } else {
498 $this->context = get_context_instance_by_id($context);
499 }
a5adfa26 500 $this->instance = $DB->get_record('repository_instances', array('id'=>$this->id));
a0ff4137
DC
501 $this->readonly = $readonly;
502 $this->options = array();
e35194be 503
a0ff4137
DC
504 if (is_array($options)) {
505 $options = array_merge($this->get_option(), $options);
506 } else {
507 $options = $this->get_option();
508 }
509 foreach ($options as $n => $v) {
510 $this->options[$n] = $v;
511 }
512 $this->name = $this->get_name();
513 $this->returntypes = $this->supported_returntypes();
514 $this->super_called = true;
515 }
1cf56396 516
dbc01944 517 /**
e35194be 518 * Get a repository type object by a given type name.
dbc01944 519 * @global object $DB
e35194be
DC
520 * @param string $typename the repository type name
521 * @return repository_type|bool
dbc01944 522 */
523 public static function get_type_by_typename($typename) {
524 global $DB;
525
526 if (!$record = $DB->get_record('repository',array('type' => $typename))) {
527 return false;
528 }
529
530 return new repository_type($typename, (array)get_config($typename), $record->visible, $record->sortorder);
531 }
532
533 /**
e35194be 534 * Get the repository type by a given repository type id.
dbc01944 535 * @global object $DB
8e0946bf
DC
536 * @param int $id the type id
537 * @return object
dbc01944 538 */
539 public static function get_type_by_id($id) {
540 global $DB;
541
542 if (!$record = $DB->get_record('repository',array('id' => $id))) {
543 return false;
544 }
545
546 return new repository_type($record->type, (array)get_config($record->type), $record->visible, $record->sortorder);
547 }
548
549 /**
e35194be
DC
550 * Return all repository types ordered by sortorder field
551 * first repository type in returnedarray[0], second repository type in returnedarray[1], ...
dbc01944 552 * @global object $DB
e35194be 553 * @global object $CFG
dbc01944 554 * @param boolean $visible can return types by visiblity, return all types if null
555 * @return array Repository types
556 */
557 public static function get_types($visible=null) {
489d8a75 558 global $DB, $CFG;
dbc01944 559
560 $types = array();
561 $params = null;
562 if (!empty($visible)) {
563 $params = array('visible' => $visible);
564 }
565 if ($records = $DB->get_records('repository',$params,'sortorder')) {
566 foreach($records as $type) {
e35194be 567 if (file_exists($CFG->dirroot . '/repository/'. $type->type .'/lib.php')) {
489d8a75
DC
568 $types[] = new repository_type($type->type, (array)get_config($type->type), $type->visible, $type->sortorder);
569 }
dbc01944 570 }
571 }
572
573 return $types;
574 }
575
576 /**
e35194be
DC
577 * To check if the context id is valid
578 * @global object $USER
579 * @param int $contextid
dbc01944 580 * @return boolean
581 */
be85f7ab 582 public static function check_capability($contextid, $instance) {
e35194be 583 $context = get_context_instance_by_id($contextid);
be85f7ab
DC
584 $capability = has_capability('repository/'.$instance->type.':view', $context);
585 if (!$capability) {
586 throw new repository_exception('nopermissiontoaccess', 'repository');
dbc01944 587 }
dbc01944 588 }
589
f392caba
DC
590 /**
591 * Check if file already exists in draft area
592 *
593 * @param int $itemid
594 * @param string $filepath
595 * @param string $filename
596 * @return boolean
597 */
598 public static function draftfile_exists($itemid, $filepath, $filename) {
599 global $USER;
600 $fs = get_file_storage();
601 $usercontext = get_context_instance(CONTEXT_USER, $USER->id);
602 if ($fs->get_file($usercontext->id, 'user', 'draft', $itemid, $filepath, $filename)) {
603 return true;
604 } else {
605 return false;
606 }
607 }
608
609 /**
610 * Does this repository used to browse moodle files?
611 *
612 * @return boolean
613 */
614 public function has_moodle_files() {
615 return false;
616 }
617 /**
618 * This function is used to copy a moodle file to draft area
619 *
620 * @global object $USER
621 * @global object $DB
622 * @param string $encoded The metainfo of file, it is base64 encoded php serialized data
623 * @param string $draftitemid itemid
624 * @param string $new_filename The intended name of file
625 * @param string $new_filepath the new path in draft area
626 * @return array The information of file
627 */
628 public function copy_to_area($encoded, $draftitemid, $new_filepath, $new_filename) {
629 global $USER, $DB;
630
631 if ($this->has_moodle_files() == false) {
632 throw new coding_exception('Only repository used to browse moodle files can use copy_to_area');
633 }
634
635 $browser = get_file_browser();
636 $params = unserialize(base64_decode($encoded));
637 $user_context = get_context_instance(CONTEXT_USER, $USER->id);
638
639 $contextid = clean_param($params['contextid'], PARAM_INT);
640 $fileitemid = clean_param($params['itemid'], PARAM_INT);
641 $filename = clean_param($params['filename'], PARAM_FILE);
642 $filepath = clean_param($params['filepath'], PARAM_PATH);;
aff24313
PS
643 $filearea = clean_param($params['filearea'], PARAM_AREA);
644 $component = clean_param($params['component'], PARAM_COMPONENT);
f392caba
DC
645
646 $context = get_context_instance_by_id($contextid);
647 // the file needs to copied to draft area
648 $file_info = $browser->get_file_info($context, $component, $filearea, $fileitemid, $filepath, $filename);
649
650 if (repository::draftfile_exists($draftitemid, $new_filepath, $new_filename)) {
651 // create new file
652 $unused_filename = repository::get_unused_filename($draftitemid, $new_filepath, $new_filename);
653 $file_info->copy_to_storage($user_context->id, 'user', 'draft', $draftitemid, $new_filepath, $unused_filename);
654 $event = array();
655 $event['event'] = 'fileexists';
656 $event['newfile'] = new stdClass;
657 $event['newfile']->filepath = $new_filepath;
658 $event['newfile']->filename = $unused_filename;
659 $event['newfile']->url = moodle_url::make_draftfile_url($draftitemid, $new_filepath, $unused_filename)->out();
660 $event['existingfile'] = new stdClass;
661 $event['existingfile']->filepath = $new_filepath;
662 $event['existingfile']->filename = $new_filename;
663 $event['existingfile']->url = moodle_url::make_draftfile_url($draftitemid, $filepath, $filename)->out();;
664 return $event;
665 } else {
666 $file_info->copy_to_storage($user_context->id, 'user', 'draft', $draftitemid, $new_filepath, $new_filename);
667 $info = array();
668 $info['itemid'] = $draftitemid;
669 $info['title'] = $new_filename;
670 $info['contextid'] = $user_context->id;
671 $info['url'] = moodle_url::make_draftfile_url($draftitemid, $new_filepath, $new_filename)->out();;
672 $info['filesize'] = $file_info->get_filesize();
673 return $info;
674 }
675 }
676
677 /**
678 * Get unused filename by appending suffix
679 *
680 * @param int $itemid
681 * @param string $filepath
682 * @param string $filename
683 * @return string
684 */
685 public static function get_unused_filename($itemid, $filepath, $filename) {
686 global $USER;
687 $fs = get_file_storage();
688 while (repository::draftfile_exists($itemid, $filepath, $filename)) {
689 $filename = repository::append_suffix($filename);
690 }
691 return $filename;
692 }
693
694 /**
695 * Append a suffix to filename
696 *
697 * @param string $filename
698 * @return string
699 */
700 function append_suffix($filename) {
701 $pathinfo = pathinfo($filename);
702 if (empty($pathinfo['extension'])) {
703 return $filename . RENAME_SUFFIX;
704 } else {
705 return $pathinfo['filename'] . RENAME_SUFFIX . '.' . $pathinfo['extension'];
706 }
707 }
708
dbc01944 709 /**
710 * Return all types that you a user can create/edit and which are also visible
711 * Note: Mostly used in order to know if at least one editable type can be set
712 * @param object $context the context for which we want the editable types
713 * @return array types
714 */
715 public static function get_editable_types($context = null) {
716
717 if (empty($context)) {
718 $context = get_system_context();
719 }
720
721 $types= repository::get_types(true);
722 $editabletypes = array();
723 foreach ($types as $type) {
724 $instanceoptionnames = repository::static_function($type->get_typename(), 'get_instance_option_names');
725 if (!empty($instanceoptionnames)) {
5363905a 726 if ($type->get_contextvisibility($context)) {
dbc01944 727 $editabletypes[]=$type;
728 }
729 }
730 }
731 return $editabletypes;
732 }
733
734 /**
735 * Return repository instances
736 * @global object $DB
737 * @global object $CFG
738 * @global object $USER
92a89068
PL
739 *
740 * @param array $args Array containing the following keys:
741 * currentcontext
742 * context
743 * onlyvisible
744 * type
745 * accepted_types
8e0946bf 746 * return_types
92a89068
PL
747 * userid
748 *
dbc01944 749 * @return array repository instances
750 */
6f2cd52a 751 public static function get_instances($args = array()) {
dbc01944 752 global $DB, $CFG, $USER;
753
6f2cd52a
DC
754 if (isset($args['currentcontext'])) {
755 $current_context = $args['currentcontext'];
756 } else {
757 $current_context = null;
758 }
759
760 if (!empty($args['context'])) {
761 $contexts = $args['context'];
762 } else {
763 $contexts = array();
764 }
765
766 $onlyvisible = isset($args['onlyvisible']) ? $args['onlyvisible'] : true;
e35194be 767 $returntypes = isset($args['return_types']) ? $args['return_types'] : 3;
6f2cd52a 768 $type = isset($args['type']) ? $args['type'] : null;
6f2cd52a 769
dbc01944 770 $params = array();
a090554a
PS
771 $sql = "SELECT i.*, r.type AS repositorytype, r.sortorder, r.visible
772 FROM {repository} r, {repository_instances} i
773 WHERE i.typeid = r.id ";
dbc01944 774
227dfa43 775 if (!empty($args['disable_types']) && is_array($args['disable_types'])) {
cf717dc2 776 list($types, $p) = $DB->get_in_or_equal($args['disable_types'], SQL_PARAMS_QM, 'param', false);
a090554a 777 $sql .= " AND r.type $types";
227dfa43
DC
778 $params = array_merge($params, $p);
779 }
780
6f2cd52a 781 if (!empty($args['userid']) && is_numeric($args['userid'])) {
a090554a 782 $sql .= " AND (i.userid = 0 or i.userid = ?)";
6f2cd52a 783 $params[] = $args['userid'];
dbc01944 784 }
227dfa43 785
dbc01944 786 foreach ($contexts as $context) {
787 if (empty($firstcontext)) {
788 $firstcontext = true;
a090554a 789 $sql .= " AND ((i.contextid = ?)";
dbc01944 790 } else {
a090554a 791 $sql .= " OR (i.contextid = ?)";
dbc01944 792 }
793 $params[] = $context->id;
794 }
795
796 if (!empty($firstcontext)) {
797 $sql .=')';
798 }
799
800 if ($onlyvisible == true) {
a090554a 801 $sql .= " AND (r.visible = 1)";
dbc01944 802 }
803
804 if (isset($type)) {
a090554a 805 $sql .= " AND (r.type = ?)";
dbc01944 806 $params[] = $type;
807 }
a090554a 808 $sql .= " ORDER BY r.sortorder, i.name";
50a5cf09 809
6f2cd52a
DC
810 if (!$records = $DB->get_records_sql($sql, $params)) {
811 $records = array();
dbc01944 812 }
813
6f2cd52a 814 $repositories = array();
99eaca9d 815 $ft = new filetype_parser();
1e0b0415
DC
816 if (isset($args['accepted_types'])) {
817 $accepted_types = $args['accepted_types'];
818 } else {
819 $accepted_types = '*';
820 }
6f2cd52a 821 foreach ($records as $record) {
e35194be 822 if (!file_exists($CFG->dirroot . '/repository/'. $record->repositorytype.'/lib.php')) {
062d21cd
DC
823 continue;
824 }
e35194be 825 require_once($CFG->dirroot . '/repository/'. $record->repositorytype.'/lib.php');
6f2cd52a 826 $options['visible'] = $record->visible;
6f2cd52a
DC
827 $options['type'] = $record->repositorytype;
828 $options['typeid'] = $record->typeid;
36ef6643 829 $options['sortorder'] = $record->sortorder;
c167aa26 830 // tell instance what file types will be accepted by file picker
6f2cd52a
DC
831 $classname = 'repository_' . $record->repositorytype;
832
833 $repository = new $classname($record->id, $record->contextid, $options, $record->readonly);
834
014c1ca0 835 $is_supported = true;
dbc01944 836
271bd2e0 837 if (empty($repository->super_called)) {
6f2cd52a
DC
838 // to make sure the super construct is called
839 debugging('parent::__construct must be called by '.$record->repositorytype.' plugin.');
271bd2e0 840 } else {
6f2cd52a 841 // check mimetypes
99eaca9d
DC
842 if ($accepted_types !== '*' and $repository->supported_filetypes() !== '*') {
843 $accepted_types = $ft->get_extensions($accepted_types);
844 $supported_filetypes = $ft->get_extensions($repository->supported_filetypes());
6f2cd52a 845
271bd2e0 846 $is_supported = false;
847 foreach ($supported_filetypes as $type) {
99eaca9d 848 if (in_array($type, $accepted_types)) {
271bd2e0 849 $is_supported = true;
850 }
014c1ca0 851 }
6f2cd52a 852
014c1ca0 853 }
6f2cd52a 854 // check return values
41076c58
DC
855 if ($returntypes !== 3 and $repository->supported_returntypes() !== 3) {
856 $type = $repository->supported_returntypes();
857 if ($type & $returntypes) {
858 //
859 } else {
860 $is_supported = false;
271bd2e0 861 }
014c1ca0 862 }
d3959c26 863
271bd2e0 864 if (!$onlyvisible || ($repository->is_visible() && !$repository->disabled)) {
6f2cd52a
DC
865 // check capability in current context
866 if (!empty($current_context)) {
867 $capability = has_capability('repository/'.$record->repositorytype.':view', $current_context);
868 } else {
6f2cd52a
DC
869 $capability = has_capability('repository/'.$record->repositorytype.':view', get_system_context());
870 }
d3959c26
DC
871 if ($record->repositorytype == 'coursefiles') {
872 // coursefiles plugin needs managefiles permission
1fbbf893
PS
873 if (!empty($current_context)) {
874 $capability = $capability && has_capability('moodle/course:managefiles', $current_context);
875 } else {
876 $capability = $capability && has_capability('moodle/course:managefiles', get_system_context());
877 }
d3959c26 878 }
c86dde2e 879 if ($is_supported && $capability) {
99eaca9d 880 $repositories[$repository->id] = $repository;
271bd2e0 881 }
014c1ca0 882 }
dbc01944 883 }
884 }
6f2cd52a 885 return $repositories;
dbc01944 886 }
887
888 /**
889 * Get single repository instance
890 * @global object $DB
891 * @global object $CFG
892 * @param integer $id repository id
893 * @return object repository instance
894 */
895 public static function get_instance($id) {
896 global $DB, $CFG;
a090554a
PS
897 $sql = "SELECT i.*, r.type AS repositorytype, r.visible
898 FROM {repository} r
899 JOIN {repository_instances} i ON i.typeid = r.id
900 WHERE i.id = ?";
dbc01944 901
a090554a 902 if (!$instance = $DB->get_record_sql($sql, array($id))) {
dbc01944 903 return false;
904 }
e35194be 905 require_once($CFG->dirroot . '/repository/'. $instance->repositorytype.'/lib.php');
dbc01944 906 $classname = 'repository_' . $instance->repositorytype;
907 $options['typeid'] = $instance->typeid;
908 $options['type'] = $instance->repositorytype;
909 $options['name'] = $instance->name;
271bd2e0 910 $obj = new $classname($instance->id, $instance->contextid, $options, $instance->readonly);
911 if (empty($obj->super_called)) {
912 debugging('parent::__construct must be called by '.$classname.' plugin.');
913 }
914 return $obj;
dbc01944 915 }
916
917 /**
e35194be 918 * Call a static function. Any additional arguments than plugin and function will be passed through.
2b8beee3 919 * @global object $CFG
920 * @param string $plugin
921 * @param string $function
2b8beee3 922 * @return mixed
dbc01944 923 */
924 public static function static_function($plugin, $function) {
925 global $CFG;
926
927 //check that the plugin exists
e35194be 928 $typedirectory = $CFG->dirroot . '/repository/'. $plugin . '/lib.php';
dbc01944 929 if (!file_exists($typedirectory)) {
f1cfe56e 930 //throw new repository_exception('invalidplugin', 'repository');
931 return false;
dbc01944 932 }
933
934 $pname = null;
935 if (is_object($plugin) || is_array($plugin)) {
936 $plugin = (object)$plugin;
937 $pname = $plugin->name;
938 } else {
939 $pname = $plugin;
940 }
941
942 $args = func_get_args();
943 if (count($args) <= 2) {
944 $args = array();
e35194be 945 } else {
dbc01944 946 array_shift($args);
947 array_shift($args);
948 }
949
950 require_once($typedirectory);
81bdfdb9 951 return call_user_func_array(array('repository_' . $plugin, $function), $args);
dbc01944 952 }
953
23bfe0a4
PS
954 /**
955 * Scan file, throws exception in case of infected file.
956 *
957 * Please note that the scanning engine must be able to access the file,
958 * permissions of the file are not modified here!
959 *
960 * @static
961 * @param string $thefile
962 * @param string $filename name of the file
963 * @param bool $deleteinfected
964 * @return void
965 */
966 public static function antivir_scan_file($thefile, $filename, $deleteinfected) {
967 global $CFG;
968
969 if (!is_readable($thefile)) {
970 // this should not happen
971 return;
972 }
973
974 if (empty($CFG->runclamonupload) or empty($CFG->pathtoclam)) {
975 // clam not enabled
976 return;
977 }
978
979 $CFG->pathtoclam = trim($CFG->pathtoclam);
980
981 if (!file_exists($CFG->pathtoclam) or !is_executable($CFG->pathtoclam)) {
982 // misconfigured clam - use the old notification for now
983 require("$CFG->libdir/uploadlib.php");
984 $notice = get_string('clamlost', 'moodle', $CFG->pathtoclam);
985 clam_message_admins($notice);
986 return;
987 }
988
989 // do NOT mess with permissions here, the calling party is responsible for making
990 // sure the scanner engine can access the files!
991
992 // execute test
993 $cmd = escapeshellcmd($CFG->pathtoclam).' --stdout '.escapeshellarg($thefile);
994 exec($cmd, $output, $return);
995
996 if ($return == 0) {
997 // perfect, no problem found
998 return;
999
1000 } else if ($return == 1) {
1001 // infection found
1002 if ($deleteinfected) {
1003 unlink($thefile);
1004 }
1005 throw new moodle_exception('virusfounduser', 'moodle', '', array('filename'=>$filename));
1006
1007 } else {
1008 //unknown problem
1009 require("$CFG->libdir/uploadlib.php");
1010 $notice = get_string('clamfailed', 'moodle', get_clam_error_code($return));
1011 $notice .= "\n\n". implode("\n", $output);
1012 clam_message_admins($notice);
1013 if ($CFG->clamfailureonupload === 'actlikevirus') {
1014 if ($deleteinfected) {
1015 unlink($thefile);
1016 }
1017 throw new moodle_exception('virusfounduser', 'moodle', '', array('filename'=>$filename));
1018 } else {
1019 return;
1020 }
1021 }
1022 }
1023
dbc01944 1024 /**
1025 * Move file from download folder to file pool using FILE API
1026 * @global object $DB
1027 * @global object $CFG
1028 * @global object $USER
1a6195b4 1029 * @global object $OUTPUT
8e0946bf 1030 * @param string $thefile file path in download folder
50dea1b7 1031 * @param object $record
1a6195b4
DC
1032 * @return array containing the following keys:
1033 * icon
1034 * file
1035 * id
1036 * url
dbc01944 1037 */
14469892 1038 public static function move_to_filepool($thefile, $record) {
390baf46 1039 global $DB, $CFG, $USER, $OUTPUT;
23bfe0a4
PS
1040
1041 // scan for viruses if possible, throws exception if problem found
1042 self::antivir_scan_file($thefile, $record->filename, empty($CFG->repository_no_delete)); //TODO: MDL-28637 this repository_no_delete is a bloody hack!
1043
14469892
DC
1044 if ($record->filepath !== '/') {
1045 $record->filepath = trim($record->filepath, '/');
1046 $record->filepath = '/'.$record->filepath.'/';
e5fa0e8d 1047 }
dbc01944 1048 $context = get_context_instance(CONTEXT_USER, $USER->id);
1049 $now = time();
14469892
DC
1050
1051 $record->contextid = $context->id;
64f93798
PS
1052 $record->component = 'user';
1053 $record->filearea = 'draft';
14469892
DC
1054 $record->timecreated = $now;
1055 $record->timemodified = $now;
1056 $record->userid = $USER->id;
1057 $record->mimetype = mimeinfo('type', $thefile);
1058 if(!is_numeric($record->itemid)) {
1059 $record->itemid = 0;
dbc01944 1060 }
dbc01944 1061 $fs = get_file_storage();
64f93798 1062 if ($existingfile = $fs->get_file($context->id, $record->component, $record->filearea, $record->itemid, $record->filepath, $record->filename)) {
f392caba
DC
1063 $draftitemid = $record->itemid;
1064 $new_filename = repository::get_unused_filename($draftitemid, $record->filepath, $record->filename);
1065 $old_filename = $record->filename;
1066 // create a tmp file
1067 $record->filename = $new_filename;
1068 $newfile = $fs->create_file_from_pathname($record, $thefile);
1069 $event = array();
1070 $event['event'] = 'fileexists';
1071 $event['newfile'] = new stdClass;
1072 $event['newfile']->filepath = $record->filepath;
1073 $event['newfile']->filename = $new_filename;
1074 $event['newfile']->url = moodle_url::make_draftfile_url($draftitemid, $record->filepath, $new_filename)->out();
1075
1076 $event['existingfile'] = new stdClass;
1077 $event['existingfile']->filepath = $record->filepath;
1078 $event['existingfile']->filename = $old_filename;
1079 $event['existingfile']->url = moodle_url::make_draftfile_url($draftitemid, $record->filepath, $old_filename)->out();;
1080 return $event;
b423b4af 1081 }
14469892 1082 if ($file = $fs->create_file_from_pathname($record, $thefile)) {
88b126a5 1083 if (empty($CFG->repository_no_delete)) {
99eaca9d 1084 $delete = unlink($thefile);
88b126a5 1085 unset($CFG->repository_no_delete);
1086 }
64f93798 1087 return array(
50a8bd6c 1088 'url'=>moodle_url::make_draftfile_url($file->get_itemid(), $file->get_filepath(), $file->get_filename())->out(),
64f93798
PS
1089 'id'=>$file->get_itemid(),
1090 'file'=>$file->get_filename(),
1091 'icon' => $OUTPUT->pix_url(file_extension_icon($thefile, 32))->out(),
1092 );
dbc01944 1093 } else {
1094 return null;
1095 }
1096 }
1097
dbc01944 1098 /**
1099 * Builds a tree of files This function is
1100 * then called recursively.
1101 *
1102 * @param $fileinfo an object returned by file_browser::get_file_info()
1103 * @param $search searched string
1104 * @param $dynamicmode bool no recursive call is done when in dynamic mode
1105 * @param $list - the array containing the files under the passed $fileinfo
1106 * @returns int the number of files found
1107 *
1108 * todo: take $search into account, and respect a threshold for dynamic loading
1109 */
1110 public static function build_tree($fileinfo, $search, $dynamicmode, &$list) {
390baf46 1111 global $CFG, $OUTPUT;
dbc01944 1112
1113 $filecount = 0;
1114 $children = $fileinfo->get_children();
1115
1116 foreach ($children as $child) {
1117 $filename = $child->get_visible_name();
1118 $filesize = $child->get_filesize();
1119 $filesize = $filesize ? display_size($filesize) : '';
1120 $filedate = $child->get_timemodified();
1121 $filedate = $filedate ? userdate($filedate) : '';
1122 $filetype = $child->get_mimetype();
1123
1124 if ($child->is_directory()) {
1125 $path = array();
1126 $level = $child->get_parent();
1127 while ($level) {
1128 $params = $level->get_params();
64f93798 1129 $path[] = array($params['filepath'], $level->get_visible_name());
dbc01944 1130 $level = $level->get_parent();
1131 }
1132
1133 $tmp = array(
1134 'title' => $child->get_visible_name(),
1135 'size' => 0,
1136 'date' => $filedate,
1137 'path' => array_reverse($path),
b5d0cafc 1138 'thumbnail' => $OUTPUT->pix_url('f/folder-32')
dbc01944 1139 );
1140
1141 //if ($dynamicmode && $child->is_writable()) {
1142 // $tmp['children'] = array();
1143 //} else {
1144 // if folder name matches search, we send back all files contained.
1145 $_search = $search;
1146 if ($search && stristr($tmp['title'], $search) !== false) {
1147 $_search = false;
1148 }
1149 $tmp['children'] = array();
1150 $_filecount = repository::build_tree($child, $_search, $dynamicmode, $tmp['children']);
1151 if ($search && $_filecount) {
1152 $tmp['expanded'] = 1;
1153 }
1154
1155 //}
1156
fc3ec2ca 1157 if (!$search || $_filecount || (stristr($tmp['title'], $search) !== false)) {
dbc01944 1158 $filecount += $_filecount;
1159 $list[] = $tmp;
1160 }
1161
1162 } else { // not a directory
1163 // skip the file, if we're in search mode and it's not a match
1164 if ($search && (stristr($filename, $search) === false)) {
1165 continue;
1166 }
1167 $params = $child->get_params();
64f93798 1168 $source = serialize(array($params['contextid'], $params['component'], $params['filearea'], $params['itemid'], $params['filepath'], $params['filename']));
dbc01944 1169 $list[] = array(
1170 'title' => $filename,
1171 'size' => $filesize,
1172 'date' => $filedate,
1173 //'source' => $child->get_url(),
1174 'source' => base64_encode($source),
b5d0cafc 1175 'thumbnail'=>$OUTPUT->pix_url(file_extension_icon($filename, 32)),
dbc01944 1176 );
1177 $filecount++;
1178 }
1179 }
1180
1181 return $filecount;
1182 }
1183
1184
1185 /**
1186 * Display a repository instance list (with edit/delete/create links)
1187 * @global object $CFG
1188 * @global object $USER
8e0946bf 1189 * @global object $OUTPUT
dbc01944 1190 * @param object $context the context for which we display the instance
1191 * @param string $typename if set, we display only one type of instance
1192 */
1193 public static function display_instances_list($context, $typename = null) {
50a5cf09 1194 global $CFG, $USER, $OUTPUT;
dbc01944 1195
50a5cf09 1196 $output = $OUTPUT->box_start('generalbox');
dbc01944 1197 //if the context is SYSTEM, so we call it from administration page
1198 $admin = ($context->id == SYSCONTEXTID) ? true : false;
1199 if ($admin) {
e35194be
DC
1200 $baseurl = new moodle_url('/'.$CFG->admin.'/repositoryinstance.php', array('sesskey'=>sesskey()));
1201 $output .= $OUTPUT->heading(get_string('siteinstances', 'repository'));
dbc01944 1202 } else {
e35194be 1203 $baseurl = new moodle_url('/repository/manage_instances.php', array('contextid'=>$context->id, 'sesskey'=>sesskey()));
dbc01944 1204 }
e35194be 1205 $url = $baseurl;
dbc01944 1206
1207 $namestr = get_string('name');
1208 $pluginstr = get_string('plugin', 'repository');
1209 $settingsstr = get_string('settings');
1210 $deletestr = get_string('delete');
dbc01944 1211 //retrieve list of instances. In administration context we want to display all
1212 //instances of a type, even if this type is not visible. In course/user context we
92eaeca5 1213 //want to display only visible instances, but for every type types. The repository::get_instances()
dbc01944 1214 //third parameter displays only visible type.
6f2cd52a
DC
1215 $params = array();
1216 $params['context'] = array($context, get_system_context());
1217 $params['currentcontext'] = $context;
1218 $params['onlyvisible'] = !$admin;
1219 $params['type'] = $typename;
1220 $instances = repository::get_instances($params);
dbc01944 1221 $instancesnumber = count($instances);
1222 $alreadyplugins = array();
1223
55400db0 1224 $table = new html_table();
79698344 1225 $table->head = array($namestr, $pluginstr, $settingsstr, $deletestr);
dbc01944 1226 $table->align = array('left', 'left', 'center','center');
1227 $table->data = array();
1228
1229 $updowncount = 1;
1230
1231 foreach ($instances as $i) {
1232 $settings = '';
1233 $delete = '';
5363905a
DC
1234
1235 $type = repository::get_type_by_id($i->options['typeid']);
1236
1237 if ($type->get_contextvisibility($context)) {
1238 if (!$i->readonly) {
1239
1240 $url->param('type', $i->options['type']);
1241 $url->param('edit', $i->id);
0f4c64b7 1242 $settings .= html_writer::link($url, $settingsstr);
5363905a
DC
1243
1244 $url->remove_params('edit');
1245 $url->param('delete', $i->id);
0f4c64b7 1246 $delete .= html_writer::link($url, $deletestr);
5363905a
DC
1247
1248 $url->remove_params('type');
1249 }
dbc01944 1250 }
1251
a3d8df25 1252 $type = repository::get_type_by_id($i->options['typeid']);
79698344 1253 $table->data[] = array($i->name, $type->get_readablename(), $settings, $delete);
dbc01944 1254
1255 //display a grey row if the type is defined as not visible
1256 if (isset($type) && !$type->get_visible()) {
704ac344 1257 $table->rowclasses[] = 'dimmed_text';
dbc01944 1258 } else {
704ac344 1259 $table->rowclasses[] = '';
dbc01944 1260 }
1261
1262 if (!in_array($i->name, $alreadyplugins)) {
1263 $alreadyplugins[] = $i->name;
1264 }
1265 }
16be8974 1266 $output .= html_writer::table($table);
dbc01944 1267 $instancehtml = '<div>';
1268 $addable = 0;
1269
1270 //if no type is set, we can create all type of instance
1271 if (!$typename) {
1272 $instancehtml .= '<h3>';
1273 $instancehtml .= get_string('createrepository', 'repository');
1274 $instancehtml .= '</h3><ul>';
1275 $types = repository::get_editable_types($context);
1276 foreach ($types as $type) {
1277 if (!empty($type) && $type->get_visible()) {
1278 $instanceoptionnames = repository::static_function($type->get_typename(), 'get_instance_option_names');
1279 if (!empty($instanceoptionnames)) {
e35194be
DC
1280 $baseurl->param('new', $type->get_typename());
1281 $instancehtml .= '<li><a href="'.$baseurl->out().'">'.get_string('createxxinstance', 'repository', get_string('pluginname', 'repository_'.$type->get_typename())). '</a></li>';
1282 $baseurl->remove_params('new');
dbc01944 1283 $addable++;
1284 }
1285 }
1286 }
1287 $instancehtml .= '</ul>';
1288
1289 } else {
1290 $instanceoptionnames = repository::static_function($typename, 'get_instance_option_names');
1291 if (!empty($instanceoptionnames)) { //create a unique type of instance
1292 $addable = 1;
e35194be
DC
1293 $baseurl->param('new', $typename);
1294 $instancehtml .= "<form action='".$baseurl->out()."' method='post'>
1295 <p><input type='submit' value='".get_string('createinstance', 'repository')."'/></p>
dbc01944 1296 </form>";
e35194be 1297 $baseurl->remove_params('new');
dbc01944 1298 }
1299 }
1300
1301 if ($addable) {
1302 $instancehtml .= '</div>';
1303 $output .= $instancehtml;
1304 }
1305
50a5cf09 1306 $output .= $OUTPUT->box_end();
dbc01944 1307
1308 //print the list + creation links
1309 print($output);
1310 }
1cf56396 1311
c425472d 1312 /**
e35194be 1313 * Decide where to save the file, can be overwriten by subclass
a53d4f45 1314 * @param string filename
c425472d 1315 */
a560785f 1316 public function prepare_file($filename) {
c425472d 1317 global $CFG;
7aa06e6d
TL
1318 if (!file_exists($CFG->tempdir.'/download')) {
1319 mkdir($CFG->tempdir.'/download/', $CFG->directorypermissions, true);
1e28c767 1320 }
7aa06e6d
TL
1321 if (is_dir($CFG->tempdir.'/download')) {
1322 $dir = $CFG->tempdir.'/download/';
1e28c767 1323 }
a560785f 1324 if (empty($filename)) {
cedc3d33 1325 $filename = uniqid('repo', true).'_'.time().'.tmp';
84df43de 1326 }
a560785f 1327 if (file_exists($dir.$filename)) {
1328 $filename = uniqid('m').$filename;
c425472d 1329 }
a560785f 1330 return $dir.$filename;
a53d4f45 1331 }
1332
99d52655
DC
1333 /**
1334 * Return file URL, for most plugins, the parameter is the original
1335 * url, but some plugins use a file id, so we need this function to
1336 * convert file id to original url.
1337 *
1338 * @param string $url the url of file
8e0946bf 1339 * @return string
99d52655
DC
1340 */
1341 public function get_link($url) {
1342 return $url;
1343 }
1344
a53d4f45 1345 /**
1346 * Download a file, this function can be overridden by
1347 * subclass.
1348 *
1349 * @global object $CFG
1350 * @param string $url the url of file
a560785f 1351 * @param string $filename save location
a53d4f45 1352 * @return string the location of the file
1353 * @see curl package
1354 */
a560785f 1355 public function get_file($url, $filename = '') {
a53d4f45 1356 global $CFG;
41076c58
DC
1357 $path = $this->prepare_file($filename);
1358 $fp = fopen($path, 'w');
1359 $c = new curl;
1360 $c->download(array(array('url'=>$url, 'file'=>$fp)));
1dce6261 1361 return array('path'=>$path, 'url'=>$url);
82669dc4 1362 }
1cf56396 1363
c0d60b3a
AKA
1364 /**
1365 * Return size of a file in bytes.
1366 *
1367 * @param string $source encoded and serialized data of file
1368 * @return integer file size in bytes
1369 */
1370 public function get_file_size($source) {
1371 $browser = get_file_browser();
1372 $params = unserialize(base64_decode($source));
1373 $contextid = clean_param($params['contextid'], PARAM_INT);
1374 $fileitemid = clean_param($params['itemid'], PARAM_INT);
1375 $filename = clean_param($params['filename'], PARAM_FILE);
1376 $filepath = clean_param($params['filepath'], PARAM_PATH);
aff24313
PS
1377 $filearea = clean_param($params['filearea'], PARAM_AREA);
1378 $component = clean_param($params['component'], PARAM_COMPONENT);
c0d60b3a
AKA
1379 $context = get_context_instance_by_id($contextid);
1380 $file_info = $browser->get_file_info($context, $component, $filearea, $fileitemid, $filepath, $filename);
1381 if (!empty($file_info)) {
1382 $filesize = $file_info->get_filesize();
1383 } else {
1384 $filesize = null;
1385 }
1386 return $filesize;
1387 }
1388
f48fb4d6 1389 /**
1390 * Return is the instance is visible
1391 * (is the type visible ? is the context enable ?)
1392 * @return boolean
1393 */
dbc01944 1394 public function is_visible() {
7d554b64 1395 $type = repository::get_type_by_id($this->options['typeid']);
dbc01944 1396 $instanceoptions = repository::static_function($type->get_typename(), 'get_instance_option_names');
f48fb4d6 1397
1398 if ($type->get_visible()) {
1399 //if the instance is unique so it's visible, otherwise check if the instance has a enabled context
5363905a 1400 if (empty($instanceoptions) || $type->get_contextvisibility($this->context)) {
f48fb4d6 1401 return true;
1402 }
1403 }
1404
1405 return false;
1406 }
1407
eb239694 1408 /**
66dc47bc 1409 * Return the name of this instance, can be overridden.
2b8beee3 1410 * @global object $DB
1411 * @return string
eb239694 1412 */
7a3b93c1 1413 public function get_name() {
d31af46a 1414 global $DB;
a5adfa26
DC
1415 if ( $name = $this->instance->name ) {
1416 return $name;
d31af46a 1417 } else {
a5adfa26 1418 return get_string('pluginname', 'repository_' . $this->options['type']);
d31af46a 1419 }
1420 }
aa754fe3 1421
b318bb6d 1422 /**
1423 * what kind of files will be in this repository?
1424 * @return array return '*' means this repository support any files, otherwise
1425 * return mimetypes of files, it can be an array
1426 */
014c1ca0 1427 public function supported_filetypes() {
b318bb6d 1428 // return array('text/plain', 'image/gif');
1429 return '*';
1430 }
1431
1432 /**
1433 * does it return a file url or a item_id
1434 * @return string
1435 */
41076c58
DC
1436 public function supported_returntypes() {
1437 return (FILE_INTERNAL | FILE_EXTERNAL);
92eaeca5 1438 }
b318bb6d 1439
82669dc4 1440 /**
3f24ea1e 1441 * Provide repository instance information for Ajax
8dcd5deb 1442 * @global object $CFG
4a65c39a 1443 * @return object
82669dc4 1444 */
7d554b64 1445 final public function get_meta() {
c82d7320 1446 global $CFG, $OUTPUT;
99eaca9d 1447 $ft = new filetype_parser;
6bdfef5d 1448 $meta = new stdClass();
7d554b64 1449 $meta->id = $this->id;
1450 $meta->name = $this->get_name();
1451 $meta->type = $this->options['type'];
c82d7320 1452 $meta->icon = $OUTPUT->pix_url('icon', 'repository_'.$meta->type)->out(false);
99eaca9d 1453 $meta->supported_types = $ft->get_extensions($this->supported_filetypes());
6f2cd52a 1454 $meta->return_types = $this->supported_returntypes();
36ef6643 1455 $meta->sortorder = $this->options['sortorder'];
7d554b64 1456 return $meta;
4a65c39a 1457 }
1cf56396 1458
b1339e98 1459 /**
1460 * Create an instance for this plug-in
8dcd5deb 1461 * @global object $CFG
1462 * @global object $DB
1463 * @param string $type the type of the repository
1464 * @param integer $userid the user id
1465 * @param object $context the context
1466 * @param array $params the options for this instance
635f1a8b 1467 * @param integer $readonly whether to create it readonly or not (defaults to not)
2b8beee3 1468 * @return mixed
b1339e98 1469 */
49d20def 1470 public static function create($type, $userid, $context, $params, $readonly=0) {
b1339e98 1471 global $CFG, $DB;
1472 $params = (array)$params;
e35194be 1473 require_once($CFG->dirroot . '/repository/'. $type . '/lib.php');
b1339e98 1474 $classname = 'repository_' . $type;
3023078f 1475 if ($repo = $DB->get_record('repository', array('type'=>$type))) {
6bdfef5d 1476 $record = new stdClass();
3023078f 1477 $record->name = $params['name'];
1478 $record->typeid = $repo->id;
1479 $record->timecreated = time();
1480 $record->timemodified = time();
1481 $record->contextid = $context->id;
948c2860 1482 $record->readonly = $readonly;
3023078f 1483 $record->userid = $userid;
1484 $id = $DB->insert_record('repository_instances', $record);
0a6221f9 1485 $options = array();
edb50637 1486 $configs = call_user_func($classname . '::get_instance_option_names');
1e08b5cf 1487 if (!empty($configs)) {
1488 foreach ($configs as $config) {
14b2d8d8
DC
1489 if (isset($params[$config])) {
1490 $options[$config] = $params[$config];
1491 } else {
1492 $options[$config] = null;
1493 }
1e08b5cf 1494 }
3023078f 1495 }
3a01a46a 1496
3023078f 1497 if (!empty($id)) {
1498 unset($options['name']);
dbc01944 1499 $instance = repository::get_instance($id);
3023078f 1500 $instance->set_option($options);
1501 return $id;
1502 } else {
1503 return null;
b1339e98 1504 }
b1339e98 1505 } else {
1506 return null;
1507 }
1508 }
8dcd5deb 1509
82669dc4 1510 /**
4a65c39a 1511 * delete a repository instance
8dcd5deb 1512 * @global object $DB
2b8beee3 1513 * @return mixed
82669dc4 1514 */
7a3b93c1 1515 final public function delete() {
4a65c39a 1516 global $DB;
122defc5 1517 $DB->delete_records('repository_instances', array('id'=>$this->id));
2b0b3626 1518 $DB->delete_records('repository_instance_config', array('instanceid'=>$this->id));
4a65c39a 1519 return true;
1520 }
8dcd5deb 1521
4a65c39a 1522 /**
1523 * Hide/Show a repository
8dcd5deb 1524 * @global object $DB
1525 * @param string $hide
2b8beee3 1526 * @return boolean
4a65c39a 1527 */
7a3b93c1 1528 final public function hide($hide = 'toggle') {
4a65c39a 1529 global $DB;
1530 if ($entry = $DB->get_record('repository', array('id'=>$this->id))) {
1531 if ($hide === 'toggle' ) {
1532 if (!empty($entry->visible)) {
1533 $entry->visible = 0;
1534 } else {
1535 $entry->visible = 1;
1536 }
1537 } else {
1538 if (!empty($hide)) {
1539 $entry->visible = 0;
1540 } else {
1541 $entry->visible = 1;
1542 }
1543 }
1544 return $DB->update_record('repository', $entry);
1545 }
1546 return false;
1547 }
1cf56396 1548
1cf56396 1549 /**
4a65c39a 1550 * Save settings for repository instance
8dcd5deb 1551 * $repo->set_option(array('api_key'=>'f2188bde132', 'name'=>'dongsheng'));
1552 * @global object $DB
1553 * @param array $options settings
4a65c39a 1554 * @return int Id of the record
1cf56396 1555 */
7a3b93c1 1556 public function set_option($options = array()) {
4a65c39a 1557 global $DB;
7a3b93c1 1558
122defc5 1559 if (!empty($options['name'])) {
a27ab6fd 1560 $r = new stdClass();
122defc5 1561 $r->id = $this->id;
1562 $r->name = $options['name'];
1563 $DB->update_record('repository_instances', $r);
1564 unset($options['name']);
1565 }
27051e43 1566 foreach ($options as $name=>$value) {
1567 if ($id = $DB->get_field('repository_instance_config', 'id', array('name'=>$name, 'instanceid'=>$this->id))) {
f685e830 1568 $DB->set_field('repository_instance_config', 'value', $value, array('id'=>$id));
27051e43 1569 } else {
a27ab6fd 1570 $config = new stdClass();
27051e43 1571 $config->instanceid = $this->id;
1572 $config->name = $name;
1573 $config->value = $value;
f685e830 1574 $DB->insert_record('repository_instance_config', $config);
27051e43 1575 }
4a65c39a 1576 }
f685e830 1577 return true;
1cf56396 1578 }
1cf56396 1579
4a65c39a 1580 /**
1581 * Get settings for repository instance
8dcd5deb 1582 * @global object $DB
2b8beee3 1583 * @param string $config
4a65c39a 1584 * @return array Settings
1585 */
7a3b93c1 1586 public function get_option($config = '') {
4a65c39a 1587 global $DB;
27051e43 1588 $entries = $DB->get_records('repository_instance_config', array('instanceid'=>$this->id));
1589 $ret = array();
1590 if (empty($entries)) {
1591 return $ret;
4a65c39a 1592 }
7a3b93c1 1593 foreach($entries as $entry) {
27051e43 1594 $ret[$entry->name] = $entry->value;
4a65c39a 1595 }
1596 if (!empty($config)) {
9e6aa5ec 1597 if (isset($ret[$config])) {
75003899 1598 return $ret[$config];
9e6aa5ec
DC
1599 } else {
1600 return null;
1601 }
4a65c39a 1602 } else {
1603 return $ret;
1604 }
1605 }
bf1fccf0 1606
c167aa26 1607 public function filter(&$value) {
1608 $pass = false;
18bd7573 1609 $accepted_types = optional_param_array('accepted_types', '', PARAM_RAW);
99eaca9d 1610 $ft = new filetype_parser;
af79a6f5 1611 //$ext = $ft->get_extensions($this->supported_filetypes());
b81ebefd 1612 if (isset($value['children'])) {
c167aa26 1613 $pass = true;
b81ebefd 1614 if (!empty($value['children'])) {
b81ebefd 1615 $value['children'] = array_filter($value['children'], array($this, 'filter'));
537d44e8 1616 }
c167aa26 1617 } else {
46ee50dc 1618 if ($accepted_types == '*' or empty($accepted_types)
1619 or (is_array($accepted_types) and in_array('*', $accepted_types))) {
c167aa26 1620 $pass = true;
1621 } elseif (is_array($accepted_types)) {
1622 foreach ($accepted_types as $type) {
af79a6f5
DC
1623 $extensions = $ft->get_extensions($type);
1624 if (!is_array($extensions)) {
c167aa26 1625 $pass = true;
af79a6f5
DC
1626 } else {
1627 foreach ($extensions as $ext) {
7633f4b5 1628 if (preg_match('#'.$ext.'$#i', $value['title'])) {
af79a6f5
DC
1629 $pass = true;
1630 }
1631 }
c167aa26 1632 }
1633 }
1634 }
1635 }
1636 return $pass;
1637 }
1638
4a65c39a 1639 /**
1640 * Given a path, and perhaps a search, get a list of files.
1641 *
728ebac7 1642 * See details on http://docs.moodle.org/dev/Repository_plugins
f7639c37 1643 *
8e0946bf 1644 * @param string $path, this parameter can
4a65c39a 1645 * a folder name, or a identification of folder
8e0946bf 1646 * @param string $page, the page number of file list
1a6195b4
DC
1647 * @return array the list of files, including meta infomation, containing the following keys
1648 * manage, url to manage url
1649 * client_id
1650 * login, login form
1651 * repo_id, active repository id
1652 * login_btn_action, the login button action
1653 * login_btn_label, the login button label
1654 * total, number of results
1655 * perpage, items per page
1656 * page
1657 * pages, total pages
29199e56 1658 * issearchresult, is it a search result?
1a6195b4
DC
1659 * list, file list
1660 * path, current path and parent path
4a65c39a 1661 */
9d6aa286 1662 public function get_listing($path = '', $page = '') {
1663 }
1cf56396 1664
fbd508b4 1665 /**
353d5cf3 1666 * Search files in repository
1667 * When doing global search, $search_text will be used as
dbc01944 1668 * keyword.
353d5cf3 1669 *
fbd508b4 1670 * @return mixed, see get_listing()
1671 */
353d5cf3 1672 public function search($search_text) {
1673 $list = array();
1674 $list['list'] = array();
1675 return false;
fbd508b4 1676 }
1677
d68c527f 1678 /**
1679 * Logout from repository instance
1680 * By default, this function will return a login form
1681 *
1682 * @return string
1683 */
1684 public function logout(){
1685 return $this->print_login();
1686 }
1687
1688 /**
1689 * To check whether the user is logged in.
1690 *
1691 * @return boolean
1692 */
1693 public function check_login(){
1694 return true;
1695 }
1696
1cf56396 1697
4a65c39a 1698 /**
1699 * Show the login screen, if required
4a65c39a 1700 */
1d66f2b2 1701 public function print_login(){
1702 return $this->get_listing();
1703 }
1cf56396 1704
4a65c39a 1705 /**
1706 * Show the search screen, if required
4a65c39a 1707 * @return null
1708 */
a560785f 1709 public function print_search() {
b763c2d9 1710 $str = '';
1711 $str .= '<input type="hidden" name="repo_id" value="'.$this->id.'" />';
1712 $str .= '<input type="hidden" name="ctx_id" value="'.$this->context->id.'" />';
1713 $str .= '<input type="hidden" name="seekey" value="'.sesskey().'" />';
1714 $str .= '<label>'.get_string('keyword', 'repository').': </label><br/><input name="s" value="" /><br/>';
1715 return $str;
2b9feb5f 1716 }
4a65c39a 1717
3e123368
DC
1718 /**
1719 * For oauth like external authentication, when external repository direct user back to moodle,
1720 * this funciton will be called to set up token and token_secret
1721 */
1722 public function callback() {
1723 }
1724
455860ce 1725 /**
1726 * is it possible to do glboal search?
1727 * @return boolean
1728 */
7a3b93c1 1729 public function global_search() {
455860ce 1730 return false;
1731 }
1732
8dcd5deb 1733 /**
a6600395 1734 * Defines operations that happen occasionally on cron
2b8beee3 1735 * @return boolean
8dcd5deb 1736 */
a6600395 1737 public function cron() {
1738 return true;
1739 }
1740
7892948d 1741 /**
83a018ed 1742 * function which is run when the type is created (moodle administrator add the plugin)
3e0794ed 1743 * @return boolean success or fail?
7892948d 1744 */
f1cfe56e 1745 public static function plugin_init() {
3e0794ed 1746 return true;
7892948d 1747 }
1748
a6600395 1749 /**
06e65e1e 1750 * Edit/Create Admin Settings Moodle form
8e5af6cf
DC
1751 * @param object $mform Moodle form (passed by reference)
1752 * @param string $classname repository class name
a6600395 1753 */
8e5af6cf
DC
1754 public function type_config_form($mform, $classname = 'repository') {
1755 $instnaceoptions = call_user_func(array($classname, 'get_instance_option_names'), $mform, $classname);
a5adfa26
DC
1756 if (empty($instnaceoptions)) {
1757 // this plugin has only one instance
1758 // so we need to give it a name
1759 // it can be empty, then moodle will look for instance name from language string
1760 $mform->addElement('text', 'pluginname', get_string('pluginname', 'repository'), array('size' => '40'));
1761 $mform->addElement('static', 'pluginnamehelp', '', get_string('pluginnamehelp', 'repository'));
1762 }
4a65c39a 1763 }
dbc01944 1764
84ee73ee
RK
1765 /**
1766 * Validate Admin Settings Moodle form
1767 * @param object $mform Moodle form (passed by reference)
1768 * @param array array of ("fieldname"=>value) of submitted data
1769 * @param array array of ("fieldname"=>errormessage) of errors
1770 * @return array array of errors
1771 */
1772 public static function type_form_validation($mform, $data, $errors) {
1773 return $errors;
1774 }
1775
1776
6f2cd52a 1777 /**
06e65e1e 1778 * Edit/Create Instance Settings Moodle form
a5adfa26 1779 * @param object $mform Moodle form (passed by reference)
a6600395 1780 */
8c4a4687 1781 public function instance_config_form($mform) {
a6600395 1782 }
4a65c39a 1783
a6600395 1784 /**
1785 * Return names of the general options
1786 * By default: no general option name
1787 * @return array
1788 */
1b79955a 1789 public static function get_type_option_names() {
a5adfa26 1790 return array('pluginname');
a6600395 1791 }
1792
1793 /**
1794 * Return names of the instance options
1795 * By default: no instance option name
1796 * @return array
1797 */
7a3b93c1 1798 public static function get_instance_option_names() {
a6600395 1799 return array();
8b65d45c 1800 }
e35194be 1801
6b172cdc
DC
1802 public static function instance_form_validation($mform, $data, $errors) {
1803 return $errors;
1804 }
1805
f00340e2 1806 public function get_short_filename($str, $maxlength) {
138c7678
PS
1807 if (textlib::strlen($str) >= $maxlength) {
1808 return trim(textlib::substr($str, 0, $maxlength)).'...';
f00340e2
DC
1809 } else {
1810 return $str;
1811 }
1812 }
f392caba
DC
1813
1814 /**
1815 * Overwrite an existing file
1816 *
1817 * @param int $itemid
1818 * @param string $filepath
1819 * @param string $filename
1820 * @param string $newfilepath
1821 * @param string $newfilename
1822 * @return boolean
1823 */
1824 function overwrite_existing_draftfile($itemid, $filepath, $filename, $newfilepath, $newfilename) {
1825 global $USER;
1826 $fs = get_file_storage();
1827 $user_context = get_context_instance(CONTEXT_USER, $USER->id);
1828 if ($file = $fs->get_file($user_context->id, 'user', 'draft', $itemid, $filepath, $filename)) {
1829 if ($tempfile = $fs->get_file($user_context->id, 'user', 'draft', $itemid, $newfilepath, $newfilename)) {
1830 // delete existing file to release filename
1831 $file->delete();
1832 // create new file
1833 $newfile = $fs->create_file_from_storedfile(array('filepath'=>$filepath, 'filename'=>$filename), $tempfile);
1834 // remove temp file
1835 $tempfile->delete();
1836 return true;
1837 }
1838 }
1839 return false;
1840 }
1841
1842 /**
1843 * Delete a temp file from draft area
1844 *
1845 * @param int $draftitemid
1846 * @param string $filepath
1847 * @param string $filename
1848 * @return boolean
1849 */
1850 function delete_tempfile_from_draft($draftitemid, $filepath, $filename) {
1851 global $USER;
1852 $fs = get_file_storage();
1853 $user_context = get_context_instance(CONTEXT_USER, $USER->id);
1854 if ($file = $fs->get_file($user_context->id, 'user', 'draft', $draftitemid, $filepath, $filename)) {
1855 $file->delete();
1856 return true;
1857 } else {
1858 return false;
1859 }
1860 }
8b65d45c 1861}
837ebb78 1862
1863/**
6f2cd52a
DC
1864 * Exception class for repository api
1865 *
1866 * @since 2.0
1867 * @package moodlecore
1868 * @subpackage repository
1869 * @copyright 2009 Dongsheng Cai <dongsheng@moodle.com>
1870 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
837ebb78 1871 */
4a65c39a 1872class repository_exception extends moodle_exception {
8b65d45c 1873}
4ed43890 1874
8dcd5deb 1875/**
6f2cd52a
DC
1876 * This is a class used to define a repository instance form
1877 *
1878 * @since 2.0
1879 * @package moodlecore
1880 * @subpackage repository
1881 * @copyright 2009 Dongsheng Cai <dongsheng@moodle.com>
1882 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
8dcd5deb 1883 */
a6600395 1884final class repository_instance_form extends moodleform {
4a65c39a 1885 protected $instance;
1886 protected $plugin;
49d20def 1887 protected function add_defaults() {
4a65c39a 1888 $mform =& $this->_form;
1889 $strrequired = get_string('required');
1890
1891 $mform->addElement('hidden', 'edit', ($this->instance) ? $this->instance->id : 0);
d18e0fe6 1892 $mform->setType('edit', PARAM_INT);
4a65c39a 1893 $mform->addElement('hidden', 'new', $this->plugin);
d18e0fe6 1894 $mform->setType('new', PARAM_FORMAT);
4a65c39a 1895 $mform->addElement('hidden', 'plugin', $this->plugin);
aff24313 1896 $mform->setType('plugin', PARAM_PLUGIN);
27051e43 1897 $mform->addElement('hidden', 'typeid', $this->typeid);
d18e0fe6 1898 $mform->setType('typeid', PARAM_INT);
faaa613d 1899 $mform->addElement('hidden', 'contextid', $this->contextid);
d18e0fe6 1900 $mform->setType('contextid', PARAM_INT);
4a65c39a 1901
1902 $mform->addElement('text', 'name', get_string('name'), 'maxlength="100" size="30"');
1903 $mform->addRule('name', $strrequired, 'required', null, 'client');
49d20def 1904 }
4a65c39a 1905
49d20def
DC
1906 public function definition() {
1907 global $CFG;
1908 // type of plugin, string
1909 $this->plugin = $this->_customdata['plugin'];
1910 $this->typeid = $this->_customdata['typeid'];
1911 $this->contextid = $this->_customdata['contextid'];
1912 $this->instance = (isset($this->_customdata['instance'])
1913 && is_subclass_of($this->_customdata['instance'], 'repository'))
1914 ? $this->_customdata['instance'] : null;
1915
1916 $mform =& $this->_form;
1e97f196 1917
49d20def 1918 $this->add_defaults();
f48fb4d6 1919 //add fields
1920 if (!$this->instance) {
dbc01944 1921 $result = repository::static_function($this->plugin, 'instance_config_form', $mform);
49d20def
DC
1922 if ($result === false) {
1923 $mform->removeElement('name');
1924 }
1925 } else {
f48fb4d6 1926 $data = array();
1927 $data['name'] = $this->instance->name;
1928 if (!$this->instance->readonly) {
1929 $result = $this->instance->instance_config_form($mform);
49d20def
DC
1930 if ($result === false) {
1931 $mform->removeElement('name');
1932 }
f48fb4d6 1933 // and set the data if we have some.
1e97f196 1934 foreach ($this->instance->get_instance_option_names() as $config) {
a3d8df25 1935 if (!empty($this->instance->options[$config])) {
1936 $data[$config] = $this->instance->options[$config];
1e97f196 1937 } else {
1938 $data[$config] = '';
1939 }
27051e43 1940 }
4a65c39a 1941 }
f48fb4d6 1942 $this->set_data($data);
1e97f196 1943 }
1944
49d20def
DC
1945 if ($result === false) {
1946 $mform->addElement('cancel');
1947 } else {
1948 $this->add_action_buttons(true, get_string('save','repository'));
1949 }
4a65c39a 1950 }
1951
1952 public function validation($data) {
1953 global $DB;
4a65c39a 1954 $errors = array();
6b172cdc
DC
1955 $plugin = $this->_customdata['plugin'];
1956 $instance = (isset($this->_customdata['instance'])
1957 && is_subclass_of($this->_customdata['instance'], 'repository'))
1958 ? $this->_customdata['instance'] : null;
1959 if (!$instance) {
1960 $errors = repository::static_function($plugin, 'instance_form_validation', $this, $data, $errors);
1961 } else {
1962 $errors = $instance->instance_form_validation($this, $data, $errors);
1963 }
1964
a090554a
PS
1965 $sql = "SELECT count('x')
1966 FROM {repository_instances} i, {repository} r
1967 WHERE r.type=:plugin AND r.id=i.typeid AND i.name=:name";
09bff8e8 1968 if ($DB->count_records_sql($sql, array('name' => $data['name'], 'plugin' => $data['plugin'])) > 1) {
6b172cdc 1969 $errors['name'] = get_string('erroruniquename', 'repository');
4a65c39a 1970 }
1971
4a65c39a 1972 return $errors;
1973 }
1974}
a6600395 1975
a6600395 1976/**
6f2cd52a
DC
1977 * This is a class used to define a repository type setting form
1978 *
1979 * @since 2.0
1980 * @package moodlecore
1981 * @subpackage repository
1982 * @copyright 2009 Dongsheng Cai <dongsheng@moodle.com>
1983 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
a6600395 1984 */
c295f9ff 1985final class repository_type_form extends moodleform {
a6600395 1986 protected $instance;
1987 protected $plugin;
79698344 1988 protected $action;
a6600395 1989
1990 /**
1991 * Definition of the moodleform
1992 * @global object $CFG
1993 */
1994 public function definition() {
1995 global $CFG;
1996 // type of plugin, string
1997 $this->plugin = $this->_customdata['plugin'];
1998 $this->instance = (isset($this->_customdata['instance'])
1999 && is_a($this->_customdata['instance'], 'repository_type'))
2000 ? $this->_customdata['instance'] : null;
2001
79698344 2002 $this->action = $this->_customdata['action'];
a5adfa26 2003 $this->pluginname = $this->_customdata['pluginname'];
a6600395 2004 $mform =& $this->_form;
2005 $strrequired = get_string('required');
4d5948f1 2006
79698344
MD
2007 $mform->addElement('hidden', 'action', $this->action);
2008 $mform->setType('action', PARAM_TEXT);
2009 $mform->addElement('hidden', 'repos', $this->plugin);
aff24313 2010 $mform->setType('repos', PARAM_PLUGIN);
8f943eba 2011
06e65e1e 2012 // let the plugin add its specific fields
a5adfa26
DC
2013 $classname = 'repository_' . $this->plugin;
2014 require_once($CFG->dirroot . '/repository/' . $this->plugin . '/lib.php');
f48fb4d6 2015 //add "enable course/user instances" checkboxes if multiple instances are allowed
dbc01944 2016 $instanceoptionnames = repository::static_function($this->plugin, 'get_instance_option_names');
8e5af6cf
DC
2017
2018 $result = call_user_func(array($classname, 'type_config_form'), $mform, $classname);
2019
a5adfa26 2020 if (!empty($instanceoptionnames)) {
8e5af6cf
DC
2021 $sm = get_string_manager();
2022 $component = 'repository';
2023 if ($sm->string_exists('enablecourseinstances', 'repository_' . $this->plugin)) {
2024 $component .= ('_' . $this->plugin);
2025 }
2026 $mform->addElement('checkbox', 'enablecourseinstances', get_string('enablecourseinstances', $component));
2027
2028 $component = 'repository';
2029 if ($sm->string_exists('enableuserinstances', 'repository_' . $this->plugin)) {
2030 $component .= ('_' . $this->plugin);
2031 }
2032 $mform->addElement('checkbox', 'enableuserinstances', get_string('enableuserinstances', $component));
f48fb4d6 2033 }
2034
2035 // set the data if we have some.
a6600395 2036 if ($this->instance) {
2037 $data = array();
1b79955a 2038 $option_names = call_user_func(array($classname,'get_type_option_names'));
f48fb4d6 2039 if (!empty($instanceoptionnames)){
2040 $option_names[] = 'enablecourseinstances';
2041 $option_names[] = 'enableuserinstances';
2042 }
2043
a6600395 2044 $instanceoptions = $this->instance->get_options();
2045 foreach ($option_names as $config) {
2046 if (!empty($instanceoptions[$config])) {
2047 $data[$config] = $instanceoptions[$config];
2048 } else {
2049 $data[$config] = '';
2050 }
2051 }
a5adfa26
DC
2052 // XXX: set plugin name for plugins which doesn't have muliti instances
2053 if (empty($instanceoptionnames)){
2054 $data['pluginname'] = $this->pluginname;
2055 }
a6600395 2056 $this->set_data($data);
2057 }
dbc01944 2058
46dd6bb0 2059 $this->add_action_buttons(true, get_string('save','repository'));
a6600395 2060 }
84ee73ee
RK
2061
2062 public function validation($data) {
2063 $errors = array();
2064 $plugin = $this->_customdata['plugin'];
2065 $instance = (isset($this->_customdata['instance'])
2066 && is_subclass_of($this->_customdata['instance'], 'repository'))
2067 ? $this->_customdata['instance'] : null;
2068 if (!$instance) {
2069 $errors = repository::static_function($plugin, 'type_form_validation', $this, $data, $errors);
2070 } else {
2071 $errors = $instance->type_form_validation($this, $data, $errors);
2072 }
2073
2074 return $errors;
2075 }
a6600395 2076}
2077
8e0946bf
DC
2078/**
2079 * Generate all options needed by filepicker
2080 *
2081 * @param array $args, including following keys
2082 * context
2083 * accepted_types
2084 * return_types
2085 *
2086 * @return array the list of repository instances, including meta infomation, containing the following keys
2087 * externallink
2088 * repositories
2089 * accepted_types
2090 */
99eaca9d 2091function initialise_filepicker($args) {
a28c9253 2092 global $CFG, $USER, $PAGE, $OUTPUT;
1dce6261 2093 require_once($CFG->libdir . '/licenselib.php');
4f0c2d00 2094
6bdfef5d 2095 $return = new stdClass();
d1d4813f 2096 $licenses = array();
4f0c2d00
PS
2097 if (!empty($CFG->licenses)) {
2098 $array = explode(',', $CFG->licenses);
2099 foreach ($array as $license) {
6bdfef5d 2100 $l = new stdClass();
4f0c2d00
PS
2101 $l->shortname = $license;
2102 $l->fullname = get_string($license, 'license');
2103 $licenses[] = $l;
2104 }
d1d4813f 2105 }
308d948b
DC
2106 if (!empty($CFG->sitedefaultlicense)) {
2107 $return->defaultlicense = $CFG->sitedefaultlicense;
2108 }
1dce6261 2109
1dce6261
DC
2110 $return->licenses = $licenses;
2111
2112 $return->author = fullname($USER);
2113
99eaca9d
DC
2114 $ft = new filetype_parser();
2115 if (empty($args->context)) {
2116 $context = $PAGE->context;
e189ec00 2117 } else {
99eaca9d
DC
2118 $context = $args->context;
2119 }
6bf197b3
DC
2120 $disable_types = array();
2121 if (!empty($args->disable_types)) {
2122 $disable_types = $args->disable_types;
2123 }
99eaca9d 2124
e189ec00 2125 $user_context = get_context_instance(CONTEXT_USER, $USER->id);
99eaca9d 2126
bf413f6f
DC
2127 list($context, $course, $cm) = get_context_info_array($context->id);
2128 $contexts = array($user_context, get_system_context());
2129 if (!empty($course)) {
2130 // adding course context
2131 $contexts[] = get_context_instance(CONTEXT_COURSE, $course->id);
2132 }
99eaca9d
DC
2133 $externallink = (int)get_config(null, 'repositoryallowexternallinks');
2134 $repositories = repository::get_instances(array(
bf413f6f 2135 'context'=>$contexts,
99eaca9d 2136 'currentcontext'=> $context,
ea1780ad 2137 'accepted_types'=>$args->accepted_types,
6bf197b3
DC
2138 'return_types'=>$args->return_types,
2139 'disable_types'=>$disable_types
99eaca9d
DC
2140 ));
2141
2142 $return->repositories = array();
2143
2144 if (empty($externallink)) {
2145 $return->externallink = false;
2146 } else {
2147 $return->externallink = true;
2148 }
2149
99eaca9d
DC
2150 // provided by form element
2151 $return->accepted_types = $ft->get_extensions($args->accepted_types);
766514a0 2152 $return->return_types = $args->return_types;
99eaca9d
DC
2153 foreach ($repositories as $repository) {
2154 $meta = $repository->get_meta();
6b37c2b0
SH
2155 // Please note that the array keys for repositories are used within
2156 // JavaScript a lot, the key NEEDS to be the repository id.
b0985814 2157 $return->repositories[$repository->id] = $meta;
99eaca9d
DC
2158 }
2159 return $return;
e189ec00 2160}
f392caba
DC
2161/**
2162 * Small function to walk an array to attach repository ID
2163 * @param array $value
2164 * @param string $key
2165 * @param int $id
2166 */
2167function repository_attach_id(&$value, $key, $id){
2168 $value['repo_id'] = $id;
2169}