xref: /plugin/struct/action/ajax.php (revision 9dfe4ab9e4aeda253f7504b2f05a184dce5b678f)
1<?php
2/**
3 * DokuWiki Plugin struct (Action Component)
4 *
5 * @license GPL 2 http://www.gnu.org/licenses/gpl-2.0.html
6 * @author  Andreas Gohr, Michael Große <dokuwiki@cosmocode.de>
7 */
8
9// must be run within Dokuwiki
10use plugin\struct\meta\Schema;
11use plugin\struct\meta\StructException;
12
13if(!defined('DOKU_INC')) die();
14
15class action_plugin_struct_ajax extends DokuWiki_Action_Plugin {
16
17    /**
18     * Registers a callback function for a given event
19     *
20     * @param Doku_Event_Handler $controller DokuWiki's event controller object
21     * @return void
22     */
23    public function register(Doku_Event_Handler $controller) {
24        $controller->register_hook('AJAX_CALL_UNKNOWN', 'BEFORE', $this, 'handle_ajax');
25    }
26
27    /**
28     * Pass Ajax call to a type
29     *
30     * @param Doku_Event $event event object by reference
31     * @param mixed $param [the parameters passed as fifth argument to register_hook() when this
32     *                           handler was registered]
33     * @return bool
34     */
35    public function handle_ajax(Doku_Event $event, $param) {
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 = array(
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        $json = new JSON;
55        echo $json->encode($result);
56    }
57
58    /**
59     * Check the input variables and run the AJAX call
60     *
61     * @throws StructException
62     * @return mixed
63     */
64    protected function executeTypeAjax() {
65        global $INPUT;
66
67        $col = $INPUT->str('column');
68        if(blank($col)) throw new StructException('No column provided');
69        list($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