xref: /dokuwiki/inc/template.php (revision 6709e843f0cb599daacc2afa793a3c17226a28a1)
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 * Available Buttons are
443 *
444 *  edit        - edit/create/show/draft button
445 *  history     - old revisions
446 *  recent      - recent changes
447 *  login       - login/logout button - if ACL enabled
448 *  profile     - user profile button (if logged in)
449 *  index       - The index
450 *  admin       - admin page - if enough rights
451 *  top         - a back to top button
452 *  back        - a back to parent button - if available
453 *  backlink    - links to the list of backlinks
454 *  subscription- subscribe/unsubscribe button
455 *
456 * @author Andreas Gohr <andi@splitbrain.org>
457 * @author Matthias Grimm <matthiasgrimm@users.sourceforge.net>
458 */
459function tpl_button($type,$return=false){
460    global $ACT;
461    global $ID;
462    global $REV;
463    global $NS;
464    global $INFO;
465    global $conf;
466    global $auth;
467
468    // check disabled actions and fix the badly named ones
469    $ctype = $type;
470    if($type == 'history') $ctype='revisions';
471    if(!actionOK($ctype)) return false;
472
473    $out = '';
474    switch($type){
475        case 'edit':
476            // most complicated type - we need to decide on current action
477            if($ACT == 'show' || $ACT == 'search'){
478                if($INFO['writable']){
479                    if(!empty($INFO['draft'])){
480                        $out .= html_btn('draft',$ID,'e',array('do' => 'draft'),'post');
481                    }else{
482                        if($INFO['exists']){
483                            $out .= html_btn('edit',$ID,'e',array('do' => 'edit','rev' => $REV),'post');
484                        }else{
485                            $out .= html_btn('create',$ID,'e',array('do' => 'edit','rev' => $REV),'post');
486                        }
487                    }
488                }else{
489                    if(!actionOK('source')) return false; //pseudo action
490                    $out .= html_btn('source',$ID,'v',array('do' => 'edit','rev' => $REV),'post');
491                }
492            }else{
493                $out .= html_btn('show',$ID,'v',array('do' => 'show'));
494            }
495            break;
496        case 'history':
497            if(actionOK('revisions'))
498                $out .= html_btn('revs',$ID,'o',array('do' => 'revisions'));
499            break;
500        case 'recent':
501            if(actionOK('recent'))
502                $out .= html_btn('recent',$ID,'r',array('do' => 'recent'));
503            break;
504        case 'index':
505            if(actionOK('index'))
506                $out .= html_btn('index',$ID,'x',array('do' => 'index'));
507            break;
508        case 'back':
509            if ($parent = tpl_getparent($ID)) {
510                $out .= html_btn('back',$parent,'b',array('do' => 'show'));
511            }
512            break;
513        case 'top':
514            $out .= html_topbtn();
515            break;
516        case 'login':
517            if($conf['useacl'] && $auth){
518                if(isset($_SERVER['REMOTE_USER'])){
519                    $out .= html_btn('logout',$ID,'',array('do' => 'logout', 'sectok' => getSecurityToken()));
520                }else{
521                    $out .= html_btn('login',$ID,'',array('do' => 'login', 'sectok' => getSecurityToken()));
522                }
523            }
524            break;
525        case 'admin':
526            if($INFO['ismanager']){
527                $out .= html_btn('admin',$ID,'',array('do' => 'admin'));
528            }
529            break;
530        case 'revert':
531            if($INFO['ismanager'] && $REV && $INFO['writable'] && actionOK('revert')){
532                $out .= html_btn('revert',$ID,'',array('do' => 'revert', 'rev' => $REV, 'sectok' => getSecurityToken()));
533            }
534            break;
535        case 'subscribe':
536            if ($conf['useacl'] && $auth && $ACT == 'show' &&
537                    $conf['subscribers'] && isset($_SERVER['REMOTE_USER']) &&
538                    actionOK('subscribe')) {
539                $out .= html_btn('subscribe',$ID,'',array('do' => 'subscribe',));
540            }
541            break;
542        case 'backlink':
543            if(actionOK('backlink'))
544                $out .= html_btn('backlink',$ID,'',array('do' => 'backlink'));
545            break;
546        case 'profile':
547            if($conf['useacl'] && isset($_SERVER['REMOTE_USER']) && $auth &&
548                    $auth->canDo('Profile') && ($ACT!='profile')){
549                $out .= html_btn('profile',$ID,'',array('do' => 'profile'));
550            }
551            break;
552        default:
553            $out .= '[unknown button type]';
554            break;
555    }
556    if ($return) return $out;
557    print $out;
558    return $out ? true : false;
559}
560
561/**
562 * Like the action buttons but links
563 *
564 * Available links are
565 *
566 *  edit    - edit/create/show link
567 *  history - old revisions
568 *  recent  - recent changes
569 *  login   - login/logout link - if ACL enabled
570 *  profile - user profile link (if logged in)
571 *  index   - The index
572 *  admin   - admin page - if enough rights
573 *  top     - a back to top link
574 *  back    - a back to parent link - if available
575 *  backlink - links to the list of backlinks
576 *  subscribe/subscription - subscribe/unsubscribe link
577 *
578 * @author Andreas Gohr <andi@splitbrain.org>
579 * @author Matthias Grimm <matthiasgrimm@users.sourceforge.net>
580 * @see    tpl_button
581 */
582function tpl_actionlink($type,$pre='',$suf='',$inner='',$return=false){
583    global $ID;
584    global $INFO;
585    global $REV;
586    global $ACT;
587    global $conf;
588    global $lang;
589    global $auth;
590
591    // check disabled actions and fix the badly named ones
592    $ctype = $type;
593    if($type == 'history') $ctype='revisions';
594    if(!actionOK($ctype)) return false;
595
596    $out = '';
597    $id = $ID;
598    $query = array();
599    $build_link = true;
600    $more = '';
601    switch($type){
602        case 'edit':
603            // most complicated type - we need to decide on current action
604            if($ACT == 'show' || $ACT == 'search'){
605                if($INFO['writable']){
606                    $more = 'class="action edit" accesskey="e"';
607                    if(!empty($INFO['draft'])) {
608                        $type = 'draft';
609                    } else {
610                        $query = array('do' => 'edit', 'rev' => $REV);
611                        if($INFO['exists']){
612                            $type = 'edit';
613                        }else{
614                            $more = 'class="action create" accesskey="e"';
615                            $type = 'create';
616                        }
617                    }
618                }else{
619                    if(actionOK('source')) { //pseudo action
620                        $query = array('do' => 'edit', 'rev' => $REV);
621                        $type = 'source';
622                        $more = 'class="action source" accesskey="v"';
623                    }
624                }
625            }else{
626                $query = '';
627                $type = 'show';
628                $more = 'class="action show" accesskey="v"';
629            }
630            break;
631        case 'history':
632            $query = array('do' => 'revisions');
633            $type = 'revs';
634            $more = 'class="action revisions" accesskey="o"';
635            break;
636        case 'recent':
637            $more = 'class="action recent" accesskey="r"';
638            break;
639        case 'index':
640            $more = 'class="action index" accesskey="x"';
641            break;
642        case 'top':
643            $build_link = false;
644            $out = '<a href="#dokuwiki__top" class="action top" accesskey="x">'.
645                $pre.(($inner)?$inner:$lang['btn_top']).$suf.'</a>';
646            break;
647        case 'back':
648            if ($parent = tpl_getparent($ID)) {
649                $id = $parent;
650                $query = '';
651                $more = 'class="action back" accesskey="b"';
652            }
653            break;
654        case 'login':
655            if($conf['useacl'] && $auth){
656                $query = array('sectok' => getSecurityToken());
657                if($_SERVER['REMOTE_USER']){
658                    $type = 'logout';
659                    $more = 'class="action logout"';
660                }else{
661                    $more = 'class="action login"';
662                }
663            }
664            break;
665        case 'admin':
666            if($INFO['ismanager']){
667                $more = 'class="action admin"';
668            }
669            break;
670        case 'revert':
671            if($INFO['ismanager'] && $REV && $INFO['writable']) {
672                $query = array('rev' => $REV, 'sectok' => getSecurityToken());
673                $more = 'class="action revert"';
674            }
675            break;
676        case 'subscription':
677            $type = 'subscribe';
678        case 'subscribe':
679            if($conf['useacl'] && $auth && $ACT == 'show' && $conf['subscribers']) {
680                if($_SERVER['REMOTE_USER']){
681                    $more = 'class="action subscribe"';
682                }
683            }
684            break;
685        case 'backlink':
686            $more = 'class="action backlink"';
687            break;
688        case 'profile':
689            if($conf['useacl'] && $auth && $_SERVER['REMOTE_USER'] &&
690                    $auth->canDo('Profile') && ($ACT!='profile')){
691                $more = 'class="action profile"';
692            }
693            break;
694        default:
695            $build_link = false;
696            $out = '[unknown link type]';
697            break;
698    }
699    if ($build_link) {
700        if (is_array($query) && !isset($query['do'])) {
701            $query['do'] = $type;
702        }
703        $out = tpl_link(wl($id, $query),
704                $pre.(($inner)?$inner:$lang['btn_' . $type]).$suf,
705                $more . ' rel="nofollow" title="' . hsc($lang['btn_' . $type]) . '"', 1);
706    }
707    if ($return) return $out;
708    print $out;
709    return $out ? true : false;
710}
711
712/**
713 * Wrapper around tpl_button() and tpl_actionlink()
714 *
715 * @author Anika Henke <anika@selfthinker.org>
716 */
717function tpl_action($type,$link=0,$wrapper=false,$return=false,$pre='',$suf='',$inner='') {
718    $out = '';
719    if ($link) $out .= tpl_actionlink($type,$pre,$suf,$inner,1);
720    else $out .= tpl_button($type,1);
721    if ($out && $wrapper) $out = "<$wrapper>$out</$wrapper>";
722
723    if ($return) return $out;
724    print $out;
725    return $out ? true : false;
726}
727
728/**
729 * Print the search form
730 *
731 * If the first parameter is given a div with the ID 'qsearch_out' will
732 * be added which instructs the ajax pagequicksearch to kick in and place
733 * its output into this div. The second parameter controls the propritary
734 * attribute autocomplete. If set to false this attribute will be set with an
735 * value of "off" to instruct the browser to disable it's own built in
736 * autocompletion feature (MSIE and Firefox)
737 *
738 * @author Andreas Gohr <andi@splitbrain.org>
739 */
740function tpl_searchform($ajax=true,$autocomplete=true){
741    global $lang;
742    global $ACT;
743    global $QUERY;
744
745    // don't print the search form if search action has been disabled
746    if (!actionOk('search')) return false;
747
748    print '<form action="'.wl().'" accept-charset="utf-8" class="search" id="dw__search"><div class="no">';
749    print '<input type="hidden" name="do" value="search" />';
750    print '<input type="text" ';
751    if($ACT == 'search') print 'value="'.htmlspecialchars($QUERY).'" ';
752    if(!$autocomplete) print 'autocomplete="off" ';
753    print 'id="qsearch__in" accesskey="f" name="id" class="edit" title="[F]" />';
754    print '<input type="submit" value="'.$lang['btn_search'].'" class="button" title="'.$lang['btn_search'].'" />';
755    if($ajax) print '<div id="qsearch__out" class="ajax_qsearch JSpopup"></div>';
756    print '</div></form>';
757    return true;
758}
759
760/**
761 * Print the breadcrumbs trace
762 *
763 * @author Andreas Gohr <andi@splitbrain.org>
764 */
765function tpl_breadcrumbs($sep='&raquo;'){
766    global $lang;
767    global $conf;
768
769    //check if enabled
770    if(!$conf['breadcrumbs']) return false;
771
772    $crumbs = breadcrumbs(); //setup crumb trace
773
774    //reverse crumborder in right-to-left mode, add RLM character to fix heb/eng display mixups
775    if($lang['direction'] == 'rtl') {
776        $crumbs = array_reverse($crumbs,true);
777        $crumbs_sep = ' &#8207;<span class="bcsep">'.$sep.'</span>&#8207; ';
778    } else {
779        $crumbs_sep = ' <span class="bcsep">'.$sep.'</span> ';
780    }
781
782    //render crumbs, highlight the last one
783    print '<span class="bchead">'.$lang['breadcrumb'].':</span>';
784    $last = count($crumbs);
785    $i = 0;
786    foreach ($crumbs as $id => $name){
787        $i++;
788        echo $crumbs_sep;
789        if ($i == $last) print '<span class="curid">';
790        tpl_link(wl($id),hsc($name),'class="breadcrumbs" title="'.$id.'"');
791        if ($i == $last) print '</span>';
792    }
793    return true;
794}
795
796/**
797 * Hierarchical breadcrumbs
798 *
799 * This code was suggested as replacement for the usual breadcrumbs.
800 * It only makes sense with a deep site structure.
801 *
802 * @author Andreas Gohr <andi@splitbrain.org>
803 * @author Nigel McNie <oracle.shinoda@gmail.com>
804 * @author Sean Coates <sean@caedmon.net>
805 * @author <fredrik@averpil.com>
806 * @todo   May behave strangely in RTL languages
807 */
808function tpl_youarehere($sep=' &raquo; '){
809    global $conf;
810    global $ID;
811    global $lang;
812
813    // check if enabled
814    if(!$conf['youarehere']) return false;
815
816    $parts = explode(':', $ID);
817    $count = count($parts);
818
819    if($GLOBALS['ACT'] == 'search')
820    {
821        $parts = array($conf['start']);
822        $count = 1;
823    }
824
825    echo '<span class="bchead">'.$lang['youarehere'].': </span>';
826
827    // always print the startpage
828    $title = useHeading('navigation') ? p_get_first_heading($conf['start']) : $conf['start'];
829    if(!$title) $title = $conf['start'];
830    tpl_link(wl($conf['start']),hsc($title),'title="'.$conf['start'].'"');
831
832    // print intermediate namespace links
833    $part = '';
834    for($i=0; $i<$count - 1; $i++){
835        $part .= $parts[$i].':';
836        $page = $part;
837        resolve_pageid('',$page,$exists);
838        if ($page == $conf['start']) continue; // Skip startpage
839
840        // output
841        echo $sep;
842        if($exists){
843            $title = useHeading('navigation') ? p_get_first_heading($page) : $parts[$i];
844            tpl_link(wl($page),hsc($title),'title="'.$page.'"');
845        }else{
846            tpl_link(wl($page),$parts[$i],'title="'.$page.'" class="wikilink2" rel="nofollow"');
847        }
848    }
849
850    // print current page, skipping start page, skipping for namespace index
851    if(isset($page) && $page==$part.$parts[$i]) return;
852    $page = $part.$parts[$i];
853    if($page == $conf['start']) return;
854    echo $sep;
855    if(page_exists($page)){
856        $title = useHeading('navigation') ? p_get_first_heading($page) : $parts[$i];
857        tpl_link(wl($page),hsc($title),'title="'.$page.'"');
858    }else{
859        tpl_link(wl($page),$parts[$i],'title="'.$page.'" class="wikilink2" rel="nofollow"');
860    }
861    return true;
862}
863
864/**
865 * Print info if the user is logged in
866 * and show full name in that case
867 *
868 * Could be enhanced with a profile link in future?
869 *
870 * @author Andreas Gohr <andi@splitbrain.org>
871 */
872function tpl_userinfo(){
873    global $lang;
874    global $INFO;
875    if(isset($_SERVER['REMOTE_USER'])){
876        print $lang['loggedinas'].': '.$INFO['userinfo']['name'].' ('.$_SERVER['REMOTE_USER'].')';
877                return true;
878                }
879                return false;
880                }
881
882                /**
883                 * Print some info about the current page
884                 *
885                 * @author Andreas Gohr <andi@splitbrain.org>
886                 */
887                function tpl_pageinfo($ret=false){
888                global $conf;
889                global $lang;
890                global $INFO;
891                global $ID;
892
893                // return if we are not allowed to view the page
894                if (!auth_quickaclcheck($ID)) { return false; }
895
896                // prepare date and path
897                $fn = $INFO['filepath'];
898                if(!$conf['fullpath']){
899                    if($INFO['rev']){
900                        $fn = str_replace(fullpath($conf['olddir']).'/','',$fn);
901                    }else{
902                        $fn = str_replace(fullpath($conf['datadir']).'/','',$fn);
903                    }
904                }
905                $fn = utf8_decodeFN($fn);
906                $date = dformat($INFO['lastmod']);
907
908                // print it
909                if($INFO['exists']){
910                    $out = '';
911                    $out .= $fn;
912                    $out .= ' &middot; ';
913                    $out .= $lang['lastmod'];
914                    $out .= ': ';
915                    $out .= $date;
916                    if($INFO['editor']){
917                        $out .= ' '.$lang['by'].' ';
918                        $out .= editorinfo($INFO['editor']);
919                    }else{
920                        $out .= ' ('.$lang['external_edit'].')';
921                                }
922                                if($INFO['locked']){
923                                $out .= ' &middot; ';
924                                $out .= $lang['lockedby'];
925                                $out .= ': ';
926                                $out .= editorinfo($INFO['locked']);
927                                }
928                                if($ret){
929                                return $out;
930                                }else{
931                                echo $out;
932                                return true;
933                                }
934                                }
935                                return false;
936                                }
937
938                                /**
939                                 * Prints or returns the name of the given page (current one if none given).
940                                 *
941                                 * If useheading is enabled this will use the first headline else
942                                 * the given ID is used.
943                                 *
944                                 * @author Andreas Gohr <andi@splitbrain.org>
945                                 */
946function tpl_pagetitle($id=null, $ret=false){
947    global $conf;
948    if(is_null($id)){
949        global $ID;
950        $id = $ID;
951    }
952
953    $name = $id;
954    if (useHeading('navigation')) {
955        $title = p_get_first_heading($id);
956        if ($title) $name = $title;
957    }
958
959    if ($ret) {
960        return hsc($name);
961    } else {
962        print hsc($name);
963        return true;
964    }
965}
966
967/**
968 * Returns the requested EXIF/IPTC tag from the current image
969 *
970 * If $tags is an array all given tags are tried until a
971 * value is found. If no value is found $alt is returned.
972 *
973 * Which texts are known is defined in the functions _exifTagNames
974 * and _iptcTagNames() in inc/jpeg.php (You need to prepend IPTC
975 * to the names of the latter one)
976 *
977 * Only allowed in: detail.php
978 *
979 * @author Andreas Gohr <andi@splitbrain.org>
980 */
981function tpl_img_getTag($tags,$alt='',$src=null){
982    // Init Exif Reader
983    global $SRC;
984
985    if(is_null($src)) $src = $SRC;
986
987    static $meta = null;
988    if(is_null($meta)) $meta = new JpegMeta($src);
989    if($meta === false) return $alt;
990    $info = $meta->getField($tags);
991    if($info == false) return $alt;
992    return $info;
993}
994
995/**
996 * Prints the image with a link to the full sized version
997 *
998 * Only allowed in: detail.php
999 */
1000function tpl_img($maxwidth=0,$maxheight=0){
1001    global $IMG;
1002    $w = tpl_img_getTag('File.Width');
1003    $h = tpl_img_getTag('File.Height');
1004
1005    //resize to given max values
1006    $ratio = 1;
1007    if($w >= $h){
1008        if($maxwidth && $w >= $maxwidth){
1009            $ratio = $maxwidth/$w;
1010        }elseif($maxheight && $h > $maxheight){
1011            $ratio = $maxheight/$h;
1012        }
1013    }else{
1014        if($maxheight && $h >= $maxheight){
1015            $ratio = $maxheight/$h;
1016        }elseif($maxwidth && $w > $maxwidth){
1017            $ratio = $maxwidth/$w;
1018        }
1019    }
1020    if($ratio){
1021        $w = floor($ratio*$w);
1022        $h = floor($ratio*$h);
1023    }
1024
1025    //prepare URLs
1026    $url=ml($IMG,array('cache'=>$_REQUEST['cache']));
1027    $src=ml($IMG,array('cache'=>$_REQUEST['cache'],'w'=>$w,'h'=>$h));
1028
1029    //prepare attributes
1030    $alt=tpl_img_getTag('Simple.Title');
1031    $p = array();
1032    if($w) $p['width']  = $w;
1033    if($h) $p['height'] = $h;
1034    $p['class']  = 'img_detail';
1035    if($alt){
1036        $p['alt']   = $alt;
1037        $p['title'] = $alt;
1038    }else{
1039        $p['alt'] = '';
1040    }
1041    $p = buildAttributes($p);
1042
1043    print '<a href="'.$url.'">';
1044    print '<img src="'.$src.'" '.$p.'/>';
1045    print '</a>';
1046    return true;
1047}
1048
1049/**
1050 * This function inserts a 1x1 pixel gif which in reality
1051 * is the indexer function.
1052 *
1053 * Should be called somewhere at the very end of the main.php
1054 * template
1055 */
1056function tpl_indexerWebBug(){
1057    global $ID;
1058    global $INFO;
1059    if(!$INFO['exists']) return false;
1060
1061    if(isHiddenPage($ID)) return false; //no need to index hidden pages
1062
1063    $p = array();
1064    $p['src']    = DOKU_BASE.'lib/exe/indexer.php?id='.rawurlencode($ID).
1065        '&'.time();
1066    $p['width']  = 1;
1067    $p['height'] = 1;
1068    $p['alt']    = '';
1069    $att = buildAttributes($p);
1070    print "<img $att />";
1071    return true;
1072}
1073
1074// configuration methods
1075/**
1076 * tpl_getConf($id)
1077 *
1078 * use this function to access template configuration variables
1079 */
1080function tpl_getConf($id){
1081    global $conf;
1082    global $tpl_configloaded;
1083
1084    $tpl = $conf['template'];
1085
1086    if (!$tpl_configloaded){
1087        $tconf = tpl_loadConfig();
1088        if ($tconf !== false){
1089            foreach ($tconf as $key => $value){
1090                if (isset($conf['tpl'][$tpl][$key])) continue;
1091                $conf['tpl'][$tpl][$key] = $value;
1092            }
1093            $tpl_configloaded = true;
1094        }
1095    }
1096
1097    return $conf['tpl'][$tpl][$id];
1098}
1099
1100/**
1101 * tpl_loadConfig()
1102 * reads all template configuration variables
1103 * this function is automatically called by tpl_getConf()
1104 */
1105function tpl_loadConfig(){
1106
1107    $file = DOKU_TPLINC.'/conf/default.php';
1108    $conf = array();
1109
1110    if (!@file_exists($file)) return false;
1111
1112    // load default config file
1113    include($file);
1114
1115    return $conf;
1116}
1117
1118/**
1119 * prints the "main content" in the mediamanger popup
1120 *
1121 * Depending on the user's actions this may be a list of
1122 * files in a namespace, the meta editing dialog or
1123 * a message of referencing pages
1124 *
1125 * Only allowed in mediamanager.php
1126 *
1127 * @triggers MEDIAMANAGER_CONTENT_OUTPUT
1128 * @param bool $fromajax - set true when calling this function via ajax
1129 * @author Andreas Gohr <andi@splitbrain.org>
1130 */
1131function tpl_mediaContent($fromajax=false){
1132    global $IMG;
1133    global $AUTH;
1134    global $INUSE;
1135    global $NS;
1136    global $JUMPTO;
1137
1138    if(is_array($_REQUEST['do'])){
1139        $do = array_shift(array_keys($_REQUEST['do']));
1140    }else{
1141        $do = $_REQUEST['do'];
1142    }
1143    if(in_array($do,array('save','cancel'))) $do = '';
1144
1145    if(!$do){
1146        if($_REQUEST['edit']){
1147            $do = 'metaform';
1148        }elseif(is_array($INUSE)){
1149            $do = 'filesinuse';
1150        }else{
1151            $do = 'filelist';
1152        }
1153    }
1154
1155    // output the content pane, wrapped in an event.
1156    if(!$fromajax) ptln('<div id="media__content">');
1157    $data = array( 'do' => $do);
1158    $evt = new Doku_Event('MEDIAMANAGER_CONTENT_OUTPUT', $data);
1159    if ($evt->advise_before()) {
1160        $do = $data['do'];
1161        if($do == 'metaform'){
1162            media_metaform($IMG,$AUTH);
1163        }elseif($do == 'filesinuse'){
1164            media_filesinuse($INUSE,$IMG);
1165        }elseif($do == 'filelist'){
1166            media_filelist($NS,$AUTH,$JUMPTO);
1167        }elseif($do == 'searchlist'){
1168            media_searchlist($_REQUEST['q'],$NS,$AUTH);
1169        }else{
1170            msg('Unknown action '.hsc($do),-1);
1171        }
1172    }
1173    $evt->advise_after();
1174    unset($evt);
1175    if(!$fromajax) ptln('</div>');
1176
1177}
1178
1179/**
1180 * prints the namespace tree in the mediamanger popup
1181 *
1182 * Only allowed in mediamanager.php
1183 *
1184 * @author Andreas Gohr <andi@splitbrain.org>
1185 */
1186function tpl_mediaTree(){
1187    global $NS;
1188
1189    ptln('<div id="media__tree">');
1190    media_nstree($NS);
1191    ptln('</div>');
1192}
1193
1194
1195/**
1196 * Print a dropdown menu with all DokuWiki actions
1197 *
1198 * Note: this will not use any pretty URLs
1199 *
1200 * @author Andreas Gohr <andi@splitbrain.org>
1201 */
1202function tpl_actiondropdown($empty='',$button='&gt;'){
1203    global $ID;
1204    global $INFO;
1205    global $REV;
1206    global $ACT;
1207    global $conf;
1208    global $lang;
1209    global $auth;
1210
1211    echo '<form method="post" accept-charset="utf-8">'; #FIXME action
1212        echo '<input type="hidden" name="id" value="'.$ID.'" />';
1213    if($REV) echo '<input type="hidden" name="rev" value="'.$REV.'" />';
1214    echo '<input type="hidden" name="sectok" value="'.getSecurityToken().'" />';
1215
1216    echo '<select name="do" id="action__selector" class="edit">';
1217    echo '<option value="">'.$empty.'</option>';
1218
1219    echo '<optgroup label=" &mdash; ">';
1220    // 'edit' - most complicated type, we need to decide on current action
1221    if($ACT == 'show' || $ACT == 'search'){
1222        if($INFO['writable']){
1223            if(!empty($INFO['draft'])) {
1224                echo '<option value="edit">'.$lang['btn_draft'].'</option>';
1225            } else {
1226                if($INFO['exists']){
1227                    echo '<option value="edit">'.$lang['btn_edit'].'</option>';
1228                }else{
1229                    echo '<option value="edit">'.$lang['btn_create'].'</option>';
1230                }
1231            }
1232        }else if(actionOK('source')) { //pseudo action
1233            echo '<option value="edit">'.$lang['btn_source'].'</option>';
1234        }
1235    }else{
1236        echo '<option value="show">'.$lang['btn_show'].'</option>';
1237    }
1238
1239    echo '<option value="revisions">'.$lang['btn_revs'].'</option>';
1240    if($INFO['ismanager'] && $REV && $INFO['writable'] && actionOK('revert')){
1241        echo '<option value="revert">'.$lang['btn_revert'].'</option>';
1242    }
1243    echo '<option value="backlink">'.$lang['btn_backlink'].'</option>';
1244    echo '</optgroup>';
1245
1246    echo '<optgroup label=" &mdash; ">';
1247    echo '<option value="recent">'.$lang['btn_recent'].'</option>';
1248    echo '<option value="index">'.$lang['btn_index'].'</option>';
1249    echo '</optgroup>';
1250
1251    echo '<optgroup label=" &mdash; ">';
1252    if($conf['useacl'] && $auth){
1253        if($_SERVER['REMOTE_USER']){
1254            echo '<option value="logout">'.$lang['btn_logout'].'</option>';
1255        }else{
1256            echo '<option value="login">'.$lang['btn_login'].'</option>';
1257        }
1258    }
1259
1260    if($conf['useacl'] && $auth && $_SERVER['REMOTE_USER'] &&
1261            $auth->canDo('Profile') && ($ACT!='profile')){
1262        echo '<option value="profile">'.$lang['btn_profile'].'</option>';
1263    }
1264
1265    if($conf['useacl'] && $auth && $ACT == 'show' && $conf['subscribers']){
1266        if($_SERVER['REMOTE_USER']){
1267            echo '<option value="subscribe">'.$lang['btn_subscribe'].'</option>';
1268        }
1269    }
1270
1271    if($INFO['ismanager']){
1272        echo '<option value="admin">'.$lang['btn_admin'].'</option>';
1273    }
1274    echo '</optgroup>';
1275
1276    echo '</select>';
1277    echo '<input type="submit" value="'.$button.'" id="action__selectorbtn" />';
1278    echo '</form>';
1279}
1280
1281/**
1282 * Print a informational line about the used license
1283 *
1284 * @author Andreas Gohr <andi@splitbrain.org>
1285 * @param  string $img    - print image? (|button|badge)
1286 * @param  bool   $return - when true don't print, but return HTML
1287 */
1288function tpl_license($img='badge',$imgonly=false,$return=false){
1289    global $license;
1290    global $conf;
1291    global $lang;
1292    if(!$conf['license']) return '';
1293    if(!is_array($license[$conf['license']])) return '';
1294    $lic = $license[$conf['license']];
1295
1296    $out  = '<div class="license">';
1297    if($img){
1298        $src = license_img($img);
1299        if($src){
1300            $out .= '<a href="'.$lic['url'].'" rel="license"';
1301            if($conf['target']['extern']) $out .= ' target="'.$conf['target']['extern'].'"';
1302            $out .= '><img src="'.DOKU_BASE.$src.'" class="medialeft lic'.$img.'" alt="'.$lic['name'].'" /></a> ';
1303        }
1304    }
1305    if(!$imgonly) {
1306        $out .= $lang['license'];
1307        $out .= '<a href="'.$lic['url'].'" rel="license" class="urlextern"';
1308        if($conf['target']['extern']) $out .= ' target="'.$conf['target']['extern'].'"';
1309        $out .= '>'.$lic['name'].'</a>';
1310    }
1311    $out .= '</div>';
1312
1313    if($return) return $out;
1314    echo $out;
1315}
1316
1317
1318/**
1319 * Includes the rendered XHTML of a given page
1320 *
1321 * This function is useful to populate sidebars or similar features in a
1322 * template
1323 */
1324function tpl_include_page($pageid,$print=true){
1325    global $ID;
1326    $oldid = $ID;
1327    $html = p_wiki_xhtml($pageid,'',false);
1328    $ID = $oldid;
1329
1330    if(!$print) return $html;
1331    echo $html;
1332}
1333
1334/**
1335 * Display the subscribe form
1336 *
1337 * @author Adrian Lang <lang@cosmocode.de>
1338 */
1339function tpl_subscribe() {
1340    global $INFO;
1341    global $ID;
1342    global $lang;
1343    global $conf;
1344
1345    echo p_locale_xhtml('subscr_form');
1346    echo '<h2>' . $lang['subscr_m_current_header'] . '</h2>';
1347    echo '<div class="level2">';
1348    if ($INFO['subscribed'] === false) {
1349        echo '<p>' . $lang['subscr_m_not_subscribed'] . '</p>';
1350    } else {
1351        echo '<ul>';
1352        foreach($INFO['subscribed'] as $sub) {
1353            echo '<li><div class="li">';
1354            if ($sub['target'] !== $ID) {
1355                echo '<code class="ns">'.hsc(prettyprint_id($sub['target'])).'</code>';
1356            } else {
1357                echo '<code class="page">'.hsc(prettyprint_id($sub['target'])).'</code>';
1358            }
1359            $sstl = $lang['subscr_style_'.$sub['style']];
1360            if(!$sstl) $sstl = hsc($sub['style']);
1361            echo ' ('.$sstl.') ';
1362
1363            echo '<a href="' . wl($ID,
1364                                  array('do'=>'subscribe',
1365                                        'sub_target'=>$sub['target'],
1366                                        'sub_style'=>$sub['style'],
1367                                        'sub_action'=>'unsubscribe',
1368                                        'sectok' => getSecurityToken())) .
1369                 '" class="unsubscribe">'.$lang['subscr_m_unsubscribe'] .
1370                 '</a></div></li>';
1371        }
1372        echo '</ul>';
1373    }
1374    echo '</div>';
1375
1376    // Add new subscription form
1377    echo '<h2>' . $lang['subscr_m_new_header'] . '</h2>';
1378    echo '<div class="level2">';
1379    $ns = getNS($ID).':';
1380    $targets = array(
1381            $ID => '<code class="page">'.prettyprint_id($ID).'</code>',
1382            $ns => '<code class="ns">'.prettyprint_id($ns).'</code>',
1383            );
1384    $stime_days = $conf['subscribe_time']/60/60/24;
1385    $styles = array(
1386            'every'  => $lang['subscr_style_every'],
1387            'digest' => sprintf($lang['subscr_style_digest'], $stime_days),
1388            'list' => sprintf($lang['subscr_style_list'], $stime_days),
1389            );
1390
1391    $form = new Doku_Form(array('id' => 'subscribe__form'));
1392    $form->startFieldset($lang['subscr_m_subscribe']);
1393    $form->addRadioSet('sub_target', $targets);
1394    $form->startFieldset($lang['subscr_m_receive']);
1395    $form->addRadioSet('sub_style', $styles);
1396    $form->addHidden('sub_action', 'subscribe');
1397    $form->addHidden('do', 'subscribe');
1398    $form->addHidden('id', $ID);
1399    $form->endFieldset();
1400    $form->addElement(form_makeButton('submit', 'subscribe', $lang['subscr_m_subscribe']));
1401    html_form('SUBSCRIBE', $form);
1402    echo '</div>';
1403}
1404
1405/**
1406 * Tries to send already created content right to the browser
1407 *
1408 * Wraps around ob_flush() and flush()
1409 *
1410 * @author Andreas Gohr <andi@splitbrain.org>
1411 */
1412function tpl_flush(){
1413    ob_flush();
1414    flush();
1415}
1416
1417
1418//Setup VIM: ex: et ts=4 enc=utf-8 :
1419
1420