summaryrefslogtreecommitdiffstats
path: root/library/Icinga/Web/Navigation/Navigation.php
blob: 8cf3f68455ac4a0c8e28d1edf538da5c8256e949 (plain)
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
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
<?php
/* Icinga Web 2 | (c) 2015 Icinga Development Team | GPLv2+ */

namespace Icinga\Web\Navigation;

use ArrayAccess;
use ArrayIterator;
use Exception;
use Countable;
use InvalidArgumentException;
use IteratorAggregate;
use Traversable;
use Icinga\Application\Icinga;
use Icinga\Application\Logger;
use Icinga\Authentication\Auth;
use Icinga\Data\ConfigObject;
use Icinga\Exception\ConfigurationError;
use Icinga\Exception\IcingaException;
use Icinga\Exception\ProgrammingError;
use Icinga\Util\StringHelper;
use Icinga\Web\Navigation\Renderer\RecursiveNavigationRenderer;

/**
 * Container for navigation items
 */
class Navigation implements ArrayAccess, Countable, IteratorAggregate
{
    /**
     * The class namespace where to locate navigation type classes
     *
     * @var string
     */
    const NAVIGATION_NS = 'Web\\Navigation';

    /**
     * Flag for dropdown layout
     *
     * @var int
     */
    const LAYOUT_DROPDOWN = 1;

    /**
     * Flag for tabs layout
     *
     * @var int
     */
    const LAYOUT_TABS = 2;

    /**
     * Known navigation types
     *
     * @var array
     */
    protected static $types;

    /**
     * This navigation's items
     *
     * @var NavigationItem[]
     */
    protected $items = array();

    /**
     * This navigation's layout
     *
     * @var int
     */
    protected $layout;

    public function offsetExists($offset): bool
    {
        return isset($this->items[$offset]);
    }

    public function offsetGet($offset): ?NavigationItem
    {
        return $this->items[$offset] ?? null;
    }

    public function offsetSet($offset, $value): void
    {
        $this->items[$offset] = $value;
    }

    public function offsetUnset($offset): void
    {
        unset($this->items[$offset]);
    }

    public function count(): int
    {
        return count($this->items);
    }

    public function getIterator(): Traversable
    {
        $this->order();
        return new ArrayIterator($this->items);
    }

    /**
     * Create and return a new navigation item for the given configuration
     *
     * @param   string              $name
     * @param   array|ConfigObject  $properties
     *
     * @return  NavigationItem
     *
     * @throws  InvalidArgumentException    If the $properties argument is neither an array nor a ConfigObject
     */
    public function createItem($name, $properties)
    {
        if ($properties instanceof ConfigObject) {
            $properties = $properties->toArray();
        } elseif (! is_array($properties)) {
            throw new InvalidArgumentException('Argument $properties must be of type array or ConfigObject');
        }

        $itemType = isset($properties['type']) ? StringHelper::cname($properties['type'], '-') : 'NavigationItem';
        if (! empty(static::$types) && isset(static::$types[$itemType])) {
            return new static::$types[$itemType]($name, $properties);
        }

        $item = null;
        foreach (Icinga::app()->getModuleManager()->getLoadedModules() as $module) {
            $classPath = 'Icinga\\Module\\'
                . ucfirst($module->getName())
                . '\\'
                . static::NAVIGATION_NS
                . '\\'
                . $itemType;
            if (class_exists($classPath)) {
                $item = new $classPath($name, $properties);
                break;
            }
        }

        if ($item === null) {
            $classPath = 'Icinga\\' . static::NAVIGATION_NS . '\\' . $itemType;
            if (class_exists($classPath)) {
                $item = new $classPath($name, $properties);
            }
        }

        if ($item === null) {
            if ($itemType !== 'MenuItem') {
                Logger::debug(
                    'Failed to find custom navigation item class %s for item %s. Using base class NavigationItem now',
                    $itemType,
                    $name
                );
            }

            $item = new NavigationItem($name, $properties);
            static::$types[$itemType] = 'Icinga\\Web\\Navigation\\NavigationItem';
        } elseif (! $item instanceof NavigationItem) {
            throw new ProgrammingError('Class %s must inherit from NavigationItem', $classPath);
        } else {
            static::$types[$itemType] = $classPath;
        }

        return $item;
    }

    /**
     * Add a navigation item
     *
     * If you do not pass an instance of NavigationItem, this will only add the item
     * if it does not require a permission or the current user has the permission.
     *
     * @param   string|NavigationItem   $name       The name of the item or an instance of NavigationItem
     * @param   array                   $properties The properties of the item to add (Ignored if $name is not a string)
     *
     * @return  bool                                Whether the item was added or not
     *
     * @throws  InvalidArgumentException            In case $name is neither a string nor an instance of NavigationItem
     */
    public function addItem($name, array $properties = array())
    {
        if (is_string($name)) {
            if (isset($properties['permission'])) {
                if (! Auth::getInstance()->hasPermission($properties['permission'])) {
                    return false;
                }

                unset($properties['permission']);
            }

            $item = $this->createItem($name, $properties);
        } elseif (! $name instanceof NavigationItem) {
            throw new InvalidArgumentException('Argument $name must be of type string or NavigationItem');
        } else {
            $item = $name;
        }

        $this->items[$item->getName()] = $item;
        return true;
    }

    /**
     * Return the item with the given name
     *
     * @param   string  $name
     * @param   mixed   $default
     *
     * @return  NavigationItem|mixed
     */
    public function getItem($name, $default = null)
    {
        return isset($this->items[$name]) ? $this->items[$name] : $default;
    }

    /**
     * Return the currently active item or the first one if none is active
     *
     * @return  NavigationItem
     */
    public function getActiveItem()
    {
        foreach ($this->items as $item) {
            if ($item->getActive()) {
                return $item;
            }
        }

        $firstItem = reset($this->items);
        return $firstItem ? $firstItem->setActive() : null;
    }

    /**
     * Return this navigation's items
     *
     * @return  array
     */
    public function getItems()
    {
        return $this->items;
    }

    /**
     * Return whether this navigation is empty
     *
     * @return  bool
     */
    public function isEmpty()
    {
        return empty($this->items);
    }

    /**
     * Return whether this navigation has any renderable items
     *
     * @return  bool
     */
    public function hasRenderableItems()
    {
        foreach ($this->getItems() as $item) {
            if ($item->shouldRender()) {
                return true;
            }
        }

        return false;
    }

    /**
     * Return this navigation's layout
     *
     * @return  int
     */
    public function getLayout()
    {
        return $this->layout;
    }

    /**
     * Set this navigation's layout
     *
     * @param   int     $layout
     *
     * @return  $this
     */
    public function setLayout($layout)
    {
        $this->layout = (int) $layout;
        return $this;
    }

    /**
     * Create and return the renderer for this navigation
     *
     * @return  RecursiveNavigationRenderer
     */
    public function getRenderer()
    {
        return new RecursiveNavigationRenderer($this);
    }

    /**
     * Return this navigation rendered to HTML
     *
     * @return  string
     */
    public function render()
    {
        return $this->getRenderer()->render();
    }

    /**
     * Order this navigation's items
     *
     * @return  $this
     */
    public function order()
    {
        uasort($this->items, array($this, 'compareItems'));
        foreach ($this->items as $item) {
            if ($item->hasChildren()) {
                $item->getChildren()->order();
            }
        }

        return $this;
    }

    /**
     * Return whether the first item is less than, more than or equal to the second one
     *
     * @param   NavigationItem  $a
     * @param   NavigationItem  $b
     *
     * @return  int
     */
    protected function compareItems(NavigationItem $a, NavigationItem $b)
    {
        if ($a->getPriority() === $b->getPriority()) {
            return strcasecmp($a->getLabel(), $b->getLabel());
        }

        return $a->getPriority() > $b->getPriority() ? 1 : -1;
    }

    /**
     * Try to find and return a item with the given or a similar name
     *
     * @param   string  $name
     *
     * @return  NavigationItem
     */
    public function findItem($name)
    {
        $item = $this->getItem($name);
        if ($item !== null) {
            return $item;
        }

        $loweredName = strtolower($name);
        foreach ($this->getItems() as $item) {
            if (strtolower($item->getName()) === $loweredName) {
                return $item;
            }
        }
    }

    /**
     * Merge this navigation with the given one
     *
     * Any duplicate items of this navigation will be overwritten by the given navigation's items.
     *
     * @param   Navigation  $navigation
     *
     * @return  $this
     */
    public function merge(Navigation $navigation)
    {
        foreach ($navigation as $item) {
            /** @var $item NavigationItem */
            if (($existingItem = $this->findItem($item->getName())) !== null) {
                if ($existingItem->conflictsWith($item)) {
                    $name = $item->getName();
                    do {
                        if (preg_match('~_(\d+)$~', $name, $matches)) {
                            $name = preg_replace('~_\d+$~', $matches[1] + 1, $name);
                        } else {
                            $name .= '_2';
                        }
                    } while ($this->getItem($name) !== null);

                    $this->addItem($item->setName($name));
                } else {
                    $existingItem->merge($item);
                }
            } else {
                $this->addItem($item);
            }
        }

        return $this;
    }

    /**
     * Extend this navigation set with all additional items of the given type
     *
     * This will fetch navigation items from the following sources:
     * * User Shareables
     * * User Preferences
     * * Modules
     * Any existing entry will be overwritten by one that is coming later in order.
     *
     * @param   string  $type
     *
     * @return  $this
     */
    public function load($type)
    {
        $user = Auth::getInstance()->getUser();
        if ($type !== 'dashboard-pane') {
            // Shareables
            $this->merge(Icinga::app()->getSharedNavigation($type));

            // User Preferences
            $this->merge($user->getNavigation($type));
        }

        // Modules
        $moduleManager = Icinga::app()->getModuleManager();
        foreach ($moduleManager->getLoadedModules() as $module) {
            if ($user->can($moduleManager::MODULE_PERMISSION_NS . $module->getName())) {
                if ($type === 'menu-item') {
                    $this->merge($module->getMenu());
                } elseif ($type === 'dashboard-pane') {
                    $this->merge($module->getDashboard());
                }
            }
        }

        return $this;
    }

    /**
     * Return the global navigation item type configuration
     *
     * @return  array
     */
    public static function getItemTypeConfiguration()
    {
        $defaultItemTypes = array(
            'menu-item' => array(
                'label'     => t('Menu Entry'),
                'config'    => 'menu'
            )/*, // Disabled, until it is able to fully replace the old implementation
            'dashlet'   => array(
                'label'     => 'Dashlet',
                'config'    => 'dashboard'
            )*/
        );

        $moduleItemTypes = array();
        $moduleManager = Icinga::app()->getModuleManager();
        foreach ($moduleManager->getLoadedModules() as $module) {
            if (Auth::getInstance()->hasPermission($moduleManager::MODULE_PERMISSION_NS . $module->getName())) {
                foreach ($module->getNavigationItems() as $type => $options) {
                    if (! isset($moduleItemTypes[$type])) {
                        $moduleItemTypes[$type] = $options;
                    }
                }
            }
        }

        return array_merge($defaultItemTypes, $moduleItemTypes);
    }

    /**
     * Create and return a new set of navigation items for the given configuration
     *
     * Note that this is supposed to be utilized for one dimensional structures
     * only. Multi dimensional structures can be processed by fromArray().
     *
     * @param   Traversable|array   $config
     *
     * @return  Navigation
     *
     * @throws  InvalidArgumentException    In case the given configuration is invalid
     * @throws  ConfigurationError          In case a referenced parent does not exist
     */
    public static function fromConfig($config)
    {
        if (! is_array($config) && !$config instanceof Traversable) {
            throw new InvalidArgumentException('Argument $config must be an array or a instance of Traversable');
        }

        $flattened = $orphans = $topLevel = array();
        foreach ($config as $sectionName => $sectionConfig) {
            $parentName = $sectionConfig->parent;
            unset($sectionConfig->parent);

            if (! $parentName) {
                $topLevel[$sectionName] = $sectionConfig->toArray();
                $flattened[$sectionName] = & $topLevel[$sectionName];
            } elseif (isset($flattened[$parentName])) {
                $flattened[$parentName]['children'][$sectionName] = $sectionConfig->toArray();
                $flattened[$sectionName] = & $flattened[$parentName]['children'][$sectionName];
            } else {
                $orphans[$parentName][$sectionName] = $sectionConfig->toArray();
                $flattened[$sectionName] = & $orphans[$parentName][$sectionName];
            }
        }

        do {
            $match = false;
            foreach ($orphans as $parentName => $children) {
                if (isset($flattened[$parentName])) {
                    if (isset($flattened[$parentName]['children'])) {
                        $flattened[$parentName]['children'] = array_merge(
                            $flattened[$parentName]['children'],
                            $children
                        );
                    } else {
                        $flattened[$parentName]['children'] = $children;
                    }

                    unset($orphans[$parentName]);
                    $match = true;
                }
            }
        } while ($match && !empty($orphans));

        if (! empty($orphans)) {
            throw new ConfigurationError(
                t(
                    'Failed to fully parse navigation configuration. Ensure that'
                    . ' all referenced parents are existing navigation items: %s'
                ),
                join(', ', array_keys($orphans))
            );
        }

        return static::fromArray($topLevel);
    }

    /**
     * Create and return a new set of navigation items for the given array
     *
     * @param   array   $array
     *
     * @return  Navigation
     */
    public static function fromArray(array $array)
    {
        $navigation = new static();
        foreach ($array as $name => $properties) {
            $navigation->addItem((string) $name, $properties);
        }

        return $navigation;
    }

    /**
     * Return this navigation rendered to HTML
     *
     * @return  string
     */
    public function __toString()
    {
        try {
            return $this->render();
        } catch (Exception $e) {
            return IcingaException::describe($e);
        }
    }
}