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