Passed
Push — master ( 409c3f...e5371a )
by Andreas
09:22
created

midcom_helper_toolbar::update_item_url()   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 2
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
    public ?string $id_style;
141
142
    /**
143
     * The CSS class-Style rule that should be used for the toolbar.
144
     * Set to null if none should be used.
145
     */
146
    public string $class_style;
147
148
    /**
149
     * The toolbar's label
150
     */
151
    protected string $label = '';
152
153
    /**
154
     * The items in the toolbar.
155
     *
156
     * The array consists of Arrays outlined in the class introduction.
157
     * You can modify existing items in this collection but you should use
158
     * the class methods to add or delete existing items. Also note that
159
     * relative URLs are processed upon the invocation of add_item(), if
160
     * you change URL manually, you have to ensure a valid URL by yourself
161
     * or use update_item_url, which is recommended.
162
     */
163
    public array $items = [];
164
165
    /**
166
     * Allow our users to add arbitrary data to the toolbar.
167
     *
168
     * This is for example used to track which items have been added to a toolbar
169
     * when it is possible that the adders are called repeatedly.
170
     *
171
     * The entries should be namespaced according to the usual MidCOM
172
     * Namespacing rules.
173
     */
174
    public array $customdata = [];
175
176
    private bool $rendered = false;
177
178
    /**
179
     * Basic constructor, initializes the class and sets defaults for the
180
     * CSS style if omitted.
181
     *
182
     * Note that the styles can be changed after construction by updating
183
     * the id_style and class_style members.
184
     */
185 350
    public function __construct(string $class_style = 'midcom_toolbar', string $id_style = null)
186
    {
187 350
        $this->id_style = $id_style;
188 350
        $this->class_style = $class_style;
189
    }
190
191 7
    public function is_rendered() : bool
192
    {
193 7
        return $this->rendered;
194
    }
195
196 7
    public function get_label() : string
197
    {
198 7
        return $this->label;
199
    }
200
201 52
    public function set_label(string $label)
202
    {
203 52
        $this->label = $label;
204
    }
205
206
    /**
207
     * Add a help item to the toolbar.
208
     */
209 2
    public function add_help_item(string $help_id, string $component = null, string $label = null, string $anchor = null, $before = -1)
210
    {
211 2
        $uri = "__ais/help/";
212 2
        if ($component !== null) {
213
            $uri .= $component . '/';
214
        }
215 2
        $uri .= $help_id . '/';
216
217 2
        if ($anchor !== null) {
218
            $uri .= "#{$anchor}";
219
        }
220
221 2
        $label ??= midcom::get()->i18n->get_string('help', 'midcom.admin.help');
222
223 2
        $this->add_item([
224 2
            MIDCOM_TOOLBAR_URL => $uri,
225 2
            MIDCOM_TOOLBAR_LABEL => $label,
226 2
            MIDCOM_TOOLBAR_GLYPHICON => 'question',
227 2
            MIDCOM_TOOLBAR_OPTIONS => [
228 2
                'target' => '_blank',
229 2
            ]],
230 2
            $before
231 2
        );
232
    }
233
234
    /**
235
     * Add an item to the toolbar.
236
     *
237
     * Set before to the index of the element before which you want to insert
238
     * the item or use -1 if you want to append an item. Alternatively,
239
     * instead of specifying an index, you can specify a URL instead.
240
     *
241
     * This member will process the URL and append the anchor prefix in case
242
     * the URL is a relative one.
243
     *
244
     * Invalid positions will result in a MidCOM Error.
245
     *
246
     * @param mixed $before The index before which the item should be inserted.
247
     *     Use -1 for appending at the end, use a string to insert
248
     *     it before a URL, an integer will insert it before a
249
     *     given index.
250
     * @see midcom_helper_toolbar::get_index_from_url()
251
     * @see midcom_helper_toolbar::_check_index()
252
     * @see midcom_helper_toolbar::clean_item()
253
     */
254 188
    public function add_item(array $item, $before = -1)
255
    {
256 188
        if ($before != -1) {
257 1
            $before = $this->_check_index($before, false);
258
        }
259 188
        $item = $this->clean_item($item);
260
261 188
        if ($before == -1) {
262 188
            $this->items[] = $item;
263 1
        } elseif ($before == 0) {
264 1
            array_unshift($this->items, $item);
265
        } else {
266 1
            $start = array_slice($this->items, 0, $before);
267 1
            $start[] = $item;
268 1
            $this->items = array_merge($start, array_slice($this->items, $before));
269
        }
270
    }
271
272
    /**
273
     * Convenience shortcut to add multiple buttons at the same item
274
     *
275
     * @param mixed $before The index before which the item should be inserted.
276
     *     Use -1 for appending at the end, use a string to insert
277
     *     it before a URL, an integer will insert it before a
278
     *     given index.
279
     */
280 128
    public function add_items(array $items, $before = -1)
281
    {
282 128
        foreach ($items as $item) {
283 123
            $this->add_item($item, $before);
284
        }
285
    }
286
287
    /**
288
     * Add an item to another item by either adding the item to the MIDCOM_TOOLBAR_SUBMENU
289
     * or creating a new subtoolbar and adding the item there.
290
     */
291
    public function add_item_to_index(array $item, int $index) : bool
292
    {
293
        $item = $this->clean_item($item);
294
        if (!array_key_exists($index, $this->items)) {
295
            debug_add("Insert of item {$item[MIDCOM_TOOLBAR_LABEL]} into index $index failed");
296
            return false;
297
        }
298
299
        $this->items[$index][MIDCOM_TOOLBAR_SUBMENU] ??= new midcom_helper_toolbar($this->class_style, $this->id_style);
300
        $this->items[$index][MIDCOM_TOOLBAR_SUBMENU]->items[] = $item;
301
302
        return true;
303
    }
304
305
    /**
306
     * Clean up an item that is added, making sure that the item has all the
307
     * needed options and indexes.
308
     */
309 189
    public function clean_item(array $item) : array
310
    {
311 189
        static $used_access_keys = [];
312
313 189
        $defaults = [
314 189
            MIDCOM_TOOLBAR_URL => './',
315 189
            MIDCOM_TOOLBAR_OPTIONS => [],
316 189
            MIDCOM_TOOLBAR_HIDDEN => false,
317 189
            MIDCOM_TOOLBAR_HELPTEXT => '',
318 189
            MIDCOM_TOOLBAR_ICON => null,
319 189
            MIDCOM_TOOLBAR_GLYPHICON => null,
320 189
            MIDCOM_TOOLBAR_ENABLED => true,
321 189
            MIDCOM_TOOLBAR_POST => false,
322 189
            MIDCOM_TOOLBAR_POST_HIDDENARGS => [],
323 189
            MIDCOM_TOOLBAR_ACCESSKEY => null
324 189
        ];
325
326 189
        $item = array_replace($defaults, $item);
327
328 189
        if (   !empty($item[MIDCOM_TOOLBAR_ACCESSKEY])
329 189
            && !array_key_exists($item[MIDCOM_TOOLBAR_ACCESSKEY], $used_access_keys)) {
330
            // We have valid access key, add it to help text
331 6
            $prefix = 'Alt-';
332 6
            if (str_contains($_SERVER['HTTP_USER_AGENT'] ?? '', 'Macintosh')) {
333
                // Mac users
334
                $prefix = 'Ctrl-Alt-';
335
            }
336 6
            $hotkey = $prefix . strtoupper($item[MIDCOM_TOOLBAR_ACCESSKEY]);
337
338 6
            if ($item[MIDCOM_TOOLBAR_HELPTEXT] == '') {
339 6
                $item[MIDCOM_TOOLBAR_HELPTEXT] = $hotkey;
340
            } else {
341
                $item[MIDCOM_TOOLBAR_HELPTEXT] .= " ({$hotkey})";
342
            }
343 6
            $used_access_keys[$item[MIDCOM_TOOLBAR_ACCESSKEY]] = true;
344
        }
345
346 189
        $this->set_url($item, $item[MIDCOM_TOOLBAR_URL]);
347 189
        return $item;
348
    }
349
350 189
    private function set_url(array &$item, string $url)
351
    {
352 189
        $item[MIDCOM_TOOLBAR__ORIGINAL_URL] = $url;
353 189
        if (   (   empty($item[MIDCOM_TOOLBAR_OPTIONS]["rel"])
354
                // Some items may want to keep their links unmutilated
355 189
                || $item[MIDCOM_TOOLBAR_OPTIONS]["rel"] != "directlink")
356 189
            && !str_starts_with($url, '/')
357 189
            && !preg_match('|^https?://|', $url)) {
358 161
            $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

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