Passed
Push — master ( 017701...122834 )
by Andreas
28:26
created

midcom_helper_toolbar::_render_post_item()   B

Complexity

Conditions 8
Paths 24

Size

Total Lines 40
Code Lines 25

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 72

Importance

Changes 0
Metric Value
cc 8
eloc 25
nc 24
nop 1
dl 0
loc 40
ccs 0
cts 26
cp 0
crap 72
rs 8.4444
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 350
    public function __construct(string $class_style = 'midcom_toolbar', string $id_style = null)
196
    {
197 350
        $this->id_style = $id_style;
198 350
        $this->class_style = $class_style;
199
    }
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
    }
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
            MIDCOM_TOOLBAR_URL => $uri,
237
            MIDCOM_TOOLBAR_LABEL => $label,
238
            MIDCOM_TOOLBAR_GLYPHICON => 'question',
239
            MIDCOM_TOOLBAR_OPTIONS => [
240
                'target' => '_blank',
241
            ]],
242
            $before
243
        );
244
    }
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 188
    public function add_item(array $item, $before = -1)
267
    {
268 188
        if ($before != -1) {
269 1
            $before = $this->_check_index($before, false);
270
        }
271 188
        $item = $this->clean_item($item);
272
273 188
        if ($before == -1) {
274 188
            $this->items[] = $item;
275 1
        } elseif ($before == 0) {
276 1
            array_unshift($this->items, $item);
277
        } else {
278 1
            $start = array_slice($this->items, 0, $before);
279 1
            $start[] = $item;
280 1
            $this->items = array_merge($start, array_slice($this->items, $before));
281
        }
282
    }
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
    }
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 189
    public function clean_item(array $item) : array
325
    {
326 189
        static $used_access_keys = [];
327
328
        $defaults = [
329
            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 189
        $item = array_replace($defaults, $item);
342
343 189
        if (   !empty($item[MIDCOM_TOOLBAR_ACCESSKEY])
344 189
            && !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 (str_contains($_SERVER['HTTP_USER_AGENT'] ?? '', 'Macintosh')) {
348
                // Mac users
349
                $prefix = 'Ctrl-Alt-';
350
            }
351 9
            $hotkey = $prefix . strtoupper($item[MIDCOM_TOOLBAR_ACCESSKEY]);
352
353 9
            if ($item[MIDCOM_TOOLBAR_HELPTEXT] == '') {
354 9
                $item[MIDCOM_TOOLBAR_HELPTEXT] = $hotkey;
355
            } else {
356
                $item[MIDCOM_TOOLBAR_HELPTEXT] .= " ({$hotkey})";
357
            }
358 9
            $used_access_keys[$item[MIDCOM_TOOLBAR_ACCESSKEY]] = true;
359
        }
360
361 189
        $this->set_url($item, $item[MIDCOM_TOOLBAR_URL]);
362 189
        return $item;
363
    }
364
365 189
    private function set_url(array &$item, string $url)
366
    {
367 189
        $item[MIDCOM_TOOLBAR__ORIGINAL_URL] = $url;
368 189
        if (   (   empty($item[MIDCOM_TOOLBAR_OPTIONS]["rel"])
369
                // Some items may want to keep their links unmutilated
370 189
                || $item[MIDCOM_TOOLBAR_OPTIONS]["rel"] != "directlink")
371 189
            && !str_starts_with($url, '/')
372 189
            && !preg_match('|^https?://|', $url)) {
373 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

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