-
Notifications
You must be signed in to change notification settings - Fork 0
/
lib.php
1588 lines (1492 loc) · 76.5 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 Turnitin specific functions called by Modules.
*
* @since 2.0
* @package plagiarism_turnitin
* @subpackage plagiarism
* @copyright 2010 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
}
define('PLAGIARISM_TII_SHOW_NEVER', 0);
define('PLAGIARISM_TII_SHOW_ALWAYS', 1);
define('PLAGIARISM_TII_SHOW_CLOSED', 2);
define('PLAGIARISM_TII_DRAFTSUBMIT_IMMEDIATE', 0);
define('PLAGIARISM_TII_DRAFTSUBMIT_FINAL', 1);
//Turnitin fcmd types - return values.
define('TURNITIN_LOGIN', 1);
define('TURNITIN_RETURN_XML', 2);
define('TURNITIN_UPDATE_RETURN_XML', 3);
// Turnitin user types
define('TURNITIN_STUDENT', 1);
define('TURNITIN_INSTRUCTOR', 2);
define('TURNITIN_ADMIN', 3);
//Turnitin API actions.
define('TURNITIN_CREATE_USER', 1);
define('TURNITIN_CREATE_CLASS', 2);
define('TURNITIN_JOIN_CLASS', 3);
define('TURNITIN_CREATE_ASSIGNMENT', 4);
define('TURNITIN_SUBMIT_PAPER', 5);
define('TURNITIN_RETURN_REPORT', 6);
define('TURNITIN_VIEW_SUBMISSION', 7);
define('TURNITIN_DELETE_SUBMISSION', 8); //unlikely to need this.
define('TURNITIN_LIST_SUBMISSIONS', 10);
define('TURNITIN_CHECK_SUBMISSION', 11);
define('TURNITIN_ADMIN_STATS', 12);
define('TURNITIN_RETURN_GRADEMARK', 13);
define('TURNITIN_REPORT_TIME', 14);
define('TURNITIN_SUBMISSION_SCORE', 15);
define('TURNITIN_START_SESSION', 17);
define('TURNITIN_END_SESSION', 18);
//Turnitin allowed file types
define('TURNITIN_TYPE_TEXT', 1);
define('TURNITIN_TYPE_FILE', 2);
//Turnitin Response codes - there are many more of these, just not used directly.
//
define('TURNITIN_RESP_USER_CREATED', 11); // User creation successful, do not send to login
define('TURNITIN_RESP_CLASS_CREATED_LOGIN', 20); // Class created successfully, send to login
define('TURNITIN_RESP_CLASS_CREATED', 21); // Class Created successfully, do not send to login
define('TURNITIN_RESP_CLASS_UPDATED', 22); // Class updated successfully
define('TURNITIN_RESP_USER_JOINED', 31); // successful, User joined to class, do not sent to login
define('TURNITIN_RESP_ASSIGN_CREATED', 41); // Assignment Created
define('TURNITIN_RESP_ASSIGN_MODIFIED', 42); // Assignment modified
define('TURNITIN_RESP_ASSIGN_DELETED', 43); // Assignment deleted
define('TURNITIN_RESP_PAPER_SENT', 51); // paper submitted
define('TURNITIN_RESP_SCORE_RECEIVED', 61); // Originality score retrieved.
define('TURNITIN_RESP_ASSIGN_EXISTS', 419); // Assignment already exists.
define('TURNITIN_RESP_SCORE_NOT_READY', 415);
//get global class
global $CFG;
require_once($CFG->dirroot.'/plagiarism/lib.php');
///// Turnitin Class ////////////////////////////////////////////////////
class plagiarism_plugin_turnitin extends plagiarism_plugin {
public function get_links($linkarray) {
global $DB, $USER, $COURSE, $CFG;
$cmid = $linkarray['cmid'];
$userid = $linkarray['userid'];
$file = $linkarray['file'];
$results = $this->get_file_results($cmid, $userid, $file);
if (empty($results)) {
// Cron has not run yet
return '<br />';
}
if (array_key_exists('error', $results)) {
return $results['error'];
}
if (empty($results['analyzed'])) {
return '<br />';
}
// TII has successfully returned a score.
$rank = plagiarism_get_css_rank($results['score']);
$similaritystring = '<span class="' . $rank . '">' . $results['score'] . '%</span>';
if (!empty($results['reporturl'])) {
// User gets to see link to similarity report & similarity score
$output = '<span class="plagiarismreport"><a href="' . $results['reporturl'] . '" target="_blank">';
$output .= get_string('similarity', 'plagiarism_turnitin').':</a>' . $similaritystring . '</span>';
} else {
// User only sees similarity score
$output = '<span class="plagiarismreport">' . get_string('similarity', 'plagiarism_turnitin') . $similaritystring . '</span>';
}
//now check if grademark enabled and return the status of this file.
if (!empty($results['grademarklink'])) {
$output .= '<span class="grademark">' . $results['grademarklink'] . "</span>";
}
return $output.'<br/>';
}
/**
* Get the information turnitin has about a file
* @param int $cmid the id of the coursemodule file was submitted for
* @param int $userid the id of the user who submitted the file
* @param stored_file $file file object describing a moodle file which was submited to TII
* @return mixed - false if no info available, or an array describing what's known about the TII submission
*/
public function get_file_results($cmid, $userid, stored_file $file) {
global $DB, $USER, $COURSE, $OUTPUT;
$plagiarismsettings = $this->get_settings();
if (empty($plagiarismsettings)) {
// Turnitin is not enabled
return false;
}
$plagiarismvalues = $DB->get_records_menu('plagiarism_turnitin_config', array('cm'=>$cmid),'','name,value');
if (empty($plagiarismvalues['use_turnitin'])) {
// Turnitin not in use for this cm
return false;
}
$filehash = $file->get_pathnamehash();
$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)) {
$module = $DB->get_record($moduledetail->name, array('id'=>$moduledetail->instance));
}
if (empty($module)) {
// No such cmid
return false;
}
$modulecontext = get_context_instance(CONTEXT_MODULE, $cmid);
// Whether the user has permissions to see all items in the context of this module.
$viewsimilarityscore = has_capability('plagiarism/turnitin:viewsimilarityscore', $modulecontext);
$viewfullreport = has_capability('plagiarism/turnitin:viewfullreport', $modulecontext);
if ($USER->id == $userid) {
// The user wants to see details on their own report
if ($plagiarismvalues['plagiarism_show_student_score'] == PLAGIARISM_TII_SHOW_ALWAYS) {
$viewsimilarityscore = true;
}
if ($plagiarismvalues['plagiarism_show_student_report'] == PLAGIARISM_TII_SHOW_ALWAYS) {
$viewfullreport = true;
}
}
if (!$viewsimilarityscore && !$viewfullreport) {
// The user has no right to see the requested detail.
return false;
}
$plagiarismfile = $DB->get_record('plagiarism_turnitin_files',
array('cm' => $cmid, 'userid' => $userid, 'identifier' => $filehash));
if (empty($plagiarismfile)) {
// No record of that submission - so no links can be returned
return false;
}
$results = array(
'analyzed' => 0,
'score' => '',
'reporturl' => '',
);
if (isset($plagiarismfile->statuscode) && $plagiarismfile->statuscode != 'success') {
//always display errors - even if the student isn't able to see report/score.
$results['error'] = turnitin_error_text($plagiarismfile->statuscode);
return $results;
}
// All non-standard situations handled.
$results['analyzed'] = 1;
$results['score'] = $plagiarismfile->similarityscore;
if ($viewfullreport) {
// User gets to see link to similarity report
$results['reporturl'] = turnitin_get_report_link($plagiarismfile, $COURSE, $plagiarismsettings);
}
if (!empty($plagiarismsettings['turnitin_enablegrademark'])) {
$results['grademarklink'] = turnitin_get_grademark_link($plagiarismfile, $COURSE, $module, $plagiarismsettings);
}
return $results;
}
public function save_form_elements($data) {
global $DB;
if (!$this->get_settings()) {
return;
}
if (isset($data->use_turnitin)) {
//array of posible plagiarism config options.
$plagiarismelements = $this->config_options();
//first get existing values
$existingelements = $DB->get_records_menu('plagiarism_turnitin_config', array('cm'=>$data->coursemodule),'','name,id');
foreach($plagiarismelements as $element) {
$newelement = new object();
$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_turnitin_config', $newelement);
} else { //insert
$DB->insert_record('plagiarism_turnitin_config', $newelement);
}
}
}
}
public function get_form_elements_module($mform, $context) {
global $CFG, $DB;
if (!$this->get_settings()) {
return;
}
$cmid = optional_param('update', 0, PARAM_INT); //there doesn't seem to be a way to obtain the current cm a better way - $this->_cm is not available here.
if (!empty($cmid)) {
$plagiarismvalues = $DB->get_records_menu('plagiarism_turnitin_config', array('cm'=>$cmid),'','name,value');
}
$plagiarismdefaults = $DB->get_records_menu('plagiarism_turnitin_config', array('cm'=>0),'','name,value'); //cmid(0) is the default list.
$plagiarismelements = $this->config_options();
if (has_capability('plagiarism/turnitin:enable', $context)) {
turnitin_get_form_elements($mform);
if ($mform->elementExists('plagiarism_draft_submit')) {
$mform->disabledIf('plagiarism_draft_submit', 'var4', 'eq', 0);
}
//disable all plagiarism elements if use_plagiarism eg 0
foreach ($plagiarismelements as $element) {
if ($element <> 'use_turnitin') { //ignore this var
$mform->disabledIf($element, 'use_turnitin', 'eq', 0);
}
}
//check if files have already been submitted and disable exclude biblio and quoted if turnitin is enabled.
if ($DB->record_exists('plagiarism_turnitin_files', array('cm'=> $cmid))) {
$mform->disabledIf('plagiarism_exclude_biblio','use_turnitin');
$mform->disabledIf('plagiarism_exclude_quoted','use_turnitin');
}
} 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]);
}
}
}
public function print_disclosure($cmid) {
global $DB, $OUTPUT;
if ($plagiarismsettings = $this->get_settings()) {
if (!empty($plagiarismsettings['turnitin_student_disclosure'])) {
$params = array('cm' => $cmid, 'name' => 'use_turnitin');
$showdisclosure = $DB->get_field('plagiarism_turnitin_config', 'value', $params);
if ($showdisclosure) {
echo $OUTPUT->box_start('generalbox boxaligncenter', 'intro');
$formatoptions = new stdClass;
$formatoptions->noclean = true;
echo format_text($plagiarismsettings['turnitin_student_disclosure'], FORMAT_MOODLE, $formatoptions);
echo $OUTPUT->box_end();
}
}
}
}
/**
* 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 relavant settings.
*/
public function get_settings() {
global $DB;
$plagiarismsettings = (array)get_config('plagiarism');
//check if tii enabled.
if (isset($plagiarismsettings['turnitin_use']) && $plagiarismsettings['turnitin_use'] && isset($plagiarismsettings['turnitin_accountid']) && $plagiarismsettings['turnitin_accountid']) {
//now check to make sure required settings are set!
if (empty($plagiarismsettings['turnitin_secretkey'])) {
print_error('missingkey', 'plagiarism_turnitin');
}
return $plagiarismsettings;
} else {
return false;
}
}
public function config_options() {
return array('use_turnitin','plagiarism_show_student_score','plagiarism_show_student_report',
'plagiarism_draft_submit','plagiarism_compare_student_papers','plagiarism_compare_internet',
'plagiarism_compare_journals','plagiarism_compare_institution','plagiarism_report_gen',
'plagiarism_exclude_biblio','plagiarism_exclude_quoted','plagiarism_exclude_matches',
'plagiarism_exclude_matches_value','plagiarism_anonymity');
}
public function update_status($course, $cm) {
global $DB, $USER, $OUTPUT;
$userprofilefieldname = 'turnitinteachercoursecache';
if (!$plagiarismsettings = $this->get_settings()) {
return;
}
// If Turinitin has already been told about this user's rights in this course,
// the courseid will exist in a comma separated listed in a hidden profile field.
// Thus stored so that we don't repeatedly advise turnitin, and site admins can clear the cache if so desired.
$newrecord = null;
if (!isset($USER->profile)) {
// User has had a partial login - possibly over web services.
// Check for profile details directly in DB:
$sql = 'SELECT uid.id, uid,data ' .
'FROM {user_info_field} uif ' .
' INNER JOIN {user_info_data} uid ON uid.fieldid = uif.id ' .
'WHERE uif.shortname = ? '.
' AND uid.userid = ? ';
$userprofiledetail = $DB->get_record_sql($sql, array($userprofilefieldname, $USER->id));
if (!empty($userprofiledetail)) {
$existingcourses = explode(',', $userprofiledetail->data);
$newrecord = false;
} else {
$existingcourses = array();
$newrecord = true;
}
} else if (!empty($USER->profile[$userprofilefieldname])) {
$existingcourses = explode(',', $USER->profile[$userprofilefieldname]);
$newrecord = false;
} else {
$existingcourses = array();
$sql = 'SELECT uid.id ' .
' FROM {user_info_field} uif ' .
' INNER JOIN {user_info_data} uid ON uid.fieldid = uif.id ' .
' WHERE uif.shortname = ? ' .
' AND uid.userid = ? ';
if (!$DB->record_exists_sql($sql, array($userprofilefieldname, $USER->id))) {
$newrecord = true;
} else {
$newrecord = false;
}
}
if (!in_array($course->id, $existingcourses)) {
// Turnititin doesn't (yet) know that this user is a teacher in this course. Tell them:
$tii = array();
$tii['utp'] = TURNITIN_INSTRUCTOR;
$tii = turnitin_get_tii_user($tii, $USER);
$tii['cid'] = get_config('plagiarism_turnitin_course', $course->id); //course ID
$tii['ctl'] = (strlen($course->shortname) > 45 ? substr($course->shortname, 0, 45) : $course->shortname);
$tii['ctl'] = (strlen($tii['ctl']) > 5 ? $tii['ctl'] : $tii['ctl']."_____");
$tii['fcmd'] = TURNITIN_RETURN_XML;
$tii['fid'] = TURNITIN_CREATE_CLASS;
$tiixml = plagiarism_get_xml(turnitin_get_url($tii, $plagiarismsettings));
if ($tiixml->rcode[0] != TURNITIN_RESP_CLASS_CREATED) {
$OUTPUT->notification(get_string('errorassigninguser','plagiarism_turnitin'));
return;
}
$existingcourses[] = $course->id;
$newcoursecache = implode(',',$existingcourses);
// Now update our record of what teacherships TII knows about:
$userprofilefieldid = $DB->get_field('user_info_field', 'id', array('shortname'=>$userprofilefieldname));
if ($newrecord) {
// New field - will need to insert a new record.
$userdata = new stdclass();
$userdata->userid = $USER->id;
$userdata->fieldid = $userprofilefieldid;
$userdata->data = $newcoursecache;
$DB->insert_record('user_info_data', $userdata);
} else {
$DB->set_field('user_info_data','data', $newcoursecache,array('userid'=>$USER->id, 'fieldid'=>$userprofilefieldid));
}
$USER->profile[$userprofilefieldname] = $newcoursecache;
}
$tii = array();
//print link to teacher login
$tii['fcmd'] = TURNITIN_LOGIN; //when set to 2 this returns XML
$tii['utp'] = TURNITIN_INSTRUCTOR;
$tii['fid'] = TURNITIN_CREATE_USER; //set commands - Administrator login/statistics.
$tii = turnitin_get_tii_user($tii, $USER);
echo '<div style="text-align:right"><a href="'.turnitin_get_url($tii, $plagiarismsettings).'" target="_blank">'.get_string("teacherlogin","plagiarism_turnitin").'</a></div>';
//currently only used for grademark - check if enabled and return if not.
//TODO: This call degrades page performance - need to run less frequently.
if (empty($plagiarismsettings['turnitin_enablegrademark'])) {
return;
}
if (!$moduletype = $DB->get_field('modules','name', array('id'=>$cm->module))) {
debugging("invalid moduleid! - moduleid:".$cm->module);
}
if (!$module = $DB->get_record($moduletype, array('id'=>$cm->instance))) {
debugging("invalid instanceid! - instance:".$cm->instance." Module:".$moduletype);
}
//set globals.
$tii['utp'] = TURNITIN_INSTRUCTOR;
$tii = turnitin_get_tii_user($tii, $USER);
$tii['cid'] = get_config('plagiarism_turnitin_course', $course->id); //course ID
$tii['ctl'] = (strlen($course->shortname) > 45 ? substr($course->shortname, 0, 45) : $course->shortname);
$tii['ctl'] = (strlen($tii['ctl']) > 5 ? $tii['ctl'] : $tii['ctl']."_____");
$turnitin_assignid = $DB->get_field('plagiarism_turnitin_config','value', array('cm'=>$cm->id, 'name'=>'turnitin_assignid'));
if (!empty($turnitin_assignid)) {
$tii['assignid'] = $turnitin_assignid;
}
$tii['assign'] = turnitin_get_assign_name($module->name, $cm->id); //assignment name stored in TII
$tii['fcmd'] = TURNITIN_RETURN_XML;
$tii['fid'] = TURNITIN_LIST_SUBMISSIONS;
$tiixml = plagiarism_get_xml(turnitin_get_url($tii, $plagiarismsettings));
if (!empty($tiixml->object)) {
//get full list of turnitin_files for this cm
$grademarkstatus= array();
foreach($tiixml->object as $tiiobject) {
$grademarkstatus[(int)$tiiobject->objectID[0]] = (int)$tiiobject->gradeMarkStatus[0];
}
if (!empty($grademarkstatus)) {
$plagiarsim_files = $DB->get_records('plagiarism_turnitin_files', array('cm'=>$cm->id));
foreach ($plagiarsim_files as $file) {
if (isset($grademarkstatus[$file->externalid]) && $file->externalstatus <> $grademarkstatus[$file->externalid]) {
$file->externalstatus = $grademarkstatus[$file->externalid];
$DB->update_record('plagiarism_turnitin_files', $file);
}
}
}
}
}
/**
* used by admin/cron.php to get similarity scores from submitted files.
*
*/
public function cron() {
global $CFG, $DB;
require_once("$CFG->libdir/filelib.php"); //HACK to include filelib so that when event cron is run then file_storage class is available
$plagiarismsettings = $this->get_settings();
if ($plagiarismsettings) {
turnitin_get_scores($plagiarismsettings);
}
//get list of files that need to be resubmitted - sanity check against cm
if (!empty($plagiarismsettings['turnitin_attempts']) && is_numeric($plagiarismsettings['turnitin_attempts'])
&& !empty($plagiarismsettings['turnitin_attemptcodes'])) {
$attemptcodes = explode(',',trim($plagiarismsettings['turnitin_attemptcodes']));
list($usql, $params) = $DB->get_in_or_equal($attemptcodes);
$sql = "SELECT tf.*
FROM {plagiarism_turnitin_files} tf, {course_modules} cm
WHERE tf.cm = cm.id AND
tf.statuscode $usql AND tf.attempt < ".$plagiarismsettings['turnitin_attempts'];
$items = $DB->get_records_sql($sql, $params);
foreach ($items as $item) {
$fs = get_file_storage();
$file = $fs->get_file_by_hash($item->identifier);
if ($file) {
$pid = plagiarism_update_record($item->cm, $item->userid, $file->get_pathnamehash(), $item->attempt+1);
if (!empty($pid)) {
turnitin_send_file($pid, $plagiarismsettings, $file);
}
} else {
debugging('file resubmit attempted but file not found id:'.$item->id, DEBUG_DEVELOPER);
}
}
}
}
public function event_handler($eventdata) {
global $DB, $CFG;
$plagiarismsettings = $this->get_settings();
$cmid = (!empty($eventdata->cm->id)) ? $eventdata->cm->id : $eventdata->cmid;
$plagiarismvalues = $DB->get_records_menu('plagiarism_turnitin_config', array('cm'=>$cmid),'','name,value');
if (!$plagiarismsettings || empty($plagiarismvalues['use_turnitin'])) {
//nothing to do here... move along!
return true;
}
if ($eventdata->eventtype == "mod_created") {
return turnitin_update_assignment($plagiarismsettings, $plagiarismvalues, $eventdata, 'create');
} else if ($eventdata->eventtype=="mod_updated") {
return turnitin_update_assignment($plagiarismsettings, $plagiarismvalues, $eventdata, 'update');
} else if ($eventdata->eventtype=="mod_deleted") {
return turnitin_update_assignment($plagiarismsettings, $plagiarismvalues, $eventdata, 'delete');
} else if ($eventdata->eventtype=="file_uploaded") {
// check if the module associated with this event still exists
$cm = $DB->get_record('course_modules', array('id' => $eventdata->cmid));
$modulename = $DB->get_field('modules', 'name', array('id' => $cm->module));
if (!$cm) {
return true;
}
// If the assignment has only just been set up, we don't want to try to submit to it, or
// we'll get a 1001 error
$assignmentstarttime = $DB->get_field('plagiarism_turnitin_config', 'value', array('cm' => $cm->id,
'name' => 'turnitin_dtstart'));
if ($assignmentstarttime > time()) {
// May not be set up properly - we need to allow for wonky server clocks.
mtrace("Warning: assignment start time is too early ".date('Y-m-d H:i:s', $assignmentstarttime)." cmid:". $eventdata->cmid." will delay sending files until next cron");
return false;
}
if (!empty($eventdata->file) && empty($eventdata->files)) { //single assignment type passes a single file
$eventdata->files[] = $eventdata->file;
}
if (empty($eventdata->files)) {
// There are no files attached to this 'fileuploaded' event.
// This is a 'finalize' event - assignment-focused functionality
mtrace("finalise");
if (isset($plagiarismvalues['plagiarism_draft_submit'])
&& $plagiarismvalues['plagiarism_draft_submit'] == PLAGIARISM_TII_DRAFTSUBMIT_FINAL) {
// Drafts haven't previously been sent
// get assignment details, list of draft files and submit to TII.
require_once("$CFG->dirroot/mod/$modulename/lib.php");
// we need to get a list of files attached to this assignment and put them in an array, so that
// we can submit each of them for processing.
$assignmentbase = new assignment_base($cmid);
$submission = $assignmentbase->get_submission($eventdata->userid);
$modulecontext = get_context_instance(CONTEXT_MODULE, $eventdata->cmid);
$fs = get_file_storage();
$result = true;
if ($files = $fs->get_area_files($modulecontext->id, 'mod_'.$modulename, 'submission', $submission->id, "timemodified", false)) {
foreach ($files as $file) {
$fileresult = false;
//TODO: need to check if this file has already been sent! - possible that the file was sent before draft submit was set.
$pid = plagiarism_update_record($cmid, $eventdata->userid, $file->get_pathnamehash());
if (!empty($pid)) {
$fileresult = turnitin_send_file($pid, $plagiarismsettings, $file);
}
$result = $fileresult && $result;
}
}
return $result;
}
}
// Assignment-module focused functionality:
if (isset($plagiarismvalues['plagiarism_draft_submit'])
&& $plagiarismvalues['plagiarism_draft_submit'] == PLAGIARISM_TII_DRAFTSUBMIT_FINAL) {
// Files shouldn't be submitted to TII until 'finalize' file upload event.
return true;
}
// Normal scenario - this is an upload event with one or more attached files
// Attached file(s) are to be immediately submitted to TII
$result = true;
foreach ($eventdata->files as $efile) {
$fileresult = false;
if ($efile->get_filename() ==='.') {
// This is a directory - nothing to do.
continue;
}
//hacky way to check file still exists
$fs = get_file_storage();
$fileid = $fs->get_file_by_hash($efile->get_pathnamehash());
if (empty($fileid)) {
mtrace("nofilefound!");
continue;
}
//TODO - check if this particular file has already been submitted.
$pid = plagiarism_update_record($cmid, $eventdata->userid, $efile->get_pathnamehash());
if (!empty($pid)) {
$fileresult = turnitin_send_file($pid, $plagiarismsettings, $efile);
}
$result = $result && $fileresult;
}
return $result;
} else if ($eventdata->eventtype=="quizattempt") {
//get list of essay questions and the users answer in this quiz
$sql = "SELECT s.* FROM {question} q, {quiz_question_instances} i, {question_states} s, {question_sessions} qs
WHERE i.quiz = ? AND i.quiz=q.id AND q.qtype='essay'
AND s.question = q.id AND qs.questionid= q.id AND qs.newest = s.id AND qs.attemptid = s.attempt AND s.attempt = ?";
$essayquestions = $DB->get_records_sql($sql, array($eventdata->quiz, $eventdata->attempt));
//check dir exists
if (!file_exists($CFG->dataroot."/temp/turnitin")) {
if (!file_exists($CFG->dataroot."/temp")) {
mkdir($CFG->dataroot."/temp",0700);
}
mkdir($CFG->dataroot."/temp/turnitin",0700);
}
foreach($essayquestions as $qid) {
//get actual response
//create file to send
$pid = plagiarism_update_record($cmid, $eventdata->userid, $qid->id);
if (!empty($pid)) {
$file = new stdclass();
$file->type = "tempturnitin";
$file->filename = $pid .".txt";
$file->timestamp = $qid->timestamp;
$file->filepath = $CFG->dataroot."/temp/turnitin/" . $pid .".txt";
$fd = fopen($file->filepath,'wb'); //create if not exist, write binary
fwrite( $fd, $qid->answer);
fclose( $fd );
$result = turnitin_send_file($pid, $plagiarismsettings, $file);
unlink($file->filepath); //delete temp file.
}
}
return true;
} else {
//return true; //Don't need to handle this event
}
}
}
//functions specific to the Turnitin plagiarism tool
/**
* generates a url including md5 for use in posting to Turnitin API.
*
* @param object $tii the intial $tii object
* @param bool $returnArray - if true, returns a formatted $tii object, if false returns a url.
* @return mixed - array or url depending on $returnArray.
*/
function turnitin_get_url($tii, $plagiarismsettings, $returnArray=false, $pid='') {
global $CFG,$DB;
//make sure all $tii values are clean.
foreach($tii as $key => $value) {
if (!empty($value) AND $key <> 'tem' AND $key <> 'uem' AND $key <> 'dtstart' AND $key <> 'dtdue' AND $key <> 'submit_date') {
$value = rawurldecode($value); //decode url first. (in case has already be encoded - don't want to end up with double % replacements)
$value = rawurlencode($value);
$value = str_replace('%20', '_', $value);
$tii[$key] = $value;
}
}
//TODO need to check lengths of certain vars. - some cannot be under 5 or over 50.
if (isset($plagiarismsettings['turnitin_senduseremail']) && $plagiarismsettings['turnitin_senduseremail']) {
$tii['dis'] ='0'; //sets e-mail notification for users in tii system to enabled.
} else {
$tii['dis'] ='1'; //sets e-mail notification for users in tii system to disabled.
}
/* //munge e-mails if prefix is set.
if (!empty($plagiarismsettings['turnitin_emailprefix'])) { //if email prefix is set
if ($tii['uem'] <> $plagiarismsettings['turnitin_email']) { //if email is not the global teacher.
$tii['uem'] = $plagiarismsettings['turnitin_emailprefix'] . $tii['uem']; //munge e-mail to prevent user access.
}
}*/
//set vars if not set.
if (!isset($tii['encrypt'])) {
$tii['encrypt'] = '0';
}
if (!isset($tii['diagnostic'])) {
$tii['diagnostic'] = '0';
}
if (!isset($tii['tem'])) {
$tii['tem'] = ''; //$plagiarismsettings['turnitin_email'];
}
if (!isset($tii['upw'])) {
$tii['upw'] = '';
}
if (!isset($tii['cpw'])) {
$tii['cpw'] = '';
}
if (!isset($tii['ced'])) {
$tii['ced'] = '';
}
if (!isset($tii['dtdue'])) {
$tii['dtdue'] = '';
}
if (!isset($tii['dtstart'])) {
$tii['dtstart'] = '';
}
if (!isset($tii['newassign'])) {
$tii['newassign'] = '';
}
if (!isset($tii['newupw'])) {
$tii['newupw'] = '';
}
if (!isset($tii['oid'])) {
$tii['oid'] = '';
}
if (!isset($tii['pfn'])) {
$tii['pfn'] = '';
}
if (!isset($tii['pln'])) {
$tii['pln'] = '';
}
if (!isset($tii['ptl'])) {
$tii['ptl'] = '';
}
if (!isset($tii['ptype'])) {
$tii['ptype'] = '';
}
if (!isset($tii['said'])) {
$tii['said'] = '';
}
if (!isset($tii['assignid'])) {
$tii['assignid'] = '';
}
if (!isset($tii['assign'])) {
$tii['assign'] = '';
}
if (!isset($tii['cid'])) {
$tii['cid'] = '';
}
if (!isset($tii['ctl'])) {
$tii['ctl'] = '';
}
$tii['gmtime'] = turnitin_get_gmtime();
$tii['aid'] = $plagiarismsettings['turnitin_accountid'];
$tii['version'] = rawurlencode($CFG->release); //only used internally by TII.
$tii['src'] = '14'; //Magic number that identifies this Integration to Turnitin
//prepare $tii for md5string - need to urldecode before generating the md5.
$tiimd5 = array();
foreach($tii as $key => $value) {
if (!empty($value) AND $key <> 'tem' AND $key <> 'uem') {
$value = rawurldecode($value); //decode url for calculating MD5
$tiimd5[$key] = $value;
} else {
$tiimd5[$key] = $value;
}
}
$tii['md5'] = turnitin_get_md5string($tiimd5, $plagiarismsettings);
if (!empty($pid) &&!empty($tii['md5'])) {
//save this md5 into the record.
$tiifile = new stdClass();
$tiifile->id = $pid;
$tiifile->apimd5 = $tii['md5'];
$DB->update_record('plagiarism_turnitin_files', $tiifile);
}
if ($returnArray) {
return $tii;
} else {
$url = $plagiarismsettings['turnitin_api']."?";
foreach ($tii as $key => $value) {
$url .= $key .'='. $value. '&';
}
return $url;
}
}
/**
* internal function gets the current time formatted for use in the Turnitin Url, used by turnitin_get_url
*
* @return string - formatted for use in Turnitin API call.
*/
function turnitin_get_gmtime() {
return substr(gmdate('YmdHi'), 0, -1);
}
/**
* internal function that generates an md5 based on particular items in a $tii array - used by turnitin_get_url
*
* @param object $tii the intial $tii object
* @return string - calculated md5
*/
function turnitin_get_md5string($tii, $plagiarismsettings){
global $CFG,$DB;
$md5string = $plagiarismsettings['turnitin_accountid'].
$tii['assign'].
$tii['assignid'].
$tii['ced'].
$tii['cid'].
$tii['cpw'].
$tii['ctl'].
$tii['diagnostic'].
$tii['dis'].
$tii['dtdue'].
$tii['dtstart'].
$tii['encrypt'].
$tii['fcmd'].
$tii['fid'].
$tii['gmtime'].
$tii['newassign'].
$tii['newupw'].
$tii['oid'].
$tii['pfn'].
$tii['pln'].
$tii['ptl'].
$tii['ptype'].
$tii['said'].
$tii['tem'].
$tii['uem'].
$tii['ufn'].
$tii['uid'].
$tii['uln'].
$tii['upw'].
$tii['username'].
$tii['utp'].
$plagiarismsettings['turnitin_secretkey'];
return md5($md5string);
}
/**
* post data to TII
*
* @param object $tii - the object containing all the settings required.
* @return xml
*/
function turnitin_post_data($tii, $plagiarismsettings, $file='', $pid='') {
global $DB, $CFG;
$fields = turnitin_get_url($tii, $plagiarismsettings, 'array', $pid);
$url = get_config('plagiarism', 'turnitin_api');
$status = check_dir_exists($CFG->dataroot."/plagiarism/",true);
if ($status && !empty($file)) {
if (!empty($file->type) && $file->type == "tempturnitin") {
$fields['pdata'] = '@'.$file->filepath;
$c = new curl(array('proxy'=>true));
$xml = $c->post($url,$fields);
$status = new SimpleXMLElement($xml);
} else {
//We cannot access the file location of $file directly - we must create a temp file to point to instead
$filename = $CFG->dataroot."/plagiarism/".time().$file->get_filename(); //unique name for this file.
$fh = fopen($filename,'w');
fwrite($fh, $file->get_content());
fclose($fh);
$fields['pdata'] = '@'.$filename;
$c = new curl(array('proxy'=>true));
$status = new SimpleXMLElement($c->post($url,$fields));
unlink($filename);
}
} else {
$c = new curl(array('proxy'=>true));
$content = $c->post($url,$fields);
$status = new SimpleXMLElement($content);
}
return $status;
}
/**
* Function that starts Turnitin session - some api calls require this
*
* @param object $plagiarismsettings - from a call to plagiarism_get_settings
* @return string - Turnitin sessionid
*/
function turnitin_start_session($user, $plagiarismsettings) {
$tii = array();
//set globals.
$tii['utp'] = TURNITIN_STUDENT;
$tii = turnitin_get_tii_user($tii, $user);
$tii['fcmd'] = TURNITIN_RETURN_XML;
$tii['fid'] = TURNITIN_START_SESSION;
$content = turnitin_get_url($tii, $plagiarismsettings);
$tiixml = plagiarism_get_xml($content);
if (isset($tiixml->sessionid[0])) {
return $tiixml->sessionid[0];
} else {
return '';
}
}
/**
* Function that ends a Turnitin session
*
* @param object $plagiarismsettings - from a call to plagiarism_get_settings
* @param string - Turnitin sessionid - from a call to turnitin_start_session
*/
function turnitin_end_session($user, $plagiarismsettings, $tiisession) {
if (empty($tiisession)) {
return;
}
$tii = array();
//set globals.
$tii['utp'] = TURNITIN_STUDENT;
$tii = turnitin_get_tii_user($tii, $user);
$tii['fcmd'] = TURNITIN_RETURN_XML;
$tii['fid'] = TURNITIN_END_SESSION;
$tii['session-id'] = $tiisession;
$tiixml = plagiarism_get_xml(turnitin_get_url($tii, $plagiarismsettings));
}
/**
* used to send files to turnitin for processing
* $pid - id of this record from turnitin_files table
* $file - contains actual file object
*
*/
function turnitin_send_file($pid, $plagiarismsettings, $file) {
global $DB, $CFG;
require_once($CFG->libdir.'/filelib.php');
//get information about this file
$plagiarism_file = $DB->get_record('plagiarism_turnitin_files', array('id'=>$pid));
$invalidrecord = false;
if (!$user = $DB->get_record('user', array('id'=>$plagiarism_file->userid))) {
debugging("invalid userid! - userid:".$plagiarism_file->userid." Module:".$moduletype." Fileid:".$plagiarism_file->id);
$invalidrecord = true;
}
if (!$cm = $DB->get_record('course_modules', array('id'=>$plagiarism_file->cm))) {
debugging("invalid cmid! ".$plagiarism_file->cm." Fileid:".$plagiarism_file->id);
$invalidrecord = true;
}
if (!$course = $DB->get_record('course', array('id'=>$cm->course))) {
debugging("invalid cmid! - courseid:".$cm->course." Module:".$moduletype." Fileid:".$plagiarism_file->id);
$invalidrecord = true;
}
if (!$moduletype = $DB->get_field('modules','name', array('id'=>$cm->module))) {
debugging("invalid moduleid! - moduleid:".$cm->module." Module:".$moduletype." Fileid:".$plagiarism_file->id);
$invalidrecord = true;
}
if (!$module = $DB->get_record($moduletype, array('id'=>$cm->instance))) {
debugging("invalid instanceid! - instance:".$cm->instance." Module:".$moduletype." Fileid:".$plagiarism_file->id);
$invalidrecord = true;
}
if ($invalidrecord) {
$DB->delete_records('plagiarism_turnitin_files', array('id'=>$plagiarism_file->id));
return true;
}
$dtstart = $DB->get_record('plagiarism_turnitin_config', array('cm' => $cm->id, 'name' => 'turnitin_dtstart'));
if (!empty($dtstart) && $dtstart->value > time()) {
mtrace("Warning: $moduletype start date is too early ".date('Y-m-d H:i:s', $dtstart->value)." in course $course->shortname $moduletype $module->name will delay sending files until next cron");
return false; //TODO: check that this doesn't cause a failure in cron
}
//Start Turnitin Session
$tiisession = turnitin_start_session($user, $plagiarismsettings);
//now send the file.
$tii = array();
$tii['utp'] = TURNITIN_STUDENT;
$tii = turnitin_get_tii_user($tii, $user);
$tii['cid'] = get_config('plagiarism_turnitin_course', $course->id);
$tii['ctl'] = (strlen($course->shortname) > 45 ? substr($course->shortname, 0, 45) : $course->shortname);
$tii['ctl'] = (strlen($tii['ctl']) > 5 ? $tii['ctl'] : $tii['ctl']."_____");
$tii['fcmd'] = TURNITIN_RETURN_XML;
$tii['session-id'] = $tiisession;
//$tii2['diagnostic'] = '1';
$tii['fid'] = TURNITIN_CREATE_USER;
$tiixml = plagiarism_get_xml(turnitin_get_url($tii, $plagiarismsettings, false, $pid));
if (empty($tiixml->rcode[0]) or $tiixml->rcode[0] <> TURNITIN_RESP_USER_CREATED) { //this is the success code for uploading a file. - we need to return the oid and save it!
mtrace('could not create user/login to turnitin code:'.$tiixml->rcode[0]);
} else {
$plagiarism_file = $DB->get_record('plagiarism_turnitin_files', array('id'=>$pid)); //make sure we get latest record as it may have changed
$plagiarism_file->statuscode = (string)$tiixml->rcode[0];
if (! $DB->update_record('plagiarism_turnitin_files', $plagiarism_file)) {
debugging("Error updating turnitin_files record");
}
//now enrol user in class under the given account (fid=3)
$params = array('cm' => $cm->id, 'name' => 'turnitin_assignid');
$turnitin_assignid = $DB->get_field('plagiarism_turnitin_config', 'value', $params);
if (!empty($turnitin_assignid)) {
$tii['assignid'] = $turnitin_assignid;
}
$tii['assign'] = turnitin_get_assign_name($module->name, $cm->id); //assignment name stored in TII
$tii['fid'] = TURNITIN_JOIN_CLASS;
//$tii2['diagnostic'] = '1';
$tiixml = plagiarism_get_xml(turnitin_get_url($tii, $plagiarismsettings, false, $pid));
if (empty($tiixml->rcode[0]) or $tiixml->rcode[0] <> TURNITIN_RESP_USER_JOINED) { //this is the success code for uploading a file. - we need to return the oid and save it!
mtrace('could not enrol user in turnitin class code:'.$tiixml->rcode[0]);
} else {
$plagiarism_file = $DB->get_record('plagiarism_turnitin_files', array('id'=>$pid)); //make sure we get latest record as it may have changed
$plagiarism_file->statuscode = (string)$tiixml->rcode[0];
if (! $DB->update_record('plagiarism_turnitin_files', $plagiarism_file)) {
debugging("Error updating turnitin_files record");
}
//now submit this uploaded file to Tii! (fid=5)
$tii['fid'] = TURNITIN_SUBMIT_PAPER;
// if ($file->type == "tempturnitin") {
// $tii['ptl'] = $file->filename; //paper title
// $tii['submit_date'] = rawurlencode(gmdate('Y-m-d H:i:s', $file->timestamp));
// } else {
$tii['ptl'] = $file->get_filename(); //paper title
$tii['submit_date'] = rawurlencode(date('Y-m-d H:i:s', $file->get_timemodified()));
// }
$tii['ptype'] = '2'; //filetype
$tii['pfn'] = $tii['ufn'];
$tii['pln'] = $tii['uln'];
//$tii['diagnostic'] = '1';
$tiixml = turnitin_post_data($tii, $plagiarismsettings, $file, $pid);
if ($tiixml->rcode[0] == TURNITIN_RESP_PAPER_SENT) { //we need to return the oid and save it!
$plagiarism_file = $DB->get_record('plagiarism_turnitin_files', array('id'=>$pid)); //make sure we get latest record as it may have changed
$plagiarism_file->externalid = (string)$tiixml->objectID[0];
debugging("success uploading assignment", DEBUG_DEVELOPER);
} else {
$plagiarism_file = $DB->get_record('plagiarism_turnitin_files', array('id'=>$pid)); //make sure we get latest record as it may have changed
debugging("failed to upload assignment errorcode".$tiixml->rcode[0]);
}