-
Notifications
You must be signed in to change notification settings - Fork 27
Expand file tree
/
Copy pathCrossrefPlugin.php
More file actions
540 lines (471 loc) · 17.9 KB
/
CrossrefPlugin.php
File metadata and controls
540 lines (471 loc) · 17.9 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
<?php
/**
* @file plugins/generic/crossref/CrossrefPlugin.php
*
* Copyright (c) 2014-2026 Simon Fraser University
* Copyright (c) 2003-2026 John Willinsky
* Distributed under The MIT License. For full terms see the file LICENSE.
*
* @class CrossrefPlugin
*
* @brief Plugin to let managers deposit DOIs and metadata to Crossref
*
*/
namespace APP\plugins\generic\crossref;
use APP\core\Application;
use APP\facades\Repo;
use APP\issue\Issue;
use APP\plugins\generic\crossref\classes\CrossrefSettings;
use APP\plugins\IDoiRegistrationAgency;
use APP\publication\Publication;
use APP\services\ContextService;
use APP\submission\Submission;
use Exception;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Validator;
use PKP\context\Context;
use PKP\doi\RegistrationAgencySettings;
use PKP\plugins\GenericPlugin;
use PKP\plugins\Hook;
use PKP\plugins\interfaces\HasTaskScheduler;
use PKP\plugins\PluginRegistry;
use PKP\scheduledTask\PKPScheduler;
use PKP\services\PKPSchemaService;
class CrossrefPlugin extends GenericPlugin implements IDoiRegistrationAgency, HasTaskScheduler
{
public const CROSSREF_API_REFS_URL = 'https://doi.crossref.org/getResolvedRefs';
public const CROSSREF_API_REFS_URL_DEV = 'https://test.crossref.org/getResolvedRefs';
private CrossrefSettings $_settingsObject;
private ?CrossrefExportPlugin $_exportPlugin = null;
private ?CrossrefCitationDoiHandler $_citationDoiHandler = null;
public function getDisplayName(): string
{
return __('plugins.generic.crossref.displayName');
}
public function getDescription(): string
{
return __('plugins.generic.crossref.description');
}
/**
* @copydoc Plugin::register()
*
* @param null|mixed $mainContextId
*/
public function register($category, $path, $mainContextId = null)
{
$success = parent::register($category, $path, $mainContextId);
if ($success) {
// If the system isn't installed, or is performing an upgrade, don't
// register hooks. This will prevent DB access attempts before the
// schema is installed.
if (Application::isUnderMaintenance()) {
return true;
}
PluginRegistry::register('importexport', new CrossrefExportPlugin($this), $this->getPluginPath());
$this->_exportPlugin = PluginRegistry::getPlugin('importexport', 'CrossrefExportPlugin');
$this->getCitationDoiHandler()->registerHooks();
Hook::add('Schema::get::doi', $this->addToSchema(...));
if ($this->getEnabled($mainContextId)) {
$this->_pluginInitialization();
$this->getCitationDoiHandler()->registerEnabledHooks();
}
}
return $success;
}
/**
* Remove plugin as configured registration agency if set at the time plugin is disabled.
*
* @copydoc LazyLoadPlugin::setEnabled()
*/
public function setEnabled($enabled)
{
parent::setEnabled($enabled);
if (!$enabled) {
$contextId = $this->getCurrentContextId();
/** @var \PKP\context\ContextDAO $contextDao */
$contextDao = Application::getContextDAO();
$context = $contextDao->getById($contextId);
if ($context->getData(Context::SETTING_CONFIGURED_REGISTRATION_AGENCY) === $this->getName()) {
$context->setData(Context::SETTING_CONFIGURED_REGISTRATION_AGENCY, Context::SETTING_NO_REGISTRATION_AGENCY);
$contextDao->updateObject($context);
}
}
}
/**
* @copydoc \PKP\plugins\Plugin::getEncryptedSettingFields()
*/
public function getEncryptedSettingFields(): array
{
return [
'password',
];
}
/**
* Register plugin hooks.
*/
private function _pluginInitialization(): void
{
Hook::add('DoiSettingsForm::setEnabledRegistrationAgencies', $this->addAsRegistrationAgencyOption(...));
Hook::add('DoiSetupSettingsForm::getObjectTypes', $this->addAllowedObjectTypes(...));
Hook::add('Context::validate', $this->validateAllowedPubObjectTypes(...));
Hook::add('Doi::markRegistered', $this->editMarkRegisteredParams(...));
Hook::add('DoiListPanel::setConfig', $this->addRegistrationAgencyName(...));
Hook::add('Publication::validatePublish', $this->validate(...));
}
/**
* @copydoc \PKP\plugins\interfaces\HasTaskScheduler::registerSchedules()
*/
public function registerSchedules(PKPScheduler $scheduler): void
{
$scheduler
->addSchedule(new CrossrefCitationDoiCheckTask([]))
->hourly()
->name(CrossrefCitationDoiCheckTask::class)
->withoutOverlapping();
}
/**
* Add properties for Crossref to the DOI entity for storage in the database.
*
* @param string $hookName `Schema::get::doi`
* @param array{schema: object{properties: array<string, object>}} $args
*/
public function addToSchema(string $hookName, array $args): bool
{
$schema = &$args[0];
$settings = [
$this->_exportPlugin->getDepositBatchIdSettingName(),
$this->_exportPlugin->getFailedMsgSettingName(),
$this->_exportPlugin->getSuccessMsgSettingName(),
];
foreach ($settings as $settingName) {
$schema->properties->{$settingName} = (object) [
'type' => 'string',
'apiSummary' => true,
'validation' => ['nullable'],
];
}
return Hook::CONTINUE;
}
/**
* Check whether Crossref credentials (username and password) are configured for the given context.
*/
public function hasCrossrefCredentials(?int $contextId = null): bool
{
if (!isset($contextId)) {
$contextId = $this->getCurrentContextId();
}
return strlen((string) $this->getSetting($contextId, 'username')) > 0
&& strlen((string) $this->getSetting($contextId, 'password')) > 0;
}
/**
* Check whether citation metadata is enabled for the given context.
*/
public function citationsEnabled(?int $contextId = null): bool
{
if (!isset($contextId)) {
$contextId = $this->getCurrentContextId();
}
$contextDao = Application::getContextDAO();
$context = $contextDao->getById($contextId);
return !empty($context->getData('citations'));
}
/**
* Get the CrossrefCitationDoiHandler instance.
*/
public function getCitationDoiHandler(): CrossrefCitationDoiHandler
{
return $this->_citationDoiHandler ??= new CrossrefCitationDoiHandler($this);
}
/**
* Fetch resolved citation DOIs from Crossref and store them for all pending submissions.
*/
public function processPendingCitationDois(Context $context): void
{
$this->getCitationDoiHandler()->processPendingCitationDois($context);
}
/**
* Includes plugin in list of configurable registration agencies for DOI depositing functionality
*
* @param string $hookName DoiSettingsForm::setEnabledRegistrationAgencies
* @param array{Collection<int,IDoiRegistrationAgency>} $args [Enabled registration agencies]
*/
public function addAsRegistrationAgencyOption($hookName, $args)
{
/** @var Collection<int,IDoiRegistrationAgency> $enabledRegistrationAgencies */
$enabledRegistrationAgencies = &$args[0];
$enabledRegistrationAgencies->add($this);
}
/**
* Includes human-readable name of registration agency for display in conjunction with how/with whom the
* DOI was registered.
*
* @param string $hookName DoiListPanel::setConfig
* @param array{array<string, mixed>} $args [Configuration]
*/
public function addRegistrationAgencyName(string $hookName, array $args): bool
{
$config = &$args[0];
$config['registrationAgencyNames'][$this->_exportPlugin->getName()] = $this->getRegistrationAgencyName();
return HOOK::CONTINUE;
}
/**
* Adds self to "allowed" list of pub object types that can be assigned DOIs for this registration agency.
*
* @param string $hookName DoiSetupSettingsForm::getObjectTypes
* @param array{array<array<string, mixed>>} $args [Object type options]
*/
public function addAllowedObjectTypes(string $hookName, array $args): bool
{
$objectTypeOptions = &$args[0];
$allowedTypes = $this->getAllowedDoiTypes();
$objectTypeOptions = array_map(function ($option) use ($allowedTypes) {
if (in_array($option['value'], $allowedTypes)) {
$option['allowedBy'][] = $this->getName();
}
return $option;
}, $objectTypeOptions);
return Hook::CONTINUE;
}
/**
* Add validation rule to Context for restriction of allowed pubObject types for DOI registration.
*
* @throws Exception
*/
public function validateAllowedPubObjectTypes(string $hookName, array $args): bool
{
$errors = &$args[0];
$props = $args[2];
if (!isset($props['enabledDoiTypes'])) {
return Hook::CONTINUE;
}
$contextId = $props['id'];
if (empty($contextId)) {
throw new Exception('A context ID must be present to edit context settings');
}
/** @var ContextService $contextService */
$contextService = app()->get('context');
$context = $contextService->get($contextId);
$enabledRegistrationAgency = $context->getConfiguredDoiAgency();
if (!$enabledRegistrationAgency instanceof $this) {
return Hook::CONTINUE;
}
$allowedTypes = $enabledRegistrationAgency->getAllowedDoiTypes();
if (!empty(array_diff($props['enabledDoiTypes'], $allowedTypes))) {
$errors['enabledDoiTypes'] = [__('doi.manager.settings.enabledDoiTypes.error')];
}
return Hook::CONTINUE;
}
/**
* Checks if plugin meets registration agency-specific requirements for being active and handling deposits
*/
public function isPluginConfigured(Context $context): bool
{
$settingsObject = $this->getSettingsObject();
/** @var PKPSchemaService $schemaService */
$schemaService = app()->get('schema');
$requiredProps = $schemaService->getRequiredProps($settingsObject::class);
foreach ($requiredProps as $requiredProp) {
$settingValue = $this->getSetting($context->getId(), $requiredProp);
if (empty($settingValue)) {
return false;
}
}
$doiPrefix = $context->getData(Context::SETTING_DOI_PREFIX);
if (empty($doiPrefix)) {
return false;
}
if (!$context->getData('publisherInstitution') || !($context->getData('onlineIssn') || $context->getData('printIssn'))) {
return false;
}
return true;
}
/**
* Get configured registration agency display name for use in DOI management pages
*/
public function getRegistrationAgencyName(): string
{
return __('plugins.generic.crossref.registrationAgency.name');
}
/**
* @param Submission[] $submissions
*/
public function exportSubmissions(array $submissions, Context $context): array
{
// Get filter and set objectsFileNamePart (see: PubObjectsExportPlugin::prepareAndExportPubObjects)
$filterName = $this->_exportPlugin->getSubmissionFilter();
$xmlErrors = [];
$temporaryFileId = $this->_exportPlugin->exportAsDownload($context, $submissions, $filterName, 'articles', null, $xmlErrors);
return ['temporaryFileId' => $temporaryFileId, 'xmlErrors' => $xmlErrors];
}
/**
* @param Submission[] $submissions
*/
public function depositSubmissions(array $submissions, Context $context): array
{
$filterName = $this->_exportPlugin->getSubmissionFilter();
$responseMessage = '';
$status = $this->_exportPlugin->exportAndDeposit($context, $submissions, $filterName, $responseMessage);
return [
'hasErrors' => !$status,
'responseMessage' => $responseMessage
];
}
/**
* @param Issue[] $issues
*/
public function exportIssues(array $issues, Context $context): array
{
// Get filter and set objectsFileNamePart (see: PubObjectsExportPlugin::prepareAndExportPubObjects)
$filterName = $this->_exportPlugin->getIssueFilter();
$xmlErrors = [];
$temporaryFileId = $this->_exportPlugin->exportAsDownload($context, $issues, $filterName, 'issues', null, $xmlErrors);
return ['temporaryFileId' => $temporaryFileId, 'xmlErrors' => $xmlErrors];
}
/**
* @param Issue[] $issues
*/
public function depositIssues(array $issues, Context $context): array
{
$filterName = $this->_exportPlugin->getIssueFilter();
$responseMessage = '';
$status = $this->_exportPlugin->exportAndDeposit($context, $issues, $filterName, $responseMessage);
return [
'hasErrors' => !$status,
'responseMessage' => $responseMessage
];
}
/**
* Adds Crossref specific info to Repo::doi()->markRegistered()
*
* @param string $hookName Doi::markRegistered
*
*/
public function editMarkRegisteredParams(string $hookName, array $args): bool
{
$editParams = &$args[0];
$editParams[$this->_exportPlugin->getFailedMsgSettingName()] = null;
$editParams[$this->_exportPlugin->getSuccessMsgSettingName()] = null;
return false;
}
/**
* @inheritDoc
*/
public function getErrorMessageKey(): ?string
{
return $this->_exportPlugin->getFailedMsgSettingName();
}
/**
* @inheritDoc
*/
public function getRegisteredMessageKey(): ?string
{
return $this->_exportPlugin->getSuccessMsgSettingName();
}
/**
* @inheritDoc
*/
public function getSettingsObject(): RegistrationAgencySettings
{
if (!isset($this->_settingsObject)) {
$this->_settingsObject = new CrossrefSettings($this);
}
return $this->_settingsObject;
}
/**
* @inheritDoc
*/
public function getAllowedDoiTypes(): array
{
return [Repo::doi()::TYPE_PUBLICATION, Repo::doi()::TYPE_ISSUE];
}
/**
* Make additional validation checks against publishing requirements
*
* @throws Exception
* @see PKPPublicationService::validatePublish()
*/
public function validate(string $hookName, array $args): bool
{
$errors = & $args[0];
$publication = $args[1];
$submission = $args[2];
$issueId = $publication->getData('issueId');
$context = Application::getContextDAO()->getById($submission->getData('contextId'));
$enabledRegistrationAgency = $context->getConfiguredDoiAgency();
$enabledDoiTypes = $context->getData('enabledDoiTypes');
$doiCreationTime = $context->getData(Context::SETTING_DOI_CREATION_TIME);
if (!($enabledRegistrationAgency instanceof $this) ||
!in_array(Repo::doi()::TYPE_PUBLICATION, $enabledDoiTypes) ||
$doiCreationTime === Repo::doi()::CREATION_TIME_PUBLICATION) {
return Hook::CONTINUE;
}
$rules = [
'publisherInstitution' => ['required', 'string'],
'onlineIssn' => ['required_without:printIssn', 'nullable', 'string'],
'printIssn' => ['required_without:onlineIssn', 'nullable', 'string'],
'doi' => ['required', 'string'],
'issueId' => [
'sometimes',
'nullable',
'integer',
function ($attribute, $value, $fail) use ($context, $publication) {
$issue = Repo::issue()->get($value, $context->getId());
if (!$issue) {
$fail(__('plugins.generic.crossref.issueId.invalid', [
'publicationTitle' => $publication->getLocalizedTitle()
]));
}
},
],
];
$metadata = [
'publisherInstitution' => $context->getData('publisherInstitution'),
'onlineIssn' => $context->getData('onlineIssn'),
'printIssn' => $context->getData('printIssn'),
'doi' => $publication->getDoi(),
'issueId' => $issueId,
];
$validator = Validator::make(
$metadata,
$rules,
$this->getValidationMessages($publication)
);
if (!$validator->passes()) {
$errors = $this->formatErrors($validator->errors()->toArray());
}
return HOOK::CONTINUE;
}
/**
* Get validation messages
* @throws Exception
*/
private function getValidationMessages(Publication $publication): array
{
return [
'doi.required' => __('plugins.generic.crossref.doi.required', [
'publicationTitle' => $publication->getLocalizedTitle()
]),
'doi.url' => __('plugins.generic.crossref.doi.url', [
'publicationTitle' => $publication->getLocalizedTitle()
]),
'onlineIssn.required_without' => __('plugins.generic.crossref.issn.requiredWithout'),
'printIssn.required_without' => __('plugins.generic.crossref.issn.requiredWithout'),
'publisherInstitution.required' => __('plugins.generic.crossref.publisherInstitution.required')
];
}
/**
* Format errors
*/
private function formatErrors(array $errors): array
{
$values = [];
foreach ($errors as $value) {
if (is_array($value)) {
$values = array_merge($values, $this->formatErrors($value));
} else {
$values[] = $value;
}
}
return $values;
}
}