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