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