public function execute(\Magento\Framework\Event\Observer $observer)
 {
     $customer = $observer->getEvent()->getCustomerDataObject();
     $activationHelper = $this->_objectManager->get('LoginRadius\\Activation\\Model\\Helper\\Data');
     $customerRegistrationHelper = $this->_objectManager->get("LoginRadius" . "\\" . $activationHelper->getAuthDirectory() . "\\Model\\Helper\\Data");
     if ($customerRegistrationHelper->enableRaas() != '1') {
         return;
     }
     $customerSession = $this->_objectManager->get('Magento\\Customer\\Model\\Session');
     $editUserData = array('firstname' => $customer->getFirstname(), 'lastname' => $customer->getLastname(), 'emailid' => $customer->getEmail(), 'gender' => $customer->getGender(), 'birthdate' => $customer->getDob());
     $userAPI = new \LoginRadiusSDK\CustomerRegistration\UserAPI($activationHelper->siteApiKey(), $activationHelper->siteApiSecret(), array('authentication' => true, 'output_format' => 'json'));
     try {
         $userEditdata = $userAPI->edit($customerSession->getLoginRadiusId(), $editUserData);
         /* Edit profile in local db */
     } catch (\LoginRadiusSDK\LoginRadiusException $e) {
         if ($customerRegistrationHelper->debug() == '1') {
             $errorDescription = isset($e->getErrorResponse()->description) ? $e->getErrorResponse()->description : '';
             $this->_messageManager->addError($errorDescription);
         }
     }
     if (isset($_REQUEST['changepassword']) && $_REQUEST['changepassword'] == '1') {
         $accountAPI = new \LoginRadiusSDK\CustomerRegistration\AccountAPI($activationHelper->siteApiKey(), $activationHelper->siteApiSecret(), array('authentication' => true, 'output_format' => 'json'));
         $postData = $_REQUEST;
         if (isset($postData['emailid']) && !empty($postData['emailid'])) {
             if ($customerRegistrationHelper->minPassword() != 0 && $customerRegistrationHelper->minPassword() > strlen($postData['password'])) {
                 $this->_messageManager->addError('The Password field must be at least ' . $customerRegistrationHelper->minPassword() . ' characters in length.');
             } elseif ($customerRegistrationHelper->maxPassword() != 0 && strlen($postData['password']) > $customerRegistrationHelper->maxPassword()) {
                 $this->_messageManager->addError('The Password field must not exceed ' . $customerRegistrationHelper->maxPassword() . ' characters in length.');
             } elseif ($postData['password'] === $postData['confirmpassword']) {
                 //check both password
                 //setpassword
                 $data = array('accountid' => $customerSession->getLoginRadiusUid(), 'password' => trim($postData['password']), 'emailid' => trim($postData['emailid']));
                 try {
                     $setUserPassword = $accountAPI->createUserRegistrationProfile($data);
                 } catch (\LoginRadiusSDK\LoginRadiusException $e) {
                     $errorDescription = isset($e->getErrorResponse()->description) ? $e->getErrorResponse()->description : '';
                     $this->_messageManager->addError($errorDescription);
                 }
             } else {
                 //password not match
                 $this->_messageManager->addError('Password don\'t match');
             }
         } else {
             if (isset($postData['oldpassword']) && isset($postData['newpassword']) && isset($postData['confirmnewpassword'])) {
                 if ($customerRegistrationHelper->minPassword() != 0 && $customerRegistrationHelper->minPassword() > strlen($postData['newpassword'])) {
                     $this->_messageManager->addError('The Password field must be at least ' . $customerRegistrationHelper->minPassword() . ' characters in length.');
                 } elseif ($customerRegistrationHelper->maxPassword() != 0 && strlen($postData['newpassword']) > $customerRegistrationHelper->maxPassword()) {
                     $this->_messageManager->addError('The Password field must not exceed ' . $customerRegistrationHelper->maxPassword() . ' characters in length.');
                 } elseif ($postData['newpassword'] !== $postData['confirmnewpassword']) {
                     //password not match
                     $this->_messageManager->addError('Password and Confirm Password don\'t match');
                 } else {
                     try {
                         $changeUserPassword = $accountAPI->changeAccountPassword($customerSession->getLoginRadiusUid(), $postData['oldpassword'], $postData['newpassword']);
                     } catch (\LoginRadiusSDK\LoginRadiusException $e) {
                         $errorDescription = isset($e->getErrorResponse()->description) ? $e->getErrorResponse()->description : '';
                         $this->_messageManager->addError($errorDescription);
                     }
                 }
             }
         }
     }
 }
 public function customer_save_before($observer)
 {
     require_once Mage::getModuleDir('', 'Loginradius_Sociallogin') . DS . 'Helper' . DS . 'SDKClient.php';
     global $apiClient_class;
     $apiClient_class = 'Loginradius_Sociallogin_Helper_SDKClient';
     $activationBlockObj = Mage::getBlockSingleton('activation/activation');
     $userApi = new LoginRadiusSDK\CustomerRegistration\UserAPI($activationBlockObj->apiKey(), $activationBlockObj->apiSecret(), array('output_format' => 'json'));
     if (Mage::app()->getFrontController()->getRequest()->getRouteName() == "checkout" && !Mage::getSingleton('customer/session')->isLoggedIn()) {
         $customer = $observer->getCustomer();
         $address = $observer->getCustomerAddress();
         $modified = $this->loginradius_get_customer_saved_data($customer, $address);
         if (isset($modified['EmailId']) && !empty($modified['EmailId'])) {
             $response = $userApi->create($modified);
             if (isset($response->description)) {
                 Mage::throwException($response->description);
             } else {
                 $_POST['lr_raas_resonse'] = $response;
             }
             return;
         }
     }
     $socialId = Mage::getSingleton("customer/session")->getloginRadiusId();
     $postData = Mage::app()->getRequest()->getPost();
     if (isset($postData['email'])) {
         $customer = Mage::getSingleton("customer/session")->getCustomer();
         if (isset($postData['email']) && $postData['email'] == $customer->email) {
             //customer basic info object
             $modified = array();
             //customer basic info
             $modified['firstname'] = isset($postData['firstname']) ? $postData['firstname'] : $customer->firstname;
             //firstname
             $modified['lastname'] = isset($postData['lastname']) ? $postData['lastname'] : $customer->lastname;
             //lastname
             $modified['email'] = isset($postData['email']) ? $postData['email'] : $customer->email;
             //email
             $modified['birthdate'] = isset($postData['dob']) ? date('m-d-Y', strtotime($postData['dob'])) : date('m-d-Y', strtotime($customer->dob));
             //dob
             $modified['taxvat'] = isset($postData['taxvat']) ? $postData['taxvat'] : $customer->taxvat;
             //taxvat
             $modified['gender'] = isset($postData['gender']) ? $postData['gender'] : $customer->gender;
             //gender
             if ($modified['gender'] == '1') {
                 $modified['gender'] = 'M';
             } elseif ($modified['gender'] == '0') {
                 $modified['gender'] = 'F';
             } else {
                 $modified['gender'] = 'M';
             }
             $address = $observer->getCustomerAddress();
             if (!isset($address) || empty($address)) {
                 $address = new stdClass();
             }
             $modified['Company'] = $this->checking_post_and_isset('company', $address);
             $modified['street'] = $this->checking_post_and_isset('street', $address);
             $modified['city'] = $this->checking_post_and_isset('city', $address);
             $modified['PostCode'] = $this->checking_post_and_isset('postcode', $address);
             $modified['phonenumber'] = $this->checking_post_and_isset('telephone', $address);
             //change and set password
             if (isset($postData['social_password']) && $postData['social_password'] == 1) {
                 $accountAPI = new LoginRadiusSDK\CustomerRegistration\AccountAPI($activationBlockObj->apiKey(), $activationBlockObj->apiSecret(), array('output_format' => 'json'));
                 $userId = Mage::getSingleton("customer/session")->getId();
                 $loginRadiusConn = Mage::getSingleton('core/resource')->getConnection('core_read');
                 $loginRadiusQuery = "select uid from " . Mage::getSingleton('core/resource')->getTableName('lr_sociallogin') . " where entity_id = '" . $userId . "' LIMIT 1";
                 $loginRadiusQueryHandle = $loginRadiusConn->query($loginRadiusQuery);
                 $loginRadiusResult = $loginRadiusQueryHandle->fetch();
                 if (isset($loginRadiusResult["uid"]) && !empty($loginRadiusResult["uid"])) {
                     //set password
                     $raasSettings = Mage::getBlockSingleton('customerregistration/customerregistration');
                     if (isset($postData['emailid']) && isset($postData['confirmpassword']) && isset($postData['password'])) {
                         if (empty($postData['emailid'])) {
                             Mage::getSingleton('core/session')->addError('Please select Email Address');
                             /* not the best redirect but don`t know how to */
                             $this->_redirectUrl('customer/account/edit');
                         }
                         if ($raasSettings->minPasswordLength() != 0 && $raasSettings->minPasswordLength() > strlen($postData['password'])) {
                             Mage::getSingleton('core/session')->addError('The Password field must be at least ' . $raasSettings->minPasswordLength() . ' characters in length.');
                         } elseif ($raasSettings->maxPasswordLength() != 0 && strlen($postData['password']) > $raasSettings->maxPasswordLength()) {
                             Mage::getSingleton('core/session')->addError('The Password field must not exceed ' . $raasSettings->maxPasswordLength() . ' characters in length.');
                         } elseif ($postData['password'] === $postData['confirmpassword']) {
                             //check both password
                             $data = array('accountid' => trim($loginRadiusResult["uid"]), 'emailid' => trim($postData['emailid']), 'password' => trim($postData['password']));
                             try {
                                 $response = $accountAPI->createUserRegistrationProfile($data);
                                 Mage::getSingleton('core/session')->addSuccess('Password updated successfully.');
                             } catch (LoginRadiusSDK\LoginRadiusException $e) {
                                 Mage::getSingleton('core/session')->addError($e->getErrorResponse()->description);
                             }
                         } else {
                             //password not match
                             Mage::getSingleton('core/session')->addError('Password don\'t match');
                         }
                         $this->_redirectUrl('customer/account/edit');
                     } elseif (isset($postData['newpassword']) && isset($postData['confirmnewpassword'])) {
                         if ($raasSettings->minPasswordLength() != 0 && $raasSettings->minPasswordLength() > strlen($postData['newpassword'])) {
                             Mage::getSingleton('core/session')->addError('The Password field must be at least ' . $raasSettings->minPasswordLength() . ' characters in length.');
                         } elseif ($raasSettings->maxPasswordLength() != 0 && strlen($postData['newpassword']) > $raasSettings->maxPasswordLength()) {
                             Mage::getSingleton('core/session')->addError('The Password field must not exceed ' . $raasSettings->maxPasswordLength() . ' characters in length.');
                         } elseif ($postData['newpassword'] !== $postData['confirmnewpassword']) {
                             //password not match
                             Mage::getSingleton('core/session')->addError('Password and Confirm Password don\'t match');
                         } else {
                             try {
                                 $response = $accountAPI->changeAccountPassword($loginRadiusResult["uid"], $postData['oldpassword'], $postData['newpassword']);
                                 Mage::getSingleton('core/session')->addSuccess('Password updated successfully.');
                             } catch (LoginRadiusSDK\LoginRadiusException $e) {
                                 Mage::getSingleton('core/session')->addError($e->getErrorResponse()->description);
                             }
                         }
                         $this->_redirectUrl('customer/account/edit');
                     }
                 } else {
                     Mage::getSingleton('core/session')->addError('An error occurred');
                     $this->_redirectUrl('customer/account/edit');
                 }
             }
             //update  user at raas
             try {
                 $response = $userApi->edit($socialId, $modified);
             } catch (LoginRadiusSDK\LoginRadiusException $e) {
                 Mage::getSingleton('core/session')->addError($e->getErrorResponse()->description);
                 $this->_redirectUrl('customer/account/edit');
             }
         }
     }
 }
 public function execute(\Magento\Framework\Event\Observer $observer)
 {
     $activationHelper = $this->_objectManager->get('LoginRadius\\Activation\\Model\\Helper\\Data');
     $customerRegistrationHelper = $this->_objectManager->get("LoginRadius" . "\\" . $activationHelper->getAuthDirectory() . "\\Model\\Helper\\Data");
     if ($customerRegistrationHelper->enableRaas() != '1') {
         return;
     }
     $events = $observer->getEvent();
     $customerData = $events->getRequest()->getPostValue();
     $customer = $observer->getEvent()->getCustomer();
     $this->_date = $this->_objectManager->create('Magento\\Framework\\Stdlib\\DateTime');
     $customer->setDob($this->_date->gmDate('m-d-Y', $this->_date->strToTime($customerData['customer']['dob'])));
     if (isset($_POST['customer']['entity_id'])) {
         $editUserData = array('firstname' => $customerData['customer']['firstname'], 'lastname' => $customerData['customer']['lastname'], 'birthdate' => $customer->getDob());
         $resource = $this->_objectManager->get('Magento\\Framework\\App\\ResourceConnection');
         $ruleTable = $resource->getTableName('lr_sociallogin');
         $connection = $resource->getConnection();
         $select = $connection->select()->from(['r' => $ruleTable])->where('entity_id=?', $customerData['customer']['entity_id']);
         $output = $connection->fetchAll($select);
         $userAPI = new \LoginRadiusSDK\CustomerRegistration\UserAPI($activationHelper->siteApiKey(), $activationHelper->siteApiSecret(), array('authentication' => true, 'output_format' => 'json'));
         $accountApi = new \LoginRadiusSDK\CustomerRegistration\AccountAPI($activationHelper->siteApiKey(), $activationHelper->siteApiSecret(), array('authentication' => true, 'output_format' => 'json'));
         /* Getting Raas Profile By User Profile by UID Api */
         $getRaasProfileEmailByUid = $accountApi->getAccounts($output[0]['uid']);
         $checkProvider = '';
         foreach ($getRaasProfileEmailByUid as $key => $value) {
             if ($getRaasProfileEmailByUid[$key]->Provider == 'RAAS') {
                 $emailRaas = $getRaasProfileEmailByUid[$key]->Email[0]->Value;
                 $checkProvider = 'true';
             }
         }
         if ($checkProvider == 'true') {
             if ($customerData['customer']['email'] != $emailRaas) {
                 /* Adding New Email by Add/Remove Email Api */
                 $addEmailData = array('EmailId' => $customerData['customer']['email'], 'EmailType' => 'Primary');
                 try {
                     $addEmailRaas = $accountApi->userAdditionalEmail($output[0]['uid'], 'add', $addEmailData);
                 } catch (\LoginRadiusSDK\LoginRadiusException $e) {
                     /* Getting Raas Profile By User Profile by UID Api */
                     $getRaasProfileByUid = $accountApi->getAccounts($output[0]['uid']);
                     $providerStatus = '';
                     foreach ($getRaasProfileByUid as $key => $value) {
                         if ($getRaasProfileByUid[$key]->Provider == 'RAAS') {
                             $providerStatus = 'true';
                         }
                     }
                     if ($providerStatus == 'true') {
                         $getRaasProfile = $userAPI->getProfileByID($output[0]['sociallogin_id']);
                         /* Updating email in local database */
                         $resource = $this->_objectManager->get('Magento\\Framework\\App\\ResourceConnection');
                         $updateRuleTable = $resource->getTableName('customer_entity');
                         $updateGridTable = $resource->getTableName('customer_grid_flat');
                         $updateConnection = $resource->getConnection();
                         $data = array("email" => $getRaasProfile->Email[0]->Value);
                         $updateConnection->update($updateRuleTable, $data, "entity_id ='" . $output[0]['entity_id'] . "'");
                         $updateConnection->update($updateGridTable, $data, "entity_id ='" . $output[0]['entity_id'] . "'");
                         $errorDescription = isset($e->getErrorResponse()->description) ? $e->getErrorResponse()->description : '';
                         $this->_messageManager->addError($errorDescription);
                     } else {
                         $getRaasProfile = $userAPI->getProfileByID($output[0]['sociallogin_id']);
                         /* Updating email in local database */
                         $resource = $this->_objectManager->get('Magento\\Framework\\App\\ResourceConnection');
                         $updateRuleTable = $resource->getTableName('customer_entity');
                         $updateGridTable = $resource->getTableName('customer_grid_flat');
                         $updateConnection = $resource->getConnection();
                         $data = array("email" => $getRaasProfile->Email[0]->Value);
                         $updateConnection->update($updateRuleTable, $data, "entity_id ='" . $output[0]['entity_id'] . "'");
                         $updateConnection->update($updateGridTable, $data, "entity_id ='" . $output[0]['entity_id'] . "'");
                         $errorDescription = isset($e->getErrorResponse()->description) ? $e->getErrorResponse()->description : '';
                         $this->_messageManager->addError('Please Reset Set Password then change the email id.');
                     }
                 }
                 if (isset($addEmailRaas->isPosted) && $addEmailRaas->isPosted == 'true') {
                     // $getRaasProfile = $userAPI->getProfileByID($output[0]['sociallogin_id']);
                     $getRaasProfileUid = $accountApi->getAccounts($output[0]['uid']);
                     foreach ($getRaasProfileUid as $key => $value) {
                         if ($getRaasProfileUid[$key]->Provider == 'RAAS') {
                             $raasEmail = $getRaasProfileUid[$key]->Email[0]->Value;
                         }
                     }
                     /* Removing Old Email by Add/Remove Email Api */
                     $removeEmailData = array('EmailId' => $raasEmail, 'EmailType' => 'Primary');
                     try {
                         $removeEmail = $accountApi->userAdditionalEmail($output[0]['uid'], 'remove', $removeEmailData);
                         try {
                             $getUserDataByEmail = $userAPI->getProfileByEmail($customerData['customer']['email']);
                             try {
                                 $userEditdata = $userAPI->edit($getUserDataByEmail[0]->ID, $editUserData);
                             } catch (\LoginRadiusSDK\LoginRadiusException $e) {
                                 $errorDescription = isset($e->getErrorResponse()->description) ? $e->getErrorResponse()->description : '';
                                 $this->_messageManager->addError($errorDescription);
                             }
                         } catch (\LoginRadiusSDK\LoginRadiusException $e) {
                         }
                     } catch (\LoginRadiusSDK\LoginRadiusException $e) {
                         $errorDescription = isset($e->getErrorResponse()->description) ? $e->getErrorResponse()->description : '';
                         $this->_messageManager->addError($errorDescription);
                     }
                 }
             } else {
                 try {
                     $getUserDataByEmail = $userAPI->getProfileByEmail($customerData['customer']['email']);
                     try {
                         $userEditdata = $userAPI->edit($getUserDataByEmail[0]->ID, $editUserData);
                     } catch (\LoginRadiusSDK\LoginRadiusException $e) {
                         $errorDescription = isset($e->getErrorResponse()->description) ? $e->getErrorResponse()->description : '';
                         $this->_messageManager->addError($errorDescription);
                     }
                 } catch (\LoginRadiusSDK\LoginRadiusException $e) {
                 }
             }
         } else {
             try {
                 $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#\$%^&*()_-=?";
                 $data = array('accountid' => $output[0]['uid'], 'emailid' => $customerData['customer']['email'], 'password' => substr(str_shuffle($chars), 0, 8));
                 $accountApi->createUserRegistrationProfile($data);
                 /* Updating Basic profile */
                 try {
                     $getUserDataByEmail = $userAPI->getProfileByEmail($customerData['customer']['email']);
                     try {
                         $userEditdata = $userAPI->edit($getUserDataByEmail[0]->ID, $editUserData);
                     } catch (\LoginRadiusSDK\LoginRadiusException $e) {
                         $errorDescription = isset($e->getErrorResponse()->description) ? $e->getErrorResponse()->description : '';
                         $this->_messageManager->addError($errorDescription);
                     }
                 } catch (\LoginRadiusSDK\LoginRadiusException $e) {
                     $errorDescription = isset($e->getErrorResponse()->description) ? $e->getErrorResponse()->description : '';
                     $this->_messageManager->addError($errorDescription);
                 }
             } catch (\LoginRadiusSDK\LoginRadiusException $e) {
                 $getRaasProfile = $userAPI->getProfileByID($output[0]['sociallogin_id']);
                 /* Updating email in local database */
                 $resource = $this->_objectManager->get('Magento\\Framework\\App\\ResourceConnection');
                 $updateRuleTable = $resource->getTableName('customer_entity');
                 $updateGridTable = $resource->getTableName('customer_grid_flat');
                 $updateConnection = $resource->getConnection();
                 $data = array("email" => $getRaasProfile->Email[0]->Value);
                 $updateConnection->update($updateRuleTable, $data, "entity_id ='" . $output[0]['entity_id'] . "'");
                 $updateConnection->update($updateGridTable, $data, "entity_id ='" . $output[0]['entity_id'] . "'");
                 //$errorDescription = isset($e->getErrorResponse()->description) ? $e->getErrorResponse()->description : '';
                 $this->_messageManager->addError('Not able to change the email of social user.');
             }
             return;
         }
     }
 }