1<?php
2/*
3** Zabbix
4** Copyright (C) 2001-2021 Zabbix SIA
5**
6** This program is free software; you can redistribute it and/or modify
7** it under the terms of the GNU General Public License as published by
8** the Free Software Foundation; either version 2 of the License, or
9** (at your option) any later version.
10**
11** This program is distributed in the hope that it will be useful,
12** but WITHOUT ANY WARRANTY; without even the implied warranty of
13** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14** GNU General Public License for more details.
15**
16** You should have received a copy of the GNU General Public License
17** along with this program; if not, write to the Free Software
18** Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
19**/
20
21
22header('Access-Control-Allow-Origin: *');
23header('Access-Control-Allow-Headers: Content-Type');
24header('Access-Control-Allow-Methods: POST');
25header('Access-Control-Max-Age: 1000');
26
27if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
28	return;
29}
30
31require_once dirname(__FILE__).'/include/func.inc.php';
32require_once dirname(__FILE__).'/include/classes/core/CHttpRequest.php';
33
34$allowed_content = [
35	'application/json-rpc' => 'json-rpc',
36	'application/json' => 'json-rpc',
37	'application/jsonrequest' => 'json-rpc'
38];
39$http_request = new CHttpRequest();
40$content_type = $http_request->header('Content-Type');
41$content_type = explode(';', $content_type);
42$content_type = $content_type[0];
43
44if (!isset($allowed_content[$content_type])) {
45	header('HTTP/1.0 412 Precondition Failed');
46	return;
47}
48
49require_once dirname(__FILE__).'/include/classes/core/Z.php';
50
51header('Content-Type: application/json');
52$data = $http_request->body();
53
54try {
55	Z::getInstance()->run(ZBase::EXEC_MODE_API);
56
57	$apiClient = API::getWrapper()->getClient();
58
59	// unset wrappers so that calls between methods would be made directly to the services
60	API::setWrapper();
61
62	$jsonRpc = new CJsonRpc($apiClient, $data);
63	echo $jsonRpc->execute();
64}
65catch (Exception $e) {
66	// decode input json request to get request's id
67	$jsonData = CJs::decodeJson($data);
68
69	$response = [
70		'jsonrpc' => '2.0',
71		'error' => [
72			'code' => 1,
73			'message' => $e->getMessage(),
74			'data' => ''
75		],
76		'id' => (isset($jsonData['id']) ? $jsonData['id'] : null)
77	];
78
79	echo CJs::encodeJson($response);
80}
81