xref: /plugin/struct/action/ajax.php (revision 9937cf33bb50a3dfba07030f80c51155dc7cb314)
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 dokuwiki\plugin\struct\meta\Schema;
11use dokuwiki\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     */
34    public function handle_ajax(Doku_Event $event, $param) {
35        if($event->data != 'plugin_struct') return;
36        $event->preventDefault();
37        $event->stopPropagation();
38        global $conf;
39
40        header('Content-Type: application/json');
41        try {
42            $result = $this->executeTypeAjax();
43        } catch(StructException $e) {
44            $result = array(
45                'error' => $e->getMessage().' '.basename($e->getFile()).':'.$e->getLine()
46            );
47            if($conf['allowdebug']) {
48                $result['stacktrace'] = $e->getTraceAsString();
49            }
50            http_status(500);
51        }
52
53        $json = new JSON;
54        echo $json->encode($result);
55    }
56
57    /**
58     * Check the input variables and run the AJAX call
59     *
60     * @throws StructException
61     * @return mixed
62     */
63    protected function executeTypeAjax() {
64        global $INPUT;
65
66        $col = $INPUT->str('column');
67        if(blank($col)) throw new StructException('No column provided');
68        list($schema, $colname) = explode('.', $col, 2);
69        if(blank($schema) || blank($colname)) throw new StructException('Column format is wrong');
70
71        $schema = new Schema($schema);
72        if(!$schema->getId()) throw new StructException('Unknown Schema');
73
74        $column = $schema->findColumn($colname);
75        if($column === false) throw new StructException('Column not found');
76
77        return $column->getType()->handleAjax();
78    }
79}
80