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