xref: /plugin/pagecss/action.php (revision 068b6f4abe5d64ce6163f21b4ecaf9fdfc068701)
1<?php
2/**
3 * DokuWiki Plugin: pagecss
4 *
5 * This plugin allows DokuWiki users to embed custom CSS directly within their
6 * wiki pages using `<pagecss>...</pagecss>` blocks. The CSS defined within
7 * these blocks is then extracted, processed, and injected into the `<head>`
8 * section of the generated HTML page.
9 *
10 * It also provides a feature to automatically wrap CSS rules for classes
11 * found within the `<pagecss>` block (e.g., `.myclass { ... }`) with a
12 * `.wrap_myclass { ... }` equivalent. This is useful for styling elements
13 * that are automatically wrapped by DokuWiki's `.wrap` classes.
14 *
15 * Author: Your Name/Entity (or original author if known)
16 * Date: 2023-10-27 (or original creation date)
17 *
18 * @license GPL 2 (http://www.gnu.org/licenses/gpl.html)
19 */
20
21// Import necessary DokuWiki extension classes
22use dokuwiki\Extension\ActionPlugin;
23use dokuwiki\Extension\EventHandler;
24use dokuwiki\Extension\Event;
25
26/**
27 * Class action_plugin_pagecss
28 *
29 * This class extends DokuWiki's ActionPlugin to hook into specific DokuWiki
30 * events for processing and injecting custom page-specific CSS.
31 */
32class action_plugin_pagecss extends ActionPlugin {
33
34    /**
35     * Registers the plugin's hooks with the DokuWiki event handler.
36     *
37     * This method is called by DokuWiki during plugin initialization.
38     * It sets up which DokuWiki events this plugin will listen for and
39     * which methods will handle those events.
40     *
41     * @param EventHandler $controller The DokuWiki event handler instance.
42     */
43    public function register(EventHandler $controller) {
44        // Register a hook to inject custom CSS into the HTML header.
45        // 'TPL_METAHEADER_OUTPUT' is triggered just before the <head> section is closed.
46        // 'BEFORE' ensures our CSS is added before other elements that might rely on it.
47        // '$this' refers to the current plugin instance.
48        // 'inject_css' is the method that will be called when this event fires.
49        $controller->register_hook('TPL_METAHEADER_OUTPUT', 'BEFORE', $this, 'inject_css');
50
51        // Register a hook to handle metadata caching and extraction of CSS.
52        // 'PARSER_CACHE_USE' is triggered before DokuWiki attempts to use its parser cache.
53        // 'BEFORE' allows us to modify the metadata before the page is rendered or cached.
54        // 'handle_metadata' is the method that will be called.
55        $controller->register_hook('PARSER_CACHE_USE', 'BEFORE', $this, 'handle_metadata');
56    }
57
58    /**
59     * Extracts CSS content from `<pagecss>...</pagecss>` blocks within a DokuWiki page.
60     *
61     * This method is triggered by the 'PARSER_CACHE_USE' event. It reads the raw
62     * content of the current wiki page, finds all `<pagecss>` blocks, combines
63     * their content, and stores it in the page's metadata. It also generates
64     * `.wrap_classname` rules for any classes found in the embedded CSS.
65     *
66     * @param \Doku_Event $event The DokuWiki event object, containing page data.
67     */
68    public function handle_metadata(\Doku_Event $event) {
69        global $ID; // Global variable holding the current DokuWiki page ID.
70
71        // Sanitize the page ID to ensure it's safe for file system operations and metadata.
72        $id = cleanID($ID);
73        // Get the raw content of the current wiki page. This includes all wiki syntax.
74        $text = rawWiki($id);
75
76        // Use a regular expression to find all occurrences of <pagecss>...</pagecss> blocks.
77        // The /s modifier makes the dot (.) match newlines as well, allowing multiline CSS.
78        // The (.*?) captures the content between the tags non-greedily.
79        preg_match_all('/<pagecss>(.*?)<\/pagecss>/s', $text, $matches);
80
81        // Check if any <pagecss> blocks were found.
82        if (!empty($matches[1])) {
83            // If blocks are found, combine all captured CSS content into a single string.
84            // trim() is used to remove leading/trailing whitespace from each block.
85            $styles = implode(" ", array_map('trim', $matches[1]));
86
87            // If there's actual CSS content after trimming and combining.
88            if ($styles) {
89                $extra = ''; // Initialize a variable to hold the generated .wrap_classname styles.
90
91                // Find all CSS class selectors (e.g., .myclass) within the extracted styles.
92                // This regex captures the class name (e.g., 'myclass').
93                preg_match_all('/\.([a-zA-Z0-9_-]+)\s*\{[^}]*\}/', $styles, $class_matches);
94
95                // Iterate over each found class name.
96                foreach ($class_matches[1] as $classname) {
97                    // Construct a regex pattern to find the full CSS rule for the current class.
98                    $pattern = '/\.' . preg_quote($classname, '/') . '\s*\{([^}]*)\}/';
99                    // Match the specific class rule in the combined styles.
100                    if (preg_match($pattern, $styles, $style_block)) {
101                        // Extract the content of the CSS rule (e.g., "color: red; font-size: 1em;").
102                        $css_properties = $style_block[1];
103
104                        // Basic check to avoid malformed or incomplete styles that might contain
105                        // unclosed braces, which could lead to invalid CSS.
106                        if (strpos($css_properties, '{') === false && strpos($css_properties, '}') === false) {
107                            // Append the generated .wrap_classname rule to the $extra string.
108                            // DokuWiki often wraps user content in divs with classes like .wrap_someclass.
109                            // This ensures that custom CSS can target these wrapped elements.
110                            $extra .= ".wrap_$classname {{$css_properties}}\n";
111                        }
112                    }
113                }
114
115                // Append the generated .wrap_classname styles to the main $styles string.
116                $styles .= "\n" . trim($extra);
117
118                // IMPORTANT: Prevent premature closing of the <style> tag in the HTML output.
119                // If a user accidentally or maliciously types `</style>` inside `<pagecss>`,
120                // this replaces it with `<\style>` which is still valid CSS but doesn't close the tag.
121                $styles = str_replace('</', '<\/', $styles);
122
123                // Store the processed CSS styles in the page's metadata.
124                // This makes the styles available later when the HTML header is generated.
125                p_set_metadata($id, ['pagecss' => ['styles' => $styles]]);
126
127                // Invalidate the DokuWiki parser cache for this page whenever its content changes.
128                // This ensures that if the <pagecss> blocks are modified, the metadata is re-extracted.
129                $event->data['depends']['page'][] = $id;
130
131                return; // Exit the function as styles were found and processed.
132            }
133        }
134
135        // If no <pagecss> blocks were found or they were empty,
136        // ensure the 'pagecss' metadata entry is reset to an empty string.
137        // This prevents old CSS from being injected if the blocks are removed.
138        p_set_metadata($id, ['pagecss' => ['styles' => '']]);
139    }
140
141    /**
142     * Injects the extracted CSS into the HTML `<head>` section of the DokuWiki page.
143     *
144     * This method is triggered by the 'TPL_METAHEADER_OUTPUT' event. It retrieves
145     * the stored CSS from the page's metadata and adds it to the event data,
146     * which DokuWiki then uses to build the `<head>` section.
147     *
148     * @param Doku_Event $event The DokuWiki event object, specifically for metaheader output.
149     */
150    public function inject_css(Doku_Event $event) {
151        global $ID; // Global variable holding the current DokuWiki page ID.
152
153        // Sanitize the page ID.
154        $id = cleanID($ID);
155
156        // Retrieve the 'pagecss' metadata for the current page.
157        $data = p_get_metadata($id, 'pagecss');
158        // Extract the 'styles' content from the metadata, defaulting to an empty string if not set.
159        $styles = isset($data['styles']) ? $data['styles'] : '';
160
161        // Check if there are valid styles to inject and ensure it's a string.
162        if ($styles && is_string($styles)) {
163            // Add the custom CSS to the event's 'style' array.
164            // DokuWiki's template system will then automatically render this
165            // as a <style> block within the HTML <head>.
166            $event->data['style'][] = [
167                'type' => 'text/css', // Specifies the content type.
168                'media' => 'screen',  // Specifies the media type for the CSS (e.g., 'screen', 'print').
169                '_data' => $styles,   // The actual CSS content.
170            ];
171        }
172    }
173
174}
175