MDL-37614 report/completion: changed generalbox class in table to generaltable class...
[moodle.git] / repository / lib.php
blob714e1b9f454e3ae1d274950f2e2fdba8b06257c7
1 <?php
2 // This file is part of Moodle - http://moodle.org/
3 //
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
8 //
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
17 /**
18 * This file contains classes used to manage the repository plugins in Moodle
20 * @since 2.0
21 * @package core_repository
22 * @copyright 2009 Dongsheng Cai {@link http://dongsheng.org}
23 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
26 defined('MOODLE_INTERNAL') || die();
27 require_once($CFG->libdir . '/filelib.php');
28 require_once($CFG->libdir . '/formslib.php');
30 define('FILE_EXTERNAL', 1);
31 define('FILE_INTERNAL', 2);
32 define('FILE_REFERENCE', 4);
33 define('RENAME_SUFFIX', '_2');
35 /**
36 * This class is used to manage repository plugins
38 * A repository_type is a repository plug-in. It can be Box.net, Flick-r, ...
39 * A repository type can be edited, sorted and hidden. It is mandatory for an
40 * administrator to create a repository type in order to be able to create
41 * some instances of this type.
42 * Coding note:
43 * - a repository_type object is mapped to the "repository" database table
44 * - "typename" attibut maps the "type" database field. It is unique.
45 * - general "options" for a repository type are saved in the config_plugin table
46 * - when you delete a repository, all instances are deleted, and general
47 * options are also deleted from database
48 * - When you create a type for a plugin that can't have multiple instances, a
49 * instance is automatically created.
51 * @package core_repository
52 * @copyright 2009 Jerome Mouneyrac
53 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
55 class repository_type {
58 /**
59 * Type name (no whitespace) - A type name is unique
60 * Note: for a user-friendly type name see get_readablename()
61 * @var String
63 private $_typename;
66 /**
67 * Options of this type
68 * They are general options that any instance of this type would share
69 * e.g. API key
70 * These options are saved in config_plugin table
71 * @var array
73 private $_options;
76 /**
77 * Is the repository type visible or hidden
78 * If false (hidden): no instances can be created, edited, deleted, showned , used...
79 * @var boolean
81 private $_visible;
84 /**
85 * 0 => not ordered, 1 => first position, 2 => second position...
86 * A not order type would appear in first position (should never happened)
87 * @var integer
89 private $_sortorder;
91 /**
92 * Return if the instance is visible in a context
94 * @todo check if the context visibility has been overwritten by the plugin creator
95 * (need to create special functions to be overvwritten in repository class)
96 * @param stdClass $context context
97 * @return bool
99 public function get_contextvisibility($context) {
100 global $USER;
102 if ($context->contextlevel == CONTEXT_COURSE) {
103 return $this->_options['enablecourseinstances'];
106 if ($context->contextlevel == CONTEXT_USER) {
107 return $this->_options['enableuserinstances'];
110 //the context is SITE
111 return true;
117 * repository_type constructor
119 * @param int $typename
120 * @param array $typeoptions
121 * @param bool $visible
122 * @param int $sortorder (don't really need set, it will be during create() call)
124 public function __construct($typename = '', $typeoptions = array(), $visible = true, $sortorder = 0) {
125 global $CFG;
127 //set type attributs
128 $this->_typename = $typename;
129 $this->_visible = $visible;
130 $this->_sortorder = $sortorder;
132 //set options attribut
133 $this->_options = array();
134 $options = repository::static_function($typename, 'get_type_option_names');
135 //check that the type can be setup
136 if (!empty($options)) {
137 //set the type options
138 foreach ($options as $config) {
139 if (array_key_exists($config, $typeoptions)) {
140 $this->_options[$config] = $typeoptions[$config];
145 //retrieve visibility from option
146 if (array_key_exists('enablecourseinstances',$typeoptions)) {
147 $this->_options['enablecourseinstances'] = $typeoptions['enablecourseinstances'];
148 } else {
149 $this->_options['enablecourseinstances'] = 0;
152 if (array_key_exists('enableuserinstances',$typeoptions)) {
153 $this->_options['enableuserinstances'] = $typeoptions['enableuserinstances'];
154 } else {
155 $this->_options['enableuserinstances'] = 0;
161 * Get the type name (no whitespace)
162 * For a human readable name, use get_readablename()
164 * @return string the type name
166 public function get_typename() {
167 return $this->_typename;
171 * Return a human readable and user-friendly type name
173 * @return string user-friendly type name
175 public function get_readablename() {
176 return get_string('pluginname','repository_'.$this->_typename);
180 * Return general options
182 * @return array the general options
184 public function get_options() {
185 return $this->_options;
189 * Return visibility
191 * @return bool
193 public function get_visible() {
194 return $this->_visible;
198 * Return order / position of display in the file picker
200 * @return int
202 public function get_sortorder() {
203 return $this->_sortorder;
207 * Create a repository type (the type name must not already exist)
208 * @param bool $silent throw exception?
209 * @return mixed return int if create successfully, return false if
211 public function create($silent = false) {
212 global $DB;
214 //check that $type has been set
215 $timmedtype = trim($this->_typename);
216 if (empty($timmedtype)) {
217 throw new repository_exception('emptytype', 'repository');
220 //set sortorder as the last position in the list
221 if (!isset($this->_sortorder) || $this->_sortorder == 0 ) {
222 $sql = "SELECT MAX(sortorder) FROM {repository}";
223 $this->_sortorder = 1 + $DB->get_field_sql($sql);
226 //only create a new type if it doesn't already exist
227 $existingtype = $DB->get_record('repository', array('type'=>$this->_typename));
228 if (!$existingtype) {
229 //create the type
230 $newtype = new stdClass();
231 $newtype->type = $this->_typename;
232 $newtype->visible = $this->_visible;
233 $newtype->sortorder = $this->_sortorder;
234 $plugin_id = $DB->insert_record('repository', $newtype);
235 //save the options in DB
236 $this->update_options();
238 $instanceoptionnames = repository::static_function($this->_typename, 'get_instance_option_names');
240 //if the plugin type has no multiple instance (e.g. has no instance option name) so it wont
241 //be possible for the administrator to create a instance
242 //in this case we need to create an instance
243 if (empty($instanceoptionnames)) {
244 $instanceoptions = array();
245 if (empty($this->_options['pluginname'])) {
246 // when moodle trying to install some repo plugin automatically
247 // this option will be empty, get it from language string when display
248 $instanceoptions['name'] = '';
249 } else {
250 // when admin trying to add a plugin manually, he will type a name
251 // for it
252 $instanceoptions['name'] = $this->_options['pluginname'];
254 repository::static_function($this->_typename, 'create', $this->_typename, 0, get_system_context(), $instanceoptions);
256 //run plugin_init function
257 if (!repository::static_function($this->_typename, 'plugin_init')) {
258 if (!$silent) {
259 throw new repository_exception('cannotinitplugin', 'repository');
263 if(!empty($plugin_id)) {
264 // return plugin_id if create successfully
265 return $plugin_id;
266 } else {
267 return false;
270 } else {
271 if (!$silent) {
272 throw new repository_exception('existingrepository', 'repository');
274 // If plugin existed, return false, tell caller no new plugins were created.
275 return false;
281 * Update plugin options into the config_plugin table
283 * @param array $options
284 * @return bool
286 public function update_options($options = null) {
287 global $DB;
288 $classname = 'repository_' . $this->_typename;
289 $instanceoptions = repository::static_function($this->_typename, 'get_instance_option_names');
290 if (empty($instanceoptions)) {
291 // update repository instance name if this plugin type doesn't have muliti instances
292 $params = array();
293 $params['type'] = $this->_typename;
294 $instances = repository::get_instances($params);
295 $instance = array_pop($instances);
296 if ($instance) {
297 $DB->set_field('repository_instances', 'name', $options['pluginname'], array('id'=>$instance->id));
299 unset($options['pluginname']);
302 if (!empty($options)) {
303 $this->_options = $options;
306 foreach ($this->_options as $name => $value) {
307 set_config($name, $value, $this->_typename);
310 return true;
314 * Update visible database field with the value given as parameter
315 * or with the visible value of this object
316 * This function is private.
317 * For public access, have a look to switch_and_update_visibility()
319 * @param bool $visible
320 * @return bool
322 private function update_visible($visible = null) {
323 global $DB;
325 if (!empty($visible)) {
326 $this->_visible = $visible;
328 else if (!isset($this->_visible)) {
329 throw new repository_exception('updateemptyvisible', 'repository');
332 return $DB->set_field('repository', 'visible', $this->_visible, array('type'=>$this->_typename));
336 * Update database sortorder field with the value given as parameter
337 * or with the sortorder value of this object
338 * This function is private.
339 * For public access, have a look to move_order()
341 * @param int $sortorder
342 * @return bool
344 private function update_sortorder($sortorder = null) {
345 global $DB;
347 if (!empty($sortorder) && $sortorder!=0) {
348 $this->_sortorder = $sortorder;
350 //if sortorder is not set, we set it as the ;ast position in the list
351 else if (!isset($this->_sortorder) || $this->_sortorder == 0 ) {
352 $sql = "SELECT MAX(sortorder) FROM {repository}";
353 $this->_sortorder = 1 + $DB->get_field_sql($sql);
356 return $DB->set_field('repository', 'sortorder', $this->_sortorder, array('type'=>$this->_typename));
360 * Change order of the type with its adjacent upper or downer type
361 * (database fields are updated)
362 * Algorithm details:
363 * 1. retrieve all types in an array. This array is sorted by sortorder,
364 * and the array keys start from 0 to X (incremented by 1)
365 * 2. switch sortorder values of this type and its adjacent type
367 * @param string $move "up" or "down"
369 public function move_order($move) {
370 global $DB;
372 $types = repository::get_types(); // retrieve all types
374 // retrieve this type into the returned array
375 $i = 0;
376 while (!isset($indice) && $i<count($types)) {
377 if ($types[$i]->get_typename() == $this->_typename) {
378 $indice = $i;
380 $i++;
383 // retrieve adjacent indice
384 switch ($move) {
385 case "up":
386 $adjacentindice = $indice - 1;
387 break;
388 case "down":
389 $adjacentindice = $indice + 1;
390 break;
391 default:
392 throw new repository_exception('movenotdefined', 'repository');
395 //switch sortorder of this type and the adjacent type
396 //TODO: we could reset sortorder for all types. This is not as good in performance term, but
397 //that prevent from wrong behaviour on a screwed database. As performance are not important in this particular case
398 //it worth to change the algo.
399 if ($adjacentindice>=0 && !empty($types[$adjacentindice])) {
400 $DB->set_field('repository', 'sortorder', $this->_sortorder, array('type'=>$types[$adjacentindice]->get_typename()));
401 $this->update_sortorder($types[$adjacentindice]->get_sortorder());
406 * 1. Change visibility to the value chosen
407 * 2. Update the type
409 * @param bool $visible
410 * @return bool
412 public function update_visibility($visible = null) {
413 if (is_bool($visible)) {
414 $this->_visible = $visible;
415 } else {
416 $this->_visible = !$this->_visible;
418 return $this->update_visible();
423 * Delete a repository_type (general options are removed from config_plugin
424 * table, and all instances are deleted)
426 * @param bool $downloadcontents download external contents if exist
427 * @return bool
429 public function delete($downloadcontents = false) {
430 global $DB;
432 //delete all instances of this type
433 $params = array();
434 $params['context'] = array();
435 $params['onlyvisible'] = false;
436 $params['type'] = $this->_typename;
437 $instances = repository::get_instances($params);
438 foreach ($instances as $instance) {
439 $instance->delete($downloadcontents);
442 //delete all general options
443 foreach ($this->_options as $name => $value) {
444 set_config($name, null, $this->_typename);
447 try {
448 $DB->delete_records('repository', array('type' => $this->_typename));
449 } catch (dml_exception $ex) {
450 return false;
452 return true;
457 * This is the base class of the repository class.
459 * To create repository plugin, see: {@link http://docs.moodle.org/dev/Repository_plugins}
460 * See an example: {@link repository_boxnet}
462 * @package core_repository
463 * @copyright 2009 Dongsheng Cai {@link http://dongsheng.org}
464 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
466 abstract class repository {
467 /** Timeout in seconds for downloading the external file into moodle */
468 const GETFILE_TIMEOUT = 30;
469 /** Timeout in seconds for syncronising the external file size */
470 const SYNCFILE_TIMEOUT = 1;
471 /** Timeout in seconds for downloading an image file from external repository during syncronisation */
472 const SYNCIMAGE_TIMEOUT = 3;
474 // $disabled can be set to true to disable a plugin by force
475 // example: self::$disabled = true
476 /** @var bool force disable repository instance */
477 public $disabled = false;
478 /** @var int repository instance id */
479 public $id;
480 /** @var stdClass current context */
481 public $context;
482 /** @var array repository options */
483 public $options;
484 /** @var bool Whether or not the repository instance is editable */
485 public $readonly;
486 /** @var int return types */
487 public $returntypes;
488 /** @var stdClass repository instance database record */
489 public $instance;
491 * Constructor
493 * @param int $repositoryid repository instance id
494 * @param int|stdClass $context a context id or context object
495 * @param array $options repository options
496 * @param int $readonly indicate this repo is readonly or not
498 public function __construct($repositoryid, $context = SYSCONTEXTID, $options = array(), $readonly = 0) {
499 global $DB;
500 $this->id = $repositoryid;
501 if (is_object($context)) {
502 $this->context = $context;
503 } else {
504 $this->context = context::instance_by_id($context);
506 $this->instance = $DB->get_record('repository_instances', array('id'=>$this->id));
507 $this->readonly = $readonly;
508 $this->options = array();
510 if (is_array($options)) {
511 // The get_option() method will get stored options in database.
512 $options = array_merge($this->get_option(), $options);
513 } else {
514 $options = $this->get_option();
516 foreach ($options as $n => $v) {
517 $this->options[$n] = $v;
519 $this->name = $this->get_name();
520 $this->returntypes = $this->supported_returntypes();
521 $this->super_called = true;
525 * Get repository instance using repository id
527 * @param int $repositoryid repository ID
528 * @param stdClass|int $context context instance or context ID
529 * @param array $options additional repository options
530 * @return repository
532 public static function get_repository_by_id($repositoryid, $context, $options = array()) {
533 global $CFG, $DB;
535 $sql = 'SELECT i.name, i.typeid, r.type FROM {repository} r, {repository_instances} i WHERE i.id=? AND i.typeid=r.id';
537 if (!$record = $DB->get_record_sql($sql, array($repositoryid))) {
538 throw new repository_exception('invalidrepositoryid', 'repository');
539 } else {
540 $type = $record->type;
541 if (file_exists($CFG->dirroot . "/repository/$type/lib.php")) {
542 require_once($CFG->dirroot . "/repository/$type/lib.php");
543 $classname = 'repository_' . $type;
544 $contextid = $context;
545 if (is_object($context)) {
546 $contextid = $context->id;
548 $options['type'] = $type;
549 $options['typeid'] = $record->typeid;
550 if (empty($options['name'])) {
551 $options['name'] = $record->name;
553 $repository = new $classname($repositoryid, $contextid, $options);
554 return $repository;
555 } else {
556 throw new repository_exception('invalidplugin', 'repository');
562 * Get a repository type object by a given type name.
564 * @static
565 * @param string $typename the repository type name
566 * @return repository_type|bool
568 public static function get_type_by_typename($typename) {
569 global $DB;
571 if (!$record = $DB->get_record('repository',array('type' => $typename))) {
572 return false;
575 return new repository_type($typename, (array)get_config($typename), $record->visible, $record->sortorder);
579 * Get the repository type by a given repository type id.
581 * @static
582 * @param int $id the type id
583 * @return object
585 public static function get_type_by_id($id) {
586 global $DB;
588 if (!$record = $DB->get_record('repository',array('id' => $id))) {
589 return false;
592 return new repository_type($record->type, (array)get_config($record->type), $record->visible, $record->sortorder);
596 * Return all repository types ordered by sortorder field
597 * first repository type in returnedarray[0], second repository type in returnedarray[1], ...
599 * @static
600 * @param bool $visible can return types by visiblity, return all types if null
601 * @return array Repository types
603 public static function get_types($visible=null) {
604 global $DB, $CFG;
606 $types = array();
607 $params = null;
608 if (!empty($visible)) {
609 $params = array('visible' => $visible);
611 if ($records = $DB->get_records('repository',$params,'sortorder')) {
612 foreach($records as $type) {
613 if (file_exists($CFG->dirroot . '/repository/'. $type->type .'/lib.php')) {
614 $types[] = new repository_type($type->type, (array)get_config($type->type), $type->visible, $type->sortorder);
619 return $types;
623 * Checks if user has a capability to view the current repository in current context
625 * @return bool
627 public final function check_capability() {
628 $capability = false;
629 if (preg_match("/^repository_(.*)$/", get_class($this), $matches)) {
630 $type = $matches[1];
631 $capability = has_capability('repository/'.$type.':view', $this->context);
633 if (!$capability) {
634 throw new repository_exception('nopermissiontoaccess', 'repository');
639 * Check if file already exists in draft area
641 * @static
642 * @param int $itemid
643 * @param string $filepath
644 * @param string $filename
645 * @return bool
647 public static function draftfile_exists($itemid, $filepath, $filename) {
648 global $USER;
649 $fs = get_file_storage();
650 $usercontext = context_user::instance($USER->id);
651 if ($fs->get_file($usercontext->id, 'user', 'draft', $itemid, $filepath, $filename)) {
652 return true;
653 } else {
654 return false;
659 * Parses the 'source' returned by moodle repositories and returns an instance of stored_file
661 * @param string $source
662 * @return stored_file|null
664 public static function get_moodle_file($source) {
665 $params = file_storage::unpack_reference($source, true);
666 $fs = get_file_storage();
667 return $fs->get_file($params['contextid'], $params['component'], $params['filearea'],
668 $params['itemid'], $params['filepath'], $params['filename']);
672 * Repository method to make sure that user can access particular file.
674 * This is checked when user tries to pick the file from repository to deal with
675 * potential parameter substitutions is request
677 * @param string $source
678 * @return bool whether the file is accessible by current user
680 public function file_is_accessible($source) {
681 if ($this->has_moodle_files()) {
682 try {
683 $params = file_storage::unpack_reference($source, true);
684 } catch (file_reference_exception $e) {
685 return false;
687 $browser = get_file_browser();
688 $context = context::instance_by_id($params['contextid']);
689 $file_info = $browser->get_file_info($context, $params['component'], $params['filearea'],
690 $params['itemid'], $params['filepath'], $params['filename']);
691 return !empty($file_info);
693 return true;
697 * This function is used to copy a moodle file to draft area.
699 * It DOES NOT check if the user is allowed to access this file because the actual file
700 * can be located in the area where user does not have access to but there is an alias
701 * to this file in the area where user CAN access it.
702 * {@link file_is_accessible} should be called for alias location before calling this function.
704 * @param string $source The metainfo of file, it is base64 encoded php serialized data
705 * @param stdClass|array $filerecord contains itemid, filepath, filename and optionally other
706 * attributes of the new file
707 * @param int $maxbytes maximum allowed size of file, -1 if unlimited. If size of file exceeds
708 * the limit, the file_exception is thrown.
709 * @param int $areamaxbytes the maximum size of the area. A file_exception is thrown if the
710 * new file will reach the limit.
711 * @return array The information about the created file
713 public function copy_to_area($source, $filerecord, $maxbytes = -1, $areamaxbytes = FILE_AREA_MAX_BYTES_UNLIMITED) {
714 global $USER;
715 $fs = get_file_storage();
717 if ($this->has_moodle_files() == false) {
718 throw new coding_exception('Only repository used to browse moodle files can use repository::copy_to_area()');
721 $user_context = context_user::instance($USER->id);
723 $filerecord = (array)$filerecord;
724 // make sure the new file will be created in user draft area
725 $filerecord['component'] = 'user';
726 $filerecord['filearea'] = 'draft';
727 $filerecord['contextid'] = $user_context->id;
728 $draftitemid = $filerecord['itemid'];
729 $new_filepath = $filerecord['filepath'];
730 $new_filename = $filerecord['filename'];
732 // the file needs to copied to draft area
733 $stored_file = self::get_moodle_file($source);
734 if ($maxbytes != -1 && $stored_file->get_filesize() > $maxbytes) {
735 throw new file_exception('maxbytes');
737 // Validate the size of the draft area.
738 if (file_is_draft_area_limit_reached($draftitemid, $areamaxbytes, $stored_file->get_filesize())) {
739 throw new file_exception('maxareabytes');
742 if (repository::draftfile_exists($draftitemid, $new_filepath, $new_filename)) {
743 // create new file
744 $unused_filename = repository::get_unused_filename($draftitemid, $new_filepath, $new_filename);
745 $filerecord['filename'] = $unused_filename;
746 $fs->create_file_from_storedfile($filerecord, $stored_file);
747 $event = array();
748 $event['event'] = 'fileexists';
749 $event['newfile'] = new stdClass;
750 $event['newfile']->filepath = $new_filepath;
751 $event['newfile']->filename = $unused_filename;
752 $event['newfile']->url = moodle_url::make_draftfile_url($draftitemid, $new_filepath, $unused_filename)->out();
753 $event['existingfile'] = new stdClass;
754 $event['existingfile']->filepath = $new_filepath;
755 $event['existingfile']->filename = $new_filename;
756 $event['existingfile']->url = moodle_url::make_draftfile_url($draftitemid, $new_filepath, $new_filename)->out();
757 return $event;
758 } else {
759 $fs->create_file_from_storedfile($filerecord, $stored_file);
760 $info = array();
761 $info['itemid'] = $draftitemid;
762 $info['file'] = $new_filename;
763 $info['title'] = $new_filename;
764 $info['contextid'] = $user_context->id;
765 $info['url'] = moodle_url::make_draftfile_url($draftitemid, $new_filepath, $new_filename)->out();
766 $info['filesize'] = $stored_file->get_filesize();
767 return $info;
772 * Get unused filename by appending suffix
774 * @static
775 * @param int $itemid
776 * @param string $filepath
777 * @param string $filename
778 * @return string
780 public static function get_unused_filename($itemid, $filepath, $filename) {
781 global $USER;
782 $fs = get_file_storage();
783 while (repository::draftfile_exists($itemid, $filepath, $filename)) {
784 $filename = repository::append_suffix($filename);
786 return $filename;
790 * Append a suffix to filename
792 * @static
793 * @param string $filename
794 * @return string
796 public static function append_suffix($filename) {
797 $pathinfo = pathinfo($filename);
798 if (empty($pathinfo['extension'])) {
799 return $filename . RENAME_SUFFIX;
800 } else {
801 return $pathinfo['filename'] . RENAME_SUFFIX . '.' . $pathinfo['extension'];
806 * Return all types that you a user can create/edit and which are also visible
807 * Note: Mostly used in order to know if at least one editable type can be set
809 * @static
810 * @param stdClass $context the context for which we want the editable types
811 * @return array types
813 public static function get_editable_types($context = null) {
815 if (empty($context)) {
816 $context = get_system_context();
819 $types= repository::get_types(true);
820 $editabletypes = array();
821 foreach ($types as $type) {
822 $instanceoptionnames = repository::static_function($type->get_typename(), 'get_instance_option_names');
823 if (!empty($instanceoptionnames)) {
824 if ($type->get_contextvisibility($context)) {
825 $editabletypes[]=$type;
829 return $editabletypes;
833 * Return repository instances
835 * @static
836 * @param array $args Array containing the following keys:
837 * currentcontext
838 * context
839 * onlyvisible
840 * type
841 * accepted_types
842 * return_types
843 * userid
845 * @return array repository instances
847 public static function get_instances($args = array()) {
848 global $DB, $CFG, $USER;
850 if (isset($args['currentcontext'])) {
851 $current_context = $args['currentcontext'];
852 } else {
853 $current_context = null;
856 if (!empty($args['context'])) {
857 $contexts = $args['context'];
858 } else {
859 $contexts = array();
862 $onlyvisible = isset($args['onlyvisible']) ? $args['onlyvisible'] : true;
863 $returntypes = isset($args['return_types']) ? $args['return_types'] : 3;
864 $type = isset($args['type']) ? $args['type'] : null;
866 $params = array();
867 $sql = "SELECT i.*, r.type AS repositorytype, r.sortorder, r.visible
868 FROM {repository} r, {repository_instances} i
869 WHERE i.typeid = r.id ";
871 if (!empty($args['disable_types']) && is_array($args['disable_types'])) {
872 list($types, $p) = $DB->get_in_or_equal($args['disable_types'], SQL_PARAMS_QM, 'param', false);
873 $sql .= " AND r.type $types";
874 $params = array_merge($params, $p);
877 if (!empty($args['userid']) && is_numeric($args['userid'])) {
878 $sql .= " AND (i.userid = 0 or i.userid = ?)";
879 $params[] = $args['userid'];
882 foreach ($contexts as $context) {
883 if (empty($firstcontext)) {
884 $firstcontext = true;
885 $sql .= " AND ((i.contextid = ?)";
886 } else {
887 $sql .= " OR (i.contextid = ?)";
889 $params[] = $context->id;
892 if (!empty($firstcontext)) {
893 $sql .=')';
896 if ($onlyvisible == true) {
897 $sql .= " AND (r.visible = 1)";
900 if (isset($type)) {
901 $sql .= " AND (r.type = ?)";
902 $params[] = $type;
904 $sql .= " ORDER BY r.sortorder, i.name";
906 if (!$records = $DB->get_records_sql($sql, $params)) {
907 $records = array();
910 $repositories = array();
911 if (isset($args['accepted_types'])) {
912 $accepted_types = $args['accepted_types'];
913 if (is_array($accepted_types) && in_array('*', $accepted_types)) {
914 $accepted_types = '*';
916 } else {
917 $accepted_types = '*';
919 // Sortorder should be unique, which is not true if we use $record->sortorder
920 // and there are multiple instances of any repository type
921 $sortorder = 1;
922 foreach ($records as $record) {
923 if (!file_exists($CFG->dirroot . '/repository/'. $record->repositorytype.'/lib.php')) {
924 continue;
926 require_once($CFG->dirroot . '/repository/'. $record->repositorytype.'/lib.php');
927 $options['visible'] = $record->visible;
928 $options['type'] = $record->repositorytype;
929 $options['typeid'] = $record->typeid;
930 $options['sortorder'] = $sortorder++;
931 // tell instance what file types will be accepted by file picker
932 $classname = 'repository_' . $record->repositorytype;
934 $repository = new $classname($record->id, $record->contextid, $options, $record->readonly);
936 $is_supported = true;
938 if (empty($repository->super_called)) {
939 // to make sure the super construct is called
940 debugging('parent::__construct must be called by '.$record->repositorytype.' plugin.');
941 } else {
942 // check mimetypes
943 if ($accepted_types !== '*' and $repository->supported_filetypes() !== '*') {
944 $accepted_ext = file_get_typegroup('extension', $accepted_types);
945 $supported_ext = file_get_typegroup('extension', $repository->supported_filetypes());
946 $valid_ext = array_intersect($accepted_ext, $supported_ext);
947 $is_supported = !empty($valid_ext);
949 // check return values
950 if ($returntypes !== 3 and $repository->supported_returntypes() !== 3) {
951 $type = $repository->supported_returntypes();
952 if ($type & $returntypes) {
954 } else {
955 $is_supported = false;
959 if (!$onlyvisible || ($repository->is_visible() && !$repository->disabled)) {
960 // check capability in current context
961 if (!empty($current_context)) {
962 $capability = has_capability('repository/'.$record->repositorytype.':view', $current_context);
963 } else {
964 $capability = has_capability('repository/'.$record->repositorytype.':view', get_system_context());
966 if ($record->repositorytype == 'coursefiles') {
967 // coursefiles plugin needs managefiles permission
968 if (!empty($current_context)) {
969 $capability = $capability && has_capability('moodle/course:managefiles', $current_context);
970 } else {
971 $capability = $capability && has_capability('moodle/course:managefiles', get_system_context());
974 if ($is_supported && $capability) {
975 $repositories[$repository->id] = $repository;
980 return $repositories;
984 * Get single repository instance
986 * @static
987 * @param integer $id repository id
988 * @return object repository instance
990 public static function get_instance($id) {
991 global $DB, $CFG;
992 $sql = "SELECT i.*, r.type AS repositorytype, r.visible
993 FROM {repository} r
994 JOIN {repository_instances} i ON i.typeid = r.id
995 WHERE i.id = ?";
997 if (!$instance = $DB->get_record_sql($sql, array($id))) {
998 return false;
1000 require_once($CFG->dirroot . '/repository/'. $instance->repositorytype.'/lib.php');
1001 $classname = 'repository_' . $instance->repositorytype;
1002 $options['typeid'] = $instance->typeid;
1003 $options['type'] = $instance->repositorytype;
1004 $options['name'] = $instance->name;
1005 $obj = new $classname($instance->id, $instance->contextid, $options, $instance->readonly);
1006 if (empty($obj->super_called)) {
1007 debugging('parent::__construct must be called by '.$classname.' plugin.');
1009 return $obj;
1013 * Call a static function. Any additional arguments than plugin and function will be passed through.
1015 * @static
1016 * @param string $plugin repository plugin name
1017 * @param string $function funciton name
1018 * @return mixed
1020 public static function static_function($plugin, $function) {
1021 global $CFG;
1023 //check that the plugin exists
1024 $typedirectory = $CFG->dirroot . '/repository/'. $plugin . '/lib.php';
1025 if (!file_exists($typedirectory)) {
1026 //throw new repository_exception('invalidplugin', 'repository');
1027 return false;
1030 $pname = null;
1031 if (is_object($plugin) || is_array($plugin)) {
1032 $plugin = (object)$plugin;
1033 $pname = $plugin->name;
1034 } else {
1035 $pname = $plugin;
1038 $args = func_get_args();
1039 if (count($args) <= 2) {
1040 $args = array();
1041 } else {
1042 array_shift($args);
1043 array_shift($args);
1046 require_once($typedirectory);
1047 return call_user_func_array(array('repository_' . $plugin, $function), $args);
1051 * Scan file, throws exception in case of infected file.
1053 * Please note that the scanning engine must be able to access the file,
1054 * permissions of the file are not modified here!
1056 * @static
1057 * @param string $thefile
1058 * @param string $filename name of the file
1059 * @param bool $deleteinfected
1061 public static function antivir_scan_file($thefile, $filename, $deleteinfected) {
1062 global $CFG;
1064 if (!is_readable($thefile)) {
1065 // this should not happen
1066 return;
1069 if (empty($CFG->runclamonupload) or empty($CFG->pathtoclam)) {
1070 // clam not enabled
1071 return;
1074 $CFG->pathtoclam = trim($CFG->pathtoclam);
1076 if (!file_exists($CFG->pathtoclam) or !is_executable($CFG->pathtoclam)) {
1077 // misconfigured clam - use the old notification for now
1078 require("$CFG->libdir/uploadlib.php");
1079 $notice = get_string('clamlost', 'moodle', $CFG->pathtoclam);
1080 clam_message_admins($notice);
1081 return;
1084 // do NOT mess with permissions here, the calling party is responsible for making
1085 // sure the scanner engine can access the files!
1087 // execute test
1088 $cmd = escapeshellcmd($CFG->pathtoclam).' --stdout '.escapeshellarg($thefile);
1089 exec($cmd, $output, $return);
1091 if ($return == 0) {
1092 // perfect, no problem found
1093 return;
1095 } else if ($return == 1) {
1096 // infection found
1097 if ($deleteinfected) {
1098 unlink($thefile);
1100 throw new moodle_exception('virusfounduser', 'moodle', '', array('filename'=>$filename));
1102 } else {
1103 //unknown problem
1104 require("$CFG->libdir/uploadlib.php");
1105 $notice = get_string('clamfailed', 'moodle', get_clam_error_code($return));
1106 $notice .= "\n\n". implode("\n", $output);
1107 clam_message_admins($notice);
1108 if ($CFG->clamfailureonupload === 'actlikevirus') {
1109 if ($deleteinfected) {
1110 unlink($thefile);
1112 throw new moodle_exception('virusfounduser', 'moodle', '', array('filename'=>$filename));
1113 } else {
1114 return;
1120 * Repository method to serve the referenced file
1122 * @see send_stored_file
1124 * @param stored_file $storedfile the file that contains the reference
1125 * @param int $lifetime Number of seconds before the file should expire from caches (default 24 hours)
1126 * @param int $filter 0 (default)=no filtering, 1=all files, 2=html files only
1127 * @param bool $forcedownload If true (default false), forces download of file rather than view in browser/plugin
1128 * @param array $options additional options affecting the file serving
1130 public function send_file($storedfile, $lifetime=86400 , $filter=0, $forcedownload=false, array $options = null) {
1131 if ($this->has_moodle_files()) {
1132 $fs = get_file_storage();
1133 $params = file_storage::unpack_reference($storedfile->get_reference(), true);
1134 $srcfile = null;
1135 if (is_array($params)) {
1136 $srcfile = $fs->get_file($params['contextid'], $params['component'], $params['filearea'],
1137 $params['itemid'], $params['filepath'], $params['filename']);
1139 if (empty($options)) {
1140 $options = array();
1142 if (!isset($options['filename'])) {
1143 $options['filename'] = $storedfile->get_filename();
1145 if (!$srcfile) {
1146 send_file_not_found();
1147 } else {
1148 send_stored_file($srcfile, $lifetime, $filter, $forcedownload, $options);
1150 } else {
1151 throw new coding_exception("Repository plugin must implement send_file() method.");
1156 * Return reference file life time
1158 * @param string $ref
1159 * @return int
1161 public function get_reference_file_lifetime($ref) {
1162 // One day
1163 return 60 * 60 * 24;
1167 * Decide whether or not the file should be synced
1169 * @param stored_file $storedfile
1170 * @return bool
1172 public function sync_individual_file(stored_file $storedfile) {
1173 return true;
1177 * Return human readable reference information
1179 * @param string $reference value of DB field files_reference.reference
1180 * @param int $filestatus status of the file, 0 - ok, 666 - source missing
1181 * @return string
1183 public function get_reference_details($reference, $filestatus = 0) {
1184 if ($this->has_moodle_files()) {
1185 $fileinfo = null;
1186 $params = file_storage::unpack_reference($reference, true);
1187 if (is_array($params)) {
1188 $context = context::instance_by_id($params['contextid'], IGNORE_MISSING);
1189 if ($context) {
1190 $browser = get_file_browser();
1191 $fileinfo = $browser->get_file_info($context, $params['component'], $params['filearea'], $params['itemid'], $params['filepath'], $params['filename']);
1194 if (empty($fileinfo)) {
1195 if ($filestatus == 666) {
1196 if (is_siteadmin() || ($context && has_capability('moodle/course:managefiles', $context))) {
1197 return get_string('lostsource', 'repository',
1198 $params['contextid']. '/'. $params['component']. '/'. $params['filearea']. '/'. $params['itemid']. $params['filepath']. $params['filename']);
1199 } else {
1200 return get_string('lostsource', 'repository', '');
1203 return get_string('undisclosedsource', 'repository');
1204 } else {
1205 return $fileinfo->get_readable_fullname();
1208 return '';
1212 * Cache file from external repository by reference
1213 * {@link repository::get_file_reference()}
1214 * {@link repository::get_file()}
1215 * Invoked at MOODLE/repository/repository_ajax.php
1217 * @param string $reference this reference is generated by
1218 * repository::get_file_reference()
1219 * @param stored_file $storedfile created file reference
1221 public function cache_file_by_reference($reference, $storedfile) {
1225 * Returns information about file in this repository by reference
1227 * This function must be implemented for repositories supporting FILE_REFERENCE, it is called
1228 * for existing aliases when the lifetime of the previous syncronisation has expired.
1230 * Returns null if file not found or is not readable or timeout occured during request.
1231 * Note that this function may be run for EACH file that needs to be synchronised at the
1232 * moment. If anything is being downloaded or requested from external sources there
1233 * should be a small timeout. The synchronisation is performed to update the size of
1234 * the file and/or to update image and re-generated image preview. There is nothing
1235 * fatal if syncronisation fails but it is fatal if syncronisation takes too long
1236 * and hangs the script generating a page.
1238 * If get_file_by_reference() returns filesize just the record in {files} table is being updated.
1239 * If filepath, handle or content are returned - the file is also stored in moodle filepool
1240 * (recommended for images to generate the thumbnails). For non-image files it is not
1241 * recommended to download them to moodle during syncronisation since it may take
1242 * unnecessary long time.
1244 * @param stdClass $reference record from DB table {files_reference}
1245 * @return stdClass|null contains one of the following:
1246 * - 'filesize' and optionally 'contenthash'
1247 * - 'filepath'
1248 * - 'handle'
1249 * - 'content'
1251 public function get_file_by_reference($reference) {
1252 if ($this->has_moodle_files() && isset($reference->reference)) {
1253 $fs = get_file_storage();
1254 $params = file_storage::unpack_reference($reference->reference, true);
1255 if (!is_array($params) || !($storedfile = $fs->get_file($params['contextid'],
1256 $params['component'], $params['filearea'], $params['itemid'], $params['filepath'],
1257 $params['filename']))) {
1258 return null;
1260 return (object)array(
1261 'contenthash' => $storedfile->get_contenthash(),
1262 'filesize' => $storedfile->get_filesize()
1265 return null;
1269 * Return the source information
1271 * The result of the function is stored in files.source field. It may be analysed
1272 * when the source file is lost or repository may use it to display human-readable
1273 * location of reference original.
1275 * This method is called when file is picked for the first time only. When file
1276 * (either copy or a reference) is already in moodle and it is being picked
1277 * again to another file area (also as a copy or as a reference), the value of
1278 * files.source is copied.
1280 * @param string $source the value that repository returned in listing as 'source'
1281 * @return string|null
1283 public function get_file_source_info($source) {
1284 if ($this->has_moodle_files()) {
1285 return $this->get_reference_details($source, 0);
1287 return $source;
1291 * Move file from download folder to file pool using FILE API
1293 * @todo MDL-28637
1294 * @static
1295 * @param string $thefile file path in download folder
1296 * @param stdClass $record
1297 * @return array containing the following keys:
1298 * icon
1299 * file
1300 * id
1301 * url
1303 public static function move_to_filepool($thefile, $record) {
1304 global $DB, $CFG, $USER, $OUTPUT;
1306 // scan for viruses if possible, throws exception if problem found
1307 self::antivir_scan_file($thefile, $record->filename, empty($CFG->repository_no_delete)); //TODO: MDL-28637 this repository_no_delete is a bloody hack!
1309 $fs = get_file_storage();
1310 // If file name being used.
1311 if (repository::draftfile_exists($record->itemid, $record->filepath, $record->filename)) {
1312 $draftitemid = $record->itemid;
1313 $new_filename = repository::get_unused_filename($draftitemid, $record->filepath, $record->filename);
1314 $old_filename = $record->filename;
1315 // Create a tmp file.
1316 $record->filename = $new_filename;
1317 $newfile = $fs->create_file_from_pathname($record, $thefile);
1318 $event = array();
1319 $event['event'] = 'fileexists';
1320 $event['newfile'] = new stdClass;
1321 $event['newfile']->filepath = $record->filepath;
1322 $event['newfile']->filename = $new_filename;
1323 $event['newfile']->url = moodle_url::make_draftfile_url($draftitemid, $record->filepath, $new_filename)->out();
1325 $event['existingfile'] = new stdClass;
1326 $event['existingfile']->filepath = $record->filepath;
1327 $event['existingfile']->filename = $old_filename;
1328 $event['existingfile']->url = moodle_url::make_draftfile_url($draftitemid, $record->filepath, $old_filename)->out();
1329 return $event;
1331 if ($file = $fs->create_file_from_pathname($record, $thefile)) {
1332 if (empty($CFG->repository_no_delete)) {
1333 $delete = unlink($thefile);
1334 unset($CFG->repository_no_delete);
1336 return array(
1337 'url'=>moodle_url::make_draftfile_url($file->get_itemid(), $file->get_filepath(), $file->get_filename())->out(),
1338 'id'=>$file->get_itemid(),
1339 'file'=>$file->get_filename(),
1340 'icon' => $OUTPUT->pix_url(file_extension_icon($thefile, 32))->out(),
1342 } else {
1343 return null;
1348 * Builds a tree of files This function is then called recursively.
1350 * @static
1351 * @todo take $search into account, and respect a threshold for dynamic loading
1352 * @param file_info $fileinfo an object returned by file_browser::get_file_info()
1353 * @param string $search searched string
1354 * @param bool $dynamicmode no recursive call is done when in dynamic mode
1355 * @param array $list the array containing the files under the passed $fileinfo
1356 * @return int the number of files found
1358 public static function build_tree($fileinfo, $search, $dynamicmode, &$list) {
1359 global $CFG, $OUTPUT;
1361 $filecount = 0;
1362 $children = $fileinfo->get_children();
1364 foreach ($children as $child) {
1365 $filename = $child->get_visible_name();
1366 $filesize = $child->get_filesize();
1367 $filesize = $filesize ? display_size($filesize) : '';
1368 $filedate = $child->get_timemodified();
1369 $filedate = $filedate ? userdate($filedate) : '';
1370 $filetype = $child->get_mimetype();
1372 if ($child->is_directory()) {
1373 $path = array();
1374 $level = $child->get_parent();
1375 while ($level) {
1376 $params = $level->get_params();
1377 $path[] = array($params['filepath'], $level->get_visible_name());
1378 $level = $level->get_parent();
1381 $tmp = array(
1382 'title' => $child->get_visible_name(),
1383 'size' => 0,
1384 'date' => $filedate,
1385 'path' => array_reverse($path),
1386 'thumbnail' => $OUTPUT->pix_url(file_folder_icon(90))->out(false)
1389 //if ($dynamicmode && $child->is_writable()) {
1390 // $tmp['children'] = array();
1391 //} else {
1392 // if folder name matches search, we send back all files contained.
1393 $_search = $search;
1394 if ($search && stristr($tmp['title'], $search) !== false) {
1395 $_search = false;
1397 $tmp['children'] = array();
1398 $_filecount = repository::build_tree($child, $_search, $dynamicmode, $tmp['children']);
1399 if ($search && $_filecount) {
1400 $tmp['expanded'] = 1;
1405 if (!$search || $_filecount || (stristr($tmp['title'], $search) !== false)) {
1406 $filecount += $_filecount;
1407 $list[] = $tmp;
1410 } else { // not a directory
1411 // skip the file, if we're in search mode and it's not a match
1412 if ($search && (stristr($filename, $search) === false)) {
1413 continue;
1415 $params = $child->get_params();
1416 $source = serialize(array($params['contextid'], $params['component'], $params['filearea'], $params['itemid'], $params['filepath'], $params['filename']));
1417 $list[] = array(
1418 'title' => $filename,
1419 'size' => $filesize,
1420 'date' => $filedate,
1421 //'source' => $child->get_url(),
1422 'source' => base64_encode($source),
1423 'icon'=>$OUTPUT->pix_url(file_file_icon($child, 24))->out(false),
1424 'thumbnail'=>$OUTPUT->pix_url(file_file_icon($child, 90))->out(false),
1426 $filecount++;
1430 return $filecount;
1434 * Display a repository instance list (with edit/delete/create links)
1436 * @static
1437 * @param stdClass $context the context for which we display the instance
1438 * @param string $typename if set, we display only one type of instance
1440 public static function display_instances_list($context, $typename = null) {
1441 global $CFG, $USER, $OUTPUT;
1443 $output = $OUTPUT->box_start('generalbox');
1444 //if the context is SYSTEM, so we call it from administration page
1445 $admin = ($context->id == SYSCONTEXTID) ? true : false;
1446 if ($admin) {
1447 $baseurl = new moodle_url('/'.$CFG->admin.'/repositoryinstance.php', array('sesskey'=>sesskey()));
1448 $output .= $OUTPUT->heading(get_string('siteinstances', 'repository'));
1449 } else {
1450 $baseurl = new moodle_url('/repository/manage_instances.php', array('contextid'=>$context->id, 'sesskey'=>sesskey()));
1453 $namestr = get_string('name');
1454 $pluginstr = get_string('plugin', 'repository');
1455 $settingsstr = get_string('settings');
1456 $deletestr = get_string('delete');
1457 //retrieve list of instances. In administration context we want to display all
1458 //instances of a type, even if this type is not visible. In course/user context we
1459 //want to display only visible instances, but for every type types. The repository::get_instances()
1460 //third parameter displays only visible type.
1461 $params = array();
1462 $params['context'] = array($context, get_system_context());
1463 $params['currentcontext'] = $context;
1464 $params['onlyvisible'] = !$admin;
1465 $params['type'] = $typename;
1466 $instances = repository::get_instances($params);
1467 $instancesnumber = count($instances);
1468 $alreadyplugins = array();
1470 $table = new html_table();
1471 $table->head = array($namestr, $pluginstr, $settingsstr, $deletestr);
1472 $table->align = array('left', 'left', 'center','center');
1473 $table->data = array();
1475 $updowncount = 1;
1477 foreach ($instances as $i) {
1478 $settings = '';
1479 $delete = '';
1481 $type = repository::get_type_by_id($i->options['typeid']);
1483 if ($type->get_contextvisibility($context)) {
1484 if (!$i->readonly) {
1486 $settingurl = new moodle_url($baseurl);
1487 $settingurl->param('type', $i->options['type']);
1488 $settingurl->param('edit', $i->id);
1489 $settings .= html_writer::link($settingurl, $settingsstr);
1491 $deleteurl = new moodle_url($baseurl);
1492 $deleteurl->param('delete', $i->id);
1493 $deleteurl->param('type', $i->options['type']);
1494 $delete .= html_writer::link($deleteurl, $deletestr);
1498 $type = repository::get_type_by_id($i->options['typeid']);
1499 $table->data[] = array(format_string($i->name), $type->get_readablename(), $settings, $delete);
1501 //display a grey row if the type is defined as not visible
1502 if (isset($type) && !$type->get_visible()) {
1503 $table->rowclasses[] = 'dimmed_text';
1504 } else {
1505 $table->rowclasses[] = '';
1508 if (!in_array($i->name, $alreadyplugins)) {
1509 $alreadyplugins[] = $i->name;
1512 $output .= html_writer::table($table);
1513 $instancehtml = '<div>';
1514 $addable = 0;
1516 //if no type is set, we can create all type of instance
1517 if (!$typename) {
1518 $instancehtml .= '<h3>';
1519 $instancehtml .= get_string('createrepository', 'repository');
1520 $instancehtml .= '</h3><ul>';
1521 $types = repository::get_editable_types($context);
1522 foreach ($types as $type) {
1523 if (!empty($type) && $type->get_visible()) {
1524 // If the user does not have the permission to view the repository, it won't be displayed in
1525 // the list of instances. Hiding the link to create new instances will prevent the
1526 // user from creating them without being able to find them afterwards, which looks like a bug.
1527 if (!has_capability('repository/'.$type->get_typename().':view', $context)) {
1528 continue;
1530 $instanceoptionnames = repository::static_function($type->get_typename(), 'get_instance_option_names');
1531 if (!empty($instanceoptionnames)) {
1532 $baseurl->param('new', $type->get_typename());
1533 $instancehtml .= '<li><a href="'.$baseurl->out().'">'.get_string('createxxinstance', 'repository', get_string('pluginname', 'repository_'.$type->get_typename())). '</a></li>';
1534 $baseurl->remove_params('new');
1535 $addable++;
1539 $instancehtml .= '</ul>';
1541 } else {
1542 $instanceoptionnames = repository::static_function($typename, 'get_instance_option_names');
1543 if (!empty($instanceoptionnames)) { //create a unique type of instance
1544 $addable = 1;
1545 $baseurl->param('new', $typename);
1546 $output .= $OUTPUT->single_button($baseurl, get_string('createinstance', 'repository'), 'get');
1547 $baseurl->remove_params('new');
1551 if ($addable) {
1552 $instancehtml .= '</div>';
1553 $output .= $instancehtml;
1556 $output .= $OUTPUT->box_end();
1558 //print the list + creation links
1559 print($output);
1563 * Prepare file reference information
1565 * @param string $source
1566 * @return string file referece
1568 public function get_file_reference($source) {
1569 if ($this->has_moodle_files() && ($this->supported_returntypes() & FILE_REFERENCE)) {
1570 $params = file_storage::unpack_reference($source);
1571 if (!is_array($params)) {
1572 throw new repository_exception('invalidparams', 'repository');
1574 return file_storage::pack_reference($params);
1576 return $source;
1580 * Decide where to save the file, can be overwriten by subclass
1582 * @param string $filename file name
1583 * @return file path
1585 public function prepare_file($filename) {
1586 global $CFG;
1587 $dir = make_temp_directory('download/'.get_class($this).'/');
1588 while (empty($filename) || file_exists($dir.$filename)) {
1589 $filename = uniqid('', true).'_'.time().'.tmp';
1591 return $dir.$filename;
1595 * Does this repository used to browse moodle files?
1597 * @return bool
1599 public function has_moodle_files() {
1600 return false;
1604 * Return file URL, for most plugins, the parameter is the original
1605 * url, but some plugins use a file id, so we need this function to
1606 * convert file id to original url.
1608 * @param string $url the url of file
1609 * @return string
1611 public function get_link($url) {
1612 return $url;
1616 * Downloads a file from external repository and saves it in temp dir
1618 * Function get_file() must be implemented by repositories that support returntypes
1619 * FILE_INTERNAL or FILE_REFERENCE. It is invoked to pick up the file and copy it
1620 * to moodle. This function is not called for moodle repositories, the function
1621 * {@link repository::copy_to_area()} is used instead.
1623 * This function can be overridden by subclass if the files.reference field contains
1624 * not just URL or if request should be done differently.
1626 * @see curl
1627 * @throws file_exception when error occured
1629 * @param string $url the content of files.reference field, in this implementaion
1630 * it is asssumed that it contains the string with URL of the file
1631 * @param string $filename filename (without path) to save the downloaded file in the
1632 * temporary directory, if omitted or file already exists the new filename will be generated
1633 * @return array with elements:
1634 * path: internal location of the file
1635 * url: URL to the source (from parameters)
1637 public function get_file($url, $filename = '') {
1638 $path = $this->prepare_file($filename);
1639 $c = new curl;
1640 $result = $c->download_one($url, null, array('filepath' => $path, 'timeout' => self::GETFILE_TIMEOUT));
1641 if ($result !== true) {
1642 throw new moodle_exception('errorwhiledownload', 'repository', '', $result);
1644 return array('path'=>$path, 'url'=>$url);
1648 * Downloads the file from external repository and saves it in moodle filepool.
1649 * This function is different from {@link repository::sync_external_file()} because it has
1650 * bigger request timeout and always downloads the content.
1652 * This function is invoked when we try to unlink the file from the source and convert
1653 * a reference into a true copy.
1655 * @throws exception when file could not be imported
1657 * @param stored_file $file
1658 * @param int $maxbytes throw an exception if file size is bigger than $maxbytes (0 means no limit)
1660 public function import_external_file_contents(stored_file $file, $maxbytes = 0) {
1661 if (!$file->is_external_file()) {
1662 // nothing to import if the file is not a reference
1663 return;
1664 } else if ($file->get_repository_id() != $this->id) {
1665 // error
1666 debugging('Repository instance id does not match');
1667 return;
1668 } else if ($this->has_moodle_files()) {
1669 // files that are references to local files are already in moodle filepool
1670 // just validate the size
1671 if ($maxbytes > 0 && $file->get_filesize() > $maxbytes) {
1672 throw new file_exception('maxbytes');
1674 return;
1675 } else {
1676 if ($maxbytes > 0 && $file->get_filesize() > $maxbytes) {
1677 // note that stored_file::get_filesize() also calls synchronisation
1678 throw new file_exception('maxbytes');
1680 $fs = get_file_storage();
1681 $contentexists = $fs->content_exists($file->get_contenthash());
1682 if ($contentexists && $file->get_filesize() && $file->get_contenthash() === sha1('')) {
1683 // even when 'file_storage::content_exists()' returns true this may be an empty
1684 // content for the file that was not actually downloaded
1685 $contentexists = false;
1687 $now = time();
1688 if ($file->get_referencelastsync() + $file->get_referencelifetime() >= $now &&
1689 !$file->get_status() &&
1690 $contentexists) {
1691 // we already have the content in moodle filepool and it was synchronised recently.
1692 // Repositories may overwrite it if they want to force synchronisation anyway!
1693 return;
1694 } else {
1695 // attempt to get a file
1696 try {
1697 $fileinfo = $this->get_file($file->get_reference());
1698 if (isset($fileinfo['path'])) {
1699 list($contenthash, $filesize, $newfile) = $fs->add_file_to_pool($fileinfo['path']);
1700 // set this file and other similar aliases synchronised
1701 $lifetime = $this->get_reference_file_lifetime($file->get_reference());
1702 $file->set_synchronized($contenthash, $filesize, 0, $lifetime);
1703 } else {
1704 throw new moodle_exception('errorwhiledownload', 'repository', '', '');
1706 } catch (Exception $e) {
1707 if ($contentexists) {
1708 // better something than nothing. We have a copy of file. It's sync time
1709 // has expired but it is still very likely that it is the last version
1710 } else {
1711 throw($e);
1719 * Return size of a file in bytes.
1721 * @param string $source encoded and serialized data of file
1722 * @return int file size in bytes
1724 public function get_file_size($source) {
1725 // TODO MDL-33297 remove this function completely?
1726 $browser = get_file_browser();
1727 $params = unserialize(base64_decode($source));
1728 $contextid = clean_param($params['contextid'], PARAM_INT);
1729 $fileitemid = clean_param($params['itemid'], PARAM_INT);
1730 $filename = clean_param($params['filename'], PARAM_FILE);
1731 $filepath = clean_param($params['filepath'], PARAM_PATH);
1732 $filearea = clean_param($params['filearea'], PARAM_AREA);
1733 $component = clean_param($params['component'], PARAM_COMPONENT);
1734 $context = context::instance_by_id($contextid);
1735 $file_info = $browser->get_file_info($context, $component, $filearea, $fileitemid, $filepath, $filename);
1736 if (!empty($file_info)) {
1737 $filesize = $file_info->get_filesize();
1738 } else {
1739 $filesize = null;
1741 return $filesize;
1745 * Return is the instance is visible
1746 * (is the type visible ? is the context enable ?)
1748 * @return bool
1750 public function is_visible() {
1751 $type = repository::get_type_by_id($this->options['typeid']);
1752 $instanceoptions = repository::static_function($type->get_typename(), 'get_instance_option_names');
1754 if ($type->get_visible()) {
1755 //if the instance is unique so it's visible, otherwise check if the instance has a enabled context
1756 if (empty($instanceoptions) || $type->get_contextvisibility($this->context)) {
1757 return true;
1761 return false;
1765 * Return the name of this instance, can be overridden.
1767 * @return string
1769 public function get_name() {
1770 global $DB;
1771 if ( $name = $this->instance->name ) {
1772 return $name;
1773 } else {
1774 return get_string('pluginname', 'repository_' . $this->options['type']);
1779 * What kind of files will be in this repository?
1781 * @return array return '*' means this repository support any files, otherwise
1782 * return mimetypes of files, it can be an array
1784 public function supported_filetypes() {
1785 // return array('text/plain', 'image/gif');
1786 return '*';
1790 * Tells how the file can be picked from this repository
1792 * Maximum value is FILE_INTERNAL | FILE_EXTERNAL | FILE_REFERENCE
1794 * @return int
1796 public function supported_returntypes() {
1797 return (FILE_INTERNAL | FILE_EXTERNAL);
1801 * Provide repository instance information for Ajax
1803 * @return stdClass
1805 final public function get_meta() {
1806 global $CFG, $OUTPUT;
1807 $meta = new stdClass();
1808 $meta->id = $this->id;
1809 $meta->name = format_string($this->get_name());
1810 $meta->type = $this->options['type'];
1811 $meta->icon = $OUTPUT->pix_url('icon', 'repository_'.$meta->type)->out(false);
1812 $meta->supported_types = file_get_typegroup('extension', $this->supported_filetypes());
1813 $meta->return_types = $this->supported_returntypes();
1814 $meta->sortorder = $this->options['sortorder'];
1815 return $meta;
1819 * Create an instance for this plug-in
1821 * @static
1822 * @param string $type the type of the repository
1823 * @param int $userid the user id
1824 * @param stdClass $context the context
1825 * @param array $params the options for this instance
1826 * @param int $readonly whether to create it readonly or not (defaults to not)
1827 * @return mixed
1829 public static function create($type, $userid, $context, $params, $readonly=0) {
1830 global $CFG, $DB;
1831 $params = (array)$params;
1832 require_once($CFG->dirroot . '/repository/'. $type . '/lib.php');
1833 $classname = 'repository_' . $type;
1834 if ($repo = $DB->get_record('repository', array('type'=>$type))) {
1835 $record = new stdClass();
1836 $record->name = $params['name'];
1837 $record->typeid = $repo->id;
1838 $record->timecreated = time();
1839 $record->timemodified = time();
1840 $record->contextid = $context->id;
1841 $record->readonly = $readonly;
1842 $record->userid = $userid;
1843 $id = $DB->insert_record('repository_instances', $record);
1844 $options = array();
1845 $configs = call_user_func($classname . '::get_instance_option_names');
1846 if (!empty($configs)) {
1847 foreach ($configs as $config) {
1848 if (isset($params[$config])) {
1849 $options[$config] = $params[$config];
1850 } else {
1851 $options[$config] = null;
1856 if (!empty($id)) {
1857 unset($options['name']);
1858 $instance = repository::get_instance($id);
1859 $instance->set_option($options);
1860 return $id;
1861 } else {
1862 return null;
1864 } else {
1865 return null;
1870 * delete a repository instance
1872 * @param bool $downloadcontents
1873 * @return bool
1875 final public function delete($downloadcontents = false) {
1876 global $DB;
1877 if ($downloadcontents) {
1878 $this->convert_references_to_local();
1880 try {
1881 $DB->delete_records('repository_instances', array('id'=>$this->id));
1882 $DB->delete_records('repository_instance_config', array('instanceid'=>$this->id));
1883 } catch (dml_exception $ex) {
1884 return false;
1886 return true;
1890 * Hide/Show a repository
1892 * @param string $hide
1893 * @return bool
1895 final public function hide($hide = 'toggle') {
1896 global $DB;
1897 if ($entry = $DB->get_record('repository', array('id'=>$this->id))) {
1898 if ($hide === 'toggle' ) {
1899 if (!empty($entry->visible)) {
1900 $entry->visible = 0;
1901 } else {
1902 $entry->visible = 1;
1904 } else {
1905 if (!empty($hide)) {
1906 $entry->visible = 0;
1907 } else {
1908 $entry->visible = 1;
1911 return $DB->update_record('repository', $entry);
1913 return false;
1917 * Save settings for repository instance
1918 * $repo->set_option(array('api_key'=>'f2188bde132', 'name'=>'dongsheng'));
1920 * @param array $options settings
1921 * @return bool
1923 public function set_option($options = array()) {
1924 global $DB;
1926 if (!empty($options['name'])) {
1927 $r = new stdClass();
1928 $r->id = $this->id;
1929 $r->name = $options['name'];
1930 $DB->update_record('repository_instances', $r);
1931 unset($options['name']);
1933 foreach ($options as $name=>$value) {
1934 if ($id = $DB->get_field('repository_instance_config', 'id', array('name'=>$name, 'instanceid'=>$this->id))) {
1935 $DB->set_field('repository_instance_config', 'value', $value, array('id'=>$id));
1936 } else {
1937 $config = new stdClass();
1938 $config->instanceid = $this->id;
1939 $config->name = $name;
1940 $config->value = $value;
1941 $DB->insert_record('repository_instance_config', $config);
1944 return true;
1948 * Get settings for repository instance
1950 * @param string $config
1951 * @return array Settings
1953 public function get_option($config = '') {
1954 global $DB;
1955 $entries = $DB->get_records('repository_instance_config', array('instanceid'=>$this->id));
1956 $ret = array();
1957 if (empty($entries)) {
1958 return $ret;
1960 foreach($entries as $entry) {
1961 $ret[$entry->name] = $entry->value;
1963 if (!empty($config)) {
1964 if (isset($ret[$config])) {
1965 return $ret[$config];
1966 } else {
1967 return null;
1969 } else {
1970 return $ret;
1975 * Filter file listing to display specific types
1977 * @param array $value
1978 * @return bool
1980 public function filter(&$value) {
1981 $accepted_types = optional_param_array('accepted_types', '', PARAM_RAW);
1982 if (isset($value['children'])) {
1983 if (!empty($value['children'])) {
1984 $value['children'] = array_filter($value['children'], array($this, 'filter'));
1986 return true; // always return directories
1987 } else {
1988 if ($accepted_types == '*' or empty($accepted_types)
1989 or (is_array($accepted_types) and in_array('*', $accepted_types))) {
1990 return true;
1991 } else {
1992 foreach ($accepted_types as $ext) {
1993 if (preg_match('#'.$ext.'$#i', $value['title'])) {
1994 return true;
1999 return false;
2003 * Given a path, and perhaps a search, get a list of files.
2005 * See details on {@link http://docs.moodle.org/dev/Repository_plugins}
2007 * @param string $path this parameter can a folder name, or a identification of folder
2008 * @param string $page the page number of file list
2009 * @return array the list of files, including meta infomation, containing the following keys
2010 * manage, url to manage url
2011 * client_id
2012 * login, login form
2013 * repo_id, active repository id
2014 * login_btn_action, the login button action
2015 * login_btn_label, the login button label
2016 * total, number of results
2017 * perpage, items per page
2018 * page
2019 * pages, total pages
2020 * issearchresult, is it a search result?
2021 * list, file list
2022 * path, current path and parent path
2024 public function get_listing($path = '', $page = '') {
2029 * Prepare the breadcrumb.
2031 * @param array $breadcrumb contains each element of the breadcrumb.
2032 * @return array of breadcrumb elements.
2033 * @since 2.3.3
2035 protected static function prepare_breadcrumb($breadcrumb) {
2036 global $OUTPUT;
2037 $foldericon = $OUTPUT->pix_url(file_folder_icon(24))->out(false);
2038 $len = count($breadcrumb);
2039 for ($i = 0; $i < $len; $i++) {
2040 if (is_array($breadcrumb[$i]) && !isset($breadcrumb[$i]['icon'])) {
2041 $breadcrumb[$i]['icon'] = $foldericon;
2042 } else if (is_object($breadcrumb[$i]) && !isset($breadcrumb[$i]->icon)) {
2043 $breadcrumb[$i]->icon = $foldericon;
2046 return $breadcrumb;
2050 * Prepare the file/folder listing.
2052 * @param array $list of files and folders.
2053 * @return array of files and folders.
2054 * @since 2.3.3
2056 protected static function prepare_list($list) {
2057 global $OUTPUT;
2058 $foldericon = $OUTPUT->pix_url(file_folder_icon(24))->out(false);
2060 // Reset the array keys because non-numeric keys will create an object when converted to JSON.
2061 $list = array_values($list);
2063 $len = count($list);
2064 for ($i = 0; $i < $len; $i++) {
2065 if (is_object($list[$i])) {
2066 $file = (array)$list[$i];
2067 $converttoobject = true;
2068 } else {
2069 $file =& $list[$i];
2070 $converttoobject = false;
2072 if (isset($file['size'])) {
2073 $file['size'] = (int)$file['size'];
2074 $file['size_f'] = display_size($file['size']);
2076 if (isset($file['license']) && get_string_manager()->string_exists($file['license'], 'license')) {
2077 $file['license_f'] = get_string($file['license'], 'license');
2079 if (isset($file['image_width']) && isset($file['image_height'])) {
2080 $a = array('width' => $file['image_width'], 'height' => $file['image_height']);
2081 $file['dimensions'] = get_string('imagesize', 'repository', (object)$a);
2083 foreach (array('date', 'datemodified', 'datecreated') as $key) {
2084 if (!isset($file[$key]) && isset($file['date'])) {
2085 $file[$key] = $file['date'];
2087 if (isset($file[$key])) {
2088 // must be UNIX timestamp
2089 $file[$key] = (int)$file[$key];
2090 if (!$file[$key]) {
2091 unset($file[$key]);
2092 } else {
2093 $file[$key.'_f'] = userdate($file[$key], get_string('strftimedatetime', 'langconfig'));
2094 $file[$key.'_f_s'] = userdate($file[$key], get_string('strftimedatetimeshort', 'langconfig'));
2098 $isfolder = (array_key_exists('children', $file) || (isset($file['type']) && $file['type'] == 'folder'));
2099 $filename = null;
2100 if (isset($file['title'])) {
2101 $filename = $file['title'];
2103 else if (isset($file['fullname'])) {
2104 $filename = $file['fullname'];
2106 if (!isset($file['mimetype']) && !$isfolder && $filename) {
2107 $file['mimetype'] = get_mimetype_description(array('filename' => $filename));
2109 if (!isset($file['icon'])) {
2110 if ($isfolder) {
2111 $file['icon'] = $foldericon;
2112 } else if ($filename) {
2113 $file['icon'] = $OUTPUT->pix_url(file_extension_icon($filename, 24))->out(false);
2117 // Recursively loop over children.
2118 if (isset($file['children'])) {
2119 $file['children'] = self::prepare_list($file['children']);
2122 // Convert the array back to an object.
2123 if ($converttoobject) {
2124 $list[$i] = (object)$file;
2127 return $list;
2131 * Prepares list of files before passing it to AJAX, makes sure data is in the correct
2132 * format and stores formatted values.
2134 * @param array|stdClass $listing result of get_listing() or search() or file_get_drafarea_files()
2135 * @return array
2137 public static function prepare_listing($listing) {
2138 $wasobject = false;
2139 if (is_object($listing)) {
2140 $listing = (array) $listing;
2141 $wasobject = true;
2144 // Prepare the breadcrumb, passed as 'path'.
2145 if (isset($listing['path']) && is_array($listing['path'])) {
2146 $listing['path'] = self::prepare_breadcrumb($listing['path']);
2149 // Prepare the listing of objects.
2150 if (isset($listing['list']) && is_array($listing['list'])) {
2151 $listing['list'] = self::prepare_list($listing['list']);
2154 // Convert back to an object.
2155 if ($wasobject) {
2156 $listing = (object) $listing;
2158 return $listing;
2162 * Search files in repository
2163 * When doing global search, $search_text will be used as
2164 * keyword.
2166 * @param string $search_text search key word
2167 * @param int $page page
2168 * @return mixed see {@link repository::get_listing()}
2170 public function search($search_text, $page = 0) {
2171 $list = array();
2172 $list['list'] = array();
2173 return false;
2177 * Logout from repository instance
2178 * By default, this function will return a login form
2180 * @return string
2182 public function logout(){
2183 return $this->print_login();
2187 * To check whether the user is logged in.
2189 * @return bool
2191 public function check_login(){
2192 return true;
2197 * Show the login screen, if required
2199 * @return string
2201 public function print_login(){
2202 return $this->get_listing();
2206 * Show the search screen, if required
2208 * @return string
2210 public function print_search() {
2211 global $PAGE;
2212 $renderer = $PAGE->get_renderer('core', 'files');
2213 return $renderer->repository_default_searchform();
2217 * For oauth like external authentication, when external repository direct user back to moodle,
2218 * this funciton will be called to set up token and token_secret
2220 public function callback() {
2224 * is it possible to do glboal search?
2226 * @return bool
2228 public function global_search() {
2229 return false;
2233 * Defines operations that happen occasionally on cron
2235 * @return bool
2237 public function cron() {
2238 return true;
2242 * function which is run when the type is created (moodle administrator add the plugin)
2244 * @return bool success or fail?
2246 public static function plugin_init() {
2247 return true;
2251 * Edit/Create Admin Settings Moodle form
2253 * @param moodleform $mform Moodle form (passed by reference)
2254 * @param string $classname repository class name
2256 public static function type_config_form($mform, $classname = 'repository') {
2257 $instnaceoptions = call_user_func(array($classname, 'get_instance_option_names'), $mform, $classname);
2258 if (empty($instnaceoptions)) {
2259 // this plugin has only one instance
2260 // so we need to give it a name
2261 // it can be empty, then moodle will look for instance name from language string
2262 $mform->addElement('text', 'pluginname', get_string('pluginname', 'repository'), array('size' => '40'));
2263 $mform->addElement('static', 'pluginnamehelp', '', get_string('pluginnamehelp', 'repository'));
2264 $mform->setType('pluginname', PARAM_TEXT);
2269 * Validate Admin Settings Moodle form
2271 * @static
2272 * @param moodleform $mform Moodle form (passed by reference)
2273 * @param array $data array of ("fieldname"=>value) of submitted data
2274 * @param array $errors array of ("fieldname"=>errormessage) of errors
2275 * @return array array of errors
2277 public static function type_form_validation($mform, $data, $errors) {
2278 return $errors;
2283 * Edit/Create Instance Settings Moodle form
2285 * @param moodleform $mform Moodle form (passed by reference)
2287 public static function instance_config_form($mform) {
2291 * Return names of the general options.
2292 * By default: no general option name
2294 * @return array
2296 public static function get_type_option_names() {
2297 return array('pluginname');
2301 * Return names of the instance options.
2302 * By default: no instance option name
2304 * @return array
2306 public static function get_instance_option_names() {
2307 return array();
2311 * Validate repository plugin instance form
2313 * @param moodleform $mform moodle form
2314 * @param array $data form data
2315 * @param array $errors errors
2316 * @return array errors
2318 public static function instance_form_validation($mform, $data, $errors) {
2319 return $errors;
2323 * Create a shorten filename
2325 * @param string $str filename
2326 * @param int $maxlength max file name length
2327 * @return string short filename
2329 public function get_short_filename($str, $maxlength) {
2330 if (textlib::strlen($str) >= $maxlength) {
2331 return trim(textlib::substr($str, 0, $maxlength)).'...';
2332 } else {
2333 return $str;
2338 * Overwrite an existing file
2340 * @param int $itemid
2341 * @param string $filepath
2342 * @param string $filename
2343 * @param string $newfilepath
2344 * @param string $newfilename
2345 * @return bool
2347 public static function overwrite_existing_draftfile($itemid, $filepath, $filename, $newfilepath, $newfilename) {
2348 global $USER;
2349 $fs = get_file_storage();
2350 $user_context = context_user::instance($USER->id);
2351 if ($file = $fs->get_file($user_context->id, 'user', 'draft', $itemid, $filepath, $filename)) {
2352 if ($tempfile = $fs->get_file($user_context->id, 'user', 'draft', $itemid, $newfilepath, $newfilename)) {
2353 // delete existing file to release filename
2354 $file->delete();
2355 // create new file
2356 $newfile = $fs->create_file_from_storedfile(array('filepath'=>$filepath, 'filename'=>$filename), $tempfile);
2357 // remove temp file
2358 $tempfile->delete();
2359 return true;
2362 return false;
2366 * Delete a temp file from draft area
2368 * @param int $draftitemid
2369 * @param string $filepath
2370 * @param string $filename
2371 * @return bool
2373 public static function delete_tempfile_from_draft($draftitemid, $filepath, $filename) {
2374 global $USER;
2375 $fs = get_file_storage();
2376 $user_context = context_user::instance($USER->id);
2377 if ($file = $fs->get_file($user_context->id, 'user', 'draft', $draftitemid, $filepath, $filename)) {
2378 $file->delete();
2379 return true;
2380 } else {
2381 return false;
2386 * Find all external files in this repo and import them
2388 public function convert_references_to_local() {
2389 $fs = get_file_storage();
2390 $files = $fs->get_external_files($this->id);
2391 foreach ($files as $storedfile) {
2392 $fs->import_external_file($storedfile);
2397 * Called from phpunit between tests, resets whatever was cached
2399 public static function reset_caches() {
2400 self::sync_external_file(null, true);
2404 * Performs synchronisation of reference to an external file if the previous one has expired.
2406 * @param stored_file $file
2407 * @param bool $resetsynchistory whether to reset all history of sync (used by phpunit)
2408 * @return bool success
2410 public static function sync_external_file($file, $resetsynchistory = false) {
2411 global $DB;
2412 // TODO MDL-25290 static should be replaced with MUC code.
2413 static $synchronized = array();
2414 if ($resetsynchistory) {
2415 $synchronized = array();
2418 $fs = get_file_storage();
2420 if (!$file || !$file->get_referencefileid()) {
2421 return false;
2423 if (array_key_exists($file->get_id(), $synchronized)) {
2424 return $synchronized[$file->get_id()];
2427 // remember that we already cached in current request to prevent from querying again
2428 $synchronized[$file->get_id()] = false;
2430 if (!$reference = $DB->get_record('files_reference', array('id'=>$file->get_referencefileid()))) {
2431 return false;
2434 if (!empty($reference->lastsync) and ($reference->lastsync + $reference->lifetime > time())) {
2435 $synchronized[$file->get_id()] = true;
2436 return true;
2439 if (!$repository = self::get_repository_by_id($reference->repositoryid, SYSCONTEXTID)) {
2440 return false;
2443 if (!$repository->sync_individual_file($file)) {
2444 return false;
2447 $lifetime = $repository->get_reference_file_lifetime($reference);
2448 $fileinfo = $repository->get_file_by_reference($reference);
2449 if ($fileinfo === null) {
2450 // does not exist any more - set status to missing
2451 $file->set_missingsource($lifetime);
2452 $synchronized[$file->get_id()] = true;
2453 return true;
2456 $contenthash = null;
2457 $filesize = null;
2458 if (!empty($fileinfo->filesize)) {
2459 // filesize returned
2460 if (!empty($fileinfo->contenthash) && $fs->content_exists($fileinfo->contenthash)) {
2461 // contenthash is specified and valid
2462 $contenthash = $fileinfo->contenthash;
2463 } else if ($fileinfo->filesize == $file->get_filesize()) {
2464 // we don't know the new contenthash but the filesize did not change,
2465 // assume the contenthash did not change either
2466 $contenthash = $file->get_contenthash();
2467 } else {
2468 // we can't save empty contenthash so generate contenthash from empty string
2469 $fs->add_string_to_pool('');
2470 $contenthash = sha1('');
2472 $filesize = $fileinfo->filesize;
2473 } else if (!empty($fileinfo->filepath)) {
2474 // File path returned
2475 list($contenthash, $filesize, $newfile) = $fs->add_file_to_pool($fileinfo->filepath);
2476 } else if (!empty($fileinfo->handle) && is_resource($fileinfo->handle)) {
2477 // File handle returned
2478 $contents = '';
2479 while (!feof($fileinfo->handle)) {
2480 $contents .= fread($handle, 8192);
2482 fclose($fileinfo->handle);
2483 list($contenthash, $filesize, $newfile) = $fs->add_string_to_pool($content);
2484 } else if (isset($fileinfo->content)) {
2485 // File content returned
2486 list($contenthash, $filesize, $newfile) = $fs->add_string_to_pool($fileinfo->content);
2489 if (!isset($contenthash) or !isset($filesize)) {
2490 return false;
2493 // update files table
2494 $file->set_synchronized($contenthash, $filesize, 0, $lifetime);
2495 $synchronized[$file->get_id()] = true;
2496 return true;
2500 * Build draft file's source field
2502 * {@link file_restore_source_field_from_draft_file()}
2503 * XXX: This is a hack for file manager (MDL-28666)
2504 * For newly created draft files we have to construct
2505 * source filed in php serialized data format.
2506 * File manager needs to know the original file information before copying
2507 * to draft area, so we append these information in mdl_files.source field
2509 * @param string $source
2510 * @return string serialised source field
2512 public static function build_source_field($source) {
2513 $sourcefield = new stdClass;
2514 $sourcefield->source = $source;
2515 return serialize($sourcefield);
2520 * Exception class for repository api
2522 * @since 2.0
2523 * @package core_repository
2524 * @copyright 2009 Dongsheng Cai {@link http://dongsheng.org}
2525 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2527 class repository_exception extends moodle_exception {
2531 * This is a class used to define a repository instance form
2533 * @since 2.0
2534 * @package core_repository
2535 * @copyright 2009 Dongsheng Cai {@link http://dongsheng.org}
2536 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2538 final class repository_instance_form extends moodleform {
2539 /** @var stdClass repository instance */
2540 protected $instance;
2541 /** @var string repository plugin type */
2542 protected $plugin;
2545 * Added defaults to moodle form
2547 protected function add_defaults() {
2548 $mform =& $this->_form;
2549 $strrequired = get_string('required');
2551 $mform->addElement('hidden', 'edit', ($this->instance) ? $this->instance->id : 0);
2552 $mform->setType('edit', PARAM_INT);
2553 $mform->addElement('hidden', 'new', $this->plugin);
2554 $mform->setType('new', PARAM_ALPHANUMEXT);
2555 $mform->addElement('hidden', 'plugin', $this->plugin);
2556 $mform->setType('plugin', PARAM_PLUGIN);
2557 $mform->addElement('hidden', 'typeid', $this->typeid);
2558 $mform->setType('typeid', PARAM_INT);
2559 $mform->addElement('hidden', 'contextid', $this->contextid);
2560 $mform->setType('contextid', PARAM_INT);
2562 $mform->addElement('text', 'name', get_string('name'), 'maxlength="100" size="30"');
2563 $mform->addRule('name', $strrequired, 'required', null, 'client');
2564 $mform->setType('name', PARAM_TEXT);
2568 * Define moodle form elements
2570 public function definition() {
2571 global $CFG;
2572 // type of plugin, string
2573 $this->plugin = $this->_customdata['plugin'];
2574 $this->typeid = $this->_customdata['typeid'];
2575 $this->contextid = $this->_customdata['contextid'];
2576 $this->instance = (isset($this->_customdata['instance'])
2577 && is_subclass_of($this->_customdata['instance'], 'repository'))
2578 ? $this->_customdata['instance'] : null;
2580 $mform =& $this->_form;
2582 $this->add_defaults();
2584 // Add instance config options.
2585 $result = repository::static_function($this->plugin, 'instance_config_form', $mform);
2586 if ($result === false) {
2587 // Remove the name element if no other config options.
2588 $mform->removeElement('name');
2590 if ($this->instance) {
2591 $data = array();
2592 $data['name'] = $this->instance->name;
2593 if (!$this->instance->readonly) {
2594 // and set the data if we have some.
2595 foreach ($this->instance->get_instance_option_names() as $config) {
2596 if (!empty($this->instance->options[$config])) {
2597 $data[$config] = $this->instance->options[$config];
2598 } else {
2599 $data[$config] = '';
2603 $this->set_data($data);
2606 if ($result === false) {
2607 $mform->addElement('cancel');
2608 } else {
2609 $this->add_action_buttons(true, get_string('save','repository'));
2614 * Validate moodle form data
2616 * @param array $data form data
2617 * @param array $files files in form
2618 * @return array errors
2620 public function validation($data, $files) {
2621 global $DB;
2622 $errors = array();
2623 $plugin = $this->_customdata['plugin'];
2624 $instance = (isset($this->_customdata['instance'])
2625 && is_subclass_of($this->_customdata['instance'], 'repository'))
2626 ? $this->_customdata['instance'] : null;
2627 if (!$instance) {
2628 $errors = repository::static_function($plugin, 'instance_form_validation', $this, $data, $errors);
2629 } else {
2630 $errors = $instance->instance_form_validation($this, $data, $errors);
2633 $sql = "SELECT count('x')
2634 FROM {repository_instances} i, {repository} r
2635 WHERE r.type=:plugin AND r.id=i.typeid AND i.name=:name";
2636 if ($DB->count_records_sql($sql, array('name' => $data['name'], 'plugin' => $data['plugin'])) > 1) {
2637 $errors['name'] = get_string('erroruniquename', 'repository');
2640 return $errors;
2645 * This is a class used to define a repository type setting form
2647 * @since 2.0
2648 * @package core_repository
2649 * @copyright 2009 Dongsheng Cai {@link http://dongsheng.org}
2650 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2652 final class repository_type_form extends moodleform {
2653 /** @var stdClass repository instance */
2654 protected $instance;
2655 /** @var string repository plugin name */
2656 protected $plugin;
2657 /** @var string action */
2658 protected $action;
2661 * Definition of the moodleform
2663 public function definition() {
2664 global $CFG;
2665 // type of plugin, string
2666 $this->plugin = $this->_customdata['plugin'];
2667 $this->instance = (isset($this->_customdata['instance'])
2668 && is_a($this->_customdata['instance'], 'repository_type'))
2669 ? $this->_customdata['instance'] : null;
2671 $this->action = $this->_customdata['action'];
2672 $this->pluginname = $this->_customdata['pluginname'];
2673 $mform =& $this->_form;
2674 $strrequired = get_string('required');
2676 $mform->addElement('hidden', 'action', $this->action);
2677 $mform->setType('action', PARAM_TEXT);
2678 $mform->addElement('hidden', 'repos', $this->plugin);
2679 $mform->setType('repos', PARAM_PLUGIN);
2681 // let the plugin add its specific fields
2682 $classname = 'repository_' . $this->plugin;
2683 require_once($CFG->dirroot . '/repository/' . $this->plugin . '/lib.php');
2684 //add "enable course/user instances" checkboxes if multiple instances are allowed
2685 $instanceoptionnames = repository::static_function($this->plugin, 'get_instance_option_names');
2687 $result = call_user_func(array($classname, 'type_config_form'), $mform, $classname);
2689 if (!empty($instanceoptionnames)) {
2690 $sm = get_string_manager();
2691 $component = 'repository';
2692 if ($sm->string_exists('enablecourseinstances', 'repository_' . $this->plugin)) {
2693 $component .= ('_' . $this->plugin);
2695 $mform->addElement('checkbox', 'enablecourseinstances', get_string('enablecourseinstances', $component));
2697 $component = 'repository';
2698 if ($sm->string_exists('enableuserinstances', 'repository_' . $this->plugin)) {
2699 $component .= ('_' . $this->plugin);
2701 $mform->addElement('checkbox', 'enableuserinstances', get_string('enableuserinstances', $component));
2704 // set the data if we have some.
2705 if ($this->instance) {
2706 $data = array();
2707 $option_names = call_user_func(array($classname,'get_type_option_names'));
2708 if (!empty($instanceoptionnames)){
2709 $option_names[] = 'enablecourseinstances';
2710 $option_names[] = 'enableuserinstances';
2713 $instanceoptions = $this->instance->get_options();
2714 foreach ($option_names as $config) {
2715 if (!empty($instanceoptions[$config])) {
2716 $data[$config] = $instanceoptions[$config];
2717 } else {
2718 $data[$config] = '';
2721 // XXX: set plugin name for plugins which doesn't have muliti instances
2722 if (empty($instanceoptionnames)){
2723 $data['pluginname'] = $this->pluginname;
2725 $this->set_data($data);
2728 $this->add_action_buttons(true, get_string('save','repository'));
2732 * Validate moodle form data
2734 * @param array $data moodle form data
2735 * @param array $files
2736 * @return array errors
2738 public function validation($data, $files) {
2739 $errors = array();
2740 $plugin = $this->_customdata['plugin'];
2741 $instance = (isset($this->_customdata['instance'])
2742 && is_subclass_of($this->_customdata['instance'], 'repository'))
2743 ? $this->_customdata['instance'] : null;
2744 if (!$instance) {
2745 $errors = repository::static_function($plugin, 'type_form_validation', $this, $data, $errors);
2746 } else {
2747 $errors = $instance->type_form_validation($this, $data, $errors);
2750 return $errors;
2755 * Generate all options needed by filepicker
2757 * @param array $args including following keys
2758 * context
2759 * accepted_types
2760 * return_types
2762 * @return array the list of repository instances, including meta infomation, containing the following keys
2763 * externallink
2764 * repositories
2765 * accepted_types
2767 function initialise_filepicker($args) {
2768 global $CFG, $USER, $PAGE, $OUTPUT;
2769 static $templatesinitialized = array();
2770 require_once($CFG->libdir . '/licenselib.php');
2772 $return = new stdClass();
2773 $licenses = array();
2774 if (!empty($CFG->licenses)) {
2775 $array = explode(',', $CFG->licenses);
2776 foreach ($array as $license) {
2777 $l = new stdClass();
2778 $l->shortname = $license;
2779 $l->fullname = get_string($license, 'license');
2780 $licenses[] = $l;
2783 if (!empty($CFG->sitedefaultlicense)) {
2784 $return->defaultlicense = $CFG->sitedefaultlicense;
2787 $return->licenses = $licenses;
2789 $return->author = fullname($USER);
2791 if (empty($args->context)) {
2792 $context = $PAGE->context;
2793 } else {
2794 $context = $args->context;
2796 $disable_types = array();
2797 if (!empty($args->disable_types)) {
2798 $disable_types = $args->disable_types;
2801 $user_context = context_user::instance($USER->id);
2803 list($context, $course, $cm) = get_context_info_array($context->id);
2804 $contexts = array($user_context, get_system_context());
2805 if (!empty($course)) {
2806 // adding course context
2807 $contexts[] = context_course::instance($course->id);
2809 $externallink = (int)get_config(null, 'repositoryallowexternallinks');
2810 $repositories = repository::get_instances(array(
2811 'context'=>$contexts,
2812 'currentcontext'=> $context,
2813 'accepted_types'=>$args->accepted_types,
2814 'return_types'=>$args->return_types,
2815 'disable_types'=>$disable_types
2818 $return->repositories = array();
2820 if (empty($externallink)) {
2821 $return->externallink = false;
2822 } else {
2823 $return->externallink = true;
2826 $return->userprefs = array();
2827 $return->userprefs['recentrepository'] = get_user_preferences('filepicker_recentrepository', '');
2828 $return->userprefs['recentlicense'] = get_user_preferences('filepicker_recentlicense', '');
2829 $return->userprefs['recentviewmode'] = get_user_preferences('filepicker_recentviewmode', '');
2831 user_preference_allow_ajax_update('filepicker_recentrepository', PARAM_INT);
2832 user_preference_allow_ajax_update('filepicker_recentlicense', PARAM_SAFEDIR);
2833 user_preference_allow_ajax_update('filepicker_recentviewmode', PARAM_INT);
2836 // provided by form element
2837 $return->accepted_types = file_get_typegroup('extension', $args->accepted_types);
2838 $return->return_types = $args->return_types;
2839 $templates = array();
2840 foreach ($repositories as $repository) {
2841 $meta = $repository->get_meta();
2842 // Please note that the array keys for repositories are used within
2843 // JavaScript a lot, the key NEEDS to be the repository id.
2844 $return->repositories[$repository->id] = $meta;
2845 // Register custom repository template if it has one
2846 if(method_exists($repository, 'get_upload_template') && !array_key_exists('uploadform_' . $meta->type, $templatesinitialized)) {
2847 $templates['uploadform_' . $meta->type] = $repository->get_upload_template();
2848 $templatesinitialized['uploadform_' . $meta->type] = true;
2851 if (!array_key_exists('core', $templatesinitialized)) {
2852 // we need to send each filepicker template to the browser just once
2853 $fprenderer = $PAGE->get_renderer('core', 'files');
2854 $templates = array_merge($templates, $fprenderer->filepicker_js_templates());
2855 $templatesinitialized['core'] = true;
2857 if (sizeof($templates)) {
2858 $PAGE->requires->js_init_call('M.core_filepicker.set_templates', array($templates), true);
2860 return $return;
2864 * Small function to walk an array to attach repository ID
2866 * @param array $value
2867 * @param string $key
2868 * @param int $id
2870 function repository_attach_id(&$value, $key, $id){
2871 $value['repo_id'] = $id;