-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathCodecheckPlugin.php
More file actions
490 lines (417 loc) · 18.7 KB
/
Copy pathCodecheckPlugin.php
File metadata and controls
490 lines (417 loc) · 18.7 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
<?php
namespace APP\plugins\generic\codecheck;
use PKP\security\Role;
use APP\core\Application;
use APP\template\TemplateManager;
use APP\plugins\generic\codecheck\classes\FrontEnd\ArticleDetails;
use APP\plugins\generic\codecheck\classes\Settings\Actions;
use APP\plugins\generic\codecheck\classes\Settings\Manage;
use APP\plugins\generic\codecheck\classes\migration\CodecheckSchemaMigration;
use APP\plugins\generic\codecheck\classes\Submission\Schema;
use APP\plugins\generic\codecheck\classes\Submission\SubmissionWizardHandler;
use APP\plugins\generic\codecheck\classes\Log\CodecheckLogger;
use PKP\plugins\GenericPlugin;
use PKP\plugins\Hook;
use PKP\components\forms\FieldOptions;
use APP\facades\Repo;
use APP\plugins\generic\codecheck\api\v1\CodecheckApiHandler;
use APP\plugins\generic\codecheck\api\v1\CurlApiClient;
use PKP\core\JSONMessage;
use APP\plugins\generic\codecheck\classes\Constants;
use APP\plugins\generic\codecheck\classes\Workflow\CodecheckStatusHandler;
use APP\plugins\generic\codecheck\controllers\page\CodecheckPageHandler;
use APP\plugins\generic\codecheck\classes\CodecheckRoles\CodecheckRoleArray;
use APP\plugins\generic\codecheck\classes\CodecheckRoles\CodecheckRoleManager;
use APP\plugins\generic\codecheck\classes\Workflow\CodecheckMetadataHandler;
use PKP\core\Request;
use \Github\Client;
class CodecheckPlugin extends GenericPlugin
{
private CodecheckSchemaMigration $migration;
public function register($category, $path, $mainContextId = null): bool
{
CodecheckLogger::debug('register() called, path=' . $path);
$success = parent::register($category, $path);
if ($success && $this->getEnabled()) {
$this->addAssets();
$articleDetails = new ArticleDetails($this);
$issueTOC = new \APP\plugins\generic\codecheck\classes\FrontEnd\IssueTOC($this);
Hook::add('Templates::Issue::Issue::Article', $issueTOC->addCodecheckBadge(...));
Hook::add('Templates::Article::Details', $articleDetails->addCodecheckInfo(...));
// Opt-in checkbox on submission start
Hook::add('Schema::get::submission', $this->addOptInToSchema(...));
Hook::add('Form::config::before', $this->addOptInCheckbox(...));
Hook::add('Submission::edit', $this->saveOptIn(...));
Hook::add('Submission::validate', $this->saveWizardFieldsFromRequest(...));
// Add hook for Ajax API calls
Hook::add('Dispatcher::dispatch', [$this, 'setupAPIHandler']);
// Add hook for the custom CODECHECK Pages
Hook::add('LoadHandler', $this->setCodecheckPageHandler(...));
// Add hook for the Template Manager
Hook::add('TemplateManager::display', $this->callbackTemplateManagerDisplay(...));
// Wizard fields schema
$codecheckSchema = new Schema();
Hook::add('Schema::get::publication', function($hookName, $args) use ($codecheckSchema) {
return $codecheckSchema->addToSchemaPublication($hookName, $args);
});
// Wizard template handlers
$codecheckWizard = new SubmissionWizardHandler($this);
Hook::add('TemplateManager::display', function($hookName, $params) use ($codecheckWizard) {
return $codecheckWizard->addToSubmissionWizardSteps($hookName, $params);
});
Hook::add('Template::SubmissionWizard::Section', function($hookName, $params) use ($codecheckWizard) {
return $codecheckWizard->addToSubmissionWizardTemplate($hookName, $params);
});
Hook::add('Template::SubmissionWizard::Section::Review', function($hookName, $params) use ($codecheckWizard) {
return $codecheckWizard->addToSubmissionWizardReviewTemplate($hookName, $params);
});
// Test if we can hook into the publication to block it if codecheck failed
Hook::add('Publication::validatePublish', $this->validateCodecheckStatus(...));
// Add Localizations to Codecheck Status Preview
Hook::add('TemplateManager::display', $this->addCodecheckStatusLocalizations(...));
}
return $success;
}
public function validateCodecheckStatus(string $hookName, array $args): bool
{
$errors = &$args[0];
$publication = $args[1]; // sometimes passed by reference depending on version
$request = Application::get()->getRequest();
$context = $request->getContext();
$codecheckMetadataHandler = new CodecheckMetadataHandler($request, new Client(), new CurlApiClient());
$codecheckStatus = CodecheckStatusHandler::getCurrentStatusData($codecheckMetadataHandler->getSubmissionId());
CodecheckLogger::debug("Validating CODECHECK before publication!");
$codecheckStatusKeysSelected = $this->getSetting($context->getId(), Constants::CODECHECK_STATUS_KEYS_SELECTED);
if (empty($codecheckStatus)) {
$errors[] = __('plugins.generic.codecheck.status.validation.failed.noStatusSet');
return false;
}
if (!in_array($codecheckStatus->status, $codecheckStatusKeysSelected)) {
$errors[] = __('plugins.generic.codecheck.status.validation.failed', [
'codecheckStatus' => __($codecheckStatus->status)
]);
return false;
}
return true;
}
public function addCodecheckStatusLocalizations($hookName, $args) {
$templateMgr = $args[0];
$templateMgr->addJavaScript(
'codecheck-locale-status',
'pkp.localeKeys = pkp.localeKeys || {};' .
'Object.assign(pkp.localeKeys, ' . json_encode(
array_combine(
Constants::CODECHECK_STATUSES,
array_map(fn($status) => __($status), Constants::CODECHECK_STATUSES)
)
) . ');',
['inline' => true, 'contexts' => ['backend']]
);
return false;
}
/**
* Setup the `CodecheckApiHandler`
*
* @param string $hookname The name of the hook
* @param array $args The arguments passed by the hook
*
* @return void
*/
public function setupAPIHandler(string $hookName, array $args): void
{
$request = $args[0];
$router = $request->getRouter();
if (!($router instanceof \PKP\core\APIRouter)) {
return;
}
if (str_contains($request->getRequestPath(), 'api/v1/codecheck')) {
CodecheckLogger::debug('Instantiating the CODECHECK APIHandler');
$adminRoles = new CodecheckRoleArray([Role::ROLE_ID_MANAGER, Role::ROLE_ID_SITE_ADMIN]);
$editRoles = new CodecheckRoleArray([$adminRoles, Role::ROLE_ID_SUB_EDITOR, Role::ROLE_ID_ASSISTANT, Role::ROLE_ID_MANAGER]);
$readRoles = new CodecheckRoleArray([$editRoles, Role::ROLE_ID_READER, Role::ROLE_ID_AUTHOR]);
$roles = new CodecheckRoleManager(
readMetadata: $readRoles,
editMetadata: $editRoles,
admin: $adminRoles,
);
$apiHandler = new CodecheckApiHandler($this, $request, $roles);
CodecheckLogger::debug('API request: ' . $request->getRequestPath());
}
if (!isset($apiHandler)) {
return;
}
$router->setHandler($apiHandler);
exit;
}
/**
* Declare the handler function to process the actual page PATH
*
* @param string $hookName The name of the invoked hook
* @param array $args Hook parameters
*
* @return bool Hook handling status
*/
public function setCodecheckPageHandler($hookName, $args)
{
$request = Application::get()->getRequest();
$templateMgr = TemplateManager::getManager($request);
$page = &$args[0];
$op = &$args[1];
$handler = &$args[3];
// Construct a path to look for
$path = $page;
if ($op !== 'index') {
$path .= "/{$op}";
}
if ($ops = $request->getRequestedArgs()) {
$path .= '/' . implode('/', $ops);
}
// Check if this is a request for a static page or preview.
if ($page = 'codecheck' && $op == 'info') {
// Trick the handler into dealing with it normally
$page = 'pages';
$op = 'view';
// It is -- attach the static pages handler.
$handler = new CodecheckPageHandler($this);
return true;
}
return false;
}
private function addAssets(): void
{
$request = Application::get()->getRequest();
$templateMgr = TemplateManager::getManager($request);
$templateMgr->addJavaScript(
'codecheck-vue-app',
"{$request->getBaseUrl()}/{$this->getPluginPath()}/public/build/build.iife.js",
[
'inline' => false,
'contexts' => ['backend'],
'priority' => TemplateManager::STYLE_SEQUENCE_LAST
]
);
$templateMgr->addStyleSheet(
'codecheck-vue-styles',
"{$request->getBaseUrl()}/{$this->getPluginPath()}/public/build/build.css",
['contexts' => ['backend', 'frontend']]
);
$cssUrl = $request->getBaseUrl() . '/' . $this->getPluginPath() . '/css/codecheck.css';
$templateMgr->addStyleSheet(
'codecheck-styles',
$cssUrl,
['contexts' => ['backend', 'frontend']]
);
}
public function callbackTemplateManagerDisplay($hookName, $args): bool
{
$templateMgr = $args[0];
$request = Application::get()->getRequest();
$context = $request->getContext();
$contextId = $context->getId();
// ----------------------------------------------------------------
// Editorial dashboard — inject dashboard config for the Vue JS layer.
// Passes showDashboardColumn (Issue #30) and codecheckMode so the
// CODECHECK status column and opt-in warning box can be controlled.
// ----------------------------------------------------------------
if ($request->getRequestedOp() == 'editorial' && $request->getRequestedPage() == 'dashboard') {
$showDashboardColumn = $this->getSetting($contextId, Constants::CODECHECK_SHOW_DASHBOARD_COLUMN);
$dashboardConfig = json_encode([
'showDashboardColumn' => $showDashboardColumn === null ? true : (bool) $showDashboardColumn,
'codecheckMode' => $this->getSetting($contextId, Constants::CODECHECK_MODE) ?? 'opt-in',
]);
$templateMgr->addJavaScript(
'codecheck-dashboard-config',
'window.codecheckDashboardConfig = ' . $dashboardConfig . ';',
[
'inline' => true,
'contexts' => ['backend'],
'priority' => TemplateManager::STYLE_SEQUENCE_LAST,
]
);
}
// ----------------------------------------------------------------
// Workflow page — inject submission data for the CODECHECK tab
// ----------------------------------------------------------------
if ($request->getRequestedOp() == 'workflow') {
$submission = $request->getRouter()->getHandler()->getAuthorizedContextObject(ASSOC_TYPE_SUBMISSION);
if ($submission) {
$templateMgr->setState([
'codecheckSubmission' => [
'id' => $submission->getId(),
'codecheckOptIn' => $submission->getData('codecheckOptIn'),
'retrieveReserveCertificateIdentifier' => $submission->getData('retrieveReserveCertificateIdentifier'),
'codeRepository' => $submission->getData('codeRepository'),
'dataRepository' => $submission->getData('dataRepository'),
'manifestFiles' => $submission->getData('manifestFiles'),
'dataAvailabilityStatement' => $submission->getData('dataAvailabilityStatement'),
]
]);
}
}
return false;
}
public function getUrlPageRoute(string $page): string
{
$request = Application::get()->getRequest();
return $request->getDispatcher()->url(
$request,
ROUTE_PAGE,
null,
$page
);
}
public function addOptInToSchema(string $hookName, array $args): bool
{
$schema = $args[0];
$schema->properties->codecheckOptIn = (object) [
'type' => 'boolean',
'apiSummary' => true,
'validation' => ['nullable']
];
$schema->properties->retrieveReserveCertificateIdentifier = (object) [
'type' => 'string',
'apiSummary' => true,
'validation' => ['nullable']
];
return false;
}
public function addOptInCheckbox(string $hookName, \PKP\components\forms\FormComponent $form): bool
{
if ($form->id === 'submitStart' || $form->id === 'submissionStart' || str_contains($form->id, 'start')) {
$request = Application::get()->getRequest();
$context = $request->getContext();
$codecheckMode = $this->getSetting($context->getId(), Constants::CODECHECK_MODE);
CodecheckLogger::debug('Mode: ' . $codecheckMode);
$checkboxValue = false;
$codecheckMandatory = false;
$codecheckDescription = __('plugins.generic.codecheck.optIn.description', [
'codecheckLink' => "<a href='{$this->getUrlPageRoute("codecheck")}/info' target='_blank'>" . __('plugins.generic.codecheck.displayName') . "</a>"
]);
if($codecheckMode == 'opt-out') {
$checkboxValue = true;
} elseif ($codecheckMode == 'mandatory') {
$checkboxValue = true;
$codecheckMandatory = true;
$codecheckDescription = __('plugins.generic.codecheck.mandatory.description', [
'codecheckLink' => "<a href='{$this->getUrlPageRoute("codecheck")}/info' target='_blank'>" . __('plugins.generic.codecheck.displayName') . "</a>"
]);
}
$form->addField(new FieldOptions('codecheckOptIn', [
'label' => __('plugins.generic.codecheck.displayName'),
'isRequired' => $codecheckMandatory,
'type' => 'checkbox',
'options' => [
[
'value' => 1,
'label' => $codecheckDescription,
'disabled' => $codecheckMandatory,
]
],
'value' => $checkboxValue,
'groupId' => 'default'
]));
}
return false;
}
public function saveOptIn(string $hookName, array $params): bool
{
$submission = $params[0];
$params_array = $params[2];
if (isset($params_array['codecheckOptIn'])) {
$submission->setData('codecheckOptIn', $params_array['codecheckOptIn']);
}
return false;
}
public function saveWizardFieldsFromRequest(string $hookName, array $params): bool
{
$submission = $params[1];
if (!$submission) {
return false;
}
$request = Application::get()->getRequest();
$codeRepository = $request->getUserVar('codeRepository');
$dataRepository = $request->getUserVar('dataRepository');
$manifestFiles = $request->getUserVar('manifestFiles');
$dataAvailabilityStatement = $request->getUserVar('dataAvailabilityStatement');
if ($codeRepository || $dataRepository || $manifestFiles || $dataAvailabilityStatement) {
$publication = $submission->getCurrentPublication();
if ($publication) {
$updates = [];
if ($codeRepository) $updates['codeRepository'] = $codeRepository;
if ($dataRepository) $updates['dataRepository'] = $dataRepository;
if ($manifestFiles) $updates['manifestFiles'] = $manifestFiles;
if ($dataAvailabilityStatement) $updates['dataAvailabilityStatement'] = $dataAvailabilityStatement;
if (!empty($updates)) {
Repo::publication()->edit($publication, $updates);
}
}
}
return false;
}
/**
* Provide a name for this plugin
*
* The name will appear in the Plugin Gallery where editors can
* install, enable and disable plugins.
*/
public function getDisplayName(): string
{
return __('plugins.generic.codecheck.displayName');
}
/**
* Provide a description for this plugin
*
* The description will appear in the Plugin Gallery where editors can
* install, enable and disable plugins.
*/
public function getDescription(): string
{
return __('plugins.generic.codecheck.description');
}
/**
* Add a settings action to the plugin's entry in the CODECHECK plugins list.
*
* @param Request $request
* @param array $actionArgs
*/
public function getActions($request, $actionArgs): array
{
$actions = new Actions($this);
return $actions->execute($request, $actionArgs, parent::getActions($request, $actionArgs));
}
/**
* Load a form when the `settings` button is clicked and
* save the form when the user saves it.
*
* @param array $args
* @param Request $request
*/
public function manage($args, $request): JSONMessage
{
$manage = new Manage($this);
return $manage->execute($args, $request);
}
public function setEnabled($enabled, $contextId = null)
{
CodecheckLogger::debug("Plugin Enabled!");
$result = parent::setEnabled($enabled, $contextId);
if ($enabled) {
$this->migration = new CodecheckSchemaMigration();
$this->migration->up();
$this->migration->issueLabelsUp();
$this->migration->codecheckStatusUp();
}
return $result;
}
public function resetSchema(): void
{
$this->migration = new CodecheckSchemaMigration();
$this->migration->down();
$this->migration->up();
$this->migration->issueLabelsDown();
$this->migration->issueLabelsUp();
}
}
if (!PKP_STRICT_MODE) {
class_alias('\APP\plugins\generic\codecheck\CodecheckPlugin', '\CodecheckPlugin');
}