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