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