xref: /dokuwiki/inc/template.php (revision e9ac0877f6c7eb3536f8f2b6b2a431c00de8fe4f)
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 * Access a template file
13 *
14 * Returns the path to the given file inside the current template, uses
15 * default template if the custom version doesn't exist.
16 *
17 * @author Andreas Gohr <andi@splitbrain.org>
18 * @param string $file
19 * @return string
20 */
21function template($file) {
22    global $conf;
23
24    if(@is_readable(DOKU_INC.'lib/tpl/'.$conf['template'].'/'.$file))
25        return DOKU_INC.'lib/tpl/'.$conf['template'].'/'.$file;
26
27    return DOKU_INC.'lib/tpl/dokuwiki/'.$file;
28}
29
30/**
31 * Convenience function to access template dir from local FS
32 *
33 * This replaces the deprecated DOKU_TPLINC constant
34 *
35 * @author Andreas Gohr <andi@splitbrain.org>
36 * @param string $tpl The template to use, default to current one
37 * @return string
38 */
39function tpl_incdir($tpl='') {
40    global $conf;
41    if(!$tpl) $tpl = $conf['template'];
42    return DOKU_INC.'lib/tpl/'.$tpl.'/';
43}
44
45/**
46 * Convenience function to access template dir from web
47 *
48 * This replaces the deprecated DOKU_TPL constant
49 *
50 * @author Andreas Gohr <andi@splitbrain.org>
51 * @param string $tpl The template to use, default to current one
52 * @return string
53 */
54function tpl_basedir($tpl='') {
55    global $conf;
56    if(!$tpl) $tpl = $conf['template'];
57    return DOKU_BASE.'lib/tpl/'.$tpl.'/';
58}
59
60/**
61 * Print the content
62 *
63 * This function is used for printing all the usual content
64 * (defined by the global $ACT var) by calling the appropriate
65 * outputfunction(s) from html.php
66 *
67 * Everything that doesn't use the main template file isn't
68 * handled by this function. ACL stuff is not done here either.
69 *
70 * @author Andreas Gohr <andi@splitbrain.org>
71 * @triggers TPL_ACT_RENDER
72 * @triggers TPL_CONTENT_DISPLAY
73 * @param bool $prependTOC should the TOC be displayed here?
74 * @return bool true if any output
75 */
76function tpl_content($prependTOC = true) {
77    global $ACT;
78    global $INFO;
79    $INFO['prependTOC'] = $prependTOC;
80
81    ob_start();
82    trigger_event('TPL_ACT_RENDER', $ACT, 'tpl_content_core');
83    $html_output = ob_get_clean();
84    trigger_event('TPL_CONTENT_DISPLAY', $html_output, 'ptln');
85
86    return !empty($html_output);
87}
88
89/**
90 * Default Action of TPL_ACT_RENDER
91 *
92 * @return bool
93 */
94function tpl_content_core() {
95    global $ACT;
96    global $TEXT;
97    global $PRE;
98    global $SUF;
99    global $SUM;
100    global $IDX;
101    global $INPUT;
102
103    switch($ACT) {
104        case 'show':
105            html_show();
106            break;
107        /** @noinspection PhpMissingBreakStatementInspection */
108        case 'locked':
109            html_locked();
110        case 'edit':
111        case 'recover':
112            html_edit();
113            break;
114        case 'preview':
115            html_edit();
116            html_show($TEXT);
117            break;
118        case 'draft':
119            html_draft();
120            break;
121        case 'search':
122            html_search();
123            break;
124        case 'revisions':
125            html_revisions($INPUT->int('first'));
126            break;
127        case 'diff':
128            html_diff();
129            break;
130        case 'recent':
131            $show_changes = $INPUT->str('show_changes');
132            if (empty($show_changes)) {
133                $show_changes = get_doku_pref('show_changes', $show_changes);
134            }
135            html_recent($INPUT->extract('first')->int('first'), $show_changes);
136            break;
137        case 'index':
138            html_index($IDX); #FIXME can this be pulled from globals? is it sanitized correctly?
139            break;
140        case 'backlink':
141            html_backlinks();
142            break;
143        case 'conflict':
144            html_conflict(con($PRE, $TEXT, $SUF), $SUM);
145            html_diff(con($PRE, $TEXT, $SUF), false);
146            break;
147        case 'login':
148            html_login();
149            break;
150        case 'register':
151            html_register();
152            break;
153        case 'resendpwd':
154            html_resendpwd();
155            break;
156        case 'denied':
157            html_denied();
158            break;
159        case 'profile' :
160            html_updateprofile();
161            break;
162        case 'admin':
163            tpl_admin();
164            break;
165        case 'subscribe':
166            tpl_subscribe();
167            break;
168        case 'media':
169            tpl_media();
170            break;
171        default:
172            $evt = new Doku_Event('TPL_ACT_UNKNOWN', $ACT);
173            if($evt->advise_before())
174                msg("Failed to handle command: ".hsc($ACT), -1);
175            $evt->advise_after();
176            unset($evt);
177            return false;
178    }
179    return true;
180}
181
182/**
183 * Places the TOC where the function is called
184 *
185 * If you use this you most probably want to call tpl_content with
186 * a false argument
187 *
188 * @author Andreas Gohr <andi@splitbrain.org>
189 * @param bool $return Should the TOC be returned instead to be printed?
190 * @return string
191 */
192function tpl_toc($return = false) {
193    global $TOC;
194    global $ACT;
195    global $ID;
196    global $REV;
197    global $INFO;
198    global $conf;
199    global $INPUT;
200    $toc = array();
201
202    if(is_array($TOC)) {
203        // if a TOC was prepared in global scope, always use it
204        $toc = $TOC;
205    } elseif(($ACT == 'show' || substr($ACT, 0, 6) == 'export') && !$REV && $INFO['exists']) {
206        // get TOC from metadata, render if neccessary
207        $meta = p_get_metadata($ID, false, METADATA_RENDER_USING_CACHE);
208        if(isset($meta['internal']['toc'])) {
209            $tocok = $meta['internal']['toc'];
210        } else {
211            $tocok = true;
212        }
213        $toc = isset($meta['description']['tableofcontents']) ? $meta['description']['tableofcontents'] : null;
214        if(!$tocok || !is_array($toc) || !$conf['tocminheads'] || count($toc) < $conf['tocminheads']) {
215            $toc = array();
216        }
217    } elseif($ACT == 'admin') {
218        // try to load admin plugin TOC FIXME: duplicates code from tpl_admin
219        $plugin = null;
220        $class  = $INPUT->str('page');
221        if(!empty($class)) {
222            $pluginlist = plugin_list('admin');
223            if(in_array($class, $pluginlist)) {
224                // attempt to load the plugin
225                /** @var $plugin DokuWiki_Admin_Plugin */
226                $plugin = plugin_load('admin', $class);
227            }
228        }
229        if( ($plugin !== null) && (!$plugin->forAdminOnly() || $INFO['isadmin']) ) {
230            $toc = $plugin->getTOC();
231            $TOC = $toc; // avoid later rebuild
232        }
233    }
234
235    trigger_event('TPL_TOC_RENDER', $toc, null, false);
236    $html = html_TOC($toc);
237    if($return) return $html;
238    echo $html;
239    return '';
240}
241
242/**
243 * Handle the admin page contents
244 *
245 * @author Andreas Gohr <andi@splitbrain.org>
246 */
247function tpl_admin() {
248    global $INFO;
249    global $TOC;
250    global $INPUT;
251
252    $plugin = null;
253    $class  = $INPUT->str('page');
254    if(!empty($class)) {
255        $pluginlist = plugin_list('admin');
256
257        if(in_array($class, $pluginlist)) {
258            // attempt to load the plugin
259            /** @var $plugin DokuWiki_Admin_Plugin */
260            $plugin = plugin_load('admin', $class);
261        }
262    }
263
264    if($plugin !== null) {
265        if(!is_array($TOC)) $TOC = $plugin->getTOC(); //if TOC wasn't requested yet
266        if($INFO['prependTOC']) tpl_toc();
267        $plugin->html();
268    } else {
269        html_admin();
270    }
271    return true;
272}
273
274/**
275 * Print the correct HTML meta headers
276 *
277 * This has to go into the head section of your template.
278 *
279 * @author Andreas Gohr <andi@splitbrain.org>
280 * @triggers TPL_METAHEADER_OUTPUT
281 * @param  bool $alt Should feeds and alternative format links be added?
282 * @return bool
283 */
284function tpl_metaheaders($alt = true) {
285    global $ID;
286    global $REV;
287    global $INFO;
288    global $JSINFO;
289    global $ACT;
290    global $QUERY;
291    global $lang;
292    global $conf;
293    global $updateVersion;
294    /** @var Input $INPUT */
295    global $INPUT;
296
297    // prepare the head array
298    $head = array();
299
300    // prepare seed for js and css
301    $tseed   = $updateVersion;
302    $depends = getConfigFiles('main');
303    foreach($depends as $f) $tseed .= @filemtime($f);
304    $tseed   = md5($tseed);
305
306    // the usual stuff
307    $head['meta'][] = array('name'=> 'generator', 'content'=> 'DokuWiki');
308    $head['link'][] = array(
309        'rel' => 'search', 'type'=> 'application/opensearchdescription+xml',
310        'href'=> DOKU_BASE.'lib/exe/opensearch.php', 'title'=> $conf['title']
311    );
312    $head['link'][] = array('rel'=> 'start', 'href'=> DOKU_BASE);
313    if(actionOK('index')) {
314        $head['link'][] = array(
315            'rel'  => 'contents', 'href'=> wl($ID, 'do=index', false, '&'),
316            'title'=> $lang['btn_index']
317        );
318    }
319
320    if($alt) {
321        $head['link'][] = array(
322            'rel'  => 'alternate', 'type'=> 'application/rss+xml',
323            'title'=> $lang['btn_recent'], 'href'=> DOKU_BASE.'feed.php'
324        );
325        $head['link'][] = array(
326            'rel'  => 'alternate', 'type'=> 'application/rss+xml',
327            'title'=> $lang['currentns'],
328            'href' => DOKU_BASE.'feed.php?mode=list&ns='.$INFO['namespace']
329        );
330        if(($ACT == 'show' || $ACT == 'search') && $INFO['writable']) {
331            $head['link'][] = array(
332                'rel'  => 'edit',
333                'title'=> $lang['btn_edit'],
334                'href' => wl($ID, 'do=edit', false, '&')
335            );
336        }
337
338        if($ACT == 'search') {
339            $head['link'][] = array(
340                'rel'  => 'alternate', 'type'=> 'application/rss+xml',
341                'title'=> $lang['searchresult'],
342                'href' => DOKU_BASE.'feed.php?mode=search&q='.$QUERY
343            );
344        }
345
346        if(actionOK('export_xhtml')) {
347            $head['link'][] = array(
348                'rel' => 'alternate', 'type'=> 'text/html', 'title'=> $lang['plainhtml'],
349                'href'=> exportlink($ID, 'xhtml', '', false, '&')
350            );
351        }
352
353        if(actionOK('export_raw')) {
354            $head['link'][] = array(
355                'rel' => 'alternate', 'type'=> 'text/plain', 'title'=> $lang['wikimarkup'],
356                'href'=> exportlink($ID, 'raw', '', false, '&')
357            );
358        }
359    }
360
361    // setup robot tags apropriate for different modes
362    if(($ACT == 'show' || $ACT == 'export_xhtml') && !$REV) {
363        if($INFO['exists']) {
364            //delay indexing:
365            if((time() - $INFO['lastmod']) >= $conf['indexdelay']) {
366                $head['meta'][] = array('name'=> 'robots', 'content'=> 'index,follow');
367            } else {
368                $head['meta'][] = array('name'=> 'robots', 'content'=> 'noindex,nofollow');
369            }
370            $head['link'][] = array('rel'=> 'canonical', 'href'=> wl($ID, '', true, '&'));
371        } else {
372            $head['meta'][] = array('name'=> 'robots', 'content'=> 'noindex,follow');
373        }
374    } elseif(defined('DOKU_MEDIADETAIL')) {
375        $head['meta'][] = array('name'=> 'robots', 'content'=> 'index,follow');
376    } else {
377        $head['meta'][] = array('name'=> 'robots', 'content'=> 'noindex,nofollow');
378    }
379
380    // set metadata
381    if($ACT == 'show' || $ACT == 'export_xhtml') {
382        // date of modification
383        if($REV) {
384            $head['meta'][] = array('name'=> 'date', 'content'=> date('Y-m-d\TH:i:sO', $REV));
385        } else {
386            $head['meta'][] = array('name'=> 'date', 'content'=> date('Y-m-d\TH:i:sO', $INFO['lastmod']));
387        }
388
389        // keywords (explicit or implicit)
390        if(!empty($INFO['meta']['subject'])) {
391            $head['meta'][] = array('name'=> 'keywords', 'content'=> join(',', $INFO['meta']['subject']));
392        } else {
393            $head['meta'][] = array('name'=> 'keywords', 'content'=> str_replace(':', ',', $ID));
394        }
395    }
396
397    // load stylesheets
398    $head['link'][] = array(
399        'rel' => 'stylesheet', 'type'=> 'text/css',
400        'href'=> DOKU_BASE.'lib/exe/css.php?t='.$conf['template'].'&tseed='.$tseed
401    );
402
403    // make $INFO and other vars available to JavaScripts
404    $json   = new JSON();
405    $script = "var NS='".$INFO['namespace']."';";
406    if($conf['useacl'] && $INPUT->server->str('REMOTE_USER')) {
407        $script .= "var SIG='".toolbar_signature()."';";
408    }
409    $script .= 'var JSINFO = '.$json->encode($JSINFO).';';
410    $head['script'][] = array('type'=> 'text/javascript', '_data'=> $script);
411
412    // load external javascript
413    $head['script'][] = array(
414        'type'=> 'text/javascript', 'charset'=> 'utf-8', '_data'=> '',
415        'src' => DOKU_BASE.'lib/exe/js.php'.'?tseed='.$tseed
416    );
417
418    // trigger event here
419    trigger_event('TPL_METAHEADER_OUTPUT', $head, '_tpl_metaheaders_action', true);
420    return true;
421}
422
423/**
424 * prints the array build by tpl_metaheaders
425 *
426 * $data is an array of different header tags. Each tag can have multiple
427 * instances. Attributes are given as key value pairs. Values will be HTML
428 * encoded automatically so they should be provided as is in the $data array.
429 *
430 * For tags having a body attribute specify the the body data in the special
431 * attribute '_data'. This field will NOT BE ESCAPED automatically.
432 *
433 * @author Andreas Gohr <andi@splitbrain.org>
434 */
435function _tpl_metaheaders_action($data) {
436    foreach($data as $tag => $inst) {
437        foreach($inst as $attr) {
438            echo '<', $tag, ' ', buildAttributes($attr);
439            if(isset($attr['_data']) || $tag == 'script') {
440                if($tag == 'script' && $attr['_data'])
441                    $attr['_data'] = "/*<![CDATA[*/".
442                        $attr['_data'].
443                        "\n/*!]]>*/";
444
445                echo '>', $attr['_data'], '</', $tag, '>';
446            } else {
447                echo '/>';
448            }
449            echo "\n";
450        }
451    }
452}
453
454/**
455 * Print a link
456 *
457 * Just builds a link.
458 *
459 * @author Andreas Gohr <andi@splitbrain.org>
460 */
461function tpl_link($url, $name, $more = '', $return = false) {
462    $out = '<a href="'.$url.'" ';
463    if($more) $out .= ' '.$more;
464    $out .= ">$name</a>";
465    if($return) return $out;
466    print $out;
467    return true;
468}
469
470/**
471 * Prints a link to a WikiPage
472 *
473 * Wrapper around html_wikilink
474 *
475 * @author Andreas Gohr <andi@splitbrain.org>
476 */
477function tpl_pagelink($id, $name = null) {
478    print '<bdi>'.html_wikilink($id, $name).'</bdi>';
479    return true;
480}
481
482/**
483 * get the parent page
484 *
485 * Tries to find out which page is parent.
486 * returns false if none is available
487 *
488 * @author Andreas Gohr <andi@splitbrain.org>
489 */
490function tpl_getparent($id) {
491    $parent = getNS($id).':';
492    resolve_pageid('', $parent, $exists);
493    if($parent == $id) {
494        $pos    = strrpos(getNS($id), ':');
495        $parent = substr($parent, 0, $pos).':';
496        resolve_pageid('', $parent, $exists);
497        if($parent == $id) return false;
498    }
499    return $parent;
500}
501
502/**
503 * Print one of the buttons
504 *
505 * @author Adrian Lang <mail@adrianlang.de>
506 * @see    tpl_get_action
507 */
508function tpl_button($type, $return = false) {
509    $data = tpl_get_action($type);
510    if($data === false) {
511        return false;
512    } elseif(!is_array($data)) {
513        $out = sprintf($data, 'button');
514    } else {
515        /**
516         * @var string $accesskey
517         * @var string $id
518         * @var string $method
519         * @var array  $params
520         */
521        extract($data);
522        if($id === '#dokuwiki__top') {
523            $out = html_topbtn();
524        } else {
525            $out = html_btn($type, $id, $accesskey, $params, $method);
526        }
527    }
528    if($return) return $out;
529    echo $out;
530    return true;
531}
532
533/**
534 * Like the action buttons but links
535 *
536 * @author Adrian Lang <mail@adrianlang.de>
537 * @see    tpl_get_action
538 */
539function tpl_actionlink($type, $pre = '', $suf = '', $inner = '', $return = false) {
540    global $lang;
541    $data = tpl_get_action($type);
542    if($data === false) {
543        return false;
544    } elseif(!is_array($data)) {
545        $out = sprintf($data, 'link');
546    } else {
547        /**
548         * @var string $accesskey
549         * @var string $id
550         * @var string $method
551         * @var bool   $nofollow
552         * @var array  $params
553         * @var string $replacement
554         */
555        extract($data);
556        if(strpos($id, '#') === 0) {
557            $linktarget = $id;
558        } else {
559            $linktarget = wl($id, $params);
560        }
561        $caption = $lang['btn_'.$type];
562        if(strpos($caption, '%s')){
563            $caption = sprintf($caption, $replacement);
564        }
565        $akey    = $addTitle = '';
566        if($accesskey) {
567            $akey     = 'accesskey="'.$accesskey.'" ';
568            $addTitle = ' ['.strtoupper($accesskey).']';
569        }
570        $rel = $nofollow ? 'rel="nofollow" ' : '';
571        $out = tpl_link(
572            $linktarget, $pre.(($inner) ? $inner : $caption).$suf,
573            'class="action '.$type.'" '.
574                $akey.$rel.
575                'title="'.hsc($caption).$addTitle.'"', 1
576        );
577    }
578    if($return) return $out;
579    echo $out;
580    return true;
581}
582
583/**
584 * Check the actions and get data for buttons and links
585 *
586 * Available actions are
587 *
588 *  edit        - edit/create/show/draft
589 *  history     - old revisions
590 *  recent      - recent changes
591 *  login       - login/logout - if ACL enabled
592 *  profile     - user profile (if logged in)
593 *  index       - The index
594 *  admin       - admin page - if enough rights
595 *  top         - back to top
596 *  back        - back to parent - if available
597 *  backlink    - links to the list of backlinks
598 *  subscribe/subscription- subscribe/unsubscribe
599 *
600 * @author Andreas Gohr <andi@splitbrain.org>
601 * @author Matthias Grimm <matthiasgrimm@users.sourceforge.net>
602 * @author Adrian Lang <mail@adrianlang.de>
603 * @param string $type
604 * @return array|bool|string
605 */
606function tpl_get_action($type) {
607    global $ID;
608    global $INFO;
609    global $REV;
610    global $ACT;
611    global $conf;
612    /** @var Input $INPUT */
613    global $INPUT;
614
615    // check disabled actions and fix the badly named ones
616    if($type == 'history') $type = 'revisions';
617    if ($type == 'subscription') $type = 'subscribe';
618    if(!actionOK($type)) return false;
619
620    $accesskey   = null;
621    $id          = $ID;
622    $method      = 'get';
623    $params      = array('do' => $type);
624    $nofollow    = true;
625    $replacement = '';
626    switch($type) {
627        case 'edit':
628            // most complicated type - we need to decide on current action
629            if($ACT == 'show' || $ACT == 'search') {
630                $method = 'post';
631                if($INFO['writable']) {
632                    $accesskey = 'e';
633                    if(!empty($INFO['draft'])) {
634                        $type         = 'draft';
635                        $params['do'] = 'draft';
636                    } else {
637                        $params['rev'] = $REV;
638                        if(!$INFO['exists']) {
639                            $type = 'create';
640                        }
641                    }
642                } else {
643                    if(!actionOK('source')) return false; //pseudo action
644                    $params['rev'] = $REV;
645                    $type          = 'source';
646                    $accesskey     = 'v';
647                }
648            } else {
649                $params    = array('do' => '');
650                $type      = 'show';
651                $accesskey = 'v';
652            }
653            break;
654        case 'revisions':
655            $type      = 'revs';
656            $accesskey = 'o';
657            break;
658        case 'recent':
659            $accesskey = 'r';
660            break;
661        case 'index':
662            $accesskey = 'x';
663            // allow searchbots to get to the sitemap from the homepage (when dokuwiki isn't providing a sitemap.xml)
664            if ($conf['start'] == $ID && !$conf['sitemap']) {
665                $nofollow = false;
666            }
667            break;
668        case 'top':
669            $accesskey = 't';
670            $params    = array('do' => '');
671            $id        = '#dokuwiki__top';
672            break;
673        case 'back':
674            $parent = tpl_getparent($ID);
675            if(!$parent) {
676                return false;
677            }
678            $id        = $parent;
679            $params    = array('do' => '');
680            $accesskey = 'b';
681            break;
682        case 'img_backto':
683            $params = array();
684            $accesskey = 'b';
685            $replacement = $ID;
686            break;
687        case 'login':
688            $params['sectok'] = getSecurityToken();
689            if($INPUT->server->has('REMOTE_USER')) {
690                if(!actionOK('logout')) {
691                    return false;
692                }
693                $params['do'] = 'logout';
694                $type         = 'logout';
695            }
696            break;
697        case 'register':
698            if($INPUT->server->str('REMOTE_USER')) {
699                return false;
700            }
701            break;
702        case 'resendpwd':
703            if($INPUT->server->str('REMOTE_USER')) {
704                return false;
705            }
706            break;
707        case 'admin':
708            if(!$INFO['ismanager']) {
709                return false;
710            }
711            break;
712        case 'revert':
713            if(!$INFO['ismanager'] || !$REV || !$INFO['writable']) {
714                return false;
715            }
716            $params['rev']    = $REV;
717            $params['sectok'] = getSecurityToken();
718            break;
719        case 'subscribe':
720            if(!$INPUT->server->str('REMOTE_USER')) {
721                return false;
722            }
723            break;
724        case 'backlink':
725            break;
726        case 'profile':
727            if(!$INPUT->server->has('REMOTE_USER')) {
728                return false;
729            }
730            break;
731        case 'media':
732            $params['ns'] = getNS($ID);
733            break;
734        case 'mediaManager':
735            // View image in media manager
736            global $IMG;
737            $imgNS = getNS($IMG);
738            $authNS = auth_quickaclcheck("$imgNS:*");
739            if ($authNS < AUTH_UPLOAD) {
740                return false;
741            }
742            $params = array(
743                'ns' => $imgNS,
744                'image' => $IMG,
745                'do' => 'media'
746            );
747            //$type = 'media';
748            break;
749        default:
750            return '[unknown %s type]';
751            break;
752    }
753    return compact('accesskey', 'type', 'id', 'method', 'params', 'nofollow', 'replacement');
754}
755
756/**
757 * Wrapper around tpl_button() and tpl_actionlink()
758 *
759 * @author Anika Henke <anika@selfthinker.org>
760 * @param
761 * @param bool   $link link or form button?
762 * @param bool   $wrapper HTML element wrapper
763 * @param bool   $return return or print
764 * @param string $pre prefix for links
765 * @param string $suf suffix for links
766 * @param string $inner inner HTML for links
767 * @return bool|string
768 */
769function tpl_action($type, $link = false, $wrapper = false, $return = false, $pre = '', $suf = '', $inner = '') {
770    $out = '';
771    if($link) {
772        $out .= tpl_actionlink($type, $pre, $suf, $inner, 1);
773    } else {
774        $out .= tpl_button($type, 1);
775    }
776    if($out && $wrapper) $out = "<$wrapper>$out</$wrapper>";
777
778    if($return) return $out;
779    print $out;
780    return $out ? true : false;
781}
782
783/**
784 * Print the search form
785 *
786 * If the first parameter is given a div with the ID 'qsearch_out' will
787 * be added which instructs the ajax pagequicksearch to kick in and place
788 * its output into this div. The second parameter controls the propritary
789 * attribute autocomplete. If set to false this attribute will be set with an
790 * value of "off" to instruct the browser to disable it's own built in
791 * autocompletion feature (MSIE and Firefox)
792 *
793 * @author Andreas Gohr <andi@splitbrain.org>
794 * @param bool $ajax
795 * @param bool $autocomplete
796 * @return bool
797 */
798function tpl_searchform($ajax = true, $autocomplete = true) {
799    global $lang;
800    global $ACT;
801    global $QUERY;
802
803    // don't print the search form if search action has been disabled
804    if(!actionOK('search')) return false;
805
806    print '<form action="'.wl().'" accept-charset="utf-8" class="search" id="dw__search" method="get" role="search"><div class="no">';
807    print '<input type="hidden" name="do" value="search" />';
808    print '<input type="text" ';
809    if($ACT == 'search') print 'value="'.htmlspecialchars($QUERY).'" ';
810    if(!$autocomplete) print 'autocomplete="off" ';
811    print 'id="qsearch__in" accesskey="f" name="id" class="edit" title="[F]" />';
812    print '<input type="submit" value="'.$lang['btn_search'].'" class="button" title="'.$lang['btn_search'].'" />';
813    if($ajax) print '<div id="qsearch__out" class="ajax_qsearch JSpopup"></div>';
814    print '</div></form>';
815    return true;
816}
817
818/**
819 * Print the breadcrumbs trace
820 *
821 * @author Andreas Gohr <andi@splitbrain.org>
822 * @param string $sep Separator between entries
823 * @return bool
824 */
825function tpl_breadcrumbs($sep = '•') {
826    global $lang;
827    global $conf;
828
829    //check if enabled
830    if(!$conf['breadcrumbs']) return false;
831
832    $crumbs = breadcrumbs(); //setup crumb trace
833
834    $crumbs_sep = ' <span class="bcsep">'.$sep.'</span> ';
835
836    //render crumbs, highlight the last one
837    print '<span class="bchead">'.$lang['breadcrumb'].':</span>';
838    $last = count($crumbs);
839    $i    = 0;
840    foreach($crumbs as $id => $name) {
841        $i++;
842        echo $crumbs_sep;
843        if($i == $last) print '<span class="curid">';
844        print '<bdi>';
845        tpl_link(wl($id), hsc($name), 'class="breadcrumbs" title="'.$id.'"');
846        print '</bdi>';
847        if($i == $last) print '</span>';
848    }
849    return true;
850}
851
852/**
853 * Hierarchical breadcrumbs
854 *
855 * This code was suggested as replacement for the usual breadcrumbs.
856 * It only makes sense with a deep site structure.
857 *
858 * @author Andreas Gohr <andi@splitbrain.org>
859 * @author Nigel McNie <oracle.shinoda@gmail.com>
860 * @author Sean Coates <sean@caedmon.net>
861 * @author <fredrik@averpil.com>
862 * @todo   May behave strangely in RTL languages
863 * @param string $sep Separator between entries
864 * @return bool
865 */
866function tpl_youarehere($sep = ' » ') {
867    global $conf;
868    global $ID;
869    global $lang;
870
871    // check if enabled
872    if(!$conf['youarehere']) return false;
873
874    $parts = explode(':', $ID);
875    $count = count($parts);
876
877    echo '<span class="bchead">'.$lang['youarehere'].': </span>';
878
879    // always print the startpage
880    echo '<span class="home">';
881    tpl_pagelink(':'.$conf['start']);
882    echo '</span>';
883
884    // print intermediate namespace links
885    $part = '';
886    for($i = 0; $i < $count - 1; $i++) {
887        $part .= $parts[$i].':';
888        $page = $part;
889        if($page == $conf['start']) continue; // Skip startpage
890
891        // output
892        echo $sep;
893        tpl_pagelink($page);
894    }
895
896    // print current page, skipping start page, skipping for namespace index
897    resolve_pageid('', $page, $exists);
898    if(isset($page) && $page == $part.$parts[$i]) return true;
899    $page = $part.$parts[$i];
900    if($page == $conf['start']) return true;
901    echo $sep;
902    tpl_pagelink($page);
903    return true;
904}
905
906/**
907 * Print info if the user is logged in
908 * and show full name in that case
909 *
910 * Could be enhanced with a profile link in future?
911 *
912 * @author Andreas Gohr <andi@splitbrain.org>
913 * @return bool
914 */
915function tpl_userinfo() {
916    global $lang;
917    global $INFO;
918    /** @var Input $INPUT */
919    global $INPUT;
920
921    if($INPUT->server->str('REMOTE_USER')) {
922        print $lang['loggedinas'].': <bdi>'.hsc($INFO['userinfo']['name']).'</bdi> (<bdi>'.hsc($INPUT->server->str('REMOTE_USER')).'</bdi>)';
923        return true;
924    }
925    return false;
926}
927
928/**
929 * Print some info about the current page
930 *
931 * @author Andreas Gohr <andi@splitbrain.org>
932 * @param bool $ret return content instead of printing it
933 * @return bool|string
934 */
935function tpl_pageinfo($ret = false) {
936    global $conf;
937    global $lang;
938    global $INFO;
939    global $ID;
940
941    // return if we are not allowed to view the page
942    if(!auth_quickaclcheck($ID)) {
943        return false;
944    }
945
946    // prepare date and path
947    $fn = $INFO['filepath'];
948    if(!$conf['fullpath']) {
949        if($INFO['rev']) {
950            $fn = str_replace(fullpath($conf['olddir']).'/', '', $fn);
951        } else {
952            $fn = str_replace(fullpath($conf['datadir']).'/', '', $fn);
953        }
954    }
955    $fn   = utf8_decodeFN($fn);
956    $date = dformat($INFO['lastmod']);
957
958    // print it
959    if($INFO['exists']) {
960        $out = '';
961        $out .= '<bdi>'.$fn.'</bdi>';
962        $out .= ' · ';
963        $out .= $lang['lastmod'];
964        $out .= ': ';
965        $out .= $date;
966        if($INFO['editor']) {
967            $out .= ' '.$lang['by'].' ';
968            $out .= '<bdi>'.editorinfo($INFO['editor']).'</bdi>';
969        } else {
970            $out .= ' ('.$lang['external_edit'].')';
971        }
972        if($INFO['locked']) {
973            $out .= ' · ';
974            $out .= $lang['lockedby'];
975            $out .= ': ';
976            $out .= '<bdi>'.editorinfo($INFO['locked']).'</bdi>';
977        }
978        if($ret) {
979            return $out;
980        } else {
981            echo $out;
982            return true;
983        }
984    }
985    return false;
986}
987
988/**
989 * Prints or returns the name of the given page (current one if none given).
990 *
991 * If useheading is enabled this will use the first headline else
992 * the given ID is used.
993 *
994 * @author Andreas Gohr <andi@splitbrain.org>
995 * @param string $id page id
996 * @param bool   $ret return content instead of printing
997 * @return bool|string
998 */
999function tpl_pagetitle($id = null, $ret = false) {
1000    if(is_null($id)) {
1001        global $ID;
1002        $id = $ID;
1003    }
1004
1005    $name = $id;
1006    if(useHeading('navigation')) {
1007        $title = p_get_first_heading($id);
1008        if($title) $name = $title;
1009    }
1010
1011    if($ret) {
1012        return hsc($name);
1013    } else {
1014        print hsc($name);
1015        return true;
1016    }
1017}
1018
1019/**
1020 * Returns the requested EXIF/IPTC tag from the current image
1021 *
1022 * If $tags is an array all given tags are tried until a
1023 * value is found. If no value is found $alt is returned.
1024 *
1025 * Which texts are known is defined in the functions _exifTagNames
1026 * and _iptcTagNames() in inc/jpeg.php (You need to prepend IPTC
1027 * to the names of the latter one)
1028 *
1029 * Only allowed in: detail.php
1030 *
1031 * @author Andreas Gohr <andi@splitbrain.org>
1032 * @param array  $tags tags to try
1033 * @param string $alt alternative output if no data was found
1034 * @param null   $src the image src, uses global $SRC if not given
1035 * @return string
1036 */
1037function tpl_img_getTag($tags, $alt = '', $src = null) {
1038    // Init Exif Reader
1039    global $SRC;
1040
1041    if(is_null($src)) $src = $SRC;
1042
1043    static $meta = null;
1044    if(is_null($meta)) $meta = new JpegMeta($src);
1045    if($meta === false) return $alt;
1046    $info = $meta->getField($tags);
1047    if($info == false) return $alt;
1048    return $info;
1049}
1050
1051/**
1052 * Returns a description list of the metatags of the current image
1053 *
1054 * @return string html of description list
1055 */
1056function tpl_img_meta() {
1057    global $lang;
1058
1059    $tags = tpl_get_img_meta();
1060
1061    echo '<dl>';
1062    foreach($tags as $tag) {
1063        $label = $lang[$tag['langkey']];
1064        if(!$label) $label = $tag['langkey'];
1065
1066        echo '<dt>'.$label.':</dt><dd>';
1067        if ($tag['type'] == 'date') {
1068            echo dformat($tag['value']);
1069        } else {
1070            echo hsc($tag['value']);
1071        }
1072        echo '</dd>';
1073    }
1074    echo '</dl>';
1075}
1076
1077/**
1078 * Returns metadata as configured in mediameta config file, ready for creating html
1079 *
1080 * @return array with arrays containing the entries:
1081 *   - string langkey  key to lookup in the $lang var, if not found printed as is
1082 *   - string type     type of value
1083 *   - string value    tag value (unescaped)
1084 */
1085function tpl_get_img_meta() {
1086
1087    $config_files = getConfigFiles('mediameta');
1088    foreach ($config_files as $config_file) {
1089        if(@file_exists($config_file)) {
1090            include($config_file);
1091        }
1092    }
1093    /** @var array $fields the included array with metadata */
1094
1095    $tags = array();
1096    foreach($fields as $tag){
1097        $t = array();
1098        if (!empty($tag[0])) {
1099            $t = array($tag[0]);
1100        }
1101        if(is_array($tag[3])) {
1102            $t = array_merge($t,$tag[3]);
1103        }
1104        $value = tpl_img_getTag($t);
1105        if ($value) {
1106            $tags[] = array('langkey' => $tag[1], 'type' => $tag[2], 'value' => $value);
1107        }
1108    }
1109    return $tags;
1110}
1111
1112/**
1113 * Prints the image with a link to the full sized version
1114 *
1115 * Only allowed in: detail.php
1116 *
1117 * @triggers TPL_IMG_DISPLAY
1118 * @param $maxwidth  int - maximal width of the image
1119 * @param $maxheight int - maximal height of the image
1120 * @param $link bool     - link to the orginal size?
1121 * @param $params array  - additional image attributes
1122 * @return mixed Result of TPL_IMG_DISPLAY
1123 */
1124function tpl_img($maxwidth = 0, $maxheight = 0, $link = true, $params = null) {
1125    global $IMG;
1126    /** @var Input $INPUT */
1127    global $INPUT;
1128    $w = tpl_img_getTag('File.Width');
1129    $h = tpl_img_getTag('File.Height');
1130
1131    //resize to given max values
1132    $ratio = 1;
1133    if($w >= $h) {
1134        if($maxwidth && $w >= $maxwidth) {
1135            $ratio = $maxwidth / $w;
1136        } elseif($maxheight && $h > $maxheight) {
1137            $ratio = $maxheight / $h;
1138        }
1139    } else {
1140        if($maxheight && $h >= $maxheight) {
1141            $ratio = $maxheight / $h;
1142        } elseif($maxwidth && $w > $maxwidth) {
1143            $ratio = $maxwidth / $w;
1144        }
1145    }
1146    if($ratio) {
1147        $w = floor($ratio * $w);
1148        $h = floor($ratio * $h);
1149    }
1150
1151    //prepare URLs
1152    $url = ml($IMG, array('cache'=> $INPUT->str('cache')), true, '&');
1153    $src = ml($IMG, array('cache'=> $INPUT->str('cache'), 'w'=> $w, 'h'=> $h), true, '&');
1154
1155    //prepare attributes
1156    $alt = tpl_img_getTag('Simple.Title');
1157    if(is_null($params)) {
1158        $p = array();
1159    } else {
1160        $p = $params;
1161    }
1162    if($w) $p['width'] = $w;
1163    if($h) $p['height'] = $h;
1164    $p['class'] = 'img_detail';
1165    if($alt) {
1166        $p['alt']   = $alt;
1167        $p['title'] = $alt;
1168    } else {
1169        $p['alt'] = '';
1170    }
1171    $p['src'] = $src;
1172
1173    $data = array('url'=> ($link ? $url : null), 'params'=> $p);
1174    return trigger_event('TPL_IMG_DISPLAY', $data, '_tpl_img_action', true);
1175}
1176
1177/**
1178 * Default action for TPL_IMG_DISPLAY
1179 *
1180 * @param array $data
1181 * @return bool
1182 */
1183function _tpl_img_action($data) {
1184    global $lang;
1185    $p = buildAttributes($data['params']);
1186
1187    if($data['url']) print '<a href="'.hsc($data['url']).'" title="'.$lang['mediaview'].'">';
1188    print '<img '.$p.'/>';
1189    if($data['url']) print '</a>';
1190    return true;
1191}
1192
1193/**
1194 * This function inserts a small gif which in reality is the indexer function.
1195 *
1196 * Should be called somewhere at the very end of the main.php
1197 * template
1198 *
1199 * @return bool
1200 */
1201function tpl_indexerWebBug() {
1202    global $ID;
1203
1204    $p           = array();
1205    $p['src']    = DOKU_BASE.'lib/exe/indexer.php?id='.rawurlencode($ID).
1206        '&'.time();
1207    $p['width']  = 2; //no more 1x1 px image because we live in times of ad blockers...
1208    $p['height'] = 1;
1209    $p['alt']    = '';
1210    $att         = buildAttributes($p);
1211    print "<img $att />";
1212    return true;
1213}
1214
1215/**
1216 * tpl_getConf($id)
1217 *
1218 * use this function to access template configuration variables
1219 *
1220 * @param string $id      name of the value to access
1221 * @param mixed  $notset  what to return if the setting is not available
1222 * @return mixed
1223 */
1224function tpl_getConf($id, $notset=false) {
1225    global $conf;
1226    static $tpl_configloaded = false;
1227
1228    $tpl = $conf['template'];
1229
1230    if(!$tpl_configloaded) {
1231        $tconf = tpl_loadConfig();
1232        if($tconf !== false) {
1233            foreach($tconf as $key => $value) {
1234                if(isset($conf['tpl'][$tpl][$key])) continue;
1235                $conf['tpl'][$tpl][$key] = $value;
1236            }
1237            $tpl_configloaded = true;
1238        }
1239    }
1240
1241    if(isset($conf['tpl'][$tpl][$id])){
1242        return $conf['tpl'][$tpl][$id];
1243    }
1244
1245    return $notset;
1246}
1247
1248/**
1249 * tpl_loadConfig()
1250 *
1251 * reads all template configuration variables
1252 * this function is automatically called by tpl_getConf()
1253 *
1254 * @return array
1255 */
1256function tpl_loadConfig() {
1257
1258    $file = tpl_incdir().'/conf/default.php';
1259    $conf = array();
1260
1261    if(!@file_exists($file)) return false;
1262
1263    // load default config file
1264    include($file);
1265
1266    return $conf;
1267}
1268
1269// language methods
1270/**
1271 * tpl_getLang($id)
1272 *
1273 * use this function to access template language variables
1274 */
1275function tpl_getLang($id) {
1276    static $lang = array();
1277
1278    if(count($lang) === 0) {
1279        $path = tpl_incdir().'lang/';
1280
1281        $lang = array();
1282
1283        global $conf; // definitely don't invoke "global $lang"
1284        // don't include once
1285        @include($path.'en/lang.php');
1286        if($conf['lang'] != 'en') @include($path.$conf['lang'].'/lang.php');
1287    }
1288
1289    return $lang[$id];
1290}
1291
1292/**
1293 * Retrieve a language dependent file and pass to xhtml renderer for display
1294 * template equivalent of p_locale_xhtml()
1295 *
1296 * @param   string $id id of language dependent wiki page
1297 * @return  string     parsed contents of the wiki page in xhtml format
1298 */
1299function tpl_locale_xhtml($id) {
1300    return p_cached_output(tpl_localeFN($id));
1301}
1302
1303/**
1304 * Prepends appropriate path for a language dependent filename
1305 */
1306function tpl_localeFN($id) {
1307    $path = tpl_incdir().'lang/';
1308    global $conf;
1309    $file = DOKU_CONF.'/template_lang/'.$conf['template'].'/'.$conf['lang'].'/'.$id.'.txt';
1310    if (!@file_exists($file)){
1311        $file = $path.$conf['lang'].'/'.$id.'.txt';
1312        if(!@file_exists($file)){
1313            //fall back to english
1314            $file = $path.'en/'.$id.'.txt';
1315        }
1316    }
1317    return $file;
1318}
1319
1320/**
1321 * prints the "main content" in the mediamanger popup
1322 *
1323 * Depending on the user's actions this may be a list of
1324 * files in a namespace, the meta editing dialog or
1325 * a message of referencing pages
1326 *
1327 * Only allowed in mediamanager.php
1328 *
1329 * @triggers MEDIAMANAGER_CONTENT_OUTPUT
1330 * @param bool $fromajax - set true when calling this function via ajax
1331 * @author Andreas Gohr <andi@splitbrain.org>
1332 */
1333function tpl_mediaContent($fromajax = false, $sort='natural') {
1334    global $IMG;
1335    global $AUTH;
1336    global $INUSE;
1337    global $NS;
1338    global $JUMPTO;
1339    /** @var Input $INPUT */
1340    global $INPUT;
1341
1342    $do = $INPUT->extract('do')->str('do');
1343    if(in_array($do, array('save', 'cancel'))) $do = '';
1344
1345    if(!$do) {
1346        if($INPUT->bool('edit')) {
1347            $do = 'metaform';
1348        } elseif(is_array($INUSE)) {
1349            $do = 'filesinuse';
1350        } else {
1351            $do = 'filelist';
1352        }
1353    }
1354
1355    // output the content pane, wrapped in an event.
1356    if(!$fromajax) ptln('<div id="media__content">');
1357    $data = array('do' => $do);
1358    $evt  = new Doku_Event('MEDIAMANAGER_CONTENT_OUTPUT', $data);
1359    if($evt->advise_before()) {
1360        $do = $data['do'];
1361        if($do == 'filesinuse') {
1362            media_filesinuse($INUSE, $IMG);
1363        } elseif($do == 'filelist') {
1364            media_filelist($NS, $AUTH, $JUMPTO,false,$sort);
1365        } elseif($do == 'searchlist') {
1366            media_searchlist($INPUT->str('q'), $NS, $AUTH);
1367        } else {
1368            msg('Unknown action '.hsc($do), -1);
1369        }
1370    }
1371    $evt->advise_after();
1372    unset($evt);
1373    if(!$fromajax) ptln('</div>');
1374
1375}
1376
1377/**
1378 * Prints the central column in full-screen media manager
1379 * Depending on the opened tab this may be a list of
1380 * files in a namespace, upload form or search form
1381 *
1382 * @author Kate Arzamastseva <pshns@ukr.net>
1383 */
1384function tpl_mediaFileList() {
1385    global $AUTH;
1386    global $NS;
1387    global $JUMPTO;
1388    global $lang;
1389    /** @var Input $INPUT */
1390    global $INPUT;
1391
1392    $opened_tab = $INPUT->str('tab_files');
1393    if(!$opened_tab || !in_array($opened_tab, array('files', 'upload', 'search'))) $opened_tab = 'files';
1394    if($INPUT->str('mediado') == 'update') $opened_tab = 'upload';
1395
1396    echo '<h2 class="a11y">'.$lang['mediaselect'].'</h2>'.NL;
1397
1398    media_tabs_files($opened_tab);
1399
1400    echo '<div class="panelHeader">'.NL;
1401    echo '<h3>';
1402    $tabTitle = ($NS) ? $NS : '['.$lang['mediaroot'].']';
1403    printf($lang['media_'.$opened_tab], '<strong>'.hsc($tabTitle).'</strong>');
1404    echo '</h3>'.NL;
1405    if($opened_tab === 'search' || $opened_tab === 'files') {
1406        media_tab_files_options();
1407    }
1408    echo '</div>'.NL;
1409
1410    echo '<div class="panelContent">'.NL;
1411    if($opened_tab == 'files') {
1412        media_tab_files($NS, $AUTH, $JUMPTO);
1413    } elseif($opened_tab == 'upload') {
1414        media_tab_upload($NS, $AUTH, $JUMPTO);
1415    } elseif($opened_tab == 'search') {
1416        media_tab_search($NS, $AUTH);
1417    }
1418    echo '</div>'.NL;
1419}
1420
1421/**
1422 * Prints the third column in full-screen media manager
1423 * Depending on the opened tab this may be details of the
1424 * selected file, the meta editing dialog or
1425 * list of file revisions
1426 *
1427 * @author Kate Arzamastseva <pshns@ukr.net>
1428 */
1429function tpl_mediaFileDetails($image, $rev) {
1430    global $AUTH, $NS, $conf, $DEL, $lang;
1431    /** @var Input $INPUT */
1432    global $INPUT;
1433
1434    $removed = (!file_exists(mediaFN($image)) && file_exists(mediaMetaFN($image, '.changes')) && $conf['mediarevisions']);
1435    if(!$image || (!file_exists(mediaFN($image)) && !$removed) || $DEL) return;
1436    if($rev && !file_exists(mediaFN($image, $rev))) $rev = false;
1437    if(isset($NS) && getNS($image) != $NS) return;
1438    $do = $INPUT->str('mediado');
1439
1440    $opened_tab = $INPUT->str('tab_details');
1441
1442    $tab_array = array('view');
1443    list(, $mime) = mimetype($image);
1444    if($mime == 'image/jpeg') {
1445        $tab_array[] = 'edit';
1446    }
1447    if($conf['mediarevisions']) {
1448        $tab_array[] = 'history';
1449    }
1450
1451    if(!$opened_tab || !in_array($opened_tab, $tab_array)) $opened_tab = 'view';
1452    if($INPUT->bool('edit')) $opened_tab = 'edit';
1453    if($do == 'restore') $opened_tab = 'view';
1454
1455    media_tabs_details($image, $opened_tab);
1456
1457    echo '<div class="panelHeader"><h3>';
1458    list($ext) = mimetype($image, false);
1459    $class    = preg_replace('/[^_\-a-z0-9]+/i', '_', $ext);
1460    $class    = 'select mediafile mf_'.$class;
1461    $tabTitle = '<strong><a href="'.ml($image).'" class="'.$class.'" title="'.$lang['mediaview'].'">'.$image.'</a>'.'</strong>';
1462    if($opened_tab === 'view' && $rev) {
1463        printf($lang['media_viewold'], $tabTitle, dformat($rev));
1464    } else {
1465        printf($lang['media_'.$opened_tab], $tabTitle);
1466    }
1467
1468    echo '</h3></div>'.NL;
1469
1470    echo '<div class="panelContent">'.NL;
1471
1472    if($opened_tab == 'view') {
1473        media_tab_view($image, $NS, $AUTH, $rev);
1474
1475    } elseif($opened_tab == 'edit' && !$removed) {
1476        media_tab_edit($image, $NS, $AUTH);
1477
1478    } elseif($opened_tab == 'history' && $conf['mediarevisions']) {
1479        media_tab_history($image, $NS, $AUTH);
1480    }
1481
1482    echo '</div>'.NL;
1483}
1484
1485/**
1486 * prints the namespace tree in the mediamanger popup
1487 *
1488 * Only allowed in mediamanager.php
1489 *
1490 * @author Andreas Gohr <andi@splitbrain.org>
1491 */
1492function tpl_mediaTree() {
1493    global $NS;
1494    ptln('<div id="media__tree">');
1495    media_nstree($NS);
1496    ptln('</div>');
1497}
1498
1499/**
1500 * Print a dropdown menu with all DokuWiki actions
1501 *
1502 * Note: this will not use any pretty URLs
1503 *
1504 * @author Andreas Gohr <andi@splitbrain.org>
1505 */
1506function tpl_actiondropdown($empty = '', $button = '&gt;') {
1507    global $ID;
1508    global $REV;
1509    global $lang;
1510    /** @var Input $INPUT */
1511    global $INPUT;
1512
1513    echo '<form action="'.script().'" method="get" accept-charset="utf-8">';
1514    echo '<div class="no">';
1515    echo '<input type="hidden" name="id" value="'.$ID.'" />';
1516    if($REV) echo '<input type="hidden" name="rev" value="'.$REV.'" />';
1517    if ($INPUT->server->str('REMOTE_USER')) {
1518        echo '<input type="hidden" name="sectok" value="'.getSecurityToken().'" />';
1519    }
1520
1521    echo '<select name="do" class="edit quickselect" title="'.$lang['tools'].'">';
1522    echo '<option value="">'.$empty.'</option>';
1523
1524    echo '<optgroup label="'.$lang['page_tools'].'">';
1525    $act = tpl_get_action('edit');
1526    if($act) echo '<option value="'.$act['params']['do'].'">'.$lang['btn_'.$act['type']].'</option>';
1527
1528    $act = tpl_get_action('revert');
1529    if($act) echo '<option value="'.$act['params']['do'].'">'.$lang['btn_'.$act['type']].'</option>';
1530
1531    $act = tpl_get_action('revisions');
1532    if($act) echo '<option value="'.$act['params']['do'].'">'.$lang['btn_'.$act['type']].'</option>';
1533
1534    $act = tpl_get_action('backlink');
1535    if($act) echo '<option value="'.$act['params']['do'].'">'.$lang['btn_'.$act['type']].'</option>';
1536
1537    $act = tpl_get_action('subscribe');
1538    if($act) echo '<option value="'.$act['params']['do'].'">'.$lang['btn_'.$act['type']].'</option>';
1539    echo '</optgroup>';
1540
1541    echo '<optgroup label="'.$lang['site_tools'].'">';
1542    $act = tpl_get_action('recent');
1543    if($act) echo '<option value="'.$act['params']['do'].'">'.$lang['btn_'.$act['type']].'</option>';
1544
1545    $act = tpl_get_action('media');
1546    if($act) echo '<option value="'.$act['params']['do'].'">'.$lang['btn_'.$act['type']].'</option>';
1547
1548    $act = tpl_get_action('index');
1549    if($act) echo '<option value="'.$act['params']['do'].'">'.$lang['btn_'.$act['type']].'</option>';
1550    echo '</optgroup>';
1551
1552    echo '<optgroup label="'.$lang['user_tools'].'">';
1553    $act = tpl_get_action('login');
1554    if($act) echo '<option value="'.$act['params']['do'].'">'.$lang['btn_'.$act['type']].'</option>';
1555
1556    $act = tpl_get_action('register');
1557    if($act) echo '<option value="'.$act['params']['do'].'">'.$lang['btn_'.$act['type']].'</option>';
1558
1559    $act = tpl_get_action('profile');
1560    if($act) echo '<option value="'.$act['params']['do'].'">'.$lang['btn_'.$act['type']].'</option>';
1561
1562    $act = tpl_get_action('admin');
1563    if($act) echo '<option value="'.$act['params']['do'].'">'.$lang['btn_'.$act['type']].'</option>';
1564    echo '</optgroup>';
1565
1566    echo '</select>';
1567    echo '<input type="submit" value="'.$button.'" />';
1568    echo '</div>';
1569    echo '</form>';
1570}
1571
1572/**
1573 * Print a informational line about the used license
1574 *
1575 * @author Andreas Gohr <andi@splitbrain.org>
1576 * @param  string $img     print image? (|button|badge)
1577 * @param  bool   $imgonly skip the textual description?
1578 * @param  bool   $return  when true don't print, but return HTML
1579 * @param  bool   $wrap    wrap in div with class="license"?
1580 * @return string
1581 */
1582function tpl_license($img = 'badge', $imgonly = false, $return = false, $wrap = true) {
1583    global $license;
1584    global $conf;
1585    global $lang;
1586    if(!$conf['license']) return '';
1587    if(!is_array($license[$conf['license']])) return '';
1588    $lic    = $license[$conf['license']];
1589    $target = ($conf['target']['extern']) ? ' target="'.$conf['target']['extern'].'"' : '';
1590
1591    $out = '';
1592    if($wrap) $out .= '<div class="license">';
1593    if($img) {
1594        $src = license_img($img);
1595        if($src) {
1596            $out .= '<a href="'.$lic['url'].'" rel="license"'.$target;
1597            $out .= '><img src="'.DOKU_BASE.$src.'" alt="'.$lic['name'].'" /></a>';
1598            if(!$imgonly) $out .= ' ';
1599        }
1600    }
1601    if(!$imgonly) {
1602        $out .= $lang['license'].' ';
1603        $out .= '<bdi><a href="'.$lic['url'].'" rel="license" class="urlextern"'.$target;
1604        $out .= '>'.$lic['name'].'</a></bdi>';
1605    }
1606    if($wrap) $out .= '</div>';
1607
1608    if($return) return $out;
1609    echo $out;
1610    return '';
1611}
1612
1613/**
1614 * Includes the rendered HTML of a given page
1615 *
1616 * This function is useful to populate sidebars or similar features in a
1617 * template
1618 */
1619function tpl_include_page($pageid, $print = true, $propagate = false) {
1620    if (!$pageid) return false;
1621    if ($propagate) $pageid = page_findnearest($pageid);
1622
1623    global $TOC;
1624    $oldtoc = $TOC;
1625    $html   = p_wiki_xhtml($pageid, '', false);
1626    $TOC    = $oldtoc;
1627
1628    if(!$print) return $html;
1629    echo $html;
1630    return $html;
1631}
1632
1633/**
1634 * Display the subscribe form
1635 *
1636 * @author Adrian Lang <lang@cosmocode.de>
1637 */
1638function tpl_subscribe() {
1639    global $INFO;
1640    global $ID;
1641    global $lang;
1642    global $conf;
1643    $stime_days = $conf['subscribe_time'] / 60 / 60 / 24;
1644
1645    echo p_locale_xhtml('subscr_form');
1646    echo '<h2>'.$lang['subscr_m_current_header'].'</h2>';
1647    echo '<div class="level2">';
1648    if($INFO['subscribed'] === false) {
1649        echo '<p>'.$lang['subscr_m_not_subscribed'].'</p>';
1650    } else {
1651        echo '<ul>';
1652        foreach($INFO['subscribed'] as $sub) {
1653            echo '<li><div class="li">';
1654            if($sub['target'] !== $ID) {
1655                echo '<code class="ns">'.hsc(prettyprint_id($sub['target'])).'</code>';
1656            } else {
1657                echo '<code class="page">'.hsc(prettyprint_id($sub['target'])).'</code>';
1658            }
1659            $sstl = sprintf($lang['subscr_style_'.$sub['style']], $stime_days);
1660            if(!$sstl) $sstl = hsc($sub['style']);
1661            echo ' ('.$sstl.') ';
1662
1663            echo '<a href="'.wl(
1664                $ID,
1665                array(
1666                     'do'        => 'subscribe',
1667                     'sub_target'=> $sub['target'],
1668                     'sub_style' => $sub['style'],
1669                     'sub_action'=> 'unsubscribe',
1670                     'sectok'    => getSecurityToken()
1671                )
1672            ).
1673                '" class="unsubscribe">'.$lang['subscr_m_unsubscribe'].
1674                '</a></div></li>';
1675        }
1676        echo '</ul>';
1677    }
1678    echo '</div>';
1679
1680    // Add new subscription form
1681    echo '<h2>'.$lang['subscr_m_new_header'].'</h2>';
1682    echo '<div class="level2">';
1683    $ns      = getNS($ID).':';
1684    $targets = array(
1685        $ID => '<code class="page">'.prettyprint_id($ID).'</code>',
1686        $ns => '<code class="ns">'.prettyprint_id($ns).'</code>',
1687    );
1688    $styles  = array(
1689        'every'  => $lang['subscr_style_every'],
1690        'digest' => sprintf($lang['subscr_style_digest'], $stime_days),
1691        'list'   => sprintf($lang['subscr_style_list'], $stime_days),
1692    );
1693
1694    $form = new Doku_Form(array('id' => 'subscribe__form'));
1695    $form->startFieldset($lang['subscr_m_subscribe']);
1696    $form->addRadioSet('sub_target', $targets);
1697    $form->startFieldset($lang['subscr_m_receive']);
1698    $form->addRadioSet('sub_style', $styles);
1699    $form->addHidden('sub_action', 'subscribe');
1700    $form->addHidden('do', 'subscribe');
1701    $form->addHidden('id', $ID);
1702    $form->endFieldset();
1703    $form->addElement(form_makeButton('submit', 'subscribe', $lang['subscr_m_subscribe']));
1704    html_form('SUBSCRIBE', $form);
1705    echo '</div>';
1706}
1707
1708/**
1709 * Tries to send already created content right to the browser
1710 *
1711 * Wraps around ob_flush() and flush()
1712 *
1713 * @author Andreas Gohr <andi@splitbrain.org>
1714 */
1715function tpl_flush() {
1716    ob_flush();
1717    flush();
1718}
1719
1720/**
1721 * Tries to find a ressource file in the given locations.
1722 *
1723 * If a given location starts with a colon it is assumed to be a media
1724 * file, otherwise it is assumed to be relative to the current template
1725 *
1726 * @param  array $search       locations to look at
1727 * @param  bool  $abs           if to use absolute URL
1728 * @param  array &$imginfo   filled with getimagesize()
1729 * @return string
1730 * @author Andreas  Gohr <andi@splitbrain.org>
1731 */
1732function tpl_getMediaFile($search, $abs = false, &$imginfo = null) {
1733    $img     = '';
1734    $file    = '';
1735    $ismedia = false;
1736    // loop through candidates until a match was found:
1737    foreach($search as $img) {
1738        if(substr($img, 0, 1) == ':') {
1739            $file    = mediaFN($img);
1740            $ismedia = true;
1741        } else {
1742            $file    = tpl_incdir().$img;
1743            $ismedia = false;
1744        }
1745
1746        if(file_exists($file)) break;
1747    }
1748
1749    // fetch image data if requested
1750    if(!is_null($imginfo)) {
1751        $imginfo = getimagesize($file);
1752    }
1753
1754    // build URL
1755    if($ismedia) {
1756        $url = ml($img, '', true, '', $abs);
1757    } else {
1758        $url = tpl_basedir().$img;
1759        if($abs) $url = DOKU_URL.substr($url, strlen(DOKU_REL));
1760    }
1761
1762    return $url;
1763}
1764
1765/**
1766 * PHP include a file
1767 *
1768 * either from the conf directory if it exists, otherwise use
1769 * file in the template's root directory.
1770 *
1771 * The function honours config cascade settings and looks for the given
1772 * file next to the ´main´ config files, in the order protected, local,
1773 * default.
1774 *
1775 * Note: no escaping or sanity checking is done here. Never pass user input
1776 * to this function!
1777 *
1778 * @author Anika Henke <anika@selfthinker.org>
1779 * @author Andreas Gohr <andi@splitbrain.org>
1780 */
1781function tpl_includeFile($file) {
1782    global $config_cascade;
1783    foreach(array('protected', 'local', 'default') as $config_group) {
1784        if(empty($config_cascade['main'][$config_group])) continue;
1785        foreach($config_cascade['main'][$config_group] as $conf_file) {
1786            $dir = dirname($conf_file);
1787            if(file_exists("$dir/$file")) {
1788                include("$dir/$file");
1789                return;
1790            }
1791        }
1792    }
1793
1794    // still here? try the template dir
1795    $file = tpl_incdir().$file;
1796    if(file_exists($file)) {
1797        include($file);
1798    }
1799}
1800
1801/**
1802 * Returns <link> tag for various icon types (favicon|mobile|generic)
1803 *
1804 * @author Anika Henke <anika@selfthinker.org>
1805 * @param  array $types - list of icon types to display (favicon|mobile|generic)
1806 * @return string
1807 */
1808function tpl_favicon($types = array('favicon')) {
1809
1810    $return = '';
1811
1812    foreach($types as $type) {
1813        switch($type) {
1814            case 'favicon':
1815                $look = array(':wiki:favicon.ico', ':favicon.ico', 'images/favicon.ico');
1816                $return .= '<link rel="shortcut icon" href="'.tpl_getMediaFile($look).'" />'.NL;
1817                break;
1818            case 'mobile':
1819                $look = array(':wiki:apple-touch-icon.png', ':apple-touch-icon.png', 'images/apple-touch-icon.png');
1820                $return .= '<link rel="apple-touch-icon" href="'.tpl_getMediaFile($look).'" />'.NL;
1821                break;
1822            case 'generic':
1823                // ideal world solution, which doesn't work in any browser yet
1824                $look = array(':wiki:favicon.svg', ':favicon.svg', 'images/favicon.svg');
1825                $return .= '<link rel="icon" href="'.tpl_getMediaFile($look).'" type="image/svg+xml" />'.NL;
1826                break;
1827        }
1828    }
1829
1830    return $return;
1831}
1832
1833/**
1834 * Prints full-screen media manager
1835 *
1836 * @author Kate Arzamastseva <pshns@ukr.net>
1837 */
1838function tpl_media() {
1839    global $NS, $IMG, $JUMPTO, $REV, $lang, $fullscreen, $INPUT;
1840    $fullscreen = true;
1841    require_once DOKU_INC.'lib/exe/mediamanager.php';
1842
1843    $rev   = '';
1844    $image = cleanID($INPUT->str('image'));
1845    if(isset($IMG)) $image = $IMG;
1846    if(isset($JUMPTO)) $image = $JUMPTO;
1847    if(isset($REV) && !$JUMPTO) $rev = $REV;
1848
1849    echo '<div id="mediamanager__page">'.NL;
1850    echo '<h1>'.$lang['btn_media'].'</h1>'.NL;
1851    html_msgarea();
1852
1853    echo '<div class="panel namespaces">'.NL;
1854    echo '<h2>'.$lang['namespaces'].'</h2>'.NL;
1855    echo '<div class="panelHeader">';
1856    echo $lang['media_namespaces'];
1857    echo '</div>'.NL;
1858
1859    echo '<div class="panelContent" id="media__tree">'.NL;
1860    media_nstree($NS);
1861    echo '</div>'.NL;
1862    echo '</div>'.NL;
1863
1864    echo '<div class="panel filelist">'.NL;
1865    tpl_mediaFileList();
1866    echo '</div>'.NL;
1867
1868    echo '<div class="panel file">'.NL;
1869    echo '<h2 class="a11y">'.$lang['media_file'].'</h2>'.NL;
1870    tpl_mediaFileDetails($image, $rev);
1871    echo '</div>'.NL;
1872
1873    echo '</div>'.NL;
1874}
1875
1876/**
1877 * Return useful layout classes
1878 *
1879 * @author Anika Henke <anika@selfthinker.org>
1880 */
1881function tpl_classes() {
1882    global $ACT, $conf, $ID, $INFO;
1883    /** @var Input $INPUT */
1884    global $INPUT;
1885
1886    $classes = array(
1887        'dokuwiki',
1888        'mode_'.$ACT,
1889        'tpl_'.$conf['template'],
1890        $INPUT->server->bool('REMOTE_USER') ? 'loggedIn' : '',
1891        $INFO['exists'] ? '' : 'notFound',
1892        ($ID == $conf['start']) ? 'home' : '',
1893    );
1894    return join(' ', $classes);
1895}
1896
1897//Setup VIM: ex: et ts=4 :
1898
1899