xref: /dokuwiki/inc/Remote/JsonRpcServer.php (revision f657e5d050d6b1d1cb1ea1c656f5aec61f5067de)
1<?php
2
3namespace dokuwiki\Remote;
4
5/**
6 * Provide the Remote XMLRPC API as a JSON based API
7 */
8class JsonRpcServer
9{
10
11    protected $remote;
12
13    /**
14     * JsonRpcServer constructor.
15     */
16    public function __construct()
17    {
18        $this->remote = new Api();
19        $this->remote->setFileTransformation(array($this, 'toFile'));
20    }
21
22    /**
23     * Serve the request
24     *
25     * @return mixed
26     * @throws RemoteException
27     */
28    public function serve()
29    {
30        global $conf;
31        if (!$conf['remote']) {
32            http_status(404);
33            throw new RemoteException("JSON-RPC server not enabled.", -32605);
34        }
35        if (!empty($conf['remotecors'])) {
36            header('Access-Control-Allow-Origin: ' . $conf['remotecors']);
37        }
38
39        global $INPUT;
40
41        $call = $INPUT->server->str('PATH_INFO');
42        $call = trim($call, '/');
43        $args = json_decode(file_get_contents('php://input'), true);
44        if (!is_array($args)) $args = [];
45
46        return $this->call($call, $args);
47    }
48
49    /**
50     * Call an API method
51     *
52     * @param string $methodname
53     * @param array $args
54     * @return mixed
55     * @throws RemoteException
56     */
57    public function call($methodname, $args)
58    {
59        try {
60            $result = $this->remote->call($methodname, $args);
61            return $result;
62        } catch (AccessDeniedException $e) {
63            if (!isset($_SERVER['REMOTE_USER'])) {
64                http_status(401);
65                throw new RemoteException("server error. not authorized to call method $methodname", -32603);
66            } else {
67                http_status(403);
68                throw new RemoteException("server error. forbidden to call the method $methodname", -32604);
69            }
70        } catch (RemoteException $e) {
71            http_status(400);
72            throw $e;
73        }
74    }
75
76    /**
77     * @param string $data
78     * @return string
79     */
80    public function toFile($data)
81    {
82        return base64_encode($data);
83    }
84
85}
86