2 // This file is part of BasicLTI4Moodle
4 // BasicLTI4Moodle is an IMS BasicLTI (Basic Learning Tools for Interoperability)
5 // consumer for Moodle 1.9 and Moodle 2.0. BasicLTI is a IMS Standard that allows web
6 // based learning tools to be easily integrated in LMS as native ones. The IMS BasicLTI
7 // specification is part of the IMS standard Common Cartridge 1.1 Sakai and other main LMS
8 // are already supporting or going to support BasicLTI. This project Implements the consumer
9 // for Moodle. Moodle is a Free Open source Learning Management System by Martin Dougiamas.
10 // BasicLTI4Moodle is a project iniciated and leaded by Ludo(Marc Alier) and Jordi Piguillem
11 // at the GESSI research group at UPC.
12 // SimpleLTI consumer for Moodle is an implementation of the early specification of LTI
13 // by Charles Severance (Dr Chuck) htp://dr-chuck.com , developed by Jordi Piguillem in a
14 // Google Summer of Code 2008 project co-mentored by Charles Severance and Marc Alier.
16 // BasicLTI4Moodle is copyright 2009 by Marc Alier Forment, Jordi Piguillem and Nikolas Galanis
17 // of the Universitat Politecnica de Catalunya http://www.upc.edu
18 // Contact info: Marc Alier Forment granludo @ gmail.com or marc.alier @ upc.edu
20 // Moodle is free software: you can redistribute it and/or modify
21 // it under the terms of the GNU General Public License as published by
22 // the Free Software Foundation, either version 3 of the License, or
23 // (at your option) any later version.
25 // Moodle is distributed in the hope that it will be useful,
26 // but WITHOUT ANY WARRANTY; without even the implied warranty of
27 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
28 // GNU General Public License for more details.
30 // You should have received a copy of the GNU General Public License
31 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
34 * This file contains the library of functions and constants for the basiclti module
37 * @copyright 2009 Marc Alier, Jordi Piguillem, Nikolas Galanis
39 * @copyright 2009 Universitat Politecnica de Catalunya http://www.upc.edu
42 * @author Jordi Piguillem
43 * @author Nikolas Galanis
45 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
48 defined('MOODLE_INTERNAL') || die;
50 use moodle\mod\lti as lti;
52 require_once($CFG->dirroot.'/mod/lti/OAuth.php');
54 define('LTI_URL_DOMAIN_REGEX', '/(?:https?:\/\/)?(?:www\.)?([^\/]+)(?:\/|$)/i');
56 define('LTI_LAUNCH_CONTAINER_DEFAULT', 1);
57 define('LTI_LAUNCH_CONTAINER_EMBED', 2);
58 define('LTI_LAUNCH_CONTAINER_EMBED_NO_BLOCKS', 3);
59 define('LTI_LAUNCH_CONTAINER_WINDOW', 4);
60 define('LTI_LAUNCH_CONTAINER_REPLACE_MOODLE_WINDOW', 5);
62 define('LTI_TOOL_STATE_ANY', 0);
63 define('LTI_TOOL_STATE_CONFIGURED', 1);
64 define('LTI_TOOL_STATE_PENDING', 2);
65 define('LTI_TOOL_STATE_REJECTED', 3);
67 define('LTI_SETTING_NEVER', 0);
68 define('LTI_SETTING_ALWAYS', 1);
69 define('LTI_SETTING_DELEGATE', 2);
72 * Prints a Basic LTI activity
74 * $param int $basicltiid Basic LTI activity id
76 function lti_view($instance) {
79 if(empty($instance->typeid)){
80 $tool = lti_get_tool_by_url_match($instance->toolurl, $instance->course);
87 $typeid = $instance->typeid;
91 $typeconfig = lti_get_type_config($typeid);
93 //There is no admin configuration for this tool. Use configuration in the lti instance record plus some defaults.
94 $typeconfig = (array)$instance;
96 $typeconfig['sendname'] = $instance->instructorchoicesendname;
97 $typeconfig['sendemailaddr'] = $instance->instructorchoicesendemailaddr;
98 $typeconfig['customparameters'] = $instance->instructorcustomparameters;
99 $typeconfig['acceptgrades'] = $instance->instructorchoiceacceptgrades;
100 $typeconfig['allowroster'] = $instance->instructorchoiceallowroster;
103 //Default the organizationid if not specified
104 if(empty($typeconfig['organizationid'])){
105 $urlparts = parse_url($CFG->wwwroot);
107 $typeconfig['organizationid'] = $urlparts['host'];
110 if(!empty($instance->resourcekey)){
111 $key = $instance->resourcekey;
112 } else if(!empty($typeconfig['resourcekey'])){
113 $key = $typeconfig['resourcekey'];
118 if(!empty($instance->password)){
119 $secret = $instance->password;
120 } else if(!empty($typeconfig['password'])){
121 $secret = $typeconfig['password'];
126 $endpoint = !empty($instance->toolurl) ? $instance->toolurl : $typeconfig['toolurl'];
127 $orgid = $typeconfig['organizationid'];
128 /* Suppress this for now - Chuck
129 $orgdesc = $typeconfig['organizationdescr'];
132 if(!strstr($endpoint, '://')){
133 $endpoint = 'http://' . $endpoint;
136 $course = $PAGE->course;
137 $requestparams = lti_build_request($instance, $typeconfig, $course);
139 $launchcontainer = lti_get_launch_container($instance, $typeconfig);
140 $returnurlparams = array('course' => $course->id, 'launch_container' => $launchcontainer);
143 $requestparams["tool_consumer_instance_guid"] = $orgid;
146 if(!empty($key) && !empty($secret)){
147 $parms = lti_sign_parameters($requestparams, $endpoint, "POST", $key, $secret);
149 //If no key and secret, do the launch unsigned.
150 $parms = $requestparams;
152 $returnurlparams['unsigned'] = '1';
155 //Add the return URL. We send the launch container along to help us avoid frames-within-frames when the user returns
156 $url = new moodle_url('/mod/lti/return.php', $returnurlparams);
157 $parms['launch_presentation_return_url'] = $url->out(false);
159 $debuglaunch = ( $instance->debuglaunch == 1 );
161 $content = lti_post_launch_html($parms, $endpoint, $debuglaunch);
166 function lti_build_sourcedid($instanceid, $userid, $launchid = null, $servicesalt){
167 $data = new stdClass();
169 $data->instanceid = $instanceid;
170 $data->userid = $userid;
171 if(!empty($launchid)){
172 $data->launchid = $launchid;
174 $data->launchid = mt_rand();
177 $json = json_encode($data);
179 $hash = hash('sha256', $json . $servicesalt, false);
181 $container = new stdClass();
182 $container->data = $data;
183 $container->hash = $hash;
189 * This function builds the request that must be sent to the tool producer
191 * @param object $instance Basic LTI instance object
192 * @param object $typeconfig Basic LTI tool configuration
193 * @param object $course Course object
195 * @return array $request Request details
197 function lti_build_request($instance, $typeconfig, $course) {
200 $context = get_context_instance(CONTEXT_COURSE, $course->id);
201 $role = lti_get_ims_role($USER, $context);
203 $locale = $course->lang;
204 if ( strlen($locale) < 1 ) {
205 $locale = $CFG->lang;
208 $requestparams = array(
209 "resource_link_id" => $instance->id,
210 "resource_link_title" => $instance->name,
211 "resource_link_description" => $instance->intro,
212 "user_id" => $USER->id,
214 "context_id" => $course->id,
215 "context_label" => $course->shortname,
216 "context_title" => $course->fullname,
217 "launch_presentation_locale" => $locale,
220 $placementsecret = $instance->servicesalt;
222 if ( isset($placementsecret) ) {
223 $sourcedid = json_encode(lti_build_sourcedid($instance->id, $USER->id, null, $placementsecret));
226 if ( isset($placementsecret) &&
227 ( $typeconfig['acceptgrades'] == LTI_SETTING_ALWAYS ||
228 ( $typeconfig['acceptgrades'] == LTI_SETTING_DELEGATE && $instance->instructorchoiceacceptgrades == LTI_SETTING_ALWAYS ) ) ) {
229 $requestparams["lis_result_sourcedid"] = $sourcedid;
230 $requestparams["ext_ims_lis_basic_outcome_url"] = $CFG->wwwroot.'/mod/lti/service.php';
233 if ( isset($placementsecret) &&
234 ( $typeconfig['allowroster'] == LTI_SETTING_ALWAYS ||
235 ( $typeconfig['allowroster'] == LTI_SETTING_DELEGATE && $instance->instructorchoiceallowroster == LTI_SETTING_ALWAYS ) ) ) {
236 $requestparams["ext_ims_lis_memberships_id"] = $sourcedid;
237 $requestparams["ext_ims_lis_memberships_url"] = $CFG->wwwroot.'/mod/lti/service.php';
240 // Send user's name and email data if appropriate
241 if ( $typeconfig['sendname'] == LTI_SETTING_ALWAYS ||
242 ( $typeconfig['sendname'] == LTI_SETTING_DELEGATE && $instance->instructorchoicesendname == LTI_SETTING_ALWAYS ) ) {
243 $requestparams["lis_person_name_given"] = $USER->firstname;
244 $requestparams["lis_person_name_family"] = $USER->lastname;
245 $requestparams["lis_person_name_full"] = $USER->firstname." ".$USER->lastname;
248 if ( $typeconfig['sendemailaddr'] == LTI_SETTING_ALWAYS ||
249 ( $typeconfig['sendemailaddr'] == LTI_SETTING_DELEGATE && $instance->instructorchoicesendemailaddr == LTI_SETTING_ALWAYS ) ) {
250 $requestparams["lis_person_contact_email_primary"] = $USER->email;
253 //Add outcome service URL
254 $url = new moodle_url('/mod/lti/service.php');
255 $requestparams['lis_outcome_service_url'] = $url->out();
257 // Concatenate the custom parameters from the administrator and the instructor
258 // Instructor parameters are only taken into consideration if the administrator
259 // has giver permission
260 $customstr = $typeconfig['customparameters'];
261 $instructorcustomstr = $instance->instructorcustomparameters;
263 $instructorcustom = array();
265 $custom = lti_split_custom_parameters($customstr);
267 if (!isset($typeconfig['allowinstructorcustom']) || $typeconfig['allowinstructorcustom'] == LTI_SETTING_NEVER) {
268 $requestparams = array_merge($custom, $requestparams);
270 if ($instructorcustomstr) {
271 $instructorcustom = lti_split_custom_parameters($instructorcustomstr);
273 foreach ($instructorcustom as $key => $val) {
274 if (array_key_exists($key, $custom)) {
275 // Ignore the instructor's parameter
277 $custom[$key] = $val;
280 $requestparams = array_merge($custom, $requestparams);
283 // Make sure we let the tool know what LMS they are being called from
284 $requestparams["ext_lms"] = "moodle-2";
286 // Add oauth_callback to be compliant with the 1.0A spec
287 $requestparams["oauth_callback"] = "about:blank";
289 $submittext = get_string('press_to_submit', 'lti');
290 $requestparams["ext_submit"] = $submittext;
292 $requestparams["lti_version"] = "LTI-1p0";
293 $requestparams["lti_message_type"] = "basic-lti-launch-request";
294 /* Suppress this for now - Chuck
295 if ( $orgdesc ) $requestparams["tool_consumer_instance_description"] = $orgdesc;
298 return $requestparams;
301 function lti_get_tool_table($tools, $id){
305 $typename = get_string('typename', 'lti');
306 $baseurl = get_string('baseurl', 'lti');
307 $action = get_string('action', 'lti');
308 $createdon = get_string('createdon', 'lti');
310 if($id == 'lti_configured'){
311 $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>';
314 if (!empty($tools)) {
316 <div id="{$id}_container" style="margin-top:.5em;margin-bottom:.5em">
317 <table id="{$id}_tools">
328 foreach ($tools as $type) {
329 $date = userdate($type->timecreated);
330 $accept = get_string('accept', 'lti');
331 $update = get_string('update', 'lti');
332 $delete = get_string('delete', 'lti');
334 $accepthtml = <<<HTML
335 <a class="editing_accept" href="{$CFG->wwwroot}/mod/lti/typessettings.php?action=accept&id={$type->id}&sesskey={$USER->sesskey}&tab={$id}" title="{$accept}">
336 <img class="iconsmall" alt="{$accept}" src="{$CFG->wwwroot}/pix/t/clear.gif"/>
340 $deleteaction = 'delete';
342 if($type->state == LTI_TOOL_STATE_CONFIGURED){
346 if($type->state != LTI_TOOL_STATE_REJECTED) {
347 $deleteaction = 'reject';
348 $delete = get_string('reject', 'lti');
364 <a class="editing_update" href="{$CFG->wwwroot}/mod/lti/typessettings.php?action=update&id={$type->id}&sesskey={$USER->sesskey}&tab={$id}" title="{$update}">
365 <img class="iconsmall" alt="{$update}" src="{$CFG->wwwroot}/pix/t/edit.gif"/>
367 <a class="editing_delete" href="{$CFG->wwwroot}/mod/lti/typessettings.php?action={$deleteaction}&id={$type->id}&sesskey={$USER->sesskey}&tab={$id}" title="{$delete}">
368 <img class="iconsmall" alt="{$delete}" src="{$CFG->wwwroot}/pix/t/delete.gif"/>
374 $html .= '</table></div>';
376 $html .= get_string('no_' . $id, 'lti');
383 * Splits the custom parameters field to the various parameters
385 * @param string $customstr String containing the parameters
387 * @return Array of custom parameters
389 function lti_split_custom_parameters($customstr) {
390 $textlib = textlib_get_instance();
392 $lines = preg_split("/[\n;]/", $customstr);
394 foreach ($lines as $line) {
395 $pos = strpos($line, "=");
396 if ( $pos === false || $pos < 1 ) {
399 $key = trim($textlib->substr($line, 0, $pos));
400 $val = trim($textlib->substr($line, $pos+1));
401 $key = lti_map_keyname($key);
402 $retval['custom_'.$key] = $val;
408 * Used for building the names of the different custom parameters
410 * @param string $key Parameter name
412 * @return string Processed name
414 function lti_map_keyname($key) {
415 $textlib = textlib_get_instance();
418 $key = $textlib->strtolower(trim($key));
419 foreach (str_split($key) as $ch) {
420 if ( ($ch >= 'a' && $ch <= 'z') || ($ch >= '0' && $ch <= '9') ) {
430 * Returns the IMS user role in a given context
432 * This function queries Moodle for an user role and
433 * returns the correspondant IMS role
435 * @param StdClass $user Moodle user instance
436 * @param StdClass $context Moodle context
438 * @return string IMS Role
441 function lti_get_ims_role($user, $context) {
443 $roles = get_user_roles($context, $user->id);
444 $rolesname = array();
445 foreach ($roles as $role) {
446 $rolesname[] = $role->shortname;
449 if (in_array('admin', $rolesname) || in_array('coursecreator', $rolesname)) {
450 return get_string('imsroleadmin', 'lti');
453 if (in_array('editingteacher', $rolesname) || in_array('teacher', $rolesname)) {
454 return get_string('imsroleinstructor', 'lti');
457 return get_string('imsrolelearner', 'lti');
461 * Returns configuration details for the tool
463 * @param int $typeid Basic LTI tool typeid
465 * @return array Tool Configuration
467 function lti_get_type_config($typeid) {
472 FROM {lti_types_config}
473 WHERE typeid = :typeid1
477 SELECT 'toolurl' AS name, baseurl AS value
482 $typeconfig = array();
483 $configs = $DB->get_records_sql($query, array('typeid1' => $typeid, 'typeid2' => $typeid));
485 if (!empty($configs)) {
486 foreach ($configs as $config) {
487 $typeconfig[$config->name] = $config->value;
494 function lti_get_tools_by_url($url, $state, $courseid = null){
495 $domain = lti_get_domain_from_url($url);
497 return lti_get_tools_by_domain($domain, $state, $courseid);
500 function lti_get_tools_by_domain($domain, $state = null, $courseid = null){
503 $filters = array('tooldomain' => $domain);
509 $statefilter = 'AND state = :state';
512 if($courseid && $courseid != $SITE->id){
513 $coursefilter = 'OR course = :courseid';
517 SELECT * FROM {lti_types}
519 tooldomain = :tooldomain
520 AND (course = :siteid $coursefilter)
524 return $DB->get_records_sql($query, array(
525 'courseid' => $courseid,
526 'siteid' => $SITE->id,
527 'tooldomain' => $domain,
533 * Returns all basicLTI tools configured by the administrator
536 function lti_filter_get_types($course) {
540 $filter = array('course' => $course);
545 return $DB->get_records('lti_types', $filter);
548 function lti_get_types_for_add_instance(){
549 global $DB, $SITE, $COURSE;
556 AND (course = :siteid OR course = :courseid)
560 $admintypes = $DB->get_records_sql($query, array('siteid' => $SITE->id, 'courseid' => $COURSE->id, 'active' => LTI_TOOL_STATE_CONFIGURED));
563 $types[0] = (object)array('name' => get_string('automatic', 'lti'), 'course' => $SITE->id);
565 foreach($admintypes as $type) {
566 $types[$type->id] = $type;
572 function lti_get_domain_from_url($url){
575 if(preg_match(LTI_URL_DOMAIN_REGEX, $url, $matches)){
580 function lti_get_tool_by_url_match($url, $courseid = null, $state = LTI_TOOL_STATE_CONFIGURED){
581 $possibletools = lti_get_tools_by_url($url, $state, $courseid);
583 return lti_get_best_tool_by_url($url, $possibletools, $courseid);
586 function lti_get_url_thumbprint($url){
587 $urlparts = parse_url(strtolower($url));
588 if(!isset($urlparts['path'])){
589 $urlparts['path'] = '';
592 if(substr($urlparts['host'], 0, 3) === 'www'){
593 $urllparts['host'] = substr($urlparts['host'], 3);
596 return $urllower = $urlparts['host'] . '/' . $urlparts['path'];
599 function lti_get_best_tool_by_url($url, $tools, $courseid = null){
600 if(count($tools) === 0){
604 $urllower = lti_get_url_thumbprint($url);
606 foreach($tools as $tool){
607 $tool->_matchscore = 0;
609 $toolbaseurllower = lti_get_url_thumbprint($tool->baseurl);
611 if($urllower === $toolbaseurllower){
612 //100 points for exact thumbprint match
613 $tool->_matchscore += 100;
614 } else if(substr($urllower, 0, strlen($toolbaseurllower)) === $toolbaseurllower){
615 //50 points if tool thumbprint starts with the base URL thumbprint
616 $tool->_matchscore += 50;
619 //Prefer course tools over site tools
620 if(!empty($courseid)){
621 //Minus 25 points for not matching the course id (global tools)
622 if($tool->course != $courseid){
623 $tool->_matchscore -= 10;
628 $bestmatch = array_reduce($tools, function($value, $tool){
629 if($tool->_matchscore > $value->_matchscore){
635 }, (object)array('_matchscore' => -1));
637 //None of the tools are suitable for this URL
638 if($bestmatch->_matchscore <= 0){
645 function lti_get_shared_secrets_by_key($key){
648 //Look up the shared secret for the specified key in both the types_config table (for configured tools)
649 //And in the lti resource table for ad-hoc tools
652 FROM {lti_types_config} t1
653 INNER JOIN {lti_types_config} t2 ON t1.typeid = t2.typeid
655 t1.name = 'resourcekey'
657 AND t2.name = 'password'
661 SELECT password AS value
663 WHERE resourcekey = :key2
666 $sharedsecrets = $DB->get_records_sql($query, array('key1' => $key, 'key2' => $key));
668 $values = array_map(function($item){
672 //There should really only be one shared secret per key. But, we can't prevent
673 //more than one getting entered. For instance, if the same key is used for two tool providers.
678 * Prints the various configured tool types
681 function lti_filter_print_types() {
684 $types = lti_filter_get_types();
685 if (!empty($types)) {
687 foreach ($types as $type) {
690 '<span class="commands">'.
691 '<a class="editing_update" href="typessettings.php?action=update&id='.$type->id.'&sesskey='.sesskey().'" title="Update">'.
692 '<img class="iconsmall" alt="Update" src="'.$CFG->wwwroot.'/pix/t/edit.gif"/>'.
694 '<a class="editing_delete" href="typessettings.php?action=delete&id='.$type->id.'&sesskey='.sesskey().'" title="Delete">'.
695 '<img class="iconsmall" alt="Delete" src="'.$CFG->wwwroot.'/pix/t/delete.gif"/>'.
703 echo '<div class="message">';
704 echo get_string('notypes', 'lti');
710 * Delete a Basic LTI configuration
712 * @param int $id Configuration id
714 function lti_delete_type($id) {
717 //We should probably just copy the launch URL to the tool instances in this case... using a single query
719 $instances = $DB->get_records('lti', array('typeid' => $id));
720 foreach ($instances as $instance) {
721 $instance->typeid = 0;
722 $DB->update_record('lti', $instance);
725 $DB->delete_records('lti_types', array('id' => $id));
726 $DB->delete_records('lti_types_config', array('typeid' => $id));
729 function lti_set_state_for_type($id, $state){
732 $DB->update_record('lti_types', array('id' => $id, 'state' => $state));
736 * Transforms a basic LTI object to an array
738 * @param object $ltiobject Basic LTI object
740 * @return array Basic LTI configuration details
742 function lti_get_config($ltiobject) {
743 $typeconfig = array();
744 $typeconfig = (array)$ltiobject;
745 $additionalconfig = lti_get_type_config($ltiobject->typeid);
746 $typeconfig = array_merge($typeconfig, $additionalconfig);
752 * Generates some of the tool configuration based on the instance details
756 * @return Instance configuration
759 function lti_get_type_config_from_instance($id) {
762 $instance = $DB->get_record('lti', array('id' => $id));
763 $config = lti_get_config($instance);
765 $type = new stdClass();
766 $type->lti_fix = $id;
767 if (isset($config['toolurl'])) {
768 $type->lti_toolurl = $config['toolurl'];
770 if (isset($config['instructorchoicesendname'])) {
771 $type->lti_sendname = $config['instructorchoicesendname'];
773 if (isset($config['instructorchoicesendemailaddr'])) {
774 $type->lti_sendemailaddr = $config['instructorchoicesendemailaddr'];
776 if (isset($config['instructorchoiceacceptgrades'])) {
777 $type->lti_acceptgrades = $config['instructorchoiceacceptgrades'];
779 if (isset($config['instructorchoiceallowroster'])) {
780 $type->lti_allowroster = $config['instructorchoiceallowroster'];
783 if (isset($config['instructorcustomparameters'])) {
784 $type->lti_allowsetting = $config['instructorcustomparameters'];
790 * Generates some of the tool configuration based on the admin configuration details
794 * @return Configuration details
796 function lti_get_type_type_config($id) {
799 $basicltitype = $DB->get_record('lti_types', array('id' => $id));
800 $config = lti_get_type_config($id);
802 $type->lti_typename = $basicltitype->name;
804 $type->typeid = $basicltitype->id;
806 $type->lti_toolurl = $basicltitype->baseurl;
808 if (isset($config['resourcekey'])) {
809 $type->lti_resourcekey = $config['resourcekey'];
811 if (isset($config['password'])) {
812 $type->lti_password = $config['password'];
815 if (isset($config['sendname'])) {
816 $type->lti_sendname = $config['sendname'];
818 if (isset($config['instructorchoicesendname'])){
819 $type->lti_instructorchoicesendname = $config['instructorchoicesendname'];
821 if (isset($config['sendemailaddr'])){
822 $type->lti_sendemailaddr = $config['sendemailaddr'];
824 if (isset($config['instructorchoicesendemailaddr'])){
825 $type->lti_instructorchoicesendemailaddr = $config['instructorchoicesendemailaddr'];
827 if (isset($config['acceptgrades'])){
828 $type->lti_acceptgrades = $config['acceptgrades'];
830 if (isset($config['instructorchoiceacceptgrades'])){
831 $type->lti_instructorchoiceacceptgrades = $config['instructorchoiceacceptgrades'];
833 if (isset($config['allowroster'])){
834 $type->lti_allowroster = $config['allowroster'];
836 if (isset($config['instructorchoiceallowroster'])){
837 $type->lti_instructorchoiceallowroster = $config['instructorchoiceallowroster'];
840 if (isset($config['customparameters'])) {
841 $type->lti_customparameters = $config['customparameters'];
844 if (isset($config['organizationid'])) {
845 $type->lti_organizationid = $config['organizationid'];
847 if (isset($config['organizationurl'])) {
848 $type->lti_organizationurl = $config['organizationurl'];
850 if (isset($config['organizationdescr'])) {
851 $type->lti_organizationdescr = $config['organizationdescr'];
853 if (isset($config['launchcontainer'])) {
854 $type->lti_launchcontainer = $config['launchcontainer'];
857 if (isset($config['coursevisible'])) {
858 $type->lti_coursevisible = $config['coursevisible'];
861 if (isset($config['debuglaunch'])) {
862 $type->lti_debuglaunch = $config['debuglaunch'];
865 if (isset($config['module_class_type'])) {
866 $type->lti_module_class_type = $config['module_class_type'];
872 function lti_prepare_type_for_save($type, $config){
873 $type->baseurl = $config->lti_toolurl;
874 $type->tooldomain = lti_get_domain_from_url($config->lti_toolurl);
875 $type->name = $config->lti_typename;
877 $type->coursevisible = !empty($config->lti_coursevisible) ? $config->lti_coursevisible : 0;
878 $config->lti_coursevisible = $type->coursevisible;
880 $type->timemodified = time();
882 unset ($config->lti_typename);
883 unset ($config->lti_toolurl);
886 function lti_update_type($type, $config){
889 lti_prepare_type_for_save($type, $config);
891 if ($DB->update_record('lti_types', $type)) {
892 foreach ($config as $key => $value) {
893 if (substr($key, 0, 4)=='lti_' && !is_null($value)) {
894 $record = new StdClass();
895 $record->typeid = $type->id;
896 $record->name = substr($key, 4);
897 $record->value = $value;
899 lti_update_config($record);
905 function lti_add_type($type, $config){
906 global $USER, $SITE, $DB;
908 lti_prepare_type_for_save($type, $config);
910 if(!isset($type->state)){
911 $type->state = LTI_TOOL_STATE_PENDING;
914 if(!isset($type->timecreated)){
915 $type->timecreated = time();
918 if(!isset($type->createdby)){
919 $type->createdby = $USER->id;
922 if(!isset($type->course)){
923 $type->course = $SITE->id;
926 //Create a salt value to be used for signing passed data to extension services
927 //The outcome service uses the service salt on the instance. This can be used
928 //for communication with services not related to a specific LTI instance.
929 $config->lti_servicesalt = uniqid('', true);
931 $id = $DB->insert_record('lti_types', $type);
934 foreach ($config as $key => $value) {
935 if (substr($key, 0, 4)=='lti_' && !is_null($value)) {
936 $record = new StdClass();
937 $record->typeid = $id;
938 $record->name = substr($key, 4);
939 $record->value = $value;
941 lti_add_config($record);
950 * Add a tool configuration in the database
952 * @param $config Tool configuration
954 * @return int Record id number
956 function lti_add_config($config) {
959 return $DB->insert_record('lti_types_config', $config);
963 * Updates a tool configuration in the database
965 * @param $config Tool configuration
967 * @return Record id number
969 function lti_update_config($config) {
973 $old = $DB->get_record('lti_types_config', array('typeid' => $config->typeid, 'name' => $config->name));
976 $config->id = $old->id;
977 $return = $DB->update_record('lti_types_config', $config);
979 $return = $DB->insert_record('lti_types_config', $config);
985 * Signs the petition to launch the external tool using OAuth
987 * @param $oldparms Parameters to be passed for signing
988 * @param $endpoint url of the external tool
989 * @param $method Method for sending the parameters (e.g. POST)
990 * @param $oauth_consumoer_key Key
991 * @param $oauth_consumoer_secret Secret
992 * @param $submittext The text for the submit button
993 * @param $orgid LMS name
994 * @param $orgdesc LMS key
996 function lti_sign_parameters($oldparms, $endpoint, $method, $oauthconsumerkey, $oauthconsumersecret) {
997 //global $lastbasestring;
1002 $hmacmethod = new lti\OAuthSignatureMethod_HMAC_SHA1();
1003 $testconsumer = new lti\OAuthConsumer($oauthconsumerkey, $oauthconsumersecret, null);
1005 $accreq = lti\OAuthRequest::from_consumer_and_token($testconsumer, $testtoken, $method, $endpoint, $parms);
1006 $accreq->sign_request($hmacmethod, $testconsumer, $testtoken);
1008 // Pass this back up "out of band" for debugging
1009 //$lastbasestring = $accreq->get_signature_base_string();
1011 $newparms = $accreq->get_parameters();
1017 * Posts the launch petition HTML
1019 * @param $newparms Signed parameters
1020 * @param $endpoint URL of the external tool
1021 * @param $debug Debug (true/false)
1023 function lti_post_launch_html($newparms, $endpoint, $debug=false) {
1024 //global $lastbasestring;
1026 $r = "<form action=\"".$endpoint."\" name=\"ltiLaunchForm\" id=\"ltiLaunchForm\" method=\"post\" encType=\"application/x-www-form-urlencoded\">\n";
1028 $submittext = $newparms['ext_submit'];
1030 // Contruct html for the launch parameters
1031 foreach ($newparms as $key => $value) {
1032 $key = htmlspecialchars($key);
1033 $value = htmlspecialchars($value);
1034 if ( $key == "ext_submit" ) {
1035 $r .= "<input type=\"submit\" name=\"";
1037 $r .= "<input type=\"hidden\" name=\"";
1040 $r .= "\" value=\"";
1046 $r .= "<script language=\"javascript\"> \n";
1047 $r .= " //<![CDATA[ \n";
1048 $r .= "function basicltiDebugToggle() {\n";
1049 $r .= " var ele = document.getElementById(\"basicltiDebug\");\n";
1050 $r .= " if(ele.style.display == \"block\") {\n";
1051 $r .= " ele.style.display = \"none\";\n";
1054 $r .= " ele.style.display = \"block\";\n";
1058 $r .= "</script>\n";
1059 $r .= "<a id=\"displayText\" href=\"javascript:basicltiDebugToggle();\">";
1060 $r .= get_string("toggle_debug_data", "lti")."</a>\n";
1061 $r .= "<div id=\"basicltiDebug\" style=\"display:none\">\n";
1062 $r .= "<b>".get_string("basiclti_endpoint", "lti")."</b><br/>\n";
1063 $r .= $endpoint . "<br/>\n <br/>\n";
1064 $r .= "<b>".get_string("basiclti_parameters", "lti")."</b><br/>\n";
1065 foreach ($newparms as $key => $value) {
1066 $key = htmlspecialchars($key);
1067 $value = htmlspecialchars($value);
1068 $r .= "$key = $value<br/>\n";
1070 $r .= " <br/>\n";
1071 //$r .= "<p><b>".get_string("basiclti_base_string", "lti")."</b><br/>\n".$lastbasestring."</p>\n";
1077 $ext_submit = "ext_submit";
1078 $ext_submit_text = $submittext;
1079 $r .= " <script type=\"text/javascript\"> \n" .
1081 " document.getElementById(\"ltiLaunchForm\").style.display = \"none\";\n" .
1082 " nei = document.createElement('input');\n" .
1083 " nei.setAttribute('type', 'hidden');\n" .
1084 " nei.setAttribute('name', '".$ext_submit."');\n" .
1085 " nei.setAttribute('value', '".$ext_submit_text."');\n" .
1086 " document.getElementById(\"ltiLaunchForm\").appendChild(nei);\n" .
1087 " document.ltiLaunchForm.submit(); \n" .
1094 function lti_get_type($typeid){
1097 return $DB->get_record('lti_types', array('id' => $typeid));
1100 function lti_get_launch_container($lti, $toolconfig){
1101 $launchcontainer = $lti->launchcontainer == LTI_LAUNCH_CONTAINER_DEFAULT ?
1102 $toolconfig['launchcontainer'] :
1103 $lti->launchcontainer;
1105 $devicetype = get_device_type();
1107 //Scrolling within the object element doesn't work on iOS or Android
1108 //Opening the popup window also had some issues in testing
1109 //For mobile devices, always take up the entire screen to ensure the best experience
1110 if($devicetype === 'mobile' || $devicetype === 'tablet' ){
1111 $launchcontainer = LTI_LAUNCH_CONTAINER_REPLACE_MOODLE_WINDOW;
1114 return $launchcontainer;