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