Code

Ensure we either call the plugins constructor or manually set the initTime variable...
[gosa.git] / gosa-core / include / class_jsonRPC.inc
index bcfe9467e929fd153d3a5e95ce5226dacb34f74f..d9084f61c0913dba6c4bbcefb8668f69ddc754dd 100644 (file)
 <?php
-/*
-                                       COPYRIGHT
+class jsonRPC {
 
-Copyright 2007 Sergio Vaccaro <sergio@inservibile.org>
-
-This file is part of JSON-RPC PHP.
-
-JSON-RPC PHP is free software; you can redistribute it and/or modify
-it under the terms of the GNU General Public License as published by
-the Free Software Foundation; either version 2 of the License, or
-(at your option) any later version.
+    private $curlHandler = NULL;
+    private $config;
+    private $id;
+    private $lastStats = array();
+    private $lastAction = "none";
 
-JSON-RPC PHP is distributed in the hope that it will be useful,
-but WITHOUT ANY WARRANTY; without even the implied warranty of
-MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-GNU General Public License for more details.
+    public function __construct($config) 
+    {
+        $this->config = $config;
+        $this->id = 0;
+        $this->__login();
+    }
 
-You should have received a copy of the GNU General Public License
-along with JSON-RPC PHP; if not, write to the Free Software
-Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
-*/
+    private function __login()
+    {
+        // Get connection data
+        $url    =  $this->config->get_cfg_value('core','gosaRpcServer');
+        $user   =  $this->config->get_cfg_value('core','gosaRpcUser');
+        $passwd =  $this->config->get_cfg_value('core','gosaRpcPassword');
 
-/**
- * The object of this class are generic jsonRPC 1.0 clients
- * http://json-rpc.org/wiki/specification
- *
- * @author sergio <jsonrpcphp@inservibile.org>
- */
-class jsonRPCClient {
+        DEBUG (DEBUG_RPC, __LINE__, __FUNCTION__, __FILE__,bold($url), "Initiated RPC "); 
+        DEBUG (DEBUG_RPC, __LINE__, __FUNCTION__, __FILE__,bold($user), "RPC user: "); 
+        DEBUG (DEBUG_RPC, __LINE__, __FUNCTION__, __FILE__,bold($passwd),"RPC password: "); 
 
-    private $curlHandler = NULL;
-       
-       /**
-        * Debug state
-        *
-        * @var boolean
-        */
-       private $debug;
-       
-       /**
-        * The server URL
-        *
-        * @var string
-        */
-       private $url;
-       /**
-        * The request id
-        *
-        * @var integer
-        */
-       private $id;
-       /**
-        * If true, notifications are performed instead of requests
-        *
-        * @var boolean
-        */
-       private $notification = false;
-       
-       /**
-        * Takes the connection parameters
-        *
-        * @param string $url
-        * @param boolean $debug
-        */
-       public function __construct($url,$debug = false) {
-               // server URL
-               $this->url = $url;
-               // proxy
-               empty($proxy) ? $this->proxy = '' : $this->proxy = $proxy;
-               // debug state
-               empty($debug) ? $this->debug = false : $this->debug = true;
-               // message id
-               $this->id = 1;
-        
         // Init Curl handler
-        $this->curlHandler = curl_init($this->url);
-        curl_setopt($this->curlHandler, CURLOPT_URL , $this->url);
+        $this->curlHandler = curl_init($url);
+
+        // Set curl options
+        curl_setopt($this->curlHandler, CURLOPT_URL , $url);
         curl_setopt($this->curlHandler, CURLOPT_COOKIESESSION , TRUE);
         curl_setopt($this->curlHandler, CURLOPT_COOKIEFILE, 'cookiefile.txt'); 
-       }
-       
-       /**
-        * Sets the notification state of the object. In this state, notifications are performed, instead of requests.
-        *
-        * @param boolean $notification
-        */
-       public function setRPCNotification($notification) {
-               empty($notification) ?
-                                                       $this->notification = false
-                                                       :
-                                                       $this->notification = true;
-       }
-       
-       /**
-        * Performs a jsonRCP request and gets the results as an array
-        *
-        * @param string $method
-        * @param array $params
-        * @return array
-        */
-       public function __call($method,$params) {
-               
-               // check
-               if (!is_scalar($method)) {
-                       throw new Exception('Method name has no scalar value');
-               }
-               
-               // check
-               if (is_array($params)) {
-                       // no keys
-                       $params = array_values($params);
-               } else {
-                       throw new Exception('Params must be given as array');
-               }
-               
-               // sets notification or request task
-               if ($this->notification) {
-                       $currentId = NULL;
-               } else {
-                       $currentId = $this->id;
-               }
-               
-               // prepares the request
-               $request = array(
-                                               'method' => $method,
-                                               'params' => $params,
-                                               'id' => $currentId
-                                               );
-               $request = json_encode($request);
-               $this->debug && $this->debug.='***** Request *****'."\n".$request."\n".'***** End Of request *****'."\n\n";
-       
         curl_setopt($this->curlHandler, CURLOPT_POST , TRUE);
-        curl_setopt($this->curlHandler, CURLOPT_POSTFIELDS , $request);
         curl_setopt($this->curlHandler, CURLOPT_RETURNTRANSFER , TRUE);
+        curl_setopt($this->curlHandler, CURLOPT_SSL_VERIFYPEER, TRUE);
         curl_setopt($this->curlHandler, CURLOPT_HTTPHEADER , array('Content-Type: application/json'));
+
+        // Try to login 
+        $this->login($user, $passwd);
+       
+    }
+        
+
+    public function getHTTPstatusCode()
+    {
+        return((isset($this->lastStats['http_code']))? $this->lastStats['http_code'] : -1 );
+    }
+
+    public function get_error()
+    {
+        if($this->lastStats['http_code'] != 200){
+            return($this->getHttpStatusCodeMessage($this->lastStats['http_code']));
+        }else{
+            return(curl_error($this->curlHandler));
+        }
+    }
+
+    public function success()
+    {
+        return(curl_errno($this->curlHandler) == 0 && $this->lastStats['http_code'] == 200);
+    }
+
+    public function __destruct()
+    {
+        if($this->curlHandler){
+             curl_close($this->curlHandler);
+        }
+    }
+
+    public function __call($method,$params) 
+    {
+        // Check if handle is still valid!
+        if(!$this->curlHandler && $this->lastAction != 'login'){
+             $this->__login();
+        }
+
+        // Start request
+        DEBUG (DEBUG_RPC, __LINE__, __FUNCTION__, __FILE__,"{$method}", "Calling: "); 
+        $response = $this->request($method,$params);
+        if($this->success()){
+            DEBUG (DEBUG_RPC, __LINE__, __FUNCTION__, __FILE__,
+                (is_array($response['result']))?$response['result']:bold($response['result']), "Result: "); 
+        }else{
+            DEBUG (DEBUG_RPC, __LINE__, __FUNCTION__, __FILE__,bold($this->get_error())."<br>".$response, "Result (FAILED): "); 
+        }
+
+        return($response['result']);
+    }
+
+    
+    private function request($method, $params)
+    {
+        // Set last action 
+        $this->lastAction = $method;
+
+        // Reset stats of last request.
+        $this->lastStats = array();
+   
+        // Validate input  values
+        if (!is_scalar($method))  trigger_error('jsonRPC::__call requires a scalar value as first parameter!');
+        if (is_array($params)) {
+            $params = array_values($params);
+        } else {
+            trigger_error('jsonRPC::__call requires an array value as second parameter!');
+        }
+
+        // prepares the request
+        $this->id ++;
+        $request = json_encode(array('method' => $method,'params' => $params,'id' => $this->id));
+
+        // Set curl options
+        curl_setopt($this->curlHandler, CURLOPT_POSTFIELDS , $request);
         $response = curl_exec($this->curlHandler);        
-               $this->debug && $this->debug.='***** Server response *****'."\n".$response.'***** End of server response *****'."\n";
-         $response = json_decode($response,true);
-
-               // debug output
-               if ($this->debug) {
-                       echo nl2br($debug);
-               }
-               
-               // final checks and return
-               if (!$this->notification) {
-                       // check
-                       if ($response['id'] != $currentId) {
-                               throw new Exception('Incorrect response id (request id: '.$currentId.', response id: '.$response['id'].')');
-                       }
-                       if (!is_null($response['error'])) {
-                               throw new Exception('Request error: '.$response['error']);
-                       }
-                       
-                       return $response['result'];
-                       
-               } else {
-                       return true;
-               }
-       }
+        $response = json_decode($response,true);
+
+        // Set current result stats.
+        $this->lastStats = curl_getinfo($this->curlHandler);
+    
+        return($response);
+    }
+    
+
+    public static function getHttpStatusCodeMessage($code)
+    {
+        $codes  = array(
+                '100' =>  'Continue',
+                '101' =>  'Switching Protocols',
+                '102' =>  'Processing',
+                '200' =>  'OK',
+                '201' =>  'Created',
+                '202' =>  'Accepted',
+                '203' =>  'Non-Authoritative Information',
+                '204' =>  'No Content',
+                '205' =>  'Reset Content',
+                '206' =>  'Partial Content',
+                '207' =>  'Multi-Status',
+                '300' =>  'Multiple Choice',
+                '301' =>  'Moved Permanently',
+                '302' =>  'Found',
+                '303' =>  'See Other',
+                '304' =>  'Not Modified',
+                '305' =>  'Use Proxy',
+                '306' =>  'reserved',
+                '307' =>  'Temporary Redirect',
+                '400' =>  'Bad Request',
+                '401' =>  'Unauthorized',
+                '402' =>  'Payment Required',
+                '403' =>  'Forbidden',
+                '404' =>  'Not Found',
+                '405' =>  'Method Not Allowed',
+                '406' =>  'Not Acceptable',
+                '407' =>  'Proxy Authentication Required',
+                '408' =>  'Request Time-out',
+                '409' =>  'Conflict',
+                '410' =>  'Gone',
+                '411' =>  'Length Required',
+                '412' =>  'Precondition Failed',
+                '413' =>  'Request Entity Too Large',
+                '414' =>  'Request-URI Too Long',
+                '415' =>  'Unsupported Media Type',
+                '416' =>  'Requested range not satisfiable',
+                '417' =>  'Expectation Failed',
+                '421' =>  'There are too many connections from your internet address',
+                '422' =>  'Unprocessable Entity',
+                '423' =>  'Locked',
+                '424' =>  'Failed Dependency',
+                '425' =>  'Unordered Collection',
+                '426' =>  'Upgrade Required',
+                '500' =>  'Internal Server Error',
+                '501' =>  'Not Implemented',
+                '502' =>  'Bad Gateway',
+                '503' =>  'Service Unavailable',
+                '504' =>  'Gateway Time-out',
+                '505' =>  'HTTP Version not supported',
+                '506' =>  'Variant Also Negotiates',
+                '507' =>  'Insufficient Storage',
+                '509' =>  'Bandwidth Limit Exceeded',
+                '510' =>  'Not Extended');
+        return((isset($codes[$code]))? $codes[$code] : sprintf(_("Unknown HTTP status code '%s'!"), $code));
+    }
 }
 ?>