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