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