xref: /dokuwiki/inc/template.php (revision 29823b4629b1d6219cf14d53fdc537bbaf08d2d5)
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
9  if(!defined('DOKU_INC')) define('DOKU_INC',fullpath(dirname(__FILE__).'/../').'/');
10  require_once(DOKU_CONF.'dokuwiki.php');
11
12/**
13 * Returns the path to the given template, uses
14 * default one if the custom version doesn't exist.
15 *
16 * @author Andreas Gohr <andi@splitbrain.org>
17 */
18function template($tpl){
19  global $conf;
20
21  if(@is_readable(DOKU_INC.'lib/tpl/'.$conf['template'].'/'.$tpl))
22    return DOKU_INC.'lib/tpl/'.$conf['template'].'/'.$tpl;
23
24  return DOKU_INC.'lib/tpl/default/'.$tpl;
25}
26
27/**
28 * Print the content
29 *
30 * This function is used for printing all the usual content
31 * (defined by the global $ACT var) by calling the appropriate
32 * outputfunction(s) from html.php
33 *
34 * Everything that doesn't use the main template file isn't
35 * handled by this function. ACL stuff is not done here either.
36 *
37 * @author Andreas Gohr <andi@splitbrain.org>
38 */
39function tpl_content($prependTOC=true) {
40    global $ACT;
41    global $INFO;
42    $INFO['prependTOC'] = $prependTOC;
43
44    ob_start();
45    trigger_event('TPL_ACT_RENDER',$ACT,'tpl_content_core');
46    $html_output = ob_get_clean();
47    trigger_event('TPL_CONTENT_DISPLAY',$html_output,'ptln');
48
49    return !empty($html_output);
50}
51
52function tpl_content_core(){
53  global $ACT;
54  global $TEXT;
55  global $PRE;
56  global $SUF;
57  global $SUM;
58  global $IDX;
59
60  switch($ACT){
61    case 'show':
62      html_show();
63      break;
64    case 'preview':
65      html_edit($TEXT);
66      html_show($TEXT);
67      break;
68    case 'recover':
69      html_edit($TEXT);
70      break;
71    case 'edit':
72      html_edit();
73      break;
74    case 'draft':
75      html_draft();
76      break;
77    case 'wordblock':
78      html_edit($TEXT,'wordblock');
79      break;
80    case 'search':
81      html_search();
82      break;
83    case 'revisions':
84      $first = is_numeric($_REQUEST['first']) ? intval($_REQUEST['first']) : 0;
85      html_revisions($first);
86      break;
87    case 'diff':
88      html_diff();
89      break;
90    case 'recent':
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 'locked':
105      html_locked();
106      break;
107    case 'login':
108      html_login();
109      break;
110    case 'register':
111      html_register();
112      break;
113    case 'resendpwd':
114      html_resendpwd();
115      break;
116    case 'denied':
117      print p_locale_xhtml('denied');
118      break;
119    case 'profile' :
120      html_updateprofile();
121      break;
122    case 'admin':
123      tpl_admin();
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    $toc = array();
151
152    if(is_array($TOC)){
153        // if a TOC was prepared in global scope, always use it
154        $toc = $TOC;
155    }elseif($ACT == 'show' && !$REV && $INFO['exists']){
156        // get TOC from metadata, render if neccessary
157        $meta = p_get_metadata($ID, false, true);
158        if(isset($meta['internal']['toc'])){
159            $tocok = $meta['internal']['toc'];
160        }else{
161            $tocok = true;
162        }
163        $toc   = $meta['description']['tableofcontents'];
164        if(!$tocok || !is_array($toc) || count($toc) < 3){
165            $toc = array();
166        }
167    }elseif($ACT == 'admin'){
168        // try to load admin plugin TOC FIXME: duplicates code from tpl_admin
169        $plugin = null;
170        if (!empty($_REQUEST['page'])) {
171            $pluginlist = plugin_list('admin');
172            if (in_array($_REQUEST['page'], $pluginlist)) {
173                // attempt to load the plugin
174                $plugin =& plugin_load('admin',$_REQUEST['page']);
175            }
176        }
177        if ( ($plugin !== null) &&
178             (!$plugin->forAdminOnly() || $INFO['isadmin']) ){
179            $toc = $plugin->getTOC();
180            $TOC = $toc; // avoid later rebuild
181        }
182    }
183
184    $html = html_TOC($toc);
185    if($return) return $html;
186    echo $html;
187}
188
189/**
190 * Handle the admin page contents
191 *
192 * @author Andreas Gohr <andi@splitbrain.org>
193 */
194function tpl_admin(){
195    global $INFO;
196    global $TOC;
197
198    $plugin = null;
199    if (!empty($_REQUEST['page'])) {
200        $pluginlist = plugin_list('admin');
201
202        if (in_array($_REQUEST['page'], $pluginlist)) {
203
204          // attempt to load the plugin
205          $plugin =& plugin_load('admin',$_REQUEST['page']);
206        }
207    }
208
209    if ($plugin !== null){
210        if($plugin->forAdminOnly() && !$INFO['isadmin']){
211            msg('For admins only',-1);
212            html_admin();
213        }else{
214            if(!is_array($TOC)) $TOC = $plugin->getTOC(); //if TOC wasn't requested yet
215            if($INFO['prependTOC']) tpl_toc();
216            $plugin->html();
217        }
218    }else{
219        html_admin();
220    }
221    return true;
222}
223
224/**
225 * Print the correct HTML meta headers
226 *
227 * This has to go into the head section of your template.
228 *
229 * @triggers TPL_METAHEADER_OUTPUT
230 * @param  boolean $alt Should feeds and alternative format links be added?
231 * @author Andreas Gohr <andi@splitbrain.org>
232 */
233function tpl_metaheaders($alt=true){
234  global $ID;
235  global $REV;
236  global $INFO;
237  global $ACT;
238  global $QUERY;
239  global $lang;
240  global $conf;
241  $it=2;
242
243  // prepare the head array
244  $head = array();
245
246
247  // the usual stuff
248  $head['meta'][] = array( 'name'=>'generator', 'content'=>'DokuWiki '.getVersion() );
249  $head['link'][] = array( 'rel'=>'search', 'type'=>'application/opensearchdescription+xml',
250                           'href'=>DOKU_BASE.'lib/exe/opensearch.php', 'title'=>$conf['title'] );
251  $head['link'][] = array( 'rel'=>'start', 'href'=>DOKU_BASE );
252  $head['link'][] = array( 'rel'=>'contents', 'href'=> wl($ID,'do=index',false,'&'),
253                           'title'=>$lang['btn_index'] );
254
255  if($alt){
256    $head['link'][] = array( 'rel'=>'alternate', 'type'=>'application/rss+xml',
257                             'title'=>'Recent Changes', 'href'=>DOKU_BASE.'feed.php');
258    $head['link'][] = array( 'rel'=>'alternate', 'type'=>'application/rss+xml',
259                             'title'=>'Current Namespace',
260                             'href'=>DOKU_BASE.'feed.php?mode=list&ns='.$INFO['namespace']);
261    if($ACT == 'search'){
262      $head['link'][] = array( 'rel'=>'alternate', 'type'=>'application/rss+xml',
263                               'title'=>'Search Result',
264                               'href'=>DOKU_BASE.'feed.php?mode=search&q='.$QUERY);
265    }
266
267    if(actionOK('export_xhtml')){
268      $head['link'][] = array( 'rel'=>'alternate', 'type'=>'text/html', 'title'=>'Plain HTML',
269                               'href'=>exportlink($ID, 'xhtml', '', false, '&'));
270    }
271
272    if(actionOK('export_raw')){
273      $head['link'][] = array( 'rel'=>'alternate', 'type'=>'text/plain', 'title'=>'Wiki Markup',
274                               'href'=>exportlink($ID, 'raw', '', false, '&'));
275    }
276  }
277
278  // setup robot tags apropriate for different modes
279  if( ($ACT=='show' || $ACT=='export_xhtml') && !$REV){
280    if($INFO['exists']){
281      //delay indexing:
282      if((time() - $INFO['lastmod']) >= $conf['indexdelay']){
283        $head['meta'][] = array( 'name'=>'robots', 'content'=>'index,follow');
284      }else{
285        $head['meta'][] = array( 'name'=>'robots', 'content'=>'noindex,nofollow');
286      }
287    }else{
288      $head['meta'][] = array( 'name'=>'robots', 'content'=>'noindex,follow');
289    }
290  }elseif(defined('DOKU_MEDIADETAIL')){
291    $head['meta'][] = array( 'name'=>'robots', 'content'=>'index,follow');
292  }else{
293    $head['meta'][] = array( 'name'=>'robots', 'content'=>'noindex,nofollow');
294  }
295
296  // set metadata
297  if($ACT == 'show' || $ACT=='export_xhtml'){
298    // date of modification
299    if($REV){
300      $head['meta'][] = array( 'name'=>'date', 'content'=>date('Y-m-d\TH:i:sO',$REV));
301    }else{
302      $head['meta'][] = array( 'name'=>'date', 'content'=>date('Y-m-d\TH:i:sO',$INFO['lastmod']));
303    }
304
305    // keywords (explicit or implicit)
306    if(!empty($INFO['meta']['subject'])){
307      $head['meta'][] = array( 'name'=>'keywords', 'content'=>join(',',$INFO['meta']['subject']));
308    }else{
309      $head['meta'][] = array( 'name'=>'keywords', 'content'=>str_replace(':',',',$ID));
310    }
311  }
312
313  // load stylesheets
314  $head['link'][] = array('rel'=>'stylesheet', 'media'=>'all', 'type'=>'text/css',
315                          'href'=>DOKU_BASE.'lib/exe/css.php?s=all&t='.$conf['template']);
316  $head['link'][] = array('rel'=>'stylesheet', 'media'=>'screen', 'type'=>'text/css',
317                          'href'=>DOKU_BASE.'lib/exe/css.php?t='.$conf['template']);
318  $head['link'][] = array('rel'=>'stylesheet', 'media'=>'print', 'type'=>'text/css',
319                          'href'=>DOKU_BASE.'lib/exe/css.php?s=print&t='.$conf['template']);
320
321  // load javascript
322  $js_edit  = ($ACT=='edit' || $ACT=='preview' || $ACT=='recover' || $ACT=='wordblock' ) ? 1 : 0;
323  $js_write = ($INFO['writable']) ? 1 : 0;
324  if(defined('DOKU_MEDIAMANAGER')){
325    $js_edit  = 1;
326    $js_write = 0;
327  }
328  if(($js_edit && $js_write) || defined('DOKU_MEDIAMANAGER')){
329    $script = "NS='".$INFO['namespace']."';";
330    if($conf['useacl'] && $_SERVER['REMOTE_USER']){
331      require_once(DOKU_INC.'inc/toolbar.php');
332      $script .= "SIG='".toolbar_signature()."';";
333    }
334    $head['script'][] = array( 'type'=>'text/javascript', 'charset'=>'utf-8',
335                               '_data'=> $script);
336  }
337  $head['script'][] = array( 'type'=>'text/javascript', 'charset'=>'utf-8', '_data'=>'',
338                             'src'=>DOKU_BASE.'lib/exe/js.php?edit='.$js_edit.'&write='.$js_write);
339
340  // trigger event here
341  trigger_event('TPL_METAHEADER_OUTPUT',$head,'_tpl_metaheaders_action',true);
342  return true;
343}
344
345/**
346 * prints the array build by tpl_metaheaders
347 *
348 * $data is an array of different header tags. Each tag can have multiple
349 * instances. Attributes are given as key value pairs. Values will be HTML
350 * encoded automatically so they should be provided as is in the $data array.
351 *
352 * For tags having a body attribute specify the the body data in the special
353 * attribute '_data'. This field will NOT BE ESCAPED automatically.
354 *
355 * @author Andreas Gohr <andi@splitbrain.org>
356 */
357function _tpl_metaheaders_action($data){
358  foreach($data as $tag => $inst){
359    foreach($inst as $attr){
360      echo '<',$tag,' ',buildAttributes($attr);
361      if(isset($attr['_data'])){
362          if($tag == 'script' && $attr['_data'])
363            $attr['_data'] = "<!--//--><![CDATA[//><!--\n".
364                             $attr['_data'].
365                             "\n//--><!]]>";
366
367          echo '>',$attr['_data'],'</',$tag,'>';
368      }else{
369        echo '/>';
370      }
371      echo "\n";
372    }
373  }
374}
375
376/**
377 * Print a link
378 *
379 * Just builds a link.
380 *
381 * @author Andreas Gohr <andi@splitbrain.org>
382 */
383function tpl_link($url,$name,$more=''){
384  print '<a href="'.$url.'" ';
385  if ($more) print ' '.$more;
386  print ">$name</a>";
387  return true;
388}
389
390/**
391 * Prints a link to a WikiPage
392 *
393 * Wrapper around html_wikilink
394 *
395 * @author Andreas Gohr <andi@splitbrain.org>
396 */
397function tpl_pagelink($id,$name=NULL){
398  print html_wikilink($id,$name);
399  return true;
400}
401
402/**
403 * get the parent page
404 *
405 * Tries to find out which page is parent.
406 * returns false if none is available
407 *
408 * @author Andreas Gohr <andi@splitbrain.org>
409 */
410function tpl_getparent($id){
411  global $conf;
412  $parent = getNS($id).':';
413  resolve_pageid('',$parent,$exists);
414  if($parent == $id) {
415    $pos = strrpos (getNS($id),':');
416    $parent = substr($parent,0,$pos).':';
417    resolve_pageid('',$parent,$exists);
418    if($parent == $id) return false;
419  }
420  return $parent;
421}
422
423/**
424 * Print one of the buttons
425 *
426 * Available Buttons are
427 *
428 *  edit        - edit/create/show/draft button
429 *  history     - old revisions
430 *  recent      - recent changes
431 *  login       - login/logout button - if ACL enabled
432 *  profile     - user profile button (if logged in)
433 *  index       - The index
434 *  admin       - admin page - if enough rights
435 *  top         - a back to top button
436 *  back        - a back to parent button - if available
437 *  backlink    - links to the list of backlinks
438 *  subscription- subscribe/unsubscribe button
439 *
440 * @author Andreas Gohr <andi@splitbrain.org>
441 * @author Matthias Grimm <matthiasgrimm@users.sourceforge.net>
442 */
443function tpl_button($type){
444  global $ACT;
445  global $ID;
446  global $REV;
447  global $NS;
448  global $INFO;
449  global $conf;
450  global $auth;
451
452  // check disabled actions and fix the badly named ones
453  $ctype = $type;
454  if($type == 'history') $ctype='revisions';
455  if(!actionOK($ctype)) return false;
456
457  switch($type){
458    case 'edit':
459      #most complicated type - we need to decide on current action
460      if($ACT == 'show' || $ACT == 'search'){
461        if($INFO['writable']){
462          if(!empty($INFO['draft'])){
463            echo html_btn('draft',$ID,'e',array('do' => 'draft'),'post');
464          }else{
465            if($INFO['exists']){
466              echo html_btn('edit',$ID,'e',array('do' => 'edit','rev' => $REV),'post');
467            }else{
468              echo html_btn('create',$ID,'e',array('do' => 'edit','rev' => $REV),'post');
469            }
470          }
471        }else{
472          if(!actionOK('source')) return false; //pseudo action
473          echo html_btn('source',$ID,'v',array('do' => 'edit','rev' => $REV),'post');
474        }
475      }else{
476          echo html_btn('show',$ID,'v',array('do' => 'show'));
477      }
478      return true;
479    case 'history':
480      print html_btn('revs',$ID,'o',array('do' => 'revisions'));
481      return true;
482    case 'recent':
483      print html_btn('recent','','r',array('do' => 'recent'));
484      return true;
485    case 'index':
486      print html_btn('index',$ID,'x',array('do' => 'index'));
487      return true;
488    case 'back':
489      if ($parent = tpl_getparent($ID)) {
490        print html_btn('back',$parent,'b',array('do' => 'show'));
491        return true;
492      }
493      return false;
494    case 'top':
495      print html_topbtn();
496      return true;
497    case 'login':
498      if($conf['useacl'] && $auth){
499        if($_SERVER['REMOTE_USER']){
500          print html_btn('logout',$ID,'',array('do' => 'logout', 'sectok' => getSecurityToken()));
501        }else{
502          print html_btn('login',$ID,'',array('do' => 'login', 'sectok' => getSecurityToken()));
503        }
504        return true;
505      }
506      return false;
507    case 'admin':
508      if($INFO['ismanager']){
509        print html_btn('admin',$ID,'',array('do' => 'admin'));
510        return true;
511      }
512      return false;
513    case 'subscription':
514      if($conf['useacl'] && $auth && $ACT == 'show' && $conf['subscribers'] == 1){
515        if($_SERVER['REMOTE_USER']){
516          if($INFO['subscribed']){
517            print html_btn('unsubscribe',$ID,'',array('do' => 'unsubscribe',));
518          } else {
519            print html_btn('subscribe',$ID,'',array('do' => 'subscribe',));
520          }
521          if($INFO['subscribedns']){
522            print html_btn('unsubscribens',$ID,'',array('do' => 'unsubscribens',));
523          } else {
524            print html_btn('subscribens',$ID,'',array('do' => 'subscribens',));
525          }
526          return true;
527        }
528      }
529      return false;
530    case 'backlink':
531      print html_btn('backlink',$ID,'',array('do' => 'backlink'));
532      return true;
533    case 'profile':
534      if($conf['useacl'] && $_SERVER['REMOTE_USER'] && $auth &&
535         $auth->canDo('Profile') && ($ACT!='profile')){
536        print html_btn('profile',$ID,'',array('do' => 'profile'));
537        return true;
538      }
539      return false;
540    default:
541      print '[unknown button type]';
542      return true;
543  }
544}
545
546/**
547 * Like the action buttons but links
548 *
549 * Available links are
550 *
551 *  edit    - edit/create/show link
552 *  history - old revisions
553 *  recent  - recent changes
554 *  login   - login/logout link - if ACL enabled
555 *  profile - user profile link (if logged in)
556 *  index   - The index
557 *  admin   - admin page - if enough rights
558 *  top     - a back to top link
559 *  back    - a back to parent link - if available
560 *  backlink - links to the list of backlinks
561 *  subscribe/subscription - subscribe/unsubscribe link
562 *
563 * @author Andreas Gohr <andi@splitbrain.org>
564 * @author Matthias Grimm <matthiasgrimm@users.sourceforge.net>
565 * @see    tpl_button
566 */
567function tpl_actionlink($type,$pre='',$suf='',$inner=''){
568  global $ID;
569  global $INFO;
570  global $REV;
571  global $ACT;
572  global $conf;
573  global $lang;
574  global $auth;
575
576  // check disabled actions and fix the badly named ones
577  $ctype = $type;
578  if($type == 'history') $ctype='revisions';
579  if(!actionOK($ctype)) return false;
580
581  switch($type){
582    case 'edit':
583      #most complicated type - we need to decide on current action
584      if($ACT == 'show' || $ACT == 'search'){
585        if($INFO['writable']){
586          if(!empty($INFO['draft'])) {
587            tpl_link(wl($ID,'do=draft'),
588                       $pre.(($inner)?$inner:$lang['btn_draft']).$suf,
589                       'class="action edit" accesskey="e" rel="nofollow"');
590          } else {
591            if($INFO['exists']){
592              tpl_link(wl($ID,'do=edit&amp;rev='.$REV),
593                       $pre.(($inner)?$inner:$lang['btn_edit']).$suf,
594                       'class="action edit" accesskey="e" rel="nofollow"');
595            }else{
596              tpl_link(wl($ID,'do=edit&amp;rev='.$REV),
597                       $pre.(($inner)?$inner:$lang['btn_create']).$suf,
598                       'class="action create" accesskey="e" rel="nofollow"');
599            }
600          }
601        }else{
602          if(!actionOK('source')) return false; //pseudo action
603          tpl_link(wl($ID,'do=edit&amp;rev='.$REV),
604                   $pre.(($inner)?$inner:$lang['btn_source']).$suf,
605                   'class="action source" accesskey="v" rel="nofollow"');
606        }
607      }else{
608          tpl_link(wl($ID,'do=show'),
609                   $pre.(($inner)?$inner:$lang['btn_show']).$suf,
610                   'class="action show" accesskey="v" rel="nofollow"');
611      }
612      return true;
613    case 'history':
614      tpl_link(wl($ID,'do=revisions'),
615               $pre.(($inner)?$inner:$lang['btn_revs']).$suf,
616               'class="action revisions" accesskey="o" rel="nofollow"');
617      return true;
618    case 'recent':
619      tpl_link(wl('','do=recent'),
620               $pre.(($inner)?$inner:$lang['btn_recent']).$suf,
621              'class="action recent" accesskey="r" rel="nofollow"');
622      return true;
623    case 'index':
624      tpl_link(wl($ID,'do=index'),
625               $pre.(($inner)?$inner:$lang['btn_index']).$suf,
626              'class="action index" accesskey="x" rel="nofollow"');
627      return true;
628    case 'top':
629      print '<a href="#dokuwiki__top" class="action top" accesskey="x">'.
630            $pre.(($inner)?$inner:$lang['btn_top']).$suf.'</a>';
631      return true;
632    case 'back':
633      if ($parent = tpl_getparent($ID)) {
634        tpl_link(wl($parent,'do=show'),
635        $pre.(($inner)?$inner:$lang['btn_back']).$suf,
636        'class="action back" accesskey="b" rel="nofollow"');
637        return true;
638      }
639      return false;
640    case 'login':
641      if($conf['useacl'] && $auth){
642        if($_SERVER['REMOTE_USER']){
643          tpl_link(wl($ID,'do=logout&amp;sectok='.getSecurityToken()),
644                   $pre.(($inner)?$inner:$lang['btn_logout']).$suf,
645                   'class="action logout" rel="nofollow"');
646        }else{
647          tpl_link(wl($ID,'do=login&amp;sectok='.getSecurityToken()),
648                   $pre.(($inner)?$inner:$lang['btn_login']).$suf,
649                   'class="action login" rel="nofollow"');
650        }
651        return true;
652      }
653      return false;
654    case 'admin':
655      if($INFO['ismanager']){
656        tpl_link(wl($ID,'do=admin'),
657                 $pre.(($inner)?$inner:$lang['btn_admin']).$suf,
658                 'class="action admin" rel="nofollow"');
659        return true;
660      }
661      return false;
662   case 'subscribe':
663   case 'subscription':
664      if($conf['useacl'] && $auth && $ACT == 'show' && $conf['subscribers'] == 1){
665        if($_SERVER['REMOTE_USER']){
666          if($INFO['subscribed']) {
667            tpl_link(wl($ID,'do=unsubscribe'),
668                     $pre.(($inner)?$inner:$lang['btn_unsubscribe']).$suf,
669                     'class="action unsubscribe" rel="nofollow"');
670          } else {
671            tpl_link(wl($ID,'do=subscribe'),
672                     $pre.(($inner)?$inner:$lang['btn_subscribe']).$suf,
673                     'class="action subscribe" rel="nofollow"');
674          }
675          return true;
676        }
677      }
678      return false;
679    case 'subscribens':
680      if($conf['useacl'] && $auth && $ACT == 'show' && $conf['subscribers'] == 1){
681        if($_SERVER['REMOTE_USER']){
682          if($INFO['subscribedns']) {
683            tpl_link(wl($ID,'do=unsubscribens'),
684                     $pre.(($inner)?$inner:$lang['btn_unsubscribens']).$suf,
685                     'class="action unsubscribens" rel="nofollow"');
686          } else {
687            tpl_link(wl($ID,'do=subscribens'),
688                     $pre.(($inner)?$inner:$lang['btn_subscribens']).$suf,
689                     'class="action subscribens" rel="nofollow"');
690          }
691          return true;
692        }
693      }
694      return false;
695    case 'backlink':
696      tpl_link(wl($ID,'do=backlink'),
697               $pre.(($inner)?$inner:$lang['btn_backlink']).$suf,
698               'class="action backlink" rel="nofollow"');
699      return true;
700    case 'profile':
701      if($conf['useacl'] && $auth && $_SERVER['REMOTE_USER'] &&
702         $auth->canDo('Profile') && ($ACT!='profile')){
703        tpl_link(wl($ID,'do=profile'),
704                 $pre.(($inner)?$inner:$lang['btn_profile']).$suf,
705                 'class="action profile" rel="nofollow"');
706        return true;
707      }
708      return false;
709    default:
710      print '[unknown link type]';
711      return true;
712  }
713}
714
715/**
716 * Print the search form
717 *
718 * If the first parameter is given a div with the ID 'qsearch_out' will
719 * be added which instructs the ajax pagequicksearch to kick in and place
720 * its output into this div. The second parameter controls the propritary
721 * attribute autocomplete. If set to false this attribute will be set with an
722 * value of "off" to instruct the browser to disable it's own built in
723 * autocompletion feature (MSIE and Firefox)
724 *
725 * @author Andreas Gohr <andi@splitbrain.org>
726 */
727function tpl_searchform($ajax=true,$autocomplete=true){
728  global $lang;
729  global $ACT;
730
731  // don't print the search form if search action has been disabled
732  if (!actionOk('search')) return false;
733
734  print '<form action="'.wl().'" accept-charset="utf-8" class="search" id="dw__search"><div class="no">';
735  print '<input type="hidden" name="do" value="search" />';
736  print '<input type="text" ';
737  if($ACT == 'search') print 'value="'.htmlspecialchars($_REQUEST['id']).'" ';
738  if(!$autocomplete) print 'autocomplete="off" ';
739  print 'id="qsearch__in" accesskey="f" name="id" class="edit" title="[ALT+F]" />';
740  print '<input type="submit" value="'.$lang['btn_search'].'" class="button" title="'.$lang['btn_search'].'" />';
741  if($ajax) print '<div id="qsearch__out" class="ajax_qsearch JSpopup"></div>';
742  print '</div></form>';
743  return true;
744}
745
746/**
747 * Print the breadcrumbs trace
748 *
749 * @author Andreas Gohr <andi@splitbrain.org>
750 */
751function tpl_breadcrumbs($sep='&raquo;'){
752  global $lang;
753  global $conf;
754
755  //check if enabled
756  if(!$conf['breadcrumbs']) return false;
757
758  $crumbs = breadcrumbs(); //setup crumb trace
759
760  //reverse crumborder in right-to-left mode, add RLM character to fix heb/eng display mixups
761  if($lang['direction'] == 'rtl') {
762    $crumbs = array_reverse($crumbs,true);
763    $crumbs_sep = ' &#8207;<span class="bcsep">'.$sep.'</span>&#8207; ';
764  } else {
765    $crumbs_sep = ' <span class="bcsep">'.$sep.'</span> ';
766  }
767
768  //render crumbs, highlight the last one
769  print '<span class="bchead">'.$lang['breadcrumb'].':</span>';
770  $last = count($crumbs);
771  $i = 0;
772  foreach ($crumbs as $id => $name){
773    $i++;
774    echo $crumbs_sep;
775    if ($i == $last) print '<span class="curid">';
776    tpl_link(wl($id),hsc($name),'class="breadcrumbs" title="'.$id.'"');
777    if ($i == $last) print '</span>';
778  }
779  return true;
780}
781
782/**
783 * Hierarchical breadcrumbs
784 *
785 * This code was suggested as replacement for the usual breadcrumbs.
786 * It only makes sense with a deep site structure.
787 *
788 * @author Andreas Gohr <andi@splitbrain.org>
789 * @author Nigel McNie <oracle.shinoda@gmail.com>
790 * @author Sean Coates <sean@caedmon.net>
791 * @link   http://wiki.splitbrain.org/wiki:tipsandtricks:hierarchicalbreadcrumbs
792 * @todo   May behave strangely in RTL languages
793 */
794function tpl_youarehere($sep=' &raquo; '){
795  global $conf;
796  global $ID;
797  global $lang;
798
799  // check if enabled
800  if(!$conf['youarehere']) return false;
801
802  $parts = explode(':', $ID);
803  $count = count($parts);
804
805  echo '<span class="bchead">'.$lang['youarehere'].': </span>';
806
807  // always print the startpage
808  $title = p_get_first_heading($conf['start']);
809  if(!$title) $title = $conf['start'];
810  tpl_link(wl($conf['start']),hsc($title),'title="'.$conf['start'].'"');
811
812  // print intermediate namespace links
813  $part = '';
814  for($i=0; $i<$count - 1; $i++){
815    $part .= $parts[$i].':';
816    $page = $part;
817    resolve_pageid('',$page,$exists);
818    if ($page == $conf['start']) continue; // Skip startpage
819
820    // output
821    echo $sep;
822    if($exists){
823      $title = p_get_first_heading($page);
824      if(!$title) $title = $parts[$i];
825      tpl_link(wl($page),hsc($title),'title="'.$page.'"');
826    }else{
827      tpl_link(wl($page),$parts[$i],'title="'.$page.'" class="wikilink2" rel="nofollow"');
828    }
829  }
830
831  // print current page, skipping start page, skipping for namespace index
832  if(isset($page) && $page==$part.$parts[$i]) return;
833  $page = $part.$parts[$i];
834  if($page == $conf['start']) return;
835  echo $sep;
836  if(page_exists($page)){
837    $title = p_get_first_heading($page);
838    if(!$title) $title = $parts[$i];
839    tpl_link(wl($page),hsc($title),'title="'.$page.'"');
840  }else{
841    tpl_link(wl($page),$parts[$i],'title="'.$page.'" class="wikilink2" rel="nofollow"');
842  }
843  return true;
844}
845
846/**
847 * Print info if the user is logged in
848 * and show full name in that case
849 *
850 * Could be enhanced with a profile link in future?
851 *
852 * @author Andreas Gohr <andi@splitbrain.org>
853 */
854function tpl_userinfo(){
855  global $lang;
856  global $INFO;
857  if($_SERVER['REMOTE_USER']){
858    print $lang['loggedinas'].': '.$INFO['userinfo']['name'];
859    return true;
860  }
861  return false;
862}
863
864/**
865 * Print some info about the current page
866 *
867 * @author Andreas Gohr <andi@splitbrain.org>
868 */
869function tpl_pageinfo(){
870  global $conf;
871  global $lang;
872  global $INFO;
873  global $REV;
874  global $ID;
875
876  // return if we are not allowed to view the page
877  if (!auth_quickaclcheck($ID)) { return; }
878
879  // prepare date and path
880  $fn = $INFO['filepath'];
881  if(!$conf['fullpath']){
882    if($REV){
883      $fn = str_replace(fullpath($conf['olddir']).DIRECTORY_SEPARATOR,'',$fn);
884    }else{
885      $fn = str_replace(fullpath($conf['datadir']).DIRECTORY_SEPARATOR,'',$fn);
886    }
887  }
888  $fn = utf8_decodeFN($fn);
889  $date = strftime($conf['dformat'],$INFO['lastmod']);
890
891  // print it
892  if($INFO['exists']){
893    print $fn;
894    print ' &middot; ';
895    print $lang['lastmod'];
896    print ': ';
897    print $date;
898    if($INFO['editor']){
899      print ' '.$lang['by'].' ';
900      print $INFO['editor'];
901    }else{
902      print ' ('.$lang['external_edit'].')';
903    }
904    if($INFO['locked']){
905      print ' &middot; ';
906      print $lang['lockedby'];
907      print ': ';
908      print $INFO['locked'];
909    }
910    return true;
911  }
912  return false;
913}
914
915/**
916 * Prints or returns the name of the given page (current one if none given).
917 *
918 * If useheading is enabled this will use the first headline else
919 * the given ID is used.
920 *
921 * @author Andreas Gohr <andi@splitbrain.org>
922 */
923function tpl_pagetitle($id=null, $ret=false){
924  global $conf;
925  if(is_null($id)){
926    global $ID;
927    $id = $ID;
928  }
929
930  $name = $id;
931  if ($conf['useheading']) {
932    $title = p_get_first_heading($id);
933    if ($title) $name = $title;
934  }
935
936  if ($ret) {
937      return hsc($name);
938  } else {
939      print hsc($name);
940      return true;
941  }
942}
943
944/**
945 * Returns the requested EXIF/IPTC tag from the current image
946 *
947 * If $tags is an array all given tags are tried until a
948 * value is found. If no value is found $alt is returned.
949 *
950 * Which texts are known is defined in the functions _exifTagNames
951 * and _iptcTagNames() in inc/jpeg.php (You need to prepend IPTC
952 * to the names of the latter one)
953 *
954 * Only allowed in: detail.php
955 *
956 * @author Andreas Gohr <andi@splitbrain.org>
957 */
958function tpl_img_getTag($tags,$alt='',$src=null){
959  // Init Exif Reader
960  global $SRC;
961
962  if(is_null($src)) $src = $SRC;
963
964  static $meta = null;
965  if(is_null($meta)) $meta = new JpegMeta($src);
966  if($meta === false) return $alt;
967  $info = $meta->getField($tags);
968  if($info == false) return $alt;
969  return $info;
970}
971
972/**
973 * Prints the image with a link to the full sized version
974 *
975 * Only allowed in: detail.php
976 */
977function tpl_img($maxwidth=0,$maxheight=0){
978  global $IMG;
979  $w = tpl_img_getTag('File.Width');
980  $h = tpl_img_getTag('File.Height');
981
982  //resize to given max values
983  $ratio = 1;
984  if($w >= $h){
985    if($maxwidth && $w >= $maxwidth){
986      $ratio = $maxwidth/$w;
987    }elseif($maxheight && $h > $maxheight){
988      $ratio = $maxheight/$h;
989    }
990  }else{
991    if($maxheight && $h >= $maxheight){
992      $ratio = $maxheight/$h;
993    }elseif($maxwidth && $w > $maxwidth){
994      $ratio = $maxwidth/$w;
995    }
996  }
997  if($ratio){
998    $w = floor($ratio*$w);
999    $h = floor($ratio*$h);
1000  }
1001
1002  //prepare URLs
1003  $url=ml($IMG,array('cache'=>$_REQUEST['cache']));
1004  $src=ml($IMG,array('cache'=>$_REQUEST['cache'],'w'=>$w,'h'=>$h));
1005
1006  //prepare attributes
1007  $alt=tpl_img_getTag('Simple.Title');
1008  $p = array();
1009  if($w) $p['width']  = $w;
1010  if($h) $p['height'] = $h;
1011         $p['class']  = 'img_detail';
1012  if($alt){
1013    $p['alt']   = $alt;
1014    $p['title'] = $alt;
1015  }else{
1016    $p['alt'] = '';
1017  }
1018  $p = buildAttributes($p);
1019
1020  print '<a href="'.$url.'">';
1021  print '<img src="'.$src.'" '.$p.'/>';
1022  print '</a>';
1023  return true;
1024}
1025
1026/**
1027 * This function inserts a 1x1 pixel gif which in reality
1028 * is the inexer function.
1029 *
1030 * Should be called somewhere at the very end of the main.php
1031 * template
1032 */
1033function tpl_indexerWebBug(){
1034  global $ID;
1035  global $INFO;
1036  if(!$INFO['exists']) return false;
1037
1038  if(isHiddenPage($ID)) return false; //no need to index hidden pages
1039
1040  $p = array();
1041  $p['src']    = DOKU_BASE.'lib/exe/indexer.php?id='.rawurlencode($ID).
1042                 '&'.time();
1043  $p['width']  = 1;
1044  $p['height'] = 1;
1045  $p['alt']    = '';
1046  $att = buildAttributes($p);
1047  print "<img $att />";
1048  return true;
1049}
1050
1051// configuration methods
1052/**
1053 * tpl_getConf($id)
1054 *
1055 * use this function to access template configuration variables
1056 */
1057function tpl_getConf($id){
1058  global $conf;
1059  global $tpl_configloaded;
1060
1061  $tpl = $conf['template'];
1062
1063  if (!$tpl_configloaded){
1064    $tconf = tpl_loadConfig();
1065    if ($tconf !== false){
1066      foreach ($tconf as $key => $value){
1067        if (isset($conf['tpl'][$tpl][$key])) continue;
1068        $conf['tpl'][$tpl][$key] = $value;
1069      }
1070      $tpl_configloaded = true;
1071    }
1072  }
1073
1074  return $conf['tpl'][$tpl][$id];
1075}
1076
1077/**
1078 * tpl_loadConfig()
1079 * reads all template configuration variables
1080 * this function is automatically called by tpl_getConf()
1081 */
1082function tpl_loadConfig(){
1083
1084  $file = DOKU_TPLINC.'/conf/default.php';
1085  $conf = array();
1086
1087  if (!@file_exists($file)) return false;
1088
1089  // load default config file
1090  include($file);
1091
1092  return $conf;
1093}
1094
1095/**
1096 * prints the "main content" in the mediamanger popup
1097 *
1098 * Depending on the user's actions this may be a list of
1099 * files in a namespace, the meta editing dialog or
1100 * a message of referencing pages
1101 *
1102 * Only allowed in mediamanager.php
1103 *
1104 * @author Andreas Gohr <andi@splitbrain.org>
1105 */
1106function tpl_mediaContent(){
1107  global $IMG;
1108  global $AUTH;
1109  global $INUSE;
1110  global $NS;
1111  global $JUMPTO;
1112
1113  ptln('<div id="media__content">');
1114  if($_REQUEST['edit']){
1115    media_metaform($IMG,$AUTH);
1116  }elseif(is_array($INUSE)){
1117    media_filesinuse($INUSE,$IMG);
1118  }else{
1119    media_filelist($NS,$AUTH,$JUMPTO);
1120  }
1121  ptln('</div>');
1122}
1123
1124/**
1125 * prints the namespace tree in the mediamanger popup
1126 *
1127 * Only allowed in mediamanager.php
1128 *
1129 * @author Andreas Gohr <andi@splitbrain.org>
1130 */
1131function tpl_mediaTree(){
1132  global $NS;
1133
1134  ptln('<div id="media__tree">');
1135  media_nstree($NS);
1136  ptln('</div>');
1137}
1138
1139//Setup VIM: ex: et ts=4 enc=utf-8 :
1140