Repository navigation
Expand file tree
/
Copy pathWebhookPlugin.php
More file actions
539 lines (460 loc) · 21.1 KB
/
Copy pathWebhookPlugin.php
File metadata and controls
539 lines (460 loc) · 21.1 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
<?php
namespace APP\plugins\generic\webhook;
use APP\core\Application;
use APP\decision\Decision;
use APP\facades\Repo;
use APP\publication\Publication;
use APP\submission\Submission;
use Illuminate\Support\Facades\Event;
use PKP\components\forms\FieldHTML;
use PKP\components\forms\FormComponent;
use PKP\context\Context;
use PKP\core\JSONMessage;
use PKP\galley\Galley;
use PKP\linkAction\LinkAction;
use PKP\linkAction\request\AjaxModal;
use PKP\observers\events\DecisionAdded;
use PKP\observers\events\MetadataChanged;
use PKP\observers\events\PublicationPublished;
use PKP\observers\events\PublicationUnpublished;
use PKP\plugins\GenericPlugin;
use PKP\plugins\Hook;
use PKP\submission\PKPSubmission;
use PKP\submissionFile\SubmissionFile;
class WebhookPlugin extends GenericPlugin
{
/**
* Publication IDs a "published" webhook was already dispatched for in this
* request. OJS fires MetadataChanged a second time right after publishing
* (IssueGridHandler and the PublishSubmissions scheduled task both do this
* in the same request as the PublicationPublished event), which would
* otherwise queue a redundant "updated" webhook for the same publication.
*/
protected array $publishedInThisRequest = [];
public function getDisplayName()
{
return __('plugins.generic.webhook.displayName');
}
public function getDescription()
{
$description = __('plugins.generic.webhook.description');
if (!$this->hasValidWebhookConfig()) {
$description .= ' ' . __('plugins.generic.webhook.description.requiresConfig');
} elseif (!WebhookStatus::tableExists()) {
$description .= ' ' . __('plugins.generic.webhook.description.missingStatusTable');
} elseif (!$this->hasRecommendedDoiConfig()) {
$description .= ' ' . __('plugins.generic.webhook.description.doiConfigWarning');
}
return $description;
}
/**
* @copydoc Plugin::register()
*/
public function register($category, $path, $mainContextId = null)
{
if (!parent::register($category, $path, $mainContextId)) {
return false;
}
// Listeners are registered unconditionally and each one checks whether the plugin is
// enabled for the *submission's* journal instead (see dispatchWebhook()). Gating on
// getEnabled($mainContextId) here would skip registration entirely in the CLI scheduler:
// it loads generic plugins without a context, so getEnabled() reads the site-level
// (context 0) setting, which is never set for a journal-level plugin - and the
// PublishSubmissions task would then publish scheduled articles across all journals
// without a single "published" webhook going out.
if (Application::isInstalled()) {
Event::listen(
DecisionAdded::class,
function (DecisionAdded $event) {
if ($event->decisionType->getDecision() === Decision::SEND_TO_PRODUCTION) {
$publication = $event->submission->getCurrentPublication();
$this->dispatchWebhook('production', $event->context->getId(), $event->submission->getId(), $publication->getId());
}
}
);
Event::listen(
PublicationPublished::class,
function (PublicationPublished $event) {
$publication = $event->publication;
$oldPublication = $event->oldPublication;
$submission = $event->submission;
$wasPublished = $oldPublication->getData('status') === PKPSubmission::STATUS_PUBLISHED;
$isPublished = $publication->getData('status') === PKPSubmission::STATUS_PUBLISHED;
if (!$wasPublished && $isPublished) {
$this->publishedInThisRequest[$publication->getId()] = true;
$this->dispatchWebhook('published', $submission->getData('contextId'), $submission->getId(), $publication->getId());
}
}
);
Event::listen(
MetadataChanged::class,
function (MetadataChanged $event) {
$submission = $event->submission;
$publication = $submission->getCurrentPublication();
if (!empty($this->publishedInThisRequest[$publication->getId()])) {
return;
}
// Only resend if this publication was already sent at least once
// before - tracked via a recorded zsId, not doiId: the
// Zeitschriftenserver may have accepted the submission without
// being able to mint a DOI (DOI_FAILED/DOI_DISABLED), in which
// case doiId never gets set but a correction still needs to
// reach it. success alone doesn't work either, since it flips
// to false again after any later failed attempt.
$status = WebhookStatus::get($publication->getId());
if ($status && $status['zsId']) {
$this->dispatchWebhook('updated', $submission->getData('contextId'), $submission->getId(), $publication->getId());
}
}
);
Event::listen(
PublicationUnpublished::class,
function (PublicationUnpublished $event) {
$this->dispatchWebhook('unpublished', $event->context->getId(), $event->submission->getId(), $event->publication->getId());
}
);
Hook::add('Galley::add', function (string $hookName, array $args) {
/** @var Galley $galley */
$galley = $args[0];
// The galley form creates a file-based galley without its file; the upload that
// follows sets submissionFileId through Galley::edit, which sends the webhook then.
// Reacting here as well would send one "updated" with an incomplete galley first.
if (!$galley->getData('submissionFileId') && !$galley->getData('urlRemote')) {
return;
}
$this->handleGalleyChanged($galley->getData('publicationId'));
});
Hook::add('Galley::edit', function (string $hookName, array $args) {
/** @var Galley $newGalley */
$newGalley = $args[0];
/** @var Galley $oldGalley */
$oldGalley = $args[1];
// Skip edits that don't change anything the webhook payload (or a reader) cares
// about - a drag-and-drop reorder in the galley grid, for instance, only changes
// `seq` and would otherwise queue a pointless "updated" webhook on every reorder.
if (!$this->galleyContentChanged($oldGalley, $newGalley)) {
return;
}
$this->handleGalleyChanged($newGalley->getData('publicationId'));
});
Hook::add('SubmissionFile::edit', function (string $hookName, array $args) {
/** @var SubmissionFile $newSubmissionFile */
$newSubmissionFile = $args[0];
/** @var SubmissionFile $oldSubmissionFile */
$oldSubmissionFile = $args[1];
// Replacing a galley's PDF via the galley grid's "Upload file" action uploads a new
// *revision* of the galley's existing submission file: only its `fileId` changes, the
// galley keeps pointing at the same submissionFileId, so Galley::edit never fires.
// MetadataChanged only follows if the editor also completes the upload wizard's
// metadata step - catch the replacement here instead.
if (
$newSubmissionFile->getData('assocType') !== Application::ASSOC_TYPE_REPRESENTATION
|| (int) $newSubmissionFile->getData('fileId') === (int) $oldSubmissionFile->getData('fileId')
) {
return;
}
$galley = Repo::galley()->get((int) $newSubmissionFile->getData('assocId'));
if (!$galley || (int) $galley->getData('submissionFileId') !== (int) $newSubmissionFile->getId()) {
return;
}
$this->handleGalleyChanged($galley->getData('publicationId'));
});
Hook::add('Publication::validatePublish', function (string $hookName, array $args) {
$errors = & $args[0];
/** @var Publication $publication */
$publication = $args[1];
/** @var Submission $submission */
$submission = $args[2];
$contextId = $submission->getData('contextId');
if (!$this->getEnabled($contextId) || !$this->getSetting($contextId, 'requireDoiBeforePublish')) {
return Hook::CONTINUE;
}
if (!$publication->getData('doiId')) {
$errors['webhookDoi'] = [__('plugins.generic.webhook.validatePublish.missingDoi')];
}
return Hook::CONTINUE;
});
Hook::add('Form::config::before', function (string $hookName, FormComponent $form) {
if ($form->id !== 'publicationIdentifiers' || !$this->getEnabled()) {
return;
}
$status = WebhookStatus::get($form->publication->getId());
if (!$status) {
return;
}
$form->addField(new FieldHTML('webhookStatus', [
'label' => __('plugins.generic.webhook.status.label'),
'description' => $this->formatStatusHtml($status),
]));
});
}
return true;
}
/**
* Render the last recorded webhook status as the description of a
* read-only FieldHTML on the Publication tab's "Identifiers" form.
*/
protected function formatStatusHtml(array $status): string
{
$lines = [$status['success']
? __('plugins.generic.webhook.status.sent', ['event' => $status['event'], 'date' => $status['sentAt']])
: __('plugins.generic.webhook.status.failed', ['event' => $status['event'], 'date' => $status['sentAt']])];
if ($status['zsId']) {
$lines[] = __('plugins.generic.webhook.status.zsId', ['id' => $status['zsId']]);
}
$warnings = WebhookStatusFormatter::normalizeWarnings($status['warnings'] ?? []);
if ($warnings) {
$lines[] = __('plugins.generic.webhook.status.warnings');
foreach ($warnings as $warning) {
$localeKey = WebhookStatusFormatter::localeKeyForCode($warning['code']);
$label = $localeKey ? __($localeKey) : $warning['code'];
$lines[] = $warning['detail']
? __('plugins.generic.webhook.status.warning', ['label' => $label, 'detail' => $warning['detail']])
: __('plugins.generic.webhook.status.warning.noDetail', ['label' => $label]);
}
}
if ($status['error']) {
$lines[] = __('plugins.generic.webhook.status.error', ['error' => $status['error']]);
}
return implode('<br>', array_map('htmlspecialchars', $lines));
}
/**
* Re-dispatch the webhook for a submission's current publication, using
* whatever event was last sent for it (defaulting to "updated" if it was
* never sent before). Used by the "resend" action in the plugin grid.
*
* Returns false if the submission/publication could not be found, or if
* no valid webhook URL is configured - the resend action is shown
* regardless of whether the plugin has been configured yet, so this must
* be checked here rather than assumed.
*/
public function resendWebhook(int $submissionId): bool
{
$submission = Repo::submission()->get($submissionId);
if (!$submission || $submission->getData('contextId') !== $this->getCurrentContextId()) {
return false;
}
$publication = $submission->getCurrentPublication();
if (!$publication) {
return false;
}
$status = WebhookStatus::get($publication->getId());
$event = $status['event'] ?? 'updated';
// The last recorded event may no longer match the publication's state (e.g. "production"
// for an article published since, or "published" after it was unpublished but that
// webhook failed). SendWebhookJob would silently drop such a job as stale, so send the
// event matching the current state instead.
$isPublished = $publication->getData('status') === PKPSubmission::STATUS_PUBLISHED;
if (WebhookEventGuard::isStale($event, $isPublished, $event)) {
$event = $isPublished ? 'published' : 'unpublished';
}
// An explicit manual action - deliberately gated only on a URL being configured, not on
// the plugin being enabled (unlike the automatic listeners, see dispatchWebhook()).
return $this->queueWebhookJob($event, $submission->getData('contextId'), $submissionId, $publication->getId());
}
/**
* Whether a galley edit touched a field the webhook payload (or a reader) actually cares
* about: its file, its label, its locale, or a remote URL it points to instead of a file.
* Deliberately excludes `seq` and other purely cosmetic/grid-internal fields.
*/
protected function galleyContentChanged(Galley $old, Galley $new): bool
{
foreach (['label', 'locale', 'submissionFileId', 'urlRemote'] as $field) {
if ($old->getData($field) !== $new->getData($field)) {
return true;
}
}
return false;
}
/**
* React to a galley being added or edited directly on the Fahnen/galley form, which (unlike
* the upload wizard's PKPManageFileApiHandler::saveMetadata()) does not fire MetadataChanged.
* Without this, a corrected galley (e.g. a replaced PDF) on an already-published publication
* never reaches the Zeitschriftenserver.
*
* Sends the same "updated" webhook as MetadataChanged, under the same condition: only once the
* publication is actually published, and only if it was already accepted by the
* Zeitschriftenserver at least once before (a zsId on record).
*/
protected function handleGalleyChanged(?int $publicationId): void
{
if (!$publicationId) {
return;
}
$publication = Repo::publication()->get($publicationId);
if (!$publication || $publication->getData('status') !== PKPSubmission::STATUS_PUBLISHED) {
return;
}
$submission = Repo::submission()->get($publication->getData('submissionId'));
if (!$submission) {
return;
}
$status = WebhookStatus::get($publicationId);
if (!$status || !$status['zsId']) {
return;
}
$this->dispatchWebhook('updated', $submission->getData('contextId'), $submission->getId(), $publicationId);
}
/**
* Queue a webhook notification for an editorial event, if the plugin is enabled for the
* submission's journal. Checked per journal rather than once at register() time: the CLI
* scheduler registers plugins without any context, and a single request (e.g. the
* scheduled-task runner) can publish submissions of several journals, not all of which
* necessarily have this plugin enabled.
*/
protected function dispatchWebhook(string $event, int $contextId, int $submissionId, int $publicationId): bool
{
if (!$this->getEnabled($contextId)) {
return false;
}
return $this->queueWebhookJob($event, $contextId, $submissionId, $publicationId);
}
/**
* Queue a webhook notification for an asynchronous send, if a webhook URL is
* configured. Returns whether a job was actually queued.
*/
protected function queueWebhookJob(string $event, int $contextId, int $submissionId, int $publicationId): bool
{
if (!$this->hasValidWebhookConfig($contextId)) {
return false;
}
$webhookUrl = $this->getSetting($contextId, 'webhookUrl');
$webhookSecret = $this->getSetting($contextId, 'webhookSecret');
SendWebhookJob::dispatch($event, $submissionId, $publicationId, $webhookUrl, $webhookSecret ?: null, $this->getPluginVersionString());
return true;
}
/**
* The installed version of this plugin, for the User-Agent header
* (SendWebhookJob has no access to the plugin instance itself, since it
* runs out of process on the job queue).
*/
protected function getPluginVersionString(): string
{
$version = $this->getCurrentVersion();
return $version ? $version->getVersionString() : 'unknown';
}
/**
* Whether a syntactically valid webhook URL is configured for the given context
* (or the current context/site if none is given).
*/
protected function hasValidWebhookConfig(?int $contextId = null): bool
{
if ($contextId === null) {
$contextId = $this->getCurrentContextId();
}
return WebhookUrlValidator::isValid($this->getSetting($contextId, 'webhookUrl'));
}
/**
* Whether the current journal's DOI settings match what the receiving end expects:
* DOIs enabled for publications, assigned manually (so the DOI returned by the
* webhook response can be recorded), and never auto-generated by OJS itself.
*/
protected function hasRecommendedDoiConfig(): bool
{
$context = Application::get()->getRequest()->getContext();
if (!$context) {
return true;
}
if (!$context->isDoiTypeEnabled(Repo::doi()::TYPE_PUBLICATION)) {
return false;
}
return $context->getData(Context::SETTING_DOI_SUFFIX_TYPE) === Repo::doi()::SUFFIX_MANUAL
&& $context->getData(Context::SETTING_DOI_CREATION_TIME) === Repo::doi()::CREATION_TIME_NEVER;
}
/**
* @copydoc Plugin::getCanEnable()
*/
public function getCanEnable()
{
return $this->hasValidWebhookConfig();
}
/**
* @copydoc Plugin::getInstallMigration()
*/
public function getInstallMigration()
{
return new WebhookStatusMigration();
}
/**
* @copydoc Plugin::getActions()
*/
public function getActions($request, $actionArgs)
{
$actions = parent::getActions($request, $actionArgs);
$router = $request->getRouter();
$resendAction = new LinkAction(
'resend',
new AjaxModal(
$router->url(
$request,
null,
null,
'manage',
null,
[
'verb' => 'resend',
'plugin' => $this->getName(),
'category' => 'generic',
]
),
__('plugins.generic.webhook.linkAction.resend')
),
__('plugins.generic.webhook.linkAction.resend'),
null
);
$settingsAction = 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
);
array_unshift($actions, $resendAction);
array_unshift($actions, $settingsAction);
return $actions;
}
/**
* @copydoc Plugin::manage()
*/
public function manage($args, $request)
{
switch ($request->getUserVar('verb')) {
case 'settings':
$form = new WebhookSettingsForm($this);
if ($request->getUserVar('save')) {
$form->readInputData();
if ($form->validate()) {
$form->execute();
return new JSONMessage(true);
}
}
$form->initData();
return new JSONMessage(true, $form->fetch($request));
case 'resend':
$form = new WebhookResendForm($this);
if ($request->getUserVar('resend')) {
$form->readInputData();
if ($form->validate()) {
$form->execute();
return new JSONMessage(true);
}
}
$form->initData();
return new JSONMessage(true, $form->fetch($request));
}
return parent::manage($args, $request);
}
}