-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCrossrefExportPlugin.php
583 lines (512 loc) · 15.6 KB
/
CrossrefExportPlugin.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
<?php
/**
* @file plugins/generic/crossref/CrossrefExportPlugin.php
*
* @brief Crossref export plugin
*/
namespace APP\plugins\generic\crossref;
use PKP\plugins\ImportExportPlugin;
use PKP\context\Context;
use APP\plugins\generic\crossref\CrossrefExportDeployment;
use APP\core\Application;
use Exception;
use PKP\doi\Doi;
use PKP\db\DAORegistry;
use APP\facades\Repo;
use PKP\plugins\Plugin;
use PKP\filter\FilterDAO;
use APP\submission\Submission;
use PKP\config\Config;
use APP\plugins\IDoiRegistrationAgency;
use DateTime;
use PKP\file\TemporaryFileManager;
use PKP\file\FileManager;
class CrossrefExportPlugin extends ImportExportPlugin
{
// Crossref settings.
public const CROSSREF_DEPOSIT_STATUS = 'depositStatus';
public const CROSSREF_STATUS_FAILED = 'failed';
public const CROSSREF_API_DEPOSIT_OK = 200;
public const CROSSREF_API_DEPOSIT_ERROR_FROM_CROSSREF = 403;
public const CROSSREF_API_URL = 'https://api.crossref.org/v2/deposits';
public const CROSSREF_API_URL_TEST = 'https://test.crossref.org/servlet/deposit';
public const CROSSREF_API_STATUS_URL = 'https://api.crossref.org/servlet/submissionDownload';
/**
* Constructor.
*/
public function __construct(protected IDoiRegistrationAgency|Plugin $agencyPlugin)
{
parent::__construct();
}
/**
* @copydoc Plugin::getName()
*/
public function getName()
{
return 'CrossrefExportPlugin';
}
/**
* @copydoc Plugin::getDisplayName()
*/
public function getDisplayName()
{
return __('plugins.importexport.crossref.displayName');
}
/**
* @copydoc Plugin::getDescription()
*/
public function getDescription()
{
return __('plugins.importexport.crossref.description');
}
public function getPluginSettingsPrefix()
{
return 'crossrefplugin';
}
public function getSubmissionFilter()
{
return 'monograph=>crossref-xml';
}
/**
* @copydoc Plugin::register()
*
* @param null|mixed $mainContextId
*/
public function register($category, $path, $mainContextId = null)
{
if (!parent::register($category, $path, $mainContextId)) return false;
$success = parent::register($category, $path, $mainContextId);
if ($success) {
// register hooks. This will prevent DB access attempts before the
// schema is installed.
if (Application::isUnderMaintenance()) {
return true;
}
}
return $success;
}
/**
* Proxy to main plugin class's `getSetting` method
*
*/
public function getSetting($contextId, $name)
{
return $this->agencyPlugin->getSetting($contextId, $name);
}
/**
* Get a list of additional setting names that should be stored with the objects.
*
* @return array
*/
protected function _getObjectAdditionalSettings()
{
return [
$this->getDepositBatchIdSettingName(),
$this->getFailedMsgSettingName(),
];
}
public function getExportDeploymentClassName()
{
return (string) \APP\plugins\generic\crossref\CrossrefExportDeployment::class;
}
public function executeCLI($scriptName, &$args): void
{
fatalError('Not implemented.');
}
public function usage($scriptName): void
{
fatalError('Not implemented.');
}
// /**
// * Mark monographs and chapters as registered.
// */
// public function markRegistered($context, $objects)
// {
// foreach ($objects as $object) {
// // Get all DOIs for each monograph and chapters.
// if ($object instanceof Submission) {
// $doiIds = Repo::doi()->getDoisForSubmission($object->getId());
// }
// foreach ($doiIds as $doiId) {
// Repo::doi()->markRegistered($doiId);
// }
// }
// }
/**
* Get request failed message setting name.
* NB: Changed as of 3.4
*
* @return string
*/
public function getFailedMsgSettingName()
{
return $this->getPluginSettingsPrefix() . '_failedMsg';
}
/**
* Get deposit batch ID setting name.
* NB Changed as of 3.4
*
* @return string
*/
public function getDepositBatchIdSettingName()
{
return $this->getPluginSettingsPrefix() . '_batchId';
}
public function getDepositSuccessNotificationMessageKey()
{
return 'plugins.generic.crossref.register.success';
}
/**
* Exports and stores XML as a TemporaryFile.
* Multiple XMLs are packaged as .tar.gz
*
* @throws Exception
*/
public function exportAsDownload(Context $context, array $submissions, string $filter, ?array &$outputErrors = null): ?int
{
$fileManager = new TemporaryFileManager();
$result = $this->_checkForTar();
if ($result === true) {
// Construct XML file for download.
$exportedFiles = [];
foreach ($submissions as $submission) {
$submissionId = $submission->getId();
$exportXml = $this->exportXML($submission, $filter, $context, $outputErrors);
// Construct export file name.
$dateString = new DateTime();
$exportFileName = $this->getExportFileName(
$this->getExportPath(),
'monograph',
$submissionId,
'.xml',
$dateString
);
$fileManager->writeFile($exportFileName, $exportXml);
$exportedFiles[] = $exportFileName;
}
// For more than one file package the files up as a single tar.
assert(count($exportedFiles) >= 1);
if (count($exportedFiles) > 1) {
$finalExportFileName = $this->getExportFileName(
$this->getExportPath(),
'monographs',
$context->getId(),
'.tar.gz',
$dateString
);
$this->_tarFiles($this->getExportPath(), $finalExportFileName, $exportedFiles);
// Remove files.
foreach ($exportedFiles as $exportedFile) {
$fileManager->deleteByPath($exportedFile);
}
} else {
$finalExportFileName = array_shift($exportedFiles);
}
// Create a temporary file for the user.
$user = Application::get()->getRequest()->getUser();
return $fileManager->createTempFileFromExisting($finalExportFileName, $user->getId());
}
return null;
}
/**
* Export XMLs and deposit via HTTP-client.
* @param Context $context
* @param array $submissions
* @param string $filter
* @param string &$responseMessage
*/
public function exportAndDeposit($context, $submissions, $filter, &$responseMessage): bool
{
$fileManager = new FileManager();
// Just one general error should be displayed.
$errorsOccurred = false;
// The new Crossref deposit API expects one request per object.
foreach ($submissions as $submission) {
// Create XML.
$outputErrors = [];
$submissionId = $submission->getId();
$exportXml = $this->exportXML($submission, $filter, $context, $outputErrors);
// Construct export file name.
$dateString = new DateTime();
$exportFileName = $this->getExportFileName(
$this->getExportPath(),
'monograph',
$submissionId,
'.xml',
$dateString
);
$fileManager->writeFile($exportFileName, $exportXml);
// Deposit the XML file if no XML-creation errors occurred.
if ($outputErrors) {
$errorsOccurred = true;
} else {
$result = $this->depositXML($submission, $context, $exportFileName);
// Handle deposit errors.
if (!$result) {
$errorsOccurred = true;
}
if (is_array($result)) {
$resultErrors[] = $result;
}
}
// Remove all temporary files.
$fileManager->deleteByPath($exportFileName);
}
// Prepare response message and return status.
if ($errorsOccurred) {
if (!empty($outputErrors)) {
$responseMessage = __($outputErrors[0]);
$this->updateDepositStatus($context, $submission, Doi::STATUS_ERROR, null, $responseMessage);
return false;
} else if (!empty($resultErrors)) {
$responseMessage = __('plugins.generic.crossref.deposit.unsuccessful');
return false;
} else {
$responseMessage = __('api.dois.400.depositFailed');
return false;
}
} else {
$responseMessage = $this->getDepositSuccessNotificationMessageKey();
return true;
}
}
/**
* Return the whole export file name.
*
* @param string $basePath Base path for temporary file storage
* @param string $objectsFileNamePart Part different for each object type.
* @param int $id Context or submission ID.
* @param string $extension
* @param ?DateTime $dateFilenamePart
*
* @return string
*/
function getExportFileName($basePath, $objectsFileNamePart, $id, $extension = '.xml', ?DateTime $dateFilenamePart = null)
{
$dateFilenamePartString = $dateFilenamePart->format('d-m-Y');
return $basePath . $this->getPluginSettingsPrefix() . '-' . $dateFilenamePartString . '-' . $objectsFileNamePart . '-' . $id . $extension;
}
/**
* Export selected submission as XML/tar-package.
*
* @param mixed $submission Array of or single published submission, issue or galley
* @param string $filter
* @param Context $context
* @param null|mixed $outputErrors
*
* @return string XML document.
*/
function exportXml($submission, $filter, $context, &$outputErrors = null)
{
// Manage XML-filter.
$filterDao = DAORegistry::getDAO('FilterDAO');
/** @var FilterDAO $filterDao */
$exportFilters = $filterDao->getObjectsByGroup($filter);
assert(count($exportFilters) == 1); // Assert only a single serialization filter
$exportFilter = array_shift($exportFilters);
// Configure filter.
$plugin = $this;
$exportFilter->setDeployment(new CrossrefExportDeployment($context, $plugin));
$exportFilter->setNoValidation(true);
// Apply filter to object and save as xml if no error is thrown.
$submissions[] = $submission; // For this filter, we need an array.
$exportXml = $exportFilter->execute($submissions);
$xml = $exportXml->saveXml();
// Handle custom filter errors.
$hasFilterErrors = $exportFilter->hasErrors();
if ($hasFilterErrors) {
$filterErrors = $exportFilter->getErrors();
$outputErrors = $filterErrors;
}
return $xml;
}
/**
* Create a tar archive.
*
* @param string $targetPath
* @param string $targetFile
* @param array $sourceFiles
*/
public function _tarFiles($targetPath, $targetFile, $sourceFiles)
{
assert((bool) $this->_checkForTar());
// GZip compressed result file.
$tarCommand = Config::getVar('cli', 'tar') . ' -czf ' . escapeshellarg($targetFile);
// Do not reveal our internal export path by exporting only relative filenames.
$tarCommand .= ' -C ' . escapeshellarg($targetPath);
// Do not reveal our webserver user by forcing root as owner.
$tarCommand .= ' --owner 0 --group 0 --';
// Add each file individually so that other files in the directory
// will not be included.
foreach ($sourceFiles as $sourceFile) {
assert(dirname($sourceFile) . '/' === $targetPath);
if (dirname($sourceFile) . '/' !== $targetPath) {
continue;
}
$tarCommand .= ' ' . escapeshellarg(basename($sourceFile));
}
// Execute the command.
exec($tarCommand);
}
/**
* Test whether the tar binary is available.
*
* @return bool|array Boolean true if available otherwise
* an array with an error message.
*/
public function _checkForTar()
{
$tarBinary = Config::getVar('cli', 'tar');
if (empty($tarBinary) || !is_executable($tarBinary)) {
$result = [
['manager.plugins.tarCommandNotFound']
];
} else {
$result = true;
}
return $result;
}
/**
* Return the plugin export directory.
*
* @return string The export directory path.
*/
public function getExportPath()
{
return Config::getVar('files', 'files_dir') . '/temp/';
}
/**
* Check the Crossref APIs, if deposits and registration have been successful
*
* @param Context $context
* @param DataObject $object The object getting deposited
* @param int $status
* @param string $batchId
* @param string $failedMsg (optional)
*/
public function updateDepositStatus($context, $object, $status, $batchId = null, $failedMsg = null)
{
// Updates DOI of monograph as well as chapters.
assert($object instanceof Submission);
if ($object instanceof Submission) {
$doiIds = Repo::doi()->getDoisForSubmission($object->getId());
}
foreach ($doiIds as $doiId) {
$doi = Repo::doi()->get($doiId);
$editParams = [
'status' => $status,
// Sets new failedMsg or resets to null for removal of previous message.
$this->getFailedMsgSettingName() => $failedMsg,
$this->getDepositBatchIdSettingName() => $batchId,
];
if ($status === Doi::STATUS_REGISTERED) {
$editParams['registrationAgency'] = $this->getName();
}
Repo::doi()->edit($doi, $editParams);
}
}
/**
* Deposit selected submissions via HTTP client.
*
* @param Submission $submission
* @param Context $context
* @param string $filename
*/
public function depositXML($submission, $context, $filename)
{
// Application is set to sandbox mode and will not run the features of plugin
if (Config::getVar('general', 'sandbox', false)) {
error_log('Application is set to sandbox mode and will not have any interaction with crossref external service');
return false;
}
$status = null;
$msgSave = null;
$httpClient = Application::get()->getHttpClient();
assert(is_readable($filename));
try {
$response = $httpClient->request(
'POST',
$this->isTestMode($context) ? static::CROSSREF_API_URL_TEST : static::CROSSREF_API_URL,
[
'multipart' => [
[
'name' => 'usr',
'contents' => $this->getSetting($context->getId(), 'username'),
],
[
'name' => 'pwd',
'contents' => $this->getSetting($context->getId(), 'password'),
],
[
'name' => 'operation',
'contents' => 'doMDUpload',
],
[
'name' => 'mdFile',
'contents' => fopen($filename, 'r'),
],
]
]
);
} catch (RequestException $e) {
// Handle exception.
$returnMessage = $e->getMessage();
if ($e->hasResponse()) {
$eResponseBody = $e->getResponse()->getBody();
$eStatusCode = $e->getResponse()->getStatusCode();
if ($eStatusCode == static::CROSSREF_API_DEPOSIT_ERROR_FROM_CROSSREF) {
$xmlDoc = new \DOMDocument('1.0', 'utf-8');
$xmlDoc->loadXML($eResponseBody);
$batchIdNode = $xmlDoc->getElementsByTagName('batch_id')->item(0);
$msg = $xmlDoc->getElementsByTagName('msg')->item(0)->nodeValue;
$msgSave = $msg . PHP_EOL . $eResponseBody;
$status = Doi::STATUS_ERROR;
$this->updateDepositStatus($context, $submission, $status, $batchIdNode->nodeValue, $msgSave);
$returnMessage = $msg . ' (' . $eStatusCode . ' ' . $e->getResponse()->getReasonPhrase() . ')';
} else {
$returnMessage = $eResponseBody . ' (' . $eStatusCode . ' ' . $e->getResponse()->getReasonPhrase() . ')';
$this->updateDepositStatus($context, $submission, Doi::STATUS_ERROR, null, $returnMessage);
}
}
return __('plugins.importexport.common.register.error.mdsError', ['param' => $returnMessage]);
}
// Get DOMDocument from the response XML string.
$xmlDoc = new \DOMDocument('1.0', 'utf-8');
$xmlDoc->loadXML($response->getBody());
$batchIdNode = $xmlDoc->getElementsByTagName('batch_id')->item(0);
// Get the DOI deposit status
// If the deposit failed
$failureCountNode = $xmlDoc->getElementsByTagName('failure_count')->item(0);
$failureCount = (int) $failureCountNode->nodeValue;
if ($failureCount > 0) {
$status = Doi::STATUS_ERROR;
$result = false;
} else {
// Deposit was received
$status = Doi::STATUS_REGISTERED;
$result = true;
// If there were some warnings, display them
$warningCountNode = $xmlDoc->getElementsByTagName('warning_count')->item(0);
$warningCount = (int) $warningCountNode->nodeValue;
if ($warningCount > 0) {
$result = [['plugins.importexport.crossref.register.success.warning', htmlspecialchars($response->getBody())]];
}
}
// Update the status.
if ($status) {
$this->updateDepositStatus($context, $submission, $status, $batchIdNode->nodeValue, $msgSave, null);
}
return $result;
}
/**
* Check whether we are in test mode.
*
* @param Context $context
*
* @return bool
*/
public function isTestMode($context)
{
return ($this->getSetting($context->getId(), 'testMode') == 1);
}
}