"MDL-13766, check if plugin file existed before displayed in admin page"
[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
24 * @package moodlecore
25 * @subpackage repository
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);
36
a6600395 37/**
6f2cd52a
DC
38 * This class is used to manage repository plugins
39 *
a6600395 40 * A repository_type is a repository plug-in. It can be Box.net, Flick-r, ...
41 * A repository type can be edited, sorted and hidden. It is mandatory for an
42 * administrator to create a repository type in order to be able to create
43 * some instances of this type.
a6600395 44 * Coding note:
45 * - a repository_type object is mapped to the "repository" database table
46 * - "typename" attibut maps the "type" database field. It is unique.
47 * - general "options" for a repository type are saved in the config_plugin table
eb239694 48 * - when you delete a repository, all instances are deleted, and general
49 * options are also deleted from database
a6600395 50 * - When you create a type for a plugin that can't have multiple instances, a
51 * instance is automatically created.
6f2cd52a
DC
52 *
53 * @package moodlecore
54 * @subpackage repository
55 * @copyright 2009 Jerome Mouneyrac
56 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
a6600395 57 */
58class repository_type {
59
60
61 /**
62 * Type name (no whitespace) - A type name is unique
63 * Note: for a user-friendly type name see get_readablename()
64 * @var String
65 */
66 private $_typename;
67
68
69 /**
70 * Options of this type
71 * They are general options that any instance of this type would share
72 * e.g. API key
73 * These options are saved in config_plugin table
74 * @var array
75 */
7a3b93c1 76 private $_options;
a6600395 77
78
79 /**
80 * Is the repository type visible or hidden
81 * If false (hidden): no instances can be created, edited, deleted, showned , used...
82 * @var boolean
83 */
7a3b93c1 84 private $_visible;
a6600395 85
86
87 /**
88 * 0 => not ordered, 1 => first position, 2 => second position...
89 * A not order type would appear in first position (should never happened)
90 * @var integer
91 */
92 private $_sortorder;
93
f48fb4d6 94 /**
95 * Return if the instance is visible in a context
96 * TODO: check if the context visibility has been overwritten by the plugin creator
97 * (need to create special functions to be overvwritten in repository class)
5363905a 98 * @param objet $context - context
f48fb4d6 99 * @return boolean
100 */
5363905a
DC
101 public function get_contextvisibility($context) {
102 global $USER;
dbc01944 103
5363905a 104 if ($context->contextlevel == CONTEXT_COURSE) {
f48fb4d6 105 return $this->_options['enablecourseinstances'];
106 }
107
5363905a 108 if ($context->contextlevel == CONTEXT_USER) {
f48fb4d6 109 return $this->_options['enableuserinstances'];
110 }
111
112 //the context is SITE
113 return true;
114 }
dbc01944 115
f48fb4d6 116
117
a6600395 118 /**
119 * repository_type constructor
2b8beee3 120 * @global object $CFG
a6600395 121 * @param integer $typename
122 * @param array $typeoptions
123 * @param boolean $visible
124 * @param integer $sortorder (don't really need set, it will be during create() call)
125 */
a642bf6f 126 public function __construct($typename = '', $typeoptions = array(), $visible = true, $sortorder = 0) {
a6600395 127 global $CFG;
128
129 //set type attributs
130 $this->_typename = $typename;
131 $this->_visible = $visible;
132 $this->_sortorder = $sortorder;
46dd6bb0 133
a6600395 134 //set options attribut
135 $this->_options = array();
dbc01944 136 $options = repository::static_function($typename,'get_type_option_names');
a6600395 137 //check that the type can be setup
06e65e1e 138 if (!empty($options)) {
a6600395 139 //set the type options
140 foreach ($options as $config) {
7a3b93c1 141 if (array_key_exists($config,$typeoptions)) {
142 $this->_options[$config] = $typeoptions[$config];
a6600395 143 }
144 }
145 }
f48fb4d6 146
147 //retrieve visibility from option
148 if (array_key_exists('enablecourseinstances',$typeoptions)) {
149 $this->_options['enablecourseinstances'] = $typeoptions['enablecourseinstances'];
9f7c761a 150 } else {
151 $this->_options['enablecourseinstances'] = 0;
f48fb4d6 152 }
dbc01944 153
f48fb4d6 154 if (array_key_exists('enableuserinstances',$typeoptions)) {
155 $this->_options['enableuserinstances'] = $typeoptions['enableuserinstances'];
9f7c761a 156 } else {
157 $this->_options['enableuserinstances'] = 0;
f48fb4d6 158 }
dbc01944 159
a6600395 160 }
161
162 /**
163 * Get the type name (no whitespace)
164 * For a human readable name, use get_readablename()
165 * @return String the type name
166 */
7a3b93c1 167 public function get_typename() {
a6600395 168 return $this->_typename;
169 }
170
171 /**
172 * Return a human readable and user-friendly type name
173 * @return string user-friendly type name
174 */
7a3b93c1 175 public function get_readablename() {
a6600395 176 return get_string('repositoryname','repository_'.$this->_typename);
177 }
178
179 /**
180 * Return general options
181 * @return array the general options
182 */
7a3b93c1 183 public function get_options() {
a6600395 184 return $this->_options;
185 }
186
187 /**
188 * Return visibility
189 * @return boolean
190 */
7a3b93c1 191 public function get_visible() {
a6600395 192 return $this->_visible;
193 }
194
195 /**
196 * Return order / position of display in the file picker
197 * @return integer
198 */
7a3b93c1 199 public function get_sortorder() {
a6600395 200 return $this->_sortorder;
201 }
202
203 /**
204 * Create a repository type (the type name must not already exist)
a75c78d3 205 * @param boolean throw exception?
206 * @return mixed return int if create successfully, return false if
207 * any errors
a6600395 208 * @global object $DB
209 */
a75c78d3 210 public function create($silent = false) {
a6600395 211 global $DB;
212
213 //check that $type has been set
214 $timmedtype = trim($this->_typename);
215 if (empty($timmedtype)) {
7a3b93c1 216 throw new repository_exception('emptytype', 'repository');
a6600395 217 }
218
219 //set sortorder as the last position in the list
7a3b93c1 220 if (!isset($this->_sortorder) || $this->_sortorder == 0 ) {
a6600395 221 $sql = "SELECT MAX(sortorder) FROM {repository}";
222 $this->_sortorder = 1 + $DB->get_field_sql($sql);
223 }
224
225 //only create a new type if it doesn't already exist
226 $existingtype = $DB->get_record('repository', array('type'=>$this->_typename));
7a3b93c1 227 if (!$existingtype) {
228 //create the type
229 $newtype = new stdclass;
230 $newtype->type = $this->_typename;
231 $newtype->visible = $this->_visible;
232 $newtype->sortorder = $this->_sortorder;
a75c78d3 233 $plugin_id = $DB->insert_record('repository', $newtype);
7a3b93c1 234 //save the options in DB
235 $this->update_options();
236
edb50637 237 //if the plugin type has no multiple instance (e.g. has no instance option name) so it wont
7a3b93c1 238 //be possible for the administrator to create a instance
239 //in this case we need to create an instance
dbc01944 240 $instanceoptionnames = repository::static_function($this->_typename, 'get_instance_option_names');
edb50637 241 if (empty($instanceoptionnames)) {
7a3b93c1 242 $instanceoptions = array();
243 $instanceoptions['name'] = $this->_typename;
dbc01944 244 repository::static_function($this->_typename, 'create', $this->_typename, 0, get_system_context(), $instanceoptions);
7a3b93c1 245 }
60c366e8 246 //run plugin_init function
247 if (!repository::static_function($this->_typename, 'plugin_init')) {
248 if (!$silent) {
249 throw new repository_exception('cannotinitplugin', 'repository');
250 }
251 }
252
a75c78d3 253 if(!empty($plugin_id)) {
254 // return plugin_id if create successfully
255 return $plugin_id;
256 } else {
257 return false;
258 }
948c2860 259
7a3b93c1 260 } else {
a75c78d3 261 if (!$silent) {
262 throw new repository_exception('existingrepository', 'repository');
263 }
264 // If plugin existed, return false, tell caller no new plugins were created.
265 return false;
a6600395 266 }
267 }
268
269
270 /**
271 * Update plugin options into the config_plugin table
272 * @param array $options
273 * @return boolean
274 */
7a3b93c1 275 public function update_options($options = null) {
276 if (!empty($options)) {
a6600395 277 $this->_options = $options;
278 }
279
280 foreach ($this->_options as $name => $value) {
281 set_config($name,$value,$this->_typename);
282 }
283
284 return true;
285 }
286
287 /**
288 * Update visible database field with the value given as parameter
289 * or with the visible value of this object
290 * This function is private.
291 * For public access, have a look to switch_and_update_visibility()
292 * @global object $DB
293 * @param boolean $visible
294 * @return boolean
295 */
7a3b93c1 296 private function update_visible($visible = null) {
a6600395 297 global $DB;
298
7a3b93c1 299 if (!empty($visible)) {
a6600395 300 $this->_visible = $visible;
301 }
7a3b93c1 302 else if (!isset($this->_visible)) {
a6600395 303 throw new repository_exception('updateemptyvisible', 'repository');
304 }
305
306 return $DB->set_field('repository', 'visible', $this->_visible, array('type'=>$this->_typename));
307 }
308
309 /**
310 * Update database sortorder field with the value given as parameter
311 * or with the sortorder value of this object
312 * This function is private.
313 * For public access, have a look to move_order()
314 * @global object $DB
315 * @param integer $sortorder
316 * @return boolean
317 */
7a3b93c1 318 private function update_sortorder($sortorder = null) {
a6600395 319 global $DB;
320
7a3b93c1 321 if (!empty($sortorder) && $sortorder!=0) {
a6600395 322 $this->_sortorder = $sortorder;
323 }
324 //if sortorder is not set, we set it as the ;ast position in the list
7a3b93c1 325 else if (!isset($this->_sortorder) || $this->_sortorder == 0 ) {
a6600395 326 $sql = "SELECT MAX(sortorder) FROM {repository}";
327 $this->_sortorder = 1 + $DB->get_field_sql($sql);
328 }
329
330 return $DB->set_field('repository', 'sortorder', $this->_sortorder, array('type'=>$this->_typename));
331 }
332
333 /**
334 * Change order of the type with its adjacent upper or downer type
335 * (database fields are updated)
336 * Algorithm details:
337 * 1. retrieve all types in an array. This array is sorted by sortorder,
338 * and the array keys start from 0 to X (incremented by 1)
339 * 2. switch sortorder values of this type and its adjacent type
340 * @global object $DB
341 * @param string $move "up" or "down"
342 */
343 public function move_order($move) {
344 global $DB;
a6600395 345
dbc01944 346 $types = repository::get_types(); // retrieve all types
7a3b93c1 347
348 /// retrieve this type into the returned array
349 $i = 0;
350 while (!isset($indice) && $i<count($types)) {
351 if ($types[$i]->get_typename() == $this->_typename) {
a6600395 352 $indice = $i;
353 }
354 $i++;
355 }
356
7a3b93c1 357 /// retrieve adjacent indice
a6600395 358 switch ($move) {
359 case "up":
360 $adjacentindice = $indice - 1;
7a3b93c1 361 break;
a6600395 362 case "down":
363 $adjacentindice = $indice + 1;
7a3b93c1 364 break;
a6600395 365 default:
7a3b93c1 366 throw new repository_exception('movenotdefined', 'repository');
a6600395 367 }
368
369 //switch sortorder of this type and the adjacent type
370 //TODO: we could reset sortorder for all types. This is not as good in performance term, but
371 //that prevent from wrong behaviour on a screwed database. As performance are not important in this particular case
372 //it worth to change the algo.
7a3b93c1 373 if ($adjacentindice>=0 && !empty($types[$adjacentindice])) {
a6600395 374 $DB->set_field('repository', 'sortorder', $this->_sortorder, array('type'=>$types[$adjacentindice]->get_typename()));
375 $this->update_sortorder($types[$adjacentindice]->get_sortorder());
376 }
377 }
378
379 /**
380 * 1. Switch the visibility OFF if it's ON, and ON if it's OFF.
381 * 2. Update the type
2b8beee3 382 * @return boolean
a6600395 383 */
7a3b93c1 384 public function switch_and_update_visibility() {
a6600395 385 $this->_visible = !$this->_visible;
386 return $this->update_visible();
387 }
388
389
390 /**
eb239694 391 * Delete a repository_type (general options are removed from config_plugin
392 * table, and all instances are deleted)
a6600395 393 * @global object $DB
394 * @return boolean
395 */
7a3b93c1 396 public function delete() {
a6600395 397 global $DB;
46dd6bb0 398
399 //delete all instances of this type
6f2cd52a
DC
400 $params = array();
401 $params['context'] = array();
402 $params['onlyvisible'] = false;
403 $params['type'] = $this->_typename;
404 $instances = repository::get_instances($params);
7a3b93c1 405 foreach ($instances as $instance) {
46dd6bb0 406 $instance->delete();
407 }
408
eb239694 409 //delete all general options
7a3b93c1 410 foreach ($this->_options as $name => $value) {
eb239694 411 set_config($name, null, $this->_typename);
412 }
413
a6600395 414 return $DB->delete_records('repository', array('type' => $this->_typename));
415 }
416}
417
a6600395 418/**
8d419e59 419 * This is the base class of the repository class
420 *
421 * To use repository plugin, see:
422 * http://docs.moodle.org/en/Development:Repository_How_to_Create_Plugin
8d419e59 423 * class repository is an abstract class, some functions must be implemented in subclass.
8d419e59 424 * See an example: repository/boxnet/repository.class.php
425 *
426 * A few notes:
427 * // for ajax file picker, this will print a json string to tell file picker
428 * // how to build a login form
429 * $repo->print_login();
430 * // for ajax file picker, this will return a files list.
431 * $repo->get_listing();
432 * // this function will be used for non-javascript version.
433 * $repo->print_listing();
434 * // print a search box
435 * $repo->print_search();
436 *
6f2cd52a
DC
437 * @package moodlecore
438 * @subpackage repository
439 * @copyright 2009 Dongsheng Cai <dongsheng@moodle.com>
440 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
a6600395 441 */
fca079c5 442abstract class repository {
efe018b4 443 // $disabled can be set to true to disable a plugin by force
444 // example: self::$disabled = true
445 public $disabled = false;
4a65c39a 446 public $id;
447 public $context;
448 public $options;
948c2860 449 public $readonly;
41076c58 450 public $returntypes;
a0ff4137
DC
451 /**
452 * 1. Initialize context and options
453 * 2. Accept necessary parameters
454 *
455 * @param integer $repositoryid
456 * @param integer $contextid
457 * @param array $options
458 */
8e0946bf 459 public function __construct($repositoryid, $contextid = SYSCONTEXTID, $options = array(), $readonly = 0) {
a0ff4137
DC
460 $this->id = $repositoryid;
461 $this->context = get_context_instance_by_id($contextid);
462 $this->readonly = $readonly;
463 $this->options = array();
464 if (is_array($options)) {
465 $options = array_merge($this->get_option(), $options);
466 } else {
467 $options = $this->get_option();
468 }
469 foreach ($options as $n => $v) {
470 $this->options[$n] = $v;
471 }
472 $this->name = $this->get_name();
473 $this->returntypes = $this->supported_returntypes();
474 $this->super_called = true;
475 }
1cf56396 476
dbc01944 477 /**
478 * Return a type for a given type name.
479 * @global object $DB
480 * @param string $typename the type name
8e0946bf 481 * @return object
dbc01944 482 */
483 public static function get_type_by_typename($typename) {
484 global $DB;
485
486 if (!$record = $DB->get_record('repository',array('type' => $typename))) {
487 return false;
488 }
489
490 return new repository_type($typename, (array)get_config($typename), $record->visible, $record->sortorder);
491 }
492
493 /**
494 * Return a type for a given type id.
495 * @global object $DB
8e0946bf
DC
496 * @param int $id the type id
497 * @return object
dbc01944 498 */
499 public static function get_type_by_id($id) {
500 global $DB;
501
502 if (!$record = $DB->get_record('repository',array('id' => $id))) {
503 return false;
504 }
505
506 return new repository_type($record->type, (array)get_config($record->type), $record->visible, $record->sortorder);
507 }
508
509 /**
510 * Return all repository types ordered by sortorder
511 * first type in returnedarray[0], second type in returnedarray[1], ...
512 * @global object $DB
513 * @param boolean $visible can return types by visiblity, return all types if null
514 * @return array Repository types
515 */
516 public static function get_types($visible=null) {
489d8a75 517 global $DB, $CFG;
dbc01944 518
519 $types = array();
520 $params = null;
521 if (!empty($visible)) {
522 $params = array('visible' => $visible);
523 }
524 if ($records = $DB->get_records('repository',$params,'sortorder')) {
525 foreach($records as $type) {
489d8a75
DC
526 if (file_exists($CFG->dirroot . '/repository/'. $type->type .'/repository.class.php')) {
527 $types[] = new repository_type($type->type, (array)get_config($type->type), $type->visible, $type->sortorder);
528 }
dbc01944 529 }
530 }
531
532 return $types;
533 }
534
535 /**
536 * Check context
537 * @param int $ctx_id
538 * @return boolean
539 */
540 public static function check_context($ctx_id) {
541 global $USER;
542
543 $context = get_context_instance_by_id($ctx_id);
544 $level = $context->contextlevel;
545
546 if ($level == CONTEXT_COURSE) {
4f0c2d00 547 if (!has_capability('moodle/course:participate', $context)) {
dbc01944 548 return false;
549 } else {
550 return true;
551 }
552 } else if ($level == CONTEXT_USER) {
553 $c = get_context_instance(CONTEXT_USER, $USER->id);
554 if ($c->id == $ctx_id) {
555 return true;
556 } else {
557 return false;
558 }
559 } else if ($level == CONTEXT_SYSTEM) {
560 // it is always ok in system level
561 return true;
562 }
563 return false;
564 }
565
566 /**
567 * Return all types that you a user can create/edit and which are also visible
568 * Note: Mostly used in order to know if at least one editable type can be set
569 * @param object $context the context for which we want the editable types
570 * @return array types
571 */
572 public static function get_editable_types($context = null) {
573
574 if (empty($context)) {
575 $context = get_system_context();
576 }
577
578 $types= repository::get_types(true);
579 $editabletypes = array();
580 foreach ($types as $type) {
581 $instanceoptionnames = repository::static_function($type->get_typename(), 'get_instance_option_names');
582 if (!empty($instanceoptionnames)) {
5363905a 583 if ($type->get_contextvisibility($context)) {
dbc01944 584 $editabletypes[]=$type;
585 }
586 }
587 }
588 return $editabletypes;
589 }
590
591 /**
592 * Return repository instances
593 * @global object $DB
594 * @global object $CFG
595 * @global object $USER
92a89068
PL
596 *
597 * @param array $args Array containing the following keys:
598 * currentcontext
599 * context
600 * onlyvisible
601 * type
602 * accepted_types
8e0946bf 603 * return_types
92a89068
PL
604 * userid
605 *
dbc01944 606 * @return array repository instances
607 */
6f2cd52a 608 public static function get_instances($args = array()) {
dbc01944 609 global $DB, $CFG, $USER;
610
6f2cd52a
DC
611 if (isset($args['currentcontext'])) {
612 $current_context = $args['currentcontext'];
613 } else {
614 $current_context = null;
615 }
616
617 if (!empty($args['context'])) {
618 $contexts = $args['context'];
619 } else {
620 $contexts = array();
621 }
622
623 $onlyvisible = isset($args['onlyvisible']) ? $args['onlyvisible'] : true;
624 $type = isset($args['type']) ? $args['type'] : null;
81bdfdb9 625 $returntypes = isset($args['return_types']) ? $args['return_types'] : 3;
6f2cd52a 626
dbc01944 627 $params = array();
628 $sql = 'SELECT i.*, r.type AS repositorytype, r.sortorder, r.visible FROM {repository} r, {repository_instances} i WHERE ';
629 $sql .= 'i.typeid = r.id ';
630
6f2cd52a 631 if (!empty($args['userid']) && is_numeric($args['userid'])) {
dbc01944 632 $sql .= ' AND (i.userid = 0 or i.userid = ?)';
6f2cd52a 633 $params[] = $args['userid'];
dbc01944 634 }
635
636 foreach ($contexts as $context) {
637 if (empty($firstcontext)) {
638 $firstcontext = true;
639 $sql .= ' AND ((i.contextid = ?)';
640 } else {
641 $sql .= ' OR (i.contextid = ?)';
642 }
643 $params[] = $context->id;
644 }
645
646 if (!empty($firstcontext)) {
647 $sql .=')';
648 }
649
650 if ($onlyvisible == true) {
651 $sql .= ' AND (r.visible = 1)';
652 }
653
654 if (isset($type)) {
655 $sql .= ' AND (r.type = ?)';
656 $params[] = $type;
657 }
658 $sql .= ' order by r.sortorder, i.name';
50a5cf09 659
6f2cd52a
DC
660 if (!$records = $DB->get_records_sql($sql, $params)) {
661 $records = array();
dbc01944 662 }
663
6f2cd52a 664 $repositories = array();
99eaca9d 665 $ft = new filetype_parser();
1e0b0415
DC
666 if (isset($args['accepted_types'])) {
667 $accepted_types = $args['accepted_types'];
668 } else {
669 $accepted_types = '*';
670 }
6f2cd52a 671 foreach ($records as $record) {
062d21cd
DC
672 if (!file_exists($CFG->dirroot . '/repository/'. $record->repositorytype.'/repository.class.php')) {
673 continue;
674 }
6f2cd52a
DC
675 require_once($CFG->dirroot . '/repository/'. $record->repositorytype.'/repository.class.php');
676 $options['visible'] = $record->visible;
677 $options['name'] = $record->name;
678 $options['type'] = $record->repositorytype;
679 $options['typeid'] = $record->typeid;
c167aa26 680 // tell instance what file types will be accepted by file picker
6f2cd52a
DC
681 $classname = 'repository_' . $record->repositorytype;
682
683 $repository = new $classname($record->id, $record->contextid, $options, $record->readonly);
684
014c1ca0 685 $is_supported = true;
dbc01944 686
271bd2e0 687 if (empty($repository->super_called)) {
6f2cd52a
DC
688 // to make sure the super construct is called
689 debugging('parent::__construct must be called by '.$record->repositorytype.' plugin.');
271bd2e0 690 } else {
6f2cd52a 691 // check mimetypes
99eaca9d
DC
692 if ($accepted_types !== '*' and $repository->supported_filetypes() !== '*') {
693 $accepted_types = $ft->get_extensions($accepted_types);
694 $supported_filetypes = $ft->get_extensions($repository->supported_filetypes());
6f2cd52a 695
271bd2e0 696 $is_supported = false;
697 foreach ($supported_filetypes as $type) {
99eaca9d 698 if (in_array($type, $accepted_types)) {
271bd2e0 699 $is_supported = true;
700 }
014c1ca0 701 }
6f2cd52a 702
014c1ca0 703 }
6f2cd52a 704 // check return values
41076c58
DC
705 if ($returntypes !== 3 and $repository->supported_returntypes() !== 3) {
706 $type = $repository->supported_returntypes();
707 if ($type & $returntypes) {
708 //
709 } else {
710 $is_supported = false;
271bd2e0 711 }
014c1ca0 712 }
271bd2e0 713 if (!$onlyvisible || ($repository->is_visible() && !$repository->disabled)) {
6f2cd52a
DC
714
715 // check capability in current context
716 if (!empty($current_context)) {
717 $capability = has_capability('repository/'.$record->repositorytype.':view', $current_context);
718 } else {
719 // TODO: what should we do if current context isn't set?
720 $capability = has_capability('repository/'.$record->repositorytype.':view', get_system_context());
721 }
c86dde2e 722 if ($is_supported && $capability) {
99eaca9d 723 $repositories[$repository->id] = $repository;
271bd2e0 724 }
014c1ca0 725 }
dbc01944 726 }
727 }
6f2cd52a 728 return $repositories;
dbc01944 729 }
730
731 /**
732 * Get single repository instance
733 * @global object $DB
734 * @global object $CFG
735 * @param integer $id repository id
736 * @return object repository instance
737 */
738 public static function get_instance($id) {
739 global $DB, $CFG;
740 $sql = 'SELECT i.*, r.type AS repositorytype, r.visible FROM {repository} r, {repository_instances} i WHERE ';
741 $sql .= 'i.typeid = r.id AND ';
742 $sql .= 'i.id = '.$id;
743
744 if(!$instance = $DB->get_record_sql($sql)) {
745 return false;
746 }
747 require_once($CFG->dirroot . '/repository/'. $instance->repositorytype
748 . '/repository.class.php');
749 $classname = 'repository_' . $instance->repositorytype;
750 $options['typeid'] = $instance->typeid;
751 $options['type'] = $instance->repositorytype;
752 $options['name'] = $instance->name;
271bd2e0 753 $obj = new $classname($instance->id, $instance->contextid, $options, $instance->readonly);
754 if (empty($obj->super_called)) {
755 debugging('parent::__construct must be called by '.$classname.' plugin.');
756 }
757 return $obj;
dbc01944 758 }
759
760 /**
92a89068 761 * call a static function. Any additional arguments than plugin and function will be passed through.
2b8beee3 762 * @global object $CFG
763 * @param string $plugin
764 * @param string $function
2b8beee3 765 * @return mixed
dbc01944 766 */
767 public static function static_function($plugin, $function) {
768 global $CFG;
769
770 //check that the plugin exists
771 $typedirectory = $CFG->dirroot . '/repository/'. $plugin . '/repository.class.php';
772 if (!file_exists($typedirectory)) {
f1cfe56e 773 //throw new repository_exception('invalidplugin', 'repository');
774 return false;
dbc01944 775 }
776
777 $pname = null;
778 if (is_object($plugin) || is_array($plugin)) {
779 $plugin = (object)$plugin;
780 $pname = $plugin->name;
781 } else {
782 $pname = $plugin;
783 }
784
785 $args = func_get_args();
786 if (count($args) <= 2) {
787 $args = array();
788 }
789 else {
790 array_shift($args);
791 array_shift($args);
792 }
793
794 require_once($typedirectory);
81bdfdb9 795 return call_user_func_array(array('repository_' . $plugin, $function), $args);
dbc01944 796 }
797
798 /**
799 * Move file from download folder to file pool using FILE API
800 * @global object $DB
801 * @global object $CFG
802 * @global object $USER
1a6195b4 803 * @global object $OUTPUT
8e0946bf 804 * @param string $thefile file path in download folder
50dea1b7 805 * @param object $record
1a6195b4
DC
806 * @return array containing the following keys:
807 * icon
808 * file
809 * id
810 * url
dbc01944 811 */
14469892 812 public static function move_to_filepool($thefile, $record) {
390baf46 813 global $DB, $CFG, $USER, $OUTPUT;
14469892
DC
814 if ($record->filepath !== '/') {
815 $record->filepath = trim($record->filepath, '/');
816 $record->filepath = '/'.$record->filepath.'/';
e5fa0e8d 817 }
dbc01944 818 $context = get_context_instance(CONTEXT_USER, $USER->id);
819 $now = time();
14469892
DC
820
821 $record->contextid = $context->id;
822 $record->timecreated = $now;
823 $record->timemodified = $now;
824 $record->userid = $USER->id;
825 $record->mimetype = mimeinfo('type', $thefile);
826 if(!is_numeric($record->itemid)) {
827 $record->itemid = 0;
dbc01944 828 }
dbc01944 829 $fs = get_file_storage();
830 $browser = get_file_browser();
14469892 831 if ($existingfile = $fs->get_file($context->id, $record->filearea, $record->itemid, $record->filepath, $record->filename)) {
b423b4af 832 $existingfile->delete();
833 }
14469892 834 if ($file = $fs->create_file_from_pathname($record, $thefile)) {
88b126a5 835 if (empty($CFG->repository_no_delete)) {
99eaca9d 836 $delete = unlink($thefile);
88b126a5 837 unset($CFG->repository_no_delete);
838 }
99eaca9d
DC
839 $fileinfo = $browser->get_file_info($context, $file->get_filearea(), $file->get_itemid(), $file->get_filepath(), $file->get_filename());
840 if(!empty($fileinfo)) {
a0ff4137 841 return array(
99eaca9d 842 'url'=>$fileinfo->get_url(),
b423b4af 843 'id'=>$file->get_itemid(),
844 'file'=>$file->get_filename(),
2539ce37 845 'icon' => $OUTPUT->pix_url(file_extension_icon($thefile, 32))->out()
b423b4af 846 );
dbc01944 847 } else {
848 return null;
849 }
850 } else {
851 return null;
852 }
853 }
854
dbc01944 855 /**
b81ebefd 856 * Return the user files tree in a format to be returned by the function get_listing
2b8beee3 857 * @global object $CFG
858 * @param string $search
859 * @return array
dbc01944 860 */
8e0946bf 861 public static function get_user_file_tree($search = ''){
dbc01944 862 global $CFG;
fc3ec2ca 863 $ret = array();
864 $ret['nologin'] = true;
865 $ret['manage'] = $CFG->wwwroot .'/files/index.php'; // temporary
866 $browser = get_file_browser();
867 $itemid = null;
868 $filename = null;
869 $filearea = null;
870 $path = '/';
871 $ret['dynload'] = false;
872
873 if ($fileinfo = $browser->get_file_info(get_system_context(), $filearea, $itemid, $path, $filename)) {
874
875 $ret['path'] = array();
876 $params = $fileinfo->get_params();
877 $filearea = $params['filearea'];
878 $ret['path'][] = repository::encode_path($filearea, $path, $fileinfo->get_visible_name());
879 if ($fileinfo->is_directory()) {
880 $level = $fileinfo->get_parent();
881 while ($level) {
882 $params = $level->get_params();
883 $ret['path'][] = repository::encode_path($params['filearea'], $params['filepath'], $level->get_visible_name());
884 $level = $level->get_parent();
dbc01944 885 }
dbc01944 886 }
fc3ec2ca 887 $filecount = repository::build_tree($fileinfo, $search, $ret['dynload'], $ret['list']);
888 $ret['path'] = array_reverse($ret['path']);
889 }
dbc01944 890
fc3ec2ca 891 if (empty($ret['list'])) {
892 //exit(mnet_server_fault(9016, get_string('emptyfilelist', 'repository_local')));
893 throw new Exception('emptyfilelist');
894 } else {
895 return $ret;
896 }
dbc01944 897
898 }
899
900 /**
8e0946bf 901 * Serialize file path
2b8beee3 902 * @param string $filearea
903 * @param string $path
904 * @param string $visiblename
905 * @return array
dbc01944 906 */
907 public static function encode_path($filearea, $path, $visiblename) {
908 return array('path'=>serialize(array($filearea, $path)), 'name'=>$visiblename);
909 }
910
911 /**
912 * Builds a tree of files This function is
913 * then called recursively.
914 *
915 * @param $fileinfo an object returned by file_browser::get_file_info()
916 * @param $search searched string
917 * @param $dynamicmode bool no recursive call is done when in dynamic mode
918 * @param $list - the array containing the files under the passed $fileinfo
919 * @returns int the number of files found
920 *
921 * todo: take $search into account, and respect a threshold for dynamic loading
922 */
923 public static function build_tree($fileinfo, $search, $dynamicmode, &$list) {
390baf46 924 global $CFG, $OUTPUT;
dbc01944 925
926 $filecount = 0;
927 $children = $fileinfo->get_children();
928
929 foreach ($children as $child) {
930 $filename = $child->get_visible_name();
931 $filesize = $child->get_filesize();
932 $filesize = $filesize ? display_size($filesize) : '';
933 $filedate = $child->get_timemodified();
934 $filedate = $filedate ? userdate($filedate) : '';
935 $filetype = $child->get_mimetype();
936
937 if ($child->is_directory()) {
938 $path = array();
939 $level = $child->get_parent();
940 while ($level) {
941 $params = $level->get_params();
942 $path[] = repository::encode_path($params['filearea'], $params['filepath'], $level->get_visible_name());
943 $level = $level->get_parent();
944 }
945
946 $tmp = array(
947 'title' => $child->get_visible_name(),
948 'size' => 0,
949 'date' => $filedate,
950 'path' => array_reverse($path),
b5d0cafc 951 'thumbnail' => $OUTPUT->pix_url('f/folder-32')
dbc01944 952 );
953
954 //if ($dynamicmode && $child->is_writable()) {
955 // $tmp['children'] = array();
956 //} else {
957 // if folder name matches search, we send back all files contained.
958 $_search = $search;
959 if ($search && stristr($tmp['title'], $search) !== false) {
960 $_search = false;
961 }
962 $tmp['children'] = array();
963 $_filecount = repository::build_tree($child, $_search, $dynamicmode, $tmp['children']);
964 if ($search && $_filecount) {
965 $tmp['expanded'] = 1;
966 }
967
968 //}
969
fc3ec2ca 970 if (!$search || $_filecount || (stristr($tmp['title'], $search) !== false)) {
dbc01944 971 $filecount += $_filecount;
972 $list[] = $tmp;
973 }
974
975 } else { // not a directory
976 // skip the file, if we're in search mode and it's not a match
977 if ($search && (stristr($filename, $search) === false)) {
978 continue;
979 }
980 $params = $child->get_params();
981 $source = serialize(array($params['contextid'], $params['filearea'], $params['itemid'], $params['filepath'], $params['filename']));
982 $list[] = array(
983 'title' => $filename,
984 'size' => $filesize,
985 'date' => $filedate,
986 //'source' => $child->get_url(),
987 'source' => base64_encode($source),
b5d0cafc 988 'thumbnail'=>$OUTPUT->pix_url(file_extension_icon($filename, 32)),
dbc01944 989 );
990 $filecount++;
991 }
992 }
993
994 return $filecount;
995 }
996
997
998 /**
999 * Display a repository instance list (with edit/delete/create links)
1000 * @global object $CFG
1001 * @global object $USER
8e0946bf 1002 * @global object $OUTPUT
dbc01944 1003 * @param object $context the context for which we display the instance
1004 * @param string $typename if set, we display only one type of instance
1005 */
1006 public static function display_instances_list($context, $typename = null) {
50a5cf09 1007 global $CFG, $USER, $OUTPUT;
dbc01944 1008
50a5cf09 1009 $output = $OUTPUT->box_start('generalbox');
dbc01944 1010 //if the context is SYSTEM, so we call it from administration page
1011 $admin = ($context->id == SYSCONTEXTID) ? true : false;
1012 if ($admin) {
d1aa1e48 1013 $baseurl = "$CFG->httpswwwroot/$CFG->admin/repositoryinstance.php?sesskey=" . sesskey();
dbc01944 1014 $output .= "<div ><h2 style='text-align: center'>" . get_string('siteinstances', 'repository') . " ";
1015 $output .= "</h2></div>";
1016 } else {
1017 $baseurl = $CFG->httpswwwroot . '/repository/manage_instances.php?contextid=' . $context->id . '&amp;sesskey=' . sesskey();
1018 }
5363905a 1019 $url = new moodle_url($baseurl);
dbc01944 1020
1021 $namestr = get_string('name');
1022 $pluginstr = get_string('plugin', 'repository');
1023 $settingsstr = get_string('settings');
1024 $deletestr = get_string('delete');
1025 $updown = get_string('updown', 'repository');
1026 //retrieve list of instances. In administration context we want to display all
1027 //instances of a type, even if this type is not visible. In course/user context we
92eaeca5 1028 //want to display only visible instances, but for every type types. The repository::get_instances()
dbc01944 1029 //third parameter displays only visible type.
6f2cd52a
DC
1030 $params = array();
1031 $params['context'] = array($context, get_system_context());
1032 $params['currentcontext'] = $context;
1033 $params['onlyvisible'] = !$admin;
1034 $params['type'] = $typename;
1035 $instances = repository::get_instances($params);
dbc01944 1036 $instancesnumber = count($instances);
1037 $alreadyplugins = array();
1038
55400db0 1039 $table = new html_table();
dbc01944 1040 $table->head = array($namestr, $pluginstr, $deletestr, $settingsstr);
1041 $table->align = array('left', 'left', 'center','center');
1042 $table->data = array();
1043
1044 $updowncount = 1;
1045
1046 foreach ($instances as $i) {
1047 $settings = '';
1048 $delete = '';
5363905a
DC
1049
1050 $type = repository::get_type_by_id($i->options['typeid']);
1051
1052 if ($type->get_contextvisibility($context)) {
1053 if (!$i->readonly) {
1054
1055 $url->param('type', $i->options['type']);
1056 $url->param('edit', $i->id);
0f4c64b7 1057 $settings .= html_writer::link($url, $settingsstr);
5363905a
DC
1058
1059 $url->remove_params('edit');
1060 $url->param('delete', $i->id);
0f4c64b7 1061 $delete .= html_writer::link($url, $deletestr);
5363905a
DC
1062
1063 $url->remove_params('type');
1064 }
dbc01944 1065 }
1066
a3d8df25 1067 $type = repository::get_type_by_id($i->options['typeid']);
dbc01944 1068 $table->data[] = array($i->name, $type->get_readablename(), $delete, $settings);
1069
1070 //display a grey row if the type is defined as not visible
1071 if (isset($type) && !$type->get_visible()) {
704ac344 1072 $table->rowclasses[] = 'dimmed_text';
dbc01944 1073 } else {
704ac344 1074 $table->rowclasses[] = '';
dbc01944 1075 }
1076
1077 if (!in_array($i->name, $alreadyplugins)) {
1078 $alreadyplugins[] = $i->name;
1079 }
1080 }
16be8974 1081 $output .= html_writer::table($table);
dbc01944 1082 $instancehtml = '<div>';
1083 $addable = 0;
1084
1085 //if no type is set, we can create all type of instance
1086 if (!$typename) {
1087 $instancehtml .= '<h3>';
1088 $instancehtml .= get_string('createrepository', 'repository');
1089 $instancehtml .= '</h3><ul>';
1090 $types = repository::get_editable_types($context);
1091 foreach ($types as $type) {
1092 if (!empty($type) && $type->get_visible()) {
1093 $instanceoptionnames = repository::static_function($type->get_typename(), 'get_instance_option_names');
1094 if (!empty($instanceoptionnames)) {
8af334cd 1095 $instancehtml .= '<li><a href="'.$baseurl.'&amp;new='.$type->get_typename().'">'.get_string('createxxinstance', 'repository', get_string('repositoryname', 'repository_'.$type->get_typename()))
1096 .'</a></li>';
dbc01944 1097 $addable++;
1098 }
1099 }
1100 }
1101 $instancehtml .= '</ul>';
1102
1103 } else {
1104 $instanceoptionnames = repository::static_function($typename, 'get_instance_option_names');
1105 if (!empty($instanceoptionnames)) { //create a unique type of instance
1106 $addable = 1;
1107 $instancehtml .= "<form action='".$baseurl."&amp;new=".$typename."' method='post'>
1108 <p style='text-align:center'><input type='submit' value='".get_string('createinstance', 'repository')."'/></p>
1109 </form>";
1110 }
1111 }
1112
1113 if ($addable) {
1114 $instancehtml .= '</div>';
1115 $output .= $instancehtml;
1116 }
1117
50a5cf09 1118 $output .= $OUTPUT->box_end();
dbc01944 1119
1120 //print the list + creation links
1121 print($output);
1122 }
1cf56396 1123
c425472d 1124 /**
a53d4f45 1125 * Decide where to save the file, can be
1126 * reused by sub class
1127 * @param string filename
c425472d 1128 */
a560785f 1129 public function prepare_file($filename) {
c425472d 1130 global $CFG;
c9260130 1131 if (!file_exists($CFG->dataroot.'/temp/download')) {
1132 mkdir($CFG->dataroot.'/temp/download/', 0777, true);
1e28c767 1133 }
7a3b93c1 1134 if (is_dir($CFG->dataroot.'/temp/download')) {
c9260130 1135 $dir = $CFG->dataroot.'/temp/download/';
1e28c767 1136 }
a560785f 1137 if (empty($filename)) {
1138 $filename = uniqid('repo').'_'.time().'.tmp';
84df43de 1139 }
a560785f 1140 if (file_exists($dir.$filename)) {
1141 $filename = uniqid('m').$filename;
c425472d 1142 }
a560785f 1143 return $dir.$filename;
a53d4f45 1144 }
1145
99d52655
DC
1146 /**
1147 * Return file URL, for most plugins, the parameter is the original
1148 * url, but some plugins use a file id, so we need this function to
1149 * convert file id to original url.
1150 *
1151 * @param string $url the url of file
8e0946bf 1152 * @return string
99d52655
DC
1153 */
1154 public function get_link($url) {
1155 return $url;
1156 }
1157
a53d4f45 1158 /**
1159 * Download a file, this function can be overridden by
1160 * subclass.
1161 *
1162 * @global object $CFG
1163 * @param string $url the url of file
a560785f 1164 * @param string $filename save location
a53d4f45 1165 * @return string the location of the file
1166 * @see curl package
1167 */
a560785f 1168 public function get_file($url, $filename = '') {
a53d4f45 1169 global $CFG;
41076c58
DC
1170 $path = $this->prepare_file($filename);
1171 $fp = fopen($path, 'w');
1172 $c = new curl;
1173 $c->download(array(array('url'=>$url, 'file'=>$fp)));
1dce6261 1174 return array('path'=>$path, 'url'=>$url);
82669dc4 1175 }
1cf56396 1176
f48fb4d6 1177 /**
1178 * Return is the instance is visible
1179 * (is the type visible ? is the context enable ?)
1180 * @return boolean
1181 */
dbc01944 1182 public function is_visible() {
7d554b64 1183 $type = repository::get_type_by_id($this->options['typeid']);
dbc01944 1184 $instanceoptions = repository::static_function($type->get_typename(), 'get_instance_option_names');
f48fb4d6 1185
1186 if ($type->get_visible()) {
1187 //if the instance is unique so it's visible, otherwise check if the instance has a enabled context
5363905a 1188 if (empty($instanceoptions) || $type->get_contextvisibility($this->context)) {
f48fb4d6 1189 return true;
1190 }
1191 }
1192
1193 return false;
1194 }
1195
eb239694 1196 /**
66dc47bc 1197 * Return the name of this instance, can be overridden.
2b8beee3 1198 * @global object $DB
1199 * @return string
eb239694 1200 */
7a3b93c1 1201 public function get_name() {
d31af46a 1202 global $DB;
1203 // We always verify instance id from database,
1204 // so we always know repository name before init
1205 // a repository, so we don't enquery repository
1206 // name from database again here.
1207 if (isset($this->options['name'])) {
1208 return $this->options['name'];
1209 } else {
1210 if ( $repo = $DB->get_record('repository_instances', array('id'=>$this->id)) ) {
1211 return $repo->name;
1212 } else {
1213 return '';
1214 }
1215 }
1216 }
aa754fe3 1217
b318bb6d 1218 /**
1219 * what kind of files will be in this repository?
1220 * @return array return '*' means this repository support any files, otherwise
1221 * return mimetypes of files, it can be an array
1222 */
014c1ca0 1223 public function supported_filetypes() {
b318bb6d 1224 // return array('text/plain', 'image/gif');
1225 return '*';
1226 }
1227
1228 /**
1229 * does it return a file url or a item_id
1230 * @return string
1231 */
41076c58
DC
1232 public function supported_returntypes() {
1233 return (FILE_INTERNAL | FILE_EXTERNAL);
92eaeca5 1234 }
b318bb6d 1235
82669dc4 1236 /**
3f24ea1e 1237 * Provide repository instance information for Ajax
8dcd5deb 1238 * @global object $CFG
4a65c39a 1239 * @return object
82669dc4 1240 */
7d554b64 1241 final public function get_meta() {
4a65c39a 1242 global $CFG;
99eaca9d 1243 $ft = new filetype_parser;
7d554b64 1244 $meta = new stdclass;
1245 $meta->id = $this->id;
1246 $meta->name = $this->get_name();
1247 $meta->type = $this->options['type'];
c875ad9a 1248 $meta->icon = $CFG->httpswwwroot.'/repository/'.$meta->type.'/icon.png';
99eaca9d 1249 $meta->supported_types = $ft->get_extensions($this->supported_filetypes());
6f2cd52a 1250 $meta->return_types = $this->supported_returntypes();
7d554b64 1251 return $meta;
4a65c39a 1252 }
1cf56396 1253
b1339e98 1254 /**
1255 * Create an instance for this plug-in
8dcd5deb 1256 * @global object $CFG
1257 * @global object $DB
1258 * @param string $type the type of the repository
1259 * @param integer $userid the user id
1260 * @param object $context the context
1261 * @param array $params the options for this instance
635f1a8b 1262 * @param integer $readonly whether to create it readonly or not (defaults to not)
2b8beee3 1263 * @return mixed
b1339e98 1264 */
948c2860 1265 final public static function create($type, $userid, $context, $params, $readonly=0) {
b1339e98 1266 global $CFG, $DB;
1267 $params = (array)$params;
1268 require_once($CFG->dirroot . '/repository/'. $type . '/repository.class.php');
1269 $classname = 'repository_' . $type;
3023078f 1270 if ($repo = $DB->get_record('repository', array('type'=>$type))) {
1271 $record = new stdclass;
1272 $record->name = $params['name'];
1273 $record->typeid = $repo->id;
1274 $record->timecreated = time();
1275 $record->timemodified = time();
1276 $record->contextid = $context->id;
948c2860 1277 $record->readonly = $readonly;
3023078f 1278 $record->userid = $userid;
1279 $id = $DB->insert_record('repository_instances', $record);
0a6221f9 1280 $options = array();
edb50637 1281 $configs = call_user_func($classname . '::get_instance_option_names');
1e08b5cf 1282 if (!empty($configs)) {
1283 foreach ($configs as $config) {
1284 $options[$config] = $params[$config];
1285 }
3023078f 1286 }
3a01a46a 1287
3023078f 1288 if (!empty($id)) {
1289 unset($options['name']);
dbc01944 1290 $instance = repository::get_instance($id);
3023078f 1291 $instance->set_option($options);
1292 return $id;
1293 } else {
1294 return null;
b1339e98 1295 }
b1339e98 1296 } else {
1297 return null;
1298 }
1299 }
8dcd5deb 1300
82669dc4 1301 /**
4a65c39a 1302 * delete a repository instance
8dcd5deb 1303 * @global object $DB
2b8beee3 1304 * @return mixed
82669dc4 1305 */
7a3b93c1 1306 final public function delete() {
4a65c39a 1307 global $DB;
122defc5 1308 $DB->delete_records('repository_instances', array('id'=>$this->id));
2b0b3626 1309 $DB->delete_records('repository_instance_config', array('instanceid'=>$this->id));
4a65c39a 1310 return true;
1311 }
8dcd5deb 1312
4a65c39a 1313 /**
1314 * Hide/Show a repository
8dcd5deb 1315 * @global object $DB
1316 * @param string $hide
2b8beee3 1317 * @return boolean
4a65c39a 1318 */
7a3b93c1 1319 final public function hide($hide = 'toggle') {
4a65c39a 1320 global $DB;
1321 if ($entry = $DB->get_record('repository', array('id'=>$this->id))) {
1322 if ($hide === 'toggle' ) {
1323 if (!empty($entry->visible)) {
1324 $entry->visible = 0;
1325 } else {
1326 $entry->visible = 1;
1327 }
1328 } else {
1329 if (!empty($hide)) {
1330 $entry->visible = 0;
1331 } else {
1332 $entry->visible = 1;
1333 }
1334 }
1335 return $DB->update_record('repository', $entry);
1336 }
1337 return false;
1338 }
1cf56396 1339
1340 /**
82669dc4 1341 * Cache login details for repositories
8dcd5deb 1342 * @global object $DB
82669dc4 1343 * @param string $username
1344 * @param string $password
8dcd5deb 1345 * @param integer $userid The id of specific user
1346 * @return integer Id of the record
1cf56396 1347 */
b6558c3b 1348 public function store_login($username = '', $password = '', $userid = 1) {
fca079c5 1349 global $DB;
1350
1351 $repository = new stdclass;
4a65c39a 1352 if (!empty($this->id)) {
1353 $repository->id = $this->id;
19add4c0 1354 } else {
1355 $repository->userid = $userid;
1356 $repository->repositorytype = $this->type;
b6558c3b 1357 $repository->contextid = $this->context->id;
19add4c0 1358 }
fca079c5 1359 if ($entry = $DB->get_record('repository', $repository)) {
1360 $repository->id = $entry->id;
1361 $repository->username = $username;
1362 $repository->password = $password;
1363 return $DB->update_record('repository', $repository);
1364 } else {
1365 $repository->username = $username;
1366 $repository->password = $password;
1367 return $DB->insert_record('repository', $repository);
1368 }
1cf56396 1369 }
1370
1cf56396 1371 /**
4a65c39a 1372 * Save settings for repository instance
8dcd5deb 1373 * $repo->set_option(array('api_key'=>'f2188bde132', 'name'=>'dongsheng'));
1374 * @global object $DB
1375 * @param array $options settings
4a65c39a 1376 * @return int Id of the record
1cf56396 1377 */
7a3b93c1 1378 public function set_option($options = array()) {
4a65c39a 1379 global $DB;
7a3b93c1 1380
122defc5 1381 if (!empty($options['name'])) {
1382 $r = new object();
1383 $r->id = $this->id;
1384 $r->name = $options['name'];
1385 $DB->update_record('repository_instances', $r);
1386 unset($options['name']);
1387 }
e53a97d1 1388 $result = true;
27051e43 1389 foreach ($options as $name=>$value) {
1390 if ($id = $DB->get_field('repository_instance_config', 'id', array('name'=>$name, 'instanceid'=>$this->id))) {
7d6ca931 1391 $result = $result && $DB->set_field('repository_instance_config', 'value', $value, array('id'=>$id));
27051e43 1392 } else {
27051e43 1393 $config = new object();
1394 $config->instanceid = $this->id;
1395 $config->name = $name;
1396 $config->value = $value;
e53a97d1 1397 $result = $result && $DB->insert_record('repository_instance_config', $config);
27051e43 1398 }
4a65c39a 1399 }
e53a97d1 1400 return $result;
1cf56396 1401 }
1cf56396 1402
4a65c39a 1403 /**
1404 * Get settings for repository instance
8dcd5deb 1405 * @global object $DB
2b8beee3 1406 * @param string $config
4a65c39a 1407 * @return array Settings
1408 */
7a3b93c1 1409 public function get_option($config = '') {
4a65c39a 1410 global $DB;
27051e43 1411 $entries = $DB->get_records('repository_instance_config', array('instanceid'=>$this->id));
1412 $ret = array();
1413 if (empty($entries)) {
1414 return $ret;
4a65c39a 1415 }
7a3b93c1 1416 foreach($entries as $entry) {
27051e43 1417 $ret[$entry->name] = $entry->value;
4a65c39a 1418 }
1419 if (!empty($config)) {
75003899 1420 return $ret[$config];
4a65c39a 1421 } else {
1422 return $ret;
1423 }
1424 }
bf1fccf0 1425
c167aa26 1426 public function filter(&$value) {
1427 $pass = false;
1428 $accepted_types = optional_param('accepted_types', '', PARAM_RAW);
99eaca9d
DC
1429 $ft = new filetype_parser;
1430 $ext = $ft->get_extensions($this->supported_filetypes());
b81ebefd 1431 if (isset($value['children'])) {
c167aa26 1432 $pass = true;
b81ebefd 1433 if (!empty($value['children'])) {
b81ebefd 1434 $value['children'] = array_filter($value['children'], array($this, 'filter'));
537d44e8 1435 }
c167aa26 1436 } else {
46ee50dc 1437 if ($accepted_types == '*' or empty($accepted_types)
1438 or (is_array($accepted_types) and in_array('*', $accepted_types))) {
c167aa26 1439 $pass = true;
1440 } elseif (is_array($accepted_types)) {
1441 foreach ($accepted_types as $type) {
1442 if (preg_match('#'.$type.'$#', $value['title'])) {
1443 $pass = true;
1444 }
1445 }
1446 }
1447 }
1448 return $pass;
1449 }
1450
4a65c39a 1451 /**
1452 * Given a path, and perhaps a search, get a list of files.
1453 *
2b8beee3 1454 * See details on http://docs.moodle.org/en/Development:Repository_plugins
f7639c37 1455 *
8e0946bf 1456 * @param string $path, this parameter can
4a65c39a 1457 * a folder name, or a identification of folder
8e0946bf 1458 * @param string $page, the page number of file list
1a6195b4
DC
1459 * @return array the list of files, including meta infomation, containing the following keys
1460 * manage, url to manage url
1461 * client_id
1462 * login, login form
1463 * repo_id, active repository id
1464 * login_btn_action, the login button action
1465 * login_btn_label, the login button label
1466 * total, number of results
1467 * perpage, items per page
1468 * page
1469 * pages, total pages
1470 * search_result, is it a search result?
1471 * list, file list
1472 * path, current path and parent path
4a65c39a 1473 */
9d6aa286 1474 public function get_listing($path = '', $page = '') {
1475 }
1cf56396 1476
fbd508b4 1477 /**
353d5cf3 1478 * Search files in repository
1479 * When doing global search, $search_text will be used as
dbc01944 1480 * keyword.
353d5cf3 1481 *
fbd508b4 1482 * @return mixed, see get_listing()
1483 */
353d5cf3 1484 public function search($search_text) {
1485 $list = array();
1486 $list['list'] = array();
1487 return false;
fbd508b4 1488 }
1489
d68c527f 1490 /**
1491 * Logout from repository instance
1492 * By default, this function will return a login form
1493 *
1494 * @return string
1495 */
1496 public function logout(){
1497 return $this->print_login();
1498 }
1499
1500 /**
1501 * To check whether the user is logged in.
1502 *
1503 * @return boolean
1504 */
1505 public function check_login(){
1506 return true;
1507 }
1508
1cf56396 1509
4a65c39a 1510 /**
1511 * Show the login screen, if required
4a65c39a 1512 */
1d66f2b2 1513 public function print_login(){
1514 return $this->get_listing();
1515 }
1cf56396 1516
4a65c39a 1517 /**
1518 * Show the search screen, if required
4a65c39a 1519 * @return null
1520 */
a560785f 1521 public function print_search() {
b763c2d9 1522 $str = '';
1523 $str .= '<input type="hidden" name="repo_id" value="'.$this->id.'" />';
1524 $str .= '<input type="hidden" name="ctx_id" value="'.$this->context->id.'" />';
1525 $str .= '<input type="hidden" name="seekey" value="'.sesskey().'" />';
1526 $str .= '<label>'.get_string('keyword', 'repository').': </label><br/><input name="s" value="" /><br/>';
1527 return $str;
2b9feb5f 1528 }
4a65c39a 1529
455860ce 1530 /**
1531 * is it possible to do glboal search?
1532 * @return boolean
1533 */
7a3b93c1 1534 public function global_search() {
455860ce 1535 return false;
1536 }
1537
8dcd5deb 1538 /**
a6600395 1539 * Defines operations that happen occasionally on cron
2b8beee3 1540 * @return boolean
8dcd5deb 1541 */
a6600395 1542 public function cron() {
1543 return true;
1544 }
1545
7892948d 1546 /**
83a018ed 1547 * function which is run when the type is created (moodle administrator add the plugin)
3e0794ed 1548 * @return boolean success or fail?
7892948d 1549 */
f1cfe56e 1550 public static function plugin_init() {
3e0794ed 1551 return true;
7892948d 1552 }
1553
a6600395 1554 /**
06e65e1e 1555 * Edit/Create Admin Settings Moodle form
1556 * @param object $ Moodle form (passed by reference)
a6600395 1557 */
8c4a4687 1558 public function type_config_form($mform) {
4a65c39a 1559 }
dbc01944 1560
6f2cd52a 1561 /**
06e65e1e 1562 * Edit/Create Instance Settings Moodle form
1563 * @param object $ Moodle form (passed by reference)
a6600395 1564 */
8c4a4687 1565 public function instance_config_form($mform) {
a6600395 1566 }
4a65c39a 1567
a6600395 1568 /**
1569 * Return names of the general options
1570 * By default: no general option name
1571 * @return array
1572 */
1b79955a 1573 public static function get_type_option_names() {
a6600395 1574 return array();
1575 }
1576
1577 /**
1578 * Return names of the instance options
1579 * By default: no instance option name
1580 * @return array
1581 */
7a3b93c1 1582 public static function get_instance_option_names() {
a6600395 1583 return array();
8b65d45c 1584 }
119a4ae1 1585
8b65d45c 1586}
837ebb78 1587
1588/**
6f2cd52a
DC
1589 * Exception class for repository api
1590 *
1591 * @since 2.0
1592 * @package moodlecore
1593 * @subpackage repository
1594 * @copyright 2009 Dongsheng Cai <dongsheng@moodle.com>
1595 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
837ebb78 1596 */
4a65c39a 1597class repository_exception extends moodle_exception {
8b65d45c 1598}
4ed43890 1599
e3ca0f3a 1600
1601
8dcd5deb 1602/**
6f2cd52a
DC
1603 * This is a class used to define a repository instance form
1604 *
1605 * @since 2.0
1606 * @package moodlecore
1607 * @subpackage repository
1608 * @copyright 2009 Dongsheng Cai <dongsheng@moodle.com>
1609 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
8dcd5deb 1610 */
a6600395 1611final class repository_instance_form extends moodleform {
4a65c39a 1612 protected $instance;
1613 protected $plugin;
1614
1615 public function definition() {
1616 global $CFG;
1617 // type of plugin, string
1618 $this->plugin = $this->_customdata['plugin'];
27051e43 1619 $this->typeid = $this->_customdata['typeid'];
faaa613d 1620 $this->contextid = $this->_customdata['contextid'];
4a65c39a 1621 $this->instance = (isset($this->_customdata['instance'])
1622 && is_subclass_of($this->_customdata['instance'], 'repository'))
1623 ? $this->_customdata['instance'] : null;
1624
1625 $mform =& $this->_form;
1626 $strrequired = get_string('required');
1627
1628 $mform->addElement('hidden', 'edit', ($this->instance) ? $this->instance->id : 0);
d18e0fe6 1629 $mform->setType('edit', PARAM_INT);
4a65c39a 1630 $mform->addElement('hidden', 'new', $this->plugin);
d18e0fe6 1631 $mform->setType('new', PARAM_FORMAT);
4a65c39a 1632 $mform->addElement('hidden', 'plugin', $this->plugin);
d18e0fe6 1633 $mform->setType('plugin', PARAM_SAFEDIR);
27051e43 1634 $mform->addElement('hidden', 'typeid', $this->typeid);
d18e0fe6 1635 $mform->setType('typeid', PARAM_INT);
faaa613d 1636 $mform->addElement('hidden', 'contextid', $this->contextid);
d18e0fe6 1637 $mform->setType('contextid', PARAM_INT);
4a65c39a 1638
1639 $mform->addElement('text', 'name', get_string('name'), 'maxlength="100" size="30"');
1640 $mform->addRule('name', $strrequired, 'required', null, 'client');
1641
1e97f196 1642
f48fb4d6 1643 //add fields
1644 if (!$this->instance) {
dbc01944 1645 $result = repository::static_function($this->plugin, 'instance_config_form', $mform);
f48fb4d6 1646 }
1647 else {
1648 $data = array();
1649 $data['name'] = $this->instance->name;
1650 if (!$this->instance->readonly) {
1651 $result = $this->instance->instance_config_form($mform);
1652 // and set the data if we have some.
1e97f196 1653 foreach ($this->instance->get_instance_option_names() as $config) {
a3d8df25 1654 if (!empty($this->instance->options[$config])) {
1655 $data[$config] = $this->instance->options[$config];
1e97f196 1656 } else {
1657 $data[$config] = '';
1658 }
27051e43 1659 }
4a65c39a 1660 }
f48fb4d6 1661 $this->set_data($data);
1e97f196 1662 }
1663
46dd6bb0 1664 $this->add_action_buttons(true, get_string('save','repository'));
4a65c39a 1665 }
1666
1667 public function validation($data) {
1668 global $DB;
1669
1670 $errors = array();
50a5cf09 1671 $sql = "SELECT count('x') FROM {repository_instances} i, {repository} r WHERE r.type=:plugin AND r.id=i.typeid AND i.name=:name";
09bff8e8 1672 if ($DB->count_records_sql($sql, array('name' => $data['name'], 'plugin' => $data['plugin'])) > 1) {
4a65c39a 1673 $errors = array('name' => get_string('err_uniquename', 'repository'));
1674 }
1675
4a65c39a 1676 return $errors;
1677 }
1678}
a6600395 1679
a6600395 1680/**
6f2cd52a
DC
1681 * This is a class used to define a repository type setting form
1682 *
1683 * @since 2.0
1684 * @package moodlecore
1685 * @subpackage repository
1686 * @copyright 2009 Dongsheng Cai <dongsheng@moodle.com>
1687 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
a6600395 1688 */
c295f9ff 1689final class repository_type_form extends moodleform {
a6600395 1690 protected $instance;
1691 protected $plugin;
1692
1693 /**
1694 * Definition of the moodleform
1695 * @global object $CFG
1696 */
1697 public function definition() {
1698 global $CFG;
1699 // type of plugin, string
1700 $this->plugin = $this->_customdata['plugin'];
1701 $this->instance = (isset($this->_customdata['instance'])
1702 && is_a($this->_customdata['instance'], 'repository_type'))
1703 ? $this->_customdata['instance'] : null;
1704
1705 $mform =& $this->_form;
1706 $strrequired = get_string('required');
4d5948f1 1707
a6600395 1708 $mform->addElement('hidden', 'edit', ($this->instance) ? $this->instance->get_typename() : 0);
d18e0fe6 1709 $mform->setType('edit', PARAM_INT);
a6600395 1710 $mform->addElement('hidden', 'new', $this->plugin);
d18e0fe6 1711 $mform->setType('new', PARAM_FORMAT);
a6600395 1712 $mform->addElement('hidden', 'plugin', $this->plugin);
d18e0fe6 1713 $mform->setType('plugin', PARAM_SAFEDIR);
8f943eba 1714
06e65e1e 1715 // let the plugin add its specific fields
1716 if (!$this->instance) {
88b126a5 1717 $result = repository::static_function($this->plugin, 'type_config_form', $mform);
1718 } else {
1719 $classname = 'repository_' . $this->instance->get_typename();
1720 $result = call_user_func(array($classname, 'type_config_form'), $mform);
a6600395 1721 }
1722
f48fb4d6 1723 //add "enable course/user instances" checkboxes if multiple instances are allowed
dbc01944 1724 $instanceoptionnames = repository::static_function($this->plugin, 'get_instance_option_names');
f48fb4d6 1725 if (!empty($instanceoptionnames)){
1726 $mform->addElement('checkbox', 'enablecourseinstances', get_string('enablecourseinstances', 'repository'));
1727 $mform->addElement('checkbox', 'enableuserinstances', get_string('enableuserinstances', 'repository'));
1728 }
1729
1730 // set the data if we have some.
a6600395 1731 if ($this->instance) {
1732 $data = array();
1b79955a 1733 $option_names = call_user_func(array($classname,'get_type_option_names'));
f48fb4d6 1734 if (!empty($instanceoptionnames)){
1735 $option_names[] = 'enablecourseinstances';
1736 $option_names[] = 'enableuserinstances';
1737 }
1738
a6600395 1739 $instanceoptions = $this->instance->get_options();
1740 foreach ($option_names as $config) {
1741 if (!empty($instanceoptions[$config])) {
1742 $data[$config] = $instanceoptions[$config];
1743 } else {
1744 $data[$config] = '';
1745 }
1746 }
1747 $this->set_data($data);
1748 }
dbc01944 1749
46dd6bb0 1750 $this->add_action_buttons(true, get_string('save','repository'));
a6600395 1751 }
a6600395 1752}
1753
8e0946bf
DC
1754/**
1755 * Generate all options needed by filepicker
1756 *
1757 * @param array $args, including following keys
1758 * context
1759 * accepted_types
1760 * return_types
1761 *
1762 * @return array the list of repository instances, including meta infomation, containing the following keys
1763 * externallink
1764 * repositories
1765 * accepted_types
1766 */
99eaca9d 1767function initialise_filepicker($args) {
a28c9253 1768 global $CFG, $USER, $PAGE, $OUTPUT;
1dce6261 1769 require_once($CFG->libdir . '/licenselib.php');
4f0c2d00
PS
1770
1771 $return = new stdclass;
d1d4813f 1772 $licenses = array();
4f0c2d00
PS
1773 if (!empty($CFG->licenses)) {
1774 $array = explode(',', $CFG->licenses);
1775 foreach ($array as $license) {
1776 $l = new stdclass;
1777 $l->shortname = $license;
1778 $l->fullname = get_string($license, 'license');
1779 $licenses[] = $l;
1780 }
d1d4813f 1781 }
1dce6261 1782
1dce6261
DC
1783 $return->licenses = $licenses;
1784
1785 $return->author = fullname($USER);
1786
99eaca9d
DC
1787 $ft = new filetype_parser();
1788 if (empty($args->context)) {
1789 $context = $PAGE->context;
e189ec00 1790 } else {
99eaca9d
DC
1791 $context = $args->context;
1792 }
99eaca9d 1793
e189ec00 1794 $user_context = get_context_instance(CONTEXT_USER, $USER->id);
99eaca9d
DC
1795
1796 $externallink = (int)get_config(null, 'repositoryallowexternallinks');
1797 $repositories = repository::get_instances(array(
1798 'context'=>array($user_context, get_system_context()),
1799 'currentcontext'=> $context,
81bdfdb9
DC
1800 'accepted_types'=>$args->accepted_types,
1801 'return_types'=>$args->return_types
99eaca9d
DC
1802 ));
1803
1804 $return->repositories = array();
1805
1806 if (empty($externallink)) {
1807 $return->externallink = false;
1808 } else {
1809 $return->externallink = true;
1810 }
1811
99eaca9d
DC
1812 // provided by form element
1813 $return->accepted_types = $ft->get_extensions($args->accepted_types);
1814 foreach ($repositories as $repository) {
1815 $meta = $repository->get_meta();
1816 $return->repositories[$repository->id] = $meta;
1817 }
1818 return $return;
e189ec00 1819}
8e0946bf
DC
1820
1821/**
1822 * The plugins should be enabled by defaulted once moodle installed
1823 *
1824 * @global object $OUTPUT
1825 *
1826 * @return boolean
1827 */
1828function repository_setup_default_plugins() {
1829 global $OUTPUT;
1830 //if the plugin type has no multiple instance (e.g. has no instance option name)
1831 //repository_type::create will create an instance automatically
1832 $local_plugin = new repository_type('local', array(), true);
1833 $local_plugin_id = $local_plugin->create(true);
1834 $upload_plugin = new repository_type('upload', array(), true);
1835 $upload_plugin_id = $upload_plugin->create(true);
1836 if (is_int($local_plugin_id) or is_int($upload_plugin_id)) {
1837 echo $OUTPUT->box(get_string('setupdefaultplugins', 'repository'));
1838 }
1839 return true;
1840}