xref: /dokuwiki/inc/template.php (revision 33c7f9a3da533668d21db2e26f776bd854ae81fa)
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 * Returns the path to the given template, uses
13 * default one if the custom version doesn't exist.
14 *
15 * @author Andreas Gohr <andi@splitbrain.org>
16 */
17function template($tpl){
18    global $conf;
19
20    if(@is_readable(DOKU_INC.'lib/tpl/'.$conf['template'].'/'.$tpl))
21        return DOKU_INC.'lib/tpl/'.$conf['template'].'/'.$tpl;
22
23    return DOKU_INC.'lib/tpl/default/'.$tpl;
24}
25
26/**
27 * Print the content
28 *
29 * This function is used for printing all the usual content
30 * (defined by the global $ACT var) by calling the appropriate
31 * outputfunction(s) from html.php
32 *
33 * Everything that doesn't use the main template file isn't
34 * handled by this function. ACL stuff is not done here either.
35 *
36 * @author Andreas Gohr <andi@splitbrain.org>
37 */
38function tpl_content($prependTOC=true) {
39    global $ACT;
40    global $INFO;
41    $INFO['prependTOC'] = $prependTOC;
42
43    ob_start();
44    trigger_event('TPL_ACT_RENDER',$ACT,'tpl_content_core');
45    $html_output = ob_get_clean();
46    trigger_event('TPL_CONTENT_DISPLAY',$html_output,'ptln');
47
48    return !empty($html_output);
49}
50
51function tpl_content_core(){
52    global $ACT;
53    global $TEXT;
54    global $PRE;
55    global $SUF;
56    global $SUM;
57    global $IDX;
58
59    switch($ACT){
60        case 'show':
61            html_show();
62            break;
63        case 'locked':
64            html_locked();
65        case 'edit':
66        case 'recover':
67            html_edit();
68            break;
69        case 'preview':
70            html_edit();
71            html_show($TEXT);
72            break;
73        case 'draft':
74            html_draft();
75            break;
76        case 'search':
77            html_search();
78            break;
79        case 'revisions':
80            $first = isset($_REQUEST['first']) ? intval($_REQUEST['first']) : 0;
81            html_revisions($first);
82            break;
83        case 'diff':
84            html_diff();
85            break;
86        case 'recent':
87            if (is_array($_REQUEST['first'])) {
88                $_REQUEST['first'] = array_keys($_REQUEST['first']);
89                $_REQUEST['first'] = $_REQUEST['first'][0];
90            }
91            $first = is_numeric($_REQUEST['first']) ? intval($_REQUEST['first']) : 0;
92            html_recent($first);
93            break;
94        case 'index':
95            html_index($IDX); #FIXME can this be pulled from globals? is it sanitized correctly?
96            break;
97        case 'backlink':
98            html_backlinks();
99            break;
100        case 'conflict':
101            html_conflict(con($PRE,$TEXT,$SUF),$SUM);
102            html_diff(con($PRE,$TEXT,$SUF),false);
103            break;
104        case 'login':
105            html_login();
106            break;
107        case 'register':
108            html_register();
109            break;
110        case 'resendpwd':
111            html_resendpwd();
112            break;
113        case 'denied':
114            print p_locale_xhtml('denied');
115            break;
116        case 'profile' :
117            html_updateprofile();
118            break;
119        case 'admin':
120            tpl_admin();
121            break;
122        case 'subscribe':
123            tpl_subscribe();
124            break;
125        default:
126            $evt = new Doku_Event('TPL_ACT_UNKNOWN',$ACT);
127            if ($evt->advise_before())
128                msg("Failed to handle command: ".hsc($ACT),-1);
129            $evt->advise_after();
130            unset($evt);
131            return false;
132    }
133    return true;
134}
135
136/**
137 * Places the TOC where the function is called
138 *
139 * If you use this you most probably want to call tpl_content with
140 * a false argument
141 *
142 * @author Andreas Gohr <andi@splitbrain.org>
143 */
144function tpl_toc($return=false){
145    global $TOC;
146    global $ACT;
147    global $ID;
148    global $REV;
149    global $INFO;
150    global $conf;
151    $toc = array();
152
153    if(is_array($TOC)){
154        // if a TOC was prepared in global scope, always use it
155        $toc = $TOC;
156    }elseif(($ACT == 'show' || substr($ACT,0,6) == 'export') && !$REV && $INFO['exists']){
157        // get TOC from metadata, render if neccessary
158        $meta = p_get_metadata($ID, false, true);
159        if(isset($meta['internal']['toc'])){
160            $tocok = $meta['internal']['toc'];
161        }else{
162            $tocok = true;
163        }
164        $toc   = $meta['description']['tableofcontents'];
165        if(!$tocok || !is_array($toc) || !$conf['tocminheads'] || count($toc) < $conf['tocminheads']){
166            $toc = array();
167        }
168    }elseif($ACT == 'admin'){
169        // try to load admin plugin TOC FIXME: duplicates code from tpl_admin
170        $plugin = null;
171        if (!empty($_REQUEST['page'])) {
172            $pluginlist = plugin_list('admin');
173            if (in_array($_REQUEST['page'], $pluginlist)) {
174                // attempt to load the plugin
175                $plugin =& plugin_load('admin',$_REQUEST['page']);
176            }
177        }
178        if ( ($plugin !== null) &&
179                (!$plugin->forAdminOnly() || $INFO['isadmin']) ){
180            $toc = $plugin->getTOC();
181            $TOC = $toc; // avoid later rebuild
182        }
183    }
184
185    trigger_event('TPL_TOC_RENDER', $toc, null, false);
186    $html = html_TOC($toc);
187    if($return) return $html;
188    echo $html;
189}
190
191/**
192 * Handle the admin page contents
193 *
194 * @author Andreas Gohr <andi@splitbrain.org>
195 */
196function tpl_admin(){
197    global $INFO;
198    global $TOC;
199
200    $plugin = null;
201    if (!empty($_REQUEST['page'])) {
202        $pluginlist = plugin_list('admin');
203
204        if (in_array($_REQUEST['page'], $pluginlist)) {
205
206            // attempt to load the plugin
207            $plugin =& plugin_load('admin',$_REQUEST['page']);
208        }
209    }
210
211    if ($plugin !== null){
212        if(!is_array($TOC)) $TOC = $plugin->getTOC(); //if TOC wasn't requested yet
213        if($INFO['prependTOC']) tpl_toc();
214        $plugin->html();
215    }else{
216        html_admin();
217    }
218    return true;
219}
220
221/**
222 * Print the correct HTML meta headers
223 *
224 * This has to go into the head section of your template.
225 *
226 * @triggers TPL_METAHEADER_OUTPUT
227 * @param  boolean $alt Should feeds and alternative format links be added?
228 * @author Andreas Gohr <andi@splitbrain.org>
229 */
230function tpl_metaheaders($alt=true){
231    global $ID;
232    global $REV;
233    global $INFO;
234    global $JSINFO;
235    global $ACT;
236    global $QUERY;
237    global $lang;
238    global $conf;
239    $it=2;
240
241    // prepare the head array
242    $head = array();
243
244    // prepare seed for js and css
245    $tseed = 0;
246    $depends = getConfigFiles('main');
247    foreach($depends as $f) {
248        $time = @filemtime($f);
249        if($time > $tseed) $tseed = $time;
250    }
251
252    // the usual stuff
253    $head['meta'][] = array( 'name'=>'generator', 'content'=>'DokuWiki');
254    $head['link'][] = array( 'rel'=>'search', 'type'=>'application/opensearchdescription+xml',
255            'href'=>DOKU_BASE.'lib/exe/opensearch.php', 'title'=>$conf['title'] );
256    $head['link'][] = array( 'rel'=>'start', 'href'=>DOKU_BASE );
257    if(actionOK('index')){
258        $head['link'][] = array( 'rel'=>'contents', 'href'=> wl($ID,'do=index',false,'&'),
259                'title'=>$lang['btn_index'] );
260    }
261
262    if($alt){
263        $head['link'][] = array( 'rel'=>'alternate', 'type'=>'application/rss+xml',
264                'title'=>'Recent Changes', 'href'=>DOKU_BASE.'feed.php');
265        $head['link'][] = array( 'rel'=>'alternate', 'type'=>'application/rss+xml',
266                'title'=>'Current Namespace',
267                'href'=>DOKU_BASE.'feed.php?mode=list&ns='.$INFO['namespace']);
268        if(($ACT == 'show' || $ACT == 'search') && $INFO['writable']){
269            $head['link'][] = array( 'rel'=>'edit',
270                    'title'=>$lang['btn_edit'],
271                    'href'=> wl($ID,'do=edit',false,'&'));
272        }
273
274        if($ACT == 'search'){
275            $head['link'][] = array( 'rel'=>'alternate', 'type'=>'application/rss+xml',
276                    'title'=>'Search Result',
277                    'href'=>DOKU_BASE.'feed.php?mode=search&q='.$QUERY);
278        }
279
280        if(actionOK('export_xhtml')){
281            $head['link'][] = array( 'rel'=>'alternate', 'type'=>'text/html', 'title'=>'Plain HTML',
282                    'href'=>exportlink($ID, 'xhtml', '', false, '&'));
283        }
284
285        if(actionOK('export_raw')){
286            $head['link'][] = array( 'rel'=>'alternate', 'type'=>'text/plain', 'title'=>'Wiki Markup',
287                    'href'=>exportlink($ID, 'raw', '', false, '&'));
288        }
289    }
290
291    // setup robot tags apropriate for different modes
292    if( ($ACT=='show' || $ACT=='export_xhtml') && !$REV){
293        if($INFO['exists']){
294            //delay indexing:
295            if((time() - $INFO['lastmod']) >= $conf['indexdelay']){
296                $head['meta'][] = array( 'name'=>'robots', 'content'=>'index,follow');
297            }else{
298                $head['meta'][] = array( 'name'=>'robots', 'content'=>'noindex,nofollow');
299            }
300            $head['link'][] = array( 'rel'=>'canonical', 'href'=>wl($ID,'',true,'&') );
301        }else{
302            $head['meta'][] = array( 'name'=>'robots', 'content'=>'noindex,follow');
303        }
304    }elseif(defined('DOKU_MEDIADETAIL')){
305        $head['meta'][] = array( 'name'=>'robots', 'content'=>'index,follow');
306    }else{
307        $head['meta'][] = array( 'name'=>'robots', 'content'=>'noindex,nofollow');
308    }
309
310    // set metadata
311    if($ACT == 'show' || $ACT=='export_xhtml'){
312        // date of modification
313        if($REV){
314            $head['meta'][] = array( 'name'=>'date', 'content'=>date('Y-m-d\TH:i:sO',$REV));
315        }else{
316            $head['meta'][] = array( 'name'=>'date', 'content'=>date('Y-m-d\TH:i:sO',$INFO['lastmod']));
317        }
318
319        // keywords (explicit or implicit)
320        if(!empty($INFO['meta']['subject'])){
321            $head['meta'][] = array( 'name'=>'keywords', 'content'=>join(',',$INFO['meta']['subject']));
322        }else{
323            $head['meta'][] = array( 'name'=>'keywords', 'content'=>str_replace(':',',',$ID));
324        }
325    }
326
327    // load stylesheets
328    $head['link'][] = array('rel'=>'stylesheet', 'media'=>'screen', 'type'=>'text/css',
329            'href'=>DOKU_BASE.'lib/exe/css.php?t='.$conf['template'].'&tseed='.$tseed);
330    $head['link'][] = array('rel'=>'stylesheet', 'media'=>'all', 'type'=>'text/css',
331            'href'=>DOKU_BASE.'lib/exe/css.php?s=all&t='.$conf['template'].'&tseed='.$tseed);
332    $head['link'][] = array('rel'=>'stylesheet', 'media'=>'print', 'type'=>'text/css',
333            'href'=>DOKU_BASE.'lib/exe/css.php?s=print&t='.$conf['template'].'&tseed='.$tseed);
334
335    // make $INFO and other vars available to JavaScripts
336    $json = new JSON();
337    $script = "var NS='".$INFO['namespace']."';";
338    if($conf['useacl'] && $_SERVER['REMOTE_USER']){
339        $script .= "var SIG='".toolbar_signature()."';";
340    }
341    $script .= 'var JSINFO = '.$json->encode($JSINFO).';';
342    $head['script'][] = array( 'type'=>'text/javascript', '_data'=> $script);
343
344    // load external javascript
345    $head['script'][] = array( 'type'=>'text/javascript', 'charset'=>'utf-8', '_data'=>'',
346            'src'=>DOKU_BASE.'lib/exe/js.php'.'?tseed='.$tseed);
347
348    // trigger event here
349    trigger_event('TPL_METAHEADER_OUTPUT',$head,'_tpl_metaheaders_action',true);
350    return true;
351}
352
353/**
354 * prints the array build by tpl_metaheaders
355 *
356 * $data is an array of different header tags. Each tag can have multiple
357 * instances. Attributes are given as key value pairs. Values will be HTML
358 * encoded automatically so they should be provided as is in the $data array.
359 *
360 * For tags having a body attribute specify the the body data in the special
361 * attribute '_data'. This field will NOT BE ESCAPED automatically.
362 *
363 * @author Andreas Gohr <andi@splitbrain.org>
364 */
365function _tpl_metaheaders_action($data){
366    foreach($data as $tag => $inst){
367        foreach($inst as $attr){
368            echo '<',$tag,' ',buildAttributes($attr);
369            if(isset($attr['_data']) || $tag == 'script'){
370                if($tag == 'script' && $attr['_data'])
371                    $attr['_data'] = "<!--//--><![CDATA[//><!--\n".
372                        $attr['_data'].
373                        "\n//--><!]]>";
374
375                echo '>',$attr['_data'],'</',$tag,'>';
376            }else{
377                echo '/>';
378            }
379            echo "\n";
380        }
381    }
382}
383
384/**
385 * Print a link
386 *
387 * Just builds a link.
388 *
389 * @author Andreas Gohr <andi@splitbrain.org>
390 */
391function tpl_link($url,$name,$more='',$return=false){
392    $out = '<a href="'.$url.'" ';
393    if ($more) $out .= ' '.$more;
394    $out .= ">$name</a>";
395    if ($return) return $out;
396    print $out;
397    return true;
398}
399
400/**
401 * Prints a link to a WikiPage
402 *
403 * Wrapper around html_wikilink
404 *
405 * @author Andreas Gohr <andi@splitbrain.org>
406 */
407function tpl_pagelink($id,$name=null){
408    print html_wikilink($id,$name);
409    return true;
410}
411
412/**
413 * get the parent page
414 *
415 * Tries to find out which page is parent.
416 * returns false if none is available
417 *
418 * @author Andreas Gohr <andi@splitbrain.org>
419 */
420function tpl_getparent($id){
421    global $conf;
422    $parent = getNS($id).':';
423    resolve_pageid('',$parent,$exists);
424    if($parent == $id) {
425        $pos = strrpos (getNS($id),':');
426        $parent = substr($parent,0,$pos).':';
427        resolve_pageid('',$parent,$exists);
428        if($parent == $id) return false;
429    }
430    return $parent;
431}
432
433/**
434 * Print one of the buttons
435 *
436 * @author Adrian Lang <mail@adrianlang.de>
437 * @see    tpl_get_action
438 */
439function tpl_button($type,$return=false){
440    $data = tpl_get_action($type);
441    if ($data === false) {
442        return false;
443    } elseif (!is_array($data)) {
444        $out = sprintf($data, 'button');
445    } else {
446        extract($data);
447        if ($id === '#dokuwiki__top') {
448            $out = html_topbtn();
449        } else {
450            $out = html_btn($type, $id, $accesskey, $params, $method);
451        }
452    }
453    if ($return) return $out;
454    echo $out;
455    return true;
456}
457
458/**
459 * Like the action buttons but links
460 *
461 * @author Adrian Lang <mail@adrianlang.de>
462 * @see    tpl_get_action
463 */
464function tpl_actionlink($type,$pre='',$suf='',$inner='',$return=false){
465    global $lang;
466    $data = tpl_get_action($type);
467    if ($data === false) {
468        return false;
469    } elseif (!is_array($data)) {
470        $out = sprintf($data, 'link');
471    } else {
472        extract($data);
473        if (strpos($id, '#') === 0) {
474            $linktarget = $id;
475        } else {
476            $linktarget = wl($id, $params);
477        }
478        $caption = $lang['btn_' . $type];
479        $out = tpl_link($linktarget, $pre.(($inner)?$inner:$caption).$suf,
480                        'class="action ' . $type . '" ' .
481                        'accesskey="' . $accesskey . '" rel="nofollow" ' .
482                        'title="' . hsc($caption) . '"', 1);
483    }
484    if ($return) return $out;
485    echo $out;
486    return true;
487}
488
489/**
490 * Check the actions and get data for buttons and links
491 *
492 * Available actions are
493 *
494 *  edit        - edit/create/show/draft
495 *  history     - old revisions
496 *  recent      - recent changes
497 *  login       - login/logout - if ACL enabled
498 *  profile     - user profile (if logged in)
499 *  index       - The index
500 *  admin       - admin page - if enough rights
501 *  top         - back to top
502 *  back        - back to parent - if available
503 *  backlink    - links to the list of backlinks
504 *  subscribe/subscription- subscribe/unsubscribe
505 *
506 * @author Andreas Gohr <andi@splitbrain.org>
507 * @author Matthias Grimm <matthiasgrimm@users.sourceforge.net>
508 * @author Adrian Lang <mail@adrianlang.de>
509 */
510function tpl_get_action($type) {
511    global $ID;
512    global $INFO;
513    global $REV;
514    global $ACT;
515    global $conf;
516    global $auth;
517
518    // check disabled actions and fix the badly named ones
519    if($type == 'history') $type='revisions';
520    if(!actionOK($type)) return false;
521
522    $accesskey = null;
523    $id        = $ID;
524    $method    = 'get';
525    $params    = array('do' => $type);
526    switch($type){
527        case 'edit':
528            // most complicated type - we need to decide on current action
529            if($ACT == 'show' || $ACT == 'search'){
530                $method = 'post';
531                if($INFO['writable']){
532                    $accesskey = 'e';
533                    if(!empty($INFO['draft'])) {
534                        $type = 'draft';
535                        $params['do'] = 'draft';
536                    } else {
537                        $params['rev'] = $REV;
538                        if(!$INFO['exists']){
539                            $type   = 'create';
540                        }
541                    }
542                }else{
543                    if(!actionOK('source')) return false; //pseudo action
544                    $params['rev'] = $REV;
545                    $type = 'source';
546                    $accesskey = 'v';
547                }
548            }else{
549                $params = '';
550                $type = 'show';
551                $accesskey = 'v';
552            }
553            break;
554        case 'revisions':
555            $type = 'revs';
556            $accesskey = 'o';
557            break;
558        case 'recent':
559            $accesskey = 'r';
560            break;
561        case 'index':
562            $accesskey = 'x';
563            break;
564        case 'top':
565            $accesskey = 'x';
566            $params = '';
567            $id = '#dokuwiki__top';
568            break;
569        case 'back':
570            $parent = tpl_getparent($ID);
571            if (!$parent) {
572                return false;
573            }
574            $id = $parent;
575            $params = '';
576            $accesskey = 'b';
577            break;
578        case 'login':
579            $params['sectok'] = getSecurityToken();
580            if(isset($_SERVER['REMOTE_USER'])){
581                if (!actionOK('logout')) {
582                    return false;
583                }
584                $params['do'] = 'logout';
585                $type = 'logout';
586            }
587            break;
588        case 'register':
589            if($_SERVER['REMOTE_USER']){
590                return false;
591            }
592            break;
593        case 'resendpwd':
594            if($_SERVER['REMOTE_USER']){
595                return false;
596            }
597            break;
598        case 'admin':
599            if(!$INFO['ismanager']){
600                return false;
601            }
602            break;
603        case 'revert':
604            if(!$INFO['ismanager'] || !$REV || !$INFO['writable']) {
605                return false;
606            }
607            $params['rev'] = $REV;
608            $params['sectok'] = getSecurityToken();
609            break;
610        case 'subscription':
611            $type = 'subscribe';
612            $params['do'] = 'subscribe';
613        case 'subscribe':
614            if(!$_SERVER['REMOTE_USER']){
615                return false;
616            }
617            break;
618        case 'backlink':
619            break;
620        case 'profile':
621            if(!isset($_SERVER['REMOTE_USER'])){
622                return false;
623            }
624            break;
625        case 'subscribens':
626            // Superseded by subscribe/subscription
627            return '';
628            break;
629        default:
630            return '[unknown %s type]';
631            break;
632    }
633    return compact('accesskey', 'type', 'id', 'method', 'params');
634}
635
636/**
637 * Wrapper around tpl_button() and tpl_actionlink()
638 *
639 * @author Anika Henke <anika@selfthinker.org>
640 */
641function tpl_action($type,$link=0,$wrapper=false,$return=false,$pre='',$suf='',$inner='') {
642    $out = '';
643    if ($link) $out .= tpl_actionlink($type,$pre,$suf,$inner,1);
644    else $out .= tpl_button($type,1);
645    if ($out && $wrapper) $out = "<$wrapper>$out</$wrapper>";
646
647    if ($return) return $out;
648    print $out;
649    return $out ? true : false;
650}
651
652/**
653 * Print the search form
654 *
655 * If the first parameter is given a div with the ID 'qsearch_out' will
656 * be added which instructs the ajax pagequicksearch to kick in and place
657 * its output into this div. The second parameter controls the propritary
658 * attribute autocomplete. If set to false this attribute will be set with an
659 * value of "off" to instruct the browser to disable it's own built in
660 * autocompletion feature (MSIE and Firefox)
661 *
662 * @author Andreas Gohr <andi@splitbrain.org>
663 */
664function tpl_searchform($ajax=true,$autocomplete=true){
665    global $lang;
666    global $ACT;
667    global $QUERY;
668
669    // don't print the search form if search action has been disabled
670    if (!actionOk('search')) return false;
671
672    print '<form action="'.wl().'" accept-charset="utf-8" class="search" id="dw__search" method="get"><div class="no">';
673    print '<input type="hidden" name="do" value="search" />';
674    print '<input type="text" ';
675    if($ACT == 'search') print 'value="'.htmlspecialchars($QUERY).'" ';
676    if(!$autocomplete) print 'autocomplete="off" ';
677    print 'id="qsearch__in" accesskey="f" name="id" class="edit" title="[F]" />';
678    print '<input type="submit" value="'.$lang['btn_search'].'" class="button" title="'.$lang['btn_search'].'" />';
679    if($ajax) print '<div id="qsearch__out" class="ajax_qsearch JSpopup"></div>';
680    print '</div></form>';
681    return true;
682}
683
684/**
685 * Print the breadcrumbs trace
686 *
687 * @author Andreas Gohr <andi@splitbrain.org>
688 */
689function tpl_breadcrumbs($sep='&bull;'){
690    global $lang;
691    global $conf;
692
693    //check if enabled
694    if(!$conf['breadcrumbs']) return false;
695
696    $crumbs = breadcrumbs(); //setup crumb trace
697
698    //reverse crumborder in right-to-left mode, add RLM character to fix heb/eng display mixups
699    if($lang['direction'] == 'rtl') {
700        $crumbs = array_reverse($crumbs,true);
701        $crumbs_sep = ' &#8207;<span class="bcsep">'.$sep.'</span>&#8207; ';
702    } else {
703        $crumbs_sep = ' <span class="bcsep">'.$sep.'</span> ';
704    }
705
706    //render crumbs, highlight the last one
707    print '<span class="bchead">'.$lang['breadcrumb'].':</span>';
708    $last = count($crumbs);
709    $i = 0;
710    foreach ($crumbs as $id => $name){
711        $i++;
712        echo $crumbs_sep;
713        if ($i == $last) print '<span class="curid">';
714        tpl_link(wl($id),hsc($name),'class="breadcrumbs" title="'.$id.'"');
715        if ($i == $last) print '</span>';
716    }
717    return true;
718}
719
720/**
721 * Hierarchical breadcrumbs
722 *
723 * This code was suggested as replacement for the usual breadcrumbs.
724 * It only makes sense with a deep site structure.
725 *
726 * @author Andreas Gohr <andi@splitbrain.org>
727 * @author Nigel McNie <oracle.shinoda@gmail.com>
728 * @author Sean Coates <sean@caedmon.net>
729 * @author <fredrik@averpil.com>
730 * @todo   May behave strangely in RTL languages
731 */
732function tpl_youarehere($sep=' &raquo; '){
733    global $conf;
734    global $ID;
735    global $lang;
736
737    // check if enabled
738    if(!$conf['youarehere']) return false;
739
740    $parts = explode(':', $ID);
741    $count = count($parts);
742
743    echo '<span class="bchead">'.$lang['youarehere'].': </span>';
744
745    // always print the startpage
746    tpl_pagelink(':'.$conf['start']);
747
748    // print intermediate namespace links
749    $part = '';
750    for($i=0; $i<$count - 1; $i++){
751        $part .= $parts[$i].':';
752        $page = $part;
753        if ($page == $conf['start']) continue; // Skip startpage
754
755        // output
756        echo $sep;
757        tpl_pagelink($page);
758    }
759
760    // print current page, skipping start page, skipping for namespace index
761    resolve_pageid('',$page,$exists);
762    if(isset($page) && $page==$part.$parts[$i]) return;
763    $page = $part.$parts[$i];
764    if($page == $conf['start']) return;
765    echo $sep;
766    tpl_pagelink($page);
767    return true;
768}
769
770/**
771 * Print info if the user is logged in
772 * and show full name in that case
773 *
774 * Could be enhanced with a profile link in future?
775 *
776 * @author Andreas Gohr <andi@splitbrain.org>
777 */
778function tpl_userinfo(){
779    global $lang;
780    global $INFO;
781    if(isset($_SERVER['REMOTE_USER'])){
782        print $lang['loggedinas'].': '.hsc($INFO['userinfo']['name']).' ('.hsc($_SERVER['REMOTE_USER']).')';
783        return true;
784    }
785    return false;
786}
787
788/**
789 * Print some info about the current page
790 *
791 * @author Andreas Gohr <andi@splitbrain.org>
792 */
793function tpl_pageinfo($ret=false){
794    global $conf;
795    global $lang;
796    global $INFO;
797    global $ID;
798
799    // return if we are not allowed to view the page
800    if (!auth_quickaclcheck($ID)) { return false; }
801
802    // prepare date and path
803    $fn = $INFO['filepath'];
804    if(!$conf['fullpath']){
805        if($INFO['rev']){
806            $fn = str_replace(fullpath($conf['olddir']).'/','',$fn);
807        }else{
808            $fn = str_replace(fullpath($conf['datadir']).'/','',$fn);
809        }
810    }
811    $fn = utf8_decodeFN($fn);
812    $date = dformat($INFO['lastmod']);
813
814    // print it
815    if($INFO['exists']){
816        $out = '';
817        $out .= $fn;
818        $out .= ' &middot; ';
819        $out .= $lang['lastmod'];
820        $out .= ': ';
821        $out .= $date;
822        if($INFO['editor']){
823            $out .= ' '.$lang['by'].' ';
824            $out .= editorinfo($INFO['editor']);
825        }else{
826            $out .= ' ('.$lang['external_edit'].')';
827        }
828        if($INFO['locked']){
829            $out .= ' &middot; ';
830            $out .= $lang['lockedby'];
831            $out .= ': ';
832            $out .= editorinfo($INFO['locked']);
833        }
834        if($ret){
835            return $out;
836        }else{
837            echo $out;
838            return true;
839        }
840    }
841    return false;
842}
843
844/**
845 * Prints or returns the name of the given page (current one if none given).
846 *
847 * If useheading is enabled this will use the first headline else
848 * the given ID is used.
849 *
850 * @author Andreas Gohr <andi@splitbrain.org>
851 */
852function tpl_pagetitle($id=null, $ret=false){
853    global $conf;
854    if(is_null($id)){
855        global $ID;
856        $id = $ID;
857    }
858
859    $name = $id;
860    if (useHeading('navigation')) {
861        $title = p_get_first_heading($id);
862        if ($title) $name = $title;
863    }
864
865    if ($ret) {
866        return hsc($name);
867    } else {
868        print hsc($name);
869        return true;
870    }
871}
872
873/**
874 * Returns the requested EXIF/IPTC tag from the current image
875 *
876 * If $tags is an array all given tags are tried until a
877 * value is found. If no value is found $alt is returned.
878 *
879 * Which texts are known is defined in the functions _exifTagNames
880 * and _iptcTagNames() in inc/jpeg.php (You need to prepend IPTC
881 * to the names of the latter one)
882 *
883 * Only allowed in: detail.php
884 *
885 * @author Andreas Gohr <andi@splitbrain.org>
886 */
887function tpl_img_getTag($tags,$alt='',$src=null){
888    // Init Exif Reader
889    global $SRC;
890
891    if(is_null($src)) $src = $SRC;
892
893    static $meta = null;
894    if(is_null($meta)) $meta = new JpegMeta($src);
895    if($meta === false) return $alt;
896    $info = $meta->getField($tags);
897    if($info == false) return $alt;
898    return $info;
899}
900
901/**
902 * Prints the image with a link to the full sized version
903 *
904 * Only allowed in: detail.php
905 *
906 * @param $maxwidth  int - maximal width of the image
907 * @param $maxheight int - maximal height of the image
908 * @param $link bool     - link to the orginal size?
909 * @param $params array  - additional image attributes
910 */
911function tpl_img($maxwidth=0,$maxheight=0,$link=true,$params=null){
912    global $IMG;
913    $w = tpl_img_getTag('File.Width');
914    $h = tpl_img_getTag('File.Height');
915
916    //resize to given max values
917    $ratio = 1;
918    if($w >= $h){
919        if($maxwidth && $w >= $maxwidth){
920            $ratio = $maxwidth/$w;
921        }elseif($maxheight && $h > $maxheight){
922            $ratio = $maxheight/$h;
923        }
924    }else{
925        if($maxheight && $h >= $maxheight){
926            $ratio = $maxheight/$h;
927        }elseif($maxwidth && $w > $maxwidth){
928            $ratio = $maxwidth/$w;
929        }
930    }
931    if($ratio){
932        $w = floor($ratio*$w);
933        $h = floor($ratio*$h);
934    }
935
936    //prepare URLs
937    $url=ml($IMG,array('cache'=>$_REQUEST['cache']),true,'&');
938    $src=ml($IMG,array('cache'=>$_REQUEST['cache'],'w'=>$w,'h'=>$h),true,'&');
939
940    //prepare attributes
941    $alt=tpl_img_getTag('Simple.Title');
942    if(is_null($params)){
943        $p = array();
944    }else{
945        $p = $params;
946    }
947    if($w) $p['width']  = $w;
948    if($h) $p['height'] = $h;
949    $p['class']  = 'img_detail';
950    if($alt){
951        $p['alt']   = $alt;
952        $p['title'] = $alt;
953    }else{
954        $p['alt'] = '';
955    }
956    $p['src'] = $src;
957
958    $data = array('url'=>($link?$url:null), 'params'=>$p);
959    return trigger_event('TPL_IMG_DISPLAY',$data,'_tpl_img_action',true);
960}
961
962/**
963 * Default action for TPL_IMG_DISPLAY
964 */
965function _tpl_img_action($data, $param=NULL) {
966    $p = buildAttributes($data['params']);
967
968    if($data['url']) print '<a href="'.hsc($data['url']).'">';
969    print '<img '.$p.'/>';
970    if($data['url']) print '</a>';
971    return true;
972}
973
974/**
975 * This function inserts a 1x1 pixel gif which in reality
976 * is the indexer function.
977 *
978 * Should be called somewhere at the very end of the main.php
979 * template
980 */
981function tpl_indexerWebBug(){
982    global $ID;
983    global $INFO;
984    if(!$INFO['exists']) return false;
985
986    $p = array();
987    $p['src']    = DOKU_BASE.'lib/exe/indexer.php?id='.rawurlencode($ID).
988        '&'.time();
989    $p['width']  = 1;
990    $p['height'] = 1;
991    $p['alt']    = '';
992    $att = buildAttributes($p);
993    print "<img $att />";
994    return true;
995}
996
997// configuration methods
998/**
999 * tpl_getConf($id)
1000 *
1001 * use this function to access template configuration variables
1002 */
1003function tpl_getConf($id){
1004    global $conf;
1005    static $tpl_configloaded = false;
1006
1007    $tpl = $conf['template'];
1008
1009    if (!$tpl_configloaded){
1010        $tconf = tpl_loadConfig();
1011        if ($tconf !== false){
1012            foreach ($tconf as $key => $value){
1013                if (isset($conf['tpl'][$tpl][$key])) continue;
1014                $conf['tpl'][$tpl][$key] = $value;
1015            }
1016            $tpl_configloaded = true;
1017        }
1018    }
1019
1020    return $conf['tpl'][$tpl][$id];
1021}
1022
1023/**
1024 * tpl_loadConfig()
1025 * reads all template configuration variables
1026 * this function is automatically called by tpl_getConf()
1027 */
1028function tpl_loadConfig(){
1029
1030    $file = DOKU_TPLINC.'/conf/default.php';
1031    $conf = array();
1032
1033    if (!@file_exists($file)) return false;
1034
1035    // load default config file
1036    include($file);
1037
1038    return $conf;
1039}
1040
1041// language methods
1042/**
1043 * tpl_getLang($id)
1044 *
1045 * use this function to access template language variables
1046 */
1047function tpl_getLang($id){
1048    static $lang = array();
1049
1050    if (count($lang) === 0){
1051        $path = DOKU_TPLINC.'lang/';
1052
1053        $lang = array();
1054
1055        global $conf;            // definitely don't invoke "global $lang"
1056        // don't include once
1057        @include($path.'en/lang.php');
1058        if ($conf['lang'] != 'en') @include($path.$conf['lang'].'/lang.php');
1059    }
1060
1061    return $lang[$id];
1062}
1063
1064/**
1065 * prints the "main content" in the mediamanger popup
1066 *
1067 * Depending on the user's actions this may be a list of
1068 * files in a namespace, the meta editing dialog or
1069 * a message of referencing pages
1070 *
1071 * Only allowed in mediamanager.php
1072 *
1073 * @triggers MEDIAMANAGER_CONTENT_OUTPUT
1074 * @param bool $fromajax - set true when calling this function via ajax
1075 * @author Andreas Gohr <andi@splitbrain.org>
1076 */
1077function tpl_mediaContent($fromajax=false){
1078    global $IMG;
1079    global $AUTH;
1080    global $INUSE;
1081    global $NS;
1082    global $JUMPTO;
1083
1084    if(is_array($_REQUEST['do'])){
1085        $do = array_shift(array_keys($_REQUEST['do']));
1086    }else{
1087        $do = $_REQUEST['do'];
1088    }
1089    if(in_array($do,array('save','cancel'))) $do = '';
1090
1091    if(!$do){
1092        if($_REQUEST['edit']){
1093            $do = 'metaform';
1094        }elseif(is_array($INUSE)){
1095            $do = 'filesinuse';
1096        }else{
1097            $do = 'filelist';
1098        }
1099    }
1100
1101    // output the content pane, wrapped in an event.
1102    if(!$fromajax) ptln('<div id="media__content">');
1103    $data = array( 'do' => $do);
1104    $evt = new Doku_Event('MEDIAMANAGER_CONTENT_OUTPUT', $data);
1105    if ($evt->advise_before()) {
1106        $do = $data['do'];
1107        if($do == 'metaform'){
1108            media_metaform($IMG,$AUTH);
1109        }elseif($do == 'filesinuse'){
1110            media_filesinuse($INUSE,$IMG);
1111        }elseif($do == 'filelist'){
1112            media_filelist($NS,$AUTH,$JUMPTO);
1113        }elseif($do == 'searchlist'){
1114            media_searchlist($_REQUEST['q'],$NS,$AUTH);
1115        }else{
1116            msg('Unknown action '.hsc($do),-1);
1117        }
1118    }
1119    $evt->advise_after();
1120    unset($evt);
1121    if(!$fromajax) ptln('</div>');
1122
1123}
1124
1125/**
1126 * prints the namespace tree in the mediamanger popup
1127 *
1128 * Only allowed in mediamanager.php
1129 *
1130 * @author Andreas Gohr <andi@splitbrain.org>
1131 */
1132function tpl_mediaTree(){
1133    global $NS;
1134
1135    ptln('<div id="media__tree">');
1136    media_nstree($NS);
1137    ptln('</div>');
1138}
1139
1140
1141/**
1142 * Print a dropdown menu with all DokuWiki actions
1143 *
1144 * Note: this will not use any pretty URLs
1145 *
1146 * @author Andreas Gohr <andi@splitbrain.org>
1147 */
1148function tpl_actiondropdown($empty='',$button='&gt;'){
1149    global $ID;
1150    global $INFO;
1151    global $REV;
1152    global $ACT;
1153    global $conf;
1154    global $lang;
1155    global $auth;
1156
1157    echo '<form action="' . DOKU_SCRIPT . '" method="post" accept-charset="utf-8">';
1158    echo '<input type="hidden" name="id" value="'.$ID.'" />';
1159    if($REV) echo '<input type="hidden" name="rev" value="'.$REV.'" />';
1160    echo '<input type="hidden" name="sectok" value="'.getSecurityToken().'" />';
1161
1162    echo '<select name="do" class="edit quickselect">';
1163    echo '<option value="">'.$empty.'</option>';
1164
1165    echo '<optgroup label=" &mdash; ">';
1166        $act = tpl_get_action('edit');
1167        if($act) echo '<option value="'.$act['params']['do'].'">'.$lang['btn_'.$act['type']].'</option>';
1168
1169        $act = tpl_get_action('revisions');
1170        if($act) echo '<option value="'.$act['params']['do'].'">'.$lang['btn_'.$act['type']].'</option>';
1171
1172        $act = tpl_get_action('revert');
1173        if($act) echo '<option value="'.$act['params']['do'].'">'.$lang['btn_'.$act['type']].'</option>';
1174
1175        $act = tpl_get_action('backlink');
1176        if($act) echo '<option value="'.$act['params']['do'].'">'.$lang['btn_'.$act['type']].'</option>';
1177    echo '</optgroup>';
1178
1179    echo '<optgroup label=" &mdash; ">';
1180        $act = tpl_get_action('recent');
1181        if($act) echo '<option value="'.$act['params']['do'].'">'.$lang['btn_'.$act['type']].'</option>';
1182
1183        $act = tpl_get_action('index');
1184        if($act) echo '<option value="'.$act['params']['do'].'">'.$lang['btn_'.$act['type']].'</option>';
1185    echo '</optgroup>';
1186
1187    echo '<optgroup label=" &mdash; ">';
1188        $act = tpl_get_action('login');
1189        if($act) echo '<option value="'.$act['params']['do'].'">'.$lang['btn_'.$act['type']].'</option>';
1190
1191        $act = tpl_get_action('profile');
1192        if($act) echo '<option value="'.$act['params']['do'].'">'.$lang['btn_'.$act['type']].'</option>';
1193
1194        $act = tpl_get_action('subscribe');
1195        if($act) echo '<option value="'.$act['params']['do'].'">'.$lang['btn_'.$act['type']].'</option>';
1196
1197        $act = tpl_get_action('admin');
1198        if($act) echo '<option value="'.$act['params']['do'].'">'.$lang['btn_'.$act['type']].'</option>';
1199    echo '</optgroup>';
1200
1201    echo '</select>';
1202    echo '<input type="submit" value="'.$button.'" />';
1203    echo '</form>';
1204}
1205
1206/**
1207 * Print a informational line about the used license
1208 *
1209 * @author Andreas Gohr <andi@splitbrain.org>
1210 * @param  string $img    - print image? (|button|badge)
1211 * @param  bool   $return - when true don't print, but return HTML
1212 */
1213function tpl_license($img='badge',$imgonly=false,$return=false){
1214    global $license;
1215    global $conf;
1216    global $lang;
1217    if(!$conf['license']) return '';
1218    if(!is_array($license[$conf['license']])) return '';
1219    $lic = $license[$conf['license']];
1220
1221    $out  = '<div class="license">';
1222    if($img){
1223        $src = license_img($img);
1224        if($src){
1225            $out .= '<a href="'.$lic['url'].'" rel="license"';
1226            if($conf['target']['extern']) $out .= ' target="'.$conf['target']['extern'].'"';
1227            $out .= '><img src="'.DOKU_BASE.$src.'" class="medialeft lic'.$img.'" alt="'.$lic['name'].'" /></a> ';
1228        }
1229    }
1230    if(!$imgonly) {
1231        $out .= $lang['license'];
1232        $out .= ' <a href="'.$lic['url'].'" rel="license" class="urlextern"';
1233        if($conf['target']['extern']) $out .= ' target="'.$conf['target']['extern'].'"';
1234        $out .= '>'.$lic['name'].'</a>';
1235    }
1236    $out .= '</div>';
1237
1238    if($return) return $out;
1239    echo $out;
1240}
1241
1242
1243/**
1244 * Includes the rendered XHTML of a given page
1245 *
1246 * This function is useful to populate sidebars or similar features in a
1247 * template
1248 */
1249function tpl_include_page($pageid,$print=true){
1250    global $ID;
1251    $oldid = $ID;
1252    $html = p_wiki_xhtml($pageid,'',false);
1253    $ID = $oldid;
1254
1255    if(!$print) return $html;
1256    echo $html;
1257}
1258
1259/**
1260 * Display the subscribe form
1261 *
1262 * @author Adrian Lang <lang@cosmocode.de>
1263 */
1264function tpl_subscribe() {
1265    global $INFO;
1266    global $ID;
1267    global $lang;
1268    global $conf;
1269    $stime_days = $conf['subscribe_time']/60/60/24;
1270
1271    echo p_locale_xhtml('subscr_form');
1272    echo '<h2>' . $lang['subscr_m_current_header'] . '</h2>';
1273    echo '<div class="level2">';
1274    if ($INFO['subscribed'] === false) {
1275        echo '<p>' . $lang['subscr_m_not_subscribed'] . '</p>';
1276    } else {
1277        echo '<ul>';
1278        foreach($INFO['subscribed'] as $sub) {
1279            echo '<li><div class="li">';
1280            if ($sub['target'] !== $ID) {
1281                echo '<code class="ns">'.hsc(prettyprint_id($sub['target'])).'</code>';
1282            } else {
1283                echo '<code class="page">'.hsc(prettyprint_id($sub['target'])).'</code>';
1284            }
1285            $sstl = sprintf($lang['subscr_style_'.$sub['style']], $stime_days);
1286            if(!$sstl) $sstl = hsc($sub['style']);
1287            echo ' ('.$sstl.') ';
1288
1289            echo '<a href="' . wl($ID,
1290                                  array('do'=>'subscribe',
1291                                        'sub_target'=>$sub['target'],
1292                                        'sub_style'=>$sub['style'],
1293                                        'sub_action'=>'unsubscribe',
1294                                        'sectok' => getSecurityToken())) .
1295                 '" class="unsubscribe">'.$lang['subscr_m_unsubscribe'] .
1296                 '</a></div></li>';
1297        }
1298        echo '</ul>';
1299    }
1300    echo '</div>';
1301
1302    // Add new subscription form
1303    echo '<h2>' . $lang['subscr_m_new_header'] . '</h2>';
1304    echo '<div class="level2">';
1305    $ns = getNS($ID).':';
1306    $targets = array(
1307            $ID => '<code class="page">'.prettyprint_id($ID).'</code>',
1308            $ns => '<code class="ns">'.prettyprint_id($ns).'</code>',
1309            );
1310    $styles = array(
1311            'every'  => $lang['subscr_style_every'],
1312            'digest' => sprintf($lang['subscr_style_digest'], $stime_days),
1313            'list' => sprintf($lang['subscr_style_list'], $stime_days),
1314            );
1315
1316    $form = new Doku_Form(array('id' => 'subscribe__form'));
1317    $form->startFieldset($lang['subscr_m_subscribe']);
1318    $form->addRadioSet('sub_target', $targets);
1319    $form->startFieldset($lang['subscr_m_receive']);
1320    $form->addRadioSet('sub_style', $styles);
1321    $form->addHidden('sub_action', 'subscribe');
1322    $form->addHidden('do', 'subscribe');
1323    $form->addHidden('id', $ID);
1324    $form->endFieldset();
1325    $form->addElement(form_makeButton('submit', 'subscribe', $lang['subscr_m_subscribe']));
1326    html_form('SUBSCRIBE', $form);
1327    echo '</div>';
1328}
1329
1330/**
1331 * Tries to send already created content right to the browser
1332 *
1333 * Wraps around ob_flush() and flush()
1334 *
1335 * @author Andreas Gohr <andi@splitbrain.org>
1336 */
1337function tpl_flush(){
1338    ob_flush();
1339    flush();
1340}
1341
1342
1343/**
1344 * Use favicon.ico from data/media root directory if it exists, otherwise use
1345 * the one in the template's image directory.
1346 *
1347 * @author Anika Henke <anika@selfthinker.org>
1348 */
1349function tpl_getFavicon() {
1350    if (file_exists(mediaFN('favicon.ico')))
1351        return ml('favicon.ico');
1352    return DOKU_TPL.'images/favicon.ico';
1353}
1354
1355
1356//Setup VIM: ex: et ts=4 :
1357
1358