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
40 * @copyright 2009 Marc Alier, Jordi Piguillem, Nikolas Galanis
42 * @copyright 2009 Universitat Politecnica de Catalunya http://www.upc.edu
44 * @author Jordi Piguillem
45 * @author Nikolas Galanis
46 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
49 defined('MOODLE_INTERNAL') || die;
51 // TODO: Switch to core oauthlib once implemented - MDL-30149
52 use moodle\mod\lti as lti;
54 require_once($CFG->dirroot.'/mod/lti/OAuth.php');
56 define('LTI_URL_DOMAIN_REGEX', '/(?:https?:\/\/)?(?:www\.)?([^\/]+)(?:\/|$)/i');
58 define('LTI_LAUNCH_CONTAINER_DEFAULT', 1);
59 define('LTI_LAUNCH_CONTAINER_EMBED', 2);
60 define('LTI_LAUNCH_CONTAINER_EMBED_NO_BLOCKS', 3);
61 define('LTI_LAUNCH_CONTAINER_WINDOW', 4);
62 define('LTI_LAUNCH_CONTAINER_REPLACE_MOODLE_WINDOW', 5);
64 define('LTI_TOOL_STATE_ANY', 0);
65 define('LTI_TOOL_STATE_CONFIGURED', 1);
66 define('LTI_TOOL_STATE_PENDING', 2);
67 define('LTI_TOOL_STATE_REJECTED', 3);
69 define('LTI_SETTING_NEVER', 0);
70 define('LTI_SETTING_ALWAYS', 1);
71 define('LTI_SETTING_DELEGATE', 2);
74 * Prints a Basic LTI activity
76 * $param int $basicltiid Basic LTI activity id
78 function lti_view($instance) {
81 if (empty($instance->typeid)) {
82 $tool = lti_get_tool_by_url_match($instance->toolurl, $instance->course);
89 $typeid = $instance->typeid;
93 $typeconfig = lti_get_type_config($typeid);
95 //There is no admin configuration for this tool. Use configuration in the lti instance record plus some defaults.
96 $typeconfig = (array)$instance;
98 $typeconfig['sendname'] = $instance->instructorchoicesendname;
99 $typeconfig['sendemailaddr'] = $instance->instructorchoicesendemailaddr;
100 $typeconfig['customparameters'] = $instance->instructorcustomparameters;
101 $typeconfig['acceptgrades'] = $instance->instructorchoiceacceptgrades;
102 $typeconfig['allowroster'] = $instance->instructorchoiceallowroster;
103 $typeconfig['forcessl'] = '0';
106 //Default the organizationid if not specified
107 if (empty($typeconfig['organizationid'])) {
108 $urlparts = parse_url($CFG->wwwroot);
110 $typeconfig['organizationid'] = $urlparts['host'];
113 if (!empty($instance->resourcekey)) {
114 $key = $instance->resourcekey;
115 } else if (!empty($typeconfig['resourcekey'])) {
116 $key = $typeconfig['resourcekey'];
121 if (!empty($instance->password)) {
122 $secret = $instance->password;
123 } else if (!empty($typeconfig['password'])) {
124 $secret = $typeconfig['password'];
129 $endpoint = !empty($instance->toolurl) ? $instance->toolurl : $typeconfig['toolurl'];
130 $endpoint = trim($endpoint);
132 //If the current request is using SSL and a secure tool URL is specified, use it
133 if (lti_request_is_using_ssl() && !empty($instance->securetoolurl)) {
134 $endpoint = trim($instance->securetoolurl);
137 //If SSL is forced, use the secure tool url if specified. Otherwise, make sure https is on the normal launch URL.
138 if ($typeconfig['forcessl'] == '1') {
139 if (!empty($instance->securetoolurl)) {
140 $endpoint = trim($instance->securetoolurl);
143 $endpoint = lti_ensure_url_is_https($endpoint);
145 if (!strstr($endpoint, '://')) {
146 $endpoint = 'http://' . $endpoint;
150 $orgid = $typeconfig['organizationid'];
152 $course = $PAGE->course;
153 $requestparams = lti_build_request($instance, $typeconfig, $course);
155 $launchcontainer = lti_get_launch_container($instance, $typeconfig);
156 $returnurlparams = array('course' => $course->id, 'launch_container' => $launchcontainer, 'instanceid' => $instance->id);
159 $requestparams["tool_consumer_instance_guid"] = $orgid;
162 if (empty($key) || empty($secret)) {
163 $returnurlparams['unsigned'] = '1';
165 //Add the return URL. We send the launch container along to help us avoid frames-within-frames when the user returns
166 $url = new moodle_url('/mod/lti/return.php', $returnurlparams);
167 $returnurl = $url->out(false);
169 if ($typeconfig['forcessl'] == '1') {
170 $returnurl = lti_ensure_url_is_https($returnurl);
173 $requestparams['launch_presentation_return_url'] = $returnurl;
176 if (!empty($key) && !empty($secret)) {
177 $parms = lti_sign_parameters($requestparams, $endpoint, "POST", $key, $secret);
179 //If no key and secret, do the launch unsigned.
180 $parms = $requestparams;
183 $debuglaunch = ( $instance->debuglaunch == 1 );
185 $content = lti_post_launch_html($parms, $endpoint, $debuglaunch);
190 function lti_build_sourcedid($instanceid, $userid, $launchid = null, $servicesalt) {
191 $data = new stdClass();
193 $data->instanceid = $instanceid;
194 $data->userid = $userid;
195 if (!empty($launchid)) {
196 $data->launchid = $launchid;
198 $data->launchid = mt_rand();
201 $json = json_encode($data);
203 $hash = hash('sha256', $json . $servicesalt, false);
205 $container = new stdClass();
206 $container->data = $data;
207 $container->hash = $hash;
213 * This function builds the request that must be sent to the tool producer
215 * @param object $instance Basic LTI instance object
216 * @param object $typeconfig Basic LTI tool configuration
217 * @param object $course Course object
219 * @return array $request Request details
221 function lti_build_request($instance, $typeconfig, $course) {
224 if (empty($instance->cmid)) {
228 $role = lti_get_ims_role($USER, $instance->cmid, $instance->course);
230 $locale = $course->lang;
231 if ( strlen($locale) < 1 ) {
232 $locale = $CFG->lang;
235 $requestparams = array(
236 "resource_link_id" => $instance->id,
237 "resource_link_title" => $instance->name,
238 "resource_link_description" => $instance->intro,
239 "user_id" => $USER->id,
241 "context_id" => $course->id,
242 "context_label" => $course->shortname,
243 "context_title" => $course->fullname,
244 "launch_presentation_locale" => $locale,
247 $placementsecret = $instance->servicesalt;
249 if ( isset($placementsecret) ) {
250 $sourcedid = json_encode(lti_build_sourcedid($instance->id, $USER->id, null, $placementsecret));
253 if ( isset($placementsecret) &&
254 ( $typeconfig['acceptgrades'] == LTI_SETTING_ALWAYS ||
255 ( $typeconfig['acceptgrades'] == LTI_SETTING_DELEGATE && $instance->instructorchoiceacceptgrades == LTI_SETTING_ALWAYS ) ) ) {
256 $requestparams["lis_result_sourcedid"] = $sourcedid;
258 $serviceurl = $CFG->wwwroot . '/mod/lti/service.php';
259 if ($typeconfig['forcessl'] == '1') {
260 $serviceurl = lti_ensure_url_is_https($serviceurl);
263 $requestparams["ext_ims_lis_basic_outcome_url"] = $serviceurl;
266 /*if ( isset($placementsecret) &&
267 ( $typeconfig['allowroster'] == LTI_SETTING_ALWAYS ||
268 ( $typeconfig['allowroster'] == LTI_SETTING_DELEGATE && $instance->instructorchoiceallowroster == LTI_SETTING_ALWAYS ) ) ) {
269 $requestparams["ext_ims_lis_memberships_id"] = $sourcedid;
270 $requestparams["ext_ims_lis_memberships_url"] = $CFG->wwwroot.'/mod/lti/service.php';
273 // Send user's name and email data if appropriate
274 if ( $typeconfig['sendname'] == LTI_SETTING_ALWAYS ||
275 ( $typeconfig['sendname'] == LTI_SETTING_DELEGATE && $instance->instructorchoicesendname == LTI_SETTING_ALWAYS ) ) {
276 $requestparams["lis_person_name_given"] = $USER->firstname;
277 $requestparams["lis_person_name_family"] = $USER->lastname;
278 $requestparams["lis_person_name_full"] = $USER->firstname." ".$USER->lastname;
281 if ( $typeconfig['sendemailaddr'] == LTI_SETTING_ALWAYS ||
282 ( $typeconfig['sendemailaddr'] == LTI_SETTING_DELEGATE && $instance->instructorchoicesendemailaddr == LTI_SETTING_ALWAYS ) ) {
283 $requestparams["lis_person_contact_email_primary"] = $USER->email;
286 //Add outcome service URL
287 $url = new moodle_url('/mod/lti/service.php');
288 $requestparams['lis_outcome_service_url'] = $url->out();
290 // Concatenate the custom parameters from the administrator and the instructor
291 // Instructor parameters are only taken into consideration if the administrator
292 // has giver permission
293 $customstr = $typeconfig['customparameters'];
294 $instructorcustomstr = $instance->instructorcustomparameters;
296 $instructorcustom = array();
298 $custom = lti_split_custom_parameters($customstr);
300 if (!isset($typeconfig['allowinstructorcustom']) || $typeconfig['allowinstructorcustom'] == LTI_SETTING_NEVER) {
301 $requestparams = array_merge($custom, $requestparams);
303 if ($instructorcustomstr) {
304 $instructorcustom = lti_split_custom_parameters($instructorcustomstr);
306 foreach ($instructorcustom as $key => $val) {
307 // Ignore the instructor's parameter
308 if (!array_key_exists($key, $custom)) {
309 $custom[$key] = $val;
312 $requestparams = array_merge($custom, $requestparams);
315 // Make sure we let the tool know what LMS they are being called from
316 $requestparams["ext_lms"] = "moodle-2";
318 // Add oauth_callback to be compliant with the 1.0A spec
319 $requestparams["oauth_callback"] = "about:blank";
321 //The submit button needs to be part of the signature as it gets posted with the form.
322 //This needs to be here to support launching without javascript.
323 $submittext = get_string('press_to_submit', 'lti');
324 $requestparams["ext_submit"] = $submittext;
326 $requestparams["lti_version"] = "LTI-1p0";
327 $requestparams["lti_message_type"] = "basic-lti-launch-request";
328 /* Suppress this for now - Chuck
329 if ( $orgdesc ) $requestparams["tool_consumer_instance_description"] = $orgdesc;
332 return $requestparams;
335 function lti_get_tool_table($tools, $id) {
339 $typename = get_string('typename', 'lti');
340 $baseurl = get_string('baseurl', 'lti');
341 $action = get_string('action', 'lti');
342 $createdon = get_string('createdon', 'lti');
344 if ($id == 'lti_configured') {
345 $html .= '<div><a style="margin-top:.25em" href="'.$CFG->wwwroot.'/mod/lti/typessettings.php?action=add&sesskey='.$USER->sesskey.'">'.get_string('addtype', 'lti').'</a></div>';
348 if (!empty($tools)) {
350 <div id="{$id}_container" style="margin-top:.5em;margin-bottom:.5em">
351 <table id="{$id}_tools">
362 foreach ($tools as $type) {
363 $date = userdate($type->timecreated);
364 $accept = get_string('accept', 'lti');
365 $update = get_string('update', 'lti');
366 $delete = get_string('delete', 'lti');
368 $accepthtml = <<<HTML
369 <a class="editing_accept" href="{$CFG->wwwroot}/mod/lti/typessettings.php?action=accept&id={$type->id}&sesskey={$USER->sesskey}&tab={$id}" title="{$accept}">
370 <img class="iconsmall" alt="{$accept}" src="{$CFG->wwwroot}/pix/t/clear.gif"/>
374 $deleteaction = 'delete';
376 if ($type->state == LTI_TOOL_STATE_CONFIGURED) {
380 if ($type->state != LTI_TOOL_STATE_REJECTED) {
381 $deleteaction = 'reject';
382 $delete = get_string('reject', 'lti');
398 <a class="editing_update" href="{$CFG->wwwroot}/mod/lti/typessettings.php?action=update&id={$type->id}&sesskey={$USER->sesskey}&tab={$id}" title="{$update}">
399 <img class="iconsmall" alt="{$update}" src="{$CFG->wwwroot}/pix/t/edit.gif"/>
401 <a class="editing_delete" href="{$CFG->wwwroot}/mod/lti/typessettings.php?action={$deleteaction}&id={$type->id}&sesskey={$USER->sesskey}&tab={$id}" title="{$delete}">
402 <img class="iconsmall" alt="{$delete}" src="{$CFG->wwwroot}/pix/t/delete.gif"/>
408 $html .= '</table></div>';
410 $html .= get_string('no_' . $id, 'lti');
417 * Splits the custom parameters field to the various parameters
419 * @param string $customstr String containing the parameters
421 * @return Array of custom parameters
423 function lti_split_custom_parameters($customstr) {
424 $textlib = textlib_get_instance();
426 $lines = preg_split("/[\n;]/", $customstr);
428 foreach ($lines as $line) {
429 $pos = strpos($line, "=");
430 if ( $pos === false || $pos < 1 ) {
433 $key = trim($textlib->substr($line, 0, $pos));
434 $val = trim($textlib->substr($line, $pos+1));
435 $key = lti_map_keyname($key);
436 $retval['custom_'.$key] = $val;
442 * Used for building the names of the different custom parameters
444 * @param string $key Parameter name
446 * @return string Processed name
448 function lti_map_keyname($key) {
449 $textlib = textlib_get_instance();
452 $key = $textlib->strtolower(trim($key));
453 foreach (str_split($key) as $ch) {
454 if ( ($ch >= 'a' && $ch <= 'z') || ($ch >= '0' && $ch <= '9') ) {
464 * Gets the IMS role string for the specified user and LTI course module.
466 * @param mixed $user User object or user id
467 * @param int $cmid The course module id of the LTI activity
468 * @return string A role string suitable for passing with an LTI launch
470 function lti_get_ims_role($user, $cmid, $courseid) {
474 //If no cmid is passed, check if the user is a teacher in the course
475 //This allows other modules to programmatically "fake" a launch without
476 //a real LTI instance
477 $coursecontext = get_context_instance(CONTEXT_COURSE, $courseid);
479 if (has_capability('moodle/course:manageactivities', $coursecontext)) {
480 array_push($roles, 'Instructor');
482 array_push($roles, 'Learner');
485 $context = get_context_instance(CONTEXT_MODULE, $cmid);
487 if (has_capability('mod/lti:manage', $context)) {
488 array_push($roles, 'Instructor');
490 array_push($roles, 'Learner');
494 if (is_siteadmin($user)) {
495 array_push($roles, 'urn:lti:sysrole:ims/lis/Administrator');
498 return join(',', $roles);
502 * Returns configuration details for the tool
504 * @param int $typeid Basic LTI tool typeid
506 * @return array Tool Configuration
508 function lti_get_type_config($typeid) {
513 FROM {lti_types_config}
514 WHERE typeid = :typeid1
518 SELECT 'toolurl' AS name, baseurl AS value
523 $typeconfig = array();
524 $configs = $DB->get_records_sql($query, array('typeid1' => $typeid, 'typeid2' => $typeid));
526 if (!empty($configs)) {
527 foreach ($configs as $config) {
528 $typeconfig[$config->name] = $config->value;
535 function lti_get_tools_by_url($url, $state, $courseid = null) {
536 $domain = lti_get_domain_from_url($url);
538 return lti_get_tools_by_domain($domain, $state, $courseid);
541 function lti_get_tools_by_domain($domain, $state = null, $courseid = null) {
544 $filters = array('tooldomain' => $domain);
550 $statefilter = 'AND state = :state';
553 if ($courseid && $courseid != $SITE->id) {
554 $coursefilter = 'OR course = :courseid';
558 SELECT * FROM {lti_types}
560 tooldomain = :tooldomain
561 AND (course = :siteid $coursefilter)
565 return $DB->get_records_sql($query, array(
566 'courseid' => $courseid,
567 'siteid' => $SITE->id,
568 'tooldomain' => $domain,
574 * Returns all basicLTI tools configured by the administrator
577 function lti_filter_get_types($course) {
580 if (!empty($course)) {
581 $filter = array('course' => $course);
586 return $DB->get_records('lti_types', $filter);
589 function lti_get_types_for_add_instance() {
590 global $DB, $SITE, $COURSE;
597 AND (course = :siteid OR course = :courseid)
601 $admintypes = $DB->get_records_sql($query, array('siteid' => $SITE->id, 'courseid' => $COURSE->id, 'active' => LTI_TOOL_STATE_CONFIGURED));
604 $types[0] = (object)array('name' => get_string('automatic', 'lti'), 'course' => $SITE->id);
606 foreach ($admintypes as $type) {
607 $types[$type->id] = $type;
613 function lti_get_domain_from_url($url) {
616 if (preg_match(LTI_URL_DOMAIN_REGEX, $url, $matches)) {
621 function lti_get_tool_by_url_match($url, $courseid = null, $state = LTI_TOOL_STATE_CONFIGURED) {
622 $possibletools = lti_get_tools_by_url($url, $state, $courseid);
624 return lti_get_best_tool_by_url($url, $possibletools, $courseid);
627 function lti_get_url_thumbprint($url) {
628 $urlparts = parse_url(strtolower($url));
629 if (!isset($urlparts['path'])) {
630 $urlparts['path'] = '';
633 if (!isset($urlparts['host'])) {
634 $urlparts['host'] = '';
637 if (substr($urlparts['host'], 0, 4) === 'www.') {
638 $urlparts['host'] = substr($urlparts['host'], 4);
641 return $urllower = $urlparts['host'] . '/' . $urlparts['path'];
644 function lti_get_best_tool_by_url($url, $tools, $courseid = null) {
645 if (count($tools) === 0) {
649 $urllower = lti_get_url_thumbprint($url);
651 foreach ($tools as $tool) {
652 $tool->_matchscore = 0;
654 $toolbaseurllower = lti_get_url_thumbprint($tool->baseurl);
656 if ($urllower === $toolbaseurllower) {
657 //100 points for exact thumbprint match
658 $tool->_matchscore += 100;
659 } else if (substr($urllower, 0, strlen($toolbaseurllower)) === $toolbaseurllower) {
660 //50 points if tool thumbprint starts with the base URL thumbprint
661 $tool->_matchscore += 50;
664 //Prefer course tools over site tools
665 if (!empty($courseid)) {
666 //Minus 25 points for not matching the course id (global tools)
667 if ($tool->course != $courseid) {
668 $tool->_matchscore -= 10;
673 $bestmatch = array_reduce($tools, function($value, $tool) {
674 if ($tool->_matchscore > $value->_matchscore) {
680 }, (object)array('_matchscore' => -1));
682 //None of the tools are suitable for this URL
683 if ($bestmatch->_matchscore <= 0) {
690 function lti_get_shared_secrets_by_key($key) {
693 //Look up the shared secret for the specified key in both the types_config table (for configured tools)
694 //And in the lti resource table for ad-hoc tools
697 FROM {lti_types_config} t1
698 INNER JOIN {lti_types_config} t2 ON t1.typeid = t2.typeid
699 INNER JOIN {lti_types} type ON t2.typeid = type.id
701 t1.name = 'resourcekey'
703 AND t2.name = 'password'
704 AND type.state = :configured
708 SELECT password AS value
710 WHERE resourcekey = :key2
713 $sharedsecrets = $DB->get_records_sql($query, array('configured' => LTI_TOOL_STATE_CONFIGURED, 'key1' => $key, 'key2' => $key));
715 $values = array_map(function($item) {
719 //There should really only be one shared secret per key. But, we can't prevent
720 //more than one getting entered. For instance, if the same key is used for two tool providers.
725 * Prints the various configured tool types
728 function lti_filter_print_types() {
731 $types = lti_filter_get_types();
732 if (!empty($types)) {
734 foreach ($types as $type) {
737 '<span class="commands">'.
738 '<a class="editing_update" href="typessettings.php?action=update&id='.$type->id.'&sesskey='.sesskey().'" title="Update">'.
739 '<img class="iconsmall" alt="Update" src="'.$CFG->wwwroot.'/pix/t/edit.gif"/>'.
741 '<a class="editing_delete" href="typessettings.php?action=delete&id='.$type->id.'&sesskey='.sesskey().'" title="Delete">'.
742 '<img class="iconsmall" alt="Delete" src="'.$CFG->wwwroot.'/pix/t/delete.gif"/>'.
750 echo '<div class="message">';
751 echo get_string('notypes', 'lti');
757 * Delete a Basic LTI configuration
759 * @param int $id Configuration id
761 function lti_delete_type($id) {
764 //We should probably just copy the launch URL to the tool instances in this case... using a single query
766 $instances = $DB->get_records('lti', array('typeid' => $id));
767 foreach ($instances as $instance) {
768 $instance->typeid = 0;
769 $DB->update_record('lti', $instance);
772 $DB->delete_records('lti_types', array('id' => $id));
773 $DB->delete_records('lti_types_config', array('typeid' => $id));
776 function lti_set_state_for_type($id, $state) {
779 $DB->update_record('lti_types', array('id' => $id, 'state' => $state));
783 * Transforms a basic LTI object to an array
785 * @param object $ltiobject Basic LTI object
787 * @return array Basic LTI configuration details
789 function lti_get_config($ltiobject) {
790 $typeconfig = array();
791 $typeconfig = (array)$ltiobject;
792 $additionalconfig = lti_get_type_config($ltiobject->typeid);
793 $typeconfig = array_merge($typeconfig, $additionalconfig);
799 * Generates some of the tool configuration based on the instance details
803 * @return Instance configuration
806 function lti_get_type_config_from_instance($id) {
809 $instance = $DB->get_record('lti', array('id' => $id));
810 $config = lti_get_config($instance);
812 $type = new stdClass();
813 $type->lti_fix = $id;
814 if (isset($config['toolurl'])) {
815 $type->lti_toolurl = $config['toolurl'];
817 if (isset($config['instructorchoicesendname'])) {
818 $type->lti_sendname = $config['instructorchoicesendname'];
820 if (isset($config['instructorchoicesendemailaddr'])) {
821 $type->lti_sendemailaddr = $config['instructorchoicesendemailaddr'];
823 if (isset($config['instructorchoiceacceptgrades'])) {
824 $type->lti_acceptgrades = $config['instructorchoiceacceptgrades'];
826 if (isset($config['instructorchoiceallowroster'])) {
827 $type->lti_allowroster = $config['instructorchoiceallowroster'];
830 if (isset($config['instructorcustomparameters'])) {
831 $type->lti_allowsetting = $config['instructorcustomparameters'];
837 * Generates some of the tool configuration based on the admin configuration details
841 * @return Configuration details
843 function lti_get_type_type_config($id) {
846 $basicltitype = $DB->get_record('lti_types', array('id' => $id));
847 $config = lti_get_type_config($id);
849 $type->lti_typename = $basicltitype->name;
851 $type->typeid = $basicltitype->id;
853 $type->lti_toolurl = $basicltitype->baseurl;
855 if (isset($config['resourcekey'])) {
856 $type->lti_resourcekey = $config['resourcekey'];
858 if (isset($config['password'])) {
859 $type->lti_password = $config['password'];
862 if (isset($config['sendname'])) {
863 $type->lti_sendname = $config['sendname'];
865 if (isset($config['instructorchoicesendname'])) {
866 $type->lti_instructorchoicesendname = $config['instructorchoicesendname'];
868 if (isset($config['sendemailaddr'])) {
869 $type->lti_sendemailaddr = $config['sendemailaddr'];
871 if (isset($config['instructorchoicesendemailaddr'])) {
872 $type->lti_instructorchoicesendemailaddr = $config['instructorchoicesendemailaddr'];
874 if (isset($config['acceptgrades'])) {
875 $type->lti_acceptgrades = $config['acceptgrades'];
877 if (isset($config['instructorchoiceacceptgrades'])) {
878 $type->lti_instructorchoiceacceptgrades = $config['instructorchoiceacceptgrades'];
880 if (isset($config['allowroster'])) {
881 $type->lti_allowroster = $config['allowroster'];
883 if (isset($config['instructorchoiceallowroster'])) {
884 $type->lti_instructorchoiceallowroster = $config['instructorchoiceallowroster'];
887 if (isset($config['customparameters'])) {
888 $type->lti_customparameters = $config['customparameters'];
891 if (isset($config['forcessl'])) {
892 $type->lti_forcessl = $config['forcessl'];
895 if (isset($config['organizationid'])) {
896 $type->lti_organizationid = $config['organizationid'];
898 if (isset($config['organizationurl'])) {
899 $type->lti_organizationurl = $config['organizationurl'];
901 if (isset($config['organizationdescr'])) {
902 $type->lti_organizationdescr = $config['organizationdescr'];
904 if (isset($config['launchcontainer'])) {
905 $type->lti_launchcontainer = $config['launchcontainer'];
908 if (isset($config['coursevisible'])) {
909 $type->lti_coursevisible = $config['coursevisible'];
912 if (isset($config['debuglaunch'])) {
913 $type->lti_debuglaunch = $config['debuglaunch'];
916 if (isset($config['module_class_type'])) {
917 $type->lti_module_class_type = $config['module_class_type'];
923 function lti_prepare_type_for_save($type, $config) {
924 $type->baseurl = $config->lti_toolurl;
925 $type->tooldomain = lti_get_domain_from_url($config->lti_toolurl);
926 $type->name = $config->lti_typename;
928 $type->coursevisible = !empty($config->lti_coursevisible) ? $config->lti_coursevisible : 0;
929 $config->lti_coursevisible = $type->coursevisible;
931 $type->forcessl = !empty($config->lti_forcessl) ? $config->lti_forcessl : 0;
932 $config->lti_forcessl = $type->forcessl;
934 $type->timemodified = time();
936 unset ($config->lti_typename);
937 unset ($config->lti_toolurl);
940 function lti_update_type($type, $config) {
943 lti_prepare_type_for_save($type, $config);
945 if ($DB->update_record('lti_types', $type)) {
946 foreach ($config as $key => $value) {
947 if (substr($key, 0, 4)=='lti_' && !is_null($value)) {
948 $record = new StdClass();
949 $record->typeid = $type->id;
950 $record->name = substr($key, 4);
951 $record->value = $value;
953 lti_update_config($record);
959 function lti_add_type($type, $config) {
960 global $USER, $SITE, $DB;
962 lti_prepare_type_for_save($type, $config);
964 if (!isset($type->state)) {
965 $type->state = LTI_TOOL_STATE_PENDING;
968 if (!isset($type->timecreated)) {
969 $type->timecreated = time();
972 if (!isset($type->createdby)) {
973 $type->createdby = $USER->id;
976 if (!isset($type->course)) {
977 $type->course = $SITE->id;
980 //Create a salt value to be used for signing passed data to extension services
981 //The outcome service uses the service salt on the instance. This can be used
982 //for communication with services not related to a specific LTI instance.
983 $config->lti_servicesalt = uniqid('', true);
985 $id = $DB->insert_record('lti_types', $type);
988 foreach ($config as $key => $value) {
989 if (substr($key, 0, 4)=='lti_' && !is_null($value)) {
990 $record = new StdClass();
991 $record->typeid = $id;
992 $record->name = substr($key, 4);
993 $record->value = $value;
995 lti_add_config($record);
1004 * Add a tool configuration in the database
1006 * @param $config Tool configuration
1008 * @return int Record id number
1010 function lti_add_config($config) {
1013 return $DB->insert_record('lti_types_config', $config);
1017 * Updates a tool configuration in the database
1019 * @param $config Tool configuration
1021 * @return Record id number
1023 function lti_update_config($config) {
1027 $old = $DB->get_record('lti_types_config', array('typeid' => $config->typeid, 'name' => $config->name));
1030 $config->id = $old->id;
1031 $return = $DB->update_record('lti_types_config', $config);
1033 $return = $DB->insert_record('lti_types_config', $config);
1039 * Signs the petition to launch the external tool using OAuth
1041 * @param $oldparms Parameters to be passed for signing
1042 * @param $endpoint url of the external tool
1043 * @param $method Method for sending the parameters (e.g. POST)
1044 * @param $oauth_consumoer_key Key
1045 * @param $oauth_consumoer_secret Secret
1046 * @param $submittext The text for the submit button
1047 * @param $orgid LMS name
1048 * @param $orgdesc LMS key
1050 function lti_sign_parameters($oldparms, $endpoint, $method, $oauthconsumerkey, $oauthconsumersecret) {
1051 //global $lastbasestring;
1056 // TODO: Switch to core oauthlib once implemented - MDL-30149
1057 $hmacmethod = new lti\OAuthSignatureMethod_HMAC_SHA1();
1058 $testconsumer = new lti\OAuthConsumer($oauthconsumerkey, $oauthconsumersecret, null);
1059 $accreq = lti\OAuthRequest::from_consumer_and_token($testconsumer, $testtoken, $method, $endpoint, $parms);
1060 $accreq->sign_request($hmacmethod, $testconsumer, $testtoken);
1062 // Pass this back up "out of band" for debugging
1063 //$lastbasestring = $accreq->get_signature_base_string();
1065 $newparms = $accreq->get_parameters();
1071 * Posts the launch petition HTML
1073 * @param $newparms Signed parameters
1074 * @param $endpoint URL of the external tool
1075 * @param $debug Debug (true/false)
1077 function lti_post_launch_html($newparms, $endpoint, $debug=false) {
1078 //global $lastbasestring;
1080 $r = "<form action=\"".$endpoint."\" name=\"ltiLaunchForm\" id=\"ltiLaunchForm\" method=\"post\" encType=\"application/x-www-form-urlencoded\">\n";
1082 $submittext = $newparms['ext_submit'];
1084 // Contruct html for the launch parameters
1085 foreach ($newparms as $key => $value) {
1086 $key = htmlspecialchars($key);
1087 $value = htmlspecialchars($value);
1088 if ( $key == "ext_submit" ) {
1089 $r .= "<input type=\"submit\" name=\"";
1091 $r .= "<input type=\"hidden\" name=\"";
1094 $r .= "\" value=\"";
1100 $r .= "<script language=\"javascript\"> \n";
1101 $r .= " //<![CDATA[ \n";
1102 $r .= "function basicltiDebugToggle() {\n";
1103 $r .= " var ele = document.getElementById(\"basicltiDebug\");\n";
1104 $r .= " if (ele.style.display == \"block\") {\n";
1105 $r .= " ele.style.display = \"none\";\n";
1108 $r .= " ele.style.display = \"block\";\n";
1112 $r .= "</script>\n";
1113 $r .= "<a id=\"displayText\" href=\"javascript:basicltiDebugToggle();\">";
1114 $r .= get_string("toggle_debug_data", "lti")."</a>\n";
1115 $r .= "<div id=\"basicltiDebug\" style=\"display:none\">\n";
1116 $r .= "<b>".get_string("basiclti_endpoint", "lti")."</b><br/>\n";
1117 $r .= $endpoint . "<br/>\n <br/>\n";
1118 $r .= "<b>".get_string("basiclti_parameters", "lti")."</b><br/>\n";
1119 foreach ($newparms as $key => $value) {
1120 $key = htmlspecialchars($key);
1121 $value = htmlspecialchars($value);
1122 $r .= "$key = $value<br/>\n";
1124 $r .= " <br/>\n";
1125 //$r .= "<p><b>".get_string("basiclti_base_string", "lti")."</b><br/>\n".$lastbasestring."</p>\n";
1131 $ext_submit = "ext_submit";
1132 $ext_submit_text = $submittext;
1133 $r .= " <script type=\"text/javascript\"> \n" .
1135 " document.getElementById(\"ltiLaunchForm\").style.display = \"none\";\n" .
1136 " nei = document.createElement('input');\n" .
1137 " nei.setAttribute('type', 'hidden');\n" .
1138 " nei.setAttribute('name', '".$ext_submit."');\n" .
1139 " nei.setAttribute('value', '".$ext_submit_text."');\n" .
1140 " document.getElementById(\"ltiLaunchForm\").appendChild(nei);\n" .
1141 " document.ltiLaunchForm.submit(); \n" .
1148 function lti_get_type($typeid) {
1151 return $DB->get_record('lti_types', array('id' => $typeid));
1154 function lti_get_launch_container($lti, $toolconfig) {
1155 if (empty($lti->launchcontainer)) {
1156 $lti->launchcontainer = LTI_LAUNCH_CONTAINER_DEFAULT;
1159 if ($lti->launchcontainer == LTI_LAUNCH_CONTAINER_DEFAULT) {
1160 if (isset($toolconfig['launchcontainer'])) {
1161 $launchcontainer = $toolconfig['launchcontainer'];
1164 $launchcontainer = $lti->launchcontainer;
1167 if (empty($launchcontainer) || $launchcontainer == LTI_LAUNCH_CONTAINER_DEFAULT) {
1168 $launchcontainer = LTI_LAUNCH_CONTAINER_EMBED_NO_BLOCKS;
1171 $devicetype = get_device_type();
1173 //Scrolling within the object element doesn't work on iOS or Android
1174 //Opening the popup window also had some issues in testing
1175 //For mobile devices, always take up the entire screen to ensure the best experience
1176 if ($devicetype === 'mobile' || $devicetype === 'tablet' ) {
1177 $launchcontainer = LTI_LAUNCH_CONTAINER_REPLACE_MOODLE_WINDOW;
1180 return $launchcontainer;
1183 function lti_request_is_using_ssl() {
1185 return (stripos($ME, 'https://') === 0);
1188 function lti_ensure_url_is_https($url) {
1189 if (!strstr($url, '://')) {
1190 $url = 'https://' . $url;
1192 //If the URL starts with http, replace with https
1193 if (stripos($url, 'http://') === 0) {
1194 $url = 'https://' . substr($url, 8);