Improving the experience of instructor managed tool types
[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)){
606ab1a1 77 $tool = lti_get_tool_by_url_match($instance->toolurl, $instance->course);
b9b2e7bb
CS
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
b9b2e7bb
CS
181 $placementsecret = $instance->servicesalt;
182
183 if ( isset($placementsecret) ) {
996b0fd9 184 $sourcedid = json_encode(lti_build_sourcedid($instance->id, $USER->id, $placementsecret));
b9b2e7bb
CS
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) {
dbb0fec9 222 $custom = lti_split_custom_parameters($customstr);
b9b2e7bb
CS
223 }
224 if (!isset($typeconfig['allowinstructorcustom']) || $typeconfig['allowinstructorcustom'] == 0) {
225 $requestparams = array_merge($custom, $requestparams);
226 } else {
227 if ($instructorcustomstr) {
dbb0fec9 228 $instructorcustom = lti_split_custom_parameters($instructorcustomstr);
b9b2e7bb
CS
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 */
dbb0fec9 250function lti_split_custom_parameters($customstr) {
b9b2e7bb
CS
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));
dbb0fec9 262 $key = lti_map_keyname($key);
b9b2e7bb
CS
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 */
dbb0fec9 275function lti_map_keyname($key) {
b9b2e7bb
CS
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
996b0fd9 341function lti_get_tools_by_url($url, $state, $courseid = null){
b9b2e7bb
CS
342 $domain = lti_get_domain_from_url($url);
343
996b0fd9 344 return lti_get_tools_by_domain($domain, $state, $courseid);
b9b2e7bb
CS
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 */
6831c7cd 383function lti_filter_get_types($course) {
b9b2e7bb
CS
384 global $DB;
385
6831c7cd
CS
386 if(!empty($course)){
387 $filter = array('course' => $course);
388 } else {
389 $filter = array();
390 }
391
392 return $DB->get_records('lti_types', $filter);
b9b2e7bb
CS
393}
394
395function lti_get_types_for_add_instance(){
996b0fd9
CS
396 global $DB, $SITE, $COURSE;
397
398 $query = <<<QUERY
399 SELECT *
400 FROM {lti_types}
401 WHERE
402 coursevisible = 1
403 AND (course = :siteid OR course = :courseid)
606ab1a1 404 AND state = :active
996b0fd9
CS
405QUERY;
406
606ab1a1 407 $admintypes = $DB->get_records_sql($query, array('siteid' => $SITE->id, 'courseid' => $COURSE->id, 'active' => LTI_TOOL_STATE_CONFIGURED));
b9b2e7bb
CS
408
409 $types = array();
996b0fd9 410 $types[0] = (object)array('name' => get_string('automatic', 'lti'), 'course' => $SITE->id);
b9b2e7bb
CS
411
412 foreach($admintypes as $type) {
16e8f130 413 $types[$type->id] = $type;
b9b2e7bb
CS
414 }
415
416 return $types;
417}
418
419function lti_get_domain_from_url($url){
420 $matches = array();
421
422 if(preg_match(LTI_URL_DOMAIN_REGEX, $url, $matches)){
423 return $matches[1];
424 }
425}
426
427function lti_get_tool_by_url_match($url, $courseid = null, $state = LTI_TOOL_STATE_CONFIGURED){
b69dc429 428 $possibletools = lti_get_tools_by_url($url, $state, $courseid);
b9b2e7bb
CS
429
430 return lti_get_best_tool_by_url($url, $possibletools);
431}
432
433function lti_get_url_thumbprint($url){
434 $urlparts = parse_url(strtolower($url));
435 if(!isset($urlparts['path'])){
436 $urlparts['path'] = '';
437 }
438
439 if(substr($urlparts['host'], 0, 3) === 'www'){
440 $urllparts['host'] = substr(3);
441 }
442
443 return $urllower = $urlparts['host'] . '/' . $urlparts['path'];
444}
445
446function lti_get_best_tool_by_url($url, $tools){
447 if(count($tools) === 0){
448 return null;
449 }
450
451 $urllower = lti_get_url_thumbprint($url);
452
453 foreach($tools as $tool){
454 $tool->_matchscore = 0;
455
456 $toolbaseurllower = lti_get_url_thumbprint($tool->baseurl);
457
458 if($urllower === $toolbaseurllower){
459 //100 points for exact match
460 $tool->_matchscore += 100;
461 } else if(substr($urllower, 0, strlen($toolbaseurllower)) === $toolbaseurllower){
462 //50 points if it starts with the base URL
463 $tool->_matchscore += 50;
464 }
465 }
466
467 $bestmatch = array_reduce($tools, function($value, $tool){
468 if($tool->_matchscore > $value->_matchscore){
469 return $tool;
470 } else {
471 return $value;
472 }
473
474 }, (object)array('_matchscore' => -1));
475
476 //None of the tools are suitable for this URL
477 if($bestmatch->_matchscore <= 0){
478 return null;
479 }
480
481 return $bestmatch;
482}
483
484/**
485 * Prints the various configured tool types
486 *
487 */
488function lti_filter_print_types() {
489 global $CFG;
490
491 $types = lti_filter_get_types();
492 if (!empty($types)) {
493 echo '<ul>';
494 foreach ($types as $type) {
495 echo '<li>'.
496 $type->name.
497 '<span class="commands">'.
498 '<a class="editing_update" href="typessettings.php?action=update&amp;id='.$type->id.'&amp;sesskey='.sesskey().'" title="Update">'.
499 '<img class="iconsmall" alt="Update" src="'.$CFG->wwwroot.'/pix/t/edit.gif"/>'.
500 '</a>'.
501 '<a class="editing_delete" href="typessettings.php?action=delete&amp;id='.$type->id.'&amp;sesskey='.sesskey().'" title="Delete">'.
502 '<img class="iconsmall" alt="Delete" src="'.$CFG->wwwroot.'/pix/t/delete.gif"/>'.
503 '</a>'.
504 '</span>'.
505 '</li>';
506
507 }
508 echo '</ul>';
509 } else {
510 echo '<div class="message">';
511 echo get_string('notypes', 'lti');
512 echo '</div>';
513 }
514}
515
516/**
517 * Delete a Basic LTI configuration
518 *
519 * @param int $id Configuration id
520 */
521function lti_delete_type($id) {
522 global $DB;
523
524 //We should probably just copy the launch URL to the tool instances in this case... using a single query
525 /*
526 $instances = $DB->get_records('lti', array('typeid' => $id));
527 foreach ($instances as $instance) {
528 $instance->typeid = 0;
529 $DB->update_record('lti', $instance);
530 }*/
531
532 $DB->delete_records('lti_types', array('id' => $id));
533 $DB->delete_records('lti_types_config', array('typeid' => $id));
534}
535
536function lti_set_state_for_type($id, $state){
537 global $DB;
538
539 $DB->update_record('lti_types', array('id' => $id, 'state' => $state));
540}
541
542/**
543 * Transforms a basic LTI object to an array
544 *
545 * @param object $ltiobject Basic LTI object
546 *
547 * @return array Basic LTI configuration details
548 */
549function lti_get_config($ltiobject) {
550 $typeconfig = array();
551 $typeconfig = (array)$ltiobject;
552 $additionalconfig = lti_get_type_config($ltiobject->typeid);
553 $typeconfig = array_merge($typeconfig, $additionalconfig);
554 return $typeconfig;
555}
556
557/**
558 *
559 * Generates some of the tool configuration based on the instance details
560 *
561 * @param int $id
562 *
563 * @return Instance configuration
564 *
565 */
566function lti_get_type_config_from_instance($id) {
567 global $DB;
568
569 $instance = $DB->get_record('lti', array('id' => $id));
570 $config = lti_get_config($instance);
571
572 $type = new stdClass();
573 $type->lti_fix = $id;
574 if (isset($config['toolurl'])) {
575 $type->lti_toolurl = $config['toolurl'];
576 }
577 if (isset($config['instructorchoicesendname'])) {
578 $type->lti_sendname = $config['instructorchoicesendname'];
579 }
580 if (isset($config['instructorchoicesendemailaddr'])) {
581 $type->lti_sendemailaddr = $config['instructorchoicesendemailaddr'];
582 }
583 if (isset($config['instructorchoiceacceptgrades'])) {
584 $type->lti_acceptgrades = $config['instructorchoiceacceptgrades'];
585 }
586 if (isset($config['instructorchoiceallowroster'])) {
587 $type->lti_allowroster = $config['instructorchoiceallowroster'];
588 }
589
590 if (isset($config['instructorcustomparameters'])) {
591 $type->lti_allowsetting = $config['instructorcustomparameters'];
592 }
593 return $type;
594}
595
596/**
597 * Generates some of the tool configuration based on the admin configuration details
598 *
599 * @param int $id
600 *
601 * @return Configuration details
602 */
603function lti_get_type_type_config($id) {
604 global $DB;
605
606 $basicltitype = $DB->get_record('lti_types', array('id' => $id));
607 $config = lti_get_type_config($id);
608
609 $type->lti_typename = $basicltitype->name;
610
6831c7cd
CS
611 $type->typeid = $basicltitype->id;
612
b9b2e7bb
CS
613 $type->lti_toolurl = $basicltitype->baseurl;
614
615 if (isset($config['resourcekey'])) {
616 $type->lti_resourcekey = $config['resourcekey'];
617 }
618 if (isset($config['password'])) {
619 $type->lti_password = $config['password'];
620 }
621
622 if (isset($config['sendname'])) {
623 $type->lti_sendname = $config['sendname'];
624 }
625 if (isset($config['instructorchoicesendname'])){
626 $type->lti_instructorchoicesendname = $config['instructorchoicesendname'];
627 }
628 if (isset($config['sendemailaddr'])){
629 $type->lti_sendemailaddr = $config['sendemailaddr'];
630 }
631 if (isset($config['instructorchoicesendemailaddr'])){
632 $type->lti_instructorchoicesendemailaddr = $config['instructorchoicesendemailaddr'];
633 }
634 if (isset($config['acceptgrades'])){
635 $type->lti_acceptgrades = $config['acceptgrades'];
636 }
637 if (isset($config['instructorchoiceacceptgrades'])){
638 $type->lti_instructorchoiceacceptgrades = $config['instructorchoiceacceptgrades'];
639 }
640 if (isset($config['allowroster'])){
641 $type->lti_allowroster = $config['allowroster'];
642 }
643 if (isset($config['instructorchoiceallowroster'])){
644 $type->lti_instructorchoiceallowroster = $config['instructorchoiceallowroster'];
645 }
646
647 if (isset($config['customparameters'])) {
648 $type->lti_customparameters = $config['customparameters'];
649 }
650
651 if (isset($config['organizationid'])) {
652 $type->lti_organizationid = $config['organizationid'];
653 }
654 if (isset($config['organizationurl'])) {
655 $type->lti_organizationurl = $config['organizationurl'];
656 }
657 if (isset($config['organizationdescr'])) {
658 $type->lti_organizationdescr = $config['organizationdescr'];
659 }
660 if (isset($config['launchcontainer'])) {
661 $type->lti_launchcontainer = $config['launchcontainer'];
662 }
663
664 if (isset($config['coursevisible'])) {
665 $type->lti_coursevisible = $config['coursevisible'];
666 }
667
668 if (isset($config['debuglaunch'])) {
669 $type->lti_debuglaunch = $config['debuglaunch'];
670 }
671
672 if (isset($config['module_class_type'])) {
673 $type->lti_module_class_type = $config['module_class_type'];
674 }
675
676 return $type;
677}
678
679function lti_prepare_type_for_save($type, $config){
680 $type->baseurl = $config->lti_toolurl;
681 $type->tooldomain = lti_get_domain_from_url($config->lti_toolurl);
682 $type->name = $config->lti_typename;
683
684 $type->coursevisible = !empty($config->lti_coursevisible) ? $config->lti_coursevisible : 0;
685 $config->lti_coursevisible = $type->coursevisible;
686
687 $type->timemodified = time();
688
689 unset ($config->lti_typename);
690 unset ($config->lti_toolurl);
691}
692
693function lti_update_type($type, $config){
694 global $DB;
695
696 lti_prepare_type_for_save($type, $config);
697
698 if ($DB->update_record('lti_types', $type)) {
699 foreach ($config as $key => $value) {
700 if (substr($key, 0, 4)=='lti_' && !is_null($value)) {
701 $record = new StdClass();
702 $record->typeid = $type->id;
703 $record->name = substr($key, 4);
704 $record->value = $value;
705
706 lti_update_config($record);
707 }
708 }
709 }
710}
711
712function lti_add_type($type, $config){
713 global $USER, $SITE, $DB;
714
715 lti_prepare_type_for_save($type, $config);
716
717 if(!isset($type->state)){
718 $type->state = LTI_TOOL_STATE_PENDING;
719 }
720
721 if(!isset($type->timecreated)){
722 $type->timecreated = time();
723 }
724
725 if(!isset($type->createdby)){
726 $type->createdby = $USER->id;
727 }
728
729 if(!isset($type->course)){
730 $type->course = $SITE->id;
731 }
732
733 //Create a salt value to be used for signing passed data to extension services
6831c7cd
CS
734 //The outcome service uses the service salt on the instance. This can be used
735 //for communication with services not related to a specific LTI instance.
b9b2e7bb
CS
736 $config->lti_servicesalt = uniqid('', true);
737
738 $id = $DB->insert_record('lti_types', $type);
739
740 if ($id) {
741 foreach ($config as $key => $value) {
742 if (substr($key, 0, 4)=='lti_' && !is_null($value)) {
743 $record = new StdClass();
744 $record->typeid = $id;
745 $record->name = substr($key, 4);
746 $record->value = $value;
747
748 lti_add_config($record);
749 }
750 }
751 }
996b0fd9
CS
752
753 return $id;
b9b2e7bb
CS
754}
755
756/**
757 * Add a tool configuration in the database
758 *
759 * @param $config Tool configuration
760 *
761 * @return int Record id number
762 */
763function lti_add_config($config) {
764 global $DB;
765
766 return $DB->insert_record('lti_types_config', $config);
767}
768
769/**
770 * Updates a tool configuration in the database
771 *
772 * @param $config Tool configuration
773 *
774 * @return Record id number
775 */
776function lti_update_config($config) {
777 global $DB;
778
779 $return = true;
780 $old = $DB->get_record('lti_types_config', array('typeid' => $config->typeid, 'name' => $config->name));
781
782 if ($old) {
783 $config->id = $old->id;
784 $return = $DB->update_record('lti_types_config', $config);
785 } else {
786 $return = $DB->insert_record('lti_types_config', $config);
787 }
788 return $return;
789}
790
791/**
792 * Signs the petition to launch the external tool using OAuth
793 *
794 * @param $oldparms Parameters to be passed for signing
795 * @param $endpoint url of the external tool
796 * @param $method Method for sending the parameters (e.g. POST)
797 * @param $oauth_consumoer_key Key
798 * @param $oauth_consumoer_secret Secret
799 * @param $submittext The text for the submit button
800 * @param $orgid LMS name
801 * @param $orgdesc LMS key
802 */
dbb0fec9 803function lti_sign_parameters($oldparms, $endpoint, $method, $oauthconsumerkey, $oauthconsumersecret, $submittext, $orgid /*, $orgdesc*/) {
b9b2e7bb
CS
804 global $lastbasestring;
805 $parms = $oldparms;
806 $parms["lti_version"] = "LTI-1p0";
807 $parms["lti_message_type"] = "basic-lti-launch-request";
808 if ( $orgid ) {
809 $parms["tool_consumer_instance_guid"] = $orgid;
810 }
811 /* Suppress this for now - Chuck
812 if ( $orgdesc ) $parms["tool_consumer_instance_description"] = $orgdesc;
813 */
814 $parms["ext_submit"] = $submittext;
815
816 $testtoken = '';
817
818 $hmacmethod = new OAuthSignatureMethod_HMAC_SHA1();
819 $testconsumer = new OAuthConsumer($oauthconsumerkey, $oauthconsumersecret, null);
820
821 $accreq = OAuthRequest::from_consumer_and_token($testconsumer, $testtoken, $method, $endpoint, $parms);
822 $accreq->sign_request($hmacmethod, $testconsumer, $testtoken);
823
824 // Pass this back up "out of band" for debugging
825 $lastbasestring = $accreq->get_signature_base_string();
826
827 $newparms = $accreq->get_parameters();
828
829 return $newparms;
830}
831
832/**
833 * Posts the launch petition HTML
834 *
835 * @param $newparms Signed parameters
836 * @param $endpoint URL of the external tool
837 * @param $debug Debug (true/false)
838 */
dbb0fec9 839function lti_post_launch_html($newparms, $endpoint, $debug=false) {
b9b2e7bb
CS
840 global $lastbasestring;
841
842 $r = "<form action=\"".$endpoint."\" name=\"ltiLaunchForm\" id=\"ltiLaunchForm\" method=\"post\" encType=\"application/x-www-form-urlencoded\">\n";
843
844 $submittext = $newparms['ext_submit'];
845
846 // Contruct html for the launch parameters
847 foreach ($newparms as $key => $value) {
848 $key = htmlspecialchars($key);
849 $value = htmlspecialchars($value);
850 if ( $key == "ext_submit" ) {
851 $r .= "<input type=\"submit\" name=\"";
852 } else {
853 $r .= "<input type=\"hidden\" name=\"";
854 }
855 $r .= $key;
856 $r .= "\" value=\"";
857 $r .= $value;
858 $r .= "\"/>\n";
859 }
860
861 if ( $debug ) {
862 $r .= "<script language=\"javascript\"> \n";
863 $r .= " //<![CDATA[ \n";
864 $r .= "function basicltiDebugToggle() {\n";
865 $r .= " var ele = document.getElementById(\"basicltiDebug\");\n";
866 $r .= " if(ele.style.display == \"block\") {\n";
867 $r .= " ele.style.display = \"none\";\n";
868 $r .= " }\n";
869 $r .= " else {\n";
870 $r .= " ele.style.display = \"block\";\n";
871 $r .= " }\n";
872 $r .= "} \n";
873 $r .= " //]]> \n";
874 $r .= "</script>\n";
875 $r .= "<a id=\"displayText\" href=\"javascript:basicltiDebugToggle();\">";
876 $r .= get_string("toggle_debug_data", "lti")."</a>\n";
877 $r .= "<div id=\"basicltiDebug\" style=\"display:none\">\n";
878 $r .= "<b>".get_string("basiclti_endpoint", "lti")."</b><br/>\n";
879 $r .= $endpoint . "<br/>\n&nbsp;<br/>\n";
880 $r .= "<b>".get_string("basiclti_parameters", "lti")."</b><br/>\n";
881 foreach ($newparms as $key => $value) {
882 $key = htmlspecialchars($key);
883 $value = htmlspecialchars($value);
884 $r .= "$key = $value<br/>\n";
885 }
886 $r .= "&nbsp;<br/>\n";
887 $r .= "<p><b>".get_string("basiclti_base_string", "lti")."</b><br/>\n".$lastbasestring."</p>\n";
888 $r .= "</div>\n";
889 }
890 $r .= "</form>\n";
891
892 if ( ! $debug ) {
893 $ext_submit = "ext_submit";
894 $ext_submit_text = $submittext;
895 $r .= " <script type=\"text/javascript\"> \n" .
896 " //<![CDATA[ \n" .
897 " document.getElementById(\"ltiLaunchForm\").style.display = \"none\";\n" .
898 " nei = document.createElement('input');\n" .
899 " nei.setAttribute('type', 'hidden');\n" .
900 " nei.setAttribute('name', '".$ext_submit."');\n" .
901 " nei.setAttribute('value', '".$ext_submit_text."');\n" .
902 " document.getElementById(\"ltiLaunchForm\").appendChild(nei);\n" .
903 " document.ltiLaunchForm.submit(); \n" .
904 " //]]> \n" .
905 " </script> \n";
906 }
907 return $r;
908}
909
910/**
911 * Returns a link with info about the state of the basiclti submissions
912 *
913 * This is used by view_header to put this link at the top right of the page.
914 * For teachers it gives the number of submitted assignments with a link
915 * For students it gives the time of their submission.
916 * This will be suitable for most assignment types.
917 *
918 * @global object
919 * @global object
920 * @param bool $allgroup print all groups info if user can access all groups, suitable for index.php
921 * @return string
922 */
dbb0fec9 923function lti_submittedlink($cm, $allgroups=false) {
b9b2e7bb
CS
924 global $CFG;
925
926 $submitted = '';
927 $urlbase = "{$CFG->wwwroot}/mod/lti/";
928
929 $context = get_context_instance(CONTEXT_MODULE, $cm->id);
930 if (has_capability('mod/lti:grade', $context)) {
931 if ($allgroups and has_capability('moodle/site:accessallgroups', $context)) {
932 $group = 0;
933 } else {
934 $group = groups_get_activity_group($cm);
935 }
936
937 $submitted = '<a href="'.$urlbase.'submissions.php?id='.$cm->id.'">'.
938 get_string('viewsubmissions', 'lti').'</a>';
939 } else {
940 if (isloggedin()) {
941 // TODO Insert code for students if needed
942 }
943 }
944
945 return $submitted;
946}
947
996b0fd9
CS
948function lti_get_type($typeid){
949 global $DB;
950
951 return $DB->get_record('lti_types', array('id' => $typeid));
952}