MDL-49143 LTI: Fix missing resource id
[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
e3f69b58 33// Contact info: Marc Alier Forment granludo @ gmail.com or marc.alier @ upc.edu.
b9b2e7bb
CS
34
35/**
61eb12d4 36 * This file contains the library of functions and constants for the lti module
b9b2e7bb 37 *
2b17ec3d 38 * @package mod_lti
61eb12d4 39 * @copyright 2009 Marc Alier, Jordi Piguillem, Nikolas Galanis
b9b2e7bb 40 * marc.alier@upc.edu
61eb12d4
CS
41 * @copyright 2009 Universitat Politecnica de Catalunya http://www.upc.edu
42 * @author Marc Alier
43 * @author Jordi Piguillem
44 * @author Nikolas Galanis
8f45215d 45 * @author Chris Scribner
01f38dd0 46 * @copyright 2015 Vital Source Technologies http://vitalsource.com
47 * @author Stephen Vickers
61eb12d4 48 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
b9b2e7bb
CS
49 */
50
51defined('MOODLE_INTERNAL') || die;
52
e3f69b58 53// TODO: Switch to core oauthlib once implemented - MDL-30149.
795dff01
CS
54use moodle\mod\lti as lti;
55
b9b2e7bb
CS
56require_once($CFG->dirroot.'/mod/lti/OAuth.php');
57
58define('LTI_URL_DOMAIN_REGEX', '/(?:https?:\/\/)?(?:www\.)?([^\/]+)(?:\/|$)/i');
59
60define('LTI_LAUNCH_CONTAINER_DEFAULT', 1);
61define('LTI_LAUNCH_CONTAINER_EMBED', 2);
62define('LTI_LAUNCH_CONTAINER_EMBED_NO_BLOCKS', 3);
63define('LTI_LAUNCH_CONTAINER_WINDOW', 4);
cca9d3f7 64define('LTI_LAUNCH_CONTAINER_REPLACE_MOODLE_WINDOW', 5);
b9b2e7bb
CS
65
66define('LTI_TOOL_STATE_ANY', 0);
67define('LTI_TOOL_STATE_CONFIGURED', 1);
68define('LTI_TOOL_STATE_PENDING', 2);
69define('LTI_TOOL_STATE_REJECTED', 3);
e3f69b58 70define('LTI_TOOL_PROXY_TAB', 4);
71
72define('LTI_TOOL_PROXY_STATE_CONFIGURED', 1);
73define('LTI_TOOL_PROXY_STATE_PENDING', 2);
74define('LTI_TOOL_PROXY_STATE_ACCEPTED', 3);
75define('LTI_TOOL_PROXY_STATE_REJECTED', 4);
b9b2e7bb
CS
76
77define('LTI_SETTING_NEVER', 0);
78define('LTI_SETTING_ALWAYS', 1);
5e078d62 79define('LTI_SETTING_DELEGATE', 2);
b9b2e7bb
CS
80
81/**
82 * Prints a Basic LTI activity
83 *
84 * $param int $basicltiid Basic LTI activity id
85 */
67ddf847 86function lti_view($instance) {
b9b2e7bb
CS
87 global $PAGE, $CFG;
88
ea04a9f9 89 if (empty($instance->typeid)) {
606ab1a1 90 $tool = lti_get_tool_by_url_match($instance->toolurl, $instance->course);
ea04a9f9 91 if ($tool) {
b9b2e7bb
CS
92 $typeid = $tool->id;
93 } else {
94 $typeid = null;
95 }
96 } else {
97 $typeid = $instance->typeid;
e3f69b58 98 $tool = lti_get_type($typeid);
b9b2e7bb 99 }
e27cb316 100
ea04a9f9 101 if ($typeid) {
b9b2e7bb
CS
102 $typeconfig = lti_get_type_config($typeid);
103 } else {
e3f69b58 104 // There is no admin configuration for this tool. Use configuration in the lti instance record plus some defaults.
b9b2e7bb 105 $typeconfig = (array)$instance;
e27cb316 106
b9b2e7bb
CS
107 $typeconfig['sendname'] = $instance->instructorchoicesendname;
108 $typeconfig['sendemailaddr'] = $instance->instructorchoicesendemailaddr;
109 $typeconfig['customparameters'] = $instance->instructorcustomparameters;
f4f711d7
CS
110 $typeconfig['acceptgrades'] = $instance->instructorchoiceacceptgrades;
111 $typeconfig['allowroster'] = $instance->instructorchoiceallowroster;
d8d04121 112 $typeconfig['forcessl'] = '0';
b9b2e7bb 113 }
e27cb316 114
e3f69b58 115 // Default the organizationid if not specified.
ea04a9f9 116 if (empty($typeconfig['organizationid'])) {
b9b2e7bb 117 $urlparts = parse_url($CFG->wwwroot);
e27cb316 118
b9b2e7bb
CS
119 $typeconfig['organizationid'] = $urlparts['host'];
120 }
e27cb316 121
e3f69b58 122 if (isset($tool->toolproxyid)) {
123 $toolproxy = lti_get_tool_proxy($tool->toolproxyid);
124 $key = $toolproxy->guid;
125 $secret = $toolproxy->secret;
3dd9ca24 126 } else {
e3f69b58 127 $toolproxy = null;
128 if (!empty($instance->resourcekey)) {
129 $key = $instance->resourcekey;
130 } else if (!empty($typeconfig['resourcekey'])) {
131 $key = $typeconfig['resourcekey'];
132 } else {
133 $key = '';
134 }
135 if (!empty($instance->password)) {
136 $secret = $instance->password;
137 } else if (!empty($typeconfig['password'])) {
138 $secret = $typeconfig['password'];
139 } else {
140 $secret = '';
141 }
3dd9ca24 142 }
e27cb316 143
b9b2e7bb 144 $endpoint = !empty($instance->toolurl) ? $instance->toolurl : $typeconfig['toolurl'];
d8d04121 145 $endpoint = trim($endpoint);
e27cb316 146
e3f69b58 147 // If the current request is using SSL and a secure tool URL is specified, use it.
ea04a9f9 148 if (lti_request_is_using_ssl() && !empty($instance->securetoolurl)) {
d8d04121
CS
149 $endpoint = trim($instance->securetoolurl);
150 }
e27cb316 151
e3f69b58 152 // If SSL is forced, use the secure tool url if specified. Otherwise, make sure https is on the normal launch URL.
153 if (isset($typeconfig['forcessl']) && ($typeconfig['forcessl'] == '1')) {
ea04a9f9 154 if (!empty($instance->securetoolurl)) {
d8d04121
CS
155 $endpoint = trim($instance->securetoolurl);
156 }
e27cb316 157
d8d04121
CS
158 $endpoint = lti_ensure_url_is_https($endpoint);
159 } else {
ea04a9f9 160 if (!strstr($endpoint, '://')) {
d8d04121
CS
161 $endpoint = 'http://' . $endpoint;
162 }
f17f4959 163 }
e27cb316 164
d8d04121
CS
165 $orgid = $typeconfig['organizationid'];
166
b9b2e7bb 167 $course = $PAGE->course;
e3f69b58 168 $islti2 = isset($tool->toolproxyid);
169 $allparams = lti_build_request($instance, $typeconfig, $course, $typeid, $islti2);
170 if ($islti2) {
171 $requestparams = lti_build_request_lti2($tool, $allparams);
8fa50fdd 172 } else {
e3f69b58 173 $requestparams = $allparams;
8fa50fdd 174 }
e3f69b58 175 $requestparams = array_merge($requestparams, lti_build_standard_request($instance, $orgid, $islti2));
176 $customstr = '';
177 if (isset($typeconfig['customparameters'])) {
178 $customstr = $typeconfig['customparameters'];
1706e83b 179 }
e3f69b58 180 $requestparams = array_merge($requestparams, lti_build_custom_parameters($toolproxy, $tool, $instance, $allparams, $customstr,
181 $instance->instructorcustomparameters, $islti2));
182
183 $launchcontainer = lti_get_launch_container($instance, $typeconfig);
edc89dfe
DW
184 $returnurlparams = array('course' => $course->id,
185 'launch_container' => $launchcontainer,
186 'instanceid' => $instance->id,
187 'sesskey' => sesskey());
6d6bd5f1
EL
188
189 // Add the return URL. We send the launch container along to help us avoid frames-within-frames when the user returns.
e3f69b58 190 $url = new \moodle_url('/mod/lti/return.php', $returnurlparams);
1706e83b 191 $returnurl = $url->out(false);
e27cb316 192
e3f69b58 193 if (isset($typeconfig['forcessl']) && ($typeconfig['forcessl'] == '1')) {
1706e83b 194 $returnurl = lti_ensure_url_is_https($returnurl);
9d57ad17 195 }
6d6bd5f1 196
e3f69b58 197 $target = '';
8fa50fdd
MN
198 switch($launchcontainer) {
199 case LTI_LAUNCH_CONTAINER_EMBED:
200 case LTI_LAUNCH_CONTAINER_EMBED_NO_BLOCKS:
201 $target = 'iframe';
202 break;
203 case LTI_LAUNCH_CONTAINER_REPLACE_MOODLE_WINDOW:
204 $target = 'frame';
205 break;
206 case LTI_LAUNCH_CONTAINER_WINDOW:
207 $target = 'window';
208 break;
209 }
e3f69b58 210 if (!empty($target)) {
8fa50fdd
MN
211 $requestparams['launch_presentation_document_target'] = $target;
212 }
213
1706e83b 214 $requestparams['launch_presentation_return_url'] = $returnurl;
e27cb316 215
d3496e3f
MN
216 // Allow request params to be updated by sub-plugins.
217 $plugins = core_component::get_plugin_list('ltisource');
218 foreach (array_keys($plugins) as $plugin) {
219 $pluginparams = component_callback('ltisource_'.$plugin, 'before_launch',
220 array($instance, $endpoint, $requestparams), array());
221
222 if (!empty($pluginparams) && is_array($pluginparams)) {
223 $requestparams = array_merge($requestparams, $pluginparams);
224 }
225 }
8fa50fdd 226
ea04a9f9 227 if (!empty($key) && !empty($secret)) {
3dd9ca24 228 $parms = lti_sign_parameters($requestparams, $endpoint, "POST", $key, $secret);
533c42ea 229
e3f69b58 230 $endpointurl = new \moodle_url($endpoint);
533c42ea
MN
231 $endpointparams = $endpointurl->params();
232
233 // Strip querystring params in endpoint url from $parms to avoid duplication.
234 if (!empty($endpointparams) && !empty($parms)) {
235 foreach (array_keys($endpointparams) as $paramname) {
236 if (isset($parms[$paramname])) {
237 unset($parms[$paramname]);
238 }
239 }
240 }
241
3dd9ca24 242 } else {
e3f69b58 243 // If no key and secret, do the launch unsigned.
244 $returnurlparams['unsigned'] = '1';
3dd9ca24 245 $parms = $requestparams;
3dd9ca24 246 }
e27cb316 247
b9b2e7bb 248 $debuglaunch = ( $instance->debuglaunch == 1 );
e27cb316 249
dbb0fec9 250 $content = lti_post_launch_html($parms, $endpoint, $debuglaunch);
e27cb316 251
b9b2e7bb
CS
252 echo $content;
253}
254
e3f69b58 255/**
256 * Prepares an LTI registration request message
257 *
258 * $param object $instance Tool Proxy instance object
259 */
260function lti_register($toolproxy) {
261 global $PAGE, $CFG;
262
263 $key = $toolproxy->guid;
264 $secret = $toolproxy->secret;
265 $endpoint = $toolproxy->regurl;
266
267 $requestparams = array();
268 $requestparams['lti_message_type'] = 'ToolProxyRegistrationRequest';
269 $requestparams['lti_version'] = 'LTI-2p0';
270 $requestparams['reg_key'] = $key;
271 $requestparams['reg_password'] = $secret;
272
273 // Change the status to pending.
274 $toolproxy->state = LTI_TOOL_PROXY_STATE_PENDING;
275 lti_update_tool_proxy($toolproxy);
276
277 // Add the profile URL.
278 $profileservice = lti_get_service_by_name('profile');
279 $profileservice->set_tool_proxy($toolproxy);
280 $requestparams['tc_profile_url'] = $profileservice->parse_value('$ToolConsumerProfile.url');
281
282 // Add the return URL.
01f38dd0 283 $returnurlparams = array('id' => $toolproxy->id, 'sesskey' => sesskey());
e3f69b58 284 $url = new \moodle_url('/mod/lti/registrationreturn.php', $returnurlparams);
285 $returnurl = $url->out(false);
286
287 $requestparams['launch_presentation_return_url'] = $returnurl;
288 $content = lti_post_launch_html($requestparams, $endpoint, false);
289
290 echo $content;
291}
292
8fa50fdd
MN
293/**
294 * Build source ID
295 *
296 * @param int $instanceid
297 * @param int $userid
298 * @param string $servicesalt
299 * @param null|int $typeid
300 * @param null|int $launchid
301 * @return stdClass
302 */
303function lti_build_sourcedid($instanceid, $userid, $servicesalt, $typeid = null, $launchid = null) {
e3f69b58 304 $data = new \stdClass();
e27cb316 305
996b0fd9
CS
306 $data->instanceid = $instanceid;
307 $data->userid = $userid;
8fa50fdd 308 $data->typeid = $typeid;
ea04a9f9 309 if (!empty($launchid)) {
f4f711d7
CS
310 $data->launchid = $launchid;
311 } else {
312 $data->launchid = mt_rand();
313 }
996b0fd9
CS
314
315 $json = json_encode($data);
316
317 $hash = hash('sha256', $json . $servicesalt, false);
318
e3f69b58 319 $container = new \stdClass();
996b0fd9
CS
320 $container->data = $data;
321 $container->hash = $hash;
322
323 return $container;
324}
325
b9b2e7bb
CS
326/**
327 * This function builds the request that must be sent to the tool producer
328 *
329 * @param object $instance Basic LTI instance object
ff9d3d81 330 * @param array $typeconfig Basic LTI tool configuration
b9b2e7bb 331 * @param object $course Course object
8fa50fdd 332 * @param int|null $typeid Basic LTI tool ID
e3f69b58 333 * @param boolean $islti2 True if an LTI 2 tool is being launched
b9b2e7bb 334 *
e3f69b58 335 * @return array Request details
b9b2e7bb 336 */
e3f69b58 337function lti_build_request($instance, $typeconfig, $course, $typeid = null, $islti2 = false) {
b9b2e7bb
CS
338 global $USER, $CFG;
339
ea04a9f9 340 if (empty($instance->cmid)) {
16cac566
CS
341 $instance->cmid = 0;
342 }
e27cb316 343
e3f69b58 344 $role = lti_get_ims_role($USER, $instance->cmid, $instance->course, $islti2);
b9b2e7bb 345
ff9d3d81
MN
346 $intro = '';
347 if (!empty($instance->cmid)) {
348 $intro = format_module_intro('lti', $instance, $instance->cmid);
349 $intro = html_to_text($intro, 0, false);
350
351 // This may look weird, but this is required for new lines
352 // so we generate the same OAuth signature as the tool provider.
353 $intro = str_replace("\n", "\r\n", $intro);
354 }
b9b2e7bb 355 $requestparams = array(
34eb0501 356 'resource_link_title' => $instance->name,
ff9d3d81 357 'resource_link_description' => $intro,
34eb0501 358 'user_id' => $USER->id,
e3f69b58 359 'lis_person_sourcedid' => $USER->idnumber,
34eb0501
CS
360 'roles' => $role,
361 'context_id' => $course->id,
362 'context_label' => $course->shortname,
363 'context_title' => $course->fullname,
b9b2e7bb 364 );
219f956a
CB
365 if (!empty($instance->id)) {
366 $requestparams['resource_link_id'] = $instance->id;
367 }
368 if (!empty($instance->resource_link_id)) {
369 $requestparams['resource_link_id'] = $instance->resource_link_id;
370 }
e3f69b58 371 if ($course->format == 'site') {
372 $requestparams['context_type'] = 'Group';
373 } else {
374 $requestparams['context_type'] = 'CourseSection';
375 $requestparams['lis_course_section_sourcedid'] = $course->idnumber;
8fa50fdd 376 }
b9b2e7bb 377 $placementsecret = $instance->servicesalt;
e27cb316 378
219f956a 379 if ( !empty($instance->id) && isset($placementsecret) && ($islti2 ||
e3f69b58 380 $typeconfig['acceptgrades'] == LTI_SETTING_ALWAYS ||
381 ($typeconfig['acceptgrades'] == LTI_SETTING_DELEGATE && $instance->instructorchoiceacceptgrades == LTI_SETTING_ALWAYS))) {
e27cb316 382
058cd1c1 383 $sourcedid = json_encode(lti_build_sourcedid($instance->id, $USER->id, $placementsecret, $typeid));
384 $requestparams['lis_result_sourcedid'] = $sourcedid;
385
e3f69b58 386 // Add outcome service URL.
387 $serviceurl = new \moodle_url('/mod/lti/service.php');
34eb0501 388 $serviceurl = $serviceurl->out();
feeb5294 389
8fa50fdd
MN
390 $forcessl = false;
391 if (!empty($CFG->mod_lti_forcessl)) {
392 $forcessl = true;
393 }
394
e3f69b58 395 if ((isset($typeconfig['forcessl']) && ($typeconfig['forcessl'] == '1')) or $forcessl) {
d8d04121
CS
396 $serviceurl = lti_ensure_url_is_https($serviceurl);
397 }
feeb5294 398
34eb0501 399 $requestparams['lis_outcome_service_url'] = $serviceurl;
b9b2e7bb
CS
400 }
401
e3f69b58 402 // Send user's name and email data if appropriate.
403 if ($islti2 || $typeconfig['sendname'] == LTI_SETTING_ALWAYS ||
5e078d62 404 ( $typeconfig['sendname'] == LTI_SETTING_DELEGATE && $instance->instructorchoicesendname == LTI_SETTING_ALWAYS ) ) {
e3f69b58 405 $requestparams['lis_person_name_given'] = $USER->firstname;
406 $requestparams['lis_person_name_family'] = $USER->lastname;
407 $requestparams['lis_person_name_full'] = $USER->firstname . ' ' . $USER->lastname;
435c709c 408 $requestparams['ext_user_username'] = $USER->username;
b9b2e7bb
CS
409 }
410
e3f69b58 411 if ($islti2 || $typeconfig['sendemailaddr'] == LTI_SETTING_ALWAYS ||
412 ($typeconfig['sendemailaddr'] == LTI_SETTING_DELEGATE && $instance->instructorchoicesendemailaddr == LTI_SETTING_ALWAYS)) {
34eb0501 413 $requestparams['lis_person_contact_email_primary'] = $USER->email;
b9b2e7bb
CS
414 }
415
e3f69b58 416 return $requestparams;
417}
418
419/**
420 * This function builds the request that must be sent to an LTI 2 tool provider
421 *
422 * @param object $tool Basic LTI tool object
423 * @param array $params Custom launch parameters
424 *
425 * @return array Request details
426 */
427function lti_build_request_lti2($tool, $params) {
428
429 $requestparams = array();
430
431 $capabilities = lti_get_capabilities();
432 $enabledcapabilities = explode("\n", $tool->enabledcapability);
433 foreach ($enabledcapabilities as $capability) {
434 if (array_key_exists($capability, $capabilities)) {
435 $val = $capabilities[$capability];
436 if ($val && (substr($val, 0, 1) != '$')) {
437 if (isset($params[$val])) {
438 $requestparams[$capabilities[$capability]] = $params[$capabilities[$capability]];
439 }
b9b2e7bb
CS
440 }
441 }
b9b2e7bb
CS
442 }
443
e3f69b58 444 return $requestparams;
445
446}
447
448/**
449 * This function builds the standard parameters for an LTI 1 or 2 request that must be sent to the tool producer
450 *
451 * @param object $instance Basic LTI instance object
452 * @param string $orgid Organisation ID
453 * @param boolean $islti2 True if an LTI 2 tool is being launched
454 *
455 * @return array Request details
456 */
457function lti_build_standard_request($instance, $orgid, $islti2) {
458 global $CFG;
459
460 $requestparams = array();
461
462 $requestparams['resource_link_id'] = $instance->id;
463 if (property_exists($instance, 'resource_link_id') and !empty($instance->resource_link_id)) {
464 $requestparams['resource_link_id'] = $instance->resource_link_id;
465 }
466
467 $requestparams['launch_presentation_locale'] = current_language();
468
469 // Make sure we let the tool know what LMS they are being called from.
470 $requestparams['ext_lms'] = 'moodle-2';
34eb0501
CS
471 $requestparams['tool_consumer_info_product_family_code'] = 'moodle';
472 $requestparams['tool_consumer_info_version'] = strval($CFG->version);
3dd9ca24 473
e3f69b58 474 // Add oauth_callback to be compliant with the 1.0A spec.
34eb0501 475 $requestparams['oauth_callback'] = 'about:blank';
3dd9ca24 476
e3f69b58 477 if (!$islti2) {
478 $requestparams['lti_version'] = 'LTI-1p0';
479 } else {
480 $requestparams['lti_version'] = 'LTI-2p0';
481 }
34eb0501 482 $requestparams['lti_message_type'] = 'basic-lti-launch-request';
e27cb316 483
e3f69b58 484 if ($orgid) {
485 $requestparams["tool_consumer_instance_guid"] = $orgid;
486 }
487 if (!empty($CFG->mod_lti_institution_name)) {
488 $requestparams['tool_consumer_instance_name'] = $CFG->mod_lti_institution_name;
489 } else {
490 $requestparams['tool_consumer_instance_name'] = get_site()->fullname;
491 }
492
b9b2e7bb
CS
493 return $requestparams;
494}
495
e3f69b58 496/**
497 * This function builds the custom parameters
498 *
499 * @param object $toolproxy Tool proxy instance object
500 * @param object $tool Tool instance object
501 * @param object $instance Tool placement instance object
502 * @param array $params LTI launch parameters
503 * @param string $customstr Custom parameters defined for tool
504 * @param string $instructorcustomstr Custom parameters defined for this placement
505 * @param boolean $islti2 True if an LTI 2 tool is being launched
506 *
507 * @return array Custom parameters
508 */
509function lti_build_custom_parameters($toolproxy, $tool, $instance, $params, $customstr, $instructorcustomstr, $islti2) {
510
511 // Concatenate the custom parameters from the administrator and the instructor
512 // Instructor parameters are only taken into consideration if the administrator
513 // has given permission.
514 $custom = array();
515 if ($customstr) {
516 $custom = lti_split_custom_parameters($toolproxy, $tool, $params, $customstr, $islti2);
517 }
518 if (!isset($typeconfig['allowinstructorcustom']) || $typeconfig['allowinstructorcustom'] != LTI_SETTING_NEVER) {
519 if ($instructorcustomstr) {
01f38dd0 520 $custom = array_merge(lti_split_custom_parameters($toolproxy, $tool, $params,
521 $instructorcustomstr, $islti2), $custom);
e3f69b58 522 }
523 }
524 if ($islti2) {
01f38dd0 525 $custom = array_merge(lti_split_custom_parameters($toolproxy, $tool, $params,
526 $tool->parameter, true), $custom);
e3f69b58 527 $settings = lti_get_tool_settings($tool->toolproxyid);
528 $custom = array_merge($custom, lti_get_custom_parameters($toolproxy, $tool, $params, $settings));
529 $settings = lti_get_tool_settings($tool->toolproxyid, $instance->course);
530 $custom = array_merge($custom, lti_get_custom_parameters($toolproxy, $tool, $params, $settings));
531 $settings = lti_get_tool_settings($tool->toolproxyid, $instance->course, $instance->id);
532 $custom = array_merge($custom, lti_get_custom_parameters($toolproxy, $tool, $params, $settings));
533 }
534
535 return $custom;
536}
537
ea04a9f9 538function lti_get_tool_table($tools, $id) {
99938034 539 global $CFG, $OUTPUT, $USER;
795dff01 540 $html = '';
e27cb316 541
795dff01
CS
542 $typename = get_string('typename', 'lti');
543 $baseurl = get_string('baseurl', 'lti');
544 $action = get_string('action', 'lti');
545 $createdon = get_string('createdon', 'lti');
e27cb316 546
795dff01 547 if (!empty($tools)) {
5de15b83 548 $html .= "
e3f69b58 549 <div id=\"{$id}_tools_container\" style=\"margin-top:.5em;margin-bottom:.5em\">
5de15b83 550 <table id=\"{$id}_tools\">
795dff01
CS
551 <thead>
552 <tr>
553 <th>$typename</th>
554 <th>$baseurl</th>
555 <th>$createdon</th>
556 <th>$action</th>
557 </tr>
558 </thead>
5de15b83 559 ";
e27cb316 560
795dff01 561 foreach ($tools as $type) {
101ec5fd 562 $date = userdate($type->timecreated, get_string('strftimedatefullshort', 'core_langconfig'));
795dff01
CS
563 $accept = get_string('accept', 'lti');
564 $update = get_string('update', 'lti');
565 $delete = get_string('delete', 'lti');
e27cb316 566
e3f69b58 567 if (empty($type->toolproxyid)) {
568 $baseurl = new \moodle_url('/mod/lti/typessettings.php', array(
569 'action' => 'accept',
570 'id' => $type->id,
571 'sesskey' => sesskey(),
572 'tab' => $id
573 ));
574 $ref = $type->baseurl;
575 } else {
576 $baseurl = new \moodle_url('/mod/lti/toolssettings.php', array(
577 'action' => 'accept',
578 'id' => $type->id,
579 'sesskey' => sesskey(),
580 'tab' => $id
581 ));
582 $ref = $type->tpname;
583 }
baf41e4b
FM
584
585 $accepthtml = $OUTPUT->action_icon($baseurl,
e3f69b58 586 new \pix_icon('t/check', $accept, '', array('class' => 'iconsmall')), null,
baf41e4b 587 array('title' => $accept, 'class' => 'editing_accept'));
795dff01
CS
588
589 $deleteaction = 'delete';
e27cb316 590
ea04a9f9 591 if ($type->state == LTI_TOOL_STATE_CONFIGURED) {
795dff01
CS
592 $accepthtml = '';
593 }
e27cb316 594
ea04a9f9 595 if ($type->state != LTI_TOOL_STATE_REJECTED) {
795dff01
CS
596 $deleteaction = 'reject';
597 $delete = get_string('reject', 'lti');
598 }
e27cb316 599
baf41e4b
FM
600 $updateurl = clone($baseurl);
601 $updateurl->param('action', 'update');
602 $updatehtml = $OUTPUT->action_icon($updateurl,
e3f69b58 603 new \pix_icon('t/edit', $update, '', array('class' => 'iconsmall')), null,
baf41e4b
FM
604 array('title' => $update, 'class' => 'editing_update'));
605
e3f69b58 606 if (($type->state != LTI_TOOL_STATE_REJECTED) || empty($type->toolproxyid)) {
607 $deleteurl = clone($baseurl);
608 $deleteurl->param('action', $deleteaction);
609 $deletehtml = $OUTPUT->action_icon($deleteurl,
610 new \pix_icon('t/delete', $delete, '', array('class' => 'iconsmall')), null,
611 array('title' => $delete, 'class' => 'editing_delete'));
612 } else {
613 $deletehtml = '';
614 }
5de15b83 615 $html .= "
795dff01
CS
616 <tr>
617 <td>
618 {$type->name}
619 </td>
620 <td>
e3f69b58 621 {$ref}
795dff01
CS
622 </td>
623 <td>
624 {$date}
625 </td>
5de15b83 626 <td align=\"center\">
baf41e4b 627 {$accepthtml}{$updatehtml}{$deletehtml}
795dff01
CS
628 </td>
629 </tr>
5de15b83 630 ";
795dff01
CS
631 }
632 $html .= '</table></div>';
633 } else {
634 $html .= get_string('no_' . $id, 'lti');
635 }
e27cb316 636
795dff01
CS
637 return $html;
638}
639
e3f69b58 640/**
641 * This function builds the tab for a category of tool proxies
642 *
643 * @param object $toolproxies Tool proxy instance objects
644 * @param string $id Category ID
645 *
646 * @return string HTML for tab
647 */
648function lti_get_tool_proxy_table($toolproxies, $id) {
649 global $OUTPUT;
650
651 if (!empty($toolproxies)) {
652 $typename = get_string('typename', 'lti');
653 $url = get_string('registrationurl', 'lti');
654 $action = get_string('action', 'lti');
655 $createdon = get_string('createdon', 'lti');
656
657 $html = <<< EOD
658 <div id="{$id}_tool_proxies_container" style="margin-top: 0.5em; margin-bottom: 0.5em">
659 <table id="{$id}_tool_proxies">
660 <thead>
661 <tr>
662 <th>{$typename}</th>
663 <th>{$url}</th>
664 <th>{$createdon}</th>
665 <th>{$action}</th>
666 </tr>
667 </thead>
668EOD;
669 foreach ($toolproxies as $toolproxy) {
670 $date = userdate($toolproxy->timecreated, get_string('strftimedatefullshort', 'core_langconfig'));
671 $accept = get_string('register', 'lti');
672 $update = get_string('update', 'lti');
673 $delete = get_string('delete', 'lti');
674
675 $baseurl = new \moodle_url('/mod/lti/registersettings.php', array(
676 'action' => 'accept',
677 'id' => $toolproxy->id,
678 'sesskey' => sesskey(),
679 'tab' => $id
680 ));
681
682 $registerurl = new \moodle_url('/mod/lti/register.php', array(
683 'id' => $toolproxy->id,
684 'sesskey' => sesskey(),
685 'tab' => 'tool_proxy'
686 ));
687
688 $accepthtml = $OUTPUT->action_icon($registerurl,
689 new \pix_icon('t/check', $accept, '', array('class' => 'iconsmall')), null,
690 array('title' => $accept, 'class' => 'editing_accept'));
691
692 $deleteaction = 'delete';
693
694 if ($toolproxy->state != LTI_TOOL_PROXY_STATE_CONFIGURED) {
695 $accepthtml = '';
696 }
697
698 if (($toolproxy->state == LTI_TOOL_PROXY_STATE_CONFIGURED) || ($toolproxy->state == LTI_TOOL_PROXY_STATE_PENDING)) {
699 $delete = get_string('cancel', 'lti');
700 }
701
702 $updateurl = clone($baseurl);
703 $updateurl->param('action', 'update');
704 $updatehtml = $OUTPUT->action_icon($updateurl,
705 new \pix_icon('t/edit', $update, '', array('class' => 'iconsmall')), null,
706 array('title' => $update, 'class' => 'editing_update'));
707
708 $deleteurl = clone($baseurl);
709 $deleteurl->param('action', $deleteaction);
710 $deletehtml = $OUTPUT->action_icon($deleteurl,
711 new \pix_icon('t/delete', $delete, '', array('class' => 'iconsmall')), null,
712 array('title' => $delete, 'class' => 'editing_delete'));
713 $html .= <<< EOD
714 <tr>
715 <td>
716 {$toolproxy->name}
717 </td>
718 <td>
719 {$toolproxy->regurl}
720 </td>
721 <td>
722 {$date}
723 </td>
724 <td align="center">
725 {$accepthtml}{$updatehtml}{$deletehtml}
726 </td>
727 </tr>
728EOD;
729 }
730 $html .= '</table></div>';
731 } else {
732 $html = get_string('no_' . $id, 'lti');
733 }
734
735 return $html;
736}
737
01f38dd0 738/**
739 * Extracts the enabled capabilities into an array, including those implicitly declared in a parameter
740 *
741 * @param object $tool Tool instance object
742 *
743 * @return Array of enabled capabilities
744 */
745function lti_get_enabled_capabilities($tool) {
746 if (!empty($tool->enabledcapability)) {
747 $enabledcapabilities = explode("\n", $tool->enabledcapability);
748 } else {
749 $enabledcapabilities = array();
750 }
751 $paramstr = str_replace("\r\n", "\n", $tool->parameter);
752 $paramstr = str_replace("\n\r", "\n", $paramstr);
753 $paramstr = str_replace("\r", "\n", $paramstr);
754 $params = explode("\n", $paramstr);
755 foreach ($params as $param) {
756 $pos = strpos($param, '=');
757 if (($pos === false) || ($pos < 1)) {
758 continue;
759 }
760 $value = trim(core_text::substr($param, $pos + 1, strlen($param)));
761 if (substr($value, 0, 1) == '$') {
762 $value = substr($value, 1);
763 if (!in_array($value, $enabledcapabilities)) {
764 $enabledcapabilities[] = $value;
765 }
766 }
767 }
768 return $enabledcapabilities;
769}
770
b9b2e7bb
CS
771/**
772 * Splits the custom parameters field to the various parameters
773 *
e3f69b58 774 * @param object $toolproxy Tool proxy instance object
775 * @param object $tool Tool instance object
776 * @param array $params LTI launch parameters
777 * @param string $customstr String containing the parameters
778 * @param boolean $islti2 True if an LTI 2 tool is being launched
b9b2e7bb
CS
779 *
780 * @return Array of custom parameters
781 */
e3f69b58 782function lti_split_custom_parameters($toolproxy, $tool, $params, $customstr, $islti2 = false) {
783 $customstr = str_replace("\r\n", "\n", $customstr);
784 $customstr = str_replace("\n\r", "\n", $customstr);
785 $customstr = str_replace("\r", "\n", $customstr);
786 $lines = explode("\n", $customstr); // Or should this split on "/[\n;]/"?
b9b2e7bb
CS
787 $retval = array();
788 foreach ($lines as $line) {
01f38dd0 789 $pos = strpos($line, '=');
b9b2e7bb
CS
790 if ( $pos === false || $pos < 1 ) {
791 continue;
792 }
2f1e464a 793 $key = trim(core_text::substr($line, 0, $pos));
e3f69b58 794 $val = trim(core_text::substr($line, $pos + 1, strlen($line)));
795 $val = lti_parse_custom_parameter($toolproxy, $tool, $params, $val, $islti2);
796 $key2 = lti_map_keyname($key);
797 $retval['custom_'.$key2] = $val;
798 if ($islti2 && ($key != $key2)) {
799 $retval['custom_'.$key] = $val;
800 }
801 }
802 return $retval;
803}
804
805/**
806 * Adds the custom parameters to an array
807 *
808 * @param object $toolproxy Tool proxy instance object
809 * @param object $tool Tool instance object
810 * @param array $params LTI launch parameters
811 * @param array $parameters Array containing the parameters
812 *
813 * @return array Array of custom parameters
814 */
815function lti_get_custom_parameters($toolproxy, $tool, $params, $parameters) {
816 $retval = array();
817 foreach ($parameters as $key => $val) {
818 $key2 = lti_map_keyname($key);
819 $val = lti_parse_custom_parameter($toolproxy, $tool, $params, $val, true);
820 $retval['custom_'.$key2] = $val;
821 if ($key != $key2) {
822 $retval['custom_'.$key] = $val;
823 }
b9b2e7bb
CS
824 }
825 return $retval;
826}
827
e3f69b58 828/**
829 * Parse a custom parameter to replace any substitution variables
830 *
831 * @param object $toolproxy Tool proxy instance object
832 * @param object $tool Tool instance object
833 * @param array $params LTI launch parameters
834 * @param string $value Custom parameter value
835 * @param boolean $islti2 True if an LTI 2 tool is being launched
836 *
837 * @return Parsed value of custom parameter
838 */
839function lti_parse_custom_parameter($toolproxy, $tool, $params, $value, $islti2) {
840 global $USER, $COURSE;
841
842 if ($value) {
843 if (substr($value, 0, 1) == '\\') {
844 $value = substr($value, 1);
845 } else if (substr($value, 0, 1) == '$') {
846 $value1 = substr($value, 1);
01f38dd0 847 $enabledcapabilities = lti_get_enabled_capabilities($tool);
e3f69b58 848 if (!$islti2 || in_array($value1, $enabledcapabilities)) {
849 $capabilities = lti_get_capabilities();
850 if (array_key_exists($value1, $capabilities)) {
851 $val = $capabilities[$value1];
852 if ($val) {
853 if (substr($val, 0, 1) != '$') {
854 $value = $params[$val];
855 } else {
856 $valarr = explode('->', substr($val, 1), 2);
857 $value = "{${$valarr[0]}->$valarr[1]}";
858 $value = str_replace('<br />' , ' ', $value);
859 $value = str_replace('<br>' , ' ', $value);
860 $value = format_string($value);
861 }
862 }
863 } else if ($islti2) {
864 $val = $value;
865 $services = lti_get_services();
866 foreach ($services as $service) {
867 $service->set_tool_proxy($toolproxy);
868 $value = $service->parse_value($val);
869 if ($val != $value) {
870 break;
871 }
872 }
873 }
874 }
875 }
876 }
877 return $value;
878}
879
b9b2e7bb
CS
880/**
881 * Used for building the names of the different custom parameters
882 *
883 * @param string $key Parameter name
884 *
885 * @return string Processed name
886 */
dbb0fec9 887function lti_map_keyname($key) {
b9b2e7bb 888 $newkey = "";
2f1e464a 889 $key = core_text::strtolower(trim($key));
b9b2e7bb
CS
890 foreach (str_split($key) as $ch) {
891 if ( ($ch >= 'a' && $ch <= 'z') || ($ch >= '0' && $ch <= '9') ) {
892 $newkey .= $ch;
893 } else {
894 $newkey .= '_';
895 }
896 }
897 return $newkey;
898}
899
900/**
16cac566 901 * Gets the IMS role string for the specified user and LTI course module.
e27cb316 902 *
e3f69b58 903 * @param mixed $user User object or user id
904 * @param int $cmid The course module id of the LTI activity
905 * @param int $courseid The course id of the LTI activity
906 * @param boolean $islti2 True if an LTI 2 tool is being launched
907 *
16cac566 908 * @return string A role string suitable for passing with an LTI launch
b9b2e7bb 909 */
e3f69b58 910function lti_get_ims_role($user, $cmid, $courseid, $islti2) {
16cac566 911 $roles = array();
e27cb316 912
ea04a9f9 913 if (empty($cmid)) {
e3f69b58 914 // If no cmid is passed, check if the user is a teacher in the course
915 // This allows other modules to programmatically "fake" a launch without
916 // a real LTI instance.
c288a3db 917 $coursecontext = context_course::instance($courseid);
e27cb316 918
ea04a9f9 919 if (has_capability('moodle/course:manageactivities', $coursecontext)) {
1d4f052e
CS
920 array_push($roles, 'Instructor');
921 } else {
922 array_push($roles, 'Learner');
923 }
16cac566 924 } else {
c288a3db 925 $context = context_module::instance($cmid);
1d4f052e 926
ea04a9f9 927 if (has_capability('mod/lti:manage', $context)) {
1d4f052e
CS
928 array_push($roles, 'Instructor');
929 } else {
930 array_push($roles, 'Learner');
931 }
b9b2e7bb 932 }
1d4f052e 933
ea04a9f9 934 if (is_siteadmin($user)) {
e3f69b58 935 if (!$islti2) {
936 array_push($roles, 'urn:lti:sysrole:ims/lis/Administrator', 'urn:lti:instrole:ims/lis/Administrator');
937 } else {
938 array_push($roles, 'http://purl.imsglobal.org/vocab/lis/v2/person#Administrator');
939 }
b9b2e7bb 940 }
e27cb316 941
16cac566 942 return join(',', $roles);
b9b2e7bb
CS
943}
944
945/**
946 * Returns configuration details for the tool
947 *
948 * @param int $typeid Basic LTI tool typeid
949 *
950 * @return array Tool Configuration
951 */
952function lti_get_type_config($typeid) {
953 global $DB;
954
5f136255
EL
955 $query = "SELECT name, value
956 FROM {lti_types_config}
957 WHERE typeid = :typeid1
958 UNION ALL
cc12ae6c 959 SELECT 'toolurl' AS name, " . $DB->sql_compare_text('baseurl', 1333) . " AS value
5f136255 960 FROM {lti_types}
3f358828 961 WHERE id = :typeid2
962 UNION ALL
963 SELECT 'icon' AS name, " . $DB->sql_compare_text('icon', 1333) . " AS value
964 FROM {lti_types}
965 WHERE id = :typeid3
966 UNION ALL
967 SELECT 'secureicon' AS name, " . $DB->sql_compare_text('secureicon', 1333) . " AS value
968 FROM {lti_types}
969 WHERE id = :typeid4";
e27cb316 970
b9b2e7bb 971 $typeconfig = array();
3f358828 972 $configs = $DB->get_records_sql($query,
973 array('typeid1' => $typeid, 'typeid2' => $typeid, 'typeid3' => $typeid, 'typeid4' => $typeid));
e27cb316 974
b9b2e7bb
CS
975 if (!empty($configs)) {
976 foreach ($configs as $config) {
977 $typeconfig[$config->name] = $config->value;
978 }
979 }
e27cb316 980
b9b2e7bb
CS
981 return $typeconfig;
982}
983
ea04a9f9 984function lti_get_tools_by_url($url, $state, $courseid = null) {
b9b2e7bb 985 $domain = lti_get_domain_from_url($url);
e27cb316 986
996b0fd9 987 return lti_get_tools_by_domain($domain, $state, $courseid);
b9b2e7bb
CS
988}
989
ea04a9f9 990function lti_get_tools_by_domain($domain, $state = null, $courseid = null) {
b9b2e7bb 991 global $DB, $SITE;
e27cb316 992
b9b2e7bb 993 $filters = array('tooldomain' => $domain);
e27cb316 994
b9b2e7bb
CS
995 $statefilter = '';
996 $coursefilter = '';
e27cb316 997
ea04a9f9 998 if ($state) {
b9b2e7bb
CS
999 $statefilter = 'AND state = :state';
1000 }
e27cb316 1001
ea04a9f9 1002 if ($courseid && $courseid != $SITE->id) {
b9b2e7bb
CS
1003 $coursefilter = 'OR course = :courseid';
1004 }
e27cb316 1005
5f136255
EL
1006 $query = "SELECT *
1007 FROM {lti_types}
1008 WHERE tooldomain = :tooldomain
1009 AND (course = :siteid $coursefilter)
1010 $statefilter";
e27cb316 1011
b9b2e7bb 1012 return $DB->get_records_sql($query, array(
e27cb316
CS
1013 'courseid' => $courseid,
1014 'siteid' => $SITE->id,
1015 'tooldomain' => $domain,
b9b2e7bb
CS
1016 'state' => $state
1017 ));
1018}
1019
1020/**
1021 * Returns all basicLTI tools configured by the administrator
1022 *
1023 */
6831c7cd 1024function lti_filter_get_types($course) {
b9b2e7bb
CS
1025 global $DB;
1026
ea04a9f9 1027 if (!empty($course)) {
e3f69b58 1028 $where = "WHERE t.course = :course";
1029 $params = array('course' => $course);
6831c7cd 1030 } else {
e3f69b58 1031 $where = '';
1032 $params = array();
6831c7cd 1033 }
e3f69b58 1034 $query = "SELECT t.id, t.name, t.baseurl, t.state, t.toolproxyid, t.timecreated, tp.name tpname
1035 FROM {lti_types} t LEFT OUTER JOIN {lti_tool_proxies} tp ON t.toolproxyid = tp.id
1036 {$where}";
1037 return $DB->get_records_sql($query, $params);
b9b2e7bb
CS
1038}
1039
d81a603e
MN
1040/**
1041 * Given an array of tools, filter them based on their state
1042 *
1043 * @param array $tools An array of lti_types records
1044 * @param int $state One of the LTI_TOOL_STATE_* constants
1045 * @return array
1046 */
1047function lti_filter_tool_types(array $tools, $state) {
1048 $return = array();
1049 foreach ($tools as $key => $tool) {
1050 if ($tool->state == $state) {
1051 $return[$key] = $tool;
1052 }
1053 }
1054 return $return;
1055}
1056
ea04a9f9 1057function lti_get_types_for_add_instance() {
996b0fd9 1058 global $DB, $SITE, $COURSE;
e27cb316 1059
5f136255
EL
1060 $query = "SELECT *
1061 FROM {lti_types}
1062 WHERE coursevisible = 1
1063 AND (course = :siteid OR course = :courseid)
1064 AND state = :active";
e27cb316 1065
e3f69b58 1066 $admintypes = $DB->get_records_sql($query,
1067 array('siteid' => $SITE->id, 'courseid' => $COURSE->id, 'active' => LTI_TOOL_STATE_CONFIGURED));
e27cb316 1068
b9b2e7bb 1069 $types = array();
e3f69b58 1070 $types[0] = (object)array('name' => get_string('automatic', 'lti'), 'course' => 0, 'toolproxyid' => null);
e27cb316 1071
ea04a9f9 1072 foreach ($admintypes as $type) {
16e8f130 1073 $types[$type->id] = $type;
b9b2e7bb 1074 }
e27cb316 1075
b9b2e7bb
CS
1076 return $types;
1077}
1078
ea04a9f9 1079function lti_get_domain_from_url($url) {
b9b2e7bb 1080 $matches = array();
e27cb316 1081
ea04a9f9 1082 if (preg_match(LTI_URL_DOMAIN_REGEX, $url, $matches)) {
b9b2e7bb
CS
1083 return $matches[1];
1084 }
1085}
1086
ea04a9f9 1087function lti_get_tool_by_url_match($url, $courseid = null, $state = LTI_TOOL_STATE_CONFIGURED) {
b69dc429 1088 $possibletools = lti_get_tools_by_url($url, $state, $courseid);
e27cb316 1089
7023b65e 1090 return lti_get_best_tool_by_url($url, $possibletools, $courseid);
b9b2e7bb
CS
1091}
1092
ea04a9f9 1093function lti_get_url_thumbprint($url) {
8fa50fdd
MN
1094 // Parse URL requires a schema otherwise everything goes into 'path'. Fixed 5.4.7 or later.
1095 if (preg_match('/https?:\/\//', $url) !== 1) {
1096 $url = 'http://'.$url;
1097 }
b9b2e7bb 1098 $urlparts = parse_url(strtolower($url));
ea04a9f9 1099 if (!isset($urlparts['path'])) {
b9b2e7bb
CS
1100 $urlparts['path'] = '';
1101 }
e27cb316 1102
ea04a9f9 1103 if (!isset($urlparts['host'])) {
d8d04121
CS
1104 $urlparts['host'] = '';
1105 }
e27cb316 1106
ea04a9f9 1107 if (substr($urlparts['host'], 0, 4) === 'www.') {
d8d04121 1108 $urlparts['host'] = substr($urlparts['host'], 4);
b9b2e7bb 1109 }
e27cb316 1110
b9b2e7bb
CS
1111 return $urllower = $urlparts['host'] . '/' . $urlparts['path'];
1112}
1113
ea04a9f9
EL
1114function lti_get_best_tool_by_url($url, $tools, $courseid = null) {
1115 if (count($tools) === 0) {
b9b2e7bb
CS
1116 return null;
1117 }
e27cb316 1118
b9b2e7bb 1119 $urllower = lti_get_url_thumbprint($url);
e27cb316 1120
ea04a9f9 1121 foreach ($tools as $tool) {
b9b2e7bb 1122 $tool->_matchscore = 0;
e27cb316 1123
b9b2e7bb 1124 $toolbaseurllower = lti_get_url_thumbprint($tool->baseurl);
e27cb316 1125
ea04a9f9 1126 if ($urllower === $toolbaseurllower) {
e3f69b58 1127 // 100 points for exact thumbprint match.
b9b2e7bb 1128 $tool->_matchscore += 100;
ea04a9f9 1129 } else if (substr($urllower, 0, strlen($toolbaseurllower)) === $toolbaseurllower) {
e3f69b58 1130 // 50 points if tool thumbprint starts with the base URL thumbprint.
b9b2e7bb
CS
1131 $tool->_matchscore += 50;
1132 }
e27cb316 1133
e3f69b58 1134 // Prefer course tools over site tools.
ea04a9f9 1135 if (!empty($courseid)) {
e3f69b58 1136 // Minus 10 points for not matching the course id (global tools).
ea04a9f9 1137 if ($tool->course != $courseid) {
7023b65e
CS
1138 $tool->_matchscore -= 10;
1139 }
1140 }
b9b2e7bb 1141 }
e27cb316 1142
ea04a9f9
EL
1143 $bestmatch = array_reduce($tools, function($value, $tool) {
1144 if ($tool->_matchscore > $value->_matchscore) {
b9b2e7bb
CS
1145 return $tool;
1146 } else {
1147 return $value;
1148 }
e27cb316 1149
b9b2e7bb 1150 }, (object)array('_matchscore' => -1));
e27cb316 1151
e3f69b58 1152 // None of the tools are suitable for this URL.
ea04a9f9 1153 if ($bestmatch->_matchscore <= 0) {
b9b2e7bb
CS
1154 return null;
1155 }
e27cb316 1156
b9b2e7bb
CS
1157 return $bestmatch;
1158}
1159
ea04a9f9 1160function lti_get_shared_secrets_by_key($key) {
020eea1b 1161 global $DB;
e27cb316 1162
e3f69b58 1163 // Look up the shared secret for the specified key in both the types_config table (for configured tools)
1164 // And in the lti resource table for ad-hoc tools.
5f136255
EL
1165 $query = "SELECT t2.value
1166 FROM {lti_types_config} t1
1167 JOIN {lti_types_config} t2 ON t1.typeid = t2.typeid
1168 JOIN {lti_types} type ON t2.typeid = type.id
1169 WHERE t1.name = 'resourcekey'
1170 AND t1.value = :key1
1171 AND t2.name = 'password'
e3f69b58 1172 AND type.state = :configured1
1173 UNION
1174 SELECT tp.secret AS value
1175 FROM {lti_tool_proxies} tp
1176 JOIN {lti_types} t ON tp.id = t.toolproxyid
1177 WHERE tp.guid = :key2
1178 AND t.state = :configured2
5f136255
EL
1179 UNION
1180 SELECT password AS value
1181 FROM {lti}
e3f69b58 1182 WHERE resourcekey = :key3";
e27cb316 1183
e3f69b58 1184 $sharedsecrets = $DB->get_records_sql($query, array('configured1' => LTI_TOOL_STATE_CONFIGURED,
1185 'configured2' => LTI_TOOL_STATE_CONFIGURED, 'key1' => $key, 'key2' => $key, 'key3' => $key));
e27cb316 1186
ea04a9f9 1187 $values = array_map(function($item) {
020eea1b
CS
1188 return $item->value;
1189 }, $sharedsecrets);
e27cb316 1190
e3f69b58 1191 // There should really only be one shared secret per key. But, we can't prevent
1192 // more than one getting entered. For instance, if the same key is used for two tool providers.
020eea1b
CS
1193 return $values;
1194}
1195
b9b2e7bb
CS
1196/**
1197 * Delete a Basic LTI configuration
1198 *
1199 * @param int $id Configuration id
1200 */
1201function lti_delete_type($id) {
1202 global $DB;
1203
e3f69b58 1204 // We should probably just copy the launch URL to the tool instances in this case... using a single query.
b9b2e7bb
CS
1205 /*
1206 $instances = $DB->get_records('lti', array('typeid' => $id));
1207 foreach ($instances as $instance) {
1208 $instance->typeid = 0;
1209 $DB->update_record('lti', $instance);
1210 }*/
1211
1212 $DB->delete_records('lti_types', array('id' => $id));
1213 $DB->delete_records('lti_types_config', array('typeid' => $id));
1214}
1215
ea04a9f9 1216function lti_set_state_for_type($id, $state) {
b9b2e7bb 1217 global $DB;
e27cb316 1218
b9b2e7bb
CS
1219 $DB->update_record('lti_types', array('id' => $id, 'state' => $state));
1220}
1221
1222/**
1223 * Transforms a basic LTI object to an array
1224 *
1225 * @param object $ltiobject Basic LTI object
1226 *
1227 * @return array Basic LTI configuration details
1228 */
1229function lti_get_config($ltiobject) {
1230 $typeconfig = array();
1231 $typeconfig = (array)$ltiobject;
1232 $additionalconfig = lti_get_type_config($ltiobject->typeid);
1233 $typeconfig = array_merge($typeconfig, $additionalconfig);
1234 return $typeconfig;
1235}
1236
1237/**
1238 *
1239 * Generates some of the tool configuration based on the instance details
1240 *
1241 * @param int $id
1242 *
1243 * @return Instance configuration
1244 *
1245 */
1246function lti_get_type_config_from_instance($id) {
1247 global $DB;
1248
1249 $instance = $DB->get_record('lti', array('id' => $id));
1250 $config = lti_get_config($instance);
1251
e3f69b58 1252 $type = new \stdClass();
b9b2e7bb
CS
1253 $type->lti_fix = $id;
1254 if (isset($config['toolurl'])) {
1255 $type->lti_toolurl = $config['toolurl'];
1256 }
1257 if (isset($config['instructorchoicesendname'])) {
1258 $type->lti_sendname = $config['instructorchoicesendname'];
1259 }
1260 if (isset($config['instructorchoicesendemailaddr'])) {
1261 $type->lti_sendemailaddr = $config['instructorchoicesendemailaddr'];
1262 }
1263 if (isset($config['instructorchoiceacceptgrades'])) {
1264 $type->lti_acceptgrades = $config['instructorchoiceacceptgrades'];
1265 }
1266 if (isset($config['instructorchoiceallowroster'])) {
1267 $type->lti_allowroster = $config['instructorchoiceallowroster'];
1268 }
1269
1270 if (isset($config['instructorcustomparameters'])) {
1271 $type->lti_allowsetting = $config['instructorcustomparameters'];
1272 }
1273 return $type;
1274}
1275
1276/**
1277 * Generates some of the tool configuration based on the admin configuration details
1278 *
1279 * @param int $id
1280 *
1281 * @return Configuration details
1282 */
1283function lti_get_type_type_config($id) {
1284 global $DB;
1285
1286 $basicltitype = $DB->get_record('lti_types', array('id' => $id));
1287 $config = lti_get_type_config($id);
1288
e3f69b58 1289 $type = new \stdClass();
5f72d102 1290
b9b2e7bb 1291 $type->lti_typename = $basicltitype->name;
e27cb316 1292
6831c7cd 1293 $type->typeid = $basicltitype->id;
e27cb316 1294
e3f69b58 1295 $type->toolproxyid = $basicltitype->toolproxyid;
1296
b9b2e7bb 1297 $type->lti_toolurl = $basicltitype->baseurl;
e27cb316 1298
e3f69b58 1299 $type->lti_parameters = $basicltitype->parameter;
1300
3f358828 1301 $type->lti_icon = $basicltitype->icon;
1302
1303 $type->lti_secureicon = $basicltitype->secureicon;
1304
b9b2e7bb
CS
1305 if (isset($config['resourcekey'])) {
1306 $type->lti_resourcekey = $config['resourcekey'];
1307 }
1308 if (isset($config['password'])) {
1309 $type->lti_password = $config['password'];
1310 }
1311
1312 if (isset($config['sendname'])) {
1313 $type->lti_sendname = $config['sendname'];
1314 }
ea04a9f9 1315 if (isset($config['instructorchoicesendname'])) {
b9b2e7bb
CS
1316 $type->lti_instructorchoicesendname = $config['instructorchoicesendname'];
1317 }
ea04a9f9 1318 if (isset($config['sendemailaddr'])) {
b9b2e7bb
CS
1319 $type->lti_sendemailaddr = $config['sendemailaddr'];
1320 }
ea04a9f9 1321 if (isset($config['instructorchoicesendemailaddr'])) {
b9b2e7bb
CS
1322 $type->lti_instructorchoicesendemailaddr = $config['instructorchoicesendemailaddr'];
1323 }
ea04a9f9 1324 if (isset($config['acceptgrades'])) {
b9b2e7bb
CS
1325 $type->lti_acceptgrades = $config['acceptgrades'];
1326 }
ea04a9f9 1327 if (isset($config['instructorchoiceacceptgrades'])) {
b9b2e7bb
CS
1328 $type->lti_instructorchoiceacceptgrades = $config['instructorchoiceacceptgrades'];
1329 }
ea04a9f9 1330 if (isset($config['allowroster'])) {
b9b2e7bb
CS
1331 $type->lti_allowroster = $config['allowroster'];
1332 }
ea04a9f9 1333 if (isset($config['instructorchoiceallowroster'])) {
b9b2e7bb
CS
1334 $type->lti_instructorchoiceallowroster = $config['instructorchoiceallowroster'];
1335 }
1336
1337 if (isset($config['customparameters'])) {
1338 $type->lti_customparameters = $config['customparameters'];
1339 }
1340
ea04a9f9 1341 if (isset($config['forcessl'])) {
d8d04121
CS
1342 $type->lti_forcessl = $config['forcessl'];
1343 }
e27cb316 1344
b9b2e7bb
CS
1345 if (isset($config['organizationid'])) {
1346 $type->lti_organizationid = $config['organizationid'];
1347 }
1348 if (isset($config['organizationurl'])) {
1349 $type->lti_organizationurl = $config['organizationurl'];
1350 }
1351 if (isset($config['organizationdescr'])) {
1352 $type->lti_organizationdescr = $config['organizationdescr'];
1353 }
1354 if (isset($config['launchcontainer'])) {
1355 $type->lti_launchcontainer = $config['launchcontainer'];
1356 }
e27cb316 1357
b9b2e7bb
CS
1358 if (isset($config['coursevisible'])) {
1359 $type->lti_coursevisible = $config['coursevisible'];
1360 }
e27cb316 1361
b9b2e7bb
CS
1362 if (isset($config['debuglaunch'])) {
1363 $type->lti_debuglaunch = $config['debuglaunch'];
1364 }
e27cb316 1365
b9b2e7bb 1366 if (isset($config['module_class_type'])) {
036e84c3 1367 $type->lti_module_class_type = $config['module_class_type'];
b9b2e7bb
CS
1368 }
1369
1370 return $type;
1371}
1372
ea04a9f9 1373function lti_prepare_type_for_save($type, $config) {
e3f69b58 1374 if (isset($config->lti_toolurl)) {
1375 $type->baseurl = $config->lti_toolurl;
1376 $type->tooldomain = lti_get_domain_from_url($config->lti_toolurl);
1377 }
1378 if (isset($config->lti_typename)) {
1379 $type->name = $config->lti_typename;
1380 }
b9b2e7bb
CS
1381 $type->coursevisible = !empty($config->lti_coursevisible) ? $config->lti_coursevisible : 0;
1382 $config->lti_coursevisible = $type->coursevisible;
e27cb316 1383
3f358828 1384 if (isset($config->lti_icon)) {
1385 $type->icon = $config->lti_icon;
1386 }
1387 if (isset($config->lti_secureicon)) {
1388 $type->secureicon = $config->lti_secureicon;
1389 }
1390
e3f69b58 1391 if (isset($config->lti_forcessl)) {
1392 $type->forcessl = !empty($config->lti_forcessl) ? $config->lti_forcessl : 0;
1393 $config->lti_forcessl = $type->forcessl;
1394 }
e27cb316 1395
b9b2e7bb 1396 $type->timemodified = time();
e27cb316 1397
b9b2e7bb
CS
1398 unset ($config->lti_typename);
1399 unset ($config->lti_toolurl);
3f358828 1400 unset ($config->lti_icon);
1401 unset ($config->lti_secureicon);
b9b2e7bb
CS
1402}
1403
ea04a9f9 1404function lti_update_type($type, $config) {
3f358828 1405 global $DB, $CFG;
e27cb316 1406
b9b2e7bb 1407 lti_prepare_type_for_save($type, $config);
e27cb316 1408
3f358828 1409 $clearcache = false;
1410 if (lti_request_is_using_ssl() && !empty($type->secureicon)) {
1411 $clearcache = !isset($config->oldicon) || ($config->oldicon !== $type->secureicon);
1412 } else {
1413 $clearcache = isset($type->icon) && (!isset($config->oldicon) || ($config->oldicon !== $type->icon));
1414 }
1415 unset($config->oldicon);
1416
b9b2e7bb
CS
1417 if ($DB->update_record('lti_types', $type)) {
1418 foreach ($config as $key => $value) {
e3f69b58 1419 if (substr($key, 0, 4) == 'lti_' && !is_null($value)) {
1420 $record = new \StdClass();
b9b2e7bb
CS
1421 $record->typeid = $type->id;
1422 $record->name = substr($key, 4);
1423 $record->value = $value;
b9b2e7bb
CS
1424 lti_update_config($record);
1425 }
1426 }
3f358828 1427 require_once($CFG->libdir.'/modinfolib.php');
1428 if ($clearcache) {
1429 rebuild_course_cache();
1430 }
b9b2e7bb
CS
1431 }
1432}
1433
ea04a9f9 1434function lti_add_type($type, $config) {
b9b2e7bb 1435 global $USER, $SITE, $DB;
e27cb316 1436
b9b2e7bb 1437 lti_prepare_type_for_save($type, $config);
e27cb316 1438
ea04a9f9 1439 if (!isset($type->state)) {
b9b2e7bb
CS
1440 $type->state = LTI_TOOL_STATE_PENDING;
1441 }
e27cb316 1442
ea04a9f9 1443 if (!isset($type->timecreated)) {
b9b2e7bb
CS
1444 $type->timecreated = time();
1445 }
e27cb316 1446
ea04a9f9 1447 if (!isset($type->createdby)) {
b9b2e7bb
CS
1448 $type->createdby = $USER->id;
1449 }
e27cb316 1450
ea04a9f9 1451 if (!isset($type->course)) {
b9b2e7bb
CS
1452 $type->course = $SITE->id;
1453 }
e27cb316 1454
e3f69b58 1455 // Create a salt value to be used for signing passed data to extension services
1456 // The outcome service uses the service salt on the instance. This can be used
1457 // for communication with services not related to a specific LTI instance.
b9b2e7bb
CS
1458 $config->lti_servicesalt = uniqid('', true);
1459
1460 $id = $DB->insert_record('lti_types', $type);
1461
1462 if ($id) {
1463 foreach ($config as $key => $value) {
e3f69b58 1464 if (substr($key, 0, 4) == 'lti_' && !is_null($value)) {
1465 $record = new \StdClass();
b9b2e7bb
CS
1466 $record->typeid = $id;
1467 $record->name = substr($key, 4);
1468 $record->value = $value;
1469
1470 lti_add_config($record);
1471 }
1472 }
1473 }
e27cb316 1474
996b0fd9 1475 return $id;
b9b2e7bb
CS
1476}
1477
e3f69b58 1478/**
1479 * Given an array of tool proxies, filter them based on their state
1480 *
1481 * @param array $toolproxies An array of lti_tool_proxies records
1482 * @param int $state One of the LTI_TOOL_PROXY_STATE_* constants
1483 *
1484 * @return array
1485 */
1486function lti_filter_tool_proxy_types(array $toolproxies, $state) {
1487 $return = array();
1488 foreach ($toolproxies as $key => $toolproxy) {
1489 if ($toolproxy->state == $state) {
1490 $return[$key] = $toolproxy;
1491 }
1492 }
1493 return $return;
1494}
1495
1496/**
1497 * Get the tool proxy instance given its GUID
1498 *
1499 * @param string $toolproxyguid Tool proxy GUID value
1500 *
1501 * @return object
1502 */
1503function lti_get_tool_proxy_from_guid($toolproxyguid) {
1504 global $DB;
1505
1506 $toolproxy = $DB->get_record('lti_tool_proxies', array('guid' => $toolproxyguid));
1507
1508 return $toolproxy;
1509}
1510
1511/**
1512 * Generates some of the tool proxy configuration based on the admin configuration details
1513 *
1514 * @param int $id
1515 *
1516 * @return Tool Proxy details
1517 */
1518function lti_get_tool_proxy($id) {
1519 global $DB;
1520
1521 $toolproxy = $DB->get_record('lti_tool_proxies', array('id' => $id));
1522 return $toolproxy;
1523}
1524
1525/**
1526 * Generates some of the tool proxy configuration based on the admin configuration details
1527 *
1528 * @param int $id
1529 *
1530 * @return Tool Proxy details
1531 */
1532function lti_get_tool_proxy_config($id) {
1533 $toolproxy = lti_get_tool_proxy($id);
1534
1535 $tp = new \stdClass();
1536 $tp->lti_registrationname = $toolproxy->name;
1537 $tp->toolproxyid = $toolproxy->id;
1538 $tp->state = $toolproxy->state;
1539 $tp->lti_registrationurl = $toolproxy->regurl;
1540 $tp->lti_capabilities = explode("\n", $toolproxy->capabilityoffered);
1541 $tp->lti_services = explode("\n", $toolproxy->serviceoffered);
1542
1543 return $tp;
1544}
1545
1546/**
1547 * Update the database with a tool proxy instance
1548 *
1549 * @param object $config Tool proxy definition
1550 *
1551 * @return int Record id number
1552 */
1553function lti_add_tool_proxy($config) {
1554 global $USER, $DB;
1555
1556 $toolproxy = new \stdClass();
1557 if (isset($config->lti_registrationname)) {
1558 $toolproxy->name = trim($config->lti_registrationname);
1559 }
1560 if (isset($config->lti_registrationurl)) {
1561 $toolproxy->regurl = trim($config->lti_registrationurl);
1562 }
1563 if (isset($config->lti_capabilities)) {
1564 $toolproxy->capabilityoffered = implode("\n", $config->lti_capabilities);
1565 }
1566 if (isset($config->lti_services)) {
1567 $toolproxy->serviceoffered = implode("\n", $config->lti_services);
1568 }
1569 if (isset($config->toolproxyid) && !empty($config->toolproxyid)) {
1570 $toolproxy->id = $config->toolproxyid;
1571 if (!isset($toolproxy->state) || ($toolproxy->state != LTI_TOOL_PROXY_STATE_ACCEPTED)) {
1572 $toolproxy->state = LTI_TOOL_PROXY_STATE_CONFIGURED;
1573 $toolproxy->guid = random_string();
1574 $toolproxy->secret = random_string();
1575 }
1576 $id = lti_update_tool_proxy($toolproxy);
1577 } else {
1578 $toolproxy->state = LTI_TOOL_PROXY_STATE_CONFIGURED;
1579 $toolproxy->timemodified = time();
1580 $toolproxy->timecreated = $toolproxy->timemodified;
1581 if (!isset($toolproxy->createdby)) {
1582 $toolproxy->createdby = $USER->id;
1583 }
1584 $toolproxy->guid = random_string();
1585 $toolproxy->secret = random_string();
1586 $id = $DB->insert_record('lti_tool_proxies', $toolproxy);
1587 }
1588
1589 return $id;
1590}
1591
1592/**
1593 * Updates a tool proxy in the database
1594 *
1595 * @param object $toolproxy Tool proxy
1596 *
1597 * @return int Record id number
1598 */
1599function lti_update_tool_proxy($toolproxy) {
1600 global $DB;
1601
1602 $toolproxy->timemodified = time();
1603 $id = $DB->update_record('lti_tool_proxies', $toolproxy);
1604
1605 return $id;
1606}
1607
1608/**
1609 * Delete a Tool Proxy
1610 *
1611 * @param int $id Tool Proxy id
1612 */
1613function lti_delete_tool_proxy($id) {
1614 global $DB;
1615 $DB->delete_records('lti_tool_settings', array('toolproxyid' => $id));
1616 $tools = $DB->get_records('lti_types', array('toolproxyid' => $id));
1617 foreach ($tools as $tool) {
1618 lti_delete_type($tool->id);
1619 }
1620 $DB->delete_records('lti_tool_proxies', array('id' => $id));
1621}
1622
b9b2e7bb
CS
1623/**
1624 * Add a tool configuration in the database
1625 *
e3f69b58 1626 * @param object $config Tool configuration
b9b2e7bb
CS
1627 *
1628 * @return int Record id number
1629 */
1630function lti_add_config($config) {
1631 global $DB;
1632
1633 return $DB->insert_record('lti_types_config', $config);
1634}
1635
1636/**
1637 * Updates a tool configuration in the database
1638 *
e3f69b58 1639 * @param object $config Tool configuration
b9b2e7bb
CS
1640 *
1641 * @return Record id number
1642 */
1643function lti_update_config($config) {
1644 global $DB;
1645
1646 $return = true;
1647 $old = $DB->get_record('lti_types_config', array('typeid' => $config->typeid, 'name' => $config->name));
e27cb316 1648
b9b2e7bb
CS
1649 if ($old) {
1650 $config->id = $old->id;
1651 $return = $DB->update_record('lti_types_config', $config);
1652 } else {
1653 $return = $DB->insert_record('lti_types_config', $config);
1654 }
1655 return $return;
1656}
1657
e3f69b58 1658/**
1659 * Gets the tool settings
1660 *
1661 * @param int $toolproxyid Id of tool proxy record
1662 * @param int $courseid Id of course (null if system settings)
1663 * @param int $instanceid Id of course module (null if system or context settings)
1664 *
1665 * @return array Array settings
1666 */
1667function lti_get_tool_settings($toolproxyid, $courseid = null, $instanceid = null) {
1668 global $DB;
1669
1670 $settings = array();
1671 $settingsstr = $DB->get_field('lti_tool_settings', 'settings', array('toolproxyid' => $toolproxyid,
1672 'course' => $courseid, 'coursemoduleid' => $instanceid));
1673 if ($settingsstr !== false) {
1674 $settings = json_decode($settingsstr, true);
1675 }
1676 return $settings;
1677}
1678
1679/**
1680 * Sets the tool settings (
1681 *
1682 * @param array $settings Array of settings
1683 * @param int $toolproxyid Id of tool proxy record
1684 * @param int $courseid Id of course (null if system settings)
1685 * @param int $instanceid Id of course module (null if system or context settings)
1686 */
1687function lti_set_tool_settings($settings, $toolproxyid, $courseid = null, $instanceid = null) {
1688 global $DB;
1689
1690 $json = json_encode($settings);
1691 $record = $DB->get_record('lti_tool_settings', array('toolproxyid' => $toolproxyid,
1692 'course' => $courseid, 'coursemoduleid' => $instanceid));
1693 if ($record !== false) {
1694 $DB->update_record('lti_tool_settings', array('id' => $record->id, 'settings' => $json, 'timemodified' => time()));
1695 } else {
1696 $record = new \stdClass();
1697 $record->toolproxyid = $toolproxyid;
1698 $record->course = $courseid;
1699 $record->coursemoduleid = $instanceid;
1700 $record->settings = $json;
1701 $record->timecreated = time();
1702 $record->timemodified = $record->timecreated;
1703 $DB->insert_record('lti_tool_settings', $record);
1704 }
1705}
1706
b9b2e7bb
CS
1707/**
1708 * Signs the petition to launch the external tool using OAuth
1709 *
1710 * @param $oldparms Parameters to be passed for signing
1711 * @param $endpoint url of the external tool
1712 * @param $method Method for sending the parameters (e.g. POST)
1713 * @param $oauth_consumoer_key Key
1714 * @param $oauth_consumoer_secret Secret
b9b2e7bb 1715 */
3dd9ca24 1716function lti_sign_parameters($oldparms, $endpoint, $method, $oauthconsumerkey, $oauthconsumersecret) {
e3f69b58 1717
b9b2e7bb 1718 $parms = $oldparms;
b9b2e7bb
CS
1719
1720 $testtoken = '';
e27cb316 1721
e3f69b58 1722 // TODO: Switch to core oauthlib once implemented - MDL-30149.
795dff01
CS
1723 $hmacmethod = new lti\OAuthSignatureMethod_HMAC_SHA1();
1724 $testconsumer = new lti\OAuthConsumer($oauthconsumerkey, $oauthconsumersecret, null);
795dff01 1725 $accreq = lti\OAuthRequest::from_consumer_and_token($testconsumer, $testtoken, $method, $endpoint, $parms);
b9b2e7bb
CS
1726 $accreq->sign_request($hmacmethod, $testconsumer, $testtoken);
1727
b9b2e7bb
CS
1728 $newparms = $accreq->get_parameters();
1729
1730 return $newparms;
1731}
1732
1733/**
1734 * Posts the launch petition HTML
1735 *
1736 * @param $newparms Signed parameters
1737 * @param $endpoint URL of the external tool
1738 * @param $debug Debug (true/false)
1739 */
dbb0fec9 1740function lti_post_launch_html($newparms, $endpoint, $debug=false) {
e3f69b58 1741 $r = "<form action=\"" . $endpoint .
1742 "\" name=\"ltiLaunchForm\" id=\"ltiLaunchForm\" method=\"post\" encType=\"application/x-www-form-urlencoded\">\n";
e27cb316 1743
e3f69b58 1744 // Contruct html for the launch parameters.
b9b2e7bb
CS
1745 foreach ($newparms as $key => $value) {
1746 $key = htmlspecialchars($key);
1747 $value = htmlspecialchars($value);
1748 if ( $key == "ext_submit" ) {
e3f69b58 1749 $r .= "<input type=\"submit\"";
b9b2e7bb 1750 } else {
e3f69b58 1751 $r .= "<input type=\"hidden\" name=\"{$key}\"";
b9b2e7bb 1752 }
e3f69b58 1753 $r .= " value=\"";
b9b2e7bb
CS
1754 $r .= $value;
1755 $r .= "\"/>\n";
1756 }
1757
1758 if ( $debug ) {
1759 $r .= "<script language=\"javascript\"> \n";
1760 $r .= " //<![CDATA[ \n";
1761 $r .= "function basicltiDebugToggle() {\n";
1762 $r .= " var ele = document.getElementById(\"basicltiDebug\");\n";
ea04a9f9 1763 $r .= " if (ele.style.display == \"block\") {\n";
b9b2e7bb
CS
1764 $r .= " ele.style.display = \"none\";\n";
1765 $r .= " }\n";
1766 $r .= " else {\n";
1767 $r .= " ele.style.display = \"block\";\n";
1768 $r .= " }\n";
1769 $r .= "} \n";
1770 $r .= " //]]> \n";
1771 $r .= "</script>\n";
1772 $r .= "<a id=\"displayText\" href=\"javascript:basicltiDebugToggle();\">";
1773 $r .= get_string("toggle_debug_data", "lti")."</a>\n";
1774 $r .= "<div id=\"basicltiDebug\" style=\"display:none\">\n";
e3f69b58 1775 $r .= "<b>".get_string("basiclti_endpoint", "lti")."</b><br/>\n";
b9b2e7bb 1776 $r .= $endpoint . "<br/>\n&nbsp;<br/>\n";
e3f69b58 1777 $r .= "<b>".get_string("basiclti_parameters", "lti")."</b><br/>\n";
b9b2e7bb
CS
1778 foreach ($newparms as $key => $value) {
1779 $key = htmlspecialchars($key);
1780 $value = htmlspecialchars($value);
1781 $r .= "$key = $value<br/>\n";
1782 }
1783 $r .= "&nbsp;<br/>\n";
b9b2e7bb
CS
1784 $r .= "</div>\n";
1785 }
1786 $r .= "</form>\n";
1787
1788 if ( ! $debug ) {
b9b2e7bb
CS
1789 $r .= " <script type=\"text/javascript\"> \n" .
1790 " //<![CDATA[ \n" .
b9b2e7bb
CS
1791 " document.ltiLaunchForm.submit(); \n" .
1792 " //]]> \n" .
1793 " </script> \n";
1794 }
1795 return $r;
1796}
1797
ea04a9f9 1798function lti_get_type($typeid) {
996b0fd9 1799 global $DB;
e27cb316 1800
996b0fd9 1801 return $DB->get_record('lti_types', array('id' => $typeid));
57d1dffd
CS
1802}
1803
ea04a9f9
EL
1804function lti_get_launch_container($lti, $toolconfig) {
1805 if (empty($lti->launchcontainer)) {
e27cb316
CS
1806 $lti->launchcontainer = LTI_LAUNCH_CONTAINER_DEFAULT;
1807 }
1808
ea04a9f9
EL
1809 if ($lti->launchcontainer == LTI_LAUNCH_CONTAINER_DEFAULT) {
1810 if (isset($toolconfig['launchcontainer'])) {
c4d80efe
CS
1811 $launchcontainer = $toolconfig['launchcontainer'];
1812 }
1813 } else {
1814 $launchcontainer = $lti->launchcontainer;
1815 }
e27cb316 1816
ea04a9f9 1817 if (empty($launchcontainer) || $launchcontainer == LTI_LAUNCH_CONTAINER_DEFAULT) {
c4d80efe
CS
1818 $launchcontainer = LTI_LAUNCH_CONTAINER_EMBED_NO_BLOCKS;
1819 }
57d1dffd 1820
c3d2fbf9 1821 $devicetype = core_useragent::get_device_type();
57d1dffd 1822
e3f69b58 1823 // Scrolling within the object element doesn't work on iOS or Android
1824 // Opening the popup window also had some issues in testing
1825 // For mobile devices, always take up the entire screen to ensure the best experience.
c3d2fbf9 1826 if ($devicetype === core_useragent::DEVICETYPE_MOBILE || $devicetype === core_useragent::DEVICETYPE_TABLET ) {
57d1dffd
CS
1827 $launchcontainer = LTI_LAUNCH_CONTAINER_REPLACE_MOODLE_WINDOW;
1828 }
e27cb316 1829
57d1dffd 1830 return $launchcontainer;
d8d04121
CS
1831}
1832
1833function lti_request_is_using_ssl() {
33dca156
PS
1834 global $CFG;
1835 return (stripos($CFG->httpswwwroot, 'https://') === 0);
d8d04121
CS
1836}
1837
ea04a9f9
EL
1838function lti_ensure_url_is_https($url) {
1839 if (!strstr($url, '://')) {
d8d04121
CS
1840 $url = 'https://' . $url;
1841 } else {
e3f69b58 1842 // If the URL starts with http, replace with https.
ea04a9f9 1843 if (stripos($url, 'http://') === 0) {
adc23cc9 1844 $url = 'https://' . substr($url, 7);
d8d04121
CS
1845 }
1846 }
e27cb316 1847
d8d04121 1848 return $url;
61eb12d4 1849}
8fa50fdd
MN
1850
1851/**
1852 * Determines if we should try to log the request
1853 *
1854 * @param string $rawbody
1855 * @return bool
1856 */
1857function lti_should_log_request($rawbody) {
1858 global $CFG;
1859
1860 if (empty($CFG->mod_lti_log_users)) {
1861 return false;
1862 }
1863
1864 $logusers = explode(',', $CFG->mod_lti_log_users);
1865 if (empty($logusers)) {
1866 return false;
1867 }
1868
1869 try {
e3f69b58 1870 $xml = new \SimpleXMLElement($rawbody);
8fa50fdd
MN
1871 $ns = $xml->getNamespaces();
1872 $ns = array_shift($ns);
1873 $xml->registerXPathNamespace('lti', $ns);
1874 $requestuserid = '';
1875 if ($node = $xml->xpath('//lti:userId')) {
1876 $node = $node[0];
1877 $requestuserid = clean_param((string) $node, PARAM_INT);
1878 } else if ($node = $xml->xpath('//lti:sourcedId')) {
1879 $node = $node[0];
1880 $resultjson = json_decode((string) $node);
1881 $requestuserid = clean_param($resultjson->data->userid, PARAM_INT);
1882 }
1883 } catch (Exception $e) {
1884 return false;
1885 }
1886
1887 if (empty($requestuserid) or !in_array($requestuserid, $logusers)) {
1888 return false;
1889 }
1890
1891 return true;
1892}
1893
1894/**
1895 * Logs the request to a file in temp dir
1896 *
1897 * @param string $rawbody
1898 */
1899function lti_log_request($rawbody) {
1900 if ($tempdir = make_temp_directory('mod_lti', false)) {
1901 if ($tempfile = tempnam($tempdir, 'mod_lti_request'.date('YmdHis'))) {
1902 file_put_contents($tempfile, $rawbody);
1903 chmod($tempfile, 0644);
1904 }
1905 }
1906}
1907
1908/**
1909 * Fetches LTI type configuration for an LTI instance
1910 *
1911 * @param stdClass $instance
1912 * @return array Can be empty if no type is found
1913 */
1914function lti_get_type_config_by_instance($instance) {
1915 $typeid = null;
1916 if (empty($instance->typeid)) {
1917 $tool = lti_get_tool_by_url_match($instance->toolurl, $instance->course);
1918 if ($tool) {
1919 $typeid = $tool->id;
1920 }
1921 } else {
1922 $typeid = $instance->typeid;
1923 }
1924 if (!empty($typeid)) {
1925 return lti_get_type_config($typeid);
1926 }
1927 return array();
1928}
1929
1930/**
1931 * Enforce type config settings onto the LTI instance
1932 *
1933 * @param stdClass $instance
1934 * @param array $typeconfig
1935 */
1936function lti_force_type_config_settings($instance, array $typeconfig) {
1937 $forced = array(
1938 'instructorchoicesendname' => 'sendname',
1939 'instructorchoicesendemailaddr' => 'sendemailaddr',
1940 'instructorchoiceacceptgrades' => 'acceptgrades',
1941 );
1942
1943 foreach ($forced as $instanceparam => $typeconfigparam) {
1944 if (array_key_exists($typeconfigparam, $typeconfig) && $typeconfig[$typeconfigparam] != LTI_SETTING_DELEGATE) {
1945 $instance->$instanceparam = $typeconfig[$typeconfigparam];
1946 }
1947 }
1948}
1949
e3f69b58 1950/**
1951 * Initializes an array with the capabilities supported by the LTI module
1952 *
1953 * @return array List of capability names (without a dollar sign prefix)
1954 */
1955function lti_get_capabilities() {
1956
1957 $capabilities = array(
1958 'basic-lti-launch-request' => '',
1959 'Context.id' => 'context_id',
1960 'CourseSection.title' => 'context_title',
1961 'CourseSection.label' => 'context_label',
1962 'CourseSection.sourcedId' => 'lis_course_section_sourcedid',
1963 'CourseSection.longDescription' => '$COURSE->summary',
1964 'CourseSection.timeFrame.begin' => '$COURSE->startdate',
1965 'ResourceLink.id' => 'resource_link_id',
1966 'ResourceLink.title' => 'resource_link_title',
1967 'ResourceLink.description' => 'resource_link_description',
1968 'User.id' => 'user_id',
1969 'User.username' => '$USER->username',
1970 'Person.name.full' => 'lis_person_name_full',
1971 'Person.name.given' => 'lis_person_name_given',
1972 'Person.name.family' => 'lis_person_name_family',
1973 'Person.email.primary' => 'lis_person_contact_email_primary',
1974 'Person.sourcedId' => 'lis_person_sourcedid',
1975 'Person.name.middle' => '$USER->middlename',
1976 'Person.address.street1' => '$USER->address',
1977 'Person.address.locality' => '$USER->city',
1978 'Person.address.country' => '$USER->country',
1979 'Person.address.timezone' => '$USER->timezone',
1980 'Person.phone.primary' => '$USER->phone1',
1981 'Person.phone.mobile' => '$USER->phone2',
1982 'Person.webaddress' => '$USER->url',
1983 'Membership.role' => 'roles',
1984 'Result.sourcedId' => 'lis_result_sourcedid',
1985 'Result.autocreate' => 'lis_outcome_service_url');
1986
1987 return $capabilities;
1988
1989}
1990
1991/**
1992 * Initializes an array with the services supported by the LTI module
1993 *
1994 * @return array List of services
1995 */
1996function lti_get_services() {
1997
1998 $services = array();
1999 $definedservices = core_component::get_plugin_list('ltiservice');
2000 foreach ($definedservices as $name => $location) {
2001 $classname = "\\ltiservice_{$name}\\local\\service\\{$name}";
2002 $services[] = new $classname();
2003 }
2004
2005 return $services;
2006
2007}
2008
2009/**
2010 * Initializes an instance of the named service
2011 *
2012 * @param string $servicename Name of service
2013 *
2014 * @return mod_lti\local\ltiservice\service_base Service
2015 */
2016function lti_get_service_by_name($servicename) {
2017
2018 $service = false;
2019 $classname = "\\ltiservice_{$servicename}\\local\\service\\{$servicename}";
2020 if (class_exists($classname)) {
2021 $service = new $classname();
2022 }
2023
2024 return $service;
2025
2026}
2027
2028/**
2029 * Finds a service by id
2030 *
2031 * @param array $services Array of services
2032 * @param string $resourceid ID of resource
2033 *
2034 * @return mod_lti\local\ltiservice\service_base Service
2035 */
2036function lti_get_service_by_resource_id($services, $resourceid) {
2037
2038 $service = false;
2039 foreach ($services as $aservice) {
2040 foreach ($aservice->get_resources() as $resource) {
2041 if ($resource->get_id() === $resourceid) {
2042 $service = $aservice;
2043 break 2;
2044 }
2045 }
2046 }
2047
2048 return $service;
2049
2050}
2051
2052/**
2053 * Extracts the named contexts from a tool proxy
2054 *
2055 * @param object $json
2056 *
2057 * @return array Contexts
2058 */
2059function lti_get_contexts($json) {
2060
2061 $contexts = array();
2062 if (isset($json->{'@context'})) {
2063 foreach ($json->{'@context'} as $context) {
2064 if (is_object($context)) {
2065 $contexts = array_merge(get_object_vars($context), $contexts);
2066 }
2067 }
2068 }
2069
2070 return $contexts;
2071
2072}
2073
2074/**
2075 * Converts an ID to a fully-qualified ID
2076 *
2077 * @param array $contexts
2078 * @param string $id
2079 *
2080 * @return string Fully-qualified ID
2081 */
2082function lti_get_fqid($contexts, $id) {
2083
2084 $parts = explode(':', $id, 2);
2085 if (count($parts) > 1) {
2086 if (array_key_exists($parts[0], $contexts)) {
2087 $id = $contexts[$parts[0]] . $parts[1];
2088 }
2089 }
2090
2091 return $id;
2092
2093}