MDL-29406 fix greedy config settings cleanup
[moodle.git] / repository / lib.php
blobafc7d12a8de47d5944e8f43b7128e4bd6b5f1b35
1 <?php
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.
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/>.
19 /**
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
23 * @since 2.0
24 * @package core
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
30 require_once(dirname(dirname(__FILE__)) . '/config.php');
31 require_once($CFG->libdir . '/filelib.php');
32 require_once($CFG->libdir . '/formslib.php');
34 define('FILE_EXTERNAL', 1);
35 define('FILE_INTERNAL', 2);
36 define('RENAME_SUFFIX', '_2');
38 /**
39 * This class is used to manage repository plugins
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.
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
49 * - when you delete a repository, all instances are deleted, and general
50 * options are also deleted from database
51 * - When you create a type for a plugin that can't have multiple instances, a
52 * instance is automatically created.
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
59 class repository_type {
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
67 private $_typename;
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
77 private $_options;
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
85 private $_visible;
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
93 private $_sortorder;
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)
99 * @param objet $context - context
100 * @return boolean
102 public function get_contextvisibility($context) {
103 global $USER;
105 if ($context->contextlevel == CONTEXT_COURSE) {
106 return $this->_options['enablecourseinstances'];
109 if ($context->contextlevel == CONTEXT_USER) {
110 return $this->_options['enableuserinstances'];
113 //the context is SITE
114 return true;
120 * repository_type constructor
121 * @global object $CFG
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)
127 public function __construct($typename = '', $typeoptions = array(), $visible = true, $sortorder = 0) {
128 global $CFG;
130 //set type attributs
131 $this->_typename = $typename;
132 $this->_visible = $visible;
133 $this->_sortorder = $sortorder;
135 //set options attribut
136 $this->_options = array();
137 $options = repository::static_function($typename, 'get_type_option_names');
138 //check that the type can be setup
139 if (!empty($options)) {
140 //set the type options
141 foreach ($options as $config) {
142 if (array_key_exists($config, $typeoptions)) {
143 $this->_options[$config] = $typeoptions[$config];
148 //retrieve visibility from option
149 if (array_key_exists('enablecourseinstances',$typeoptions)) {
150 $this->_options['enablecourseinstances'] = $typeoptions['enablecourseinstances'];
151 } else {
152 $this->_options['enablecourseinstances'] = 0;
155 if (array_key_exists('enableuserinstances',$typeoptions)) {
156 $this->_options['enableuserinstances'] = $typeoptions['enableuserinstances'];
157 } else {
158 $this->_options['enableuserinstances'] = 0;
164 * Get the type name (no whitespace)
165 * For a human readable name, use get_readablename()
166 * @return String the type name
168 public function get_typename() {
169 return $this->_typename;
173 * Return a human readable and user-friendly type name
174 * @return string user-friendly type name
176 public function get_readablename() {
177 return get_string('pluginname','repository_'.$this->_typename);
181 * Return general options
182 * @return array the general options
184 public function get_options() {
185 return $this->_options;
189 * Return visibility
190 * @return boolean
192 public function get_visible() {
193 return $this->_visible;
197 * Return order / position of display in the file picker
198 * @return integer
200 public function get_sortorder() {
201 return $this->_sortorder;
205 * Create a repository type (the type name must not already exist)
206 * @param boolean throw exception?
207 * @return mixed return int if create successfully, return false if
208 * any errors
209 * @global object $DB
211 public function create($silent = false) {
212 global $DB;
214 //check that $type has been set
215 $timmedtype = trim($this->_typename);
216 if (empty($timmedtype)) {
217 throw new repository_exception('emptytype', 'repository');
220 //set sortorder as the last position in the list
221 if (!isset($this->_sortorder) || $this->_sortorder == 0 ) {
222 $sql = "SELECT MAX(sortorder) FROM {repository}";
223 $this->_sortorder = 1 + $DB->get_field_sql($sql);
226 //only create a new type if it doesn't already exist
227 $existingtype = $DB->get_record('repository', array('type'=>$this->_typename));
228 if (!$existingtype) {
229 //create the type
230 $newtype = new stdClass();
231 $newtype->type = $this->_typename;
232 $newtype->visible = $this->_visible;
233 $newtype->sortorder = $this->_sortorder;
234 $plugin_id = $DB->insert_record('repository', $newtype);
235 //save the options in DB
236 $this->update_options();
238 $instanceoptionnames = repository::static_function($this->_typename, 'get_instance_option_names');
240 //if the plugin type has no multiple instance (e.g. has no instance option name) so it wont
241 //be possible for the administrator to create a instance
242 //in this case we need to create an instance
243 if (empty($instanceoptionnames)) {
244 $instanceoptions = array();
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'];
254 repository::static_function($this->_typename, 'create', $this->_typename, 0, get_system_context(), $instanceoptions);
256 //run plugin_init function
257 if (!repository::static_function($this->_typename, 'plugin_init')) {
258 if (!$silent) {
259 throw new repository_exception('cannotinitplugin', 'repository');
263 if(!empty($plugin_id)) {
264 // return plugin_id if create successfully
265 return $plugin_id;
266 } else {
267 return false;
270 } else {
271 if (!$silent) {
272 throw new repository_exception('existingrepository', 'repository');
274 // If plugin existed, return false, tell caller no new plugins were created.
275 return false;
281 * Update plugin options into the config_plugin table
282 * @param array $options
283 * @return boolean
285 public function update_options($options = null) {
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));
298 unset($options['pluginname']);
301 if (!empty($options)) {
302 $this->_options = $options;
305 foreach ($this->_options as $name => $value) {
306 set_config($name, $value, $this->_typename);
309 return true;
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
321 private function update_visible($visible = null) {
322 global $DB;
324 if (!empty($visible)) {
325 $this->_visible = $visible;
327 else if (!isset($this->_visible)) {
328 throw new repository_exception('updateemptyvisible', 'repository');
331 return $DB->set_field('repository', 'visible', $this->_visible, array('type'=>$this->_typename));
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
343 private function update_sortorder($sortorder = null) {
344 global $DB;
346 if (!empty($sortorder) && $sortorder!=0) {
347 $this->_sortorder = $sortorder;
349 //if sortorder is not set, we set it as the ;ast position in the list
350 else if (!isset($this->_sortorder) || $this->_sortorder == 0 ) {
351 $sql = "SELECT MAX(sortorder) FROM {repository}";
352 $this->_sortorder = 1 + $DB->get_field_sql($sql);
355 return $DB->set_field('repository', 'sortorder', $this->_sortorder, array('type'=>$this->_typename));
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"
368 public function move_order($move) {
369 global $DB;
371 $types = repository::get_types(); // retrieve all types
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) {
377 $indice = $i;
379 $i++;
382 /// retrieve adjacent indice
383 switch ($move) {
384 case "up":
385 $adjacentindice = $indice - 1;
386 break;
387 case "down":
388 $adjacentindice = $indice + 1;
389 break;
390 default:
391 throw new repository_exception('movenotdefined', 'repository');
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.
398 if ($adjacentindice>=0 && !empty($types[$adjacentindice])) {
399 $DB->set_field('repository', 'sortorder', $this->_sortorder, array('type'=>$types[$adjacentindice]->get_typename()));
400 $this->update_sortorder($types[$adjacentindice]->get_sortorder());
405 * 1. Change visibility to the value chosen
407 * 2. Update the type
408 * @return boolean
410 public function update_visibility($visible = null) {
411 if (is_bool($visible)) {
412 $this->_visible = $visible;
413 } else {
414 $this->_visible = !$this->_visible;
416 return $this->update_visible();
421 * Delete a repository_type (general options are removed from config_plugin
422 * table, and all instances are deleted)
423 * @global object $DB
424 * @return boolean
426 public function delete() {
427 global $DB;
429 //delete all instances of this type
430 $params = array();
431 $params['context'] = array();
432 $params['onlyvisible'] = false;
433 $params['type'] = $this->_typename;
434 $instances = repository::get_instances($params);
435 foreach ($instances as $instance) {
436 $instance->delete();
439 //delete all general options
440 foreach ($this->_options as $name => $value) {
441 set_config($name, null, $this->_typename);
444 return $DB->delete_records('repository', array('type' => $this->_typename));
449 * This is the base class of the repository class
451 * To use repository plugin, see:
452 * http://docs.moodle.org/dev/Repository_How_to_Create_Plugin
453 * class repository is an abstract class, some functions must be implemented in subclass.
454 * See an example: repository/boxnet/lib.php
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();
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
472 abstract class repository {
473 // $disabled can be set to true to disable a plugin by force
474 // example: self::$disabled = true
475 public $disabled = false;
476 public $id;
477 /** @var object current context */
478 public $context;
479 public $options;
480 public $readonly;
481 public $returntypes;
482 /** @var object repository instance database record */
483 public $instance;
485 * 1. Initialize context and options
486 * 2. Accept necessary parameters
488 * @param integer $repositoryid repository instance id
489 * @param integer|object a context id or context object
490 * @param array $options repository options
492 public function __construct($repositoryid, $context = SYSCONTEXTID, $options = array(), $readonly = 0) {
493 global $DB;
494 $this->id = $repositoryid;
495 if (is_object($context)) {
496 $this->context = $context;
497 } else {
498 $this->context = get_context_instance_by_id($context);
500 $this->instance = $DB->get_record('repository_instances', array('id'=>$this->id));
501 $this->readonly = $readonly;
502 $this->options = array();
504 if (is_array($options)) {
505 $options = array_merge($this->get_option(), $options);
506 } else {
507 $options = $this->get_option();
509 foreach ($options as $n => $v) {
510 $this->options[$n] = $v;
512 $this->name = $this->get_name();
513 $this->returntypes = $this->supported_returntypes();
514 $this->super_called = true;
518 * Get a repository type object by a given type name.
519 * @global object $DB
520 * @param string $typename the repository type name
521 * @return repository_type|bool
523 public static function get_type_by_typename($typename) {
524 global $DB;
526 if (!$record = $DB->get_record('repository',array('type' => $typename))) {
527 return false;
530 return new repository_type($typename, (array)get_config($typename), $record->visible, $record->sortorder);
534 * Get the repository type by a given repository type id.
535 * @global object $DB
536 * @param int $id the type id
537 * @return object
539 public static function get_type_by_id($id) {
540 global $DB;
542 if (!$record = $DB->get_record('repository',array('id' => $id))) {
543 return false;
546 return new repository_type($record->type, (array)get_config($record->type), $record->visible, $record->sortorder);
550 * Return all repository types ordered by sortorder field
551 * first repository type in returnedarray[0], second repository type in returnedarray[1], ...
552 * @global object $DB
553 * @global object $CFG
554 * @param boolean $visible can return types by visiblity, return all types if null
555 * @return array Repository types
557 public static function get_types($visible=null) {
558 global $DB, $CFG;
560 $types = array();
561 $params = null;
562 if (!empty($visible)) {
563 $params = array('visible' => $visible);
565 if ($records = $DB->get_records('repository',$params,'sortorder')) {
566 foreach($records as $type) {
567 if (file_exists($CFG->dirroot . '/repository/'. $type->type .'/lib.php')) {
568 $types[] = new repository_type($type->type, (array)get_config($type->type), $type->visible, $type->sortorder);
573 return $types;
577 * To check if the context id is valid
578 * @global object $USER
579 * @param int $contextid
580 * @return boolean
582 public static function check_capability($contextid, $instance) {
583 $context = get_context_instance_by_id($contextid);
584 $capability = has_capability('repository/'.$instance->type.':view', $context);
585 if (!$capability) {
586 throw new repository_exception('nopermissiontoaccess', 'repository');
591 * Check if file already exists in draft area
593 * @param int $itemid
594 * @param string $filepath
595 * @param string $filename
596 * @return boolean
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;
610 * Does this repository used to browse moodle files?
612 * @return boolean
614 public function has_moodle_files() {
615 return false;
618 * This function is used to copy a moodle file to draft area
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
628 public function copy_to_area($encoded, $draftitemid, $new_filepath, $new_filename) {
629 global $USER, $DB;
631 if ($this->has_moodle_files() == false) {
632 throw new coding_exception('Only repository used to browse moodle files can use copy_to_area');
635 $browser = get_file_browser();
636 $params = unserialize(base64_decode($encoded));
637 $user_context = get_context_instance(CONTEXT_USER, $USER->id);
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);;
643 $filearea = clean_param($params['filearea'], PARAM_ALPHAEXT);
644 $component = clean_param($params['component'], PARAM_ALPHAEXT);
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);
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;
678 * Get unused filename by appending suffix
680 * @param int $itemid
681 * @param string $filepath
682 * @param string $filename
683 * @return string
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);
691 return $filename;
695 * Append a suffix to filename
697 * @param string $filename
698 * @return string
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'];
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
715 public static function get_editable_types($context = null) {
717 if (empty($context)) {
718 $context = get_system_context();
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)) {
726 if ($type->get_contextvisibility($context)) {
727 $editabletypes[]=$type;
731 return $editabletypes;
735 * Return repository instances
736 * @global object $DB
737 * @global object $CFG
738 * @global object $USER
740 * @param array $args Array containing the following keys:
741 * currentcontext
742 * context
743 * onlyvisible
744 * type
745 * accepted_types
746 * return_types
747 * userid
749 * @return array repository instances
751 public static function get_instances($args = array()) {
752 global $DB, $CFG, $USER;
754 if (isset($args['currentcontext'])) {
755 $current_context = $args['currentcontext'];
756 } else {
757 $current_context = null;
760 if (!empty($args['context'])) {
761 $contexts = $args['context'];
762 } else {
763 $contexts = array();
766 $onlyvisible = isset($args['onlyvisible']) ? $args['onlyvisible'] : true;
767 $returntypes = isset($args['return_types']) ? $args['return_types'] : 3;
768 $type = isset($args['type']) ? $args['type'] : null;
770 $params = array();
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 ";
775 if (!empty($args['disable_types']) && is_array($args['disable_types'])) {
776 list($types, $p) = $DB->get_in_or_equal($args['disable_types'], SQL_PARAMS_QM, 'param', false);
777 $sql .= " AND r.type $types";
778 $params = array_merge($params, $p);
781 if (!empty($args['userid']) && is_numeric($args['userid'])) {
782 $sql .= " AND (i.userid = 0 or i.userid = ?)";
783 $params[] = $args['userid'];
786 foreach ($contexts as $context) {
787 if (empty($firstcontext)) {
788 $firstcontext = true;
789 $sql .= " AND ((i.contextid = ?)";
790 } else {
791 $sql .= " OR (i.contextid = ?)";
793 $params[] = $context->id;
796 if (!empty($firstcontext)) {
797 $sql .=')';
800 if ($onlyvisible == true) {
801 $sql .= " AND (r.visible = 1)";
804 if (isset($type)) {
805 $sql .= " AND (r.type = ?)";
806 $params[] = $type;
808 $sql .= " ORDER BY r.sortorder, i.name";
810 if (!$records = $DB->get_records_sql($sql, $params)) {
811 $records = array();
814 $repositories = array();
815 $ft = new filetype_parser();
816 if (isset($args['accepted_types'])) {
817 $accepted_types = $args['accepted_types'];
818 } else {
819 $accepted_types = '*';
821 foreach ($records as $record) {
822 if (!file_exists($CFG->dirroot . '/repository/'. $record->repositorytype.'/lib.php')) {
823 continue;
825 require_once($CFG->dirroot . '/repository/'. $record->repositorytype.'/lib.php');
826 $options['visible'] = $record->visible;
827 $options['type'] = $record->repositorytype;
828 $options['typeid'] = $record->typeid;
829 // tell instance what file types will be accepted by file picker
830 $classname = 'repository_' . $record->repositorytype;
832 $repository = new $classname($record->id, $record->contextid, $options, $record->readonly);
834 $is_supported = true;
836 if (empty($repository->super_called)) {
837 // to make sure the super construct is called
838 debugging('parent::__construct must be called by '.$record->repositorytype.' plugin.');
839 } else {
840 // check mimetypes
841 if ($accepted_types !== '*' and $repository->supported_filetypes() !== '*') {
842 $accepted_types = $ft->get_extensions($accepted_types);
843 $supported_filetypes = $ft->get_extensions($repository->supported_filetypes());
845 $is_supported = false;
846 foreach ($supported_filetypes as $type) {
847 if (in_array($type, $accepted_types)) {
848 $is_supported = true;
853 // check return values
854 if ($returntypes !== 3 and $repository->supported_returntypes() !== 3) {
855 $type = $repository->supported_returntypes();
856 if ($type & $returntypes) {
858 } else {
859 $is_supported = false;
863 if (!$onlyvisible || ($repository->is_visible() && !$repository->disabled)) {
864 // check capability in current context
865 if (!empty($current_context)) {
866 $capability = has_capability('repository/'.$record->repositorytype.':view', $current_context);
867 } else {
868 $capability = has_capability('repository/'.$record->repositorytype.':view', get_system_context());
870 if ($record->repositorytype == 'coursefiles') {
871 // coursefiles plugin needs managefiles permission
872 $capability = $capability && has_capability('moodle/course:managefiles', $current_context);
874 if ($is_supported && $capability) {
875 $repositories[$repository->id] = $repository;
880 return $repositories;
884 * Get single repository instance
885 * @global object $DB
886 * @global object $CFG
887 * @param integer $id repository id
888 * @return object repository instance
890 public static function get_instance($id) {
891 global $DB, $CFG;
892 $sql = "SELECT i.*, r.type AS repositorytype, r.visible
893 FROM {repository} r
894 JOIN {repository_instances} i ON i.typeid = r.id
895 WHERE i.id = ?";
897 if (!$instance = $DB->get_record_sql($sql, array($id))) {
898 return false;
900 require_once($CFG->dirroot . '/repository/'. $instance->repositorytype.'/lib.php');
901 $classname = 'repository_' . $instance->repositorytype;
902 $options['typeid'] = $instance->typeid;
903 $options['type'] = $instance->repositorytype;
904 $options['name'] = $instance->name;
905 $obj = new $classname($instance->id, $instance->contextid, $options, $instance->readonly);
906 if (empty($obj->super_called)) {
907 debugging('parent::__construct must be called by '.$classname.' plugin.');
909 return $obj;
913 * Call a static function. Any additional arguments than plugin and function will be passed through.
914 * @global object $CFG
915 * @param string $plugin
916 * @param string $function
917 * @return mixed
919 public static function static_function($plugin, $function) {
920 global $CFG;
922 //check that the plugin exists
923 $typedirectory = $CFG->dirroot . '/repository/'. $plugin . '/lib.php';
924 if (!file_exists($typedirectory)) {
925 //throw new repository_exception('invalidplugin', 'repository');
926 return false;
929 $pname = null;
930 if (is_object($plugin) || is_array($plugin)) {
931 $plugin = (object)$plugin;
932 $pname = $plugin->name;
933 } else {
934 $pname = $plugin;
937 $args = func_get_args();
938 if (count($args) <= 2) {
939 $args = array();
940 } else {
941 array_shift($args);
942 array_shift($args);
945 require_once($typedirectory);
946 return call_user_func_array(array('repository_' . $plugin, $function), $args);
950 * Scan file, throws exception in case of infected file.
952 * Please note that the scanning engine must be able to access the file,
953 * permissions of the file are not modified here!
955 * @static
956 * @param string $thefile
957 * @param string $filename name of the file
958 * @param bool $deleteinfected
959 * @return void
961 public static function antivir_scan_file($thefile, $filename, $deleteinfected) {
962 global $CFG;
964 if (!is_readable($thefile)) {
965 // this should not happen
966 return;
969 if (empty($CFG->runclamonupload) or empty($CFG->pathtoclam)) {
970 // clam not enabled
971 return;
974 $CFG->pathtoclam = trim($CFG->pathtoclam);
976 if (!file_exists($CFG->pathtoclam) or !is_executable($CFG->pathtoclam)) {
977 // misconfigured clam - use the old notification for now
978 require("$CFG->libdir/uploadlib.php");
979 $notice = get_string('clamlost', 'moodle', $CFG->pathtoclam);
980 clam_message_admins($notice);
981 return;
984 // do NOT mess with permissions here, the calling party is responsible for making
985 // sure the scanner engine can access the files!
987 // execute test
988 $cmd = escapeshellcmd($CFG->pathtoclam).' --stdout '.escapeshellarg($thefile);
989 exec($cmd, $output, $return);
991 if ($return == 0) {
992 // perfect, no problem found
993 return;
995 } else if ($return == 1) {
996 // infection found
997 if ($deleteinfected) {
998 unlink($thefile);
1000 throw new moodle_exception('virusfounduser', 'moodle', '', array('filename'=>$filename));
1002 } else {
1003 //unknown problem
1004 require("$CFG->libdir/uploadlib.php");
1005 $notice = get_string('clamfailed', 'moodle', get_clam_error_code($return));
1006 $notice .= "\n\n". implode("\n", $output);
1007 clam_message_admins($notice);
1008 if ($CFG->clamfailureonupload === 'actlikevirus') {
1009 if ($deleteinfected) {
1010 unlink($thefile);
1012 throw new moodle_exception('virusfounduser', 'moodle', '', array('filename'=>$filename));
1013 } else {
1014 return;
1020 * Move file from download folder to file pool using FILE API
1021 * @global object $DB
1022 * @global object $CFG
1023 * @global object $USER
1024 * @global object $OUTPUT
1025 * @param string $thefile file path in download folder
1026 * @param object $record
1027 * @return array containing the following keys:
1028 * icon
1029 * file
1030 * id
1031 * url
1033 public static function move_to_filepool($thefile, $record) {
1034 global $DB, $CFG, $USER, $OUTPUT;
1036 // scan for viruses if possible, throws exception if problem found
1037 self::antivir_scan_file($thefile, $record->filename, empty($CFG->repository_no_delete)); //TODO: MDL-28637 this repository_no_delete is a bloody hack!
1039 if ($record->filepath !== '/') {
1040 $record->filepath = trim($record->filepath, '/');
1041 $record->filepath = '/'.$record->filepath.'/';
1043 $context = get_context_instance(CONTEXT_USER, $USER->id);
1044 $now = time();
1046 $record->contextid = $context->id;
1047 $record->component = 'user';
1048 $record->filearea = 'draft';
1049 $record->timecreated = $now;
1050 $record->timemodified = $now;
1051 $record->userid = $USER->id;
1052 $record->mimetype = mimeinfo('type', $thefile);
1053 if(!is_numeric($record->itemid)) {
1054 $record->itemid = 0;
1056 $fs = get_file_storage();
1057 if ($existingfile = $fs->get_file($context->id, $record->component, $record->filearea, $record->itemid, $record->filepath, $record->filename)) {
1058 $draftitemid = $record->itemid;
1059 $new_filename = repository::get_unused_filename($draftitemid, $record->filepath, $record->filename);
1060 $old_filename = $record->filename;
1061 // create a tmp file
1062 $record->filename = $new_filename;
1063 $newfile = $fs->create_file_from_pathname($record, $thefile);
1064 $event = array();
1065 $event['event'] = 'fileexists';
1066 $event['newfile'] = new stdClass;
1067 $event['newfile']->filepath = $record->filepath;
1068 $event['newfile']->filename = $new_filename;
1069 $event['newfile']->url = moodle_url::make_draftfile_url($draftitemid, $record->filepath, $new_filename)->out();
1071 $event['existingfile'] = new stdClass;
1072 $event['existingfile']->filepath = $record->filepath;
1073 $event['existingfile']->filename = $old_filename;
1074 $event['existingfile']->url = moodle_url::make_draftfile_url($draftitemid, $record->filepath, $old_filename)->out();;
1075 return $event;
1077 if ($file = $fs->create_file_from_pathname($record, $thefile)) {
1078 if (empty($CFG->repository_no_delete)) {
1079 $delete = unlink($thefile);
1080 unset($CFG->repository_no_delete);
1082 return array(
1083 'url'=>moodle_url::make_draftfile_url($file->get_itemid(), $file->get_filepath(), $file->get_filename())->out(),
1084 'id'=>$file->get_itemid(),
1085 'file'=>$file->get_filename(),
1086 'icon' => $OUTPUT->pix_url(file_extension_icon($thefile, 32))->out(),
1088 } else {
1089 return null;
1094 * Builds a tree of files This function is
1095 * then called recursively.
1097 * @param $fileinfo an object returned by file_browser::get_file_info()
1098 * @param $search searched string
1099 * @param $dynamicmode bool no recursive call is done when in dynamic mode
1100 * @param $list - the array containing the files under the passed $fileinfo
1101 * @returns int the number of files found
1103 * todo: take $search into account, and respect a threshold for dynamic loading
1105 public static function build_tree($fileinfo, $search, $dynamicmode, &$list) {
1106 global $CFG, $OUTPUT;
1108 $filecount = 0;
1109 $children = $fileinfo->get_children();
1111 foreach ($children as $child) {
1112 $filename = $child->get_visible_name();
1113 $filesize = $child->get_filesize();
1114 $filesize = $filesize ? display_size($filesize) : '';
1115 $filedate = $child->get_timemodified();
1116 $filedate = $filedate ? userdate($filedate) : '';
1117 $filetype = $child->get_mimetype();
1119 if ($child->is_directory()) {
1120 $path = array();
1121 $level = $child->get_parent();
1122 while ($level) {
1123 $params = $level->get_params();
1124 $path[] = array($params['filepath'], $level->get_visible_name());
1125 $level = $level->get_parent();
1128 $tmp = array(
1129 'title' => $child->get_visible_name(),
1130 'size' => 0,
1131 'date' => $filedate,
1132 'path' => array_reverse($path),
1133 'thumbnail' => $OUTPUT->pix_url('f/folder-32')
1136 //if ($dynamicmode && $child->is_writable()) {
1137 // $tmp['children'] = array();
1138 //} else {
1139 // if folder name matches search, we send back all files contained.
1140 $_search = $search;
1141 if ($search && stristr($tmp['title'], $search) !== false) {
1142 $_search = false;
1144 $tmp['children'] = array();
1145 $_filecount = repository::build_tree($child, $_search, $dynamicmode, $tmp['children']);
1146 if ($search && $_filecount) {
1147 $tmp['expanded'] = 1;
1152 if (!$search || $_filecount || (stristr($tmp['title'], $search) !== false)) {
1153 $filecount += $_filecount;
1154 $list[] = $tmp;
1157 } else { // not a directory
1158 // skip the file, if we're in search mode and it's not a match
1159 if ($search && (stristr($filename, $search) === false)) {
1160 continue;
1162 $params = $child->get_params();
1163 $source = serialize(array($params['contextid'], $params['component'], $params['filearea'], $params['itemid'], $params['filepath'], $params['filename']));
1164 $list[] = array(
1165 'title' => $filename,
1166 'size' => $filesize,
1167 'date' => $filedate,
1168 //'source' => $child->get_url(),
1169 'source' => base64_encode($source),
1170 'thumbnail'=>$OUTPUT->pix_url(file_extension_icon($filename, 32)),
1172 $filecount++;
1176 return $filecount;
1181 * Display a repository instance list (with edit/delete/create links)
1182 * @global object $CFG
1183 * @global object $USER
1184 * @global object $OUTPUT
1185 * @param object $context the context for which we display the instance
1186 * @param string $typename if set, we display only one type of instance
1188 public static function display_instances_list($context, $typename = null) {
1189 global $CFG, $USER, $OUTPUT;
1191 $output = $OUTPUT->box_start('generalbox');
1192 //if the context is SYSTEM, so we call it from administration page
1193 $admin = ($context->id == SYSCONTEXTID) ? true : false;
1194 if ($admin) {
1195 $baseurl = new moodle_url('/'.$CFG->admin.'/repositoryinstance.php', array('sesskey'=>sesskey()));
1196 $output .= $OUTPUT->heading(get_string('siteinstances', 'repository'));
1197 } else {
1198 $baseurl = new moodle_url('/repository/manage_instances.php', array('contextid'=>$context->id, 'sesskey'=>sesskey()));
1200 $url = $baseurl;
1202 $namestr = get_string('name');
1203 $pluginstr = get_string('plugin', 'repository');
1204 $settingsstr = get_string('settings');
1205 $deletestr = get_string('delete');
1206 //retrieve list of instances. In administration context we want to display all
1207 //instances of a type, even if this type is not visible. In course/user context we
1208 //want to display only visible instances, but for every type types. The repository::get_instances()
1209 //third parameter displays only visible type.
1210 $params = array();
1211 $params['context'] = array($context, get_system_context());
1212 $params['currentcontext'] = $context;
1213 $params['onlyvisible'] = !$admin;
1214 $params['type'] = $typename;
1215 $instances = repository::get_instances($params);
1216 $instancesnumber = count($instances);
1217 $alreadyplugins = array();
1219 $table = new html_table();
1220 $table->head = array($namestr, $pluginstr, $settingsstr, $deletestr);
1221 $table->align = array('left', 'left', 'center','center');
1222 $table->data = array();
1224 $updowncount = 1;
1226 foreach ($instances as $i) {
1227 $settings = '';
1228 $delete = '';
1230 $type = repository::get_type_by_id($i->options['typeid']);
1232 if ($type->get_contextvisibility($context)) {
1233 if (!$i->readonly) {
1235 $url->param('type', $i->options['type']);
1236 $url->param('edit', $i->id);
1237 $settings .= html_writer::link($url, $settingsstr);
1239 $url->remove_params('edit');
1240 $url->param('delete', $i->id);
1241 $delete .= html_writer::link($url, $deletestr);
1243 $url->remove_params('type');
1247 $type = repository::get_type_by_id($i->options['typeid']);
1248 $table->data[] = array($i->name, $type->get_readablename(), $settings, $delete);
1250 //display a grey row if the type is defined as not visible
1251 if (isset($type) && !$type->get_visible()) {
1252 $table->rowclasses[] = 'dimmed_text';
1253 } else {
1254 $table->rowclasses[] = '';
1257 if (!in_array($i->name, $alreadyplugins)) {
1258 $alreadyplugins[] = $i->name;
1261 $output .= html_writer::table($table);
1262 $instancehtml = '<div>';
1263 $addable = 0;
1265 //if no type is set, we can create all type of instance
1266 if (!$typename) {
1267 $instancehtml .= '<h3>';
1268 $instancehtml .= get_string('createrepository', 'repository');
1269 $instancehtml .= '</h3><ul>';
1270 $types = repository::get_editable_types($context);
1271 foreach ($types as $type) {
1272 if (!empty($type) && $type->get_visible()) {
1273 $instanceoptionnames = repository::static_function($type->get_typename(), 'get_instance_option_names');
1274 if (!empty($instanceoptionnames)) {
1275 $baseurl->param('new', $type->get_typename());
1276 $instancehtml .= '<li><a href="'.$baseurl->out().'">'.get_string('createxxinstance', 'repository', get_string('pluginname', 'repository_'.$type->get_typename())). '</a></li>';
1277 $baseurl->remove_params('new');
1278 $addable++;
1282 $instancehtml .= '</ul>';
1284 } else {
1285 $instanceoptionnames = repository::static_function($typename, 'get_instance_option_names');
1286 if (!empty($instanceoptionnames)) { //create a unique type of instance
1287 $addable = 1;
1288 $baseurl->param('new', $typename);
1289 $instancehtml .= "<form action='".$baseurl->out()."' method='post'>
1290 <p><input type='submit' value='".get_string('createinstance', 'repository')."'/></p>
1291 </form>";
1292 $baseurl->remove_params('new');
1296 if ($addable) {
1297 $instancehtml .= '</div>';
1298 $output .= $instancehtml;
1301 $output .= $OUTPUT->box_end();
1303 //print the list + creation links
1304 print($output);
1308 * Decide where to save the file, can be overwriten by subclass
1309 * @param string filename
1311 public function prepare_file($filename) {
1312 global $CFG;
1313 if (!file_exists($CFG->dataroot.'/temp/download')) {
1314 mkdir($CFG->dataroot.'/temp/download/', $CFG->directorypermissions, true);
1316 if (is_dir($CFG->dataroot.'/temp/download')) {
1317 $dir = $CFG->dataroot.'/temp/download/';
1319 if (empty($filename)) {
1320 $filename = uniqid('repo').'_'.time().'.tmp';
1322 if (file_exists($dir.$filename)) {
1323 $filename = uniqid('m').$filename;
1325 return $dir.$filename;
1329 * Return file URL, for most plugins, the parameter is the original
1330 * url, but some plugins use a file id, so we need this function to
1331 * convert file id to original url.
1333 * @param string $url the url of file
1334 * @return string
1336 public function get_link($url) {
1337 return $url;
1341 * Download a file, this function can be overridden by
1342 * subclass.
1344 * @global object $CFG
1345 * @param string $url the url of file
1346 * @param string $filename save location
1347 * @return string the location of the file
1348 * @see curl package
1350 public function get_file($url, $filename = '') {
1351 global $CFG;
1352 $path = $this->prepare_file($filename);
1353 $fp = fopen($path, 'w');
1354 $c = new curl;
1355 $c->download(array(array('url'=>$url, 'file'=>$fp)));
1356 return array('path'=>$path, 'url'=>$url);
1360 * Return is the instance is visible
1361 * (is the type visible ? is the context enable ?)
1362 * @return boolean
1364 public function is_visible() {
1365 $type = repository::get_type_by_id($this->options['typeid']);
1366 $instanceoptions = repository::static_function($type->get_typename(), 'get_instance_option_names');
1368 if ($type->get_visible()) {
1369 //if the instance is unique so it's visible, otherwise check if the instance has a enabled context
1370 if (empty($instanceoptions) || $type->get_contextvisibility($this->context)) {
1371 return true;
1375 return false;
1379 * Return the name of this instance, can be overridden.
1380 * @global object $DB
1381 * @return string
1383 public function get_name() {
1384 global $DB;
1385 if ( $name = $this->instance->name ) {
1386 return $name;
1387 } else {
1388 return get_string('pluginname', 'repository_' . $this->options['type']);
1393 * what kind of files will be in this repository?
1394 * @return array return '*' means this repository support any files, otherwise
1395 * return mimetypes of files, it can be an array
1397 public function supported_filetypes() {
1398 // return array('text/plain', 'image/gif');
1399 return '*';
1403 * does it return a file url or a item_id
1404 * @return string
1406 public function supported_returntypes() {
1407 return (FILE_INTERNAL | FILE_EXTERNAL);
1411 * Provide repository instance information for Ajax
1412 * @global object $CFG
1413 * @return object
1415 final public function get_meta() {
1416 global $CFG, $OUTPUT;
1417 $ft = new filetype_parser;
1418 $meta = new stdClass();
1419 $meta->id = $this->id;
1420 $meta->name = $this->get_name();
1421 $meta->type = $this->options['type'];
1422 $meta->icon = $OUTPUT->pix_url('icon', 'repository_'.$meta->type)->out(false);
1423 $meta->supported_types = $ft->get_extensions($this->supported_filetypes());
1424 $meta->return_types = $this->supported_returntypes();
1425 return $meta;
1429 * Create an instance for this plug-in
1430 * @global object $CFG
1431 * @global object $DB
1432 * @param string $type the type of the repository
1433 * @param integer $userid the user id
1434 * @param object $context the context
1435 * @param array $params the options for this instance
1436 * @param integer $readonly whether to create it readonly or not (defaults to not)
1437 * @return mixed
1439 public static function create($type, $userid, $context, $params, $readonly=0) {
1440 global $CFG, $DB;
1441 $params = (array)$params;
1442 require_once($CFG->dirroot . '/repository/'. $type . '/lib.php');
1443 $classname = 'repository_' . $type;
1444 if ($repo = $DB->get_record('repository', array('type'=>$type))) {
1445 $record = new stdClass();
1446 $record->name = $params['name'];
1447 $record->typeid = $repo->id;
1448 $record->timecreated = time();
1449 $record->timemodified = time();
1450 $record->contextid = $context->id;
1451 $record->readonly = $readonly;
1452 $record->userid = $userid;
1453 $id = $DB->insert_record('repository_instances', $record);
1454 $options = array();
1455 $configs = call_user_func($classname . '::get_instance_option_names');
1456 if (!empty($configs)) {
1457 foreach ($configs as $config) {
1458 if (isset($params[$config])) {
1459 $options[$config] = $params[$config];
1460 } else {
1461 $options[$config] = null;
1466 if (!empty($id)) {
1467 unset($options['name']);
1468 $instance = repository::get_instance($id);
1469 $instance->set_option($options);
1470 return $id;
1471 } else {
1472 return null;
1474 } else {
1475 return null;
1480 * delete a repository instance
1481 * @global object $DB
1482 * @return mixed
1484 final public function delete() {
1485 global $DB;
1486 $DB->delete_records('repository_instances', array('id'=>$this->id));
1487 $DB->delete_records('repository_instance_config', array('instanceid'=>$this->id));
1488 return true;
1492 * Hide/Show a repository
1493 * @global object $DB
1494 * @param string $hide
1495 * @return boolean
1497 final public function hide($hide = 'toggle') {
1498 global $DB;
1499 if ($entry = $DB->get_record('repository', array('id'=>$this->id))) {
1500 if ($hide === 'toggle' ) {
1501 if (!empty($entry->visible)) {
1502 $entry->visible = 0;
1503 } else {
1504 $entry->visible = 1;
1506 } else {
1507 if (!empty($hide)) {
1508 $entry->visible = 0;
1509 } else {
1510 $entry->visible = 1;
1513 return $DB->update_record('repository', $entry);
1515 return false;
1519 * Save settings for repository instance
1520 * $repo->set_option(array('api_key'=>'f2188bde132', 'name'=>'dongsheng'));
1521 * @global object $DB
1522 * @param array $options settings
1523 * @return int Id of the record
1525 public function set_option($options = array()) {
1526 global $DB;
1528 if (!empty($options['name'])) {
1529 $r = new stdClass();
1530 $r->id = $this->id;
1531 $r->name = $options['name'];
1532 $DB->update_record('repository_instances', $r);
1533 unset($options['name']);
1535 foreach ($options as $name=>$value) {
1536 if ($id = $DB->get_field('repository_instance_config', 'id', array('name'=>$name, 'instanceid'=>$this->id))) {
1537 $DB->set_field('repository_instance_config', 'value', $value, array('id'=>$id));
1538 } else {
1539 $config = new stdClass();
1540 $config->instanceid = $this->id;
1541 $config->name = $name;
1542 $config->value = $value;
1543 $DB->insert_record('repository_instance_config', $config);
1546 return true;
1550 * Get settings for repository instance
1551 * @global object $DB
1552 * @param string $config
1553 * @return array Settings
1555 public function get_option($config = '') {
1556 global $DB;
1557 $entries = $DB->get_records('repository_instance_config', array('instanceid'=>$this->id));
1558 $ret = array();
1559 if (empty($entries)) {
1560 return $ret;
1562 foreach($entries as $entry) {
1563 $ret[$entry->name] = $entry->value;
1565 if (!empty($config)) {
1566 if (isset($ret[$config])) {
1567 return $ret[$config];
1568 } else {
1569 return null;
1571 } else {
1572 return $ret;
1576 public function filter(&$value) {
1577 $pass = false;
1578 $accepted_types = optional_param('accepted_types', '', PARAM_RAW);
1579 $ft = new filetype_parser;
1580 //$ext = $ft->get_extensions($this->supported_filetypes());
1581 if (isset($value['children'])) {
1582 $pass = true;
1583 if (!empty($value['children'])) {
1584 $value['children'] = array_filter($value['children'], array($this, 'filter'));
1586 } else {
1587 if ($accepted_types == '*' or empty($accepted_types)
1588 or (is_array($accepted_types) and in_array('*', $accepted_types))) {
1589 $pass = true;
1590 } elseif (is_array($accepted_types)) {
1591 foreach ($accepted_types as $type) {
1592 $extensions = $ft->get_extensions($type);
1593 if (!is_array($extensions)) {
1594 $pass = true;
1595 } else {
1596 foreach ($extensions as $ext) {
1597 if (preg_match('#'.$ext.'$#', $value['title'])) {
1598 $pass = true;
1605 return $pass;
1609 * Given a path, and perhaps a search, get a list of files.
1611 * See details on http://docs.moodle.org/dev/Repository_plugins
1613 * @param string $path, this parameter can
1614 * a folder name, or a identification of folder
1615 * @param string $page, the page number of file list
1616 * @return array the list of files, including meta infomation, containing the following keys
1617 * manage, url to manage url
1618 * client_id
1619 * login, login form
1620 * repo_id, active repository id
1621 * login_btn_action, the login button action
1622 * login_btn_label, the login button label
1623 * total, number of results
1624 * perpage, items per page
1625 * page
1626 * pages, total pages
1627 * issearchresult, is it a search result?
1628 * list, file list
1629 * path, current path and parent path
1631 public function get_listing($path = '', $page = '') {
1635 * Search files in repository
1636 * When doing global search, $search_text will be used as
1637 * keyword.
1639 * @return mixed, see get_listing()
1641 public function search($search_text) {
1642 $list = array();
1643 $list['list'] = array();
1644 return false;
1648 * Logout from repository instance
1649 * By default, this function will return a login form
1651 * @return string
1653 public function logout(){
1654 return $this->print_login();
1658 * To check whether the user is logged in.
1660 * @return boolean
1662 public function check_login(){
1663 return true;
1668 * Show the login screen, if required
1670 public function print_login(){
1671 return $this->get_listing();
1675 * Show the search screen, if required
1676 * @return null
1678 public function print_search() {
1679 $str = '';
1680 $str .= '<input type="hidden" name="repo_id" value="'.$this->id.'" />';
1681 $str .= '<input type="hidden" name="ctx_id" value="'.$this->context->id.'" />';
1682 $str .= '<input type="hidden" name="seekey" value="'.sesskey().'" />';
1683 $str .= '<label>'.get_string('keyword', 'repository').': </label><br/><input name="s" value="" /><br/>';
1684 return $str;
1688 * For oauth like external authentication, when external repository direct user back to moodle,
1689 * this funciton will be called to set up token and token_secret
1691 public function callback() {
1695 * is it possible to do glboal search?
1696 * @return boolean
1698 public function global_search() {
1699 return false;
1703 * Defines operations that happen occasionally on cron
1704 * @return boolean
1706 public function cron() {
1707 return true;
1711 * function which is run when the type is created (moodle administrator add the plugin)
1712 * @return boolean success or fail?
1714 public static function plugin_init() {
1715 return true;
1719 * Edit/Create Admin Settings Moodle form
1720 * @param object $mform Moodle form (passed by reference)
1721 * @param string $classname repository class name
1723 public function type_config_form($mform, $classname = 'repository') {
1724 $instnaceoptions = call_user_func(array($classname, 'get_instance_option_names'), $mform, $classname);
1725 if (empty($instnaceoptions)) {
1726 // this plugin has only one instance
1727 // so we need to give it a name
1728 // it can be empty, then moodle will look for instance name from language string
1729 $mform->addElement('text', 'pluginname', get_string('pluginname', 'repository'), array('size' => '40'));
1730 $mform->addElement('static', 'pluginnamehelp', '', get_string('pluginnamehelp', 'repository'));
1735 * Edit/Create Instance Settings Moodle form
1736 * @param object $mform Moodle form (passed by reference)
1738 public function instance_config_form($mform) {
1742 * Return names of the general options
1743 * By default: no general option name
1744 * @return array
1746 public static function get_type_option_names() {
1747 return array('pluginname');
1751 * Return names of the instance options
1752 * By default: no instance option name
1753 * @return array
1755 public static function get_instance_option_names() {
1756 return array();
1759 public static function instance_form_validation($mform, $data, $errors) {
1760 return $errors;
1763 public function get_short_filename($str, $maxlength) {
1764 if (strlen($str) >= $maxlength) {
1765 return trim(substr($str, 0, $maxlength)).'...';
1766 } else {
1767 return $str;
1772 * Overwrite an existing file
1774 * @param int $itemid
1775 * @param string $filepath
1776 * @param string $filename
1777 * @param string $newfilepath
1778 * @param string $newfilename
1779 * @return boolean
1781 function overwrite_existing_draftfile($itemid, $filepath, $filename, $newfilepath, $newfilename) {
1782 global $USER;
1783 $fs = get_file_storage();
1784 $user_context = get_context_instance(CONTEXT_USER, $USER->id);
1785 if ($file = $fs->get_file($user_context->id, 'user', 'draft', $itemid, $filepath, $filename)) {
1786 if ($tempfile = $fs->get_file($user_context->id, 'user', 'draft', $itemid, $newfilepath, $newfilename)) {
1787 // delete existing file to release filename
1788 $file->delete();
1789 // create new file
1790 $newfile = $fs->create_file_from_storedfile(array('filepath'=>$filepath, 'filename'=>$filename), $tempfile);
1791 // remove temp file
1792 $tempfile->delete();
1793 return true;
1796 return false;
1800 * Delete a temp file from draft area
1802 * @param int $draftitemid
1803 * @param string $filepath
1804 * @param string $filename
1805 * @return boolean
1807 function delete_tempfile_from_draft($draftitemid, $filepath, $filename) {
1808 global $USER;
1809 $fs = get_file_storage();
1810 $user_context = get_context_instance(CONTEXT_USER, $USER->id);
1811 if ($file = $fs->get_file($user_context->id, 'user', 'draft', $draftitemid, $filepath, $filename)) {
1812 $file->delete();
1813 return true;
1814 } else {
1815 return false;
1821 * Exception class for repository api
1823 * @since 2.0
1824 * @package moodlecore
1825 * @subpackage repository
1826 * @copyright 2009 Dongsheng Cai <dongsheng@moodle.com>
1827 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1829 class repository_exception extends moodle_exception {
1833 * This is a class used to define a repository instance form
1835 * @since 2.0
1836 * @package moodlecore
1837 * @subpackage repository
1838 * @copyright 2009 Dongsheng Cai <dongsheng@moodle.com>
1839 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1841 final class repository_instance_form extends moodleform {
1842 protected $instance;
1843 protected $plugin;
1844 protected function add_defaults() {
1845 $mform =& $this->_form;
1846 $strrequired = get_string('required');
1848 $mform->addElement('hidden', 'edit', ($this->instance) ? $this->instance->id : 0);
1849 $mform->setType('edit', PARAM_INT);
1850 $mform->addElement('hidden', 'new', $this->plugin);
1851 $mform->setType('new', PARAM_FORMAT);
1852 $mform->addElement('hidden', 'plugin', $this->plugin);
1853 $mform->setType('plugin', PARAM_SAFEDIR);
1854 $mform->addElement('hidden', 'typeid', $this->typeid);
1855 $mform->setType('typeid', PARAM_INT);
1856 $mform->addElement('hidden', 'contextid', $this->contextid);
1857 $mform->setType('contextid', PARAM_INT);
1859 $mform->addElement('text', 'name', get_string('name'), 'maxlength="100" size="30"');
1860 $mform->addRule('name', $strrequired, 'required', null, 'client');
1863 public function definition() {
1864 global $CFG;
1865 // type of plugin, string
1866 $this->plugin = $this->_customdata['plugin'];
1867 $this->typeid = $this->_customdata['typeid'];
1868 $this->contextid = $this->_customdata['contextid'];
1869 $this->instance = (isset($this->_customdata['instance'])
1870 && is_subclass_of($this->_customdata['instance'], 'repository'))
1871 ? $this->_customdata['instance'] : null;
1873 $mform =& $this->_form;
1875 $this->add_defaults();
1876 //add fields
1877 if (!$this->instance) {
1878 $result = repository::static_function($this->plugin, 'instance_config_form', $mform);
1879 if ($result === false) {
1880 $mform->removeElement('name');
1882 } else {
1883 $data = array();
1884 $data['name'] = $this->instance->name;
1885 if (!$this->instance->readonly) {
1886 $result = $this->instance->instance_config_form($mform);
1887 if ($result === false) {
1888 $mform->removeElement('name');
1890 // and set the data if we have some.
1891 foreach ($this->instance->get_instance_option_names() as $config) {
1892 if (!empty($this->instance->options[$config])) {
1893 $data[$config] = $this->instance->options[$config];
1894 } else {
1895 $data[$config] = '';
1899 $this->set_data($data);
1902 if ($result === false) {
1903 $mform->addElement('cancel');
1904 } else {
1905 $this->add_action_buttons(true, get_string('save','repository'));
1909 public function validation($data) {
1910 global $DB;
1911 $errors = array();
1912 $plugin = $this->_customdata['plugin'];
1913 $instance = (isset($this->_customdata['instance'])
1914 && is_subclass_of($this->_customdata['instance'], 'repository'))
1915 ? $this->_customdata['instance'] : null;
1916 if (!$instance) {
1917 $errors = repository::static_function($plugin, 'instance_form_validation', $this, $data, $errors);
1918 } else {
1919 $errors = $instance->instance_form_validation($this, $data, $errors);
1922 $sql = "SELECT count('x')
1923 FROM {repository_instances} i, {repository} r
1924 WHERE r.type=:plugin AND r.id=i.typeid AND i.name=:name";
1925 if ($DB->count_records_sql($sql, array('name' => $data['name'], 'plugin' => $data['plugin'])) > 1) {
1926 $errors['name'] = get_string('erroruniquename', 'repository');
1929 return $errors;
1934 * This is a class used to define a repository type setting form
1936 * @since 2.0
1937 * @package moodlecore
1938 * @subpackage repository
1939 * @copyright 2009 Dongsheng Cai <dongsheng@moodle.com>
1940 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1942 final class repository_type_form extends moodleform {
1943 protected $instance;
1944 protected $plugin;
1945 protected $action;
1948 * Definition of the moodleform
1949 * @global object $CFG
1951 public function definition() {
1952 global $CFG;
1953 // type of plugin, string
1954 $this->plugin = $this->_customdata['plugin'];
1955 $this->instance = (isset($this->_customdata['instance'])
1956 && is_a($this->_customdata['instance'], 'repository_type'))
1957 ? $this->_customdata['instance'] : null;
1959 $this->action = $this->_customdata['action'];
1960 $this->pluginname = $this->_customdata['pluginname'];
1961 $mform =& $this->_form;
1962 $strrequired = get_string('required');
1964 $mform->addElement('hidden', 'action', $this->action);
1965 $mform->setType('action', PARAM_TEXT);
1966 $mform->addElement('hidden', 'repos', $this->plugin);
1967 $mform->setType('repos', PARAM_SAFEDIR);
1969 // let the plugin add its specific fields
1970 $classname = 'repository_' . $this->plugin;
1971 require_once($CFG->dirroot . '/repository/' . $this->plugin . '/lib.php');
1972 //add "enable course/user instances" checkboxes if multiple instances are allowed
1973 $instanceoptionnames = repository::static_function($this->plugin, 'get_instance_option_names');
1975 $result = call_user_func(array($classname, 'type_config_form'), $mform, $classname);
1977 if (!empty($instanceoptionnames)) {
1978 $sm = get_string_manager();
1979 $component = 'repository';
1980 if ($sm->string_exists('enablecourseinstances', 'repository_' . $this->plugin)) {
1981 $component .= ('_' . $this->plugin);
1983 $mform->addElement('checkbox', 'enablecourseinstances', get_string('enablecourseinstances', $component));
1985 $component = 'repository';
1986 if ($sm->string_exists('enableuserinstances', 'repository_' . $this->plugin)) {
1987 $component .= ('_' . $this->plugin);
1989 $mform->addElement('checkbox', 'enableuserinstances', get_string('enableuserinstances', $component));
1992 // set the data if we have some.
1993 if ($this->instance) {
1994 $data = array();
1995 $option_names = call_user_func(array($classname,'get_type_option_names'));
1996 if (!empty($instanceoptionnames)){
1997 $option_names[] = 'enablecourseinstances';
1998 $option_names[] = 'enableuserinstances';
2001 $instanceoptions = $this->instance->get_options();
2002 foreach ($option_names as $config) {
2003 if (!empty($instanceoptions[$config])) {
2004 $data[$config] = $instanceoptions[$config];
2005 } else {
2006 $data[$config] = '';
2009 // XXX: set plugin name for plugins which doesn't have muliti instances
2010 if (empty($instanceoptionnames)){
2011 $data['pluginname'] = $this->pluginname;
2013 $this->set_data($data);
2016 $this->add_action_buttons(true, get_string('save','repository'));
2021 * Generate all options needed by filepicker
2023 * @param array $args, including following keys
2024 * context
2025 * accepted_types
2026 * return_types
2028 * @return array the list of repository instances, including meta infomation, containing the following keys
2029 * externallink
2030 * repositories
2031 * accepted_types
2033 function initialise_filepicker($args) {
2034 global $CFG, $USER, $PAGE, $OUTPUT;
2035 require_once($CFG->libdir . '/licenselib.php');
2037 $return = new stdClass();
2038 $licenses = array();
2039 if (!empty($CFG->licenses)) {
2040 $array = explode(',', $CFG->licenses);
2041 foreach ($array as $license) {
2042 $l = new stdClass();
2043 $l->shortname = $license;
2044 $l->fullname = get_string($license, 'license');
2045 $licenses[] = $l;
2048 if (!empty($CFG->sitedefaultlicense)) {
2049 $return->defaultlicense = $CFG->sitedefaultlicense;
2052 $return->licenses = $licenses;
2054 $return->author = fullname($USER);
2056 $ft = new filetype_parser();
2057 if (empty($args->context)) {
2058 $context = $PAGE->context;
2059 } else {
2060 $context = $args->context;
2062 $disable_types = array();
2063 if (!empty($args->disable_types)) {
2064 $disable_types = $args->disable_types;
2067 $user_context = get_context_instance(CONTEXT_USER, $USER->id);
2069 list($context, $course, $cm) = get_context_info_array($context->id);
2070 $contexts = array($user_context, get_system_context());
2071 if (!empty($course)) {
2072 // adding course context
2073 $contexts[] = get_context_instance(CONTEXT_COURSE, $course->id);
2075 $externallink = (int)get_config(null, 'repositoryallowexternallinks');
2076 $repositories = repository::get_instances(array(
2077 'context'=>$contexts,
2078 'currentcontext'=> $context,
2079 'accepted_types'=>$args->accepted_types,
2080 'return_types'=>$args->return_types,
2081 'disable_types'=>$disable_types
2084 $return->repositories = array();
2086 if (empty($externallink)) {
2087 $return->externallink = false;
2088 } else {
2089 $return->externallink = true;
2092 // provided by form element
2093 $return->accepted_types = $ft->get_extensions($args->accepted_types);
2094 $return->return_types = $args->return_types;
2095 foreach ($repositories as $repository) {
2096 $meta = $repository->get_meta();
2097 $return->repositories[$repository->id] = $meta;
2099 return $return;
2102 * Small function to walk an array to attach repository ID
2103 * @param array $value
2104 * @param string $key
2105 * @param int $id
2107 function repository_attach_id(&$value, $key, $id){
2108 $value['repo_id'] = $id;