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