Merge branch 'MDL-51445_m30v1' of https://github.com/sbourget/moodle into MOODLE_30_S...
[moodle.git] / mod / lti / locallib.php
blob9840dba6181cfb57a7623b850cb3c93016f1b457
1 <?php
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.
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/>.
17 // This file is part of BasicLTI4Moodle
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.
31 // BasicLTI4Moodle is copyright 2009 by Marc Alier Forment, Jordi Piguillem and Nikolas Galanis
32 // of the Universitat Politecnica de Catalunya http://www.upc.edu
33 // Contact info: Marc Alier Forment granludo @ gmail.com or marc.alier @ upc.edu.
35 /**
36 * This file contains the library of functions and constants for the lti module
38 * @package mod_lti
39 * @copyright 2009 Marc Alier, Jordi Piguillem, Nikolas Galanis
40 * marc.alier@upc.edu
41 * @copyright 2009 Universitat Politecnica de Catalunya http://www.upc.edu
42 * @author Marc Alier
43 * @author Jordi Piguillem
44 * @author Nikolas Galanis
45 * @author Chris Scribner
46 * @copyright 2015 Vital Source Technologies http://vitalsource.com
47 * @author Stephen Vickers
48 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
51 defined('MOODLE_INTERNAL') || die;
53 // TODO: Switch to core oauthlib once implemented - MDL-30149.
54 use moodle\mod\lti as lti;
56 require_once($CFG->dirroot.'/mod/lti/OAuth.php');
58 define('LTI_URL_DOMAIN_REGEX', '/(?:https?:\/\/)?(?:www\.)?([^\/]+)(?:\/|$)/i');
60 define('LTI_LAUNCH_CONTAINER_DEFAULT', 1);
61 define('LTI_LAUNCH_CONTAINER_EMBED', 2);
62 define('LTI_LAUNCH_CONTAINER_EMBED_NO_BLOCKS', 3);
63 define('LTI_LAUNCH_CONTAINER_WINDOW', 4);
64 define('LTI_LAUNCH_CONTAINER_REPLACE_MOODLE_WINDOW', 5);
66 define('LTI_TOOL_STATE_ANY', 0);
67 define('LTI_TOOL_STATE_CONFIGURED', 1);
68 define('LTI_TOOL_STATE_PENDING', 2);
69 define('LTI_TOOL_STATE_REJECTED', 3);
70 define('LTI_TOOL_PROXY_TAB', 4);
72 define('LTI_TOOL_PROXY_STATE_CONFIGURED', 1);
73 define('LTI_TOOL_PROXY_STATE_PENDING', 2);
74 define('LTI_TOOL_PROXY_STATE_ACCEPTED', 3);
75 define('LTI_TOOL_PROXY_STATE_REJECTED', 4);
77 define('LTI_SETTING_NEVER', 0);
78 define('LTI_SETTING_ALWAYS', 1);
79 define('LTI_SETTING_DELEGATE', 2);
81 /**
82 * Return the launch data required for opening the external tool.
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
88 function lti_get_launch_data($instance) {
89 global $PAGE, $CFG;
91 if (empty($instance->typeid)) {
92 $tool = lti_get_tool_by_url_match($instance->toolurl, $instance->course);
93 if ($tool) {
94 $typeid = $tool->id;
95 } else {
96 $typeid = null;
98 } else {
99 $typeid = $instance->typeid;
100 $tool = lti_get_type($typeid);
103 if ($typeid) {
104 $typeconfig = lti_get_type_config($typeid);
105 } else {
106 // There is no admin configuration for this tool. Use configuration in the lti instance record plus some defaults.
107 $typeconfig = (array)$instance;
109 $typeconfig['sendname'] = $instance->instructorchoicesendname;
110 $typeconfig['sendemailaddr'] = $instance->instructorchoicesendemailaddr;
111 $typeconfig['customparameters'] = $instance->instructorcustomparameters;
112 $typeconfig['acceptgrades'] = $instance->instructorchoiceacceptgrades;
113 $typeconfig['allowroster'] = $instance->instructorchoiceallowroster;
114 $typeconfig['forcessl'] = '0';
117 // Default the organizationid if not specified.
118 if (empty($typeconfig['organizationid'])) {
119 $urlparts = parse_url($CFG->wwwroot);
121 $typeconfig['organizationid'] = $urlparts['host'];
124 if (isset($tool->toolproxyid)) {
125 $toolproxy = lti_get_tool_proxy($tool->toolproxyid);
126 $key = $toolproxy->guid;
127 $secret = $toolproxy->secret;
128 } else {
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 = '';
137 if (!empty($instance->password)) {
138 $secret = $instance->password;
139 } else if (!empty($typeconfig['password'])) {
140 $secret = $typeconfig['password'];
141 } else {
142 $secret = '';
146 $endpoint = !empty($instance->toolurl) ? $instance->toolurl : $typeconfig['toolurl'];
147 $endpoint = trim($endpoint);
149 // If the current request is using SSL and a secure tool URL is specified, use it.
150 if (lti_request_is_using_ssl() && !empty($instance->securetoolurl)) {
151 $endpoint = trim($instance->securetoolurl);
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')) {
156 if (!empty($instance->securetoolurl)) {
157 $endpoint = trim($instance->securetoolurl);
160 $endpoint = lti_ensure_url_is_https($endpoint);
161 } else {
162 if (!strstr($endpoint, '://')) {
163 $endpoint = 'http://' . $endpoint;
167 $orgid = $typeconfig['organizationid'];
169 $course = $PAGE->course;
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);
174 } else {
175 $requestparams = $allparams;
177 $requestparams = array_merge($requestparams, lti_build_standard_request($instance, $orgid, $islti2));
178 $customstr = '';
179 if (isset($typeconfig['customparameters'])) {
180 $customstr = $typeconfig['customparameters'];
182 $requestparams = array_merge($requestparams, lti_build_custom_parameters($toolproxy, $tool, $instance, $allparams, $customstr,
183 $instance->instructorcustomparameters, $islti2));
185 $launchcontainer = lti_get_launch_container($instance, $typeconfig);
186 $returnurlparams = array('course' => $course->id,
187 'launch_container' => $launchcontainer,
188 'instanceid' => $instance->id,
189 'sesskey' => sesskey());
191 // Add the return URL. We send the launch container along to help us avoid frames-within-frames when the user returns.
192 $url = new \moodle_url('/mod/lti/return.php', $returnurlparams);
193 $returnurl = $url->out(false);
195 if (isset($typeconfig['forcessl']) && ($typeconfig['forcessl'] == '1')) {
196 $returnurl = lti_ensure_url_is_https($returnurl);
199 $target = '';
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;
212 if (!empty($target)) {
213 $requestparams['launch_presentation_document_target'] = $target;
216 $requestparams['launch_presentation_return_url'] = $returnurl;
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());
224 if (!empty($pluginparams) && is_array($pluginparams)) {
225 $requestparams = array_merge($requestparams, $pluginparams);
229 if (!empty($key) && !empty($secret)) {
230 $parms = lti_sign_parameters($requestparams, $endpoint, "POST", $key, $secret);
232 $endpointurl = new \moodle_url($endpoint);
233 $endpointparams = $endpointurl->params();
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]);
244 } else {
245 // If no key and secret, do the launch unsigned.
246 $returnurlparams['unsigned'] = '1';
247 $parms = $requestparams;
250 return array($endpoint, $parms);
254 * Launch an external tool activity.
256 * @param stdClass $instance the external tool activity settings
257 * @return string The HTML code containing the javascript code for the launch
259 function lti_launch_tool($instance) {
261 list($endpoint, $parms) = lti_get_launch_data($instance);
262 $debuglaunch = ( $instance->debuglaunch == 1 );
264 $content = lti_post_launch_html($parms, $endpoint, $debuglaunch);
266 echo $content;
270 * Prepares an LTI registration request message
272 * $param object $instance Tool Proxy instance object
274 function lti_register($toolproxy) {
275 global $PAGE, $CFG;
277 $key = $toolproxy->guid;
278 $secret = $toolproxy->secret;
279 $endpoint = $toolproxy->regurl;
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;
287 // Change the status to pending.
288 $toolproxy->state = LTI_TOOL_PROXY_STATE_PENDING;
289 lti_update_tool_proxy($toolproxy);
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');
296 // Add the return URL.
297 $returnurlparams = array('id' => $toolproxy->id, 'sesskey' => sesskey());
298 $url = new \moodle_url('/mod/lti/registrationreturn.php', $returnurlparams);
299 $returnurl = $url->out(false);
301 $requestparams['launch_presentation_return_url'] = $returnurl;
302 $content = lti_post_launch_html($requestparams, $endpoint, false);
304 echo $content;
308 * Build source ID
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
317 function lti_build_sourcedid($instanceid, $userid, $servicesalt, $typeid = null, $launchid = null) {
318 $data = new \stdClass();
320 $data->instanceid = $instanceid;
321 $data->userid = $userid;
322 $data->typeid = $typeid;
323 if (!empty($launchid)) {
324 $data->launchid = $launchid;
325 } else {
326 $data->launchid = mt_rand();
329 $json = json_encode($data);
331 $hash = hash('sha256', $json . $servicesalt, false);
333 $container = new \stdClass();
334 $container->data = $data;
335 $container->hash = $hash;
337 return $container;
341 * This function builds the request that must be sent to the tool producer
343 * @param object $instance Basic LTI instance object
344 * @param array $typeconfig Basic LTI tool configuration
345 * @param object $course Course object
346 * @param int|null $typeid Basic LTI tool ID
347 * @param boolean $islti2 True if an LTI 2 tool is being launched
349 * @return array Request details
351 function lti_build_request($instance, $typeconfig, $course, $typeid = null, $islti2 = false) {
352 global $USER, $CFG;
354 if (empty($instance->cmid)) {
355 $instance->cmid = 0;
358 $role = lti_get_ims_role($USER, $instance->cmid, $instance->course, $islti2);
360 $intro = '';
361 if (!empty($instance->cmid)) {
362 $intro = format_module_intro('lti', $instance, $instance->cmid);
363 $intro = html_to_text($intro, 0, false);
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);
369 $requestparams = array(
370 'resource_link_title' => $instance->name,
371 'resource_link_description' => $intro,
372 'user_id' => $USER->id,
373 'lis_person_sourcedid' => $USER->idnumber,
374 'roles' => $role,
375 'context_id' => $course->id,
376 'context_label' => $course->shortname,
377 'context_title' => $course->fullname,
379 if (!empty($instance->id)) {
380 $requestparams['resource_link_id'] = $instance->id;
382 if (!empty($instance->resource_link_id)) {
383 $requestparams['resource_link_id'] = $instance->resource_link_id;
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;
391 $placementsecret = $instance->servicesalt;
393 if ( !empty($instance->id) && isset($placementsecret) && ($islti2 ||
394 $typeconfig['acceptgrades'] == LTI_SETTING_ALWAYS ||
395 ($typeconfig['acceptgrades'] == LTI_SETTING_DELEGATE && $instance->instructorchoiceacceptgrades == LTI_SETTING_ALWAYS))) {
397 $sourcedid = json_encode(lti_build_sourcedid($instance->id, $USER->id, $placementsecret, $typeid));
398 $requestparams['lis_result_sourcedid'] = $sourcedid;
400 // Add outcome service URL.
401 $serviceurl = new \moodle_url('/mod/lti/service.php');
402 $serviceurl = $serviceurl->out();
404 $forcessl = false;
405 if (!empty($CFG->mod_lti_forcessl)) {
406 $forcessl = true;
409 if ((isset($typeconfig['forcessl']) && ($typeconfig['forcessl'] == '1')) or $forcessl) {
410 $serviceurl = lti_ensure_url_is_https($serviceurl);
413 $requestparams['lis_outcome_service_url'] = $serviceurl;
416 // Send user's name and email data if appropriate.
417 if ($islti2 || $typeconfig['sendname'] == LTI_SETTING_ALWAYS ||
418 ( $typeconfig['sendname'] == LTI_SETTING_DELEGATE && $instance->instructorchoicesendname == LTI_SETTING_ALWAYS ) ) {
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;
422 $requestparams['ext_user_username'] = $USER->username;
425 if ($islti2 || $typeconfig['sendemailaddr'] == LTI_SETTING_ALWAYS ||
426 ($typeconfig['sendemailaddr'] == LTI_SETTING_DELEGATE && $instance->instructorchoicesendemailaddr == LTI_SETTING_ALWAYS)) {
427 $requestparams['lis_person_contact_email_primary'] = $USER->email;
430 return $requestparams;
434 * This function builds the request that must be sent to an LTI 2 tool provider
436 * @param object $tool Basic LTI tool object
437 * @param array $params Custom launch parameters
439 * @return array Request details
441 function lti_build_request_lti2($tool, $params) {
443 $requestparams = array();
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]];
458 return $requestparams;
463 * This function builds the standard parameters for an LTI 1 or 2 request that must be sent to the tool producer
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
469 * @return array Request details
471 function lti_build_standard_request($instance, $orgid, $islti2) {
472 global $CFG;
474 $requestparams = array();
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;
481 $requestparams['launch_presentation_locale'] = current_language();
483 // Make sure we let the tool know what LMS they are being called from.
484 $requestparams['ext_lms'] = 'moodle-2';
485 $requestparams['tool_consumer_info_product_family_code'] = 'moodle';
486 $requestparams['tool_consumer_info_version'] = strval($CFG->version);
488 // Add oauth_callback to be compliant with the 1.0A spec.
489 $requestparams['oauth_callback'] = 'about:blank';
491 if (!$islti2) {
492 $requestparams['lti_version'] = 'LTI-1p0';
493 } else {
494 $requestparams['lti_version'] = 'LTI-2p0';
496 $requestparams['lti_message_type'] = 'basic-lti-launch-request';
498 if ($orgid) {
499 $requestparams["tool_consumer_instance_guid"] = $orgid;
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;
507 return $requestparams;
511 * This function builds the custom parameters
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
521 * @return array Custom parameters
523 function lti_build_custom_parameters($toolproxy, $tool, $instance, $params, $customstr, $instructorcustomstr, $islti2) {
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);
532 if (!isset($typeconfig['allowinstructorcustom']) || $typeconfig['allowinstructorcustom'] != LTI_SETTING_NEVER) {
533 if ($instructorcustomstr) {
534 $custom = array_merge(lti_split_custom_parameters($toolproxy, $tool, $params,
535 $instructorcustomstr, $islti2), $custom);
538 if ($islti2) {
539 $custom = array_merge(lti_split_custom_parameters($toolproxy, $tool, $params,
540 $tool->parameter, true), $custom);
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));
549 return $custom;
552 function lti_get_tool_table($tools, $id) {
553 global $CFG, $OUTPUT, $USER;
554 $html = '';
556 $typename = get_string('typename', 'lti');
557 $baseurl = get_string('baseurl', 'lti');
558 $action = get_string('action', 'lti');
559 $createdon = get_string('createdon', 'lti');
561 if (!empty($tools)) {
562 $html .= "
563 <div id=\"{$id}_tools_container\" style=\"margin-top:.5em;margin-bottom:.5em\">
564 <table id=\"{$id}_tools\">
565 <thead>
566 <tr>
567 <th>$typename</th>
568 <th>$baseurl</th>
569 <th>$createdon</th>
570 <th>$action</th>
571 </tr>
572 </thead>
575 foreach ($tools as $type) {
576 $date = userdate($type->timecreated, get_string('strftimedatefullshort', 'core_langconfig'));
577 $accept = get_string('accept', 'lti');
578 $update = get_string('update', 'lti');
579 $delete = get_string('delete', 'lti');
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
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
596 $ref = $type->tpname;
599 $accepthtml = $OUTPUT->action_icon($baseurl,
600 new \pix_icon('t/check', $accept, '', array('class' => 'iconsmall')), null,
601 array('title' => $accept, 'class' => 'editing_accept'));
603 $deleteaction = 'delete';
605 if ($type->state == LTI_TOOL_STATE_CONFIGURED) {
606 $accepthtml = '';
609 if ($type->state != LTI_TOOL_STATE_REJECTED) {
610 $deleteaction = 'reject';
611 $delete = get_string('reject', 'lti');
614 $updateurl = clone($baseurl);
615 $updateurl->param('action', 'update');
616 $updatehtml = $OUTPUT->action_icon($updateurl,
617 new \pix_icon('t/edit', $update, '', array('class' => 'iconsmall')), null,
618 array('title' => $update, 'class' => 'editing_update'));
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 = '';
629 $html .= "
630 <tr>
631 <td>
632 {$type->name}
633 </td>
634 <td>
635 {$ref}
636 </td>
637 <td>
638 {$date}
639 </td>
640 <td align=\"center\">
641 {$accepthtml}{$updatehtml}{$deletehtml}
642 </td>
643 </tr>
646 $html .= '</table></div>';
647 } else {
648 $html .= get_string('no_' . $id, 'lti');
651 return $html;
655 * This function builds the tab for a category of tool proxies
657 * @param object $toolproxies Tool proxy instance objects
658 * @param string $id Category ID
660 * @return string HTML for tab
662 function lti_get_tool_proxy_table($toolproxies, $id) {
663 global $OUTPUT;
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');
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>
682 EOD;
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');
689 $baseurl = new \moodle_url('/mod/lti/registersettings.php', array(
690 'action' => 'accept',
691 'id' => $toolproxy->id,
692 'sesskey' => sesskey(),
693 'tab' => $id
696 $registerurl = new \moodle_url('/mod/lti/register.php', array(
697 'id' => $toolproxy->id,
698 'sesskey' => sesskey(),
699 'tab' => 'tool_proxy'
702 $accepthtml = $OUTPUT->action_icon($registerurl,
703 new \pix_icon('t/check', $accept, '', array('class' => 'iconsmall')), null,
704 array('title' => $accept, 'class' => 'editing_accept'));
706 $deleteaction = 'delete';
708 if ($toolproxy->state != LTI_TOOL_PROXY_STATE_CONFIGURED) {
709 $accepthtml = '';
712 if (($toolproxy->state == LTI_TOOL_PROXY_STATE_CONFIGURED) || ($toolproxy->state == LTI_TOOL_PROXY_STATE_PENDING)) {
713 $delete = get_string('cancel', 'lti');
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'));
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>
742 EOD;
744 $html .= '</table></div>';
745 } else {
746 $html = get_string('no_' . $id, 'lti');
749 return $html;
753 * Extracts the enabled capabilities into an array, including those implicitly declared in a parameter
755 * @param object $tool Tool instance object
757 * @return Array of enabled capabilities
759 function lti_get_enabled_capabilities($tool) {
760 if (!empty($tool->enabledcapability)) {
761 $enabledcapabilities = explode("\n", $tool->enabledcapability);
762 } else {
763 $enabledcapabilities = array();
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;
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;
782 return $enabledcapabilities;
786 * Splits the custom parameters field to the various parameters
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
794 * @return Array of custom parameters
796 function 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;]/"?
801 $retval = array();
802 foreach ($lines as $line) {
803 $pos = strpos($line, '=');
804 if ( $pos === false || $pos < 1 ) {
805 continue;
807 $key = trim(core_text::substr($line, 0, $pos));
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;
816 return $retval;
820 * Adds the custom parameters to an array
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
827 * @return array Array of custom parameters
829 function 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;
839 return $retval;
843 * Parse a custom parameter to replace any substitution variables
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
851 * @return Parsed value of custom parameter
853 function lti_parse_custom_parameter($toolproxy, $tool, $params, $value, $islti2) {
854 global $USER, $COURSE;
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);
861 $enabledcapabilities = lti_get_enabled_capabilities($tool);
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);
871 $value = "{${$valarr[0]}->{$valarr[1]}}";
872 $value = str_replace('<br />' , ' ', $value);
873 $value = str_replace('<br>' , ' ', $value);
874 $value = format_string($value);
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;
891 return $value;
895 * Used for building the names of the different custom parameters
897 * @param string $key Parameter name
899 * @return string Processed name
901 function lti_map_keyname($key) {
902 $newkey = "";
903 $key = core_text::strtolower(trim($key));
904 foreach (str_split($key) as $ch) {
905 if ( ($ch >= 'a' && $ch <= 'z') || ($ch >= '0' && $ch <= '9') ) {
906 $newkey .= $ch;
907 } else {
908 $newkey .= '_';
911 return $newkey;
915 * Gets the IMS role string for the specified user and LTI course module.
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
922 * @return string A role string suitable for passing with an LTI launch
924 function lti_get_ims_role($user, $cmid, $courseid, $islti2) {
925 $roles = array();
927 if (empty($cmid)) {
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.
931 $coursecontext = context_course::instance($courseid);
933 if (has_capability('moodle/course:manageactivities', $coursecontext, $user)) {
934 array_push($roles, 'Instructor');
935 } else {
936 array_push($roles, 'Learner');
938 } else {
939 $context = context_module::instance($cmid);
941 if (has_capability('mod/lti:manage', $context)) {
942 array_push($roles, 'Instructor');
943 } else {
944 array_push($roles, 'Learner');
948 if (is_siteadmin($user)) {
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');
956 return join(',', $roles);
960 * Returns configuration details for the tool
962 * @param int $typeid Basic LTI tool typeid
964 * @return array Tool Configuration
966 function lti_get_type_config($typeid) {
967 global $DB;
969 $query = "SELECT name, value
970 FROM {lti_types_config}
971 WHERE typeid = :typeid1
972 UNION ALL
973 SELECT 'toolurl' AS name, " . $DB->sql_compare_text('baseurl', 1333) . " AS value
974 FROM {lti_types}
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";
985 $typeconfig = array();
986 $configs = $DB->get_records_sql($query,
987 array('typeid1' => $typeid, 'typeid2' => $typeid, 'typeid3' => $typeid, 'typeid4' => $typeid));
989 if (!empty($configs)) {
990 foreach ($configs as $config) {
991 $typeconfig[$config->name] = $config->value;
995 return $typeconfig;
998 function lti_get_tools_by_url($url, $state, $courseid = null) {
999 $domain = lti_get_domain_from_url($url);
1001 return lti_get_tools_by_domain($domain, $state, $courseid);
1004 function lti_get_tools_by_domain($domain, $state = null, $courseid = null) {
1005 global $DB, $SITE;
1007 $filters = array('tooldomain' => $domain);
1009 $statefilter = '';
1010 $coursefilter = '';
1012 if ($state) {
1013 $statefilter = 'AND state = :state';
1016 if ($courseid && $courseid != $SITE->id) {
1017 $coursefilter = 'OR course = :courseid';
1020 $query = "SELECT *
1021 FROM {lti_types}
1022 WHERE tooldomain = :tooldomain
1023 AND (course = :siteid $coursefilter)
1024 $statefilter";
1026 return $DB->get_records_sql($query, array(
1027 'courseid' => $courseid,
1028 'siteid' => $SITE->id,
1029 'tooldomain' => $domain,
1030 'state' => $state
1035 * Returns all basicLTI tools configured by the administrator
1038 function lti_filter_get_types($course) {
1039 global $DB;
1041 if (!empty($course)) {
1042 $where = "WHERE t.course = :course";
1043 $params = array('course' => $course);
1044 } else {
1045 $where = '';
1046 $params = array();
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);
1055 * Given an array of tools, filter them based on their state
1057 * @param array $tools An array of lti_types records
1058 * @param int $state One of the LTI_TOOL_STATE_* constants
1059 * @return array
1061 function 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;
1068 return $return;
1071 function lti_get_types_for_add_instance() {
1072 global $DB, $SITE, $COURSE;
1074 $query = "SELECT *
1075 FROM {lti_types}
1076 WHERE coursevisible = 1
1077 AND (course = :siteid OR course = :courseid)
1078 AND state = :active";
1080 $admintypes = $DB->get_records_sql($query,
1081 array('siteid' => $SITE->id, 'courseid' => $COURSE->id, 'active' => LTI_TOOL_STATE_CONFIGURED));
1083 $types = array();
1084 $types[0] = (object)array('name' => get_string('automatic', 'lti'), 'course' => 0, 'toolproxyid' => null);
1086 foreach ($admintypes as $type) {
1087 $types[$type->id] = $type;
1090 return $types;
1093 function lti_get_domain_from_url($url) {
1094 $matches = array();
1096 if (preg_match(LTI_URL_DOMAIN_REGEX, $url, $matches)) {
1097 return $matches[1];
1101 function lti_get_tool_by_url_match($url, $courseid = null, $state = LTI_TOOL_STATE_CONFIGURED) {
1102 $possibletools = lti_get_tools_by_url($url, $state, $courseid);
1104 return lti_get_best_tool_by_url($url, $possibletools, $courseid);
1107 function lti_get_url_thumbprint($url) {
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;
1112 $urlparts = parse_url(strtolower($url));
1113 if (!isset($urlparts['path'])) {
1114 $urlparts['path'] = '';
1117 if (!isset($urlparts['host'])) {
1118 $urlparts['host'] = '';
1121 if (substr($urlparts['host'], 0, 4) === 'www.') {
1122 $urlparts['host'] = substr($urlparts['host'], 4);
1125 return $urllower = $urlparts['host'] . '/' . $urlparts['path'];
1128 function lti_get_best_tool_by_url($url, $tools, $courseid = null) {
1129 if (count($tools) === 0) {
1130 return null;
1133 $urllower = lti_get_url_thumbprint($url);
1135 foreach ($tools as $tool) {
1136 $tool->_matchscore = 0;
1138 $toolbaseurllower = lti_get_url_thumbprint($tool->baseurl);
1140 if ($urllower === $toolbaseurllower) {
1141 // 100 points for exact thumbprint match.
1142 $tool->_matchscore += 100;
1143 } else if (substr($urllower, 0, strlen($toolbaseurllower)) === $toolbaseurllower) {
1144 // 50 points if tool thumbprint starts with the base URL thumbprint.
1145 $tool->_matchscore += 50;
1148 // Prefer course tools over site tools.
1149 if (!empty($courseid)) {
1150 // Minus 10 points for not matching the course id (global tools).
1151 if ($tool->course != $courseid) {
1152 $tool->_matchscore -= 10;
1157 $bestmatch = array_reduce($tools, function($value, $tool) {
1158 if ($tool->_matchscore > $value->_matchscore) {
1159 return $tool;
1160 } else {
1161 return $value;
1164 }, (object)array('_matchscore' => -1));
1166 // None of the tools are suitable for this URL.
1167 if ($bestmatch->_matchscore <= 0) {
1168 return null;
1171 return $bestmatch;
1174 function lti_get_shared_secrets_by_key($key) {
1175 global $DB;
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.
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'
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
1193 UNION
1194 SELECT password AS value
1195 FROM {lti}
1196 WHERE resourcekey = :key3";
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));
1201 $values = array_map(function($item) {
1202 return $item->value;
1203 }, $sharedsecrets);
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.
1207 return $values;
1211 * Delete a Basic LTI configuration
1213 * @param int $id Configuration id
1215 function lti_delete_type($id) {
1216 global $DB;
1218 // We should probably just copy the launch URL to the tool instances in this case... using a single query.
1220 $instances = $DB->get_records('lti', array('typeid' => $id));
1221 foreach ($instances as $instance) {
1222 $instance->typeid = 0;
1223 $DB->update_record('lti', $instance);
1226 $DB->delete_records('lti_types', array('id' => $id));
1227 $DB->delete_records('lti_types_config', array('typeid' => $id));
1230 function lti_set_state_for_type($id, $state) {
1231 global $DB;
1233 $DB->update_record('lti_types', array('id' => $id, 'state' => $state));
1237 * Transforms a basic LTI object to an array
1239 * @param object $ltiobject Basic LTI object
1241 * @return array Basic LTI configuration details
1243 function 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;
1253 * Generates some of the tool configuration based on the instance details
1255 * @param int $id
1257 * @return Instance configuration
1260 function lti_get_type_config_from_instance($id) {
1261 global $DB;
1263 $instance = $DB->get_record('lti', array('id' => $id));
1264 $config = lti_get_config($instance);
1266 $type = new \stdClass();
1267 $type->lti_fix = $id;
1268 if (isset($config['toolurl'])) {
1269 $type->lti_toolurl = $config['toolurl'];
1271 if (isset($config['instructorchoicesendname'])) {
1272 $type->lti_sendname = $config['instructorchoicesendname'];
1274 if (isset($config['instructorchoicesendemailaddr'])) {
1275 $type->lti_sendemailaddr = $config['instructorchoicesendemailaddr'];
1277 if (isset($config['instructorchoiceacceptgrades'])) {
1278 $type->lti_acceptgrades = $config['instructorchoiceacceptgrades'];
1280 if (isset($config['instructorchoiceallowroster'])) {
1281 $type->lti_allowroster = $config['instructorchoiceallowroster'];
1284 if (isset($config['instructorcustomparameters'])) {
1285 $type->lti_allowsetting = $config['instructorcustomparameters'];
1287 return $type;
1291 * Generates some of the tool configuration based on the admin configuration details
1293 * @param int $id
1295 * @return Configuration details
1297 function lti_get_type_type_config($id) {
1298 global $DB;
1300 $basicltitype = $DB->get_record('lti_types', array('id' => $id));
1301 $config = lti_get_type_config($id);
1303 $type = new \stdClass();
1305 $type->lti_typename = $basicltitype->name;
1307 $type->typeid = $basicltitype->id;
1309 $type->toolproxyid = $basicltitype->toolproxyid;
1311 $type->lti_toolurl = $basicltitype->baseurl;
1313 $type->lti_parameters = $basicltitype->parameter;
1315 $type->lti_icon = $basicltitype->icon;
1317 $type->lti_secureicon = $basicltitype->secureicon;
1319 if (isset($config['resourcekey'])) {
1320 $type->lti_resourcekey = $config['resourcekey'];
1322 if (isset($config['password'])) {
1323 $type->lti_password = $config['password'];
1326 if (isset($config['sendname'])) {
1327 $type->lti_sendname = $config['sendname'];
1329 if (isset($config['instructorchoicesendname'])) {
1330 $type->lti_instructorchoicesendname = $config['instructorchoicesendname'];
1332 if (isset($config['sendemailaddr'])) {
1333 $type->lti_sendemailaddr = $config['sendemailaddr'];
1335 if (isset($config['instructorchoicesendemailaddr'])) {
1336 $type->lti_instructorchoicesendemailaddr = $config['instructorchoicesendemailaddr'];
1338 if (isset($config['acceptgrades'])) {
1339 $type->lti_acceptgrades = $config['acceptgrades'];
1341 if (isset($config['instructorchoiceacceptgrades'])) {
1342 $type->lti_instructorchoiceacceptgrades = $config['instructorchoiceacceptgrades'];
1344 if (isset($config['allowroster'])) {
1345 $type->lti_allowroster = $config['allowroster'];
1347 if (isset($config['instructorchoiceallowroster'])) {
1348 $type->lti_instructorchoiceallowroster = $config['instructorchoiceallowroster'];
1351 if (isset($config['customparameters'])) {
1352 $type->lti_customparameters = $config['customparameters'];
1355 if (isset($config['forcessl'])) {
1356 $type->lti_forcessl = $config['forcessl'];
1359 if (isset($config['organizationid'])) {
1360 $type->lti_organizationid = $config['organizationid'];
1362 if (isset($config['organizationurl'])) {
1363 $type->lti_organizationurl = $config['organizationurl'];
1365 if (isset($config['organizationdescr'])) {
1366 $type->lti_organizationdescr = $config['organizationdescr'];
1368 if (isset($config['launchcontainer'])) {
1369 $type->lti_launchcontainer = $config['launchcontainer'];
1372 if (isset($config['coursevisible'])) {
1373 $type->lti_coursevisible = $config['coursevisible'];
1376 if (isset($config['debuglaunch'])) {
1377 $type->lti_debuglaunch = $config['debuglaunch'];
1380 if (isset($config['module_class_type'])) {
1381 $type->lti_module_class_type = $config['module_class_type'];
1384 return $type;
1387 function lti_prepare_type_for_save($type, $config) {
1388 if (isset($config->lti_toolurl)) {
1389 $type->baseurl = $config->lti_toolurl;
1390 $type->tooldomain = lti_get_domain_from_url($config->lti_toolurl);
1392 if (isset($config->lti_typename)) {
1393 $type->name = $config->lti_typename;
1395 $type->coursevisible = !empty($config->lti_coursevisible) ? $config->lti_coursevisible : 0;
1396 $config->lti_coursevisible = $type->coursevisible;
1398 if (isset($config->lti_icon)) {
1399 $type->icon = $config->lti_icon;
1401 if (isset($config->lti_secureicon)) {
1402 $type->secureicon = $config->lti_secureicon;
1405 if (isset($config->lti_forcessl)) {
1406 $type->forcessl = !empty($config->lti_forcessl) ? $config->lti_forcessl : 0;
1407 $config->lti_forcessl = $type->forcessl;
1410 $type->timemodified = time();
1412 unset ($config->lti_typename);
1413 unset ($config->lti_toolurl);
1414 unset ($config->lti_icon);
1415 unset ($config->lti_secureicon);
1418 function lti_update_type($type, $config) {
1419 global $DB, $CFG;
1421 lti_prepare_type_for_save($type, $config);
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));
1429 unset($config->oldicon);
1431 if ($DB->update_record('lti_types', $type)) {
1432 foreach ($config as $key => $value) {
1433 if (substr($key, 0, 4) == 'lti_' && !is_null($value)) {
1434 $record = new \StdClass();
1435 $record->typeid = $type->id;
1436 $record->name = substr($key, 4);
1437 $record->value = $value;
1438 lti_update_config($record);
1441 require_once($CFG->libdir.'/modinfolib.php');
1442 if ($clearcache) {
1443 rebuild_course_cache();
1448 function lti_add_type($type, $config) {
1449 global $USER, $SITE, $DB;
1451 lti_prepare_type_for_save($type, $config);
1453 if (!isset($type->state)) {
1454 $type->state = LTI_TOOL_STATE_PENDING;
1457 if (!isset($type->timecreated)) {
1458 $type->timecreated = time();
1461 if (!isset($type->createdby)) {
1462 $type->createdby = $USER->id;
1465 if (!isset($type->course)) {
1466 $type->course = $SITE->id;
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.
1472 $config->lti_servicesalt = uniqid('', true);
1474 $id = $DB->insert_record('lti_types', $type);
1476 if ($id) {
1477 foreach ($config as $key => $value) {
1478 if (substr($key, 0, 4) == 'lti_' && !is_null($value)) {
1479 $record = new \StdClass();
1480 $record->typeid = $id;
1481 $record->name = substr($key, 4);
1482 $record->value = $value;
1484 lti_add_config($record);
1489 return $id;
1493 * Given an array of tool proxies, filter them based on their state
1495 * @param array $toolproxies An array of lti_tool_proxies records
1496 * @param int $state One of the LTI_TOOL_PROXY_STATE_* constants
1498 * @return array
1500 function 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;
1507 return $return;
1511 * Get the tool proxy instance given its GUID
1513 * @param string $toolproxyguid Tool proxy GUID value
1515 * @return object
1517 function lti_get_tool_proxy_from_guid($toolproxyguid) {
1518 global $DB;
1520 $toolproxy = $DB->get_record('lti_tool_proxies', array('guid' => $toolproxyguid));
1522 return $toolproxy;
1526 * Generates some of the tool proxy configuration based on the admin configuration details
1528 * @param int $id
1530 * @return Tool Proxy details
1532 function lti_get_tool_proxy($id) {
1533 global $DB;
1535 $toolproxy = $DB->get_record('lti_tool_proxies', array('id' => $id));
1536 return $toolproxy;
1540 * Generates some of the tool proxy configuration based on the admin configuration details
1542 * @param int $id
1544 * @return Tool Proxy details
1546 function lti_get_tool_proxy_config($id) {
1547 $toolproxy = lti_get_tool_proxy($id);
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);
1557 return $tp;
1561 * Update the database with a tool proxy instance
1563 * @param object $config Tool proxy definition
1565 * @return int Record id number
1567 function lti_add_tool_proxy($config) {
1568 global $USER, $DB;
1570 $toolproxy = new \stdClass();
1571 if (isset($config->lti_registrationname)) {
1572 $toolproxy->name = trim($config->lti_registrationname);
1574 if (isset($config->lti_registrationurl)) {
1575 $toolproxy->regurl = trim($config->lti_registrationurl);
1577 if (isset($config->lti_capabilities)) {
1578 $toolproxy->capabilityoffered = implode("\n", $config->lti_capabilities);
1580 if (isset($config->lti_services)) {
1581 $toolproxy->serviceoffered = implode("\n", $config->lti_services);
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();
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;
1598 $toolproxy->guid = random_string();
1599 $toolproxy->secret = random_string();
1600 $id = $DB->insert_record('lti_tool_proxies', $toolproxy);
1603 return $id;
1607 * Updates a tool proxy in the database
1609 * @param object $toolproxy Tool proxy
1611 * @return int Record id number
1613 function lti_update_tool_proxy($toolproxy) {
1614 global $DB;
1616 $toolproxy->timemodified = time();
1617 $id = $DB->update_record('lti_tool_proxies', $toolproxy);
1619 return $id;
1623 * Delete a Tool Proxy
1625 * @param int $id Tool Proxy id
1627 function 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);
1634 $DB->delete_records('lti_tool_proxies', array('id' => $id));
1638 * Add a tool configuration in the database
1640 * @param object $config Tool configuration
1642 * @return int Record id number
1644 function lti_add_config($config) {
1645 global $DB;
1647 return $DB->insert_record('lti_types_config', $config);
1651 * Updates a tool configuration in the database
1653 * @param object $config Tool configuration
1655 * @return Record id number
1657 function lti_update_config($config) {
1658 global $DB;
1660 $return = true;
1661 $old = $DB->get_record('lti_types_config', array('typeid' => $config->typeid, 'name' => $config->name));
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);
1669 return $return;
1673 * Gets the tool settings
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)
1679 * @return array Array settings
1681 function lti_get_tool_settings($toolproxyid, $courseid = null, $instanceid = null) {
1682 global $DB;
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);
1690 return $settings;
1694 * Sets the tool settings (
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)
1701 function lti_set_tool_settings($settings, $toolproxyid, $courseid = null, $instanceid = null) {
1702 global $DB;
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);
1722 * Signs the petition to launch the external tool using OAuth
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
1730 function lti_sign_parameters($oldparms, $endpoint, $method, $oauthconsumerkey, $oauthconsumersecret) {
1732 $parms = $oldparms;
1734 $testtoken = '';
1736 // TODO: Switch to core oauthlib once implemented - MDL-30149.
1737 $hmacmethod = new lti\OAuthSignatureMethod_HMAC_SHA1();
1738 $testconsumer = new lti\OAuthConsumer($oauthconsumerkey, $oauthconsumersecret, null);
1739 $accreq = lti\OAuthRequest::from_consumer_and_token($testconsumer, $testtoken, $method, $endpoint, $parms);
1740 $accreq->sign_request($hmacmethod, $testconsumer, $testtoken);
1742 $newparms = $accreq->get_parameters();
1744 return $newparms;
1748 * Posts the launch petition HTML
1750 * @param $newparms Signed parameters
1751 * @param $endpoint URL of the external tool
1752 * @param $debug Debug (true/false)
1754 function lti_post_launch_html($newparms, $endpoint, $debug=false) {
1755 $r = "<form action=\"" . $endpoint .
1756 "\" name=\"ltiLaunchForm\" id=\"ltiLaunchForm\" method=\"post\" encType=\"application/x-www-form-urlencoded\">\n";
1758 // Contruct html for the launch parameters.
1759 foreach ($newparms as $key => $value) {
1760 $key = htmlspecialchars($key);
1761 $value = htmlspecialchars($value);
1762 if ( $key == "ext_submit" ) {
1763 $r .= "<input type=\"submit\"";
1764 } else {
1765 $r .= "<input type=\"hidden\" name=\"{$key}\"";
1767 $r .= " value=\"";
1768 $r .= $value;
1769 $r .= "\"/>\n";
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";
1777 $r .= " if (ele.style.display == \"block\") {\n";
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";
1789 $r .= "<b>".get_string("basiclti_endpoint", "lti")."</b><br/>\n";
1790 $r .= $endpoint . "<br/>\n&nbsp;<br/>\n";
1791 $r .= "<b>".get_string("basiclti_parameters", "lti")."</b><br/>\n";
1792 foreach ($newparms as $key => $value) {
1793 $key = htmlspecialchars($key);
1794 $value = htmlspecialchars($value);
1795 $r .= "$key = $value<br/>\n";
1797 $r .= "&nbsp;<br/>\n";
1798 $r .= "</div>\n";
1800 $r .= "</form>\n";
1802 if ( ! $debug ) {
1803 $r .= " <script type=\"text/javascript\"> \n" .
1804 " //<![CDATA[ \n" .
1805 " document.ltiLaunchForm.submit(); \n" .
1806 " //]]> \n" .
1807 " </script> \n";
1809 return $r;
1812 function lti_get_type($typeid) {
1813 global $DB;
1815 return $DB->get_record('lti_types', array('id' => $typeid));
1818 function lti_get_launch_container($lti, $toolconfig) {
1819 if (empty($lti->launchcontainer)) {
1820 $lti->launchcontainer = LTI_LAUNCH_CONTAINER_DEFAULT;
1823 if ($lti->launchcontainer == LTI_LAUNCH_CONTAINER_DEFAULT) {
1824 if (isset($toolconfig['launchcontainer'])) {
1825 $launchcontainer = $toolconfig['launchcontainer'];
1827 } else {
1828 $launchcontainer = $lti->launchcontainer;
1831 if (empty($launchcontainer) || $launchcontainer == LTI_LAUNCH_CONTAINER_DEFAULT) {
1832 $launchcontainer = LTI_LAUNCH_CONTAINER_EMBED_NO_BLOCKS;
1835 $devicetype = core_useragent::get_device_type();
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.
1840 if ($devicetype === core_useragent::DEVICETYPE_MOBILE || $devicetype === core_useragent::DEVICETYPE_TABLET ) {
1841 $launchcontainer = LTI_LAUNCH_CONTAINER_REPLACE_MOODLE_WINDOW;
1844 return $launchcontainer;
1847 function lti_request_is_using_ssl() {
1848 global $CFG;
1849 return (stripos($CFG->httpswwwroot, 'https://') === 0);
1852 function lti_ensure_url_is_https($url) {
1853 if (!strstr($url, '://')) {
1854 $url = 'https://' . $url;
1855 } else {
1856 // If the URL starts with http, replace with https.
1857 if (stripos($url, 'http://') === 0) {
1858 $url = 'https://' . substr($url, 7);
1862 return $url;
1866 * Determines if we should try to log the request
1868 * @param string $rawbody
1869 * @return bool
1871 function lti_should_log_request($rawbody) {
1872 global $CFG;
1874 if (empty($CFG->mod_lti_log_users)) {
1875 return false;
1878 $logusers = explode(',', $CFG->mod_lti_log_users);
1879 if (empty($logusers)) {
1880 return false;
1883 try {
1884 $xml = new \SimpleXMLElement($rawbody);
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);
1897 } catch (Exception $e) {
1898 return false;
1901 if (empty($requestuserid) or !in_array($requestuserid, $logusers)) {
1902 return false;
1905 return true;
1909 * Logs the request to a file in temp dir
1911 * @param string $rawbody
1913 function lti_log_request($rawbody) {
1914 if ($tempdir = make_temp_directory('mod_lti', false)) {
1915 if ($tempfile = tempnam($tempdir, 'mod_lti_request'.date('YmdHis'))) {
1916 file_put_contents($tempfile, $rawbody);
1917 chmod($tempfile, 0644);
1923 * Fetches LTI type configuration for an LTI instance
1925 * @param stdClass $instance
1926 * @return array Can be empty if no type is found
1928 function lti_get_type_config_by_instance($instance) {
1929 $typeid = null;
1930 if (empty($instance->typeid)) {
1931 $tool = lti_get_tool_by_url_match($instance->toolurl, $instance->course);
1932 if ($tool) {
1933 $typeid = $tool->id;
1935 } else {
1936 $typeid = $instance->typeid;
1938 if (!empty($typeid)) {
1939 return lti_get_type_config($typeid);
1941 return array();
1945 * Enforce type config settings onto the LTI instance
1947 * @param stdClass $instance
1948 * @param array $typeconfig
1950 function lti_force_type_config_settings($instance, array $typeconfig) {
1951 $forced = array(
1952 'instructorchoicesendname' => 'sendname',
1953 'instructorchoicesendemailaddr' => 'sendemailaddr',
1954 'instructorchoiceacceptgrades' => 'acceptgrades',
1957 foreach ($forced as $instanceparam => $typeconfigparam) {
1958 if (array_key_exists($typeconfigparam, $typeconfig) && $typeconfig[$typeconfigparam] != LTI_SETTING_DELEGATE) {
1959 $instance->$instanceparam = $typeconfig[$typeconfigparam];
1965 * Initializes an array with the capabilities supported by the LTI module
1967 * @return array List of capability names (without a dollar sign prefix)
1969 function lti_get_capabilities() {
1971 $capabilities = array(
1972 'basic-lti-launch-request' => '',
1973 'Context.id' => 'context_id',
1974 'CourseSection.title' => 'context_title',
1975 'CourseSection.label' => 'context_label',
1976 'CourseSection.sourcedId' => 'lis_course_section_sourcedid',
1977 'CourseSection.longDescription' => '$COURSE->summary',
1978 'CourseSection.timeFrame.begin' => '$COURSE->startdate',
1979 'ResourceLink.id' => 'resource_link_id',
1980 'ResourceLink.title' => 'resource_link_title',
1981 'ResourceLink.description' => 'resource_link_description',
1982 'User.id' => 'user_id',
1983 'User.username' => '$USER->username',
1984 'Person.name.full' => 'lis_person_name_full',
1985 'Person.name.given' => 'lis_person_name_given',
1986 'Person.name.family' => 'lis_person_name_family',
1987 'Person.email.primary' => 'lis_person_contact_email_primary',
1988 'Person.sourcedId' => 'lis_person_sourcedid',
1989 'Person.name.middle' => '$USER->middlename',
1990 'Person.address.street1' => '$USER->address',
1991 'Person.address.locality' => '$USER->city',
1992 'Person.address.country' => '$USER->country',
1993 'Person.address.timezone' => '$USER->timezone',
1994 'Person.phone.primary' => '$USER->phone1',
1995 'Person.phone.mobile' => '$USER->phone2',
1996 'Person.webaddress' => '$USER->url',
1997 'Membership.role' => 'roles',
1998 'Result.sourcedId' => 'lis_result_sourcedid',
1999 'Result.autocreate' => 'lis_outcome_service_url');
2001 return $capabilities;
2006 * Initializes an array with the services supported by the LTI module
2008 * @return array List of services
2010 function lti_get_services() {
2012 $services = array();
2013 $definedservices = core_component::get_plugin_list('ltiservice');
2014 foreach ($definedservices as $name => $location) {
2015 $classname = "\\ltiservice_{$name}\\local\\service\\{$name}";
2016 $services[] = new $classname();
2019 return $services;
2024 * Initializes an instance of the named service
2026 * @param string $servicename Name of service
2028 * @return mod_lti\local\ltiservice\service_base Service
2030 function lti_get_service_by_name($servicename) {
2032 $service = false;
2033 $classname = "\\ltiservice_{$servicename}\\local\\service\\{$servicename}";
2034 if (class_exists($classname)) {
2035 $service = new $classname();
2038 return $service;
2043 * Finds a service by id
2045 * @param array $services Array of services
2046 * @param string $resourceid ID of resource
2048 * @return mod_lti\local\ltiservice\service_base Service
2050 function lti_get_service_by_resource_id($services, $resourceid) {
2052 $service = false;
2053 foreach ($services as $aservice) {
2054 foreach ($aservice->get_resources() as $resource) {
2055 if ($resource->get_id() === $resourceid) {
2056 $service = $aservice;
2057 break 2;
2062 return $service;
2067 * Extracts the named contexts from a tool proxy
2069 * @param object $json
2071 * @return array Contexts
2073 function lti_get_contexts($json) {
2075 $contexts = array();
2076 if (isset($json->{'@context'})) {
2077 foreach ($json->{'@context'} as $context) {
2078 if (is_object($context)) {
2079 $contexts = array_merge(get_object_vars($context), $contexts);
2084 return $contexts;
2089 * Converts an ID to a fully-qualified ID
2091 * @param array $contexts
2092 * @param string $id
2094 * @return string Fully-qualified ID
2096 function lti_get_fqid($contexts, $id) {
2098 $parts = explode(':', $id, 2);
2099 if (count($parts) > 1) {
2100 if (array_key_exists($parts[0], $contexts)) {
2101 $id = $contexts[$parts[0]] . $parts[1];
2105 return $id;