MDL-20534 lti: Updating the tool consumer information strings to match newest spec...
[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 *
61eb12d4
CS
38 * @package mod
39 * @subpackage lti
40 * @copyright 2009 Marc Alier, Jordi Piguillem, Nikolas Galanis
b9b2e7bb 41 * marc.alier@upc.edu
61eb12d4
CS
42 * @copyright 2009 Universitat Politecnica de Catalunya http://www.upc.edu
43 * @author Marc Alier
44 * @author Jordi Piguillem
45 * @author Nikolas Galanis
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
CS
152 $course = $PAGE->course;
153 $requestparams = lti_build_request($instance, $typeconfig, $course);
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 }
e27cb316 161
ea04a9f9 162 if (empty($key) || empty($secret)) {
9d57ad17 163 $returnurlparams['unsigned'] = '1';
e27cb316 164
9d57ad17 165 //Add the return URL. We send the launch container along to help us avoid frames-within-frames when the user returns
c4d80efe 166 $url = new moodle_url('/mod/lti/return.php', $returnurlparams);
d8d04121 167 $returnurl = $url->out(false);
e27cb316 168
ea04a9f9 169 if ($typeconfig['forcessl'] == '1') {
d8d04121
CS
170 $returnurl = lti_ensure_url_is_https($returnurl);
171 }
e27cb316 172
d8d04121 173 $requestparams['launch_presentation_return_url'] = $returnurl;
9d57ad17 174 }
e27cb316 175
ea04a9f9 176 if (!empty($key) && !empty($secret)) {
3dd9ca24
CS
177 $parms = lti_sign_parameters($requestparams, $endpoint, "POST", $key, $secret);
178 } else {
179 //If no key and secret, do the launch unsigned.
180 $parms = $requestparams;
3dd9ca24 181 }
e27cb316 182
b9b2e7bb 183 $debuglaunch = ( $instance->debuglaunch == 1 );
e27cb316 184
dbb0fec9 185 $content = lti_post_launch_html($parms, $endpoint, $debuglaunch);
e27cb316 186
b9b2e7bb
CS
187 echo $content;
188}
189
ea04a9f9 190function lti_build_sourcedid($instanceid, $userid, $launchid = null, $servicesalt) {
996b0fd9 191 $data = new stdClass();
e27cb316 192
996b0fd9
CS
193 $data->instanceid = $instanceid;
194 $data->userid = $userid;
ea04a9f9 195 if (!empty($launchid)) {
f4f711d7
CS
196 $data->launchid = $launchid;
197 } else {
198 $data->launchid = mt_rand();
199 }
996b0fd9
CS
200
201 $json = json_encode($data);
202
203 $hash = hash('sha256', $json . $servicesalt, false);
204
205 $container = new stdClass();
206 $container->data = $data;
207 $container->hash = $hash;
208
209 return $container;
210}
211
b9b2e7bb
CS
212/**
213 * This function builds the request that must be sent to the tool producer
214 *
215 * @param object $instance Basic LTI instance object
216 * @param object $typeconfig Basic LTI tool configuration
217 * @param object $course Course object
218 *
219 * @return array $request Request details
220 */
221function lti_build_request($instance, $typeconfig, $course) {
222 global $USER, $CFG;
223
ea04a9f9 224 if (empty($instance->cmid)) {
16cac566
CS
225 $instance->cmid = 0;
226 }
e27cb316 227
1d4f052e 228 $role = lti_get_ims_role($USER, $instance->cmid, $instance->course);
b9b2e7bb
CS
229
230 $locale = $course->lang;
231 if ( strlen($locale) < 1 ) {
232 $locale = $CFG->lang;
233 }
234
235 $requestparams = array(
236 "resource_link_id" => $instance->id,
237 "resource_link_title" => $instance->name,
238 "resource_link_description" => $instance->intro,
239 "user_id" => $USER->id,
240 "roles" => $role,
241 "context_id" => $course->id,
242 "context_label" => $course->shortname,
243 "context_title" => $course->fullname,
244 "launch_presentation_locale" => $locale,
245 );
246
b9b2e7bb 247 $placementsecret = $instance->servicesalt;
e27cb316 248
b9b2e7bb 249 if ( isset($placementsecret) ) {
f4f711d7 250 $sourcedid = json_encode(lti_build_sourcedid($instance->id, $USER->id, null, $placementsecret));
b9b2e7bb
CS
251 }
252
253 if ( isset($placementsecret) &&
5e078d62
CS
254 ( $typeconfig['acceptgrades'] == LTI_SETTING_ALWAYS ||
255 ( $typeconfig['acceptgrades'] == LTI_SETTING_DELEGATE && $instance->instructorchoiceacceptgrades == LTI_SETTING_ALWAYS ) ) ) {
0297a3d4 256 $requestparams['lis_result_sourcedid'] = $sourcedid;
e27cb316 257
d8d04121 258 $serviceurl = $CFG->wwwroot . '/mod/lti/service.php';
ea04a9f9 259 if ($typeconfig['forcessl'] == '1') {
d8d04121
CS
260 $serviceurl = lti_ensure_url_is_https($serviceurl);
261 }
e27cb316 262
0297a3d4 263 $requestparams['ext_ims_lis_basic_outcome_url'] = $serviceurl;
b9b2e7bb
CS
264 }
265
9d57ad17 266 /*if ( isset($placementsecret) &&
5e078d62
CS
267 ( $typeconfig['allowroster'] == LTI_SETTING_ALWAYS ||
268 ( $typeconfig['allowroster'] == LTI_SETTING_DELEGATE && $instance->instructorchoiceallowroster == LTI_SETTING_ALWAYS ) ) ) {
b9b2e7bb
CS
269 $requestparams["ext_ims_lis_memberships_id"] = $sourcedid;
270 $requestparams["ext_ims_lis_memberships_url"] = $CFG->wwwroot.'/mod/lti/service.php';
9d57ad17 271 }*/
b9b2e7bb
CS
272
273 // Send user's name and email data if appropriate
5e078d62
CS
274 if ( $typeconfig['sendname'] == LTI_SETTING_ALWAYS ||
275 ( $typeconfig['sendname'] == LTI_SETTING_DELEGATE && $instance->instructorchoicesendname == LTI_SETTING_ALWAYS ) ) {
0297a3d4
CS
276 $requestparams['lis_person_name_given'] = $USER->firstname;
277 $requestparams['lis_person_name_family'] = $USER->lastname;
278 $requestparams['lis_person_name_full'] = $USER->firstname." ".$USER->lastname;
b9b2e7bb
CS
279 }
280
5e078d62
CS
281 if ( $typeconfig['sendemailaddr'] == LTI_SETTING_ALWAYS ||
282 ( $typeconfig['sendemailaddr'] == LTI_SETTING_DELEGATE && $instance->instructorchoicesendemailaddr == LTI_SETTING_ALWAYS ) ) {
0297a3d4 283 $requestparams['lis_person_contact_email_primary'] = $USER->email;
b9b2e7bb
CS
284 }
285
3ff01b2f
CS
286 //Add outcome service URL
287 $url = new moodle_url('/mod/lti/service.php');
288 $requestparams['lis_outcome_service_url'] = $url->out();
57d1dffd 289
b9b2e7bb
CS
290 // Concatenate the custom parameters from the administrator and the instructor
291 // Instructor parameters are only taken into consideration if the administrator
292 // has giver permission
293 $customstr = $typeconfig['customparameters'];
294 $instructorcustomstr = $instance->instructorcustomparameters;
295 $custom = array();
296 $instructorcustom = array();
297 if ($customstr) {
dbb0fec9 298 $custom = lti_split_custom_parameters($customstr);
b9b2e7bb 299 }
5e078d62 300 if (!isset($typeconfig['allowinstructorcustom']) || $typeconfig['allowinstructorcustom'] == LTI_SETTING_NEVER) {
b9b2e7bb
CS
301 $requestparams = array_merge($custom, $requestparams);
302 } else {
303 if ($instructorcustomstr) {
dbb0fec9 304 $instructorcustom = lti_split_custom_parameters($instructorcustomstr);
b9b2e7bb
CS
305 }
306 foreach ($instructorcustom as $key => $val) {
ea04a9f9
EL
307 // Ignore the instructor's parameter
308 if (!array_key_exists($key, $custom)) {
b9b2e7bb
CS
309 $custom[$key] = $val;
310 }
311 }
312 $requestparams = array_merge($custom, $requestparams);
313 }
314
3dd9ca24 315 // Make sure we let the tool know what LMS they are being called from
0297a3d4
CS
316 $requestparams['ext_lms'] = 'moodle-2';
317 $requestparams['tool_consumer_info_product_family_code'] = 'moodle';
318 $requestparams['tool_consumer_info_version'] = strval($CFG->version);
3dd9ca24
CS
319
320 // Add oauth_callback to be compliant with the 1.0A spec
0297a3d4 321 $requestparams['oauth_callback'] = 'about:blank';
3dd9ca24 322
558be8fc
CS
323 //The submit button needs to be part of the signature as it gets posted with the form.
324 //This needs to be here to support launching without javascript.
3dd9ca24 325 $submittext = get_string('press_to_submit', 'lti');
0297a3d4 326 $requestparams['ext_submit'] = $submittext;
e27cb316 327
0297a3d4
CS
328 $requestparams['lti_version'] = 'LTI-1p0';
329 $requestparams['lti_message_type'] = 'basic-lti-launch-request';
3dd9ca24
CS
330 /* Suppress this for now - Chuck
331 if ( $orgdesc ) $requestparams["tool_consumer_instance_description"] = $orgdesc;
332 */
e27cb316 333
b9b2e7bb
CS
334 return $requestparams;
335}
336
ea04a9f9 337function lti_get_tool_table($tools, $id) {
795dff01
CS
338 global $CFG, $USER;
339 $html = '';
e27cb316 340
795dff01
CS
341 $typename = get_string('typename', 'lti');
342 $baseurl = get_string('baseurl', 'lti');
343 $action = get_string('action', 'lti');
344 $createdon = get_string('createdon', 'lti');
e27cb316 345
ea04a9f9 346 if ($id == 'lti_configured') {
795dff01
CS
347 $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>';
348 }
e27cb316 349
795dff01 350 if (!empty($tools)) {
5de15b83
CS
351 $html .= "
352 <div id=\"{$id}_container\" style=\"margin-top:.5em;margin-bottom:.5em\">
353 <table id=\"{$id}_tools\">
795dff01
CS
354 <thead>
355 <tr>
356 <th>$typename</th>
357 <th>$baseurl</th>
358 <th>$createdon</th>
359 <th>$action</th>
360 </tr>
361 </thead>
5de15b83 362 ";
e27cb316 363
795dff01
CS
364 foreach ($tools as $type) {
365 $date = userdate($type->timecreated);
366 $accept = get_string('accept', 'lti');
367 $update = get_string('update', 'lti');
368 $delete = get_string('delete', 'lti');
e27cb316 369
5de15b83
CS
370 $accepthtml = "
371 <a class=\"editing_accept\" href=\"{$CFG->wwwroot}/mod/lti/typessettings.php?action=accept&amp;id={$type->id}&amp;sesskey={$USER->sesskey}&amp;tab={$id}\" title=\"{$accept}\">
372 <img class=\"iconsmall\" alt=\"{$accept}\" src=\"{$CFG->wwwroot}/pix/t/clear.gif\"/>
795dff01 373 </a>
5de15b83 374 ";
795dff01
CS
375
376 $deleteaction = 'delete';
e27cb316 377
ea04a9f9 378 if ($type->state == LTI_TOOL_STATE_CONFIGURED) {
795dff01
CS
379 $accepthtml = '';
380 }
e27cb316 381
ea04a9f9 382 if ($type->state != LTI_TOOL_STATE_REJECTED) {
795dff01
CS
383 $deleteaction = 'reject';
384 $delete = get_string('reject', 'lti');
385 }
e27cb316 386
5de15b83 387 $html .= "
795dff01
CS
388 <tr>
389 <td>
390 {$type->name}
391 </td>
392 <td>
393 {$type->baseurl}
394 </td>
395 <td>
396 {$date}
397 </td>
5de15b83 398 <td align=\"center\">
795dff01 399 {$accepthtml}
5de15b83
CS
400 <a class=\"editing_update\" href=\"{$CFG->wwwroot}/mod/lti/typessettings.php?action=update&amp;id={$type->id}&amp;sesskey={$USER->sesskey}&amp;tab={$id}\" title=\"{$update}\">
401 <img class=\"iconsmall\" alt=\"{$update}\" src=\"{$CFG->wwwroot}/pix/t/edit.gif\"/>
795dff01 402 </a>
5de15b83
CS
403 <a class=\"editing_delete\" href=\"{$CFG->wwwroot}/mod/lti/typessettings.php?action={$deleteaction}&amp;id={$type->id}&amp;sesskey={$USER->sesskey}&amp;tab={$id}\" title=\"{$delete}\">
404 <img class=\"iconsmall\" alt=\"{$delete}\" src=\"{$CFG->wwwroot}/pix/t/delete.gif\"/>
795dff01
CS
405 </a>
406 </td>
407 </tr>
5de15b83 408 ";
795dff01
CS
409 }
410 $html .= '</table></div>';
411 } else {
412 $html .= get_string('no_' . $id, 'lti');
413 }
e27cb316 414
795dff01
CS
415 return $html;
416}
417
b9b2e7bb
CS
418/**
419 * Splits the custom parameters field to the various parameters
420 *
421 * @param string $customstr String containing the parameters
422 *
423 * @return Array of custom parameters
424 */
dbb0fec9 425function lti_split_custom_parameters($customstr) {
b9b2e7bb
CS
426 $textlib = textlib_get_instance();
427
428 $lines = preg_split("/[\n;]/", $customstr);
429 $retval = array();
430 foreach ($lines as $line) {
431 $pos = strpos($line, "=");
432 if ( $pos === false || $pos < 1 ) {
433 continue;
434 }
435 $key = trim($textlib->substr($line, 0, $pos));
436 $val = trim($textlib->substr($line, $pos+1));
dbb0fec9 437 $key = lti_map_keyname($key);
b9b2e7bb
CS
438 $retval['custom_'.$key] = $val;
439 }
440 return $retval;
441}
442
443/**
444 * Used for building the names of the different custom parameters
445 *
446 * @param string $key Parameter name
447 *
448 * @return string Processed name
449 */
dbb0fec9 450function lti_map_keyname($key) {
b9b2e7bb
CS
451 $textlib = textlib_get_instance();
452
453 $newkey = "";
454 $key = $textlib->strtolower(trim($key));
455 foreach (str_split($key) as $ch) {
456 if ( ($ch >= 'a' && $ch <= 'z') || ($ch >= '0' && $ch <= '9') ) {
457 $newkey .= $ch;
458 } else {
459 $newkey .= '_';
460 }
461 }
462 return $newkey;
463}
464
465/**
16cac566 466 * Gets the IMS role string for the specified user and LTI course module.
e27cb316 467 *
16cac566
CS
468 * @param mixed $user User object or user id
469 * @param int $cmid The course module id of the LTI activity
470 * @return string A role string suitable for passing with an LTI launch
b9b2e7bb 471 */
1d4f052e 472function lti_get_ims_role($user, $cmid, $courseid) {
16cac566 473 $roles = array();
e27cb316 474
ea04a9f9 475 if (empty($cmid)) {
1d4f052e
CS
476 //If no cmid is passed, check if the user is a teacher in the course
477 //This allows other modules to programmatically "fake" a launch without
478 //a real LTI instance
479 $coursecontext = get_context_instance(CONTEXT_COURSE, $courseid);
e27cb316 480
ea04a9f9 481 if (has_capability('moodle/course:manageactivities', $coursecontext)) {
1d4f052e
CS
482 array_push($roles, 'Instructor');
483 } else {
484 array_push($roles, 'Learner');
485 }
16cac566 486 } else {
1d4f052e
CS
487 $context = get_context_instance(CONTEXT_MODULE, $cmid);
488
ea04a9f9 489 if (has_capability('mod/lti:manage', $context)) {
1d4f052e
CS
490 array_push($roles, 'Instructor');
491 } else {
492 array_push($roles, 'Learner');
493 }
b9b2e7bb 494 }
1d4f052e 495
ea04a9f9 496 if (is_siteadmin($user)) {
16cac566 497 array_push($roles, 'urn:lti:sysrole:ims/lis/Administrator');
b9b2e7bb 498 }
e27cb316 499
16cac566 500 return join(',', $roles);
b9b2e7bb
CS
501}
502
503/**
504 * Returns configuration details for the tool
505 *
506 * @param int $typeid Basic LTI tool typeid
507 *
508 * @return array Tool Configuration
509 */
510function lti_get_type_config($typeid) {
511 global $DB;
512
5f136255
EL
513 $query = "SELECT name, value
514 FROM {lti_types_config}
515 WHERE typeid = :typeid1
516 UNION ALL
517 SELECT 'toolurl' AS name, baseurl AS value
518 FROM {lti_types}
519 WHERE id = :typeid2";
e27cb316 520
b9b2e7bb 521 $typeconfig = array();
f17f4959 522 $configs = $DB->get_records_sql($query, array('typeid1' => $typeid, 'typeid2' => $typeid));
e27cb316 523
b9b2e7bb
CS
524 if (!empty($configs)) {
525 foreach ($configs as $config) {
526 $typeconfig[$config->name] = $config->value;
527 }
528 }
e27cb316 529
b9b2e7bb
CS
530 return $typeconfig;
531}
532
ea04a9f9 533function lti_get_tools_by_url($url, $state, $courseid = null) {
b9b2e7bb 534 $domain = lti_get_domain_from_url($url);
e27cb316 535
996b0fd9 536 return lti_get_tools_by_domain($domain, $state, $courseid);
b9b2e7bb
CS
537}
538
ea04a9f9 539function lti_get_tools_by_domain($domain, $state = null, $courseid = null) {
b9b2e7bb 540 global $DB, $SITE;
e27cb316 541
b9b2e7bb 542 $filters = array('tooldomain' => $domain);
e27cb316 543
b9b2e7bb
CS
544 $statefilter = '';
545 $coursefilter = '';
e27cb316 546
ea04a9f9 547 if ($state) {
b9b2e7bb
CS
548 $statefilter = 'AND state = :state';
549 }
e27cb316 550
ea04a9f9 551 if ($courseid && $courseid != $SITE->id) {
b9b2e7bb
CS
552 $coursefilter = 'OR course = :courseid';
553 }
e27cb316 554
5f136255
EL
555 $query = "SELECT *
556 FROM {lti_types}
557 WHERE tooldomain = :tooldomain
558 AND (course = :siteid $coursefilter)
559 $statefilter";
e27cb316 560
b9b2e7bb 561 return $DB->get_records_sql($query, array(
e27cb316
CS
562 'courseid' => $courseid,
563 'siteid' => $SITE->id,
564 'tooldomain' => $domain,
b9b2e7bb
CS
565 'state' => $state
566 ));
567}
568
569/**
570 * Returns all basicLTI tools configured by the administrator
571 *
572 */
6831c7cd 573function lti_filter_get_types($course) {
b9b2e7bb
CS
574 global $DB;
575
ea04a9f9 576 if (!empty($course)) {
6831c7cd
CS
577 $filter = array('course' => $course);
578 } else {
579 $filter = array();
580 }
e27cb316 581
6831c7cd 582 return $DB->get_records('lti_types', $filter);
b9b2e7bb
CS
583}
584
ea04a9f9 585function lti_get_types_for_add_instance() {
996b0fd9 586 global $DB, $SITE, $COURSE;
e27cb316 587
5f136255
EL
588 $query = "SELECT *
589 FROM {lti_types}
590 WHERE coursevisible = 1
591 AND (course = :siteid OR course = :courseid)
592 AND state = :active";
e27cb316 593
606ab1a1 594 $admintypes = $DB->get_records_sql($query, array('siteid' => $SITE->id, 'courseid' => $COURSE->id, 'active' => LTI_TOOL_STATE_CONFIGURED));
e27cb316 595
b9b2e7bb 596 $types = array();
996b0fd9 597 $types[0] = (object)array('name' => get_string('automatic', 'lti'), 'course' => $SITE->id);
e27cb316 598
ea04a9f9 599 foreach ($admintypes as $type) {
16e8f130 600 $types[$type->id] = $type;
b9b2e7bb 601 }
e27cb316 602
b9b2e7bb
CS
603 return $types;
604}
605
ea04a9f9 606function lti_get_domain_from_url($url) {
b9b2e7bb 607 $matches = array();
e27cb316 608
ea04a9f9 609 if (preg_match(LTI_URL_DOMAIN_REGEX, $url, $matches)) {
b9b2e7bb
CS
610 return $matches[1];
611 }
612}
613
ea04a9f9 614function lti_get_tool_by_url_match($url, $courseid = null, $state = LTI_TOOL_STATE_CONFIGURED) {
b69dc429 615 $possibletools = lti_get_tools_by_url($url, $state, $courseid);
e27cb316 616
7023b65e 617 return lti_get_best_tool_by_url($url, $possibletools, $courseid);
b9b2e7bb
CS
618}
619
ea04a9f9 620function lti_get_url_thumbprint($url) {
b9b2e7bb 621 $urlparts = parse_url(strtolower($url));
ea04a9f9 622 if (!isset($urlparts['path'])) {
b9b2e7bb
CS
623 $urlparts['path'] = '';
624 }
e27cb316 625
ea04a9f9 626 if (!isset($urlparts['host'])) {
d8d04121
CS
627 $urlparts['host'] = '';
628 }
e27cb316 629
ea04a9f9 630 if (substr($urlparts['host'], 0, 4) === 'www.') {
d8d04121 631 $urlparts['host'] = substr($urlparts['host'], 4);
b9b2e7bb 632 }
e27cb316 633
b9b2e7bb
CS
634 return $urllower = $urlparts['host'] . '/' . $urlparts['path'];
635}
636
ea04a9f9
EL
637function lti_get_best_tool_by_url($url, $tools, $courseid = null) {
638 if (count($tools) === 0) {
b9b2e7bb
CS
639 return null;
640 }
e27cb316 641
b9b2e7bb 642 $urllower = lti_get_url_thumbprint($url);
e27cb316 643
ea04a9f9 644 foreach ($tools as $tool) {
b9b2e7bb 645 $tool->_matchscore = 0;
e27cb316 646
b9b2e7bb 647 $toolbaseurllower = lti_get_url_thumbprint($tool->baseurl);
e27cb316 648
ea04a9f9 649 if ($urllower === $toolbaseurllower) {
7023b65e 650 //100 points for exact thumbprint match
b9b2e7bb 651 $tool->_matchscore += 100;
ea04a9f9 652 } else if (substr($urllower, 0, strlen($toolbaseurllower)) === $toolbaseurllower) {
7023b65e 653 //50 points if tool thumbprint starts with the base URL thumbprint
b9b2e7bb
CS
654 $tool->_matchscore += 50;
655 }
e27cb316 656
7023b65e 657 //Prefer course tools over site tools
ea04a9f9 658 if (!empty($courseid)) {
7023b65e 659 //Minus 25 points for not matching the course id (global tools)
ea04a9f9 660 if ($tool->course != $courseid) {
7023b65e
CS
661 $tool->_matchscore -= 10;
662 }
663 }
b9b2e7bb 664 }
e27cb316 665
ea04a9f9
EL
666 $bestmatch = array_reduce($tools, function($value, $tool) {
667 if ($tool->_matchscore > $value->_matchscore) {
b9b2e7bb
CS
668 return $tool;
669 } else {
670 return $value;
671 }
e27cb316 672
b9b2e7bb 673 }, (object)array('_matchscore' => -1));
e27cb316 674
b9b2e7bb 675 //None of the tools are suitable for this URL
ea04a9f9 676 if ($bestmatch->_matchscore <= 0) {
b9b2e7bb
CS
677 return null;
678 }
e27cb316 679
b9b2e7bb
CS
680 return $bestmatch;
681}
682
ea04a9f9 683function lti_get_shared_secrets_by_key($key) {
020eea1b 684 global $DB;
e27cb316 685
020eea1b
CS
686 //Look up the shared secret for the specified key in both the types_config table (for configured tools)
687 //And in the lti resource table for ad-hoc tools
5f136255
EL
688 $query = "SELECT t2.value
689 FROM {lti_types_config} t1
690 JOIN {lti_types_config} t2 ON t1.typeid = t2.typeid
691 JOIN {lti_types} type ON t2.typeid = type.id
692 WHERE t1.name = 'resourcekey'
693 AND t1.value = :key1
694 AND t2.name = 'password'
695 AND type.state = :configured
696 UNION
697 SELECT password AS value
698 FROM {lti}
699 WHERE resourcekey = :key2";
e27cb316 700
feb30fd8 701 $sharedsecrets = $DB->get_records_sql($query, array('configured' => LTI_TOOL_STATE_CONFIGURED, 'key1' => $key, 'key2' => $key));
e27cb316 702
ea04a9f9 703 $values = array_map(function($item) {
020eea1b
CS
704 return $item->value;
705 }, $sharedsecrets);
e27cb316 706
020eea1b
CS
707 //There should really only be one shared secret per key. But, we can't prevent
708 //more than one getting entered. For instance, if the same key is used for two tool providers.
709 return $values;
710}
711
b9b2e7bb
CS
712/**
713 * Prints the various configured tool types
714 *
715 */
716function lti_filter_print_types() {
717 global $CFG;
718
719 $types = lti_filter_get_types();
720 if (!empty($types)) {
721 echo '<ul>';
722 foreach ($types as $type) {
723 echo '<li>'.
724 $type->name.
725 '<span class="commands">'.
726 '<a class="editing_update" href="typessettings.php?action=update&amp;id='.$type->id.'&amp;sesskey='.sesskey().'" title="Update">'.
727 '<img class="iconsmall" alt="Update" src="'.$CFG->wwwroot.'/pix/t/edit.gif"/>'.
728 '</a>'.
729 '<a class="editing_delete" href="typessettings.php?action=delete&amp;id='.$type->id.'&amp;sesskey='.sesskey().'" title="Delete">'.
730 '<img class="iconsmall" alt="Delete" src="'.$CFG->wwwroot.'/pix/t/delete.gif"/>'.
731 '</a>'.
732 '</span>'.
733 '</li>';
734
735 }
736 echo '</ul>';
737 } else {
738 echo '<div class="message">';
739 echo get_string('notypes', 'lti');
740 echo '</div>';
741 }
742}
743
744/**
745 * Delete a Basic LTI configuration
746 *
747 * @param int $id Configuration id
748 */
749function lti_delete_type($id) {
750 global $DB;
751
752 //We should probably just copy the launch URL to the tool instances in this case... using a single query
753 /*
754 $instances = $DB->get_records('lti', array('typeid' => $id));
755 foreach ($instances as $instance) {
756 $instance->typeid = 0;
757 $DB->update_record('lti', $instance);
758 }*/
759
760 $DB->delete_records('lti_types', array('id' => $id));
761 $DB->delete_records('lti_types_config', array('typeid' => $id));
762}
763
ea04a9f9 764function lti_set_state_for_type($id, $state) {
b9b2e7bb 765 global $DB;
e27cb316 766
b9b2e7bb
CS
767 $DB->update_record('lti_types', array('id' => $id, 'state' => $state));
768}
769
770/**
771 * Transforms a basic LTI object to an array
772 *
773 * @param object $ltiobject Basic LTI object
774 *
775 * @return array Basic LTI configuration details
776 */
777function lti_get_config($ltiobject) {
778 $typeconfig = array();
779 $typeconfig = (array)$ltiobject;
780 $additionalconfig = lti_get_type_config($ltiobject->typeid);
781 $typeconfig = array_merge($typeconfig, $additionalconfig);
782 return $typeconfig;
783}
784
785/**
786 *
787 * Generates some of the tool configuration based on the instance details
788 *
789 * @param int $id
790 *
791 * @return Instance configuration
792 *
793 */
794function lti_get_type_config_from_instance($id) {
795 global $DB;
796
797 $instance = $DB->get_record('lti', array('id' => $id));
798 $config = lti_get_config($instance);
799
800 $type = new stdClass();
801 $type->lti_fix = $id;
802 if (isset($config['toolurl'])) {
803 $type->lti_toolurl = $config['toolurl'];
804 }
805 if (isset($config['instructorchoicesendname'])) {
806 $type->lti_sendname = $config['instructorchoicesendname'];
807 }
808 if (isset($config['instructorchoicesendemailaddr'])) {
809 $type->lti_sendemailaddr = $config['instructorchoicesendemailaddr'];
810 }
811 if (isset($config['instructorchoiceacceptgrades'])) {
812 $type->lti_acceptgrades = $config['instructorchoiceacceptgrades'];
813 }
814 if (isset($config['instructorchoiceallowroster'])) {
815 $type->lti_allowroster = $config['instructorchoiceallowroster'];
816 }
817
818 if (isset($config['instructorcustomparameters'])) {
819 $type->lti_allowsetting = $config['instructorcustomparameters'];
820 }
821 return $type;
822}
823
824/**
825 * Generates some of the tool configuration based on the admin configuration details
826 *
827 * @param int $id
828 *
829 * @return Configuration details
830 */
831function lti_get_type_type_config($id) {
832 global $DB;
833
834 $basicltitype = $DB->get_record('lti_types', array('id' => $id));
835 $config = lti_get_type_config($id);
836
837 $type->lti_typename = $basicltitype->name;
e27cb316 838
6831c7cd 839 $type->typeid = $basicltitype->id;
e27cb316 840
b9b2e7bb 841 $type->lti_toolurl = $basicltitype->baseurl;
e27cb316 842
b9b2e7bb
CS
843 if (isset($config['resourcekey'])) {
844 $type->lti_resourcekey = $config['resourcekey'];
845 }
846 if (isset($config['password'])) {
847 $type->lti_password = $config['password'];
848 }
849
850 if (isset($config['sendname'])) {
851 $type->lti_sendname = $config['sendname'];
852 }
ea04a9f9 853 if (isset($config['instructorchoicesendname'])) {
b9b2e7bb
CS
854 $type->lti_instructorchoicesendname = $config['instructorchoicesendname'];
855 }
ea04a9f9 856 if (isset($config['sendemailaddr'])) {
b9b2e7bb
CS
857 $type->lti_sendemailaddr = $config['sendemailaddr'];
858 }
ea04a9f9 859 if (isset($config['instructorchoicesendemailaddr'])) {
b9b2e7bb
CS
860 $type->lti_instructorchoicesendemailaddr = $config['instructorchoicesendemailaddr'];
861 }
ea04a9f9 862 if (isset($config['acceptgrades'])) {
b9b2e7bb
CS
863 $type->lti_acceptgrades = $config['acceptgrades'];
864 }
ea04a9f9 865 if (isset($config['instructorchoiceacceptgrades'])) {
b9b2e7bb
CS
866 $type->lti_instructorchoiceacceptgrades = $config['instructorchoiceacceptgrades'];
867 }
ea04a9f9 868 if (isset($config['allowroster'])) {
b9b2e7bb
CS
869 $type->lti_allowroster = $config['allowroster'];
870 }
ea04a9f9 871 if (isset($config['instructorchoiceallowroster'])) {
b9b2e7bb
CS
872 $type->lti_instructorchoiceallowroster = $config['instructorchoiceallowroster'];
873 }
874
875 if (isset($config['customparameters'])) {
876 $type->lti_customparameters = $config['customparameters'];
877 }
878
ea04a9f9 879 if (isset($config['forcessl'])) {
d8d04121
CS
880 $type->lti_forcessl = $config['forcessl'];
881 }
e27cb316 882
b9b2e7bb
CS
883 if (isset($config['organizationid'])) {
884 $type->lti_organizationid = $config['organizationid'];
885 }
886 if (isset($config['organizationurl'])) {
887 $type->lti_organizationurl = $config['organizationurl'];
888 }
889 if (isset($config['organizationdescr'])) {
890 $type->lti_organizationdescr = $config['organizationdescr'];
891 }
892 if (isset($config['launchcontainer'])) {
893 $type->lti_launchcontainer = $config['launchcontainer'];
894 }
e27cb316 895
b9b2e7bb
CS
896 if (isset($config['coursevisible'])) {
897 $type->lti_coursevisible = $config['coursevisible'];
898 }
e27cb316 899
b9b2e7bb
CS
900 if (isset($config['debuglaunch'])) {
901 $type->lti_debuglaunch = $config['debuglaunch'];
902 }
e27cb316 903
b9b2e7bb
CS
904 if (isset($config['module_class_type'])) {
905 $type->lti_module_class_type = $config['module_class_type'];
906 }
907
908 return $type;
909}
910
ea04a9f9 911function lti_prepare_type_for_save($type, $config) {
b9b2e7bb
CS
912 $type->baseurl = $config->lti_toolurl;
913 $type->tooldomain = lti_get_domain_from_url($config->lti_toolurl);
914 $type->name = $config->lti_typename;
e27cb316 915
b9b2e7bb
CS
916 $type->coursevisible = !empty($config->lti_coursevisible) ? $config->lti_coursevisible : 0;
917 $config->lti_coursevisible = $type->coursevisible;
e27cb316 918
d8d04121
CS
919 $type->forcessl = !empty($config->lti_forcessl) ? $config->lti_forcessl : 0;
920 $config->lti_forcessl = $type->forcessl;
e27cb316 921
b9b2e7bb 922 $type->timemodified = time();
e27cb316 923
b9b2e7bb
CS
924 unset ($config->lti_typename);
925 unset ($config->lti_toolurl);
926}
927
ea04a9f9 928function lti_update_type($type, $config) {
b9b2e7bb 929 global $DB;
e27cb316 930
b9b2e7bb 931 lti_prepare_type_for_save($type, $config);
e27cb316 932
b9b2e7bb
CS
933 if ($DB->update_record('lti_types', $type)) {
934 foreach ($config as $key => $value) {
935 if (substr($key, 0, 4)=='lti_' && !is_null($value)) {
936 $record = new StdClass();
937 $record->typeid = $type->id;
938 $record->name = substr($key, 4);
939 $record->value = $value;
e27cb316 940
b9b2e7bb
CS
941 lti_update_config($record);
942 }
943 }
944 }
945}
946
ea04a9f9 947function lti_add_type($type, $config) {
b9b2e7bb 948 global $USER, $SITE, $DB;
e27cb316 949
b9b2e7bb 950 lti_prepare_type_for_save($type, $config);
e27cb316 951
ea04a9f9 952 if (!isset($type->state)) {
b9b2e7bb
CS
953 $type->state = LTI_TOOL_STATE_PENDING;
954 }
e27cb316 955
ea04a9f9 956 if (!isset($type->timecreated)) {
b9b2e7bb
CS
957 $type->timecreated = time();
958 }
e27cb316 959
ea04a9f9 960 if (!isset($type->createdby)) {
b9b2e7bb
CS
961 $type->createdby = $USER->id;
962 }
e27cb316 963
ea04a9f9 964 if (!isset($type->course)) {
b9b2e7bb
CS
965 $type->course = $SITE->id;
966 }
e27cb316 967
b9b2e7bb 968 //Create a salt value to be used for signing passed data to extension services
6831c7cd
CS
969 //The outcome service uses the service salt on the instance. This can be used
970 //for communication with services not related to a specific LTI instance.
b9b2e7bb
CS
971 $config->lti_servicesalt = uniqid('', true);
972
973 $id = $DB->insert_record('lti_types', $type);
974
975 if ($id) {
976 foreach ($config as $key => $value) {
977 if (substr($key, 0, 4)=='lti_' && !is_null($value)) {
978 $record = new StdClass();
979 $record->typeid = $id;
980 $record->name = substr($key, 4);
981 $record->value = $value;
982
983 lti_add_config($record);
984 }
985 }
986 }
e27cb316 987
996b0fd9 988 return $id;
b9b2e7bb
CS
989}
990
991/**
992 * Add a tool configuration in the database
993 *
994 * @param $config Tool configuration
995 *
996 * @return int Record id number
997 */
998function lti_add_config($config) {
999 global $DB;
1000
1001 return $DB->insert_record('lti_types_config', $config);
1002}
1003
1004/**
1005 * Updates a tool configuration in the database
1006 *
1007 * @param $config Tool configuration
1008 *
1009 * @return Record id number
1010 */
1011function lti_update_config($config) {
1012 global $DB;
1013
1014 $return = true;
1015 $old = $DB->get_record('lti_types_config', array('typeid' => $config->typeid, 'name' => $config->name));
e27cb316 1016
b9b2e7bb
CS
1017 if ($old) {
1018 $config->id = $old->id;
1019 $return = $DB->update_record('lti_types_config', $config);
1020 } else {
1021 $return = $DB->insert_record('lti_types_config', $config);
1022 }
1023 return $return;
1024}
1025
1026/**
1027 * Signs the petition to launch the external tool using OAuth
1028 *
1029 * @param $oldparms Parameters to be passed for signing
1030 * @param $endpoint url of the external tool
1031 * @param $method Method for sending the parameters (e.g. POST)
1032 * @param $oauth_consumoer_key Key
1033 * @param $oauth_consumoer_secret Secret
1034 * @param $submittext The text for the submit button
1035 * @param $orgid LMS name
1036 * @param $orgdesc LMS key
1037 */
3dd9ca24
CS
1038function lti_sign_parameters($oldparms, $endpoint, $method, $oauthconsumerkey, $oauthconsumersecret) {
1039 //global $lastbasestring;
b9b2e7bb 1040 $parms = $oldparms;
b9b2e7bb
CS
1041
1042 $testtoken = '';
e27cb316 1043
fabd4fcf 1044 // TODO: Switch to core oauthlib once implemented - MDL-30149
795dff01
CS
1045 $hmacmethod = new lti\OAuthSignatureMethod_HMAC_SHA1();
1046 $testconsumer = new lti\OAuthConsumer($oauthconsumerkey, $oauthconsumersecret, null);
795dff01 1047 $accreq = lti\OAuthRequest::from_consumer_and_token($testconsumer, $testtoken, $method, $endpoint, $parms);
b9b2e7bb
CS
1048 $accreq->sign_request($hmacmethod, $testconsumer, $testtoken);
1049
1050 // Pass this back up "out of band" for debugging
3dd9ca24 1051 //$lastbasestring = $accreq->get_signature_base_string();
b9b2e7bb
CS
1052
1053 $newparms = $accreq->get_parameters();
1054
1055 return $newparms;
1056}
1057
1058/**
1059 * Posts the launch petition HTML
1060 *
1061 * @param $newparms Signed parameters
1062 * @param $endpoint URL of the external tool
1063 * @param $debug Debug (true/false)
1064 */
dbb0fec9 1065function lti_post_launch_html($newparms, $endpoint, $debug=false) {
3dd9ca24 1066 //global $lastbasestring;
e27cb316 1067
b9b2e7bb 1068 $r = "<form action=\"".$endpoint."\" name=\"ltiLaunchForm\" id=\"ltiLaunchForm\" method=\"post\" encType=\"application/x-www-form-urlencoded\">\n";
e27cb316 1069
b9b2e7bb
CS
1070 $submittext = $newparms['ext_submit'];
1071
1072 // Contruct html for the launch parameters
1073 foreach ($newparms as $key => $value) {
1074 $key = htmlspecialchars($key);
1075 $value = htmlspecialchars($value);
1076 if ( $key == "ext_submit" ) {
1077 $r .= "<input type=\"submit\" name=\"";
1078 } else {
1079 $r .= "<input type=\"hidden\" name=\"";
1080 }
1081 $r .= $key;
1082 $r .= "\" value=\"";
1083 $r .= $value;
1084 $r .= "\"/>\n";
1085 }
1086
1087 if ( $debug ) {
1088 $r .= "<script language=\"javascript\"> \n";
1089 $r .= " //<![CDATA[ \n";
1090 $r .= "function basicltiDebugToggle() {\n";
1091 $r .= " var ele = document.getElementById(\"basicltiDebug\");\n";
ea04a9f9 1092 $r .= " if (ele.style.display == \"block\") {\n";
b9b2e7bb
CS
1093 $r .= " ele.style.display = \"none\";\n";
1094 $r .= " }\n";
1095 $r .= " else {\n";
1096 $r .= " ele.style.display = \"block\";\n";
1097 $r .= " }\n";
1098 $r .= "} \n";
1099 $r .= " //]]> \n";
1100 $r .= "</script>\n";
1101 $r .= "<a id=\"displayText\" href=\"javascript:basicltiDebugToggle();\">";
1102 $r .= get_string("toggle_debug_data", "lti")."</a>\n";
1103 $r .= "<div id=\"basicltiDebug\" style=\"display:none\">\n";
1104 $r .= "<b>".get_string("basiclti_endpoint", "lti")."</b><br/>\n";
1105 $r .= $endpoint . "<br/>\n&nbsp;<br/>\n";
1106 $r .= "<b>".get_string("basiclti_parameters", "lti")."</b><br/>\n";
1107 foreach ($newparms as $key => $value) {
1108 $key = htmlspecialchars($key);
1109 $value = htmlspecialchars($value);
1110 $r .= "$key = $value<br/>\n";
1111 }
1112 $r .= "&nbsp;<br/>\n";
3dd9ca24 1113 //$r .= "<p><b>".get_string("basiclti_base_string", "lti")."</b><br/>\n".$lastbasestring."</p>\n";
b9b2e7bb
CS
1114 $r .= "</div>\n";
1115 }
1116 $r .= "</form>\n";
1117
1118 if ( ! $debug ) {
1119 $ext_submit = "ext_submit";
1120 $ext_submit_text = $submittext;
1121 $r .= " <script type=\"text/javascript\"> \n" .
1122 " //<![CDATA[ \n" .
1123 " document.getElementById(\"ltiLaunchForm\").style.display = \"none\";\n" .
1124 " nei = document.createElement('input');\n" .
1125 " nei.setAttribute('type', 'hidden');\n" .
1126 " nei.setAttribute('name', '".$ext_submit."');\n" .
1127 " nei.setAttribute('value', '".$ext_submit_text."');\n" .
1128 " document.getElementById(\"ltiLaunchForm\").appendChild(nei);\n" .
1129 " document.ltiLaunchForm.submit(); \n" .
1130 " //]]> \n" .
1131 " </script> \n";
1132 }
1133 return $r;
1134}
1135
ea04a9f9 1136function lti_get_type($typeid) {
996b0fd9 1137 global $DB;
e27cb316 1138
996b0fd9 1139 return $DB->get_record('lti_types', array('id' => $typeid));
57d1dffd
CS
1140}
1141
ea04a9f9
EL
1142function lti_get_launch_container($lti, $toolconfig) {
1143 if (empty($lti->launchcontainer)) {
e27cb316
CS
1144 $lti->launchcontainer = LTI_LAUNCH_CONTAINER_DEFAULT;
1145 }
1146
ea04a9f9
EL
1147 if ($lti->launchcontainer == LTI_LAUNCH_CONTAINER_DEFAULT) {
1148 if (isset($toolconfig['launchcontainer'])) {
c4d80efe
CS
1149 $launchcontainer = $toolconfig['launchcontainer'];
1150 }
1151 } else {
1152 $launchcontainer = $lti->launchcontainer;
1153 }
e27cb316 1154
ea04a9f9 1155 if (empty($launchcontainer) || $launchcontainer == LTI_LAUNCH_CONTAINER_DEFAULT) {
c4d80efe
CS
1156 $launchcontainer = LTI_LAUNCH_CONTAINER_EMBED_NO_BLOCKS;
1157 }
57d1dffd
CS
1158
1159 $devicetype = get_device_type();
1160
1161 //Scrolling within the object element doesn't work on iOS or Android
1162 //Opening the popup window also had some issues in testing
1163 //For mobile devices, always take up the entire screen to ensure the best experience
ea04a9f9 1164 if ($devicetype === 'mobile' || $devicetype === 'tablet' ) {
57d1dffd
CS
1165 $launchcontainer = LTI_LAUNCH_CONTAINER_REPLACE_MOODLE_WINDOW;
1166 }
e27cb316 1167
57d1dffd 1168 return $launchcontainer;
d8d04121
CS
1169}
1170
1171function lti_request_is_using_ssl() {
1172 global $ME;
1173 return (stripos($ME, 'https://') === 0);
1174}
1175
ea04a9f9
EL
1176function lti_ensure_url_is_https($url) {
1177 if (!strstr($url, '://')) {
d8d04121
CS
1178 $url = 'https://' . $url;
1179 } else {
1180 //If the URL starts with http, replace with https
ea04a9f9 1181 if (stripos($url, 'http://') === 0) {
d8d04121
CS
1182 $url = 'https://' . substr($url, 8);
1183 }
1184 }
e27cb316 1185
d8d04121 1186 return $url;
61eb12d4 1187}