Completed
Push — master ( 10885e...e41e62 )
by Andreas
13:56
created

midcom_helper_toolbar::remove_item()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 11
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 12

Importance

Changes 0
Metric Value
cc 3
eloc 8
nc 3
nop 1
dl 0
loc 11
ccs 0
cts 8
cp 0
crap 12
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 = Array (
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
     * @param string $class_style The class style tag for the UL.
196
     * @param string $id_style The id style tag for the UL.
197
     */
198 338
    public function __construct($class_style = 'midcom_toolbar', $id_style = null)
199
    {
200 338
        $this->id_style = $id_style;
201 338
        $this->class_style = $class_style;
202 338
    }
203
204
    public function is_rendered() : bool
205
    {
206
        return $this->rendered;
207
    }
208
209
    /**
210
     *
211
     * @return string
212
     */
213
    public function get_label()
214
    {
215
        return $this->label;
216
    }
217
218
    /**
219
     *
220
     * @param string $label
221
     */
222 52
    public function set_label($label)
223
    {
224 52
        $this->label = $label;
225 52
    }
226
227
    /**
228
     * Add a help item to the toolbar.
229
     *
230
     * @param string $help_id Name of the help file in component documentation directory.
231
     * @param string $component Component to display the help from
232
     * @param string $label Label for the help link
233
     * @param string $anchor Anchor ("a name" or "id" in HTML page) to link to
234
     */
235 3
    public function add_help_item($help_id, $component = null, $label = null, $anchor = null, $before = -1)
236
    {
237 3
        $uri = "__ais/help/";
238 3
        if ($component !== null) {
239 1
            $uri .= $component . '/';
240
        }
241 3
        $uri .= $help_id . '/';
242
243 3
        if ($anchor !== null) {
244
            $uri .= "#{$anchor}";
245
        }
246
247 3
        if ($label === null) {
248 3
            $label = midcom::get()->i18n->get_string('help', 'midcom.admin.help');
249
        }
250
251 3
        $this->add_item([
252 3
            MIDCOM_TOOLBAR_URL => $uri,
253 3
            MIDCOM_TOOLBAR_LABEL => $label,
254 3
            MIDCOM_TOOLBAR_GLYPHICON => 'question',
255 3
            MIDCOM_TOOLBAR_ACCESSKEY => 'h',
256
            MIDCOM_TOOLBAR_OPTIONS => [
257
                'target' => '_blank',
258
            ]],
259
            $before
260
        );
261 3
    }
262
263
    /**
264
     * Add an item to the toolbar.
265
     *
266
     * Set before to the index of the element before which you want to insert
267
     * the item or use -1 if you want to append an item. Alternatively,
268
     * instead of specifying an index, you can specify a URL instead.
269
     *
270
     * This member will process the URL and append the anchor prefix in case
271
     * the URL is a relative one.
272
     *
273
     * Invalid positions will result in a MidCOM Error.
274
     *
275
     * @param array $item The item to add.
276
     * @param mixed $before The index before which the item should be inserted.
277
     *     Use -1 for appending at the end, use a string to insert
278
     *     it before a URL, an integer will insert it before a
279
     *     given index.
280
     * @see midcom_helper_toolbar::get_index_from_url()
281
     * @see midcom_helper_toolbar::_check_index()
282
     * @see midcom_helper_toolbar::clean_item()
283
     */
284 326
    public function add_item($item, $before = -1)
285
    {
286 326
        if ($before != -1) {
287 1
            $before = $this->_check_index($before, false);
288
        }
289 326
        $item = $this->clean_item($item);
290
291 326
        if ($before == -1) {
292 326
            $this->items[] = $item;
293 1
        } elseif ($before == 0) {
294
            array_unshift($this->items, $item);
295
        } else {
296 1
            $start = array_slice($this->items, 0, $before - 1);
297 1
            $start[] = $item;
298 1
            $this->items = array_merge($start, array_slice($this->items, $before));
299
        }
300 326
    }
301
302
    /**
303
     * Convenience shortcut to add multiple buttons at the same item
304
     *
305
     * @param array $items The items to add.
306
     * @param mixed $before The index before which the item should be inserted.
307
     *     Use -1 for appending at the end, use a string to insert
308
     *     it before a URL, an integer will insert it before a
309
     *     given index.
310
     */
311 338
    public function add_items(array $items, $before = -1)
312
    {
313 338
        foreach ($items as $item) {
314 317
            $this->add_item($item, $before);
315
        }
316 338
    }
317
318
    /**
319
     * Add an item to another item by either adding the item to the MIDCOM_TOOLBAR_SUBMENU
320
     * or creating a new subtoolbar and adding the item there.
321
     *
322
     * @param array $item
323
     * @param int $index toolbar item index.
324
     * @return boolean false if insert failed.
325
     */
326
    public function add_item_to_index($item, $index)
327
    {
328
        $item = $this->clean_item($item);
329
        if (!array_key_exists($index, $this->items)) {
330
            debug_add("Insert of item {$item[MIDCOM_TOOLBAR_LABEL]} into index $index failed");
331
            return false;
332
        }
333
334
        if (empty($this->items[$index][MIDCOM_TOOLBAR_SUBMENU])) {
335
            $this->items[$index][MIDCOM_TOOLBAR_SUBMENU] = new midcom_helper_toolbar($this->class_style, $this->id_style);
336
        }
337
338
        $this->items[$index][MIDCOM_TOOLBAR_SUBMENU]->items[] = $item;
339
340
        return true;
341
    }
342
343
    /**
344
     * Clean up an item that is added, making sure that the item has all the
345
     * needed options and indexes.
346
     *
347
     * @param array $item the item to be cleaned
348
     * @return array the cleaned item.
349
     */
350 326
    public function clean_item($item)
351
    {
352 326
        static $used_access_keys = [];
353
354
        $defaults = [
355 326
            MIDCOM_TOOLBAR_URL => './',
356
            MIDCOM_TOOLBAR_OPTIONS => [],
357
            MIDCOM_TOOLBAR_HIDDEN => false,
358
            MIDCOM_TOOLBAR_HELPTEXT => '',
359
            MIDCOM_TOOLBAR_ICON => null,
360
            MIDCOM_TOOLBAR_GLYPHICON => null,
361
            MIDCOM_TOOLBAR_ENABLED => true,
362
            MIDCOM_TOOLBAR_POST => false,
363
            MIDCOM_TOOLBAR_POST_HIDDENARGS => [],
364
            MIDCOM_TOOLBAR_ACCESSKEY => null
365
        ];
366
367 326
        $item = array_replace($defaults, $item);
368
369 326
        if (   !empty($item[MIDCOM_TOOLBAR_ACCESSKEY])
370 326
            && !array_key_exists($item[MIDCOM_TOOLBAR_ACCESSKEY], $used_access_keys)) {
371
            // We have valid access key, add it to help text
372 11
            $prefix = 'Alt-';
373 11
            if (   isset($_SERVER['HTTP_USER_AGENT'])
374 11
                && strstr($_SERVER['HTTP_USER_AGENT'], 'Macintosh')) {
375
                // Mac users
376
                $prefix = 'Ctrl-Alt-';
377
            }
378 11
            $hotkey = $prefix . strtoupper($item[MIDCOM_TOOLBAR_ACCESSKEY]);
379
380 11
            if ($item[MIDCOM_TOOLBAR_HELPTEXT] == '') {
381 11
                $item[MIDCOM_TOOLBAR_HELPTEXT] = $hotkey;
382
            } else {
383
                $item[MIDCOM_TOOLBAR_HELPTEXT] .= " ({$hotkey})";
384
            }
385 11
            $used_access_keys[$item[MIDCOM_TOOLBAR_ACCESSKEY]] = true;
386
        }
387
388 326
        $this->set_url($item, $item[MIDCOM_TOOLBAR_URL]);
389 326
        return $item;
390
    }
391
392 326
    private function set_url(array &$item, $url)
393
    {
394 326
        $item[MIDCOM_TOOLBAR__ORIGINAL_URL] = $url;
395 326
        if (   (   empty($item[MIDCOM_TOOLBAR_OPTIONS]["rel"])
396
                // Some items may want to keep their links unmutilated
397 326
                || $item[MIDCOM_TOOLBAR_OPTIONS]["rel"] != "directlink")
398 326
            && substr($url, 0, 1) != '/'
399 326
            && !preg_match('|^https?://|', $url)) {
400 322
            $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

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