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

/repository/equella/lib.php

https://bitbucket.org/synergylearning/campusconnect
PHP | 441 lines | 243 code | 40 blank | 158 comment | 47 complexity | 898462b32df6a5325acd6011b8973db9 MD5 | raw file
Possible License(s): MPL-2.0-no-copyleft-exception, LGPL-3.0, GPL-3.0, LGPL-2.1, Apache-2.0, BSD-3-Clause, AGPL-3.0
  1. <?php
  2. // This file is part of Moodle - http://moodle.org/
  3. //
  4. // Moodle is free software: you can redistribute it and/or modify
  5. // it under the terms of the GNU General Public License as published by
  6. // the Free Software Foundation, either version 3 of the License, or
  7. // (at your option) any later version.
  8. //
  9. // Moodle is distributed in the hope that it will be useful,
  10. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. // GNU General Public License for more details.
  13. //
  14. // You should have received a copy of the GNU General Public License
  15. // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
  16. /**
  17. * This plugin is used to access equella repositories.
  18. *
  19. * @since 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 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_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;
  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' => self::GETFILE_TIMEOUT));
  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;
  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' => self::SYNCIMAGE_TIMEOUT));
  199. if ($result === true) {
  200. $fs = get_file_storage();
  201. list($contenthash, $filesize, $newfile) = $fs->add_file_to_pool($path);
  202. $file->set_synchronized($contenthash, $filesize);
  203. return true;
  204. }
  205. } else {
  206. $result = $c->head($url, array('followlocation' => true, 'timeout' => self::SYNCFILE_TIMEOUT));
  207. }
  208. // Delete cookie jar.
  209. if (file_exists($cookiepathname)) {
  210. unlink($cookiepathname);
  211. }
  212. $this->connection_result($c->get_errno());
  213. $curlinfo = $c->get_info();
  214. if (isset($curlinfo['http_code']) && $curlinfo['http_code'] == 200
  215. && array_key_exists('download_content_length', $curlinfo)
  216. && $curlinfo['download_content_length'] >= 0) {
  217. // we received a correct header and at least can tell the file size
  218. $file->set_synchronized(null, $curlinfo['download_content_length']);
  219. return true;
  220. }
  221. $file->set_missingsource();
  222. return true;
  223. }
  224. /**
  225. * Repository method to serve the referenced file
  226. *
  227. * @param stored_file $storedfile the file that contains the reference
  228. * @param int $lifetime Number of seconds before the file should expire from caches (null means $CFG->filelifetime)
  229. * @param int $filter 0 (default)=no filtering, 1=all files, 2=html files only
  230. * @param bool $forcedownload If true (default false), forces download of file rather than view in browser/plugin
  231. * @param array $options additional options affecting the file serving
  232. */
  233. public function send_file($stored_file, $lifetime=null , $filter=0, $forcedownload=false, array $options = null) {
  234. $reference = unserialize(base64_decode($stored_file->get_reference()));
  235. $url = $this->appendtoken($reference->url);
  236. if ($url) {
  237. header('Location: ' . $url);
  238. } else {
  239. send_file_not_found();
  240. }
  241. }
  242. /**
  243. * Add Instance settings input to Moodle form
  244. *
  245. * @param moodleform $mform
  246. */
  247. public static function instance_config_form($mform) {
  248. $mform->addElement('text', 'equella_url', get_string('equellaurl', 'repository_equella'));
  249. $mform->setType('equella_url', PARAM_URL);
  250. $strrequired = get_string('required');
  251. $mform->addRule('equella_url', $strrequired, 'required', null, 'client');
  252. $mform->addElement('text', 'equella_options', get_string('equellaoptions', 'repository_equella'));
  253. $mform->setType('equella_options', PARAM_NOTAGS);
  254. $choices = array(
  255. 'none' => get_string('restrictionnone', 'repository_equella'),
  256. 'itemonly' => get_string('restrictionitemsonly', 'repository_equella'),
  257. 'attachmentonly' => get_string('restrictionattachmentsonly', 'repository_equella'),
  258. );
  259. $mform->addElement('select', 'equella_select_restriction', get_string('selectrestriction', 'repository_equella'), $choices);
  260. $mform->addElement('header', 'groupheader',
  261. get_string('group', 'repository_equella', get_string('groupdefault', 'repository_equella')));
  262. $mform->addElement('text', 'equella_shareid', get_string('sharedid', 'repository_equella'));
  263. $mform->setType('equella_shareid', PARAM_RAW);
  264. $mform->addRule('equella_shareid', $strrequired, 'required', null, 'client');
  265. $mform->addElement('text', 'equella_sharedsecret', get_string('sharedsecrets', 'repository_equella'));
  266. $mform->setType('equella_sharedsecret', PARAM_RAW);
  267. $mform->addRule('equella_sharedsecret', $strrequired, 'required', null, 'client');
  268. foreach (self::get_all_editing_roles() as $role) {
  269. $mform->addElement('header', 'groupheader_'.$role->shortname, get_string('group', 'repository_equella',
  270. format_string($role->name)));
  271. $mform->addElement('text', "equella_{$role->shortname}_shareid", get_string('sharedid', 'repository_equella'));
  272. $mform->setType("equella_{$role->shortname}_shareid", PARAM_RAW);
  273. $mform->addElement('text', "equella_{$role->shortname}_sharedsecret",
  274. get_string('sharedsecrets', 'repository_equella'));
  275. $mform->setType("equella_{$role->shortname}_sharedsecret", PARAM_RAW);
  276. }
  277. }
  278. /**
  279. * Names of the instance settings
  280. *
  281. * @return array
  282. */
  283. public static function get_instance_option_names() {
  284. $rv = array('equella_url', 'equella_select_restriction', 'equella_options',
  285. 'equella_shareid', 'equella_sharedsecret'
  286. );
  287. foreach (self::get_all_editing_roles() as $role) {
  288. array_push($rv, "equella_{$role->shortname}_shareid");
  289. array_push($rv, "equella_{$role->shortname}_sharedsecret");
  290. }
  291. return $rv;
  292. }
  293. /**
  294. * Generate equella token
  295. *
  296. * @param string $username
  297. * @param string $shareid
  298. * @param string $sharedsecret
  299. * @return string
  300. */
  301. private static function getssotoken_raw($username, $shareid, $sharedsecret) {
  302. $time = time() . '000';
  303. return urlencode($username)
  304. . ':'
  305. . $shareid
  306. . ':'
  307. . $time
  308. . ':'
  309. . base64_encode(pack('H*', md5($username . $shareid . $time . $sharedsecret)));
  310. }
  311. /**
  312. * Append token
  313. *
  314. * @param string $url
  315. * @param $readwrite
  316. * @return string
  317. */
  318. private function appendtoken($url, $readwrite = null) {
  319. $ssotoken = $this->getssotoken($readwrite);
  320. if (!$ssotoken) {
  321. return false;
  322. }
  323. return $url . (strpos($url, '?') != false ? '&' : '?') . 'token=' . urlencode($ssotoken);
  324. }
  325. /**
  326. * Generate equella sso token
  327. *
  328. * @param string $readwrite
  329. * @return string
  330. */
  331. private function getssotoken($readwrite = 'read') {
  332. global $USER;
  333. if (empty($USER->username)) {
  334. return false;
  335. }
  336. if ($readwrite == 'write') {
  337. foreach (self::get_all_editing_roles() as $role) {
  338. if (user_has_role_assignment($USER->id, $role->id, $this->context->id)) {
  339. // See if the user has a role that is linked to an equella role.
  340. $shareid = $this->get_option("equella_{$role->shortname}_shareid");
  341. if (!empty($shareid)) {
  342. return $this->getssotoken_raw($USER->username, $shareid,
  343. $this->get_option("equella_{$role->shortname}_sharedsecret"));
  344. }
  345. }
  346. }
  347. }
  348. // If we are only reading, use the unadorned shareid and secret.
  349. $shareid = $this->get_option('equella_shareid');
  350. if (!empty($shareid)) {
  351. return $this->getssotoken_raw($USER->username, $shareid, $this->get_option('equella_sharedsecret'));
  352. }
  353. }
  354. private static function get_all_editing_roles() {
  355. return get_roles_with_capability('moodle/course:manageactivities', CAP_ALLOW);
  356. }
  357. /**
  358. * Convert moodle mimetypes list to equella format
  359. *
  360. * @param string $value
  361. * @return string
  362. */
  363. private static function to_mime_type($value) {
  364. return mimeinfo('type', $value);
  365. }
  366. /**
  367. * Return the source information
  368. *
  369. * @param string $source
  370. * @return string|null
  371. */
  372. public function get_file_source_info($source) {
  373. $ref = json_decode(base64_decode($source));
  374. $filename = clean_param($ref->filename, PARAM_FILE);
  375. return 'EQUELLA: ' . $filename;
  376. }
  377. /**
  378. * Return human readable reference information
  379. * {@link stored_file::get_reference()}
  380. *
  381. * @param string $reference
  382. * @param int $filestatus status of the file, 0 - ok, 666 - source missing
  383. * @return string
  384. */
  385. public function get_reference_details($reference, $filestatus = 0) {
  386. if (!$filestatus) {
  387. $ref = unserialize(base64_decode($reference));
  388. return $this->get_name(). ': '. $ref->filename;
  389. } else {
  390. return get_string('lostsource', 'repository', '');
  391. }
  392. }
  393. /**
  394. * Is this repository accessing private data?
  395. *
  396. * @return bool
  397. */
  398. public function contains_private_data() {
  399. return false;
  400. }
  401. }