Moodle release 2.3.5
[moodle.git] / repository / lib.php
blob93e426cefb43f01a91fd63f4944977596ac570ad
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 require_once(dirname(dirname(__FILE__)) . '/config.php');
27 require_once($CFG->libdir . '/filelib.php');
28 require_once($CFG->libdir . '/formslib.php');
30 define('FILE_EXTERNAL', 1);
31 define('FILE_INTERNAL', 2);
32 define('FILE_REFERENCE', 4);
33 define('RENAME_SUFFIX', '_2');
35 /**
36 * This class is used to manage repository plugins
38 * A repository_type is a repository plug-in. It can be Box.net, Flick-r, ...
39 * A repository type can be edited, sorted and hidden. It is mandatory for an
40 * administrator to create a repository type in order to be able to create
41 * some instances of this type.
42 * Coding note:
43 * - a repository_type object is mapped to the "repository" database table
44 * - "typename" attibut maps the "type" database field. It is unique.
45 * - general "options" for a repository type are saved in the config_plugin table
46 * - when you delete a repository, all instances are deleted, and general
47 * options are also deleted from database
48 * - When you create a type for a plugin that can't have multiple instances, a
49 * instance is automatically created.
51 * @package core_repository
52 * @copyright 2009 Jerome Mouneyrac
53 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
55 class repository_type {
58 /**
59 * Type name (no whitespace) - A type name is unique
60 * Note: for a user-friendly type name see get_readablename()
61 * @var String
63 private $_typename;
66 /**
67 * Options of this type
68 * They are general options that any instance of this type would share
69 * e.g. API key
70 * These options are saved in config_plugin table
71 * @var array
73 private $_options;
76 /**
77 * Is the repository type visible or hidden
78 * If false (hidden): no instances can be created, edited, deleted, showned , used...
79 * @var boolean
81 private $_visible;
84 /**
85 * 0 => not ordered, 1 => first position, 2 => second position...
86 * A not order type would appear in first position (should never happened)
87 * @var integer
89 private $_sortorder;
91 /**
92 * Return if the instance is visible in a context
94 * @todo check if the context visibility has been overwritten by the plugin creator
95 * (need to create special functions to be overvwritten in repository class)
96 * @param stdClass $context context
97 * @return bool
99 public function get_contextvisibility($context) {
100 global $USER;
102 if ($context->contextlevel == CONTEXT_COURSE) {
103 return $this->_options['enablecourseinstances'];
106 if ($context->contextlevel == CONTEXT_USER) {
107 return $this->_options['enableuserinstances'];
110 //the context is SITE
111 return true;
117 * repository_type constructor
119 * @param int $typename
120 * @param array $typeoptions
121 * @param bool $visible
122 * @param int $sortorder (don't really need set, it will be during create() call)
124 public function __construct($typename = '', $typeoptions = array(), $visible = true, $sortorder = 0) {
125 global $CFG;
127 //set type attributs
128 $this->_typename = $typename;
129 $this->_visible = $visible;
130 $this->_sortorder = $sortorder;
132 //set options attribut
133 $this->_options = array();
134 $options = repository::static_function($typename, 'get_type_option_names');
135 //check that the type can be setup
136 if (!empty($options)) {
137 //set the type options
138 foreach ($options as $config) {
139 if (array_key_exists($config, $typeoptions)) {
140 $this->_options[$config] = $typeoptions[$config];
145 //retrieve visibility from option
146 if (array_key_exists('enablecourseinstances',$typeoptions)) {
147 $this->_options['enablecourseinstances'] = $typeoptions['enablecourseinstances'];
148 } else {
149 $this->_options['enablecourseinstances'] = 0;
152 if (array_key_exists('enableuserinstances',$typeoptions)) {
153 $this->_options['enableuserinstances'] = $typeoptions['enableuserinstances'];
154 } else {
155 $this->_options['enableuserinstances'] = 0;
161 * Get the type name (no whitespace)
162 * For a human readable name, use get_readablename()
164 * @return string the type name
166 public function get_typename() {
167 return $this->_typename;
171 * Return a human readable and user-friendly type name
173 * @return string user-friendly type name
175 public function get_readablename() {
176 return get_string('pluginname','repository_'.$this->_typename);
180 * Return general options
182 * @return array the general options
184 public function get_options() {
185 return $this->_options;
189 * Return visibility
191 * @return bool
193 public function get_visible() {
194 return $this->_visible;
198 * Return order / position of display in the file picker
200 * @return int
202 public function get_sortorder() {
203 return $this->_sortorder;
207 * Create a repository type (the type name must not already exist)
208 * @param bool $silent throw exception?
209 * @return mixed return int if create successfully, return false if
211 public function create($silent = false) {
212 global $DB;
214 //check that $type has been set
215 $timmedtype = trim($this->_typename);
216 if (empty($timmedtype)) {
217 throw new repository_exception('emptytype', 'repository');
220 //set sortorder as the last position in the list
221 if (!isset($this->_sortorder) || $this->_sortorder == 0 ) {
222 $sql = "SELECT MAX(sortorder) FROM {repository}";
223 $this->_sortorder = 1 + $DB->get_field_sql($sql);
226 //only create a new type if it doesn't already exist
227 $existingtype = $DB->get_record('repository', array('type'=>$this->_typename));
228 if (!$existingtype) {
229 //create the type
230 $newtype = new stdClass();
231 $newtype->type = $this->_typename;
232 $newtype->visible = $this->_visible;
233 $newtype->sortorder = $this->_sortorder;
234 $plugin_id = $DB->insert_record('repository', $newtype);
235 //save the options in DB
236 $this->update_options();
238 $instanceoptionnames = repository::static_function($this->_typename, 'get_instance_option_names');
240 //if the plugin type has no multiple instance (e.g. has no instance option name) so it wont
241 //be possible for the administrator to create a instance
242 //in this case we need to create an instance
243 if (empty($instanceoptionnames)) {
244 $instanceoptions = array();
245 if (empty($this->_options['pluginname'])) {
246 // when moodle trying to install some repo plugin automatically
247 // this option will be empty, get it from language string when display
248 $instanceoptions['name'] = '';
249 } else {
250 // when admin trying to add a plugin manually, he will type a name
251 // for it
252 $instanceoptions['name'] = $this->_options['pluginname'];
254 repository::static_function($this->_typename, 'create', $this->_typename, 0, get_system_context(), $instanceoptions);
256 //run plugin_init function
257 if (!repository::static_function($this->_typename, 'plugin_init')) {
258 if (!$silent) {
259 throw new repository_exception('cannotinitplugin', 'repository');
263 if(!empty($plugin_id)) {
264 // return plugin_id if create successfully
265 return $plugin_id;
266 } else {
267 return false;
270 } else {
271 if (!$silent) {
272 throw new repository_exception('existingrepository', 'repository');
274 // If plugin existed, return false, tell caller no new plugins were created.
275 return false;
281 * Update plugin options into the config_plugin table
283 * @param array $options
284 * @return bool
286 public function update_options($options = null) {
287 global $DB;
288 $classname = 'repository_' . $this->_typename;
289 $instanceoptions = repository::static_function($this->_typename, 'get_instance_option_names');
290 if (empty($instanceoptions)) {
291 // update repository instance name if this plugin type doesn't have muliti instances
292 $params = array();
293 $params['type'] = $this->_typename;
294 $instances = repository::get_instances($params);
295 $instance = array_pop($instances);
296 if ($instance) {
297 $DB->set_field('repository_instances', 'name', $options['pluginname'], array('id'=>$instance->id));
299 unset($options['pluginname']);
302 if (!empty($options)) {
303 $this->_options = $options;
306 foreach ($this->_options as $name => $value) {
307 set_config($name, $value, $this->_typename);
310 return true;
314 * Update visible database field with the value given as parameter
315 * or with the visible value of this object
316 * This function is private.
317 * For public access, have a look to switch_and_update_visibility()
319 * @param bool $visible
320 * @return bool
322 private function update_visible($visible = null) {
323 global $DB;
325 if (!empty($visible)) {
326 $this->_visible = $visible;
328 else if (!isset($this->_visible)) {
329 throw new repository_exception('updateemptyvisible', 'repository');
332 return $DB->set_field('repository', 'visible', $this->_visible, array('type'=>$this->_typename));
336 * Update database sortorder field with the value given as parameter
337 * or with the sortorder value of this object
338 * This function is private.
339 * For public access, have a look to move_order()
341 * @param int $sortorder
342 * @return bool
344 private function update_sortorder($sortorder = null) {
345 global $DB;
347 if (!empty($sortorder) && $sortorder!=0) {
348 $this->_sortorder = $sortorder;
350 //if sortorder is not set, we set it as the ;ast position in the list
351 else if (!isset($this->_sortorder) || $this->_sortorder == 0 ) {
352 $sql = "SELECT MAX(sortorder) FROM {repository}";
353 $this->_sortorder = 1 + $DB->get_field_sql($sql);
356 return $DB->set_field('repository', 'sortorder', $this->_sortorder, array('type'=>$this->_typename));
360 * Change order of the type with its adjacent upper or downer type
361 * (database fields are updated)
362 * Algorithm details:
363 * 1. retrieve all types in an array. This array is sorted by sortorder,
364 * and the array keys start from 0 to X (incremented by 1)
365 * 2. switch sortorder values of this type and its adjacent type
367 * @param string $move "up" or "down"
369 public function move_order($move) {
370 global $DB;
372 $types = repository::get_types(); // retrieve all types
374 // retrieve this type into the returned array
375 $i = 0;
376 while (!isset($indice) && $i<count($types)) {
377 if ($types[$i]->get_typename() == $this->_typename) {
378 $indice = $i;
380 $i++;
383 // retrieve adjacent indice
384 switch ($move) {
385 case "up":
386 $adjacentindice = $indice - 1;
387 break;
388 case "down":
389 $adjacentindice = $indice + 1;
390 break;
391 default:
392 throw new repository_exception('movenotdefined', 'repository');
395 //switch sortorder of this type and the adjacent type
396 //TODO: we could reset sortorder for all types. This is not as good in performance term, but
397 //that prevent from wrong behaviour on a screwed database. As performance are not important in this particular case
398 //it worth to change the algo.
399 if ($adjacentindice>=0 && !empty($types[$adjacentindice])) {
400 $DB->set_field('repository', 'sortorder', $this->_sortorder, array('type'=>$types[$adjacentindice]->get_typename()));
401 $this->update_sortorder($types[$adjacentindice]->get_sortorder());
406 * 1. Change visibility to the value chosen
407 * 2. Update the type
409 * @param bool $visible
410 * @return bool
412 public function update_visibility($visible = null) {
413 if (is_bool($visible)) {
414 $this->_visible = $visible;
415 } else {
416 $this->_visible = !$this->_visible;
418 return $this->update_visible();
423 * Delete a repository_type (general options are removed from config_plugin
424 * table, and all instances are deleted)
426 * @param bool $downloadcontents download external contents if exist
427 * @return bool
429 public function delete($downloadcontents = false) {
430 global $DB;
432 //delete all instances of this type
433 $params = array();
434 $params['context'] = array();
435 $params['onlyvisible'] = false;
436 $params['type'] = $this->_typename;
437 $instances = repository::get_instances($params);
438 foreach ($instances as $instance) {
439 $instance->delete($downloadcontents);
442 //delete all general options
443 foreach ($this->_options as $name => $value) {
444 set_config($name, null, $this->_typename);
447 try {
448 $DB->delete_records('repository', array('type' => $this->_typename));
449 } catch (dml_exception $ex) {
450 return false;
452 return true;
457 * This is the base class of the repository class.
459 * To create repository plugin, see: {@link http://docs.moodle.org/dev/Repository_plugins}
460 * See an example: {@link repository_boxnet}
462 * @package core_repository
463 * @copyright 2009 Dongsheng Cai {@link http://dongsheng.org}
464 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
466 abstract class repository {
467 /** Timeout in seconds for downloading the external file into moodle */
468 const GETFILE_TIMEOUT = 30;
469 /** Timeout in seconds for syncronising the external file size */
470 const SYNCFILE_TIMEOUT = 1;
471 /** Timeout in seconds for downloading an image file from external repository during syncronisation */
472 const SYNCIMAGE_TIMEOUT = 3;
474 // $disabled can be set to true to disable a plugin by force
475 // example: self::$disabled = true
476 /** @var bool force disable repository instance */
477 public $disabled = false;
478 /** @var int repository instance id */
479 public $id;
480 /** @var stdClass current context */
481 public $context;
482 /** @var array repository options */
483 public $options;
484 /** @var bool Whether or not the repository instance is editable */
485 public $readonly;
486 /** @var int return types */
487 public $returntypes;
488 /** @var stdClass repository instance database record */
489 public $instance;
490 /** @var string Type of repository (webdav, google_docs, dropbox, ...). */
491 public $type;
494 * Constructor
496 * @param int $repositoryid repository instance id
497 * @param int|stdClass $context a context id or context object
498 * @param array $options repository options
499 * @param int $readonly indicate this repo is readonly or not
501 public function __construct($repositoryid, $context = SYSCONTEXTID, $options = array(), $readonly = 0) {
502 global $DB;
503 $this->id = $repositoryid;
504 if (is_object($context)) {
505 $this->context = $context;
506 } else {
507 $this->context = get_context_instance_by_id($context);
509 $this->instance = $DB->get_record('repository_instances', array('id'=>$this->id));
510 $this->readonly = $readonly;
511 $this->options = array();
513 if (is_array($options)) {
514 // The get_option() method will get stored options in database.
515 $options = array_merge($this->get_option(), $options);
516 } else {
517 $options = $this->get_option();
519 foreach ($options as $n => $v) {
520 $this->options[$n] = $v;
522 $this->name = $this->get_name();
523 $this->returntypes = $this->supported_returntypes();
524 $this->super_called = true;
526 // Determining the type of repository if not set.
527 if (empty($this->type)) {
528 $matches = array();
529 if (!preg_match("/^repository_(.*)$/", get_class($this), $matches)) {
530 throw new coding_exception('The class name of a repository should be repository_<typeofrepository>, '.
531 'e.g. repository_dropbox');
533 $this->type = $matches[1];
538 * Get repository instance using repository id
540 * @param int $repositoryid repository ID
541 * @param stdClass|int $context context instance or context ID
542 * @param array $options additional repository options
543 * @return repository
545 public static function get_repository_by_id($repositoryid, $context, $options = array()) {
546 global $CFG, $DB;
548 $sql = 'SELECT i.name, i.typeid, r.type FROM {repository} r, {repository_instances} i WHERE i.id=? AND i.typeid=r.id';
550 if (!$record = $DB->get_record_sql($sql, array($repositoryid))) {
551 throw new repository_exception('invalidrepositoryid', 'repository');
552 } else {
553 $type = $record->type;
554 if (file_exists($CFG->dirroot . "/repository/$type/lib.php")) {
555 require_once($CFG->dirroot . "/repository/$type/lib.php");
556 $classname = 'repository_' . $type;
557 $contextid = $context;
558 if (is_object($context)) {
559 $contextid = $context->id;
561 $options['type'] = $type;
562 $options['typeid'] = $record->typeid;
563 if (empty($options['name'])) {
564 $options['name'] = $record->name;
566 $repository = new $classname($repositoryid, $contextid, $options);
567 return $repository;
568 } else {
569 throw new repository_exception('invalidplugin', 'repository');
575 * Get a repository type object by a given type name.
577 * @static
578 * @param string $typename the repository type name
579 * @return repository_type|bool
581 public static function get_type_by_typename($typename) {
582 global $DB;
584 if (!$record = $DB->get_record('repository',array('type' => $typename))) {
585 return false;
588 return new repository_type($typename, (array)get_config($typename), $record->visible, $record->sortorder);
592 * Get the repository type by a given repository type id.
594 * @static
595 * @param int $id the type id
596 * @return object
598 public static function get_type_by_id($id) {
599 global $DB;
601 if (!$record = $DB->get_record('repository',array('id' => $id))) {
602 return false;
605 return new repository_type($record->type, (array)get_config($record->type), $record->visible, $record->sortorder);
609 * Return all repository types ordered by sortorder field
610 * first repository type in returnedarray[0], second repository type in returnedarray[1], ...
612 * @static
613 * @param bool $visible can return types by visiblity, return all types if null
614 * @return array Repository types
616 public static function get_types($visible=null) {
617 global $DB, $CFG;
619 $types = array();
620 $params = null;
621 if (!empty($visible)) {
622 $params = array('visible' => $visible);
624 if ($records = $DB->get_records('repository',$params,'sortorder')) {
625 foreach($records as $type) {
626 if (file_exists($CFG->dirroot . '/repository/'. $type->type .'/lib.php')) {
627 $types[] = new repository_type($type->type, (array)get_config($type->type), $type->visible, $type->sortorder);
632 return $types;
636 * Checks if user has a capability to view the current repository.
638 * @return bool true when the user can, otherwise throws an exception.
639 * @throws repository_exception when the user does not meet the requirements.
641 public final function check_capability() {
642 global $USER;
644 // Ensure that the user can view the repository in the current context.
645 $can = has_capability('repository/'.$this->type.':view', $this->context);
647 // Context in which the repository has been created.
648 $repocontext = context::instance_by_id($this->instance->contextid);
650 // Prevent access to private repositories when logged in as.
651 if (session_is_loggedinas()) {
652 $can = false;
655 // Ensure that the user can view the repository in the context of the repository.
656 // Ne need to perform the check when already disallowed.
657 if ($can) {
658 if ($repocontext->contextlevel == CONTEXT_USER && $repocontext->instanceid != $USER->id) {
659 // Prevent URL hijack to access someone else's repository.
660 $can = false;
661 } else {
662 $can = has_capability('repository/'.$this->type.':view', $repocontext);
666 if ($can) {
667 return true;
670 throw new repository_exception('nopermissiontoaccess', 'repository');
674 * Check if file already exists in draft area
676 * @static
677 * @param int $itemid
678 * @param string $filepath
679 * @param string $filename
680 * @return bool
682 public static function draftfile_exists($itemid, $filepath, $filename) {
683 global $USER;
684 $fs = get_file_storage();
685 $usercontext = get_context_instance(CONTEXT_USER, $USER->id);
686 if ($fs->get_file($usercontext->id, 'user', 'draft', $itemid, $filepath, $filename)) {
687 return true;
688 } else {
689 return false;
694 * Parses the 'source' returned by moodle repositories and returns an instance of stored_file
696 * @param string $source
697 * @return stored_file|null
699 public static function get_moodle_file($source) {
700 $params = file_storage::unpack_reference($source, true);
701 $fs = get_file_storage();
702 return $fs->get_file($params['contextid'], $params['component'], $params['filearea'],
703 $params['itemid'], $params['filepath'], $params['filename']);
707 * Repository method to make sure that user can access particular file.
709 * This is checked when user tries to pick the file from repository to deal with
710 * potential parameter substitutions is request
712 * @param string $source
713 * @return bool whether the file is accessible by current user
715 public function file_is_accessible($source) {
716 if ($this->has_moodle_files()) {
717 try {
718 $params = file_storage::unpack_reference($source, true);
719 } catch (file_reference_exception $e) {
720 return false;
722 $browser = get_file_browser();
723 $context = context::instance_by_id($params['contextid']);
724 $file_info = $browser->get_file_info($context, $params['component'], $params['filearea'],
725 $params['itemid'], $params['filepath'], $params['filename']);
726 return !empty($file_info);
728 return true;
732 * This function is used to copy a moodle file to draft area.
734 * It DOES NOT check if the user is allowed to access this file because the actual file
735 * can be located in the area where user does not have access to but there is an alias
736 * to this file in the area where user CAN access it.
737 * {@link file_is_accessible} should be called for alias location before calling this function.
739 * @param string $source The metainfo of file, it is base64 encoded php serialized data
740 * @param stdClass|array $filerecord contains itemid, filepath, filename and optionally other
741 * attributes of the new file
742 * @param int $maxbytes maximum allowed size of file, -1 if unlimited. If size of file exceeds
743 * the limit, the file_exception is thrown.
744 * @return array The information about the created file
746 public function copy_to_area($source, $filerecord, $maxbytes = -1) {
747 global $USER;
748 $fs = get_file_storage();
750 if ($this->has_moodle_files() == false) {
751 throw new coding_exception('Only repository used to browse moodle files can use repository::copy_to_area()');
754 $user_context = context_user::instance($USER->id);
756 $filerecord = (array)$filerecord;
757 // make sure the new file will be created in user draft area
758 $filerecord['component'] = 'user';
759 $filerecord['filearea'] = 'draft';
760 $filerecord['contextid'] = $user_context->id;
761 $draftitemid = $filerecord['itemid'];
762 $new_filepath = $filerecord['filepath'];
763 $new_filename = $filerecord['filename'];
765 // the file needs to copied to draft area
766 $stored_file = self::get_moodle_file($source);
767 if ($maxbytes != -1 && $stored_file->get_filesize() > $maxbytes) {
768 throw new file_exception('maxbytes');
771 if (repository::draftfile_exists($draftitemid, $new_filepath, $new_filename)) {
772 // create new file
773 $unused_filename = repository::get_unused_filename($draftitemid, $new_filepath, $new_filename);
774 $filerecord['filename'] = $unused_filename;
775 $fs->create_file_from_storedfile($filerecord, $stored_file);
776 $event = array();
777 $event['event'] = 'fileexists';
778 $event['newfile'] = new stdClass;
779 $event['newfile']->filepath = $new_filepath;
780 $event['newfile']->filename = $unused_filename;
781 $event['newfile']->url = moodle_url::make_draftfile_url($draftitemid, $new_filepath, $unused_filename)->out();
782 $event['existingfile'] = new stdClass;
783 $event['existingfile']->filepath = $new_filepath;
784 $event['existingfile']->filename = $new_filename;
785 $event['existingfile']->url = moodle_url::make_draftfile_url($draftitemid, $new_filepath, $new_filename)->out();
786 return $event;
787 } else {
788 $fs->create_file_from_storedfile($filerecord, $stored_file);
789 $info = array();
790 $info['itemid'] = $draftitemid;
791 $info['file'] = $new_filename;
792 $info['title'] = $new_filename;
793 $info['contextid'] = $user_context->id;
794 $info['url'] = moodle_url::make_draftfile_url($draftitemid, $new_filepath, $new_filename)->out();
795 $info['filesize'] = $stored_file->get_filesize();
796 return $info;
801 * Get unused filename by appending suffix
803 * @static
804 * @param int $itemid
805 * @param string $filepath
806 * @param string $filename
807 * @return string
809 public static function get_unused_filename($itemid, $filepath, $filename) {
810 global $USER;
811 $fs = get_file_storage();
812 while (repository::draftfile_exists($itemid, $filepath, $filename)) {
813 $filename = repository::append_suffix($filename);
815 return $filename;
819 * Append a suffix to filename
821 * @static
822 * @param string $filename
823 * @return string
825 public static function append_suffix($filename) {
826 $pathinfo = pathinfo($filename);
827 if (empty($pathinfo['extension'])) {
828 return $filename . RENAME_SUFFIX;
829 } else {
830 return $pathinfo['filename'] . RENAME_SUFFIX . '.' . $pathinfo['extension'];
835 * Return all types that you a user can create/edit and which are also visible
836 * Note: Mostly used in order to know if at least one editable type can be set
838 * @static
839 * @param stdClass $context the context for which we want the editable types
840 * @return array types
842 public static function get_editable_types($context = null) {
844 if (empty($context)) {
845 $context = get_system_context();
848 $types= repository::get_types(true);
849 $editabletypes = array();
850 foreach ($types as $type) {
851 $instanceoptionnames = repository::static_function($type->get_typename(), 'get_instance_option_names');
852 if (!empty($instanceoptionnames)) {
853 if ($type->get_contextvisibility($context)) {
854 $editabletypes[]=$type;
858 return $editabletypes;
862 * Return repository instances
864 * @static
865 * @param array $args Array containing the following keys:
866 * currentcontext
867 * context
868 * onlyvisible
869 * type
870 * accepted_types
871 * return_types
872 * userid
874 * @return array repository instances
876 public static function get_instances($args = array()) {
877 global $DB, $CFG, $USER;
879 if (isset($args['currentcontext'])) {
880 $current_context = $args['currentcontext'];
881 } else {
882 $current_context = null;
885 if (!empty($args['context'])) {
886 $contexts = $args['context'];
887 } else {
888 $contexts = array();
891 $onlyvisible = isset($args['onlyvisible']) ? $args['onlyvisible'] : true;
892 $returntypes = isset($args['return_types']) ? $args['return_types'] : 3;
893 $type = isset($args['type']) ? $args['type'] : null;
895 $params = array();
896 $sql = "SELECT i.*, r.type AS repositorytype, r.sortorder, r.visible
897 FROM {repository} r, {repository_instances} i
898 WHERE i.typeid = r.id ";
900 if (!empty($args['disable_types']) && is_array($args['disable_types'])) {
901 list($types, $p) = $DB->get_in_or_equal($args['disable_types'], SQL_PARAMS_QM, 'param', false);
902 $sql .= " AND r.type $types";
903 $params = array_merge($params, $p);
906 if (!empty($args['userid']) && is_numeric($args['userid'])) {
907 $sql .= " AND (i.userid = 0 or i.userid = ?)";
908 $params[] = $args['userid'];
911 foreach ($contexts as $context) {
912 if (empty($firstcontext)) {
913 $firstcontext = true;
914 $sql .= " AND ((i.contextid = ?)";
915 } else {
916 $sql .= " OR (i.contextid = ?)";
918 $params[] = $context->id;
921 if (!empty($firstcontext)) {
922 $sql .=')';
925 if ($onlyvisible == true) {
926 $sql .= " AND (r.visible = 1)";
929 if (isset($type)) {
930 $sql .= " AND (r.type = ?)";
931 $params[] = $type;
933 $sql .= " ORDER BY r.sortorder, i.name";
935 if (!$records = $DB->get_records_sql($sql, $params)) {
936 $records = array();
939 $repositories = array();
940 if (isset($args['accepted_types'])) {
941 $accepted_types = $args['accepted_types'];
942 if (is_array($accepted_types) && in_array('*', $accepted_types)) {
943 $accepted_types = '*';
945 } else {
946 $accepted_types = '*';
948 // Sortorder should be unique, which is not true if we use $record->sortorder
949 // and there are multiple instances of any repository type
950 $sortorder = 1;
951 foreach ($records as $record) {
952 if (!file_exists($CFG->dirroot . '/repository/'. $record->repositorytype.'/lib.php')) {
953 continue;
955 require_once($CFG->dirroot . '/repository/'. $record->repositorytype.'/lib.php');
956 $options['visible'] = $record->visible;
957 $options['type'] = $record->repositorytype;
958 $options['typeid'] = $record->typeid;
959 $options['sortorder'] = $sortorder++;
960 // tell instance what file types will be accepted by file picker
961 $classname = 'repository_' . $record->repositorytype;
963 $repository = new $classname($record->id, $record->contextid, $options, $record->readonly);
965 $is_supported = true;
967 if (empty($repository->super_called)) {
968 // to make sure the super construct is called
969 debugging('parent::__construct must be called by '.$record->repositorytype.' plugin.');
970 } else {
971 // check mimetypes
972 if ($accepted_types !== '*' and $repository->supported_filetypes() !== '*') {
973 $accepted_ext = file_get_typegroup('extension', $accepted_types);
974 $supported_ext = file_get_typegroup('extension', $repository->supported_filetypes());
975 $valid_ext = array_intersect($accepted_ext, $supported_ext);
976 $is_supported = !empty($valid_ext);
978 // check return values
979 if ($returntypes !== 3 and $repository->supported_returntypes() !== 3) {
980 $type = $repository->supported_returntypes();
981 if ($type & $returntypes) {
983 } else {
984 $is_supported = false;
988 if (!$onlyvisible || ($repository->is_visible() && !$repository->disabled)) {
989 // check capability in current context
990 if (!empty($current_context)) {
991 $capability = has_capability('repository/'.$record->repositorytype.':view', $current_context);
992 } else {
993 $capability = has_capability('repository/'.$record->repositorytype.':view', get_system_context());
995 if ($record->repositorytype == 'coursefiles') {
996 // coursefiles plugin needs managefiles permission
997 if (!empty($current_context)) {
998 $capability = $capability && has_capability('moodle/course:managefiles', $current_context);
999 } else {
1000 $capability = $capability && has_capability('moodle/course:managefiles', get_system_context());
1003 if ($is_supported && $capability) {
1004 $repositories[$repository->id] = $repository;
1009 return $repositories;
1013 * Get single repository instance
1015 * @static
1016 * @param integer $id repository id
1017 * @return object repository instance
1019 public static function get_instance($id) {
1020 global $DB, $CFG;
1021 $sql = "SELECT i.*, r.type AS repositorytype, r.visible
1022 FROM {repository} r
1023 JOIN {repository_instances} i ON i.typeid = r.id
1024 WHERE i.id = ?";
1026 if (!$instance = $DB->get_record_sql($sql, array($id))) {
1027 return false;
1029 require_once($CFG->dirroot . '/repository/'. $instance->repositorytype.'/lib.php');
1030 $classname = 'repository_' . $instance->repositorytype;
1031 $options['typeid'] = $instance->typeid;
1032 $options['type'] = $instance->repositorytype;
1033 $options['name'] = $instance->name;
1034 $obj = new $classname($instance->id, $instance->contextid, $options, $instance->readonly);
1035 if (empty($obj->super_called)) {
1036 debugging('parent::__construct must be called by '.$classname.' plugin.');
1038 return $obj;
1042 * Call a static function. Any additional arguments than plugin and function will be passed through.
1044 * @static
1045 * @param string $plugin repository plugin name
1046 * @param string $function funciton name
1047 * @return mixed
1049 public static function static_function($plugin, $function) {
1050 global $CFG;
1052 //check that the plugin exists
1053 $typedirectory = $CFG->dirroot . '/repository/'. $plugin . '/lib.php';
1054 if (!file_exists($typedirectory)) {
1055 //throw new repository_exception('invalidplugin', 'repository');
1056 return false;
1059 $pname = null;
1060 if (is_object($plugin) || is_array($plugin)) {
1061 $plugin = (object)$plugin;
1062 $pname = $plugin->name;
1063 } else {
1064 $pname = $plugin;
1067 $args = func_get_args();
1068 if (count($args) <= 2) {
1069 $args = array();
1070 } else {
1071 array_shift($args);
1072 array_shift($args);
1075 require_once($typedirectory);
1076 return call_user_func_array(array('repository_' . $plugin, $function), $args);
1080 * Scan file, throws exception in case of infected file.
1082 * Please note that the scanning engine must be able to access the file,
1083 * permissions of the file are not modified here!
1085 * @static
1086 * @param string $thefile
1087 * @param string $filename name of the file
1088 * @param bool $deleteinfected
1090 public static function antivir_scan_file($thefile, $filename, $deleteinfected) {
1091 global $CFG;
1093 if (!is_readable($thefile)) {
1094 // this should not happen
1095 return;
1098 if (empty($CFG->runclamonupload) or empty($CFG->pathtoclam)) {
1099 // clam not enabled
1100 return;
1103 $CFG->pathtoclam = trim($CFG->pathtoclam);
1105 if (!file_exists($CFG->pathtoclam) or !is_executable($CFG->pathtoclam)) {
1106 // misconfigured clam - use the old notification for now
1107 require("$CFG->libdir/uploadlib.php");
1108 $notice = get_string('clamlost', 'moodle', $CFG->pathtoclam);
1109 clam_message_admins($notice);
1110 return;
1113 // do NOT mess with permissions here, the calling party is responsible for making
1114 // sure the scanner engine can access the files!
1116 // execute test
1117 $cmd = escapeshellcmd($CFG->pathtoclam).' --stdout '.escapeshellarg($thefile);
1118 exec($cmd, $output, $return);
1120 if ($return == 0) {
1121 // perfect, no problem found
1122 return;
1124 } else if ($return == 1) {
1125 // infection found
1126 if ($deleteinfected) {
1127 unlink($thefile);
1129 throw new moodle_exception('virusfounduser', 'moodle', '', array('filename'=>$filename));
1131 } else {
1132 //unknown problem
1133 require("$CFG->libdir/uploadlib.php");
1134 $notice = get_string('clamfailed', 'moodle', get_clam_error_code($return));
1135 $notice .= "\n\n". implode("\n", $output);
1136 clam_message_admins($notice);
1137 if ($CFG->clamfailureonupload === 'actlikevirus') {
1138 if ($deleteinfected) {
1139 unlink($thefile);
1141 throw new moodle_exception('virusfounduser', 'moodle', '', array('filename'=>$filename));
1142 } else {
1143 return;
1149 * Repository method to serve the referenced file
1151 * @see send_stored_file
1153 * @param stored_file $storedfile the file that contains the reference
1154 * @param int $lifetime Number of seconds before the file should expire from caches (default 24 hours)
1155 * @param int $filter 0 (default)=no filtering, 1=all files, 2=html files only
1156 * @param bool $forcedownload If true (default false), forces download of file rather than view in browser/plugin
1157 * @param array $options additional options affecting the file serving
1159 public function send_file($storedfile, $lifetime=86400 , $filter=0, $forcedownload=false, array $options = null) {
1160 if ($this->has_moodle_files()) {
1161 $fs = get_file_storage();
1162 $params = file_storage::unpack_reference($storedfile->get_reference(), true);
1163 $srcfile = null;
1164 if (is_array($params)) {
1165 $srcfile = $fs->get_file($params['contextid'], $params['component'], $params['filearea'],
1166 $params['itemid'], $params['filepath'], $params['filename']);
1168 if (empty($options)) {
1169 $options = array();
1171 if (!isset($options['filename'])) {
1172 $options['filename'] = $storedfile->get_filename();
1174 if (!$srcfile) {
1175 send_file_not_found();
1176 } else {
1177 send_stored_file($srcfile, $lifetime, $filter, $forcedownload, $options);
1179 } else {
1180 throw new coding_exception("Repository plugin must implement send_file() method.");
1185 * Return reference file life time
1187 * @param string $ref
1188 * @return int
1190 public function get_reference_file_lifetime($ref) {
1191 // One day
1192 return 60 * 60 * 24;
1196 * Decide whether or not the file should be synced
1198 * @param stored_file $storedfile
1199 * @return bool
1201 public function sync_individual_file(stored_file $storedfile) {
1202 return true;
1206 * Return human readable reference information
1208 * @param string $reference value of DB field files_reference.reference
1209 * @param int $filestatus status of the file, 0 - ok, 666 - source missing
1210 * @return string
1212 public function get_reference_details($reference, $filestatus = 0) {
1213 if ($this->has_moodle_files()) {
1214 $fileinfo = null;
1215 $params = file_storage::unpack_reference($reference, true);
1216 if (is_array($params)) {
1217 $context = get_context_instance_by_id($params['contextid']);
1218 if ($context) {
1219 $browser = get_file_browser();
1220 $fileinfo = $browser->get_file_info($context, $params['component'], $params['filearea'], $params['itemid'], $params['filepath'], $params['filename']);
1223 if (empty($fileinfo)) {
1224 if ($filestatus == 666) {
1225 if (is_siteadmin() || ($context && has_capability('moodle/course:managefiles', $context))) {
1226 return get_string('lostsource', 'repository',
1227 $params['contextid']. '/'. $params['component']. '/'. $params['filearea']. '/'. $params['itemid']. $params['filepath']. $params['filename']);
1228 } else {
1229 return get_string('lostsource', 'repository', '');
1232 return get_string('undisclosedsource', 'repository');
1233 } else {
1234 return $fileinfo->get_readable_fullname();
1237 return '';
1241 * Cache file from external repository by reference
1242 * {@link repository::get_file_reference()}
1243 * {@link repository::get_file()}
1244 * Invoked at MOODLE/repository/repository_ajax.php
1246 * @param string $reference this reference is generated by
1247 * repository::get_file_reference()
1248 * @param stored_file $storedfile created file reference
1250 public function cache_file_by_reference($reference, $storedfile) {
1254 * Returns information about file in this repository by reference
1256 * This function must be implemented for repositories supporting FILE_REFERENCE, it is called
1257 * for existing aliases when the lifetime of the previous syncronisation has expired.
1259 * Returns null if file not found or is not readable or timeout occured during request.
1260 * Note that this function may be run for EACH file that needs to be synchronised at the
1261 * moment. If anything is being downloaded or requested from external sources there
1262 * should be a small timeout. The synchronisation is performed to update the size of
1263 * the file and/or to update image and re-generated image preview. There is nothing
1264 * fatal if syncronisation fails but it is fatal if syncronisation takes too long
1265 * and hangs the script generating a page.
1267 * If get_file_by_reference() returns filesize just the record in {files} table is being updated.
1268 * If filepath, handle or content are returned - the file is also stored in moodle filepool
1269 * (recommended for images to generate the thumbnails). For non-image files it is not
1270 * recommended to download them to moodle during syncronisation since it may take
1271 * unnecessary long time.
1273 * @param stdClass $reference record from DB table {files_reference}
1274 * @return stdClass|null contains one of the following:
1275 * - 'filesize' and optionally 'contenthash'
1276 * - 'filepath'
1277 * - 'handle'
1278 * - 'content'
1280 public function get_file_by_reference($reference) {
1281 if ($this->has_moodle_files() && isset($reference->reference)) {
1282 $fs = get_file_storage();
1283 $params = file_storage::unpack_reference($reference->reference, true);
1284 if (!is_array($params) || !($storedfile = $fs->get_file($params['contextid'],
1285 $params['component'], $params['filearea'], $params['itemid'], $params['filepath'],
1286 $params['filename']))) {
1287 return null;
1289 return (object)array(
1290 'contenthash' => $storedfile->get_contenthash(),
1291 'filesize' => $storedfile->get_filesize()
1294 return null;
1298 * Return the source information
1300 * The result of the function is stored in files.source field. It may be analysed
1301 * when the source file is lost or repository may use it to display human-readable
1302 * location of reference original.
1304 * This method is called when file is picked for the first time only. When file
1305 * (either copy or a reference) is already in moodle and it is being picked
1306 * again to another file area (also as a copy or as a reference), the value of
1307 * files.source is copied.
1309 * @param string $source the value that repository returned in listing as 'source'
1310 * @return string|null
1312 public function get_file_source_info($source) {
1313 if ($this->has_moodle_files()) {
1314 return $this->get_reference_details($source, 0);
1316 return $source;
1320 * Move file from download folder to file pool using FILE API
1322 * @todo MDL-28637
1323 * @static
1324 * @param string $thefile file path in download folder
1325 * @param stdClass $record
1326 * @return array containing the following keys:
1327 * icon
1328 * file
1329 * id
1330 * url
1332 public static function move_to_filepool($thefile, $record) {
1333 global $DB, $CFG, $USER, $OUTPUT;
1335 // scan for viruses if possible, throws exception if problem found
1336 self::antivir_scan_file($thefile, $record->filename, empty($CFG->repository_no_delete)); //TODO: MDL-28637 this repository_no_delete is a bloody hack!
1338 $fs = get_file_storage();
1339 // If file name being used.
1340 if (repository::draftfile_exists($record->itemid, $record->filepath, $record->filename)) {
1341 $draftitemid = $record->itemid;
1342 $new_filename = repository::get_unused_filename($draftitemid, $record->filepath, $record->filename);
1343 $old_filename = $record->filename;
1344 // Create a tmp file.
1345 $record->filename = $new_filename;
1346 $newfile = $fs->create_file_from_pathname($record, $thefile);
1347 $event = array();
1348 $event['event'] = 'fileexists';
1349 $event['newfile'] = new stdClass;
1350 $event['newfile']->filepath = $record->filepath;
1351 $event['newfile']->filename = $new_filename;
1352 $event['newfile']->url = moodle_url::make_draftfile_url($draftitemid, $record->filepath, $new_filename)->out();
1354 $event['existingfile'] = new stdClass;
1355 $event['existingfile']->filepath = $record->filepath;
1356 $event['existingfile']->filename = $old_filename;
1357 $event['existingfile']->url = moodle_url::make_draftfile_url($draftitemid, $record->filepath, $old_filename)->out();;
1358 return $event;
1360 if ($file = $fs->create_file_from_pathname($record, $thefile)) {
1361 if (empty($CFG->repository_no_delete)) {
1362 $delete = unlink($thefile);
1363 unset($CFG->repository_no_delete);
1365 return array(
1366 'url'=>moodle_url::make_draftfile_url($file->get_itemid(), $file->get_filepath(), $file->get_filename())->out(),
1367 'id'=>$file->get_itemid(),
1368 'file'=>$file->get_filename(),
1369 'icon' => $OUTPUT->pix_url(file_extension_icon($thefile, 32))->out(),
1371 } else {
1372 return null;
1377 * Builds a tree of files This function is then called recursively.
1379 * @static
1380 * @todo take $search into account, and respect a threshold for dynamic loading
1381 * @param file_info $fileinfo an object returned by file_browser::get_file_info()
1382 * @param string $search searched string
1383 * @param bool $dynamicmode no recursive call is done when in dynamic mode
1384 * @param array $list the array containing the files under the passed $fileinfo
1385 * @return int the number of files found
1387 public static function build_tree($fileinfo, $search, $dynamicmode, &$list) {
1388 global $CFG, $OUTPUT;
1390 $filecount = 0;
1391 $children = $fileinfo->get_children();
1393 foreach ($children as $child) {
1394 $filename = $child->get_visible_name();
1395 $filesize = $child->get_filesize();
1396 $filesize = $filesize ? display_size($filesize) : '';
1397 $filedate = $child->get_timemodified();
1398 $filedate = $filedate ? userdate($filedate) : '';
1399 $filetype = $child->get_mimetype();
1401 if ($child->is_directory()) {
1402 $path = array();
1403 $level = $child->get_parent();
1404 while ($level) {
1405 $params = $level->get_params();
1406 $path[] = array($params['filepath'], $level->get_visible_name());
1407 $level = $level->get_parent();
1410 $tmp = array(
1411 'title' => $child->get_visible_name(),
1412 'size' => 0,
1413 'date' => $filedate,
1414 'path' => array_reverse($path),
1415 'thumbnail' => $OUTPUT->pix_url(file_folder_icon(90))->out(false)
1418 //if ($dynamicmode && $child->is_writable()) {
1419 // $tmp['children'] = array();
1420 //} else {
1421 // if folder name matches search, we send back all files contained.
1422 $_search = $search;
1423 if ($search && stristr($tmp['title'], $search) !== false) {
1424 $_search = false;
1426 $tmp['children'] = array();
1427 $_filecount = repository::build_tree($child, $_search, $dynamicmode, $tmp['children']);
1428 if ($search && $_filecount) {
1429 $tmp['expanded'] = 1;
1434 if (!$search || $_filecount || (stristr($tmp['title'], $search) !== false)) {
1435 $filecount += $_filecount;
1436 $list[] = $tmp;
1439 } else { // not a directory
1440 // skip the file, if we're in search mode and it's not a match
1441 if ($search && (stristr($filename, $search) === false)) {
1442 continue;
1444 $params = $child->get_params();
1445 $source = serialize(array($params['contextid'], $params['component'], $params['filearea'], $params['itemid'], $params['filepath'], $params['filename']));
1446 $list[] = array(
1447 'title' => $filename,
1448 'size' => $filesize,
1449 'date' => $filedate,
1450 //'source' => $child->get_url(),
1451 'source' => base64_encode($source),
1452 'icon'=>$OUTPUT->pix_url(file_file_icon($child, 24))->out(false),
1453 'thumbnail'=>$OUTPUT->pix_url(file_file_icon($child, 90))->out(false),
1455 $filecount++;
1459 return $filecount;
1463 * Display a repository instance list (with edit/delete/create links)
1465 * @static
1466 * @param stdClass $context the context for which we display the instance
1467 * @param string $typename if set, we display only one type of instance
1469 public static function display_instances_list($context, $typename = null) {
1470 global $CFG, $USER, $OUTPUT;
1472 $output = $OUTPUT->box_start('generalbox');
1473 //if the context is SYSTEM, so we call it from administration page
1474 $admin = ($context->id == SYSCONTEXTID) ? true : false;
1475 if ($admin) {
1476 $baseurl = new moodle_url('/'.$CFG->admin.'/repositoryinstance.php', array('sesskey'=>sesskey()));
1477 $output .= $OUTPUT->heading(get_string('siteinstances', 'repository'));
1478 } else {
1479 $baseurl = new moodle_url('/repository/manage_instances.php', array('contextid'=>$context->id, 'sesskey'=>sesskey()));
1482 $namestr = get_string('name');
1483 $pluginstr = get_string('plugin', 'repository');
1484 $settingsstr = get_string('settings');
1485 $deletestr = get_string('delete');
1486 //retrieve list of instances. In administration context we want to display all
1487 //instances of a type, even if this type is not visible. In course/user context we
1488 //want to display only visible instances, but for every type types. The repository::get_instances()
1489 //third parameter displays only visible type.
1490 $params = array();
1491 $params['context'] = array($context);
1492 $params['currentcontext'] = $context;
1493 $params['onlyvisible'] = !$admin;
1494 $params['type'] = $typename;
1495 $instances = repository::get_instances($params);
1496 $instancesnumber = count($instances);
1497 $alreadyplugins = array();
1499 $table = new html_table();
1500 $table->head = array($namestr, $pluginstr, $settingsstr, $deletestr);
1501 $table->align = array('left', 'left', 'center','center');
1502 $table->data = array();
1504 $updowncount = 1;
1506 foreach ($instances as $i) {
1507 $settings = '';
1508 $delete = '';
1510 $type = repository::get_type_by_id($i->options['typeid']);
1512 if ($type->get_contextvisibility($context)) {
1513 if (!$i->readonly) {
1515 $settingurl = new moodle_url($baseurl);
1516 $settingurl->param('type', $i->options['type']);
1517 $settingurl->param('edit', $i->id);
1518 $settings .= html_writer::link($settingurl, $settingsstr);
1520 $deleteurl = new moodle_url($baseurl);
1521 $deleteurl->param('delete', $i->id);
1522 $deleteurl->param('type', $i->options['type']);
1523 $delete .= html_writer::link($deleteurl, $deletestr);
1527 $type = repository::get_type_by_id($i->options['typeid']);
1528 $table->data[] = array(format_string($i->name), $type->get_readablename(), $settings, $delete);
1530 //display a grey row if the type is defined as not visible
1531 if (isset($type) && !$type->get_visible()) {
1532 $table->rowclasses[] = 'dimmed_text';
1533 } else {
1534 $table->rowclasses[] = '';
1537 if (!in_array($i->name, $alreadyplugins)) {
1538 $alreadyplugins[] = $i->name;
1541 $output .= html_writer::table($table);
1542 $instancehtml = '<div>';
1543 $addable = 0;
1545 //if no type is set, we can create all type of instance
1546 if (!$typename) {
1547 $instancehtml .= '<h3>';
1548 $instancehtml .= get_string('createrepository', 'repository');
1549 $instancehtml .= '</h3><ul>';
1550 $types = repository::get_editable_types($context);
1551 foreach ($types as $type) {
1552 if (!empty($type) && $type->get_visible()) {
1553 // If the user does not have the permission to view the repository, it won't be displayed in
1554 // the list of instances. Hiding the link to create new instances will prevent the
1555 // user from creating them without being able to find them afterwards, which looks like a bug.
1556 if (!has_capability('repository/'.$type->get_typename().':view', $context)) {
1557 continue;
1559 $instanceoptionnames = repository::static_function($type->get_typename(), 'get_instance_option_names');
1560 if (!empty($instanceoptionnames)) {
1561 $baseurl->param('new', $type->get_typename());
1562 $instancehtml .= '<li><a href="'.$baseurl->out().'">'.get_string('createxxinstance', 'repository', get_string('pluginname', 'repository_'.$type->get_typename())). '</a></li>';
1563 $baseurl->remove_params('new');
1564 $addable++;
1568 $instancehtml .= '</ul>';
1570 } else {
1571 $instanceoptionnames = repository::static_function($typename, 'get_instance_option_names');
1572 if (!empty($instanceoptionnames)) { //create a unique type of instance
1573 $addable = 1;
1574 $baseurl->param('new', $typename);
1575 $output .= $OUTPUT->single_button($baseurl, get_string('createinstance', 'repository'), 'get');
1576 $baseurl->remove_params('new');
1580 if ($addable) {
1581 $instancehtml .= '</div>';
1582 $output .= $instancehtml;
1585 $output .= $OUTPUT->box_end();
1587 //print the list + creation links
1588 print($output);
1592 * Prepare file reference information
1594 * @param string $source
1595 * @return string file referece
1597 public function get_file_reference($source) {
1598 if ($this->has_moodle_files() && ($this->supported_returntypes() & FILE_REFERENCE)) {
1599 $params = file_storage::unpack_reference($source);
1600 if (!is_array($params)) {
1601 throw new repository_exception('invalidparams', 'repository');
1603 return file_storage::pack_reference($params);
1605 return $source;
1609 * Decide where to save the file, can be overwriten by subclass
1611 * @param string $filename file name
1612 * @return file path
1614 public function prepare_file($filename) {
1615 global $CFG;
1616 $dir = make_temp_directory('download/'.get_class($this).'/');
1617 while (empty($filename) || file_exists($dir.$filename)) {
1618 $filename = uniqid('', true).'_'.time().'.tmp';
1620 return $dir.$filename;
1624 * Does this repository used to browse moodle files?
1626 * @return bool
1628 public function has_moodle_files() {
1629 return false;
1633 * Return file URL, for most plugins, the parameter is the original
1634 * url, but some plugins use a file id, so we need this function to
1635 * convert file id to original url.
1637 * @param string $url the url of file
1638 * @return string
1640 public function get_link($url) {
1641 return $url;
1645 * Downloads a file from external repository and saves it in temp dir
1647 * Function get_file() must be implemented by repositories that support returntypes
1648 * FILE_INTERNAL or FILE_REFERENCE. It is invoked to pick up the file and copy it
1649 * to moodle. This function is not called for moodle repositories, the function
1650 * {@link repository::copy_to_area()} is used instead.
1652 * This function can be overridden by subclass if the files.reference field contains
1653 * not just URL or if request should be done differently.
1655 * @see curl
1656 * @throws file_exception when error occured
1658 * @param string $url the content of files.reference field, in this implementaion
1659 * it is asssumed that it contains the string with URL of the file
1660 * @param string $filename filename (without path) to save the downloaded file in the
1661 * temporary directory, if omitted or file already exists the new filename will be generated
1662 * @return array with elements:
1663 * path: internal location of the file
1664 * url: URL to the source (from parameters)
1666 public function get_file($url, $filename = '') {
1667 $path = $this->prepare_file($filename);
1668 $c = new curl;
1669 $result = $c->download_one($url, null, array('filepath' => $path, 'timeout' => self::GETFILE_TIMEOUT));
1670 if ($result !== true) {
1671 throw new moodle_exception('errorwhiledownload', 'repository', '', $result);
1673 return array('path'=>$path, 'url'=>$url);
1677 * Downloads the file from external repository and saves it in moodle filepool.
1678 * This function is different from {@link repository::sync_external_file()} because it has
1679 * bigger request timeout and always downloads the content.
1681 * This function is invoked when we try to unlink the file from the source and convert
1682 * a reference into a true copy.
1684 * @throws exception when file could not be imported
1686 * @param stored_file $file
1687 * @param int $maxbytes throw an exception if file size is bigger than $maxbytes (0 means no limit)
1689 public function import_external_file_contents(stored_file $file, $maxbytes = 0) {
1690 if (!$file->is_external_file()) {
1691 // nothing to import if the file is not a reference
1692 return;
1693 } else if ($file->get_repository_id() != $this->id) {
1694 // error
1695 debugging('Repository instance id does not match');
1696 return;
1697 } else if ($this->has_moodle_files()) {
1698 // files that are references to local files are already in moodle filepool
1699 // just validate the size
1700 if ($maxbytes > 0 && $file->get_filesize() > $maxbytes) {
1701 throw new file_exception('maxbytes');
1703 return;
1704 } else {
1705 if ($maxbytes > 0 && $file->get_filesize() > $maxbytes) {
1706 // note that stored_file::get_filesize() also calls synchronisation
1707 throw new file_exception('maxbytes');
1709 $fs = get_file_storage();
1710 $contentexists = $fs->content_exists($file->get_contenthash());
1711 if ($contentexists && $file->get_filesize() && $file->get_contenthash() === sha1('')) {
1712 // even when 'file_storage::content_exists()' returns true this may be an empty
1713 // content for the file that was not actually downloaded
1714 $contentexists = false;
1716 $now = time();
1717 if ($file->get_referencelastsync() + $file->get_referencelifetime() >= $now &&
1718 !$file->get_status() &&
1719 $contentexists) {
1720 // we already have the content in moodle filepool and it was synchronised recently.
1721 // Repositories may overwrite it if they want to force synchronisation anyway!
1722 return;
1723 } else {
1724 // attempt to get a file
1725 try {
1726 $fileinfo = $this->get_file($file->get_reference());
1727 if (isset($fileinfo['path'])) {
1728 list($contenthash, $filesize, $newfile) = $fs->add_file_to_pool($fileinfo['path']);
1729 // set this file and other similar aliases synchronised
1730 $lifetime = $this->get_reference_file_lifetime($file->get_reference());
1731 $file->set_synchronized($contenthash, $filesize, 0, $lifetime);
1732 } else {
1733 throw new moodle_exception('errorwhiledownload', 'repository', '', '');
1735 } catch (Exception $e) {
1736 if ($contentexists) {
1737 // better something than nothing. We have a copy of file. It's sync time
1738 // has expired but it is still very likely that it is the last version
1739 } else {
1740 throw($e);
1748 * Return size of a file in bytes.
1750 * @param string $source encoded and serialized data of file
1751 * @return int file size in bytes
1753 public function get_file_size($source) {
1754 // TODO MDL-33297 remove this function completely?
1755 $browser = get_file_browser();
1756 $params = unserialize(base64_decode($source));
1757 $contextid = clean_param($params['contextid'], PARAM_INT);
1758 $fileitemid = clean_param($params['itemid'], PARAM_INT);
1759 $filename = clean_param($params['filename'], PARAM_FILE);
1760 $filepath = clean_param($params['filepath'], PARAM_PATH);
1761 $filearea = clean_param($params['filearea'], PARAM_AREA);
1762 $component = clean_param($params['component'], PARAM_COMPONENT);
1763 $context = get_context_instance_by_id($contextid);
1764 $file_info = $browser->get_file_info($context, $component, $filearea, $fileitemid, $filepath, $filename);
1765 if (!empty($file_info)) {
1766 $filesize = $file_info->get_filesize();
1767 } else {
1768 $filesize = null;
1770 return $filesize;
1774 * Return is the instance is visible
1775 * (is the type visible ? is the context enable ?)
1777 * @return bool
1779 public function is_visible() {
1780 $type = repository::get_type_by_id($this->options['typeid']);
1781 $instanceoptions = repository::static_function($type->get_typename(), 'get_instance_option_names');
1783 if ($type->get_visible()) {
1784 //if the instance is unique so it's visible, otherwise check if the instance has a enabled context
1785 if (empty($instanceoptions) || $type->get_contextvisibility($this->context)) {
1786 return true;
1790 return false;
1794 * Return the name of this instance, can be overridden.
1796 * @return string
1798 public function get_name() {
1799 global $DB;
1800 if ( $name = $this->instance->name ) {
1801 return $name;
1802 } else {
1803 return get_string('pluginname', 'repository_' . $this->options['type']);
1808 * What kind of files will be in this repository?
1810 * @return array return '*' means this repository support any files, otherwise
1811 * return mimetypes of files, it can be an array
1813 public function supported_filetypes() {
1814 // return array('text/plain', 'image/gif');
1815 return '*';
1819 * Tells how the file can be picked from this repository
1821 * Maximum value is FILE_INTERNAL | FILE_EXTERNAL | FILE_REFERENCE
1823 * @return int
1825 public function supported_returntypes() {
1826 return (FILE_INTERNAL | FILE_EXTERNAL);
1830 * Provide repository instance information for Ajax
1832 * @return stdClass
1834 final public function get_meta() {
1835 global $CFG, $OUTPUT;
1836 $meta = new stdClass();
1837 $meta->id = $this->id;
1838 $meta->name = format_string($this->get_name());
1839 $meta->type = $this->options['type'];
1840 $meta->icon = $OUTPUT->pix_url('icon', 'repository_'.$meta->type)->out(false);
1841 $meta->supported_types = file_get_typegroup('extension', $this->supported_filetypes());
1842 $meta->return_types = $this->supported_returntypes();
1843 $meta->sortorder = $this->options['sortorder'];
1844 return $meta;
1848 * Create an instance for this plug-in
1850 * @static
1851 * @param string $type the type of the repository
1852 * @param int $userid the user id
1853 * @param stdClass $context the context
1854 * @param array $params the options for this instance
1855 * @param int $readonly whether to create it readonly or not (defaults to not)
1856 * @return mixed
1858 public static function create($type, $userid, $context, $params, $readonly=0) {
1859 global $CFG, $DB;
1860 $params = (array)$params;
1861 require_once($CFG->dirroot . '/repository/'. $type . '/lib.php');
1862 $classname = 'repository_' . $type;
1863 if ($repo = $DB->get_record('repository', array('type'=>$type))) {
1864 $record = new stdClass();
1865 $record->name = $params['name'];
1866 $record->typeid = $repo->id;
1867 $record->timecreated = time();
1868 $record->timemodified = time();
1869 $record->contextid = $context->id;
1870 $record->readonly = $readonly;
1871 $record->userid = $userid;
1872 $id = $DB->insert_record('repository_instances', $record);
1873 $options = array();
1874 $configs = call_user_func($classname . '::get_instance_option_names');
1875 if (!empty($configs)) {
1876 foreach ($configs as $config) {
1877 if (isset($params[$config])) {
1878 $options[$config] = $params[$config];
1879 } else {
1880 $options[$config] = null;
1885 if (!empty($id)) {
1886 unset($options['name']);
1887 $instance = repository::get_instance($id);
1888 $instance->set_option($options);
1889 return $id;
1890 } else {
1891 return null;
1893 } else {
1894 return null;
1899 * delete a repository instance
1901 * @param bool $downloadcontents
1902 * @return bool
1904 final public function delete($downloadcontents = false) {
1905 global $DB;
1906 if ($downloadcontents) {
1907 $this->convert_references_to_local();
1909 try {
1910 $DB->delete_records('repository_instances', array('id'=>$this->id));
1911 $DB->delete_records('repository_instance_config', array('instanceid'=>$this->id));
1912 } catch (dml_exception $ex) {
1913 return false;
1915 return true;
1919 * Hide/Show a repository
1921 * @param string $hide
1922 * @return bool
1924 final public function hide($hide = 'toggle') {
1925 global $DB;
1926 if ($entry = $DB->get_record('repository', array('id'=>$this->id))) {
1927 if ($hide === 'toggle' ) {
1928 if (!empty($entry->visible)) {
1929 $entry->visible = 0;
1930 } else {
1931 $entry->visible = 1;
1933 } else {
1934 if (!empty($hide)) {
1935 $entry->visible = 0;
1936 } else {
1937 $entry->visible = 1;
1940 return $DB->update_record('repository', $entry);
1942 return false;
1946 * Save settings for repository instance
1947 * $repo->set_option(array('api_key'=>'f2188bde132', 'name'=>'dongsheng'));
1949 * @param array $options settings
1950 * @return bool
1952 public function set_option($options = array()) {
1953 global $DB;
1955 if (!empty($options['name'])) {
1956 $r = new stdClass();
1957 $r->id = $this->id;
1958 $r->name = $options['name'];
1959 $DB->update_record('repository_instances', $r);
1960 unset($options['name']);
1962 foreach ($options as $name=>$value) {
1963 if ($id = $DB->get_field('repository_instance_config', 'id', array('name'=>$name, 'instanceid'=>$this->id))) {
1964 $DB->set_field('repository_instance_config', 'value', $value, array('id'=>$id));
1965 } else {
1966 $config = new stdClass();
1967 $config->instanceid = $this->id;
1968 $config->name = $name;
1969 $config->value = $value;
1970 $DB->insert_record('repository_instance_config', $config);
1973 return true;
1977 * Get settings for repository instance
1979 * @param string $config
1980 * @return array Settings
1982 public function get_option($config = '') {
1983 global $DB;
1984 $entries = $DB->get_records('repository_instance_config', array('instanceid'=>$this->id));
1985 $ret = array();
1986 if (empty($entries)) {
1987 return $ret;
1989 foreach($entries as $entry) {
1990 $ret[$entry->name] = $entry->value;
1992 if (!empty($config)) {
1993 if (isset($ret[$config])) {
1994 return $ret[$config];
1995 } else {
1996 return null;
1998 } else {
1999 return $ret;
2004 * Filter file listing to display specific types
2006 * @param array $value
2007 * @return bool
2009 public function filter(&$value) {
2010 $accepted_types = optional_param_array('accepted_types', '', PARAM_RAW);
2011 if (isset($value['children'])) {
2012 if (!empty($value['children'])) {
2013 $value['children'] = array_filter($value['children'], array($this, 'filter'));
2015 return true; // always return directories
2016 } else {
2017 if ($accepted_types == '*' or empty($accepted_types)
2018 or (is_array($accepted_types) and in_array('*', $accepted_types))) {
2019 return true;
2020 } else {
2021 foreach ($accepted_types as $ext) {
2022 if (preg_match('#'.$ext.'$#i', $value['title'])) {
2023 return true;
2028 return false;
2032 * Given a path, and perhaps a search, get a list of files.
2034 * See details on {@link http://docs.moodle.org/dev/Repository_plugins}
2036 * @param string $path this parameter can a folder name, or a identification of folder
2037 * @param string $page the page number of file list
2038 * @return array the list of files, including meta infomation, containing the following keys
2039 * manage, url to manage url
2040 * client_id
2041 * login, login form
2042 * repo_id, active repository id
2043 * login_btn_action, the login button action
2044 * login_btn_label, the login button label
2045 * total, number of results
2046 * perpage, items per page
2047 * page
2048 * pages, total pages
2049 * issearchresult, is it a search result?
2050 * list, file list
2051 * path, current path and parent path
2053 public function get_listing($path = '', $page = '') {
2058 * Prepare the breadcrumb.
2060 * @param array $breadcrumb contains each element of the breadcrumb.
2061 * @return array of breadcrumb elements.
2062 * @since 2.3.3
2064 protected static function prepare_breadcrumb($breadcrumb) {
2065 global $OUTPUT;
2066 $foldericon = $OUTPUT->pix_url(file_folder_icon(24))->out(false);
2067 $len = count($breadcrumb);
2068 for ($i = 0; $i < $len; $i++) {
2069 if (is_array($breadcrumb[$i]) && !isset($breadcrumb[$i]['icon'])) {
2070 $breadcrumb[$i]['icon'] = $foldericon;
2071 } else if (is_object($breadcrumb[$i]) && !isset($breadcrumb[$i]->icon)) {
2072 $breadcrumb[$i]->icon = $foldericon;
2075 return $breadcrumb;
2079 * Prepare the file/folder listing.
2081 * @param array $list of files and folders.
2082 * @return array of files and folders.
2083 * @since 2.3.3
2085 protected static function prepare_list($list) {
2086 global $OUTPUT;
2087 $foldericon = $OUTPUT->pix_url(file_folder_icon(24))->out(false);
2089 // Reset the array keys because non-numeric keys will create an object when converted to JSON.
2090 $list = array_values($list);
2092 $len = count($list);
2093 for ($i = 0; $i < $len; $i++) {
2094 if (is_object($list[$i])) {
2095 $file = (array)$list[$i];
2096 $converttoobject = true;
2097 } else {
2098 $file =& $list[$i];
2099 $converttoobject = false;
2101 if (isset($file['size'])) {
2102 $file['size'] = (int)$file['size'];
2103 $file['size_f'] = display_size($file['size']);
2105 if (isset($file['license']) && get_string_manager()->string_exists($file['license'], 'license')) {
2106 $file['license_f'] = get_string($file['license'], 'license');
2108 if (isset($file['image_width']) && isset($file['image_height'])) {
2109 $a = array('width' => $file['image_width'], 'height' => $file['image_height']);
2110 $file['dimensions'] = get_string('imagesize', 'repository', (object)$a);
2112 foreach (array('date', 'datemodified', 'datecreated') as $key) {
2113 if (!isset($file[$key]) && isset($file['date'])) {
2114 $file[$key] = $file['date'];
2116 if (isset($file[$key])) {
2117 // must be UNIX timestamp
2118 $file[$key] = (int)$file[$key];
2119 if (!$file[$key]) {
2120 unset($file[$key]);
2121 } else {
2122 $file[$key.'_f'] = userdate($file[$key], get_string('strftimedatetime', 'langconfig'));
2123 $file[$key.'_f_s'] = userdate($file[$key], get_string('strftimedatetimeshort', 'langconfig'));
2127 $isfolder = (array_key_exists('children', $file) || (isset($file['type']) && $file['type'] == 'folder'));
2128 $filename = null;
2129 if (isset($file['title'])) {
2130 $filename = $file['title'];
2132 else if (isset($file['fullname'])) {
2133 $filename = $file['fullname'];
2135 if (!isset($file['mimetype']) && !$isfolder && $filename) {
2136 $file['mimetype'] = get_mimetype_description(array('filename' => $filename));
2138 if (!isset($file['icon'])) {
2139 if ($isfolder) {
2140 $file['icon'] = $foldericon;
2141 } else if ($filename) {
2142 $file['icon'] = $OUTPUT->pix_url(file_extension_icon($filename, 24))->out(false);
2146 // Recursively loop over children.
2147 if (isset($file['children'])) {
2148 $file['children'] = self::prepare_list($file['children']);
2151 // Convert the array back to an object.
2152 if ($converttoobject) {
2153 $list[$i] = (object)$file;
2156 return $list;
2160 * Prepares list of files before passing it to AJAX, makes sure data is in the correct
2161 * format and stores formatted values.
2163 * @param array|stdClass $listing result of get_listing() or search() or file_get_drafarea_files()
2164 * @return array
2166 public static function prepare_listing($listing) {
2167 $wasobject = false;
2168 if (is_object($listing)) {
2169 $listing = (array) $listing;
2170 $wasobject = true;
2173 // Prepare the breadcrumb, passed as 'path'.
2174 if (isset($listing['path']) && is_array($listing['path'])) {
2175 $listing['path'] = self::prepare_breadcrumb($listing['path']);
2178 // Prepare the listing of objects.
2179 if (isset($listing['list']) && is_array($listing['list'])) {
2180 $listing['list'] = self::prepare_list($listing['list']);
2183 // Convert back to an object.
2184 if ($wasobject) {
2185 $listing = (object) $listing;
2187 return $listing;
2191 * Search files in repository
2192 * When doing global search, $search_text will be used as
2193 * keyword.
2195 * @param string $search_text search key word
2196 * @param int $page page
2197 * @return mixed see {@link repository::get_listing()}
2199 public function search($search_text, $page = 0) {
2200 $list = array();
2201 $list['list'] = array();
2202 return false;
2206 * Logout from repository instance
2207 * By default, this function will return a login form
2209 * @return string
2211 public function logout(){
2212 return $this->print_login();
2216 * To check whether the user is logged in.
2218 * @return bool
2220 public function check_login(){
2221 return true;
2226 * Show the login screen, if required
2228 * @return string
2230 public function print_login(){
2231 return $this->get_listing();
2235 * Show the search screen, if required
2237 * @return string
2239 public function print_search() {
2240 global $PAGE;
2241 $renderer = $PAGE->get_renderer('core', 'files');
2242 return $renderer->repository_default_searchform();
2246 * For oauth like external authentication, when external repository direct user back to moodle,
2247 * this funciton will be called to set up token and token_secret
2249 public function callback() {
2253 * is it possible to do glboal search?
2255 * @return bool
2257 public function global_search() {
2258 return false;
2262 * Defines operations that happen occasionally on cron
2264 * @return bool
2266 public function cron() {
2267 return true;
2271 * function which is run when the type is created (moodle administrator add the plugin)
2273 * @return bool success or fail?
2275 public static function plugin_init() {
2276 return true;
2280 * Edit/Create Admin Settings Moodle form
2282 * @param moodleform $mform Moodle form (passed by reference)
2283 * @param string $classname repository class name
2285 public static function type_config_form($mform, $classname = 'repository') {
2286 $instnaceoptions = call_user_func(array($classname, 'get_instance_option_names'), $mform, $classname);
2287 if (empty($instnaceoptions)) {
2288 // this plugin has only one instance
2289 // so we need to give it a name
2290 // it can be empty, then moodle will look for instance name from language string
2291 $mform->addElement('text', 'pluginname', get_string('pluginname', 'repository'), array('size' => '40'));
2292 $mform->addElement('static', 'pluginnamehelp', '', get_string('pluginnamehelp', 'repository'));
2293 $mform->setType('pluginname', PARAM_TEXT);
2298 * Validate Admin Settings Moodle form
2300 * @static
2301 * @param moodleform $mform Moodle form (passed by reference)
2302 * @param array $data array of ("fieldname"=>value) of submitted data
2303 * @param array $errors array of ("fieldname"=>errormessage) of errors
2304 * @return array array of errors
2306 public static function type_form_validation($mform, $data, $errors) {
2307 return $errors;
2312 * Edit/Create Instance Settings Moodle form
2314 * @param moodleform $mform Moodle form (passed by reference)
2316 public static function instance_config_form($mform) {
2320 * Return names of the general options.
2321 * By default: no general option name
2323 * @return array
2325 public static function get_type_option_names() {
2326 return array('pluginname');
2330 * Return names of the instance options.
2331 * By default: no instance option name
2333 * @return array
2335 public static function get_instance_option_names() {
2336 return array();
2340 * Validate repository plugin instance form
2342 * @param moodleform $mform moodle form
2343 * @param array $data form data
2344 * @param array $errors errors
2345 * @return array errors
2347 public static function instance_form_validation($mform, $data, $errors) {
2348 return $errors;
2352 * Create a shorten filename
2354 * @param string $str filename
2355 * @param int $maxlength max file name length
2356 * @return string short filename
2358 public function get_short_filename($str, $maxlength) {
2359 if (textlib::strlen($str) >= $maxlength) {
2360 return trim(textlib::substr($str, 0, $maxlength)).'...';
2361 } else {
2362 return $str;
2367 * Overwrite an existing file
2369 * @param int $itemid
2370 * @param string $filepath
2371 * @param string $filename
2372 * @param string $newfilepath
2373 * @param string $newfilename
2374 * @return bool
2376 public static function overwrite_existing_draftfile($itemid, $filepath, $filename, $newfilepath, $newfilename) {
2377 global $USER;
2378 $fs = get_file_storage();
2379 $user_context = get_context_instance(CONTEXT_USER, $USER->id);
2380 if ($file = $fs->get_file($user_context->id, 'user', 'draft', $itemid, $filepath, $filename)) {
2381 if ($tempfile = $fs->get_file($user_context->id, 'user', 'draft', $itemid, $newfilepath, $newfilename)) {
2382 // delete existing file to release filename
2383 $file->delete();
2384 // create new file
2385 $newfile = $fs->create_file_from_storedfile(array('filepath'=>$filepath, 'filename'=>$filename), $tempfile);
2386 // remove temp file
2387 $tempfile->delete();
2388 return true;
2391 return false;
2395 * Delete a temp file from draft area
2397 * @param int $draftitemid
2398 * @param string $filepath
2399 * @param string $filename
2400 * @return bool
2402 public static function delete_tempfile_from_draft($draftitemid, $filepath, $filename) {
2403 global $USER;
2404 $fs = get_file_storage();
2405 $user_context = get_context_instance(CONTEXT_USER, $USER->id);
2406 if ($file = $fs->get_file($user_context->id, 'user', 'draft', $draftitemid, $filepath, $filename)) {
2407 $file->delete();
2408 return true;
2409 } else {
2410 return false;
2415 * Find all external files in this repo and import them
2417 public function convert_references_to_local() {
2418 $fs = get_file_storage();
2419 $files = $fs->get_external_files($this->id);
2420 foreach ($files as $storedfile) {
2421 $fs->import_external_file($storedfile);
2426 * Called from phpunit between tests, resets whatever was cached
2428 public static function reset_caches() {
2429 self::sync_external_file(null, true);
2433 * Performs synchronisation of reference to an external file if the previous one has expired.
2435 * @param stored_file $file
2436 * @param bool $resetsynchistory whether to reset all history of sync (used by phpunit)
2437 * @return bool success
2439 public static function sync_external_file($file, $resetsynchistory = false) {
2440 global $DB;
2441 // TODO MDL-25290 static should be replaced with MUC code.
2442 static $synchronized = array();
2443 if ($resetsynchistory) {
2444 $synchronized = array();
2447 $fs = get_file_storage();
2449 if (!$file || !$file->get_referencefileid()) {
2450 return false;
2452 if (array_key_exists($file->get_id(), $synchronized)) {
2453 return $synchronized[$file->get_id()];
2456 // remember that we already cached in current request to prevent from querying again
2457 $synchronized[$file->get_id()] = false;
2459 if (!$reference = $DB->get_record('files_reference', array('id'=>$file->get_referencefileid()))) {
2460 return false;
2463 if (!empty($reference->lastsync) and ($reference->lastsync + $reference->lifetime > time())) {
2464 $synchronized[$file->get_id()] = true;
2465 return true;
2468 if (!$repository = self::get_repository_by_id($reference->repositoryid, SYSCONTEXTID)) {
2469 return false;
2472 if (!$repository->sync_individual_file($file)) {
2473 return false;
2476 $lifetime = $repository->get_reference_file_lifetime($reference);
2477 $fileinfo = $repository->get_file_by_reference($reference);
2478 if ($fileinfo === null) {
2479 // does not exist any more - set status to missing
2480 $file->set_missingsource($lifetime);
2481 $synchronized[$file->get_id()] = true;
2482 return true;
2485 $contenthash = null;
2486 $filesize = null;
2487 if (!empty($fileinfo->filesize)) {
2488 // filesize returned
2489 if (!empty($fileinfo->contenthash) && $fs->content_exists($fileinfo->contenthash)) {
2490 // contenthash is specified and valid
2491 $contenthash = $fileinfo->contenthash;
2492 } else if ($fileinfo->filesize == $file->get_filesize()) {
2493 // we don't know the new contenthash but the filesize did not change,
2494 // assume the contenthash did not change either
2495 $contenthash = $file->get_contenthash();
2496 } else {
2497 // we can't save empty contenthash so generate contenthash from empty string
2498 $fs->add_string_to_pool('');
2499 $contenthash = sha1('');
2501 $filesize = $fileinfo->filesize;
2502 } else if (!empty($fileinfo->filepath)) {
2503 // File path returned
2504 list($contenthash, $filesize, $newfile) = $fs->add_file_to_pool($fileinfo->filepath);
2505 } else if (!empty($fileinfo->handle) && is_resource($fileinfo->handle)) {
2506 // File handle returned
2507 $contents = '';
2508 while (!feof($fileinfo->handle)) {
2509 $contents .= fread($handle, 8192);
2511 fclose($fileinfo->handle);
2512 list($contenthash, $filesize, $newfile) = $fs->add_string_to_pool($content);
2513 } else if (isset($fileinfo->content)) {
2514 // File content returned
2515 list($contenthash, $filesize, $newfile) = $fs->add_string_to_pool($fileinfo->content);
2518 if (!isset($contenthash) or !isset($filesize)) {
2519 return false;
2522 // update files table
2523 $file->set_synchronized($contenthash, $filesize, 0, $lifetime);
2524 $synchronized[$file->get_id()] = true;
2525 return true;
2529 * Build draft file's source field
2531 * {@link file_restore_source_field_from_draft_file()}
2532 * XXX: This is a hack for file manager (MDL-28666)
2533 * For newly created draft files we have to construct
2534 * source filed in php serialized data format.
2535 * File manager needs to know the original file information before copying
2536 * to draft area, so we append these information in mdl_files.source field
2538 * @param string $source
2539 * @return string serialised source field
2541 public static function build_source_field($source) {
2542 $sourcefield = new stdClass;
2543 $sourcefield->source = $source;
2544 return serialize($sourcefield);
2549 * Exception class for repository api
2551 * @since 2.0
2552 * @package core_repository
2553 * @copyright 2009 Dongsheng Cai {@link http://dongsheng.org}
2554 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2556 class repository_exception extends moodle_exception {
2560 * This is a class used to define a repository instance form
2562 * @since 2.0
2563 * @package core_repository
2564 * @copyright 2009 Dongsheng Cai {@link http://dongsheng.org}
2565 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2567 final class repository_instance_form extends moodleform {
2568 /** @var stdClass repository instance */
2569 protected $instance;
2570 /** @var string repository plugin type */
2571 protected $plugin;
2574 * Added defaults to moodle form
2576 protected function add_defaults() {
2577 $mform =& $this->_form;
2578 $strrequired = get_string('required');
2580 $mform->addElement('hidden', 'edit', ($this->instance) ? $this->instance->id : 0);
2581 $mform->setType('edit', PARAM_INT);
2582 $mform->addElement('hidden', 'new', $this->plugin);
2583 $mform->setType('new', PARAM_FORMAT);
2584 $mform->addElement('hidden', 'plugin', $this->plugin);
2585 $mform->setType('plugin', PARAM_PLUGIN);
2586 $mform->addElement('hidden', 'typeid', $this->typeid);
2587 $mform->setType('typeid', PARAM_INT);
2588 $mform->addElement('hidden', 'contextid', $this->contextid);
2589 $mform->setType('contextid', PARAM_INT);
2591 $mform->addElement('text', 'name', get_string('name'), 'maxlength="100" size="30"');
2592 $mform->addRule('name', $strrequired, 'required', null, 'client');
2593 $mform->setType('name', PARAM_TEXT);
2597 * Define moodle form elements
2599 public function definition() {
2600 global $CFG;
2601 // type of plugin, string
2602 $this->plugin = $this->_customdata['plugin'];
2603 $this->typeid = $this->_customdata['typeid'];
2604 $this->contextid = $this->_customdata['contextid'];
2605 $this->instance = (isset($this->_customdata['instance'])
2606 && is_subclass_of($this->_customdata['instance'], 'repository'))
2607 ? $this->_customdata['instance'] : null;
2609 $mform =& $this->_form;
2611 $this->add_defaults();
2613 // Add instance config options.
2614 $result = repository::static_function($this->plugin, 'instance_config_form', $mform);
2615 if ($result === false) {
2616 // Remove the name element if no other config options.
2617 $mform->removeElement('name');
2619 if ($this->instance) {
2620 $data = array();
2621 $data['name'] = $this->instance->name;
2622 if (!$this->instance->readonly) {
2623 // and set the data if we have some.
2624 foreach ($this->instance->get_instance_option_names() as $config) {
2625 if (!empty($this->instance->options[$config])) {
2626 $data[$config] = $this->instance->options[$config];
2627 } else {
2628 $data[$config] = '';
2632 $this->set_data($data);
2635 if ($result === false) {
2636 $mform->addElement('cancel');
2637 } else {
2638 $this->add_action_buttons(true, get_string('save','repository'));
2643 * Validate moodle form data
2645 * @param array $data form data
2646 * @param array $files files in form
2647 * @return array errors
2649 public function validation($data, $files) {
2650 global $DB;
2651 $errors = array();
2652 $plugin = $this->_customdata['plugin'];
2653 $instance = (isset($this->_customdata['instance'])
2654 && is_subclass_of($this->_customdata['instance'], 'repository'))
2655 ? $this->_customdata['instance'] : null;
2656 if (!$instance) {
2657 $errors = repository::static_function($plugin, 'instance_form_validation', $this, $data, $errors);
2658 } else {
2659 $errors = $instance->instance_form_validation($this, $data, $errors);
2662 $sql = "SELECT count('x')
2663 FROM {repository_instances} i, {repository} r
2664 WHERE r.type=:plugin AND r.id=i.typeid AND i.name=:name";
2665 if ($DB->count_records_sql($sql, array('name' => $data['name'], 'plugin' => $data['plugin'])) > 1) {
2666 $errors['name'] = get_string('erroruniquename', 'repository');
2669 return $errors;
2674 * This is a class used to define a repository type setting form
2676 * @since 2.0
2677 * @package core_repository
2678 * @copyright 2009 Dongsheng Cai {@link http://dongsheng.org}
2679 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2681 final class repository_type_form extends moodleform {
2682 /** @var stdClass repository instance */
2683 protected $instance;
2684 /** @var string repository plugin name */
2685 protected $plugin;
2686 /** @var string action */
2687 protected $action;
2690 * Definition of the moodleform
2692 public function definition() {
2693 global $CFG;
2694 // type of plugin, string
2695 $this->plugin = $this->_customdata['plugin'];
2696 $this->instance = (isset($this->_customdata['instance'])
2697 && is_a($this->_customdata['instance'], 'repository_type'))
2698 ? $this->_customdata['instance'] : null;
2700 $this->action = $this->_customdata['action'];
2701 $this->pluginname = $this->_customdata['pluginname'];
2702 $mform =& $this->_form;
2703 $strrequired = get_string('required');
2705 $mform->addElement('hidden', 'action', $this->action);
2706 $mform->setType('action', PARAM_TEXT);
2707 $mform->addElement('hidden', 'repos', $this->plugin);
2708 $mform->setType('repos', PARAM_PLUGIN);
2710 // let the plugin add its specific fields
2711 $classname = 'repository_' . $this->plugin;
2712 require_once($CFG->dirroot . '/repository/' . $this->plugin . '/lib.php');
2713 //add "enable course/user instances" checkboxes if multiple instances are allowed
2714 $instanceoptionnames = repository::static_function($this->plugin, 'get_instance_option_names');
2716 $result = call_user_func(array($classname, 'type_config_form'), $mform, $classname);
2718 if (!empty($instanceoptionnames)) {
2719 $sm = get_string_manager();
2720 $component = 'repository';
2721 if ($sm->string_exists('enablecourseinstances', 'repository_' . $this->plugin)) {
2722 $component .= ('_' . $this->plugin);
2724 $mform->addElement('checkbox', 'enablecourseinstances', get_string('enablecourseinstances', $component));
2726 $component = 'repository';
2727 if ($sm->string_exists('enableuserinstances', 'repository_' . $this->plugin)) {
2728 $component .= ('_' . $this->plugin);
2730 $mform->addElement('checkbox', 'enableuserinstances', get_string('enableuserinstances', $component));
2733 // set the data if we have some.
2734 if ($this->instance) {
2735 $data = array();
2736 $option_names = call_user_func(array($classname,'get_type_option_names'));
2737 if (!empty($instanceoptionnames)){
2738 $option_names[] = 'enablecourseinstances';
2739 $option_names[] = 'enableuserinstances';
2742 $instanceoptions = $this->instance->get_options();
2743 foreach ($option_names as $config) {
2744 if (!empty($instanceoptions[$config])) {
2745 $data[$config] = $instanceoptions[$config];
2746 } else {
2747 $data[$config] = '';
2750 // XXX: set plugin name for plugins which doesn't have muliti instances
2751 if (empty($instanceoptionnames)){
2752 $data['pluginname'] = $this->pluginname;
2754 $this->set_data($data);
2757 $this->add_action_buttons(true, get_string('save','repository'));
2761 * Validate moodle form data
2763 * @param array $data moodle form data
2764 * @param array $files
2765 * @return array errors
2767 public function validation($data, $files) {
2768 $errors = array();
2769 $plugin = $this->_customdata['plugin'];
2770 $instance = (isset($this->_customdata['instance'])
2771 && is_subclass_of($this->_customdata['instance'], 'repository'))
2772 ? $this->_customdata['instance'] : null;
2773 if (!$instance) {
2774 $errors = repository::static_function($plugin, 'type_form_validation', $this, $data, $errors);
2775 } else {
2776 $errors = $instance->type_form_validation($this, $data, $errors);
2779 return $errors;
2784 * Generate all options needed by filepicker
2786 * @param array $args including following keys
2787 * context
2788 * accepted_types
2789 * return_types
2791 * @return array the list of repository instances, including meta infomation, containing the following keys
2792 * externallink
2793 * repositories
2794 * accepted_types
2796 function initialise_filepicker($args) {
2797 global $CFG, $USER, $PAGE, $OUTPUT;
2798 static $templatesinitialized = array();
2799 require_once($CFG->libdir . '/licenselib.php');
2801 $return = new stdClass();
2802 $licenses = array();
2803 if (!empty($CFG->licenses)) {
2804 $array = explode(',', $CFG->licenses);
2805 foreach ($array as $license) {
2806 $l = new stdClass();
2807 $l->shortname = $license;
2808 $l->fullname = get_string($license, 'license');
2809 $licenses[] = $l;
2812 if (!empty($CFG->sitedefaultlicense)) {
2813 $return->defaultlicense = $CFG->sitedefaultlicense;
2816 $return->licenses = $licenses;
2818 $return->author = fullname($USER);
2820 if (empty($args->context)) {
2821 $context = $PAGE->context;
2822 } else {
2823 $context = $args->context;
2825 $disable_types = array();
2826 if (!empty($args->disable_types)) {
2827 $disable_types = $args->disable_types;
2830 $user_context = get_context_instance(CONTEXT_USER, $USER->id);
2832 list($context, $course, $cm) = get_context_info_array($context->id);
2833 $contexts = array($user_context, get_system_context());
2834 if (!empty($course)) {
2835 // adding course context
2836 $contexts[] = get_context_instance(CONTEXT_COURSE, $course->id);
2838 $externallink = (int)get_config(null, 'repositoryallowexternallinks');
2839 $repositories = repository::get_instances(array(
2840 'context'=>$contexts,
2841 'currentcontext'=> $context,
2842 'accepted_types'=>$args->accepted_types,
2843 'return_types'=>$args->return_types,
2844 'disable_types'=>$disable_types
2847 $return->repositories = array();
2849 if (empty($externallink)) {
2850 $return->externallink = false;
2851 } else {
2852 $return->externallink = true;
2855 $return->userprefs = array();
2856 $return->userprefs['recentrepository'] = get_user_preferences('filepicker_recentrepository', '');
2857 $return->userprefs['recentlicense'] = get_user_preferences('filepicker_recentlicense', '');
2858 $return->userprefs['recentviewmode'] = get_user_preferences('filepicker_recentviewmode', '');
2860 user_preference_allow_ajax_update('filepicker_recentrepository', PARAM_INT);
2861 user_preference_allow_ajax_update('filepicker_recentlicense', PARAM_SAFEDIR);
2862 user_preference_allow_ajax_update('filepicker_recentviewmode', PARAM_INT);
2865 // provided by form element
2866 $return->accepted_types = file_get_typegroup('extension', $args->accepted_types);
2867 $return->return_types = $args->return_types;
2868 $templates = array();
2869 foreach ($repositories as $repository) {
2870 $meta = $repository->get_meta();
2871 // Please note that the array keys for repositories are used within
2872 // JavaScript a lot, the key NEEDS to be the repository id.
2873 $return->repositories[$repository->id] = $meta;
2874 // Register custom repository template if it has one
2875 if(method_exists($repository, 'get_upload_template') && !array_key_exists('uploadform_' . $meta->type, $templatesinitialized)) {
2876 $templates['uploadform_' . $meta->type] = $repository->get_upload_template();
2877 $templatesinitialized['uploadform_' . $meta->type] = true;
2880 if (!array_key_exists('core', $templatesinitialized)) {
2881 // we need to send each filepicker template to the browser just once
2882 $fprenderer = $PAGE->get_renderer('core', 'files');
2883 $templates = array_merge($templates, $fprenderer->filepicker_js_templates());
2884 $templatesinitialized['core'] = true;
2886 if (sizeof($templates)) {
2887 $PAGE->requires->js_init_call('M.core_filepicker.set_templates', array($templates), true);
2889 return $return;
2893 * Small function to walk an array to attach repository ID
2895 * @param array $value
2896 * @param string $key
2897 * @param int $id
2899 function repository_attach_id(&$value, $key, $id){
2900 $value['repo_id'] = $id;