xref: /dokuwiki/inc/Parsing/ModeRegistry.php (revision 0244be5c08829b6ca187d7158bca94e7c2fd7be3)
1<?php
2
3namespace dokuwiki\Parsing;
4
5use dokuwiki\Extension\PluginInterface;
6use dokuwiki\Extension\SyntaxPlugin;
7use dokuwiki\Parsing\ParserMode\Acronym;
8use dokuwiki\Parsing\ParserMode\ModeInterface;
9use dokuwiki\Parsing\ParserMode\Camelcaselink;
10use dokuwiki\Parsing\ParserMode\Entity;
11use dokuwiki\Parsing\ParserMode\Smiley;
12
13/**
14 * Central registry for parser mode categories and mode instantiation.
15 *
16 * The underlying data is kept in the global $PARSER_MODES array because
17 * third-party plugins read and write it directly at runtime (e.g. to register
18 * their mode in a category). All methods in this class operate on that global
19 * so changes are visible to both old and new code.
20 */
21class ModeRegistry
22{
23    // Category constants (preserving the historical 'substition' typo)
24    public const CATEGORY_CONTAINER   = 'container';
25    public const CATEGORY_BASEONLY    = 'baseonly';
26    public const CATEGORY_FORMATTING  = 'formatting';
27    public const CATEGORY_SUBSTITION  = 'substition';
28    public const CATEGORY_PROTECTED   = 'protected';
29    public const CATEGORY_DISABLED    = 'disabled';
30    public const CATEGORY_PARAGRAPHS  = 'paragraphs';
31
32    /** @var array{sort: int, mode: string, obj: ModeInterface}[]|null */
33    private ?array $modes = null;
34
35    /** @var string[] Modes that handle their own line endings (skip EOL connection) */
36    private array $blockEolModes = [];
37
38    /** @var array<string, string[]> Mode name => regex-escaped line start marker characters */
39    private array $lineStartMarkers = [];
40
41    private static ?self $instance = null;
42
43    /**
44     * Get the singleton instance of the ModeRegistry.
45     *
46     * @return self
47     */
48    public static function getInstance(): self
49    {
50        if (!self::$instance instanceof self) {
51            self::$instance = new self();
52        }
53        return self::$instance;
54    }
55
56    /**
57     * Reset the singleton instance.
58     *
59     * This is mainly useful for testing to force re-initialization.
60     *
61     * @return void
62     */
63    public static function reset(): void
64    {
65        self::$instance = null;
66    }
67
68    /**
69     * Constructor. Initializes the global $PARSER_MODES array with the default mode categories.
70     */
71    private function __construct()
72    {
73        global $PARSER_MODES;
74        $PARSER_MODES = [
75            self::CATEGORY_CONTAINER  => ['listblock', 'table', 'quote', 'hr'],
76            self::CATEGORY_BASEONLY   => ['header'],
77            self::CATEGORY_FORMATTING => [
78                'strong', 'emphasis', 'underline', 'monospace',
79                'subscript', 'superscript', 'deleted', 'footnote',
80                'gfm_emphasis', 'gfm_emphasis_underscore', 'gfm_strong_underscore',
81                'gfm_emphasis_strong', 'gfm_emphasis_strong_underscore',
82                'gfm_deleted',
83            ],
84            self::CATEGORY_SUBSTITION => [
85                'acronym', 'smiley', 'wordblock', 'entity',
86                'camelcaselink', 'internallink', 'media', 'externallink',
87                'linebreak', 'emaillink', 'windowssharelink', 'filelink',
88                'notoc', 'nocache', 'multiplyentity', 'quotes', 'rss',
89            ],
90            self::CATEGORY_PROTECTED  => ['preformatted', 'code', 'file'],
91            self::CATEGORY_DISABLED   => ['unformatted'],
92            self::CATEGORY_PARAGRAPHS => ['eol'],
93        ];
94    }
95
96    /**
97     * Get all mode names in the given categories.
98     *
99     * @param string[] $categories One or more CATEGORY_* constants
100     * @return string[] Unique list of mode names
101     */
102    public function getModesForCategories(array $categories): array
103    {
104        global $PARSER_MODES;
105        $modes = [];
106        foreach ($categories as $cat) {
107            if (isset($PARSER_MODES[$cat])) {
108                $modes = array_merge($modes, $PARSER_MODES[$cat]);
109            }
110        }
111        return array_unique($modes);
112    }
113
114    /**
115     * Get the raw categories array.
116     *
117     * @return array<string, string[]> Category name => list of mode names
118     */
119    public function getCategories(): array
120    {
121        global $PARSER_MODES;
122        return $PARSER_MODES;
123    }
124
125    /**
126     * Register a mode in a category.
127     *
128     * @param string $category One of the CATEGORY_* constants
129     * @param string $modeName The mode name to register
130     * @return void
131     */
132    public function registerMode(string $category, string $modeName): void
133    {
134        global $PARSER_MODES;
135        $PARSER_MODES[$category][] = $modeName;
136        $this->modes = null; // invalidate cached mode list
137    }
138
139    /**
140     * Register a mode that handles its own line endings.
141     * Modes registered here will be skipped by Eol's connectTo().
142     *
143     * @param string $mode The mode name
144     * @return void
145     */
146    public function registerBlockEolMode(string $mode): void
147    {
148        $this->blockEolModes[] = $mode;
149    }
150
151    /**
152     * Get all modes that handle their own line endings.
153     *
154     * @return string[]
155     */
156    public function getBlockEolModes(): array
157    {
158        return $this->blockEolModes;
159    }
160
161    /**
162     * Register regex-escaped line start marker characters for a mode.
163     * Preformatted uses these to build a negative lookahead.
164     *
165     * @param string $mode The mode name
166     * @param string[] $markers Regex-escaped marker characters (e.g. ['\\*', '\\-'])
167     * @return void
168     */
169    public function registerLineStartMarkers(string $mode, array $markers): void
170    {
171        $this->lineStartMarkers[$mode] = $markers;
172    }
173
174    /**
175     * Get all registered line start markers, merged and deduplicated.
176     *
177     * @return string[]
178     */
179    public function getLineStartMarkers(): array
180    {
181        if (!$this->lineStartMarkers) return [];
182        return array_unique(array_merge(...array_values($this->lineStartMarkers)));
183    }
184
185    /**
186     * Get all parser modes, fully instantiated and sorted by priority.
187     *
188     * This includes syntax plugins, built-in modes, formatting modes, and
189     * data-driven modes (smileys, acronyms, entities). Results are cached
190     * unless running in a test environment.
191     *
192     * @return array[] Each entry is ['sort' => int, 'mode' => string, 'obj' => ModeInterface]
193     */
194    public function getModes(): array
195    {
196        global $conf;
197
198        if ($this->modes !== null && !defined('DOKU_UNITTEST')) {
199            return $this->modes;
200        }
201
202        $this->modes = [];
203        $syntax = $conf['syntax'] ?? 'dokuwiki';
204        $loadDw = in_array($syntax, ['dokuwiki', 'dw+md', 'md+dw']);
205        $loadMd = in_array($syntax, ['markdown', 'dw+md', 'md+dw']);
206
207        $this->loadPluginModes();
208        $this->loadAlwaysModes();
209        if ($loadDw) $this->loadDokuWikiModes();
210        if ($loadMd) $this->loadMarkdownModes();
211        $this->loadDataModes();
212
213        usort($this->modes, self::sortModes(...));
214        return $this->modes;
215    }
216
217    /**
218     * Load syntax plugin modes and register them in their categories.
219     */
220    protected function loadPluginModes(): void
221    {
222        global $PARSER_MODES;
223
224        $plugins = plugin_list('syntax');
225        foreach ($plugins as $p) {
226            $obj = plugin_load('syntax', $p);
227            if (!$obj instanceof PluginInterface) continue;
228            $PARSER_MODES[$obj->getType()][] = "plugin_$p";
229            $this->modes[] = [
230                'sort' => $obj->getSort(),
231                'mode' => "plugin_$p",
232                'obj'  => $obj,
233            ];
234            unset($obj);
235        }
236    }
237
238    /**
239     * Load modes that have no equivalent in the other syntax.
240     * These are always active regardless of the syntax setting.
241     */
242    protected function loadAlwaysModes(): void
243    {
244        global $conf;
245
246        $modes = [
247            'strong', 'monospace', 'subscript', 'superscript',
248            'footnote', 'eol', 'unformatted', 'preformatted', 'file',
249            'quote', 'externallink', 'emaillink', 'windowssharelink',
250            'notoc', 'nocache', 'rss',
251        ];
252
253        if ($conf['typography']) {
254            $modes[] = 'quotes';
255            $modes[] = 'multiplyentity';
256        }
257
258        $this->instantiateModes($modes);
259    }
260
261    /**
262     * Load DokuWiki-specific modes for features that also exist in Markdown.
263     * Skipped when syntax is 'markdown'.
264     */
265    protected function loadDokuWikiModes(): void
266    {
267        global $conf;
268        $syntax = $conf['syntax'] ?? 'dokuwiki';
269        $dwPreferred = in_array($syntax, ['dokuwiki', 'dw+md'], true);
270
271        $modes = [
272            'emphasis', 'deleted', 'code', 'header', 'hr',
273            'linebreak', 'internallink', 'media', 'listblock', 'table',
274        ];
275
276        // Underline only loads when DokuWiki is preferred. In MD-preferred
277        // modes, `__` means strong (via gfm_strong_underscore) and loading
278        // Underline here would conflict.
279        if ($dwPreferred) {
280            $modes[] = 'underline';
281        }
282
283        $this->instantiateModes($modes);
284    }
285
286    /**
287     * Load Markdown-specific modes for features that also exist in DokuWiki.
288     * Skipped when syntax is 'dokuwiki'.
289     */
290    protected function loadMarkdownModes(): void
291    {
292        global $conf;
293        $syntax = $conf['syntax'] ?? 'dokuwiki';
294        $mdPreferred = in_array($syntax, ['markdown', 'md+dw'], true);
295
296        $modes = ['gfm_emphasis', 'gfm_emphasis_strong', 'gfm_deleted'];
297
298        // Underscore-based emphasis and strong only load when Markdown is
299        // preferred. In DW-preferred modes, `__` means underline and loading
300        // these would conflict.
301        if ($mdPreferred) {
302            $modes[] = 'gfm_emphasis_underscore';
303            $modes[] = 'gfm_strong_underscore';
304            $modes[] = 'gfm_emphasis_strong_underscore';
305        }
306
307        $this->instantiateModes($modes);
308    }
309
310    /**
311     * Load data-driven modes that require constructor arguments
312     * (smileys, acronyms, entities) and optional config-gated modes.
313     */
314    protected function loadDataModes(): void
315    {
316        global $conf;
317
318        $obj = new Smiley(array_keys(getSmileys()));
319        $this->modes[] = ['sort' => $obj->getSort(), 'mode' => 'smiley', 'obj' => $obj];
320
321        $obj = new Acronym(array_keys(getAcronyms()));
322        $this->modes[] = ['sort' => $obj->getSort(), 'mode' => 'acronym', 'obj' => $obj];
323
324        $obj = new Entity(array_keys(getEntities()));
325        $this->modes[] = ['sort' => $obj->getSort(), 'mode' => 'entity', 'obj' => $obj];
326
327        if (!empty($conf['camelcase'])) {
328            $obj = new Camelcaselink();
329            $this->modes[] = ['sort' => $obj->getSort(), 'mode' => 'camelcaselink', 'obj' => $obj];
330        }
331    }
332
333    /**
334     * Instantiate mode classes by name and add them to the mode list.
335     *
336     * Mode names are split on `_` and each segment is PascalCased to form the
337     * class name (e.g. `gfm_emphasis_underscore` → `GfmEmphasisUnderscore`,
338     * `internallink` → `Internallink`, `strong` → `Strong`).
339     *
340     * @param string[] $modeNames
341     */
342    protected function instantiateModes(array $modeNames): void
343    {
344        foreach ($modeNames as $mode) {
345            $class = implode('', array_map('ucfirst', explode('_', $mode))); // snake_case to PascalCase
346            $class = 'dokuwiki\\Parsing\\ParserMode\\' . $class; // prepend namespace
347            $obj = new $class();
348            $this->modes[] = [
349                'sort' => $obj->getSort(),
350                'mode' => $mode,
351                'obj'  => $obj,
352            ];
353        }
354    }
355
356    /**
357     * Callback function for usort
358     *
359     * @param array $a
360     * @param array $b
361     * @return int
362     */
363    public static function sortModes(array $a, array $b): int
364    {
365        return $a['sort'] <=> $b['sort'];
366    }
367}
368