1 <?php
4 class jsonRPC {
6 private $curlHandler = NULL;
7 private $config;
8 private $id;
9 private $lastStats = array();
10 private $lastResult = array();
11 private $lastAction = "none";
14 private $connectUrl = "";
15 private $username = "";
16 private $userPassword = "";
17 private $authModeDigest = FALSE;
20 /*! \brief This function is used by the property editor and checks the
21 * given rpc connection informations.
22 */
23 public static function testConnectionProperties($message,$class,$name,$value, $type)
24 {
25 global $config;
27 // Get currently used connection usernamem and password.
28 // We use the temporary values, due to the fact, that we do not want to test
29 // the current values, we want to test the modified values.
30 $user = $config->configRegistry->getProperty('core','gosaRpcUser');
31 $username = $user->getValue($temporaryValue = TRUE);
32 $passwd = $config->configRegistry->getProperty('core','gosaRpcPassword');
33 $passwdString = $passwd->getValue($temporaryValue = TRUE);
35 $connection = new jsonRPC($config, $value, $username, $passwdString);
36 if(!$connection->success() && $message){
37 msg_dialog::display(_("Warning"),
38 sprintf(_("The rpc connection (%s) specified for '%s:%s' is invalid! Error was: %s."),
39 bold($value),bold($class),bold($name), bold($connection->get_error())),
40 WARNING_DIALOG);
42 }
44 return($connection->success());
45 }
48 /*! \brief Constructs a new jsonRPC handle which is connected to a given URL.
49 * It can either connect using a rpc method or via auth method digest.
50 * @param object The gosa configuration object (class_config)
51 * @param string The url to connect to.
52 * @param string The username for authentication
53 * @param string The password to use for authentication
54 * @param boolean Whether to use DIGEST authentication or not.
55 * @return
56 */
57 public function __construct($config, $connectUrl, $username, $userPassword, $authModeDigest=FALSE)
58 {
59 $this->config = $config;
60 $this->id = 0;
62 // Get connection data
63 $this->connectUrl = $connectUrl;
64 $this->username = $username;
65 $this->userPassword = $userPassword;
66 $this->authModeDigest = $authModeDigest;
68 // Put some usefull info in the logs
69 DEBUG (DEBUG_RPC, __LINE__, __FUNCTION__, __FILE__,bold($this->connectUrl), "Initiated RPC ");
70 DEBUG (DEBUG_RPC, __LINE__, __FUNCTION__, __FILE__,bold($this->username), "RPC user: ");
71 DEBUG (DEBUG_RPC, __LINE__, __FUNCTION__, __FILE__,bold($this->userPassword),"RPC password: ");
72 DEBUG (DEBUG_RPC, __LINE__, __FUNCTION__, __FILE__,bold($this->authModeDigest),"Digest Auth (0: No, 1: Yes): ");
74 $this->__login();
75 }
78 /*! \brief
79 * @param
80 * @return
81 */
82 private function __login()
83 {
84 // Init Curl handler
85 $this->curlHandler = curl_init($this->connectUrl);
87 // Set curl options
88 curl_setopt($this->curlHandler, CURLOPT_URL , $this->connectUrl);
89 curl_setopt($this->curlHandler, CURLOPT_POST , TRUE);
90 curl_setopt($this->curlHandler, CURLOPT_RETURNTRANSFER ,TRUE);
91 curl_setopt($this->curlHandler, CURLOPT_HTTPHEADER , array('Content-Type: application/json'));
92 curl_setopt($this->curlHandler, CURLOPT_SSL_VERIFYPEER, FALSE);
94 // Try to login
95 if($this->authModeDigest){
96 if(!empty($this->username))
97 curl_setopt($this->curlHandler, CURLOPT_USERPWD , "{$this->username}:{$this->userPassword}");
98 curl_setopt($this->curlHandler, CURLOPT_HTTPAUTH , CURLAUTH_ANYSAFE);
99 }else{
100 curl_setopt($this->curlHandler, CURLOPT_COOKIESESSION , TRUE);
101 curl_setopt($this->curlHandler, CURLOPT_COOKIEFILE, 'cookiefile.txt');
102 if(!empty($this->username))
103 $this->login($this->username, $this->userPassword);
104 }
105 }
108 /*! \brief Returns the last HTTP status code.
109 * @return int The last status code.
110 */
111 public function getHTTPstatusCode()
112 {
113 return((isset($this->lastStats['http_code']))? $this->lastStats['http_code'] : -1 );
114 }
117 /*! \brief Returns the last error string.
118 * @return string The last error message.
119 */
120 public function get_error()
121 {
122 if($this->lastStats['http_code'] != 200){
123 $error = $this->getHttpStatusCodeMessage($this->lastStats['http_code']);
124 if(isset($this->lastResult['error']['message'])){
125 $error .= ": ".$this->lastResult['error']['message'];
126 }
127 return($error);
128 }else{
129 return(curl_error($this->curlHandler));
130 }
131 }
135 /*! \brief Returns TRUE if the last action was successfull else FALSE.
136 * @return boolean TRUE on success else FALSE.
137 */
138 public function success()
139 {
140 return(curl_errno($this->curlHandler) == 0 && $this->lastStats['http_code'] == 200);
141 }
144 /*! \brief The class destructor, it destroys open rpc handles if needed.
145 */
146 public function __destruct()
147 {
148 if($this->curlHandler){
149 curl_close($this->curlHandler);
150 }
151 }
154 /*! \brief This is some kind of catch-all method, all unknown method names will
155 * will be interpreted as rpc request.
156 * If you call "$this->blafasel" this method will initiate an rpc request
157 * for method 'blafasel'.
158 * @param string method The rpc method to execute.
159 * @param params array The parameter to use.
160 * @return mixed The request result.
161 */
162 public function __call($method,$params)
163 {
164 // Check if handle is still valid!
165 if(!$this->curlHandler && $this->lastAction != 'login'){
166 $this->__login();
167 }
169 // Start request
170 DEBUG (DEBUG_RPC, __LINE__, __FUNCTION__, __FILE__,"{$method}", "Calling: ");
171 $response = $this->request($method,$params);
172 if($this->success()){
173 DEBUG (DEBUG_RPC, __LINE__, __FUNCTION__, __FILE__,
174 (is_array($response['result']))?$response['result']:bold($response['result']), "Result: ");
175 }else{
176 DEBUG (DEBUG_RPC, __LINE__, __FUNCTION__, __FILE__,bold($this->get_error())."<br>".$response, "Result (FAILED): ");
177 }
179 global $config;
180 $debugLevel = $config->get_cfg_value('core', 'debugLevel');
181 if($debugLevel & DEBUG_RPC){
182 print_a(array('CALLED:' => array($method => $params)));
183 print_a(array('RESPONSE' => $response));
184 }
185 $return = $response['result'];
187 // Create remote-object handling using the jsonROP class
188 if(class_available('jsonROP')){
189 $return = jsonROP::inspectJsonResult($return);
190 }
192 return($return);
193 }
196 /*! \brief This method finally initiates the real RPC requests and handles
197 * the result from the server.
198 * @param string method The method to call
199 * @param array params The paramter to use.
200 * @return mixed The server response.
201 */
202 private function request($method, $params)
203 {
204 // Set last action
205 $this->lastAction = $method;
207 // Reset stats of last request.
208 $this->lastStats = array();
210 // Validate input values
211 if (!is_scalar($method)) trigger_error('jsonRPC::__call requires a scalar value as first parameter!');
212 if (is_array($params)) {
213 $params = array_values($params);
214 } else {
215 trigger_error('jsonRPC::__call requires an array value as second parameter!');
216 }
218 // prepares the request
219 $this->id ++;
220 $request = json_encode(array('method' => $method,'params' => $params,'id' => $this->id));
222 // Set curl options
223 curl_setopt($this->curlHandler, CURLOPT_POSTFIELDS , $request);
224 $response = curl_exec($this->curlHandler);
225 $response = json_decode($response,true);
227 // Set current result stats.
228 $this->lastStats = curl_getinfo($this->curlHandler);
229 $this->lastResult = $response;
231 return($response);
232 }
235 /*! \brief Returns the HTTP status message for a given HTTP status code.
236 * @param int code The status to code to return a message for.
237 * @return string The corresponding status message.
238 */
239 public static function getHttpStatusCodeMessage($code)
240 {
241 $codes = array(
242 '100' => 'Continue',
243 '101' => 'Switching Protocols',
244 '102' => 'Processing',
245 '200' => 'OK',
246 '201' => 'Created',
247 '202' => 'Accepted',
248 '203' => 'Non-Authoritative Information',
249 '204' => 'No Content',
250 '205' => 'Reset Content',
251 '206' => 'Partial Content',
252 '207' => 'Multi-Status',
253 '300' => 'Multiple Choice',
254 '301' => 'Moved Permanently',
255 '302' => 'Found',
256 '303' => 'See Other',
257 '304' => 'Not Modified',
258 '305' => 'Use Proxy',
259 '306' => 'reserved',
260 '307' => 'Temporary Redirect',
261 '400' => 'Bad Request',
262 '401' => 'Unauthorized',
263 '402' => 'Payment Required',
264 '403' => 'Forbidden',
265 '404' => 'Not Found',
266 '405' => 'Method Not Allowed',
267 '406' => 'Not Acceptable',
268 '407' => 'Proxy Authentication Required',
269 '408' => 'Request Time-out',
270 '409' => 'Conflict',
271 '410' => 'Gone',
272 '411' => 'Length Required',
273 '412' => 'Precondition Failed',
274 '413' => 'Request Entity Too Large',
275 '414' => 'Request-URI Too Long',
276 '415' => 'Unsupported Media Type',
277 '416' => 'Requested range not satisfiable',
278 '417' => 'Expectation Failed',
279 '421' => 'There are too many connections from your internet address',
280 '422' => 'Unprocessable Entity',
281 '423' => 'Locked',
282 '424' => 'Failed Dependency',
283 '425' => 'Unordered Collection',
284 '426' => 'Upgrade Required',
285 '500' => 'Internal Server Error',
286 '501' => 'Not Implemented',
287 '502' => 'Bad Gateway',
288 '503' => 'Service Unavailable',
289 '504' => 'Gateway Time-out',
290 '505' => 'HTTP Version not supported',
291 '506' => 'Variant Also Negotiates',
292 '507' => 'Insufficient Storage',
293 '509' => 'Bandwidth Limit Exceeded',
294 '510' => 'Not Extended');
295 return((isset($codes[$code]))? $codes[$code] : sprintf(_("Unknown HTTP status code '%s'!"), $code));
296 }
297 }
298 ?>