1<?php
2
3/**
4 * Class action_plugin_interwikipaste
5 */
6class action_plugin_interwikipaste extends DokuWiki_Action_Plugin
7{
8    /**
9     * Register handlers for event hooks
10     *
11     * @param Doku_Event_Handler $controller
12     */
13    public function register(Doku_Event_Handler $controller)
14    {
15        $controller->register_hook('DOKUWIKI_STARTED', 'AFTER', $this, 'addInterwikisToJSINFO');
16    }
17
18    public function addInterwikisToJSINFO(Doku_Event $event)
19    {
20        global $JSINFO;
21        $JSINFO['plugins']['interwikipaste']['patterns'] = json_encode($this->getInterwikiPatterns());
22    }
23
24    /**
25     * Loads interwiki configuration and transforms it into regular expressions
26     *
27     * @return array
28     */
29    protected function getInterwikiPatterns()
30    {
31        $patterns = [];
32        $wikis = getInterwiki();
33
34        // sort urls by longer first (probably more specific matches)
35        uasort($wikis, function ($a, $b) {
36            if (strlen($a) === strlen($b)) {
37                return 0;
38            }
39            return (strlen($a) > strlen($b)) ? -1 : 1;
40        });
41
42        foreach ($wikis as $shortcut => $url) {
43            // escaping now makes it easier to manipulate regex patterns later
44            $pattern = preg_quote_cb($url);
45            $encode = (preg_match('/{URL|QUERY\\\}/', $url) === 1);
46
47            // replace already escaped placeholders with named groups
48            $cnt = 0;
49            $pattern = preg_replace(
50                '/\\\{(URL|NAME|SCHEME|HOST|PORT|PATH|QUERY)\\\}/',
51                '([^ ]+)?',
52                $pattern,
53                -1,
54                $cnt
55            );
56
57            if (!$cnt) {
58                $pattern .= '([^ ]+)?';
59            }
60
61            $patterns[] = [
62                'shortcut' => $shortcut,
63                'pattern' => $pattern,
64                'encode' => $encode,
65            ];
66        }
67
68        return $patterns;
69    }
70}
71