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