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