Code

Updated json Rop and RPC again
[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']['message'])){
125                 $error .= ": ".$this->lastResult['error']['message']; 
126             }
127             return($error);
128         }else{
129             return(curl_error($this->curlHandler));
130         }
131     }
133     
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'];
186         
187         // Inspect the result and replace predefined statements with their 
188         //  coresponding classes.
189         $return = $this->inspectJsonResult($return);
191         return($return);
192     }
196     public function inspectJsonResult($result)
197     {
198         // Check for remove objects we've to create
199         if(isset($result['__jsonclass__']) && class_available('remoteObject')){
201             // Get all relevant class informations
202             $classDef = $result['__jsonclass__'][1];
203             $type = $classDef[0];
204             $ref_id = $classDef[1];
205             $object_id = $classDef[2];
206             $methods = $classDef[3];
207             $properties = $classDef[4];
209             // Prepare values
210             $values = array();
211             foreach($properties as $prop){
212                 $values[$prop] = NULL;
213                 if(isset($res[$prop])) $values[$prop] = $res[$prop];
214             }
216             // Build up remote object
217             $object = new remoteObject($rpc, $type, $properties, $values, $methods, $object_id, $ref_id);
218             return($object);
219         }
220         return($result);
221     }
231     /*! \brief      This method finally initiates the real RPC requests and handles 
232      *               the result from the server.
233      *  @param      string  method      The method to call 
234      *  @param      array   params      The paramter to use.
235      *  @return     mixed   The server response. 
236      */
237     private function request($method, $params)
238     {
239         // Set last action 
240         $this->lastAction = $method;
242         // Reset stats of last request.
243         $this->lastStats = array();
245         // Validate input  values
246         if (!is_scalar($method))  trigger_error('jsonRPC::__call requires a scalar value as first parameter!');
247         if (is_array($params)) {
248             $params = array_values($params);
249         } else {
250             trigger_error('jsonRPC::__call requires an array value as second parameter!');
251         }
253         // prepares the request
254         $this->id ++;
255         $request = json_encode(array('method' => $method,'params' => $params,'id' => $this->id));
257         // Set curl options
258         curl_setopt($this->curlHandler, CURLOPT_POSTFIELDS , $request);
259         $response = curl_exec($this->curlHandler);        
260         $response = json_decode($response,true);
262         // Set current result stats.
263         $this->lastStats = curl_getinfo($this->curlHandler);
264         $this->lastResult = $response;
266         return($response);
267     }
270     /*! \brief      Returns the HTTP status message for a given HTTP status code.        
271      *  @param      int     code    The status to code to return a message for. 
272      *  @return     string  The corresponding status message. 
273      */
274     public static function getHttpStatusCodeMessage($code)
275     {
276         $codes  = array(
277                 '100' =>  'Continue',
278                 '101' =>  'Switching Protocols',
279                 '102' =>  'Processing',
280                 '200' =>  'OK',
281                 '201' =>  'Created',
282                 '202' =>  'Accepted',
283                 '203' =>  'Non-Authoritative Information',
284                 '204' =>  'No Content',
285                 '205' =>  'Reset Content',
286                 '206' =>  'Partial Content',
287                 '207' =>  'Multi-Status',
288                 '300' =>  'Multiple Choice',
289                 '301' =>  'Moved Permanently',
290                 '302' =>  'Found',
291                 '303' =>  'See Other',
292                 '304' =>  'Not Modified',
293                 '305' =>  'Use Proxy',
294                 '306' =>  'reserved',
295                 '307' =>  'Temporary Redirect',
296                 '400' =>  'Bad Request',
297                 '401' =>  'Unauthorized',
298                 '402' =>  'Payment Required',
299                 '403' =>  'Forbidden',
300                 '404' =>  'Not Found',
301                 '405' =>  'Method Not Allowed',
302                 '406' =>  'Not Acceptable',
303                 '407' =>  'Proxy Authentication Required',
304                 '408' =>  'Request Time-out',
305                 '409' =>  'Conflict',
306                 '410' =>  'Gone',
307                 '411' =>  'Length Required',
308                 '412' =>  'Precondition Failed',
309                 '413' =>  'Request Entity Too Large',
310                 '414' =>  'Request-URI Too Long',
311                 '415' =>  'Unsupported Media Type',
312                 '416' =>  'Requested range not satisfiable',
313                 '417' =>  'Expectation Failed',
314                 '421' =>  'There are too many connections from your internet address',
315                 '422' =>  'Unprocessable Entity',
316                 '423' =>  'Locked',
317                 '424' =>  'Failed Dependency',
318                 '425' =>  'Unordered Collection',
319                 '426' =>  'Upgrade Required',
320                 '500' =>  'Internal Server Error',
321                 '501' =>  'Not Implemented',
322                 '502' =>  'Bad Gateway',
323                 '503' =>  'Service Unavailable',
324                 '504' =>  'Gateway Time-out',
325                 '505' =>  'HTTP Version not supported',
326                 '506' =>  'Variant Also Negotiates',
327                 '507' =>  'Insufficient Storage',
328                 '509' =>  'Bandwidth Limit Exceeded',
329                 '510' =>  'Not Extended');
330         return((isset($codes[$code]))? $codes[$code] : sprintf(_("Unknown HTTP status code '%s'!"), $code));
331     }
333 ?>