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