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