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: %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 }
100 curl_setopt($this->curlHandler, CURLOPT_HTTPAUTH , CURLAUTH_ANYSAFE);
101 }else{
102 curl_setopt($this->curlHandler, CURLOPT_COOKIESESSION , TRUE);
103 curl_setopt($this->curlHandler, CURLOPT_COOKIEFILE, 'cookiefile.txt');
104 if(!empty($this->username))
105 $this->login($this->username, $this->userPassword);
106 }
107 }
110 /*! \brief Returns the last HTTP status code.
111 * @return int The last status code.
112 */
113 public function getHTTPstatusCode()
114 {
115 return((isset($this->lastStats['http_code']))? $this->lastStats['http_code'] : -1 );
116 }
119 /*! \brief Returns the last error string.
120 * @return string The last error message.
121 */
122 public function get_error()
123 {
124 if($this->lastStats['http_code'] != 200){
125 $error = $this->getHttpStatusCodeMessage($this->lastStats['http_code']);
126 if(isset($this->lastResult['error']['error']) && is_array($this->lastResult['error']['error'])){
127 $err = $this->lastResult['error']['error'];
128 $message = call_user_func_array(sprintf,$err);
129 $error .= $message;
130 }elseif(isset($this->lastResult['error']['message'])){
131 $error .= ": ".$this->lastResult['error']['message'];
132 }
133 return($error);
134 }else{
135 return(curl_error($this->curlHandler));
136 }
137 }
141 /*! \brief Returns TRUE if the last action was successfull else FALSE.
142 * @return boolean TRUE on success else FALSE.
143 */
144 public function success()
145 {
146 return(curl_errno($this->curlHandler) == 0 &&
147 isset($this->lastStats['http_code']) &&
148 $this->lastStats['http_code'] == 200);
149 }
152 /*! \brief The class destructor, it destroys open rpc handles if needed.
153 */
154 public function __destruct()
155 {
156 if($this->curlHandler){
157 curl_close($this->curlHandler);
158 }
159 }
162 /*! \brief This is some kind of catch-all method, all unknown method names will
163 * will be interpreted as rpc request.
164 * If you call "$this->blafasel" this method will initiate an rpc request
165 * for method 'blafasel'.
166 * @param string method The rpc method to execute.
167 * @param params array The parameter to use.
168 * @return mixed The request result.
169 */
170 public function __call($method,$params)
171 {
172 // Check if handle is still valid!
173 if(!$this->curlHandler && $this->lastAction != 'login'){
174 $this->__login();
175 }
177 // Start request
178 DEBUG (DEBUG_RPC, __LINE__, __FUNCTION__, __FILE__,"{$method}", "Calling: ");
179 $response = $this->request($method,$params);
180 if($this->success()){
181 DEBUG (DEBUG_RPC, __LINE__, __FUNCTION__, __FILE__,
182 (is_array($response['result']))?$response['result']:bold($response['result']), "Result: ");
183 }else{
184 DEBUG (DEBUG_RPC, __LINE__, __FUNCTION__, __FILE__,bold($this->get_error())."<br>".$response, "Result (FAILED): ");
185 }
187 global $config;
188 $debugLevel = $config->get_cfg_value('core', 'debugLevel');
189 if($debugLevel & DEBUG_RPC){
190 print_a(array('CALLED:' => array($method => $params)));
191 print_a(array('RESPONSE' => $response));
192 }
193 $return = $response['result'];
195 // Inspect the result and replace predefined statements with their
196 // coresponding classes.
197 $return = $this->inspectJsonResult($return);
199 return($return);
200 }
204 public function inspectJsonResult($result)
205 {
206 // Check for remove objects we've to create
207 if(is_array($result) && isset($result['__jsonclass__']) && class_available('remoteObject')){
209 // Get all relevant class informations
210 $classDef = $result['__jsonclass__'][1];
211 $type = $classDef[0];
212 $ref_id = $classDef[1];
213 $object_id = $classDef[2];
214 $methods = $classDef[3];
215 $properties = $classDef[4];
217 // Prepare values
218 $values = array();
219 foreach($properties as $prop){
220 $values[$prop] = NULL;
221 if(isset($res[$prop])) $values[$prop] = $res[$prop];
222 }
224 // Build up remote object
225 $object = new remoteObject($rpc, $type, $properties, $values, $methods, $object_id, $ref_id);
226 return($object);
227 }
228 return($result);
229 }
232 /*! \brief This method finally initiates the real RPC requests and handles
233 * the result from the server.
234 * @param string method The method to call
235 * @param array params The paramter to use.
236 * @return mixed The server response.
237 */
238 private function request($method, $params)
239 {
240 // Set last action
241 $this->lastAction = $method;
243 // Reset stats of last request.
244 $this->lastStats = array();
246 // Validate input values
247 if (!is_scalar($method)) trigger_error('jsonRPC::__call requires a scalar value as first parameter!');
248 if (is_array($params)) {
249 $params = array_values($params);
250 } else {
251 trigger_error('jsonRPC::__call requires an array value as second parameter!');
252 }
254 // prepares the request
255 $this->id ++;
256 $request = json_encode(array('method' => $method,'params' => $params,'id' => $this->id));
258 // Set curl options
259 curl_setopt($this->curlHandler, CURLOPT_POSTFIELDS , $request);
260 $response = curl_exec($this->curlHandler);
261 $response = json_decode($response,true);
263 // Set current result stats.
264 $this->lastStats = curl_getinfo($this->curlHandler);
265 $this->lastResult = $response;
267 return($response);
268 }
271 /*! \brief Returns the HTTP status message for a given HTTP status code.
272 * @param int code The status to code to return a message for.
273 * @return string The corresponding status message.
274 */
275 public static function getHttpStatusCodeMessage($code)
276 {
277 $codes = array(
278 '100' => 'Continue',
279 '101' => 'Switching Protocols',
280 '102' => 'Processing',
281 '200' => 'OK',
282 '201' => 'Created',
283 '202' => 'Accepted',
284 '203' => 'Non-Authoritative Information',
285 '204' => 'No Content',
286 '205' => 'Reset Content',
287 '206' => 'Partial Content',
288 '207' => 'Multi-Status',
289 '300' => 'Multiple Choice',
290 '301' => 'Moved Permanently',
291 '302' => 'Found',
292 '303' => 'See Other',
293 '304' => 'Not Modified',
294 '305' => 'Use Proxy',
295 '306' => 'reserved',
296 '307' => 'Temporary Redirect',
297 '400' => 'Bad Request',
298 '401' => 'Unauthorized',
299 '402' => 'Payment Required',
300 '403' => 'Forbidden',
301 '404' => 'Not Found',
302 '405' => 'Method Not Allowed',
303 '406' => 'Not Acceptable',
304 '407' => 'Proxy Authentication Required',
305 '408' => 'Request Time-out',
306 '409' => 'Conflict',
307 '410' => 'Gone',
308 '411' => 'Length Required',
309 '412' => 'Precondition Failed',
310 '413' => 'Request Entity Too Large',
311 '414' => 'Request-URI Too Long',
312 '415' => 'Unsupported Media Type',
313 '416' => 'Requested range not satisfiable',
314 '417' => 'Expectation Failed',
315 '421' => 'There are too many connections from your internet address',
316 '422' => 'Unprocessable Entity',
317 '423' => 'Locked',
318 '424' => 'Failed Dependency',
319 '425' => 'Unordered Collection',
320 '426' => 'Upgrade Required',
321 '500' => 'Internal Server Error',
322 '501' => 'Not Implemented',
323 '502' => 'Bad Gateway',
324 '503' => 'Service Unavailable',
325 '504' => 'Gateway Time-out',
326 '505' => 'HTTP Version not supported',
327 '506' => 'Variant Also Negotiates',
328 '507' => 'Insufficient Storage',
329 '509' => 'Bandwidth Limit Exceeded',
330 '510' => 'Not Extended');
331 return((isset($codes[$code]))? $codes[$code] : sprintf(_("Unknown HTTP status code %s!"), bold($code)));
332 }
333 }
334 ?>