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);
36 define('RENAME_SUFFIX', '_2');
39 * This class is used to manage repository plugins
41 * A repository_type is a repository plug-in. It can be Box.net, Flick-r, ...
42 * A repository type can be edited, sorted and hidden. It is mandatory for an
43 * administrator to create a repository type in order to be able to create
44 * some instances of this type.
46 * - a repository_type object is mapped to the "repository" database table
47 * - "typename" attibut maps the "type" database field. It is unique.
48 * - general "options" for a repository type are saved in the config_plugin table
49 * - when you delete a repository, all instances are deleted, and general
50 * options are also deleted from database
51 * - When you create a type for a plugin that can't have multiple instances, a
52 * instance is automatically created.
55 * @subpackage repository
56 * @copyright 2009 Jerome Mouneyrac
57 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
59 class repository_type
{
63 * Type name (no whitespace) - A type name is unique
64 * Note: for a user-friendly type name see get_readablename()
71 * Options of this type
72 * They are general options that any instance of this type would share
74 * These options are saved in config_plugin table
81 * Is the repository type visible or hidden
82 * If false (hidden): no instances can be created, edited, deleted, showned , used...
89 * 0 => not ordered, 1 => first position, 2 => second position...
90 * A not order type would appear in first position (should never happened)
96 * Return if the instance is visible in a context
97 * TODO: check if the context visibility has been overwritten by the plugin creator
98 * (need to create special functions to be overvwritten in repository class)
99 * @param objet $context - context
102 public function get_contextvisibility($context) {
105 if ($context->contextlevel
== CONTEXT_COURSE
) {
106 return $this->_options
['enablecourseinstances'];
109 if ($context->contextlevel
== CONTEXT_USER
) {
110 return $this->_options
['enableuserinstances'];
113 //the context is SITE
120 * repository_type constructor
121 * @global object $CFG
122 * @param integer $typename
123 * @param array $typeoptions
124 * @param boolean $visible
125 * @param integer $sortorder (don't really need set, it will be during create() call)
127 public function __construct($typename = '', $typeoptions = array(), $visible = true, $sortorder = 0) {
131 $this->_typename
= $typename;
132 $this->_visible
= $visible;
133 $this->_sortorder
= $sortorder;
135 //set options attribut
136 $this->_options
= array();
137 $options = repository
::static_function($typename, 'get_type_option_names');
138 //check that the type can be setup
139 if (!empty($options)) {
140 //set the type options
141 foreach ($options as $config) {
142 if (array_key_exists($config, $typeoptions)) {
143 $this->_options
[$config] = $typeoptions[$config];
148 //retrieve visibility from option
149 if (array_key_exists('enablecourseinstances',$typeoptions)) {
150 $this->_options
['enablecourseinstances'] = $typeoptions['enablecourseinstances'];
152 $this->_options
['enablecourseinstances'] = 0;
155 if (array_key_exists('enableuserinstances',$typeoptions)) {
156 $this->_options
['enableuserinstances'] = $typeoptions['enableuserinstances'];
158 $this->_options
['enableuserinstances'] = 0;
164 * Get the type name (no whitespace)
165 * For a human readable name, use get_readablename()
166 * @return String the type name
168 public function get_typename() {
169 return $this->_typename
;
173 * Return a human readable and user-friendly type name
174 * @return string user-friendly type name
176 public function get_readablename() {
177 return get_string('pluginname','repository_'.$this->_typename
);
181 * Return general options
182 * @return array the general options
184 public function get_options() {
185 return $this->_options
;
192 public function get_visible() {
193 return $this->_visible
;
197 * Return order / position of display in the file picker
200 public function get_sortorder() {
201 return $this->_sortorder
;
205 * Create a repository type (the type name must not already exist)
206 * @param boolean throw exception?
207 * @return mixed return int if create successfully, return false if
211 public function create($silent = false) {
214 //check that $type has been set
215 $timmedtype = trim($this->_typename
);
216 if (empty($timmedtype)) {
217 throw new repository_exception('emptytype', 'repository');
220 //set sortorder as the last position in the list
221 if (!isset($this->_sortorder
) ||
$this->_sortorder
== 0 ) {
222 $sql = "SELECT MAX(sortorder) FROM {repository}";
223 $this->_sortorder
= 1 +
$DB->get_field_sql($sql);
226 //only create a new type if it doesn't already exist
227 $existingtype = $DB->get_record('repository', array('type'=>$this->_typename
));
228 if (!$existingtype) {
230 $newtype = new stdClass();
231 $newtype->type
= $this->_typename
;
232 $newtype->visible
= $this->_visible
;
233 $newtype->sortorder
= $this->_sortorder
;
234 $plugin_id = $DB->insert_record('repository', $newtype);
235 //save the options in DB
236 $this->update_options();
238 $instanceoptionnames = repository
::static_function($this->_typename
, 'get_instance_option_names');
240 //if the plugin type has no multiple instance (e.g. has no instance option name) so it wont
241 //be possible for the administrator to create a instance
242 //in this case we need to create an instance
243 if (empty($instanceoptionnames)) {
244 $instanceoptions = array();
245 if (empty($this->_options
['pluginname'])) {
246 // when moodle trying to install some repo plugin automatically
247 // this option will be empty, get it from language string when display
248 $instanceoptions['name'] = '';
250 // when admin trying to add a plugin manually, he will type a name
252 $instanceoptions['name'] = $this->_options
['pluginname'];
254 repository
::static_function($this->_typename
, 'create', $this->_typename
, 0, get_system_context(), $instanceoptions);
256 //run plugin_init function
257 if (!repository
::static_function($this->_typename
, 'plugin_init')) {
259 throw new repository_exception('cannotinitplugin', 'repository');
263 if(!empty($plugin_id)) {
264 // return plugin_id if create successfully
272 throw new repository_exception('existingrepository', 'repository');
274 // If plugin existed, return false, tell caller no new plugins were created.
281 * Update plugin options into the config_plugin table
282 * @param array $options
285 public function update_options($options = null) {
287 $classname = 'repository_' . $this->_typename
;
288 $instanceoptions = repository
::static_function($this->_typename
, 'get_instance_option_names');
289 if (empty($instanceoptions)) {
290 // update repository instance name if this plugin type doesn't have muliti instances
292 $params['type'] = $this->_typename
;
293 $instances = repository
::get_instances($params);
294 $instance = array_pop($instances);
296 $DB->set_field('repository_instances', 'name', $options['pluginname'], array('id'=>$instance->id
));
298 unset($options['pluginname']);
301 if (!empty($options)) {
302 $this->_options
= $options;
305 foreach ($this->_options
as $name => $value) {
306 set_config($name, $value, $this->_typename
);
313 * Update visible database field with the value given as parameter
314 * or with the visible value of this object
315 * This function is private.
316 * For public access, have a look to switch_and_update_visibility()
318 * @param boolean $visible
321 private function update_visible($visible = null) {
324 if (!empty($visible)) {
325 $this->_visible
= $visible;
327 else if (!isset($this->_visible
)) {
328 throw new repository_exception('updateemptyvisible', 'repository');
331 return $DB->set_field('repository', 'visible', $this->_visible
, array('type'=>$this->_typename
));
335 * Update database sortorder field with the value given as parameter
336 * or with the sortorder value of this object
337 * This function is private.
338 * For public access, have a look to move_order()
340 * @param integer $sortorder
343 private function update_sortorder($sortorder = null) {
346 if (!empty($sortorder) && $sortorder!=0) {
347 $this->_sortorder
= $sortorder;
349 //if sortorder is not set, we set it as the ;ast position in the list
350 else if (!isset($this->_sortorder
) ||
$this->_sortorder
== 0 ) {
351 $sql = "SELECT MAX(sortorder) FROM {repository}";
352 $this->_sortorder
= 1 +
$DB->get_field_sql($sql);
355 return $DB->set_field('repository', 'sortorder', $this->_sortorder
, array('type'=>$this->_typename
));
359 * Change order of the type with its adjacent upper or downer type
360 * (database fields are updated)
362 * 1. retrieve all types in an array. This array is sorted by sortorder,
363 * and the array keys start from 0 to X (incremented by 1)
364 * 2. switch sortorder values of this type and its adjacent type
366 * @param string $move "up" or "down"
368 public function move_order($move) {
371 $types = repository
::get_types(); // retrieve all types
373 /// retrieve this type into the returned array
375 while (!isset($indice) && $i<count($types)) {
376 if ($types[$i]->get_typename() == $this->_typename
) {
382 /// retrieve adjacent indice
385 $adjacentindice = $indice - 1;
388 $adjacentindice = $indice +
1;
391 throw new repository_exception('movenotdefined', 'repository');
394 //switch sortorder of this type and the adjacent type
395 //TODO: we could reset sortorder for all types. This is not as good in performance term, but
396 //that prevent from wrong behaviour on a screwed database. As performance are not important in this particular case
397 //it worth to change the algo.
398 if ($adjacentindice>=0 && !empty($types[$adjacentindice])) {
399 $DB->set_field('repository', 'sortorder', $this->_sortorder
, array('type'=>$types[$adjacentindice]->get_typename()));
400 $this->update_sortorder($types[$adjacentindice]->get_sortorder());
405 * 1. Change visibility to the value chosen
410 public function update_visibility($visible = null) {
411 if (is_bool($visible)) {
412 $this->_visible
= $visible;
414 $this->_visible
= !$this->_visible
;
416 return $this->update_visible();
421 * Delete a repository_type (general options are removed from config_plugin
422 * table, and all instances are deleted)
426 public function delete() {
429 //delete all instances of this type
431 $params['context'] = array();
432 $params['onlyvisible'] = false;
433 $params['type'] = $this->_typename
;
434 $instances = repository
::get_instances($params);
435 foreach ($instances as $instance) {
439 //delete all general options
440 foreach ($this->_options
as $name => $value) {
441 set_config($name, null, $this->_typename
);
444 return $DB->delete_records('repository', array('type' => $this->_typename
));
449 * This is the base class of the repository class
451 * To use repository plugin, see:
452 * http://docs.moodle.org/dev/Repository_How_to_Create_Plugin
453 * class repository is an abstract class, some functions must be implemented in subclass.
454 * See an example: repository/boxnet/lib.php
457 * // for ajax file picker, this will print a json string to tell file picker
458 * // how to build a login form
459 * $repo->print_login();
460 * // for ajax file picker, this will return a files list.
461 * $repo->get_listing();
462 * // this function will be used for non-javascript version.
463 * $repo->print_listing();
464 * // print a search box
465 * $repo->print_search();
467 * @package moodlecore
468 * @subpackage repository
469 * @copyright 2009 Dongsheng Cai <dongsheng@moodle.com>
470 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
472 abstract class repository
{
473 // $disabled can be set to true to disable a plugin by force
474 // example: self::$disabled = true
475 public $disabled = false;
477 /** @var object current context */
482 /** @var object repository instance database record */
485 * 1. Initialize context and options
486 * 2. Accept necessary parameters
488 * @param integer $repositoryid repository instance id
489 * @param integer|object a context id or context object
490 * @param array $options repository options
492 public function __construct($repositoryid, $context = SYSCONTEXTID
, $options = array(), $readonly = 0) {
494 $this->id
= $repositoryid;
495 if (is_object($context)) {
496 $this->context
= $context;
498 $this->context
= get_context_instance_by_id($context);
500 $this->instance
= $DB->get_record('repository_instances', array('id'=>$this->id
));
501 $this->readonly
= $readonly;
502 $this->options
= array();
504 if (is_array($options)) {
505 $options = array_merge($this->get_option(), $options);
507 $options = $this->get_option();
509 foreach ($options as $n => $v) {
510 $this->options
[$n] = $v;
512 $this->name
= $this->get_name();
513 $this->returntypes
= $this->supported_returntypes();
514 $this->super_called
= true;
518 * Get a repository type object by a given type name.
520 * @param string $typename the repository type name
521 * @return repository_type|bool
523 public static function get_type_by_typename($typename) {
526 if (!$record = $DB->get_record('repository',array('type' => $typename))) {
530 return new repository_type($typename, (array)get_config($typename), $record->visible
, $record->sortorder
);
534 * Get the repository type by a given repository type id.
536 * @param int $id the type id
539 public static function get_type_by_id($id) {
542 if (!$record = $DB->get_record('repository',array('id' => $id))) {
546 return new repository_type($record->type
, (array)get_config($record->type
), $record->visible
, $record->sortorder
);
550 * Return all repository types ordered by sortorder field
551 * first repository type in returnedarray[0], second repository type in returnedarray[1], ...
553 * @global object $CFG
554 * @param boolean $visible can return types by visiblity, return all types if null
555 * @return array Repository types
557 public static function get_types($visible=null) {
562 if (!empty($visible)) {
563 $params = array('visible' => $visible);
565 if ($records = $DB->get_records('repository',$params,'sortorder')) {
566 foreach($records as $type) {
567 if (file_exists($CFG->dirroot
. '/repository/'. $type->type
.'/lib.php')) {
568 $types[] = new repository_type($type->type
, (array)get_config($type->type
), $type->visible
, $type->sortorder
);
577 * To check if the context id is valid
578 * @global object $USER
579 * @param int $contextid
582 public static function check_capability($contextid, $instance) {
583 $context = get_context_instance_by_id($contextid);
584 $capability = has_capability('repository/'.$instance->type
.':view', $context);
586 throw new repository_exception('nopermissiontoaccess', 'repository');
591 * Check if file already exists in draft area
594 * @param string $filepath
595 * @param string $filename
598 public static function draftfile_exists($itemid, $filepath, $filename) {
600 $fs = get_file_storage();
601 $usercontext = get_context_instance(CONTEXT_USER
, $USER->id
);
602 if ($fs->get_file($usercontext->id
, 'user', 'draft', $itemid, $filepath, $filename)) {
610 * Does this repository used to browse moodle files?
614 public function has_moodle_files() {
618 * This function is used to copy a moodle file to draft area
620 * @global object $USER
622 * @param string $encoded The metainfo of file, it is base64 encoded php serialized data
623 * @param string $draftitemid itemid
624 * @param string $new_filename The intended name of file
625 * @param string $new_filepath the new path in draft area
626 * @return array The information of file
628 public function copy_to_area($encoded, $draftitemid, $new_filepath, $new_filename) {
631 if ($this->has_moodle_files() == false) {
632 throw new coding_exception('Only repository used to browse moodle files can use copy_to_area');
635 $browser = get_file_browser();
636 $params = unserialize(base64_decode($encoded));
637 $user_context = get_context_instance(CONTEXT_USER
, $USER->id
);
639 $contextid = clean_param($params['contextid'], PARAM_INT
);
640 $fileitemid = clean_param($params['itemid'], PARAM_INT
);
641 $filename = clean_param($params['filename'], PARAM_FILE
);
642 $filepath = clean_param($params['filepath'], PARAM_PATH
);;
643 $filearea = clean_param($params['filearea'], PARAM_AREA
);
644 $component = clean_param($params['component'], PARAM_COMPONENT
);
646 $context = get_context_instance_by_id($contextid);
647 // the file needs to copied to draft area
648 $file_info = $browser->get_file_info($context, $component, $filearea, $fileitemid, $filepath, $filename);
650 if (repository
::draftfile_exists($draftitemid, $new_filepath, $new_filename)) {
652 $unused_filename = repository
::get_unused_filename($draftitemid, $new_filepath, $new_filename);
653 $file_info->copy_to_storage($user_context->id
, 'user', 'draft', $draftitemid, $new_filepath, $unused_filename);
655 $event['event'] = 'fileexists';
656 $event['newfile'] = new stdClass
;
657 $event['newfile']->filepath
= $new_filepath;
658 $event['newfile']->filename
= $unused_filename;
659 $event['newfile']->url
= moodle_url
::make_draftfile_url($draftitemid, $new_filepath, $unused_filename)->out();
660 $event['existingfile'] = new stdClass
;
661 $event['existingfile']->filepath
= $new_filepath;
662 $event['existingfile']->filename
= $new_filename;
663 $event['existingfile']->url
= moodle_url
::make_draftfile_url($draftitemid, $filepath, $filename)->out();;
666 $file_info->copy_to_storage($user_context->id
, 'user', 'draft', $draftitemid, $new_filepath, $new_filename);
668 $info['itemid'] = $draftitemid;
669 $info['title'] = $new_filename;
670 $info['contextid'] = $user_context->id
;
671 $info['url'] = moodle_url
::make_draftfile_url($draftitemid, $new_filepath, $new_filename)->out();;
672 $info['filesize'] = $file_info->get_filesize();
678 * Get unused filename by appending suffix
681 * @param string $filepath
682 * @param string $filename
685 public static function get_unused_filename($itemid, $filepath, $filename) {
687 $fs = get_file_storage();
688 while (repository
::draftfile_exists($itemid, $filepath, $filename)) {
689 $filename = repository
::append_suffix($filename);
695 * Append a suffix to filename
697 * @param string $filename
700 function append_suffix($filename) {
701 $pathinfo = pathinfo($filename);
702 if (empty($pathinfo['extension'])) {
703 return $filename . RENAME_SUFFIX
;
705 return $pathinfo['filename'] . RENAME_SUFFIX
. '.' . $pathinfo['extension'];
710 * Return all types that you a user can create/edit and which are also visible
711 * Note: Mostly used in order to know if at least one editable type can be set
712 * @param object $context the context for which we want the editable types
713 * @return array types
715 public static function get_editable_types($context = null) {
717 if (empty($context)) {
718 $context = get_system_context();
721 $types= repository
::get_types(true);
722 $editabletypes = array();
723 foreach ($types as $type) {
724 $instanceoptionnames = repository
::static_function($type->get_typename(), 'get_instance_option_names');
725 if (!empty($instanceoptionnames)) {
726 if ($type->get_contextvisibility($context)) {
727 $editabletypes[]=$type;
731 return $editabletypes;
735 * Return repository instances
737 * @global object $CFG
738 * @global object $USER
740 * @param array $args Array containing the following keys:
749 * @return array repository instances
751 public static function get_instances($args = array()) {
752 global $DB, $CFG, $USER;
754 if (isset($args['currentcontext'])) {
755 $current_context = $args['currentcontext'];
757 $current_context = null;
760 if (!empty($args['context'])) {
761 $contexts = $args['context'];
766 $onlyvisible = isset($args['onlyvisible']) ?
$args['onlyvisible'] : true;
767 $returntypes = isset($args['return_types']) ?
$args['return_types'] : 3;
768 $type = isset($args['type']) ?
$args['type'] : null;
771 $sql = "SELECT i.*, r.type AS repositorytype, r.sortorder, r.visible
772 FROM {repository} r, {repository_instances} i
773 WHERE i.typeid = r.id ";
775 if (!empty($args['disable_types']) && is_array($args['disable_types'])) {
776 list($types, $p) = $DB->get_in_or_equal($args['disable_types'], SQL_PARAMS_QM
, 'param', false);
777 $sql .= " AND r.type $types";
778 $params = array_merge($params, $p);
781 if (!empty($args['userid']) && is_numeric($args['userid'])) {
782 $sql .= " AND (i.userid = 0 or i.userid = ?)";
783 $params[] = $args['userid'];
786 foreach ($contexts as $context) {
787 if (empty($firstcontext)) {
788 $firstcontext = true;
789 $sql .= " AND ((i.contextid = ?)";
791 $sql .= " OR (i.contextid = ?)";
793 $params[] = $context->id
;
796 if (!empty($firstcontext)) {
800 if ($onlyvisible == true) {
801 $sql .= " AND (r.visible = 1)";
805 $sql .= " AND (r.type = ?)";
808 $sql .= " ORDER BY r.sortorder, i.name";
810 if (!$records = $DB->get_records_sql($sql, $params)) {
814 $repositories = array();
815 $ft = new filetype_parser();
816 if (isset($args['accepted_types'])) {
817 $accepted_types = $args['accepted_types'];
819 $accepted_types = '*';
821 // Sortorder should be unique, which is not true if we use $record->sortorder
822 // and there are multiple instances of any repository type
824 foreach ($records as $record) {
825 if (!file_exists($CFG->dirroot
. '/repository/'. $record->repositorytype
.'/lib.php')) {
828 require_once($CFG->dirroot
. '/repository/'. $record->repositorytype
.'/lib.php');
829 $options['visible'] = $record->visible
;
830 $options['type'] = $record->repositorytype
;
831 $options['typeid'] = $record->typeid
;
832 $options['sortorder'] = $sortorder++
;
833 // tell instance what file types will be accepted by file picker
834 $classname = 'repository_' . $record->repositorytype
;
836 $repository = new $classname($record->id
, $record->contextid
, $options, $record->readonly
);
838 $is_supported = true;
840 if (empty($repository->super_called
)) {
841 // to make sure the super construct is called
842 debugging('parent::__construct must be called by '.$record->repositorytype
.' plugin.');
845 if ($accepted_types !== '*' and $repository->supported_filetypes() !== '*') {
846 $accepted_types = $ft->get_extensions($accepted_types);
847 $supported_filetypes = $ft->get_extensions($repository->supported_filetypes());
849 $is_supported = false;
850 foreach ($supported_filetypes as $type) {
851 if (in_array($type, $accepted_types)) {
852 $is_supported = true;
857 // check return values
858 if ($returntypes !== 3 and $repository->supported_returntypes() !== 3) {
859 $type = $repository->supported_returntypes();
860 if ($type & $returntypes) {
863 $is_supported = false;
867 if (!$onlyvisible ||
($repository->is_visible() && !$repository->disabled
)) {
868 // check capability in current context
869 if (!empty($current_context)) {
870 $capability = has_capability('repository/'.$record->repositorytype
.':view', $current_context);
872 $capability = has_capability('repository/'.$record->repositorytype
.':view', get_system_context());
874 if ($record->repositorytype
== 'coursefiles') {
875 // coursefiles plugin needs managefiles permission
876 if (!empty($current_context)) {
877 $capability = $capability && has_capability('moodle/course:managefiles', $current_context);
879 $capability = $capability && has_capability('moodle/course:managefiles', get_system_context());
882 if ($is_supported && $capability) {
883 $repositories[$repository->id
] = $repository;
888 return $repositories;
892 * Get single repository instance
894 * @global object $CFG
895 * @param integer $id repository id
896 * @return object repository instance
898 public static function get_instance($id) {
900 $sql = "SELECT i.*, r.type AS repositorytype, r.visible
902 JOIN {repository_instances} i ON i.typeid = r.id
905 if (!$instance = $DB->get_record_sql($sql, array($id))) {
908 require_once($CFG->dirroot
. '/repository/'. $instance->repositorytype
.'/lib.php');
909 $classname = 'repository_' . $instance->repositorytype
;
910 $options['typeid'] = $instance->typeid
;
911 $options['type'] = $instance->repositorytype
;
912 $options['name'] = $instance->name
;
913 $obj = new $classname($instance->id
, $instance->contextid
, $options, $instance->readonly
);
914 if (empty($obj->super_called
)) {
915 debugging('parent::__construct must be called by '.$classname.' plugin.');
921 * Call a static function. Any additional arguments than plugin and function will be passed through.
922 * @global object $CFG
923 * @param string $plugin
924 * @param string $function
927 public static function static_function($plugin, $function) {
930 //check that the plugin exists
931 $typedirectory = $CFG->dirroot
. '/repository/'. $plugin . '/lib.php';
932 if (!file_exists($typedirectory)) {
933 //throw new repository_exception('invalidplugin', 'repository');
938 if (is_object($plugin) ||
is_array($plugin)) {
939 $plugin = (object)$plugin;
940 $pname = $plugin->name
;
945 $args = func_get_args();
946 if (count($args) <= 2) {
953 require_once($typedirectory);
954 return call_user_func_array(array('repository_' . $plugin, $function), $args);
958 * Scan file, throws exception in case of infected file.
960 * Please note that the scanning engine must be able to access the file,
961 * permissions of the file are not modified here!
964 * @param string $thefile
965 * @param string $filename name of the file
966 * @param bool $deleteinfected
969 public static function antivir_scan_file($thefile, $filename, $deleteinfected) {
972 if (!is_readable($thefile)) {
973 // this should not happen
977 if (empty($CFG->runclamonupload
) or empty($CFG->pathtoclam
)) {
982 $CFG->pathtoclam
= trim($CFG->pathtoclam
);
984 if (!file_exists($CFG->pathtoclam
) or !is_executable($CFG->pathtoclam
)) {
985 // misconfigured clam - use the old notification for now
986 require("$CFG->libdir/uploadlib.php");
987 $notice = get_string('clamlost', 'moodle', $CFG->pathtoclam
);
988 clam_message_admins($notice);
992 // do NOT mess with permissions here, the calling party is responsible for making
993 // sure the scanner engine can access the files!
996 $cmd = escapeshellcmd($CFG->pathtoclam
).' --stdout '.escapeshellarg($thefile);
997 exec($cmd, $output, $return);
1000 // perfect, no problem found
1003 } else if ($return == 1) {
1005 if ($deleteinfected) {
1008 throw new moodle_exception('virusfounduser', 'moodle', '', array('filename'=>$filename));
1012 require("$CFG->libdir/uploadlib.php");
1013 $notice = get_string('clamfailed', 'moodle', get_clam_error_code($return));
1014 $notice .= "\n\n". implode("\n", $output);
1015 clam_message_admins($notice);
1016 if ($CFG->clamfailureonupload
=== 'actlikevirus') {
1017 if ($deleteinfected) {
1020 throw new moodle_exception('virusfounduser', 'moodle', '', array('filename'=>$filename));
1028 * Move file from download folder to file pool using FILE API
1029 * @global object $DB
1030 * @global object $CFG
1031 * @global object $USER
1032 * @global object $OUTPUT
1033 * @param string $thefile file path in download folder
1034 * @param object $record
1035 * @return array containing the following keys:
1041 public static function move_to_filepool($thefile, $record) {
1042 global $DB, $CFG, $USER, $OUTPUT;
1044 // scan for viruses if possible, throws exception if problem found
1045 self
::antivir_scan_file($thefile, $record->filename
, empty($CFG->repository_no_delete
)); //TODO: MDL-28637 this repository_no_delete is a bloody hack!
1047 if ($record->filepath
!== '/') {
1048 $record->filepath
= trim($record->filepath
, '/');
1049 $record->filepath
= '/'.$record->filepath
.'/';
1051 $context = get_context_instance(CONTEXT_USER
, $USER->id
);
1054 $record->contextid
= $context->id
;
1055 $record->component
= 'user';
1056 $record->filearea
= 'draft';
1057 $record->timecreated
= $now;
1058 $record->timemodified
= $now;
1059 $record->userid
= $USER->id
;
1060 $record->mimetype
= mimeinfo('type', $thefile);
1061 if(!is_numeric($record->itemid
)) {
1062 $record->itemid
= 0;
1064 $fs = get_file_storage();
1065 if ($existingfile = $fs->get_file($context->id
, $record->component
, $record->filearea
, $record->itemid
, $record->filepath
, $record->filename
)) {
1066 $draftitemid = $record->itemid
;
1067 $new_filename = repository
::get_unused_filename($draftitemid, $record->filepath
, $record->filename
);
1068 $old_filename = $record->filename
;
1069 // create a tmp file
1070 $record->filename
= $new_filename;
1071 $newfile = $fs->create_file_from_pathname($record, $thefile);
1073 $event['event'] = 'fileexists';
1074 $event['newfile'] = new stdClass
;
1075 $event['newfile']->filepath
= $record->filepath
;
1076 $event['newfile']->filename
= $new_filename;
1077 $event['newfile']->url
= moodle_url
::make_draftfile_url($draftitemid, $record->filepath
, $new_filename)->out();
1079 $event['existingfile'] = new stdClass
;
1080 $event['existingfile']->filepath
= $record->filepath
;
1081 $event['existingfile']->filename
= $old_filename;
1082 $event['existingfile']->url
= moodle_url
::make_draftfile_url($draftitemid, $record->filepath
, $old_filename)->out();;
1085 if ($file = $fs->create_file_from_pathname($record, $thefile)) {
1086 if (empty($CFG->repository_no_delete
)) {
1087 $delete = unlink($thefile);
1088 unset($CFG->repository_no_delete
);
1091 'url'=>moodle_url
::make_draftfile_url($file->get_itemid(), $file->get_filepath(), $file->get_filename())->out(),
1092 'id'=>$file->get_itemid(),
1093 'file'=>$file->get_filename(),
1094 'icon' => $OUTPUT->pix_url(file_extension_icon($thefile, 32))->out(),
1102 * Builds a tree of files This function is
1103 * then called recursively.
1105 * @param $fileinfo an object returned by file_browser::get_file_info()
1106 * @param $search searched string
1107 * @param $dynamicmode bool no recursive call is done when in dynamic mode
1108 * @param $list - the array containing the files under the passed $fileinfo
1109 * @returns int the number of files found
1111 * todo: take $search into account, and respect a threshold for dynamic loading
1113 public static function build_tree($fileinfo, $search, $dynamicmode, &$list) {
1114 global $CFG, $OUTPUT;
1117 $children = $fileinfo->get_children();
1119 foreach ($children as $child) {
1120 $filename = $child->get_visible_name();
1121 $filesize = $child->get_filesize();
1122 $filesize = $filesize ?
display_size($filesize) : '';
1123 $filedate = $child->get_timemodified();
1124 $filedate = $filedate ?
userdate($filedate) : '';
1125 $filetype = $child->get_mimetype();
1127 if ($child->is_directory()) {
1129 $level = $child->get_parent();
1131 $params = $level->get_params();
1132 $path[] = array($params['filepath'], $level->get_visible_name());
1133 $level = $level->get_parent();
1137 'title' => $child->get_visible_name(),
1139 'date' => $filedate,
1140 'path' => array_reverse($path),
1141 'thumbnail' => $OUTPUT->pix_url('f/folder-32')
1144 //if ($dynamicmode && $child->is_writable()) {
1145 // $tmp['children'] = array();
1147 // if folder name matches search, we send back all files contained.
1149 if ($search && stristr($tmp['title'], $search) !== false) {
1152 $tmp['children'] = array();
1153 $_filecount = repository
::build_tree($child, $_search, $dynamicmode, $tmp['children']);
1154 if ($search && $_filecount) {
1155 $tmp['expanded'] = 1;
1160 if (!$search ||
$_filecount ||
(stristr($tmp['title'], $search) !== false)) {
1161 $filecount +
= $_filecount;
1165 } else { // not a directory
1166 // skip the file, if we're in search mode and it's not a match
1167 if ($search && (stristr($filename, $search) === false)) {
1170 $params = $child->get_params();
1171 $source = serialize(array($params['contextid'], $params['component'], $params['filearea'], $params['itemid'], $params['filepath'], $params['filename']));
1173 'title' => $filename,
1174 'size' => $filesize,
1175 'date' => $filedate,
1176 //'source' => $child->get_url(),
1177 'source' => base64_encode($source),
1178 'thumbnail'=>$OUTPUT->pix_url(file_extension_icon($filename, 32)),
1189 * Display a repository instance list (with edit/delete/create links)
1190 * @global object $CFG
1191 * @global object $USER
1192 * @global object $OUTPUT
1193 * @param object $context the context for which we display the instance
1194 * @param string $typename if set, we display only one type of instance
1196 public static function display_instances_list($context, $typename = null) {
1197 global $CFG, $USER, $OUTPUT;
1199 $output = $OUTPUT->box_start('generalbox');
1200 //if the context is SYSTEM, so we call it from administration page
1201 $admin = ($context->id
== SYSCONTEXTID
) ?
true : false;
1203 $baseurl = new moodle_url('/'.$CFG->admin
.'/repositoryinstance.php', array('sesskey'=>sesskey()));
1204 $output .= $OUTPUT->heading(get_string('siteinstances', 'repository'));
1206 $baseurl = new moodle_url('/repository/manage_instances.php', array('contextid'=>$context->id
, 'sesskey'=>sesskey()));
1210 $namestr = get_string('name');
1211 $pluginstr = get_string('plugin', 'repository');
1212 $settingsstr = get_string('settings');
1213 $deletestr = get_string('delete');
1214 //retrieve list of instances. In administration context we want to display all
1215 //instances of a type, even if this type is not visible. In course/user context we
1216 //want to display only visible instances, but for every type types. The repository::get_instances()
1217 //third parameter displays only visible type.
1219 $params['context'] = array($context, get_system_context());
1220 $params['currentcontext'] = $context;
1221 $params['onlyvisible'] = !$admin;
1222 $params['type'] = $typename;
1223 $instances = repository
::get_instances($params);
1224 $instancesnumber = count($instances);
1225 $alreadyplugins = array();
1227 $table = new html_table();
1228 $table->head
= array($namestr, $pluginstr, $settingsstr, $deletestr);
1229 $table->align
= array('left', 'left', 'center','center');
1230 $table->data
= array();
1234 foreach ($instances as $i) {
1238 $type = repository
::get_type_by_id($i->options
['typeid']);
1240 if ($type->get_contextvisibility($context)) {
1241 if (!$i->readonly
) {
1243 $url->param('type', $i->options
['type']);
1244 $url->param('edit', $i->id
);
1245 $settings .= html_writer
::link($url, $settingsstr);
1247 $url->remove_params('edit');
1248 $url->param('delete', $i->id
);
1249 $delete .= html_writer
::link($url, $deletestr);
1251 $url->remove_params('type');
1255 $type = repository
::get_type_by_id($i->options
['typeid']);
1256 $table->data
[] = array($i->name
, $type->get_readablename(), $settings, $delete);
1258 //display a grey row if the type is defined as not visible
1259 if (isset($type) && !$type->get_visible()) {
1260 $table->rowclasses
[] = 'dimmed_text';
1262 $table->rowclasses
[] = '';
1265 if (!in_array($i->name
, $alreadyplugins)) {
1266 $alreadyplugins[] = $i->name
;
1269 $output .= html_writer
::table($table);
1270 $instancehtml = '<div>';
1273 //if no type is set, we can create all type of instance
1275 $instancehtml .= '<h3>';
1276 $instancehtml .= get_string('createrepository', 'repository');
1277 $instancehtml .= '</h3><ul>';
1278 $types = repository
::get_editable_types($context);
1279 foreach ($types as $type) {
1280 if (!empty($type) && $type->get_visible()) {
1281 $instanceoptionnames = repository
::static_function($type->get_typename(), 'get_instance_option_names');
1282 if (!empty($instanceoptionnames)) {
1283 $baseurl->param('new', $type->get_typename());
1284 $instancehtml .= '<li><a href="'.$baseurl->out().'">'.get_string('createxxinstance', 'repository', get_string('pluginname', 'repository_'.$type->get_typename())). '</a></li>';
1285 $baseurl->remove_params('new');
1290 $instancehtml .= '</ul>';
1293 $instanceoptionnames = repository
::static_function($typename, 'get_instance_option_names');
1294 if (!empty($instanceoptionnames)) { //create a unique type of instance
1296 $baseurl->param('new', $typename);
1297 $instancehtml .= "<form action='".$baseurl->out()."' method='post'>
1298 <p><input type='submit' value='".get_string('createinstance', 'repository')."'/></p>
1300 $baseurl->remove_params('new');
1305 $instancehtml .= '</div>';
1306 $output .= $instancehtml;
1309 $output .= $OUTPUT->box_end();
1311 //print the list + creation links
1316 * Decide where to save the file, can be overwriten by subclass
1317 * @param string filename
1319 public function prepare_file($filename) {
1321 if (!file_exists($CFG->tempdir
.'/download')) {
1322 mkdir($CFG->tempdir
.'/download/', $CFG->directorypermissions
, true);
1324 if (is_dir($CFG->tempdir
.'/download')) {
1325 $dir = $CFG->tempdir
.'/download/';
1327 if (empty($filename)) {
1328 $filename = uniqid('repo', true).'_'.time().'.tmp';
1330 if (file_exists($dir.$filename)) {
1331 $filename = uniqid('m').$filename;
1333 return $dir.$filename;
1337 * Return file URL, for most plugins, the parameter is the original
1338 * url, but some plugins use a file id, so we need this function to
1339 * convert file id to original url.
1341 * @param string $url the url of file
1344 public function get_link($url) {
1349 * Download a file, this function can be overridden by
1352 * @global object $CFG
1353 * @param string $url the url of file
1354 * @param string $filename save location
1355 * @return string the location of the file
1358 public function get_file($url, $filename = '') {
1360 $path = $this->prepare_file($filename);
1361 $fp = fopen($path, 'w');
1363 $c->download(array(array('url'=>$url, 'file'=>$fp)));
1364 return array('path'=>$path, 'url'=>$url);
1368 * Return size of a file in bytes.
1370 * @param string $source encoded and serialized data of file
1371 * @return integer file size in bytes
1373 public function get_file_size($source) {
1374 $browser = get_file_browser();
1375 $params = unserialize(base64_decode($source));
1376 $contextid = clean_param($params['contextid'], PARAM_INT
);
1377 $fileitemid = clean_param($params['itemid'], PARAM_INT
);
1378 $filename = clean_param($params['filename'], PARAM_FILE
);
1379 $filepath = clean_param($params['filepath'], PARAM_PATH
);
1380 $filearea = clean_param($params['filearea'], PARAM_AREA
);
1381 $component = clean_param($params['component'], PARAM_COMPONENT
);
1382 $context = get_context_instance_by_id($contextid);
1383 $file_info = $browser->get_file_info($context, $component, $filearea, $fileitemid, $filepath, $filename);
1384 if (!empty($file_info)) {
1385 $filesize = $file_info->get_filesize();
1393 * Return is the instance is visible
1394 * (is the type visible ? is the context enable ?)
1397 public function is_visible() {
1398 $type = repository
::get_type_by_id($this->options
['typeid']);
1399 $instanceoptions = repository
::static_function($type->get_typename(), 'get_instance_option_names');
1401 if ($type->get_visible()) {
1402 //if the instance is unique so it's visible, otherwise check if the instance has a enabled context
1403 if (empty($instanceoptions) ||
$type->get_contextvisibility($this->context
)) {
1412 * Return the name of this instance, can be overridden.
1413 * @global object $DB
1416 public function get_name() {
1418 if ( $name = $this->instance
->name
) {
1421 return get_string('pluginname', 'repository_' . $this->options
['type']);
1426 * what kind of files will be in this repository?
1427 * @return array return '*' means this repository support any files, otherwise
1428 * return mimetypes of files, it can be an array
1430 public function supported_filetypes() {
1431 // return array('text/plain', 'image/gif');
1436 * does it return a file url or a item_id
1439 public function supported_returntypes() {
1440 return (FILE_INTERNAL | FILE_EXTERNAL
);
1444 * Provide repository instance information for Ajax
1445 * @global object $CFG
1448 final public function get_meta() {
1449 global $CFG, $OUTPUT;
1450 $ft = new filetype_parser
;
1451 $meta = new stdClass();
1452 $meta->id
= $this->id
;
1453 $meta->name
= $this->get_name();
1454 $meta->type
= $this->options
['type'];
1455 $meta->icon
= $OUTPUT->pix_url('icon', 'repository_'.$meta->type
)->out(false);
1456 $meta->supported_types
= $ft->get_extensions($this->supported_filetypes());
1457 $meta->return_types
= $this->supported_returntypes();
1458 $meta->sortorder
= $this->options
['sortorder'];
1463 * Create an instance for this plug-in
1464 * @global object $CFG
1465 * @global object $DB
1466 * @param string $type the type of the repository
1467 * @param integer $userid the user id
1468 * @param object $context the context
1469 * @param array $params the options for this instance
1470 * @param integer $readonly whether to create it readonly or not (defaults to not)
1473 public static function create($type, $userid, $context, $params, $readonly=0) {
1475 $params = (array)$params;
1476 require_once($CFG->dirroot
. '/repository/'. $type . '/lib.php');
1477 $classname = 'repository_' . $type;
1478 if ($repo = $DB->get_record('repository', array('type'=>$type))) {
1479 $record = new stdClass();
1480 $record->name
= $params['name'];
1481 $record->typeid
= $repo->id
;
1482 $record->timecreated
= time();
1483 $record->timemodified
= time();
1484 $record->contextid
= $context->id
;
1485 $record->readonly
= $readonly;
1486 $record->userid
= $userid;
1487 $id = $DB->insert_record('repository_instances', $record);
1489 $configs = call_user_func($classname . '::get_instance_option_names');
1490 if (!empty($configs)) {
1491 foreach ($configs as $config) {
1492 if (isset($params[$config])) {
1493 $options[$config] = $params[$config];
1495 $options[$config] = null;
1501 unset($options['name']);
1502 $instance = repository
::get_instance($id);
1503 $instance->set_option($options);
1514 * delete a repository instance
1515 * @global object $DB
1518 final public function delete() {
1520 $DB->delete_records('repository_instances', array('id'=>$this->id
));
1521 $DB->delete_records('repository_instance_config', array('instanceid'=>$this->id
));
1526 * Hide/Show a repository
1527 * @global object $DB
1528 * @param string $hide
1531 final public function hide($hide = 'toggle') {
1533 if ($entry = $DB->get_record('repository', array('id'=>$this->id
))) {
1534 if ($hide === 'toggle' ) {
1535 if (!empty($entry->visible
)) {
1536 $entry->visible
= 0;
1538 $entry->visible
= 1;
1541 if (!empty($hide)) {
1542 $entry->visible
= 0;
1544 $entry->visible
= 1;
1547 return $DB->update_record('repository', $entry);
1553 * Save settings for repository instance
1554 * $repo->set_option(array('api_key'=>'f2188bde132', 'name'=>'dongsheng'));
1555 * @global object $DB
1556 * @param array $options settings
1557 * @return int Id of the record
1559 public function set_option($options = array()) {
1562 if (!empty($options['name'])) {
1563 $r = new stdClass();
1565 $r->name
= $options['name'];
1566 $DB->update_record('repository_instances', $r);
1567 unset($options['name']);
1569 foreach ($options as $name=>$value) {
1570 if ($id = $DB->get_field('repository_instance_config', 'id', array('name'=>$name, 'instanceid'=>$this->id
))) {
1571 $DB->set_field('repository_instance_config', 'value', $value, array('id'=>$id));
1573 $config = new stdClass();
1574 $config->instanceid
= $this->id
;
1575 $config->name
= $name;
1576 $config->value
= $value;
1577 $DB->insert_record('repository_instance_config', $config);
1584 * Get settings for repository instance
1585 * @global object $DB
1586 * @param string $config
1587 * @return array Settings
1589 public function get_option($config = '') {
1591 $entries = $DB->get_records('repository_instance_config', array('instanceid'=>$this->id
));
1593 if (empty($entries)) {
1596 foreach($entries as $entry) {
1597 $ret[$entry->name
] = $entry->value
;
1599 if (!empty($config)) {
1600 if (isset($ret[$config])) {
1601 return $ret[$config];
1610 public function filter(&$value) {
1612 $accepted_types = optional_param_array('accepted_types', '', PARAM_RAW
);
1613 $ft = new filetype_parser
;
1614 //$ext = $ft->get_extensions($this->supported_filetypes());
1615 if (isset($value['children'])) {
1617 if (!empty($value['children'])) {
1618 $value['children'] = array_filter($value['children'], array($this, 'filter'));
1621 if ($accepted_types == '*' or empty($accepted_types)
1622 or (is_array($accepted_types) and in_array('*', $accepted_types))) {
1624 } elseif (is_array($accepted_types)) {
1625 foreach ($accepted_types as $type) {
1626 $extensions = $ft->get_extensions($type);
1627 if (!is_array($extensions)) {
1630 foreach ($extensions as $ext) {
1631 if (preg_match('#'.$ext.'$#i', $value['title'])) {
1643 * Given a path, and perhaps a search, get a list of files.
1645 * See details on http://docs.moodle.org/dev/Repository_plugins
1647 * @param string $path, this parameter can
1648 * a folder name, or a identification of folder
1649 * @param string $page, the page number of file list
1650 * @return array the list of files, including meta infomation, containing the following keys
1651 * manage, url to manage url
1654 * repo_id, active repository id
1655 * login_btn_action, the login button action
1656 * login_btn_label, the login button label
1657 * total, number of results
1658 * perpage, items per page
1660 * pages, total pages
1661 * issearchresult, is it a search result?
1663 * path, current path and parent path
1665 public function get_listing($path = '', $page = '') {
1669 * Search files in repository
1670 * When doing global search, $search_text will be used as
1673 * @return mixed, see get_listing()
1675 public function search($search_text) {
1677 $list['list'] = array();
1682 * Logout from repository instance
1683 * By default, this function will return a login form
1687 public function logout(){
1688 return $this->print_login();
1692 * To check whether the user is logged in.
1696 public function check_login(){
1702 * Show the login screen, if required
1704 public function print_login(){
1705 return $this->get_listing();
1709 * Show the search screen, if required
1712 public function print_search() {
1714 $str .= '<input type="hidden" name="repo_id" value="'.$this->id
.'" />';
1715 $str .= '<input type="hidden" name="ctx_id" value="'.$this->context
->id
.'" />';
1716 $str .= '<input type="hidden" name="seekey" value="'.sesskey().'" />';
1717 $str .= '<label>'.get_string('keyword', 'repository').': </label><br/><input name="s" value="" /><br/>';
1722 * For oauth like external authentication, when external repository direct user back to moodle,
1723 * this funciton will be called to set up token and token_secret
1725 public function callback() {
1729 * is it possible to do glboal search?
1732 public function global_search() {
1737 * Defines operations that happen occasionally on cron
1740 public function cron() {
1745 * function which is run when the type is created (moodle administrator add the plugin)
1746 * @return boolean success or fail?
1748 public static function plugin_init() {
1753 * Edit/Create Admin Settings Moodle form
1754 * @param object $mform Moodle form (passed by reference)
1755 * @param string $classname repository class name
1757 public function type_config_form($mform, $classname = 'repository') {
1758 $instnaceoptions = call_user_func(array($classname, 'get_instance_option_names'), $mform, $classname);
1759 if (empty($instnaceoptions)) {
1760 // this plugin has only one instance
1761 // so we need to give it a name
1762 // it can be empty, then moodle will look for instance name from language string
1763 $mform->addElement('text', 'pluginname', get_string('pluginname', 'repository'), array('size' => '40'));
1764 $mform->addElement('static', 'pluginnamehelp', '', get_string('pluginnamehelp', 'repository'));
1769 * Validate Admin Settings Moodle form
1770 * @param object $mform Moodle form (passed by reference)
1771 * @param array array of ("fieldname"=>value) of submitted data
1772 * @param array array of ("fieldname"=>errormessage) of errors
1773 * @return array array of errors
1775 public static function type_form_validation($mform, $data, $errors) {
1781 * Edit/Create Instance Settings Moodle form
1782 * @param object $mform Moodle form (passed by reference)
1784 public function instance_config_form($mform) {
1788 * Return names of the general options
1789 * By default: no general option name
1792 public static function get_type_option_names() {
1793 return array('pluginname');
1797 * Return names of the instance options
1798 * By default: no instance option name
1801 public static function get_instance_option_names() {
1805 public static function instance_form_validation($mform, $data, $errors) {
1809 public function get_short_filename($str, $maxlength) {
1810 if (textlib
::strlen($str) >= $maxlength) {
1811 return trim(textlib
::substr($str, 0, $maxlength)).'...';
1818 * Overwrite an existing file
1820 * @param int $itemid
1821 * @param string $filepath
1822 * @param string $filename
1823 * @param string $newfilepath
1824 * @param string $newfilename
1827 function overwrite_existing_draftfile($itemid, $filepath, $filename, $newfilepath, $newfilename) {
1829 $fs = get_file_storage();
1830 $user_context = get_context_instance(CONTEXT_USER
, $USER->id
);
1831 if ($file = $fs->get_file($user_context->id
, 'user', 'draft', $itemid, $filepath, $filename)) {
1832 if ($tempfile = $fs->get_file($user_context->id
, 'user', 'draft', $itemid, $newfilepath, $newfilename)) {
1833 // delete existing file to release filename
1836 $newfile = $fs->create_file_from_storedfile(array('filepath'=>$filepath, 'filename'=>$filename), $tempfile);
1838 $tempfile->delete();
1846 * Delete a temp file from draft area
1848 * @param int $draftitemid
1849 * @param string $filepath
1850 * @param string $filename
1853 function delete_tempfile_from_draft($draftitemid, $filepath, $filename) {
1855 $fs = get_file_storage();
1856 $user_context = get_context_instance(CONTEXT_USER
, $USER->id
);
1857 if ($file = $fs->get_file($user_context->id
, 'user', 'draft', $draftitemid, $filepath, $filename)) {
1867 * Exception class for repository api
1870 * @package moodlecore
1871 * @subpackage repository
1872 * @copyright 2009 Dongsheng Cai <dongsheng@moodle.com>
1873 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1875 class repository_exception
extends moodle_exception
{
1879 * This is a class used to define a repository instance form
1882 * @package moodlecore
1883 * @subpackage repository
1884 * @copyright 2009 Dongsheng Cai <dongsheng@moodle.com>
1885 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1887 final class repository_instance_form
extends moodleform
{
1888 protected $instance;
1890 protected function add_defaults() {
1891 $mform =& $this->_form
;
1892 $strrequired = get_string('required');
1894 $mform->addElement('hidden', 'edit', ($this->instance
) ?
$this->instance
->id
: 0);
1895 $mform->setType('edit', PARAM_INT
);
1896 $mform->addElement('hidden', 'new', $this->plugin
);
1897 $mform->setType('new', PARAM_FORMAT
);
1898 $mform->addElement('hidden', 'plugin', $this->plugin
);
1899 $mform->setType('plugin', PARAM_PLUGIN
);
1900 $mform->addElement('hidden', 'typeid', $this->typeid
);
1901 $mform->setType('typeid', PARAM_INT
);
1902 $mform->addElement('hidden', 'contextid', $this->contextid
);
1903 $mform->setType('contextid', PARAM_INT
);
1905 $mform->addElement('text', 'name', get_string('name'), 'maxlength="100" size="30"');
1906 $mform->addRule('name', $strrequired, 'required', null, 'client');
1909 public function definition() {
1911 // type of plugin, string
1912 $this->plugin
= $this->_customdata
['plugin'];
1913 $this->typeid
= $this->_customdata
['typeid'];
1914 $this->contextid
= $this->_customdata
['contextid'];
1915 $this->instance
= (isset($this->_customdata
['instance'])
1916 && is_subclass_of($this->_customdata
['instance'], 'repository'))
1917 ?
$this->_customdata
['instance'] : null;
1919 $mform =& $this->_form
;
1921 $this->add_defaults();
1923 if (!$this->instance
) {
1924 $result = repository
::static_function($this->plugin
, 'instance_config_form', $mform);
1925 if ($result === false) {
1926 $mform->removeElement('name');
1930 $data['name'] = $this->instance
->name
;
1931 if (!$this->instance
->readonly
) {
1932 $result = $this->instance
->instance_config_form($mform);
1933 if ($result === false) {
1934 $mform->removeElement('name');
1936 // and set the data if we have some.
1937 foreach ($this->instance
->get_instance_option_names() as $config) {
1938 if (!empty($this->instance
->options
[$config])) {
1939 $data[$config] = $this->instance
->options
[$config];
1941 $data[$config] = '';
1945 $this->set_data($data);
1948 if ($result === false) {
1949 $mform->addElement('cancel');
1951 $this->add_action_buttons(true, get_string('save','repository'));
1955 public function validation($data) {
1958 $plugin = $this->_customdata
['plugin'];
1959 $instance = (isset($this->_customdata
['instance'])
1960 && is_subclass_of($this->_customdata
['instance'], 'repository'))
1961 ?
$this->_customdata
['instance'] : null;
1963 $errors = repository
::static_function($plugin, 'instance_form_validation', $this, $data, $errors);
1965 $errors = $instance->instance_form_validation($this, $data, $errors);
1968 $sql = "SELECT count('x')
1969 FROM {repository_instances} i, {repository} r
1970 WHERE r.type=:plugin AND r.id=i.typeid AND i.name=:name";
1971 if ($DB->count_records_sql($sql, array('name' => $data['name'], 'plugin' => $data['plugin'])) > 1) {
1972 $errors['name'] = get_string('erroruniquename', 'repository');
1980 * This is a class used to define a repository type setting form
1983 * @package moodlecore
1984 * @subpackage repository
1985 * @copyright 2009 Dongsheng Cai <dongsheng@moodle.com>
1986 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1988 final class repository_type_form
extends moodleform
{
1989 protected $instance;
1994 * Definition of the moodleform
1995 * @global object $CFG
1997 public function definition() {
1999 // type of plugin, string
2000 $this->plugin
= $this->_customdata
['plugin'];
2001 $this->instance
= (isset($this->_customdata
['instance'])
2002 && is_a($this->_customdata
['instance'], 'repository_type'))
2003 ?
$this->_customdata
['instance'] : null;
2005 $this->action
= $this->_customdata
['action'];
2006 $this->pluginname
= $this->_customdata
['pluginname'];
2007 $mform =& $this->_form
;
2008 $strrequired = get_string('required');
2010 $mform->addElement('hidden', 'action', $this->action
);
2011 $mform->setType('action', PARAM_TEXT
);
2012 $mform->addElement('hidden', 'repos', $this->plugin
);
2013 $mform->setType('repos', PARAM_PLUGIN
);
2015 // let the plugin add its specific fields
2016 $classname = 'repository_' . $this->plugin
;
2017 require_once($CFG->dirroot
. '/repository/' . $this->plugin
. '/lib.php');
2018 //add "enable course/user instances" checkboxes if multiple instances are allowed
2019 $instanceoptionnames = repository
::static_function($this->plugin
, 'get_instance_option_names');
2021 $result = call_user_func(array($classname, 'type_config_form'), $mform, $classname);
2023 if (!empty($instanceoptionnames)) {
2024 $sm = get_string_manager();
2025 $component = 'repository';
2026 if ($sm->string_exists('enablecourseinstances', 'repository_' . $this->plugin
)) {
2027 $component .= ('_' . $this->plugin
);
2029 $mform->addElement('checkbox', 'enablecourseinstances', get_string('enablecourseinstances', $component));
2031 $component = 'repository';
2032 if ($sm->string_exists('enableuserinstances', 'repository_' . $this->plugin
)) {
2033 $component .= ('_' . $this->plugin
);
2035 $mform->addElement('checkbox', 'enableuserinstances', get_string('enableuserinstances', $component));
2038 // set the data if we have some.
2039 if ($this->instance
) {
2041 $option_names = call_user_func(array($classname,'get_type_option_names'));
2042 if (!empty($instanceoptionnames)){
2043 $option_names[] = 'enablecourseinstances';
2044 $option_names[] = 'enableuserinstances';
2047 $instanceoptions = $this->instance
->get_options();
2048 foreach ($option_names as $config) {
2049 if (!empty($instanceoptions[$config])) {
2050 $data[$config] = $instanceoptions[$config];
2052 $data[$config] = '';
2055 // XXX: set plugin name for plugins which doesn't have muliti instances
2056 if (empty($instanceoptionnames)){
2057 $data['pluginname'] = $this->pluginname
;
2059 $this->set_data($data);
2062 $this->add_action_buttons(true, get_string('save','repository'));
2065 public function validation($data) {
2067 $plugin = $this->_customdata
['plugin'];
2068 $instance = (isset($this->_customdata
['instance'])
2069 && is_subclass_of($this->_customdata
['instance'], 'repository'))
2070 ?
$this->_customdata
['instance'] : null;
2072 $errors = repository
::static_function($plugin, 'type_form_validation', $this, $data, $errors);
2074 $errors = $instance->type_form_validation($this, $data, $errors);
2082 * Generate all options needed by filepicker
2084 * @param array $args, including following keys
2089 * @return array the list of repository instances, including meta infomation, containing the following keys
2094 function initialise_filepicker($args) {
2095 global $CFG, $USER, $PAGE, $OUTPUT;
2096 require_once($CFG->libdir
. '/licenselib.php');
2098 $return = new stdClass();
2099 $licenses = array();
2100 if (!empty($CFG->licenses
)) {
2101 $array = explode(',', $CFG->licenses
);
2102 foreach ($array as $license) {
2103 $l = new stdClass();
2104 $l->shortname
= $license;
2105 $l->fullname
= get_string($license, 'license');
2109 if (!empty($CFG->sitedefaultlicense
)) {
2110 $return->defaultlicense
= $CFG->sitedefaultlicense
;
2113 $return->licenses
= $licenses;
2115 $return->author
= fullname($USER);
2117 $ft = new filetype_parser();
2118 if (empty($args->context
)) {
2119 $context = $PAGE->context
;
2121 $context = $args->context
;
2123 $disable_types = array();
2124 if (!empty($args->disable_types
)) {
2125 $disable_types = $args->disable_types
;
2128 $user_context = get_context_instance(CONTEXT_USER
, $USER->id
);
2130 list($context, $course, $cm) = get_context_info_array($context->id
);
2131 $contexts = array($user_context, get_system_context());
2132 if (!empty($course)) {
2133 // adding course context
2134 $contexts[] = get_context_instance(CONTEXT_COURSE
, $course->id
);
2136 $externallink = (int)get_config(null, 'repositoryallowexternallinks');
2137 $repositories = repository
::get_instances(array(
2138 'context'=>$contexts,
2139 'currentcontext'=> $context,
2140 'accepted_types'=>$args->accepted_types
,
2141 'return_types'=>$args->return_types
,
2142 'disable_types'=>$disable_types
2145 $return->repositories
= array();
2147 if (empty($externallink)) {
2148 $return->externallink
= false;
2150 $return->externallink
= true;
2153 // provided by form element
2154 $return->accepted_types
= $ft->get_extensions($args->accepted_types
);
2155 $return->return_types
= $args->return_types
;
2156 foreach ($repositories as $repository) {
2157 $meta = $repository->get_meta();
2158 // Please note that the array keys for repositories are used within
2159 // JavaScript a lot, the key NEEDS to be the repository id.
2160 $return->repositories
[$repository->id
] = $meta;
2165 * Small function to walk an array to attach repository ID
2166 * @param array $value
2167 * @param string $key
2170 function repository_attach_id(&$value, $key, $id){
2171 $value['repo_id'] = $id;