xref: /dokuwiki/inc/template.php (revision 734a059e6df6fbc3a8750a1672ac5fb68255e123)
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 'preview':
64      html_edit($TEXT);
65      html_show($TEXT);
66      break;
67    case 'recover':
68      html_edit($TEXT);
69      break;
70    case 'edit':
71      html_edit();
72      break;
73    case 'draft':
74      html_draft();
75      break;
76    case 'wordblock':
77      html_edit($TEXT,'wordblock');
78      break;
79    case 'search':
80      html_search();
81      break;
82    case 'revisions':
83      $first = is_numeric($_REQUEST['first']) ? intval($_REQUEST['first']) : 0;
84      html_revisions($first);
85      break;
86    case 'diff':
87      html_diff();
88      break;
89    case 'recent':
90      if (is_array($_REQUEST['first'])) {
91        $_REQUEST['first'] = array_keys($_REQUEST['first']);
92        $_REQUEST['first'] = $_REQUEST['first'][0];
93      }
94      $first = is_numeric($_REQUEST['first']) ? intval($_REQUEST['first']) : 0;
95      html_recent($first);
96      break;
97    case 'index':
98      html_index($IDX); #FIXME can this be pulled from globals? is it sanitized correctly?
99      break;
100    case 'backlink':
101      html_backlinks();
102      break;
103    case 'conflict':
104      html_conflict(con($PRE,$TEXT,$SUF),$SUM);
105      html_diff(con($PRE,$TEXT,$SUF),false);
106      break;
107    case 'locked':
108      html_locked();
109      html_edit();
110      break;
111    case 'login':
112      html_login();
113      break;
114    case 'register':
115      html_register();
116      break;
117    case 'resendpwd':
118      html_resendpwd();
119      break;
120    case 'denied':
121      print p_locale_xhtml('denied');
122      break;
123    case 'profile' :
124      html_updateprofile();
125      break;
126    case 'admin':
127      tpl_admin();
128      break;
129    default:
130      $evt = new Doku_Event('TPL_ACT_UNKNOWN',$ACT);
131      if ($evt->advise_before())
132        msg("Failed to handle command: ".hsc($ACT),-1);
133      $evt->advise_after();
134      unset($evt);
135      return false;
136  }
137  return true;
138}
139
140/**
141 * Places the TOC where the function is called
142 *
143 * If you use this you most probably want to call tpl_content with
144 * a false argument
145 *
146 * @author Andreas Gohr <andi@splitbrain.org>
147 */
148function tpl_toc($return=false){
149    global $TOC;
150    global $ACT;
151    global $ID;
152    global $REV;
153    global $INFO;
154    global $conf;
155    $toc = array();
156
157    if(is_array($TOC)){
158        // if a TOC was prepared in global scope, always use it
159        $toc = $TOC;
160    }elseif(($ACT == 'show' || substr($ACT,0,6) == 'export') && !$REV && $INFO['exists']){
161        // get TOC from metadata, render if neccessary
162        $meta = p_get_metadata($ID, false, true);
163        if(isset($meta['internal']['toc'])){
164            $tocok = $meta['internal']['toc'];
165        }else{
166            $tocok = true;
167        }
168        $toc   = $meta['description']['tableofcontents'];
169        if(!$tocok || !is_array($toc) || !$conf['tocminheads'] || count($toc) < $conf['tocminheads']){
170            $toc = array();
171        }
172    }elseif($ACT == 'admin'){
173        // try to load admin plugin TOC FIXME: duplicates code from tpl_admin
174        $plugin = null;
175        if (!empty($_REQUEST['page'])) {
176            $pluginlist = plugin_list('admin');
177            if (in_array($_REQUEST['page'], $pluginlist)) {
178                // attempt to load the plugin
179                $plugin =& plugin_load('admin',$_REQUEST['page']);
180            }
181        }
182        if ( ($plugin !== null) &&
183             (!$plugin->forAdminOnly() || $INFO['isadmin']) ){
184            $toc = $plugin->getTOC();
185            $TOC = $toc; // avoid later rebuild
186        }
187    }
188
189    trigger_event('TPL_TOC_RENDER', $toc, NULL, false);
190    $html = html_TOC($toc);
191    if($return) return $html;
192    echo $html;
193}
194
195/**
196 * Handle the admin page contents
197 *
198 * @author Andreas Gohr <andi@splitbrain.org>
199 */
200function tpl_admin(){
201    global $INFO;
202    global $TOC;
203
204    $plugin = null;
205    if (!empty($_REQUEST['page'])) {
206        $pluginlist = plugin_list('admin');
207
208        if (in_array($_REQUEST['page'], $pluginlist)) {
209
210          // attempt to load the plugin
211          $plugin =& plugin_load('admin',$_REQUEST['page']);
212        }
213    }
214
215    if ($plugin !== null){
216        if($plugin->forAdminOnly() && !$INFO['isadmin']){
217            msg('For admins only',-1);
218            html_admin();
219        }else{
220            if(!is_array($TOC)) $TOC = $plugin->getTOC(); //if TOC wasn't requested yet
221            if($INFO['prependTOC']) tpl_toc();
222            $plugin->html();
223        }
224    }else{
225        html_admin();
226    }
227    return true;
228}
229
230/**
231 * Print the correct HTML meta headers
232 *
233 * This has to go into the head section of your template.
234 *
235 * @triggers TPL_METAHEADER_OUTPUT
236 * @param  boolean $alt Should feeds and alternative format links be added?
237 * @author Andreas Gohr <andi@splitbrain.org>
238 */
239function tpl_metaheaders($alt=true){
240  global $ID;
241  global $REV;
242  global $INFO;
243  global $ACT;
244  global $QUERY;
245  global $lang;
246  global $conf;
247  $it=2;
248
249  // prepare the head array
250  $head = array();
251
252
253  // the usual stuff
254  $head['meta'][] = array( 'name'=>'generator', 'content'=>'DokuWiki '.getVersion() );
255  $head['link'][] = array( 'rel'=>'search', 'type'=>'application/opensearchdescription+xml',
256                           'href'=>DOKU_BASE.'lib/exe/opensearch.php', 'title'=>$conf['title'] );
257  $head['link'][] = array( 'rel'=>'start', 'href'=>DOKU_BASE );
258  if(actionOK('index')){
259    $head['link'][] = array( 'rel'=>'contents', 'href'=> wl($ID,'do=index',false,'&'),
260                           'title'=>$lang['btn_index'] );
261  }
262
263  if($alt){
264    $head['link'][] = array( 'rel'=>'alternate', 'type'=>'application/rss+xml',
265                             'title'=>'Recent Changes', 'href'=>DOKU_BASE.'feed.php');
266    $head['link'][] = array( 'rel'=>'alternate', 'type'=>'application/rss+xml',
267                             'title'=>'Current Namespace',
268                             'href'=>DOKU_BASE.'feed.php?mode=list&ns='.$INFO['namespace']);
269    if(($ACT == 'show' || $ACT == 'search') && $INFO['writable']){
270        $head['link'][] = array( 'rel'=>'edit',
271                                 'title'=>$lang['btn_edit'],
272                                 'href'=> wl($ID,'do=edit',false,'&'));
273    }
274
275    if($ACT == 'search'){
276      $head['link'][] = array( 'rel'=>'alternate', 'type'=>'application/rss+xml',
277                               'title'=>'Search Result',
278                               'href'=>DOKU_BASE.'feed.php?mode=search&q='.$QUERY);
279    }
280
281    if(actionOK('export_xhtml')){
282      $head['link'][] = array( 'rel'=>'alternate', 'type'=>'text/html', 'title'=>'Plain HTML',
283                               'href'=>exportlink($ID, 'xhtml', '', false, '&'));
284    }
285
286    if(actionOK('export_raw')){
287      $head['link'][] = array( 'rel'=>'alternate', 'type'=>'text/plain', 'title'=>'Wiki Markup',
288                               'href'=>exportlink($ID, 'raw', '', false, '&'));
289    }
290  }
291
292  // setup robot tags apropriate for different modes
293  if( ($ACT=='show' || $ACT=='export_xhtml') && !$REV){
294    if($INFO['exists']){
295      //delay indexing:
296      if((time() - $INFO['lastmod']) >= $conf['indexdelay']){
297        $head['meta'][] = array( 'name'=>'robots', 'content'=>'index,follow');
298      }else{
299        $head['meta'][] = array( 'name'=>'robots', 'content'=>'noindex,nofollow');
300      }
301    }else{
302      $head['meta'][] = array( 'name'=>'robots', 'content'=>'noindex,follow');
303    }
304  }elseif(defined('DOKU_MEDIADETAIL')){
305    $head['meta'][] = array( 'name'=>'robots', 'content'=>'index,follow');
306  }else{
307    $head['meta'][] = array( 'name'=>'robots', 'content'=>'noindex,nofollow');
308  }
309
310  // set metadata
311  if($ACT == 'show' || $ACT=='export_xhtml'){
312    // date of modification
313    if($REV){
314      $head['meta'][] = array( 'name'=>'date', 'content'=>date('Y-m-d\TH:i:sO',$REV));
315    }else{
316      $head['meta'][] = array( 'name'=>'date', 'content'=>date('Y-m-d\TH:i:sO',$INFO['lastmod']));
317    }
318
319    // keywords (explicit or implicit)
320    if(!empty($INFO['meta']['subject'])){
321      $head['meta'][] = array( 'name'=>'keywords', 'content'=>join(',',$INFO['meta']['subject']));
322    }else{
323      $head['meta'][] = array( 'name'=>'keywords', 'content'=>str_replace(':',',',$ID));
324    }
325  }
326
327  // load stylesheets
328  $head['link'][] = array('rel'=>'stylesheet', 'media'=>'all', 'type'=>'text/css',
329                          'href'=>DOKU_BASE.'lib/exe/css.php?s=all&t='.$conf['template']);
330  $head['link'][] = array('rel'=>'stylesheet', 'media'=>'screen', 'type'=>'text/css',
331                          'href'=>DOKU_BASE.'lib/exe/css.php?t='.$conf['template']);
332  $head['link'][] = array('rel'=>'stylesheet', 'media'=>'print', 'type'=>'text/css',
333                          'href'=>DOKU_BASE.'lib/exe/css.php?s=print&t='.$conf['template']);
334
335  // load javascript
336  $js_edit  = ($ACT=='edit' || $ACT=='preview' || $ACT=='recover' || $ACT=='wordblock' ) ? 1 : 0;
337  $js_write = ($INFO['writable']) ? 1 : 0;
338  if(defined('DOKU_MEDIAMANAGER')){
339    $js_edit  = 1;
340    $js_write = 0;
341  }
342  if(($js_edit && $js_write) || defined('DOKU_MEDIAMANAGER')){
343    $script = "NS='".$INFO['namespace']."';";
344    if($conf['useacl'] && $_SERVER['REMOTE_USER']){
345      require_once(DOKU_INC.'inc/toolbar.php');
346      $script .= "SIG='".toolbar_signature()."';";
347    }
348    $head['script'][] = array( 'type'=>'text/javascript', 'charset'=>'utf-8',
349                               '_data'=> $script);
350  }
351  $head['script'][] = array( 'type'=>'text/javascript', 'charset'=>'utf-8', '_data'=>'',
352                             'src'=>DOKU_BASE.'lib/exe/js.php?edit='.$js_edit.'&write='.$js_write);
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($_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 'subscribe':
531    case 'subscription':
532      if($conf['useacl'] && $auth && $ACT == 'show' && $conf['subscribers'] == 1){
533        if($_SERVER['REMOTE_USER']){
534          if($INFO['subscribed']){
535            if(actionOK('unsubscribe'))
536              $out .= html_btn('unsubscribe',$ID,'',array('do' => 'unsubscribe',));
537          } else {
538            if(actionOK('subscribe'))
539              $out .= html_btn('subscribe',$ID,'',array('do' => 'subscribe',));
540          }
541        }
542      }
543      if($type == 'subscribe') break;
544      // else: fall through for backward compatibility
545    case 'subscribens':
546      if($conf['useacl'] && $auth && $ACT == 'show' && $conf['subscribers'] == 1){
547        if($_SERVER['REMOTE_USER']){
548          if($INFO['subscribedns']){
549            if(actionOK('unsubscribens'))
550              $out .= html_btn('unsubscribens',$ID,'',array('do' => 'unsubscribens',));
551          } else {
552            if(actionOK('subscribens'))
553              $out .= html_btn('subscribens',$ID,'',array('do' => 'subscribens',));
554          }
555        }
556      }
557      break;
558    case 'backlink':
559      if(actionOK('backlink'))
560        $out .= html_btn('backlink',$ID,'',array('do' => 'backlink'));
561    case 'profile':
562      if($conf['useacl'] && $_SERVER['REMOTE_USER'] && $auth &&
563          $auth->canDo('Profile') && ($ACT!='profile')){
564        $out .= html_btn('profile',$ID,'',array('do' => 'profile'));
565      }
566      break;
567    default:
568      $out .= '[unknown button type]';
569      break;
570  }
571  if ($return) return $out;
572  print $out;
573  return $out ? true : false;
574}
575
576/**
577 * Like the action buttons but links
578 *
579 * Available links are
580 *
581 *  edit    - edit/create/show link
582 *  history - old revisions
583 *  recent  - recent changes
584 *  login   - login/logout link - if ACL enabled
585 *  profile - user profile link (if logged in)
586 *  index   - The index
587 *  admin   - admin page - if enough rights
588 *  top     - a back to top link
589 *  back    - a back to parent link - if available
590 *  backlink - links to the list of backlinks
591 *  subscribe/subscription - subscribe/unsubscribe link
592 *
593 * @author Andreas Gohr <andi@splitbrain.org>
594 * @author Matthias Grimm <matthiasgrimm@users.sourceforge.net>
595 * @see    tpl_button
596 */
597function tpl_actionlink($type,$pre='',$suf='',$inner='',$return=false){
598  global $ID;
599  global $INFO;
600  global $REV;
601  global $ACT;
602  global $conf;
603  global $lang;
604  global $auth;
605
606  // check disabled actions and fix the badly named ones
607  $ctype = $type;
608  if($type == 'history') $ctype='revisions';
609  if(!actionOK($ctype)) return false;
610
611  $out = '';
612  switch($type){
613    case 'edit':
614      #most complicated type - we need to decide on current action
615      if($ACT == 'show' || $ACT == 'search'){
616        if($INFO['writable']){
617          if(!empty($INFO['draft'])) {
618            $out .= tpl_link(wl($ID,'do=draft'),
619                       $pre.(($inner)?$inner:$lang['btn_draft']).$suf,
620                       'class="action edit" accesskey="e" rel="nofollow"',1);
621          } else {
622            if($INFO['exists']){
623              $out .= tpl_link(wl($ID,'do=edit&amp;rev='.$REV),
624                       $pre.(($inner)?$inner:$lang['btn_edit']).$suf,
625                       'class="action edit" accesskey="e" rel="nofollow"',1);
626            }else{
627              $out .= tpl_link(wl($ID,'do=edit&amp;rev='.$REV),
628                       $pre.(($inner)?$inner:$lang['btn_create']).$suf,
629                       'class="action create" accesskey="e" rel="nofollow"',1);
630            }
631          }
632        }else{
633          if(actionOK('source')) //pseudo action
634            $out .= tpl_link(wl($ID,'do=edit&amp;rev='.$REV),
635                   $pre.(($inner)?$inner:$lang['btn_source']).$suf,
636                   'class="action source" accesskey="v" rel="nofollow"',1);
637        }
638      }else{
639          $out .= tpl_link(wl($ID,'do=show'),
640                   $pre.(($inner)?$inner:$lang['btn_show']).$suf,
641                   'class="action show" accesskey="v" rel="nofollow"',1);
642      }
643      break;
644    case 'history':
645      if(actionOK('revisions'))
646        $out .= tpl_link(wl($ID,'do=revisions'),
647               $pre.(($inner)?$inner:$lang['btn_revs']).$suf,
648               'class="action revisions" accesskey="o" rel="nofollow"',1);
649      break;
650    case 'recent':
651      if(actionOK('recent'))
652        $out .= tpl_link(wl($ID,'do=recent'),
653               $pre.(($inner)?$inner:$lang['btn_recent']).$suf,
654              'class="action recent" accesskey="r" rel="nofollow"',1);
655      break;
656    case 'index':
657      if(actionOK('index'))
658        $out .= tpl_link(wl($ID,'do=index'),
659               $pre.(($inner)?$inner:$lang['btn_index']).$suf,
660              'class="action index" accesskey="x" rel="nofollow"',1);
661      break;
662    case 'top':
663      $out .= '<a href="#dokuwiki__top" class="action top" accesskey="x">'.
664            $pre.(($inner)?$inner:$lang['btn_top']).$suf.'</a>';
665      break;
666    case 'back':
667      if ($parent = tpl_getparent($ID)) {
668        $out .= tpl_link(wl($parent,'do=show'),
669        $pre.(($inner)?$inner:$lang['btn_back']).$suf,
670        'class="action back" accesskey="b" rel="nofollow"',1);
671      }
672      break;
673    case 'login':
674      if($conf['useacl'] && $auth){
675        if($_SERVER['REMOTE_USER']){
676          $out .= tpl_link(wl($ID,'do=logout&amp;sectok='.getSecurityToken()),
677                   $pre.(($inner)?$inner:$lang['btn_logout']).$suf,
678                   'class="action logout" rel="nofollow"',1);
679        }else{
680          $out .= tpl_link(wl($ID,'do=login&amp;sectok='.getSecurityToken()),
681                   $pre.(($inner)?$inner:$lang['btn_login']).$suf,
682                   'class="action login" rel="nofollow"',1);
683        }
684      }
685      break;
686    case 'admin':
687      if($INFO['ismanager']){
688        $out .= tpl_link(wl($ID,'do=admin'),
689                 $pre.(($inner)?$inner:$lang['btn_admin']).$suf,
690                 'class="action admin" rel="nofollow"',1);
691      }
692      break;
693   case 'subscribe':
694   case 'subscription':
695      if($conf['useacl'] && $auth && $ACT == 'show' && $conf['subscribers'] == 1){
696        if($_SERVER['REMOTE_USER']){
697          if($INFO['subscribed']) {
698            if(actionOK('unsubscribe'))
699              $out .= tpl_link(wl($ID,'do=unsubscribe'),
700                     $pre.(($inner)?$inner:$lang['btn_unsubscribe']).$suf,
701                     'class="action unsubscribe" rel="nofollow"',1);
702          } else {
703            if(actionOK('subscribe'))
704              $out .= tpl_link(wl($ID,'do=subscribe'),
705                     $pre.(($inner)?$inner:$lang['btn_subscribe']).$suf,
706                     'class="action subscribe" rel="nofollow"',1);
707          }
708        }
709      }
710      if($type == 'subscribe') break;
711      // else: fall through for backward compatibility
712    case 'subscribens':
713      if($conf['useacl'] && $auth && $ACT == 'show' && $conf['subscribers'] == 1){
714        if($_SERVER['REMOTE_USER']){
715          if($INFO['subscribedns']) {
716            if(actionOK('unsubscribens'))
717              $out .= tpl_link(wl($ID,'do=unsubscribens'),
718                     $pre.(($inner)?$inner:$lang['btn_unsubscribens']).$suf,
719                     'class="action unsubscribens" rel="nofollow"',1);
720          } else {
721            if(actionOK('subscribens'))
722              $out .= tpl_link(wl($ID,'do=subscribens'),
723                     $pre.(($inner)?$inner:$lang['btn_subscribens']).$suf,
724                     'class="action subscribens" rel="nofollow"',1);
725          }
726        }
727      }
728      break;
729    case 'backlink':
730      if(actionOK('backlink'))
731        $out .= tpl_link(wl($ID,'do=backlink'),
732               $pre.(($inner)?$inner:$lang['btn_backlink']).$suf,
733               'class="action backlink" rel="nofollow"',1);
734      break;
735    case 'profile':
736      if($conf['useacl'] && $auth && $_SERVER['REMOTE_USER'] &&
737         $auth->canDo('Profile') && ($ACT!='profile')){
738        $out .= tpl_link(wl($ID,'do=profile'),
739                 $pre.(($inner)?$inner:$lang['btn_profile']).$suf,
740                 'class="action profile" rel="nofollow"',1);
741      }
742      break;
743    default:
744      $out .= '[unknown link type]';
745      break;
746  }
747  if ($return) return $out;
748  print $out;
749  return $out ? true : false;
750}
751
752/**
753 * Wrapper around tpl_button() and tpl_actionlink()
754 *
755 * @author Anika Henke <anika@selfthinker.org>
756 */
757function tpl_action($type,$link=0,$wrapper=false,$return=false,$pre='',$suf='',$inner='') {
758    $out = '';
759    if ($link) $out .= tpl_actionlink($type,$pre,$suf,$inner,1);
760    else $out .= tpl_button($type,1);
761    if ($out && $wrapper) $out = "<$wrapper>$out</$wrapper>";
762
763    if ($return) return $out;
764    print $out;
765    return $out ? true : false;
766}
767
768/**
769 * Print the search form
770 *
771 * If the first parameter is given a div with the ID 'qsearch_out' will
772 * be added which instructs the ajax pagequicksearch to kick in and place
773 * its output into this div. The second parameter controls the propritary
774 * attribute autocomplete. If set to false this attribute will be set with an
775 * value of "off" to instruct the browser to disable it's own built in
776 * autocompletion feature (MSIE and Firefox)
777 *
778 * @author Andreas Gohr <andi@splitbrain.org>
779 */
780function tpl_searchform($ajax=true,$autocomplete=true){
781  global $lang;
782  global $ACT;
783
784  // don't print the search form if search action has been disabled
785  if (!actionOk('search')) return false;
786
787  print '<form action="'.wl().'" accept-charset="utf-8" class="search" id="dw__search"><div class="no">';
788  print '<input type="hidden" name="do" value="search" />';
789  print '<input type="text" ';
790  if($ACT == 'search') print 'value="'.htmlspecialchars($_REQUEST['id']).'" ';
791  if(!$autocomplete) print 'autocomplete="off" ';
792  print 'id="qsearch__in" accesskey="f" name="id" class="edit" title="[F]" />';
793  print '<input type="submit" value="'.$lang['btn_search'].'" class="button" title="'.$lang['btn_search'].'" />';
794  if($ajax) print '<div id="qsearch__out" class="ajax_qsearch JSpopup"></div>';
795  print '</div></form>';
796  return true;
797}
798
799/**
800 * Print the breadcrumbs trace
801 *
802 * @author Andreas Gohr <andi@splitbrain.org>
803 */
804function tpl_breadcrumbs($sep='&raquo;'){
805  global $lang;
806  global $conf;
807
808  //check if enabled
809  if(!$conf['breadcrumbs']) return false;
810
811  $crumbs = breadcrumbs(); //setup crumb trace
812
813  //reverse crumborder in right-to-left mode, add RLM character to fix heb/eng display mixups
814  if($lang['direction'] == 'rtl') {
815    $crumbs = array_reverse($crumbs,true);
816    $crumbs_sep = ' &#8207;<span class="bcsep">'.$sep.'</span>&#8207; ';
817  } else {
818    $crumbs_sep = ' <span class="bcsep">'.$sep.'</span> ';
819  }
820
821  //render crumbs, highlight the last one
822  print '<span class="bchead">'.$lang['breadcrumb'].':</span>';
823  $last = count($crumbs);
824  $i = 0;
825  foreach ($crumbs as $id => $name){
826    $i++;
827    echo $crumbs_sep;
828    if ($i == $last) print '<span class="curid">';
829    tpl_link(wl($id),hsc($name),'class="breadcrumbs" title="'.$id.'"');
830    if ($i == $last) print '</span>';
831  }
832  return true;
833}
834
835/**
836 * Hierarchical breadcrumbs
837 *
838 * This code was suggested as replacement for the usual breadcrumbs.
839 * It only makes sense with a deep site structure.
840 *
841 * @author Andreas Gohr <andi@splitbrain.org>
842 * @author Nigel McNie <oracle.shinoda@gmail.com>
843 * @author Sean Coates <sean@caedmon.net>
844 * @author <fredrik@averpil.com>
845 * @todo   May behave strangely in RTL languages
846 */
847function tpl_youarehere($sep=' &raquo; '){
848  global $conf;
849  global $ID;
850  global $lang;
851
852  // check if enabled
853  if(!$conf['youarehere']) return false;
854
855  $parts = explode(':', $ID);
856  $count = count($parts);
857
858  echo '<span class="bchead">'.$lang['youarehere'].': </span>';
859
860  // always print the startpage
861  $title = useHeading('navigation') ? p_get_first_heading($conf['start']) : $conf['start'];
862  if(!$title) $title = $conf['start'];
863  tpl_link(wl($conf['start']),hsc($title),'title="'.$conf['start'].'"');
864
865  // print intermediate namespace links
866  $part = '';
867  for($i=0; $i<$count - 1; $i++){
868    $part .= $parts[$i].':';
869    $page = $part;
870    resolve_pageid('',$page,$exists);
871    if ($page == $conf['start']) continue; // Skip startpage
872
873    // output
874    echo $sep;
875    if($exists){
876      $title = useHeading('navigation') ? p_get_first_heading($page) : $parts[$i];
877      tpl_link(wl($page),hsc($title),'title="'.$page.'"');
878    }else{
879      tpl_link(wl($page),$parts[$i],'title="'.$page.'" class="wikilink2" rel="nofollow"');
880    }
881  }
882
883  // print current page, skipping start page, skipping for namespace index
884  if(isset($page) && $page==$part.$parts[$i]) return;
885  $page = $part.$parts[$i];
886  if($page == $conf['start']) return;
887  echo $sep;
888  if(page_exists($page)){
889    $title = useHeading('navigation') ? p_get_first_heading($page) : $parts[$i];
890    tpl_link(wl($page),hsc($title),'title="'.$page.'"');
891  }else{
892    tpl_link(wl($page),$parts[$i],'title="'.$page.'" class="wikilink2" rel="nofollow"');
893  }
894  return true;
895}
896
897/**
898 * Print info if the user is logged in
899 * and show full name in that case
900 *
901 * Could be enhanced with a profile link in future?
902 *
903 * @author Andreas Gohr <andi@splitbrain.org>
904 */
905function tpl_userinfo(){
906  global $lang;
907  global $INFO;
908  if($_SERVER['REMOTE_USER']){
909    print $lang['loggedinas'].': '.$INFO['userinfo']['name'].' ('.$_SERVER['REMOTE_USER'].')';
910    return true;
911  }
912  return false;
913}
914
915/**
916 * Print some info about the current page
917 *
918 * @author Andreas Gohr <andi@splitbrain.org>
919 */
920function tpl_pageinfo($ret=false){
921  global $conf;
922  global $lang;
923  global $INFO;
924  global $REV;
925  global $ID;
926
927  // return if we are not allowed to view the page
928  if (!auth_quickaclcheck($ID)) { return false; }
929
930  // prepare date and path
931  $fn = $INFO['filepath'];
932  if(!$conf['fullpath']){
933    if($REV){
934      $fn = str_replace(fullpath($conf['olddir']).'/','',$fn);
935    }else{
936      $fn = str_replace(fullpath($conf['datadir']).'/','',$fn);
937    }
938  }
939  $fn = utf8_decodeFN($fn);
940  $date = strftime($conf['dformat'],$INFO['lastmod']);
941
942  // print it
943  if($INFO['exists']){
944    $out = '';
945    $out .= $fn;
946    $out .= ' &middot; ';
947    $out .= $lang['lastmod'];
948    $out .= ': ';
949    $out .= $date;
950    if($INFO['editor']){
951      $out .= ' '.$lang['by'].' ';
952      $out .= editorinfo($INFO['editor']);
953    }else{
954      $out .= ' ('.$lang['external_edit'].')';
955    }
956    if($INFO['locked']){
957      $out .= ' &middot; ';
958      $out .= $lang['lockedby'];
959      $out .= ': ';
960      $out .= editorinfo($INFO['locked']);
961    }
962    if($ret){
963        return $out;
964    }else{
965        echo $out;
966        return true;
967    }
968  }
969  return false;
970}
971
972/**
973 * Prints or returns the name of the given page (current one if none given).
974 *
975 * If useheading is enabled this will use the first headline else
976 * the given ID is used.
977 *
978 * @author Andreas Gohr <andi@splitbrain.org>
979 */
980function tpl_pagetitle($id=null, $ret=false){
981  global $conf;
982  if(is_null($id)){
983    global $ID;
984    $id = $ID;
985  }
986
987  $name = $id;
988  if (useHeading('navigation')) {
989    $title = p_get_first_heading($id);
990    if ($title) $name = $title;
991  }
992
993  if ($ret) {
994      return hsc($name);
995  } else {
996      print hsc($name);
997      return true;
998  }
999}
1000
1001/**
1002 * Returns the requested EXIF/IPTC tag from the current image
1003 *
1004 * If $tags is an array all given tags are tried until a
1005 * value is found. If no value is found $alt is returned.
1006 *
1007 * Which texts are known is defined in the functions _exifTagNames
1008 * and _iptcTagNames() in inc/jpeg.php (You need to prepend IPTC
1009 * to the names of the latter one)
1010 *
1011 * Only allowed in: detail.php
1012 *
1013 * @author Andreas Gohr <andi@splitbrain.org>
1014 */
1015function tpl_img_getTag($tags,$alt='',$src=null){
1016  // Init Exif Reader
1017  global $SRC;
1018
1019  if(is_null($src)) $src = $SRC;
1020
1021  static $meta = null;
1022  if(is_null($meta)) $meta = new JpegMeta($src);
1023  if($meta === false) return $alt;
1024  $info = $meta->getField($tags);
1025  if($info == false) return $alt;
1026  return $info;
1027}
1028
1029/**
1030 * Prints the image with a link to the full sized version
1031 *
1032 * Only allowed in: detail.php
1033 */
1034function tpl_img($maxwidth=0,$maxheight=0){
1035  global $IMG;
1036  $w = tpl_img_getTag('File.Width');
1037  $h = tpl_img_getTag('File.Height');
1038
1039  //resize to given max values
1040  $ratio = 1;
1041  if($w >= $h){
1042    if($maxwidth && $w >= $maxwidth){
1043      $ratio = $maxwidth/$w;
1044    }elseif($maxheight && $h > $maxheight){
1045      $ratio = $maxheight/$h;
1046    }
1047  }else{
1048    if($maxheight && $h >= $maxheight){
1049      $ratio = $maxheight/$h;
1050    }elseif($maxwidth && $w > $maxwidth){
1051      $ratio = $maxwidth/$w;
1052    }
1053  }
1054  if($ratio){
1055    $w = floor($ratio*$w);
1056    $h = floor($ratio*$h);
1057  }
1058
1059  //prepare URLs
1060  $url=ml($IMG,array('cache'=>$_REQUEST['cache']));
1061  $src=ml($IMG,array('cache'=>$_REQUEST['cache'],'w'=>$w,'h'=>$h));
1062
1063  //prepare attributes
1064  $alt=tpl_img_getTag('Simple.Title');
1065  $p = array();
1066  if($w) $p['width']  = $w;
1067  if($h) $p['height'] = $h;
1068         $p['class']  = 'img_detail';
1069  if($alt){
1070    $p['alt']   = $alt;
1071    $p['title'] = $alt;
1072  }else{
1073    $p['alt'] = '';
1074  }
1075  $p = buildAttributes($p);
1076
1077  print '<a href="'.$url.'">';
1078  print '<img src="'.$src.'" '.$p.'/>';
1079  print '</a>';
1080  return true;
1081}
1082
1083/**
1084 * This function inserts a 1x1 pixel gif which in reality
1085 * is the inexer function.
1086 *
1087 * Should be called somewhere at the very end of the main.php
1088 * template
1089 */
1090function tpl_indexerWebBug(){
1091  global $ID;
1092  global $INFO;
1093  if(!$INFO['exists']) return false;
1094
1095  if(isHiddenPage($ID)) return false; //no need to index hidden pages
1096
1097  $p = array();
1098  $p['src']    = DOKU_BASE.'lib/exe/indexer.php?id='.rawurlencode($ID).
1099                 '&'.time();
1100  $p['width']  = 1;
1101  $p['height'] = 1;
1102  $p['alt']    = '';
1103  $att = buildAttributes($p);
1104  print "<img $att />";
1105  return true;
1106}
1107
1108// configuration methods
1109/**
1110 * tpl_getConf($id)
1111 *
1112 * use this function to access template configuration variables
1113 */
1114function tpl_getConf($id){
1115  global $conf;
1116  global $tpl_configloaded;
1117
1118  $tpl = $conf['template'];
1119
1120  if (!$tpl_configloaded){
1121    $tconf = tpl_loadConfig();
1122    if ($tconf !== false){
1123      foreach ($tconf as $key => $value){
1124        if (isset($conf['tpl'][$tpl][$key])) continue;
1125        $conf['tpl'][$tpl][$key] = $value;
1126      }
1127      $tpl_configloaded = true;
1128    }
1129  }
1130
1131  return $conf['tpl'][$tpl][$id];
1132}
1133
1134/**
1135 * tpl_loadConfig()
1136 * reads all template configuration variables
1137 * this function is automatically called by tpl_getConf()
1138 */
1139function tpl_loadConfig(){
1140
1141  $file = DOKU_TPLINC.'/conf/default.php';
1142  $conf = array();
1143
1144  if (!@file_exists($file)) return false;
1145
1146  // load default config file
1147  include($file);
1148
1149  return $conf;
1150}
1151
1152/**
1153 * prints the "main content" in the mediamanger popup
1154 *
1155 * Depending on the user's actions this may be a list of
1156 * files in a namespace, the meta editing dialog or
1157 * a message of referencing pages
1158 *
1159 * Only allowed in mediamanager.php
1160 *
1161 * @author Andreas Gohr <andi@splitbrain.org>
1162 */
1163function tpl_mediaContent(){
1164  global $IMG;
1165  global $AUTH;
1166  global $INUSE;
1167  global $NS;
1168  global $JUMPTO;
1169
1170  ptln('<div id="media__content">');
1171  if($_REQUEST['edit']){
1172    media_metaform($IMG,$AUTH);
1173  }elseif(is_array($INUSE)){
1174    media_filesinuse($INUSE,$IMG);
1175  }else{
1176    media_filelist($NS,$AUTH,$JUMPTO);
1177  }
1178  ptln('</div>');
1179}
1180
1181/**
1182 * prints the namespace tree in the mediamanger popup
1183 *
1184 * Only allowed in mediamanager.php
1185 *
1186 * @author Andreas Gohr <andi@splitbrain.org>
1187 */
1188function tpl_mediaTree(){
1189  global $NS;
1190
1191  ptln('<div id="media__tree">');
1192  media_nstree($NS);
1193  ptln('</div>');
1194}
1195
1196
1197/**
1198 * Print a dropdown menu with all DokuWiki actions
1199 *
1200 * Note: this will not use any pretty URLs
1201 *
1202 * @author Andreas Gohr <andi@splitbrain.org>
1203 */
1204function tpl_actiondropdown($empty='',$button='&gt;'){
1205    global $ID;
1206    global $INFO;
1207    global $REV;
1208    global $ACT;
1209    global $conf;
1210    global $lang;
1211    global $auth;
1212
1213
1214    echo '<form method="post" accept-charset="utf-8">'; #FIXME action
1215    echo '<input type="hidden" name="id" value="'.$ID.'" />';
1216    if($REV) echo '<input type="hidden" name="rev" value="'.$REV.'" />';
1217    echo '<input type="hidden" name="sectok" value="'.getSecurityToken().'" />';
1218
1219    echo '<select name="do" id="action__selector" class="edit">';
1220    echo '<option value="">'.$empty.'</option>';
1221
1222    echo '<optgroup label=" &mdash; ">';
1223        // 'edit' - most complicated type, we need to decide on current action
1224        if($ACT == 'show' || $ACT == 'search'){
1225            if($INFO['writable']){
1226                if(!empty($INFO['draft'])) {
1227                    echo '<option value="edit">'.$lang['btn_draft'].'</option>';
1228                } else {
1229                    if($INFO['exists']){
1230                        echo '<option value="edit">'.$lang['btn_edit'].'</option>';
1231                    }else{
1232                        echo '<option value="edit">'.$lang['btn_create'].'</option>';
1233                    }
1234                }
1235            }else if(actionOK('source')) { //pseudo action
1236                echo '<option value="edit">'.$lang['btn_source'].'</option>';
1237            }
1238        }else{
1239            echo '<option value="show">'.$lang['btn_show'].'</option>';
1240        }
1241
1242        echo '<option value="revisions">'.$lang['btn_revs'].'</option>';
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'] == 1){
1266            if($_SERVER['REMOTE_USER']){
1267                if($INFO['subscribed']) {
1268                    echo '<option value="unsubscribe">'.$lang['btn_unsubscribe'].'</option>';
1269                } else {
1270                    echo '<option value="subscribe">'.$lang['btn_subscribe'].'</option>';
1271                }
1272            }
1273        }
1274
1275        if($conf['useacl'] && $auth && $ACT == 'show' && $conf['subscribers'] == 1){
1276            if($_SERVER['REMOTE_USER']){
1277                if($INFO['subscribedns']) {
1278                    echo '<option value="unsubscribens">'.$lang['btn_unsubscribens'].'</option>';
1279                } else {
1280                    echo '<option value="subscribens">'.$lang['btn_subscribens'].'</option>';
1281                }
1282            }
1283        }
1284
1285        if($INFO['ismanager']){
1286            echo '<option value="admin">'.$lang['btn_admin'].'</option>';
1287        }
1288    echo '</optgroup>';
1289
1290    echo '</select>';
1291    echo '<input type="submit" value="'.$button.'" id="action__selectorbtn" />';
1292    echo '</form>';
1293}
1294
1295/**
1296 * Print a informational line about the used license
1297 *
1298 * @author Andreas Gohr <andi@splitbrain.org>
1299 * @param  string $img    - print image? (|button|badge)
1300 * @param  bool   $return - when true don't print, but return HTML
1301 */
1302function tpl_license($img='badge',$imgonly=false,$return=false){
1303    global $license;
1304    global $conf;
1305    global $lang;
1306    if(!$conf['license']) return '';
1307    if(!is_array($license[$conf['license']])) return '';
1308    $lic = $license[$conf['license']];
1309
1310    $out  = '<div class="license">';
1311    if($img){
1312        $src = license_img($img);
1313        if($src){
1314            $out .= '<a href="'.$lic['url'].'" rel="license"';
1315            if($conf['target']['external']) $out .= ' target="'.$conf['target']['external'].'"';
1316            $out .= '><img src="'.DOKU_BASE.$src.'" class="medialeft lic'.$img.'" alt="'.$lic['name'].'" /></a> ';
1317        }
1318    }
1319    if(!$imgonly) {
1320        $out .= $lang['license'];
1321        $out .= '<a href="'.$lic['url'].'" rel="license" class="urlextern"';
1322        if($conf['target']['external']) $out .= ' target="'.$conf['target']['external'].'"';
1323        $out .= '>'.$lic['name'].'</a>';
1324        $out .= '</div>';
1325    }
1326
1327    if($return) return $out;
1328    echo $out;
1329}
1330
1331//Setup VIM: ex: et ts=4 enc=utf-8 :
1332
1333