-
Notifications
You must be signed in to change notification settings - Fork 33
/
PlagiarismPlugin.php
1205 lines (1030 loc) · 39.2 KB
/
PlagiarismPlugin.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
/**
* @file plugins/generic/plagiarism/PlagiarismPlugin.php
*
* Copyright (c) 2013-2024 Simon Fraser University
* Copyright (c) 2013-2024 John Willinsky
* Distributed under the GNU GPL v3. For full terms see the file docs/COPYING.
*
* @class PlagiarismPlugin
*
* @brief Coar plugin class of plagiarism plugin
*/
namespace APP\plugins\generic\plagiarism;
use APP\core\Request;
use PKP\notification\Notification;
use APP\facades\Repo;
use APP\template\TemplateManager;
use APP\notification\NotificationManager;
use APP\submission\Submission;
use APP\plugins\generic\plagiarism\PlagiarismSubmissionSubmitListener;
use APP\plugins\generic\plagiarism\PlagiarismSettingsForm;
use APP\plugins\generic\plagiarism\IThenticate;
use APP\plugins\generic\plagiarism\classes\form\component\ConfirmSubmission;
use APP\plugins\generic\plagiarism\controllers\PlagiarismArticleGalleyGridHandler;
use APP\plugins\generic\plagiarism\controllers\PlagiarismIthenticateActionHandler;
use APP\plugins\generic\plagiarism\controllers\PlagiarismWebhookHandler;
use APP\plugins\generic\plagiarism\grids\SimilarityActionGridColumn;
use APP\plugins\generic\plagiarism\grids\RearrangeColumnsFeature;
use PKP\core\PKPRequest;
use PKP\components\forms\FormComponent;
use PKP\services\PKPSchemaService;
use PKP\plugins\Hook;
use PKP\core\Core;
use PKP\user\User;
use PKP\controllers\grid\files\review\EditorReviewFilesGridHandler;
use PKP\controllers\grid\files\submission\EditorSubmissionDetailsFilesGridHandler;
use PKP\submissionFile\SubmissionFile;
use PKP\context\Context;
use PKP\config\Config;
use PKP\security\Role;
use APP\core\Application;
use Illuminate\Support\Facades\Cache;
use PKP\core\JSONMessage;
use PKP\linkAction\LinkAction;
use PKP\plugins\GenericPlugin;
use PKP\linkAction\request\AjaxModal;
use PKP\pages\submission\PKPSubmissionHandler;
use Illuminate\Support\Facades\Event;
use Throwable;
class PlagiarismPlugin extends GenericPlugin
{
/**
* Specify a default integration name for iThenticate service
*/
public const PLUGIN_INTEGRATION_NAME = 'Plagiarism plugin for OJS/OMP/OPS';
/**
* The default permission of submission primary author's to pass to the iThenticate service
*/
public const SUBMISSION_AUTOR_ITHENTICATE_DEFAULT_PERMISSION = 'USER';
/**
* Number of seconds EULA details for a context should be cached before refreshing it
*/
public const EULA_CACHE_LIFETIME = 60 * 60 * 24;
/**
* Mapping of similarity settings with value type
*/
public array $similaritySettings = [
'addToIndex' => 'bool',
'excludeQuotes' => 'bool',
'excludeBibliography' => 'bool',
'excludeCitations' => 'bool',
'excludeAbstract' => 'bool',
'excludeMethods' => 'bool',
'excludeSmallMatches' => 'int',
'allowViewerUpdate' => 'bool',
];
/**
* List of archive mime type that will not be uploaded to iThenticate service
*/
public array $uploadRestrictedArchiveMimeTypes = [
'application/gzip',
'application/zip',
'application/x-tar',
];
/**
* List of valid url components
*/
protected array $validRouteComponentHandlers = [
'plugins.generic.plagiarism.controllers.PlagiarismWebhookHandler',
'plugins.generic.plagiarism.controllers.PlagiarismIthenticateActionHandler',
];
/**
* Determine if running application is OPS or not
*/
public static function isOPS(): bool
{
return strtolower(Application::get()->getName()) === 'ops';
}
/**
* @copydoc Plugin::register()
*/
public function register($category, $path, $mainContextId = null)
{
$success = parent::register($category, $path, $mainContextId);
$this->addLocaleData();
// if plugin hasn't registered, not allow loading plugin
if (!$success) {
return false;
}
// Plugin has been registered but not enabled
// will allow to load plugin but no plugin feature will be executed
if (!$this->getEnabled($mainContextId)) {
return $success;
}
Hook::add('Schema::get::' . PKPSchemaService::SCHEMA_SUBMISSION, [$this, 'addPlagiarismCheckDataToSubmissionSchema']);
Hook::add('Schema::get::' . PKPSchemaService::SCHEMA_SUBMISSION_FILE, [$this, 'addPlagiarismCheckDataToSubmissionFileSchema']);
Hook::add('Schema::get::' . PKPSchemaService::SCHEMA_CONTEXT, [$this, 'addIthenticateConfigSettingsToContextSchema']);
Hook::add('SubmissionFile::edit', [$this, 'updateIthenticateRevisionHistory']);
Hook::add('Schema::get::' . PKPSchemaService::SCHEMA_USER, [$this, 'stampPlagiarismDataToUserSchema']);
app()->get('schema')->get(PKPSchemaService::SCHEMA_USER, true);
Hook::add('LoadComponentHandler', [$this, 'handleRouteComponent']);
Hook::add('editorsubmissiondetailsfilesgridhandler::initfeatures', [$this, 'addActionsToSubmissionFileGrid']);
Hook::add('editorreviewfilesgridhandler::initfeatures', [$this, 'addActionsToSubmissionFileGrid']);
Event::subscribe(new PlagiarismSubmissionSubmitListener($this));
Hook::add('TemplateManager::display', [$this, 'addEulaAcceptanceConfirmation']);
return $success;
}
/**
* Running in test mode
*/
public static function isRunningInTestMode(): bool
{
return Config::getVar('ithenticate', 'test_mode', false);
}
/**
* @copydoc Plugin::getDisplayName()
*/
public function getDisplayName()
{
return __('plugins.generic.plagiarism.displayName');
}
/**
* @copydoc Plugin::getDescription()
*/
public function getDescription()
{
return __('plugins.generic.plagiarism.description');
}
/**
* @copydoc LazyLoadPlugin::getCanEnable()
*/
public function getCanEnable($contextId = null)
{
return !Config::getVar('ithenticate', 'ithenticate');
}
/**
* @copydoc LazyLoadPlugin::getCanDisable()
*/
public function getCanDisable($contextId = null)
{
return !Config::getVar('ithenticate', 'ithenticate');
}
/**
* @copydoc LazyLoadPlugin::getEnabled()
*/
public function getEnabled($contextId = null)
{
// This check is required as plugin can be forced enable by setting `ithenticate` to `On`
// in the config file which cuase the hooks to run but unavailable
// in the installation mode by setting `installed` to `Off`
if (!Config::getVar('general', 'installed')) {
return false;
}
// This allow to force enable the plugin into the system if `ithenticate` set to `On` but the plugin
// itself still disable as in `plugin_setings` table, the `enabled` value not set or set to `0`
// for more details, see https://github.com/pkp/plagiarism/issues/49
if (Config::getVar('ithenticate', 'ithenticate') && !parent::getEnabled($contextId)) {
$this->setEnabled(true);
}
return parent::getEnabled($contextId) || Config::getVar('ithenticate', 'ithenticate');
}
/**
* Add properties for this type of public identifier to the user entity's list for
* storage in the database.
*
* @param string $hookName `Schema::get::user`
*/
public function stampPlagiarismDataToUserSchema(string $hookName, array $params): bool
{
$schema =& $params[0];
$schema->properties->ithenticateEulaVersion = (object) [
'type' => 'string',
'description' => 'The iThenticate EULA version which has been agreed at submission file uploading to iThenticate',
'writeOnly' => true,
'validation' => ['nullable'],
];
$schema->properties->ithenticateEulaConfirmedAt = (object) [
'type' => 'string',
'description' => 'The timestamp at which this submission successfully completed uploading all files at iThenticate service end',
'writeOnly' => true,
'validation' => [
'date:Y-m-d H:i:s',
'nullable',
],
];
return Hook::CONTINUE;
}
/**
* Add properties for this type of public identifier to the submission entity's list for
* storage in the database.
*
* @param string $hookName `Schema::get::submission`
*/
public function addPlagiarismCheckDataToSubmissionSchema(string $hookName, array $params): bool
{
$schema =& $params[0];
$schema->properties->ithenticateEulaVersion = (object) [
'type' => 'string',
'description' => 'The iThenticate EULA version which has been agreed at submission checklist',
'writeOnly' => true,
'validation' => ['nullable'],
];
$schema->properties->ithenticateEulaUrl = (object) [
'type' => 'string',
'description' => 'The iThenticate EULA url which has been agreen at submission checklist',
'writeOnly' => true,
'validation' => ['nullable'],
];
$schema->properties->ithenticateSubmissionCompletedAt = (object) [
'type' => 'string',
'description' => 'The timestamp at which this submission successfully completed uploading all files at iThenticate service end',
'writeOnly' => true,
'validation' => [
'date:Y-m-d H:i:s',
'nullable',
],
];
return Hook::CONTINUE;
}
/**
* Add properties for this type of public identifier to the submission file entity's list for
* storage in the database.
*
* @param string $hookName `Schema::get::submissionFile`
*/
public function addPlagiarismCheckDataToSubmissionFileSchema(string $hookName, array $params): bool
{
$schema =& $params[0];
$schema->properties->ithenticateFileId = (object) [
'type' => 'integer',
'description' => 'The file id from the files table',
'writeOnly' => true,
'validation' => ['nullable'],
];
$schema->properties->ithenticateId = (object) [
'type' => 'string',
'description' => 'The iThenticate submission id for submission file',
'writeOnly' => true,
'validation' => ['nullable'],
];
$schema->properties->ithenticateSimilarityScheduled = (object) [
'type' => 'boolean',
'description' => 'The status which identify if the iThenticate similarity process has been scheduled for this submission file',
'writeOnly' => true,
'validation' => ['nullable'],
];
$schema->properties->ithenticateSimilarityResult = (object) [
'type' => 'string',
'description' => 'The similarity check result for this submission file in json format',
'writeOnly' => true,
'validation' => ['nullable'],
];
$schema->properties->ithenticateSubmissionAcceptedAt = (object) [
'type' => 'string',
'description' => 'The timestamp at which this submission file successfully accepted at iThenticate service end',
'writeOnly' => true,
'validation' => [
'date:Y-m-d H:i:s',
'nullable',
],
];
$schema->properties->ithenticateRevisionHistory = (object) [
'type' => 'string',
'description' => 'The similarity check action history on the previous revisions of this submission file',
'writeOnly' => true,
'validation' => ['nullable'],
];
return Hook::CONTINUE;
}
/**
* Add properties for this type of public identifier to the context entity's list for
* storage in the database.
*
* @param string $hookName `Schema::get::context`
*/
public function addIthenticateConfigSettingsToContextSchema(string $hookName, array $params): bool
{
$schema =& $params[0];
$schema->properties->ithenticateWebhookSigningSecret = (object) [
'type' => 'string',
'description' => 'The iThenticate service webook registration signing secret',
'writeOnly' => true,
'validation' => ['nullable'],
];
$schema->properties->ithenticateWebhookId = (object) [
'type' => 'string',
'description' => 'The iThenticate service webook id that return back after successful webhook registration',
'writeOnly' => true,
'validation' => ['nullable'],
];
return Hook::CONTINUE;
}
/**
* Attach the EULA confirmation if require at the final stage of submission
*
* @param string $hookName `TemplateManager::display`
*/
public function addEulaAcceptanceConfirmation(string $hookName, array $params): bool
{
$templateManager =& $params[0]; /** @var TemplateManager $templateManager */
$templatePath = $params[1]; /** @var string $templatePath */
if ($templateManager->getTemplateVars('requestedPage') !== 'submission' || $templatePath !== 'submission/wizard.tpl') {
return Hook::CONTINUE;
}
$request = Application::get()->getRequest();
$context = $request->getContext();
// plugin can not function if the iThenticate service access not available at global/context level
if (!$this->isServiceAccessAvailable($context)) {
error_log("ithenticate service access not set for context id : " . ($context ? $context->getId() : 'undefined'));
return Hook::CONTINUE;
}
// if the auto upload to ithenticate disable
// not going to do the EULA confirmation at submission time
if ($this->hasAutoSubmissionDisabled()) {
return Hook::CONTINUE;
}
// EULA confirmation is not required, so no need for the checking of EULA acceptance
if ($this->getContextEulaDetails($context, 'require_eula') == false) {
return Hook::CONTINUE;
}
$submission = $templateManager->getTemplateVars('submission'); /** @var Submission $submission */
$user = Repo::user()->get($request->getUser()->getId());
// If submission has EULA stamped and user has EULA stamped and both are same version
// so there is no need to confirm EULA again
if ($submission->getData('ithenticateEulaVersion') &&
$submission->getData('ithenticateEulaVersion') == $user->getData('ithenticateEulaVersion')) {
return Hook::CONTINUE;
}
$eulaVersionDetails = $this->getContextEulaDetails($context, [
$submission->getData('locale'),
$context->getPrimaryLocale(),
$request->getSite()->getPrimaryLocale(),
IThenticate::DEFAULT_EULA_LANGUAGE
]);
$steps = $templateManager->getState('steps'); /** @var array $steps */
$reviewStep = collect($steps)->filter(fn ($step) => $step['id'] === 'review');
$reviewStepIndex = $reviewStep->keys()->first();
$reviewStepSections = collect($reviewStep->first())->get('sections');
$reviewStepSectionConfirm = collect($reviewStepSections)
->filter(fn ($section) => $section['id'] === ConfirmSubmission::FORM_CONFIRM_SUBMISSION);
// The confirm submission form may not pushed to `steps state of Template` if no
// copyright defined but we still need it to confrim the EULA as final confirmation process
if ($reviewStepSectionConfirm->count() <= 0) {
$confirmForm = new ConfirmSubmission(
FormComponent::ACTION_EMIT,
$context,
[
'localizedEulaUrl' => $eulaVersionDetails['url'],
]
);
$reviewStepSections[] = [
'id' => $confirmForm->id,
'name' => __('author.submit.confirmation'),
'type' => PKPSubmissionHandler::SECTION_TYPE_CONFIRM,
'description' => '<p>' . __('submission.wizard.confirm') . '</p>',
'form' => $confirmForm->getConfig(),
];
} else {
$reviewStepSectionConfirmIndex = array_key_first($reviewStepSectionConfirm->toArray());
$reviewStepSectionConfirm = $reviewStepSectionConfirm->first();
$reviewStepSectionConfirm['form'] = (new ConfirmSubmission(
$reviewStepSectionConfirm['form']['action'],
Application::get()->getRequest()->getContext(),
[
'localizedEulaUrl' => $eulaVersionDetails['url'],
]
))->getConfig();
$reviewStepSections[$reviewStepSectionConfirmIndex] = $reviewStepSectionConfirm;
}
$steps[$reviewStepIndex]['sections'] = $reviewStepSections;
$templateManager->setState(['steps' => $steps]);
return Hook::CONTINUE;
}
/**
* Add plagiarism action history for revision files.
* Only contains action history for files that has been sent for plagiarism check.
*
* @param string $hookName `SubmissionFile::edit`
*/
public function updateIthenticateRevisionHistory(string $hookName, array $params): bool
{
$submissionFile =& $params[0]; /** @var SubmissionFile $submissionFile */
$currentSubmissionFile = $params[1]; /** @var SubmissionFile $currentSubmissionFile */
// Do not track for plagiarism revision history until marked for tracking
if (is_null($currentSubmissionFile->getData('ithenticateFileId'))) {
return Hook::CONTINUE;
}
// If file has not changed, no change in plagiarism revision history
if ($currentSubmissionFile->getData('fileId') === $submissionFile->getData('fileId')) {
return Hook::CONTINUE;
}
// new file revision added, so add/update itnenticate revision hisotry
$revisionHistory = json_decode($currentSubmissionFile->getData('ithenticateRevisionHistory') ?? '{}', true);
$submissionFile->setData('ithenticateFileId', $submissionFile->getData('fileId'));
// If the previous file not sent schedule for plagiarism check
// no need to store it's plagiarism revision history
if (is_null($currentSubmissionFile->getData('ithenticateId'))) {
return Hook::CONTINUE;
}
array_push($revisionHistory, [
'ithenticateFileId' => $currentSubmissionFile->getData('ithenticateFileId'),
'ithenticateId' => $currentSubmissionFile->getData('ithenticateId'),
'ithenticateSimilarityResult' => $currentSubmissionFile->getData('ithenticateSimilarityResult'),
'ithenticateSimilarityScheduled' => $currentSubmissionFile->getData('ithenticateSimilarityScheduled'),
'ithenticateSubmissionAcceptedAt' => $currentSubmissionFile->getData('ithenticateSubmissionAcceptedAt'),
]);
$submissionFile->setData('ithenticateRevisionHistory', json_encode($revisionHistory));
$submissionFile->setData('ithenticateId', null);
$submissionFile->setData('ithenticateSimilarityResult', null);
$submissionFile->setData('ithenticateSimilarityScheduled', 0);
$submissionFile->setData('ithenticateSubmissionAcceptedAt', null);
return Hook::CONTINUE;
}
/**
* Handle the plugin specific route component requests
*
* @param string $hookName `LoadComponentHandler`
*/
public function handleRouteComponent(string $hookName, array $params): bool
{
$component =& $params[0]; /** @var string $component */
$componentInstance =& $params[2]; /** @var mixed $componentInstance */
if (static::isOPS() && $component === 'grid.preprintGalleys.PreprintGalleyGridHandler') {
$componentInstance = new PlagiarismArticleGalleyGridHandler($this);
$component = "plugins.generic.plagiarism.controllers.PlagiarismArticleGalleyGridHandler";
return Hook::ABORT;
}
if (!in_array($component, $this->validRouteComponentHandlers)) {
return Hook::CONTINUE;
}
$componentName = last(explode('.', $component));
$componentInstance = match($componentName) {
'PlagiarismWebhookHandler' => new PlagiarismWebhookHandler($this),
'PlagiarismIthenticateActionHandler' => new PlagiarismIthenticateActionHandler($this),
};
return Hook::ABORT;
}
/**
* Complete the submission process at iThenticate service's end
* The steps follows as:
* - Check if proper service credentials(API Url and Key) are available
* - Register webhook for context if not already registered
* - Check for EULA confirmation requirement
* - Check if EULA is stamped to submission
* - if not stamped, not allowed to submit at iThenticate
* - Check if EULA is stamped to submitting user
* - if not stamped, not allowed to submit at iThenticate
* - Traversing the submission files
* - Create new submission at ithenticate's end for each submission file
* - Upload the file for newly created submission uuid return back from ithenticate
* - Stamp the retuning iThenticate submission id with submission file
* - Return bool to indicate the status of process completion
*/
public function submitForPlagiarismCheck(Context $context, Submission $submission): bool
{
$request = Application::get()->getRequest();
// plugin can not function if the iThenticate service access not available at global/context level
if (!$this->isServiceAccessAvailable($context)) {
error_log("ithenticate service access not set for context id : " . ($context ? $context->getId() : 'undefined'));
return false;
}
// if the auto upload to ithenticate disable
// not going to upload files to iThenticate at submission time
if ($this->hasAutoSubmissionDisabled()) {
return false;
}
$user = $request->getUser();
$ithenticate = $this->initIthenticate(...$this->getServiceAccess($context)); /** @var IThenticate $ithenticate */
// If no webhook previously registered for this Context, register it
if (!$context->getData('ithenticateWebhookId')) {
$this->registerIthenticateWebhook($ithenticate, $context);
}
// Only set applicable EULA if EULA required
if ($this->getContextEulaDetails($context, 'require_eula') == true) {
$ithenticate->setApplicableEulaVersion($submission->getData('ithenticateEulaVersion'));
}
// Check EULA stamped to submission or submitter only if it is required
if ($this->getContextEulaDetails($context, 'require_eula') != false) {
// not going to sent it for plagiarism check if EULA not stamped to submission or submitter
if (!$submission->getData('ithenticateEulaVersion') || !$user->getData('ithenticateEulaVersion')) {
$this->sendErrorMessage(__('plugins.generic.plagiarism.stamped.eula.missing'), $submission->getId());
return false;
}
}
$submissionFiles = Repo::submissionFile()
->getCollector()
->filterBySubmissionIds([$submission->getId()])
->getMany();
try {
foreach($submissionFiles as $submissionFile) { /** @var SubmissionFile $submissionFile */
if (!$this->createNewSubmission($request, $user, $submission, $submissionFile, $ithenticate)) {
return false;
}
}
$submission->setData('ithenticateSubmissionCompletedAt', Core::getCurrentDate());
} catch (Throwable $exception) {
error_log('submit for plagiarism check failed with excaption ' . $exception->__toString());
$this->sendErrorMessage(__('plugins.generic.plagiarism.ithenticate.upload.complete.failed'), $submission->getId());
return false;
}
Repo::submission()->edit($submission, []);
return true;
}
/**
* Add ithenticate related data and actions to submission file grid view
*
* @param string $hookName `editorsubmissiondetailsfilesgridhandler::initfeatures` or `editorreviewfilesgridhandler::initfeatures`
*/
public function addActionsToSubmissionFileGrid(string $hookName, array $params): bool
{
$request = Application::get()->getRequest();
$context = $request->getContext();
// plugin can not function if the iThenticate service access not available at global/context level
if (!$this->isServiceAccessAvailable($context)) {
error_log("ithenticate service access not set for context id : " . ($context ? $context->getId() : 'undefined'));
return Hook::CONTINUE;
}
$user = $request->getUser();
if (!$user->hasRole([Role::ROLE_ID_MANAGER, Role::ROLE_ID_SUB_EDITOR, Role::ROLE_ID_REVIEWER], $context->getId())) {
return Hook::CONTINUE;
}
/** @var EditorSubmissionDetailsFilesGridHandler|EditorReviewFilesGridHandler $submissionDetailsFilesGridHandler */
$submissionDetailsFilesGridHandler = & $params[0];
$submissionDetailsFilesGridHandler->addColumn(new SimilarityActionGridColumn($this));
$features =& $params[3]; /** @var array $features */
$features[] = new RearrangeColumnsFeature($submissionDetailsFilesGridHandler);
return Hook::CONTINUE;
}
/**
* Stamp the iThenticate EULA with the submission
*/
public function stampEulaToSubmission(Context $context, Submission $submission): bool
{
$request = Application::get()->getRequest();
$eulaDetails = $this->getContextEulaDetails($context, [
$submission->getData('locale'),
$context->getPrimaryLocale(),
$request->getSite()->getPrimaryLocale(),
IThenticate::DEFAULT_EULA_LANGUAGE
]);
Repo::submission()->edit($submission, [
'ithenticateEulaVersion' => $eulaDetails['version'],
'ithenticateEulaUrl' => $eulaDetails['url'],
]);
return true;
}
/**
* Stamp the iThenticate EULA to the submitting user
*/
public function stampEulaToSubmittingUser(Context $context, Submission $submission, ?User $user = null): bool
{
$request = Application::get()->getRequest();
$user ??= $request->getUser();
$submissionEulaVersion = $submission->getData('ithenticateEulaVersion');
if (is_null($submissionEulaVersion)) {
$eulaDetails = $this->getContextEulaDetails($context, [
$submission->getData('locale'),
$context->getPrimaryLocale(),
$request->getSite()->getPrimaryLocale(),
IThenticate::DEFAULT_EULA_LANGUAGE
]);
$submissionEulaVersion = $eulaDetails['version'];
}
// If submission EULA version has already been stamped to user
// no need to do the confirmation and stamping again
if ($user->getData('ithenticateEulaVersion') === $submissionEulaVersion) {
return true;
}
$ithenticate = $this->initIthenticate(...$this->getServiceAccess($context)); /** @var IThenticate $ithenticate */
$ithenticate->setApplicableEulaVersion($submissionEulaVersion);
// Check if user has ever already accepted this EULA version and if so, stamp it to user
// Or, try to confirm the EULA for user and upon succeeding, stamp it to user
if ($ithenticate->verifyUserEulaAcceptance($user, $submissionEulaVersion) ||
$ithenticate->confirmEula($user, $context)) {
$this->stampEulaVersionToUser($user, $submissionEulaVersion);
return true;
}
return false;
}
/**
* Create a new submission at iThenticate service's end
*/
public function createNewSubmission(
PKPRequest $request,
User $user,
Submission $submission,
SubmissionFile $submissionFile,
IThenticate|TestIThenticate $ithenticate
): bool
{
$context = $request->getContext();
$publication = $submission->getCurrentPublication();
$author = $publication->getPrimaryAuthor();
$submissionUuid = $ithenticate->createSubmission(
$request->getSite(),
$submission,
$user,
$author,
static::SUBMISSION_AUTOR_ITHENTICATE_DEFAULT_PERMISSION,
$this->getSubmitterPermission($context, $user)
);
if (!$submissionUuid) {
$this->sendErrorMessage(
__('plugins.generic.plagiarism.ithenticate.submission.create.failed', [
'submissionFileId' => $submissionFile->getId(),
]),
$submission->getId()
);
return false;
}
$pkpFileService = app()->get('file'); /** @var \PKP\Services\PKPFileService $pkpFileService */
$file = $pkpFileService->get($submissionFile->getData('fileId'));
if (in_array($file->mimetype, $this->uploadRestrictedArchiveMimeTypes)) {
return true;
}
$submissionFileName = $submissionFile->getData("name", $publication->getData("locale"))
?? collect([$context->getPrimaryLocale()])
->merge($context->getData("supportedSubmissionLocales") ?? [])
->merge([$request->getSite()->getPrimaryLocale()])
->unique()
->map(fn(string $locale): ?string => $submissionFile->getData("name", $locale))
->filter()
->first();
$uploadStatus = $ithenticate->uploadFile(
$submissionUuid,
$submissionFileName,
$pkpFileService->fs->read($file->path),
);
// Upload submission files for successfully created submission at iThenticate's end
if (!$uploadStatus) {
$this->sendErrorMessage(
__('plugins.generic.plagiarism.ithenticate.file.upload.failed', [
'submissionFileId' => $submissionFile->getId(),
]),
$submission->getId()
);
return false;
}
$submissionFile->setData('ithenticateId', $submissionUuid);
$submissionFile->setData('ithenticateFileId', $submissionFile->getData('fileId'));
$submissionFile->setData('ithenticateSimilarityScheduled', 0);
Repo::submissionFile()->edit($submissionFile, []);
return true;
}
/**
* Register the webhook for this context
*/
public function registerIthenticateWebhook(IThenticate|TestIThenticate $ithenticate, ?Context $context = null): bool
{
$request = Application::get()->getRequest();
$context ??= $request->getContext();
$signingSecret = \Illuminate\Support\Str::random(12);
$webhookUrl = Application::get()->getDispatcher()->url(
$request,
Application::ROUTE_COMPONENT,
$context->getData('urlPath'),
'plugins.generic.plagiarism.controllers.PlagiarismWebhookHandler',
'handle'
);
if ($webhookId = $ithenticate->registerWebhook($signingSecret, $webhookUrl)) {
$contextService = app()->get('context'); /** @var \PKP\Services\PKPContextService $contextService */
$context = $contextService->edit($context, [
'ithenticateWebhookSigningSecret' => $signingSecret,
'ithenticateWebhookId' => $webhookId
], $request);
return true;
}
error_log("unable to complete the iThenticate webhook registration for context id {$context->getId()}");
return false;
}
/**
* Get the cached EULA details form Context
* The eula details structure is in the following format
* [
* 'require_eula' => null/true/false, // null => not possible to retrived,
* // true => EULA confirmation required,
* // false => EULA confirmation not required
* 'en_US' => [
* 'version' => '',
* 'url' => '',
* ],
* ...
* ]
*
* Based on the `key` param defined, it will return in following format
* - if null, will return the whole details in above structure
* - if array, will try to find the first matching `key` index value and return that
* - if array and not found any match or if string, will return value based on last
* array index or string value and considering the default value along with it
*
*/
public function getContextEulaDetails(
Context $context,
string|array|null $keys = null,
mixed $default = null
): mixed
{
$eulaDetails = Cache::remember(
"ithenticate_eula_{$context->getId()}",
// if running on ithenticate test mode, set the cache life time to 60 seconds
static::isRunningInTestMode() ? 60 : static::EULA_CACHE_LIFETIME,
fn () => $this->retrieveEulaDetails()
);
if (!$keys) {
return $eulaDetails;
}
if (is_array($keys)) {
foreach ($keys as $key) {
$value = data_get($eulaDetails, $key);
if ($value) {
return $value;
}
}
}
return data_get(
$eulaDetails,
last(\Illuminate\Support\Arr::wrap($keys)),
$default
);
}
/**
* Retrieved and generate the localized EULA details and EULA confirmation requirement
* for given context and cache it in following format
* [
* 'require_eula' => null/true/false, // null => not possible to retrived,
* // true => EULA confirmation required,
* // false => EULA confirmation not required
* 'en_US' => [
* 'version' => '',
* 'url' => '',
* ],
* ...
* ]
*
*/
public function retrieveEulaDetails(): array
{
$context = Application::get()->getRequest()->getContext();
$ithenticate = $this->initIthenticate(...$this->getServiceAccess($context)); /** @var IThenticate $ithenticate */
$eulaDetails = [];
$eulaDetails['require_eula'] = $ithenticate->getEnabledFeature('tenant.require_eula');
// If `require_eula` is set to `true` that is EULA confirmation is required
// and default EULA version is verified
// we will map and store locale key to eula details (version and url) in following structure
// 'en_US' => [
// 'version' => '',
// 'url' => '',
// ],
// ...
if ($eulaDetails['require_eula'] == true &&
$ithenticate->validateEulaVersion($ithenticate::DEFAULT_EULA_VERSION)) {
foreach($context->getSupportedSubmissionLocaleNames() as $localeKey => $localeName) {
$eulaDetails[$localeKey] = [
'version' => $ithenticate->getApplicableEulaVersion(),
'url' => $ithenticate->getApplicableEulaUrl($localeKey),
];
}
// Also store the default iThenticate language version details
if (!isset($eulaDetails[$ithenticate::DEFAULT_EULA_LANGUAGE])) {
$eulaDetails[$ithenticate::DEFAULT_EULA_LANGUAGE] = [
'version' => $ithenticate->getApplicableEulaVersion(),
'url' => $ithenticate->getApplicableEulaUrl($ithenticate::DEFAULT_EULA_LANGUAGE),
];
}
}
return $eulaDetails;
}
/**
* Create and return an instance of service class responsible to handle the
* communication with iThenticate service.
*
* If the test mode is enable, it will return an instance of mock class
* `TestIThenticate` instead of actual commucation responsible class.
*/
public function initIthenticate(string $apiUrl, string $apiKey): IThenticate|TestIThenticate
{
if (static::isRunningInTestMode()) {
return new TestIThenticate(
$apiUrl,
$apiKey,
static::PLUGIN_INTEGRATION_NAME,
$this->getCurrentVersion()->getData('current')
);
}
return new IThenticate(
$apiUrl,
$apiKey,
static::PLUGIN_INTEGRATION_NAME,
$this->getCurrentVersion()->getData('current')
);
}
/**
* Stamp the EULA version and confirmation datetime for submitting user
*/
public function stampEulaVersionToUser(User $user, string $version): void
{
$user->setData('ithenticateEulaVersion', $version);
$user->setData('ithenticateEulaConfirmedAt', Core::getCurrentDate());
Repo::user()->edit($user);
}
/**
* @copydoc Plugin::getActions()
*/
function getActions($request, $verb)
{
$router = $request->getRouter();
return array_merge(
$this->getEnabled()
? [
new LinkAction(
'settings',
new AjaxModal(
$router->url(
$request,
null,
null,
'manage',
null,
[
'verb' => 'settings',
'plugin' => $this->getName(),
'category' => 'generic'
]
),
$this->getDisplayName()
),
__('manager.plugins.settings'),
null
),
] : [],
parent::getActions($request, $verb)
);
}