Passed
Push — master ( 4e3bf7...c9bf3c )
by Andreas
29:31
created

midcom_helper_toolbar::show_item()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
cc 1
eloc 2
nc 1
nop 1
dl 0
loc 4
ccs 0
cts 3
cp 0
crap 2
rs 10
c 0
b 0
f 0
1
<?php
2
/**
3
 * @package midcom.helper
4
 * @author The Midgard Project, http://www.midgard-project.org
5
 * @copyright The Midgard Project, http://www.midgard-project.org
6
 * @license http://www.gnu.org/licenses/lgpl.html GNU Lesser General Public License
7
 */
8
9
/**
10
 * This class is a generic toolbar class. It supports enabling
11
 * and disabling of buttons, icons and hover-helptexts (currently
12
 * rendered using TITLE tags).
13
 *
14
 * A single button in the toolbar is represented using an associative
15
 * array with the following elements:
16
 *
17
 * <code>
18
 * $item = [
19
 *     MIDCOM_TOOLBAR_URL => $url,
20
 *     MIDCOM_TOOLBAR_LABEL => $label,
21
 *     MIDCOM_TOOLBAR_HELPTEXT => $helptext,
22
 *     MIDCOM_TOOLBAR_ICON => $icon,
23
 *     MIDCOM_TOOLBAR_ENABLED => $enabled,
24
 *     MIDCOM_TOOLBAR_HIDDEN => $hidden
25
 *     MIDCOM_TOOLBAR_OPTIONS => array $options,
26
 *     MIDCOM_TOOLBAR_SUBMENU => midcom_helper_toolbar $submenu,
27
 *     MIDCOM_TOOLBAR_ACCESSKEY => (char) 'a',
28
 *     MIDCOM_TOOLBAR_POST => true,
29
 *     MIDCOM_TOOLBAR_POST_HIDDENARGS => array $args,
30
 * ];
31
 * </code>
32
 *
33
 * The URL parameter can be interpreted in three different ways:
34
 * If it is a relative URL (not starting with 'http[s]://' or at least
35
 * a '/') it will be interpreted relative to the current Anchor
36
 * Prefix as defined in the active MidCOM context. Otherwise, the URL
37
 * is used as-is. Note, that the Anchor-Prefix is appended immediately
38
 * when the item is added, not when the toolbar is rendered.
39
 *
40
 * The original URL (before prepending anything) is stored internally;
41
 * so in all places where you reference an element by-URL, you can use
42
 * the original URL if you wish (actually, both URLs are recognized
43
 * during the translation into an id).
44
 *
45
 * The label is the text shown as the button, the helptext is used as
46
 * TITLE value to the anchor, and will be shown when hovering over the
47
 * link therefore. Set it to null, to suppress this feature (this is the
48
 * default).
49
 *
50
 * The icon is a relative URL within the static MidCOM tree, for example
51
 * 'stock-icons/16x16/attach.png'. Set it to null, to suppress the display
52
 * of an icon (this is the default)
53
 *
54
 * By default, as shown below, the toolbar system renders a standard Hyperlink.
55
 * If you set MIDCOM_TOOLBAR_POST to true however, a form is used instead.
56
 * This is important if you want to provide operations directly behind the
57
 * toolbar entries - you'd run into problems with HTTP Link Prefetching
58
 * otherwise. It is also useful if you want to pass complex operations
59
 * to the URL target, as the option MIDCOM_TOOLBAR_POST_HIDDENARGS allows
60
 * you to add HIDDEN variables to the form. These arguments will be automatically
61
 * run through htmlspecialchars when rendering. By default, standard links will
62
 * be rendered, POST versions will only be used if explicitly requested.
63
 *
64
 * Note, that while this should prevent link prefetching on the POST entries,
65
 * this is a big should. Due to its lack of standardization, it is strongly
66
 * recommended to check for a POST request when processing such toolbar
67
 * targets, using something like this:
68
 *
69
 * <code>
70
 * if ($_SERVER['REQUEST_METHOD'] != 'post')
71
 * {
72
 *     throw new midcom_error_forbidden('Only POST requests are allowed here.');
73
 * }
74
 * </code>
75
 *
76
 * The enabled boolean flag is set to true (the default) if the link should
77
 * be clickable, or to false otherwise.
78
 *
79
 * The hidden boolean flag is very similar to the enabled one: Instead of
80
 * having unclickable links, it just hides the toolbar button entirely.
81
 * This is useful for access control checks, where you want to completely
82
 * hide items without access. The difference from just not adding the
83
 * corresponding variable is that you can have a consistent set of
84
 * toolbar options in a "template" which you just need to tweak by
85
 * setting this flag. (Note, that there is no explicit access
86
 * control checks in the toolbar helper itself, as this would mean that
87
 * the corresponding content objects need to be passed into the toolbar,
88
 * which is not feasible with the large number of toolbars in use in NAP
89
 * for example.)
90
 *
91
 * The midcom_toolbar_submenu can be used to create nested submenus by adding a pointer
92
 * to a new toolbar object.
93
 *
94
 * The toolbar gets rendered as an unordered list, letting you define the
95
 * CSS id and/or class tags of the list itself. The default class for
96
 * example used the well-known horizontal-UL approach to transform this
97
 * into a real toolbar. The output of the draw call therefore looks like
98
 * this:
99
 *
100
 * The <b>accesskey</b> option is used to assign an accesskey to the toolbar item.
101
 * It will be rendered in the toolbar text as either underlining the key or stated in
102
 * parentheses behind the text.
103
 *
104
 * <pre>
105
 * &lt;ul [class="$class"] [id="$id"]&gt;
106
 *   &lt;li class="(enabled|disabled)"&gt;
107
 *     [&lt;a href="$url" [title="$helptext"] [ $options as $key =&gt; $val ]&gt;]
108
 *       [&lt;img src="$calculated_image_url"&gt;]
109
 *       $label
110
 *      [new submenu here]
111
 *     [&lt;/a&gt;]
112
 *   &lt;/li&gt;
113
 * &lt;/ul&gt;
114
 * </pre>
115
 *
116
 * Both class and id can be null, indicating no style should be selected.
117
 * By default, the class will use "midcom_toolbar" and no id style, which
118
 * will yield a traditional MidCOM toolbar. Of course, the
119
 * style sheet must be loaded to support this. Note, that this style assumes
120
 * 16x16 height icons in its toolbar rendering. Larger or smaller icons
121
 * will look ugly in the layout.
122
 *
123
 * The options array. You can use the options array to make simple changes to the toolbar items.
124
 * Here's a quick example to remove the underlining.
125
 * <code>
126
 * foreach ($toolbar->items as $index => $item) {
127
 *     $toolbar->items[$index][MIDCOM_TOOLBAR_OPTIONS] = [ "style" => "text-decoration:none;"];
128
 * }
129
 * </code>
130
 * This will add style="text-decoration:none;" to all the links in the toolbar.
131
 *
132
 * @package midcom.helper
133
 */
134
class midcom_helper_toolbar
135
{
136
    /**
137
     * The CSS ID-Style rule that should be used for the toolbar.
138
     * Set to null if none should be used.
139
     *
140
     * @var string
141
     */
142
    public $id_style;
143
144
    /**
145
     * The CSS class-Style rule that should be used for the toolbar.
146
     * Set to null if none should be used.
147
     *
148
     * @var string
149
     */
150
    public $class_style;
151
152
    /**
153
     * The toolbar's label
154
     *
155
     * @var string
156
     */
157
    protected $label = '';
158
159
    /**
160
     * The items in the toolbar.
161
     *
162
     * The array consists of Arrays outlined in the class introduction.
163
     * You can modify existing items in this collection but you should use
164
     * the class methods to add or delete existing items. Also note that
165
     * relative URLs are processed upon the invocation of add_item(), if
166
     * you change URL manually, you have to ensure a valid URL by yourself
167
     * or use update_item_url, which is recommended.
168
     *
169
     * @var array
170
     */
171
    public $items = [];
172
173
    /**
174
     * Allow our users to add arbitrary data to the toolbar.
175
     *
176
     * This is for example used to track which items have been added to a toolbar
177
     * when it is possible that the adders are called repeatedly.
178
     *
179
     * The entries should be namespaced according to the usual MidCOM
180
     * Namespacing rules.
181
     *
182
     * @var array
183
     */
184
    public $customdata = [];
185
186
    private $rendered = false;
187
188
    /**
189
     * Basic constructor, initializes the class and sets defaults for the
190
     * CSS style if omitted.
191
     *
192
     * Note that the styles can be changed after construction by updating
193
     * the id_style and class_style members.
194
     */
195 348
    public function __construct(string $class_style = 'midcom_toolbar', string $id_style = null)
196
    {
197 348
        $this->id_style = $id_style;
198 348
        $this->class_style = $class_style;
199 348
    }
200
201 7
    public function is_rendered() : bool
202
    {
203 7
        return $this->rendered;
204
    }
205
206 7
    public function get_label() : string
207
    {
208 7
        return $this->label;
209
    }
210
211 52
    public function set_label(string $label)
212
    {
213 52
        $this->label = $label;
214 52
    }
215
216
    /**
217
     * Add a help item to the toolbar.
218
     */
219 2
    public function add_help_item(string $help_id, string $component = null, string $label = null, string $anchor = null, $before = -1)
220
    {
221 2
        $uri = "__ais/help/";
222 2
        if ($component !== null) {
223
            $uri .= $component . '/';
224
        }
225 2
        $uri .= $help_id . '/';
226
227 2
        if ($anchor !== null) {
228
            $uri .= "#{$anchor}";
229
        }
230
231 2
        if ($label === null) {
232 2
            $label = midcom::get()->i18n->get_string('help', 'midcom.admin.help');
233
        }
234
235 2
        $this->add_item([
236 2
            MIDCOM_TOOLBAR_URL => $uri,
237 2
            MIDCOM_TOOLBAR_LABEL => $label,
238 2
            MIDCOM_TOOLBAR_GLYPHICON => 'question',
239
            MIDCOM_TOOLBAR_OPTIONS => [
240
                'target' => '_blank',
241
            ]],
242
            $before
243
        );
244 2
    }
245
246
    /**
247
     * Add an item to the toolbar.
248
     *
249
     * Set before to the index of the element before which you want to insert
250
     * the item or use -1 if you want to append an item. Alternatively,
251
     * instead of specifying an index, you can specify a URL instead.
252
     *
253
     * This member will process the URL and append the anchor prefix in case
254
     * the URL is a relative one.
255
     *
256
     * Invalid positions will result in a MidCOM Error.
257
     *
258
     * @param mixed $before The index before which the item should be inserted.
259
     *     Use -1 for appending at the end, use a string to insert
260
     *     it before a URL, an integer will insert it before a
261
     *     given index.
262
     * @see midcom_helper_toolbar::get_index_from_url()
263
     * @see midcom_helper_toolbar::_check_index()
264
     * @see midcom_helper_toolbar::clean_item()
265
     */
266 187
    public function add_item(array $item, $before = -1)
267
    {
268 187
        if ($before != -1) {
269
            $before = $this->_check_index($before, false);
270
        }
271 187
        $item = $this->clean_item($item);
272
273 187
        if ($before == -1) {
274 187
            $this->items[] = $item;
275
        } elseif ($before == 0) {
276
            array_unshift($this->items, $item);
277
        } else {
278
            $start = array_slice($this->items, 0, $before - 1);
279
            $start[] = $item;
280
            $this->items = array_merge($start, array_slice($this->items, $before));
281
        }
282 187
    }
283
284
    /**
285
     * Convenience shortcut to add multiple buttons at the same item
286
     *
287
     * @param mixed $before The index before which the item should be inserted.
288
     *     Use -1 for appending at the end, use a string to insert
289
     *     it before a URL, an integer will insert it before a
290
     *     given index.
291
     */
292 128
    public function add_items(array $items, $before = -1)
293
    {
294 128
        foreach ($items as $item) {
295 123
            $this->add_item($item, $before);
296
        }
297 128
    }
298
299
    /**
300
     * Add an item to another item by either adding the item to the MIDCOM_TOOLBAR_SUBMENU
301
     * or creating a new subtoolbar and adding the item there.
302
     */
303
    public function add_item_to_index(array $item, int $index) : bool
304
    {
305
        $item = $this->clean_item($item);
306
        if (!array_key_exists($index, $this->items)) {
307
            debug_add("Insert of item {$item[MIDCOM_TOOLBAR_LABEL]} into index $index failed");
308
            return false;
309
        }
310
311
        if (empty($this->items[$index][MIDCOM_TOOLBAR_SUBMENU])) {
312
            $this->items[$index][MIDCOM_TOOLBAR_SUBMENU] = new midcom_helper_toolbar($this->class_style, $this->id_style);
313
        }
314
315
        $this->items[$index][MIDCOM_TOOLBAR_SUBMENU]->items[] = $item;
316
317
        return true;
318
    }
319
320
    /**
321
     * Clean up an item that is added, making sure that the item has all the
322
     * needed options and indexes.
323
     */
324 188
    public function clean_item(array $item) : array
325
    {
326 188
        static $used_access_keys = [];
327
328
        $defaults = [
329 188
            MIDCOM_TOOLBAR_URL => './',
330
            MIDCOM_TOOLBAR_OPTIONS => [],
331
            MIDCOM_TOOLBAR_HIDDEN => false,
332
            MIDCOM_TOOLBAR_HELPTEXT => '',
333
            MIDCOM_TOOLBAR_ICON => null,
334
            MIDCOM_TOOLBAR_GLYPHICON => null,
335
            MIDCOM_TOOLBAR_ENABLED => true,
336
            MIDCOM_TOOLBAR_POST => false,
337
            MIDCOM_TOOLBAR_POST_HIDDENARGS => [],
338
            MIDCOM_TOOLBAR_ACCESSKEY => null
339
        ];
340
341 188
        $item = array_replace($defaults, $item);
342
343 188
        if (   !empty($item[MIDCOM_TOOLBAR_ACCESSKEY])
344 188
            && !array_key_exists($item[MIDCOM_TOOLBAR_ACCESSKEY], $used_access_keys)) {
345
            // We have valid access key, add it to help text
346 9
            $prefix = 'Alt-';
347 9
            if (   isset($_SERVER['HTTP_USER_AGENT'])
348 9
                && strstr($_SERVER['HTTP_USER_AGENT'], 'Macintosh')) {
349
                // Mac users
350
                $prefix = 'Ctrl-Alt-';
351
            }
352 9
            $hotkey = $prefix . strtoupper($item[MIDCOM_TOOLBAR_ACCESSKEY]);
353
354 9
            if ($item[MIDCOM_TOOLBAR_HELPTEXT] == '') {
355 9
                $item[MIDCOM_TOOLBAR_HELPTEXT] = $hotkey;
356
            } else {
357
                $item[MIDCOM_TOOLBAR_HELPTEXT] .= " ({$hotkey})";
358
            }
359 9
            $used_access_keys[$item[MIDCOM_TOOLBAR_ACCESSKEY]] = true;
360
        }
361
362 188
        $this->set_url($item, $item[MIDCOM_TOOLBAR_URL]);
363 188
        return $item;
364
    }
365
366 188
    private function set_url(array &$item, string $url)
367
    {
368 188
        $item[MIDCOM_TOOLBAR__ORIGINAL_URL] = $url;
369 188
        if (   (   empty($item[MIDCOM_TOOLBAR_OPTIONS]["rel"])
370
                // Some items may want to keep their links unmutilated
371 188
                || $item[MIDCOM_TOOLBAR_OPTIONS]["rel"] != "directlink")
372 188
            && !str_starts_with($url, '/')
373 188
            && !preg_match('|^https?://|', $url)) {
374 160
            $url = midcom_core_context::get()->get_key(MIDCOM_CONTEXT_ANCHORPREFIX) . $url;
0 ignored issues
show
Bug introduced by
Are you sure midcom_core_context::get...M_CONTEXT_ANCHORPREFIX) of type false|mixed can be used in concatenation? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

374
            $url = /** @scrutinizer ignore-type */ midcom_core_context::get()->get_key(MIDCOM_CONTEXT_ANCHORPREFIX) . $url;
Loading history...
375
        }
376 188
        $item[MIDCOM_TOOLBAR_URL] = $url;
377 188
    }
378
379
    /**
380
     * Removes a toolbar item based on its index or its URL
381
     *
382
     * It will trigger a MidCOM Error upon an invalid index.
383
     *
384
     * @param mixed $index The (integer) index or URL to remove.
385
     * @see midcom_helper_toolbar::get_index_from_url()
386
     * @see midcom_helper_toolbar::_check_index()
387
     */
388 1
    public function remove_item($index)
389
    {
390 1
        $index = $this->_check_index($index);
391
392 1
        if ($index == 0) {
393
            array_shift($this->items);
394 1
        } elseif ($index == count($this->items) -1) {
395
            array_pop($this->items);
396
        } else {
397 1
            $this->items = array_merge(array_slice($this->items, 0, $index),
398 1
                array_slice($this->items, $index + 1));
399
        }
400 1
    }
401
402
    /**
403
     * Clears the complete toolbar.
404
     */
405
    public function remove_all_items()
406
    {
407
        $this->items = [];
408
    }
409
410
    /**
411
     * Moves an item on place upwards in the list.
412
     *
413
     * This will only work, of course, if you are not working with the top element.
414
     *
415
     * @param mixed $index The integer index or URL of the item to move upwards.
416
     */
417
    public function move_item_up($index)
418
    {
419
        if ($index == 0) {
420
            throw new midcom_error('Cannot move the top element upwards.');
421
        }
422
        $index = $this->_check_index($index);
423
424
        $tmp = $this->items[$index];
425
        $this->items[$index] = $this->items[$index - 1];
426
        $this->items[$index - 1] = $tmp;
427
    }
428
429
    /**
430
     * Moves an item on place downwards in the list.
431
     *
432
     * This will only work, of course, if you are not working with the bottom element.
433
     *
434
     * @param mixed $index The integer index or URL of the item to move downwards.
435
     */
436
    public function move_item_down($index)
437
    {
438
        if ($index == (count($this->items) - 1)) {
439
            throw new midcom_error('Cannot move the bottom element downwards.');
440
        }
441
        $index = $this->_check_index($index);
442
443
        $tmp = $this->items[$index];
444
        $this->items[$index] = $this->items[$index + 1];
445
        $this->items[$index + 1] = $tmp;
446
    }
447
448
    /**
449
     * Set's an item's enabled flag to true.
450
     *
451
     * @param mixed $index The integer index or URL of the item to enable.
452
     */
453
    public function enable_item($index)
454
    {
455
        $index = $this->_check_index($index);
456
        $this->items[$index][MIDCOM_TOOLBAR_ENABLED] = true;
457
    }
458
459
    /**
460
     * Set's an item's enabled flag to false.
461
     *
462
     * @param mixed $index The integer index or URL of the item to disable.
463
     */
464 12
    public function disable_item($index)
465
    {
466 12
        $index = $this->_check_index($index, false);
467
468 12
        if ($index !== null) {
469 12
            $this->items[$index][MIDCOM_TOOLBAR_ENABLED] = false;
470
        }
471 12
    }
472
473
    /**
474
     * Set's an item's hidden flag to true.
475
     *
476
     * @param mixed $index The integer index or URL of the item to hide.
477
     */
478 7
    public function hide_item($index)
479
    {
480 7
        $index = $this->_check_index($index, false);
481
482 7
        if ($index !== null) {
483 5
            $this->items[$index][MIDCOM_TOOLBAR_HIDDEN] = true;
484
        }
485 7
    }
486
487
    /**
488
     * Set's an item's hidden flag to false.
489
     *
490
     * @param mixed $index The integer index or URL of the item to show.
491
     */
492
    public function show_item($index)
493
    {
494
        $index = $this->_check_index($index);
495
        $this->items[$index][MIDCOM_TOOLBAR_HIDDEN] = false;
496
    }
497
498
    /**
499
     * Updates an items URL using the same rules as in add_item.
500
     *
501
     * @param mixed $index The integer index or URL of the item to update.
502
     * @see midcom_helper_toolbar::get_index_from_url()
503
     * @see midcom_helper_toolbar::_check_index()
504
     * @see midcom_helper_toolbar::add_item()
505
     */
506
    public function update_item_url($index, string $url)
507
    {
508
        $index = $this->_check_index($index);
509
        $this->set_url($this->items[$index], $url);
510
    }
511
512
    /**
513
     * Renders the toolbar and returns it as a string.
514
     */
515 20
    public function render() : string
516
    {
517
        $visible_items = array_filter($this->items, function ($item) {
518 15
            return !$item[MIDCOM_TOOLBAR_HIDDEN];
519 20
        });
520 20
        $this->rendered = true;
521
522 20
        if (empty($visible_items)) {
523 12
            debug_add('Tried to render an empty toolbar, returning an empty string.');
524 12
            return '';
525
        }
526
527
        // List header
528 15
        $output = '<ul';
529 15
        if ($this->class_style !== null) {
530 15
            $output .= " class='{$this->class_style}'";
531
        }
532 15
        if ($this->id_style !== null) {
533
            $output .= " id='{$this->id_style}'";
534
        }
535 15
        $output .= '>';
536
537 15
        $last = count($visible_items);
538 15
        $first_class = ($last === 1) ? 'only_item' : 'first_item';
539
        // List items
540 15
        foreach ($visible_items as $i => $item) {
541 15
            $output .= '<li class="';
542 15
            if ($i == 0) {
543 15
                $output .= $first_class . ' ';
544 13
            } elseif ($i == $last) {
545
                $output .= 'last_item ';
546
            }
547
548 15
            if ($item[MIDCOM_TOOLBAR_ENABLED]) {
549 15
                $output .= 'enabled">';
550
            } else {
551 11
                $output .= 'disabled">';
552
            }
553
554 15
            if ($item[MIDCOM_TOOLBAR_POST]) {
555
                $output .= $this->_render_post_item($item);
556
            } else {
557 15
                $output .= $this->_render_link_item($item);
558
            }
559
560 15
            $output .= '</li>';
561
        }
562
563
        // List footer
564 15
        $output .= '</ul>';
565
566 15
        return $output;
567
    }
568
569
    /**
570
     * Generate a label for the item that includes its accesskey
571
     */
572 15
    private function _generate_item_label(array $item) : string
573
    {
574 15
        $label = htmlentities($item[MIDCOM_TOOLBAR_LABEL], ENT_COMPAT, "UTF-8");
575
576 15
        if (!empty($item[MIDCOM_TOOLBAR_ACCESSKEY])) {
577
            // Try finding uppercase version of the accesskey first
578 8
            $accesskey = strtoupper($item[MIDCOM_TOOLBAR_ACCESSKEY]);
579 8
            $position = strpos($label, $accesskey);
580 8
            if (   $position === false
581 8
                && midcom::get()->i18n->get_current_language() == 'en') {
582
                // Try lowercase, too
583 7
                $accesskey = strtolower($accesskey);
584 7
                $position = strpos($label, $accesskey);
585
            }
586 8
            if ($position !== false) {
587 8
                $label = substr_replace($label, "<span style=\"text-decoration: underline;\">{$accesskey}</span>", $position, 1);
588
            }
589
        }
590
591 15
        return $label;
592
    }
593
594
    /**
595
     * Render a regular a href... based link target.
596
     */
597 15
    private function _render_link_item(array $item) : string
598
    {
599 15
        $attributes = $this->get_item_attributes($item);
600
601 15
        if ($item[MIDCOM_TOOLBAR_ENABLED]) {
602 15
            $tagname = 'a';
603 15
            $attributes['href'] = $item[MIDCOM_TOOLBAR_URL];
604
        } else {
605 11
            $tagname = !empty($attributes['title']) ? 'abbr' : 'span';
606
        }
607
608 15
        $output = '<' . $tagname;
609 15
        foreach ($attributes as $key => $val) {
610 15
            $output .= ' ' . $key . '="' . htmlspecialchars($val) . '"';
611
        }
612 15
        $output .= '>';
613
614 15
        if ($item[MIDCOM_TOOLBAR_GLYPHICON] !== null) {
615 15
            $class = 'fa fa-' . $item[MIDCOM_TOOLBAR_GLYPHICON];
616 15
            $output .= "<i class='{$class}'></i>";
617
        } elseif ($item[MIDCOM_TOOLBAR_ICON] !== null) {
618
            $url = MIDCOM_STATIC_URL . '/' . $item[MIDCOM_TOOLBAR_ICON];
619
            $output .= "<img src='{$url}' alt=\"{$item[MIDCOM_TOOLBAR_HELPTEXT]}\" />";
620
        }
621
622 15
        $output .= '&nbsp;<span class="toolbar_label">' . $this->_generate_item_label($item) . "</span>";
623 15
        $output .= '</' . $tagname . '>';
624
625 15
        if (!empty($item[MIDCOM_TOOLBAR_SUBMENU])) {
626
            $output .= $item[MIDCOM_TOOLBAR_SUBMENU]->render();
627
        }
628
629 15
        return $output;
630
    }
631
632 15
    private function get_item_attributes(array $item) : array
633
    {
634 15
        $attributes = ($item[MIDCOM_TOOLBAR_ENABLED]) ? $item[MIDCOM_TOOLBAR_OPTIONS] : [];
635
636 15
        if ($item[MIDCOM_TOOLBAR_HELPTEXT] !== null) {
637 15
            $attributes['title'] = $item[MIDCOM_TOOLBAR_HELPTEXT];
638
        }
639
640 15
        if (   $item[MIDCOM_TOOLBAR_ENABLED]
641 15
            && $item[MIDCOM_TOOLBAR_ACCESSKEY] !== null) {
642 8
            $attributes['class'] = 'accesskey';
643 8
            $attributes['accesskey'] = $item[MIDCOM_TOOLBAR_ACCESSKEY];
644
        }
645 15
        return $attributes;
646
    }
647
648
    /**
649
     * Render a form based link target.
650
     */
651
    private function _render_post_item(array $item) : string
652
    {
653
        $output = '';
654
655
        if ($item[MIDCOM_TOOLBAR_ENABLED]) {
656
            $output .= "<form method=\"post\" action=\"{$item[MIDCOM_TOOLBAR_URL]}\">";
657
            $output .= "<div><button type=\"submit\" name=\"midcom_helper_toolbar_submit\"";
658
659
            foreach ($this->get_item_attributes($item) as $key => $val) {
660
                $output .= ' ' . $key . '="' . htmlspecialchars($val) . '"';
661
            }
662
            $output .= '>';
663
        }
664
665
        if ($item[MIDCOM_TOOLBAR_GLYPHICON] !== null) {
666
            $class = 'fa fa-' . $item[MIDCOM_TOOLBAR_GLYPHICON];
667
            $output .= "<i class='{$class}'></i>";
668
        } elseif ($item[MIDCOM_TOOLBAR_ICON]) {
669
            $url = MIDCOM_STATIC_URL . "/{$item[MIDCOM_TOOLBAR_ICON]}";
670
            $output .= "<img src=\"{$url}\" alt=\"{$item[MIDCOM_TOOLBAR_HELPTEXT]}\" />";
671
        }
672
673
        $label = $this->_generate_item_label($item);
674
        $output .= " {$label}";
675
676
        if ($item[MIDCOM_TOOLBAR_ENABLED]) {
677
            $output .= '</button>';
678
            foreach ($item[MIDCOM_TOOLBAR_POST_HIDDENARGS] as $key => $value) {
679
                $key = htmlspecialchars($key);
680
                $value = htmlspecialchars($value);
681
                $output .= "<input type=\"hidden\" name=\"{$key}\" value=\"{$value}\"/>";
682
            }
683
            $output .= '</div></form>';
684
        }
685
686
        if (!empty($item[MIDCOM_TOOLBAR_SUBMENU])) {
687
            $output .= $item[MIDCOM_TOOLBAR_SUBMENU]->render();
688
        }
689
690
        return $output;
691
    }
692
693
    /**
694
     * Traverse all available items and return the first
695
     * element whose URL matches the value passed to the function.
696
     *
697
     * Note, that if two items point to the same URL, only the first one
698
     * will be reported.
699
     */
700 19
    public function get_index_from_url(string $url) : ?int
701
    {
702 19
        foreach ($this->items as $i => $item) {
703 17
            if (   $item[MIDCOM_TOOLBAR_URL] == $url
704 17
                || $item[MIDCOM_TOOLBAR__ORIGINAL_URL] == $url) {
705 17
                return $i;
706
            }
707
        }
708 2
        return null;
709
    }
710
711
    /**
712
     * Check an index for validity.
713
     *
714
     * It will automatically convert a string-based URL into an
715
     * Index (if possible); if the URL can't be found, it will
716
     * also trigger an error. The translated URL is returned by the
717
     * function.
718
     *
719
     * @param mixed $index The integer index or URL to check
720
     */
721 20
    protected function _check_index($index, bool $raise_error = true) :?int
722
    {
723 20
        if (is_string($index)) {
724 19
            $url = $index;
725 19
            debug_add("Translating the URL '{$url}' into an index.");
726 19
            $index = $this->get_index_from_url($url);
727 19
            if ($index === null) {
728 2
                debug_add("Invalid URL '{$url}', URL not found.", MIDCOM_LOG_ERROR);
729
730 2
                if ($raise_error) {
731
                    throw new midcom_error("Invalid URL '{$url}', URL not found.");
732
                }
733 2
                return null;
734
            }
735
        }
736 18
        if ($index >= count($this->items)) {
737
            throw new midcom_error("Invalid index {$index}, it is off-the-end.");
738
        }
739 18
        if ($index < 0) {
740
            throw new midcom_error("Invalid index {$index}, it is negative.");
741
        }
742 18
        return $index;
743
    }
744
745
    /**
746
     * Binds this toolbar instance to a DBA content object using the MidCOM toolbar service.
747
     *
748
     * @see midcom_services_toolbars
749
     */
750 52
    public function bind_to(midcom_core_dbaobject $object)
751
    {
752 52
        midcom::get()->toolbars->bind_toolbar_to_object($this, $object);
753 52
    }
754
}
755