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