xref: /template/ad-hominem/my_template.php (revision 56919fe9575b8496ca18fe44265b7cf334d262c6)
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;
11
12/**
13 * Print the specific HTML meta headers
14 *
15 * Overrides the original version by modifying the headers and the way it is printed
16 *
17 * @author Sascha Leib <sascha@leib.be>
18 * @author Andreas Gohr <andi@splitbrain.org>
19 *
20 * @triggers TPL_METAHEADER_OUTPUT
21 * @param  bool $alt Should feeds and alternative format links be added?
22 * @return bool
23 */
24function my_metaheaders($alt = true) {
25    global $ID;
26    global $REV;
27    global $INFO;
28    global $JSINFO;
29    global $ACT;
30    global $QUERY;
31    global $lang;
32    global $conf;
33    global $updateVersion;
34    /** @var Input $INPUT */
35    global $INPUT;
36
37    // prepare the head array
38    $head = array();
39
40    // prepare seed for js and css
41    $tseed   = $updateVersion;
42    $depends = getConfigFiles('main');
43    $depends[] = DOKU_CONF."tpl/".$conf['template']."/style.ini";
44    foreach($depends as $f) $tseed .= @filemtime($f);
45    $tseed   = md5($tseed);
46
47	// Open Graph information
48	$meta = p_get_metadata($ID);
49	if ($meta['title'] !== null) {
50		$head['meta'][] = array('property' => 'og:title', 'content' => tpl_pagetitle($ID, true));
51		$head['meta'][] = array('property' => 'og:site_name ', 'content' => $conf['title']);
52		$head['meta'][] = array('property' => 'og:type', 'content' => 'website');
53		$head['meta'][] = array('property' => 'og:url', 'content' => wl($ID));
54
55		$parts = explode("\n", $meta['description']['abstract']);
56		$head['meta'][] = array('property' => 'og:description ', 'content' => $parts[2]);
57	}
58
59    // the usual stuff
60    $head['meta'][] = array('name'=> 'generator', 'content'=> 'DokuWiki');
61    if(actionOK('search')) {
62        $head['link'][] = array(
63            'rel' => 'search', 'type'=> 'application/opensearchdescription+xml',
64            'href'=> DOKU_BASE.'lib/exe/opensearch.php', 'title'=> $conf['title']
65        );
66    }
67
68    $head['link'][] = array('rel'=> 'start', 'href'=> DOKU_BASE);
69    if(actionOK('index')) {
70        $head['link'][] = array(
71            'rel'  => 'contents', 'href'=> wl($ID, 'do=index', false, '&'),
72            'title'=> $lang['btn_index']
73        );
74    }
75
76    if (actionOK('manifest')) {
77        $head['link'][] = array('rel'=> 'manifest', 'href'=> DOKU_BASE.'lib/exe/manifest.php');
78    }
79
80    $styleUtil = new \dokuwiki\StyleUtils();
81    $styleIni = $styleUtil->cssStyleini();
82    $replacements = $styleIni['replacements'];
83    if (!empty($replacements['__theme_color__'])) {
84        $head['meta'][] = array('name' => 'theme-color', 'content' => $replacements['__theme_color__']);
85    }
86
87    if($alt) {
88        if(actionOK('rss')) {
89            $head['link'][] = array(
90                'rel'  => 'alternate', 'type'=> 'application/rss+xml',
91                'title'=> $lang['btn_recent'], 'href'=> DOKU_BASE.'feed.php'
92            );
93            $head['link'][] = array(
94                'rel'  => 'alternate', 'type'=> 'application/rss+xml',
95                'title'=> $lang['currentns'],
96                'href' => DOKU_BASE.'feed.php?mode=list&ns='.(isset($INFO) ? $INFO['namespace'] : '')
97            );
98        }
99        if(($ACT == 'show' || $ACT == 'search') && $INFO['writable']) {
100            $head['link'][] = array(
101                'rel'  => 'edit',
102                'title'=> $lang['btn_edit'],
103                'href' => wl($ID, 'do=edit', false, '&')
104            );
105        }
106
107        if(actionOK('rss') && $ACT == 'search') {
108            $head['link'][] = array(
109                'rel'  => 'alternate', 'type'=> 'application/rss+xml',
110                'title'=> $lang['searchresult'],
111                'href' => DOKU_BASE.'feed.php?mode=search&q='.$QUERY
112            );
113        }
114
115        if(actionOK('export_xhtml')) {
116            $head['link'][] = array(
117                'rel' => 'alternate', 'type'=> 'text/html', 'title'=> $lang['plainhtml'],
118                'href'=> exportlink($ID, 'xhtml', '', false, '&')
119            );
120        }
121
122        if(actionOK('export_raw')) {
123            $head['link'][] = array(
124                'rel' => 'alternate', 'type'=> 'text/plain', 'title'=> $lang['wikimarkup'],
125                'href'=> exportlink($ID, 'raw', '', false, '&')
126            );
127        }
128    }
129
130    // setup robot tags apropriate for different modes
131    if(($ACT == 'show' || $ACT == 'export_xhtml') && !$REV) {
132        if($INFO['exists']) {
133            //delay indexing:
134            if((time() - $INFO['lastmod']) >= $conf['indexdelay'] && !isHiddenPage($ID) ) {
135                $head['meta'][] = array('name'=> 'robots', 'content'=> 'index,follow');
136            } else {
137                $head['meta'][] = array('name'=> 'robots', 'content'=> 'noindex,nofollow');
138            }
139            $canonicalUrl = wl($ID, '', true, '&');
140            if ($ID == $conf['start']) {
141                $canonicalUrl = DOKU_URL;
142            }
143            $head['link'][] = array('rel'=> 'canonical', 'href'=> $canonicalUrl);
144        } else {
145            $head['meta'][] = array('name'=> 'robots', 'content'=> 'noindex,follow');
146        }
147    } elseif(defined('DOKU_MEDIADETAIL')) {
148        $head['meta'][] = array('name'=> 'robots', 'content'=> 'index,follow');
149    } else {
150        $head['meta'][] = array('name'=> 'robots', 'content'=> 'noindex,nofollow');
151    }
152
153    // set metadata
154    if($ACT == 'show' || $ACT == 'export_xhtml') {
155        // keywords (explicit or implicit)
156        if(!empty($INFO['meta']['subject'])) {
157            $head['meta'][] = array('name'=> 'keywords', 'content'=> join(',', $INFO['meta']['subject']));
158        } else {
159            $head['meta'][] = array('name'=> 'keywords', 'content'=> str_replace(':', ',', $ID));
160        }
161    }
162
163    // load stylesheets
164    $head['link'][] = array(
165        'rel' => 'stylesheet',
166        'href'=> DOKU_BASE . 'lib/exe/css.php?t='.rawurlencode($conf['template']).'&tseed='.$tseed
167    );
168
169    $script = "var NS='".(isset($INFO)?$INFO['namespace']:'')."';\n\t\t";
170    if($conf['useacl'] && $INPUT->server->str('REMOTE_USER')) {
171        $script .= "var SIG=".toolbar_signature().";\n\t\t";
172    }
173
174    if($conf['basedir']) {
175        $script .= 'var BASEDIR="'.$conf['basedir']."\";\n\t\t";
176    }
177
178    jsinfo();
179    $script .= 'var JSINFO = ' . json_encode($JSINFO).';';
180    $head['script'][] = array('_data'=> $script);
181
182    // load jquery
183    $jquery = getCdnUrls();
184    foreach($jquery as $src) {
185        $head['script'][] = array(
186            'charset' => 'utf-8',
187            '_data' => '',
188            'src' => $src,
189        ) + ($conf['defer_js'] ? [ 'defer' => 'defer'] : []);
190    }
191
192    // load our javascript dispatcher
193    $head['script'][] = array(
194        'charset'=> 'utf-8', '_data'=> '',
195        'src' => DOKU_BASE . 'lib/exe/js.php'.'?t='.rawurlencode($conf['template']).'&tseed='.$tseed,
196    ) + ($conf['defer_js'] ? [ 'defer' => 'defer'] : []);
197
198    // trigger event here
199    Event::createAndTrigger('TPL_METAHEADER_OUTPUT', $head, '_my_metaheaders_action', true);
200    return true;
201}
202
203
204/**
205 * prints the array build by my_metaheaders
206 *
207 * Overrides the original version by adding a tab before each line for neater HTML code
208 *
209 * @author Sascha Leib <sascha@leib.be>
210 * @author Andreas Gohr <andi@splitbrain.org>
211 *
212 * @param array $data
213 */
214function _my_metaheaders_action($data) {
215    foreach($data as $tag => $inst) {
216        /* if($tag == 'script') {
217            echo "\t<!--[if gte IE 9]><!-->\n"; // no scripts for old IE
218        } NO LONGER NEEDED */
219
220        foreach($inst as $attr) {
221            if ( empty($attr) ) { continue; }
222            echo "\t<", $tag, ' ', buildAttributes($attr);
223            if(isset($attr['_data']) || $tag == 'script') {
224                if($tag == 'script' && $attr['_data'])
225                    $attr['_data'] = "/*<![CDATA[*/".
226                        $attr['_data'].
227                        "\n/*!]]>*/";
228
229                echo '>', $attr['_data'], '</', $tag, '>';
230            } else {
231                echo '/>';
232            }
233            echo "\n";
234        }
235        /* if($tag == 'script') {
236            echo "\t<!--<![endif]-->\n";
237        } -- Not Needed Any Longer */
238    }
239}
240
241/**
242 * Print the breadcrumbs trace
243 *
244 * Cleanup of the original code to create neater and more accessible HTML
245 *
246 * @author Sascha Leib <sascha@leib.be>
247 * @author Andreas Gohr <andi@splitbrain.org>
248 *
249 * @param string $prefix inserted before each line
250 *
251 * @return void
252 */
253function my_breadcrumbs($prefix = '') {
254    global $lang;
255    global $conf;
256
257    //check if enabled
258    if(!$conf['breadcrumbs']) return false;
259
260    $crumbs = breadcrumbs(); //setup crumb trace
261
262	/* begin listing */
263	echo $prefix . "<nav id=\"navBreadCrumbs\">\n";
264	echo $prefix . "\t<h4 class=\"toggle\">" . $lang['breadcrumb'] . "</h4>\n";
265	echo $prefix . "\t<ol reversed>\n";
266
267
268    $last = count($crumbs);
269    $i    = 0;
270    foreach($crumbs as $id => $name) {
271        $i++;
272		echo $prefix . "\t\t<li" . ($i == $last ? ' class="current"' : '') . '><bdi>' . tpl_link(wl($id), hsc($name), '', true) .  "</bdi></li>\n";
273    }
274	echo $prefix . "\t</ol>\n";
275	echo $prefix . "</nav>\n";
276}
277
278
279/**
280 * Hierarchical breadcrumbs
281 *
282 * Cleanup of the original code to create neater and more accessible HTML
283 *
284 * @author Sascha Leib <sascha@leib.be>
285 * @author Andreas Gohr <andi@splitbrain.org>
286 * @author Nigel McNie <oracle.shinoda@gmail.com>
287 * @author Sean Coates <sean@caedmon.net>
288 * @author <fredrik@averpil.com>
289 *
290 * @param  string $prefix to be added before each line
291 *
292 */
293function my_youarehere($prefix = '') {
294    global $conf;
295    global $ID;
296    global $lang;
297
298    // check if enabled
299    if(!$conf['youarehere']) return false;
300
301    $parts = explode(':', $ID);
302    $count = count($parts);
303
304	echo $prefix . "<nav id=\"navYouAreHere\">\n";
305	echo $prefix . "\t<h4>" . $lang['youarehere'] . "</h4>\n";
306	echo $prefix . "\t<ol>\n";
307
308    // always print the startpage
309    echo $prefix . "\t\t<li class=\"home\">" . tpl_pagelink(':'.$conf['start'], null, true) . "</li>\n";
310
311    // print intermediate namespace links
312    $part = '';
313    for($i = 0; $i < $count - 1; $i++) {
314        $part .= $parts[$i].':';
315        $page = $part;
316        if($page == $conf['start']) continue; // Skip startpage
317
318        // output
319        echo $prefix . "\t\t<li>" . tpl_pagelink($page, null, true) . "</li>\n";
320    }
321
322    // print current page, skipping start page, skipping for namespace index
323    /* resolve_pageid('', $page, $exists);
324    if ( !(isset($page) && $page == $part.$parts[$i])
325		|| !($page == $conf['start']) ) {
326		echo "\t\t\t\t\t<li>" . tpl_pagelink($page, null, true) . "</li>\n";
327	} */
328
329	echo $prefix . "\t</ol>\n";
330	echo $prefix . "</nav>\n";
331}
332
333/**
334 * My implementation of the basic userinfo (in the global banner)
335 *
336 *
337 * @author Sascha Leib <sascha@leib.be>
338 *
339 * @param  string $prefix to be added before each line
340 *
341 * @return void
342 */
343function my_userinfo($prefix = '') {
344    global $lang;
345    global $INPUT;
346
347	// add login/logout button:
348	$items = array_reverse((new \dokuwiki\Menu\UserMenu())->getItems());
349	foreach($items as $it) {
350		$typ = $it->getType();
351		if ($typ === 'profile') {
352			echo $prefix . "<li class=\"action $typ\"><span class=\"sronly\">" . $lang['loggedinas'] . ' </span>' . userlink() . "</li>\n";
353		} else {
354			echo $prefix . "<li class=\"action $typ\"><a href=\"" . htmlentities($it->getLink()) . '" title="' . $it->getTitle() . '">' . $it->getLabel() . "</a></li>\n";
355		}
356	}
357
358}
359
360/**
361 *Inserts a cleaner version of the TOC
362 *
363 * This is an update of the original function that renders the TOC directly.
364 *
365 * @author Sascha Leib <sascha@leib.be>
366 * @author Andreas Gohr <andi@splitbrain.org>
367 *
368 * @param  string $prefix to be added before each line
369 *
370 * @return void
371 */
372function my_toc($prefix = '') {
373    global $TOC;
374    global $ACT;
375    global $ID;
376    global $REV;
377    global $INFO;
378    global $conf;
379    global $lang;
380    $toc = array();
381
382    if(is_array($TOC)) {
383        // if a TOC was prepared in global scope, always use it
384        $toc = $TOC;
385    } elseif(($ACT == 'show' || substr($ACT, 0, 6) == 'export') && !$REV && $INFO['exists']) {
386        // get TOC from metadata, render if neccessary
387        $meta = p_get_metadata($ID, '', METADATA_RENDER_USING_CACHE);
388        if(isset($meta['internal']['toc'])) {
389            $tocok = $meta['internal']['toc'];
390        } else {
391            $tocok = true;
392        }
393        $toc = isset($meta['description']['tableofcontents']) ? $meta['description']['tableofcontents'] : null;
394        if(!$tocok || !is_array($toc) || !$conf['tocminheads'] || count($toc) < $conf['tocminheads']) {
395            $toc = array();
396        }
397    } elseif($ACT == 'admin') {
398        // try to load admin plugin TOC
399        /** @var $plugin AdminPlugin */
400        if ($plugin = plugin_getRequestAdminPlugin()) {
401            $toc = $plugin->getTOC();
402            $TOC = $toc; // avoid later rebuild
403        }
404    }
405
406	/* Build the hierarchical list of headline links: */
407	if (count($toc) >= intval($conf['tocminheads'])) {
408		echo $prefix . "<aside id=\"dw__toc\" class=\"dw__toc\">\n";
409		echo $prefix . "\t<h3>" . $lang['toc'] . "</h3>\n" . $prefix . "\t<div>";
410		$level = intval("0");
411		foreach($toc as $it) {
412
413			$nl = intval($it['level']);
414			$cp = ($nl <=> $level);
415
416			if ($cp > 0) {
417				echo "\n" . $prefix . str_repeat("\t", $level*2 + 2) . "<ol>\n";
418			} else if ($cp < 0) {
419				echo "\n" . $prefix . str_repeat("\t", $level*2) . "</ol></li>\n";
420			} else {
421				echo "</li>\n";
422			}
423
424			echo $prefix . str_repeat("\t", $nl*2 + 1) . "<li><a href=\"#" . $it['hid'] . '">' . htmlentities($it['title']) . "</a>";
425			$level = $nl;
426		}
427
428		for ($i = $level-1; $i > 0; $i--) {
429			echo "</li>\n" . $prefix . str_repeat("\t", $i*2 + 1) . "</ol>";
430		}
431
432		echo "</li>\n" . $prefix . "\t\t</ol>\n" . $prefix . "\t</div>\n" . $prefix . "</aside>\n";
433	}
434}
435
436/**
437 * Print last change date
438 *
439 * @author Sascha Leib <sascha@leib.be>
440 *
441 * @param  string $prefix to be added before each line
442 *
443 * @return void
444 */
445function my_lastchange($prefix = '') {
446
447    global $lang;
448    global $INFO;
449
450	$format = '%Y-%m-%dT%T%z';	/* 2021-21-05T16:45:12+02:00 */
451
452	$date = $INFO['lastmod'];
453
454	echo $prefix . '<bdi>' . $lang['lastmod'] . "</bdi>\n";
455	echo $prefix . '<time itemprop="dateModified" datetime="' . strftime($format, $date) . '">' . dformat($date) . "</time>\n";
456	echo $prefix .'<span class="editorname" tabindex="0">' . $lang['by'] . ' <bdi itemprop="editor">' . editorinfo($INFO['editor']) . "</bdi></span>\n";
457}