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