MDL-20534 lti: various fixes to add/update_instance()
[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 ) ) ) {
b9b2e7bb 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
d8d04121 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 ) ) {
b9b2e7bb
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;
279 }
280
5e078d62
CS
281 if ( $typeconfig['sendemailaddr'] == LTI_SETTING_ALWAYS ||
282 ( $typeconfig['sendemailaddr'] == LTI_SETTING_DELEGATE && $instance->instructorchoicesendemailaddr == LTI_SETTING_ALWAYS ) ) {
b9b2e7bb
CS
283 $requestparams["lis_person_contact_email_primary"] = $USER->email;
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
CS
315 // Make sure we let the tool know what LMS they are being called from
316 $requestparams["ext_lms"] = "moodle-2";
317
318 // Add oauth_callback to be compliant with the 1.0A spec
319 $requestparams["oauth_callback"] = "about:blank";
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
CS
323 $submittext = get_string('press_to_submit', 'lti');
324 $requestparams["ext_submit"] = $submittext;
e27cb316 325
3dd9ca24
CS
326 $requestparams["lti_version"] = "LTI-1p0";
327 $requestparams["lti_message_type"] = "basic-lti-launch-request";
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
5de15b83 511 $query = '
f17f4959
CS
512 SELECT name, value
513 FROM {lti_types_config}
514 WHERE typeid = :typeid1
e27cb316 515
f17f4959 516 UNION ALL
e27cb316 517
5de15b83 518 SELECT \'toolurl\' AS name, baseurl AS value
f17f4959
CS
519 FROM {lti_types}
520 WHERE id = :typeid2
5de15b83 521 ';
e27cb316 522
b9b2e7bb 523 $typeconfig = array();
f17f4959 524 $configs = $DB->get_records_sql($query, array('typeid1' => $typeid, 'typeid2' => $typeid));
e27cb316 525
b9b2e7bb
CS
526 if (!empty($configs)) {
527 foreach ($configs as $config) {
528 $typeconfig[$config->name] = $config->value;
529 }
530 }
e27cb316 531
b9b2e7bb
CS
532 return $typeconfig;
533}
534
ea04a9f9 535function lti_get_tools_by_url($url, $state, $courseid = null) {
b9b2e7bb 536 $domain = lti_get_domain_from_url($url);
e27cb316 537
996b0fd9 538 return lti_get_tools_by_domain($domain, $state, $courseid);
b9b2e7bb
CS
539}
540
ea04a9f9 541function lti_get_tools_by_domain($domain, $state = null, $courseid = null) {
b9b2e7bb 542 global $DB, $SITE;
e27cb316 543
b9b2e7bb 544 $filters = array('tooldomain' => $domain);
e27cb316 545
b9b2e7bb
CS
546 $statefilter = '';
547 $coursefilter = '';
e27cb316 548
ea04a9f9 549 if ($state) {
b9b2e7bb
CS
550 $statefilter = 'AND state = :state';
551 }
e27cb316 552
ea04a9f9 553 if ($courseid && $courseid != $SITE->id) {
b9b2e7bb
CS
554 $coursefilter = 'OR course = :courseid';
555 }
e27cb316 556
5de15b83 557 $query = '
b9b2e7bb
CS
558 SELECT * FROM {lti_types}
559 WHERE
560 tooldomain = :tooldomain
561 AND (course = :siteid $coursefilter)
562 $statefilter
5de15b83 563 ';
e27cb316 564
b9b2e7bb 565 return $DB->get_records_sql($query, array(
e27cb316
CS
566 'courseid' => $courseid,
567 'siteid' => $SITE->id,
568 'tooldomain' => $domain,
b9b2e7bb
CS
569 'state' => $state
570 ));
571}
572
573/**
574 * Returns all basicLTI tools configured by the administrator
575 *
576 */
6831c7cd 577function lti_filter_get_types($course) {
b9b2e7bb
CS
578 global $DB;
579
ea04a9f9 580 if (!empty($course)) {
6831c7cd
CS
581 $filter = array('course' => $course);
582 } else {
583 $filter = array();
584 }
e27cb316 585
6831c7cd 586 return $DB->get_records('lti_types', $filter);
b9b2e7bb
CS
587}
588
ea04a9f9 589function lti_get_types_for_add_instance() {
996b0fd9 590 global $DB, $SITE, $COURSE;
e27cb316 591
5de15b83 592 $query = '
996b0fd9
CS
593 SELECT *
594 FROM {lti_types}
595 WHERE
596 coursevisible = 1
597 AND (course = :siteid OR course = :courseid)
606ab1a1 598 AND state = :active
5de15b83 599 ';
e27cb316 600
606ab1a1 601 $admintypes = $DB->get_records_sql($query, array('siteid' => $SITE->id, 'courseid' => $COURSE->id, 'active' => LTI_TOOL_STATE_CONFIGURED));
e27cb316 602
b9b2e7bb 603 $types = array();
996b0fd9 604 $types[0] = (object)array('name' => get_string('automatic', 'lti'), 'course' => $SITE->id);
e27cb316 605
ea04a9f9 606 foreach ($admintypes as $type) {
16e8f130 607 $types[$type->id] = $type;
b9b2e7bb 608 }
e27cb316 609
b9b2e7bb
CS
610 return $types;
611}
612
ea04a9f9 613function lti_get_domain_from_url($url) {
b9b2e7bb 614 $matches = array();
e27cb316 615
ea04a9f9 616 if (preg_match(LTI_URL_DOMAIN_REGEX, $url, $matches)) {
b9b2e7bb
CS
617 return $matches[1];
618 }
619}
620
ea04a9f9 621function lti_get_tool_by_url_match($url, $courseid = null, $state = LTI_TOOL_STATE_CONFIGURED) {
b69dc429 622 $possibletools = lti_get_tools_by_url($url, $state, $courseid);
e27cb316 623
7023b65e 624 return lti_get_best_tool_by_url($url, $possibletools, $courseid);
b9b2e7bb
CS
625}
626
ea04a9f9 627function lti_get_url_thumbprint($url) {
b9b2e7bb 628 $urlparts = parse_url(strtolower($url));
ea04a9f9 629 if (!isset($urlparts['path'])) {
b9b2e7bb
CS
630 $urlparts['path'] = '';
631 }
e27cb316 632
ea04a9f9 633 if (!isset($urlparts['host'])) {
d8d04121
CS
634 $urlparts['host'] = '';
635 }
e27cb316 636
ea04a9f9 637 if (substr($urlparts['host'], 0, 4) === 'www.') {
d8d04121 638 $urlparts['host'] = substr($urlparts['host'], 4);
b9b2e7bb 639 }
e27cb316 640
b9b2e7bb
CS
641 return $urllower = $urlparts['host'] . '/' . $urlparts['path'];
642}
643
ea04a9f9
EL
644function lti_get_best_tool_by_url($url, $tools, $courseid = null) {
645 if (count($tools) === 0) {
b9b2e7bb
CS
646 return null;
647 }
e27cb316 648
b9b2e7bb 649 $urllower = lti_get_url_thumbprint($url);
e27cb316 650
ea04a9f9 651 foreach ($tools as $tool) {
b9b2e7bb 652 $tool->_matchscore = 0;
e27cb316 653
b9b2e7bb 654 $toolbaseurllower = lti_get_url_thumbprint($tool->baseurl);
e27cb316 655
ea04a9f9 656 if ($urllower === $toolbaseurllower) {
7023b65e 657 //100 points for exact thumbprint match
b9b2e7bb 658 $tool->_matchscore += 100;
ea04a9f9 659 } else if (substr($urllower, 0, strlen($toolbaseurllower)) === $toolbaseurllower) {
7023b65e 660 //50 points if tool thumbprint starts with the base URL thumbprint
b9b2e7bb
CS
661 $tool->_matchscore += 50;
662 }
e27cb316 663
7023b65e 664 //Prefer course tools over site tools
ea04a9f9 665 if (!empty($courseid)) {
7023b65e 666 //Minus 25 points for not matching the course id (global tools)
ea04a9f9 667 if ($tool->course != $courseid) {
7023b65e
CS
668 $tool->_matchscore -= 10;
669 }
670 }
b9b2e7bb 671 }
e27cb316 672
ea04a9f9
EL
673 $bestmatch = array_reduce($tools, function($value, $tool) {
674 if ($tool->_matchscore > $value->_matchscore) {
b9b2e7bb
CS
675 return $tool;
676 } else {
677 return $value;
678 }
e27cb316 679
b9b2e7bb 680 }, (object)array('_matchscore' => -1));
e27cb316 681
b9b2e7bb 682 //None of the tools are suitable for this URL
ea04a9f9 683 if ($bestmatch->_matchscore <= 0) {
b9b2e7bb
CS
684 return null;
685 }
e27cb316 686
b9b2e7bb
CS
687 return $bestmatch;
688}
689
ea04a9f9 690function lti_get_shared_secrets_by_key($key) {
020eea1b 691 global $DB;
e27cb316 692
020eea1b
CS
693 //Look up the shared secret for the specified key in both the types_config table (for configured tools)
694 //And in the lti resource table for ad-hoc tools
5de15b83 695 $query = '
020eea1b
CS
696 SELECT t2.value
697 FROM {lti_types_config} t1
698 INNER JOIN {lti_types_config} t2 ON t1.typeid = t2.typeid
feb30fd8 699 INNER JOIN {lti_types} type ON t2.typeid = type.id
e27cb316 700 WHERE
5de15b83 701 t1.name = \'resourcekey\'
020eea1b 702 AND t1.value = :key1
5de15b83 703 AND t2.name = \'password\'
feb30fd8
CS
704 AND type.state = :configured
705
020eea1b 706 UNION
e27cb316 707
3dd9ca24 708 SELECT password AS value
020eea1b
CS
709 FROM {lti}
710 WHERE resourcekey = :key2
5de15b83 711 ';
e27cb316 712
feb30fd8 713 $sharedsecrets = $DB->get_records_sql($query, array('configured' => LTI_TOOL_STATE_CONFIGURED, 'key1' => $key, 'key2' => $key));
e27cb316 714
ea04a9f9 715 $values = array_map(function($item) {
020eea1b
CS
716 return $item->value;
717 }, $sharedsecrets);
e27cb316 718
020eea1b
CS
719 //There should really only be one shared secret per key. But, we can't prevent
720 //more than one getting entered. For instance, if the same key is used for two tool providers.
721 return $values;
722}
723
b9b2e7bb
CS
724/**
725 * Prints the various configured tool types
726 *
727 */
728function lti_filter_print_types() {
729 global $CFG;
730
731 $types = lti_filter_get_types();
732 if (!empty($types)) {
733 echo '<ul>';
734 foreach ($types as $type) {
735 echo '<li>'.
736 $type->name.
737 '<span class="commands">'.
738 '<a class="editing_update" href="typessettings.php?action=update&amp;id='.$type->id.'&amp;sesskey='.sesskey().'" title="Update">'.
739 '<img class="iconsmall" alt="Update" src="'.$CFG->wwwroot.'/pix/t/edit.gif"/>'.
740 '</a>'.
741 '<a class="editing_delete" href="typessettings.php?action=delete&amp;id='.$type->id.'&amp;sesskey='.sesskey().'" title="Delete">'.
742 '<img class="iconsmall" alt="Delete" src="'.$CFG->wwwroot.'/pix/t/delete.gif"/>'.
743 '</a>'.
744 '</span>'.
745 '</li>';
746
747 }
748 echo '</ul>';
749 } else {
750 echo '<div class="message">';
751 echo get_string('notypes', 'lti');
752 echo '</div>';
753 }
754}
755
756/**
757 * Delete a Basic LTI configuration
758 *
759 * @param int $id Configuration id
760 */
761function lti_delete_type($id) {
762 global $DB;
763
764 //We should probably just copy the launch URL to the tool instances in this case... using a single query
765 /*
766 $instances = $DB->get_records('lti', array('typeid' => $id));
767 foreach ($instances as $instance) {
768 $instance->typeid = 0;
769 $DB->update_record('lti', $instance);
770 }*/
771
772 $DB->delete_records('lti_types', array('id' => $id));
773 $DB->delete_records('lti_types_config', array('typeid' => $id));
774}
775
ea04a9f9 776function lti_set_state_for_type($id, $state) {
b9b2e7bb 777 global $DB;
e27cb316 778
b9b2e7bb
CS
779 $DB->update_record('lti_types', array('id' => $id, 'state' => $state));
780}
781
782/**
783 * Transforms a basic LTI object to an array
784 *
785 * @param object $ltiobject Basic LTI object
786 *
787 * @return array Basic LTI configuration details
788 */
789function lti_get_config($ltiobject) {
790 $typeconfig = array();
791 $typeconfig = (array)$ltiobject;
792 $additionalconfig = lti_get_type_config($ltiobject->typeid);
793 $typeconfig = array_merge($typeconfig, $additionalconfig);
794 return $typeconfig;
795}
796
797/**
798 *
799 * Generates some of the tool configuration based on the instance details
800 *
801 * @param int $id
802 *
803 * @return Instance configuration
804 *
805 */
806function lti_get_type_config_from_instance($id) {
807 global $DB;
808
809 $instance = $DB->get_record('lti', array('id' => $id));
810 $config = lti_get_config($instance);
811
812 $type = new stdClass();
813 $type->lti_fix = $id;
814 if (isset($config['toolurl'])) {
815 $type->lti_toolurl = $config['toolurl'];
816 }
817 if (isset($config['instructorchoicesendname'])) {
818 $type->lti_sendname = $config['instructorchoicesendname'];
819 }
820 if (isset($config['instructorchoicesendemailaddr'])) {
821 $type->lti_sendemailaddr = $config['instructorchoicesendemailaddr'];
822 }
823 if (isset($config['instructorchoiceacceptgrades'])) {
824 $type->lti_acceptgrades = $config['instructorchoiceacceptgrades'];
825 }
826 if (isset($config['instructorchoiceallowroster'])) {
827 $type->lti_allowroster = $config['instructorchoiceallowroster'];
828 }
829
830 if (isset($config['instructorcustomparameters'])) {
831 $type->lti_allowsetting = $config['instructorcustomparameters'];
832 }
833 return $type;
834}
835
836/**
837 * Generates some of the tool configuration based on the admin configuration details
838 *
839 * @param int $id
840 *
841 * @return Configuration details
842 */
843function lti_get_type_type_config($id) {
844 global $DB;
845
846 $basicltitype = $DB->get_record('lti_types', array('id' => $id));
847 $config = lti_get_type_config($id);
848
849 $type->lti_typename = $basicltitype->name;
e27cb316 850
6831c7cd 851 $type->typeid = $basicltitype->id;
e27cb316 852
b9b2e7bb 853 $type->lti_toolurl = $basicltitype->baseurl;
e27cb316 854
b9b2e7bb
CS
855 if (isset($config['resourcekey'])) {
856 $type->lti_resourcekey = $config['resourcekey'];
857 }
858 if (isset($config['password'])) {
859 $type->lti_password = $config['password'];
860 }
861
862 if (isset($config['sendname'])) {
863 $type->lti_sendname = $config['sendname'];
864 }
ea04a9f9 865 if (isset($config['instructorchoicesendname'])) {
b9b2e7bb
CS
866 $type->lti_instructorchoicesendname = $config['instructorchoicesendname'];
867 }
ea04a9f9 868 if (isset($config['sendemailaddr'])) {
b9b2e7bb
CS
869 $type->lti_sendemailaddr = $config['sendemailaddr'];
870 }
ea04a9f9 871 if (isset($config['instructorchoicesendemailaddr'])) {
b9b2e7bb
CS
872 $type->lti_instructorchoicesendemailaddr = $config['instructorchoicesendemailaddr'];
873 }
ea04a9f9 874 if (isset($config['acceptgrades'])) {
b9b2e7bb
CS
875 $type->lti_acceptgrades = $config['acceptgrades'];
876 }
ea04a9f9 877 if (isset($config['instructorchoiceacceptgrades'])) {
b9b2e7bb
CS
878 $type->lti_instructorchoiceacceptgrades = $config['instructorchoiceacceptgrades'];
879 }
ea04a9f9 880 if (isset($config['allowroster'])) {
b9b2e7bb
CS
881 $type->lti_allowroster = $config['allowroster'];
882 }
ea04a9f9 883 if (isset($config['instructorchoiceallowroster'])) {
b9b2e7bb
CS
884 $type->lti_instructorchoiceallowroster = $config['instructorchoiceallowroster'];
885 }
886
887 if (isset($config['customparameters'])) {
888 $type->lti_customparameters = $config['customparameters'];
889 }
890
ea04a9f9 891 if (isset($config['forcessl'])) {
d8d04121
CS
892 $type->lti_forcessl = $config['forcessl'];
893 }
e27cb316 894
b9b2e7bb
CS
895 if (isset($config['organizationid'])) {
896 $type->lti_organizationid = $config['organizationid'];
897 }
898 if (isset($config['organizationurl'])) {
899 $type->lti_organizationurl = $config['organizationurl'];
900 }
901 if (isset($config['organizationdescr'])) {
902 $type->lti_organizationdescr = $config['organizationdescr'];
903 }
904 if (isset($config['launchcontainer'])) {
905 $type->lti_launchcontainer = $config['launchcontainer'];
906 }
e27cb316 907
b9b2e7bb
CS
908 if (isset($config['coursevisible'])) {
909 $type->lti_coursevisible = $config['coursevisible'];
910 }
e27cb316 911
b9b2e7bb
CS
912 if (isset($config['debuglaunch'])) {
913 $type->lti_debuglaunch = $config['debuglaunch'];
914 }
e27cb316 915
b9b2e7bb
CS
916 if (isset($config['module_class_type'])) {
917 $type->lti_module_class_type = $config['module_class_type'];
918 }
919
920 return $type;
921}
922
ea04a9f9 923function lti_prepare_type_for_save($type, $config) {
b9b2e7bb
CS
924 $type->baseurl = $config->lti_toolurl;
925 $type->tooldomain = lti_get_domain_from_url($config->lti_toolurl);
926 $type->name = $config->lti_typename;
e27cb316 927
b9b2e7bb
CS
928 $type->coursevisible = !empty($config->lti_coursevisible) ? $config->lti_coursevisible : 0;
929 $config->lti_coursevisible = $type->coursevisible;
e27cb316 930
d8d04121
CS
931 $type->forcessl = !empty($config->lti_forcessl) ? $config->lti_forcessl : 0;
932 $config->lti_forcessl = $type->forcessl;
e27cb316 933
b9b2e7bb 934 $type->timemodified = time();
e27cb316 935
b9b2e7bb
CS
936 unset ($config->lti_typename);
937 unset ($config->lti_toolurl);
938}
939
ea04a9f9 940function lti_update_type($type, $config) {
b9b2e7bb 941 global $DB;
e27cb316 942
b9b2e7bb 943 lti_prepare_type_for_save($type, $config);
e27cb316 944
b9b2e7bb
CS
945 if ($DB->update_record('lti_types', $type)) {
946 foreach ($config as $key => $value) {
947 if (substr($key, 0, 4)=='lti_' && !is_null($value)) {
948 $record = new StdClass();
949 $record->typeid = $type->id;
950 $record->name = substr($key, 4);
951 $record->value = $value;
e27cb316 952
b9b2e7bb
CS
953 lti_update_config($record);
954 }
955 }
956 }
957}
958
ea04a9f9 959function lti_add_type($type, $config) {
b9b2e7bb 960 global $USER, $SITE, $DB;
e27cb316 961
b9b2e7bb 962 lti_prepare_type_for_save($type, $config);
e27cb316 963
ea04a9f9 964 if (!isset($type->state)) {
b9b2e7bb
CS
965 $type->state = LTI_TOOL_STATE_PENDING;
966 }
e27cb316 967
ea04a9f9 968 if (!isset($type->timecreated)) {
b9b2e7bb
CS
969 $type->timecreated = time();
970 }
e27cb316 971
ea04a9f9 972 if (!isset($type->createdby)) {
b9b2e7bb
CS
973 $type->createdby = $USER->id;
974 }
e27cb316 975
ea04a9f9 976 if (!isset($type->course)) {
b9b2e7bb
CS
977 $type->course = $SITE->id;
978 }
e27cb316 979
b9b2e7bb 980 //Create a salt value to be used for signing passed data to extension services
6831c7cd
CS
981 //The outcome service uses the service salt on the instance. This can be used
982 //for communication with services not related to a specific LTI instance.
b9b2e7bb
CS
983 $config->lti_servicesalt = uniqid('', true);
984
985 $id = $DB->insert_record('lti_types', $type);
986
987 if ($id) {
988 foreach ($config as $key => $value) {
989 if (substr($key, 0, 4)=='lti_' && !is_null($value)) {
990 $record = new StdClass();
991 $record->typeid = $id;
992 $record->name = substr($key, 4);
993 $record->value = $value;
994
995 lti_add_config($record);
996 }
997 }
998 }
e27cb316 999
996b0fd9 1000 return $id;
b9b2e7bb
CS
1001}
1002
1003/**
1004 * Add a tool configuration in the database
1005 *
1006 * @param $config Tool configuration
1007 *
1008 * @return int Record id number
1009 */
1010function lti_add_config($config) {
1011 global $DB;
1012
1013 return $DB->insert_record('lti_types_config', $config);
1014}
1015
1016/**
1017 * Updates a tool configuration in the database
1018 *
1019 * @param $config Tool configuration
1020 *
1021 * @return Record id number
1022 */
1023function lti_update_config($config) {
1024 global $DB;
1025
1026 $return = true;
1027 $old = $DB->get_record('lti_types_config', array('typeid' => $config->typeid, 'name' => $config->name));
e27cb316 1028
b9b2e7bb
CS
1029 if ($old) {
1030 $config->id = $old->id;
1031 $return = $DB->update_record('lti_types_config', $config);
1032 } else {
1033 $return = $DB->insert_record('lti_types_config', $config);
1034 }
1035 return $return;
1036}
1037
1038/**
1039 * Signs the petition to launch the external tool using OAuth
1040 *
1041 * @param $oldparms Parameters to be passed for signing
1042 * @param $endpoint url of the external tool
1043 * @param $method Method for sending the parameters (e.g. POST)
1044 * @param $oauth_consumoer_key Key
1045 * @param $oauth_consumoer_secret Secret
1046 * @param $submittext The text for the submit button
1047 * @param $orgid LMS name
1048 * @param $orgdesc LMS key
1049 */
3dd9ca24
CS
1050function lti_sign_parameters($oldparms, $endpoint, $method, $oauthconsumerkey, $oauthconsumersecret) {
1051 //global $lastbasestring;
b9b2e7bb 1052 $parms = $oldparms;
b9b2e7bb
CS
1053
1054 $testtoken = '';
e27cb316 1055
fabd4fcf 1056 // TODO: Switch to core oauthlib once implemented - MDL-30149
795dff01
CS
1057 $hmacmethod = new lti\OAuthSignatureMethod_HMAC_SHA1();
1058 $testconsumer = new lti\OAuthConsumer($oauthconsumerkey, $oauthconsumersecret, null);
795dff01 1059 $accreq = lti\OAuthRequest::from_consumer_and_token($testconsumer, $testtoken, $method, $endpoint, $parms);
b9b2e7bb
CS
1060 $accreq->sign_request($hmacmethod, $testconsumer, $testtoken);
1061
1062 // Pass this back up "out of band" for debugging
3dd9ca24 1063 //$lastbasestring = $accreq->get_signature_base_string();
b9b2e7bb
CS
1064
1065 $newparms = $accreq->get_parameters();
1066
1067 return $newparms;
1068}
1069
1070/**
1071 * Posts the launch petition HTML
1072 *
1073 * @param $newparms Signed parameters
1074 * @param $endpoint URL of the external tool
1075 * @param $debug Debug (true/false)
1076 */
dbb0fec9 1077function lti_post_launch_html($newparms, $endpoint, $debug=false) {
3dd9ca24 1078 //global $lastbasestring;
e27cb316 1079
b9b2e7bb 1080 $r = "<form action=\"".$endpoint."\" name=\"ltiLaunchForm\" id=\"ltiLaunchForm\" method=\"post\" encType=\"application/x-www-form-urlencoded\">\n";
e27cb316 1081
b9b2e7bb
CS
1082 $submittext = $newparms['ext_submit'];
1083
1084 // Contruct html for the launch parameters
1085 foreach ($newparms as $key => $value) {
1086 $key = htmlspecialchars($key);
1087 $value = htmlspecialchars($value);
1088 if ( $key == "ext_submit" ) {
1089 $r .= "<input type=\"submit\" name=\"";
1090 } else {
1091 $r .= "<input type=\"hidden\" name=\"";
1092 }
1093 $r .= $key;
1094 $r .= "\" value=\"";
1095 $r .= $value;
1096 $r .= "\"/>\n";
1097 }
1098
1099 if ( $debug ) {
1100 $r .= "<script language=\"javascript\"> \n";
1101 $r .= " //<![CDATA[ \n";
1102 $r .= "function basicltiDebugToggle() {\n";
1103 $r .= " var ele = document.getElementById(\"basicltiDebug\");\n";
ea04a9f9 1104 $r .= " if (ele.style.display == \"block\") {\n";
b9b2e7bb
CS
1105 $r .= " ele.style.display = \"none\";\n";
1106 $r .= " }\n";
1107 $r .= " else {\n";
1108 $r .= " ele.style.display = \"block\";\n";
1109 $r .= " }\n";
1110 $r .= "} \n";
1111 $r .= " //]]> \n";
1112 $r .= "</script>\n";
1113 $r .= "<a id=\"displayText\" href=\"javascript:basicltiDebugToggle();\">";
1114 $r .= get_string("toggle_debug_data", "lti")."</a>\n";
1115 $r .= "<div id=\"basicltiDebug\" style=\"display:none\">\n";
1116 $r .= "<b>".get_string("basiclti_endpoint", "lti")."</b><br/>\n";
1117 $r .= $endpoint . "<br/>\n&nbsp;<br/>\n";
1118 $r .= "<b>".get_string("basiclti_parameters", "lti")."</b><br/>\n";
1119 foreach ($newparms as $key => $value) {
1120 $key = htmlspecialchars($key);
1121 $value = htmlspecialchars($value);
1122 $r .= "$key = $value<br/>\n";
1123 }
1124 $r .= "&nbsp;<br/>\n";
3dd9ca24 1125 //$r .= "<p><b>".get_string("basiclti_base_string", "lti")."</b><br/>\n".$lastbasestring."</p>\n";
b9b2e7bb
CS
1126 $r .= "</div>\n";
1127 }
1128 $r .= "</form>\n";
1129
1130 if ( ! $debug ) {
1131 $ext_submit = "ext_submit";
1132 $ext_submit_text = $submittext;
1133 $r .= " <script type=\"text/javascript\"> \n" .
1134 " //<![CDATA[ \n" .
1135 " document.getElementById(\"ltiLaunchForm\").style.display = \"none\";\n" .
1136 " nei = document.createElement('input');\n" .
1137 " nei.setAttribute('type', 'hidden');\n" .
1138 " nei.setAttribute('name', '".$ext_submit."');\n" .
1139 " nei.setAttribute('value', '".$ext_submit_text."');\n" .
1140 " document.getElementById(\"ltiLaunchForm\").appendChild(nei);\n" .
1141 " document.ltiLaunchForm.submit(); \n" .
1142 " //]]> \n" .
1143 " </script> \n";
1144 }
1145 return $r;
1146}
1147
ea04a9f9 1148function lti_get_type($typeid) {
996b0fd9 1149 global $DB;
e27cb316 1150
996b0fd9 1151 return $DB->get_record('lti_types', array('id' => $typeid));
57d1dffd
CS
1152}
1153
ea04a9f9
EL
1154function lti_get_launch_container($lti, $toolconfig) {
1155 if (empty($lti->launchcontainer)) {
e27cb316
CS
1156 $lti->launchcontainer = LTI_LAUNCH_CONTAINER_DEFAULT;
1157 }
1158
ea04a9f9
EL
1159 if ($lti->launchcontainer == LTI_LAUNCH_CONTAINER_DEFAULT) {
1160 if (isset($toolconfig['launchcontainer'])) {
c4d80efe
CS
1161 $launchcontainer = $toolconfig['launchcontainer'];
1162 }
1163 } else {
1164 $launchcontainer = $lti->launchcontainer;
1165 }
e27cb316 1166
ea04a9f9 1167 if (empty($launchcontainer) || $launchcontainer == LTI_LAUNCH_CONTAINER_DEFAULT) {
c4d80efe
CS
1168 $launchcontainer = LTI_LAUNCH_CONTAINER_EMBED_NO_BLOCKS;
1169 }
57d1dffd
CS
1170
1171 $devicetype = get_device_type();
1172
1173 //Scrolling within the object element doesn't work on iOS or Android
1174 //Opening the popup window also had some issues in testing
1175 //For mobile devices, always take up the entire screen to ensure the best experience
ea04a9f9 1176 if ($devicetype === 'mobile' || $devicetype === 'tablet' ) {
57d1dffd
CS
1177 $launchcontainer = LTI_LAUNCH_CONTAINER_REPLACE_MOODLE_WINDOW;
1178 }
e27cb316 1179
57d1dffd 1180 return $launchcontainer;
d8d04121
CS
1181}
1182
1183function lti_request_is_using_ssl() {
1184 global $ME;
1185 return (stripos($ME, 'https://') === 0);
1186}
1187
ea04a9f9
EL
1188function lti_ensure_url_is_https($url) {
1189 if (!strstr($url, '://')) {
d8d04121
CS
1190 $url = 'https://' . $url;
1191 } else {
1192 //If the URL starts with http, replace with https
ea04a9f9 1193 if (stripos($url, 'http://') === 0) {
d8d04121
CS
1194 $url = 'https://' . substr($url, 8);
1195 }
1196 }
e27cb316 1197
d8d04121 1198 return $url;
61eb12d4 1199}