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