-
Notifications
You must be signed in to change notification settings - Fork 28
/
lib.php
838 lines (738 loc) · 26.6 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
<?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 ltd <brainstation-23.com>
* @copyright 2022 Brain station 23 ltd
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
defined('MOODLE_INTERNAL') || die();
/**
* Generic select statement to be reused.
*/
const GENERIC_SELECT_STATMENT = ' SELECT e.id as reportid, e.userid as studentid, e.webcampicture as webcampicture,
e.status as status, ';
/**
* Generic select statement from proctoring logs table.
*/
const COMMON_SELECT = ' 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 ';
/**
* Temp folder constant.
*/
const TEMP = '/temp/';
/**
* Time modified part of query.
*/
const TIMEMODIFIED_AS_TIMEMODIFIED =
' e.timemodified as timemodified, u.firstname as firstname, u.lastname as lastname, u.email as email ';
/**
* Query constants.
*/
const FROM_QUIZACCESS_PROCTORING_LOGS_INNER_JOIN_USERS =
' from {quizaccess_proctoring_logs} e INNER JOIN {user} u ON u.id = e.userid ';
require_once(__DIR__ . '/vendor/autoload.php');
$token = "";
use Aws\Rekognition\RekognitionClient;
/**
* Serve the files.
*
* @param stdClass $course the course object
* @param stdClass $cm the course module object
* @param context $context the context
* @param string $filearea the name of the file area
* @param array $args extra arguments (itemid, path)
* @param bool $forcedownload whether or not force download
* @param array $options additional options affecting the file serving
*
* @return bool false if the file not found, just send the file otherwise and do not return anything
*/
function quizaccess_proctoring_pluginfile($course, $cm, $context, $filearea, $args, $forcedownload, array $options = []) {
$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.
*
* @param int $userid User id
* @return string imageurl
*/
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.
*
* @param int $userid User id
* @return mixed image file
*/
function quizaccess_proctoring_get_image_file($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() != '.') {
// Return the image file.
return $file;
}
}
}
return false;
}
/**
* Updates match result.
*
* @param int $rowid the reportid
* @param string $matchresult similarity
* @param int $awsflag Flag for status of the analyzed images (1/2/3)
*
* @return array similaritycheck
*/
function update_match_result($rowid, $matchresult, $awsflag) {
global $DB;
$score = (int)$matchresult;
$updatesql = "UPDATE {quizaccess_proctoring_logs} SET awsflag = '$awsflag', awsscore = '$score' WHERE id='$rowid'";
$DB->execute($updatesql);
}
/**
* Returns face match similarity.
*
* @param string $referenceimageurl the courseid
* @param string $targetimageurl the course module id
*
* @return array similaritycheck
*/
function check_similarity_aws($referenceimageurl, $targetimageurl) {
$awskey = get_proctoring_settings('awskey');
$awssecret = get_proctoring_settings('awssecret');
$threshhold = (int)get_proctoring_settings('awsfcthreshold');
$credentials = new Aws\Credentials\Credentials($awskey, $awssecret);
$rekognitionclient = RekognitionClient::factory([
'region' => 'us-east-1',
'version' => 'latest',
'credentials' => $credentials,
]);
try {
$comparefaceresult = $rekognitionclient->compareFaces([
'SimilarityThreshold' => $threshhold,
'SourceImage' => [
'Bytes' => file_get_contents($referenceimageurl),
],
'TargetImage' => [
'Bytes' => file_get_contents($targetimageurl),
],
]);
return $comparefaceresult['FaceMatches'];
} catch (Exception $e) {
return [];
}
}
/**
* Execute facerecognition task.
*
* @return bool false if no record found
*/
function execute_fm_task() {
global $DB;
// Get 5 task.
$sql = 'SELECT * FROM {proctoring_facematch_task} LIMIT 5';
$data = $DB->get_recordset_sql($sql);
$facematchmethod = get_proctoring_settings('fcmethod');
foreach ($data as $row) {
$rowid = $row->id;
$reportid = $row->reportid;
$refimageurl = $row->refimageurl;
$targetimageurl = $row->targetimageurl;
if ($facematchmethod == 'AWS') {
// Get Match result.
get_match_result($refimageurl, $targetimageurl, $reportid);
// Delete from task table.
$DB->delete_records('proctoring_facematch_task', ['id' => $rowid]);
} else if ($facematchmethod == 'BS') {
list($userfaceimageurl, $webcamfaceimageurl) = get_face_images($reportid);
extracted($userfaceimageurl, $webcamfaceimageurl, $reportid);
// Delete from task table.
$DB->delete_records('proctoring_facematch_task', ['id' => $rowid]);
} else {
echo 'Invalid fc method<br/>';
}
}
}
/**
* Returns the similarity result from AWS API call.
*
* @param $refimageurl
* @param $targetimageurl
* @param $reportid
*
* @return mixed similarityresult
*/
function get_match_result($refimageurl, $targetimageurl, $reportid): array {
$similarityresult = check_similarity_aws($refimageurl, $targetimageurl);
// Log AWS API Call.
$apiresponse = json_encode($similarityresult);
log_aws_api_call($reportid, $apiresponse);
// Update Match result.
if (!empty($similarityresult)) {
if (isset($similarityresult[0]['Similarity'])) {
$similarity = $similarityresult[0]['Similarity'];
} else {
$similarity = 0;
log_fm_warning($reportid);
}
} else {
$similarity = 0;
log_fm_warning($reportid);
}
update_match_result($reportid, $similarity, 2);
return [$similarityresult, $similarity];
}
/**
* Execute facerecognition task.
*
* @return bool false if no record found
*/
function log_facematch_task() {
global $DB;
$sql = 'SELECT DISTINCT courseid,quizid,userid FROM {quizaccess_proctoring_logs} WHERE awsflag = 0';
$data = $DB->get_recordset_sql($sql);
foreach ($data as $row) {
$courseid = $row->courseid;
$quizid = $row->quizid;
$userid = $row->userid;
log_specific_quiz($courseid, $quizid, $userid);
}
echo 'Log success';
}
/**
* Log for analysis.
*
* @param int $courseid the courseid
* @param int $cmid the course module id
* @param int $studentid the context
*
* @return bool false if no record found
*/
function log_specific_quiz($courseid, $cmid, $studentid) {
global $DB;
// Get user profile image.
$user = core_user::get_user($studentid);
$profileimageurl = '';
$profileimageurl = quizaccess_proctoring_get_image_url($studentid);
// Update all as attempted.
$updatesql = 'UPDATE {quizaccess_proctoring_logs}'
. 'SET awsflag = 1'
. "WHERE courseid = '$courseid' AND quizid = '$cmid' AND userid = '$studentid'";
$DB->execute($updatesql);
// Check random.
$limit = 5;
$awschecknumber = get_proctoring_settings('awschecknumber');
if ($awschecknumber != '') {
$limit = (int)$awschecknumber;
}
if ($limit == -1) {
$sql = GENERIC_SELECT_STATMENT . COMMON_SELECT
. " WHERE e.courseid = '$courseid' AND e.quizid = '$cmid' AND u.id = '$studentid' AND e.webcampicture != '' ";
} else if ($limit > 0) {
$sql = GENERIC_SELECT_STATMENT
. TIMEMODIFIED_AS_TIMEMODIFIED
. FROM_QUIZACCESS_PROCTORING_LOGS_INNER_JOIN_USERS
. " WHERE e.courseid = '$courseid' AND e.quizid = '$cmid' AND u.id = '$studentid' AND e.webcampicture != '' "
. ' ORDER BY RAND() '
. " LIMIT $limit ";
} else {
$sql = GENERIC_SELECT_STATMENT
. TIMEMODIFIED_AS_TIMEMODIFIED
. FROM_QUIZACCESS_PROCTORING_LOGS_INNER_JOIN_USERS
. " WHERE e.courseid = '$courseid' AND e.quizid = '$cmid' AND u.id = '$studentid' AND e.webcampicture != ''";
}
$sqlexecuted = $DB->get_recordset_sql($sql);
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();
$DB->insert_record('proctoring_facematch_task', $inserttaskrow);
}
}
return true;
}
/**
* Analyze specific Quiz images.
*
* @param int $courseid the courseid
* @param int $cmid the course module id
* @param int $studentid the context
*
* @return bool false if no record found
*/
function aws_analyze_specific_quiz($courseid, $cmid, $studentid) {
global $DB;
// Get user profile image.
$user = core_user::get_user($studentid);
$profileimageurl = '';
$profileimageurl = quizaccess_proctoring_get_image_url($studentid);
// Update all as attempted.
$updatesql = ' UPDATE {quizaccess_proctoring_logs} '
. ' SET awsflag = 1 '
. " WHERE courseid = '$courseid' AND quizid = '$cmid' AND userid = '$studentid' AND awsflag = 0 ";
$DB->execute($updatesql);
// Check random.
$limit = 5;
$awschecknumber = get_proctoring_settings('awschecknumber');
if ($awschecknumber != '') {
$limit = (int)$awschecknumber;
}
if ($limit == -1) {
$sql = GENERIC_SELECT_STATMENT
. TIMEMODIFIED_AS_TIMEMODIFIED
. FROM_QUIZACCESS_PROCTORING_LOGS_INNER_JOIN_USERS
. " WHERE e.courseid = '$courseid' AND e.quizid = '$cmid' AND u.id = '$studentid' AND e.webcampicture != '' ";
} else if ($limit > 0) {
$sql = GENERIC_SELECT_STATMENT
. TIMEMODIFIED_AS_TIMEMODIFIED
. FROM_QUIZACCESS_PROCTORING_LOGS_INNER_JOIN_USERS
. " WHERE e.courseid = '$courseid' AND e.quizid = '$cmid' AND u.id = '$studentid' AND e.webcampicture != '' "
. ' ORDER BY RAND() '
. " LIMIT $limit";
} else {
$sql = GENERIC_SELECT_STATMENT
. TIMEMODIFIED_AS_TIMEMODIFIED
. FROM_QUIZACCESS_PROCTORING_LOGS_INNER_JOIN_USERS
. " WHERE e.courseid = '$courseid' AND e.quizid = '$cmid' AND u.id = '$studentid' AND e.webcampicture != ''";
}
$sqlexecuted = $DB->get_recordset_sql($sql);
foreach ($sqlexecuted as $row) {
$reportid = $row->reportid;
$refimageurl = $profileimageurl;
$targetimageurl = $row->webcampicture;
get_match_result($refimageurl, $targetimageurl, $reportid);
}
return true;
}
/**
* Analyze specific Quiz images.
*
* @param int $courseid the courseid
* @param int $cmid the course module id
* @param int $studentid the context
* @param $redirecturl Redirect url
*
* @return bool false if no record found
*/
function bs_analyze_specific_quiz($courseid, $cmid, $studentid, $redirecturl) {
global $DB;
// Get user profile image.
$user = core_user::get_user($studentid);
$profileimageurl = '';
$profileimageurl = quizaccess_proctoring_get_image_url($studentid);
// Update all as attempted.
$updatesql = 'UPDATE {quizaccess_proctoring_logs}'
. ' SET awsflag = 1 '
. " WHERE courseid = '$courseid' AND quizid = '$cmid' AND userid = '$studentid' AND awsflag = 0";
$DB->execute($updatesql);
// Check random.
$limit = 5;
$awschecknumber = get_proctoring_settings('awschecknumber');
if ($awschecknumber != '') {
$limit = (int)$awschecknumber;
}
$sql = "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 = '$cmid' AND u.id = '$studentid' AND e.webcampicture != ''";
if ($limit > 0) {
$sql .= " ORDER BY RAND() LIMIT $limit";
}
$sqlexecuted = $DB->get_recordset_sql($sql);
foreach ($sqlexecuted as $row) {
$reportid = $row->reportid;
$refimageurl = $profileimageurl;
$targetimageurl = $row->webcampicture;
list($userfaceimageurl, $webcamfaceimageurl) = get_face_images($reportid);
if (!$userfaceimageurl || !$webcamfaceimageurl) {
// Update face match result.
log_fm_warning($reportid);
// Set $awsflag = 3 when face not found for admin / webcam image.
$awsflag = 3;
update_match_result($reportid, 0, $awsflag);
continue;
}
extracted($userfaceimageurl, $webcamfaceimageurl, $reportid);
}
return true;
}
/**
* Get proctoring settings values.
*
* @param string $settingtype the courseid
*
* @return string
*/
function get_proctoring_settings($settingtype) {
$value = '';
global $DB;
$settingssql = "SELECT * FROM {config_plugins}
WHERE {config_plugins}.plugin = 'quizaccess_proctoring' AND {config_plugins}.name = '$settingtype'";
$settingsdata = $DB->get_records_sql($settingssql);
if (count($settingsdata) > 0) {
foreach ($settingsdata as $row) {
$value = $row->value;
}
}
return $value;
}
/**
* Analyze specific image.
*
* @param int $reportid the context
*
* @return bool false if no record found
*/
function aws_analyze_specific_image($reportid) {
global $DB;
$reportsql = 'SELECT id,courseid,quizid,userid,webcampicture FROM {quizaccess_proctoring_logs} WHERE id=:id';
$reportdata = $DB->get_record_sql($reportsql, ['id' => $reportid]);
if ($reportdata) {
$studentid = $reportdata->userid;
$courseid = $reportdata->courseid;
$cmid = $reportdata->quizid;
$targetimage = $reportdata->webcampicture;
// Get user profile image.
$user = core_user::get_user($studentid);
$profileimageurl = '';
$profileimageurl = quizaccess_proctoring_get_image_url($studentid);
// Update all as attempted.
$updatesql = "UPDATE {quizaccess_proctoring_logs}
SET awsflag = 1
WHERE courseid = '$courseid' AND quizid = '$cmid' AND userid = '$studentid' AND awsflag = 0";
$DB->execute($updatesql);
get_match_result($profileimageurl, $targetimage, $reportid);
}
return true;
}
/**
* Analyze specific image.
*
* @param int $reportid the context
* @param $redirecturl
*
* @return bool false if no record found
*/
function bs_analyze_specific_image($reportid, $redirecturl) {
global $DB;
$reportsql = 'SELECT id,courseid,quizid,userid,webcampicture FROM {quizaccess_proctoring_logs} WHERE id=:id';
$reportdata = $DB->get_record_sql($reportsql, ['id' => $reportid]);
if ($reportdata) {
$studentid = $reportdata->userid;
$courseid = $reportdata->courseid;
$cmid = $reportdata->quizid;
list($userfaceimageurl, $webcamfaceimageurl) = get_face_images($reportid);
if (!$userfaceimageurl || !$webcamfaceimageurl) {
// Update face match result.
log_fm_warning($reportid);
// Set $awsflag = 3 when face not found for admin / webcam image.
$awsflag = 3;
update_match_result($reportid, 0, $awsflag);
redirect($redirecturl, "Error encountered while analyzing the image. Please contact with Admin",
1,
\core\output\notification::NOTIFY_ERROR);
return;
}
// Update all as attempted.
$updatesql = "UPDATE {quizaccess_proctoring_logs}
SET awsflag = 1
WHERE courseid = '$courseid' AND quizid = '$cmid' AND userid = '$studentid' AND awsflag = 0";
$DB->execute($updatesql);
extracted($userfaceimageurl, $webcamfaceimageurl, $reportid);
}
return true;
}
/**
* Analyze specific image from validate face without redirect.
*
* @param int $reportid the context
*
* @return bool false if no record found
*/
function bs_analyze_specific_image_from_validate($reportid) {
global $DB;
$reportsql = 'SELECT id,courseid,quizid,userid,webcampicture FROM {quizaccess_proctoring_logs} WHERE id=:id';
$reportdata = $DB->get_record_sql($reportsql, ['id' => $reportid]);
if ($reportdata) {
$studentid = $reportdata->userid;
$courseid = $reportdata->courseid;
$cmid = $reportdata->quizid;
list($userfaceimageurl, $webcamfaceimageurl) = get_face_images($reportid);
if (!$userfaceimageurl || !$webcamfaceimageurl) {
// Update face match result.
log_fm_warning($reportid);
$awsflag = 3;
// Set $awsflag = 3 when face not found for admin / webcam image.
update_match_result($reportid, 0, $awsflag);
return;
}
// Update all as attempted.
$updatesql = "UPDATE {quizaccess_proctoring_logs}
SET awsflag = 1
WHERE courseid = '$courseid' AND quizid = '$cmid' AND userid = '$studentid' AND awsflag = 0";
$DB->execute($updatesql);
extracted($userfaceimageurl, $webcamfaceimageurl, $reportid);
}
return true;
}
function get_face_images($reportid) {
global $DB;
$reportdata = $DB->get_record('quizaccess_proctoring_logs', array('id' => $reportid));
$studentid = $reportdata->userid;
$webcamfaceimage = $DB->get_record('proctoring_face_images', array('parentid' => $reportid, 'parent_type' => 'camshot_image'));
$webcamfaceimageurl = "";
if ($webcamfaceimage) {
$webcamfaceimageurl = $webcamfaceimage->faceimage;
}
$userimagerow = $DB->get_record('proctoring_user_images', array('user_id' => $studentid));
$userfaceimageurl = "";
if ($userimagerow) {
$userfaceimagerow = $DB->get_record(
'proctoring_face_images',
array('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.
*
* @param $profileimageurl
* @param $targetimage
* @param $reportid Report Id
*
* @return void
*/
function extracted($profileimageurl, $targetimage, int $reportid): void {
$similarityresult = check_similarity_bs($profileimageurl, $targetimage);
$response = json_decode($similarityresult);
$threshold = get_proctoring_settings('threshold');
// Update Match result.
if ($response->statusCode == 200 && isset($response->body->distance)) {
if ($response->body->distance <= $threshold / 100) {
$similarity = 100;
} else {
$similarity = 0;
log_fm_warning($reportid);
}
} else {
$similarity = 0;
log_fm_warning($reportid);
}
update_match_result($reportid, $similarity, 2);
}
/**
* Analyze specific image.
*
* @param int $reportid the context
* @param $apiresponse API response from AWS
*
* @return bool false if no record found
*/
function log_aws_api_call($reportid, $apiresponse) {
global $DB;
$log = new stdClass();
$log->reportid = $reportid;
$log->apiresponse = $apiresponse;
$log->timecreated = time();
return $DB->insert_record('aws_api_log', $log);
}
/**
* Returns face match similarity.
*
* @param string $referenceimageurl the courseid
* @param string $targetimageurl the course module id
*
* @return bool|string similaritycheck
*/
function check_similarity_bs($referenceimageurl, $targetimageurl) {
global $CFG;
$bsapi = get_proctoring_settings('bsapi');
$threshold = get_proctoring_settings('threshold');
$bsapikey = get_proctoring_settings('bs_api_key');
// Load File.
$image1 = basename($referenceimageurl);
file_put_contents($CFG->dataroot . TEMP . $image1, file_get_contents($referenceimageurl));
$image2 = basename($targetimageurl);
file_put_contents($CFG->dataroot . TEMP . $image2, file_get_contents($targetimageurl));
$imagedata1 = file_get_contents($referenceimageurl);
$imagedata2 = file_get_contents($targetimageurl);
$data = array(
'original_img_response' => base64_encode($imagedata1),
'face_img_response' => base64_encode($imagedata2),
);
$payload = json_encode($data);
// Check similarity.
$curl = curl_init();
curl_setopt_array($curl, [
CURLOPT_URL => $bsapi,
CURLOPT_HTTPHEADER => array(
'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,
]);
$response = curl_exec($curl);
curl_close($curl);
// Clear File.
unlink($CFG->dataroot . TEMP . $image1);
unlink($CFG->dataroot . TEMP . $image2);
return $response;
}
/**
* Get token from Facematching API
* @return mixed
*/
function get_token() {
$bsapi = get_proctoring_settings('bsapi') . '/get_token';
$bsusername = get_proctoring_settings('username');
$bspassword = get_proctoring_settings('password');
// Check similarity.
$curl = curl_init();
curl_setopt_array($curl, [
CURLOPT_URL => $bsapi,
CURLOPT_HTTPHEADER => array(
'Content-Type: multipart/form-data'
),
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => '',
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => 'POST',
CURLOPT_POSTFIELDS => ['username' => $bsusername,
'password' => $bspassword],
]);
$response = curl_exec($curl);
curl_close($curl);
$tokendata = json_decode($response);
$token = $tokendata->token;
return $token;
}
/**
* Log fm warnings.
*
* @param string $reportid the reportid
*
* @return void
*/
function log_fm_warning($reportid) {
global $DB;
$reportsql = 'SELECT * FROM {quizaccess_proctoring_logs} WHERE id=:id';
$reportdata = $DB->get_record_sql($reportsql, ['id' => $reportid]);
if ($reportdata) {
$userid = $reportdata->userid;
$courseid = $reportdata->courseid;
$quizid = $reportdata->quizid;
$warningsql = 'SELECT * FROM {proctoring_fm_warnings} WHERE userid = :userid AND courseid = :courseid AND quizid = :quizid';
$params = [];
$params['userid'] = $userid;
$params['courseid'] = $courseid;
$params['quizid'] = $quizid;
// Check availability.
$warnings = $DB->get_record_sql($warningsql, $params);
// If does not exists.
if (!$warnings) {
$warning = new stdClass();
$warning->reportid = $reportid;
$warning->courseid = $courseid;
$warning->quizid = $quizid;
$warning->userid = $userid;
$DB->insert_record('proctoring_fm_warnings', $warning);
}
}
}
/**
* Returns the url of face image.
*
* @param string $data
* @param $USER
* @param int $courseid
* @param stdClass $record
* @param $context
* @param $fs
*
* @return mixed
*/
function quizaccess_proctoring_geturl_of_faceimage(string $data, int $userid, stdClass $record, $context, $fs) {
list(, $data) = explode(',', $data);
$data = base64_decode($data);
$filename = 'faceimage-' . $userid . '-' . time() . random_int(1, 1000) . '.png';
$record->filename = $filename;
$record->contextid = $context->id;
$record->userid = $userid;
$fs->create_file_from_string($record, $data);
return moodle_url::make_pluginfile_url(
$context->id,
$record->component,
$record->filearea,
$record->itemid,
$record->filepath,
$record->filename,
false
);
}