bb53e6f0be7b7e00c0eae53c99c22b146ed473bb
[moodle.git] / mod / lti / locallib.php
1 <?php
2 // This file is part of Moodle - http://moodle.org/
3 //
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.
8 //
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.
13 //
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/>.
16 //
17 // This file is part of BasicLTI4Moodle
18 //
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.
30 //
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
35 /**
36  * This file contains the library of functions and constants for the lti module
37  *
38  * @package    mod
39  * @subpackage lti
40  * @copyright  2009 Marc Alier, Jordi Piguillem, Nikolas Galanis
41  *  marc.alier@upc.edu
42  * @copyright  2009 Universitat Politecnica de Catalunya http://www.upc.edu
43  * @author     Marc Alier
44  * @author     Jordi Piguillem
45  * @author     Nikolas Galanis
46  * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
47  */
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);
73 /**
74  * Prints a Basic LTI activity
75  *
76  * $param int $basicltiid       Basic LTI activity id
77  */
78 function lti_view($instance) {
79     global $PAGE, $CFG;
81     if (empty($instance->typeid)) {
82         $tool = lti_get_tool_by_url_match($instance->toolurl, $instance->course);
83         if ($tool) {
84             $typeid = $tool->id;
85         } else {
86             $typeid = null;
87         }
88     } else {
89         $typeid = $instance->typeid;
90     }
92     if ($typeid) {
93         $typeconfig = lti_get_type_config($typeid);
94     } else {
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';
104     }
106     //Default the organizationid if not specified
107     if (empty($typeconfig['organizationid'])) {
108         $urlparts = parse_url($CFG->wwwroot);
110         $typeconfig['organizationid'] = $urlparts['host'];
111     }
113     if (!empty($instance->resourcekey)) {
114         $key = $instance->resourcekey;
115     } else if (!empty($typeconfig['resourcekey'])) {
116         $key = $typeconfig['resourcekey'];
117     } else {
118         $key = '';
119     }
121     if (!empty($instance->password)) {
122         $secret = $instance->password;
123     } else if (!empty($typeconfig['password'])) {
124         $secret = $typeconfig['password'];
125     } else {
126         $secret = '';
127     }
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);
135     }
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);
141         }
143         $endpoint = lti_ensure_url_is_https($endpoint);
144     } else {
145         if (!strstr($endpoint, '://')) {
146             $endpoint = 'http://' . $endpoint;
147         }
148     }
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);
158     if ( $orgid ) {
159         $requestparams["tool_consumer_instance_guid"] = $orgid;
160     }
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);
171         }
173         $requestparams['launch_presentation_return_url'] = $returnurl;
174     }
176     $requestparams['tool_consumer_info_product_family_code'] = 'moodle';
177     $requestparams['tool_consumer_info_version'] = strval($CFG->version);
179     if (!empty($key) && !empty($secret)) {
180         $parms = lti_sign_parameters($requestparams, $endpoint, "POST", $key, $secret);
181     } else {
182         //If no key and secret, do the launch unsigned.
183         $parms = $requestparams;
184     }
186     $debuglaunch = ( $instance->debuglaunch == 1 );
188     $content = lti_post_launch_html($parms, $endpoint, $debuglaunch);
190     echo $content;
193 function lti_build_sourcedid($instanceid, $userid, $launchid = null, $servicesalt) {
194     $data = new stdClass();
196     $data->instanceid = $instanceid;
197     $data->userid = $userid;
198     if (!empty($launchid)) {
199         $data->launchid = $launchid;
200     } else {
201         $data->launchid = mt_rand();
202     }
204     $json = json_encode($data);
206     $hash = hash('sha256', $json . $servicesalt, false);
208     $container = new stdClass();
209     $container->data = $data;
210     $container->hash = $hash;
212     return $container;
215 /**
216  * This function builds the request that must be sent to the tool producer
217  *
218  * @param object    $instance       Basic LTI instance object
219  * @param object    $typeconfig     Basic LTI tool configuration
220  * @param object    $course         Course object
221  *
222  * @return array    $request        Request details
223  */
224 function lti_build_request($instance, $typeconfig, $course) {
225     global $USER, $CFG;
227     if (empty($instance->cmid)) {
228         $instance->cmid = 0;
229     }
231     $role = lti_get_ims_role($USER, $instance->cmid, $instance->course);
233     $locale = $course->lang;
234     if ( strlen($locale) < 1 ) {
235          $locale = $CFG->lang;
236     }
238     $requestparams = array(
239         'resource_link_id' => $instance->id,
240         'resource_link_title' => $instance->name,
241         'resource_link_description' => $instance->intro,
242         'user_id' => $USER->id,
243         'roles' => $role,
244         'context_id' => $course->id,
245         'context_label' => $course->shortname,
246         'context_title' => $course->fullname,
247         'launch_presentation_locale' => $locale,
248     );
250     $placementsecret = $instance->servicesalt;
252     if ( isset($placementsecret) ) {
253         $sourcedid = json_encode(lti_build_sourcedid($instance->id, $USER->id, null, $placementsecret));
254     }
256     if ( isset($placementsecret) &&
257          ( $typeconfig['acceptgrades'] == LTI_SETTING_ALWAYS ||
258          ( $typeconfig['acceptgrades'] == LTI_SETTING_DELEGATE && $instance->instructorchoiceacceptgrades == LTI_SETTING_ALWAYS ) ) ) {
259         $requestparams['lis_result_sourcedid'] = $sourcedid;
261         //Add outcome service URL
262         $serviceurl = new moodle_url('/mod/lti/service.php');
263         $serviceurl = $serviceurl->out();
264         
265         if ($typeconfig['forcessl'] == '1') {
266             $serviceurl = lti_ensure_url_is_https($serviceurl);
267         }
268         
269         $requestparams['lis_outcome_service_url'] = $serviceurl;
270     }
272     // Send user's name and email data if appropriate
273     if ( $typeconfig['sendname'] == LTI_SETTING_ALWAYS ||
274          ( $typeconfig['sendname'] == LTI_SETTING_DELEGATE && $instance->instructorchoicesendname == LTI_SETTING_ALWAYS ) ) {
275         $requestparams['lis_person_name_given'] =  $USER->firstname;
276         $requestparams['lis_person_name_family'] =  $USER->lastname;
277         $requestparams['lis_person_name_full'] =  $USER->firstname." ".$USER->lastname;
278     }
280     if ( $typeconfig['sendemailaddr'] == LTI_SETTING_ALWAYS ||
281          ( $typeconfig['sendemailaddr'] == LTI_SETTING_DELEGATE && $instance->instructorchoicesendemailaddr == LTI_SETTING_ALWAYS ) ) {
282         $requestparams['lis_person_contact_email_primary'] = $USER->email;
283     }
285     // Concatenate the custom parameters from the administrator and the instructor
286     // Instructor parameters are only taken into consideration if the administrator
287     // has giver permission
288     $customstr = $typeconfig['customparameters'];
289     $instructorcustomstr = $instance->instructorcustomparameters;
290     $custom = array();
291     $instructorcustom = array();
292     if ($customstr) {
293         $custom = lti_split_custom_parameters($customstr);
294     }
295     if (!isset($typeconfig['allowinstructorcustom']) || $typeconfig['allowinstructorcustom'] == LTI_SETTING_NEVER) {
296         $requestparams = array_merge($custom, $requestparams);
297     } else {
298         if ($instructorcustomstr) {
299             $instructorcustom = lti_split_custom_parameters($instructorcustomstr);
300         }
301         foreach ($instructorcustom as $key => $val) {
302             // Ignore the instructor's parameter
303             if (!array_key_exists($key, $custom)) {
304                 $custom[$key] = $val;
305             }
306         }
307         $requestparams = array_merge($custom, $requestparams);
308     }
310     // Make sure we let the tool know what LMS they are being called from
311     $requestparams["ext_lms"] = "moodle-2";
312     $requestparams['tool_consumer_info_product_family_code'] = 'moodle';
313     $requestparams['tool_consumer_info_version'] = strval($CFG->version);
315     // Add oauth_callback to be compliant with the 1.0A spec
316     $requestparams['oauth_callback'] = 'about:blank';
318     //The submit button needs to be part of the signature as it gets posted with the form.
319     //This needs to be here to support launching without javascript.
320     $submittext = get_string('press_to_submit', 'lti');
321     $requestparams['ext_submit'] = $submittext;
323     $requestparams['lti_version'] = 'LTI-1p0';
324     $requestparams['lti_message_type'] = 'basic-lti-launch-request';
326     return $requestparams;
329 function lti_get_tool_table($tools, $id) {
330     global $CFG, $USER;
331     $html = '';
333     $typename = get_string('typename', 'lti');
334     $baseurl = get_string('baseurl', 'lti');
335     $action = get_string('action', 'lti');
336     $createdon = get_string('createdon', 'lti');
338     if ($id == 'lti_configured') {
339         $html .= '<div><a style="margin-top:.25em" href="'.$CFG->wwwroot.'/mod/lti/typessettings.php?action=add&amp;sesskey='.$USER->sesskey.'">'.get_string('addtype', 'lti').'</a></div>';
340     }
342     if (!empty($tools)) {
343         $html .= "
344         <div id=\"{$id}_container\" style=\"margin-top:.5em;margin-bottom:.5em\">
345             <table id=\"{$id}_tools\">
346                 <thead>
347                     <tr>
348                         <th>$typename</th>
349                         <th>$baseurl</th>
350                         <th>$createdon</th>
351                         <th>$action</th>
352                     </tr>
353                 </thead>
354         ";
356         foreach ($tools as $type) {
357             $date = userdate($type->timecreated);
358             $accept = get_string('accept', 'lti');
359             $update = get_string('update', 'lti');
360             $delete = get_string('delete', 'lti');
362             $accepthtml = "
363                 <a class=\"editing_accept\" href=\"{$CFG->wwwroot}/mod/lti/typessettings.php?action=accept&amp;id={$type->id}&amp;sesskey={$USER->sesskey}&amp;tab={$id}\" title=\"{$accept}\">
364                     <img class=\"iconsmall\" alt=\"{$accept}\" src=\"{$CFG->wwwroot}/pix/t/clear.gif\"/>
365                 </a>
366             ";
368             $deleteaction = 'delete';
370             if ($type->state == LTI_TOOL_STATE_CONFIGURED) {
371                 $accepthtml = '';
372             }
374             if ($type->state != LTI_TOOL_STATE_REJECTED) {
375                 $deleteaction = 'reject';
376                 $delete = get_string('reject', 'lti');
377             }
379             $html .= "
380             <tr>
381                 <td>
382                     {$type->name}
383                 </td>
384                 <td>
385                     {$type->baseurl}
386                 </td>
387                 <td>
388                     {$date}
389                 </td>
390                 <td align=\"center\">
391                     {$accepthtml}
392                     <a class=\"editing_update\" href=\"{$CFG->wwwroot}/mod/lti/typessettings.php?action=update&amp;id={$type->id}&amp;sesskey={$USER->sesskey}&amp;tab={$id}\" title=\"{$update}\">
393                         <img class=\"iconsmall\" alt=\"{$update}\" src=\"{$CFG->wwwroot}/pix/t/edit.gif\"/>
394                     </a>
395                     <a class=\"editing_delete\" href=\"{$CFG->wwwroot}/mod/lti/typessettings.php?action={$deleteaction}&amp;id={$type->id}&amp;sesskey={$USER->sesskey}&amp;tab={$id}\" title=\"{$delete}\">
396                         <img class=\"iconsmall\" alt=\"{$delete}\" src=\"{$CFG->wwwroot}/pix/t/delete.gif\"/>
397                     </a>
398                 </td>
399             </tr>
400             ";
401         }
402         $html .= '</table></div>';
403     } else {
404         $html .= get_string('no_' . $id, 'lti');
405     }
407     return $html;
410 /**
411  * Splits the custom parameters field to the various parameters
412  *
413  * @param string $customstr     String containing the parameters
414  *
415  * @return Array of custom parameters
416  */
417 function lti_split_custom_parameters($customstr) {
418     $textlib = textlib_get_instance();
420     $lines = preg_split("/[\n;]/", $customstr);
421     $retval = array();
422     foreach ($lines as $line) {
423         $pos = strpos($line, "=");
424         if ( $pos === false || $pos < 1 ) {
425             continue;
426         }
427         $key = trim($textlib->substr($line, 0, $pos));
428         $val = trim($textlib->substr($line, $pos+1, strlen($line)));
429         $key = lti_map_keyname($key);
430         $retval['custom_'.$key] = $val;
431     }
432     return $retval;
435 /**
436  * Used for building the names of the different custom parameters
437  *
438  * @param string $key   Parameter name
439  *
440  * @return string       Processed name
441  */
442 function lti_map_keyname($key) {
443     $textlib = textlib_get_instance();
445     $newkey = "";
446     $key = $textlib->strtolower(trim($key));
447     foreach (str_split($key) as $ch) {
448         if ( ($ch >= 'a' && $ch <= 'z') || ($ch >= '0' && $ch <= '9') ) {
449             $newkey .= $ch;
450         } else {
451             $newkey .= '_';
452         }
453     }
454     return $newkey;
457 /**
458  * Gets the IMS role string for the specified user and LTI course module.
459  *
460  * @param mixed $user User object or user id
461  * @param int $cmid The course module id of the LTI activity
462  * @return string A role string suitable for passing with an LTI launch
463  */
464 function lti_get_ims_role($user, $cmid, $courseid) {
465     $roles = array();
467     if (empty($cmid)) {
468         //If no cmid is passed, check if the user is a teacher in the course
469         //This allows other modules to programmatically "fake" a launch without
470         //a real LTI instance
471         $coursecontext = get_context_instance(CONTEXT_COURSE, $courseid);
473         if (has_capability('moodle/course:manageactivities', $coursecontext)) {
474             array_push($roles, 'Instructor');
475         } else {
476             array_push($roles, 'Learner');
477         }
478     } else {
479         $context = get_context_instance(CONTEXT_MODULE, $cmid);
481         if (has_capability('mod/lti:manage', $context)) {
482             array_push($roles, 'Instructor');
483         } else {
484             array_push($roles, 'Learner');
485         }
486     }
488     if (is_siteadmin($user)) {
489         array_push($roles, 'urn:lti:sysrole:ims/lis/Administrator');
490     }
492     return join(',', $roles);
495 /**
496  * Returns configuration details for the tool
497  *
498  * @param int $typeid   Basic LTI tool typeid
499  *
500  * @return array        Tool Configuration
501  */
502 function lti_get_type_config($typeid) {
503     global $DB;
505     $query = "SELECT name, value
506                 FROM {lti_types_config}
507                WHERE typeid = :typeid1
508            UNION ALL
509               SELECT 'toolurl' AS name, baseurl AS value
510                 FROM {lti_types}
511                WHERE id = :typeid2";
513     $typeconfig = array();
514     $configs = $DB->get_records_sql($query, array('typeid1' => $typeid, 'typeid2' => $typeid));
516     if (!empty($configs)) {
517         foreach ($configs as $config) {
518             $typeconfig[$config->name] = $config->value;
519         }
520     }
522     return $typeconfig;
525 function lti_get_tools_by_url($url, $state, $courseid = null) {
526     $domain = lti_get_domain_from_url($url);
528     return lti_get_tools_by_domain($domain, $state, $courseid);
531 function lti_get_tools_by_domain($domain, $state = null, $courseid = null) {
532     global $DB, $SITE;
534     $filters = array('tooldomain' => $domain);
536     $statefilter = '';
537     $coursefilter = '';
539     if ($state) {
540         $statefilter = 'AND state = :state';
541     }
543     if ($courseid && $courseid != $SITE->id) {
544         $coursefilter = 'OR course = :courseid';
545     }
547     $query = "SELECT *
548                 FROM {lti_types}
549                WHERE tooldomain = :tooldomain
550                  AND (course = :siteid $coursefilter)
551                  $statefilter";
553     return $DB->get_records_sql($query, array(
554         'courseid' => $courseid,
555         'siteid' => $SITE->id,
556         'tooldomain' => $domain,
557         'state' => $state
558     ));
561 /**
562  * Returns all basicLTI tools configured by the administrator
563  *
564  */
565 function lti_filter_get_types($course) {
566     global $DB;
568     if (!empty($course)) {
569         $filter = array('course' => $course);
570     } else {
571         $filter = array();
572     }
574     return $DB->get_records('lti_types', $filter);
577 function lti_get_types_for_add_instance() {
578     global $DB, $SITE, $COURSE;
580     $query = "SELECT *
581                 FROM {lti_types}
582                WHERE coursevisible = 1
583                  AND (course = :siteid OR course = :courseid)
584                  AND state = :active";
586     $admintypes = $DB->get_records_sql($query, array('siteid' => $SITE->id, 'courseid' => $COURSE->id, 'active' => LTI_TOOL_STATE_CONFIGURED));
588     $types = array();
589     $types[0] = (object)array('name' => get_string('automatic', 'lti'), 'course' => $SITE->id);
591     foreach ($admintypes as $type) {
592         $types[$type->id] = $type;
593     }
595     return $types;
598 function lti_get_domain_from_url($url) {
599     $matches = array();
601     if (preg_match(LTI_URL_DOMAIN_REGEX, $url, $matches)) {
602         return $matches[1];
603     }
606 function lti_get_tool_by_url_match($url, $courseid = null, $state = LTI_TOOL_STATE_CONFIGURED) {
607     $possibletools = lti_get_tools_by_url($url, $state, $courseid);
609     return lti_get_best_tool_by_url($url, $possibletools, $courseid);
612 function lti_get_url_thumbprint($url) {
613     $urlparts = parse_url(strtolower($url));
614     if (!isset($urlparts['path'])) {
615         $urlparts['path'] = '';
616     }
618     if (!isset($urlparts['host'])) {
619         $urlparts['host'] = '';
620     }
622     if (substr($urlparts['host'], 0, 4) === 'www.') {
623         $urlparts['host'] = substr($urlparts['host'], 4);
624     }
626     return $urllower = $urlparts['host'] . '/' . $urlparts['path'];
629 function lti_get_best_tool_by_url($url, $tools, $courseid = null) {
630     if (count($tools) === 0) {
631         return null;
632     }
634     $urllower = lti_get_url_thumbprint($url);
636     foreach ($tools as $tool) {
637         $tool->_matchscore = 0;
639         $toolbaseurllower = lti_get_url_thumbprint($tool->baseurl);
641         if ($urllower === $toolbaseurllower) {
642             //100 points for exact thumbprint match
643             $tool->_matchscore += 100;
644         } else if (substr($urllower, 0, strlen($toolbaseurllower)) === $toolbaseurllower) {
645             //50 points if tool thumbprint starts with the base URL thumbprint
646             $tool->_matchscore += 50;
647         }
649         //Prefer course tools over site tools
650         if (!empty($courseid)) {
651             //Minus 25 points for not matching the course id (global tools)
652             if ($tool->course != $courseid) {
653                 $tool->_matchscore -= 10;
654             }
655         }
656     }
658     $bestmatch = array_reduce($tools, function($value, $tool) {
659         if ($tool->_matchscore > $value->_matchscore) {
660             return $tool;
661         } else {
662             return $value;
663         }
665     }, (object)array('_matchscore' => -1));
667     //None of the tools are suitable for this URL
668     if ($bestmatch->_matchscore <= 0) {
669         return null;
670     }
672     return $bestmatch;
675 function lti_get_shared_secrets_by_key($key) {
676     global $DB;
678     //Look up the shared secret for the specified key in both the types_config table (for configured tools)
679     //And in the lti resource table for ad-hoc tools
680     $query = "SELECT t2.value
681                 FROM {lti_types_config} t1
682                 JOIN {lti_types_config} t2 ON t1.typeid = t2.typeid
683                 JOIN {lti_types} type ON t2.typeid = type.id
684               WHERE t1.name = 'resourcekey'
685                 AND t1.value = :key1
686                 AND t2.name = 'password'
687                 AND type.state = :configured
688               UNION
689              SELECT password AS value
690                FROM {lti}
691               WHERE resourcekey = :key2";
693     $sharedsecrets = $DB->get_records_sql($query, array('configured' => LTI_TOOL_STATE_CONFIGURED, 'key1' => $key, 'key2' => $key));
695     $values = array_map(function($item) {
696         return $item->value;
697     }, $sharedsecrets);
699     //There should really only be one shared secret per key. But, we can't prevent
700     //more than one getting entered. For instance, if the same key is used for two tool providers.
701     return $values;
704 /**
705  * Prints the various configured tool types
706  *
707  */
708 function lti_filter_print_types() {
709     global $CFG;
711     $types = lti_filter_get_types();
712     if (!empty($types)) {
713         echo '<ul>';
714         foreach ($types as $type) {
715             echo '<li>'.
716             $type->name.
717             '<span class="commands">'.
718             '<a class="editing_update" href="typessettings.php?action=update&amp;id='.$type->id.'&amp;sesskey='.sesskey().'" title="Update">'.
719             '<img class="iconsmall" alt="Update" src="'.$CFG->wwwroot.'/pix/t/edit.gif"/>'.
720             '</a>'.
721             '<a class="editing_delete" href="typessettings.php?action=delete&amp;id='.$type->id.'&amp;sesskey='.sesskey().'" title="Delete">'.
722             '<img class="iconsmall" alt="Delete" src="'.$CFG->wwwroot.'/pix/t/delete.gif"/>'.
723             '</a>'.
724             '</span>'.
725             '</li>';
727         }
728         echo '</ul>';
729     } else {
730         echo '<div class="message">';
731         echo get_string('notypes', 'lti');
732         echo '</div>';
733     }
736 /**
737  * Delete a Basic LTI configuration
738  *
739  * @param int $id   Configuration id
740  */
741 function lti_delete_type($id) {
742     global $DB;
744     //We should probably just copy the launch URL to the tool instances in this case... using a single query
745     /*
746     $instances = $DB->get_records('lti', array('typeid' => $id));
747     foreach ($instances as $instance) {
748         $instance->typeid = 0;
749         $DB->update_record('lti', $instance);
750     }*/
752     $DB->delete_records('lti_types', array('id' => $id));
753     $DB->delete_records('lti_types_config', array('typeid' => $id));
756 function lti_set_state_for_type($id, $state) {
757     global $DB;
759     $DB->update_record('lti_types', array('id' => $id, 'state' => $state));
762 /**
763  * Transforms a basic LTI object to an array
764  *
765  * @param object $ltiobject    Basic LTI object
766  *
767  * @return array Basic LTI configuration details
768  */
769 function lti_get_config($ltiobject) {
770     $typeconfig = array();
771     $typeconfig = (array)$ltiobject;
772     $additionalconfig = lti_get_type_config($ltiobject->typeid);
773     $typeconfig = array_merge($typeconfig, $additionalconfig);
774     return $typeconfig;
777 /**
778  *
779  * Generates some of the tool configuration based on the instance details
780  *
781  * @param int $id
782  *
783  * @return Instance configuration
784  *
785  */
786 function lti_get_type_config_from_instance($id) {
787     global $DB;
789     $instance = $DB->get_record('lti', array('id' => $id));
790     $config = lti_get_config($instance);
792     $type = new stdClass();
793     $type->lti_fix = $id;
794     if (isset($config['toolurl'])) {
795         $type->lti_toolurl = $config['toolurl'];
796     }
797     if (isset($config['instructorchoicesendname'])) {
798         $type->lti_sendname = $config['instructorchoicesendname'];
799     }
800     if (isset($config['instructorchoicesendemailaddr'])) {
801         $type->lti_sendemailaddr = $config['instructorchoicesendemailaddr'];
802     }
803     if (isset($config['instructorchoiceacceptgrades'])) {
804         $type->lti_acceptgrades = $config['instructorchoiceacceptgrades'];
805     }
806     if (isset($config['instructorchoiceallowroster'])) {
807         $type->lti_allowroster = $config['instructorchoiceallowroster'];
808     }
810     if (isset($config['instructorcustomparameters'])) {
811         $type->lti_allowsetting = $config['instructorcustomparameters'];
812     }
813     return $type;
816 /**
817  * Generates some of the tool configuration based on the admin configuration details
818  *
819  * @param int $id
820  *
821  * @return Configuration details
822  */
823 function lti_get_type_type_config($id) {
824     global $DB;
826     $basicltitype = $DB->get_record('lti_types', array('id' => $id));
827     $config = lti_get_type_config($id);
829     $type->lti_typename = $basicltitype->name;
831     $type->typeid = $basicltitype->id;
833     $type->lti_toolurl = $basicltitype->baseurl;
835     if (isset($config['resourcekey'])) {
836         $type->lti_resourcekey = $config['resourcekey'];
837     }
838     if (isset($config['password'])) {
839         $type->lti_password = $config['password'];
840     }
842     if (isset($config['sendname'])) {
843         $type->lti_sendname = $config['sendname'];
844     }
845     if (isset($config['instructorchoicesendname'])) {
846         $type->lti_instructorchoicesendname = $config['instructorchoicesendname'];
847     }
848     if (isset($config['sendemailaddr'])) {
849         $type->lti_sendemailaddr = $config['sendemailaddr'];
850     }
851     if (isset($config['instructorchoicesendemailaddr'])) {
852         $type->lti_instructorchoicesendemailaddr = $config['instructorchoicesendemailaddr'];
853     }
854     if (isset($config['acceptgrades'])) {
855         $type->lti_acceptgrades = $config['acceptgrades'];
856     }
857     if (isset($config['instructorchoiceacceptgrades'])) {
858         $type->lti_instructorchoiceacceptgrades = $config['instructorchoiceacceptgrades'];
859     }
860     if (isset($config['allowroster'])) {
861         $type->lti_allowroster = $config['allowroster'];
862     }
863     if (isset($config['instructorchoiceallowroster'])) {
864         $type->lti_instructorchoiceallowroster = $config['instructorchoiceallowroster'];
865     }
867     if (isset($config['customparameters'])) {
868         $type->lti_customparameters = $config['customparameters'];
869     }
871     if (isset($config['forcessl'])) {
872         $type->lti_forcessl = $config['forcessl'];
873     }
875     if (isset($config['organizationid'])) {
876         $type->lti_organizationid = $config['organizationid'];
877     }
878     if (isset($config['organizationurl'])) {
879         $type->lti_organizationurl = $config['organizationurl'];
880     }
881     if (isset($config['organizationdescr'])) {
882         $type->lti_organizationdescr = $config['organizationdescr'];
883     }
884     if (isset($config['launchcontainer'])) {
885         $type->lti_launchcontainer = $config['launchcontainer'];
886     }
888     if (isset($config['coursevisible'])) {
889         $type->lti_coursevisible = $config['coursevisible'];
890     }
892     if (isset($config['debuglaunch'])) {
893         $type->lti_debuglaunch = $config['debuglaunch'];
894     }
896     if (isset($config['module_class_type'])) {
897             $type->lti_module_class_type = $config['module_class_type'];
898     }
900     return $type;
903 function lti_prepare_type_for_save($type, $config) {
904     $type->baseurl = $config->lti_toolurl;
905     $type->tooldomain = lti_get_domain_from_url($config->lti_toolurl);
906     $type->name = $config->lti_typename;
908     $type->coursevisible = !empty($config->lti_coursevisible) ? $config->lti_coursevisible : 0;
909     $config->lti_coursevisible = $type->coursevisible;
911     $type->forcessl = !empty($config->lti_forcessl) ? $config->lti_forcessl : 0;
912     $config->lti_forcessl = $type->forcessl;
914     $type->timemodified = time();
916     unset ($config->lti_typename);
917     unset ($config->lti_toolurl);
920 function lti_update_type($type, $config) {
921     global $DB;
923     lti_prepare_type_for_save($type, $config);
925     if ($DB->update_record('lti_types', $type)) {
926         foreach ($config as $key => $value) {
927             if (substr($key, 0, 4)=='lti_' && !is_null($value)) {
928                 $record = new StdClass();
929                 $record->typeid = $type->id;
930                 $record->name = substr($key, 4);
931                 $record->value = $value;
933                 lti_update_config($record);
934             }
935         }
936     }
939 function lti_add_type($type, $config) {
940     global $USER, $SITE, $DB;
942     lti_prepare_type_for_save($type, $config);
944     if (!isset($type->state)) {
945         $type->state = LTI_TOOL_STATE_PENDING;
946     }
948     if (!isset($type->timecreated)) {
949         $type->timecreated = time();
950     }
952     if (!isset($type->createdby)) {
953         $type->createdby = $USER->id;
954     }
956     if (!isset($type->course)) {
957         $type->course = $SITE->id;
958     }
960     //Create a salt value to be used for signing passed data to extension services
961     //The outcome service uses the service salt on the instance. This can be used
962     //for communication with services not related to a specific LTI instance.
963     $config->lti_servicesalt = uniqid('', true);
965     $id = $DB->insert_record('lti_types', $type);
967     if ($id) {
968         foreach ($config as $key => $value) {
969             if (substr($key, 0, 4)=='lti_' && !is_null($value)) {
970                 $record = new StdClass();
971                 $record->typeid = $id;
972                 $record->name = substr($key, 4);
973                 $record->value = $value;
975                 lti_add_config($record);
976             }
977         }
978     }
980     return $id;
983 /**
984  * Add a tool configuration in the database
985  *
986  * @param $config   Tool configuration
987  *
988  * @return int Record id number
989  */
990 function lti_add_config($config) {
991     global $DB;
993     return $DB->insert_record('lti_types_config', $config);
996 /**
997  * Updates a tool configuration in the database
998  *
999  * @param $config   Tool configuration
1000  *
1001  * @return Record id number
1002  */
1003 function lti_update_config($config) {
1004     global $DB;
1006     $return = true;
1007     $old = $DB->get_record('lti_types_config', array('typeid' => $config->typeid, 'name' => $config->name));
1009     if ($old) {
1010         $config->id = $old->id;
1011         $return = $DB->update_record('lti_types_config', $config);
1012     } else {
1013         $return = $DB->insert_record('lti_types_config', $config);
1014     }
1015     return $return;
1018 /**
1019  * Signs the petition to launch the external tool using OAuth
1020  *
1021  * @param $oldparms     Parameters to be passed for signing
1022  * @param $endpoint     url of the external tool
1023  * @param $method       Method for sending the parameters (e.g. POST)
1024  * @param $oauth_consumoer_key          Key
1025  * @param $oauth_consumoer_secret       Secret
1026  * @param $submittext  The text for the submit button
1027  * @param $orgid       LMS name
1028  * @param $orgdesc     LMS key
1029  */
1030 function lti_sign_parameters($oldparms, $endpoint, $method, $oauthconsumerkey, $oauthconsumersecret) {
1031     //global $lastbasestring;
1032     $parms = $oldparms;
1034     $testtoken = '';
1036     // TODO: Switch to core oauthlib once implemented - MDL-30149
1037     $hmacmethod = new lti\OAuthSignatureMethod_HMAC_SHA1();
1038     $testconsumer = new lti\OAuthConsumer($oauthconsumerkey, $oauthconsumersecret, null);
1039     $accreq = lti\OAuthRequest::from_consumer_and_token($testconsumer, $testtoken, $method, $endpoint, $parms);
1040     $accreq->sign_request($hmacmethod, $testconsumer, $testtoken);
1042     // Pass this back up "out of band" for debugging
1043     //$lastbasestring = $accreq->get_signature_base_string();
1045     $newparms = $accreq->get_parameters();
1047     return $newparms;
1050 /**
1051  * Posts the launch petition HTML
1052  *
1053  * @param $newparms     Signed parameters
1054  * @param $endpoint     URL of the external tool
1055  * @param $debug        Debug (true/false)
1056  */
1057 function lti_post_launch_html($newparms, $endpoint, $debug=false) {
1058     //global $lastbasestring;
1060     $r = "<form action=\"".$endpoint."\" name=\"ltiLaunchForm\" id=\"ltiLaunchForm\" method=\"post\" encType=\"application/x-www-form-urlencoded\">\n";
1062     $submittext = $newparms['ext_submit'];
1064     // Contruct html for the launch parameters
1065     foreach ($newparms as $key => $value) {
1066         $key = htmlspecialchars($key);
1067         $value = htmlspecialchars($value);
1068         if ( $key == "ext_submit" ) {
1069             $r .= "<input type=\"submit\" name=\"";
1070         } else {
1071             $r .= "<input type=\"hidden\" name=\"";
1072         }
1073         $r .= $key;
1074         $r .= "\" value=\"";
1075         $r .= $value;
1076         $r .= "\"/>\n";
1077     }
1079     if ( $debug ) {
1080         $r .= "<script language=\"javascript\"> \n";
1081         $r .= "  //<![CDATA[ \n";
1082         $r .= "function basicltiDebugToggle() {\n";
1083         $r .= "    var ele = document.getElementById(\"basicltiDebug\");\n";
1084         $r .= "    if (ele.style.display == \"block\") {\n";
1085         $r .= "        ele.style.display = \"none\";\n";
1086         $r .= "    }\n";
1087         $r .= "    else {\n";
1088         $r .= "        ele.style.display = \"block\";\n";
1089         $r .= "    }\n";
1090         $r .= "} \n";
1091         $r .= "  //]]> \n";
1092         $r .= "</script>\n";
1093         $r .= "<a id=\"displayText\" href=\"javascript:basicltiDebugToggle();\">";
1094         $r .= get_string("toggle_debug_data", "lti")."</a>\n";
1095         $r .= "<div id=\"basicltiDebug\" style=\"display:none\">\n";
1096         $r .=  "<b>".get_string("basiclti_endpoint", "lti")."</b><br/>\n";
1097         $r .= $endpoint . "<br/>\n&nbsp;<br/>\n";
1098         $r .=  "<b>".get_string("basiclti_parameters", "lti")."</b><br/>\n";
1099         foreach ($newparms as $key => $value) {
1100             $key = htmlspecialchars($key);
1101             $value = htmlspecialchars($value);
1102             $r .= "$key = $value<br/>\n";
1103         }
1104         $r .= "&nbsp;<br/>\n";
1105         //$r .= "<p><b>".get_string("basiclti_base_string", "lti")."</b><br/>\n".$lastbasestring."</p>\n";
1106         $r .= "</div>\n";
1107     }
1108     $r .= "</form>\n";
1110     if ( ! $debug ) {
1111         $ext_submit = "ext_submit";
1112         $ext_submit_text = $submittext;
1113         $r .= " <script type=\"text/javascript\"> \n" .
1114             "  //<![CDATA[ \n" .
1115             "    document.getElementById(\"ltiLaunchForm\").style.display = \"none\";\n" .
1116             "    nei = document.createElement('input');\n" .
1117             "    nei.setAttribute('type', 'hidden');\n" .
1118             "    nei.setAttribute('name', '".$ext_submit."');\n" .
1119             "    nei.setAttribute('value', '".$ext_submit_text."');\n" .
1120             "    document.getElementById(\"ltiLaunchForm\").appendChild(nei);\n" .
1121             "    document.ltiLaunchForm.submit(); \n" .
1122             "  //]]> \n" .
1123             " </script> \n";
1124     }
1125     return $r;
1128 function lti_get_type($typeid) {
1129     global $DB;
1131     return $DB->get_record('lti_types', array('id' => $typeid));
1134 function lti_get_launch_container($lti, $toolconfig) {
1135     if (empty($lti->launchcontainer)) {
1136         $lti->launchcontainer = LTI_LAUNCH_CONTAINER_DEFAULT;
1137     }
1139     if ($lti->launchcontainer == LTI_LAUNCH_CONTAINER_DEFAULT) {
1140         if (isset($toolconfig['launchcontainer'])) {
1141             $launchcontainer = $toolconfig['launchcontainer'];
1142         }
1143     } else {
1144         $launchcontainer = $lti->launchcontainer;
1145     }
1147     if (empty($launchcontainer) || $launchcontainer == LTI_LAUNCH_CONTAINER_DEFAULT) {
1148         $launchcontainer = LTI_LAUNCH_CONTAINER_EMBED_NO_BLOCKS;
1149     }
1151     $devicetype = get_device_type();
1153     //Scrolling within the object element doesn't work on iOS or Android
1154     //Opening the popup window also had some issues in testing
1155     //For mobile devices, always take up the entire screen to ensure the best experience
1156     if ($devicetype === 'mobile' || $devicetype === 'tablet' ) {
1157         $launchcontainer = LTI_LAUNCH_CONTAINER_REPLACE_MOODLE_WINDOW;
1158     }
1160     return $launchcontainer;
1163 function lti_request_is_using_ssl() {
1164     global $ME;
1165     return (stripos($ME, 'https://') === 0);
1168 function lti_ensure_url_is_https($url) {
1169     if (!strstr($url, '://')) {
1170         $url = 'https://' . $url;
1171     } else {
1172         //If the URL starts with http, replace with https
1173         if (stripos($url, 'http://') === 0) {
1174             $url = 'https://' . substr($url, 8);
1175         }
1176     }
1178     return $url;