4e1892d32b0bb4c050d99ae2df75c223babd1e38
[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  * @author     Chris Scribner
47  * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
48  */
50 defined('MOODLE_INTERNAL') || die;
52 // TODO: Switch to core oauthlib once implemented - MDL-30149
53 use moodle\mod\lti as lti;
55 require_once($CFG->dirroot.'/mod/lti/OAuth.php');
57 define('LTI_URL_DOMAIN_REGEX', '/(?:https?:\/\/)?(?:www\.)?([^\/]+)(?:\/|$)/i');
59 define('LTI_LAUNCH_CONTAINER_DEFAULT', 1);
60 define('LTI_LAUNCH_CONTAINER_EMBED', 2);
61 define('LTI_LAUNCH_CONTAINER_EMBED_NO_BLOCKS', 3);
62 define('LTI_LAUNCH_CONTAINER_WINDOW', 4);
63 define('LTI_LAUNCH_CONTAINER_REPLACE_MOODLE_WINDOW', 5);
65 define('LTI_TOOL_STATE_ANY', 0);
66 define('LTI_TOOL_STATE_CONFIGURED', 1);
67 define('LTI_TOOL_STATE_PENDING', 2);
68 define('LTI_TOOL_STATE_REJECTED', 3);
70 define('LTI_SETTING_NEVER', 0);
71 define('LTI_SETTING_ALWAYS', 1);
72 define('LTI_SETTING_DELEGATE', 2);
74 /**
75  * Prints a Basic LTI activity
76  *
77  * $param int $basicltiid       Basic LTI activity id
78  */
79 function lti_view($instance) {
80     global $PAGE, $CFG;
82     if (empty($instance->typeid)) {
83         $tool = lti_get_tool_by_url_match($instance->toolurl, $instance->course);
84         if ($tool) {
85             $typeid = $tool->id;
86         } else {
87             $typeid = null;
88         }
89     } else {
90         $typeid = $instance->typeid;
91     }
93     if ($typeid) {
94         $typeconfig = lti_get_type_config($typeid);
95     } else {
96         //There is no admin configuration for this tool. Use configuration in the lti instance record plus some defaults.
97         $typeconfig = (array)$instance;
99         $typeconfig['sendname'] = $instance->instructorchoicesendname;
100         $typeconfig['sendemailaddr'] = $instance->instructorchoicesendemailaddr;
101         $typeconfig['customparameters'] = $instance->instructorcustomparameters;
102         $typeconfig['acceptgrades'] = $instance->instructorchoiceacceptgrades;
103         $typeconfig['allowroster'] = $instance->instructorchoiceallowroster;
104         $typeconfig['forcessl'] = '0';
105     }
107     //Default the organizationid if not specified
108     if (empty($typeconfig['organizationid'])) {
109         $urlparts = parse_url($CFG->wwwroot);
111         $typeconfig['organizationid'] = $urlparts['host'];
112     }
114     if (!empty($instance->resourcekey)) {
115         $key = $instance->resourcekey;
116     } else if (!empty($typeconfig['resourcekey'])) {
117         $key = $typeconfig['resourcekey'];
118     } else {
119         $key = '';
120     }
122     if (!empty($instance->password)) {
123         $secret = $instance->password;
124     } else if (!empty($typeconfig['password'])) {
125         $secret = $typeconfig['password'];
126     } else {
127         $secret = '';
128     }
130     $endpoint = !empty($instance->toolurl) ? $instance->toolurl : $typeconfig['toolurl'];
131     $endpoint = trim($endpoint);
133     //If the current request is using SSL and a secure tool URL is specified, use it
134     if (lti_request_is_using_ssl() && !empty($instance->securetoolurl)) {
135         $endpoint = trim($instance->securetoolurl);
136     }
138     //If SSL is forced, use the secure tool url if specified. Otherwise, make sure https is on the normal launch URL.
139     if ($typeconfig['forcessl'] == '1') {
140         if (!empty($instance->securetoolurl)) {
141             $endpoint = trim($instance->securetoolurl);
142         }
144         $endpoint = lti_ensure_url_is_https($endpoint);
145     } else {
146         if (!strstr($endpoint, '://')) {
147             $endpoint = 'http://' . $endpoint;
148         }
149     }
151     $orgid = $typeconfig['organizationid'];
153     $course = $PAGE->course;
154     $requestparams = lti_build_request($instance, $typeconfig, $course);
156     $launchcontainer = lti_get_launch_container($instance, $typeconfig);
157     $returnurlparams = array('course' => $course->id, 'launch_container' => $launchcontainer, 'instanceid' => $instance->id);
159     if ( $orgid ) {
160         $requestparams["tool_consumer_instance_guid"] = $orgid;
161     }
163     if (empty($key) || empty($secret)) {
164         $returnurlparams['unsigned'] = '1';
166         //Add the return URL. We send the launch container along to help us avoid frames-within-frames when the user returns
167         $url = new moodle_url('/mod/lti/return.php', $returnurlparams);
168         $returnurl = $url->out(false);
170         if ($typeconfig['forcessl'] == '1') {
171             $returnurl = lti_ensure_url_is_https($returnurl);
172         }
174         $requestparams['launch_presentation_return_url'] = $returnurl;
175     }
177     if (!empty($key) && !empty($secret)) {
178         $parms = lti_sign_parameters($requestparams, $endpoint, "POST", $key, $secret);
179     } else {
180         //If no key and secret, do the launch unsigned.
181         $parms = $requestparams;
182     }
184     $debuglaunch = ( $instance->debuglaunch == 1 );
186     $content = lti_post_launch_html($parms, $endpoint, $debuglaunch);
188     echo $content;
191 function lti_build_sourcedid($instanceid, $userid, $launchid = null, $servicesalt) {
192     $data = new stdClass();
194     $data->instanceid = $instanceid;
195     $data->userid = $userid;
196     if (!empty($launchid)) {
197         $data->launchid = $launchid;
198     } else {
199         $data->launchid = mt_rand();
200     }
202     $json = json_encode($data);
204     $hash = hash('sha256', $json . $servicesalt, false);
206     $container = new stdClass();
207     $container->data = $data;
208     $container->hash = $hash;
210     return $container;
213 /**
214  * This function builds the request that must be sent to the tool producer
215  *
216  * @param object    $instance       Basic LTI instance object
217  * @param object    $typeconfig     Basic LTI tool configuration
218  * @param object    $course         Course object
219  *
220  * @return array    $request        Request details
221  */
222 function lti_build_request($instance, $typeconfig, $course) {
223     global $USER, $CFG;
225     if (empty($instance->cmid)) {
226         $instance->cmid = 0;
227     }
229     $role = lti_get_ims_role($USER, $instance->cmid, $instance->course);
231     $locale = $course->lang;
232     if ( strlen($locale) < 1 ) {
233          $locale = $CFG->lang;
234     }
236     $requestparams = array(
237         "resource_link_id" => $instance->id,
238         "resource_link_title" => $instance->name,
239         "resource_link_description" => $instance->intro,
240         "user_id" => $USER->id,
241         "roles" => $role,
242         "context_id" => $course->id,
243         "context_label" => $course->shortname,
244         "context_title" => $course->fullname,
245         "launch_presentation_locale" => $locale,
246     );
248     $placementsecret = $instance->servicesalt;
250     if ( isset($placementsecret) ) {
251         $sourcedid = json_encode(lti_build_sourcedid($instance->id, $USER->id, null, $placementsecret));
252     }
254     if ( isset($placementsecret) &&
255          ( $typeconfig['acceptgrades'] == LTI_SETTING_ALWAYS ||
256          ( $typeconfig['acceptgrades'] == LTI_SETTING_DELEGATE && $instance->instructorchoiceacceptgrades == LTI_SETTING_ALWAYS ) ) ) {
257         $requestparams["lis_result_sourcedid"] = $sourcedid;
259         $serviceurl = $CFG->wwwroot . '/mod/lti/service.php';
260         if ($typeconfig['forcessl'] == '1') {
261             $serviceurl = lti_ensure_url_is_https($serviceurl);
262         }
264         $requestparams["ext_ims_lis_basic_outcome_url"] = $serviceurl;
265     }
267     /*if ( isset($placementsecret) &&
268          ( $typeconfig['allowroster'] == LTI_SETTING_ALWAYS ||
269          ( $typeconfig['allowroster'] == LTI_SETTING_DELEGATE && $instance->instructorchoiceallowroster == LTI_SETTING_ALWAYS ) ) ) {
270         $requestparams["ext_ims_lis_memberships_id"] = $sourcedid;
271         $requestparams["ext_ims_lis_memberships_url"] = $CFG->wwwroot.'/mod/lti/service.php';
272     }*/
274     // Send user's name and email data if appropriate
275     if ( $typeconfig['sendname'] == LTI_SETTING_ALWAYS ||
276          ( $typeconfig['sendname'] == LTI_SETTING_DELEGATE && $instance->instructorchoicesendname == LTI_SETTING_ALWAYS ) ) {
277         $requestparams["lis_person_name_given"] =  $USER->firstname;
278         $requestparams["lis_person_name_family"] =  $USER->lastname;
279         $requestparams["lis_person_name_full"] =  $USER->firstname." ".$USER->lastname;
280     }
282     if ( $typeconfig['sendemailaddr'] == LTI_SETTING_ALWAYS ||
283          ( $typeconfig['sendemailaddr'] == LTI_SETTING_DELEGATE && $instance->instructorchoicesendemailaddr == LTI_SETTING_ALWAYS ) ) {
284         $requestparams["lis_person_contact_email_primary"] = $USER->email;
285     }
287     //Add outcome service URL
288     $url = new moodle_url('/mod/lti/service.php');
289     $requestparams['lis_outcome_service_url'] = $url->out();
291     // Concatenate the custom parameters from the administrator and the instructor
292     // Instructor parameters are only taken into consideration if the administrator
293     // has giver permission
294     $customstr = $typeconfig['customparameters'];
295     $instructorcustomstr = $instance->instructorcustomparameters;
296     $custom = array();
297     $instructorcustom = array();
298     if ($customstr) {
299         $custom = lti_split_custom_parameters($customstr);
300     }
301     if (!isset($typeconfig['allowinstructorcustom']) || $typeconfig['allowinstructorcustom'] == LTI_SETTING_NEVER) {
302         $requestparams = array_merge($custom, $requestparams);
303     } else {
304         if ($instructorcustomstr) {
305             $instructorcustom = lti_split_custom_parameters($instructorcustomstr);
306         }
307         foreach ($instructorcustom as $key => $val) {
308             // Ignore the instructor's parameter
309             if (!array_key_exists($key, $custom)) {
310                 $custom[$key] = $val;
311             }
312         }
313         $requestparams = array_merge($custom, $requestparams);
314     }
316     // Make sure we let the tool know what LMS they are being called from
317     $requestparams["ext_lms"] = "moodle-2";
319     // Add oauth_callback to be compliant with the 1.0A spec
320     $requestparams["oauth_callback"] = "about:blank";
322     //The submit button needs to be part of the signature as it gets posted with the form.
323     //This needs to be here to support launching without javascript.
324     $submittext = get_string('press_to_submit', 'lti');
325     $requestparams["ext_submit"] = $submittext;
327     $requestparams["lti_version"] = "LTI-1p0";
328     $requestparams["lti_message_type"] = "basic-lti-launch-request";
329     /* Suppress this for now - Chuck
330     if ( $orgdesc ) $requestparams["tool_consumer_instance_description"] = $orgdesc;
331     */
333     return $requestparams;
336 function lti_get_tool_table($tools, $id) {
337     global $CFG, $USER;
338     $html = '';
340     $typename = get_string('typename', 'lti');
341     $baseurl = get_string('baseurl', 'lti');
342     $action = get_string('action', 'lti');
343     $createdon = get_string('createdon', 'lti');
345     if ($id == 'lti_configured') {
346         $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>';
347     }
349     if (!empty($tools)) {
350         $html .= "
351         <div id=\"{$id}_container\" style=\"margin-top:.5em;margin-bottom:.5em\">
352             <table id=\"{$id}_tools\">
353                 <thead>
354                     <tr>
355                         <th>$typename</th>
356                         <th>$baseurl</th>
357                         <th>$createdon</th>
358                         <th>$action</th>
359                     </tr>
360                 </thead>
361         ";
363         foreach ($tools as $type) {
364             $date = userdate($type->timecreated);
365             $accept = get_string('accept', 'lti');
366             $update = get_string('update', 'lti');
367             $delete = get_string('delete', 'lti');
369             $accepthtml = "
370                 <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}\">
371                     <img class=\"iconsmall\" alt=\"{$accept}\" src=\"{$CFG->wwwroot}/pix/t/clear.gif\"/>
372                 </a>
373             ";
375             $deleteaction = 'delete';
377             if ($type->state == LTI_TOOL_STATE_CONFIGURED) {
378                 $accepthtml = '';
379             }
381             if ($type->state != LTI_TOOL_STATE_REJECTED) {
382                 $deleteaction = 'reject';
383                 $delete = get_string('reject', 'lti');
384             }
386             $html .= "
387             <tr>
388                 <td>
389                     {$type->name}
390                 </td>
391                 <td>
392                     {$type->baseurl}
393                 </td>
394                 <td>
395                     {$date}
396                 </td>
397                 <td align=\"center\">
398                     {$accepthtml}
399                     <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}\">
400                         <img class=\"iconsmall\" alt=\"{$update}\" src=\"{$CFG->wwwroot}/pix/t/edit.gif\"/>
401                     </a>
402                     <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}\">
403                         <img class=\"iconsmall\" alt=\"{$delete}\" src=\"{$CFG->wwwroot}/pix/t/delete.gif\"/>
404                     </a>
405                 </td>
406             </tr>
407             ";
408         }
409         $html .= '</table></div>';
410     } else {
411         $html .= get_string('no_' . $id, 'lti');
412     }
414     return $html;
417 /**
418  * Splits the custom parameters field to the various parameters
419  *
420  * @param string $customstr     String containing the parameters
421  *
422  * @return Array of custom parameters
423  */
424 function lti_split_custom_parameters($customstr) {
425     $textlib = textlib_get_instance();
427     $lines = preg_split("/[\n;]/", $customstr);
428     $retval = array();
429     foreach ($lines as $line) {
430         $pos = strpos($line, "=");
431         if ( $pos === false || $pos < 1 ) {
432             continue;
433         }
434         $key = trim($textlib->substr($line, 0, $pos));
435         $val = trim($textlib->substr($line, $pos+1));
436         $key = lti_map_keyname($key);
437         $retval['custom_'.$key] = $val;
438     }
439     return $retval;
442 /**
443  * Used for building the names of the different custom parameters
444  *
445  * @param string $key   Parameter name
446  *
447  * @return string       Processed name
448  */
449 function lti_map_keyname($key) {
450     $textlib = textlib_get_instance();
452     $newkey = "";
453     $key = $textlib->strtolower(trim($key));
454     foreach (str_split($key) as $ch) {
455         if ( ($ch >= 'a' && $ch <= 'z') || ($ch >= '0' && $ch <= '9') ) {
456             $newkey .= $ch;
457         } else {
458             $newkey .= '_';
459         }
460     }
461     return $newkey;
464 /**
465  * Gets the IMS role string for the specified user and LTI course module.
466  *
467  * @param mixed $user User object or user id
468  * @param int $cmid The course module id of the LTI activity
469  * @return string A role string suitable for passing with an LTI launch
470  */
471 function lti_get_ims_role($user, $cmid, $courseid) {
472     $roles = array();
474     if (empty($cmid)) {
475         //If no cmid is passed, check if the user is a teacher in the course
476         //This allows other modules to programmatically "fake" a launch without
477         //a real LTI instance
478         $coursecontext = get_context_instance(CONTEXT_COURSE, $courseid);
480         if (has_capability('moodle/course:manageactivities', $coursecontext)) {
481             array_push($roles, 'Instructor');
482         } else {
483             array_push($roles, 'Learner');
484         }
485     } else {
486         $context = get_context_instance(CONTEXT_MODULE, $cmid);
488         if (has_capability('mod/lti:manage', $context)) {
489             array_push($roles, 'Instructor');
490         } else {
491             array_push($roles, 'Learner');
492         }
493     }
495     if (is_siteadmin($user)) {
496         array_push($roles, 'urn:lti:sysrole:ims/lis/Administrator');
497     }
499     return join(',', $roles);
502 /**
503  * Returns configuration details for the tool
504  *
505  * @param int $typeid   Basic LTI tool typeid
506  *
507  * @return array        Tool Configuration
508  */
509 function lti_get_type_config($typeid) {
510     global $DB;
512     $query = "SELECT name, value
513                 FROM {lti_types_config}
514                WHERE typeid = :typeid1
515            UNION ALL
516               SELECT 'toolurl' AS name, baseurl AS value
517                 FROM {lti_types}
518                WHERE id = :typeid2";
520     $typeconfig = array();
521     $configs = $DB->get_records_sql($query, array('typeid1' => $typeid, 'typeid2' => $typeid));
523     if (!empty($configs)) {
524         foreach ($configs as $config) {
525             $typeconfig[$config->name] = $config->value;
526         }
527     }
529     return $typeconfig;
532 function lti_get_tools_by_url($url, $state, $courseid = null) {
533     $domain = lti_get_domain_from_url($url);
535     return lti_get_tools_by_domain($domain, $state, $courseid);
538 function lti_get_tools_by_domain($domain, $state = null, $courseid = null) {
539     global $DB, $SITE;
541     $filters = array('tooldomain' => $domain);
543     $statefilter = '';
544     $coursefilter = '';
546     if ($state) {
547         $statefilter = 'AND state = :state';
548     }
550     if ($courseid && $courseid != $SITE->id) {
551         $coursefilter = 'OR course = :courseid';
552     }
554     $query = "SELECT *
555                 FROM {lti_types}
556                WHERE tooldomain = :tooldomain
557                  AND (course = :siteid $coursefilter)
558                  $statefilter";
560     return $DB->get_records_sql($query, array(
561         'courseid' => $courseid,
562         'siteid' => $SITE->id,
563         'tooldomain' => $domain,
564         'state' => $state
565     ));
568 /**
569  * Returns all basicLTI tools configured by the administrator
570  *
571  */
572 function lti_filter_get_types($course) {
573     global $DB;
575     if (!empty($course)) {
576         $filter = array('course' => $course);
577     } else {
578         $filter = array();
579     }
581     return $DB->get_records('lti_types', $filter);
584 function lti_get_types_for_add_instance() {
585     global $DB, $SITE, $COURSE;
587     $query = "SELECT *
588                 FROM {lti_types}
589                WHERE coursevisible = 1
590                  AND (course = :siteid OR course = :courseid)
591                  AND state = :active";
593     $admintypes = $DB->get_records_sql($query, array('siteid' => $SITE->id, 'courseid' => $COURSE->id, 'active' => LTI_TOOL_STATE_CONFIGURED));
595     $types = array();
596     $types[0] = (object)array('name' => get_string('automatic', 'lti'), 'course' => $SITE->id);
598     foreach ($admintypes as $type) {
599         $types[$type->id] = $type;
600     }
602     return $types;
605 function lti_get_domain_from_url($url) {
606     $matches = array();
608     if (preg_match(LTI_URL_DOMAIN_REGEX, $url, $matches)) {
609         return $matches[1];
610     }
613 function lti_get_tool_by_url_match($url, $courseid = null, $state = LTI_TOOL_STATE_CONFIGURED) {
614     $possibletools = lti_get_tools_by_url($url, $state, $courseid);
616     return lti_get_best_tool_by_url($url, $possibletools, $courseid);
619 function lti_get_url_thumbprint($url) {
620     $urlparts = parse_url(strtolower($url));
621     if (!isset($urlparts['path'])) {
622         $urlparts['path'] = '';
623     }
625     if (!isset($urlparts['host'])) {
626         $urlparts['host'] = '';
627     }
629     if (substr($urlparts['host'], 0, 4) === 'www.') {
630         $urlparts['host'] = substr($urlparts['host'], 4);
631     }
633     return $urllower = $urlparts['host'] . '/' . $urlparts['path'];
636 function lti_get_best_tool_by_url($url, $tools, $courseid = null) {
637     if (count($tools) === 0) {
638         return null;
639     }
641     $urllower = lti_get_url_thumbprint($url);
643     foreach ($tools as $tool) {
644         $tool->_matchscore = 0;
646         $toolbaseurllower = lti_get_url_thumbprint($tool->baseurl);
648         if ($urllower === $toolbaseurllower) {
649             //100 points for exact thumbprint match
650             $tool->_matchscore += 100;
651         } else if (substr($urllower, 0, strlen($toolbaseurllower)) === $toolbaseurllower) {
652             //50 points if tool thumbprint starts with the base URL thumbprint
653             $tool->_matchscore += 50;
654         }
656         //Prefer course tools over site tools
657         if (!empty($courseid)) {
658             //Minus 25 points for not matching the course id (global tools)
659             if ($tool->course != $courseid) {
660                 $tool->_matchscore -= 10;
661             }
662         }
663     }
665     $bestmatch = array_reduce($tools, function($value, $tool) {
666         if ($tool->_matchscore > $value->_matchscore) {
667             return $tool;
668         } else {
669             return $value;
670         }
672     }, (object)array('_matchscore' => -1));
674     //None of the tools are suitable for this URL
675     if ($bestmatch->_matchscore <= 0) {
676         return null;
677     }
679     return $bestmatch;
682 function lti_get_shared_secrets_by_key($key) {
683     global $DB;
685     //Look up the shared secret for the specified key in both the types_config table (for configured tools)
686     //And in the lti resource table for ad-hoc tools
687     $query = "SELECT t2.value
688                 FROM {lti_types_config} t1
689                 JOIN {lti_types_config} t2 ON t1.typeid = t2.typeid
690                 JOIN {lti_types} type ON t2.typeid = type.id
691               WHERE t1.name = 'resourcekey'
692                 AND t1.value = :key1
693                 AND t2.name = 'password'
694                 AND type.state = :configured
695               UNION
696              SELECT password AS value
697                FROM {lti}
698               WHERE resourcekey = :key2";
700     $sharedsecrets = $DB->get_records_sql($query, array('configured' => LTI_TOOL_STATE_CONFIGURED, 'key1' => $key, 'key2' => $key));
702     $values = array_map(function($item) {
703         return $item->value;
704     }, $sharedsecrets);
706     //There should really only be one shared secret per key. But, we can't prevent
707     //more than one getting entered. For instance, if the same key is used for two tool providers.
708     return $values;
711 /**
712  * Prints the various configured tool types
713  *
714  */
715 function lti_filter_print_types() {
716     global $CFG;
718     $types = lti_filter_get_types();
719     if (!empty($types)) {
720         echo '<ul>';
721         foreach ($types as $type) {
722             echo '<li>'.
723             $type->name.
724             '<span class="commands">'.
725             '<a class="editing_update" href="typessettings.php?action=update&amp;id='.$type->id.'&amp;sesskey='.sesskey().'" title="Update">'.
726             '<img class="iconsmall" alt="Update" src="'.$CFG->wwwroot.'/pix/t/edit.gif"/>'.
727             '</a>'.
728             '<a class="editing_delete" href="typessettings.php?action=delete&amp;id='.$type->id.'&amp;sesskey='.sesskey().'" title="Delete">'.
729             '<img class="iconsmall" alt="Delete" src="'.$CFG->wwwroot.'/pix/t/delete.gif"/>'.
730             '</a>'.
731             '</span>'.
732             '</li>';
734         }
735         echo '</ul>';
736     } else {
737         echo '<div class="message">';
738         echo get_string('notypes', 'lti');
739         echo '</div>';
740     }
743 /**
744  * Delete a Basic LTI configuration
745  *
746  * @param int $id   Configuration id
747  */
748 function lti_delete_type($id) {
749     global $DB;
751     //We should probably just copy the launch URL to the tool instances in this case... using a single query
752     /*
753     $instances = $DB->get_records('lti', array('typeid' => $id));
754     foreach ($instances as $instance) {
755         $instance->typeid = 0;
756         $DB->update_record('lti', $instance);
757     }*/
759     $DB->delete_records('lti_types', array('id' => $id));
760     $DB->delete_records('lti_types_config', array('typeid' => $id));
763 function lti_set_state_for_type($id, $state) {
764     global $DB;
766     $DB->update_record('lti_types', array('id' => $id, 'state' => $state));
769 /**
770  * Transforms a basic LTI object to an array
771  *
772  * @param object $ltiobject    Basic LTI object
773  *
774  * @return array Basic LTI configuration details
775  */
776 function lti_get_config($ltiobject) {
777     $typeconfig = array();
778     $typeconfig = (array)$ltiobject;
779     $additionalconfig = lti_get_type_config($ltiobject->typeid);
780     $typeconfig = array_merge($typeconfig, $additionalconfig);
781     return $typeconfig;
784 /**
785  *
786  * Generates some of the tool configuration based on the instance details
787  *
788  * @param int $id
789  *
790  * @return Instance configuration
791  *
792  */
793 function lti_get_type_config_from_instance($id) {
794     global $DB;
796     $instance = $DB->get_record('lti', array('id' => $id));
797     $config = lti_get_config($instance);
799     $type = new stdClass();
800     $type->lti_fix = $id;
801     if (isset($config['toolurl'])) {
802         $type->lti_toolurl = $config['toolurl'];
803     }
804     if (isset($config['instructorchoicesendname'])) {
805         $type->lti_sendname = $config['instructorchoicesendname'];
806     }
807     if (isset($config['instructorchoicesendemailaddr'])) {
808         $type->lti_sendemailaddr = $config['instructorchoicesendemailaddr'];
809     }
810     if (isset($config['instructorchoiceacceptgrades'])) {
811         $type->lti_acceptgrades = $config['instructorchoiceacceptgrades'];
812     }
813     if (isset($config['instructorchoiceallowroster'])) {
814         $type->lti_allowroster = $config['instructorchoiceallowroster'];
815     }
817     if (isset($config['instructorcustomparameters'])) {
818         $type->lti_allowsetting = $config['instructorcustomparameters'];
819     }
820     return $type;
823 /**
824  * Generates some of the tool configuration based on the admin configuration details
825  *
826  * @param int $id
827  *
828  * @return Configuration details
829  */
830 function lti_get_type_type_config($id) {
831     global $DB;
833     $basicltitype = $DB->get_record('lti_types', array('id' => $id));
834     $config = lti_get_type_config($id);
836     $type->lti_typename = $basicltitype->name;
838     $type->typeid = $basicltitype->id;
840     $type->lti_toolurl = $basicltitype->baseurl;
842     if (isset($config['resourcekey'])) {
843         $type->lti_resourcekey = $config['resourcekey'];
844     }
845     if (isset($config['password'])) {
846         $type->lti_password = $config['password'];
847     }
849     if (isset($config['sendname'])) {
850         $type->lti_sendname = $config['sendname'];
851     }
852     if (isset($config['instructorchoicesendname'])) {
853         $type->lti_instructorchoicesendname = $config['instructorchoicesendname'];
854     }
855     if (isset($config['sendemailaddr'])) {
856         $type->lti_sendemailaddr = $config['sendemailaddr'];
857     }
858     if (isset($config['instructorchoicesendemailaddr'])) {
859         $type->lti_instructorchoicesendemailaddr = $config['instructorchoicesendemailaddr'];
860     }
861     if (isset($config['acceptgrades'])) {
862         $type->lti_acceptgrades = $config['acceptgrades'];
863     }
864     if (isset($config['instructorchoiceacceptgrades'])) {
865         $type->lti_instructorchoiceacceptgrades = $config['instructorchoiceacceptgrades'];
866     }
867     if (isset($config['allowroster'])) {
868         $type->lti_allowroster = $config['allowroster'];
869     }
870     if (isset($config['instructorchoiceallowroster'])) {
871         $type->lti_instructorchoiceallowroster = $config['instructorchoiceallowroster'];
872     }
874     if (isset($config['customparameters'])) {
875         $type->lti_customparameters = $config['customparameters'];
876     }
878     if (isset($config['forcessl'])) {
879         $type->lti_forcessl = $config['forcessl'];
880     }
882     if (isset($config['organizationid'])) {
883         $type->lti_organizationid = $config['organizationid'];
884     }
885     if (isset($config['organizationurl'])) {
886         $type->lti_organizationurl = $config['organizationurl'];
887     }
888     if (isset($config['organizationdescr'])) {
889         $type->lti_organizationdescr = $config['organizationdescr'];
890     }
891     if (isset($config['launchcontainer'])) {
892         $type->lti_launchcontainer = $config['launchcontainer'];
893     }
895     if (isset($config['coursevisible'])) {
896         $type->lti_coursevisible = $config['coursevisible'];
897     }
899     if (isset($config['debuglaunch'])) {
900         $type->lti_debuglaunch = $config['debuglaunch'];
901     }
903     if (isset($config['module_class_type'])) {
904             $type->lti_module_class_type = $config['module_class_type'];
905     }
907     return $type;
910 function lti_prepare_type_for_save($type, $config) {
911     $type->baseurl = $config->lti_toolurl;
912     $type->tooldomain = lti_get_domain_from_url($config->lti_toolurl);
913     $type->name = $config->lti_typename;
915     $type->coursevisible = !empty($config->lti_coursevisible) ? $config->lti_coursevisible : 0;
916     $config->lti_coursevisible = $type->coursevisible;
918     $type->forcessl = !empty($config->lti_forcessl) ? $config->lti_forcessl : 0;
919     $config->lti_forcessl = $type->forcessl;
921     $type->timemodified = time();
923     unset ($config->lti_typename);
924     unset ($config->lti_toolurl);
927 function lti_update_type($type, $config) {
928     global $DB;
930     lti_prepare_type_for_save($type, $config);
932     if ($DB->update_record('lti_types', $type)) {
933         foreach ($config as $key => $value) {
934             if (substr($key, 0, 4)=='lti_' && !is_null($value)) {
935                 $record = new StdClass();
936                 $record->typeid = $type->id;
937                 $record->name = substr($key, 4);
938                 $record->value = $value;
940                 lti_update_config($record);
941             }
942         }
943     }
946 function lti_add_type($type, $config) {
947     global $USER, $SITE, $DB;
949     lti_prepare_type_for_save($type, $config);
951     if (!isset($type->state)) {
952         $type->state = LTI_TOOL_STATE_PENDING;
953     }
955     if (!isset($type->timecreated)) {
956         $type->timecreated = time();
957     }
959     if (!isset($type->createdby)) {
960         $type->createdby = $USER->id;
961     }
963     if (!isset($type->course)) {
964         $type->course = $SITE->id;
965     }
967     //Create a salt value to be used for signing passed data to extension services
968     //The outcome service uses the service salt on the instance. This can be used
969     //for communication with services not related to a specific LTI instance.
970     $config->lti_servicesalt = uniqid('', true);
972     $id = $DB->insert_record('lti_types', $type);
974     if ($id) {
975         foreach ($config as $key => $value) {
976             if (substr($key, 0, 4)=='lti_' && !is_null($value)) {
977                 $record = new StdClass();
978                 $record->typeid = $id;
979                 $record->name = substr($key, 4);
980                 $record->value = $value;
982                 lti_add_config($record);
983             }
984         }
985     }
987     return $id;
990 /**
991  * Add a tool configuration in the database
992  *
993  * @param $config   Tool configuration
994  *
995  * @return int Record id number
996  */
997 function lti_add_config($config) {
998     global $DB;
1000     return $DB->insert_record('lti_types_config', $config);
1003 /**
1004  * Updates a tool configuration in the database
1005  *
1006  * @param $config   Tool configuration
1007  *
1008  * @return Record id number
1009  */
1010 function lti_update_config($config) {
1011     global $DB;
1013     $return = true;
1014     $old = $DB->get_record('lti_types_config', array('typeid' => $config->typeid, 'name' => $config->name));
1016     if ($old) {
1017         $config->id = $old->id;
1018         $return = $DB->update_record('lti_types_config', $config);
1019     } else {
1020         $return = $DB->insert_record('lti_types_config', $config);
1021     }
1022     return $return;
1025 /**
1026  * Signs the petition to launch the external tool using OAuth
1027  *
1028  * @param $oldparms     Parameters to be passed for signing
1029  * @param $endpoint     url of the external tool
1030  * @param $method       Method for sending the parameters (e.g. POST)
1031  * @param $oauth_consumoer_key          Key
1032  * @param $oauth_consumoer_secret       Secret
1033  * @param $submittext  The text for the submit button
1034  * @param $orgid       LMS name
1035  * @param $orgdesc     LMS key
1036  */
1037 function lti_sign_parameters($oldparms, $endpoint, $method, $oauthconsumerkey, $oauthconsumersecret) {
1038     //global $lastbasestring;
1039     $parms = $oldparms;
1041     $testtoken = '';
1043     // TODO: Switch to core oauthlib once implemented - MDL-30149
1044     $hmacmethod = new lti\OAuthSignatureMethod_HMAC_SHA1();
1045     $testconsumer = new lti\OAuthConsumer($oauthconsumerkey, $oauthconsumersecret, null);
1046     $accreq = lti\OAuthRequest::from_consumer_and_token($testconsumer, $testtoken, $method, $endpoint, $parms);
1047     $accreq->sign_request($hmacmethod, $testconsumer, $testtoken);
1049     // Pass this back up "out of band" for debugging
1050     //$lastbasestring = $accreq->get_signature_base_string();
1052     $newparms = $accreq->get_parameters();
1054     return $newparms;
1057 /**
1058  * Posts the launch petition HTML
1059  *
1060  * @param $newparms     Signed parameters
1061  * @param $endpoint     URL of the external tool
1062  * @param $debug        Debug (true/false)
1063  */
1064 function lti_post_launch_html($newparms, $endpoint, $debug=false) {
1065     //global $lastbasestring;
1067     $r = "<form action=\"".$endpoint."\" name=\"ltiLaunchForm\" id=\"ltiLaunchForm\" method=\"post\" encType=\"application/x-www-form-urlencoded\">\n";
1069     $submittext = $newparms['ext_submit'];
1071     // Contruct html for the launch parameters
1072     foreach ($newparms as $key => $value) {
1073         $key = htmlspecialchars($key);
1074         $value = htmlspecialchars($value);
1075         if ( $key == "ext_submit" ) {
1076             $r .= "<input type=\"submit\" name=\"";
1077         } else {
1078             $r .= "<input type=\"hidden\" name=\"";
1079         }
1080         $r .= $key;
1081         $r .= "\" value=\"";
1082         $r .= $value;
1083         $r .= "\"/>\n";
1084     }
1086     if ( $debug ) {
1087         $r .= "<script language=\"javascript\"> \n";
1088         $r .= "  //<![CDATA[ \n";
1089         $r .= "function basicltiDebugToggle() {\n";
1090         $r .= "    var ele = document.getElementById(\"basicltiDebug\");\n";
1091         $r .= "    if (ele.style.display == \"block\") {\n";
1092         $r .= "        ele.style.display = \"none\";\n";
1093         $r .= "    }\n";
1094         $r .= "    else {\n";
1095         $r .= "        ele.style.display = \"block\";\n";
1096         $r .= "    }\n";
1097         $r .= "} \n";
1098         $r .= "  //]]> \n";
1099         $r .= "</script>\n";
1100         $r .= "<a id=\"displayText\" href=\"javascript:basicltiDebugToggle();\">";
1101         $r .= get_string("toggle_debug_data", "lti")."</a>\n";
1102         $r .= "<div id=\"basicltiDebug\" style=\"display:none\">\n";
1103         $r .=  "<b>".get_string("basiclti_endpoint", "lti")."</b><br/>\n";
1104         $r .= $endpoint . "<br/>\n&nbsp;<br/>\n";
1105         $r .=  "<b>".get_string("basiclti_parameters", "lti")."</b><br/>\n";
1106         foreach ($newparms as $key => $value) {
1107             $key = htmlspecialchars($key);
1108             $value = htmlspecialchars($value);
1109             $r .= "$key = $value<br/>\n";
1110         }
1111         $r .= "&nbsp;<br/>\n";
1112         //$r .= "<p><b>".get_string("basiclti_base_string", "lti")."</b><br/>\n".$lastbasestring."</p>\n";
1113         $r .= "</div>\n";
1114     }
1115     $r .= "</form>\n";
1117     if ( ! $debug ) {
1118         $ext_submit = "ext_submit";
1119         $ext_submit_text = $submittext;
1120         $r .= " <script type=\"text/javascript\"> \n" .
1121             "  //<![CDATA[ \n" .
1122             "    document.getElementById(\"ltiLaunchForm\").style.display = \"none\";\n" .
1123             "    nei = document.createElement('input');\n" .
1124             "    nei.setAttribute('type', 'hidden');\n" .
1125             "    nei.setAttribute('name', '".$ext_submit."');\n" .
1126             "    nei.setAttribute('value', '".$ext_submit_text."');\n" .
1127             "    document.getElementById(\"ltiLaunchForm\").appendChild(nei);\n" .
1128             "    document.ltiLaunchForm.submit(); \n" .
1129             "  //]]> \n" .
1130             " </script> \n";
1131     }
1132     return $r;
1135 function lti_get_type($typeid) {
1136     global $DB;
1138     return $DB->get_record('lti_types', array('id' => $typeid));
1141 function lti_get_launch_container($lti, $toolconfig) {
1142     if (empty($lti->launchcontainer)) {
1143         $lti->launchcontainer = LTI_LAUNCH_CONTAINER_DEFAULT;
1144     }
1146     if ($lti->launchcontainer == LTI_LAUNCH_CONTAINER_DEFAULT) {
1147         if (isset($toolconfig['launchcontainer'])) {
1148             $launchcontainer = $toolconfig['launchcontainer'];
1149         }
1150     } else {
1151         $launchcontainer = $lti->launchcontainer;
1152     }
1154     if (empty($launchcontainer) || $launchcontainer == LTI_LAUNCH_CONTAINER_DEFAULT) {
1155         $launchcontainer = LTI_LAUNCH_CONTAINER_EMBED_NO_BLOCKS;
1156     }
1158     $devicetype = get_device_type();
1160     //Scrolling within the object element doesn't work on iOS or Android
1161     //Opening the popup window also had some issues in testing
1162     //For mobile devices, always take up the entire screen to ensure the best experience
1163     if ($devicetype === 'mobile' || $devicetype === 'tablet' ) {
1164         $launchcontainer = LTI_LAUNCH_CONTAINER_REPLACE_MOODLE_WINDOW;
1165     }
1167     return $launchcontainer;
1170 function lti_request_is_using_ssl() {
1171     global $ME;
1172     return (stripos($ME, 'https://') === 0);
1175 function lti_ensure_url_is_https($url) {
1176     if (!strstr($url, '://')) {
1177         $url = 'https://' . $url;
1178     } else {
1179         //If the URL starts with http, replace with https
1180         if (stripos($url, 'http://') === 0) {
1181             $url = 'https://' . substr($url, 8);
1182         }
1183     }
1185     return $url;