1<?php
2/**
3 * hiddenheader Plugin for DokuWiki / action.php
4 *
5 * This would be easier and more performant as a syntax plugin, but .
6 * See the
7 *
8 *
9 * @author  Eli Fenton
10 */
11
12if (!defined('DOKU_INC')) {die();}
13if (!defined('DOKU_PLUGIN')) {define('DOKU_PLUGIN', DOKU_INC . 'lib/plugins/');}
14require_once DOKU_PLUGIN . 'action.php';
15
16class action_plugin_hiddenheader extends DokuWiki_Action_Plugin {
17	function register(Doku_Event_Handler $controller) {
18		$controller->register_hook('PARSER_WIKITEXT_PREPROCESS', 'AFTER', $this, 'handlePreprocess');
19		$controller->register_hook('RENDERER_CONTENT_POSTPROCESS', 'BEFORE', $this, 'handlePostProcess');
20		$controller->register_hook('TPL_TOC_RENDER', 'BEFORE', $this, 'handleToc');
21	}
22
23	function handlePreprocess(&$event, $param) {
24		// should accumulate in hash
25		if ($this->hidden) {
26			return;
27		}
28		preg_match_all('/==+\%hide\s*([^=]+)/', $event->data, $m);
29		$this->hidden = $m && count($m[1]) > 0 ? array_map('trim', $m[1]) : null;
30
31		if ($this->hidden) {
32			$event->data = preg_replace('/(==+)\%hide/', '$1', $event->data);
33		}
34	}
35
36	//TODO Bug: If you use plugin:include to inlcude a page with hidden headers, this processing doesn't happen.
37	//		The only way to fix this is to use a syntax plugin, or do it before save
38	function handlePostProcess(&$event, $param) {
39		if ($this->hidden)
40			foreach ($this->hidden as $h) {
41				$event->data[1] = preg_replace('/(<h\d[^>]*)(>(?:<a name[^>]*>|)' . trim($h) . '(?:<\/a>|)<\/h\d>)/', '$1 style="display:none"$2', $event->data[1]);
42			}
43	}
44
45	function handleToc(&$event, $param) {
46		if ($this->hidden) {
47			$map = array();
48			foreach ($this->hidden as $h) {
49				$map[trim($h)] = 1;
50			}
51			// Remove all hidden headers from the TOC.
52			$newdata = array();
53			foreach ($event->data as $d) {
54				if (!$map[$d['hid']]) {
55					$newdata[] = $d;
56				}
57			}
58
59			global $conf;
60			$minItemsToShow = $conf['tocminheads'] ?: 0;
61			$event->data = count($newdata) < $minItemsToShow ? array() : $newdata;
62		}
63	}
64
65	var $hidden;
66}
67