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