xref: /dokuwiki/inc/template.php (revision 59bc3b48fdffb76ee65a4b630be3ffa1f6c20c80)
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    }
763    return compact('accesskey', 'type', 'id', 'method', 'params', 'nofollow', 'replacement');
764}
765
766/**
767 * Wrapper around tpl_button() and tpl_actionlink()
768 *
769 * @author Anika Henke <anika@selfthinker.org>
770 * @param
771 * @param bool          $link link or form button?
772 * @param string|bool   $wrapper HTML element wrapper
773 * @param bool          $return return or print
774 * @param string        $pre prefix for links
775 * @param string        $suf suffix for links
776 * @param string        $inner inner HTML for links
777 * @return bool|string
778 */
779function tpl_action($type, $link = false, $wrapper = false, $return = false, $pre = '', $suf = '', $inner = '') {
780    $out = '';
781    if($link) {
782        $out .= tpl_actionlink($type, $pre, $suf, $inner, true);
783    } else {
784        $out .= tpl_button($type, true);
785    }
786    if($out && $wrapper) $out = "<$wrapper>$out</$wrapper>";
787
788    if($return) return $out;
789    print $out;
790    return $out ? true : false;
791}
792
793/**
794 * Print the search form
795 *
796 * If the first parameter is given a div with the ID 'qsearch_out' will
797 * be added which instructs the ajax pagequicksearch to kick in and place
798 * its output into this div. The second parameter controls the propritary
799 * attribute autocomplete. If set to false this attribute will be set with an
800 * value of "off" to instruct the browser to disable it's own built in
801 * autocompletion feature (MSIE and Firefox)
802 *
803 * @author Andreas Gohr <andi@splitbrain.org>
804 * @param bool $ajax
805 * @param bool $autocomplete
806 * @return bool
807 */
808function tpl_searchform($ajax = true, $autocomplete = true) {
809    global $lang;
810    global $ACT;
811    global $QUERY;
812
813    // don't print the search form if search action has been disabled
814    if(!actionOK('search')) return false;
815
816    print '<form action="'.wl().'" accept-charset="utf-8" class="search" id="dw__search" method="get" role="search"><div class="no">';
817    print '<input type="hidden" name="do" value="search" />';
818    print '<input type="text" ';
819    if($ACT == 'search') print 'value="'.htmlspecialchars($QUERY).'" ';
820    if(!$autocomplete) print 'autocomplete="off" ';
821    print 'id="qsearch__in" accesskey="f" name="id" class="edit" title="[F]" />';
822    print '<input type="submit" value="'.$lang['btn_search'].'" class="button" title="'.$lang['btn_search'].'" />';
823    if($ajax) print '<div id="qsearch__out" class="ajax_qsearch JSpopup"></div>';
824    print '</div></form>';
825    return true;
826}
827
828/**
829 * Print the breadcrumbs trace
830 *
831 * @author Andreas Gohr <andi@splitbrain.org>
832 * @param string $sep Separator between entries
833 * @return bool
834 */
835function tpl_breadcrumbs($sep = '•') {
836    global $lang;
837    global $conf;
838
839    //check if enabled
840    if(!$conf['breadcrumbs']) return false;
841
842    $crumbs = breadcrumbs(); //setup crumb trace
843
844    $crumbs_sep = ' <span class="bcsep">'.$sep.'</span> ';
845
846    //render crumbs, highlight the last one
847    print '<span class="bchead">'.$lang['breadcrumb'].'</span>';
848    $last = count($crumbs);
849    $i    = 0;
850    foreach($crumbs as $id => $name) {
851        $i++;
852        echo $crumbs_sep;
853        if($i == $last) print '<span class="curid">';
854        print '<bdi>';
855        tpl_link(wl($id), hsc($name), 'class="breadcrumbs" title="'.$id.'"');
856        print '</bdi>';
857        if($i == $last) print '</span>';
858    }
859    return true;
860}
861
862/**
863 * Hierarchical breadcrumbs
864 *
865 * This code was suggested as replacement for the usual breadcrumbs.
866 * It only makes sense with a deep site structure.
867 *
868 * @author Andreas Gohr <andi@splitbrain.org>
869 * @author Nigel McNie <oracle.shinoda@gmail.com>
870 * @author Sean Coates <sean@caedmon.net>
871 * @author <fredrik@averpil.com>
872 * @todo   May behave strangely in RTL languages
873 * @param string $sep Separator between entries
874 * @return bool
875 */
876function tpl_youarehere($sep = ' » ') {
877    global $conf;
878    global $ID;
879    global $lang;
880
881    // check if enabled
882    if(!$conf['youarehere']) return false;
883
884    $parts = explode(':', $ID);
885    $count = count($parts);
886
887    echo '<span class="bchead">'.$lang['youarehere'].' </span>';
888
889    // always print the startpage
890    echo '<span class="home">';
891    tpl_pagelink(':'.$conf['start']);
892    echo '</span>';
893
894    // print intermediate namespace links
895    $part = '';
896    for($i = 0; $i < $count - 1; $i++) {
897        $part .= $parts[$i].':';
898        $page = $part;
899        if($page == $conf['start']) continue; // Skip startpage
900
901        // output
902        echo $sep;
903        tpl_pagelink($page);
904    }
905
906    // print current page, skipping start page, skipping for namespace index
907    resolve_pageid('', $page, $exists);
908    if(isset($page) && $page == $part.$parts[$i]) return true;
909    $page = $part.$parts[$i];
910    if($page == $conf['start']) return true;
911    echo $sep;
912    tpl_pagelink($page);
913    return true;
914}
915
916/**
917 * Print info if the user is logged in
918 * and show full name in that case
919 *
920 * Could be enhanced with a profile link in future?
921 *
922 * @author Andreas Gohr <andi@splitbrain.org>
923 * @return bool
924 */
925function tpl_userinfo() {
926    global $lang;
927    /** @var Input $INPUT */
928    global $INPUT;
929
930    if($INPUT->server->str('REMOTE_USER')) {
931        print $lang['loggedinas'].' '.userlink();
932        return true;
933    }
934    return false;
935}
936
937/**
938 * Print some info about the current page
939 *
940 * @author Andreas Gohr <andi@splitbrain.org>
941 * @param bool $ret return content instead of printing it
942 * @return bool|string
943 */
944function tpl_pageinfo($ret = false) {
945    global $conf;
946    global $lang;
947    global $INFO;
948    global $ID;
949
950    // return if we are not allowed to view the page
951    if(!auth_quickaclcheck($ID)) {
952        return false;
953    }
954
955    // prepare date and path
956    $fn = $INFO['filepath'];
957    if(!$conf['fullpath']) {
958        if($INFO['rev']) {
959            $fn = str_replace(fullpath($conf['olddir']).'/', '', $fn);
960        } else {
961            $fn = str_replace(fullpath($conf['datadir']).'/', '', $fn);
962        }
963    }
964    $fn   = utf8_decodeFN($fn);
965    $date = dformat($INFO['lastmod']);
966
967    // print it
968    if($INFO['exists']) {
969        $out = '';
970        $out .= '<bdi>'.$fn.'</bdi>';
971        $out .= ' · ';
972        $out .= $lang['lastmod'];
973        $out .= ' ';
974        $out .= $date;
975        if($INFO['editor']) {
976            $out .= ' '.$lang['by'].' ';
977            $out .= '<bdi>'.editorinfo($INFO['editor']).'</bdi>';
978        } else {
979            $out .= ' ('.$lang['external_edit'].')';
980        }
981        if($INFO['locked']) {
982            $out .= ' · ';
983            $out .= $lang['lockedby'];
984            $out .= ' ';
985            $out .= '<bdi>'.editorinfo($INFO['locked']).'</bdi>';
986        }
987        if($ret) {
988            return $out;
989        } else {
990            echo $out;
991            return true;
992        }
993    }
994    return false;
995}
996
997/**
998 * Prints or returns the name of the given page (current one if none given).
999 *
1000 * If useheading is enabled this will use the first headline else
1001 * the given ID is used.
1002 *
1003 * @author Andreas Gohr <andi@splitbrain.org>
1004 * @param string $id page id
1005 * @param bool   $ret return content instead of printing
1006 * @return bool|string
1007 */
1008function tpl_pagetitle($id = null, $ret = false) {
1009    if(is_null($id)) {
1010        global $ID;
1011        $id = $ID;
1012    }
1013
1014    $name = $id;
1015    if(useHeading('navigation')) {
1016        $title = p_get_first_heading($id);
1017        if($title) $name = $title;
1018    }
1019
1020    if($ret) {
1021        return hsc($name);
1022    } else {
1023        print hsc($name);
1024        return true;
1025    }
1026}
1027
1028/**
1029 * Returns the requested EXIF/IPTC tag from the current image
1030 *
1031 * If $tags is an array all given tags are tried until a
1032 * value is found. If no value is found $alt is returned.
1033 *
1034 * Which texts are known is defined in the functions _exifTagNames
1035 * and _iptcTagNames() in inc/jpeg.php (You need to prepend IPTC
1036 * to the names of the latter one)
1037 *
1038 * Only allowed in: detail.php
1039 *
1040 * @author Andreas Gohr <andi@splitbrain.org>
1041 * @param array  $tags tags to try
1042 * @param string $alt alternative output if no data was found
1043 * @param null|string   $src the image src, uses global $SRC if not given
1044 * @return string
1045 */
1046function tpl_img_getTag($tags, $alt = '', $src = null) {
1047    // Init Exif Reader
1048    global $SRC;
1049
1050    if(is_null($src)) $src = $SRC;
1051
1052    static $meta = null;
1053    if(is_null($meta)) $meta = new JpegMeta($src);
1054    if($meta === false) return $alt;
1055    $info = cleanText($meta->getField($tags));
1056    if($info == false) return $alt;
1057    return $info;
1058}
1059
1060/**
1061 * Returns a description list of the metatags of the current image
1062 *
1063 * @return string html of description list
1064 */
1065function tpl_img_meta() {
1066    global $lang;
1067
1068    $tags = tpl_get_img_meta();
1069
1070    echo '<dl>';
1071    foreach($tags as $tag) {
1072        $label = $lang[$tag['langkey']];
1073        if(!$label) $label = $tag['langkey'] . ':';
1074
1075        echo '<dt>'.$label.'</dt><dd>';
1076        if ($tag['type'] == 'date') {
1077            echo dformat($tag['value']);
1078        } else {
1079            echo hsc($tag['value']);
1080        }
1081        echo '</dd>';
1082    }
1083    echo '</dl>';
1084}
1085
1086/**
1087 * Returns metadata as configured in mediameta config file, ready for creating html
1088 *
1089 * @return array with arrays containing the entries:
1090 *   - string langkey  key to lookup in the $lang var, if not found printed as is
1091 *   - string type     type of value
1092 *   - string value    tag value (unescaped)
1093 */
1094function tpl_get_img_meta() {
1095
1096    $config_files = getConfigFiles('mediameta');
1097    foreach ($config_files as $config_file) {
1098        if(@file_exists($config_file)) {
1099            include($config_file);
1100        }
1101    }
1102    /** @var array $fields the included array with metadata */
1103
1104    $tags = array();
1105    foreach($fields as $tag){
1106        $t = array();
1107        if (!empty($tag[0])) {
1108            $t = array($tag[0]);
1109        }
1110        if(is_array($tag[3])) {
1111            $t = array_merge($t,$tag[3]);
1112        }
1113        $value = tpl_img_getTag($t);
1114        if ($value) {
1115            $tags[] = array('langkey' => $tag[1], 'type' => $tag[2], 'value' => $value);
1116        }
1117    }
1118    return $tags;
1119}
1120
1121/**
1122 * Prints the image with a link to the full sized version
1123 *
1124 * Only allowed in: detail.php
1125 *
1126 * @triggers TPL_IMG_DISPLAY
1127 * @param $maxwidth  int - maximal width of the image
1128 * @param $maxheight int - maximal height of the image
1129 * @param $link bool     - link to the orginal size?
1130 * @param $params array  - additional image attributes
1131 * @return mixed Result of TPL_IMG_DISPLAY
1132 */
1133function tpl_img($maxwidth = 0, $maxheight = 0, $link = true, $params = null) {
1134    global $IMG;
1135    /** @var Input $INPUT */
1136    global $INPUT;
1137    $w = tpl_img_getTag('File.Width');
1138    $h = tpl_img_getTag('File.Height');
1139
1140    //resize to given max values
1141    $ratio = 1;
1142    if($w >= $h) {
1143        if($maxwidth && $w >= $maxwidth) {
1144            $ratio = $maxwidth / $w;
1145        } elseif($maxheight && $h > $maxheight) {
1146            $ratio = $maxheight / $h;
1147        }
1148    } else {
1149        if($maxheight && $h >= $maxheight) {
1150            $ratio = $maxheight / $h;
1151        } elseif($maxwidth && $w > $maxwidth) {
1152            $ratio = $maxwidth / $w;
1153        }
1154    }
1155    if($ratio) {
1156        $w = floor($ratio * $w);
1157        $h = floor($ratio * $h);
1158    }
1159
1160    //prepare URLs
1161    $url = ml($IMG, array('cache'=> $INPUT->str('cache')), true, '&');
1162    $src = ml($IMG, array('cache'=> $INPUT->str('cache'), 'w'=> $w, 'h'=> $h), true, '&');
1163
1164    //prepare attributes
1165    $alt = tpl_img_getTag('Simple.Title');
1166    if(is_null($params)) {
1167        $p = array();
1168    } else {
1169        $p = $params;
1170    }
1171    if($w) $p['width'] = $w;
1172    if($h) $p['height'] = $h;
1173    $p['class'] = 'img_detail';
1174    if($alt) {
1175        $p['alt']   = $alt;
1176        $p['title'] = $alt;
1177    } else {
1178        $p['alt'] = '';
1179    }
1180    $p['src'] = $src;
1181
1182    $data = array('url'=> ($link ? $url : null), 'params'=> $p);
1183    return trigger_event('TPL_IMG_DISPLAY', $data, '_tpl_img_action', true);
1184}
1185
1186/**
1187 * Default action for TPL_IMG_DISPLAY
1188 *
1189 * @param array $data
1190 * @return bool
1191 */
1192function _tpl_img_action($data) {
1193    global $lang;
1194    $p = buildAttributes($data['params']);
1195
1196    if($data['url']) print '<a href="'.hsc($data['url']).'" title="'.$lang['mediaview'].'">';
1197    print '<img '.$p.'/>';
1198    if($data['url']) print '</a>';
1199    return true;
1200}
1201
1202/**
1203 * This function inserts a small gif which in reality is the indexer function.
1204 *
1205 * Should be called somewhere at the very end of the main.php
1206 * template
1207 *
1208 * @return bool
1209 */
1210function tpl_indexerWebBug() {
1211    global $ID;
1212
1213    $p           = array();
1214    $p['src']    = DOKU_BASE.'lib/exe/indexer.php?id='.rawurlencode($ID).
1215        '&'.time();
1216    $p['width']  = 2; //no more 1x1 px image because we live in times of ad blockers...
1217    $p['height'] = 1;
1218    $p['alt']    = '';
1219    $att         = buildAttributes($p);
1220    print "<img $att />";
1221    return true;
1222}
1223
1224/**
1225 * tpl_getConf($id)
1226 *
1227 * use this function to access template configuration variables
1228 *
1229 * @param string $id      name of the value to access
1230 * @param mixed  $notset  what to return if the setting is not available
1231 * @return mixed
1232 */
1233function tpl_getConf($id, $notset=false) {
1234    global $conf;
1235    static $tpl_configloaded = false;
1236
1237    $tpl = $conf['template'];
1238
1239    if(!$tpl_configloaded) {
1240        $tconf = tpl_loadConfig();
1241        if($tconf !== false) {
1242            foreach($tconf as $key => $value) {
1243                if(isset($conf['tpl'][$tpl][$key])) continue;
1244                $conf['tpl'][$tpl][$key] = $value;
1245            }
1246            $tpl_configloaded = true;
1247        }
1248    }
1249
1250    if(isset($conf['tpl'][$tpl][$id])){
1251        return $conf['tpl'][$tpl][$id];
1252    }
1253
1254    return $notset;
1255}
1256
1257/**
1258 * tpl_loadConfig()
1259 *
1260 * reads all template configuration variables
1261 * this function is automatically called by tpl_getConf()
1262 *
1263 * @return array
1264 */
1265function tpl_loadConfig() {
1266
1267    $file = tpl_incdir().'/conf/default.php';
1268    $conf = array();
1269
1270    if(!@file_exists($file)) return false;
1271
1272    // load default config file
1273    include($file);
1274
1275    return $conf;
1276}
1277
1278// language methods
1279/**
1280 * tpl_getLang($id)
1281 *
1282 * use this function to access template language variables
1283 */
1284function tpl_getLang($id) {
1285    static $lang = array();
1286
1287    if(count($lang) === 0) {
1288        $path = tpl_incdir().'lang/';
1289
1290        $lang = array();
1291
1292        global $conf; // definitely don't invoke "global $lang"
1293        // don't include once
1294        @include($path.'en/lang.php');
1295        if($conf['lang'] != 'en') @include($path.$conf['lang'].'/lang.php');
1296    }
1297
1298    return $lang[$id];
1299}
1300
1301/**
1302 * Retrieve a language dependent file and pass to xhtml renderer for display
1303 * template equivalent of p_locale_xhtml()
1304 *
1305 * @param   string $id id of language dependent wiki page
1306 * @return  string     parsed contents of the wiki page in xhtml format
1307 */
1308function tpl_locale_xhtml($id) {
1309    return p_cached_output(tpl_localeFN($id));
1310}
1311
1312/**
1313 * Prepends appropriate path for a language dependent filename
1314 */
1315function tpl_localeFN($id) {
1316    $path = tpl_incdir().'lang/';
1317    global $conf;
1318    $file = DOKU_CONF.'/template_lang/'.$conf['template'].'/'.$conf['lang'].'/'.$id.'.txt';
1319    if (!@file_exists($file)){
1320        $file = $path.$conf['lang'].'/'.$id.'.txt';
1321        if(!@file_exists($file)){
1322            //fall back to english
1323            $file = $path.'en/'.$id.'.txt';
1324        }
1325    }
1326    return $file;
1327}
1328
1329/**
1330 * prints the "main content" in the mediamanger popup
1331 *
1332 * Depending on the user's actions this may be a list of
1333 * files in a namespace, the meta editing dialog or
1334 * a message of referencing pages
1335 *
1336 * Only allowed in mediamanager.php
1337 *
1338 * @triggers MEDIAMANAGER_CONTENT_OUTPUT
1339 * @param bool $fromajax - set true when calling this function via ajax
1340 * @author Andreas Gohr <andi@splitbrain.org>
1341 */
1342function tpl_mediaContent($fromajax = false, $sort='natural') {
1343    global $IMG;
1344    global $AUTH;
1345    global $INUSE;
1346    global $NS;
1347    global $JUMPTO;
1348    /** @var Input $INPUT */
1349    global $INPUT;
1350
1351    $do = $INPUT->extract('do')->str('do');
1352    if(in_array($do, array('save', 'cancel'))) $do = '';
1353
1354    if(!$do) {
1355        if($INPUT->bool('edit')) {
1356            $do = 'metaform';
1357        } elseif(is_array($INUSE)) {
1358            $do = 'filesinuse';
1359        } else {
1360            $do = 'filelist';
1361        }
1362    }
1363
1364    // output the content pane, wrapped in an event.
1365    if(!$fromajax) ptln('<div id="media__content">');
1366    $data = array('do' => $do);
1367    $evt  = new Doku_Event('MEDIAMANAGER_CONTENT_OUTPUT', $data);
1368    if($evt->advise_before()) {
1369        $do = $data['do'];
1370        if($do == 'filesinuse') {
1371            media_filesinuse($INUSE, $IMG);
1372        } elseif($do == 'filelist') {
1373            media_filelist($NS, $AUTH, $JUMPTO,false,$sort);
1374        } elseif($do == 'searchlist') {
1375            media_searchlist($INPUT->str('q'), $NS, $AUTH);
1376        } else {
1377            msg('Unknown action '.hsc($do), -1);
1378        }
1379    }
1380    $evt->advise_after();
1381    unset($evt);
1382    if(!$fromajax) ptln('</div>');
1383
1384}
1385
1386/**
1387 * Prints the central column in full-screen media manager
1388 * Depending on the opened tab this may be a list of
1389 * files in a namespace, upload form or search form
1390 *
1391 * @author Kate Arzamastseva <pshns@ukr.net>
1392 */
1393function tpl_mediaFileList() {
1394    global $AUTH;
1395    global $NS;
1396    global $JUMPTO;
1397    global $lang;
1398    /** @var Input $INPUT */
1399    global $INPUT;
1400
1401    $opened_tab = $INPUT->str('tab_files');
1402    if(!$opened_tab || !in_array($opened_tab, array('files', 'upload', 'search'))) $opened_tab = 'files';
1403    if($INPUT->str('mediado') == 'update') $opened_tab = 'upload';
1404
1405    echo '<h2 class="a11y">'.$lang['mediaselect'].'</h2>'.NL;
1406
1407    media_tabs_files($opened_tab);
1408
1409    echo '<div class="panelHeader">'.NL;
1410    echo '<h3>';
1411    $tabTitle = ($NS) ? $NS : '['.$lang['mediaroot'].']';
1412    printf($lang['media_'.$opened_tab], '<strong>'.hsc($tabTitle).'</strong>');
1413    echo '</h3>'.NL;
1414    if($opened_tab === 'search' || $opened_tab === 'files') {
1415        media_tab_files_options();
1416    }
1417    echo '</div>'.NL;
1418
1419    echo '<div class="panelContent">'.NL;
1420    if($opened_tab == 'files') {
1421        media_tab_files($NS, $AUTH, $JUMPTO);
1422    } elseif($opened_tab == 'upload') {
1423        media_tab_upload($NS, $AUTH, $JUMPTO);
1424    } elseif($opened_tab == 'search') {
1425        media_tab_search($NS, $AUTH);
1426    }
1427    echo '</div>'.NL;
1428}
1429
1430/**
1431 * Prints the third column in full-screen media manager
1432 * Depending on the opened tab this may be details of the
1433 * selected file, the meta editing dialog or
1434 * list of file revisions
1435 *
1436 * @author Kate Arzamastseva <pshns@ukr.net>
1437 */
1438function tpl_mediaFileDetails($image, $rev) {
1439    global $conf, $DEL, $lang;
1440    /** @var Input $INPUT */
1441    global $INPUT;
1442
1443    $removed = (!file_exists(mediaFN($image)) && file_exists(mediaMetaFN($image, '.changes')) && $conf['mediarevisions']);
1444    if(!$image || (!file_exists(mediaFN($image)) && !$removed) || $DEL) return;
1445    if($rev && !file_exists(mediaFN($image, $rev))) $rev = false;
1446    $ns = getNS($image);
1447    $do = $INPUT->str('mediado');
1448
1449    $opened_tab = $INPUT->str('tab_details');
1450
1451    $tab_array = array('view');
1452    list(, $mime) = mimetype($image);
1453    if($mime == 'image/jpeg') {
1454        $tab_array[] = 'edit';
1455    }
1456    if($conf['mediarevisions']) {
1457        $tab_array[] = 'history';
1458    }
1459
1460    if(!$opened_tab || !in_array($opened_tab, $tab_array)) $opened_tab = 'view';
1461    if($INPUT->bool('edit')) $opened_tab = 'edit';
1462    if($do == 'restore') $opened_tab = 'view';
1463
1464    media_tabs_details($image, $opened_tab);
1465
1466    echo '<div class="panelHeader"><h3>';
1467    list($ext) = mimetype($image, false);
1468    $class    = preg_replace('/[^_\-a-z0-9]+/i', '_', $ext);
1469    $class    = 'select mediafile mf_'.$class;
1470    $tabTitle = '<strong><a href="'.ml($image).'" class="'.$class.'" title="'.$lang['mediaview'].'">'.$image.'</a>'.'</strong>';
1471    if($opened_tab === 'view' && $rev) {
1472        printf($lang['media_viewold'], $tabTitle, dformat($rev));
1473    } else {
1474        printf($lang['media_'.$opened_tab], $tabTitle);
1475    }
1476
1477    echo '</h3></div>'.NL;
1478
1479    echo '<div class="panelContent">'.NL;
1480
1481    if($opened_tab == 'view') {
1482        media_tab_view($image, $ns, null, $rev);
1483
1484    } elseif($opened_tab == 'edit' && !$removed) {
1485        media_tab_edit($image, $ns);
1486
1487    } elseif($opened_tab == 'history' && $conf['mediarevisions']) {
1488        media_tab_history($image, $ns);
1489    }
1490
1491    echo '</div>'.NL;
1492}
1493
1494/**
1495 * prints the namespace tree in the mediamanger popup
1496 *
1497 * Only allowed in mediamanager.php
1498 *
1499 * @author Andreas Gohr <andi@splitbrain.org>
1500 */
1501function tpl_mediaTree() {
1502    global $NS;
1503    ptln('<div id="media__tree">');
1504    media_nstree($NS);
1505    ptln('</div>');
1506}
1507
1508/**
1509 * Print a dropdown menu with all DokuWiki actions
1510 *
1511 * Note: this will not use any pretty URLs
1512 *
1513 * @author Andreas Gohr <andi@splitbrain.org>
1514 */
1515function tpl_actiondropdown($empty = '', $button = '&gt;') {
1516    global $ID;
1517    global $REV;
1518    global $lang;
1519    /** @var Input $INPUT */
1520    global $INPUT;
1521
1522    echo '<form action="'.script().'" method="get" accept-charset="utf-8">';
1523    echo '<div class="no">';
1524    echo '<input type="hidden" name="id" value="'.$ID.'" />';
1525    if($REV) echo '<input type="hidden" name="rev" value="'.$REV.'" />';
1526    if ($INPUT->server->str('REMOTE_USER')) {
1527        echo '<input type="hidden" name="sectok" value="'.getSecurityToken().'" />';
1528    }
1529
1530    echo '<select name="do" class="edit quickselect" title="'.$lang['tools'].'">';
1531    echo '<option value="">'.$empty.'</option>';
1532
1533    echo '<optgroup label="'.$lang['page_tools'].'">';
1534    $act = tpl_get_action('edit');
1535    if($act) echo '<option value="'.$act['params']['do'].'">'.$lang['btn_'.$act['type']].'</option>';
1536
1537    $act = tpl_get_action('revert');
1538    if($act) echo '<option value="'.$act['params']['do'].'">'.$lang['btn_'.$act['type']].'</option>';
1539
1540    $act = tpl_get_action('revisions');
1541    if($act) echo '<option value="'.$act['params']['do'].'">'.$lang['btn_'.$act['type']].'</option>';
1542
1543    $act = tpl_get_action('backlink');
1544    if($act) echo '<option value="'.$act['params']['do'].'">'.$lang['btn_'.$act['type']].'</option>';
1545
1546    $act = tpl_get_action('subscribe');
1547    if($act) echo '<option value="'.$act['params']['do'].'">'.$lang['btn_'.$act['type']].'</option>';
1548    echo '</optgroup>';
1549
1550    echo '<optgroup label="'.$lang['site_tools'].'">';
1551    $act = tpl_get_action('recent');
1552    if($act) echo '<option value="'.$act['params']['do'].'">'.$lang['btn_'.$act['type']].'</option>';
1553
1554    $act = tpl_get_action('media');
1555    if($act) echo '<option value="'.$act['params']['do'].'">'.$lang['btn_'.$act['type']].'</option>';
1556
1557    $act = tpl_get_action('index');
1558    if($act) echo '<option value="'.$act['params']['do'].'">'.$lang['btn_'.$act['type']].'</option>';
1559    echo '</optgroup>';
1560
1561    echo '<optgroup label="'.$lang['user_tools'].'">';
1562    $act = tpl_get_action('login');
1563    if($act) echo '<option value="'.$act['params']['do'].'">'.$lang['btn_'.$act['type']].'</option>';
1564
1565    $act = tpl_get_action('register');
1566    if($act) echo '<option value="'.$act['params']['do'].'">'.$lang['btn_'.$act['type']].'</option>';
1567
1568    $act = tpl_get_action('profile');
1569    if($act) echo '<option value="'.$act['params']['do'].'">'.$lang['btn_'.$act['type']].'</option>';
1570
1571    $act = tpl_get_action('admin');
1572    if($act) echo '<option value="'.$act['params']['do'].'">'.$lang['btn_'.$act['type']].'</option>';
1573    echo '</optgroup>';
1574
1575    echo '</select>';
1576    echo '<input type="submit" value="'.$button.'" />';
1577    echo '</div>';
1578    echo '</form>';
1579}
1580
1581/**
1582 * Print a informational line about the used license
1583 *
1584 * @author Andreas Gohr <andi@splitbrain.org>
1585 * @param  string $img     print image? (|button|badge)
1586 * @param  bool   $imgonly skip the textual description?
1587 * @param  bool   $return  when true don't print, but return HTML
1588 * @param  bool   $wrap    wrap in div with class="license"?
1589 * @return string
1590 */
1591function tpl_license($img = 'badge', $imgonly = false, $return = false, $wrap = true) {
1592    global $license;
1593    global $conf;
1594    global $lang;
1595    if(!$conf['license']) return '';
1596    if(!is_array($license[$conf['license']])) return '';
1597    $lic    = $license[$conf['license']];
1598    $target = ($conf['target']['extern']) ? ' target="'.$conf['target']['extern'].'"' : '';
1599
1600    $out = '';
1601    if($wrap) $out .= '<div class="license">';
1602    if($img) {
1603        $src = license_img($img);
1604        if($src) {
1605            $out .= '<a href="'.$lic['url'].'" rel="license"'.$target;
1606            $out .= '><img src="'.DOKU_BASE.$src.'" alt="'.$lic['name'].'" /></a>';
1607            if(!$imgonly) $out .= ' ';
1608        }
1609    }
1610    if(!$imgonly) {
1611        $out .= $lang['license'].' ';
1612        $out .= '<bdi><a href="'.$lic['url'].'" rel="license" class="urlextern"'.$target;
1613        $out .= '>'.$lic['name'].'</a></bdi>';
1614    }
1615    if($wrap) $out .= '</div>';
1616
1617    if($return) return $out;
1618    echo $out;
1619    return '';
1620}
1621
1622/**
1623 * Includes the rendered HTML of a given page
1624 *
1625 * This function is useful to populate sidebars or similar features in a
1626 * template
1627 *
1628 * @param string $pageid
1629 * @param bool $print
1630 * @param bool $propagate
1631 * @return bool|null|string
1632 */
1633function tpl_include_page($pageid, $print = true, $propagate = false) {
1634    if (!$pageid) return false;
1635    if ($propagate) $pageid = page_findnearest($pageid);
1636
1637    global $TOC;
1638    $oldtoc = $TOC;
1639    $html   = p_wiki_xhtml($pageid, '', false);
1640    $TOC    = $oldtoc;
1641
1642    if(!$print) return $html;
1643    echo $html;
1644    return $html;
1645}
1646
1647/**
1648 * Display the subscribe form
1649 *
1650 * @author Adrian Lang <lang@cosmocode.de>
1651 */
1652function tpl_subscribe() {
1653    global $INFO;
1654    global $ID;
1655    global $lang;
1656    global $conf;
1657    $stime_days = $conf['subscribe_time'] / 60 / 60 / 24;
1658
1659    echo p_locale_xhtml('subscr_form');
1660    echo '<h2>'.$lang['subscr_m_current_header'].'</h2>';
1661    echo '<div class="level2">';
1662    if($INFO['subscribed'] === false) {
1663        echo '<p>'.$lang['subscr_m_not_subscribed'].'</p>';
1664    } else {
1665        echo '<ul>';
1666        foreach($INFO['subscribed'] as $sub) {
1667            echo '<li><div class="li">';
1668            if($sub['target'] !== $ID) {
1669                echo '<code class="ns">'.hsc(prettyprint_id($sub['target'])).'</code>';
1670            } else {
1671                echo '<code class="page">'.hsc(prettyprint_id($sub['target'])).'</code>';
1672            }
1673            $sstl = sprintf($lang['subscr_style_'.$sub['style']], $stime_days);
1674            if(!$sstl) $sstl = hsc($sub['style']);
1675            echo ' ('.$sstl.') ';
1676
1677            echo '<a href="'.wl(
1678                $ID,
1679                array(
1680                     'do'        => 'subscribe',
1681                     'sub_target'=> $sub['target'],
1682                     'sub_style' => $sub['style'],
1683                     'sub_action'=> 'unsubscribe',
1684                     'sectok'    => getSecurityToken()
1685                )
1686            ).
1687                '" class="unsubscribe">'.$lang['subscr_m_unsubscribe'].
1688                '</a></div></li>';
1689        }
1690        echo '</ul>';
1691    }
1692    echo '</div>';
1693
1694    // Add new subscription form
1695    echo '<h2>'.$lang['subscr_m_new_header'].'</h2>';
1696    echo '<div class="level2">';
1697    $ns      = getNS($ID).':';
1698    $targets = array(
1699        $ID => '<code class="page">'.prettyprint_id($ID).'</code>',
1700        $ns => '<code class="ns">'.prettyprint_id($ns).'</code>',
1701    );
1702    $styles  = array(
1703        'every'  => $lang['subscr_style_every'],
1704        'digest' => sprintf($lang['subscr_style_digest'], $stime_days),
1705        'list'   => sprintf($lang['subscr_style_list'], $stime_days),
1706    );
1707
1708    $form = new Doku_Form(array('id' => 'subscribe__form'));
1709    $form->startFieldset($lang['subscr_m_subscribe']);
1710    $form->addRadioSet('sub_target', $targets);
1711    $form->startFieldset($lang['subscr_m_receive']);
1712    $form->addRadioSet('sub_style', $styles);
1713    $form->addHidden('sub_action', 'subscribe');
1714    $form->addHidden('do', 'subscribe');
1715    $form->addHidden('id', $ID);
1716    $form->endFieldset();
1717    $form->addElement(form_makeButton('submit', 'subscribe', $lang['subscr_m_subscribe']));
1718    html_form('SUBSCRIBE', $form);
1719    echo '</div>';
1720}
1721
1722/**
1723 * Tries to send already created content right to the browser
1724 *
1725 * Wraps around ob_flush() and flush()
1726 *
1727 * @author Andreas Gohr <andi@splitbrain.org>
1728 */
1729function tpl_flush() {
1730    ob_flush();
1731    flush();
1732}
1733
1734/**
1735 * Tries to find a ressource file in the given locations.
1736 *
1737 * If a given location starts with a colon it is assumed to be a media
1738 * file, otherwise it is assumed to be relative to the current template
1739 *
1740 * @param  array $search       locations to look at
1741 * @param  bool  $abs           if to use absolute URL
1742 * @param  array &$imginfo   filled with getimagesize()
1743 * @return string
1744 * @author Andreas  Gohr <andi@splitbrain.org>
1745 */
1746function tpl_getMediaFile($search, $abs = false, &$imginfo = null) {
1747    $img     = '';
1748    $file    = '';
1749    $ismedia = false;
1750    // loop through candidates until a match was found:
1751    foreach($search as $img) {
1752        if(substr($img, 0, 1) == ':') {
1753            $file    = mediaFN($img);
1754            $ismedia = true;
1755        } else {
1756            $file    = tpl_incdir().$img;
1757            $ismedia = false;
1758        }
1759
1760        if(file_exists($file)) break;
1761    }
1762
1763    // fetch image data if requested
1764    if(!is_null($imginfo)) {
1765        $imginfo = getimagesize($file);
1766    }
1767
1768    // build URL
1769    if($ismedia) {
1770        $url = ml($img, '', true, '', $abs);
1771    } else {
1772        $url = tpl_basedir().$img;
1773        if($abs) $url = DOKU_URL.substr($url, strlen(DOKU_REL));
1774    }
1775
1776    return $url;
1777}
1778
1779/**
1780 * PHP include a file
1781 *
1782 * either from the conf directory if it exists, otherwise use
1783 * file in the template's root directory.
1784 *
1785 * The function honours config cascade settings and looks for the given
1786 * file next to the ´main´ config files, in the order protected, local,
1787 * default.
1788 *
1789 * Note: no escaping or sanity checking is done here. Never pass user input
1790 * to this function!
1791 *
1792 * @author Anika Henke <anika@selfthinker.org>
1793 * @author Andreas Gohr <andi@splitbrain.org>
1794 */
1795function tpl_includeFile($file) {
1796    global $config_cascade;
1797    foreach(array('protected', 'local', 'default') as $config_group) {
1798        if(empty($config_cascade['main'][$config_group])) continue;
1799        foreach($config_cascade['main'][$config_group] as $conf_file) {
1800            $dir = dirname($conf_file);
1801            if(file_exists("$dir/$file")) {
1802                include("$dir/$file");
1803                return;
1804            }
1805        }
1806    }
1807
1808    // still here? try the template dir
1809    $file = tpl_incdir().$file;
1810    if(file_exists($file)) {
1811        include($file);
1812    }
1813}
1814
1815/**
1816 * Returns <link> tag for various icon types (favicon|mobile|generic)
1817 *
1818 * @author Anika Henke <anika@selfthinker.org>
1819 * @param  array $types - list of icon types to display (favicon|mobile|generic)
1820 * @return string
1821 */
1822function tpl_favicon($types = array('favicon')) {
1823
1824    $return = '';
1825
1826    foreach($types as $type) {
1827        switch($type) {
1828            case 'favicon':
1829                $look = array(':wiki:favicon.ico', ':favicon.ico', 'images/favicon.ico');
1830                $return .= '<link rel="shortcut icon" href="'.tpl_getMediaFile($look).'" />'.NL;
1831                break;
1832            case 'mobile':
1833                $look = array(':wiki:apple-touch-icon.png', ':apple-touch-icon.png', 'images/apple-touch-icon.png');
1834                $return .= '<link rel="apple-touch-icon" href="'.tpl_getMediaFile($look).'" />'.NL;
1835                break;
1836            case 'generic':
1837                // ideal world solution, which doesn't work in any browser yet
1838                $look = array(':wiki:favicon.svg', ':favicon.svg', 'images/favicon.svg');
1839                $return .= '<link rel="icon" href="'.tpl_getMediaFile($look).'" type="image/svg+xml" />'.NL;
1840                break;
1841        }
1842    }
1843
1844    return $return;
1845}
1846
1847/**
1848 * Prints full-screen media manager
1849 *
1850 * @author Kate Arzamastseva <pshns@ukr.net>
1851 */
1852function tpl_media() {
1853    global $NS, $IMG, $JUMPTO, $REV, $lang, $fullscreen, $INPUT;
1854    $fullscreen = true;
1855    require_once DOKU_INC.'lib/exe/mediamanager.php';
1856
1857    $rev   = '';
1858    $image = cleanID($INPUT->str('image'));
1859    if(isset($IMG)) $image = $IMG;
1860    if(isset($JUMPTO)) $image = $JUMPTO;
1861    if(isset($REV) && !$JUMPTO) $rev = $REV;
1862
1863    echo '<div id="mediamanager__page">'.NL;
1864    echo '<h1>'.$lang['btn_media'].'</h1>'.NL;
1865    html_msgarea();
1866
1867    echo '<div class="panel namespaces">'.NL;
1868    echo '<h2>'.$lang['namespaces'].'</h2>'.NL;
1869    echo '<div class="panelHeader">';
1870    echo $lang['media_namespaces'];
1871    echo '</div>'.NL;
1872
1873    echo '<div class="panelContent" id="media__tree">'.NL;
1874    media_nstree($NS);
1875    echo '</div>'.NL;
1876    echo '</div>'.NL;
1877
1878    echo '<div class="panel filelist">'.NL;
1879    tpl_mediaFileList();
1880    echo '</div>'.NL;
1881
1882    echo '<div class="panel file">'.NL;
1883    echo '<h2 class="a11y">'.$lang['media_file'].'</h2>'.NL;
1884    tpl_mediaFileDetails($image, $rev);
1885    echo '</div>'.NL;
1886
1887    echo '</div>'.NL;
1888}
1889
1890/**
1891 * Return useful layout classes
1892 *
1893 * @author Anika Henke <anika@selfthinker.org>
1894 */
1895function tpl_classes() {
1896    global $ACT, $conf, $ID, $INFO;
1897    /** @var Input $INPUT */
1898    global $INPUT;
1899
1900    $classes = array(
1901        'dokuwiki',
1902        'mode_'.$ACT,
1903        'tpl_'.$conf['template'],
1904        $INPUT->server->bool('REMOTE_USER') ? 'loggedIn' : '',
1905        $INFO['exists'] ? '' : 'notFound',
1906        ($ID == $conf['start']) ? 'home' : '',
1907    );
1908    return join(' ', $classes);
1909}
1910
1911//Setup VIM: ex: et ts=4 :
1912
1913