* @license MIT https://opensource.org/licenses/MIT * @version GIT: 0.0.1 * @link / */ namespace LDCCRM; use Exception; // phpcs:ignore Squiz.PHP.CommentedOutCode.Found // 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 * 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') { // phpcs:ignore Squiz.PHP.DiscouragedFunctions.Found 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') { // phpcs:ignore Squiz.PHP.DiscouragedFunctions.Found 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 getUserFromTable($crm_id) { return self::getWpDb()->get_row( 'SELECT * FROM `ldc_wp_customers` WHERE `crm_id` = ' . $crm_id ); } /** * Get a customer from table by an email * * @param int $email The customer email * * @return object|null */ public static function getUserFromTableByEmail($email) { return self::getWpDb()->get_row( 'SELECT * FROM `ldc_wp_customers` WHERE `email` = "' . $email . '"' ); } /** * Get a customer from table * * @return object|null */ public static function getUserToTable() { 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::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() { // phpcs:ignore Squiz.PHP.GlobalKeyword.NotAllowed global $wpdb; return $wpdb; } }