From 08da3674d33034f77d2bfac0f1c2e66767cd126f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=A9r=C3=A9my=20Munsch?= Date: Thu, 22 Apr 2021 16:03:22 +0200 Subject: [PATCH] Add WPCrm for WordPress (beurk !) --- clients/WPCrm.php | 323 ++++++++++++++++++++++++++++++++++++++++++ clients/WPCrmUser.php | 148 +++++++++++++++++++ 2 files changed, 471 insertions(+) create mode 100644 clients/WPCrm.php create mode 100644 clients/WPCrmUser.php diff --git a/clients/WPCrm.php b/clients/WPCrm.php new file mode 100644 index 0000000..883432c --- /dev/null +++ b/clients/WPCrm.php @@ -0,0 +1,323 @@ + + * @license MIT https://opensource.org/licenses/MIT + * @version GIT: 0.0.1 + * @link / + */ + +namespace LDCCRM; + +use Exception; + +// TABLE LDC CUSTOMERS +// CREATE TABLE `ldc_wp_customers` ( +// `crm_id` BIGINT NOT NULL COMMENT 'Le CRM ID', +// `hashcode` VARCHAR(36) NOT NULL DEFAULT '' COMMENT 'Le hashcode (UUID)', +// `email` VARCHAR(255) NOT NULL DEFAULT '' COMMENT 'Le customer email', +// PRIMARY KEY (`crm_id`), +// UNIQUE INDEX `hashcode` (`hashcode`) +// ) +// COMMENT='Les customers sur un WP liées à la CRM' +// COLLATE='utf8mb4_unicode_ci'; + +/** + * Class de gestion des users en session avec Wordpress (ce truc immonde) + * Compatible avec php5 + * + * @category API + * @package None + * @author Jérémy Munsch + * @license MIT https://opensource.org/licenses/MIT + * @link / + */ +class WPCrm extends ApiV1 +{ + + private static $_sessionKey = 'LDC_CRM_USER'; + + private static $_sessionDestroyed = false; + + /** + * The user object + * + * @var \LDCCRM\ApiV1 + */ + protected static $api = null; + + /** + * The user object + * + * @var \LDCCRM\WPCrmUser + */ + protected static $user = null; + + /** + * Try to login with CRM API + * return api response code if an error occurs + * + * @param string $email The customer email + * @param string $password The customer password + * + * @return \LDCCRM\WPCrmUser|int + */ + public static function login($email, $password) + { + self::_bootSessionIfNeeded(); + return self::_loginUserWithApi($email, $password); + } + + /** + * Get the current user + * return null if the user is not logged in + * + * @return \LDCCRM\WPCrmUser|null + */ + public static function getUser() + { + self::_bootSessionIfNeeded(); + return self::$user; + } + + /** + * Get the current user + * return api response code if an error occurs + * + * @param string $email The customer email + * + * @return \LDCCRM\WPCrmUser|int + */ + public static function getUserFromApi($email) + { + self::_initLDCApi(); + /** + * Object response + * + * @var object + */ + $response = self::$api->getCustomerByEmail($email); + if ($response->status === 'KO') { + error_log( + sprintf( + 'LDC CRM: returned KO from CRM => %s', + $response->message + ) + ); + return $response->code; + } + self::_setUser( + $response->user->crm_id, + $response->user->hashcode, + $response->user->email, + $response + ); + return self::$user; + } + + /** + * Get the current user + * return null if the user is not logged in + * + * @param string $email The customer email + * @param string $password The customer password + * + * @return \LDCCRM\WPCrmUser|int + */ + private static function _loginUserWithApi($email, $password) + { + self::_initLDCApi(); + /** + * Object response + * + * @var object + */ + $response = self::$api->loginCustomer($email, $password); + if ($response->status === 'KO') { + error_log( + sprintf( + 'LDC CRM: returned KO from CRM => %s', + $response->message + ) + ); + return $response->code; + } + self::_setUser( + $response->user->crm_id, + $response->user->hashcode, + $response->user->email, + $response + ); + self::_saveOrUpdateUserToTable(); + return self::$user; + } + + /** + * Destroy the customer from session + * and therefore logout + * + * @return void + */ + public static function logout() + { + self::_bootSessionIfNeeded(); + unset($_SESSION[self::$_sessionKey]); + session_destroy(); + self::$_sessionDestroyed = true; + } + + /** + * Check if the user is Authenticated + * + * @return bool + */ + public static function check() + { + self::_bootSessionIfNeeded(); + return (bool) self::getUser(); + } + + /** + * Create a user + * stores it to the session + * and finally saves it to the database if it does not exists + * + * @param int $crm_id The crm id + * @param string $hashcode The customer hashcode (UUID) + * @param string $email The customer email + * @param object $response The crm API response + * + * @return void + */ + private static function _setUser($crm_id, $hashcode, $email, $response) + { + self::_bootSessionIfNeeded(); + if (!self::$user) { + self::$user = new WPCrmUser($crm_id, $hashcode, $email); + } + self::$user->setInfo($response->user); + $_SESSION[self::$_sessionKey] = json_encode(self::$user); + } + + /** + * Get the initialized API object + * + * @return \LDCCRM\ApiV1 + */ + private static function _initLDCApi() + { + if (!self::$api) { + if (!extension_loaded('curl')) { + throw new Exception( + 'LDC CRM require php extension curl' + ); + } + $endpoint = getenv('CRM_ENDPOINT'); + $api_key = getenv('CRM_API_TOKEN'); + if ($endpoint === false or $api_key === false) { + throw new Exception( + 'LDC CRM require .env to have CRM_ENDPOINT and CRM_API_TOKEN' + ); + } + self::$api = new ApiV1($endpoint, $api_key); + } + return self::$api; + } + + /** + * Boot the php session if needed + * + * @return void + */ + private static function _bootSessionIfNeeded() + { + if (!session_id() && !self::$_sessionDestroyed) { + session_start(); + } + if (!self::$user and array_key_exists(self::$_sessionKey, $_SESSION)) { + /** + * The user object + * + * @var \LDCCRM\WPCrmUser + */ + self::$user = WPCrmUser::parseFromJson( + $_SESSION[self::$_sessionKey] ?? null + ); + } + } + + /** + * Get a customer from table + * + * @param int $crm_id The customer crm id + * + * @return object|null + */ + public static function getUserToTable($crm_id) + { + return self::_getWpDB()->get_row( + 'SELECT * FROM `ldc_wp_customers` WHERE `crm_id` = ' . + self::$user->crm_id + ); + } + + /** + * Save or update the user to the table + * + * @return void + */ + private static function _saveOrUpdateUserToTable() + { + if (self::getUserToTable(self::$user->crm_id)) { + self::_query( + 'UPDATE `ldc_wp_customers` SET `hashcode` = %d, `email` = %d' . + ' WHERE `crm_id` = %d', + [ + 'crm_id' => self::$user->crm_id, + 'hashcode' => self::$user->hashcode, + 'email' => self::$user->email, + ] + ); + } else { + self::_query( + 'INSERT INTO `ldc_wp_customers` VALUES (%d, %s, %s)', + [ + 'crm_id' => self::$user->crm_id, + 'hashcode' => self::$user->hashcode, + 'email' => self::$user->email, + ] + ); + } + } + + /** + * Query in DB + * + * @param string $query La request avec les variables en points d'interrogation + * @param array $params Les paramètres des la requète + * + * @return object Containing the row columns + */ + private static function _query($query, array $params = []) + { + return self::_getWpDB()->query( + self::_getWpDB()->prepare($query, $params) + ); + } + + /** + * Get WP 'pdo instance' + * + * @return object The $wpdb variable + */ + private static function _getWpDB() + { + global $wpdb; + return $wpdb; + } +} diff --git a/clients/WPCrmUser.php b/clients/WPCrmUser.php new file mode 100644 index 0000000..f2e2f73 --- /dev/null +++ b/clients/WPCrmUser.php @@ -0,0 +1,148 @@ + + * @license MIT https://opensource.org/licenses/MIT + * @version GIT: 0.0.1 + * @link / + */ + +namespace LDCCRM; + +use Exception; +use JsonSerializable; + +/** + * Class de gestion des users en session avec Wordpress (ce truc immonde) + * Compatible avec php5 + * + * @category API + * @package None + * @author Jérémy Munsch + * @license MIT https://opensource.org/licenses/MIT + * @link / + */ +class WPCrmUser implements JsonSerializable +{ + /** + * The CRM ID + * + * @var int + */ + protected $crm_id = null; + + /** + * The CRM hashcode (UUID) + * + * @var string + */ + protected $hashcode = null; + + /** + * The CRM customer email + * + * @var string + */ + protected $email = null; + + /** + * The CRM customer info (the api response) + * + * @var object + */ + protected $info = null; + + /** + * WPCrmUser construct + * + * @param int $crm_id The crm id + * @param string $hashcode The customer hashcode (UUID) + * @param string $email The customer email + */ + public function __construct($crm_id, $hashcode, $email) + { + $this->crm_id = $crm_id; + $this->hashcode = $hashcode; + $this->email = $email; + } + + /** + * Magic getter + * + * @param string $prop The prop to get + * + * @return int|string + */ + public function __get($prop) + { + if (is_null($this->info)) { + /** + * Object response + * + * @var object + */ + WPCrm::getUserFromApi($this->email); + } + if (!array_key_exists($prop, (array)$this->info)) { + throw new Exception('This value does not exists'); + } + return $this->info->{$prop}; + } + + /** + * Set the customer info + * with api response + * + * @param object $info The Api object reponse (user) + * + * @return void + */ + public function setInfo($info) + { + if (is_null($info) or is_null($info->email)) { + throw new Exception('Info cannot be null'); + } + $this->info = $info; + $this->crm_id = $info->crm_id; + $this->email = $info->email; + $this->hashcode = $info->hashcode; + } + + /** + * Generate a user from session data + * + * @param string $string The json data stored in session + * + * @return \LDCCRM\WPCrmUser + */ + public static function parseFromJson($string) + { + $a = json_decode($string, true); + return new self( + $a['crm_id'], + $a['hashcode'], + $a['email'], + $a['info'] + ); + } + + /** + * Serialize this object to an array + * + * @return array + */ + public function jsonSerialize() + { + return [ + 'crm_id' => $this->crm_id, + 'hashcode' => $this->hashcode, + 'email' => $this->email, + 'info' => $this->info + ]; + } +}