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