-
Notifications
You must be signed in to change notification settings - Fork 1
/
locallib.php
executable file
·3324 lines (2916 loc) · 117 KB
/
locallib.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* This file contains the library of functions and constants for the lti module
*
* @package qtype_lti
* @copyright 2019 ETH Zurich
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
defined('MOODLE_INTERNAL') || die();
require_once($CFG->dirroot . '/question/type/lti/OAuth.php');
// TODO: Switch to core oauthlib once implemented - MDL-30149.
use moodle\qtype\lti as lti;
require_once($CFG->libdir . '/weblib.php');
require_once($CFG->dirroot . '/course/modlib.php');
require_once($CFG->dirroot . '/question/type/lti/TrivialStore.php');
define('QTYPE_LTI_URL_DOMAIN_REGEX', '/(?:https?:\/\/)?(?:www\.)?([^\/]+)(?:\/|$)/i');
define('QTYPE_LTI_LAUNCH_CONTAINER_DEFAULT', 1);
define('QTYPE_LTI_LAUNCH_CONTAINER_EMBED', 2);
define('QTYPE_LTI_LAUNCH_CONTAINER_EMBED_NO_BLOCKS', 3);
define('QTYPE_LTI_LAUNCH_CONTAINER_WINDOW', 4);
define('QTYPE_LTI_LAUNCH_CONTAINER_REPLACE_MOODLE_WINDOW', 5);
define('QTYPE_LTI_TOOL_STATE_ANY', 0);
define('QTYPE_LTI_TOOL_STATE_CONFIGURED', 1);
define('QTYPE_LTI_TOOL_STATE_PENDING', 2);
define('QTYPE_LTI_TOOL_STATE_REJECTED', 3);
define('QTYPE_LTI_TOOL_PROXY_TAB', 4);
define('QTYPE_LTI_TOOL_PROXY_STATE_CONFIGURED', 1);
define('QTYPE_LTI_TOOL_PROXY_STATE_PENDING', 2);
define('QTYPE_LTI_TOOL_PROXY_STATE_ACCEPTED', 3);
define('QTYPE_LTI_TOOL_PROXY_STATE_REJECTED', 4);
define('QTYPE_LTI_SETTING_NEVER', 0);
define('QTYPE_LTI_SETTING_ALWAYS', 1);
define('QTYPE_LTI_SETTING_DELEGATE', 2);
define('QTYPE_LTI_COURSEVISIBLE_NO', 0);
define('QTYPE_LTI_COURSEVISIBLE_PRECONFIGURED', 1);
define('QTYPE_LTI_COURSEVISIBLE_ACTIVITYCHOOSER', 2);
define('QTYPE_LTI_VERSION_1', 'LTI-1p0');
define('QTYPE_LTI_VERSION_2', 'LTI-2p0');
/**
* Return the launch data required for opening the external tool.
*
* @param stdClass $instance
* the external tool activity settings
* @return array the endpoint URL and parameters (including the signature)
* @since Moodle 3.0
*/
function qtype_lti_get_launch_data($instance, $userid = null, $readonly = null,
$questionmode = 'create', $manuallygradedinmoodle = 0,
$extracodeexpertparams = array()) {
global $PAGE, $CFG, $DB;
if (empty($instance->typeid)) {
$tool = qtype_lti_get_tool_by_url_match($instance->toolurl, $instance->course);
if ($tool) {
$typeid = $tool->id;
} else {
$typeid = null;
}
} else {
$typeid = $instance->typeid;
$tool = qtype_lti_get_type($typeid);
}
if ($typeid) {
$typeconfig = qtype_lti_get_type_config($typeid);
$noadminconfigfound = 0;
} else {
// There is no admin configuration for this tool. Use configuration in the lti instance record plus some defaults.
$typeconfig = (array)$instance;
$typeconfig['sendname'] = $instance->instructorchoicesendname;
$typeconfig['sendemailaddr'] = $instance->instructorchoicesendemailaddr;
$typeconfig['customparameters'] = $instance->instructorcustomparameters;
$typeconfig['acceptgrades'] = $instance->instructorchoiceacceptgrades;
$typeconfig['allowroster'] = $instance->instructorchoiceallowroster;
$typeconfig['forcessl'] = '0';
$noadminconfigfound = 1;
}
// Default the organizationid if not specified.
if (empty($typeconfig['organizationid'])) {
$urlparts = parse_url($CFG->wwwroot);
$typeconfig['organizationid'] = $urlparts['host'];
}
if (isset($tool->toolproxyid)) {
$toolproxy = qtype_lti_get_tool_proxy($tool->toolproxyid);
$key = $toolproxy->guid;
$secret = $toolproxy->secret;
} else {
$toolproxy = null;
if (!empty($instance->resourcekey)) {
$key = $instance->resourcekey;
} else if (!empty($typeconfig['resourcekey'])) {
$key = $typeconfig['resourcekey'];
} else {
$key = '';
}
if (!empty($instance->password)) {
$secret = $instance->password;
} else if (!empty($typeconfig['password'])) {
$secret = $typeconfig['password'];
} else {
$secret = '';
}
}
$endpoint = !empty($instance->toolurl) ? $instance->toolurl : $typeconfig['toolurl'];
$endpoint = trim($endpoint);
// If the current request is using SSL and a secure tool URL is specified, use it.
if (qtype_lti_request_is_using_ssl() && !empty($instance->securetoolurl)) {
$endpoint = trim($instance->securetoolurl);
}
// If SSL is forced, use the secure tool url if specified. Otherwise, make sure https is on the normal launch URL.
if (isset($typeconfig['forcessl']) && ($typeconfig['forcessl'] == '1')) {
if (!empty($instance->securetoolurl)) {
$endpoint = trim($instance->securetoolurl);
}
$endpoint = qtype_lti_ensure_url_is_https($endpoint);
} else {
if (!strstr($endpoint, '://')) {
$endpoint = 'http://' . $endpoint;
}
}
$orgid = $typeconfig['organizationid'];
$course = $DB->get_record('course', array('id' => $instance->course));
$islti2 = isset($tool->toolproxyid);
$allparams = qtype_lti_build_request($instance, $typeconfig, $course, $userid, $readonly, $questionmode,
$manuallygradedinmoodle, $extracodeexpertparams, $typeid, $islti2);
if ($islti2) {
$requestparams = qtype_lti_build_request_lti2($tool, $allparams, $userid, $readonly, $questionmode,
$manuallygradedinmoodle, $extracodeexpertparams);
} else {
$requestparams = $allparams;
}
$requestparams = array_merge($requestparams,
qtype_lti_build_standard_request($instance, $orgid, $islti2,
$extracodeexpertparams, 'basic-lti-launch-request'));
$customstr = '';
if (isset($typeconfig['customparameters'])) {
$customstr = $typeconfig['customparameters'];
}
$requestparams = array_merge($requestparams,
qtype_lti_build_custom_parameters($toolproxy, $tool, $instance, $allparams, $customstr,
$instance->instructorcustomparameters, $islti2, $userid));
$launchcontainer = qtype_lti_get_launch_container($instance, $typeconfig);
$returnurlparams = array('course' => $course->id, 'launch_container' => $launchcontainer, 'instanceid' => $instance->id,
'sesskey' => sesskey());
// Add the return URL. We send the launch container along to help us avoid frames-within-frames when the user returns.
$url = new \moodle_url('/question/type/lti/return.php', $returnurlparams);
$returnurl = $url->out(false);
if (isset($typeconfig['forcessl']) && ($typeconfig['forcessl'] == '1')) {
$returnurl = qtype_lti_ensure_url_is_https($returnurl);
}
$target = '';
switch ($launchcontainer) {
case QTYPE_LTI_LAUNCH_CONTAINER_EMBED:
case QTYPE_LTI_LAUNCH_CONTAINER_EMBED_NO_BLOCKS:
$target = 'iframe';
break;
case QTYPE_LTI_LAUNCH_CONTAINER_REPLACE_MOODLE_WINDOW:
$target = 'frame';
break;
case QTYPE_LTI_LAUNCH_CONTAINER_WINDOW:
$target = 'window';
break;
}
if (!empty($target)) {
$requestparams['launch_presentation_document_target'] = $target;
}
$requestparams['launch_presentation_return_url'] = $returnurl;
// Allow request params to be updated by sub-plugins.
$plugins = core_component::get_plugin_list('ltisource');
foreach (array_keys($plugins) as $plugin) {
$pluginparams = component_callback('ltisource_' . $plugin, 'before_launch', array($instance, $endpoint, $requestparams),
array());
if (!empty($pluginparams) && is_array($pluginparams)) {
$requestparams = array_merge($requestparams, $pluginparams);
}
}
if (!empty($key) && !empty($secret)) {
$parms = qtype_lti_sign_parameters($requestparams, $endpoint, "POST", $key, $secret);
$endpointurl = new \moodle_url($endpoint);
$endpointparams = $endpointurl->params();
// Strip querystring params in endpoint url from $parms to avoid duplication.
if (!empty($endpointparams) && !empty($parms)) {
foreach (array_keys($endpointparams) as $paramname) {
if (isset($parms[$paramname])) {
unset($parms[$paramname]);
}
}
}
} else {
// If no key and secret, do the launch unsigned.
$returnurlparams['unsigned'] = '1';
$parms = $requestparams;
}
return array($endpoint, $parms);
}
/**
* Launch an external tool activity.
*
* @param stdClass $instance
* the external tool activity settings
* @return string The HTML code containing the javascript code for the launch
*/
function qtype_lti_launch_tool($instance, $userid = null, $readonly = null, $questionmode = 'create', $manuallygradedinmoodle = 0,
$extracodeexpertparams = array()) {
list($endpoint, $parms) = qtype_lti_get_launch_data($instance, $userid, $readonly, $questionmode, $manuallygradedinmoodle,
$extracodeexpertparams);
$debuglaunch = ($instance->debuglaunch == 1);
$content = qtype_lti_post_launch_html($parms, $endpoint, $debuglaunch);
echo $content;
}
/**
* Prepares an LTI registration request message
* $param object $instance Tool Proxy instance object
*/
function qtype_lti_register($toolproxy) {
$endpoint = $toolproxy->regurl;
// Change the status to pending.
$toolproxy->state = QTYPE_LTI_TOOL_PROXY_STATE_PENDING;
qtype_lti_update_tool_proxy($toolproxy);
$requestparams = qtype_lti_build_registration_request($toolproxy);
$content = qtype_lti_post_launch_html($requestparams, $endpoint, false);
echo $content;
}
/**
* Gets the parameters for the regirstration request
*
* @param object $toolproxy
* Tool Proxy instance object
* @return array Registration request parameters
*/
function qtype_lti_build_registration_request($toolproxy) {
$key = $toolproxy->guid;
$secret = $toolproxy->secret;
$requestparams = array();
$requestparams['lti_message_type'] = 'ToolProxyRegistrationRequest';
$requestparams['lti_version'] = 'LTI-2p0';
$requestparams['reg_key'] = $key;
$requestparams['reg_password'] = $secret;
$requestparams['reg_url'] = $toolproxy->regurl;
// Add the profile URL.
$profileservice = qtype_lti_get_service_by_name('profile');
$profileservice->set_tool_proxy($toolproxy);
$requestparams['tc_profile_url'] = $profileservice->parse_value('$ToolConsumerProfile.url');
// Add the return URL.
$returnurlparams = array('id' => $toolproxy->id, 'sesskey' => sesskey());
$url = new \moodle_url('/question/type/lti/externalregistrationreturn.php', $returnurlparams);
$returnurl = $url->out(false);
$requestparams['launch_presentation_return_url'] = $returnurl;
return $requestparams;
}
/**
* Build source ID
*
* @param int $instanceid
* @param int $userid
* @param string $servicesalt
* @param null|int $typeid
* @param null|int $launchid
* @return stdClass
*/
function qtype_lti_build_sourcedid($instanceid, $mattempt, $userid, $servicesalt, $typeid = null, $attemptid = null, $ltiid = null) {
$data = new \stdClass();
$data->instance = $instanceid;
$data->username = $userid;
if (!empty($attemptid)) {
$data->attemptid = $attemptid;
} else {
$data->attemptid = uniqid();
}
$data->ltiid = $ltiid;
$data->mattempt = $mattempt;
$json = json_encode($data);
$hash = hash('sha256', $json . $servicesalt, false);
$container = new \stdClass();
$container->data = $data;
$container->hash = $hash;
return $container;
}
/**
* This function builds the request that must be sent to the tool producer
*
* @param object $instance
* Basic LTI instance object
* @param array $typeconfig
* Basic LTI tool configuration
* @param object $course
* Course object
* @param int|null $typeid
* Basic LTI tool ID
* @param boolean $islti2
* True if an LTI 2 tool is being launched
* @return array Request details
*/
function qtype_lti_build_request($instance, $typeconfig, $course,
$userid, $readonly, $questionmode,
$manuallygradedinmoodle, $extracodeexpertparams,
$typeid = null, $islti2 = false) {
global $USER, $CFG, $DB;
if (empty($instance->cmid)) {
$instance->cmid = 0;
}
$originaluser = $USER;
$role = qtype_lti_get_ims_role($originaluser, $instance->cmid, $instance->course, $islti2);
$requestparams = array('user_id' => $originaluser->id, 'lis_person_sourcedid' => $originaluser->idnumber, 'roles' => $role,
'context_id' => $course->id, 'context_label' => trim(html_to_text($course->shortname, 0)),
'context_title' => trim(html_to_text($course->fullname, 0)));
if ($readonly) {
$requestparams['ext_question_readonly_mode'] = 1;
}
if (!empty($instance->name)) {
$requestparams['resource_link_title'] = trim(html_to_text($instance->name, 0));
}
if (!empty($instance->cmid)) {
$intro = format_module_intro('qtype_lti', $instance, $instance->cmid);
$intro = trim(html_to_text($intro, 0, false));
// This may look weird, but this is required for new lines
// so we generate the same OAuth signature as the tool provider.
$intro = str_replace("\n", "\r\n", $intro);
$requestparams['resource_link_description'] = $intro;
}
if (!empty($instance->id)) {
$requestparams['resource_link_id'] = $instance->instancecode;
}
if (!empty($instance->resource_link_id)) {
$requestparams['resource_link_id'] = $instance->instancecode;
}
$requestparams['resource_link_id'] = $extracodeexpertparams['resourcelinkid'];
if ($course->format == 'site') {
$requestparams['context_type'] = 'Group';
} else {
$requestparams['context_type'] = 'CourseSection';
if (!$course->idnumber || empty($course->idnumber)) {
$course->idnumber = $course->shortname;
}
$requestparams['lis_course_section_sourcedid'] = $course->idnumber;
}
if (!empty($instance->id) && !empty($instance->servicesalt) &&
($islti2 || $typeconfig['acceptgrades'] == QTYPE_LTI_SETTING_ALWAYS ||
($typeconfig['acceptgrades'] == QTYPE_LTI_SETTING_DELEGATE &&
$instance->instructorchoiceacceptgrades == QTYPE_LTI_SETTING_ALWAYS))) {
$placementsecret = $instance->servicesalt;
/*
$sourcedid = json_encode(
qtype_lti_build_sourcedid($extracodeexpertparams['resultid'], $originaluser->username,
$placementsecret, $typeid, $extracodeexpertparams['attemptid'],
$instance->id, $extracodeexpertparams['mattempt']));
*/
$sourcedid = json_encode(
qtype_lti_build_sourcedid($extracodeexpertparams['resultid'], $extracodeexpertparams['mattempt'],
$userid,
$placementsecret, $typeid,
$extracodeexpertparams['attemptid'],
$instance->id
));
$requestparams['lis_result_sourcedid'] = $sourcedid;
// Add outcome service URL.
$serviceurl = new \moodle_url('/question/type/lti/service.php');
$serviceurl = $serviceurl->out();
$forcessl = false;
if (!empty($CFG->qtype_lti_forcessl)) {
$forcessl = true;
}
if ((isset($typeconfig['forcessl']) && ($typeconfig['forcessl'] == '1')) or $forcessl) {
$serviceurl = qtype_lti_ensure_url_is_https($serviceurl);
}
$requestparams['lis_outcome_service_url'] = $serviceurl;
}
$requestparams['lis_person_name_given'] = $originaluser->firstname;
$requestparams['lis_person_name_family'] = $originaluser->lastname;
$requestparams['lis_person_name_full'] = $originaluser->firstname . ' ' . $originaluser->lastname;
$requestparams['ext_user_username'] = $originaluser->username;
// In case the teacher wants to see the users submission in review mode.
$requestparams['ext_student_username'] = $userid;
$requestparams['ext_moodleattemptid'] = $extracodeexpertparams['mattempt'];
/*
* The workflow used for the launch.
* The 4 following workflows based on the processes described in Spezifikation Code Expert in Moodle are supported:
* "create" Create & Edit Mode describes the process of a Lecturer creating or modifying a Code Expert question in Moodle.
* "solve" Solve Task Mode stands for the the student solving a Moodle exam containing Code Expert questions.
* The "student" may also be a lecturer impersonating a student to verify his own exam.
* "correction" Correction Mode is used by an assistant or a lecturer while correcting an solved exam by one or multiple
* students.
* "review" for Reviewing the answer (after submission and usually attached to readonly mode).
*/
// Due to inability to control the launch url in question edit mode, questionmodede is defaulted to 1.
// Transform it to 'create' shall it be 1.
if (!$questionmode || $questionmode == '1') {
$questionmode = 'create';
}
$requestparams['ext_workflow_mode'] = $questionmode;
$requestparams['ext_manually_graded'] = $manuallygradedinmoodle;
$requestparams['ext_attempt_id'] = $extracodeexpertparams['attemptid'];
$requestparams['ext_attempt_state'] = $extracodeexpertparams['attemptstate'];
$requestparams['ext_attempt_onlast'] = $extracodeexpertparams['attemptonlast'];
$requestparams['ext_quiz_id'] = $extracodeexpertparams['quizid'];
$requestparams['ext_quiz_title'] = trim(html_to_text($extracodeexpertparams['quiztitle'], 0));
$requestparams['ext_question_id'] = $extracodeexpertparams['questionid'];
$requestparams['ext_lti_id'] = $extracodeexpertparams['ltiid'];
$requestparams['ext_instancecode'] = $extracodeexpertparams['instancecode'];
$requestparams['ext_course_id'] = $extracodeexpertparams['courseid'];
$requestparams['ext_unique_connection'] = $extracodeexpertparams['resultid'];
$requestparams["ext_student_matriculationnumber"] = '';
if (isset($typeconfig['whichadditionalfield'])) {
// Case 1: Get optional userfield
if ($typeconfig['whichadditionalfield'] == 'optional') {
if (isset($typeconfig['userfield_optional'])) {
$param = clean_param($typeconfig['userfield_optional'], PARAM_ALPHAEXT);
if (!empty($param) && !in_array($param, ['password'])) {
$dbman = $DB->get_manager();
$table = new xmldb_table('user');
$field = new xmldb_field($param);
if ($dbman->field_exists($table, $field)) {
if ($result = $DB->get_record_select('user', "username = :username", ['username' => $userid], $param)) {
if (!empty($result->{$param})) {
$requestparams["ext_student_matriculationnumber"] = $result->{$param};
}
}
}
}
}
// Case 2: Or get other userfield
} else if ($typeconfig['whichadditionalfield'] == 'other') {
if (isset($typeconfig['userfield_other'])) {
$param = clean_param($typeconfig['userfield_other'], PARAM_INT);
if (!empty($param)) {
$sql = "SELECT uda.data
FROM {user_info_data} uda
JOIN {user} u ON u.id = uda.userid
WHERE u.username = :username AND uda.fieldid = :fieldid";
if ($result = $DB->get_record_sql($sql, ['username' => $userid, 'fieldid' => $param], $param)) {
if (!empty($result->data)) {
$requestparams["ext_student_matriculationnumber"] = $result->data;
}
}
}
}
}
}
if ($islti2 || $typeconfig['sendemailaddr'] == QTYPE_LTI_SETTING_ALWAYS || ($typeconfig['sendemailaddr'] ==
QTYPE_LTI_SETTING_DELEGATE && isset($instance->instructorchoicesendemailaddr) &&
$instance->instructorchoicesendemailaddr == QTYPE_LTI_SETTING_ALWAYS)) {
$requestparams['lis_person_contact_email_primary'] = $originaluser->email;
}
return $requestparams;
}
/**
* This function builds the request that must be sent to an LTI 2 tool provider
*
* @param object $tool
* Basic LTI tool object
* @param array $params
* Custom launch parameters
* @return array Request details
*/
function qtype_lti_build_request_lti2($tool, $params, $userid, $readonly, $questionmode, $manuallygradedinmoodle,
$extracodeexpertparams) {
$requestparams = array();
$capabilities = qtype_lti_get_capabilities();
$enabledcapabilities = explode("\n", $tool->enabledcapability);
foreach ($enabledcapabilities as $capability) {
if (array_key_exists($capability, $capabilities)) {
$val = $capabilities[$capability];
if ($val && (substr($val, 0, 1) != '$')) {
if (isset($params[$val])) {
$requestparams[$capabilities[$capability]] = $params[$capabilities[$capability]];
}
}
}
}
return $requestparams;
}
/**
* This function builds the standard parameters for an LTI 1 or 2 request that must be sent to the tool producer
*
* @param stdClass $instance
* Basic LTI instance object
* @param string $orgid
* Organisation ID
* @param boolean $islti2
* True if an LTI 2 tool is being launched
* @param string $messagetype
* The request message type. Defaults to basic-lti-launch-request if empty.
* @return array Request details
*/
function qtype_lti_build_standard_request($instance, $orgid, $islti2,
$extracodeexpertparams, $messagetype = 'basic-lti-launch-request') {
global $CFG;
$requestparams = array();
if ($instance) {
global $DB;
$requestparams['resource_link_id'] = $extracodeexpertparams['resourcelinkid'];
if (property_exists($instance, 'resource_link_id') and !empty($instance->resource_link_id)) {
$requestparams['resource_link_id'] = $extracodeexpertparams['resourcelinkid'];
}
}
$requestparams['launch_presentation_locale'] = current_language();
// Make sure we let the tool know what LMS they are being called from.
$requestparams['ext_lms'] = 'moodle-2';
$requestparams['tool_consumer_info_product_family_code'] = 'moodle';
$requestparams['tool_consumer_info_version'] = strval($CFG->version);
// Add oauth_callback to be compliant with the 1.0A spec.
$requestparams['oauth_callback'] = 'about:blank';
if (!$islti2) {
$requestparams['lti_version'] = 'LTI-1p0';
} else {
$requestparams['lti_version'] = 'LTI-2p0';
}
$requestparams['lti_message_type'] = $messagetype;
if ($orgid) {
$requestparams["tool_consumer_instance_guid"] = $orgid;
}
if (!empty($CFG->qtype_lti_institution_name)) {
$requestparams['tool_consumer_instance_name'] = trim(html_to_text($CFG->qtype_lti_institution_name, 0));
} else {
$requestparams['tool_consumer_instance_name'] = get_site()->shortname;
}
$requestparams['tool_consumer_instance_description'] = trim(html_to_text(get_site()->fullname, 0));
return $requestparams;
}
/**
* This function builds the custom parameters
*
* @param object $toolproxy
* Tool proxy instance object
* @param object $tool
* Tool instance object
* @param object $instance
* Tool placement instance object
* @param array $params
* LTI launch parameters
* @param string $customstr
* Custom parameters defined for tool
* @param string $instructorcustomstr
* Custom parameters defined for this placement
* @param boolean $islti2
* True if an LTI 2 tool is being launched
* @return array Custom parameters
*/
function qtype_lti_build_custom_parameters($toolproxy, $tool, $instance, $params,
$customstr, $instructorcustomstr, $islti2, $userid) {
// Concatenate the custom parameters from the administrator and the instructor
// Instructor parameters are only taken into consideration if the administrator
// has given permission.
$custom = array();
if ($customstr) {
$custom = qtype_lti_split_custom_parameters($toolproxy, $tool, $params, $customstr, $userid, $islti2);
}
if (!isset($typeconfig['allowinstructorcustom']) || $typeconfig['allowinstructorcustom'] != QTYPE_LTI_SETTING_NEVER) {
if ($instructorcustomstr) {
$custom = array_merge(
qtype_lti_split_custom_parameters($toolproxy, $tool, $params, $instructorcustomstr,
$userid, $islti2), $custom);
}
}
if ($islti2) {
$custom = array_merge(
qtype_lti_split_custom_parameters($toolproxy, $tool, $params,
$tool->parameter, $userid, true), $custom);
$settings = qtype_lti_get_tool_settings($tool->toolproxyid);
$custom = array_merge($custom, qtype_lti_get_custom_parameters($toolproxy, $tool, $params, $settings));
if (!empty($instance->course)) {
$settings = qtype_lti_get_tool_settings($tool->toolproxyid, $instance->course);
$custom = array_merge($custom, qtype_lti_get_custom_parameters($toolproxy, $tool, $params, $settings));
if (!empty($instance->id)) {
$settings = qtype_lti_get_tool_settings($tool->toolproxyid, $instance->course, $instance->id);
$custom = array_merge($custom, qtype_lti_get_custom_parameters($toolproxy, $tool, $params, $settings));
}
}
}
return $custom;
}
/**
* Builds a standard LTI Content-Item selection request.
*
* @param int $id
* The tool type ID.
* @param stdClass $course
* The course object.
* @param moodle_url $returnurl
* The return URL in the tool consumer (TC) that the tool provider (TP)
* will use to return the Content-Item message.
* @param string $title
* The tool's title, if available.
* @param string $text
* The text to display to represent the content item. This value may be a long description of the content item.
* @param array $mediatypes
* Array of MIME types types supported by the TC. If empty, the TC will support ltilink by default.
* @param array $presentationtargets
* Array of ways in which the selected content item(s) can be requested to be opened
* (via the presentationDocumentTarget element for a returned content item).
* If empty, "frame", "iframe", and "window" will be supported by default.
* @param bool $autocreate
* Indicates whether any content items returned by the TP would be automatically persisted without
* @param bool $multiple
* Indicates whether the user should be permitted to select more than one item. False by default.
* any option for the user to cancel the operation. False by default.
* @param bool $unsigned
* Indicates whether the TC is willing to accept an unsigned return message, or not.
* A signed message should always be required when the content item is being created automatically in the
* TC without further interaction from the user. False by default.
* @param bool $canconfirm
* Flag for can_confirm parameter. False by default.
* @param bool $copyadvice
* Indicates whether the TC is able and willing to make a local copy of a content item. False by default.
* @return stdClass The object containing the signed request parameters and the URL to the TP's Content-Item selection interface.
* @throws moodle_exception When the LTI tool type does not exist.`
* @throws coding_exception For invalid media type and presentation target parameters.
*/
function qtype_lti_build_content_item_selection_request($id, $course, moodle_url $returnurl, $title = '',
$text = '', $mediatypes = [], $presentationtargets = [],
$autocreate = false, $multiple = false, $unsigned = false,
$canconfirm = false, $copyadvice = false, $userid = null, $readonly = null,
$questionmode = 'create', $manuallygradedinmoodle = 0,
$extracodeexpertparams = array()) {
$tool = qtype_lti_get_type($id);
// Validate parameters.
if (!$tool) {
throw new moodle_exception('errortooltypenotfound', 'qtype_lti');
}
if (!is_array($mediatypes)) {
throw new coding_exception('The list of accepted media types should be in an array');
}
if (!is_array($presentationtargets)) {
throw new coding_exception('The list of accepted presentation targets should be in an array');
}
// Check title. If empty, use the tool's name.
if (empty($title)) {
$title = $tool->name;
}
$typeconfig = qtype_lti_get_type_config($id);
$key = '';
$secret = '';
$islti2 = false;
if (isset($tool->toolproxyid)) {
$islti2 = true;
$toolproxy = qtype_lti_get_tool_proxy($tool->toolproxyid);
$key = $toolproxy->guid;
$secret = $toolproxy->secret;
} else {
$toolproxy = null;
if (!empty($typeconfig['resourcekey'])) {
$key = $typeconfig['resourcekey'];
}
if (!empty($typeconfig['password'])) {
$secret = $typeconfig['password'];
}
}
$tool->enabledcapability = '';
if (!empty($typeconfig['enabledcapability_ContentItemSelectionRequest'])) {
$tool->enabledcapability = $typeconfig['enabledcapability_ContentItemSelectionRequest'];
}
$tool->parameter = '';
if (!empty($typeconfig['parameter_ContentItemSelectionRequest'])) {
$tool->parameter = $typeconfig['parameter_ContentItemSelectionRequest'];
}
// Set the tool URL.
if (!empty($typeconfig['toolurl_ContentItemSelectionRequest'])) {
$toolurl = new moodle_url($typeconfig['toolurl_ContentItemSelectionRequest']);
} else {
$toolurl = new moodle_url($typeconfig['toolurl']);
}
// Check if SSL is forced.
if (!empty($typeconfig['forcessl'])) {
// Make sure the tool URL is set to https.
if (strtolower($toolurl->get_scheme()) === 'http') {
$toolurl->set_scheme('https');
}
// Make sure the return URL is set to https.
if (strtolower($returnurl->get_scheme()) === 'http') {
$returnurl->set_scheme('https');
}
}
$toolurlout = $toolurl->out(false);
// Get base request parameters.
$instance = new stdClass();
$instance->course = $course->id;
$requestparams = qtype_lti_build_request($instance, $typeconfig, $course, $userid, $readonly, $questionmode,
$manuallygradedinmoodle, $extracodeexpertparams, $id, $islti2);
// Get LTI2-specific request parameters and merge to the request parameters if applicable.
if ($islti2) {
$lti2params = qtype_lti_build_request_lti2($tool, $requestparams);
$requestparams = array_merge($requestparams, $lti2params);
}
// Get standard request parameters and merge to the request parameters.
$orgid = !empty($typeconfig['organizationid']) ? $typeconfig['organizationid'] : '';
$standardparams = qtype_lti_build_standard_request(null, $orgid, $islti2,
$extracodeexpertparams, 'ContentItemSelectionRequest');
$requestparams = array_merge($requestparams, $standardparams);
// Get custom request parameters and merge to the request parameters.
$customstr = '';
if (!empty($typeconfig['customparameters'])) {
$customstr = $typeconfig['customparameters'];
}
$customparams = qtype_lti_build_custom_parameters($toolproxy, $tool, $instance, $requestparams, $customstr, '', $islti2,
$userid);
$requestparams = array_merge($requestparams, $customparams);
// Allow request params to be updated by sub-plugins.
$plugins = core_component::get_plugin_list('ltisource');
foreach (array_keys($plugins) as $plugin) {
$pluginparams = component_callback('ltisource_' . $plugin, 'before_launch', [$instance, $toolurlout, $requestparams],
[]);
if (!empty($pluginparams) && is_array($pluginparams)) {
$requestparams = array_merge($requestparams, $pluginparams);
}
}
// Media types. Set to ltilink by default if empty.
if (empty($mediatypes)) {
$mediatypes = ['application/vnd.ims.lti.v1.ltilink'];
}
$requestparams['accept_media_types'] = implode(',', $mediatypes);
// Presentation targets. Supports frame, iframe, window by default if empty.
if (empty($presentationtargets)) {
$presentationtargets = ['frame', 'iframe', 'window'];
}
$requestparams['accept_presentation_document_targets'] = implode(',', $presentationtargets);
// Other request parameters.
$requestparams['accept_copy_advice'] = $copyadvice === true ? 'true' : 'false';
$requestparams['accept_multiple'] = $multiple === true ? 'true' : 'false';
$requestparams['accept_unsigned'] = $unsigned === true ? 'true' : 'false';
$requestparams['auto_create'] = $autocreate === true ? 'true' : 'false';
$requestparams['can_confirm'] = $canconfirm === true ? 'true' : 'false';
$requestparams['content_item_return_url'] = $returnurl->out(false);
$requestparams['title'] = $title;
$requestparams['text'] = $text;
$signedparams = qtype_lti_sign_parameters($requestparams, $toolurlout, 'POST', $key, $secret);
$toolurlparams = $toolurl->params();
// Strip querystring params in endpoint url from $signedparams to avoid duplication.
if (!empty($toolurlparams) && !empty($signedparams)) {
foreach (array_keys($toolurlparams) as $paramname) {
if (isset($signedparams[$paramname])) {
unset($signedparams[$paramname]);
}
}
}
// Check for params that should not be passed. Unset if they are set.
$unwantedparams = ['resource_link_id', 'resource_link_title', 'resource_link_description', 'launch_presentation_return_url',
'lis_result_sourcedid'];
foreach ($unwantedparams as $param) {
if (isset($signedparams[$param])) {
unset($signedparams[$param]);
}
}
// Prepare result object.
$result = new stdClass();
$result->params = $signedparams;
$result->url = $toolurlout;
return $result;
}
/**
* Processes the tool provider's response to the ContentItemSelectionRequest and builds the configuration data from the
* selected content item.
* This configuration data can be then used when adding a tool into the course.
*
* @param int $typeid
* The tool type ID.
* @param string $messagetype
* The value for the qtype_lti_message_type parameter.
* @param string $ltiversion
* The value for the qtype_lti_version parameter.
* @param string $consumerkey
* The consumer key.
* @param string $contentitemsjson
* The JSON string for the content_items parameter.
* @return stdClass The array of module information objects.
* @throws moodle_exception
* @throws lti\OAuthException
*/
function qtype_lti_tool_configuration_from_content_item($typeid, $messagetype, $ltiversion, $consumerkey, $contentitemsjson) {
$tool = qtype_lti_get_type($typeid);
// Validate parameters.
if (!$tool) {
throw new moodle_exception('errortooltypenotfound', 'qtype_lti');
}
// Check qtype_lti_message_type. Show debugging if it's not set to ContentItemSelection.
// No need to throw exceptions for now since qtype_lti_message_type does not seem to be used in this processing at the moment.
if ($messagetype !== 'ContentItemSelection') {
debugging("lti_message_type is invalid: {$messagetype}. It should be set to 'ContentItemSelection'.", DEBUG_DEVELOPER);
}
$typeconfig = qtype_lti_get_type_config($typeid);
if (isset($tool->toolproxyid)) {
$islti2 = true;
$toolproxy = qtype_lti_get_tool_proxy($tool->toolproxyid);
$key = $toolproxy->guid;
$secret = $toolproxy->secret;
} else {
$islti2 = false;
$toolproxy = null;
if (!empty($typeconfig['resourcekey'])) {
$key = $typeconfig['resourcekey'];
} else {
$key = '';
}
if (!empty($typeconfig['password'])) {
$secret = $typeconfig['password'];
} else {
$secret = '';
}
}
// Check LTI versions from our side and the response's side. Show debugging if they don't match.
// No need to throw exceptions for now since LTI version does not seem to be used in this processing at the moment.
$expectedversion = QTYPE_LTI_VERSION_1;
if ($islti2) {
$expectedversion = QTYPE_LTI_VERSION_2;
}
if ($ltiversion !== $expectedversion) {
debugging(
"lti_version from response does not match the tool's configuration. Tool: {$expectedversion}," .
" Response: {$ltiversion}", DEBUG_DEVELOPER);
}
if ($consumerkey !== $key) {
throw new moodle_exception('errorincorrectconsumerkey', 'qtype_lti');
}
$store = new lti\TrivialOAuthDataStore();
$store->add_consumer($key, $secret);
$server = new lti\OAuthServer($store);
$method = new lti\OAuthSignatureMethod_HMAC_SHA1();
$server->add_signature_method($method);
$request = lti\OAuthRequest::from_request();
try {
$server->verify_request($request);
} catch (lti\OAuthException $e) {
throw new lti\OAuthException("OAuth signature failed: " . $e->getMessage());
}
$items = json_decode($contentitemsjson);
if (empty($items)) {
throw new moodle_exception('errorinvaliddata', 'qtype_lti', '', $contentitemsjson);
}
if ($items->{'@context'} !== 'http://purl.imsglobal.org/ctx/lti/v1/ContentItem') {
throw new moodle_exception('errorinvalidmediatype', 'qtype_lti', '', $items->{'@context'});
}
if (!isset($items->{'@graph'}) || !is_array($items->{'@graph'}) || (count($items->{'@graph'}) > 1)) {
throw new moodle_exception('errorinvalidresponseformat', 'qtype_lti');
}
$config = null;
if (!empty($items->{'@graph'})) {
$item = $items->{'@graph'}[0];
$config = new stdClass();
$config->name = '';
if (isset($item->title)) {
$config->name = $item->title;
}
if (empty($config->name)) {
$config->name = $tool->name;
}
if (isset($item->text)) {
$config->introeditor = ['text' => $item->text, 'format' => FORMAT_PLAIN];
}
if (isset($item->icon->{'@id'})) {
$iconurl = new moodle_url($item->icon->{'@id'});
// Assign item's icon URL to secureicon or icon depending on its scheme.
if (strtolower($iconurl->get_scheme()) === 'https') {
$config->secureicon = $iconurl->out(false);
} else {
$config->icon = $iconurl->out(false);
}
}
if (isset($item->url)) {
$url = new moodle_url($item->url);
$config->toolurl = $url->out(false);
$config->typeid = 0;
} else {
$config->typeid = $typeid;
}
$config->instructorchoicesendname = QTYPE_LTI_SETTING_NEVER;
$config->instructorchoicesendemailaddr = QTYPE_LTI_SETTING_NEVER;
$config->instructorchoiceacceptgrades = QTYPE_LTI_SETTING_NEVER;
$config->launchcontainer = QTYPE_LTI_LAUNCH_CONTAINER_DEFAULT;