Fix a bug introduced recently that broke launches (adding the return url after signin...
[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
CS
141 $launchcontainer = lti_get_launch_container($instance, $typeconfig);
142 $returnurlparams = array('course' => $course->id, 'launch_container' => $launchcontainer);
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
152 $url = new moodle_url('/mod/lti/return.php', $returnurlparams);
153 $parms['launch_presentation_return_url'] = $url->out(false);
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
204 $context = get_context_instance(CONTEXT_COURSE, $course->id);
205 $role = lti_get_ims_role($USER, $context);
206
207 $locale = $course->lang;
208 if ( strlen($locale) < 1 ) {
209 $locale = $CFG->lang;
210 }
211
212 $requestparams = array(
213 "resource_link_id" => $instance->id,
214 "resource_link_title" => $instance->name,
215 "resource_link_description" => $instance->intro,
216 "user_id" => $USER->id,
217 "roles" => $role,
218 "context_id" => $course->id,
219 "context_label" => $course->shortname,
220 "context_title" => $course->fullname,
221 "launch_presentation_locale" => $locale,
222 );
223
b9b2e7bb
CS
224 $placementsecret = $instance->servicesalt;
225
226 if ( isset($placementsecret) ) {
f4f711d7 227 $sourcedid = json_encode(lti_build_sourcedid($instance->id, $USER->id, null, $placementsecret));
b9b2e7bb
CS
228 }
229
230 if ( isset($placementsecret) &&
5e078d62
CS
231 ( $typeconfig['acceptgrades'] == LTI_SETTING_ALWAYS ||
232 ( $typeconfig['acceptgrades'] == LTI_SETTING_DELEGATE && $instance->instructorchoiceacceptgrades == LTI_SETTING_ALWAYS ) ) ) {
b9b2e7bb
CS
233 $requestparams["lis_result_sourcedid"] = $sourcedid;
234 $requestparams["ext_ims_lis_basic_outcome_url"] = $CFG->wwwroot.'/mod/lti/service.php';
235 }
236
9d57ad17 237 /*if ( isset($placementsecret) &&
5e078d62
CS
238 ( $typeconfig['allowroster'] == LTI_SETTING_ALWAYS ||
239 ( $typeconfig['allowroster'] == LTI_SETTING_DELEGATE && $instance->instructorchoiceallowroster == LTI_SETTING_ALWAYS ) ) ) {
b9b2e7bb
CS
240 $requestparams["ext_ims_lis_memberships_id"] = $sourcedid;
241 $requestparams["ext_ims_lis_memberships_url"] = $CFG->wwwroot.'/mod/lti/service.php';
9d57ad17 242 }*/
b9b2e7bb
CS
243
244 // Send user's name and email data if appropriate
5e078d62
CS
245 if ( $typeconfig['sendname'] == LTI_SETTING_ALWAYS ||
246 ( $typeconfig['sendname'] == LTI_SETTING_DELEGATE && $instance->instructorchoicesendname == LTI_SETTING_ALWAYS ) ) {
b9b2e7bb
CS
247 $requestparams["lis_person_name_given"] = $USER->firstname;
248 $requestparams["lis_person_name_family"] = $USER->lastname;
249 $requestparams["lis_person_name_full"] = $USER->firstname." ".$USER->lastname;
250 }
251
5e078d62
CS
252 if ( $typeconfig['sendemailaddr'] == LTI_SETTING_ALWAYS ||
253 ( $typeconfig['sendemailaddr'] == LTI_SETTING_DELEGATE && $instance->instructorchoicesendemailaddr == LTI_SETTING_ALWAYS ) ) {
b9b2e7bb
CS
254 $requestparams["lis_person_contact_email_primary"] = $USER->email;
255 }
256
3ff01b2f
CS
257 //Add outcome service URL
258 $url = new moodle_url('/mod/lti/service.php');
259 $requestparams['lis_outcome_service_url'] = $url->out();
57d1dffd 260
b9b2e7bb
CS
261 // Concatenate the custom parameters from the administrator and the instructor
262 // Instructor parameters are only taken into consideration if the administrator
263 // has giver permission
264 $customstr = $typeconfig['customparameters'];
265 $instructorcustomstr = $instance->instructorcustomparameters;
266 $custom = array();
267 $instructorcustom = array();
268 if ($customstr) {
dbb0fec9 269 $custom = lti_split_custom_parameters($customstr);
b9b2e7bb 270 }
5e078d62 271 if (!isset($typeconfig['allowinstructorcustom']) || $typeconfig['allowinstructorcustom'] == LTI_SETTING_NEVER) {
b9b2e7bb
CS
272 $requestparams = array_merge($custom, $requestparams);
273 } else {
274 if ($instructorcustomstr) {
dbb0fec9 275 $instructorcustom = lti_split_custom_parameters($instructorcustomstr);
b9b2e7bb
CS
276 }
277 foreach ($instructorcustom as $key => $val) {
278 if (array_key_exists($key, $custom)) {
279 // Ignore the instructor's parameter
280 } else {
281 $custom[$key] = $val;
282 }
283 }
284 $requestparams = array_merge($custom, $requestparams);
285 }
286
3dd9ca24
CS
287 // Make sure we let the tool know what LMS they are being called from
288 $requestparams["ext_lms"] = "moodle-2";
289
290 // Add oauth_callback to be compliant with the 1.0A spec
291 $requestparams["oauth_callback"] = "about:blank";
292
293 $submittext = get_string('press_to_submit', 'lti');
294 $requestparams["ext_submit"] = $submittext;
295
296 $requestparams["lti_version"] = "LTI-1p0";
297 $requestparams["lti_message_type"] = "basic-lti-launch-request";
298 /* Suppress this for now - Chuck
299 if ( $orgdesc ) $requestparams["tool_consumer_instance_description"] = $orgdesc;
300 */
301
b9b2e7bb
CS
302 return $requestparams;
303}
304
795dff01
CS
305function lti_get_tool_table($tools, $id){
306 global $CFG, $USER;
307 $html = '';
308
309 $typename = get_string('typename', 'lti');
310 $baseurl = get_string('baseurl', 'lti');
311 $action = get_string('action', 'lti');
312 $createdon = get_string('createdon', 'lti');
313
314 if($id == 'lti_configured'){
315 $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>';
316 }
317
318 if (!empty($tools)) {
319 $html .= <<<HTML
320 <div id="{$id}_container" style="margin-top:.5em;margin-bottom:.5em">
321 <table id="{$id}_tools">
322 <thead>
323 <tr>
324 <th>$typename</th>
325 <th>$baseurl</th>
326 <th>$createdon</th>
327 <th>$action</th>
328 </tr>
329 </thead>
330HTML;
331
332 foreach ($tools as $type) {
333 $date = userdate($type->timecreated);
334 $accept = get_string('accept', 'lti');
335 $update = get_string('update', 'lti');
336 $delete = get_string('delete', 'lti');
337
338 $accepthtml = <<<HTML
339 <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}">
340 <img class="iconsmall" alt="{$accept}" src="{$CFG->wwwroot}/pix/t/clear.gif"/>
341 </a>
342HTML;
343
344 $deleteaction = 'delete';
345
346 if($type->state == LTI_TOOL_STATE_CONFIGURED){
347 $accepthtml = '';
348 }
349
350 if($type->state != LTI_TOOL_STATE_REJECTED) {
351 $deleteaction = 'reject';
352 $delete = get_string('reject', 'lti');
353 }
354
355 $html .= <<<HTML
356 <tr>
357 <td>
358 {$type->name}
359 </td>
360 <td>
361 {$type->baseurl}
362 </td>
363 <td>
364 {$date}
365 </td>
366 <td align="center">
367 {$accepthtml}
368 <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}">
369 <img class="iconsmall" alt="{$update}" src="{$CFG->wwwroot}/pix/t/edit.gif"/>
370 </a>
371 <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}">
372 <img class="iconsmall" alt="{$delete}" src="{$CFG->wwwroot}/pix/t/delete.gif"/>
373 </a>
374 </td>
375 </tr>
376HTML;
377 }
378 $html .= '</table></div>';
379 } else {
380 $html .= get_string('no_' . $id, 'lti');
381 }
382
383 return $html;
384}
385
b9b2e7bb
CS
386/**
387 * Splits the custom parameters field to the various parameters
388 *
389 * @param string $customstr String containing the parameters
390 *
391 * @return Array of custom parameters
392 */
dbb0fec9 393function lti_split_custom_parameters($customstr) {
b9b2e7bb
CS
394 $textlib = textlib_get_instance();
395
396 $lines = preg_split("/[\n;]/", $customstr);
397 $retval = array();
398 foreach ($lines as $line) {
399 $pos = strpos($line, "=");
400 if ( $pos === false || $pos < 1 ) {
401 continue;
402 }
403 $key = trim($textlib->substr($line, 0, $pos));
404 $val = trim($textlib->substr($line, $pos+1));
dbb0fec9 405 $key = lti_map_keyname($key);
b9b2e7bb
CS
406 $retval['custom_'.$key] = $val;
407 }
408 return $retval;
409}
410
411/**
412 * Used for building the names of the different custom parameters
413 *
414 * @param string $key Parameter name
415 *
416 * @return string Processed name
417 */
dbb0fec9 418function lti_map_keyname($key) {
b9b2e7bb
CS
419 $textlib = textlib_get_instance();
420
421 $newkey = "";
422 $key = $textlib->strtolower(trim($key));
423 foreach (str_split($key) as $ch) {
424 if ( ($ch >= 'a' && $ch <= 'z') || ($ch >= '0' && $ch <= '9') ) {
425 $newkey .= $ch;
426 } else {
427 $newkey .= '_';
428 }
429 }
430 return $newkey;
431}
432
433/**
434 * Returns the IMS user role in a given context
435 *
436 * This function queries Moodle for an user role and
437 * returns the correspondant IMS role
438 *
439 * @param StdClass $user Moodle user instance
440 * @param StdClass $context Moodle context
441 *
442 * @return string IMS Role
443 *
444 */
445function lti_get_ims_role($user, $context) {
446
447 $roles = get_user_roles($context, $user->id);
448 $rolesname = array();
449 foreach ($roles as $role) {
450 $rolesname[] = $role->shortname;
451 }
452
453 if (in_array('admin', $rolesname) || in_array('coursecreator', $rolesname)) {
454 return get_string('imsroleadmin', 'lti');
455 }
456
457 if (in_array('editingteacher', $rolesname) || in_array('teacher', $rolesname)) {
458 return get_string('imsroleinstructor', 'lti');
459 }
460
461 return get_string('imsrolelearner', 'lti');
462}
463
464/**
465 * Returns configuration details for the tool
466 *
467 * @param int $typeid Basic LTI tool typeid
468 *
469 * @return array Tool Configuration
470 */
471function lti_get_type_config($typeid) {
472 global $DB;
473
f17f4959
CS
474 $query = <<<QUERY
475 SELECT name, value
476 FROM {lti_types_config}
477 WHERE typeid = :typeid1
478
479 UNION ALL
480
481 SELECT 'toolurl' AS name, baseurl AS value
482 FROM {lti_types}
483 WHERE id = :typeid2
484QUERY;
485
b9b2e7bb 486 $typeconfig = array();
f17f4959
CS
487 $configs = $DB->get_records_sql($query, array('typeid1' => $typeid, 'typeid2' => $typeid));
488
b9b2e7bb
CS
489 if (!empty($configs)) {
490 foreach ($configs as $config) {
491 $typeconfig[$config->name] = $config->value;
492 }
493 }
f17f4959 494
b9b2e7bb
CS
495 return $typeconfig;
496}
497
996b0fd9 498function lti_get_tools_by_url($url, $state, $courseid = null){
b9b2e7bb
CS
499 $domain = lti_get_domain_from_url($url);
500
996b0fd9 501 return lti_get_tools_by_domain($domain, $state, $courseid);
b9b2e7bb
CS
502}
503
504function lti_get_tools_by_domain($domain, $state = null, $courseid = null){
505 global $DB, $SITE;
506
507 $filters = array('tooldomain' => $domain);
508
509 $statefilter = '';
510 $coursefilter = '';
511
512 if($state){
513 $statefilter = 'AND state = :state';
514 }
515
516 if($courseid && $courseid != $SITE->id){
517 $coursefilter = 'OR course = :courseid';
518 }
519
520 $query = <<<QUERY
521 SELECT * FROM {lti_types}
522 WHERE
523 tooldomain = :tooldomain
524 AND (course = :siteid $coursefilter)
525 $statefilter
526QUERY;
527
528 return $DB->get_records_sql($query, array(
529 'courseid' => $courseid,
530 'siteid' => $SITE->id,
531 'tooldomain' => $domain,
532 'state' => $state
533 ));
534}
535
536/**
537 * Returns all basicLTI tools configured by the administrator
538 *
539 */
6831c7cd 540function lti_filter_get_types($course) {
b9b2e7bb
CS
541 global $DB;
542
6831c7cd
CS
543 if(!empty($course)){
544 $filter = array('course' => $course);
545 } else {
546 $filter = array();
547 }
548
549 return $DB->get_records('lti_types', $filter);
b9b2e7bb
CS
550}
551
552function lti_get_types_for_add_instance(){
996b0fd9
CS
553 global $DB, $SITE, $COURSE;
554
555 $query = <<<QUERY
556 SELECT *
557 FROM {lti_types}
558 WHERE
559 coursevisible = 1
560 AND (course = :siteid OR course = :courseid)
606ab1a1 561 AND state = :active
996b0fd9
CS
562QUERY;
563
606ab1a1 564 $admintypes = $DB->get_records_sql($query, array('siteid' => $SITE->id, 'courseid' => $COURSE->id, 'active' => LTI_TOOL_STATE_CONFIGURED));
b9b2e7bb
CS
565
566 $types = array();
996b0fd9 567 $types[0] = (object)array('name' => get_string('automatic', 'lti'), 'course' => $SITE->id);
b9b2e7bb
CS
568
569 foreach($admintypes as $type) {
16e8f130 570 $types[$type->id] = $type;
b9b2e7bb
CS
571 }
572
573 return $types;
574}
575
576function lti_get_domain_from_url($url){
577 $matches = array();
578
579 if(preg_match(LTI_URL_DOMAIN_REGEX, $url, $matches)){
580 return $matches[1];
581 }
582}
583
584function lti_get_tool_by_url_match($url, $courseid = null, $state = LTI_TOOL_STATE_CONFIGURED){
b69dc429 585 $possibletools = lti_get_tools_by_url($url, $state, $courseid);
b9b2e7bb 586
7023b65e 587 return lti_get_best_tool_by_url($url, $possibletools, $courseid);
b9b2e7bb
CS
588}
589
590function lti_get_url_thumbprint($url){
591 $urlparts = parse_url(strtolower($url));
592 if(!isset($urlparts['path'])){
593 $urlparts['path'] = '';
594 }
595
596 if(substr($urlparts['host'], 0, 3) === 'www'){
d66865d9 597 $urllparts['host'] = substr($urlparts['host'], 3);
b9b2e7bb
CS
598 }
599
600 return $urllower = $urlparts['host'] . '/' . $urlparts['path'];
601}
602
7023b65e 603function lti_get_best_tool_by_url($url, $tools, $courseid = null){
b9b2e7bb
CS
604 if(count($tools) === 0){
605 return null;
606 }
607
608 $urllower = lti_get_url_thumbprint($url);
609
610 foreach($tools as $tool){
611 $tool->_matchscore = 0;
612
613 $toolbaseurllower = lti_get_url_thumbprint($tool->baseurl);
614
615 if($urllower === $toolbaseurllower){
7023b65e 616 //100 points for exact thumbprint match
b9b2e7bb
CS
617 $tool->_matchscore += 100;
618 } else if(substr($urllower, 0, strlen($toolbaseurllower)) === $toolbaseurllower){
7023b65e 619 //50 points if tool thumbprint starts with the base URL thumbprint
b9b2e7bb
CS
620 $tool->_matchscore += 50;
621 }
7023b65e
CS
622
623 //Prefer course tools over site tools
624 if(!empty($courseid)){
625 //Minus 25 points for not matching the course id (global tools)
626 if($tool->course != $courseid){
627 $tool->_matchscore -= 10;
628 }
629 }
b9b2e7bb
CS
630 }
631
632 $bestmatch = array_reduce($tools, function($value, $tool){
633 if($tool->_matchscore > $value->_matchscore){
634 return $tool;
635 } else {
636 return $value;
637 }
638
639 }, (object)array('_matchscore' => -1));
640
641 //None of the tools are suitable for this URL
642 if($bestmatch->_matchscore <= 0){
643 return null;
644 }
645
646 return $bestmatch;
647}
648
020eea1b
CS
649function lti_get_shared_secrets_by_key($key){
650 global $DB;
651
652 //Look up the shared secret for the specified key in both the types_config table (for configured tools)
653 //And in the lti resource table for ad-hoc tools
654 $query = <<<QUERY
655 SELECT t2.value
656 FROM {lti_types_config} t1
657 INNER JOIN {lti_types_config} t2 ON t1.typeid = t2.typeid
658 WHERE
659 t1.name = 'resourcekey'
660 AND t1.value = :key1
661 AND t2.name = 'password'
662
663 UNION
664
3dd9ca24 665 SELECT password AS value
020eea1b
CS
666 FROM {lti}
667 WHERE resourcekey = :key2
668QUERY;
669
670 $sharedsecrets = $DB->get_records_sql($query, array('key1' => $key, 'key2' => $key));
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){
1105 $launchcontainer = $lti->launchcontainer == LTI_LAUNCH_CONTAINER_DEFAULT ?
1106 $toolconfig['launchcontainer'] :
1107 $lti->launchcontainer;
1108
1109 $devicetype = get_device_type();
1110
1111 //Scrolling within the object element doesn't work on iOS or Android
1112 //Opening the popup window also had some issues in testing
1113 //For mobile devices, always take up the entire screen to ensure the best experience
1114 if($devicetype === 'mobile' || $devicetype === 'tablet' ){
1115 $launchcontainer = LTI_LAUNCH_CONTAINER_REPLACE_MOODLE_WINDOW;
1116 }
1117
1118 return $launchcontainer;
996b0fd9 1119}