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 * @author Chris Scribner
47 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
50 defined('MOODLE_INTERNAL') || die;
52 // TODO: Switch to core oauthlib once implemented - MDL-30149
53 use moodle\mod\lti as lti;
55 require_once($CFG->dirroot.'/mod/lti/OAuth.php');
57 define('LTI_URL_DOMAIN_REGEX', '/(?:https?:\/\/)?(?:www\.)?([^\/]+)(?:\/|$)/i');
59 define('LTI_LAUNCH_CONTAINER_DEFAULT', 1);
60 define('LTI_LAUNCH_CONTAINER_EMBED', 2);
61 define('LTI_LAUNCH_CONTAINER_EMBED_NO_BLOCKS', 3);
62 define('LTI_LAUNCH_CONTAINER_WINDOW', 4);
63 define('LTI_LAUNCH_CONTAINER_REPLACE_MOODLE_WINDOW', 5);
65 define('LTI_TOOL_STATE_ANY', 0);
66 define('LTI_TOOL_STATE_CONFIGURED', 1);
67 define('LTI_TOOL_STATE_PENDING', 2);
68 define('LTI_TOOL_STATE_REJECTED', 3);
70 define('LTI_SETTING_NEVER', 0);
71 define('LTI_SETTING_ALWAYS', 1);
72 define('LTI_SETTING_DELEGATE', 2);
75 * Prints a Basic LTI activity
77 * $param int $basicltiid Basic LTI activity id
79 function lti_view($instance) {
82 if (empty($instance->typeid)) {
83 $tool = lti_get_tool_by_url_match($instance->toolurl, $instance->course);
90 $typeid = $instance->typeid;
94 $typeconfig = lti_get_type_config($typeid);
96 //There is no admin configuration for this tool. Use configuration in the lti instance record plus some defaults.
97 $typeconfig = (array)$instance;
99 $typeconfig['sendname'] = $instance->instructorchoicesendname;
100 $typeconfig['sendemailaddr'] = $instance->instructorchoicesendemailaddr;
101 $typeconfig['customparameters'] = $instance->instructorcustomparameters;
102 $typeconfig['acceptgrades'] = $instance->instructorchoiceacceptgrades;
103 $typeconfig['allowroster'] = $instance->instructorchoiceallowroster;
104 $typeconfig['forcessl'] = '0';
107 //Default the organizationid if not specified
108 if (empty($typeconfig['organizationid'])) {
109 $urlparts = parse_url($CFG->wwwroot);
111 $typeconfig['organizationid'] = $urlparts['host'];
114 if (!empty($instance->resourcekey)) {
115 $key = $instance->resourcekey;
116 } else if (!empty($typeconfig['resourcekey'])) {
117 $key = $typeconfig['resourcekey'];
122 if (!empty($instance->password)) {
123 $secret = $instance->password;
124 } else if (!empty($typeconfig['password'])) {
125 $secret = $typeconfig['password'];
130 $endpoint = !empty($instance->toolurl) ? $instance->toolurl : $typeconfig['toolurl'];
131 $endpoint = trim($endpoint);
133 //If the current request is using SSL and a secure tool URL is specified, use it
134 if (lti_request_is_using_ssl() && !empty($instance->securetoolurl)) {
135 $endpoint = trim($instance->securetoolurl);
138 //If SSL is forced, use the secure tool url if specified. Otherwise, make sure https is on the normal launch URL.
139 if ($typeconfig['forcessl'] == '1') {
140 if (!empty($instance->securetoolurl)) {
141 $endpoint = trim($instance->securetoolurl);
144 $endpoint = lti_ensure_url_is_https($endpoint);
146 if (!strstr($endpoint, '://')) {
147 $endpoint = 'http://' . $endpoint;
151 $orgid = $typeconfig['organizationid'];
153 $course = $PAGE->course;
154 $requestparams = lti_build_request($instance, $typeconfig, $course);
156 $launchcontainer = lti_get_launch_container($instance, $typeconfig);
157 $returnurlparams = array('course' => $course->id, 'launch_container' => $launchcontainer, 'instanceid' => $instance->id);
160 $requestparams["tool_consumer_instance_guid"] = $orgid;
163 if (empty($key) || empty($secret)) {
164 $returnurlparams['unsigned'] = '1';
167 // Add the return URL. We send the launch container along to help us avoid frames-within-frames when the user returns.
168 $url = new moodle_url('/mod/lti/return.php', $returnurlparams);
169 $returnurl = $url->out(false);
171 if ($typeconfig['forcessl'] == '1') {
172 $returnurl = lti_ensure_url_is_https($returnurl);
175 $requestparams['launch_presentation_return_url'] = $returnurl;
177 if (!empty($key) && !empty($secret)) {
178 $parms = lti_sign_parameters($requestparams, $endpoint, "POST", $key, $secret);
180 $endpointurl = new moodle_url($endpoint);
181 $endpointparams = $endpointurl->params();
183 // Strip querystring params in endpoint url from $parms to avoid duplication.
184 if (!empty($endpointparams) && !empty($parms)) {
185 foreach (array_keys($endpointparams) as $paramname) {
186 if (isset($parms[$paramname])) {
187 unset($parms[$paramname]);
193 //If no key and secret, do the launch unsigned.
194 $parms = $requestparams;
197 $debuglaunch = ( $instance->debuglaunch == 1 );
199 $content = lti_post_launch_html($parms, $endpoint, $debuglaunch);
204 function lti_build_sourcedid($instanceid, $userid, $launchid = null, $servicesalt) {
205 $data = new stdClass();
207 $data->instanceid = $instanceid;
208 $data->userid = $userid;
209 if (!empty($launchid)) {
210 $data->launchid = $launchid;
212 $data->launchid = mt_rand();
215 $json = json_encode($data);
217 $hash = hash('sha256', $json . $servicesalt, false);
219 $container = new stdClass();
220 $container->data = $data;
221 $container->hash = $hash;
227 * This function builds the request that must be sent to the tool producer
229 * @param object $instance Basic LTI instance object
230 * @param object $typeconfig Basic LTI tool configuration
231 * @param object $course Course object
233 * @return array $request Request details
235 function lti_build_request($instance, $typeconfig, $course) {
238 if (empty($instance->cmid)) {
242 $role = lti_get_ims_role($USER, $instance->cmid, $instance->course);
244 $requestparams = array(
245 'resource_link_id' => $instance->id,
246 'resource_link_title' => $instance->name,
247 'resource_link_description' => $instance->intro,
248 'user_id' => $USER->id,
250 'context_id' => $course->id,
251 'context_label' => $course->shortname,
252 'context_title' => $course->fullname,
253 'launch_presentation_locale' => current_language()
256 $placementsecret = $instance->servicesalt;
258 if ( isset($placementsecret) ) {
259 $sourcedid = json_encode(lti_build_sourcedid($instance->id, $USER->id, null, $placementsecret));
262 if ( isset($placementsecret) &&
263 ( $typeconfig['acceptgrades'] == LTI_SETTING_ALWAYS ||
264 ( $typeconfig['acceptgrades'] == LTI_SETTING_DELEGATE && $instance->instructorchoiceacceptgrades == LTI_SETTING_ALWAYS ) ) ) {
265 $requestparams['lis_result_sourcedid'] = $sourcedid;
267 //Add outcome service URL
268 $serviceurl = new moodle_url('/mod/lti/service.php');
269 $serviceurl = $serviceurl->out();
271 if ($typeconfig['forcessl'] == '1') {
272 $serviceurl = lti_ensure_url_is_https($serviceurl);
275 $requestparams['lis_outcome_service_url'] = $serviceurl;
278 // Send user's name and email data if appropriate
279 if ( $typeconfig['sendname'] == LTI_SETTING_ALWAYS ||
280 ( $typeconfig['sendname'] == LTI_SETTING_DELEGATE && $instance->instructorchoicesendname == LTI_SETTING_ALWAYS ) ) {
281 $requestparams['lis_person_name_given'] = $USER->firstname;
282 $requestparams['lis_person_name_family'] = $USER->lastname;
283 $requestparams['lis_person_name_full'] = $USER->firstname." ".$USER->lastname;
286 if ( $typeconfig['sendemailaddr'] == LTI_SETTING_ALWAYS ||
287 ( $typeconfig['sendemailaddr'] == LTI_SETTING_DELEGATE && $instance->instructorchoicesendemailaddr == LTI_SETTING_ALWAYS ) ) {
288 $requestparams['lis_person_contact_email_primary'] = $USER->email;
291 // Concatenate the custom parameters from the administrator and the instructor
292 // Instructor parameters are only taken into consideration if the administrator
293 // has giver permission
294 $customstr = $typeconfig['customparameters'];
295 $instructorcustomstr = $instance->instructorcustomparameters;
297 $instructorcustom = array();
299 $custom = lti_split_custom_parameters($customstr);
301 if (isset($typeconfig['allowinstructorcustom']) && $typeconfig['allowinstructorcustom'] == LTI_SETTING_NEVER) {
302 $requestparams = array_merge($custom, $requestparams);
304 if ($instructorcustomstr) {
305 $instructorcustom = lti_split_custom_parameters($instructorcustomstr);
307 foreach ($instructorcustom as $key => $val) {
308 // Ignore the instructor's parameter
309 if (!array_key_exists($key, $custom)) {
310 $custom[$key] = $val;
313 $requestparams = array_merge($custom, $requestparams);
316 // Make sure we let the tool know what LMS they are being called from
317 $requestparams["ext_lms"] = "moodle-2";
318 $requestparams['tool_consumer_info_product_family_code'] = 'moodle';
319 $requestparams['tool_consumer_info_version'] = strval($CFG->version);
321 // Add oauth_callback to be compliant with the 1.0A spec
322 $requestparams['oauth_callback'] = 'about:blank';
324 //The submit button needs to be part of the signature as it gets posted with the form.
325 //This needs to be here to support launching without javascript.
326 $submittext = get_string('press_to_submit', 'lti');
327 $requestparams['ext_submit'] = $submittext;
329 $requestparams['lti_version'] = 'LTI-1p0';
330 $requestparams['lti_message_type'] = 'basic-lti-launch-request';
332 return $requestparams;
335 function lti_get_tool_table($tools, $id) {
336 global $CFG, $OUTPUT, $USER;
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 $baseurl = new moodle_url('/mod/lti/typessettings.php', array(
369 'action' => 'accept',
371 'sesskey' => sesskey(),
375 $accepthtml = $OUTPUT->action_icon($baseurl,
376 new pix_icon('t/check', $accept, '', array('class' => 'iconsmall')), null,
377 array('title' => $accept, 'class' => 'editing_accept'));
379 $deleteaction = 'delete';
381 if ($type->state == LTI_TOOL_STATE_CONFIGURED) {
385 if ($type->state != LTI_TOOL_STATE_REJECTED) {
386 $deleteaction = 'reject';
387 $delete = get_string('reject', 'lti');
390 $updateurl = clone($baseurl);
391 $updateurl->param('action', 'update');
392 $updatehtml = $OUTPUT->action_icon($updateurl,
393 new pix_icon('t/edit', $update, '', array('class' => 'iconsmall')), null,
394 array('title' => $update, 'class' => 'editing_update'));
396 $deleteurl = clone($baseurl);
397 $deleteurl->param('action', $deleteaction);
398 $deletehtml = $OUTPUT->action_icon($deleteurl,
399 new pix_icon('t/delete', $delete, '', array('class' => 'iconsmall')), null,
400 array('title' => $delete, 'class' => 'editing_delete'));
412 <td align=\"center\">
413 {$accepthtml}{$updatehtml}{$deletehtml}
418 $html .= '</table></div>';
420 $html .= get_string('no_' . $id, 'lti');
427 * Splits the custom parameters field to the various parameters
429 * @param string $customstr String containing the parameters
431 * @return Array of custom parameters
433 function lti_split_custom_parameters($customstr) {
434 $lines = preg_split("/[\n;]/", $customstr);
436 foreach ($lines as $line) {
437 $pos = strpos($line, "=");
438 if ( $pos === false || $pos < 1 ) {
441 $key = trim(core_text::substr($line, 0, $pos));
442 $val = trim(core_text::substr($line, $pos+1, strlen($line)));
443 $key = lti_map_keyname($key);
444 $retval['custom_'.$key] = $val;
450 * Used for building the names of the different custom parameters
452 * @param string $key Parameter name
454 * @return string Processed name
456 function lti_map_keyname($key) {
458 $key = core_text::strtolower(trim($key));
459 foreach (str_split($key) as $ch) {
460 if ( ($ch >= 'a' && $ch <= 'z') || ($ch >= '0' && $ch <= '9') ) {
470 * Gets the IMS role string for the specified user and LTI course module.
472 * @param mixed $user User object or user id
473 * @param int $cmid The course module id of the LTI activity
474 * @return string A role string suitable for passing with an LTI launch
476 function lti_get_ims_role($user, $cmid, $courseid) {
480 //If no cmid is passed, check if the user is a teacher in the course
481 //This allows other modules to programmatically "fake" a launch without
482 //a real LTI instance
483 $coursecontext = context_course::instance($courseid);
485 if (has_capability('moodle/course:manageactivities', $coursecontext)) {
486 array_push($roles, 'Instructor');
488 array_push($roles, 'Learner');
491 $context = context_module::instance($cmid);
493 if (has_capability('mod/lti:manage', $context)) {
494 array_push($roles, 'Instructor');
496 array_push($roles, 'Learner');
500 if (is_siteadmin($user)) {
501 array_push($roles, 'urn:lti:sysrole:ims/lis/Administrator');
504 return join(',', $roles);
508 * Returns configuration details for the tool
510 * @param int $typeid Basic LTI tool typeid
512 * @return array Tool Configuration
514 function lti_get_type_config($typeid) {
517 $query = "SELECT name, value
518 FROM {lti_types_config}
519 WHERE typeid = :typeid1
521 SELECT 'toolurl' AS name, " . $DB->sql_compare_text('baseurl', 1333) . " AS value
523 WHERE id = :typeid2";
525 $typeconfig = array();
526 $configs = $DB->get_records_sql($query, array('typeid1' => $typeid, 'typeid2' => $typeid));
528 if (!empty($configs)) {
529 foreach ($configs as $config) {
530 $typeconfig[$config->name] = $config->value;
537 function lti_get_tools_by_url($url, $state, $courseid = null) {
538 $domain = lti_get_domain_from_url($url);
540 return lti_get_tools_by_domain($domain, $state, $courseid);
543 function lti_get_tools_by_domain($domain, $state = null, $courseid = null) {
546 $filters = array('tooldomain' => $domain);
552 $statefilter = 'AND state = :state';
555 if ($courseid && $courseid != $SITE->id) {
556 $coursefilter = 'OR course = :courseid';
561 WHERE tooldomain = :tooldomain
562 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);
590 * Given an array of tools, filter them based on their state
592 * @param array $tools An array of lti_types records
593 * @param int $state One of the LTI_TOOL_STATE_* constants
596 function lti_filter_tool_types(array $tools, $state) {
598 foreach ($tools as $key => $tool) {
599 if ($tool->state == $state) {
600 $return[$key] = $tool;
606 function lti_get_types_for_add_instance() {
607 global $DB, $SITE, $COURSE;
611 WHERE coursevisible = 1
612 AND (course = :siteid OR course = :courseid)
613 AND state = :active";
615 $admintypes = $DB->get_records_sql($query, array('siteid' => $SITE->id, 'courseid' => $COURSE->id, 'active' => LTI_TOOL_STATE_CONFIGURED));
618 $types[0] = (object)array('name' => get_string('automatic', 'lti'), 'course' => $SITE->id);
620 foreach ($admintypes as $type) {
621 $types[$type->id] = $type;
627 function lti_get_domain_from_url($url) {
630 if (preg_match(LTI_URL_DOMAIN_REGEX, $url, $matches)) {
635 function lti_get_tool_by_url_match($url, $courseid = null, $state = LTI_TOOL_STATE_CONFIGURED) {
636 $possibletools = lti_get_tools_by_url($url, $state, $courseid);
638 return lti_get_best_tool_by_url($url, $possibletools, $courseid);
641 function lti_get_url_thumbprint($url) {
642 $urlparts = parse_url(strtolower($url));
643 if (!isset($urlparts['path'])) {
644 $urlparts['path'] = '';
647 if (!isset($urlparts['host'])) {
648 $urlparts['host'] = '';
651 if (substr($urlparts['host'], 0, 4) === 'www.') {
652 $urlparts['host'] = substr($urlparts['host'], 4);
655 return $urllower = $urlparts['host'] . '/' . $urlparts['path'];
658 function lti_get_best_tool_by_url($url, $tools, $courseid = null) {
659 if (count($tools) === 0) {
663 $urllower = lti_get_url_thumbprint($url);
665 foreach ($tools as $tool) {
666 $tool->_matchscore = 0;
668 $toolbaseurllower = lti_get_url_thumbprint($tool->baseurl);
670 if ($urllower === $toolbaseurllower) {
671 //100 points for exact thumbprint match
672 $tool->_matchscore += 100;
673 } else if (substr($urllower, 0, strlen($toolbaseurllower)) === $toolbaseurllower) {
674 //50 points if tool thumbprint starts with the base URL thumbprint
675 $tool->_matchscore += 50;
678 //Prefer course tools over site tools
679 if (!empty($courseid)) {
680 //Minus 10 points for not matching the course id (global tools)
681 if ($tool->course != $courseid) {
682 $tool->_matchscore -= 10;
687 $bestmatch = array_reduce($tools, function($value, $tool) {
688 if ($tool->_matchscore > $value->_matchscore) {
694 }, (object)array('_matchscore' => -1));
696 //None of the tools are suitable for this URL
697 if ($bestmatch->_matchscore <= 0) {
704 function lti_get_shared_secrets_by_key($key) {
707 //Look up the shared secret for the specified key in both the types_config table (for configured tools)
708 //And in the lti resource table for ad-hoc tools
709 $query = "SELECT t2.value
710 FROM {lti_types_config} t1
711 JOIN {lti_types_config} t2 ON t1.typeid = t2.typeid
712 JOIN {lti_types} type ON t2.typeid = type.id
713 WHERE t1.name = 'resourcekey'
715 AND t2.name = 'password'
716 AND type.state = :configured
718 SELECT password AS value
720 WHERE resourcekey = :key2";
722 $sharedsecrets = $DB->get_records_sql($query, array('configured' => LTI_TOOL_STATE_CONFIGURED, 'key1' => $key, 'key2' => $key));
724 $values = array_map(function($item) {
728 //There should really only be one shared secret per key. But, we can't prevent
729 //more than one getting entered. For instance, if the same key is used for two tool providers.
734 * Delete a Basic LTI configuration
736 * @param int $id Configuration id
738 function lti_delete_type($id) {
741 //We should probably just copy the launch URL to the tool instances in this case... using a single query
743 $instances = $DB->get_records('lti', array('typeid' => $id));
744 foreach ($instances as $instance) {
745 $instance->typeid = 0;
746 $DB->update_record('lti', $instance);
749 $DB->delete_records('lti_types', array('id' => $id));
750 $DB->delete_records('lti_types_config', array('typeid' => $id));
753 function lti_set_state_for_type($id, $state) {
756 $DB->update_record('lti_types', array('id' => $id, 'state' => $state));
760 * Transforms a basic LTI object to an array
762 * @param object $ltiobject Basic LTI object
764 * @return array Basic LTI configuration details
766 function lti_get_config($ltiobject) {
767 $typeconfig = array();
768 $typeconfig = (array)$ltiobject;
769 $additionalconfig = lti_get_type_config($ltiobject->typeid);
770 $typeconfig = array_merge($typeconfig, $additionalconfig);
776 * Generates some of the tool configuration based on the instance details
780 * @return Instance configuration
783 function lti_get_type_config_from_instance($id) {
786 $instance = $DB->get_record('lti', array('id' => $id));
787 $config = lti_get_config($instance);
789 $type = new stdClass();
790 $type->lti_fix = $id;
791 if (isset($config['toolurl'])) {
792 $type->lti_toolurl = $config['toolurl'];
794 if (isset($config['instructorchoicesendname'])) {
795 $type->lti_sendname = $config['instructorchoicesendname'];
797 if (isset($config['instructorchoicesendemailaddr'])) {
798 $type->lti_sendemailaddr = $config['instructorchoicesendemailaddr'];
800 if (isset($config['instructorchoiceacceptgrades'])) {
801 $type->lti_acceptgrades = $config['instructorchoiceacceptgrades'];
803 if (isset($config['instructorchoiceallowroster'])) {
804 $type->lti_allowroster = $config['instructorchoiceallowroster'];
807 if (isset($config['instructorcustomparameters'])) {
808 $type->lti_allowsetting = $config['instructorcustomparameters'];
814 * Generates some of the tool configuration based on the admin configuration details
818 * @return Configuration details
820 function lti_get_type_type_config($id) {
823 $basicltitype = $DB->get_record('lti_types', array('id' => $id));
824 $config = lti_get_type_config($id);
826 $type = new stdClass();
828 $type->lti_typename = $basicltitype->name;
830 $type->typeid = $basicltitype->id;
832 $type->lti_toolurl = $basicltitype->baseurl;
834 if (isset($config['resourcekey'])) {
835 $type->lti_resourcekey = $config['resourcekey'];
837 if (isset($config['password'])) {
838 $type->lti_password = $config['password'];
841 if (isset($config['sendname'])) {
842 $type->lti_sendname = $config['sendname'];
844 if (isset($config['instructorchoicesendname'])) {
845 $type->lti_instructorchoicesendname = $config['instructorchoicesendname'];
847 if (isset($config['sendemailaddr'])) {
848 $type->lti_sendemailaddr = $config['sendemailaddr'];
850 if (isset($config['instructorchoicesendemailaddr'])) {
851 $type->lti_instructorchoicesendemailaddr = $config['instructorchoicesendemailaddr'];
853 if (isset($config['acceptgrades'])) {
854 $type->lti_acceptgrades = $config['acceptgrades'];
856 if (isset($config['instructorchoiceacceptgrades'])) {
857 $type->lti_instructorchoiceacceptgrades = $config['instructorchoiceacceptgrades'];
859 if (isset($config['allowroster'])) {
860 $type->lti_allowroster = $config['allowroster'];
862 if (isset($config['instructorchoiceallowroster'])) {
863 $type->lti_instructorchoiceallowroster = $config['instructorchoiceallowroster'];
866 if (isset($config['customparameters'])) {
867 $type->lti_customparameters = $config['customparameters'];
870 if (isset($config['forcessl'])) {
871 $type->lti_forcessl = $config['forcessl'];
874 if (isset($config['organizationid'])) {
875 $type->lti_organizationid = $config['organizationid'];
877 if (isset($config['organizationurl'])) {
878 $type->lti_organizationurl = $config['organizationurl'];
880 if (isset($config['organizationdescr'])) {
881 $type->lti_organizationdescr = $config['organizationdescr'];
883 if (isset($config['launchcontainer'])) {
884 $type->lti_launchcontainer = $config['launchcontainer'];
887 if (isset($config['coursevisible'])) {
888 $type->lti_coursevisible = $config['coursevisible'];
891 if (isset($config['debuglaunch'])) {
892 $type->lti_debuglaunch = $config['debuglaunch'];
895 if (isset($config['module_class_type'])) {
896 $type->lti_module_class_type = $config['module_class_type'];
902 function lti_prepare_type_for_save($type, $config) {
903 $type->baseurl = $config->lti_toolurl;
904 $type->tooldomain = lti_get_domain_from_url($config->lti_toolurl);
905 $type->name = $config->lti_typename;
907 $type->coursevisible = !empty($config->lti_coursevisible) ? $config->lti_coursevisible : 0;
908 $config->lti_coursevisible = $type->coursevisible;
910 $type->forcessl = !empty($config->lti_forcessl) ? $config->lti_forcessl : 0;
911 $config->lti_forcessl = $type->forcessl;
913 $type->timemodified = time();
915 unset ($config->lti_typename);
916 unset ($config->lti_toolurl);
919 function lti_update_type($type, $config) {
922 lti_prepare_type_for_save($type, $config);
924 if ($DB->update_record('lti_types', $type)) {
925 foreach ($config as $key => $value) {
926 if (substr($key, 0, 4)=='lti_' && !is_null($value)) {
927 $record = new StdClass();
928 $record->typeid = $type->id;
929 $record->name = substr($key, 4);
930 $record->value = $value;
932 lti_update_config($record);
938 function lti_add_type($type, $config) {
939 global $USER, $SITE, $DB;
941 lti_prepare_type_for_save($type, $config);
943 if (!isset($type->state)) {
944 $type->state = LTI_TOOL_STATE_PENDING;
947 if (!isset($type->timecreated)) {
948 $type->timecreated = time();
951 if (!isset($type->createdby)) {
952 $type->createdby = $USER->id;
955 if (!isset($type->course)) {
956 $type->course = $SITE->id;
959 //Create a salt value to be used for signing passed data to extension services
960 //The outcome service uses the service salt on the instance. This can be used
961 //for communication with services not related to a specific LTI instance.
962 $config->lti_servicesalt = uniqid('', true);
964 $id = $DB->insert_record('lti_types', $type);
967 foreach ($config as $key => $value) {
968 if (substr($key, 0, 4)=='lti_' && !is_null($value)) {
969 $record = new StdClass();
970 $record->typeid = $id;
971 $record->name = substr($key, 4);
972 $record->value = $value;
974 lti_add_config($record);
983 * Add a tool configuration in the database
985 * @param $config Tool configuration
987 * @return int Record id number
989 function lti_add_config($config) {
992 return $DB->insert_record('lti_types_config', $config);
996 * Updates a tool configuration in the database
998 * @param $config Tool configuration
1000 * @return Record id number
1002 function lti_update_config($config) {
1006 $old = $DB->get_record('lti_types_config', array('typeid' => $config->typeid, 'name' => $config->name));
1009 $config->id = $old->id;
1010 $return = $DB->update_record('lti_types_config', $config);
1012 $return = $DB->insert_record('lti_types_config', $config);
1018 * Signs the petition to launch the external tool using OAuth
1020 * @param $oldparms Parameters to be passed for signing
1021 * @param $endpoint url of the external tool
1022 * @param $method Method for sending the parameters (e.g. POST)
1023 * @param $oauth_consumoer_key Key
1024 * @param $oauth_consumoer_secret Secret
1025 * @param $submittext The text for the submit button
1026 * @param $orgid LMS name
1027 * @param $orgdesc LMS key
1029 function lti_sign_parameters($oldparms, $endpoint, $method, $oauthconsumerkey, $oauthconsumersecret) {
1030 //global $lastbasestring;
1035 // TODO: Switch to core oauthlib once implemented - MDL-30149
1036 $hmacmethod = new lti\OAuthSignatureMethod_HMAC_SHA1();
1037 $testconsumer = new lti\OAuthConsumer($oauthconsumerkey, $oauthconsumersecret, null);
1038 $accreq = lti\OAuthRequest::from_consumer_and_token($testconsumer, $testtoken, $method, $endpoint, $parms);
1039 $accreq->sign_request($hmacmethod, $testconsumer, $testtoken);
1041 // Pass this back up "out of band" for debugging
1042 //$lastbasestring = $accreq->get_signature_base_string();
1044 $newparms = $accreq->get_parameters();
1050 * Posts the launch petition HTML
1052 * @param $newparms Signed parameters
1053 * @param $endpoint URL of the external tool
1054 * @param $debug Debug (true/false)
1056 function lti_post_launch_html($newparms, $endpoint, $debug=false) {
1057 $r = "<form action=\"".$endpoint."\" name=\"ltiLaunchForm\" id=\"ltiLaunchForm\" method=\"post\" encType=\"application/x-www-form-urlencoded\">\n";
1059 $submittext = $newparms['ext_submit'];
1061 // Contruct html for the launch parameters
1062 foreach ($newparms as $key => $value) {
1063 $key = htmlspecialchars($key);
1064 $value = htmlspecialchars($value);
1065 if ( $key == "ext_submit" ) {
1066 $r .= "<input type=\"submit\" name=\"";
1068 $r .= "<input type=\"hidden\" name=\"";
1071 $r .= "\" value=\"";
1077 $r .= "<script language=\"javascript\"> \n";
1078 $r .= " //<![CDATA[ \n";
1079 $r .= "function basicltiDebugToggle() {\n";
1080 $r .= " var ele = document.getElementById(\"basicltiDebug\");\n";
1081 $r .= " if (ele.style.display == \"block\") {\n";
1082 $r .= " ele.style.display = \"none\";\n";
1085 $r .= " ele.style.display = \"block\";\n";
1089 $r .= "</script>\n";
1090 $r .= "<a id=\"displayText\" href=\"javascript:basicltiDebugToggle();\">";
1091 $r .= get_string("toggle_debug_data", "lti")."</a>\n";
1092 $r .= "<div id=\"basicltiDebug\" style=\"display:none\">\n";
1093 $r .= "<b>".get_string("basiclti_endpoint", "lti")."</b><br/>\n";
1094 $r .= $endpoint . "<br/>\n <br/>\n";
1095 $r .= "<b>".get_string("basiclti_parameters", "lti")."</b><br/>\n";
1096 foreach ($newparms as $key => $value) {
1097 $key = htmlspecialchars($key);
1098 $value = htmlspecialchars($value);
1099 $r .= "$key = $value<br/>\n";
1101 $r .= " <br/>\n";
1102 //$r .= "<p><b>".get_string("basiclti_base_string", "lti")."</b><br/>\n".$lastbasestring."</p>\n";
1108 $ext_submit = "ext_submit";
1109 $ext_submit_text = $submittext;
1110 $r .= " <script type=\"text/javascript\"> \n" .
1112 " document.getElementById(\"ltiLaunchForm\").style.display = \"none\";\n" .
1113 " nei = document.createElement('input');\n" .
1114 " nei.setAttribute('type', 'hidden');\n" .
1115 " nei.setAttribute('name', '".$ext_submit."');\n" .
1116 " nei.setAttribute('value', '".$ext_submit_text."');\n" .
1117 " document.getElementById(\"ltiLaunchForm\").appendChild(nei);\n" .
1118 " document.ltiLaunchForm.submit(); \n" .
1125 function lti_get_type($typeid) {
1128 return $DB->get_record('lti_types', array('id' => $typeid));
1131 function lti_get_launch_container($lti, $toolconfig) {
1132 if (empty($lti->launchcontainer)) {
1133 $lti->launchcontainer = LTI_LAUNCH_CONTAINER_DEFAULT;
1136 if ($lti->launchcontainer == LTI_LAUNCH_CONTAINER_DEFAULT) {
1137 if (isset($toolconfig['launchcontainer'])) {
1138 $launchcontainer = $toolconfig['launchcontainer'];
1141 $launchcontainer = $lti->launchcontainer;
1144 if (empty($launchcontainer) || $launchcontainer == LTI_LAUNCH_CONTAINER_DEFAULT) {
1145 $launchcontainer = LTI_LAUNCH_CONTAINER_EMBED_NO_BLOCKS;
1148 $devicetype = core_useragent::get_device_type();
1150 //Scrolling within the object element doesn't work on iOS or Android
1151 //Opening the popup window also had some issues in testing
1152 //For mobile devices, always take up the entire screen to ensure the best experience
1153 if ($devicetype === core_useragent::DEVICETYPE_MOBILE || $devicetype === core_useragent::DEVICETYPE_TABLET ) {
1154 $launchcontainer = LTI_LAUNCH_CONTAINER_REPLACE_MOODLE_WINDOW;
1157 return $launchcontainer;
1160 function lti_request_is_using_ssl() {
1162 return (stripos($CFG->httpswwwroot, 'https://') === 0);
1165 function lti_ensure_url_is_https($url) {
1166 if (!strstr($url, '://')) {
1167 $url = 'https://' . $url;
1169 //If the URL starts with http, replace with https
1170 if (stripos($url, 'http://') === 0) {
1171 $url = 'https://' . substr($url, 7);