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