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