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