Code

Added rpc connection settings check to the peroperty editor
[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             curl_setopt($this->curlHandler, CURLOPT_USERPWD , "{$this->username}:{$this->userPassword}");
97             curl_setopt($this->curlHandler, CURLOPT_HTTPAUTH , CURLAUTH_ANYSAFE);
98         }else{
99             curl_setopt($this->curlHandler, CURLOPT_COOKIESESSION , TRUE);
100             curl_setopt($this->curlHandler, CURLOPT_COOKIEFILE, 'cookiefile.txt'); 
101             $this->login($this->username, $this->userPassword);
102         }
103     }
106     /*! \brief      Returns the last HTTP status code.  
107      *  @return     int         The last status code.          
108      */
109     public function getHTTPstatusCode()
110     {
111         return((isset($this->lastStats['http_code']))? $this->lastStats['http_code'] : -1 );
112     }
115     /*! \brief      Returns the last error string. 
116      *  @return     string      The last error message.
117      */
118     public function get_error()
119     {
120         if($this->lastStats['http_code'] != 200){
121             $error = $this->getHttpStatusCodeMessage($this->lastStats['http_code']);
122             if(isset($this->lastResult['error']['message'])){
123                 $error .= ": ".$this->lastResult['error']['message']; 
124             }
125             return($error);
126         }else{
127             return(curl_error($this->curlHandler));
128         }
129     }
131     
133     /*! \brief      Returns TRUE if the last action was successfull else FALSE.
134      *  @return     boolean     TRUE on success else FALSE. 
135      */
136     public function success()
137     {
138         return(curl_errno($this->curlHandler) == 0 && $this->lastStats['http_code'] == 200);
139     }
142     /*! \brief      The class destructor, it destroys open rpc handles if needed.
143      */
144     public function __destruct()
145     {
146         if($this->curlHandler){
147             curl_close($this->curlHandler);
148         }
149     }
152     /*! \brief      This is some kind of catch-all method, all unknown method names will 
153      *               will be interpreted as rpc request. 
154      *              If you call "$this->blafasel" this method will initiate an rpc request 
155      *               for method 'blafasel'.
156      *  @param      string  method   The rpc method to execute.
157      *  @param      params  array    The parameter to use.
158      *  @return     mixed            The request result.
159      */
160     public function __call($method,$params) 
161     {
162         // Check if handle is still valid!
163         if(!$this->curlHandler && $this->lastAction != 'login'){
164             $this->__login();
165         }
167         // Start request
168         DEBUG (DEBUG_RPC, __LINE__, __FUNCTION__, __FILE__,"{$method}", "Calling: "); 
169         $response = $this->request($method,$params);
170         if($this->success()){
171             DEBUG (DEBUG_RPC, __LINE__, __FUNCTION__, __FILE__,
172                     (is_array($response['result']))?$response['result']:bold($response['result']), "Result: "); 
173         }else{
174             DEBUG (DEBUG_RPC, __LINE__, __FUNCTION__, __FILE__,bold($this->get_error())."<br>".$response, "Result (FAILED): "); 
175         }
177         global $config;
178         $debugLevel = $config->get_cfg_value('core', 'debugLevel'); 
179         if($debugLevel & DEBUG_RPC){
180             print_a(array('CALLED:' => array($method => $params)));
181             print_a(array('RESPONSE' => $response));
182         }
183         return($response['result']);
184     }
187     /*! \brief      This method finally initiates the real RPC requests and handles 
188      *               the result from the server.
189      *  @param      string  method      The method to call 
190      *  @param      array   params      The paramter to use.
191      *  @return     mixed   The server response. 
192      */
193     private function request($method, $params)
194     {
195         // Set last action 
196         $this->lastAction = $method;
198         // Reset stats of last request.
199         $this->lastStats = array();
201         // Validate input  values
202         if (!is_scalar($method))  trigger_error('jsonRPC::__call requires a scalar value as first parameter!');
203         if (is_array($params)) {
204             $params = array_values($params);
205         } else {
206             trigger_error('jsonRPC::__call requires an array value as second parameter!');
207         }
209         // prepares the request
210         $this->id ++;
211         $request = json_encode(array('method' => $method,'params' => $params,'id' => $this->id));
213         // Set curl options
214         curl_setopt($this->curlHandler, CURLOPT_POSTFIELDS , $request);
215         $response = curl_exec($this->curlHandler);        
216         $response = json_decode($response,true);
218         // Set current result stats.
219         $this->lastStats = curl_getinfo($this->curlHandler);
220         $this->lastResult = $response;
222         return($response);
223     }
226     /*! \brief      Returns the HTTP status message for a given HTTP status code.        
227      *  @param      int     code    The status to code to return a message for. 
228      *  @return     string  The corresponding status message. 
229      */
230     public static function getHttpStatusCodeMessage($code)
231     {
232         $codes  = array(
233                 '100' =>  'Continue',
234                 '101' =>  'Switching Protocols',
235                 '102' =>  'Processing',
236                 '200' =>  'OK',
237                 '201' =>  'Created',
238                 '202' =>  'Accepted',
239                 '203' =>  'Non-Authoritative Information',
240                 '204' =>  'No Content',
241                 '205' =>  'Reset Content',
242                 '206' =>  'Partial Content',
243                 '207' =>  'Multi-Status',
244                 '300' =>  'Multiple Choice',
245                 '301' =>  'Moved Permanently',
246                 '302' =>  'Found',
247                 '303' =>  'See Other',
248                 '304' =>  'Not Modified',
249                 '305' =>  'Use Proxy',
250                 '306' =>  'reserved',
251                 '307' =>  'Temporary Redirect',
252                 '400' =>  'Bad Request',
253                 '401' =>  'Unauthorized',
254                 '402' =>  'Payment Required',
255                 '403' =>  'Forbidden',
256                 '404' =>  'Not Found',
257                 '405' =>  'Method Not Allowed',
258                 '406' =>  'Not Acceptable',
259                 '407' =>  'Proxy Authentication Required',
260                 '408' =>  'Request Time-out',
261                 '409' =>  'Conflict',
262                 '410' =>  'Gone',
263                 '411' =>  'Length Required',
264                 '412' =>  'Precondition Failed',
265                 '413' =>  'Request Entity Too Large',
266                 '414' =>  'Request-URI Too Long',
267                 '415' =>  'Unsupported Media Type',
268                 '416' =>  'Requested range not satisfiable',
269                 '417' =>  'Expectation Failed',
270                 '421' =>  'There are too many connections from your internet address',
271                 '422' =>  'Unprocessable Entity',
272                 '423' =>  'Locked',
273                 '424' =>  'Failed Dependency',
274                 '425' =>  'Unordered Collection',
275                 '426' =>  'Upgrade Required',
276                 '500' =>  'Internal Server Error',
277                 '501' =>  'Not Implemented',
278                 '502' =>  'Bad Gateway',
279                 '503' =>  'Service Unavailable',
280                 '504' =>  'Gateway Time-out',
281                 '505' =>  'HTTP Version not supported',
282                 '506' =>  'Variant Also Negotiates',
283                 '507' =>  'Insufficient Storage',
284                 '509' =>  'Bandwidth Limit Exceeded',
285                 '510' =>  'Not Extended');
286         return((isset($codes[$code]))? $codes[$code] : sprintf(_("Unknown HTTP status code '%s'!"), $code));
287     }
289 ?>