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