-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.php
More file actions
2090 lines (1908 loc) · 104 KB
/
index.php
File metadata and controls
2090 lines (1908 loc) · 104 KB
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
require_once "../config.php";
require_once "points-util.php";
require_once "ai-util.php";
require_once "aipaper-util.php";
use \Tsugi\Util\U;
use \Tsugi\Util\FakeName;
use \Tsugi\Core\LTIX;
use \Tsugi\Core\Settings;
use \Tsugi\Core\Result;
use \Tsugi\Util\LTI13;
use \Tsugi\UI\SettingsForm;
// No parameter means we require CONTEXT, USER, and LINK
$LAUNCH = LTIX::requireData();
$p = $CFG->dbprefix;
// If settings were updated
if ( SettingsForm::handleSettingsPost() ) {
$_SESSION["success"] = "Settings updated.";
header( 'Location: '.addSession('index.php') ) ;
return;
}
$LAUNCH->link->settingsDefaultsFromCustom(array('instructions', 'submitpoints', 'instructorpoints', 'commentpoints', 'mincomments', 'userealnames', 'allowall', 'resubmit', 'auto_timeout'));
// Grab the due date information
$dueDate = SettingsForm::getDueDate();
$user_id = U::safe_href(U::get($_GET, 'user_id'));
if ( $user_id && ! $LAUNCH->user->instructor ) {
http_response_code(403);
die('Not authorized');
}
if ( ! $user_id ) $user_id = $LAUNCH->user->id;
$inst_note = $LAUNCH->result->getNote($user_id);
// Get result_id for this user
$result_id = $RESULT->id;
if ( ! $result_id ) {
$_SESSION['error'] = 'No result record found';
header( 'Location: '.addSession('index.php') ) ;
return;
}
// Load or create aipaper_result record
$paper_row = $PDOX->rowDie(
"SELECT raw_submission, ai_enhanced_submission, submitted, flagged, flagged_by, json, updated_at, instructor_points
FROM {$p}aipaper_result WHERE result_id = :RID",
array(':RID' => $result_id)
);
if ( $paper_row === false ) {
// Create new record
$PDOX->queryDie(
"INSERT INTO {$p}aipaper_result (result_id, created_at) VALUES (:RID, NOW())",
array(':RID' => $result_id)
);
$paper_row = array(
'raw_submission' => '',
'ai_enhanced_submission' => '',
'submitted' => false,
'flagged' => false,
'flagged_by' => null,
'json' => null
);
}
// Check submission status from submitted column (MySQL returns 0/1, not boolean)
$is_submitted = isset($paper_row['submitted']) && ($paper_row['submitted'] == true || $paper_row['submitted'] == 1);
// Check if resubmit is allowed
$resubmit_allowed = Settings::linkGet('resubmit', false);
// Can edit only if not submitted (or if instructor)
// Resubmit setting only controls Reset button visibility, not editability
$can_edit = !$is_submitted || $USER->instructor;
// Get minimum comments setting
$min_comments = Settings::linkGet('mincomments', 0);
$min_comments = intval($min_comments);
// Count how many unique submissions the current user has reviewed (for students only)
$reviewed_count = 0;
$total_comments_made = 0;
if ( !$USER->instructor ) {
$reviewed_row = $PDOX->rowDie(
"SELECT COUNT(DISTINCT result_id) as cnt
FROM {$p}aipaper_comment
WHERE user_id = :UID",
array(':UID' => $USER->id)
);
$reviewed_count = $reviewed_row ? intval($reviewed_row['cnt']) : 0;
// Count total comments made by this student (for points calculation)
$total_comments_row = $PDOX->rowDie(
"SELECT COUNT(*) as cnt
FROM {$p}aipaper_comment
WHERE user_id = :UID",
array(':UID' => $USER->id)
);
$total_comments_made = $total_comments_row ? intval($total_comments_row['cnt']) : 0;
}
// Auto-grade logic: Send grade of 1.0 after timeout if overall_points > 0
// This ensures students get full credit even if they can't complete enough reviews
if ( !$USER->instructor && $is_submitted ) {
$auto_timeout = Settings::linkGet('auto_instructor_grade_timeout', 0);
$auto_timeout = intval($auto_timeout);
// Calculate overall_points to check if auto-grading should apply
$instructor_points = Settings::linkGet('instructorpoints', 0);
$instructor_points = intval($instructor_points);
$submit_points = Settings::linkGet('submitpoints', 0);
$submit_points = intval($submit_points);
$comment_points = Settings::linkGet('commentpoints', 0);
$comment_points = intval($comment_points);
$min_comments = Settings::linkGet('mincomments', 0);
$min_comments = intval($min_comments);
$overall_points = $instructor_points + $submit_points + ($comment_points * $min_comments);
// Only check if overall_points > 0 and timeout is set
if ( $overall_points > 0 && $auto_timeout > 0 ) {
// Get submission timestamp
$submission_timestamp = isset($paper_row['updated_at']) ? strtotime($paper_row['updated_at']) : null;
if ( $submission_timestamp ) {
$current_timestamp = time();
$seconds_since_submission = $current_timestamp - $submission_timestamp;
// If timeout has passed, send grade of 1.0 (100%) regardless of instructor grading
// This ensures students get credit even if they can't complete enough reviews
if ( $seconds_since_submission >= $auto_timeout ) {
// Send grade of 1.0 directly to LTI
$result = Result::lookupResultBypass($USER->id);
$result['grade'] = -1; // Force resend
$debug_log = array();
$extra13 = array(
LTI13::ACTIVITY_PROGRESS => LTI13::ACTIVITY_PROGRESS_COMPLETED,
LTI13::GRADING_PROGRESS => LTI13::GRADING_PROGRESS_FULLYGRADED,
);
$LAUNCH->result->gradeSend(1.0, $result, $debug_log, $extra13);
}
}
}
}
// Calculate overall_points and earned_points using shared function
$points_data = calculatePoints($USER->id, $LAUNCH->link->id, $result_id);
$earned_points = $points_data['earned_points'];
$overall_points = $points_data['overall_points'];
// Send grade to LTI whenever student views the page (if they can see points)
if ( !$USER->instructor && $overall_points > 0 ) {
sendGradeToLTI($USER->id, $earned_points, $overall_points);
}
// Load submissions for review (only if student has submitted)
$review_submissions = array();
$review_page = 1;
$total_review_pages = 0;
if ( $is_submitted && !$USER->instructor ) {
// Get allowall setting - if min_comments is 0, allowall is effectively true
$allowall_setting = Settings::linkGet('allowall', false);
$allowall = ($min_comments == 0) ? true : $allowall_setting;
// Get page number
$review_page = isset($_GET['review_page']) ? max(1, intval($_GET['review_page'])) : 1;
$items_per_page = 10;
$offset = ($review_page - 1) * $items_per_page;
// First, get all submitted results from other students
$all_submissions = $PDOX->allRowsDie(
"SELECT r.result_id, r.user_id, r.created_at,
u.displayname, u.email,
ar.raw_submission, ar.ai_enhanced_submission, ar.json
FROM {$p}lti_result r
INNER JOIN {$p}lti_user u ON r.user_id = u.user_id
INNER JOIN {$p}aipaper_result ar ON r.result_id = ar.result_id
WHERE r.link_id = :LID
AND r.user_id != :MY_USER_ID
AND ar.submitted = true",
array(
':LID' => $LAUNCH->link->id,
':MY_USER_ID' => $USER->id
)
);
// Count comments for each submission (by current user)
$use_real_names = Settings::linkGet('userealnames', false);
$submissions_with_counts = array();
foreach ( $all_submissions as $sub_row ) {
// Count how many comments current user has made on this submission
$my_comment_count = $PDOX->rowDie(
"SELECT COUNT(*) as cnt
FROM {$p}aipaper_comment
WHERE result_id = :RID AND user_id = :MY_USER_ID",
array(
':RID' => $sub_row['result_id'],
':MY_USER_ID' => $USER->id
)
);
$my_comments = $my_comment_count ? intval($my_comment_count['cnt']) : 0;
// Filter logic:
// - If min_comments == 0: show all submissions
// - If reviewed_count < min_comments: only show submissions where user hasn't reached min_comments (to help reach minimum)
// BUT always include submissions user has already commented on (my_comments >= 1)
// - If reviewed_count >= min_comments and allowall is checked: show all submissions
// - If reviewed_count >= min_comments and allowall is not checked: only show submissions user has already reviewed (my_comments >= 1)
$should_include = false;
if ( $min_comments == 0 ) {
$should_include = true;
} else if ( $reviewed_count < $min_comments ) {
// User is working toward minimum
// Always show submissions they've already commented on, OR submissions that help them reach minimum
$should_include = ($my_comments >= 1) || ($my_comments < $min_comments);
} else if ( $reviewed_count >= $min_comments && $allowall ) {
// User has met minimum and allowall is checked - show all submissions
$should_include = true;
} else if ( $reviewed_count >= $min_comments && !$allowall ) {
// User has met minimum but allowall is not checked - only show submissions they've already reviewed
$should_include = ($my_comments >= 1);
} else {
// Default: only show submissions where user hasn't reached min_comments
$should_include = ($my_comments < $min_comments);
}
if ( $should_include ) {
$submissions_with_counts[] = array(
'result_id' => $sub_row['result_id'],
'user_id' => $sub_row['user_id'],
'display_name' => $use_real_names && !empty($sub_row['displayname'])
? $sub_row['displayname']
: FakeName::getName($sub_row['user_id']),
'raw_submission' => $sub_row['raw_submission'],
'ai_enhanced_submission' => $sub_row['ai_enhanced_submission'],
'comment_count' => $my_comments,
'submission_date' => $sub_row['created_at']
);
}
}
// Sort: submissions where current user has >= 1 comment first, then by oldest submission, then by comment count
usort($submissions_with_counts, function($a, $b) {
// Prioritize submissions where current user has made >= 1 comment
$a_has_comments = $a['comment_count'] >= 1;
$b_has_comments = $b['comment_count'] >= 1;
if ( $a_has_comments && !$b_has_comments ) return -1;
if ( !$a_has_comments && $b_has_comments ) return 1;
// If both have comments or both don't, sort by oldest submission first, then by comment count
$date_cmp = strcmp($a['submission_date'], $b['submission_date']);
if ( $date_cmp != 0 ) return $date_cmp;
return $a['comment_count'] - $b['comment_count'];
});
// If allowall is not checked and min_comments > 0, limit to min_comments submissions
// But always include submissions the user has already commented on
if ( !$allowall && $min_comments > 0 ) {
// Separate submissions: ones they've started vs ones they haven't
$started = array();
$not_started = array();
foreach ( $submissions_with_counts as $sub ) {
if ( $sub['comment_count'] >= 1 ) {
$started[] = $sub;
} else {
$not_started[] = $sub;
}
}
// Combine: all started ones + enough not_started to reach min_comments total
$max_to_show = max($min_comments, count($started));
$needed_from_not_started = max(0, $max_to_show - count($started));
$submissions_with_counts = array_merge($started, array_slice($not_started, 0, $needed_from_not_started));
}
// Paginate
$total_review_count = count($submissions_with_counts);
$total_review_pages = ceil($total_review_count / $items_per_page);
$review_submissions = array_slice($submissions_with_counts, $offset, $items_per_page);
}
// Load comments for this submission (if submitted)
$comments = array();
if ( $is_submitted ) {
$use_real_names = Settings::linkGet('userealnames', false);
// For students, hide soft-deleted comments. For instructors, show them with indication.
$deleted_filter = $USER->instructor ? '' : 'AND c.deleted = 0';
$comment_rows = $PDOX->allRowsDie(
"SELECT c.comment_id, c.comment_text, c.comment_type, c.created_at, c.user_id, c.deleted,
c.flagged, c.flagged_by,
u.displayname, u.email
FROM {$p}aipaper_comment c
LEFT JOIN {$p}lti_user u ON c.user_id = u.user_id
WHERE c.result_id = :RID $deleted_filter
ORDER BY c.created_at DESC",
array(':RID' => $result_id)
);
foreach ( $comment_rows as $comment_row ) {
$comment = array(
'comment_id' => $comment_row['comment_id'],
'comment_text' => $comment_row['comment_text'],
'comment_type' => $comment_row['comment_type'],
'created_at' => $comment_row['created_at'],
'user_id' => $comment_row['user_id'],
'deleted' => isset($comment_row['deleted']) && ($comment_row['deleted'] == 1 || $comment_row['deleted'] == true),
'flagged' => isset($comment_row['flagged']) && ($comment_row['flagged'] == 1 || $comment_row['flagged'] == true)
);
// Get display name based on comment type and settings
if ( $comment_row['comment_type'] == 'AI' ) {
$comment['display_name'] = 'AI';
} else if ( $comment_row['comment_type'] == 'instructor' ) {
$comment['display_name'] = 'Staff';
} else {
// Student comment
if ( $use_real_names && !empty($comment_row['displayname']) ) {
$comment['display_name'] = $comment_row['displayname'];
} else {
$comment['display_name'] = FakeName::getName($comment_row['user_id']);
}
}
$comments[] = $comment;
}
}
// Load instructions from settings
$instructions = Settings::linkGet('instructions', '');
// Load current settings values for instructor (to check if defaults needed)
$current_submitpoints = Settings::linkGet('submitpoints', '');
$current_instructorpoints = Settings::linkGet('instructorpoints', '');
$current_commentpoints = Settings::linkGet('commentpoints', '');
$current_mincomments = Settings::linkGet('mincomments', '');
$current_userealnames = Settings::linkGet('userealnames', false);
$current_allowall = Settings::linkGet('allowall', false);
$current_resubmit = Settings::linkGet('resubmit', false);
$current_ai_api_url = Settings::linkGet('ai_api_url', '');
$current_ai_api_key = Settings::linkGet('ai_api_key', '');
$current_auto_timeout = Settings::linkGet('auto_instructor_grade_timeout', '');
// Convert seconds to days and hours for display
$auto_timeout_days = 0;
$auto_timeout_hours = 0;
if ( !empty($current_auto_timeout) && is_numeric($current_auto_timeout) ) {
$total_seconds = intval($current_auto_timeout);
$auto_timeout_days = floor($total_seconds / 86400); // 86400 seconds per day
$auto_timeout_hours = floor(($total_seconds % 86400) / 3600); // 3600 seconds per hour
}
// Determine if settings need defaults (all point values empty)
$needs_defaults = empty($current_submitpoints) && empty($current_instructorpoints) &&
empty($current_commentpoints) && empty($current_mincomments);
// Determine if instructions will be truncated in preview (for students)
$instructions_will_be_truncated = false;
if ( !$USER->instructor && is_string($instructions) && U::strlen($instructions) > 0 ) {
$instructions_plain = strip_tags($instructions);
// Check if likely to be truncated: > 300 chars OR has multiple paragraphs
if ( strlen($instructions_plain) > 300 ) {
$instructions_will_be_truncated = true;
} else {
// Check for multiple paragraphs in HTML
if ( preg_match('/<p[^>]*>.*?<\/p>/s', $instructions) ) {
preg_match_all('/<p[^>]*>.*?<\/p>/s', $instructions, $matches);
if ( count($matches[0]) > 1 ) {
$instructions_will_be_truncated = true;
}
}
}
}
// Load AI prompt from settings (per link)
$ai_prompt = Settings::linkGet('ai_prompt', '');
// Handle toggle comment (soft delete/un-delete)
if ( count($_POST) > 0 && isset($_POST['toggle_comment']) && $USER->instructor ) {
$comment_id = intval($_POST['toggle_comment']);
$new_deleted = intval($_POST['comment_deleted']);
// Verify comment exists and belongs to this link
$comment_check = $PDOX->rowDie(
"SELECT c.comment_id
FROM {$p}aipaper_comment c
INNER JOIN {$p}lti_result r ON c.result_id = r.result_id
WHERE c.comment_id = :CID AND r.link_id = :LID",
array(':CID' => $comment_id, ':LID' => $LAUNCH->link->id)
);
if ( $comment_check ) {
$PDOX->queryDie(
"UPDATE {$p}aipaper_comment
SET deleted = :DELETED, updated_at = NOW()
WHERE comment_id = :CID",
array(':DELETED' => $new_deleted, ':CID' => $comment_id)
);
$_SESSION['success'] = $new_deleted ? 'Comment hidden' : 'Comment shown';
} else {
$_SESSION['error'] = 'Comment not found';
}
header( 'Location: '.addSession('index.php') ) ;
return;
}
// Handle reset submission (check before flag to avoid interference)
if ( count($_POST) > 0 && isset($_POST['reset_submission']) ) {
// Allow reset if instructor, or if resubmit is allowed, or if submission has been submitted
// (Since the button only shows when submitted, this check ensures reset is allowed)
if ( !$USER->instructor && !$resubmit_allowed && !$is_submitted ) {
$_SESSION['error'] = 'Reset not allowed';
header( 'Location: '.addSession('index.php') ) ;
return;
}
// Reset submission status (keep content, just make it editable again)
// Reset submitted column but keep all content (paper, AI enhanced, comments)
// Soft delete all comments on this submission
$PDOX->queryDie(
"UPDATE {$p}aipaper_result
SET submitted = false, updated_at = NOW()
WHERE result_id = :RID",
array(
':RID' => $result_id
)
);
// Soft delete all comments on this submission (for points calculation, but hidden from students)
$PDOX->queryDie(
"UPDATE {$p}aipaper_comment
SET deleted = 1, updated_at = NOW()
WHERE result_id = :RID",
array(
':RID' => $result_id
)
);
$_SESSION['success'] = 'Submission has been reset. Your paper and AI enhanced content are now editable again.';
header( 'Location: '.addSession('index.php') ) ;
return;
}
// Handle toggle flag (anyone can flag and unflag)
if ( count($_POST) > 0 && isset($_POST['toggle_flag']) ) {
$comment_id = intval($_POST['toggle_flag']);
$new_flagged = intval($_POST['comment_flagged']);
// Verify comment exists and belongs to this link
$comment_check = $PDOX->rowDie(
"SELECT c.comment_id, c.flagged, c.flagged_by
FROM {$p}aipaper_comment c
INNER JOIN {$p}lti_result r ON c.result_id = r.result_id
WHERE c.comment_id = :CID AND r.link_id = :LID",
array(':CID' => $comment_id, ':LID' => $LAUNCH->link->id)
);
if ( $comment_check ) {
// Anyone can flag and unflag
$flagged_by = $new_flagged == 1 ? $USER->id : null;
$PDOX->queryDie(
"UPDATE {$p}aipaper_comment
SET flagged = :FLAGGED, flagged_by = :FLAGGED_BY, updated_at = NOW()
WHERE comment_id = :CID",
array(
':FLAGGED' => $new_flagged,
':FLAGGED_BY' => $flagged_by,
':CID' => $comment_id
)
);
// No flash message - visual feedback (icon color change) is sufficient
} else {
$_SESSION['error'] = 'Comment not found';
}
header( 'Location: '.addSession('index.php') ) ;
return;
}
if ( count($_POST) > 0 && isset($_POST['reset_submission']) ) {
// Allow reset if instructor, or if resubmit is allowed, or if submission has been submitted
// (Since the button only shows when submitted, this check ensures reset is allowed)
if ( !$USER->instructor && !$resubmit_allowed && !$is_submitted ) {
$_SESSION['error'] = 'Reset not allowed';
header( 'Location: '.addSession('index.php') ) ;
return;
}
// Reset submission status (keep content, just make it editable again)
// Reset submitted column but keep all content (paper, AI enhanced, comments)
// Soft delete all comments on this submission
$PDOX->queryDie(
"UPDATE {$p}aipaper_result
SET submitted = false, updated_at = NOW()
WHERE result_id = :RID",
array(
':RID' => $result_id
)
);
// Soft delete all comments on this submission (for points calculation, but hidden from students)
$PDOX->queryDie(
"UPDATE {$p}aipaper_comment
SET deleted = 1, updated_at = NOW()
WHERE result_id = :RID",
array(
':RID' => $result_id
)
);
$_SESSION['success'] = 'Submission has been reset. Your paper and AI enhanced content are now editable again.';
header( 'Location: '.addSession('index.php') ) ;
return;
}
// Handle POST submission
if ( count($_POST) > 0 && (isset($_POST['submit_paper']) || isset($_POST['save_paper']) || isset($_POST['save_instructions'])) ) {
$is_submit = isset($_POST['submit_paper']);
if ( !$can_edit && !$USER->instructor ) {
$_SESSION['error'] = 'Submission is locked';
header( 'Location: '.addSession('index.php') ) ;
return;
}
$raw_submission = U::get($_POST, 'raw_submission', '');
$ai_enhanced = U::get($_POST, 'ai_enhanced_submission', '');
// Validate that paper is not blank when submitting (not when saving draft)
if ( $is_submit && !$USER->instructor && U::isEmpty($raw_submission) ) {
$_SESSION['error'] = 'Your paper cannot be blank. Please write your paper before submitting.';
header( 'Location: '.addSession('index.php') ) ;
return;
}
// For instructors, save instructions, AI prompt, and all settings
if ( $USER->instructor ) {
$instructions = U::get($_POST, 'instructions', '');
Settings::linkSet('instructions', $instructions);
// Save AI prompt to settings
$ai_prompt = U::get($_POST, 'ai_prompt', '');
// If AI prompt is blank, reset to default
if ( empty(trim(strip_tags($ai_prompt))) ) {
// Create default prompt with HTML formatting (for CKEditor)
$ai_prompt = "<p>You are reviewing a student's paper submission.</p>\n\n<p>Provide a brief paragraph (approximately 200 words or less) with specific, actionable feedback. Focus on:</p>\n<ul>\n<li>Strengths of the submission</li>\n<li>Areas for improvement</li>\n<li>Specific suggestions for revision</li>\n</ul>\n\n<p>Be encouraging but honest, and reference specific parts of the paper when possible.</p>\n\n<p>The following are the instructions for the assignment:</p>\n\n<p>-- Instructions Included Here --</p>\n\n";
}
Settings::linkSet('ai_prompt', $ai_prompt);
// Save all settings fields
Settings::linkSet('submitpoints', U::get($_POST, 'submitpoints', ''));
Settings::linkSet('instructorpoints', U::get($_POST, 'instructorpoints', ''));
Settings::linkSet('commentpoints', U::get($_POST, 'commentpoints', ''));
Settings::linkSet('mincomments', U::get($_POST, 'mincomments', ''));
Settings::linkSet('userealnames', U::get($_POST, 'userealnames', false) ? true : false);
Settings::linkSet('allowall', U::get($_POST, 'allowall', false) ? true : false);
Settings::linkSet('resubmit', U::get($_POST, 'resubmit', false) ? true : false);
Settings::linkSet('ai_api_url', U::get($_POST, 'ai_api_url', ''));
Settings::linkSet('ai_api_key', U::get($_POST, 'ai_api_key', ''));
Settings::linkSet('auto_instructor_grade_timeout', U::get($_POST, 'auto_instructor_grade_timeout', ''));
// Save due date
$due_date = U::get($_POST, 'due_date', '');
if ( !empty($due_date) ) {
Settings::linkSet('due_date', $due_date);
} else {
Settings::linkSet('due_date', '');
}
}
// Check if was already submitted (MySQL returns 0/1, not boolean)
$was_submitted = isset($paper_row['submitted']) && ($paper_row['submitted'] == true || $paper_row['submitted'] == 1);
// Mark as submitted only if Submit button was clicked (not Save)
$new_submitted = $was_submitted;
if ( $is_submit && !$was_submitted && U::isNotEmpty($raw_submission) ) {
$new_submitted = true;
$RESULT->notifyReadyToGrade();
}
// Update aipaper_result
$PDOX->queryDie(
"UPDATE {$p}aipaper_result
SET raw_submission = :RAW, ai_enhanced_submission = :AI,
submitted = :SUBMITTED, updated_at = NOW()
WHERE result_id = :RID",
array(
':RAW' => $raw_submission,
':AI' => $ai_enhanced,
':SUBMITTED' => $new_submitted ? 1 : 0,
':RID' => $result_id
)
);
// Set success message first (before AI processing)
if ( $USER->instructor ) {
$_SESSION['success'] = 'Instructions updated';
} else {
if ( $is_submit ) {
$success_msg = 'Paper submitted';
if ( $resubmit_allowed ) {
$success_msg .= '. You can reset your submission if you need to make changes.';
} else {
$success_msg .= '. Your submission is now locked and cannot be edited.';
}
$_SESSION['success'] = $success_msg;
} else {
$_SESSION['success'] = 'Draft saved';
}
}
// Generate AI comment if paper was just submitted (first time or resubmission)
// Note: On resubmission, previous comments (including AI) are soft-deleted, so we need a new AI comment
// Generate whenever Submit button is clicked (not Save) and paper is not empty
if ( $is_submit && U::isNotEmpty($raw_submission) ) {
// Use AI prompt if set, otherwise fall back to instructions
$instructions = Settings::linkGet('instructions', '');
$prompt_to_use = $instructions;
$ai_prompt = Settings::linkGet('ai_prompt', '');
if ( !empty($ai_prompt) ) {
$prompt_to_use = $ai_prompt;
// Replace placeholder with actual instructions
// Use regex to find the placeholder in various HTML contexts and preserve formatting
// Match the placeholder text regardless of surrounding HTML tags
$placeholder_pattern = '/--\s*Instructions\s+Included\s+Here\s*--/i';
// Find all matches and replace, preserving the HTML structure around it
$prompt_to_use = preg_replace($placeholder_pattern, $instructions, $prompt_to_use);
} else {
// Fallback to instructions if no AI prompt is set
$prompt_to_use = $instructions;
}
$api_info = getAIApiUrl();
// Only generate AI comment if AI is configured
if ( $api_info['configured'] ) {
// Pass URL if available, otherwise let function use test endpoint
$ai_result = generateAIComment($prompt_to_use, $raw_submission, $api_info['url']);
if ( $ai_result['success'] ) {
// Insert AI comment (user_id is NULL for AI comments)
$PDOX->queryDie(
"INSERT INTO {$p}aipaper_comment (result_id, user_id, comment_text, comment_type, created_at)
VALUES (:RID, NULL, :TEXT, 'AI', NOW())",
array(
':RID' => $result_id,
':TEXT' => $ai_result['comment']
)
);
$user_id = $LAUNCH->user->id ?? 'unknown';
$user_email = $LAUNCH->user->email ?? 'unknown';
error_log("AI Comment: Comment successfully added to database - result_id: {$result_id}, user_id: {$user_id}, email: {$user_email}, comment_length: " . strlen($ai_result['comment']));
// Send notification to the paper owner about the AI comment
$paper_owner_user_id = $USER->id; // The current user owns this paper
$notification_url = null;
if ( is_object($LAUNCH) && method_exists($LAUNCH, 'returnUrl') ) {
$notification_url = $LAUNCH->returnUrl();
}
if ( empty($notification_url) ) {
$notification_url = addSession('index');
}
// Get assignment title from link title
$assignment_title = $LINK->title ?? null;
notifyCommentAdded($paper_owner_user_id, 'AI', $assignment_title, $notification_url);
} else {
// Log error to server logs
$user_id = $LAUNCH->user->id ?? 'unknown';
$error_message = $ai_result['error'] ?? 'Unknown error';
$error_log_entry = "AI Comment: Generation failed - result_id: {$result_id}, user_id: {$user_id}, error: {$error_message}";
if ( isset($ai_result['error_log']) ) {
$error_log_entry .= "\nFull error log: " . $ai_result['error_log'];
}
error_log($error_log_entry);
// Store error details for console.log (will be output in JavaScript)
$error_for_console = array(
'message' => 'Unable to contact AI for review',
'error' => $error_message,
'error_log' => $ai_result['error_log'] ?? null
);
$_SESSION['ai_error_console'] = json_encode($error_for_console);
// Show error message to user
$_SESSION['error'] = 'Unable to contact AI for review. Check browser console for details.';
}
}
}
header( 'Location: '.addSession('index.php') ) ;
return;
}
$menu = new \Tsugi\UI\MenuSet();
if ( $LAUNCH->user->instructor ) {
$menu->addLeft(__('Instructions'), '#', /* push */ false, 'class="tsugi-nav-link" data-section="instructions" role="tab" aria-controls="section-instructions" style="cursor: pointer;"');
$menu->addLeft(__('Settings'), '#', /* push */ false, 'class="tsugi-nav-link" data-section="settings" role="tab" aria-controls="section-settings" style="cursor: pointer;"');
// Only show AI Prompt if AI is configured
if ( isAIConfigured() ) {
$menu->addLeft(__('AI Prompt'), '#', /* push */ false, 'class="tsugi-nav-link" data-section="ai_prompt" role="tab" aria-controls="section-ai_prompt" style="cursor: pointer;"');
}
$submenu = new \Tsugi\UI\Menu();
$submenu->addLink(__('Student Data'), 'grades');
if ( $CFG->launchactivity ) {
$submenu->addLink(__('Analytics'), 'analytics');
}
// Only show test data generator if key is '12345'
$key = $LAUNCH->key->key ?? '';
if ( $key === '12345' ) {
$submenu->addLink(__('Generate Test Data'), 'testdata.php');
}
$menu->addRight(__('Save'), '#', /* push */ false, 'id="menu-save-instructor-btn" style="cursor: pointer; font-weight: bold;"');
$menu->addRight(__('Documentation'), 'documentation.html', /* push */ false, 'target="_blank" rel="noopener noreferrer" aria-label="'.htmlspecialchars(__('Open documentation in new tab'), ENT_QUOTES, 'UTF-8').'"');
$menu->addRight(__('Instructor'), $submenu, /* push */ false);
} else {
// Add navigation items to menu
if ( !$is_submitted ) {
// When not submitted: Paper, Paper+AI, Instructions (if truncated) on left; Save Draft, Submit Paper on right
$menu->addLeft(__('Paper'), '#', /* push */ false, 'class="tsugi-nav-link" data-section="submission" style="cursor: pointer;"');
$menu->addLeft(__('Paper+AI'), '#', /* push */ false, 'class="tsugi-nav-link" data-section="ai_enhanced" style="cursor: pointer;"');
// Only show Instructions tab if instructions will be truncated
if ( $instructions_will_be_truncated ) {
$menu->addLeft(__('Instructions'), '#', /* push */ false, 'class="tsugi-nav-link" data-section="instructions" style="cursor: pointer;"');
}
// Show Peer Review menu item (disabled) if peer reviews are required
if ( $min_comments > 0 ) {
$menu->addLeft(__('Peer Review'), '#', /* push */ false, 'class="tsugi-nav-link" style="cursor: not-allowed; color: #999; opacity: 0.6;" title="Available after you submit your paper"');
}
// Add Save and Submit buttons to menu if student can edit
if ( $can_edit ) {
$menu->addRight(__('Save Draft'), '#', /* push */ false, 'id="menu-save-btn" style="cursor: pointer;"');
$submit_text = __('Submit Paper');
$menu->addRight($submit_text, '#', /* push */ false, 'id="menu-submit-btn" style="cursor: pointer; font-weight: bold;"');
}
} else {
// When submitted: Main, Instructions (if truncated), Peer Review on left
$menu->addLeft(__('Main'), '#', /* push */ false, 'class="tsugi-nav-link" data-section="main" style="cursor: pointer;"');
// Only show Instructions tab if instructions were truncated
if ( $instructions_will_be_truncated ) {
$menu->addLeft(__('Instructions'), '#', /* push */ false, 'class="tsugi-nav-link" data-section="instructions" style="cursor: pointer;"');
}
$menu->addLeft(__('Peer Review'), '#', /* push */ false, 'class="tsugi-nav-link" data-section="review" style="cursor: pointer;" title="Review and comment on other students\' submissions"');
}
if ( U::strlen($inst_note) > 0 ) $menu->addRight(__('Note'), '#', /* push */ false, 'data-toggle="modal" data-target="#noteModal"');
// Add Reset Submission button if submitted and resubmit is allowed
if ( $is_submitted && $resubmit_allowed ) {
$menu->addRight(__('Reset Submission'), '#', /* push */ false, 'id="menu-reset-btn" style="cursor: pointer; color: #f0ad4e;"');
}
}
// Render view
$OUTPUT->header();
$OUTPUT->bodyStart();
$OUTPUT->topNav($menu);
$OUTPUT->flashMessages();
// Student settings form (keep as modal)
if ( !$USER->instructor ) {
SettingsForm::start();
SettingsForm::checkbox('allowall', __('Allow students to see and comment on all submissions after the minimum has been met'));
SettingsForm::dueDate();
SettingsForm::done();
SettingsForm::end();
}
if ( U::strlen($inst_note) > 0 ) {
echo($OUTPUT->modalString(__("Instructor Note"), htmlentities($inst_note ?? ''), "noteModal"));
}
?>
<style>
.student-section {
display: none;
padding: 20px;
border: 1px solid #ddd;
border-radius: 4px;
min-height: 25em;
}
.student-section.active {
display: block;
}
.ckeditor-container { min-height: 25em; }
.ckeditor-display {
border: 1px solid #ddd;
border-radius: 4px;
background-color: #f9f9f9;
padding: 15px;
min-height: 10em;
}
.ckeditor-display .ck-editor__editable {
border: none;
background: transparent;
box-shadow: none;
}
.tsugi-nav-link.active {
font-weight: bold;
text-decoration: underline;
}
</style>
<?php if ( $USER->instructor ) { ?>
<!-- Instructor: Tabbed interface -->
<?php if ( $dueDate->message ) { ?>
<p style="color:red;"><?= htmlentities($dueDate->message) ?></p>
<?php } ?>
<form method="post" id="instructor_form">
<!-- Progress indicator -->
<div style="margin-bottom: 20px; padding: 15px; background-color: #f0f0f0; border-radius: 4px;">
<strong>Setup Progress:</strong>
<span style="color: #5cb85c;">Step 1: Instructions</span> →
<span style="color: <?= $needs_defaults ? '#f0ad4e' : '#5cb85c' ?>;">Step 2: Settings</span>
</div>
<!-- Instructions section -->
<div class="student-section active" id="section-instructions" role="tabpanel" aria-labelledby="heading-instructions">
<h3 id="heading-instructions" style="margin-top: 0;">Step 1: Assignment Instructions</h3>
<p>Please enter the instructions for the assignment here. This will be used to generate feedback for the students.</p>
<label for="editor_instructions" class="sr-only">Assignment instructions</label>
<div class="ckeditor-container">
<textarea name="instructions" id="editor_instructions" aria-label="Assignment instructions"><?= htmlentities($instructions ?? '') ?></textarea>
</div>
</div>
<!-- Settings section -->
<div class="student-section" id="section-settings" role="tabpanel" aria-labelledby="heading-settings" style="margin-top: 30px;">
<h3 id="heading-settings" style="margin-top: 0;">Step 2: Assignment Settings</h3>
<p>Configure how points are awarded and other assignment options. You can use the preset options below or customize manually.</p>
<!-- Assignment Type Preset Dropdown -->
<div style="margin-bottom: 25px; padding: 15px; background-color: #e8f4f8; border-radius: 4px;">
<label for="assignment_type_preset" style="font-weight: bold; display: block; margin-bottom: 8px;">
Assignment Type (Optional - select to auto-fill recommended settings):
</label>
<select id="assignment_type_preset" style="width: 100%; max-width: 500px; padding: 8px;">
<option value="">-- Select a preset (optional) --</option>
<option value="peer_review">Peer Review Focused</option>
<option value="instructor_graded">Instructor Graded</option>
<option value="completion">Completion-Based</option>
<option value="hybrid">Hybrid Peer Review + Instructor Grading</option>
<option value="anonymous">Anonymous Peer Review</option>
<option value="scaffolded">Scaffolded Peer Review</option>
</select>
<p style="margin-top: 8px; margin-bottom: 0; font-size: 0.9em; color: #666;">
<em>Selecting a preset will populate the fields below with recommended values. You can still modify them before saving.</em>
</p>
</div>
<!-- Points Settings -->
<div style="margin-bottom: 25px;">
<h4 style="border-bottom: 2px solid #ddd; padding-bottom: 8px;">Points Configuration</h4>
<div style="margin-bottom: 15px;">
<label for="submitpoints" style="font-weight: bold; display: inline-block; min-width: 200px;">
Submit Points
<span class="info-icon" data-help="submitpoints" style="cursor: help; color: #337ab7; margin-left: 5px;">ℹ️</span>
</label>
<input type="number" name="submitpoints" id="submitpoints"
value="<?= htmlentities($current_submitpoints) ?>"
placeholder=""
min="0" step="1"
style="width: 100px; padding: 5px;">
<span class="help-text" id="help-submitpoints" style="display: none; margin-left: 10px; color: #666; font-size: 0.9em;">
Points students earn for submitting their paper. Can be zero. Typical range: 10-20 points.
</span>
</div>
<div style="margin-bottom: 15px;">
<label for="instructorpoints" style="font-weight: bold; display: inline-block; min-width: 200px;">
Instructor Grade Points
<span class="info-icon" data-help="instructorpoints" style="cursor: help; color: #337ab7; margin-left: 5px;">ℹ️</span>
</label>
<input type="number" name="instructorpoints" id="instructorpoints"
value="<?= htmlentities($current_instructorpoints) ?>"
placeholder=""
min="0" step="1"
style="width: 100px; padding: 5px;">
<span class="help-text" id="help-instructorpoints" style="display: none; margin-left: 10px; color: #666; font-size: 0.9em;">
Points you will award based on your evaluation. Can be zero. Typical range: 0-80 points depending on assignment type.
</span>
</div>
<div style="margin-bottom: 15px;">
<label for="commentpoints" style="font-weight: bold; display: inline-block; min-width: 200px;">
Points per Comment
<span class="info-icon" data-help="commentpoints" style="cursor: help; color: #337ab7; margin-left: 5px;">ℹ️</span>
</label>
<input type="number" name="commentpoints" id="commentpoints"
value="<?= htmlentities($current_commentpoints) ?>"
placeholder=""
min="0" step="1"
style="width: 100px; padding: 5px;">
<span class="help-text" id="help-commentpoints" style="display: none; margin-left: 10px; color: #666; font-size: 0.9em;">
Points students earn for each peer review comment they make. Can be zero. If minimum comments is 0, this should also be 0. Typical range: 5-10 points.
</span>
</div>
<div style="margin-bottom: 15px;">
<label for="mincomments" style="font-weight: bold; display: inline-block; min-width: 200px;">
Minimum Comments Required
<span class="info-icon" data-help="mincomments" style="cursor: help; color: #337ab7; margin-left: 5px;">ℹ️</span>
</label>
<input type="number" name="mincomments" id="mincomments"
value="<?= htmlentities($current_mincomments) ?>"
placeholder=""
min="0" step="1"
style="width: 100px; padding: 5px;">
<span class="help-text" id="help-mincomments" style="display: none; margin-left: 10px; color: #666; font-size: 0.9em;">
Required number of peer review comments each student must make. If zero, peer review is optional. Typical: 3-5 for classes of 20+, 2-3 for smaller classes.
</span>
</div>
<!-- Live Total Points Display -->
<div style="margin-top: 20px; padding: 15px; background-color: #f9f9f9; border: 2px solid #5cb85c; border-radius: 4px;">
<strong>Total Points:</strong>
<span id="total-points-display" style="font-size: 1.2em; font-weight: bold; color: #5cb85c;">0</span>
<div style="margin-top: 8px; font-size: 0.9em; color: #666;">
Formula: <code>Total = Instructor Points + Submit Points + (Comment Points × Min Comments)</code>
</div>
<div id="points-warning" style="margin-top: 8px; color: #d9534f; font-weight: bold; display: none;">
⚠️ Warning: Total points is 0. Grades will not be sent to the LMS.
</div>
</div>
</div>
<!-- Other Settings -->
<div style="margin-bottom: 25px;">
<h4 style="border-bottom: 2px solid #ddd; padding-bottom: 8px;">Other Settings</h4>
<div style="margin-bottom: 15px;">
<label style="font-weight: bold; display: inline-block; min-width: 200px;">
<input type="checkbox" name="userealnames" id="userealnames" value="1"
<?= $current_userealnames ? 'checked' : '' ?>>
Use Actual Student Names
<span class="info-icon" data-help="userealnames" style="cursor: help; color: #337ab7; margin-left: 5px;">ℹ️</span>
</label>
<span class="help-text" id="help-userealnames" style="display: none; margin-left: 10px; color: #666; font-size: 0.9em;">
When unchecked, students see generated names (e.g., "Purple Elephant") for anonymity. Instructors always see real names.
</span>
</div>
<div style="margin-bottom: 15px;">
<label style="font-weight: bold; display: inline-block; min-width: 200px;">
<input type="checkbox" name="allowall" id="allowall" value="1"
<?= $current_allowall ? 'checked' : '' ?>>
Allow students to see all submissions after minimum is met
<span class="info-icon" data-help="allowall" style="cursor: help; color: #337ab7; margin-left: 5px;">ℹ️</span>
</label>
<span class="help-text" id="help-allowall" style="display: none; margin-left: 10px; color: #666; font-size: 0.9em;">
When checked, students who meet the minimum comment requirement can see and comment on all submissions. When unchecked, they only see submissions they've already reviewed.
</span>
</div>
<div style="margin-bottom: 15px;">
<label style="font-weight: bold; display: inline-block; min-width: 200px;">
<input type="checkbox" name="resubmit" id="resubmit" value="1"
<?= $current_resubmit ? 'checked' : '' ?>>
Allow Students to Reset and Resubmit
<span class="info-icon" data-help="resubmit" style="cursor: help; color: #337ab7; margin-left: 5px;">ℹ️</span>
</label>
<span class="help-text" id="help-resubmit" style="display: none; margin-left: 10px; color: #666; font-size: 0.9em;">
When enabled, students can reset their submission to make it editable again. Comments are hidden but still count for points.
</span>
</div>
<div style="margin-bottom: 15px;">
<label for="auto_timeout_days" style="font-weight: bold; display: inline-block; min-width: 200px;">
Auto Grade Timeout
<span class="info-icon" data-help="auto_timeout" style="cursor: help; color: #337ab7; margin-left: 5px;">ℹ️</span>
</label>
<div style="display: inline-block;">
<select id="auto_timeout_days" style="width: 100px; padding: 5px; margin-right: 5px;">
<option value="0">0 days</option>
<?php for ($i = 1; $i <= 30; $i++): ?>
<option value="<?= $i ?>" <?= $auto_timeout_days == $i ? 'selected' : '' ?>><?= $i ?> day<?= $i == 1 ? '' : 's' ?></option>
<?php endfor; ?>
</select>
<select id="auto_timeout_hours" style="width: 100px; padding: 5px;">
<option value="0">0 hours</option>
<?php for ($i = 1; $i <= 23; $i++): ?>
<option value="<?= $i ?>" <?= $auto_timeout_hours == $i ? 'selected' : '' ?>><?= $i ?> hour<?= $i == 1 ? '' : 's' ?></option>
<?php endfor; ?>
</select>
<input type="hidden" name="auto_instructor_grade_timeout" id="auto_instructor_grade_timeout" value="<?= htmlentities($current_auto_timeout) ?>">
<span id="auto_timeout_display" style="margin-left: 10px; color: #666; font-size: 0.9em;"></span>
</div>
<span class="help-text" id="help-auto_timeout" style="display: none; margin-left: 10px; color: #666; font-size: 0.9em; clear: both; display: block; margin-top: 5px;">
Automatically send grade of 100% after this time since submission. Ensures students get credit even if they can't complete reviews or if the instructor does not do their grading. Typically left at 0 days and 0 hours except for courses with little regular instructor supervision.
</span>
</div>
<div style="margin-bottom: 15px;">
<label for="ai_api_url" style="font-weight: bold; display: inline-block; min-width: 200px;">
AI API URL (optional)
<span class="info-icon" data-help="ai_api_url" style="cursor: help; color: #337ab7; margin-left: 5px;">ℹ️</span>
</label>
<input type="text" name="ai_api_url" id="ai_api_url"