MDL-35421 Add conclusion text fields into the workshop table
[moodle.git] / repository / lib.php
blob0997fb99a8b792c835b88066b263590a9254c883
1 <?php
2 // This file is part of Moodle - http://moodle.org/
3 //
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
8 //
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
17 /**
18 * This file contains classes used to manage the repository plugins in Moodle
20 * @since 2.0
21 * @package core_repository
22 * @copyright 2009 Dongsheng Cai {@link http://dongsheng.org}
23 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
26 defined('MOODLE_INTERNAL') || die();
27 require_once($CFG->libdir . '/filelib.php');
28 require_once($CFG->libdir . '/formslib.php');
30 define('FILE_EXTERNAL', 1);
31 define('FILE_INTERNAL', 2);
32 define('FILE_REFERENCE', 4);
33 define('RENAME_SUFFIX', '_2');
35 /**
36 * This class is used to manage repository plugins
38 * A repository_type is a repository plug-in. It can be Box.net, Flick-r, ...
39 * A repository type can be edited, sorted and hidden. It is mandatory for an
40 * administrator to create a repository type in order to be able to create
41 * some instances of this type.
42 * Coding note:
43 * - a repository_type object is mapped to the "repository" database table
44 * - "typename" attibut maps the "type" database field. It is unique.
45 * - general "options" for a repository type are saved in the config_plugin table
46 * - when you delete a repository, all instances are deleted, and general
47 * options are also deleted from database
48 * - When you create a type for a plugin that can't have multiple instances, a
49 * instance is automatically created.
51 * @package core_repository
52 * @copyright 2009 Jerome Mouneyrac
53 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
55 class repository_type {
58 /**
59 * Type name (no whitespace) - A type name is unique
60 * Note: for a user-friendly type name see get_readablename()
61 * @var String
63 private $_typename;
66 /**
67 * Options of this type
68 * They are general options that any instance of this type would share
69 * e.g. API key
70 * These options are saved in config_plugin table
71 * @var array
73 private $_options;
76 /**
77 * Is the repository type visible or hidden
78 * If false (hidden): no instances can be created, edited, deleted, showned , used...
79 * @var boolean
81 private $_visible;
84 /**
85 * 0 => not ordered, 1 => first position, 2 => second position...
86 * A not order type would appear in first position (should never happened)
87 * @var integer
89 private $_sortorder;
91 /**
92 * Return if the instance is visible in a context
94 * @todo check if the context visibility has been overwritten by the plugin creator
95 * (need to create special functions to be overvwritten in repository class)
96 * @param stdClass $context context
97 * @return bool
99 public function get_contextvisibility($context) {
100 global $USER;
102 if ($context->contextlevel == CONTEXT_COURSE) {
103 return $this->_options['enablecourseinstances'];
106 if ($context->contextlevel == CONTEXT_USER) {
107 return $this->_options['enableuserinstances'];
110 //the context is SITE
111 return true;
117 * repository_type constructor
119 * @param int $typename
120 * @param array $typeoptions
121 * @param bool $visible
122 * @param int $sortorder (don't really need set, it will be during create() call)
124 public function __construct($typename = '', $typeoptions = array(), $visible = true, $sortorder = 0) {
125 global $CFG;
127 //set type attributs
128 $this->_typename = $typename;
129 $this->_visible = $visible;
130 $this->_sortorder = $sortorder;
132 //set options attribut
133 $this->_options = array();
134 $options = repository::static_function($typename, 'get_type_option_names');
135 //check that the type can be setup
136 if (!empty($options)) {
137 //set the type options
138 foreach ($options as $config) {
139 if (array_key_exists($config, $typeoptions)) {
140 $this->_options[$config] = $typeoptions[$config];
145 //retrieve visibility from option
146 if (array_key_exists('enablecourseinstances',$typeoptions)) {
147 $this->_options['enablecourseinstances'] = $typeoptions['enablecourseinstances'];
148 } else {
149 $this->_options['enablecourseinstances'] = 0;
152 if (array_key_exists('enableuserinstances',$typeoptions)) {
153 $this->_options['enableuserinstances'] = $typeoptions['enableuserinstances'];
154 } else {
155 $this->_options['enableuserinstances'] = 0;
161 * Get the type name (no whitespace)
162 * For a human readable name, use get_readablename()
164 * @return string the type name
166 public function get_typename() {
167 return $this->_typename;
171 * 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('pluginname','repository_'.$this->_typename);
180 * Return general options
182 * @return array the general options
184 public function get_options() {
185 return $this->_options;
189 * Return visibility
191 * @return bool
193 public function get_visible() {
194 return $this->_visible;
198 * Return order / position of display in the file picker
200 * @return int
202 public function get_sortorder() {
203 return $this->_sortorder;
207 * Create a repository type (the type name must not already exist)
208 * @param bool $silent throw exception?
209 * @return mixed return int if create successfully, return false if
211 public function create($silent = false) {
212 global $DB;
214 //check that $type has been set
215 $timmedtype = trim($this->_typename);
216 if (empty($timmedtype)) {
217 throw new repository_exception('emptytype', 'repository');
220 //set sortorder as the last position in the list
221 if (!isset($this->_sortorder) || $this->_sortorder == 0 ) {
222 $sql = "SELECT MAX(sortorder) FROM {repository}";
223 $this->_sortorder = 1 + $DB->get_field_sql($sql);
226 //only create a new type if it doesn't already exist
227 $existingtype = $DB->get_record('repository', array('type'=>$this->_typename));
228 if (!$existingtype) {
229 //create the type
230 $newtype = new stdClass();
231 $newtype->type = $this->_typename;
232 $newtype->visible = $this->_visible;
233 $newtype->sortorder = $this->_sortorder;
234 $plugin_id = $DB->insert_record('repository', $newtype);
235 //save the options in DB
236 $this->update_options();
238 $instanceoptionnames = repository::static_function($this->_typename, 'get_instance_option_names');
240 //if the plugin type has no multiple instance (e.g. has no instance option name) so it wont
241 //be possible for the administrator to create a instance
242 //in this case we need to create an instance
243 if (empty($instanceoptionnames)) {
244 $instanceoptions = array();
245 if (empty($this->_options['pluginname'])) {
246 // when moodle trying to install some repo plugin automatically
247 // this option will be empty, get it from language string when display
248 $instanceoptions['name'] = '';
249 } else {
250 // when admin trying to add a plugin manually, he will type a name
251 // for it
252 $instanceoptions['name'] = $this->_options['pluginname'];
254 repository::static_function($this->_typename, 'create', $this->_typename, 0, get_system_context(), $instanceoptions);
256 //run plugin_init function
257 if (!repository::static_function($this->_typename, 'plugin_init')) {
258 if (!$silent) {
259 throw new repository_exception('cannotinitplugin', 'repository');
263 if(!empty($plugin_id)) {
264 // return plugin_id if create successfully
265 return $plugin_id;
266 } else {
267 return false;
270 } else {
271 if (!$silent) {
272 throw new repository_exception('existingrepository', 'repository');
274 // If plugin existed, return false, tell caller no new plugins were created.
275 return false;
281 * Update plugin options into the config_plugin table
283 * @param array $options
284 * @return bool
286 public function update_options($options = null) {
287 global $DB;
288 $classname = 'repository_' . $this->_typename;
289 $instanceoptions = repository::static_function($this->_typename, 'get_instance_option_names');
290 if (empty($instanceoptions)) {
291 // update repository instance name if this plugin type doesn't have muliti instances
292 $params = array();
293 $params['type'] = $this->_typename;
294 $instances = repository::get_instances($params);
295 $instance = array_pop($instances);
296 if ($instance) {
297 $DB->set_field('repository_instances', 'name', $options['pluginname'], array('id'=>$instance->id));
299 unset($options['pluginname']);
302 if (!empty($options)) {
303 $this->_options = $options;
306 foreach ($this->_options as $name => $value) {
307 set_config($name, $value, $this->_typename);
310 return true;
314 * Update visible database field with the value given as parameter
315 * or with the visible value of this object
316 * This function is private.
317 * For public access, have a look to switch_and_update_visibility()
319 * @param bool $visible
320 * @return bool
322 private function update_visible($visible = null) {
323 global $DB;
325 if (!empty($visible)) {
326 $this->_visible = $visible;
328 else if (!isset($this->_visible)) {
329 throw new repository_exception('updateemptyvisible', 'repository');
332 return $DB->set_field('repository', 'visible', $this->_visible, array('type'=>$this->_typename));
336 * Update database sortorder field with the value given as parameter
337 * or with the sortorder value of this object
338 * This function is private.
339 * For public access, have a look to move_order()
341 * @param int $sortorder
342 * @return bool
344 private function update_sortorder($sortorder = null) {
345 global $DB;
347 if (!empty($sortorder) && $sortorder!=0) {
348 $this->_sortorder = $sortorder;
350 //if sortorder is not set, we set it as the ;ast position in the list
351 else if (!isset($this->_sortorder) || $this->_sortorder == 0 ) {
352 $sql = "SELECT MAX(sortorder) FROM {repository}";
353 $this->_sortorder = 1 + $DB->get_field_sql($sql);
356 return $DB->set_field('repository', 'sortorder', $this->_sortorder, array('type'=>$this->_typename));
360 * Change order of the type with its adjacent upper or downer type
361 * (database fields are updated)
362 * Algorithm details:
363 * 1. retrieve all types in an array. This array is sorted by sortorder,
364 * and the array keys start from 0 to X (incremented by 1)
365 * 2. switch sortorder values of this type and its adjacent type
367 * @param string $move "up" or "down"
369 public function move_order($move) {
370 global $DB;
372 $types = repository::get_types(); // retrieve all types
374 // retrieve this type into the returned array
375 $i = 0;
376 while (!isset($indice) && $i<count($types)) {
377 if ($types[$i]->get_typename() == $this->_typename) {
378 $indice = $i;
380 $i++;
383 // retrieve adjacent indice
384 switch ($move) {
385 case "up":
386 $adjacentindice = $indice - 1;
387 break;
388 case "down":
389 $adjacentindice = $indice + 1;
390 break;
391 default:
392 throw new repository_exception('movenotdefined', 'repository');
395 //switch sortorder of this type and the adjacent type
396 //TODO: we could reset sortorder for all types. This is not as good in performance term, but
397 //that prevent from wrong behaviour on a screwed database. As performance are not important in this particular case
398 //it worth to change the algo.
399 if ($adjacentindice>=0 && !empty($types[$adjacentindice])) {
400 $DB->set_field('repository', 'sortorder', $this->_sortorder, array('type'=>$types[$adjacentindice]->get_typename()));
401 $this->update_sortorder($types[$adjacentindice]->get_sortorder());
406 * 1. Change visibility to the value chosen
407 * 2. Update the type
409 * @param bool $visible
410 * @return bool
412 public function update_visibility($visible = null) {
413 if (is_bool($visible)) {
414 $this->_visible = $visible;
415 } else {
416 $this->_visible = !$this->_visible;
418 return $this->update_visible();
423 * Delete a repository_type (general options are removed from config_plugin
424 * table, and all instances are deleted)
426 * @param bool $downloadcontents download external contents if exist
427 * @return bool
429 public function delete($downloadcontents = false) {
430 global $DB;
432 //delete all instances of this type
433 $params = array();
434 $params['context'] = array();
435 $params['onlyvisible'] = false;
436 $params['type'] = $this->_typename;
437 $instances = repository::get_instances($params);
438 foreach ($instances as $instance) {
439 $instance->delete($downloadcontents);
442 //delete all general options
443 foreach ($this->_options as $name => $value) {
444 set_config($name, null, $this->_typename);
447 try {
448 $DB->delete_records('repository', array('type' => $this->_typename));
449 } catch (dml_exception $ex) {
450 return false;
452 return true;
457 * This is the base class of the repository class.
459 * To create repository plugin, see: {@link http://docs.moodle.org/dev/Repository_plugins}
460 * See an example: {@link repository_boxnet}
462 * @package core_repository
463 * @copyright 2009 Dongsheng Cai {@link http://dongsheng.org}
464 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
466 abstract class repository {
467 /** Timeout in seconds for downloading the external file into moodle */
468 const GETFILE_TIMEOUT = 30;
469 /** Timeout in seconds for syncronising the external file size */
470 const SYNCFILE_TIMEOUT = 1;
471 /** Timeout in seconds for downloading an image file from external repository during syncronisation */
472 const SYNCIMAGE_TIMEOUT = 3;
474 // $disabled can be set to true to disable a plugin by force
475 // example: self::$disabled = true
476 /** @var bool force disable repository instance */
477 public $disabled = false;
478 /** @var int repository instance id */
479 public $id;
480 /** @var stdClass current context */
481 public $context;
482 /** @var array repository options */
483 public $options;
484 /** @var bool Whether or not the repository instance is editable */
485 public $readonly;
486 /** @var int return types */
487 public $returntypes;
488 /** @var stdClass repository instance database record */
489 public $instance;
491 * Constructor
493 * @param int $repositoryid repository instance id
494 * @param int|stdClass $context a context id or context object
495 * @param array $options repository options
496 * @param int $readonly indicate this repo is readonly or not
498 public function __construct($repositoryid, $context = SYSCONTEXTID, $options = array(), $readonly = 0) {
499 global $DB;
500 $this->id = $repositoryid;
501 if (is_object($context)) {
502 $this->context = $context;
503 } else {
504 $this->context = context::instance_by_id($context);
506 $this->instance = $DB->get_record('repository_instances', array('id'=>$this->id));
507 $this->readonly = $readonly;
508 $this->options = array();
510 if (is_array($options)) {
511 // The get_option() method will get stored options in database.
512 $options = array_merge($this->get_option(), $options);
513 } else {
514 $options = $this->get_option();
516 foreach ($options as $n => $v) {
517 $this->options[$n] = $v;
519 $this->name = $this->get_name();
520 $this->returntypes = $this->supported_returntypes();
521 $this->super_called = true;
525 * Get repository instance using repository id
527 * @param int $repositoryid repository ID
528 * @param stdClass|int $context context instance or context ID
529 * @param array $options additional repository options
530 * @return repository
532 public static function get_repository_by_id($repositoryid, $context, $options = array()) {
533 global $CFG, $DB;
535 $sql = 'SELECT i.name, i.typeid, r.type FROM {repository} r, {repository_instances} i WHERE i.id=? AND i.typeid=r.id';
537 if (!$record = $DB->get_record_sql($sql, array($repositoryid))) {
538 throw new repository_exception('invalidrepositoryid', 'repository');
539 } else {
540 $type = $record->type;
541 if (file_exists($CFG->dirroot . "/repository/$type/lib.php")) {
542 require_once($CFG->dirroot . "/repository/$type/lib.php");
543 $classname = 'repository_' . $type;
544 $contextid = $context;
545 if (is_object($context)) {
546 $contextid = $context->id;
548 $options['type'] = $type;
549 $options['typeid'] = $record->typeid;
550 if (empty($options['name'])) {
551 $options['name'] = $record->name;
553 $repository = new $classname($repositoryid, $contextid, $options);
554 return $repository;
555 } else {
556 throw new repository_exception('invalidplugin', 'repository');
562 * Get a repository type object by a given type name.
564 * @static
565 * @param string $typename the repository type name
566 * @return repository_type|bool
568 public static function get_type_by_typename($typename) {
569 global $DB;
571 if (!$record = $DB->get_record('repository',array('type' => $typename))) {
572 return false;
575 return new repository_type($typename, (array)get_config($typename), $record->visible, $record->sortorder);
579 * Get the repository type by a given repository type id.
581 * @static
582 * @param int $id the type id
583 * @return object
585 public static function get_type_by_id($id) {
586 global $DB;
588 if (!$record = $DB->get_record('repository',array('id' => $id))) {
589 return false;
592 return new repository_type($record->type, (array)get_config($record->type), $record->visible, $record->sortorder);
596 * Return all repository types ordered by sortorder field
597 * first repository type in returnedarray[0], second repository type in returnedarray[1], ...
599 * @static
600 * @param bool $visible can return types by visiblity, return all types if null
601 * @return array Repository types
603 public static function get_types($visible=null) {
604 global $DB, $CFG;
606 $types = array();
607 $params = null;
608 if (!empty($visible)) {
609 $params = array('visible' => $visible);
611 if ($records = $DB->get_records('repository',$params,'sortorder')) {
612 foreach($records as $type) {
613 if (file_exists($CFG->dirroot . '/repository/'. $type->type .'/lib.php')) {
614 $types[] = new repository_type($type->type, (array)get_config($type->type), $type->visible, $type->sortorder);
619 return $types;
623 * Checks if user has a capability to view the current repository in current context
625 * @return bool
627 public final function check_capability() {
628 $capability = false;
629 if (preg_match("/^repository_(.*)$/", get_class($this), $matches)) {
630 $type = $matches[1];
631 $capability = has_capability('repository/'.$type.':view', $this->context);
633 if (!$capability) {
634 throw new repository_exception('nopermissiontoaccess', 'repository');
639 * Check if file already exists in draft area
641 * @static
642 * @param int $itemid
643 * @param string $filepath
644 * @param string $filename
645 * @return bool
647 public static function draftfile_exists($itemid, $filepath, $filename) {
648 global $USER;
649 $fs = get_file_storage();
650 $usercontext = context_user::instance($USER->id);
651 if ($fs->get_file($usercontext->id, 'user', 'draft', $itemid, $filepath, $filename)) {
652 return true;
653 } else {
654 return false;
659 * Parses the 'source' returned by moodle repositories and returns an instance of stored_file
661 * @param string $source
662 * @return stored_file|null
664 public static function get_moodle_file($source) {
665 $params = file_storage::unpack_reference($source, true);
666 $fs = get_file_storage();
667 return $fs->get_file($params['contextid'], $params['component'], $params['filearea'],
668 $params['itemid'], $params['filepath'], $params['filename']);
672 * Repository method to make sure that user can access particular file.
674 * This is checked when user tries to pick the file from repository to deal with
675 * potential parameter substitutions is request
677 * @param string $source
678 * @return bool whether the file is accessible by current user
680 public function file_is_accessible($source) {
681 if ($this->has_moodle_files()) {
682 try {
683 $params = file_storage::unpack_reference($source, true);
684 } catch (file_reference_exception $e) {
685 return false;
687 $browser = get_file_browser();
688 $context = context::instance_by_id($params['contextid']);
689 $file_info = $browser->get_file_info($context, $params['component'], $params['filearea'],
690 $params['itemid'], $params['filepath'], $params['filename']);
691 return !empty($file_info);
693 return true;
697 * This function is used to copy a moodle file to draft area.
699 * It DOES NOT check if the user is allowed to access this file because the actual file
700 * can be located in the area where user does not have access to but there is an alias
701 * to this file in the area where user CAN access it.
702 * {@link file_is_accessible} should be called for alias location before calling this function.
704 * @param string $source The metainfo of file, it is base64 encoded php serialized data
705 * @param stdClass|array $filerecord contains itemid, filepath, filename and optionally other
706 * attributes of the new file
707 * @param int $maxbytes maximum allowed size of file, -1 if unlimited. If size of file exceeds
708 * the limit, the file_exception is thrown.
709 * @return array The information about the created file
711 public function copy_to_area($source, $filerecord, $maxbytes = -1) {
712 global $USER;
713 $fs = get_file_storage();
715 if ($this->has_moodle_files() == false) {
716 throw new coding_exception('Only repository used to browse moodle files can use repository::copy_to_area()');
719 $user_context = context_user::instance($USER->id);
721 $filerecord = (array)$filerecord;
722 // make sure the new file will be created in user draft area
723 $filerecord['component'] = 'user';
724 $filerecord['filearea'] = 'draft';
725 $filerecord['contextid'] = $user_context->id;
726 $draftitemid = $filerecord['itemid'];
727 $new_filepath = $filerecord['filepath'];
728 $new_filename = $filerecord['filename'];
730 // the file needs to copied to draft area
731 $stored_file = self::get_moodle_file($source);
732 if ($maxbytes != -1 && $stored_file->get_filesize() > $maxbytes) {
733 throw new file_exception('maxbytes');
736 if (repository::draftfile_exists($draftitemid, $new_filepath, $new_filename)) {
737 // create new file
738 $unused_filename = repository::get_unused_filename($draftitemid, $new_filepath, $new_filename);
739 $filerecord['filename'] = $unused_filename;
740 $fs->create_file_from_storedfile($filerecord, $stored_file);
741 $event = array();
742 $event['event'] = 'fileexists';
743 $event['newfile'] = new stdClass;
744 $event['newfile']->filepath = $new_filepath;
745 $event['newfile']->filename = $unused_filename;
746 $event['newfile']->url = moodle_url::make_draftfile_url($draftitemid, $new_filepath, $unused_filename)->out();
747 $event['existingfile'] = new stdClass;
748 $event['existingfile']->filepath = $new_filepath;
749 $event['existingfile']->filename = $new_filename;
750 $event['existingfile']->url = moodle_url::make_draftfile_url($draftitemid, $new_filepath, $new_filename)->out();
751 return $event;
752 } else {
753 $fs->create_file_from_storedfile($filerecord, $stored_file);
754 $info = array();
755 $info['itemid'] = $draftitemid;
756 $info['file'] = $new_filename;
757 $info['title'] = $new_filename;
758 $info['contextid'] = $user_context->id;
759 $info['url'] = moodle_url::make_draftfile_url($draftitemid, $new_filepath, $new_filename)->out();
760 $info['filesize'] = $stored_file->get_filesize();
761 return $info;
766 * Get unused filename by appending suffix
768 * @static
769 * @param int $itemid
770 * @param string $filepath
771 * @param string $filename
772 * @return string
774 public static function get_unused_filename($itemid, $filepath, $filename) {
775 global $USER;
776 $fs = get_file_storage();
777 while (repository::draftfile_exists($itemid, $filepath, $filename)) {
778 $filename = repository::append_suffix($filename);
780 return $filename;
784 * Append a suffix to filename
786 * @static
787 * @param string $filename
788 * @return string
790 public static function append_suffix($filename) {
791 $pathinfo = pathinfo($filename);
792 if (empty($pathinfo['extension'])) {
793 return $filename . RENAME_SUFFIX;
794 } else {
795 return $pathinfo['filename'] . RENAME_SUFFIX . '.' . $pathinfo['extension'];
800 * Return all types that you a user can create/edit and which are also visible
801 * Note: Mostly used in order to know if at least one editable type can be set
803 * @static
804 * @param stdClass $context the context for which we want the editable types
805 * @return array types
807 public static function get_editable_types($context = null) {
809 if (empty($context)) {
810 $context = get_system_context();
813 $types= repository::get_types(true);
814 $editabletypes = array();
815 foreach ($types as $type) {
816 $instanceoptionnames = repository::static_function($type->get_typename(), 'get_instance_option_names');
817 if (!empty($instanceoptionnames)) {
818 if ($type->get_contextvisibility($context)) {
819 $editabletypes[]=$type;
823 return $editabletypes;
827 * Return repository instances
829 * @static
830 * @param array $args Array containing the following keys:
831 * currentcontext
832 * context
833 * onlyvisible
834 * type
835 * accepted_types
836 * return_types
837 * userid
839 * @return array repository instances
841 public static function get_instances($args = array()) {
842 global $DB, $CFG, $USER;
844 if (isset($args['currentcontext'])) {
845 $current_context = $args['currentcontext'];
846 } else {
847 $current_context = null;
850 if (!empty($args['context'])) {
851 $contexts = $args['context'];
852 } else {
853 $contexts = array();
856 $onlyvisible = isset($args['onlyvisible']) ? $args['onlyvisible'] : true;
857 $returntypes = isset($args['return_types']) ? $args['return_types'] : 3;
858 $type = isset($args['type']) ? $args['type'] : null;
860 $params = array();
861 $sql = "SELECT i.*, r.type AS repositorytype, r.sortorder, r.visible
862 FROM {repository} r, {repository_instances} i
863 WHERE i.typeid = r.id ";
865 if (!empty($args['disable_types']) && is_array($args['disable_types'])) {
866 list($types, $p) = $DB->get_in_or_equal($args['disable_types'], SQL_PARAMS_QM, 'param', false);
867 $sql .= " AND r.type $types";
868 $params = array_merge($params, $p);
871 if (!empty($args['userid']) && is_numeric($args['userid'])) {
872 $sql .= " AND (i.userid = 0 or i.userid = ?)";
873 $params[] = $args['userid'];
876 foreach ($contexts as $context) {
877 if (empty($firstcontext)) {
878 $firstcontext = true;
879 $sql .= " AND ((i.contextid = ?)";
880 } else {
881 $sql .= " OR (i.contextid = ?)";
883 $params[] = $context->id;
886 if (!empty($firstcontext)) {
887 $sql .=')';
890 if ($onlyvisible == true) {
891 $sql .= " AND (r.visible = 1)";
894 if (isset($type)) {
895 $sql .= " AND (r.type = ?)";
896 $params[] = $type;
898 $sql .= " ORDER BY r.sortorder, i.name";
900 if (!$records = $DB->get_records_sql($sql, $params)) {
901 $records = array();
904 $repositories = array();
905 if (isset($args['accepted_types'])) {
906 $accepted_types = $args['accepted_types'];
907 if (is_array($accepted_types) && in_array('*', $accepted_types)) {
908 $accepted_types = '*';
910 } else {
911 $accepted_types = '*';
913 // Sortorder should be unique, which is not true if we use $record->sortorder
914 // and there are multiple instances of any repository type
915 $sortorder = 1;
916 foreach ($records as $record) {
917 if (!file_exists($CFG->dirroot . '/repository/'. $record->repositorytype.'/lib.php')) {
918 continue;
920 require_once($CFG->dirroot . '/repository/'. $record->repositorytype.'/lib.php');
921 $options['visible'] = $record->visible;
922 $options['type'] = $record->repositorytype;
923 $options['typeid'] = $record->typeid;
924 $options['sortorder'] = $sortorder++;
925 // tell instance what file types will be accepted by file picker
926 $classname = 'repository_' . $record->repositorytype;
928 $repository = new $classname($record->id, $record->contextid, $options, $record->readonly);
930 $is_supported = true;
932 if (empty($repository->super_called)) {
933 // to make sure the super construct is called
934 debugging('parent::__construct must be called by '.$record->repositorytype.' plugin.');
935 } else {
936 // check mimetypes
937 if ($accepted_types !== '*' and $repository->supported_filetypes() !== '*') {
938 $accepted_ext = file_get_typegroup('extension', $accepted_types);
939 $supported_ext = file_get_typegroup('extension', $repository->supported_filetypes());
940 $valid_ext = array_intersect($accepted_ext, $supported_ext);
941 $is_supported = !empty($valid_ext);
943 // check return values
944 if ($returntypes !== 3 and $repository->supported_returntypes() !== 3) {
945 $type = $repository->supported_returntypes();
946 if ($type & $returntypes) {
948 } else {
949 $is_supported = false;
953 if (!$onlyvisible || ($repository->is_visible() && !$repository->disabled)) {
954 // check capability in current context
955 if (!empty($current_context)) {
956 $capability = has_capability('repository/'.$record->repositorytype.':view', $current_context);
957 } else {
958 $capability = has_capability('repository/'.$record->repositorytype.':view', get_system_context());
960 if ($record->repositorytype == 'coursefiles') {
961 // coursefiles plugin needs managefiles permission
962 if (!empty($current_context)) {
963 $capability = $capability && has_capability('moodle/course:managefiles', $current_context);
964 } else {
965 $capability = $capability && has_capability('moodle/course:managefiles', get_system_context());
968 if ($is_supported && $capability) {
969 $repositories[$repository->id] = $repository;
974 return $repositories;
978 * Get single repository instance
980 * @static
981 * @param integer $id repository id
982 * @return object repository instance
984 public static function get_instance($id) {
985 global $DB, $CFG;
986 $sql = "SELECT i.*, r.type AS repositorytype, r.visible
987 FROM {repository} r
988 JOIN {repository_instances} i ON i.typeid = r.id
989 WHERE i.id = ?";
991 if (!$instance = $DB->get_record_sql($sql, array($id))) {
992 return false;
994 require_once($CFG->dirroot . '/repository/'. $instance->repositorytype.'/lib.php');
995 $classname = 'repository_' . $instance->repositorytype;
996 $options['typeid'] = $instance->typeid;
997 $options['type'] = $instance->repositorytype;
998 $options['name'] = $instance->name;
999 $obj = new $classname($instance->id, $instance->contextid, $options, $instance->readonly);
1000 if (empty($obj->super_called)) {
1001 debugging('parent::__construct must be called by '.$classname.' plugin.');
1003 return $obj;
1007 * Call a static function. Any additional arguments than plugin and function will be passed through.
1009 * @static
1010 * @param string $plugin repository plugin name
1011 * @param string $function funciton name
1012 * @return mixed
1014 public static function static_function($plugin, $function) {
1015 global $CFG;
1017 //check that the plugin exists
1018 $typedirectory = $CFG->dirroot . '/repository/'. $plugin . '/lib.php';
1019 if (!file_exists($typedirectory)) {
1020 //throw new repository_exception('invalidplugin', 'repository');
1021 return false;
1024 $pname = null;
1025 if (is_object($plugin) || is_array($plugin)) {
1026 $plugin = (object)$plugin;
1027 $pname = $plugin->name;
1028 } else {
1029 $pname = $plugin;
1032 $args = func_get_args();
1033 if (count($args) <= 2) {
1034 $args = array();
1035 } else {
1036 array_shift($args);
1037 array_shift($args);
1040 require_once($typedirectory);
1041 return call_user_func_array(array('repository_' . $plugin, $function), $args);
1045 * Scan file, throws exception in case of infected file.
1047 * Please note that the scanning engine must be able to access the file,
1048 * permissions of the file are not modified here!
1050 * @static
1051 * @param string $thefile
1052 * @param string $filename name of the file
1053 * @param bool $deleteinfected
1055 public static function antivir_scan_file($thefile, $filename, $deleteinfected) {
1056 global $CFG;
1058 if (!is_readable($thefile)) {
1059 // this should not happen
1060 return;
1063 if (empty($CFG->runclamonupload) or empty($CFG->pathtoclam)) {
1064 // clam not enabled
1065 return;
1068 $CFG->pathtoclam = trim($CFG->pathtoclam);
1070 if (!file_exists($CFG->pathtoclam) or !is_executable($CFG->pathtoclam)) {
1071 // misconfigured clam - use the old notification for now
1072 require("$CFG->libdir/uploadlib.php");
1073 $notice = get_string('clamlost', 'moodle', $CFG->pathtoclam);
1074 clam_message_admins($notice);
1075 return;
1078 // do NOT mess with permissions here, the calling party is responsible for making
1079 // sure the scanner engine can access the files!
1081 // execute test
1082 $cmd = escapeshellcmd($CFG->pathtoclam).' --stdout '.escapeshellarg($thefile);
1083 exec($cmd, $output, $return);
1085 if ($return == 0) {
1086 // perfect, no problem found
1087 return;
1089 } else if ($return == 1) {
1090 // infection found
1091 if ($deleteinfected) {
1092 unlink($thefile);
1094 throw new moodle_exception('virusfounduser', 'moodle', '', array('filename'=>$filename));
1096 } else {
1097 //unknown problem
1098 require("$CFG->libdir/uploadlib.php");
1099 $notice = get_string('clamfailed', 'moodle', get_clam_error_code($return));
1100 $notice .= "\n\n". implode("\n", $output);
1101 clam_message_admins($notice);
1102 if ($CFG->clamfailureonupload === 'actlikevirus') {
1103 if ($deleteinfected) {
1104 unlink($thefile);
1106 throw new moodle_exception('virusfounduser', 'moodle', '', array('filename'=>$filename));
1107 } else {
1108 return;
1114 * Repository method to serve the referenced file
1116 * @see send_stored_file
1118 * @param stored_file $storedfile the file that contains the reference
1119 * @param int $lifetime Number of seconds before the file should expire from caches (default 24 hours)
1120 * @param int $filter 0 (default)=no filtering, 1=all files, 2=html files only
1121 * @param bool $forcedownload If true (default false), forces download of file rather than view in browser/plugin
1122 * @param array $options additional options affecting the file serving
1124 public function send_file($storedfile, $lifetime=86400 , $filter=0, $forcedownload=false, array $options = null) {
1125 if ($this->has_moodle_files()) {
1126 $fs = get_file_storage();
1127 $params = file_storage::unpack_reference($storedfile->get_reference(), true);
1128 $srcfile = null;
1129 if (is_array($params)) {
1130 $srcfile = $fs->get_file($params['contextid'], $params['component'], $params['filearea'],
1131 $params['itemid'], $params['filepath'], $params['filename']);
1133 if (empty($options)) {
1134 $options = array();
1136 if (!isset($options['filename'])) {
1137 $options['filename'] = $storedfile->get_filename();
1139 if (!$srcfile) {
1140 send_file_not_found();
1141 } else {
1142 send_stored_file($srcfile, $lifetime, $filter, $forcedownload, $options);
1144 } else {
1145 throw new coding_exception("Repository plugin must implement send_file() method.");
1150 * Return reference file life time
1152 * @param string $ref
1153 * @return int
1155 public function get_reference_file_lifetime($ref) {
1156 // One day
1157 return 60 * 60 * 24;
1161 * Decide whether or not the file should be synced
1163 * @param stored_file $storedfile
1164 * @return bool
1166 public function sync_individual_file(stored_file $storedfile) {
1167 return true;
1171 * Return human readable reference information
1173 * @param string $reference value of DB field files_reference.reference
1174 * @param int $filestatus status of the file, 0 - ok, 666 - source missing
1175 * @return string
1177 public function get_reference_details($reference, $filestatus = 0) {
1178 if ($this->has_moodle_files()) {
1179 $fileinfo = null;
1180 $params = file_storage::unpack_reference($reference, true);
1181 if (is_array($params)) {
1182 $context = context::instance_by_id($params['contextid'], IGNORE_MISSING);
1183 if ($context) {
1184 $browser = get_file_browser();
1185 $fileinfo = $browser->get_file_info($context, $params['component'], $params['filearea'], $params['itemid'], $params['filepath'], $params['filename']);
1188 if (empty($fileinfo)) {
1189 if ($filestatus == 666) {
1190 if (is_siteadmin() || ($context && has_capability('moodle/course:managefiles', $context))) {
1191 return get_string('lostsource', 'repository',
1192 $params['contextid']. '/'. $params['component']. '/'. $params['filearea']. '/'. $params['itemid']. $params['filepath']. $params['filename']);
1193 } else {
1194 return get_string('lostsource', 'repository', '');
1197 return get_string('undisclosedsource', 'repository');
1198 } else {
1199 return $fileinfo->get_readable_fullname();
1202 return '';
1206 * Cache file from external repository by reference
1207 * {@link repository::get_file_reference()}
1208 * {@link repository::get_file()}
1209 * Invoked at MOODLE/repository/repository_ajax.php
1211 * @param string $reference this reference is generated by
1212 * repository::get_file_reference()
1213 * @param stored_file $storedfile created file reference
1215 public function cache_file_by_reference($reference, $storedfile) {
1219 * Returns information about file in this repository by reference
1221 * This function must be implemented for repositories supporting FILE_REFERENCE, it is called
1222 * for existing aliases when the lifetime of the previous syncronisation has expired.
1224 * Returns null if file not found or is not readable or timeout occured during request.
1225 * Note that this function may be run for EACH file that needs to be synchronised at the
1226 * moment. If anything is being downloaded or requested from external sources there
1227 * should be a small timeout. The synchronisation is performed to update the size of
1228 * the file and/or to update image and re-generated image preview. There is nothing
1229 * fatal if syncronisation fails but it is fatal if syncronisation takes too long
1230 * and hangs the script generating a page.
1232 * If get_file_by_reference() returns filesize just the record in {files} table is being updated.
1233 * If filepath, handle or content are returned - the file is also stored in moodle filepool
1234 * (recommended for images to generate the thumbnails). For non-image files it is not
1235 * recommended to download them to moodle during syncronisation since it may take
1236 * unnecessary long time.
1238 * @param stdClass $reference record from DB table {files_reference}
1239 * @return stdClass|null contains one of the following:
1240 * - 'filesize' and optionally 'contenthash'
1241 * - 'filepath'
1242 * - 'handle'
1243 * - 'content'
1245 public function get_file_by_reference($reference) {
1246 if ($this->has_moodle_files() && isset($reference->reference)) {
1247 $fs = get_file_storage();
1248 $params = file_storage::unpack_reference($reference->reference, true);
1249 if (!is_array($params) || !($storedfile = $fs->get_file($params['contextid'],
1250 $params['component'], $params['filearea'], $params['itemid'], $params['filepath'],
1251 $params['filename']))) {
1252 return null;
1254 return (object)array(
1255 'contenthash' => $storedfile->get_contenthash(),
1256 'filesize' => $storedfile->get_filesize()
1259 return null;
1263 * Return the source information
1265 * The result of the function is stored in files.source field. It may be analysed
1266 * when the source file is lost or repository may use it to display human-readable
1267 * location of reference original.
1269 * This method is called when file is picked for the first time only. When file
1270 * (either copy or a reference) is already in moodle and it is being picked
1271 * again to another file area (also as a copy or as a reference), the value of
1272 * files.source is copied.
1274 * @param string $source the value that repository returned in listing as 'source'
1275 * @return string|null
1277 public function get_file_source_info($source) {
1278 if ($this->has_moodle_files()) {
1279 return $this->get_reference_details($source, 0);
1281 return $source;
1285 * Move file from download folder to file pool using FILE API
1287 * @todo MDL-28637
1288 * @static
1289 * @param string $thefile file path in download folder
1290 * @param stdClass $record
1291 * @return array containing the following keys:
1292 * icon
1293 * file
1294 * id
1295 * url
1297 public static function move_to_filepool($thefile, $record) {
1298 global $DB, $CFG, $USER, $OUTPUT;
1300 // scan for viruses if possible, throws exception if problem found
1301 self::antivir_scan_file($thefile, $record->filename, empty($CFG->repository_no_delete)); //TODO: MDL-28637 this repository_no_delete is a bloody hack!
1303 $fs = get_file_storage();
1304 // If file name being used.
1305 if (repository::draftfile_exists($record->itemid, $record->filepath, $record->filename)) {
1306 $draftitemid = $record->itemid;
1307 $new_filename = repository::get_unused_filename($draftitemid, $record->filepath, $record->filename);
1308 $old_filename = $record->filename;
1309 // Create a tmp file.
1310 $record->filename = $new_filename;
1311 $newfile = $fs->create_file_from_pathname($record, $thefile);
1312 $event = array();
1313 $event['event'] = 'fileexists';
1314 $event['newfile'] = new stdClass;
1315 $event['newfile']->filepath = $record->filepath;
1316 $event['newfile']->filename = $new_filename;
1317 $event['newfile']->url = moodle_url::make_draftfile_url($draftitemid, $record->filepath, $new_filename)->out();
1319 $event['existingfile'] = new stdClass;
1320 $event['existingfile']->filepath = $record->filepath;
1321 $event['existingfile']->filename = $old_filename;
1322 $event['existingfile']->url = moodle_url::make_draftfile_url($draftitemid, $record->filepath, $old_filename)->out();;
1323 return $event;
1325 if ($file = $fs->create_file_from_pathname($record, $thefile)) {
1326 if (empty($CFG->repository_no_delete)) {
1327 $delete = unlink($thefile);
1328 unset($CFG->repository_no_delete);
1330 return array(
1331 'url'=>moodle_url::make_draftfile_url($file->get_itemid(), $file->get_filepath(), $file->get_filename())->out(),
1332 'id'=>$file->get_itemid(),
1333 'file'=>$file->get_filename(),
1334 'icon' => $OUTPUT->pix_url(file_extension_icon($thefile, 32))->out(),
1336 } else {
1337 return null;
1342 * Builds a tree of files This function is then called recursively.
1344 * @static
1345 * @todo take $search into account, and respect a threshold for dynamic loading
1346 * @param file_info $fileinfo an object returned by file_browser::get_file_info()
1347 * @param string $search searched string
1348 * @param bool $dynamicmode no recursive call is done when in dynamic mode
1349 * @param array $list the array containing the files under the passed $fileinfo
1350 * @return int the number of files found
1352 public static function build_tree($fileinfo, $search, $dynamicmode, &$list) {
1353 global $CFG, $OUTPUT;
1355 $filecount = 0;
1356 $children = $fileinfo->get_children();
1358 foreach ($children as $child) {
1359 $filename = $child->get_visible_name();
1360 $filesize = $child->get_filesize();
1361 $filesize = $filesize ? display_size($filesize) : '';
1362 $filedate = $child->get_timemodified();
1363 $filedate = $filedate ? userdate($filedate) : '';
1364 $filetype = $child->get_mimetype();
1366 if ($child->is_directory()) {
1367 $path = array();
1368 $level = $child->get_parent();
1369 while ($level) {
1370 $params = $level->get_params();
1371 $path[] = array($params['filepath'], $level->get_visible_name());
1372 $level = $level->get_parent();
1375 $tmp = array(
1376 'title' => $child->get_visible_name(),
1377 'size' => 0,
1378 'date' => $filedate,
1379 'path' => array_reverse($path),
1380 'thumbnail' => $OUTPUT->pix_url(file_folder_icon(90))->out(false)
1383 //if ($dynamicmode && $child->is_writable()) {
1384 // $tmp['children'] = array();
1385 //} else {
1386 // if folder name matches search, we send back all files contained.
1387 $_search = $search;
1388 if ($search && stristr($tmp['title'], $search) !== false) {
1389 $_search = false;
1391 $tmp['children'] = array();
1392 $_filecount = repository::build_tree($child, $_search, $dynamicmode, $tmp['children']);
1393 if ($search && $_filecount) {
1394 $tmp['expanded'] = 1;
1399 if (!$search || $_filecount || (stristr($tmp['title'], $search) !== false)) {
1400 $filecount += $_filecount;
1401 $list[] = $tmp;
1404 } else { // not a directory
1405 // skip the file, if we're in search mode and it's not a match
1406 if ($search && (stristr($filename, $search) === false)) {
1407 continue;
1409 $params = $child->get_params();
1410 $source = serialize(array($params['contextid'], $params['component'], $params['filearea'], $params['itemid'], $params['filepath'], $params['filename']));
1411 $list[] = array(
1412 'title' => $filename,
1413 'size' => $filesize,
1414 'date' => $filedate,
1415 //'source' => $child->get_url(),
1416 'source' => base64_encode($source),
1417 'icon'=>$OUTPUT->pix_url(file_file_icon($child, 24))->out(false),
1418 'thumbnail'=>$OUTPUT->pix_url(file_file_icon($child, 90))->out(false),
1420 $filecount++;
1424 return $filecount;
1428 * Display a repository instance list (with edit/delete/create links)
1430 * @static
1431 * @param stdClass $context the context for which we display the instance
1432 * @param string $typename if set, we display only one type of instance
1434 public static function display_instances_list($context, $typename = null) {
1435 global $CFG, $USER, $OUTPUT;
1437 $output = $OUTPUT->box_start('generalbox');
1438 //if the context is SYSTEM, so we call it from administration page
1439 $admin = ($context->id == SYSCONTEXTID) ? true : false;
1440 if ($admin) {
1441 $baseurl = new moodle_url('/'.$CFG->admin.'/repositoryinstance.php', array('sesskey'=>sesskey()));
1442 $output .= $OUTPUT->heading(get_string('siteinstances', 'repository'));
1443 } else {
1444 $baseurl = new moodle_url('/repository/manage_instances.php', array('contextid'=>$context->id, 'sesskey'=>sesskey()));
1447 $namestr = get_string('name');
1448 $pluginstr = get_string('plugin', 'repository');
1449 $settingsstr = get_string('settings');
1450 $deletestr = get_string('delete');
1451 //retrieve list of instances. In administration context we want to display all
1452 //instances of a type, even if this type is not visible. In course/user context we
1453 //want to display only visible instances, but for every type types. The repository::get_instances()
1454 //third parameter displays only visible type.
1455 $params = array();
1456 $params['context'] = array($context, get_system_context());
1457 $params['currentcontext'] = $context;
1458 $params['onlyvisible'] = !$admin;
1459 $params['type'] = $typename;
1460 $instances = repository::get_instances($params);
1461 $instancesnumber = count($instances);
1462 $alreadyplugins = array();
1464 $table = new html_table();
1465 $table->head = array($namestr, $pluginstr, $settingsstr, $deletestr);
1466 $table->align = array('left', 'left', 'center','center');
1467 $table->data = array();
1469 $updowncount = 1;
1471 foreach ($instances as $i) {
1472 $settings = '';
1473 $delete = '';
1475 $type = repository::get_type_by_id($i->options['typeid']);
1477 if ($type->get_contextvisibility($context)) {
1478 if (!$i->readonly) {
1480 $settingurl = new moodle_url($baseurl);
1481 $settingurl->param('type', $i->options['type']);
1482 $settingurl->param('edit', $i->id);
1483 $settings .= html_writer::link($settingurl, $settingsstr);
1485 $deleteurl = new moodle_url($baseurl);
1486 $deleteurl->param('delete', $i->id);
1487 $deleteurl->param('type', $i->options['type']);
1488 $delete .= html_writer::link($deleteurl, $deletestr);
1492 $type = repository::get_type_by_id($i->options['typeid']);
1493 $table->data[] = array(format_string($i->name), $type->get_readablename(), $settings, $delete);
1495 //display a grey row if the type is defined as not visible
1496 if (isset($type) && !$type->get_visible()) {
1497 $table->rowclasses[] = 'dimmed_text';
1498 } else {
1499 $table->rowclasses[] = '';
1502 if (!in_array($i->name, $alreadyplugins)) {
1503 $alreadyplugins[] = $i->name;
1506 $output .= html_writer::table($table);
1507 $instancehtml = '<div>';
1508 $addable = 0;
1510 //if no type is set, we can create all type of instance
1511 if (!$typename) {
1512 $instancehtml .= '<h3>';
1513 $instancehtml .= get_string('createrepository', 'repository');
1514 $instancehtml .= '</h3><ul>';
1515 $types = repository::get_editable_types($context);
1516 foreach ($types as $type) {
1517 if (!empty($type) && $type->get_visible()) {
1518 // If the user does not have the permission to view the repository, it won't be displayed in
1519 // the list of instances. Hiding the link to create new instances will prevent the
1520 // user from creating them without being able to find them afterwards, which looks like a bug.
1521 if (!has_capability('repository/'.$type->get_typename().':view', $context)) {
1522 continue;
1524 $instanceoptionnames = repository::static_function($type->get_typename(), 'get_instance_option_names');
1525 if (!empty($instanceoptionnames)) {
1526 $baseurl->param('new', $type->get_typename());
1527 $instancehtml .= '<li><a href="'.$baseurl->out().'">'.get_string('createxxinstance', 'repository', get_string('pluginname', 'repository_'.$type->get_typename())). '</a></li>';
1528 $baseurl->remove_params('new');
1529 $addable++;
1533 $instancehtml .= '</ul>';
1535 } else {
1536 $instanceoptionnames = repository::static_function($typename, 'get_instance_option_names');
1537 if (!empty($instanceoptionnames)) { //create a unique type of instance
1538 $addable = 1;
1539 $baseurl->param('new', $typename);
1540 $output .= $OUTPUT->single_button($baseurl, get_string('createinstance', 'repository'), 'get');
1541 $baseurl->remove_params('new');
1545 if ($addable) {
1546 $instancehtml .= '</div>';
1547 $output .= $instancehtml;
1550 $output .= $OUTPUT->box_end();
1552 //print the list + creation links
1553 print($output);
1557 * Prepare file reference information
1559 * @param string $source
1560 * @return string file referece
1562 public function get_file_reference($source) {
1563 if ($this->has_moodle_files() && ($this->supported_returntypes() & FILE_REFERENCE)) {
1564 $params = file_storage::unpack_reference($source);
1565 if (!is_array($params)) {
1566 throw new repository_exception('invalidparams', 'repository');
1568 return file_storage::pack_reference($params);
1570 return $source;
1574 * Decide where to save the file, can be overwriten by subclass
1576 * @param string $filename file name
1577 * @return file path
1579 public function prepare_file($filename) {
1580 global $CFG;
1581 $dir = make_temp_directory('download/'.get_class($this).'/');
1582 while (empty($filename) || file_exists($dir.$filename)) {
1583 $filename = uniqid('', true).'_'.time().'.tmp';
1585 return $dir.$filename;
1589 * Does this repository used to browse moodle files?
1591 * @return bool
1593 public function has_moodle_files() {
1594 return false;
1598 * Return file URL, for most plugins, the parameter is the original
1599 * url, but some plugins use a file id, so we need this function to
1600 * convert file id to original url.
1602 * @param string $url the url of file
1603 * @return string
1605 public function get_link($url) {
1606 return $url;
1610 * Downloads a file from external repository and saves it in temp dir
1612 * Function get_file() must be implemented by repositories that support returntypes
1613 * FILE_INTERNAL or FILE_REFERENCE. It is invoked to pick up the file and copy it
1614 * to moodle. This function is not called for moodle repositories, the function
1615 * {@link repository::copy_to_area()} is used instead.
1617 * This function can be overridden by subclass if the files.reference field contains
1618 * not just URL or if request should be done differently.
1620 * @see curl
1621 * @throws file_exception when error occured
1623 * @param string $url the content of files.reference field, in this implementaion
1624 * it is asssumed that it contains the string with URL of the file
1625 * @param string $filename filename (without path) to save the downloaded file in the
1626 * temporary directory, if omitted or file already exists the new filename will be generated
1627 * @return array with elements:
1628 * path: internal location of the file
1629 * url: URL to the source (from parameters)
1631 public function get_file($url, $filename = '') {
1632 $path = $this->prepare_file($filename);
1633 $c = new curl;
1634 $result = $c->download_one($url, null, array('filepath' => $path, 'timeout' => self::GETFILE_TIMEOUT));
1635 if ($result !== true) {
1636 throw new moodle_exception('errorwhiledownload', 'repository', '', $result);
1638 return array('path'=>$path, 'url'=>$url);
1642 * Downloads the file from external repository and saves it in moodle filepool.
1643 * This function is different from {@link repository::sync_external_file()} because it has
1644 * bigger request timeout and always downloads the content.
1646 * This function is invoked when we try to unlink the file from the source and convert
1647 * a reference into a true copy.
1649 * @throws exception when file could not be imported
1651 * @param stored_file $file
1652 * @param int $maxbytes throw an exception if file size is bigger than $maxbytes (0 means no limit)
1654 public function import_external_file_contents(stored_file $file, $maxbytes = 0) {
1655 if (!$file->is_external_file()) {
1656 // nothing to import if the file is not a reference
1657 return;
1658 } else if ($file->get_repository_id() != $this->id) {
1659 // error
1660 debugging('Repository instance id does not match');
1661 return;
1662 } else if ($this->has_moodle_files()) {
1663 // files that are references to local files are already in moodle filepool
1664 // just validate the size
1665 if ($maxbytes > 0 && $file->get_filesize() > $maxbytes) {
1666 throw new file_exception('maxbytes');
1668 return;
1669 } else {
1670 if ($maxbytes > 0 && $file->get_filesize() > $maxbytes) {
1671 // note that stored_file::get_filesize() also calls synchronisation
1672 throw new file_exception('maxbytes');
1674 $fs = get_file_storage();
1675 $contentexists = $fs->content_exists($file->get_contenthash());
1676 if ($contentexists && $file->get_filesize() && $file->get_contenthash() === sha1('')) {
1677 // even when 'file_storage::content_exists()' returns true this may be an empty
1678 // content for the file that was not actually downloaded
1679 $contentexists = false;
1681 $now = time();
1682 if ($file->get_referencelastsync() + $file->get_referencelifetime() >= $now &&
1683 !$file->get_status() &&
1684 $contentexists) {
1685 // we already have the content in moodle filepool and it was synchronised recently.
1686 // Repositories may overwrite it if they want to force synchronisation anyway!
1687 return;
1688 } else {
1689 // attempt to get a file
1690 try {
1691 $fileinfo = $this->get_file($file->get_reference());
1692 if (isset($fileinfo['path'])) {
1693 list($contenthash, $filesize, $newfile) = $fs->add_file_to_pool($fileinfo['path']);
1694 // set this file and other similar aliases synchronised
1695 $lifetime = $this->get_reference_file_lifetime($file->get_reference());
1696 $file->set_synchronized($contenthash, $filesize, 0, $lifetime);
1697 } else {
1698 throw new moodle_exception('errorwhiledownload', 'repository', '', '');
1700 } catch (Exception $e) {
1701 if ($contentexists) {
1702 // better something than nothing. We have a copy of file. It's sync time
1703 // has expired but it is still very likely that it is the last version
1704 } else {
1705 throw($e);
1713 * Return size of a file in bytes.
1715 * @param string $source encoded and serialized data of file
1716 * @return int file size in bytes
1718 public function get_file_size($source) {
1719 // TODO MDL-33297 remove this function completely?
1720 $browser = get_file_browser();
1721 $params = unserialize(base64_decode($source));
1722 $contextid = clean_param($params['contextid'], PARAM_INT);
1723 $fileitemid = clean_param($params['itemid'], PARAM_INT);
1724 $filename = clean_param($params['filename'], PARAM_FILE);
1725 $filepath = clean_param($params['filepath'], PARAM_PATH);
1726 $filearea = clean_param($params['filearea'], PARAM_AREA);
1727 $component = clean_param($params['component'], PARAM_COMPONENT);
1728 $context = context::instance_by_id($contextid);
1729 $file_info = $browser->get_file_info($context, $component, $filearea, $fileitemid, $filepath, $filename);
1730 if (!empty($file_info)) {
1731 $filesize = $file_info->get_filesize();
1732 } else {
1733 $filesize = null;
1735 return $filesize;
1739 * Return is the instance is visible
1740 * (is the type visible ? is the context enable ?)
1742 * @return bool
1744 public function is_visible() {
1745 $type = repository::get_type_by_id($this->options['typeid']);
1746 $instanceoptions = repository::static_function($type->get_typename(), 'get_instance_option_names');
1748 if ($type->get_visible()) {
1749 //if the instance is unique so it's visible, otherwise check if the instance has a enabled context
1750 if (empty($instanceoptions) || $type->get_contextvisibility($this->context)) {
1751 return true;
1755 return false;
1759 * Return the name of this instance, can be overridden.
1761 * @return string
1763 public function get_name() {
1764 global $DB;
1765 if ( $name = $this->instance->name ) {
1766 return $name;
1767 } else {
1768 return get_string('pluginname', 'repository_' . $this->options['type']);
1773 * What kind of files will be in this repository?
1775 * @return array return '*' means this repository support any files, otherwise
1776 * return mimetypes of files, it can be an array
1778 public function supported_filetypes() {
1779 // return array('text/plain', 'image/gif');
1780 return '*';
1784 * Tells how the file can be picked from this repository
1786 * Maximum value is FILE_INTERNAL | FILE_EXTERNAL | FILE_REFERENCE
1788 * @return int
1790 public function supported_returntypes() {
1791 return (FILE_INTERNAL | FILE_EXTERNAL);
1795 * Provide repository instance information for Ajax
1797 * @return stdClass
1799 final public function get_meta() {
1800 global $CFG, $OUTPUT;
1801 $meta = new stdClass();
1802 $meta->id = $this->id;
1803 $meta->name = format_string($this->get_name());
1804 $meta->type = $this->options['type'];
1805 $meta->icon = $OUTPUT->pix_url('icon', 'repository_'.$meta->type)->out(false);
1806 $meta->supported_types = file_get_typegroup('extension', $this->supported_filetypes());
1807 $meta->return_types = $this->supported_returntypes();
1808 $meta->sortorder = $this->options['sortorder'];
1809 return $meta;
1813 * Create an instance for this plug-in
1815 * @static
1816 * @param string $type the type of the repository
1817 * @param int $userid the user id
1818 * @param stdClass $context the context
1819 * @param array $params the options for this instance
1820 * @param int $readonly whether to create it readonly or not (defaults to not)
1821 * @return mixed
1823 public static function create($type, $userid, $context, $params, $readonly=0) {
1824 global $CFG, $DB;
1825 $params = (array)$params;
1826 require_once($CFG->dirroot . '/repository/'. $type . '/lib.php');
1827 $classname = 'repository_' . $type;
1828 if ($repo = $DB->get_record('repository', array('type'=>$type))) {
1829 $record = new stdClass();
1830 $record->name = $params['name'];
1831 $record->typeid = $repo->id;
1832 $record->timecreated = time();
1833 $record->timemodified = time();
1834 $record->contextid = $context->id;
1835 $record->readonly = $readonly;
1836 $record->userid = $userid;
1837 $id = $DB->insert_record('repository_instances', $record);
1838 $options = array();
1839 $configs = call_user_func($classname . '::get_instance_option_names');
1840 if (!empty($configs)) {
1841 foreach ($configs as $config) {
1842 if (isset($params[$config])) {
1843 $options[$config] = $params[$config];
1844 } else {
1845 $options[$config] = null;
1850 if (!empty($id)) {
1851 unset($options['name']);
1852 $instance = repository::get_instance($id);
1853 $instance->set_option($options);
1854 return $id;
1855 } else {
1856 return null;
1858 } else {
1859 return null;
1864 * delete a repository instance
1866 * @param bool $downloadcontents
1867 * @return bool
1869 final public function delete($downloadcontents = false) {
1870 global $DB;
1871 if ($downloadcontents) {
1872 $this->convert_references_to_local();
1874 try {
1875 $DB->delete_records('repository_instances', array('id'=>$this->id));
1876 $DB->delete_records('repository_instance_config', array('instanceid'=>$this->id));
1877 } catch (dml_exception $ex) {
1878 return false;
1880 return true;
1884 * Hide/Show a repository
1886 * @param string $hide
1887 * @return bool
1889 final public function hide($hide = 'toggle') {
1890 global $DB;
1891 if ($entry = $DB->get_record('repository', array('id'=>$this->id))) {
1892 if ($hide === 'toggle' ) {
1893 if (!empty($entry->visible)) {
1894 $entry->visible = 0;
1895 } else {
1896 $entry->visible = 1;
1898 } else {
1899 if (!empty($hide)) {
1900 $entry->visible = 0;
1901 } else {
1902 $entry->visible = 1;
1905 return $DB->update_record('repository', $entry);
1907 return false;
1911 * Save settings for repository instance
1912 * $repo->set_option(array('api_key'=>'f2188bde132', 'name'=>'dongsheng'));
1914 * @param array $options settings
1915 * @return bool
1917 public function set_option($options = array()) {
1918 global $DB;
1920 if (!empty($options['name'])) {
1921 $r = new stdClass();
1922 $r->id = $this->id;
1923 $r->name = $options['name'];
1924 $DB->update_record('repository_instances', $r);
1925 unset($options['name']);
1927 foreach ($options as $name=>$value) {
1928 if ($id = $DB->get_field('repository_instance_config', 'id', array('name'=>$name, 'instanceid'=>$this->id))) {
1929 $DB->set_field('repository_instance_config', 'value', $value, array('id'=>$id));
1930 } else {
1931 $config = new stdClass();
1932 $config->instanceid = $this->id;
1933 $config->name = $name;
1934 $config->value = $value;
1935 $DB->insert_record('repository_instance_config', $config);
1938 return true;
1942 * Get settings for repository instance
1944 * @param string $config
1945 * @return array Settings
1947 public function get_option($config = '') {
1948 global $DB;
1949 $entries = $DB->get_records('repository_instance_config', array('instanceid'=>$this->id));
1950 $ret = array();
1951 if (empty($entries)) {
1952 return $ret;
1954 foreach($entries as $entry) {
1955 $ret[$entry->name] = $entry->value;
1957 if (!empty($config)) {
1958 if (isset($ret[$config])) {
1959 return $ret[$config];
1960 } else {
1961 return null;
1963 } else {
1964 return $ret;
1969 * Filter file listing to display specific types
1971 * @param array $value
1972 * @return bool
1974 public function filter(&$value) {
1975 $accepted_types = optional_param_array('accepted_types', '', PARAM_RAW);
1976 if (isset($value['children'])) {
1977 if (!empty($value['children'])) {
1978 $value['children'] = array_filter($value['children'], array($this, 'filter'));
1980 return true; // always return directories
1981 } else {
1982 if ($accepted_types == '*' or empty($accepted_types)
1983 or (is_array($accepted_types) and in_array('*', $accepted_types))) {
1984 return true;
1985 } else {
1986 foreach ($accepted_types as $ext) {
1987 if (preg_match('#'.$ext.'$#i', $value['title'])) {
1988 return true;
1993 return false;
1997 * Given a path, and perhaps a search, get a list of files.
1999 * See details on {@link http://docs.moodle.org/dev/Repository_plugins}
2001 * @param string $path this parameter can a folder name, or a identification of folder
2002 * @param string $page the page number of file list
2003 * @return array the list of files, including meta infomation, containing the following keys
2004 * manage, url to manage url
2005 * client_id
2006 * login, login form
2007 * repo_id, active repository id
2008 * login_btn_action, the login button action
2009 * login_btn_label, the login button label
2010 * total, number of results
2011 * perpage, items per page
2012 * page
2013 * pages, total pages
2014 * issearchresult, is it a search result?
2015 * list, file list
2016 * path, current path and parent path
2018 public function get_listing($path = '', $page = '') {
2023 * Prepare the breadcrumb.
2025 * @param array $breadcrumb contains each element of the breadcrumb.
2026 * @return array of breadcrumb elements.
2027 * @since 2.3.3
2029 protected static function prepare_breadcrumb($breadcrumb) {
2030 global $OUTPUT;
2031 $foldericon = $OUTPUT->pix_url(file_folder_icon(24))->out(false);
2032 $len = count($breadcrumb);
2033 for ($i = 0; $i < $len; $i++) {
2034 if (is_array($breadcrumb[$i]) && !isset($breadcrumb[$i]['icon'])) {
2035 $breadcrumb[$i]['icon'] = $foldericon;
2036 } else if (is_object($breadcrumb[$i]) && !isset($breadcrumb[$i]->icon)) {
2037 $breadcrumb[$i]->icon = $foldericon;
2040 return $breadcrumb;
2044 * Prepare the file/folder listing.
2046 * @param array $list of files and folders.
2047 * @return array of files and folders.
2048 * @since 2.3.3
2050 protected static function prepare_list($list) {
2051 global $OUTPUT;
2052 $foldericon = $OUTPUT->pix_url(file_folder_icon(24))->out(false);
2054 // Reset the array keys because non-numeric keys will create an object when converted to JSON.
2055 $list = array_values($list);
2057 $len = count($list);
2058 for ($i = 0; $i < $len; $i++) {
2059 if (is_object($list[$i])) {
2060 $file = (array)$list[$i];
2061 $converttoobject = true;
2062 } else {
2063 $file =& $list[$i];
2064 $converttoobject = false;
2066 if (isset($file['size'])) {
2067 $file['size'] = (int)$file['size'];
2068 $file['size_f'] = display_size($file['size']);
2070 if (isset($file['license']) && get_string_manager()->string_exists($file['license'], 'license')) {
2071 $file['license_f'] = get_string($file['license'], 'license');
2073 if (isset($file['image_width']) && isset($file['image_height'])) {
2074 $a = array('width' => $file['image_width'], 'height' => $file['image_height']);
2075 $file['dimensions'] = get_string('imagesize', 'repository', (object)$a);
2077 foreach (array('date', 'datemodified', 'datecreated') as $key) {
2078 if (!isset($file[$key]) && isset($file['date'])) {
2079 $file[$key] = $file['date'];
2081 if (isset($file[$key])) {
2082 // must be UNIX timestamp
2083 $file[$key] = (int)$file[$key];
2084 if (!$file[$key]) {
2085 unset($file[$key]);
2086 } else {
2087 $file[$key.'_f'] = userdate($file[$key], get_string('strftimedatetime', 'langconfig'));
2088 $file[$key.'_f_s'] = userdate($file[$key], get_string('strftimedatetimeshort', 'langconfig'));
2092 $isfolder = (array_key_exists('children', $file) || (isset($file['type']) && $file['type'] == 'folder'));
2093 $filename = null;
2094 if (isset($file['title'])) {
2095 $filename = $file['title'];
2097 else if (isset($file['fullname'])) {
2098 $filename = $file['fullname'];
2100 if (!isset($file['mimetype']) && !$isfolder && $filename) {
2101 $file['mimetype'] = get_mimetype_description(array('filename' => $filename));
2103 if (!isset($file['icon'])) {
2104 if ($isfolder) {
2105 $file['icon'] = $foldericon;
2106 } else if ($filename) {
2107 $file['icon'] = $OUTPUT->pix_url(file_extension_icon($filename, 24))->out(false);
2111 // Recursively loop over children.
2112 if (isset($file['children'])) {
2113 $file['children'] = self::prepare_list($file['children']);
2116 // Convert the array back to an object.
2117 if ($converttoobject) {
2118 $list[$i] = (object)$file;
2121 return $list;
2125 * Prepares list of files before passing it to AJAX, makes sure data is in the correct
2126 * format and stores formatted values.
2128 * @param array|stdClass $listing result of get_listing() or search() or file_get_drafarea_files()
2129 * @return array
2131 public static function prepare_listing($listing) {
2132 $wasobject = false;
2133 if (is_object($listing)) {
2134 $listing = (array) $listing;
2135 $wasobject = true;
2138 // Prepare the breadcrumb, passed as 'path'.
2139 if (isset($listing['path']) && is_array($listing['path'])) {
2140 $listing['path'] = self::prepare_breadcrumb($listing['path']);
2143 // Prepare the listing of objects.
2144 if (isset($listing['list']) && is_array($listing['list'])) {
2145 $listing['list'] = self::prepare_list($listing['list']);
2148 // Convert back to an object.
2149 if ($wasobject) {
2150 $listing = (object) $listing;
2152 return $listing;
2156 * Search files in repository
2157 * When doing global search, $search_text will be used as
2158 * keyword.
2160 * @param string $search_text search key word
2161 * @param int $page page
2162 * @return mixed see {@link repository::get_listing()}
2164 public function search($search_text, $page = 0) {
2165 $list = array();
2166 $list['list'] = array();
2167 return false;
2171 * Logout from repository instance
2172 * By default, this function will return a login form
2174 * @return string
2176 public function logout(){
2177 return $this->print_login();
2181 * To check whether the user is logged in.
2183 * @return bool
2185 public function check_login(){
2186 return true;
2191 * Show the login screen, if required
2193 * @return string
2195 public function print_login(){
2196 return $this->get_listing();
2200 * Show the search screen, if required
2202 * @return string
2204 public function print_search() {
2205 global $PAGE;
2206 $renderer = $PAGE->get_renderer('core', 'files');
2207 return $renderer->repository_default_searchform();
2211 * For oauth like external authentication, when external repository direct user back to moodle,
2212 * this funciton will be called to set up token and token_secret
2214 public function callback() {
2218 * is it possible to do glboal search?
2220 * @return bool
2222 public function global_search() {
2223 return false;
2227 * Defines operations that happen occasionally on cron
2229 * @return bool
2231 public function cron() {
2232 return true;
2236 * function which is run when the type is created (moodle administrator add the plugin)
2238 * @return bool success or fail?
2240 public static function plugin_init() {
2241 return true;
2245 * Edit/Create Admin Settings Moodle form
2247 * @param moodleform $mform Moodle form (passed by reference)
2248 * @param string $classname repository class name
2250 public static function type_config_form($mform, $classname = 'repository') {
2251 $instnaceoptions = call_user_func(array($classname, 'get_instance_option_names'), $mform, $classname);
2252 if (empty($instnaceoptions)) {
2253 // this plugin has only one instance
2254 // so we need to give it a name
2255 // it can be empty, then moodle will look for instance name from language string
2256 $mform->addElement('text', 'pluginname', get_string('pluginname', 'repository'), array('size' => '40'));
2257 $mform->addElement('static', 'pluginnamehelp', '', get_string('pluginnamehelp', 'repository'));
2258 $mform->setType('pluginname', PARAM_TEXT);
2263 * Validate Admin Settings Moodle form
2265 * @static
2266 * @param moodleform $mform Moodle form (passed by reference)
2267 * @param array $data array of ("fieldname"=>value) of submitted data
2268 * @param array $errors array of ("fieldname"=>errormessage) of errors
2269 * @return array array of errors
2271 public static function type_form_validation($mform, $data, $errors) {
2272 return $errors;
2277 * Edit/Create Instance Settings Moodle form
2279 * @param moodleform $mform Moodle form (passed by reference)
2281 public static function instance_config_form($mform) {
2285 * Return names of the general options.
2286 * By default: no general option name
2288 * @return array
2290 public static function get_type_option_names() {
2291 return array('pluginname');
2295 * Return names of the instance options.
2296 * By default: no instance option name
2298 * @return array
2300 public static function get_instance_option_names() {
2301 return array();
2305 * Validate repository plugin instance form
2307 * @param moodleform $mform moodle form
2308 * @param array $data form data
2309 * @param array $errors errors
2310 * @return array errors
2312 public static function instance_form_validation($mform, $data, $errors) {
2313 return $errors;
2317 * Create a shorten filename
2319 * @param string $str filename
2320 * @param int $maxlength max file name length
2321 * @return string short filename
2323 public function get_short_filename($str, $maxlength) {
2324 if (textlib::strlen($str) >= $maxlength) {
2325 return trim(textlib::substr($str, 0, $maxlength)).'...';
2326 } else {
2327 return $str;
2332 * Overwrite an existing file
2334 * @param int $itemid
2335 * @param string $filepath
2336 * @param string $filename
2337 * @param string $newfilepath
2338 * @param string $newfilename
2339 * @return bool
2341 public static function overwrite_existing_draftfile($itemid, $filepath, $filename, $newfilepath, $newfilename) {
2342 global $USER;
2343 $fs = get_file_storage();
2344 $user_context = context_user::instance($USER->id);
2345 if ($file = $fs->get_file($user_context->id, 'user', 'draft', $itemid, $filepath, $filename)) {
2346 if ($tempfile = $fs->get_file($user_context->id, 'user', 'draft', $itemid, $newfilepath, $newfilename)) {
2347 // delete existing file to release filename
2348 $file->delete();
2349 // create new file
2350 $newfile = $fs->create_file_from_storedfile(array('filepath'=>$filepath, 'filename'=>$filename), $tempfile);
2351 // remove temp file
2352 $tempfile->delete();
2353 return true;
2356 return false;
2360 * Delete a temp file from draft area
2362 * @param int $draftitemid
2363 * @param string $filepath
2364 * @param string $filename
2365 * @return bool
2367 public static function delete_tempfile_from_draft($draftitemid, $filepath, $filename) {
2368 global $USER;
2369 $fs = get_file_storage();
2370 $user_context = context_user::instance($USER->id);
2371 if ($file = $fs->get_file($user_context->id, 'user', 'draft', $draftitemid, $filepath, $filename)) {
2372 $file->delete();
2373 return true;
2374 } else {
2375 return false;
2380 * Find all external files in this repo and import them
2382 public function convert_references_to_local() {
2383 $fs = get_file_storage();
2384 $files = $fs->get_external_files($this->id);
2385 foreach ($files as $storedfile) {
2386 $fs->import_external_file($storedfile);
2391 * Called from phpunit between tests, resets whatever was cached
2393 public static function reset_caches() {
2394 self::sync_external_file(null, true);
2398 * Performs synchronisation of reference to an external file if the previous one has expired.
2400 * @param stored_file $file
2401 * @param bool $resetsynchistory whether to reset all history of sync (used by phpunit)
2402 * @return bool success
2404 public static function sync_external_file($file, $resetsynchistory = false) {
2405 global $DB;
2406 // TODO MDL-25290 static should be replaced with MUC code.
2407 static $synchronized = array();
2408 if ($resetsynchistory) {
2409 $synchronized = array();
2412 $fs = get_file_storage();
2414 if (!$file || !$file->get_referencefileid()) {
2415 return false;
2417 if (array_key_exists($file->get_id(), $synchronized)) {
2418 return $synchronized[$file->get_id()];
2421 // remember that we already cached in current request to prevent from querying again
2422 $synchronized[$file->get_id()] = false;
2424 if (!$reference = $DB->get_record('files_reference', array('id'=>$file->get_referencefileid()))) {
2425 return false;
2428 if (!empty($reference->lastsync) and ($reference->lastsync + $reference->lifetime > time())) {
2429 $synchronized[$file->get_id()] = true;
2430 return true;
2433 if (!$repository = self::get_repository_by_id($reference->repositoryid, SYSCONTEXTID)) {
2434 return false;
2437 if (!$repository->sync_individual_file($file)) {
2438 return false;
2441 $lifetime = $repository->get_reference_file_lifetime($reference);
2442 $fileinfo = $repository->get_file_by_reference($reference);
2443 if ($fileinfo === null) {
2444 // does not exist any more - set status to missing
2445 $file->set_missingsource($lifetime);
2446 $synchronized[$file->get_id()] = true;
2447 return true;
2450 $contenthash = null;
2451 $filesize = null;
2452 if (!empty($fileinfo->filesize)) {
2453 // filesize returned
2454 if (!empty($fileinfo->contenthash) && $fs->content_exists($fileinfo->contenthash)) {
2455 // contenthash is specified and valid
2456 $contenthash = $fileinfo->contenthash;
2457 } else if ($fileinfo->filesize == $file->get_filesize()) {
2458 // we don't know the new contenthash but the filesize did not change,
2459 // assume the contenthash did not change either
2460 $contenthash = $file->get_contenthash();
2461 } else {
2462 // we can't save empty contenthash so generate contenthash from empty string
2463 $fs->add_string_to_pool('');
2464 $contenthash = sha1('');
2466 $filesize = $fileinfo->filesize;
2467 } else if (!empty($fileinfo->filepath)) {
2468 // File path returned
2469 list($contenthash, $filesize, $newfile) = $fs->add_file_to_pool($fileinfo->filepath);
2470 } else if (!empty($fileinfo->handle) && is_resource($fileinfo->handle)) {
2471 // File handle returned
2472 $contents = '';
2473 while (!feof($fileinfo->handle)) {
2474 $contents .= fread($handle, 8192);
2476 fclose($fileinfo->handle);
2477 list($contenthash, $filesize, $newfile) = $fs->add_string_to_pool($content);
2478 } else if (isset($fileinfo->content)) {
2479 // File content returned
2480 list($contenthash, $filesize, $newfile) = $fs->add_string_to_pool($fileinfo->content);
2483 if (!isset($contenthash) or !isset($filesize)) {
2484 return false;
2487 // update files table
2488 $file->set_synchronized($contenthash, $filesize, 0, $lifetime);
2489 $synchronized[$file->get_id()] = true;
2490 return true;
2494 * Build draft file's source field
2496 * {@link file_restore_source_field_from_draft_file()}
2497 * XXX: This is a hack for file manager (MDL-28666)
2498 * For newly created draft files we have to construct
2499 * source filed in php serialized data format.
2500 * File manager needs to know the original file information before copying
2501 * to draft area, so we append these information in mdl_files.source field
2503 * @param string $source
2504 * @return string serialised source field
2506 public static function build_source_field($source) {
2507 $sourcefield = new stdClass;
2508 $sourcefield->source = $source;
2509 return serialize($sourcefield);
2514 * Exception class for repository api
2516 * @since 2.0
2517 * @package core_repository
2518 * @copyright 2009 Dongsheng Cai {@link http://dongsheng.org}
2519 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2521 class repository_exception extends moodle_exception {
2525 * This is a class used to define a repository instance form
2527 * @since 2.0
2528 * @package core_repository
2529 * @copyright 2009 Dongsheng Cai {@link http://dongsheng.org}
2530 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2532 final class repository_instance_form extends moodleform {
2533 /** @var stdClass repository instance */
2534 protected $instance;
2535 /** @var string repository plugin type */
2536 protected $plugin;
2539 * Added defaults to moodle form
2541 protected function add_defaults() {
2542 $mform =& $this->_form;
2543 $strrequired = get_string('required');
2545 $mform->addElement('hidden', 'edit', ($this->instance) ? $this->instance->id : 0);
2546 $mform->setType('edit', PARAM_INT);
2547 $mform->addElement('hidden', 'new', $this->plugin);
2548 $mform->setType('new', PARAM_ALPHANUMEXT);
2549 $mform->addElement('hidden', 'plugin', $this->plugin);
2550 $mform->setType('plugin', PARAM_PLUGIN);
2551 $mform->addElement('hidden', 'typeid', $this->typeid);
2552 $mform->setType('typeid', PARAM_INT);
2553 $mform->addElement('hidden', 'contextid', $this->contextid);
2554 $mform->setType('contextid', PARAM_INT);
2556 $mform->addElement('text', 'name', get_string('name'), 'maxlength="100" size="30"');
2557 $mform->addRule('name', $strrequired, 'required', null, 'client');
2558 $mform->setType('name', PARAM_TEXT);
2562 * Define moodle form elements
2564 public function definition() {
2565 global $CFG;
2566 // type of plugin, string
2567 $this->plugin = $this->_customdata['plugin'];
2568 $this->typeid = $this->_customdata['typeid'];
2569 $this->contextid = $this->_customdata['contextid'];
2570 $this->instance = (isset($this->_customdata['instance'])
2571 && is_subclass_of($this->_customdata['instance'], 'repository'))
2572 ? $this->_customdata['instance'] : null;
2574 $mform =& $this->_form;
2576 $this->add_defaults();
2578 // Add instance config options.
2579 $result = repository::static_function($this->plugin, 'instance_config_form', $mform);
2580 if ($result === false) {
2581 // Remove the name element if no other config options.
2582 $mform->removeElement('name');
2584 if ($this->instance) {
2585 $data = array();
2586 $data['name'] = $this->instance->name;
2587 if (!$this->instance->readonly) {
2588 // and set the data if we have some.
2589 foreach ($this->instance->get_instance_option_names() as $config) {
2590 if (!empty($this->instance->options[$config])) {
2591 $data[$config] = $this->instance->options[$config];
2592 } else {
2593 $data[$config] = '';
2597 $this->set_data($data);
2600 if ($result === false) {
2601 $mform->addElement('cancel');
2602 } else {
2603 $this->add_action_buttons(true, get_string('save','repository'));
2608 * Validate moodle form data
2610 * @param array $data form data
2611 * @param array $files files in form
2612 * @return array errors
2614 public function validation($data, $files) {
2615 global $DB;
2616 $errors = array();
2617 $plugin = $this->_customdata['plugin'];
2618 $instance = (isset($this->_customdata['instance'])
2619 && is_subclass_of($this->_customdata['instance'], 'repository'))
2620 ? $this->_customdata['instance'] : null;
2621 if (!$instance) {
2622 $errors = repository::static_function($plugin, 'instance_form_validation', $this, $data, $errors);
2623 } else {
2624 $errors = $instance->instance_form_validation($this, $data, $errors);
2627 $sql = "SELECT count('x')
2628 FROM {repository_instances} i, {repository} r
2629 WHERE r.type=:plugin AND r.id=i.typeid AND i.name=:name";
2630 if ($DB->count_records_sql($sql, array('name' => $data['name'], 'plugin' => $data['plugin'])) > 1) {
2631 $errors['name'] = get_string('erroruniquename', 'repository');
2634 return $errors;
2639 * This is a class used to define a repository type setting form
2641 * @since 2.0
2642 * @package core_repository
2643 * @copyright 2009 Dongsheng Cai {@link http://dongsheng.org}
2644 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2646 final class repository_type_form extends moodleform {
2647 /** @var stdClass repository instance */
2648 protected $instance;
2649 /** @var string repository plugin name */
2650 protected $plugin;
2651 /** @var string action */
2652 protected $action;
2655 * Definition of the moodleform
2657 public function definition() {
2658 global $CFG;
2659 // type of plugin, string
2660 $this->plugin = $this->_customdata['plugin'];
2661 $this->instance = (isset($this->_customdata['instance'])
2662 && is_a($this->_customdata['instance'], 'repository_type'))
2663 ? $this->_customdata['instance'] : null;
2665 $this->action = $this->_customdata['action'];
2666 $this->pluginname = $this->_customdata['pluginname'];
2667 $mform =& $this->_form;
2668 $strrequired = get_string('required');
2670 $mform->addElement('hidden', 'action', $this->action);
2671 $mform->setType('action', PARAM_TEXT);
2672 $mform->addElement('hidden', 'repos', $this->plugin);
2673 $mform->setType('repos', PARAM_PLUGIN);
2675 // let the plugin add its specific fields
2676 $classname = 'repository_' . $this->plugin;
2677 require_once($CFG->dirroot . '/repository/' . $this->plugin . '/lib.php');
2678 //add "enable course/user instances" checkboxes if multiple instances are allowed
2679 $instanceoptionnames = repository::static_function($this->plugin, 'get_instance_option_names');
2681 $result = call_user_func(array($classname, 'type_config_form'), $mform, $classname);
2683 if (!empty($instanceoptionnames)) {
2684 $sm = get_string_manager();
2685 $component = 'repository';
2686 if ($sm->string_exists('enablecourseinstances', 'repository_' . $this->plugin)) {
2687 $component .= ('_' . $this->plugin);
2689 $mform->addElement('checkbox', 'enablecourseinstances', get_string('enablecourseinstances', $component));
2691 $component = 'repository';
2692 if ($sm->string_exists('enableuserinstances', 'repository_' . $this->plugin)) {
2693 $component .= ('_' . $this->plugin);
2695 $mform->addElement('checkbox', 'enableuserinstances', get_string('enableuserinstances', $component));
2698 // set the data if we have some.
2699 if ($this->instance) {
2700 $data = array();
2701 $option_names = call_user_func(array($classname,'get_type_option_names'));
2702 if (!empty($instanceoptionnames)){
2703 $option_names[] = 'enablecourseinstances';
2704 $option_names[] = 'enableuserinstances';
2707 $instanceoptions = $this->instance->get_options();
2708 foreach ($option_names as $config) {
2709 if (!empty($instanceoptions[$config])) {
2710 $data[$config] = $instanceoptions[$config];
2711 } else {
2712 $data[$config] = '';
2715 // XXX: set plugin name for plugins which doesn't have muliti instances
2716 if (empty($instanceoptionnames)){
2717 $data['pluginname'] = $this->pluginname;
2719 $this->set_data($data);
2722 $this->add_action_buttons(true, get_string('save','repository'));
2726 * Validate moodle form data
2728 * @param array $data moodle form data
2729 * @param array $files
2730 * @return array errors
2732 public function validation($data, $files) {
2733 $errors = array();
2734 $plugin = $this->_customdata['plugin'];
2735 $instance = (isset($this->_customdata['instance'])
2736 && is_subclass_of($this->_customdata['instance'], 'repository'))
2737 ? $this->_customdata['instance'] : null;
2738 if (!$instance) {
2739 $errors = repository::static_function($plugin, 'type_form_validation', $this, $data, $errors);
2740 } else {
2741 $errors = $instance->type_form_validation($this, $data, $errors);
2744 return $errors;
2749 * Generate all options needed by filepicker
2751 * @param array $args including following keys
2752 * context
2753 * accepted_types
2754 * return_types
2756 * @return array the list of repository instances, including meta infomation, containing the following keys
2757 * externallink
2758 * repositories
2759 * accepted_types
2761 function initialise_filepicker($args) {
2762 global $CFG, $USER, $PAGE, $OUTPUT;
2763 static $templatesinitialized = array();
2764 require_once($CFG->libdir . '/licenselib.php');
2766 $return = new stdClass();
2767 $licenses = array();
2768 if (!empty($CFG->licenses)) {
2769 $array = explode(',', $CFG->licenses);
2770 foreach ($array as $license) {
2771 $l = new stdClass();
2772 $l->shortname = $license;
2773 $l->fullname = get_string($license, 'license');
2774 $licenses[] = $l;
2777 if (!empty($CFG->sitedefaultlicense)) {
2778 $return->defaultlicense = $CFG->sitedefaultlicense;
2781 $return->licenses = $licenses;
2783 $return->author = fullname($USER);
2785 if (empty($args->context)) {
2786 $context = $PAGE->context;
2787 } else {
2788 $context = $args->context;
2790 $disable_types = array();
2791 if (!empty($args->disable_types)) {
2792 $disable_types = $args->disable_types;
2795 $user_context = context_user::instance($USER->id);
2797 list($context, $course, $cm) = get_context_info_array($context->id);
2798 $contexts = array($user_context, get_system_context());
2799 if (!empty($course)) {
2800 // adding course context
2801 $contexts[] = context_course::instance($course->id);
2803 $externallink = (int)get_config(null, 'repositoryallowexternallinks');
2804 $repositories = repository::get_instances(array(
2805 'context'=>$contexts,
2806 'currentcontext'=> $context,
2807 'accepted_types'=>$args->accepted_types,
2808 'return_types'=>$args->return_types,
2809 'disable_types'=>$disable_types
2812 $return->repositories = array();
2814 if (empty($externallink)) {
2815 $return->externallink = false;
2816 } else {
2817 $return->externallink = true;
2820 $return->userprefs = array();
2821 $return->userprefs['recentrepository'] = get_user_preferences('filepicker_recentrepository', '');
2822 $return->userprefs['recentlicense'] = get_user_preferences('filepicker_recentlicense', '');
2823 $return->userprefs['recentviewmode'] = get_user_preferences('filepicker_recentviewmode', '');
2825 user_preference_allow_ajax_update('filepicker_recentrepository', PARAM_INT);
2826 user_preference_allow_ajax_update('filepicker_recentlicense', PARAM_SAFEDIR);
2827 user_preference_allow_ajax_update('filepicker_recentviewmode', PARAM_INT);
2830 // provided by form element
2831 $return->accepted_types = file_get_typegroup('extension', $args->accepted_types);
2832 $return->return_types = $args->return_types;
2833 $templates = array();
2834 foreach ($repositories as $repository) {
2835 $meta = $repository->get_meta();
2836 // Please note that the array keys for repositories are used within
2837 // JavaScript a lot, the key NEEDS to be the repository id.
2838 $return->repositories[$repository->id] = $meta;
2839 // Register custom repository template if it has one
2840 if(method_exists($repository, 'get_upload_template') && !array_key_exists('uploadform_' . $meta->type, $templatesinitialized)) {
2841 $templates['uploadform_' . $meta->type] = $repository->get_upload_template();
2842 $templatesinitialized['uploadform_' . $meta->type] = true;
2845 if (!array_key_exists('core', $templatesinitialized)) {
2846 // we need to send each filepicker template to the browser just once
2847 $fprenderer = $PAGE->get_renderer('core', 'files');
2848 $templates = array_merge($templates, $fprenderer->filepicker_js_templates());
2849 $templatesinitialized['core'] = true;
2851 if (sizeof($templates)) {
2852 $PAGE->requires->js_init_call('M.core_filepicker.set_templates', array($templates), true);
2854 return $return;
2858 * Small function to walk an array to attach repository ID
2860 * @param array $value
2861 * @param string $key
2862 * @param int $id
2864 function repository_attach_id(&$value, $key, $id){
2865 $value['repo_id'] = $id;