From 15fd966208b12d3b68d17ffef7862b52945f48e4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=BCrgen=20Ratzenb=C3=B6ck?= Date: Thu, 18 Oct 2018 09:37:24 +0200 Subject: [PATCH 01/12] Check whether array has at least two elements before accessing the index 1 This allows to have an editorconfig with insert_final_new_line and prevents a nasty bug to track down. --- .../zoho/crm/library/common/CommonUtil.php | 54 +++++++++---------- src/com/zoho/oauth/common/ZohoOAuthUtil.php | 42 +++++++-------- 2 files changed, 46 insertions(+), 50 deletions(-) diff --git a/src/com/zoho/crm/library/common/CommonUtil.php b/src/com/zoho/crm/library/common/CommonUtil.php index 5cf68021..bd2ff575 100644 --- a/src/com/zoho/crm/library/common/CommonUtil.php +++ b/src/com/zoho/crm/library/common/CommonUtil.php @@ -1,32 +1,30 @@ 1) { + $reponseMap[trim($lineAfterSplit[0])] = trim($lineAfterSplit[1]); + } + } + fclose($fileHandler); + } catch (Exception $ex) { + Logger::warn("Exception occured while converting file content as map (file::ZohoOAuthUtil.php)"); + } + return $reponseMap; + } + + public static function getEmptyJSONObject() + { + return new ArrayObject(); + } } -?> \ No newline at end of file + +?> diff --git a/src/com/zoho/oauth/common/ZohoOAuthUtil.php b/src/com/zoho/oauth/common/ZohoOAuthUtil.php index 3fe280fb..57552734 100644 --- a/src/com/zoho/oauth/common/ZohoOAuthUtil.php +++ b/src/com/zoho/oauth/common/ZohoOAuthUtil.php @@ -1,27 +1,25 @@ 1) { + $reponseMap[trim($lineAfterSplit[0])] = trim($lineAfterSplit[1]); + } + } + fclose($fileHandler); + } catch (Exception $ex) { + OAuthLogger::warn("Exception occured while converting file content as map (file::ZohoOAuthUtil.php)"); + } + return $reponseMap; + } } -?> \ No newline at end of file + +?> From b3a303ce44fd474177181c8bb7a213228736ba9f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=BCrgen=20Ratzenb=C3=B6ck?= Date: Thu, 18 Oct 2018 09:43:18 +0200 Subject: [PATCH 02/12] Update package descriptions in composer.json --- composer.json | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/composer.json b/composer.json index e3110491..76c315f4 100644 --- a/composer.json +++ b/composer.json @@ -1,13 +1,19 @@ { - "name": "zohocrm/php-sdk", + "name": "jobs-at/zohocrm-php-sdk", "description": "Zoho CRM API SDK for PHP", - "type": "SDK", + "type": "sdk", "homepage": "https://github.com/zoho/zcrm-php-sdk", "authors": [ { "name": "Zoho CRM API Team", "email":"support@zohocrm.com", "homepage": "https://www.zoho.com/crm/help/customer-support.html", + "role": "Creator" + }, + { + "name": "jobs.at Dev Team", + "email": "dev@jobs.at", + "homepage": "https://www.jobs.at", "role": "Developer" } ], From e225f12777da5ab8e4c8c5c5c2e8474cf7ccc473 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=BCrgen=20Ratzenb=C3=B6ck?= Date: Thu, 18 Oct 2018 11:31:02 +0200 Subject: [PATCH 03/12] Make setConfigValues methods static to prevent an exception when calling them PHP throws an exception when you call non-static methods from within a static method. This was done until this change. --- .../crm/library/common/ZCRMConfigUtil.php | 22 +++++----- src/com/zoho/oauth/client/ZohoOAuth.php | 44 +++++++++---------- 2 files changed, 33 insertions(+), 33 deletions(-) diff --git a/src/com/zoho/crm/library/common/ZCRMConfigUtil.php b/src/com/zoho/crm/library/common/ZCRMConfigUtil.php index 267f16f0..3af88c60 100644 --- a/src/com/zoho/crm/library/common/ZCRMConfigUtil.php +++ b/src/com/zoho/crm/library/common/ZCRMConfigUtil.php @@ -5,7 +5,7 @@ class ZCRMConfigUtil { private static $configProperties=array(); - + public static function getInstance() { return new ZCRMConfigUtil(); @@ -56,11 +56,11 @@ public static function initialize($initializeOAuth,$configuration) } } - private function setConfigValues($configuration) + private static function setConfigValues($configuration) { $config_keys = array(APIConstants::CURRENT_USER_EMAIL,ZohoOAuthConstants::SANDBOX,APIConstants::API_BASEURL, APIConstants::API_VERSION,APIConstants::APPLICATION_LOGFILE_PATH); - + if(!array_key_exists(ZohoOAuthConstants::SANDBOX,$configuration)) { self::$configProperties[ZohoOAuthConstants::SANDBOX] = "false"; @@ -79,7 +79,7 @@ private function setConfigValues($configuration) self::$configProperties[$key] = $configuration[$key]; } } - + public static function loadConfigProperties($fileHandler) { $configMap=CommonUtil::getFileContentAsMap($fileHandler); @@ -88,22 +88,22 @@ public static function loadConfigProperties($fileHandler) self::$configProperties[$key]=$value; } } - + public static function getConfigValue($key) { return isset(self::$configProperties[$key])?self::$configProperties[$key]:''; } - + public static function setConfigValue($key,$value) { self::$configProperties[$key]=$value; } - + public static function getAPIBaseUrl() { return self::getConfigValue("apiBaseUrl"); } - + public static function getAPIVersion() { return self::getConfigValue("apiVersion"); @@ -111,7 +111,7 @@ public static function getAPIVersion() public static function getAccessToken() { $currentUserEmail= ZCRMRestClient::getCurrentUserEmailID(); - + if ($currentUserEmail == null && self::getConfigValue("currentUserEmail") == null) { throw new ZCRMException("Current user should either be set in ZCRMRestClient or in configuration.properties file"); @@ -123,10 +123,10 @@ public static function getAccessToken() $oAuthCliIns = ZohoOAuth::getClientInstance(); return $oAuthCliIns->getAccessToken($currentUserEmail); } - + public static function getAllConfigs() { return self::$configProperties; } } -?> \ No newline at end of file +?> diff --git a/src/com/zoho/oauth/client/ZohoOAuth.php b/src/com/zoho/oauth/client/ZohoOAuth.php index a329da39..f49f90cf 100644 --- a/src/com/zoho/oauth/client/ZohoOAuth.php +++ b/src/com/zoho/oauth/client/ZohoOAuth.php @@ -11,12 +11,12 @@ class ZohoOAuth { private static $configProperties =array(); - + public static function initializeWithOutInputStream($configuration) { self::initialize(false,$configuration); } - + public static function initialize($configFilePointer,$configuration) { try @@ -55,7 +55,7 @@ public static function initialize($configFilePointer,$configuration) } } $oAuthParams=new ZohoOAuthParams(); - + $oAuthParams->setAccessType(self::getConfigValue(ZohoOAuthConstants::ACCESS_TYPE)); $oAuthParams->setClientId(self::getConfigValue(ZohoOAuthConstants::CLIENT_ID)); $oAuthParams->setClientSecret(self::getConfigValue(ZohoOAuthConstants::CLIENT_SECRET)); @@ -68,13 +68,13 @@ public static function initialize($configFilePointer,$configuration) throw ioe; } } - - private function setConfigValues($configuration) + + private static function setConfigValues($configuration) { $config_keys = array(ZohoOAuthConstants::CLIENT_ID,ZohoOAuthConstants::CLIENT_SECRET,ZohoOAuthConstants::REDIRECT_URL,ZohoOAuthConstants::ACCESS_TYPE ,ZohoOAuthConstants::PERSISTENCE_HANDLER_CLASS,ZohoOAuthConstants::IAM_URL,ZohoOAuthConstants::TOKEN_PERSISTENCE_PATH,ZohoOAuthConstants::DATABASE_PORT ,ZohoOAuthConstants::DATABASE_PASSWORD,ZohoOAuthConstants::DATABASE_USERNAME); - + if(!array_key_exists(ZohoOAuthConstants::ACCESS_TYPE,$configuration) || $configuration[ZohoOAuthConstants::ACCESS_TYPE] == "") { self::$configProperties[ZohoOAuthConstants::ACCESS_TYPE] = "offline"; @@ -87,7 +87,7 @@ private function setConfigValues($configuration) { self::$configProperties[ZohoOAuthConstants::IAM_URL] = "https://accounts.zoho.com"; } - + foreach($config_keys as $key) { if(array_key_exists($key,$configuration)) @@ -98,62 +98,62 @@ public static function getConfigValue($key) { return self::$configProperties[$key]; } - + public static function getAllConfigs() { return self::$configProperties; } - + public static function getIAMUrl() { return self::getConfigValue(ZohoOAuthConstants::IAM_URL); } - + public static function getGrantURL() { return self::getIAMUrl()."/oauth/v2/auth"; } - + public static function getTokenURL() { return self::getIAMUrl()."/oauth/v2/token"; } - + public static function getRefreshTokenURL() { return self::getIAMUrl()."/oauth/v2/token"; } - + public static function getRevokeTokenURL() { return self::getIAMUrl()."/oauth/v2/token/revoke"; } - + public static function getUserInfoURL() { return self::getIAMUrl()."/oauth/user/info"; } - + public static function getClientID() { return self::getConfigValue(ZohoOAuthConstants::CLIENT_ID); } - + public static function getClientSecret() { return self::getConfigValue(ZohoOAuthConstants::CLIENT_SECRET); } - + public static function getRedirectURL() { return self::getConfigValue(ZohoOAuthConstants::REDIRECT_URL); } - + public static function getAccessType() { return self::getConfigValue(ZohoOAuthConstants::ACCESS_TYPE); } - + public static function getPersistenceHandlerInstance() { try @@ -165,7 +165,7 @@ public static function getPersistenceHandlerInstance() throw new ZohoOAuthException($ex); } } - + public static function getClientInstance() { if(ZohoOAuthClient::getInstanceWithOutParam() == null) @@ -174,6 +174,6 @@ public static function getClientInstance() } return ZohoOAuthClient::getInstanceWithOutParam(); } - + } -?> \ No newline at end of file +?> From c8490f91c68eb09e87f624163a9f4c1baabc7e5f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=BCrgen=20Ratzenb=C3=B6ck?= Date: Tue, 30 Oct 2018 13:25:16 +0100 Subject: [PATCH 04/12] Interpret sandbox env flag as boolean The sandbox flag comes into the zoho api as boolean flag from our config file but was interpreted by the official zcrm php sdk as string ("true" or "false") which makes no sense. Thus, interpet it as boolean value to decide whether to use sandbox or production. --- src/com/zoho/crm/library/api/APIRequest.php | 389 +++++++++--------- .../crm/library/common/ZCRMConfigUtil.php | 2 +- 2 files changed, 199 insertions(+), 192 deletions(-) diff --git a/src/com/zoho/crm/library/api/APIRequest.php b/src/com/zoho/crm/library/api/APIRequest.php index cd214d35..a750c550 100644 --- a/src/com/zoho/crm/library/api/APIRequest.php +++ b/src/com/zoho/crm/library/api/APIRequest.php @@ -1,11 +1,12 @@ url.$apiHandler->getUrlPath()); - if(substr($apiHandler->getUrlPath(),0,4)!=="http") - { - self::setUrl("https://".$this->url); - } - self::setRequestParams($apiHandler->getRequestParams()); - self::setRequestHeaders($apiHandler->getRequestHeaders()); - self::setRequestBody($apiHandler->getRequestBody()); - self::setRequestMethod($apiHandler->getRequestMethod()); - self::setApiKey($apiHandler->getApiKey()); - } - - public static function getInstance($apiHandler) - { - $instance=new APIRequest($apiHandler); - return $instance; - } - /** - * Method to construct the API Url - */ - public function constructAPIUrl() - { - $hitSandbox=ZCRMConfigUtil::getConfigValue('sandbox'); - $baseUrl=strcasecmp($hitSandbox, "true")==0?str_replace('www','sandbox',ZCRMConfigUtil::getAPIBaseUrl()):ZCRMConfigUtil::getAPIBaseUrl(); - $this->url=$baseUrl."/crm/".ZCRMConfigUtil::getAPIVersion()."/"; - $this->url=str_replace(PHP_EOL, '', $this->url); - } - - - private function authenticateRequest() - { - try{ - $accessToken= (new ZCRMConfigUtil())->getAccessToken(); - $this->requestHeaders[APIConstants::AUTHORIZATION]=APIConstants::OAUTH_HEADER_PREFIX.$accessToken; - }catch (ZCRMException $ex) - { - throw $ex; - } - } - /** - * initiate the request and get the API response - * @return Instance of APIResponse - */ - public function getAPIResponse() - { - try { - $connector=ZohoHTTPConnector::getInstance(); - $connector->setUrl($this->url); - self::authenticateRequest(); - $connector->setRequestHeadersMap($this->requestHeaders); - $connector->setRequestParamsMap($this->requestParams); - $connector->setRequestBody($this->requestBody); - $connector->setRequestType($this->requestMethod); - $connector->setApiKey($this->apiKey); - $response=$connector->fireRequest(); - $this->response=$response[0]; - $this->responseInfo=$response[1]; - return new APIResponse($this->response,$this->responseInfo['http_code']); - } - catch (ZCRMException $e) - { - throw $e; - } - } - - /** - * initiate the request and get the API response - * @return instance of BulkAPIResponse - */ - public function getBulkAPIResponse() - { - try { - $connector=ZohoHTTPConnector::getInstance(); - $connector->setUrl($this->url); - self::authenticateRequest(); - $connector->setRequestHeadersMap($this->requestHeaders); - $connector->setRequestParamsMap($this->requestParams); - $connector->setRequestBody($this->requestBody); - $connector->setRequestType($this->requestMethod); - $connector->setApiKey($this->apiKey); - $connector->setBulkRequest(true); - $response=$connector->fireRequest(); - $this->response=$response[0]; - $this->responseInfo=$response[1]; - return new BulkAPIResponse($this->response,$this->responseInfo['http_code']); - } - catch (ZCRMException $e) - { - throw $e; - } - } - - public function uploadFile($filePath) - { - try { - $fileContent=file_get_contents($filePath); - $filePathArray=explode('/',$filePath); - $fileName=$filePathArray[sizeof($filePathArray)-1]; - if (function_exists('curl_file_create')) { // php 5.6+ - $cFile = curl_file_create($filePath); - } else { // - $cFile = '@' . realpath($filePath); - } - $post = array('file'=> $cFile); - - $connector=ZohoHTTPConnector::getInstance(); - $connector->setUrl($this->url); - self::authenticateRequest(); - $connector->setRequestHeadersMap($this->requestHeaders); - $connector->setRequestParamsMap($this->requestParams); - $connector->setRequestBody($post); - $connector->setRequestType($this->requestMethod); - $connector->setApiKey($this->apiKey); - $response=$connector->fireRequest(); - $this->response=$response[0]; - $this->responseInfo=$response[1]; - return new APIResponse($this->response,$this->responseInfo['http_code']); - } - catch (ZCRMException $e) - { - throw $e; - } - } - public function uploadLinkAsAttachment($linkURL) - { - try { - $post = array('attachmentUrl'=> $linkURL); - - $connector=ZohoHTTPConnector::getInstance(); - $connector->setUrl($this->url); - self::authenticateRequest(); - $connector->setRequestHeadersMap($this->requestHeaders); - $connector->setRequestBody($post); - $connector->setRequestType($this->requestMethod); - $connector->setApiKey($this->apiKey); - $response=$connector->fireRequest(); - $this->response=$response[0]; - $this->responseInfo=$response[1]; - return new APIResponse($this->response,$this->responseInfo['http_code']); - } - catch (ZCRMException $e) - { - throw $e; - } - } - - public function downloadFile() - { - try { - $connector=ZohoHTTPConnector::getInstance(); - $connector->setUrl($this->url); - self::authenticateRequest(); - $connector->setRequestHeadersMap($this->requestHeaders); - $connector->setRequestParamsMap($this->requestParams); - $connector->setRequestType($this->requestMethod); - $response=$connector->downloadFile(); - return (new FileAPIResponse())->setFileContent($response[0],$response[1]['http_code']); - }catch (ZCRMException $e) - { - throw $e; - } - } + private $url = null; + private $requestParams = []; + private $requestHeaders = []; + private $requestBody; + private $requestMethod; + private $apiKey = null; + private $response = null; + private $reponseInfo = null; + + private function __construct($apiHandler) + { + self::constructAPIUrl(); + self::setUrl($this->url . $apiHandler->getUrlPath()); + if (substr($apiHandler->getUrlPath(), 0, 4) !== "http") { + self::setUrl("https://" . $this->url); + } + self::setRequestParams($apiHandler->getRequestParams()); + self::setRequestHeaders($apiHandler->getRequestHeaders()); + self::setRequestBody($apiHandler->getRequestBody()); + self::setRequestMethod($apiHandler->getRequestMethod()); + self::setApiKey($apiHandler->getApiKey()); + } + + public static function getInstance($apiHandler) + { + $instance = new APIRequest($apiHandler); + return $instance; + } + + /** + * Method to construct the API Url + */ + public function constructAPIUrl() + { + $hitSandbox = ZCRMConfigUtil::getConfigValue('sandbox'); + $baseUrl = $hitSandbox ? str_replace('www', 'sandbox', ZCRMConfigUtil::getAPIBaseUrl()) : ZCRMConfigUtil::getAPIBaseUrl(); + $this->url = $baseUrl . "/crm/" . ZCRMConfigUtil::getAPIVersion() . "/"; + $this->url = str_replace(PHP_EOL, '', $this->url); + } + + + private function authenticateRequest() + { + try { + $accessToken = (new ZCRMConfigUtil())->getAccessToken(); + $this->requestHeaders[APIConstants::AUTHORIZATION] = APIConstants::OAUTH_HEADER_PREFIX . $accessToken; + } catch (ZCRMException $ex) { + throw $ex; + } + } + + /** + * initiate the request and get the API response + * @return Instance of APIResponse + */ + public function getAPIResponse() + { + try { + $connector = ZohoHTTPConnector::getInstance(); + $connector->setUrl($this->url); + self::authenticateRequest(); + $connector->setRequestHeadersMap($this->requestHeaders); + $connector->setRequestParamsMap($this->requestParams); + $connector->setRequestBody($this->requestBody); + $connector->setRequestType($this->requestMethod); + $connector->setApiKey($this->apiKey); + $response = $connector->fireRequest(); + $this->response = $response[0]; + $this->responseInfo = $response[1]; + return new APIResponse($this->response, $this->responseInfo['http_code']); + } catch (ZCRMException $e) { + throw $e; + } + } + + /** + * initiate the request and get the API response + * @return instance of BulkAPIResponse + */ + public function getBulkAPIResponse() + { + try { + $connector = ZohoHTTPConnector::getInstance(); + $connector->setUrl($this->url); + self::authenticateRequest(); + $connector->setRequestHeadersMap($this->requestHeaders); + $connector->setRequestParamsMap($this->requestParams); + $connector->setRequestBody($this->requestBody); + $connector->setRequestType($this->requestMethod); + $connector->setApiKey($this->apiKey); + $connector->setBulkRequest(true); + $response = $connector->fireRequest(); + $this->response = $response[0]; + $this->responseInfo = $response[1]; + return new BulkAPIResponse($this->response, $this->responseInfo['http_code']); + } catch (ZCRMException $e) { + throw $e; + } + } + + public function uploadFile($filePath) + { + try { + $fileContent = file_get_contents($filePath); + $filePathArray = explode('/', $filePath); + $fileName = $filePathArray[sizeof($filePathArray) - 1]; + if (function_exists('curl_file_create')) { // php 5.6+ + $cFile = curl_file_create($filePath); + } else { // + $cFile = '@' . realpath($filePath); + } + $post = ['file' => $cFile]; + + $connector = ZohoHTTPConnector::getInstance(); + $connector->setUrl($this->url); + self::authenticateRequest(); + $connector->setRequestHeadersMap($this->requestHeaders); + $connector->setRequestParamsMap($this->requestParams); + $connector->setRequestBody($post); + $connector->setRequestType($this->requestMethod); + $connector->setApiKey($this->apiKey); + $response = $connector->fireRequest(); + $this->response = $response[0]; + $this->responseInfo = $response[1]; + return new APIResponse($this->response, $this->responseInfo['http_code']); + } catch (ZCRMException $e) { + throw $e; + } + } + + public function uploadLinkAsAttachment($linkURL) + { + try { + $post = ['attachmentUrl' => $linkURL]; + + $connector = ZohoHTTPConnector::getInstance(); + $connector->setUrl($this->url); + self::authenticateRequest(); + $connector->setRequestHeadersMap($this->requestHeaders); + $connector->setRequestBody($post); + $connector->setRequestType($this->requestMethod); + $connector->setApiKey($this->apiKey); + $response = $connector->fireRequest(); + $this->response = $response[0]; + $this->responseInfo = $response[1]; + return new APIResponse($this->response, $this->responseInfo['http_code']); + } catch (ZCRMException $e) { + throw $e; + } + } + + public function downloadFile() + { + try { + $connector = ZohoHTTPConnector::getInstance(); + $connector->setUrl($this->url); + self::authenticateRequest(); + $connector->setRequestHeadersMap($this->requestHeaders); + $connector->setRequestParamsMap($this->requestParams); + $connector->setRequestType($this->requestMethod); + $response = $connector->downloadFile(); + return (new FileAPIResponse())->setFileContent($response[0], $response[1]['http_code']); + } catch (ZCRMException $e) { + throw $e; + } + } /** * Get the request url * @return String */ - public function getUrl(){ + public function getUrl() + { return $this->url; } @@ -199,7 +194,8 @@ public function getUrl(){ * Set the request url * @param String $url */ - public function setUrl($url){ + public function setUrl($url) + { $this->url = $url; } @@ -207,7 +203,8 @@ public function setUrl($url){ * Get the request parameters * @return Array */ - public function getRequestParams(){ + public function getRequestParams() + { return $this->requestParams; } @@ -215,7 +212,8 @@ public function getRequestParams(){ * Set the request parameters * @param Array $requestParams */ - public function setRequestParams($requestParams){ + public function setRequestParams($requestParams) + { $this->requestParams = $requestParams; } @@ -223,7 +221,8 @@ public function setRequestParams($requestParams){ * Get the request headers * @return Array */ - public function getRequestHeaders(){ + public function getRequestHeaders() + { return $this->requestHeaders; } @@ -231,7 +230,8 @@ public function getRequestHeaders(){ * Set the request headers * @param Array $requestHeaders */ - public function setRequestHeaders($requestHeaders){ + public function setRequestHeaders($requestHeaders) + { $this->requestHeaders = $requestHeaders; } @@ -239,7 +239,8 @@ public function setRequestHeaders($requestHeaders){ * Get the request body * @return JSON */ - public function getRequestBody(){ + public function getRequestBody() + { return $this->requestBody; } @@ -247,7 +248,8 @@ public function getRequestBody(){ * Set the request body * @param JSON $requestBody */ - public function setRequestBody($requestBody){ + public function setRequestBody($requestBody) + { $this->requestBody = $requestBody; } @@ -255,7 +257,8 @@ public function setRequestBody($requestBody){ * Get the request method * @return String */ - public function getRequestMethod(){ + public function getRequestMethod() + { return $this->requestMethod; } @@ -263,7 +266,8 @@ public function getRequestMethod(){ * Set the request method * @param String $requestMethod */ - public function setRequestMethod($requestMethod){ + public function setRequestMethod($requestMethod) + { $this->requestMethod = $requestMethod; } @@ -271,7 +275,8 @@ public function setRequestMethod($requestMethod){ * Get the API Key used in the input json data(like 'modules', 'data','layouts',..etc) * @return String */ - public function getApiKey(){ + public function getApiKey() + { return $this->apiKey; } @@ -279,9 +284,11 @@ public function getApiKey(){ * Set the API Key used in the input json data(like 'modules', 'data','layouts',..etc) * @param String $apiKey */ - public function setApiKey($apiKey){ + public function setApiKey($apiKey) + { $this->apiKey = $apiKey; } } -?> \ No newline at end of file + +?> diff --git a/src/com/zoho/crm/library/common/ZCRMConfigUtil.php b/src/com/zoho/crm/library/common/ZCRMConfigUtil.php index 3af88c60..921ecd81 100644 --- a/src/com/zoho/crm/library/common/ZCRMConfigUtil.php +++ b/src/com/zoho/crm/library/common/ZCRMConfigUtil.php @@ -63,7 +63,7 @@ private static function setConfigValues($configuration) if(!array_key_exists(ZohoOAuthConstants::SANDBOX,$configuration)) { - self::$configProperties[ZohoOAuthConstants::SANDBOX] = "false"; + self::$configProperties[ZohoOAuthConstants::SANDBOX] = false; } if(!array_key_exists(APIConstants::API_BASEURL,$configuration)) { From 5f79bf0d3eccca6833dd6fedd2e41649f8532a00 Mon Sep 17 00:00:00 2001 From: Roman Sumereder Date: Thu, 11 Jul 2019 12:24:12 +0200 Subject: [PATCH 05/12] Remove array filter to allow syncing of null values --- .../library/api/handler/EntityAPIHandler.php | 100 +++++++++--------- 1 file changed, 50 insertions(+), 50 deletions(-) diff --git a/src/com/zoho/crm/library/api/handler/EntityAPIHandler.php b/src/com/zoho/crm/library/api/handler/EntityAPIHandler.php index b5c00daa..43b1a0f1 100644 --- a/src/com/zoho/crm/library/api/handler/EntityAPIHandler.php +++ b/src/com/zoho/crm/library/api/handler/EntityAPIHandler.php @@ -13,17 +13,17 @@ class EntityAPIHandler extends APIHandler { protected $record=null; - + private function __construct($zcrmrecord) { $this->record=$zcrmrecord; } - + public static function getInstance($zcrmrecord) { return new EntityAPIHandler($zcrmrecord); } - + public function getRecord() { try{ @@ -41,7 +41,7 @@ public function getRecord() throw $exception; } } - + public function createRecord() { try{ @@ -58,9 +58,9 @@ public function createRecord() $this->record->setCreatedTime($reponseDetails['Created_Time']); $createdBy=$reponseDetails['Created_By']; $this->record->setCreatedBy(ZCRMUser::getInstance($createdBy['id'],$createdBy['name'])); - + $responseInstance->setData($this->record); - + return $responseInstance; }catch (ZCRMException $exception) { @@ -68,7 +68,7 @@ public function createRecord() throw $exception; } } - + public function updateRecord() { try{ @@ -77,9 +77,9 @@ public function updateRecord() $this->urlPath=$this->record->getModuleApiName()."/".$this->record->getEntityId(); $this->addHeader("Content-Type","application/json"); $this->requestBody=json_encode(array_filter(array("data"=>array($inputJSON))));; - + $responseInstance=APIRequest::getInstance($this)->getAPIResponse(); - + $responseDataArray=$responseInstance->getResponseJSON()['data']; $responseData=$responseDataArray[0]; $reponseDetails=$responseData['details']; @@ -89,9 +89,9 @@ public function updateRecord() $this->record->setCreatedBy(ZCRMUser::getInstance($createdBy['id'],$createdBy['name'])); $modifiedBy=$reponseDetails['Modified_By']; $this->record->setModifiedBy(ZCRMUser::getInstance($modifiedBy['id'],$modifiedBy['name'])); - + $responseInstance->setData($this->record); - + return $responseInstance; }catch (ZCRMException $exception) { @@ -99,16 +99,16 @@ public function updateRecord() throw $exception; } } - + public function deleteRecord() { try{ $this->requestMethod=APIConstants::REQUEST_METHOD_DELETE; $this->urlPath=$this->record->getModuleApiName()."/".$this->record->getEntityId(); $this->addHeader("Content-Type","application/json"); - + $responseInstance=APIRequest::getInstance($this)->getAPIResponse(); - + return $responseInstance; }catch (ZCRMException $exception) { @@ -116,14 +116,14 @@ public function deleteRecord() throw $exception; } } - + public function convertRecord($potentialRecord, $assignToUser) { try{ $this->requestMethod=APIConstants::REQUEST_METHOD_POST; $this->urlPath=$this->record->getModuleApiName()."/".$this->record->getEntityId()."/actions/convert"; $this->addHeader("Content-Type","application/json"); - + $dataObject=array(); if($assignToUser!=null) { @@ -141,12 +141,12 @@ public function convertRecord($potentialRecord, $assignToUser) $dataArray=json_encode(array(APIConstants::DATA=>array(new ArrayObject()))); } $this->requestBody=$dataArray; - + $responseInstance=APIRequest::getInstance($this)->getAPIResponse(); - + $responseJSON=$responseInstance->getResponseJSON(); - - + + //Process Response JSON $convertedIdsJSON = $responseJSON[APIConstants::DATA][0]; $convertedIds = array(); @@ -159,7 +159,7 @@ public function convertRecord($potentialRecord, $assignToUser) { $convertedIds[APIConstants::DEALS]=$convertedIdsJSON[APIConstants::DEALS]; } - + return $convertedIds; }catch (ZCRMException $exception) { @@ -167,7 +167,7 @@ public function convertRecord($potentialRecord, $assignToUser) throw $exception; } } - + public function uploadPhoto($filePath) { try{ @@ -180,15 +180,15 @@ public function uploadPhoto($filePath) $cFile = '@' . realpath($filePath); } $post = array('file'=> $cFile); - + $this->requestMethod=APIConstants::REQUEST_METHOD_POST; $this->urlPath=$this->record->getModuleApiName()."/".$this->record->getEntityId()."/photo"; $this->requestBody=$post; - + $responseInstance=APIRequest::getInstance($this)->getAPIResponse(); - + return $responseInstance; - + }catch (ZCRMException $exception) { APIExceptionHandler::logException($exception); @@ -200,7 +200,7 @@ public function downloadPhoto() try{ $this->requestMethod=APIConstants::REQUEST_METHOD_GET; $this->urlPath=$this->record->getModuleApiName()."/".$this->record->getEntityId()."/photo"; - + return APIRequest::getInstance($this)->downloadFile(); }catch (ZCRMException $exception) { @@ -208,13 +208,13 @@ public function downloadPhoto() throw $exception; } } - + public function deletePhoto() { try{ $this->requestMethod=APIConstants::REQUEST_METHOD_DELETE; $this->urlPath=$this->record->getModuleApiName()."/".$this->record->getEntityId()."/photo"; - + return APIRequest::getInstance($this)->getAPIResponse(); }catch (ZCRMException $exception) { @@ -222,7 +222,7 @@ public function deletePhoto() throw $exception; } } - + function getZCRMRecordAsJSON() { $recordJSON=array(); @@ -263,9 +263,9 @@ function getZCRMRecordAsJSON() { $recordJSON["Tax"]=self::getTaxListAsJSON(); } - return array_filter($recordJSON); + return $recordJSON; } - + public function getTaxListAsJSON() { $taxes = array(); @@ -298,7 +298,7 @@ public function getZCRMPriceDetailAsJSON(ZCRMPriceBookPricing $priceDetailIns) $priceDetailJSON["from_range"]=$priceDetailIns->getFromRange(); return $priceDetailJSON; } - + public function getParticipantsAsJSONArray() { $participantsArr = array(); @@ -309,7 +309,7 @@ public function getParticipantsAsJSONArray() } return $participantsArr; } - + public function getZCRMParticipantAsJSON(ZCRMEventParticipant $participantIns) { $participantJSON = array(); @@ -319,10 +319,10 @@ public function getZCRMParticipantAsJSON(ZCRMEventParticipant $participantIns) $participantJSON["Email"]="".$participantIns->getEmail(); $participantJSON["invited"]=(boolean)$participantIns->isInvited(); $participantJSON["status"]="".$participantIns->getStatus(); - + return $participantJSON; } - + public function getLineItemJSON($lineItemsArray) { $lineItemsAsJSONArray=array(); @@ -373,12 +373,12 @@ public function getLineItemJSON($lineItemsArray) array_push($lineTaxArray,$tax); } $lineItemData['line_tax']=$lineTaxArray; - + array_push($lineItemsAsJSONArray,array_filter($lineItemData)); } return array_filter($lineItemsAsJSONArray); } - + public function setRecordProperties($recordDetails) { foreach($recordDetails as $key=>$value) @@ -465,7 +465,7 @@ public function setRecordProperties($recordDetails) { $this->record->setFieldValue($key, $value); } - + } else { @@ -473,7 +473,7 @@ public function setRecordProperties($recordDetails) } } } - + private function setParticipants($participants) { foreach ($participants as $participantDetail) @@ -481,8 +481,8 @@ private function setParticipants($participants) $this->record->addParticipant(self::getZCRMParticipant($participantDetail)); } } - - + + private function setPriceDetails($priceDetails) { foreach($priceDetails as $priceDetail) @@ -490,7 +490,7 @@ private function setPriceDetails($priceDetails) $this->record->addPriceDetail(self::getZCRMPriceDetail($priceDetail)); } } - + public function getZCRMParticipant($participantDetail) { $participant = ZCRMEventParticipant::getInstance($participantDetail['type'],$participantDetail['participant']); @@ -498,20 +498,20 @@ public function getZCRMParticipant($participantDetail) $participant->setEmail($participantDetail["Email"]); $participant->setInvited((boolean)$participantDetail["invited"]); $participant->setStatus($participantDetail["status"]); - + return $participant; } - + public function getZCRMPriceDetail($priceDetails) { $priceDetailIns = ZCRMPriceBookPricing::getInstance($priceDetails["id"]); $priceDetailIns->setDiscount((double)$priceDetails["discount"]); $priceDetailIns->setToRange((double)$priceDetails["to_range"]); $priceDetailIns->setFromRange((double)$priceDetails["from_range"]); - + return $priceDetailIns; } - + public function setInventoryLineItems($lineItems) { foreach ($lineItems as $lineItem) @@ -519,7 +519,7 @@ public function setInventoryLineItems($lineItems) $this->record->addLineItem(self::getZCRMLineItemInstance($lineItem)); } } - + public function getZCRMLineItemInstance($lineItemDetails) { $productDetails = $lineItemDetails["product"]; @@ -548,8 +548,8 @@ public function getZCRMLineItemInstance($lineItemDetails) $lineItemInstance->addLineTax($taxInstance); } $lineItemInstance->setNetTotal($lineItemDetails["net_total"]+0); - + return $lineItemInstance; } } -?> \ No newline at end of file +?> From 7f0eebf2def2ea7905117e1f9aff083ac23f6125 Mon Sep 17 00:00:00 2001 From: Roman Sumereder Date: Mon, 25 Nov 2019 12:44:15 +0100 Subject: [PATCH 06/12] Bugfix Check if is array before calling the count function --- .../crm/library/common/ZohoHTTPConnector.php | 38 +++++++++---------- 1 file changed, 19 insertions(+), 19 deletions(-) diff --git a/src/com/zoho/crm/library/common/ZohoHTTPConnector.php b/src/com/zoho/crm/library/common/ZohoHTTPConnector.php index 5063eb98..f02f3195 100644 --- a/src/com/zoho/crm/library/common/ZohoHTTPConnector.php +++ b/src/com/zoho/crm/library/common/ZohoHTTPConnector.php @@ -17,26 +17,26 @@ class ZohoHTTPConnector private $userAgent="ZohoCRM PHP SDK"; private $apiKey=null; private $isBulkRequest=false; - + private function __construct() { - + } - + public static function getInstance() { return new ZohoHTTPConnector(); } - + public function fireRequest() { $curl_pointer=curl_init(); - if(count(self::getRequestParamsMap())>0) + if(is_array(self::getRequestParamsMap()) && count(self::getRequestParamsMap()) > 0) { $url=self::getUrl()."?".self::getUrlParamsAsString(self::getRequestParamsMap()); curl_setopt($curl_pointer,CURLOPT_URL,$url); } - else + else { curl_setopt($curl_pointer,CURLOPT_URL,self::getUrl()); } @@ -45,7 +45,7 @@ public function fireRequest() curl_setopt($curl_pointer,CURLOPT_USERAGENT,$this->userAgent); curl_setopt($curl_pointer,CURLOPT_HTTPHEADER,self::getRequestHeadersAsArray()); curl_setopt($curl_pointer,CURLOPT_CUSTOMREQUEST,APIConstants::REQUEST_METHOD_GET); - + if ($this->requestType===APIConstants::REQUEST_METHOD_POST) { curl_setopt($curl_pointer,CURLOPT_CUSTOMREQUEST,APIConstants::REQUEST_METHOD_POST); @@ -64,10 +64,10 @@ public function fireRequest() $result=curl_exec($curl_pointer); $responseInfo=curl_getinfo($curl_pointer); curl_close($curl_pointer); - + return array($result,$responseInfo); } - + public function downloadFile() { $curl_pointer=curl_init(); @@ -82,7 +82,7 @@ public function downloadFile() curl_close($curl_pointer); return array($result,$responseInfo); } - + public function getUrl() { return $this->url; } @@ -109,7 +109,7 @@ public function addHeader($key,$value) { $this->requestHeaders[$key]=$valArray; } } - + public function getUrlParamsAsString($urlParams) { $params_as_string=""; @@ -123,10 +123,10 @@ public function getUrlParamsAsString($urlParams) } $params_as_string=rtrim($params_as_string,"&"); $params_as_string=str_replace(PHP_EOL, '', $params_as_string); - + return $params_as_string; } - + public function setRequestHeadersMap($headers) { $this->requestHeaders=$headers; @@ -135,7 +135,7 @@ public function getRequestHeadersMap() { return $this->requestHeaders; } - + public function setRequestParamsMap($params) { $this->requestParams=$params; @@ -144,7 +144,7 @@ public function getRequestParamsMap() { return $this->requestParams; } - + public function setRequestBody($reqBody) { $this->requestBody=$reqBody; @@ -153,7 +153,7 @@ public function getRequestBody() { return $this->requestBody; } - + public function setRequestType($reqType) { $this->requestType=$reqType; @@ -162,7 +162,7 @@ public function getRequestType() { return $this->requestType; } - + public function getRequestHeadersAsArray() { $headersArray=array(); @@ -171,7 +171,7 @@ public function getRequestHeadersAsArray() { $headersArray[]=$key.":".$value; } - + return $headersArray; } @@ -209,4 +209,4 @@ public function setBulkRequest($isBulkRequest){ } } -?> \ No newline at end of file +?> From 70c1abdbc1467993fde03e1ae326ec41dcde72c5 Mon Sep 17 00:00:00 2001 From: Matthias Balota Date: Wed, 12 Feb 2020 12:41:16 +0100 Subject: [PATCH 07/12] JOBS-526 Replaces deprecated offset access syntax curly braces with square ones for PHP 7.4 --- src/com/zoho/crm/library/exception/Logger.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/com/zoho/crm/library/exception/Logger.php b/src/com/zoho/crm/library/exception/Logger.php index b85f8e5a..f369d841 100644 --- a/src/com/zoho/crm/library/exception/Logger.php +++ b/src/com/zoho/crm/library/exception/Logger.php @@ -6,7 +6,7 @@ public static function writeToFile($msg) { set_include_path(ZCRMConfigUtil::getConfigValue('applicationLogFilePath')); $path=get_include_path(); - if($path{strlen($path)-1}!='\/') + if($path[strlen($path)-1]!='\/') { $path=$path."/"; } From 1dd033ef322806dd02d1c4336f7f4f0407d727b1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=BCrgen=20Ratzenb=C3=B6ck?= Date: Fri, 14 Feb 2020 11:49:21 +0100 Subject: [PATCH 08/12] JOBS-526 Add gitignore --- .gitignore | 2 ++ 1 file changed, 2 insertions(+) create mode 100644 .gitignore diff --git a/.gitignore b/.gitignore new file mode 100644 index 00000000..55940e57 --- /dev/null +++ b/.gitignore @@ -0,0 +1,2 @@ +/vendor/ +composer.lock \ No newline at end of file From 45bc9572d01eac78a7e4ec905b14d3b1b83dc15b Mon Sep 17 00:00:00 2001 From: Marc Melchor Date: Wed, 15 Jul 2020 13:30:34 +0200 Subject: [PATCH 09/12] JOBS-845 Zoho CRM not call zoho API fds --- src/com/zoho/crm/library/common/ZCRMConfigUtil.php | 4 ++-- src/com/zoho/crm/library/exception/Logger.php | 6 +++--- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/src/com/zoho/crm/library/common/ZCRMConfigUtil.php b/src/com/zoho/crm/library/common/ZCRMConfigUtil.php index 921ecd81..3f47d791 100644 --- a/src/com/zoho/crm/library/common/ZCRMConfigUtil.php +++ b/src/com/zoho/crm/library/common/ZCRMConfigUtil.php @@ -112,13 +112,13 @@ public static function getAccessToken() { $currentUserEmail= ZCRMRestClient::getCurrentUserEmailID(); - if ($currentUserEmail == null && self::getConfigValue("currentUserEmail") == null) + if ($currentUserEmail == null && \Illuminate\Support\Facades\Config::get('zoho.currentUserEmail') == null) { throw new ZCRMException("Current user should either be set in ZCRMRestClient or in configuration.properties file"); } else if ($currentUserEmail == null) { - $currentUserEmail = self::getConfigValue("currentUserEmail"); + $currentUserEmail = \Illuminate\Support\Facades\Config::get('zoho.currentUserEmail'); } $oAuthCliIns = ZohoOAuth::getClientInstance(); return $oAuthCliIns->getAccessToken($currentUserEmail); diff --git a/src/com/zoho/crm/library/exception/Logger.php b/src/com/zoho/crm/library/exception/Logger.php index f369d841..b101e49c 100644 --- a/src/com/zoho/crm/library/exception/Logger.php +++ b/src/com/zoho/crm/library/exception/Logger.php @@ -4,7 +4,7 @@ class Logger { public static function writeToFile($msg) { - set_include_path(ZCRMConfigUtil::getConfigValue('applicationLogFilePath')); + set_include_path(set_include_path(ZCRMConfigUtil::getConfigValue('applicationLogFilePath'))); $path=get_include_path(); if($path[strlen($path)-1]!='\/') { @@ -19,7 +19,7 @@ public static function writeToFile($msg) fwrite($filePointer,sprintf("%s %s\n",date("Y-m-d H:i:s"),$msg)); fclose($filePointer); } - + public static function warn($msg) { self::writeToFile("WARNING: $msg"); @@ -41,4 +41,4 @@ public static function debug($msg) self::writeToFile("DEBUG: $msg"); } } -?> \ No newline at end of file +?> From 6e75fdb0e92643a44f697ef8149e4b40fd426da9 Mon Sep 17 00:00:00 2001 From: Marc Melchor Date: Thu, 16 Jul 2020 12:23:43 +0200 Subject: [PATCH 10/12] JOBS-870 Set back the Logger log path --- src/com/zoho/crm/library/exception/Logger.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/com/zoho/crm/library/exception/Logger.php b/src/com/zoho/crm/library/exception/Logger.php index b101e49c..af3a8d66 100644 --- a/src/com/zoho/crm/library/exception/Logger.php +++ b/src/com/zoho/crm/library/exception/Logger.php @@ -4,7 +4,7 @@ class Logger { public static function writeToFile($msg) { - set_include_path(set_include_path(ZCRMConfigUtil::getConfigValue('applicationLogFilePath'))); + set_include_path(ZCRMConfigUtil::getConfigValue('applicationLogFilePath')); $path=get_include_path(); if($path[strlen($path)-1]!='\/') { From d0d53d151f8f2c0a53e157f880cdb4c75036cce5 Mon Sep 17 00:00:00 2001 From: Marc Melchor Date: Tue, 21 Jul 2020 14:16:37 +0200 Subject: [PATCH 11/12] JOBS-845 Replace Congif by import --- src/com/zoho/crm/library/common/ZCRMConfigUtil.php | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/src/com/zoho/crm/library/common/ZCRMConfigUtil.php b/src/com/zoho/crm/library/common/ZCRMConfigUtil.php index 3f47d791..00dac5c1 100644 --- a/src/com/zoho/crm/library/common/ZCRMConfigUtil.php +++ b/src/com/zoho/crm/library/common/ZCRMConfigUtil.php @@ -1,4 +1,7 @@ getAccessToken($currentUserEmail); From 045064da05c4c67293412c369854d7b898d09f04 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=BCrgen=20Ratzenb=C3=B6ck?= Date: Mon, 31 Aug 2020 07:45:03 +0200 Subject: [PATCH 12/12] FIX Convert expiry duration to milliseconds before adding to expiry time The expiry time is returned in seconds from the refresh token call but the current timestamp is retrieved in milliseconds. Thus we have to convert the duration first to milliseconds before adding it to the final expiry time. --- src/com/zoho/oauth/client/ZohoOAuthClient.php | 309 ++++++++---------- 1 file changed, 145 insertions(+), 164 deletions(-) diff --git a/src/com/zoho/oauth/client/ZohoOAuthClient.php b/src/com/zoho/oauth/client/ZohoOAuthClient.php index f8a683d4..ed81bddb 100644 --- a/src/com/zoho/oauth/client/ZohoOAuthClient.php +++ b/src/com/zoho/oauth/client/ZohoOAuthClient.php @@ -1,164 +1,142 @@ zohoOAuthParams=$params; - } - public static function getInstance($params) - { - if(self::$zohoOAuthClient == null) - { - self::$zohoOAuthClient = new ZohoOAuthClient($params); - } - return self::$zohoOAuthClient; - } - - public static function getInstanceWithOutParam() - { - return self::$zohoOAuthClient; - } - - public function getAccessToken($userEmailId) - { - $persistence = ZohoOAuth::getPersistenceHandlerInstance(); - $tokens; - try - { - $tokens = $persistence->getOAuthTokens($userEmailId); - } - catch(ZohoOAuthException $ex) - { - OAuthLogger::severe("Exception while retrieving tokens from persistence - ".$ex); - throw $ex; - } - catch(Exception $ex) - { - OAuthLogger::severe("Exception while retrieving tokens from persistence - ".$ex); - throw new ZohoOAuthException($ex); - } - try - { - return $tokens->getAccessToken(); - } - catch(ZohoOAuthException $ex) - { - OAuthLogger::info("Access Token has expired. Hence refreshing."); - $tokens = self::refreshAccessToken($tokens->getRefreshToken(),$userEmailId); - return $tokens->getAccessToken(); - } - } - - public function generateAccessToken($grantToken) - { - if($grantToken == null) - { - throw new ZohoOAuthException("Grant Token is not provided."); - } - try - { - $conn = self::getZohoConnector(ZohoOAuth::getTokenURL()); - $conn->addParam(ZohoOAuthConstants::GRANT_TYPE, ZohoOAuthConstants::GRANT_TYPE_AUTH_CODE); - $conn->addParam(ZohoOAuthConstants::CODE, $grantToken); - $resp = $conn->post(); - $responseJSON=self::processResponse($resp); - if(array_key_exists(ZohoOAuthConstants::ACCESS_TOKEN,$responseJSON)) - { - $tokens = self::getTokensFromJSON($responseJSON); - $tokens->setUserEmailId(self::getUserEmailIdFromIAM($tokens->getAccessToken())); - ZohoOAuth::getPersistenceHandlerInstance()->saveOAuthData($tokens); - return $tokens; - } - else - { - throw new ZohoOAuthException("Exception while fetching access token from grant token - " .$resp); - } - } - catch (ZohoOAuthException $ex) - { - throw new ZohoOAuthException($ex); - } - } - - public function generateAccessTokenFromRefreshToken($refreshToken,$userEmailId) - { - self::refreshAccessToken($refreshToken,$userEmailId); - } - public function refreshAccessToken($refreshToken,$userEmailId) - { - if($refreshToken == null) - { - throw new ZohoOAuthException("Refresh token is not provided."); - } - try - { - $conn = self::getZohoConnector(ZohoOAuth::getRefreshTokenURL()); - $conn->addParam(ZohoOAuthConstants::GRANT_TYPE, ZohoOAuthConstants::GRANT_TYPE_REFRESH); - $conn->addParam(ZohoOAuthConstants::REFRESH_TOKEN, $refreshToken); - $response = $conn->post(); - $responseJSON=self::processResponse($response); - if (array_key_exists(ZohoOAuthConstants::ACCESS_TOKEN,$responseJSON)) - { - $tokens = self::getTokensFromJSON($responseJSON); - $tokens->setRefreshToken($refreshToken); - $tokens->setUserEmailId($userEmailId); - ZohoOAuth::getPersistenceHandlerInstance()->saveOAuthData($tokens); - return $tokens; - } - else - { - throw new ZohoOAuthException("Exception while fetching access token from refresh token - " . $response); - } - } - catch (ZohoOAuthException $ex) - { - throw new ZohoOAuthException($ex); - } - } - - private function getZohoConnector($url) - { - $zohoHttpCon = new ZohoOAuthHTTPConnector(); - $zohoHttpCon->setUrl($url); - $zohoHttpCon->addParam(ZohoOAuthConstants::CLIENT_ID, $this->zohoOAuthParams->getClientId()); - $zohoHttpCon->addParam(ZohoOAuthConstants::CLIENT_SECRET, $this->zohoOAuthParams->getClientSecret()); - $zohoHttpCon->addParam(ZohoOAuthConstants::REDIRECT_URL, $this->zohoOAuthParams->getRedirectURL()); - return $zohoHttpCon; - } - - private function getTokensFromJSON($responseObj) - { - $oAuthTokens = new ZohoOAuthTokens(); - $expiresIn = $responseObj[ZohoOAuthConstants::EXPIRES_IN]; - $oAuthTokens->setExpiryTime($oAuthTokens->getCurrentTimeInMillis()+$expiresIn); - - $accessToken = $responseObj[ZohoOAuthConstants::ACCESS_TOKEN]; - $oAuthTokens->setAccessToken($accessToken); - if (array_key_exists(ZohoOAuthConstants::REFRESH_TOKEN,$responseObj)) - { - $refreshToken = $responseObj[ZohoOAuthConstants::REFRESH_TOKEN]; - $oAuthTokens->setRefreshToken($refreshToken); - } - return $oAuthTokens; - } - - + private $zohoOAuthParams; + private static $zohoOAuthClient; + + private function __construct($params) + { + $this->zohoOAuthParams = $params; + } + + public static function getInstance($params) + { + if (self::$zohoOAuthClient == null) { + self::$zohoOAuthClient = new ZohoOAuthClient($params); + } + return self::$zohoOAuthClient; + } + + public static function getInstanceWithOutParam() + { + return self::$zohoOAuthClient; + } + + public function getAccessToken($userEmailId) + { + $persistence = ZohoOAuth::getPersistenceHandlerInstance(); + $tokens; + try { + $tokens = $persistence->getOAuthTokens($userEmailId); + } catch (ZohoOAuthException $ex) { + OAuthLogger::severe("Exception while retrieving tokens from persistence - " . $ex); + throw $ex; + } catch (Exception $ex) { + OAuthLogger::severe("Exception while retrieving tokens from persistence - " . $ex); + throw new ZohoOAuthException($ex); + } + try { + return $tokens->getAccessToken(); + } catch (ZohoOAuthException $ex) { + OAuthLogger::info("Access Token has expired. Hence refreshing."); + $tokens = self::refreshAccessToken($tokens->getRefreshToken(), $userEmailId); + return $tokens->getAccessToken(); + } + } + + public function generateAccessToken($grantToken) + { + if ($grantToken == null) { + throw new ZohoOAuthException("Grant Token is not provided."); + } + try { + $conn = self::getZohoConnector(ZohoOAuth::getTokenURL()); + $conn->addParam(ZohoOAuthConstants::GRANT_TYPE, ZohoOAuthConstants::GRANT_TYPE_AUTH_CODE); + $conn->addParam(ZohoOAuthConstants::CODE, $grantToken); + $resp = $conn->post(); + $responseJSON = self::processResponse($resp); + if (array_key_exists(ZohoOAuthConstants::ACCESS_TOKEN, $responseJSON)) { + $tokens = self::getTokensFromJSON($responseJSON); + $tokens->setUserEmailId(self::getUserEmailIdFromIAM($tokens->getAccessToken())); + ZohoOAuth::getPersistenceHandlerInstance()->saveOAuthData($tokens); + return $tokens; + } else { + throw new ZohoOAuthException("Exception while fetching access token from grant token - " . $resp); + } + } catch (ZohoOAuthException $ex) { + throw new ZohoOAuthException($ex); + } + } + + public function generateAccessTokenFromRefreshToken($refreshToken, $userEmailId) + { + self::refreshAccessToken($refreshToken, $userEmailId); + } + + public function refreshAccessToken($refreshToken, $userEmailId) + { + if ($refreshToken == null) { + throw new ZohoOAuthException("Refresh token is not provided."); + } + try { + $conn = self::getZohoConnector(ZohoOAuth::getRefreshTokenURL()); + $conn->addParam(ZohoOAuthConstants::GRANT_TYPE, ZohoOAuthConstants::GRANT_TYPE_REFRESH); + $conn->addParam(ZohoOAuthConstants::REFRESH_TOKEN, $refreshToken); + $response = $conn->post(); + $responseJSON = self::processResponse($response); + if (array_key_exists(ZohoOAuthConstants::ACCESS_TOKEN, $responseJSON)) { + $tokens = self::getTokensFromJSON($responseJSON); + $tokens->setRefreshToken($refreshToken); + $tokens->setUserEmailId($userEmailId); + ZohoOAuth::getPersistenceHandlerInstance()->saveOAuthData($tokens); + return $tokens; + } else { + throw new ZohoOAuthException("Exception while fetching access token from refresh token - " . $response); + } + } catch (ZohoOAuthException $ex) { + throw new ZohoOAuthException($ex); + } + } + + private function getZohoConnector($url) + { + $zohoHttpCon = new ZohoOAuthHTTPConnector(); + $zohoHttpCon->setUrl($url); + $zohoHttpCon->addParam(ZohoOAuthConstants::CLIENT_ID, $this->zohoOAuthParams->getClientId()); + $zohoHttpCon->addParam(ZohoOAuthConstants::CLIENT_SECRET, $this->zohoOAuthParams->getClientSecret()); + $zohoHttpCon->addParam(ZohoOAuthConstants::REDIRECT_URL, $this->zohoOAuthParams->getRedirectURL()); + return $zohoHttpCon; + } + + private function getTokensFromJSON($responseObj) + { + $oAuthTokens = new ZohoOAuthTokens(); + $expiresIn = $responseObj[ZohoOAuthConstants::EXPIRES_IN]; + $oAuthTokens->setExpiryTime($oAuthTokens->getCurrentTimeInMillis() + $expiresIn * 1000); + + $accessToken = $responseObj[ZohoOAuthConstants::ACCESS_TOKEN]; + $oAuthTokens->setAccessToken($accessToken); + if (array_key_exists(ZohoOAuthConstants::REFRESH_TOKEN, $responseObj)) { + $refreshToken = $responseObj[ZohoOAuthConstants::REFRESH_TOKEN]; + $oAuthTokens->setRefreshToken($refreshToken); + } + return $oAuthTokens; + } + /** * zohoOAuthParams * @return unkown */ - public function getZohoOAuthParams(){ + public function getZohoOAuthParams() + { return $this->zohoOAuthParams; } @@ -166,27 +144,30 @@ public function getZohoOAuthParams(){ * zohoOAuthParams * @param unkown $zohoOAuthParams */ - public function setZohoOAuthParams($zohoOAuthParams){ + public function setZohoOAuthParams($zohoOAuthParams) + { $this->zohoOAuthParams = $zohoOAuthParams; } - + public function getUserEmailIdFromIAM($accessToken) { - $connector = new ZohoOAuthHTTPConnector(); - $connector->setUrl(ZohoOAuth::getUserInfoURL()); - $connector->addHeadder(ZohoOAuthConstants::AUTHORIZATION, ZohoOAuthConstants::OAUTH_HEADER_PREFIX.$accessToken); - $apiResponse=$connector->get(); - $jsonResponse=self::processResponse($apiResponse); - - return $jsonResponse['Email']; + $connector = new ZohoOAuthHTTPConnector(); + $connector->setUrl(ZohoOAuth::getUserInfoURL()); + $connector->addHeadder(ZohoOAuthConstants::AUTHORIZATION, ZohoOAuthConstants::OAUTH_HEADER_PREFIX . $accessToken); + $apiResponse = $connector->get(); + $jsonResponse = self::processResponse($apiResponse); + + return $jsonResponse['Email']; } + public function processResponse($apiResponse) { - list($headers, $content) = explode("\r\n\r\n",$apiResponse,2); - $jsonResponse=json_decode($content,true); - - return $jsonResponse; + list($headers, $content) = explode("\r\n\r\n", $apiResponse, 2); + $jsonResponse = json_decode($content, true); + + return $jsonResponse; } - + } + ?> \ No newline at end of file