🤖 Rector and PHPCS fixes
[dokuwiki.git] / inc / Remote / JsonRpcServer.php
blob0ffcb53d22fc34068b40d60fd34f75e06be57507
1 <?php
3 namespace dokuwiki\Remote;
5 /**
6 * Provide the Remote XMLRPC API as a JSON based API
7 */
8 class JsonRpcServer
10 protected $remote;
12 /**
13 * JsonRpcServer constructor.
15 public function __construct()
17 $this->remote = new Api();
18 $this->remote->setFileTransformation([$this, 'toFile']);
21 /**
22 * Serve the request
24 * @return mixed
25 * @throws RemoteException
27 public function serve()
29 global $conf;
30 global $INPUT;
32 if (!$conf['remote']) {
33 http_status(404);
34 throw new RemoteException("JSON-RPC server not enabled.", -32605);
36 if (!empty($conf['remotecors'])) {
37 header('Access-Control-Allow-Origin: ' . $conf['remotecors']);
39 if ($INPUT->server->str('REQUEST_METHOD') !== 'POST') {
40 http_status(405);
41 header('Allow: POST');
42 throw new RemoteException("JSON-RPC server only accepts POST requests.", -32606);
44 if ($INPUT->server->str('CONTENT_TYPE') !== 'application/json') {
45 http_status(415);
46 throw new RemoteException("JSON-RPC server only accepts application/json requests.", -32606);
49 $call = $INPUT->server->str('PATH_INFO');
50 $call = trim($call, '/');
51 try {
52 $args = json_decode(file_get_contents('php://input'), true, 512, JSON_THROW_ON_ERROR);
53 } catch (\Exception $e) {
54 $args = [];
56 if (!is_array($args)) $args = [];
58 return $this->call($call, $args);
61 /**
62 * Call an API method
64 * @param string $methodname
65 * @param array $args
66 * @return mixed
67 * @throws RemoteException
69 public function call($methodname, $args)
71 try {
72 $result = $this->remote->call($methodname, $args);
73 return $result;
74 } catch (AccessDeniedException $e) {
75 if (!isset($_SERVER['REMOTE_USER'])) {
76 http_status(401);
77 throw new RemoteException("server error. not authorized to call method $methodname", -32603);
78 } else {
79 http_status(403);
80 throw new RemoteException("server error. forbidden to call the method $methodname", -32604);
82 } catch (RemoteException $e) {
83 http_status(400);
84 throw $e;
88 /**
89 * @param string $data
90 * @return string
92 public function toFile($data)
94 return base64_encode($data);