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