1<?php
2/**
3 * Overwriting DokuWiki template functions
4 *
5 * @license    GPL 2 (http://www.gnu.org/licenses/gpl.html)
6 * @author     Sascha Leib <sascha@leib.be>
7 * @author     Andreas Gohr <andi@splitbrain.org>
8 */
9
10use dokuwiki\Extension\Event;
11use dokuwiki\File\PageResolver;
12
13/**
14 * Print the specific HTML meta headers
15 *
16 * Overrides the original version by modifying the headers and the way it is printed
17 *
18 * @author Sascha Leib <sascha@leib.be>
19 * @author Andreas Gohr <andi@splitbrain.org>
20 *
21 * @triggers TPL_METAHEADER_OUTPUT
22 * @param  bool $alt Should feeds and alternative format links be added?
23 * @return bool
24 */
25function my_metaheaders($alt = true) {
26    global $ID;
27    global $REV;
28    global $INFO;
29    global $JSINFO;
30    global $ACT;
31    global $QUERY;
32    global $lang;
33    global $conf;
34    global $updateVersion;
35    /** @var Input $INPUT */
36    global $INPUT;
37
38    // prepare the head array
39    $head = array();
40
41    // prepare seed for js and css
42    $tseed   = $updateVersion;
43    $depends = getConfigFiles('main');
44    $depends[] = DOKU_CONF."tpl/".$conf['template']."/style.ini";
45    foreach($depends as $f) $tseed .= @filemtime($f);
46    $tseed   = md5($tseed);
47
48	// Open Graph information
49	$meta = p_get_metadata($ID);
50	if (is_array($meta) && array_key_exists('title', $meta) && $meta['title'] !== null) {
51		$head['meta'][] = array('property' => 'og:title', 'content' => tpl_pagetitle($ID, true));
52		$head['meta'][] = array('property' => 'og:site_name ', 'content' => $conf['title']);
53		$head['meta'][] = array('property' => 'og:type', 'content' => 'website');
54		$head['meta'][] = array('property' => 'og:url', 'content' => wl($ID, '', true, '&'));
55
56		if (array_key_exists('description', $meta) && is_array($meta['description'])) {
57			if (array_key_exists('abstract', $meta['description'])) {
58				$parts = explode("\n", $meta['description']['abstract']);
59
60				if (is_array($parts) && array_key_exists(2, $parts)) {
61					$head['meta'][] = array('property' => 'og:description', 'content' => $parts[2]);
62
63					// Bing insists in a non-og description:
64					$head['meta'][] = array('name' => 'description', 'content' => $parts[2]);
65				}
66			}
67		}
68	}
69
70    // the usual stuff
71    $head['meta'][] = array('name'=> 'generator', 'content'=> 'DokuWiki');
72    if(actionOK('search')) {
73        $head['link'][] = array(
74            'rel' => 'search', 'type'=> 'application/opensearchdescription+xml',
75            'href'=> DOKU_BASE.'lib/exe/opensearch.php', 'title'=> $conf['title']
76        );
77    }
78
79    $head['link'][] = array('rel'=> 'start', 'href'=> DOKU_BASE);
80    if(actionOK('index')) {
81        $head['link'][] = array(
82            'rel'  => 'contents', 'href'=> wl($ID, 'do=index', false, '&'),
83            'title'=> $lang['btn_index']
84        );
85    }
86
87    if (actionOK('manifest')) {
88        $head['link'][] = array('rel'=> 'manifest', 'href'=> DOKU_BASE.'lib/exe/manifest.php');
89    }
90
91    $styleUtil = new \dokuwiki\StyleUtils();
92    $styleIni = $styleUtil->cssStyleini();
93    $replacements = $styleIni['replacements'];
94    if (!empty($replacements['__theme_color__'])) {
95        $head['meta'][] = array(
96			'name' => 'theme-color',
97			'content' => $replacements['__theme_color__']
98		);
99    }
100
101    if($alt) {
102        if(actionOK('rss')) {
103            $head['link'][] = array(
104                'rel'  => 'alternate', 'type'=> 'application/rss+xml',
105                'title'=> $lang['btn_recent'], 'href'=> DOKU_BASE.'feed.php'
106            );
107            $head['link'][] = array(
108                'rel'  => 'alternate', 'type'=> 'application/rss+xml',
109                'title'=> $lang['currentns'],
110                'href' => DOKU_BASE.'feed.php?mode=list&ns='.(isset($INFO) ? $INFO['namespace'] : '')
111            );
112        }
113        if(($ACT == 'show' || $ACT == 'search') && $INFO['writable']) {
114            $head['link'][] = array(
115                'rel'  => 'edit',
116                'title'=> $lang['btn_edit'],
117                'href' => wl($ID, 'do=edit', false, '&')
118            );
119        }
120
121        if(actionOK('rss') && $ACT == 'search') {
122            $head['link'][] = array(
123                'rel'  => 'alternate', 'type'=> 'application/rss+xml',
124                'title'=> $lang['searchresult'],
125                'href' => DOKU_BASE.'feed.php?mode=search&q='.$QUERY
126            );
127        }
128
129        if(actionOK('export_xhtml')) {
130            $head['link'][] = array(
131                'rel' => 'alternate', 'type'=> 'text/html', 'title'=> $lang['plainhtml'],
132                'href'=> exportlink($ID, 'xhtml', '', false, '&')
133            );
134        }
135
136        if(actionOK('export_raw')) {
137            $head['link'][] = array(
138                'rel' => 'alternate', 'type'=> 'text/plain', 'title'=> $lang['wikimarkup'],
139                'href'=> exportlink($ID, 'raw', '', false, '&')
140            );
141        }
142    }
143
144    // setup robot tags apropriate for different modes
145    if(($ACT == 'show' || $ACT == 'export_xhtml') && !$REV) {
146        if($INFO['exists']) {
147            //delay indexing:
148            if((time() - $INFO['lastmod']) >= $conf['indexdelay'] && !isHiddenPage($ID) ) {
149                $head['meta'][] = array('name'=> 'robots', 'content'=> 'index,follow');
150            } else {
151                $head['meta'][] = array('name'=> 'robots', 'content'=> 'noindex,nofollow');
152            }
153            $canonicalUrl = wl($ID, '', true, '&');
154            if ($ID == $conf['start']) {
155                $canonicalUrl = DOKU_URL;
156            }
157            $head['link'][] = array('rel'=> 'canonical', 'href'=> $canonicalUrl);
158        } else {
159            $head['meta'][] = array('name'=> 'robots', 'content'=> 'noindex,follow');
160        }
161    } elseif(defined('DOKU_MEDIADETAIL')) {
162        $head['meta'][] = array('name'=> 'robots', 'content'=> 'index,follow');
163    } else {
164        $head['meta'][] = array('name'=> 'robots', 'content'=> 'noindex,nofollow');
165    }
166
167    // set metadata
168    if($ACT == 'show' || $ACT == 'export_xhtml') {
169        // keywords (explicit or implicit)
170        if(!empty($INFO['meta']['subject'])) {
171            $head['meta'][] = array('name'=> 'keywords', 'content'=> join(',', $INFO['meta']['subject']));
172        } else {
173            $head['meta'][] = array('name'=> 'keywords', 'content'=> str_replace(':', ',', $ID));
174        }
175    }
176
177    // load stylesheets
178    $head['link'][] = array(
179        'rel' => 'stylesheet',
180        'href'=> DOKU_BASE . 'lib/exe/css.php?t='.rawurlencode($conf['template']).'&tseed='.$tseed
181    );
182
183    $script = "var NS='".(isset($INFO)?$INFO['namespace']:'')."';\n\t\t";
184    if($conf['useacl'] && $INPUT->server->str('REMOTE_USER')) {
185        $script .= "var SIG=".toolbar_signature().";\n\t\t";
186    }
187
188    if($conf['basedir']) {
189        $script .= 'var BASEDIR="'.$conf['basedir']."\";\n\t\t";
190    }
191
192    jsinfo();
193    $script .= 'var JSINFO = ' . json_encode($JSINFO).';';
194    $head['script'][] = array('_data'=> $script);
195
196    // load jquery
197    $jquery = getCdnUrls();
198    foreach($jquery as $src) {
199        $head['script'][] = array(
200            /* 'charset' => 'utf-8', -- obsolete */
201            '_data' => '',
202            'src' => $src,
203        ) + ($conf['defer_js'] ? [ 'defer' => 'defer'] : []);
204    }
205
206    // load our javascript dispatcher
207    $head['script'][] = array(
208        /* 'charset'=> 'utf-8', -- obsolete */
209		'_data'=> '',
210        'src' => DOKU_BASE . 'lib/exe/js.php'.'?t='.rawurlencode($conf['template']).'&tseed='.$tseed,
211    ) + ($conf['defer_js'] ? [ 'defer' => 'defer'] : []);
212
213    // trigger event here
214    Event::createAndTrigger('TPL_METAHEADER_OUTPUT', $head, '_my_metaheaders_action', true);
215    return true;
216}
217
218/**
219 * prints the array build by my_metaheaders
220 *
221 * Overrides the original version by adding a tab before each line for neater HTML code
222 *
223 * @author Sascha Leib <sascha@leib.be>
224 * @author Andreas Gohr <andi@splitbrain.org>
225 *
226 * @param array $data
227 */
228function _my_metaheaders_action($data) {
229    foreach($data as $tag => $inst) {
230        foreach($inst as $attr) {
231            if ( empty($attr) ) { continue; }
232            echo "\t<", $tag, ' ', buildAttributes($attr);
233            if(isset($attr['_data']) || $tag == 'script') {
234                if($tag == 'script' && $attr['_data'])
235                    $attr['_data'] = "/*<![CDATA[*/".
236                        $attr['_data'].
237                        "\n/*!]]>*/";
238
239                echo '>', $attr['_data'], '</', $tag, '>';
240            } else {
241                echo '/>';
242            }
243            echo "\n";
244        }
245    }
246}
247
248/**
249 * get a link to the homepage.
250 *
251 * wraps the original wl() function to allow overriding in the options
252 *
253 * @author Sascha Leib <sascha@leib.be>
254 *
255 * @returns string (link)
256 */
257function my_homelink() {
258    global $conf;
259
260	$hl = trim(tpl_getConf('homelink'));
261
262	if ( $hl !== '' ) {
263		return $hl;
264	} else {
265		return wl(); // default homelink
266	}
267}
268
269/**
270 * Print the breadcrumbs trace
271 *
272 * Cleanup of the original code to create neater and more accessible HTML
273 *
274 * @author Sascha Leib <sascha@leib.be>
275 * @author Andreas Gohr <andi@splitbrain.org>
276 *
277 * @param string $prefix inserted before each line
278 *
279 * @return void
280 */
281function my_breadcrumbs($prefix = '') {
282    global $lang;
283    global $conf;
284
285    //check if enabled
286    if(!$conf['breadcrumbs']) return false;
287
288    $crumbs = breadcrumbs(); //setup crumb trace
289
290	/* begin listing */
291	echo $prefix . "<nav id=\"navBreadCrumbs\">\n";
292	echo $prefix . "\t<h4>" . $lang['breadcrumb'] . "</h4>\n";
293	echo $prefix . "\t<ol reversed>\n";
294
295    $last = count($crumbs);
296    $i    = 0;
297    foreach($crumbs as $id => $name) {
298        $i++;
299		echo $prefix . "\t\t<li" . ($i == $last ? ' class="current"' : '') . '><bdi>' . tpl_link(wl($id), hsc($name), '', true) .  "</bdi></li>\n";
300    }
301	echo $prefix . "\t</ol>\n";
302	echo $prefix . "</nav>\n";
303}
304
305/**
306 * Hierarchical breadcrumbs
307 *
308 * Cleanup of the original code to create neater and more accessible HTML
309 *
310 * @author Sascha Leib <sascha@leib.be>
311 * @author Andreas Gohr <andi@splitbrain.org>
312 * @author Nigel McNie <oracle.shinoda@gmail.com>
313 * @author Sean Coates <sean@caedmon.net>
314 * @author <fredrik@averpil.com>
315 *
316 * @param  string $prefix to be added before each line
317 *
318 */
319function my_youarehere($prefix = '') {
320    global $conf;
321    global $ID;
322    global $lang;
323
324    // check if enabled
325    if(!$conf['youarehere']) return false;
326
327    $parts = explode(':', $ID);
328    $count = count($parts);
329	$isdir = ( $parts[$count-1] == $conf['start']);
330
331	$hl = trim(tpl_getConf('homelink'));
332
333	echo $prefix . "<nav id=\"navYouAreHere\">\n";
334	echo $prefix . "\t<h4>" . $lang['youarehere'] . "</h4>\n";
335	echo $prefix . "\t<ol>\n";
336
337    // always print the startpage
338	if ( $hl !== '' ) {
339		echo $prefix . "\t\t<li class=\"home\">" . tpl_link( $hl, htmlentities(tpl_getLang('homepage')), ' title="' . htmlentities(tpl_getLang('homepage')) . '"', true) . "</li>\n";
340		echo $prefix . "\t\t<li>" . tpl_pagelink(':'.$conf['start'], null, true) . "</li>\n";
341	} else {
342		echo $prefix . "\t\t<li class=\"home\">" . tpl_pagelink(':'.$conf['start'], null, true) . "</li>\n";
343	}
344
345    // print intermediate namespace links
346    $page = '';
347    for($i = 0; $i < $count - 1; $i++) {
348        $part = $parts[$i];
349        $page .= $part . ':';
350
351		if ($i == $count-2 && $isdir)  break; // Skip last if it is an index page
352
353		echo $prefix . "\t\t<li>" . tpl_pagelink($page, null, true) . "</li>\n";
354    }
355
356    // chould the current page be included in the listing?
357	$trail = tpl_getConf('navtrail');
358
359	if ($trail !== 'none' && $trail !== '') {
360
361		echo $prefix . "\t\t<li class=\"current\">";
362		if ($trail == 'text') {
363			echo tpl_pagetitle($page . $parts[$count-1], true);
364		} else if ($trail == 'link') {
365			echo tpl_pagelink($page . $parts[$count-1], null, true);
366		}
367		echo "</li>\n";
368	}
369
370	echo $prefix . "\t</ol>\n";
371	echo $prefix . "</nav>\n";
372}
373
374/**
375 * My implementation of the basic userinfo (in the global banner)
376 *
377 *
378 * @author Sascha Leib <sascha@leib.be>
379 *
380 * @param  string $prefix to be added before each line
381 *
382 * @return void
383 */
384function my_userinfo($prefix = '') {
385    global $lang;
386    global $INPUT;
387
388	// add login/logout button:
389	$items = (new \dokuwiki\Menu\UserMenu())->getItems();
390	foreach($items as $it) {
391		$typ = $it->getType();
392
393		if ($typ === 'profile') { // special case for user profile:
394
395			echo $prefix . '<li class="action profile"><span class="sronly">' . $lang['loggedinas'] .
396				' </span><a href="' . htmlentities($it->getLink()) . '" title="' . $it->getTitle() . '">' .
397				userlink() . "</a></li>\n";
398
399		} else {
400
401			echo $prefix . "<li class=\"action $typ\"><a href=\"" . htmlentities($it->getLink()) .
402				'" title="' . $it->getTitle() . '">' . ($typ === 'profile'? userlink() : $it->getLabel() ) .
403				"</a></li>\n";
404		}
405	}
406}
407
408/**
409 *Inserts a cleaner version of the TOC
410 *
411 * This is an update of the original function that renders the TOC directly.
412 *
413 * @author Sascha Leib <sascha@leib.be>
414 * @author Andreas Gohr <andi@splitbrain.org>
415 *
416 * @param  string $prefix to be added before each line
417 *
418 * @return void
419 */
420function my_toc($prefix = '') {
421    global $TOC;
422    global $ACT;
423    global $ID;
424    global $REV;
425    global $INFO;
426    global $conf;
427    global $lang;
428    $toc = array();
429
430    if(is_array($TOC)) {
431        // if a TOC was prepared in global scope, always use it
432        $toc = $TOC;
433    } elseif(($ACT == 'show' || substr($ACT, 0, 6) == 'export') && !$REV && $INFO['exists']) {
434        // get TOC from metadata, render if neccessary
435        $meta = p_get_metadata($ID, '', METADATA_RENDER_USING_CACHE);
436        if(isset($meta['internal']['toc'])) {
437            $tocok = $meta['internal']['toc'];
438        } else {
439            $tocok = true;
440        }
441        $toc = isset($meta['description']['tableofcontents']) ? $meta['description']['tableofcontents'] : null;
442        if(!$tocok || !is_array($toc) || !$conf['tocminheads'] || count($toc) < $conf['tocminheads']) {
443            $toc = array();
444        }
445    } elseif($ACT == 'admin') {
446        // try to load admin plugin TOC
447        /** @var $plugin AdminPlugin */
448        if ($plugin = plugin_getRequestAdminPlugin()) {
449            $toc = $plugin->getTOC();
450            $TOC = $toc; // avoid later rebuild
451        }
452    }
453
454	/* Build the hierarchical list of headline links: */
455	if (count($toc) >= intval($conf['tocminheads'])) {
456		echo $prefix . "<aside id=\"toc\" class=\"toggle hide\">\n";
457		echo $prefix . "\t<button type=\"button\" id=\"toc-menubutton\" class=\"tg_button\" title=\"" . htmlentities($lang['toc']) . '" aria-haspopup="true" aria-controls="toc-menu"><span>' . htmlentities($lang['toc']) . "</span></button>\n" . $prefix . "\t<div id=\"toc-menu\" class=\"tg_content\" role=\"menu\" aria-labelledby=\"toc-menubutton\">";
458		$level = 0;
459		foreach($toc as $it) {
460
461			$nl = intval($it['level']);
462			$cp = ($nl <=> $level);
463
464			if ($cp > 0) {
465				while ($level < $nl) {
466					echo "\n" . $prefix . str_repeat("\t", $level*2 + 2) . "<ol>\n";
467					$level++;
468				}
469			} else if ($cp < 0) {
470				while ($level > $nl) {
471					echo "\n" . $prefix . str_repeat("\t", $level*2) . "</ol>\n" . $prefix . str_repeat("\t", $level*2-1) . "</li>\n";
472					$level--;
473				}
474			} else {
475				echo "</li>\n";
476			}
477
478			$href = ( array_key_exists('link', $it ) ? $it['link'] : '' ) . ( array_key_exists('hid', $it) && $it['hid'] !== '' ? '#' . $it['hid'] : '' );
479
480			echo $prefix . str_repeat("\t", $nl*2 + 1) . '<li  role="presentation"><a role="menuitem" href="' . $href . '">' . htmlentities($it['title']) . "</a>";
481			$level = $nl;
482		}
483
484		for ($i = $level-1; $i > 0; $i--) {
485			echo "</li>\n" . $prefix . str_repeat("\t", $i*2 + 1) . "</ol>";
486		}
487
488		echo "</li>\n" . $prefix . "\t\t</ol>\n" . $prefix . "\t</div>\n" . $prefix . "</aside>\n";
489	}
490}
491
492/**
493 * Print last change date
494 *
495 * @author Sascha Leib <sascha@leib.be>
496 *
497 * @param  string $prefix to be added before each line
498 *
499 * @return void
500 */
501function my_lastchange($prefix = '') {
502
503    global $lang;
504    global $INFO;
505    global $conf;
506
507	$lastmod = $INFO['lastmod'];
508
509	if (intval($lastmod) > 0) { // is valid date?
510
511		$longDate = htmlentities(dformat($lastmod));
512
513		echo $prefix . "<p class=\"docInfo\">\n";
514		echo $prefix . "\t<bdi>" . $lang['lastmod'] . "</bdi>\n";
515		echo $prefix . "\t<time datetime=\"" . date('c', $lastmod) . '" title="' . $longDate . '"><span class="print-only">' . $longDate . '</span><span class="noprint">' . datetime_h($lastmod) . "</span></time>\n";
516		echo $prefix . "</p>\n";
517	}
518
519	/* user name for last change (is this really interesting to the visitor?) */
520	/* echo $prefix .'<span class="editorname" tabindex="0">' . $lang['by'] . ' <bdi>' . editorinfo($INFO['editor']) . "</bdi></span>\n"; */
521}
522
523/**
524 * Returns a description list of the metatags of the current image
525 *
526 * @return string html of description list
527 */
528function my_img_meta($prefix = '') {
529    global $lang;
530
531	$format = '%Y-%m-%dT%T%z';	/* e.g. 2021-21-05T16:45:12+02:00 */
532
533    $tags = tpl_get_img_meta();
534
535    foreach($tags as $tag) {
536        $label = $lang[$tag['langkey']];
537        if(!$label) $label = $tag['langkey'] . ':';
538
539        echo $prefix . '<tr><th>'.$label.'</th><td>';
540        if ($tag['type'] == 'date') {
541            echo '<time datetime="' . strftime($format, $tag['value']) . '">' . dformat($tag['value']) . '</time>';
542        } else {
543            echo hsc($tag['value']);
544        }
545        echo "</td></tr>\n";
546    }
547}
548
549/**
550 * Creates the Site logo image link
551 *
552 */
553function my_sitelogo() {
554    global $conf;
555
556	// get logo either out of the template images folder or data/media folder
557	$logoSize = array();
558	$logo = tpl_getMediaFile(array(':logo.svg', ':wiki:logo.svg', ':logo.png', ':wiki:logo.png', 'images/sitelogo.svg'), false, $logoSize);
559	tpl_link( my_homelink(),
560		'<img src="'.$logo.'" ' . (is_array($logoSize) && array_key_exists(3, $logoSize) ? $logoSize[3] : '') . ' alt="' . htmlentities($conf['title']) . '" />', 'accesskey="h" title="[H]" class="logo"');
561}
562
563/**
564 * Creates the various favicon and similar links:
565 *
566 * @param  string $color overwrite the theme color.
567 *
568 * @return null
569 */
570function my_favicons($color = null) {
571
572	$logoSize = array();
573
574	/* Theme color:
575	if ($color == null) {
576
577		// get the style config:
578		$styleUtil = new \dokuwiki\StyleUtils();
579		$styleIni = $styleUtil->cssStyleini();
580		$replacements = $styleIni['replacements'];
581		$color = $replacements['__theme_color__'];
582
583		if ($color== null) { $color = '#2b73b7'; }
584	}
585	echo "\t<meta name=\"theme-color\" content=\"" . $color . "\" />\n"; */
586
587	// get the favicon:
588	$link = tpl_getMediaFile(array(':favicon.ico', ':favicon.png', ':favicon.svg', ':wiki:favicon.ico', ':wiki:favicon.png', ':wiki:favicon.svg'), false, $logoSize);
589	echo "\t<link rel=\"icon\" href=\"" . $link . "\" />\n";
590
591	// Apple Touch Icon
592	$logoSize = array();
593	$link = tpl_getMediaFile(array(':apple-touch-icon.png', ':wiki:apple-touch-icon.png', 'images/apple-touch-icon.png'), false, $logoSize);
594	echo "\t<link rel=\"apple-touch-icon\" href=\"" . $link . "\" />\n";
595
596}
597
598/**
599 * inserts the Cookies banner, if appropriate.
600 * This is based on Michal Koutny’s "cookielaw" plugin
601 *
602 * @param  string $prefix to be added before each line
603 */
604function my_cookiebanner($prefix = '') {
605
606	// get the configuration settings:
607	$msg = tpl_getConf('cookiemsg', '(no message configured)');
608	$position = tpl_getConf('cookiepos', 'bottom');
609	$link = tpl_getConf('cookielink', 'about:cookies');
610
611	// if the cookie is already set or position is set to hide, do nothing.
612	if ( isset($_COOKIE['cookielaw']) or $position == 'hide') {
613		return;
614	}
615
616	// output the HTML code:
617	echo $prefix . "<div id=\"cookiebanner\" class=\"cb_" . $position . "\">\n";
618	echo $prefix . "\t<p class=\"cb_info\"><span class=\"cb_icon\"></span>\n";
619	echo $prefix . "\t\t<span class=\"cb_msg\">". $msg . "</span>\r";
620	echo $prefix . "\t</p>\n";
621	echo $prefix . "\t<p class=\"cb_action\">\n";
622	echo $prefix . "\t\t<button>" . hsc(tpl_getLang('cookie_consent')) . "</button>\n";
623	echo $prefix . "\t\t";
624	if ( substr($link, 0, 7) == 'http://' || substr($link, 0, 8) == 'https://') {
625		echo '<a href="' . $link . '" target="_blank">' . hsc(tpl_getLang('cookie_linktext')) . '</a>';
626	} else {
627		tpl_pagelink($link, tpl_getLang('cookie_linktext'));
628	}
629	echo $prefix . "\n\t</p>\n" . $prefix . "</div>\n";
630
631}
632