-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathreviewableAssessments.php
executable file
·2849 lines (2358 loc) · 111 KB
/
reviewableAssessments.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
# Abstract class to create an online reviewable assessment system; requires a form definition implementation
abstract class reviewableAssessments extends frontControllerApplication
{
# Function to assign defaults additional to the general application defaults
public function defaults ()
{
# Specify available arguments as defaults or as NULL (to represent a required argument)
$defaults = array (
'applicationName' => NULL,
'hostname' => 'localhost',
'username' => 'reviewableassessments', /* Note that these are only used for the lookup of people and colleges from the people database, not the main application itself */
'database' => 'reviewableassessments',
'table' => 'submissions',
'password' => NULL,
'databaseStrictWhere' => true,
'authentication' => true,
'administrators' => true,
'div' => 'reviewableassessments',
'tabUlClass' => 'tabsflat',
'description' => 'assessment',
'userCallback' => NULL, // NB Currently only a simple public function name supported
'collegesCallback' => NULL, // NB Currently only a simple public function name supported
'dosListCallback' => NULL, // NB Currently only a simple public function name supported
'researchMphils' => array (), // Research MPhil course names, e.g. 'mphil-foo'
'usersAutocomplete' => false, // URL of an autocomplete JSON endpoint
'emailDomain' => 'cam.ac.uk',
'directorDescription' => NULL, // E.g. 'XYZ Officer',
'pdfStylesheets' => array (),
'stage2Info' => false, // To enable stage 2 info, define a string describing the information to be added, e.g. 'additional information'
'types' => array ('Undergraduate', 'MPhil', 'PhD', 'Research staff', 'Academic staff', 'Other'), // In order of appearance in the form and for the exemplars listing
'listingAdditionalFields' => array (),
'descriptionDefault' => false, // Whether to create a default description when creating a new form
'descriptionMaxLength' => 130,
'emailSubjectAddition' => array (), // Token to add, indexed by form type, when e-mailing
'recordErasureYears' => 5, // Years after which records will be completely erased from the database, e.g. for data protection compliance; false to retain all records
);
# Return the defaults
return $defaults;
}
# Properties
public $legacyForms = array ();
public $formColours = array ();
# Function to assign supported actions
public function actions ()
{
# Define available tasks
$actions = array (
'home' => array (
'description' => false,
'url' => '',
'icon' => 'house',
'tab' => 'Home',
),
'create' => array (
'description' => false,
'url' => 'new/',
'tab' => 'New',
'icon' => 'add',
),
'examples' => array (
'url' => 'examples/',
'tab' => 'Examplars',
'description' => false,
'icon' => 'page_white_stack',
'enableIf' => $this->settings['exemplars'],
),
'submissions' => array ( // Available to all users
'url' => 'submissions/',
'description' => false,
'tab' => ($this->user && $this->userIsReviewer ? ($this->userIsAdministrator ? 'All submissions' : 'Submissions') : NULL), // Show only the tab if the user is logged-in and a reviewer
'icon' => 'application_view_list',
),
'download' => array (
'description' => 'Download data',
'administrator' => true,
'parent' => 'admin',
'subtab' => 'Download data',
'icon' => 'database_save',
),
'downloadcsv' => array (
'description' => 'Download data',
'administrator' => true,
'export' => true,
),
);
# Return the actions
return $actions;
}
# Database structure definition
public function databaseStructure ()
{
# Define the base SQL
$sql = "
CREATE TABLE IF NOT EXISTS `administrators` (
`username__JOIN__people__people__reserved` varchar(191) NOT NULL COMMENT 'Username',
`active` enum('','Yes','No') NOT NULL DEFAULT 'Yes' COMMENT 'Currently active?',
`privilege` enum('Administrator','Restricted administrator') NOT NULL DEFAULT 'Administrator' COMMENT 'Administrator level',
`state` varchar(255) DEFAULT NULL COMMENT 'State',
PRIMARY KEY (`username__JOIN__people__people__reserved`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci COMMENT='System administrators';
CREATE TABLE `countries` (
`id` int(11) NOT NULL COMMENT 'Automatic key',
`value` varchar(191) NOT NULL COMMENT 'Country name',
`label` varchar(255) NOT NULL COMMENT 'Label',
PRIMARY KEY (`id`),
KEY `country` (`value`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci COMMENT='Country names';
CREATE TABLE IF NOT EXISTS `settings` (
`id` int(11) NOT NULL AUTO_INCREMENT COMMENT 'Automatic key (ignored)',
`directorUsername` VARCHAR(255) NOT NULL COMMENT 'Director username',
`peopleResponsible` TEXT NULL COMMENT 'People responsible, for specified groupings',
`additionalCompletionCc` TEXT NULL COMMENT 'Additional e-mail addresses to Cc on completion, for specified groupings',
`introductionHtml` text COMMENT 'Front page introduction text',
`feedbackHtml` TEXT NULL COMMENT 'Feedback page additional note',
`yearsVisibleMax` int DEFAULT '3' COMMENT 'Years visible maximum',
`exemplars` TEXT NULL DEFAULT NULL COMMENT 'Exemplars (list of IDs, one per line)',
`approvalCoverSheetHtml` TEXT NULL DEFAULT NULL COMMENT 'Approval cover sheet template',
`logoImageFile` varchar(255) DEFAULT NULL COMMENT 'Logo image (.png only, max 200px), for cover letter',
`directorName` varchar(255) DEFAULT NULL COMMENT 'Director name',
`directorSignatureImageFile` varchar(255) DEFAULT NULL COMMENT 'Director signature image (.png only, max 120px), for cover letter',
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci COMMENT='Settings';
CREATE TABLE IF NOT EXISTS `submissions` (
`id` int(11) NOT NULL AUTO_INCREMENT COMMENT 'Automatic key',
`form` varchar(255) NOT NULL DEFAULT 'form_default' COMMENT 'Form definition (table)',
`username` varchar(50) NOT NULL COMMENT 'CRSID',
`status` enum('started','submitted','reopened','deleted','archived','rejected','approved','parked') NOT NULL DEFAULT 'started' COMMENT 'Status of submission',
`parentId` int(11) DEFAULT NULL COMMENT 'Master record for this version (NULL indicates the master itself)',
`archivedVersion` int(11) DEFAULT NULL COMMENT 'Version number (NULL represents current, 1 is oldest, 2 is newer, etc.)',
`description` varchar(255) NOT NULL COMMENT 'Description',
`name` varchar(255) DEFAULT NULL COMMENT 'Your name',
`email` varchar(255) DEFAULT NULL COMMENT 'Your email',
`type` enum('" . implode ("','", $this->settings['types']) . "') DEFAULT NULL COMMENT 'Position/course',
`college` varchar(255) DEFAULT NULL COMMENT 'College',
`seniorPerson` varchar(255) DEFAULT NULL COMMENT 'Person responsible',
`currentReviewer` varchar(255) DEFAULT NULL COMMENT 'Current reviewer (initially same as seniorPerson, but a passup event can change this)',
`confirmation` TINYINT NULL DEFAULT '0' COMMENT 'Confirmation';
`reviewOutcome` varchar(255) DEFAULT NULL COMMENT 'Review outcome',
`comments` text COMMENT 'Comments from administrator',
`stage2InfoRequired` int(1) DEFAULT NULL COMMENT 'Stage 2 information required',
`dataJson` JSON NULL DEFAULT NULL COMMENT 'Details (JSON)',
`updatedAt` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT 'Automatic timestamp',
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci COMMENT='Table of submissions';
";
# Return the SQL
return $sql;
}
# Additional processing, run before actions is processed
protected function mainPreActions ()
{
# Disable caching on home
$this->globalActions['home']['nocache'] = true;
# If using descriptionDefault, switch on name lookups
if ($this->settings['descriptionDefault']) {
$this->settings['useCamUniLookup'] = true;
}
# Get the list of available forms, e.g. form_default, form_..., ...
$this->availableForms = array_values (preg_grep ('/^form_[a-z]+$/', get_class_methods ($this)));
# Get the list of Directors of Studies and determine if the user is a DoS
$this->dosList = $this->getDosList ();
$this->userIsDos = (isSet ($this->dosList[$this->user]));
# Determine what submissions, if any, the user has rights to review
$this->userHasReviewableSubmissions = $this->getReviewableSubmissionsIds ();
# Determine if the user has submissions that they can review, or it is expected that they will have in the future (e.g. because they are a DoS)
$this->userIsReviewer = ($this->userHasReviewableSubmissions || $this->userIsAdministrator || $this->userIsDos);
# Workaround for incorrect dataDirectory in FCA, as we need the child class, not this inherited parent
$reflector = new ReflectionClass (get_class ($this)); // I.e. child class, e.g. fooAssessments.php
$applicationRoot = dirname ($reflector->getFileName ());
$this->dataDirectory = $applicationRoot . $this->settings['dataDirectory'];
}
# Function to get reviewable submission IDs
private function getReviewableSubmissionsIds ()
{
# Determine the conditions; if an administrator, there is no limitation
$conditions = array ();
if (!$this->userIsAdministrator) {
#!# Should this be using currentReviewer now instead?
$conditions = array ('seniorPerson' => $this->user);
}
# Get the data
$data = $this->databaseConnection->selectPairs ($this->settings['database'], $this->settings['table'], $conditions, 'id');
# Return the list
return $data;
}
# Additional processing
protected function main ()
{
# Define the internal fields that should not be made visible or editable by the user
$this->internalFields = array ('id', 'form', 'username', 'status', 'parentId', 'archivedVersion', 'currentReviewer', 'reviewOutcome', 'comments', 'stage2InfoRequired', 'dataJson', 'updatedAt');
# Define private data fields, used for hiding in examples mode
$this->privateDataFields = $this->privateDataFields ();
# Define the review outcomes
$this->reviewOutcomes = $this->reviewOutcomes ();
# Define statuses; the keys here must be kept in sync with the status field's ENUM specification
$this->statuses = $this->statuses ();
}
# Function to define the private data fields, used for hiding in examples mode; this is overrideable by the form definition implementation
public function privateDataFields ()
{
return array ('name', 'email', 'college', 'seniorPerson');
}
# Function to define the review outcomes
public function reviewOutcomes ()
{
# Define the review outcomes
$reviewOutcomes = array (
'rejected' => array (
'setStatusTo' => 'rejected',
'icon' => 'cancel',
'text' => "Your {$this->settings['description']} has <strong>not been approved</strong> for the reasons given below. You will need to rethink your proposed project and submit a completely new assessment. If necessary, please visit to discuss the reasons for this.",
'requireComments' => true,
'emailSubject' => 'not approved',
),
'changesneeded' => array (
'setStatusTo' => 'reopened',
'icon' => 'bullet_error',
'text' => 'You need to <strong>make changes</strong> to the form as per the following comments:', // NB '<strong>make changes</strong> to the form' will get highlighted, so this string must remain
'requireComments' => true,
'createArchivalVersion' => true,
'emailSubject' => 'changes needed',
),
#!# This appears even if the current director is reviewing
'passup' => array (
'setStatusTo' => 'submitted',
'icon' => 'bullet_go',
'text' => "Your {$this->settings['description']} has been through initial review, and will now <strong>proceed to the next stage of review</strong> by the {$this->settings['directorDescription']}.",
'emailSubject' => 'passed to next stage of review',
'setCurrentReviewerToDirector' => true,
),
'stage2' => array (
'setStatusTo' => 'reopened',
'icon' => 'bullet_go',
'text' => "You now need to <strong>add {$this->settings['stage2Info']}</strong>.",
'directorOnly' => true,
'createArchivalVersion' => true,
'setStage2InfoRequired' => true,
'emailSubject' => 'more information needed',
),
'changesstage2' => array (
'setStatusTo' => 'reopened',
'icon' => 'bullet_go',
'text' => "You need to <strong>make changes</strong> to the form as per the comments below <strong>and also add {$this->settings['stage2Info']}</strong>.", // NB '<strong>make changes</strong> to the form' will get highlighted, so these strings must remain
'directorOnly' => true,
'requireComments' => true,
'setStage2InfoRequired' => true,
'createArchivalVersion' => true,
'emailSubject' => 'changes and more information needed',
),
'approved' => array (
'setStatusTo' => 'approved',
'icon' => 'tick',
'text' => "Your {$this->settings['description']} has been <strong>approved</strong>, and so you are now permitted to undertake the activity in line with your submission. Many thanks for your careful attention. Please print it out and take it with you.",
'directorOnly' => true,
'emailSubject' => 'approved',
),
'parked' => array (
'setStatusTo' => 'parked',
'icon' => 'control_pause',
'text' => "Set this {$this->settings['description']} as permanently <strong>parked</strong>. (This will not send a notification to the user.)",
'directorOnly' => true,
'emailSubject' => false, // i.e. do not send an e-mail
),
);
# Set undefined flags to false to avoid having to do isSet checks
$optionalFlags = array ('requireComments', 'createArchivalVersion', 'setCurrentReviewerToDirector', 'directorOnly', 'setStage2InfoRequired');
foreach ($reviewOutcomes as $id => $reviewOutcome) {
foreach ($optionalFlags as $optionalFlag) {
if (!isSet ($reviewOutcome[$optionalFlag])) {
$reviewOutcomes[$id][$optionalFlag] = false;
}
}
}
# Remove stage2-related options if not enabled
if (!$this->settings['stage2Info']) {
unset ($reviewOutcomes['stage2']);
unset ($reviewOutcomes['changesstage2']);
}
# Return the review outcomes
return $reviewOutcomes;
}
# Function to define the statuses
public function statuses ()
{
# Define statuses; the keys here must be kept in sync with the status field's ENUM specification
return array (
'started' => array (
'icon' => 'page_edit',
'editableBySubmitter' => true,
),
'submitted' => array (
'icon' => 'page_find',
'editableBySubmitter' => false,
),
'reopened' => array (
'icon' => 'page_error',
'editableBySubmitter' => true,
),
'deleted' => array (
'icon' => 'page_delete',
'editableBySubmitter' => false,
),
'archived' => array (
'icon' => 'page',
'editableBySubmitter' => false,
),
'rejected' => array (
'icon' => 'page_red',
'editableBySubmitter' => false,
),
'approved' => array (
'icon' => 'page_green',
'editableBySubmitter' => false,
),
'parked' => array (
'icon' => 'control_pause',
'editableBySubmitter' => false,
),
);
}
# Home page
public function home ()
{
# Start the HTML
$html = '';
# Show introduction HTML
if ($this->userIsAdministrator) {
$html .= "\n" . '<p class="actions right"><a href="' . $this->baseUrl . '/settings.html#form_introductionHtml"><img src="/images/icons/pencil.png" alt=""> Edit text</a></p>';
}
$html .= $this->settings['introductionHtml'];
# Start new
$html .= "\n<h2>Start a new {$this->settings['description']}</h2>";
$html .= "\n<p><a class=\"actions\" href=\"{$this->baseUrl}/new/\"><img src=\"/images/icons/add.png\" alt=\"Add\" class=\"icon\" /> Start a <strong>new</strong> {$this->settings['description']}</a></p>";
# List submitted forms
$html .= $this->listSubmissions (array ('approved'), "Approved {$this->settings['description']} forms");
$html .= $this->listSubmissions (array ('submitted'), 'Forms awaiting review');
$html .= $this->listSubmissions (array ('reopened', 'started'), "Incomplete {$this->settings['description']} forms");
$html .= $this->listSubmissions (array ('rejected'), ucfirst ($this->settings['descriptionPlural']) . ' not approved');
# Show the HTML
echo $html;
}
# Function to create a global submissions table
private function unifiedSubmissionsTable ()
{
# Start the HTML
$html = '';
# End if not a reviewer
if (!$this->userIsReviewer) {
$html .= "\n<p>You do not appear to be a reviewer so have no access to this section. Please check the URL and try again.</p>";
return $html;
}
# Add export button
if ($this->userIsAdministrator) {
$html .= "\n<p><a class=\"actions right\" href=\"{$this->baseUrl}/download.html\"><img src=\"/images/icons/database_save.png\" /> Download data</a></p>";
}
# Construct the HTML
$html .= "\n<p>As a reviewer, you can see the following submissions:</p>";
$submissionsTable = $this->listSubmissions (false, false, $reviewingMode = true);
$html .= $submissionsTable;
# Return the HTML
return $html;
}
# Submissions (front controller)
public function submissions ($id)
{
# Start the HTML
$html = '';
# Show the table of submissions if no ID supplied
if (!$id) {
$html .= $this->unifiedSubmissionsTable ();
echo $html;
return false;
}
# Ensure the ID is numeric or end
if (!is_numeric ($id)) {
$html .= "\n<p>The ID you supplied is not valid. Please check the URL and try again.</p>";
echo $html;
return false;
}
# If a version is specified, ensure it is numeric
$version = false;
if (isSet ($_GET['version'])) {
# Ensure the version is numeric or end
if (!is_numeric ($_GET['version']) || $_GET['version'] < 1) {
$html .= "\n<p>The version you supplied is not valid. Please check the URL and try again.</p>";
echo $html;
return false;
}
$version = $_GET['version'];
# Lookup up the actual ID of the record
if (!$id = $this->getDatabaseIdOfVersion ($id, $version)) {
$html .= "\n<p>The version you supplied is not valid. Please check the URL and try again.</p>";
echo $html;
return false;
}
}
# Get the submission or end
if (!$submission = $this->getSubmission ($id)) {
$html .= "\n<p>The ID you supplied is not valid. Please check the URL and try again.</p>";
echo $html;
return false;
}
# Deny direct ID access to archived versions
if ($submission['archivedVersion'] && !$version) {
$html .= "\n<p>The ID you supplied is not valid. Please check the URL and try again.</p>";
echo $html;
return false;
}
# Ensure this ID is owned by this user
if ($submission['username'] != $this->user) {
if (!$this->userCanReviewSubmission ($id)) {
$html .= "\n<p>You do not appear to have rights to view the specified submission. Please check the URL and try again.</p>";
echo $html;
return false;
}
}
# Deny access if deleted
if ($submission['status'] == 'deleted') {
$html = "\n" . '<p>The submission has been deleted.</p>';
$html .= "\n" . "<p><a href=\"{$this->baseUrl}/\">Return to the home page.</a></p>";
echo $html;
return true;
}
# Determine the action, ensuring it is supported
$action = 'show';
if (isSet ($_GET['do'])) {
$extraActions = array ('delete', 'clone', 'review', 'compare', 'reassign');
if (!in_array ($_GET['do'], $extraActions)) {
$this->page404 ();
return false;
}
$action = $_GET['do'];
}
# For edit/clone/delete, check that the user has rights, or end
$userHasEditCloneDeleteRights = $this->userHasEditCloneDeleteRights ($submission['username']);
if (!$userHasEditCloneDeleteRights) {
$disallowedActions = array ('edit', 'clone', 'delete');
if (in_array ($action, $disallowedActions)) {
$html .= "\n<p>You do not appear to have rights to {$action} the specified submission. Please check the URL and try again.</p>";
echo $html;
return false;
}
}
# For reassign, check that the user has rights, or end
if ($action == 'reassign') {
if (!$this->userCanReassign ($submission)) {
$html = "\n<p>You do not appear to have rights to reassign this submission.</p>";
echo $html;
return $html;
}
}
# If showing, switch between show and edit depending on the status of the submission
#!# Review whether the architecture here can be improved; see also the presence of 'edit' above
if ($action == 'show') {
if ($this->statuses[$submission['status']]['editableBySubmitter']) {
if ($userHasEditCloneDeleteRights) {
$action = 'edit';
}
}
}
# Create the HTML for this action
$action = 'submission' . ucfirst ($action); // e.g. submissionEdit, submissionReview, etc,
$html = $this->{$action} ($submission);
# Show the HTML
echo $html;
}
# Function to determine if a user can review a submission
private function userCanReviewSubmission ($id)
{
return (in_array ($id, $this->userHasReviewableSubmissions));
}
# Function to view a submission
private function submissionShow ($submission)
{
# Show title
#!# Replace username with real name
$html = "\n<h2>" . ucfirst ($this->settings['description']) . " form by {$submission['username']} (#{$submission['id']})</h2>";
# Display a flash message if set
if ($flashValue = application::getFlashMessage ('submission' . $submission['id'], $this->baseUrl . '/')) { // id is used to ensure the flash only appears attached to the matching submission
$message = "\n" . "<p>{$this->tick} <strong>The submission has been " . htmlspecialchars ($flashValue) . ', as below:</strong></p>';
$html .= "\n<div class=\"graybox flashmessage\">" . $message . '</div>';
}
# Show the form
$html .= $this->viewSubmission ($submission);
# If approved, and PDF export is requested, do export
if (isSet ($_GET['export']) && $_GET['export'] == 'pdf') {
$this->exportPdf ($html, $submission['status'], $submission['id'], $submission);
return;
}
# Return the HTML
return $html;
}
# Function to export as PDF
private function exportPdf ($html, $status, $id, $submission)
{
# End if not approved
if ($status != 'approved') {
$this->page404 ();
return false;
}
# Compile the stylesheets for each
$stylesheetsHtml = '';
foreach ($this->settings['pdfStylesheets'] as $stylesheetFilename) {
$stylesheetsHtml .= "\n" . '<style type="text/css" media="all">@import "' . $stylesheetFilename . '";</style>';
}
# Assemble cover sheet if required
$coverSheetHtml = '';
if (trim ($this->settings['approvalCoverSheetHtml'])) {
$coverSheetHtml = str_repeat ('<p> </p>', 3);
$coverSheetHtml .= $this->processTemplate ($this->settings['approvalCoverSheetHtml'], $submission);
$coverSheetHtml .= "\n" . '<p style="page-break-after: always;"> </p>';
}
# Add a timestamp heading
$introductionHtml = "\n<p class=\"comment\">Printed at " . date ('g:ia, jS F Y') . " from {$_SERVER['_SITE_URL']}{$this->baseUrl}/submissions/{$id}/</p>\n<hr />";
# Compile the HTML
$pdfHtml = $stylesheetsHtml;
$pdfHtml .= $coverSheetHtml;
$pdfHtml .= $introductionHtml;
$pdfHtml .= "\n<div id=\"{$this->settings['div']}\">";
$pdfHtml .= $html;
$pdfHtml .= "\n</div>";
# Serve the HTML and terminate all execution
application::html2pdf ($pdfHtml, "assessment{$id}.pdf");
exit;
}
# Function to templatise
private function processTemplate ($template, $submission)
{
# Start an array of placeholders for replacement
$replacements = array ();
# Replace submission fields where present
foreach ($submission as $field => $value) {
$placeholder = '{' . $field . '}';
if (substr_count ($template, $placeholder)) {
$replacements[$placeholder] = $value;
}
}
# Format special-case fields
$replacements['{updatedAt}'] = date ('jS F, Y', strtotime ($submission['updatedAt']));
$replacements['{seniorPerson}'] = strip_tags ($this->renderResponsiblePerson ($submission['seniorPerson']));
$replacements['{college}'] = $this->renderCollege ($submission['college']);
# Similarly, substitute supported settings values
$replacements['{settings.directorName}'] = $this->settings['directorName'];
# Image files, and their max size
$settings = array (
'directorSignatureImageFile' => 120,
'logoImageFile' => 300,
);
foreach ($settings as $setting => $maxSize) {
$imageFile = $this->dataDirectory . $setting . '.png';
if (file_exists ($imageFile)) {
$imageFileBase64 = base64_encode (file_get_contents ($imageFile));
$replacements["{settings.{$setting}}"] = "<img src=\"data:image/png;base64,{$imageFileBase64}\" style=\"max-width: {$maxSize}px; max-height: {$maxSize}px;\" />";
}
}
# Substitute
$template = strtr ($template, $replacements);
# Return the template
return $template;
}
# Function to edit a submission
private function submissionEdit ($submission)
{
# Show title
#!# Replace username with real name
$html = "\n<h2>" . ucfirst ($this->settings['description']) . " form by {$submission['username']} (#{$submission['id']})</h2>";
# Display a flash message if set
if ($flashValue = application::getFlashMessage ('submission' . $submission['id'], $this->baseUrl . '/')) { // id is used to ensure the flash only appears attached to the matching submission
$message = "\n" . "<p>{$this->tick} <strong>The submission has been " . htmlspecialchars ($flashValue) . ', as below:</strong></p>';
$html .= "\n<div class=\"graybox flashmessage\">" . $message . '</div>';
}
# Show the form or view it, depending on the status
$html .= $this->submissionProcessor ($submission);
# Return the HTML
return $html;
}
# Function to delete a submission
private function submissionDelete ($submission)
{
# Start the HTML
$html = "\n<h2>Delete a {$this->settings['description']} form by {$submission['username']} (#{$submission['id']})</h2>";
# If re-opening, change the database status then redirect
if ($submission['status'] == 'submitted') {
$html = "\n<p>This submission has been submitted so cannot now be deleted.</p>";
return $html;
}
# Get any archive versions
$archivedVersions = $this->getArchivedVersionsSummary ($submission['id']);
$totalArchivedVersions = count ($archivedVersions);
# Confirmation form
$form = new form (array (
'databaseConnection' => $this->databaseConnection,
'formCompleteText' => false,
'nullText' => '',
'display' => 'paragraphs',
'submitButtonText' => 'Delete submission permanently',
'div' => 'graybox',
));
$form->heading ('p', "Do you really want to delete the submission below" . ($archivedVersions ? ' (and its ' . ($totalArchivedVersions == 1 ? 'earlier version' : "{$totalArchivedVersions} earlier versions") . ')' : '') . "? This cannot be undone.");
$form->select (array (
'name' => 'confirmation',
'title' => 'Confirm deletion',
'required' => true,
'forceAssociative' => true,
'values' => array ('Yes, delete this submission permanently'),
));
if (!$result = $form->process ($html)) {
$html .= $this->viewSubmission ($submission, true);
return $html;
}
# Set the status of the record (and any archived versions) as deleted
$query = "UPDATE {$this->settings['database']}.{$this->settings['table']} SET status = 'deleted' WHERE id = :id OR parentId = :id;";
if (!$this->databaseConnection->query ($query, array ('id' => $submission['id']))) {
$html .= $this->reportError ("There was a problem setting the submission as deleted:\n\n" . print_r ($version, true), 'There was a problem deleting the submission. The Webmaster has been informed and will investigate shortly.');
return $html;
}
# Redirect, resetting the HTML
$html = "\n<p>{$this->tick} The submission has been deleted.</p>";
# Redirect
$redirectTo = "{$_SERVER['_SITE_URL']}{$this->baseUrl}/submissions/{$submission['id']}/";
$html .= application::sendHeader (302, $redirectTo, true);
# Return the HTML
return $html;
}
# Function to review a submission
private function submissionReview ($submission)
{
# Start the HTML
$html = "\n<h2>Review a {$this->settings['description']} form by {$submission['username']} (#{$submission['id']})</h2>";
# Ensure the user has reviewing rights
if (!$this->userCanReviewSubmission ($submission['id'])) {
$html = "\n<p>You do not appear to have rights to review this submission.</p>";
return $html;
}
# Ensure the submission has not been handed up to the Director
$passedUp = ($submission['currentReviewer'] != $submission['seniorPerson']); // Whether the submission is now in the hands of the Director
if ($passedUp && !$this->userIsAdministrator) {
$html = "\n<p>You have already passed this submission up to the {$this->settings['directorDescription']}, so you cannot now review the submission.</p>";
return $html;
}
# Reviewing is only possible in the 'submitted' state, so that a versioning cannot be done twice accidentally
if ($submission['status'] != 'submitted') {
if ($submission['status'] == 'started' || $submission['status'] == 'reopened') {
$html = "\n<p>The submission is <a href=\"{$this->baseUrl}/submissions/{$submission['id']}/\">open for editing</a>.</p>";
} else {
$html = "\n<p>The submission <a href=\"{$this->baseUrl}/submissions/{$submission['id']}/\">can be viewed</a>.</p>";
}
return $html;
}
# Obtain the review, or end
if (!$reviewOutcome = $this->reviewForm ($submission)) {
$html .= $this->viewSubmission ($submission, true);
return $html;
}
# Create an archival version if necessary; effectively this is a cloned submission which references a parentId; if an error occurs, report this but continue
if ($reviewOutcome['createArchivalVersion']) {
$this->createArchivalVersion ($submission, $reviewOutcome['outcome'], $reviewOutcome['comments'], $html);
}
# Update the record
$update = array (
'status' => $reviewOutcome['setStatusTo'],
'comments' => $reviewOutcome['comments'], // May be blank
'reviewOutcome' => $reviewOutcome['outcome'],
'currentReviewer' => ($reviewOutcome['setCurrentReviewerToDirector'] ? $this->settings['directorUsername'] : $submission['currentReviewer']), // Update, or retain original value
'stage2InfoRequired' => ($reviewOutcome['setStage2InfoRequired'] ? 1 : $submission['stage2InfoRequired']), // Update, or retain original value
'updatedAt' => 'NOW()', // Database library will convert from string to SQL keyword
);
$this->databaseConnection->update ($this->settings['database'], $this->settings['table'], $update, array ('id' => $submission['id']));
# Determine the submission URL
$submissionUrl = "{$_SERVER['_SITE_URL']}{$this->baseUrl}/submissions/{$submission['id']}/";
# E-mail the review outcome if required
$this->emailReviewOutcome ($submissionUrl, $submission, $update['currentReviewer'], $reviewOutcome['outcome'], $reviewOutcome['comments']);
# Redirect to the submission URL, resetting the HTML
$html = application::sendHeader (302, $submissionUrl, true);
# Return the HTML
return $html;
}
# Function to create the review outcomes form
private function reviewForm ($submission)
{
# Start the HTML
$html = '';
# If the user can reassign, show a link to the reassign page
if ($this->userCanReassign ($submission)) {
$html .= "<p class=\"alignright\">Or <a class=\"submission\" href=\"{$this->baseUrl}/submissions/{$submission['id']}/reassign.html\"> reassign reviewer …</a></p>";
}
# Filter the review outcomes to those available for the current user
$reviewOutcomes = array ();
foreach ($this->reviewOutcomes as $id => $reviewOutcome) {
if ($reviewOutcome['directorOnly'] && !$this->userIsAdministrator) {continue;} // Omit Director-only items if not an admin
$reviewOutcomes[$id] = $this->icon ($reviewOutcome['icon']) . ' ' . $reviewOutcome['text'];
}
# Create the form
$form = new form (array (
'display' => 'paragraphs',
'div' => 'graybox ultimateform',
'unsavedDataProtection' => true,
));
$form->heading ('p', 'Please review the submission below and submit the form. This will e-mail your decision, and a link to this page, to the original submitter.');
$form->radiobuttons (array (
'name' => 'outcome',
'title' => 'Review outcome',
'values' => $reviewOutcomes,
'required' => true,
'entities' => false, // i.e. treat labels as incoming HTML
));
$form->textarea (array (
'name' => 'comments',
'title' => 'Comments (optional)',
'cols' => 80,
'rows' => 6,
'required' => false,
));
if ($unfinalisedData = $form->getUnfinalisedData ()) {
if ($unfinalisedData['outcome']) {
if ($this->reviewOutcomes[$unfinalisedData['outcome']]['requireComments']) {
if (!strlen ($unfinalisedData['comments'])) {
$form->registerProblem ('commentsneeded', 'You need to add comments.', 'comments');
}
}
}
}
# Process the form
if ($result = $form->process ($html)) {
# Merge in the review outcomes attributes to the outcome ID and the comments
$result += $this->reviewOutcomes[$result['outcome']];
}
# Show the HTML
echo $html;
# Return the result
return $result;
}
# Function to create an archived submission, which clones the original to a new entry with a higher ID, so that the original ID is maintained
# This cloning happens at the point of review, so that a timestamped archival record of that edition is kept
private function createArchivalVersion ($version, $reviewOutcome, $reviewComments, &$html)
{
# Set the parentId and remove the current ID
$version['parentId'] = $version['id'];
unset ($version['id']);
# Set the status, comments and review outcome
$version['status'] = 'archived';
$version['comments'] = $reviewComments;
$version['reviewOutcome'] = $reviewOutcome;
# Get the highest version number
$maxArchivedVersion = $this->getMostRecentArchivedVersion ($version['parentId'], true); // Will return NULL (equivalent to 0) if no previous versions, i.e. currently at original
$version['archivedVersion'] = $maxArchivedVersion + 1;
# Set the last updated time
$version['updatedAt'] = 'NOW()'; // Database library will convert to native function
# Pack the local data fields to JSON, and remove their native values
$version = $this->packSubmissionJson ($version);
# Insert the new archival entry
if (!$this->databaseConnection->insert ($this->settings['database'], $this->settings['table'], $version)) {
$html = $this->reportError ("There was a problem creating the new version:\n\n" . print_r ($version, true), 'There was a problem archiving the old version of this submission. The Webmaster has been informed and will investigate shortly.');
}
}
# Function to e-mail the review outcome
private function emailReviewOutcome ($submissionUrl, $submission, $currentReviewer, $reviewOutcome /* i.e. the new status */, $comments)
{
# End if this review outcome type is set not to send an e-mail
if (!$this->reviewOutcomes[$reviewOutcome]['emailSubject']) {return;}
# Assemble the reviewer's details
$userLookupData = camUniData::lookupUser ($this->user);
$loggedInReviewerEmail = $this->user . "@{$this->settings['emailDomain']}";
$loggedInReviewerName = ($userLookupData ? $userLookupData['name'] : false);
# Construct the message
$message = '';
$message .= ($submission['name'] ? "\nDear {$submission['name']},\n\n" : '');
$message .= "A {$this->settings['description']} that you submitted has been reviewed.";
$message .= "\n\n" . str_repeat ('-', 74);
$message .= "\n\n" . strip_tags ($this->reviewOutcomes[$reviewOutcome]['text']);
if ($comments) {$message .= "\n\n" . $comments;}
$message .= "\n\n" . str_repeat ('-', 74);
$message .= "\n\nAccess it at:\n{$submissionUrl}";
if ($reviewOutcome == 'approved') {
$message .= "\n\nYou can also download a printable PDF at:\n{$submissionUrl}assessment{$submission['id']}.pdf";
}
$message .= "\n\n\nThanks" . ($loggedInReviewerName ? ",\n\n{$loggedInReviewerName}" : '.');
# The recipient is always the original submitter
$to = ($submission['name'] ? "{$submission['name']} <{$submission['email']}>" : $submission['email']);
# Construct the message details
$subject = ucfirst ($this->settings['description']) . " (#{$submission['id']}" . $this->emailSubjectAddition ($submission['form']) . ') review: ' . $this->reviewOutcomes[$reviewOutcome]['emailSubject'];
$headers = 'From: ' . ($loggedInReviewerName ? "{$loggedInReviewerName} <{$loggedInReviewerEmail}>" : $loggedInReviewerEmail);
# Determine Cc
$cc = array ();
if ($currentReviewer != $submission['seniorPerson']) { // i.e. Copy in the DoS if in passup
if ($reviewOutcome == 'passup') { // On the specific passup event, copy in the main reviewer
$cc[] = $currentReviewer . (str_contains ($currentReviewer, '@') ? '' : "@{$this->settings['emailDomain']}");
}
$cc[] = $submission['seniorPerson'] . "@{$this->settings['emailDomain']}"; // Copy to DoS; this is done even at passup as a courtesy e.g. to make contact more easily with the Director
}
# On final approval (only), if additional completion e-mail addresses are specified, and the type (e.g. 'Undergraduate') matches, add that address on completion
if ($reviewOutcome == 'approved') {
if (trim ($this->settings['additionalCompletionCc'])) {
$additionalCompletionCcAddresses = array ();
$additionalCompletionCc = preg_split ("/\s*\r?\n\t*\s*/", trim ($this->settings['additionalCompletionCc']));
foreach ($additionalCompletionCc as $additionalCompletionCcLine) {
list ($courseMoniker, $emailAddressString) = explode (',', $additionalCompletionCcLine, 2);
$additionalCompletionCcAddresses[$courseMoniker] = trim ($emailAddressString); // e.g. 'Undergraduate' => 'foo@example.com, bar@example.com'
}
if (isSet ($additionalCompletionCcAddresses[$submission['type']])) {
$cc[] = $additionalCompletionCcAddresses[$submission['type']];
}
}
}
# Add Cc if set
if ($cc) {
$headers .= "\r\nCc: " . implode (', ', $cc);
}
# Send the message
application::utf8Mail ($to, $subject, wordwrap ($message), $headers);
}
# Function to get the most recent archived version (which may not exist)
private function getMostRecentArchivedVersion ($parentId, $getOnlyArchivedVersionField = false)
{
# Get the data, or end if no parent (i.e. current is original submission)
if (!$result = $this->databaseConnection->selectOne ($this->settings['database'], $this->settings['table'], array ('parentId' => $parentId), array (), false, $orderBy = 'archivedVersion DESC', $limit = 1)) {
return NULL; // Which will evaluate to 0 for addition purposes
}
# Unpack the detail data
$result = $this->unpackSubmissionJson ($result);
# If required, return only the archived version field value
if ($getOnlyArchivedVersionField) {
$result = $result['archivedVersion'];
}
# Return the result
return $result;
}
# Function to determine any additional subject component based on the form type
private function emailSubjectAddition ($form)
{
# End if not enabled
if (!$this->settings['emailSubjectAddition']) {return false;}
# End if not enabled for this form type
if (!isSet ($this->settings['emailSubjectAddition'][$form])) {return false;}
# Return the token, with a space-dash before
return ' - ' . $this->settings['emailSubjectAddition'][$form];
}
# Function to compare versions of a submission
private function submissionCompare ($submission)
{
# Start the HTML
$html = '';