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