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