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