PageRenderTime 82ms CodeModel.GetById 21ms RepoModel.GetById 1ms app.codeStats 0ms

/repository/lib.php

http://github.com/moodle/moodle
PHP | 3309 lines | 1850 code | 291 blank | 1168 comment | 409 complexity | f1cb589d088fb743be7cb9cd934d0071 MD5 | raw file
Possible License(s): MIT, AGPL-3.0, MPL-2.0-no-copyleft-exception, LGPL-3.0, GPL-3.0, Apache-2.0, LGPL-2.1, BSD-3-Clause
  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: {@link repository_boxnet}
  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);
  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']) || !($args['currentcontext'] instanceof context)) {
  917. $current_context = context_system::instance();
  918. } else {
  919. $current_context = $args['currentcontext'];
  920. }
  921. $args['currentcontext'] = $current_context->id;
  922. $contextids = array();
  923. if (!empty($args['context'])) {
  924. foreach ($args['context'] as $context) {
  925. $contextids[] = $context->id;
  926. }
  927. }
  928. $args['context'] = $contextids;
  929. if (!isset($args['onlyvisible'])) {
  930. $args['onlyvisible'] = true;
  931. }
  932. if (!isset($args['return_types'])) {
  933. $args['return_types'] = FILE_INTERNAL | FILE_EXTERNAL;
  934. }
  935. if (!isset($args['type'])) {
  936. $args['type'] = null;
  937. }
  938. if (empty($args['disable_types']) || !is_array($args['disable_types'])) {
  939. $args['disable_types'] = null;
  940. }
  941. if (empty($args['userid']) || !is_numeric($args['userid'])) {
  942. $args['userid'] = null;
  943. }
  944. if (!isset($args['accepted_types']) || (is_array($args['accepted_types']) && in_array('*', $args['accepted_types']))) {
  945. $args['accepted_types'] = '*';
  946. }
  947. ksort($args);
  948. $cachekey = 'all:'. serialize($args);
  949. // Check if we have cached list of repositories with the same query
  950. $cache = cache::make('core', 'repositories');
  951. if (($cachedrepositories = $cache->get($cachekey)) !== false) {
  952. // convert from cacheable_object_array to array
  953. $repositories = array();
  954. foreach ($cachedrepositories as $repository) {
  955. $repositories[$repository->id] = $repository;
  956. }
  957. return $repositories;
  958. }
  959. // Prepare DB SQL query to retrieve repositories
  960. $params = array();
  961. $sql = "SELECT i.*, r.type AS repositorytype, r.sortorder, r.visible
  962. FROM {repository} r, {repository_instances} i
  963. WHERE i.typeid = r.id ";
  964. if ($args['disable_types']) {
  965. list($types, $p) = $DB->get_in_or_equal($args['disable_types'], SQL_PARAMS_NAMED, 'distype', false);
  966. $sql .= " AND r.type $types";
  967. $params = array_merge($params, $p);
  968. }
  969. if ($args['userid']) {
  970. $sql .= " AND (i.userid = 0 or i.userid = :userid)";
  971. $params['userid'] = $args['userid'];
  972. }
  973. if ($args['context']) {
  974. list($ctxsql, $p2) = $DB->get_in_or_equal($args['context'], SQL_PARAMS_NAMED, 'ctx');
  975. $sql .= " AND i.contextid $ctxsql";
  976. $params = array_merge($params, $p2);
  977. }
  978. if ($args['onlyvisible'] == true) {
  979. $sql .= " AND r.visible = 1";
  980. }
  981. if ($args['type'] !== null) {
  982. $sql .= " AND r.type = :type";
  983. $params['type'] = $args['type'];
  984. }
  985. $sql .= " ORDER BY r.sortorder, i.name";
  986. if (!$records = $DB->get_records_sql($sql, $params)) {
  987. $records = array();
  988. }
  989. $repositories = array();
  990. // Sortorder should be unique, which is not true if we use $record->sortorder
  991. // and there are multiple instances of any repository type
  992. $sortorder = 1;
  993. foreach ($records as $record) {
  994. $cache->set('i:'. $record->id, $record);
  995. if (!file_exists($CFG->dirroot . '/repository/'. $record->repositorytype.'/lib.php')) {
  996. continue;
  997. }
  998. $repository = self::get_repository_by_id($record->id, $current_context);
  999. $repository->options['sortorder'] = $sortorder++;
  1000. $is_supported = true;
  1001. // check mimetypes
  1002. if ($args['accepted_types'] !== '*' and $repository->supported_filetypes() !== '*') {
  1003. $accepted_ext = file_get_typegroup('extension', $args['accepted_types']);
  1004. $supported_ext = file_get_typegroup('extension', $repository->supported_filetypes());
  1005. $valid_ext = array_intersect($accepted_ext, $supported_ext);
  1006. $is_supported = !empty($valid_ext);
  1007. }
  1008. // Check return values.
  1009. if (!empty($args['return_types']) && !($repository->supported_returntypes() & $args['return_types'])) {
  1010. $is_supported = false;
  1011. }
  1012. if (!$args['onlyvisible'] || ($repository->is_visible() && !$repository->disabled)) {
  1013. // check capability in current context
  1014. $capability = has_capability('repository/'.$record->repositorytype.':view', $current_context);
  1015. if ($record->repositorytype == 'coursefiles') {
  1016. // coursefiles plugin needs managefiles permission
  1017. $capability = $capability && has_capability('moodle/course:managefiles', $current_context);
  1018. }
  1019. if ($is_supported && $capability) {
  1020. $repositories[$repository->id] = $repository;
  1021. }
  1022. }
  1023. }
  1024. $cache->set($cachekey, new cacheable_object_array($repositories));
  1025. return $repositories;
  1026. }
  1027. /**
  1028. * Get single repository instance for administrative actions
  1029. *
  1030. * Do not use this function to access repository contents, because it
  1031. * does not set the current context
  1032. *
  1033. * @see repository::get_repository_by_id()
  1034. *
  1035. * @static
  1036. * @param integer $id repository instance id
  1037. * @return repository
  1038. */
  1039. public static function get_instance($id) {
  1040. return self::get_repository_by_id($id, context_system::instance());
  1041. }
  1042. /**
  1043. * Call a static function. Any additional arguments than plugin and function will be passed through.
  1044. *
  1045. * @static
  1046. * @param string $plugin repository plugin name
  1047. * @param string $function function name
  1048. * @return mixed
  1049. */
  1050. public static function static_function($plugin, $function) {
  1051. global $CFG;
  1052. //check that the plugin exists
  1053. $typedirectory = $CFG->dirroot . '/repository/'. $plugin . '/lib.php';
  1054. if (!file_exists($typedirectory)) {
  1055. //throw new repository_exception('invalidplugin', 'repository');
  1056. return false;
  1057. }
  1058. $args = func_get_args();
  1059. if (count($args) <= 2) {
  1060. $args = array();
  1061. } else {
  1062. array_shift($args);
  1063. array_shift($args);
  1064. }
  1065. require_once($typedirectory);
  1066. return call_user_func_array(array('repository_' . $plugin, $function), $args);
  1067. }
  1068. /**
  1069. * Scan file, throws exception in case of infected file.
  1070. *
  1071. * Please note that the scanning engine must be able to access the file,
  1072. * permissions of the file are not modified here!
  1073. *
  1074. * @static
  1075. * @deprecated since Moodle 3.0
  1076. * @param string $thefile
  1077. * @param string $filename name of the file
  1078. * @param bool $deleteinfected
  1079. */
  1080. public static function antivir_scan_file($thefile, $filename, $deleteinfected) {
  1081. debugging('Please upgrade your code to use \core\antivirus\manager::scan_file instead', DEBUG_DEVELOPER);
  1082. \core\antivirus\manager::scan_file($thefile, $filename, $deleteinfected);
  1083. }
  1084. /**
  1085. * Repository method to serve the referenced file
  1086. *
  1087. * @see send_stored_file
  1088. *
  1089. * @param stored_file $storedfile the file that contains the reference
  1090. * @param int $lifetime Number of seconds before the file should expire from caches (null means $CFG->filelifetime)
  1091. * @param int $filter 0 (default)=no filtering, 1=all files, 2=html files only
  1092. * @param bool $forcedownload If true (default false), forces download of file rather than view in browser/plugin
  1093. * @param array $options additional options affecting the file serving
  1094. */
  1095. public function send_file($storedfile, $lifetime=null , $filter=0, $forcedownload=false, array $options = null) {
  1096. if ($this->has_moodle_files()) {
  1097. $fs = get_file_storage();
  1098. $params = file_storage::unpack_reference($storedfile->get_reference(), true);
  1099. $srcfile = null;
  1100. if (is_array($params)) {
  1101. $srcfile = $fs->get_file($params['contextid'], $params['component'], $params['filearea'],
  1102. $params['itemid'], $params['filepath'], $params['filename']);
  1103. }
  1104. if (empty($options)) {
  1105. $options = array();
  1106. }
  1107. if (!isset($options['filename'])) {
  1108. $options['filename'] = $storedfile->get_filename();
  1109. }
  1110. if (!$srcfile) {
  1111. send_file_not_found();
  1112. } else {
  1113. send_stored_file($srcfile, $lifetime, $filter, $forcedownload, $options);
  1114. }
  1115. } else {
  1116. throw new coding_exception("Repository plugin must implement send_file() method.");
  1117. }
  1118. }
  1119. /**
  1120. * Return human readable reference information
  1121. *
  1122. * @param string $reference value of DB field files_reference.reference
  1123. * @param int $filestatus status of the file, 0 - ok, 666 - source missing
  1124. * @return string
  1125. */
  1126. public function get_reference_details($reference, $filestatus = 0) {
  1127. if ($this->has_moodle_files()) {
  1128. $fileinfo = null;
  1129. $params = file_storage::unpack_reference($reference, true);
  1130. if (is_array($params)) {
  1131. $context = context::instance_by_id($params['contextid'], IGNORE_MISSING);
  1132. if ($context) {
  1133. $browser = get_file_browser();
  1134. $fileinfo = $browser->get_file_info($context, $params['component'], $params['filearea'], $params['itemid'], $params['filepath'], $params['filename']);
  1135. }
  1136. }
  1137. if (empty($fileinfo)) {
  1138. if ($filestatus == 666) {
  1139. if (is_siteadmin() || ($context && has_capability('moodle/course:managefiles', $context))) {
  1140. return get_string('lostsource', 'repository',
  1141. $params['contextid']. '/'. $params['component']. '/'. $params['filearea']. '/'. $params['itemid']. $params['filepath']. $params['filename']);
  1142. } else {
  1143. return get_string('lostsource', 'repository', '');
  1144. }
  1145. }
  1146. return get_string('undisclosedsource', 'repository');
  1147. } else {
  1148. return $fileinfo->get_readable_fullname();
  1149. }
  1150. }
  1151. return '';
  1152. }
  1153. /**
  1154. * Cache file from external repository by reference
  1155. * {@link repository::get_file_reference()}
  1156. * {@link repository::get_file()}
  1157. * Invoked at MOODLE/repository/repository_ajax.php
  1158. *
  1159. * @param string $reference this reference is generated by
  1160. * repository::get_file_reference()
  1161. * @param stored_file $storedfile created file reference
  1162. */
  1163. public function cache_file_by_reference($reference, $storedfile) {
  1164. }
  1165. /**
  1166. * reference_file_selected
  1167. *
  1168. * This function is called when a controlled link file is selected in a file picker and the form is
  1169. * saved. The expected behaviour for repositories supporting controlled links is to
  1170. * - copy the file to the moodle system account
  1171. * - put it in a folder that reflects the context it is being used
  1172. * - make sure the sharing permissions are correct (read-only with the link)
  1173. * - return a new reference string pointing to the newly copied file.
  1174. *
  1175. * @param string $reference this reference is generated by
  1176. * repository::get_file_reference()
  1177. * @param context $context the target context for this new file.
  1178. * @param string $component the target component for this new file.
  1179. * @param string $filearea the target filearea for this new file.
  1180. * @param string $itemid the target itemid for this new file.
  1181. * @return string updated reference (final one before it's saved to db).
  1182. */
  1183. public function reference_file_selected($reference, $context, $component, $filearea, $itemid) {
  1184. return $reference;
  1185. }
  1186. /**
  1187. * Return the source information
  1188. *
  1189. * The result of the function is stored in files.source field. It may be analysed
  1190. * when the source file is lost or repository may use it to display human-readable
  1191. * location of reference original.
  1192. *
  1193. * This method is called when file is picked for the first time only. When file
  1194. * (either copy or a reference) is already in moodle and it is being picked
  1195. * again to another file area (also as a copy or as a reference), the value of
  1196. * files.source is copied.
  1197. *
  1198. * @param string $source source of the file, returned by repository as 'source' and received back from user (not cleaned)
  1199. * @return string|null
  1200. */
  1201. public function get_file_source_info($source) {
  1202. if ($this->has_moodle_files()) {
  1203. $reference = $this->get_file_reference($source);
  1204. return $this->get_reference_details($reference, 0);
  1205. }
  1206. return $source;
  1207. }
  1208. /**
  1209. * Move file from download folder to file pool using FILE API
  1210. *
  1211. * @todo MDL-28637
  1212. * @static
  1213. * @param string $thefile file path in download folder
  1214. * @param stdClass $record
  1215. * @return array containing the following keys:
  1216. * icon
  1217. * file
  1218. * id
  1219. * url
  1220. */
  1221. public static function move_to_filepool($thefile, $record) {
  1222. global $DB, $CFG, $USER, $OUTPUT;
  1223. // scan for viruses if possible, throws exception if problem found
  1224. // TODO: MDL-28637 this repository_no_delete is a bloody hack!
  1225. \core\antivirus\manager::scan_file($thefile, $record->filename, empty($CFG->repository_no_delete));
  1226. $fs = get_file_storage();
  1227. // If file name being used.
  1228. if (repository::draftfile_exists($record->itemid, $record->filepath, $record->filename)) {
  1229. $draftitemid = $record->itemid;
  1230. $new_filename = repository::get_unused_filename($draftitemid, $record->filepath, $record->filename);
  1231. $old_filename = $record->filename;
  1232. // Create a tmp file.
  1233. $record->filename = $new_filename;
  1234. $newfile = $fs->create_file_from_pathname($record, $thefile);
  1235. $event = array();
  1236. $event['event'] = 'fileexists';
  1237. $event['newfile'] = new stdClass;
  1238. $event['newfile']->filepath = $record->filepath;
  1239. $event['newfile']->filename = $new_filename;
  1240. $event['newfile']->url = moodle_url::make_draftfile_url($draftitemid, $record->filepath, $new_filename)->out();
  1241. $event['existingfile'] = new stdClass;
  1242. $event['existingfile']->filepath = $record->filepath;
  1243. $event['existingfile']->filename = $old_filename;
  1244. $event['existingfile']->url = moodle_url::make_draftfile_url($draftitemid, $record->filepath, $old_filename)->out();
  1245. return $event;
  1246. }
  1247. if ($file = $fs->create_file_from_pathname($record, $thefile)) {
  1248. if (empty($CFG->repository_no_delete)) {
  1249. $delete = unlink($thefile);
  1250. unset($CFG->repository_no_delete);
  1251. }
  1252. return array(
  1253. 'url'=>moodle_url::make_draftfile_url($file->get_itemid(), $file->get_filepath(), $file->get_filename())->out(),
  1254. 'id'=>$file->get_itemid(),
  1255. 'file'=>$file->get_filename(),
  1256. 'icon' => $OUTPUT->image_url(file_extension_icon($thefile, 32))->out(),
  1257. );
  1258. } else {
  1259. return null;
  1260. }
  1261. }
  1262. /**
  1263. * Builds a tree of files This function is then called recursively.
  1264. *
  1265. * @static
  1266. * @todo take $search into account, and respect a threshold for dynamic loading
  1267. * @param file_info $fileinfo an object returned by file_browser::get_file_info()
  1268. * @param string $search searched string
  1269. * @param bool $dynamicmode no recursive call is done when in dynamic mode
  1270. * @param array $list the array containing the files under the passed $fileinfo
  1271. * @return int the number of files found
  1272. */
  1273. public static function build_tree($fileinfo, $search, $dynamicmode, &$list) {
  1274. global $CFG, $OUTPUT;
  1275. $filecount = 0;
  1276. $children = $fileinfo->get_children();
  1277. foreach ($children as $child) {
  1278. $filename = $child->get_visible_name();
  1279. $filesize = $child->get_filesize();
  1280. $filesize = $filesize ? display_size($filesize) : '';
  1281. $filedate = $child->get_timemodified();
  1282. $filedate = $filedate ? userdate($filedate) : '';
  1283. $filetype = $child->get_mimetype();
  1284. if ($child->is_directory()) {
  1285. $path = array();
  1286. $level = $child->get_parent();
  1287. while ($level) {
  1288. $params = $level->get_params();
  1289. $path[] = array($params['filepath'], $level->get_visible_name());
  1290. $level = $level->get_parent();
  1291. }
  1292. $tmp = array(
  1293. 'title' => $child->get_visible_name(),
  1294. 'size' => 0,
  1295. 'date' => $filedate,
  1296. 'path' => array_reverse($path),
  1297. 'thumbnail' => $OUTPUT->image_url(file_folder_icon(90))->out(false)
  1298. );
  1299. //if ($dynamicmode && $child->is_writable()) {
  1300. // $tmp['children'] = array();
  1301. //} else {
  1302. // if folder name matches search, we send back all files contained.
  1303. $_search = $search;
  1304. if ($search && stristr($tmp['title'], $search) !== false) {
  1305. $_search = false;
  1306. }
  1307. $tmp['children'] = array();
  1308. $_filecount = repository::build_tree($child, $_search, $dynamicmode, $tmp['children']);
  1309. if ($search && $_filecount) {
  1310. $tmp['expanded'] = 1;
  1311. }
  1312. //}
  1313. if (!$search || $_filecount || (stristr($tmp['title'], $search) !== false)) {
  1314. $filecount += $_filecount;
  1315. $list[] = $tmp;
  1316. }
  1317. } else { // not a directory
  1318. // skip the file, if we're in search mode and it's not a match
  1319. if ($search && (stristr($filename, $search) === false)) {
  1320. continue;
  1321. }
  1322. $params = $child->get_params();
  1323. $source = serialize(array($params['contextid'], $params['component'], $params['filearea'], $params['itemid'], $params['filepath'], $params['filename']));
  1324. $list[] = array(
  1325. 'title' => $filename,
  1326. 'size' => $filesize,
  1327. 'date' => $filedate,
  1328. //'source' => $child->get_url(),
  1329. 'source' => base64_encode($source),
  1330. 'icon'=>$OUTPUT->image_url(file_file_icon($child, 24))->out(false),
  1331. 'thumbnail'=>$OUTPUT->image_url(file_file_icon($child, 90))->out(false),
  1332. );
  1333. $filecount++;
  1334. }
  1335. }
  1336. return $filecount;
  1337. }
  1338. /**
  1339. * Display a repository instance list (with edit/delete/create links)
  1340. *
  1341. * @static
  1342. * @param stdClass $context the context for which we display the instance
  1343. * @param string $typename if set, we display only one type of instance
  1344. */
  1345. public static function display_instances_list($context, $typename = null) {
  1346. global $CFG, $USER, $OUTPUT;
  1347. $output = $OUTPUT->box_start('generalbox');
  1348. //if the context is SYSTEM, so we call it from administration page
  1349. $admin = ($context->id == SYSCONTEXTID) ? true : false;
  1350. if ($admin) {
  1351. $baseurl = new moodle_url('/'.$CFG->admin.'/repositoryinstance.php', array('sesskey'=>sesskey()));
  1352. $output .= $OUTPUT->heading(get_string('siteinstances', 'repository'));
  1353. } else {
  1354. $baseurl = new moodle_url('/repository/manage_instances.php', array('contextid'=>$context->id, 'sesskey'=>sesskey()));
  1355. }
  1356. $namestr = get_string('name');
  1357. $pluginstr = get_string('plugin', 'repository');
  1358. $settingsstr = get_string('settings');
  1359. $deletestr = get_string('delete');
  1360. // Retrieve list of instances. In administration context we want to display all
  1361. // instances of a type, even if this type is not visible. In course/user context we
  1362. // want to display only visible instances, but for every type types. The repository::get_instances()
  1363. // third parameter displays only visible type.
  1364. $params = array();
  1365. $params['context'] = array($context);
  1366. $params['currentcontext'] = $context;
  1367. $params['return_types'] = 0;
  1368. $params['onlyvisible'] = !$admin;
  1369. $params['type'] = $typename;
  1370. $instances = repository::get_instances($params);
  1371. $instancesnumber = count($instances);
  1372. $alreadyplugins = array();
  1373. $table = new html_table();
  1374. $table->head = array($namestr, $pluginstr, $settingsstr, $deletestr);
  1375. $table->align = array('left', 'left', 'center','center');
  1376. $table->data = array();
  1377. $updowncount = 1;
  1378. foreach ($instances as $i) {
  1379. $settings = '';
  1380. $delete = '';
  1381. $type = repository::get_type_by_id($i->options['typeid']);
  1382. if ($type->get_contextvisibility($context)) {
  1383. if (!$i->readonly) {
  1384. $settingurl = new moodle_url($baseurl);
  1385. $settingurl->param('type', $i->options['type']);
  1386. $settingurl->param('edit', $i->id);
  1387. $settings .= html_writer::link($settingurl, $settingsstr);
  1388. $deleteurl = new moodle_url($baseurl);
  1389. $deleteurl->param('delete', $i->id);
  1390. $deleteurl->param('type', $i->options['type']);
  1391. $delete .= html_writer::link($deleteurl, $deletestr);
  1392. }
  1393. }
  1394. $type = repository::get_type_by_id($i->options['typeid']);
  1395. $table->data[] = array(format_string($i->name), $type->get_readablename(), $settings, $delete);
  1396. //display a grey row if the type is defined as not visible
  1397. if (isset($type) && !$type->get_visible()) {
  1398. $table->rowclasses[] = 'dimmed_text';
  1399. } else {
  1400. $table->rowclasses[] = '';
  1401. }
  1402. if (!in_array($i->name, $alreadyplugins)) {
  1403. $alreadyplugins[] = $i->name;
  1404. }
  1405. }
  1406. $output .= html_writer::table($table);
  1407. $instancehtml = '<div>';
  1408. $addable = 0;
  1409. //if no type is set, we can create all type of instance
  1410. if (!$typename) {
  1411. $instancehtml .= '<h3>';
  1412. $instancehtml .= get_string('createrepository', 'repository');
  1413. $instancehtml .= '</h3><ul>';
  1414. $types = repository::get_editable_types($context);
  1415. foreach ($types as $type) {
  1416. if (!empty($type) && $type->get_visible()) {
  1417. // If the user does not have the permission to view the repository, it won't be displayed in
  1418. // the list of instances. Hiding the link to create new instances will prevent the
  1419. // user from creating them without being able to find them afterwards, which looks like a bug.
  1420. if (!has_capability('repository/'.$type->get_typename().':view', $context)) {
  1421. continue;
  1422. }
  1423. $instanceoptionnames = repository::static_function($type->get_typename(), 'get_instance_option_names');
  1424. if (!empty($instanceoptionnames)) {
  1425. $baseurl->param('new', $type->get_typename());
  1426. $instancehtml .= '<li><a href="'.$baseurl->out().'">'.get_string('createxxinstance', 'repository', get_string('pluginname', 'repository_'.$type->get_typename())). '</a></li>';
  1427. $baseurl->remove_params('new');
  1428. $addable++;
  1429. }
  1430. }
  1431. }
  1432. $instancehtml .= '</ul>';
  1433. } else {
  1434. $instanceoptionnames = repository::static_function($typename, 'get_instance_option_names');
  1435. if (!empty($instanceoptionnames)) { //create a unique type of instance
  1436. $addable = 1;
  1437. $baseurl->param('new', $typename);
  1438. $output .= $OUTPUT->single_button($baseurl, get_string('createinstance', 'repository'), 'get');
  1439. $baseurl->remove_params('new');
  1440. }
  1441. }
  1442. if ($addable) {
  1443. $instancehtml .= '</div>';
  1444. $output .= $instancehtml;
  1445. }
  1446. $output .= $OUTPUT->box_end();
  1447. //print the list + creation links
  1448. print($output);
  1449. }
  1450. /**
  1451. * Prepare file reference information
  1452. *
  1453. * @param string $source source of the file, returned by repository as 'source' and received back from user (not cleaned)
  1454. * @return string file reference, ready to be stored
  1455. */
  1456. public function get_file_reference($source) {
  1457. if ($source && $this->has_moodle_files()) {
  1458. $params = @json_decode(base64_decode($source), true);
  1459. if (!is_array($params) || empty($params['contextid'])) {
  1460. throw new repository_exception('invalidparams', 'repository');
  1461. }
  1462. $params = array(
  1463. 'component' => empty($params['component']) ? '' : clean_param($params['component'], PARAM_COMPONENT),
  1464. 'filearea' => empty($params['filearea']) ? '' : clean_param($params['filearea'], PARAM_AREA),
  1465. 'itemid' => empty($params['itemid']) ? 0 : clean_param($params['itemid'], PARAM_INT),
  1466. 'filename' => empty($params['filename']) ? null : clean_param($params['filename'], PARAM_FILE),
  1467. 'filepath' => empty($params['filepath']) ? null : clean_param($params['filepath'], PARAM_PATH),
  1468. 'contextid' => clean_param($params['contextid'], PARAM_INT)
  1469. );
  1470. // Check if context exists.
  1471. if (!context::instance_by_id($params['contextid'], IGNORE_MISSING)) {
  1472. throw new repository_exception('invalidparams', 'repository');
  1473. }
  1474. return file_storage::pack_reference($params);
  1475. }
  1476. return $source;
  1477. }
  1478. /**
  1479. * Get a unique file path in which to save the file.
  1480. *
  1481. * The filename returned will be removed at the end of the request and
  1482. * should not be relied upon to exist in subsequent requests.
  1483. *
  1484. * @param string $filename file name
  1485. * @return file path
  1486. */
  1487. public function prepare_file($filename) {
  1488. if (empty($filename)) {
  1489. $filename = 'file';
  1490. }
  1491. return sprintf('%s/%s', make_request_directory(), $filename);
  1492. }
  1493. /**
  1494. * Does this repository used to browse moodle files?
  1495. *
  1496. * @return bool
  1497. */
  1498. public function has_moodle_files() {
  1499. return false;
  1500. }
  1501. /**
  1502. * Return file URL, for most plugins, the parameter is the original
  1503. * url, but some plugins use a file id, so we need this function to
  1504. * convert file id to original url.
  1505. *
  1506. * @param string $url the url of file
  1507. * @return string
  1508. */
  1509. public function get_link($url) {
  1510. return $url;
  1511. }
  1512. /**
  1513. * Downloads a file from external repository and saves it in temp dir
  1514. *
  1515. * Function get_file() must be implemented by repositories that support returntypes
  1516. * FILE_INTERNAL or FILE_REFERENCE. It is invoked to pick up the file and copy it
  1517. * to moodle. This function is not called for moodle repositories, the function
  1518. * {@link repository::copy_to_area()} is used instead.
  1519. *
  1520. * This function can be overridden by subclass if the files.reference field contains
  1521. * not just URL or if request should be done differently.
  1522. *
  1523. * @see curl
  1524. * @throws file_exception when error occured
  1525. *
  1526. * @param string $url the content of files.reference field, in this implementaion
  1527. * it is asssumed that it contains the string with URL of the file
  1528. * @param string $filename filename (without path) to save the downloaded file in the
  1529. * temporary directory, if omitted or file already exists the new filename will be generated
  1530. * @return array with elements:
  1531. * path: internal location of the file
  1532. * url: URL to the source (from parameters)
  1533. */
  1534. public function get_file($url, $filename = '') {
  1535. global $CFG;
  1536. $path = $this->prepare_file($filename);
  1537. $c = new curl;
  1538. $result = $c->download_one($url, null, array('filepath' => $path, 'timeout' => $CFG->repositorygetfiletimeout));
  1539. if ($result !== true) {
  1540. throw new moodle_exception('errorwhiledownload', 'repository', '', $result);
  1541. }
  1542. return array('path'=>$path, 'url'=>$url);
  1543. }
  1544. /**
  1545. * Downloads the file from external repository and saves it in moodle filepool.
  1546. * This function is different from {@link repository::sync_reference()} because it has
  1547. * bigger request timeout and always downloads the content.
  1548. *
  1549. * This function is invoked when we try to unlink the file from the source and convert
  1550. * a reference into a true copy.
  1551. *
  1552. * @throws exception when file could not be imported
  1553. *
  1554. * @param stored_file $file
  1555. * @param int $maxbytes throw an exception if file size is bigger than $maxbytes (0 means no limit)
  1556. */
  1557. public function import_external_file_contents(stored_file $file, $maxbytes = 0) {
  1558. if (!$file->is_external_file()) {
  1559. // nothing to import if the file is not a reference
  1560. return;
  1561. } else if ($file->get_repository_id() != $this->id) {
  1562. // error
  1563. debugging('Repository instance id does not match');
  1564. return;
  1565. } else if ($this->has_moodle_files()) {
  1566. // files that are references to local files are already in moodle filepool
  1567. // just validate the size
  1568. if ($maxbytes > 0 && $file->get_filesize() > $maxbytes) {
  1569. $maxbytesdisplay = display_size($maxbytes);
  1570. throw new file_exception('maxbytesfile', (object) array('file' => $file->get_filename(),
  1571. 'size' => $maxbytesdisplay));
  1572. }
  1573. return;
  1574. } else {
  1575. if ($maxbytes > 0 && $file->get_filesize() > $maxbytes) {
  1576. // note that stored_file::get_filesize() also calls synchronisation
  1577. $maxbytesdisplay = display_size($maxbytes);
  1578. throw new file_exception('maxbytesfile', (object) array('file' => $file->get_filename(),
  1579. 'size' => $maxbytesdisplay));
  1580. }
  1581. $fs = get_file_storage();
  1582. // If a file has been downloaded, the file record should report both a positive file
  1583. // size, and a contenthash which does not related to empty content.
  1584. // If thereis no file size, or the contenthash is for an empty file, then the file has
  1585. // yet to be successfully downloaded.
  1586. $contentexists = $file->get_filesize() && !$file->compare_to_string('');
  1587. if (!$file->get_status() && $contentexists) {
  1588. // we already have the content in moodle filepool and it was synchronised recently.
  1589. // Repositories may overwrite it if they want to force synchronisation anyway!
  1590. return;
  1591. } else {
  1592. // attempt to get a file
  1593. try {
  1594. $fileinfo = $this->get_file($file->get_reference());
  1595. if (isset($fileinfo['path'])) {
  1596. $file->set_synchronised_content_from_file($fileinfo['path']);
  1597. } else {
  1598. throw new moodle_exception('errorwhiledownload', 'repository', '', '');
  1599. }
  1600. } catch (Exception $e) {
  1601. if ($contentexists) {
  1602. // better something than nothing. We have a copy of file. It's sync time
  1603. // has expired but it is still very likely that it is the last version
  1604. } else {
  1605. throw($e);
  1606. }
  1607. }
  1608. }
  1609. }
  1610. }
  1611. /**
  1612. * Return size of a file in bytes.
  1613. *
  1614. * @param string $source encoded and serialized data of file
  1615. * @return int file size in bytes
  1616. */
  1617. public function get_file_size($source) {
  1618. // TODO MDL-33297 remove this function completely?
  1619. $browser = get_file_browser();
  1620. $params = unserialize(base64_decode($source));
  1621. $contextid = clean_param($params['contextid'], PARAM_INT);
  1622. $fileitemid = clean_param($params['itemid'], PARAM_INT);
  1623. $filename = clean_param($params['filename'], PARAM_FILE);
  1624. $filepath = clean_param($params['filepath'], PARAM_PATH);
  1625. $filearea = clean_param($params['filearea'], PARAM_AREA);
  1626. $component = clean_param($params['component'], PARAM_COMPONENT);
  1627. $context = context::instance_by_id($contextid);
  1628. $file_info = $browser->get_file_info($context, $component, $filearea, $fileitemid, $filepath, $filename);
  1629. if (!empty($file_info)) {
  1630. $filesize = $file_info->get_filesize();
  1631. } else {
  1632. $filesize = null;
  1633. }
  1634. return $filesize;
  1635. }
  1636. /**
  1637. * Return is the instance is visible
  1638. * (is the type visible ? is the context enable ?)
  1639. *
  1640. * @return bool
  1641. */
  1642. public function is_visible() {
  1643. $type = repository::get_type_by_id($this->options['typeid']);
  1644. $instanceoptions = repository::static_function($type->get_typename(), 'get_instance_option_names');
  1645. if ($type->get_visible()) {
  1646. //if the instance is unique so it's visible, otherwise check if the instance has a enabled context
  1647. if (empty($instanceoptions) || $type->get_contextvisibility(context::instance_by_id($this->instance->contextid))) {
  1648. return true;
  1649. }
  1650. }
  1651. return false;
  1652. }
  1653. /**
  1654. * Can the instance be edited by the current user?
  1655. *
  1656. * The property $readonly must not be used within this method because
  1657. * it only controls if the options from self::get_instance_option_names()
  1658. * can be edited.
  1659. *
  1660. * @return bool true if the user can edit the instance.
  1661. * @since Moodle 2.5
  1662. */
  1663. public final function can_be_edited_by_user() {
  1664. global $USER;
  1665. // We need to be able to explore the repository.
  1666. try {
  1667. $this->check_capability();
  1668. } catch (repository_exception $e) {
  1669. return false;
  1670. }
  1671. $repocontext = context::instance_by_id($this->instance->contextid);
  1672. if ($repocontext->contextlevel == CONTEXT_USER && $repocontext->instanceid != $USER->id) {
  1673. // If the context of this instance is a user context, we need to be this user.
  1674. return false;
  1675. } else if ($repocontext->contextlevel == CONTEXT_MODULE && !has_capability('moodle/course:update', $repocontext)) {
  1676. // We need to have permissions on the course to edit the instance.
  1677. return false;
  1678. } else if ($repocontext->contextlevel == CONTEXT_SYSTEM && !has_capability('moodle/site:config', $repocontext)) {
  1679. // Do not meet the requirements for the context system.
  1680. return false;
  1681. }
  1682. return true;
  1683. }
  1684. /**
  1685. * Return the name of this instance, can be overridden.
  1686. *
  1687. * @return string
  1688. */
  1689. public function get_name() {
  1690. if ($name = $this->instance->name) {
  1691. return $name;
  1692. } else {
  1693. return get_string('pluginname', 'repository_' . $this->get_typename());
  1694. }
  1695. }
  1696. /**
  1697. * Is this repository accessing private data?
  1698. *
  1699. * This function should return true for the repositories which access external private
  1700. * data from a user. This is the case for repositories such as Dropbox, Google Docs or Box.net
  1701. * which authenticate the user and then store the auth token.
  1702. *
  1703. * Of course, many repositories store 'private data', but we only want to set
  1704. * contains_private_data() to repositories which are external to Moodle and shouldn't be accessed
  1705. * to by the users having the capability to 'login as' someone else. For instance, the repository
  1706. * 'Private files' is not considered as private because it's part of Moodle.
  1707. *
  1708. * You should not set contains_private_data() to true on repositories which allow different types
  1709. * of instances as the levels other than 'user' are, by definition, not private. Also
  1710. * the user instances will be protected when they need to.
  1711. *
  1712. * @return boolean True when the repository accesses private external data.
  1713. * @since Moodle 2.5
  1714. */
  1715. public function contains_private_data() {
  1716. return true;
  1717. }
  1718. /**
  1719. * What kind of files will be in this repository?
  1720. *
  1721. * @return array return '*' means this repository support any files, otherwise
  1722. * return mimetypes of files, it can be an array
  1723. */
  1724. public function supported_filetypes() {
  1725. // return array('text/plain', 'image/gif');
  1726. return '*';
  1727. }
  1728. /**
  1729. * Tells how the file can be picked from this repository
  1730. *
  1731. * Maximum value is FILE_INTERNAL | FILE_EXTERNAL | FILE_REFERENCE
  1732. *
  1733. * @return int
  1734. */
  1735. public function supported_returntypes() {
  1736. return (FILE_INTERNAL | FILE_EXTERNAL);
  1737. }
  1738. /**
  1739. * Tells how the file can be picked from this repository
  1740. *
  1741. * Maximum value is FILE_INTERNAL | FILE_EXTERNAL | FILE_REFERENCE
  1742. *
  1743. * @return int
  1744. */
  1745. public function default_returntype() {
  1746. return FILE_INTERNAL;
  1747. }
  1748. /**
  1749. * Provide repository instance information for Ajax
  1750. *
  1751. * @return stdClass
  1752. */
  1753. final public function get_meta() {
  1754. global $CFG, $OUTPUT;
  1755. $meta = new stdClass();
  1756. $meta->id = $this->id;
  1757. $meta->name = format_string($this->get_name());
  1758. $meta->type = $this->get_typename();
  1759. $meta->icon = $OUTPUT->image_url('icon', 'repository_'.$meta->type)->out(false);
  1760. $meta->supported_types = file_get_typegroup('extension', $this->supported_filetypes());
  1761. $meta->return_types = $this->supported_returntypes();
  1762. $meta->defaultreturntype = $this->default_returntype();
  1763. $meta->sortorder = $this->options['sortorder'];
  1764. return $meta;
  1765. }
  1766. /**
  1767. * Create an instance for this plug-in
  1768. *
  1769. * @static
  1770. * @param string $type the type of the repository
  1771. * @param int $userid the user id
  1772. * @param stdClass $context the context
  1773. * @param array $params the options for this instance
  1774. * @param int $readonly whether to create it readonly or not (defaults to not)
  1775. * @return mixed
  1776. */
  1777. public static function create($type, $userid, $context, $params, $readonly=0) {
  1778. global $CFG, $DB;
  1779. $params = (array)$params;
  1780. require_once($CFG->dirroot . '/repository/'. $type . '/lib.php');
  1781. $classname = 'repository_' . $type;
  1782. if ($repo = $DB->get_record('repository', array('type'=>$type))) {
  1783. $record = new stdClass();
  1784. $record->name = $params['name'];
  1785. $record->typeid = $repo->id;
  1786. $record->timecreated = time();
  1787. $record->timemodified = time();
  1788. $record->contextid = $context->id;
  1789. $record->readonly = $readonly;
  1790. $record->userid = $userid;
  1791. $id = $DB->insert_record('repository_instances', $record);
  1792. cache::make('core', 'repositories')->purge();
  1793. $options = array();
  1794. $configs = call_user_func($classname . '::get_instance_option_names');
  1795. if (!empty($configs)) {
  1796. foreach ($configs as $config) {
  1797. if (isset($params[$config])) {
  1798. $options[$config] = $params[$config];
  1799. } else {
  1800. $options[$config] = null;
  1801. }
  1802. }
  1803. }
  1804. if (!empty($id)) {
  1805. unset($options['name']);
  1806. $instance = repository::get_instance($id);
  1807. $instance->set_option($options);
  1808. return $id;
  1809. } else {
  1810. return null;
  1811. }
  1812. } else {
  1813. return null;
  1814. }
  1815. }
  1816. /**
  1817. * delete a repository instance
  1818. *
  1819. * @param bool $downloadcontents
  1820. * @return bool
  1821. */
  1822. final public function delete($downloadcontents = false) {
  1823. global $DB;
  1824. if ($downloadcontents) {
  1825. $this->convert_references_to_local();
  1826. } else {
  1827. $this->remove_files();
  1828. }
  1829. cache::make('core', 'repositories')->purge();
  1830. try {
  1831. $DB->delete_records('repository_instances', array('id'=>$this->id));
  1832. $DB->delete_records('repository_instance_config', array('instanceid'=>$this->id));
  1833. } catch (dml_exception $ex) {
  1834. return false;
  1835. }
  1836. return true;
  1837. }
  1838. /**
  1839. * Delete all the instances associated to a context.
  1840. *
  1841. * This method is intended to be a callback when deleting
  1842. * a course or a user to delete all the instances associated
  1843. * to their context. The usual way to delete a single instance
  1844. * is to use {@link self::delete()}.
  1845. *
  1846. * @param int $contextid context ID.
  1847. * @param boolean $downloadcontents true to convert references to hard copies.
  1848. * @return void
  1849. */
  1850. final public static function delete_all_for_context($contextid, $downloadcontents = true) {
  1851. global $DB;
  1852. $repoids = $DB->get_fieldset_select('repository_instances', 'id', 'contextid = :contextid', array('contextid' => $contextid));
  1853. if ($downloadcontents) {
  1854. foreach ($repoids as $repoid) {
  1855. $repo = repository::get_repository_by_id($repoid, $contextid);
  1856. $repo->convert_references_to_local();
  1857. }
  1858. }
  1859. cache::make('core', 'repositories')->purge();
  1860. $DB->delete_records_list('repository_instances', 'id', $repoids);
  1861. $DB->delete_records_list('repository_instance_config', 'instanceid', $repoids);
  1862. }
  1863. /**
  1864. * Hide/Show a repository
  1865. *
  1866. * @param string $hide
  1867. * @return bool
  1868. */
  1869. final public function hide($hide = 'toggle') {
  1870. global $DB;
  1871. if ($entry = $DB->get_record('repository', array('id'=>$this->id))) {
  1872. if ($hide === 'toggle' ) {
  1873. if (!empty($entry->visible)) {
  1874. $entry->visible = 0;
  1875. } else {
  1876. $entry->visible = 1;
  1877. }
  1878. } else {
  1879. if (!empty($hide)) {
  1880. $entry->visible = 0;
  1881. } else {
  1882. $entry->visible = 1;
  1883. }
  1884. }
  1885. return $DB->update_record('repository', $entry);
  1886. }
  1887. return false;
  1888. }
  1889. /**
  1890. * Save settings for repository instance
  1891. * $repo->set_option(array('api_key'=>'f2188bde132', 'name'=>'dongsheng'));
  1892. *
  1893. * @param array $options settings
  1894. * @return bool
  1895. */
  1896. public function set_option($options = array()) {
  1897. global $DB;
  1898. if (!empty($options['name'])) {
  1899. $r = new stdClass();
  1900. $r->id = $this->id;
  1901. $r->name = $options['name'];
  1902. $DB->update_record('repository_instances', $r);
  1903. unset($options['name']);
  1904. }
  1905. foreach ($options as $name=>$value) {
  1906. if ($id = $DB->get_field('repository_instance_config', 'id', array('name'=>$name, 'instanceid'=>$this->id))) {
  1907. $DB->set_field('repository_instance_config', 'value', $value, array('id'=>$id));
  1908. } else {
  1909. $config = new stdClass();
  1910. $config->instanceid = $this->id;
  1911. $config->name = $name;
  1912. $config->value = $value;
  1913. $DB->insert_record('repository_instance_config', $config);
  1914. }
  1915. }
  1916. cache::make('core', 'repositories')->purge();
  1917. return true;
  1918. }
  1919. /**
  1920. * Get settings for repository instance.
  1921. *
  1922. * @param string $config a specific option to get.
  1923. * @return mixed returns an array of options. If $config is not empty, then it returns that option,
  1924. * or null if the option does not exist.
  1925. */
  1926. public function get_option($config = '') {
  1927. global $DB;
  1928. $cache = cache::make('core', 'repositories');
  1929. if (($entries = $cache->get('ops:'. $this->id)) === false) {
  1930. $entries = $DB->get_records('repository_instance_config', array('instanceid' => $this->id));
  1931. $cache->set('ops:'. $this->id, $entries);
  1932. }
  1933. $ret = array();
  1934. foreach($entries as $entry) {
  1935. $ret[$entry->name] = $entry->value;
  1936. }
  1937. if (!empty($config)) {
  1938. if (isset($ret[$config])) {
  1939. return $ret[$config];
  1940. } else {
  1941. return null;
  1942. }
  1943. } else {
  1944. return $ret;
  1945. }
  1946. }
  1947. /**
  1948. * Filter file listing to display specific types
  1949. *
  1950. * @param array $value
  1951. * @return bool
  1952. */
  1953. public function filter(&$value) {
  1954. $accepted_types = optional_param_array('accepted_types', '', PARAM_RAW);
  1955. if (isset($value['children'])) {
  1956. if (!empty($value['children'])) {
  1957. $value['children'] = array_filter($value['children'], array($this, 'filter'));
  1958. }
  1959. return true; // always return directories
  1960. } else {
  1961. if ($accepted_types == '*' or empty($accepted_types)
  1962. or (is_array($accepted_types) and in_array('*', $accepted_types))) {
  1963. return true;
  1964. } else {
  1965. foreach ($accepted_types as $ext) {
  1966. if (preg_match('#'.$ext.'$#i', $value['title'])) {
  1967. return true;
  1968. }
  1969. }
  1970. }
  1971. }
  1972. return false;
  1973. }
  1974. /**
  1975. * Given a path, and perhaps a search, get a list of files.
  1976. *
  1977. * See details on {@link http://docs.moodle.org/dev/Repository_plugins}
  1978. *
  1979. * @param string $path this parameter can a folder name, or a identification of folder
  1980. * @param string $page the page number of file list
  1981. * @return array the list of files, including meta infomation, containing the following keys
  1982. * manage, url to manage url
  1983. * client_id
  1984. * login, login form
  1985. * repo_id, active repository id
  1986. * login_btn_action, the login button action
  1987. * login_btn_label, the login button label
  1988. * total, number of results
  1989. * perpage, items per page
  1990. * page
  1991. * pages, total pages
  1992. * issearchresult, is it a search result?
  1993. * list, file list
  1994. * path, current path and parent path
  1995. */
  1996. public function get_listing($path = '', $page = '') {
  1997. }
  1998. /**
  1999. * Prepare the breadcrumb.
  2000. *
  2001. * @param array $breadcrumb contains each element of the breadcrumb.
  2002. * @return array of breadcrumb elements.
  2003. * @since Moodle 2.3.3
  2004. */
  2005. protected static function prepare_breadcrumb($breadcrumb) {
  2006. global $OUTPUT;
  2007. $foldericon = $OUTPUT->image_url(file_folder_icon(24))->out(false);
  2008. $len = count($breadcrumb);
  2009. for ($i = 0; $i < $len; $i++) {
  2010. if (is_array($breadcrumb[$i]) && !isset($breadcrumb[$i]['icon'])) {
  2011. $breadcrumb[$i]['icon'] = $foldericon;
  2012. } else if (is_object($breadcrumb[$i]) && !isset($breadcrumb[$i]->icon)) {
  2013. $breadcrumb[$i]->icon = $foldericon;
  2014. }
  2015. }
  2016. return $breadcrumb;
  2017. }
  2018. /**
  2019. * Prepare the file/folder listing.
  2020. *
  2021. * @param array $list of files and folders.
  2022. * @return array of files and folders.
  2023. * @since Moodle 2.3.3
  2024. */
  2025. protected static function prepare_list($list) {
  2026. global $OUTPUT;
  2027. $foldericon = $OUTPUT->image_url(file_folder_icon(24))->out(false);
  2028. // Reset the array keys because non-numeric keys will create an object when converted to JSON.
  2029. $list = array_values($list);
  2030. $len = count($list);
  2031. for ($i = 0; $i < $len; $i++) {
  2032. if (is_object($list[$i])) {
  2033. $file = (array)$list[$i];
  2034. $converttoobject = true;
  2035. } else {
  2036. $file =& $list[$i];
  2037. $converttoobject = false;
  2038. }
  2039. if (isset($file['source'])) {
  2040. $file['sourcekey'] = sha1($file['source'] . self::get_secret_key() . sesskey());
  2041. }
  2042. if (isset($file['size'])) {
  2043. $file['size'] = (int)$file['size'];
  2044. $file['size_f'] = display_size($file['size']);
  2045. }
  2046. if (isset($file['license']) && get_string_manager()->string_exists($file['license'], 'license')) {
  2047. $file['license_f'] = get_string($file['license'], 'license');
  2048. }
  2049. if (isset($file['image_width']) && isset($file['image_height'])) {
  2050. $a = array('width' => $file['image_width'], 'height' => $file['image_height']);
  2051. $file['dimensions'] = get_string('imagesize', 'repository', (object)$a);
  2052. }
  2053. foreach (array('date', 'datemodified', 'datecreated') as $key) {
  2054. if (!isset($file[$key]) && isset($file['date'])) {
  2055. $file[$key] = $file['date'];
  2056. }
  2057. if (isset($file[$key])) {
  2058. // must be UNIX timestamp
  2059. $file[$key] = (int)$file[$key];
  2060. if (!$file[$key]) {
  2061. unset($file[$key]);
  2062. } else {
  2063. $file[$key.'_f'] = userdate($file[$key], get_string('strftimedatetime', 'langconfig'));
  2064. $file[$key.'_f_s'] = userdate($file[$key], get_string('strftimedatetimeshort', 'langconfig'));
  2065. }
  2066. }
  2067. }
  2068. $isfolder = (array_key_exists('children', $file) || (isset($file['type']) && $file['type'] == 'folder'));
  2069. $filename = null;
  2070. if (isset($file['title'])) {
  2071. $filename = $file['title'];
  2072. }
  2073. else if (isset($file['fullname'])) {
  2074. $filename = $file['fullname'];
  2075. }
  2076. if (!isset($file['mimetype']) && !$isfolder && $filename) {
  2077. $file['mimetype'] = get_mimetype_description(array('filename' => $filename));
  2078. }
  2079. if (!isset($file['icon'])) {
  2080. if ($isfolder) {
  2081. $file['icon'] = $foldericon;
  2082. } else if ($filename) {
  2083. $file['icon'] = $OUTPUT->image_url(file_extension_icon($filename, 24))->out(false);
  2084. }
  2085. }
  2086. // Recursively loop over children.
  2087. if (isset($file['children'])) {
  2088. $file['children'] = self::prepare_list($file['children']);
  2089. }
  2090. // Convert the array back to an object.
  2091. if ($converttoobject) {
  2092. $list[$i] = (object)$file;
  2093. }
  2094. }
  2095. return $list;
  2096. }
  2097. /**
  2098. * Prepares list of files before passing it to AJAX, makes sure data is in the correct
  2099. * format and stores formatted values.
  2100. *
  2101. * @param array|stdClass $listing result of get_listing() or search() or file_get_drafarea_files()
  2102. * @return array
  2103. */
  2104. public static function prepare_listing($listing) {
  2105. $wasobject = false;
  2106. if (is_object($listing)) {
  2107. $listing = (array) $listing;
  2108. $wasobject = true;
  2109. }
  2110. // Prepare the breadcrumb, passed as 'path'.
  2111. if (isset($listing['path']) && is_array($listing['path'])) {
  2112. $listing['path'] = self::prepare_breadcrumb($listing['path']);
  2113. }
  2114. // Prepare the listing of objects.
  2115. if (isset($listing['list']) && is_array($listing['list'])) {
  2116. $listing['list'] = self::prepare_list($listing['list']);
  2117. }
  2118. // Convert back to an object.
  2119. if ($wasobject) {
  2120. $listing = (object) $listing;
  2121. }
  2122. return $listing;
  2123. }
  2124. /**
  2125. * Search files in repository
  2126. * When doing global search, $search_text will be used as
  2127. * keyword.
  2128. *
  2129. * @param string $search_text search key word
  2130. * @param int $page page
  2131. * @return mixed see {@link repository::get_listing()}
  2132. */
  2133. public function search($search_text, $page = 0) {
  2134. $list = array();
  2135. $list['list'] = array();
  2136. return false;
  2137. }
  2138. /**
  2139. * Logout from repository instance
  2140. * By default, this function will return a login form
  2141. *
  2142. * @return string
  2143. */
  2144. public function logout(){
  2145. return $this->print_login();
  2146. }
  2147. /**
  2148. * To check whether the user is logged in.
  2149. *
  2150. * @return bool
  2151. */
  2152. public function check_login(){
  2153. return true;
  2154. }
  2155. /**
  2156. * Show the login screen, if required
  2157. *
  2158. * @return string
  2159. */
  2160. public function print_login(){
  2161. return $this->get_listing();
  2162. }
  2163. /**
  2164. * Show the search screen, if required
  2165. *
  2166. * @return string
  2167. */
  2168. public function print_search() {
  2169. global $PAGE;
  2170. $renderer = $PAGE->get_renderer('core', 'files');
  2171. return $renderer->repository_default_searchform();
  2172. }
  2173. /**
  2174. * For oauth like external authentication, when external repository direct user back to moodle,
  2175. * this function will be called to set up token and token_secret
  2176. */
  2177. public function callback() {
  2178. }
  2179. /**
  2180. * is it possible to do glboal search?
  2181. *
  2182. * @return bool
  2183. */
  2184. public function global_search() {
  2185. return false;
  2186. }
  2187. /**
  2188. * Defines operations that happen occasionally on cron
  2189. *
  2190. * @return bool
  2191. */
  2192. public function cron() {
  2193. return true;
  2194. }
  2195. /**
  2196. * function which is run when the type is created (moodle administrator add the plugin)
  2197. *
  2198. * @return bool success or fail?
  2199. */
  2200. public static function plugin_init() {
  2201. return true;
  2202. }
  2203. /**
  2204. * Edit/Create Admin Settings Moodle form
  2205. *
  2206. * @param moodleform $mform Moodle form (passed by reference)
  2207. * @param string $classname repository class name
  2208. */
  2209. public static function type_config_form($mform, $classname = 'repository') {
  2210. $instnaceoptions = call_user_func(array($classname, 'get_instance_option_names'), $mform, $classname);
  2211. if (empty($instnaceoptions)) {
  2212. // this plugin has only one instance
  2213. // so we need to give it a name
  2214. // it can be empty, then moodle will look for instance name from language string
  2215. $mform->addElement('text', 'pluginname', get_string('pluginname', 'repository'), array('size' => '40'));
  2216. $mform->addElement('static', 'pluginnamehelp', '', get_string('pluginnamehelp', 'repository'));
  2217. $mform->setType('pluginname', PARAM_TEXT);
  2218. }
  2219. }
  2220. /**
  2221. * Validate Admin Settings Moodle form
  2222. *
  2223. * @static
  2224. * @param moodleform $mform Moodle form (passed by reference)
  2225. * @param array $data array of ("fieldname"=>value) of submitted data
  2226. * @param array $errors array of ("fieldname"=>errormessage) of errors
  2227. * @return array array of errors
  2228. */
  2229. public static function type_form_validation($mform, $data, $errors) {
  2230. return $errors;
  2231. }
  2232. /**
  2233. * Edit/Create Instance Settings Moodle form
  2234. *
  2235. * @param moodleform $mform Moodle form (passed by reference)
  2236. */
  2237. public static function instance_config_form($mform) {
  2238. }
  2239. /**
  2240. * Return names of the general options.
  2241. * By default: no general option name
  2242. *
  2243. * @return array
  2244. */
  2245. public static function get_type_option_names() {
  2246. return array('pluginname');
  2247. }
  2248. /**
  2249. * Return names of the instance options.
  2250. * By default: no instance option name
  2251. *
  2252. * @return array
  2253. */
  2254. public static function get_instance_option_names() {
  2255. return array();
  2256. }
  2257. /**
  2258. * Validate repository plugin instance form
  2259. *
  2260. * @param moodleform $mform moodle form
  2261. * @param array $data form data
  2262. * @param array $errors errors
  2263. * @return array errors
  2264. */
  2265. public static function instance_form_validation($mform, $data, $errors) {
  2266. return $errors;
  2267. }
  2268. /**
  2269. * Create a shorten filename
  2270. *
  2271. * @param string $str filename
  2272. * @param int $maxlength max file name length
  2273. * @return string short filename
  2274. */
  2275. public function get_short_filename($str, $maxlength) {
  2276. if (core_text::strlen($str) >= $maxlength) {
  2277. return trim(core_text::substr($str, 0, $maxlength)).'...';
  2278. } else {
  2279. return $str;
  2280. }
  2281. }
  2282. /**
  2283. * Overwrite an existing file
  2284. *
  2285. * @param int $itemid
  2286. * @param string $filepath
  2287. * @param string $filename
  2288. * @param string $newfilepath
  2289. * @param string $newfilename
  2290. * @return bool
  2291. */
  2292. public static function overwrite_existing_draftfile($itemid, $filepath, $filename, $newfilepath, $newfilename) {
  2293. global $USER;
  2294. $fs = get_file_storage();
  2295. $user_context = context_user::instance($USER->id);
  2296. if ($file = $fs->get_file($user_context->id, 'user', 'draft', $itemid, $filepath, $filename)) {
  2297. if ($tempfile = $fs->get_file($user_context->id, 'user', 'draft', $itemid, $newfilepath, $newfilename)) {
  2298. // Remember original file source field.
  2299. $source = @unserialize($file->get_source());
  2300. // Remember the original sortorder.
  2301. $sortorder = $file->get_sortorder();
  2302. if ($tempfile->is_external_file()) {
  2303. // New file is a reference. Check that existing file does not have any other files referencing to it
  2304. if (isset($source->original) && $fs->search_references_count($source->original)) {
  2305. return (object)array('error' => get_string('errordoublereference', 'repository'));
  2306. }
  2307. }
  2308. // delete existing file to release filename
  2309. $file->delete();
  2310. // create new file
  2311. $newfile = $fs->create_file_from_storedfile(array('filepath'=>$filepath, 'filename'=>$filename), $tempfile);
  2312. // Preserve original file location (stored in source field) for handling references
  2313. if (isset($source->original)) {
  2314. if (!($newfilesource = @unserialize($newfile->get_source()))) {
  2315. $newfilesource = new stdClass();
  2316. }
  2317. $newfilesource->original = $source->original;
  2318. $newfile->set_source(serialize($newfilesource));
  2319. }
  2320. $newfile->set_sortorder($sortorder);
  2321. // remove temp file
  2322. $tempfile->delete();
  2323. return true;
  2324. }
  2325. }
  2326. return false;
  2327. }
  2328. /**
  2329. * Updates a file in draft filearea.
  2330. *
  2331. * This function can only update fields filepath, filename, author, license.
  2332. * If anything (except filepath) is updated, timemodified is set to current time.
  2333. * If filename or filepath is updated the file unconnects from it's origin
  2334. * and therefore all references to it will be converted to copies when
  2335. * filearea is saved.
  2336. *
  2337. * @param int $draftid
  2338. * @param string $filepath path to the directory containing the file, or full path in case of directory
  2339. * @param string $filename name of the file, or '.' in case of directory
  2340. * @param array $updatedata array of fields to change (only filename, filepath, license and/or author can be updated)
  2341. * @throws moodle_exception if for any reason file can not be updated (file does not exist, target already exists, etc.)
  2342. */
  2343. public static function update_draftfile($draftid, $filepath, $filename, $updatedata) {
  2344. global $USER;
  2345. $fs = get_file_storage();
  2346. $usercontext = context_user::instance($USER->id);
  2347. // make sure filename and filepath are present in $updatedata
  2348. $updatedata = $updatedata + array('filepath' => $filepath, 'filename' => $filename);
  2349. $filemodified = false;
  2350. if (!$file = $fs->get_file($usercontext->id, 'user', 'draft', $draftid, $filepath, $filename)) {
  2351. if ($filename === '.') {
  2352. throw new moodle_exception('foldernotfound', 'repository');
  2353. } else {
  2354. throw new moodle_exception('filenotfound', 'error');
  2355. }
  2356. }
  2357. if (!$file->is_directory()) {
  2358. // This is a file
  2359. if ($updatedata['filepath'] !== $filepath || $updatedata['filename'] !== $filename) {
  2360. // Rename/move file: check that target file name does not exist.
  2361. if ($fs->file_exists($usercontext->id, 'user', 'draft', $draftid, $updatedata['filepath'], $updatedata['filename'])) {
  2362. throw new moodle_exception('fileexists', 'repository');
  2363. }
  2364. if (($filesource = @unserialize($file->get_source())) && isset($filesource->original)) {
  2365. unset($filesource->original);
  2366. $file->set_source(serialize($filesource));
  2367. }
  2368. $file->rename($updatedata['filepath'], $updatedata['filename']);
  2369. // timemodified is updated only when file is renamed and not updated when file is moved.
  2370. $filemodified = $filemodified || ($updatedata['filename'] !== $filename);
  2371. }
  2372. if (array_key_exists('license', $updatedata) && $updatedata['license'] !== $file->get_license()) {
  2373. // Update license and timemodified.
  2374. $file->set_license($updatedata['license']);
  2375. $filemodified = true;
  2376. }
  2377. if (array_key_exists('author', $updatedata) && $updatedata['author'] !== $file->get_author()) {
  2378. // Update author and timemodified.
  2379. $file->set_author($updatedata['author']);
  2380. $filemodified = true;
  2381. }
  2382. // Update timemodified:
  2383. if ($filemodified) {
  2384. $file->set_timemodified(time());
  2385. }
  2386. } else {
  2387. // This is a directory - only filepath can be updated for a directory (it was moved).
  2388. if ($updatedata['filepath'] === $filepath) {
  2389. // nothing to update
  2390. return;
  2391. }
  2392. if ($fs->file_exists($usercontext->id, 'user', 'draft', $draftid, $updatedata['filepath'], '.')) {
  2393. // bad luck, we can not rename if something already exists there
  2394. throw new moodle_exception('folderexists', 'repository');
  2395. }
  2396. $xfilepath = preg_quote($filepath, '|');
  2397. if (preg_match("|^$xfilepath|", $updatedata['filepath'])) {
  2398. // we can not move folder to it's own subfolder
  2399. throw new moodle_exception('folderrecurse', 'repository');
  2400. }
  2401. // If directory changed the name, update timemodified.
  2402. $filemodified = (basename(rtrim($file->get_filepath(), '/')) !== basename(rtrim($updatedata['filepath'], '/')));
  2403. // Now update directory and all children.
  2404. $files = $fs->get_area_files($usercontext->id, 'user', 'draft', $draftid);
  2405. foreach ($files as $f) {
  2406. if (preg_match("|^$xfilepath|", $f->get_filepath())) {
  2407. $path = preg_replace("|^$xfilepath|", $updatedata['filepath'], $f->get_filepath());
  2408. if (($filesource = @unserialize($f->get_source())) && isset($filesource->original)) {
  2409. // unset original so the references are not shown any more
  2410. unset($filesource->original);
  2411. $f->set_source(serialize($filesource));
  2412. }
  2413. $f->rename($path, $f->get_filename());
  2414. if ($filemodified && $f->get_filepath() === $updatedata['filepath'] && $f->get_filename() === $filename) {
  2415. $f->set_timemodified(time());
  2416. }
  2417. }
  2418. }
  2419. }
  2420. }
  2421. /**
  2422. * Delete a temp file from draft area
  2423. *
  2424. * @param int $draftitemid
  2425. * @param string $filepath
  2426. * @param string $filename
  2427. * @return bool
  2428. */
  2429. public static function delete_tempfile_from_draft($draftitemid, $filepath, $filename) {
  2430. global $USER;
  2431. $fs = get_file_storage();
  2432. $user_context = context_user::instance($USER->id);
  2433. if ($file = $fs->get_file($user_context->id, 'user', 'draft', $draftitemid, $filepath, $filename)) {
  2434. $file->delete();
  2435. return true;
  2436. } else {
  2437. return false;
  2438. }
  2439. }
  2440. /**
  2441. * Find all external files in this repo and import them
  2442. */
  2443. public function convert_references_to_local() {
  2444. $fs = get_file_storage();
  2445. $files = $fs->get_external_files($this->id);
  2446. foreach ($files as $storedfile) {
  2447. $fs->import_external_file($storedfile);
  2448. }
  2449. }
  2450. /**
  2451. * Find all external files linked to this repository and delete them.
  2452. */
  2453. public function remove_files() {
  2454. $fs = get_file_storage();
  2455. $files = $fs->get_external_files($this->id);
  2456. foreach ($files as $storedfile) {
  2457. $storedfile->delete();
  2458. }
  2459. }
  2460. /**
  2461. * Function repository::reset_caches() is deprecated, cache is handled by MUC now.
  2462. * @deprecated since Moodle 2.6 MDL-42016 - please do not use this function any more.
  2463. */
  2464. public static function reset_caches() {
  2465. throw new coding_exception('Function repository::reset_caches() can not be used any more, cache is handled by MUC now.');
  2466. }
  2467. /**
  2468. * Function repository::sync_external_file() is deprecated. Use repository::sync_reference instead
  2469. *
  2470. * @deprecated since Moodle 2.6 MDL-42016 - please do not use this function any more.
  2471. * @see repository::sync_reference()
  2472. */
  2473. public static function sync_external_file($file, $resetsynchistory = false) {
  2474. throw new coding_exception('Function repository::sync_external_file() can not be used any more. ' .
  2475. 'Use repository::sync_reference instead.');
  2476. }
  2477. /**
  2478. * Performs synchronisation of an external file if the previous one has expired.
  2479. *
  2480. * This function must be implemented for external repositories supporting
  2481. * FILE_REFERENCE, it is called for existing aliases when their filesize,
  2482. * contenthash or timemodified are requested. It is not called for internal
  2483. * repositories (see {@link repository::has_moodle_files()}), references to
  2484. * internal files are updated immediately when source is modified.
  2485. *
  2486. * Referenced files may optionally keep their content in Moodle filepool (for
  2487. * thumbnail generation or to be able to serve cached copy). In this
  2488. * case both contenthash and filesize need to be synchronized. Otherwise repositories
  2489. * should use contenthash of empty file and correct filesize in bytes.
  2490. *
  2491. * Note that this function may be run for EACH file that needs to be synchronised at the
  2492. * moment. If anything is being downloaded or requested from external sources there
  2493. * should be a small timeout. The synchronisation is performed to update the size of
  2494. * the file and/or to update image and re-generated image preview. There is nothing
  2495. * fatal if syncronisation fails but it is fatal if syncronisation takes too long
  2496. * and hangs the script generating a page.
  2497. *
  2498. * Note: If you wish to call $file->get_filesize(), $file->get_contenthash() or
  2499. * $file->get_timemodified() make sure that recursion does not happen.
  2500. *
  2501. * Called from {@link stored_file::sync_external_file()}
  2502. *
  2503. * @uses stored_file::set_missingsource()
  2504. * @uses stored_file::set_synchronized()
  2505. * @param stored_file $file
  2506. * @return bool false when file does not need synchronisation, true if it was synchronised
  2507. */
  2508. public function sync_reference(stored_file $file) {
  2509. if ($file->get_repository_id() != $this->id) {
  2510. // This should not really happen because the function can be called from stored_file only.
  2511. return false;
  2512. }
  2513. if ($this->has_moodle_files()) {
  2514. // References to local files need to be synchronised only once.
  2515. // Later they will be synchronised automatically when the source is changed.
  2516. if ($file->get_referencelastsync()) {
  2517. return false;
  2518. }
  2519. $fs = get_file_storage();
  2520. $params = file_storage::unpack_reference($file->get_reference(), true);
  2521. if (!is_array($params) || !($storedfile = $fs->get_file($params['contextid'],
  2522. $params['component'], $params['filearea'], $params['itemid'], $params['filepath'],
  2523. $params['filename']))) {
  2524. $file->set_missingsource();
  2525. } else {
  2526. $file->set_synchronized($storedfile->get_contenthash(), $storedfile->get_filesize(), 0, $storedfile->get_timemodified());
  2527. }
  2528. return true;
  2529. }
  2530. return false;
  2531. }
  2532. /**
  2533. * Build draft file's source field
  2534. *
  2535. * {@link file_restore_source_field_from_draft_file()}
  2536. * XXX: This is a hack for file manager (MDL-28666)
  2537. * For newly created draft files we have to construct
  2538. * source filed in php serialized data format.
  2539. * File manager needs to know the original file information before copying
  2540. * to draft area, so we append these information in mdl_files.source field
  2541. *
  2542. * @param string $source
  2543. * @return string serialised source field
  2544. */
  2545. public static function build_source_field($source) {
  2546. $sourcefield = new stdClass;
  2547. $sourcefield->source = $source;
  2548. return serialize($sourcefield);
  2549. }
  2550. /**
  2551. * Prepares the repository to be cached. Implements method from cacheable_object interface.
  2552. *
  2553. * @return array
  2554. */
  2555. public function prepare_to_cache() {
  2556. return array(
  2557. 'class' => get_class($this),
  2558. 'id' => $this->id,
  2559. 'ctxid' => $this->context->id,
  2560. 'options' => $this->options,
  2561. 'readonly' => $this->readonly
  2562. );
  2563. }
  2564. /**
  2565. * Restores the repository from cache. Implements method from cacheable_object interface.
  2566. *
  2567. * @return array
  2568. */
  2569. public static function wake_from_cache($data) {
  2570. $classname = $data['class'];
  2571. return new $classname($data['id'], $data['ctxid'], $data['options'], $data['readonly']);
  2572. }
  2573. /**
  2574. * Gets a file relative to this file in the repository and sends it to the browser.
  2575. * Used to allow relative file linking within a repository without creating file records
  2576. * for linked files
  2577. *
  2578. * Repositories that overwrite this must be very careful - see filesystem repository for example.
  2579. *
  2580. * @param stored_file $mainfile The main file we are trying to access relative files for.
  2581. * @param string $relativepath the relative path to the file we are trying to access.
  2582. *
  2583. */
  2584. public function send_relative_file(stored_file $mainfile, $relativepath) {
  2585. // This repository hasn't implemented this so send_file_not_found.
  2586. send_file_not_found();
  2587. }
  2588. /**
  2589. * helper function to check if the repository supports send_relative_file.
  2590. *
  2591. * @return true|false
  2592. */
  2593. public function supports_relative_file() {
  2594. return false;
  2595. }
  2596. /**
  2597. * Helper function to indicate if this repository uses post requests for uploading files.
  2598. *
  2599. * @deprecated since Moodle 3.2, 3.1.1, 3.0.5
  2600. * @return bool
  2601. */
  2602. public function uses_post_requests() {
  2603. debugging('The method repository::uses_post_requests() is deprecated and must not be used anymore.', DEBUG_DEVELOPER);
  2604. return false;
  2605. }
  2606. /**
  2607. * Generate a secret key to be used for passing sensitive information around.
  2608. *
  2609. * @return string repository secret key.
  2610. */
  2611. final static public function get_secret_key() {
  2612. global $CFG;
  2613. if (!isset($CFG->reposecretkey)) {
  2614. set_config('reposecretkey', time() . random_string(32));
  2615. }
  2616. return $CFG->reposecretkey;
  2617. }
  2618. }
  2619. /**
  2620. * Exception class for repository api
  2621. *
  2622. * @since Moodle 2.0
  2623. * @package core_repository
  2624. * @copyright 2009 Dongsheng Cai {@link http://dongsheng.org}
  2625. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  2626. */
  2627. class repository_exception extends moodle_exception {
  2628. }
  2629. /**
  2630. * This is a class used to define a repository instance form
  2631. *
  2632. * @since Moodle 2.0
  2633. * @package core_repository
  2634. * @copyright 2009 Dongsheng Cai {@link http://dongsheng.org}
  2635. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  2636. */
  2637. final class repository_instance_form extends moodleform {
  2638. /** @var stdClass repository instance */
  2639. protected $instance;
  2640. /** @var string repository plugin type */
  2641. protected $plugin;
  2642. /**
  2643. * Added defaults to moodle form
  2644. */
  2645. protected function add_defaults() {
  2646. $mform =& $this->_form;
  2647. $strrequired = get_string('required');
  2648. $mform->addElement('hidden', 'edit', ($this->instance) ? $this->instance->id : 0);
  2649. $mform->setType('edit', PARAM_INT);
  2650. $mform->addElement('hidden', 'new', $this->plugin);
  2651. $mform->setType('new', PARAM_ALPHANUMEXT);
  2652. $mform->addElement('hidden', 'plugin', $this->plugin);
  2653. $mform->setType('plugin', PARAM_PLUGIN);
  2654. $mform->addElement('hidden', 'typeid', $this->typeid);
  2655. $mform->setType('typeid', PARAM_INT);
  2656. $mform->addElement('hidden', 'contextid', $this->contextid);
  2657. $mform->setType('contextid', PARAM_INT);
  2658. $mform->addElement('text', 'name', get_string('name'), 'maxlength="100" size="30"');
  2659. $mform->addRule('name', $strrequired, 'required', null, 'client');
  2660. $mform->setType('name', PARAM_TEXT);
  2661. }
  2662. /**
  2663. * Define moodle form elements
  2664. */
  2665. public function definition() {
  2666. global $CFG;
  2667. // type of plugin, string
  2668. $this->plugin = $this->_customdata['plugin'];
  2669. $this->typeid = $this->_customdata['typeid'];
  2670. $this->contextid = $this->_customdata['contextid'];
  2671. $this->instance = (isset($this->_customdata['instance'])
  2672. && is_subclass_of($this->_customdata['instance'], 'repository'))
  2673. ? $this->_customdata['instance'] : null;
  2674. $mform =& $this->_form;
  2675. $this->add_defaults();
  2676. // Add instance config options.
  2677. $result = repository::static_function($this->plugin, 'instance_config_form', $mform);
  2678. if ($result === false) {
  2679. // Remove the name element if no other config options.
  2680. $mform->removeElement('name');
  2681. }
  2682. if ($this->instance) {
  2683. $data = array();
  2684. $data['name'] = $this->instance->name;
  2685. if (!$this->instance->readonly) {
  2686. // and set the data if we have some.
  2687. foreach ($this->instance->get_instance_option_names() as $config) {
  2688. if (!empty($this->instance->options[$config])) {
  2689. $data[$config] = $this->instance->options[$config];
  2690. } else {
  2691. $data[$config] = '';
  2692. }
  2693. }
  2694. }
  2695. $this->set_data($data);
  2696. }
  2697. if ($result === false) {
  2698. $mform->addElement('cancel');
  2699. } else {
  2700. $this->add_action_buttons(true, get_string('save','repository'));
  2701. }
  2702. }
  2703. /**
  2704. * Validate moodle form data
  2705. *
  2706. * @param array $data form data
  2707. * @param array $files files in form
  2708. * @return array errors
  2709. */
  2710. public function validation($data, $files) {
  2711. global $DB;
  2712. $errors = array();
  2713. $plugin = $this->_customdata['plugin'];
  2714. $instance = (isset($this->_customdata['instance'])
  2715. && is_subclass_of($this->_customdata['instance'], 'repository'))
  2716. ? $this->_customdata['instance'] : null;
  2717. if (!$instance) {
  2718. $errors = repository::static_function($plugin, 'instance_form_validation', $this, $data, $errors);
  2719. } else {
  2720. $errors = $instance->instance_form_validation($this, $data, $errors);
  2721. }
  2722. $sql = "SELECT count('x')
  2723. FROM {repository_instances} i, {repository} r
  2724. WHERE r.type=:plugin AND r.id=i.typeid AND i.name=:name AND i.contextid=:contextid";
  2725. $params = array('name' => $data['name'], 'plugin' => $this->plugin, 'contextid' => $this->contextid);
  2726. if ($instance) {
  2727. $sql .= ' AND i.id != :instanceid';
  2728. $params['instanceid'] = $instance->id;
  2729. }
  2730. if ($DB->count_records_sql($sql, $params) > 0) {
  2731. $errors['name'] = get_string('erroruniquename', 'repository');
  2732. }
  2733. return $errors;
  2734. }
  2735. }
  2736. /**
  2737. * This is a class used to define a repository type setting form
  2738. *
  2739. * @since Moodle 2.0
  2740. * @package core_repository
  2741. * @copyright 2009 Dongsheng Cai {@link http://dongsheng.org}
  2742. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  2743. */
  2744. final class repository_type_form extends moodleform {
  2745. /** @var stdClass repository instance */
  2746. protected $instance;
  2747. /** @var string repository plugin name */
  2748. protected $plugin;
  2749. /** @var string action */
  2750. protected $action;
  2751. /**
  2752. * Definition of the moodleform
  2753. */
  2754. public function definition() {
  2755. global $CFG;
  2756. // type of plugin, string
  2757. $this->plugin = $this->_customdata['plugin'];
  2758. $this->instance = (isset($this->_customdata['instance'])
  2759. && is_a($this->_customdata['instance'], 'repository_type'))
  2760. ? $this->_customdata['instance'] : null;
  2761. $this->action = $this->_customdata['action'];
  2762. $this->pluginname = $this->_customdata['pluginname'];
  2763. $mform =& $this->_form;
  2764. $strrequired = get_string('required');
  2765. $mform->addElement('hidden', 'action', $this->action);
  2766. $mform->setType('action', PARAM_TEXT);
  2767. $mform->addElement('hidden', 'repos', $this->plugin);
  2768. $mform->setType('repos', PARAM_PLUGIN);
  2769. // let the plugin add its specific fields
  2770. $classname = 'repository_' . $this->plugin;
  2771. require_once($CFG->dirroot . '/repository/' . $this->plugin . '/lib.php');
  2772. //add "enable course/user instances" checkboxes if multiple instances are allowed
  2773. $instanceoptionnames = repository::static_function($this->plugin, 'get_instance_option_names');
  2774. $result = call_user_func(array($classname, 'type_config_form'), $mform, $classname);
  2775. if (!empty($instanceoptionnames)) {
  2776. $sm = get_string_manager();
  2777. $component = 'repository';
  2778. if ($sm->string_exists('enablecourseinstances', 'repository_' . $this->plugin)) {
  2779. $component .= ('_' . $this->plugin);
  2780. }
  2781. $mform->addElement('checkbox', 'enablecourseinstances', get_string('enablecourseinstances', $component));
  2782. $mform->setType('enablecourseinstances', PARAM_BOOL);
  2783. $component = 'repository';
  2784. if ($sm->string_exists('enableuserinstances', 'repository_' . $this->plugin)) {
  2785. $component .= ('_' . $this->plugin);
  2786. }
  2787. $mform->addElement('checkbox', 'enableuserinstances', get_string('enableuserinstances', $component));
  2788. $mform->setType('enableuserinstances', PARAM_BOOL);
  2789. }
  2790. // set the data if we have some.
  2791. if ($this->instance) {
  2792. $data = array();
  2793. $option_names = call_user_func(array($classname,'get_type_option_names'));
  2794. if (!empty($instanceoptionnames)){
  2795. $option_names[] = 'enablecourseinstances';
  2796. $option_names[] = 'enableuserinstances';
  2797. }
  2798. $instanceoptions = $this->instance->get_options();
  2799. foreach ($option_names as $config) {
  2800. if (!empty($instanceoptions[$config])) {
  2801. $data[$config] = $instanceoptions[$config];
  2802. } else {
  2803. $data[$config] = '';
  2804. }
  2805. }
  2806. // XXX: set plugin name for plugins which doesn't have muliti instances
  2807. if (empty($instanceoptionnames)){
  2808. $data['pluginname'] = $this->pluginname;
  2809. }
  2810. $this->set_data($data);
  2811. }
  2812. $this->add_action_buttons(true, get_string('save','repository'));
  2813. }
  2814. /**
  2815. * Validate moodle form data
  2816. *
  2817. * @param array $data moodle form data
  2818. * @param array $files
  2819. * @return array errors
  2820. */
  2821. public function validation($data, $files) {
  2822. $errors = array();
  2823. $plugin = $this->_customdata['plugin'];
  2824. $instance = (isset($this->_customdata['instance'])
  2825. && is_subclass_of($this->_customdata['instance'], 'repository'))
  2826. ? $this->_customdata['instance'] : null;
  2827. if (!$instance) {
  2828. $errors = repository::static_function($plugin, 'type_form_validation', $this, $data, $errors);
  2829. } else {
  2830. $errors = $instance->type_form_validation($this, $data, $errors);
  2831. }
  2832. return $errors;
  2833. }
  2834. }
  2835. /**
  2836. * Generate all options needed by filepicker
  2837. *
  2838. * @param array $args including following keys
  2839. * context
  2840. * accepted_types
  2841. * return_types
  2842. *
  2843. * @return array the list of repository instances, including meta infomation, containing the following keys
  2844. * externallink
  2845. * repositories
  2846. * accepted_types
  2847. */
  2848. function initialise_filepicker($args) {
  2849. global $CFG, $USER, $PAGE, $OUTPUT;
  2850. static $templatesinitialized = array();
  2851. require_once($CFG->libdir . '/licenselib.php');
  2852. $return = new stdClass();
  2853. $licenses = array();
  2854. if (!empty($CFG->licenses)) {
  2855. $array = explode(',', $CFG->licenses);
  2856. foreach ($array as $license) {
  2857. $l = new stdClass();
  2858. $l->shortname = $license;
  2859. $l->fullname = get_string($license, 'license');
  2860. $licenses[] = $l;
  2861. }
  2862. }
  2863. if (!empty($CFG->sitedefaultlicense)) {
  2864. $return->defaultlicense = $CFG->sitedefaultlicense;
  2865. }
  2866. $return->licenses = $licenses;
  2867. $return->author = fullname($USER);
  2868. if (empty($args->context)) {
  2869. $context = $PAGE->context;
  2870. } else {
  2871. $context = $args->context;
  2872. }
  2873. $disable_types = array();
  2874. if (!empty($args->disable_types)) {
  2875. $disable_types = $args->disable_types;
  2876. }
  2877. $user_context = context_user::instance($USER->id);
  2878. list($context, $course, $cm) = get_context_info_array($context->id);
  2879. $contexts = array($user_context, context_system::instance());
  2880. if (!empty($course)) {
  2881. // adding course context
  2882. $contexts[] = context_course::instance($course->id);
  2883. }
  2884. $externallink = (int)get_config(null, 'repositoryallowexternallinks');
  2885. $repositories = repository::get_instances(array(
  2886. 'context'=>$contexts,
  2887. 'currentcontext'=> $context,
  2888. 'accepted_types'=>$args->accepted_types,
  2889. 'return_types'=>$args->return_types,
  2890. 'disable_types'=>$disable_types
  2891. ));
  2892. $return->repositories = array();
  2893. if (empty($externallink)) {
  2894. $return->externallink = false;
  2895. } else {
  2896. $return->externallink = true;
  2897. }
  2898. $return->userprefs = array();
  2899. $return->userprefs['recentrepository'] = get_user_preferences('filepicker_recentrepository', '');
  2900. $return->userprefs['recentlicense'] = get_user_preferences('filepicker_recentlicense', '');
  2901. $return->userprefs['recentviewmode'] = get_user_preferences('filepicker_recentviewmode', '');
  2902. user_preference_allow_ajax_update('filepicker_recentrepository', PARAM_INT);
  2903. user_preference_allow_ajax_update('filepicker_recentlicense', PARAM_SAFEDIR);
  2904. user_preference_allow_ajax_update('filepicker_recentviewmode', PARAM_INT);
  2905. // provided by form element
  2906. $return->accepted_types = file_get_typegroup('extension', $args->accepted_types);
  2907. $return->return_types = $args->return_types;
  2908. $templates = array();
  2909. foreach ($repositories as $repository) {
  2910. $meta = $repository->get_meta();
  2911. // Please note that the array keys for repositories are used within
  2912. // JavaScript a lot, the key NEEDS to be the repository id.
  2913. $return->repositories[$repository->id] = $meta;
  2914. // Register custom repository template if it has one
  2915. if(method_exists($repository, 'get_upload_template') && !array_key_exists('uploadform_' . $meta->type, $templatesinitialized)) {
  2916. $templates['uploadform_' . $meta->type] = $repository->get_upload_template();
  2917. $templatesinitialized['uploadform_' . $meta->type] = true;
  2918. }
  2919. }
  2920. if (!array_key_exists('core', $templatesinitialized)) {
  2921. // we need to send each filepicker template to the browser just once
  2922. $fprenderer = $PAGE->get_renderer('core', 'files');
  2923. $templates = array_merge($templates, $fprenderer->filepicker_js_templates());
  2924. $templatesinitialized['core'] = true;
  2925. }
  2926. if (sizeof($templates)) {
  2927. $PAGE->requires->js_init_call('M.core_filepicker.set_templates', array($templates), true);
  2928. }
  2929. return $return;
  2930. }
  2931. /**
  2932. * Convenience function to handle deletion of files.
  2933. *
  2934. * @param object $context The context where the delete is called
  2935. * @param string $component component
  2936. * @param string $filearea filearea
  2937. * @param int $itemid the item id
  2938. * @param array $files Array of files object with each item having filename/filepath as values
  2939. * @return array $return Array of strings matching up to the parent directory of the deleted files
  2940. * @throws coding_exception
  2941. */
  2942. function repository_delete_selected_files($context, string $component, string $filearea, $itemid, array $files) {
  2943. $fs = get_file_storage();
  2944. $return = [];
  2945. foreach ($files as $selectedfile) {
  2946. $filename = clean_filename($selectedfile->filename);
  2947. $filepath = clean_param($selectedfile->filepath, PARAM_PATH);
  2948. $filepath = file_correct_filepath($filepath);
  2949. if ($storedfile = $fs->get_file($context->id, $component, $filearea, $itemid, $filepath, $filename)) {
  2950. $parentpath = $storedfile->get_parent_directory()->get_filepath();
  2951. if ($storedfile->is_directory()) {
  2952. $files = $fs->get_directory_files($context->id, $component, $filearea, $itemid, $filepath, true);
  2953. foreach ($files as $file) {
  2954. $file->delete();
  2955. }
  2956. $storedfile->delete();
  2957. $return[$parentpath] = "";
  2958. } else {
  2959. if ($result = $storedfile->delete()) {
  2960. $return[$parentpath] = "";
  2961. }
  2962. }
  2963. }
  2964. }
  2965. return $return;
  2966. }
  2967. /**
  2968. * Convenience function to handle deletion of files.
  2969. *
  2970. * @param object $context The context where the delete is called
  2971. * @param string $component component
  2972. * @param string $filearea filearea
  2973. * @param int $itemid the item id
  2974. * @param array $files Array of files object with each item having filename/filepath as values
  2975. * @return array $return Array of strings matching up to the parent directory of the deleted files
  2976. * @throws coding_exception
  2977. */
  2978. function repository_download_selected_files($context, string $component, string $filearea, $itemid, array $files) {
  2979. global $USER;
  2980. $return = false;
  2981. $zipper = get_file_packer('application/zip');
  2982. $fs = get_file_storage();
  2983. // Archive compressed file to an unused draft area.
  2984. $newdraftitemid = file_get_unused_draft_itemid();
  2985. $filestoarchive = [];
  2986. foreach ($files as $selectedfile) {
  2987. $filename = clean_filename($selectedfile->filename); // Default to '.' for root.
  2988. $filepath = clean_param($selectedfile->filepath, PARAM_PATH); // Default to '/' for downloadall.
  2989. $filepath = file_correct_filepath($filepath);
  2990. $area = file_get_draft_area_info($itemid, $filepath);
  2991. if ($area['filecount'] == 0 && $area['foldercount'] == 0) {
  2992. continue;
  2993. }
  2994. $storedfile = $fs->get_file($context->id, $component, $filearea, $itemid, $filepath, $filename);
  2995. // If it is empty we are downloading a directory.
  2996. $archivefile = $storedfile->get_filename();
  2997. if (!$filename || $filename == '.' ) {
  2998. $archivefile = $filepath;
  2999. }
  3000. $filestoarchive[$archivefile] = $storedfile;
  3001. }
  3002. $zippedfile = get_string('files') . '.zip';
  3003. if ($newfile =
  3004. $zipper->archive_to_storage(
  3005. $filestoarchive,
  3006. $context->id,
  3007. $component,
  3008. $filearea,
  3009. $newdraftitemid,
  3010. "/",
  3011. $zippedfile, $USER->id)
  3012. ) {
  3013. $return = new stdClass();
  3014. $return->fileurl = moodle_url::make_draftfile_url($newdraftitemid, '/', $zippedfile)->out();
  3015. $return->filepath = $filepath;
  3016. }
  3017. return $return;
  3018. }