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