3 // This file is part of Moodle - http://moodle.org/
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.
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/>.
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
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);
38 * This class is used to manage repository plugins
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.
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
48 * - when you delete a repository, all instances are deleted, and general
49 * options are also deleted from database
50 * - When you create a type for a plugin that can't have multiple instances, a
51 * instance is automatically created.
54 * @subpackage repository
55 * @copyright 2009 Jerome Mouneyrac
56 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
58 class repository_type {
62 * Type name (no whitespace) - A type name is unique
63 * Note: for a user-friendly type name see get_readablename()
70 * Options of this type
71 * They are general options that any instance of this type would share
73 * These options are saved in config_plugin table
80 * Is the repository type visible or hidden
81 * If false (hidden): no instances can be created, edited, deleted, showned , used...
88 * 0 => not ordered, 1 => first position, 2 => second position...
89 * A not order type would appear in first position (should never happened)
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)
98 * @param objet $context - context
101 public function get_contextvisibility($context) {
104 if ($context->contextlevel == CONTEXT_COURSE) {
105 return $this->_options['enablecourseinstances'];
108 if ($context->contextlevel == CONTEXT_USER) {
109 return $this->_options['enableuserinstances'];
112 //the context is SITE
119 * repository_type constructor
120 * @global object $CFG
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)
126 public function __construct($typename = '', $typeoptions = array(), $visible = true, $sortorder = 0) {
130 $this->_typename = $typename;
131 $this->_visible = $visible;
132 $this->_sortorder = $sortorder;
134 //set options attribut
135 $this->_options = array();
136 $options = repository::static_function($typename,'get_type_option_names');
137 //check that the type can be setup
138 if (!empty($options)) {
139 //set the type options
140 foreach ($options as $config) {
141 if (array_key_exists($config,$typeoptions)) {
142 $this->_options[$config] = $typeoptions[$config];
147 //retrieve visibility from option
148 if (array_key_exists('enablecourseinstances',$typeoptions)) {
149 $this->_options['enablecourseinstances'] = $typeoptions['enablecourseinstances'];
151 $this->_options['enablecourseinstances'] = 0;
154 if (array_key_exists('enableuserinstances',$typeoptions)) {
155 $this->_options['enableuserinstances'] = $typeoptions['enableuserinstances'];
157 $this->_options['enableuserinstances'] = 0;
163 * Get the type name (no whitespace)
164 * For a human readable name, use get_readablename()
165 * @return String the type name
167 public function get_typename() {
168 return $this->_typename;
172 * Return a human readable and user-friendly type name
173 * @return string user-friendly type name
175 public function get_readablename() {
176 return get_string('repositoryname','repository_'.$this->_typename);
180 * Return general options
181 * @return array the general options
183 public function get_options() {
184 return $this->_options;
191 public function get_visible() {
192 return $this->_visible;
196 * Return order / position of display in the file picker
199 public function get_sortorder() {
200 return $this->_sortorder;
204 * Create a repository type (the type name must not already exist)
205 * @param boolean throw exception?
206 * @return mixed return int if create successfully, return false if
210 public function create($silent = false) {
213 //check that $type has been set
214 $timmedtype = trim($this->_typename);
215 if (empty($timmedtype)) {
216 throw new repository_exception('emptytype', 'repository');
219 //set sortorder as the last position in the list
220 if (!isset($this->_sortorder) || $this->_sortorder == 0 ) {
221 $sql = "SELECT MAX(sortorder) FROM {repository}";
222 $this->_sortorder = 1 + $DB->get_field_sql($sql);
225 //only create a new type if it doesn't already exist
226 $existingtype = $DB->get_record('repository', array('type'=>$this->_typename));
227 if (!$existingtype) {
229 $newtype = new stdclass;
230 $newtype->type = $this->_typename;
231 $newtype->visible = $this->_visible;
232 $newtype->sortorder = $this->_sortorder;
233 $plugin_id = $DB->insert_record('repository', $newtype);
234 //save the options in DB
235 $this->update_options();
237 //if the plugin type has no multiple instance (e.g. has no instance option name) so it wont
238 //be possible for the administrator to create a instance
239 //in this case we need to create an instance
240 $instanceoptionnames = repository::static_function($this->_typename, 'get_instance_option_names');
241 if (empty($instanceoptionnames)) {
242 $instanceoptions = array();
243 $instanceoptions['name'] = $this->_typename;
244 repository::static_function($this->_typename, 'create', $this->_typename, 0, get_system_context(), $instanceoptions);
246 //run plugin_init function
247 if (!repository::static_function($this->_typename, 'plugin_init')) {
249 throw new repository_exception('cannotinitplugin', 'repository');
253 if(!empty($plugin_id)) {
254 // return plugin_id if create successfully
262 throw new repository_exception('existingrepository', 'repository');
264 // If plugin existed, return false, tell caller no new plugins were created.
271 * Update plugin options into the config_plugin table
272 * @param array $options
275 public function update_options($options = null) {
276 if (!empty($options)) {
277 $this->_options = $options;
280 foreach ($this->_options as $name => $value) {
281 set_config($name,$value,$this->_typename);
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()
293 * @param boolean $visible
296 private function update_visible($visible = null) {
299 if (!empty($visible)) {
300 $this->_visible = $visible;
302 else if (!isset($this->_visible)) {
303 throw new repository_exception('updateemptyvisible', 'repository');
306 return $DB->set_field('repository', 'visible', $this->_visible, array('type'=>$this->_typename));
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()
315 * @param integer $sortorder
318 private function update_sortorder($sortorder = null) {
321 if (!empty($sortorder) && $sortorder!=0) {
322 $this->_sortorder = $sortorder;
324 //if sortorder is not set, we set it as the ;ast position in the list
325 else if (!isset($this->_sortorder) || $this->_sortorder == 0 ) {
326 $sql = "SELECT MAX(sortorder) FROM {repository}";
327 $this->_sortorder = 1 + $DB->get_field_sql($sql);
330 return $DB->set_field('repository', 'sortorder', $this->_sortorder, array('type'=>$this->_typename));
334 * Change order of the type with its adjacent upper or downer type
335 * (database fields are updated)
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
341 * @param string $move "up" or "down"
343 public function move_order($move) {
346 $types = repository::get_types(); // retrieve all types
348 /// retrieve this type into the returned array
350 while (!isset($indice) && $i<count($types)) {
351 if ($types[$i]->get_typename() == $this->_typename) {
357 /// retrieve adjacent indice
360 $adjacentindice = $indice - 1;
363 $adjacentindice = $indice + 1;
366 throw new repository_exception('movenotdefined', 'repository');
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.
373 if ($adjacentindice>=0 && !empty($types[$adjacentindice])) {
374 $DB->set_field('repository', 'sortorder', $this->_sortorder, array('type'=>$types[$adjacentindice]->get_typename()));
375 $this->update_sortorder($types[$adjacentindice]->get_sortorder());
380 * 1. Switch the visibility OFF if it's ON, and ON if it's OFF.
384 public function switch_and_update_visibility() {
385 $this->_visible = !$this->_visible;
386 return $this->update_visible();
391 * Delete a repository_type (general options are removed from config_plugin
392 * table, and all instances are deleted)
396 public function delete() {
399 //delete all instances of this type
401 $params['context'] = array();
402 $params['onlyvisible'] = false;
403 $params['type'] = $this->_typename;
404 $instances = repository::get_instances($params);
405 foreach ($instances as $instance) {
409 //delete all general options
410 foreach ($this->_options as $name => $value) {
411 set_config($name, null, $this->_typename);
414 return $DB->delete_records('repository', array('type' => $this->_typename));
419 * This is the base class of the repository class
421 * To use repository plugin, see:
422 * http://docs.moodle.org/en/Development:Repository_How_to_Create_Plugin
423 * class repository is an abstract class, some functions must be implemented in subclass.
424 * See an example: repository/boxnet/repository.class.php
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();
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
442 abstract class repository {
443 // $disabled can be set to true to disable a plugin by force
444 // example: self::$disabled = true
445 public $disabled = false;
452 * 1. Initialize context and options
453 * 2. Accept necessary parameters
455 * @param integer $repositoryid
456 * @param integer $contextid
457 * @param array $options
459 public function __construct($repositoryid, $contextid = SYSCONTEXTID, $options = array(), $readonly = 0) {
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);
467 $options = $this->get_option();
469 foreach ($options as $n => $v) {
470 $this->options[$n] = $v;
472 $this->name = $this->get_name();
473 $this->returntypes = $this->supported_returntypes();
474 $this->super_called = true;
478 * Return a type for a given type name.
480 * @param string $typename the type name
483 public static function get_type_by_typename($typename) {
486 if (!$record = $DB->get_record('repository',array('type' => $typename))) {
490 return new repository_type($typename, (array)get_config($typename), $record->visible, $record->sortorder);
494 * Return a type for a given type id.
496 * @param int $id the type id
499 public static function get_type_by_id($id) {
502 if (!$record = $DB->get_record('repository',array('id' => $id))) {
506 return new repository_type($record->type, (array)get_config($record->type), $record->visible, $record->sortorder);
510 * Return all repository types ordered by sortorder
511 * first type in returnedarray[0], second type in returnedarray[1], ...
513 * @param boolean $visible can return types by visiblity, return all types if null
514 * @return array Repository types
516 public static function get_types($visible=null) {
521 if (!empty($visible)) {
522 $params = array('visible' => $visible);
524 if ($records = $DB->get_records('repository',$params,'sortorder')) {
525 foreach($records as $type) {
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);
540 public static function check_context($ctx_id) {
543 $context = get_context_instance_by_id($ctx_id);
544 $level = $context->contextlevel;
546 if ($level == CONTEXT_COURSE) {
547 if (!has_capability('moodle/course:participate', $context)) {
552 } else if ($level == CONTEXT_USER) {
553 $c = get_context_instance(CONTEXT_USER, $USER->id);
554 if ($c->id == $ctx_id) {
559 } else if ($level == CONTEXT_SYSTEM) {
560 // it is always ok in system level
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
572 public static function get_editable_types($context = null) {
574 if (empty($context)) {
575 $context = get_system_context();
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)) {
583 if ($type->get_contextvisibility($context)) {
584 $editabletypes[]=$type;
588 return $editabletypes;
592 * Return repository instances
594 * @global object $CFG
595 * @global object $USER
597 * @param array $args Array containing the following keys:
606 * @return array repository instances
608 public static function get_instances($args = array()) {
609 global $DB, $CFG, $USER;
611 if (isset($args['currentcontext'])) {
612 $current_context = $args['currentcontext'];
614 $current_context = null;
617 if (!empty($args['context'])) {
618 $contexts = $args['context'];
623 $onlyvisible = isset($args['onlyvisible']) ? $args['onlyvisible'] : true;
624 $type = isset($args['type']) ? $args['type'] : null;
625 $returntypes = isset($args['return_types']) ? $args['return_types'] : 3;
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 ';
631 if (!empty($args['userid']) && is_numeric($args['userid'])) {
632 $sql .= ' AND (i.userid = 0 or i.userid = ?)';
633 $params[] = $args['userid'];
636 foreach ($contexts as $context) {
637 if (empty($firstcontext)) {
638 $firstcontext = true;
639 $sql .= ' AND ((i.contextid = ?)';
641 $sql .= ' OR (i.contextid = ?)';
643 $params[] = $context->id;
646 if (!empty($firstcontext)) {
650 if ($onlyvisible == true) {
651 $sql .= ' AND (r.visible = 1)';
655 $sql .= ' AND (r.type = ?)';
658 $sql .= ' order by r.sortorder, i.name';
660 if (!$records = $DB->get_records_sql($sql, $params)) {
664 $repositories = array();
665 $ft = new filetype_parser();
666 if (isset($args['accepted_types'])) {
667 $accepted_types = $args['accepted_types'];
669 $accepted_types = '*';
671 foreach ($records as $record) {
672 if (!file_exists($CFG->dirroot . '/repository/'. $record->repositorytype.'/repository.class.php')) {
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;
680 // tell instance what file types will be accepted by file picker
681 $classname = 'repository_' . $record->repositorytype;
683 $repository = new $classname($record->id, $record->contextid, $options, $record->readonly);
685 $is_supported = true;
687 if (empty($repository->super_called)) {
688 // to make sure the super construct is called
689 debugging('parent::__construct must be called by '.$record->repositorytype.' plugin.');
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());
696 $is_supported = false;
697 foreach ($supported_filetypes as $type) {
698 if (in_array($type, $accepted_types)) {
699 $is_supported = true;
704 // check return values
705 if ($returntypes !== 3 and $repository->supported_returntypes() !== 3) {
706 $type = $repository->supported_returntypes();
707 if ($type & $returntypes) {
710 $is_supported = false;
713 if (!$onlyvisible || ($repository->is_visible() && !$repository->disabled)) {
715 // check capability in current context
716 if (!empty($current_context)) {
717 $capability = has_capability('repository/'.$record->repositorytype.':view', $current_context);
719 // TODO: what should we do if current context isn't set?
720 $capability = has_capability('repository/'.$record->repositorytype.':view', get_system_context());
722 if ($is_supported && $capability) {
723 $repositories[$repository->id] = $repository;
728 return $repositories;
732 * Get single repository instance
734 * @global object $CFG
735 * @param integer $id repository id
736 * @return object repository instance
738 public static function get_instance($id) {
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;
744 if(!$instance = $DB->get_record_sql($sql)) {
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;
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.');
761 * call a static function. Any additional arguments than plugin and function will be passed through.
762 * @global object $CFG
763 * @param string $plugin
764 * @param string $function
767 public static function static_function($plugin, $function) {
770 //check that the plugin exists
771 $typedirectory = $CFG->dirroot . '/repository/'. $plugin . '/repository.class.php';
772 if (!file_exists($typedirectory)) {
773 //throw new repository_exception('invalidplugin', 'repository');
778 if (is_object($plugin) || is_array($plugin)) {
779 $plugin = (object)$plugin;
780 $pname = $plugin->name;
785 $args = func_get_args();
786 if (count($args) <= 2) {
794 require_once($typedirectory);
795 return call_user_func_array(array('repository_' . $plugin, $function), $args);
799 * Move file from download folder to file pool using FILE API
801 * @global object $CFG
802 * @global object $USER
803 * @global object $OUTPUT
804 * @param string $thefile file path in download folder
805 * @param object $record
806 * @return array containing the following keys:
812 public static function move_to_filepool($thefile, $record) {
813 global $DB, $CFG, $USER, $OUTPUT;
814 if ($record->filepath !== '/') {
815 $record->filepath = trim($record->filepath, '/');
816 $record->filepath = '/'.$record->filepath.'/';
818 $context = get_context_instance(CONTEXT_USER, $USER->id);
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)) {
829 $fs = get_file_storage();
830 $browser = get_file_browser();
831 if ($existingfile = $fs->get_file($context->id, $record->filearea, $record->itemid, $record->filepath, $record->filename)) {
832 $existingfile->delete();
834 if ($file = $fs->create_file_from_pathname($record, $thefile)) {
835 if (empty($CFG->repository_no_delete)) {
836 $delete = unlink($thefile);
837 unset($CFG->repository_no_delete);
839 $fileinfo = $browser->get_file_info($context, $file->get_filearea(), $file->get_itemid(), $file->get_filepath(), $file->get_filename());
840 if(!empty($fileinfo)) {
842 'url'=>$fileinfo->get_url(),
843 'id'=>$file->get_itemid(),
844 'file'=>$file->get_filename(),
845 'icon' => $OUTPUT->pix_url(file_extension_icon($thefile, 32))->out()
856 * Return the user files tree in a format to be returned by the function get_listing
857 * @global object $CFG
858 * @param string $search
861 public static function get_user_file_tree($search = ''){
864 $ret['nologin'] = true;
865 $ret['manage'] = $CFG->wwwroot .'/files/index.php'; // temporary
866 $browser = get_file_browser();
871 $ret['dynload'] = false;
873 if ($fileinfo = $browser->get_file_info(get_system_context(), $filearea, $itemid, $path, $filename)) {
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();
882 $params = $level->get_params();
883 $ret['path'][] = repository::encode_path($params['filearea'], $params['filepath'], $level->get_visible_name());
884 $level = $level->get_parent();
887 $filecount = repository::build_tree($fileinfo, $search, $ret['dynload'], $ret['list']);
888 $ret['path'] = array_reverse($ret['path']);
891 if (empty($ret['list'])) {
892 //exit(mnet_server_fault(9016, get_string('emptyfilelist', 'repository_local')));
893 throw new Exception('emptyfilelist');
901 * Serialize file path
902 * @param string $filearea
903 * @param string $path
904 * @param string $visiblename
907 public static function encode_path($filearea, $path, $visiblename) {
908 return array('path'=>serialize(array($filearea, $path)), 'name'=>$visiblename);
912 * Builds a tree of files This function is
913 * then called recursively.
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
921 * todo: take $search into account, and respect a threshold for dynamic loading
923 public static function build_tree($fileinfo, $search, $dynamicmode, &$list) {
924 global $CFG, $OUTPUT;
927 $children = $fileinfo->get_children();
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();
937 if ($child->is_directory()) {
939 $level = $child->get_parent();
941 $params = $level->get_params();
942 $path[] = repository::encode_path($params['filearea'], $params['filepath'], $level->get_visible_name());
943 $level = $level->get_parent();
947 'title' => $child->get_visible_name(),
950 'path' => array_reverse($path),
951 'thumbnail' => $OUTPUT->pix_url('f/folder-32')
954 //if ($dynamicmode && $child->is_writable()) {
955 // $tmp['children'] = array();
957 // if folder name matches search, we send back all files contained.
959 if ($search && stristr($tmp['title'], $search) !== false) {
962 $tmp['children'] = array();
963 $_filecount = repository::build_tree($child, $_search, $dynamicmode, $tmp['children']);
964 if ($search && $_filecount) {
965 $tmp['expanded'] = 1;
970 if (!$search || $_filecount || (stristr($tmp['title'], $search) !== false)) {
971 $filecount += $_filecount;
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)) {
980 $params = $child->get_params();
981 $source = serialize(array($params['contextid'], $params['filearea'], $params['itemid'], $params['filepath'], $params['filename']));
983 'title' => $filename,
986 //'source' => $child->get_url(),
987 'source' => base64_encode($source),
988 'thumbnail'=>$OUTPUT->pix_url(file_extension_icon($filename, 32)),
999 * Display a repository instance list (with edit/delete/create links)
1000 * @global object $CFG
1001 * @global object $USER
1002 * @global object $OUTPUT
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
1006 public static function display_instances_list($context, $typename = null) {
1007 global $CFG, $USER, $OUTPUT;
1009 $output = $OUTPUT->box_start('generalbox');
1010 //if the context is SYSTEM, so we call it from administration page
1011 $admin = ($context->id == SYSCONTEXTID) ? true : false;
1013 $baseurl = "$CFG->httpswwwroot/$CFG->admin/repositoryinstance.php?sesskey=" . sesskey();
1014 $output .= "<div ><h2 style='text-align: center'>" . get_string('siteinstances', 'repository') . " ";
1015 $output .= "</h2></div>";
1017 $baseurl = $CFG->httpswwwroot . '/repository/manage_instances.php?contextid=' . $context->id . '&sesskey=' . sesskey();
1019 $url = new moodle_url($baseurl);
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
1028 //want to display only visible instances, but for every type types. The repository::get_instances()
1029 //third parameter displays only visible type.
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);
1036 $instancesnumber = count($instances);
1037 $alreadyplugins = array();
1039 $table = new html_table();
1040 $table->head = array($namestr, $pluginstr, $deletestr, $settingsstr);
1041 $table->align = array('left', 'left', 'center','center');
1042 $table->data = array();
1046 foreach ($instances as $i) {
1050 $type = repository::get_type_by_id($i->options['typeid']);
1052 if ($type->get_contextvisibility($context)) {
1053 if (!$i->readonly) {
1055 $url->param('type', $i->options['type']);
1056 $url->param('edit', $i->id);
1057 $settings .= html_writer::link($url, $settingsstr);
1059 $url->remove_params('edit');
1060 $url->param('delete', $i->id);
1061 $delete .= html_writer::link($url, $deletestr);
1063 $url->remove_params('type');
1067 $type = repository::get_type_by_id($i->options['typeid']);
1068 $table->data[] = array($i->name, $type->get_readablename(), $delete, $settings);
1070 //display a grey row if the type is defined as not visible
1071 if (isset($type) && !$type->get_visible()) {
1072 $table->rowclasses[] = 'dimmed_text';
1074 $table->rowclasses[] = '';
1077 if (!in_array($i->name, $alreadyplugins)) {
1078 $alreadyplugins[] = $i->name;
1081 $output .= html_writer::table($table);
1082 $instancehtml = '<div>';
1085 //if no type is set, we can create all type of instance
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)) {
1095 $instancehtml .= '<li><a href="'.$baseurl.'&new='.$type->get_typename().'">'.get_string('createxxinstance', 'repository', get_string('repositoryname', 'repository_'.$type->get_typename()))
1101 $instancehtml .= '</ul>';
1104 $instanceoptionnames = repository::static_function($typename, 'get_instance_option_names');
1105 if (!empty($instanceoptionnames)) { //create a unique type of instance
1107 $instancehtml .= "<form action='".$baseurl."&new=".$typename."' method='post'>
1108 <p style='text-align:center'><input type='submit' value='".get_string('createinstance', 'repository')."'/></p>
1114 $instancehtml .= '</div>';
1115 $output .= $instancehtml;
1118 $output .= $OUTPUT->box_end();
1120 //print the list + creation links
1125 * Decide where to save the file, can be
1126 * reused by sub class
1127 * @param string filename
1129 public function prepare_file($filename) {
1131 if (!file_exists($CFG->dataroot.'/temp/download')) {
1132 mkdir($CFG->dataroot.'/temp/download/', 0777, true);
1134 if (is_dir($CFG->dataroot.'/temp/download')) {
1135 $dir = $CFG->dataroot.'/temp/download/';
1137 if (empty($filename)) {
1138 $filename = uniqid('repo').'_'.time().'.tmp';
1140 if (file_exists($dir.$filename)) {
1141 $filename = uniqid('m').$filename;
1143 return $dir.$filename;
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.
1151 * @param string $url the url of file
1154 public function get_link($url) {
1159 * Download a file, this function can be overridden by
1162 * @global object $CFG
1163 * @param string $url the url of file
1164 * @param string $filename save location
1165 * @return string the location of the file
1168 public function get_file($url, $filename = '') {
1170 $path = $this->prepare_file($filename);
1171 $fp = fopen($path, 'w');
1173 $c->download(array(array('url'=>$url, 'file'=>$fp)));
1174 return array('path'=>$path, 'url'=>$url);
1178 * Return is the instance is visible
1179 * (is the type visible ? is the context enable ?)
1182 public function is_visible() {
1183 $type = repository::get_type_by_id($this->options['typeid']);
1184 $instanceoptions = repository::static_function($type->get_typename(), 'get_instance_option_names');
1186 if ($type->get_visible()) {
1187 //if the instance is unique so it's visible, otherwise check if the instance has a enabled context
1188 if (empty($instanceoptions) || $type->get_contextvisibility($this->context)) {
1197 * Return the name of this instance, can be overridden.
1198 * @global object $DB
1201 public function get_name() {
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'];
1210 if ( $repo = $DB->get_record('repository_instances', array('id'=>$this->id)) ) {
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
1223 public function supported_filetypes() {
1224 // return array('text/plain', 'image/gif');
1229 * does it return a file url or a item_id
1232 public function supported_returntypes() {
1233 return (FILE_INTERNAL | FILE_EXTERNAL);
1237 * Provide repository instance information for Ajax
1238 * @global object $CFG
1241 final public function get_meta() {
1243 $ft = new filetype_parser;
1244 $meta = new stdclass;
1245 $meta->id = $this->id;
1246 $meta->name = $this->get_name();
1247 $meta->type = $this->options['type'];
1248 $meta->icon = $CFG->httpswwwroot.'/repository/'.$meta->type.'/icon.png';
1249 $meta->supported_types = $ft->get_extensions($this->supported_filetypes());
1250 $meta->return_types = $this->supported_returntypes();
1255 * Create an instance for this plug-in
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
1262 * @param integer $readonly whether to create it readonly or not (defaults to not)
1265 final public static function create($type, $userid, $context, $params, $readonly=0) {
1267 $params = (array)$params;
1268 require_once($CFG->dirroot . '/repository/'. $type . '/repository.class.php');
1269 $classname = 'repository_' . $type;
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;
1277 $record->readonly = $readonly;
1278 $record->userid = $userid;
1279 $id = $DB->insert_record('repository_instances', $record);
1281 $configs = call_user_func($classname . '::get_instance_option_names');
1282 if (!empty($configs)) {
1283 foreach ($configs as $config) {
1284 $options[$config] = $params[$config];
1289 unset($options['name']);
1290 $instance = repository::get_instance($id);
1291 $instance->set_option($options);
1302 * delete a repository instance
1303 * @global object $DB
1306 final public function delete() {
1308 $DB->delete_records('repository_instances', array('id'=>$this->id));
1309 $DB->delete_records('repository_instance_config', array('instanceid'=>$this->id));
1314 * Hide/Show a repository
1315 * @global object $DB
1316 * @param string $hide
1319 final public function hide($hide = 'toggle') {
1321 if ($entry = $DB->get_record('repository', array('id'=>$this->id))) {
1322 if ($hide === 'toggle' ) {
1323 if (!empty($entry->visible)) {
1324 $entry->visible = 0;
1326 $entry->visible = 1;
1329 if (!empty($hide)) {
1330 $entry->visible = 0;
1332 $entry->visible = 1;
1335 return $DB->update_record('repository', $entry);
1341 * Cache login details for repositories
1342 * @global object $DB
1343 * @param string $username
1344 * @param string $password
1345 * @param integer $userid The id of specific user
1346 * @return integer Id of the record
1348 public function store_login($username = '', $password = '', $userid = 1) {
1351 $repository = new stdclass;
1352 if (!empty($this->id)) {
1353 $repository->id = $this->id;
1355 $repository->userid = $userid;
1356 $repository->repositorytype = $this->type;
1357 $repository->contextid = $this->context->id;
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);
1365 $repository->username = $username;
1366 $repository->password = $password;
1367 return $DB->insert_record('repository', $repository);
1372 * Save settings for repository instance
1373 * $repo->set_option(array('api_key'=>'f2188bde132', 'name'=>'dongsheng'));
1374 * @global object $DB
1375 * @param array $options settings
1376 * @return int Id of the record
1378 public function set_option($options = array()) {
1381 if (!empty($options['name'])) {
1384 $r->name = $options['name'];
1385 $DB->update_record('repository_instances', $r);
1386 unset($options['name']);
1389 foreach ($options as $name=>$value) {
1390 if ($id = $DB->get_field('repository_instance_config', 'id', array('name'=>$name, 'instanceid'=>$this->id))) {
1391 $result = $result && $DB->set_field('repository_instance_config', 'value', $value, array('id'=>$id));
1393 $config = new object();
1394 $config->instanceid = $this->id;
1395 $config->name = $name;
1396 $config->value = $value;
1397 $result = $result && $DB->insert_record('repository_instance_config', $config);
1404 * Get settings for repository instance
1405 * @global object $DB
1406 * @param string $config
1407 * @return array Settings
1409 public function get_option($config = '') {
1411 $entries = $DB->get_records('repository_instance_config', array('instanceid'=>$this->id));
1413 if (empty($entries)) {
1416 foreach($entries as $entry) {
1417 $ret[$entry->name] = $entry->value;
1419 if (!empty($config)) {
1420 return $ret[$config];
1426 public function filter(&$value) {
1428 $accepted_types = optional_param('accepted_types', '', PARAM_RAW);
1429 $ft = new filetype_parser;
1430 $ext = $ft->get_extensions($this->supported_filetypes());
1431 if (isset($value['children'])) {
1433 if (!empty($value['children'])) {
1434 $value['children'] = array_filter($value['children'], array($this, 'filter'));
1437 if ($accepted_types == '*' or empty($accepted_types)
1438 or (is_array($accepted_types) and in_array('*', $accepted_types))) {
1440 } elseif (is_array($accepted_types)) {
1441 foreach ($accepted_types as $type) {
1442 if (preg_match('#'.$type.'$#', $value['title'])) {
1452 * Given a path, and perhaps a search, get a list of files.
1454 * See details on http://docs.moodle.org/en/Development:Repository_plugins
1456 * @param string $path, this parameter can
1457 * a folder name, or a identification of folder
1458 * @param string $page, the page number of file list
1459 * @return array the list of files, including meta infomation, containing the following keys
1460 * manage, url to manage url
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
1469 * pages, total pages
1470 * search_result, is it a search result?
1472 * path, current path and parent path
1474 public function get_listing($path = '', $page = '') {
1478 * Search files in repository
1479 * When doing global search, $search_text will be used as
1482 * @return mixed, see get_listing()
1484 public function search($search_text) {
1486 $list['list'] = array();
1491 * Logout from repository instance
1492 * By default, this function will return a login form
1496 public function logout(){
1497 return $this->print_login();
1501 * To check whether the user is logged in.
1505 public function check_login(){
1511 * Show the login screen, if required
1513 public function print_login(){
1514 return $this->get_listing();
1518 * Show the search screen, if required
1521 public function print_search() {
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/>';
1531 * is it possible to do glboal search?
1534 public function global_search() {
1539 * Defines operations that happen occasionally on cron
1542 public function cron() {
1547 * function which is run when the type is created (moodle administrator add the plugin)
1548 * @return boolean success or fail?
1550 public static function plugin_init() {
1555 * Edit/Create Admin Settings Moodle form
1556 * @param object $ Moodle form (passed by reference)
1558 public function type_config_form($mform) {
1562 * Edit/Create Instance Settings Moodle form
1563 * @param object $ Moodle form (passed by reference)
1565 public function instance_config_form($mform) {
1569 * Return names of the general options
1570 * By default: no general option name
1573 public static function get_type_option_names() {
1578 * Return names of the instance options
1579 * By default: no instance option name
1582 public static function get_instance_option_names() {
1589 * Exception class for repository api
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
1597 class repository_exception extends moodle_exception {
1603 * This is a class used to define a repository instance form
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
1611 final class repository_instance_form extends moodleform {
1612 protected $instance;
1615 public function definition() {
1617 // type of plugin, string
1618 $this->plugin = $this->_customdata['plugin'];
1619 $this->typeid = $this->_customdata['typeid'];
1620 $this->contextid = $this->_customdata['contextid'];
1621 $this->instance = (isset($this->_customdata['instance'])
1622 && is_subclass_of($this->_customdata['instance'], 'repository'))
1623 ? $this->_customdata['instance'] : null;
1625 $mform =& $this->_form;
1626 $strrequired = get_string('required');
1628 $mform->addElement('hidden', 'edit', ($this->instance) ? $this->instance->id : 0);
1629 $mform->setType('edit', PARAM_INT);
1630 $mform->addElement('hidden', 'new', $this->plugin);
1631 $mform->setType('new', PARAM_FORMAT);
1632 $mform->addElement('hidden', 'plugin', $this->plugin);
1633 $mform->setType('plugin', PARAM_SAFEDIR);
1634 $mform->addElement('hidden', 'typeid', $this->typeid);
1635 $mform->setType('typeid', PARAM_INT);
1636 $mform->addElement('hidden', 'contextid', $this->contextid);
1637 $mform->setType('contextid', PARAM_INT);
1639 $mform->addElement('text', 'name', get_string('name'), 'maxlength="100" size="30"');
1640 $mform->addRule('name', $strrequired, 'required', null, 'client');
1644 if (!$this->instance) {
1645 $result = repository::static_function($this->plugin, 'instance_config_form', $mform);
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.
1653 foreach ($this->instance->get_instance_option_names() as $config) {
1654 if (!empty($this->instance->options[$config])) {
1655 $data[$config] = $this->instance->options[$config];
1657 $data[$config] = '';
1661 $this->set_data($data);
1664 $this->add_action_buttons(true, get_string('save','repository'));
1667 public function validation($data) {
1671 $sql = "SELECT count('x') FROM {repository_instances} i, {repository} r WHERE r.type=:plugin AND r.id=i.typeid AND i.name=:name";
1672 if ($DB->count_records_sql($sql, array('name' => $data['name'], 'plugin' => $data['plugin'])) > 1) {
1673 $errors = array('name' => get_string('err_uniquename', 'repository'));
1681 * This is a class used to define a repository type setting form
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
1689 final class repository_type_form extends moodleform {
1690 protected $instance;
1694 * Definition of the moodleform
1695 * @global object $CFG
1697 public function definition() {
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;
1705 $mform =& $this->_form;
1706 $strrequired = get_string('required');
1708 $mform->addElement('hidden', 'edit', ($this->instance) ? $this->instance->get_typename() : 0);
1709 $mform->setType('edit', PARAM_INT);
1710 $mform->addElement('hidden', 'new', $this->plugin);
1711 $mform->setType('new', PARAM_FORMAT);
1712 $mform->addElement('hidden', 'plugin', $this->plugin);
1713 $mform->setType('plugin', PARAM_SAFEDIR);
1715 // let the plugin add its specific fields
1716 if (!$this->instance) {
1717 $result = repository::static_function($this->plugin, 'type_config_form', $mform);
1719 $classname = 'repository_' . $this->instance->get_typename();
1720 $result = call_user_func(array($classname, 'type_config_form'), $mform);
1723 //add "enable course/user instances" checkboxes if multiple instances are allowed
1724 $instanceoptionnames = repository::static_function($this->plugin, 'get_instance_option_names');
1725 if (!empty($instanceoptionnames)){
1726 $mform->addElement('checkbox', 'enablecourseinstances', get_string('enablecourseinstances', 'repository'));
1727 $mform->addElement('checkbox', 'enableuserinstances', get_string('enableuserinstances', 'repository'));
1730 // set the data if we have some.
1731 if ($this->instance) {
1733 $option_names = call_user_func(array($classname,'get_type_option_names'));
1734 if (!empty($instanceoptionnames)){
1735 $option_names[] = 'enablecourseinstances';
1736 $option_names[] = 'enableuserinstances';
1739 $instanceoptions = $this->instance->get_options();
1740 foreach ($option_names as $config) {
1741 if (!empty($instanceoptions[$config])) {
1742 $data[$config] = $instanceoptions[$config];
1744 $data[$config] = '';
1747 $this->set_data($data);
1750 $this->add_action_buttons(true, get_string('save','repository'));
1755 * Generate all options needed by filepicker
1757 * @param array $args, including following keys
1762 * @return array the list of repository instances, including meta infomation, containing the following keys
1767 function initialise_filepicker($args) {
1768 global $CFG, $USER, $PAGE, $OUTPUT;
1769 require_once($CFG->libdir . '/licenselib.php');
1771 $return = new stdclass;
1772 $licenses = array();
1773 if (!empty($CFG->licenses)) {
1774 $array = explode(',', $CFG->licenses);
1775 foreach ($array as $license) {
1777 $l->shortname = $license;
1778 $l->fullname = get_string($license, 'license');
1783 $return->licenses = $licenses;
1785 $return->author = fullname($USER);
1787 $ft = new filetype_parser();
1788 if (empty($args->context)) {
1789 $context = $PAGE->context;
1791 $context = $args->context;
1794 $user_context = get_context_instance(CONTEXT_USER, $USER->id);
1796 $externallink = (int)get_config(null, 'repositoryallowexternallinks');
1797 $repositories = repository::get_instances(array(
1798 'context'=>array($user_context, get_system_context()),
1799 'currentcontext'=> $context,
1800 'accepted_types'=>$args->accepted_types,
1801 'return_types'=>$args->return_types
1804 $return->repositories = array();
1806 if (empty($externallink)) {
1807 $return->externallink = false;
1809 $return->externallink = true;
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;
1822 * The plugins should be enabled by defaulted once moodle installed
1824 * @global object $OUTPUT
1828 function repository_setup_default_plugins() {
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'));