Code

Optimized jsonRPC class
[gosa.git] / gosa-core / include / class_jsonRPC.inc
1 <?php
2 class jsonRPC {
4     private $curlHandler = NULL;
5     private $debug;
6     private $url;
7     private $id;
9     public function __construct($url,$debug = false) 
10     {
12         $this->url = $url;
13         $this->debug = $debug;
14         $this->id = 0;
16         // Init Curl handler
17         $this->curlHandler = curl_init($this->url);
18         curl_setopt($this->curlHandler, CURLOPT_URL , $this->url);
19         curl_setopt($this->curlHandler, CURLOPT_COOKIESESSION , TRUE);
20         curl_setopt($this->curlHandler, CURLOPT_COOKIEFILE, 'cookiefile.txt'); 
21         curl_setopt($this->curlHandler, CURLOPT_POST , TRUE);
22         curl_setopt($this->curlHandler, CURLOPT_RETURNTRANSFER , TRUE);
23         curl_setopt($this->curlHandler, CURLOPT_HTTPHEADER , array('Content-Type: application/json'));
24     }
26     public function __destruct()
27     {
28         curl_close($this->curlHandler);
29     }
31     public function __call($method,$params) 
32     {
34         if (!is_scalar($method))  trigger_error('jsonRPC::__call requires a scalar value as first parameter!');
36         if (is_array($params)) {
37             $params = array_values($params);
38         } else {
39             trigger_error('jsonRPC::__call requires an array value as second parameter!');
40         }
42         // prepares the request
43         $this->id ++;
44         $request = json_encode(array('method' => $method,'params' => $params,'id' => $this->id));
46         // Set curl options
47         curl_setopt($this->curlHandler, CURLOPT_POSTFIELDS , $request);
48         $response = curl_exec($this->curlHandler);        
49         $response = json_decode($response,true);
51         // Check responce id
52         if ($response['id'] != $this->id){
53             trigger_error('jsonPRC returned incorrect response '.
54                     'id (request id: '.$this->id.', response id: '.$response['id'].')');
55         }
56         return($response['result']);
57     }
58 }
59 ?>