Code

Added extended error messages
[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      Constructs a new jsonRPC handle which is connected to a given URL.
21      *              It can either connect using a rpc method or via auth method digest.
22      *  @param      object      The gosa configuration object (class_config)
23      *  @param      string      The url to connect to. 
24      *  @param      string      The username for authentication
25      *  @param      string      The password to use for authentication
26      *  @param      boolean     Whether to use DIGEST authentication or not.
27      *  @return     
28      */
29     public function __construct($config, $connectUrl, $username, $userPassword, $authModeDigest=FALSE) 
30     {
31         $this->config = $config;
32         $this->id = 0;
34         // Get connection data
35         $this->connectUrl     = $connectUrl; 
36         $this->username       = $username; 
37         $this->userPassword   = $userPassword; 
38         $this->authModeDigest = $authModeDigest;
40         // Put some usefull info in the logs 
41         DEBUG (DEBUG_RPC, __LINE__, __FUNCTION__, __FILE__,bold($this->connectUrl), "Initiated RPC "); 
42         DEBUG (DEBUG_RPC, __LINE__, __FUNCTION__, __FILE__,bold($this->username), "RPC user: "); 
43         DEBUG (DEBUG_RPC, __LINE__, __FUNCTION__, __FILE__,bold($this->userPassword),"RPC password: "); 
44         DEBUG (DEBUG_RPC, __LINE__, __FUNCTION__, __FILE__,bold($this->authModeDigest),"Digest Auth (0: No, 1: Yes): "); 
46         $this->__login();
47     }
50     /*! \brief          
51      *  @param      
52      *  @return     
53      */
54     private function __login()
55     {
56         // Init Curl handler
57         $this->curlHandler = curl_init($this->connectUrl);
59         // Set curl options
60         curl_setopt($this->curlHandler, CURLOPT_URL ,           $this->connectUrl);
61         curl_setopt($this->curlHandler, CURLOPT_POST ,          TRUE);
62         curl_setopt($this->curlHandler, CURLOPT_RETURNTRANSFER ,TRUE);
63         curl_setopt($this->curlHandler, CURLOPT_HTTPHEADER ,    array('Content-Type: application/json'));
64         curl_setopt($this->curlHandler, CURLOPT_SSL_VERIFYPEER, FALSE);
66         // Try to login 
67         if($this->authModeDigest){
68             curl_setopt($this->curlHandler, CURLOPT_USERPWD , "{$this->username}:{$this->userPassword}");
69             curl_setopt($this->curlHandler, CURLOPT_HTTPAUTH , CURLAUTH_ANYSAFE);
70         }else{
71             curl_setopt($this->curlHandler, CURLOPT_COOKIESESSION , TRUE);
72             curl_setopt($this->curlHandler, CURLOPT_COOKIEFILE, 'cookiefile.txt'); 
73             $this->login($this->username, $this->userPassword);
74         }
75     }
78     /*! \brief      Returns the last HTTP status code.  
79      *  @return     int         The last status code.          
80      */
81     public function getHTTPstatusCode()
82     {
83         return((isset($this->lastStats['http_code']))? $this->lastStats['http_code'] : -1 );
84     }
87     /*! \brief      Returns the last error string. 
88      *  @return     string      The last error message.
89      */
90     public function get_error()
91     {
92         if($this->lastStats['http_code'] != 200){
93             $error = $this->getHttpStatusCodeMessage($this->lastStats['http_code']);
94             if(isset($this->lastResult['error']['message'])){
95                 $error .= ": ".$this->lastResult['error']['message']; 
96             }
97             return($error);
98         }else{
99             return(curl_error($this->curlHandler));
100         }
101     }
103     
105     /*! \brief      Returns TRUE if the last action was successfull else FALSE.
106      *  @return     boolean     TRUE on success else FALSE. 
107      */
108     public function success()
109     {
110         return(curl_errno($this->curlHandler) == 0 && $this->lastStats['http_code'] == 200);
111     }
114     /*! \brief      The class destructor, it destroys open rpc handles if needed.
115      */
116     public function __destruct()
117     {
118         if($this->curlHandler){
119             curl_close($this->curlHandler);
120         }
121     }
124     /*! \brief      This is some kind of catch-all method, all unknown method names will 
125      *               will be interpreted as rpc request. 
126      *              If you call "$this->blafasel" this method will initiate an rpc request 
127      *               for method 'blafasel'.
128      *  @param      string  method   The rpc method to execute.
129      *  @param      params  array    The parameter to use.
130      *  @return     mixed            The request result.
131      */
132     public function __call($method,$params) 
133     {
134         // Check if handle is still valid!
135         if(!$this->curlHandler && $this->lastAction != 'login'){
136             $this->__login();
137         }
139         // Start request
140         DEBUG (DEBUG_RPC, __LINE__, __FUNCTION__, __FILE__,"{$method}", "Calling: "); 
141         $response = $this->request($method,$params);
142         if($this->success()){
143             DEBUG (DEBUG_RPC, __LINE__, __FUNCTION__, __FILE__,
144                     (is_array($response['result']))?$response['result']:bold($response['result']), "Result: "); 
145         }else{
146             DEBUG (DEBUG_RPC, __LINE__, __FUNCTION__, __FILE__,bold($this->get_error())."<br>".$response, "Result (FAILED): "); 
147         }
148         if(isset($response['error']) && !empty($response['error'])){
149               print_a(array($response));
150         }
151         return($response['result']);
152     }
155     /*! \brief      This method finally initiates the real RPC requests and handles 
156      *               the result from the server.
157      *  @param      string  method      The method to call 
158      *  @param      array   params      The paramter to use.
159      *  @return     mixed   The server response. 
160      */
161     private function request($method, $params)
162     {
163         // Set last action 
164         $this->lastAction = $method;
166         // Reset stats of last request.
167         $this->lastStats = array();
169         // Validate input  values
170         if (!is_scalar($method))  trigger_error('jsonRPC::__call requires a scalar value as first parameter!');
171         if (is_array($params)) {
172             $params = array_values($params);
173         } else {
174             trigger_error('jsonRPC::__call requires an array value as second parameter!');
175         }
177         // prepares the request
178         $this->id ++;
179         $request = json_encode(array('method' => $method,'params' => $params,'id' => $this->id));
181         // Set curl options
182         curl_setopt($this->curlHandler, CURLOPT_POSTFIELDS , $request);
183         $response = curl_exec($this->curlHandler);        
184         $response = json_decode($response,true);
186         // Set current result stats.
187         $this->lastStats = curl_getinfo($this->curlHandler);
188         $this->lastResult = $response;
190         return($response);
191     }
194     /*! \brief      Returns the HTTP status message for a given HTTP status code.        
195      *  @param      int     code    The status to code to return a message for. 
196      *  @return     string  The corresponding status message. 
197      */
198     public static function getHttpStatusCodeMessage($code)
199     {
200         $codes  = array(
201                 '100' =>  'Continue',
202                 '101' =>  'Switching Protocols',
203                 '102' =>  'Processing',
204                 '200' =>  'OK',
205                 '201' =>  'Created',
206                 '202' =>  'Accepted',
207                 '203' =>  'Non-Authoritative Information',
208                 '204' =>  'No Content',
209                 '205' =>  'Reset Content',
210                 '206' =>  'Partial Content',
211                 '207' =>  'Multi-Status',
212                 '300' =>  'Multiple Choice',
213                 '301' =>  'Moved Permanently',
214                 '302' =>  'Found',
215                 '303' =>  'See Other',
216                 '304' =>  'Not Modified',
217                 '305' =>  'Use Proxy',
218                 '306' =>  'reserved',
219                 '307' =>  'Temporary Redirect',
220                 '400' =>  'Bad Request',
221                 '401' =>  'Unauthorized',
222                 '402' =>  'Payment Required',
223                 '403' =>  'Forbidden',
224                 '404' =>  'Not Found',
225                 '405' =>  'Method Not Allowed',
226                 '406' =>  'Not Acceptable',
227                 '407' =>  'Proxy Authentication Required',
228                 '408' =>  'Request Time-out',
229                 '409' =>  'Conflict',
230                 '410' =>  'Gone',
231                 '411' =>  'Length Required',
232                 '412' =>  'Precondition Failed',
233                 '413' =>  'Request Entity Too Large',
234                 '414' =>  'Request-URI Too Long',
235                 '415' =>  'Unsupported Media Type',
236                 '416' =>  'Requested range not satisfiable',
237                 '417' =>  'Expectation Failed',
238                 '421' =>  'There are too many connections from your internet address',
239                 '422' =>  'Unprocessable Entity',
240                 '423' =>  'Locked',
241                 '424' =>  'Failed Dependency',
242                 '425' =>  'Unordered Collection',
243                 '426' =>  'Upgrade Required',
244                 '500' =>  'Internal Server Error',
245                 '501' =>  'Not Implemented',
246                 '502' =>  'Bad Gateway',
247                 '503' =>  'Service Unavailable',
248                 '504' =>  'Gateway Time-out',
249                 '505' =>  'HTTP Version not supported',
250                 '506' =>  'Variant Also Negotiates',
251                 '507' =>  'Insufficient Storage',
252                 '509' =>  'Bandwidth Limit Exceeded',
253                 '510' =>  'Not Extended');
254         return((isset($codes[$code]))? $codes[$code] : sprintf(_("Unknown HTTP status code '%s'!"), $code));
255     }
257 ?>