forked from compilatio/moodle-plagiarism_compilatio
-
Notifications
You must be signed in to change notification settings - Fork 0
/
lib.php
2508 lines (2176 loc) · 106 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
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
// 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/>.
/**
* lib.php - Contains Plagiarism plugin specific functions called by Modules.
*
* @since 2.0
* @package plagiarism_compilatio
* @subpackage plagiarism
* @author Dan Marsden <dan@danmarsden.com>
* @copyright 2012 Dan Marsden http://danmarsden.com
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
if (!defined('MOODLE_INTERNAL')) {
die('Direct access to this script is forbidden.'); // It must be included from a Moodle page.
}
// Get global class.
global $CFG;
require_once($CFG->dirroot . '/plagiarism/lib.php');
require_once($CFG->dirroot . '/plagiarism/compilatio/compilatio.class.php');
define('COMPILATIO_MAX_SUBMISSION_ATTEMPTS', 6); // Max num to try and send a submission to Compilatio.
define('COMPILATIO_MAX_SUBMISSION_DELAY', 60); // Max time to wait between submissions (defined in minutes).
define('COMPILATIO_SUBMISSION_DELAY', 15); // Initial wait time, doubled each time until max_submission_delay is met.
define('COMPILATIO_MAX_STATUS_ATTEMPTS', 10); // Maximum number of times to try and obtain the status of a submission.
define('COMPILATIO_MAX_STATUS_DELAY', 1440); // Maximum time to wait between checks (defined in minutes).
define('COMPILATIO_STATUS_DELAY', 10); // Initial wait time, doubled each time a until the max_status_delay is met.
define('COMPILATIO_STATUSCODE_ACCEPTED', '202');
define('COMPILATIO_STATUSCODE_ANALYSING', '203');
define('COMPILATIO_STATUSCODE_BAD_REQUEST', '400');
define('COMPILATIO_STATUSCODE_NOT_FOUND', '404');
define('COMPILATIO_STATUSCODE_UNSUPPORTED', '415');
define('COMPILATIO_STATUSCODE_UNEXTRACTABLE', '416');
define('COMPILATIO_STATUSCODE_TOO_LARGE', '413');
define('COMPILATIO_STATUSCODE_COMPLETE', 'Analyzed');
define('COMPILATIO_STATUSCODE_IN_QUEUE', 'In queue');
define('COMPILATIO_ANALYSISTYPE_AUTO', 0); // File shoud be processed as soon as the file is sent.
define('COMPILATIO_ANALYSISTYPE_MANUAL', 1); // File processed when teacher manually decides to.
define('COMPILATIO_ANALYSISTYPE_PROG', 2); // File processed on set time/date.
define('PLAGIARISM_COMPILATIO_SHOW_NEVER', 0);
define('PLAGIARISM_COMPILATIO_SHOW_ALWAYS', 1);
define('PLAGIARISM_COMPILATIO_SHOW_CLOSED', 2);
define('PLAGIARISM_COMPILATIO_DRAFTSUBMIT_IMMEDIATE', 0);
define('PLAGIARISM_COMPILATIO_DRAFTSUBMIT_FINAL', 1);
define('PLAGIARISM_COMPILATIO_NEWS_UPDATE', 1);
define('PLAGIARISM_COMPILATIO_NEWS_INCIDENT', 2);
define('PLAGIARISM_COMPILATIO_NEWS_MAINTENANCE', 3);
define('PLAGIARISM_COMPILATIO_NEWS_ANALYSIS_PERTURBATED', 4);
// Compilatio Class.
class plagiarism_plugin_compilatio extends plagiarism_plugin {
// Used to store cache data about Compilatio module thresholds.
private $_green_threshold_cache = null;
private $_orange_threshold_cache = null;
/**
* This function should be used to initialise settings and check if plagiarism is enabled.
* *
* @return mixed - false if not enabled, or returns an array of relevant settings.
*/
public function get_settings() {
static $plagiarismsettings;
if (!empty($plagiarism_settings) || $plagiarismsettings === false) {
return $plagiarismsettings;
}
$plagiarismsettings = (array) get_config('plagiarism');
// Check if compilatio enabled.
if (isset($plagiarismsettings['compilatio_use']) && $plagiarismsettings['compilatio_use']) {
// Now check to make sure required settings are set!
if (empty($plagiarismsettings['compilatio_api'])) {
error("Compilatio API URL not set!");
}
return $plagiarismsettings;
} else {
return false;
}
}
/**
* function which returns an array of all the module instance settings.
*
* @return array
*
*/
public function config_options() {
return array('use_compilatio', 'compilatio_show_student_score',
'compilatio_show_student_report',
'compilatio_draft_submit',
'compilatio_studentemail',
'compilatio_timeanalyse',
'compilatio_analysistype',
'green_threshold',
'orange_threshold');
}
public function cron() {
/* Deprecated for TaskAPI - https://docs.moodle.org/dev/Plagiarism_plugins#cron
"This function was deprecated in 3.1, Moodle 2.7 added the new Task_API
which should now be used instead.
in versions prior to 3.1 this function must exist within your local
class but can be empty if you have migrated to using the newer Task_API"
*/
global $CFG;
if ($CFG->version < 2014051200) { // Legacy cron for Moodle<2.7
$plagiarismsettings = $this->get_settings();
compilatio_send_pending_files($plagiarismsettings);
compilatio_get_scores($plagiarismsettings);
compilatio_trigger_timed_analyses();
compilatio_update_meta();
}
}
/**
* hook to allow plagiarism specific information to be displayed beside a submission.
* @param array $linkarray contains all relevant information for the plugin to generate a link.
* @return string
*
*/
public function get_links($linkarray) {
global $DB, $COURSE, $CFG, $PAGE;
$cmid = $linkarray['cmid'];
$userid = $linkarray['userid'];
if (!empty($linkarray['content'])) {
$filename = "content-" . $COURSE->id . "-" . $cmid . "-" . $userid . ".htm";
$filepath = $CFG->dataroot . "/temp/compilatio/" . $filename;
$file = new stdclass();
$file->type = "tempcompilatio";
$file->filename = $filename;
$file->timestamp = time();
$file->identifier = null;
$file->filepath = $filepath;
} else if (!empty($linkarray['file'])) {
$file = new stdclass();
$file->filename = $linkarray['file']->get_filename();
$file->timestamp = time();
$file->identifier = $linkarray['file']->get_contenthash();
$file->filepath = $linkarray['file']->get_filepath();
}
$results = $this->get_file_results($cmid, $userid, $file);
$output = '';
$modulecontext = context_module::instance($cmid);
if (empty($results)) {
// Check if Compilatio is enabled in this assignment.
$sql = "select value from {plagiarism_compilatio_config} where cm=? and name='use_compilatio'";
$active_compilatio = $DB->get_record_sql($sql, array($cmid));
if ($active_compilatio === false || $active_compilatio->value === '0') {
return "";
}
// If the user has permission to see result of all items in this course module.
$teacher = has_capability('plagiarism/compilatio:viewreport', $modulecontext);
if (!$teacher) {
return '';
} else {
// Only works for assign.
$cm = get_coursemodule_from_id('assign', $cmid);
if (!isset($linkarray["file"]) || $cm === false) {
return $output;
}
$trigger = optional_param('sendfile', 0, PARAM_INT);
$fileInstance = $linkarray["file"];
$fileID = $fileInstance->get_id();
if ($trigger == $fileID) {
$res = $DB->get_record("files", array("id" => $fileID));
if (!defined("COMPILATIO_MANUAL_SEND")) {
define("COMPILATIO_MANUAL_SEND", true); // hack to hide mtrace in function execution.
compilatio_upload_files(array($res), $cmid);
return $output . $this->get_links($linkarray);
} else {
return $output;
}
}
$moodle_url = new moodle_url("/mod/assign/view.php", array("id" => $cmid, "sendfile" => $fileID, "action" => "grading"));
$url = array();
$url["url"] = "$moodle_url";
$url["target-blank"] = false;
$spanContent = get_string("analyze", "plagiarism_compilatio");
$image = "play";
$title = get_string('startanalysis', 'plagiarism_compilatio');
$output .= compilatio_get_plagiarism_area($spanContent, $image, $title, "", $url);
return $output;
}
// Info about this file is not available to this user.
return $output;
}
$trigger = optional_param('compilatioprocess', 0, PARAM_INT);
if ($results['statuscode'] == COMPILATIO_STATUSCODE_ACCEPTED && $trigger == $results['pid']) {
if (has_capability('plagiarism/compilatio:triggeranalysis', $modulecontext)) {
// Trigger manual analysis call.
$plagiarism_file = compilatio_get_plagiarism_file($cmid, $userid, $file);
$analyse = compilatio_startanalyse($plagiarism_file);
if ($analyse === true) {
// Update plagiarism record.
$plagiarism_file->statuscode = COMPILATIO_STATUSCODE_IN_QUEUE;
$DB->update_record('plagiarism_compilatio_files', $plagiarism_file);
$spanContent = get_string("queue", "plagiarism_compilatio");
$image = "queue";
$title = get_string('queued', 'plagiarism_compilatio');
$output.= compilatio_get_plagiarism_area($spanContent, $image, $title, "");
} else {
$output .= '<span class="plagiarismreport">' .
'</span>';
}
return $output;
}
}
if ($results['statuscode'] == 'pending') {
$spanContent = get_string("pending_status", "plagiarism_compilatio");
$image = "hourglass";
$title = get_string('pending', 'plagiarism_compilatio');
$output.= compilatio_get_plagiarism_area($spanContent, $image, $title, "");
return $output;
}
if ($results['statuscode'] == 'Analyzed') {
// Normal situation - Compilatio has successfully analyzed the file.
// Cache Thresholds values.
if ($this->_green_threshold_cache == null || $this->_orange_threshold_cache == null) {
$plagiarismvalues = $DB->get_records_menu('plagiarism_compilatio_config', array('cm' => $cmid), '', 'name, value');
if (isset($plagiarismvalues["green_threshold"], $plagiarismvalues["orange_threshold"])) {
$this->_green_threshold_cache = $plagiarismvalues["green_threshold"];
$this->_orange_threshold_cache = $plagiarismvalues["orange_threshold"];
} else {
$this->_green_threshold_cache = 10;
$this->_orange_threshold_cache = 25;
}
}
$url = "";
$append = "";
if (!empty($results['reporturl'])) {
// User is allowed to view the report
// Score is contained in report, so they can see the score too.
$url = $results['reporturl'];
$append = compilatio_get_image_similarity($results['score'], $this->_green_threshold_cache, $this->_orange_threshold_cache);
} else if ($results['score'] !== '') {
// User is allowed to view only the score.
$append = compilatio_get_image_similarity($results['score'], $this->_green_threshold_cache, $this->_orange_threshold_cache);
}
$title = get_string("analysis_completed", 'plagiarism_compilatio', $results['score']);
$url = array("target-blank" => true, "url" => $url);
$output.= compilatio_get_plagiarism_area("", "", $title, $append, $url);
if (!empty($results['renamed'])) {
$output .= $results['renamed'];
}
} else if ($results['statuscode'] == COMPILATIO_STATUSCODE_IN_QUEUE) {
$spanContent = get_string("queue", "plagiarism_compilatio");
$image = "queue";
$title = get_string('queued', 'plagiarism_compilatio');
$output.= compilatio_get_plagiarism_area($spanContent, $image, $title, "");
} else if ($results['statuscode'] == COMPILATIO_STATUSCODE_ACCEPTED) {
$plagiarismvalues = $DB->get_records_menu('plagiarism_compilatio_config', array('cm' => $cmid), '', 'name, value');
$title = "";
$span = "";
$url = "";
$image = "";
// Check settings to see if we need to tell compilatio to process this file now.
// Check if this is a timed release and add hourglass image.
if ($plagiarismvalues['compilatio_analysistype'] == COMPILATIO_ANALYSISTYPE_PROG) {
$image = "prog";
$span = get_string('planned', 'plagiarism_compilatio');
$title = get_string('waitingforanalysis', 'plagiarism_compilatio', userdate($plagiarismvalues['compilatio_timeanalyse']));
} else if (has_capability('plagiarism/compilatio:triggeranalysis', $modulecontext)) {
$url = new moodle_url($PAGE->url, array('compilatioprocess' => $results['pid']));
$action = optional_param('action', '', PARAM_TEXT); // Hack to add action to params for mod/assign.
if (!empty($action)) {
$url->param('action', $action);
}
$url = "$url";
$span = get_string("analyze", "plagiarism_compilatio");
$image = "play";
$title = get_string('startanalysis', 'plagiarism_compilatio');
} else if ($results['score'] !== '') {//If score === "" => Student, not allowed to see.
$image = "inprogress";
$title = get_string('processing_doc', 'plagiarism_compilatio');
}
if ($title !== "") {
$url = array("target-blank" => false, "url" => $url);
$output .= compilatio_get_plagiarism_area($span, $image, $title, "", $url);
}
} else if ($results['statuscode'] == COMPILATIO_STATUSCODE_ANALYSING) {
$span = get_string("analyzing", "plagiarism_compilatio");
$image = "inprogress";
$title = get_string('processing_doc', 'plagiarism_compilatio');
$output .= compilatio_get_plagiarism_area($span, $image, $title);
} else if ($results['statuscode'] == COMPILATIO_STATUSCODE_UNSUPPORTED) {
$span = get_string("error", "plagiarism_compilatio");
$image = "exclamation";
$title = get_string('unsupportedfiletype', 'plagiarism_compilatio');
$output .= compilatio_get_plagiarism_area($span, $image, $title, "", "", true);
} else if ($results['statuscode'] == COMPILATIO_STATUSCODE_TOO_LARGE) {
$span = get_string("error", "plagiarism_compilatio");
$image = "exclamation";
$title = get_string('toolarge', 'plagiarism_compilatio');
$output .= compilatio_get_plagiarism_area($span, $image, $title, "", "", true);
} else if ($results['statuscode'] == COMPILATIO_STATUSCODE_UNEXTRACTABLE) {
$span = get_string("error", "plagiarism_compilatio");
$image = "exclamation";
$title = get_string('unextractablefile', 'plagiarism_compilatio');
$output .= compilatio_get_plagiarism_area($span, $image, $title, "", "", true);
} else {
$title = get_string('unknownwarning', 'plagiarism_compilatio');
$reset = '';
$url = "";
if (has_capability('plagiarism/compilatio:resetfile', $modulecontext) &&
!empty($results['error'])) { // This is a teacher viewing the responses.
// Strip out some possible known text to tidy it up.
$erroresponse = format_text($results['error'], FORMAT_PLAIN);
$erroresponse = str_replace('{"LocalisedMessage":"', '', $erroresponse);
$erroresponse = str_replace('","Message":null}', '', $erroresponse);
$title .= ': ' . $erroresponse;
$url = new moodle_url('/plagiarism/compilatio/reset.php', array('cmid' => $cmid, 'pf' => $results['pid'], 'sesskey' => sesskey()));
$reset = "<a class='reinit' href='$url'>" . get_string('reset') . "</a>";
}
$span = get_string('reset', "plagiarism_compilatio");
$url = array("target-blank" => false, "url" => $url);
$image = "exclamation";
$output .= compilatio_get_plagiarism_area($span, $image, $title, "", $url, true);
}
return $output;
}
public function get_file_results($cmid, $userid, $file) {
global $DB, $USER, $CFG;
$plagiarismsettings = $this->get_settings();
if (empty($plagiarismsettings)) {
// Compilatio is not enabled.
return false;
}
$plagiarismvalues = compilatio_cm_use($cmid);
if (empty($plagiarismvalues)) {
// Compilatio not enabled for this cm.
return false;
}
// Collect detail about the specified coursemodule.
$filehash = $file->identifier;
$modulesql = 'SELECT m.id, m.name, cm.instance' .
' FROM {course_modules} cm' .
' INNER JOIN {modules} m on cm.module = m.id ' .
'WHERE cm.id = ?';
$moduledetail = $DB->get_record_sql($modulesql, array($cmid));
if (!empty($moduledetail)) {
$sql = "SELECT * FROM " . $CFG->prefix . $moduledetail->name . " WHERE id= ?";
$module = $DB->get_record_sql($sql, array($moduledetail->instance));
}
if (empty($module)) {
// No such cmid.
return false;
}
$modulecontext = context_module::instance($cmid);
// If the user has permission to see result of all items in this course module.
$viewscore = $viewreport = has_capability('plagiarism/compilatio:viewreport', $modulecontext);
// Determine if the activity is closed.
// If report is closed, this can make the report available to more users.
$assignclosed = false;
$time = time();
if (!empty($module->preventlate) && !empty($module->timedue)) {
$assignclosed = ($module->timeavailable <= $time && $time <= $module->timedue);
} else if (!empty($module->timeavailable)) {
$assignclosed = ($module->timeavailable <= $time);
}
// Under certain circumstances, users are allowed to see plagiarism info
// even if they don't have view report capability.
if ($USER->id == $userid) {
$selfreport = true;
if (get_config("plagiarism", "compilatio_allow_teachers_to_show_reports") === '1' &&
isset($plagiarismvalues['compilatio_show_student_report']) &&
($plagiarismvalues['compilatio_show_student_report'] == PLAGIARISM_COMPILATIO_SHOW_ALWAYS ||
$plagiarismvalues['compilatio_show_student_report'] == PLAGIARISM_COMPILATIO_SHOW_CLOSED && $assignclosed)) {
$viewreport = true;
}
if (isset($plagiarismvalues['compilatio_show_student_score']) &&
($plagiarismvalues['compilatio_show_student_score'] == PLAGIARISM_COMPILATIO_SHOW_ALWAYS) ||
($plagiarismvalues['compilatio_show_student_score'] == PLAGIARISM_COMPILATIO_SHOW_CLOSED && $assignclosed)) {
$viewscore = true;
}
} else {
$selfreport = false;
}
// End of rights checking.
if (!$viewscore && !$viewreport && $selfreport) {
// User is not permitted to see any details.
return false;
}
if ($filehash != null) {
$plagiarismfile = $DB->get_record_sql(
"SELECT * FROM {plagiarism_compilatio_files}
WHERE cm = ? AND userid = ? AND " .
"identifier = ?", array($cmid, $userid, $filehash));
} else {
// We don't have the hash of the content-submission, get it by name
$plagiarismfile = $DB->get_record_sql(
"SELECT * FROM {plagiarism_compilatio_files}
WHERE cm = ? AND userid = ? AND " .
"filename = ?", array($cmid, $userid, $file->filename));
}
if (empty($plagiarismfile)) {
// No record of that submitted file.
return false;
}
// Returns after this point will include a result set describing information about
// interactions with compilatio servers.
$results = array('statuscode' => '', 'error' => '', 'reporturl' => '',
'score' => '', 'pid' => '', 'renamed' => '',
'analyzed' => 0,
);
if ($plagiarismfile->statuscode == 'pending') {
$results['statuscode'] = 'pending';
return $results;
}
// Now check for differing filename and display info related to it.
$previouslysubmitted = '';
if ($file->filename !== $plagiarismfile->filename) {
$previouslysubmitted = '<span class="prevsubmitted">(' . get_string('previouslysubmitted', 'plagiarism_compilatio') .
': ' . $plagiarismfile->filename . ')</span>';
}
$results['statuscode'] = $plagiarismfile->statuscode;
$results['pid'] = $plagiarismfile->id;
$results['error'] = $plagiarismfile->errorresponse;
if ($plagiarismfile->statuscode == 'Analyzed') {
$results['analyzed'] = 1;
// File has been successfully analyzed - return all appropriate details.
if ($viewscore || $viewreport) {
// If user can see the report, they can see the score on the report
// so make it directly available.
$results['score'] = $plagiarismfile->similarityscore;
}
if ($viewreport) {
$results['reporturl'] = $plagiarismfile->reporturl;
}
$results['renamed'] = $previouslysubmitted;
}
return $results;
}
/* hook to save plagiarism specific settings on a module settings page.
* @param object $data - data from an mform submission.
*/
public function save_form_elements($data) {
global $DB;
if (!$this->get_settings()) {
return;
}
if (isset($data->use_compilatio)) {
// Array of possible plagiarism config options.
$plagiarismelements = $this->config_options();
//Validation on thresholds :
//Set thresholds to default if the green one is greater than the orange.
if (!isset($data->green_threshold, $data->orange_threshold) ||
$data->green_threshold > $data->orange_threshold ||
$data->green_threshold > 100 ||
$data->green_threshold < 0 ||
$data->orange_threshold > 100 ||
$data->orange_threshold < 0
) {
$data->green_threshold = 10;
$data->orange_threshold = 25;
}
if (get_config("plagiarism", "compilatio_allow_teachers_to_show_reports") !== '1') {
$data->compilatio_show_student_report = PLAGIARISM_COMPILATIO_SHOW_NEVER;
}
// First get existing values.
$existingelements = $DB->get_records_menu('plagiarism_compilatio_config', array('cm' => $data->coursemodule), '', 'name, id');
foreach ($plagiarismelements as $element) {
$newelement = new stdClass();
$newelement->cm = $data->coursemodule;
$newelement->name = $element;
$newelement->value = (isset($data->$element) ? $data->$element : 0);
if (isset($existingelements[$element])) { // Update.
$newelement->id = $existingelements[$element];
$DB->update_record('plagiarism_compilatio_config', $newelement);
} else { // Insert.
$DB->insert_record('plagiarism_compilatio_config', $newelement);
}
}
//check if we are changing from timed or manual to instant
//if changing to instant, make all existing files to get a report.
if (isset($existingelements['compilatio_analysistype']) && $existingelements['compilatio_analysistype'] !== $data->compilatio_analysistype &&
$data->compilatio_analysistype == COMPILATIO_ANALYSISTYPE_AUTO) {
//get all existing files in this assignment set to manual status
$plagiarismfiles = $DB->get_records('plagiarism_compilatio_files', array('cm' => $data->coursemodule, 'statuscode' => COMPILATIO_STATUSCODE_ACCEPTED));
compilatio_analyse_files($plagiarismfiles);
}
}
}
/**
* hook to add plagiarism specific settings to a module settings page.
* @param object $mform - Moodle form
* @param object $context - current context
*/
public function get_form_elements_module($mform, $context, $modulename = "") {
global $DB;
$plagiarismsettings = $this->get_settings();
if (!$plagiarismsettings) {
return;
}
// Hack to prevent this from showing on custom compilatioassignment type.
if ($mform->elementExists('seuil_faible')) {
return;
}
$cmid = optional_param('update', 0, PARAM_INT); // We can't access $this->_cm here.
if (!empty($modulename)) {
$modname = 'compilatio_enable_' . $modulename;
if (empty($plagiarismsettings[$modname])) {
return; // Return if compilatio is not enabled for the module
}
}
if (!empty($cmid)) {
$plagiarismvalues = $DB->get_records_menu('plagiarism_compilatio_config', array('cm' => $cmid), '', 'name, value');
}
// The cmid(0) is the default list.
$plagiarismdefaults = $DB->get_records_menu('plagiarism_compilatio_config', array('cm' => 0), '', 'name, value');
$plagiarismelements = $this->config_options();
if (has_capability('plagiarism/compilatio:enable', $context)) {
compilatio_get_form_elements($mform);
if ($mform->elementExists('compilatio_draft_submit')) {
if ($mform->elementExists('var4')) {
$mform->disabledIf('compilatio_draft_submit', 'var4', 'eq', 0);
} else if ($mform->elementExists('submissiondrafts')) {
$mform->disabledIf('compilatio_draft_submit', 'submissiondrafts', 'eq', 0);
}
}
// Disable all plagiarism elements if use_plagiarism eg 0.
foreach ($plagiarismelements as $element) {
if ($element <> 'use_compilatio') { // Ignore this var.
$mform->disabledIf($element, 'use_compilatio', 'eq', 0);
}
}
} else { // Add plagiarism settings as hidden vars.
foreach ($plagiarismelements as $element) {
$mform->addElement('hidden', $element);
}
}
// Now set defaults.
foreach ($plagiarismelements as $element) {
if (isset($plagiarismvalues[$element])) {
$mform->setDefault($element, $plagiarismvalues[$element]);
} else if (isset($plagiarismdefaults[$element])) {
$mform->setDefault($element, $plagiarismdefaults[$element]);
}
}
}
/**
* hook to allow a disclosure to be printed notifying users what will happen with their submission.
* @param int $cmid - course module id
* @return string
*/
public function print_disclosure($cmid) {
global $OUTPUT;
$outputhtml = '';
$compilatiouse = compilatio_cm_use($cmid);
$plagiarismsettings = $this->get_settings();
if (!empty($plagiarismsettings['compilatio_student_disclosure']) &&
!empty($compilatiouse)) {
$outputhtml .= $OUTPUT->box_start('generalbox boxaligncenter', 'intro');
$formatoptions = new stdClass;
$formatoptions->noclean = true;
$outputhtml .= format_text($plagiarismsettings['compilatio_student_disclosure'], FORMAT_MOODLE, $formatoptions);
$outputhtml .= $OUTPUT->box_end();
}
return $outputhtml;
}
/**
* hook to allow status of submitted files to be updated - called on grading/report pages.
*
* @param object $course - full Course object
* @param object $cm - full cm object
* @return string
*/
public function update_status($course, $cm) {
global $PAGE, $OUTPUT, $DB;
$alerts = array();
$output = '';
//Handle the action of the button.
$update = optional_param('compilatioupdate', '', PARAM_BOOL);
if ($update) {
$sql = "cm = ? AND externalid IS NOT NULL";
$params = array($cm->id);
$plagiarism_files = $DB->get_records_select('plagiarism_compilatio_files', $sql, $params);
foreach ($plagiarism_files as $pf) {
compilatio_check_analysis($pf, true);
}
$alerts[] = array(
"class" => "success",
"title" => get_string('updated_analysis', 'plagiarism_compilatio'),
"content" => "");
}
$export = optional_param('compilatio_export', '', PARAM_BOOL);
if ($export) {
compilatio_csv_export($cm->id);
}
//Handle the action of the button when course is set on manual analysis
$startAllAnalysis = optional_param('compilatiostartanalysis', '', PARAM_BOOL);
if ($startAllAnalysis) {
$sql = "cm = ? AND name='compilatio_analysistype'";
$params = array($cm->id);
$record = $DB->get_record_select('plagiarism_compilatio_config', $sql, $params);
//Counter incremented on success
$countSuccess = 0;
$plagiarism_files = array();
$docsFailed = array();
if ($record != null && $record->value == COMPILATIO_ANALYSISTYPE_MANUAL) {
$sql = "cm = ? AND statuscode = ?";
$params = array($cm->id, COMPILATIO_STATUSCODE_ACCEPTED);
$plagiarism_files = $DB->get_records_select('plagiarism_compilatio_files', $sql, $params);
foreach ($plagiarism_files as $file) {
if (compilatio_startanalyse($file)) {
$countSuccess++;
} else {
$docsFailed[] = $file["filename"];
}
}
}
//Handle not sent documents :
$files = compilatio_get_non_uploaded_documents($cm->id);
$countBegin = count($files);
if ($countBegin != 0) {
define("COMPILATIO_MANUAL_SEND", true);
compilatio_upload_files($files, $cm->id);
$countSuccess += $countBegin - count(compilatio_get_non_uploaded_documents($cm->id));
}
$countTotal = count($plagiarism_files) + $countBegin;
$countErrors = count($docsFailed);
if ($countTotal === 0) {
$alerts[] = array(
"class" => "info",
"title" => get_string("start_analysis_title", "plagiarism_compilatio"),
"content" => get_string("no_document_available_for_analysis", "plagiarism_compilatio"));
} elseif ($countErrors === 0) {
$alerts[] = array(
"class" => "info",
"title" => get_string("start_analysis_title", "plagiarism_compilatio"),
"content" => get_string("analysis_started", "plagiarism_compilatio", $countSuccess));
} else {
$alerts[] = array(
"class" => "danger",
"title" => get_string("not_analyzed", "plagiarism_compilatio"),
"content" => "<ul><li>" . implode("</li><li>", $docsFailed) . "</li></ul>"
);
}
//$output .= $OUTPUT->notification(get_string('manual_global_analysis', 'plagiarism_compilatio'), 'notifysuccess');
}
$plagiarismsettings = (array) get_config('plagiarism');
$compilatio_enabled = $plagiarismsettings["compilatio_use"] && $plagiarismsettings["compilatio_enable_mod_assign"];
$sql = "select value from {plagiarism_compilatio_config} where cm=? and name='use_compilatio'";
$active_compilatio = $DB->get_record_sql($sql, array($cm->id));
//Compilatio not enabled, return.
if ($active_compilatio === false) {
//Plagiarism settings have not been saved :
$plagiarismdefaults = $DB->get_records_menu('plagiarism_compilatio_config', array('cm' => 0), '', 'name, value');
$plagiarismelements = $this->config_options();
foreach ($plagiarismelements as $element) {
if (isset($plagiarismdefaults[$element])) {
$newelement = new Stdclass();
$newelement->cm = $cm->id;
$newelement->name = $element;
$newelement->value = $plagiarismdefaults[$element];
$DB->insert_record('plagiarism_compilatio_config', $newelement);
}
}
//Get the new status
$active_compilatio = $DB->get_record_sql($sql, array($cm->id));
}
if ($active_compilatio == null || $active_compilatio->value != 1 || !$compilatio_enabled) {
return "";
}
//Get compilatio analysis type
$sql = "cm = ? AND name='compilatio_analysistype'";
$params = array($cm->id);
$record = $DB->get_record_select('plagiarism_compilatio_config', $sql, $params);
$value = $record->value;
if ($value == COMPILATIO_ANALYSISTYPE_MANUAL) {//Display a button that start all the analysis of the activity
$url = $PAGE->url;
$url->param('compilatiostartanalysis', true);
$StartAllAnalysisButton = "
<a href='$url' class='compilatio-button button' >
<i class='fa fa-play-circle'>
</i>
" . get_string('startallcompilatioanalysis', 'plagiarism_compilatio') . "
</a>";
} else if ($value == COMPILATIO_ANALYSISTYPE_PROG) {//Display the date of analysis if its type is set on 'Timed'.
//Get analysis date :
$sql = "cm = ? AND name='compilatio_timeanalyse'";
$params = array($cm->id);
$plagiarism_files = $DB->get_records_select('plagiarism_compilatio_config', $sql, $params);
$record = reset($plagiarism_files); //Get the first value of the array
$date = userdate($record->value);
if ($record->value > time()) {
$programmedAnalysisDate = get_string("programmed_analysis_future", "plagiarism_compilatio", $date);
} else {
$programmedAnalysisDate = get_string("programmed_analysis_past", "plagiarism_compilatio", $date);
}
}
//Get the DB record containing the webservice status :
$oldConnectionStatus = $DB->get_record('plagiarism_compilatio_data', array('name' => 'connection_webservice'));
//If the record exists and if the webservice is marked as unreachable in Cron function :
if ($oldConnectionStatus != null && $oldConnectionStatus->value === '0') {
$alerts[] = array(
"class" => "danger",
"title" => get_string("webservice_unreachable_title", "plagiarism_compilatio"),
"content" => get_string("webservice_unreachable_content", "plagiarism_compilatio"));
}
//Display a notification of the unsupported files
$files = compilatio_get_unsupported_files($cm->id);
if (count($files) !== 0) {
$list = "<ul><li>" . implode("</li><li>", $files) . "</li></ul>";
$alerts[] = array(
"class" => "danger",
"title" => get_string("unsupported_files", "plagiarism_compilatio"),
"content" => $list
);
}
//Display a notification form the unextractable files
$files = compilatio_get_unextractable_files($cm->id);
if (count($files) !== 0) {
$list = "<ul><li>" . implode("</li><li>", $files) . "</li></ul>";
$alerts[] = array(
"class" => "danger",
"title" => get_string("unextractable_files", "plagiarism_compilatio"),
"content" => $list
);
}
//If the account expires within the month, display an alert :
if (compilatio_check_account_expiration_date()) {
$alerts[] = array(
"class" => "danger",
"title" => get_string("account_expire_soon_title", "plagiarism_compilatio"),
"content" => get_string("account_expire_soon_content", "plagiarism_compilatio")
);
}
$documentsNotUploaded = compilatio_get_non_uploaded_documents($cm->id);
if (count($documentsNotUploaded) !== 0) {
$alerts[] = array(
"class" => "danger",
"title" => get_string("unsent_documents", "plagiarism_compilatio"),
"content" => get_string("unsent_documents_content", "plagiarism_compilatio"));
$url = $PAGE->url;
$url->param('compilatiostartanalysis', true);
$StartAllAnalysisButton = "
<a href='$url' class='compilatio-button button' >
<i class='fa fa-play-circle'>
</i>
" . get_string('startallcompilatioanalysis', 'plagiarism_compilatio') . "
</a>";
}
//Add the Compilatio news to the alerts displayed :
$alerts = array_merge($alerts, compilatio_display_news());
$jquery_url = new moodle_url("/plagiarism/compilatio/jquery.min.js");
$fontawesome_url = new moodle_url("/plagiarism/compilatio/fonts/font-awesome.min.css");
//Include JQuery & FontAwesome
$output .= "<script src='$jquery_url'></script>";
$output .= "<link rel='stylesheet' href='$fontawesome_url'>";
$output .= "<div id='compilatio-container'>";
$output .= compilatio_get_logo();
//Display the tabs: Notification tab will be hidden if there is 0 alerts.
$output .= "<div id='compilatio-tabs' style='display:none'>";
$output .= "<div title=\"" . get_string("compilatio_help_assign", "plagiarism_compilatio") . "\" id='show-help' class='compilatio-icon'><i class='fa fa-question-circle fa-2x'></i></div>";
$output .= "<div id='show-stats' class='compilatio-icon' title='" . get_string("display_stats", "plagiarism_compilatio") . "'><i class='fa fa-bar-chart fa-2x'></i></div>";
if (count($alerts) !== 0) {
$output .= "<div id='show-notifications' title='" . get_string("display_notifications", "plagiarism_compilatio") . "'
class='compilatio-icon active' ><i class='fa fa-bell fa-2x'></i>";
$output .= "<span>" . count($alerts) . "</span>";
$output .= "</div>";
}
$output .= "<div id='compilatio-hide-area' class='compilatio-icon' title='" . get_string("hide_area", "plagiarism_compilatio") . "'><i class='fa fa-chevron-up fa-2x'></i></div>";
$output .= "</div>";
$output .= "<script>";
//Focus on notifications if there is any.
$output .= "var selectedElement = ";
if (count($alerts) !== 0) {
$output .= "'#compilatio-notifications';";
} else {
$output .= "'#compilatio-home';";
}
//JQuery Script to handle click on the tabs
$output .= "$(document).ready(function(){
$('#compilatio-tabs').show();
var tabs = $('#show-notifications, #show-stats, #show-help');
var elements = $('#compilatio-notifications, #compilatio-stats, #compilatio-help, #compilatio-home');
elements.not($(selectedElement)).hide();
$('#show-notifications').on('click',function(){
tabClick($(this), $('#compilatio-notifications'));
});
$('#show-stats').on('click',function(){
tabClick($(this), $('#compilatio-stats'));
});
$('#show-help').on('click',function(){
tabClick($(this), $('#compilatio-help'));
});
function tabClick(tabClicked, contentToShow)
{
if(!contentToShow.is(':visible'))
{
contentToShow.show();
elements.not(contentToShow).hide();
tabs.not(tabClicked).removeClass('active');
tabClicked.toggleClass('active');
$('#compilatio-hide-area').fadeIn();
}
}
$('#compilatio-logo').on('click',function(){
elementClicked = $('#compilatio-home');
elementClicked.show();
elements.not(elementClicked).hide();
tabs.removeClass('active');
$('#compilatio-hide-area').fadeIn();
});
$('#compilatio-hide-area').on('click',function(event){
elements.hide();
$(this).fadeOut();
tabs.removeClass('active');
});
});
</script>";
$output .= "<div class='clear'></div>";
//Home tab
$output .= "
<div id='compilatio-home'>
<p style='margin-top: 15px;'>" . get_string('similarities_disclaimer', 'plagiarism_compilatio') . "</p>
</div>";
//Alerts tab
if (count($alerts) !== 0) {
$output .= "<div id='compilatio-notifications'>";
$output .= "<h5>" . get_string("tabs_title_notifications", "plagiarism_compilatio") . " : </h5>";
foreach ($alerts as $alert) {
$output .= "<div class='alert alert-" . $alert["class"] . "'><strong>" . $alert["title"] . "</strong><br/>" . $alert["content"] . "</div>";
}
$output .= "</div>";
}
//Stats tab
$output .= "<div id='compilatio-stats'>
<h5>" . get_string("tabs_title_stats", "plagiarism_compilatio") . " : </h5>
" . compilatio_get_statistics($cm->id) . "
</div>";
//Help tab
$output .= "<div id='compilatio-help'>
<h5>" . get_string("tabs_title_help", "plagiarism_compilatio") . " : </h5>
" . compilatio_display_help() . "
</div>";
//Display timed analysis date :
if (isset($programmedAnalysisDate)) {
$output .= "<p id='programmed-analysis'>$programmedAnalysisDate</p>";
}
$output .= "</div>";
//Display buttons :
$output .= "<div id='button-container'>";
//Update button
$url = $PAGE->url;
$url->param('compilatioupdate', true);
$output .= "
<a class='compilatio-button button' href='$url'>
<i class='fa fa-refresh'></i>
" . get_string('updatecompilatioresults', 'plagiarism_compilatio') . "
</a>";
//Start all analysis button.
if (isset($StartAllAnalysisButton)) {
$output .= $StartAllAnalysisButton;
}
$output .= "</div>";
return $output;
}