-
Notifications
You must be signed in to change notification settings - Fork 28
/
Copy pathlib.php
executable file
·951 lines (808 loc) · 34.4 KB
/
lib.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
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Library function for the quizaccess_proctoring plugin.
*
* @package quizaccess_proctoring
* @author Brain station 23 <brainstation-23.com>
* @copyright 2024 Brain station 23
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
defined('MOODLE_INTERNAL') || die();
$token = "";
/**
* Serves files for the quizaccess proctoring plugin.
*
* This function handles the process of serving files that are stored in the file storage for the quizaccess proctoring plugin.
* It retrieves the requested file based on the file area, item ID, and path, and then sends the file to the user.
*
* @param stdClass $course The course object.
* @param stdClass $cm The course module object.
* @param context $context The context within which the file is being served.
* @param string $filearea The name of the file area where the file is stored.
* @param array $args Extra arguments used to locate the file, including itemid and the path.
* @param bool $forcedownload Whether or not the file should be forced to download.
* @param array $options Additional options affecting the file serving.
*
* @return bool Returns false if the file cannot be found.
*/
function quizaccess_proctoring_pluginfile($course, $cm, $context, $filearea, $args, $forcedownload, array $options = []) {
if ( $filearea == 'picture' || $fileare =='face_image' ) {
if (!has_capability('quizaccess/proctoring:viewreport', $context) && !is_siteadmin() ) {
throw new moodle_exception('nopermission', 'quizaccess_proctoring');
}
}
$itemid = array_shift($args);
$filename = array_pop($args);
if (!$args) {
$filepath = '/';
} else {
$filepath = '/' . implode('/', $args) . '/';
}
$fs = get_file_storage();
$file = $fs->get_file($context->id, 'quizaccess_proctoring', $filearea, $itemid, $filepath, $filename);
if (!$file) {
return false;
}
send_stored_file($file, 0, 0, $forcedownload, $options);
}
/**
* Returns the image URL of a specific user from the quizaccess proctoring plugin.
*
* This function retrieves the image associated with a specific user by searching the `user_photo`
* file area within the context of the system.
* It then constructs and returns the image URL for that user, if the image exists.
*
* @param int $userid The user ID for which the image URL is to be fetched.
*
* @return string|false The image URL if the image is found, or false if no image is found.
*/
function quizaccess_proctoring_get_image_url($userid) {
$context = context_system::instance();
$fs = get_file_storage();
if ($files = $fs->get_area_files($context->id, 'quizaccess_proctoring', 'user_photo')) {
foreach ($files as $file) {
if ($userid == $file->get_itemid() && $file->get_filename() != '.') {
// Build the File URL. Long process! But extremely accurate.
$fileurl = moodle_url::make_pluginfile_url(
$file->get_contextid(), $file->get_component(), $file->get_filearea(),
$file->get_itemid(), $file->get_filepath(), $file->get_filename(), true);
// Display the image.
$downloadurl = $fileurl->get_port() ?
$fileurl->get_scheme().'://'.$fileurl->get_host().$fileurl->get_path().':'.$fileurl->get_port() :
$fileurl->get_scheme().'://'.$fileurl->get_host().$fileurl->get_path();
return $downloadurl;
}
}
}
return false;
}
/**
* Returns the image file of a specific user.
*
* This function retrieves the image file associated with a specific user by searching the `user_photo` file area
* in the `quizaccess_proctoring` context. If an image is found, it also deletes the corresponding records from
* the `quizaccess_proctoring_user_images` and `quizaccess_proctoring_face_images` tables, ensuring that the
* image is removed from the database and the related image records are cleaned up.
*
* @param int $userid The user ID for which the image file is to be fetched.
*
* @return mixed The image file object if the image is found, or false if no image is found for the user.
*/
function quizaccess_proctoring_get_image_file($userid) {
global $DB;
$context = context_system::instance();
$fs = get_file_storage();
if ($files = $fs->get_area_files($context->id, 'quizaccess_proctoring', 'user_photo')) {
foreach ($files as $file) {
if ($userid == $file->get_itemid() && $file->get_filename() != '.') {
// Get the record ID from the database.
$recordid = $DB->get_field('quizaccess_proctoring_user_images', 'id', ['user_id' => $userid]);
// Delete the record from the database.
$DB->delete_records('quizaccess_proctoring_user_images', ['user_id' => $userid]);
// Delete associated row from proctoring_face_images table.
$DB->delete_records('quizaccess_proctoring_face_images', ['parentid' => $recordid]);
return $file;
}
}
}
return false;
}
/**
* Updates match result.
*
* This function updates the match result for a specific report in the `quizaccess_proctoring_logs` table.
* It takes the report ID, the similarity match result, and an AWS flag indicating the status of the analyzed images.
* The match result (similarity) is stored as an integer score, and the AWS flag indicates the result of the analysis.
*
* @param int $rowid The report ID (`rowid`) of the record to be updated.
* @param string $matchresult The similarity score, which will be converted to an integer.
* @param int $awsflag Flag indicating the status of the analyzed images (1/2/3).
*
* @return void This function does not return any value.
*/
function quizaccess_update_match_result($rowid, $matchresult, $awsflag) {
global $DB;
$score = (int)$matchresult;
// Prepare the record with fields to be updated.
$record = new stdClass();
$record->id = $rowid;
$record->awsflag = $awsflag;
$record->awsscore = $score;
// Update the record using Moodle's update_record method.
$DB->update_record('quizaccess_proctoring_logs', $record);
}
/**
* Execute face recognition task.
*
* This function fetches up to 5 tasks from the `quizaccess_proctoring_facematch_task` table, processes each task
* by performing a face recognition operation, and deletes the processed tasks. The face matching is done using the
* method specified in the `fcmethod` setting.
*
* The function supports the 'BS' method for face recognition, where it retrieves face images and calls the `quizaccess_extracted`
* function to perform the face matching. After processing, the task is removed from the table.
*
* @return bool Returns false if no records are found to process, otherwise performs the task and deletes processed records.
*/
function quizaccess_execute_fm_task() {
global $DB;
// Fetch up to 5 tasks using Moodle's API.
$tasks = $DB->get_records('quizaccess_proctoring_facematch_task', null, '', '*', 0, 5);
$facematchmethod = quizaccess_get_proctoring_settings('fcmethod');
foreach ($tasks as $row) {
$rowid = $row->id;
$reportid = $row->reportid;
if ($facematchmethod === 'BS') {
// Fetch face images.
list($userfaceimageurl, $webcamfaceimageurl) = quizaccess_get_face_images($reportid);
// Perform the face matching operation.
quizaccess_extracted($userfaceimageurl, $webcamfaceimageurl, $reportid);
// Delete the processed task using Moodle's delete_records.
$DB->delete_records('quizaccess_proctoring_facematch_task', ['id' => $rowid]);
} else {
echo 'Invalid face match method<br/>';
}
}
}
/**
* Execute face recognition logging task.
*
* This function fetches distinct records from the `quizaccess_proctoring_logs` table where the `awsflag` is 0, and then processes
* each record by logging specific quiz details for the corresponding user, course, and quiz ID. After logging the information,
* a success message is displayed.
*
* @return bool Returns false if no records are found to process, otherwise processes the records and logs the data.
*/
function quizaccess_log_facematch_task() {
global $DB;
// Fetch distinct records where awsflag is 0 using Moodle's get_records_sql.
$sql = 'SELECT DISTINCT courseid, quizid, userid FROM {quizaccess_proctoring_logs} WHERE awsflag = 0';
$records = $DB->get_records_sql($sql);
// Process each record.
foreach ($records as $record) {
$courseid = $record->courseid;
$quizid = $record->quizid;
$userid = $record->userid;
// Log specific quiz details.
quizaccess_log_specific_quiz($courseid, $quizid, $userid);
}
// Use Moodle's notification API for success messages.
echo 'Log success';
}
/**
* Log the analysis of a specific quiz for a student.
*
* This function fetches the user's profile image and updates the `awsflag` field to mark records as attempted.
* It then queries the `quizaccess_proctoring_logs` table to retrieve specific records for the quiz and student,
* checks a random limit for the number of records, and logs the results for each match task.
*
* @param int $courseid The ID of the course.
* @param int $cmid The ID of the course module.
* @param int $studentid The ID of the student.
*
* @return bool Returns `true` if records were processed, `false` if no record was found.
*/
function quizaccess_log_specific_quiz($courseid, $cmid, $studentid) {
global $DB;
// Get user profile image.
$user = core_user::get_user($studentid);
$profileimageurl = quizaccess_proctoring_get_image_url($studentid);
// Update all as attempted.
$DB->set_field('quizaccess_proctoring_logs', 'awsflag', 1, [
'courseid' => $courseid,
'quizid' => $cmid,
'userid' => $studentid,
]);
// Check random limit.
$limit = 5;
$awschecknumber = quizaccess_get_proctoring_settings('awschecknumber');
if ($awschecknumber !== '') {
$limit = (int)$awschecknumber;
}
// SQL queries as variables.
$basequery = "SELECT e.id AS reportid, e.userid AS studentid, e.webcampicture AS webcampicture,
e.status AS status, e.timemodified AS timemodified, u.firstname AS firstname,
u.lastname AS lastname, u.email AS email
FROM {quizaccess_proctoring_logs} e
INNER JOIN {user} u ON u.id = e.userid
WHERE e.courseid = :courseid AND e.quizid = :quizid AND u.id = :userid AND e.webcampicture != ''";
$randomquery = $basequery . " ORDER BY RAND() LIMIT :limit";
$params = [
'courseid' => $courseid,
'quizid' => $cmid,
'userid' => $studentid,
];
if ($limit === -1) {
$query = $basequery;
} else if ($limit > 0) {
$query = $randomquery;
$params['limit'] = $limit;
} else {
$query = $basequery;
}
// Execute the query.
$sqlexecuted = $DB->get_recordset_sql($query, $params);
// Process each result.
foreach ($sqlexecuted as $row) {
$reportid = $row->reportid;
$snapshot = $row->webcampicture;
echo $snapshot;
if ($snapshot !== '') {
$inserttaskrow = new stdClass();
$inserttaskrow->refimageurl = $profileimageurl;
$inserttaskrow->targetimageurl = $snapshot;
$inserttaskrow->reportid = $reportid;
$inserttaskrow->timemodified = time();
// Insert a new record for the face match task.
$DB->insert_record('quizaccess_proctoring_facematch_task', $inserttaskrow);
}
}
$sqlexecuted->close();
return true;
}
/**
* Analyze specific quiz images for face matching.
*
* This function fetches the user's profile image, redirects if not available,
* and processes the quiz records for the student. It fetches the webcam face
* images for the student, compares them with the profile image, and updates
* the face match status in the database. The function also handles logging
* of warnings and updating the `awsflag` status based on the results.
*
* @param int $courseid The ID of the course.
* @param int $cmid The ID of the course module.
* @param int $studentid The ID of the student.
* @param mixed $redirecturl The URL to redirect to in case the profile image is missing.
*
* @return bool Returns `true` if records were processed successfully, `false` if no records found.
*/
function quizaccess_bs_analyze_specific_quiz($courseid, $cmid, $studentid, $redirecturl) {
global $DB;
// Get user profile image.
$profileimageurl = quizaccess_proctoring_get_image_url($studentid);
$redirecturl = new moodle_url('/mod/quiz/accessrule/proctoring/upload_image.php', ['id' => $studentid]);
// Redirect if profile image is not available.
if (!$profileimageurl) {
redirect(
$redirecturl,
get_string('user_image_not_uploaded', 'mod_quiz'),
1,
\core\output\notification::NOTIFY_WARNING
);
}
// Update all as attempted.
$DB->set_field_select(
'quizaccess_proctoring_logs',
'awsflag',
1,
"courseid = :courseid AND quizid = :quizid AND userid = :userid AND awsflag = 0",
[
'courseid' => $courseid,
'quizid' => $cmid,
'userid' => $studentid,
]
);
// Check random limit.
$limit = 5;
$awschecknumber = quizaccess_get_proctoring_settings('awschecknumber');
if ($awschecknumber !== '') {
$limit = (int)$awschecknumber;
}
// Prepare SQL query and parameters.
$basequery = "SELECT e.id as reportid, e.userid as studentid, e.webcampicture as webcampicture,
e.status as status, e.timemodified as timemodified, u.firstname as firstname,
u.lastname as lastname, u.email as email
FROM {quizaccess_proctoring_logs} e
INNER JOIN {user} u ON u.id = e.userid
WHERE e.courseid = :courseid AND e.quizid = :quizid AND u.id = :userid AND e.webcampicture != ''";
$params = [
'courseid' => $courseid,
'quizid' => $cmid,
'userid' => $studentid,
];
if ($limit > 0) {
$basequery .= " ORDER BY RAND() LIMIT :limit";
$params['limit'] = $limit;
}
// Execute the query.
$sqlexecuted = $DB->get_recordset_sql($basequery, $params);
// Process each record.
foreach ($sqlexecuted as $row) {
$reportid = $row->reportid;
// Get face images for comparison.
list($userfaceimageurl, $webcamfaceimageurl) = quizaccess_get_face_images($reportid);
if (!$userfaceimageurl || !$webcamfaceimageurl) {
// Log warning if faces are not found.
quizaccess_log_fm_warning($reportid);
// Set awsflag = 3 if face not found.
quizaccess_update_match_result($reportid, 0, 3);
continue;
}
// Perform face extraction and comparison.
quizaccess_extracted($userfaceimageurl, $webcamfaceimageurl, $reportid);
}
// Close the recordset.
$sqlexecuted->close();
return true;
}
/**
* Get proctoring settings values from the database.
*
* This function retrieves the value of a specific proctoring setting for the
* plugin `quizaccess_proctoring` from the Moodle configuration table.
* If the setting is not found, it returns an empty string.
*
* @param string $settingtype The name of the setting to retrieve (e.g., 'awschecknumber').
*
* @return string The value of the specified setting, or an empty string if the setting is not found.
*/
function quizaccess_get_proctoring_settings($settingtype) {
global $DB;
// Query the settings table for the specified setting type.
$record = $DB->get_record('config_plugins', [
'plugin' => 'quizaccess_proctoring',
'name' => $settingtype,
], 'value', IGNORE_MISSING);
// Return the value or an empty string if the setting is not found.
return $record ? $record->value : '';
}
/**
* Analyze a specific image for face match and logging.
*
* This function performs analysis on a specific image associated with a report.
* It retrieves face images, performs a face match operation, and updates the database with the results.
* If the face images are not found, an error is logged, and the user is redirected with an error message.
*
* @param int $reportid The ID of the proctoring report record to analyze.
* @param mixed $redirecturl The URL to redirect to if an error occurs.
*
* @return bool Returns true if the analysis was successful, false if no record is found or if an error occurs.
*/
function quizaccess_bs_analyze_specific_image($reportid, $redirecturl) {
global $DB;
// Fetch the record for the specific report ID.
$reportdata = $DB->get_record('quizaccess_proctoring_logs', ['id' => $reportid], 'id, courseid, quizid, userid, webcampicture');
if (!$reportdata) {
redirect(
$redirecturl,
get_string('error_invalid_report', 'quizaccess_proctoring'),
1,
\core\output\notification::NOTIFY_ERROR
);
return false;
}
$studentid = $reportdata->userid;
$courseid = $reportdata->courseid;
$cmid = $reportdata->quizid;
// Retrieve face images.
list($userfaceimageurl, $webcamfaceimageurl) = quizaccess_get_face_images($reportid);
if (!$userfaceimageurl || !$webcamfaceimageurl) {
// Log a face match warning.
quizaccess_log_fm_warning($reportid);
// Update the match result with an error flag (awsflag = 3).
quizaccess_update_match_result($reportid, 0, 3);
// Redirect with an error message.
redirect(
$redirecturl,
get_string('error_face_not_found', 'quizaccess_proctoring'),
1,
\core\output\notification::NOTIFY_ERROR
);
return true;
}
// Update logs to mark all as attempted.
$DB->execute(
"UPDATE {quizaccess_proctoring_logs}
SET awsflag = 1
WHERE courseid = :courseid AND quizid = :quizid AND userid = :userid AND awsflag = 0",
[
'courseid' => $courseid,
'quizid' => $cmid,
'userid' => $studentid,
]
);
// Perform face extraction analysis.
quizaccess_extracted($userfaceimageurl, $webcamfaceimageurl, $reportid);
return true;
}
/**
* Analyze a specific image for face match and logging.
*
* This function performs analysis on a specific image associated with a report.
* It retrieves face images, performs a face match operation, and updates the database with the results.
* If the face images are not found, an error is logged, and the user is redirected with an error message.
*
* @param int $reportid The ID of the proctoring report record to analyze.
*
* @return bool Returns true if the analysis was successful, false if no record is found or if an error occurs.
*/
function quizaccess_bs_analyze_specific_image_from_validate($reportid) {
global $DB;
// Fetch report data from the database based on the provided report ID.
$reportdata = $DB->get_record('quizaccess_proctoring_logs', ['id' => $reportid], 'id, courseid, quizid, userid, webcampicture');
// If the report data exists, proceed with analysis.
if ($reportdata) {
$studentid = $reportdata->userid;
$courseid = $reportdata->courseid;
$cmid = $reportdata->quizid;
// Retrieve the user's face image and webcam image for comparison.
list($userfaceimageurl, $webcamfaceimageurl) = quizaccess_get_face_images($reportid);
// If either face image is not found, log the warning and update the result.
if (!$userfaceimageurl || !$webcamfaceimageurl) {
// Log the warning for face match.
quizaccess_log_fm_warning($reportid);
// Update the match result with flag indicating face match failure (awsflag = 3).
$awsflag = 3;
quizaccess_update_match_result($reportid, 0, $awsflag);
return;
}
// Update all logs as attempted by setting awsflag to 1.
$DB->execute(
"UPDATE {quizaccess_proctoring_logs}
SET awsflag = 1
WHERE courseid = :courseid AND quizid = :quizid AND userid = :userid AND awsflag = 0",
[
'courseid' => $courseid,
'quizid' => $cmid,
'userid' => $studentid,
]
);
// Perform the extraction process for face images.
quizaccess_extracted($userfaceimageurl, $webcamfaceimageurl, $reportid);
}
return true;
}
/**
* Retrieve the face images for a specific report.
*
* This function fetches both the user's face image and the webcam face image associated with
* a given proctoring report. If the user's image is not uploaded, it redirects to the image upload page.
* If no images are found, the function returns `null` for both face images.
*
* @param int $reportid The ID of the proctoring report to fetch the images for.
*
* @return array An array containing the user's face image URL and the webcam face image URL.
* Both values will be `null` if no images are found.
*/
function quizaccess_get_face_images($reportid) {
global $DB;
// Fetch report data for the given report ID.
$reportdata = $DB->get_record('quizaccess_proctoring_logs', ['id' => $reportid]);
if (!$reportdata) {
return [null, null];
}
$studentid = $reportdata->userid;
// Fetch webcam face images associated with the report.
$webcamfaceimage = $DB->get_records(
'quizaccess_proctoring_face_images',
[
'parentid' => $reportid,
'parent_type' => 'camshot_image',
'facefound' => 1,
]
);
$webcamfaceimageurl = '';
if ($webcamfaceimage) {
// If there are multiple webcam images, use the first one.
$firstwebcamimage = reset($webcamfaceimage);
$webcamfaceimageurl = $firstwebcamimage->faceimage;
}
// Fetch user image data.
$userimagerow = $DB->get_record('quizaccess_proctoring_user_images', ['user_id' => $studentid]);
$redirecturl = new moodle_url('/mod/quiz/accessrule/proctoring/upload_image.php', ['id' => $studentid]);
// If user image is not uploaded, redirect to upload page with a warning.
if (!$userimagerow) {
redirect(
$redirecturl,
get_string('userimagenotuploaded', 'quizaccess_proctoring'),
1,
\core\output\notification::NOTIFY_WARNING
);
}
// Fetch the face image associated with the user's image.
$userfaceimageurl = '';
if ($userimagerow) {
$userfaceimagerow = $DB->get_record(
'quizaccess_proctoring_face_images',
['parentid' => $userimagerow->id, 'parent_type' => 'admin_image']
);
if ($userfaceimagerow) {
$userfaceimageurl = $userfaceimagerow->faceimage;
}
}
return [$userfaceimageurl, $webcamfaceimageurl];
}
/**
* Gets the similarity result and checks with the threshold mentioned in the config.
*
* This function compares the face images using a face similarity function and evaluates the result
* against a threshold value specified in the configuration. If the similarity is below the threshold,
* a warning is logged. The result is then updated in the database.
*
* @param string $profileimageurl URL of the profile image to compare.
* @param string $targetimage URL of the target image to compare against.
* @param int $reportid The ID of the report associated with the image comparison.
*
* @return void
*/
function quizaccess_extracted(string $profileimageurl, string $targetimage, int $reportid): void {
// Get the similarity result from the image comparison function.
$similarityresult = quizaccess_check_similarity_bs($profileimageurl, $targetimage);
// Decode the JSON response from the similarity check.
$response = json_decode($similarityresult);
// Fetch the threshold for face matching.
$threshold = (float) quizaccess_get_proctoring_settings('threshold');
// Initialize similarity variable.
$similarity = 0;
// Ensure response is valid and contains the expected data.
if ($response && $response->statusCode == 200 && isset($response->body->distance)) {
// Check if the distance is within the allowed threshold.
if ($response->body->distance <= $threshold / 100) {
$similarity = 100;
} else {
// Log a warning if the distance is above threshold.
quizaccess_log_fm_warning($reportid);
}
} else {
// Log a warning if the response is invalid or if no matching data is found.
quizaccess_log_fm_warning($reportid);
}
// Update the match result in the database with the calculated similarity.
quizaccess_update_match_result($reportid, $similarity, 2);
}
/**
* Returns face match similarity.
*
* This function sends two images (reference image and target image) to an external API for face comparison
* and returns the similarity check result. It ensures that the necessary API settings (URL and key) are
* available, then fetches the images, processes them, and sends a request to the API.
* If the request succeeds, the API response is returned. Otherwise, an error is logged.
*
* @param string $referenceimageurl The URL of the reference image (profile image).
* @param string $targetimageurl The URL of the target image (webcam image).
*
* @return bool|string The API response as a string, or false on failure.
*/
function quizaccess_check_similarity_bs(string $referenceimageurl, string $targetimageurl) {
global $CFG;
// Fetch the required API settings.
$bsapi = quizaccess_get_proctoring_settings('bsapi');
$bsapikey = quizaccess_get_proctoring_settings('bs_api_key');
// Ensure the API URL and key are available.
if (empty($bsapi) || empty($bsapikey)) {
// Log an error and return early if API URL or key are missing.
mtrace('Error: Missing BS API URL or API key.');
return false;
}
// Load images from the provided URLs and save them temporarily.
$image1 = basename($referenceimageurl);
$image2 = basename($targetimageurl);
$imagepath1 = $CFG->dataroot . '/temp/' . $image1;
$imagepath2 = $CFG->dataroot . '/temp/' . $image2;
// Download and save the reference and target images.
if (!file_put_contents($imagepath1, file_get_contents($referenceimageurl)) ||
!file_put_contents($imagepath2, file_get_contents($targetimageurl))) {
// Log error if images cannot be saved.
mtrace("Error: Unable to save images to temporary directory.");
return false;
}
// Get image data for API request.
$imagedata1 = file_get_contents($imagepath1);
$imagedata2 = file_get_contents($imagepath2);
// Prepare the data for the API request.
$data = [
'original_img_response' => base64_encode($imagedata1),
'face_img_response' => base64_encode($imagedata2),
];
// JSON encode the payload for the API request.
$payload = json_encode($data);
// Initialize cURL to send the request to the API.
$curl = curl_init();
curl_setopt_array($curl, [
CURLOPT_URL => $bsapi,
CURLOPT_HTTPHEADER => [
'x-api-key: ' . $bsapikey,
'Content-Type: application/json',
],
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 0,
CURLOPT_FOLLOWLOCATION => false,
CURLOPT_SSL_VERIFYHOST => false,
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => 'POST',
CURLOPT_POSTFIELDS => $payload,
]);
// Execute the cURL request and capture the response.
$response = curl_exec($curl);
$curlerror = curl_error($curl);
// Close cURL connection.
curl_close($curl);
// Handle cURL errors.
if ($curlerror) {
mtrace("Error: cURL request failed - " . $curlerror);
return false;
}
// Clean up the temporary images.
unlink($imagepath1);
unlink($imagepath2);
// Return the response from the API.
return $response;
}
/**
* Retrieves an authentication token from the BS API.
*
* This function sends a request to the BS API using the provided username and password,
* retrieves an authentication token, and returns it. If any required settings are missing
* or an error occurs during the request, it returns `false`.
*
* @return string|false The token on success or false on failure.
*/
function quizaccess_get_token() {
global $CFG;
// Fetch required settings from proctoring settings.
$bsapi = quizaccess_get_proctoring_settings('bsapi') . '/get_token';
$bsusername = quizaccess_get_proctoring_settings('username');
$bspassword = quizaccess_get_proctoring_settings('password');
// Check if all required settings are available.
if (empty($bsapi) || empty($bsusername) || empty($bspassword)) {
mtrace('Error: Missing BS API URL, username, or password.');
return false; // Return false if any required setting is missing.
}
// Prepare cURL request to get the token.
$curl = curl_init();
curl_setopt_array($curl, [
CURLOPT_URL => $bsapi,
CURLOPT_HTTPHEADER => [
'Content-Type: multipart/form-data',
],
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => '',
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30, // Set a reasonable timeout for the request.
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => 'POST',
CURLOPT_POSTFIELDS => [
'username' => $bsusername,
'password' => $bspassword,
],
]);
// Execute the cURL request.
$response = curl_exec($curl);
// Check for cURL errors.
if (curl_errno($curl)) {
mtrace('cURL Error: ' . curl_error($curl));
curl_close($curl);
return false; // Return false on cURL error.
}
// Close the cURL session.
curl_close($curl);
// Decode the JSON response.
$tokendata = json_decode($response);
// Check if the token was received in the response.
if (isset($tokendata->token)) {
return $tokendata->token; // Return the token.
}
// Log error if token is not found in the response.
mtrace('Error: Token not found in the response.');
return false; // Return false if token is not found.
}
/**
* Logs a face matching warning for the given report ID.
*
* This function checks if a warning already exists for a particular user, course, and quiz.
* If no warning exists, it inserts a new record into the `quizaccess_proctoring_fm_warnings` table.
* If the report cannot be found, it logs an error message.
*
* @param int $reportid The report ID for which the warning is being logged.
*
* @return void
*/
function quizaccess_log_fm_warning(int $reportid): void {
global $DB;
// Fetch the report data.
$report = $DB->get_record('quizaccess_proctoring_logs', ['id' => $reportid]);
// Check if the report exists.
if ($report) {
// Extract necessary data.
$userid = $report->userid;
$courseid = $report->courseid;
$quizid = $report->quizid;
// Check if a warning already exists for this user, course, and quiz.
$existingwarning = $DB->get_record('quizaccess_proctoring_fm_warnings', [
'userid' => $userid,
'courseid' => $courseid,
'quizid' => $quizid,
]);
// If no warning exists, insert a new record.
if (!$existingwarning) {
// Prepare a new warning object.
$warning = new stdClass();
$warning->reportid = $reportid;
$warning->courseid = $courseid;
$warning->quizid = $quizid;
$warning->userid = $userid;
// Insert the new warning record into the database.
$DB->insert_record('quizaccess_proctoring_fm_warnings', $warning);
}
} else {
// Log a message if the report cannot be found.
mtrace('Error: Report ID ' . $reportid . ' not found.');
}
}
/**
* Saves the face image as a file and returns its URL.
*
* This function decodes a base64 string, saves the image as a file in Moodle's file system,
* and returns a URL to access the file.
*
* @param string $data The base64 encoded image data.
* @param int $userid The ID of the user who uploaded the image.
* @param stdClass $record The file record that contains metadata.
* @param context $context The context for the file (usually the course or activity context).
* @param stored_file_system $fs The file storage system instance.
* @return moodle_url The URL to access the saved face image.
*/
function quizaccess_proctoring_geturl_of_faceimage(string $data, int $userid, stdClass $record, $context, $fs): moodle_url {
// Remove any metadata from the base64 string.
list(, $data) = explode(',', $data);
// Decode the base64 data into raw binary image data.
$data = base64_decode($data);
// Generate a unique filename for the image.
$filename = 'faceimage-' . $userid . '-' . time() . random_int(1, 1000) . '.png';
// Set the filename and context ID in the file record.
$record->filename = $filename;
$record->contextid = $context->id;
$record->userid = $userid;
// Ensure the file is created in Moodle's file storage system.
try {
$fs->create_file_from_string($record, $data);
} catch (Exception $e) {
// Handle any exceptions during file storage creation.
throw new moodle_exception('filecreationerror', 'error', '', $e->getMessage());
}
// Return the URL to access the stored file.
return moodle_url::make_pluginfile_url(
$context->id,
$record->component,
$record->filearea,
$record->itemid,
$record->filepath,
$record->filename,
false
);
}