-
Notifications
You must be signed in to change notification settings - Fork 96
/
CMSMenu.php
442 lines (399 loc) · 15 KB
/
CMSMenu.php
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
<?php
namespace SilverStripe\Admin;
use SilverStripe\CMS\Controllers\CMSMain;
use SilverStripe\Core\ClassInfo;
use SilverStripe\Core\Config\Config;
use SilverStripe\Core\Convert;
use SilverStripe\Core\Manifest\ClassLoader;
use SilverStripe\Control\Controller;
use SilverStripe\Dev\TestOnly;
use SilverStripe\i18n\i18nEntityProvider;
use SilverStripe\Security\Member;
use IteratorAggregate;
use ReflectionClass;
use ArrayIterator;
use SilverStripe\Security\Security;
use Traversable;
/**
* The object manages the main CMS menu. See {@link LeftAndMain::init()} for
* example usage.
*
* The menu will be automatically populated with menu items for subclasses of
* {@link LeftAndMain}. That is, for each class in the CMS that creates an
* administration panel, a CMS menu item will be created. The default
* configuration will also include a 'help' link to the SilverStripe user
* documentation.
*
* Additional CMSMenu items can be added through {@link LeftAndMainExtension::init()}
* extensions added to {@link LeftAndMain}.
*/
class CMSMenu implements IteratorAggregate, i18nEntityProvider
{
/**
* Sort by menu priority, highest to lowest
*/
const MENU_PRIORITY = 'menu_priority';
/**
* Sort by url priority, highest to lowest
*/
const URL_PRIORITY = 'url_priority';
/**
* An array of changes to be made to the menu items, in the order that the changes should be
* applied. Each item is a map in one of the two forms:
* - array('type' => 'add', 'item' => CMSMenuItem::create(...) )
* - array('type' => 'remove', 'code' => 'codename' )
*/
protected static $menu_item_changes = [];
/**
* Set to true if clear_menu() is called, to indicate that the default menu shouldn't be
* included
*/
protected static $menu_is_cleared = false;
/**
* Generate CMS main menu items by collecting valid
* subclasses of {@link LeftAndMain}
*/
public static function populate_menu()
{
self::$menu_is_cleared = false;
}
/**
* Add a LeftAndMain controller to the CMS menu.
*
* @param string $controllerClass The class name of the controller
* @todo A director rule is added when a controller link is added, but it won't be removed
* when the item is removed. Functionality needed in {@link Director}.
*/
public static function add_controller($controllerClass)
{
if ($menuItem = self::menuitem_for_controller($controllerClass)) {
$code = static::get_menu_code($controllerClass);
self::add_menu_item_obj($code, $menuItem);
}
}
/**
* Return a CMSMenuItem to add the given controller to the CMSMenu
*
* @param string $controllerClass
* @return CMSMenuItem
*/
protected static function menuitem_for_controller($controllerClass)
{
$urlBase = AdminRootController::admin_url();
$urlSegment = Config::inst()->get($controllerClass, 'url_segment');
$menuPriority = Config::inst()->get($controllerClass, 'menu_priority');
$ignoreFromMenu = Config::inst()->get($controllerClass, 'ignore_menuitem');
// Don't add menu items defined the old way, or for controllers that are set to be ignored
if (!$urlSegment || $ignoreFromMenu) {
return null;
}
$link = Controller::join_links($urlBase, $urlSegment);
// doesn't work if called outside of a controller context (e.g. in _config.php)
// as the locale won't be detected properly. Use {@link LeftAndMain->MainMenu()} to update
// titles for existing menu entries
$menuTitle = LeftAndMain::menu_title($controllerClass);
return CMSMenuItem::create($menuTitle, $link, $controllerClass, $menuPriority);
}
/**
* Add an arbitrary URL to the CMS menu.
*
* @param string $code A unique identifier (used to create a CSS ID and its key in {@link $menu_items})
* @param string $menuTitle The link's title in the CMS menu
* @param string $url The url of the link
* @param integer $priority The menu priority (sorting order) of the menu item. Higher priorities will be further
* left.
* @param array $attributes an array of attributes to include on the link.
* @param string $iconClass
*
* @return boolean The result of the operation.
*/
public static function add_link($code, $menuTitle, $url, $priority = -1, $attributes = null, $iconClass = null)
{
return self::add_menu_item($code, $menuTitle, $url, null, $priority, $attributes, $iconClass);
}
/**
* Add a navigation item to the main administration menu showing in the top bar.
*
* uses {@link CMSMenu::$menu_items}
*
* @param string $code Unique identifier for this menu item (e.g. used by {@link replace_menu_item()} and
* {@link remove_menu_item}. Also used as a CSS-class for icon customization.
* @param string $menuTitle Localized title showing in the menu bar
* @param string $url A relative URL that will be linked in the menu bar.
* @param string $controllerClass The controller class for this menu, used to check permisssions.
* If blank, it's assumed that this is public, and always shown to users who
* have the rights to access some other part of the admin area.
* @param int $priority
* @param array $attributes an array of attributes to include on the link.
* @param string $iconClass
*
* @return bool Success
*/
public static function add_menu_item(
$code,
$menuTitle,
$url,
$controllerClass = null,
$priority = -1,
$attributes = null,
$iconClass = null
) {
// If a class is defined, then force the use of that as a code. This helps prevent menu item duplication
if ($controllerClass) {
$code = self::get_menu_code($controllerClass);
}
return self::replace_menu_item(
$code,
$menuTitle,
$url,
$controllerClass,
$priority,
$attributes,
$iconClass
);
}
/**
* Get a single menu item by its code value.
*
* @param string $code
* @return array
*/
public static function get_menu_item($code)
{
$menuItems = self::get_menu_items();
return (isset($menuItems[$code])) ? $menuItems[$code] : false;
}
/**
* Get menu code for class
*
* @param string $cmsClass Controller class name
* @return string
*/
public static function get_menu_code($cmsClass)
{
return Convert::raw2htmlname(str_replace('\\', '-', $cmsClass ?? ''));
}
/**
* Get all menu entries.
*
* @return array
*/
public static function get_menu_items()
{
$menuItems = [];
// Set up default menu items
if (!self::$menu_is_cleared) {
$cmsClasses = self::get_cms_classes();
foreach ($cmsClasses as $cmsClass) {
$menuItem = self::menuitem_for_controller($cmsClass);
$menuCode = self::get_menu_code($cmsClass);
if ($menuItem) {
$menuItems[$menuCode] = $menuItem;
}
}
}
// Apply changes
foreach (self::$menu_item_changes as $change) {
switch ($change['type']) {
case 'add':
$menuItems[$change['code']] = $change['item'];
break;
case 'remove':
unset($menuItems[$change['code']]);
break;
default:
user_error("Bad menu item change type {$change['type']}", E_USER_WARNING);
}
}
// Sort menu items according to priority, then title asc
$menuPriority = [];
$menuTitle = [];
foreach ($menuItems as $key => $menuItem) {
$menuPriority[$key] = is_numeric($menuItem->priority) ? $menuItem->priority : 0;
$menuTitle[$key] = $menuItem->title;
}
array_multisort($menuPriority, SORT_DESC, $menuTitle, SORT_ASC, $menuItems);
return $menuItems;
}
/**
* Get all menu items that the passed member can view.
* Defaults to {@link Security::getCurrentUser()}.
*
* @param Member $member
* @return array
*/
public static function get_viewable_menu_items($member = null)
{
if (!$member && $member !== false) {
$member = Security::getCurrentUser();
}
$viewableMenuItems = [];
$allMenuItems = self::get_menu_items();
if ($allMenuItems) {
foreach ($allMenuItems as $code => $menuItem) {
// exclude all items which have a controller to perform permission
// checks on
if ($menuItem->controller) {
$controllerObj = singleton($menuItem->controller);
if (Controller::has_curr()) {
// Necessary for canView() to have request data available,
// e.g. to check permissions against LeftAndMain->currentPage()
$controllerObj->setRequest(Controller::curr()->getRequest());
if (!$controllerObj->canView($member)) {
continue;
}
}
}
$viewableMenuItems[$code] = $menuItem;
}
}
return $viewableMenuItems;
}
/**
* Removes an existing item from the menu.
*
* @param string $code Unique identifier for this menu item
*/
public static function remove_menu_item($code)
{
self::$menu_item_changes[] = ['type' => 'remove', 'code' => $code];
}
/**
* Remove menu item by class name.
*
* @param string $className Name of class
*/
public static function remove_menu_class($className)
{
$code = self::get_menu_code($className);
self::remove_menu_item($code);
}
/**
* Clears the entire menu
*/
public static function clear_menu()
{
self::$menu_item_changes = [];
self::$menu_is_cleared = true;
}
/**
* Replace a navigation item to the main administration menu showing in the top bar.
*
* @param string $code Unique identifier for this menu item (e.g. used by {@link replace_menu_item()} and
* {@link remove_menu_item}. Also used as a CSS-class for icon customization.
* @param string $menuTitle Localized title showing in the menu bar
* @param string $url A relative URL that will be linked in the menu bar.
* Make sure to add a matching route via {@link Director::$rules} to this url.
* @param string $controllerClass The controller class for this menu, used to check permisssions.
* If blank, it's assumed that this is public, and always shown to users who
* have the rights to access some other part of the admin area.
* @param int $priority
* @param array $attributes an array of attributes to include on the link.
* @param string $iconClass
*
* @return bool Success
*/
public static function replace_menu_item(
$code,
$menuTitle,
$url,
$controllerClass = null,
$priority = -1,
$attributes = null,
$iconClass = null
) {
$item = CMSMenuItem::create($menuTitle, $url, $controllerClass, $priority, $iconClass);
if ($attributes) {
$item->setAttributes($attributes);
}
self::$menu_item_changes[] = [
'type' => 'add',
'code' => $code,
'item' => $item,
];
}
/**
* Add a previously built menu item object to the menu
*
* @param string $code
* @param CMSMenuItem $cmsMenuItem
*/
protected static function add_menu_item_obj($code, $cmsMenuItem)
{
self::$menu_item_changes[] = [
'type' => 'add',
'code' => $code,
'item' => $cmsMenuItem,
];
}
/**
* A utility funciton to retrieve subclasses of a given class that
* are instantiable (ie, not abstract) and have a valid menu title.
*
* Sorted by url_priority config.
*
* @todo A variation of this function could probably be moved to {@link ClassInfo}
* @param string $root The root class to begin finding subclasses
* @param boolean $recursive Look for subclasses recursively?
* @param string $sort Name of config on which to sort. Can be 'menu_priority' or 'url_priority'
* @return array Valid, unique subclasses
*/
public static function get_cms_classes($root = null, $recursive = true, $sort = self::MENU_PRIORITY)
{
if (!$root) {
$root = LeftAndMain::class;
}
/** @todo Make these actual abstract classes */
$abstractClasses = [LeftAndMain::class, CMSMain::class];
$subClasses = array_values(ClassInfo::subclassesFor($root) ?? []);
foreach ($subClasses as $className) {
if ($recursive && $className != $root) {
$subClasses = array_merge($subClasses, array_values(ClassInfo::subclassesFor($className) ?? []));
}
}
$subClasses = array_unique($subClasses ?? []);
foreach ($subClasses as $key => $className) {
// Remove abstract classes and LeftAndMain
if (in_array($className, $abstractClasses ?? []) || ClassInfo::classImplements($className, TestOnly::class)) {
unset($subClasses[$key]);
} else {
// Separate conditional to avoid autoloading the class
$classReflection = new ReflectionClass($className);
if (!$classReflection->isInstantiable()) {
unset($subClasses[$key]);
}
}
}
// Sort by specified sorting config
usort($subClasses, function ($a, $b) use ($sort) {
$priorityA = Config::inst()->get($a, $sort);
$priorityB = Config::inst()->get($b, $sort);
return $priorityB - $priorityA;
});
return $subClasses;
}
/**
* IteratorAggregate Interface Method. Iterates over the menu items.
*/
public function getIterator(): Traversable
{
return new ArrayIterator(self::get_menu_items());
}
/**
* Provide menu titles to the i18n entity provider
*/
public function provideI18nEntities()
{
$cmsClasses = self::get_cms_classes();
$entities = [];
foreach ($cmsClasses as $cmsClass) {
$defaultTitle = LeftAndMain::menu_title($cmsClass, false);
$ownerModule = ClassLoader::inst()->getManifest()->getOwnerModule($cmsClass);
$entities["{$cmsClass}.MENUTITLE"] = [
'default' => $defaultTitle,
'module' => $ownerModule->getShortName()
];
}
return $entities;
}
}