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. Change visibility to the value chosen
385 public function update_visibility($visible = null) {
386 if (is_bool($visible)) {
387 $this->_visible = $visible;
389 $this->_visible = !$this->_visible;
391 return $this->update_visible();
396 * Delete a repository_type (general options are removed from config_plugin
397 * table, and all instances are deleted)
401 public function delete() {
404 //delete all instances of this type
406 $params['context'] = array();
407 $params['onlyvisible'] = false;
408 $params['type'] = $this->_typename;
409 $instances = repository::get_instances($params);
410 foreach ($instances as $instance) {
414 //delete all general options
415 foreach ($this->_options as $name => $value) {
416 set_config($name, null, $this->_typename);
419 return $DB->delete_records('repository', array('type' => $this->_typename));
424 * This is the base class of the repository class
426 * To use repository plugin, see:
427 * http://docs.moodle.org/en/Development:Repository_How_to_Create_Plugin
428 * class repository is an abstract class, some functions must be implemented in subclass.
429 * See an example: repository/boxnet/repository.class.php
432 * // for ajax file picker, this will print a json string to tell file picker
433 * // how to build a login form
434 * $repo->print_login();
435 * // for ajax file picker, this will return a files list.
436 * $repo->get_listing();
437 * // this function will be used for non-javascript version.
438 * $repo->print_listing();
439 * // print a search box
440 * $repo->print_search();
442 * @package moodlecore
443 * @subpackage repository
444 * @copyright 2009 Dongsheng Cai <dongsheng@moodle.com>
445 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
447 abstract class repository {
448 // $disabled can be set to true to disable a plugin by force
449 // example: self::$disabled = true
450 public $disabled = false;
457 * 1. Initialize context and options
458 * 2. Accept necessary parameters
460 * @param integer $repositoryid
461 * @param integer $contextid
462 * @param array $options
464 public function __construct($repositoryid, $contextid = SYSCONTEXTID, $options = array(), $readonly = 0) {
465 $this->id = $repositoryid;
466 $this->context = get_context_instance_by_id($contextid);
467 $this->readonly = $readonly;
468 $this->options = array();
469 if (is_array($options)) {
470 $options = array_merge($this->get_option(), $options);
472 $options = $this->get_option();
474 foreach ($options as $n => $v) {
475 $this->options[$n] = $v;
477 $this->name = $this->get_name();
478 $this->returntypes = $this->supported_returntypes();
479 $this->super_called = true;
483 * Return a type for a given type name.
485 * @param string $typename the type name
486 * @return repository_type
488 public static function get_type_by_typename($typename) {
491 if (!$record = $DB->get_record('repository',array('type' => $typename))) {
495 return new repository_type($typename, (array)get_config($typename), $record->visible, $record->sortorder);
499 * Return a type for a given type id.
501 * @param int $id the type id
504 public static function get_type_by_id($id) {
507 if (!$record = $DB->get_record('repository',array('id' => $id))) {
511 return new repository_type($record->type, (array)get_config($record->type), $record->visible, $record->sortorder);
515 * Return all repository types ordered by sortorder
516 * first type in returnedarray[0], second type in returnedarray[1], ...
518 * @param boolean $visible can return types by visiblity, return all types if null
519 * @return array Repository types
521 public static function get_types($visible=null) {
526 if (!empty($visible)) {
527 $params = array('visible' => $visible);
529 if ($records = $DB->get_records('repository',$params,'sortorder')) {
530 foreach($records as $type) {
531 if (file_exists($CFG->dirroot . '/repository/'. $type->type .'/repository.class.php')) {
532 $types[] = new repository_type($type->type, (array)get_config($type->type), $type->visible, $type->sortorder);
545 public static function check_context($ctx_id) {
548 $context = get_context_instance_by_id($ctx_id);
549 $level = $context->contextlevel;
551 if ($level == CONTEXT_COURSE) {
552 if (!is_enrolled($context)) { //TODO: this looks a bit too simple, verify!
557 } else if ($level == CONTEXT_USER) {
558 $c = get_context_instance(CONTEXT_USER, $USER->id);
559 if ($c->id == $ctx_id) {
564 } else if ($level == CONTEXT_SYSTEM) {
565 // it is always ok in system level
572 * Return all types that you a user can create/edit and which are also visible
573 * Note: Mostly used in order to know if at least one editable type can be set
574 * @param object $context the context for which we want the editable types
575 * @return array types
577 public static function get_editable_types($context = null) {
579 if (empty($context)) {
580 $context = get_system_context();
583 $types= repository::get_types(true);
584 $editabletypes = array();
585 foreach ($types as $type) {
586 $instanceoptionnames = repository::static_function($type->get_typename(), 'get_instance_option_names');
587 if (!empty($instanceoptionnames)) {
588 if ($type->get_contextvisibility($context)) {
589 $editabletypes[]=$type;
593 return $editabletypes;
597 * Return repository instances
599 * @global object $CFG
600 * @global object $USER
602 * @param array $args Array containing the following keys:
611 * @return array repository instances
613 public static function get_instances($args = array()) {
614 global $DB, $CFG, $USER;
616 if (isset($args['currentcontext'])) {
617 $current_context = $args['currentcontext'];
619 $current_context = null;
622 if (!empty($args['context'])) {
623 $contexts = $args['context'];
628 $onlyvisible = isset($args['onlyvisible']) ? $args['onlyvisible'] : true;
629 $type = isset($args['type']) ? $args['type'] : null;
630 $returntypes = isset($args['return_types']) ? $args['return_types'] : 3;
633 $sql = "SELECT i.*, r.type AS repositorytype, r.sortorder, r.visible
634 FROM {repository} r, {repository_instances} i
635 WHERE i.typeid = r.id ";
637 if (!empty($args['disable_types']) && is_array($args['disable_types'])) {
638 list($types, $p) = $DB->get_in_or_equal($args['disable_types'], SQL_PARAMS_QM, 'param0000', false);
639 $sql .= " AND r.type $types";
640 $params = array_merge($params, $p);
643 if (!empty($args['userid']) && is_numeric($args['userid'])) {
644 $sql .= " AND (i.userid = 0 or i.userid = ?)";
645 $params[] = $args['userid'];
648 foreach ($contexts as $context) {
649 if (empty($firstcontext)) {
650 $firstcontext = true;
651 $sql .= " AND ((i.contextid = ?)";
653 $sql .= " OR (i.contextid = ?)";
655 $params[] = $context->id;
658 if (!empty($firstcontext)) {
662 if ($onlyvisible == true) {
663 $sql .= " AND (r.visible = 1)";
667 $sql .= " AND (r.type = ?)";
670 $sql .= " ORDER BY r.sortorder, i.name";
672 if (!$records = $DB->get_records_sql($sql, $params)) {
676 $repositories = array();
677 $ft = new filetype_parser();
678 if (isset($args['accepted_types'])) {
679 $accepted_types = $args['accepted_types'];
681 $accepted_types = '*';
683 foreach ($records as $record) {
684 if (!file_exists($CFG->dirroot . '/repository/'. $record->repositorytype.'/repository.class.php')) {
687 require_once($CFG->dirroot . '/repository/'. $record->repositorytype.'/repository.class.php');
688 $options['visible'] = $record->visible;
689 $options['name'] = $record->name;
690 $options['type'] = $record->repositorytype;
691 $options['typeid'] = $record->typeid;
692 // tell instance what file types will be accepted by file picker
693 $classname = 'repository_' . $record->repositorytype;
695 $repository = new $classname($record->id, $record->contextid, $options, $record->readonly);
697 $is_supported = true;
699 if (empty($repository->super_called)) {
700 // to make sure the super construct is called
701 debugging('parent::__construct must be called by '.$record->repositorytype.' plugin.');
704 if ($accepted_types !== '*' and $repository->supported_filetypes() !== '*') {
705 $accepted_types = $ft->get_extensions($accepted_types);
706 $supported_filetypes = $ft->get_extensions($repository->supported_filetypes());
708 $is_supported = false;
709 foreach ($supported_filetypes as $type) {
710 if (in_array($type, $accepted_types)) {
711 $is_supported = true;
716 // check return values
717 if ($returntypes !== 3 and $repository->supported_returntypes() !== 3) {
718 $type = $repository->supported_returntypes();
719 if ($type & $returntypes) {
722 $is_supported = false;
725 if (!$onlyvisible || ($repository->is_visible() && !$repository->disabled)) {
727 // check capability in current context
728 if (!empty($current_context)) {
729 $capability = has_capability('repository/'.$record->repositorytype.':view', $current_context);
731 // TODO: what should we do if current context isn't set?
732 $capability = has_capability('repository/'.$record->repositorytype.':view', get_system_context());
734 if ($is_supported && $capability) {
735 $repositories[$repository->id] = $repository;
740 return $repositories;
744 * Get single repository instance
746 * @global object $CFG
747 * @param integer $id repository id
748 * @return object repository instance
750 public static function get_instance($id) {
752 $sql = "SELECT i.*, r.type AS repositorytype, r.visible
754 JOIN {repository_instances} i ON i.typeid = r.id
757 if (!$instance = $DB->get_record_sql($sql, array($id))) {
760 require_once($CFG->dirroot . '/repository/'. $instance->repositorytype
761 . '/repository.class.php');
762 $classname = 'repository_' . $instance->repositorytype;
763 $options['typeid'] = $instance->typeid;
764 $options['type'] = $instance->repositorytype;
765 $options['name'] = $instance->name;
766 $obj = new $classname($instance->id, $instance->contextid, $options, $instance->readonly);
767 if (empty($obj->super_called)) {
768 debugging('parent::__construct must be called by '.$classname.' plugin.');
774 * call a static function. Any additional arguments than plugin and function will be passed through.
775 * @global object $CFG
776 * @param string $plugin
777 * @param string $function
780 public static function static_function($plugin, $function) {
783 //check that the plugin exists
784 $typedirectory = $CFG->dirroot . '/repository/'. $plugin . '/repository.class.php';
785 if (!file_exists($typedirectory)) {
786 //throw new repository_exception('invalidplugin', 'repository');
791 if (is_object($plugin) || is_array($plugin)) {
792 $plugin = (object)$plugin;
793 $pname = $plugin->name;
798 $args = func_get_args();
799 if (count($args) <= 2) {
807 require_once($typedirectory);
808 return call_user_func_array(array('repository_' . $plugin, $function), $args);
812 * Move file from download folder to file pool using FILE API
814 * @global object $CFG
815 * @global object $USER
816 * @global object $OUTPUT
817 * @param string $thefile file path in download folder
818 * @param object $record
819 * @return array containing the following keys:
825 public static function move_to_filepool($thefile, $record) {
826 global $DB, $CFG, $USER, $OUTPUT;
827 if ($record->filepath !== '/') {
828 $record->filepath = trim($record->filepath, '/');
829 $record->filepath = '/'.$record->filepath.'/';
831 $context = get_context_instance(CONTEXT_USER, $USER->id);
834 $record->contextid = $context->id;
835 $record->component = 'user';
836 $record->filearea = 'draft';
837 $record->timecreated = $now;
838 $record->timemodified = $now;
839 $record->userid = $USER->id;
840 $record->mimetype = mimeinfo('type', $thefile);
841 if(!is_numeric($record->itemid)) {
844 $fs = get_file_storage();
845 if ($existingfile = $fs->get_file($context->id, $record->component, $record->filearea, $record->itemid, $record->filepath, $record->filename)) {
846 $existingfile->delete();
848 if ($file = $fs->create_file_from_pathname($record, $thefile)) {
849 if (empty($CFG->repository_no_delete)) {
850 $delete = unlink($thefile);
851 unset($CFG->repository_no_delete);
854 'url'=>file_draftfile_url($file->get_itemid(), $file->get_filepath(), $file->get_filename()),
855 'id'=>$file->get_itemid(),
856 'file'=>$file->get_filename(),
857 'icon' => $OUTPUT->pix_url(file_extension_icon($thefile, 32))->out(),
865 * Builds a tree of files This function is
866 * then called recursively.
868 * @param $fileinfo an object returned by file_browser::get_file_info()
869 * @param $search searched string
870 * @param $dynamicmode bool no recursive call is done when in dynamic mode
871 * @param $list - the array containing the files under the passed $fileinfo
872 * @returns int the number of files found
874 * todo: take $search into account, and respect a threshold for dynamic loading
876 public static function build_tree($fileinfo, $search, $dynamicmode, &$list) {
877 global $CFG, $OUTPUT;
880 $children = $fileinfo->get_children();
882 foreach ($children as $child) {
883 $filename = $child->get_visible_name();
884 $filesize = $child->get_filesize();
885 $filesize = $filesize ? display_size($filesize) : '';
886 $filedate = $child->get_timemodified();
887 $filedate = $filedate ? userdate($filedate) : '';
888 $filetype = $child->get_mimetype();
890 if ($child->is_directory()) {
892 $level = $child->get_parent();
894 $params = $level->get_params();
895 $path[] = array($params['filepath'], $level->get_visible_name());
896 $level = $level->get_parent();
900 'title' => $child->get_visible_name(),
903 'path' => array_reverse($path),
904 'thumbnail' => $OUTPUT->pix_url('f/folder-32')
907 //if ($dynamicmode && $child->is_writable()) {
908 // $tmp['children'] = array();
910 // if folder name matches search, we send back all files contained.
912 if ($search && stristr($tmp['title'], $search) !== false) {
915 $tmp['children'] = array();
916 $_filecount = repository::build_tree($child, $_search, $dynamicmode, $tmp['children']);
917 if ($search && $_filecount) {
918 $tmp['expanded'] = 1;
923 if (!$search || $_filecount || (stristr($tmp['title'], $search) !== false)) {
924 $filecount += $_filecount;
928 } else { // not a directory
929 // skip the file, if we're in search mode and it's not a match
930 if ($search && (stristr($filename, $search) === false)) {
933 $params = $child->get_params();
934 $source = serialize(array($params['contextid'], $params['component'], $params['filearea'], $params['itemid'], $params['filepath'], $params['filename']));
936 'title' => $filename,
939 //'source' => $child->get_url(),
940 'source' => base64_encode($source),
941 'thumbnail'=>$OUTPUT->pix_url(file_extension_icon($filename, 32)),
952 * Display a repository instance list (with edit/delete/create links)
953 * @global object $CFG
954 * @global object $USER
955 * @global object $OUTPUT
956 * @param object $context the context for which we display the instance
957 * @param string $typename if set, we display only one type of instance
959 public static function display_instances_list($context, $typename = null) {
960 global $CFG, $USER, $OUTPUT;
962 $output = $OUTPUT->box_start('generalbox');
963 //if the context is SYSTEM, so we call it from administration page
964 $admin = ($context->id == SYSCONTEXTID) ? true : false;
966 $baseurl = "$CFG->httpswwwroot/$CFG->admin/repositoryinstance.php?sesskey=" . sesskey();
967 $output .= "<div ><h2 style='text-align: center'>" . get_string('siteinstances', 'repository') . " ";
968 $output .= "</h2></div>";
970 $baseurl = $CFG->httpswwwroot . '/repository/manage_instances.php?contextid=' . $context->id . '&sesskey=' . sesskey();
972 $url = new moodle_url($baseurl);
974 $namestr = get_string('name');
975 $pluginstr = get_string('plugin', 'repository');
976 $settingsstr = get_string('settings');
977 $deletestr = get_string('delete');
978 //retrieve list of instances. In administration context we want to display all
979 //instances of a type, even if this type is not visible. In course/user context we
980 //want to display only visible instances, but for every type types. The repository::get_instances()
981 //third parameter displays only visible type.
983 $params['context'] = array($context, get_system_context());
984 $params['currentcontext'] = $context;
985 $params['onlyvisible'] = !$admin;
986 $params['type'] = $typename;
987 $instances = repository::get_instances($params);
988 $instancesnumber = count($instances);
989 $alreadyplugins = array();
991 $table = new html_table();
992 $table->head = array($namestr, $pluginstr, $settingsstr, $deletestr);
993 $table->align = array('left', 'left', 'center','center');
994 $table->data = array();
998 foreach ($instances as $i) {
1002 $type = repository::get_type_by_id($i->options['typeid']);
1004 if ($type->get_contextvisibility($context)) {
1005 if (!$i->readonly) {
1007 $url->param('type', $i->options['type']);
1008 $url->param('edit', $i->id);
1009 $settings .= html_writer::link($url, $settingsstr);
1011 $url->remove_params('edit');
1012 $url->param('delete', $i->id);
1013 $delete .= html_writer::link($url, $deletestr);
1015 $url->remove_params('type');
1019 $type = repository::get_type_by_id($i->options['typeid']);
1020 $table->data[] = array($i->name, $type->get_readablename(), $settings, $delete);
1022 //display a grey row if the type is defined as not visible
1023 if (isset($type) && !$type->get_visible()) {
1024 $table->rowclasses[] = 'dimmed_text';
1026 $table->rowclasses[] = '';
1029 if (!in_array($i->name, $alreadyplugins)) {
1030 $alreadyplugins[] = $i->name;
1033 $output .= html_writer::table($table);
1034 $instancehtml = '<div>';
1037 //if no type is set, we can create all type of instance
1039 $instancehtml .= '<h3>';
1040 $instancehtml .= get_string('createrepository', 'repository');
1041 $instancehtml .= '</h3><ul>';
1042 $types = repository::get_editable_types($context);
1043 foreach ($types as $type) {
1044 if (!empty($type) && $type->get_visible()) {
1045 $instanceoptionnames = repository::static_function($type->get_typename(), 'get_instance_option_names');
1046 if (!empty($instanceoptionnames)) {
1047 $instancehtml .= '<li><a href="'.$baseurl.'&new='.$type->get_typename().'">'.get_string('createxxinstance', 'repository', get_string('repositoryname', 'repository_'.$type->get_typename()))
1053 $instancehtml .= '</ul>';
1056 $instanceoptionnames = repository::static_function($typename, 'get_instance_option_names');
1057 if (!empty($instanceoptionnames)) { //create a unique type of instance
1059 $instancehtml .= "<form action='".$baseurl."&new=".$typename."' method='post'>
1060 <p style='text-align:center'><input type='submit' value='".get_string('createinstance', 'repository')."'/></p>
1066 $instancehtml .= '</div>';
1067 $output .= $instancehtml;
1070 $output .= $OUTPUT->box_end();
1072 //print the list + creation links
1077 * Decide where to save the file, can be
1078 * reused by sub class
1079 * @param string filename
1081 public function prepare_file($filename) {
1083 if (!file_exists($CFG->dataroot.'/temp/download')) {
1084 mkdir($CFG->dataroot.'/temp/download/', $CFG->directorypermissions, true);
1086 if (is_dir($CFG->dataroot.'/temp/download')) {
1087 $dir = $CFG->dataroot.'/temp/download/';
1089 if (empty($filename)) {
1090 $filename = uniqid('repo').'_'.time().'.tmp';
1092 if (file_exists($dir.$filename)) {
1093 $filename = uniqid('m').$filename;
1095 return $dir.$filename;
1099 * Return file URL, for most plugins, the parameter is the original
1100 * url, but some plugins use a file id, so we need this function to
1101 * convert file id to original url.
1103 * @param string $url the url of file
1106 public function get_link($url) {
1111 * Download a file, this function can be overridden by
1114 * @global object $CFG
1115 * @param string $url the url of file
1116 * @param string $filename save location
1117 * @return string the location of the file
1120 public function get_file($url, $filename = '') {
1122 $path = $this->prepare_file($filename);
1123 $fp = fopen($path, 'w');
1125 $c->download(array(array('url'=>$url, 'file'=>$fp)));
1126 return array('path'=>$path, 'url'=>$url);
1130 * Return is the instance is visible
1131 * (is the type visible ? is the context enable ?)
1134 public function is_visible() {
1135 $type = repository::get_type_by_id($this->options['typeid']);
1136 $instanceoptions = repository::static_function($type->get_typename(), 'get_instance_option_names');
1138 if ($type->get_visible()) {
1139 //if the instance is unique so it's visible, otherwise check if the instance has a enabled context
1140 if (empty($instanceoptions) || $type->get_contextvisibility($this->context)) {
1149 * Return the name of this instance, can be overridden.
1150 * @global object $DB
1153 public function get_name() {
1155 // We always verify instance id from database,
1156 // so we always know repository name before init
1157 // a repository, so we don't enquery repository
1158 // name from database again here.
1159 if (isset($this->options['name'])) {
1160 return $this->options['name'];
1162 if ( $repo = $DB->get_record('repository_instances', array('id'=>$this->id)) ) {
1171 * what kind of files will be in this repository?
1172 * @return array return '*' means this repository support any files, otherwise
1173 * return mimetypes of files, it can be an array
1175 public function supported_filetypes() {
1176 // return array('text/plain', 'image/gif');
1181 * does it return a file url or a item_id
1184 public function supported_returntypes() {
1185 return (FILE_INTERNAL | FILE_EXTERNAL);
1189 * Provide repository instance information for Ajax
1190 * @global object $CFG
1193 final public function get_meta() {
1194 global $CFG, $OUTPUT;
1195 $ft = new filetype_parser;
1196 $meta = new stdclass;
1197 $meta->id = $this->id;
1198 $meta->name = $this->get_name();
1199 $meta->type = $this->options['type'];
1200 $meta->icon = $OUTPUT->pix_url('icon', 'repository_'.$meta->type)->out(false);
1201 $meta->supported_types = $ft->get_extensions($this->supported_filetypes());
1202 $meta->return_types = $this->supported_returntypes();
1207 * Create an instance for this plug-in
1208 * @global object $CFG
1209 * @global object $DB
1210 * @param string $type the type of the repository
1211 * @param integer $userid the user id
1212 * @param object $context the context
1213 * @param array $params the options for this instance
1214 * @param integer $readonly whether to create it readonly or not (defaults to not)
1217 public static function create($type, $userid, $context, $params, $readonly=0) {
1219 $params = (array)$params;
1220 require_once($CFG->dirroot . '/repository/'. $type . '/repository.class.php');
1221 $classname = 'repository_' . $type;
1222 if ($repo = $DB->get_record('repository', array('type'=>$type))) {
1223 $record = new stdclass;
1224 $record->name = $params['name'];
1225 $record->typeid = $repo->id;
1226 $record->timecreated = time();
1227 $record->timemodified = time();
1228 $record->contextid = $context->id;
1229 $record->readonly = $readonly;
1230 $record->userid = $userid;
1231 $id = $DB->insert_record('repository_instances', $record);
1233 $configs = call_user_func($classname . '::get_instance_option_names');
1234 if (!empty($configs)) {
1235 foreach ($configs as $config) {
1236 $options[$config] = $params[$config];
1241 unset($options['name']);
1242 $instance = repository::get_instance($id);
1243 $instance->set_option($options);
1254 * delete a repository instance
1255 * @global object $DB
1258 final public function delete() {
1260 $DB->delete_records('repository_instances', array('id'=>$this->id));
1261 $DB->delete_records('repository_instance_config', array('instanceid'=>$this->id));
1266 * Hide/Show a repository
1267 * @global object $DB
1268 * @param string $hide
1271 final public function hide($hide = 'toggle') {
1273 if ($entry = $DB->get_record('repository', array('id'=>$this->id))) {
1274 if ($hide === 'toggle' ) {
1275 if (!empty($entry->visible)) {
1276 $entry->visible = 0;
1278 $entry->visible = 1;
1281 if (!empty($hide)) {
1282 $entry->visible = 0;
1284 $entry->visible = 1;
1287 return $DB->update_record('repository', $entry);
1293 * Cache login details for repositories
1294 * @global object $DB
1295 * @param string $username
1296 * @param string $password
1297 * @param integer $userid The id of specific user
1298 * @return integer Id of the record
1300 public function store_login($username = '', $password = '', $userid = 1) {
1303 $repository = new stdclass;
1304 if (!empty($this->id)) {
1305 $repository->id = $this->id;
1307 $repository->userid = $userid;
1308 $repository->repositorytype = $this->type;
1309 $repository->contextid = $this->context->id;
1311 if ($entry = $DB->get_record('repository', $repository)) {
1312 $repository->id = $entry->id;
1313 $repository->username = $username;
1314 $repository->password = $password;
1315 return $DB->update_record('repository', $repository);
1317 $repository->username = $username;
1318 $repository->password = $password;
1319 return $DB->insert_record('repository', $repository);
1324 * Save settings for repository instance
1325 * $repo->set_option(array('api_key'=>'f2188bde132', 'name'=>'dongsheng'));
1326 * @global object $DB
1327 * @param array $options settings
1328 * @return int Id of the record
1330 public function set_option($options = array()) {
1333 if (!empty($options['name'])) {
1336 $r->name = $options['name'];
1337 $DB->update_record('repository_instances', $r);
1338 unset($options['name']);
1341 foreach ($options as $name=>$value) {
1342 if ($id = $DB->get_field('repository_instance_config', 'id', array('name'=>$name, 'instanceid'=>$this->id))) {
1343 $result = $result && $DB->set_field('repository_instance_config', 'value', $value, array('id'=>$id));
1345 $config = new object();
1346 $config->instanceid = $this->id;
1347 $config->name = $name;
1348 $config->value = $value;
1349 $result = $result && $DB->insert_record('repository_instance_config', $config);
1356 * Get settings for repository instance
1357 * @global object $DB
1358 * @param string $config
1359 * @return array Settings
1361 public function get_option($config = '') {
1363 $entries = $DB->get_records('repository_instance_config', array('instanceid'=>$this->id));
1365 if (empty($entries)) {
1368 foreach($entries as $entry) {
1369 $ret[$entry->name] = $entry->value;
1371 if (!empty($config)) {
1372 return $ret[$config];
1378 public function filter(&$value) {
1380 $accepted_types = optional_param('accepted_types', '', PARAM_RAW);
1381 $ft = new filetype_parser;
1382 //$ext = $ft->get_extensions($this->supported_filetypes());
1383 if (isset($value['children'])) {
1385 if (!empty($value['children'])) {
1386 $value['children'] = array_filter($value['children'], array($this, 'filter'));
1389 if ($accepted_types == '*' or empty($accepted_types)
1390 or (is_array($accepted_types) and in_array('*', $accepted_types))) {
1392 } elseif (is_array($accepted_types)) {
1393 foreach ($accepted_types as $type) {
1394 $extensions = $ft->get_extensions($type);
1395 if (!is_array($extensions)) {
1398 foreach ($extensions as $ext) {
1399 if (preg_match('#'.$ext.'$#', $value['title'])) {
1411 * Given a path, and perhaps a search, get a list of files.
1413 * See details on http://docs.moodle.org/en/Development:Repository_plugins
1415 * @param string $path, this parameter can
1416 * a folder name, or a identification of folder
1417 * @param string $page, the page number of file list
1418 * @return array the list of files, including meta infomation, containing the following keys
1419 * manage, url to manage url
1422 * repo_id, active repository id
1423 * login_btn_action, the login button action
1424 * login_btn_label, the login button label
1425 * total, number of results
1426 * perpage, items per page
1428 * pages, total pages
1429 * search_result, is it a search result?
1431 * path, current path and parent path
1433 public function get_listing($path = '', $page = '') {
1437 * Search files in repository
1438 * When doing global search, $search_text will be used as
1441 * @return mixed, see get_listing()
1443 public function search($search_text) {
1445 $list['list'] = array();
1450 * Logout from repository instance
1451 * By default, this function will return a login form
1455 public function logout(){
1456 return $this->print_login();
1460 * To check whether the user is logged in.
1464 public function check_login(){
1470 * Show the login screen, if required
1472 public function print_login(){
1473 return $this->get_listing();
1477 * Show the search screen, if required
1480 public function print_search() {
1482 $str .= '<input type="hidden" name="repo_id" value="'.$this->id.'" />';
1483 $str .= '<input type="hidden" name="ctx_id" value="'.$this->context->id.'" />';
1484 $str .= '<input type="hidden" name="seekey" value="'.sesskey().'" />';
1485 $str .= '<label>'.get_string('keyword', 'repository').': </label><br/><input name="s" value="" /><br/>';
1490 * For oauth like external authentication, when external repository direct user back to moodle,
1491 * this funciton will be called to set up token and token_secret
1493 public function callback() {
1497 * is it possible to do glboal search?
1500 public function global_search() {
1505 * Defines operations that happen occasionally on cron
1508 public function cron() {
1513 * function which is run when the type is created (moodle administrator add the plugin)
1514 * @return boolean success or fail?
1516 public static function plugin_init() {
1521 * Edit/Create Admin Settings Moodle form
1522 * @param object $ Moodle form (passed by reference)
1524 public function type_config_form($mform) {
1528 * Edit/Create Instance Settings Moodle form
1529 * @param object $ Moodle form (passed by reference)
1531 public function instance_config_form($mform) {
1535 * Return names of the general options
1536 * By default: no general option name
1539 public static function get_type_option_names() {
1544 * Return names of the instance options
1545 * By default: no instance option name
1548 public static function get_instance_option_names() {
1551 public function get_short_filename($str, $maxlength) {
1552 if (strlen($str) >= $maxlength) {
1553 return trim(substr($str, 0, $maxlength)).'...';
1561 * Exception class for repository api
1564 * @package moodlecore
1565 * @subpackage repository
1566 * @copyright 2009 Dongsheng Cai <dongsheng@moodle.com>
1567 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1569 class repository_exception extends moodle_exception {
1575 * This is a class used to define a repository instance form
1578 * @package moodlecore
1579 * @subpackage repository
1580 * @copyright 2009 Dongsheng Cai <dongsheng@moodle.com>
1581 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1583 final class repository_instance_form extends moodleform {
1584 protected $instance;
1586 protected function add_defaults() {
1587 $mform =& $this->_form;
1588 $strrequired = get_string('required');
1590 $mform->addElement('hidden', 'edit', ($this->instance) ? $this->instance->id : 0);
1591 $mform->setType('edit', PARAM_INT);
1592 $mform->addElement('hidden', 'new', $this->plugin);
1593 $mform->setType('new', PARAM_FORMAT);
1594 $mform->addElement('hidden', 'plugin', $this->plugin);
1595 $mform->setType('plugin', PARAM_SAFEDIR);
1596 $mform->addElement('hidden', 'typeid', $this->typeid);
1597 $mform->setType('typeid', PARAM_INT);
1598 $mform->addElement('hidden', 'contextid', $this->contextid);
1599 $mform->setType('contextid', PARAM_INT);
1601 $mform->addElement('text', 'name', get_string('name'), 'maxlength="100" size="30"');
1602 $mform->addRule('name', $strrequired, 'required', null, 'client');
1605 public function definition() {
1607 // type of plugin, string
1608 $this->plugin = $this->_customdata['plugin'];
1609 $this->typeid = $this->_customdata['typeid'];
1610 $this->contextid = $this->_customdata['contextid'];
1611 $this->instance = (isset($this->_customdata['instance'])
1612 && is_subclass_of($this->_customdata['instance'], 'repository'))
1613 ? $this->_customdata['instance'] : null;
1615 $mform =& $this->_form;
1617 $this->add_defaults();
1619 if (!$this->instance) {
1620 $result = repository::static_function($this->plugin, 'instance_config_form', $mform);
1621 if ($result === false) {
1622 $mform->removeElement('name');
1626 $data['name'] = $this->instance->name;
1627 if (!$this->instance->readonly) {
1628 $result = $this->instance->instance_config_form($mform);
1629 if ($result === false) {
1630 $mform->removeElement('name');
1632 // and set the data if we have some.
1633 foreach ($this->instance->get_instance_option_names() as $config) {
1634 if (!empty($this->instance->options[$config])) {
1635 $data[$config] = $this->instance->options[$config];
1637 $data[$config] = '';
1641 $this->set_data($data);
1644 if ($result === false) {
1645 $mform->addElement('cancel');
1647 $this->add_action_buttons(true, get_string('save','repository'));
1651 public function validation($data) {
1655 $sql = "SELECT count('x')
1656 FROM {repository_instances} i, {repository} r
1657 WHERE r.type=:plugin AND r.id=i.typeid AND i.name=:name";
1658 if ($DB->count_records_sql($sql, array('name' => $data['name'], 'plugin' => $data['plugin'])) > 1) {
1659 $errors = array('name' => get_string('err_uniquename', 'repository'));
1667 * This is a class used to define a repository type setting form
1670 * @package moodlecore
1671 * @subpackage repository
1672 * @copyright 2009 Dongsheng Cai <dongsheng@moodle.com>
1673 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1675 final class repository_type_form extends moodleform {
1676 protected $instance;
1681 * Definition of the moodleform
1682 * @global object $CFG
1684 public function definition() {
1686 // type of plugin, string
1687 $this->plugin = $this->_customdata['plugin'];
1688 $this->instance = (isset($this->_customdata['instance'])
1689 && is_a($this->_customdata['instance'], 'repository_type'))
1690 ? $this->_customdata['instance'] : null;
1692 $this->action = $this->_customdata['action'];
1693 $mform =& $this->_form;
1694 $strrequired = get_string('required');
1696 $mform->addElement('hidden', 'repos', ($this->instance) ? $this->instance->get_typename() : 0);
1697 $mform->setType('repos', PARAM_INT);
1698 $mform->addElement('hidden', 'repos', $this->plugin);
1699 $mform->setType('repos', PARAM_FORMAT);
1700 $mform->addElement('hidden', 'action', $this->action);
1701 $mform->setType('action', PARAM_TEXT);
1702 $mform->addElement('hidden', 'repos', $this->plugin);
1703 $mform->setType('repos', PARAM_SAFEDIR);
1705 // let the plugin add its specific fields
1706 if (!$this->instance) {
1707 $result = repository::static_function($this->plugin, 'type_config_form', $mform);
1709 $classname = 'repository_' . $this->instance->get_typename();
1710 $result = call_user_func(array($classname, 'type_config_form'), $mform);
1713 //add "enable course/user instances" checkboxes if multiple instances are allowed
1714 $instanceoptionnames = repository::static_function($this->plugin, 'get_instance_option_names');
1715 if (!empty($instanceoptionnames)){
1716 $mform->addElement('checkbox', 'enablecourseinstances', get_string('enablecourseinstances', 'repository'));
1717 $mform->addElement('checkbox', 'enableuserinstances', get_string('enableuserinstances', 'repository'));
1720 // set the data if we have some.
1721 if ($this->instance) {
1723 $option_names = call_user_func(array($classname,'get_type_option_names'));
1724 if (!empty($instanceoptionnames)){
1725 $option_names[] = 'enablecourseinstances';
1726 $option_names[] = 'enableuserinstances';
1729 $instanceoptions = $this->instance->get_options();
1730 foreach ($option_names as $config) {
1731 if (!empty($instanceoptions[$config])) {
1732 $data[$config] = $instanceoptions[$config];
1734 $data[$config] = '';
1737 $this->set_data($data);
1740 $this->add_action_buttons(true, get_string('save','repository'));
1745 * Generate all options needed by filepicker
1747 * @param array $args, including following keys
1752 * @return array the list of repository instances, including meta infomation, containing the following keys
1757 function initialise_filepicker($args) {
1758 global $CFG, $USER, $PAGE, $OUTPUT;
1759 require_once($CFG->libdir . '/licenselib.php');
1761 $return = new stdclass;
1762 $licenses = array();
1763 if (!empty($CFG->licenses)) {
1764 $array = explode(',', $CFG->licenses);
1765 foreach ($array as $license) {
1767 $l->shortname = $license;
1768 $l->fullname = get_string($license, 'license');
1772 if (!empty($CFG->sitedefaultlicense)) {
1773 $return->defaultlicense = $CFG->sitedefaultlicense;
1776 $return->licenses = $licenses;
1778 $return->author = fullname($USER);
1780 $ft = new filetype_parser();
1781 if (empty($args->context)) {
1782 $context = $PAGE->context;
1784 $context = $args->context;
1786 $disable_types = array();
1787 if (!empty($args->disable_types)) {
1788 $disable_types = $args->disable_types;
1791 $user_context = get_context_instance(CONTEXT_USER, $USER->id);
1793 $externallink = (int)get_config(null, 'repositoryallowexternallinks');
1794 $repositories = repository::get_instances(array(
1795 'context'=>array($user_context, get_system_context()),
1796 'currentcontext'=> $context,
1797 'accepted_types'=>$args->accepted_types,
1798 'return_types'=>$args->return_types,
1799 'disable_types'=>$disable_types
1802 $return->repositories = array();
1804 if (empty($externallink)) {
1805 $return->externallink = false;
1807 $return->externallink = true;
1810 // provided by form element
1811 $return->accepted_types = $ft->get_extensions($args->accepted_types);
1812 foreach ($repositories as $repository) {
1813 $meta = $repository->get_meta();
1814 $return->repositories[$repository->id] = $meta;
1820 * The plugins should be enabled by defaulted once moodle installed
1822 * @global object $OUTPUT
1826 function repository_setup_default_plugins() {
1828 //if the plugin type has no multiple instance (e.g. has no instance option name)
1829 //repository_type::create will create an instance automatically
1830 $user_plugin = new repository_type('user', array(), true);
1831 $user_plugin->create(true);
1833 $recent_plugin = new repository_type('recent', array(), true);
1834 $recent_plugin->create(true);
1836 $upload_plugin = new repository_type('upload', array(), true);
1837 $upload_plugin->create(true);
1839 $local_plugin = new repository_type('local', array(), true);
1840 $local_plugin->create(true);
1842 echo $OUTPUT->notification(get_string('setupdefaultplugins', 'repository'), 'notifysuccess');