-
Notifications
You must be signed in to change notification settings - Fork 0
/
courseEvaluations.php
executable file
·1892 lines (1608 loc) · 77 KB
/
courseEvaluations.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
# Class to provide a course evaluations system
class courseEvaluations extends frontControllerApplication
{
# Specify available arguments as defaults or as NULL (to represent a required argument)
public function defaults ()
{
return $defaults = array (
'hostname' => 'localhost',
'username' => 'courseevaluations',
'database' => 'courseevaluations',
'globalPeopleDatabase' => 'people',
'div' => 'courseevaluations',
'table' => 'people',
'applicationName' => 'Course evaluations',
'administrators' => true,
'tabUlClass' => 'tabsflat',
'authentication' => true,
'feedback' => false,
'yearStartMonth' => 12,
'includePieCharts' => true,
'piechartStub' => '/images/piechart',
'pieChartWidth' => 250,
'pieChartHeight' => 200,
'phpmyadminUrl' => '/phpmyadmin/',
'denyResults' => array (),
'overrideYear' => false,
'overrideUserYeargroup' => false,
'additionalLecturersResultsAccess' => array (),
'userNameCallback' => 'userNameCallback', // Callback function
'overrideQuestionLabels' => array (), // Array of academicYear => array (table => array (questionId => questionTitle))
'userSwitcherUsers' => array ($this, 'userSwitcherUsers'),
'userSwitcherOnSwitch' => array ($this, 'userSwitcherOnSwitch'),
);
}
# Specify additional actions
public function actions ()
{
# Define the actions
return $actions = array (
'data' => array (
'description' => 'Submit an evaluation',
'tab' => 'Evaluations',
'url' => '',
),
'results' => array (
'description' => 'Results',
'tab' => 'Results',
'url' => 'results/',
'enableIf' => $this->userHasResultsAccess,
),
'rates' => array (
'description' => 'Submission rates',
'tab' => 'Submission rates',
'url' => 'rates.html',
'restrictedAdministrator' => true,
'parent' => 'admin',
),
'export' => array (
'description' => 'Export data',
'url' => 'export.html',
'restrictedAdministrator' => true,
'parent' => 'admin',
'subtab' => 'Export data',
'export' => true,
),
'import' => array (
'description' => 'Set up course/student details',
'url' => 'import.html',
'restrictedAdministrator' => true,
'parent' => 'admin',
'subtab' => 'Set up course/student details',
),
# Override settings default to enable restricted administrators to access
'settings' => array (
'description' => 'Settings',
'url' => 'settings.html',
'restrictedAdministrator' => true, // Normally 'administrator' => true
'parent' => 'admin',
'subtab' => 'Settings',
),
);
}
# Database structure definition
public function databaseStructure ()
{
return "
CREATE TABLE `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',
PRIMARY KEY (`username__JOIN__people__people__reserved`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci COMMENT='System administrators';
CREATE TABLE `courses` (
`id` int NOT NULL AUTO_INCREMENT COMMENT 'Unique key',
`year` varchar(9) NOT NULL COMMENT 'Academic year',
`yeargroup` enum('ia','ib','ii') DEFAULT NULL COMMENT 'Year-group',
`type` enum('','courses','fieldtrips','practicals','projects','dissertation','general') DEFAULT 'courses' COMMENT 'Type of module',
`url` varchar(255) NOT NULL COMMENT 'URL fragment',
`title` varchar(255) NOT NULL COMMENT 'Course title',
`entries` enum('0','1') NOT NULL DEFAULT '0' COMMENT 'Whether the course requires entries (=0) or is instead available for assessment by all students in the year (=1)',
`paper` varchar(255) DEFAULT NULL COMMENT 'Paper number',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci COMMENT='Courses';
CREATE TABLE `entries` (
`id` int NOT NULL AUTO_INCREMENT COMMENT 'Unique key',
`crsid` varchar(255) NOT NULL COMMENT 'Username',
`year` varchar(10) NOT NULL COMMENT 'Year',
`yeargroup` enum('IA','IB','II') NOT NULL COMMENT 'Year-group',
`paper` varchar(255) NOT NULL COMMENT 'Paper number',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci COMMENT='Examination entries';
CREATE TABLE `feedbackcourses` (
`id` int NOT NULL AUTO_INCREMENT,
`user` varchar(255) NOT NULL COMMENT 'Username',
`courseId` int NOT NULL COMMENT 'Course',
`q1howmany` enum('','All','Most','About half','Less than half') NOT NULL COMMENT '1. How many lectures in this %type have you attended?',
`q2overall` enum('','Excellent','Good','Fair','Poor','No opinion') NOT NULL COMMENT '2. In general, how did you find this %type?',
`q3stimulating` enum('','Agree strongly','Agree','Disagree','Disagree strongly','No opinion') NOT NULL COMMENT '3. To what extent do you agree that the %type was intellectually stimulating?',
`qsubcoursemodeextra4connection` enum('','Agree strongly','Agree','Disagree','Disagree strongly','No opinion') DEFAULT NULL COMMENT '4. To what extent do you agree that the sections of the paper connect logically with one another?',
`q4enjoy` mediumtext COMMENT '4. Which aspect of the %type did you particularly enjoy?',
`q5improvement` mediumtext COMMENT '5. Do you have any suggestions on how the %type might be improved?',
`timestamp` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT 'Date/time submitted',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci COMMENT='Feedback from courses';
CREATE TABLE `feedbackgeneral` (
`id` int NOT NULL AUTO_INCREMENT,
`user` varchar(255) NOT NULL COMMENT 'Username',
`courseId` int NOT NULL COMMENT 'Course ID',
`q1library` mediumtext COMMENT '1. The Library resources and services are good enough for my needs – please comment',
`q2it` mediumtext COMMENT '2. I have been able to access general IT resources when I have needed to – please comment',
`q3facilities` mediumtext COMMENT '3. I have been able to access specialised equipment, facilities or rooms when I have needed to – please comment',
`q4confidence` mediumtext COMMENT '4. The course has helped me to present myself with confidence – please comment',
`q5communication` mediumtext COMMENT '5. My communication skills have improved – please comment',
`q6problemsolving` mediumtext COMMENT '6. As a result of my studies, I feel confident in tackling unfamiliar problems – please comment',
`timestamp` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT 'Date/time submitted',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci COMMENT='Feedback on general matters';
CREATE TABLE `feedbacklecturers` (
`id` int NOT NULL AUTO_INCREMENT,
`user` varchar(255) NOT NULL,
`lecturerId` int NOT NULL COMMENT 'Lecturer',
`q1howmany` enum('','All','Most','About half','Less than half') DEFAULT NULL COMMENT '1. How many lectures by this lecturer have you attended?',
`q2overall` enum('','Excellent','Good','Fair','Poor','No opinion') DEFAULT NULL COMMENT '2. In general, how did you find this set of lectures?',
`q3stimulating` enum('','Agree strongly','Agree','Disagree','Disagree strongly','No opinion') DEFAULT NULL COMMENT '3. To what extent do you agree that the lectures were intellectually stimulating?',
`q4presentation` enum('','Agree strongly','Agree','Disagree','Disagree strongly','No opinion') DEFAULT NULL COMMENT '4. To what extent do you agree that the lectures were clearly presented?',
`q5readinglists` enum('','Agree strongly','Agree','Disagree','Disagree strongly','No opinion') DEFAULT NULL COMMENT '5. To what extent do you agree that reading lists were satisfactory?',
`q6enjoy` mediumtext COMMENT 'Which aspect of this set of lectures did you particularly enjoy?',
`q7improvement` mediumtext COMMENT 'Do you have any suggestions on how this set of lectures might be improved?',
`timestamp` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT 'Date/time submitted',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci COMMENT='Feedback from lecturers';
CREATE TABLE `feedbackdissertation` (
`id` int NOT NULL AUTO_INCREMENT,
`user` varchar(255) NOT NULL COMMENT 'Username',
`courseId` int NOT NULL COMMENT 'Course ID',
`q1overall` enum('','Agree strongly','Agree','Disagree','Disagree strongly','No opinion') NOT NULL COMMENT '1. This set of lectures has given me more confidence in developing a dissertation idea than at the start of the year',
`timestamp` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT 'Date/time submitted',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci COMMENT='Dissertation feedback';
CREATE TABLE `feedbackothers` (
`id` int NOT NULL AUTO_INCREMENT,
`user` varchar(255) NOT NULL COMMENT 'Username',
`courseId` int NOT NULL AUTO_INCREMENT COMMENT 'Course ID',
`q1overall` enum('','Excellent','Good','Fair','Poor','No opinion') NOT NULL COMMENT '1. In general, how did you find this %type?',
`q2astimulating` enum('','Agree strongly','Agree','Disagree','Disagree strongly','No opinion') NOT NULL COMMENT '2a. The %type was intellectually stimulating.',
`q2bknowledge` enum('','Agree strongly','Agree','Disagree','Disagree strongly','No opinion') NOT NULL COMMENT '2b. The %type provided me with new knowledge.',
`q2cintegration` enum('','Agree strongly','Agree','Disagree','Disagree strongly','No opinion') NOT NULL COMMENT '2c. Sessions/days linked together well.',
`q3enjoy` mediumtext COMMENT '3. Which aspect of the %type did you particularly enjoy?',
`q4improvement` mediumtext COMMENT '4. Do you have any suggestions about how the %type might be improved?',
`timestamp` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT 'Date/time submitted',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci COMMENT='Feedback from fieldtrips/practicals/projects';
CREATE TABLE `lecturers` (
`id` int NOT NULL AUTO_INCREMENT COMMENT 'Unique key',
`year` varchar(10) NOT NULL COMMENT 'Year',
`yeargroup` enum('IA','IB','II') DEFAULT NULL COMMENT 'Year-group',
`course` varchar(255) NOT NULL COMMENT 'Course',
`subcourseId` varchar(255) DEFAULT NULL COMMENT 'Sub-course URL moniker, if relevant',
`subcourseName` varchar(255) DEFAULT NULL COMMENT 'Sub-course name, if relevant',
`lecturer` varchar(255) NOT NULL COMMENT 'Lecturer',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci COMMENT='Lecturing assessments';
CREATE TABLE `settings` (
`id` int NOT NULL AUTO_INCREMENT COMMENT 'Automatic key',
`opening` datetime NOT NULL COMMENT 'Opening date',
`closing` datetime NOT NULL COMMENT 'Closing date',
`allowViewingDuringSubmitting` TINYINT NULL DEFAULT NULL COMMENT 'Allow staff to view results while submission ongoing?',
`introductionHtml` mediumtext COMMENT 'Introduction text',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci COMMENT='Settings';
";
}
# Define the table names, which may be overriden by year later
private $tables = array (
'courses' => 'feedbackcourses',
'lecturers' => 'feedbacklecturers',
'others' => 'feedbackothers', // E.g. for practicals
'dissertation' => 'feedbackdissertation',
'general' => 'feedbackgeneral',
);
# Define the non-course types
#!# May be able to get rid of this now that all entries are defined explicitly, though check this doesn't disrupt the "how did you find this [name]?" label
var $types = array (
'courses' => array (
'name' => 'Courses',
'singular' => 'course',
'ia' => 0,
'ib' => 0,
'ii' => 0, /* Means unlimited, i.e. as many as are in the database */
),
'practicals' => array (
'name' => 'Practicals',
'singular' => 'practical',
#!# Need to get rid of this numbering system
'ia' => 5,
),
'projects' => array (
'name' => 'Projects',
'singular' => 'project',
'ib' => 3,
),
'dissertation' => array (
'name' => 'Dissertation',
'singular' => 'dissertation',
'ib' => 1,
'ii' => 1,
),
'fieldtrips' => array (
'name' => 'Fieldtrips',
'singular' => 'fieldtrip',
'ib' => 1,
),
'general' => array (
'name' => 'Learning resources and Personal development',
'singular' => 'aspect',
'ia' => 1,
'ib' => 1,
'ii' => 1,
),
);
# Fields to exclude in subcourse mode
private $subcourseModeExcludeFields = array ('q1howmany', 'q3stimulating', 'q4presentation', 'q5readinglists', );
# Pre-actions logic
public function mainPreActions ()
{
# Determine the current academic year, e.g. '2020-2021'
$this->currentAcademicYear = timedate::academicYear ($this->settings['yearStartMonth'], $asRangeString = true);
# Override the current year if fixed
if ($this->settings['overrideYear']) {
$this->currentAcademicYear = $this->settings['overrideYear'];
}
# Get the user details
$this->userDetails = $this->getUserDetails ();
# Students can never see results
$this->userHasResultsAccess = ($this->userDetails && ($this->userDetails['type'] != 'student'));
}
# Constructor
public function main ()
{
# Do not load these on the generic feedback page
if ($this->action == 'feedback') {return;}
# Version tables by year if required
if ($this->action != 'results') { // Results can switch year so should run year versioning itself
$this->yearVersioning ($this->currentAcademicYear);
}
# Perform data integrity checks or end
if (!$this->userDataIntegrity ()) {return false;}
# Confirm the user exists
if (!$this->userDetails) {
echo "\n<p>Welcome. You do not appear to be registered on this system. If you think you should be, please <a href=\"{$this->baseUrl}/feedback.html\">contact the Webmaster</a>.</p>";
return false;
}
# Override the current year if fixed
if ($this->settings['overrideUserYeargroup']) {$this->userDetails['yeargroup'] = $this->settings['overrideUserYeargroup'];}
# Make a hash of the user's year; note that this is taken from the database-retrieved value to prevent any encoding mismatches
$this->userMd5 = md5 ($this->userDetails['crsid']);
# Determine which courses the user can access
$this->assessing = $this->getAssessing ($this->user);
# Get current data for this user
$this->submissions = $this->getSubmissionsOfCurrentUser ();
# Make a placeholder for the type and course ID of the current data page (if any)
$this->type = NULL;
$this->courseId = NULL;
# If the user is an administrator, run the duplicates check
if ($this->userIsAdministrator) {
$this->runDuplicatesCheck ();
}
}
# Overrides for particular years
private function yearVersioning ($currentAcademicYear)
{
// Any overrides would go here
}
# Function to run a duplicates check; this can happen when a form is submitted quickly, and so the switching between INSERT/UPDATE is too slow, i.e. Time-of-check-to-time-of-use condition
#!# Need to understand and eliminate the underlying issue, if it still exists
private function runDuplicatesCheck ()
{
$duplicatesProblemsHtml = '';
$checkTables = array ($this->tables['courses'], $this->tables['lecturers'], $this->tables['others']);
foreach ($checkTables as $checkTable) {
#!# Hard-coded year, not taking account of $this->settings['overrideYear']
$query = "SELECT
id,user,courseId, COUNT(courseId) AS 'Submissions for this {Username+Course}'
FROM {$this->settings['database']}.{$checkTable}
WHERE YEAR(`timestamp`) = " . date ('Y') . "
GROUP BY user,courseId
HAVING COUNT(courseId) > 1
;";
if ($results = $this->databaseConnection->getData ($query, "{$this->settings['database']}.{$checkTable}")) {
$phpmyadminUrl = "{$this->settings['phpmyadminUrl']}/tbl_select.php?db={$this->settings['database']}&table={$checkTable}";
$duplicatesProblemsHtml .= "\n<div class=\"box\">";
$duplicatesProblemsHtml .= "\n\t<p class=\"warning\">The following data in <strong><a href=\"" . htmlspecialchars ($phpmyadminUrl) . "\" target=\"_blank\">{$this->settings['database']}.{$checkTable}</a></strong> is duplicated (probably caused by multiple quick submissions), as found by this query:</p>";
$duplicatesProblemsHtml .= "\n\t<p class=\"warning\"><tt>{$query}</tt></p>";
$headings = $this->databaseConnection->getHeadings ($this->settings['database'], $checkTable);
$headings['id'] = 'id (ignore this)';
$duplicatesProblemsHtml .= application::htmlTable ($results, $headings, 'lines compressed', false);
$duplicatesProblemsHtml .= "\n</div>";
}
}
if ($duplicatesProblemsHtml) {
echo $duplicatesProblemsHtml;
application::utf8Mail ($this->settings['webmaster'], 'Duplicate data issue in course evaluations system', strip_tags ($duplicatesProblemsHtml), "From: {$this->settings['webmaster']}");
}
}
# Home page
public function home ()
{
# Welcome message
$html = "\n<p>Welcome. You are logged in as <strong>{$this->userDetails['name']}</strong>.</p>";
# Deal with the submission half
$html .= $this->submissionSystem ();
# Show the HTML
echo $html;
}
# Results
public function results ()
{
# Start the HTML
$html = '';
# Get the list of available years in the data
$years = $this->getAvailableYears ();
# If there is no selected year, redirect to a URL containing the current academic year, to ensure that results for the current year are always consistently at the same URL, not left as /results/
if (!isSet ($_GET['academicyear'])) {
$url = $_SERVER['_SITE_URL'] . $this->baseUrl . '/results/' . $this->currentAcademicYear . '/';
$html = application::sendHeader (302, $url);
echo $html;
return;
}
# Ensure the selected year is valid
if (!in_array ($_GET['academicyear'], $years)) {
$this->page404 ();
return false;
}
# Set the selected year
$selectedAcademicYear = $_GET['academicyear'];
# Version tables by year if required
$this->yearVersioning ($selectedAcademicYear);
# Show a droplist of years
$html .= $this->yearsDroplist ($years, $selectedAcademicYear);
# Show results
$html .= $this->showResults ($selectedAcademicYear);
# Show the HTML
echo $html;
}
# Function to get the list of available years in the data
private function getAvailableYears ($yearsBack = 5)
{
# Get the data
$query = "SELECT
DISTINCT year
FROM courses
WHERE (SUBSTR(year, 1, 4) >= (YEAR(CURDATE()) - {$yearsBack}))
ORDER BY year
;";
$years = $this->databaseConnection->getPairs ($query);
# Ensure the current academic year is present
$years = array_merge ($years, array ($this->currentAcademicYear));
# Return the list
return ($years);
}
# Function to create a droplist of years
private function yearsDroplist ($years, $defaultYear)
{
# Create the list of URLs
$urls = array ();
foreach ($years as $year) {
$url = $this->baseUrl . '/results/' . $year . '/';
$urls[$url] = $year;
}
# Get the selected value
$yearUrls = array_flip ($urls);
$selected = $yearUrls[$defaultYear];
# Create the droplist, which includes the redirection processor
$html = application::htmlJumplist ($urls, $selected, '', 'jumplist', 0, 'jumplist', $introductoryText = 'Show results for year:');
# Return the HTML
return $html;
}
# Function to export the result data to a CSV
public function export ()
{
# Show results
#!# Academic year currently fixed at current year
echo $this->showResults ($this->currentAcademicYear, $csv = true);
}
# Function to ensure various aspects of data integrity relating to usernames (that they are in the people database, that students are correctly marked as such and that there is no crossover)
private function userDataIntegrity ()
{
# Ensure the lecturers and students are all in the people database
#!# Get rid of the anomaly between lecturer/crsid
$check = array ('lecturers' => 'lecturer', 'entries' => 'crsid');
foreach ($check as $table => $field) {
$query = "SELECT DISTINCT {$field} FROM {$this->settings['database']}.{$table} WHERE year = '{$this->currentAcademicYear}' AND {$field} NOT IN (SELECT username FROM {$this->settings['globalPeopleDatabase']}.people);";
if ($data = $this->databaseConnection->getPairs ($query)) {
if ($this->action != 'import') {
// $error = "The following user(s) present in {$this->settings['database']}.{$table}.{$field} were not found in the user database ({$this->settings['globalPeopleDatabase']}.people) :\n\n" . print_r ($data, true);
$error = "The following user(s) present in the imported setup data are not matching any known user. Please check for any typos and update the data, or if the usernames are correct, add the users to the Contacts Database.\n\n" . print_r ($data, true);
echo $this->reportError ($error);
return false;
}
}
}
# Check that all students are marked as students (staffType: 1) and have the course as undergraduate*
#!# Need to eradicate direct lookup of staffType here - move to isUndergraduate as used elsewhere in this class
$query = "SELECT
DISTINCT crsid
FROM {$this->settings['database']}.entries
LEFT OUTER JOIN {$this->settings['globalPeopleDatabase']}.people ON {$this->settings['database']}.entries.crsid = {$this->settings['globalPeopleDatabase']}.people.username
WHERE
year = '{$this->currentAcademicYear}'
AND (
course__JOIN__people__courses__reserved NOT REGEXP '^undergraduate'
OR (
staffType__JOIN__people__staffType__reserved != '1'
AND staffType__JOIN__people__staffType__reserved != '2' /* This AND clause is to deal with Undergraduates who have gone onto be graduates, though is not ideal */
)
)
;";
if ($data = $this->databaseConnection->getPairs ($query)) {
$error = "The following user(s) present in {$this->settings['database']}.{$table}.{$field} were not marked as undergraduates in the user database ({$this->settings['globalPeopleDatabase']}.people) :\n\n" . print_r ($data, true);
//echo $this->reportError ($error);
//return false;
}
/*
#!# This is disabled as it is very slow - find a way to find the intersection of {$this->settings['database']}.entries.crsid and {$this->settings['database']}.lecturers.lecturer. This is probably slow because of the use of IN() rather than a join or subtable.
# Check that no-one is both a student is also a lecturer
$query = "
SELECT DISTINCT crsid AS user FROM {$this->settings['database']}.entries WHERE year = '{$this->currentAcademicYear}' AND crsid IN (SELECT lecturer FROM {$this->settings['database']}.lecturers WHERE year = '{$this->currentAcademicYear}')
UNION
SELECT DISTINCT lecturer AS user FROM {$this->settings['database']}.lecturers WHERE year = '{$this->currentAcademicYear}' AND lecturer IN (SELECT crsid FROM {$this->settings['database']}.entries WHERE year = '{$this->currentAcademicYear}')
";
if ($data = $this->databaseConnection->getPairs ($query, true)) {
$error = "The following user(s) appear as both an undergraduate in {$this->settings['database']}.entries.crsid and as a lecturer in {$this->settings['database']}.lecturers.lecturer :\n\n" . print_r ($data, true);
echo $this->reportError ($error);
return false;
}
*/
# Return true since all tests have been passed
return true;
}
# Function to get user details
private function getUserDetails ()
{
# Get the user (who must be 'active') from the master database or end
$returnFalseIfGone = true;
if (in_array ($this->user, $this->settings['additionalLecturersResultsAccess'])) {
$returnFalseIfGone = false;
}
# Get the user via the supplied callback
$userNameCallback = $this->settings['userNameCallback'];
$person = $userNameCallback ($this->user, $returnFalseIfGone);
# Determine the user type or end
if (!$userType = $this->userType ($person)) {
return false;
}
# Get the user's yeargroup (e.g. 'ia') if they are a student
#!# This needs to take account of overrideYear which effectively rewinds time and therefore their yeargroup will be different
$yearGroupOfUser = $this->yearGroupOfUser ($person, $userType);
if ($yearGroupOfUser === false) {
#!# Report error
return false;
}
# Assignments
#!# Refactor these out by changing them lower down the code hierarchy
$user = array (
'crsid' => $person['username'],
'name' => $person['name'],
'type' => $userType,
'yeargroup' => $yearGroupOfUser,
'resultsOtherCourses' => ($userType == 'administrator' || $userType == 'organiser'), // Full/restricted administrators can view other courses
'resultsOtherLecturers' => ($userType == 'administrator'), // Full administrators only
);
# Return the user
return $user;
}
# Function to determine a year group (applies to students only), e.g. 'ia'
private function yearGroupOfUser ($person, $userType)
{
# If not a student, return NULL signifying an empty (but correct) result
if ($userType != 'student') {return NULL;}
# Extract the year from the course, e.g. 'undergraduate2020' or 'undergraduate2020education' are '2020'
if (!preg_match ('([0-9]{4})', $person['course__JOIN__people__courses__reserved'], $matches)) {return false;}
$userStartYear = $matches[0];
# Get the groups
$groups = $this->undergraduateYearGroupsForCurrentAcademicYear ();
# End if not found
if (!isSet ($groups[$userStartYear])) {return false;}
# Lookup the year group
$yearGroup = $groups[$userStartYear];
# Return the year group, e.g. 'ia'
return $yearGroup;
}
# Function to determine the user type, which starts with the most restrictive first, then the local administrator database, for security
private function userType ($user)
{
# See also "SECURITY MODEL" section elsewhere in this file
# Check for a student in the people database (type is '1')
if ($user['isUndergraduate']) {
return 'student';
}
# Restricted administrators
if ($this->restrictedAdministrator) {
return 'organiser';
}
# Application admins
if ($this->userIsAdministrator) {
return 'administrator';
}
# Staff
#!# This is still too broad really
if ($user['isStaffInternal']) {
return 'lecturer';
}
# Graduates who teach
if ($user['isGraduate']) {
return 'lecturer';
}
# Hasn't been found
return false;
}
# Function to get the year groups
private function undergraduateYearGroupsForCurrentAcademicYear ()
{
# Get the current academic year, e.g. '2020'
$currentYearStart = timedate::academicYear ($this->settings['yearStartMonth']);
# Create a lookup between the year and the label
$groups = array (
$currentYearStart => 'ia',
($currentYearStart - 1) => 'ib',
($currentYearStart - 2) => 'ii',
);
# Return the groups
return $groups;
}
# Function to deal with data submission/viewing
public function data ()
{
# Ensure the facility is open
#!# Inconsistent here
if (!$this->facilityIsOpen ($html)) {
echo $html;
return false;
}
# Determine the type of module being assessed of viewed; this sets $this->type
if (!$this->determineType ()) {
$this->page404 ();
return false;
}
# Show the relevant form
$formFunction = $this->type . 'Form'; // e.g. coursesForm, fieldtripsForm, practicalsForm, projectsForm, generalForm
$this->{$formFunction} ();
}
# Function to determine the type of module being assessed or viewed
#!# Should these checks be run if in home() rather than data() ?
private function determineType ()
{
# End if no assessing
if (!$this->assessing) {return false;}
# Ensure that the URL hasn't been fiddled; all these parameters should be set, even if they are not empty
$parameters = array ('action', 'year', 'yeargroup', 'module', 'item');
foreach ($parameters as $parameter) {
if (!isSet ($_GET[$parameter])) {
return false;
}
}
#!# Ensure the year and yeargroup are correct, e.g. {baseUrl}/2100-2102/ia/fieldtrips/berlin/ works!
# Determine the current overall type and the specific module; hence if the module type is not found, default to courses
foreach ($this->types as $type => $attributes) {
# Check for a generic module type (i.e. fieldtrip/practical/project
if ($_GET['module'] == $type) {
# Skip if this type isn't being assessed (this would be due to the user fiddling the URL)
if (!isSet ($this->assessing[$type])) {continue;}
# If found, sanity-check that there enough available projects for the number to be assessed in this yeargroup
if (count ($this->assessing[$type]) < $attributes[$this->userDetails['yeargroup']]) {
#!# Use generic error-throwing stuff
$errorMessage = 'Data mismatch: There are not enough available projects for the number to be assessed in this yeargroup.';
application::utf8Mail ($this->settings['webmaster'], 'System error in course evaluations', wordwrap ($errorMessage), "From: {$this->settings['webmaster']}");
return false;
}
# Set the particular item if a particular item is set
if ($_GET['item']) {
foreach ($this->assessing[$type] as $index => $course) {
if ($_GET['item'] == $course['url']) {
$this->type = $type;
$this->courseId = $index;
return true;
}
}
# If not found, then an incorrect item has been submitted
if (!$this->courseId) {
return false;
}
}
# Otherwise set only the type
$this->type = $type;
return true;
}
}
# No type found, so it should be a course; ensure the specified course is within the user's list of those being assessed, and assign it
foreach ($this->assessing['courses'] as $index => $course) {
if ($_GET['module'] == $course['url']) {
$this->type = 'courses';
$this->courseId = $index;
return true;
}
}
# Type not found
return false;
}
# Courses form
private function coursesForm ()
{
# Determine which course
$course = ($this->assessing['courses'][$this->courseId]);
# Get the course title
$courseTitle = /* strtoupper ($course['yeargroup']) . ' ' . */ htmlspecialchars ($course['title']);
# Get the lecturers for this course
$courseUrl = $_GET['module'];
$lecturers = $this->getLecturers ($courseUrl);
# In some cases, the courses have subcourses, so always regroup lecturers, so that we can add headers below (which will only happen if there is a subcourse) between each group
$lecturersBySubcourse = application::regroup ($lecturers, 'subcourseName', false); // We actually want to sort by subcourseId but show subcourseName; however, application::regroup works through the grouping in order, so the ORDER BY subcourseId will be maintained naturally
$subcourseMode = (count ($lecturersBySubcourse) != 1);
# Create the form
$form = new form (array (
'displayRestrictions' => false,
'databaseConnection' => $this->databaseConnection,
'nullText' => '',
'formCompleteText' => "Thanks for submitting your evaluation. Please now return to the <a href=\"{$this->baseUrl}/\">main overview page</a> (though you can <a href=\"{$_SERVER['REQUEST_URI']}\">edit this submission further</a> if necessary).",
'linebreaks' => false,
'div' => 'ultimateform assessments courses',
'titleReplacements' => array ('%type' => $this->types[$this->type]['singular']),
'rows' => 6,
'cols' => 50,
'unsavedDataProtection' => true,
));
# Introduction
$form->heading ('p', "This evaluation form for <strong>{$courseTitle}</strong> is divided into two sections: (i) the course overall, and (ii) an evaluation for each lecturer who has given 4 or more lectures.<br /><br />");
# Databind the main course questions
$data['course'] = ((isSet ($this->submissions[$this->type]) && isSet ($this->submissions[$this->type][$this->courseId])) ? $this->submissions[$this->type][$this->courseId] : array ());
$isUpdate = (!empty ($data['course']));
$exclude = array ('id','user','courseId', 'timestamp');
if (!$subcourseMode) {
$alsoExclude = array ('qsubcoursemodeextra4connection', );
$exclude = array_merge ($exclude, $alsoExclude);
}
$table = $this->tables['courses'];
$attributes = array (
'q1howmany' => array ('heading' => array ('3' => "Overview: {$courseTitle}")),
'qsubcoursemodeextra4connection' => array ('required' => true, ),
'q4enjoy' => array ('title' => ($subcourseMode ? '5' : '4') . '. Which aspect of the course did you particularly enjoy?', ),
'q5improvement' => array ('title' => ($subcourseMode ? '6' : '5') . '. Do you have any suggestions on how the course might be improved?', ),
);
$attributes = $this->overrideQuestionLabels ($table, $attributes);
$form->dataBinding (array (
'database' => $this->settings['database'],
'table' => $table,
'prefix' => "course{$course['id']}",
'exclude' => $exclude,
'data' => $data['course'],
'attributes' => $attributes,
));
# Databind the form for each lecturer
$form->heading (3, "Lecturers: {$courseTitle}");
$totalLecturers = count ($lecturers);
$form->heading ('p', ($totalLecturers == 1 ? 'There is a separate evaluation for the lecturer:' : "There is a separate evaluation for each of the {$totalLecturers} lecturers:"));
# State that they can skip any lecturer if required
if (count ($lecturersBySubcourse) > 1) {
$form->heading ('', '<p class="noteskippable">Please make any comments on any specific lecture material in the space provided below. (Then click Submit at end.)</p>');
}
$data['lecturers'] = array ();
foreach ($lecturersBySubcourse as $subcourse => $lecturers) {
# Determine the fields to exclude
$exclude = array ('id','user','timestamp');
# In subcourse mode, add a subheading
if ($subcourseMode) {
$form->heading ('', '<h4>' . htmlspecialchars ($subcourse) . '</h4>');
$exclude = array_merge ($exclude, $this->subcourseModeExcludeFields);
}
# Add this block
$table = $this->tables['lecturers'];
foreach ($lecturers as $key => $lecturer) {
$data['lecturers'][$key] = ((isSet ($this->submissions['lecturers']) && isSet ($this->submissions['lecturers'][$key])) ? $this->submissions['lecturers'][$key] : array ());
$attributes = array (
'lecturerId' => array ('type' => 'select', 'editable' => false, 'values' => array ($lecturer['id'] => $lecturer['name']), 'default' => $lecturer['id']),
'q1howmany' => array ('required' => true, ),
'q2overall' => array ('required' => true, ),
'q6enjoy' => array ('rows' => 4, 'title' => ($subcourseMode ? '1' : '6') . '. Which aspect of this set of lectures did you particularly enjoy?', ),
'q7improvement' => array ('rows' => 4, 'title' => ($subcourseMode ? '2' : '7') . '. Do you have any suggestions on how this set of lectures might be improved?', ),
);
$attributes = $this->overrideQuestionLabels ($table, $attributes);
$form->dataBinding (array (
'database' => $this->settings['database'],
'table' => $table,
'data' => $data['lecturers'][$key],
'prefix' => "lecturer{$key}",
'exclude' => $exclude,
'attributes' => $attributes,
));
}
}
# Show the results on screen
$form->setOutputScreen ();
# Send a backup copy to the administrator
$subject = "Course evaluation: {$this->user} - {$this->userDetails['yeargroup']} - {$this->type} - {$courseUrl}" . ($isUpdate ? ' (update)' : '');
$form->setOutputEmail ($this->settings['webmaster'], $this->settings['webmaster'], $subject, "From: {$this->settings['webmaster']}");
# Obtain the result
if (!$result = $form->process ()) {return false;}
# Insert the course data
$action = ($isUpdate ? 'update' : 'insert');
$keying = array (
'user' => $this->userMd5,
'courseId' => $course['id'],
);
$conditions = ($isUpdate ? $keying : false);
$result["course{$course['id']}"] += $keying;
if (!$this->databaseConnection->$action ($this->settings['database'], $this->tables['courses'], $result["course{$course['id']}"], $conditions)) {
#!# Use generic error-throwing stuff
application::utf8Mail ($this->settings['webmaster'], 'System error in course evaluations', wordwrap ("{$action} failed for {$this->settings['database']}.{$this->tables['courses']} with data:\n\n" . print_r ($result["course{$course['id']}"], 1)), "From: {$this->settings['webmaster']}");
echo "<p>There was a problem " . ($isUpdate ? 'updating' : 'inserting') . " the data. The webmaster has been informed.</p>";
}
# Insert the lecturer data
#!# Now that the subcourse grouping is in, ideally this would put the insert as a single insertMany query, but there would need to be an updateMany also, which wouldn't be any more efficient
foreach ($lecturersBySubcourse as $subcourse => $lecturers) {
foreach ($lecturers as $key => $lecturer) {
$isUpdate = (!empty ($data['lecturers'][$key]));
$action = ($isUpdate ? 'update' : 'insert');
$keying = array (
'user' => $this->userMd5,
'lecturerId' => $key,
);
$result["lecturer{$key}"] += $keying;
$result['user'] = $this->userMd5;
$conditions = ($isUpdate ? $keying : false);
if (!$this->databaseConnection->$action ($this->settings['database'], $this->tables['lecturers'], $result["lecturer{$key}"], $conditions)) {
#!# Use generic error-throwing stuff
application::utf8Mail ($this->settings['webmaster'], 'System error in course evaluations', wordwrap ("{$action} failed for {$this->settings['database']}.{$this->tables['lecturers']} with data:\n\n" . print_r ($result["lecturer{$key}"], 1)), "From: {$this->settings['webmaster']}");
echo "<p>There was a problem " . ($isUpdate ? 'updating' : 'inserting') . " the data. The webmaster has been informed.</p>";
}
}
}
}
# Function to merge in overriden question labels
#!# Need to add support for e.g. '2021-2022+' to cover future years
private function overrideQuestionLabels ($currentTable, $definitions, $format = 'form' /* or results */)
{
# Loop through each supplied override year, if any
foreach ($this->settings['overrideQuestionLabels'] as $academicYear => $tables) {
if ($academicYear != $this->currentAcademicYear) {continue;} // Skip if not matching
foreach ($tables as $type => $questions) {
# Format for use in a form
if ($format == 'form') {
$table = $this->tables[$type];
if ($table == $currentTable) { // Ensure matching table
foreach ($questions as $questionFieldname => $title) {
$definitions[$questionFieldname]['title'] = $title;
}
}
}
# Format for use in results
if ($format == 'results') {
foreach ($questions as $questionFieldname => $title) {
$definitions[$questionFieldname] = $title;
}
}
}
}
# Return the overriden attributes
return $definitions;
}
# Fieldtrips form
private function fieldtripsForm ()
{
$this->createForm ($this->tables['others']);
}
# Practicals form
private function practicalsForm ()
{
$this->createForm ($this->tables['others']);
}
# Projects form
private function projectsForm ()
{
$this->createForm ($this->tables['others']);
}
# Dissertation form
private function dissertationForm ()
{
$this->createForm ($this->tables['dissertation']);
}
# General form
private function generalForm ()
{
$this->createForm ($this->tables['general'], 'Section');
}
# Others form
private function createForm ($table, $label = 'Course')
{
# Get the data about each module
foreach ($this->assessing[$this->type] as $key => $module) {
$title = trim ($module['title']);
$titles[$module['url']] = $title;
$modules[$module['url']] = "<a href=\"{$module['link']}\">{$title}</a>";
}
# Get any data already submitted for this item
$data[$this->type] = ($this->submissions && (isSet ($this->submissions[$this->type]) && isSet ($this->submissions[$this->type][$this->courseId])) ? $this->submissions[$this->type][$this->courseId] : array ());
# If there is no data submitted for this item, check the totals to ensure the user is not submitting more than they are allowed to assess
if (!$data[$this->type]) {
$totalSubmissions = (($this->submissions && isSet ($this->submissions[$this->type])) ? count ($this->submissions[$this->type]) : 0);
$allowableSubmissions = $this->types[$this->type][$this->userDetails['yeargroup']];
if ($totalSubmissions == $allowableSubmissions) {
echo "<p>You cannot submit any more {$this->types[$this->type]['singular']} submissions as you have already submitted the maximum number ({$allowableSubmissions}) allowed.</p>";
return false;
}
}
# If there is no item, force selection (a present 'item' will have been validated by now
if (empty ($_GET['item'])) {
echo "<p>Please firstly select which <strong>{$this->types[$this->type]['singular']}</strong> you want to assess:</p>";
echo application::htmlUl ($modules);
return false;
}
# Determine if this is an update
$isUpdate = (!empty ($data[$this->type]));
# Assign the title
$title = $titles[$_GET['item']];
# Create the form