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