File: //usr/local/mailchannels/clients/CPanel/CPanelGenericAPIJsonImpl.php
<?php
namespace MailChannels;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\GuzzleException;
class CPanelGenericAPIJsonImpl {
private $host;
private $username;
private $hash;
private $version;
private $client;
private $cpanelApiVersion;
private $logger;
function __construct($host, $username, $hash, $version, Client $client=null, $cpanelApiVersion) {
$this->logger = App::getLogger();
$this->host = $host;
$this->username = $username;
$this->hash = $hash;
$this->version = $version;
$this->cpanelApiVersion = $cpanelApiVersion;
if (!$client) {
$client = new Client([
'base_uri' => "https://$this->host:2087",
'timeout' => 300.0, // 5 min in seconds
]);
}
$this->client = $client;
}
/**
* @param $user
* @param $module
* @param $function
* @param array $params
* @return mixed
* @throws CPanelApiException
*/
function api($user, $module, $function, $params=array()) {
$headers = array();
if ($this->hash) {
$headers["Authorization"] = "WHM $this->username:" . preg_replace("'(\r|\n)'","",$this->hash);
}
$params['api.version'] = $this->version;
$params['cpanel_jsonapi_module'] = $module;
$params['cpanel_jsonapi_func'] = $function;
$params['cpanel_jsonapi_apiversion'] = $this->cpanelApiVersion;
$params['cpanel_jsonapi_user'] = $user;
$queryString = http_build_query($params);
App::getLogger()->debug("CPanel2 query: $module / $function / $user");
try {
$response = $this->client->request('GET', "/json-api/cpanel?$queryString", [
'headers' => $headers,
'verify' => App::verifySSL()
]);
} catch(GuzzleException $e) {
throw new CPanelApiException($e->getCode(), $e->getMessage(), null, $e);
} catch(\Exception $e) {
throw new CPanelApiException($e->getCode(), $e->getMessage(), null, $e);
}
if( $response->getStatusCode() >= 400 ) {
throw new CPanelApiException($response->getStatusCode(),
$response->getReasonPhrase(),
$response->getBody()->getContents());
}
$contents = $response->getBody()->getContents();
$this->logger->debug("CPanelAPI response: {$response->getStatusCode()} {$response->getReasonPhrase()}\n\t{$contents}");
$jsonResponse = json_decode($contents);
if ($this->cpanelApiVersion == 2) {
if( $jsonResponse->cpanelresult->event->result == "0" ) {
throw new CPanelApiException($response->getStatusCode(),
$jsonResponse->cpanelresult->event->reason,
$response->getBody()->getContents());
}
} elseif ($this->cpanelApiVersion == 3) {
if ( $jsonResponse->result->data == null) {
throw new CPanelApiException($response->getStatusCode(),
$jsonResponse->result->errors[0],
$response->getBody()->getContents());
}
} else {
if( isset($jsonResponse->data) && isset($jsonResponse->data->result) && $jsonResponse->data->result == "0" ) {
throw new CPanelApiException($response->getStatusCode(),
$jsonResponse->data->reason,
$response->getBody()->getContents());
}
}
return $jsonResponse;
}
}