1<?php
2
3use ComboStrap\CallStack;
4use ComboStrap\ExceptionNotFound;
5use ComboStrap\HeadingTag;
6use ComboStrap\LogUtility;
7use ComboStrap\PluginUtility;
8use ComboStrap\SiteConfig;
9use ComboStrap\TagAttributes;
10
11
12/**
13 * Class headingwiki
14 * Taking over {@link \dokuwiki\Parsing\ParserMode\Header}
15 */
16class syntax_plugin_combo_headingwiki extends DokuWiki_Syntax_Plugin
17{
18
19    /**
20     * Header pattern
21     *   * Dokuwiki does not made a space mandatory after and before the opening an closing `=` character
22     *   * No line break in the look ahead
23     *   * The capture of the first spaces should be optional otherwise the {@link \dokuwiki\Parsing\ParserMode\Header} is taking over
24     *
25     * See also for information,
26     * the original heading pattern of Dokuwiki {@link \dokuwiki\Parsing\ParserMode\Header}
27     */
28    const ENTRY_PATTERN = '[ \t]*={1,6}(?=[^\n]*={1,6}\s*\r??\n)';
29    const EXIT_PATTERN = '={1,6}\s*(?=\r??\n)';
30    const TAG = "headingwiki";
31
32    const CONF_WIKI_HEADING_ENABLE = "headingWikiEnable";
33    const CONF_DEFAULT_WIKI_ENABLE_VALUE = 1;
34
35
36    /**
37     * When we takes over the dokuwiki heading
38     * we are also taking over the sectioning
39     * and allows {@link syntax_plugin_combo_section}
40     * @return int - 1 or 0
41     */
42    public static function isEnabled(): int
43    {
44        return SiteConfig::getConfValue(self::CONF_WIKI_HEADING_ENABLE, self::CONF_DEFAULT_WIKI_ENABLE_VALUE);
45    }
46
47    public function getSort(): int
48    {
49        /**
50         * It's 49 (on less than the original heading)
51         * {@link \dokuwiki\Parsing\ParserMode\Header::getSort()}
52         */
53        return 49;
54    }
55
56    public function getType(): string
57    {
58        return HeadingTag::SYNTAX_TYPE;
59    }
60
61
62    /**
63     *
64     * How Dokuwiki will add P element
65     *
66     *  * 'normal' - The plugin can be used inside paragraphs (inline)
67     *  * 'block'  - Open paragraphs need to be closed before plugin output - block should not be inside paragraphs
68     *  * 'stack'  - Special case. Plugin wraps other paragraphs. - Stacks can contain paragraphs
69     *
70     * @see DokuWiki_Syntax_Plugin::getPType()
71     *
72     * This is the equivalent of inline or block for css
73     */
74    public function getPType(): string
75    {
76        return HeadingTag::SYNTAX_PTYPE;
77    }
78
79    /**
80     * @return array
81     * Allow which kind of plugin inside
82     *
83     * No one of array('baseonly','container', 'formatting', 'substition', 'protected', 'disabled', 'paragraphs')
84     * because we manage self the content and we call self the parser
85     *
86     * Return an array of one or more of the mode types {@link $PARSER_MODES} in Parser.php
87     */
88    function getAllowedTypes(): array
89    {
90        return array('formatting', 'substition', 'protected', 'disabled');
91    }
92
93
94    public function connectTo($mode)
95    {
96        if ($this->enableWikiHeading($mode)) {
97            $this->Lexer->addEntryPattern(self::ENTRY_PATTERN, $mode, PluginUtility::getModeFromTag($this->getPluginComponent()));
98        }
99    }
100
101    public function postConnect()
102    {
103
104        $this->Lexer->addExitPattern(self::EXIT_PATTERN, PluginUtility::getModeFromTag($this->getPluginComponent()));
105
106    }
107
108
109    /**
110     * Handle the syntax
111     *
112     * At the end of the parser, the `section_open` and `section_close` calls
113     * are created in {@link action_plugin_combo_instructionspostprocessing}
114     * and the text inside for the toc is captured
115     *
116     * @param string $match
117     * @param int $state
118     * @param int $pos
119     * @param Doku_Handler $handler
120     * @return array
121     */
122    public function handle($match, $state, $pos, Doku_Handler $handler): array
123    {
124        switch ($state) {
125
126            case DOKU_LEXER_ENTER:
127                /**
128                 * Title regexp
129                 */
130                $level = $this->getLevelFromMatch($match);
131
132
133                $attributes = TagAttributes::createEmpty(self::TAG)
134                    ->addComponentAttributeValue(HeadingTag::LEVEL, $level)
135                    ->toCallStackArray();
136
137                $callStack = CallStack::createFromHandler($handler);
138                $context = HeadingTag::getContext($callStack);
139
140                return array(
141                    PluginUtility::STATE => $state,
142                    PluginUtility::ATTRIBUTES => $attributes,
143                    PluginUtility::CONTEXT => $context,
144                    PluginUtility::POSITION => $pos
145                );
146            case DOKU_LEXER_UNMATCHED :
147
148                return PluginUtility::handleAndReturnUnmatchedData(self::TAG, $match, $handler);
149
150            case DOKU_LEXER_EXIT :
151
152                $returnedData = HeadingTag::handleExit($handler);
153
154                /**
155                 * Control of the Number of `=` before and after
156                 */
157                $callStack = CallStack::createFromHandler($handler);
158                $callStack->moveToEnd();
159                $openingTag = $callStack->moveToPreviousCorrespondingOpeningCall();
160                $levelFromMatch = $this->getLevelFromMatch($match);
161                $levelFromStartTag = $openingTag->getAttribute(HeadingTag::LEVEL);
162                if ($levelFromMatch != $levelFromStartTag) {
163                    $content = "";
164                    while ($actualCall = $callStack->next()) {
165                        $content .= $actualCall->getCapturedContent();
166                    }
167                    LogUtility::msg("The number of `=` character for a wiki heading is not the same before ($levelFromStartTag) and after ($levelFromMatch) the content ($content).", LogUtility::LVL_MSG_INFO, HeadingTag::CANONICAL);
168                }
169
170                return $returnedData;
171
172        }
173        return array();
174    }
175
176    public function render($format, Doku_Renderer $renderer, $data): bool
177    {
178
179        switch ($format) {
180            case "xhtml":
181                /**
182                 * @var Doku_Renderer_xhtml $renderer
183                 */
184                $state = $data[PluginUtility::STATE];
185                $context = $data[PluginUtility::CONTEXT];
186                switch ($state) {
187
188                    case DOKU_LEXER_ENTER:
189                        $callStackArray = $data[PluginUtility::ATTRIBUTES];
190                        $tagAttributes = TagAttributes::createFromCallStackArray($callStackArray, HeadingTag::HEADING_TAG);
191                        $pos = $data[PluginUtility::POSITION];
192                        HeadingTag::processRenderEnterXhtml($context, $tagAttributes, $renderer, $pos);
193                        return true;
194                    case DOKU_LEXER_UNMATCHED:
195                        $renderer->doc .= PluginUtility::renderUnmatched($data);
196                        return true;
197                    case DOKU_LEXER_EXIT:
198                        $callStackArray = $data[PluginUtility::ATTRIBUTES];
199                        $tagAttributes = TagAttributes::createFromCallStackArray($callStackArray);
200                        $renderer->doc .= HeadingTag::renderClosingTag($tagAttributes, $context);
201                        return true;
202
203                }
204                return false;
205            case renderer_plugin_combo_analytics::RENDERER_FORMAT:
206
207                /**
208                 * @var renderer_plugin_combo_analytics $renderer
209                 */
210                HeadingTag::processMetadataAnalytics($data, $renderer);
211                return true;
212
213            case "metadata":
214
215                /**
216                 * @var Doku_Renderer_metadata $renderer
217                 */
218                HeadingTag::processHeadingEnterMetadata($data, $renderer);
219                return true;
220
221            case renderer_plugin_combo_xml::FORMAT:
222                $state = $data[PluginUtility::STATE];
223                switch ($state) {
224                    case DOKU_LEXER_ENTER:
225                        $level = $data[PluginUtility::ATTRIBUTES][HeadingTag::LEVEL];
226                        $renderer->doc .= "<h$level>";
227                        return true;
228                    case DOKU_LEXER_UNMATCHED:
229                        $renderer->doc .= PluginUtility::renderUnmatchedXml($data);
230                        return true;
231                    case DOKU_LEXER_EXIT:
232                        $level = $data[PluginUtility::ATTRIBUTES][HeadingTag::LEVEL];
233                        $renderer->doc .= "</h$level>";
234                        return true;
235
236                }
237                return false;
238            default:
239                return false;
240        }
241
242    }
243
244    /**
245     * @param $match
246     * @return int
247     */
248    public
249    function getLevelFromMatch($match): int
250    {
251        return 7 - strlen(trim($match));
252    }
253
254
255    private
256    function enableWikiHeading($mode)
257    {
258
259
260        /**
261         * Basically all mode that are not `base`
262         * To not take the dokuwiki heading
263         */
264        if (!(in_array($mode, ['base', 'header', 'table']))) {
265            return true;
266        } else {
267            return SiteConfig::getConfValue(self::CONF_WIKI_HEADING_ENABLE, self::CONF_DEFAULT_WIKI_ENABLE_VALUE);
268        }
269
270
271    }
272
273
274}
275