1<?php
2
3/**
4 * DokuWiki Mikio Template
5 *
6 * @link    http://dokuwiki.org/template:mikio
7 * @author  James Collins <james.collins@outlook.com.au>
8 * @license GPLv2 (http://www.gnu.org/licenses/gpl-2.0.html)
9 */
10
11namespace dokuwiki\template\mikio;
12
13if (!defined('DOKU_INC')) die();
14
15require_once('icons/icons.php');
16require_once('inc/simple_html_dom.php');
17
18class Template
19{
20    public $tplDir  = '';
21    public $baseDir = '';
22    public $footerScript = array();
23    public $lessIgnored = false;
24
25
26    /**
27     * Class constructor
28     */
29    public function __construct()
30    {
31        $this->tplDir  = tpl_incdir();
32        $this->baseDir = tpl_basedir();
33
34        $this->_registerHooks();
35    }
36
37
38    /**
39     * Returns the instance of the class
40     *
41     * @return  Template        class instance
42     */
43    public static function getInstance()
44    {
45        static $instance = null;
46
47        if ($instance === null) {
48            $instance = new Template();
49        }
50
51        return $instance;
52    }
53
54
55    /**
56     * Register the themes hooks into Dokuwiki
57     */
58    private function _registerHooks()
59    {
60        global $EVENT_HANDLER;
61
62        $events_dispatcher = array(
63            'TPL_METAHEADER_OUTPUT'     => 'metaheadersHandler'
64        );
65
66        foreach ($events_dispatcher as $event => $method) {
67            $EVENT_HANDLER->register_hook($event, 'BEFORE', $this, $method);
68        }
69    }
70
71
72    /**
73     * Meta handler hook for DokuWiki
74     *
75     * @param   Doku_Event  $event
76     */
77    public function metaHeadersHandler(\Doku_Event $event)
78    {
79        global $MIKIO_ICONS;
80        global $conf;
81
82        $this->includePage('theme', FALSE, TRUE);
83
84        $stylesheets    = array();
85        $scripts        = array();
86
87        if ($this->getConf('customTheme') != '') {
88            if (file_exists($this->tplDir . 'themes/' . $this->getConf('customTheme') . '/style.less')) {
89                $stylesheets[] = $this->baseDir . 'themes/' . $this->getConf('customTheme') . '/style.less';
90            } else {
91                if (file_exists($this->tplDir . 'themes/' . $this->getConf('customTheme') . '/style.css')) {
92                    $stylesheets[] = $this->baseDir . 'themes/' . $this->getConf('customTheme') . '/style.css';
93                }
94            }
95            if (file_exists($this->tplDir . 'themes/' . $this->getConf('customTheme') . '/script.js')) {
96                $scripts[] = $this->baseDir . 'themes/' . $this->getConf('customTheme') . '/script.js';
97            }
98        }
99
100        if (is_array($MIKIO_ICONS) && $this->getConf('iconTag', 'icon') != '') {
101            $icons = array();
102            foreach ($MIKIO_ICONS as $icon) {
103                if (isset($icon['name']) && isset($icon['css']) && isset($icon['insert'])) {
104                    $icons[] = $icon;
105
106                    if ($icon['css'] != '') {
107                        if (strpos($icon['css'], '//') === FALSE) {
108                            $stylesheets[] = $this->baseDir . 'icons/' . $icon['css'];
109                        } else {
110                            $stylesheets[] = $icon['css'];
111                        }
112                    }
113                }
114            }
115            $MIKIO_ICONS = $icons;
116        } else {
117            $MIKIO_ICONS = [];
118        }
119
120        $scripts[] = $this->baseDir . 'assets/mikio-typeahead.js';
121        $scripts[] = $this->baseDir . 'assets/mikio.js';
122
123        if ($this->getConf('useLESS')) {
124            $stylesheets[] = $this->baseDir . 'assets/mikio.less';
125        } else {
126            $stylesheets[] = $this->baseDir . 'assets/mikio.css';
127        }
128
129
130        $set = [];
131        foreach ($stylesheets as $style) {
132            if (in_array($style, $set) == FALSE) {
133                if (strtolower(substr($style, -5)) == '.less' && $this->getConf('useLESS')) {
134                    $style = $this->baseDir . 'css.php?css=' . str_replace($this->baseDir, '', $style);
135                }
136
137                array_unshift($event->data['link'], array(
138                    'type' => 'text/css',
139                    'rel'  => 'stylesheet',
140                    'href' => $style
141                ));
142            }
143            $set[] = $style;
144        }
145
146        $set = [];
147        foreach ($scripts as $script) {
148            if (in_array($script, $set) == FALSE) {
149                $script_params = array(
150                    'type'  => 'text/javascript',
151                    '_data' => '',
152                    'src'   => $script
153                );
154
155                // equal to or greator than hogfather
156                if($this->dwVersionNumber() >= 20200729) {
157                    // greator than hogfather - defer always on
158                    if($this->dwVersionNumber() >= 20200729) {
159                        $script_params += ['defer' => 'defer'];
160                    } else {
161                        // hogfather - defer always on unless $conf['defer_js'] is false
162                        if(!array_key_exists('defer_js', $conf) || $conf['defer_js']) {
163                            $script_params += ['defer' => 'defer'];
164                        }
165                    }
166                }
167
168                $event->data['script'][] = $script_params;
169            }
170            $set[] = $script;
171        }
172    }
173
174
175    /**
176     * Print or return the footer meta data
177     *
178     * @param   boolean $print      print the data to buffer
179     */
180    public function includeFooterMeta($print = TRUE)
181    {
182        $html = '';
183
184        if (count($this->footerScript) > 0) {
185            $html .= '<script type="text/javascript">function mikioFooterRun() {';
186            foreach ($this->footerScript as $script) {
187                $html .= $script . ';';
188            }
189            $html .= '}</script>';
190        }
191
192
193        if ($print) echo $html;
194        return $html;
195    }
196
197    /**
198     * Retreive and parse theme configuration options
199     *
200     * @param   string  $key        the configuration key to retreive
201     * @param   mixed   $default    if key doesn't exist, return this value
202     * @return  mixed               parsed value of configuration
203     */
204    public function getConf($key, $default = FALSE)
205    {
206        $value = tpl_getConf($key, $default);
207
208        switch ($key) {
209            case 'navbarDWMenuType':
210                $value = strtolower($value);
211                if ($value != 'icons' && $value != 'text' && $value != 'both') $value = 'both';
212                break;
213            case 'navbarDWMenuCombine':
214                $value = strtolower($value);
215                if ($value != 'seperate' && $value != 'dropdown' && $value != 'combine') $value = 'combine';
216                break;
217            case 'navbarPosLeft':
218            case 'navbarPosMiddle':
219            case 'navbarPosRight':
220                $value = strtolower($value);
221                if ($value != 'none' && $value != 'custom' && $value != 'search' && $value != 'dokuwiki') {
222                    if ($key == 'navbarPosLeft') $value = 'none';
223                    if ($key == 'navbarPosMiddle') $value = 'search';
224                    if ($key == 'navbarPosRight') $value = 'dokuwiki';
225                }
226                break;
227            case 'navbarItemShowCreate':
228            case 'navbarItemShowShow':
229            case 'navbarItemShowRevs':
230            case 'navbarItemShowBacklink':
231            case 'navbarItemShowRecent':
232            case 'navbarItemShowMedia':
233            case 'navbarItemShowIndex':
234            case 'navbarItemShowProfile':
235            case 'navbarItemShowAdmin':
236                $value = strtolower($value);
237                if ($value != 'always' && $value != 'logged in' && $value != 'logged out' && $value != 'never') {
238                    $value = 'always';
239                }
240                break;
241            case 'navbarItemShowLogin':
242            case 'navbarItemShowLogout':
243                $value = strtolower($value);
244                if ($value != 'always' && $value != 'never') {
245                    $value = 'always';
246                }
247                break;
248            case 'searchButton':
249                $value = strtolower($value);
250                if ($value != 'icon' && $value != 'text') $value = 'icon';
251                break;
252            case 'searchButton':
253                $value = strtolower($value);
254                if ($value != 'icon' && $value != 'text') $value = 'icon';
255                break;
256            case 'breadcrumbPosition':
257                $value = strtolower($value);
258                if ($value != 'none' && $value != 'top' && $value != 'hero' && $value != 'page') $value = 'top';
259                break;
260            case 'youareherePosition':
261                $value = strtolower($value);
262                if ($value != 'none' && $value != 'top' && $value != 'hero' && $value != 'page') $value = 'top';
263                break;
264            case 'youarehereHome':
265                $value = strtolower($value);
266                if ($value != 'none' && $value != 'page title' && $value != 'home' && $value != 'icon') $value = 'page title';
267                break;
268            case 'sidebarLeftRow1':
269            case 'sidebarLeftRow2':
270            case 'sidebarLeftRow3':
271            case 'sidebarLeftRow4':
272                $value = strtolower($value);
273                if ($value != 'none' && $value != 'logged in user' && $value != 'search' && $value != 'content' && $value != 'tags') {
274                    if ($key == 'sidebarLeftRow1') $value = 'logged in user';
275                    if ($key == 'sidebarLeftRow2') $value = 'search';
276                    if ($key == 'sidebarLeftRow3') $value = 'content';
277                    if ($key == 'sidebarLeftRow4') $value = 'none';
278                }
279                break;
280            case 'pageToolsFloating':
281            case 'pageToolsFooter':
282                $value = strtolower($value);
283                if ($value != 'none' && $value != 'page editors' && $value != 'always') {
284                    if ($key == 'pageToolsFloating') $value = 'always';
285                    if ($key == 'pageToolsFooter') $value = 'always';
286                }
287                break;
288            case 'pageToolsShowCreate':
289            case 'pageToolsShowEdit':
290            case 'pageToolsShowRevs':
291            case 'pageToolsShowBacklink':
292            case 'pageToolsShowTop':
293                $value = strtolower($value);
294                if ($value != 'always' && $value != 'logged in' && $value != 'logged out' && $value != 'never') {
295                    $value = 'always';
296                }
297                break;
298            case 'showNotifications':
299                $value = strtolower($value);
300                if ($value != 'none' && $value != 'admin' && $value != 'always') $value = 'admin';
301                break;
302            case 'licenseType':
303                $value = strtolower($value);
304                if ($value != 'none' && $value != 'badge' && $value != 'buttom') $value = 'badge';
305                break;
306            case 'navbarUseTitleIcon':
307            case 'navbarUseTitleText':
308            case 'navbarUseTaglineText':
309            case 'navbarShowSub':
310            case 'heroTitle':
311            case 'heroImagePropagation':
312            case 'breadcrumbPrefix':
313            case 'breadcrumbSep':
314            case 'youareherePrefix':
315            case 'youarehereSep':
316            case 'sidebarShowLeft':
317            case 'sidebarShowRight':
318            case 'tocFull':
319            case 'footerSearch':
320            case 'licenseImageOnly':
321            case 'includePageUseACL':
322            case 'includePagePropagate':
323            case 'youarehereHideHome':
324            case 'tagsConsolidate':
325            case 'footerInPage':
326            case 'sidebarMobileDefaultCollapse':
327            case 'sidebarAlwaysShowLeft':
328            case 'sidebarAlwaysShowRight':
329            case 'searchUseTypeahead':
330                $value = (bool)$value;
331                break;
332            case 'youarehereShowLast':
333                $value = (int)$value;
334                break;
335            case 'iconTag':
336            case 'customTheme':
337            case 'navbarCustomMenuText':
338            case 'breadcrumbPrefixText':
339            case 'breadcrumbSepText':
340            case 'youareherePrefixText':
341            case 'youarehereSepText':
342            case 'footerCustomMenuText':
343            case 'brandURLGuest':
344            case 'brandURLUser':
345                break;
346            case 'useLESS':
347                $value = (bool)$value;
348                $lessAvailable = true;
349
350                // check for less library
351                $lesscLib = '../../../vendor/marcusschwarz/lesserphp/lessc.inc.php';
352                if (!file_exists($lesscLib))
353                    $lesscLib = $_SERVER['DOCUMENT_ROOT'] . '/vendor/marcusschwarz/lesserphp/lessc.inc.php';
354                if (!file_exists($lesscLib))
355                    $lesscLib = '../../../../../app/dokuwiki/vendor/marcusschwarz/lesserphp/lessc.inc.php';
356                if (!file_exists($lesscLib))
357                    $lesscLib = $_SERVER['DOCUMENT_ROOT'] . '/app/dokuwiki/vendor/marcusschwarz/lesserphp/lessc.inc.php';
358                if (!file_exists($lesscLib)) {
359                    $lessAvailable = false;
360                }
361
362                // check for ctype extensions
363                if (!function_exists('ctype_digit')) {
364                    $lessAvailable = false;
365                }
366
367                if ($value && !$lessAvailable) {
368                    $this->lessIgnored = true;
369                    $value = false;
370                }
371                break;
372        }
373
374        return $value;
375    }
376
377
378    /**
379     * Check if a page exist in directory or namespace
380     *
381     * @param   string  $page   page/namespace to search
382     * @return  boolean         if page exists
383     */
384    public function pageExists($page)
385    {
386        ob_start();
387        tpl_includeFile($page . '.html');
388        $html = ob_get_contents();
389        ob_end_clean();
390
391        if ($html != '') return TRUE;
392
393        $useACL = $this->getConf('includePageUseACL');
394        $propagate = $this->getConf('includePagePropagate');
395
396        if ($propagate) {
397            if (page_findnearest($page, $useACL)) return TRUE;
398        } elseif ($useACL && auth_quickaclcheck($page) != AUTH_NONE) {
399            return TRUE;
400        }
401
402        return FALSE;
403    }
404
405
406    /**
407     * Print or return page from directory or namespace
408     *
409     * @param   string  $page           page/namespace to include
410     * @param   boolean $print          print content
411     * @param   boolean $parse          parse content before printing/returning
412     * @param   string  $classWrapper   wrap page in a div with class
413     * @return  string                  contents of page found
414     */
415    public function includePage($page, $print = TRUE, $parse = TRUE, $classWrapper = '')
416    {
417        ob_start();
418        tpl_includeFile($page . '.html');
419        $html = ob_get_contents();
420        ob_end_clean();
421
422        if ($html == '') {
423            $useACL = $this->getConf('includePageUseACL');
424            $propagate = $this->getConf('includePagePropagate');
425            $html = '';
426
427            $html = tpl_include_page($page, false, $propagate, $useACL);
428        }
429
430        if ($html != '' && $parse) {
431            $html = $this->parseContent($html);
432        }
433
434        if ($classWrapper != '' && $html != '') $html = '<div class="' . $classWrapper . '">' . $html . '</div>';
435
436        if ($print) echo $html;
437        return $html;
438    }
439
440
441    /**
442     * Print or return logged in user information
443     *
444     * @param   boolean $print          print content
445     * @return  string                  user information
446     */
447    public function includeLoggedIn($print = TRUE)
448    {
449        $html = '';
450
451        if (!empty($_SERVER['REMOTE_USER'])) {
452            $html .= '<div class="mikio-user-info">';
453            ob_start();
454            tpl_userinfo();
455            $html .= ob_get_contents();
456            ob_end_clean();
457            $html .= '</div>';
458        }
459
460        if ($print) echo $html;
461        return $html;
462    }
463
464
465    /**
466     * Print or return DokuWiki Menu
467     *
468     * @param   boolean $print          print content
469     * @return  string                  contents of the menu
470     */
471    public function includeDWMenu($print = TRUE)
472    {
473        global $lang;
474        global $USERINFO;
475
476        $loggedIn = (is_array($USERINFO) && count($USERINFO) > 0);
477        $html = '<ul class="mikio-nav">';
478
479        $pageToolsMenu = [];
480        $siteToolsMenu = [];
481        $userToolsMenu = [];
482
483        $showIcons  = ($this->getConf('navbarDWMenuType') != 'text');
484        $showText   = ($this->getConf('navbarDWMenuType') != 'icons');
485        $isDropDown = ($this->getConf('navbarDWMenuCombine') != 'seperate');
486
487        $items = (new \dokuwiki\Menu\PageMenu())->getItems();
488        foreach ($items as $item) {
489            if ($item->getType() != 'top') {
490                $itemHtml = '';
491
492                $showItem = $this->getConf('navbarItemShow' . ucfirst($item->getType()));
493                if ($showItem !== false && ($showItem == 'always' || ($showItem == 'logged in' && $loggedIn) || ($showItem == 'logged out' && !$loggedIn))) {
494                    $itemHtml .= '<a class="mikio-nav-link ' . ($isDropDown ? 'mikio-dropdown-item' : '') . ' ' . $item->getType() . '" href="' . $item->getLink() . '" title="' . $item->getTitle() . '">';
495                    if ($showIcons) $itemHtml .= '<span class="mikio-icon">' . inlineSVG($item->getSvg()) . '</span>';
496                    if ($showText || $isDropDown) $itemHtml .= '<span>' . $item->getLabel() . '</span>';
497                    $itemHtml .= '</a>';
498
499                    $pageToolsMenu[] = $itemHtml;
500                }
501            }
502        }
503
504        $items = (new \dokuwiki\Menu\SiteMenu())->getItems('action');
505        foreach ($items as $item) {
506            $itemHtml = '';
507
508            $showItem = $this->getConf('navbarItemShow' . ucfirst($item->getType()));
509            if ($showItem !== false && ($showItem == 'always' || ($showItem == 'logged in' && $loggedIn) || ($showItem == 'logged out' && !$loggedIn))) {
510                $itemHtml .= '<a class="mikio-nav-link ' . ($isDropDown ? 'mikio-dropdown-item' : '') . ' ' . $item->getType() . '" href="' . $item->getLink() . '" title="' . $item->getTitle() . '">';
511                if ($showIcons) $itemHtml .= '<span class="mikio-icon">' . inlineSVG($item->getSvg()) . '</span>';
512                if ($showText || $isDropDown) $itemHtml .= '<span>' . $item->getLabel() . '</span>';
513                $itemHtml .= '</a>';
514
515                $siteToolsMenu[] = $itemHtml;
516            }
517        }
518
519        $items = (new \dokuwiki\Menu\UserMenu())->getItems('action');
520        foreach ($items as $item) {
521            $itemHtml = '';
522
523            $showItem = $this->getConf('navbarItemShow' . ucfirst($item->getType()));
524            if ($showItem !== false && ($showItem == 'always' || ($showItem == 'logged in' && $loggedIn) || ($showItem == 'logged out' && !$loggedIn))) {
525                $itemHtml .= '<a class="mikio-nav-link' . ($isDropDown ? ' mikio-dropdown-item' : '') . ' ' . $item->getType() . '" href="' . $item->getLink() . '" title="' . $item->getTitle() . '">';
526                if ($showIcons) $itemHtml .= '<span class="mikio-icon">' . inlineSVG($item->getSvg()) . '</span>';
527                if ($showText || $isDropDown) $itemHtml .= '<span>' . $item->getLabel() . '</span>';
528                $itemHtml .= '</a>';
529
530                $userToolsMenu[] = $itemHtml;
531            }
532        }
533
534
535        switch ($this->getConf('navbarDWMenuCombine')) {
536            case 'dropdown':
537                $html .= '<li id="dokuwiki__pagetools" class="mikio-nav-dropdown">';
538                $html .= '<a id="mikio_dropdown_pagetools" class="nav-link dropdown-toggle" href="#" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">' . ($showIcons ? $this->mikioInlineIcon('file') : '') . ($showText ? $lang['page_tools'] : '<span class="mikio-small-only">' . $lang['page_tools'] . '</span>') . '</a>';
539                $html .= '<div class="mikio-dropdown closed">';
540
541                foreach ($pageToolsMenu as $item) {
542                    $html .= $item;
543                }
544
545                $html .= '</div>';
546                $html .= '</li>';
547
548                $html .= '<li id="dokuwiki__sitetools" class="mikio-nav-dropdown">';
549                $html .= '<a id="mikio_dropdown_sitetools" class="nav-link dropdown-toggle" href="#" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">' . ($showIcons ? $this->mikioInlineIcon('gear') : '') . ($showText ? $lang['site_tools'] : '<span class="mikio-small-only">' . $lang['site_tools'] . '</span>') . '</a>';
550                $html .= '<div class="mikio-dropdown closed">';
551
552                foreach ($siteToolsMenu as $item) {
553                    $html .= $item;
554                }
555
556                $html .= '</div>';
557                $html .= '</li>';
558
559                $html .= '<li id="dokuwiki__usertools" class="mikio-nav-dropdown">';
560                $html .= '<a id="mikio_dropdown_usertools" class="nav-link dropdown-toggle" href="#" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">' . ($showIcons ? $this->mikioInlineIcon('user') : '') . ($showText ? $lang['user_tools'] : '<span class="mikio-small-only">' . $lang['user_tools'] . '</span>') . '</a>';
561                $html .= '<div class="mikio-dropdown closed">';
562
563                foreach ($userToolsMenu as $item) {
564                    $html .= $item;
565                }
566
567                $html .= '</div>';
568                $html .= '</li>';
569
570                break;
571
572            case 'combine':
573                $html .= '<li class="mikio-nav-dropdown">';
574                $html .= '<a class="mikio-nav-link" href="#">' . ($showIcons ? $this->mikioInlineIcon('wrench') : '') . ($showText ? tpl_getLang('tools-menu') : '<span class="mikio-small-only">' . tpl_getLang('tools-menu') . '</span>') . '</a>';   // TODO change $lang
575                $html .= '<div class="mikio-dropdown closed">';
576
577                $html .= '<h6 class="mikio-dropdown-header">' . $lang['page_tools'] . '</h6>';
578                foreach ($pageToolsMenu as $item) {
579                    $html .= $item;
580                }
581
582                $html .= '<div class="mikio-dropdown-divider"></div>';
583                $html .= '<h6 class="mikio-dropdown-header">' . $lang['site_tools'] . '</h6>';
584                foreach ($siteToolsMenu as $item) {
585                    $html .= $item;
586                }
587
588                $html .= '<div class="mikio-dropdown-divider"></div>';
589                $html .= '<h6 class="mikio-dropdown-header">' . $lang['user_tools'] . '</h6>';
590                foreach ($userToolsMenu as $item) {
591                    $html .= $item;
592                }
593
594                $html .= '</div>';
595                $html .= '</li>';
596                break;
597
598            default:    // seperate
599                foreach ($siteToolsMenu as $item) {
600                    $html .= '<li class="mikio-nav-item">' . $item . '</li>';
601                }
602
603                foreach ($pageToolsMenu as $item) {
604                    $html .= '<li class="mikio-nav-item">' . $item . '</li>';
605                }
606
607                foreach ($userToolsMenu as $item) {
608                    $html .= '<li class="mikio-nav-item">' . $item . '</li>';
609                }
610
611                break;
612        }
613
614        $html .= '</ul>';
615
616        if ($print) echo $html;
617        return $html;
618    }
619
620
621    /**
622     * Create a nav element from a string. <uri>|<title>;
623     *
624     * @param string   $str     string to generate nav
625     * @return string           nav elements generated
626     */
627    public function stringToNav($str)
628    {
629        $html = '';
630
631        if ($str != '') {
632            $items = explode(';', $str);
633            if (count($items) > 0) {
634                $html .= '<ul class="mikio-nav">';
635                foreach ($items as $item) {
636                    $parts = explode('|', $item);
637                    if ($parts > 1) {
638                        $html .= '<li class="mikio-nav-item"><a class="mikio-nav-link" href="' . strip_tags($this->getLink(trim($parts[0]))) . '">' . strip_tags(trim($parts[1])) . '</a></li>';
639                    }
640                }
641                $html .= '</ul>';
642            }
643        }
644
645        return $html;
646    }
647
648    /**
649     * print or return the main navbar
650     *
651     * @param boolean   $print      print the navbar
652     * @param boolean   $showSub    include the sub navbar
653     * @return string               generated content
654     */
655    public function includeNavbar($print = TRUE, $showSub = FALSE)
656    {
657        global $conf, $USERINFO;
658
659        $homeUrl = wl();
660
661        if (!plugin_isdisabled('showpageafterlogin')) {
662            $p = &plugin_load('action', 'showpageafterlogin');
663            if ($p) {
664                if (is_array($USERINFO) && count($USERINFO) > 0) {
665                    $homeUrl = wl($p->getConf('page_after_login'));
666                }
667            }
668        } else {
669            if (is_array($USERINFO) && count($USERINFO) > 0) {
670                $url = $this->getConf('brandURLUser');
671                if(strlen($url) > 0) {
672                    $homeUrl = $url;
673                }
674            } else {
675                $url = $this->getConf('brandURLGuest');
676                if(strlen($url) > 0) {
677                    $homeUrl = $url;
678                }
679            }
680        }
681
682        $html = '';
683
684        $html .= '<nav class="mikio-navbar'  . (($this->getConf('stickyNavbar')) ? ' mikio-sticky' : '') . '">';
685        $html .= '<div class="mikio-container">';
686        $html .= '<a class="mikio-navbar-brand" href="' . $homeUrl . '">';
687        if ($this->getConf('navbarUseTitleIcon') || $this->getConf('navbarUseTitleText')) {
688
689            // Brand image
690            if ($this->getConf('navbarUseTitleIcon')) {
691                $logo = $this->getMediaFile('logo', FALSE);;
692                if ($logo != '') {
693                    $html .= '<img src="' . $logo . '" class="mikio-navbar-brand-image">';
694                }
695            }
696
697            // Brand title
698            if ($this->getConf('navbarUseTitleText')) {
699                $html .= '<div class="mikio-navbar-brand-title">';
700                $html .= '<h1 class="mikio-navbar-brand-title-text">' . $conf['title'] . '</h1>';
701                if ($this->getConf('navbarUseTaglineText')) {
702                    $html .= '<p class="claim mikio-navbar-brand-title-tagline">' . $conf['tagline'] . '</p>';
703                }
704                $html .= '</div>';
705            }
706        }
707        $html .= '</a>';
708        $html .= '<div class="mikio-navbar-toggle"><span class="icon"></span></div>';
709
710        // Menus
711        $html .= '<div class="mikio-navbar-collapse">';
712
713        $menus = array($this->getConf('navbarPosLeft', 'none'), $this->getConf('navbarPosMiddle', 'none'), $this->getConf('navbarPosRight', 'none'));
714        foreach ($menus as $menuType) {
715            switch ($menuType) {
716                case 'custom':
717                    $html .= $this->stringToNav($this->getConf('navbarCustomMenuText', ''));
718                    break;
719                case 'search':
720                    $html .= '<div class="mikio-nav-item">';
721                    $html .= $this->includeSearch(false);
722                    $html .= '</div>';
723                    break;
724                case 'dokuwiki':
725                    $html .= $this->includeDWMenu(FALSE);
726                    break;
727            }
728        }
729
730        $html .= '</div>';
731        $html .= '</div>';
732        $html .= '</nav>';
733
734        // Sub Navbar
735        if ($showSub) {
736            $sub = $this->includePage('submenu', FALSE);
737            if ($sub != '') $html .= '<nav class="mikio-navbar mikio-sub-navbar">' . $sub . '</nav>';
738        }
739
740        if ($print) echo $html;
741        return $html;
742    }
743
744
745    /**
746     * Is there a sidebar
747     *
748     * @param   string  $prefix     sidebar prefix to use when searching
749     * @return  boolean             if sidebar exists
750     */
751    public function sidebarExists($prefix = '')
752    {
753        global $conf;
754
755        if ($prefix == 'left') $prefix = '';
756
757        return $this->pageExists($conf['sidebar' . $prefix]);
758    }
759
760
761    /**
762     * Print or return the sidebar content
763     *
764     * @param   string  $prefix     sidebar prefix to use when searching
765     * @param   boolean $print      print the generated content to the output buffer
766     * @param   boolean $parse      parse the content
767     * @return  string              generated content
768     */
769    public function includeSidebar($prefix = '', $print = TRUE, $parse = TRUE)
770    {
771        global $conf, $ID;
772
773        $html = '';
774        $confPrefix = preg_replace('/[^a-zA-Z0-9]/', '', ucwords($prefix));
775        $prefix = preg_replace('/[^a-zA-Z0-9]/', '', strtolower($prefix));
776
777        if ($confPrefix == '') $confPrefix = 'Left';
778        if ($prefix == 'Left') $prefix = '';
779
780        $sidebarPage = $conf[$prefix . 'sidebar'] == '' ? $prefix . 'sidebar' : $conf[$prefix . 'sidebar'];
781
782        if ($this->getConf('sidebarShow' . $confPrefix) && page_findnearest($sidebarPage) != FALSE && p_get_metadata($ID, 'nosidebar', FALSE) == FALSE) {
783            $content = $this->includePage($sidebarPage . 'header', FALSE);
784            if ($content != '') $html .= '<div class="mikio-sidebar-header">' . $content . '</div>';
785
786            if ($prefix == '') {
787                $rows = array($this->getConf('sidebarLeftRow1'), $this->getConf('sidebarLeftRow2'), $this->getConf('sidebarLeftRow3'), $this->getConf('sidebarLeftRow4'));
788
789                foreach ($rows as $row) {
790                    switch ($row) {
791                        case 'search':
792                            $html .= $this->includeSearch(FALSE);
793                            break;
794                        case 'logged in user':
795                            $html .= $this->includeLoggedIn(FALSE);
796                            break;
797                        case 'content':
798                            $content = $this->includePage($sidebarPage, FALSE);
799                            if ($content != '') $html .= '<div class="mikio-sidebar-content">' . $content . '</div>';
800                            break;
801                        case 'tags':
802                            $html .= '<div class="mikio-tags"></div>';
803                    }
804                }
805            } else {
806                $content = $this->includePage($sidebarPage, FALSE);
807                if ($content != '') $html .= '<div class="mikio-sidebar-content">' . $content . '</div>';
808            }
809
810            $content = $this->includePage($sidebarPage . 'footer', FALSE);
811            if ($content != '') $html .= '<div class="mikio-sidebar-footer">' . $content . '</div>';
812        }
813
814        if ($html == '') {
815            if ($prefix == '' && $this->getConf('sidebarAlwaysShowLeft')) $html = '&nbsp;';
816            if ($this->getConf('sidebarAlwaysShow' . ucfirst($prefix))) $html = '&nbsp;';
817        }
818
819        if ($html != '') {
820            $html = '<aside class="mikio-sidebar mikio-sidebar-' . ($prefix == '' ? 'left' : $prefix) . '"><a class="mikio-sidebar-toggle' . ($this->getConf('sidebarMobileDefaultCollapse') ? ' closed' : '') . '" href="#">' . tpl_getLang('sidebar-title') . ' <span class="icon"></span></a><div class="mikio-sidebar-collapse">' . $html . '</div></aside>';
821        }
822
823        if ($parse) $html = $this->includeIcons($html);
824        if ($print) echo $html;
825        return $html;
826    }
827
828
829    /**
830     * Print or return the page tools content
831     *
832     * @param   boolean $print      print the generated content to the output buffer
833     * @param   boolean $includeId  include the dw__pagetools id in the element
834     * @return  string              generated content
835     */
836    public function includePageTools($print = TRUE, $includeId = FALSE)
837    {
838        global $USERINFO;
839
840        $loggedIn = (is_array($USERINFO) && count($USERINFO) > 0);
841        $html = '';
842
843        $html .= '<nav' . ($includeId ? ' id="dw__pagetools"' : '') . ' class="hidden-print dw__pagetools">';
844        $html .= '<ul class="tools">';
845
846        $items = (new \dokuwiki\Menu\PageMenu())->getItems();
847        foreach ($items as $item) {
848            $classes = array();
849            $classes[] = $item->getType();
850            $attr = $item->getLinkAttributes();
851
852            if (!empty($attr['class'])) {
853                $classes = array_merge($classes, explode(' ', $attr['class']));
854            }
855
856            $classes = array_unique($classes);
857
858            $showItem = $this->getConf('pageToolsShow' . ucfirst($item->getType()));
859            if ($showItem !== false && ($showItem == 'always' || ($showItem == 'logged in' && $loggedIn) || ($showItem == 'logged out' && !$loggedIn))) {
860                $html .= '<li class="' . implode(' ', $classes) . '">';
861                $html .= '<a href="' . $item->getLink() . '" class="' . $item->getType() . '" title="' . $item->getTitle() . '"><div class="icon">' . inlineSVG($item->getSvg()) . '</div><span class="a11y">' . $item->getLabel() . '</span></a>';
862                $html .= '</li>';
863            }
864        }
865
866        $html .= '</ul>';
867        $html .= '</nav>';
868
869        if ($print) echo $html;
870        return $html;
871    }
872
873
874    /**
875     * Print or return the search bar
876     *
877     * @param   boolean $print          print content
878     * @return  string                  contents of the search bar
879     */
880    public function includeSearch($print = TRUE)
881    {
882        global $lang, $ID;
883        $html = '';
884
885        $html .= '<form class="mikio-search search" action="' . wl() . '" accept-charset="utf-8" method="get" role="search">';
886        $html .= '<input type="hidden" name="do" value="search">';
887        $html .= '<input type="hidden" name="id" value="' . $ID . '">';
888        $html .= '<input name="q" ';
889        if ($this->getConf('searchUseTypeahead')) {
890            $html .= 'class="search_typeahead" ';
891        }
892        $html .= 'autocomplete="off" type="search" placeholder="' . $lang['btn_search'] . '" value="' . (($ACT == 'search') ? htmlspecialchars($QUERY) : '') . '" accesskey="f" title="[F]" />';
893        $html .= '<button type="submit" title="' .  $lang['btn_search'] . '">';
894        if ($this->getConf('searchButton') == 'icon') {
895            $html .= $this->mikioInlineIcon('search');
896        } else {
897            $html .= $lang['btn_search'];
898        }
899        $html .= '</button>';
900        $html .= '</form>';
901
902
903
904        if ($print) print $html;
905        return $html;
906    }
907
908
909    /**
910     * Print or return content
911     *
912     * @param   boolean $print          print content
913     * @return  string                  contents
914     */
915    public function includeContent($print = TRUE)
916    {
917        ob_start();
918        tpl_content(FALSE);
919        $html = ob_get_contents();
920        ob_end_clean();
921
922        $html = $this->includeIcons($html);
923        $html = $this->parseContent($html);
924
925        $html .= '<div style="clear:both"></div>';
926
927        if (!$this->getConf('heroTitle')) $html = '<div class="mikio-tags"></div>' . $html;
928
929        $html = '<div class="mikio-article-content">' . $html . '</div>';
930
931        if ($print) echo $html;
932        return $html;
933    }
934
935    /**
936     * Print or return footer
937     *
938     * @param   boolean  $print     print footer
939     * @return  string              html string containing footer
940     */
941    public function includeFooter($print = TRUE)
942    {
943        global $ACT;
944
945        $html = '';
946
947        $html .= '<footer class="mikio-footer">';
948        $html .= '<div class="doc">' . tpl_pageinfo(TRUE) . '</div>';
949        $html .= $this->includePage('footer', FALSE);
950
951        $html .= $this->stringToNav($this->getConf('footerCustomMenuText'));
952
953        if ($this->getConf('footerSearch')) {
954            $html .= '<div class="mikio-footer-search">';
955            $html .= $this->includeSearch(FALSE);
956            $html .= '</div>';
957        }
958
959        $showPageTools = $this->getConf('pageToolsFooter');
960        if ($ACT == 'show' && ($showPageTools == 'always' || $this->userCanEdit() && $showPageTools == 'page editors')) $html .= $this->includePageTools(FALSE);
961
962        $meta['licenseType']            = array('multichoice', '_choices' => array('none', 'badge', 'button'));
963        $meta['licenseImageOnly']       = array('onoff');
964
965        $licenseType = $this->getConf('licenseType');
966        if ($licenseType != 'none') {
967            $html .= tpl_license($licenseType, $this->getConf('licenseImageOnly'), TRUE, TRUE);
968        }
969
970        $html .= '</footer>';
971
972        if ($print) echo $html;
973        return $html;
974    }
975
976
977    /**
978     * Print or return breadcrumb trail
979     *
980     * @param   boolean  $print     print out trail
981     * @param   boolean  $parse     parse trail before printing
982     * @return  string              html string containing breadcrumbs
983     */
984    public function includeBreadcrumbs($print = TRUE, $parse = TRUE)
985    {
986        global $conf, $ID, $lang, $ACT;
987
988        if ($this->getConf('breadcrumbHideHome') && $ID == 'start' && $ACT == 'show' || $ACT == 'showtag') return '';
989
990        $html = '<div class="mikio-breadcrumbs">';
991        $html .= '<div class="mikio-container">';
992        if ($ACT == 'show') {
993            if ($conf['breadcrumbs']) {
994                if (!$this->getConf('breadcrumbPrefix') && !$this->getConf('breadcrumbSep')) {
995                    ob_start();
996                    tpl_breadcrumbs();
997                    $html .= ob_get_contents();
998                    ob_end_clean();
999                } else {
1000                    $sep = '•';
1001                    $prefix = $lang['breadcrumb'];
1002
1003                    if ($this->getConf('breadcrumbSep')) {
1004                        $sep = $this->getConf('breadcrumbSepText');
1005                        $img = $this->getMediaFile('breadcrumb-sep', FALSE);
1006
1007                        if ($img !== FALSE) {
1008                            $sep = '<img src="' . $img . '">';
1009                        }
1010                    }
1011
1012                    if ($this->getConf('breadcrumbPrefix')) {
1013                        $prefix = $this->getConf('breadcrumbPrefixText');
1014                        $img = $this->getMediaFile('breadcrumb-prefix', FALSE);
1015
1016                        if ($img !== FALSE) {
1017                            $prefix = '<img src="' . $img . '">';
1018                        }
1019                    }
1020
1021                    $crumbs = breadcrumbs();
1022
1023                    $html .= '<ul>';
1024                    if ($prefix != '') $html .= '<li class="prefix">' . $prefix . '</li>';
1025
1026                    $last = count($crumbs);
1027                    $i    = 0;
1028                    foreach ($crumbs as $id => $name) {
1029                        $i++;
1030                        $html .= '<li class="sep">' . $sep . '</li>';
1031                        $html .= '<li' . ($i == $last ? ' class="curid"' : '') . '>';
1032                        $html .= tpl_pagelink($id, NULL, TRUE);
1033                        $html .= '</li>';
1034                    }
1035
1036                    $html .= '</ul>';
1037                }
1038            }
1039        }
1040
1041        $html .= '</div>';
1042        $html .= '</div>';
1043
1044        if ($parse) $html = $this->includeIcons($html);
1045        if ($print) echo $html;
1046        return $html;
1047    }
1048
1049    /**
1050     * Print or return you are here trail
1051     *
1052     * @param   boolean  $print     print out trail
1053     * @param   boolean  $parse     parse trail before printing
1054     * @return  string              html string containing breadcrumbs
1055     */
1056    public function includeYouAreHere($print = TRUE, $parse = TRUE)
1057    {
1058        global $conf, $ID, $lang, $ACT;
1059
1060        if ($this->getConf('youarehereHideHome') && $ID == 'start' && $ACT == 'show' || $ACT == 'showtag') return '';
1061
1062        $html = '<div class="mikio-youarehere">';
1063        $html .= '<div class="mikio-container">';
1064        if ($ACT == 'show') {
1065            if ($conf['youarehere']) {
1066                if (!$this->getConf('youareherePrefix') && !$this->getConf('youarehereSep')) {
1067                    ob_start();
1068                    tpl_youarehere();
1069                    $html .= ob_get_contents();
1070                    ob_end_clean();
1071                } else {
1072                    $sep = ' » ';
1073                    $prefix = $lang['youarehere'];
1074
1075                    if ($this->getConf('youarehereSep')) {
1076                        $sep = $this->getConf('youarehereSepText');
1077                        $img = $this->getMediaFile('youarehere-sep', FALSE);
1078
1079                        if ($img !== FALSE) {
1080                            $sep = '<img src="' . $img . '">';
1081                        }
1082                    }
1083
1084                    if ($this->getConf('youareherePrefix')) {
1085                        $prefix = $this->getConf('youareherePrefixText');
1086                        $img = $this->getMediaFile('youarehere-prefix', FALSE);
1087
1088                        if ($img !== FALSE) {
1089                            $prefix = '<img src="' . $img . '">';
1090                        }
1091                    }
1092
1093                    $html .= '<ul>';
1094                    if ($prefix != '') $html .= '<li class="prefix">' . $prefix . '</li>';
1095                    $html .= '<li>' . tpl_pagelink(':' . $conf['start'], NULL, TRUE) . '</li>';
1096
1097                    $parts = explode(':', $ID);
1098                    $count = count($parts);
1099
1100                    $part = '';
1101                    for ($i = 0; $i < $count - 1; $i++) {
1102                        $part .= $parts[$i] . ':';
1103                        $page = $part;
1104                        if ($page == $conf['start']) continue;
1105
1106                        $html .= '<li class="sep">' . $sep . '</li>';
1107                        $html .= '<li>' . tpl_pagelink($page, NULL, TRUE) . '</li>';
1108                    }
1109
1110                    resolve_pageid('', $page, $exists);
1111                    if (!(isset($page) && $page == $part . $parts[$i])) {
1112                        $page = $part . $parts[$i];
1113                        if ($page != $conf['start']) {
1114                            $html .= '<li class="sep">' . $sep . '</li>';
1115                            $html .= '<li>' . tpl_pagelink($page, NULL, TRUE) . '</li>';
1116                        }
1117                    }
1118
1119                    $html .= '</ul>';
1120                }
1121            }
1122
1123            $showLast = $this->getConf('youarehereShowLast');
1124            if ($showLast != 0) {
1125                preg_match_all('/(<li[^>]*>.+?<\/li>)/', $html, $matches);
1126                if (count($matches) > 0 && count($matches[0]) > ($showLast * 2) + 2) {
1127                    $count = count($matches[0]);
1128                    $list = '';
1129
1130                    // Show Home
1131                    $list .= $matches[0][0] . $matches[0][1];
1132
1133                    $list .= '<li>...</li>';
1134                    for ($i = $count - ($showLast * 2); $i <= $count; $i++) {
1135                        $list .= $matches[0][$i];
1136                    }
1137
1138                    $html = preg_replace('/<ul>.*<\/ul>/', '<ul>' . $list . '</ul>', $html);
1139                }
1140            }
1141
1142            switch ($this->getConf('youarehereHome')) {
1143                case 'none':
1144                    $html = preg_replace('/<li[^>]*>.+?<\/li>/', '', $html, 2);
1145                    break;
1146                case 'home':
1147                    $html = preg_replace('/(<a[^>]*>)(.+?)(<\/a>)/', '$1' . tpl_getlang('home') . '$3', $html, 1);
1148                    break;
1149                case 'icon':
1150                    $html = preg_replace('/(<a[^>]*>)(.+?)(<\/a>)/', '$1' . $this->mikioInlineIcon('home') . '$3', $html, 1);
1151                    break;
1152            }
1153        } else {
1154            $html .= '&#8810; ';
1155            if (isset($_GET['page'])) {
1156                $html .= '<a href="' . wl($ID, array('do' => $ACT)) . '">Back</a>&nbsp;&nbsp;&nbsp;/&nbsp;&nbsp;&nbsp;';
1157            }
1158            $html .= '<a href="' . wl($ID) . '">View Page</a>';
1159        }
1160
1161        $html .= '</div>';
1162        $html .= '</div>';
1163
1164        if ($parse) $html = $this->includeIcons($html);
1165        if ($print) echo $html;
1166        return $html;
1167    }
1168
1169    /**
1170     * Get Page Title
1171     */
1172    public function parsePageTitle()
1173    {
1174        global $ID;
1175
1176        $title = p_get_first_heading($ID);
1177        if (strlen($title) <= 0) $title = tpl_pagetitle(null, TRUE);
1178        $title = $this->includeIcons($title);
1179
1180        return $title;
1181    }
1182
1183
1184    /**
1185     * Print or return hero block
1186     *
1187     * @param   boolean $print          print content
1188     * @return  string                  contents of hero
1189     */
1190    public function includeHero($print = TRUE)
1191    {
1192        $html = '';
1193
1194        if ($this->getConf('heroTitle')) {
1195            $html .= '<div class="mikio-hero">';
1196            $html .= '<div class="mikio-container">';
1197            $html .= '<div class="mikio-hero-text">';
1198            if ($this->getConf('youareherePosition') == 'hero') $html .= $this->includeYouAreHere(FALSE);
1199            if ($this->getConf('breadcrumbPosition') == 'hero') $html .= $this->includeBreadcrumbs(FALSE);
1200
1201            $html .= '<h1 class="mikio-hero-title">';
1202            $html .= $this->parsePageTitle();    // No idea why this requires a blank space afterwards to work?
1203            $html .= '</h1>';
1204            $html .= '<h2 class="mikio-hero-subtitle"></h2>';
1205            $html .= '</div>';
1206
1207            $hero_image = $this->getMediaFile('hero', TRUE, $this->getConf('heroImagePropagation', TRUE));
1208            $hero_image_resize_class = '';
1209            if ($hero_image != '') {
1210                $hero_image = ' style="background-image:url(\'' . $hero_image . '\');"';
1211                $hero_image_resize_class = ' mikio-hero-image-resize';
1212            }
1213
1214            $html .= '<div class="mikio-hero-image' . $hero_image_resize_class . '"' . $hero_image . '><div class="mikio-tags"></div></div>';
1215
1216            $html .= '</div>';
1217            $html .= '</div>';
1218        }
1219
1220        if ($print) echo $html;
1221
1222        return $html;
1223    }
1224
1225
1226    /**
1227     * Print or return out TOC
1228     *
1229     * @param   boolean $print          print TOC
1230     * @return  string                  contents of TOC
1231     */
1232    public function includeTOC($parse = TRUE)
1233    {
1234        $html = '';
1235
1236        $tocHtml = tpl_toc(true);
1237
1238        if ($tocHtml != '') {
1239            $tocHtml = preg_replace('/<li.*><div.*><a.*><\/a><\/div><\/li>\s*/', '', $tocHtml);
1240            $tocHtml = preg_replace('/<ul.*>\s*<\/ul>\s*/', '', $tocHtml);
1241
1242            $html .= '<div class="mikio-toc">';
1243            $html .= $tocHtml;
1244            $html .= '</div>';
1245        }
1246
1247        if ($parse) $html = $this->includeIcons($html);
1248        echo $html;
1249    }
1250
1251
1252    /**
1253     * Parse the string and replace icon elements with included icon libraries
1254     *
1255     * @param   string  $str        content to parse
1256     * @return  string              parsed string
1257     */
1258    public function includeIcons($str)
1259    {
1260        global $ACT, $MIKIO_ICONS;
1261
1262        $iconTag = $this->getConf('iconTag', 'icon');
1263        if ($iconTag == '') return $str;
1264
1265        if ($ACT == 'show' || $ACT == 'admin' && count($MIKIO_ICONS) > 0 || $ACT == 'showtag' || $ACT == 'revisions' || $ACT == 'index' || $ACT == 'preview') {
1266            $content = $str;
1267            $preview = null;
1268
1269            if ($ACT == 'preview') {
1270                $html = new \simple_html_dom;
1271                $html->stripRNAttrValues = false;
1272                $html->load($str, true, false);
1273
1274                $preview = $html->find('div.preview');
1275                if (is_array($preview) && count($preview) > 0) {
1276                    $content = $preview[0]->innertext;
1277                }
1278            }
1279
1280            $page_regex = '/(.*)/';
1281            if (stripos($str, '<pre')) {
1282                $page_regex = '/<(?!pre|\/).*?>(.*)[^<]*/';
1283            }
1284
1285            $content = preg_replace_callback($page_regex, function ($icons) {
1286                $iconTag = $this->getConf('iconTag', 'icon');
1287
1288                return preg_replace_callback(
1289                    '/&lt;' . $iconTag . ' ([\w\- #]*)&gt;(?=[^>]*(<|$))/',
1290                    function ($matches) {
1291                        global $MIKIO_ICONS;
1292
1293                        $s = $matches[0];
1294
1295                        if (count($MIKIO_ICONS) > 0) {
1296                            $icon = $MIKIO_ICONS[0];
1297
1298                            if (count($matches) > 1) {
1299                                $e = explode(' ', $matches[1]);
1300
1301                                if (count($e) > 1) {
1302                                    foreach ($MIKIO_ICONS as $iconItem) {
1303                                        if (strcasecmp($iconItem['name'], $e[0]) == 0) {
1304                                            $icon = $iconItem;
1305
1306                                            $s = $icon['insert'];
1307                                            for ($i = 1; $i < 9; $i++) {
1308                                                if (count($e) < $i || $e[$i] == '') {
1309                                                    if (isset($icon['$' . $i])) {
1310                                                        $s = str_replace('$' . $i, $icon['$' . $i], $s);
1311                                                    }
1312                                                } else {
1313                                                    $s = str_replace('$' . $i, $e[$i], $s);
1314                                                }
1315                                            }
1316
1317                                            $dir = '';
1318                                            if (isset($icon['dir'])) $dir = $this->baseDir . 'icons/' . $icon['dir'] . '/';
1319
1320                                            $s = str_replace('$0', $dir, $s);
1321
1322                                            break;
1323                                        }
1324                                    }
1325                                } else {
1326                                    $s = str_replace('$1', $matches[1], $icon['insert']);
1327                                }
1328                            }
1329                        }
1330
1331                        $s = preg_replace('/(class=")(.*)"/', '$1mikio-icon $2"', $s, -1, $count);
1332                        if ($count == 0) {
1333                            $s = preg_replace('/(<\w* )/', '$1class="mikio-icon" ', $s);
1334                        }
1335
1336                        return $s;
1337                    },
1338                    $icons[0]
1339                );
1340            }, $content);
1341
1342            if ($ACT == 'preview') {
1343                if (is_array($preview) && count($preview) > 0) {
1344                    $preview[0]->innertext = $content;
1345                }
1346
1347                $str = $html->save();
1348                $html->clear();
1349                unset($html);
1350            } else {
1351                $str = $content;
1352            }
1353        }
1354
1355        return $str;
1356    }
1357
1358    /**
1359     * Parse HTML for theme
1360     *
1361     * @param   string  $content    HTML content to parse
1362     * @return  string              Parsed content
1363     */
1364    public function parseContent($content)
1365    {
1366        global $INPUT, $ACT;
1367
1368        // Add Mikio Section titles
1369        if ($INPUT->str('page') == 'config') {
1370            $admin_sections = array(
1371                // Section      Insert Before                       Icon
1372                'navbar'        => array('navbarUseTitleIcon',      ''),
1373                'search'        => array('searchButton',            ''),
1374                'hero'          => array('heroTitle',               ''),
1375                'tags'          => array('tagsConsolidate',         ''),
1376                'breadcrumb'    => array('breadcrumbHideHome',      ''),
1377                'youarehere'    => array('youarehereHideHome',      ''),
1378                'sidebar'       => array('sidebarShowLeft',         ''),
1379                'toc'           => array('tocFull',                 ''),
1380                'pagetools'     => array('pageToolsFloating',       ''),
1381                'footer'        => array('footerCustomMenuText',    ''),
1382                'license'       => array('licenseType',             ''),
1383                'acl'           => array('includePageUseACL',       ''),
1384                'sticky'        => array('stickyTopHeader',         ''),
1385            );
1386
1387            foreach ($admin_sections as $section => $items) {
1388                $search = $items[0];
1389                $icon   = $items[1];
1390
1391                // $content = preg_replace('/<tr(.*)>\s+<td(.*)>\s+<span(.*)>(tpl»mikio»' . $search . ')<\/span>/',
1392                // '<tr class="default"><td class="mikio-config-table-header" colspan="2">' . $this->mikioInlineIcon($icon) . tpl_getLang('config_' . $section) . '</td></tr><tr$1><td$2><span$3>$4</span>', $content);
1393
1394                $content = preg_replace(
1395                    '/<tr(.*)>\s*<td class="label">\s*<span class="outkey">(tpl»mikio»' . $search . ')<\/span>/',
1396                    '<tr$1><td class="mikio-config-table-header" colspan="2">' . $this->mikioInlineIcon($icon) . tpl_getLang('config_' . $section) . '</td></tr><tr class="default"><td class="label"><span class="outkey">tpl»mikio»' . $search . '</span>',
1397                    $content
1398                );
1399            }
1400        }
1401
1402        if ($ACT == 'admin' && !isset($_GET['page'])) {
1403            $content = preg_replace('/(<ul.*?>.*?)<\/ul>.*?<ul.*?>(.*?<\/ul>)/s', '$1$2', $content);
1404        }
1405
1406        // Page Revisions - Table Fix
1407        if (strpos($content, 'id="page__revisions"') !== FALSE) {
1408            $content = preg_replace('/(<span class="sum">\s.*<\/span>\s.*<span class="user">\s.*<\/span>)/', '<span>$1</span>', $content);
1409        }
1410
1411        $html = new \simple_html_dom;
1412        $html->stripRNAttrValues = false;
1413        $html->load($content, true, false);
1414
1415        if (!$html) return $content;
1416
1417        /* Buttons */
1418        foreach ($html->find('#config__manager button') as $node) {
1419            $c = explode(' ', $node->class);
1420            if (!in_array('mikio-button', $c)) $c[] = 'mikio-button';
1421            $node->class = implode(' ', $c);
1422        }
1423
1424
1425        /* Buttons - Primary */
1426        foreach ($html->find('#config__manager [type=submit]') as $node) {
1427            $c = explode(' ', $node->class);
1428            if (!in_array('mikio-primary', $c)) $c[] = 'mikio-primary';
1429            $node->class = implode(' ', $c);
1430        }
1431
1432        /* Hide page title if hero is enabled */
1433        if ($this->getConf('heroTitle') && $ACT != 'preview') {
1434            $pageTitle = $this->parsePageTitle();
1435
1436            foreach ($html->find('h1,h2,h3,h4') as $elm) {
1437                if ($elm->innertext == $pageTitle) {
1438                    // $elm->innertext = '';
1439                    $elm->setAttribute('style', 'display:none');
1440
1441                    break;
1442                }
1443            }
1444        }
1445
1446        /* Hero subtitle */
1447        foreach ($html->find('p') as $elm) {
1448            $i = stripos($elm->innertext, '~~hero-subtitle');
1449            if ($i !== false) {
1450                $j = strpos($elm->innertext, '~~', $i + 2);
1451                if ($j !== false) {
1452                    if ($j > $i + 16) {
1453                        $subtitle = substr($elm->innertext, $i + 16, $j - $i - 16);
1454                        $this->footerScript['hero-subtitle'] = 'mikio.setHeroSubTitle(\'' . $subtitle . '\')';
1455
1456                        // $elm->innertext = substr($elm->innertext, 0, $i + 2) . substr($elm->innertext, $j + 2);
1457                        $elm->innertext = preg_replace('/~~hero-subtitle (.+?)~~.*/ui', '', $elm->innertext);
1458                    }
1459
1460                    break;
1461                }
1462            }
1463        }
1464
1465        /* Hero image */
1466        foreach ($html->find('p') as $elm) {
1467            $image = '';
1468            preg_match('/~~hero-image (.+?)~~(?!.?")/ui', $elm->innertext, $matches);
1469            if (count($matches) > 0) {
1470                preg_match('/<img.*src="(.+?)"/ui', $matches[1], $imageTagMatches);
1471                if (count($imageTagMatches) > 0) {
1472                    $image = $imageTagMatches[1];
1473                } else {
1474                    preg_match('/<a.+?>(.+?)[~<]/ui', $matches[1], $imageTagMatches);
1475                    if (count($imageTagMatches) > 0) {
1476                        $image = $imageTagMatches[1];
1477                    } else {
1478                        $image = strip_tags($matches[1]);
1479                        if (stripos($image, ':') === FALSE) {
1480                            $image = str_replace(array('{', '}'), '', $image);
1481                            $i = stripos($image, '?');
1482                            if ($i !== FALSE) {
1483                                $image = substr($image, 0, $i);
1484                            }
1485
1486                            $image = ml($image, '', true, '', false);
1487                        }
1488                    }
1489                }
1490
1491                $this->footerScript['hero-image'] = 'mikio.setHeroImage(\'' . $image . '\')';
1492
1493                $elm->innertext = preg_replace('/~~hero-image (.+?)~~.*/ui', '', $elm->innertext);
1494            }
1495        }
1496
1497        /* Hero colors - ~~hero-colors [background-color] [hero-title-color] [hero-subtitle-color] [breadcrumb-text-color] [breadcrumb-hover-color] (use 'initial' for original color) */
1498        foreach ($html->find('p') as $elm) {
1499            $i = stripos($elm->innertext, '~~hero-colors');
1500            if ($i !== false) {
1501                $j = strpos($elm->innertext, '~~', $i + 2);
1502                if ($j !== false) {
1503                    if ($j > $i + 14) {
1504                        $color = substr($elm->innertext, $i + 14, $j - $i - 14);
1505                        $this->footerScript['hero-colors'] = 'mikio.setHeroColor(\'' . $color . '\')';
1506
1507                        $elm->innertext = preg_replace('/~~hero-colors (.+?)~~.*/ui', '', $elm->innertext);
1508                    }
1509
1510                    break;
1511                }
1512            }
1513        }
1514
1515        /* Hide parts - ~~hide-parts [parts]~~  */
1516        foreach ($html->find('p') as $elm) {
1517            $i = stripos($elm->innertext, '~~hide-parts');
1518            if ($i !== false) {
1519                $j = strpos($elm->innertext, '~~', $i + 2);
1520                if ($j !== false) {
1521                    if ($j > $i + 13) {
1522                        $parts = explode(' ', substr($elm->innertext, $i + 13, $j - $i - 13));
1523                        $script = '';
1524
1525                        foreach ($parts as $part) {
1526                            // $part = trim($part);
1527                            if (strlen($part) > 0) {
1528                                $script .= 'mikio.hidePart(\'' . $part . '\');';
1529                            }
1530                        }
1531
1532                        if (strlen($script) > 0) {
1533                            $this->footerScript['hide-parts'] = $script;
1534                        }
1535
1536                        $elm->innertext = preg_replace('/~~hide-parts (.+?)~~.*/ui', '', $elm->innertext);
1537                    }
1538
1539                    break;
1540                }
1541            }
1542        }
1543
1544
1545        /* Page Tags (tag plugin) */
1546        if ($this->getConf('tagsConsolidate')) {
1547            $tags = '';
1548            foreach ($html->find('div.tags a') as $elm) {
1549                $tags .= $elm->outertext;
1550            }
1551
1552            foreach ($html->find('div.tags') as $elm) {
1553                $elm->innertext = '';
1554                $elm->setAttribute('style', 'display:none');
1555            }
1556
1557            if ($tags != '') {
1558                $this->footerScript['tags'] = 'mikio.setTags(\'' . $tags . '\')';
1559            }
1560        }
1561
1562        // Configuration Manager
1563        if ($INPUT->str('page') == 'config') {
1564
1565            // Additional save buttons
1566            foreach ($html->find('#config__manager') as $cm) {
1567                $saveButtons = '';
1568
1569                foreach ($cm->find('p') as $elm) {
1570                    $saveButtons = $elm->outertext;
1571                    $saveButtons = str_replace('<p>', '<p style="text-align:right">', $saveButtons);
1572                    $elm->outertext = '';
1573                }
1574
1575                foreach ($cm->find('fieldset') as $elm) {
1576                    $elm->innertext .= $saveButtons;
1577                }
1578            }
1579        }
1580
1581        $content = $html->save();
1582        $html->clear();
1583        unset($html);
1584
1585        return $content;
1586    }
1587
1588
1589    /**
1590     * Get DokuWiki namespace/page/URI as link
1591     *
1592     * @param   string  $str            string to parse
1593     * @return  string                  parsed uri
1594     */
1595    public function getLink($str)
1596    {
1597        $i = strpos($str, '://');
1598        if ($i !== false) return $str;
1599
1600        return wl($str);
1601    }
1602
1603
1604    /**
1605     * Check if the user can edit current namespace/page
1606     *
1607     * @return  boolean                  user can edit
1608     */
1609    public function userCanEdit()
1610    {
1611        global $INFO;
1612        global $ID;
1613
1614        $wiki_file = wikiFN($ID);
1615        if (@!file_exists($wiki_file)) return true;
1616        if ($INFO['isadmin'] || $INFO['ismanager']) return true;
1617        // $meta_file = metaFN($ID, '.meta');
1618        if (!$INFO['meta']['user']) return true;
1619        if ($INFO['client'] ==  $INFO['meta']['user']) return true;
1620
1621        return false;
1622    }
1623
1624
1625    /**
1626     * Search for and return the uri of a media file
1627     *
1628     * @param string    $image              image name to search for (without extension)
1629     * @param bool      $searchCurrentNS    search the current namespace
1630     * @return string                       uri of the found media file
1631     */
1632    public function getMediaFile($image, $searchCurrentNS = TRUE, $propagate = TRUE)
1633    {
1634        global $INFO;
1635
1636        $ext = array('png', 'jpg', 'gif', 'svg');
1637
1638        if ($searchCurrentNS) $prefix[] = ':' . $INFO['namespace'] . ':';
1639        if ($propagate) {
1640            $prefix[] = ':';
1641            $prefix[] = ':wiki:';
1642        }
1643        $theme = $this->getConf('customTheme');
1644        if ($theme != '') $prefix[] = 'themes/' . $theme . '/images/';
1645        $prefix[] = 'images/';
1646
1647        $search = array();
1648        foreach ($prefix as $pitem) {
1649            foreach ($ext as $eitem) {
1650                $search[] = $pitem . $image . '.' . $eitem;
1651            }
1652        }
1653
1654        $img = '';
1655        $file = '';
1656        $url = '';
1657        $ismedia = false;
1658        $found = false;
1659
1660        foreach ($search as $img) {
1661            if (substr($img, 0, 1) == ':') {
1662                $file    = mediaFN($img);
1663                $ismedia = true;
1664            } else {
1665                $file    = tpl_incdir() . $img;
1666                $ismedia = false;
1667            }
1668
1669            if (file_exists($file)) {
1670                $found = true;
1671                break;
1672            }
1673        }
1674
1675        if (!$found) return false;
1676
1677        if ($ismedia) {
1678            $url = ml($img, '', true, '', false);
1679        } else {
1680            $url = tpl_basedir() . $img;
1681        }
1682
1683        return $url;
1684    }
1685
1686
1687    /**
1688     * Print or return the page title
1689     *
1690     * @param string    $page       page id or empty string for current page
1691     * @return string               generated content
1692     */
1693    public function getPageTitle($page = '')
1694    {
1695        global $ID, $conf;
1696
1697        $html = '';
1698
1699        if ($page == '') $page = $ID;
1700
1701        $html = p_get_first_heading($page);
1702        $html = strip_tags($html);
1703        $html = preg_replace('/\s+/', ' ', $html);
1704        $html .= ' [' . strip_tags($conf['title']) . ']';
1705        $html = trim($html);
1706
1707        return $html;
1708    }
1709
1710
1711    /**
1712     * Return inline theme icon
1713     *
1714     * @param   string  $type           icon to retreive
1715     * @return  string                  html icon content
1716     */
1717    public function mikioInlineIcon($type)
1718    {
1719        switch ($type) {
1720            case 'wrench':
1721                return '<svg class="mikio-iicon" xmlns="http://www.w3.org/2000/svg" viewBox="0 -256 1792 1792" style="fill:currentColor"><g transform="matrix(1,0,0,-1,53.152542,1217.0847)"><path d="m 384,64 q 0,26 -19,45 -19,19 -45,19 -26,0 -45,-19 -19,-19 -19,-45 0,-26 19,-45 19,-19 45,-19 26,0 45,19 19,19 19,45 z m 644,420 -682,-682 q -37,-37 -90,-37 -52,0 -91,37 L 59,-90 Q 21,-54 21,0 21,53 59,91 L 740,772 Q 779,674 854.5,598.5 930,523 1028,484 z m 634,435 q 0,-39 -23,-106 Q 1592,679 1474.5,595.5 1357,512 1216,512 1031,512 899.5,643.5 768,775 768,960 q 0,185 131.5,316.5 131.5,131.5 316.5,131.5 58,0 121.5,-16.5 63.5,-16.5 107.5,-46.5 16,-11 16,-28 0,-17 -16,-28 L 1152,1120 V 896 l 193,-107 q 5,3 79,48.5 74,45.5 135.5,81 61.5,35.5 70.5,35.5 15,0 23.5,-10 8.5,-10 8.5,-25 z"/></g></svg>';
1722            case 'file':
1723                return '<svg class="mikio-iicon" xmlns="http://www.w3.org/2000/svg" viewBox="0 -256 1792 1792" style="fill:currentColor"><g transform="matrix(1,0,0,-1,235.38983,1277.8305)" id="g2991"><path d="M 128,0 H 1152 V 768 H 736 q -40,0 -68,28 -28,28 -28,68 v 416 H 128 V 0 z m 640,896 h 299 L 768,1195 V 896 z M 1280,768 V -32 q 0,-40 -28,-68 -28,-28 -68,-28 H 96 q -40,0 -68,28 -28,28 -28,68 v 1344 q 0,40 28,68 28,28 68,28 h 544 q 40,0 88,-20 48,-20 76,-48 l 408,-408 q 28,-28 48,-76 20,-48 20,-88 z" id="path2993" inkscape:connector-curvature="0" xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape" /></g></svg>';
1724            case 'gear':
1725                return '<svg class="mikio-iicon" xmlns="http://www.w3.org/2000/svg" viewBox="0 -256 1792 1792" style="fill:currentColor"><g transform="matrix(1,0,0,-1,121.49153,1285.4237)" id="g3027"><path d="m 1024,640 q 0,106 -75,181 -75,75 -181,75 -106,0 -181,-75 -75,-75 -75,-181 0,-106 75,-181 75,-75 181,-75 106,0 181,75 75,75 75,181 z m 512,109 V 527 q 0,-12 -8,-23 -8,-11 -20,-13 l -185,-28 q -19,-54 -39,-91 35,-50 107,-138 10,-12 10,-25 0,-13 -9,-23 -27,-37 -99,-108 -72,-71 -94,-71 -12,0 -26,9 l -138,108 q -44,-23 -91,-38 -16,-136 -29,-186 -7,-28 -36,-28 H 657 q -14,0 -24.5,8.5 Q 622,-111 621,-98 L 593,86 q -49,16 -90,37 L 362,16 Q 352,7 337,7 323,7 312,18 186,132 147,186 q -7,10 -7,23 0,12 8,23 15,21 51,66.5 36,45.5 54,70.5 -27,50 -41,99 L 29,495 Q 16,497 8,507.5 0,518 0,531 v 222 q 0,12 8,23 8,11 19,13 l 186,28 q 14,46 39,92 -40,57 -107,138 -10,12 -10,24 0,10 9,23 26,36 98.5,107.5 72.5,71.5 94.5,71.5 13,0 26,-10 l 138,-107 q 44,23 91,38 16,136 29,186 7,28 36,28 h 222 q 14,0 24.5,-8.5 Q 914,1391 915,1378 l 28,-184 q 49,-16 90,-37 l 142,107 q 9,9 24,9 13,0 25,-10 129,-119 165,-170 7,-8 7,-22 0,-12 -8,-23 -15,-21 -51,-66.5 -36,-45.5 -54,-70.5 26,-50 41,-98 l 183,-28 q 13,-2 21,-12.5 8,-10.5 8,-23.5 z" id="path3029" inkscape:connector-curvature="0" /></g></svg>';
1726            case 'user':
1727                return '<svg class="mikio-iicon" xmlns="http://www.w3.org/2000/svg" viewBox="0 -256 1792 1792" style="fill:currentColor"><g transform="matrix(1,0,0,-1,197.42373,1300.6102)"><path d="M 1408,131 Q 1408,11 1335,-58.5 1262,-128 1141,-128 H 267 Q 146,-128 73,-58.5 0,11 0,131 0,184 3.5,234.5 7,285 17.5,343.5 28,402 44,452 q 16,50 43,97.5 27,47.5 62,81 35,33.5 85.5,53.5 50.5,20 111.5,20 9,0 42,-21.5 33,-21.5 74.5,-48 41.5,-26.5 108,-48 Q 637,565 704,565 q 67,0 133.5,21.5 66.5,21.5 108,48 41.5,26.5 74.5,48 33,21.5 42,21.5 61,0 111.5,-20 50.5,-20 85.5,-53.5 35,-33.5 62,-81 27,-47.5 43,-97.5 16,-50 26.5,-108.5 10.5,-58.5 14,-109 Q 1408,184 1408,131 z m -320,893 Q 1088,865 975.5,752.5 863,640 704,640 545,640 432.5,752.5 320,865 320,1024 320,1183 432.5,1295.5 545,1408 704,1408 863,1408 975.5,1295.5 1088,1183 1088,1024 z"/></g></svg>';
1728            case 'search':
1729                return '<svg class="mikio-iicon" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32" aria-hidden="true" style="fill:currentColor"><path d="M27 24.57l-5.647-5.648a8.895 8.895 0 0 0 1.522-4.984C22.875 9.01 18.867 5 13.938 5 9.01 5 5 9.01 5 13.938c0 4.929 4.01 8.938 8.938 8.938a8.887 8.887 0 0 0 4.984-1.522L24.568 27 27 24.57zm-13.062-4.445a6.194 6.194 0 0 1-6.188-6.188 6.195 6.195 0 0 1 6.188-6.188 6.195 6.195 0 0 1 6.188 6.188 6.195 6.195 0 0 1-6.188 6.188z"/></svg>';
1730            case 'home':
1731                return '<svg class="mikio-iicon" xmlns="http://www.w3.org/2000/svg" viewBox="0 -256 1792 1792" aria-hidden="true" style="fill:currentColor"><g transform="matrix(1,0,0,-1,68.338983,1285.4237)" id="g3015"><path d="M 1408,544 V 64 Q 1408,38 1389,19 1370,0 1344,0 H 960 V 384 H 704 V 0 H 320 q -26,0 -45,19 -19,19 -19,45 v 480 q 0,1 0.5,3 0.5,2 0.5,3 l 575,474 575,-474 q 1,-2 1,-6 z m 223,69 -62,-74 q -8,-9 -21,-11 h -3 q -13,0 -21,7 L 832,1112 140,535 q -12,-8 -24,-7 -13,2 -21,11 l -62,74 q -8,10 -7,23.5 1,13.5 11,21.5 l 719,599 q 32,26 76,26 44,0 76,-26 l 244,-204 v 195 q 0,14 9,23 9,9 23,9 h 192 q 14,0 23,-9 9,-9 9,-23 V 840 l 219,-182 q 10,-8 11,-21.5 1,-13.5 -7,-23.5 z" id="path3017" inkscape:connector-curvature="0" xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape" /></g></svg>';
1732        }
1733
1734        return '';
1735    }
1736
1737    /**
1738     * Finalize theme
1739     */
1740    public function finalize()
1741    {
1742    }
1743
1744    /**
1745     * Show Messages
1746     */
1747    public function showMessages()
1748    {
1749        global $ACT;
1750
1751        if ($this->lessIgnored) {
1752            msg('useLESS is enabled on the Mikio template, however is not supported on this server', 2, '', '', MSG_ADMINS_ONLY);
1753        }
1754
1755        $show = $this->getConf('showNotifications');
1756        if ($show == 'always' || ($show == 'admin' && $ACT == 'admin')) {
1757            global $MSG, $MSG_shown;
1758
1759            if (!isset($MSG)) {
1760                return;
1761            }
1762
1763            if (!isset($MSG_shown)) {
1764                $MSG_shown = array();
1765            }
1766
1767            foreach ($MSG as $msg) {
1768
1769                $hash = md5($msg['msg']);
1770                if (isset($MSG_shown[$hash])) {
1771                    continue;
1772                }
1773                // skip double messages
1774
1775                if (info_msg_allowed($msg)) {
1776
1777                    print '<div class="' . $msg['lvl'] . '">';
1778                    print $msg['msg'];
1779                    print '</div>';
1780                }
1781
1782                $MSG_shown[$hash] = true;
1783            }
1784
1785            unset($GLOBALS['MSG']);
1786        }
1787    }
1788
1789    /**
1790     * Dokuwiki version
1791     *
1792     * @return  string        the dw version name
1793     */
1794    public function dwVersion() {
1795        if(function_exists('getVersionData')) {
1796            $version_data = getVersionData();
1797            if(is_array($version_data) && array_key_exists('date', $version_data)) {
1798                $version_items = explode(' ', $version_data['date']);
1799                if(count($version_items) >= 2) {
1800                    return preg_replace('/[^a-zA-Z0-9 ]+/', '', strtolower($version_items[1]));
1801                }
1802            }
1803        }
1804
1805        return 'unknown';
1806    }
1807
1808    /**
1809     * Dokuwiki version number
1810     *
1811     * @return  string        the dw version date converted to integer
1812     */
1813    public function dwVersionNumber() {
1814        if(function_exists('getVersionData')) {
1815            $version_data = getVersionData();
1816            if(is_array($version_data) && array_key_exists('date', $version_data)) {
1817                $version_items = explode(' ', $version_data['date']);
1818                if(count($version_items) >= 1) {
1819                    return intval(preg_replace('/[^0-9]+/', '', strtolower($version_items[0])));
1820                }
1821            }
1822        }
1823
1824        return 0;
1825    }
1826}
1827
1828global $TEMPLATE;
1829$TEMPLATE = \dokuwiki\template\mikio\Template::getInstance();
1830