Merge branch 'MDL-45645_LTIUsernameParam' of https://github.com/moodlerooms/moodle
[moodle.git] / mod / lti / locallib.php
CommitLineData
b9b2e7bb 1<?php
61eb12d4
CS
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//
b9b2e7bb
CS
17// This file is part of BasicLTI4Moodle
18//
19// BasicLTI4Moodle is an IMS BasicLTI (Basic Learning Tools for Interoperability)
20// consumer for Moodle 1.9 and Moodle 2.0. BasicLTI is a IMS Standard that allows web
21// based learning tools to be easily integrated in LMS as native ones. The IMS BasicLTI
22// specification is part of the IMS standard Common Cartridge 1.1 Sakai and other main LMS
23// are already supporting or going to support BasicLTI. This project Implements the consumer
24// for Moodle. Moodle is a Free Open source Learning Management System by Martin Dougiamas.
25// BasicLTI4Moodle is a project iniciated and leaded by Ludo(Marc Alier) and Jordi Piguillem
26// at the GESSI research group at UPC.
27// SimpleLTI consumer for Moodle is an implementation of the early specification of LTI
28// by Charles Severance (Dr Chuck) htp://dr-chuck.com , developed by Jordi Piguillem in a
29// Google Summer of Code 2008 project co-mentored by Charles Severance and Marc Alier.
30//
31// BasicLTI4Moodle is copyright 2009 by Marc Alier Forment, Jordi Piguillem and Nikolas Galanis
32// of the Universitat Politecnica de Catalunya http://www.upc.edu
33// Contact info: Marc Alier Forment granludo @ gmail.com or marc.alier @ upc.edu
b9b2e7bb
CS
34
35/**
61eb12d4 36 * This file contains the library of functions and constants for the lti module
b9b2e7bb 37 *
2b17ec3d 38 * @package mod_lti
61eb12d4 39 * @copyright 2009 Marc Alier, Jordi Piguillem, Nikolas Galanis
b9b2e7bb 40 * marc.alier@upc.edu
61eb12d4
CS
41 * @copyright 2009 Universitat Politecnica de Catalunya http://www.upc.edu
42 * @author Marc Alier
43 * @author Jordi Piguillem
44 * @author Nikolas Galanis
8f45215d 45 * @author Chris Scribner
61eb12d4 46 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
b9b2e7bb
CS
47 */
48
49defined('MOODLE_INTERNAL') || die;
50
fabd4fcf 51// TODO: Switch to core oauthlib once implemented - MDL-30149
795dff01
CS
52use moodle\mod\lti as lti;
53
b9b2e7bb
CS
54require_once($CFG->dirroot.'/mod/lti/OAuth.php');
55
56define('LTI_URL_DOMAIN_REGEX', '/(?:https?:\/\/)?(?:www\.)?([^\/]+)(?:\/|$)/i');
57
58define('LTI_LAUNCH_CONTAINER_DEFAULT', 1);
59define('LTI_LAUNCH_CONTAINER_EMBED', 2);
60define('LTI_LAUNCH_CONTAINER_EMBED_NO_BLOCKS', 3);
61define('LTI_LAUNCH_CONTAINER_WINDOW', 4);
cca9d3f7 62define('LTI_LAUNCH_CONTAINER_REPLACE_MOODLE_WINDOW', 5);
b9b2e7bb
CS
63
64define('LTI_TOOL_STATE_ANY', 0);
65define('LTI_TOOL_STATE_CONFIGURED', 1);
66define('LTI_TOOL_STATE_PENDING', 2);
67define('LTI_TOOL_STATE_REJECTED', 3);
68
69define('LTI_SETTING_NEVER', 0);
70define('LTI_SETTING_ALWAYS', 1);
5e078d62 71define('LTI_SETTING_DELEGATE', 2);
b9b2e7bb
CS
72
73/**
74 * Prints a Basic LTI activity
75 *
76 * $param int $basicltiid Basic LTI activity id
77 */
67ddf847 78function lti_view($instance) {
b9b2e7bb
CS
79 global $PAGE, $CFG;
80
ea04a9f9 81 if (empty($instance->typeid)) {
606ab1a1 82 $tool = lti_get_tool_by_url_match($instance->toolurl, $instance->course);
ea04a9f9 83 if ($tool) {
b9b2e7bb
CS
84 $typeid = $tool->id;
85 } else {
86 $typeid = null;
87 }
88 } else {
89 $typeid = $instance->typeid;
90 }
e27cb316 91
ea04a9f9 92 if ($typeid) {
b9b2e7bb
CS
93 $typeconfig = lti_get_type_config($typeid);
94 } else {
95 //There is no admin configuration for this tool. Use configuration in the lti instance record plus some defaults.
96 $typeconfig = (array)$instance;
e27cb316 97
b9b2e7bb
CS
98 $typeconfig['sendname'] = $instance->instructorchoicesendname;
99 $typeconfig['sendemailaddr'] = $instance->instructorchoicesendemailaddr;
100 $typeconfig['customparameters'] = $instance->instructorcustomparameters;
f4f711d7
CS
101 $typeconfig['acceptgrades'] = $instance->instructorchoiceacceptgrades;
102 $typeconfig['allowroster'] = $instance->instructorchoiceallowroster;
d8d04121 103 $typeconfig['forcessl'] = '0';
b9b2e7bb 104 }
e27cb316 105
b9b2e7bb 106 //Default the organizationid if not specified
ea04a9f9 107 if (empty($typeconfig['organizationid'])) {
b9b2e7bb 108 $urlparts = parse_url($CFG->wwwroot);
e27cb316 109
b9b2e7bb
CS
110 $typeconfig['organizationid'] = $urlparts['host'];
111 }
e27cb316 112
ea04a9f9 113 if (!empty($instance->resourcekey)) {
3dd9ca24 114 $key = $instance->resourcekey;
ea04a9f9 115 } else if (!empty($typeconfig['resourcekey'])) {
3dd9ca24
CS
116 $key = $typeconfig['resourcekey'];
117 } else {
118 $key = '';
119 }
120
ea04a9f9 121 if (!empty($instance->password)) {
3dd9ca24 122 $secret = $instance->password;
ea04a9f9 123 } else if (!empty($typeconfig['password'])) {
3dd9ca24
CS
124 $secret = $typeconfig['password'];
125 } else {
126 $secret = '';
127 }
e27cb316 128
b9b2e7bb 129 $endpoint = !empty($instance->toolurl) ? $instance->toolurl : $typeconfig['toolurl'];
d8d04121 130 $endpoint = trim($endpoint);
e27cb316 131
d8d04121 132 //If the current request is using SSL and a secure tool URL is specified, use it
ea04a9f9 133 if (lti_request_is_using_ssl() && !empty($instance->securetoolurl)) {
d8d04121
CS
134 $endpoint = trim($instance->securetoolurl);
135 }
e27cb316 136
d8d04121 137 //If SSL is forced, use the secure tool url if specified. Otherwise, make sure https is on the normal launch URL.
ea04a9f9
EL
138 if ($typeconfig['forcessl'] == '1') {
139 if (!empty($instance->securetoolurl)) {
d8d04121
CS
140 $endpoint = trim($instance->securetoolurl);
141 }
e27cb316 142
d8d04121
CS
143 $endpoint = lti_ensure_url_is_https($endpoint);
144 } else {
ea04a9f9 145 if (!strstr($endpoint, '://')) {
d8d04121
CS
146 $endpoint = 'http://' . $endpoint;
147 }
f17f4959 148 }
e27cb316 149
d8d04121
CS
150 $orgid = $typeconfig['organizationid'];
151
b9b2e7bb 152 $course = $PAGE->course;
8fa50fdd 153 $requestparams = lti_build_request($instance, $typeconfig, $course, $typeid);
b9b2e7bb 154
3dd9ca24 155 $launchcontainer = lti_get_launch_container($instance, $typeconfig);
c4d80efe 156 $returnurlparams = array('course' => $course->id, 'launch_container' => $launchcontainer, 'instanceid' => $instance->id);
e27cb316 157
3dd9ca24
CS
158 if ( $orgid ) {
159 $requestparams["tool_consumer_instance_guid"] = $orgid;
160 }
8fa50fdd
MN
161 if (!empty($CFG->mod_lti_institution_name)) {
162 $requestparams['tool_consumer_instance_name'] = $CFG->mod_lti_institution_name;
163 } else {
164 $requestparams['tool_consumer_instance_name'] = get_site()->fullname;
165 }
ea04a9f9 166 if (empty($key) || empty($secret)) {
9d57ad17 167 $returnurlparams['unsigned'] = '1';
1706e83b 168 }
6d6bd5f1
EL
169
170 // Add the return URL. We send the launch container along to help us avoid frames-within-frames when the user returns.
1706e83b
CS
171 $url = new moodle_url('/mod/lti/return.php', $returnurlparams);
172 $returnurl = $url->out(false);
e27cb316 173
1706e83b
CS
174 if ($typeconfig['forcessl'] == '1') {
175 $returnurl = lti_ensure_url_is_https($returnurl);
9d57ad17 176 }
6d6bd5f1 177
8fa50fdd
MN
178 $target = null;
179 switch($launchcontainer) {
180 case LTI_LAUNCH_CONTAINER_EMBED:
181 case LTI_LAUNCH_CONTAINER_EMBED_NO_BLOCKS:
182 $target = 'iframe';
183 break;
184 case LTI_LAUNCH_CONTAINER_REPLACE_MOODLE_WINDOW:
185 $target = 'frame';
186 break;
187 case LTI_LAUNCH_CONTAINER_WINDOW:
188 $target = 'window';
189 break;
190 }
191 if (!is_null($target)) {
192 $requestparams['launch_presentation_document_target'] = $target;
193 }
194
1706e83b 195 $requestparams['launch_presentation_return_url'] = $returnurl;
e27cb316 196
d3496e3f
MN
197 // Allow request params to be updated by sub-plugins.
198 $plugins = core_component::get_plugin_list('ltisource');
199 foreach (array_keys($plugins) as $plugin) {
200 $pluginparams = component_callback('ltisource_'.$plugin, 'before_launch',
201 array($instance, $endpoint, $requestparams), array());
202
203 if (!empty($pluginparams) && is_array($pluginparams)) {
204 $requestparams = array_merge($requestparams, $pluginparams);
205 }
206 }
8fa50fdd 207
ea04a9f9 208 if (!empty($key) && !empty($secret)) {
3dd9ca24 209 $parms = lti_sign_parameters($requestparams, $endpoint, "POST", $key, $secret);
533c42ea
MN
210
211 $endpointurl = new moodle_url($endpoint);
212 $endpointparams = $endpointurl->params();
213
214 // Strip querystring params in endpoint url from $parms to avoid duplication.
215 if (!empty($endpointparams) && !empty($parms)) {
216 foreach (array_keys($endpointparams) as $paramname) {
217 if (isset($parms[$paramname])) {
218 unset($parms[$paramname]);
219 }
220 }
221 }
222
3dd9ca24
CS
223 } else {
224 //If no key and secret, do the launch unsigned.
225 $parms = $requestparams;
3dd9ca24 226 }
e27cb316 227
b9b2e7bb 228 $debuglaunch = ( $instance->debuglaunch == 1 );
e27cb316 229
dbb0fec9 230 $content = lti_post_launch_html($parms, $endpoint, $debuglaunch);
e27cb316 231
b9b2e7bb
CS
232 echo $content;
233}
234
8fa50fdd
MN
235/**
236 * Build source ID
237 *
238 * @param int $instanceid
239 * @param int $userid
240 * @param string $servicesalt
241 * @param null|int $typeid
242 * @param null|int $launchid
243 * @return stdClass
244 */
245function lti_build_sourcedid($instanceid, $userid, $servicesalt, $typeid = null, $launchid = null) {
996b0fd9 246 $data = new stdClass();
e27cb316 247
996b0fd9
CS
248 $data->instanceid = $instanceid;
249 $data->userid = $userid;
8fa50fdd 250 $data->typeid = $typeid;
ea04a9f9 251 if (!empty($launchid)) {
f4f711d7
CS
252 $data->launchid = $launchid;
253 } else {
254 $data->launchid = mt_rand();
255 }
996b0fd9
CS
256
257 $json = json_encode($data);
258
259 $hash = hash('sha256', $json . $servicesalt, false);
260
261 $container = new stdClass();
262 $container->data = $data;
263 $container->hash = $hash;
264
265 return $container;
266}
267
b9b2e7bb
CS
268/**
269 * This function builds the request that must be sent to the tool producer
270 *
271 * @param object $instance Basic LTI instance object
272 * @param object $typeconfig Basic LTI tool configuration
273 * @param object $course Course object
8fa50fdd 274 * @param int|null $typeid Basic LTI tool ID
b9b2e7bb
CS
275 *
276 * @return array $request Request details
277 */
8fa50fdd 278function lti_build_request($instance, $typeconfig, $course, $typeid = null) {
b9b2e7bb
CS
279 global $USER, $CFG;
280
ea04a9f9 281 if (empty($instance->cmid)) {
16cac566
CS
282 $instance->cmid = 0;
283 }
e27cb316 284
1d4f052e 285 $role = lti_get_ims_role($USER, $instance->cmid, $instance->course);
b9b2e7bb 286
b9b2e7bb 287 $requestparams = array(
34eb0501
CS
288 'resource_link_id' => $instance->id,
289 'resource_link_title' => $instance->name,
290 'resource_link_description' => $instance->intro,
291 'user_id' => $USER->id,
292 'roles' => $role,
293 'context_id' => $course->id,
294 'context_label' => $course->shortname,
295 'context_title' => $course->fullname,
2a457227 296 'launch_presentation_locale' => current_language()
b9b2e7bb
CS
297 );
298
8fa50fdd
MN
299 if (property_exists($instance, 'resource_link_id') and !empty($instance->resource_link_id)) {
300 $requestparams['resource_link_id'] = $instance->resource_link_id;
301 }
b9b2e7bb 302 $placementsecret = $instance->servicesalt;
e27cb316 303
b9b2e7bb 304 if ( isset($placementsecret) ) {
8fa50fdd
MN
305 $sourcedid = json_encode(lti_build_sourcedid($instance->id, $USER->id, $placementsecret, $typeid));
306 $requestparams['lis_result_sourcedid'] = $sourcedid;
b9b2e7bb
CS
307 }
308
309 if ( isset($placementsecret) &&
5e078d62
CS
310 ( $typeconfig['acceptgrades'] == LTI_SETTING_ALWAYS ||
311 ( $typeconfig['acceptgrades'] == LTI_SETTING_DELEGATE && $instance->instructorchoiceacceptgrades == LTI_SETTING_ALWAYS ) ) ) {
e27cb316 312
34eb0501
CS
313 //Add outcome service URL
314 $serviceurl = new moodle_url('/mod/lti/service.php');
315 $serviceurl = $serviceurl->out();
feeb5294 316
8fa50fdd
MN
317 $forcessl = false;
318 if (!empty($CFG->mod_lti_forcessl)) {
319 $forcessl = true;
320 }
321
322 if ($typeconfig['forcessl'] == '1' or $forcessl) {
d8d04121
CS
323 $serviceurl = lti_ensure_url_is_https($serviceurl);
324 }
feeb5294 325
34eb0501 326 $requestparams['lis_outcome_service_url'] = $serviceurl;
b9b2e7bb
CS
327 }
328
b9b2e7bb 329 // Send user's name and email data if appropriate
5e078d62
CS
330 if ( $typeconfig['sendname'] == LTI_SETTING_ALWAYS ||
331 ( $typeconfig['sendname'] == LTI_SETTING_DELEGATE && $instance->instructorchoicesendname == LTI_SETTING_ALWAYS ) ) {
34eb0501
CS
332 $requestparams['lis_person_name_given'] = $USER->firstname;
333 $requestparams['lis_person_name_family'] = $USER->lastname;
334 $requestparams['lis_person_name_full'] = $USER->firstname." ".$USER->lastname;
435c709c 335 $requestparams['ext_user_username'] = $USER->username;
b9b2e7bb
CS
336 }
337
5e078d62
CS
338 if ( $typeconfig['sendemailaddr'] == LTI_SETTING_ALWAYS ||
339 ( $typeconfig['sendemailaddr'] == LTI_SETTING_DELEGATE && $instance->instructorchoicesendemailaddr == LTI_SETTING_ALWAYS ) ) {
34eb0501 340 $requestparams['lis_person_contact_email_primary'] = $USER->email;
b9b2e7bb
CS
341 }
342
343 // Concatenate the custom parameters from the administrator and the instructor
344 // Instructor parameters are only taken into consideration if the administrator
345 // has giver permission
346 $customstr = $typeconfig['customparameters'];
347 $instructorcustomstr = $instance->instructorcustomparameters;
348 $custom = array();
349 $instructorcustom = array();
350 if ($customstr) {
dbb0fec9 351 $custom = lti_split_custom_parameters($customstr);
b9b2e7bb 352 }
e91be4ff 353 if (isset($typeconfig['allowinstructorcustom']) && $typeconfig['allowinstructorcustom'] == LTI_SETTING_NEVER) {
b9b2e7bb
CS
354 $requestparams = array_merge($custom, $requestparams);
355 } else {
356 if ($instructorcustomstr) {
dbb0fec9 357 $instructorcustom = lti_split_custom_parameters($instructorcustomstr);
b9b2e7bb
CS
358 }
359 foreach ($instructorcustom as $key => $val) {
ea04a9f9
EL
360 // Ignore the instructor's parameter
361 if (!array_key_exists($key, $custom)) {
b9b2e7bb
CS
362 $custom[$key] = $val;
363 }
364 }
365 $requestparams = array_merge($custom, $requestparams);
366 }
367
3dd9ca24
CS
368 // Make sure we let the tool know what LMS they are being called from
369 $requestparams["ext_lms"] = "moodle-2";
34eb0501
CS
370 $requestparams['tool_consumer_info_product_family_code'] = 'moodle';
371 $requestparams['tool_consumer_info_version'] = strval($CFG->version);
3dd9ca24
CS
372
373 // Add oauth_callback to be compliant with the 1.0A spec
34eb0501 374 $requestparams['oauth_callback'] = 'about:blank';
3dd9ca24 375
558be8fc
CS
376 //The submit button needs to be part of the signature as it gets posted with the form.
377 //This needs to be here to support launching without javascript.
3dd9ca24 378 $submittext = get_string('press_to_submit', 'lti');
34eb0501 379 $requestparams['ext_submit'] = $submittext;
e27cb316 380
34eb0501
CS
381 $requestparams['lti_version'] = 'LTI-1p0';
382 $requestparams['lti_message_type'] = 'basic-lti-launch-request';
e27cb316 383
b9b2e7bb
CS
384 return $requestparams;
385}
386
ea04a9f9 387function lti_get_tool_table($tools, $id) {
99938034 388 global $CFG, $OUTPUT, $USER;
795dff01 389 $html = '';
e27cb316 390
795dff01
CS
391 $typename = get_string('typename', 'lti');
392 $baseurl = get_string('baseurl', 'lti');
393 $action = get_string('action', 'lti');
394 $createdon = get_string('createdon', 'lti');
e27cb316 395
ea04a9f9 396 if ($id == 'lti_configured') {
795dff01
CS
397 $html .= '<div><a style="margin-top:.25em" href="'.$CFG->wwwroot.'/mod/lti/typessettings.php?action=add&amp;sesskey='.$USER->sesskey.'">'.get_string('addtype', 'lti').'</a></div>';
398 }
e27cb316 399
795dff01 400 if (!empty($tools)) {
5de15b83
CS
401 $html .= "
402 <div id=\"{$id}_container\" style=\"margin-top:.5em;margin-bottom:.5em\">
403 <table id=\"{$id}_tools\">
795dff01
CS
404 <thead>
405 <tr>
406 <th>$typename</th>
407 <th>$baseurl</th>
408 <th>$createdon</th>
409 <th>$action</th>
410 </tr>
411 </thead>
5de15b83 412 ";
e27cb316 413
795dff01 414 foreach ($tools as $type) {
101ec5fd 415 $date = userdate($type->timecreated, get_string('strftimedatefullshort', 'core_langconfig'));
795dff01
CS
416 $accept = get_string('accept', 'lti');
417 $update = get_string('update', 'lti');
418 $delete = get_string('delete', 'lti');
e27cb316 419
baf41e4b
FM
420 $baseurl = new moodle_url('/mod/lti/typessettings.php', array(
421 'action' => 'accept',
422 'id' => $type->id,
423 'sesskey' => sesskey(),
424 'tab' => $id
425 ));
426
427 $accepthtml = $OUTPUT->action_icon($baseurl,
428 new pix_icon('t/check', $accept, '', array('class' => 'iconsmall')), null,
429 array('title' => $accept, 'class' => 'editing_accept'));
795dff01
CS
430
431 $deleteaction = 'delete';
e27cb316 432
ea04a9f9 433 if ($type->state == LTI_TOOL_STATE_CONFIGURED) {
795dff01
CS
434 $accepthtml = '';
435 }
e27cb316 436
ea04a9f9 437 if ($type->state != LTI_TOOL_STATE_REJECTED) {
795dff01
CS
438 $deleteaction = 'reject';
439 $delete = get_string('reject', 'lti');
440 }
e27cb316 441
baf41e4b
FM
442 $updateurl = clone($baseurl);
443 $updateurl->param('action', 'update');
444 $updatehtml = $OUTPUT->action_icon($updateurl,
73584712 445 new pix_icon('t/edit', $update, '', array('class' => 'iconsmall')), null,
baf41e4b
FM
446 array('title' => $update, 'class' => 'editing_update'));
447
448 $deleteurl = clone($baseurl);
449 $deleteurl->param('action', $deleteaction);
450 $deletehtml = $OUTPUT->action_icon($deleteurl,
73584712 451 new pix_icon('t/delete', $delete, '', array('class' => 'iconsmall')), null,
baf41e4b 452 array('title' => $delete, 'class' => 'editing_delete'));
5de15b83 453 $html .= "
795dff01
CS
454 <tr>
455 <td>
456 {$type->name}
457 </td>
458 <td>
459 {$type->baseurl}
460 </td>
461 <td>
462 {$date}
463 </td>
5de15b83 464 <td align=\"center\">
baf41e4b 465 {$accepthtml}{$updatehtml}{$deletehtml}
795dff01
CS
466 </td>
467 </tr>
5de15b83 468 ";
795dff01
CS
469 }
470 $html .= '</table></div>';
471 } else {
472 $html .= get_string('no_' . $id, 'lti');
473 }
e27cb316 474
795dff01
CS
475 return $html;
476}
477
b9b2e7bb
CS
478/**
479 * Splits the custom parameters field to the various parameters
480 *
481 * @param string $customstr String containing the parameters
482 *
483 * @return Array of custom parameters
484 */
dbb0fec9 485function lti_split_custom_parameters($customstr) {
b9b2e7bb
CS
486 $lines = preg_split("/[\n;]/", $customstr);
487 $retval = array();
488 foreach ($lines as $line) {
489 $pos = strpos($line, "=");
490 if ( $pos === false || $pos < 1 ) {
491 continue;
492 }
2f1e464a
PS
493 $key = trim(core_text::substr($line, 0, $pos));
494 $val = trim(core_text::substr($line, $pos+1, strlen($line)));
dbb0fec9 495 $key = lti_map_keyname($key);
b9b2e7bb
CS
496 $retval['custom_'.$key] = $val;
497 }
498 return $retval;
499}
500
501/**
502 * Used for building the names of the different custom parameters
503 *
504 * @param string $key Parameter name
505 *
506 * @return string Processed name
507 */
dbb0fec9 508function lti_map_keyname($key) {
b9b2e7bb 509 $newkey = "";
2f1e464a 510 $key = core_text::strtolower(trim($key));
b9b2e7bb
CS
511 foreach (str_split($key) as $ch) {
512 if ( ($ch >= 'a' && $ch <= 'z') || ($ch >= '0' && $ch <= '9') ) {
513 $newkey .= $ch;
514 } else {
515 $newkey .= '_';
516 }
517 }
518 return $newkey;
519}
520
521/**
16cac566 522 * Gets the IMS role string for the specified user and LTI course module.
e27cb316 523 *
16cac566
CS
524 * @param mixed $user User object or user id
525 * @param int $cmid The course module id of the LTI activity
526 * @return string A role string suitable for passing with an LTI launch
b9b2e7bb 527 */
1d4f052e 528function lti_get_ims_role($user, $cmid, $courseid) {
16cac566 529 $roles = array();
e27cb316 530
ea04a9f9 531 if (empty($cmid)) {
1d4f052e
CS
532 //If no cmid is passed, check if the user is a teacher in the course
533 //This allows other modules to programmatically "fake" a launch without
534 //a real LTI instance
c288a3db 535 $coursecontext = context_course::instance($courseid);
e27cb316 536
ea04a9f9 537 if (has_capability('moodle/course:manageactivities', $coursecontext)) {
1d4f052e
CS
538 array_push($roles, 'Instructor');
539 } else {
540 array_push($roles, 'Learner');
541 }
16cac566 542 } else {
c288a3db 543 $context = context_module::instance($cmid);
1d4f052e 544
ea04a9f9 545 if (has_capability('mod/lti:manage', $context)) {
1d4f052e
CS
546 array_push($roles, 'Instructor');
547 } else {
548 array_push($roles, 'Learner');
549 }
b9b2e7bb 550 }
1d4f052e 551
ea04a9f9 552 if (is_siteadmin($user)) {
8fa50fdd 553 array_push($roles, 'urn:lti:sysrole:ims/lis/Administrator', 'urn:lti:instrole:ims/lis/Administrator');
b9b2e7bb 554 }
e27cb316 555
16cac566 556 return join(',', $roles);
b9b2e7bb
CS
557}
558
559/**
560 * Returns configuration details for the tool
561 *
562 * @param int $typeid Basic LTI tool typeid
563 *
564 * @return array Tool Configuration
565 */
566function lti_get_type_config($typeid) {
567 global $DB;
568
5f136255
EL
569 $query = "SELECT name, value
570 FROM {lti_types_config}
571 WHERE typeid = :typeid1
572 UNION ALL
cc12ae6c 573 SELECT 'toolurl' AS name, " . $DB->sql_compare_text('baseurl', 1333) . " AS value
5f136255
EL
574 FROM {lti_types}
575 WHERE id = :typeid2";
e27cb316 576
b9b2e7bb 577 $typeconfig = array();
f17f4959 578 $configs = $DB->get_records_sql($query, array('typeid1' => $typeid, 'typeid2' => $typeid));
e27cb316 579
b9b2e7bb
CS
580 if (!empty($configs)) {
581 foreach ($configs as $config) {
582 $typeconfig[$config->name] = $config->value;
583 }
584 }
e27cb316 585
b9b2e7bb
CS
586 return $typeconfig;
587}
588
ea04a9f9 589function lti_get_tools_by_url($url, $state, $courseid = null) {
b9b2e7bb 590 $domain = lti_get_domain_from_url($url);
e27cb316 591
996b0fd9 592 return lti_get_tools_by_domain($domain, $state, $courseid);
b9b2e7bb
CS
593}
594
ea04a9f9 595function lti_get_tools_by_domain($domain, $state = null, $courseid = null) {
b9b2e7bb 596 global $DB, $SITE;
e27cb316 597
b9b2e7bb 598 $filters = array('tooldomain' => $domain);
e27cb316 599
b9b2e7bb
CS
600 $statefilter = '';
601 $coursefilter = '';
e27cb316 602
ea04a9f9 603 if ($state) {
b9b2e7bb
CS
604 $statefilter = 'AND state = :state';
605 }
e27cb316 606
ea04a9f9 607 if ($courseid && $courseid != $SITE->id) {
b9b2e7bb
CS
608 $coursefilter = 'OR course = :courseid';
609 }
e27cb316 610
5f136255
EL
611 $query = "SELECT *
612 FROM {lti_types}
613 WHERE tooldomain = :tooldomain
614 AND (course = :siteid $coursefilter)
615 $statefilter";
e27cb316 616
b9b2e7bb 617 return $DB->get_records_sql($query, array(
e27cb316
CS
618 'courseid' => $courseid,
619 'siteid' => $SITE->id,
620 'tooldomain' => $domain,
b9b2e7bb
CS
621 'state' => $state
622 ));
623}
624
625/**
626 * Returns all basicLTI tools configured by the administrator
627 *
628 */
6831c7cd 629function lti_filter_get_types($course) {
b9b2e7bb
CS
630 global $DB;
631
ea04a9f9 632 if (!empty($course)) {
6831c7cd
CS
633 $filter = array('course' => $course);
634 } else {
635 $filter = array();
636 }
e27cb316 637
6831c7cd 638 return $DB->get_records('lti_types', $filter);
b9b2e7bb
CS
639}
640
d81a603e
MN
641/**
642 * Given an array of tools, filter them based on their state
643 *
644 * @param array $tools An array of lti_types records
645 * @param int $state One of the LTI_TOOL_STATE_* constants
646 * @return array
647 */
648function lti_filter_tool_types(array $tools, $state) {
649 $return = array();
650 foreach ($tools as $key => $tool) {
651 if ($tool->state == $state) {
652 $return[$key] = $tool;
653 }
654 }
655 return $return;
656}
657
ea04a9f9 658function lti_get_types_for_add_instance() {
996b0fd9 659 global $DB, $SITE, $COURSE;
e27cb316 660
5f136255
EL
661 $query = "SELECT *
662 FROM {lti_types}
663 WHERE coursevisible = 1
664 AND (course = :siteid OR course = :courseid)
665 AND state = :active";
e27cb316 666
606ab1a1 667 $admintypes = $DB->get_records_sql($query, array('siteid' => $SITE->id, 'courseid' => $COURSE->id, 'active' => LTI_TOOL_STATE_CONFIGURED));
e27cb316 668
b9b2e7bb 669 $types = array();
200aeda6 670 $types[0] = (object)array('name' => get_string('automatic', 'lti'), 'course' => 0);
e27cb316 671
ea04a9f9 672 foreach ($admintypes as $type) {
16e8f130 673 $types[$type->id] = $type;
b9b2e7bb 674 }
e27cb316 675
b9b2e7bb
CS
676 return $types;
677}
678
ea04a9f9 679function lti_get_domain_from_url($url) {
b9b2e7bb 680 $matches = array();
e27cb316 681
ea04a9f9 682 if (preg_match(LTI_URL_DOMAIN_REGEX, $url, $matches)) {
b9b2e7bb
CS
683 return $matches[1];
684 }
685}
686
ea04a9f9 687function lti_get_tool_by_url_match($url, $courseid = null, $state = LTI_TOOL_STATE_CONFIGURED) {
b69dc429 688 $possibletools = lti_get_tools_by_url($url, $state, $courseid);
e27cb316 689
7023b65e 690 return lti_get_best_tool_by_url($url, $possibletools, $courseid);
b9b2e7bb
CS
691}
692
ea04a9f9 693function lti_get_url_thumbprint($url) {
8fa50fdd
MN
694 // Parse URL requires a schema otherwise everything goes into 'path'. Fixed 5.4.7 or later.
695 if (preg_match('/https?:\/\//', $url) !== 1) {
696 $url = 'http://'.$url;
697 }
b9b2e7bb 698 $urlparts = parse_url(strtolower($url));
ea04a9f9 699 if (!isset($urlparts['path'])) {
b9b2e7bb
CS
700 $urlparts['path'] = '';
701 }
e27cb316 702
ea04a9f9 703 if (!isset($urlparts['host'])) {
d8d04121
CS
704 $urlparts['host'] = '';
705 }
e27cb316 706
ea04a9f9 707 if (substr($urlparts['host'], 0, 4) === 'www.') {
d8d04121 708 $urlparts['host'] = substr($urlparts['host'], 4);
b9b2e7bb 709 }
e27cb316 710
b9b2e7bb
CS
711 return $urllower = $urlparts['host'] . '/' . $urlparts['path'];
712}
713
ea04a9f9
EL
714function lti_get_best_tool_by_url($url, $tools, $courseid = null) {
715 if (count($tools) === 0) {
b9b2e7bb
CS
716 return null;
717 }
e27cb316 718
b9b2e7bb 719 $urllower = lti_get_url_thumbprint($url);
e27cb316 720
ea04a9f9 721 foreach ($tools as $tool) {
b9b2e7bb 722 $tool->_matchscore = 0;
e27cb316 723
b9b2e7bb 724 $toolbaseurllower = lti_get_url_thumbprint($tool->baseurl);
e27cb316 725
ea04a9f9 726 if ($urllower === $toolbaseurllower) {
7023b65e 727 //100 points for exact thumbprint match
b9b2e7bb 728 $tool->_matchscore += 100;
ea04a9f9 729 } else if (substr($urllower, 0, strlen($toolbaseurllower)) === $toolbaseurllower) {
7023b65e 730 //50 points if tool thumbprint starts with the base URL thumbprint
b9b2e7bb
CS
731 $tool->_matchscore += 50;
732 }
e27cb316 733
7023b65e 734 //Prefer course tools over site tools
ea04a9f9 735 if (!empty($courseid)) {
4c598b13 736 //Minus 10 points for not matching the course id (global tools)
ea04a9f9 737 if ($tool->course != $courseid) {
7023b65e
CS
738 $tool->_matchscore -= 10;
739 }
740 }
b9b2e7bb 741 }
e27cb316 742
ea04a9f9
EL
743 $bestmatch = array_reduce($tools, function($value, $tool) {
744 if ($tool->_matchscore > $value->_matchscore) {
b9b2e7bb
CS
745 return $tool;
746 } else {
747 return $value;
748 }
e27cb316 749
b9b2e7bb 750 }, (object)array('_matchscore' => -1));
e27cb316 751
b9b2e7bb 752 //None of the tools are suitable for this URL
ea04a9f9 753 if ($bestmatch->_matchscore <= 0) {
b9b2e7bb
CS
754 return null;
755 }
e27cb316 756
b9b2e7bb
CS
757 return $bestmatch;
758}
759
ea04a9f9 760function lti_get_shared_secrets_by_key($key) {
020eea1b 761 global $DB;
e27cb316 762
020eea1b
CS
763 //Look up the shared secret for the specified key in both the types_config table (for configured tools)
764 //And in the lti resource table for ad-hoc tools
5f136255
EL
765 $query = "SELECT t2.value
766 FROM {lti_types_config} t1
767 JOIN {lti_types_config} t2 ON t1.typeid = t2.typeid
768 JOIN {lti_types} type ON t2.typeid = type.id
769 WHERE t1.name = 'resourcekey'
770 AND t1.value = :key1
771 AND t2.name = 'password'
772 AND type.state = :configured
773 UNION
774 SELECT password AS value
775 FROM {lti}
776 WHERE resourcekey = :key2";
e27cb316 777
feb30fd8 778 $sharedsecrets = $DB->get_records_sql($query, array('configured' => LTI_TOOL_STATE_CONFIGURED, 'key1' => $key, 'key2' => $key));
e27cb316 779
ea04a9f9 780 $values = array_map(function($item) {
020eea1b
CS
781 return $item->value;
782 }, $sharedsecrets);
e27cb316 783
020eea1b
CS
784 //There should really only be one shared secret per key. But, we can't prevent
785 //more than one getting entered. For instance, if the same key is used for two tool providers.
786 return $values;
787}
788
b9b2e7bb
CS
789/**
790 * Delete a Basic LTI configuration
791 *
792 * @param int $id Configuration id
793 */
794function lti_delete_type($id) {
795 global $DB;
796
797 //We should probably just copy the launch URL to the tool instances in this case... using a single query
798 /*
799 $instances = $DB->get_records('lti', array('typeid' => $id));
800 foreach ($instances as $instance) {
801 $instance->typeid = 0;
802 $DB->update_record('lti', $instance);
803 }*/
804
805 $DB->delete_records('lti_types', array('id' => $id));
806 $DB->delete_records('lti_types_config', array('typeid' => $id));
807}
808
ea04a9f9 809function lti_set_state_for_type($id, $state) {
b9b2e7bb 810 global $DB;
e27cb316 811
b9b2e7bb
CS
812 $DB->update_record('lti_types', array('id' => $id, 'state' => $state));
813}
814
815/**
816 * Transforms a basic LTI object to an array
817 *
818 * @param object $ltiobject Basic LTI object
819 *
820 * @return array Basic LTI configuration details
821 */
822function lti_get_config($ltiobject) {
823 $typeconfig = array();
824 $typeconfig = (array)$ltiobject;
825 $additionalconfig = lti_get_type_config($ltiobject->typeid);
826 $typeconfig = array_merge($typeconfig, $additionalconfig);
827 return $typeconfig;
828}
829
830/**
831 *
832 * Generates some of the tool configuration based on the instance details
833 *
834 * @param int $id
835 *
836 * @return Instance configuration
837 *
838 */
839function lti_get_type_config_from_instance($id) {
840 global $DB;
841
842 $instance = $DB->get_record('lti', array('id' => $id));
843 $config = lti_get_config($instance);
844
845 $type = new stdClass();
846 $type->lti_fix = $id;
847 if (isset($config['toolurl'])) {
848 $type->lti_toolurl = $config['toolurl'];
849 }
850 if (isset($config['instructorchoicesendname'])) {
851 $type->lti_sendname = $config['instructorchoicesendname'];
852 }
853 if (isset($config['instructorchoicesendemailaddr'])) {
854 $type->lti_sendemailaddr = $config['instructorchoicesendemailaddr'];
855 }
856 if (isset($config['instructorchoiceacceptgrades'])) {
857 $type->lti_acceptgrades = $config['instructorchoiceacceptgrades'];
858 }
859 if (isset($config['instructorchoiceallowroster'])) {
860 $type->lti_allowroster = $config['instructorchoiceallowroster'];
861 }
862
863 if (isset($config['instructorcustomparameters'])) {
864 $type->lti_allowsetting = $config['instructorcustomparameters'];
865 }
866 return $type;
867}
868
869/**
870 * Generates some of the tool configuration based on the admin configuration details
871 *
872 * @param int $id
873 *
874 * @return Configuration details
875 */
876function lti_get_type_type_config($id) {
877 global $DB;
878
879 $basicltitype = $DB->get_record('lti_types', array('id' => $id));
880 $config = lti_get_type_config($id);
881
036e84c3 882 $type = new stdClass();
5f72d102 883
b9b2e7bb 884 $type->lti_typename = $basicltitype->name;
e27cb316 885
6831c7cd 886 $type->typeid = $basicltitype->id;
e27cb316 887
b9b2e7bb 888 $type->lti_toolurl = $basicltitype->baseurl;
e27cb316 889
b9b2e7bb
CS
890 if (isset($config['resourcekey'])) {
891 $type->lti_resourcekey = $config['resourcekey'];
892 }
893 if (isset($config['password'])) {
894 $type->lti_password = $config['password'];
895 }
896
897 if (isset($config['sendname'])) {
898 $type->lti_sendname = $config['sendname'];
899 }
ea04a9f9 900 if (isset($config['instructorchoicesendname'])) {
b9b2e7bb
CS
901 $type->lti_instructorchoicesendname = $config['instructorchoicesendname'];
902 }
ea04a9f9 903 if (isset($config['sendemailaddr'])) {
b9b2e7bb
CS
904 $type->lti_sendemailaddr = $config['sendemailaddr'];
905 }
ea04a9f9 906 if (isset($config['instructorchoicesendemailaddr'])) {
b9b2e7bb
CS
907 $type->lti_instructorchoicesendemailaddr = $config['instructorchoicesendemailaddr'];
908 }
ea04a9f9 909 if (isset($config['acceptgrades'])) {
b9b2e7bb
CS
910 $type->lti_acceptgrades = $config['acceptgrades'];
911 }
ea04a9f9 912 if (isset($config['instructorchoiceacceptgrades'])) {
b9b2e7bb
CS
913 $type->lti_instructorchoiceacceptgrades = $config['instructorchoiceacceptgrades'];
914 }
ea04a9f9 915 if (isset($config['allowroster'])) {
b9b2e7bb
CS
916 $type->lti_allowroster = $config['allowroster'];
917 }
ea04a9f9 918 if (isset($config['instructorchoiceallowroster'])) {
b9b2e7bb
CS
919 $type->lti_instructorchoiceallowroster = $config['instructorchoiceallowroster'];
920 }
921
922 if (isset($config['customparameters'])) {
923 $type->lti_customparameters = $config['customparameters'];
924 }
925
ea04a9f9 926 if (isset($config['forcessl'])) {
d8d04121
CS
927 $type->lti_forcessl = $config['forcessl'];
928 }
e27cb316 929
b9b2e7bb
CS
930 if (isset($config['organizationid'])) {
931 $type->lti_organizationid = $config['organizationid'];
932 }
933 if (isset($config['organizationurl'])) {
934 $type->lti_organizationurl = $config['organizationurl'];
935 }
936 if (isset($config['organizationdescr'])) {
937 $type->lti_organizationdescr = $config['organizationdescr'];
938 }
939 if (isset($config['launchcontainer'])) {
940 $type->lti_launchcontainer = $config['launchcontainer'];
941 }
e27cb316 942
b9b2e7bb
CS
943 if (isset($config['coursevisible'])) {
944 $type->lti_coursevisible = $config['coursevisible'];
945 }
e27cb316 946
b9b2e7bb
CS
947 if (isset($config['debuglaunch'])) {
948 $type->lti_debuglaunch = $config['debuglaunch'];
949 }
e27cb316 950
b9b2e7bb 951 if (isset($config['module_class_type'])) {
036e84c3 952 $type->lti_module_class_type = $config['module_class_type'];
b9b2e7bb
CS
953 }
954
955 return $type;
956}
957
ea04a9f9 958function lti_prepare_type_for_save($type, $config) {
b9b2e7bb
CS
959 $type->baseurl = $config->lti_toolurl;
960 $type->tooldomain = lti_get_domain_from_url($config->lti_toolurl);
961 $type->name = $config->lti_typename;
e27cb316 962
b9b2e7bb
CS
963 $type->coursevisible = !empty($config->lti_coursevisible) ? $config->lti_coursevisible : 0;
964 $config->lti_coursevisible = $type->coursevisible;
e27cb316 965
d8d04121
CS
966 $type->forcessl = !empty($config->lti_forcessl) ? $config->lti_forcessl : 0;
967 $config->lti_forcessl = $type->forcessl;
e27cb316 968
b9b2e7bb 969 $type->timemodified = time();
e27cb316 970
b9b2e7bb
CS
971 unset ($config->lti_typename);
972 unset ($config->lti_toolurl);
973}
974
ea04a9f9 975function lti_update_type($type, $config) {
b9b2e7bb 976 global $DB;
e27cb316 977
b9b2e7bb 978 lti_prepare_type_for_save($type, $config);
e27cb316 979
b9b2e7bb
CS
980 if ($DB->update_record('lti_types', $type)) {
981 foreach ($config as $key => $value) {
982 if (substr($key, 0, 4)=='lti_' && !is_null($value)) {
983 $record = new StdClass();
984 $record->typeid = $type->id;
985 $record->name = substr($key, 4);
986 $record->value = $value;
e27cb316 987
b9b2e7bb
CS
988 lti_update_config($record);
989 }
990 }
991 }
992}
993
ea04a9f9 994function lti_add_type($type, $config) {
b9b2e7bb 995 global $USER, $SITE, $DB;
e27cb316 996
b9b2e7bb 997 lti_prepare_type_for_save($type, $config);
e27cb316 998
ea04a9f9 999 if (!isset($type->state)) {
b9b2e7bb
CS
1000 $type->state = LTI_TOOL_STATE_PENDING;
1001 }
e27cb316 1002
ea04a9f9 1003 if (!isset($type->timecreated)) {
b9b2e7bb
CS
1004 $type->timecreated = time();
1005 }
e27cb316 1006
ea04a9f9 1007 if (!isset($type->createdby)) {
b9b2e7bb
CS
1008 $type->createdby = $USER->id;
1009 }
e27cb316 1010
ea04a9f9 1011 if (!isset($type->course)) {
b9b2e7bb
CS
1012 $type->course = $SITE->id;
1013 }
e27cb316 1014
b9b2e7bb 1015 //Create a salt value to be used for signing passed data to extension services
6831c7cd
CS
1016 //The outcome service uses the service salt on the instance. This can be used
1017 //for communication with services not related to a specific LTI instance.
b9b2e7bb
CS
1018 $config->lti_servicesalt = uniqid('', true);
1019
1020 $id = $DB->insert_record('lti_types', $type);
1021
1022 if ($id) {
1023 foreach ($config as $key => $value) {
1024 if (substr($key, 0, 4)=='lti_' && !is_null($value)) {
1025 $record = new StdClass();
1026 $record->typeid = $id;
1027 $record->name = substr($key, 4);
1028 $record->value = $value;
1029
1030 lti_add_config($record);
1031 }
1032 }
1033 }
e27cb316 1034
996b0fd9 1035 return $id;
b9b2e7bb
CS
1036}
1037
1038/**
1039 * Add a tool configuration in the database
1040 *
1041 * @param $config Tool configuration
1042 *
1043 * @return int Record id number
1044 */
1045function lti_add_config($config) {
1046 global $DB;
1047
1048 return $DB->insert_record('lti_types_config', $config);
1049}
1050
1051/**
1052 * Updates a tool configuration in the database
1053 *
1054 * @param $config Tool configuration
1055 *
1056 * @return Record id number
1057 */
1058function lti_update_config($config) {
1059 global $DB;
1060
1061 $return = true;
1062 $old = $DB->get_record('lti_types_config', array('typeid' => $config->typeid, 'name' => $config->name));
e27cb316 1063
b9b2e7bb
CS
1064 if ($old) {
1065 $config->id = $old->id;
1066 $return = $DB->update_record('lti_types_config', $config);
1067 } else {
1068 $return = $DB->insert_record('lti_types_config', $config);
1069 }
1070 return $return;
1071}
1072
1073/**
1074 * Signs the petition to launch the external tool using OAuth
1075 *
1076 * @param $oldparms Parameters to be passed for signing
1077 * @param $endpoint url of the external tool
1078 * @param $method Method for sending the parameters (e.g. POST)
1079 * @param $oauth_consumoer_key Key
1080 * @param $oauth_consumoer_secret Secret
1081 * @param $submittext The text for the submit button
1082 * @param $orgid LMS name
1083 * @param $orgdesc LMS key
1084 */
3dd9ca24
CS
1085function lti_sign_parameters($oldparms, $endpoint, $method, $oauthconsumerkey, $oauthconsumersecret) {
1086 //global $lastbasestring;
b9b2e7bb 1087 $parms = $oldparms;
b9b2e7bb
CS
1088
1089 $testtoken = '';
e27cb316 1090
fabd4fcf 1091 // TODO: Switch to core oauthlib once implemented - MDL-30149
795dff01
CS
1092 $hmacmethod = new lti\OAuthSignatureMethod_HMAC_SHA1();
1093 $testconsumer = new lti\OAuthConsumer($oauthconsumerkey, $oauthconsumersecret, null);
795dff01 1094 $accreq = lti\OAuthRequest::from_consumer_and_token($testconsumer, $testtoken, $method, $endpoint, $parms);
b9b2e7bb
CS
1095 $accreq->sign_request($hmacmethod, $testconsumer, $testtoken);
1096
1097 // Pass this back up "out of band" for debugging
3dd9ca24 1098 //$lastbasestring = $accreq->get_signature_base_string();
b9b2e7bb
CS
1099
1100 $newparms = $accreq->get_parameters();
1101
1102 return $newparms;
1103}
1104
1105/**
1106 * Posts the launch petition HTML
1107 *
1108 * @param $newparms Signed parameters
1109 * @param $endpoint URL of the external tool
1110 * @param $debug Debug (true/false)
1111 */
dbb0fec9 1112function lti_post_launch_html($newparms, $endpoint, $debug=false) {
b9b2e7bb 1113 $r = "<form action=\"".$endpoint."\" name=\"ltiLaunchForm\" id=\"ltiLaunchForm\" method=\"post\" encType=\"application/x-www-form-urlencoded\">\n";
e27cb316 1114
b9b2e7bb
CS
1115 $submittext = $newparms['ext_submit'];
1116
1117 // Contruct html for the launch parameters
1118 foreach ($newparms as $key => $value) {
1119 $key = htmlspecialchars($key);
1120 $value = htmlspecialchars($value);
1121 if ( $key == "ext_submit" ) {
1122 $r .= "<input type=\"submit\" name=\"";
1123 } else {
1124 $r .= "<input type=\"hidden\" name=\"";
1125 }
1126 $r .= $key;
1127 $r .= "\" value=\"";
1128 $r .= $value;
1129 $r .= "\"/>\n";
1130 }
1131
1132 if ( $debug ) {
1133 $r .= "<script language=\"javascript\"> \n";
1134 $r .= " //<![CDATA[ \n";
1135 $r .= "function basicltiDebugToggle() {\n";
1136 $r .= " var ele = document.getElementById(\"basicltiDebug\");\n";
ea04a9f9 1137 $r .= " if (ele.style.display == \"block\") {\n";
b9b2e7bb
CS
1138 $r .= " ele.style.display = \"none\";\n";
1139 $r .= " }\n";
1140 $r .= " else {\n";
1141 $r .= " ele.style.display = \"block\";\n";
1142 $r .= " }\n";
1143 $r .= "} \n";
1144 $r .= " //]]> \n";
1145 $r .= "</script>\n";
1146 $r .= "<a id=\"displayText\" href=\"javascript:basicltiDebugToggle();\">";
1147 $r .= get_string("toggle_debug_data", "lti")."</a>\n";
1148 $r .= "<div id=\"basicltiDebug\" style=\"display:none\">\n";
1149 $r .= "<b>".get_string("basiclti_endpoint", "lti")."</b><br/>\n";
1150 $r .= $endpoint . "<br/>\n&nbsp;<br/>\n";
1151 $r .= "<b>".get_string("basiclti_parameters", "lti")."</b><br/>\n";
1152 foreach ($newparms as $key => $value) {
1153 $key = htmlspecialchars($key);
1154 $value = htmlspecialchars($value);
1155 $r .= "$key = $value<br/>\n";
1156 }
1157 $r .= "&nbsp;<br/>\n";
3dd9ca24 1158 //$r .= "<p><b>".get_string("basiclti_base_string", "lti")."</b><br/>\n".$lastbasestring."</p>\n";
b9b2e7bb
CS
1159 $r .= "</div>\n";
1160 }
1161 $r .= "</form>\n";
1162
1163 if ( ! $debug ) {
1164 $ext_submit = "ext_submit";
1165 $ext_submit_text = $submittext;
1166 $r .= " <script type=\"text/javascript\"> \n" .
1167 " //<![CDATA[ \n" .
1168 " document.getElementById(\"ltiLaunchForm\").style.display = \"none\";\n" .
1169 " nei = document.createElement('input');\n" .
1170 " nei.setAttribute('type', 'hidden');\n" .
1171 " nei.setAttribute('name', '".$ext_submit."');\n" .
1172 " nei.setAttribute('value', '".$ext_submit_text."');\n" .
1173 " document.getElementById(\"ltiLaunchForm\").appendChild(nei);\n" .
1174 " document.ltiLaunchForm.submit(); \n" .
1175 " //]]> \n" .
1176 " </script> \n";
1177 }
1178 return $r;
1179}
1180
ea04a9f9 1181function lti_get_type($typeid) {
996b0fd9 1182 global $DB;
e27cb316 1183
996b0fd9 1184 return $DB->get_record('lti_types', array('id' => $typeid));
57d1dffd
CS
1185}
1186
ea04a9f9
EL
1187function lti_get_launch_container($lti, $toolconfig) {
1188 if (empty($lti->launchcontainer)) {
e27cb316
CS
1189 $lti->launchcontainer = LTI_LAUNCH_CONTAINER_DEFAULT;
1190 }
1191
ea04a9f9
EL
1192 if ($lti->launchcontainer == LTI_LAUNCH_CONTAINER_DEFAULT) {
1193 if (isset($toolconfig['launchcontainer'])) {
c4d80efe
CS
1194 $launchcontainer = $toolconfig['launchcontainer'];
1195 }
1196 } else {
1197 $launchcontainer = $lti->launchcontainer;
1198 }
e27cb316 1199
ea04a9f9 1200 if (empty($launchcontainer) || $launchcontainer == LTI_LAUNCH_CONTAINER_DEFAULT) {
c4d80efe
CS
1201 $launchcontainer = LTI_LAUNCH_CONTAINER_EMBED_NO_BLOCKS;
1202 }
57d1dffd 1203
c3d2fbf9 1204 $devicetype = core_useragent::get_device_type();
57d1dffd
CS
1205
1206 //Scrolling within the object element doesn't work on iOS or Android
1207 //Opening the popup window also had some issues in testing
1208 //For mobile devices, always take up the entire screen to ensure the best experience
c3d2fbf9 1209 if ($devicetype === core_useragent::DEVICETYPE_MOBILE || $devicetype === core_useragent::DEVICETYPE_TABLET ) {
57d1dffd
CS
1210 $launchcontainer = LTI_LAUNCH_CONTAINER_REPLACE_MOODLE_WINDOW;
1211 }
e27cb316 1212
57d1dffd 1213 return $launchcontainer;
d8d04121
CS
1214}
1215
1216function lti_request_is_using_ssl() {
33dca156
PS
1217 global $CFG;
1218 return (stripos($CFG->httpswwwroot, 'https://') === 0);
d8d04121
CS
1219}
1220
ea04a9f9
EL
1221function lti_ensure_url_is_https($url) {
1222 if (!strstr($url, '://')) {
d8d04121
CS
1223 $url = 'https://' . $url;
1224 } else {
1225 //If the URL starts with http, replace with https
ea04a9f9 1226 if (stripos($url, 'http://') === 0) {
adc23cc9 1227 $url = 'https://' . substr($url, 7);
d8d04121
CS
1228 }
1229 }
e27cb316 1230
d8d04121 1231 return $url;
61eb12d4 1232}
8fa50fdd
MN
1233
1234/**
1235 * Determines if we should try to log the request
1236 *
1237 * @param string $rawbody
1238 * @return bool
1239 */
1240function lti_should_log_request($rawbody) {
1241 global $CFG;
1242
1243 if (empty($CFG->mod_lti_log_users)) {
1244 return false;
1245 }
1246
1247 $logusers = explode(',', $CFG->mod_lti_log_users);
1248 if (empty($logusers)) {
1249 return false;
1250 }
1251
1252 try {
1253 $xml = new SimpleXMLElement($rawbody);
1254 $ns = $xml->getNamespaces();
1255 $ns = array_shift($ns);
1256 $xml->registerXPathNamespace('lti', $ns);
1257 $requestuserid = '';
1258 if ($node = $xml->xpath('//lti:userId')) {
1259 $node = $node[0];
1260 $requestuserid = clean_param((string) $node, PARAM_INT);
1261 } else if ($node = $xml->xpath('//lti:sourcedId')) {
1262 $node = $node[0];
1263 $resultjson = json_decode((string) $node);
1264 $requestuserid = clean_param($resultjson->data->userid, PARAM_INT);
1265 }
1266 } catch (Exception $e) {
1267 return false;
1268 }
1269
1270 if (empty($requestuserid) or !in_array($requestuserid, $logusers)) {
1271 return false;
1272 }
1273
1274 return true;
1275}
1276
1277/**
1278 * Logs the request to a file in temp dir
1279 *
1280 * @param string $rawbody
1281 */
1282function lti_log_request($rawbody) {
1283 if ($tempdir = make_temp_directory('mod_lti', false)) {
1284 if ($tempfile = tempnam($tempdir, 'mod_lti_request'.date('YmdHis'))) {
1285 file_put_contents($tempfile, $rawbody);
1286 chmod($tempfile, 0644);
1287 }
1288 }
1289}
1290
1291/**
1292 * Fetches LTI type configuration for an LTI instance
1293 *
1294 * @param stdClass $instance
1295 * @return array Can be empty if no type is found
1296 */
1297function lti_get_type_config_by_instance($instance) {
1298 $typeid = null;
1299 if (empty($instance->typeid)) {
1300 $tool = lti_get_tool_by_url_match($instance->toolurl, $instance->course);
1301 if ($tool) {
1302 $typeid = $tool->id;
1303 }
1304 } else {
1305 $typeid = $instance->typeid;
1306 }
1307 if (!empty($typeid)) {
1308 return lti_get_type_config($typeid);
1309 }
1310 return array();
1311}
1312
1313/**
1314 * Enforce type config settings onto the LTI instance
1315 *
1316 * @param stdClass $instance
1317 * @param array $typeconfig
1318 */
1319function lti_force_type_config_settings($instance, array $typeconfig) {
1320 $forced = array(
1321 'instructorchoicesendname' => 'sendname',
1322 'instructorchoicesendemailaddr' => 'sendemailaddr',
1323 'instructorchoiceacceptgrades' => 'acceptgrades',
1324 );
1325
1326 foreach ($forced as $instanceparam => $typeconfigparam) {
1327 if (array_key_exists($typeconfigparam, $typeconfig) && $typeconfig[$typeconfigparam] != LTI_SETTING_DELEGATE) {
1328 $instance->$instanceparam = $typeconfig[$typeconfigparam];
1329 }
1330 }
1331}
1332