Repository navigation
Expand file tree
/
Copy pathCustomMetadataPlugin.php
More file actions
420 lines (391 loc) · 15.8 KB
/
Copy pathCustomMetadataPlugin.php
File metadata and controls
420 lines (391 loc) · 15.8 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
<?php
/**
* @file plugins/generic/customMetadata/CustomMetadataPlugin.php
*
* Copyright (c) 2026 OJSBR (https://ojsbr.com)
* Distributed under the GNU GPL v3. For full terms see the file docs/COPYING.
*
* @class CustomMetadataPlugin
*
* @brief Simple extra metadata fields (no validation) on the publication
* Metadata tab of OJS and OMP, available in the theme through
* $publication->getData('key') or $publication->getLocalizedData('key').
* Each field is editable by everyone who can edit the publication, or by
* the editors only.
*/
namespace APP\plugins\generic\customMetadata;
use APP\core\Application;
use APP\facades\Repo;
use APP\plugins\generic\customMetadata\classes\CustomMetadataSettingsForm;
use PKP\components\forms\FieldHTML;
use PKP\components\forms\FieldText;
use PKP\components\forms\FieldTextarea;
use PKP\components\forms\publication\PKPMetadataForm;
use PKP\components\forms\submission\ForTheEditors;
use PKP\core\JSONMessage;
use PKP\linkAction\LinkAction;
use PKP\linkAction\request\AjaxModal;
use PKP\plugins\GenericPlugin;
use PKP\plugins\Hook;
use PKP\publication\PKPPublication;
use PKP\security\Role;
use PKP\services\PKPSchemaService;
use PKP\stageAssignment\StageAssignment;
use PKP\user\User;
class CustomMetadataPlugin extends GenericPlugin
{
/** Values of the fifth column that keep a field for the editors. */
public const EDITORS_ONLY = ['editor', 'editors', 'editores', 'editoras'];
/** @var string[] Keys this plugin added to the publication schema in this request */
protected $schemaKeys = [];
/**
* Register the plugin and its hooks.
*
* @param string $category
* @param string $path
* @param null|int $mainContextId
*/
public function register($category, $path, $mainContextId = null): bool
{
$success = parent::register($category, $path, $mainContextId);
if (!$success || Application::isUnderMaintenance()) {
return $success;
}
// The hooks are always registered and each callback checks whether the plugin is
// enabled (pkp/pkp-lib#11793): the publication schema must be extended on every
// request (display, save, API), or saving a publication silently drops the
// custom fields of a context where the plugin is off.
Hook::add('Schema::get::publication', $this->addToSchema(...));
Hook::add('Form::config::before', $this->addToForm(...));
Hook::add('Publication::validate', $this->validateEditorsOnly(...));
return $success;
}
/**
* Name shown in the plugins list.
*/
public function getDisplayName(): string
{
return __('plugins.generic.customMetadata.displayName');
}
/**
* Description shown in the plugins list.
*/
public function getDescription(): string
{
return __('plugins.generic.customMetadata.description');
}
/**
* Read and normalize the field definitions configured for the context.
*
* One field per line:
* key | Label | type | multilingual | who edits
*
* - key: letters, numbers and underscore only (the name used in getData()).
* - type: "text" (default) or "textarea".
* - multilingual: 1/yes/true (or sim/s) for a multilingual field; empty or 0 otherwise.
* - who edits: "editors" (or "editores") keeps the field for the editors; empty or
* anything else lets the authors edit it too.
*
* @return array<int,array{key:string,label:string,type:string,multilingual:bool,editorsOnly:bool}>
*/
public function getCustomFields(): array
{
return $this->parseDefinition((string) $this->getSetting($this->resolveContextId(), 'customFieldsDefinition'));
}
/**
* Parse a field definition text.
*
* @return array<int,array{key:string,label:string,type:string,multilingual:bool,editorsOnly:bool}>
*/
public function parseDefinition(string $raw): array
{
$fields = [];
foreach (preg_split('/\r\n|\r|\n/', $raw) as $line) {
$line = trim($line);
if ($line === '' || str_starts_with($line, '#')) {
continue;
}
$parts = array_map('trim', explode('|', $line));
$key = preg_replace('/[^A-Za-z0-9_]/', '', $parts[0] ?? '');
if ($key === '' || isset($fields[$key])) {
continue;
}
$type = (isset($parts[2]) && strtolower($parts[2]) === 'textarea') ? 'textarea' : 'text';
$multilingual = isset($parts[3]) && in_array(strtolower($parts[3]), ['1', 'sim', 'true', 'yes', 'y', 's']);
$fields[$key] = [
'key' => $key,
'label' => ($parts[1] ?? '') !== '' ? $parts[1] : $key,
'type' => $type,
'multilingual' => $multilingual,
'editorsOnly' => isset($parts[4]) && in_array(mb_strtolower($parts[4]), self::EDITORS_ONLY, true),
];
}
return array_values($fields);
}
/**
* Add each custom field to the publication schema, with no validation rule
* besides nullable, so it is saved in publication_settings and read back
* with getData().
*
* Called by Hook::call('Schema::get::publication', [&$schema]).
*/
public function addToSchema($hookName, $params): bool
{
$schema = $params[0];
foreach ($this->getCustomFields() as $field) {
// Never replace a property the schema already has.
if (isset($schema->properties->{$field['key']})) {
continue;
}
$this->schemaKeys[] = $field['key'];
$prop = (object) [
'type' => 'string',
'apiSummary' => true,
'validation' => ['nullable'],
];
if ($field['multilingual']) {
$prop->multilingual = true;
}
$schema->properties->{$field['key']} = $prop;
}
return Hook::CONTINUE;
}
/**
* Add the custom fields to the publication metadata form, and to the "For the
* Editors" step of the submission wizard, which extends it.
*
* A field kept for the editors is shown to anybody else as read-only text on the
* Metadata tab, and left out of the submission wizard. The wizard uses this form only
* when the context asks the authors for other metadata in it: it counts the fields
* before this hook adds any.
*
* Called by Hook::run('Form::config::before', [$form]), so the second
* argument is the form itself.
*/
public function addToForm($hookName, $form): bool
{
if (!$form instanceof PKPMetadataForm) {
return Hook::CONTINUE;
}
$publication = $form->publication;
$contextId = $form->context->getId();
if (!$this->getEnabled($contextId)) {
return Hook::CONTINUE;
}
// A key that names a property of the core or of another plugin is not
// shown: the field would replace that property's value on save.
app()->get('schema')->get(PKPSchemaService::SCHEMA_PUBLICATION);
$isEditor = null;
foreach ($this->getCustomFields() as $field) {
if (!in_array($field['key'], $this->schemaKeys, true)) {
continue;
}
if ($field['editorsOnly']) {
$isEditor ??= $this->isEditor(Application::get()->getRequest()->getUser(), (int) $publication->getData('submissionId'), $contextId);
if (!$isEditor) {
if (!$form instanceof ForTheEditors) {
$form->addField(new FieldHTML($field['key'], [
'label' => $field['label'],
'description' => $this->readOnlyValue($field, $publication, $form->locales),
]));
}
continue;
}
}
$options = [
'label' => $field['label'],
'isMultilingual' => $field['multilingual'],
'value' => $publication->getData($field['key']),
];
if ($field['multilingual']) {
$options['locales'] = $form->locales;
}
if ($field['type'] === 'textarea') {
$form->addField(new FieldTextarea($field['key'], $options));
} else {
$form->addField(new FieldText($field['key'], $options));
}
}
return Hook::CONTINUE;
}
/**
* Refuse a change to a field kept for the editors when it comes from somebody
* else. Hiding the field is not enough: the publication API accepts any key of the
* schema from whoever may edit the publication.
*
* Called by Hook::call('Publication::validate', [&$errors, $publication, $props, $allowedLocales, $primaryLocale]).
*/
public function validateEditorsOnly($hookName, $args): bool
{
$errors = &$args[0];
$publication = $args[1];
$props = $args[2];
if (!$publication instanceof PKPPublication) {
return Hook::CONTINUE;
}
$user = Application::get()->getRequest()->getUser();
// Without a user it is the system at work (command line, jobs, imports).
if (!$user) {
return Hook::CONTINUE;
}
$submission = Repo::submission()->get((int) $publication->getData('submissionId'));
if (!$submission || !$this->getEnabled($submission->getData('contextId'))) {
return Hook::CONTINUE;
}
$changed = self::changedEditorsOnlyKeys($this->getCustomFields(), $props, $publication);
if ($changed && !$this->isEditor($user, $submission->getId(), $submission->getData('contextId'))) {
foreach ($changed as $key) {
$errors[$key][] = __('plugins.generic.customMetadata.editorsOnly');
}
}
return Hook::CONTINUE;
}
/**
* The keys of the fields kept for the editors whose value the props change.
*
* A form that sends a field back unchanged changes nothing, and an empty string is
* the same as no value.
*
* @param array<int,array{key:string,multilingual:bool,editorsOnly:bool}> $fields
*
* @return string[]
*/
public static function changedEditorsOnlyKeys(array $fields, array $props, object $publication): array
{
$changed = [];
foreach ($fields as $field) {
$key = $field['key'];
if (!$field['editorsOnly'] || !array_key_exists($key, $props)) {
continue;
}
$new = $props[$key];
if ($field['multilingual'] && is_array($new)) {
foreach ($new as $locale => $value) {
if (self::normalize($value) !== self::normalize($publication->getData($key, $locale))) {
$changed[] = $key;
break;
}
}
} elseif (self::normalize($new) !== self::normalize($publication->getData($key))) {
$changed[] = $key;
}
}
return $changed;
}
/**
* A value as it is compared: null and blank are the same.
*/
protected static function normalize(mixed $value): mixed
{
if (is_array($value)) {
$value = array_filter(array_map(self::normalize(...), $value), fn ($v) => $v !== null);
ksort($value);
return $value ?: null;
}
if ($value === null || (is_string($value) && trim($value) === '')) {
return null;
}
return (string) $value;
}
/**
* Whether the user edits the fields kept for the editors of a submission: a site
* administrator, a manager of the context, or somebody assigned to the submission
* in a role other than author. The same line the core draws between the editors
* and the authors for a published publication (Repository::canEditPublication()).
*/
public function isEditor(?User $user, int $submissionId, int $contextId): bool
{
if (!$user) {
return false;
}
if ($user->hasRole([Role::ROLE_ID_SITE_ADMIN], Application::SITE_CONTEXT_ID)
|| $user->hasRole(Repo::userGroup()::NOT_CHANGE_METADATA_EDIT_PERMISSION_ROLES, $contextId)) {
return true;
}
return StageAssignment::withSubmissionIds([$submissionId])
->withUserId($user->getId())
->get()
->contains(fn (StageAssignment $assignment) => $assignment->userGroup && $assignment->userGroup->roleId != Role::ROLE_ID_AUTHOR);
}
/**
* The value of a field as read-only HTML, with every language of the form for a
* multilingual field.
*
* @param array{key:string,type:string,multilingual:bool} $field
*/
protected function readOnlyValue(array $field, object $publication, array $locales): string
{
$format = fn ($value) => nl2br(htmlspecialchars((string) $value, ENT_QUOTES, 'UTF-8'), false);
$lines = [];
if ($field['multilingual']) {
foreach ($locales as $locale) {
$value = $publication->getData($field['key'], $locale['key']);
if (self::normalize($value) !== null) {
$lines[] = '<strong>' . htmlspecialchars($locale['label'], ENT_QUOTES, 'UTF-8') . ':</strong> ' . $format($value);
}
}
} elseif (self::normalize($publication->getData($field['key'])) !== null) {
$lines[] = $format($publication->getData($field['key']));
}
$value = $lines ? implode('<br>', $lines) : '—';
return '<p>' . $value . '</p><p><em>' . htmlspecialchars(__('plugins.generic.customMetadata.editorsOnly'), ENT_QUOTES, 'UTF-8') . '</em></p>';
}
/**
* Add the settings action to the plugin entry in the plugins list.
*/
public function getActions($request, $actionArgs): array
{
$actions = parent::getActions($request, $actionArgs);
if (!$request->getContext() || !$this->getEnabled()) {
return $actions;
}
$router = $request->getRouter();
$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, $settingsAction);
return $actions;
}
/**
* Show and save the settings form.
*/
public function manage($args, $request): JSONMessage
{
// The settings belong to a journal or press; there is nothing to configure site-wide.
$context = $request->getContext();
if ($request->getUserVar('verb') !== 'settings' || !$context) {
return parent::manage($args, $request);
}
$form = new CustomMetadataSettingsForm($this, (int) $context->getId());
if (!$request->getUserVar('save')) {
$form->initData();
return new JSONMessage(true, $form->fetch($request));
}
$form->readInputData();
if (!$form->validate()) {
return new JSONMessage(true, $form->fetch($request));
}
$form->execute();
return new JSONMessage(true);
}
/**
* The id of the current context, or the site context without one.
*/
protected function resolveContextId(): ?int
{
return Application::get()->getRequest()->getContext()?->getId() ?? Application::SITE_CONTEXT_ID;
}
}
if (!PKP_STRICT_MODE) {
class_alias('\APP\plugins\generic\customMetadata\CustomMetadataPlugin', '\CustomMetadataPlugin');
}