PageRenderTime 68ms CodeModel.GetById 18ms RepoModel.GetById 1ms app.codeStats 0ms

/repository/lib.php

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