Merge branch 'MDL-47576-master' of git://github.com/jethac/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
ff9d3d81 272 * @param array $typeconfig Basic LTI tool configuration
b9b2e7bb 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
ff9d3d81
MN
287 $intro = '';
288 if (!empty($instance->cmid)) {
289 $intro = format_module_intro('lti', $instance, $instance->cmid);
290 $intro = html_to_text($intro, 0, false);
291
292 // This may look weird, but this is required for new lines
293 // so we generate the same OAuth signature as the tool provider.
294 $intro = str_replace("\n", "\r\n", $intro);
295 }
b9b2e7bb 296 $requestparams = array(
34eb0501
CS
297 'resource_link_id' => $instance->id,
298 'resource_link_title' => $instance->name,
ff9d3d81 299 'resource_link_description' => $intro,
34eb0501
CS
300 'user_id' => $USER->id,
301 'roles' => $role,
302 'context_id' => $course->id,
303 'context_label' => $course->shortname,
304 'context_title' => $course->fullname,
2a457227 305 'launch_presentation_locale' => current_language()
b9b2e7bb
CS
306 );
307
8fa50fdd
MN
308 if (property_exists($instance, 'resource_link_id') and !empty($instance->resource_link_id)) {
309 $requestparams['resource_link_id'] = $instance->resource_link_id;
310 }
b9b2e7bb 311 $placementsecret = $instance->servicesalt;
e27cb316 312
b9b2e7bb 313 if ( isset($placementsecret) ) {
8fa50fdd
MN
314 $sourcedid = json_encode(lti_build_sourcedid($instance->id, $USER->id, $placementsecret, $typeid));
315 $requestparams['lis_result_sourcedid'] = $sourcedid;
b9b2e7bb
CS
316 }
317
318 if ( isset($placementsecret) &&
5e078d62
CS
319 ( $typeconfig['acceptgrades'] == LTI_SETTING_ALWAYS ||
320 ( $typeconfig['acceptgrades'] == LTI_SETTING_DELEGATE && $instance->instructorchoiceacceptgrades == LTI_SETTING_ALWAYS ) ) ) {
e27cb316 321
34eb0501
CS
322 //Add outcome service URL
323 $serviceurl = new moodle_url('/mod/lti/service.php');
324 $serviceurl = $serviceurl->out();
feeb5294 325
8fa50fdd
MN
326 $forcessl = false;
327 if (!empty($CFG->mod_lti_forcessl)) {
328 $forcessl = true;
329 }
330
331 if ($typeconfig['forcessl'] == '1' or $forcessl) {
d8d04121
CS
332 $serviceurl = lti_ensure_url_is_https($serviceurl);
333 }
feeb5294 334
34eb0501 335 $requestparams['lis_outcome_service_url'] = $serviceurl;
b9b2e7bb
CS
336 }
337
b9b2e7bb 338 // Send user's name and email data if appropriate
5e078d62
CS
339 if ( $typeconfig['sendname'] == LTI_SETTING_ALWAYS ||
340 ( $typeconfig['sendname'] == LTI_SETTING_DELEGATE && $instance->instructorchoicesendname == LTI_SETTING_ALWAYS ) ) {
34eb0501
CS
341 $requestparams['lis_person_name_given'] = $USER->firstname;
342 $requestparams['lis_person_name_family'] = $USER->lastname;
343 $requestparams['lis_person_name_full'] = $USER->firstname." ".$USER->lastname;
435c709c 344 $requestparams['ext_user_username'] = $USER->username;
b9b2e7bb
CS
345 }
346
5e078d62
CS
347 if ( $typeconfig['sendemailaddr'] == LTI_SETTING_ALWAYS ||
348 ( $typeconfig['sendemailaddr'] == LTI_SETTING_DELEGATE && $instance->instructorchoicesendemailaddr == LTI_SETTING_ALWAYS ) ) {
34eb0501 349 $requestparams['lis_person_contact_email_primary'] = $USER->email;
b9b2e7bb
CS
350 }
351
352 // Concatenate the custom parameters from the administrator and the instructor
353 // Instructor parameters are only taken into consideration if the administrator
354 // has giver permission
355 $customstr = $typeconfig['customparameters'];
356 $instructorcustomstr = $instance->instructorcustomparameters;
357 $custom = array();
358 $instructorcustom = array();
359 if ($customstr) {
dbb0fec9 360 $custom = lti_split_custom_parameters($customstr);
b9b2e7bb 361 }
e91be4ff 362 if (isset($typeconfig['allowinstructorcustom']) && $typeconfig['allowinstructorcustom'] == LTI_SETTING_NEVER) {
b9b2e7bb
CS
363 $requestparams = array_merge($custom, $requestparams);
364 } else {
365 if ($instructorcustomstr) {
dbb0fec9 366 $instructorcustom = lti_split_custom_parameters($instructorcustomstr);
b9b2e7bb
CS
367 }
368 foreach ($instructorcustom as $key => $val) {
ea04a9f9
EL
369 // Ignore the instructor's parameter
370 if (!array_key_exists($key, $custom)) {
b9b2e7bb
CS
371 $custom[$key] = $val;
372 }
373 }
374 $requestparams = array_merge($custom, $requestparams);
375 }
376
3dd9ca24
CS
377 // Make sure we let the tool know what LMS they are being called from
378 $requestparams["ext_lms"] = "moodle-2";
34eb0501
CS
379 $requestparams['tool_consumer_info_product_family_code'] = 'moodle';
380 $requestparams['tool_consumer_info_version'] = strval($CFG->version);
3dd9ca24
CS
381
382 // Add oauth_callback to be compliant with the 1.0A spec
34eb0501 383 $requestparams['oauth_callback'] = 'about:blank';
3dd9ca24 384
558be8fc
CS
385 //The submit button needs to be part of the signature as it gets posted with the form.
386 //This needs to be here to support launching without javascript.
3dd9ca24 387 $submittext = get_string('press_to_submit', 'lti');
34eb0501 388 $requestparams['ext_submit'] = $submittext;
e27cb316 389
34eb0501
CS
390 $requestparams['lti_version'] = 'LTI-1p0';
391 $requestparams['lti_message_type'] = 'basic-lti-launch-request';
e27cb316 392
b9b2e7bb
CS
393 return $requestparams;
394}
395
ea04a9f9 396function lti_get_tool_table($tools, $id) {
99938034 397 global $CFG, $OUTPUT, $USER;
795dff01 398 $html = '';
e27cb316 399
795dff01
CS
400 $typename = get_string('typename', 'lti');
401 $baseurl = get_string('baseurl', 'lti');
402 $action = get_string('action', 'lti');
403 $createdon = get_string('createdon', 'lti');
e27cb316 404
ea04a9f9 405 if ($id == 'lti_configured') {
795dff01
CS
406 $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>';
407 }
e27cb316 408
795dff01 409 if (!empty($tools)) {
5de15b83
CS
410 $html .= "
411 <div id=\"{$id}_container\" style=\"margin-top:.5em;margin-bottom:.5em\">
412 <table id=\"{$id}_tools\">
795dff01
CS
413 <thead>
414 <tr>
415 <th>$typename</th>
416 <th>$baseurl</th>
417 <th>$createdon</th>
418 <th>$action</th>
419 </tr>
420 </thead>
5de15b83 421 ";
e27cb316 422
795dff01 423 foreach ($tools as $type) {
101ec5fd 424 $date = userdate($type->timecreated, get_string('strftimedatefullshort', 'core_langconfig'));
795dff01
CS
425 $accept = get_string('accept', 'lti');
426 $update = get_string('update', 'lti');
427 $delete = get_string('delete', 'lti');
e27cb316 428
baf41e4b
FM
429 $baseurl = new moodle_url('/mod/lti/typessettings.php', array(
430 'action' => 'accept',
431 'id' => $type->id,
432 'sesskey' => sesskey(),
433 'tab' => $id
434 ));
435
436 $accepthtml = $OUTPUT->action_icon($baseurl,
437 new pix_icon('t/check', $accept, '', array('class' => 'iconsmall')), null,
438 array('title' => $accept, 'class' => 'editing_accept'));
795dff01
CS
439
440 $deleteaction = 'delete';
e27cb316 441
ea04a9f9 442 if ($type->state == LTI_TOOL_STATE_CONFIGURED) {
795dff01
CS
443 $accepthtml = '';
444 }
e27cb316 445
ea04a9f9 446 if ($type->state != LTI_TOOL_STATE_REJECTED) {
795dff01
CS
447 $deleteaction = 'reject';
448 $delete = get_string('reject', 'lti');
449 }
e27cb316 450
baf41e4b
FM
451 $updateurl = clone($baseurl);
452 $updateurl->param('action', 'update');
453 $updatehtml = $OUTPUT->action_icon($updateurl,
73584712 454 new pix_icon('t/edit', $update, '', array('class' => 'iconsmall')), null,
baf41e4b
FM
455 array('title' => $update, 'class' => 'editing_update'));
456
457 $deleteurl = clone($baseurl);
458 $deleteurl->param('action', $deleteaction);
459 $deletehtml = $OUTPUT->action_icon($deleteurl,
73584712 460 new pix_icon('t/delete', $delete, '', array('class' => 'iconsmall')), null,
baf41e4b 461 array('title' => $delete, 'class' => 'editing_delete'));
5de15b83 462 $html .= "
795dff01
CS
463 <tr>
464 <td>
465 {$type->name}
466 </td>
467 <td>
468 {$type->baseurl}
469 </td>
470 <td>
471 {$date}
472 </td>
5de15b83 473 <td align=\"center\">
baf41e4b 474 {$accepthtml}{$updatehtml}{$deletehtml}
795dff01
CS
475 </td>
476 </tr>
5de15b83 477 ";
795dff01
CS
478 }
479 $html .= '</table></div>';
480 } else {
481 $html .= get_string('no_' . $id, 'lti');
482 }
e27cb316 483
795dff01
CS
484 return $html;
485}
486
b9b2e7bb
CS
487/**
488 * Splits the custom parameters field to the various parameters
489 *
490 * @param string $customstr String containing the parameters
491 *
492 * @return Array of custom parameters
493 */
dbb0fec9 494function lti_split_custom_parameters($customstr) {
b9b2e7bb
CS
495 $lines = preg_split("/[\n;]/", $customstr);
496 $retval = array();
497 foreach ($lines as $line) {
498 $pos = strpos($line, "=");
499 if ( $pos === false || $pos < 1 ) {
500 continue;
501 }
2f1e464a
PS
502 $key = trim(core_text::substr($line, 0, $pos));
503 $val = trim(core_text::substr($line, $pos+1, strlen($line)));
dbb0fec9 504 $key = lti_map_keyname($key);
b9b2e7bb
CS
505 $retval['custom_'.$key] = $val;
506 }
507 return $retval;
508}
509
510/**
511 * Used for building the names of the different custom parameters
512 *
513 * @param string $key Parameter name
514 *
515 * @return string Processed name
516 */
dbb0fec9 517function lti_map_keyname($key) {
b9b2e7bb 518 $newkey = "";
2f1e464a 519 $key = core_text::strtolower(trim($key));
b9b2e7bb
CS
520 foreach (str_split($key) as $ch) {
521 if ( ($ch >= 'a' && $ch <= 'z') || ($ch >= '0' && $ch <= '9') ) {
522 $newkey .= $ch;
523 } else {
524 $newkey .= '_';
525 }
526 }
527 return $newkey;
528}
529
530/**
16cac566 531 * Gets the IMS role string for the specified user and LTI course module.
e27cb316 532 *
16cac566
CS
533 * @param mixed $user User object or user id
534 * @param int $cmid The course module id of the LTI activity
535 * @return string A role string suitable for passing with an LTI launch
b9b2e7bb 536 */
1d4f052e 537function lti_get_ims_role($user, $cmid, $courseid) {
16cac566 538 $roles = array();
e27cb316 539
ea04a9f9 540 if (empty($cmid)) {
1d4f052e
CS
541 //If no cmid is passed, check if the user is a teacher in the course
542 //This allows other modules to programmatically "fake" a launch without
543 //a real LTI instance
c288a3db 544 $coursecontext = context_course::instance($courseid);
e27cb316 545
ea04a9f9 546 if (has_capability('moodle/course:manageactivities', $coursecontext)) {
1d4f052e
CS
547 array_push($roles, 'Instructor');
548 } else {
549 array_push($roles, 'Learner');
550 }
16cac566 551 } else {
c288a3db 552 $context = context_module::instance($cmid);
1d4f052e 553
ea04a9f9 554 if (has_capability('mod/lti:manage', $context)) {
1d4f052e
CS
555 array_push($roles, 'Instructor');
556 } else {
557 array_push($roles, 'Learner');
558 }
b9b2e7bb 559 }
1d4f052e 560
ea04a9f9 561 if (is_siteadmin($user)) {
8fa50fdd 562 array_push($roles, 'urn:lti:sysrole:ims/lis/Administrator', 'urn:lti:instrole:ims/lis/Administrator');
b9b2e7bb 563 }
e27cb316 564
16cac566 565 return join(',', $roles);
b9b2e7bb
CS
566}
567
568/**
569 * Returns configuration details for the tool
570 *
571 * @param int $typeid Basic LTI tool typeid
572 *
573 * @return array Tool Configuration
574 */
575function lti_get_type_config($typeid) {
576 global $DB;
577
5f136255
EL
578 $query = "SELECT name, value
579 FROM {lti_types_config}
580 WHERE typeid = :typeid1
581 UNION ALL
cc12ae6c 582 SELECT 'toolurl' AS name, " . $DB->sql_compare_text('baseurl', 1333) . " AS value
5f136255
EL
583 FROM {lti_types}
584 WHERE id = :typeid2";
e27cb316 585
b9b2e7bb 586 $typeconfig = array();
f17f4959 587 $configs = $DB->get_records_sql($query, array('typeid1' => $typeid, 'typeid2' => $typeid));
e27cb316 588
b9b2e7bb
CS
589 if (!empty($configs)) {
590 foreach ($configs as $config) {
591 $typeconfig[$config->name] = $config->value;
592 }
593 }
e27cb316 594
b9b2e7bb
CS
595 return $typeconfig;
596}
597
ea04a9f9 598function lti_get_tools_by_url($url, $state, $courseid = null) {
b9b2e7bb 599 $domain = lti_get_domain_from_url($url);
e27cb316 600
996b0fd9 601 return lti_get_tools_by_domain($domain, $state, $courseid);
b9b2e7bb
CS
602}
603
ea04a9f9 604function lti_get_tools_by_domain($domain, $state = null, $courseid = null) {
b9b2e7bb 605 global $DB, $SITE;
e27cb316 606
b9b2e7bb 607 $filters = array('tooldomain' => $domain);
e27cb316 608
b9b2e7bb
CS
609 $statefilter = '';
610 $coursefilter = '';
e27cb316 611
ea04a9f9 612 if ($state) {
b9b2e7bb
CS
613 $statefilter = 'AND state = :state';
614 }
e27cb316 615
ea04a9f9 616 if ($courseid && $courseid != $SITE->id) {
b9b2e7bb
CS
617 $coursefilter = 'OR course = :courseid';
618 }
e27cb316 619
5f136255
EL
620 $query = "SELECT *
621 FROM {lti_types}
622 WHERE tooldomain = :tooldomain
623 AND (course = :siteid $coursefilter)
624 $statefilter";
e27cb316 625
b9b2e7bb 626 return $DB->get_records_sql($query, array(
e27cb316
CS
627 'courseid' => $courseid,
628 'siteid' => $SITE->id,
629 'tooldomain' => $domain,
b9b2e7bb
CS
630 'state' => $state
631 ));
632}
633
634/**
635 * Returns all basicLTI tools configured by the administrator
636 *
637 */
6831c7cd 638function lti_filter_get_types($course) {
b9b2e7bb
CS
639 global $DB;
640
ea04a9f9 641 if (!empty($course)) {
6831c7cd
CS
642 $filter = array('course' => $course);
643 } else {
644 $filter = array();
645 }
e27cb316 646
6831c7cd 647 return $DB->get_records('lti_types', $filter);
b9b2e7bb
CS
648}
649
d81a603e
MN
650/**
651 * Given an array of tools, filter them based on their state
652 *
653 * @param array $tools An array of lti_types records
654 * @param int $state One of the LTI_TOOL_STATE_* constants
655 * @return array
656 */
657function lti_filter_tool_types(array $tools, $state) {
658 $return = array();
659 foreach ($tools as $key => $tool) {
660 if ($tool->state == $state) {
661 $return[$key] = $tool;
662 }
663 }
664 return $return;
665}
666
ea04a9f9 667function lti_get_types_for_add_instance() {
996b0fd9 668 global $DB, $SITE, $COURSE;
e27cb316 669
5f136255
EL
670 $query = "SELECT *
671 FROM {lti_types}
672 WHERE coursevisible = 1
673 AND (course = :siteid OR course = :courseid)
674 AND state = :active";
e27cb316 675
606ab1a1 676 $admintypes = $DB->get_records_sql($query, array('siteid' => $SITE->id, 'courseid' => $COURSE->id, 'active' => LTI_TOOL_STATE_CONFIGURED));
e27cb316 677
b9b2e7bb 678 $types = array();
200aeda6 679 $types[0] = (object)array('name' => get_string('automatic', 'lti'), 'course' => 0);
e27cb316 680
ea04a9f9 681 foreach ($admintypes as $type) {
16e8f130 682 $types[$type->id] = $type;
b9b2e7bb 683 }
e27cb316 684
b9b2e7bb
CS
685 return $types;
686}
687
ea04a9f9 688function lti_get_domain_from_url($url) {
b9b2e7bb 689 $matches = array();
e27cb316 690
ea04a9f9 691 if (preg_match(LTI_URL_DOMAIN_REGEX, $url, $matches)) {
b9b2e7bb
CS
692 return $matches[1];
693 }
694}
695
ea04a9f9 696function lti_get_tool_by_url_match($url, $courseid = null, $state = LTI_TOOL_STATE_CONFIGURED) {
b69dc429 697 $possibletools = lti_get_tools_by_url($url, $state, $courseid);
e27cb316 698
7023b65e 699 return lti_get_best_tool_by_url($url, $possibletools, $courseid);
b9b2e7bb
CS
700}
701
ea04a9f9 702function lti_get_url_thumbprint($url) {
8fa50fdd
MN
703 // Parse URL requires a schema otherwise everything goes into 'path'. Fixed 5.4.7 or later.
704 if (preg_match('/https?:\/\//', $url) !== 1) {
705 $url = 'http://'.$url;
706 }
b9b2e7bb 707 $urlparts = parse_url(strtolower($url));
ea04a9f9 708 if (!isset($urlparts['path'])) {
b9b2e7bb
CS
709 $urlparts['path'] = '';
710 }
e27cb316 711
ea04a9f9 712 if (!isset($urlparts['host'])) {
d8d04121
CS
713 $urlparts['host'] = '';
714 }
e27cb316 715
ea04a9f9 716 if (substr($urlparts['host'], 0, 4) === 'www.') {
d8d04121 717 $urlparts['host'] = substr($urlparts['host'], 4);
b9b2e7bb 718 }
e27cb316 719
b9b2e7bb
CS
720 return $urllower = $urlparts['host'] . '/' . $urlparts['path'];
721}
722
ea04a9f9
EL
723function lti_get_best_tool_by_url($url, $tools, $courseid = null) {
724 if (count($tools) === 0) {
b9b2e7bb
CS
725 return null;
726 }
e27cb316 727
b9b2e7bb 728 $urllower = lti_get_url_thumbprint($url);
e27cb316 729
ea04a9f9 730 foreach ($tools as $tool) {
b9b2e7bb 731 $tool->_matchscore = 0;
e27cb316 732
b9b2e7bb 733 $toolbaseurllower = lti_get_url_thumbprint($tool->baseurl);
e27cb316 734
ea04a9f9 735 if ($urllower === $toolbaseurllower) {
7023b65e 736 //100 points for exact thumbprint match
b9b2e7bb 737 $tool->_matchscore += 100;
ea04a9f9 738 } else if (substr($urllower, 0, strlen($toolbaseurllower)) === $toolbaseurllower) {
7023b65e 739 //50 points if tool thumbprint starts with the base URL thumbprint
b9b2e7bb
CS
740 $tool->_matchscore += 50;
741 }
e27cb316 742
7023b65e 743 //Prefer course tools over site tools
ea04a9f9 744 if (!empty($courseid)) {
4c598b13 745 //Minus 10 points for not matching the course id (global tools)
ea04a9f9 746 if ($tool->course != $courseid) {
7023b65e
CS
747 $tool->_matchscore -= 10;
748 }
749 }
b9b2e7bb 750 }
e27cb316 751
ea04a9f9
EL
752 $bestmatch = array_reduce($tools, function($value, $tool) {
753 if ($tool->_matchscore > $value->_matchscore) {
b9b2e7bb
CS
754 return $tool;
755 } else {
756 return $value;
757 }
e27cb316 758
b9b2e7bb 759 }, (object)array('_matchscore' => -1));
e27cb316 760
b9b2e7bb 761 //None of the tools are suitable for this URL
ea04a9f9 762 if ($bestmatch->_matchscore <= 0) {
b9b2e7bb
CS
763 return null;
764 }
e27cb316 765
b9b2e7bb
CS
766 return $bestmatch;
767}
768
ea04a9f9 769function lti_get_shared_secrets_by_key($key) {
020eea1b 770 global $DB;
e27cb316 771
020eea1b
CS
772 //Look up the shared secret for the specified key in both the types_config table (for configured tools)
773 //And in the lti resource table for ad-hoc tools
5f136255
EL
774 $query = "SELECT t2.value
775 FROM {lti_types_config} t1
776 JOIN {lti_types_config} t2 ON t1.typeid = t2.typeid
777 JOIN {lti_types} type ON t2.typeid = type.id
778 WHERE t1.name = 'resourcekey'
779 AND t1.value = :key1
780 AND t2.name = 'password'
781 AND type.state = :configured
782 UNION
783 SELECT password AS value
784 FROM {lti}
785 WHERE resourcekey = :key2";
e27cb316 786
feb30fd8 787 $sharedsecrets = $DB->get_records_sql($query, array('configured' => LTI_TOOL_STATE_CONFIGURED, 'key1' => $key, 'key2' => $key));
e27cb316 788
ea04a9f9 789 $values = array_map(function($item) {
020eea1b
CS
790 return $item->value;
791 }, $sharedsecrets);
e27cb316 792
020eea1b
CS
793 //There should really only be one shared secret per key. But, we can't prevent
794 //more than one getting entered. For instance, if the same key is used for two tool providers.
795 return $values;
796}
797
b9b2e7bb
CS
798/**
799 * Delete a Basic LTI configuration
800 *
801 * @param int $id Configuration id
802 */
803function lti_delete_type($id) {
804 global $DB;
805
806 //We should probably just copy the launch URL to the tool instances in this case... using a single query
807 /*
808 $instances = $DB->get_records('lti', array('typeid' => $id));
809 foreach ($instances as $instance) {
810 $instance->typeid = 0;
811 $DB->update_record('lti', $instance);
812 }*/
813
814 $DB->delete_records('lti_types', array('id' => $id));
815 $DB->delete_records('lti_types_config', array('typeid' => $id));
816}
817
ea04a9f9 818function lti_set_state_for_type($id, $state) {
b9b2e7bb 819 global $DB;
e27cb316 820
b9b2e7bb
CS
821 $DB->update_record('lti_types', array('id' => $id, 'state' => $state));
822}
823
824/**
825 * Transforms a basic LTI object to an array
826 *
827 * @param object $ltiobject Basic LTI object
828 *
829 * @return array Basic LTI configuration details
830 */
831function lti_get_config($ltiobject) {
832 $typeconfig = array();
833 $typeconfig = (array)$ltiobject;
834 $additionalconfig = lti_get_type_config($ltiobject->typeid);
835 $typeconfig = array_merge($typeconfig, $additionalconfig);
836 return $typeconfig;
837}
838
839/**
840 *
841 * Generates some of the tool configuration based on the instance details
842 *
843 * @param int $id
844 *
845 * @return Instance configuration
846 *
847 */
848function lti_get_type_config_from_instance($id) {
849 global $DB;
850
851 $instance = $DB->get_record('lti', array('id' => $id));
852 $config = lti_get_config($instance);
853
854 $type = new stdClass();
855 $type->lti_fix = $id;
856 if (isset($config['toolurl'])) {
857 $type->lti_toolurl = $config['toolurl'];
858 }
859 if (isset($config['instructorchoicesendname'])) {
860 $type->lti_sendname = $config['instructorchoicesendname'];
861 }
862 if (isset($config['instructorchoicesendemailaddr'])) {
863 $type->lti_sendemailaddr = $config['instructorchoicesendemailaddr'];
864 }
865 if (isset($config['instructorchoiceacceptgrades'])) {
866 $type->lti_acceptgrades = $config['instructorchoiceacceptgrades'];
867 }
868 if (isset($config['instructorchoiceallowroster'])) {
869 $type->lti_allowroster = $config['instructorchoiceallowroster'];
870 }
871
872 if (isset($config['instructorcustomparameters'])) {
873 $type->lti_allowsetting = $config['instructorcustomparameters'];
874 }
875 return $type;
876}
877
878/**
879 * Generates some of the tool configuration based on the admin configuration details
880 *
881 * @param int $id
882 *
883 * @return Configuration details
884 */
885function lti_get_type_type_config($id) {
886 global $DB;
887
888 $basicltitype = $DB->get_record('lti_types', array('id' => $id));
889 $config = lti_get_type_config($id);
890
036e84c3 891 $type = new stdClass();
5f72d102 892
b9b2e7bb 893 $type->lti_typename = $basicltitype->name;
e27cb316 894
6831c7cd 895 $type->typeid = $basicltitype->id;
e27cb316 896
b9b2e7bb 897 $type->lti_toolurl = $basicltitype->baseurl;
e27cb316 898
b9b2e7bb
CS
899 if (isset($config['resourcekey'])) {
900 $type->lti_resourcekey = $config['resourcekey'];
901 }
902 if (isset($config['password'])) {
903 $type->lti_password = $config['password'];
904 }
905
906 if (isset($config['sendname'])) {
907 $type->lti_sendname = $config['sendname'];
908 }
ea04a9f9 909 if (isset($config['instructorchoicesendname'])) {
b9b2e7bb
CS
910 $type->lti_instructorchoicesendname = $config['instructorchoicesendname'];
911 }
ea04a9f9 912 if (isset($config['sendemailaddr'])) {
b9b2e7bb
CS
913 $type->lti_sendemailaddr = $config['sendemailaddr'];
914 }
ea04a9f9 915 if (isset($config['instructorchoicesendemailaddr'])) {
b9b2e7bb
CS
916 $type->lti_instructorchoicesendemailaddr = $config['instructorchoicesendemailaddr'];
917 }
ea04a9f9 918 if (isset($config['acceptgrades'])) {
b9b2e7bb
CS
919 $type->lti_acceptgrades = $config['acceptgrades'];
920 }
ea04a9f9 921 if (isset($config['instructorchoiceacceptgrades'])) {
b9b2e7bb
CS
922 $type->lti_instructorchoiceacceptgrades = $config['instructorchoiceacceptgrades'];
923 }
ea04a9f9 924 if (isset($config['allowroster'])) {
b9b2e7bb
CS
925 $type->lti_allowroster = $config['allowroster'];
926 }
ea04a9f9 927 if (isset($config['instructorchoiceallowroster'])) {
b9b2e7bb
CS
928 $type->lti_instructorchoiceallowroster = $config['instructorchoiceallowroster'];
929 }
930
931 if (isset($config['customparameters'])) {
932 $type->lti_customparameters = $config['customparameters'];
933 }
934
ea04a9f9 935 if (isset($config['forcessl'])) {
d8d04121
CS
936 $type->lti_forcessl = $config['forcessl'];
937 }
e27cb316 938
b9b2e7bb
CS
939 if (isset($config['organizationid'])) {
940 $type->lti_organizationid = $config['organizationid'];
941 }
942 if (isset($config['organizationurl'])) {
943 $type->lti_organizationurl = $config['organizationurl'];
944 }
945 if (isset($config['organizationdescr'])) {
946 $type->lti_organizationdescr = $config['organizationdescr'];
947 }
948 if (isset($config['launchcontainer'])) {
949 $type->lti_launchcontainer = $config['launchcontainer'];
950 }
e27cb316 951
b9b2e7bb
CS
952 if (isset($config['coursevisible'])) {
953 $type->lti_coursevisible = $config['coursevisible'];
954 }
e27cb316 955
b9b2e7bb
CS
956 if (isset($config['debuglaunch'])) {
957 $type->lti_debuglaunch = $config['debuglaunch'];
958 }
e27cb316 959
b9b2e7bb 960 if (isset($config['module_class_type'])) {
036e84c3 961 $type->lti_module_class_type = $config['module_class_type'];
b9b2e7bb
CS
962 }
963
964 return $type;
965}
966
ea04a9f9 967function lti_prepare_type_for_save($type, $config) {
b9b2e7bb
CS
968 $type->baseurl = $config->lti_toolurl;
969 $type->tooldomain = lti_get_domain_from_url($config->lti_toolurl);
970 $type->name = $config->lti_typename;
e27cb316 971
b9b2e7bb
CS
972 $type->coursevisible = !empty($config->lti_coursevisible) ? $config->lti_coursevisible : 0;
973 $config->lti_coursevisible = $type->coursevisible;
e27cb316 974
d8d04121
CS
975 $type->forcessl = !empty($config->lti_forcessl) ? $config->lti_forcessl : 0;
976 $config->lti_forcessl = $type->forcessl;
e27cb316 977
b9b2e7bb 978 $type->timemodified = time();
e27cb316 979
b9b2e7bb
CS
980 unset ($config->lti_typename);
981 unset ($config->lti_toolurl);
982}
983
ea04a9f9 984function lti_update_type($type, $config) {
b9b2e7bb 985 global $DB;
e27cb316 986
b9b2e7bb 987 lti_prepare_type_for_save($type, $config);
e27cb316 988
b9b2e7bb
CS
989 if ($DB->update_record('lti_types', $type)) {
990 foreach ($config as $key => $value) {
991 if (substr($key, 0, 4)=='lti_' && !is_null($value)) {
992 $record = new StdClass();
993 $record->typeid = $type->id;
994 $record->name = substr($key, 4);
995 $record->value = $value;
e27cb316 996
b9b2e7bb
CS
997 lti_update_config($record);
998 }
999 }
1000 }
1001}
1002
ea04a9f9 1003function lti_add_type($type, $config) {
b9b2e7bb 1004 global $USER, $SITE, $DB;
e27cb316 1005
b9b2e7bb 1006 lti_prepare_type_for_save($type, $config);
e27cb316 1007
ea04a9f9 1008 if (!isset($type->state)) {
b9b2e7bb
CS
1009 $type->state = LTI_TOOL_STATE_PENDING;
1010 }
e27cb316 1011
ea04a9f9 1012 if (!isset($type->timecreated)) {
b9b2e7bb
CS
1013 $type->timecreated = time();
1014 }
e27cb316 1015
ea04a9f9 1016 if (!isset($type->createdby)) {
b9b2e7bb
CS
1017 $type->createdby = $USER->id;
1018 }
e27cb316 1019
ea04a9f9 1020 if (!isset($type->course)) {
b9b2e7bb
CS
1021 $type->course = $SITE->id;
1022 }
e27cb316 1023
b9b2e7bb 1024 //Create a salt value to be used for signing passed data to extension services
6831c7cd
CS
1025 //The outcome service uses the service salt on the instance. This can be used
1026 //for communication with services not related to a specific LTI instance.
b9b2e7bb
CS
1027 $config->lti_servicesalt = uniqid('', true);
1028
1029 $id = $DB->insert_record('lti_types', $type);
1030
1031 if ($id) {
1032 foreach ($config as $key => $value) {
1033 if (substr($key, 0, 4)=='lti_' && !is_null($value)) {
1034 $record = new StdClass();
1035 $record->typeid = $id;
1036 $record->name = substr($key, 4);
1037 $record->value = $value;
1038
1039 lti_add_config($record);
1040 }
1041 }
1042 }
e27cb316 1043
996b0fd9 1044 return $id;
b9b2e7bb
CS
1045}
1046
1047/**
1048 * Add a tool configuration in the database
1049 *
1050 * @param $config Tool configuration
1051 *
1052 * @return int Record id number
1053 */
1054function lti_add_config($config) {
1055 global $DB;
1056
1057 return $DB->insert_record('lti_types_config', $config);
1058}
1059
1060/**
1061 * Updates a tool configuration in the database
1062 *
1063 * @param $config Tool configuration
1064 *
1065 * @return Record id number
1066 */
1067function lti_update_config($config) {
1068 global $DB;
1069
1070 $return = true;
1071 $old = $DB->get_record('lti_types_config', array('typeid' => $config->typeid, 'name' => $config->name));
e27cb316 1072
b9b2e7bb
CS
1073 if ($old) {
1074 $config->id = $old->id;
1075 $return = $DB->update_record('lti_types_config', $config);
1076 } else {
1077 $return = $DB->insert_record('lti_types_config', $config);
1078 }
1079 return $return;
1080}
1081
1082/**
1083 * Signs the petition to launch the external tool using OAuth
1084 *
1085 * @param $oldparms Parameters to be passed for signing
1086 * @param $endpoint url of the external tool
1087 * @param $method Method for sending the parameters (e.g. POST)
1088 * @param $oauth_consumoer_key Key
1089 * @param $oauth_consumoer_secret Secret
1090 * @param $submittext The text for the submit button
1091 * @param $orgid LMS name
1092 * @param $orgdesc LMS key
1093 */
3dd9ca24
CS
1094function lti_sign_parameters($oldparms, $endpoint, $method, $oauthconsumerkey, $oauthconsumersecret) {
1095 //global $lastbasestring;
b9b2e7bb 1096 $parms = $oldparms;
b9b2e7bb
CS
1097
1098 $testtoken = '';
e27cb316 1099
fabd4fcf 1100 // TODO: Switch to core oauthlib once implemented - MDL-30149
795dff01
CS
1101 $hmacmethod = new lti\OAuthSignatureMethod_HMAC_SHA1();
1102 $testconsumer = new lti\OAuthConsumer($oauthconsumerkey, $oauthconsumersecret, null);
795dff01 1103 $accreq = lti\OAuthRequest::from_consumer_and_token($testconsumer, $testtoken, $method, $endpoint, $parms);
b9b2e7bb
CS
1104 $accreq->sign_request($hmacmethod, $testconsumer, $testtoken);
1105
1106 // Pass this back up "out of band" for debugging
3dd9ca24 1107 //$lastbasestring = $accreq->get_signature_base_string();
b9b2e7bb
CS
1108
1109 $newparms = $accreq->get_parameters();
1110
1111 return $newparms;
1112}
1113
1114/**
1115 * Posts the launch petition HTML
1116 *
1117 * @param $newparms Signed parameters
1118 * @param $endpoint URL of the external tool
1119 * @param $debug Debug (true/false)
1120 */
dbb0fec9 1121function lti_post_launch_html($newparms, $endpoint, $debug=false) {
b9b2e7bb 1122 $r = "<form action=\"".$endpoint."\" name=\"ltiLaunchForm\" id=\"ltiLaunchForm\" method=\"post\" encType=\"application/x-www-form-urlencoded\">\n";
e27cb316 1123
b9b2e7bb
CS
1124 $submittext = $newparms['ext_submit'];
1125
1126 // Contruct html for the launch parameters
1127 foreach ($newparms as $key => $value) {
1128 $key = htmlspecialchars($key);
1129 $value = htmlspecialchars($value);
1130 if ( $key == "ext_submit" ) {
1131 $r .= "<input type=\"submit\" name=\"";
1132 } else {
1133 $r .= "<input type=\"hidden\" name=\"";
1134 }
1135 $r .= $key;
1136 $r .= "\" value=\"";
1137 $r .= $value;
1138 $r .= "\"/>\n";
1139 }
1140
1141 if ( $debug ) {
1142 $r .= "<script language=\"javascript\"> \n";
1143 $r .= " //<![CDATA[ \n";
1144 $r .= "function basicltiDebugToggle() {\n";
1145 $r .= " var ele = document.getElementById(\"basicltiDebug\");\n";
ea04a9f9 1146 $r .= " if (ele.style.display == \"block\") {\n";
b9b2e7bb
CS
1147 $r .= " ele.style.display = \"none\";\n";
1148 $r .= " }\n";
1149 $r .= " else {\n";
1150 $r .= " ele.style.display = \"block\";\n";
1151 $r .= " }\n";
1152 $r .= "} \n";
1153 $r .= " //]]> \n";
1154 $r .= "</script>\n";
1155 $r .= "<a id=\"displayText\" href=\"javascript:basicltiDebugToggle();\">";
1156 $r .= get_string("toggle_debug_data", "lti")."</a>\n";
1157 $r .= "<div id=\"basicltiDebug\" style=\"display:none\">\n";
1158 $r .= "<b>".get_string("basiclti_endpoint", "lti")."</b><br/>\n";
1159 $r .= $endpoint . "<br/>\n&nbsp;<br/>\n";
1160 $r .= "<b>".get_string("basiclti_parameters", "lti")."</b><br/>\n";
1161 foreach ($newparms as $key => $value) {
1162 $key = htmlspecialchars($key);
1163 $value = htmlspecialchars($value);
1164 $r .= "$key = $value<br/>\n";
1165 }
1166 $r .= "&nbsp;<br/>\n";
3dd9ca24 1167 //$r .= "<p><b>".get_string("basiclti_base_string", "lti")."</b><br/>\n".$lastbasestring."</p>\n";
b9b2e7bb
CS
1168 $r .= "</div>\n";
1169 }
1170 $r .= "</form>\n";
1171
1172 if ( ! $debug ) {
1173 $ext_submit = "ext_submit";
1174 $ext_submit_text = $submittext;
1175 $r .= " <script type=\"text/javascript\"> \n" .
1176 " //<![CDATA[ \n" .
1177 " document.getElementById(\"ltiLaunchForm\").style.display = \"none\";\n" .
1178 " nei = document.createElement('input');\n" .
1179 " nei.setAttribute('type', 'hidden');\n" .
1180 " nei.setAttribute('name', '".$ext_submit."');\n" .
1181 " nei.setAttribute('value', '".$ext_submit_text."');\n" .
1182 " document.getElementById(\"ltiLaunchForm\").appendChild(nei);\n" .
1183 " document.ltiLaunchForm.submit(); \n" .
1184 " //]]> \n" .
1185 " </script> \n";
1186 }
1187 return $r;
1188}
1189
ea04a9f9 1190function lti_get_type($typeid) {
996b0fd9 1191 global $DB;
e27cb316 1192
996b0fd9 1193 return $DB->get_record('lti_types', array('id' => $typeid));
57d1dffd
CS
1194}
1195
ea04a9f9
EL
1196function lti_get_launch_container($lti, $toolconfig) {
1197 if (empty($lti->launchcontainer)) {
e27cb316
CS
1198 $lti->launchcontainer = LTI_LAUNCH_CONTAINER_DEFAULT;
1199 }
1200
ea04a9f9
EL
1201 if ($lti->launchcontainer == LTI_LAUNCH_CONTAINER_DEFAULT) {
1202 if (isset($toolconfig['launchcontainer'])) {
c4d80efe
CS
1203 $launchcontainer = $toolconfig['launchcontainer'];
1204 }
1205 } else {
1206 $launchcontainer = $lti->launchcontainer;
1207 }
e27cb316 1208
ea04a9f9 1209 if (empty($launchcontainer) || $launchcontainer == LTI_LAUNCH_CONTAINER_DEFAULT) {
c4d80efe
CS
1210 $launchcontainer = LTI_LAUNCH_CONTAINER_EMBED_NO_BLOCKS;
1211 }
57d1dffd 1212
c3d2fbf9 1213 $devicetype = core_useragent::get_device_type();
57d1dffd
CS
1214
1215 //Scrolling within the object element doesn't work on iOS or Android
1216 //Opening the popup window also had some issues in testing
1217 //For mobile devices, always take up the entire screen to ensure the best experience
c3d2fbf9 1218 if ($devicetype === core_useragent::DEVICETYPE_MOBILE || $devicetype === core_useragent::DEVICETYPE_TABLET ) {
57d1dffd
CS
1219 $launchcontainer = LTI_LAUNCH_CONTAINER_REPLACE_MOODLE_WINDOW;
1220 }
e27cb316 1221
57d1dffd 1222 return $launchcontainer;
d8d04121
CS
1223}
1224
1225function lti_request_is_using_ssl() {
33dca156
PS
1226 global $CFG;
1227 return (stripos($CFG->httpswwwroot, 'https://') === 0);
d8d04121
CS
1228}
1229
ea04a9f9
EL
1230function lti_ensure_url_is_https($url) {
1231 if (!strstr($url, '://')) {
d8d04121
CS
1232 $url = 'https://' . $url;
1233 } else {
1234 //If the URL starts with http, replace with https
ea04a9f9 1235 if (stripos($url, 'http://') === 0) {
adc23cc9 1236 $url = 'https://' . substr($url, 7);
d8d04121
CS
1237 }
1238 }
e27cb316 1239
d8d04121 1240 return $url;
61eb12d4 1241}
8fa50fdd
MN
1242
1243/**
1244 * Determines if we should try to log the request
1245 *
1246 * @param string $rawbody
1247 * @return bool
1248 */
1249function lti_should_log_request($rawbody) {
1250 global $CFG;
1251
1252 if (empty($CFG->mod_lti_log_users)) {
1253 return false;
1254 }
1255
1256 $logusers = explode(',', $CFG->mod_lti_log_users);
1257 if (empty($logusers)) {
1258 return false;
1259 }
1260
1261 try {
1262 $xml = new SimpleXMLElement($rawbody);
1263 $ns = $xml->getNamespaces();
1264 $ns = array_shift($ns);
1265 $xml->registerXPathNamespace('lti', $ns);
1266 $requestuserid = '';
1267 if ($node = $xml->xpath('//lti:userId')) {
1268 $node = $node[0];
1269 $requestuserid = clean_param((string) $node, PARAM_INT);
1270 } else if ($node = $xml->xpath('//lti:sourcedId')) {
1271 $node = $node[0];
1272 $resultjson = json_decode((string) $node);
1273 $requestuserid = clean_param($resultjson->data->userid, PARAM_INT);
1274 }
1275 } catch (Exception $e) {
1276 return false;
1277 }
1278
1279 if (empty($requestuserid) or !in_array($requestuserid, $logusers)) {
1280 return false;
1281 }
1282
1283 return true;
1284}
1285
1286/**
1287 * Logs the request to a file in temp dir
1288 *
1289 * @param string $rawbody
1290 */
1291function lti_log_request($rawbody) {
1292 if ($tempdir = make_temp_directory('mod_lti', false)) {
1293 if ($tempfile = tempnam($tempdir, 'mod_lti_request'.date('YmdHis'))) {
1294 file_put_contents($tempfile, $rawbody);
1295 chmod($tempfile, 0644);
1296 }
1297 }
1298}
1299
1300/**
1301 * Fetches LTI type configuration for an LTI instance
1302 *
1303 * @param stdClass $instance
1304 * @return array Can be empty if no type is found
1305 */
1306function lti_get_type_config_by_instance($instance) {
1307 $typeid = null;
1308 if (empty($instance->typeid)) {
1309 $tool = lti_get_tool_by_url_match($instance->toolurl, $instance->course);
1310 if ($tool) {
1311 $typeid = $tool->id;
1312 }
1313 } else {
1314 $typeid = $instance->typeid;
1315 }
1316 if (!empty($typeid)) {
1317 return lti_get_type_config($typeid);
1318 }
1319 return array();
1320}
1321
1322/**
1323 * Enforce type config settings onto the LTI instance
1324 *
1325 * @param stdClass $instance
1326 * @param array $typeconfig
1327 */
1328function lti_force_type_config_settings($instance, array $typeconfig) {
1329 $forced = array(
1330 'instructorchoicesendname' => 'sendname',
1331 'instructorchoicesendemailaddr' => 'sendemailaddr',
1332 'instructorchoiceacceptgrades' => 'acceptgrades',
1333 );
1334
1335 foreach ($forced as $instanceparam => $typeconfigparam) {
1336 if (array_key_exists($typeconfigparam, $typeconfig) && $typeconfig[$typeconfigparam] != LTI_SETTING_DELEGATE) {
1337 $instance->$instanceparam = $typeconfig[$typeconfigparam];
1338 }
1339 }
1340}
1341