forked from danmarsden/moodle-plagiarism_urkund
-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathlib.php
2520 lines (2307 loc) · 108 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_urkund
* @subpackage plagiarism
* @author Dan Marsden <[email protected]>
* @copyright 2011 Dan Marsden http://danmarsden.com
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
defined('MOODLE_INTERNAL') || die();
// Get global class.
global $CFG;
require_once($CFG->dirroot.'/plagiarism/lib.php');
require_once($CFG->dirroot . '/lib/filelib.php');
// There is a new URKUND API - The Integration Service - we only currently use this to verify the receiver address.
// If we convert the existing calls to send file/get score we should move this to a config setting.
define('URKUND_STATUSCODE_PROCESSED', '200');
define('URKUND_STATUSCODE_ACCEPTED', '202');
define('URKUND_STATUSCODE_ACCEPTED_OLD', '202-old'); // File submitted before we changed the way the identifiers were stored.
define('URKUND_STATUSCODE_BAD_REQUEST', '400');
define('URKUND_STATUSCODE_NOT_FOUND', '404');
define('URKUND_STATUSCODE_GONE', '410'); // Receiver is inactive or deleted.
define('URKUND_STATUSCODE_UNSUPPORTED', '415');
define('URKUND_STATUSCODE_TOO_LARGE', '413');
define('URKUND_STATUSCODE_NORECEIVER', '444');
define('URKUND_STATUSCODE_INVALID_RESPONSE', '613'); // Invalid response received from URKUND.
define('URKUND_STATUSCODE_PENDING', 'pending');
// Url to external xml that states URKUNDS allowed file type list.
define('URKUND_FILETYPE_URL', 'https://secure.urkund.com/ws/integration/accepted-formats.xml');
define('PLAGIARISM_URKUND_SHOW_NEVER', 0);
define('PLAGIARISM_URKUND_SHOW_ALWAYS', 1);
define('PLAGIARISM_URKUND_SHOW_WHENDUE', 2);
define('PLAGIARISM_URKUND_SHOW_WHENCUTOFF', 3);
define('PLAGIARISM_URKUND_DRAFTSUBMIT_IMMEDIATE', 0);
define('PLAGIARISM_URKUND_DRAFTSUBMIT_FINAL', 1);
// Used by content type restriction form - inline-text vs file attachments.
define('PLAGIARISM_URKUND_RESTRICTCONTENTNO', 0);
define('PLAGIARISM_URKUND_RESTRICTCONTENTFILES', 1);
define('PLAGIARISM_URKUND_RESTRICTCONTENTTEXT', 2);
// Used by resubmit form element.
define('PLAGIARISM_URKUND_RESUBMITNO', 0);
define('PLAGIARISM_URKUND_RESUBMITDUEDATE', 1);
define('PLAGIARISM_URKUND_RESUBMITCLOSEDATE', 2);
define('PLAGIARISM_URKUND_MAXATTEMPTS', 28);
/**
* Class plagiarism_plugin_urkund
*
* @package plagiarism_urkund
* @copyright 2011 Dan Marsden
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class plagiarism_plugin_urkund extends plagiarism_plugin {
/**
* 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 static function get_settings() {
static $plagiarismsettings;
if (!empty($plagiarismsettings) || $plagiarismsettings === false) {
return $plagiarismsettings;
}
$plagiarismsettings = (array)get_config('plagiarism_urkund');
// Check if enabled.
if (isset($plagiarismsettings['enabled']) && $plagiarismsettings['enabled']) {
// Now check to make sure required settings are set!
if (empty($plagiarismsettings['api'])) {
debugging("URKUND API URL not set!");
return false;
}
return $plagiarismsettings;
} else {
return false;
}
}
/**
* We return an array of all the module instance or administration settings, correspondingly.
*
* @param bool $adminsettings true if we get the admin settings.
*
* @return array
*/
public static function config_options($adminsettings = false) {
$options = array('use_urkund', 'urkund_show_student_score', 'urkund_show_student_report',
'urkund_draft_submit', 'urkund_resubmit_on_close', 'urkund_receiver', 'urkund_studentemail',
'urkund_allowallfile', 'urkund_selectfiletypes', 'urkund_restrictcontent', 'urkund_storedocuments');
if ($adminsettings) {
$options[] = 'urkund_advanceditems';
}
return $options;
}
/**
* 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;
static $plagiarismvalues = array();
$fullquizlist = false;
if (!empty($linkarray['component']) && strpos($linkarray['component'], 'qtype_') === 0) {
// This is a question report.
$qtype = str_replace('qtype_', '', $linkarray['component']);
// We only support a limited number of qtypes at the moment - exit early.
if (!in_array($qtype, plagiarism_urkund_supported_qtypes())) {
return '';
}
// We only support the use of questions in the quiz activity - should be extended to support other activity types.
if (empty(get_config('plagiarism_urkund', 'enable_mod_quiz'))) {
// Urkund not configured to run on mod_quiz, exit early.
return '';
}
if (!empty($linkarray['cmid'])) {
// We are on a reporting page so show all related links.
$fullquizlist = true;
}
if (empty($linkarray['cmid']) || empty($linkarray['content'])) {
$quba = question_engine::load_questions_usage_by_activity($linkarray['area']);
if (empty($linkarray['cmid'])) {
// Try to get cm using the questions owning context.
$context = $quba->get_owning_context();
if ($context->contextlevel == CONTEXT_MODULE) {
$cm = get_coursemodule_from_id(false, $context->instanceid);
}
$linkarray['cmid'] = $cm->id;
}
// If still empty, we couldn't find cmid, so return early.
// We only support coursemodule things at the moment.
if (empty($linkarray['cmid'])) {
return '';
}
if (empty($linkarray['userid']) || (empty($linkarray['content'])) && empty($linkarray['file'])) {
// Try to get userid from attempt step.
$attempt = $quba->get_question_attempt($linkarray['itemid']);
if (empty($linkarray['userid'])) {
$linkarray['userid'] = $attempt->get_step(0)->get_user_id();
}
// If content and file not submitted, try to get the content.
if (empty($linkarray['content']) && empty($linkarray['file'])) {
$linkarray['content'] = $attempt->get_response_summary();
}
}
}
}
if (empty($plagiarismvalues[$linkarray['cmid']])) {
$plagiarismvalues[$linkarray['cmid']] = $DB->get_records_menu('plagiarism_urkund_config',
array('cm' => $linkarray['cmid']), '', 'name,value');
}
$output = $this->get_links_helper($plagiarismvalues[$linkarray['cmid']], $linkarray);
// If on a quiz report page, we want to show multiple reports in the same place.
if ($fullquizlist) {
// Get all files for this quiz submission.
if (empty($quba)) {
$quba = question_engine::load_questions_usage_by_activity($linkarray['area']);
}
if (!empty($quba) && empty($attempt)) {
$attempt = $quba->get_question_attempt($linkarray['itemid']);
}
if (!empty($attempt)) {
$context = context_module::instance($linkarray['cmid']);
$files = $attempt->get_last_qt_files('attachments', $context->id);
foreach ($files as $file) {
$linkarray['content'] = '';
$linkarray['file'] = $file;
$output .= $this->get_links_helper($plagiarismvalues[$linkarray['cmid']], $linkarray);
}
}
}
return $output;
}
/**
* Helper function to get links for a specific item.
* @param array $plagiarismvalues
* @param array $linkarray
* @return string
* @throws coding_exception
* @throws dml_exception
* @throws moodle_exception
*/
private function get_links_helper($plagiarismvalues, $linkarray) {
global $COURSE, $OUTPUT, $CFG, $DB;
$cmid = $linkarray['cmid'];
$userid = $linkarray['userid'];
$showcontent = true;
$showfiles = true;
if (!empty($plagiarismvalues['urkund_restrictcontent'])) {
if ($plagiarismvalues['urkund_restrictcontent'] == PLAGIARISM_URKUND_RESTRICTCONTENTFILES) {
$showcontent = false;
} else if ($plagiarismvalues['urkund_restrictcontent'] == PLAGIARISM_URKUND_RESTRICTCONTENTTEXT) {
$showfiles = false;
}
}
if (!empty($linkarray['content']) && $showcontent) {
$filename = "content-" . $COURSE->id . "-" . $cmid . "-" . $userid . ".htm";
$filepath = $CFG->tempdir . "/urkund/" . $filename;
$file = new stdclass();
$file->type = "tempurkund";
$file->filename = $filename;
$file->timestamp = time();
$file->identifier = sha1(plagiarism_urkund_format_temp_content($linkarray['content']));
$file->altidentifier = sha1(plagiarism_urkund_format_temp_content($linkarray['content'], true));
$file->oldidentifier = sha1($linkarray['content']);
$file->filepath = $filepath;
// TODO: Remove this when MDL-57886 is fixed.
if (!empty($linkarray['assignment'])) {
// Get raw content to calculate sha1.
$sql = "SELECT a.id, o.onlinetext
FROM {assignsubmission_onlinetext} o
JOIN {assign_submission} a ON a.id = o.submission
WHERE a.userid = ? AND o.assignment = ?
ORDER BY a.id DESC";
$moodletextsubmissions = $DB->get_records_sql($sql, array($userid, $linkarray['assignment']), 0, 1);
$moodletextsubmission = end($moodletextsubmissions);
$file->altidentifier = sha1(plagiarism_urkund_format_temp_content($moodletextsubmission->onlinetext));
}
} else if (!empty($linkarray['file']) && $showfiles) {
$file = new stdclass();
$file->filename = $linkarray['file']->get_filename();
$file->timestamp = time();
$file->identifier = $linkarray['file']->get_contenthash();
$file->filepath = $linkarray['file']->get_filepath();
} else {
return '';
}
$results = $this->get_file_results($cmid, $userid, $file);
if (empty($results)) {
// Info about this file is not available to this user.
return '';
}
$modulecontext = context_module::instance($cmid);
$output = '';
if ($results['statuscode'] == 'pending') {
// TODO: check to make sure there is a pending event entry for this file - if not add one.
$output .= '<span class="plagiarism_urkund_report">' .
'<img src="' . $OUTPUT->image_url('processing', 'plagiarism_urkund') .
'" alt="' . get_string('pending', 'plagiarism_urkund') . '" ' .
'" title="' . get_string('pending', 'plagiarism_urkund') . '" />' .
'</span>';
return $output;
}
if ($results['statuscode'] == 'Analyzed') {
// Normal situation - URKUND has successfully analyzed the file.
$rank = urkund_get_css_rank($results['score']);
$output .= '<span class="plagiarism_urkund_report">';
if (!empty($results['reporturl'])) {
// User is allowed to view the report.
// Score is contained in report, so they can see the score too.
$output .= '<a href="' . $results['reporturl'] . '" target="_blank" title="'.$file->filename.'">';
$output .= get_string('similarity', 'plagiarism_urkund') . ':';
$output .= '<span class="' . $rank . '">' . $results['score'] . '%</span>';
$output .= '</a>';
} else if ($results['score'] !== '') {
// User is allowed to view only the score.
$output .= get_string('similarity', 'plagiarism_urkund') . ':';
$output .= '<span class="' . $rank . '">' . $results['score'] . '%</span>';
}
if (!empty($results['optoutlink'])) {
// Display opt-out link.
$output .= ' <span class="plagiarismoptout">' .
'<a href="' . $results['optoutlink'] . '" target="_blank">' .
get_string('optout', 'plagiarism_urkund') .
'</a></span>';
}
if (!empty($results['renamed'])) {
$output .= $results['renamed'];
}
$output .= '</span>';
} else if ($results['statuscode'] == URKUND_STATUSCODE_ACCEPTED) {
$output .= '<span class="plagiarism_urkund_report">' .
'<img src="' . $OUTPUT->image_url('processing', 'plagiarism_urkund') .
'" alt="' . get_string('processing', 'plagiarism_urkund') . '" ' .
'" title="' . get_string('processing', 'plagiarism_urkund') . '" />' .
'</span>';
} else if ($results['statuscode'] == URKUND_STATUSCODE_UNSUPPORTED) {
$output .= '<span class="plagiarism_urkund_report">' .
'<img src="' . $OUTPUT->image_url('warning', 'plagiarism_urkund') .
'" alt="' . get_string('unsupportedfiletype', 'plagiarism_urkund') . '" ' .
'" title="' . get_string('unsupportedfiletype', 'plagiarism_urkund') . '" />' .
'</span>';
} else if ($results['statuscode'] == URKUND_STATUSCODE_TOO_LARGE) {
$output .= '<span class="plagiarism_urkund_report">' .
'<img src="' . $OUTPUT->image_url('warning', 'plagiarism_urkund') .
'" alt="' . get_string('toolarge', 'plagiarism_urkund') . '" ' .
'" title="' . get_string('toolarge', 'plagiarism_urkund') . '" />' .
'</span>';
} else {
$title = get_string('unknownwarning', 'plagiarism_urkund');
$reset = '';
if (has_capability('plagiarism/urkund:resetfile', $modulecontext) &&
!empty($results['error'])) { // This is a teacher viewing the responses.
$json = json_decode($results['error']);
if (json_last_error() == JSON_ERROR_NONE) {
$last = end($json); // When multiple results, the last one is the important one.
$errorcode = (int)$last->Status->ErrorCode;
} else {
// This is an old error - might be stored in XML.
$xml = simplexml_load_string($results['error']);
$errorcode = (int)$xml->SubmissionData->Status->ErrorCode;
}
if (!empty($errorcode)) {
$errormessage = plagiarism_urkund_get_error_string($errorcode);
} else {
$errormessage = get_string('errorcode_unknown', 'plagiarism_urkund', '');
}
$title .= ': ' . $errormessage;
$url = new moodle_url('/plagiarism/urkund/reset.php', array('cmid' => $cmid, 'pf' => $results['pid'],
'sesskey' => sesskey()));
$reset = "<a href='$url'>" . get_string('reset') . "</a>";
}
$output .= '<span class="plagiarism_urkund_report">' .
'<img src="' . $OUTPUT->image_url('warning', 'plagiarism_urkund') .
'" alt="' . get_string('unknownwarning', 'plagiarism_urkund') . '" ' .
'" title="' . $title . '" />' . $reset . '</span>';
}
return $output;
}
/**
* returns array of plagiarism details about specified file
*
* @param int $cmid
* @param int $userid
* @param object $file moodle file object
* @return array - sets of details about specified file, one array of details per plagiarism plugin
* - each set contains at least 'analyzed', 'score', 'reporturl'
*/
public function get_file_results($cmid, $userid, $file) {
global $DB, $USER, $CFG;
$plagiarismsettings = $this->get_settings();
if (empty($plagiarismsettings)) {
// Urkund is not enabled.
return false;
}
$plagiarismvalues = urkund_cm_use($cmid);
if (empty($plagiarismvalues)) {
// Urkund 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/urkund:viewreport', $modulecontext);
// Determine if the activity is past due date.
// If report is closed, this can make the report available to more users.
$assignpastdue = false;
$assignpastcutoff = false;
if ($moduledetail->name == 'assign') {
$time = time();
if ($USER->id == $userid) {
list($course, $cm) = get_course_and_cm_from_cmid($cmid, 'assign');
$assignment = new assign($modulecontext, $cm, $course);
$flags = $assignment->get_user_flags($userid, false);
}
// Check assignment due date.
if (!empty($module->duedate)) {
$assignpastdue = ($module->duedate <= $time);
if ($assignpastdue && $USER->id == $userid) {
// Check to make sure this user doesn't have an extension to the duedate.
if (!empty($flags->extensionduedate) && $flags->extensionduedate > $time) {
$assignpastdue = false;
}
}
}
// Check assignment cutoffdate.
if (!empty($module->cutoffdate)) {
$assignpastcutoff = ($module->cutoffdate <= $time);
if ($assignpastcutoff && $USER->id == $userid) {
// Check to make sure this user doesn't have an extension to the duedate.
if (!empty($flags->extensionduedate) && $flags->extensionduedate > $time) {
$assignpastcutoff = false;
}
}
}
}
// Under certain circumstances, users are allowed to see plagiarism info
// even if they don't have view report capability.
if ($USER->id == $userid || // If this is a user viewing their own report, check if settings allow it.
// In workshop and assign if the user can see the submission they might be allowed to see the urkund report.
// If they are in the forum activity they should not see other users reports.
(!$viewscore &&
$moduledetail->name <> 'forum' &&
$moduledetail->name <> 'hsuform')) { // Teamsubmisson or teacher submitted may be from different user.
$selfreport = true;
if (isset($plagiarismvalues['urkund_show_student_report']) &&
($plagiarismvalues['urkund_show_student_report'] == PLAGIARISM_URKUND_SHOW_ALWAYS) ||
($plagiarismvalues['urkund_show_student_report'] == PLAGIARISM_URKUND_SHOW_WHENDUE && $assignpastdue) ||
($plagiarismvalues['urkund_show_student_report'] == PLAGIARISM_URKUND_SHOW_WHENCUTOFF && $assignpastcutoff)) {
$viewreport = true;
}
if (isset($plagiarismvalues['urkund_show_student_score']) &&
($plagiarismvalues['urkund_show_student_score'] == PLAGIARISM_URKUND_SHOW_ALWAYS) ||
($plagiarismvalues['urkund_show_student_score'] == PLAGIARISM_URKUND_SHOW_WHENDUE && $assignpastdue) ||
($plagiarismvalues['urkund_show_student_score'] == PLAGIARISM_URKUND_SHOW_WHENCUTOFF && $assignpastcutoff)) {
$viewscore = true;
}
} else {
$selfreport = false;
}
// End of rights checking.
if (!$viewscore && !$viewreport && !$selfreport) {
// User is not permitted to see any details.
return false;
}
$params = array($cmid, $userid, $userid, $filehash);
$extrasql = '';
if (!empty($file->oldidentifier)) {
$extrasql = ' OR identifier = ?';
$params[] = $file->oldidentifier;
}
if (!empty($file->altidentifier)) {
$extrasql .= ' OR identifier = ?';
$params[] = $file->altidentifier;
}
$plagiarismfile = $DB->get_record_sql(
"SELECT * FROM {plagiarism_urkund_files}
WHERE cm = ? AND (userid = ? OR relateduserid = ?) AND " .
"(identifier = ? ".$extrasql.")", $params);
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 urkund servers.
$results = array('statuscode' => '', 'error' => '', 'reporturl' => '',
'score' => '', 'pid' => '', 'optoutlink' => '', '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 &&
strpos($plagiarismfile->filename, 'content-') !== 0) {
// Check if this is content-courseid-cmid - if so, ignore the name difference.
$previouslysubmitted = '('.get_string('previouslysubmitted', 'plagiarism_urkund').': '.$plagiarismfile->filename.')';
}
$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;
}
if (!empty($plagiarismsettings['optout']) && !empty($plagiarismfile->optout) && $selfreport) {
$results['optoutlink'] = $plagiarismfile->optout;
}
$results['renamed'] = $previouslysubmitted;
}
return $results;
}
/**
* 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, $USER, $SESSION;
$outputhtml = '';
$urkunduse = urkund_cm_use($cmid);
$plagiarismsettings = $this->get_settings();
if (!empty($plagiarismsettings['student_disclosure']) &&
!empty($urkunduse)) {
$cm = get_coursemodule_from_id('', $cmid);
if ($cm->modname == 'assign' && !empty($plagiarismsettings['assignforcedisclosureagreement'])) {
$confirmdisclosure = optional_param('ouriginalagreement', false, PARAM_BOOL);
$userid = optional_param('userid', false, PARAM_INT);
if (!empty($userid) && $userid <> $USER->id) {
// Add the notification directly to the session.
// We can't use redirect/notify here because we are mid-state.
if (!isset($SESSION->notifications) || !array($SESSION->notifications)) {
// Initialise $SESSION if necessary.
if (!is_object($SESSION)) {
$SESSION = new stdClass();
}
$SESSION->notifications = [];
}
$SESSION->notifications[] = (object) array(
'message' => get_string('cannotsubmitonbehalf', 'plagiarism_urkund'),
'type' => null,
);
$url = new moodle_url('/mod/assign/view.php', ['id' => $cmid]);
redirect($url);
}
if (!$confirmdisclosure) {
$url = new moodle_url('/plagiarism/urkund/agreement.php', ['id' => $cmid]);
redirect($url);
}
}
$outputhtml .= $OUTPUT->box_start('generalbox boxaligncenter', 'intro');
$formatoptions = new stdClass;
$formatoptions->noclean = true;
$outputhtml .= format_text($plagiarismsettings['student_disclosure'], FORMAT_MOODLE, $formatoptions);
$outputhtml .= $OUTPUT->box_end();
}
return $outputhtml;
}
/**
* Generic handler function for all events - queues files for sending.
* @param stdClass $eventdata
* @return boolean
*/
public function event_handler($eventdata) {
global $DB, $CFG;
$plagiarismsettings = $this->get_settings();
if (!$plagiarismsettings) {
return true;
}
$cmid = $eventdata['contextinstanceid'];
$plagiarismvalues = $DB->get_records_menu('plagiarism_urkund_config', array('cm' => $cmid), '', 'name, value');
if (empty($plagiarismvalues['use_urkund'])) {
// Urkund not in use for this cm - return.
return true;
}
// Check if the module associated with this event still exists.
if (!$DB->record_exists('course_modules', array('id' => $cmid))) {
return true;
}
$userid = $eventdata['userid'];
$relateduserid = null;
// Check if this is a submission on-behalf.
if (!empty($eventdata['relateduserid'])) {
$relateduserid = $eventdata['relateduserid'];
}
// Check to see if restrictcontent is in use.
$showcontent = true;
$showfiles = true;
if (!empty($plagiarismvalues['urkund_restrictcontent'])) {
if ($plagiarismvalues['urkund_restrictcontent'] == PLAGIARISM_URKUND_RESTRICTCONTENTFILES) {
$showcontent = false;
} else if ($plagiarismvalues['urkund_restrictcontent'] == PLAGIARISM_URKUND_RESTRICTCONTENTTEXT) {
$showfiles = false;
}
}
$charcount = plagiarism_urkund_charcount();
if ($eventdata['eventtype'] == 'assignsubmission_submitted' && empty($eventdata['other']['submission_editable'])) {
// Assignment-specific functionality:
// This is a 'finalize' event. No files from this event itself,
// but need to check if files from previous events need to be submitted for processing.
$result = true;
if (isset($plagiarismvalues['urkund_draft_submit']) &&
$plagiarismvalues['urkund_draft_submit'] == PLAGIARISM_URKUND_DRAFTSUBMIT_FINAL) {
// Any files attached to previous events were not submitted.
// These files are now finalized, and should be submitted for processing.
require_once("$CFG->dirroot/mod/assign/locallib.php");
require_once("$CFG->dirroot/mod/assign/submission/file/locallib.php");
$modulecontext = context_module::instance($cmid);
if ($showfiles) { // If we should be handling files.
$fs = get_file_storage();
if ($files = $fs->get_area_files($modulecontext->id, 'assignsubmission_file',
ASSIGNSUBMISSION_FILE_FILEAREA, $eventdata['objectid'], "id", false)) {
foreach ($files as $file) {
urkund_queue_file($cmid, $userid, $file, $relateduserid);
}
}
}
if ($showcontent) { // If we should be handling in-line text.
$submission = $DB->get_record('assignsubmission_onlinetext', array('submission' => $eventdata['objectid']));
if (!empty($submission) && strlen(utf8_decode(strip_tags($submission->onlinetext))) >= $charcount) {
$file = urkund_create_temp_file($cmid, $eventdata['courseid'], $userid, $submission->onlinetext);
urkund_queue_file($cmid, $userid, $file, $relateduserid);
}
}
}
return $result;
}
if ($eventdata['eventtype'] == 'quiz_submitted') {
$result = true;
$attemptid = $eventdata['objectid'];
plagiarism_urkund_quiz_queue_attempt($attemptid, true);
return $result;
}
if (isset($plagiarismvalues['urkund_draft_submit']) &&
$plagiarismvalues['urkund_draft_submit'] == PLAGIARISM_URKUND_DRAFTSUBMIT_FINAL) {
// Assignment-specific functionality:
// Files should only be sent for checking once "finalized".
return true;
}
// Text is attached.
$result = true;
if (!empty($eventdata['other']['content']) && $showcontent &&
strlen(utf8_decode(strip_tags($eventdata['other']['content']))) >= $charcount) {
$file = urkund_create_temp_file($cmid, $eventdata['courseid'], $userid, $eventdata['other']['content']);
urkund_queue_file($cmid, $userid, $file, $relateduserid);
}
// Normal situation: 1 or more assessable files attached to event, ready to be checked.
if (!empty($eventdata['other']['pathnamehashes']) && $showfiles) {
foreach ($eventdata['other']['pathnamehashes'] as $hash) {
$fs = get_file_storage();
$efile = $fs->get_file_by_hash($hash);
if (empty($efile)) {
continue;
} else if ($efile->get_filename() === '.') {
// This 'file' is actually a directory - nothing to submit.
continue;
}
urkund_queue_file($cmid, $userid, $efile, $relateduserid);
}
}
return $result;
}
/**
* Send student e-mail when score available.
*
* @param stdClass $plagiarismfile - file record.
*/
public function urkund_send_student_email($plagiarismfile) {
global $DB, $CFG;
if (empty($plagiarismfile->userid)) { // Sanity check.
return false;
}
if (!empty($plagiarismfile->relateduserid)) {
$user = $DB->get_record('user', array('id' => $plagiarismfile->relateduserid));
} else {
$user = $DB->get_record('user', array('id' => $plagiarismfile->userid));
}
$site = get_site();
$a = new stdClass();
$cm = get_coursemodule_from_id('', $plagiarismfile->cm);
$a->modulename = format_string($cm->name);
$a->modulelink = $CFG->wwwroot.'/mod/'.$cm->modname.'/view.php?id='.$cm->id;
$a->coursename = format_string($DB->get_field('course', 'fullname', array('id' => $cm->course)));
$plagiarismsettings = $this->get_settings();
if (!empty($plagiarismsettings['optout'])) {
$a->optoutlink = $plagiarismfile->optout;
$emailcontent = get_string('studentemailcontent', 'plagiarism_urkund', $a);
} else {
$emailcontent = get_string('studentemailcontentnoopt', 'plagiarism_urkund', $a);
}
$emailsubject = get_string('studentemailsubject', 'plagiarism_urkund');
email_to_user($user, $site->shortname, $emailsubject, $emailcontent);
}
/**
* Validates receiver address.
*
* @param string $receiver
*/
public function validate_receiver($receiver) {
if (defined('BEHAT_SITE_RUNNING')) {
// If running behat tests/ fake a failure.
return false;
}
$plagiarismsettings = $this->get_settings();
$url = get_config('plagiarism_urkund', 'api') .'/api/receivers'.'/'. trim($receiver);;
$headers = array('Accept-Language: '.$plagiarismsettings['lang']);
$allowedstatus = array(URKUND_STATUSCODE_PROCESSED,
URKUND_STATUSCODE_NOT_FOUND,
URKUND_STATUSCODE_BAD_REQUEST,
URKUND_STATUSCODE_GONE);
// Use Moodle curl wrapper.
$c = new curl(array('proxy' => true));
$c->setopt(array());
$c->setopt(array('CURLOPT_RETURNTRANSFER' => 1,
'CURLOPT_TIMEOUT' => 60, // Set to 60seconds just in case.
'CURLOPT_HTTPAUTH' => CURLAUTH_BASIC,
'CURLOPT_USERPWD' => $plagiarismsettings['username'].":".$plagiarismsettings['password']));
$c->setHeader($headers);
$response = $c->get($url);
$httpstatus = $c->info['http_code'];
if (!empty($httpstatus)) {
if (in_array($httpstatus, $allowedstatus)) {
if ($httpstatus == URKUND_STATUSCODE_PROCESSED) {
// Valid address found, return true.
return true;
} else {
return $httpstatus;
}
}
}
return false;
}
/**
* Executes a call to URKUND's API to see if a receiver address exists for the logged in user.
* If so we store that receiver address in the user preferences.
* Otherwise we attempt to create a receiver address.
*/
public function load_receiver() {
global $USER;
$plagiarismsettings = self::get_settings();
$headers = array('Accept: application/json', 'Content-Type: application/json');
$c = new curl(array('proxy' => true));
$c->setopt(array());
$c->setopt(array('CURLOPT_RETURNTRANSFER' => 1,
'CURLOPT_TIMEOUT' => 60, // Set to 60seconds just in case.
'CURLOPT_HTTPAUTH' => CURLAUTH_BASIC,
'CURLOPT_USERPWD' => $plagiarismsettings['username'].":".$plagiarismsettings['password']));
$c->setHeader($headers);
$email = $USER->email;
$name = $USER->firstname . " " . $USER->lastname;
$response = $c->get(get_config('plagiarism_urkund', 'api') . "/api/receivers?emailAddress=" . urlencode($email));
$status = $c->info['http_code'];
if (!empty($status)) {
$json = json_decode($response);
if (count($json) > 0 && !empty($json[0]->AnalysisAddress)) {
// Receiver linked to this user found.
set_user_preference('urkund_receiver', trim($json[0]->AnalysisAddress));
return array('receiver' => trim($json[0]->AnalysisAddress), 'retrieved' => true);
} else {
// No receiver found that matches this user.
if (!empty(get_config('plagiarism_urkund', 'unitid'))) {
// If Unit id is set, we can try to create a receiver address for this user.
$data = array(
'UnitId' => (int)get_config('plagiarism_urkund', 'unitid'),
'Fullname' => $name,
'EmailAddress' => $email,
);
// Create a receiver for this user.
$response = $c->post(get_config('plagiarism_urkund', 'api') . "/api/receivers", json_encode($data));
$status = $c->info['http_code'];
if (!empty($status)) {
if ($status == '403') {
return array('error' => true, 'msg' => get_string('errorcode_403', 'plagiarism_urkund'));
} else if ($status == '409') {
return array('error' => true, 'msg' => get_string('errorcode_409', 'plagiarism_urkund'));
}
$json = json_decode($response);
if (count($json) > 0 && !empty($json->AnalysisAddress)) {
// Receiver address was found.
set_user_preference('urkund_receiver', trim($json->AnalysisAddress));
return array('receiver' => trim($json->AnalysisAddress), 'created' => true);
}
}
}
}
}
return array('error' => true, 'msg' => get_string('errorcreate', 'plagiarism_urkund'));
}
}
/**
* Create temp file for text content
*
* @param int $cmid - coursemodule id.
* @param int $courseid - course id.
* @param int $userid - user id.
* @param string $filecontent - raw content of file.
*
* @return string
*/
function urkund_create_temp_file($cmid, $courseid, $userid, $filecontent) {
global $CFG;
if (!check_dir_exists($CFG->tempdir."/urkund", true, true)) {
mkdir($CFG->tempdir."/urkund", 0700);
}
$filename = "content-" . $courseid . "-" . $cmid . "-" . $userid ."-". random_string(8).".htm";
$filepath = $CFG->tempdir."/urkund/" . $filename;
$fd = fopen($filepath, 'wb'); // Create if not exist, write binary.
// Write html and body tags as it seems that Urkund doesn't works well without them.
$content = plagiarism_urkund_format_temp_content($filecontent);
fwrite($fd, $content);
fclose($fd);
return $filepath;
}
/**
* Helper function used to add extra html around file contents.
*
* @param string $content - raw content of file.
* @param boolean $strippretag - should we strip tags first.
*
* @return string
*/
function plagiarism_urkund_format_temp_content($content, $strippretag = false) {
// See MDL-57886.
if ($strippretag) {
$content = substr($content, 25, strlen($content) - 31);
}
return '<html>' .
'<head>' .
'<meta charset="UTF-8">' .
'</head>' .
'<body>' .
$content .
'</body></html>';
}
/**
* Hook to save plagiarism specific settings on a module settings page.
*
* @param stdClass $data
* @param stdClass $course
*/
function plagiarism_urkund_coursemodule_edit_post_actions($data, $course) {
global $DB;
$plugin = new plagiarism_plugin_urkund();
if (!$plugin->get_settings()) {
return $data;
}
if (isset($data->use_urkund)) {
if (empty($data->submissiondrafts)) {
// Make sure draft_submit is not set if submissiondrafts not used.
$data->urkund_draft_submit = 0;
}
// Array of possible plagiarism config options.
$plagiarismelements = $plugin->config_options();
$contextmodule = context_module::instance($data->coursemodule);
foreach ($plagiarismelements as $key => $elements) {
if (!has_capability('plagiarism/urkund:resubmitonclose', $contextmodule) &&
$elements == 'urkund_resubmit_on_close') {
unset($plagiarismelements[$key]);
}
}
// First get existing values.
if (empty($data->coursemodule)) {
debugging("URKUND settings failure - no coursemodule set in form data, URKUND could not be enabled.");
return $data;
}
$existingelements = $DB->get_records_menu('plagiarism_urkund_config', array('cm' => $data->coursemodule),
'', 'name, id');
foreach ($plagiarismelements as $element) {
// Don't allow changes to receiver address if urkund is disabled.
if (empty($data->use_urkund) && $element == 'urkund_receiver') {
continue;
}
$newelement = new stdClass();
$newelement->cm = $data->coursemodule;
$newelement->name = $element;
if (isset($data->$element) && is_array($data->$element)) {
$newelement->value = implode(',', $data->$element);
} else {
$newelement->value = (isset($data->$element) ? $data->$element : 0);
}
if (isset($existingelements[$element])) {
$newelement->id = $existingelements[$element];
$DB->update_record('plagiarism_urkund_config', $newelement);
} else {
$DB->insert_record('plagiarism_urkund_config', $newelement);
}
}
// Don't save user preference if this assignment doesn't use Urkund.
if (!empty($data->urkund_receiver) && !empty($data->use_urkund)) {
set_user_preference('urkund_receiver', trim($data->urkund_receiver));
}
// If we are forcing requiresubmissionstatement setting, check that it is set correctly.
if ($data->modulename == 'assign' && !empty(get_config('plagiarism_urkund', 'assignforcesubmissionstatement'))
&& empty($data->requiresubmissionstatement) && !empty($data->instance)) {
// We need to update the requiresubmissionstatement for this assignment.
$sql = "UPDATE {assign} set requiresubmissionstatement = 1 WHERE id = ?";
$DB->execute($sql, array($data->instance));
}
}
return $data;
}
/**
* Validate receiver address
*
* @param stdClass $data
* @return array $errors
*/
function plagiarism_urkund_coursemodule_validation($data) {
$data = $data->get_submitted_data();
if (!empty($data->use_urkund)) {
$plugin = new plagiarism_plugin_urkund();
if (empty($data->urkund_receiver)) {
$result = $plugin->load_receiver();
if (!empty($result['error']) && !empty($result['msg'])) {
return array('urkund_receiver' => $result['msg']);
}
return array('urkund_receiver' => get_string('receivernotvalid', 'plagiarism_urkund'));
}
$result = $plugin->validate_receiver($data->urkund_receiver);
if ($result === 404) {
return array('urkund_receiver' => get_string('receivernotvalid', 'plagiarism_urkund'));
}
}
return array();
}
/**
* Hook to add plagiarism specific settings to a module settings page
*
* @param moodleform $formwrapper