xref: /dokuwiki/inc/template.php (revision f2a2bc72e5b7df30d6d4d0a49c3a971037c4bba0)
1<?php
2
3/**
4 * DokuWiki template functions
5 *
6 * @license    GPL 2 (http://www.gnu.org/licenses/gpl.html)
7 * @author     Andreas Gohr <andi@splitbrain.org>
8 */
9
10use dokuwiki\ActionRouter;
11use dokuwiki\Action\Exception\FatalException;
12use dokuwiki\Extension\PluginInterface;
13use dokuwiki\Ui\Admin;
14use dokuwiki\StyleUtils;
15use dokuwiki\Menu\Item\AbstractItem;
16use dokuwiki\Form\Form;
17use dokuwiki\Menu\MobileMenu;
18use dokuwiki\Ui\Subscribe;
19use dokuwiki\Extension\AdminPlugin;
20use dokuwiki\Extension\Event;
21use dokuwiki\File\PageResolver;
22
23/**
24 * Access a template file
25 *
26 * Returns the path to the given file inside the current template, uses
27 * default template if the custom version doesn't exist.
28 *
29 * @param string $file
30 * @return string
31 *
32 * @author Andreas Gohr <andi@splitbrain.org>
33 */
34function template($file)
35{
36    global $conf;
37
38    if (@is_readable(DOKU_INC . 'lib/tpl/' . $conf['template'] . '/' . $file))
39        return DOKU_INC . 'lib/tpl/' . $conf['template'] . '/' . $file;
40
41    return DOKU_INC . 'lib/tpl/dokuwiki/' . $file;
42}
43
44/**
45 * Convenience function to access template dir from local FS
46 *
47 * This replaces the deprecated DOKU_TPLINC constant
48 *
49 * @param string $tpl The template to use, default to current one
50 * @return string
51 *
52 * @author Andreas Gohr <andi@splitbrain.org>
53 */
54function tpl_incdir($tpl = '')
55{
56    global $conf;
57    if (!$tpl) $tpl = $conf['template'];
58    return DOKU_INC . 'lib/tpl/' . $tpl . '/';
59}
60
61/**
62 * Convenience function to access template dir from web
63 *
64 * This replaces the deprecated DOKU_TPL constant
65 *
66 * @param string $tpl The template to use, default to current one
67 * @return string
68 *
69 * @author Andreas Gohr <andi@splitbrain.org>
70 */
71function tpl_basedir($tpl = '')
72{
73    global $conf;
74    if (!$tpl) $tpl = $conf['template'];
75    return DOKU_BASE . 'lib/tpl/' . $tpl . '/';
76}
77
78/**
79 * Print the content
80 *
81 * This function is used for printing all the usual content
82 * (defined by the global $ACT var) by calling the appropriate
83 * outputfunction(s) from html.php
84 *
85 * Everything that doesn't use the main template file isn't
86 * handled by this function. ACL stuff is not done here either.
87 *
88 * @param bool $prependTOC should the TOC be displayed here?
89 * @return bool true if any output
90 *
91 * @triggers TPL_ACT_RENDER
92 * @triggers TPL_CONTENT_DISPLAY
93 * @author Andreas Gohr <andi@splitbrain.org>
94 */
95function tpl_content($prependTOC = true)
96{
97    global $ACT;
98    global $INFO;
99    $INFO['prependTOC'] = $prependTOC;
100
101    ob_start();
102    Event::createAndTrigger('TPL_ACT_RENDER', $ACT, 'tpl_content_core');
103    $html_output = ob_get_clean();
104    Event::createAndTrigger('TPL_CONTENT_DISPLAY', $html_output, function ($html_output) {
105        echo $html_output;
106    });
107
108    return !empty($html_output);
109}
110
111/**
112 * Default Action of TPL_ACT_RENDER
113 *
114 * @return bool
115 */
116function tpl_content_core()
117{
118    $router = ActionRouter::getInstance();
119    try {
120        $router->getAction()->tplContent();
121    } catch (FatalException $e) {
122        // there was no content for the action
123        msg(hsc($e->getMessage()), -1);
124        return false;
125    }
126    return true;
127}
128
129/**
130 * Places the TOC where the function is called
131 *
132 * If you use this you most probably want to call tpl_content with
133 * a false argument
134 *
135 * @param bool $return Should the TOC be returned instead to be printed?
136 * @return string
137 *
138 * @author Andreas Gohr <andi@splitbrain.org>
139 */
140function tpl_toc($return = false)
141{
142    global $TOC;
143    global $ACT;
144    global $ID;
145    global $REV;
146    global $INFO;
147    global $conf;
148    $toc = [];
149
150    if (is_array($TOC)) {
151        // if a TOC was prepared in global scope, always use it
152        $toc = $TOC;
153    } elseif (($ACT == 'show' || str_starts_with($ACT, 'export')) && !$REV && $INFO['exists']) {
154        // get TOC from metadata, render if neccessary
155        $meta = p_get_metadata($ID, '', METADATA_RENDER_USING_CACHE);
156        $tocok = $meta['internal']['toc'] ?? true;
157        $toc = $meta['description']['tableofcontents'] ?? null;
158        if (!$tocok || !is_array($toc) || !$conf['tocminheads'] || count($toc) < $conf['tocminheads']) {
159            $toc = [];
160        }
161    } elseif ($ACT == 'admin') {
162        // try to load admin plugin TOC
163        /** @var AdminPlugin $plugin */
164        if ($plugin = plugin_getRequestAdminPlugin()) {
165            $toc = $plugin->getTOC();
166            $TOC = $toc; // avoid later rebuild
167        }
168    }
169
170    Event::createAndTrigger('TPL_TOC_RENDER', $toc, null, false);
171    $html = html_TOC($toc);
172    if ($return) return $html;
173    echo $html;
174    return '';
175}
176
177/**
178 * Handle the admin page contents
179 *
180 * @return bool
181 *
182 * @author Andreas Gohr <andi@splitbrain.org>
183 */
184function tpl_admin()
185{
186    global $INFO;
187    global $TOC;
188    global $INPUT;
189
190    $plugin = null;
191    $class = $INPUT->str('page');
192    if (!empty($class)) {
193        $pluginlist = plugin_list('admin');
194
195        if (in_array($class, $pluginlist)) {
196            // attempt to load the plugin
197            /** @var AdminPlugin $plugin */
198            $plugin = plugin_load('admin', $class);
199        }
200    }
201
202    if ($plugin instanceof PluginInterface) {
203        if (!is_array($TOC)) $TOC = $plugin->getTOC(); //if TOC wasn't requested yet
204        if ($INFO['prependTOC']) tpl_toc();
205        $plugin->html();
206    } else {
207        $admin = new Admin();
208        $admin->show();
209    }
210    return true;
211}
212
213/**
214 * Print the correct HTML meta headers
215 *
216 * This has to go into the head section of your template.
217 *
218 * @param bool $alt Should feeds and alternative format links be added?
219 * @return bool
220 * @throws JsonException
221 *
222 * @author Andreas Gohr <andi@splitbrain.org>
223 * @triggers TPL_METAHEADER_OUTPUT
224 */
225function tpl_metaheaders($alt = true)
226{
227    global $ID;
228    global $REV;
229    global $INFO;
230    global $JSINFO;
231    global $ACT;
232    global $QUERY;
233    global $lang;
234    global $conf;
235    global $updateVersion;
236    /** @var Input $INPUT */
237    global $INPUT;
238
239    // prepare the head array
240    $head = [];
241
242    // prepare seed for js and css
243    $tseed = $updateVersion;
244    $depends = getConfigFiles('main');
245    $depends[] = DOKU_CONF . "tpl/" . $conf['template'] . "/style.ini";
246    foreach ($depends as $f) $tseed .= @filemtime($f);
247    $tseed = md5($tseed);
248
249    // the usual stuff
250    $head['meta'][] = ['name' => 'generator', 'content' => 'DokuWiki'];
251    if (actionOK('search')) {
252        $head['link'][] = [
253            'rel' => 'search',
254            'type' => 'application/opensearchdescription+xml',
255            'href' => DOKU_BASE . 'lib/exe/opensearch.php',
256            'title' => $conf['title']
257        ];
258    }
259
260    $head['link'][] = ['rel' => 'start', 'href' => DOKU_BASE];
261    if (actionOK('index')) {
262        $head['link'][] = [
263            'rel' => 'contents',
264            'href' => wl($ID, 'do=index', false, '&'),
265            'title' => $lang['btn_index']
266        ];
267    }
268
269    if (actionOK('manifest')) {
270        $head['link'][] = [
271            'rel' => 'manifest',
272            'href' => DOKU_BASE . 'lib/exe/manifest.php'
273        ];
274    }
275
276    $styleUtil = new StyleUtils();
277    $styleIni = $styleUtil->cssStyleini();
278    $replacements = $styleIni['replacements'];
279    if (!empty($replacements['__theme_color__'])) {
280        $head['meta'][] = [
281            'name' => 'theme-color',
282            'content' => $replacements['__theme_color__']
283        ];
284    }
285
286    if ($alt) {
287        if (actionOK('rss')) {
288            $head['link'][] = [
289                'rel' => 'alternate',
290                'type' => 'application/rss+xml',
291                'title' => $lang['btn_recent'],
292                'href' => DOKU_BASE . 'feed.php'
293            ];
294            $head['link'][] = [
295                'rel' => 'alternate',
296                'type' => 'application/rss+xml',
297                'title' => $lang['currentns'],
298                'href' => DOKU_BASE . 'feed.php?mode=list&ns=' . (isset($INFO) ? $INFO['namespace'] : '')
299            ];
300        }
301        if (($ACT == 'show' || $ACT == 'search') && $INFO['writable']) {
302            $head['link'][] = [
303                'rel' => 'edit',
304                'title' => $lang['btn_edit'],
305                'href' => wl($ID, 'do=edit', false, '&')
306            ];
307        }
308
309        if (actionOK('rss') && $ACT == 'search') {
310            $head['link'][] = [
311                'rel' => 'alternate',
312                'type' => 'application/rss+xml',
313                'title' => $lang['searchresult'],
314                'href' => DOKU_BASE . 'feed.php?mode=search&q=' . $QUERY
315            ];
316        }
317
318        if (actionOK('export_xhtml')) {
319            $head['link'][] = [
320                'rel' => 'alternate',
321                'type' => 'text/html',
322                'title' => $lang['plainhtml'],
323                'href' => exportlink($ID, 'xhtml', '', false, '&')
324            ];
325        }
326
327        if (actionOK('export_raw')) {
328            $head['link'][] = [
329                'rel' => 'alternate',
330                'type' => 'text/plain',
331                'title' => $lang['wikimarkup'],
332                'href' => exportlink($ID, 'raw', '', false, '&')
333            ];
334        }
335    }
336
337    // setup robot tags appropriate for different modes
338    if (($ACT == 'show' || $ACT == 'export_xhtml') && !$REV) {
339        if ($INFO['exists']) {
340            //delay indexing:
341            if ((time() - $INFO['lastmod']) >= $conf['indexdelay'] && !isHiddenPage($ID)) {
342                $head['meta'][] = ['name' => 'robots', 'content' => 'index,follow'];
343            } else {
344                $head['meta'][] = ['name' => 'robots', 'content' => 'noindex,nofollow'];
345            }
346            $canonicalUrl = wl($ID, '', true, '&');
347            if ($ID == $conf['start']) {
348                $canonicalUrl = DOKU_URL;
349            }
350            $head['link'][] = ['rel' => 'canonical', 'href' => $canonicalUrl];
351        } else {
352            $head['meta'][] = ['name' => 'robots', 'content' => 'noindex,follow'];
353        }
354    } elseif (defined('DOKU_MEDIADETAIL')) {
355        $head['meta'][] = ['name' => 'robots', 'content' => 'index,follow'];
356    } else {
357        $head['meta'][] = ['name' => 'robots', 'content' => 'noindex,nofollow'];
358    }
359
360    // set metadata
361    if ($ACT == 'show' || $ACT == 'export_xhtml') {
362        // keywords (explicit or implicit)
363        if (!empty($INFO['meta']['subject'])) {
364            $head['meta'][] = ['name' => 'keywords', 'content' => implode(',', $INFO['meta']['subject'])];
365        } else {
366            $head['meta'][] = ['name' => 'keywords', 'content' => str_replace(':', ',', $ID)];
367        }
368    }
369
370    // load stylesheets
371    $head['link'][] = [
372        'rel' => 'stylesheet',
373        'href' => DOKU_BASE . 'lib/exe/css.php?t=' . rawurlencode($conf['template']) . '&tseed=' . $tseed
374    ];
375
376    $script = "var NS='" . (isset($INFO) ? $INFO['namespace'] : '') . "';";
377    if ($conf['useacl'] && $INPUT->server->str('REMOTE_USER')) {
378        $script .= "var SIG=" . toolbar_signature() . ";";
379    }
380    jsinfo();
381    $script .= 'var JSINFO = ' . json_encode($JSINFO, JSON_THROW_ON_ERROR) . ';';
382    $head['script'][] = ['_data' => $script];
383
384    // load jquery
385    $jquery = getCdnUrls();
386    foreach ($jquery as $src) {
387        $head['script'][] = [
388                '_data' => '',
389                'src' => $src
390            ] + ($conf['defer_js'] ? ['defer' => 'defer'] : []);
391    }
392
393    // load our javascript dispatcher
394    $head['script'][] = [
395            '_data' => '',
396            'src' => DOKU_BASE . 'lib/exe/js.php' . '?t=' . rawurlencode($conf['template']) . '&tseed=' . $tseed
397        ] + ($conf['defer_js'] ? ['defer' => 'defer'] : []);
398
399    // trigger event here
400    Event::createAndTrigger('TPL_METAHEADER_OUTPUT', $head, '_tpl_metaheaders_action', true);
401    return true;
402}
403
404/**
405 * prints the array build by tpl_metaheaders
406 *
407 * $data is an array of different header tags. Each tag can have multiple
408 * instances. Attributes are given as key value pairs. Values will be HTML
409 * encoded automatically so they should be provided as is in the $data array.
410 *
411 * For tags having a body attribute specify the body data in the special
412 * attribute '_data'. This field will NOT BE ESCAPED automatically.
413 *
414 * @param array $data
415 *
416 * @author Andreas Gohr <andi@splitbrain.org>
417 */
418function _tpl_metaheaders_action($data)
419{
420    foreach ($data as $tag => $inst) {
421        foreach ($inst as $attr) {
422            if (empty($attr)) {
423                continue;
424            }
425            echo '<', $tag, ' ', buildAttributes($attr);
426            if (isset($attr['_data']) || $tag == 'script') {
427                if ($tag == 'script' && isset($attr['_data']))
428                    $attr['_data'] = "/*<![CDATA[*/" .
429                        $attr['_data'] .
430                        "\n/*!]]>*/";
431
432                echo '>', $attr['_data'] ?? '', '</', $tag, '>';
433            } else {
434                echo '/>';
435            }
436            echo "\n";
437        }
438    }
439}
440
441/**
442 * Print a link
443 *
444 * Just builds a link.
445 *
446 * @param string $url
447 * @param string $name
448 * @param string $more
449 * @param bool $return if true return the link html, otherwise print
450 * @return bool|string html of the link, or true if printed
451 *
452 * @author Andreas Gohr <andi@splitbrain.org>
453 */
454function tpl_link($url, $name, $more = '', $return = false)
455{
456    $out = '<a href="' . $url . '" ';
457    if ($more) $out .= ' ' . $more;
458    $out .= ">$name</a>";
459    if ($return) return $out;
460    echo $out;
461    return true;
462}
463
464/**
465 * Prints a link to a WikiPage
466 *
467 * Wrapper around html_wikilink
468 *
469 * @param string $id page id
470 * @param string|null $name the name of the link
471 * @param bool $return
472 * @return true|string
473 *
474 * @author Andreas Gohr <andi@splitbrain.org>
475 */
476function tpl_pagelink($id, $name = null, $return = false)
477{
478    $out = '<bdi>' . html_wikilink($id, $name) . '</bdi>';
479    if ($return) return $out;
480    echo $out;
481    return true;
482}
483
484/**
485 * get the parent page
486 *
487 * Tries to find out which page is parent.
488 * returns false if none is available
489 *
490 * @param string $id page id
491 * @return false|string
492 *
493 * @author Andreas Gohr <andi@splitbrain.org>
494 */
495function tpl_getparent($id)
496{
497    $resolver = new PageResolver('root');
498
499    $parent = getNS($id) . ':';
500    $parent = $resolver->resolveId($parent);
501    if ($parent == $id) {
502        $pos = strrpos(getNS($id), ':');
503        $parent = substr($parent, 0, $pos) . ':';
504        $parent = $resolver->resolveId($parent);
505        if ($parent == $id) return false;
506    }
507    return $parent;
508}
509
510/**
511 * Print one of the buttons
512 *
513 * @param string $type
514 * @param bool $return
515 * @return bool|string html, or false if no data, true if printed
516 * @see    tpl_get_action
517 *
518 * @author Adrian Lang <mail@adrianlang.de>
519 * @deprecated 2017-09-01 see devel:menus
520 */
521function tpl_button($type, $return = false)
522{
523    dbg_deprecated('see devel:menus');
524    $data = tpl_get_action($type);
525    if ($data === false) {
526        return false;
527    } elseif (!is_array($data)) {
528        $out = sprintf($data, 'button');
529    } else {
530        /**
531         * @var string $accesskey
532         * @var string $id
533         * @var string $method
534         * @var array $params
535         */
536        extract($data);
537        if ($id === '#dokuwiki__top') {
538            $out = html_topbtn();
539        } else {
540            $out = html_btn($type, $id, $accesskey, $params, $method);
541        }
542    }
543    if ($return) return $out;
544    echo $out;
545    return true;
546}
547
548/**
549 * Like the action buttons but links
550 *
551 * @param string $type action command
552 * @param string $pre prefix of link
553 * @param string $suf suffix of link
554 * @param string $inner innerHML of link
555 * @param bool $return if true it returns html, otherwise prints
556 * @return bool|string html or false if no data, true if printed
557 *
558 * @see    tpl_get_action
559 * @author Adrian Lang <mail@adrianlang.de>
560 * @deprecated 2017-09-01 see devel:menus
561 */
562function tpl_actionlink($type, $pre = '', $suf = '', $inner = '', $return = false)
563{
564    dbg_deprecated('see devel:menus');
565    global $lang;
566    $data = tpl_get_action($type);
567    if ($data === false) {
568        return false;
569    } elseif (!is_array($data)) {
570        $out = sprintf($data, 'link');
571    } else {
572        /**
573         * @var string $accesskey
574         * @var string $id
575         * @var string $method
576         * @var bool $nofollow
577         * @var array $params
578         * @var string $replacement
579         */
580        extract($data);
581        if (strpos($id, '#') === 0) {
582            $linktarget = $id;
583        } else {
584            $linktarget = wl($id, $params);
585        }
586        $caption = $lang['btn_' . $type];
587        if (strpos($caption, '%s')) {
588            $caption = sprintf($caption, $replacement);
589        }
590        $akey = '';
591        $addTitle = '';
592        if ($accesskey) {
593            $akey = 'accesskey="' . $accesskey . '" ';
594            $addTitle = ' [' . strtoupper($accesskey) . ']';
595        }
596        $rel = $nofollow ? 'rel="nofollow" ' : '';
597        $out = tpl_link(
598            $linktarget,
599            $pre . ($inner ?: $caption) . $suf,
600            'class="action ' . $type . '" ' .
601            $akey . $rel .
602            'title="' . hsc($caption) . $addTitle . '"',
603            true
604        );
605    }
606    if ($return) return $out;
607    echo $out;
608    return true;
609}
610
611/**
612 * Check the actions and get data for buttons and links
613 *
614 * @param string $type
615 * @return array|bool|string
616 *
617 * @author Adrian Lang <mail@adrianlang.de>
618 * @author Andreas Gohr <andi@splitbrain.org>
619 * @author Matthias Grimm <matthiasgrimm@users.sourceforge.net>
620 * @deprecated 2017-09-01 see devel:menus
621 */
622function tpl_get_action($type)
623{
624    dbg_deprecated('see devel:menus');
625    if ($type == 'history') $type = 'revisions';
626    if ($type == 'subscription') $type = 'subscribe';
627    if ($type == 'img_backto') $type = 'imgBackto';
628
629    $class = '\\dokuwiki\\Menu\\Item\\' . ucfirst($type);
630    if (class_exists($class)) {
631        try {
632            /** @var AbstractItem $item */
633            $item = new $class();
634            $data = $item->getLegacyData();
635            $unknown = false;
636        } catch (RuntimeException $ignored) {
637            return false;
638        }
639    } else {
640        global $ID;
641        $data = [
642            'accesskey' => null,
643            'type' => $type,
644            'id' => $ID,
645            'method' => 'get',
646            'params' => ['do' => $type],
647            'nofollow' => true,
648            'replacement' => ''
649        ];
650        $unknown = true;
651    }
652
653    $evt = new Event('TPL_ACTION_GET', $data);
654    if ($evt->advise_before()) {
655        //handle unknown types
656        if ($unknown) {
657            $data = '[unknown %s type]';
658        }
659    }
660    $evt->advise_after();
661    unset($evt);
662
663    return $data;
664}
665
666/**
667 * Wrapper around tpl_button() and tpl_actionlink()
668 *
669 * @param string $type action command
670 * @param bool $link link or form button?
671 * @param string|bool $wrapper HTML element wrapper
672 * @param bool $return return or print
673 * @param string $pre prefix for links
674 * @param string $suf suffix for links
675 * @param string $inner inner HTML for links
676 * @return bool|string
677 *
678 * @author Anika Henke <anika@selfthinker.org>
679 * @deprecated 2017-09-01 see devel:menus
680 */
681function tpl_action($type, $link = false, $wrapper = false, $return = false, $pre = '', $suf = '', $inner = '')
682{
683    dbg_deprecated('see devel:menus');
684    $out = '';
685    if ($link) {
686        $out .= tpl_actionlink($type, $pre, $suf, $inner, true);
687    } else {
688        $out .= tpl_button($type, true);
689    }
690    if ($out && $wrapper) $out = "<$wrapper>$out</$wrapper>";
691
692    if ($return) return $out;
693    echo $out;
694    return (bool)$out;
695}
696
697/**
698 * Print the search form
699 *
700 * If the first parameter is given a div with the ID 'qsearch_out' will
701 * be added which instructs the ajax pagequicksearch to kick in and place
702 * its output into this div. The second parameter controls the propritary
703 * attribute autocomplete. If set to false this attribute will be set with an
704 * value of "off" to instruct the browser to disable it's own built in
705 * autocompletion feature (MSIE and Firefox)
706 *
707 * @param bool $ajax
708 * @param bool $autocomplete
709 * @return bool
710 *
711 * @author Andreas Gohr <andi@splitbrain.org>
712 */
713function tpl_searchform($ajax = true, $autocomplete = true)
714{
715    global $lang;
716    global $ACT;
717    global $QUERY;
718    global $ID;
719
720    // don't print the search form if search action has been disabled
721    if (!actionOK('search')) return false;
722
723    $searchForm = new Form([
724        'action' => wl(),
725        'method' => 'get',
726        'role' => 'search',
727        'class' => 'search',
728        'id' => 'dw__search',
729    ], true);
730    $searchForm->addTagOpen('div')->addClass('no');
731    $searchForm->setHiddenField('do', 'search');
732    $searchForm->setHiddenField('id', $ID);
733    $searchForm->addTextInput('q')
734        ->addClass('edit')
735        ->attrs([
736            'title' => '[F]',
737            'accesskey' => 'f',
738            'placeholder' => $lang['btn_search'],
739            'autocomplete' => $autocomplete ? 'on' : 'off',
740        ])
741        ->id('qsearch__in')
742        ->val($ACT === 'search' ? $QUERY : '')
743        ->useInput(false);
744    $searchForm->addButton('', $lang['btn_search'])->attrs([
745        'type' => 'submit',
746        'title' => $lang['btn_search'],
747    ]);
748    if ($ajax) {
749        $searchForm->addTagOpen('div')->id('qsearch__out')->addClass('ajax_qsearch JSpopup');
750        $searchForm->addTagClose('div');
751    }
752    $searchForm->addTagClose('div');
753
754    echo $searchForm->toHTML('QuickSearch');
755
756    return true;
757}
758
759/**
760 * Print the breadcrumbs trace
761 *
762 * @param string $sep Separator between entries
763 * @param bool $return return or print
764 * @return bool|string
765 *
766 * @author Andreas Gohr <andi@splitbrain.org>
767 */
768function tpl_breadcrumbs($sep = null, $return = false)
769{
770    global $lang;
771    global $conf;
772
773    //check if enabled
774    if (!$conf['breadcrumbs']) return false;
775
776    //set default
777    if (is_null($sep)) $sep = '•';
778
779    $out = '';
780
781    $crumbs = breadcrumbs(); //setup crumb trace
782
783    $crumbs_sep = ' <span class="bcsep">' . $sep . '</span> ';
784
785    //render crumbs, highlight the last one
786    $out .= '<span class="bchead">' . $lang['breadcrumb'] . '</span>';
787    $last = count($crumbs);
788    $i = 0;
789    foreach ($crumbs as $id => $name) {
790        $i++;
791        $out .= $crumbs_sep;
792        if ($i == $last) $out .= '<span class="curid">';
793        $out .= '<bdi>' . tpl_link(wl($id), hsc($name), 'class="breadcrumbs" title="' . $id . '"', true) . '</bdi>';
794        if ($i == $last) $out .= '</span>';
795    }
796    if ($return) return $out;
797    echo $out;
798    return (bool)$out;
799}
800
801/**
802 * Hierarchical breadcrumbs
803 *
804 * This code was suggested as replacement for the usual breadcrumbs.
805 * It only makes sense with a deep site structure.
806 *
807 * @param string $sep Separator between entries
808 * @param bool $return return or print
809 * @return bool|string
810 *
811 * @todo   May behave strangely in RTL languages
812 * @author <fredrik@averpil.com>
813 * @author Andreas Gohr <andi@splitbrain.org>
814 * @author Nigel McNie <oracle.shinoda@gmail.com>
815 * @author Sean Coates <sean@caedmon.net>
816 */
817function tpl_youarehere($sep = null, $return = false)
818{
819    global $conf;
820    global $ID;
821    global $lang;
822
823    // check if enabled
824    if (!$conf['youarehere']) return false;
825
826    //set default
827    if (is_null($sep)) $sep = ' » ';
828
829    $out = '';
830
831    $parts = explode(':', $ID);
832    $count = count($parts);
833
834    $out .= '<span class="bchead">' . $lang['youarehere'] . ' </span>';
835
836    // always print the startpage
837    $out .= '<span class="home">' . tpl_pagelink(':' . $conf['start'], null, true) . '</span>';
838
839    // print intermediate namespace links
840    $part = '';
841    for ($i = 0; $i < $count - 1; $i++) {
842        $part .= $parts[$i] . ':';
843        $page = $part;
844        if ($page == $conf['start']) continue; // Skip startpage
845
846        // output
847        $out .= $sep . tpl_pagelink($page, null, true);
848    }
849
850    // print current page, skipping start page, skipping for namespace index
851    if (isset($page)) {
852        $page = (new PageResolver('root'))->resolveId($page);
853        if ($page == $part . $parts[$i]) {
854            if ($return) return $out;
855            echo $out;
856            return true;
857        }
858    }
859    $page = $part . $parts[$i];
860    if ($page == $conf['start']) {
861        if ($return) return $out;
862        echo $out;
863        return true;
864    }
865    $out .= $sep;
866    $out .= tpl_pagelink($page, null, true);
867    if ($return) return $out;
868    echo $out;
869    return (bool)$out;
870}
871
872/**
873 * Print info if the user is logged in
874 * and show full name in that case
875 *
876 * Could be enhanced with a profile link in future?
877 *
878 * @return bool
879 *
880 * @author Andreas Gohr <andi@splitbrain.org>
881 */
882function tpl_userinfo()
883{
884    global $lang;
885    /** @var Input $INPUT */
886    global $INPUT;
887
888    if ($INPUT->server->str('REMOTE_USER')) {
889        echo $lang['loggedinas'] . ' ' . userlink();
890        return true;
891    }
892    return false;
893}
894
895/**
896 * Print some info about the current page
897 *
898 * @param bool $ret return content instead of printing it
899 * @return bool|string
900 *
901 * @author Andreas Gohr <andi@splitbrain.org>
902 */
903function tpl_pageinfo($ret = false)
904{
905    global $conf;
906    global $lang;
907    global $INFO;
908    global $ID;
909
910    // return if we are not allowed to view the page
911    if (!auth_quickaclcheck($ID)) {
912        return false;
913    }
914
915    // prepare date and path
916    $fn = $INFO['filepath'];
917    if (!$conf['fullpath']) {
918        if ($INFO['rev']) {
919            $fn = str_replace($conf['olddir'] . '/', '', $fn);
920        } else {
921            $fn = str_replace($conf['datadir'] . '/', '', $fn);
922        }
923    }
924    $fn = utf8_decodeFN($fn);
925    $date = dformat($INFO['lastmod']);
926
927    // print it
928    if ($INFO['exists']) {
929        $out = '<bdi>' . $fn . '</bdi>';
930        $out .= ' · ';
931        $out .= $lang['lastmod'];
932        $out .= ' ';
933        $out .= $date;
934        if ($INFO['editor']) {
935            $out .= ' ' . $lang['by'] . ' ';
936            $out .= '<bdi>' . editorinfo($INFO['editor']) . '</bdi>';
937        } else {
938            $out .= ' (' . $lang['external_edit'] . ')';
939        }
940        if ($INFO['locked']) {
941            $out .= ' · ';
942            $out .= $lang['lockedby'];
943            $out .= ' ';
944            $out .= '<bdi>' . editorinfo($INFO['locked']) . '</bdi>';
945        }
946        if ($ret) {
947            return $out;
948        } else {
949            echo $out;
950            return true;
951        }
952    }
953    return false;
954}
955
956/**
957 * Prints or returns the name of the given page (current one if none given).
958 *
959 * If useheading is enabled this will use the first headline else
960 * the given ID is used.
961 *
962 * @param string $id page id
963 * @param bool $ret return content instead of printing
964 * @return bool|string
965 *
966 * @author Andreas Gohr <andi@splitbrain.org>
967 */
968function tpl_pagetitle($id = null, $ret = false)
969{
970    global $ACT, $conf, $lang;
971
972    if (is_null($id)) {
973        global $ID;
974        $id = $ID;
975    }
976
977    $name = $id;
978    if (useHeading('navigation')) {
979        $first_heading = p_get_first_heading($id);
980        if ($first_heading) $name = $first_heading;
981    }
982
983    // default page title is the page name, modify with the current action
984    switch ($ACT) {
985        // admin functions
986        case 'admin':
987            $page_title = $lang['btn_admin'];
988            // try to get the plugin name
989            /** @var AdminPlugin $plugin */
990            if ($plugin = plugin_getRequestAdminPlugin()) {
991                $plugin_title = $plugin->getMenuText($conf['lang']);
992                $page_title = $plugin_title ?: $plugin->getPluginName();
993            }
994            break;
995
996        // show action as title
997        case 'login':
998        case 'profile':
999        case 'register':
1000        case 'resendpwd':
1001        case 'index':
1002        case 'search':
1003            $page_title = $lang['btn_' . $ACT];
1004            break;
1005
1006        // add pen during editing
1007        case 'edit':
1008        case 'preview':
1009            $page_title = "✎ " . $name;
1010            break;
1011
1012        // add action to page name
1013        case 'revisions':
1014            $page_title = $name . ' - ' . $lang['btn_revs'];
1015            break;
1016
1017        // add action to page name
1018        case 'backlink':
1019        case 'recent':
1020        case 'subscribe':
1021            $page_title = $name . ' - ' . $lang['btn_' . $ACT];
1022            break;
1023
1024        default: // SHOW and anything else not included
1025            $page_title = $name;
1026    }
1027
1028    if ($ret) {
1029        return hsc($page_title);
1030    } else {
1031        echo hsc($page_title);
1032        return true;
1033    }
1034}
1035
1036/**
1037 * Returns the requested EXIF/IPTC tag from the current image
1038 *
1039 * If $tags is an array all given tags are tried until a
1040 * value is found. If no value is found $alt is returned.
1041 *
1042 * Which texts are known is defined in the functions _exifTagNames
1043 * and _iptcTagNames() in inc/jpeg.php (You need to prepend IPTC
1044 * to the names of the latter one)
1045 *
1046 * Only allowed in: detail.php
1047 *
1048 * @param array|string $tags tag or array of tags to try
1049 * @param string $alt alternative output if no data was found
1050 * @param null|string $src the image src, uses global $SRC if not given
1051 * @return string
1052 *
1053 * @author Andreas Gohr <andi@splitbrain.org>
1054 */
1055function tpl_img_getTag($tags, $alt = '', $src = null)
1056{
1057    // Init Exif Reader
1058    global $SRC, $imgMeta;
1059
1060    if (is_null($src)) $src = $SRC;
1061    if (is_null($src)) return $alt;
1062
1063    if (!isset($imgMeta)) {
1064        $imgMeta = new JpegMeta($src);
1065    }
1066    if ($imgMeta === false) return $alt;
1067    $info = cleanText($imgMeta->getField($tags));
1068    if (!$info) return $alt;
1069    return $info;
1070}
1071
1072
1073/**
1074 * Garbage collects up the open JpegMeta object.
1075 */
1076function tpl_img_close()
1077{
1078    global $imgMeta;
1079    $imgMeta = null;
1080}
1081
1082/**
1083 * Prints a html description list of the metatags of the current image
1084 */
1085function tpl_img_meta()
1086{
1087    global $lang;
1088
1089    $tags = tpl_get_img_meta();
1090
1091    echo '<dl>';
1092    foreach ($tags as $tag) {
1093        $label = $lang[$tag['langkey']];
1094        if (!$label) $label = $tag['langkey'] . ':';
1095
1096        echo '<dt>' . $label . '</dt><dd>';
1097        if ($tag['type'] == 'date') {
1098            echo dformat($tag['value']);
1099        } else {
1100            echo hsc($tag['value']);
1101        }
1102        echo '</dd>';
1103    }
1104    echo '</dl>';
1105}
1106
1107/**
1108 * Returns metadata as configured in mediameta config file, ready for creating html
1109 *
1110 * @return array with arrays containing the entries:
1111 *   - string langkey  key to lookup in the $lang var, if not found printed as is
1112 *   - string type     type of value
1113 *   - string value    tag value (unescaped)
1114 */
1115function tpl_get_img_meta()
1116{
1117
1118    $config_files = getConfigFiles('mediameta');
1119    foreach ($config_files as $config_file) {
1120        if (file_exists($config_file)) {
1121            include($config_file);
1122        }
1123    }
1124    $tags = [];
1125    foreach ($fields as $tag) {
1126        $t = [];
1127        if (!empty($tag[0])) {
1128            $t = [$tag[0]];
1129        }
1130        if (isset($tag[3]) && is_array($tag[3])) {
1131            $t = array_merge($t, $tag[3]);
1132        }
1133        $value = tpl_img_getTag($t);
1134        if ($value) {
1135            $tags[] = ['langkey' => $tag[1], 'type' => $tag[2], 'value' => $value];
1136        }
1137    }
1138    return $tags;
1139}
1140
1141/**
1142 * Prints the image with a link to the full sized version
1143 *
1144 * Only allowed in: detail.php
1145 *
1146 * @triggers TPL_IMG_DISPLAY
1147 * @param int $maxwidth - maximal width of the image
1148 * @param int $maxheight - maximal height of the image
1149 * @param bool $link - link to the orginal size?
1150 * @param array $params - additional image attributes
1151 * @return bool Result of TPL_IMG_DISPLAY
1152 */
1153function tpl_img($maxwidth = 0, $maxheight = 0, $link = true, $params = null)
1154{
1155    global $IMG;
1156    /** @var Input $INPUT */
1157    global $INPUT;
1158    global $REV;
1159    $w = (int)tpl_img_getTag('File.Width');
1160    $h = (int)tpl_img_getTag('File.Height');
1161
1162    //resize to given max values
1163    $ratio = 1;
1164    if ($w >= $h) {
1165        if ($maxwidth && $w >= $maxwidth) {
1166            $ratio = $maxwidth / $w;
1167        } elseif ($maxheight && $h > $maxheight) {
1168            $ratio = $maxheight / $h;
1169        }
1170    } elseif ($maxheight && $h >= $maxheight) {
1171        $ratio = $maxheight / $h;
1172    } elseif ($maxwidth && $w > $maxwidth) {
1173        $ratio = $maxwidth / $w;
1174    }
1175    if ($ratio) {
1176        $w = floor($ratio * $w);
1177        $h = floor($ratio * $h);
1178    }
1179
1180    //prepare URLs
1181    $url = ml($IMG, ['cache' => $INPUT->str('cache'), 'rev' => $REV], true, '&');
1182    $src = ml($IMG, ['cache' => $INPUT->str('cache'), 'rev' => $REV, 'w' => $w, 'h' => $h], true, '&');
1183
1184    //prepare attributes
1185    $alt = tpl_img_getTag('Simple.Title');
1186    if (is_null($params)) {
1187        $p = [];
1188    } else {
1189        $p = $params;
1190    }
1191    if ($w) $p['width'] = $w;
1192    if ($h) $p['height'] = $h;
1193    $p['class'] = 'img_detail';
1194    if ($alt) {
1195        $p['alt'] = $alt;
1196        $p['title'] = $alt;
1197    } else {
1198        $p['alt'] = '';
1199    }
1200    $p['src'] = $src;
1201
1202    $data = ['url' => ($link ? $url : null), 'params' => $p];
1203    return Event::createAndTrigger('TPL_IMG_DISPLAY', $data, '_tpl_img_action', true);
1204}
1205
1206/**
1207 * Default action for TPL_IMG_DISPLAY
1208 *
1209 * @param array $data
1210 * @return bool
1211 */
1212function _tpl_img_action($data)
1213{
1214    global $lang;
1215    $p = buildAttributes($data['params']);
1216
1217    if ($data['url']) echo '<a href="' . hsc($data['url']) . '" title="' . $lang['mediaview'] . '">';
1218    echo '<img ' . $p . '/>';
1219    if ($data['url']) echo '</a>';
1220    return true;
1221}
1222
1223/**
1224 * This function inserts a small gif which in reality is the indexer function.
1225 *
1226 * Should be called somewhere at the very end of the main.php template
1227 *
1228 * @return bool
1229 */
1230function tpl_indexerWebBug()
1231{
1232    global $ID;
1233
1234    $p = [];
1235    $p['src'] = DOKU_BASE . 'lib/exe/taskrunner.php?id=' . rawurlencode($ID) .
1236        '&' . time();
1237    $p['width'] = 2; //no more 1x1 px image because we live in times of ad blockers...
1238    $p['height'] = 1;
1239    $p['alt'] = '';
1240    $att = buildAttributes($p);
1241    echo "<img $att />";
1242    return true;
1243}
1244
1245/**
1246 * tpl_getConf($id)
1247 *
1248 * use this function to access template configuration variables
1249 *
1250 * @param string $id name of the value to access
1251 * @param mixed $notset what to return if the setting is not available
1252 * @return mixed
1253 */
1254function tpl_getConf($id, $notset = false)
1255{
1256    global $conf;
1257    static $tpl_configloaded = false;
1258
1259    $tpl = $conf['template'];
1260
1261    if (!$tpl_configloaded) {
1262        $tconf = tpl_loadConfig();
1263        if ($tconf !== false) {
1264            foreach ($tconf as $key => $value) {
1265                if (isset($conf['tpl'][$tpl][$key])) continue;
1266                $conf['tpl'][$tpl][$key] = $value;
1267            }
1268            $tpl_configloaded = true;
1269        }
1270    }
1271
1272    return $conf['tpl'][$tpl][$id] ?? $notset;
1273}
1274
1275/**
1276 * tpl_loadConfig()
1277 *
1278 * reads all template configuration variables
1279 * this function is automatically called by tpl_getConf()
1280 *
1281 * @return false|array
1282 */
1283function tpl_loadConfig()
1284{
1285
1286    $file = tpl_incdir() . '/conf/default.php';
1287    $conf = [];
1288
1289    if (!file_exists($file)) return false;
1290
1291    // load default config file
1292    include($file);
1293
1294    return $conf;
1295}
1296
1297// language methods
1298
1299/**
1300 * tpl_getLang($id)
1301 *
1302 * use this function to access template language variables
1303 *
1304 * @param string $id key of language string
1305 * @return string
1306 */
1307function tpl_getLang($id)
1308{
1309    static $lang = [];
1310
1311    if (count($lang) === 0) {
1312        global $conf, $config_cascade; // definitely don't invoke "global $lang"
1313
1314        $path = tpl_incdir() . 'lang/';
1315
1316        $lang = [];
1317
1318        // don't include once
1319        @include($path . 'en/lang.php');
1320        foreach ($config_cascade['lang']['template'] as $config_file) {
1321            if (file_exists($config_file . $conf['template'] . '/en/lang.php')) {
1322                include($config_file . $conf['template'] . '/en/lang.php');
1323            }
1324        }
1325
1326        if ($conf['lang'] != 'en') {
1327            @include($path . $conf['lang'] . '/lang.php');
1328            foreach ($config_cascade['lang']['template'] as $config_file) {
1329                if (file_exists($config_file . $conf['template'] . '/' . $conf['lang'] . '/lang.php')) {
1330                    include($config_file . $conf['template'] . '/' . $conf['lang'] . '/lang.php');
1331                }
1332            }
1333        }
1334    }
1335    return $lang[$id] ?? '';
1336}
1337
1338/**
1339 * Retrieve a language dependent file and pass to xhtml renderer for display
1340 * template equivalent of p_locale_xhtml()
1341 *
1342 * @param string $id id of language dependent wiki page
1343 * @return  string     parsed contents of the wiki page in xhtml format
1344 */
1345function tpl_locale_xhtml($id)
1346{
1347    return p_cached_output(tpl_localeFN($id));
1348}
1349
1350/**
1351 * Prepends appropriate path for a language dependent filename
1352 *
1353 * @param string $id id of localized text
1354 * @return string wiki text
1355 */
1356function tpl_localeFN($id)
1357{
1358    $path = tpl_incdir() . 'lang/';
1359    global $conf;
1360    $file = DOKU_CONF . 'template_lang/' . $conf['template'] . '/' . $conf['lang'] . '/' . $id . '.txt';
1361    if (!file_exists($file)) {
1362        $file = $path . $conf['lang'] . '/' . $id . '.txt';
1363        if (!file_exists($file)) {
1364            //fall back to english
1365            $file = $path . 'en/' . $id . '.txt';
1366        }
1367    }
1368    return $file;
1369}
1370
1371/**
1372 * prints the "main content" in the mediamanager popup
1373 *
1374 * Depending on the user's actions this may be a list of
1375 * files in a namespace, the meta editing dialog or
1376 * a message of referencing pages
1377 *
1378 * Only allowed in mediamanager.php
1379 *
1380 * @triggers MEDIAMANAGER_CONTENT_OUTPUT
1381 * @param bool $fromajax - set true when calling this function via ajax
1382 * @param string $sort
1383 *
1384 * @author Andreas Gohr <andi@splitbrain.org>
1385 */
1386function tpl_mediaContent($fromajax = false, $sort = 'natural')
1387{
1388    global $IMG;
1389    global $AUTH;
1390    global $INUSE;
1391    global $NS;
1392    global $JUMPTO;
1393    /** @var Input $INPUT */
1394    global $INPUT;
1395
1396    $do = $INPUT->extract('do')->str('do');
1397    if (in_array($do, ['save', 'cancel'])) $do = '';
1398
1399    if (!$do) {
1400        if ($INPUT->bool('edit')) {
1401            $do = 'metaform';
1402        } elseif (is_array($INUSE)) {
1403            $do = 'filesinuse';
1404        } else {
1405            $do = 'filelist';
1406        }
1407    }
1408
1409    // output the content pane, wrapped in an event.
1410    if (!$fromajax) echo '<div id="media__content">';
1411    $data = ['do' => $do];
1412    $evt = new Event('MEDIAMANAGER_CONTENT_OUTPUT', $data);
1413    if ($evt->advise_before()) {
1414        $do = $data['do'];
1415        if ($do == 'filesinuse') {
1416            media_filesinuse($INUSE, $IMG);
1417        } elseif ($do == 'filelist') {
1418            media_filelist($NS, $AUTH, $JUMPTO, false, $sort);
1419        } elseif ($do == 'searchlist') {
1420            media_searchlist($INPUT->str('q'), $NS, $AUTH);
1421        } else {
1422            msg('Unknown action ' . hsc($do), -1);
1423        }
1424    }
1425    $evt->advise_after();
1426    unset($evt);
1427    if (!$fromajax) echo '</div>';
1428}
1429
1430/**
1431 * Prints the central column in full-screen media manager
1432 * Depending on the opened tab this may be a list of
1433 * files in a namespace, upload form or search form
1434 *
1435 * @author Kate Arzamastseva <pshns@ukr.net>
1436 */
1437function tpl_mediaFileList()
1438{
1439    global $AUTH;
1440    global $NS;
1441    global $JUMPTO;
1442    global $lang;
1443    /** @var Input $INPUT */
1444    global $INPUT;
1445
1446    $opened_tab = $INPUT->str('tab_files');
1447    if (!$opened_tab || !in_array($opened_tab, ['files', 'upload', 'search'])) $opened_tab = 'files';
1448    if ($INPUT->str('mediado') == 'update') $opened_tab = 'upload';
1449
1450    echo '<h2 class="a11y">' . $lang['mediaselect'] . '</h2>' . NL;
1451
1452    media_tabs_files($opened_tab);
1453
1454    echo '<div class="panelHeader">' . NL;
1455    echo '<h3>';
1456    $tabTitle = $NS ?: '[' . $lang['mediaroot'] . ']';
1457    printf($lang['media_' . $opened_tab], '<strong>' . hsc($tabTitle) . '</strong>');
1458    echo '</h3>' . NL;
1459    if ($opened_tab === 'search' || $opened_tab === 'files') {
1460        media_tab_files_options();
1461    }
1462    echo '</div>' . NL;
1463
1464    echo '<div class="panelContent">' . NL;
1465    if ($opened_tab == 'files') {
1466        media_tab_files($NS, $AUTH, $JUMPTO);
1467    } elseif ($opened_tab == 'upload') {
1468        media_tab_upload($NS, $AUTH, $JUMPTO);
1469    } elseif ($opened_tab == 'search') {
1470        media_tab_search($NS, $AUTH);
1471    }
1472    echo '</div>' . NL;
1473}
1474
1475/**
1476 * Prints the third column in full-screen media manager
1477 * Depending on the opened tab this may be details of the
1478 * selected file, the meta editing dialog or
1479 * list of file revisions
1480 *
1481 * @param string $image
1482 * @param boolean $rev
1483 *
1484 * @author Kate Arzamastseva <pshns@ukr.net>
1485 */
1486function tpl_mediaFileDetails($image, $rev)
1487{
1488    global $conf, $DEL, $lang;
1489    /** @var Input $INPUT */
1490    global $INPUT;
1491
1492    $removed = (
1493        !file_exists(mediaFN($image)) &&
1494        file_exists(mediaMetaFN($image, '.changes')) &&
1495        $conf['mediarevisions']
1496    );
1497    if (!$image || (!file_exists(mediaFN($image)) && !$removed) || $DEL) return;
1498    if ($rev && !file_exists(mediaFN($image, $rev))) $rev = false;
1499    $ns = getNS($image);
1500    $do = $INPUT->str('mediado');
1501
1502    $opened_tab = $INPUT->str('tab_details');
1503
1504    $tab_array = ['view'];
1505    [, $mime] = mimetype($image);
1506    if ($mime == 'image/jpeg') {
1507        $tab_array[] = 'edit';
1508    }
1509    if ($conf['mediarevisions']) {
1510        $tab_array[] = 'history';
1511    }
1512
1513    if (!$opened_tab || !in_array($opened_tab, $tab_array)) $opened_tab = 'view';
1514    if ($INPUT->bool('edit')) $opened_tab = 'edit';
1515    if ($do == 'restore') $opened_tab = 'view';
1516
1517    media_tabs_details($image, $opened_tab);
1518
1519    echo '<div class="panelHeader"><h3>';
1520    [$ext] = mimetype($image, false);
1521    $class = preg_replace('/[^_\-a-z0-9]+/i', '_', $ext);
1522    $class = 'select mediafile mf_' . $class;
1523
1524    $attributes = $rev ? ['rev' => $rev] : [];
1525    $tabTitle = sprintf(
1526        '<strong><a href="%s" class="%s" title="%s">%s</a></strong>',
1527        ml($image, $attributes),
1528        $class,
1529        $lang['mediaview'],
1530        $image
1531    );
1532    if ($opened_tab === 'view' && $rev) {
1533        printf($lang['media_viewold'], $tabTitle, dformat($rev));
1534    } else {
1535        printf($lang['media_' . $opened_tab], $tabTitle);
1536    }
1537
1538    echo '</h3></div>' . NL;
1539
1540    echo '<div class="panelContent">' . NL;
1541
1542    if ($opened_tab == 'view') {
1543        media_tab_view($image, $ns, null, $rev);
1544    } elseif ($opened_tab == 'edit' && !$removed) {
1545        media_tab_edit($image, $ns);
1546    } elseif ($opened_tab == 'history' && $conf['mediarevisions']) {
1547        media_tab_history($image, $ns);
1548    }
1549
1550    echo '</div>' . NL;
1551}
1552
1553/**
1554 * prints the namespace tree in the mediamanager popup
1555 *
1556 * Only allowed in mediamanager.php
1557 *
1558 * @author Andreas Gohr <andi@splitbrain.org>
1559 */
1560function tpl_mediaTree()
1561{
1562    global $NS;
1563    echo '<div id="media__tree">';
1564    media_nstree($NS);
1565    echo '</div>';
1566}
1567
1568/**
1569 * Print a dropdown menu with all DokuWiki actions
1570 *
1571 * Note: this will not use any pretty URLs
1572 *
1573 * @param string $empty empty option label
1574 * @param string $button submit button label
1575 *
1576 * @author Andreas Gohr <andi@splitbrain.org>
1577 * @deprecated 2017-09-01 see devel:menus
1578 */
1579function tpl_actiondropdown($empty = '', $button = '&gt;')
1580{
1581    dbg_deprecated('see devel:menus');
1582    $menu = new MobileMenu();
1583    echo $menu->getDropdown($empty, $button);
1584}
1585
1586/**
1587 * Print a informational line about the used license
1588 *
1589 * @param string $img print image? (|button|badge)
1590 * @param bool $imgonly skip the textual description?
1591 * @param bool $return when true don't print, but return HTML
1592 * @param bool $wrap wrap in div with class="license"?
1593 * @return string
1594 *
1595 * @author Andreas Gohr <andi@splitbrain.org>
1596 */
1597function tpl_license($img = 'badge', $imgonly = false, $return = false, $wrap = true)
1598{
1599    global $license;
1600    global $conf;
1601    global $lang;
1602    if (!$conf['license']) return '';
1603    if (!is_array($license[$conf['license']])) return '';
1604    $lic = $license[$conf['license']];
1605    $target = ($conf['target']['extern']) ? ' target="' . $conf['target']['extern'] . '"' : '';
1606
1607    $out = '';
1608    if ($wrap) $out .= '<div class="license">';
1609    if ($img) {
1610        $src = license_img($img);
1611        if ($src) {
1612            $out .= '<a href="' . $lic['url'] . '" rel="license"' . $target;
1613            $out .= '><img src="' . DOKU_BASE . $src . '" alt="' . $lic['name'] . '" /></a>';
1614            if (!$imgonly) $out .= ' ';
1615        }
1616    }
1617    if (!$imgonly) {
1618        $out .= $lang['license'] . ' ';
1619        $out .= '<bdi><a href="' . $lic['url'] . '" rel="license" class="urlextern"' . $target;
1620        $out .= '>' . $lic['name'] . '</a></bdi>';
1621    }
1622    if ($wrap) $out .= '</div>';
1623
1624    if ($return) return $out;
1625    echo $out;
1626    return '';
1627}
1628
1629/**
1630 * Includes the rendered HTML of a given page
1631 *
1632 * This function is useful to populate sidebars or similar features in a
1633 * template
1634 *
1635 * @param string $pageid The page name you want to include
1636 * @param bool $print Should the content be printed or returned only
1637 * @param bool $propagate Search higher namespaces, too?
1638 * @param bool $useacl Include the page only if the ACLs check out?
1639 * @return bool|null|string
1640 */
1641function tpl_include_page($pageid, $print = true, $propagate = false, $useacl = true)
1642{
1643    if ($propagate) {
1644        $pageid = page_findnearest($pageid, $useacl);
1645    } elseif ($useacl && auth_quickaclcheck($pageid) == AUTH_NONE) {
1646        return false;
1647    }
1648    if (!$pageid) return false;
1649
1650    global $TOC;
1651    $oldtoc = $TOC;
1652    $html = p_wiki_xhtml($pageid, '', false);
1653    $TOC = $oldtoc;
1654
1655    if ($print) echo $html;
1656    return $html;
1657}
1658
1659/**
1660 * Display the subscribe form
1661 *
1662 * @author Adrian Lang <lang@cosmocode.de>
1663 * @deprecated 2020-07-23
1664 */
1665function tpl_subscribe()
1666{
1667    dbg_deprecated(Subscribe::class . '::show()');
1668    (new Subscribe())->show();
1669}
1670
1671/**
1672 * Tries to send already created content right to the browser
1673 *
1674 * Wraps around ob_flush() and flush()
1675 *
1676 * @author Andreas Gohr <andi@splitbrain.org>
1677 */
1678function tpl_flush()
1679{
1680    if (ob_get_level() > 0) ob_flush();
1681    flush();
1682}
1683
1684/**
1685 * Tries to find a ressource file in the given locations.
1686 *
1687 * If a given location starts with a colon it is assumed to be a media
1688 * file, otherwise it is assumed to be relative to the current template
1689 *
1690 * @param string[] $search locations to look at
1691 * @param bool $abs if to use absolute URL
1692 * @param array    &$imginfo filled with getimagesize()
1693 * @param bool $fallback use fallback image if target isn't found or return 'false' if potential
1694 *                                false result is required
1695 * @return string
1696 *
1697 * @author Andreas  Gohr <andi@splitbrain.org>
1698 */
1699function tpl_getMediaFile($search, $abs = false, &$imginfo = null, $fallback = true)
1700{
1701    $img = '';
1702    $file = '';
1703    $ismedia = false;
1704    // loop through candidates until a match was found:
1705    foreach ($search as $img) {
1706        if (str_starts_with($img, ':')) {
1707            $file = mediaFN($img);
1708            $ismedia = true;
1709        } else {
1710            $file = tpl_incdir() . $img;
1711            $ismedia = false;
1712        }
1713
1714        if (file_exists($file)) break;
1715    }
1716
1717    // manage non existing target
1718    if (!file_exists($file)) {
1719        // give result for fallback image
1720        if ($fallback) {
1721            $file = DOKU_INC . 'lib/images/blank.gif';
1722            // stop process if false result is required (if $fallback is false)
1723        } else {
1724            return false;
1725        }
1726    }
1727
1728    // fetch image data if requested
1729    if (!is_null($imginfo)) {
1730        $imginfo = getimagesize($file);
1731    }
1732
1733    // build URL
1734    if ($ismedia) {
1735        $url = ml($img, '', true, '', $abs);
1736    } else {
1737        $url = tpl_basedir() . $img;
1738        if ($abs) $url = DOKU_URL . substr($url, strlen(DOKU_REL));
1739    }
1740
1741    return $url;
1742}
1743
1744/**
1745 * PHP include a file
1746 *
1747 * either from the conf directory if it exists, otherwise use
1748 * file in the template's root directory.
1749 *
1750 * The function honours config cascade settings and looks for the given
1751 * file next to the ´main´ config files, in the order protected, local,
1752 * default.
1753 *
1754 * Note: no escaping or sanity checking is done here. Never pass user input
1755 * to this function!
1756 *
1757 * @param string $file
1758 *
1759 * @author Andreas Gohr <andi@splitbrain.org>
1760 * @author Anika Henke <anika@selfthinker.org>
1761 */
1762function tpl_includeFile($file)
1763{
1764    global $config_cascade;
1765    foreach (['protected', 'local', 'default'] as $config_group) {
1766        if (empty($config_cascade['main'][$config_group])) continue;
1767        foreach ($config_cascade['main'][$config_group] as $conf_file) {
1768            $dir = dirname($conf_file);
1769            if (file_exists("$dir/$file")) {
1770                include("$dir/$file");
1771                return;
1772            }
1773        }
1774    }
1775
1776    // still here? try the template dir
1777    $file = tpl_incdir() . $file;
1778    if (file_exists($file)) {
1779        include($file);
1780    }
1781}
1782
1783/**
1784 * Returns <link> tag for various icon types (favicon|mobile|generic)
1785 *
1786 * @param array $types - list of icon types to display (favicon|mobile|generic)
1787 * @return string
1788 *
1789 * @author Anika Henke <anika@selfthinker.org>
1790 */
1791function tpl_favicon($types = ['favicon'])
1792{
1793
1794    $return = '';
1795
1796    foreach ($types as $type) {
1797        switch ($type) {
1798            case 'favicon':
1799                $look = [':wiki:favicon.ico', ':favicon.ico', 'images/favicon.ico'];
1800                $return .= '<link rel="shortcut icon" href="' . tpl_getMediaFile($look) . '" />' . NL;
1801                break;
1802            case 'mobile':
1803                $look = [':wiki:apple-touch-icon.png', ':apple-touch-icon.png', 'images/apple-touch-icon.png'];
1804                $return .= '<link rel="apple-touch-icon" href="' . tpl_getMediaFile($look) . '" />' . NL;
1805                break;
1806            case 'generic':
1807                // ideal world solution, which doesn't work in any browser yet
1808                $look = [':wiki:favicon.svg', ':favicon.svg', 'images/favicon.svg'];
1809                $return .= '<link rel="icon" href="' . tpl_getMediaFile($look) . '" type="image/svg+xml" />' . NL;
1810                break;
1811        }
1812    }
1813
1814    return $return;
1815}
1816
1817/**
1818 * Prints full-screen media manager
1819 *
1820 * @author Kate Arzamastseva <pshns@ukr.net>
1821 */
1822function tpl_media()
1823{
1824    global $NS, $IMG, $JUMPTO, $REV, $lang, $fullscreen, $INPUT;
1825    $fullscreen = true;
1826    require_once DOKU_INC . 'lib/exe/mediamanager.php';
1827
1828    $rev = '';
1829    $image = cleanID($INPUT->str('image'));
1830    if (isset($IMG)) $image = $IMG;
1831    if (isset($JUMPTO)) $image = $JUMPTO;
1832    if (isset($REV) && !$JUMPTO) $rev = $REV;
1833
1834    echo '<div id="mediamanager__page">' . NL;
1835    echo '<h1>' . $lang['btn_media'] . '</h1>' . NL;
1836    html_msgarea();
1837
1838    echo '<div class="panel namespaces">' . NL;
1839    echo '<h2>' . $lang['namespaces'] . '</h2>' . NL;
1840    echo '<div class="panelHeader">';
1841    echo $lang['media_namespaces'];
1842    echo '</div>' . NL;
1843
1844    echo '<div class="panelContent" id="media__tree">' . NL;
1845    media_nstree($NS);
1846    echo '</div>' . NL;
1847    echo '</div>' . NL;
1848
1849    echo '<div class="panel filelist">' . NL;
1850    tpl_mediaFileList();
1851    echo '</div>' . NL;
1852
1853    echo '<div class="panel file">' . NL;
1854    echo '<h2 class="a11y">' . $lang['media_file'] . '</h2>' . NL;
1855    tpl_mediaFileDetails($image, $rev);
1856    echo '</div>' . NL;
1857
1858    echo '</div>' . NL;
1859}
1860
1861/**
1862 * Return useful layout classes
1863 *
1864 * @return string
1865 *
1866 * @author Anika Henke <anika@selfthinker.org>
1867 */
1868function tpl_classes()
1869{
1870    global $ACT, $conf, $ID, $INFO;
1871    /** @var Input $INPUT */
1872    global $INPUT;
1873
1874    $classes = [
1875        'dokuwiki',
1876        'mode_' . $ACT,
1877        'tpl_' . $conf['template'],
1878        $INPUT->server->bool('REMOTE_USER') ? 'loggedIn' : '',
1879        (isset($INFO['exists']) && $INFO['exists']) ? '' : 'notFound',
1880        ($ID == $conf['start']) ? 'home' : ''
1881    ];
1882    return implode(' ', $classes);
1883}
1884
1885/**
1886 * Create event for tools menues
1887 *
1888 * @param string $toolsname name of menu
1889 * @param array $items
1890 * @param string $view e.g. 'main', 'detail', ...
1891 *
1892 * @author Anika Henke <anika@selfthinker.org>
1893 * @deprecated 2017-09-01 see devel:menus
1894 */
1895function tpl_toolsevent($toolsname, $items, $view = 'main')
1896{
1897    dbg_deprecated('see devel:menus');
1898    $data = ['view' => $view, 'items' => $items];
1899
1900    $hook = 'TEMPLATE_' . strtoupper($toolsname) . '_DISPLAY';
1901    $evt = new Event($hook, $data);
1902    if ($evt->advise_before()) {
1903        foreach ($evt->data['items'] as $html) echo $html;
1904    }
1905    $evt->advise_after();
1906}
1907