Merge branch 'w50_MDL-31410_m24_paypalipn' of https://github.com/skodak/moodle into...
[moodle.git] / repository / lib.php
blobe9781e20bccba75bbd56730f9599b82baafe42a5
1 <?php
2 // This file is part of Moodle - http://moodle.org/
3 //
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
8 //
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
17 /**
18 * This file contains classes used to manage the repository plugins in Moodle
20 * @since 2.0
21 * @package core_repository
22 * @copyright 2009 Dongsheng Cai {@link http://dongsheng.org}
23 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
26 defined('MOODLE_INTERNAL') || die();
27 require_once($CFG->libdir . '/filelib.php');
28 require_once($CFG->libdir . '/formslib.php');
30 define('FILE_EXTERNAL', 1);
31 define('FILE_INTERNAL', 2);
32 define('FILE_REFERENCE', 4);
33 define('RENAME_SUFFIX', '_2');
35 /**
36 * This class is used to manage repository plugins
38 * A repository_type is a repository plug-in. It can be Box.net, Flick-r, ...
39 * A repository type can be edited, sorted and hidden. It is mandatory for an
40 * administrator to create a repository type in order to be able to create
41 * some instances of this type.
42 * Coding note:
43 * - a repository_type object is mapped to the "repository" database table
44 * - "typename" attibut maps the "type" database field. It is unique.
45 * - general "options" for a repository type are saved in the config_plugin table
46 * - when you delete a repository, all instances are deleted, and general
47 * options are also deleted from database
48 * - When you create a type for a plugin that can't have multiple instances, a
49 * instance is automatically created.
51 * @package core_repository
52 * @copyright 2009 Jerome Mouneyrac
53 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
55 class repository_type {
58 /**
59 * Type name (no whitespace) - A type name is unique
60 * Note: for a user-friendly type name see get_readablename()
61 * @var String
63 private $_typename;
66 /**
67 * Options of this type
68 * They are general options that any instance of this type would share
69 * e.g. API key
70 * These options are saved in config_plugin table
71 * @var array
73 private $_options;
76 /**
77 * Is the repository type visible or hidden
78 * If false (hidden): no instances can be created, edited, deleted, showned , used...
79 * @var boolean
81 private $_visible;
84 /**
85 * 0 => not ordered, 1 => first position, 2 => second position...
86 * A not order type would appear in first position (should never happened)
87 * @var integer
89 private $_sortorder;
91 /**
92 * Return if the instance is visible in a context
94 * @todo check if the context visibility has been overwritten by the plugin creator
95 * (need to create special functions to be overvwritten in repository class)
96 * @param stdClass $context context
97 * @return bool
99 public function get_contextvisibility($context) {
100 global $USER;
102 if ($context->contextlevel == CONTEXT_COURSE) {
103 return $this->_options['enablecourseinstances'];
106 if ($context->contextlevel == CONTEXT_USER) {
107 return $this->_options['enableuserinstances'];
110 //the context is SITE
111 return true;
117 * repository_type constructor
119 * @param int $typename
120 * @param array $typeoptions
121 * @param bool $visible
122 * @param int $sortorder (don't really need set, it will be during create() call)
124 public function __construct($typename = '', $typeoptions = array(), $visible = true, $sortorder = 0) {
125 global $CFG;
127 //set type attributs
128 $this->_typename = $typename;
129 $this->_visible = $visible;
130 $this->_sortorder = $sortorder;
132 //set options attribut
133 $this->_options = array();
134 $options = repository::static_function($typename, 'get_type_option_names');
135 //check that the type can be setup
136 if (!empty($options)) {
137 //set the type options
138 foreach ($options as $config) {
139 if (array_key_exists($config, $typeoptions)) {
140 $this->_options[$config] = $typeoptions[$config];
145 //retrieve visibility from option
146 if (array_key_exists('enablecourseinstances',$typeoptions)) {
147 $this->_options['enablecourseinstances'] = $typeoptions['enablecourseinstances'];
148 } else {
149 $this->_options['enablecourseinstances'] = 0;
152 if (array_key_exists('enableuserinstances',$typeoptions)) {
153 $this->_options['enableuserinstances'] = $typeoptions['enableuserinstances'];
154 } else {
155 $this->_options['enableuserinstances'] = 0;
161 * Get the type name (no whitespace)
162 * For a human readable name, use get_readablename()
164 * @return string the type name
166 public function get_typename() {
167 return $this->_typename;
171 * Return a human readable and user-friendly type name
173 * @return string user-friendly type name
175 public function get_readablename() {
176 return get_string('pluginname','repository_'.$this->_typename);
180 * Return general options
182 * @return array the general options
184 public function get_options() {
185 return $this->_options;
189 * Return visibility
191 * @return bool
193 public function get_visible() {
194 return $this->_visible;
198 * Return order / position of display in the file picker
200 * @return int
202 public function get_sortorder() {
203 return $this->_sortorder;
207 * Create a repository type (the type name must not already exist)
208 * @param bool $silent throw exception?
209 * @return mixed return int if create successfully, return false if
211 public function create($silent = false) {
212 global $DB;
214 //check that $type has been set
215 $timmedtype = trim($this->_typename);
216 if (empty($timmedtype)) {
217 throw new repository_exception('emptytype', 'repository');
220 //set sortorder as the last position in the list
221 if (!isset($this->_sortorder) || $this->_sortorder == 0 ) {
222 $sql = "SELECT MAX(sortorder) FROM {repository}";
223 $this->_sortorder = 1 + $DB->get_field_sql($sql);
226 //only create a new type if it doesn't already exist
227 $existingtype = $DB->get_record('repository', array('type'=>$this->_typename));
228 if (!$existingtype) {
229 //create the type
230 $newtype = new stdClass();
231 $newtype->type = $this->_typename;
232 $newtype->visible = $this->_visible;
233 $newtype->sortorder = $this->_sortorder;
234 $plugin_id = $DB->insert_record('repository', $newtype);
235 //save the options in DB
236 $this->update_options();
238 $instanceoptionnames = repository::static_function($this->_typename, 'get_instance_option_names');
240 //if the plugin type has no multiple instance (e.g. has no instance option name) so it wont
241 //be possible for the administrator to create a instance
242 //in this case we need to create an instance
243 if (empty($instanceoptionnames)) {
244 $instanceoptions = array();
245 if (empty($this->_options['pluginname'])) {
246 // when moodle trying to install some repo plugin automatically
247 // this option will be empty, get it from language string when display
248 $instanceoptions['name'] = '';
249 } else {
250 // when admin trying to add a plugin manually, he will type a name
251 // for it
252 $instanceoptions['name'] = $this->_options['pluginname'];
254 repository::static_function($this->_typename, 'create', $this->_typename, 0, get_system_context(), $instanceoptions);
256 //run plugin_init function
257 if (!repository::static_function($this->_typename, 'plugin_init')) {
258 $this->update_visibility(false);
259 if (!$silent) {
260 throw new repository_exception('cannotinitplugin', 'repository');
264 if(!empty($plugin_id)) {
265 // return plugin_id if create successfully
266 return $plugin_id;
267 } else {
268 return false;
271 } else {
272 if (!$silent) {
273 throw new repository_exception('existingrepository', 'repository');
275 // If plugin existed, return false, tell caller no new plugins were created.
276 return false;
282 * Update plugin options into the config_plugin table
284 * @param array $options
285 * @return bool
287 public function update_options($options = null) {
288 global $DB;
289 $classname = 'repository_' . $this->_typename;
290 $instanceoptions = repository::static_function($this->_typename, 'get_instance_option_names');
291 if (empty($instanceoptions)) {
292 // update repository instance name if this plugin type doesn't have muliti instances
293 $params = array();
294 $params['type'] = $this->_typename;
295 $instances = repository::get_instances($params);
296 $instance = array_pop($instances);
297 if ($instance) {
298 $DB->set_field('repository_instances', 'name', $options['pluginname'], array('id'=>$instance->id));
300 unset($options['pluginname']);
303 if (!empty($options)) {
304 $this->_options = $options;
307 foreach ($this->_options as $name => $value) {
308 set_config($name, $value, $this->_typename);
311 return true;
315 * Update visible database field with the value given as parameter
316 * or with the visible value of this object
317 * This function is private.
318 * For public access, have a look to switch_and_update_visibility()
320 * @param bool $visible
321 * @return bool
323 private function update_visible($visible = null) {
324 global $DB;
326 if (!empty($visible)) {
327 $this->_visible = $visible;
329 else if (!isset($this->_visible)) {
330 throw new repository_exception('updateemptyvisible', 'repository');
333 return $DB->set_field('repository', 'visible', $this->_visible, array('type'=>$this->_typename));
337 * Update database sortorder field with the value given as parameter
338 * or with the sortorder value of this object
339 * This function is private.
340 * For public access, have a look to move_order()
342 * @param int $sortorder
343 * @return bool
345 private function update_sortorder($sortorder = null) {
346 global $DB;
348 if (!empty($sortorder) && $sortorder!=0) {
349 $this->_sortorder = $sortorder;
351 //if sortorder is not set, we set it as the ;ast position in the list
352 else if (!isset($this->_sortorder) || $this->_sortorder == 0 ) {
353 $sql = "SELECT MAX(sortorder) FROM {repository}";
354 $this->_sortorder = 1 + $DB->get_field_sql($sql);
357 return $DB->set_field('repository', 'sortorder', $this->_sortorder, array('type'=>$this->_typename));
361 * Change order of the type with its adjacent upper or downer type
362 * (database fields are updated)
363 * Algorithm details:
364 * 1. retrieve all types in an array. This array is sorted by sortorder,
365 * and the array keys start from 0 to X (incremented by 1)
366 * 2. switch sortorder values of this type and its adjacent type
368 * @param string $move "up" or "down"
370 public function move_order($move) {
371 global $DB;
373 $types = repository::get_types(); // retrieve all types
375 // retrieve this type into the returned array
376 $i = 0;
377 while (!isset($indice) && $i<count($types)) {
378 if ($types[$i]->get_typename() == $this->_typename) {
379 $indice = $i;
381 $i++;
384 // retrieve adjacent indice
385 switch ($move) {
386 case "up":
387 $adjacentindice = $indice - 1;
388 break;
389 case "down":
390 $adjacentindice = $indice + 1;
391 break;
392 default:
393 throw new repository_exception('movenotdefined', 'repository');
396 //switch sortorder of this type and the adjacent type
397 //TODO: we could reset sortorder for all types. This is not as good in performance term, but
398 //that prevent from wrong behaviour on a screwed database. As performance are not important in this particular case
399 //it worth to change the algo.
400 if ($adjacentindice>=0 && !empty($types[$adjacentindice])) {
401 $DB->set_field('repository', 'sortorder', $this->_sortorder, array('type'=>$types[$adjacentindice]->get_typename()));
402 $this->update_sortorder($types[$adjacentindice]->get_sortorder());
407 * 1. Change visibility to the value chosen
408 * 2. Update the type
410 * @param bool $visible
411 * @return bool
413 public function update_visibility($visible = null) {
414 if (is_bool($visible)) {
415 $this->_visible = $visible;
416 } else {
417 $this->_visible = !$this->_visible;
419 return $this->update_visible();
424 * Delete a repository_type (general options are removed from config_plugin
425 * table, and all instances are deleted)
427 * @param bool $downloadcontents download external contents if exist
428 * @return bool
430 public function delete($downloadcontents = false) {
431 global $DB;
433 //delete all instances of this type
434 $params = array();
435 $params['context'] = array();
436 $params['onlyvisible'] = false;
437 $params['type'] = $this->_typename;
438 $instances = repository::get_instances($params);
439 foreach ($instances as $instance) {
440 $instance->delete($downloadcontents);
443 //delete all general options
444 foreach ($this->_options as $name => $value) {
445 set_config($name, null, $this->_typename);
448 try {
449 $DB->delete_records('repository', array('type' => $this->_typename));
450 } catch (dml_exception $ex) {
451 return false;
453 return true;
458 * This is the base class of the repository class.
460 * To create repository plugin, see: {@link http://docs.moodle.org/dev/Repository_plugins}
461 * See an example: {@link repository_boxnet}
463 * @package core_repository
464 * @copyright 2009 Dongsheng Cai {@link http://dongsheng.org}
465 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
467 abstract class repository {
468 /** Timeout in seconds for downloading the external file into moodle */
469 const GETFILE_TIMEOUT = 30;
470 /** Timeout in seconds for syncronising the external file size */
471 const SYNCFILE_TIMEOUT = 1;
472 /** Timeout in seconds for downloading an image file from external repository during syncronisation */
473 const SYNCIMAGE_TIMEOUT = 3;
475 // $disabled can be set to true to disable a plugin by force
476 // example: self::$disabled = true
477 /** @var bool force disable repository instance */
478 public $disabled = false;
479 /** @var int repository instance id */
480 public $id;
481 /** @var stdClass current context */
482 public $context;
483 /** @var array repository options */
484 public $options;
485 /** @var bool Whether or not the repository instance is editable */
486 public $readonly;
487 /** @var int return types */
488 public $returntypes;
489 /** @var stdClass repository instance database record */
490 public $instance;
491 /** @var string Type of repository (webdav, google_docs, dropbox, ...). */
492 public $type;
495 * Constructor
497 * @param int $repositoryid repository instance id
498 * @param int|stdClass $context a context id or context object
499 * @param array $options repository options
500 * @param int $readonly indicate this repo is readonly or not
502 public function __construct($repositoryid, $context = SYSCONTEXTID, $options = array(), $readonly = 0) {
503 global $DB;
504 $this->id = $repositoryid;
505 if (is_object($context)) {
506 $this->context = $context;
507 } else {
508 $this->context = context::instance_by_id($context);
510 $this->instance = $DB->get_record('repository_instances', array('id'=>$this->id));
511 $this->readonly = $readonly;
512 $this->options = array();
514 if (is_array($options)) {
515 // The get_option() method will get stored options in database.
516 $options = array_merge($this->get_option(), $options);
517 } else {
518 $options = $this->get_option();
520 foreach ($options as $n => $v) {
521 $this->options[$n] = $v;
523 $this->name = $this->get_name();
524 $this->returntypes = $this->supported_returntypes();
525 $this->super_called = true;
527 // Determining the type of repository if not set.
528 if (empty($this->type)) {
529 $matches = array();
530 if (!preg_match("/^repository_(.*)$/", get_class($this), $matches)) {
531 throw new coding_exception('The class name of a repository should be repository_<typeofrepository>, '.
532 'e.g. repository_dropbox');
534 $this->type = $matches[1];
539 * Get repository instance using repository id
541 * @param int $repositoryid repository ID
542 * @param stdClass|int $context context instance or context ID
543 * @param array $options additional repository options
544 * @return repository
546 public static function get_repository_by_id($repositoryid, $context, $options = array()) {
547 global $CFG, $DB;
549 $sql = 'SELECT i.name, i.typeid, r.type FROM {repository} r, {repository_instances} i WHERE i.id=? AND i.typeid=r.id';
551 if (!$record = $DB->get_record_sql($sql, array($repositoryid))) {
552 throw new repository_exception('invalidrepositoryid', 'repository');
553 } else {
554 $type = $record->type;
555 if (file_exists($CFG->dirroot . "/repository/$type/lib.php")) {
556 require_once($CFG->dirroot . "/repository/$type/lib.php");
557 $classname = 'repository_' . $type;
558 $contextid = $context;
559 if (is_object($context)) {
560 $contextid = $context->id;
562 $options['type'] = $type;
563 $options['typeid'] = $record->typeid;
564 if (empty($options['name'])) {
565 $options['name'] = $record->name;
567 $repository = new $classname($repositoryid, $contextid, $options);
568 return $repository;
569 } else {
570 throw new repository_exception('invalidplugin', 'repository');
576 * Get a repository type object by a given type name.
578 * @static
579 * @param string $typename the repository type name
580 * @return repository_type|bool
582 public static function get_type_by_typename($typename) {
583 global $DB;
585 if (!$record = $DB->get_record('repository',array('type' => $typename))) {
586 return false;
589 return new repository_type($typename, (array)get_config($typename), $record->visible, $record->sortorder);
593 * Get the repository type by a given repository type id.
595 * @static
596 * @param int $id the type id
597 * @return object
599 public static function get_type_by_id($id) {
600 global $DB;
602 if (!$record = $DB->get_record('repository',array('id' => $id))) {
603 return false;
606 return new repository_type($record->type, (array)get_config($record->type), $record->visible, $record->sortorder);
610 * Return all repository types ordered by sortorder field
611 * first repository type in returnedarray[0], second repository type in returnedarray[1], ...
613 * @static
614 * @param bool $visible can return types by visiblity, return all types if null
615 * @return array Repository types
617 public static function get_types($visible=null) {
618 global $DB, $CFG;
620 $types = array();
621 $params = null;
622 if (!empty($visible)) {
623 $params = array('visible' => $visible);
625 if ($records = $DB->get_records('repository',$params,'sortorder')) {
626 foreach($records as $type) {
627 if (file_exists($CFG->dirroot . '/repository/'. $type->type .'/lib.php')) {
628 $types[] = new repository_type($type->type, (array)get_config($type->type), $type->visible, $type->sortorder);
633 return $types;
637 * Checks if user has a capability to view the current repository.
639 * @return bool true when the user can, otherwise throws an exception.
640 * @throws repository_exception when the user does not meet the requirements.
642 public final function check_capability() {
643 global $USER;
645 // The context we are on.
646 $currentcontext = $this->context;
648 // Ensure that the user can view the repository in the current context.
649 $can = has_capability('repository/'.$this->type.':view', $currentcontext);
651 // Context in which the repository has been created.
652 $repocontext = context::instance_by_id($this->instance->contextid);
654 // Prevent access to private repositories when logged in as.
655 if (session_is_loggedinas()) {
656 $allowed = array('coursefiles', 'equella', 'filesystem', 'flickr_public', 'local', 'merlot', 'recent',
657 's3', 'upload', 'url', 'user', 'webdav', 'wikimedia', 'youtube');
658 // Are only accessible the repositories which do not contain private data (any data
659 // that is not part of Moodle, "Private files" is not considered "Pivate"). And if they
660 // do not contain private data, then it should not be a user instance, which is private by definition.
661 if (!in_array($this->type, $allowed) || $repocontext->contextlevel == CONTEXT_USER) {
662 $can = false;
666 // We are going to ensure that the current context was legit, and reliable to check
667 // the capability against. (No need to do that if we already cannot).
668 if ($can) {
669 if ($repocontext->contextlevel == CONTEXT_USER) {
670 // The repository is a user instance, ensure we're the right user to access it!
671 if ($repocontext->instanceid != $USER->id) {
672 $can = false;
674 } else if ($repocontext->contextlevel == CONTEXT_COURSE) {
675 // The repository is a course one. Let's check that we are on the right course.
676 if (in_array($currentcontext->contextlevel, array(CONTEXT_COURSE, CONTEXT_MODULE, CONTEXT_BLOCK))) {
677 $coursecontext = $currentcontext->get_course_context();
678 if ($coursecontext->instanceid != $repocontext->instanceid) {
679 $can = false;
681 } else {
682 // We are on a parent context, therefore it's legit to check the permissions
683 // in the current context.
685 } else {
686 // Nothing to check here, system instances can have different permissions on different
687 // levels. We do not want to prevent URL hack here, because it does not make sense to
688 // prevent a user to access a repository in a context if it's accessible in another one.
692 if ($can) {
693 return true;
696 throw new repository_exception('nopermissiontoaccess', 'repository');
700 * Check if file already exists in draft area
702 * @static
703 * @param int $itemid
704 * @param string $filepath
705 * @param string $filename
706 * @return bool
708 public static function draftfile_exists($itemid, $filepath, $filename) {
709 global $USER;
710 $fs = get_file_storage();
711 $usercontext = context_user::instance($USER->id);
712 if ($fs->get_file($usercontext->id, 'user', 'draft', $itemid, $filepath, $filename)) {
713 return true;
714 } else {
715 return false;
720 * Parses the 'source' returned by moodle repositories and returns an instance of stored_file
722 * @param string $source
723 * @return stored_file|null
725 public static function get_moodle_file($source) {
726 $params = file_storage::unpack_reference($source, true);
727 $fs = get_file_storage();
728 return $fs->get_file($params['contextid'], $params['component'], $params['filearea'],
729 $params['itemid'], $params['filepath'], $params['filename']);
733 * Repository method to make sure that user can access particular file.
735 * This is checked when user tries to pick the file from repository to deal with
736 * potential parameter substitutions is request
738 * @param string $source
739 * @return bool whether the file is accessible by current user
741 public function file_is_accessible($source) {
742 if ($this->has_moodle_files()) {
743 try {
744 $params = file_storage::unpack_reference($source, true);
745 } catch (file_reference_exception $e) {
746 return false;
748 $browser = get_file_browser();
749 $context = context::instance_by_id($params['contextid']);
750 $file_info = $browser->get_file_info($context, $params['component'], $params['filearea'],
751 $params['itemid'], $params['filepath'], $params['filename']);
752 return !empty($file_info);
754 return true;
758 * This function is used to copy a moodle file to draft area.
760 * It DOES NOT check if the user is allowed to access this file because the actual file
761 * can be located in the area where user does not have access to but there is an alias
762 * to this file in the area where user CAN access it.
763 * {@link file_is_accessible} should be called for alias location before calling this function.
765 * @param string $source The metainfo of file, it is base64 encoded php serialized data
766 * @param stdClass|array $filerecord contains itemid, filepath, filename and optionally other
767 * attributes of the new file
768 * @param int $maxbytes maximum allowed size of file, -1 if unlimited. If size of file exceeds
769 * the limit, the file_exception is thrown.
770 * @param int $areamaxbytes the maximum size of the area. A file_exception is thrown if the
771 * new file will reach the limit.
772 * @return array The information about the created file
774 public function copy_to_area($source, $filerecord, $maxbytes = -1, $areamaxbytes = FILE_AREA_MAX_BYTES_UNLIMITED) {
775 global $USER;
776 $fs = get_file_storage();
778 if ($this->has_moodle_files() == false) {
779 throw new coding_exception('Only repository used to browse moodle files can use repository::copy_to_area()');
782 $user_context = context_user::instance($USER->id);
784 $filerecord = (array)$filerecord;
785 // make sure the new file will be created in user draft area
786 $filerecord['component'] = 'user';
787 $filerecord['filearea'] = 'draft';
788 $filerecord['contextid'] = $user_context->id;
789 $draftitemid = $filerecord['itemid'];
790 $new_filepath = $filerecord['filepath'];
791 $new_filename = $filerecord['filename'];
793 // the file needs to copied to draft area
794 $stored_file = self::get_moodle_file($source);
795 if ($maxbytes != -1 && $stored_file->get_filesize() > $maxbytes) {
796 throw new file_exception('maxbytes');
798 // Validate the size of the draft area.
799 if (file_is_draft_area_limit_reached($draftitemid, $areamaxbytes, $stored_file->get_filesize())) {
800 throw new file_exception('maxareabytes');
803 if (repository::draftfile_exists($draftitemid, $new_filepath, $new_filename)) {
804 // create new file
805 $unused_filename = repository::get_unused_filename($draftitemid, $new_filepath, $new_filename);
806 $filerecord['filename'] = $unused_filename;
807 $fs->create_file_from_storedfile($filerecord, $stored_file);
808 $event = array();
809 $event['event'] = 'fileexists';
810 $event['newfile'] = new stdClass;
811 $event['newfile']->filepath = $new_filepath;
812 $event['newfile']->filename = $unused_filename;
813 $event['newfile']->url = moodle_url::make_draftfile_url($draftitemid, $new_filepath, $unused_filename)->out();
814 $event['existingfile'] = new stdClass;
815 $event['existingfile']->filepath = $new_filepath;
816 $event['existingfile']->filename = $new_filename;
817 $event['existingfile']->url = moodle_url::make_draftfile_url($draftitemid, $new_filepath, $new_filename)->out();
818 return $event;
819 } else {
820 $fs->create_file_from_storedfile($filerecord, $stored_file);
821 $info = array();
822 $info['itemid'] = $draftitemid;
823 $info['file'] = $new_filename;
824 $info['title'] = $new_filename;
825 $info['contextid'] = $user_context->id;
826 $info['url'] = moodle_url::make_draftfile_url($draftitemid, $new_filepath, $new_filename)->out();
827 $info['filesize'] = $stored_file->get_filesize();
828 return $info;
833 * Get unused filename by appending suffix
835 * @static
836 * @param int $itemid
837 * @param string $filepath
838 * @param string $filename
839 * @return string
841 public static function get_unused_filename($itemid, $filepath, $filename) {
842 global $USER;
843 $fs = get_file_storage();
844 while (repository::draftfile_exists($itemid, $filepath, $filename)) {
845 $filename = repository::append_suffix($filename);
847 return $filename;
851 * Append a suffix to filename
853 * @static
854 * @param string $filename
855 * @return string
857 public static function append_suffix($filename) {
858 $pathinfo = pathinfo($filename);
859 if (empty($pathinfo['extension'])) {
860 return $filename . RENAME_SUFFIX;
861 } else {
862 return $pathinfo['filename'] . RENAME_SUFFIX . '.' . $pathinfo['extension'];
867 * Return all types that you a user can create/edit and which are also visible
868 * Note: Mostly used in order to know if at least one editable type can be set
870 * @static
871 * @param stdClass $context the context for which we want the editable types
872 * @return array types
874 public static function get_editable_types($context = null) {
876 if (empty($context)) {
877 $context = get_system_context();
880 $types= repository::get_types(true);
881 $editabletypes = array();
882 foreach ($types as $type) {
883 $instanceoptionnames = repository::static_function($type->get_typename(), 'get_instance_option_names');
884 if (!empty($instanceoptionnames)) {
885 if ($type->get_contextvisibility($context)) {
886 $editabletypes[]=$type;
890 return $editabletypes;
894 * Return repository instances
896 * @static
897 * @param array $args Array containing the following keys:
898 * currentcontext
899 * context
900 * onlyvisible
901 * type
902 * accepted_types
903 * return_types
904 * userid
906 * @return array repository instances
908 public static function get_instances($args = array()) {
909 global $DB, $CFG, $USER;
911 if (isset($args['currentcontext'])) {
912 $current_context = $args['currentcontext'];
913 } else {
914 $current_context = null;
917 if (!empty($args['context'])) {
918 $contexts = $args['context'];
919 } else {
920 $contexts = array();
923 $onlyvisible = isset($args['onlyvisible']) ? $args['onlyvisible'] : true;
924 $returntypes = isset($args['return_types']) ? $args['return_types'] : 3;
925 $type = isset($args['type']) ? $args['type'] : null;
927 $params = array();
928 $sql = "SELECT i.*, r.type AS repositorytype, r.sortorder, r.visible
929 FROM {repository} r, {repository_instances} i
930 WHERE i.typeid = r.id ";
932 if (!empty($args['disable_types']) && is_array($args['disable_types'])) {
933 list($types, $p) = $DB->get_in_or_equal($args['disable_types'], SQL_PARAMS_QM, 'param', false);
934 $sql .= " AND r.type $types";
935 $params = array_merge($params, $p);
938 if (!empty($args['userid']) && is_numeric($args['userid'])) {
939 $sql .= " AND (i.userid = 0 or i.userid = ?)";
940 $params[] = $args['userid'];
943 foreach ($contexts as $context) {
944 if (empty($firstcontext)) {
945 $firstcontext = true;
946 $sql .= " AND ((i.contextid = ?)";
947 } else {
948 $sql .= " OR (i.contextid = ?)";
950 $params[] = $context->id;
953 if (!empty($firstcontext)) {
954 $sql .=')';
957 if ($onlyvisible == true) {
958 $sql .= " AND (r.visible = 1)";
961 if (isset($type)) {
962 $sql .= " AND (r.type = ?)";
963 $params[] = $type;
965 $sql .= " ORDER BY r.sortorder, i.name";
967 if (!$records = $DB->get_records_sql($sql, $params)) {
968 $records = array();
971 $repositories = array();
972 if (isset($args['accepted_types'])) {
973 $accepted_types = $args['accepted_types'];
974 if (is_array($accepted_types) && in_array('*', $accepted_types)) {
975 $accepted_types = '*';
977 } else {
978 $accepted_types = '*';
980 // Sortorder should be unique, which is not true if we use $record->sortorder
981 // and there are multiple instances of any repository type
982 $sortorder = 1;
983 foreach ($records as $record) {
984 if (!file_exists($CFG->dirroot . '/repository/'. $record->repositorytype.'/lib.php')) {
985 continue;
987 require_once($CFG->dirroot . '/repository/'. $record->repositorytype.'/lib.php');
988 $options['visible'] = $record->visible;
989 $options['type'] = $record->repositorytype;
990 $options['typeid'] = $record->typeid;
991 $options['sortorder'] = $sortorder++;
992 // tell instance what file types will be accepted by file picker
993 $classname = 'repository_' . $record->repositorytype;
995 $repository = new $classname($record->id, $record->contextid, $options, $record->readonly);
997 $is_supported = true;
999 if (empty($repository->super_called)) {
1000 // to make sure the super construct is called
1001 debugging('parent::__construct must be called by '.$record->repositorytype.' plugin.');
1002 } else {
1003 // check mimetypes
1004 if ($accepted_types !== '*' and $repository->supported_filetypes() !== '*') {
1005 $accepted_ext = file_get_typegroup('extension', $accepted_types);
1006 $supported_ext = file_get_typegroup('extension', $repository->supported_filetypes());
1007 $valid_ext = array_intersect($accepted_ext, $supported_ext);
1008 $is_supported = !empty($valid_ext);
1010 // check return values
1011 if ($returntypes !== 3 and $repository->supported_returntypes() !== 3) {
1012 $type = $repository->supported_returntypes();
1013 if ($type & $returntypes) {
1015 } else {
1016 $is_supported = false;
1020 if (!$onlyvisible || ($repository->is_visible() && !$repository->disabled)) {
1021 // check capability in current context
1022 if (!empty($current_context)) {
1023 $capability = has_capability('repository/'.$record->repositorytype.':view', $current_context);
1024 } else {
1025 $capability = has_capability('repository/'.$record->repositorytype.':view', get_system_context());
1027 if ($record->repositorytype == 'coursefiles') {
1028 // coursefiles plugin needs managefiles permission
1029 if (!empty($current_context)) {
1030 $capability = $capability && has_capability('moodle/course:managefiles', $current_context);
1031 } else {
1032 $capability = $capability && has_capability('moodle/course:managefiles', get_system_context());
1035 if ($is_supported && $capability) {
1036 $repositories[$repository->id] = $repository;
1041 return $repositories;
1045 * Get single repository instance
1047 * @static
1048 * @param integer $id repository id
1049 * @return object repository instance
1051 public static function get_instance($id) {
1052 global $DB, $CFG;
1053 $sql = "SELECT i.*, r.type AS repositorytype, r.visible
1054 FROM {repository} r
1055 JOIN {repository_instances} i ON i.typeid = r.id
1056 WHERE i.id = ?";
1058 if (!$instance = $DB->get_record_sql($sql, array($id))) {
1059 return false;
1061 require_once($CFG->dirroot . '/repository/'. $instance->repositorytype.'/lib.php');
1062 $classname = 'repository_' . $instance->repositorytype;
1063 $options['typeid'] = $instance->typeid;
1064 $options['type'] = $instance->repositorytype;
1065 $options['name'] = $instance->name;
1066 $obj = new $classname($instance->id, $instance->contextid, $options, $instance->readonly);
1067 if (empty($obj->super_called)) {
1068 debugging('parent::__construct must be called by '.$classname.' plugin.');
1070 return $obj;
1074 * Call a static function. Any additional arguments than plugin and function will be passed through.
1076 * @static
1077 * @param string $plugin repository plugin name
1078 * @param string $function function name
1079 * @return mixed
1081 public static function static_function($plugin, $function) {
1082 global $CFG;
1084 //check that the plugin exists
1085 $typedirectory = $CFG->dirroot . '/repository/'. $plugin . '/lib.php';
1086 if (!file_exists($typedirectory)) {
1087 //throw new repository_exception('invalidplugin', 'repository');
1088 return false;
1091 $args = func_get_args();
1092 if (count($args) <= 2) {
1093 $args = array();
1094 } else {
1095 array_shift($args);
1096 array_shift($args);
1099 require_once($typedirectory);
1100 return call_user_func_array(array('repository_' . $plugin, $function), $args);
1104 * Scan file, throws exception in case of infected file.
1106 * Please note that the scanning engine must be able to access the file,
1107 * permissions of the file are not modified here!
1109 * @static
1110 * @param string $thefile
1111 * @param string $filename name of the file
1112 * @param bool $deleteinfected
1114 public static function antivir_scan_file($thefile, $filename, $deleteinfected) {
1115 global $CFG;
1117 if (!is_readable($thefile)) {
1118 // this should not happen
1119 return;
1122 if (empty($CFG->runclamonupload) or empty($CFG->pathtoclam)) {
1123 // clam not enabled
1124 return;
1127 $CFG->pathtoclam = trim($CFG->pathtoclam);
1129 if (!file_exists($CFG->pathtoclam) or !is_executable($CFG->pathtoclam)) {
1130 // misconfigured clam - use the old notification for now
1131 require("$CFG->libdir/uploadlib.php");
1132 $notice = get_string('clamlost', 'moodle', $CFG->pathtoclam);
1133 clam_message_admins($notice);
1134 return;
1137 $clamparam = ' --stdout ';
1138 // If we are dealing with clamdscan, clamd is likely run as a different user
1139 // that might not have permissions to access your file.
1140 // To make clamdscan work, we use --fdpass parameter that passes the file
1141 // descriptor permissions to clamd, which allows it to scan given file
1142 // irrespective of directory and file permissions.
1143 if (basename($CFG->pathtoclam) == 'clamdscan') {
1144 $clamparam .= '--fdpass ';
1146 // execute test
1147 $cmd = escapeshellcmd($CFG->pathtoclam).$clamparam.escapeshellarg($thefile);
1148 exec($cmd, $output, $return);
1150 if ($return == 0) {
1151 // perfect, no problem found
1152 return;
1154 } else if ($return == 1) {
1155 // infection found
1156 if ($deleteinfected) {
1157 unlink($thefile);
1159 throw new moodle_exception('virusfounduser', 'moodle', '', array('filename'=>$filename));
1161 } else {
1162 //unknown problem
1163 require("$CFG->libdir/uploadlib.php");
1164 $notice = get_string('clamfailed', 'moodle', get_clam_error_code($return));
1165 $notice .= "\n\n". implode("\n", $output);
1166 clam_message_admins($notice);
1167 if ($CFG->clamfailureonupload === 'actlikevirus') {
1168 if ($deleteinfected) {
1169 unlink($thefile);
1171 throw new moodle_exception('virusfounduser', 'moodle', '', array('filename'=>$filename));
1172 } else {
1173 return;
1179 * Repository method to serve the referenced file
1181 * @see send_stored_file
1183 * @param stored_file $storedfile the file that contains the reference
1184 * @param int $lifetime Number of seconds before the file should expire from caches (default 24 hours)
1185 * @param int $filter 0 (default)=no filtering, 1=all files, 2=html files only
1186 * @param bool $forcedownload If true (default false), forces download of file rather than view in browser/plugin
1187 * @param array $options additional options affecting the file serving
1189 public function send_file($storedfile, $lifetime=86400 , $filter=0, $forcedownload=false, array $options = null) {
1190 if ($this->has_moodle_files()) {
1191 $fs = get_file_storage();
1192 $params = file_storage::unpack_reference($storedfile->get_reference(), true);
1193 $srcfile = null;
1194 if (is_array($params)) {
1195 $srcfile = $fs->get_file($params['contextid'], $params['component'], $params['filearea'],
1196 $params['itemid'], $params['filepath'], $params['filename']);
1198 if (empty($options)) {
1199 $options = array();
1201 if (!isset($options['filename'])) {
1202 $options['filename'] = $storedfile->get_filename();
1204 if (!$srcfile) {
1205 send_file_not_found();
1206 } else {
1207 send_stored_file($srcfile, $lifetime, $filter, $forcedownload, $options);
1209 } else {
1210 throw new coding_exception("Repository plugin must implement send_file() method.");
1215 * Return reference file life time
1217 * @param string $ref
1218 * @return int
1220 public function get_reference_file_lifetime($ref) {
1221 // One day
1222 return 60 * 60 * 24;
1226 * Decide whether or not the file should be synced
1228 * @param stored_file $storedfile
1229 * @return bool
1231 public function sync_individual_file(stored_file $storedfile) {
1232 return true;
1236 * Return human readable reference information
1238 * @param string $reference value of DB field files_reference.reference
1239 * @param int $filestatus status of the file, 0 - ok, 666 - source missing
1240 * @return string
1242 public function get_reference_details($reference, $filestatus = 0) {
1243 if ($this->has_moodle_files()) {
1244 $fileinfo = null;
1245 $params = file_storage::unpack_reference($reference, true);
1246 if (is_array($params)) {
1247 $context = context::instance_by_id($params['contextid'], IGNORE_MISSING);
1248 if ($context) {
1249 $browser = get_file_browser();
1250 $fileinfo = $browser->get_file_info($context, $params['component'], $params['filearea'], $params['itemid'], $params['filepath'], $params['filename']);
1253 if (empty($fileinfo)) {
1254 if ($filestatus == 666) {
1255 if (is_siteadmin() || ($context && has_capability('moodle/course:managefiles', $context))) {
1256 return get_string('lostsource', 'repository',
1257 $params['contextid']. '/'. $params['component']. '/'. $params['filearea']. '/'. $params['itemid']. $params['filepath']. $params['filename']);
1258 } else {
1259 return get_string('lostsource', 'repository', '');
1262 return get_string('undisclosedsource', 'repository');
1263 } else {
1264 return $fileinfo->get_readable_fullname();
1267 return '';
1271 * Cache file from external repository by reference
1272 * {@link repository::get_file_reference()}
1273 * {@link repository::get_file()}
1274 * Invoked at MOODLE/repository/repository_ajax.php
1276 * @param string $reference this reference is generated by
1277 * repository::get_file_reference()
1278 * @param stored_file $storedfile created file reference
1280 public function cache_file_by_reference($reference, $storedfile) {
1284 * Returns information about file in this repository by reference
1286 * This function must be implemented for repositories supporting FILE_REFERENCE, it is called
1287 * for existing aliases when the lifetime of the previous syncronisation has expired.
1289 * Returns null if file not found or is not readable or timeout occured during request.
1290 * Note that this function may be run for EACH file that needs to be synchronised at the
1291 * moment. If anything is being downloaded or requested from external sources there
1292 * should be a small timeout. The synchronisation is performed to update the size of
1293 * the file and/or to update image and re-generated image preview. There is nothing
1294 * fatal if syncronisation fails but it is fatal if syncronisation takes too long
1295 * and hangs the script generating a page.
1297 * If get_file_by_reference() returns filesize just the record in {files} table is being updated.
1298 * If filepath, handle or content are returned - the file is also stored in moodle filepool
1299 * (recommended for images to generate the thumbnails). For non-image files it is not
1300 * recommended to download them to moodle during syncronisation since it may take
1301 * unnecessary long time.
1303 * @param stdClass $reference record from DB table {files_reference}
1304 * @return stdClass|null contains one of the following:
1305 * - 'filesize' and optionally 'contenthash'
1306 * - 'filepath'
1307 * - 'handle'
1308 * - 'content'
1310 public function get_file_by_reference($reference) {
1311 if ($this->has_moodle_files() && isset($reference->reference)) {
1312 $fs = get_file_storage();
1313 $params = file_storage::unpack_reference($reference->reference, true);
1314 if (!is_array($params) || !($storedfile = $fs->get_file($params['contextid'],
1315 $params['component'], $params['filearea'], $params['itemid'], $params['filepath'],
1316 $params['filename']))) {
1317 return null;
1319 return (object)array(
1320 'contenthash' => $storedfile->get_contenthash(),
1321 'filesize' => $storedfile->get_filesize()
1324 return null;
1328 * Return the source information
1330 * The result of the function is stored in files.source field. It may be analysed
1331 * when the source file is lost or repository may use it to display human-readable
1332 * location of reference original.
1334 * This method is called when file is picked for the first time only. When file
1335 * (either copy or a reference) is already in moodle and it is being picked
1336 * again to another file area (also as a copy or as a reference), the value of
1337 * files.source is copied.
1339 * @param string $source the value that repository returned in listing as 'source'
1340 * @return string|null
1342 public function get_file_source_info($source) {
1343 if ($this->has_moodle_files()) {
1344 return $this->get_reference_details($source, 0);
1346 return $source;
1350 * Move file from download folder to file pool using FILE API
1352 * @todo MDL-28637
1353 * @static
1354 * @param string $thefile file path in download folder
1355 * @param stdClass $record
1356 * @return array containing the following keys:
1357 * icon
1358 * file
1359 * id
1360 * url
1362 public static function move_to_filepool($thefile, $record) {
1363 global $DB, $CFG, $USER, $OUTPUT;
1365 // scan for viruses if possible, throws exception if problem found
1366 self::antivir_scan_file($thefile, $record->filename, empty($CFG->repository_no_delete)); //TODO: MDL-28637 this repository_no_delete is a bloody hack!
1368 $fs = get_file_storage();
1369 // If file name being used.
1370 if (repository::draftfile_exists($record->itemid, $record->filepath, $record->filename)) {
1371 $draftitemid = $record->itemid;
1372 $new_filename = repository::get_unused_filename($draftitemid, $record->filepath, $record->filename);
1373 $old_filename = $record->filename;
1374 // Create a tmp file.
1375 $record->filename = $new_filename;
1376 $newfile = $fs->create_file_from_pathname($record, $thefile);
1377 $event = array();
1378 $event['event'] = 'fileexists';
1379 $event['newfile'] = new stdClass;
1380 $event['newfile']->filepath = $record->filepath;
1381 $event['newfile']->filename = $new_filename;
1382 $event['newfile']->url = moodle_url::make_draftfile_url($draftitemid, $record->filepath, $new_filename)->out();
1384 $event['existingfile'] = new stdClass;
1385 $event['existingfile']->filepath = $record->filepath;
1386 $event['existingfile']->filename = $old_filename;
1387 $event['existingfile']->url = moodle_url::make_draftfile_url($draftitemid, $record->filepath, $old_filename)->out();;
1388 return $event;
1390 if ($file = $fs->create_file_from_pathname($record, $thefile)) {
1391 if (empty($CFG->repository_no_delete)) {
1392 $delete = unlink($thefile);
1393 unset($CFG->repository_no_delete);
1395 return array(
1396 'url'=>moodle_url::make_draftfile_url($file->get_itemid(), $file->get_filepath(), $file->get_filename())->out(),
1397 'id'=>$file->get_itemid(),
1398 'file'=>$file->get_filename(),
1399 'icon' => $OUTPUT->pix_url(file_extension_icon($thefile, 32))->out(),
1401 } else {
1402 return null;
1407 * Builds a tree of files This function is then called recursively.
1409 * @static
1410 * @todo take $search into account, and respect a threshold for dynamic loading
1411 * @param file_info $fileinfo an object returned by file_browser::get_file_info()
1412 * @param string $search searched string
1413 * @param bool $dynamicmode no recursive call is done when in dynamic mode
1414 * @param array $list the array containing the files under the passed $fileinfo
1415 * @return int the number of files found
1417 public static function build_tree($fileinfo, $search, $dynamicmode, &$list) {
1418 global $CFG, $OUTPUT;
1420 $filecount = 0;
1421 $children = $fileinfo->get_children();
1423 foreach ($children as $child) {
1424 $filename = $child->get_visible_name();
1425 $filesize = $child->get_filesize();
1426 $filesize = $filesize ? display_size($filesize) : '';
1427 $filedate = $child->get_timemodified();
1428 $filedate = $filedate ? userdate($filedate) : '';
1429 $filetype = $child->get_mimetype();
1431 if ($child->is_directory()) {
1432 $path = array();
1433 $level = $child->get_parent();
1434 while ($level) {
1435 $params = $level->get_params();
1436 $path[] = array($params['filepath'], $level->get_visible_name());
1437 $level = $level->get_parent();
1440 $tmp = array(
1441 'title' => $child->get_visible_name(),
1442 'size' => 0,
1443 'date' => $filedate,
1444 'path' => array_reverse($path),
1445 'thumbnail' => $OUTPUT->pix_url(file_folder_icon(90))->out(false)
1448 //if ($dynamicmode && $child->is_writable()) {
1449 // $tmp['children'] = array();
1450 //} else {
1451 // if folder name matches search, we send back all files contained.
1452 $_search = $search;
1453 if ($search && stristr($tmp['title'], $search) !== false) {
1454 $_search = false;
1456 $tmp['children'] = array();
1457 $_filecount = repository::build_tree($child, $_search, $dynamicmode, $tmp['children']);
1458 if ($search && $_filecount) {
1459 $tmp['expanded'] = 1;
1464 if (!$search || $_filecount || (stristr($tmp['title'], $search) !== false)) {
1465 $filecount += $_filecount;
1466 $list[] = $tmp;
1469 } else { // not a directory
1470 // skip the file, if we're in search mode and it's not a match
1471 if ($search && (stristr($filename, $search) === false)) {
1472 continue;
1474 $params = $child->get_params();
1475 $source = serialize(array($params['contextid'], $params['component'], $params['filearea'], $params['itemid'], $params['filepath'], $params['filename']));
1476 $list[] = array(
1477 'title' => $filename,
1478 'size' => $filesize,
1479 'date' => $filedate,
1480 //'source' => $child->get_url(),
1481 'source' => base64_encode($source),
1482 'icon'=>$OUTPUT->pix_url(file_file_icon($child, 24))->out(false),
1483 'thumbnail'=>$OUTPUT->pix_url(file_file_icon($child, 90))->out(false),
1485 $filecount++;
1489 return $filecount;
1493 * Display a repository instance list (with edit/delete/create links)
1495 * @static
1496 * @param stdClass $context the context for which we display the instance
1497 * @param string $typename if set, we display only one type of instance
1499 public static function display_instances_list($context, $typename = null) {
1500 global $CFG, $USER, $OUTPUT;
1502 $output = $OUTPUT->box_start('generalbox');
1503 //if the context is SYSTEM, so we call it from administration page
1504 $admin = ($context->id == SYSCONTEXTID) ? true : false;
1505 if ($admin) {
1506 $baseurl = new moodle_url('/'.$CFG->admin.'/repositoryinstance.php', array('sesskey'=>sesskey()));
1507 $output .= $OUTPUT->heading(get_string('siteinstances', 'repository'));
1508 } else {
1509 $baseurl = new moodle_url('/repository/manage_instances.php', array('contextid'=>$context->id, 'sesskey'=>sesskey()));
1512 $namestr = get_string('name');
1513 $pluginstr = get_string('plugin', 'repository');
1514 $settingsstr = get_string('settings');
1515 $deletestr = get_string('delete');
1516 //retrieve list of instances. In administration context we want to display all
1517 //instances of a type, even if this type is not visible. In course/user context we
1518 //want to display only visible instances, but for every type types. The repository::get_instances()
1519 //third parameter displays only visible type.
1520 $params = array();
1521 $params['context'] = array($context);
1522 $params['currentcontext'] = $context;
1523 $params['onlyvisible'] = !$admin;
1524 $params['type'] = $typename;
1525 $instances = repository::get_instances($params);
1526 $instancesnumber = count($instances);
1527 $alreadyplugins = array();
1529 $table = new html_table();
1530 $table->head = array($namestr, $pluginstr, $settingsstr, $deletestr);
1531 $table->align = array('left', 'left', 'center','center');
1532 $table->data = array();
1534 $updowncount = 1;
1536 foreach ($instances as $i) {
1537 $settings = '';
1538 $delete = '';
1540 $type = repository::get_type_by_id($i->options['typeid']);
1542 if ($type->get_contextvisibility($context)) {
1543 if (!$i->readonly) {
1545 $settingurl = new moodle_url($baseurl);
1546 $settingurl->param('type', $i->options['type']);
1547 $settingurl->param('edit', $i->id);
1548 $settings .= html_writer::link($settingurl, $settingsstr);
1550 $deleteurl = new moodle_url($baseurl);
1551 $deleteurl->param('delete', $i->id);
1552 $deleteurl->param('type', $i->options['type']);
1553 $delete .= html_writer::link($deleteurl, $deletestr);
1557 $type = repository::get_type_by_id($i->options['typeid']);
1558 $table->data[] = array(format_string($i->name), $type->get_readablename(), $settings, $delete);
1560 //display a grey row if the type is defined as not visible
1561 if (isset($type) && !$type->get_visible()) {
1562 $table->rowclasses[] = 'dimmed_text';
1563 } else {
1564 $table->rowclasses[] = '';
1567 if (!in_array($i->name, $alreadyplugins)) {
1568 $alreadyplugins[] = $i->name;
1571 $output .= html_writer::table($table);
1572 $instancehtml = '<div>';
1573 $addable = 0;
1575 //if no type is set, we can create all type of instance
1576 if (!$typename) {
1577 $instancehtml .= '<h3>';
1578 $instancehtml .= get_string('createrepository', 'repository');
1579 $instancehtml .= '</h3><ul>';
1580 $types = repository::get_editable_types($context);
1581 foreach ($types as $type) {
1582 if (!empty($type) && $type->get_visible()) {
1583 // If the user does not have the permission to view the repository, it won't be displayed in
1584 // the list of instances. Hiding the link to create new instances will prevent the
1585 // user from creating them without being able to find them afterwards, which looks like a bug.
1586 if (!has_capability('repository/'.$type->get_typename().':view', $context)) {
1587 continue;
1589 $instanceoptionnames = repository::static_function($type->get_typename(), 'get_instance_option_names');
1590 if (!empty($instanceoptionnames)) {
1591 $baseurl->param('new', $type->get_typename());
1592 $instancehtml .= '<li><a href="'.$baseurl->out().'">'.get_string('createxxinstance', 'repository', get_string('pluginname', 'repository_'.$type->get_typename())). '</a></li>';
1593 $baseurl->remove_params('new');
1594 $addable++;
1598 $instancehtml .= '</ul>';
1600 } else {
1601 $instanceoptionnames = repository::static_function($typename, 'get_instance_option_names');
1602 if (!empty($instanceoptionnames)) { //create a unique type of instance
1603 $addable = 1;
1604 $baseurl->param('new', $typename);
1605 $output .= $OUTPUT->single_button($baseurl, get_string('createinstance', 'repository'), 'get');
1606 $baseurl->remove_params('new');
1610 if ($addable) {
1611 $instancehtml .= '</div>';
1612 $output .= $instancehtml;
1615 $output .= $OUTPUT->box_end();
1617 //print the list + creation links
1618 print($output);
1622 * Prepare file reference information
1624 * @param string $source
1625 * @return string file referece
1627 public function get_file_reference($source) {
1628 if ($this->has_moodle_files() && ($this->supported_returntypes() & FILE_REFERENCE)) {
1629 $params = file_storage::unpack_reference($source);
1630 if (!is_array($params)) {
1631 throw new repository_exception('invalidparams', 'repository');
1633 return file_storage::pack_reference($params);
1635 return $source;
1639 * Decide where to save the file, can be overwriten by subclass
1641 * @param string $filename file name
1642 * @return file path
1644 public function prepare_file($filename) {
1645 global $CFG;
1646 $dir = make_temp_directory('download/'.get_class($this).'/');
1647 while (empty($filename) || file_exists($dir.$filename)) {
1648 $filename = uniqid('', true).'_'.time().'.tmp';
1650 return $dir.$filename;
1654 * Does this repository used to browse moodle files?
1656 * @return bool
1658 public function has_moodle_files() {
1659 return false;
1663 * Return file URL, for most plugins, the parameter is the original
1664 * url, but some plugins use a file id, so we need this function to
1665 * convert file id to original url.
1667 * @param string $url the url of file
1668 * @return string
1670 public function get_link($url) {
1671 return $url;
1675 * Downloads a file from external repository and saves it in temp dir
1677 * Function get_file() must be implemented by repositories that support returntypes
1678 * FILE_INTERNAL or FILE_REFERENCE. It is invoked to pick up the file and copy it
1679 * to moodle. This function is not called for moodle repositories, the function
1680 * {@link repository::copy_to_area()} is used instead.
1682 * This function can be overridden by subclass if the files.reference field contains
1683 * not just URL or if request should be done differently.
1685 * @see curl
1686 * @throws file_exception when error occured
1688 * @param string $url the content of files.reference field, in this implementaion
1689 * it is asssumed that it contains the string with URL of the file
1690 * @param string $filename filename (without path) to save the downloaded file in the
1691 * temporary directory, if omitted or file already exists the new filename will be generated
1692 * @return array with elements:
1693 * path: internal location of the file
1694 * url: URL to the source (from parameters)
1696 public function get_file($url, $filename = '') {
1697 $path = $this->prepare_file($filename);
1698 $c = new curl;
1699 $result = $c->download_one($url, null, array('filepath' => $path, 'timeout' => self::GETFILE_TIMEOUT));
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_external_file()} 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
1722 return;
1723 } else if ($file->get_repository_id() != $this->id) {
1724 // error
1725 debugging('Repository instance id does not match');
1726 return;
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 throw new file_exception('maxbytes');
1733 return;
1734 } else {
1735 if ($maxbytes > 0 && $file->get_filesize() > $maxbytes) {
1736 // note that stored_file::get_filesize() also calls synchronisation
1737 throw new file_exception('maxbytes');
1739 $fs = get_file_storage();
1740 $contentexists = $fs->content_exists($file->get_contenthash());
1741 if ($contentexists && $file->get_filesize() && $file->get_contenthash() === sha1('')) {
1742 // even when 'file_storage::content_exists()' returns true this may be an empty
1743 // content for the file that was not actually downloaded
1744 $contentexists = false;
1746 $now = time();
1747 if ($file->get_referencelastsync() + $file->get_referencelifetime() >= $now &&
1748 !$file->get_status() &&
1749 $contentexists) {
1750 // we already have the content in moodle filepool and it was synchronised recently.
1751 // Repositories may overwrite it if they want to force synchronisation anyway!
1752 return;
1753 } else {
1754 // attempt to get a file
1755 try {
1756 $fileinfo = $this->get_file($file->get_reference());
1757 if (isset($fileinfo['path'])) {
1758 list($contenthash, $filesize, $newfile) = $fs->add_file_to_pool($fileinfo['path']);
1759 // set this file and other similar aliases synchronised
1760 $lifetime = $this->get_reference_file_lifetime($file->get_reference());
1761 $file->set_synchronized($contenthash, $filesize, 0, $lifetime);
1762 } else {
1763 throw new moodle_exception('errorwhiledownload', 'repository', '', '');
1765 } catch (Exception $e) {
1766 if ($contentexists) {
1767 // better something than nothing. We have a copy of file. It's sync time
1768 // has expired but it is still very likely that it is the last version
1769 } else {
1770 throw($e);
1778 * Return size of a file in bytes.
1780 * @param string $source encoded and serialized data of file
1781 * @return int file size in bytes
1783 public function get_file_size($source) {
1784 // TODO MDL-33297 remove this function completely?
1785 $browser = get_file_browser();
1786 $params = unserialize(base64_decode($source));
1787 $contextid = clean_param($params['contextid'], PARAM_INT);
1788 $fileitemid = clean_param($params['itemid'], PARAM_INT);
1789 $filename = clean_param($params['filename'], PARAM_FILE);
1790 $filepath = clean_param($params['filepath'], PARAM_PATH);
1791 $filearea = clean_param($params['filearea'], PARAM_AREA);
1792 $component = clean_param($params['component'], PARAM_COMPONENT);
1793 $context = context::instance_by_id($contextid);
1794 $file_info = $browser->get_file_info($context, $component, $filearea, $fileitemid, $filepath, $filename);
1795 if (!empty($file_info)) {
1796 $filesize = $file_info->get_filesize();
1797 } else {
1798 $filesize = null;
1800 return $filesize;
1804 * Return is the instance is visible
1805 * (is the type visible ? is the context enable ?)
1807 * @return bool
1809 public function is_visible() {
1810 $type = repository::get_type_by_id($this->options['typeid']);
1811 $instanceoptions = repository::static_function($type->get_typename(), 'get_instance_option_names');
1813 if ($type->get_visible()) {
1814 //if the instance is unique so it's visible, otherwise check if the instance has a enabled context
1815 if (empty($instanceoptions) || $type->get_contextvisibility($this->context)) {
1816 return true;
1820 return false;
1824 * Return the name of this instance, can be overridden.
1826 * @return string
1828 public function get_name() {
1829 global $DB;
1830 if ( $name = $this->instance->name ) {
1831 return $name;
1832 } else {
1833 return get_string('pluginname', 'repository_' . $this->options['type']);
1838 * What kind of files will be in this repository?
1840 * @return array return '*' means this repository support any files, otherwise
1841 * return mimetypes of files, it can be an array
1843 public function supported_filetypes() {
1844 // return array('text/plain', 'image/gif');
1845 return '*';
1849 * Tells how the file can be picked from this repository
1851 * Maximum value is FILE_INTERNAL | FILE_EXTERNAL | FILE_REFERENCE
1853 * @return int
1855 public function supported_returntypes() {
1856 return (FILE_INTERNAL | FILE_EXTERNAL);
1860 * Provide repository instance information for Ajax
1862 * @return stdClass
1864 final public function get_meta() {
1865 global $CFG, $OUTPUT;
1866 $meta = new stdClass();
1867 $meta->id = $this->id;
1868 $meta->name = format_string($this->get_name());
1869 $meta->type = $this->options['type'];
1870 $meta->icon = $OUTPUT->pix_url('icon', 'repository_'.$meta->type)->out(false);
1871 $meta->supported_types = file_get_typegroup('extension', $this->supported_filetypes());
1872 $meta->return_types = $this->supported_returntypes();
1873 $meta->sortorder = $this->options['sortorder'];
1874 return $meta;
1878 * Create an instance for this plug-in
1880 * @static
1881 * @param string $type the type of the repository
1882 * @param int $userid the user id
1883 * @param stdClass $context the context
1884 * @param array $params the options for this instance
1885 * @param int $readonly whether to create it readonly or not (defaults to not)
1886 * @return mixed
1888 public static function create($type, $userid, $context, $params, $readonly=0) {
1889 global $CFG, $DB;
1890 $params = (array)$params;
1891 require_once($CFG->dirroot . '/repository/'. $type . '/lib.php');
1892 $classname = 'repository_' . $type;
1893 if ($repo = $DB->get_record('repository', array('type'=>$type))) {
1894 $record = new stdClass();
1895 $record->name = $params['name'];
1896 $record->typeid = $repo->id;
1897 $record->timecreated = time();
1898 $record->timemodified = time();
1899 $record->contextid = $context->id;
1900 $record->readonly = $readonly;
1901 $record->userid = $userid;
1902 $id = $DB->insert_record('repository_instances', $record);
1903 $options = array();
1904 $configs = call_user_func($classname . '::get_instance_option_names');
1905 if (!empty($configs)) {
1906 foreach ($configs as $config) {
1907 if (isset($params[$config])) {
1908 $options[$config] = $params[$config];
1909 } else {
1910 $options[$config] = null;
1915 if (!empty($id)) {
1916 unset($options['name']);
1917 $instance = repository::get_instance($id);
1918 $instance->set_option($options);
1919 return $id;
1920 } else {
1921 return null;
1923 } else {
1924 return null;
1929 * delete a repository instance
1931 * @param bool $downloadcontents
1932 * @return bool
1934 final public function delete($downloadcontents = false) {
1935 global $DB;
1936 if ($downloadcontents) {
1937 $this->convert_references_to_local();
1939 try {
1940 $DB->delete_records('repository_instances', array('id'=>$this->id));
1941 $DB->delete_records('repository_instance_config', array('instanceid'=>$this->id));
1942 } catch (dml_exception $ex) {
1943 return false;
1945 return true;
1949 * Delete all the instances associated to a context.
1951 * This method is intended to be a callback when deleting
1952 * a course or a user to delete all the instances associated
1953 * to their context. The usual way to delete a single instance
1954 * is to use {@link self::delete()}.
1956 * @param int $contextid context ID.
1957 * @param boolean $downloadcontents true to convert references to hard copies.
1958 * @return void
1960 final public static function delete_all_for_context($contextid, $downloadcontents = true) {
1961 global $DB;
1962 $repoids = $DB->get_fieldset_select('repository_instances', 'id', 'contextid = :contextid', array('contextid' => $contextid));
1963 if ($downloadcontents) {
1964 foreach ($repoids as $repoid) {
1965 $repo = repository::get_repository_by_id($repoid, $contextid);
1966 $repo->convert_references_to_local();
1969 $DB->delete_records_list('repository_instances', 'id', $repoids);
1970 $DB->delete_records_list('repository_instance_config', 'instanceid', $repoids);
1974 * Hide/Show a repository
1976 * @param string $hide
1977 * @return bool
1979 final public function hide($hide = 'toggle') {
1980 global $DB;
1981 if ($entry = $DB->get_record('repository', array('id'=>$this->id))) {
1982 if ($hide === 'toggle' ) {
1983 if (!empty($entry->visible)) {
1984 $entry->visible = 0;
1985 } else {
1986 $entry->visible = 1;
1988 } else {
1989 if (!empty($hide)) {
1990 $entry->visible = 0;
1991 } else {
1992 $entry->visible = 1;
1995 return $DB->update_record('repository', $entry);
1997 return false;
2001 * Save settings for repository instance
2002 * $repo->set_option(array('api_key'=>'f2188bde132', 'name'=>'dongsheng'));
2004 * @param array $options settings
2005 * @return bool
2007 public function set_option($options = array()) {
2008 global $DB;
2010 if (!empty($options['name'])) {
2011 $r = new stdClass();
2012 $r->id = $this->id;
2013 $r->name = $options['name'];
2014 $DB->update_record('repository_instances', $r);
2015 unset($options['name']);
2017 foreach ($options as $name=>$value) {
2018 if ($id = $DB->get_field('repository_instance_config', 'id', array('name'=>$name, 'instanceid'=>$this->id))) {
2019 $DB->set_field('repository_instance_config', 'value', $value, array('id'=>$id));
2020 } else {
2021 $config = new stdClass();
2022 $config->instanceid = $this->id;
2023 $config->name = $name;
2024 $config->value = $value;
2025 $DB->insert_record('repository_instance_config', $config);
2028 return true;
2032 * Get settings for repository instance
2034 * @param string $config
2035 * @return array Settings
2037 public function get_option($config = '') {
2038 global $DB;
2039 $entries = $DB->get_records('repository_instance_config', array('instanceid'=>$this->id));
2040 $ret = array();
2041 if (empty($entries)) {
2042 return $ret;
2044 foreach($entries as $entry) {
2045 $ret[$entry->name] = $entry->value;
2047 if (!empty($config)) {
2048 if (isset($ret[$config])) {
2049 return $ret[$config];
2050 } else {
2051 return null;
2053 } else {
2054 return $ret;
2059 * Filter file listing to display specific types
2061 * @param array $value
2062 * @return bool
2064 public function filter(&$value) {
2065 $accepted_types = optional_param_array('accepted_types', '', PARAM_RAW);
2066 if (isset($value['children'])) {
2067 if (!empty($value['children'])) {
2068 $value['children'] = array_filter($value['children'], array($this, 'filter'));
2070 return true; // always return directories
2071 } else {
2072 if ($accepted_types == '*' or empty($accepted_types)
2073 or (is_array($accepted_types) and in_array('*', $accepted_types))) {
2074 return true;
2075 } else {
2076 foreach ($accepted_types as $ext) {
2077 if (preg_match('#'.$ext.'$#i', $value['title'])) {
2078 return true;
2083 return false;
2087 * Given a path, and perhaps a search, get a list of files.
2089 * See details on {@link http://docs.moodle.org/dev/Repository_plugins}
2091 * @param string $path this parameter can a folder name, or a identification of folder
2092 * @param string $page the page number of file list
2093 * @return array the list of files, including meta infomation, containing the following keys
2094 * manage, url to manage url
2095 * client_id
2096 * login, login form
2097 * repo_id, active repository id
2098 * login_btn_action, the login button action
2099 * login_btn_label, the login button label
2100 * total, number of results
2101 * perpage, items per page
2102 * page
2103 * pages, total pages
2104 * issearchresult, is it a search result?
2105 * list, file list
2106 * path, current path and parent path
2108 public function get_listing($path = '', $page = '') {
2113 * Prepare the breadcrumb.
2115 * @param array $breadcrumb contains each element of the breadcrumb.
2116 * @return array of breadcrumb elements.
2117 * @since 2.3.3
2119 protected static function prepare_breadcrumb($breadcrumb) {
2120 global $OUTPUT;
2121 $foldericon = $OUTPUT->pix_url(file_folder_icon(24))->out(false);
2122 $len = count($breadcrumb);
2123 for ($i = 0; $i < $len; $i++) {
2124 if (is_array($breadcrumb[$i]) && !isset($breadcrumb[$i]['icon'])) {
2125 $breadcrumb[$i]['icon'] = $foldericon;
2126 } else if (is_object($breadcrumb[$i]) && !isset($breadcrumb[$i]->icon)) {
2127 $breadcrumb[$i]->icon = $foldericon;
2130 return $breadcrumb;
2134 * Prepare the file/folder listing.
2136 * @param array $list of files and folders.
2137 * @return array of files and folders.
2138 * @since 2.3.3
2140 protected static function prepare_list($list) {
2141 global $OUTPUT;
2142 $foldericon = $OUTPUT->pix_url(file_folder_icon(24))->out(false);
2144 // Reset the array keys because non-numeric keys will create an object when converted to JSON.
2145 $list = array_values($list);
2147 $len = count($list);
2148 for ($i = 0; $i < $len; $i++) {
2149 if (is_object($list[$i])) {
2150 $file = (array)$list[$i];
2151 $converttoobject = true;
2152 } else {
2153 $file =& $list[$i];
2154 $converttoobject = false;
2156 if (isset($file['size'])) {
2157 $file['size'] = (int)$file['size'];
2158 $file['size_f'] = display_size($file['size']);
2160 if (isset($file['license']) && get_string_manager()->string_exists($file['license'], 'license')) {
2161 $file['license_f'] = get_string($file['license'], 'license');
2163 if (isset($file['image_width']) && isset($file['image_height'])) {
2164 $a = array('width' => $file['image_width'], 'height' => $file['image_height']);
2165 $file['dimensions'] = get_string('imagesize', 'repository', (object)$a);
2167 foreach (array('date', 'datemodified', 'datecreated') as $key) {
2168 if (!isset($file[$key]) && isset($file['date'])) {
2169 $file[$key] = $file['date'];
2171 if (isset($file[$key])) {
2172 // must be UNIX timestamp
2173 $file[$key] = (int)$file[$key];
2174 if (!$file[$key]) {
2175 unset($file[$key]);
2176 } else {
2177 $file[$key.'_f'] = userdate($file[$key], get_string('strftimedatetime', 'langconfig'));
2178 $file[$key.'_f_s'] = userdate($file[$key], get_string('strftimedatetimeshort', 'langconfig'));
2182 $isfolder = (array_key_exists('children', $file) || (isset($file['type']) && $file['type'] == 'folder'));
2183 $filename = null;
2184 if (isset($file['title'])) {
2185 $filename = $file['title'];
2187 else if (isset($file['fullname'])) {
2188 $filename = $file['fullname'];
2190 if (!isset($file['mimetype']) && !$isfolder && $filename) {
2191 $file['mimetype'] = get_mimetype_description(array('filename' => $filename));
2193 if (!isset($file['icon'])) {
2194 if ($isfolder) {
2195 $file['icon'] = $foldericon;
2196 } else if ($filename) {
2197 $file['icon'] = $OUTPUT->pix_url(file_extension_icon($filename, 24))->out(false);
2201 // Recursively loop over children.
2202 if (isset($file['children'])) {
2203 $file['children'] = self::prepare_list($file['children']);
2206 // Convert the array back to an object.
2207 if ($converttoobject) {
2208 $list[$i] = (object)$file;
2211 return $list;
2215 * Prepares list of files before passing it to AJAX, makes sure data is in the correct
2216 * format and stores formatted values.
2218 * @param array|stdClass $listing result of get_listing() or search() or file_get_drafarea_files()
2219 * @return array
2221 public static function prepare_listing($listing) {
2222 $wasobject = false;
2223 if (is_object($listing)) {
2224 $listing = (array) $listing;
2225 $wasobject = true;
2228 // Prepare the breadcrumb, passed as 'path'.
2229 if (isset($listing['path']) && is_array($listing['path'])) {
2230 $listing['path'] = self::prepare_breadcrumb($listing['path']);
2233 // Prepare the listing of objects.
2234 if (isset($listing['list']) && is_array($listing['list'])) {
2235 $listing['list'] = self::prepare_list($listing['list']);
2238 // Convert back to an object.
2239 if ($wasobject) {
2240 $listing = (object) $listing;
2242 return $listing;
2246 * Search files in repository
2247 * When doing global search, $search_text will be used as
2248 * keyword.
2250 * @param string $search_text search key word
2251 * @param int $page page
2252 * @return mixed see {@link repository::get_listing()}
2254 public function search($search_text, $page = 0) {
2255 $list = array();
2256 $list['list'] = array();
2257 return false;
2261 * Logout from repository instance
2262 * By default, this function will return a login form
2264 * @return string
2266 public function logout(){
2267 return $this->print_login();
2271 * To check whether the user is logged in.
2273 * @return bool
2275 public function check_login(){
2276 return true;
2281 * Show the login screen, if required
2283 * @return string
2285 public function print_login(){
2286 return $this->get_listing();
2290 * Show the search screen, if required
2292 * @return string
2294 public function print_search() {
2295 global $PAGE;
2296 $renderer = $PAGE->get_renderer('core', 'files');
2297 return $renderer->repository_default_searchform();
2301 * For oauth like external authentication, when external repository direct user back to moodle,
2302 * this function will be called to set up token and token_secret
2304 public function callback() {
2308 * is it possible to do glboal search?
2310 * @return bool
2312 public function global_search() {
2313 return false;
2317 * Defines operations that happen occasionally on cron
2319 * @return bool
2321 public function cron() {
2322 return true;
2326 * function which is run when the type is created (moodle administrator add the plugin)
2328 * @return bool success or fail?
2330 public static function plugin_init() {
2331 return true;
2335 * Edit/Create Admin Settings Moodle form
2337 * @param moodleform $mform Moodle form (passed by reference)
2338 * @param string $classname repository class name
2340 public static function type_config_form($mform, $classname = 'repository') {
2341 $instnaceoptions = call_user_func(array($classname, 'get_instance_option_names'), $mform, $classname);
2342 if (empty($instnaceoptions)) {
2343 // this plugin has only one instance
2344 // so we need to give it a name
2345 // it can be empty, then moodle will look for instance name from language string
2346 $mform->addElement('text', 'pluginname', get_string('pluginname', 'repository'), array('size' => '40'));
2347 $mform->addElement('static', 'pluginnamehelp', '', get_string('pluginnamehelp', 'repository'));
2348 $mform->setType('pluginname', PARAM_TEXT);
2353 * Validate Admin Settings Moodle form
2355 * @static
2356 * @param moodleform $mform Moodle form (passed by reference)
2357 * @param array $data array of ("fieldname"=>value) of submitted data
2358 * @param array $errors array of ("fieldname"=>errormessage) of errors
2359 * @return array array of errors
2361 public static function type_form_validation($mform, $data, $errors) {
2362 return $errors;
2367 * Edit/Create Instance Settings Moodle form
2369 * @param moodleform $mform Moodle form (passed by reference)
2371 public static function instance_config_form($mform) {
2375 * Return names of the general options.
2376 * By default: no general option name
2378 * @return array
2380 public static function get_type_option_names() {
2381 return array('pluginname');
2385 * Return names of the instance options.
2386 * By default: no instance option name
2388 * @return array
2390 public static function get_instance_option_names() {
2391 return array();
2395 * Validate repository plugin instance form
2397 * @param moodleform $mform moodle form
2398 * @param array $data form data
2399 * @param array $errors errors
2400 * @return array errors
2402 public static function instance_form_validation($mform, $data, $errors) {
2403 return $errors;
2407 * Create a shorten filename
2409 * @param string $str filename
2410 * @param int $maxlength max file name length
2411 * @return string short filename
2413 public function get_short_filename($str, $maxlength) {
2414 if (textlib::strlen($str) >= $maxlength) {
2415 return trim(textlib::substr($str, 0, $maxlength)).'...';
2416 } else {
2417 return $str;
2422 * Overwrite an existing file
2424 * @param int $itemid
2425 * @param string $filepath
2426 * @param string $filename
2427 * @param string $newfilepath
2428 * @param string $newfilename
2429 * @return bool
2431 public static function overwrite_existing_draftfile($itemid, $filepath, $filename, $newfilepath, $newfilename) {
2432 global $USER;
2433 $fs = get_file_storage();
2434 $user_context = context_user::instance($USER->id);
2435 if ($file = $fs->get_file($user_context->id, 'user', 'draft', $itemid, $filepath, $filename)) {
2436 if ($tempfile = $fs->get_file($user_context->id, 'user', 'draft', $itemid, $newfilepath, $newfilename)) {
2437 // Remember original file source field.
2438 $source = @unserialize($file->get_source());
2439 // Remember the original sortorder.
2440 $sortorder = $file->get_sortorder();
2441 if ($tempfile->is_external_file()) {
2442 // New file is a reference. Check that existing file does not have any other files referencing to it
2443 if (isset($source->original) && $fs->search_references_count($source->original)) {
2444 return (object)array('error' => get_string('errordoublereference', 'repository'));
2447 // delete existing file to release filename
2448 $file->delete();
2449 // create new file
2450 $newfile = $fs->create_file_from_storedfile(array('filepath'=>$filepath, 'filename'=>$filename), $tempfile);
2451 // Preserve original file location (stored in source field) for handling references
2452 if (isset($source->original)) {
2453 if (!($newfilesource = @unserialize($newfile->get_source()))) {
2454 $newfilesource = new stdClass();
2456 $newfilesource->original = $source->original;
2457 $newfile->set_source(serialize($newfilesource));
2459 $newfile->set_sortorder($sortorder);
2460 // remove temp file
2461 $tempfile->delete();
2462 return true;
2465 return false;
2469 * Updates a file in draft filearea.
2471 * This function can only update fields filepath, filename, author, license.
2472 * If anything (except filepath) is updated, timemodified is set to current time.
2473 * If filename or filepath is updated the file unconnects from it's origin
2474 * and therefore all references to it will be converted to copies when
2475 * filearea is saved.
2477 * @param int $draftid
2478 * @param string $filepath path to the directory containing the file, or full path in case of directory
2479 * @param string $filename name of the file, or '.' in case of directory
2480 * @param array $updatedata array of fields to change (only filename, filepath, license and/or author can be updated)
2481 * @throws moodle_exception if for any reason file can not be updated (file does not exist, target already exists, etc.)
2483 public static function update_draftfile($draftid, $filepath, $filename, $updatedata) {
2484 global $USER;
2485 $fs = get_file_storage();
2486 $usercontext = context_user::instance($USER->id);
2487 // make sure filename and filepath are present in $updatedata
2488 $updatedata = $updatedata + array('filepath' => $filepath, 'filename' => $filename);
2489 $filemodified = false;
2490 if (!$file = $fs->get_file($usercontext->id, 'user', 'draft', $draftid, $filepath, $filename)) {
2491 if ($filename === '.') {
2492 throw new moodle_exception('foldernotfound', 'repository');
2493 } else {
2494 throw new moodle_exception('filenotfound', 'error');
2497 if (!$file->is_directory()) {
2498 // This is a file
2499 if ($updatedata['filepath'] !== $filepath || $updatedata['filename'] !== $filename) {
2500 // Rename/move file: check that target file name does not exist.
2501 if ($fs->file_exists($usercontext->id, 'user', 'draft', $draftid, $updatedata['filepath'], $updatedata['filename'])) {
2502 throw new moodle_exception('fileexists', 'repository');
2504 if (($filesource = @unserialize($file->get_source())) && isset($filesource->original)) {
2505 unset($filesource->original);
2506 $file->set_source(serialize($filesource));
2508 $file->rename($updatedata['filepath'], $updatedata['filename']);
2509 // timemodified is updated only when file is renamed and not updated when file is moved.
2510 $filemodified = $filemodified || ($updatedata['filename'] !== $filename);
2512 if (array_key_exists('license', $updatedata) && $updatedata['license'] !== $file->get_license()) {
2513 // Update license and timemodified.
2514 $file->set_license($updatedata['license']);
2515 $filemodified = true;
2517 if (array_key_exists('author', $updatedata) && $updatedata['author'] !== $file->get_author()) {
2518 // Update author and timemodified.
2519 $file->set_author($updatedata['author']);
2520 $filemodified = true;
2522 // Update timemodified:
2523 if ($filemodified) {
2524 $file->set_timemodified(time());
2526 } else {
2527 // This is a directory - only filepath can be updated for a directory (it was moved).
2528 if ($updatedata['filepath'] === $filepath) {
2529 // nothing to update
2530 return;
2532 if ($fs->file_exists($usercontext->id, 'user', 'draft', $draftid, $updatedata['filepath'], '.')) {
2533 // bad luck, we can not rename if something already exists there
2534 throw new moodle_exception('folderexists', 'repository');
2536 $xfilepath = preg_quote($filepath, '|');
2537 if (preg_match("|^$xfilepath|", $updatedata['filepath'])) {
2538 // we can not move folder to it's own subfolder
2539 throw new moodle_exception('folderrecurse', 'repository');
2542 // If directory changed the name, update timemodified.
2543 $filemodified = (basename(rtrim($file->get_filepath(), '/')) !== basename(rtrim($updatedata['filepath'], '/')));
2545 // Now update directory and all children.
2546 $files = $fs->get_area_files($usercontext->id, 'user', 'draft', $draftid);
2547 foreach ($files as $f) {
2548 if (preg_match("|^$xfilepath|", $f->get_filepath())) {
2549 $path = preg_replace("|^$xfilepath|", $updatedata['filepath'], $f->get_filepath());
2550 if (($filesource = @unserialize($f->get_source())) && isset($filesource->original)) {
2551 // unset original so the references are not shown any more
2552 unset($filesource->original);
2553 $f->set_source(serialize($filesource));
2555 $f->rename($path, $f->get_filename());
2556 if ($filemodified && $f->get_filepath() === $updatedata['filepath'] && $f->get_filename() === $filename) {
2557 $f->set_timemodified(time());
2565 * Delete a temp file from draft area
2567 * @param int $draftitemid
2568 * @param string $filepath
2569 * @param string $filename
2570 * @return bool
2572 public static function delete_tempfile_from_draft($draftitemid, $filepath, $filename) {
2573 global $USER;
2574 $fs = get_file_storage();
2575 $user_context = context_user::instance($USER->id);
2576 if ($file = $fs->get_file($user_context->id, 'user', 'draft', $draftitemid, $filepath, $filename)) {
2577 $file->delete();
2578 return true;
2579 } else {
2580 return false;
2585 * Find all external files in this repo and import them
2587 public function convert_references_to_local() {
2588 $fs = get_file_storage();
2589 $files = $fs->get_external_files($this->id);
2590 foreach ($files as $storedfile) {
2591 $fs->import_external_file($storedfile);
2596 * Called from phpunit between tests, resets whatever was cached
2598 public static function reset_caches() {
2599 self::sync_external_file(null, true);
2603 * Performs synchronisation of reference to an external file if the previous one has expired.
2605 * @param stored_file $file
2606 * @param bool $resetsynchistory whether to reset all history of sync (used by phpunit)
2607 * @return bool success
2609 public static function sync_external_file($file, $resetsynchistory = false) {
2610 global $DB;
2611 // TODO MDL-25290 static should be replaced with MUC code.
2612 static $synchronized = array();
2613 if ($resetsynchistory) {
2614 $synchronized = array();
2617 $fs = get_file_storage();
2619 if (!$file || !$file->get_referencefileid()) {
2620 return false;
2622 if (array_key_exists($file->get_id(), $synchronized)) {
2623 return $synchronized[$file->get_id()];
2626 // remember that we already cached in current request to prevent from querying again
2627 $synchronized[$file->get_id()] = false;
2629 if (!$reference = $DB->get_record('files_reference', array('id'=>$file->get_referencefileid()))) {
2630 return false;
2633 if (!empty($reference->lastsync) and ($reference->lastsync + $reference->lifetime > time())) {
2634 $synchronized[$file->get_id()] = true;
2635 return true;
2638 if (!$repository = self::get_repository_by_id($reference->repositoryid, SYSCONTEXTID)) {
2639 return false;
2642 if (!$repository->sync_individual_file($file)) {
2643 return false;
2646 $lifetime = $repository->get_reference_file_lifetime($reference);
2647 $fileinfo = $repository->get_file_by_reference($reference);
2648 if ($fileinfo === null) {
2649 // does not exist any more - set status to missing
2650 $file->set_missingsource($lifetime);
2651 $synchronized[$file->get_id()] = true;
2652 return true;
2655 $contenthash = null;
2656 $filesize = null;
2657 if (!empty($fileinfo->filesize)) {
2658 // filesize returned
2659 if (!empty($fileinfo->contenthash) && $fs->content_exists($fileinfo->contenthash)) {
2660 // contenthash is specified and valid
2661 $contenthash = $fileinfo->contenthash;
2662 } else if ($fileinfo->filesize == $file->get_filesize()) {
2663 // we don't know the new contenthash but the filesize did not change,
2664 // assume the contenthash did not change either
2665 $contenthash = $file->get_contenthash();
2666 } else {
2667 // we can't save empty contenthash so generate contenthash from empty string
2668 $fs->add_string_to_pool('');
2669 $contenthash = sha1('');
2671 $filesize = $fileinfo->filesize;
2672 } else if (!empty($fileinfo->filepath)) {
2673 // File path returned
2674 list($contenthash, $filesize, $newfile) = $fs->add_file_to_pool($fileinfo->filepath);
2675 } else if (!empty($fileinfo->handle) && is_resource($fileinfo->handle)) {
2676 // File handle returned
2677 $contents = '';
2678 while (!feof($fileinfo->handle)) {
2679 $contents .= fread($handle, 8192);
2681 fclose($fileinfo->handle);
2682 list($contenthash, $filesize, $newfile) = $fs->add_string_to_pool($content);
2683 } else if (isset($fileinfo->content)) {
2684 // File content returned
2685 list($contenthash, $filesize, $newfile) = $fs->add_string_to_pool($fileinfo->content);
2688 if (!isset($contenthash) or !isset($filesize)) {
2689 return false;
2692 // update files table
2693 $file->set_synchronized($contenthash, $filesize, 0, $lifetime);
2694 $synchronized[$file->get_id()] = true;
2695 return true;
2699 * Build draft file's source field
2701 * {@link file_restore_source_field_from_draft_file()}
2702 * XXX: This is a hack for file manager (MDL-28666)
2703 * For newly created draft files we have to construct
2704 * source filed in php serialized data format.
2705 * File manager needs to know the original file information before copying
2706 * to draft area, so we append these information in mdl_files.source field
2708 * @param string $source
2709 * @return string serialised source field
2711 public static function build_source_field($source) {
2712 $sourcefield = new stdClass;
2713 $sourcefield->source = $source;
2714 return serialize($sourcefield);
2719 * Exception class for repository api
2721 * @since 2.0
2722 * @package core_repository
2723 * @copyright 2009 Dongsheng Cai {@link http://dongsheng.org}
2724 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2726 class repository_exception extends moodle_exception {
2730 * This is a class used to define a repository instance form
2732 * @since 2.0
2733 * @package core_repository
2734 * @copyright 2009 Dongsheng Cai {@link http://dongsheng.org}
2735 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2737 final class repository_instance_form extends moodleform {
2738 /** @var stdClass repository instance */
2739 protected $instance;
2740 /** @var string repository plugin type */
2741 protected $plugin;
2744 * Added defaults to moodle form
2746 protected function add_defaults() {
2747 $mform =& $this->_form;
2748 $strrequired = get_string('required');
2750 $mform->addElement('hidden', 'edit', ($this->instance) ? $this->instance->id : 0);
2751 $mform->setType('edit', PARAM_INT);
2752 $mform->addElement('hidden', 'new', $this->plugin);
2753 $mform->setType('new', PARAM_ALPHANUMEXT);
2754 $mform->addElement('hidden', 'plugin', $this->plugin);
2755 $mform->setType('plugin', PARAM_PLUGIN);
2756 $mform->addElement('hidden', 'typeid', $this->typeid);
2757 $mform->setType('typeid', PARAM_INT);
2758 $mform->addElement('hidden', 'contextid', $this->contextid);
2759 $mform->setType('contextid', PARAM_INT);
2761 $mform->addElement('text', 'name', get_string('name'), 'maxlength="100" size="30"');
2762 $mform->addRule('name', $strrequired, 'required', null, 'client');
2763 $mform->setType('name', PARAM_TEXT);
2767 * Define moodle form elements
2769 public function definition() {
2770 global $CFG;
2771 // type of plugin, string
2772 $this->plugin = $this->_customdata['plugin'];
2773 $this->typeid = $this->_customdata['typeid'];
2774 $this->contextid = $this->_customdata['contextid'];
2775 $this->instance = (isset($this->_customdata['instance'])
2776 && is_subclass_of($this->_customdata['instance'], 'repository'))
2777 ? $this->_customdata['instance'] : null;
2779 $mform =& $this->_form;
2781 $this->add_defaults();
2783 // Add instance config options.
2784 $result = repository::static_function($this->plugin, 'instance_config_form', $mform);
2785 if ($result === false) {
2786 // Remove the name element if no other config options.
2787 $mform->removeElement('name');
2789 if ($this->instance) {
2790 $data = array();
2791 $data['name'] = $this->instance->name;
2792 if (!$this->instance->readonly) {
2793 // and set the data if we have some.
2794 foreach ($this->instance->get_instance_option_names() as $config) {
2795 if (!empty($this->instance->options[$config])) {
2796 $data[$config] = $this->instance->options[$config];
2797 } else {
2798 $data[$config] = '';
2802 $this->set_data($data);
2805 if ($result === false) {
2806 $mform->addElement('cancel');
2807 } else {
2808 $this->add_action_buttons(true, get_string('save','repository'));
2813 * Validate moodle form data
2815 * @param array $data form data
2816 * @param array $files files in form
2817 * @return array errors
2819 public function validation($data, $files) {
2820 global $DB;
2821 $errors = array();
2822 $plugin = $this->_customdata['plugin'];
2823 $instance = (isset($this->_customdata['instance'])
2824 && is_subclass_of($this->_customdata['instance'], 'repository'))
2825 ? $this->_customdata['instance'] : null;
2827 if (!$instance) {
2828 $errors = repository::static_function($plugin, 'instance_form_validation', $this, $data, $errors);
2829 } else {
2830 $errors = $instance->instance_form_validation($this, $data, $errors);
2833 $sql = "SELECT count('x')
2834 FROM {repository_instances} i, {repository} r
2835 WHERE r.type=:plugin AND r.id=i.typeid AND i.name=:name AND i.contextid=:contextid";
2836 $params = array('name' => $data['name'], 'plugin' => $this->plugin, 'contextid' => $this->contextid);
2837 if ($instance) {
2838 $sql .= ' AND i.id != :instanceid';
2839 $params['instanceid'] = $instance->id;
2841 if ($DB->count_records_sql($sql, $params) > 0) {
2842 $errors['name'] = get_string('erroruniquename', 'repository');
2845 return $errors;
2850 * This is a class used to define a repository type setting form
2852 * @since 2.0
2853 * @package core_repository
2854 * @copyright 2009 Dongsheng Cai {@link http://dongsheng.org}
2855 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2857 final class repository_type_form extends moodleform {
2858 /** @var stdClass repository instance */
2859 protected $instance;
2860 /** @var string repository plugin name */
2861 protected $plugin;
2862 /** @var string action */
2863 protected $action;
2866 * Definition of the moodleform
2868 public function definition() {
2869 global $CFG;
2870 // type of plugin, string
2871 $this->plugin = $this->_customdata['plugin'];
2872 $this->instance = (isset($this->_customdata['instance'])
2873 && is_a($this->_customdata['instance'], 'repository_type'))
2874 ? $this->_customdata['instance'] : null;
2876 $this->action = $this->_customdata['action'];
2877 $this->pluginname = $this->_customdata['pluginname'];
2878 $mform =& $this->_form;
2879 $strrequired = get_string('required');
2881 $mform->addElement('hidden', 'action', $this->action);
2882 $mform->setType('action', PARAM_TEXT);
2883 $mform->addElement('hidden', 'repos', $this->plugin);
2884 $mform->setType('repos', PARAM_PLUGIN);
2886 // let the plugin add its specific fields
2887 $classname = 'repository_' . $this->plugin;
2888 require_once($CFG->dirroot . '/repository/' . $this->plugin . '/lib.php');
2889 //add "enable course/user instances" checkboxes if multiple instances are allowed
2890 $instanceoptionnames = repository::static_function($this->plugin, 'get_instance_option_names');
2892 $result = call_user_func(array($classname, 'type_config_form'), $mform, $classname);
2894 if (!empty($instanceoptionnames)) {
2895 $sm = get_string_manager();
2896 $component = 'repository';
2897 if ($sm->string_exists('enablecourseinstances', 'repository_' . $this->plugin)) {
2898 $component .= ('_' . $this->plugin);
2900 $mform->addElement('checkbox', 'enablecourseinstances', get_string('enablecourseinstances', $component));
2902 $component = 'repository';
2903 if ($sm->string_exists('enableuserinstances', 'repository_' . $this->plugin)) {
2904 $component .= ('_' . $this->plugin);
2906 $mform->addElement('checkbox', 'enableuserinstances', get_string('enableuserinstances', $component));
2909 // set the data if we have some.
2910 if ($this->instance) {
2911 $data = array();
2912 $option_names = call_user_func(array($classname,'get_type_option_names'));
2913 if (!empty($instanceoptionnames)){
2914 $option_names[] = 'enablecourseinstances';
2915 $option_names[] = 'enableuserinstances';
2918 $instanceoptions = $this->instance->get_options();
2919 foreach ($option_names as $config) {
2920 if (!empty($instanceoptions[$config])) {
2921 $data[$config] = $instanceoptions[$config];
2922 } else {
2923 $data[$config] = '';
2926 // XXX: set plugin name for plugins which doesn't have muliti instances
2927 if (empty($instanceoptionnames)){
2928 $data['pluginname'] = $this->pluginname;
2930 $this->set_data($data);
2933 $this->add_action_buttons(true, get_string('save','repository'));
2937 * Validate moodle form data
2939 * @param array $data moodle form data
2940 * @param array $files
2941 * @return array errors
2943 public function validation($data, $files) {
2944 $errors = array();
2945 $plugin = $this->_customdata['plugin'];
2946 $instance = (isset($this->_customdata['instance'])
2947 && is_subclass_of($this->_customdata['instance'], 'repository'))
2948 ? $this->_customdata['instance'] : null;
2949 if (!$instance) {
2950 $errors = repository::static_function($plugin, 'type_form_validation', $this, $data, $errors);
2951 } else {
2952 $errors = $instance->type_form_validation($this, $data, $errors);
2955 return $errors;
2960 * Generate all options needed by filepicker
2962 * @param array $args including following keys
2963 * context
2964 * accepted_types
2965 * return_types
2967 * @return array the list of repository instances, including meta infomation, containing the following keys
2968 * externallink
2969 * repositories
2970 * accepted_types
2972 function initialise_filepicker($args) {
2973 global $CFG, $USER, $PAGE, $OUTPUT;
2974 static $templatesinitialized = array();
2975 require_once($CFG->libdir . '/licenselib.php');
2977 $return = new stdClass();
2978 $licenses = array();
2979 if (!empty($CFG->licenses)) {
2980 $array = explode(',', $CFG->licenses);
2981 foreach ($array as $license) {
2982 $l = new stdClass();
2983 $l->shortname = $license;
2984 $l->fullname = get_string($license, 'license');
2985 $licenses[] = $l;
2988 if (!empty($CFG->sitedefaultlicense)) {
2989 $return->defaultlicense = $CFG->sitedefaultlicense;
2992 $return->licenses = $licenses;
2994 $return->author = fullname($USER);
2996 if (empty($args->context)) {
2997 $context = $PAGE->context;
2998 } else {
2999 $context = $args->context;
3001 $disable_types = array();
3002 if (!empty($args->disable_types)) {
3003 $disable_types = $args->disable_types;
3006 $user_context = context_user::instance($USER->id);
3008 list($context, $course, $cm) = get_context_info_array($context->id);
3009 $contexts = array($user_context, get_system_context());
3010 if (!empty($course)) {
3011 // adding course context
3012 $contexts[] = context_course::instance($course->id);
3014 $externallink = (int)get_config(null, 'repositoryallowexternallinks');
3015 $repositories = repository::get_instances(array(
3016 'context'=>$contexts,
3017 'currentcontext'=> $context,
3018 'accepted_types'=>$args->accepted_types,
3019 'return_types'=>$args->return_types,
3020 'disable_types'=>$disable_types
3023 $return->repositories = array();
3025 if (empty($externallink)) {
3026 $return->externallink = false;
3027 } else {
3028 $return->externallink = true;
3031 $return->userprefs = array();
3032 $return->userprefs['recentrepository'] = get_user_preferences('filepicker_recentrepository', '');
3033 $return->userprefs['recentlicense'] = get_user_preferences('filepicker_recentlicense', '');
3034 $return->userprefs['recentviewmode'] = get_user_preferences('filepicker_recentviewmode', '');
3036 user_preference_allow_ajax_update('filepicker_recentrepository', PARAM_INT);
3037 user_preference_allow_ajax_update('filepicker_recentlicense', PARAM_SAFEDIR);
3038 user_preference_allow_ajax_update('filepicker_recentviewmode', PARAM_INT);
3041 // provided by form element
3042 $return->accepted_types = file_get_typegroup('extension', $args->accepted_types);
3043 $return->return_types = $args->return_types;
3044 $templates = array();
3045 foreach ($repositories as $repository) {
3046 $meta = $repository->get_meta();
3047 // Please note that the array keys for repositories are used within
3048 // JavaScript a lot, the key NEEDS to be the repository id.
3049 $return->repositories[$repository->id] = $meta;
3050 // Register custom repository template if it has one
3051 if(method_exists($repository, 'get_upload_template') && !array_key_exists('uploadform_' . $meta->type, $templatesinitialized)) {
3052 $templates['uploadform_' . $meta->type] = $repository->get_upload_template();
3053 $templatesinitialized['uploadform_' . $meta->type] = true;
3056 if (!array_key_exists('core', $templatesinitialized)) {
3057 // we need to send each filepicker template to the browser just once
3058 $fprenderer = $PAGE->get_renderer('core', 'files');
3059 $templates = array_merge($templates, $fprenderer->filepicker_js_templates());
3060 $templatesinitialized['core'] = true;
3062 if (sizeof($templates)) {
3063 $PAGE->requires->js_init_call('M.core_filepicker.set_templates', array($templates), true);
3065 return $return;
3069 * Small function to walk an array to attach repository ID
3071 * @param array $value
3072 * @param string $key
3073 * @param int $id
3075 function repository_attach_id(&$value, $key, $id){
3076 $value['repo_id'] = $id;