xref: /plugin/jstweak/action.php (revision 758a829520f98d6c9b6486cd3fa0aa9d3e139135)
1<?php
2
3// must be run within Dokuwiki
4if(!defined('DOKU_INC')) die();
5
6use dokuwiki\Extension\ActionPlugin;
7use dokuwiki\Extension\EventHandler;
8use dokuwiki\Extension\Event;
9use dokuwiki\Logger;
10
11/**
12 * DokuWiki Plugin jstweak (Action Component)
13 *
14 * @license GPL 2 http://www.gnu.org/licenses/gpl-2.0.html
15 * @author Volker Bürckel <volker@vrbdev.eu>
16 */
17class action_plugin_jstweak extends ActionPlugin
18{
19    const PLUGIN_PATH = DOKU_INC . 'lib/plugins/';
20    const OVERRIDE_PATH = DOKU_CONF . 'plugins.script.local.js.d/';
21    const SCRIPT_NAME = 'script.js';
22
23    /** @inheritDoc */
24    public function register(EventHandler $controller)
25    {
26        $controller->register_hook('JS_SCRIPT_LIST', 'AFTER', $this, 'handleJsScriptList');
27    }
28
29    /**
30     * Event handler for JS_SCRIPT_LIST
31     *
32     * For any plugin's script.js found in the list, it checks for existence
33     * of a local override script.js in the subdirectory
34     *   plugins.script.local.js.d/<pluginName>/
35     * of the conf directory.
36     *
37     * @see https://www.dokuwiki.org/devel:events:JS_SCRIPT_LIST
38     * @param Event $event Event object, $event->data holds the list
39     * @param mixed $param optional parameter passed when event was registered
40     * @return void
41     */
42    public function handleJsScriptList(Event $event, $param)
43    {
44        $pluginPathLen = strlen(self::PLUGIN_PATH);
45        $scriptNameLen = strlen(self::SCRIPT_NAME);
46
47        foreach ($event->data as $key => $entry) {
48            // if we have a plugin's script.js file...
49            if (str_starts_with($entry, self::PLUGIN_PATH)
50                && str_ends_with($entry, self::SCRIPT_NAME)) {
51                // ... extract the plugin's name, ...
52                $pluginName = substr(
53                    $entry,
54                    $pluginPathLen,
55                    strlen($entry) - $pluginPathLen - $scriptNameLen - 1
56                );
57                // ... check if there's a local replacement file ...
58                $newEntry = self::OVERRIDE_PATH . $pluginName . '/' . self::SCRIPT_NAME;
59                if (file_exists($newEntry)) {
60                    // ... and if yes: change the script list.
61                    $event->data[$key] = $newEntry;
62                    Logger::debug("jstweak: new script.js for plugin $pluginName -> $newEntry");
63                }
64            }
65        }
66    }
67}
68