summaryrefslogtreecommitdiffstats
path: root/library/Icinga/Web/Navigation/NavigationItem.php
blob: e262f5af005c30524e341ec7bada87bd796b4c4b (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
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
<?php
/* Icinga Web 2 | (c) 2015 Icinga Development Team | GPLv2+ */

namespace Icinga\Web\Navigation;

use Exception;
use Icinga\Authentication\Auth;
use InvalidArgumentException;
use IteratorAggregate;
use Icinga\Application\Icinga;
use Icinga\Application\Logger;
use Icinga\Exception\IcingaException;
use Icinga\Exception\ProgrammingError;
use Icinga\Web\Navigation\Renderer\NavigationItemRenderer;
use Icinga\Web\Url;
use Traversable;

/**
 * A navigation item
 */
class NavigationItem implements IteratorAggregate
{
    /**
     * Alternative markup element for items without a url
     *
     * @var string
     */
    const LINK_ALTERNATIVE = 'span';

    /**
     * The class namespace where to locate navigation type renderer classes
     */
    const RENDERER_NS = 'Web\\Navigation\\Renderer';

    /**
     * Whether this item is active
     *
     * @var bool
     */
    protected $active;

    /**
     * Whether this item is selected
     *
     * @var bool
     */
    protected $selected;

    /**
     * The CSS class used for the outer li element
     *
     * @var string
     */
    protected $cssClass;

    /**
     * This item's priority
     *
     * The priority defines when the item is rendered in relation to its parent's childs.
     *
     * @var int
     */
    protected $priority;

    /**
     * The attributes of this item's element
     *
     * @var array
     */
    protected $attributes;

    /**
     * This item's children
     *
     * @var Navigation
     */
    protected $children;

    /**
     * This item's icon
     *
     * @var string
     */
    protected $icon;

    /**
     * This item's name
     *
     * @var string
     */
    protected $name;

    /**
     * This item's label
     *
     * @var string
     */
    protected $label;

    /**
     * The item's description
     *
     * @var string
     */
    protected $description;

    /**
     * This item's parent
     *
     * @var NavigationItem
     */
    protected $parent;

    /**
     * This item's url
     *
     * @var Url
     */
    protected $url;

    /**
     * This item's url target
     *
     * @var string
     */
    protected $target;

    /**
     * Additional parameters for this item's url
     *
     * @var array
     */
    protected $urlParameters;

    /**
     * This item's renderer
     *
     * @var NavigationItemRenderer
     */
    protected $renderer;

    /**
     * Whether to render this item
     *
     * @var bool
     */
    protected $render;

    /**
     * Create a new NavigationItem
     *
     * @param   string  $name
     * @param   array   $properties
     */
    public function __construct($name, array $properties = null)
    {
        $this->setName($name);
        $this->children = new Navigation();

        if (! empty($properties)) {
            $this->setProperties($properties);
        }

        $this->init();
    }

    /**
     * Initialize this NavigationItem
     */
    public function init()
    {
    }

    /**
     * @return Navigation
     */
    public function getIterator(): Traversable
    {
        return $this->getChildren();
    }

    /**
     * Return whether this item is active
     *
     * @return  bool
     */
    public function getActive()
    {
        if ($this->active === null) {
            $this->active = false;
            if ($this->getUrl() !== null && Icinga::app()->getRequest()->getUrl()->matches($this->getUrl())) {
                $this->setActive();
            } elseif ($this->hasChildren()) {
                foreach ($this->getChildren() as $item) {
                    /** @var NavigationItem $item */
                    if ($item->getActive()) {
                        // Do nothing, a true active state is automatically passed to all parents
                    }
                }
            }
        }

        return $this->active;
    }

    /**
     * Set whether this item is active
     *
     * If it's active and has a parent, the parent gets activated as well.
     *
     * @param   bool    $active
     *
     * @return  $this
     */
    public function setActive($active = true)
    {
        $this->active = (bool) $active;
        if ($this->active && $this->getParent() !== null) {
            $this->getParent()->setActive();
        }

        return $this;
    }

    /**
     * Return whether this item is selected
     *
     * @return  bool
     */
    public function getSelected()
    {
        if ($this->selected === null) {
            $this->active = false;
            if ($this->getUrl() !== null && Icinga::app()->getRequest()->getUrl()->matches($this->getUrl())) {
                $this->setSelected();
            }
        }

        return $this->selected;
    }

    /**
     * Set whether this item is active
     *
     * If it's active and has a parent, the parent gets activated as well.
     *
     * @param   bool    $selected
     *
     * @return  $this
     */
    public function setSelected($selected = true)
    {
        $this->selected = (bool) $selected;

        return $this;
    }

    /**
     * Get the CSS class used for the outer li element
     *
     * @return  string
     */
    public function getCssClass()
    {
        return $this->cssClass;
    }

    /**
     * Set the CSS class to use for the outer li element
     *
     * @param   string  $class
     *
     * @return  $this
     */
    public function setCssClass($class)
    {
        $this->cssClass = (string) $class;
        return $this;
    }

    /**
     * Return this item's priority
     *
     * @return  int
     */
    public function getPriority()
    {
        return $this->priority !== null ? $this->priority : 100;
    }

    /**
     * Set this item's priority
     *
     * @param   int     $priority
     *
     * @return  $this
     */
    public function setPriority($priority)
    {
        $this->priority = (int) $priority;
        return $this;
    }

    /**
     * Return the value of the given element attribute
     *
     * @param   string  $name
     * @param   mixed   $default
     *
     * @return  mixed
     */
    public function getAttribute($name, $default = null)
    {
        $attributes = $this->getAttributes();
        return array_key_exists($name, $attributes) ? $attributes[$name] : $default;
    }

    /**
     * Set the value of the given element attribute
     *
     * @param   string  $name
     * @param   mixed   $value
     *
     * @return  $this
     */
    public function setAttribute($name, $value)
    {
        $this->attributes[$name] = $value;
        return $this;
    }

    /**
     * Return the attributes of this item's element
     *
     * @return  array
     */
    public function getAttributes()
    {
        return $this->attributes ?: array();
    }

    /**
     * Set the attributes of this item's element
     *
     * @param   array   $attributes
     *
     * @return  $this
     */
    public function setAttributes(array $attributes)
    {
        $this->attributes = $attributes;
        return $this;
    }

    /**
     * Add a child to this item
     *
     * If the child is active this item gets activated as well.
     *
     * @param   NavigationItem  $child
     *
     * @return  $this
     */
    public function addChild(NavigationItem $child)
    {
        $this->getChildren()->addItem($child->setParent($this));
        if ($child->getActive()) {
            $this->setActive();
        }

        return $this;
    }

    /**
     * Return this item's children
     *
     * @return  Navigation
     */
    public function getChildren()
    {
        return $this->children;
    }

    /**
     * Return whether this item has any children
     *
     * @return  bool
     */
    public function hasChildren()
    {
        return ! $this->getChildren()->isEmpty();
    }

    /**
     * Set this item's children
     *
     * @param   array|Navigation  $children
     *
     * @return  $this
     */
    public function setChildren($children)
    {
        if (is_array($children)) {
            $children = Navigation::fromArray($children);
        } elseif (! $children instanceof Navigation) {
            throw new InvalidArgumentException('Argument $children must be of type array or Navigation');
        }

        foreach ($children as $item) {
            $item->setParent($this);
        }

        $this->children = $children;
        return $this;
    }

    /**
     * Return this item's icon
     *
     * @return  string
     */
    public function getIcon()
    {
        return $this->icon;
    }

    /**
     * Set this item's icon
     *
     * @param   string  $icon
     *
     * @return  $this
     */
    public function setIcon($icon)
    {
        $this->icon = $icon;
        return $this;
    }

    /**
     * Return this item's name escaped with only ASCII chars and/or digits
     *
     * @return  string
     */
    protected function getEscapedName()
    {
        return preg_replace('~[^a-zA-Z0-9]~', '_', $this->getName());
    }

    /**
     * Return a unique version of this item's name
     *
     * @return  string
     */
    public function getUniqueName()
    {
        if ($this->getParent() === null) {
            return 'navigation-' . $this->getEscapedName();
        }

        return $this->getParent()->getUniqueName() . '-' . $this->getEscapedName();
    }

    /**
     * Return this item's name
     *
     * @return  string
     */
    public function getName()
    {
        return $this->name;
    }

    /**
     * Set this item's name
     *
     * @param   string  $name
     *
     * @return  $this
     */
    public function setName($name)
    {
        $this->name = $name;
        return $this;
    }

    /**
     * Set this item's parent
     *
     * @param   NavigationItem  $parent
     *
     * @return  $this
     */
    public function setParent(NavigationItem $parent)
    {
        $this->parent = $parent;
        return $this;
    }

    /**
     * Return this item's parent
     *
     * @return  NavigationItem
     */
    public function getParent()
    {
        return $this->parent;
    }

    /**
     * Return this item's label
     *
     * @return  string
     */
    public function getLabel()
    {
        return $this->label !== null ? $this->label : $this->getName();
    }

    /**
     * Set this item's label
     *
     * @param   string  $label
     *
     * @return  $this
     */
    public function setLabel($label)
    {
        $this->label = $label;
        return $this;
    }

    /**
     * Get the item's description
     *
     * @return  string
     */
    public function getDescription()
    {
        return $this->description;
    }

    /**
     * Set the item's description
     *
     * @param   string  $description
     *
     * @return  $this
     */
    public function setDescription($description)
    {
        $this->description = $description;

        return $this;
    }

    /**
     * Set this item's url target
     *
     * @param   string  $target
     *
     * @return  $this
     */
    public function setTarget($target)
    {
        $this->target = $target;
        return $this;
    }

    /**
     * Return this item's url target
     *
     * @return  string
     */
    public function getTarget()
    {
        return $this->target;
    }

    /**
     * Return this item's url
     *
     * @return  Url
     */
    public function getUrl()
    {
        if ($this->url === null && $this->hasChildren()) {
            $this->setUrl(Url::fromPath('navigation/dashboard', array('name' => strtolower($this->getName()))));
        }

        return $this->url;
    }

    /**
     * Set this item's url
     *
     * @param   Url|string  $url
     *
     * @return  $this
     *
     * @throws  InvalidArgumentException    If the given url is neither of type
     */
    public function setUrl($url)
    {
        if (is_string($url)) {
            $url = Url::fromPath($this->resolveMacros($url));
        } elseif ($url instanceof Url) {
            $url = Url::fromPath($this->resolveMacros($url->getAbsoluteUrl()));
        } else {
            throw new InvalidArgumentException('Argument $url must be of type string or Url');
        }

        $this->url = $url;

        return $this;
    }

    /**
     * Return the value of the given url parameter
     *
     * @param   string  $name
     * @param   mixed   $default
     *
     * @return  mixed
     */
    public function getUrlParameter($name, $default = null)
    {
        $parameters = $this->getUrlParameters();
        return isset($parameters[$name]) ? $parameters[$name] : $default;
    }

    /**
     * Set the value of the given url parameter
     *
     * @param   string  $name
     * @param   mixed   $value
     *
     * @return  $this
     */
    public function setUrlParameter($name, $value)
    {
        $this->urlParameters[$name] = $value;
        return $this;
    }

    /**
     * Return all additional parameters for this item's url
     *
     * @return  array
     */
    public function getUrlParameters()
    {
        return $this->urlParameters ?: array();
    }

    /**
     * Set additional parameters for this item's url
     *
     * @param   array   $urlParameters
     *
     * @return  $this
     */
    public function setUrlParameters(array $urlParameters)
    {
        $this->urlParameters = $urlParameters;
        return $this;
    }

    /**
     * Set this item's properties
     *
     * Unknown properties (no matching setter) are considered as element attributes.
     *
     * @param   array   $properties
     *
     * @return  $this
     */
    public function setProperties(array $properties)
    {
        foreach ($properties as $name => $value) {
            $setter = 'set' . ucfirst($name);
            if (method_exists($this, $setter)) {
                $this->$setter($value);
            } else {
                $this->setAttribute($name, $value);
            }
        }

        return $this;
    }

    /**
     * Merge this item with the given one
     *
     * @param   NavigationItem  $item
     *
     * @return  $this
     */
    public function merge(NavigationItem $item)
    {
        if ($this->conflictsWith($item)) {
            throw new ProgrammingError('Cannot merge, conflict detected.');
        }

        if ($this->priority === null) {
            $priority = $item->getPriority();
            if ($priority !== 100) {
                $this->setPriority($priority);
            }
        }

        if (! $this->getIcon()) {
            $this->setIcon($item->getIcon());
        }

        if ($this->getLabel() === $this->getName() && $item->getLabel() !== $item->getName()) {
            $this->setLabel($item->getLabel());
        }

        if ($this->target === null && ($target = $item->getTarget()) !== null) {
            $this->setTarget($target);
        }

        if ($this->renderer === null) {
            $renderer = $item->getRenderer();
            if (get_class($renderer) !== 'NavigationItemRenderer') {
                $this->setRenderer($renderer);
            }
        }

        foreach ($item->getAttributes() as $name => $value) {
            $this->setAttribute($name, $value);
        }

        foreach ($item->getUrlParameters() as $name => $value) {
            $this->setUrlParameter($name, $value);
        }

        if ($item->hasChildren()) {
            $this->getChildren()->merge($item->getChildren());
        }

        return $this;
    }

    /**
     * Return whether it's possible to merge this item with the given one
     *
     * @param   NavigationItem  $item
     *
     * @return  bool
     */
    public function conflictsWith(NavigationItem $item)
    {
        if (! $item instanceof $this) {
            return true;
        }

        if ($this->getUrl() === null || $item->getUrl() === null) {
            return false;
        }

        return !$this->getUrl()->matches($item->getUrl());
    }

    /**
     * Create and return the given renderer
     *
     * @param   string|array    $name
     *
     * @return  NavigationItemRenderer
     */
    protected function createRenderer($name)
    {
        if (is_array($name)) {
            $options = array_splice($name, 1);
            $name = $name[0];
        } else {
            $options = array();
        }

        $renderer = null;
        foreach (Icinga::app()->getModuleManager()->getLoadedModules() as $module) {
            $classPath = 'Icinga\\Module\\' . ucfirst($module->getName()) . '\\' . static::RENDERER_NS . '\\' . $name;
            if (class_exists($classPath)) {
                $renderer = new $classPath($options);
                break;
            }
        }

        if ($renderer === null) {
            $classPath = 'Icinga\\' . static::RENDERER_NS . '\\' . $name;
            if (class_exists($classPath)) {
                $renderer = new $classPath($options);
            }
        }

        if ($renderer === null) {
            throw new ProgrammingError(
                'Cannot find renderer "%s" for navigation item "%s"',
                $name,
                $this->getName()
            );
        } elseif (! $renderer instanceof NavigationItemRenderer) {
            throw new ProgrammingError('Class %s must inherit from NavigationItemRenderer', $classPath);
        }

        return $renderer;
    }

    /**
     * Set this item's renderer
     *
     * @param   string|array|NavigationItemRenderer     $renderer
     *
     * @return  $this
     *
     * @throws  InvalidArgumentException    If the $renderer argument is neither a string nor a NavigationItemRenderer
     */
    public function setRenderer($renderer)
    {
        if (is_string($renderer) || is_array($renderer)) {
            $renderer = $this->createRenderer($renderer);
        } elseif (! $renderer instanceof NavigationItemRenderer) {
            throw new InvalidArgumentException(
                'Argument $renderer must be of type string, array or NavigationItemRenderer'
            );
        }

        $this->renderer = $renderer;
        return $this;
    }

    /**
     * Return this item's renderer
     *
     * @return  NavigationItemRenderer
     */
    public function getRenderer()
    {
        if ($this->renderer === null) {
            $this->setRenderer('NavigationItemRenderer');
        }

        return $this->renderer;
    }

    /**
     * Set whether this item should be rendered
     *
     * @param   bool    $state
     *
     * @return  $this
     */
    public function setRender($state = true)
    {
        $this->render = (bool) $state;
        return $this;
    }

    /**
     * Return whether this item should be rendered
     *
     * @return  bool
     */
    public function getRender()
    {
        if ($this->render === null) {
            return $this->getUrl() !== null;
        }

        return $this->render;
    }

    /**
     * Return whether this item should be rendered
     *
     * Alias for NavigationItem::getRender().
     *
     * @return  bool
     */
    public function shouldRender()
    {
        return $this->getRender();
    }

    /**
     * Return this item rendered to HTML
     *
     * @return  string
     */
    public function render()
    {
        try {
            return $this->getRenderer()->setItem($this)->render();
        } catch (Exception $e) {
            Logger::error(
                'Could not invoke custom navigation item renderer. %s in %s:%d with message: %s',
                get_class($e),
                $e->getFile(),
                $e->getLine(),
                $e->getMessage()
            );

            $renderer = new NavigationItemRenderer();
            return $renderer->render($this);
        }
    }

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

    /**
     * Resolve all macros in the given URL
     *
     * @param string $url
     *
     * @return  string
     */
    protected function resolveMacros($url)
    {
        if (strpos($url, '$') === false) {
            return $url;
        }

        $macros = [];
        if (Auth::getInstance()->isAuthenticated()) {
            $macros['$user.local_name$'] = Auth::getInstance()->getUser()->getLocalUsername();
        }
        if (! empty($macros)) {
            $url = str_replace(array_keys($macros), array_values($macros), $url);
        }

        return $url;
    }
}