PageRenderTime 58ms CodeModel.GetById 12ms RepoModel.GetById 0ms app.codeStats 1ms

/repository/lib.php

https://bitbucket.org/synergylearning/campusconnect
PHP | 3317 lines | 1888 code | 286 blank | 1143 comment | 455 complexity | 9eed1caff850c24826e808293ae2d74c MD5 | raw file
Possible License(s): MPL-2.0-no-copyleft-exception, LGPL-3.0, GPL-3.0, LGPL-2.1, Apache-2.0, BSD-3-Clause, AGPL-3.0
  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.
  13. //
  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/>.
  16. /**
  17. * This file contains classes used to manage the repository plugins in Moodle
  18. *
  19. * @since 2.0
  20. * @package core_repository
  21. * @copyright 2009 Dongsheng Cai {@link http://dongsheng.org}
  22. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  23. */
  24. defined('MOODLE_INTERNAL') || die();
  25. require_once($CFG->libdir . '/filelib.php');
  26. require_once($CFG->libdir . '/formslib.php');
  27. define('FILE_EXTERNAL', 1);
  28. define('FILE_INTERNAL', 2);
  29. define('FILE_REFERENCE', 4);
  30. define('RENAME_SUFFIX', '_2');
  31. /**
  32. * This class is used to manage repository plugins
  33. *
  34. * A repository_type is a repository plug-in. It can be Box.net, Flick-r, ...
  35. * A repository type can be edited, sorted and hidden. It is mandatory for an
  36. * administrator to create a repository type in order to be able to create
  37. * some instances of this type.
  38. * Coding note:
  39. * - a repository_type object is mapped to the "repository" database table
  40. * - "typename" attibut maps the "type" database field. It is unique.
  41. * - general "options" for a repository type are saved in the config_plugin table
  42. * - when you delete a repository, all instances are deleted, and general
  43. * options are also deleted from database
  44. * - When you create a type for a plugin that can't have multiple instances, a
  45. * instance is automatically created.
  46. *
  47. * @package core_repository
  48. * @copyright 2009 Jerome Mouneyrac
  49. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  50. */
  51. class repository_type implements cacheable_object {
  52. /**
  53. * Type name (no whitespace) - A type name is unique
  54. * Note: for a user-friendly type name see get_readablename()
  55. * @var String
  56. */
  57. private $_typename;
  58. /**
  59. * Options of this type
  60. * They are general options that any instance of this type would share
  61. * e.g. API key
  62. * These options are saved in config_plugin table
  63. * @var array
  64. */
  65. private $_options;
  66. /**
  67. * Is the repository type visible or hidden
  68. * If false (hidden): no instances can be created, edited, deleted, showned , used...
  69. * @var boolean
  70. */
  71. private $_visible;
  72. /**
  73. * 0 => not ordered, 1 => first position, 2 => second position...
  74. * A not order type would appear in first position (should never happened)
  75. * @var integer
  76. */
  77. private $_sortorder;
  78. /**
  79. * Return if the instance is visible in a context
  80. *
  81. * @todo check if the context visibility has been overwritten by the plugin creator
  82. * (need to create special functions to be overvwritten in repository class)
  83. * @param stdClass $context context
  84. * @return bool
  85. */
  86. public function get_contextvisibility($context) {
  87. global $USER;
  88. if ($context->contextlevel == CONTEXT_COURSE) {
  89. return $this->_options['enablecourseinstances'];
  90. }
  91. if ($context->contextlevel == CONTEXT_USER) {
  92. return $this->_options['enableuserinstances'];
  93. }
  94. //the context is SITE
  95. return true;
  96. }
  97. /**
  98. * repository_type constructor
  99. *
  100. * @param int $typename
  101. * @param array $typeoptions
  102. * @param bool $visible
  103. * @param int $sortorder (don't really need set, it will be during create() call)
  104. */
  105. public function __construct($typename = '', $typeoptions = array(), $visible = true, $sortorder = 0) {
  106. global $CFG;
  107. //set type attributs
  108. $this->_typename = $typename;
  109. $this->_visible = $visible;
  110. $this->_sortorder = $sortorder;
  111. //set options attribut
  112. $this->_options = array();
  113. $options = repository::static_function($typename, 'get_type_option_names');
  114. //check that the type can be setup
  115. if (!empty($options)) {
  116. //set the type options
  117. foreach ($options as $config) {
  118. if (array_key_exists($config, $typeoptions)) {
  119. $this->_options[$config] = $typeoptions[$config];
  120. }
  121. }
  122. }
  123. //retrieve visibility from option
  124. if (array_key_exists('enablecourseinstances',$typeoptions)) {
  125. $this->_options['enablecourseinstances'] = $typeoptions['enablecourseinstances'];
  126. } else {
  127. $this->_options['enablecourseinstances'] = 0;
  128. }
  129. if (array_key_exists('enableuserinstances',$typeoptions)) {
  130. $this->_options['enableuserinstances'] = $typeoptions['enableuserinstances'];
  131. } else {
  132. $this->_options['enableuserinstances'] = 0;
  133. }
  134. }
  135. /**
  136. * Get the type name (no whitespace)
  137. * For a human readable name, use get_readablename()
  138. *
  139. * @return string the type name
  140. */
  141. public function get_typename() {
  142. return $this->_typename;
  143. }
  144. /**
  145. * Return a human readable and user-friendly type name
  146. *
  147. * @return string user-friendly type name
  148. */
  149. public function get_readablename() {
  150. return get_string('pluginname','repository_'.$this->_typename);
  151. }
  152. /**
  153. * Return general options
  154. *
  155. * @return array the general options
  156. */
  157. public function get_options() {
  158. return $this->_options;
  159. }
  160. /**
  161. * Return visibility
  162. *
  163. * @return bool
  164. */
  165. public function get_visible() {
  166. return $this->_visible;
  167. }
  168. /**
  169. * Return order / position of display in the file picker
  170. *
  171. * @return int
  172. */
  173. public function get_sortorder() {
  174. return $this->_sortorder;
  175. }
  176. /**
  177. * Create a repository type (the type name must not already exist)
  178. * @param bool $silent throw exception?
  179. * @return mixed return int if create successfully, return false if
  180. */
  181. public function create($silent = false) {
  182. global $DB;
  183. //check that $type has been set
  184. $timmedtype = trim($this->_typename);
  185. if (empty($timmedtype)) {
  186. throw new repository_exception('emptytype', 'repository');
  187. }
  188. //set sortorder as the last position in the list
  189. if (!isset($this->_sortorder) || $this->_sortorder == 0 ) {
  190. $sql = "SELECT MAX(sortorder) FROM {repository}";
  191. $this->_sortorder = 1 + $DB->get_field_sql($sql);
  192. }
  193. //only create a new type if it doesn't already exist
  194. $existingtype = $DB->get_record('repository', array('type'=>$this->_typename));
  195. if (!$existingtype) {
  196. //create the type
  197. $newtype = new stdClass();
  198. $newtype->type = $this->_typename;
  199. $newtype->visible = $this->_visible;
  200. $newtype->sortorder = $this->_sortorder;
  201. $plugin_id = $DB->insert_record('repository', $newtype);
  202. //save the options in DB
  203. $this->update_options();
  204. $instanceoptionnames = repository::static_function($this->_typename, 'get_instance_option_names');
  205. //if the plugin type has no multiple instance (e.g. has no instance option name) so it wont
  206. //be possible for the administrator to create a instance
  207. //in this case we need to create an instance
  208. if (empty($instanceoptionnames)) {
  209. $instanceoptions = array();
  210. if (empty($this->_options['pluginname'])) {
  211. // when moodle trying to install some repo plugin automatically
  212. // this option will be empty, get it from language string when display
  213. $instanceoptions['name'] = '';
  214. } else {
  215. // when admin trying to add a plugin manually, he will type a name
  216. // for it
  217. $instanceoptions['name'] = $this->_options['pluginname'];
  218. }
  219. repository::static_function($this->_typename, 'create', $this->_typename, 0, context_system::instance(), $instanceoptions);
  220. }
  221. //run plugin_init function
  222. if (!repository::static_function($this->_typename, 'plugin_init')) {
  223. $this->update_visibility(false);
  224. if (!$silent) {
  225. throw new repository_exception('cannotinitplugin', 'repository');
  226. }
  227. }
  228. cache::make('core', 'repositories')->purge();
  229. if(!empty($plugin_id)) {
  230. // return plugin_id if create successfully
  231. return $plugin_id;
  232. } else {
  233. return false;
  234. }
  235. } else {
  236. if (!$silent) {
  237. throw new repository_exception('existingrepository', 'repository');
  238. }
  239. // If plugin existed, return false, tell caller no new plugins were created.
  240. return false;
  241. }
  242. }
  243. /**
  244. * Update plugin options into the config_plugin table
  245. *
  246. * @param array $options
  247. * @return bool
  248. */
  249. public function update_options($options = null) {
  250. global $DB;
  251. $classname = 'repository_' . $this->_typename;
  252. $instanceoptions = repository::static_function($this->_typename, 'get_instance_option_names');
  253. if (empty($instanceoptions)) {
  254. // update repository instance name if this plugin type doesn't have muliti instances
  255. $params = array();
  256. $params['type'] = $this->_typename;
  257. $instances = repository::get_instances($params);
  258. $instance = array_pop($instances);
  259. if ($instance) {
  260. $DB->set_field('repository_instances', 'name', $options['pluginname'], array('id'=>$instance->id));
  261. }
  262. unset($options['pluginname']);
  263. }
  264. if (!empty($options)) {
  265. $this->_options = $options;
  266. }
  267. foreach ($this->_options as $name => $value) {
  268. set_config($name, $value, $this->_typename);
  269. }
  270. cache::make('core', 'repositories')->purge();
  271. return true;
  272. }
  273. /**
  274. * Update visible database field with the value given as parameter
  275. * or with the visible value of this object
  276. * This function is private.
  277. * For public access, have a look to switch_and_update_visibility()
  278. *
  279. * @param bool $visible
  280. * @return bool
  281. */
  282. private function update_visible($visible = null) {
  283. global $DB;
  284. if (!empty($visible)) {
  285. $this->_visible = $visible;
  286. }
  287. else if (!isset($this->_visible)) {
  288. throw new repository_exception('updateemptyvisible', 'repository');
  289. }
  290. cache::make('core', 'repositories')->purge();
  291. return $DB->set_field('repository', 'visible', $this->_visible, array('type'=>$this->_typename));
  292. }
  293. /**
  294. * Update database sortorder field with the value given as parameter
  295. * or with the sortorder value of this object
  296. * This function is private.
  297. * For public access, have a look to move_order()
  298. *
  299. * @param int $sortorder
  300. * @return bool
  301. */
  302. private function update_sortorder($sortorder = null) {
  303. global $DB;
  304. if (!empty($sortorder) && $sortorder!=0) {
  305. $this->_sortorder = $sortorder;
  306. }
  307. //if sortorder is not set, we set it as the ;ast position in the list
  308. else if (!isset($this->_sortorder) || $this->_sortorder == 0 ) {
  309. $sql = "SELECT MAX(sortorder) FROM {repository}";
  310. $this->_sortorder = 1 + $DB->get_field_sql($sql);
  311. }
  312. cache::make('core', 'repositories')->purge();
  313. return $DB->set_field('repository', 'sortorder', $this->_sortorder, array('type'=>$this->_typename));
  314. }
  315. /**
  316. * Change order of the type with its adjacent upper or downer type
  317. * (database fields are updated)
  318. * Algorithm details:
  319. * 1. retrieve all types in an array. This array is sorted by sortorder,
  320. * and the array keys start from 0 to X (incremented by 1)
  321. * 2. switch sortorder values of this type and its adjacent type
  322. *
  323. * @param string $move "up" or "down"
  324. */
  325. public function move_order($move) {
  326. global $DB;
  327. $types = repository::get_types(); // retrieve all types
  328. // retrieve this type into the returned array
  329. $i = 0;
  330. while (!isset($indice) && $i<count($types)) {
  331. if ($types[$i]->get_typename() == $this->_typename) {
  332. $indice = $i;
  333. }
  334. $i++;
  335. }
  336. // retrieve adjacent indice
  337. switch ($move) {
  338. case "up":
  339. $adjacentindice = $indice - 1;
  340. break;
  341. case "down":
  342. $adjacentindice = $indice + 1;
  343. break;
  344. default:
  345. throw new repository_exception('movenotdefined', 'repository');
  346. }
  347. //switch sortorder of this type and the adjacent type
  348. //TODO: we could reset sortorder for all types. This is not as good in performance term, but
  349. //that prevent from wrong behaviour on a screwed database. As performance are not important in this particular case
  350. //it worth to change the algo.
  351. if ($adjacentindice>=0 && !empty($types[$adjacentindice])) {
  352. $DB->set_field('repository', 'sortorder', $this->_sortorder, array('type'=>$types[$adjacentindice]->get_typename()));
  353. $this->update_sortorder($types[$adjacentindice]->get_sortorder());
  354. }
  355. }
  356. /**
  357. * 1. Change visibility to the value chosen
  358. * 2. Update the type
  359. *
  360. * @param bool $visible
  361. * @return bool
  362. */
  363. public function update_visibility($visible = null) {
  364. if (is_bool($visible)) {
  365. $this->_visible = $visible;
  366. } else {
  367. $this->_visible = !$this->_visible;
  368. }
  369. return $this->update_visible();
  370. }
  371. /**
  372. * Delete a repository_type (general options are removed from config_plugin
  373. * table, and all instances are deleted)
  374. *
  375. * @param bool $downloadcontents download external contents if exist
  376. * @return bool
  377. */
  378. public function delete($downloadcontents = false) {
  379. global $DB;
  380. //delete all instances of this type
  381. $params = array();
  382. $params['context'] = array();
  383. $params['onlyvisible'] = false;
  384. $params['type'] = $this->_typename;
  385. $instances = repository::get_instances($params);
  386. foreach ($instances as $instance) {
  387. $instance->delete($downloadcontents);
  388. }
  389. //delete all general options
  390. foreach ($this->_options as $name => $value) {
  391. set_config($name, null, $this->_typename);
  392. }
  393. cache::make('core', 'repositories')->purge();
  394. try {
  395. $DB->delete_records('repository', array('type' => $this->_typename));
  396. } catch (dml_exception $ex) {
  397. return false;
  398. }
  399. return true;
  400. }
  401. /**
  402. * Prepares the repository type to be cached. Implements method from cacheable_object interface.
  403. *
  404. * @return array
  405. */
  406. public function prepare_to_cache() {
  407. return array(
  408. 'typename' => $this->_typename,
  409. 'typeoptions' => $this->_options,
  410. 'visible' => $this->_visible,
  411. 'sortorder' => $this->_sortorder
  412. );
  413. }
  414. /**
  415. * Restores repository type from cache. Implements method from cacheable_object interface.
  416. *
  417. * @return array
  418. */
  419. public static function wake_from_cache($data) {
  420. return new repository_type($data['typename'], $data['typeoptions'], $data['visible'], $data['sortorder']);
  421. }
  422. }
  423. /**
  424. * This is the base class of the repository class.
  425. *
  426. * To create repository plugin, see: {@link http://docs.moodle.org/dev/Repository_plugins}
  427. * See an example: {@link repository_boxnet}
  428. *
  429. * @package core_repository
  430. * @copyright 2009 Dongsheng Cai {@link http://dongsheng.org}
  431. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  432. */
  433. abstract class repository implements cacheable_object {
  434. /** Timeout in seconds for downloading the external file into moodle */
  435. const GETFILE_TIMEOUT = 30;
  436. /** Timeout in seconds for syncronising the external file size */
  437. const SYNCFILE_TIMEOUT = 1;
  438. /** Timeout in seconds for downloading an image file from external repository during syncronisation */
  439. const SYNCIMAGE_TIMEOUT = 3;
  440. // $disabled can be set to true to disable a plugin by force
  441. // example: self::$disabled = true
  442. /** @var bool force disable repository instance */
  443. public $disabled = false;
  444. /** @var int repository instance id */
  445. public $id;
  446. /** @var stdClass current context */
  447. public $context;
  448. /** @var array repository options */
  449. public $options;
  450. /** @var bool Whether or not the repository instance is editable */
  451. public $readonly;
  452. /** @var int return types */
  453. public $returntypes;
  454. /** @var stdClass repository instance database record */
  455. public $instance;
  456. /** @var string Type of repository (webdav, google_docs, dropbox, ...). Read from $this->get_typename(). */
  457. protected $typename;
  458. /**
  459. * Constructor
  460. *
  461. * @param int $repositoryid repository instance id
  462. * @param int|stdClass $context a context id or context object
  463. * @param array $options repository options
  464. * @param int $readonly indicate this repo is readonly or not
  465. */
  466. public function __construct($repositoryid, $context = SYSCONTEXTID, $options = array(), $readonly = 0) {
  467. global $DB;
  468. $this->id = $repositoryid;
  469. if (is_object($context)) {
  470. $this->context = $context;
  471. } else {
  472. $this->context = context::instance_by_id($context);
  473. }
  474. $cache = cache::make('core', 'repositories');
  475. if (($this->instance = $cache->get('i:'. $this->id)) === false) {
  476. $this->instance = $DB->get_record_sql("SELECT i.*, r.type AS repositorytype, r.sortorder, r.visible
  477. FROM {repository} r, {repository_instances} i
  478. WHERE i.typeid = r.id and i.id = ?", array('id' => $this->id));
  479. $cache->set('i:'. $this->id, $this->instance);
  480. }
  481. $this->readonly = $readonly;
  482. $this->options = array();
  483. if (is_array($options)) {
  484. // The get_option() method will get stored options in database.
  485. $options = array_merge($this->get_option(), $options);
  486. } else {
  487. $options = $this->get_option();
  488. }
  489. foreach ($options as $n => $v) {
  490. $this->options[$n] = $v;
  491. }
  492. $this->name = $this->get_name();
  493. $this->returntypes = $this->supported_returntypes();
  494. $this->super_called = true;
  495. }
  496. /**
  497. * Magic method for non-existing (usually deprecated) class methods.
  498. *
  499. * @param string $name
  500. * @param array $arguments
  501. * @return mixed
  502. * @throws coding_exception
  503. */
  504. public function __call($name, $arguments) {
  505. if ($name === 'sync_individual_file') {
  506. // Method repository::sync_individual_file() was deprecated in Moodle 2.6.
  507. // See repository::sync_reference().
  508. debugging('Function repository::sync_individual_file() is deprecated.', DEBUG_DEVELOPER);
  509. return true;
  510. } else if ($name === 'get_file_by_reference') {
  511. // Method repository::get_file_by_reference() was deprecated in Moodle 2.6.
  512. // See repository::sync_reference().
  513. debugging('Function repository::get_file_by_reference() is deprecated.', DEBUG_DEVELOPER);
  514. return null;
  515. } else if ($name === 'get_reference_file_lifetime') {
  516. // Method repository::get_file_by_reference() was deprecated in Moodle 2.6.
  517. // See repository::sync_reference().
  518. debugging('Function repository::get_reference_file_lifetime() is deprecated.', DEBUG_DEVELOPER);
  519. return 24 * 60 * 60;
  520. } else {
  521. throw new coding_exception('Tried to call unknown method '.get_class($this).'::'.$name);
  522. }
  523. }
  524. /**
  525. * Get repository instance using repository id
  526. *
  527. * Note that this function does not check permission to access repository contents
  528. *
  529. * @throws repository_exception
  530. *
  531. * @param int $repositoryid repository instance ID
  532. * @param context|int $context context instance or context ID where this repository will be used
  533. * @param array $options additional repository options
  534. * @return repository
  535. */
  536. public static function get_repository_by_id($repositoryid, $context, $options = array()) {
  537. global $CFG, $DB;
  538. $cache = cache::make('core', 'repositories');
  539. if (!is_object($context)) {
  540. $context = context::instance_by_id($context);
  541. }
  542. $cachekey = 'rep:'. $repositoryid. ':'. $context->id. ':'. serialize($options);
  543. if ($repository = $cache->get($cachekey)) {
  544. return $repository;
  545. }
  546. if (!$record = $cache->get('i:'. $repositoryid)) {
  547. $sql = "SELECT i.*, r.type AS repositorytype, r.visible, r.sortorder
  548. FROM {repository_instances} i
  549. JOIN {repository} r ON r.id = i.typeid
  550. WHERE i.id = ?";
  551. if (!$record = $DB->get_record_sql($sql, array($repositoryid))) {
  552. throw new repository_exception('invalidrepositoryid', 'repository');
  553. }
  554. $cache->set('i:'. $record->id, $record);
  555. }
  556. $type = $record->repositorytype;
  557. if (file_exists($CFG->dirroot . "/repository/$type/lib.php")) {
  558. require_once($CFG->dirroot . "/repository/$type/lib.php");
  559. $classname = 'repository_' . $type;
  560. $options['type'] = $type;
  561. $options['typeid'] = $record->typeid;
  562. $options['visible'] = $record->visible;
  563. if (empty($options['name'])) {
  564. $options['name'] = $record->name;
  565. }
  566. $repository = new $classname($repositoryid, $context, $options, $record->readonly);
  567. if (empty($repository->super_called)) {
  568. // to make sure the super construct is called
  569. debugging('parent::__construct must be called by '.$type.' plugin.');
  570. }
  571. $cache->set($cachekey, $repository);
  572. return $repository;
  573. } else {
  574. throw new repository_exception('invalidplugin', 'repository');
  575. }
  576. }
  577. /**
  578. * Returns the type name of the repository.
  579. *
  580. * @return string type name of the repository.
  581. * @since 2.5
  582. */
  583. public function get_typename() {
  584. if (empty($this->typename)) {
  585. $matches = array();
  586. if (!preg_match("/^repository_(.*)$/", get_class($this), $matches)) {
  587. throw new coding_exception('The class name of a repository should be repository_<typeofrepository>, '.
  588. 'e.g. repository_dropbox');
  589. }
  590. $this->typename = $matches[1];
  591. }
  592. return $this->typename;
  593. }
  594. /**
  595. * Get a repository type object by a given type name.
  596. *
  597. * @static
  598. * @param string $typename the repository type name
  599. * @return repository_type|bool
  600. */
  601. public static function get_type_by_typename($typename) {
  602. global $DB;
  603. $cache = cache::make('core', 'repositories');
  604. if (($repositorytype = $cache->get('typename:'. $typename)) === false) {
  605. $repositorytype = null;
  606. if ($record = $DB->get_record('repository', array('type' => $typename))) {
  607. $repositorytype = new repository_type($record->type, (array)get_config($record->type), $record->visible, $record->sortorder);
  608. $cache->set('typeid:'. $record->id, $repositorytype);
  609. }
  610. $cache->set('typename:'. $typename, $repositorytype);
  611. }
  612. return $repositorytype;
  613. }
  614. /**
  615. * Get the repository type by a given repository type id.
  616. *
  617. * @static
  618. * @param int $id the type id
  619. * @return object
  620. */
  621. public static function get_type_by_id($id) {
  622. global $DB;
  623. $cache = cache::make('core', 'repositories');
  624. if (($repositorytype = $cache->get('typeid:'. $id)) === false) {
  625. $repositorytype = null;
  626. if ($record = $DB->get_record('repository', array('id' => $id))) {
  627. $repositorytype = new repository_type($record->type, (array)get_config($record->type), $record->visible, $record->sortorder);
  628. $cache->set('typename:'. $record->type, $repositorytype);
  629. }
  630. $cache->set('typeid:'. $id, $repositorytype);
  631. }
  632. return $repositorytype;
  633. }
  634. /**
  635. * Return all repository types ordered by sortorder field
  636. * first repository type in returnedarray[0], second repository type in returnedarray[1], ...
  637. *
  638. * @static
  639. * @param bool $visible can return types by visiblity, return all types if null
  640. * @return array Repository types
  641. */
  642. public static function get_types($visible=null) {
  643. global $DB, $CFG;
  644. $cache = cache::make('core', 'repositories');
  645. if (!$visible) {
  646. $typesnames = $cache->get('types');
  647. } else {
  648. $typesnames = $cache->get('typesvis');
  649. }
  650. $types = array();
  651. if ($typesnames === false) {
  652. $typesnames = array();
  653. $vistypesnames = array();
  654. if ($records = $DB->get_records('repository', null ,'sortorder')) {
  655. foreach($records as $type) {
  656. if (($repositorytype = $cache->get('typename:'. $type->type)) === false) {
  657. // Create new instance of repository_type.
  658. if (file_exists($CFG->dirroot . '/repository/'. $type->type .'/lib.php')) {
  659. $repositorytype = new repository_type($type->type, (array)get_config($type->type), $type->visible, $type->sortorder);
  660. $cache->set('typeid:'. $type->id, $repositorytype);
  661. $cache->set('typename:'. $type->type, $repositorytype);
  662. }
  663. }
  664. if ($repositorytype) {
  665. if (empty($visible) || $repositorytype->get_visible()) {
  666. $types[] = $repositorytype;
  667. $vistypesnames[] = $repositorytype->get_typename();
  668. }
  669. $typesnames[] = $repositorytype->get_typename();
  670. }
  671. }
  672. }
  673. $cache->set('types', $typesnames);
  674. $cache->set('typesvis', $vistypesnames);
  675. } else {
  676. foreach ($typesnames as $typename) {
  677. $types[] = self::get_type_by_typename($typename);
  678. }
  679. }
  680. return $types;
  681. }
  682. /**
  683. * Checks if user has a capability to view the current repository.
  684. *
  685. * @return bool true when the user can, otherwise throws an exception.
  686. * @throws repository_exception when the user does not meet the requirements.
  687. */
  688. public final function check_capability() {
  689. global $USER;
  690. // The context we are on.
  691. $currentcontext = $this->context;
  692. // Ensure that the user can view the repository in the current context.
  693. $can = has_capability('repository/'.$this->get_typename().':view', $currentcontext);
  694. // Context in which the repository has been created.
  695. $repocontext = context::instance_by_id($this->instance->contextid);
  696. // Prevent access to private repositories when logged in as.
  697. if ($can && \core\session\manager::is_loggedinas()) {
  698. if ($this->contains_private_data() || $repocontext->contextlevel == CONTEXT_USER) {
  699. $can = false;
  700. }
  701. }
  702. // We are going to ensure that the current context was legit, and reliable to check
  703. // the capability against. (No need to do that if we already cannot).
  704. if ($can) {
  705. if ($repocontext->contextlevel == CONTEXT_USER) {
  706. // The repository is a user instance, ensure we're the right user to access it!
  707. if ($repocontext->instanceid != $USER->id) {
  708. $can = false;
  709. }
  710. } else if ($repocontext->contextlevel == CONTEXT_COURSE) {
  711. // The repository is a course one. Let's check that we are on the right course.
  712. if (in_array($currentcontext->contextlevel, array(CONTEXT_COURSE, CONTEXT_MODULE, CONTEXT_BLOCK))) {
  713. $coursecontext = $currentcontext->get_course_context();
  714. if ($coursecontext->instanceid != $repocontext->instanceid) {
  715. $can = false;
  716. }
  717. } else {
  718. // We are on a parent context, therefore it's legit to check the permissions
  719. // in the current context.
  720. }
  721. } else {
  722. // Nothing to check here, system instances can have different permissions on different
  723. // levels. We do not want to prevent URL hack here, because it does not make sense to
  724. // prevent a user to access a repository in a context if it's accessible in another one.
  725. }
  726. }
  727. if ($can) {
  728. return true;
  729. }
  730. throw new repository_exception('nopermissiontoaccess', 'repository');
  731. }
  732. /**
  733. * Check if file already exists in draft area.
  734. *
  735. * @static
  736. * @param int $itemid of the draft area.
  737. * @param string $filepath path to the file.
  738. * @param string $filename file name.
  739. * @return bool
  740. */
  741. public static function draftfile_exists($itemid, $filepath, $filename) {
  742. global $USER;
  743. $fs = get_file_storage();
  744. $usercontext = context_user::instance($USER->id);
  745. return $fs->file_exists($usercontext->id, 'user', 'draft', $itemid, $filepath, $filename);
  746. }
  747. /**
  748. * Parses the moodle file reference and returns an instance of stored_file
  749. *
  750. * @param string $reference reference to the moodle internal file as retruned by
  751. * {@link repository::get_file_reference()} or {@link file_storage::pack_reference()}
  752. * @return stored_file|null
  753. */
  754. public static function get_moodle_file($reference) {
  755. $params = file_storage::unpack_reference($reference, true);
  756. $fs = get_file_storage();
  757. return $fs->get_file($params['contextid'], $params['component'], $params['filearea'],
  758. $params['itemid'], $params['filepath'], $params['filename']);
  759. }
  760. /**
  761. * Repository method to make sure that user can access particular file.
  762. *
  763. * This is checked when user tries to pick the file from repository to deal with
  764. * potential parameter substitutions is request
  765. *
  766. * @param string $source source of the file, returned by repository as 'source' and received back from user (not cleaned)
  767. * @return bool whether the file is accessible by current user
  768. */
  769. public function file_is_accessible($source) {
  770. if ($this->has_moodle_files()) {
  771. $reference = $this->get_file_reference($source);
  772. try {
  773. $params = file_storage::unpack_reference($reference, true);
  774. } catch (file_reference_exception $e) {
  775. return false;
  776. }
  777. $browser = get_file_browser();
  778. $context = context::instance_by_id($params['contextid']);
  779. $file_info = $browser->get_file_info($context, $params['component'], $params['filearea'],
  780. $params['itemid'], $params['filepath'], $params['filename']);
  781. return !empty($file_info);
  782. }
  783. return true;
  784. }
  785. /**
  786. * This function is used to copy a moodle file to draft area.
  787. *
  788. * It DOES NOT check if the user is allowed to access this file because the actual file
  789. * can be located in the area where user does not have access to but there is an alias
  790. * to this file in the area where user CAN access it.
  791. * {@link file_is_accessible} should be called for alias location before calling this function.
  792. *
  793. * @param string $source The metainfo of file, it is base64 encoded php serialized data
  794. * @param stdClass|array $filerecord contains itemid, filepath, filename and optionally other
  795. * attributes of the new file
  796. * @param int $maxbytes maximum allowed size of file, -1 if unlimited. If size of file exceeds
  797. * the limit, the file_exception is thrown.
  798. * @param int $areamaxbytes the maximum size of the area. A file_exception is thrown if the
  799. * new file will reach the limit.
  800. * @return array The information about the created file
  801. */
  802. public function copy_to_area($source, $filerecord, $maxbytes = -1, $areamaxbytes = FILE_AREA_MAX_BYTES_UNLIMITED) {
  803. global $USER;
  804. $fs = get_file_storage();
  805. if ($this->has_moodle_files() == false) {
  806. throw new coding_exception('Only repository used to browse moodle files can use repository::copy_to_area()');
  807. }
  808. $user_context = context_user::instance($USER->id);
  809. $filerecord = (array)$filerecord;
  810. // make sure the new file will be created in user draft area
  811. $filerecord['component'] = 'user';
  812. $filerecord['filearea'] = 'draft';
  813. $filerecord['contextid'] = $user_context->id;
  814. $draftitemid = $filerecord['itemid'];
  815. $new_filepath = $filerecord['filepath'];
  816. $new_filename = $filerecord['filename'];
  817. // the file needs to copied to draft area
  818. $stored_file = self::get_moodle_file($source);
  819. if ($maxbytes != -1 && $stored_file->get_filesize() > $maxbytes) {
  820. throw new file_exception('maxbytes');
  821. }
  822. // Validate the size of the draft area.
  823. if (file_is_draft_area_limit_reached($draftitemid, $areamaxbytes, $stored_file->get_filesize())) {
  824. throw new file_exception('maxareabytes');
  825. }
  826. if (repository::draftfile_exists($draftitemid, $new_filepath, $new_filename)) {
  827. // create new file
  828. $unused_filename = repository::get_unused_filename($draftitemid, $new_filepath, $new_filename);
  829. $filerecord['filename'] = $unused_filename;
  830. $fs->create_file_from_storedfile($filerecord, $stored_file);
  831. $event = array();
  832. $event['event'] = 'fileexists';
  833. $event['newfile'] = new stdClass;
  834. $event['newfile']->filepath = $new_filepath;
  835. $event['newfile']->filename = $unused_filename;
  836. $event['newfile']->url = moodle_url::make_draftfile_url($draftitemid, $new_filepath, $unused_filename)->out();
  837. $event['existingfile'] = new stdClass;
  838. $event['existingfile']->filepath = $new_filepath;
  839. $event['existingfile']->filename = $new_filename;
  840. $event['existingfile']->url = moodle_url::make_draftfile_url($draftitemid, $new_filepath, $new_filename)->out();
  841. return $event;
  842. } else {
  843. $fs->create_file_from_storedfile($filerecord, $stored_file);
  844. $info = array();
  845. $info['itemid'] = $draftitemid;
  846. $info['file'] = $new_filename;
  847. $info['title'] = $new_filename;
  848. $info['contextid'] = $user_context->id;
  849. $info['url'] = moodle_url::make_draftfile_url($draftitemid, $new_filepath, $new_filename)->out();
  850. $info['filesize'] = $stored_file->get_filesize();
  851. return $info;
  852. }
  853. }
  854. /**
  855. * Get an unused filename from the current draft area.
  856. *
  857. * Will check if the file ends with ([0-9]) and increase the number.
  858. *
  859. * @static
  860. * @param int $itemid draft item ID.
  861. * @param string $filepath path to the file.
  862. * @param string $filename name of the file.
  863. * @return string an unused file name.
  864. */
  865. public static function get_unused_filename($itemid, $filepath, $filename) {
  866. global $USER;
  867. $contextid = context_user::instance($USER->id)->id;
  868. $fs = get_file_storage();
  869. return $fs->get_unused_filename($contextid, 'user', 'draft', $itemid, $filepath, $filename);
  870. }
  871. /**
  872. * Append a suffix to filename.
  873. *
  874. * @static
  875. * @param string $filename
  876. * @return string
  877. * @deprecated since 2.5
  878. */
  879. public static function append_suffix($filename) {
  880. debugging('The function repository::append_suffix() has been deprecated. Use repository::get_unused_filename() instead.',
  881. DEBUG_DEVELOPER);
  882. $pathinfo = pathinfo($filename);
  883. if (empty($pathinfo['extension'])) {
  884. return $filename . RENAME_SUFFIX;
  885. } else {
  886. return $pathinfo['filename'] . RENAME_SUFFIX . '.' . $pathinfo['extension'];
  887. }
  888. }
  889. /**
  890. * Return all types that you a user can create/edit and which are also visible
  891. * Note: Mostly used in order to know if at least one editable type can be set
  892. *
  893. * @static
  894. * @param stdClass $context the context for which we want the editable types
  895. * @return array types
  896. */
  897. public static function get_editable_types($context = null) {
  898. if (empty($context)) {
  899. $context = context_system::instance();
  900. }
  901. $types= repository::get_types(true);
  902. $editabletypes = array();
  903. foreach ($types as $type) {
  904. $instanceoptionnames = repository::static_function($type->get_typename(), 'get_instance_option_names');
  905. if (!empty($instanceoptionnames)) {
  906. if ($type->get_contextvisibility($context)) {
  907. $editabletypes[]=$type;
  908. }
  909. }
  910. }
  911. return $editabletypes;
  912. }
  913. /**
  914. * Return repository instances
  915. *
  916. * @static
  917. * @param array $args Array containing the following keys:
  918. * currentcontext : instance of context (default system context)
  919. * context : array of instances of context (default empty array)
  920. * onlyvisible : bool (default true)
  921. * type : string return instances of this type only
  922. * accepted_types : string|array return instances that contain files of those types (*, web_image, .pdf, ...)
  923. * return_types : int combination of FILE_INTERNAL & FILE_EXTERNAL & FILE_REFERENCE.
  924. * 0 means every type. The default is FILE_INTERNAL | FILE_EXTERNAL.
  925. * userid : int if specified, instances belonging to other users will not be returned
  926. *
  927. * @return array repository instances
  928. */
  929. public static function get_instances($args = array()) {
  930. global $DB, $CFG, $USER;
  931. // Fill $args attributes with default values unless specified
  932. if (!isset($args['currentcontext']) || !($args['currentcontext'] instanceof context)) {
  933. $current_context = context_system::instance();
  934. } else {
  935. $current_context = $args['currentcontext'];
  936. }
  937. $args['currentcontext'] = $current_context->id;
  938. $contextids = array();
  939. if (!empty($args['context'])) {
  940. foreach ($args['context'] as $context) {
  941. $contextids[] = $context->id;
  942. }
  943. }
  944. $args['context'] = $contextids;
  945. if (!isset($args['onlyvisible'])) {
  946. $args['onlyvisible'] = true;
  947. }
  948. if (!isset($args['return_types'])) {
  949. $args['return_types'] = FILE_INTERNAL | FILE_EXTERNAL;
  950. }
  951. if (!isset($args['type'])) {
  952. $args['type'] = null;
  953. }
  954. if (empty($args['disable_types']) || !is_array($args['disable_types'])) {
  955. $args['disable_types'] = null;
  956. }
  957. if (empty($args['userid']) || !is_numeric($args['userid'])) {
  958. $args['userid'] = null;
  959. }
  960. if (!isset($args['accepted_types']) || (is_array($args['accepted_types']) && in_array('*', $args['accepted_types']))) {
  961. $args['accepted_types'] = '*';
  962. }
  963. ksort($args);
  964. $cachekey = 'all:'. serialize($args);
  965. // Check if we have cached list of repositories with the same query
  966. $cache = cache::make('core', 'repositories');
  967. if (($cachedrepositories = $cache->get($cachekey)) !== false) {
  968. // convert from cacheable_object_array to array
  969. $repositories = array();
  970. foreach ($cachedrepositories as $repository) {
  971. $repositories[$repository->id] = $repository;
  972. }
  973. return $repositories;
  974. }
  975. // Prepare DB SQL query to retrieve repositories
  976. $params = array();
  977. $sql = "SELECT i.*, r.type AS repositorytype, r.sortorder, r.visible
  978. FROM {repository} r, {repository_instances} i
  979. WHERE i.typeid = r.id ";
  980. if ($args['disable_types']) {
  981. list($types, $p) = $DB->get_in_or_equal($args['disable_types'], SQL_PARAMS_NAMED, 'distype', false);
  982. $sql .= " AND r.type $types";
  983. $params = array_merge($params, $p);
  984. }
  985. if ($args['userid']) {
  986. $sql .= " AND (i.userid = 0 or i.userid = :userid)";
  987. $params['userid'] = $args['userid'];
  988. }
  989. if ($args['context']) {
  990. list($ctxsql, $p2) = $DB->get_in_or_equal($args['context'], SQL_PARAMS_NAMED, 'ctx');
  991. $sql .= " AND i.contextid $ctxsql";
  992. $params = array_merge($params, $p2);
  993. }
  994. if ($args['onlyvisible'] == true) {
  995. $sql .= " AND r.visible = 1";
  996. }
  997. if ($args['type'] !== null) {
  998. $sql .= " AND r.type = :type";
  999. $params['type'] = $args['type'];
  1000. }
  1001. $sql .= " ORDER BY r.sortorder, i.name";
  1002. if (!$records = $DB->get_records_sql($sql, $params)) {
  1003. $records = array();
  1004. }
  1005. $repositories = array();
  1006. // Sortorder should be unique, which is not true if we use $record->sortorder
  1007. // and there are multiple instances of any repository type
  1008. $sortorder = 1;
  1009. foreach ($records as $record) {
  1010. $cache->set('i:'. $record->id, $record);
  1011. if (!file_exists($CFG->dirroot . '/repository/'. $record->repositorytype.'/lib.php')) {
  1012. continue;
  1013. }
  1014. $repository = self::get_repository_by_id($record->id, $current_context);
  1015. $repository->options['sortorder'] = $sortorder++;
  1016. $is_supported = true;
  1017. // check mimetypes
  1018. if ($args['accepted_types'] !== '*' and $repository->supported_filetypes() !== '*') {
  1019. $accepted_ext = file_get_typegroup('extension', $args['accepted_types']);
  1020. $supported_ext = file_get_typegroup('extension', $repository->supported_filetypes());
  1021. $valid_ext = array_intersect($accepted_ext, $supported_ext);
  1022. $is_supported = !empty($valid_ext);
  1023. }
  1024. // Check return values.
  1025. if (!empty($args['return_types']) && !($repository->supported_returntypes() & $args['return_types'])) {
  1026. $is_supported = false;
  1027. }
  1028. if (!$args['onlyvisible'] || ($repository->is_visible() && !$repository->disabled)) {
  1029. // check capability in current context
  1030. $capability = has_capability('repository/'.$record->repositorytype.':view', $current_context);
  1031. if ($record->repositorytype == 'coursefiles') {
  1032. // coursefiles plugin needs managefiles permission
  1033. $capability = $capability && has_capability('moodle/course:managefiles', $current_context);
  1034. }
  1035. if ($is_supported && $capability) {
  1036. $repositories[$repository->id] = $repository;
  1037. }
  1038. }
  1039. }
  1040. $cache->set($cachekey, new cacheable_object_array($repositories));
  1041. return $repositories;
  1042. }
  1043. /**
  1044. * Get single repository instance for administrative actions
  1045. *
  1046. * Do not use this function to access repository contents, because it
  1047. * does not set the current context
  1048. *
  1049. * @see repository::get_repository_by_id()
  1050. *
  1051. * @static
  1052. * @param integer $id repository instance id
  1053. * @return repository
  1054. */
  1055. public static function get_instance($id) {
  1056. return self::get_repository_by_id($id, context_system::instance());
  1057. }
  1058. /**
  1059. * Call a static function. Any additional arguments than plugin and function will be passed through.
  1060. *
  1061. * @static
  1062. * @param string $plugin repository plugin name
  1063. * @param string $function function name
  1064. * @return mixed
  1065. */
  1066. public static function static_function($plugin, $function) {
  1067. global $CFG;
  1068. //check that the plugin exists
  1069. $typedirectory = $CFG->dirroot . '/repository/'. $plugin . '/lib.php';
  1070. if (!file_exists($typedirectory)) {
  1071. //throw new repository_exception('invalidplugin', 'repository');
  1072. return false;
  1073. }
  1074. $args = func_get_args();
  1075. if (count($args) <= 2) {
  1076. $args = array();
  1077. } else {
  1078. array_shift($args);
  1079. array_shift($args);
  1080. }
  1081. require_once($typedirectory);
  1082. return call_user_func_array(array('repository_' . $plugin, $function), $args);
  1083. }
  1084. /**
  1085. * Scan file, throws exception in case of infected file.
  1086. *
  1087. * Please note that the scanning engine must be able to access the file,
  1088. * permissions of the file are not modified here!
  1089. *
  1090. * @static
  1091. * @param string $thefile
  1092. * @param string $filename name of the file
  1093. * @param bool $deleteinfected
  1094. */
  1095. public static function antivir_scan_file($thefile, $filename, $deleteinfected) {
  1096. global $CFG;
  1097. if (!is_readable($thefile)) {
  1098. // this should not happen
  1099. return;
  1100. }
  1101. if (empty($CFG->runclamonupload) or empty($CFG->pathtoclam)) {
  1102. // clam not enabled
  1103. return;
  1104. }
  1105. $CFG->pathtoclam = trim($CFG->pathtoclam);
  1106. if (!file_exists($CFG->pathtoclam) or !is_executable($CFG->pathtoclam)) {
  1107. // misconfigured clam - use the old notification for now
  1108. require("$CFG->libdir/uploadlib.php");
  1109. $notice = get_string('clamlost', 'moodle', $CFG->pathtoclam);
  1110. clam_message_admins($notice);
  1111. return;
  1112. }
  1113. $clamparam = ' --stdout ';
  1114. // If we are dealing with clamdscan, clamd is likely run as a different user
  1115. // that might not have permissions to access your file.
  1116. // To make clamdscan work, we use --fdpass parameter that passes the file
  1117. // descriptor permissions to clamd, which allows it to scan given file
  1118. // irrespective of directory and file permissions.
  1119. if (basename($CFG->pathtoclam) == 'clamdscan') {
  1120. $clamparam .= '--fdpass ';
  1121. }
  1122. // execute test
  1123. $cmd = escapeshellcmd($CFG->pathtoclam).$clamparam.escapeshellarg($thefile);
  1124. exec($cmd, $output, $return);
  1125. if ($return == 0) {
  1126. // perfect, no problem found
  1127. return;
  1128. } else if ($return == 1) {
  1129. // infection found
  1130. if ($deleteinfected) {
  1131. unlink($thefile);
  1132. }
  1133. throw new moodle_exception('virusfounduser', 'moodle', '', array('filename'=>$filename));
  1134. } else {
  1135. //unknown problem
  1136. require("$CFG->libdir/uploadlib.php");
  1137. $notice = get_string('clamfailed', 'moodle', get_clam_error_code($return));
  1138. $notice .= "\n\n". implode("\n", $output);
  1139. clam_message_admins($notice);
  1140. if ($CFG->clamfailureonupload === 'actlikevirus') {
  1141. if ($deleteinfected) {
  1142. unlink($thefile);
  1143. }
  1144. throw new moodle_exception('virusfounduser', 'moodle', '', array('filename'=>$filename));
  1145. } else {
  1146. return;
  1147. }
  1148. }
  1149. }
  1150. /**
  1151. * Repository method to serve the referenced file
  1152. *
  1153. * @see send_stored_file
  1154. *
  1155. * @param stored_file $storedfile the file that contains the reference
  1156. * @param int $lifetime Number of seconds before the file should expire from caches (null means $CFG->filelifetime)
  1157. * @param int $filter 0 (default)=no filtering, 1=all files, 2=html files only
  1158. * @param bool $forcedownload If true (default false), forces download of file rather than view in browser/plugin
  1159. * @param array $options additional options affecting the file serving
  1160. */
  1161. public function send_file($storedfile, $lifetime=null , $filter=0, $forcedownload=false, array $options = null) {
  1162. if ($this->has_moodle_files()) {
  1163. $fs = get_file_storage();
  1164. $params = file_storage::unpack_reference($storedfile->get_reference(), true);
  1165. $srcfile = null;
  1166. if (is_array($params)) {
  1167. $srcfile = $fs->get_file($params['contextid'], $params['component'], $params['filearea'],
  1168. $params['itemid'], $params['filepath'], $params['filename']);
  1169. }
  1170. if (empty($options)) {
  1171. $options = array();
  1172. }
  1173. if (!isset($options['filename'])) {
  1174. $options['filename'] = $storedfile->get_filename();
  1175. }
  1176. if (!$srcfile) {
  1177. send_file_not_found();
  1178. } else {
  1179. send_stored_file($srcfile, $lifetime, $filter, $forcedownload, $options);
  1180. }
  1181. } else {
  1182. throw new coding_exception("Repository plugin must implement send_file() method.");
  1183. }
  1184. }
  1185. /**
  1186. * Return human readable reference information
  1187. *
  1188. * @param string $reference value of DB field files_reference.reference
  1189. * @param int $filestatus status of the file, 0 - ok, 666 - source missing
  1190. * @return string
  1191. */
  1192. public function get_reference_details($reference, $filestatus = 0) {
  1193. if ($this->has_moodle_files()) {
  1194. $fileinfo = null;
  1195. $params = file_storage::unpack_reference($reference, true);
  1196. if (is_array($params)) {
  1197. $context = context::instance_by_id($params['contextid'], IGNORE_MISSING);
  1198. if ($context) {
  1199. $browser = get_file_browser();
  1200. $fileinfo = $browser->get_file_info($context, $params['component'], $params['filearea'], $params['itemid'], $params['filepath'], $params['filename']);
  1201. }
  1202. }
  1203. if (empty($fileinfo)) {
  1204. if ($filestatus == 666) {
  1205. if (is_siteadmin() || ($context && has_capability('moodle/course:managefiles', $context))) {
  1206. return get_string('lostsource', 'repository',
  1207. $params['contextid']. '/'. $params['component']. '/'. $params['filearea']. '/'. $params['itemid']. $params['filepath']. $params['filename']);
  1208. } else {
  1209. return get_string('lostsource', 'repository', '');
  1210. }
  1211. }
  1212. return get_string('undisclosedsource', 'repository');
  1213. } else {
  1214. return $fileinfo->get_readable_fullname();
  1215. }
  1216. }
  1217. return '';
  1218. }
  1219. /**
  1220. * Cache file from external repository by reference
  1221. * {@link repository::get_file_reference()}
  1222. * {@link repository::get_file()}
  1223. * Invoked at MOODLE/repository/repository_ajax.php
  1224. *
  1225. * @param string $reference this reference is generated by
  1226. * repository::get_file_reference()
  1227. * @param stored_file $storedfile created file reference
  1228. */
  1229. public function cache_file_by_reference($reference, $storedfile) {
  1230. }
  1231. /**
  1232. * Return the source information
  1233. *
  1234. * The result of the function is stored in files.source field. It may be analysed
  1235. * when the source file is lost or repository may use it to display human-readable
  1236. * location of reference original.
  1237. *
  1238. * This method is called when file is picked for the first time only. When file
  1239. * (either copy or a reference) is already in moodle and it is being picked
  1240. * again to another file area (also as a copy or as a reference), the value of
  1241. * files.source is copied.
  1242. *
  1243. * @param string $source source of the file, returned by repository as 'source' and received back from user (not cleaned)
  1244. * @return string|null
  1245. */
  1246. public function get_file_source_info($source) {
  1247. if ($this->has_moodle_files()) {
  1248. $reference = $this->get_file_reference($source);
  1249. return $this->get_reference_details($reference, 0);
  1250. }
  1251. return $source;
  1252. }
  1253. /**
  1254. * Move file from download folder to file pool using FILE API
  1255. *
  1256. * @todo MDL-28637
  1257. * @static
  1258. * @param string $thefile file path in download folder
  1259. * @param stdClass $record
  1260. * @return array containing the following keys:
  1261. * icon
  1262. * file
  1263. * id
  1264. * url
  1265. */
  1266. public static function move_to_filepool($thefile, $record) {
  1267. global $DB, $CFG, $USER, $OUTPUT;
  1268. // scan for viruses if possible, throws exception if problem found
  1269. self::antivir_scan_file($thefile, $record->filename, empty($CFG->repository_no_delete)); //TODO: MDL-28637 this repository_no_delete is a bloody hack!
  1270. $fs = get_file_storage();
  1271. // If file name being used.
  1272. if (repository::draftfile_exists($record->itemid, $record->filepath, $record->filename)) {
  1273. $draftitemid = $record->itemid;
  1274. $new_filename = repository::get_unused_filename($draftitemid, $record->filepath, $record->filename);
  1275. $old_filename = $record->filename;
  1276. // Create a tmp file.
  1277. $record->filename = $new_filename;
  1278. $newfile = $fs->create_file_from_pathname($record, $thefile);
  1279. $event = array();
  1280. $event['event'] = 'fileexists';
  1281. $event['newfile'] = new stdClass;
  1282. $event['newfile']->filepath = $record->filepath;
  1283. $event['newfile']->filename = $new_filename;
  1284. $event['newfile']->url = moodle_url::make_draftfile_url($draftitemid, $record->filepath, $new_filename)->out();
  1285. $event['existingfile'] = new stdClass;
  1286. $event['existingfile']->filepath = $record->filepath;
  1287. $event['existingfile']->filename = $old_filename;
  1288. $event['existingfile']->url = moodle_url::make_draftfile_url($draftitemid, $record->filepath, $old_filename)->out();
  1289. return $event;
  1290. }
  1291. if ($file = $fs->create_file_from_pathname($record, $thefile)) {
  1292. if (empty($CFG->repository_no_delete)) {
  1293. $delete = unlink($thefile);
  1294. unset($CFG->repository_no_delete);
  1295. }
  1296. return array(
  1297. 'url'=>moodle_url::make_draftfile_url($file->get_itemid(), $file->get_filepath(), $file->get_filename())->out(),
  1298. 'id'=>$file->get_itemid(),
  1299. 'file'=>$file->get_filename(),
  1300. 'icon' => $OUTPUT->pix_url(file_extension_icon($thefile, 32))->out(),
  1301. );
  1302. } else {
  1303. return null;
  1304. }
  1305. }
  1306. /**
  1307. * Builds a tree of files This function is then called recursively.
  1308. *
  1309. * @static
  1310. * @todo take $search into account, and respect a threshold for dynamic loading
  1311. * @param file_info $fileinfo an object returned by file_browser::get_file_info()
  1312. * @param string $search searched string
  1313. * @param bool $dynamicmode no recursive call is done when in dynamic mode
  1314. * @param array $list the array containing the files under the passed $fileinfo
  1315. * @return int the number of files found
  1316. */
  1317. public static function build_tree($fileinfo, $search, $dynamicmode, &$list) {
  1318. global $CFG, $OUTPUT;
  1319. $filecount = 0;
  1320. $children = $fileinfo->get_children();
  1321. foreach ($children as $child) {
  1322. $filename = $child->get_visible_name();
  1323. $filesize = $child->get_filesize();
  1324. $filesize = $filesize ? display_size($filesize) : '';
  1325. $filedate = $child->get_timemodified();
  1326. $filedate = $filedate ? userdate($filedate) : '';
  1327. $filetype = $child->get_mimetype();
  1328. if ($child->is_directory()) {
  1329. $path = array();
  1330. $level = $child->get_parent();
  1331. while ($level) {
  1332. $params = $level->get_params();
  1333. $path[] = array($params['filepath'], $level->get_visible_name());
  1334. $level = $level->get_parent();
  1335. }
  1336. $tmp = array(
  1337. 'title' => $child->get_visible_name(),
  1338. 'size' => 0,
  1339. 'date' => $filedate,
  1340. 'path' => array_reverse($path),
  1341. 'thumbnail' => $OUTPUT->pix_url(file_folder_icon(90))->out(false)
  1342. );
  1343. //if ($dynamicmode && $child->is_writable()) {
  1344. // $tmp['children'] = array();
  1345. //} else {
  1346. // if folder name matches search, we send back all files contained.
  1347. $_search = $search;
  1348. if ($search && stristr($tmp['title'], $search) !== false) {
  1349. $_search = false;
  1350. }
  1351. $tmp['children'] = array();
  1352. $_filecount = repository::build_tree($child, $_search, $dynamicmode, $tmp['children']);
  1353. if ($search && $_filecount) {
  1354. $tmp['expanded'] = 1;
  1355. }
  1356. //}
  1357. if (!$search || $_filecount || (stristr($tmp['title'], $search) !== false)) {
  1358. $filecount += $_filecount;
  1359. $list[] = $tmp;
  1360. }
  1361. } else { // not a directory
  1362. // skip the file, if we're in search mode and it's not a match
  1363. if ($search && (stristr($filename, $search) === false)) {
  1364. continue;
  1365. }
  1366. $params = $child->get_params();
  1367. $source = serialize(array($params['contextid'], $params['component'], $params['filearea'], $params['itemid'], $params['filepath'], $params['filename']));
  1368. $list[] = array(
  1369. 'title' => $filename,
  1370. 'size' => $filesize,
  1371. 'date' => $filedate,
  1372. //'source' => $child->get_url(),
  1373. 'source' => base64_encode($source),
  1374. 'icon'=>$OUTPUT->pix_url(file_file_icon($child, 24))->out(false),
  1375. 'thumbnail'=>$OUTPUT->pix_url(file_file_icon($child, 90))->out(false),
  1376. );
  1377. $filecount++;
  1378. }
  1379. }
  1380. return $filecount;
  1381. }
  1382. /**
  1383. * Display a repository instance list (with edit/delete/create links)
  1384. *
  1385. * @static
  1386. * @param stdClass $context the context for which we display the instance
  1387. * @param string $typename if set, we display only one type of instance
  1388. */
  1389. public static function display_instances_list($context, $typename = null) {
  1390. global $CFG, $USER, $OUTPUT;
  1391. $output = $OUTPUT->box_start('generalbox');
  1392. //if the context is SYSTEM, so we call it from administration page
  1393. $admin = ($context->id == SYSCONTEXTID) ? true : false;
  1394. if ($admin) {
  1395. $baseurl = new moodle_url('/'.$CFG->admin.'/repositoryinstance.php', array('sesskey'=>sesskey()));
  1396. $output .= $OUTPUT->heading(get_string('siteinstances', 'repository'));
  1397. } else {
  1398. $baseurl = new moodle_url('/repository/manage_instances.php', array('contextid'=>$context->id, 'sesskey'=>sesskey()));
  1399. }
  1400. $namestr = get_string('name');
  1401. $pluginstr = get_string('plugin', 'repository');
  1402. $settingsstr = get_string('settings');
  1403. $deletestr = get_string('delete');
  1404. // Retrieve list of instances. In administration context we want to display all
  1405. // instances of a type, even if this type is not visible. In course/user context we
  1406. // want to display only visible instances, but for every type types. The repository::get_instances()
  1407. // third parameter displays only visible type.
  1408. $params = array();
  1409. $params['context'] = array($context);
  1410. $params['currentcontext'] = $context;
  1411. $params['return_types'] = 0;
  1412. $params['onlyvisible'] = !$admin;
  1413. $params['type'] = $typename;
  1414. $instances = repository::get_instances($params);
  1415. $instancesnumber = count($instances);
  1416. $alreadyplugins = array();
  1417. $table = new html_table();
  1418. $table->head = array($namestr, $pluginstr, $settingsstr, $deletestr);
  1419. $table->align = array('left', 'left', 'center','center');
  1420. $table->data = array();
  1421. $updowncount = 1;
  1422. foreach ($instances as $i) {
  1423. $settings = '';
  1424. $delete = '';
  1425. $type = repository::get_type_by_id($i->options['typeid']);
  1426. if ($type->get_contextvisibility($context)) {
  1427. if (!$i->readonly) {
  1428. $settingurl = new moodle_url($baseurl);
  1429. $settingurl->param('type', $i->options['type']);
  1430. $settingurl->param('edit', $i->id);
  1431. $settings .= html_writer::link($settingurl, $settingsstr);
  1432. $deleteurl = new moodle_url($baseurl);
  1433. $deleteurl->param('delete', $i->id);
  1434. $deleteurl->param('type', $i->options['type']);
  1435. $delete .= html_writer::link($deleteurl, $deletestr);
  1436. }
  1437. }
  1438. $type = repository::get_type_by_id($i->options['typeid']);
  1439. $table->data[] = array(format_string($i->name), $type->get_readablename(), $settings, $delete);
  1440. //display a grey row if the type is defined as not visible
  1441. if (isset($type) && !$type->get_visible()) {
  1442. $table->rowclasses[] = 'dimmed_text';
  1443. } else {
  1444. $table->rowclasses[] = '';
  1445. }
  1446. if (!in_array($i->name, $alreadyplugins)) {
  1447. $alreadyplugins[] = $i->name;
  1448. }
  1449. }
  1450. $output .= html_writer::table($table);
  1451. $instancehtml = '<div>';
  1452. $addable = 0;
  1453. //if no type is set, we can create all type of instance
  1454. if (!$typename) {
  1455. $instancehtml .= '<h3>';
  1456. $instancehtml .= get_string('createrepository', 'repository');
  1457. $instancehtml .= '</h3><ul>';
  1458. $types = repository::get_editable_types($context);
  1459. foreach ($types as $type) {
  1460. if (!empty($type) && $type->get_visible()) {
  1461. // If the user does not have the permission to view the repository, it won't be displayed in
  1462. // the list of instances. Hiding the link to create new instances will prevent the
  1463. // user from creating them without being able to find them afterwards, which looks like a bug.
  1464. if (!has_capability('repository/'.$type->get_typename().':view', $context)) {
  1465. continue;
  1466. }
  1467. $instanceoptionnames = repository::static_function($type->get_typename(), 'get_instance_option_names');
  1468. if (!empty($instanceoptionnames)) {
  1469. $baseurl->param('new', $type->get_typename());
  1470. $instancehtml .= '<li><a href="'.$baseurl->out().'">'.get_string('createxxinstance', 'repository', get_string('pluginname', 'repository_'.$type->get_typename())). '</a></li>';
  1471. $baseurl->remove_params('new');
  1472. $addable++;
  1473. }
  1474. }
  1475. }
  1476. $instancehtml .= '</ul>';
  1477. } else {
  1478. $instanceoptionnames = repository::static_function($typename, 'get_instance_option_names');
  1479. if (!empty($instanceoptionnames)) { //create a unique type of instance
  1480. $addable = 1;
  1481. $baseurl->param('new', $typename);
  1482. $output .= $OUTPUT->single_button($baseurl, get_string('createinstance', 'repository'), 'get');
  1483. $baseurl->remove_params('new');
  1484. }
  1485. }
  1486. if ($addable) {
  1487. $instancehtml .= '</div>';
  1488. $output .= $instancehtml;
  1489. }
  1490. $output .= $OUTPUT->box_end();
  1491. //print the list + creation links
  1492. print($output);
  1493. }
  1494. /**
  1495. * Prepare file reference information
  1496. *
  1497. * @param string $source source of the file, returned by repository as 'source' and received back from user (not cleaned)
  1498. * @return string file reference, ready to be stored
  1499. */
  1500. public function get_file_reference($source) {
  1501. if ($source && $this->has_moodle_files()) {
  1502. $params = @json_decode(base64_decode($source), true);
  1503. if (!$params && !in_array($this->get_typename(), array('recent', 'user', 'local', 'coursefiles'))) {
  1504. // IMPORTANT! Since default format for moodle files was changed in the minor release as a security fix
  1505. // we maintain an old code here in order not to break 3rd party repositories that deal
  1506. // with moodle files. Repositories are strongly encouraged to be upgraded, see MDL-45616.
  1507. // In Moodle 2.8 this fallback will be removed.
  1508. $params = file_storage::unpack_reference($source, true);
  1509. return file_storage::pack_reference($params);
  1510. }
  1511. if (!is_array($params) || empty($params['contextid'])) {
  1512. throw new repository_exception('invalidparams', 'repository');
  1513. }
  1514. $params = array(
  1515. 'component' => empty($params['component']) ? '' : clean_param($params['component'], PARAM_COMPONENT),
  1516. 'filearea' => empty($params['filearea']) ? '' : clean_param($params['filearea'], PARAM_AREA),
  1517. 'itemid' => empty($params['itemid']) ? 0 : clean_param($params['itemid'], PARAM_INT),
  1518. 'filename' => empty($params['filename']) ? null : clean_param($params['filename'], PARAM_FILE),
  1519. 'filepath' => empty($params['filepath']) ? null : clean_param($params['filepath'], PARAM_PATH),
  1520. 'contextid' => clean_param($params['contextid'], PARAM_INT)
  1521. );
  1522. // Check if context exists.
  1523. if (!context::instance_by_id($params['contextid'], IGNORE_MISSING)) {
  1524. throw new repository_exception('invalidparams', 'repository');
  1525. }
  1526. return file_storage::pack_reference($params);
  1527. }
  1528. return $source;
  1529. }
  1530. /**
  1531. * Decide where to save the file, can be overwriten by subclass
  1532. *
  1533. * @param string $filename file name
  1534. * @return file path
  1535. */
  1536. public function prepare_file($filename) {
  1537. global $CFG;
  1538. $dir = make_temp_directory('download/'.get_class($this).'/');
  1539. while (empty($filename) || file_exists($dir.$filename)) {
  1540. $filename = uniqid('', true).'_'.time().'.tmp';
  1541. }
  1542. return $dir.$filename;
  1543. }
  1544. /**
  1545. * Does this repository used to browse moodle files?
  1546. *
  1547. * @return bool
  1548. */
  1549. public function has_moodle_files() {
  1550. return false;
  1551. }
  1552. /**
  1553. * Return file URL, for most plugins, the parameter is the original
  1554. * url, but some plugins use a file id, so we need this function to
  1555. * convert file id to original url.
  1556. *
  1557. * @param string $url the url of file
  1558. * @return string
  1559. */
  1560. public function get_link($url) {
  1561. return $url;
  1562. }
  1563. /**
  1564. * Downloads a file from external repository and saves it in temp dir
  1565. *
  1566. * Function get_file() must be implemented by repositories that support returntypes
  1567. * FILE_INTERNAL or FILE_REFERENCE. It is invoked to pick up the file and copy it
  1568. * to moodle. This function is not called for moodle repositories, the function
  1569. * {@link repository::copy_to_area()} is used instead.
  1570. *
  1571. * This function can be overridden by subclass if the files.reference field contains
  1572. * not just URL or if request should be done differently.
  1573. *
  1574. * @see curl
  1575. * @throws file_exception when error occured
  1576. *
  1577. * @param string $url the content of files.reference field, in this implementaion
  1578. * it is asssumed that it contains the string with URL of the file
  1579. * @param string $filename filename (without path) to save the downloaded file in the
  1580. * temporary directory, if omitted or file already exists the new filename will be generated
  1581. * @return array with elements:
  1582. * path: internal location of the file
  1583. * url: URL to the source (from parameters)
  1584. */
  1585. public function get_file($url, $filename = '') {
  1586. $path = $this->prepare_file($filename);
  1587. $c = new curl;
  1588. $result = $c->download_one($url, null, array('filepath' => $path, 'timeout' => self::GETFILE_TIMEOUT));
  1589. if ($result !== true) {
  1590. throw new moodle_exception('errorwhiledownload', 'repository', '', $result);
  1591. }
  1592. return array('path'=>$path, 'url'=>$url);
  1593. }
  1594. /**
  1595. * Downloads the file from external repository and saves it in moodle filepool.
  1596. * This function is different from {@link repository::sync_reference()} because it has
  1597. * bigger request timeout and always downloads the content.
  1598. *
  1599. * This function is invoked when we try to unlink the file from the source and convert
  1600. * a reference into a true copy.
  1601. *
  1602. * @throws exception when file could not be imported
  1603. *
  1604. * @param stored_file $file
  1605. * @param int $maxbytes throw an exception if file size is bigger than $maxbytes (0 means no limit)
  1606. */
  1607. public function import_external_file_contents(stored_file $file, $maxbytes = 0) {
  1608. if (!$file->is_external_file()) {
  1609. // nothing to import if the file is not a reference
  1610. return;
  1611. } else if ($file->get_repository_id() != $this->id) {
  1612. // error
  1613. debugging('Repository instance id does not match');
  1614. return;
  1615. } else if ($this->has_moodle_files()) {
  1616. // files that are references to local files are already in moodle filepool
  1617. // just validate the size
  1618. if ($maxbytes > 0 && $file->get_filesize() > $maxbytes) {
  1619. throw new file_exception('maxbytes');
  1620. }
  1621. return;
  1622. } else {
  1623. if ($maxbytes > 0 && $file->get_filesize() > $maxbytes) {
  1624. // note that stored_file::get_filesize() also calls synchronisation
  1625. throw new file_exception('maxbytes');
  1626. }
  1627. $fs = get_file_storage();
  1628. $contentexists = $fs->content_exists($file->get_contenthash());
  1629. if ($contentexists && $file->get_filesize() && $file->get_contenthash() === sha1('')) {
  1630. // even when 'file_storage::content_exists()' returns true this may be an empty
  1631. // content for the file that was not actually downloaded
  1632. $contentexists = false;
  1633. }
  1634. if (!$file->get_status() && $contentexists) {
  1635. // we already have the content in moodle filepool and it was synchronised recently.
  1636. // Repositories may overwrite it if they want to force synchronisation anyway!
  1637. return;
  1638. } else {
  1639. // attempt to get a file
  1640. try {
  1641. $fileinfo = $this->get_file($file->get_reference());
  1642. if (isset($fileinfo['path'])) {
  1643. list($contenthash, $filesize, $newfile) = $fs->add_file_to_pool($fileinfo['path']);
  1644. // set this file and other similar aliases synchronised
  1645. $file->set_synchronized($contenthash, $filesize);
  1646. } else {
  1647. throw new moodle_exception('errorwhiledownload', 'repository', '', '');
  1648. }
  1649. } catch (Exception $e) {
  1650. if ($contentexists) {
  1651. // better something than nothing. We have a copy of file. It's sync time
  1652. // has expired but it is still very likely that it is the last version
  1653. } else {
  1654. throw($e);
  1655. }
  1656. }
  1657. }
  1658. }
  1659. }
  1660. /**
  1661. * Return size of a file in bytes.
  1662. *
  1663. * @param string $source encoded and serialized data of file
  1664. * @return int file size in bytes
  1665. */
  1666. public function get_file_size($source) {
  1667. // TODO MDL-33297 remove this function completely?
  1668. $browser = get_file_browser();
  1669. $params = unserialize(base64_decode($source));
  1670. $contextid = clean_param($params['contextid'], PARAM_INT);
  1671. $fileitemid = clean_param($params['itemid'], PARAM_INT);
  1672. $filename = clean_param($params['filename'], PARAM_FILE);
  1673. $filepath = clean_param($params['filepath'], PARAM_PATH);
  1674. $filearea = clean_param($params['filearea'], PARAM_AREA);
  1675. $component = clean_param($params['component'], PARAM_COMPONENT);
  1676. $context = context::instance_by_id($contextid);
  1677. $file_info = $browser->get_file_info($context, $component, $filearea, $fileitemid, $filepath, $filename);
  1678. if (!empty($file_info)) {
  1679. $filesize = $file_info->get_filesize();
  1680. } else {
  1681. $filesize = null;
  1682. }
  1683. return $filesize;
  1684. }
  1685. /**
  1686. * Return is the instance is visible
  1687. * (is the type visible ? is the context enable ?)
  1688. *
  1689. * @return bool
  1690. */
  1691. public function is_visible() {
  1692. $type = repository::get_type_by_id($this->options['typeid']);
  1693. $instanceoptions = repository::static_function($type->get_typename(), 'get_instance_option_names');
  1694. if ($type->get_visible()) {
  1695. //if the instance is unique so it's visible, otherwise check if the instance has a enabled context
  1696. if (empty($instanceoptions) || $type->get_contextvisibility(context::instance_by_id($this->instance->contextid))) {
  1697. return true;
  1698. }
  1699. }
  1700. return false;
  1701. }
  1702. /**
  1703. * Can the instance be edited by the current user?
  1704. *
  1705. * The property $readonly must not be used within this method because
  1706. * it only controls if the options from self::get_instance_option_names()
  1707. * can be edited.
  1708. *
  1709. * @return bool true if the user can edit the instance.
  1710. * @since 2.5
  1711. */
  1712. public final function can_be_edited_by_user() {
  1713. global $USER;
  1714. // We need to be able to explore the repository.
  1715. try {
  1716. $this->check_capability();
  1717. } catch (repository_exception $e) {
  1718. return false;
  1719. }
  1720. $repocontext = context::instance_by_id($this->instance->contextid);
  1721. if ($repocontext->contextlevel == CONTEXT_USER && $repocontext->instanceid != $USER->id) {
  1722. // If the context of this instance is a user context, we need to be this user.
  1723. return false;
  1724. } else if ($repocontext->contextlevel == CONTEXT_MODULE && !has_capability('moodle/course:update', $repocontext)) {
  1725. // We need to have permissions on the course to edit the instance.
  1726. return false;
  1727. } else if ($repocontext->contextlevel == CONTEXT_SYSTEM && !has_capability('moodle/site:config', $repocontext)) {
  1728. // Do not meet the requirements for the context system.
  1729. return false;
  1730. }
  1731. return true;
  1732. }
  1733. /**
  1734. * Return the name of this instance, can be overridden.
  1735. *
  1736. * @return string
  1737. */
  1738. public function get_name() {
  1739. if ($name = $this->instance->name) {
  1740. return $name;
  1741. } else {
  1742. return get_string('pluginname', 'repository_' . $this->get_typename());
  1743. }
  1744. }
  1745. /**
  1746. * Is this repository accessing private data?
  1747. *
  1748. * This function should return true for the repositories which access external private
  1749. * data from a user. This is the case for repositories such as Dropbox, Google Docs or Box.net
  1750. * which authenticate the user and then store the auth token.
  1751. *
  1752. * Of course, many repositories store 'private data', but we only want to set
  1753. * contains_private_data() to repositories which are external to Moodle and shouldn't be accessed
  1754. * to by the users having the capability to 'login as' someone else. For instance, the repository
  1755. * 'Private files' is not considered as private because it's part of Moodle.
  1756. *
  1757. * You should not set contains_private_data() to true on repositories which allow different types
  1758. * of instances as the levels other than 'user' are, by definition, not private. Also
  1759. * the user instances will be protected when they need to.
  1760. *
  1761. * @return boolean True when the repository accesses private external data.
  1762. * @since 2.5
  1763. */
  1764. public function contains_private_data() {
  1765. return true;
  1766. }
  1767. /**
  1768. * What kind of files will be in this repository?
  1769. *
  1770. * @return array return '*' means this repository support any files, otherwise
  1771. * return mimetypes of files, it can be an array
  1772. */
  1773. public function supported_filetypes() {
  1774. // return array('text/plain', 'image/gif');
  1775. return '*';
  1776. }
  1777. /**
  1778. * Tells how the file can be picked from this repository
  1779. *
  1780. * Maximum value is FILE_INTERNAL | FILE_EXTERNAL | FILE_REFERENCE
  1781. *
  1782. * @return int
  1783. */
  1784. public function supported_returntypes() {
  1785. return (FILE_INTERNAL | FILE_EXTERNAL);
  1786. }
  1787. /**
  1788. * Provide repository instance information for Ajax
  1789. *
  1790. * @return stdClass
  1791. */
  1792. final public function get_meta() {
  1793. global $CFG, $OUTPUT;
  1794. $meta = new stdClass();
  1795. $meta->id = $this->id;
  1796. $meta->name = format_string($this->get_name());
  1797. $meta->type = $this->get_typename();
  1798. $meta->icon = $OUTPUT->pix_url('icon', 'repository_'.$meta->type)->out(false);
  1799. $meta->supported_types = file_get_typegroup('extension', $this->supported_filetypes());
  1800. $meta->return_types = $this->supported_returntypes();
  1801. $meta->sortorder = $this->options['sortorder'];
  1802. return $meta;
  1803. }
  1804. /**
  1805. * Create an instance for this plug-in
  1806. *
  1807. * @static
  1808. * @param string $type the type of the repository
  1809. * @param int $userid the user id
  1810. * @param stdClass $context the context
  1811. * @param array $params the options for this instance
  1812. * @param int $readonly whether to create it readonly or not (defaults to not)
  1813. * @return mixed
  1814. */
  1815. public static function create($type, $userid, $context, $params, $readonly=0) {
  1816. global $CFG, $DB;
  1817. $params = (array)$params;
  1818. require_once($CFG->dirroot . '/repository/'. $type . '/lib.php');
  1819. $classname = 'repository_' . $type;
  1820. if ($repo = $DB->get_record('repository', array('type'=>$type))) {
  1821. $record = new stdClass();
  1822. $record->name = $params['name'];
  1823. $record->typeid = $repo->id;
  1824. $record->timecreated = time();
  1825. $record->timemodified = time();
  1826. $record->contextid = $context->id;
  1827. $record->readonly = $readonly;
  1828. $record->userid = $userid;
  1829. $id = $DB->insert_record('repository_instances', $record);
  1830. cache::make('core', 'repositories')->purge();
  1831. $options = array();
  1832. $configs = call_user_func($classname . '::get_instance_option_names');
  1833. if (!empty($configs)) {
  1834. foreach ($configs as $config) {
  1835. if (isset($params[$config])) {
  1836. $options[$config] = $params[$config];
  1837. } else {
  1838. $options[$config] = null;
  1839. }
  1840. }
  1841. }
  1842. if (!empty($id)) {
  1843. unset($options['name']);
  1844. $instance = repository::get_instance($id);
  1845. $instance->set_option($options);
  1846. return $id;
  1847. } else {
  1848. return null;
  1849. }
  1850. } else {
  1851. return null;
  1852. }
  1853. }
  1854. /**
  1855. * delete a repository instance
  1856. *
  1857. * @param bool $downloadcontents
  1858. * @return bool
  1859. */
  1860. final public function delete($downloadcontents = false) {
  1861. global $DB;
  1862. if ($downloadcontents) {
  1863. $this->convert_references_to_local();
  1864. }
  1865. cache::make('core', 'repositories')->purge();
  1866. try {
  1867. $DB->delete_records('repository_instances', array('id'=>$this->id));
  1868. $DB->delete_records('repository_instance_config', array('instanceid'=>$this->id));
  1869. } catch (dml_exception $ex) {
  1870. return false;
  1871. }
  1872. return true;
  1873. }
  1874. /**
  1875. * Delete all the instances associated to a context.
  1876. *
  1877. * This method is intended to be a callback when deleting
  1878. * a course or a user to delete all the instances associated
  1879. * to their context. The usual way to delete a single instance
  1880. * is to use {@link self::delete()}.
  1881. *
  1882. * @param int $contextid context ID.
  1883. * @param boolean $downloadcontents true to convert references to hard copies.
  1884. * @return void
  1885. */
  1886. final public static function delete_all_for_context($contextid, $downloadcontents = true) {
  1887. global $DB;
  1888. $repoids = $DB->get_fieldset_select('repository_instances', 'id', 'contextid = :contextid', array('contextid' => $contextid));
  1889. if ($downloadcontents) {
  1890. foreach ($repoids as $repoid) {
  1891. $repo = repository::get_repository_by_id($repoid, $contextid);
  1892. $repo->convert_references_to_local();
  1893. }
  1894. }
  1895. cache::make('core', 'repositories')->purge();
  1896. $DB->delete_records_list('repository_instances', 'id', $repoids);
  1897. $DB->delete_records_list('repository_instance_config', 'instanceid', $repoids);
  1898. }
  1899. /**
  1900. * Hide/Show a repository
  1901. *
  1902. * @param string $hide
  1903. * @return bool
  1904. */
  1905. final public function hide($hide = 'toggle') {
  1906. global $DB;
  1907. if ($entry = $DB->get_record('repository', array('id'=>$this->id))) {
  1908. if ($hide === 'toggle' ) {
  1909. if (!empty($entry->visible)) {
  1910. $entry->visible = 0;
  1911. } else {
  1912. $entry->visible = 1;
  1913. }
  1914. } else {
  1915. if (!empty($hide)) {
  1916. $entry->visible = 0;
  1917. } else {
  1918. $entry->visible = 1;
  1919. }
  1920. }
  1921. return $DB->update_record('repository', $entry);
  1922. }
  1923. return false;
  1924. }
  1925. /**
  1926. * Save settings for repository instance
  1927. * $repo->set_option(array('api_key'=>'f2188bde132', 'name'=>'dongsheng'));
  1928. *
  1929. * @param array $options settings
  1930. * @return bool
  1931. */
  1932. public function set_option($options = array()) {
  1933. global $DB;
  1934. if (!empty($options['name'])) {
  1935. $r = new stdClass();
  1936. $r->id = $this->id;
  1937. $r->name = $options['name'];
  1938. $DB->update_record('repository_instances', $r);
  1939. unset($options['name']);
  1940. }
  1941. foreach ($options as $name=>$value) {
  1942. if ($id = $DB->get_field('repository_instance_config', 'id', array('name'=>$name, 'instanceid'=>$this->id))) {
  1943. $DB->set_field('repository_instance_config', 'value', $value, array('id'=>$id));
  1944. } else {
  1945. $config = new stdClass();
  1946. $config->instanceid = $this->id;
  1947. $config->name = $name;
  1948. $config->value = $value;
  1949. $DB->insert_record('repository_instance_config', $config);
  1950. }
  1951. }
  1952. cache::make('core', 'repositories')->purge();
  1953. return true;
  1954. }
  1955. /**
  1956. * Get settings for repository instance.
  1957. *
  1958. * @param string $config a specific option to get.
  1959. * @return mixed returns an array of options. If $config is not empty, then it returns that option,
  1960. * or null if the option does not exist.
  1961. */
  1962. public function get_option($config = '') {
  1963. global $DB;
  1964. $cache = cache::make('core', 'repositories');
  1965. if (($entries = $cache->get('ops:'. $this->id)) === false) {
  1966. $entries = $DB->get_records('repository_instance_config', array('instanceid' => $this->id));
  1967. $cache->set('ops:'. $this->id, $entries);
  1968. }
  1969. $ret = array();
  1970. foreach($entries as $entry) {
  1971. $ret[$entry->name] = $entry->value;
  1972. }
  1973. if (!empty($config)) {
  1974. if (isset($ret[$config])) {
  1975. return $ret[$config];
  1976. } else {
  1977. return null;
  1978. }
  1979. } else {
  1980. return $ret;
  1981. }
  1982. }
  1983. /**
  1984. * Filter file listing to display specific types
  1985. *
  1986. * @param array $value
  1987. * @return bool
  1988. */
  1989. public function filter(&$value) {
  1990. $accepted_types = optional_param_array('accepted_types', '', PARAM_RAW);
  1991. if (isset($value['children'])) {
  1992. if (!empty($value['children'])) {
  1993. $value['children'] = array_filter($value['children'], array($this, 'filter'));
  1994. }
  1995. return true; // always return directories
  1996. } else {
  1997. if ($accepted_types == '*' or empty($accepted_types)
  1998. or (is_array($accepted_types) and in_array('*', $accepted_types))) {
  1999. return true;
  2000. } else {
  2001. foreach ($accepted_types as $ext) {
  2002. if (preg_match('#'.$ext.'$#i', $value['title'])) {
  2003. return true;
  2004. }
  2005. }
  2006. }
  2007. }
  2008. return false;
  2009. }
  2010. /**
  2011. * Given a path, and perhaps a search, get a list of files.
  2012. *
  2013. * See details on {@link http://docs.moodle.org/dev/Repository_plugins}
  2014. *
  2015. * @param string $path this parameter can a folder name, or a identification of folder
  2016. * @param string $page the page number of file list
  2017. * @return array the list of files, including meta infomation, containing the following keys
  2018. * manage, url to manage url
  2019. * client_id
  2020. * login, login form
  2021. * repo_id, active repository id
  2022. * login_btn_action, the login button action
  2023. * login_btn_label, the login button label
  2024. * total, number of results
  2025. * perpage, items per page
  2026. * page
  2027. * pages, total pages
  2028. * issearchresult, is it a search result?
  2029. * list, file list
  2030. * path, current path and parent path
  2031. */
  2032. public function get_listing($path = '', $page = '') {
  2033. }
  2034. /**
  2035. * Prepare the breadcrumb.
  2036. *
  2037. * @param array $breadcrumb contains each element of the breadcrumb.
  2038. * @return array of breadcrumb elements.
  2039. * @since 2.3.3
  2040. */
  2041. protected static function prepare_breadcrumb($breadcrumb) {
  2042. global $OUTPUT;
  2043. $foldericon = $OUTPUT->pix_url(file_folder_icon(24))->out(false);
  2044. $len = count($breadcrumb);
  2045. for ($i = 0; $i < $len; $i++) {
  2046. if (is_array($breadcrumb[$i]) && !isset($breadcrumb[$i]['icon'])) {
  2047. $breadcrumb[$i]['icon'] = $foldericon;
  2048. } else if (is_object($breadcrumb[$i]) && !isset($breadcrumb[$i]->icon)) {
  2049. $breadcrumb[$i]->icon = $foldericon;
  2050. }
  2051. }
  2052. return $breadcrumb;
  2053. }
  2054. /**
  2055. * Prepare the file/folder listing.
  2056. *
  2057. * @param array $list of files and folders.
  2058. * @return array of files and folders.
  2059. * @since 2.3.3
  2060. */
  2061. protected static function prepare_list($list) {
  2062. global $OUTPUT;
  2063. $foldericon = $OUTPUT->pix_url(file_folder_icon(24))->out(false);
  2064. // Reset the array keys because non-numeric keys will create an object when converted to JSON.
  2065. $list = array_values($list);
  2066. $len = count($list);
  2067. for ($i = 0; $i < $len; $i++) {
  2068. if (is_object($list[$i])) {
  2069. $file = (array)$list[$i];
  2070. $converttoobject = true;
  2071. } else {
  2072. $file =& $list[$i];
  2073. $converttoobject = false;
  2074. }
  2075. if (isset($file['size'])) {
  2076. $file['size'] = (int)$file['size'];
  2077. $file['size_f'] = display_size($file['size']);
  2078. }
  2079. if (isset($file['license']) && get_string_manager()->string_exists($file['license'], 'license')) {
  2080. $file['license_f'] = get_string($file['license'], 'license');
  2081. }
  2082. if (isset($file['image_width']) && isset($file['image_height'])) {
  2083. $a = array('width' => $file['image_width'], 'height' => $file['image_height']);
  2084. $file['dimensions'] = get_string('imagesize', 'repository', (object)$a);
  2085. }
  2086. foreach (array('date', 'datemodified', 'datecreated') as $key) {
  2087. if (!isset($file[$key]) && isset($file['date'])) {
  2088. $file[$key] = $file['date'];
  2089. }
  2090. if (isset($file[$key])) {
  2091. // must be UNIX timestamp
  2092. $file[$key] = (int)$file[$key];
  2093. if (!$file[$key]) {
  2094. unset($file[$key]);
  2095. } else {
  2096. $file[$key.'_f'] = userdate($file[$key], get_string('strftimedatetime', 'langconfig'));
  2097. $file[$key.'_f_s'] = userdate($file[$key], get_string('strftimedatetimeshort', 'langconfig'));
  2098. }
  2099. }
  2100. }
  2101. $isfolder = (array_key_exists('children', $file) || (isset($file['type']) && $file['type'] == 'folder'));
  2102. $filename = null;
  2103. if (isset($file['title'])) {
  2104. $filename = $file['title'];
  2105. }
  2106. else if (isset($file['fullname'])) {
  2107. $filename = $file['fullname'];
  2108. }
  2109. if (!isset($file['mimetype']) && !$isfolder && $filename) {
  2110. $file['mimetype'] = get_mimetype_description(array('filename' => $filename));
  2111. }
  2112. if (!isset($file['icon'])) {
  2113. if ($isfolder) {
  2114. $file['icon'] = $foldericon;
  2115. } else if ($filename) {
  2116. $file['icon'] = $OUTPUT->pix_url(file_extension_icon($filename, 24))->out(false);
  2117. }
  2118. }
  2119. // Recursively loop over children.
  2120. if (isset($file['children'])) {
  2121. $file['children'] = self::prepare_list($file['children']);
  2122. }
  2123. // Convert the array back to an object.
  2124. if ($converttoobject) {
  2125. $list[$i] = (object)$file;
  2126. }
  2127. }
  2128. return $list;
  2129. }
  2130. /**
  2131. * Prepares list of files before passing it to AJAX, makes sure data is in the correct
  2132. * format and stores formatted values.
  2133. *
  2134. * @param array|stdClass $listing result of get_listing() or search() or file_get_drafarea_files()
  2135. * @return array
  2136. */
  2137. public static function prepare_listing($listing) {
  2138. $wasobject = false;
  2139. if (is_object($listing)) {
  2140. $listing = (array) $listing;
  2141. $wasobject = true;
  2142. }
  2143. // Prepare the breadcrumb, passed as 'path'.
  2144. if (isset($listing['path']) && is_array($listing['path'])) {
  2145. $listing['path'] = self::prepare_breadcrumb($listing['path']);
  2146. }
  2147. // Prepare the listing of objects.
  2148. if (isset($listing['list']) && is_array($listing['list'])) {
  2149. $listing['list'] = self::prepare_list($listing['list']);
  2150. }
  2151. // Convert back to an object.
  2152. if ($wasobject) {
  2153. $listing = (object) $listing;
  2154. }
  2155. return $listing;
  2156. }
  2157. /**
  2158. * Search files in repository
  2159. * When doing global search, $search_text will be used as
  2160. * keyword.
  2161. *
  2162. * @param string $search_text search key word
  2163. * @param int $page page
  2164. * @return mixed see {@link repository::get_listing()}
  2165. */
  2166. public function search($search_text, $page = 0) {
  2167. $list = array();
  2168. $list['list'] = array();
  2169. return false;
  2170. }
  2171. /**
  2172. * Logout from repository instance
  2173. * By default, this function will return a login form
  2174. *
  2175. * @return string
  2176. */
  2177. public function logout(){
  2178. return $this->print_login();
  2179. }
  2180. /**
  2181. * To check whether the user is logged in.
  2182. *
  2183. * @return bool
  2184. */
  2185. public function check_login(){
  2186. return true;
  2187. }
  2188. /**
  2189. * Show the login screen, if required
  2190. *
  2191. * @return string
  2192. */
  2193. public function print_login(){
  2194. return $this->get_listing();
  2195. }
  2196. /**
  2197. * Show the search screen, if required
  2198. *
  2199. * @return string
  2200. */
  2201. public function print_search() {
  2202. global $PAGE;
  2203. $renderer = $PAGE->get_renderer('core', 'files');
  2204. return $renderer->repository_default_searchform();
  2205. }
  2206. /**
  2207. * For oauth like external authentication, when external repository direct user back to moodle,
  2208. * this function will be called to set up token and token_secret
  2209. */
  2210. public function callback() {
  2211. }
  2212. /**
  2213. * is it possible to do glboal search?
  2214. *
  2215. * @return bool
  2216. */
  2217. public function global_search() {
  2218. return false;
  2219. }
  2220. /**
  2221. * Defines operations that happen occasionally on cron
  2222. *
  2223. * @return bool
  2224. */
  2225. public function cron() {
  2226. return true;
  2227. }
  2228. /**
  2229. * function which is run when the type is created (moodle administrator add the plugin)
  2230. *
  2231. * @return bool success or fail?
  2232. */
  2233. public static function plugin_init() {
  2234. return true;
  2235. }
  2236. /**
  2237. * Edit/Create Admin Settings Moodle form
  2238. *
  2239. * @param moodleform $mform Moodle form (passed by reference)
  2240. * @param string $classname repository class name
  2241. */
  2242. public static function type_config_form($mform, $classname = 'repository') {
  2243. $instnaceoptions = call_user_func(array($classname, 'get_instance_option_names'), $mform, $classname);
  2244. if (empty($instnaceoptions)) {
  2245. // this plugin has only one instance
  2246. // so we need to give it a name
  2247. // it can be empty, then moodle will look for instance name from language string
  2248. $mform->addElement('text', 'pluginname', get_string('pluginname', 'repository'), array('size' => '40'));
  2249. $mform->addElement('static', 'pluginnamehelp', '', get_string('pluginnamehelp', 'repository'));
  2250. $mform->setType('pluginname', PARAM_TEXT);
  2251. }
  2252. }
  2253. /**
  2254. * Validate Admin Settings Moodle form
  2255. *
  2256. * @static
  2257. * @param moodleform $mform Moodle form (passed by reference)
  2258. * @param array $data array of ("fieldname"=>value) of submitted data
  2259. * @param array $errors array of ("fieldname"=>errormessage) of errors
  2260. * @return array array of errors
  2261. */
  2262. public static function type_form_validation($mform, $data, $errors) {
  2263. return $errors;
  2264. }
  2265. /**
  2266. * Edit/Create Instance Settings Moodle form
  2267. *
  2268. * @param moodleform $mform Moodle form (passed by reference)
  2269. */
  2270. public static function instance_config_form($mform) {
  2271. }
  2272. /**
  2273. * Return names of the general options.
  2274. * By default: no general option name
  2275. *
  2276. * @return array
  2277. */
  2278. public static function get_type_option_names() {
  2279. return array('pluginname');
  2280. }
  2281. /**
  2282. * Return names of the instance options.
  2283. * By default: no instance option name
  2284. *
  2285. * @return array
  2286. */
  2287. public static function get_instance_option_names() {
  2288. return array();
  2289. }
  2290. /**
  2291. * Validate repository plugin instance form
  2292. *
  2293. * @param moodleform $mform moodle form
  2294. * @param array $data form data
  2295. * @param array $errors errors
  2296. * @return array errors
  2297. */
  2298. public static function instance_form_validation($mform, $data, $errors) {
  2299. return $errors;
  2300. }
  2301. /**
  2302. * Create a shorten filename
  2303. *
  2304. * @param string $str filename
  2305. * @param int $maxlength max file name length
  2306. * @return string short filename
  2307. */
  2308. public function get_short_filename($str, $maxlength) {
  2309. if (core_text::strlen($str) >= $maxlength) {
  2310. return trim(core_text::substr($str, 0, $maxlength)).'...';
  2311. } else {
  2312. return $str;
  2313. }
  2314. }
  2315. /**
  2316. * Overwrite an existing file
  2317. *
  2318. * @param int $itemid
  2319. * @param string $filepath
  2320. * @param string $filename
  2321. * @param string $newfilepath
  2322. * @param string $newfilename
  2323. * @return bool
  2324. */
  2325. public static function overwrite_existing_draftfile($itemid, $filepath, $filename, $newfilepath, $newfilename) {
  2326. global $USER;
  2327. $fs = get_file_storage();
  2328. $user_context = context_user::instance($USER->id);
  2329. if ($file = $fs->get_file($user_context->id, 'user', 'draft', $itemid, $filepath, $filename)) {
  2330. if ($tempfile = $fs->get_file($user_context->id, 'user', 'draft', $itemid, $newfilepath, $newfilename)) {
  2331. // Remember original file source field.
  2332. $source = @unserialize($file->get_source());
  2333. // Remember the original sortorder.
  2334. $sortorder = $file->get_sortorder();
  2335. if ($tempfile->is_external_file()) {
  2336. // New file is a reference. Check that existing file does not have any other files referencing to it
  2337. if (isset($source->original) && $fs->search_references_count($source->original)) {
  2338. return (object)array('error' => get_string('errordoublereference', 'repository'));
  2339. }
  2340. }
  2341. // delete existing file to release filename
  2342. $file->delete();
  2343. // create new file
  2344. $newfile = $fs->create_file_from_storedfile(array('filepath'=>$filepath, 'filename'=>$filename), $tempfile);
  2345. // Preserve original file location (stored in source field) for handling references
  2346. if (isset($source->original)) {
  2347. if (!($newfilesource = @unserialize($newfile->get_source()))) {
  2348. $newfilesource = new stdClass();
  2349. }
  2350. $newfilesource->original = $source->original;
  2351. $newfile->set_source(serialize($newfilesource));
  2352. }
  2353. $newfile->set_sortorder($sortorder);
  2354. // remove temp file
  2355. $tempfile->delete();
  2356. return true;
  2357. }
  2358. }
  2359. return false;
  2360. }
  2361. /**
  2362. * Updates a file in draft filearea.
  2363. *
  2364. * This function can only update fields filepath, filename, author, license.
  2365. * If anything (except filepath) is updated, timemodified is set to current time.
  2366. * If filename or filepath is updated the file unconnects from it's origin
  2367. * and therefore all references to it will be converted to copies when
  2368. * filearea is saved.
  2369. *
  2370. * @param int $draftid
  2371. * @param string $filepath path to the directory containing the file, or full path in case of directory
  2372. * @param string $filename name of the file, or '.' in case of directory
  2373. * @param array $updatedata array of fields to change (only filename, filepath, license and/or author can be updated)
  2374. * @throws moodle_exception if for any reason file can not be updated (file does not exist, target already exists, etc.)
  2375. */
  2376. public static function update_draftfile($draftid, $filepath, $filename, $updatedata) {
  2377. global $USER;
  2378. $fs = get_file_storage();
  2379. $usercontext = context_user::instance($USER->id);
  2380. // make sure filename and filepath are present in $updatedata
  2381. $updatedata = $updatedata + array('filepath' => $filepath, 'filename' => $filename);
  2382. $filemodified = false;
  2383. if (!$file = $fs->get_file($usercontext->id, 'user', 'draft', $draftid, $filepath, $filename)) {
  2384. if ($filename === '.') {
  2385. throw new moodle_exception('foldernotfound', 'repository');
  2386. } else {
  2387. throw new moodle_exception('filenotfound', 'error');
  2388. }
  2389. }
  2390. if (!$file->is_directory()) {
  2391. // This is a file
  2392. if ($updatedata['filepath'] !== $filepath || $updatedata['filename'] !== $filename) {
  2393. // Rename/move file: check that target file name does not exist.
  2394. if ($fs->file_exists($usercontext->id, 'user', 'draft', $draftid, $updatedata['filepath'], $updatedata['filename'])) {
  2395. throw new moodle_exception('fileexists', 'repository');
  2396. }
  2397. if (($filesource = @unserialize($file->get_source())) && isset($filesource->original)) {
  2398. unset($filesource->original);
  2399. $file->set_source(serialize($filesource));
  2400. }
  2401. $file->rename($updatedata['filepath'], $updatedata['filename']);
  2402. // timemodified is updated only when file is renamed and not updated when file is moved.
  2403. $filemodified = $filemodified || ($updatedata['filename'] !== $filename);
  2404. }
  2405. if (array_key_exists('license', $updatedata) && $updatedata['license'] !== $file->get_license()) {
  2406. // Update license and timemodified.
  2407. $file->set_license($updatedata['license']);
  2408. $filemodified = true;
  2409. }
  2410. if (array_key_exists('author', $updatedata) && $updatedata['author'] !== $file->get_author()) {
  2411. // Update author and timemodified.
  2412. $file->set_author($updatedata['author']);
  2413. $filemodified = true;
  2414. }
  2415. // Update timemodified:
  2416. if ($filemodified) {
  2417. $file->set_timemodified(time());
  2418. }
  2419. } else {
  2420. // This is a directory - only filepath can be updated for a directory (it was moved).
  2421. if ($updatedata['filepath'] === $filepath) {
  2422. // nothing to update
  2423. return;
  2424. }
  2425. if ($fs->file_exists($usercontext->id, 'user', 'draft', $draftid, $updatedata['filepath'], '.')) {
  2426. // bad luck, we can not rename if something already exists there
  2427. throw new moodle_exception('folderexists', 'repository');
  2428. }
  2429. $xfilepath = preg_quote($filepath, '|');
  2430. if (preg_match("|^$xfilepath|", $updatedata['filepath'])) {
  2431. // we can not move folder to it's own subfolder
  2432. throw new moodle_exception('folderrecurse', 'repository');
  2433. }
  2434. // If directory changed the name, update timemodified.
  2435. $filemodified = (basename(rtrim($file->get_filepath(), '/')) !== basename(rtrim($updatedata['filepath'], '/')));
  2436. // Now update directory and all children.
  2437. $files = $fs->get_area_files($usercontext->id, 'user', 'draft', $draftid);
  2438. foreach ($files as $f) {
  2439. if (preg_match("|^$xfilepath|", $f->get_filepath())) {
  2440. $path = preg_replace("|^$xfilepath|", $updatedata['filepath'], $f->get_filepath());
  2441. if (($filesource = @unserialize($f->get_source())) && isset($filesource->original)) {
  2442. // unset original so the references are not shown any more
  2443. unset($filesource->original);
  2444. $f->set_source(serialize($filesource));
  2445. }
  2446. $f->rename($path, $f->get_filename());
  2447. if ($filemodified && $f->get_filepath() === $updatedata['filepath'] && $f->get_filename() === $filename) {
  2448. $f->set_timemodified(time());
  2449. }
  2450. }
  2451. }
  2452. }
  2453. }
  2454. /**
  2455. * Delete a temp file from draft area
  2456. *
  2457. * @param int $draftitemid
  2458. * @param string $filepath
  2459. * @param string $filename
  2460. * @return bool
  2461. */
  2462. public static function delete_tempfile_from_draft($draftitemid, $filepath, $filename) {
  2463. global $USER;
  2464. $fs = get_file_storage();
  2465. $user_context = context_user::instance($USER->id);
  2466. if ($file = $fs->get_file($user_context->id, 'user', 'draft', $draftitemid, $filepath, $filename)) {
  2467. $file->delete();
  2468. return true;
  2469. } else {
  2470. return false;
  2471. }
  2472. }
  2473. /**
  2474. * Find all external files in this repo and import them
  2475. */
  2476. public function convert_references_to_local() {
  2477. $fs = get_file_storage();
  2478. $files = $fs->get_external_files($this->id);
  2479. foreach ($files as $storedfile) {
  2480. $fs->import_external_file($storedfile);
  2481. }
  2482. }
  2483. /**
  2484. * Method deprecated, cache is handled by MUC now.
  2485. * @deprecated since 2.6
  2486. */
  2487. public static function reset_caches() {
  2488. debugging('Function repository::reset_caches() is deprecated.', DEBUG_DEVELOPER);
  2489. }
  2490. /**
  2491. * Method deprecated
  2492. * @deprecated since 2.6
  2493. * @see repository::sync_reference()
  2494. */
  2495. public static function sync_external_file($file, $resetsynchistory = false) {
  2496. debugging('Function repository::sync_external_file() is deprecated.',
  2497. DEBUG_DEVELOPER);
  2498. if ($resetsynchistory || !$file || !$file->get_repository_id() ||
  2499. !($repository = self::get_repository_by_id($file->get_repository_id(), SYSCONTEXTID))) {
  2500. return false;
  2501. }
  2502. return $repository->sync_reference($file);
  2503. }
  2504. /**
  2505. * Performs synchronisation of an external file if the previous one has expired.
  2506. *
  2507. * This function must be implemented for external repositories supporting
  2508. * FILE_REFERENCE, it is called for existing aliases when their filesize,
  2509. * contenthash or timemodified are requested. It is not called for internal
  2510. * repositories (see {@link repository::has_moodle_files()}), references to
  2511. * internal files are updated immediately when source is modified.
  2512. *
  2513. * Referenced files may optionally keep their content in Moodle filepool (for
  2514. * thumbnail generation or to be able to serve cached copy). In this
  2515. * case both contenthash and filesize need to be synchronized. Otherwise repositories
  2516. * should use contenthash of empty file and correct filesize in bytes.
  2517. *
  2518. * Note that this function may be run for EACH file that needs to be synchronised at the
  2519. * moment. If anything is being downloaded or requested from external sources there
  2520. * should be a small timeout. The synchronisation is performed to update the size of
  2521. * the file and/or to update image and re-generated image preview. There is nothing
  2522. * fatal if syncronisation fails but it is fatal if syncronisation takes too long
  2523. * and hangs the script generating a page.
  2524. *
  2525. * Note: If you wish to call $file->get_filesize(), $file->get_contenthash() or
  2526. * $file->get_timemodified() make sure that recursion does not happen.
  2527. *
  2528. * Called from {@link stored_file::sync_external_file()}
  2529. *
  2530. * @uses stored_file::set_missingsource()
  2531. * @uses stored_file::set_synchronized()
  2532. * @param stored_file $file
  2533. * @return bool false when file does not need synchronisation, true if it was synchronised
  2534. */
  2535. public function sync_reference(stored_file $file) {
  2536. if ($file->get_repository_id() != $this->id) {
  2537. // This should not really happen because the function can be called from stored_file only.
  2538. return false;
  2539. }
  2540. if ($this->has_moodle_files()) {
  2541. // References to local files need to be synchronised only once.
  2542. // Later they will be synchronised automatically when the source is changed.
  2543. if ($file->get_referencelastsync()) {
  2544. return false;
  2545. }
  2546. $fs = get_file_storage();
  2547. $params = file_storage::unpack_reference($file->get_reference(), true);
  2548. if (!is_array($params) || !($storedfile = $fs->get_file($params['contextid'],
  2549. $params['component'], $params['filearea'], $params['itemid'], $params['filepath'],
  2550. $params['filename']))) {
  2551. $file->set_missingsource();
  2552. } else {
  2553. $file->set_synchronized($storedfile->get_contenthash(), $storedfile->get_filesize());
  2554. }
  2555. return true;
  2556. }
  2557. // Backward compatibility (Moodle 2.3-2.5) implementation that calls
  2558. // methods repository::get_reference_file_lifetime(), repository::sync_individual_file()
  2559. // and repository::get_file_by_reference(). These methods are removed from the
  2560. // base repository class but may still be implemented by the child classes.
  2561. // THIS IS NOT A GOOD EXAMPLE of implementation. For good examples see the overwriting methods.
  2562. if (!method_exists($this, 'get_file_by_reference')) {
  2563. // Function get_file_by_reference() is not implemented. No synchronisation.
  2564. return false;
  2565. }
  2566. // Check if the previous sync result is still valid.
  2567. if (method_exists($this, 'get_reference_file_lifetime')) {
  2568. $lifetime = $this->get_reference_file_lifetime($file->get_reference());
  2569. } else {
  2570. // Default value that was hardcoded in Moodle 2.3 - 2.5.
  2571. $lifetime = 60 * 60 * 24;
  2572. }
  2573. if (($lastsynced = $file->get_referencelastsync()) && $lastsynced + $lifetime >= time()) {
  2574. return false;
  2575. }
  2576. $cache = cache::make('core', 'repositories');
  2577. if (($lastsyncresult = $cache->get('sync:'.$file->get_referencefileid())) !== false) {
  2578. if ($lastsyncresult === true) {
  2579. // We are in the process of synchronizing this reference.
  2580. // Avoid recursion when calling $file->get_filesize() and $file->get_contenthash().
  2581. return false;
  2582. } else {
  2583. // We have synchronised the same reference inside this request already.
  2584. // It looks like the object $file was created before the synchronisation and contains old data.
  2585. if (!empty($lastsyncresult['missing'])) {
  2586. $file->set_missingsource();
  2587. } else {
  2588. $cache->set('sync:'.$file->get_referencefileid(), true);
  2589. if ($file->get_contenthash() != $lastsyncresult['contenthash'] ||
  2590. $file->get_filesize() != $lastsyncresult['filesize']) {
  2591. $file->set_synchronized($lastsyncresult['contenthash'], $lastsyncresult['filesize']);
  2592. }
  2593. $cache->set('sync:'.$file->get_referencefileid(), $lastsyncresult);
  2594. }
  2595. return true;
  2596. }
  2597. }
  2598. // Weird function sync_individual_file() that was present in API in 2.3 - 2.5, default value was true.
  2599. if (method_exists($this, 'sync_individual_file') && !$this->sync_individual_file($file)) {
  2600. return false;
  2601. }
  2602. // Set 'true' into the cache to indicate that file is in the process of synchronisation.
  2603. $cache->set('sync:'.$file->get_referencefileid(), true);
  2604. // Create object with the structure that repository::get_file_by_reference() expects.
  2605. $reference = new stdClass();
  2606. $reference->id = $file->get_referencefileid();
  2607. $reference->reference = $file->get_reference();
  2608. $reference->referencehash = sha1($file->get_reference());
  2609. $reference->lastsync = $file->get_referencelastsync();
  2610. $reference->lifetime = $lifetime;
  2611. $fileinfo = $this->get_file_by_reference($reference);
  2612. $contenthash = null;
  2613. $filesize = null;
  2614. $fs = get_file_storage();
  2615. if (!empty($fileinfo->filesize)) {
  2616. // filesize returned
  2617. if (!empty($fileinfo->contenthash) && $fs->content_exists($fileinfo->contenthash)) {
  2618. // contenthash is specified and valid
  2619. $contenthash = $fileinfo->contenthash;
  2620. } else if ($fileinfo->filesize == $file->get_filesize()) {
  2621. // we don't know the new contenthash but the filesize did not change,
  2622. // assume the contenthash did not change either
  2623. $contenthash = $file->get_contenthash();
  2624. } else {
  2625. // we can't save empty contenthash so generate contenthash from empty string
  2626. list($contenthash, $unused1, $unused2) = $fs->add_string_to_pool('');
  2627. }
  2628. $filesize = $fileinfo->filesize;
  2629. } else if (!empty($fileinfo->filepath)) {
  2630. // File path returned
  2631. list($contenthash, $filesize, $newfile) = $fs->add_file_to_pool($fileinfo->filepath);
  2632. } else if (!empty($fileinfo->handle) && is_resource($fileinfo->handle)) {
  2633. // File handle returned
  2634. $contents = '';
  2635. while (!feof($fileinfo->handle)) {
  2636. $contents .= fread($fileinfo->handle, 8192);
  2637. }
  2638. fclose($fileinfo->handle);
  2639. list($contenthash, $filesize, $newfile) = $fs->add_string_to_pool($contents);
  2640. } else if (isset($fileinfo->content)) {
  2641. // File content returned
  2642. list($contenthash, $filesize, $newfile) = $fs->add_string_to_pool($fileinfo->content);
  2643. }
  2644. if (!isset($contenthash) or !isset($filesize)) {
  2645. $file->set_missingsource(null);
  2646. $cache->set('sync:'.$file->get_referencefileid(), array('missing' => true));
  2647. } else {
  2648. // update files table
  2649. $file->set_synchronized($contenthash, $filesize);
  2650. $cache->set('sync:'.$file->get_referencefileid(),
  2651. array('contenthash' => $contenthash, 'filesize' => $filesize));
  2652. }
  2653. return true;
  2654. }
  2655. /**
  2656. * Build draft file's source field
  2657. *
  2658. * {@link file_restore_source_field_from_draft_file()}
  2659. * XXX: This is a hack for file manager (MDL-28666)
  2660. * For newly created draft files we have to construct
  2661. * source filed in php serialized data format.
  2662. * File manager needs to know the original file information before copying
  2663. * to draft area, so we append these information in mdl_files.source field
  2664. *
  2665. * @param string $source
  2666. * @return string serialised source field
  2667. */
  2668. public static function build_source_field($source) {
  2669. $sourcefield = new stdClass;
  2670. $sourcefield->source = $source;
  2671. return serialize($sourcefield);
  2672. }
  2673. /**
  2674. * Prepares the repository to be cached. Implements method from cacheable_object interface.
  2675. *
  2676. * @return array
  2677. */
  2678. public function prepare_to_cache() {
  2679. return array(
  2680. 'class' => get_class($this),
  2681. 'id' => $this->id,
  2682. 'ctxid' => $this->context->id,
  2683. 'options' => $this->options,
  2684. 'readonly' => $this->readonly
  2685. );
  2686. }
  2687. /**
  2688. * Restores the repository from cache. Implements method from cacheable_object interface.
  2689. *
  2690. * @return array
  2691. */
  2692. public static function wake_from_cache($data) {
  2693. $classname = $data['class'];
  2694. return new $classname($data['id'], $data['ctxid'], $data['options'], $data['readonly']);
  2695. }
  2696. /**
  2697. * Gets a file relative to this file in the repository and sends it to the browser.
  2698. * Used to allow relative file linking within a repository without creating file records
  2699. * for linked files
  2700. *
  2701. * Repositories that overwrite this must be very careful - see filesystem repository for example.
  2702. *
  2703. * @param stored_file $mainfile The main file we are trying to access relative files for.
  2704. * @param string $relativepath the relative path to the file we are trying to access.
  2705. *
  2706. */
  2707. public function send_relative_file(stored_file $mainfile, $relativepath) {
  2708. // This repository hasn't implemented this so send_file_not_found.
  2709. send_file_not_found();
  2710. }
  2711. /**
  2712. * helper function to check if the repository supports send_relative_file.
  2713. *
  2714. * @return true|false
  2715. */
  2716. public function supports_relative_file() {
  2717. return false;
  2718. }
  2719. }
  2720. /**
  2721. * Exception class for repository api
  2722. *
  2723. * @since 2.0
  2724. * @package core_repository
  2725. * @copyright 2009 Dongsheng Cai {@link http://dongsheng.org}
  2726. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  2727. */
  2728. class repository_exception extends moodle_exception {
  2729. }
  2730. /**
  2731. * This is a class used to define a repository instance form
  2732. *
  2733. * @since 2.0
  2734. * @package core_repository
  2735. * @copyright 2009 Dongsheng Cai {@link http://dongsheng.org}
  2736. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  2737. */
  2738. final class repository_instance_form extends moodleform {
  2739. /** @var stdClass repository instance */
  2740. protected $instance;
  2741. /** @var string repository plugin type */
  2742. protected $plugin;
  2743. /**
  2744. * Added defaults to moodle form
  2745. */
  2746. protected function add_defaults() {
  2747. $mform =& $this->_form;
  2748. $strrequired = get_string('required');
  2749. $mform->addElement('hidden', 'edit', ($this->instance) ? $this->instance->id : 0);
  2750. $mform->setType('edit', PARAM_INT);
  2751. $mform->addElement('hidden', 'new', $this->plugin);
  2752. $mform->setType('new', PARAM_ALPHANUMEXT);
  2753. $mform->addElement('hidden', 'plugin', $this->plugin);
  2754. $mform->setType('plugin', PARAM_PLUGIN);
  2755. $mform->addElement('hidden', 'typeid', $this->typeid);
  2756. $mform->setType('typeid', PARAM_INT);
  2757. $mform->addElement('hidden', 'contextid', $this->contextid);
  2758. $mform->setType('contextid', PARAM_INT);
  2759. $mform->addElement('text', 'name', get_string('name'), 'maxlength="100" size="30"');
  2760. $mform->addRule('name', $strrequired, 'required', null, 'client');
  2761. $mform->setType('name', PARAM_TEXT);
  2762. }
  2763. /**
  2764. * Define moodle form elements
  2765. */
  2766. public function definition() {
  2767. global $CFG;
  2768. // type of plugin, string
  2769. $this->plugin = $this->_customdata['plugin'];
  2770. $this->typeid = $this->_customdata['typeid'];
  2771. $this->contextid = $this->_customdata['contextid'];
  2772. $this->instance = (isset($this->_customdata['instance'])
  2773. && is_subclass_of($this->_customdata['instance'], 'repository'))
  2774. ? $this->_customdata['instance'] : null;
  2775. $mform =& $this->_form;
  2776. $this->add_defaults();
  2777. // Add instance config options.
  2778. $result = repository::static_function($this->plugin, 'instance_config_form', $mform);
  2779. if ($result === false) {
  2780. // Remove the name element if no other config options.
  2781. $mform->removeElement('name');
  2782. }
  2783. if ($this->instance) {
  2784. $data = array();
  2785. $data['name'] = $this->instance->name;
  2786. if (!$this->instance->readonly) {
  2787. // and set the data if we have some.
  2788. foreach ($this->instance->get_instance_option_names() as $config) {
  2789. if (!empty($this->instance->options[$config])) {
  2790. $data[$config] = $this->instance->options[$config];
  2791. } else {
  2792. $data[$config] = '';
  2793. }
  2794. }
  2795. }
  2796. $this->set_data($data);
  2797. }
  2798. if ($result === false) {
  2799. $mform->addElement('cancel');
  2800. } else {
  2801. $this->add_action_buttons(true, get_string('save','repository'));
  2802. }
  2803. }
  2804. /**
  2805. * Validate moodle form data
  2806. *
  2807. * @param array $data form data
  2808. * @param array $files files in form
  2809. * @return array errors
  2810. */
  2811. public function validation($data, $files) {
  2812. global $DB;
  2813. $errors = array();
  2814. $plugin = $this->_customdata['plugin'];
  2815. $instance = (isset($this->_customdata['instance'])
  2816. && is_subclass_of($this->_customdata['instance'], 'repository'))
  2817. ? $this->_customdata['instance'] : null;
  2818. if (!$instance) {
  2819. $errors = repository::static_function($plugin, 'instance_form_validation', $this, $data, $errors);
  2820. } else {
  2821. $errors = $instance->instance_form_validation($this, $data, $errors);
  2822. }
  2823. $sql = "SELECT count('x')
  2824. FROM {repository_instances} i, {repository} r
  2825. WHERE r.type=:plugin AND r.id=i.typeid AND i.name=:name AND i.contextid=:contextid";
  2826. $params = array('name' => $data['name'], 'plugin' => $this->plugin, 'contextid' => $this->contextid);
  2827. if ($instance) {
  2828. $sql .= ' AND i.id != :instanceid';
  2829. $params['instanceid'] = $instance->id;
  2830. }
  2831. if ($DB->count_records_sql($sql, $params) > 0) {
  2832. $errors['name'] = get_string('erroruniquename', 'repository');
  2833. }
  2834. return $errors;
  2835. }
  2836. }
  2837. /**
  2838. * This is a class used to define a repository type setting form
  2839. *
  2840. * @since 2.0
  2841. * @package core_repository
  2842. * @copyright 2009 Dongsheng Cai {@link http://dongsheng.org}
  2843. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  2844. */
  2845. final class repository_type_form extends moodleform {
  2846. /** @var stdClass repository instance */
  2847. protected $instance;
  2848. /** @var string repository plugin name */
  2849. protected $plugin;
  2850. /** @var string action */
  2851. protected $action;
  2852. /**
  2853. * Definition of the moodleform
  2854. */
  2855. public function definition() {
  2856. global $CFG;
  2857. // type of plugin, string
  2858. $this->plugin = $this->_customdata['plugin'];
  2859. $this->instance = (isset($this->_customdata['instance'])
  2860. && is_a($this->_customdata['instance'], 'repository_type'))
  2861. ? $this->_customdata['instance'] : null;
  2862. $this->action = $this->_customdata['action'];
  2863. $this->pluginname = $this->_customdata['pluginname'];
  2864. $mform =& $this->_form;
  2865. $strrequired = get_string('required');
  2866. $mform->addElement('hidden', 'action', $this->action);
  2867. $mform->setType('action', PARAM_TEXT);
  2868. $mform->addElement('hidden', 'repos', $this->plugin);
  2869. $mform->setType('repos', PARAM_PLUGIN);
  2870. // let the plugin add its specific fields
  2871. $classname = 'repository_' . $this->plugin;
  2872. require_once($CFG->dirroot . '/repository/' . $this->plugin . '/lib.php');
  2873. //add "enable course/user instances" checkboxes if multiple instances are allowed
  2874. $instanceoptionnames = repository::static_function($this->plugin, 'get_instance_option_names');
  2875. $result = call_user_func(array($classname, 'type_config_form'), $mform, $classname);
  2876. if (!empty($instanceoptionnames)) {
  2877. $sm = get_string_manager();
  2878. $component = 'repository';
  2879. if ($sm->string_exists('enablecourseinstances', 'repository_' . $this->plugin)) {
  2880. $component .= ('_' . $this->plugin);
  2881. }
  2882. $mform->addElement('checkbox', 'enablecourseinstances', get_string('enablecourseinstances', $component));
  2883. $mform->setType('enablecourseinstances', PARAM_BOOL);
  2884. $component = 'repository';
  2885. if ($sm->string_exists('enableuserinstances', 'repository_' . $this->plugin)) {
  2886. $component .= ('_' . $this->plugin);
  2887. }
  2888. $mform->addElement('checkbox', 'enableuserinstances', get_string('enableuserinstances', $component));
  2889. $mform->setType('enableuserinstances', PARAM_BOOL);
  2890. }
  2891. // set the data if we have some.
  2892. if ($this->instance) {
  2893. $data = array();
  2894. $option_names = call_user_func(array($classname,'get_type_option_names'));
  2895. if (!empty($instanceoptionnames)){
  2896. $option_names[] = 'enablecourseinstances';
  2897. $option_names[] = 'enableuserinstances';
  2898. }
  2899. $instanceoptions = $this->instance->get_options();
  2900. foreach ($option_names as $config) {
  2901. if (!empty($instanceoptions[$config])) {
  2902. $data[$config] = $instanceoptions[$config];
  2903. } else {
  2904. $data[$config] = '';
  2905. }
  2906. }
  2907. // XXX: set plugin name for plugins which doesn't have muliti instances
  2908. if (empty($instanceoptionnames)){
  2909. $data['pluginname'] = $this->pluginname;
  2910. }
  2911. $this->set_data($data);
  2912. }
  2913. $this->add_action_buttons(true, get_string('save','repository'));
  2914. }
  2915. /**
  2916. * Validate moodle form data
  2917. *
  2918. * @param array $data moodle form data
  2919. * @param array $files
  2920. * @return array errors
  2921. */
  2922. public function validation($data, $files) {
  2923. $errors = array();
  2924. $plugin = $this->_customdata['plugin'];
  2925. $instance = (isset($this->_customdata['instance'])
  2926. && is_subclass_of($this->_customdata['instance'], 'repository'))
  2927. ? $this->_customdata['instance'] : null;
  2928. if (!$instance) {
  2929. $errors = repository::static_function($plugin, 'type_form_validation', $this, $data, $errors);
  2930. } else {
  2931. $errors = $instance->type_form_validation($this, $data, $errors);
  2932. }
  2933. return $errors;
  2934. }
  2935. }
  2936. /**
  2937. * Generate all options needed by filepicker
  2938. *
  2939. * @param array $args including following keys
  2940. * context
  2941. * accepted_types
  2942. * return_types
  2943. *
  2944. * @return array the list of repository instances, including meta infomation, containing the following keys
  2945. * externallink
  2946. * repositories
  2947. * accepted_types
  2948. */
  2949. function initialise_filepicker($args) {
  2950. global $CFG, $USER, $PAGE, $OUTPUT;
  2951. static $templatesinitialized = array();
  2952. require_once($CFG->libdir . '/licenselib.php');
  2953. $return = new stdClass();
  2954. $licenses = array();
  2955. if (!empty($CFG->licenses)) {
  2956. $array = explode(',', $CFG->licenses);
  2957. foreach ($array as $license) {
  2958. $l = new stdClass();
  2959. $l->shortname = $license;
  2960. $l->fullname = get_string($license, 'license');
  2961. $licenses[] = $l;
  2962. }
  2963. }
  2964. if (!empty($CFG->sitedefaultlicense)) {
  2965. $return->defaultlicense = $CFG->sitedefaultlicense;
  2966. }
  2967. $return->licenses = $licenses;
  2968. $return->author = fullname($USER);
  2969. if (empty($args->context)) {
  2970. $context = $PAGE->context;
  2971. } else {
  2972. $context = $args->context;
  2973. }
  2974. $disable_types = array();
  2975. if (!empty($args->disable_types)) {
  2976. $disable_types = $args->disable_types;
  2977. }
  2978. $user_context = context_user::instance($USER->id);
  2979. list($context, $course, $cm) = get_context_info_array($context->id);
  2980. $contexts = array($user_context, context_system::instance());
  2981. if (!empty($course)) {
  2982. // adding course context
  2983. $contexts[] = context_course::instance($course->id);
  2984. }
  2985. $externallink = (int)get_config(null, 'repositoryallowexternallinks');
  2986. $repositories = repository::get_instances(array(
  2987. 'context'=>$contexts,
  2988. 'currentcontext'=> $context,
  2989. 'accepted_types'=>$args->accepted_types,
  2990. 'return_types'=>$args->return_types,
  2991. 'disable_types'=>$disable_types
  2992. ));
  2993. $return->repositories = array();
  2994. if (empty($externallink)) {
  2995. $return->externallink = false;
  2996. } else {
  2997. $return->externallink = true;
  2998. }
  2999. $return->userprefs = array();
  3000. $return->userprefs['recentrepository'] = get_user_preferences('filepicker_recentrepository', '');
  3001. $return->userprefs['recentlicense'] = get_user_preferences('filepicker_recentlicense', '');
  3002. $return->userprefs['recentviewmode'] = get_user_preferences('filepicker_recentviewmode', '');
  3003. user_preference_allow_ajax_update('filepicker_recentrepository', PARAM_INT);
  3004. user_preference_allow_ajax_update('filepicker_recentlicense', PARAM_SAFEDIR);
  3005. user_preference_allow_ajax_update('filepicker_recentviewmode', PARAM_INT);
  3006. // provided by form element
  3007. $return->accepted_types = file_get_typegroup('extension', $args->accepted_types);
  3008. $return->return_types = $args->return_types;
  3009. $templates = array();
  3010. foreach ($repositories as $repository) {
  3011. $meta = $repository->get_meta();
  3012. // Please note that the array keys for repositories are used within
  3013. // JavaScript a lot, the key NEEDS to be the repository id.
  3014. $return->repositories[$repository->id] = $meta;
  3015. // Register custom repository template if it has one
  3016. if(method_exists($repository, 'get_upload_template') && !array_key_exists('uploadform_' . $meta->type, $templatesinitialized)) {
  3017. $templates['uploadform_' . $meta->type] = $repository->get_upload_template();
  3018. $templatesinitialized['uploadform_' . $meta->type] = true;
  3019. }
  3020. }
  3021. if (!array_key_exists('core', $templatesinitialized)) {
  3022. // we need to send each filepicker template to the browser just once
  3023. $fprenderer = $PAGE->get_renderer('core', 'files');
  3024. $templates = array_merge($templates, $fprenderer->filepicker_js_templates());
  3025. $templatesinitialized['core'] = true;
  3026. }
  3027. if (sizeof($templates)) {
  3028. $PAGE->requires->js_init_call('M.core_filepicker.set_templates', array($templates), true);
  3029. }
  3030. return $return;
  3031. }