2 // This file is part of Moodle - http://moodle.org/
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.
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.
36 * This file contains the library of functions and constants for the lti module
39 * @copyright 2009 Marc Alier, Jordi Piguillem, Nikolas Galanis
41 * @copyright 2009 Universitat Politecnica de Catalunya http://www.upc.edu
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);
82 * Prints a Basic LTI activity
84 * $param int $basicltiid Basic LTI activity id
86 function lti_view($instance) {
89 if (empty($instance->typeid)) {
90 $tool = lti_get_tool_by_url_match($instance->toolurl, $instance->course);
97 $typeid = $instance->typeid;
98 $tool = lti_get_type($typeid);
102 $typeconfig = lti_get_type_config($typeid);
104 // There is no admin configuration for this tool. Use configuration in the lti instance record plus some defaults.
105 $typeconfig = (array)$instance;
107 $typeconfig['sendname'] = $instance->instructorchoicesendname;
108 $typeconfig['sendemailaddr'] = $instance->instructorchoicesendemailaddr;
109 $typeconfig['customparameters'] = $instance->instructorcustomparameters;
110 $typeconfig['acceptgrades'] = $instance->instructorchoiceacceptgrades;
111 $typeconfig['allowroster'] = $instance->instructorchoiceallowroster;
112 $typeconfig['forcessl'] = '0';
115 // Default the organizationid if not specified.
116 if (empty($typeconfig['organizationid'])) {
117 $urlparts = parse_url($CFG->wwwroot);
119 $typeconfig['organizationid'] = $urlparts['host'];
122 if (isset($tool->toolproxyid)) {
123 $toolproxy = lti_get_tool_proxy($tool->toolproxyid);
124 $key = $toolproxy->guid;
125 $secret = $toolproxy->secret;
128 if (!empty($instance->resourcekey)) {
129 $key = $instance->resourcekey;
130 } else if (!empty($typeconfig['resourcekey'])) {
131 $key = $typeconfig['resourcekey'];
135 if (!empty($instance->password)) {
136 $secret = $instance->password;
137 } else if (!empty($typeconfig['password'])) {
138 $secret = $typeconfig['password'];
144 $endpoint = !empty($instance->toolurl) ? $instance->toolurl : $typeconfig['toolurl'];
145 $endpoint = trim($endpoint);
147 // If the current request is using SSL and a secure tool URL is specified, use it.
148 if (lti_request_is_using_ssl() && !empty($instance->securetoolurl)) {
149 $endpoint = trim($instance->securetoolurl);
152 // If SSL is forced, use the secure tool url if specified. Otherwise, make sure https is on the normal launch URL.
153 if (isset($typeconfig['forcessl']) && ($typeconfig['forcessl'] == '1')) {
154 if (!empty($instance->securetoolurl)) {
155 $endpoint = trim($instance->securetoolurl);
158 $endpoint = lti_ensure_url_is_https($endpoint);
160 if (!strstr($endpoint, '://')) {
161 $endpoint = 'http://' . $endpoint;
165 $orgid = $typeconfig['organizationid'];
167 $course = $PAGE->course;
168 $islti2 = isset($tool->toolproxyid);
169 $allparams = lti_build_request($instance, $typeconfig, $course, $typeid, $islti2);
171 $requestparams = lti_build_request_lti2($tool, $allparams);
173 $requestparams = $allparams;
175 $requestparams = array_merge($requestparams, lti_build_standard_request($instance, $orgid, $islti2));
177 if (isset($typeconfig['customparameters'])) {
178 $customstr = $typeconfig['customparameters'];
180 $requestparams = array_merge($requestparams, lti_build_custom_parameters($toolproxy, $tool, $instance, $allparams, $customstr,
181 $instance->instructorcustomparameters, $islti2));
183 $launchcontainer = lti_get_launch_container($instance, $typeconfig);
184 $returnurlparams = array('course' => $course->id,
185 'launch_container' => $launchcontainer,
186 'instanceid' => $instance->id,
187 'sesskey' => sesskey());
189 // Add the return URL. We send the launch container along to help us avoid frames-within-frames when the user returns.
190 $url = new \moodle_url('/mod/lti/return.php', $returnurlparams);
191 $returnurl = $url->out(false);
193 if (isset($typeconfig['forcessl']) && ($typeconfig['forcessl'] == '1')) {
194 $returnurl = lti_ensure_url_is_https($returnurl);
198 switch($launchcontainer) {
199 case LTI_LAUNCH_CONTAINER_EMBED:
200 case LTI_LAUNCH_CONTAINER_EMBED_NO_BLOCKS:
203 case LTI_LAUNCH_CONTAINER_REPLACE_MOODLE_WINDOW:
206 case LTI_LAUNCH_CONTAINER_WINDOW:
210 if (!empty($target)) {
211 $requestparams['launch_presentation_document_target'] = $target;
214 $requestparams['launch_presentation_return_url'] = $returnurl;
216 // Allow request params to be updated by sub-plugins.
217 $plugins = core_component::get_plugin_list('ltisource');
218 foreach (array_keys($plugins) as $plugin) {
219 $pluginparams = component_callback('ltisource_'.$plugin, 'before_launch',
220 array($instance, $endpoint, $requestparams), array());
222 if (!empty($pluginparams) && is_array($pluginparams)) {
223 $requestparams = array_merge($requestparams, $pluginparams);
227 if (!empty($key) && !empty($secret)) {
228 $parms = lti_sign_parameters($requestparams, $endpoint, "POST", $key, $secret);
230 $endpointurl = new \moodle_url($endpoint);
231 $endpointparams = $endpointurl->params();
233 // Strip querystring params in endpoint url from $parms to avoid duplication.
234 if (!empty($endpointparams) && !empty($parms)) {
235 foreach (array_keys($endpointparams) as $paramname) {
236 if (isset($parms[$paramname])) {
237 unset($parms[$paramname]);
243 // If no key and secret, do the launch unsigned.
244 $returnurlparams['unsigned'] = '1';
245 $parms = $requestparams;
248 $debuglaunch = ( $instance->debuglaunch == 1 );
250 $content = lti_post_launch_html($parms, $endpoint, $debuglaunch);
256 * Prepares an LTI registration request message
258 * $param object $instance Tool Proxy instance object
260 function lti_register($toolproxy) {
263 $key = $toolproxy->guid;
264 $secret = $toolproxy->secret;
265 $endpoint = $toolproxy->regurl;
267 $requestparams = array();
268 $requestparams['lti_message_type'] = 'ToolProxyRegistrationRequest';
269 $requestparams['lti_version'] = 'LTI-2p0';
270 $requestparams['reg_key'] = $key;
271 $requestparams['reg_password'] = $secret;
273 // Change the status to pending.
274 $toolproxy->state = LTI_TOOL_PROXY_STATE_PENDING;
275 lti_update_tool_proxy($toolproxy);
277 // Add the profile URL.
278 $profileservice = lti_get_service_by_name('profile');
279 $profileservice->set_tool_proxy($toolproxy);
280 $requestparams['tc_profile_url'] = $profileservice->parse_value('$ToolConsumerProfile.url');
282 // Add the return URL.
283 $returnurlparams = array('id' => $toolproxy->id, 'sesskey' => sesskey());
284 $url = new \moodle_url('/mod/lti/registrationreturn.php', $returnurlparams);
285 $returnurl = $url->out(false);
287 $requestparams['launch_presentation_return_url'] = $returnurl;
288 $content = lti_post_launch_html($requestparams, $endpoint, false);
296 * @param int $instanceid
298 * @param string $servicesalt
299 * @param null|int $typeid
300 * @param null|int $launchid
303 function lti_build_sourcedid($instanceid, $userid, $servicesalt, $typeid = null, $launchid = null) {
304 $data = new \stdClass();
306 $data->instanceid = $instanceid;
307 $data->userid = $userid;
308 $data->typeid = $typeid;
309 if (!empty($launchid)) {
310 $data->launchid = $launchid;
312 $data->launchid = mt_rand();
315 $json = json_encode($data);
317 $hash = hash('sha256', $json . $servicesalt, false);
319 $container = new \stdClass();
320 $container->data = $data;
321 $container->hash = $hash;
327 * This function builds the request that must be sent to the tool producer
329 * @param object $instance Basic LTI instance object
330 * @param array $typeconfig Basic LTI tool configuration
331 * @param object $course Course object
332 * @param int|null $typeid Basic LTI tool ID
333 * @param boolean $islti2 True if an LTI 2 tool is being launched
335 * @return array Request details
337 function lti_build_request($instance, $typeconfig, $course, $typeid = null, $islti2 = false) {
340 if (empty($instance->cmid)) {
344 $role = lti_get_ims_role($USER, $instance->cmid, $instance->course, $islti2);
347 if (!empty($instance->cmid)) {
348 $intro = format_module_intro('lti', $instance, $instance->cmid);
349 $intro = html_to_text($intro, 0, false);
351 // This may look weird, but this is required for new lines
352 // so we generate the same OAuth signature as the tool provider.
353 $intro = str_replace("\n", "\r\n", $intro);
355 $requestparams = array(
356 'resource_link_title' => $instance->name,
357 'resource_link_description' => $intro,
358 'user_id' => $USER->id,
359 'lis_person_sourcedid' => $USER->idnumber,
361 'context_id' => $course->id,
362 'context_label' => $course->shortname,
363 'context_title' => $course->fullname,
365 if (!empty($instance->id)) {
366 $requestparams['resource_link_id'] = $instance->id;
368 if (!empty($instance->resource_link_id)) {
369 $requestparams['resource_link_id'] = $instance->resource_link_id;
371 if ($course->format == 'site') {
372 $requestparams['context_type'] = 'Group';
374 $requestparams['context_type'] = 'CourseSection';
375 $requestparams['lis_course_section_sourcedid'] = $course->idnumber;
377 $placementsecret = $instance->servicesalt;
379 if ( !empty($instance->id) && isset($placementsecret) && ($islti2 ||
380 $typeconfig['acceptgrades'] == LTI_SETTING_ALWAYS ||
381 ($typeconfig['acceptgrades'] == LTI_SETTING_DELEGATE && $instance->instructorchoiceacceptgrades == LTI_SETTING_ALWAYS))) {
383 $sourcedid = json_encode(lti_build_sourcedid($instance->id, $USER->id, $placementsecret, $typeid));
384 $requestparams['lis_result_sourcedid'] = $sourcedid;
386 // Add outcome service URL.
387 $serviceurl = new \moodle_url('/mod/lti/service.php');
388 $serviceurl = $serviceurl->out();
391 if (!empty($CFG->mod_lti_forcessl)) {
395 if ((isset($typeconfig['forcessl']) && ($typeconfig['forcessl'] == '1')) or $forcessl) {
396 $serviceurl = lti_ensure_url_is_https($serviceurl);
399 $requestparams['lis_outcome_service_url'] = $serviceurl;
402 // Send user's name and email data if appropriate.
403 if ($islti2 || $typeconfig['sendname'] == LTI_SETTING_ALWAYS ||
404 ( $typeconfig['sendname'] == LTI_SETTING_DELEGATE && $instance->instructorchoicesendname == LTI_SETTING_ALWAYS ) ) {
405 $requestparams['lis_person_name_given'] = $USER->firstname;
406 $requestparams['lis_person_name_family'] = $USER->lastname;
407 $requestparams['lis_person_name_full'] = $USER->firstname . ' ' . $USER->lastname;
408 $requestparams['ext_user_username'] = $USER->username;
411 if ($islti2 || $typeconfig['sendemailaddr'] == LTI_SETTING_ALWAYS ||
412 ($typeconfig['sendemailaddr'] == LTI_SETTING_DELEGATE && $instance->instructorchoicesendemailaddr == LTI_SETTING_ALWAYS)) {
413 $requestparams['lis_person_contact_email_primary'] = $USER->email;
416 return $requestparams;
420 * This function builds the request that must be sent to an LTI 2 tool provider
422 * @param object $tool Basic LTI tool object
423 * @param array $params Custom launch parameters
425 * @return array Request details
427 function lti_build_request_lti2($tool, $params) {
429 $requestparams = array();
431 $capabilities = lti_get_capabilities();
432 $enabledcapabilities = explode("\n", $tool->enabledcapability);
433 foreach ($enabledcapabilities as $capability) {
434 if (array_key_exists($capability, $capabilities)) {
435 $val = $capabilities[$capability];
436 if ($val && (substr($val, 0, 1) != '$')) {
437 if (isset($params[$val])) {
438 $requestparams[$capabilities[$capability]] = $params[$capabilities[$capability]];
444 return $requestparams;
449 * This function builds the standard parameters for an LTI 1 or 2 request that must be sent to the tool producer
451 * @param object $instance Basic LTI instance object
452 * @param string $orgid Organisation ID
453 * @param boolean $islti2 True if an LTI 2 tool is being launched
455 * @return array Request details
457 function lti_build_standard_request($instance, $orgid, $islti2) {
460 $requestparams = array();
462 $requestparams['resource_link_id'] = $instance->id;
463 if (property_exists($instance, 'resource_link_id') and !empty($instance->resource_link_id)) {
464 $requestparams['resource_link_id'] = $instance->resource_link_id;
467 $requestparams['launch_presentation_locale'] = current_language();
469 // Make sure we let the tool know what LMS they are being called from.
470 $requestparams['ext_lms'] = 'moodle-2';
471 $requestparams['tool_consumer_info_product_family_code'] = 'moodle';
472 $requestparams['tool_consumer_info_version'] = strval($CFG->version);
474 // Add oauth_callback to be compliant with the 1.0A spec.
475 $requestparams['oauth_callback'] = 'about:blank';
478 $requestparams['lti_version'] = 'LTI-1p0';
480 $requestparams['lti_version'] = 'LTI-2p0';
482 $requestparams['lti_message_type'] = 'basic-lti-launch-request';
485 $requestparams["tool_consumer_instance_guid"] = $orgid;
487 if (!empty($CFG->mod_lti_institution_name)) {
488 $requestparams['tool_consumer_instance_name'] = $CFG->mod_lti_institution_name;
490 $requestparams['tool_consumer_instance_name'] = get_site()->fullname;
493 return $requestparams;
497 * This function builds the custom parameters
499 * @param object $toolproxy Tool proxy instance object
500 * @param object $tool Tool instance object
501 * @param object $instance Tool placement instance object
502 * @param array $params LTI launch parameters
503 * @param string $customstr Custom parameters defined for tool
504 * @param string $instructorcustomstr Custom parameters defined for this placement
505 * @param boolean $islti2 True if an LTI 2 tool is being launched
507 * @return array Custom parameters
509 function lti_build_custom_parameters($toolproxy, $tool, $instance, $params, $customstr, $instructorcustomstr, $islti2) {
511 // Concatenate the custom parameters from the administrator and the instructor
512 // Instructor parameters are only taken into consideration if the administrator
513 // has given permission.
516 $custom = lti_split_custom_parameters($toolproxy, $tool, $params, $customstr, $islti2);
518 if (!isset($typeconfig['allowinstructorcustom']) || $typeconfig['allowinstructorcustom'] != LTI_SETTING_NEVER) {
519 if ($instructorcustomstr) {
520 $custom = array_merge(lti_split_custom_parameters($toolproxy, $tool, $params,
521 $instructorcustomstr, $islti2), $custom);
525 $custom = array_merge(lti_split_custom_parameters($toolproxy, $tool, $params,
526 $tool->parameter, true), $custom);
527 $settings = lti_get_tool_settings($tool->toolproxyid);
528 $custom = array_merge($custom, lti_get_custom_parameters($toolproxy, $tool, $params, $settings));
529 $settings = lti_get_tool_settings($tool->toolproxyid, $instance->course);
530 $custom = array_merge($custom, lti_get_custom_parameters($toolproxy, $tool, $params, $settings));
531 $settings = lti_get_tool_settings($tool->toolproxyid, $instance->course, $instance->id);
532 $custom = array_merge($custom, lti_get_custom_parameters($toolproxy, $tool, $params, $settings));
538 function lti_get_tool_table($tools, $id) {
539 global $CFG, $OUTPUT, $USER;
542 $typename = get_string('typename', 'lti');
543 $baseurl = get_string('baseurl', 'lti');
544 $action = get_string('action', 'lti');
545 $createdon = get_string('createdon', 'lti');
547 if (!empty($tools)) {
549 <div id=\"{$id}_tools_container\" style=\"margin-top:.5em;margin-bottom:.5em\">
550 <table id=\"{$id}_tools\">
561 foreach ($tools as $type) {
562 $date = userdate($type->timecreated, get_string('strftimedatefullshort', 'core_langconfig'));
563 $accept = get_string('accept', 'lti');
564 $update = get_string('update', 'lti');
565 $delete = get_string('delete', 'lti');
567 if (empty($type->toolproxyid)) {
568 $baseurl = new \moodle_url('/mod/lti/typessettings.php', array(
569 'action' => 'accept',
571 'sesskey' => sesskey(),
574 $ref = $type->baseurl;
576 $baseurl = new \moodle_url('/mod/lti/toolssettings.php', array(
577 'action' => 'accept',
579 'sesskey' => sesskey(),
582 $ref = $type->tpname;
585 $accepthtml = $OUTPUT->action_icon($baseurl,
586 new \pix_icon('t/check', $accept, '', array('class' => 'iconsmall')), null,
587 array('title' => $accept, 'class' => 'editing_accept'));
589 $deleteaction = 'delete';
591 if ($type->state == LTI_TOOL_STATE_CONFIGURED) {
595 if ($type->state != LTI_TOOL_STATE_REJECTED) {
596 $deleteaction = 'reject';
597 $delete = get_string('reject', 'lti');
600 $updateurl = clone($baseurl);
601 $updateurl->param('action', 'update');
602 $updatehtml = $OUTPUT->action_icon($updateurl,
603 new \pix_icon('t/edit', $update, '', array('class' => 'iconsmall')), null,
604 array('title' => $update, 'class' => 'editing_update'));
606 if (($type->state != LTI_TOOL_STATE_REJECTED) || empty($type->toolproxyid)) {
607 $deleteurl = clone($baseurl);
608 $deleteurl->param('action', $deleteaction);
609 $deletehtml = $OUTPUT->action_icon($deleteurl,
610 new \pix_icon('t/delete', $delete, '', array('class' => 'iconsmall')), null,
611 array('title' => $delete, 'class' => 'editing_delete'));
626 <td align=\"center\">
627 {$accepthtml}{$updatehtml}{$deletehtml}
632 $html .= '</table></div>';
634 $html .= get_string('no_' . $id, 'lti');
641 * This function builds the tab for a category of tool proxies
643 * @param object $toolproxies Tool proxy instance objects
644 * @param string $id Category ID
646 * @return string HTML for tab
648 function lti_get_tool_proxy_table($toolproxies, $id) {
651 if (!empty($toolproxies)) {
652 $typename = get_string('typename', 'lti');
653 $url = get_string('registrationurl', 'lti');
654 $action = get_string('action', 'lti');
655 $createdon = get_string('createdon', 'lti');
658 <div id="{$id}_tool_proxies_container" style="margin-top: 0.5em; margin-bottom: 0.5em">
659 <table id="{$id}_tool_proxies">
664 <th>{$createdon}</th>
669 foreach ($toolproxies as $toolproxy) {
670 $date = userdate($toolproxy->timecreated, get_string('strftimedatefullshort', 'core_langconfig'));
671 $accept = get_string('register', 'lti');
672 $update = get_string('update', 'lti');
673 $delete = get_string('delete', 'lti');
675 $baseurl = new \moodle_url('/mod/lti/registersettings.php', array(
676 'action' => 'accept',
677 'id' => $toolproxy->id,
678 'sesskey' => sesskey(),
682 $registerurl = new \moodle_url('/mod/lti/register.php', array(
683 'id' => $toolproxy->id,
684 'sesskey' => sesskey(),
685 'tab' => 'tool_proxy'
688 $accepthtml = $OUTPUT->action_icon($registerurl,
689 new \pix_icon('t/check', $accept, '', array('class' => 'iconsmall')), null,
690 array('title' => $accept, 'class' => 'editing_accept'));
692 $deleteaction = 'delete';
694 if ($toolproxy->state != LTI_TOOL_PROXY_STATE_CONFIGURED) {
698 if (($toolproxy->state == LTI_TOOL_PROXY_STATE_CONFIGURED) || ($toolproxy->state == LTI_TOOL_PROXY_STATE_PENDING)) {
699 $delete = get_string('cancel', 'lti');
702 $updateurl = clone($baseurl);
703 $updateurl->param('action', 'update');
704 $updatehtml = $OUTPUT->action_icon($updateurl,
705 new \pix_icon('t/edit', $update, '', array('class' => 'iconsmall')), null,
706 array('title' => $update, 'class' => 'editing_update'));
708 $deleteurl = clone($baseurl);
709 $deleteurl->param('action', $deleteaction);
710 $deletehtml = $OUTPUT->action_icon($deleteurl,
711 new \pix_icon('t/delete', $delete, '', array('class' => 'iconsmall')), null,
712 array('title' => $delete, 'class' => 'editing_delete'));
725 {$accepthtml}{$updatehtml}{$deletehtml}
730 $html .= '</table></div>';
732 $html = get_string('no_' . $id, 'lti');
739 * Extracts the enabled capabilities into an array, including those implicitly declared in a parameter
741 * @param object $tool Tool instance object
743 * @return Array of enabled capabilities
745 function lti_get_enabled_capabilities($tool) {
746 if (!empty($tool->enabledcapability)) {
747 $enabledcapabilities = explode("\n", $tool->enabledcapability);
749 $enabledcapabilities = array();
751 $paramstr = str_replace("\r\n", "\n", $tool->parameter);
752 $paramstr = str_replace("\n\r", "\n", $paramstr);
753 $paramstr = str_replace("\r", "\n", $paramstr);
754 $params = explode("\n", $paramstr);
755 foreach ($params as $param) {
756 $pos = strpos($param, '=');
757 if (($pos === false) || ($pos < 1)) {
760 $value = trim(core_text::substr($param, $pos + 1, strlen($param)));
761 if (substr($value, 0, 1) == '$') {
762 $value = substr($value, 1);
763 if (!in_array($value, $enabledcapabilities)) {
764 $enabledcapabilities[] = $value;
768 return $enabledcapabilities;
772 * Splits the custom parameters field to the various parameters
774 * @param object $toolproxy Tool proxy instance object
775 * @param object $tool Tool instance object
776 * @param array $params LTI launch parameters
777 * @param string $customstr String containing the parameters
778 * @param boolean $islti2 True if an LTI 2 tool is being launched
780 * @return Array of custom parameters
782 function lti_split_custom_parameters($toolproxy, $tool, $params, $customstr, $islti2 = false) {
783 $customstr = str_replace("\r\n", "\n", $customstr);
784 $customstr = str_replace("\n\r", "\n", $customstr);
785 $customstr = str_replace("\r", "\n", $customstr);
786 $lines = explode("\n", $customstr); // Or should this split on "/[\n;]/"?
788 foreach ($lines as $line) {
789 $pos = strpos($line, '=');
790 if ( $pos === false || $pos < 1 ) {
793 $key = trim(core_text::substr($line, 0, $pos));
794 $val = trim(core_text::substr($line, $pos + 1, strlen($line)));
795 $val = lti_parse_custom_parameter($toolproxy, $tool, $params, $val, $islti2);
796 $key2 = lti_map_keyname($key);
797 $retval['custom_'.$key2] = $val;
798 if ($islti2 && ($key != $key2)) {
799 $retval['custom_'.$key] = $val;
806 * Adds the custom parameters to an array
808 * @param object $toolproxy Tool proxy instance object
809 * @param object $tool Tool instance object
810 * @param array $params LTI launch parameters
811 * @param array $parameters Array containing the parameters
813 * @return array Array of custom parameters
815 function lti_get_custom_parameters($toolproxy, $tool, $params, $parameters) {
817 foreach ($parameters as $key => $val) {
818 $key2 = lti_map_keyname($key);
819 $val = lti_parse_custom_parameter($toolproxy, $tool, $params, $val, true);
820 $retval['custom_'.$key2] = $val;
822 $retval['custom_'.$key] = $val;
829 * Parse a custom parameter to replace any substitution variables
831 * @param object $toolproxy Tool proxy instance object
832 * @param object $tool Tool instance object
833 * @param array $params LTI launch parameters
834 * @param string $value Custom parameter value
835 * @param boolean $islti2 True if an LTI 2 tool is being launched
837 * @return Parsed value of custom parameter
839 function lti_parse_custom_parameter($toolproxy, $tool, $params, $value, $islti2) {
840 global $USER, $COURSE;
843 if (substr($value, 0, 1) == '\\') {
844 $value = substr($value, 1);
845 } else if (substr($value, 0, 1) == '$') {
846 $value1 = substr($value, 1);
847 $enabledcapabilities = lti_get_enabled_capabilities($tool);
848 if (!$islti2 || in_array($value1, $enabledcapabilities)) {
849 $capabilities = lti_get_capabilities();
850 if (array_key_exists($value1, $capabilities)) {
851 $val = $capabilities[$value1];
853 if (substr($val, 0, 1) != '$') {
854 $value = $params[$val];
856 $valarr = explode('->', substr($val, 1), 2);
857 $value = "{${$valarr[0]}->$valarr[1]}";
858 $value = str_replace('<br />' , ' ', $value);
859 $value = str_replace('<br>' , ' ', $value);
860 $value = format_string($value);
863 } else if ($islti2) {
865 $services = lti_get_services();
866 foreach ($services as $service) {
867 $service->set_tool_proxy($toolproxy);
868 $value = $service->parse_value($val);
869 if ($val != $value) {
881 * Used for building the names of the different custom parameters
883 * @param string $key Parameter name
885 * @return string Processed name
887 function lti_map_keyname($key) {
889 $key = core_text::strtolower(trim($key));
890 foreach (str_split($key) as $ch) {
891 if ( ($ch >= 'a' && $ch <= 'z') || ($ch >= '0' && $ch <= '9') ) {
901 * Gets the IMS role string for the specified user and LTI course module.
903 * @param mixed $user User object or user id
904 * @param int $cmid The course module id of the LTI activity
905 * @param int $courseid The course id of the LTI activity
906 * @param boolean $islti2 True if an LTI 2 tool is being launched
908 * @return string A role string suitable for passing with an LTI launch
910 function lti_get_ims_role($user, $cmid, $courseid, $islti2) {
914 // If no cmid is passed, check if the user is a teacher in the course
915 // This allows other modules to programmatically "fake" a launch without
916 // a real LTI instance.
917 $coursecontext = context_course::instance($courseid);
919 if (has_capability('moodle/course:manageactivities', $coursecontext)) {
920 array_push($roles, 'Instructor');
922 array_push($roles, 'Learner');
925 $context = context_module::instance($cmid);
927 if (has_capability('mod/lti:manage', $context)) {
928 array_push($roles, 'Instructor');
930 array_push($roles, 'Learner');
934 if (is_siteadmin($user)) {
936 array_push($roles, 'urn:lti:sysrole:ims/lis/Administrator', 'urn:lti:instrole:ims/lis/Administrator');
938 array_push($roles, 'http://purl.imsglobal.org/vocab/lis/v2/person#Administrator');
942 return join(',', $roles);
946 * Returns configuration details for the tool
948 * @param int $typeid Basic LTI tool typeid
950 * @return array Tool Configuration
952 function lti_get_type_config($typeid) {
955 $query = "SELECT name, value
956 FROM {lti_types_config}
957 WHERE typeid = :typeid1
959 SELECT 'toolurl' AS name, " . $DB->sql_compare_text('baseurl', 1333) . " AS value
963 SELECT 'icon' AS name, " . $DB->sql_compare_text('icon', 1333) . " AS value
967 SELECT 'secureicon' AS name, " . $DB->sql_compare_text('secureicon', 1333) . " AS value
969 WHERE id = :typeid4";
971 $typeconfig = array();
972 $configs = $DB->get_records_sql($query,
973 array('typeid1' => $typeid, 'typeid2' => $typeid, 'typeid3' => $typeid, 'typeid4' => $typeid));
975 if (!empty($configs)) {
976 foreach ($configs as $config) {
977 $typeconfig[$config->name] = $config->value;
984 function lti_get_tools_by_url($url, $state, $courseid = null) {
985 $domain = lti_get_domain_from_url($url);
987 return lti_get_tools_by_domain($domain, $state, $courseid);
990 function lti_get_tools_by_domain($domain, $state = null, $courseid = null) {
993 $filters = array('tooldomain' => $domain);
999 $statefilter = 'AND state = :state';
1002 if ($courseid && $courseid != $SITE->id) {
1003 $coursefilter = 'OR course = :courseid';
1008 WHERE tooldomain = :tooldomain
1009 AND (course = :siteid $coursefilter)
1012 return $DB->get_records_sql($query, array(
1013 'courseid' => $courseid,
1014 'siteid' => $SITE->id,
1015 'tooldomain' => $domain,
1021 * Returns all basicLTI tools configured by the administrator
1024 function lti_filter_get_types($course) {
1027 if (!empty($course)) {
1028 $where = "WHERE t.course = :course";
1029 $params = array('course' => $course);
1034 $query = "SELECT t.id, t.name, t.baseurl, t.state, t.toolproxyid, t.timecreated, tp.name tpname
1035 FROM {lti_types} t LEFT OUTER JOIN {lti_tool_proxies} tp ON t.toolproxyid = tp.id
1037 return $DB->get_records_sql($query, $params);
1041 * Given an array of tools, filter them based on their state
1043 * @param array $tools An array of lti_types records
1044 * @param int $state One of the LTI_TOOL_STATE_* constants
1047 function lti_filter_tool_types(array $tools, $state) {
1049 foreach ($tools as $key => $tool) {
1050 if ($tool->state == $state) {
1051 $return[$key] = $tool;
1057 function lti_get_types_for_add_instance() {
1058 global $DB, $SITE, $COURSE;
1062 WHERE coursevisible = 1
1063 AND (course = :siteid OR course = :courseid)
1064 AND state = :active";
1066 $admintypes = $DB->get_records_sql($query,
1067 array('siteid' => $SITE->id, 'courseid' => $COURSE->id, 'active' => LTI_TOOL_STATE_CONFIGURED));
1070 $types[0] = (object)array('name' => get_string('automatic', 'lti'), 'course' => 0, 'toolproxyid' => null);
1072 foreach ($admintypes as $type) {
1073 $types[$type->id] = $type;
1079 function lti_get_domain_from_url($url) {
1082 if (preg_match(LTI_URL_DOMAIN_REGEX, $url, $matches)) {
1087 function lti_get_tool_by_url_match($url, $courseid = null, $state = LTI_TOOL_STATE_CONFIGURED) {
1088 $possibletools = lti_get_tools_by_url($url, $state, $courseid);
1090 return lti_get_best_tool_by_url($url, $possibletools, $courseid);
1093 function lti_get_url_thumbprint($url) {
1094 // Parse URL requires a schema otherwise everything goes into 'path'. Fixed 5.4.7 or later.
1095 if (preg_match('/https?:\/\//', $url) !== 1) {
1096 $url = 'http://'.$url;
1098 $urlparts = parse_url(strtolower($url));
1099 if (!isset($urlparts['path'])) {
1100 $urlparts['path'] = '';
1103 if (!isset($urlparts['host'])) {
1104 $urlparts['host'] = '';
1107 if (substr($urlparts['host'], 0, 4) === 'www.') {
1108 $urlparts['host'] = substr($urlparts['host'], 4);
1111 return $urllower = $urlparts['host'] . '/' . $urlparts['path'];
1114 function lti_get_best_tool_by_url($url, $tools, $courseid = null) {
1115 if (count($tools) === 0) {
1119 $urllower = lti_get_url_thumbprint($url);
1121 foreach ($tools as $tool) {
1122 $tool->_matchscore = 0;
1124 $toolbaseurllower = lti_get_url_thumbprint($tool->baseurl);
1126 if ($urllower === $toolbaseurllower) {
1127 // 100 points for exact thumbprint match.
1128 $tool->_matchscore += 100;
1129 } else if (substr($urllower, 0, strlen($toolbaseurllower)) === $toolbaseurllower) {
1130 // 50 points if tool thumbprint starts with the base URL thumbprint.
1131 $tool->_matchscore += 50;
1134 // Prefer course tools over site tools.
1135 if (!empty($courseid)) {
1136 // Minus 10 points for not matching the course id (global tools).
1137 if ($tool->course != $courseid) {
1138 $tool->_matchscore -= 10;
1143 $bestmatch = array_reduce($tools, function($value, $tool) {
1144 if ($tool->_matchscore > $value->_matchscore) {
1150 }, (object)array('_matchscore' => -1));
1152 // None of the tools are suitable for this URL.
1153 if ($bestmatch->_matchscore <= 0) {
1160 function lti_get_shared_secrets_by_key($key) {
1163 // Look up the shared secret for the specified key in both the types_config table (for configured tools)
1164 // And in the lti resource table for ad-hoc tools.
1165 $query = "SELECT t2.value
1166 FROM {lti_types_config} t1
1167 JOIN {lti_types_config} t2 ON t1.typeid = t2.typeid
1168 JOIN {lti_types} type ON t2.typeid = type.id
1169 WHERE t1.name = 'resourcekey'
1170 AND t1.value = :key1
1171 AND t2.name = 'password'
1172 AND type.state = :configured1
1174 SELECT tp.secret AS value
1175 FROM {lti_tool_proxies} tp
1176 JOIN {lti_types} t ON tp.id = t.toolproxyid
1177 WHERE tp.guid = :key2
1178 AND t.state = :configured2
1180 SELECT password AS value
1182 WHERE resourcekey = :key3";
1184 $sharedsecrets = $DB->get_records_sql($query, array('configured1' => LTI_TOOL_STATE_CONFIGURED,
1185 'configured2' => LTI_TOOL_STATE_CONFIGURED, 'key1' => $key, 'key2' => $key, 'key3' => $key));
1187 $values = array_map(function($item) {
1188 return $item->value;
1191 // There should really only be one shared secret per key. But, we can't prevent
1192 // more than one getting entered. For instance, if the same key is used for two tool providers.
1197 * Delete a Basic LTI configuration
1199 * @param int $id Configuration id
1201 function lti_delete_type($id) {
1204 // We should probably just copy the launch URL to the tool instances in this case... using a single query.
1206 $instances = $DB->get_records('lti', array('typeid' => $id));
1207 foreach ($instances as $instance) {
1208 $instance->typeid = 0;
1209 $DB->update_record('lti', $instance);
1212 $DB->delete_records('lti_types', array('id' => $id));
1213 $DB->delete_records('lti_types_config', array('typeid' => $id));
1216 function lti_set_state_for_type($id, $state) {
1219 $DB->update_record('lti_types', array('id' => $id, 'state' => $state));
1223 * Transforms a basic LTI object to an array
1225 * @param object $ltiobject Basic LTI object
1227 * @return array Basic LTI configuration details
1229 function lti_get_config($ltiobject) {
1230 $typeconfig = array();
1231 $typeconfig = (array)$ltiobject;
1232 $additionalconfig = lti_get_type_config($ltiobject->typeid);
1233 $typeconfig = array_merge($typeconfig, $additionalconfig);
1239 * Generates some of the tool configuration based on the instance details
1243 * @return Instance configuration
1246 function lti_get_type_config_from_instance($id) {
1249 $instance = $DB->get_record('lti', array('id' => $id));
1250 $config = lti_get_config($instance);
1252 $type = new \stdClass();
1253 $type->lti_fix = $id;
1254 if (isset($config['toolurl'])) {
1255 $type->lti_toolurl = $config['toolurl'];
1257 if (isset($config['instructorchoicesendname'])) {
1258 $type->lti_sendname = $config['instructorchoicesendname'];
1260 if (isset($config['instructorchoicesendemailaddr'])) {
1261 $type->lti_sendemailaddr = $config['instructorchoicesendemailaddr'];
1263 if (isset($config['instructorchoiceacceptgrades'])) {
1264 $type->lti_acceptgrades = $config['instructorchoiceacceptgrades'];
1266 if (isset($config['instructorchoiceallowroster'])) {
1267 $type->lti_allowroster = $config['instructorchoiceallowroster'];
1270 if (isset($config['instructorcustomparameters'])) {
1271 $type->lti_allowsetting = $config['instructorcustomparameters'];
1277 * Generates some of the tool configuration based on the admin configuration details
1281 * @return Configuration details
1283 function lti_get_type_type_config($id) {
1286 $basicltitype = $DB->get_record('lti_types', array('id' => $id));
1287 $config = lti_get_type_config($id);
1289 $type = new \stdClass();
1291 $type->lti_typename = $basicltitype->name;
1293 $type->typeid = $basicltitype->id;
1295 $type->toolproxyid = $basicltitype->toolproxyid;
1297 $type->lti_toolurl = $basicltitype->baseurl;
1299 $type->lti_parameters = $basicltitype->parameter;
1301 $type->lti_icon = $basicltitype->icon;
1303 $type->lti_secureicon = $basicltitype->secureicon;
1305 if (isset($config['resourcekey'])) {
1306 $type->lti_resourcekey = $config['resourcekey'];
1308 if (isset($config['password'])) {
1309 $type->lti_password = $config['password'];
1312 if (isset($config['sendname'])) {
1313 $type->lti_sendname = $config['sendname'];
1315 if (isset($config['instructorchoicesendname'])) {
1316 $type->lti_instructorchoicesendname = $config['instructorchoicesendname'];
1318 if (isset($config['sendemailaddr'])) {
1319 $type->lti_sendemailaddr = $config['sendemailaddr'];
1321 if (isset($config['instructorchoicesendemailaddr'])) {
1322 $type->lti_instructorchoicesendemailaddr = $config['instructorchoicesendemailaddr'];
1324 if (isset($config['acceptgrades'])) {
1325 $type->lti_acceptgrades = $config['acceptgrades'];
1327 if (isset($config['instructorchoiceacceptgrades'])) {
1328 $type->lti_instructorchoiceacceptgrades = $config['instructorchoiceacceptgrades'];
1330 if (isset($config['allowroster'])) {
1331 $type->lti_allowroster = $config['allowroster'];
1333 if (isset($config['instructorchoiceallowroster'])) {
1334 $type->lti_instructorchoiceallowroster = $config['instructorchoiceallowroster'];
1337 if (isset($config['customparameters'])) {
1338 $type->lti_customparameters = $config['customparameters'];
1341 if (isset($config['forcessl'])) {
1342 $type->lti_forcessl = $config['forcessl'];
1345 if (isset($config['organizationid'])) {
1346 $type->lti_organizationid = $config['organizationid'];
1348 if (isset($config['organizationurl'])) {
1349 $type->lti_organizationurl = $config['organizationurl'];
1351 if (isset($config['organizationdescr'])) {
1352 $type->lti_organizationdescr = $config['organizationdescr'];
1354 if (isset($config['launchcontainer'])) {
1355 $type->lti_launchcontainer = $config['launchcontainer'];
1358 if (isset($config['coursevisible'])) {
1359 $type->lti_coursevisible = $config['coursevisible'];
1362 if (isset($config['debuglaunch'])) {
1363 $type->lti_debuglaunch = $config['debuglaunch'];
1366 if (isset($config['module_class_type'])) {
1367 $type->lti_module_class_type = $config['module_class_type'];
1373 function lti_prepare_type_for_save($type, $config) {
1374 if (isset($config->lti_toolurl)) {
1375 $type->baseurl = $config->lti_toolurl;
1376 $type->tooldomain = lti_get_domain_from_url($config->lti_toolurl);
1378 if (isset($config->lti_typename)) {
1379 $type->name = $config->lti_typename;
1381 $type->coursevisible = !empty($config->lti_coursevisible) ? $config->lti_coursevisible : 0;
1382 $config->lti_coursevisible = $type->coursevisible;
1384 if (isset($config->lti_icon)) {
1385 $type->icon = $config->lti_icon;
1387 if (isset($config->lti_secureicon)) {
1388 $type->secureicon = $config->lti_secureicon;
1391 if (isset($config->lti_forcessl)) {
1392 $type->forcessl = !empty($config->lti_forcessl) ? $config->lti_forcessl : 0;
1393 $config->lti_forcessl = $type->forcessl;
1396 $type->timemodified = time();
1398 unset ($config->lti_typename);
1399 unset ($config->lti_toolurl);
1400 unset ($config->lti_icon);
1401 unset ($config->lti_secureicon);
1404 function lti_update_type($type, $config) {
1407 lti_prepare_type_for_save($type, $config);
1409 $clearcache = false;
1410 if (lti_request_is_using_ssl() && !empty($type->secureicon)) {
1411 $clearcache = !isset($config->oldicon) || ($config->oldicon !== $type->secureicon);
1413 $clearcache = isset($type->icon) && (!isset($config->oldicon) || ($config->oldicon !== $type->icon));
1415 unset($config->oldicon);
1417 if ($DB->update_record('lti_types', $type)) {
1418 foreach ($config as $key => $value) {
1419 if (substr($key, 0, 4) == 'lti_' && !is_null($value)) {
1420 $record = new \StdClass();
1421 $record->typeid = $type->id;
1422 $record->name = substr($key, 4);
1423 $record->value = $value;
1424 lti_update_config($record);
1427 require_once($CFG->libdir.'/modinfolib.php');
1429 rebuild_course_cache();
1434 function lti_add_type($type, $config) {
1435 global $USER, $SITE, $DB;
1437 lti_prepare_type_for_save($type, $config);
1439 if (!isset($type->state)) {
1440 $type->state = LTI_TOOL_STATE_PENDING;
1443 if (!isset($type->timecreated)) {
1444 $type->timecreated = time();
1447 if (!isset($type->createdby)) {
1448 $type->createdby = $USER->id;
1451 if (!isset($type->course)) {
1452 $type->course = $SITE->id;
1455 // Create a salt value to be used for signing passed data to extension services
1456 // The outcome service uses the service salt on the instance. This can be used
1457 // for communication with services not related to a specific LTI instance.
1458 $config->lti_servicesalt = uniqid('', true);
1460 $id = $DB->insert_record('lti_types', $type);
1463 foreach ($config as $key => $value) {
1464 if (substr($key, 0, 4) == 'lti_' && !is_null($value)) {
1465 $record = new \StdClass();
1466 $record->typeid = $id;
1467 $record->name = substr($key, 4);
1468 $record->value = $value;
1470 lti_add_config($record);
1479 * Given an array of tool proxies, filter them based on their state
1481 * @param array $toolproxies An array of lti_tool_proxies records
1482 * @param int $state One of the LTI_TOOL_PROXY_STATE_* constants
1486 function lti_filter_tool_proxy_types(array $toolproxies, $state) {
1488 foreach ($toolproxies as $key => $toolproxy) {
1489 if ($toolproxy->state == $state) {
1490 $return[$key] = $toolproxy;
1497 * Get the tool proxy instance given its GUID
1499 * @param string $toolproxyguid Tool proxy GUID value
1503 function lti_get_tool_proxy_from_guid($toolproxyguid) {
1506 $toolproxy = $DB->get_record('lti_tool_proxies', array('guid' => $toolproxyguid));
1512 * Generates some of the tool proxy configuration based on the admin configuration details
1516 * @return Tool Proxy details
1518 function lti_get_tool_proxy($id) {
1521 $toolproxy = $DB->get_record('lti_tool_proxies', array('id' => $id));
1526 * Generates some of the tool proxy configuration based on the admin configuration details
1530 * @return Tool Proxy details
1532 function lti_get_tool_proxy_config($id) {
1533 $toolproxy = lti_get_tool_proxy($id);
1535 $tp = new \stdClass();
1536 $tp->lti_registrationname = $toolproxy->name;
1537 $tp->toolproxyid = $toolproxy->id;
1538 $tp->state = $toolproxy->state;
1539 $tp->lti_registrationurl = $toolproxy->regurl;
1540 $tp->lti_capabilities = explode("\n", $toolproxy->capabilityoffered);
1541 $tp->lti_services = explode("\n", $toolproxy->serviceoffered);
1547 * Update the database with a tool proxy instance
1549 * @param object $config Tool proxy definition
1551 * @return int Record id number
1553 function lti_add_tool_proxy($config) {
1556 $toolproxy = new \stdClass();
1557 if (isset($config->lti_registrationname)) {
1558 $toolproxy->name = trim($config->lti_registrationname);
1560 if (isset($config->lti_registrationurl)) {
1561 $toolproxy->regurl = trim($config->lti_registrationurl);
1563 if (isset($config->lti_capabilities)) {
1564 $toolproxy->capabilityoffered = implode("\n", $config->lti_capabilities);
1566 if (isset($config->lti_services)) {
1567 $toolproxy->serviceoffered = implode("\n", $config->lti_services);
1569 if (isset($config->toolproxyid) && !empty($config->toolproxyid)) {
1570 $toolproxy->id = $config->toolproxyid;
1571 if (!isset($toolproxy->state) || ($toolproxy->state != LTI_TOOL_PROXY_STATE_ACCEPTED)) {
1572 $toolproxy->state = LTI_TOOL_PROXY_STATE_CONFIGURED;
1573 $toolproxy->guid = random_string();
1574 $toolproxy->secret = random_string();
1576 $id = lti_update_tool_proxy($toolproxy);
1578 $toolproxy->state = LTI_TOOL_PROXY_STATE_CONFIGURED;
1579 $toolproxy->timemodified = time();
1580 $toolproxy->timecreated = $toolproxy->timemodified;
1581 if (!isset($toolproxy->createdby)) {
1582 $toolproxy->createdby = $USER->id;
1584 $toolproxy->guid = random_string();
1585 $toolproxy->secret = random_string();
1586 $id = $DB->insert_record('lti_tool_proxies', $toolproxy);
1593 * Updates a tool proxy in the database
1595 * @param object $toolproxy Tool proxy
1597 * @return int Record id number
1599 function lti_update_tool_proxy($toolproxy) {
1602 $toolproxy->timemodified = time();
1603 $id = $DB->update_record('lti_tool_proxies', $toolproxy);
1609 * Delete a Tool Proxy
1611 * @param int $id Tool Proxy id
1613 function lti_delete_tool_proxy($id) {
1615 $DB->delete_records('lti_tool_settings', array('toolproxyid' => $id));
1616 $tools = $DB->get_records('lti_types', array('toolproxyid' => $id));
1617 foreach ($tools as $tool) {
1618 lti_delete_type($tool->id);
1620 $DB->delete_records('lti_tool_proxies', array('id' => $id));
1624 * Add a tool configuration in the database
1626 * @param object $config Tool configuration
1628 * @return int Record id number
1630 function lti_add_config($config) {
1633 return $DB->insert_record('lti_types_config', $config);
1637 * Updates a tool configuration in the database
1639 * @param object $config Tool configuration
1641 * @return Record id number
1643 function lti_update_config($config) {
1647 $old = $DB->get_record('lti_types_config', array('typeid' => $config->typeid, 'name' => $config->name));
1650 $config->id = $old->id;
1651 $return = $DB->update_record('lti_types_config', $config);
1653 $return = $DB->insert_record('lti_types_config', $config);
1659 * Gets the tool settings
1661 * @param int $toolproxyid Id of tool proxy record
1662 * @param int $courseid Id of course (null if system settings)
1663 * @param int $instanceid Id of course module (null if system or context settings)
1665 * @return array Array settings
1667 function lti_get_tool_settings($toolproxyid, $courseid = null, $instanceid = null) {
1670 $settings = array();
1671 $settingsstr = $DB->get_field('lti_tool_settings', 'settings', array('toolproxyid' => $toolproxyid,
1672 'course' => $courseid, 'coursemoduleid' => $instanceid));
1673 if ($settingsstr !== false) {
1674 $settings = json_decode($settingsstr, true);
1680 * Sets the tool settings (
1682 * @param array $settings Array of settings
1683 * @param int $toolproxyid Id of tool proxy record
1684 * @param int $courseid Id of course (null if system settings)
1685 * @param int $instanceid Id of course module (null if system or context settings)
1687 function lti_set_tool_settings($settings, $toolproxyid, $courseid = null, $instanceid = null) {
1690 $json = json_encode($settings);
1691 $record = $DB->get_record('lti_tool_settings', array('toolproxyid' => $toolproxyid,
1692 'course' => $courseid, 'coursemoduleid' => $instanceid));
1693 if ($record !== false) {
1694 $DB->update_record('lti_tool_settings', array('id' => $record->id, 'settings' => $json, 'timemodified' => time()));
1696 $record = new \stdClass();
1697 $record->toolproxyid = $toolproxyid;
1698 $record->course = $courseid;
1699 $record->coursemoduleid = $instanceid;
1700 $record->settings = $json;
1701 $record->timecreated = time();
1702 $record->timemodified = $record->timecreated;
1703 $DB->insert_record('lti_tool_settings', $record);
1708 * Signs the petition to launch the external tool using OAuth
1710 * @param $oldparms Parameters to be passed for signing
1711 * @param $endpoint url of the external tool
1712 * @param $method Method for sending the parameters (e.g. POST)
1713 * @param $oauth_consumoer_key Key
1714 * @param $oauth_consumoer_secret Secret
1716 function lti_sign_parameters($oldparms, $endpoint, $method, $oauthconsumerkey, $oauthconsumersecret) {
1722 // TODO: Switch to core oauthlib once implemented - MDL-30149.
1723 $hmacmethod = new lti\OAuthSignatureMethod_HMAC_SHA1();
1724 $testconsumer = new lti\OAuthConsumer($oauthconsumerkey, $oauthconsumersecret, null);
1725 $accreq = lti\OAuthRequest::from_consumer_and_token($testconsumer, $testtoken, $method, $endpoint, $parms);
1726 $accreq->sign_request($hmacmethod, $testconsumer, $testtoken);
1728 $newparms = $accreq->get_parameters();
1734 * Posts the launch petition HTML
1736 * @param $newparms Signed parameters
1737 * @param $endpoint URL of the external tool
1738 * @param $debug Debug (true/false)
1740 function lti_post_launch_html($newparms, $endpoint, $debug=false) {
1741 $r = "<form action=\"" . $endpoint .
1742 "\" name=\"ltiLaunchForm\" id=\"ltiLaunchForm\" method=\"post\" encType=\"application/x-www-form-urlencoded\">\n";
1744 // Contruct html for the launch parameters.
1745 foreach ($newparms as $key => $value) {
1746 $key = htmlspecialchars($key);
1747 $value = htmlspecialchars($value);
1748 if ( $key == "ext_submit" ) {
1749 $r .= "<input type=\"submit\"";
1751 $r .= "<input type=\"hidden\" name=\"{$key}\"";
1759 $r .= "<script language=\"javascript\"> \n";
1760 $r .= " //<![CDATA[ \n";
1761 $r .= "function basicltiDebugToggle() {\n";
1762 $r .= " var ele = document.getElementById(\"basicltiDebug\");\n";
1763 $r .= " if (ele.style.display == \"block\") {\n";
1764 $r .= " ele.style.display = \"none\";\n";
1767 $r .= " ele.style.display = \"block\";\n";
1771 $r .= "</script>\n";
1772 $r .= "<a id=\"displayText\" href=\"javascript:basicltiDebugToggle();\">";
1773 $r .= get_string("toggle_debug_data", "lti")."</a>\n";
1774 $r .= "<div id=\"basicltiDebug\" style=\"display:none\">\n";
1775 $r .= "<b>".get_string("basiclti_endpoint", "lti")."</b><br/>\n";
1776 $r .= $endpoint . "<br/>\n <br/>\n";
1777 $r .= "<b>".get_string("basiclti_parameters", "lti")."</b><br/>\n";
1778 foreach ($newparms as $key => $value) {
1779 $key = htmlspecialchars($key);
1780 $value = htmlspecialchars($value);
1781 $r .= "$key = $value<br/>\n";
1783 $r .= " <br/>\n";
1789 $r .= " <script type=\"text/javascript\"> \n" .
1791 " document.ltiLaunchForm.submit(); \n" .
1798 function lti_get_type($typeid) {
1801 return $DB->get_record('lti_types', array('id' => $typeid));
1804 function lti_get_launch_container($lti, $toolconfig) {
1805 if (empty($lti->launchcontainer)) {
1806 $lti->launchcontainer = LTI_LAUNCH_CONTAINER_DEFAULT;
1809 if ($lti->launchcontainer == LTI_LAUNCH_CONTAINER_DEFAULT) {
1810 if (isset($toolconfig['launchcontainer'])) {
1811 $launchcontainer = $toolconfig['launchcontainer'];
1814 $launchcontainer = $lti->launchcontainer;
1817 if (empty($launchcontainer) || $launchcontainer == LTI_LAUNCH_CONTAINER_DEFAULT) {
1818 $launchcontainer = LTI_LAUNCH_CONTAINER_EMBED_NO_BLOCKS;
1821 $devicetype = core_useragent::get_device_type();
1823 // Scrolling within the object element doesn't work on iOS or Android
1824 // Opening the popup window also had some issues in testing
1825 // For mobile devices, always take up the entire screen to ensure the best experience.
1826 if ($devicetype === core_useragent::DEVICETYPE_MOBILE || $devicetype === core_useragent::DEVICETYPE_TABLET ) {
1827 $launchcontainer = LTI_LAUNCH_CONTAINER_REPLACE_MOODLE_WINDOW;
1830 return $launchcontainer;
1833 function lti_request_is_using_ssl() {
1835 return (stripos($CFG->httpswwwroot, 'https://') === 0);
1838 function lti_ensure_url_is_https($url) {
1839 if (!strstr($url, '://')) {
1840 $url = 'https://' . $url;
1842 // If the URL starts with http, replace with https.
1843 if (stripos($url, 'http://') === 0) {
1844 $url = 'https://' . substr($url, 7);
1852 * Determines if we should try to log the request
1854 * @param string $rawbody
1857 function lti_should_log_request($rawbody) {
1860 if (empty($CFG->mod_lti_log_users)) {
1864 $logusers = explode(',', $CFG->mod_lti_log_users);
1865 if (empty($logusers)) {
1870 $xml = new \SimpleXMLElement($rawbody);
1871 $ns = $xml->getNamespaces();
1872 $ns = array_shift($ns);
1873 $xml->registerXPathNamespace('lti', $ns);
1874 $requestuserid = '';
1875 if ($node = $xml->xpath('//lti:userId')) {
1877 $requestuserid = clean_param((string) $node, PARAM_INT);
1878 } else if ($node = $xml->xpath('//lti:sourcedId')) {
1880 $resultjson = json_decode((string) $node);
1881 $requestuserid = clean_param($resultjson->data->userid, PARAM_INT);
1883 } catch (Exception $e) {
1887 if (empty($requestuserid) or !in_array($requestuserid, $logusers)) {
1895 * Logs the request to a file in temp dir
1897 * @param string $rawbody
1899 function lti_log_request($rawbody) {
1900 if ($tempdir = make_temp_directory('mod_lti', false)) {
1901 if ($tempfile = tempnam($tempdir, 'mod_lti_request'.date('YmdHis'))) {
1902 file_put_contents($tempfile, $rawbody);
1903 chmod($tempfile, 0644);
1909 * Fetches LTI type configuration for an LTI instance
1911 * @param stdClass $instance
1912 * @return array Can be empty if no type is found
1914 function lti_get_type_config_by_instance($instance) {
1916 if (empty($instance->typeid)) {
1917 $tool = lti_get_tool_by_url_match($instance->toolurl, $instance->course);
1919 $typeid = $tool->id;
1922 $typeid = $instance->typeid;
1924 if (!empty($typeid)) {
1925 return lti_get_type_config($typeid);
1931 * Enforce type config settings onto the LTI instance
1933 * @param stdClass $instance
1934 * @param array $typeconfig
1936 function lti_force_type_config_settings($instance, array $typeconfig) {
1938 'instructorchoicesendname' => 'sendname',
1939 'instructorchoicesendemailaddr' => 'sendemailaddr',
1940 'instructorchoiceacceptgrades' => 'acceptgrades',
1943 foreach ($forced as $instanceparam => $typeconfigparam) {
1944 if (array_key_exists($typeconfigparam, $typeconfig) && $typeconfig[$typeconfigparam] != LTI_SETTING_DELEGATE) {
1945 $instance->$instanceparam = $typeconfig[$typeconfigparam];
1951 * Initializes an array with the capabilities supported by the LTI module
1953 * @return array List of capability names (without a dollar sign prefix)
1955 function lti_get_capabilities() {
1957 $capabilities = array(
1958 'basic-lti-launch-request' => '',
1959 'Context.id' => 'context_id',
1960 'CourseSection.title' => 'context_title',
1961 'CourseSection.label' => 'context_label',
1962 'CourseSection.sourcedId' => 'lis_course_section_sourcedid',
1963 'CourseSection.longDescription' => '$COURSE->summary',
1964 'CourseSection.timeFrame.begin' => '$COURSE->startdate',
1965 'ResourceLink.id' => 'resource_link_id',
1966 'ResourceLink.title' => 'resource_link_title',
1967 'ResourceLink.description' => 'resource_link_description',
1968 'User.id' => 'user_id',
1969 'User.username' => '$USER->username',
1970 'Person.name.full' => 'lis_person_name_full',
1971 'Person.name.given' => 'lis_person_name_given',
1972 'Person.name.family' => 'lis_person_name_family',
1973 'Person.email.primary' => 'lis_person_contact_email_primary',
1974 'Person.sourcedId' => 'lis_person_sourcedid',
1975 'Person.name.middle' => '$USER->middlename',
1976 'Person.address.street1' => '$USER->address',
1977 'Person.address.locality' => '$USER->city',
1978 'Person.address.country' => '$USER->country',
1979 'Person.address.timezone' => '$USER->timezone',
1980 'Person.phone.primary' => '$USER->phone1',
1981 'Person.phone.mobile' => '$USER->phone2',
1982 'Person.webaddress' => '$USER->url',
1983 'Membership.role' => 'roles',
1984 'Result.sourcedId' => 'lis_result_sourcedid',
1985 'Result.autocreate' => 'lis_outcome_service_url');
1987 return $capabilities;
1992 * Initializes an array with the services supported by the LTI module
1994 * @return array List of services
1996 function lti_get_services() {
1998 $services = array();
1999 $definedservices = core_component::get_plugin_list('ltiservice');
2000 foreach ($definedservices as $name => $location) {
2001 $classname = "\\ltiservice_{$name}\\local\\service\\{$name}";
2002 $services[] = new $classname();
2010 * Initializes an instance of the named service
2012 * @param string $servicename Name of service
2014 * @return mod_lti\local\ltiservice\service_base Service
2016 function lti_get_service_by_name($servicename) {
2019 $classname = "\\ltiservice_{$servicename}\\local\\service\\{$servicename}";
2020 if (class_exists($classname)) {
2021 $service = new $classname();
2029 * Finds a service by id
2031 * @param array $services Array of services
2032 * @param string $resourceid ID of resource
2034 * @return mod_lti\local\ltiservice\service_base Service
2036 function lti_get_service_by_resource_id($services, $resourceid) {
2039 foreach ($services as $aservice) {
2040 foreach ($aservice->get_resources() as $resource) {
2041 if ($resource->get_id() === $resourceid) {
2042 $service = $aservice;
2053 * Extracts the named contexts from a tool proxy
2055 * @param object $json
2057 * @return array Contexts
2059 function lti_get_contexts($json) {
2061 $contexts = array();
2062 if (isset($json->{'@context'})) {
2063 foreach ($json->{'@context'} as $context) {
2064 if (is_object($context)) {
2065 $contexts = array_merge(get_object_vars($context), $contexts);
2075 * Converts an ID to a fully-qualified ID
2077 * @param array $contexts
2080 * @return string Fully-qualified ID
2082 function lti_get_fqid($contexts, $id) {
2084 $parts = explode(':', $id, 2);
2085 if (count($parts) > 1) {
2086 if (array_key_exists($parts[0], $contexts)) {
2087 $id = $contexts[$parts[0]] . $parts[1];