-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathNavMenuSyncPlugin.inc.php
More file actions
547 lines (472 loc) · 17.7 KB
/
NavMenuSyncPlugin.inc.php
File metadata and controls
547 lines (472 loc) · 17.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
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
541
542
543
544
545
546
547
<?php
/**
* @file NavMenuSyncPlugin.inc.php
*
* Copyright (c) 2024 OJS Services
* Distributed under the GNU GPL v3. For full terms see the file docs/COPYING.
*
* @package plugins.generic.navMenuSync
* @class NavMenuSyncPlugin
*
* Navigation Menu Synchronizer plugin: copies navigation menus
* (with items, assignments, hierarchy, and settings) from one
* journal to another in a multi-journal OJS 3.3 installation.
*/
import('lib.pkp.classes.plugins.GenericPlugin');
class NavMenuSyncPlugin extends GenericPlugin {
/**
* @copydoc Plugin::getDisplayName()
*/
function getDisplayName() {
return __('plugins.generic.navMenuSync.displayName');
}
/**
* @copydoc Plugin::getDescription()
*/
function getDescription() {
return __('plugins.generic.navMenuSync.description');
}
/**
* @copydoc Plugin::register()
*/
function register($category, $path, $mainContextId = null) {
if (parent::register($category, $path, $mainContextId)) {
return true;
}
return false;
}
/**
* @copydoc Plugin::getActions()
*/
function getActions($request, $actionArgs) {
$router = $request->getRouter();
import('lib.pkp.classes.linkAction.request.AjaxModal');
return array_merge(
$this->getEnabled() ? array(
new LinkAction(
'settings',
new AjaxModal(
$router->url($request, null, null, 'manage', null, array(
'verb' => 'settings',
'plugin' => $this->getName(),
'category' => 'generic'
)),
$this->getDisplayName()
),
__('plugins.generic.navMenuSync.manage'),
null
)
) : array(),
parent::getActions($request, $actionArgs)
);
}
/**
* @copydoc Plugin::manage()
*/
function manage($args, $request) {
// Enforce site administrator access only.
// OJS PluginAccessPolicy already restricts manage() to authorized roles,
// but this plugin operates across journal contexts, so we explicitly
// require ROLE_ID_SITE_ADMIN for all operations.
$user = $request->getUser();
if (!$user) {
return new JSONMessage(false, __('plugins.generic.navMenuSync.error.unauthorized'));
}
$roleDao = DAORegistry::getDAO('RoleDAO');
if (!$roleDao->userHasRole(CONTEXT_SITE, $user->getId(), ROLE_ID_SITE_ADMIN)) {
return new JSONMessage(false, __('plugins.generic.navMenuSync.error.unauthorized'));
}
switch ($request->getUserVar('verb')) {
case 'settings':
return $this->_showSyncForm($request);
case 'preview':
return $this->_previewMenus($request);
case 'sync':
return $this->_performSync($request);
}
return parent::manage($args, $request);
}
/**
* Show the synchronization form.
*
* @param PKPRequest $request
* @return JSONMessage
*/
private function _showSyncForm($request) {
$context = $request->getContext();
$templateMgr = TemplateManager::getManager($request);
$journalDao = DAORegistry::getDAO('JournalDAO');
$journals = $journalDao->getAll(true);
$journalOptions = array();
while ($journal = $journals->next()) {
if ($journal->getId() != $context->getId()) {
$journalOptions[$journal->getId()] = $journal->getLocalizedName();
}
}
$templateMgr->assign(array(
'pluginName' => $this->getName(),
'currentJournalName' => $context->getLocalizedName(),
'currentJournalId' => $context->getId(),
'journalOptions' => $journalOptions,
'manageUrl' => $request->getRouter()->url($request, null, null, 'manage', null, array(
'plugin' => $this->getName(),
'category' => 'generic',
)),
));
return new JSONMessage(true, $templateMgr->fetch($this->getTemplateResource('syncForm.tpl')));
}
/**
* Preview menus from source journal.
*
* @param PKPRequest $request
* @return JSONMessage
*/
private function _previewMenus($request) {
$sourceContextId = (int) $request->getUserVar('sourceJournalId');
$copyMode = $request->getUserVar('copyMode');
// Whitelist copyMode values
if (!in_array($copyMode, array('activeOnly', 'all'))) {
$copyMode = 'activeOnly';
}
if (!$sourceContextId) {
return new JSONMessage(false, __('plugins.generic.navMenuSync.error.noSource'));
}
// Validate source journal exists
$journalDao = DAORegistry::getDAO('JournalDAO');
$sourceJournal = $journalDao->getById($sourceContextId);
if (!$sourceJournal) {
return new JSONMessage(false, __('plugins.generic.navMenuSync.error.noSource'));
}
$navigationMenuDao = DAORegistry::getDAO('NavigationMenuDAO');
$navigationMenuItemDao = DAORegistry::getDAO('NavigationMenuItemDAO');
$assignmentDao = DAORegistry::getDAO('NavigationMenuItemAssignmentDAO');
$sourceMenus = $navigationMenuDao->getByContextId($sourceContextId);
$menuData = array();
// Track which item IDs are assigned to any menu
$assignedItemIds = array();
while ($menu = $sourceMenus->next()) {
$menuInfo = array(
'id' => $menu->getId(),
'title' => $menu->getTitle(),
'area' => $menu->getAreaName(),
'items' => array(),
);
$assignments = $assignmentDao->getByMenuId($menu->getId());
$assignmentList = array();
while ($assignment = $assignments->next()) {
$assignmentList[] = $assignment;
$assignedItemIds[$assignment->getMenuItemId()] = true;
}
// Build lookup maps for parent matching.
// In OJS, parent_id can reference either an assignment ID or an item ID
// depending on how the data was originally created.
$assignmentById = array();
$assignmentsByItemId = array();
foreach ($assignmentList as $assignment) {
$assignmentById[$assignment->getId()] = $assignment;
$assignmentsByItemId[$assignment->getMenuItemId()] = $assignment;
}
$topLevel = array();
$childrenOf = array();
foreach ($assignmentList as $assignment) {
$parentId = (int) $assignment->getParentId();
if ($parentId == 0) {
$topLevel[] = $assignment;
} else {
$parentAssignment = null;
if (isset($assignmentById[$parentId])) {
$parentAssignment = $assignmentById[$parentId];
} elseif (isset($assignmentsByItemId[$parentId])) {
$parentAssignment = $assignmentsByItemId[$parentId];
}
if ($parentAssignment) {
$pKey = $parentAssignment->getId();
if (!isset($childrenOf[$pKey])) {
$childrenOf[$pKey] = array();
}
$childrenOf[$pKey][] = $assignment;
}
}
}
foreach ($topLevel as $assignment) {
$item = $navigationMenuItemDao->getById($assignment->getMenuItemId());
if (!$item) continue;
$itemInfo = array(
'title' => $item->getLocalizedTitle() ?: $item->getType(),
'type' => $item->getType(),
'seq' => $assignment->getSequence(),
'children' => array(),
);
$children = isset($childrenOf[$assignment->getId()]) ? $childrenOf[$assignment->getId()] : array();
usort($children, function($a, $b) {
return (int) $a->getSequence() - (int) $b->getSequence();
});
foreach ($children as $childAssignment) {
$childItem = $navigationMenuItemDao->getById($childAssignment->getMenuItemId());
if (!$childItem) continue;
$itemInfo['children'][] = array(
'title' => $childItem->getLocalizedTitle() ?: $childItem->getType(),
'type' => $childItem->getType(),
'seq' => $childAssignment->getSequence(),
);
}
$menuInfo['items'][] = $itemInfo;
}
$menuData[] = $menuInfo;
}
// If copyMode is 'all', find unassigned items
$unassignedItems = array();
if ($copyMode === 'all') {
$allItems = $navigationMenuItemDao->getByContextId($sourceContextId);
while ($item = $allItems->next()) {
if (!isset($assignedItemIds[$item->getId()])) {
$unassignedItems[] = array(
'title' => $item->getLocalizedTitle() ?: $item->getType(),
'type' => $item->getType(),
'id' => $item->getId(),
);
}
}
}
$templateMgr = TemplateManager::getManager($request);
$templateMgr->assign('menuData', $menuData);
$templateMgr->assign('unassignedItems', $unassignedItems);
$templateMgr->assign('copyMode', $copyMode);
$templateMgr->assign('sourceJournalName', $sourceJournal->getLocalizedName());
return new JSONMessage(true, $templateMgr->fetch($this->getTemplateResource('preview.tpl')));
}
/**
* Perform the synchronization.
*
* @param PKPRequest $request
* @return JSONMessage
*/
private function _performSync($request) {
$context = $request->getContext();
$sourceContextId = (int) $request->getUserVar('sourceJournalId');
$clearExisting = (bool) $request->getUserVar('clearExisting');
$copyMode = $request->getUserVar('copyMode');
// Whitelist copyMode values
if (!in_array($copyMode, array('activeOnly', 'all'))) {
$copyMode = 'activeOnly';
}
if (!$sourceContextId) {
return new JSONMessage(false, __('plugins.generic.navMenuSync.error.noSource'));
}
if ($sourceContextId == $context->getId()) {
return new JSONMessage(false, __('plugins.generic.navMenuSync.error.sameJournal'));
}
// Validate source journal exists
$journalDao = DAORegistry::getDAO('JournalDAO');
$sourceJournal = $journalDao->getById($sourceContextId);
if (!$sourceJournal) {
return new JSONMessage(false, __('plugins.generic.navMenuSync.error.noSource'));
}
$copyAll = ($copyMode === 'all');
$results = $this->synchronizeMenus($sourceContextId, $context->getId(), $clearExisting, $copyAll);
$templateMgr = TemplateManager::getManager($request);
$templateMgr->assign('results', $results);
$templateMgr->assign('sourceJournalName', $sourceJournal->getLocalizedName());
$templateMgr->assign('targetJournalName', $context->getLocalizedName());
return new JSONMessage(true, $templateMgr->fetch($this->getTemplateResource('results.tpl')));
}
/**
* Copy a single navigation menu item and its settings from source to target context.
*
* @param NavigationMenuItemDAO $navigationMenuItemDao
* @param int $sourceItemId Source item ID
* @param int $targetContextId Target journal context ID
* @return int|null New item ID, or null on failure
*/
private function _copyMenuItem($navigationMenuItemDao, $sourceItemId, $targetContextId) {
$sourceItem = $navigationMenuItemDao->getById($sourceItemId);
if (!$sourceItem) {
return null;
}
$newItem = $navigationMenuItemDao->newDataObject();
$newItem->setContextId($targetContextId);
$newItem->setType($sourceItem->getType());
$newItem->setPath($sourceItem->getPath());
// Copy locale-specific title data
$titleData = $sourceItem->getTitle(null);
if (is_array($titleData)) {
foreach ($titleData as $locale => $val) {
$newItem->setTitle($val, $locale);
}
}
// Copy locale-specific content data
$contentData = $sourceItem->getContent(null);
if (is_array($contentData)) {
foreach ($contentData as $locale => $val) {
$newItem->setContent($val, $locale);
}
}
// Copy locale-specific remote URL data
$remoteUrlData = $sourceItem->getRemoteUrl(null);
if (is_array($remoteUrlData)) {
foreach ($remoteUrlData as $locale => $val) {
$newItem->setRemoteUrl($val, $locale);
}
}
$newItemId = $navigationMenuItemDao->insertObject($newItem);
// Copy titleLocaleKey setting (used by built-in menu item types
// like NMI_TYPE_CONTACT, NMI_TYPE_EDITORIAL_TEAM, etc.)
// Wrapped in try-catch due to OJS 3.3 core bug in getSetting()
// where variable name mismatch causes count(null) TypeError.
try {
$titleLocaleKey = $navigationMenuItemDao->getSetting($sourceItemId, 'titleLocaleKey');
if ($titleLocaleKey) {
$navigationMenuItemDao->updateSetting($newItemId, 'titleLocaleKey', $titleLocaleKey);
}
} catch (Exception $e) {
// Silently continue: setting may not exist
} catch (TypeError $e) {
// PHP 8 throws TypeError for count(null) in OJS core
}
return $newItemId;
}
/**
* Synchronize navigation menus from source journal to target journal.
*
* @param int $sourceContextId Source journal context ID
* @param int $targetContextId Target journal context ID
* @param bool $clearExisting Whether to clear existing menus in target first
* @param bool $copyAll Whether to also copy unassigned (passive) items
* @return array Results summary
*/
function synchronizeMenus($sourceContextId, $targetContextId, $clearExisting = false, $copyAll = false) {
$navigationMenuDao = DAORegistry::getDAO('NavigationMenuDAO');
$navigationMenuItemDao = DAORegistry::getDAO('NavigationMenuItemDAO');
$assignmentDao = DAORegistry::getDAO('NavigationMenuItemAssignmentDAO');
$results = array(
'menusCreated' => 0,
'itemsCopied' => 0,
'assignmentsCopied' => 0,
'menusCleared' => 0,
'unassignedItemsCopied' => 0,
);
// Global map of old item ID => new item ID (persists across all menus)
$itemIdMap = array();
// Step 1: Clear existing menus in target if requested
if ($clearExisting) {
$existingMenus = $navigationMenuDao->getByContextId($targetContextId);
while ($menu = $existingMenus->next()) {
$assignments = $assignmentDao->getByMenuId($menu->getId());
while ($assignment = $assignments->next()) {
$assignmentDao->deleteById($assignment->getId());
}
$results['menusCleared']++;
}
$existingItems = $navigationMenuItemDao->getByContextId($targetContextId);
while ($item = $existingItems->next()) {
$navigationMenuItemDao->deleteById($item->getId());
}
$navigationMenuDao->deleteByContextId($targetContextId);
}
// Step 2: Copy each source menu with its items and assignments
$sourceMenus = $navigationMenuDao->getByContextId($sourceContextId);
while ($sourceMenu = $sourceMenus->next()) {
$newMenu = $navigationMenuDao->newDataObject();
$newMenu->setTitle($sourceMenu->getTitle());
$newMenu->setAreaName($sourceMenu->getAreaName());
$newMenu->setContextId($targetContextId);
// If not clearing, replace menus that occupy the same area
if (!$clearExisting) {
$existingMenusInArea = $navigationMenuDao->getByArea($targetContextId, $sourceMenu->getAreaName());
$areaMenus = $existingMenusInArea->toArray();
if (count($areaMenus) > 0) {
foreach ($areaMenus as $existingMenu) {
$existingAssignments = $assignmentDao->getByMenuId($existingMenu->getId());
while ($existingAssignment = $existingAssignments->next()) {
$existingItem = $navigationMenuItemDao->getById($existingAssignment->getMenuItemId());
if ($existingItem && $existingItem->getContextId() == $targetContextId) {
$navigationMenuItemDao->deleteById($existingItem->getId());
}
$assignmentDao->deleteById($existingAssignment->getId());
}
$navigationMenuDao->deleteById($existingMenu->getId());
}
}
}
$newMenuId = $navigationMenuDao->insertObject($newMenu);
$results['menusCreated']++;
// Step 3: Copy assignments and items for this menu.
//
// OJS loadMenuTree() matches children to parents using
// getMenuItemId() (the item ID), NOT the assignment ID.
// Therefore parent_id in assignments must store the ITEM ID of the parent.
$sourceAssignments = $assignmentDao->getByMenuId($sourceMenu->getId());
$allAssignments = array();
while ($sourceAssignment = $sourceAssignments->next()) {
$allAssignments[] = $sourceAssignment;
}
// Build lookups for resolving source parent references.
// Source parent_id can reference either an assignment ID or an item ID.
$sourceAssignById = array();
$sourceAssignByItemId = array();
foreach ($allAssignments as $sa) {
$sourceAssignById[$sa->getId()] = $sa;
$sourceAssignByItemId[$sa->getMenuItemId()] = $sa;
}
// Sort: parents first (parentId=0), then children
usort($allAssignments, function($a, $b) {
$aParent = (int) $a->getParentId();
$bParent = (int) $b->getParentId();
if ($aParent == 0 && $bParent != 0) return -1;
if ($aParent != 0 && $bParent == 0) return 1;
return (int) $a->getSequence() - (int) $b->getSequence();
});
foreach ($allAssignments as $sourceAssignment) {
$sourceItemId = $sourceAssignment->getMenuItemId();
// Copy item if not already copied (items can be shared across menus)
if (!isset($itemIdMap[$sourceItemId])) {
$newItemId = $this->_copyMenuItem($navigationMenuItemDao, $sourceItemId, $targetContextId);
if ($newItemId === null) continue;
$itemIdMap[$sourceItemId] = $newItemId;
$results['itemsCopied']++;
}
// Resolve parent: find the source parent's ITEM ID, then map to new ITEM ID
$sourceParentId = (int) $sourceAssignment->getParentId();
$newParentItemId = 0;
if ($sourceParentId > 0) {
$sourceParentAssign = null;
if (isset($sourceAssignById[$sourceParentId])) {
$sourceParentAssign = $sourceAssignById[$sourceParentId];
} elseif (isset($sourceAssignByItemId[$sourceParentId])) {
$sourceParentAssign = $sourceAssignByItemId[$sourceParentId];
}
if ($sourceParentAssign) {
$sourceParentItemId = $sourceParentAssign->getMenuItemId();
if (isset($itemIdMap[$sourceParentItemId])) {
$newParentItemId = $itemIdMap[$sourceParentItemId];
}
}
}
// Create assignment with parent_id = new item ID of parent
$newAssignment = $assignmentDao->newDataObject();
$newAssignment->setMenuId($newMenuId);
$newAssignment->setMenuItemId($itemIdMap[$sourceItemId]);
$newAssignment->setParentId($newParentItemId);
$newAssignment->setSequence($sourceAssignment->getSequence());
$assignmentDao->insertObject($newAssignment);
$results['assignmentsCopied']++;
}
}
// Step 4: Copy unassigned (passive) items if copyAll is enabled
if ($copyAll) {
$allSourceItems = $navigationMenuItemDao->getByContextId($sourceContextId);
while ($sourceItem = $allSourceItems->next()) {
$sourceItemId = $sourceItem->getId();
// Skip items already copied via menu assignments
if (isset($itemIdMap[$sourceItemId])) {
continue;
}
$newItemId = $this->_copyMenuItem($navigationMenuItemDao, $sourceItemId, $targetContextId);
if ($newItemId === null) continue;
$itemIdMap[$sourceItemId] = $newItemId;
$results['unassignedItemsCopied']++;
}
}
return $results;
}
}