-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCustomMetadataPlugin.php
More file actions
233 lines (217 loc) · 7.81 KB
/
Copy pathCustomMetadataPlugin.php
File metadata and controls
233 lines (217 loc) · 7.81 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
<?php
/**
* @file CustomMetadataPlugin.php
*
* Plugin de metadados personalizados para OMP 3.5.
*
* Permite cadastrar campos de metadados simples (sem validacao) que aparecem
* na aba "Metadados" da publicacao e ficam disponiveis no tema via
* $publication->getData('chave') ou $publication->getLocalizedData('chave').
*
* @class CustomMetadataPlugin
*/
namespace APP\plugins\generic\customMetadata;
use APP\core\Application;
use APP\plugins\generic\customMetadata\classes\CustomMetadataSettingsForm;
use PKP\components\forms\FieldText;
use PKP\components\forms\FieldTextarea;
use PKP\components\forms\publication\PKPMetadataForm;
use PKP\core\JSONMessage;
use PKP\linkAction\LinkAction;
use PKP\linkAction\request\AjaxModal;
use PKP\plugins\GenericPlugin;
use PKP\plugins\Hook;
class CustomMetadataPlugin extends GenericPlugin
{
/**
* @copydoc Plugin::register()
*/
public function register($category, $path, $mainContextId = null)
{
$success = parent::register($category, $path, $mainContextId);
if (Application::isUnderMaintenance()) {
return $success;
}
if (!$success) {
return $success;
}
// OMP 3.5 (PKP #11793): SEMPRE registrar os hooks; o check de getEnabled()
// vai dentro dos callbacks. Isso garante que o schema da publicacao seja
// estendido em todo request (display, save, API) para que o save via
// SchemaDAO nao descarte silenciosamente os campos personalizados.
Hook::add('Schema::get::publication', [$this, 'addToSchema']);
Hook::add('Form::config::before', [$this, 'addToForm']);
return $success;
}
/**
* @copydoc Plugin::getDisplayName()
*/
public function getDisplayName()
{
return __('plugins.generic.customMetadata.displayName');
}
/**
* @copydoc Plugin::getDescription()
*/
public function getDescription()
{
return __('plugins.generic.customMetadata.description');
}
/**
* Le e normaliza a definicao dos campos personalizados configurada pelo usuario.
*
* Formato esperado (um campo por linha):
* chave | Rotulo exibido | tipo | multilingue
*
* - chave: somente letras, numeros e underscore (usada em getData()).
* - tipo: "text" (padrao) ou "textarea".
* - multilingue: 1/sim/true para multilingue; vazio ou 0 para monolingue.
*
* @return array<int,array{key:string,label:string,type:string,multilingual:bool}>
*/
public function getCustomFields(): array
{
$raw = (string) $this->getSetting($this->resolveContextId(), 'customFieldsDefinition');
$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 === '') {
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,
'label' => ($parts[1] ?? '') !== '' ? $parts[1] : $key,
'type' => $type,
'multilingual' => $multilingual,
];
}
return $fields;
}
/**
* Adiciona cada campo personalizado como propriedade do schema da publicacao,
* sem regras de validacao (apenas nullable), para que sejam salvos em
* publication_settings e recuperaveis via getData().
*
* Disparado por Hook::call('Schema::get::publication', [&$schema]),
* portanto o segundo argumento chega como array.
*/
public function addToSchema(string $hookName, array $params): bool
{
$schema = $params[0];
foreach ($this->getCustomFields() as $field) {
// Nao sobrescreve propriedades nativas ja existentes no schema.
if (isset($schema->properties->{$field['key']})) {
continue;
}
$prop = (object) [
'type' => 'string',
'apiSummary' => true,
'validation' => ['nullable'],
];
if ($field['multilingual']) {
$prop->multilingual = true;
}
$schema->properties->{$field['key']} = $prop;
}
return Hook::CONTINUE;
}
/**
* Adiciona os campos personalizados ao formulario de metadados da publicacao.
*
* Disparado por Hook::run('Form::config::before', [$form]),
* portanto o segundo argumento chega como o proprio objeto do formulario.
*/
public function addToForm(string $hookName, $form): bool
{
if (!$form instanceof PKPMetadataForm) {
return Hook::CONTINUE;
}
// OMP 3.5 (#11793): os hooks sao sempre registrados; o campo visual so
// aparece quando o plugin esta habilitado no contexto (press) atual.
if (!$this->getEnabled()) {
return Hook::CONTINUE;
}
$publication = $form->publication;
foreach ($this->getCustomFields() as $field) {
$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;
}
/**
* @copydoc Plugin::getActions()
*/
public function getActions($request, $actionArgs)
{
$actions = parent::getActions($request, $actionArgs);
if (!$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;
}
/**
* @copydoc Plugin::manage()
*/
public function manage($args, $request)
{
switch ($request->getUserVar('verb')) {
case 'settings':
$form = new CustomMetadataSettingsForm($this);
if ($request->getUserVar('save')) {
$form->readInputData();
if ($form->validate()) {
$form->execute();
return new JSONMessage(true);
}
} else {
$form->initData();
}
return new JSONMessage(true, $form->fetch($request));
}
return parent::manage($args, $request);
}
/**
* Retorna o id do contexto (press) atual, com fallback para o contexto do site.
*/
protected function resolveContextId(): int
{
$context = Application::get()->getRequest()->getContext();
return $context ? $context->getId() : Application::SITE_CONTEXT_ID;
}
}
if (!PKP_STRICT_MODE) {
class_alias('\APP\plugins\generic\customMetadata\CustomMetadataPlugin', '\CustomMetadataPlugin');
}