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