xref: /plugin/struct/action/ajax.php (revision 61356325e2c5dbdcb8405fa2eb4c34732d79b65f)
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
10// must be run within Dokuwiki
11use dokuwiki\plugin\struct\meta\Schema;
12use dokuwiki\plugin\struct\meta\StructException;
13
14if (!defined('DOKU_INC')) die();
15
16class action_plugin_struct_ajax extends DokuWiki_Action_Plugin
17{
18
19    /**
20     * Registers a callback function for a given event
21     *
22     * @param Doku_Event_Handler $controller DokuWiki's event controller object
23     * @return void
24     */
25    public function register(Doku_Event_Handler $controller)
26    {
27        $controller->register_hook('AJAX_CALL_UNKNOWN', 'BEFORE', $this, 'handle_ajax');
28    }
29
30    /**
31     * Pass Ajax call to a type
32     *
33     * @param Doku_Event $event event object by reference
34     * @param mixed $param [the parameters passed as fifth argument to register_hook() when this
35     *                           handler was registered]
36     */
37    public function handle_ajax(Doku_Event $event, $param)
38    {
39        if ($event->data != 'plugin_struct') return;
40        $event->preventDefault();
41        $event->stopPropagation();
42        global $conf;
43
44        header('Content-Type: application/json');
45        try {
46            $result = $this->executeTypeAjax();
47        } catch (StructException $e) {
48            $result = array(
49                'error' => $e->getMessage() . ' ' . basename($e->getFile()) . ':' . $e->getLine()
50            );
51            if ($conf['allowdebug']) {
52                $result['stacktrace'] = $e->getTraceAsString();
53            }
54            http_status(500);
55        }
56
57        $json = new JSON();
58        echo $json->encode($result);
59    }
60
61    /**
62     * Check the input variables and run the AJAX call
63     *
64     * @throws StructException
65     * @return mixed
66     */
67    protected function executeTypeAjax()
68    {
69        global $INPUT;
70
71        $col = $INPUT->str('column');
72        if (blank($col)) throw new StructException('No column provided');
73        list($schema, $colname) = explode('.', $col, 2);
74        if (blank($schema) || blank($colname)) throw new StructException('Column format is wrong');
75
76        $schema = new Schema($schema);
77        if (!$schema->getId()) throw new StructException('Unknown Schema');
78
79        $column = $schema->findColumn($colname);
80        if ($column === false) throw new StructException('Column not found');
81
82        return $column->getType()->handleAjax();
83    }
84}
85