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