/**
     * @see FrontController::initContent()
     */
    public function initContent()
    {
        parent::initContent();
        if ($this->context->customer->isLogged()) {
            Tools::redirect('index.php?controller=my-account');
        }
        $fb_connect_appid = Configuration::get('FB_CONNECT_APPID');
        $fb_connect_appkey = Configuration::get('FB_CONNECT_APPKEY');
        $this->redirect_uri = $this->context->link->getModuleLink('fbconnect_psb', 'registration', array('done' => 1), TRUE, $this->context->language->id);
        require_once _PS_ROOT_DIR_ . '/modules/fbconnect_psb/fb_sdk/facebook.php';
        $facebook = new Facebook(array('appId' => $fb_connect_appid, 'secret' => $fb_connect_appkey));
        // Get User ID
        $user = $facebook->getUser();
        // We may or may not have this data based on whether the user is logged in.
        //
        // If we have a $user id here, it means we know the user is logged into
        // Facebook, but we don't know if the access token is valid. An access
        // token is invalid if the user logged out of Facebook.
        if ($user) {
            try {
                // Proceed knowing you have a logged in user who's authenticated.
                $fb_user_profile = $facebook->api('/me');
            } catch (FacebookApiException $e) {
                //die('Error: '.$e);
                error_log($e);
                $user = null;
            }
        } else {
            // Get new Access tokens
            Tools::redirect($facebook->getLoginUrl(array('scope' => 'email')));
        }
        // if user's FB account is linked than log the user in
        if (isset($fb_user_profile['id'])) {
            $sql = 'SELECT `id_customer`
				FROM `' . _DB_PREFIX_ . 'customer_profile_connect`
				WHERE `facebook_id` = \'' . (int) $fb_user_profile['id'] . '\'' . Shop::addSqlRestriction(Shop::SHARE_CUSTOMER);
            if (Db::getInstance()->getValue($sql)) {
                Tools::redirect($this->context->link->getModuleLink('fbconnect_psb', 'login', array(), TRUE, $this->context->language->id));
            }
        }
        if (Tools::getValue('done')) {
            $response = $facebook->getSignedRequest($_REQUEST['signed_request']);
            $reg_metadata_fields = '[{"name":"name"},{"name":"first_name"},{"name":"last_name"},{"name":"email"},{"name":"password"},{"name":"birthday"},{"name":"gender"}]';
            $reg_metadata_fields_clean = preg_replace('/\\s+/', '', $reg_metadata_fields);
            $response_metadata_fields_clean = preg_replace('/\\s+/', '', $response['registration_metadata']['fields']);
            if (strcmp($reg_metadata_fields_clean, $response_metadata_fields_clean) != 0) {
                $this->errors[] = Tools::displayError('registration metadata fields not valid');
            }
            $response_email = trim($response['registration']['email']);
            if (empty($response_email)) {
                $this->errors[] = Tools::displayError('An email address required.');
            } else {
                if (!Validate::isEmail($response_email)) {
                    $this->errors[] = Tools::displayError('Invalid email address.');
                } else {
                    if (Customer::customerExists($response_email)) {
                        // Need to clean up the code here most of it is from
                        // IDFBCon_v.0.2 (Chandra R. Atmaja <*****@*****.**>)
                        // Someone has already registered with this e-mail address
                        // This will link the 1st existing email/account on site with Facebook
                        // and log the user in to the account. Is this safe?
                        $customer = new Customer();
                        $authentication = $customer->getByEmail($response['registration']['email']);
                        // This is done to see if a existing users try's to re-registrar
                        $sql = 'SELECT `facebook_id`
					FROM `' . _DB_PREFIX_ . 'customer_profile_connect`
					WHERE `id_customer` = \'' . (int) $customer->id . '\' ' . Shop::addSqlRestriction(Shop::SHARE_CUSTOMER);
                        $customer_fb_id = Db::getInstance()->getValue($sql);
                        if ($customer_fb_id) {
                            if ($customer_fb_id == (int) $response['user_id']) {
                                Tools::redirect($this->context->link->getModuleLink('fbconnect_psb', 'login', array(), false, $this->context->language->id));
                            } else {
                                $this->errors[] = Tools::displayError('An error occurred while linking your Facebook account.');
                            }
                        } else {
                            if (Db::getInstance()->insert('customer_profile_connect', array('id_customer' => (int) $customer->id, 'facebook_id' => (int) $response['user_id']))) {
                                $this->errors[] = Tools::displayError('an error occurred while linking your Facebook account.');
                            }
                            $customer->active = 1;
                            $customer->deleted = 0;
                            $this->context->cookie->id_customer = intval($customer->id);
                            $this->context->cookie->customer_lastname = $customer->lastname;
                            $this->context->cookie->customer_firstname = $customer->firstname;
                            $this->context->cookie->logged = 1;
                            $this->context->cookie->passwd = $customer->passwd;
                            $this->context->cookie->email = $customer->email;
                            if (Configuration::get('PS_CART_FOLLOWING') and (empty($this->context->cookie->id_cart) or Cart::getNbProducts($this->context->cookie->id_cart) == 0)) {
                                $this->context->cookie->id_cart = intval(Cart::lastNoneOrderedCart(intval($customer->id)));
                            }
                            Module::hookExec('authentication');
                            if ($back = Tools::getValue('back')) {
                                Tools::redirect($back);
                            }
                            Tools::redirect('index.php?controller=my-account');
                        }
                    }
                }
            }
            if (!sizeof($this->errors)) {
                // TODO: use this->context for customer instead of new object?
                // Need to clean up the code here most of it is from
                // IDFBCon_v.0.2 (Chandra R. Atmaja <*****@*****.**>)
                $customer = new Customer();
                $customer_birthday = explode('/', $response['registration']['birthday']);
                $customer->birthday = intval($customer_birthday[2]) . '-' . intval($customer_birthday[0]) . '-' . intval($customer_birthday[1]);
                if ($response['registration']['last_name'] == "male") {
                    $_POST['id_gender'] = 1;
                } else {
                    if ($response['registration']['last_name'] == "female") {
                        $_POST['id_gender'] = 2;
                    } else {
                        $_POST['id_gender'] = 0;
                    }
                }
                $_POST['lastname'] = $response['registration']['last_name'];
                $_POST['firstname'] = $response['registration']['first_name'];
                $_POST['passwd'] = $response['registration']['password'];
                $_POST['email'] = $response['registration']['email'];
                $this->errors = $customer->validateControler();
                if (!sizeof($this->errors)) {
                    $customer->active = 1;
                    if (!$customer->add()) {
                        $this->errors[] = Tools::displayError('an error occurred while creating your account');
                    } else {
                        if (Db::getInstance()->insert('customer_profile_connect', array('id_customer' => (int) $customer->id, 'facebook_id' => (int) $response['user_id']))) {
                            $this->errors[] = Tools::displayError('an error occurred while linking your Facebook account.');
                        }
                        $email_var = array('{firstname}' => $customer->firstname, '{lastname}' => $customer->lastname, '{email}' => $customer->email, '{passwd}' => $response['registration']['password']);
                        if (!Mail::Send(intval($this->context->cookie->id_lang), 'account', 'Welcome!', $email_var, $customer->email, $customer->firstname . ' ' . $customer->lastname)) {
                            $this->errors[] = Tools::displayError('cannot send email');
                        }
                        $this->context->smarty->assign('confirmation', 1);
                        $this->context->cookie->id_customer = intval($customer->id);
                        $this->context->cookie->customer_lastname = $customer->lastname;
                        $this->context->cookie->customer_firstname = $customer->firstname;
                        $this->context->cookie->passwd = $customer->passwd;
                        $this->context->cookie->logged = 1;
                        $this->context->cookie->email = $customer->email;
                        Module::hookExec('createAccount', array('_POST' => $_POST, 'newCustomer' => $customer));
                        if ($back) {
                            Tools::redirect($back);
                        }
                        Tools::redirect('index.php?controller=my-account');
                    }
                }
            }
        }
        $useSSL = isset($this->ssl) && $this->ssl && Configuration::get('PS_SSL_ENABLED') || Tools::usingSecureMode() ? true : false;
        $this->context->smarty->assign(array('redirect_uri' => $this->redirect_uri, 'protocol_content' => $useSSL ? 'https://' : 'http://', 'fb_connect_appid' => $fb_connect_appid));
        $this->setTemplate('registration_fb.tpl');
    }
Beispiel #2
0
 protected function changePassword()
 {
     $token = Tools::getValue('token');
     $id_customer = (int) Tools::getValue('id_customer');
     if ($email = Db::getInstance()->getValue('SELECT `email` FROM ' . _DB_PREFIX_ . 'customer c WHERE c.`secure_key` = \'' . pSQL($token) . '\' AND c.id_customer = ' . $id_customer)) {
         $customer = new Customer();
         $customer->getByEmail($email);
         if (!Validate::isLoadedObject($customer)) {
             $this->errors[] = $this->trans('Customer account not found', array(), 'Shop.Notifications.Error');
         } elseif (!$customer->active) {
             $this->errors[] = $this->trans('You cannot regenerate the password for this account.', array(), 'Shop.Notifications.Error');
         }
         // Case if both password params not posted or different, then "change password" form is not POSTED, show it.
         if (!Tools::isSubmit('passwd') || !Tools::isSubmit('confirmation') || ($passwd = Tools::getValue('passwd')) !== ($confirmation = Tools::getValue('confirmation')) || !Validate::isPasswd($passwd) || !Validate::isPasswd($confirmation)) {
             // Check if passwords are here anyway, BUT does not match the password validation format
             if (Tools::isSubmit('passwd') || Tools::isSubmit('confirmation')) {
                 $this->errors[] = $this->trans('The password and its confirmation do not match.', array(), 'Shop.Notifications.Error');
             }
             $this->context->smarty->assign(['customer_email' => $customer->email, 'customer_token' => $token, 'id_customer' => $id_customer, 'reset_token' => Tools::getValue('reset_token')]);
             $this->setTemplate('customer/password-new');
         } else {
             // Both password fields posted. Check if all is right and store new password properly.
             if (!Tools::getValue('reset_token') || strtotime($customer->last_passwd_gen . '+' . (int) Configuration::get('PS_PASSWD_TIME_FRONT') . ' minutes') - time() > 0) {
                 Tools::redirect('index.php?controller=authentication&error_regen_pwd');
             } else {
                 // To update password, we must have the temporary reset token that matches.
                 if ($customer->getValidResetPasswordToken() !== Tools::getValue('reset_token')) {
                     $this->errors[] = $this->trans('The password change request expired. You should ask for a new one.', array(), 'Shop.Notifications.Error');
                 } else {
                     try {
                         $crypto = new Hashing();
                     } catch (\PrestaShop\PrestaShop\Adapter\CoreException $e) {
                         $this->errors[] = $this->trans('An error occurred with your account, which prevents us from updating the new password. Please report this issue using the contact form.', array(), 'Shop.Notifications.Error');
                         return false;
                     }
                     $customer->passwd = $crypto->encrypt($password = Tools::getValue('passwd'), _COOKIE_KEY_);
                     $customer->last_passwd_gen = date('Y-m-d H:i:s', time());
                     if ($customer->update()) {
                         Hook::exec('actionPasswordRenew', array('customer' => $customer, 'password' => $password));
                         $customer->removeResetPasswordToken();
                         $customer->update();
                         $mail_params = ['{email}' => $customer->email, '{lastname}' => $customer->lastname, '{firstname}' => $customer->firstname];
                         if (Mail::Send($this->context->language->id, 'password', Mail::l('Your new password'), $mail_params, $customer->email, $customer->firstname . ' ' . $customer->lastname)) {
                             $this->context->smarty->assign(['customer_email' => $customer->email]);
                             $this->success[] = $this->trans('Your password has been successfully reset and a confirmation has been sent to your email address: %s', array($customer->email), 'Shop.Notifications.Success');
                             $this->context->updateCustomer($customer);
                             $this->redirectWithNotifications('index.php?controller=my-account');
                         } else {
                             $this->errors[] = $this->trans('An error occurred while sending the email.', array(), 'Shop.Notifications.Error');
                         }
                     } else {
                         $this->errors[] = $this->trans('An error occurred with your account, which prevents us from updating the new password. Please report this issue using the contact form.', array(), 'Shop.Notifications.Error');
                     }
                 }
             }
         }
     } else {
         $this->errors[] = $this->trans('We cannot regenerate your password with the data you\'ve submitted', array(), 'Shop.Notifications.Error');
     }
 }
 public function init()
 {
     parent::init();
     /*
      * Piqué dans le AuthController. J'aurais bien aimé utiliser le AuthController, mais le premier contrôle dans son init()
      * c'est pour vérifier si l'utilisateur est loggé ou non, ce qui mettait à plat ma stratégie.
      *
      * Je me suis posé la question 'Faut il que ca marche pour des admin ?', j'ai supposé que non,
      * mais s'il avait fallu, il suffisait de tester un 'Employee' en plus d'un 'Customer'
      */
     $passwd = trim(Tools::getValue('passwd'));
     $_POST['passwd'] = null;
     $email = trim(Tools::getValue('email'));
     if (!empty($email) && Validate::isEmail($email) && !empty($passwd) && Validate::isPasswd($passwd)) {
         $customer = new Customer();
         $authentication = $customer->getByEmail(trim($email), trim($passwd));
         if (isset($authentication->active) && $authentication->active && $customer->id) {
             Tools::redirect(Configuration::get("ADMIN_TAB_MODULE_URLBACK"));
         }
     }
     /*
      * Ici, je ne suis vraiment pas satisfait de la méthode employée, je trouve ça plutôt crade
      * de transmettre des infos sur les erreurs via un param en GET, mais dans l'immédiat je n'ai pas trouvé mieux
      */
     Tools::redirect("index.php?urlback_haserror=1");
 }
 /**
  * @param $email
  * @param $password
  * @return int
  */
 public function getCustomerIdByEmailAndPassword($email, $password)
 {
     /** @var CustomerCore $customer */
     $customer = new Customer();
     /** @var CustomerCore $authentication */
     $authentication = $customer->getByEmail(trim($email), trim($password));
     return $authentication->id;
 }
 /**
  * 
  * @param array $event
  */
 public function unsubscribe(array $event)
 {
     if (!array_key_exists('email', $event)) {
         return false;
     }
     if (!$event['email']) {
         return false;
     }
     $customerClass = new Customer();
     $customer = $customerClass->getByEmail($event['email']);
     if ($customer) {
         $customer->newsletter = 0;
         $customer->update();
     }
 }
Beispiel #6
0
 public function submit()
 {
     if ($this->validate()) {
         Hook::exec('actionAuthenticationBefore');
         $customer = new Customer();
         $authentication = $customer->getByEmail($this->getValue('email'), $this->getValue('password'));
         if (isset($authentication->active) && !$authentication->active) {
             $this->errors[''][] = $this->translator->trans('Your account isn\'t available at this time, please contact us', [], 'Shop.Notifications.Error');
         } elseif (!$authentication || !$customer->id || $customer->is_guest) {
             $this->errors[''][] = $this->translator->trans('Authentication failed.', [], 'Shop.Notifications.Error');
         } else {
             $this->context->updateCustomer($customer);
             Hook::exec('actionAuthentication', ['customer' => $this->context->customer]);
             // Login information have changed, so we check if the cart rules still apply
             CartRule::autoRemoveFromCart($this->context);
             CartRule::autoAddToCart($this->context);
         }
     }
     return !$this->hasErrors();
 }
 protected function runPage()
 {
     if (WebRequest::wasPosted()) {
         if (!($email = WebRequest::postString("lgEmail"))) {
             // no email address specified
             $this->redirect("noemail");
             return;
         }
         if (!($password = WebRequest::postString("lgPasswd"))) {
             // no password specified
             $this->redirect("nopass");
             return;
         }
         $cust = Customer::getByEmail($email);
         if ($cust == null) {
             // customer doesn't exist. offer to signup or retry?
             $this->redirect("invalid");
             return;
         }
         if (!$cust->isMailConfirmed()) {
             // customer hasn't confirmed their email
             $this->redirect("noconfirm");
             return;
         }
         if (!$cust->authenticate($password)) {
             // not a valid password
             $this->redirect("invalid");
             return;
         }
         // seems to be ok.
         // set up the session
         Session::setLoggedInCustomer($cust->getId());
         // redirect back to the main page.
         $this->redirect();
     } else {
         // urm, something's not quite right here...
         // redirect back to the main page.
         $this->mHeaders[] = "HTTP/1.1 303 See Other";
         $this->mHeaders[] = "Location: " . $cWebPath . "/index.php";
     }
 }
Beispiel #8
0
 public function postProcess()
 {
     global $currentIndex;
     if (Tools::getValue('submitAdd' . $this->table)) {
         /* Checking fields validity */
         $this->validateRules();
         if (!sizeof($this->_errors)) {
             $id = intval(Tools::getValue('id_' . $this->table));
             if (isset($id) and !empty($id)) {
                 if ($this->tabAccess['edit'] !== '1') {
                     $this->_errors[] = Tools::displayError('You do not have permission to edit anything here.');
                 } else {
                     $object = new $this->className($id);
                     if (Validate::isLoadedObject($object)) {
                         $customer_email = strval(Tools::getValue('email'));
                         // check if e-mail already used
                         if ($customer_email != $object->email) {
                             $customer = new Customer();
                             $customer->getByEmail($customer_email);
                             if ($customer->id) {
                                 $this->_errors[] = Tools::displayError('an account already exists for this e-mail address:') . ' ' . $customer_email;
                             }
                         }
                         // Updating customer's group
                         if (!sizeof($this->_errors)) {
                             $groupList = Tools::getValue('groupBox');
                             $object->cleanGroups();
                             if (is_array($groupList) and sizeof($groupList) > 0) {
                                 $object->addGroups($groupList);
                             }
                         }
                     } else {
                         $this->_errors[] = Tools::displayError('an error occurred while loading object') . ' <b>' . $this->table . '</b> ' . Tools::displayError('(cannot load object)');
                     }
                 }
             }
         }
     }
     return parent::postProcess();
 }
 /**
  * @param $user
  * @param $pass
  * @param ShopgateCustomer $customer
  * @throws ShopgateLibraryException
  */
 public function registerCustomer($user, $pass, ShopgateCustomer $customer)
 {
     if (!Validate::isEmail($user)) {
         throw new ShopgateLibraryException(ShopgateLibraryException::PLUGIN_REGISTER_CUSTOMER_ERROR, 'E-mail Address validation error', true);
     }
     if ($pass && !Validate::isPasswd($pass)) {
         throw new ShopgateLibraryException(ShopgateLibraryException::PLUGIN_REGISTER_CUSTOMER_ERROR, 'Password validation error', true);
     }
     /** @var CustomerCore | Customer $customerModel */
     $customerModel = new Customer();
     if ($customerModel->getByEmail($user)) {
         throw new ShopgateLibraryException(ShopgateLibraryException::REGISTER_USER_ALREADY_EXISTS);
     }
     $customerModel->active = 1;
     $customerModel->lastname = $customer->getLastName();
     $customerModel->firstname = $customer->getFirstName();
     $customerModel->email = $user;
     $customerModel->passwd = Tools::encrypt($pass);
     $customerModel->id_gender = $this->mapGender($customer->getGender());
     $customerModel->birthday = $customer->getBirthday();
     $customerModel->newsletter = $customer->getNewsletterSubscription();
     $shopgateCustomFieldsHelper = new ShopgateCustomFieldsHelper();
     $shopgateCustomFieldsHelper->saveCustomFields($customerModel, $customer->getCustomFields());
     $validateMessage = $customerModel->validateFields(false, true);
     if ($validateMessage !== true) {
         throw new ShopgateLibraryException(ShopgateLibraryException::REGISTER_FAILED_TO_ADD_USER, $validateMessage, true);
     }
     $customerModel->save();
     /**
      * addresses
      */
     foreach ($customer->getAddresses() as $address) {
         $this->createAddress($address, $customerModel);
     }
     return $customerModel->id;
 }
 private function sendTest($recipient)
 {
     if (!empty($this->session_api->account_id) && $this->session_api->account_id > 0) {
         $last_tester = new Customer();
         // 1 - On ajoute le destinataire du test dans la liste du mailing en cours
         // -----------------------------------------------------------------------
         if ($last_tester->getByEmail((string) $recipient)) {
             $response_array = array();
             $parameters = array('account_id' => $this->session_api->account_id, 'list_id' => $this->campaign_infos['campaign_api_list_id'], 'recipients' => array(array('target' => $last_tester->email, 'lastname' => $last_tester->lastname, 'firstname' => $last_tester->firstname)));
             $this->session_api->call('email', 'recipients', 'add', $parameters, $response_array);
         }
         // 2 - On envoi un test au destinataire
         /// -----------------------------------
         $response_array = array();
         $parameters = array('account_id' => $this->session_api->account_id, 'campaign_id' => $this->campaign_infos['campaign_api_message_id'], 'list_id' => $this->campaign_infos['campaign_api_list_id'], 'recipient' => $recipient);
         if ($this->session_api->call('email', 'campaign', 'send_test', $parameters, $response_array)) {
             $this->confirmations[] = sprintf($this->module->l('An email as been sent to : %s', 'adminmarketingestep7'), $recipient);
             return true;
         }
     }
     $this->errors[] = sprintf($this->module->l('Error during communication with Express-Mailing API : %s', 'adminmarketingestep7'), $this->session_api->getError());
     return false;
 }
 /**
  * When the customer is back from PayPal after filling his/her credit card info or credentials, this function is preparing the order
  * PayPal is providing us with the customer info (E-mail address, billing address) and we are trying to find a matching customer in the Shop database.
  * If no customer is found, we create a new one and we simulate a logged customer session.
  * Eventually it will redirect the customer to the "Shipping" step/page of the order process
  */
 private function _expressCheckout()
 {
     /* We need to double-check that the token provided by PayPal is the one expected */
     $result = $this->paypal_usa->postToPayPal('GetExpressCheckoutDetails', '&TOKEN=' . urlencode(Tools::getValue('token')));
     if ((strtoupper($result['ACK']) == 'SUCCESS' || strtoupper($result['ACK']) == 'SUCCESSWITHWARNING') && $result['TOKEN'] == Tools::getValue('token') && $result['PAYERID'] == Tools::getValue('PayerID')) {
         /* Checks if a customer already exists for this e-mail address */
         if (Validate::isEmail($result['EMAIL'])) {
             $customer = new Customer();
             $customer->getByEmail($result['EMAIL']);
         }
         /* If the customer does not exist yet, create a new one */
         if (!Validate::isLoadedObject($customer)) {
             $customer = new Customer();
             $customer->email = $result['EMAIL'];
             $customer->firstname = $result['FIRSTNAME'];
             $customer->lastname = $result['LASTNAME'];
             $customer->passwd = Tools::encrypt(Tools::passwdGen());
             $customer->add();
         }
         /* Look for an existing PayPal address for this customer */
         $addresses = $customer->getAddresses((int) Configuration::get('PS_LANG_DEFAULT'));
         foreach ($addresses as $address) {
             if ($address['alias'] == 'PayPal') {
                 $id_address = (int) $address['id_address'];
                 break;
             }
         }
         /* Create or update a PayPal address for this customer */
         $address = new Address(isset($id_address) ? (int) $id_address : 0);
         $address->id_customer = (int) $customer->id;
         $address->id_country = (int) Country::getByIso($result['PAYMENTREQUEST_0_SHIPTOCOUNTRYCODE']);
         $address->id_state = (int) State::getIdByIso($result['PAYMENTREQUEST_0_SHIPTOSTATE'], (int) $address->id_country);
         $address->alias = 'PayPal';
         $address->lastname = substr($result['PAYMENTREQUEST_0_SHIPTONAME'], 0, strpos($result['PAYMENTREQUEST_0_SHIPTONAME'], ' '));
         $address->firstname = substr($result['PAYMENTREQUEST_0_SHIPTONAME'], strpos($result['PAYMENTREQUEST_0_SHIPTONAME'], ' '), strlen($result['PAYMENTREQUEST_0_SHIPTONAME']) - strlen($address->lastname));
         $address->address1 = $result['PAYMENTREQUEST_0_SHIPTOSTREET'];
         if ($result['PAYMENTREQUEST_0_SHIPTOSTREET2'] != '') {
             $address->address2 = $result['PAYMENTREQUEST_0_SHIPTOSTREET2'];
         }
         $address->city = $result['PAYMENTREQUEST_0_SHIPTOCITY'];
         $address->postcode = $result['PAYMENTREQUEST_0_SHIPTOZIP'];
         $address->save();
         /* Update the cart billing and delivery addresses */
         $this->context->cart->id_address_delivery = (int) $address->id;
         $this->context->cart->id_address_invoice = (int) $address->id;
         $this->context->cart->update();
         /* Update the customer cookie to simulate a logged-in session */
         $this->context->cookie->id_customer = (int) $customer->id;
         $this->context->cookie->customer_lastname = $customer->lastname;
         $this->context->cookie->customer_firstname = $customer->firstname;
         $this->context->cookie->passwd = $customer->passwd;
         $this->context->cookie->email = $customer->email;
         $this->context->cookie->is_guest = $customer->isGuest();
         $this->context->cookie->logged = 1;
         /* Save the Payer ID and Checkout token for later use (during the payment step/page) */
         $this->context->cookie->paypal_express_checkout_token = $result['TOKEN'];
         $this->context->cookie->paypal_express_checkout_payer_id = $result['PAYERID'];
         if (_PS_VERSION_ < '1.5') {
             Module::hookExec('authentication');
         } else {
             Hook::exec('authentication');
         }
         /* Redirect the use to the "Shipping" step/page of the order process */
         Tools::redirectLink($this->context->link->getPageLink('order.php', false, null, array('step' => '3')));
         exit;
     } else {
         foreach ($result as $key => $val) {
             $result[$key] = urldecode($val);
         }
         $this->context->smarty->assign('paypal_usa_errors', $result);
         $this->setTemplate('express-checkout-messages.tpl');
     }
 }
 protected function getCustomerByEmail($email, $register = false, $lastName = null, $firstName = null, $emailAddress = null)
 {
     $customer = new Customer();
     $customer->getByEmail($email);
     if (!Validate::isLoadedObject($customer) && $register) {
         if (PowaTagAPI::apiLog()) {
             PowaTagLogs::initAPILog('Create customer', PowaTagLogs::IN_PROGRESS, 'Customer : ' . $lastName . ' ' . $firstName);
         }
         $customer->lastname = $lastName;
         $customer->firstname = $firstName;
         $customer->email = $emailAddress;
         $customer->setWsPasswd(Tools::substr($customer->lastname, 0, 1) . $firstName);
         if (!$customer->save()) {
             $this->addError($this->module->l('Impossible to save customer'), PowaTagErrorType::$INTERNAL_ERROR);
             if (PowaTagAPI::apiLog()) {
                 PowaTagLogs::initAPILog('Create customer', PowaTagLogs::ERROR, $this->error['message']);
             }
             return false;
         }
         if (PowaTagAPI::apiLog()) {
             PowaTagLogs::initAPILog('Create customer', PowaTagLogs::SUCCESS, 'Customer ID : ' . $customer->id);
         }
     }
     return $customer;
 }
    public function processUpdate()
    {
        if (Validate::isLoadedObject($this->object)) {
            $customer_email = strval(Tools::getValue('email'));
            // check if e-mail already used
            if ($customer_email != $this->object->email) {
                $customer = new Customer();
                if (Validate::isEmail($customer_email)) {
                    $customer->getByEmail($customer_email);
                }
                if ($customer->id && $customer->id != (int) $this->object->id) {
                    $this->errors[] = Tools::displayError('An account already exists for this email address:') . ' ' . $customer_email;
                }
            }
            return parent::processUpdate();
        } else {
            $this->errors[] = Tools::displayError('An error occurred while loading the object.') . '
				<b>' . $this->table . '</b> ' . Tools::displayError('(cannot load object)');
        }
    }
 protected function runPage()
 {
     if (WebRequest::wasPosted()) {
         if (!WebRequest::postInt("calroom")) {
             $this->showCal();
             return;
         }
         $startdate = new DateTime(WebRequest::post("qbCheckin"));
         $enddate = new DateTime(WebRequest::post("qbCheckout"));
         $room = Room::getById(WebRequest::postInt("calroom"));
         for ($date = $startdate; $date < $enddate; $date->modify("+1 day")) {
             if (!$room->isAvailable($date)) {
                 $this->error("room-not-available");
                 $this->showCal();
                 return;
             }
         }
         // search for customer
         if (!($customer = Customer::getByEmail(WebRequest::post("qbEmail")))) {
             $customer = new Customer();
             $suTitle = WebRequest::post("qbTitle");
             $suFirstname = WebRequest::post("qbFirstname");
             $suLastname = WebRequest::post("qbLastname");
             $suAddress = WebRequest::post("qbAddress");
             $suCity = WebRequest::post("qbCity");
             $suPostcode = WebRequest::post("qbPostcode");
             $suCountry = WebRequest::post("qbCountry");
             $suEmail = WebRequest::post("qbEmail");
             $customer->setPassword($suEmail);
             // set values
             $customer->setTitle($suTitle);
             $customer->setFirstname($suFirstname);
             $customer->setSurname($suLastname);
             $address = new Address();
             $address->setLine1($suAddress);
             $address->setCity($suCity);
             $address->setPostCode($suPostcode);
             $address->setCountry($suCountry);
             $address->save();
             $customer->setAddress($address);
             $customer->setEmail($suEmail);
             // save it
             $customer->save();
             $customer->sendMailConfirm();
             // save it again
             $customer->save();
         }
         $booking = new Booking();
         $booking->setStartDate(WebRequest::post("qbCheckin"));
         $booking->setEndDate(WebRequest::post("qbCheckout"));
         $booking->setAdults(WebRequest::post("qbAdults"));
         $booking->setChildren(WebRequest::post("qbChildren"));
         $booking->setPromocode(WebRequest::post("qbPromoCode"));
         $booking->setRoom($room->getId());
         $booking->setCustomer($customer->getId());
         $booking->save();
         $msg = Message::getMessage("booking-confirmation");
         $msg = str_replace("\$1", $booking->getStartDate(), $msg);
         $msg = str_replace("\$2", $booking->getEndDate(), $msg);
         $msg = str_replace("\$3", $booking->getAdults(), $msg);
         $msg = str_replace("\$4", $booking->getChildren(), $msg);
         $msg = str_replace("\$5", $booking->getRoom()->getName(), $msg);
         Mail::send($customer->getEmail(), Message::getMessage("booking-confimation-subject"), $msg);
         $this->mSmarty->assign("content", $msg);
         return;
     }
     throw new YouShouldntBeDoingThatException();
 }
Beispiel #15
0
     $xml = $webService->get(array('url' => PS_SHOP_PATH . 'api/customers?schema=blank'));
     $resources = $xml->children()->children();
     $resources->id_default_group = 3;
     $resources->passwd = $customer->passwd;
     $resources->lastname = $customer->lastname;
     $resources->firstname = $customer->firstname;
     $resources->email = $customer->email;
     $resources->is_guest = 0;
     $resources->active = 1;
     $resources->associations->groups->group->id = 3;
     //$xml = $webService->add($opt);
     $opt = array('resource' => 'customers');
     $opt['postXml'] = $xml->asXML();
     $xml = $webService->add($opt);
     $cookieCustomer = new Customer();
     $cookieCustomer->getByEmail($customer->email);
     $cookie->id_customer = intval($cookieCustomer->id);
     $cookie->customer_lastname = $cookieCustomer->lastname;
     $cookie->customer_firstname = $cookieCustomer->firstname;
     $cookie->logged = 1;
     $cookie->passwd = $cookieCustomer->passwd;
     $cookie->email = $cookieCustomer->email;
     if (Configuration::get('PS_CART_FOLLOWING') and (empty($cookie->id_cart) or Cart::getNbProducts($cookie->id_cart) == 0)) {
         $cookie->id_cart = intval(Cart::lastNoneOrderedCart(intval($customer->id)));
     }
 } catch (PrestaShopWebserviceException $e) {
     // Here we are dealing with errors
     $trace = $e->getTrace();
     if ($trace[0]['args'][0] == 404) {
         echo 'Bad ID';
     } else {
    public function ajaxProcessSyncImap()
    {
        if ($this->tabAccess['edit'] != '1') {
            throw new PrestaShopException(Tools::displayError('You do not have permission to edit this.'));
        }
        if (Tools::isSubmit('syncImapMail')) {
            if (!($url = Configuration::get('PS_SAV_IMAP_URL')) || !($port = Configuration::get('PS_SAV_IMAP_PORT')) || !($user = Configuration::get('PS_SAV_IMAP_USER')) || !($password = Configuration::get('PS_SAV_IMAP_PWD'))) {
                die('{"hasError" : true, "errors" : ["Configuration is not correct"]}');
            }
            $conf = Configuration::getMultiple(array('PS_SAV_IMAP_OPT_NORSH', 'PS_SAV_IMAP_OPT_SSL', 'PS_SAV_IMAP_OPT_VALIDATE-CERT', 'PS_SAV_IMAP_OPT_NOVALIDATE-CERT', 'PS_SAV_IMAP_OPT_TLS', 'PS_SAV_IMAP_OPT_NOTLS'));
            $conf_str = '';
            if ($conf['PS_SAV_IMAP_OPT_NORSH']) {
                $conf_str .= '/norsh';
            }
            if ($conf['PS_SAV_IMAP_OPT_SSL']) {
                $conf_str .= '/ssl';
            }
            if ($conf['PS_SAV_IMAP_OPT_VALIDATE-CERT']) {
                $conf_str .= '/validate-cert';
            }
            if ($conf['PS_SAV_IMAP_OPT_NOVALIDATE-CERT']) {
                $conf_str .= '/novalidate-cert';
            }
            if ($conf['PS_SAV_IMAP_OPT_TLS']) {
                $conf_str .= '/tls';
            }
            if ($conf['PS_SAV_IMAP_OPT_NOTLS']) {
                $conf_str .= '/notls';
            }
            if (!function_exists('imap_open')) {
                die('{"hasError" : true, "errors" : ["imap is not installed on this server"]}');
            }
            $mbox = @imap_open('{' . $url . ':' . $port . $conf_str . '}', $user, $password);
            //checks if there is no error when connecting imap server
            $errors = array_unique(imap_errors());
            $str_errors = '';
            $str_error_delete = '';
            if (sizeof($errors) && is_array($errors)) {
                $str_errors = '';
                foreach ($errors as $error) {
                    $str_errors .= $error . ', ';
                }
                $str_errors = rtrim(trim($str_errors), ',');
            }
            //checks if imap connexion is active
            if (!$mbox) {
                $array = array('hasError' => true, 'errors' => array('Cannot connect to the mailbox :<br />' . $str_errors));
                die(Tools::jsonEncode($array));
            }
            //Returns information about the current mailbox. Returns FALSE on failure.
            $check = imap_check($mbox);
            if (!$check) {
                die('{"hasError" : true, "errors" : ["Fail to get information about the current mailbox"]}');
            }
            if ($check->Nmsgs == 0) {
                die('{"hasError" : true, "errors" : ["NO message to sync"]}');
            }
            $result = imap_fetch_overview($mbox, "1:{$check->Nmsgs}", 0);
            foreach ($result as $overview) {
                //check if message exist in database
                if (isset($overview->subject)) {
                    $subject = $overview->subject;
                } else {
                    $subject = '';
                }
                //Creating an md5 to check if message has been allready processed
                $md5 = md5($overview->date . $overview->from . $subject . $overview->msgno);
                $exist = Db::getInstance()->getValue('SELECT `md5_header`
						 FROM `' . _DB_PREFIX_ . 'customer_message_sync_imap`
						 WHERE `md5_header` = \'' . pSQL($md5) . '\'');
                if ($exist) {
                    if (Configuration::get('PS_SAV_IMAP_DELETE_MSG')) {
                        if (!imap_delete($mbox, $overview->msgno)) {
                            $str_error_delete = ', Fail to delete message';
                        }
                    }
                } else {
                    //check if subject has id_order
                    preg_match('/\\#ct([0-9]*)/', $subject, $matches1);
                    preg_match('/\\#tc([0-9-a-z-A-Z]*)/', $subject, $matches2);
                    $matchFound = false;
                    if (isset($matches1[1]) && isset($matches2[1])) {
                        $matchFound = true;
                    }
                    $new_ct = Configuration::get('PS_SAV_IMAP_CREATE_THREADS') && !$matchFound && strpos($subject, '[no_sync]') == false;
                    if ($matchFound || $new_ct) {
                        if ($new_ct) {
                            if (!preg_match('/<(' . Tools::cleanNonUnicodeSupport('[a-z\\p{L}0-9!#$%&\'*+\\/=?^`{}|~_-]+[.a-z\\p{L}0-9!#$%&\'*+\\/=?^`{}|~_-]*@[a-z\\p{L}0-9]+[._a-z\\p{L}0-9-]*\\.[a-z0-9]+') . ')>/', $overview->from, $result) || !Validate::isEmail($from = $result[1])) {
                                continue;
                            }
                            // we want to assign unrecognized mails to the right contact category
                            $contacts = Contact::getContacts($this->context->language->id);
                            if (!$contacts) {
                                continue;
                            }
                            foreach ($contacts as $contact) {
                                if (strpos($overview->to, $contact['email']) !== false) {
                                    $id_contact = $contact['id_contact'];
                                }
                            }
                            if (!isset($id_contact)) {
                                // if not use the default contact category
                                $id_contact = $contacts[0]['id_contact'];
                            }
                            $customer = new Customer();
                            $client = $customer->getByEmail($from);
                            //check if we already have a customer with this email
                            $ct = new CustomerThread();
                            if (isset($client->id)) {
                                //if mail is owned by a customer assign to him
                                $ct->id_customer = $client->id;
                            }
                            $ct->email = $from;
                            $ct->id_contact = $id_contact;
                            $ct->id_lang = (int) Configuration::get('PS_LANG_DEFAULT');
                            $ct->id_shop = $this->context->shop->id;
                            //new customer threads for unrecognized mails are not shown without shop id
                            $ct->status = 'open';
                            $ct->token = Tools::passwdGen(12);
                            $ct->add();
                        } else {
                            $ct = new CustomerThread((int) $matches1[1]);
                        }
                        //check if order exist in database
                        if (Validate::isLoadedObject($ct) && (isset($matches2[1]) && $ct->token == $matches2[1] || $new_ct)) {
                            $message = imap_fetchbody($mbox, $overview->msgno, 1);
                            $message = quoted_printable_decode($message);
                            $message = utf8_encode($message);
                            $message = quoted_printable_decode($message);
                            $message = nl2br($message);
                            $cm = new CustomerMessage();
                            $cm->id_customer_thread = $ct->id;
                            $cm->message = $message;
                            $cm->add();
                        }
                    }
                    Db::getInstance()->execute('INSERT INTO `' . _DB_PREFIX_ . 'customer_message_sync_imap` (`md5_header`) VALUES (\'' . pSQL($md5) . '\')');
                }
            }
            imap_expunge($mbox);
            imap_close($mbox);
            $array = array('hasError' => false, 'errors' => array($str_errors . $str_error_delete));
            die(Tools::jsonEncode($array));
        }
    }
 protected function runPage()
 {
     if (Session::isCustomerLoggedIn()) {
         global $cWebPath;
         // redirect to main page
         $this->mHeaders[] = "HTTP/1.1 303 See Other";
         $this->mHeaders[] = "Location: " . $cWebPath . "/index.php";
         return;
     }
     if (WebRequest::wasPosted()) {
         if (WebRequest::get("id") && WebRequest::get("hash")) {
             // setting password
             $id = WebRequest::get("id");
             $hash = WebRequest::get("hash");
             $customer = Customer::getById($id);
             try {
                 if ($customer->getMailChecksum() != $hash) {
                     throw new InvalidChecksumException();
                 }
                 $suPassword = WebRequest::post("suPassword");
                 $suConfirm = WebRequest::post("suConfirm");
                 // validation
                 if ($suPassword == "") {
                     throw new CreateCustomerException("Password not specified");
                 }
                 if ($suConfirm == "") {
                     throw new CreateCustomerException("Confirmed password not specified");
                 }
                 if ($suPassword != $suConfirm) {
                     throw new CreateCustomerException("Password mismatch");
                 }
                 // validation
                 if ($suPassword != "" && $suPassword == $suConfirm) {
                     $customer->setPassword($suPassword);
                 }
                 $customer->save();
                 // log them in
                 Session::setLoggedInCustomer($id);
                 // redirect to main page
                 global $cWebPath;
                 $this->mHeaders[] = "HTTP/1.1 303 See Other";
                 $this->mHeaders[] = "Location: " . $cWebPath . "/index.php";
             } catch (CreateCustomerException $ex) {
                 $this->mBasePage = "changePassword.tpl";
                 $this->error($ex->getMessage());
             } catch (InvalidChecksumException $ex) {
                 $this->mBasePage = "changePassword.tpl";
                 $this->error($ex->getMessage());
             }
         } else {
             // requesting
             try {
                 $suEmail = WebRequest::post("suEmail");
                 // validation
                 if ($suEmail == "") {
                     throw new CreateCustomerException("Email not specified");
                 }
                 $customer = Customer::getByEmail($suEmail);
                 if ($customer == null) {
                     throw new NonexistantObjectException();
                 }
                 $customer->sendPasswordReset();
                 $this->mBasePage = "forgotpassword.tpl";
                 // TODO: show some confirmation, check email, etc
             } catch (CreateCustomerException $ex) {
                 $this->mBasePage = "forgottenpassword.tpl";
                 $this->error($ex->getMessage());
             } catch (NonexistantObjectException $ex) {
                 $this->mBasePage = "forgottenpassword.tpl";
                 $this->error("nonexistant object");
             }
         }
     } else {
         if (WebRequest::get("id") && WebRequest::get("hash")) {
             // show reset password form
             try {
                 $id = WebRequest::get("id");
                 $hash = WebRequest::get("hash");
                 $customer = Customer::getById($id);
                 if ($customer->getMailChecksum() != $hash) {
                     throw new InvalidChecksumException();
                 }
                 $this->mBasePage = "changePassword.tpl";
                 $this->mSmarty->assign("cpid", $id);
                 $this->mSmarty->assign("cphash", $hash);
             } catch (InvalidChecksumException $ex) {
                 $this->mBasePage = "forgottenpassword.tpl";
                 $this->error("invalid checksum");
             }
         } else {
             // show request form
             $this->mBasePage = "forgottenpassword.tpl";
             return;
         }
     }
 }
    public function postProcess()
    {
        global $currentIndex;
        if (Tools::isSubmit('submitDel' . $this->table) or Tools::isSubmit('delete' . $this->table)) {
            $deleteForm = '
			<form action="' . htmlentities($_SERVER['REQUEST_URI']) . '" method="post">
				<fieldset><legend>' . $this->l('How do you want to delete your customer(s)?') . '</legend>
					' . $this->l('You have two ways to delete a customer, please choose what you want to do.') . '
					<p>
						<input type="radio" name="deleteMode" value="real" id="deleteMode_real" />
						<label for="deleteMode_real" style="float:none">' . $this->l('I want to delete my customer(s) for real, all data will be removed from the database. A customer with the same e-mail address will be able to register again.') . '</label>
					</p>
					<p>
						<input type="radio" name="deleteMode" value="deleted" id="deleteMode_deleted" />
						<label for="deleteMode_deleted" style="float:none">' . $this->l('I don\'t want my customer(s) to register again. The customer(s) will be removed from this list but all data will be kept in the database.') . '</label>
					</p>';
            foreach ($_POST as $key => $value) {
                if (is_array($value)) {
                    foreach ($value as $val) {
                        $deleteForm .= '<input type="hidden" name="' . htmlentities($key) . '[]" value="' . htmlentities($val) . '" />';
                    }
                } else {
                    $deleteForm .= '<input type="hidden" name="' . htmlentities($key) . '" value="' . htmlentities($value) . '" />';
                }
            }
            $deleteForm .= '	<br /><input type="submit" class="button" value="' . $this->l('   Delete   ') . '" />
				</fieldset>
			</form>
			<div class="clear">&nbsp;</div>';
        }
        if (Tools::getValue('submitAdd' . $this->table)) {
            $groupList = Tools::getValue('groupBox');
            /* Checking fields validity */
            $this->validateRules();
            if (!sizeof($this->_errors)) {
                $id = (int) Tools::getValue('id_' . $this->table);
                if (isset($id) and !empty($id)) {
                    if ($this->tabAccess['edit'] !== '1') {
                        $this->_errors[] = Tools::displayError('You do not have permission to edit here.');
                    } else {
                        $object = new $this->className($id);
                        if (Validate::isLoadedObject($object)) {
                            $customer_email = strval(Tools::getValue('email'));
                            // check if e-mail already used
                            if ($customer_email != $object->email) {
                                $customer = new Customer();
                                $customer->getByEmail($customer_email);
                                if ($customer->id) {
                                    $this->_errors[] = Tools::displayError('An account already exists for this e-mail address:') . ' ' . $customer_email;
                                }
                            }
                            if (!is_array($groupList) or sizeof($groupList) == 0) {
                                $this->_errors[] = Tools::displayError('Customer must be in at least one group.');
                            } else {
                                if (!in_array(Tools::getValue('id_default_group'), $groupList)) {
                                    $this->_errors[] = Tools::displayError('Default customer group must be selected in group box.');
                                }
                            }
                            // Updating customer's group
                            if (!sizeof($this->_errors)) {
                                $object->cleanGroups();
                                if (is_array($groupList) and sizeof($groupList) > 0) {
                                    $object->addGroups($groupList);
                                }
                            }
                        } else {
                            $this->_errors[] = Tools::displayError('An error occurred while loading object.') . ' <b>' . $this->table . '</b> ' . Tools::displayError('(cannot load object)');
                        }
                    }
                } else {
                    if ($this->tabAccess['add'] === '1') {
                        $object = new $this->className();
                        $this->copyFromPost($object, $this->table);
                        if (!$object->add()) {
                            $this->_errors[] = Tools::displayError('An error occurred while creating object.') . ' <b>' . $this->table . ' (' . mysql_error() . ')</b>';
                        } elseif ($_POST[$this->identifier] = $object->id and $this->postImage($object->id) and !sizeof($this->_errors) and $this->_redirect) {
                            // Add Associated groups
                            $group_list = Tools::getValue('groupBox');
                            if (is_array($group_list) && sizeof($group_list) > 0) {
                                $object->addGroups($group_list, true);
                            }
                            $parent_id = (int) Tools::getValue('id_parent', 1);
                            // Save and stay on same form
                            if (Tools::isSubmit('submitAdd' . $this->table . 'AndStay')) {
                                Tools::redirectAdmin($currentIndex . '&' . $this->identifier . '=' . $object->id . '&conf=3&update' . $this->table . '&token=' . $this->token);
                            }
                            // Save and back to parent
                            if (Tools::isSubmit('submitAdd' . $this->table . 'AndBackToParent')) {
                                Tools::redirectAdmin($currentIndex . '&' . $this->identifier . '=' . $parent_id . '&conf=3&token=' . $this->token);
                            }
                            // Default behavior (save and back)
                            Tools::redirectAdmin($currentIndex . ($parent_id ? '&' . $this->identifier . '=' . $object->id : '') . '&conf=3&token=' . $this->token);
                        }
                    } else {
                        $this->_errors[] = Tools::displayError('You do not have permission to add here.');
                    }
                }
            }
        } elseif (Tools::isSubmit('delete' . $this->table) and $this->tabAccess['delete'] === '1') {
            switch (Tools::getValue('deleteMode')) {
                case 'real':
                    $this->deleted = false;
                    Discount::deleteByIdCustomer((int) Tools::getValue('id_customer'));
                    break;
                case 'deleted':
                    $this->deleted = true;
                    break;
                default:
                    echo $deleteForm;
                    if (isset($_POST['delete' . $this->table])) {
                        unset($_POST['delete' . $this->table]);
                    }
                    if (isset($_GET['delete' . $this->table])) {
                        unset($_GET['delete' . $this->table]);
                    }
                    break;
            }
        } elseif (Tools::isSubmit('submitDel' . $this->table) and $this->tabAccess['delete'] === '1') {
            switch (Tools::getValue('deleteMode')) {
                case 'real':
                    $this->deleted = false;
                    foreach (Tools::getValue('customerBox') as $id_customer) {
                        Discount::deleteByIdCustomer((int) $id_customer);
                    }
                    break;
                case 'deleted':
                    $this->deleted = true;
                    break;
                default:
                    echo $deleteForm;
                    if (isset($_POST['submitDel' . $this->table])) {
                        unset($_POST['submitDel' . $this->table]);
                    }
                    if (isset($_GET['submitDel' . $this->table])) {
                        unset($_GET['submitDel' . $this->table]);
                    }
                    break;
            }
        } elseif (Tools::isSubmit('submitGuestToCustomer') and Tools::getValue('id_customer')) {
            if ($this->tabAccess['edit'] === '1') {
                $customer = new Customer((int) Tools::getValue('id_customer'));
                if (!Validate::isLoadedObject($customer)) {
                    $this->_errors[] = Tools::displayError('This customer does not exist.');
                }
                if (Customer::customerExists($customer->email)) {
                    $this->_errors[] = Tools::displayError('This customer already exist as non-guest.');
                } elseif ($customer->transformToCustomer(Tools::getValue('id_lang', Configuration::get('PS_LANG_DEFAULT')))) {
                    Tools::redirectAdmin($currentIndex . '&' . $this->identifier . '=' . $customer->id . '&conf=3&token=' . $this->token);
                } else {
                    $this->_errors[] = Tools::displayError('An error occurred while updating customer.');
                }
            } else {
                $this->_errors[] = Tools::displayError('You do not have permission to edit here.');
            }
        } elseif (Tools::isSubmit('changeNewsletterVal') and Tools::getValue('id_customer')) {
            $id_customer = (int) Tools::getValue('id_customer');
            $customer = new Customer($id_customer);
            if (!Validate::isLoadedObject($customer)) {
                $this->_errors[] = Tools::displayError('An error occurred while updating customer.');
            }
            $update = Db::getInstance()->Execute('UPDATE `' . _DB_PREFIX_ . 'customer` SET newsletter = ' . ($customer->newsletter ? 0 : 1) . ' WHERE `id_customer` = ' . (int) $customer->id);
            if (!$update) {
                $this->_errors[] = Tools::displayError('An error occurred while updating customer.');
            }
            Tools::redirectAdmin($currentIndex . '&token=' . $this->token);
        } elseif (Tools::isSubmit('changeOptinVal') and Tools::getValue('id_customer')) {
            $id_customer = (int) Tools::getValue('id_customer');
            $customer = new Customer($id_customer);
            if (!Validate::isLoadedObject($customer)) {
                $this->_errors[] = Tools::displayError('An error occurred while updating customer.');
            }
            $update = Db::getInstance()->Execute('UPDATE `' . _DB_PREFIX_ . 'customer` SET optin = ' . ($customer->optin ? 0 : 1) . ' WHERE `id_customer` = ' . (int) $customer->id);
            if (!$update) {
                $this->_errors[] = Tools::displayError('An error occurred while updating customer.');
            }
            Tools::redirectAdmin($currentIndex . '&token=' . $this->token);
        }
        return parent::postProcess();
    }
Beispiel #19
0
 /**
  * Set Admin customer link for customer
  *
  * @param $events
  * @return mixed
  */
 private function setUserLinkToEvents($events)
 {
     foreach ($events as &$event) {
         if (!empty($event['email'])) {
             $customer = Customer::getByEmail($event['email']);
             if (isset($customer->id) && !empty($customer->id)) {
                 $params = array('id_customer' => $customer->id, 'viewcustomer' => '');
                 unset($customer);
                 $event['email'] = '<a href="' . $this->getAdminModuleLink($params, 'AdminCustomers') . '">' . $event['email'] . '</a>';
             }
         }
     }
     return $events;
 }
 /**
  * Process login
  */
 protected function processSubmitLogin()
 {
     Hook::exec('actionBeforeAuthentication');
     $passwd = trim(Tools::getValue('passwd'));
     $_POST['passwd'] = null;
     $email = trim(Tools::getValue('email'));
     if (empty($email)) {
         $this->errors[] = Tools::displayError('An email address required.');
     } elseif (!Validate::isEmail($email)) {
         $this->errors[] = Tools::displayError('Invalid email address.');
     } elseif (empty($passwd)) {
         $this->errors[] = Tools::displayError('Password is required.');
     } elseif (!Validate::isPasswd($passwd)) {
         $this->errors[] = Tools::displayError('Invalid password.');
     } else {
         $customer = new Customer();
         $authentication = $customer->getByEmail(trim($email), trim($passwd));
         if (isset($authentication->active) && !$authentication->active) {
             $this->errors[] = Tools::displayError('Your account isn\'t available at this time, please contact us');
         } elseif (!$authentication || !$customer->id) {
             $this->errors[] = Tools::displayError('Authentication failed.');
         } else {
             $this->context->cookie->id_compare = isset($this->context->cookie->id_compare) ? $this->context->cookie->id_compare : CompareProduct::getIdCompareByIdCustomer($customer->id);
             $this->context->cookie->id_customer = (int) $customer->id;
             $this->context->cookie->customer_lastname = $customer->lastname;
             $this->context->cookie->customer_firstname = $customer->firstname;
             $this->context->cookie->logged = 1;
             $customer->logged = 1;
             $this->context->cookie->is_guest = $customer->isGuest();
             $this->context->cookie->passwd = $customer->passwd;
             $this->context->cookie->email = $customer->email;
             // Add customer to the context
             $this->context->customer = $customer;
             if (Configuration::get('PS_CART_FOLLOWING') && (empty($this->context->cookie->id_cart) || Cart::getNbProducts($this->context->cookie->id_cart) == 0) && ($id_cart = (int) Cart::lastNoneOrderedCart($this->context->customer->id))) {
                 $this->context->cart = new Cart($id_cart);
             } else {
                 $id_carrier = (int) $this->context->cart->id_carrier;
                 $this->context->cart->id_carrier = 0;
                 $this->context->cart->setDeliveryOption(null);
                 $this->context->cart->id_address_delivery = (int) Address::getFirstCustomerAddressId((int) $customer->id);
                 $this->context->cart->id_address_invoice = (int) Address::getFirstCustomerAddressId((int) $customer->id);
             }
             $this->context->cart->id_customer = (int) $customer->id;
             $this->context->cart->secure_key = $customer->secure_key;
             if ($this->ajax && isset($id_carrier) && $id_carrier && Configuration::get('PS_ORDER_PROCESS_TYPE')) {
                 $delivery_option = array($this->context->cart->id_address_delivery => $id_carrier . ',');
                 $this->context->cart->setDeliveryOption($delivery_option);
             }
             $this->context->cart->save();
             $this->context->cookie->id_cart = (int) $this->context->cart->id;
             $this->context->cookie->write();
             $this->context->cart->autosetProductAddress();
             Hook::exec('actionAuthentication', array('customer' => $this->context->customer));
             // Login information have changed, so we check if the cart rules still apply
             CartRule::autoRemoveFromCart($this->context);
             CartRule::autoAddToCart($this->context);
             if (!$this->ajax) {
                 $back = Tools::getValue('back', 'my-account');
                 if ($back == Tools::secureReferrer($back)) {
                     Tools::redirect(html_entity_decode($back));
                 }
                 Tools::redirect('index.php?controller=' . ($this->authRedirection !== false ? urlencode($this->authRedirection) : $back));
             }
         }
     }
     if ($this->ajax) {
         $return = array('hasError' => !empty($this->errors), 'errors' => $this->errors, 'token' => Tools::getToken(false));
         $this->ajaxDie(Tools::jsonEncode($return));
     } else {
         $this->context->smarty->assign('authentification_error', $this->errors);
     }
 }
Beispiel #21
0
 /**
  * Process login
  */
 protected function processSubmitLogin()
 {
     Hook::exec('actionBeforeAuthentication');
     $passwd = trim(Tools::getValue('passwd'));
     $email = trim(Tools::getValue('email'));
     if (empty($email)) {
         $this->errors[] = Tools::displayError('E-mail address required');
     } elseif (!Validate::isEmail($email)) {
         $this->errors[] = Tools::displayError('Invalid e-mail address');
     } elseif (empty($passwd)) {
         $this->errors[] = Tools::displayError('Password is required');
     } elseif (!Validate::isPasswd($passwd)) {
         $this->errors[] = Tools::displayError('Invalid password');
     } else {
         $customer = new Customer();
         $authentication = $customer->getByEmail(trim($email), trim($passwd));
         if (!$authentication || !$customer->id) {
             $this->errors[] = Tools::displayError('Authentication failed');
         } else {
             $this->context->cookie->id_compare = isset($this->context->cookie->id_compare) ? $this->context->cookie->id_compare : CompareProduct::getIdCompareByIdCustomer($customer->id);
             $this->context->cookie->id_customer = (int) $customer->id;
             $this->context->cookie->customer_lastname = $customer->lastname;
             $this->context->cookie->customer_firstname = $customer->firstname;
             $this->context->cookie->logged = 1;
             $customer->logged = 1;
             $this->context->cookie->is_guest = $customer->isGuest();
             $this->context->cookie->passwd = $customer->passwd;
             $this->context->cookie->email = $customer->email;
             // Add customer to the context
             $this->context->customer = $customer;
             if (Configuration::get('PS_CART_FOLLOWING') && (empty($this->context->cookie->id_cart) || Cart::getNbProducts($this->context->cookie->id_cart) == 0)) {
                 $this->context->cookie->id_cart = (int) Cart::lastNoneOrderedCart($this->context->customer->id);
             }
             // Update cart address
             $this->context->cart->id = $this->context->cookie->id_cart;
             $this->context->cart->setDeliveryOption(null);
             $this->context->cart->id_address_delivery = Address::getFirstCustomerAddressId((int) $customer->id);
             $this->context->cart->id_address_invoice = Address::getFirstCustomerAddressId((int) $customer->id);
             $this->context->cart->secure_key = $customer->secure_key;
             $this->context->cart->update();
             $this->context->cart->autosetProductAddress();
             Hook::exec('actionAuthentication');
             // Login information have changed, so we check if the cart rules still apply
             CartRule::autoRemoveFromCart($this->context);
             CartRule::autoAddToCart($this->context);
             if (!$this->ajax) {
                 if ($back = Tools::getValue('back')) {
                     Tools::redirect(html_entity_decode($back));
                 }
                 Tools::redirect('index.php?controller=my-account');
             }
         }
     }
     if ($this->ajax) {
         $return = array('hasError' => !empty($this->errors), 'errors' => $this->errors, 'token' => Tools::getToken(false));
         die(Tools::jsonEncode($return));
     } else {
         $this->context->smarty->assign('authentification_error', $this->errors);
     }
 }
 public function postProcess()
 {
     if (isset($_POST['submitAdd' . $this->table])) {
         // Transform e-mail in id_customer for parent processing
         if ($this->addressType == 'customer') {
             if (Validate::isEmail(Tools::getValue('email'))) {
                 $customer = new Customer();
                 $customer->getByEmail(Tools::getValue('email'));
                 if (Validate::isLoadedObject($customer)) {
                     $_POST['id_customer'] = $customer->id;
                 } else {
                     $this->_errors[] = Tools::displayError('This e-mail address is not registered.');
                 }
             } elseif ($id_customer = Tools::getValue('id_customer')) {
                 $customer = new Customer((int) $id_customer);
                 if (Validate::isLoadedObject($customer)) {
                     $_POST['id_customer'] = $customer->id;
                 } else {
                     $this->_errors[] = Tools::displayError('Unknown customer');
                 }
             } else {
                 $this->_errors[] = Tools::displayError('Unknown customer');
             }
             if (Country::isNeedDniByCountryId(Tools::getValue('id_country')) and !Tools::getValue('dni')) {
                 $this->_errors[] = Tools::displayError('Identification number is incorrect or has already been used.');
             }
         }
         // Check manufacturer selected
         if ($this->addressType == 'manufacturer') {
             $manufacturer = new Manufacturer((int) Tools::getValue('id_manufacturer'));
             if (!Validate::isLoadedObject($manufacturer)) {
                 $this->_errors[] = Tools::displayError('Manufacturer selected is not valid.');
             }
         }
         /* If the selected country does not contain states */
         $id_state = (int) Tools::getValue('id_state');
         if ($id_country = Tools::getValue('id_country') and $country = new Country((int) $id_country) and !(int) $country->contains_states and $id_state) {
             $this->_errors[] = Tools::displayError('You have selected a state for a country that does not contain states.');
         }
         /* If the selected country contains states, then a state have to be selected */
         if ((int) $country->contains_states and !$id_state) {
             $this->_errors[] = Tools::displayError('An address located in a country containing states must have a state selected.');
         }
         /* Check zip code */
         if ($country->need_zip_code) {
             $zip_code_format = $country->zip_code_format;
             if ($postcode = Tools::getValue('postcode') and $zip_code_format) {
                 $zip_regexp = '/^' . $zip_code_format . '$/ui';
                 $zip_regexp = str_replace(' ', '( |)', $zip_regexp);
                 $zip_regexp = str_replace('-', '(-|)', $zip_regexp);
                 $zip_regexp = str_replace('N', '[0-9]', $zip_regexp);
                 $zip_regexp = str_replace('L', '[a-zA-Z]', $zip_regexp);
                 $zip_regexp = str_replace('C', $country->iso_code, $zip_regexp);
                 if (!preg_match($zip_regexp, $postcode)) {
                     $this->_errors[] = Tools::displayError('Your zip/postal code is incorrect.') . '<br />' . Tools::displayError('Must be typed as follows:') . ' ' . str_replace('C', $country->iso_code, str_replace('N', '0', str_replace('L', 'A', $zip_code_format)));
                 }
             } elseif ($zip_code_format) {
                 $this->_errors[] = Tools::displayError('Postcode required.');
             } elseif ($postcode and !preg_match('/^[0-9a-zA-Z -]{4,9}$/ui', $postcode)) {
                 $this->_errors[] = Tools::displayError('Your zip/postal code is incorrect.');
             }
         }
         /* If this address come from order's edition and is the same as the other one (invoice or delivery one)
          ** we delete its id_address to force the creation of a new one */
         if ((int) Tools::getValue('id_order')) {
             $this->_redirect = false;
             if (isset($_POST['address_type'])) {
                 $_POST['id_address'] = '';
             }
         }
     }
     if (!sizeof($this->_errors)) {
         parent::postProcess();
     }
     /* Reassignation of the order's new (invoice or delivery) address */
     $address_type = (int) Tools::getValue('address_type') == 2 ? 'invoice' : ((int) Tools::getValue('address_type') == 1 ? 'delivery' : '');
     if (isset($_POST['submitAdd' . $this->table]) and $id_order = (int) Tools::getValue('id_order') and !sizeof($this->_errors) and !empty($address_type)) {
         if (!Db::getInstance()->Execute('UPDATE ' . _DB_PREFIX_ . 'orders SET `id_address_' . $address_type . '` = ' . Db::getInstance()->Insert_ID() . ' WHERE `id_order` = ' . $id_order)) {
             $this->_errors[] = Tools::displayError('An error occurred while linking this address to its order.');
         } else {
             Tools::redirectAdmin(Tools::getValue('back') . '&conf=4');
         }
     }
 }
 public function handleBuyerLoginUserPassword($metadata, $request, $encoder)
 {
     // code from AuthController SubmitLogin
     $email = $request['Username'];
     $passwd = $request['Password'];
     $customer = new Customer();
     if (!Validate::isEmail($email) or $passwd and !Validate::isPasswd($passwd)) {
         CartAPI_Helpers::dieOnError($encoder, 'LoginNotAuthorized', CartAPI_Handlers_Helpers::removeHtmlTags(Tools::displayError('Authentication failed')));
     }
     $authentication = $customer->getByEmail(trim($email), trim($passwd));
     if (!$authentication or !$customer->id) {
         /* Handle brute force attacks */
         sleep(1);
         CartAPI_Helpers::dieOnError($encoder, 'LoginNotAuthorized', CartAPI_Handlers_Helpers::removeHtmlTags(Tools::displayError('Authentication failed')));
     }
     // if here than passed authentication
     $this->syncCookie($customer);
     // run the after login events
     $this->afterBuyerLogin($customer);
 }
 public function postProcess()
 {
     global $currentIndex;
     if (Tools::getValue('submitAdd' . $this->table)) {
         $groupList = Tools::getValue('groupBox');
         /* Checking fields validity */
         $this->validateRules();
         if (!sizeof($this->_errors)) {
             $id = intval(Tools::getValue('id_' . $this->table));
             if (isset($id) and !empty($id)) {
                 if ($this->tabAccess['edit'] !== '1') {
                     $this->_errors[] = Tools::displayError('You do not have permission to edit anything here.');
                 } else {
                     $object = new $this->className($id);
                     if (Validate::isLoadedObject($object)) {
                         $customer_email = strval(Tools::getValue('email'));
                         // check if e-mail already used
                         if ($customer_email != $object->email) {
                             $customer = new Customer();
                             $customer->getByEmail($customer_email);
                             if ($customer->id) {
                                 $this->_errors[] = Tools::displayError('an account already exists for this e-mail address:') . ' ' . $customer_email;
                             }
                         }
                         if ($object->getNeedDNI() and Tools::getValue('dni') != NULL and !Validate::isDni(Tools::getValue('dni'))) {
                             $this->_errors[] = Tools::displayError('identification number is incorrect or already used');
                         }
                         if (!is_array($groupList) or sizeof($groupList) == 0) {
                             $this->_errors[] = Tools::displayError('customer must be in at least one group');
                         } else {
                             if (!in_array(Tools::getValue('id_default_group'), $groupList)) {
                                 $this->_errors[] = Tools::displayError('default customer group must be selected on group box');
                             }
                         }
                         // Updating customer's group
                         if (!sizeof($this->_errors)) {
                             $object->cleanGroups();
                             if (is_array($groupList) and sizeof($groupList) > 0) {
                                 $object->addGroups($groupList);
                             }
                         }
                     } else {
                         $this->_errors[] = Tools::displayError('an error occurred while loading object') . ' <b>' . $this->table . '</b> ' . Tools::displayError('(cannot load object)');
                     }
                 }
             } else {
                 if ($this->tabAccess['add'] === '1') {
                     $object = new $this->className();
                     $this->copyFromPost($object, $this->table);
                     if (!$object->add()) {
                         $this->_errors[] = Tools::displayError('an error occurred while creating object') . ' <b>' . $this->table . ' (' . mysql_error() . ')</b>';
                     } elseif ($_POST[$this->identifier] = $object->id and $this->postImage($object->id) and !sizeof($this->_errors) and $this->_redirect) {
                         // Add Associated groups
                         $group_list = Tools::getValue('groupBox');
                         if (is_array($group_list) && sizeof($group_list) > 0) {
                             $object->addGroups($group_list, true);
                         }
                         $parent_id = intval(Tools::getValue('id_parent', 1));
                         // Save and stay on same form
                         if (Tools::isSubmit('submitAdd' . $this->table . 'AndStay')) {
                             Tools::redirectAdmin($currentIndex . '&' . $this->identifier . '=' . $object->id . '&conf=3&update' . $this->table . '&token=' . $this->token);
                         }
                         // Save and back to parent
                         if (Tools::isSubmit('submitAdd' . $this->table . 'AndBackToParent')) {
                             Tools::redirectAdmin($currentIndex . '&' . $this->identifier . '=' . $parent_id . '&conf=3&token=' . $this->token);
                         }
                         // Default behavior (save and back)
                         Tools::redirectAdmin($currentIndex . ($parent_id ? '&' . $this->identifier . '=' . $object->id : '') . '&conf=3&token=' . $this->token);
                     }
                 } else {
                     $this->_errors[] = Tools::displayError('You do not have permission to add anything here.');
                 }
             }
         }
     }
     return parent::postProcess();
 }
 public function preProcess()
 {
     parent::preProcess();
     if (self::$cookie->isLogged() and !Tools::isSubmit('ajax')) {
         Tools::redirect('my-account.php');
     }
     if (Tools::getValue('create_account')) {
         $create_account = 1;
         self::$smarty->assign('email_create', 1);
     }
     if (Tools::isSubmit('SubmitCreate')) {
         if (!Validate::isEmail($email = Tools::getValue('email_create')) or empty($email)) {
             $this->errors[] = Tools::displayError('Invalid e-mail address');
         } elseif (Customer::customerExists($email)) {
             $this->errors[] = Tools::displayError('An account is already registered with this e-mail, please fill in the password or request a new one.');
             $_POST['email'] = $_POST['email_create'];
             unset($_POST['email_create']);
         } else {
             $create_account = 1;
             self::$smarty->assign('email_create', Tools::safeOutput($email));
             $_POST['email'] = $email;
         }
     }
     if (Tools::isSubmit('submitAccount') or Tools::isSubmit('submitGuestAccount')) {
         $create_account = 1;
         if (Tools::isSubmit('submitAccount')) {
             self::$smarty->assign('email_create', 1);
         }
         /* New Guest customer */
         if (!Tools::getValue('is_new_customer', 1) and !Configuration::get('PS_GUEST_CHECKOUT_ENABLED')) {
             $this->errors[] = Tools::displayError('You cannot create a guest account.');
         }
         if (!Tools::getValue('is_new_customer', 1)) {
             $_POST['passwd'] = md5(time() . _COOKIE_KEY_);
         }
         if (isset($_POST['guest_email']) and $_POST['guest_email']) {
             $_POST['email'] = $_POST['guest_email'];
         }
         /* Preparing customer */
         $customer = new Customer();
         $lastnameAddress = $_POST['lastname'];
         $firstnameAddress = $_POST['firstname'];
         $_POST['lastname'] = $_POST['customer_lastname'];
         $_POST['firstname'] = $_POST['customer_firstname'];
         if (!Tools::getValue('phone') and !Tools::getValue('phone_mobile')) {
             $this->errors[] = Tools::displayError('You must register at least one phone number');
         }
         if (!@checkdate(Tools::getValue('months'), Tools::getValue('days'), Tools::getValue('years')) and !(Tools::getValue('months') == '' and Tools::getValue('days') == '' and Tools::getValue('years') == '')) {
             $this->errors[] = Tools::displayError('Invalid date of birth');
         }
         $customer->birthday = empty($_POST['years']) ? '' : (int) $_POST['years'] . '-' . (int) $_POST['months'] . '-' . (int) $_POST['days'];
         $this->errors = array_unique(array_merge($this->errors, $customer->validateControler()));
         /* Preparing address */
         $address = new Address();
         $_POST['lastname'] = $lastnameAddress;
         $_POST['firstname'] = $firstnameAddress;
         $address->id_customer = 1;
         $this->errors = array_unique(array_merge($this->errors, $address->validateControler()));
         /* US customer: normalize the address */
         if ($address->id_country == Country::getByIso('US')) {
             include_once _PS_TAASC_PATH_ . 'AddressStandardizationSolution.php';
             $normalize = new AddressStandardizationSolution();
             $address->address1 = $normalize->AddressLineStandardization($address->address1);
             $address->address2 = $normalize->AddressLineStandardization($address->address2);
         }
         $zip_code_format = Country::getZipCodeFormat((int) Tools::getValue('id_country'));
         if (Country::getNeedZipCode((int) Tools::getValue('id_country'))) {
             if ($postcode = Tools::getValue('postcode') and $zip_code_format) {
                 $zip_regexp = '/^' . $zip_code_format . '$/ui';
                 $zip_regexp = str_replace(' ', '( |)', $zip_regexp);
                 $zip_regexp = str_replace('-', '(-|)', $zip_regexp);
                 $zip_regexp = str_replace('N', '[0-9]', $zip_regexp);
                 $zip_regexp = str_replace('L', '[a-zA-Z]', $zip_regexp);
                 $zip_regexp = str_replace('C', Country::getIsoById((int) Tools::getValue('id_country')), $zip_regexp);
                 if (!preg_match($zip_regexp, $postcode)) {
                     $this->errors[] = '<strong>' . Tools::displayError('Zip/ Postal code') . '</strong> ' . Tools::displayError('is invalid.') . '<br />' . Tools::displayError('Must be typed as follows:') . ' ' . str_replace('C', Country::getIsoById((int) Tools::getValue('id_country')), str_replace('N', '0', str_replace('L', 'A', $zip_code_format)));
                 }
             } elseif ($zip_code_format) {
                 $this->errors[] = '<strong>' . Tools::displayError('Zip/ Postal code') . '</strong> ' . Tools::displayError('is required.');
             } elseif ($postcode and !preg_match('/^[0-9a-zA-Z -]{4,9}$/ui', $postcode)) {
                 $this->errors[] = '<strong>' . Tools::displayError('Zip/ Postal code') . '</strong> ' . Tools::displayError('is invalid.');
             }
         }
         if (Country::isNeedDniByCountryId($address->id_country) and (!Tools::getValue('dni') or !Validate::isDniLite(Tools::getValue('dni')))) {
             $this->errors[] = Tools::displayError('Identification number is incorrect or has already been used.');
         } elseif (!Country::isNeedDniByCountryId($address->id_country)) {
             $address->dni = NULL;
         }
         if (!sizeof($this->errors)) {
             if (Customer::customerExists(Tools::getValue('email'))) {
                 $this->errors[] = Tools::displayError('An account is already registered with this e-mail, please fill in the password or request a new one.');
             }
             if (Tools::isSubmit('newsletter')) {
                 $customer->ip_registration_newsletter = pSQL(Tools::getRemoteAddr());
                 $customer->newsletter_date_add = pSQL(date('Y-m-d H:i:s'));
             }
             if (!sizeof($this->errors)) {
                 if (!($country = new Country($address->id_country, Configuration::get('PS_LANG_DEFAULT'))) or !Validate::isLoadedObject($country)) {
                     die(Tools::displayError());
                 }
                 if ((int) $country->contains_states and !(int) $address->id_state) {
                     $this->errors[] = Tools::displayError('This country requires a state selection.');
                 } else {
                     $customer->active = 1;
                     /* New Guest customer */
                     if (Tools::isSubmit('is_new_customer')) {
                         $customer->is_guest = !Tools::getValue('is_new_customer', 1);
                     } else {
                         $customer->is_guest = 0;
                     }
                     if (!$customer->add()) {
                         $this->errors[] = Tools::displayError('An error occurred while creating your account.');
                     } else {
                         $address->id_customer = (int) $customer->id;
                         if (!$address->add()) {
                             $this->errors[] = Tools::displayError('An error occurred while creating your address.');
                         } else {
                             if (!$customer->is_guest) {
                                 if (!Mail::Send((int) self::$cookie->id_lang, 'account', Mail::l('Welcome!'), array('{firstname}' => $customer->firstname, '{lastname}' => $customer->lastname, '{email}' => $customer->email, '{passwd}' => Tools::getValue('passwd')), $customer->email, $customer->firstname . ' ' . $customer->lastname)) {
                                     $this->errors[] = Tools::displayError('Cannot send email');
                                 }
                             }
                             self::$smarty->assign('confirmation', 1);
                             self::$cookie->id_customer = (int) $customer->id;
                             self::$cookie->customer_lastname = $customer->lastname;
                             self::$cookie->customer_firstname = $customer->firstname;
                             self::$cookie->passwd = $customer->passwd;
                             self::$cookie->logged = 1;
                             self::$cookie->email = $customer->email;
                             self::$cookie->is_guest = !Tools::getValue('is_new_customer', 1);
                             /* Update cart address */
                             self::$cart->secure_key = $customer->secure_key;
                             self::$cart->id_address_delivery = Address::getFirstCustomerAddressId((int) $customer->id);
                             self::$cart->id_address_invoice = Address::getFirstCustomerAddressId((int) $customer->id);
                             self::$cart->update();
                             Module::hookExec('createAccount', array('_POST' => $_POST, 'newCustomer' => $customer));
                             if (Tools::isSubmit('ajax')) {
                                 $return = array('hasError' => !empty($this->errors), 'errors' => $this->errors, 'isSaved' => true, 'id_customer' => (int) self::$cookie->id_customer, 'id_address_delivery' => self::$cart->id_address_delivery, 'id_address_invoice' => self::$cart->id_address_invoice, 'token' => Tools::getToken(false));
                                 die(Tools::jsonEncode($return));
                             }
                             if ($back = Tools::getValue('back')) {
                                 Tools::redirect($back);
                             }
                             Tools::redirect('my-account.php');
                         }
                     }
                 }
             }
         }
         if (sizeof($this->errors)) {
             if (!Tools::getValue('is_new_customer')) {
                 unset($_POST['passwd']);
             }
             if (Tools::isSubmit('ajax')) {
                 $return = array('hasError' => !empty($this->errors), 'errors' => $this->errors, 'isSaved' => false, 'id_customer' => 0);
                 die(Tools::jsonEncode($return));
             }
         }
     }
     if (Tools::isSubmit('SubmitLogin')) {
         Module::hookExec('beforeAuthentication');
         $passwd = trim(Tools::getValue('passwd'));
         $email = trim(Tools::getValue('email'));
         if (empty($email)) {
             $this->errors[] = Tools::displayError('E-mail address required');
         } elseif (!Validate::isEmail($email)) {
             $this->errors[] = Tools::displayError('Invalid e-mail address');
         } elseif (empty($passwd)) {
             $this->errors[] = Tools::displayError('Password is required');
         } elseif (Tools::strlen($passwd) > 32) {
             $this->errors[] = Tools::displayError('Password is too long');
         } elseif (!Validate::isPasswd($passwd)) {
             $this->errors[] = Tools::displayError('Invalid password');
         } else {
             $customer = new Customer();
             $authentication = $customer->getByEmail(trim($email), trim($passwd));
             if (!$authentication or !$customer->id) {
                 /* Handle brute force attacks */
                 sleep(1);
                 $this->errors[] = Tools::displayError('Authentication failed');
             } else {
                 self::$cookie->id_compare = isset(self::$cookie->id_compare) ? self::$cookie->id_compare : CompareProduct::getIdCompareByIdCustomer($customer->id);
                 self::$cookie->id_customer = (int) $customer->id;
                 self::$cookie->customer_lastname = $customer->lastname;
                 self::$cookie->customer_firstname = $customer->firstname;
                 self::$cookie->id_default_group = $customer->id_default_group;
                 self::$cookie->logged = 1;
                 self::$cookie->is_guest = $customer->isGuest();
                 self::$cookie->passwd = $customer->passwd;
                 self::$cookie->email = $customer->email;
                 if (Configuration::get('PS_CART_FOLLOWING') and (empty(self::$cookie->id_cart) or Cart::getNbProducts(self::$cookie->id_cart) == 0)) {
                     self::$cookie->id_cart = (int) Cart::lastNoneOrderedCart((int) $customer->id);
                 }
                 /* Update cart address */
                 self::$cart->id_carrier = 0;
                 self::$cart->id_address_delivery = Address::getFirstCustomerAddressId((int) $customer->id);
                 self::$cart->id_address_invoice = Address::getFirstCustomerAddressId((int) $customer->id);
                 // If a logged guest logs in as a customer, the cart secure key was already set and needs to be updated
                 self::$cart->secure_key = $customer->secure_key;
                 self::$cart->update();
                 Module::hookExec('authentication');
                 if (!Tools::isSubmit('ajax')) {
                     if ($back = Tools::getValue('back')) {
                         Tools::redirect($back);
                     }
                     Tools::redirect('my-account.php');
                 }
             }
         }
         if (Tools::isSubmit('ajax')) {
             $return = array('hasError' => !empty($this->errors), 'errors' => $this->errors, 'token' => Tools::getToken(false));
             die(Tools::jsonEncode($return));
         }
     }
     if (isset($create_account)) {
         /* Select the most appropriate country */
         if (isset($_POST['id_country']) and is_numeric($_POST['id_country'])) {
             $selectedCountry = (int) $_POST['id_country'];
         }
         /* FIXME : language iso and country iso are not similar,
         			 * maybe an associative table with country an language can resolve it,
         			 * But for now it's a bug !
         			 * @see : bug #6968
         			 * @link:http://www.prestashop.com/bug_tracker/view/6968/
         			elseif (isset($_SERVER['HTTP_ACCEPT_LANGUAGE']))
         			{
         				$array = explode(',', $_SERVER['HTTP_ACCEPT_LANGUAGE']);
         				if (Validate::isLanguageIsoCode($array[0]))
         				{
         					$selectedCountry = Country::getByIso($array[0]);
         					if (!$selectedCountry)
         						$selectedCountry = (int)(Configuration::get('PS_COUNTRY_DEFAULT'));
         				}
         			}*/
         if (!isset($selectedCountry)) {
             $selectedCountry = (int) Configuration::get('PS_COUNTRY_DEFAULT');
         }
         if (Configuration::get('PS_RESTRICT_DELIVERED_COUNTRIES')) {
             $countries = Carrier::getDeliveredCountries((int) self::$cookie->id_lang, true, true);
         } else {
             $countries = Country::getCountries((int) self::$cookie->id_lang, true);
         }
         self::$smarty->assign(array('countries' => $countries, 'sl_country' => isset($selectedCountry) ? $selectedCountry : 0, 'vat_management' => Configuration::get('VATNUMBER_MANAGEMENT')));
         /* Call a hook to display more information on form */
         self::$smarty->assign(array('HOOK_CREATE_ACCOUNT_FORM' => Module::hookExec('createAccountForm'), 'HOOK_CREATE_ACCOUNT_TOP' => Module::hookExec('createAccountTop')));
     }
     /* Generate years, months and days */
     if (isset($_POST['years']) and is_numeric($_POST['years'])) {
         $selectedYears = (int) $_POST['years'];
     }
     $years = Tools::dateYears();
     if (isset($_POST['months']) and is_numeric($_POST['months'])) {
         $selectedMonths = (int) $_POST['months'];
     }
     $months = Tools::dateMonths();
     if (isset($_POST['days']) and is_numeric($_POST['days'])) {
         $selectedDays = (int) $_POST['days'];
     }
     $days = Tools::dateDays();
     self::$smarty->assign(array('years' => $years, 'sl_year' => isset($selectedYears) ? $selectedYears : 0, 'months' => $months, 'sl_month' => isset($selectedMonths) ? $selectedMonths : 0, 'days' => $days, 'sl_day' => isset($selectedDays) ? $selectedDays : 0));
     self::$smarty->assign('newsletter', (int) Module::getInstanceByName('blocknewsletter')->active);
 }
    public function preProcess()
    {
        parent::preProcess();
        if (self::$cookie->isLogged()) {
            self::$smarty->assign('isLogged', 1);
            $customer = new Customer((int) self::$cookie->id_customer);
            if (!Validate::isLoadedObject($customer)) {
                die(Tools::displayError('Customer not found'));
            }
            $products = array();
            $orders = array();
            $getOrders = Db::getInstance()->ExecuteS('
				SELECT id_order
				FROM ' . _DB_PREFIX_ . 'orders
				WHERE id_customer = ' . (int) $customer->id . ' ORDER BY date_add');
            foreach ($getOrders as $row) {
                $order = new Order($row['id_order']);
                $date = explode(' ', $order->date_add);
                $orders[$row['id_order']] = Tools::displayDate($date[0], self::$cookie->id_lang);
                $tmp = $order->getProducts();
                foreach ($tmp as $key => $val) {
                    $products[$val['product_id']] = $val['product_name'];
                }
            }
            $orderList = '';
            foreach ($orders as $key => $val) {
                $orderList .= '<option value="' . $key . '" ' . ((int) Tools::getValue('id_order') == $key ? 'selected' : '') . ' >' . $key . ' -- ' . $val . '</option>';
            }
            $orderedProductList = '';
            foreach ($products as $key => $val) {
                $orderedProductList .= '<option value="' . $key . '" ' . ((int) Tools::getValue('id_product') == $key ? 'selected' : '') . ' >' . $val . '</option>';
            }
            self::$smarty->assign('orderList', $orderList);
            self::$smarty->assign('orderedProductList', $orderedProductList);
        }
        if (Tools::isSubmit('submitMessage')) {
            $fileAttachment = NULL;
            if (isset($_FILES['fileUpload']['name']) and !empty($_FILES['fileUpload']['name']) and !empty($_FILES['fileUpload']['tmp_name'])) {
                $extension = array('.txt', '.rtf', '.doc', '.docx', '.pdf', '.zip', '.png', '.jpeg', '.gif', '.jpg');
                $filename = uniqid() . substr($_FILES['fileUpload']['name'], -5);
                $fileAttachment['content'] = file_get_contents($_FILES['fileUpload']['tmp_name']);
                $fileAttachment['name'] = $_FILES['fileUpload']['name'];
                $fileAttachment['mime'] = $_FILES['fileUpload']['type'];
            }
            $message = Tools::htmlentitiesUTF8(Tools::getValue('message'));
            if (!($from = trim(Tools::getValue('from'))) or !Validate::isEmail($from)) {
                $this->errors[] = Tools::displayError('Invalid e-mail address');
            } elseif (!($message = nl2br2($message))) {
                $this->errors[] = Tools::displayError('Message cannot be blank');
            } elseif (!Validate::isCleanHtml($message)) {
                $this->errors[] = Tools::displayError('Invalid message');
            } elseif (!($id_contact = (int) Tools::getValue('id_contact')) or !Validate::isLoadedObject($contact = new Contact((int) $id_contact, (int) self::$cookie->id_lang))) {
                $this->errors[] = Tools::displayError('Please select a subject on the list.');
            } elseif (!empty($_FILES['fileUpload']['name']) and $_FILES['fileUpload']['error'] != 0) {
                $this->errors[] = Tools::displayError('An error occurred during the file upload');
            } elseif (!empty($_FILES['fileUpload']['name']) and !in_array(substr($_FILES['fileUpload']['name'], -4), $extension) and !in_array(substr($_FILES['fileUpload']['name'], -5), $extension)) {
                $this->errors[] = Tools::displayError('Bad file extension');
            } else {
                if ((int) self::$cookie->id_customer) {
                    $customer = new Customer((int) self::$cookie->id_customer);
                } else {
                    $customer = new Customer();
                    $customer->getByEmail($from);
                }
                $contact = new Contact($id_contact, self::$cookie->id_lang);
                if (!($id_customer_thread = (int) Tools::getValue('id_customer_thread') and (int) Db::getInstance()->getValue('
						SELECT cm.id_customer_thread FROM ' . _DB_PREFIX_ . 'customer_thread cm
						WHERE cm.id_customer_thread = ' . (int) $id_customer_thread . ' AND token = \'' . pSQL(Tools::getValue('token')) . '\'') or $id_customer_thread = (int) Db::getInstance()->getValue('
						SELECT cm.id_customer_thread FROM ' . _DB_PREFIX_ . 'customer_thread cm
						WHERE cm.email = \'' . pSQL($from) . '\' AND cm.id_order = ' . (int) Tools::getValue('id_order') . ''))) {
                    $fields = Db::getInstance()->ExecuteS('
					SELECT cm.id_customer_thread, cm.id_contact, cm.id_customer, cm.id_order, cm.id_product, cm.email
					FROM ' . _DB_PREFIX_ . 'customer_thread cm
					WHERE email = \'' . pSQL($from) . '\' AND (' . ($customer->id ? 'id_customer = ' . (int) $customer->id . ' OR ' : '') . '
						id_order = ' . (int) Tools::getValue('id_order') . ')');
                    $score = 0;
                    foreach ($fields as $key => $row) {
                        $tmp = 0;
                        if ((int) $row['id_customer'] and $row['id_customer'] != $customer->id and $row['email'] != $from) {
                            continue;
                        }
                        if ($row['id_order'] != 0 and Tools::getValue('id_order') != $row['id_order']) {
                            continue;
                        }
                        if ($row['email'] == $from) {
                            $tmp += 4;
                        }
                        if ($row['id_contact'] == $id_contact) {
                            $tmp++;
                        }
                        if (Tools::getValue('id_product') != 0 and $row['id_product'] == Tools::getValue('id_product')) {
                            $tmp += 2;
                        }
                        if ($tmp >= 5 and $tmp >= $score) {
                            $score = $tmp;
                            $id_customer_thread = $row['id_customer_thread'];
                        }
                    }
                }
                $old_message = Db::getInstance()->getValue('
					SELECT cm.message FROM ' . _DB_PREFIX_ . 'customer_message cm
					WHERE cm.id_customer_thread = ' . (int) $id_customer_thread . '
					ORDER BY date_add DESC');
                if ($old_message == htmlentities($message, ENT_COMPAT, 'UTF-8')) {
                    self::$smarty->assign('alreadySent', 1);
                    $contact->email = '';
                    $contact->customer_service = 0;
                }
                if (!empty($contact->email)) {
                    if (Mail::Send((int) self::$cookie->id_lang, 'contact', Mail::l('Message from contact form'), array('{email}' => $from, '{message}' => stripslashes($message)), $contact->email, $contact->name, $from, (int) self::$cookie->id_customer ? $customer->firstname . ' ' . $customer->lastname : '', $fileAttachment) and Mail::Send((int) self::$cookie->id_lang, 'contact_form', Mail::l('Your message has been correctly sent'), array('{message}' => stripslashes($message)), $from)) {
                        self::$smarty->assign('confirmation', 1);
                    } else {
                        $this->errors[] = Tools::displayError('An error occurred while sending message.');
                    }
                }
                if ($contact->customer_service) {
                    if ((int) $id_customer_thread) {
                        $ct = new CustomerThread($id_customer_thread);
                        $ct->status = 'open';
                        $ct->id_lang = (int) self::$cookie->id_lang;
                        $ct->id_contact = (int) $id_contact;
                        if ($id_order = (int) Tools::getValue('id_order')) {
                            $ct->id_order = $id_order;
                        }
                        if ($id_product = (int) Tools::getValue('id_product')) {
                            $ct->id_product = $id_product;
                        }
                        $ct->update();
                    } else {
                        $ct = new CustomerThread();
                        if (isset($customer->id)) {
                            $ct->id_customer = (int) $customer->id;
                        }
                        if ($id_order = (int) Tools::getValue('id_order')) {
                            $ct->id_order = $id_order;
                        }
                        if ($id_product = (int) Tools::getValue('id_product')) {
                            $ct->id_product = $id_product;
                        }
                        $ct->id_contact = (int) $id_contact;
                        $ct->id_lang = (int) self::$cookie->id_lang;
                        $ct->email = $from;
                        $ct->status = 'open';
                        $ct->token = Tools::passwdGen(12);
                        $ct->add();
                    }
                    if ($ct->id) {
                        $cm = new CustomerMessage();
                        $cm->id_customer_thread = $ct->id;
                        $cm->message = htmlentities($message, ENT_COMPAT, 'UTF-8');
                        if (isset($filename) and rename($_FILES['fileUpload']['tmp_name'], _PS_MODULE_DIR_ . '../upload/' . $filename)) {
                            $cm->file_name = $filename;
                        }
                        $cm->ip_address = ip2long($_SERVER['REMOTE_ADDR']);
                        $cm->user_agent = $_SERVER['HTTP_USER_AGENT'];
                        if ($cm->add()) {
                            if (empty($contact->email)) {
                                Mail::Send((int) self::$cookie->id_lang, 'contact_form', Mail::l('Your message has been correctly sent'), array('{message}' => stripslashes($message)), $from);
                            }
                            self::$smarty->assign('confirmation', 1);
                        } else {
                            $this->errors[] = Tools::displayError('An error occurred while sending message.');
                        }
                    } else {
                        $this->errors[] = Tools::displayError('An error occurred while sending message.');
                    }
                }
                if (count($this->errors) > 1) {
                    array_unique($this->errors);
                }
            }
        }
    }
 protected function authenticateUser()
 {
     if ($this->context->customer->id !== null) {
         $this->customer_id = $this->context->customer->id;
         return;
     }
     $email = Tools::getValue('email');
     if (!Validate::isEmail($email)) {
         return;
     }
     //get customer
     $customer = new Customer();
     $result = $customer->getByEmail($email);
     if (!$result || !Validate::isLoadedObject($customer)) {
         return false;
     }
     $this->customer_id = $customer->id;
 }
Beispiel #28
0
 public function preProcess()
 {
     if (Tools::isSubmit('SubmitLogin') || Tools::getValue('SubmitLogin')) {
         Module::hookExec('beforeAuthentication');
         $passwd = trim(Tools::getValue('passwd'));
         $email = trim(Tools::getValue('email'));
         if (empty($email)) {
             $this->errors[] = Tools::displayError('E-mail address required');
         } elseif (!Validate::isEmail($email)) {
             $this->errors[] = Tools::displayError('Invalid e-mail address');
         } elseif (empty($passwd)) {
             $this->errors[] = Tools::displayError('Password is required');
         } elseif (Tools::strlen($passwd) > 32) {
             $this->errors[] = Tools::displayError('Password is too long');
         } elseif (!Validate::isPasswd($passwd)) {
             $this->errors[] = Tools::displayError('Invalid password');
         } else {
             $customer = new Customer();
             $authentication = $customer->getByEmail(trim($email), trim($passwd));
             if (!$authentication or !$customer->id) {
                 /* Handle brute force attacks */
                 sleep(1);
                 $this->errors[] = Tools::displayError('Authentication failed');
             } else {
                 self::$cookie->id_customer = (int) $customer->id;
                 self::$cookie->customer_lastname = $customer->lastname;
                 self::$cookie->customer_firstname = $customer->firstname;
                 self::$cookie->logged = 1;
                 self::$cookie->is_guest = $customer->isGuest();
                 self::$cookie->passwd = $customer->passwd;
                 self::$cookie->email = $customer->email;
                 if (Configuration::get('PS_CART_FOLLOWING') and (empty(self::$cookie->id_cart) or Cart::getNbProducts(self::$cookie->id_cart) == 0)) {
                     self::$cookie->id_cart = (int) Cart::lastNoneOrderedCart((int) $customer->id);
                 }
                 /* Update cart address */
                 self::$cart->id_carrier = 0;
                 self::$cart->id_address_delivery = Address::getFirstCustomerAddressId((int) $customer->id);
                 self::$cart->id_address_invoice = Address::getFirstCustomerAddressId((int) $customer->id);
                 self::$cart->update();
                 Module::hookExec('authentication');
                 if (!Tools::isSubmit('ajax')) {
                     if ($back = Tools::getValue('back')) {
                         Tools::redirect($back);
                     }
                     Tools::redirect('history.php');
                 }
             }
         }
         if (Tools::getValue('ajax')) {
             $return = array('hasError' => !empty($this->errors), 'errors' => $this->errors, 'token' => Tools::getToken(false));
             die(Tools::jsonEncode($return));
         }
     }
 }
 public function processSave()
 {
     if (Tools::getValue('submitFormAjax')) {
         $this->redirect_after = false;
     }
     // Transform e-mail in id_customer for parent processing
     if (Validate::isEmail(Tools::getValue('email'))) {
         $customer = new Customer();
         $customer->getByEmail(Tools::getValue('email'), null, false);
         if (Validate::isLoadedObject($customer)) {
             $_POST['id_customer'] = $customer->id;
         } else {
             $this->errors[] = Tools::displayError('This email address is not registered.');
         }
     } else {
         if ($id_customer = Tools::getValue('id_customer')) {
             $customer = new Customer((int) $id_customer);
             if (Validate::isLoadedObject($customer)) {
                 $_POST['id_customer'] = $customer->id;
             } else {
                 $this->errors[] = Tools::displayError('Unknown customer');
             }
         } else {
             $this->errors[] = Tools::displayError('Unknown customer');
         }
     }
     if (Country::isNeedDniByCountryId(Tools::getValue('id_country')) && !Tools::getValue('dni')) {
         $this->errors[] = Tools::displayError('The identification number is incorrect or has already been used.');
     }
     /* If the selected country does not contain states */
     $id_state = (int) Tools::getValue('id_state');
     $id_country = (int) Tools::getValue('id_country');
     $country = new Country((int) $id_country);
     if ($country && !(int) $country->contains_states && $id_state) {
         $this->errors[] = Tools::displayError('You have selected a state for a country that does not contain states.');
     }
     /* If the selected country contains states, then a state have to be selected */
     if ((int) $country->contains_states && !$id_state) {
         $this->errors[] = Tools::displayError('An address located in a country containing states must have a state selected.');
     }
     $postcode = Tools::getValue('postcode');
     /* Check zip code format */
     if ($country->zip_code_format && !$country->checkZipCode($postcode)) {
         $this->errors[] = Tools::displayError('Your Zip/postal code is incorrect.') . '<br />' . Tools::displayError('It must be entered as follows:') . ' ' . str_replace('C', $country->iso_code, str_replace('N', '0', str_replace('L', 'A', $country->zip_code_format)));
     } elseif (empty($postcode) && $country->need_zip_code) {
         $this->errors[] = Tools::displayError('A Zip/postal code is required.');
     } elseif ($postcode && !Validate::isPostCode($postcode)) {
         $this->errors[] = Tools::displayError('The Zip/postal code is invalid.');
     }
     if (Configuration::get('PS_ONE_PHONE_AT_LEAST') && !Tools::getValue('phone') && !Tools::getValue('phone_mobile')) {
         $this->errors[] = Tools::displayError('You must register at least one phone number.');
     }
     /* If this address come from order's edition and is the same as the other one (invoice or delivery one)
      ** we delete its id_address to force the creation of a new one */
     if ((int) Tools::getValue('id_order')) {
         $this->_redirect = false;
         if (isset($_POST['address_type'])) {
             $_POST['id_address'] = '';
         }
     }
     // Check the requires fields which are settings in the BO
     $address = new Address();
     $this->errors = array_merge($this->errors, $address->validateFieldsRequiredDatabase());
     if (empty($this->errors)) {
         return parent::processSave();
     } else {
         // if we have errors, we stay on the form instead of going back to the list
         $this->display = 'edit';
     }
     /* Reassignation of the order's new (invoice or delivery) address */
     $address_type = (int) Tools::getValue('address_type') == 2 ? 'invoice' : ((int) Tools::getValue('address_type') == 1 ? 'delivery' : '');
     if ($this->action == 'save' && ($id_order = (int) Tools::getValue('id_order')) && !count($this->errors) && !empty($address_type)) {
         if (!Db::getInstance()->execute('UPDATE ' . _DB_PREFIX_ . 'orders SET `id_address_' . $address_type . '` = ' . Db::getInstance()->Insert_ID() . ' WHERE `id_order` = ' . $id_order)) {
             $this->errors[] = Tools::displayError('An error occurred while linking this address to its order.');
         } else {
             Tools::redirectAdmin(Tools::getValue('back') . '&conf=4');
         }
     }
 }
 public function alertOrderStatus($data)
 {
     $order = $this->module->getOrderByYaId((int) $data->order->id);
     if ($order->id_cart > 0) {
         $status = $data->order->status;
         if ($status == 'CANCELLED') {
             $sub = $data->order->substatus;
             if (isset($sub) && $sub == 'RESERVATION_EXPIRED') {
                 $order->setCurrentState((int) $this->module->status['RESERVATION_EXPIRED']);
             } else {
                 $order->setCurrentState((int) $this->module->status['CANCELLED']);
             }
         }
         if ($status == 'PROCESSING') {
             $buyer = isset($data->order->buyer) ? $data->order->buyer : '';
             if (isset($buyer) && !empty($buyer)) {
                 $customer = new Customer();
                 $c = $customer->getByEmail($buyer->email);
                 if (isset($c->id) && $c->id > 0) {
                     $customer = new Customer($c->id);
                 } else {
                     $customer->firstname = $buyer->firstName;
                     $customer->lastname = $buyer->lastName;
                     $customer->email = $buyer->email;
                     $customer->passwd = Tools::encrypt('OPC123456dmo');
                     $customer->newsletter = 1;
                     $customer->optin = 1;
                     $customer->active = 1;
                     $customer->save();
                 }
                 $address = new Address($order->id_address_delivery);
                 $address->id_customer = $customer->id;
                 $order->id_customer = $customer->id;
                 $order->save();
                 $address->save();
             }
             $order->setCurrentState((int) $this->module->status['PROCESSING']);
         }
         if ($status == 'UNPAID') {
             $order->setCurrentState($this->module->status['UNPAID']);
         }
         die(1);
     }
 }