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