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 $endpoint = !empty($instance->toolurl) ? $instance->toolurl : $typeconfig['toolurl'];
111 $key = !empty($instance->resourcekey) ? $instance->resourcekey : $typeconfig['resourcekey'];
112 $secret = !empty($instance->password) ? $instance->password : $typeconfig['password'];
113 $orgid = $typeconfig['organizationid'];
114 /* Suppress this for now - Chuck
115 $orgdesc = $typeconfig['organizationdescr'];
118 if(!strstr($endpoint, '://')){
119 $endpoint = 'http://' . $endpoint;
122 $course = $PAGE->course;
123 $requestparams = lti_build_request($instance, $typeconfig, $course);
125 // Make sure we let the tool know what LMS they are being called from
126 $requestparams["ext_lms"] = "moodle-2";
128 // Add oauth_callback to be compliant with the 1.0A spec
129 $requestparams["oauth_callback"] = "about:blank";
131 $submittext = get_string('press_to_submit', 'lti');
132 $parms = lti_sign_parameters($requestparams, $endpoint, "POST", $key, $secret, $submittext, $orgid /*, $orgdesc*/);
134 $debuglaunch = ( $instance->debuglaunch == 1 );
136 $content = lti_post_launch_html($parms, $endpoint, $debuglaunch);
141 function lti_build_sourcedid($instanceid, $userid, $launchid = null, $servicesalt){
142 $data = new stdClass();
144 $data->instanceid = $instanceid;
145 $data->userid = $userid;
146 if(!empty($launchid)){
147 $data->launchid = $launchid;
149 $data->launchid = mt_rand();
152 $json = json_encode($data);
154 $hash = hash('sha256', $json . $servicesalt, false);
156 $container = new stdClass();
157 $container->data = $data;
158 $container->hash = $hash;
164 * This function builds the request that must be sent to the tool producer
166 * @param object $instance Basic LTI instance object
167 * @param object $typeconfig Basic LTI tool configuration
168 * @param object $course Course object
170 * @return array $request Request details
172 function lti_build_request($instance, $typeconfig, $course) {
175 $context = get_context_instance(CONTEXT_COURSE, $course->id);
176 $role = lti_get_ims_role($USER, $context);
178 $locale = $course->lang;
179 if ( strlen($locale) < 1 ) {
180 $locale = $CFG->lang;
183 $requestparams = array(
184 "resource_link_id" => $instance->id,
185 "resource_link_title" => $instance->name,
186 "resource_link_description" => $instance->intro,
187 "user_id" => $USER->id,
189 "context_id" => $course->id,
190 "context_label" => $course->shortname,
191 "context_title" => $course->fullname,
192 "launch_presentation_locale" => $locale,
195 $placementsecret = $instance->servicesalt;
197 if ( isset($placementsecret) ) {
198 $sourcedid = json_encode(lti_build_sourcedid($instance->id, $USER->id, null, $placementsecret));
201 if ( isset($placementsecret) &&
202 ( $typeconfig['acceptgrades'] == LTI_SETTING_ALWAYS ||
203 ( $typeconfig['acceptgrades'] == LTI_SETTING_DELEGATE && $instance->instructorchoiceacceptgrades == LTI_SETTING_ALWAYS ) ) ) {
204 $requestparams["lis_result_sourcedid"] = $sourcedid;
205 $requestparams["ext_ims_lis_basic_outcome_url"] = $CFG->wwwroot.'/mod/lti/service.php';
208 if ( isset($placementsecret) &&
209 ( $typeconfig['allowroster'] == LTI_SETTING_ALWAYS ||
210 ( $typeconfig['allowroster'] == LTI_SETTING_DELEGATE && $instance->instructorchoiceallowroster == LTI_SETTING_ALWAYS ) ) ) {
211 $requestparams["ext_ims_lis_memberships_id"] = $sourcedid;
212 $requestparams["ext_ims_lis_memberships_url"] = $CFG->wwwroot.'/mod/lti/service.php';
215 // Send user's name and email data if appropriate
216 if ( $typeconfig['sendname'] == LTI_SETTING_ALWAYS ||
217 ( $typeconfig['sendname'] == LTI_SETTING_DELEGATE && $instance->instructorchoicesendname == LTI_SETTING_ALWAYS ) ) {
218 $requestparams["lis_person_name_given"] = $USER->firstname;
219 $requestparams["lis_person_name_family"] = $USER->lastname;
220 $requestparams["lis_person_name_full"] = $USER->firstname." ".$USER->lastname;
223 if ( $typeconfig['sendemailaddr'] == LTI_SETTING_ALWAYS ||
224 ( $typeconfig['sendemailaddr'] == LTI_SETTING_DELEGATE && $instance->instructorchoicesendemailaddr == LTI_SETTING_ALWAYS ) ) {
225 $requestparams["lis_person_contact_email_primary"] = $USER->email;
228 //Add outcome service URL
229 $url = new moodle_url('/mod/lti/service.php');
230 $requestparams['lis_outcome_service_url'] = $url->out();
232 $launchcontainer = lti_get_launch_container($instance, $typeconfig);
234 //Add the return URL. We send the launch container along to help us avoid frames-within-frames when the user returns
235 $url = new moodle_url('/mod/lti/return.php', array('course' => $course->id, 'launch_container' => $launchcontainer));
236 $requestparams['launch_presentation_return_url'] = $url->out(false);
238 // Concatenate the custom parameters from the administrator and the instructor
239 // Instructor parameters are only taken into consideration if the administrator
240 // has giver permission
241 $customstr = $typeconfig['customparameters'];
242 $instructorcustomstr = $instance->instructorcustomparameters;
244 $instructorcustom = array();
246 $custom = lti_split_custom_parameters($customstr);
248 if (!isset($typeconfig['allowinstructorcustom']) || $typeconfig['allowinstructorcustom'] == LTI_SETTING_NEVER) {
249 $requestparams = array_merge($custom, $requestparams);
251 if ($instructorcustomstr) {
252 $instructorcustom = lti_split_custom_parameters($instructorcustomstr);
254 foreach ($instructorcustom as $key => $val) {
255 if (array_key_exists($key, $custom)) {
256 // Ignore the instructor's parameter
258 $custom[$key] = $val;
261 $requestparams = array_merge($custom, $requestparams);
264 return $requestparams;
267 function lti_get_tool_table($tools, $id){
271 $typename = get_string('typename', 'lti');
272 $baseurl = get_string('baseurl', 'lti');
273 $action = get_string('action', 'lti');
274 $createdon = get_string('createdon', 'lti');
276 if($id == 'lti_configured'){
277 $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>';
280 if (!empty($tools)) {
282 <div id="{$id}_container" style="margin-top:.5em;margin-bottom:.5em">
283 <table id="{$id}_tools">
294 foreach ($tools as $type) {
295 $date = userdate($type->timecreated);
296 $accept = get_string('accept', 'lti');
297 $update = get_string('update', 'lti');
298 $delete = get_string('delete', 'lti');
300 $accepthtml = <<<HTML
301 <a class="editing_accept" href="{$CFG->wwwroot}/mod/lti/typessettings.php?action=accept&id={$type->id}&sesskey={$USER->sesskey}&tab={$id}" title="{$accept}">
302 <img class="iconsmall" alt="{$accept}" src="{$CFG->wwwroot}/pix/t/clear.gif"/>
306 $deleteaction = 'delete';
308 if($type->state == LTI_TOOL_STATE_CONFIGURED){
312 if($type->state != LTI_TOOL_STATE_REJECTED) {
313 $deleteaction = 'reject';
314 $delete = get_string('reject', 'lti');
330 <a class="editing_update" href="{$CFG->wwwroot}/mod/lti/typessettings.php?action=update&id={$type->id}&sesskey={$USER->sesskey}&tab={$id}" title="{$update}">
331 <img class="iconsmall" alt="{$update}" src="{$CFG->wwwroot}/pix/t/edit.gif"/>
333 <a class="editing_delete" href="{$CFG->wwwroot}/mod/lti/typessettings.php?action={$deleteaction}&id={$type->id}&sesskey={$USER->sesskey}&tab={$id}" title="{$delete}">
334 <img class="iconsmall" alt="{$delete}" src="{$CFG->wwwroot}/pix/t/delete.gif"/>
340 $html .= '</table></div>';
342 $html .= get_string('no_' . $id, 'lti');
349 * Splits the custom parameters field to the various parameters
351 * @param string $customstr String containing the parameters
353 * @return Array of custom parameters
355 function lti_split_custom_parameters($customstr) {
356 $textlib = textlib_get_instance();
358 $lines = preg_split("/[\n;]/", $customstr);
360 foreach ($lines as $line) {
361 $pos = strpos($line, "=");
362 if ( $pos === false || $pos < 1 ) {
365 $key = trim($textlib->substr($line, 0, $pos));
366 $val = trim($textlib->substr($line, $pos+1));
367 $key = lti_map_keyname($key);
368 $retval['custom_'.$key] = $val;
374 * Used for building the names of the different custom parameters
376 * @param string $key Parameter name
378 * @return string Processed name
380 function lti_map_keyname($key) {
381 $textlib = textlib_get_instance();
384 $key = $textlib->strtolower(trim($key));
385 foreach (str_split($key) as $ch) {
386 if ( ($ch >= 'a' && $ch <= 'z') || ($ch >= '0' && $ch <= '9') ) {
396 * Returns the IMS user role in a given context
398 * This function queries Moodle for an user role and
399 * returns the correspondant IMS role
401 * @param StdClass $user Moodle user instance
402 * @param StdClass $context Moodle context
404 * @return string IMS Role
407 function lti_get_ims_role($user, $context) {
409 $roles = get_user_roles($context, $user->id);
410 $rolesname = array();
411 foreach ($roles as $role) {
412 $rolesname[] = $role->shortname;
415 if (in_array('admin', $rolesname) || in_array('coursecreator', $rolesname)) {
416 return get_string('imsroleadmin', 'lti');
419 if (in_array('editingteacher', $rolesname) || in_array('teacher', $rolesname)) {
420 return get_string('imsroleinstructor', 'lti');
423 return get_string('imsrolelearner', 'lti');
427 * Returns configuration details for the tool
429 * @param int $typeid Basic LTI tool typeid
431 * @return array Tool Configuration
433 function lti_get_type_config($typeid) {
438 FROM {lti_types_config}
439 WHERE typeid = :typeid1
443 SELECT 'toolurl' AS name, baseurl AS value
448 $typeconfig = array();
449 $configs = $DB->get_records_sql($query, array('typeid1' => $typeid, 'typeid2' => $typeid));
451 if (!empty($configs)) {
452 foreach ($configs as $config) {
453 $typeconfig[$config->name] = $config->value;
460 function lti_get_tools_by_url($url, $state, $courseid = null){
461 $domain = lti_get_domain_from_url($url);
463 return lti_get_tools_by_domain($domain, $state, $courseid);
466 function lti_get_tools_by_domain($domain, $state = null, $courseid = null){
469 $filters = array('tooldomain' => $domain);
475 $statefilter = 'AND state = :state';
478 if($courseid && $courseid != $SITE->id){
479 $coursefilter = 'OR course = :courseid';
483 SELECT * FROM {lti_types}
485 tooldomain = :tooldomain
486 AND (course = :siteid $coursefilter)
490 return $DB->get_records_sql($query, array(
491 'courseid' => $courseid,
492 'siteid' => $SITE->id,
493 'tooldomain' => $domain,
499 * Returns all basicLTI tools configured by the administrator
502 function lti_filter_get_types($course) {
506 $filter = array('course' => $course);
511 return $DB->get_records('lti_types', $filter);
514 function lti_get_types_for_add_instance(){
515 global $DB, $SITE, $COURSE;
522 AND (course = :siteid OR course = :courseid)
526 $admintypes = $DB->get_records_sql($query, array('siteid' => $SITE->id, 'courseid' => $COURSE->id, 'active' => LTI_TOOL_STATE_CONFIGURED));
529 $types[0] = (object)array('name' => get_string('automatic', 'lti'), 'course' => $SITE->id);
531 foreach($admintypes as $type) {
532 $types[$type->id] = $type;
538 function lti_get_domain_from_url($url){
541 if(preg_match(LTI_URL_DOMAIN_REGEX, $url, $matches)){
546 function lti_get_tool_by_url_match($url, $courseid = null, $state = LTI_TOOL_STATE_CONFIGURED){
547 $possibletools = lti_get_tools_by_url($url, $state, $courseid);
549 return lti_get_best_tool_by_url($url, $possibletools, $courseid);
552 function lti_get_url_thumbprint($url){
553 $urlparts = parse_url(strtolower($url));
554 if(!isset($urlparts['path'])){
555 $urlparts['path'] = '';
558 if(substr($urlparts['host'], 0, 3) === 'www'){
559 $urllparts['host'] = substr($urlparts['host'], 3);
562 return $urllower = $urlparts['host'] . '/' . $urlparts['path'];
565 function lti_get_best_tool_by_url($url, $tools, $courseid = null){
566 if(count($tools) === 0){
570 $urllower = lti_get_url_thumbprint($url);
572 foreach($tools as $tool){
573 $tool->_matchscore = 0;
575 $toolbaseurllower = lti_get_url_thumbprint($tool->baseurl);
577 if($urllower === $toolbaseurllower){
578 //100 points for exact thumbprint match
579 $tool->_matchscore += 100;
580 } else if(substr($urllower, 0, strlen($toolbaseurllower)) === $toolbaseurllower){
581 //50 points if tool thumbprint starts with the base URL thumbprint
582 $tool->_matchscore += 50;
585 //Prefer course tools over site tools
586 if(!empty($courseid)){
587 //Minus 25 points for not matching the course id (global tools)
588 if($tool->course != $courseid){
589 $tool->_matchscore -= 10;
594 $bestmatch = array_reduce($tools, function($value, $tool){
595 if($tool->_matchscore > $value->_matchscore){
601 }, (object)array('_matchscore' => -1));
603 //None of the tools are suitable for this URL
604 if($bestmatch->_matchscore <= 0){
611 function lti_get_shared_secrets_by_key($key){
614 //Look up the shared secret for the specified key in both the types_config table (for configured tools)
615 //And in the lti resource table for ad-hoc tools
618 FROM {lti_types_config} t1
619 INNER JOIN {lti_types_config} t2 ON t1.typeid = t2.typeid
621 t1.name = 'resourcekey'
623 AND t2.name = 'password'
629 WHERE resourcekey = :key2
632 $sharedsecrets = $DB->get_records_sql($query, array('key1' => $key, 'key2' => $key));
634 $values = array_map(function($item){
638 //There should really only be one shared secret per key. But, we can't prevent
639 //more than one getting entered. For instance, if the same key is used for two tool providers.
644 * Prints the various configured tool types
647 function lti_filter_print_types() {
650 $types = lti_filter_get_types();
651 if (!empty($types)) {
653 foreach ($types as $type) {
656 '<span class="commands">'.
657 '<a class="editing_update" href="typessettings.php?action=update&id='.$type->id.'&sesskey='.sesskey().'" title="Update">'.
658 '<img class="iconsmall" alt="Update" src="'.$CFG->wwwroot.'/pix/t/edit.gif"/>'.
660 '<a class="editing_delete" href="typessettings.php?action=delete&id='.$type->id.'&sesskey='.sesskey().'" title="Delete">'.
661 '<img class="iconsmall" alt="Delete" src="'.$CFG->wwwroot.'/pix/t/delete.gif"/>'.
669 echo '<div class="message">';
670 echo get_string('notypes', 'lti');
676 * Delete a Basic LTI configuration
678 * @param int $id Configuration id
680 function lti_delete_type($id) {
683 //We should probably just copy the launch URL to the tool instances in this case... using a single query
685 $instances = $DB->get_records('lti', array('typeid' => $id));
686 foreach ($instances as $instance) {
687 $instance->typeid = 0;
688 $DB->update_record('lti', $instance);
691 $DB->delete_records('lti_types', array('id' => $id));
692 $DB->delete_records('lti_types_config', array('typeid' => $id));
695 function lti_set_state_for_type($id, $state){
698 $DB->update_record('lti_types', array('id' => $id, 'state' => $state));
702 * Transforms a basic LTI object to an array
704 * @param object $ltiobject Basic LTI object
706 * @return array Basic LTI configuration details
708 function lti_get_config($ltiobject) {
709 $typeconfig = array();
710 $typeconfig = (array)$ltiobject;
711 $additionalconfig = lti_get_type_config($ltiobject->typeid);
712 $typeconfig = array_merge($typeconfig, $additionalconfig);
718 * Generates some of the tool configuration based on the instance details
722 * @return Instance configuration
725 function lti_get_type_config_from_instance($id) {
728 $instance = $DB->get_record('lti', array('id' => $id));
729 $config = lti_get_config($instance);
731 $type = new stdClass();
732 $type->lti_fix = $id;
733 if (isset($config['toolurl'])) {
734 $type->lti_toolurl = $config['toolurl'];
736 if (isset($config['instructorchoicesendname'])) {
737 $type->lti_sendname = $config['instructorchoicesendname'];
739 if (isset($config['instructorchoicesendemailaddr'])) {
740 $type->lti_sendemailaddr = $config['instructorchoicesendemailaddr'];
742 if (isset($config['instructorchoiceacceptgrades'])) {
743 $type->lti_acceptgrades = $config['instructorchoiceacceptgrades'];
745 if (isset($config['instructorchoiceallowroster'])) {
746 $type->lti_allowroster = $config['instructorchoiceallowroster'];
749 if (isset($config['instructorcustomparameters'])) {
750 $type->lti_allowsetting = $config['instructorcustomparameters'];
756 * Generates some of the tool configuration based on the admin configuration details
760 * @return Configuration details
762 function lti_get_type_type_config($id) {
765 $basicltitype = $DB->get_record('lti_types', array('id' => $id));
766 $config = lti_get_type_config($id);
768 $type->lti_typename = $basicltitype->name;
770 $type->typeid = $basicltitype->id;
772 $type->lti_toolurl = $basicltitype->baseurl;
774 if (isset($config['resourcekey'])) {
775 $type->lti_resourcekey = $config['resourcekey'];
777 if (isset($config['password'])) {
778 $type->lti_password = $config['password'];
781 if (isset($config['sendname'])) {
782 $type->lti_sendname = $config['sendname'];
784 if (isset($config['instructorchoicesendname'])){
785 $type->lti_instructorchoicesendname = $config['instructorchoicesendname'];
787 if (isset($config['sendemailaddr'])){
788 $type->lti_sendemailaddr = $config['sendemailaddr'];
790 if (isset($config['instructorchoicesendemailaddr'])){
791 $type->lti_instructorchoicesendemailaddr = $config['instructorchoicesendemailaddr'];
793 if (isset($config['acceptgrades'])){
794 $type->lti_acceptgrades = $config['acceptgrades'];
796 if (isset($config['instructorchoiceacceptgrades'])){
797 $type->lti_instructorchoiceacceptgrades = $config['instructorchoiceacceptgrades'];
799 if (isset($config['allowroster'])){
800 $type->lti_allowroster = $config['allowroster'];
802 if (isset($config['instructorchoiceallowroster'])){
803 $type->lti_instructorchoiceallowroster = $config['instructorchoiceallowroster'];
806 if (isset($config['customparameters'])) {
807 $type->lti_customparameters = $config['customparameters'];
810 if (isset($config['organizationid'])) {
811 $type->lti_organizationid = $config['organizationid'];
813 if (isset($config['organizationurl'])) {
814 $type->lti_organizationurl = $config['organizationurl'];
816 if (isset($config['organizationdescr'])) {
817 $type->lti_organizationdescr = $config['organizationdescr'];
819 if (isset($config['launchcontainer'])) {
820 $type->lti_launchcontainer = $config['launchcontainer'];
823 if (isset($config['coursevisible'])) {
824 $type->lti_coursevisible = $config['coursevisible'];
827 if (isset($config['debuglaunch'])) {
828 $type->lti_debuglaunch = $config['debuglaunch'];
831 if (isset($config['module_class_type'])) {
832 $type->lti_module_class_type = $config['module_class_type'];
838 function lti_prepare_type_for_save($type, $config){
839 $type->baseurl = $config->lti_toolurl;
840 $type->tooldomain = lti_get_domain_from_url($config->lti_toolurl);
841 $type->name = $config->lti_typename;
843 $type->coursevisible = !empty($config->lti_coursevisible) ? $config->lti_coursevisible : 0;
844 $config->lti_coursevisible = $type->coursevisible;
846 $type->timemodified = time();
848 unset ($config->lti_typename);
849 unset ($config->lti_toolurl);
852 function lti_update_type($type, $config){
855 lti_prepare_type_for_save($type, $config);
857 if ($DB->update_record('lti_types', $type)) {
858 foreach ($config as $key => $value) {
859 if (substr($key, 0, 4)=='lti_' && !is_null($value)) {
860 $record = new StdClass();
861 $record->typeid = $type->id;
862 $record->name = substr($key, 4);
863 $record->value = $value;
865 lti_update_config($record);
871 function lti_add_type($type, $config){
872 global $USER, $SITE, $DB;
874 lti_prepare_type_for_save($type, $config);
876 if(!isset($type->state)){
877 $type->state = LTI_TOOL_STATE_PENDING;
880 if(!isset($type->timecreated)){
881 $type->timecreated = time();
884 if(!isset($type->createdby)){
885 $type->createdby = $USER->id;
888 if(!isset($type->course)){
889 $type->course = $SITE->id;
892 //Create a salt value to be used for signing passed data to extension services
893 //The outcome service uses the service salt on the instance. This can be used
894 //for communication with services not related to a specific LTI instance.
895 $config->lti_servicesalt = uniqid('', true);
897 $id = $DB->insert_record('lti_types', $type);
900 foreach ($config as $key => $value) {
901 if (substr($key, 0, 4)=='lti_' && !is_null($value)) {
902 $record = new StdClass();
903 $record->typeid = $id;
904 $record->name = substr($key, 4);
905 $record->value = $value;
907 lti_add_config($record);
916 * Add a tool configuration in the database
918 * @param $config Tool configuration
920 * @return int Record id number
922 function lti_add_config($config) {
925 return $DB->insert_record('lti_types_config', $config);
929 * Updates a tool configuration in the database
931 * @param $config Tool configuration
933 * @return Record id number
935 function lti_update_config($config) {
939 $old = $DB->get_record('lti_types_config', array('typeid' => $config->typeid, 'name' => $config->name));
942 $config->id = $old->id;
943 $return = $DB->update_record('lti_types_config', $config);
945 $return = $DB->insert_record('lti_types_config', $config);
951 * Signs the petition to launch the external tool using OAuth
953 * @param $oldparms Parameters to be passed for signing
954 * @param $endpoint url of the external tool
955 * @param $method Method for sending the parameters (e.g. POST)
956 * @param $oauth_consumoer_key Key
957 * @param $oauth_consumoer_secret Secret
958 * @param $submittext The text for the submit button
959 * @param $orgid LMS name
960 * @param $orgdesc LMS key
962 function lti_sign_parameters($oldparms, $endpoint, $method, $oauthconsumerkey, $oauthconsumersecret, $submittext, $orgid /*, $orgdesc*/) {
963 global $lastbasestring;
965 $parms["lti_version"] = "LTI-1p0";
966 $parms["lti_message_type"] = "basic-lti-launch-request";
968 $parms["tool_consumer_instance_guid"] = $orgid;
970 /* Suppress this for now - Chuck
971 if ( $orgdesc ) $parms["tool_consumer_instance_description"] = $orgdesc;
973 $parms["ext_submit"] = $submittext;
977 $hmacmethod = new lti\OAuthSignatureMethod_HMAC_SHA1();
978 $testconsumer = new lti\OAuthConsumer($oauthconsumerkey, $oauthconsumersecret, null);
980 $accreq = lti\OAuthRequest::from_consumer_and_token($testconsumer, $testtoken, $method, $endpoint, $parms);
981 $accreq->sign_request($hmacmethod, $testconsumer, $testtoken);
983 // Pass this back up "out of band" for debugging
984 $lastbasestring = $accreq->get_signature_base_string();
986 $newparms = $accreq->get_parameters();
992 * Posts the launch petition HTML
994 * @param $newparms Signed parameters
995 * @param $endpoint URL of the external tool
996 * @param $debug Debug (true/false)
998 function lti_post_launch_html($newparms, $endpoint, $debug=false) {
999 global $lastbasestring;
1001 $r = "<form action=\"".$endpoint."\" name=\"ltiLaunchForm\" id=\"ltiLaunchForm\" method=\"post\" encType=\"application/x-www-form-urlencoded\">\n";
1003 $submittext = $newparms['ext_submit'];
1005 // Contruct html for the launch parameters
1006 foreach ($newparms as $key => $value) {
1007 $key = htmlspecialchars($key);
1008 $value = htmlspecialchars($value);
1009 if ( $key == "ext_submit" ) {
1010 $r .= "<input type=\"submit\" name=\"";
1012 $r .= "<input type=\"hidden\" name=\"";
1015 $r .= "\" value=\"";
1021 $r .= "<script language=\"javascript\"> \n";
1022 $r .= " //<![CDATA[ \n";
1023 $r .= "function basicltiDebugToggle() {\n";
1024 $r .= " var ele = document.getElementById(\"basicltiDebug\");\n";
1025 $r .= " if(ele.style.display == \"block\") {\n";
1026 $r .= " ele.style.display = \"none\";\n";
1029 $r .= " ele.style.display = \"block\";\n";
1033 $r .= "</script>\n";
1034 $r .= "<a id=\"displayText\" href=\"javascript:basicltiDebugToggle();\">";
1035 $r .= get_string("toggle_debug_data", "lti")."</a>\n";
1036 $r .= "<div id=\"basicltiDebug\" style=\"display:none\">\n";
1037 $r .= "<b>".get_string("basiclti_endpoint", "lti")."</b><br/>\n";
1038 $r .= $endpoint . "<br/>\n <br/>\n";
1039 $r .= "<b>".get_string("basiclti_parameters", "lti")."</b><br/>\n";
1040 foreach ($newparms as $key => $value) {
1041 $key = htmlspecialchars($key);
1042 $value = htmlspecialchars($value);
1043 $r .= "$key = $value<br/>\n";
1045 $r .= " <br/>\n";
1046 $r .= "<p><b>".get_string("basiclti_base_string", "lti")."</b><br/>\n".$lastbasestring."</p>\n";
1052 $ext_submit = "ext_submit";
1053 $ext_submit_text = $submittext;
1054 $r .= " <script type=\"text/javascript\"> \n" .
1056 " document.getElementById(\"ltiLaunchForm\").style.display = \"none\";\n" .
1057 " nei = document.createElement('input');\n" .
1058 " nei.setAttribute('type', 'hidden');\n" .
1059 " nei.setAttribute('name', '".$ext_submit."');\n" .
1060 " nei.setAttribute('value', '".$ext_submit_text."');\n" .
1061 " document.getElementById(\"ltiLaunchForm\").appendChild(nei);\n" .
1062 " document.ltiLaunchForm.submit(); \n" .
1069 function lti_get_type($typeid){
1072 return $DB->get_record('lti_types', array('id' => $typeid));
1075 function lti_get_launch_container($lti, $toolconfig){
1076 $launchcontainer = $lti->launchcontainer == LTI_LAUNCH_CONTAINER_DEFAULT ?
1077 $toolconfig['launchcontainer'] :
1078 $lti->launchcontainer;
1080 $devicetype = get_device_type();
1082 //Scrolling within the object element doesn't work on iOS or Android
1083 //Opening the popup window also had some issues in testing
1084 //For mobile devices, always take up the entire screen to ensure the best experience
1085 if($devicetype === 'mobile' || $devicetype === 'tablet' ){
1086 $launchcontainer = LTI_LAUNCH_CONTAINER_REPLACE_MOODLE_WINDOW;
1089 return $launchcontainer;