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