Repository navigation
Expand file tree
/
Copy pathInspecExportPlugin.php
More file actions
867 lines (783 loc) · 31.6 KB
/
Copy pathInspecExportPlugin.php
File metadata and controls
867 lines (783 loc) · 31.6 KB
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
<?php
/**
* @file InspecExportPlugin.php
*
* Copyright (c) 2026 Simon Fraser University
* Copyright (c) 2026 John Willinsky
* Distributed under the GNU GPL v3. For full terms see the file LICENSE.
*
* @class InspecExportPlugin
*
* @brief Inspec export plugin
*/
namespace APP\plugins\generic\inspec;
use APP\facades\Repo;
use APP\notification\NotificationManager;
use APP\plugins\generic\inspec\classes\form\InspecSettingsForm;
use APP\plugins\generic\inspec\jobs\InspecDeliver;
use APP\plugins\PubObjectsExportPlugin;
use APP\publication\Publication;
use APP\submission\Submission;
use APP\template\TemplateManager;
use DOMDocument;
use DOMXPath;
use Exception;
use League\Flysystem\Filesystem;
use League\Flysystem\PhpseclibV3\SftpAdapter;
use League\Flysystem\PhpseclibV3\SftpConnectionProvider;
use PKP\context\Context;
use PKP\core\Core;
use PKP\core\JSONMessage;
use PKP\db\DAORegistry;
use PKP\file\FileManager;
use PKP\galley\Galley;
use PKP\notification\Notification;
use PKP\plugins\interfaces\HasTaskScheduler;
use PKP\scheduledTask\PKPScheduler;
use PKP\submission\Genre;
use PKP\submission\GenreDAO;
use ZipArchive;
class InspecExportPlugin extends PubObjectsExportPlugin implements HasTaskScheduler
{
/**
* The JATS 1.2 Journal Publishing DTD bundled with the application, and the
* identifiers a document uses to name it.
*/
protected const JATS_12_PUBLIC_ID = '-//NLM//DTD JATS (Z39.96) Journal Publishing DTD v1.2 20190208//EN';
protected const JATS_12_SYSTEM_ID = 'http://jats.nlm.nih.gov/publishing/1.2/JATS-journalpublishing1.dtd';
protected const JATS_12_DTD_PATH = '/dtd/jats/1.2/JATS-journalpublishing1.dtd';
/**
* @copydoc ImportExportPlugin::display()
*/
public function display($args, $request): void
{
parent::display($args, $request);
$templateManager = TemplateManager::getManager();
$templateManager->assign([
'sftpLibraryMissing' => !class_exists('\League\Flysystem\PhpseclibV3\SftpAdapter'),
]);
switch (array_shift($args)) {
case 'index':
case '':
$templateMgr = TemplateManager::getManager($request);
$templateMgr->display($this->getTemplateResource('index.tpl'));
break;
}
}
/**
* Resolve the publication to deposit, which is the submission's current one.
*
* Inspec only indexes the first published version of an article, and a submission
* is deposited once and never re-deposited, so in practice this is the version
* that was current when the article first became depositable. Depositing the
* current publication rather than the earliest one keeps the metadata we package
* the same metadata the article displays, so an editor fixing a reported problem
* knows which version to edit.
*/
protected function depositPublication(Submission|Publication $object): ?Publication
{
return $object instanceof Publication ? $object : $object->getCurrentPublication();
}
/**
* Create a filename for files created in the plugin, removing any invalid characters:
* journalAbbreviation_submissionId_versionStageVersionMajor(_timestamp), e.g. ORE_7449_VoR1
*
* @param bool $ts Whether to include a timestamp in the filename.
* @param string|null $fileExtension The optional file extension to include in the filename.
*/
protected function buildFileName(
string $journalAbbreviation,
Context $context,
Submission|Publication|null $object = null,
bool $ts = false,
?string $fileExtension = null
): string {
$parts = [$journalAbbreviation];
if ($object) {
$publication = $this->depositPublication($object);
$parts[] = $object instanceof Submission ? $object->getId() : $object->getData('submissionId');
$parts[] = $publication?->getData('versionStage') . $publication?->getData('versionMajor');
}
if ($ts) {
$parts[] = date('YmdHis');
}
// File names cannot contain spaces or special characters (such as ?, %, #, /, or :)
$parts = array_map(
fn ($part) => preg_replace('/[^a-zA-Z0-9]/', '', (string) $part),
$parts
);
return implode('_', array_filter($parts, fn ($part) => $part !== ''))
. ($fileExtension ? '.' . $fileExtension : '');
}
/**
* @copydoc PubObjectsExportPlugin::executeExportAction()
*
* @param null|mixed $noValidation
*
* @throws Exception
*/
public function executeExportAction(
$request,
$objects,
$filter,
$tab,
$objectsFileNamePart,
$noValidation = null,
$shouldRedirect = true
): void {
$context = $request->getContext();
// Use the same check as the parent so that the export and deposit actions are
// always handled here. The parent's equivalent branches pass an array of objects
// to exportXML(), which expects a single object.
if ($this->_checkForExportAction(PubObjectsExportPlugin::EXPORT_ACTION_DEPOSIT)) {
$resultErrors = [];
$result = $this->depositXML($objects, $context, null, $noValidation);
if (is_array($result)) {
$resultErrors[] = $result;
}
// send notifications
if (empty($resultErrors)) {
$this->_sendNotification(
$request->getUser(),
$this->getDepositSuccessNotificationMessageKey(),
Notification::NOTIFICATION_TYPE_SUCCESS
);
} else {
foreach ($resultErrors as $error) {
if (!is_array($error) || count($error) === 0) {
throw new Exception('Invalid error message');
}
$this->_sendNotification(
$request->getUser(),
$error[0],
Notification::NOTIFICATION_TYPE_ERROR,
($error[1] ?? null)
);
}
}
// Redirect back to the right tab
$request->redirect(null, null, null, ['plugin', $this->getName()], null, $tab);
} elseif ($this->_checkForExportAction(PubObjectsExportPlugin::EXPORT_ACTION_EXPORT)) {
$path = $this->createZipCollection($objects, $context, $noValidation);
if (!empty($path['error'])) {
$this->_sendNotification(
$request->getUser(),
$path['error'][0],
Notification::NOTIFICATION_TYPE_ERROR,
$path['error'][1] ?? null
);
$request->redirect(null, null, null, ['plugin', $this->getName()], null, $tab);
} else {
$journalAbbreviation = $this->journalAbbreviation($context);
$filename = $this->buildFileName($journalAbbreviation, $context, null, true, 'zip');
if (count($objects) == 1) {
$object = array_shift($objects);
$filename = $this->buildFileName($journalAbbreviation, $context, $object, true, 'zip');
}
$fileManager = new FileManager();
$fileManager->downloadByPath(
$path['path'],
'application/zip',
false,
$filename
);
$fileManager->deleteByPath($path['path']);
}
} else {
parent::executeExportAction(
$request,
$objects,
$filter,
$tab,
$objectsFileNamePart,
$noValidation,
$shouldRedirect
);
}
}
/**
* Get the XML for selected objects.
*
* @param null|mixed $noValidation
* @param null|mixed $outputErrors
* @param null|mixed $genres
*
* @return array|string array of error message, or XML document.
*/
public function exportXML(
$object,
$filter,
$context,
$noValidation = null,
&$outputErrors = null,
?string $articlePdfFilename = null,
$genres = null
): array|string {
libxml_use_internal_errors(true);
$publication = $this->depositPublication($object);
if (!$publication) {
return ['plugins.importexport.inspec.export.failure.noPublication'];
}
$submissionId = $object instanceof Publication ? $object->getData('submissionId') : $object->getId();
if ($genres == null) {
$genreDao = DAORegistry::getDAO('GenreDAO'); /** @var GenreDAO $genreDao */
$genres = $genreDao->getEnabledByContextId($context->getId());
}
$document = Repo::jats()
->getJatsFile($publication->getId(), $submissionId, $genres->toArray());
// Only uploaded JATS is exported for now: generated JATS has no usable body or media.
if (
!$document ||
!$document->jatsContent ||
$document->isDefaultContent ||
$document->loadingContentError
) {
return ['plugins.importexport.inspec.export.failure.jatsFileNotFound'];
}
$xml = $document->jatsContent;
// Building the document leaves its own parse errors behind: the JATS Template
// plugin recovers from malformed author markup itself, and a document that could
// not be loaded at all is reported above. Cleared so that the DTD validation
// reports only what it found.
libxml_clear_errors();
$returnXml = $this->addPdfSelfUri($xml, $articlePdfFilename);
if (is_array($returnXml)) {
return $returnXml;
}
// Validate the XML document.
$dom = new DOMDocument();
$dom->loadXML($returnXml);
if (!$noValidation) {
$validation = $this->validateJats($dom);
if (is_string($validation)) {
return ['plugins.importexport.inspec.export.failure.jatsValidation', $validation];
}
}
return $returnXml;
}
/**
* @copydoc ImportExportPlugin::getPluginSettingsPrefix()
*/
public function getPluginSettingsPrefix(): string
{
return 'inspec';
}
/**
* Get the journal abbreviation used to name packages and files, falling
* back to the journal's URL path when no abbreviation is set.
*/
public function journalAbbreviation(Context $context): string
{
return $context->getData('abbreviation', $context->getPrimaryLocale())
?: $context->getPath();
}
/**
* Get the connection settings values.
*/
public function getConnectionSettings(Context $context): array
{
$connectionSettings = [];
$connectionSettings['host'] = $this->getSetting($context->getId(), 'host');
$connectionSettings['port'] = $this->getSetting($context->getId(), 'port');
$connectionSettings['username'] = $this->getSetting($context->getId(), 'username');
$connectionSettings['password'] = $this->getSetting($context->getId(), 'password');
$connectionSettings['path'] = $this->getSetting($context->getId(), 'path');
return $connectionSettings;
}
/**
* Whether the SFTP account has everything required to deposit to it.
*/
public function hasCompleteConnectionSettings(int $contextId): bool
{
return $this->isAccountComplete([
'host' => $this->getSetting($contextId, 'host'),
'username' => $this->getSetting($contextId, 'username'),
'password' => $this->getSetting($contextId, 'password'),
]);
}
/**
* Whether an SFTP account (host/username/password) is fully filled in. The account
* is optional -- a journal may use the plugin for Export only and deliver packages
* to Inspec by hand -- but if any of the three is set, all three must be.
*/
public function isAccountComplete(array $account): bool
{
return !empty($account['host']) && !empty($account['username']) && !empty($account['password']);
}
/**
* Queue a delivery job per selected article, so that building the package and
* uploading it cannot block the request that triggered the deposit.
*
* @copydoc PubObjectsExportPlugin::depositXML()
*
* @param Submission[]|Publication[] $objects
* @param null|mixed $filename
*
* @return bool|array True once the deliveries are queued, or an array of error message details.
*/
public function depositXML($objects, $context, $filename = null, ?bool $noValidation = null): bool|array
{
if (!$this->hasCompleteConnectionSettings($context->getId())) {
return ['plugins.importexport.inspec.export.failure.settings'];
}
foreach ($objects as $object) {
dispatch(new InspecDeliver(
$object->getId(),
$object instanceof Publication,
$context->getId(),
$noValidation
));
$this->updateStatus($object, PubObjectsExportPlugin::EXPORT_STATUS_SUBMITTED);
}
return true;
}
/**
* Write a package to the configured Inspec SFTP account.
*
* @throws Exception If the package cannot be read, or the upload fails.
*/
public function deliverToEndpoint(string $path, string $filename, Context $context): void
{
$settings = $this->getConnectionSettings($context);
$adapter = new SftpAdapter(
new SftpConnectionProvider(
$settings['host'],
$settings['username'],
$settings['password'],
null,
null,
(int) $settings['port'] ?: 22
),
$settings['path'] ?: '/'
);
$fp = fopen($path, 'r');
if (!$fp) {
throw new Exception(
$this->convertErrorMessage(['plugins.importexport.inspec.export.failure.openingFile', $path])
);
}
try {
(new Filesystem($adapter))->writeStream($filename, $fp);
} finally {
fclose($fp);
}
}
/**
* Create a zip file with the given publications.
*
* @return array the paths of the created zip files and any error messages.
*/
public function createZip(Submission|Publication $object, Context $context, ?bool $noValidation = null): array
{
$zipDetails = [];
$fileService = app()->get('file');
$journalAbbreviation = $this->journalAbbreviation($context);
$genreDao = DAORegistry::getDAO('GenreDAO'); /** @var GenreDAO $genreDao */
$genres = $genreDao->getEnabledByContextId($context->getId());
$publication = $this->depositPublication($object);
if (!$publication) {
return ['error' => ['plugins.importexport.inspec.export.failure.noPublication']];
}
$locale = $object->getData('locale');
$zipPath = tempnam(sys_get_temp_dir(), 'InspecExport_');
$zip = new ZipArchive();
// OVERWRITE avoids the "Using empty file as ZipArchive" deprecation that is
// raised when opening the empty file tempnam() has already created.
if ($zip->open($zipPath, ZipArchive::CREATE | ZipArchive::OVERWRITE) !== true) {
$error = ['plugins.importexport.inspec.export.failure.creatingFile', $zip->getStatusString()];
$this->deleteTempFile($zipPath);
return ['error' => $error];
}
$filename = $this->buildFileName($journalAbbreviation, $context, $object);
// Add a PDF article galley file
$pdfFilesFound = 0;
$articlePdfFilename = null;
foreach ($publication->getData('galleys') ?? [] as $galley) { /** @var Galley $galley */
// Ignore remote galleys
if ($galley->getData('urlRemote')) {
continue;
}
// Ignore galleys with locales other than the submission locale
if ($galley->getData('locale') !== $locale) {
continue;
}
$submissionFileId = $galley->getData('submissionFileId');
$galleyFile = $submissionFileId ? Repo::submissionFile()->get($submissionFileId) : null;
if (!$galleyFile || $galleyFile->getData('mimetype') !== 'application/pdf') {
continue;
}
$genre = $genreDao->getById($galleyFile->getData('genreId'));
$isPrimaryDocument =
($genre->getCategory() == Genre::GENRE_CATEGORY_DOCUMENT) &&
!$genre->getSupplementary() &&
!$genre->getDependent();
if (!$isPrimaryDocument) {
continue;
}
$galleyPath = $fileService->get($galleyFile->getData('fileId'))->path;
$extension = pathinfo($galleyPath, PATHINFO_EXTENSION);
$galleyFilename = $this->buildFileName($journalAbbreviation, $context, $object, false, $extension);
$galleyFilePath = $filename . '/' . $galleyFilename;
$articlePdfFilename = $galleyFilename;
if ($pdfFilesFound > 0) {
return $this->discardZip(
$zip,
$zipPath,
['plugins.importexport.inspec.export.failure.multipleArticleFiles']
);
}
if (
!$zip->addFromString(
$galleyFilePath,
$fileService->fs->read($galleyPath)
)
) {
return $this->discardZip(
$zip,
$zipPath,
['plugins.importexport.inspec.export.failure.addingFile', $zip->getStatusString()]
);
}
$pdfFilesFound++;
}
// Add article XML to the zip
$document = $this->exportXML($object, null, $context, $noValidation, $exportErrors, $articlePdfFilename, $genres);
if (is_array($document)) {
return $this->discardZip($zip, $zipPath, $document);
} else {
$articlePathName = $filename . '/' . $this->buildFileName($journalAbbreviation, $context, $object, false, 'xml');
if (!$zip->addFromString($articlePathName, $document)) {
return $this->discardZip(
$zip,
$zipPath,
['plugins.importexport.inspec.export.failure.addingFile', $zip->getStatusString()]
);
}
$zipDetails['filename'] = $this->buildFileName($journalAbbreviation, $context, $object, true);
$zipDetails['path'] = $zipPath;
$zip->close();
}
return $zipDetails;
}
/**
* Create a zip file of collected objects for download.
*
* A single object is downloaded as its own package. Only several objects are
* gathered into a collection, because Inspec takes one article per zip.
*
* @return array the path of the created zip file or error details, if applicable.
*/
private function createZipCollection(array $objects, Context $context, ?bool $noValidation = null): array
{
if (count($objects) === 1) {
$zipPackage = $this->createZip(reset($objects), $context, $noValidation);
return empty($zipPackage['path'])
? ['error' => $zipPackage['error']]
: ['path' => $zipPackage['path']];
}
$finalZipPath = tempnam(sys_get_temp_dir(), 'InspecExport_');
$finalZip = new ZipArchive();
// OVERWRITE avoids the "Using empty file as ZipArchive" deprecation that is
// raised when opening the empty file tempnam() has already created.
if ($finalZip->open($finalZipPath, ZipArchive::CREATE | ZipArchive::OVERWRITE) !== true) {
$error = ['plugins.importexport.inspec.export.failure.creatingFile', $finalZip->getStatusString()];
$this->deleteTempFile($finalZipPath);
return ['error' => $error];
}
$createdPaths = [];
foreach ($objects as $object) {
$zipPackage = $this->createZip($object, $context, $noValidation);
if (empty($zipPackage['path']) || empty($zipPackage['filename'])) {
$submissionId = $object instanceof Publication ? $object->getData('submissionId') : $object->getId();
$versionString = $this->depositPublication($object)?->getData('versionString');
$errorDetails = __('plugins.importexport.inspec.export.failure.submissionVersion', [
'version' => $versionString,
'submissionId' => $submissionId,
'error' => $this->convertErrorMessage($zipPackage['error'])
]);
return $this->discardZip(
$finalZip,
$finalZipPath,
['plugins.importexport.inspec.export.failure.creatingFile', $errorDetails],
$createdPaths
);
}
// Track the package before adding it so that it is cleaned up either way.
$createdPaths[] = $zipPackage['path'];
if (!$finalZip->addFile($zipPackage['path'], $zipPackage['filename'] . '.zip')) {
return $this->discardZip(
$finalZip,
$finalZipPath,
['plugins.importexport.inspec.export.failure.creatingFile', $finalZip->getStatusString()],
$createdPaths
);
}
}
// The added files are only read when the archive is closed, so the per-article
// packages cannot be removed before this point.
$finalZip->close();
foreach ($createdPaths as $createdPath) {
$this->deleteTempFile($createdPath);
}
return ['path' => $finalZipPath];
}
/**
* Discard a partially built zip file and any temporary files collected for it,
* returning the error for the caller.
*
* @param array $collectedPaths Additional temporary files to remove.
*/
private function discardZip(ZipArchive $zip, string $zipPath, array $error, array $collectedPaths = []): array
{
$zip->close();
$this->deleteTempFile($zipPath);
foreach ($collectedPaths as $collectedPath) {
$this->deleteTempFile($collectedPath);
}
return ['error' => $error];
}
/**
* Remove a temporary file created during an export.
*/
public function deleteTempFile(string $path): void
{
if (file_exists($path) && !unlink($path)) {
error_log('Failed to delete temporary export file: ' . $path);
}
}
/**
* @copydoc Plugin::manage()
*/
public function manage($args, $request): JSONMessage
{
if ($request->getUserVar('verb') == 'settings') {
$user = $request->getUser();
$this->addLocaleData();
$form = new InspecSettingsForm($this, $request->getContext()->getId());
if ($request->getUserVar('save')) {
$form->readInputData();
if ($form->validate()) {
$form->execute();
$notificationManager = new NotificationManager();
$notificationManager->createTrivialNotification($user->getId());
}
} else {
$form->initData();
}
return new JSONMessage(true, $form->fetch($request));
}
return parent::manage($args, $request);
}
/**
* @copydoc ImportExportPlugin::executeCLI()
*/
public function executeCLI($scriptName, &$args)
{
}
/**
* @copydoc ImportExportPlugin::usage()
*/
public function usage($scriptName)
{
}
/**
* @copydoc Plugin::getName()
*/
public function getName(): string
{
return 'InspecExportPlugin';
}
/**
* @copydoc Plugin::getDisplayName()
*/
public function getDisplayName(): string
{
return __('plugins.importexport.inspec.displayName');
}
/**
* @copydoc Plugin::getDescription()
*/
public function getDescription(): string
{
return __('plugins.importexport.inspec.description.short');
}
/**
* @copydoc Plugin::getEncryptedSettingFields()
*/
public function getEncryptedSettingFields(): array
{
return [
'password',
];
}
/**
* @copydoc PubObjectsExportPlugin::getDepositSuccessNotificationMessageKey()
*
* Deliveries are queued rather than performed in the request, so the deposit
* action reports that the articles were submitted, not that they arrived.
*/
public function getDepositSuccessNotificationMessageKey(): string
{
return 'plugins.importexport.inspec.submit.success';
}
/**
* @copydoc PubObjectsExportPlugin::getSettingsFormClassName()
*/
public function getSettingsFormClassName(): string
{
return '\APP\plugins\generic\inspec\classes\form\InspecSettingsForm';
}
/**
* @copydoc \PKP\plugins\interfaces\HasTaskScheduler::registerSchedules()
*/
public function registerSchedules(PKPScheduler $scheduler): void
{
$scheduler
->addSchedule(new InspecInfoSender())
->daily()
->name(InspecInfoSender::class)
->withoutOverlapping();
}
/**
* @copydoc PubObjectsExportPlugin::getExportDeploymentClassName()
*/
public function getExportDeploymentClassName(): string
{
return '\APP\plugins\generic\inspec\InspecExportDeployment';
}
/**
* @copydoc PubObjectsExportPlugin::getExportActions()
*/
public function getExportActions($context): array
{
$actions = [PubObjectsExportPlugin::EXPORT_ACTION_EXPORT, PubObjectsExportPlugin::EXPORT_ACTION_MARKREGISTERED];
if ($this->hasCompleteConnectionSettings($context->getId())) {
array_unshift($actions, PubObjectsExportPlugin::EXPORT_ACTION_DEPOSIT);
}
return $actions;
}
/**
* Add a self-uri element referencing the PDF galley packaged alongside the XML.
*
* @return string|array Modified XML, or an array of error message details.
*/
protected function addPdfSelfUri(string $importedJats, ?string $articlePdfFilename): string|array
{
$dom = new DOMDocument();
$dom->preserveWhiteSpace = false;
if (!$dom->loadXML($importedJats)) {
return ['plugins.importexport.inspec.export.failure.loadJats'];
}
$xpath = new DOMXPath($dom);
if (!$articleMetaNode = $xpath->query('//article/front/article-meta')->item(0)) {
return ['plugins.importexport.inspec.export.failure.jatsNodeMissing', 'article-meta'];
}
if ($articlePdfFilename) {
// Remove any existing self-uri PDF links. This happens only when there
// is a replacement for them, so an article packaged without a PDF galley
// keeps whatever PDF reference its JATS already carried.
$selfUriPdfNodes = $xpath->query(
"self-uri[@content-type='pdf' or @content-type='application/pdf']",
$articleMetaNode
);
foreach ($selfUriPdfNodes as $selfUriPdfNode) {
$selfUriPdfNode->parentNode->removeChild($selfUriPdfNode);
}
$linkElement = $dom->createElement('self-uri');
$linkElement->setAttribute('content-type', 'pdf');
$linkElement->setAttribute('xlink:href', $articlePdfFilename);
$uriNode = $xpath->query('self-uri', $articleMetaNode)->item(0);
if ($uriNode) {
$uriNode->parentNode->insertBefore($linkElement, $uriNode);
} else {
if (!$abstractNode = $xpath->query('abstract', $articleMetaNode)->item(0)) {
return ['plugins.importexport.inspec.export.failure.jatsNodeMissing', 'abstract'];
}
$articleMetaNode->insertBefore($linkElement, $abstractNode);
}
}
return $dom->saveXML();
}
/**
* Resolve the JATS 1.2 publishing DTD, and the modules it includes, to the copy
* bundled with the application, so that validation does not depend on a request to
* jats.nlm.nih.gov. Any other document type is fetched as before.
*/
protected function resolveJatsEntity(?string $publicId, string $systemId, array $context): mixed
{
return $this->isBundledJatsIdentifier($publicId, $systemId)
? Core::getBaseDir() . self::JATS_12_DTD_PATH
: $systemId;
}
/**
* Whether a document declares the JATS version bundled with the application, and can
* therefore be validated against it. Generated JATS always does; uploaded JATS may
* declare another version, or no document type at all.
*/
protected function isBundledJatsVersion(DOMDocument $importedJats): bool
{
$doctype = $importedJats->doctype;
return $doctype !== null && $this->isBundledJatsIdentifier($doctype->publicId, $doctype->systemId);
}
/**
* Whether a public or system identifier names the JATS DTD bundled with the application.
*/
protected function isBundledJatsIdentifier(?string $publicId, ?string $systemId): bool
{
return $publicId === self::JATS_12_PUBLIC_ID
|| ($systemId !== null && str_replace('https://', 'http://', $systemId) === self::JATS_12_SYSTEM_ID);
}
/**
* Validate a JATS XML document against the DTD.
*
* @return true|string true if valid, or an error message.
*/
protected function validateJats(DOMDocument $importedJats): true|string
{
libxml_use_internal_errors(true);
// Validate against the bundled DTD rather than jats.nlm.nih.gov. Only JATS 1.2
// is bundled, so a document declaring any other version, or none, cannot be
// validated and is deposited as it is.
//
// @todo Report this to the journal instead of passing silently. It cannot be a
// notification: deposits are built in a queue job, so neither the manual nor the
// scheduled path has a request or a user by the time this runs. It is also a
// standing fact about the article's uploaded JATS rather than about one deposit,
// so it wants to be stored per article and surfaced in the export grid, next to
// the deposit status.
if (!$this->isBundledJatsVersion($importedJats)) {
libxml_clear_errors();
return true;
}
libxml_set_external_entity_loader($this->resolveJatsEntity(...));
try {
$isValid = $importedJats->validate();
} finally {
libxml_set_external_entity_loader(null);
}
if (!$isValid) {
$errors = libxml_get_errors();
$validationErrors = [];
foreach ($errors as $error) {
$validationErrors[] = "DTD Error [line {$error->line}]: " . trim($error->message);
}
libxml_clear_errors();
return implode(PHP_EOL, $validationErrors);
}
libxml_clear_errors();
return true;
}
/**
* Helper to convert an error array to a string.
*/
public function convertErrorMessage(array $errorMessage): string
{
$message = $errorMessage[0];
$param = $errorMessage[1] ?? null;
if (!$param) {
return __($message);
} else {
return __($message, ['param' => $param]);
}
}
}