PageRenderTime 36ms CodeModel.GetById 8ms RepoModel.GetById 0ms app.codeStats 0ms

/repository/equella/lib.php

https://bitbucket.org/moodle/moodle
PHP | 439 lines | 241 code | 40 blank | 158 comment | 47 complexity | 86d05db418f0f245e1332020f3133483 MD5 | raw file
Possible License(s): Apache-2.0, LGPL-2.1, BSD-3-Clause, MIT, GPL-3.0
  1. <?php
  2. // This file is part of Moodle - http://moodle.org/
  3. //
  4. // Moodle is free software: you can redistribute it and/or modify
  5. // it under the terms of the GNU General Public License as published by
  6. // the Free Software Foundation, either version 3 of the License, or
  7. // (at your option) any later version.
  8. //
  9. // Moodle is distributed in the hope that it will be useful,
  10. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. // GNU General Public License for more details.
  13. //
  14. // You should have received a copy of the GNU General Public License
  15. // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
  16. /**
  17. * This plugin is used to access equella repositories.
  18. *
  19. * @since Moodle 2.3
  20. * @package repository_equella
  21. * @copyright 2012 Dongsheng Cai {@link http://dongsheng.org}
  22. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  23. */
  24. defined('MOODLE_INTERNAL') || die();
  25. require_once($CFG->dirroot . '/repository/lib.php');
  26. /**
  27. * repository_equella class implements equella_client
  28. *
  29. * @since Moodle 2.3
  30. * @package repository_equella
  31. * @copyright 2012 Dongsheng Cai {@link http://dongsheng.org}
  32. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  33. */
  34. class repository_equella extends repository {
  35. /** @var array mimetype filter */
  36. private $mimetypes = array();
  37. /**
  38. * Constructor
  39. *
  40. * @param int $repositoryid repository instance id
  41. * @param int|stdClass $context a context id or context object
  42. * @param array $options repository options
  43. */
  44. public function __construct($repositoryid, $context = SYSCONTEXTID, $options = array()) {
  45. parent::__construct($repositoryid, $context, $options);
  46. if (isset($this->options['mimetypes'])) {
  47. $mt = $this->options['mimetypes'];
  48. if (!empty($mt) && is_array($mt) && !in_array('*', $mt)) {
  49. $this->mimetypes = array_unique(array_map(array($this, 'to_mime_type'), $mt));
  50. }
  51. }
  52. }
  53. /**
  54. * Display embedded equella interface
  55. *
  56. * @param string $path
  57. * @param mixed $page
  58. * @return array
  59. */
  60. public function get_listing($path = null, $page = null) {
  61. global $COURSE;
  62. $callbackurl = new moodle_url('/repository/equella/callback.php', array('repo_id'=>$this->id));
  63. $mimetypesstr = '';
  64. $restrict = '';
  65. if (!empty($this->mimetypes)) {
  66. $mimetypesstr = '&mimeTypes=' . implode(',', $this->mimetypes);
  67. // We're restricting to a mime type, so we always restrict to selecting resources only.
  68. $restrict = '&attachmentonly=true';
  69. } else if ($this->get_option('equella_select_restriction') != 'none') {
  70. // The option value matches the EQUELLA paramter name.
  71. $restrict = '&' . $this->get_option('equella_select_restriction') . '=true';
  72. }
  73. $url = $this->get_option('equella_url')
  74. . '?method=lms'
  75. . '&returnurl='.urlencode($callbackurl)
  76. . '&returnprefix=tle'
  77. . '&template=standard'
  78. . '&token='.urlencode($this->getssotoken('write'))
  79. . '&courseId='.urlencode($COURSE->idnumber)
  80. . '&courseCode='.urlencode($COURSE->shortname)
  81. . '&action=searchThin'
  82. . '&forcePost=true'
  83. . '&cancelDisabled=true'
  84. . '&attachmentUuidUrls=true'
  85. . '&options='.urlencode($this->get_option('equella_options') . $mimetypesstr)
  86. . $restrict;
  87. $manageurl = $this->get_option('equella_url');
  88. $manageurl = str_ireplace('signon.do', 'logon.do', $manageurl);
  89. $manageurl = $this->appendtoken($manageurl);
  90. $list = array();
  91. $list['object'] = array();
  92. $list['object']['type'] = 'text/html';
  93. $list['object']['src'] = $url;
  94. $list['nologin'] = true;
  95. $list['nosearch'] = true;
  96. $list['norefresh'] = true;
  97. $list['manage'] = $manageurl;
  98. return $list;
  99. }
  100. /**
  101. * Supported equella file types
  102. *
  103. * @return int
  104. */
  105. public function supported_returntypes() {
  106. return (FILE_INTERNAL | FILE_REFERENCE);
  107. }
  108. /**
  109. * Prepare file reference information
  110. *
  111. * @param string $source
  112. * @return string file referece
  113. */
  114. public function get_file_reference($source) {
  115. // Internally we store serialized value but user input is json-encoded for security reasons.
  116. $ref = json_decode(base64_decode($source));
  117. $filename = clean_param($ref->filename, PARAM_FILE);
  118. $url = clean_param($ref->url, PARAM_URL);
  119. return base64_encode(serialize((object)array('url' => $url, 'filename' => $filename)));
  120. }
  121. /**
  122. * Counts the number of failed connections.
  123. *
  124. * If we received the connection timeout more than 3 times in a row, we don't attemt to
  125. * connect to the server any more during this request.
  126. *
  127. * This function is used by {@link repository_equella::sync_reference()} that
  128. * synchronises the file size of referenced files.
  129. *
  130. * @param int $errno omit if we just want to know the return value, the last curl_errno otherwise
  131. * @return bool true if we had less than 3 failed connections, false if no more connections
  132. * attempts recommended
  133. */
  134. private function connection_result($errno = null) {
  135. static $countfailures = array();
  136. $sess = sesskey();
  137. if (!array_key_exists($sess, $countfailures)) {
  138. $countfailures[$sess] = 0;
  139. }
  140. if ($errno !== null) {
  141. if ($errno == 0) {
  142. // reset count of failed connections
  143. $countfailures[$sess] = 0;
  144. } else if ($errno == 7 /*CURLE_COULDNT_CONNECT*/ || $errno == 9 /*CURLE_REMOTE_ACCESS_DENIED*/) {
  145. // problems with server
  146. $countfailures[$sess]++;
  147. }
  148. }
  149. return ($countfailures[$sess] < 3);
  150. }
  151. /**
  152. * Download a file, this function can be overridden by subclass. {@link curl}
  153. *
  154. * @param string $reference the source of the file
  155. * @param string $filename filename (without path) to save the downloaded file in the
  156. * temporary directory
  157. * @return null|array null if download failed or array with elements:
  158. * path: internal location of the file
  159. * url: URL to the source (from parameters)
  160. */
  161. public function get_file($reference, $filename = '') {
  162. global $USER, $CFG;
  163. $ref = @unserialize(base64_decode($reference));
  164. if (!isset($ref->url) || !($url = $this->appendtoken($ref->url))) {
  165. // Occurs when the user isn't known..
  166. return null;
  167. }
  168. $path = $this->prepare_file($filename);
  169. $cookiepathname = $this->prepare_file($USER->id. '_'. uniqid('', true). '.cookie');
  170. $c = new curl(array('cookie'=>$cookiepathname));
  171. $result = $c->download_one($url, null, array('filepath' => $path, 'followlocation' => true, 'timeout' => $CFG->repositorygetfiletimeout));
  172. // Delete cookie jar.
  173. if (file_exists($cookiepathname)) {
  174. unlink($cookiepathname);
  175. }
  176. if ($result !== true) {
  177. throw new moodle_exception('errorwhiledownload', 'repository', '', $result);
  178. }
  179. return array('path'=>$path, 'url'=>$url);
  180. }
  181. public function sync_reference(stored_file $file) {
  182. global $USER, $CFG;
  183. if ($file->get_referencelastsync() + DAYSECS > time() || !$this->connection_result()) {
  184. // Synchronise not more often than once a day.
  185. // if we had several unsuccessfull attempts to connect to server - do not try any more.
  186. return false;
  187. }
  188. $ref = @unserialize(base64_decode($file->get_reference()));
  189. if (!isset($ref->url) || !($url = $this->appendtoken($ref->url))) {
  190. // Occurs when the user isn't known..
  191. $file->set_missingsource();
  192. return true;
  193. }
  194. $cookiepathname = $this->prepare_file($USER->id. '_'. uniqid('', true). '.cookie');
  195. $c = new curl(array('cookie' => $cookiepathname));
  196. if (file_extension_in_typegroup($ref->filename, 'web_image')) {
  197. $path = $this->prepare_file('');
  198. $result = $c->download_one($url, null, array('filepath' => $path, 'followlocation' => true, 'timeout' => $CFG->repositorysyncimagetimeout));
  199. if ($result === true) {
  200. $file->set_synchronised_content_from_file($path);
  201. return true;
  202. }
  203. } else {
  204. $result = $c->head($url, array('followlocation' => true, 'timeout' => $CFG->repositorysyncfiletimeout));
  205. }
  206. // Delete cookie jar.
  207. if (file_exists($cookiepathname)) {
  208. unlink($cookiepathname);
  209. }
  210. $this->connection_result($c->get_errno());
  211. $curlinfo = $c->get_info();
  212. if (isset($curlinfo['http_code']) && $curlinfo['http_code'] == 200
  213. && array_key_exists('download_content_length', $curlinfo)
  214. && $curlinfo['download_content_length'] >= 0) {
  215. // we received a correct header and at least can tell the file size
  216. $file->set_synchronized(null, $curlinfo['download_content_length']);
  217. return true;
  218. }
  219. $file->set_missingsource();
  220. return true;
  221. }
  222. /**
  223. * Repository method to serve the referenced file
  224. *
  225. * @param stored_file $storedfile the file that contains the reference
  226. * @param int $lifetime Number of seconds before the file should expire from caches (null means $CFG->filelifetime)
  227. * @param int $filter 0 (default)=no filtering, 1=all files, 2=html files only
  228. * @param bool $forcedownload If true (default false), forces download of file rather than view in browser/plugin
  229. * @param array $options additional options affecting the file serving
  230. */
  231. public function send_file($stored_file, $lifetime=null , $filter=0, $forcedownload=false, array $options = null) {
  232. $reference = unserialize(base64_decode($stored_file->get_reference()));
  233. $url = $this->appendtoken($reference->url);
  234. if ($url) {
  235. header('Location: ' . $url);
  236. } else {
  237. send_file_not_found();
  238. }
  239. }
  240. /**
  241. * Add Instance settings input to Moodle form
  242. *
  243. * @param moodleform $mform
  244. */
  245. public static function instance_config_form($mform) {
  246. $mform->addElement('text', 'equella_url', get_string('equellaurl', 'repository_equella'));
  247. $mform->setType('equella_url', PARAM_URL);
  248. $strrequired = get_string('required');
  249. $mform->addRule('equella_url', $strrequired, 'required', null, 'client');
  250. $mform->addElement('text', 'equella_options', get_string('equellaoptions', 'repository_equella'));
  251. $mform->setType('equella_options', PARAM_NOTAGS);
  252. $choices = array(
  253. 'none' => get_string('restrictionnone', 'repository_equella'),
  254. 'itemonly' => get_string('restrictionitemsonly', 'repository_equella'),
  255. 'attachmentonly' => get_string('restrictionattachmentsonly', 'repository_equella'),
  256. );
  257. $mform->addElement('select', 'equella_select_restriction', get_string('selectrestriction', 'repository_equella'), $choices);
  258. $mform->addElement('header', 'groupheader',
  259. get_string('group', 'repository_equella', get_string('groupdefault', 'repository_equella')));
  260. $mform->addElement('text', 'equella_shareid', get_string('sharedid', 'repository_equella'));
  261. $mform->setType('equella_shareid', PARAM_RAW);
  262. $mform->addRule('equella_shareid', $strrequired, 'required', null, 'client');
  263. $mform->addElement('text', 'equella_sharedsecret', get_string('sharedsecrets', 'repository_equella'));
  264. $mform->setType('equella_sharedsecret', PARAM_RAW);
  265. $mform->addRule('equella_sharedsecret', $strrequired, 'required', null, 'client');
  266. foreach (self::get_all_editing_roles() as $role) {
  267. $mform->addElement('header', 'groupheader_'.$role->shortname, get_string('group', 'repository_equella',
  268. role_get_name($role)));
  269. $mform->addElement('text', "equella_{$role->shortname}_shareid", get_string('sharedid', 'repository_equella'));
  270. $mform->setType("equella_{$role->shortname}_shareid", PARAM_RAW);
  271. $mform->addElement('text', "equella_{$role->shortname}_sharedsecret",
  272. get_string('sharedsecrets', 'repository_equella'));
  273. $mform->setType("equella_{$role->shortname}_sharedsecret", PARAM_RAW);
  274. }
  275. }
  276. /**
  277. * Names of the instance settings
  278. *
  279. * @return array
  280. */
  281. public static function get_instance_option_names() {
  282. $rv = array('equella_url', 'equella_select_restriction', 'equella_options',
  283. 'equella_shareid', 'equella_sharedsecret'
  284. );
  285. foreach (self::get_all_editing_roles() as $role) {
  286. array_push($rv, "equella_{$role->shortname}_shareid");
  287. array_push($rv, "equella_{$role->shortname}_sharedsecret");
  288. }
  289. return $rv;
  290. }
  291. /**
  292. * Generate equella token
  293. *
  294. * @param string $username
  295. * @param string $shareid
  296. * @param string $sharedsecret
  297. * @return string
  298. */
  299. private static function getssotoken_raw($username, $shareid, $sharedsecret) {
  300. $time = time() . '000';
  301. return urlencode($username)
  302. . ':'
  303. . $shareid
  304. . ':'
  305. . $time
  306. . ':'
  307. . base64_encode(pack('H*', md5($username . $shareid . $time . $sharedsecret)));
  308. }
  309. /**
  310. * Append token
  311. *
  312. * @param string $url
  313. * @param $readwrite
  314. * @return string
  315. */
  316. private function appendtoken($url, $readwrite = null) {
  317. $ssotoken = $this->getssotoken($readwrite);
  318. if (!$ssotoken) {
  319. return false;
  320. }
  321. return $url . (strpos($url, '?') != false ? '&' : '?') . 'token=' . urlencode($ssotoken);
  322. }
  323. /**
  324. * Generate equella sso token
  325. *
  326. * @param string $readwrite
  327. * @return string
  328. */
  329. private function getssotoken($readwrite = 'read') {
  330. global $USER;
  331. if (empty($USER->username)) {
  332. return false;
  333. }
  334. if ($readwrite == 'write') {
  335. foreach (self::get_all_editing_roles() as $role) {
  336. if (user_has_role_assignment($USER->id, $role->id, $this->context->id)) {
  337. // See if the user has a role that is linked to an equella role.
  338. $shareid = $this->get_option("equella_{$role->shortname}_shareid");
  339. if (!empty($shareid)) {
  340. return $this->getssotoken_raw($USER->username, $shareid,
  341. $this->get_option("equella_{$role->shortname}_sharedsecret"));
  342. }
  343. }
  344. }
  345. }
  346. // If we are only reading, use the unadorned shareid and secret.
  347. $shareid = $this->get_option('equella_shareid');
  348. if (!empty($shareid)) {
  349. return $this->getssotoken_raw($USER->username, $shareid, $this->get_option('equella_sharedsecret'));
  350. }
  351. }
  352. private static function get_all_editing_roles() {
  353. return get_roles_with_capability('moodle/course:manageactivities', CAP_ALLOW);
  354. }
  355. /**
  356. * Convert moodle mimetypes list to equella format
  357. *
  358. * @param string $value
  359. * @return string
  360. */
  361. private static function to_mime_type($value) {
  362. return mimeinfo('type', $value);
  363. }
  364. /**
  365. * Return the source information
  366. *
  367. * @param string $source
  368. * @return string|null
  369. */
  370. public function get_file_source_info($source) {
  371. $ref = json_decode(base64_decode($source));
  372. $filename = clean_param($ref->filename, PARAM_FILE);
  373. return 'EQUELLA: ' . $filename;
  374. }
  375. /**
  376. * Return human readable reference information
  377. * {@link stored_file::get_reference()}
  378. *
  379. * @param string $reference
  380. * @param int $filestatus status of the file, 0 - ok, 666 - source missing
  381. * @return string
  382. */
  383. public function get_reference_details($reference, $filestatus = 0) {
  384. if (!$filestatus) {
  385. $ref = unserialize(base64_decode($reference));
  386. return $this->get_name(). ': '. $ref->filename;
  387. } else {
  388. return get_string('lostsource', 'repository', '');
  389. }
  390. }
  391. /**
  392. * Is this repository accessing private data?
  393. *
  394. * @return bool
  395. */
  396. public function contains_private_data() {
  397. return false;
  398. }
  399. }