-
Notifications
You must be signed in to change notification settings - Fork 100
/
bltilaunch.php
3033 lines (2857 loc) · 136 KB
/
bltilaunch.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
//IMathAS: BasicLTI Producer Code
//(c) David Lippman 2009
//
//
//launches with 5 types of key/secrets
// username : of a user with rights 11 or 76 (has to manually entered into database, along with a plaintext password as the secret)
// aid_### : launches assessment with given id. secret is course's ltisecret
// cid_### : launches course with given id. secret is course's ltisecret
// placein_### : launches a content linkage selector. In Canvas, uses resource selection return.
// in others, links to resource id (which is lost on LMS course copy)
// sso_username : launches single signon to home page using given userid w/ rights 11 or 76.
// secret value stored in DB password field. Currently must be manually editted in DB
// username : like sso_username, but triggers course/item connection
// aid_, cid_, and sso_ types accept additional _0 or _1 : 0 is default, and links LMS account with a local account
// 1 using LMS for validation, does not ask for local account info
//
// for sso_ and username types, if associated user has rights 11, instructors must link accounts;
// rights 76 allows TC to create instructor accounts
//
// LMS MUST provide, in addition to key and secret:
// user_id
//
// LMS MAY provide:
// lis_person_name_given
// lis_person_name_family
// lis_person_contact_email_primary
header('P3P: CP="ALL CUR ADM OUR"');
$init_skip_csrfp = true;
$init_session_start = true;
require_once "init_without_validate.php";
unset($init_skip_csrfp);
//Look to see if a hook file is defined, and include if it is
if (isset($CFG['hooks']['bltilaunch'])) {
require_once $CFG['hooks']['bltilaunch'];
}
$curdir = rtrim(dirname(__FILE__), '/\\');
if((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS']=='on') || (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO']=='https')) {
$urlmode = 'https://';
} else if ($_SERVER['HTTP_HOST'] != 'localhost') {
$urlmode = 'http://';
$errormsg = _('This launch was made insecurely (using http instead of https). ');
$errormsg .= sprintf(_('%s requires secure launches to protect student data. '),$installname);
$ltirole = strtolower($_REQUEST['roles']);
if (strpos($ltirole,'instructor')!== false || strpos($ltirole,'administrator')!== false || strpos($ltirole,'contentdeveloper')!== false) {
$errormsg .= _('Please update the links or tool in the LMS to use https (aka SSL). ');
if ($_REQUEST['tool_consumer_info_product_family_code'] == 'moodle') {
$errormsg .= _('In Moodle, you can do this by clicking the "Edit preconfigured tool" icon, scrolling down to Privacy, and clicking the Force SSL checkbox. ');
$errormsg .= _('If you do not have access to do this, you might need to ask your LMS administrator to enable the Force SSL option. ');
}
}
reporterror($errormsg);
}
if ($enablebasiclti!=true) {
echo _("BasicLTI not enabled");
exit;
}
function reporterror($err) {
global $imasroot,$staticroot,$installname;
require_once "header.php";
printf('<p>%s</p>', Sanitize::encodeStringForDisplay($err));
require_once "footer.php";
exit;
}
function generateToolState() {
if (function_exists("random_bytes")) {
$token = bin2hex(random_bytes(64));
} elseif (function_exists("openssl_random_pseudo_bytes")) {
$token = bin2hex(openssl_random_pseudo_bytes(64));
} else {
$token = '';
for ($i = 0; $i < 64; ++$i) {
$r = mt_rand (0, 35);
if ($r < 26) {
$c = chr(ord('a') + $r);
} else {
$c = chr(ord('0') + $r - 26);
}
$token .= $c;
}
}
return substr($token, 0, 64);
}
function do112relaunch() {
if (!isset($_REQUEST['platform_state'])) {
reporterror(_("Missing platform_state"));
}
$_SESSION['lti_tool_state'] = generateToolState();
echo '<html><body><form id="theform" method="POST" action="'.Sanitize::encodeStringForDisplay($_REQUEST['relaunch_url']).'">
<input type=hidden name="tool_state" value="'.Sanitize::encodeUrlParam($_SESSION['lti_tool_state']).'">
<input type=hidden name="platform_state" value="'.Sanitize::encodeUrlParam($_REQUEST['platform_state']).'">
</form><script>document.getElementById("theform").submit();</script></body></html>';
exit;
}
function verify112relaunch() {
if ($_REQUEST['tool_state'] != $_SESSION['lti_tool_state']) {
reporterror(_("Invalid tool_state"));
exit;
}
}
//start session - session_start already called in init
$sessionid = session_id();
$atstarthasltiuserid = isset($_SESSION['ltiuserid']);
$askforuserinfo = false;
$now = time();
//use new behavior for place_aid requests that don't come from a placein_###_# key
if (
(isset($_SESSION['place_aid']) && isset($_SESSION['lti_keytype']) && $_SESSION['lti_keytype']=='cc-a' && !isset($_REQUEST['oauth_consumer_key']))
||
(isset($_REQUEST['custom_place_aid']) && isset($_REQUEST['oauth_consumer_key']) && substr($_REQUEST['oauth_consumer_key'],0,7)!='placein')
) {
//if (isset($_SESSION['place_aid']) || isset($_REQUEST['custom_place_aid'])) {
/*use new behavior for place_aid requests */
//check to see if accessiblity page is posting back
if (isset($_GET['launch'])) {
if (empty($_SESSION['userid'])) {
reporterror(_("No authorized session exists. This is most likely caused by your browser blocking third-party cookies. Please adjust your browser settings and try again. If you are using Safari, you may need to disable Prevent Cross-Site Tracking."));
}
$userid = $_SESSION['userid'];
if (empty($_POST['tzname']) && $_POST['tzoffset']=='') {
echo _('Uh oh, something went wrong. Please go back and try again');
exit;
}
if (isset($_POST['tzname'])) {
$_SESSION['logintzname'] = $_POST['tzname'];
}
if ($_POST['orig_linkid'] != $_SESSION['lti_resource_link_id']) {
echo _('Uh oh, something went wrong. Please go back and try again').'. ';
echo _('You may have launched too many assignments too quickly.');
exit;
}
require_once "$curdir/includes/userprefs.php";
generateuserprefs($userid);
$stm = $DBH->prepare('UPDATE imas_users SET lastaccess=:lastaccess WHERE id=:id');
$stm->execute(array(':lastaccess'=>$now, ':id'=>$userid));
if (isset($_POST['tzname'])) {
$tzname = $_POST['tzname'];
} else {
$tzname = '';
}
$_SESSION['tzoffset'] = $_POST['tzoffset'];
$_SESSION['tzname'] = $tzname;
if (isset($CFG['static_server']) && !empty($_POST['static_check'])) {
$_SESSION['static_ok'] = 1;
}
$keyparts = explode('_',$_SESSION['lti_key']);
if ($_SESSION['ltiitemtype']==0) { //is aid
$aid = $_SESSION['ltiitemid'];
$stm = $DBH->prepare('SELECT courseid,ver FROM imas_assessments WHERE id=:aid');
$stm->execute(array(':aid'=>$aid));
list($cid,$aver) = $stm->fetch(PDO::FETCH_NUM);
if ($cid===false) {
$diaginfo = "(Debug info: 1-$aid)";
reporterror(_("This assignment does not appear to exist anymore.")." $diaginfo");
}
if ($_SESSION['ltirole'] == 'learner') {
$stm = $DBH->prepare('INSERT INTO imas_content_track (userid,courseid,type,typeid,viewtime,info) VALUES (:userid,:courseid,\'assesslti\',:typeid,:viewtime,\'\')');
$stm->execute(array(':userid'=>$userid,':courseid'=>$cid,':typeid'=>$aid,':viewtime'=>$now));
}
if ($aver > 1) {
header('Location: ' . $GLOBALS['basesiteurl'] . "/assess2/?cid=$cid&aid=$aid");
} else {
header('Location: ' . $GLOBALS['basesiteurl'] . "/assessment/showtest.php?cid=$cid&id=$aid");
}
} else if ($_SESSION['ltiitemtype']==1) { //is cid
$cid = $_SESSION['ltiitemid'];
header('Location: ' . $GLOBALS['basesiteurl'] . "/course/course.php?cid=$cid");
} else if ($_SESSION['ltiitemtype']==2) {
header('Location: ' . $GLOBALS['basesiteurl'] . "/index.php");
} else if ($_SESSION['ltiitemtype']==3) {
$cid = $_SESSION['ltiitemid'][2];
$folder = $_SESSION['ltiitemid'][1];
header('Location: ' . $GLOBALS['basesiteurl'] . "/course/course.php?cid=$cid&folder=".$folder);
} else { //will only be instructors hitting this option
header('Location: ' . $GLOBALS['basesiteurl'] . "/ltihome.php");
}
exit;
} else if (isset($_GET['accessibility'])) {
if (empty($_SESSION['userid'])) {
reporterror(_("No authorized session exists. This is most likely caused by your browser blocking third-party cookies. Please adjust your browser settings and try again. If you are using Safari, you may need to disable Prevent Cross-Site Tracking."));
}
$userid = $_SESSION['userid'];
//time to output a postback to capture tzname
$pref = 0;
$flexwidth = true;
$nologo = true;
$placeinhead = "<script type=\"text/javascript\" src=\"$staticroot/javascript/jstz_min.js\" ></script>";
require_once "header.php";
echo "<h3>Connecting to $installname</h3>";
echo "<form id=\"postbackform\" method=\"post\" action=\"" . $imasroot . "/bltilaunch.php?launch=true\" ";
if ($_SESSION['ltiitemtype']==0 && $_SESSION['ltitlwrds'] != '') {
echo "onsubmit='return confirm(\"This assessment has a time limit of "
.Sanitize::encodeStringForJavascript($_SESSION['ltitlwrds'])
.". Click OK to start or continue working on the assessment.\")' >";
echo "<p class=noticetext>This assessment has a time limit of ".Sanitize::encodeStringForDisplay($_SESSION['ltitlwrds']).".</p>";
echo '<div class="textright"><input type="submit" value="Continue" /></div>';
if ($_SESSION['lticanuselatepass']) {
echo "<p><a href=\"$imasroot/course/redeemlatepass.php?from=ltitimelimit&cid=".Sanitize::encodeUrlParam($_SESSION['ltiitemcid'])."&aid=".Sanitize::encodeUrlParam($_SESSION['ltiitemid'])."\">", _('Use LatePass'), "</a></p>";
}
} else {
echo ">";
}
echo '<input type=hidden name="orig_linkid" value="'. Sanitize::encodeStringForDisplay($_SESSION['lti_resource_link_id']) . '"/>';
?>
<div id="settings"><noscript>JavaScript is not enabled. JavaScript is required for <?php echo $installname; ?>.
Please enable JavaScript and reload this page</noscript></div>
<input type="hidden" id="tzoffset" name="tzoffset" value="" />
<input type="hidden" id="tzname" name="tzname" value="">
<script type="text/javascript">
$(function() {
var thedate = new Date();
document.getElementById("tzoffset").value = thedate.getTimezoneOffset();
var tz = jstz.determine();
document.getElementById("tzname").value = tz.name();
<?php
if ($_SESSION['ltiitemtype']!=0 || $_SESSION['ltitlwrds'] == '') {
//auto submit the form
echo 'document.getElementById("postbackform").submit();';
}
?>
});
</script>
</form>
<?php
require_once "footer.php";
exit;
} else if (isset($_GET['userinfo']) && isset($_SESSION['ltiuserid'])) {
//check to see if new LTI user is posting back user info
$ltiuserid = $_SESSION['ltiuserid'];
$ltiorg = $_SESSION['ltiorg'];
$ltirole = $_SESSION['ltirole'];
$keyparts = explode('_',$_SESSION['lti_key']);
$name_only = false;
if (count($keyparts)==1 && $ltirole=='learner') {
$name_only = true;
} else if (count($keyparts)>2 && $keyparts[2]==1 && $ltirole=='learner') {
$name_only = true;
}
if ($ltirole=='learner' || $_SESSION['lti_keyrights']==76 || $_SESSION['lti_keyrights']==77) {
$allow_acctcreation = true;
} else {
$allow_acctcreation = false;
}
if ($_GET['userinfo']=='set') {
if (isset($CFG['GEN']['newpasswords'])) {
require_once "includes/password.php";
}
//check input
$infoerr = '';
unset($userid);
if ($name_only) {
if (empty($_POST['firstname']) || empty($_POST['lastname'])) {
$infoerr = 'Please provide your name';
}
$_POST['email'] = 'none@none.com';
$msgnot = 0;
} else {
if (!empty($_POST['curSID']) && !empty($_POST['curPW'])) {
//provided current SID/PW pair
$stm = $DBH->prepare('SELECT password,id,mfa FROM imas_users WHERE SID=:sid');
$stm->execute(array(':sid'=>$_POST['curSID']));
//if (mysql_num_rows($result)==0) {
if ($stm->rowCount()==0) {
$infoerr = 'Username (key) is not valid';
} else {
list($realpw,$tmpuserid,$mfadata) = $stm->fetch(PDO::FETCH_NUM); //DB mysql_result($result,0,0);
if (((!isset($CFG['GEN']['newpasswords']) || $CFG['GEN']['newpasswords']!='only') && ($realpw == md5($_POST['curPW'])))
|| (isset($CFG['GEN']['newpasswords']) && password_verify($_POST['curPW'],$realpw)) ) {
if ($mfadata != '') {
$mfadata = json_decode($mfadata, true);
if (empty($mfadata['mfatype']) || $mfadata['mfatype'] == 'all') {
$flexwidth = true;
$nologo = true;
require_once __DIR__.'/includes/mfa.php';
$formaction = $imasroot."/bltilaunch.php?userinfo=set";
if (!isset($_POST['mfatoken'])) {
mfa_showLoginEntryForm($formaction, '', false);
exit;
} else if (mfa_verify($mfadata, $formaction, $tmpuserid, false)) {
// good to go
} else {
$infoerr = "MFA verification failed";
}
}
}
$userid= $tmpuserid;
} else {
$infoerr = 'Existing username/password provided are not valid.';
unset($tmpuserid);
}
}
} else {
if (!$allow_acctcreation) {
$infoerr = 'Must link to an existing account';
} else {
require_once __DIR__.'/includes/newusercommon.php';
$infoerr = checkNewUserValidation();
//new info
if (isset($_POST['msgnot'])) {
$msgnot = 1;
} else {
$msgnot = 0;
}
if (isset($CFG['GEN']['newpasswords'])) {
$md5pw = password_hash($_POST['pw1'], PASSWORD_DEFAULT);
} else {
$md5pw = md5($_POST['pw1']);
}
}
}
}
if ($infoerr=='') { // no error, so create!
$DBH->beginTransaction();
$stm = $DBH->prepare('INSERT INTO imas_ltiusers (org,ltiuserid) VALUES (:org,:ltiuserid)');
$stm->execute(array(':org'=>$ltiorg,':ltiuserid'=>$ltiuserid));
$localltiuser = $DBH->lastInsertId();
if (!isset($userid) && $allow_acctcreation) {
if ($name_only) {
//make up a username/password for them
$_POST['SID'] = 'lti-'.$localltiuser;
$md5pw = 'pass'; //totally unusable since not md5'ed
}
if ($ltirole=='instructor') {
if (isset($CFG['LTI']['instrrights'])) {
$rights = $CFG['LTI']['instrrights'];
} else {
$rights = 40;
}
$newgroupid = intval($_SESSION['lti_keygroupid']);
$query = "INSERT INTO imas_users (SID,password,rights,FirstName,LastName,email,msgnotify,groupid) VALUES ";
$query .= '(:SID,:password,:rights,:FirstName,:LastName,:email,:msgnotify,:groupid)';
$stm = $DBH->prepare($query);
$stm->execute(array(':SID'=>$_POST['SID'], ':password'=>$md5pw,':rights'=>$rights,
':FirstName'=>Sanitize::stripHtmlTags($_POST['firstname']),
':LastName'=>Sanitize::stripHtmlTags($_POST['lastname']),
':email'=>Sanitize::emailAddress($_POST['email']),
':msgnotify'=>$msgnot,':groupid'=>$newgroupid));
} else {
$rights = 10;
$query = "INSERT INTO imas_users (SID,password,rights,FirstName,LastName,email,msgnotify) VALUES ";
$query .= '(:SID,:password,:rights,:FirstName,:LastName,:email,:msgnotify)';
$stm = $DBH->prepare($query);
$stm->execute(array(':SID'=>$_POST['SID'], ':password'=>$md5pw,':rights'=>$rights,
':FirstName'=>Sanitize::stripHtmlTags($_POST['firstname']),
':LastName'=>Sanitize::stripHtmlTags($_POST['lastname']),
':email'=>Sanitize::emailAddress($_POST['email']),
':msgnotify'=>$msgnot));
}
$userid = $DBH->lastInsertId(); //DB mysql_insert_id();
if ($rights>=20) {
//log new account
$stm = $DBH->prepare("INSERT INTO imas_log (time, log) VALUES (:now, :log)");
$stm->execute(array(':now'=>$now, ':log'=>"New Instructor Request: $userid:: Group: $newgroupid, added via LTI"));
$reqdata = array('added'=>$now, 'actions'=>array(array('on'=>$now, 'status'=>11, 'via'=>'LTI')));
$stm = $DBH->prepare("INSERT INTO imas_instr_acct_reqs (userid,status,reqdate,reqdata) VALUES (?,11,?,?)");
$stm->execute(array($newuserid, $now, json_encode($reqdata)));
}
}
$stm = $DBH->prepare('UPDATE imas_ltiusers SET userid=:userid WHERE id=:localltiuser');
$stm->execute(array(':userid'=>$userid, ':localltiuser'=>$localltiuser));
$DBH->commit();
} else {
//uh-oh, had an error. Better ask for user info again
$askforuserinfo = true;
}
} else {
//ask for student info
$flexwidth = true;
$nologo = true;
$placeinhead = '<script type="text/javascript" src="'.$staticroot.'/javascript/jquery.validate.min.js?v=122917"></script>';
require_once "header.php";
if (isset($infoerr)) {
echo '<p class=noticetext>'.Sanitize::encodeStringForDisplay($infoerr).'</p>';
}
echo "<form method=\"post\" id=\"pageform\" class=\"limitaftervalidate\" action=\"".$imasroot."/bltilaunch.php?userinfo=set\" ";
if ($name_only) {
//using LTI for authentication; don't need username/password
//only request name
echo "<p>Please provide a little information about yourself:</p>";
echo "<span class=form><label for=\"firstname\">Enter First Name (given name):</label></span> <input class=form type=text size=20 id=firstname name=firstname autocomplete=\"given-name\"><BR class=form>\n";
echo "<span class=form><label for=\"lastname\">Enter Last Name (surname):</label></span> <input class=form type=text size=20 id=lastname name=lastname autocomplete=\"family-name\"><BR class=form>\n";
echo "<div class=submit><input type=submit value='Submit'></div>\n";
echo '<script type="text/javascript"> $(function() {
$("#pageform").validate({
rules: {
firstname: {required: true},
lastname: {required: true}
},
submitHandler: function(el,evt) {return submitlimiter(evt);}
});
});</script>';
} else {
$deffirst = '';
$deflast = '';
$defemail = '';
if (isset($_SESSION['LMSfirstname'])) {
$deffirst = $_SESSION['LMSfirstname'];
}
if (isset($_SESSION['LMSlastname'])) {
$deflast = $_SESSION['LMSlastname'];
}
if (isset($_SESSION['LMSemail'])) {
$defemail = $_SESSION['LMSemail'];
}
if (isset($_SESSION['ltiorgname'])) {
$ltiorgname = $_SESSION['ltiorgname'];
} else {
$ltiorgname = $ltiorg;
}
//strip off prepended org info before display
$ltiorgparts = explode(':',$ltiorgname);
if (count($ltiorgparts)>2) {
array_shift($ltiorgparts);
$ltiorgname = implode(':',$ltiorgparts);
} else if (count($ltiorgparts)>1) {
$ltiorgname = $ltiorgparts[1] ?? '';
}
//tying LTI to IMAthAS account
//give option to provide existing account info, or provide full new student info
if ($allow_acctcreation) {
echo "<p>".sprintf(_("If you already have an account on %s, enter your username and password below to enable automated signon from %s"),$installname,Sanitize::encodeStringForDisplay($ltiorgname))."</p>";
} else {
echo "<p>".sprintf(_("Enter your username and password for %s below to enable automated signon from %s"),$installname,Sanitize::encodeStringForDisplay($ltiorgname))."</p>";
}
echo "<span class=form><label for=\"curSID\">".Sanitize::encodeStringForDisplay($loginprompt).":</label></span> <input class=form type=text size=12 id=\"curSID\" name=\"curSID\"><BR class=form>\n";
echo "<span class=form><label for=\"curPW\">"._("Password:")."</label></span><input class=form type=password size=20 id=\"curPW\" name=\"curPW\"><BR class=form>\n";
echo "<div class=submit><input type=submit value='"._("Sign In")."'></div>\n";
if ($allow_acctcreation) {
echo "<p>".sprintf(_("If you do not already have an account on %s, provide the information below to create an account and enable automated signon from %s"),$installname,Sanitize::encodeStringForDisplay($ltiorgname))."</p>";
echo '<div id="errorlive" aria-live="polite" class="sr-only"></div>';
echo "<span class=form><label for=\"SID\">".Sanitize::encodeStringForDisplay($longloginprompt).":</label></span> <input class=form type=text size=12 id=SID name=SID><BR class=form>\n";
echo "<span class=form><label for=\"pw1\">"._("Choose a password:")."</label></span><input class=form type=password size=20 id=pw1 name=pw1><BR class=form>\n";
echo "<span class=form><label for=\"pw2\">"._("Confirm password:")."</label></span> <input class=form type=password size=20 id=pw2 name=pw2><BR class=form>\n";
echo "<span class=form><label for=\"firstname\">"._("Enter First Name:")."</label></span> <input class=form type=text value=\"".Sanitize::encodeStringForDisplay($deffirst)."\" size=20 id=firstname name=firstname autocomplete=\"given-name\"><BR class=form>\n";
echo "<span class=form><label for=\"lastname\">"._("Enter Last Name:")."</label></span> <input class=form type=text value=\"".Sanitize::encodeStringForDisplay($deflast)."\" size=20 id=lastname name=lastname autocomplete=\"family-name\"><BR class=form>\n";
echo "<span class=form><label for=\"email\">"._("Enter E-mail address:")."</label></span> <input class=form type=email value=\"".Sanitize::encodeStringForDisplay($defemail)."\" size=60 id=email name=email autocomplete=\"email\"><BR class=form>\n";
echo "<span class=form><label for=\"msgnot\">"._("Notify me by email when I receive a new message:")."</label></span><input class=floatleft type=checkbox id=msgnot name=msgnot /><BR class=form>\n";
echo "<div class=submit><input type=submit value='"._("Create Account")."'></div>\n";
require_once __DIR__.'/includes/newusercommon.php';
$requiredrules = array(
'curSID'=>'{depends: function(element) {return $("#SID").val()==""}}',
'curPW'=>'{depends: function(element) {return $("#SID").val()==""}}',
'SID'=>'{depends: function(element) {return $("#SID").val()!=""}}',
'pw1'=>'{depends: function(element) {return $("#SID").val()!=""}}',
'pw2'=>'{depends: function(element) {return $("#SID").val()!=""}}',
'firstname'=>'{depends: function(element) {return $("#SID").val()!=""}}',
'lastname'=>'{depends: function(element) {return $("#SID").val()!=""}}',
'email'=>'{depends: function(element) {return $("#SID").val()!=""}}',
);
showNewUserValidation('pageform',array('curSID','curPW'), $requiredrules);
} else {
echo "<p>".sprintf(_("If you do not already have an account on %s, please visit the site to request an account."),$installname)."</p>";
echo '<script type="text/javascript"> $(function() {
$("#pageform").validate({
rules: {
curSID: {required: true},
curPW: {required: true}
},
submitHandler: function(el,evt) {return submitlimiter(evt);}
});
});</script>';
}
}
echo "</form>\n";
require_once "footer.php";
exit;
}
} else if (isset($_SESSION['ltiuserid']) && !isset($_REQUEST['oauth_consumer_key'])) {
//refreshed this page from accessibility options page so session already exists
// (if user_id is set, then is new LTI request, so want to pass down to OAuth)
//pull necessary info and continue
if (isset($_SESSION['userid'])) {
$userid = $_SESSION['userid'];
} else {
reporterror(_("No session recorded"));
}
$keyparts = explode('_',$_SESSION['lti_key']);
} else if(isset($_REQUEST['custom_view_folder'])) {
//temporary branch for handling this deprecated feature, until it can be removed.
$linkparts = explode("-",$_REQUEST['custom_view_folder']);
$stm = $DBH->prepare('SELECT itemorder FROM imas_courses WHERE id=:cid');
$stm->execute(array(':cid'=>$linkparts[0]));
if ($stm->rowCount()==0) {
reporterror(_("invalid course identifier in folder view launch"));
} else {
$cid = intval($linkparts[0]);
$row = $stm->fetch(PDO::FETCH_ASSOC); //DB mysql_fetch_row($result2);
$items = unserialize($row['itemorder']);
function findfolder($items,$n,$loc) {
foreach ($items as $k=>$b) {
if (is_array($b)) {
if ($b['id']==$n) {
return $loc.'-'.($k+1);
} else {
$out = findfolder($b['items'],$n,$loc.'-'.($k+1));
if ($out != '') {
return $out;
}
}
}
}
return '';
}
$loc = findfolder($items, $linkparts[1], '0');
if ($loc=='') {
reporterror(_("invalid folder identifier in folder view launch"));
}
header('Location: ' . $GLOBALS['basesiteurl'] . "/course/public.php?cid=".$linkparts[0]."&folder=".$loc);
}
exit;
} else {
//not postback of new LTI user info, so must be fresh request
//verify necessary POST values for LTI. OAuth specific will be checked later
if (empty($_REQUEST['lti_version'])) {
reporterror(_("Insufficient launch information. This might indicate your browser is set to restrict third-party cookies. Check your browser settings and try again. If you are using Safari, you may need to disable Prevent Cross-Site Tracking."));
}
if (empty($_REQUEST['user_id'])) {
if (isset($_REQUEST['relaunch_url'])) {
do112relaunch();
}
reporterror(_("Unable to launch - User information not provided (user_id is required)"));
} else {
$ltiuserid = $_REQUEST['user_id'];
}
if (!empty($_REQUEST['tool_state'])) {
verify112relaunch();
}
if (empty($_REQUEST['context_id'])) {
reporterror(_("Unable to launch - Course information not provided (context_id is required)"));
}
if (isset($_SESSION['ltiuserid']) && $_SESSION['ltiuserid']!=$ltiuserid) {
//new user - need to clear out session
session_destroy();
session_start();
session_regenerate_id();
$sessionid = session_id();
$_SESSION = array();
//setcookie(session_name(),session_id(),0,'','',false,true );
}
/*if (empty($_REQUEST['roles'])) {
reporterror("roles is required");
} else {
$ltirole = $_REQUEST['roles'];
}*/
if (empty($_REQUEST['tool_consumer_instance_guid'])) {
$ltiorg = 'Unknown';
} else {
$ltiorg = $_REQUEST['tool_consumer_instance_guid'];
}
if (empty($_REQUEST['oauth_consumer_key'])) {
reporterror(_("Unable to launch - oauth_consumer_key (resource key) is required"));
} else {
$ltikey = $_REQUEST['oauth_consumer_key'];
}
//check OAuth Signature!
require_once 'includes/OAuth.php';
require_once 'includes/ltioauthstore.php';
//set up OAuth
$store = new IMathASLTIOAuthDataStore();
$server = new OAuthServer($store);
$method = new OAuthSignatureMethod_HMAC_SHA1();
$server->add_signature_method($method);
$method2 = new OAuthSignatureMethod_HMAC_SHA256();
$server->add_signature_method($method2);
$request = OAuthRequest::from_request();
$base = $request->get_signature_base_string();
try {
$requestinfo = $server->verify_request($request);
} catch (Exception $e) {
reporterror($e->getMessage());
}
$store->mark_nonce_used($request);
$keyparts = explode('_',$ltikey);
$_SESSION['ltiorigkey'] = $ltikey;
// prepend ltiorg with courseid or sso+userid to prevent cross-instructor hacking
if ($keyparts[0]=='LTIkey') { //cid:org
$_SESSION['ltilookup'] = 'c';
$ltiorg = $keyparts[1].':'.$ltiorg;
$keytype = 'gc';
} else {
$_SESSION['ltilookup'] = 'u';
$ltiorg = $ltikey.':'.$ltiorg;
$keytype = 'g';
}
if (isset($_REQUEST['custom_place_aid'])) { //common catridge lti placement, or Canvas LTI selection
$placeaid = intval($_REQUEST['custom_place_aid']);
$keytype = 'cc-a';
$_SESSION['place_aid'] = $_REQUEST['custom_place_aid'];
} else if (isset($_REQUEST['custom_open_folder'])) {
$keytype = 'cc-of';
$parts = explode('-',$_REQUEST['custom_open_folder']);
$sourcecid = $parts[0];
$_SESSION['open_folder'] = array($sourcecid,$parts[1]);
}
//Store all LTI request data in session variable for reuse on submit
//if we got this far, secret has already been verified
$_SESSION['ltiuserid'] = $ltiuserid;
$_SESSION['ltiorg'] = $ltiorg;
$ltirole = strtolower($_REQUEST['roles']);
if (strpos($ltirole,'instructor')!== false || strpos($ltirole,'administrator')!== false || strpos($ltirole,'contentdeveloper')!== false) {
$ltirole = 'instructor';
} else {
$ltirole = 'learner';
}
$_SESSION['ltirole'] = $ltirole;
$_SESSION['lti_context_id'] = $_REQUEST['context_id'];
if (!empty($_REQUEST['context_label'])) {
$_SESSION['lti_context_label'] = $_REQUEST['context_label'];
} else if (!empty($_REQUEST['context_title'])) {
$_SESSION['lti_context_label'] = $_REQUEST['context_title'];
} else {
$_SESSION['lti_context_label'] = $_REQUEST['context_id'];
}
$_SESSION['lti_resource_link_id'] = $_REQUEST['resource_link_id'] ?? '';
$_SESSION['lti_lis_result_sourcedid'] = $_REQUEST['lis_result_sourcedid'] ?? '';
$_SESSION['lti_outcomeurl'] = $_REQUEST['lis_outcome_service_url'] ?? '';
$_SESSION['lti_key'] = $ltikey;
$_SESSION['lti_keytype'] = $keytype;
$_SESSION['lti_keyrights'] = $requestinfo[0]->rights;
$_SESSION['lti_keygroupid'] = intval($requestinfo[0]->groupid);
if (isset($_REQUEST['selection_directive']) && $_REQUEST['selection_directive']=='select_link') {
$_SESSION['selection_return'] = $_REQUEST['launch_presentation_return_url'];
$_SESSION['selection_return_format'] = "Canvas";
unset($_SESSION['place_aid']);
}
if (isset($_REQUEST['lti_message_type']) && $_REQUEST['lti_message_type']=='ContentItemSelectionRequest') {
$_SESSION['selection_return'] = $_REQUEST['content_item_return_url'];
$_SESSION['selection_targets'] = $_REQUEST['accept_presentation_document_targets'];
$_SESSION['selection_return_format'] = "IMSdeeplink";
if (isset($_REQUEST['ltiseltype']) && $_REQUEST['ltiseltype']=='assn') {
$_SESSION['selection_type'] = 'assn';
} else if (isset($_REQUEST['ltiseltype']) && $_REQUEST['ltiseltype']=='link') {
$_SESSION['selection_type'] = 'link';
} else {
$_SESSION['selection_type'] = 'all';
}
$_SESSION['selection_data'] = @$_REQUEST['data'];
unset($_SESSION['place_aid']);
}
unset($_SESSION['lti_duedate']);
if (!isset($_REQUEST['custom_canvas_assignment_due_at'])) {
if (isset($_REQUEST['custom_assignment_due_at'])) {
$_REQUEST['custom_canvas_assignment_due_at'] = $_REQUEST['custom_assignment_due_at'];
}
}
if (array_key_exists('custom_canvas_assignment_due_at', $_REQUEST)) {
$duedate = strtotime($_REQUEST['custom_canvas_assignment_due_at'] ?? '');
if ($duedate !== false) {
$_SESSION['lti_duedate'] = $duedate;
} else {
$_SESSION['lti_duedate'] = 2000000000;
}
}
//look if we know this user
$orgparts = explode(':',$ltiorg); //THIS was added to avoid issues when LMS GUID change, while still storing it
$shortorg = $orgparts[0]; //we'll only use the part from the lti key
$query = "SELECT lti.userid,iu.FirstName,iu.LastName,iu.email,lti.id FROM imas_ltiusers AS lti LEFT JOIN imas_users as iu ON lti.userid=iu.id ";
$query .= "WHERE lti.org LIKE :org AND lti.ltiuserid=:ltiuserid ";
if ($ltirole!='learner') {
//if they're a teacher, make sure their imathas account is too. If not, we'll act like we don't know them
//and require a new connection
$query .= "AND iu.rights>19 ";
}
//if multiple accounts, use student one first (if not $ltirole of teacher) then higher rights.
//if there was a mixup and multiple records were created, use the first one
$query .= "ORDER BY iu.rights, lti.id";
$stm = $DBH->prepare($query);
$stm->execute(array(':org'=>"$shortorg:%", ':ltiuserid'=>$ltiuserid));
if ($stm->rowCount()>0) { //yup, we know them
$userrow = $stm->fetch(PDO::FETCH_ASSOC);
$userid = $userrow['userid'];
if (((!empty($_REQUEST['lis_person_name_given']) && !empty($_REQUEST['lis_person_name_family'])) || !empty($_REQUEST['lis_person_name_full'])) &&
((count($keyparts)==1 && $ltirole=='learner') || (count($keyparts)>2 && $keyparts[2]==1 && $ltirole=='learner') )) {
if (!empty($_REQUEST['lis_person_name_given']) && !empty($_REQUEST['lis_person_name_family'])) {
$firstname = $_REQUEST['lis_person_name_given'];
$lastname = $_REQUEST['lis_person_name_family'];
} else {
$firstname = '';
$lastname = $_REQUEST['lis_person_name_full'];
}
if (!empty($_REQUEST['lis_person_contact_email_primary'])) {
$email = $_REQUEST['lis_person_contact_email_primary'];
} else if (!empty($userrow['email'])) {
$email = $userrow['email']; // keep existing if we have it and no new one
} else {
$email = 'none@none.com';
}
if ($userrow['FirstName'] === null) { //accidentally deleted the imas_users record! Restore it
$query = "INSERT INTO imas_users (id,SID,password,rights,FirstName,LastName,email,msgnotify) VALUES ";
$query .= '(:userid,:SID,:password,:rights,:FirstName,:LastName,:email,0)';
$stm = $DBH->prepare($query);
$stm->execute(array(':userid'=>$userid, ':SID'=>'lti-'.$userrow['id'], ':password'=>'pass' ,':rights'=>10,
':FirstName'=>Sanitize::stripHtmlTags($firstname),
':LastName'=>Sanitize::stripHtmlTags($lastname),
':email'=>Sanitize::emailAddress($email)));
} else if ($firstname != $userrow['FirstName'] || $lastname != $userrow['LastName'] || $email != $userrow['email']) {
//update imas_users record
$stm2 = $DBH->prepare("UPDATE imas_users SET FirstName=?,LastName=?,email=? WHERE id=?");
$stm2->execute(array($firstname, $lastname, $email, $userid));
}
}
} else {
//student is not known. Bummer. Better figure out what to do with them :)
//go ahead and create the account if:
//has name information (should we skip?)
//domain level placement and (student or instructor with acceptable key rights)
//a _1 type placement and (student or instructor with acceptable key rights)
if (((!empty($_REQUEST['lis_person_name_given']) && !empty($_REQUEST['lis_person_name_family'])) || !empty($_REQUEST['lis_person_name_full'])) &&
((count($keyparts)==1 && $ltirole=='learner') || (count($keyparts)>2 && $keyparts[2]==1 && $ltirole=='learner') )) {
if (!empty($_REQUEST['lis_person_name_given']) && !empty($_REQUEST['lis_person_name_family'])) {
$firstname = $_REQUEST['lis_person_name_given'];
$lastname = $_REQUEST['lis_person_name_family'];
} else {
$firstname = '';
$lastname = $_REQUEST['lis_person_name_full'];
}
if (!empty($_REQUEST['lis_person_contact_email_primary'])) {
$email = $_REQUEST['lis_person_contact_email_primary'];
} else {
$email = 'none@none.com';
}
$DBH->beginTransaction();
$stm = $DBH->prepare('INSERT INTO imas_ltiusers (org,ltiuserid) VALUES (:org,:ltiuserid)');
$stm->execute(array(':org'=>$ltiorg,':ltiuserid'=>$ltiuserid));
$localltiuser = $DBH->lastInsertId();
if (!isset($userid)) {
//make up a username/password for them
$_POST['SID'] = 'lti-'.$localltiuser;
$md5pw = 'pass'; //totally unusable since not md5'ed
if ($ltirole=='instructor') { //not currently used - no teachers without real usernames/passwords
if (isset($CFG['LTI']['instrrights'])) {
$rights = $CFG['LTI']['instrrights'];
} else {
$rights = 40;
}
$newgroupid = intval($_SESSION['lti_keygroupid']);
$query = "INSERT INTO imas_users (SID,password,rights,FirstName,LastName,email,msgnotify,groupid) VALUES ";
$query .= '(:SID,:password,:rights,:FirstName,:LastName,:email,0,:groupid)';
$stm = $DBH->prepare($query);
$stm->execute(array(':SID'=>$_POST['SID'], ':password'=>$md5pw,':rights'=>$rights,
':FirstName'=>Sanitize::stripHtmlTags($firstname),
':LastName'=>Sanitize::stripHtmlTags($lastname),
':email'=>Sanitize::emailAddress($email),
':groupid'=>$newgroupid));
} else {
$rights = 10;
$query = "INSERT INTO imas_users (SID,password,rights,FirstName,LastName,email,msgnotify) VALUES ";
$query .= '(:SID,:password,:rights,:FirstName,:LastName,:email,0)';
$stm = $DBH->prepare($query);
$stm->execute(array(':SID'=>$_POST['SID'], ':password'=>$md5pw,':rights'=>$rights,
':FirstName'=>Sanitize::stripHtmlTags($firstname),
':LastName'=>Sanitize::stripHtmlTags($lastname),
':email'=>Sanitize::emailAddress($email)));
}
$userid = $DBH->lastInsertId(); //DB $userid = mysql_insert_id();
if ($rights>=20) {
//log new account
$stm = $DBH->prepare("INSERT INTO imas_log (time, log) VALUES (:now, :log)");
$stm->execute(array(':now'=>$now, ':log'=>"New Instructor Request: $userid:: Group: $newgroupid, added via LTI"));
$reqdata = array('added'=>$now, 'actions'=>array(array('on'=>$now, 'status'=>11, 'via'=>'LTI')));
$stm = $DBH->prepare("INSERT INTO imas_instr_acct_reqs (userid,status,reqdate,reqdata) VALUES (?,11,?,?)");
$stm->execute(array($newuserid, $now, json_encode($reqdata)));
}
}
$stm = $DBH->prepare('UPDATE imas_ltiusers SET userid=:userid WHERE id=:localltiuser');
$stm->execute(array(':userid'=>$userid, ':localltiuser'=>$localltiuser));
$DBH->commit();
} else {
////create form asking them for user info
$askforuserinfo = true;
$_SESSION['LMSfirstname'] = $_REQUEST['lis_person_name_given'] ?? '';
$_SESSION['LMSlastname'] = $_REQUEST['lis_person_name_family'] ?? '';
if (!empty($_REQUEST['lis_person_contact_email_primary'])) {
$_SESSION['LMSemail'] = $_REQUEST['lis_person_contact_email_primary'];
}
}
}
$_SESSION['lti_key'] = $ltikey;
}
//Do we need to ask for student's info?
//either first connect or bad info on first submit
if ($askforuserinfo == true) {
if (!empty($_REQUEST['tool_consumer_instance_description'])) {
$_SESSION['ltiorgname'] = $_REQUEST['tool_consumer_instance_description'];
}
header('Location: ' . $GLOBALS['basesiteurl'] . "/bltilaunch.php?userinfo=ask");
exit;
}
//if here, we know the local userid.
//call hook, if defined
if (function_exists('onHaveLocalUser')) {
onHaveLocalUser($userid);
}
//if it's a common catridge placement and we're here, then either we're using domain credentials, or
//course credentials for a non-source course.
//see if lti_courses is created
// if not, see if source cid is instructors course
// if so, give option to copy or set lti_course
// if not, create a course copy
//
//see if courseid==source course cid
// if not, copy assessment if needed into course, set placement
// if so, set placement
//determine request type, and check availability
$now = time();
//general placement or common catridge placement - look for placement, or create if know info
$orgparts = explode(':',$_SESSION['ltiorg']); //THIS was added to avoid issues when GUID change, while still storing it
$shortorg = $orgparts[0];
$query = "SELECT placementtype,typeid FROM imas_lti_placements WHERE ";
$query .= "contextid=:contextid AND linkid=:linkid AND typeid>0 AND org LIKE :org";
$stm = $DBH->prepare($query);
$stm->execute(array(':contextid'=>$_SESSION['lti_context_id'], ':linkid'=>$_SESSION['lti_resource_link_id'], ':org'=>"$shortorg:%"));
if ($stm->rowCount()==0) {
if (isset($_SESSION['place_aid'])) {
$stm = $DBH->prepare('SELECT courseid,name FROM imas_assessments WHERE id=:aid');
$stm->execute(array(':aid'=>$_SESSION['place_aid']));
$row = $stm->fetch(PDO::FETCH_NUM);
if ($row===false) {
$aidsourcecid = -1; // assessment doesn't exist anymore
$aidsourcename = '';
} else {
list($aidsourcecid,$aidsourcename) = $row;
}
//look to see if we've already linked this context_id with a course
$stm = $DBH->prepare('SELECT courseid,copiedfrom FROM imas_lti_courses WHERE contextid=:contextid AND org LIKE :org');
$stm->execute(array(':contextid'=>$_SESSION['lti_context_id'], ':org'=>"$shortorg:%"));
if ($stm->rowCount()==0) {
if ($aidsourcecid == -1) { // not enough info to proceed
$diaginfo = "(Debug info: 2a-{$_SESSION['place_aid']})";
reporterror(_("The originally linked assignment does not appear to exist anymore.")." $diaginfo");
}
//if instructor, see if the source course is ours
/***TODO: check rights to see if they have course creation rights or not */
if ($_SESSION['ltirole']=='instructor') {
$copycourse = "notify";
$stm = $DBH->prepare('SELECT id FROM imas_teachers WHERE courseid=:aidsourcecid AND userid=:userid');
$stm->execute(array(':aidsourcecid'=>$aidsourcecid, ':userid'=>$userid));
if ($stm->rowCount()>0) {
$copycourse="ask";
if (isset($_POST['docoursecopy']) && $_POST['docoursecopy']=="useexisting") {
$destcid = $aidsourcecid;
$copycourse = "no";
$ltilog = ['copy'=>'useorig', 'cid'=>$destcid];
}
}
$stm = $DBH->prepare('SELECT jsondata,UIver FROM imas_courses WHERE id=:aidsourcecid');
$stm->execute(array(':aidsourcecid'=>$aidsourcecid));
list($aidsourcejsondata,$sourceUIver) = $stm->fetch(PDO::FETCH_NUM);
if ($aidsourcejsondata!==null) {
$aidsourcejsondata = json_decode($aidsourcejsondata, true);
}
$blockLTICopyOfCopies = ($aidsourcejsondata!==null && !empty($aidsourcejsondata['blockLTICopyOfCopies']));
if (isset($_POST['docoursecopy']) && $_POST['docoursecopy']=="useother" && !empty($_POST['useothercoursecid'])) {
$destcid = $_POST['useothercoursecid'];
$copycourse = "no";
$ltilog = ['copy'=>'useother', 'cid'=>$destcid];
} else if (isset($_POST['docoursecopy']) && $_POST['docoursecopy']=="makecopy") {
$copycourse = "yes";
$sourcecid = $aidsourcecid;
$ltilog = ['copy'=>'copyorig', 'cid'=>$sourcecid];
} else if (isset($_POST['docoursecopy']) && $_POST['docoursecopy']=="copyother" && $_POST['othercoursecid']>0) {
$copycourse = "yes";
$sourcecid = Sanitize::onlyInt($_POST['othercoursecid']);
$ltilog = ['copy'=>'copyother', 'cid'=>$sourcecid];
}
if ($copycourse=="notify" || $copycourse=="ask") {
$_SESSION['userid'] = $userid; //remember me
$nologo = true;
$flexwidth = true;
$placeinhead = '<style type="text/css"> ul.nomark {margin-left: 20px;} ul.nomark li {text-indent: -20px;}</style>';
require_once "header.php";
$query = "SELECT DISTINCT ic.id,ic.name FROM imas_courses AS ic JOIN imas_teachers AS imt ON ic.id=imt.courseid ";
$query .= "AND imt.userid=:userid JOIN imas_assessments AS ia ON ic.id=ia.courseid ";
$query .= "WHERE ic.available<4 AND ic.ancestors REGEXP :cregex AND ia.ancestors REGEXP :aregex ORDER BY ic.name";
$stm = $DBH->prepare($query);
$stm->execute(array(
':userid'=>$userid,
':cregex'=>MYSQL_LEFT_WRDBND.$aidsourcecid.MYSQL_RIGHT_WRDBND,
':aregex'=>MYSQL_LEFT_WRDBND.$_SESSION['place_aid'].MYSQL_RIGHT_WRDBND));
$othercourses = array();
while ($row = $stm->fetch(PDO::FETCH_NUM)) {
$othercourses[$row[0]] = $row[1];
}
$advuseother = '';
if (count($othercourses)>0) {
$advuseother .= '<li><a class="small" style="margin-left:20px;" href="#" onclick="$(this).hide().next(\'span\').show();return false;">Show advanced options</a> ';
$advuseother .= '<span style="display:none;"><input name="docoursecopy" type="radio" value="useother" />';
$advuseother .= 'Associate this LMS course with an existing course: ';
$advuseother .= '<select name="useothercoursecid">';
foreach ($othercourses as $k=>$v) {
if ($k==$aidsourcecid) {continue;}
$advuseother .= '<option value="'.$k.'">'.Sanitize::encodeStringForDisplay($v.' (Course ID '.$k.')').'</option>';
}
$advuseother .= '</select>';
$advuseother .= '<br/>Using this option means students in this LMS course will show up in the Roster and Gradebook of the '.$installname.' course you associate it with.</span></li>';
}
echo "<form method=\"post\" action=\"".$imasroot."/bltilaunch.php\">";
if ($copycourse=="ask") {
echo "<p>Your LMS course is not yet associated with a course on $installname. The assignment associated with this
link is located in a $installname course you are already a teacher of (course ID $aidsourcecid).
Would you like to associate this LMS course with that $installname course? This means
that your students in your LMS course will show up in the Roster and Gradebook in that
$installname course. If you don't want to use your existing $installname course,
a copy of the $installname assignments can be made for you automatically and associated with
this LMS course.</p>
<ul class=nomark>
<li><input name=\"docoursecopy\" type=\"radio\" value=\"useexisting\" checked onclick=\"$('#usenew').hide()\" />Associate this LMS course with my existing course (ID $aidsourcecid) on $installname</li>
<li><input name=\"docoursecopy\" type=\"radio\" value=\"makecopy\" onclick=\"$('#usenew').show()\"/>Create a copy of my existing course (ID $aidsourcecid) on $installname</li>";
if (count($othercourses)>0 && !$blockLTICopyOfCopies) {
echo '<li><input name="docoursecopy" type="radio" value="copyother" onclick="$(\'#usenew\').show()" />Create a copy of another course: <select name="othercoursecid">';
foreach ($othercourses as $k=>$v) {
echo '<option value="'.$k.'">'.Sanitize::encodeStringForDisplay($v.' (Course ID '.$k.')').'</option>';
}
echo '</select></li>';
echo $advuseother;
}
echo " </ul>";
if ($sourceUIver == 1) {
if (!empty($CFG['assess_upgrade_optout'])) {
echo '<p id="usenew" style="display:none;"><input type="checkbox" name="usenewassess" value="1" checked /> Use new assessment interface (only applies if copying)</p>';
} else {
echo '<input type="hidden" name="usenewassess" value="1">';
}
}
echo "<p>The first option is best if this is your first time using this $installname course. The second option
may be preferrable if you have copied the course in your LMS and want your students records to
show in a separate $installname course.</p>
<p><input type=\"submit\" value=\"Continue\"/> (this may take a few moments - please be patient)</p>";
} else {
echo "<p>Your LMS course is not yet associated with a course on $installname. The assignment associated with this
link is located in a $installname course you are not a teacher of (course ID $aidsourcecid).
To use this content, a copy of the assignments will be made for you automatically,
and this LMS course will be associated with that copy in $installname. This will allow you to make changes to the assignments
without affecting the original course, and will ensure your student records are housed in your own
$installname course.</p>";
if (count($othercourses)>0 && !$blockLTICopyOfCopies) {