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