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

/repository/lib.php

https://bitbucket.org/andrewdavidson/sl-clone
PHP | 2708 lines | 1564 code | 259 blank | 885 comment | 343 complexity | 4bcafd1f2c3d0bdaab5b7ad45ea3aa72 MD5 | raw file
Possible License(s): AGPL-3.0, MPL-2.0-no-copyleft-exception, LGPL-3.0, Apache-2.0, GPL-3.0, BSD-3-Clause, LGPL-2.1
  1. <?php
  2. // This file is part of Moodle - http://moodle.org/
  3. //
  4. // Moodle is free software: you can redistribute it and/or modify
  5. // it under the terms of the GNU General Public License as published by
  6. // the Free Software Foundation, either version 3 of the License, or
  7. // (at your option) any later version.
  8. //
  9. // Moodle is distributed in the hope that it will be useful,
  10. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. // GNU General Public License for more details.
  13. //
  14. // You should have received a copy of the GNU General Public License
  15. // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
  16. /**
  17. * This file contains classes used to manage the repository plugins in Moodle
  18. * and was introduced as part of the changes occuring in Moodle 2.0
  19. *
  20. * @since 2.0
  21. * @package repository
  22. * @copyright 2009 Dongsheng Cai {@link http://dongsheng.org}
  23. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  24. */
  25. require_once(dirname(dirname(__FILE__)) . '/config.php');
  26. require_once($CFG->libdir . '/filelib.php');
  27. require_once($CFG->libdir . '/formslib.php');
  28. define('FILE_EXTERNAL', 1);
  29. define('FILE_INTERNAL', 2);
  30. define('FILE_REFERENCE', 4);
  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 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 {
  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, get_system_context(), $instanceoptions);
  221. }
  222. //run plugin_init function
  223. if (!repository::static_function($this->_typename, 'plugin_init')) {
  224. if (!$silent) {
  225. throw new repository_exception('cannotinitplugin', 'repository');
  226. }
  227. }
  228. if(!empty($plugin_id)) {
  229. // return plugin_id if create successfully
  230. return $plugin_id;
  231. } else {
  232. return false;
  233. }
  234. } else {
  235. if (!$silent) {
  236. throw new repository_exception('existingrepository', 'repository');
  237. }
  238. // If plugin existed, return false, tell caller no new plugins were created.
  239. return false;
  240. }
  241. }
  242. /**
  243. * Update plugin options into the config_plugin table
  244. *
  245. * @param array $options
  246. * @return bool
  247. */
  248. public function update_options($options = null) {
  249. global $DB;
  250. $classname = 'repository_' . $this->_typename;
  251. $instanceoptions = repository::static_function($this->_typename, 'get_instance_option_names');
  252. if (empty($instanceoptions)) {
  253. // update repository instance name if this plugin type doesn't have muliti instances
  254. $params = array();
  255. $params['type'] = $this->_typename;
  256. $instances = repository::get_instances($params);
  257. $instance = array_pop($instances);
  258. if ($instance) {
  259. $DB->set_field('repository_instances', 'name', $options['pluginname'], array('id'=>$instance->id));
  260. }
  261. unset($options['pluginname']);
  262. }
  263. if (!empty($options)) {
  264. $this->_options = $options;
  265. }
  266. foreach ($this->_options as $name => $value) {
  267. set_config($name, $value, $this->_typename);
  268. }
  269. return true;
  270. }
  271. /**
  272. * Update visible database field with the value given as parameter
  273. * or with the visible value of this object
  274. * This function is private.
  275. * For public access, have a look to switch_and_update_visibility()
  276. *
  277. * @param bool $visible
  278. * @return bool
  279. */
  280. private function update_visible($visible = null) {
  281. global $DB;
  282. if (!empty($visible)) {
  283. $this->_visible = $visible;
  284. }
  285. else if (!isset($this->_visible)) {
  286. throw new repository_exception('updateemptyvisible', 'repository');
  287. }
  288. return $DB->set_field('repository', 'visible', $this->_visible, array('type'=>$this->_typename));
  289. }
  290. /**
  291. * Update database sortorder field with the value given as parameter
  292. * or with the sortorder value of this object
  293. * This function is private.
  294. * For public access, have a look to move_order()
  295. *
  296. * @param int $sortorder
  297. * @return bool
  298. */
  299. private function update_sortorder($sortorder = null) {
  300. global $DB;
  301. if (!empty($sortorder) && $sortorder!=0) {
  302. $this->_sortorder = $sortorder;
  303. }
  304. //if sortorder is not set, we set it as the ;ast position in the list
  305. else if (!isset($this->_sortorder) || $this->_sortorder == 0 ) {
  306. $sql = "SELECT MAX(sortorder) FROM {repository}";
  307. $this->_sortorder = 1 + $DB->get_field_sql($sql);
  308. }
  309. return $DB->set_field('repository', 'sortorder', $this->_sortorder, array('type'=>$this->_typename));
  310. }
  311. /**
  312. * Change order of the type with its adjacent upper or downer type
  313. * (database fields are updated)
  314. * Algorithm details:
  315. * 1. retrieve all types in an array. This array is sorted by sortorder,
  316. * and the array keys start from 0 to X (incremented by 1)
  317. * 2. switch sortorder values of this type and its adjacent type
  318. *
  319. * @param string $move "up" or "down"
  320. */
  321. public function move_order($move) {
  322. global $DB;
  323. $types = repository::get_types(); // retrieve all types
  324. // retrieve this type into the returned array
  325. $i = 0;
  326. while (!isset($indice) && $i<count($types)) {
  327. if ($types[$i]->get_typename() == $this->_typename) {
  328. $indice = $i;
  329. }
  330. $i++;
  331. }
  332. // retrieve adjacent indice
  333. switch ($move) {
  334. case "up":
  335. $adjacentindice = $indice - 1;
  336. break;
  337. case "down":
  338. $adjacentindice = $indice + 1;
  339. break;
  340. default:
  341. throw new repository_exception('movenotdefined', 'repository');
  342. }
  343. //switch sortorder of this type and the adjacent type
  344. //TODO: we could reset sortorder for all types. This is not as good in performance term, but
  345. //that prevent from wrong behaviour on a screwed database. As performance are not important in this particular case
  346. //it worth to change the algo.
  347. if ($adjacentindice>=0 && !empty($types[$adjacentindice])) {
  348. $DB->set_field('repository', 'sortorder', $this->_sortorder, array('type'=>$types[$adjacentindice]->get_typename()));
  349. $this->update_sortorder($types[$adjacentindice]->get_sortorder());
  350. }
  351. }
  352. /**
  353. * 1. Change visibility to the value chosen
  354. * 2. Update the type
  355. *
  356. * @param bool $visible
  357. * @return bool
  358. */
  359. public function update_visibility($visible = null) {
  360. if (is_bool($visible)) {
  361. $this->_visible = $visible;
  362. } else {
  363. $this->_visible = !$this->_visible;
  364. }
  365. return $this->update_visible();
  366. }
  367. /**
  368. * Delete a repository_type (general options are removed from config_plugin
  369. * table, and all instances are deleted)
  370. *
  371. * @param bool $downloadcontents download external contents if exist
  372. * @return bool
  373. */
  374. public function delete($downloadcontents = false) {
  375. global $DB;
  376. //delete all instances of this type
  377. $params = array();
  378. $params['context'] = array();
  379. $params['onlyvisible'] = false;
  380. $params['type'] = $this->_typename;
  381. $instances = repository::get_instances($params);
  382. foreach ($instances as $instance) {
  383. $instance->delete($downloadcontents);
  384. }
  385. //delete all general options
  386. foreach ($this->_options as $name => $value) {
  387. set_config($name, null, $this->_typename);
  388. }
  389. try {
  390. $DB->delete_records('repository', array('type' => $this->_typename));
  391. } catch (dml_exception $ex) {
  392. return false;
  393. }
  394. return true;
  395. }
  396. }
  397. /**
  398. * This is the base class of the repository class.
  399. *
  400. * To create repository plugin, see: {@link http://docs.moodle.org/dev/Repository_plugins}
  401. * See an example: {@link repository_boxnet}
  402. *
  403. * @package repository
  404. * @category repository
  405. * @copyright 2009 Dongsheng Cai {@link http://dongsheng.org}
  406. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  407. */
  408. abstract class repository {
  409. // $disabled can be set to true to disable a plugin by force
  410. // example: self::$disabled = true
  411. /** @var bool force disable repository instance */
  412. public $disabled = false;
  413. /** @var int repository instance id */
  414. public $id;
  415. /** @var stdClass current context */
  416. public $context;
  417. /** @var array repository options */
  418. public $options;
  419. /** @var bool Whether or not the repository instance is editable */
  420. public $readonly;
  421. /** @var int return types */
  422. public $returntypes;
  423. /** @var stdClass repository instance database record */
  424. public $instance;
  425. /**
  426. * Constructor
  427. *
  428. * @param int $repositoryid repository instance id
  429. * @param int|stdClass $context a context id or context object
  430. * @param array $options repository options
  431. * @param int $readonly indicate this repo is readonly or not
  432. */
  433. public function __construct($repositoryid, $context = SYSCONTEXTID, $options = array(), $readonly = 0) {
  434. global $DB;
  435. $this->id = $repositoryid;
  436. if (is_object($context)) {
  437. $this->context = $context;
  438. } else {
  439. $this->context = get_context_instance_by_id($context);
  440. }
  441. $this->instance = $DB->get_record('repository_instances', array('id'=>$this->id));
  442. $this->readonly = $readonly;
  443. $this->options = array();
  444. if (is_array($options)) {
  445. // The get_option() method will get stored options in database.
  446. $options = array_merge($this->get_option(), $options);
  447. } else {
  448. $options = $this->get_option();
  449. }
  450. foreach ($options as $n => $v) {
  451. $this->options[$n] = $v;
  452. }
  453. $this->name = $this->get_name();
  454. $this->returntypes = $this->supported_returntypes();
  455. $this->super_called = true;
  456. }
  457. /**
  458. * Get repository instance using repository id
  459. *
  460. * @param int $repositoryid repository ID
  461. * @param stdClass|int $context context instance or context ID
  462. * @param array $options additional repository options
  463. * @return repository
  464. */
  465. public static function get_repository_by_id($repositoryid, $context, $options = array()) {
  466. global $CFG, $DB;
  467. $sql = 'SELECT i.name, i.typeid, r.type FROM {repository} r, {repository_instances} i WHERE i.id=? AND i.typeid=r.id';
  468. if (!$record = $DB->get_record_sql($sql, array($repositoryid))) {
  469. throw new repository_exception('invalidrepositoryid', 'repository');
  470. } else {
  471. $type = $record->type;
  472. if (file_exists($CFG->dirroot . "/repository/$type/lib.php")) {
  473. require_once($CFG->dirroot . "/repository/$type/lib.php");
  474. $classname = 'repository_' . $type;
  475. $contextid = $context;
  476. if (is_object($context)) {
  477. $contextid = $context->id;
  478. }
  479. $options['type'] = $type;
  480. $options['typeid'] = $record->typeid;
  481. if (empty($options['name'])) {
  482. $options['name'] = $record->name;
  483. }
  484. $repository = new $classname($repositoryid, $contextid, $options);
  485. return $repository;
  486. } else {
  487. throw new repository_exception('invalidplugin', 'repository');
  488. }
  489. }
  490. }
  491. /**
  492. * Get a repository type object by a given type name.
  493. *
  494. * @static
  495. * @param string $typename the repository type name
  496. * @return repository_type|bool
  497. */
  498. public static function get_type_by_typename($typename) {
  499. global $DB;
  500. if (!$record = $DB->get_record('repository',array('type' => $typename))) {
  501. return false;
  502. }
  503. return new repository_type($typename, (array)get_config($typename), $record->visible, $record->sortorder);
  504. }
  505. /**
  506. * Get the repository type by a given repository type id.
  507. *
  508. * @static
  509. * @param int $id the type id
  510. * @return object
  511. */
  512. public static function get_type_by_id($id) {
  513. global $DB;
  514. if (!$record = $DB->get_record('repository',array('id' => $id))) {
  515. return false;
  516. }
  517. return new repository_type($record->type, (array)get_config($record->type), $record->visible, $record->sortorder);
  518. }
  519. /**
  520. * Return all repository types ordered by sortorder field
  521. * first repository type in returnedarray[0], second repository type in returnedarray[1], ...
  522. *
  523. * @static
  524. * @param bool $visible can return types by visiblity, return all types if null
  525. * @return array Repository types
  526. */
  527. public static function get_types($visible=null) {
  528. global $DB, $CFG;
  529. $types = array();
  530. $params = null;
  531. if (!empty($visible)) {
  532. $params = array('visible' => $visible);
  533. }
  534. if ($records = $DB->get_records('repository',$params,'sortorder')) {
  535. foreach($records as $type) {
  536. if (file_exists($CFG->dirroot . '/repository/'. $type->type .'/lib.php')) {
  537. $types[] = new repository_type($type->type, (array)get_config($type->type), $type->visible, $type->sortorder);
  538. }
  539. }
  540. }
  541. return $types;
  542. }
  543. /**
  544. * Checks if user has a capability to view the current repository in current context
  545. *
  546. * @return bool
  547. */
  548. public final function check_capability() {
  549. $capability = false;
  550. if (preg_match("/^repository_(.*)$/", get_class($this), $matches)) {
  551. $type = $matches[1];
  552. $capability = has_capability('repository/'.$type.':view', $this->context);
  553. }
  554. if (!$capability) {
  555. throw new repository_exception('nopermissiontoaccess', 'repository');
  556. }
  557. }
  558. /**
  559. * Check if file already exists in draft area
  560. *
  561. * @static
  562. * @param int $itemid
  563. * @param string $filepath
  564. * @param string $filename
  565. * @return bool
  566. */
  567. public static function draftfile_exists($itemid, $filepath, $filename) {
  568. global $USER;
  569. $fs = get_file_storage();
  570. $usercontext = get_context_instance(CONTEXT_USER, $USER->id);
  571. if ($fs->get_file($usercontext->id, 'user', 'draft', $itemid, $filepath, $filename)) {
  572. return true;
  573. } else {
  574. return false;
  575. }
  576. }
  577. /**
  578. * Parses the 'source' returned by moodle repositories and returns an instance of stored_file
  579. *
  580. * @param string $source
  581. * @return stored_file|null
  582. */
  583. public static function get_moodle_file($source) {
  584. $params = file_storage::unpack_reference($source, true);
  585. $fs = get_file_storage();
  586. return $fs->get_file($params['contextid'], $params['component'], $params['filearea'],
  587. $params['itemid'], $params['filepath'], $params['filename']);
  588. }
  589. /**
  590. * Repository method to make sure that user can access particular file.
  591. *
  592. * This is checked when user tries to pick the file from repository to deal with
  593. * potential parameter substitutions is request
  594. *
  595. * @param string $source
  596. * @return bool whether the file is accessible by current user
  597. */
  598. public function file_is_accessible($source) {
  599. if ($this->has_moodle_files()) {
  600. try {
  601. $params = file_storage::unpack_reference($source, true);
  602. } catch (file_reference_exception $e) {
  603. return false;
  604. }
  605. $browser = get_file_browser();
  606. $context = context::instance_by_id($params['contextid']);
  607. $file_info = $browser->get_file_info($context, $params['component'], $params['filearea'],
  608. $params['itemid'], $params['filepath'], $params['filename']);
  609. return !empty($file_info);
  610. }
  611. return true;
  612. }
  613. /**
  614. * This function is used to copy a moodle file to draft area.
  615. *
  616. * It DOES NOT check if the user is allowed to access this file because the actual file
  617. * can be located in the area where user does not have access to but there is an alias
  618. * to this file in the area where user CAN access it.
  619. * {@link file_is_accessible} should be called for alias location before calling this function.
  620. *
  621. * @param string $source The metainfo of file, it is base64 encoded php serialized data
  622. * @param stdClass|array $filerecord contains itemid, filepath, filename and optionally other
  623. * attributes of the new file
  624. * @param int $maxbytes maximum allowed size of file, -1 if unlimited. If size of file exceeds
  625. * the limit, the file_exception is thrown.
  626. * @return array The information about the created file
  627. */
  628. public function copy_to_area($source, $filerecord, $maxbytes = -1) {
  629. global $USER;
  630. $fs = get_file_storage();
  631. if ($this->has_moodle_files() == false) {
  632. throw new coding_exception('Only repository used to browse moodle files can use repository::copy_to_area()');
  633. }
  634. $user_context = context_user::instance($USER->id);
  635. $filerecord = (array)$filerecord;
  636. // make sure the new file will be created in user draft area
  637. $filerecord['component'] = 'user';
  638. $filerecord['filearea'] = 'draft';
  639. $filerecord['contextid'] = $user_context->id;
  640. $draftitemid = $filerecord['itemid'];
  641. $new_filepath = $filerecord['filepath'];
  642. $new_filename = $filerecord['filename'];
  643. // the file needs to copied to draft area
  644. $stored_file = self::get_moodle_file($source);
  645. if ($maxbytes != -1 && $stored_file->get_filesize() > $maxbytes) {
  646. throw new file_exception('maxbytes');
  647. }
  648. if (repository::draftfile_exists($draftitemid, $new_filepath, $new_filename)) {
  649. // create new file
  650. $unused_filename = repository::get_unused_filename($draftitemid, $new_filepath, $new_filename);
  651. $filerecord['filename'] = $unused_filename;
  652. $fs->create_file_from_storedfile($filerecord, $stored_file);
  653. $event = array();
  654. $event['event'] = 'fileexists';
  655. $event['newfile'] = new stdClass;
  656. $event['newfile']->filepath = $new_filepath;
  657. $event['newfile']->filename = $unused_filename;
  658. $event['newfile']->url = moodle_url::make_draftfile_url($draftitemid, $new_filepath, $unused_filename)->out();
  659. $event['existingfile'] = new stdClass;
  660. $event['existingfile']->filepath = $new_filepath;
  661. $event['existingfile']->filename = $new_filename;
  662. $event['existingfile']->url = moodle_url::make_draftfile_url($draftitemid, $new_filepath, $new_filename)->out();
  663. return $event;
  664. } else {
  665. $fs->create_file_from_storedfile($filerecord, $stored_file);
  666. $info = array();
  667. $info['itemid'] = $draftitemid;
  668. $info['file'] = $new_filename;
  669. $info['title'] = $new_filename;
  670. $info['contextid'] = $user_context->id;
  671. $info['url'] = moodle_url::make_draftfile_url($draftitemid, $new_filepath, $new_filename)->out();
  672. $info['filesize'] = $stored_file->get_filesize();
  673. return $info;
  674. }
  675. }
  676. /**
  677. * Get unused filename by appending suffix
  678. *
  679. * @static
  680. * @param int $itemid
  681. * @param string $filepath
  682. * @param string $filename
  683. * @return string
  684. */
  685. public static function get_unused_filename($itemid, $filepath, $filename) {
  686. global $USER;
  687. $fs = get_file_storage();
  688. while (repository::draftfile_exists($itemid, $filepath, $filename)) {
  689. $filename = repository::append_suffix($filename);
  690. }
  691. return $filename;
  692. }
  693. /**
  694. * Append a suffix to filename
  695. *
  696. * @static
  697. * @param string $filename
  698. * @return string
  699. */
  700. public static function append_suffix($filename) {
  701. $pathinfo = pathinfo($filename);
  702. if (empty($pathinfo['extension'])) {
  703. return $filename . RENAME_SUFFIX;
  704. } else {
  705. return $pathinfo['filename'] . RENAME_SUFFIX . '.' . $pathinfo['extension'];
  706. }
  707. }
  708. /**
  709. * Return all types that you a user can create/edit and which are also visible
  710. * Note: Mostly used in order to know if at least one editable type can be set
  711. *
  712. * @static
  713. * @param stdClass $context the context for which we want the editable types
  714. * @return array types
  715. */
  716. public static function get_editable_types($context = null) {
  717. if (empty($context)) {
  718. $context = get_system_context();
  719. }
  720. $types= repository::get_types(true);
  721. $editabletypes = array();
  722. foreach ($types as $type) {
  723. $instanceoptionnames = repository::static_function($type->get_typename(), 'get_instance_option_names');
  724. if (!empty($instanceoptionnames)) {
  725. if ($type->get_contextvisibility($context)) {
  726. $editabletypes[]=$type;
  727. }
  728. }
  729. }
  730. return $editabletypes;
  731. }
  732. /**
  733. * Return repository instances
  734. *
  735. * @static
  736. * @param array $args Array containing the following keys:
  737. * currentcontext
  738. * context
  739. * onlyvisible
  740. * type
  741. * accepted_types
  742. * return_types
  743. * userid
  744. *
  745. * @return array repository instances
  746. */
  747. public static function get_instances($args = array()) {
  748. global $DB, $CFG, $USER;
  749. if (isset($args['currentcontext'])) {
  750. $current_context = $args['currentcontext'];
  751. } else {
  752. $current_context = null;
  753. }
  754. if (!empty($args['context'])) {
  755. $contexts = $args['context'];
  756. } else {
  757. $contexts = array();
  758. }
  759. $onlyvisible = isset($args['onlyvisible']) ? $args['onlyvisible'] : true;
  760. $returntypes = isset($args['return_types']) ? $args['return_types'] : 3;
  761. $type = isset($args['type']) ? $args['type'] : null;
  762. $params = array();
  763. $sql = "SELECT i.*, r.type AS repositorytype, r.sortorder, r.visible
  764. FROM {repository} r, {repository_instances} i
  765. WHERE i.typeid = r.id ";
  766. if (!empty($args['disable_types']) && is_array($args['disable_types'])) {
  767. list($types, $p) = $DB->get_in_or_equal($args['disable_types'], SQL_PARAMS_QM, 'param', false);
  768. $sql .= " AND r.type $types";
  769. $params = array_merge($params, $p);
  770. }
  771. if (!empty($args['userid']) && is_numeric($args['userid'])) {
  772. $sql .= " AND (i.userid = 0 or i.userid = ?)";
  773. $params[] = $args['userid'];
  774. }
  775. foreach ($contexts as $context) {
  776. if (empty($firstcontext)) {
  777. $firstcontext = true;
  778. $sql .= " AND ((i.contextid = ?)";
  779. } else {
  780. $sql .= " OR (i.contextid = ?)";
  781. }
  782. $params[] = $context->id;
  783. }
  784. if (!empty($firstcontext)) {
  785. $sql .=')';
  786. }
  787. if ($onlyvisible == true) {
  788. $sql .= " AND (r.visible = 1)";
  789. }
  790. if (isset($type)) {
  791. $sql .= " AND (r.type = ?)";
  792. $params[] = $type;
  793. }
  794. $sql .= " ORDER BY r.sortorder, i.name";
  795. if (!$records = $DB->get_records_sql($sql, $params)) {
  796. $records = array();
  797. }
  798. $repositories = array();
  799. if (isset($args['accepted_types'])) {
  800. $accepted_types = $args['accepted_types'];
  801. } else {
  802. $accepted_types = '*';
  803. }
  804. // Sortorder should be unique, which is not true if we use $record->sortorder
  805. // and there are multiple instances of any repository type
  806. $sortorder = 1;
  807. foreach ($records as $record) {
  808. if (!file_exists($CFG->dirroot . '/repository/'. $record->repositorytype.'/lib.php')) {
  809. continue;
  810. }
  811. require_once($CFG->dirroot . '/repository/'. $record->repositorytype.'/lib.php');
  812. $options['visible'] = $record->visible;
  813. $options['type'] = $record->repositorytype;
  814. $options['typeid'] = $record->typeid;
  815. $options['sortorder'] = $sortorder++;
  816. // tell instance what file types will be accepted by file picker
  817. $classname = 'repository_' . $record->repositorytype;
  818. $repository = new $classname($record->id, $record->contextid, $options, $record->readonly);
  819. $is_supported = true;
  820. if (empty($repository->super_called)) {
  821. // to make sure the super construct is called
  822. debugging('parent::__construct must be called by '.$record->repositorytype.' plugin.');
  823. } else {
  824. // check mimetypes
  825. if ($accepted_types !== '*' and $repository->supported_filetypes() !== '*') {
  826. $accepted_ext = file_get_typegroup('extension', $accepted_types);
  827. $supported_ext = file_get_typegroup('extension', $repository->supported_filetypes());
  828. $valid_ext = array_intersect($accepted_ext, $supported_ext);
  829. $is_supported = !empty($valid_ext);
  830. }
  831. // check return values
  832. if ($returntypes !== 3 and $repository->supported_returntypes() !== 3) {
  833. $type = $repository->supported_returntypes();
  834. if ($type & $returntypes) {
  835. //
  836. } else {
  837. $is_supported = false;
  838. }
  839. }
  840. if (!$onlyvisible || ($repository->is_visible() && !$repository->disabled)) {
  841. // check capability in current context
  842. if (!empty($current_context)) {
  843. $capability = has_capability('repository/'.$record->repositorytype.':view', $current_context);
  844. } else {
  845. $capability = has_capability('repository/'.$record->repositorytype.':view', get_system_context());
  846. }
  847. if ($record->repositorytype == 'coursefiles') {
  848. // coursefiles plugin needs managefiles permission
  849. if (!empty($current_context)) {
  850. $capability = $capability && has_capability('moodle/course:managefiles', $current_context);
  851. } else {
  852. $capability = $capability && has_capability('moodle/course:managefiles', get_system_context());
  853. }
  854. }
  855. if ($is_supported && $capability) {
  856. $repositories[$repository->id] = $repository;
  857. }
  858. }
  859. }
  860. }
  861. return $repositories;
  862. }
  863. /**
  864. * Get single repository instance
  865. *
  866. * @static
  867. * @param integer $id repository id
  868. * @return object repository instance
  869. */
  870. public static function get_instance($id) {
  871. global $DB, $CFG;
  872. $sql = "SELECT i.*, r.type AS repositorytype, r.visible
  873. FROM {repository} r
  874. JOIN {repository_instances} i ON i.typeid = r.id
  875. WHERE i.id = ?";
  876. if (!$instance = $DB->get_record_sql($sql, array($id))) {
  877. return false;
  878. }
  879. require_once($CFG->dirroot . '/repository/'. $instance->repositorytype.'/lib.php');
  880. $classname = 'repository_' . $instance->repositorytype;
  881. $options['typeid'] = $instance->typeid;
  882. $options['type'] = $instance->repositorytype;
  883. $options['name'] = $instance->name;
  884. $obj = new $classname($instance->id, $instance->contextid, $options, $instance->readonly);
  885. if (empty($obj->super_called)) {
  886. debugging('parent::__construct must be called by '.$classname.' plugin.');
  887. }
  888. return $obj;
  889. }
  890. /**
  891. * Call a static function. Any additional arguments than plugin and function will be passed through.
  892. *
  893. * @static
  894. * @param string $plugin repository plugin name
  895. * @param string $function funciton name
  896. * @return mixed
  897. */
  898. public static function static_function($plugin, $function) {
  899. global $CFG;
  900. //check that the plugin exists
  901. $typedirectory = $CFG->dirroot . '/repository/'. $plugin . '/lib.php';
  902. if (!file_exists($typedirectory)) {
  903. //throw new repository_exception('invalidplugin', 'repository');
  904. return false;
  905. }
  906. $pname = null;
  907. if (is_object($plugin) || is_array($plugin)) {
  908. $plugin = (object)$plugin;
  909. $pname = $plugin->name;
  910. } else {
  911. $pname = $plugin;
  912. }
  913. $args = func_get_args();
  914. if (count($args) <= 2) {
  915. $args = array();
  916. } else {
  917. array_shift($args);
  918. array_shift($args);
  919. }
  920. require_once($typedirectory);
  921. return call_user_func_array(array('repository_' . $plugin, $function), $args);
  922. }
  923. /**
  924. * Scan file, throws exception in case of infected file.
  925. *
  926. * Please note that the scanning engine must be able to access the file,
  927. * permissions of the file are not modified here!
  928. *
  929. * @static
  930. * @param string $thefile
  931. * @param string $filename name of the file
  932. * @param bool $deleteinfected
  933. */
  934. public static function antivir_scan_file($thefile, $filename, $deleteinfected) {
  935. global $CFG;
  936. if (!is_readable($thefile)) {
  937. // this should not happen
  938. return;
  939. }
  940. if (empty($CFG->runclamonupload) or empty($CFG->pathtoclam)) {
  941. // clam not enabled
  942. return;
  943. }
  944. $CFG->pathtoclam = trim($CFG->pathtoclam);
  945. if (!file_exists($CFG->pathtoclam) or !is_executable($CFG->pathtoclam)) {
  946. // misconfigured clam - use the old notification for now
  947. require("$CFG->libdir/uploadlib.php");
  948. $notice = get_string('clamlost', 'moodle', $CFG->pathtoclam);
  949. clam_message_admins($notice);
  950. return;
  951. }
  952. // do NOT mess with permissions here, the calling party is responsible for making
  953. // sure the scanner engine can access the files!
  954. // execute test
  955. $cmd = escapeshellcmd($CFG->pathtoclam).' --stdout '.escapeshellarg($thefile);
  956. exec($cmd, $output, $return);
  957. if ($return == 0) {
  958. // perfect, no problem found
  959. return;
  960. } else if ($return == 1) {
  961. // infection found
  962. if ($deleteinfected) {
  963. unlink($thefile);
  964. }
  965. throw new moodle_exception('virusfounduser', 'moodle', '', array('filename'=>$filename));
  966. } else {
  967. //unknown problem
  968. require("$CFG->libdir/uploadlib.php");
  969. $notice = get_string('clamfailed', 'moodle', get_clam_error_code($return));
  970. $notice .= "\n\n". implode("\n", $output);
  971. clam_message_admins($notice);
  972. if ($CFG->clamfailureonupload === 'actlikevirus') {
  973. if ($deleteinfected) {
  974. unlink($thefile);
  975. }
  976. throw new moodle_exception('virusfounduser', 'moodle', '', array('filename'=>$filename));
  977. } else {
  978. return;
  979. }
  980. }
  981. }
  982. /**
  983. * Repository method to serve the referenced file
  984. *
  985. * @see send_stored_file
  986. *
  987. * @param stored_file $storedfile the file that contains the reference
  988. * @param int $lifetime Number of seconds before the file should expire from caches (default 24 hours)
  989. * @param int $filter 0 (default)=no filtering, 1=all files, 2=html files only
  990. * @param bool $forcedownload If true (default false), forces download of file rather than view in browser/plugin
  991. * @param array $options additional options affecting the file serving
  992. */
  993. public function send_file($storedfile, $lifetime=86400 , $filter=0, $forcedownload=false, array $options = null) {
  994. if ($this->has_moodle_files()) {
  995. $fs = get_file_storage();
  996. $params = file_storage::unpack_reference($storedfile->get_reference(), true);
  997. $srcfile = null;
  998. if (is_array($params)) {
  999. $srcfile = $fs->get_file($params['contextid'], $params['component'], $params['filearea'],
  1000. $params['itemid'], $params['filepath'], $params['filename']);
  1001. }
  1002. if (empty($options)) {
  1003. $options = array();
  1004. }
  1005. if (!isset($options['filename'])) {
  1006. $options['filename'] = $storedfile->get_filename();
  1007. }
  1008. if (!$srcfile) {
  1009. send_file_not_found();
  1010. } else {
  1011. send_stored_file($srcfile, $lifetime, $filter, $forcedownload, $options);
  1012. }
  1013. } else {
  1014. throw new coding_exception("Repository plugin must implement send_file() method.");
  1015. }
  1016. }
  1017. /**
  1018. * Return reference file life time
  1019. *
  1020. * @param string $ref
  1021. * @return int
  1022. */
  1023. public function get_reference_file_lifetime($ref) {
  1024. // One day
  1025. return 60 * 60 * 24;
  1026. }
  1027. /**
  1028. * Decide whether or not the file should be synced
  1029. *
  1030. * @param stored_file $storedfile
  1031. * @return bool
  1032. */
  1033. public function sync_individual_file(stored_file $storedfile) {
  1034. return true;
  1035. }
  1036. /**
  1037. * Return human readable reference information
  1038. * {@link stored_file::get_reference()}
  1039. *
  1040. * @param string $reference
  1041. * @param int $filestatus status of the file, 0 - ok, 666 - source missing
  1042. * @return string
  1043. */
  1044. public function get_reference_details($reference, $filestatus = 0) {
  1045. if ($this->has_moodle_files()) {
  1046. $fileinfo = null;
  1047. $params = file_storage::unpack_reference($reference, true);
  1048. if (is_array($params)) {
  1049. $context = get_context_instance_by_id($params['contextid']);
  1050. if ($context) {
  1051. $browser = get_file_browser();
  1052. $fileinfo = $browser->get_file_info($context, $params['component'], $params['filearea'], $params['itemid'], $params['filepath'], $params['filename']);
  1053. }
  1054. }
  1055. if (empty($fileinfo)) {
  1056. if ($filestatus == 666) {
  1057. if (is_siteadmin() || ($context && has_capability('moodle/course:managefiles', $context))) {
  1058. return get_string('lostsource', 'repository',
  1059. $params['contextid']. '/'. $params['component']. '/'. $params['filearea']. '/'. $params['itemid']. $params['filepath']. $params['filename']);
  1060. } else {
  1061. return get_string('lostsource', 'repository', '');
  1062. }
  1063. }
  1064. return get_string('undisclosedsource', 'repository');
  1065. } else {
  1066. return $fileinfo->get_readable_fullname();
  1067. }
  1068. }
  1069. return '';
  1070. }
  1071. /**
  1072. * Cache file from external repository by reference
  1073. * {@link repository::get_file_reference()}
  1074. * {@link repository::get_file()}
  1075. * Invoked at MOODLE/repository/repository_ajax.php
  1076. *
  1077. * @param string $reference this reference is generated by
  1078. * repository::get_file_reference()
  1079. * @param stored_file $storedfile created file reference
  1080. */
  1081. public function cache_file_by_reference($reference, $storedfile) {
  1082. }
  1083. /**
  1084. * Returns information about file in this repository by reference
  1085. * {@link repository::get_file_reference()}
  1086. * {@link repository::get_file()}
  1087. *
  1088. * Returns null if file not found or is not readable
  1089. *
  1090. * @param stdClass $reference file reference db record
  1091. * @return stdClass|null contains one of the following:
  1092. * - 'contenthash' and 'filesize'
  1093. * - 'filepath'
  1094. * - 'handle'
  1095. * - 'content'
  1096. */
  1097. public function get_file_by_reference($reference) {
  1098. if ($this->has_moodle_files() && isset($reference->reference)) {
  1099. $fs = get_file_storage();
  1100. $params = file_storage::unpack_reference($reference->reference, true);
  1101. if (!is_array($params) || !($storedfile = $fs->get_file($params['contextid'],
  1102. $params['component'], $params['filearea'], $params['itemid'], $params['filepath'],
  1103. $params['filename']))) {
  1104. return null;
  1105. }
  1106. return (object)array(
  1107. 'contenthash' => $storedfile->get_contenthash(),
  1108. 'filesize' => $storedfile->get_filesize()
  1109. );
  1110. }
  1111. return null;
  1112. }
  1113. /**
  1114. * Return the source information
  1115. *
  1116. * @param stdClass $url
  1117. * @return string|null
  1118. */
  1119. public function get_file_source_info($url) {
  1120. if ($this->has_moodle_files()) {
  1121. return $this->get_reference_details($url, 0);
  1122. }
  1123. return $url;
  1124. }
  1125. /**
  1126. * Move file from download folder to file pool using FILE API
  1127. *
  1128. * @todo MDL-28637
  1129. * @static
  1130. * @param string $thefile file path in download folder
  1131. * @param stdClass $record
  1132. * @return array containing the following keys:
  1133. * icon
  1134. * file
  1135. * id
  1136. * url
  1137. */
  1138. public static function move_to_filepool($thefile, $record) {
  1139. global $DB, $CFG, $USER, $OUTPUT;
  1140. // scan for viruses if possible, throws exception if problem found
  1141. self::antivir_scan_file($thefile, $record->filename, empty($CFG->repository_no_delete)); //TODO: MDL-28637 this repository_no_delete is a bloody hack!
  1142. $fs = get_file_storage();
  1143. // If file name being used.
  1144. if (repository::draftfile_exists($record->itemid, $record->filepath, $record->filename)) {
  1145. $draftitemid = $record->itemid;
  1146. $new_filename = repository::get_unused_filename($draftitemid, $record->filepath, $record->filename);
  1147. $old_filename = $record->filename;
  1148. // Create a tmp file.
  1149. $record->filename = $new_filename;
  1150. $newfile = $fs->create_file_from_pathname($record, $thefile);
  1151. $event = array();
  1152. $event['event'] = 'fileexists';
  1153. $event['newfile'] = new stdClass;
  1154. $event['newfile']->filepath = $record->filepath;
  1155. $event['newfile']->filename = $new_filename;
  1156. $event['newfile']->url = moodle_url::make_draftfile_url($draftitemid, $record->filepath, $new_filename)->out();
  1157. $event['existingfile'] = new stdClass;
  1158. $event['existingfile']->filepath = $record->filepath;
  1159. $event['existingfile']->filename = $old_filename;
  1160. $event['existingfile']->url = moodle_url::make_draftfile_url($draftitemid, $record->filepath, $old_filename)->out();;
  1161. return $event;
  1162. }
  1163. if ($file = $fs->create_file_from_pathname($record, $thefile)) {
  1164. if (empty($CFG->repository_no_delete)) {
  1165. $delete = unlink($thefile);
  1166. unset($CFG->repository_no_delete);
  1167. }
  1168. return array(
  1169. 'url'=>moodle_url::make_draftfile_url($file->get_itemid(), $file->get_filepath(), $file->get_filename())->out(),
  1170. 'id'=>$file->get_itemid(),
  1171. 'file'=>$file->get_filename(),
  1172. 'icon' => $OUTPUT->pix_url(file_extension_icon($thefile, 32))->out(),
  1173. );
  1174. } else {
  1175. return null;
  1176. }
  1177. }
  1178. /**
  1179. * Builds a tree of files This function is then called recursively.
  1180. *
  1181. * @static
  1182. * @todo take $search into account, and respect a threshold for dynamic loading
  1183. * @param file_info $fileinfo an object returned by file_browser::get_file_info()
  1184. * @param string $search searched string
  1185. * @param bool $dynamicmode no recursive call is done when in dynamic mode
  1186. * @param array $list the array containing the files under the passed $fileinfo
  1187. * @returns int the number of files found
  1188. *
  1189. */
  1190. public static function build_tree($fileinfo, $search, $dynamicmode, &$list) {
  1191. global $CFG, $OUTPUT;
  1192. $filecount = 0;
  1193. $children = $fileinfo->get_children();
  1194. foreach ($children as $child) {
  1195. $filename = $child->get_visible_name();
  1196. $filesize = $child->get_filesize();
  1197. $filesize = $filesize ? display_size($filesize) : '';
  1198. $filedate = $child->get_timemodified();
  1199. $filedate = $filedate ? userdate($filedate) : '';
  1200. $filetype = $child->get_mimetype();
  1201. if ($child->is_directory()) {
  1202. $path = array();
  1203. $level = $child->get_parent();
  1204. while ($level) {
  1205. $params = $level->get_params();
  1206. $path[] = array($params['filepath'], $level->get_visible_name());
  1207. $level = $level->get_parent();
  1208. }
  1209. $tmp = array(
  1210. 'title' => $child->get_visible_name(),
  1211. 'size' => 0,
  1212. 'date' => $filedate,
  1213. 'path' => array_reverse($path),
  1214. 'thumbnail' => $OUTPUT->pix_url(file_folder_icon(90))->out(false)
  1215. );
  1216. //if ($dynamicmode && $child->is_writable()) {
  1217. // $tmp['children'] = array();
  1218. //} else {
  1219. // if folder name matches search, we send back all files contained.
  1220. $_search = $search;
  1221. if ($search && stristr($tmp['title'], $search) !== false) {
  1222. $_search = false;
  1223. }
  1224. $tmp['children'] = array();
  1225. $_filecount = repository::build_tree($child, $_search, $dynamicmode, $tmp['children']);
  1226. if ($search && $_filecount) {
  1227. $tmp['expanded'] = 1;
  1228. }
  1229. //}
  1230. if (!$search || $_filecount || (stristr($tmp['title'], $search) !== false)) {
  1231. $filecount += $_filecount;
  1232. $list[] = $tmp;
  1233. }
  1234. } else { // not a directory
  1235. // skip the file, if we're in search mode and it's not a match
  1236. if ($search && (stristr($filename, $search) === false)) {
  1237. continue;
  1238. }
  1239. $params = $child->get_params();
  1240. $source = serialize(array($params['contextid'], $params['component'], $params['filearea'], $params['itemid'], $params['filepath'], $params['filename']));
  1241. $list[] = array(
  1242. 'title' => $filename,
  1243. 'size' => $filesize,
  1244. 'date' => $filedate,
  1245. //'source' => $child->get_url(),
  1246. 'source' => base64_encode($source),
  1247. 'icon'=>$OUTPUT->pix_url(file_file_icon($child, 24))->out(false),
  1248. 'thumbnail'=>$OUTPUT->pix_url(file_file_icon($child, 90))->out(false),
  1249. );
  1250. $filecount++;
  1251. }
  1252. }
  1253. return $filecount;
  1254. }
  1255. /**
  1256. * Display a repository instance list (with edit/delete/create links)
  1257. *
  1258. * @static
  1259. * @param stdClass $context the context for which we display the instance
  1260. * @param string $typename if set, we display only one type of instance
  1261. */
  1262. public static function display_instances_list($context, $typename = null) {
  1263. global $CFG, $USER, $OUTPUT;
  1264. $output = $OUTPUT->box_start('generalbox');
  1265. //if the context is SYSTEM, so we call it from administration page
  1266. $admin = ($context->id == SYSCONTEXTID) ? true : false;
  1267. if ($admin) {
  1268. $baseurl = new moodle_url('/'.$CFG->admin.'/repositoryinstance.php', array('sesskey'=>sesskey()));
  1269. $output .= $OUTPUT->heading(get_string('siteinstances', 'repository'));
  1270. } else {
  1271. $baseurl = new moodle_url('/repository/manage_instances.php', array('contextid'=>$context->id, 'sesskey'=>sesskey()));
  1272. }
  1273. $namestr = get_string('name');
  1274. $pluginstr = get_string('plugin', 'repository');
  1275. $settingsstr = get_string('settings');
  1276. $deletestr = get_string('delete');
  1277. //retrieve list of instances. In administration context we want to display all
  1278. //instances of a type, even if this type is not visible. In course/user context we
  1279. //want to display only visible instances, but for every type types. The repository::get_instances()
  1280. //third parameter displays only visible type.
  1281. $params = array();
  1282. $params['context'] = array($context, get_system_context());
  1283. $params['currentcontext'] = $context;
  1284. $params['onlyvisible'] = !$admin;
  1285. $params['type'] = $typename;
  1286. $instances = repository::get_instances($params);
  1287. $instancesnumber = count($instances);
  1288. $alreadyplugins = array();
  1289. $table = new html_table();
  1290. $table->head = array($namestr, $pluginstr, $settingsstr, $deletestr);
  1291. $table->align = array('left', 'left', 'center','center');
  1292. $table->data = array();
  1293. $updowncount = 1;
  1294. foreach ($instances as $i) {
  1295. $settings = '';
  1296. $delete = '';
  1297. $type = repository::get_type_by_id($i->options['typeid']);
  1298. if ($type->get_contextvisibility($context)) {
  1299. if (!$i->readonly) {
  1300. $settingurl = new moodle_url($baseurl);
  1301. $settingurl->param('type', $i->options['type']);
  1302. $settingurl->param('edit', $i->id);
  1303. $settings .= html_writer::link($settingurl, $settingsstr);
  1304. $deleteurl = new moodle_url($baseurl);
  1305. $deleteurl->param('delete', $i->id);
  1306. $deleteurl->param('type', $i->options['type']);
  1307. $delete .= html_writer::link($deleteurl, $deletestr);
  1308. }
  1309. }
  1310. $type = repository::get_type_by_id($i->options['typeid']);
  1311. $table->data[] = array(format_string($i->name), $type->get_readablename(), $settings, $delete);
  1312. //display a grey row if the type is defined as not visible
  1313. if (isset($type) && !$type->get_visible()) {
  1314. $table->rowclasses[] = 'dimmed_text';
  1315. } else {
  1316. $table->rowclasses[] = '';
  1317. }
  1318. if (!in_array($i->name, $alreadyplugins)) {
  1319. $alreadyplugins[] = $i->name;
  1320. }
  1321. }
  1322. $output .= html_writer::table($table);
  1323. $instancehtml = '<div>';
  1324. $addable = 0;
  1325. //if no type is set, we can create all type of instance
  1326. if (!$typename) {
  1327. $instancehtml .= '<h3>';
  1328. $instancehtml .= get_string('createrepository', 'repository');
  1329. $instancehtml .= '</h3><ul>';
  1330. $types = repository::get_editable_types($context);
  1331. foreach ($types as $type) {
  1332. if (!empty($type) && $type->get_visible()) {
  1333. $instanceoptionnames = repository::static_function($type->get_typename(), 'get_instance_option_names');
  1334. if (!empty($instanceoptionnames)) {
  1335. $baseurl->param('new', $type->get_typename());
  1336. $instancehtml .= '<li><a href="'.$baseurl->out().'">'.get_string('createxxinstance', 'repository', get_string('pluginname', 'repository_'.$type->get_typename())). '</a></li>';
  1337. $baseurl->remove_params('new');
  1338. $addable++;
  1339. }
  1340. }
  1341. }
  1342. $instancehtml .= '</ul>';
  1343. } else {
  1344. $instanceoptionnames = repository::static_function($typename, 'get_instance_option_names');
  1345. if (!empty($instanceoptionnames)) { //create a unique type of instance
  1346. $addable = 1;
  1347. $baseurl->param('new', $typename);
  1348. $output .= $OUTPUT->single_button($baseurl, get_string('createinstance', 'repository'), 'get');
  1349. $baseurl->remove_params('new');
  1350. }
  1351. }
  1352. if ($addable) {
  1353. $instancehtml .= '</div>';
  1354. $output .= $instancehtml;
  1355. }
  1356. $output .= $OUTPUT->box_end();
  1357. //print the list + creation links
  1358. print($output);
  1359. }
  1360. /**
  1361. * Prepare file reference information
  1362. *
  1363. * @param string $source
  1364. * @return string file referece
  1365. */
  1366. public function get_file_reference($source) {
  1367. if ($this->has_moodle_files() && ($this->supported_returntypes() & FILE_REFERENCE)) {
  1368. $params = file_storage::unpack_reference($source);
  1369. if (!is_array($params)) {
  1370. throw new repository_exception('invalidparams', 'repository');
  1371. }
  1372. return file_storage::pack_reference($params);
  1373. }
  1374. return $source;
  1375. }
  1376. /**
  1377. * Decide where to save the file, can be overwriten by subclass
  1378. *
  1379. * @param string $filename file name
  1380. * @return file path
  1381. */
  1382. public function prepare_file($filename) {
  1383. global $CFG;
  1384. if (!file_exists($CFG->tempdir.'/download')) {
  1385. mkdir($CFG->tempdir.'/download/', $CFG->directorypermissions, true);
  1386. }
  1387. if (is_dir($CFG->tempdir.'/download')) {
  1388. $dir = $CFG->tempdir.'/download/';
  1389. }
  1390. if (empty($filename)) {
  1391. $filename = uniqid('repo', true).'_'.time().'.tmp';
  1392. }
  1393. if (file_exists($dir.$filename)) {
  1394. $filename = uniqid('m').$filename;
  1395. }
  1396. return $dir.$filename;
  1397. }
  1398. /**
  1399. * Does this repository used to browse moodle files?
  1400. *
  1401. * @return bool
  1402. */
  1403. public function has_moodle_files() {
  1404. return false;
  1405. }
  1406. /**
  1407. * Return file URL, for most plugins, the parameter is the original
  1408. * url, but some plugins use a file id, so we need this function to
  1409. * convert file id to original url.
  1410. *
  1411. * @param string $url the url of file
  1412. * @return string
  1413. */
  1414. public function get_link($url) {
  1415. return $url;
  1416. }
  1417. /**
  1418. * Download a file, this function can be overridden by subclass. {@link curl}
  1419. *
  1420. * @param string $url the url of file
  1421. * @param string $filename save location
  1422. * @return array with elements:
  1423. * path: internal location of the file
  1424. * url: URL to the source (from parameters)
  1425. */
  1426. public function get_file($url, $filename = '') {
  1427. global $CFG;
  1428. $path = $this->prepare_file($filename);
  1429. $fp = fopen($path, 'w');
  1430. $c = new curl;
  1431. $result = $c->download(array(array('url'=>$url, 'file'=>$fp)));
  1432. // Close file handler.
  1433. fclose($fp);
  1434. if (empty($result)) {
  1435. unlink($path);
  1436. return null;
  1437. }
  1438. return array('path'=>$path, 'url'=>$url);
  1439. }
  1440. /**
  1441. * Return size of a file in bytes.
  1442. *
  1443. * @param string $source encoded and serialized data of file
  1444. * @return int file size in bytes
  1445. */
  1446. public function get_file_size($source) {
  1447. // TODO MDL-33297 remove this function completely?
  1448. $browser = get_file_browser();
  1449. $params = unserialize(base64_decode($source));
  1450. $contextid = clean_param($params['contextid'], PARAM_INT);
  1451. $fileitemid = clean_param($params['itemid'], PARAM_INT);
  1452. $filename = clean_param($params['filename'], PARAM_FILE);
  1453. $filepath = clean_param($params['filepath'], PARAM_PATH);
  1454. $filearea = clean_param($params['filearea'], PARAM_AREA);
  1455. $component = clean_param($params['component'], PARAM_COMPONENT);
  1456. $context = get_context_instance_by_id($contextid);
  1457. $file_info = $browser->get_file_info($context, $component, $filearea, $fileitemid, $filepath, $filename);
  1458. if (!empty($file_info)) {
  1459. $filesize = $file_info->get_filesize();
  1460. } else {
  1461. $filesize = null;
  1462. }
  1463. return $filesize;
  1464. }
  1465. /**
  1466. * Return is the instance is visible
  1467. * (is the type visible ? is the context enable ?)
  1468. *
  1469. * @return bool
  1470. */
  1471. public function is_visible() {
  1472. $type = repository::get_type_by_id($this->options['typeid']);
  1473. $instanceoptions = repository::static_function($type->get_typename(), 'get_instance_option_names');
  1474. if ($type->get_visible()) {
  1475. //if the instance is unique so it's visible, otherwise check if the instance has a enabled context
  1476. if (empty($instanceoptions) || $type->get_contextvisibility($this->context)) {
  1477. return true;
  1478. }
  1479. }
  1480. return false;
  1481. }
  1482. /**
  1483. * Return the name of this instance, can be overridden.
  1484. *
  1485. * @return string
  1486. */
  1487. public function get_name() {
  1488. global $DB;
  1489. if ( $name = $this->instance->name ) {
  1490. return $name;
  1491. } else {
  1492. return get_string('pluginname', 'repository_' . $this->options['type']);
  1493. }
  1494. }
  1495. /**
  1496. * What kind of files will be in this repository?
  1497. *
  1498. * @return array return '*' means this repository support any files, otherwise
  1499. * return mimetypes of files, it can be an array
  1500. */
  1501. public function supported_filetypes() {
  1502. // return array('text/plain', 'image/gif');
  1503. return '*';
  1504. }
  1505. /**
  1506. * Tells how the file can be picked from this repository
  1507. *
  1508. * Maximum value is FILE_INTERNAL | FILE_EXTERNAL | FILE_REFERENCE
  1509. *
  1510. * @return int
  1511. */
  1512. public function supported_returntypes() {
  1513. return (FILE_INTERNAL | FILE_EXTERNAL);
  1514. }
  1515. /**
  1516. * Provide repository instance information for Ajax
  1517. *
  1518. * @return stdClass
  1519. */
  1520. final public function get_meta() {
  1521. global $CFG, $OUTPUT;
  1522. $meta = new stdClass();
  1523. $meta->id = $this->id;
  1524. $meta->name = format_string($this->get_name());
  1525. $meta->type = $this->options['type'];
  1526. $meta->icon = $OUTPUT->pix_url('icon', 'repository_'.$meta->type)->out(false);
  1527. $meta->supported_types = file_get_typegroup('extension', $this->supported_filetypes());
  1528. $meta->return_types = $this->supported_returntypes();
  1529. $meta->sortorder = $this->options['sortorder'];
  1530. return $meta;
  1531. }
  1532. /**
  1533. * Create an instance for this plug-in
  1534. *
  1535. * @static
  1536. * @param string $type the type of the repository
  1537. * @param int $userid the user id
  1538. * @param stdClass $context the context
  1539. * @param array $params the options for this instance
  1540. * @param int $readonly whether to create it readonly or not (defaults to not)
  1541. * @return mixed
  1542. */
  1543. public static function create($type, $userid, $context, $params, $readonly=0) {
  1544. global $CFG, $DB;
  1545. $params = (array)$params;
  1546. require_once($CFG->dirroot . '/repository/'. $type . '/lib.php');
  1547. $classname = 'repository_' . $type;
  1548. if ($repo = $DB->get_record('repository', array('type'=>$type))) {
  1549. $record = new stdClass();
  1550. $record->name = $params['name'];
  1551. $record->typeid = $repo->id;
  1552. $record->timecreated = time();
  1553. $record->timemodified = time();
  1554. $record->contextid = $context->id;
  1555. $record->readonly = $readonly;
  1556. $record->userid = $userid;
  1557. $id = $DB->insert_record('repository_instances', $record);
  1558. $options = array();
  1559. $configs = call_user_func($classname . '::get_instance_option_names');
  1560. if (!empty($configs)) {
  1561. foreach ($configs as $config) {
  1562. if (isset($params[$config])) {
  1563. $options[$config] = $params[$config];
  1564. } else {
  1565. $options[$config] = null;
  1566. }
  1567. }
  1568. }
  1569. if (!empty($id)) {
  1570. unset($options['name']);
  1571. $instance = repository::get_instance($id);
  1572. $instance->set_option($options);
  1573. return $id;
  1574. } else {
  1575. return null;
  1576. }
  1577. } else {
  1578. return null;
  1579. }
  1580. }
  1581. /**
  1582. * delete a repository instance
  1583. *
  1584. * @param bool $downloadcontents
  1585. * @return bool
  1586. */
  1587. final public function delete($downloadcontents = false) {
  1588. global $DB;
  1589. if ($downloadcontents) {
  1590. $this->convert_references_to_local();
  1591. }
  1592. try {
  1593. $DB->delete_records('repository_instances', array('id'=>$this->id));
  1594. $DB->delete_records('repository_instance_config', array('instanceid'=>$this->id));
  1595. } catch (dml_exception $ex) {
  1596. return false;
  1597. }
  1598. return true;
  1599. }
  1600. /**
  1601. * Hide/Show a repository
  1602. *
  1603. * @param string $hide
  1604. * @return bool
  1605. */
  1606. final public function hide($hide = 'toggle') {
  1607. global $DB;
  1608. if ($entry = $DB->get_record('repository', array('id'=>$this->id))) {
  1609. if ($hide === 'toggle' ) {
  1610. if (!empty($entry->visible)) {
  1611. $entry->visible = 0;
  1612. } else {
  1613. $entry->visible = 1;
  1614. }
  1615. } else {
  1616. if (!empty($hide)) {
  1617. $entry->visible = 0;
  1618. } else {
  1619. $entry->visible = 1;
  1620. }
  1621. }
  1622. return $DB->update_record('repository', $entry);
  1623. }
  1624. return false;
  1625. }
  1626. /**
  1627. * Save settings for repository instance
  1628. * $repo->set_option(array('api_key'=>'f2188bde132', 'name'=>'dongsheng'));
  1629. *
  1630. * @param array $options settings
  1631. * @return bool
  1632. */
  1633. public function set_option($options = array()) {
  1634. global $DB;
  1635. if (!empty($options['name'])) {
  1636. $r = new stdClass();
  1637. $r->id = $this->id;
  1638. $r->name = $options['name'];
  1639. $DB->update_record('repository_instances', $r);
  1640. unset($options['name']);
  1641. }
  1642. foreach ($options as $name=>$value) {
  1643. if ($id = $DB->get_field('repository_instance_config', 'id', array('name'=>$name, 'instanceid'=>$this->id))) {
  1644. $DB->set_field('repository_instance_config', 'value', $value, array('id'=>$id));
  1645. } else {
  1646. $config = new stdClass();
  1647. $config->instanceid = $this->id;
  1648. $config->name = $name;
  1649. $config->value = $value;
  1650. $DB->insert_record('repository_instance_config', $config);
  1651. }
  1652. }
  1653. return true;
  1654. }
  1655. /**
  1656. * Get settings for repository instance
  1657. *
  1658. * @param string $config
  1659. * @return array Settings
  1660. */
  1661. public function get_option($config = '') {
  1662. global $DB;
  1663. $entries = $DB->get_records('repository_instance_config', array('instanceid'=>$this->id));
  1664. $ret = array();
  1665. if (empty($entries)) {
  1666. return $ret;
  1667. }
  1668. foreach($entries as $entry) {
  1669. $ret[$entry->name] = $entry->value;
  1670. }
  1671. if (!empty($config)) {
  1672. if (isset($ret[$config])) {
  1673. return $ret[$config];
  1674. } else {
  1675. return null;
  1676. }
  1677. } else {
  1678. return $ret;
  1679. }
  1680. }
  1681. /**
  1682. * Filter file listing to display specific types
  1683. *
  1684. * @param array $value
  1685. * @return bool
  1686. */
  1687. public function filter(&$value) {
  1688. $accepted_types = optional_param_array('accepted_types', '', PARAM_RAW);
  1689. if (isset($value['children'])) {
  1690. if (!empty($value['children'])) {
  1691. $value['children'] = array_filter($value['children'], array($this, 'filter'));
  1692. }
  1693. return true; // always return directories
  1694. } else {
  1695. if ($accepted_types == '*' or empty($accepted_types)
  1696. or (is_array($accepted_types) and in_array('*', $accepted_types))) {
  1697. return true;
  1698. } else {
  1699. foreach ($accepted_types as $ext) {
  1700. if (preg_match('#'.$ext.'$#i', $value['title'])) {
  1701. return true;
  1702. }
  1703. }
  1704. }
  1705. }
  1706. return false;
  1707. }
  1708. /**
  1709. * Given a path, and perhaps a search, get a list of files.
  1710. *
  1711. * See details on {@link http://docs.moodle.org/dev/Repository_plugins}
  1712. *
  1713. * @param string $path this parameter can a folder name, or a identification of folder
  1714. * @param string $page the page number of file list
  1715. * @return array the list of files, including meta infomation, containing the following keys
  1716. * manage, url to manage url
  1717. * client_id
  1718. * login, login form
  1719. * repo_id, active repository id
  1720. * login_btn_action, the login button action
  1721. * login_btn_label, the login button label
  1722. * total, number of results
  1723. * perpage, items per page
  1724. * page
  1725. * pages, total pages
  1726. * issearchresult, is it a search result?
  1727. * list, file list
  1728. * path, current path and parent path
  1729. */
  1730. public function get_listing($path = '', $page = '') {
  1731. }
  1732. /**
  1733. * Prepares list of files before passing it to AJAX, makes sure data is in the correct
  1734. * format and stores formatted values.
  1735. *
  1736. * @param array|stdClass $listing result of get_listing() or search() or file_get_drafarea_files()
  1737. * @return array
  1738. */
  1739. public static function prepare_listing($listing) {
  1740. global $OUTPUT;
  1741. $defaultfoldericon = $OUTPUT->pix_url(file_folder_icon(24))->out(false);
  1742. // prepare $listing['path'] or $listing->path
  1743. if (is_array($listing) && isset($listing['path']) && is_array($listing['path'])) {
  1744. $path = &$listing['path'];
  1745. } else if (is_object($listing) && isset($listing->path) && is_array($listing->path)) {
  1746. $path = &$listing->path;
  1747. }
  1748. if (isset($path)) {
  1749. $len = count($path);
  1750. for ($i=0; $i<$len; $i++) {
  1751. if (is_array($path[$i]) && !isset($path[$i]['icon'])) {
  1752. $path[$i]['icon'] = $defaultfoldericon;
  1753. } else if (is_object($path[$i]) && !isset($path[$i]->icon)) {
  1754. $path[$i]->icon = $defaultfoldericon;
  1755. }
  1756. }
  1757. }
  1758. // prepare $listing['list'] or $listing->list
  1759. if (is_array($listing) && isset($listing['list']) && is_array($listing['list'])) {
  1760. $listing['list'] = array_values($listing['list']); // convert to array
  1761. $files = &$listing['list'];
  1762. } else if (is_object($listing) && isset($listing->list) && is_array($listing->list)) {
  1763. $listing->list = array_values($listing->list); // convert to array
  1764. $files = &$listing->list;
  1765. } else {
  1766. return $listing;
  1767. }
  1768. $len = count($files);
  1769. for ($i=0; $i<$len; $i++) {
  1770. if (is_object($files[$i])) {
  1771. $file = (array)$files[$i];
  1772. $converttoobject = true;
  1773. } else {
  1774. $file = & $files[$i];
  1775. $converttoobject = false;
  1776. }
  1777. if (isset($file['size'])) {
  1778. $file['size'] = (int)$file['size'];
  1779. $file['size_f'] = display_size($file['size']);
  1780. }
  1781. if (isset($file['license']) &&
  1782. get_string_manager()->string_exists($file['license'], 'license')) {
  1783. $file['license_f'] = get_string($file['license'], 'license');
  1784. }
  1785. if (isset($file['image_width']) && isset($file['image_height'])) {
  1786. $a = array('width' => $file['image_width'], 'height' => $file['image_height']);
  1787. $file['dimensions'] = get_string('imagesize', 'repository', (object)$a);
  1788. }
  1789. foreach (array('date', 'datemodified', 'datecreated') as $key) {
  1790. if (!isset($file[$key]) && isset($file['date'])) {
  1791. $file[$key] = $file['date'];
  1792. }
  1793. if (isset($file[$key])) {
  1794. // must be UNIX timestamp
  1795. $file[$key] = (int)$file[$key];
  1796. if (!$file[$key]) {
  1797. unset($file[$key]);
  1798. } else {
  1799. $file[$key.'_f'] = userdate($file[$key], get_string('strftimedatetime', 'langconfig'));
  1800. $file[$key.'_f_s'] = userdate($file[$key], get_string('strftimedatetimeshort', 'langconfig'));
  1801. }
  1802. }
  1803. }
  1804. $isfolder = (array_key_exists('children', $file) || (isset($file['type']) && $file['type'] == 'folder'));
  1805. $filename = null;
  1806. if (isset($file['title'])) {
  1807. $filename = $file['title'];
  1808. }
  1809. else if (isset($file['fullname'])) {
  1810. $filename = $file['fullname'];
  1811. }
  1812. if (!isset($file['mimetype']) && !$isfolder && $filename) {
  1813. $file['mimetype'] = get_mimetype_description(array('filename' => $filename));
  1814. }
  1815. if (!isset($file['icon'])) {
  1816. if ($isfolder) {
  1817. $file['icon'] = $defaultfoldericon;
  1818. } else if ($filename) {
  1819. $file['icon'] = $OUTPUT->pix_url(file_extension_icon($filename, 24))->out(false);
  1820. }
  1821. }
  1822. if ($converttoobject) {
  1823. $files[$i] = (object)$file;
  1824. }
  1825. }
  1826. return $listing;
  1827. }
  1828. /**
  1829. * Search files in repository
  1830. * When doing global search, $search_text will be used as
  1831. * keyword.
  1832. *
  1833. * @param string $search_text search key word
  1834. * @param int $page page
  1835. * @return mixed {@see repository::get_listing}
  1836. */
  1837. public function search($search_text, $page = 0) {
  1838. $list = array();
  1839. $list['list'] = array();
  1840. return false;
  1841. }
  1842. /**
  1843. * Logout from repository instance
  1844. * By default, this function will return a login form
  1845. *
  1846. * @return string
  1847. */
  1848. public function logout(){
  1849. return $this->print_login();
  1850. }
  1851. /**
  1852. * To check whether the user is logged in.
  1853. *
  1854. * @return bool
  1855. */
  1856. public function check_login(){
  1857. return true;
  1858. }
  1859. /**
  1860. * Show the login screen, if required
  1861. *
  1862. * @return string
  1863. */
  1864. public function print_login(){
  1865. return $this->get_listing();
  1866. }
  1867. /**
  1868. * Show the search screen, if required
  1869. *
  1870. * @return string
  1871. */
  1872. public function print_search() {
  1873. global $PAGE;
  1874. $renderer = $PAGE->get_renderer('core', 'files');
  1875. return $renderer->repository_default_searchform();
  1876. }
  1877. /**
  1878. * For oauth like external authentication, when external repository direct user back to moodle,
  1879. * this funciton will be called to set up token and token_secret
  1880. */
  1881. public function callback() {
  1882. }
  1883. /**
  1884. * is it possible to do glboal search?
  1885. *
  1886. * @return bool
  1887. */
  1888. public function global_search() {
  1889. return false;
  1890. }
  1891. /**
  1892. * Defines operations that happen occasionally on cron
  1893. *
  1894. * @return bool
  1895. */
  1896. public function cron() {
  1897. return true;
  1898. }
  1899. /**
  1900. * function which is run when the type is created (moodle administrator add the plugin)
  1901. *
  1902. * @return bool success or fail?
  1903. */
  1904. public static function plugin_init() {
  1905. return true;
  1906. }
  1907. /**
  1908. * Edit/Create Admin Settings Moodle form
  1909. *
  1910. * @param moodleform $mform Moodle form (passed by reference)
  1911. * @param string $classname repository class name
  1912. */
  1913. public static function type_config_form($mform, $classname = 'repository') {
  1914. $instnaceoptions = call_user_func(array($classname, 'get_instance_option_names'), $mform, $classname);
  1915. if (empty($instnaceoptions)) {
  1916. // this plugin has only one instance
  1917. // so we need to give it a name
  1918. // it can be empty, then moodle will look for instance name from language string
  1919. $mform->addElement('text', 'pluginname', get_string('pluginname', 'repository'), array('size' => '40'));
  1920. $mform->addElement('static', 'pluginnamehelp', '', get_string('pluginnamehelp', 'repository'));
  1921. $mform->setType('pluginname', PARAM_TEXT);
  1922. }
  1923. }
  1924. /**
  1925. * Validate Admin Settings Moodle form
  1926. *
  1927. * @static
  1928. * @param moodleform $mform Moodle form (passed by reference)
  1929. * @param array $data array of ("fieldname"=>value) of submitted data
  1930. * @param array $errors array of ("fieldname"=>errormessage) of errors
  1931. * @return array array of errors
  1932. */
  1933. public static function type_form_validation($mform, $data, $errors) {
  1934. return $errors;
  1935. }
  1936. /**
  1937. * Edit/Create Instance Settings Moodle form
  1938. *
  1939. * @param moodleform $mform Moodle form (passed by reference)
  1940. */
  1941. public static function instance_config_form($mform) {
  1942. }
  1943. /**
  1944. * Return names of the general options.
  1945. * By default: no general option name
  1946. *
  1947. * @return array
  1948. */
  1949. public static function get_type_option_names() {
  1950. return array('pluginname');
  1951. }
  1952. /**
  1953. * Return names of the instance options.
  1954. * By default: no instance option name
  1955. *
  1956. * @return array
  1957. */
  1958. public static function get_instance_option_names() {
  1959. return array();
  1960. }
  1961. /**
  1962. * Validate repository plugin instance form
  1963. *
  1964. * @param moodleform $mform moodle form
  1965. * @param array $data form data
  1966. * @param array $errors errors
  1967. * @return array errors
  1968. */
  1969. public static function instance_form_validation($mform, $data, $errors) {
  1970. return $errors;
  1971. }
  1972. /**
  1973. * Create a shorten filename
  1974. *
  1975. * @param string $str filename
  1976. * @param int $maxlength max file name length
  1977. * @return string short filename
  1978. */
  1979. public function get_short_filename($str, $maxlength) {
  1980. if (textlib::strlen($str) >= $maxlength) {
  1981. return trim(textlib::substr($str, 0, $maxlength)).'...';
  1982. } else {
  1983. return $str;
  1984. }
  1985. }
  1986. /**
  1987. * Overwrite an existing file
  1988. *
  1989. * @param int $itemid
  1990. * @param string $filepath
  1991. * @param string $filename
  1992. * @param string $newfilepath
  1993. * @param string $newfilename
  1994. * @return bool
  1995. */
  1996. public static function overwrite_existing_draftfile($itemid, $filepath, $filename, $newfilepath, $newfilename) {
  1997. global $USER;
  1998. $fs = get_file_storage();
  1999. $user_context = get_context_instance(CONTEXT_USER, $USER->id);
  2000. if ($file = $fs->get_file($user_context->id, 'user', 'draft', $itemid, $filepath, $filename)) {
  2001. if ($tempfile = $fs->get_file($user_context->id, 'user', 'draft', $itemid, $newfilepath, $newfilename)) {
  2002. // delete existing file to release filename
  2003. $file->delete();
  2004. // create new file
  2005. $newfile = $fs->create_file_from_storedfile(array('filepath'=>$filepath, 'filename'=>$filename), $tempfile);
  2006. // remove temp file
  2007. $tempfile->delete();
  2008. return true;
  2009. }
  2010. }
  2011. return false;
  2012. }
  2013. /**
  2014. * Delete a temp file from draft area
  2015. *
  2016. * @param int $draftitemid
  2017. * @param string $filepath
  2018. * @param string $filename
  2019. * @return bool
  2020. */
  2021. public static function delete_tempfile_from_draft($draftitemid, $filepath, $filename) {
  2022. global $USER;
  2023. $fs = get_file_storage();
  2024. $user_context = get_context_instance(CONTEXT_USER, $USER->id);
  2025. if ($file = $fs->get_file($user_context->id, 'user', 'draft', $draftitemid, $filepath, $filename)) {
  2026. $file->delete();
  2027. return true;
  2028. } else {
  2029. return false;
  2030. }
  2031. }
  2032. /**
  2033. * Find all external files in this repo and import them
  2034. */
  2035. public function convert_references_to_local() {
  2036. $fs = get_file_storage();
  2037. $files = $fs->get_external_files($this->id);
  2038. foreach ($files as $storedfile) {
  2039. $fs->import_external_file($storedfile);
  2040. }
  2041. }
  2042. /**
  2043. * Called from phpunit between tests, resets whatever was cached
  2044. */
  2045. public static function reset_caches() {
  2046. self::sync_external_file(null, true);
  2047. }
  2048. /**
  2049. * Call to request proxy file sync with repository source.
  2050. *
  2051. * @param stored_file $file
  2052. * @param bool $resetsynchistory whether to reset all history of sync (used by phpunit)
  2053. * @return bool success
  2054. */
  2055. public static function sync_external_file($file, $resetsynchistory = false) {
  2056. global $DB;
  2057. // TODO MDL-25290 static should be replaced with MUC code.
  2058. static $synchronized = array();
  2059. if ($resetsynchistory) {
  2060. $synchronized = array();
  2061. }
  2062. $fs = get_file_storage();
  2063. if (!$file || !$file->get_referencefileid()) {
  2064. return false;
  2065. }
  2066. if (array_key_exists($file->get_id(), $synchronized)) {
  2067. return $synchronized[$file->get_id()];
  2068. }
  2069. // remember that we already cached in current request to prevent from querying again
  2070. $synchronized[$file->get_id()] = false;
  2071. if (!$reference = $DB->get_record('files_reference', array('id'=>$file->get_referencefileid()))) {
  2072. return false;
  2073. }
  2074. if (!empty($reference->lastsync) and ($reference->lastsync + $reference->lifetime > time())) {
  2075. $synchronized[$file->get_id()] = true;
  2076. return true;
  2077. }
  2078. if (!$repository = self::get_repository_by_id($reference->repositoryid, SYSCONTEXTID)) {
  2079. return false;
  2080. }
  2081. if (!$repository->sync_individual_file($file)) {
  2082. return false;
  2083. }
  2084. $fileinfo = $repository->get_file_by_reference($reference);
  2085. if ($fileinfo === null) {
  2086. // does not exist any more - set status to missing
  2087. $file->set_missingsource();
  2088. //TODO: purge content from pool if we set some other content hash and it is no used any more
  2089. $synchronized[$file->get_id()] = true;
  2090. return true;
  2091. }
  2092. $contenthash = null;
  2093. $filesize = null;
  2094. if (!empty($fileinfo->contenthash)) {
  2095. // contenthash returned, file already in moodle
  2096. $contenthash = $fileinfo->contenthash;
  2097. $filesize = $fileinfo->filesize;
  2098. } else if (!empty($fileinfo->filepath)) {
  2099. // File path returned
  2100. list($contenthash, $filesize, $newfile) = $fs->add_file_to_pool($fileinfo->filepath);
  2101. } else if (!empty($fileinfo->handle) && is_resource($fileinfo->handle)) {
  2102. // File handle returned
  2103. $contents = '';
  2104. while (!feof($fileinfo->handle)) {
  2105. $contents .= fread($handle, 8192);
  2106. }
  2107. fclose($fileinfo->handle);
  2108. list($contenthash, $filesize, $newfile) = $fs->add_string_to_pool($content);
  2109. } else if (isset($fileinfo->content)) {
  2110. // File content returned
  2111. list($contenthash, $filesize, $newfile) = $fs->add_string_to_pool($fileinfo->content);
  2112. }
  2113. if (!isset($contenthash) or !isset($filesize)) {
  2114. return false;
  2115. }
  2116. // update files table
  2117. $file->set_synchronized($contenthash, $filesize);
  2118. $synchronized[$file->get_id()] = true;
  2119. return true;
  2120. }
  2121. /**
  2122. * Build draft file's source field
  2123. *
  2124. * {@link file_restore_source_field_from_draft_file()}
  2125. * XXX: This is a hack for file manager (MDL-28666)
  2126. * For newly created draft files we have to construct
  2127. * source filed in php serialized data format.
  2128. * File manager needs to know the original file information before copying
  2129. * to draft area, so we append these information in mdl_files.source field
  2130. *
  2131. * @param string $source
  2132. * @return string serialised source field
  2133. */
  2134. public static function build_source_field($source) {
  2135. $sourcefield = new stdClass;
  2136. $sourcefield->source = $source;
  2137. return serialize($sourcefield);
  2138. }
  2139. }
  2140. /**
  2141. * Exception class for repository api
  2142. *
  2143. * @since 2.0
  2144. * @package repository
  2145. * @category repository
  2146. * @copyright 2009 Dongsheng Cai {@link http://dongsheng.org}
  2147. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  2148. */
  2149. class repository_exception extends moodle_exception {
  2150. }
  2151. /**
  2152. * This is a class used to define a repository instance form
  2153. *
  2154. * @since 2.0
  2155. * @package repository
  2156. * @category repository
  2157. * @copyright 2009 Dongsheng Cai {@link http://dongsheng.org}
  2158. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  2159. */
  2160. final class repository_instance_form extends moodleform {
  2161. /** @var stdClass repository instance */
  2162. protected $instance;
  2163. /** @var string repository plugin type */
  2164. protected $plugin;
  2165. /**
  2166. * Added defaults to moodle form
  2167. */
  2168. protected function add_defaults() {
  2169. $mform =& $this->_form;
  2170. $strrequired = get_string('required');
  2171. $mform->addElement('hidden', 'edit', ($this->instance) ? $this->instance->id : 0);
  2172. $mform->setType('edit', PARAM_INT);
  2173. $mform->addElement('hidden', 'new', $this->plugin);
  2174. $mform->setType('new', PARAM_FORMAT);
  2175. $mform->addElement('hidden', 'plugin', $this->plugin);
  2176. $mform->setType('plugin', PARAM_PLUGIN);
  2177. $mform->addElement('hidden', 'typeid', $this->typeid);
  2178. $mform->setType('typeid', PARAM_INT);
  2179. $mform->addElement('hidden', 'contextid', $this->contextid);
  2180. $mform->setType('contextid', PARAM_INT);
  2181. $mform->addElement('text', 'name', get_string('name'), 'maxlength="100" size="30"');
  2182. $mform->addRule('name', $strrequired, 'required', null, 'client');
  2183. $mform->setType('name', PARAM_TEXT);
  2184. }
  2185. /**
  2186. * Define moodle form elements
  2187. */
  2188. public function definition() {
  2189. global $CFG;
  2190. // type of plugin, string
  2191. $this->plugin = $this->_customdata['plugin'];
  2192. $this->typeid = $this->_customdata['typeid'];
  2193. $this->contextid = $this->_customdata['contextid'];
  2194. $this->instance = (isset($this->_customdata['instance'])
  2195. && is_subclass_of($this->_customdata['instance'], 'repository'))
  2196. ? $this->_customdata['instance'] : null;
  2197. $mform =& $this->_form;
  2198. $this->add_defaults();
  2199. // Add instance config options.
  2200. $result = repository::static_function($this->plugin, 'instance_config_form', $mform);
  2201. if ($result === false) {
  2202. // Remove the name element if no other config options.
  2203. $mform->removeElement('name');
  2204. }
  2205. if ($this->instance) {
  2206. $data = array();
  2207. $data['name'] = $this->instance->name;
  2208. if (!$this->instance->readonly) {
  2209. // and set the data if we have some.
  2210. foreach ($this->instance->get_instance_option_names() as $config) {
  2211. if (!empty($this->instance->options[$config])) {
  2212. $data[$config] = $this->instance->options[$config];
  2213. } else {
  2214. $data[$config] = '';
  2215. }
  2216. }
  2217. }
  2218. $this->set_data($data);
  2219. }
  2220. if ($result === false) {
  2221. $mform->addElement('cancel');
  2222. } else {
  2223. $this->add_action_buttons(true, get_string('save','repository'));
  2224. }
  2225. }
  2226. /**
  2227. * Validate moodle form data
  2228. *
  2229. * @param array $data form data
  2230. * @param array $files files in form
  2231. * @return array errors
  2232. */
  2233. public function validation($data, $files) {
  2234. global $DB;
  2235. $errors = array();
  2236. $plugin = $this->_customdata['plugin'];
  2237. $instance = (isset($this->_customdata['instance'])
  2238. && is_subclass_of($this->_customdata['instance'], 'repository'))
  2239. ? $this->_customdata['instance'] : null;
  2240. if (!$instance) {
  2241. $errors = repository::static_function($plugin, 'instance_form_validation', $this, $data, $errors);
  2242. } else {
  2243. $errors = $instance->instance_form_validation($this, $data, $errors);
  2244. }
  2245. $sql = "SELECT count('x')
  2246. FROM {repository_instances} i, {repository} r
  2247. WHERE r.type=:plugin AND r.id=i.typeid AND i.name=:name";
  2248. if ($DB->count_records_sql($sql, array('name' => $data['name'], 'plugin' => $data['plugin'])) > 1) {
  2249. $errors['name'] = get_string('erroruniquename', 'repository');
  2250. }
  2251. return $errors;
  2252. }
  2253. }
  2254. /**
  2255. * This is a class used to define a repository type setting form
  2256. *
  2257. * @since 2.0
  2258. * @package repository
  2259. * @category repository
  2260. * @copyright 2009 Dongsheng Cai {@link http://dongsheng.org}
  2261. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  2262. */
  2263. final class repository_type_form extends moodleform {
  2264. /** @var stdClass repository instance */
  2265. protected $instance;
  2266. /** @var string repository plugin name */
  2267. protected $plugin;
  2268. /** @var string action */
  2269. protected $action;
  2270. /**
  2271. * Definition of the moodleform
  2272. */
  2273. public function definition() {
  2274. global $CFG;
  2275. // type of plugin, string
  2276. $this->plugin = $this->_customdata['plugin'];
  2277. $this->instance = (isset($this->_customdata['instance'])
  2278. && is_a($this->_customdata['instance'], 'repository_type'))
  2279. ? $this->_customdata['instance'] : null;
  2280. $this->action = $this->_customdata['action'];
  2281. $this->pluginname = $this->_customdata['pluginname'];
  2282. $mform =& $this->_form;
  2283. $strrequired = get_string('required');
  2284. $mform->addElement('hidden', 'action', $this->action);
  2285. $mform->setType('action', PARAM_TEXT);
  2286. $mform->addElement('hidden', 'repos', $this->plugin);
  2287. $mform->setType('repos', PARAM_PLUGIN);
  2288. // let the plugin add its specific fields
  2289. $classname = 'repository_' . $this->plugin;
  2290. require_once($CFG->dirroot . '/repository/' . $this->plugin . '/lib.php');
  2291. //add "enable course/user instances" checkboxes if multiple instances are allowed
  2292. $instanceoptionnames = repository::static_function($this->plugin, 'get_instance_option_names');
  2293. $result = call_user_func(array($classname, 'type_config_form'), $mform, $classname);
  2294. if (!empty($instanceoptionnames)) {
  2295. $sm = get_string_manager();
  2296. $component = 'repository';
  2297. if ($sm->string_exists('enablecourseinstances', 'repository_' . $this->plugin)) {
  2298. $component .= ('_' . $this->plugin);
  2299. }
  2300. $mform->addElement('checkbox', 'enablecourseinstances', get_string('enablecourseinstances', $component));
  2301. $component = 'repository';
  2302. if ($sm->string_exists('enableuserinstances', 'repository_' . $this->plugin)) {
  2303. $component .= ('_' . $this->plugin);
  2304. }
  2305. $mform->addElement('checkbox', 'enableuserinstances', get_string('enableuserinstances', $component));
  2306. }
  2307. // set the data if we have some.
  2308. if ($this->instance) {
  2309. $data = array();
  2310. $option_names = call_user_func(array($classname,'get_type_option_names'));
  2311. if (!empty($instanceoptionnames)){
  2312. $option_names[] = 'enablecourseinstances';
  2313. $option_names[] = 'enableuserinstances';
  2314. }
  2315. $instanceoptions = $this->instance->get_options();
  2316. foreach ($option_names as $config) {
  2317. if (!empty($instanceoptions[$config])) {
  2318. $data[$config] = $instanceoptions[$config];
  2319. } else {
  2320. $data[$config] = '';
  2321. }
  2322. }
  2323. // XXX: set plugin name for plugins which doesn't have muliti instances
  2324. if (empty($instanceoptionnames)){
  2325. $data['pluginname'] = $this->pluginname;
  2326. }
  2327. $this->set_data($data);
  2328. }
  2329. $this->add_action_buttons(true, get_string('save','repository'));
  2330. }
  2331. /**
  2332. * Validate moodle form data
  2333. *
  2334. * @param array $data moodle form data
  2335. * @param array $files
  2336. * @return array errors
  2337. */
  2338. public function validation($data, $files) {
  2339. $errors = array();
  2340. $plugin = $this->_customdata['plugin'];
  2341. $instance = (isset($this->_customdata['instance'])
  2342. && is_subclass_of($this->_customdata['instance'], 'repository'))
  2343. ? $this->_customdata['instance'] : null;
  2344. if (!$instance) {
  2345. $errors = repository::static_function($plugin, 'type_form_validation', $this, $data, $errors);
  2346. } else {
  2347. $errors = $instance->type_form_validation($this, $data, $errors);
  2348. }
  2349. return $errors;
  2350. }
  2351. }
  2352. /**
  2353. * Generate all options needed by filepicker
  2354. *
  2355. * @param array $args including following keys
  2356. * context
  2357. * accepted_types
  2358. * return_types
  2359. *
  2360. * @return array the list of repository instances, including meta infomation, containing the following keys
  2361. * externallink
  2362. * repositories
  2363. * accepted_types
  2364. */
  2365. function initialise_filepicker($args) {
  2366. global $CFG, $USER, $PAGE, $OUTPUT;
  2367. static $templatesinitialized;
  2368. require_once($CFG->libdir . '/licenselib.php');
  2369. $return = new stdClass();
  2370. $licenses = array();
  2371. if (!empty($CFG->licenses)) {
  2372. $array = explode(',', $CFG->licenses);
  2373. foreach ($array as $license) {
  2374. $l = new stdClass();
  2375. $l->shortname = $license;
  2376. $l->fullname = get_string($license, 'license');
  2377. $licenses[] = $l;
  2378. }
  2379. }
  2380. if (!empty($CFG->sitedefaultlicense)) {
  2381. $return->defaultlicense = $CFG->sitedefaultlicense;
  2382. }
  2383. $return->licenses = $licenses;
  2384. $return->author = fullname($USER);
  2385. if (empty($args->context)) {
  2386. $context = $PAGE->context;
  2387. } else {
  2388. $context = $args->context;
  2389. }
  2390. $disable_types = array();
  2391. if (!empty($args->disable_types)) {
  2392. $disable_types = $args->disable_types;
  2393. }
  2394. $user_context = get_context_instance(CONTEXT_USER, $USER->id);
  2395. list($context, $course, $cm) = get_context_info_array($context->id);
  2396. $contexts = array($user_context, get_system_context());
  2397. if (!empty($course)) {
  2398. // adding course context
  2399. $contexts[] = get_context_instance(CONTEXT_COURSE, $course->id);
  2400. }
  2401. $externallink = (int)get_config(null, 'repositoryallowexternallinks');
  2402. $repositories = repository::get_instances(array(
  2403. 'context'=>$contexts,
  2404. 'currentcontext'=> $context,
  2405. 'accepted_types'=>$args->accepted_types,
  2406. 'return_types'=>$args->return_types,
  2407. 'disable_types'=>$disable_types
  2408. ));
  2409. $return->repositories = array();
  2410. if (empty($externallink)) {
  2411. $return->externallink = false;
  2412. } else {
  2413. $return->externallink = true;
  2414. }
  2415. $return->userprefs = array();
  2416. $return->userprefs['recentrepository'] = get_user_preferences('filepicker_recentrepository', '');
  2417. $return->userprefs['recentlicense'] = get_user_preferences('filepicker_recentlicense', '');
  2418. $return->userprefs['recentviewmode'] = get_user_preferences('filepicker_recentviewmode', '');
  2419. user_preference_allow_ajax_update('filepicker_recentrepository', PARAM_INT);
  2420. user_preference_allow_ajax_update('filepicker_recentlicense', PARAM_SAFEDIR);
  2421. user_preference_allow_ajax_update('filepicker_recentviewmode', PARAM_INT);
  2422. // provided by form element
  2423. $return->accepted_types = file_get_typegroup('extension', $args->accepted_types);
  2424. $return->return_types = $args->return_types;
  2425. foreach ($repositories as $repository) {
  2426. $meta = $repository->get_meta();
  2427. // Please note that the array keys for repositories are used within
  2428. // JavaScript a lot, the key NEEDS to be the repository id.
  2429. $return->repositories[$repository->id] = $meta;
  2430. }
  2431. if (!$templatesinitialized) {
  2432. // we need to send filepicker templates to the browser just once
  2433. $fprenderer = $PAGE->get_renderer('core', 'files');
  2434. $templates = $fprenderer->filepicker_js_templates();
  2435. $PAGE->requires->js_init_call('M.core_filepicker.set_templates', array($templates), true);
  2436. $templatesinitialized = true;
  2437. }
  2438. return $return;
  2439. }
  2440. /**
  2441. * Small function to walk an array to attach repository ID
  2442. *
  2443. * @param array $value
  2444. * @param string $key
  2445. * @param int $id
  2446. */
  2447. function repository_attach_id(&$value, $key, $id){
  2448. $value['repo_id'] = $id;
  2449. }