1<?php
2
3use dokuwiki\Extension\ActionPlugin;
4use dokuwiki\Extension\EventHandler;
5use dokuwiki\Extension\Event;
6
7/**
8 * DokuWiki Plugin tagbutton (Action Component)
9 *
10 * @license GPL 2 http://www.gnu.org/licenses/gpl-2.0.html
11 * @author Louis Ouellet <louis_ouellet@hotmail.com>
12 */
13class action_plugin_tagbutton extends ActionPlugin
14{
15    /** @inheritDoc */
16    public function register(EventHandler $controller)
17    {
18        $controller->register_hook('AJAX_CALL_UNKNOWN', 'BEFORE', $this, 'handle_ajax');
19    }
20
21    /**
22     * Event handler for EXAMPLE_EVENT
23     *
24     * @see https://www.dokuwiki.org/devel:events:EXAMPLE_EVENT
25     * @param Event $event Event object
26     * @param mixed $param optional parameter passed when event was registered
27     * @return void
28     */
29    public function handle_ajax(Event $event, $param)
30    {
31        if($event->data !== 'tagbutton_add') return;
32
33        global $INPUT, $ID, $TEXT;
34        $event->preventDefault();
35        $event->stopPropagation();
36
37        // Get the tag and page ID from the AJAX request
38        $tag = $INPUT->str('tag');
39        $id = $INPUT->str('id');
40
41        if($tag && $id) {
42            $pageContent = rawWiki($id);
43
44            // Check if {{tag>}} already exists
45            if (preg_match('/\{\{tag>(.*?)\}\}/', $pageContent, $matches)) {
46                $existingTags = explode(' ', trim($matches[1]));
47
48                // If tag already exists and the configuration is set to hide the button, return
49                if (in_array($tag, $existingTags) && $this->getConf('hide_if_exists')) {
50                    echo json_encode(array('status' => 'exists'));
51                    exit;
52                }
53
54                // Add the tag if it doesn't already exist
55                if (!in_array($tag, $existingTags)) {
56                    $existingTags[] = $tag;
57                    $newTagBlock = '{{tag>' . implode(' ', $existingTags) . '}}';
58                    $pageContent = str_replace($matches[0], $newTagBlock, $pageContent);
59                }
60            } else {
61                // If no {{tag>}} block exists, add one
62                $newTagBlock = '{{tag>' . $tag . '}}';
63                $pageContent .= "\n\n" . $newTagBlock;
64            }
65
66            // Save the updated content
67            saveWikiText($id, $pageContent, 'Added tag: ' . $tag);
68            echo json_encode(array('status' => 'success'));
69        } else {
70            echo json_encode(array('status' => 'error'));
71        }
72        exit;
73    }
74}
75