1<?php
2
3use dokuwiki\Extension\ActionPlugin;
4use dokuwiki\Extension\EventHandler;
5use dokuwiki\Extension\Event;
6
7/**
8 * DokuWiki Plugin iconify (Action Component)
9 *
10 * @license GPL 2 http://www.gnu.org/licenses/gpl-2.0.html
11 * @author Tokano <contact@tokano.fr>
12 */
13class action_plugin_iconify extends ActionPlugin
14{
15    /** @inheritDoc */
16    public function register(EventHandler $controller)
17    {
18        $controller->register_hook('TPL_METAHEADER_OUTPUT', 'BEFORE', $this, 'add_iconify_resources');
19    }
20
21    /**
22     * Event handler for TPL_METAHEADER_OUTPUT
23     *
24     * @param Event $event Event object
25     * @return void
26     */
27    public function add_iconify_resources(Event $event)
28    {
29        // Check if the user wants to use a local file
30        $useLocal = $this->getConf('use_local');
31
32        if ($useLocal) {
33            // Use local file path
34            $localPath = DOKU_INC . 'lib/plugins/iconify/local/iconify.min.js';
35
36            if (file_exists($localPath)) {
37                $event->data["script"][] = [
38                    "type" => "text/javascript",
39                    "src" => DOKU_BASE . 'lib/plugins/iconify/local/iconify.min.js',
40                    "defer" => "defer"
41                ];
42            } else {
43                // If the local file is missing, log an error
44                msg('Iconify: Local file not found. Please upload iconify.min.js to the plugin\'s local folder.', -1);
45            }
46        } else {
47            // Use the online option and get the version from the plugin configuration
48            $version = $this->getConf('iconify_version');
49
50            // If version is not set, fetch the latest version dynamically
51            if (!$version || $version === 'latest') {
52                $version = $this->fetchLatestVersion();
53            }
54
55            // Build the script URL
56            $url = "https://cdnjs.cloudflare.com/ajax/libs/iconify/$version/iconify.min.js";
57
58            // Add the Iconify script
59            $event->data["script"][] = [
60                "type" => "text/javascript",
61                "src" => $url,
62                "defer" => "defer"
63            ];
64        }
65    }
66
67    private function fetchLatestVersion() {
68        $apiUrl = "https://api.cdnjs.com/libraries/iconify";
69        $response = file_get_contents($apiUrl);
70
71        if ($response === false) {
72            // Fall back to a default version in case of an error
73            return "3.1.1";
74        }
75
76        $data = json_decode($response, true);
77
78        if (isset($data['version'])) {
79            return $data['version'];
80        }
81
82        // Fall back to a default version if the API response is not as expected
83        return "3.1.1";
84    }
85}
86