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