xref: /dokuwiki/inc/template.php (revision 94070874cc8d8702821161dbaa291e8b2d043ad3)
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    global $INFO;
889    if(isset($_SERVER['REMOTE_USER'])) {
890        print $lang['loggedinas'].': <bdi>'.hsc($INFO['userinfo']['name']).'</bdi> (<bdi>'.hsc($_SERVER['REMOTE_USER']).'</bdi>)';
891        return true;
892    }
893    return false;
894}
895
896/**
897 * Print some info about the current page
898 *
899 * @author Andreas Gohr <andi@splitbrain.org>
900 * @param bool $ret return content instead of printing it
901 * @return bool|string
902 */
903function tpl_pageinfo($ret = false) {
904    global $conf;
905    global $lang;
906    global $INFO;
907    global $ID;
908
909    // return if we are not allowed to view the page
910    if(!auth_quickaclcheck($ID)) {
911        return false;
912    }
913
914    // prepare date and path
915    $fn = $INFO['filepath'];
916    if(!$conf['fullpath']) {
917        if($INFO['rev']) {
918            $fn = str_replace(fullpath($conf['olddir']).'/', '', $fn);
919        } else {
920            $fn = str_replace(fullpath($conf['datadir']).'/', '', $fn);
921        }
922    }
923    $fn   = utf8_decodeFN($fn);
924    $date = dformat($INFO['lastmod']);
925
926    // print it
927    if($INFO['exists']) {
928        $out = '';
929        $out .= '<bdi>'.$fn.'</bdi>';
930        $out .= ' · ';
931        $out .= $lang['lastmod'];
932        $out .= ': ';
933        $out .= $date;
934        if($INFO['editor']) {
935            $out .= ' '.$lang['by'].' ';
936            $out .= '<bdi>'.editorinfo($INFO['editor']).'</bdi>';
937        } else {
938            $out .= ' ('.$lang['external_edit'].')';
939        }
940        if($INFO['locked']) {
941            $out .= ' · ';
942            $out .= $lang['lockedby'];
943            $out .= ': ';
944            $out .= '<bdi>'.editorinfo($INFO['locked']).'</bdi>';
945        }
946        if($ret) {
947            return $out;
948        } else {
949            echo $out;
950            return true;
951        }
952    }
953    return false;
954}
955
956/**
957 * Prints or returns the name of the given page (current one if none given).
958 *
959 * If useheading is enabled this will use the first headline else
960 * the given ID is used.
961 *
962 * @author Andreas Gohr <andi@splitbrain.org>
963 * @param string $id page id
964 * @param bool   $ret return content instead of printing
965 * @return bool|string
966 */
967function tpl_pagetitle($id = null, $ret = false) {
968    if(is_null($id)) {
969        global $ID;
970        $id = $ID;
971    }
972
973    $name = $id;
974    if(useHeading('navigation')) {
975        $title = p_get_first_heading($id);
976        if($title) $name = $title;
977    }
978
979    if($ret) {
980        return hsc($name);
981    } else {
982        print hsc($name);
983        return true;
984    }
985}
986
987/**
988 * Returns the requested EXIF/IPTC tag from the current image
989 *
990 * If $tags is an array all given tags are tried until a
991 * value is found. If no value is found $alt is returned.
992 *
993 * Which texts are known is defined in the functions _exifTagNames
994 * and _iptcTagNames() in inc/jpeg.php (You need to prepend IPTC
995 * to the names of the latter one)
996 *
997 * Only allowed in: detail.php
998 *
999 * @author Andreas Gohr <andi@splitbrain.org>
1000 * @param array  $tags tags to try
1001 * @param string $alt alternative output if no data was found
1002 * @param null   $src the image src, uses global $SRC if not given
1003 * @return string
1004 */
1005function tpl_img_getTag($tags, $alt = '', $src = null) {
1006    // Init Exif Reader
1007    global $SRC;
1008
1009    if(is_null($src)) $src = $SRC;
1010
1011    static $meta = null;
1012    if(is_null($meta)) $meta = new JpegMeta($src);
1013    if($meta === false) return $alt;
1014    $info = $meta->getField($tags);
1015    if($info == false) return $alt;
1016    return $info;
1017}
1018
1019/**
1020 * Prints the image with a link to the full sized version
1021 *
1022 * Only allowed in: detail.php
1023 *
1024 * @triggers TPL_IMG_DISPLAY
1025 * @param $maxwidth  int - maximal width of the image
1026 * @param $maxheight int - maximal height of the image
1027 * @param $link bool     - link to the orginal size?
1028 * @param $params array  - additional image attributes
1029 * @return mixed Result of TPL_IMG_DISPLAY
1030 */
1031function tpl_img($maxwidth = 0, $maxheight = 0, $link = true, $params = null) {
1032    global $IMG;
1033    global $INPUT;
1034    $w = tpl_img_getTag('File.Width');
1035    $h = tpl_img_getTag('File.Height');
1036
1037    //resize to given max values
1038    $ratio = 1;
1039    if($w >= $h) {
1040        if($maxwidth && $w >= $maxwidth) {
1041            $ratio = $maxwidth / $w;
1042        } elseif($maxheight && $h > $maxheight) {
1043            $ratio = $maxheight / $h;
1044        }
1045    } else {
1046        if($maxheight && $h >= $maxheight) {
1047            $ratio = $maxheight / $h;
1048        } elseif($maxwidth && $w > $maxwidth) {
1049            $ratio = $maxwidth / $w;
1050        }
1051    }
1052    if($ratio) {
1053        $w = floor($ratio * $w);
1054        $h = floor($ratio * $h);
1055    }
1056
1057    //prepare URLs
1058    $url = ml($IMG, array('cache'=> $INPUT->str('cache')), true, '&');
1059    $src = ml($IMG, array('cache'=> $INPUT->str('cache'), 'w'=> $w, 'h'=> $h), true, '&');
1060
1061    //prepare attributes
1062    $alt = tpl_img_getTag('Simple.Title');
1063    if(is_null($params)) {
1064        $p = array();
1065    } else {
1066        $p = $params;
1067    }
1068    if($w) $p['width'] = $w;
1069    if($h) $p['height'] = $h;
1070    $p['class'] = 'img_detail';
1071    if($alt) {
1072        $p['alt']   = $alt;
1073        $p['title'] = $alt;
1074    } else {
1075        $p['alt'] = '';
1076    }
1077    $p['src'] = $src;
1078
1079    $data = array('url'=> ($link ? $url : null), 'params'=> $p);
1080    return trigger_event('TPL_IMG_DISPLAY', $data, '_tpl_img_action', true);
1081}
1082
1083/**
1084 * Default action for TPL_IMG_DISPLAY
1085 *
1086 * @param array $data
1087 * @return bool
1088 */
1089function _tpl_img_action($data) {
1090    global $lang;
1091    $p = buildAttributes($data['params']);
1092
1093    if($data['url']) print '<a href="'.hsc($data['url']).'" title="'.$lang['mediaview'].'">';
1094    print '<img '.$p.'/>';
1095    if($data['url']) print '</a>';
1096    return true;
1097}
1098
1099/**
1100 * This function inserts a small gif which in reality is the indexer function.
1101 *
1102 * Should be called somewhere at the very end of the main.php
1103 * template
1104 *
1105 * @return bool
1106 */
1107function tpl_indexerWebBug() {
1108    global $ID;
1109
1110    $p           = array();
1111    $p['src']    = DOKU_BASE.'lib/exe/indexer.php?id='.rawurlencode($ID).
1112        '&'.time();
1113    $p['width']  = 2; //no more 1x1 px image because we live in times of ad blockers...
1114    $p['height'] = 1;
1115    $p['alt']    = '';
1116    $att         = buildAttributes($p);
1117    print "<img $att />";
1118    return true;
1119}
1120
1121/**
1122 * tpl_getConf($id)
1123 *
1124 * use this function to access template configuration variables
1125 *
1126 * @param string $id
1127 * @return string
1128 */
1129function tpl_getConf($id) {
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    return $conf['tpl'][$tpl][$id];
1147}
1148
1149/**
1150 * tpl_loadConfig()
1151 *
1152 * reads all template configuration variables
1153 * this function is automatically called by tpl_getConf()
1154 *
1155 * @return array
1156 */
1157function tpl_loadConfig() {
1158
1159    $file = tpl_incdir().'/conf/default.php';
1160    $conf = array();
1161
1162    if(!@file_exists($file)) return false;
1163
1164    // load default config file
1165    include($file);
1166
1167    return $conf;
1168}
1169
1170// language methods
1171/**
1172 * tpl_getLang($id)
1173 *
1174 * use this function to access template language variables
1175 */
1176function tpl_getLang($id) {
1177    static $lang = array();
1178
1179    if(count($lang) === 0) {
1180        $path = tpl_incdir().'lang/';
1181
1182        $lang = array();
1183
1184        global $conf; // definitely don't invoke "global $lang"
1185        // don't include once
1186        @include($path.'en/lang.php');
1187        if($conf['lang'] != 'en') @include($path.$conf['lang'].'/lang.php');
1188    }
1189
1190    return $lang[$id];
1191}
1192
1193/**
1194 * Retrieve a language dependent file and pass to xhtml renderer for display
1195 * template equivalent of p_locale_xhtml()
1196 *
1197 * @param   string $id id of language dependent wiki page
1198 * @return  string     parsed contents of the wiki page in xhtml format
1199 */
1200function tpl_locale_xhtml($id) {
1201    return p_cached_output(tpl_localeFN($id));
1202}
1203
1204/**
1205 * Prepends appropriate path for a language dependent filename
1206 */
1207function tpl_localeFN($id) {
1208    $path = tpl_incdir().'lang/';
1209    global $conf;
1210    $file = DOKU_CONF.'/template_lang/'.$conf['template'].'/'.$conf['lang'].'/'.$id.'.txt';
1211    if (!@file_exists($file)){
1212        $file = $path.$conf['lang'].'/'.$id.'.txt';
1213        if(!@file_exists($file)){
1214            //fall back to english
1215            $file = $path.'en/'.$id.'.txt';
1216        }
1217    }
1218    return $file;
1219}
1220
1221/**
1222 * prints the "main content" in the mediamanger popup
1223 *
1224 * Depending on the user's actions this may be a list of
1225 * files in a namespace, the meta editing dialog or
1226 * a message of referencing pages
1227 *
1228 * Only allowed in mediamanager.php
1229 *
1230 * @triggers MEDIAMANAGER_CONTENT_OUTPUT
1231 * @param bool $fromajax - set true when calling this function via ajax
1232 * @author Andreas Gohr <andi@splitbrain.org>
1233 */
1234function tpl_mediaContent($fromajax = false, $sort='natural') {
1235    global $IMG;
1236    global $AUTH;
1237    global $INUSE;
1238    global $NS;
1239    global $JUMPTO;
1240    global $INPUT;
1241
1242    $do = $INPUT->extract('do')->str('do');
1243    if(in_array($do, array('save', 'cancel'))) $do = '';
1244
1245    if(!$do) {
1246        if($INPUT->bool('edit')) {
1247            $do = 'metaform';
1248        } elseif(is_array($INUSE)) {
1249            $do = 'filesinuse';
1250        } else {
1251            $do = 'filelist';
1252        }
1253    }
1254
1255    // output the content pane, wrapped in an event.
1256    if(!$fromajax) ptln('<div id="media__content">');
1257    $data = array('do' => $do);
1258    $evt  = new Doku_Event('MEDIAMANAGER_CONTENT_OUTPUT', $data);
1259    if($evt->advise_before()) {
1260        $do = $data['do'];
1261        if($do == 'filesinuse') {
1262            media_filesinuse($INUSE, $IMG);
1263        } elseif($do == 'filelist') {
1264            media_filelist($NS, $AUTH, $JUMPTO,false,$sort);
1265        } elseif($do == 'searchlist') {
1266            media_searchlist($INPUT->str('q'), $NS, $AUTH);
1267        } else {
1268            msg('Unknown action '.hsc($do), -1);
1269        }
1270    }
1271    $evt->advise_after();
1272    unset($evt);
1273    if(!$fromajax) ptln('</div>');
1274
1275}
1276
1277/**
1278 * Prints the central column in full-screen media manager
1279 * Depending on the opened tab this may be a list of
1280 * files in a namespace, upload form or search form
1281 *
1282 * @author Kate Arzamastseva <pshns@ukr.net>
1283 */
1284function tpl_mediaFileList() {
1285    global $AUTH;
1286    global $NS;
1287    global $JUMPTO;
1288    global $lang;
1289    global $INPUT;
1290
1291    $opened_tab = $INPUT->str('tab_files');
1292    if(!$opened_tab || !in_array($opened_tab, array('files', 'upload', 'search'))) $opened_tab = 'files';
1293    if($INPUT->str('mediado') == 'update') $opened_tab = 'upload';
1294
1295    echo '<h2 class="a11y">'.$lang['mediaselect'].'</h2>'.NL;
1296
1297    media_tabs_files($opened_tab);
1298
1299    echo '<div class="panelHeader">'.NL;
1300    echo '<h3>';
1301    $tabTitle = ($NS) ? $NS : '['.$lang['mediaroot'].']';
1302    printf($lang['media_'.$opened_tab], '<strong>'.hsc($tabTitle).'</strong>');
1303    echo '</h3>'.NL;
1304    if($opened_tab === 'search' || $opened_tab === 'files') {
1305        media_tab_files_options();
1306    }
1307    echo '</div>'.NL;
1308
1309    echo '<div class="panelContent">'.NL;
1310    if($opened_tab == 'files') {
1311        media_tab_files($NS, $AUTH, $JUMPTO);
1312    } elseif($opened_tab == 'upload') {
1313        media_tab_upload($NS, $AUTH, $JUMPTO);
1314    } elseif($opened_tab == 'search') {
1315        media_tab_search($NS, $AUTH);
1316    }
1317    echo '</div>'.NL;
1318}
1319
1320/**
1321 * Prints the third column in full-screen media manager
1322 * Depending on the opened tab this may be details of the
1323 * selected file, the meta editing dialog or
1324 * list of file revisions
1325 *
1326 * @author Kate Arzamastseva <pshns@ukr.net>
1327 */
1328function tpl_mediaFileDetails($image, $rev) {
1329    global $AUTH, $NS, $conf, $DEL, $lang, $INPUT;
1330
1331    $removed = (!file_exists(mediaFN($image)) && file_exists(mediaMetaFN($image, '.changes')) && $conf['mediarevisions']);
1332    if(!$image || (!file_exists(mediaFN($image)) && !$removed) || $DEL) return;
1333    if($rev && !file_exists(mediaFN($image, $rev))) $rev = false;
1334    if(isset($NS) && getNS($image) != $NS) return;
1335    $do = $INPUT->str('mediado');
1336
1337    $opened_tab = $INPUT->str('tab_details');
1338
1339    $tab_array = array('view');
1340    list(, $mime) = mimetype($image);
1341    if($mime == 'image/jpeg') {
1342        $tab_array[] = 'edit';
1343    }
1344    if($conf['mediarevisions']) {
1345        $tab_array[] = 'history';
1346    }
1347
1348    if(!$opened_tab || !in_array($opened_tab, $tab_array)) $opened_tab = 'view';
1349    if($INPUT->bool('edit')) $opened_tab = 'edit';
1350    if($do == 'restore') $opened_tab = 'view';
1351
1352    media_tabs_details($image, $opened_tab);
1353
1354    echo '<div class="panelHeader"><h3>';
1355    list($ext) = mimetype($image, false);
1356    $class    = preg_replace('/[^_\-a-z0-9]+/i', '_', $ext);
1357    $class    = 'select mediafile mf_'.$class;
1358    $tabTitle = '<strong><a href="'.ml($image).'" class="'.$class.'" title="'.$lang['mediaview'].'">'.$image.'</a>'.'</strong>';
1359    if($opened_tab === 'view' && $rev) {
1360        printf($lang['media_viewold'], $tabTitle, dformat($rev));
1361    } else {
1362        printf($lang['media_'.$opened_tab], $tabTitle);
1363    }
1364
1365    echo '</h3></div>'.NL;
1366
1367    echo '<div class="panelContent">'.NL;
1368
1369    if($opened_tab == 'view') {
1370        media_tab_view($image, $NS, $AUTH, $rev);
1371
1372    } elseif($opened_tab == 'edit' && !$removed) {
1373        media_tab_edit($image, $NS, $AUTH);
1374
1375    } elseif($opened_tab == 'history' && $conf['mediarevisions']) {
1376        media_tab_history($image, $NS, $AUTH);
1377    }
1378
1379    echo '</div>'.NL;
1380}
1381
1382/**
1383 * prints the namespace tree in the mediamanger popup
1384 *
1385 * Only allowed in mediamanager.php
1386 *
1387 * @author Andreas Gohr <andi@splitbrain.org>
1388 */
1389function tpl_mediaTree() {
1390    global $NS;
1391    ptln('<div id="media__tree">');
1392    media_nstree($NS);
1393    ptln('</div>');
1394}
1395
1396/**
1397 * Print a dropdown menu with all DokuWiki actions
1398 *
1399 * Note: this will not use any pretty URLs
1400 *
1401 * @author Andreas Gohr <andi@splitbrain.org>
1402 */
1403function tpl_actiondropdown($empty = '', $button = '&gt;') {
1404    global $ID;
1405    global $REV;
1406    global $lang;
1407
1408    echo '<form action="'.script().'" method="get" accept-charset="utf-8">';
1409    echo '<div class="no">';
1410    echo '<input type="hidden" name="id" value="'.$ID.'" />';
1411    if($REV) echo '<input type="hidden" name="rev" value="'.$REV.'" />';
1412    if (!empty($_SERVER['REMOTE_USER'])) {
1413        echo '<input type="hidden" name="sectok" value="'.getSecurityToken().'" />';
1414    }
1415
1416    echo '<select name="do" class="edit quickselect" title="'.$lang['tools'].'">';
1417    echo '<option value="">'.$empty.'</option>';
1418
1419    echo '<optgroup label="'.$lang['page_tools'].'">';
1420    $act = tpl_get_action('edit');
1421    if($act) echo '<option value="'.$act['params']['do'].'">'.$lang['btn_'.$act['type']].'</option>';
1422
1423    $act = tpl_get_action('revert');
1424    if($act) echo '<option value="'.$act['params']['do'].'">'.$lang['btn_'.$act['type']].'</option>';
1425
1426    $act = tpl_get_action('revisions');
1427    if($act) echo '<option value="'.$act['params']['do'].'">'.$lang['btn_'.$act['type']].'</option>';
1428
1429    $act = tpl_get_action('backlink');
1430    if($act) echo '<option value="'.$act['params']['do'].'">'.$lang['btn_'.$act['type']].'</option>';
1431
1432    $act = tpl_get_action('subscribe');
1433    if($act) echo '<option value="'.$act['params']['do'].'">'.$lang['btn_'.$act['type']].'</option>';
1434    echo '</optgroup>';
1435
1436    echo '<optgroup label="'.$lang['site_tools'].'">';
1437    $act = tpl_get_action('recent');
1438    if($act) echo '<option value="'.$act['params']['do'].'">'.$lang['btn_'.$act['type']].'</option>';
1439
1440    $act = tpl_get_action('media');
1441    if($act) echo '<option value="'.$act['params']['do'].'">'.$lang['btn_'.$act['type']].'</option>';
1442
1443    $act = tpl_get_action('index');
1444    if($act) echo '<option value="'.$act['params']['do'].'">'.$lang['btn_'.$act['type']].'</option>';
1445    echo '</optgroup>';
1446
1447    echo '<optgroup label="'.$lang['user_tools'].'">';
1448    $act = tpl_get_action('login');
1449    if($act) echo '<option value="'.$act['params']['do'].'">'.$lang['btn_'.$act['type']].'</option>';
1450
1451    $act = tpl_get_action('register');
1452    if($act) echo '<option value="'.$act['params']['do'].'">'.$lang['btn_'.$act['type']].'</option>';
1453
1454    $act = tpl_get_action('profile');
1455    if($act) echo '<option value="'.$act['params']['do'].'">'.$lang['btn_'.$act['type']].'</option>';
1456
1457    $act = tpl_get_action('admin');
1458    if($act) echo '<option value="'.$act['params']['do'].'">'.$lang['btn_'.$act['type']].'</option>';
1459    echo '</optgroup>';
1460
1461    echo '</select>';
1462    echo '<input type="submit" value="'.$button.'" />';
1463    echo '</div>';
1464    echo '</form>';
1465}
1466
1467/**
1468 * Print a informational line about the used license
1469 *
1470 * @author Andreas Gohr <andi@splitbrain.org>
1471 * @param  string $img     print image? (|button|badge)
1472 * @param  bool   $imgonly skip the textual description?
1473 * @param  bool   $return  when true don't print, but return HTML
1474 * @param  bool   $wrap    wrap in div with class="license"?
1475 * @return string
1476 */
1477function tpl_license($img = 'badge', $imgonly = false, $return = false, $wrap = true) {
1478    global $license;
1479    global $conf;
1480    global $lang;
1481    if(!$conf['license']) return '';
1482    if(!is_array($license[$conf['license']])) return '';
1483    $lic    = $license[$conf['license']];
1484    $target = ($conf['target']['extern']) ? ' target="'.$conf['target']['extern'].'"' : '';
1485
1486    $out = '';
1487    if($wrap) $out .= '<div class="license">';
1488    if($img) {
1489        $src = license_img($img);
1490        if($src) {
1491            $out .= '<a href="'.$lic['url'].'" rel="license"'.$target;
1492            $out .= '><img src="'.DOKU_BASE.$src.'" alt="'.$lic['name'].'" /></a>';
1493            if(!$imgonly) $out .= ' ';
1494        }
1495    }
1496    if(!$imgonly) {
1497        $out .= $lang['license'].' ';
1498        $out .= '<bdi><a href="'.$lic['url'].'" rel="license" class="urlextern"'.$target;
1499        $out .= '>'.$lic['name'].'</a></bdi>';
1500    }
1501    if($wrap) $out .= '</div>';
1502
1503    if($return) return $out;
1504    echo $out;
1505    return '';
1506}
1507
1508/**
1509 * Includes the rendered HTML of a given page
1510 *
1511 * This function is useful to populate sidebars or similar features in a
1512 * template
1513 */
1514function tpl_include_page($pageid, $print = true, $propagate = false) {
1515    if (!$pageid) return false;
1516    if ($propagate) $pageid = page_findnearest($pageid);
1517
1518    global $TOC;
1519    $oldtoc = $TOC;
1520    $html   = p_wiki_xhtml($pageid, '', false);
1521    $TOC    = $oldtoc;
1522
1523    if(!$print) return $html;
1524    echo $html;
1525    return $html;
1526}
1527
1528/**
1529 * Display the subscribe form
1530 *
1531 * @author Adrian Lang <lang@cosmocode.de>
1532 */
1533function tpl_subscribe() {
1534    global $INFO;
1535    global $ID;
1536    global $lang;
1537    global $conf;
1538    $stime_days = $conf['subscribe_time'] / 60 / 60 / 24;
1539
1540    echo p_locale_xhtml('subscr_form');
1541    echo '<h2>'.$lang['subscr_m_current_header'].'</h2>';
1542    echo '<div class="level2">';
1543    if($INFO['subscribed'] === false) {
1544        echo '<p>'.$lang['subscr_m_not_subscribed'].'</p>';
1545    } else {
1546        echo '<ul>';
1547        foreach($INFO['subscribed'] as $sub) {
1548            echo '<li><div class="li">';
1549            if($sub['target'] !== $ID) {
1550                echo '<code class="ns">'.hsc(prettyprint_id($sub['target'])).'</code>';
1551            } else {
1552                echo '<code class="page">'.hsc(prettyprint_id($sub['target'])).'</code>';
1553            }
1554            $sstl = sprintf($lang['subscr_style_'.$sub['style']], $stime_days);
1555            if(!$sstl) $sstl = hsc($sub['style']);
1556            echo ' ('.$sstl.') ';
1557
1558            echo '<a href="'.wl(
1559                $ID,
1560                array(
1561                     'do'        => 'subscribe',
1562                     'sub_target'=> $sub['target'],
1563                     'sub_style' => $sub['style'],
1564                     'sub_action'=> 'unsubscribe',
1565                     'sectok'    => getSecurityToken()
1566                )
1567            ).
1568                '" class="unsubscribe">'.$lang['subscr_m_unsubscribe'].
1569                '</a></div></li>';
1570        }
1571        echo '</ul>';
1572    }
1573    echo '</div>';
1574
1575    // Add new subscription form
1576    echo '<h2>'.$lang['subscr_m_new_header'].'</h2>';
1577    echo '<div class="level2">';
1578    $ns      = getNS($ID).':';
1579    $targets = array(
1580        $ID => '<code class="page">'.prettyprint_id($ID).'</code>',
1581        $ns => '<code class="ns">'.prettyprint_id($ns).'</code>',
1582    );
1583    $styles  = array(
1584        'every'  => $lang['subscr_style_every'],
1585        'digest' => sprintf($lang['subscr_style_digest'], $stime_days),
1586        'list'   => sprintf($lang['subscr_style_list'], $stime_days),
1587    );
1588
1589    $form = new Doku_Form(array('id' => 'subscribe__form'));
1590    $form->startFieldset($lang['subscr_m_subscribe']);
1591    $form->addRadioSet('sub_target', $targets);
1592    $form->startFieldset($lang['subscr_m_receive']);
1593    $form->addRadioSet('sub_style', $styles);
1594    $form->addHidden('sub_action', 'subscribe');
1595    $form->addHidden('do', 'subscribe');
1596    $form->addHidden('id', $ID);
1597    $form->endFieldset();
1598    $form->addElement(form_makeButton('submit', 'subscribe', $lang['subscr_m_subscribe']));
1599    html_form('SUBSCRIBE', $form);
1600    echo '</div>';
1601}
1602
1603/**
1604 * Tries to send already created content right to the browser
1605 *
1606 * Wraps around ob_flush() and flush()
1607 *
1608 * @author Andreas Gohr <andi@splitbrain.org>
1609 */
1610function tpl_flush() {
1611    ob_flush();
1612    flush();
1613}
1614
1615/**
1616 * Tries to find a ressource file in the given locations.
1617 *
1618 * If a given location starts with a colon it is assumed to be a media
1619 * file, otherwise it is assumed to be relative to the current template
1620 *
1621 * @param  array $search       locations to look at
1622 * @param  bool  $abs           if to use absolute URL
1623 * @param  array &$imginfo   filled with getimagesize()
1624 * @return string
1625 * @author Andreas  Gohr <andi@splitbrain.org>
1626 */
1627function tpl_getMediaFile($search, $abs = false, &$imginfo = null) {
1628    $img     = '';
1629    $file    = '';
1630    $ismedia = false;
1631    // loop through candidates until a match was found:
1632    foreach($search as $img) {
1633        if(substr($img, 0, 1) == ':') {
1634            $file    = mediaFN($img);
1635            $ismedia = true;
1636        } else {
1637            $file    = tpl_incdir().$img;
1638            $ismedia = false;
1639        }
1640
1641        if(file_exists($file)) break;
1642    }
1643
1644    // fetch image data if requested
1645    if(!is_null($imginfo)) {
1646        $imginfo = getimagesize($file);
1647    }
1648
1649    // build URL
1650    if($ismedia) {
1651        $url = ml($img, '', true, '', $abs);
1652    } else {
1653        $url = tpl_basedir().$img;
1654        if($abs) $url = DOKU_URL.substr($url, strlen(DOKU_REL));
1655    }
1656
1657    return $url;
1658}
1659
1660/**
1661 * PHP include a file
1662 *
1663 * either from the conf directory if it exists, otherwise use
1664 * file in the template's root directory.
1665 *
1666 * The function honours config cascade settings and looks for the given
1667 * file next to the ´main´ config files, in the order protected, local,
1668 * default.
1669 *
1670 * Note: no escaping or sanity checking is done here. Never pass user input
1671 * to this function!
1672 *
1673 * @author Anika Henke <anika@selfthinker.org>
1674 * @author Andreas Gohr <andi@splitbrain.org>
1675 */
1676function tpl_includeFile($file) {
1677    global $config_cascade;
1678    foreach(array('protected', 'local', 'default') as $config_group) {
1679        if(empty($config_cascade['main'][$config_group])) continue;
1680        foreach($config_cascade['main'][$config_group] as $conf_file) {
1681            $dir = dirname($conf_file);
1682            if(file_exists("$dir/$file")) {
1683                include("$dir/$file");
1684                return;
1685            }
1686        }
1687    }
1688
1689    // still here? try the template dir
1690    $file = tpl_incdir().$file;
1691    if(file_exists($file)) {
1692        include($file);
1693    }
1694}
1695
1696/**
1697 * Returns <link> tag for various icon types (favicon|mobile|generic)
1698 *
1699 * @author Anika Henke <anika@selfthinker.org>
1700 * @param  array $types - list of icon types to display (favicon|mobile|generic)
1701 * @return string
1702 */
1703function tpl_favicon($types = array('favicon')) {
1704
1705    $return = '';
1706
1707    foreach($types as $type) {
1708        switch($type) {
1709            case 'favicon':
1710                $look = array(':wiki:favicon.ico', ':favicon.ico', 'images/favicon.ico');
1711                $return .= '<link rel="shortcut icon" href="'.tpl_getMediaFile($look).'" />'.NL;
1712                break;
1713            case 'mobile':
1714                $look = array(':wiki:apple-touch-icon.png', ':apple-touch-icon.png', 'images/apple-touch-icon.png');
1715                $return .= '<link rel="apple-touch-icon" href="'.tpl_getMediaFile($look).'" />'.NL;
1716                break;
1717            case 'generic':
1718                // ideal world solution, which doesn't work in any browser yet
1719                $look = array(':wiki:favicon.svg', ':favicon.svg', 'images/favicon.svg');
1720                $return .= '<link rel="icon" href="'.tpl_getMediaFile($look).'" type="image/svg+xml" />'.NL;
1721                break;
1722        }
1723    }
1724
1725    return $return;
1726}
1727
1728/**
1729 * Prints full-screen media manager
1730 *
1731 * @author Kate Arzamastseva <pshns@ukr.net>
1732 */
1733function tpl_media() {
1734    global $NS, $IMG, $JUMPTO, $REV, $lang, $fullscreen, $INPUT;
1735    $fullscreen = true;
1736    require_once DOKU_INC.'lib/exe/mediamanager.php';
1737
1738    $rev   = '';
1739    $image = cleanID($INPUT->str('image'));
1740    if(isset($IMG)) $image = $IMG;
1741    if(isset($JUMPTO)) $image = $JUMPTO;
1742    if(isset($REV) && !$JUMPTO) $rev = $REV;
1743
1744    echo '<div id="mediamanager__page">'.NL;
1745    echo '<h1>'.$lang['btn_media'].'</h1>'.NL;
1746    html_msgarea();
1747
1748    echo '<div class="panel namespaces">'.NL;
1749    echo '<h2>'.$lang['namespaces'].'</h2>'.NL;
1750    echo '<div class="panelHeader">';
1751    echo $lang['media_namespaces'];
1752    echo '</div>'.NL;
1753
1754    echo '<div class="panelContent" id="media__tree">'.NL;
1755    media_nstree($NS);
1756    echo '</div>'.NL;
1757    echo '</div>'.NL;
1758
1759    echo '<div class="panel filelist">'.NL;
1760    tpl_mediaFileList();
1761    echo '</div>'.NL;
1762
1763    echo '<div class="panel file">'.NL;
1764    echo '<h2 class="a11y">'.$lang['media_file'].'</h2>'.NL;
1765    tpl_mediaFileDetails($image, $rev);
1766    echo '</div>'.NL;
1767
1768    echo '</div>'.NL;
1769}
1770
1771/**
1772 * Return useful layout classes
1773 *
1774 * @author Anika Henke <anika@selfthinker.org>
1775 */
1776function tpl_classes() {
1777    global $ACT, $conf, $ID, $INFO;
1778    $classes = array(
1779        'dokuwiki',
1780        'mode_'.$ACT,
1781        'tpl_'.$conf['template'],
1782        !empty($_SERVER['REMOTE_USER']) ? 'loggedIn' : '',
1783        $INFO['exists'] ? '' : 'notFound',
1784        ($ID == $conf['start']) ? 'home' : '',
1785    );
1786    return join(' ', $classes);
1787}
1788
1789//Setup VIM: ex: et ts=4 :
1790
1791