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