2 // This file is part of Moodle - http://moodle.org/
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.
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/>.
18 * This file contains classes used to manage the repository plugins in Moodle
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('FILE_CONTROLLED_LINK', 8);
35 define('RENAME_SUFFIX', '_2');
38 * This class is used to manage repository plugins
40 * A repository_type is a repository plug-in. It can be Box.net, Flick-r, ...
41 * A repository type can be edited, sorted and hidden. It is mandatory for an
42 * administrator to create a repository type in order to be able to create
43 * some instances of this type.
45 * - a repository_type object is mapped to the "repository" database table
46 * - "typename" attibut maps the "type" database field. It is unique.
47 * - general "options" for a repository type are saved in the config_plugin table
48 * - when you delete a repository, all instances are deleted, and general
49 * options are also deleted from database
50 * - When you create a type for a plugin that can't have multiple instances, a
51 * instance is automatically created.
53 * @package core_repository
54 * @copyright 2009 Jerome Mouneyrac
55 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
57 class repository_type
implements cacheable_object
{
61 * Type name (no whitespace) - A type name is unique
62 * Note: for a user-friendly type name see get_readablename()
69 * Options of this type
70 * They are general options that any instance of this type would share
72 * These options are saved in config_plugin table
79 * Is the repository type visible or hidden
80 * If false (hidden): no instances can be created, edited, deleted, showned , used...
87 * 0 => not ordered, 1 => first position, 2 => second position...
88 * A not order type would appear in first position (should never happened)
94 * Return if the instance is visible in a context
96 * @todo check if the context visibility has been overwritten by the plugin creator
97 * (need to create special functions to be overvwritten in repository class)
98 * @param stdClass $context context
101 public function get_contextvisibility($context) {
104 if ($context->contextlevel
== CONTEXT_COURSE
) {
105 return $this->_options
['enablecourseinstances'];
108 if ($context->contextlevel
== CONTEXT_USER
) {
109 return $this->_options
['enableuserinstances'];
112 //the context is SITE
119 * repository_type constructor
121 * @param int $typename
122 * @param array $typeoptions
123 * @param bool $visible
124 * @param int $sortorder (don't really need set, it will be during create() call)
126 public function __construct($typename = '', $typeoptions = array(), $visible = true, $sortorder = 0) {
130 $this->_typename
= $typename;
131 $this->_visible
= $visible;
132 $this->_sortorder
= $sortorder;
134 //set options attribut
135 $this->_options
= array();
136 $options = repository
::static_function($typename, 'get_type_option_names');
137 //check that the type can be setup
138 if (!empty($options)) {
139 //set the type options
140 foreach ($options as $config) {
141 if (array_key_exists($config, $typeoptions)) {
142 $this->_options
[$config] = $typeoptions[$config];
147 //retrieve visibility from option
148 if (array_key_exists('enablecourseinstances',$typeoptions)) {
149 $this->_options
['enablecourseinstances'] = $typeoptions['enablecourseinstances'];
151 $this->_options
['enablecourseinstances'] = 0;
154 if (array_key_exists('enableuserinstances',$typeoptions)) {
155 $this->_options
['enableuserinstances'] = $typeoptions['enableuserinstances'];
157 $this->_options
['enableuserinstances'] = 0;
163 * Get the type name (no whitespace)
164 * For a human readable name, use get_readablename()
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
175 * @return string user-friendly type name
177 public function get_readablename() {
178 return get_string('pluginname','repository_'.$this->_typename
);
182 * Return general options
184 * @return array the general options
186 public function get_options() {
187 return $this->_options
;
195 public function get_visible() {
196 return $this->_visible
;
200 * Return order / position of display in the file picker
204 public function get_sortorder() {
205 return $this->_sortorder
;
209 * Create a repository type (the type name must not already exist)
210 * @param bool $silent throw exception?
211 * @return mixed return int if create successfully, return false if
213 public function create($silent = false) {
216 //check that $type has been set
217 $timmedtype = trim($this->_typename
);
218 if (empty($timmedtype)) {
219 throw new repository_exception('emptytype', 'repository');
222 //set sortorder as the last position in the list
223 if (!isset($this->_sortorder
) ||
$this->_sortorder
== 0 ) {
224 $sql = "SELECT MAX(sortorder) FROM {repository}";
225 $this->_sortorder
= 1 +
$DB->get_field_sql($sql);
228 //only create a new type if it doesn't already exist
229 $existingtype = $DB->get_record('repository', array('type'=>$this->_typename
));
230 if (!$existingtype) {
232 $newtype = new stdClass();
233 $newtype->type
= $this->_typename
;
234 $newtype->visible
= $this->_visible
;
235 $newtype->sortorder
= $this->_sortorder
;
236 $plugin_id = $DB->insert_record('repository', $newtype);
237 //save the options in DB
238 $this->update_options();
240 $instanceoptionnames = repository
::static_function($this->_typename
, 'get_instance_option_names');
242 //if the plugin type has no multiple instance (e.g. has no instance option name) so it wont
243 //be possible for the administrator to create a instance
244 //in this case we need to create an instance
245 if (empty($instanceoptionnames)) {
246 $instanceoptions = array();
247 if (empty($this->_options
['pluginname'])) {
248 // when moodle trying to install some repo plugin automatically
249 // this option will be empty, get it from language string when display
250 $instanceoptions['name'] = '';
252 // when admin trying to add a plugin manually, he will type a name
254 $instanceoptions['name'] = $this->_options
['pluginname'];
256 repository
::static_function($this->_typename
, 'create', $this->_typename
, 0, context_system
::instance(), $instanceoptions);
258 //run plugin_init function
259 if (!repository
::static_function($this->_typename
, 'plugin_init')) {
260 $this->update_visibility(false);
262 throw new repository_exception('cannotinitplugin', 'repository');
266 cache
::make('core', 'repositories')->purge();
267 if(!empty($plugin_id)) {
268 // return plugin_id if create successfully
276 throw new repository_exception('existingrepository', 'repository');
278 // If plugin existed, return false, tell caller no new plugins were created.
285 * Update plugin options into the config_plugin table
287 * @param array $options
290 public function update_options($options = null) {
292 $classname = 'repository_' . $this->_typename
;
293 $instanceoptions = repository
::static_function($this->_typename
, 'get_instance_option_names');
294 if (empty($instanceoptions)) {
295 // update repository instance name if this plugin type doesn't have muliti instances
297 $params['type'] = $this->_typename
;
298 $instances = repository
::get_instances($params);
299 $instance = array_pop($instances);
301 $DB->set_field('repository_instances', 'name', $options['pluginname'], array('id'=>$instance->id
));
303 unset($options['pluginname']);
306 if (!empty($options)) {
307 $this->_options
= $options;
310 foreach ($this->_options
as $name => $value) {
311 set_config($name, $value, $this->_typename
);
314 cache
::make('core', 'repositories')->purge();
319 * Update visible database field with the value given as parameter
320 * or with the visible value of this object
321 * This function is private.
322 * For public access, have a look to switch_and_update_visibility()
324 * @param bool $visible
327 private function update_visible($visible = null) {
330 if (!empty($visible)) {
331 $this->_visible
= $visible;
333 else if (!isset($this->_visible
)) {
334 throw new repository_exception('updateemptyvisible', 'repository');
337 cache
::make('core', 'repositories')->purge();
338 return $DB->set_field('repository', 'visible', $this->_visible
, array('type'=>$this->_typename
));
342 * Update database sortorder field with the value given as parameter
343 * or with the sortorder value of this object
344 * This function is private.
345 * For public access, have a look to move_order()
347 * @param int $sortorder
350 private function update_sortorder($sortorder = null) {
353 if (!empty($sortorder) && $sortorder!=0) {
354 $this->_sortorder
= $sortorder;
356 //if sortorder is not set, we set it as the ;ast position in the list
357 else if (!isset($this->_sortorder
) ||
$this->_sortorder
== 0 ) {
358 $sql = "SELECT MAX(sortorder) FROM {repository}";
359 $this->_sortorder
= 1 +
$DB->get_field_sql($sql);
362 cache
::make('core', 'repositories')->purge();
363 return $DB->set_field('repository', 'sortorder', $this->_sortorder
, array('type'=>$this->_typename
));
367 * Change order of the type with its adjacent upper or downer type
368 * (database fields are updated)
370 * 1. retrieve all types in an array. This array is sorted by sortorder,
371 * and the array keys start from 0 to X (incremented by 1)
372 * 2. switch sortorder values of this type and its adjacent type
374 * @param string $move "up" or "down"
376 public function move_order($move) {
379 $types = repository
::get_types(); // retrieve all types
381 // retrieve this type into the returned array
383 while (!isset($indice) && $i<count($types)) {
384 if ($types[$i]->get_typename() == $this->_typename
) {
390 // retrieve adjacent indice
393 $adjacentindice = $indice - 1;
396 $adjacentindice = $indice +
1;
399 throw new repository_exception('movenotdefined', 'repository');
402 //switch sortorder of this type and the adjacent type
403 //TODO: we could reset sortorder for all types. This is not as good in performance term, but
404 //that prevent from wrong behaviour on a screwed database. As performance are not important in this particular case
405 //it worth to change the algo.
406 if ($adjacentindice>=0 && !empty($types[$adjacentindice])) {
407 $DB->set_field('repository', 'sortorder', $this->_sortorder
, array('type'=>$types[$adjacentindice]->get_typename()));
408 $this->update_sortorder($types[$adjacentindice]->get_sortorder());
413 * 1. Change visibility to the value chosen
416 * @param bool $visible
419 public function update_visibility($visible = null) {
420 if (is_bool($visible)) {
421 $this->_visible
= $visible;
423 $this->_visible
= !$this->_visible
;
425 return $this->update_visible();
430 * Delete a repository_type (general options are removed from config_plugin
431 * table, and all instances are deleted)
433 * @param bool $downloadcontents download external contents if exist
436 public function delete($downloadcontents = false) {
439 //delete all instances of this type
441 $params['context'] = array();
442 $params['onlyvisible'] = false;
443 $params['type'] = $this->_typename
;
444 $instances = repository
::get_instances($params);
445 foreach ($instances as $instance) {
446 $instance->delete($downloadcontents);
449 //delete all general options
450 foreach ($this->_options
as $name => $value) {
451 set_config($name, null, $this->_typename
);
454 cache
::make('core', 'repositories')->purge();
456 $DB->delete_records('repository', array('type' => $this->_typename
));
457 } catch (dml_exception
$ex) {
464 * Prepares the repository type to be cached. Implements method from cacheable_object interface.
468 public function prepare_to_cache() {
470 'typename' => $this->_typename
,
471 'typeoptions' => $this->_options
,
472 'visible' => $this->_visible
,
473 'sortorder' => $this->_sortorder
478 * Restores repository type from cache. Implements method from cacheable_object interface.
482 public static function wake_from_cache($data) {
483 return new repository_type($data['typename'], $data['typeoptions'], $data['visible'], $data['sortorder']);
488 * This is the base class of the repository class.
490 * To create repository plugin, see: {@link http://docs.moodle.org/dev/Repository_plugins}
491 * See an example: {@link repository_boxnet}
493 * @package core_repository
494 * @copyright 2009 Dongsheng Cai {@link http://dongsheng.org}
495 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
497 abstract class repository
implements cacheable_object
{
499 * Timeout in seconds for downloading the external file into moodle
500 * @deprecated since Moodle 2.7, please use $CFG->repositorygetfiletimeout instead
502 const GETFILE_TIMEOUT
= 30;
505 * Timeout in seconds for syncronising the external file size
506 * @deprecated since Moodle 2.7, please use $CFG->repositorysyncfiletimeout instead
508 const SYNCFILE_TIMEOUT
= 1;
511 * Timeout in seconds for downloading an image file from external repository during syncronisation
512 * @deprecated since Moodle 2.7, please use $CFG->repositorysyncimagetimeout instead
514 const SYNCIMAGE_TIMEOUT
= 3;
516 // $disabled can be set to true to disable a plugin by force
517 // example: self::$disabled = true
518 /** @var bool force disable repository instance */
519 public $disabled = false;
520 /** @var int repository instance id */
522 /** @var stdClass current context */
524 /** @var array repository options */
526 /** @var bool Whether or not the repository instance is editable */
528 /** @var int return types */
530 /** @var stdClass repository instance database record */
532 /** @var string Type of repository (webdav, google_docs, dropbox, ...). Read from $this->get_typename(). */
538 * @param int $repositoryid repository instance id
539 * @param int|stdClass $context a context id or context object
540 * @param array $options repository options
541 * @param int $readonly indicate this repo is readonly or not
543 public function __construct($repositoryid, $context = SYSCONTEXTID
, $options = array(), $readonly = 0) {
545 $this->id
= $repositoryid;
546 if (is_object($context)) {
547 $this->context
= $context;
549 $this->context
= context
::instance_by_id($context);
551 $cache = cache
::make('core', 'repositories');
552 if (($this->instance
= $cache->get('i:'. $this->id
)) === false) {
553 $this->instance
= $DB->get_record_sql("SELECT i.*, r.type AS repositorytype, r.sortorder, r.visible
554 FROM {repository} r, {repository_instances} i
555 WHERE i.typeid = r.id and i.id = ?", array('id' => $this->id
));
556 $cache->set('i:'. $this->id
, $this->instance
);
558 $this->readonly
= $readonly;
559 $this->options
= array();
561 if (is_array($options)) {
562 // The get_option() method will get stored options in database.
563 $options = array_merge($this->get_option(), $options);
565 $options = $this->get_option();
567 foreach ($options as $n => $v) {
568 $this->options
[$n] = $v;
570 $this->name
= $this->get_name();
571 $this->returntypes
= $this->supported_returntypes();
572 $this->super_called
= true;
576 * Get repository instance using repository id
578 * Note that this function does not check permission to access repository contents
580 * @throws repository_exception
582 * @param int $repositoryid repository instance ID
583 * @param context|int $context context instance or context ID where this repository will be used
584 * @param array $options additional repository options
587 public static function get_repository_by_id($repositoryid, $context, $options = array()) {
589 $cache = cache
::make('core', 'repositories');
590 if (!is_object($context)) {
591 $context = context
::instance_by_id($context);
593 $cachekey = 'rep:'. $repositoryid. ':'. $context->id
. ':'. serialize($options);
594 if ($repository = $cache->get($cachekey)) {
598 if (!$record = $cache->get('i:'. $repositoryid)) {
599 $sql = "SELECT i.*, r.type AS repositorytype, r.visible, r.sortorder
600 FROM {repository_instances} i
601 JOIN {repository} r ON r.id = i.typeid
603 if (!$record = $DB->get_record_sql($sql, array($repositoryid))) {
604 throw new repository_exception('invalidrepositoryid', 'repository');
606 $cache->set('i:'. $record->id
, $record);
609 $type = $record->repositorytype
;
610 if (file_exists($CFG->dirroot
. "/repository/$type/lib.php")) {
611 require_once($CFG->dirroot
. "/repository/$type/lib.php");
612 $classname = 'repository_' . $type;
613 $options['type'] = $type;
614 $options['typeid'] = $record->typeid
;
615 $options['visible'] = $record->visible
;
616 if (empty($options['name'])) {
617 $options['name'] = $record->name
;
619 $repository = new $classname($repositoryid, $context, $options, $record->readonly
);
620 if (empty($repository->super_called
)) {
621 // to make sure the super construct is called
622 debugging('parent::__construct must be called by '.$type.' plugin.');
624 $cache->set($cachekey, $repository);
627 throw new repository_exception('invalidplugin', 'repository');
632 * Returns the type name of the repository.
634 * @return string type name of the repository.
637 public function get_typename() {
638 if (empty($this->typename
)) {
640 if (!preg_match("/^repository_(.*)$/", get_class($this), $matches)) {
641 throw new coding_exception('The class name of a repository should be repository_<typeofrepository>, '.
642 'e.g. repository_dropbox');
644 $this->typename
= $matches[1];
646 return $this->typename
;
650 * Get a repository type object by a given type name.
653 * @param string $typename the repository type name
654 * @return repository_type|bool
656 public static function get_type_by_typename($typename) {
658 $cache = cache
::make('core', 'repositories');
659 if (($repositorytype = $cache->get('typename:'. $typename)) === false) {
660 $repositorytype = null;
661 if ($record = $DB->get_record('repository', array('type' => $typename))) {
662 $repositorytype = new repository_type($record->type
, (array)get_config($record->type
), $record->visible
, $record->sortorder
);
663 $cache->set('typeid:'. $record->id
, $repositorytype);
665 $cache->set('typename:'. $typename, $repositorytype);
667 return $repositorytype;
671 * Get the repository type by a given repository type id.
674 * @param int $id the type id
677 public static function get_type_by_id($id) {
679 $cache = cache
::make('core', 'repositories');
680 if (($repositorytype = $cache->get('typeid:'. $id)) === false) {
681 $repositorytype = null;
682 if ($record = $DB->get_record('repository', array('id' => $id))) {
683 $repositorytype = new repository_type($record->type
, (array)get_config($record->type
), $record->visible
, $record->sortorder
);
684 $cache->set('typename:'. $record->type
, $repositorytype);
686 $cache->set('typeid:'. $id, $repositorytype);
688 return $repositorytype;
692 * Return all repository types ordered by sortorder field
693 * first repository type in returnedarray[0], second repository type in returnedarray[1], ...
696 * @param bool $visible can return types by visiblity, return all types if null
697 * @return array Repository types
699 public static function get_types($visible=null) {
701 $cache = cache
::make('core', 'repositories');
703 $typesnames = $cache->get('types');
705 $typesnames = $cache->get('typesvis');
708 if ($typesnames === false) {
709 $typesnames = array();
710 $vistypesnames = array();
711 if ($records = $DB->get_records('repository', null ,'sortorder')) {
712 foreach($records as $type) {
713 if (($repositorytype = $cache->get('typename:'. $type->type
)) === false) {
714 // Create new instance of repository_type.
715 if (file_exists($CFG->dirroot
. '/repository/'. $type->type
.'/lib.php')) {
716 $repositorytype = new repository_type($type->type
, (array)get_config($type->type
), $type->visible
, $type->sortorder
);
717 $cache->set('typeid:'. $type->id
, $repositorytype);
718 $cache->set('typename:'. $type->type
, $repositorytype);
721 if ($repositorytype) {
722 if (empty($visible) ||
$repositorytype->get_visible()) {
723 $types[] = $repositorytype;
724 $vistypesnames[] = $repositorytype->get_typename();
726 $typesnames[] = $repositorytype->get_typename();
730 $cache->set('types', $typesnames);
731 $cache->set('typesvis', $vistypesnames);
733 foreach ($typesnames as $typename) {
734 $types[] = self
::get_type_by_typename($typename);
741 * Checks if user has a capability to view the current repository.
743 * @return bool true when the user can, otherwise throws an exception.
744 * @throws repository_exception when the user does not meet the requirements.
746 public final function check_capability() {
749 // The context we are on.
750 $currentcontext = $this->context
;
752 // Ensure that the user can view the repository in the current context.
753 $can = has_capability('repository/'.$this->get_typename().':view', $currentcontext);
755 // Context in which the repository has been created.
756 $repocontext = context
::instance_by_id($this->instance
->contextid
);
758 // Prevent access to private repositories when logged in as.
759 if ($can && \core\session\manager
::is_loggedinas()) {
760 if ($this->contains_private_data() ||
$repocontext->contextlevel
== CONTEXT_USER
) {
765 // We are going to ensure that the current context was legit, and reliable to check
766 // the capability against. (No need to do that if we already cannot).
768 if ($repocontext->contextlevel
== CONTEXT_USER
) {
769 // The repository is a user instance, ensure we're the right user to access it!
770 if ($repocontext->instanceid
!= $USER->id
) {
773 } else if ($repocontext->contextlevel
== CONTEXT_COURSE
) {
774 // The repository is a course one. Let's check that we are on the right course.
775 if (in_array($currentcontext->contextlevel
, array(CONTEXT_COURSE
, CONTEXT_MODULE
, CONTEXT_BLOCK
))) {
776 $coursecontext = $currentcontext->get_course_context();
777 if ($coursecontext->instanceid
!= $repocontext->instanceid
) {
781 // We are on a parent context, therefore it's legit to check the permissions
782 // in the current context.
785 // Nothing to check here, system instances can have different permissions on different
786 // levels. We do not want to prevent URL hack here, because it does not make sense to
787 // prevent a user to access a repository in a context if it's accessible in another one.
795 throw new repository_exception('nopermissiontoaccess', 'repository');
799 * Check if file already exists in draft area.
802 * @param int $itemid of the draft area.
803 * @param string $filepath path to the file.
804 * @param string $filename file name.
807 public static function draftfile_exists($itemid, $filepath, $filename) {
809 $fs = get_file_storage();
810 $usercontext = context_user
::instance($USER->id
);
811 return $fs->file_exists($usercontext->id
, 'user', 'draft', $itemid, $filepath, $filename);
815 * Parses the moodle file reference and returns an instance of stored_file
817 * @param string $reference reference to the moodle internal file as retruned by
818 * {@link repository::get_file_reference()} or {@link file_storage::pack_reference()}
819 * @return stored_file|null
821 public static function get_moodle_file($reference) {
822 $params = file_storage
::unpack_reference($reference, true);
823 $fs = get_file_storage();
824 return $fs->get_file($params['contextid'], $params['component'], $params['filearea'],
825 $params['itemid'], $params['filepath'], $params['filename']);
829 * Repository method to make sure that user can access particular file.
831 * This is checked when user tries to pick the file from repository to deal with
832 * potential parameter substitutions is request
834 * @param string $source source of the file, returned by repository as 'source' and received back from user (not cleaned)
835 * @return bool whether the file is accessible by current user
837 public function file_is_accessible($source) {
838 if ($this->has_moodle_files()) {
839 $reference = $this->get_file_reference($source);
841 $params = file_storage
::unpack_reference($reference, true);
842 } catch (file_reference_exception
$e) {
845 $browser = get_file_browser();
846 $context = context
::instance_by_id($params['contextid']);
847 $file_info = $browser->get_file_info($context, $params['component'], $params['filearea'],
848 $params['itemid'], $params['filepath'], $params['filename']);
849 return !empty($file_info);
855 * This function is used to copy a moodle file to draft area.
857 * It DOES NOT check if the user is allowed to access this file because the actual file
858 * can be located in the area where user does not have access to but there is an alias
859 * to this file in the area where user CAN access it.
860 * {@link file_is_accessible} should be called for alias location before calling this function.
862 * @param string $source The metainfo of file, it is base64 encoded php serialized data
863 * @param stdClass|array $filerecord contains itemid, filepath, filename and optionally other
864 * attributes of the new file
865 * @param int $maxbytes maximum allowed size of file, -1 if unlimited. If size of file exceeds
866 * the limit, the file_exception is thrown.
867 * @param int $areamaxbytes the maximum size of the area. A file_exception is thrown if the
868 * new file will reach the limit.
869 * @return array The information about the created file
871 public function copy_to_area($source, $filerecord, $maxbytes = -1, $areamaxbytes = FILE_AREA_MAX_BYTES_UNLIMITED
) {
873 $fs = get_file_storage();
875 if ($this->has_moodle_files() == false) {
876 throw new coding_exception('Only repository used to browse moodle files can use repository::copy_to_area()');
879 $user_context = context_user
::instance($USER->id
);
881 $filerecord = (array)$filerecord;
882 // make sure the new file will be created in user draft area
883 $filerecord['component'] = 'user';
884 $filerecord['filearea'] = 'draft';
885 $filerecord['contextid'] = $user_context->id
;
886 $draftitemid = $filerecord['itemid'];
887 $new_filepath = $filerecord['filepath'];
888 $new_filename = $filerecord['filename'];
890 // the file needs to copied to draft area
891 $stored_file = self
::get_moodle_file($source);
892 if ($maxbytes != -1 && $stored_file->get_filesize() > $maxbytes) {
893 $maxbytesdisplay = display_size($maxbytes);
894 throw new file_exception('maxbytesfile', (object) array('file' => $filerecord['filename'],
895 'size' => $maxbytesdisplay));
897 // Validate the size of the draft area.
898 if (file_is_draft_area_limit_reached($draftitemid, $areamaxbytes, $stored_file->get_filesize())) {
899 throw new file_exception('maxareabytes');
902 if (repository
::draftfile_exists($draftitemid, $new_filepath, $new_filename)) {
904 $unused_filename = repository
::get_unused_filename($draftitemid, $new_filepath, $new_filename);
905 $filerecord['filename'] = $unused_filename;
906 $fs->create_file_from_storedfile($filerecord, $stored_file);
908 $event['event'] = 'fileexists';
909 $event['newfile'] = new stdClass
;
910 $event['newfile']->filepath
= $new_filepath;
911 $event['newfile']->filename
= $unused_filename;
912 $event['newfile']->url
= moodle_url
::make_draftfile_url($draftitemid, $new_filepath, $unused_filename)->out();
913 $event['existingfile'] = new stdClass
;
914 $event['existingfile']->filepath
= $new_filepath;
915 $event['existingfile']->filename
= $new_filename;
916 $event['existingfile']->url
= moodle_url
::make_draftfile_url($draftitemid, $new_filepath, $new_filename)->out();
919 $fs->create_file_from_storedfile($filerecord, $stored_file);
921 $info['itemid'] = $draftitemid;
922 $info['file'] = $new_filename;
923 $info['title'] = $new_filename;
924 $info['contextid'] = $user_context->id
;
925 $info['url'] = moodle_url
::make_draftfile_url($draftitemid, $new_filepath, $new_filename)->out();
926 $info['filesize'] = $stored_file->get_filesize();
932 * Get an unused filename from the current draft area.
934 * Will check if the file ends with ([0-9]) and increase the number.
937 * @param int $itemid draft item ID.
938 * @param string $filepath path to the file.
939 * @param string $filename name of the file.
940 * @return string an unused file name.
942 public static function get_unused_filename($itemid, $filepath, $filename) {
944 $contextid = context_user
::instance($USER->id
)->id
;
945 $fs = get_file_storage();
946 return $fs->get_unused_filename($contextid, 'user', 'draft', $itemid, $filepath, $filename);
950 * Append a suffix to filename.
953 * @param string $filename
955 * @deprecated since 2.5
957 public static function append_suffix($filename) {
958 debugging('The function repository::append_suffix() has been deprecated. Use repository::get_unused_filename() instead.',
960 $pathinfo = pathinfo($filename);
961 if (empty($pathinfo['extension'])) {
962 return $filename . RENAME_SUFFIX
;
964 return $pathinfo['filename'] . RENAME_SUFFIX
. '.' . $pathinfo['extension'];
969 * Return all types that you a user can create/edit and which are also visible
970 * Note: Mostly used in order to know if at least one editable type can be set
973 * @param stdClass $context the context for which we want the editable types
974 * @return array types
976 public static function get_editable_types($context = null) {
978 if (empty($context)) {
979 $context = context_system
::instance();
982 $types= repository
::get_types(true);
983 $editabletypes = array();
984 foreach ($types as $type) {
985 $instanceoptionnames = repository
::static_function($type->get_typename(), 'get_instance_option_names');
986 if (!empty($instanceoptionnames)) {
987 if ($type->get_contextvisibility($context)) {
988 $editabletypes[]=$type;
992 return $editabletypes;
996 * Return repository instances
999 * @param array $args Array containing the following keys:
1000 * currentcontext : instance of context (default system context)
1001 * context : array of instances of context (default empty array)
1002 * onlyvisible : bool (default true)
1003 * type : string return instances of this type only
1004 * accepted_types : string|array return instances that contain files of those types (*, web_image, .pdf, ...)
1005 * return_types : int combination of FILE_INTERNAL & FILE_EXTERNAL & FILE_REFERENCE & FILE_CONTROLLED_LINK.
1006 * 0 means every type. The default is FILE_INTERNAL | FILE_EXTERNAL.
1007 * userid : int if specified, instances belonging to other users will not be returned
1009 * @return array repository instances
1011 public static function get_instances($args = array()) {
1012 global $DB, $CFG, $USER;
1014 // Fill $args attributes with default values unless specified
1015 if (!isset($args['currentcontext']) ||
!($args['currentcontext'] instanceof context
)) {
1016 $current_context = context_system
::instance();
1018 $current_context = $args['currentcontext'];
1020 $args['currentcontext'] = $current_context->id
;
1021 $contextids = array();
1022 if (!empty($args['context'])) {
1023 foreach ($args['context'] as $context) {
1024 $contextids[] = $context->id
;
1027 $args['context'] = $contextids;
1028 if (!isset($args['onlyvisible'])) {
1029 $args['onlyvisible'] = true;
1031 if (!isset($args['return_types'])) {
1032 $args['return_types'] = FILE_INTERNAL | FILE_EXTERNAL
;
1034 if (!isset($args['type'])) {
1035 $args['type'] = null;
1037 if (empty($args['disable_types']) ||
!is_array($args['disable_types'])) {
1038 $args['disable_types'] = null;
1040 if (empty($args['userid']) ||
!is_numeric($args['userid'])) {
1041 $args['userid'] = null;
1043 if (!isset($args['accepted_types']) ||
(is_array($args['accepted_types']) && in_array('*', $args['accepted_types']))) {
1044 $args['accepted_types'] = '*';
1047 $cachekey = 'all:'. serialize($args);
1049 // Check if we have cached list of repositories with the same query
1050 $cache = cache
::make('core', 'repositories');
1051 if (($cachedrepositories = $cache->get($cachekey)) !== false) {
1052 // convert from cacheable_object_array to array
1053 $repositories = array();
1054 foreach ($cachedrepositories as $repository) {
1055 $repositories[$repository->id
] = $repository;
1057 return $repositories;
1060 // Prepare DB SQL query to retrieve repositories
1062 $sql = "SELECT i.*, r.type AS repositorytype, r.sortorder, r.visible
1063 FROM {repository} r, {repository_instances} i
1064 WHERE i.typeid = r.id ";
1066 if ($args['disable_types']) {
1067 list($types, $p) = $DB->get_in_or_equal($args['disable_types'], SQL_PARAMS_NAMED
, 'distype', false);
1068 $sql .= " AND r.type $types";
1069 $params = array_merge($params, $p);
1072 if ($args['userid']) {
1073 $sql .= " AND (i.userid = 0 or i.userid = :userid)";
1074 $params['userid'] = $args['userid'];
1077 if ($args['context']) {
1078 list($ctxsql, $p2) = $DB->get_in_or_equal($args['context'], SQL_PARAMS_NAMED
, 'ctx');
1079 $sql .= " AND i.contextid $ctxsql";
1080 $params = array_merge($params, $p2);
1083 if ($args['onlyvisible'] == true) {
1084 $sql .= " AND r.visible = 1";
1087 if ($args['type'] !== null) {
1088 $sql .= " AND r.type = :type";
1089 $params['type'] = $args['type'];
1091 $sql .= " ORDER BY r.sortorder, i.name";
1093 if (!$records = $DB->get_records_sql($sql, $params)) {
1097 $repositories = array();
1098 // Sortorder should be unique, which is not true if we use $record->sortorder
1099 // and there are multiple instances of any repository type
1101 foreach ($records as $record) {
1102 $cache->set('i:'. $record->id
, $record);
1103 if (!file_exists($CFG->dirroot
. '/repository/'. $record->repositorytype
.'/lib.php')) {
1106 $repository = self
::get_repository_by_id($record->id
, $current_context);
1107 $repository->options
['sortorder'] = $sortorder++
;
1109 $is_supported = true;
1112 if ($args['accepted_types'] !== '*' and $repository->supported_filetypes() !== '*') {
1113 $accepted_ext = file_get_typegroup('extension', $args['accepted_types']);
1114 $supported_ext = file_get_typegroup('extension', $repository->supported_filetypes());
1115 $valid_ext = array_intersect($accepted_ext, $supported_ext);
1116 $is_supported = !empty($valid_ext);
1118 // Check return values.
1119 if (!empty($args['return_types']) && !($repository->supported_returntypes() & $args['return_types'])) {
1120 $is_supported = false;
1123 if (!$args['onlyvisible'] ||
($repository->is_visible() && !$repository->disabled
)) {
1124 // check capability in current context
1125 $capability = has_capability('repository/'.$record->repositorytype
.':view', $current_context);
1126 if ($record->repositorytype
== 'coursefiles') {
1127 // coursefiles plugin needs managefiles permission
1128 $capability = $capability && has_capability('moodle/course:managefiles', $current_context);
1130 if ($is_supported && $capability) {
1131 $repositories[$repository->id
] = $repository;
1135 $cache->set($cachekey, new cacheable_object_array($repositories));
1136 return $repositories;
1140 * Get single repository instance for administrative actions
1142 * Do not use this function to access repository contents, because it
1143 * does not set the current context
1145 * @see repository::get_repository_by_id()
1148 * @param integer $id repository instance id
1149 * @return repository
1151 public static function get_instance($id) {
1152 return self
::get_repository_by_id($id, context_system
::instance());
1156 * Call a static function. Any additional arguments than plugin and function will be passed through.
1159 * @param string $plugin repository plugin name
1160 * @param string $function function name
1163 public static function static_function($plugin, $function) {
1166 //check that the plugin exists
1167 $typedirectory = $CFG->dirroot
. '/repository/'. $plugin . '/lib.php';
1168 if (!file_exists($typedirectory)) {
1169 //throw new repository_exception('invalidplugin', 'repository');
1173 $args = func_get_args();
1174 if (count($args) <= 2) {
1181 require_once($typedirectory);
1182 return call_user_func_array(array('repository_' . $plugin, $function), $args);
1186 * Scan file, throws exception in case of infected file.
1188 * Please note that the scanning engine must be able to access the file,
1189 * permissions of the file are not modified here!
1192 * @deprecated since Moodle 3.0
1193 * @param string $thefile
1194 * @param string $filename name of the file
1195 * @param bool $deleteinfected
1197 public static function antivir_scan_file($thefile, $filename, $deleteinfected) {
1198 debugging('Please upgrade your code to use \core\antivirus\manager::scan_file instead', DEBUG_DEVELOPER
);
1199 \core\antivirus\manager
::scan_file($thefile, $filename, $deleteinfected);
1203 * Repository method to serve the referenced file
1205 * @see send_stored_file
1207 * @param stored_file $storedfile the file that contains the reference
1208 * @param int $lifetime Number of seconds before the file should expire from caches (null means $CFG->filelifetime)
1209 * @param int $filter 0 (default)=no filtering, 1=all files, 2=html files only
1210 * @param bool $forcedownload If true (default false), forces download of file rather than view in browser/plugin
1211 * @param array $options additional options affecting the file serving
1213 public function send_file($storedfile, $lifetime=null , $filter=0, $forcedownload=false, array $options = null) {
1214 if ($this->has_moodle_files()) {
1215 $fs = get_file_storage();
1216 $params = file_storage
::unpack_reference($storedfile->get_reference(), true);
1218 if (is_array($params)) {
1219 $srcfile = $fs->get_file($params['contextid'], $params['component'], $params['filearea'],
1220 $params['itemid'], $params['filepath'], $params['filename']);
1222 if (empty($options)) {
1225 if (!isset($options['filename'])) {
1226 $options['filename'] = $storedfile->get_filename();
1229 send_file_not_found();
1231 send_stored_file($srcfile, $lifetime, $filter, $forcedownload, $options);
1234 throw new coding_exception("Repository plugin must implement send_file() method.");
1239 * Return human readable reference information
1241 * @param string $reference value of DB field files_reference.reference
1242 * @param int $filestatus status of the file, 0 - ok, 666 - source missing
1245 public function get_reference_details($reference, $filestatus = 0) {
1246 if ($this->has_moodle_files()) {
1248 $params = file_storage
::unpack_reference($reference, true);
1249 if (is_array($params)) {
1250 $context = context
::instance_by_id($params['contextid'], IGNORE_MISSING
);
1252 $browser = get_file_browser();
1253 $fileinfo = $browser->get_file_info($context, $params['component'], $params['filearea'], $params['itemid'], $params['filepath'], $params['filename']);
1256 if (empty($fileinfo)) {
1257 if ($filestatus == 666) {
1258 if (is_siteadmin() ||
($context && has_capability('moodle/course:managefiles', $context))) {
1259 return get_string('lostsource', 'repository',
1260 $params['contextid']. '/'. $params['component']. '/'. $params['filearea']. '/'. $params['itemid']. $params['filepath']. $params['filename']);
1262 return get_string('lostsource', 'repository', '');
1265 return get_string('undisclosedsource', 'repository');
1267 return $fileinfo->get_readable_fullname();
1274 * Cache file from external repository by reference
1275 * {@link repository::get_file_reference()}
1276 * {@link repository::get_file()}
1277 * Invoked at MOODLE/repository/repository_ajax.php
1279 * @param string $reference this reference is generated by
1280 * repository::get_file_reference()
1281 * @param stored_file $storedfile created file reference
1283 public function cache_file_by_reference($reference, $storedfile) {
1287 * reference_file_selected
1289 * This function is called when a controlled link file is selected in a file picker and the form is
1290 * saved. The expected behaviour for repositories supporting controlled links is to
1291 * - copy the file to the moodle system account
1292 * - put it in a folder that reflects the context it is being used
1293 * - make sure the sharing permissions are correct (read-only with the link)
1294 * - return a new reference string pointing to the newly copied file.
1296 * @param string $reference this reference is generated by
1297 * repository::get_file_reference()
1298 * @param context $context the target context for this new file.
1299 * @param string $component the target component for this new file.
1300 * @param string $filearea the target filearea for this new file.
1301 * @param string $itemid the target itemid for this new file.
1302 * @return string updated reference (final one before it's saved to db).
1304 public function reference_file_selected($reference, $context, $component, $filearea, $itemid) {
1309 * Return the source information
1311 * The result of the function is stored in files.source field. It may be analysed
1312 * when the source file is lost or repository may use it to display human-readable
1313 * location of reference original.
1315 * This method is called when file is picked for the first time only. When file
1316 * (either copy or a reference) is already in moodle and it is being picked
1317 * again to another file area (also as a copy or as a reference), the value of
1318 * files.source is copied.
1320 * @param string $source source of the file, returned by repository as 'source' and received back from user (not cleaned)
1321 * @return string|null
1323 public function get_file_source_info($source) {
1324 if ($this->has_moodle_files()) {
1325 $reference = $this->get_file_reference($source);
1326 return $this->get_reference_details($reference, 0);
1332 * Move file from download folder to file pool using FILE API
1336 * @param string $thefile file path in download folder
1337 * @param stdClass $record
1338 * @return array containing the following keys:
1344 public static function move_to_filepool($thefile, $record) {
1345 global $DB, $CFG, $USER, $OUTPUT;
1347 // scan for viruses if possible, throws exception if problem found
1348 // TODO: MDL-28637 this repository_no_delete is a bloody hack!
1349 \core\antivirus\manager
::scan_file($thefile, $record->filename
, empty($CFG->repository_no_delete
));
1351 $fs = get_file_storage();
1352 // If file name being used.
1353 if (repository
::draftfile_exists($record->itemid
, $record->filepath
, $record->filename
)) {
1354 $draftitemid = $record->itemid
;
1355 $new_filename = repository
::get_unused_filename($draftitemid, $record->filepath
, $record->filename
);
1356 $old_filename = $record->filename
;
1357 // Create a tmp file.
1358 $record->filename
= $new_filename;
1359 $newfile = $fs->create_file_from_pathname($record, $thefile);
1361 $event['event'] = 'fileexists';
1362 $event['newfile'] = new stdClass
;
1363 $event['newfile']->filepath
= $record->filepath
;
1364 $event['newfile']->filename
= $new_filename;
1365 $event['newfile']->url
= moodle_url
::make_draftfile_url($draftitemid, $record->filepath
, $new_filename)->out();
1367 $event['existingfile'] = new stdClass
;
1368 $event['existingfile']->filepath
= $record->filepath
;
1369 $event['existingfile']->filename
= $old_filename;
1370 $event['existingfile']->url
= moodle_url
::make_draftfile_url($draftitemid, $record->filepath
, $old_filename)->out();
1373 if ($file = $fs->create_file_from_pathname($record, $thefile)) {
1374 if (empty($CFG->repository_no_delete
)) {
1375 $delete = unlink($thefile);
1376 unset($CFG->repository_no_delete
);
1379 'url'=>moodle_url
::make_draftfile_url($file->get_itemid(), $file->get_filepath(), $file->get_filename())->out(),
1380 'id'=>$file->get_itemid(),
1381 'file'=>$file->get_filename(),
1382 'icon' => $OUTPUT->image_url(file_extension_icon($thefile, 32))->out(),
1390 * Builds a tree of files This function is then called recursively.
1393 * @todo take $search into account, and respect a threshold for dynamic loading
1394 * @param file_info $fileinfo an object returned by file_browser::get_file_info()
1395 * @param string $search searched string
1396 * @param bool $dynamicmode no recursive call is done when in dynamic mode
1397 * @param array $list the array containing the files under the passed $fileinfo
1398 * @return int the number of files found
1400 public static function build_tree($fileinfo, $search, $dynamicmode, &$list) {
1401 global $CFG, $OUTPUT;
1404 $children = $fileinfo->get_children();
1406 foreach ($children as $child) {
1407 $filename = $child->get_visible_name();
1408 $filesize = $child->get_filesize();
1409 $filesize = $filesize ?
display_size($filesize) : '';
1410 $filedate = $child->get_timemodified();
1411 $filedate = $filedate ?
userdate($filedate) : '';
1412 $filetype = $child->get_mimetype();
1414 if ($child->is_directory()) {
1416 $level = $child->get_parent();
1418 $params = $level->get_params();
1419 $path[] = array($params['filepath'], $level->get_visible_name());
1420 $level = $level->get_parent();
1424 'title' => $child->get_visible_name(),
1426 'date' => $filedate,
1427 'path' => array_reverse($path),
1428 'thumbnail' => $OUTPUT->image_url(file_folder_icon(90))->out(false)
1431 //if ($dynamicmode && $child->is_writable()) {
1432 // $tmp['children'] = array();
1434 // if folder name matches search, we send back all files contained.
1436 if ($search && stristr($tmp['title'], $search) !== false) {
1439 $tmp['children'] = array();
1440 $_filecount = repository
::build_tree($child, $_search, $dynamicmode, $tmp['children']);
1441 if ($search && $_filecount) {
1442 $tmp['expanded'] = 1;
1447 if (!$search ||
$_filecount ||
(stristr($tmp['title'], $search) !== false)) {
1448 $filecount +
= $_filecount;
1452 } else { // not a directory
1453 // skip the file, if we're in search mode and it's not a match
1454 if ($search && (stristr($filename, $search) === false)) {
1457 $params = $child->get_params();
1458 $source = serialize(array($params['contextid'], $params['component'], $params['filearea'], $params['itemid'], $params['filepath'], $params['filename']));
1460 'title' => $filename,
1461 'size' => $filesize,
1462 'date' => $filedate,
1463 //'source' => $child->get_url(),
1464 'source' => base64_encode($source),
1465 'icon'=>$OUTPUT->image_url(file_file_icon($child, 24))->out(false),
1466 'thumbnail'=>$OUTPUT->image_url(file_file_icon($child, 90))->out(false),
1476 * Display a repository instance list (with edit/delete/create links)
1479 * @param stdClass $context the context for which we display the instance
1480 * @param string $typename if set, we display only one type of instance
1482 public static function display_instances_list($context, $typename = null) {
1483 global $CFG, $USER, $OUTPUT;
1485 $output = $OUTPUT->box_start('generalbox');
1486 //if the context is SYSTEM, so we call it from administration page
1487 $admin = ($context->id
== SYSCONTEXTID
) ?
true : false;
1489 $baseurl = new moodle_url('/'.$CFG->admin
.'/repositoryinstance.php', array('sesskey'=>sesskey()));
1490 $output .= $OUTPUT->heading(get_string('siteinstances', 'repository'));
1492 $baseurl = new moodle_url('/repository/manage_instances.php', array('contextid'=>$context->id
, 'sesskey'=>sesskey()));
1495 $namestr = get_string('name');
1496 $pluginstr = get_string('plugin', 'repository');
1497 $settingsstr = get_string('settings');
1498 $deletestr = get_string('delete');
1499 // Retrieve list of instances. In administration context we want to display all
1500 // instances of a type, even if this type is not visible. In course/user context we
1501 // want to display only visible instances, but for every type types. The repository::get_instances()
1502 // third parameter displays only visible type.
1504 $params['context'] = array($context);
1505 $params['currentcontext'] = $context;
1506 $params['return_types'] = 0;
1507 $params['onlyvisible'] = !$admin;
1508 $params['type'] = $typename;
1509 $instances = repository
::get_instances($params);
1510 $instancesnumber = count($instances);
1511 $alreadyplugins = array();
1513 $table = new html_table();
1514 $table->head
= array($namestr, $pluginstr, $settingsstr, $deletestr);
1515 $table->align
= array('left', 'left', 'center','center');
1516 $table->data
= array();
1520 foreach ($instances as $i) {
1524 $type = repository
::get_type_by_id($i->options
['typeid']);
1526 if ($type->get_contextvisibility($context)) {
1527 if (!$i->readonly
) {
1529 $settingurl = new moodle_url($baseurl);
1530 $settingurl->param('type', $i->options
['type']);
1531 $settingurl->param('edit', $i->id
);
1532 $settings .= html_writer
::link($settingurl, $settingsstr);
1534 $deleteurl = new moodle_url($baseurl);
1535 $deleteurl->param('delete', $i->id
);
1536 $deleteurl->param('type', $i->options
['type']);
1537 $delete .= html_writer
::link($deleteurl, $deletestr);
1541 $type = repository
::get_type_by_id($i->options
['typeid']);
1542 $table->data
[] = array(format_string($i->name
), $type->get_readablename(), $settings, $delete);
1544 //display a grey row if the type is defined as not visible
1545 if (isset($type) && !$type->get_visible()) {
1546 $table->rowclasses
[] = 'dimmed_text';
1548 $table->rowclasses
[] = '';
1551 if (!in_array($i->name
, $alreadyplugins)) {
1552 $alreadyplugins[] = $i->name
;
1555 $output .= html_writer
::table($table);
1556 $instancehtml = '<div>';
1559 //if no type is set, we can create all type of instance
1561 $instancehtml .= '<h3>';
1562 $instancehtml .= get_string('createrepository', 'repository');
1563 $instancehtml .= '</h3><ul>';
1564 $types = repository
::get_editable_types($context);
1565 foreach ($types as $type) {
1566 if (!empty($type) && $type->get_visible()) {
1567 // If the user does not have the permission to view the repository, it won't be displayed in
1568 // the list of instances. Hiding the link to create new instances will prevent the
1569 // user from creating them without being able to find them afterwards, which looks like a bug.
1570 if (!has_capability('repository/'.$type->get_typename().':view', $context)) {
1573 $instanceoptionnames = repository
::static_function($type->get_typename(), 'get_instance_option_names');
1574 if (!empty($instanceoptionnames)) {
1575 $baseurl->param('new', $type->get_typename());
1576 $instancehtml .= '<li><a href="'.$baseurl->out().'">'.get_string('createxxinstance', 'repository', get_string('pluginname', 'repository_'.$type->get_typename())). '</a></li>';
1577 $baseurl->remove_params('new');
1582 $instancehtml .= '</ul>';
1585 $instanceoptionnames = repository
::static_function($typename, 'get_instance_option_names');
1586 if (!empty($instanceoptionnames)) { //create a unique type of instance
1588 $baseurl->param('new', $typename);
1589 $output .= $OUTPUT->single_button($baseurl, get_string('createinstance', 'repository'), 'get');
1590 $baseurl->remove_params('new');
1595 $instancehtml .= '</div>';
1596 $output .= $instancehtml;
1599 $output .= $OUTPUT->box_end();
1601 //print the list + creation links
1606 * Prepare file reference information
1608 * @param string $source source of the file, returned by repository as 'source' and received back from user (not cleaned)
1609 * @return string file reference, ready to be stored
1611 public function get_file_reference($source) {
1612 if ($source && $this->has_moodle_files()) {
1613 $params = @json_decode
(base64_decode($source), true);
1614 if (!is_array($params) ||
empty($params['contextid'])) {
1615 throw new repository_exception('invalidparams', 'repository');
1618 'component' => empty($params['component']) ?
'' : clean_param($params['component'], PARAM_COMPONENT
),
1619 'filearea' => empty($params['filearea']) ?
'' : clean_param($params['filearea'], PARAM_AREA
),
1620 'itemid' => empty($params['itemid']) ?
0 : clean_param($params['itemid'], PARAM_INT
),
1621 'filename' => empty($params['filename']) ?
null : clean_param($params['filename'], PARAM_FILE
),
1622 'filepath' => empty($params['filepath']) ?
null : clean_param($params['filepath'], PARAM_PATH
),
1623 'contextid' => clean_param($params['contextid'], PARAM_INT
)
1625 // Check if context exists.
1626 if (!context
::instance_by_id($params['contextid'], IGNORE_MISSING
)) {
1627 throw new repository_exception('invalidparams', 'repository');
1629 return file_storage
::pack_reference($params);
1635 * Get a unique file path in which to save the file.
1637 * The filename returned will be removed at the end of the request and
1638 * should not be relied upon to exist in subsequent requests.
1640 * @param string $filename file name
1643 public function prepare_file($filename) {
1644 if (empty($filename)) {
1647 return sprintf('%s/%s', make_request_directory(), $filename);
1651 * Does this repository used to browse moodle files?
1655 public function has_moodle_files() {
1660 * Return file URL, for most plugins, the parameter is the original
1661 * url, but some plugins use a file id, so we need this function to
1662 * convert file id to original url.
1664 * @param string $url the url of file
1667 public function get_link($url) {
1672 * Downloads a file from external repository and saves it in temp dir
1674 * Function get_file() must be implemented by repositories that support returntypes
1675 * FILE_INTERNAL or FILE_REFERENCE. It is invoked to pick up the file and copy it
1676 * to moodle. This function is not called for moodle repositories, the function
1677 * {@link repository::copy_to_area()} is used instead.
1679 * This function can be overridden by subclass if the files.reference field contains
1680 * not just URL or if request should be done differently.
1683 * @throws file_exception when error occured
1685 * @param string $url the content of files.reference field, in this implementaion
1686 * it is asssumed that it contains the string with URL of the file
1687 * @param string $filename filename (without path) to save the downloaded file in the
1688 * temporary directory, if omitted or file already exists the new filename will be generated
1689 * @return array with elements:
1690 * path: internal location of the file
1691 * url: URL to the source (from parameters)
1693 public function get_file($url, $filename = '') {
1696 $path = $this->prepare_file($filename);
1699 $result = $c->download_one($url, null, array('filepath' => $path, 'timeout' => $CFG->repositorygetfiletimeout
));
1700 if ($result !== true) {
1701 throw new moodle_exception('errorwhiledownload', 'repository', '', $result);
1703 return array('path'=>$path, 'url'=>$url);
1707 * Downloads the file from external repository and saves it in moodle filepool.
1708 * This function is different from {@link repository::sync_reference()} because it has
1709 * bigger request timeout and always downloads the content.
1711 * This function is invoked when we try to unlink the file from the source and convert
1712 * a reference into a true copy.
1714 * @throws exception when file could not be imported
1716 * @param stored_file $file
1717 * @param int $maxbytes throw an exception if file size is bigger than $maxbytes (0 means no limit)
1719 public function import_external_file_contents(stored_file
$file, $maxbytes = 0) {
1720 if (!$file->is_external_file()) {
1721 // nothing to import if the file is not a reference
1723 } else if ($file->get_repository_id() != $this->id
) {
1725 debugging('Repository instance id does not match');
1727 } else if ($this->has_moodle_files()) {
1728 // files that are references to local files are already in moodle filepool
1729 // just validate the size
1730 if ($maxbytes > 0 && $file->get_filesize() > $maxbytes) {
1731 $maxbytesdisplay = display_size($maxbytes);
1732 throw new file_exception('maxbytesfile', (object) array('file' => $file->get_filename(),
1733 'size' => $maxbytesdisplay));
1737 if ($maxbytes > 0 && $file->get_filesize() > $maxbytes) {
1738 // note that stored_file::get_filesize() also calls synchronisation
1739 $maxbytesdisplay = display_size($maxbytes);
1740 throw new file_exception('maxbytesfile', (object) array('file' => $file->get_filename(),
1741 'size' => $maxbytesdisplay));
1743 $fs = get_file_storage();
1745 // If a file has been downloaded, the file record should report both a positive file
1746 // size, and a contenthash which does not related to empty content.
1747 // If thereis no file size, or the contenthash is for an empty file, then the file has
1748 // yet to be successfully downloaded.
1749 $contentexists = $file->get_filesize() && !$file->compare_to_string('');
1751 if (!$file->get_status() && $contentexists) {
1752 // we already have the content in moodle filepool and it was synchronised recently.
1753 // Repositories may overwrite it if they want to force synchronisation anyway!
1756 // attempt to get a file
1758 $fileinfo = $this->get_file($file->get_reference());
1759 if (isset($fileinfo['path'])) {
1760 $file->set_synchronised_content_from_file($fileinfo['path']);
1762 throw new moodle_exception('errorwhiledownload', 'repository', '', '');
1764 } catch (Exception
$e) {
1765 if ($contentexists) {
1766 // better something than nothing. We have a copy of file. It's sync time
1767 // has expired but it is still very likely that it is the last version
1777 * Return size of a file in bytes.
1779 * @param string $source encoded and serialized data of file
1780 * @return int file size in bytes
1782 public function get_file_size($source) {
1783 // TODO MDL-33297 remove this function completely?
1784 $browser = get_file_browser();
1785 $params = unserialize(base64_decode($source));
1786 $contextid = clean_param($params['contextid'], PARAM_INT
);
1787 $fileitemid = clean_param($params['itemid'], PARAM_INT
);
1788 $filename = clean_param($params['filename'], PARAM_FILE
);
1789 $filepath = clean_param($params['filepath'], PARAM_PATH
);
1790 $filearea = clean_param($params['filearea'], PARAM_AREA
);
1791 $component = clean_param($params['component'], PARAM_COMPONENT
);
1792 $context = context
::instance_by_id($contextid);
1793 $file_info = $browser->get_file_info($context, $component, $filearea, $fileitemid, $filepath, $filename);
1794 if (!empty($file_info)) {
1795 $filesize = $file_info->get_filesize();
1803 * Return is the instance is visible
1804 * (is the type visible ? is the context enable ?)
1808 public function is_visible() {
1809 $type = repository
::get_type_by_id($this->options
['typeid']);
1810 $instanceoptions = repository
::static_function($type->get_typename(), 'get_instance_option_names');
1812 if ($type->get_visible()) {
1813 //if the instance is unique so it's visible, otherwise check if the instance has a enabled context
1814 if (empty($instanceoptions) ||
$type->get_contextvisibility(context
::instance_by_id($this->instance
->contextid
))) {
1823 * Can the instance be edited by the current user?
1825 * The property $readonly must not be used within this method because
1826 * it only controls if the options from self::get_instance_option_names()
1829 * @return bool true if the user can edit the instance.
1832 public final function can_be_edited_by_user() {
1835 // We need to be able to explore the repository.
1837 $this->check_capability();
1838 } catch (repository_exception
$e) {
1842 $repocontext = context
::instance_by_id($this->instance
->contextid
);
1843 if ($repocontext->contextlevel
== CONTEXT_USER
&& $repocontext->instanceid
!= $USER->id
) {
1844 // If the context of this instance is a user context, we need to be this user.
1846 } else if ($repocontext->contextlevel
== CONTEXT_MODULE
&& !has_capability('moodle/course:update', $repocontext)) {
1847 // We need to have permissions on the course to edit the instance.
1849 } else if ($repocontext->contextlevel
== CONTEXT_SYSTEM
&& !has_capability('moodle/site:config', $repocontext)) {
1850 // Do not meet the requirements for the context system.
1858 * Return the name of this instance, can be overridden.
1862 public function get_name() {
1863 if ($name = $this->instance
->name
) {
1866 return get_string('pluginname', 'repository_' . $this->get_typename());
1871 * Is this repository accessing private data?
1873 * This function should return true for the repositories which access external private
1874 * data from a user. This is the case for repositories such as Dropbox, Google Docs or Box.net
1875 * which authenticate the user and then store the auth token.
1877 * Of course, many repositories store 'private data', but we only want to set
1878 * contains_private_data() to repositories which are external to Moodle and shouldn't be accessed
1879 * to by the users having the capability to 'login as' someone else. For instance, the repository
1880 * 'Private files' is not considered as private because it's part of Moodle.
1882 * You should not set contains_private_data() to true on repositories which allow different types
1883 * of instances as the levels other than 'user' are, by definition, not private. Also
1884 * the user instances will be protected when they need to.
1886 * @return boolean True when the repository accesses private external data.
1889 public function contains_private_data() {
1894 * What kind of files will be in this repository?
1896 * @return array return '*' means this repository support any files, otherwise
1897 * return mimetypes of files, it can be an array
1899 public function supported_filetypes() {
1900 // return array('text/plain', 'image/gif');
1905 * Tells how the file can be picked from this repository
1907 * Maximum value is FILE_INTERNAL | FILE_EXTERNAL | FILE_REFERENCE
1911 public function supported_returntypes() {
1912 return (FILE_INTERNAL | FILE_EXTERNAL
);
1916 * Tells how the file can be picked from this repository
1918 * Maximum value is FILE_INTERNAL | FILE_EXTERNAL | FILE_REFERENCE
1922 public function default_returntype() {
1923 return FILE_INTERNAL
;
1927 * Provide repository instance information for Ajax
1931 final public function get_meta() {
1932 global $CFG, $OUTPUT;
1933 $meta = new stdClass();
1934 $meta->id
= $this->id
;
1935 $meta->name
= format_string($this->get_name());
1936 $meta->type
= $this->get_typename();
1937 $meta->icon
= $OUTPUT->image_url('icon', 'repository_'.$meta->type
)->out(false);
1938 $meta->supported_types
= file_get_typegroup('extension', $this->supported_filetypes());
1939 $meta->return_types
= $this->supported_returntypes();
1940 $meta->defaultreturntype
= $this->default_returntype();
1941 $meta->sortorder
= $this->options
['sortorder'];
1946 * Create an instance for this plug-in
1949 * @param string $type the type of the repository
1950 * @param int $userid the user id
1951 * @param stdClass $context the context
1952 * @param array $params the options for this instance
1953 * @param int $readonly whether to create it readonly or not (defaults to not)
1956 public static function create($type, $userid, $context, $params, $readonly=0) {
1958 $params = (array)$params;
1959 require_once($CFG->dirroot
. '/repository/'. $type . '/lib.php');
1960 $classname = 'repository_' . $type;
1961 if ($repo = $DB->get_record('repository', array('type'=>$type))) {
1962 $record = new stdClass();
1963 $record->name
= $params['name'];
1964 $record->typeid
= $repo->id
;
1965 $record->timecreated
= time();
1966 $record->timemodified
= time();
1967 $record->contextid
= $context->id
;
1968 $record->readonly
= $readonly;
1969 $record->userid
= $userid;
1970 $id = $DB->insert_record('repository_instances', $record);
1971 cache
::make('core', 'repositories')->purge();
1973 $configs = call_user_func($classname . '::get_instance_option_names');
1974 if (!empty($configs)) {
1975 foreach ($configs as $config) {
1976 if (isset($params[$config])) {
1977 $options[$config] = $params[$config];
1979 $options[$config] = null;
1985 unset($options['name']);
1986 $instance = repository
::get_instance($id);
1987 $instance->set_option($options);
1998 * delete a repository instance
2000 * @param bool $downloadcontents
2003 final public function delete($downloadcontents = false) {
2005 if ($downloadcontents) {
2006 $this->convert_references_to_local();
2008 cache
::make('core', 'repositories')->purge();
2010 $DB->delete_records('repository_instances', array('id'=>$this->id
));
2011 $DB->delete_records('repository_instance_config', array('instanceid'=>$this->id
));
2012 } catch (dml_exception
$ex) {
2019 * Delete all the instances associated to a context.
2021 * This method is intended to be a callback when deleting
2022 * a course or a user to delete all the instances associated
2023 * to their context. The usual way to delete a single instance
2024 * is to use {@link self::delete()}.
2026 * @param int $contextid context ID.
2027 * @param boolean $downloadcontents true to convert references to hard copies.
2030 final public static function delete_all_for_context($contextid, $downloadcontents = true) {
2032 $repoids = $DB->get_fieldset_select('repository_instances', 'id', 'contextid = :contextid', array('contextid' => $contextid));
2033 if ($downloadcontents) {
2034 foreach ($repoids as $repoid) {
2035 $repo = repository
::get_repository_by_id($repoid, $contextid);
2036 $repo->convert_references_to_local();
2039 cache
::make('core', 'repositories')->purge();
2040 $DB->delete_records_list('repository_instances', 'id', $repoids);
2041 $DB->delete_records_list('repository_instance_config', 'instanceid', $repoids);
2045 * Hide/Show a repository
2047 * @param string $hide
2050 final public function hide($hide = 'toggle') {
2052 if ($entry = $DB->get_record('repository', array('id'=>$this->id
))) {
2053 if ($hide === 'toggle' ) {
2054 if (!empty($entry->visible
)) {
2055 $entry->visible
= 0;
2057 $entry->visible
= 1;
2060 if (!empty($hide)) {
2061 $entry->visible
= 0;
2063 $entry->visible
= 1;
2066 return $DB->update_record('repository', $entry);
2072 * Save settings for repository instance
2073 * $repo->set_option(array('api_key'=>'f2188bde132', 'name'=>'dongsheng'));
2075 * @param array $options settings
2078 public function set_option($options = array()) {
2081 if (!empty($options['name'])) {
2082 $r = new stdClass();
2084 $r->name
= $options['name'];
2085 $DB->update_record('repository_instances', $r);
2086 unset($options['name']);
2088 foreach ($options as $name=>$value) {
2089 if ($id = $DB->get_field('repository_instance_config', 'id', array('name'=>$name, 'instanceid'=>$this->id
))) {
2090 $DB->set_field('repository_instance_config', 'value', $value, array('id'=>$id));
2092 $config = new stdClass();
2093 $config->instanceid
= $this->id
;
2094 $config->name
= $name;
2095 $config->value
= $value;
2096 $DB->insert_record('repository_instance_config', $config);
2099 cache
::make('core', 'repositories')->purge();
2104 * Get settings for repository instance.
2106 * @param string $config a specific option to get.
2107 * @return mixed returns an array of options. If $config is not empty, then it returns that option,
2108 * or null if the option does not exist.
2110 public function get_option($config = '') {
2112 $cache = cache
::make('core', 'repositories');
2113 if (($entries = $cache->get('ops:'. $this->id
)) === false) {
2114 $entries = $DB->get_records('repository_instance_config', array('instanceid' => $this->id
));
2115 $cache->set('ops:'. $this->id
, $entries);
2119 foreach($entries as $entry) {
2120 $ret[$entry->name
] = $entry->value
;
2123 if (!empty($config)) {
2124 if (isset($ret[$config])) {
2125 return $ret[$config];
2135 * Filter file listing to display specific types
2137 * @param array $value
2140 public function filter(&$value) {
2141 $accepted_types = optional_param_array('accepted_types', '', PARAM_RAW
);
2142 if (isset($value['children'])) {
2143 if (!empty($value['children'])) {
2144 $value['children'] = array_filter($value['children'], array($this, 'filter'));
2146 return true; // always return directories
2148 if ($accepted_types == '*' or empty($accepted_types)
2149 or (is_array($accepted_types) and in_array('*', $accepted_types))) {
2152 foreach ($accepted_types as $ext) {
2153 if (preg_match('#'.$ext.'$#i', $value['title'])) {
2163 * Given a path, and perhaps a search, get a list of files.
2165 * See details on {@link http://docs.moodle.org/dev/Repository_plugins}
2167 * @param string $path this parameter can a folder name, or a identification of folder
2168 * @param string $page the page number of file list
2169 * @return array the list of files, including meta infomation, containing the following keys
2170 * manage, url to manage url
2173 * repo_id, active repository id
2174 * login_btn_action, the login button action
2175 * login_btn_label, the login button label
2176 * total, number of results
2177 * perpage, items per page
2179 * pages, total pages
2180 * issearchresult, is it a search result?
2182 * path, current path and parent path
2184 public function get_listing($path = '', $page = '') {
2189 * Prepare the breadcrumb.
2191 * @param array $breadcrumb contains each element of the breadcrumb.
2192 * @return array of breadcrumb elements.
2193 * @since Moodle 2.3.3
2195 protected static function prepare_breadcrumb($breadcrumb) {
2197 $foldericon = $OUTPUT->image_url(file_folder_icon(24))->out(false);
2198 $len = count($breadcrumb);
2199 for ($i = 0; $i < $len; $i++
) {
2200 if (is_array($breadcrumb[$i]) && !isset($breadcrumb[$i]['icon'])) {
2201 $breadcrumb[$i]['icon'] = $foldericon;
2202 } else if (is_object($breadcrumb[$i]) && !isset($breadcrumb[$i]->icon
)) {
2203 $breadcrumb[$i]->icon
= $foldericon;
2210 * Prepare the file/folder listing.
2212 * @param array $list of files and folders.
2213 * @return array of files and folders.
2214 * @since Moodle 2.3.3
2216 protected static function prepare_list($list) {
2218 $foldericon = $OUTPUT->image_url(file_folder_icon(24))->out(false);
2220 // Reset the array keys because non-numeric keys will create an object when converted to JSON.
2221 $list = array_values($list);
2223 $len = count($list);
2224 for ($i = 0; $i < $len; $i++
) {
2225 if (is_object($list[$i])) {
2226 $file = (array)$list[$i];
2227 $converttoobject = true;
2230 $converttoobject = false;
2232 if (isset($file['size'])) {
2233 $file['size'] = (int)$file['size'];
2234 $file['size_f'] = display_size($file['size']);
2236 if (isset($file['license']) && get_string_manager()->string_exists($file['license'], 'license')) {
2237 $file['license_f'] = get_string($file['license'], 'license');
2239 if (isset($file['image_width']) && isset($file['image_height'])) {
2240 $a = array('width' => $file['image_width'], 'height' => $file['image_height']);
2241 $file['dimensions'] = get_string('imagesize', 'repository', (object)$a);
2243 foreach (array('date', 'datemodified', 'datecreated') as $key) {
2244 if (!isset($file[$key]) && isset($file['date'])) {
2245 $file[$key] = $file['date'];
2247 if (isset($file[$key])) {
2248 // must be UNIX timestamp
2249 $file[$key] = (int)$file[$key];
2253 $file[$key.'_f'] = userdate($file[$key], get_string('strftimedatetime', 'langconfig'));
2254 $file[$key.'_f_s'] = userdate($file[$key], get_string('strftimedatetimeshort', 'langconfig'));
2258 $isfolder = (array_key_exists('children', $file) ||
(isset($file['type']) && $file['type'] == 'folder'));
2260 if (isset($file['title'])) {
2261 $filename = $file['title'];
2263 else if (isset($file['fullname'])) {
2264 $filename = $file['fullname'];
2266 if (!isset($file['mimetype']) && !$isfolder && $filename) {
2267 $file['mimetype'] = get_mimetype_description(array('filename' => $filename));
2269 if (!isset($file['icon'])) {
2271 $file['icon'] = $foldericon;
2272 } else if ($filename) {
2273 $file['icon'] = $OUTPUT->image_url(file_extension_icon($filename, 24))->out(false);
2277 // Recursively loop over children.
2278 if (isset($file['children'])) {
2279 $file['children'] = self
::prepare_list($file['children']);
2282 // Convert the array back to an object.
2283 if ($converttoobject) {
2284 $list[$i] = (object)$file;
2291 * Prepares list of files before passing it to AJAX, makes sure data is in the correct
2292 * format and stores formatted values.
2294 * @param array|stdClass $listing result of get_listing() or search() or file_get_drafarea_files()
2297 public static function prepare_listing($listing) {
2299 if (is_object($listing)) {
2300 $listing = (array) $listing;
2304 // Prepare the breadcrumb, passed as 'path'.
2305 if (isset($listing['path']) && is_array($listing['path'])) {
2306 $listing['path'] = self
::prepare_breadcrumb($listing['path']);
2309 // Prepare the listing of objects.
2310 if (isset($listing['list']) && is_array($listing['list'])) {
2311 $listing['list'] = self
::prepare_list($listing['list']);
2314 // Convert back to an object.
2316 $listing = (object) $listing;
2322 * Search files in repository
2323 * When doing global search, $search_text will be used as
2326 * @param string $search_text search key word
2327 * @param int $page page
2328 * @return mixed see {@link repository::get_listing()}
2330 public function search($search_text, $page = 0) {
2332 $list['list'] = array();
2337 * Logout from repository instance
2338 * By default, this function will return a login form
2342 public function logout(){
2343 return $this->print_login();
2347 * To check whether the user is logged in.
2351 public function check_login(){
2357 * Show the login screen, if required
2361 public function print_login(){
2362 return $this->get_listing();
2366 * Show the search screen, if required
2370 public function print_search() {
2372 $renderer = $PAGE->get_renderer('core', 'files');
2373 return $renderer->repository_default_searchform();
2377 * For oauth like external authentication, when external repository direct user back to moodle,
2378 * this function will be called to set up token and token_secret
2380 public function callback() {
2384 * is it possible to do glboal search?
2388 public function global_search() {
2393 * Defines operations that happen occasionally on cron
2397 public function cron() {
2402 * function which is run when the type is created (moodle administrator add the plugin)
2404 * @return bool success or fail?
2406 public static function plugin_init() {
2411 * Edit/Create Admin Settings Moodle form
2413 * @param moodleform $mform Moodle form (passed by reference)
2414 * @param string $classname repository class name
2416 public static function type_config_form($mform, $classname = 'repository') {
2417 $instnaceoptions = call_user_func(array($classname, 'get_instance_option_names'), $mform, $classname);
2418 if (empty($instnaceoptions)) {
2419 // this plugin has only one instance
2420 // so we need to give it a name
2421 // it can be empty, then moodle will look for instance name from language string
2422 $mform->addElement('text', 'pluginname', get_string('pluginname', 'repository'), array('size' => '40'));
2423 $mform->addElement('static', 'pluginnamehelp', '', get_string('pluginnamehelp', 'repository'));
2424 $mform->setType('pluginname', PARAM_TEXT
);
2429 * Validate Admin Settings Moodle form
2432 * @param moodleform $mform Moodle form (passed by reference)
2433 * @param array $data array of ("fieldname"=>value) of submitted data
2434 * @param array $errors array of ("fieldname"=>errormessage) of errors
2435 * @return array array of errors
2437 public static function type_form_validation($mform, $data, $errors) {
2443 * Edit/Create Instance Settings Moodle form
2445 * @param moodleform $mform Moodle form (passed by reference)
2447 public static function instance_config_form($mform) {
2451 * Return names of the general options.
2452 * By default: no general option name
2456 public static function get_type_option_names() {
2457 return array('pluginname');
2461 * Return names of the instance options.
2462 * By default: no instance option name
2466 public static function get_instance_option_names() {
2471 * Validate repository plugin instance form
2473 * @param moodleform $mform moodle form
2474 * @param array $data form data
2475 * @param array $errors errors
2476 * @return array errors
2478 public static function instance_form_validation($mform, $data, $errors) {
2483 * Create a shorten filename
2485 * @param string $str filename
2486 * @param int $maxlength max file name length
2487 * @return string short filename
2489 public function get_short_filename($str, $maxlength) {
2490 if (core_text
::strlen($str) >= $maxlength) {
2491 return trim(core_text
::substr($str, 0, $maxlength)).'...';
2498 * Overwrite an existing file
2500 * @param int $itemid
2501 * @param string $filepath
2502 * @param string $filename
2503 * @param string $newfilepath
2504 * @param string $newfilename
2507 public static function overwrite_existing_draftfile($itemid, $filepath, $filename, $newfilepath, $newfilename) {
2509 $fs = get_file_storage();
2510 $user_context = context_user
::instance($USER->id
);
2511 if ($file = $fs->get_file($user_context->id
, 'user', 'draft', $itemid, $filepath, $filename)) {
2512 if ($tempfile = $fs->get_file($user_context->id
, 'user', 'draft', $itemid, $newfilepath, $newfilename)) {
2513 // Remember original file source field.
2514 $source = @unserialize
($file->get_source());
2515 // Remember the original sortorder.
2516 $sortorder = $file->get_sortorder();
2517 if ($tempfile->is_external_file()) {
2518 // New file is a reference. Check that existing file does not have any other files referencing to it
2519 if (isset($source->original
) && $fs->search_references_count($source->original
)) {
2520 return (object)array('error' => get_string('errordoublereference', 'repository'));
2523 // delete existing file to release filename
2526 $newfile = $fs->create_file_from_storedfile(array('filepath'=>$filepath, 'filename'=>$filename), $tempfile);
2527 // Preserve original file location (stored in source field) for handling references
2528 if (isset($source->original
)) {
2529 if (!($newfilesource = @unserialize
($newfile->get_source()))) {
2530 $newfilesource = new stdClass();
2532 $newfilesource->original
= $source->original
;
2533 $newfile->set_source(serialize($newfilesource));
2535 $newfile->set_sortorder($sortorder);
2537 $tempfile->delete();
2545 * Updates a file in draft filearea.
2547 * This function can only update fields filepath, filename, author, license.
2548 * If anything (except filepath) is updated, timemodified is set to current time.
2549 * If filename or filepath is updated the file unconnects from it's origin
2550 * and therefore all references to it will be converted to copies when
2551 * filearea is saved.
2553 * @param int $draftid
2554 * @param string $filepath path to the directory containing the file, or full path in case of directory
2555 * @param string $filename name of the file, or '.' in case of directory
2556 * @param array $updatedata array of fields to change (only filename, filepath, license and/or author can be updated)
2557 * @throws moodle_exception if for any reason file can not be updated (file does not exist, target already exists, etc.)
2559 public static function update_draftfile($draftid, $filepath, $filename, $updatedata) {
2561 $fs = get_file_storage();
2562 $usercontext = context_user
::instance($USER->id
);
2563 // make sure filename and filepath are present in $updatedata
2564 $updatedata = $updatedata +
array('filepath' => $filepath, 'filename' => $filename);
2565 $filemodified = false;
2566 if (!$file = $fs->get_file($usercontext->id
, 'user', 'draft', $draftid, $filepath, $filename)) {
2567 if ($filename === '.') {
2568 throw new moodle_exception('foldernotfound', 'repository');
2570 throw new moodle_exception('filenotfound', 'error');
2573 if (!$file->is_directory()) {
2575 if ($updatedata['filepath'] !== $filepath ||
$updatedata['filename'] !== $filename) {
2576 // Rename/move file: check that target file name does not exist.
2577 if ($fs->file_exists($usercontext->id
, 'user', 'draft', $draftid, $updatedata['filepath'], $updatedata['filename'])) {
2578 throw new moodle_exception('fileexists', 'repository');
2580 if (($filesource = @unserialize
($file->get_source())) && isset($filesource->original
)) {
2581 unset($filesource->original
);
2582 $file->set_source(serialize($filesource));
2584 $file->rename($updatedata['filepath'], $updatedata['filename']);
2585 // timemodified is updated only when file is renamed and not updated when file is moved.
2586 $filemodified = $filemodified ||
($updatedata['filename'] !== $filename);
2588 if (array_key_exists('license', $updatedata) && $updatedata['license'] !== $file->get_license()) {
2589 // Update license and timemodified.
2590 $file->set_license($updatedata['license']);
2591 $filemodified = true;
2593 if (array_key_exists('author', $updatedata) && $updatedata['author'] !== $file->get_author()) {
2594 // Update author and timemodified.
2595 $file->set_author($updatedata['author']);
2596 $filemodified = true;
2598 // Update timemodified:
2599 if ($filemodified) {
2600 $file->set_timemodified(time());
2603 // This is a directory - only filepath can be updated for a directory (it was moved).
2604 if ($updatedata['filepath'] === $filepath) {
2605 // nothing to update
2608 if ($fs->file_exists($usercontext->id
, 'user', 'draft', $draftid, $updatedata['filepath'], '.')) {
2609 // bad luck, we can not rename if something already exists there
2610 throw new moodle_exception('folderexists', 'repository');
2612 $xfilepath = preg_quote($filepath, '|');
2613 if (preg_match("|^$xfilepath|", $updatedata['filepath'])) {
2614 // we can not move folder to it's own subfolder
2615 throw new moodle_exception('folderrecurse', 'repository');
2618 // If directory changed the name, update timemodified.
2619 $filemodified = (basename(rtrim($file->get_filepath(), '/')) !== basename(rtrim($updatedata['filepath'], '/')));
2621 // Now update directory and all children.
2622 $files = $fs->get_area_files($usercontext->id
, 'user', 'draft', $draftid);
2623 foreach ($files as $f) {
2624 if (preg_match("|^$xfilepath|", $f->get_filepath())) {
2625 $path = preg_replace("|^$xfilepath|", $updatedata['filepath'], $f->get_filepath());
2626 if (($filesource = @unserialize
($f->get_source())) && isset($filesource->original
)) {
2627 // unset original so the references are not shown any more
2628 unset($filesource->original
);
2629 $f->set_source(serialize($filesource));
2631 $f->rename($path, $f->get_filename());
2632 if ($filemodified && $f->get_filepath() === $updatedata['filepath'] && $f->get_filename() === $filename) {
2633 $f->set_timemodified(time());
2641 * Delete a temp file from draft area
2643 * @param int $draftitemid
2644 * @param string $filepath
2645 * @param string $filename
2648 public static function delete_tempfile_from_draft($draftitemid, $filepath, $filename) {
2650 $fs = get_file_storage();
2651 $user_context = context_user
::instance($USER->id
);
2652 if ($file = $fs->get_file($user_context->id
, 'user', 'draft', $draftitemid, $filepath, $filename)) {
2661 * Find all external files in this repo and import them
2663 public function convert_references_to_local() {
2664 $fs = get_file_storage();
2665 $files = $fs->get_external_files($this->id
);
2666 foreach ($files as $storedfile) {
2667 $fs->import_external_file($storedfile);
2672 * Function repository::reset_caches() is deprecated, cache is handled by MUC now.
2673 * @deprecated since Moodle 2.6 MDL-42016 - please do not use this function any more.
2675 public static function reset_caches() {
2676 throw new coding_exception('Function repository::reset_caches() can not be used any more, cache is handled by MUC now.');
2680 * Function repository::sync_external_file() is deprecated. Use repository::sync_reference instead
2682 * @deprecated since Moodle 2.6 MDL-42016 - please do not use this function any more.
2683 * @see repository::sync_reference()
2685 public static function sync_external_file($file, $resetsynchistory = false) {
2686 throw new coding_exception('Function repository::sync_external_file() can not be used any more. ' .
2687 'Use repository::sync_reference instead.');
2691 * Performs synchronisation of an external file if the previous one has expired.
2693 * This function must be implemented for external repositories supporting
2694 * FILE_REFERENCE, it is called for existing aliases when their filesize,
2695 * contenthash or timemodified are requested. It is not called for internal
2696 * repositories (see {@link repository::has_moodle_files()}), references to
2697 * internal files are updated immediately when source is modified.
2699 * Referenced files may optionally keep their content in Moodle filepool (for
2700 * thumbnail generation or to be able to serve cached copy). In this
2701 * case both contenthash and filesize need to be synchronized. Otherwise repositories
2702 * should use contenthash of empty file and correct filesize in bytes.
2704 * Note that this function may be run for EACH file that needs to be synchronised at the
2705 * moment. If anything is being downloaded or requested from external sources there
2706 * should be a small timeout. The synchronisation is performed to update the size of
2707 * the file and/or to update image and re-generated image preview. There is nothing
2708 * fatal if syncronisation fails but it is fatal if syncronisation takes too long
2709 * and hangs the script generating a page.
2711 * Note: If you wish to call $file->get_filesize(), $file->get_contenthash() or
2712 * $file->get_timemodified() make sure that recursion does not happen.
2714 * Called from {@link stored_file::sync_external_file()}
2716 * @uses stored_file::set_missingsource()
2717 * @uses stored_file::set_synchronized()
2718 * @param stored_file $file
2719 * @return bool false when file does not need synchronisation, true if it was synchronised
2721 public function sync_reference(stored_file
$file) {
2722 if ($file->get_repository_id() != $this->id
) {
2723 // This should not really happen because the function can be called from stored_file only.
2727 if ($this->has_moodle_files()) {
2728 // References to local files need to be synchronised only once.
2729 // Later they will be synchronised automatically when the source is changed.
2730 if ($file->get_referencelastsync()) {
2733 $fs = get_file_storage();
2734 $params = file_storage
::unpack_reference($file->get_reference(), true);
2735 if (!is_array($params) ||
!($storedfile = $fs->get_file($params['contextid'],
2736 $params['component'], $params['filearea'], $params['itemid'], $params['filepath'],
2737 $params['filename']))) {
2738 $file->set_missingsource();
2740 $file->set_synchronized($storedfile->get_contenthash(), $storedfile->get_filesize(), 0, $storedfile->get_timemodified());
2749 * Build draft file's source field
2751 * {@link file_restore_source_field_from_draft_file()}
2752 * XXX: This is a hack for file manager (MDL-28666)
2753 * For newly created draft files we have to construct
2754 * source filed in php serialized data format.
2755 * File manager needs to know the original file information before copying
2756 * to draft area, so we append these information in mdl_files.source field
2758 * @param string $source
2759 * @return string serialised source field
2761 public static function build_source_field($source) {
2762 $sourcefield = new stdClass
;
2763 $sourcefield->source
= $source;
2764 return serialize($sourcefield);
2768 * Prepares the repository to be cached. Implements method from cacheable_object interface.
2772 public function prepare_to_cache() {
2774 'class' => get_class($this),
2776 'ctxid' => $this->context
->id
,
2777 'options' => $this->options
,
2778 'readonly' => $this->readonly
2783 * Restores the repository from cache. Implements method from cacheable_object interface.
2787 public static function wake_from_cache($data) {
2788 $classname = $data['class'];
2789 return new $classname($data['id'], $data['ctxid'], $data['options'], $data['readonly']);
2793 * Gets a file relative to this file in the repository and sends it to the browser.
2794 * Used to allow relative file linking within a repository without creating file records
2797 * Repositories that overwrite this must be very careful - see filesystem repository for example.
2799 * @param stored_file $mainfile The main file we are trying to access relative files for.
2800 * @param string $relativepath the relative path to the file we are trying to access.
2803 public function send_relative_file(stored_file
$mainfile, $relativepath) {
2804 // This repository hasn't implemented this so send_file_not_found.
2805 send_file_not_found();
2809 * helper function to check if the repository supports send_relative_file.
2811 * @return true|false
2813 public function supports_relative_file() {
2818 * Helper function to indicate if this repository uses post requests for uploading files.
2820 * @deprecated since Moodle 3.2, 3.1.1, 3.0.5
2823 public function uses_post_requests() {
2824 debugging('The method repository::uses_post_requests() is deprecated and must not be used anymore.', DEBUG_DEVELOPER
);
2830 * Exception class for repository api
2833 * @package core_repository
2834 * @copyright 2009 Dongsheng Cai {@link http://dongsheng.org}
2835 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2837 class repository_exception
extends moodle_exception
{
2841 * This is a class used to define a repository instance form
2844 * @package core_repository
2845 * @copyright 2009 Dongsheng Cai {@link http://dongsheng.org}
2846 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2848 final class repository_instance_form
extends moodleform
{
2849 /** @var stdClass repository instance */
2850 protected $instance;
2851 /** @var string repository plugin type */
2855 * Added defaults to moodle form
2857 protected function add_defaults() {
2858 $mform =& $this->_form
;
2859 $strrequired = get_string('required');
2861 $mform->addElement('hidden', 'edit', ($this->instance
) ?
$this->instance
->id
: 0);
2862 $mform->setType('edit', PARAM_INT
);
2863 $mform->addElement('hidden', 'new', $this->plugin
);
2864 $mform->setType('new', PARAM_ALPHANUMEXT
);
2865 $mform->addElement('hidden', 'plugin', $this->plugin
);
2866 $mform->setType('plugin', PARAM_PLUGIN
);
2867 $mform->addElement('hidden', 'typeid', $this->typeid
);
2868 $mform->setType('typeid', PARAM_INT
);
2869 $mform->addElement('hidden', 'contextid', $this->contextid
);
2870 $mform->setType('contextid', PARAM_INT
);
2872 $mform->addElement('text', 'name', get_string('name'), 'maxlength="100" size="30"');
2873 $mform->addRule('name', $strrequired, 'required', null, 'client');
2874 $mform->setType('name', PARAM_TEXT
);
2878 * Define moodle form elements
2880 public function definition() {
2882 // type of plugin, string
2883 $this->plugin
= $this->_customdata
['plugin'];
2884 $this->typeid
= $this->_customdata
['typeid'];
2885 $this->contextid
= $this->_customdata
['contextid'];
2886 $this->instance
= (isset($this->_customdata
['instance'])
2887 && is_subclass_of($this->_customdata
['instance'], 'repository'))
2888 ?
$this->_customdata
['instance'] : null;
2890 $mform =& $this->_form
;
2892 $this->add_defaults();
2894 // Add instance config options.
2895 $result = repository
::static_function($this->plugin
, 'instance_config_form', $mform);
2896 if ($result === false) {
2897 // Remove the name element if no other config options.
2898 $mform->removeElement('name');
2900 if ($this->instance
) {
2902 $data['name'] = $this->instance
->name
;
2903 if (!$this->instance
->readonly
) {
2904 // and set the data if we have some.
2905 foreach ($this->instance
->get_instance_option_names() as $config) {
2906 if (!empty($this->instance
->options
[$config])) {
2907 $data[$config] = $this->instance
->options
[$config];
2909 $data[$config] = '';
2913 $this->set_data($data);
2916 if ($result === false) {
2917 $mform->addElement('cancel');
2919 $this->add_action_buttons(true, get_string('save','repository'));
2924 * Validate moodle form data
2926 * @param array $data form data
2927 * @param array $files files in form
2928 * @return array errors
2930 public function validation($data, $files) {
2933 $plugin = $this->_customdata
['plugin'];
2934 $instance = (isset($this->_customdata
['instance'])
2935 && is_subclass_of($this->_customdata
['instance'], 'repository'))
2936 ?
$this->_customdata
['instance'] : null;
2939 $errors = repository
::static_function($plugin, 'instance_form_validation', $this, $data, $errors);
2941 $errors = $instance->instance_form_validation($this, $data, $errors);
2944 $sql = "SELECT count('x')
2945 FROM {repository_instances} i, {repository} r
2946 WHERE r.type=:plugin AND r.id=i.typeid AND i.name=:name AND i.contextid=:contextid";
2947 $params = array('name' => $data['name'], 'plugin' => $this->plugin
, 'contextid' => $this->contextid
);
2949 $sql .= ' AND i.id != :instanceid';
2950 $params['instanceid'] = $instance->id
;
2952 if ($DB->count_records_sql($sql, $params) > 0) {
2953 $errors['name'] = get_string('erroruniquename', 'repository');
2961 * This is a class used to define a repository type setting form
2964 * @package core_repository
2965 * @copyright 2009 Dongsheng Cai {@link http://dongsheng.org}
2966 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2968 final class repository_type_form
extends moodleform
{
2969 /** @var stdClass repository instance */
2970 protected $instance;
2971 /** @var string repository plugin name */
2973 /** @var string action */
2977 * Definition of the moodleform
2979 public function definition() {
2981 // type of plugin, string
2982 $this->plugin
= $this->_customdata
['plugin'];
2983 $this->instance
= (isset($this->_customdata
['instance'])
2984 && is_a($this->_customdata
['instance'], 'repository_type'))
2985 ?
$this->_customdata
['instance'] : null;
2987 $this->action
= $this->_customdata
['action'];
2988 $this->pluginname
= $this->_customdata
['pluginname'];
2989 $mform =& $this->_form
;
2990 $strrequired = get_string('required');
2992 $mform->addElement('hidden', 'action', $this->action
);
2993 $mform->setType('action', PARAM_TEXT
);
2994 $mform->addElement('hidden', 'repos', $this->plugin
);
2995 $mform->setType('repos', PARAM_PLUGIN
);
2997 // let the plugin add its specific fields
2998 $classname = 'repository_' . $this->plugin
;
2999 require_once($CFG->dirroot
. '/repository/' . $this->plugin
. '/lib.php');
3000 //add "enable course/user instances" checkboxes if multiple instances are allowed
3001 $instanceoptionnames = repository
::static_function($this->plugin
, 'get_instance_option_names');
3003 $result = call_user_func(array($classname, 'type_config_form'), $mform, $classname);
3005 if (!empty($instanceoptionnames)) {
3006 $sm = get_string_manager();
3007 $component = 'repository';
3008 if ($sm->string_exists('enablecourseinstances', 'repository_' . $this->plugin
)) {
3009 $component .= ('_' . $this->plugin
);
3011 $mform->addElement('checkbox', 'enablecourseinstances', get_string('enablecourseinstances', $component));
3012 $mform->setType('enablecourseinstances', PARAM_BOOL
);
3014 $component = 'repository';
3015 if ($sm->string_exists('enableuserinstances', 'repository_' . $this->plugin
)) {
3016 $component .= ('_' . $this->plugin
);
3018 $mform->addElement('checkbox', 'enableuserinstances', get_string('enableuserinstances', $component));
3019 $mform->setType('enableuserinstances', PARAM_BOOL
);
3022 // set the data if we have some.
3023 if ($this->instance
) {
3025 $option_names = call_user_func(array($classname,'get_type_option_names'));
3026 if (!empty($instanceoptionnames)){
3027 $option_names[] = 'enablecourseinstances';
3028 $option_names[] = 'enableuserinstances';
3031 $instanceoptions = $this->instance
->get_options();
3032 foreach ($option_names as $config) {
3033 if (!empty($instanceoptions[$config])) {
3034 $data[$config] = $instanceoptions[$config];
3036 $data[$config] = '';
3039 // XXX: set plugin name for plugins which doesn't have muliti instances
3040 if (empty($instanceoptionnames)){
3041 $data['pluginname'] = $this->pluginname
;
3043 $this->set_data($data);
3046 $this->add_action_buttons(true, get_string('save','repository'));
3050 * Validate moodle form data
3052 * @param array $data moodle form data
3053 * @param array $files
3054 * @return array errors
3056 public function validation($data, $files) {
3058 $plugin = $this->_customdata
['plugin'];
3059 $instance = (isset($this->_customdata
['instance'])
3060 && is_subclass_of($this->_customdata
['instance'], 'repository'))
3061 ?
$this->_customdata
['instance'] : null;
3063 $errors = repository
::static_function($plugin, 'type_form_validation', $this, $data, $errors);
3065 $errors = $instance->type_form_validation($this, $data, $errors);
3073 * Generate all options needed by filepicker
3075 * @param array $args including following keys
3080 * @return array the list of repository instances, including meta infomation, containing the following keys
3085 function initialise_filepicker($args) {
3086 global $CFG, $USER, $PAGE, $OUTPUT;
3087 static $templatesinitialized = array();
3088 require_once($CFG->libdir
. '/licenselib.php');
3090 $return = new stdClass();
3091 $licenses = array();
3092 if (!empty($CFG->licenses
)) {
3093 $array = explode(',', $CFG->licenses
);
3094 foreach ($array as $license) {
3095 $l = new stdClass();
3096 $l->shortname
= $license;
3097 $l->fullname
= get_string($license, 'license');
3101 if (!empty($CFG->sitedefaultlicense
)) {
3102 $return->defaultlicense
= $CFG->sitedefaultlicense
;
3105 $return->licenses
= $licenses;
3107 $return->author
= fullname($USER);
3109 if (empty($args->context
)) {
3110 $context = $PAGE->context
;
3112 $context = $args->context
;
3114 $disable_types = array();
3115 if (!empty($args->disable_types
)) {
3116 $disable_types = $args->disable_types
;
3119 $user_context = context_user
::instance($USER->id
);
3121 list($context, $course, $cm) = get_context_info_array($context->id
);
3122 $contexts = array($user_context, context_system
::instance());
3123 if (!empty($course)) {
3124 // adding course context
3125 $contexts[] = context_course
::instance($course->id
);
3127 $externallink = (int)get_config(null, 'repositoryallowexternallinks');
3128 $repositories = repository
::get_instances(array(
3129 'context'=>$contexts,
3130 'currentcontext'=> $context,
3131 'accepted_types'=>$args->accepted_types
,
3132 'return_types'=>$args->return_types
,
3133 'disable_types'=>$disable_types
3136 $return->repositories
= array();
3138 if (empty($externallink)) {
3139 $return->externallink
= false;
3141 $return->externallink
= true;
3144 $return->userprefs
= array();
3145 $return->userprefs
['recentrepository'] = get_user_preferences('filepicker_recentrepository', '');
3146 $return->userprefs
['recentlicense'] = get_user_preferences('filepicker_recentlicense', '');
3147 $return->userprefs
['recentviewmode'] = get_user_preferences('filepicker_recentviewmode', '');
3149 user_preference_allow_ajax_update('filepicker_recentrepository', PARAM_INT
);
3150 user_preference_allow_ajax_update('filepicker_recentlicense', PARAM_SAFEDIR
);
3151 user_preference_allow_ajax_update('filepicker_recentviewmode', PARAM_INT
);
3154 // provided by form element
3155 $return->accepted_types
= file_get_typegroup('extension', $args->accepted_types
);
3156 $return->return_types
= $args->return_types
;
3157 $templates = array();
3158 foreach ($repositories as $repository) {
3159 $meta = $repository->get_meta();
3160 // Please note that the array keys for repositories are used within
3161 // JavaScript a lot, the key NEEDS to be the repository id.
3162 $return->repositories
[$repository->id
] = $meta;
3163 // Register custom repository template if it has one
3164 if(method_exists($repository, 'get_upload_template') && !array_key_exists('uploadform_' . $meta->type
, $templatesinitialized)) {
3165 $templates['uploadform_' . $meta->type
] = $repository->get_upload_template();
3166 $templatesinitialized['uploadform_' . $meta->type
] = true;
3169 if (!array_key_exists('core', $templatesinitialized)) {
3170 // we need to send each filepicker template to the browser just once
3171 $fprenderer = $PAGE->get_renderer('core', 'files');
3172 $templates = array_merge($templates, $fprenderer->filepicker_js_templates());
3173 $templatesinitialized['core'] = true;
3175 if (sizeof($templates)) {
3176 $PAGE->requires
->js_init_call('M.core_filepicker.set_templates', array($templates), true);