1<?php
2
3/**
4 * DokuWiki Plugin struct (Action Component)
5 *
6 * @license GPL 2 http://www.gnu.org/licenses/gpl-2.0.html
7 * @author  Andreas Gohr, Michael Große <dokuwiki@cosmocode.de>
8 */
9
10use dokuwiki\Extension\ActionPlugin;
11use dokuwiki\Extension\EventHandler;
12use dokuwiki\Extension\Event;
13use dokuwiki\plugin\struct\meta\Schema;
14use dokuwiki\plugin\struct\meta\StructException;
15
16class action_plugin_struct_ajax extends ActionPlugin
17{
18    /**
19     * Registers a callback function for a given event
20     *
21     * @param EventHandler $controller DokuWiki's event controller object
22     * @return void
23     */
24    public function register(EventHandler $controller)
25    {
26        $controller->register_hook('AJAX_CALL_UNKNOWN', 'BEFORE', $this, 'handleAjax');
27    }
28
29    /**
30     * Pass Ajax call to a type
31     *
32     * @param Event $event event object by reference
33     */
34    public function handleAjax(Event $event)
35    {
36        if ($event->data != 'plugin_struct') return;
37        $event->preventDefault();
38        $event->stopPropagation();
39        global $conf;
40
41        header('Content-Type: application/json');
42        try {
43            $result = $this->executeTypeAjax();
44        } catch (StructException $e) {
45            $result = [
46                'error' => $e->getMessage() . ' ' . basename($e->getFile()) . ':' . $e->getLine()
47            ];
48            if ($conf['allowdebug']) {
49                $result['stacktrace'] = $e->getTraceAsString();
50            }
51            http_status(500);
52        }
53
54        echo json_encode($result, JSON_THROW_ON_ERROR);
55    }
56
57    /**
58     * Check the input variables and run the AJAX call
59     *
60     * @return mixed
61     * @throws StructException
62     */
63    protected function executeTypeAjax()
64    {
65        global $INPUT;
66
67        $col = $INPUT->str('column');
68        if (blank($col)) throw new StructException('No column provided');
69        [$schema, $colname] = explode('.', $col, 2);
70        if (blank($schema) || blank($colname)) throw new StructException('Column format is wrong');
71
72        $schema = new Schema($schema);
73        if (!$schema->getId()) throw new StructException('Unknown Schema');
74
75        $column = $schema->findColumn($colname);
76        if ($column === false) throw new StructException('Column not found');
77
78        return $column->getType()->handleAjax();
79    }
80}
81