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