Code

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