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