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