/**
     * @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');
    }
Exemple #2
0
 public function create()
 {
     if ($this->f3->exists('POST.create')) {
         $user = new Customer($this->db);
         $user->add();
         $this->f3->reroute('/customer');
     } else {
         $this->f3->set('page_head', 'Create Customer');
         $this->f3->set('view', 'customer/create.htm');
     }
     echo Template::instance()->render('layout.htm');
 }
Exemple #3
0
 public function helloWorld()
 {
     $obj = new Customer();
     $obj->fname = 'Monika';
     $obj->lname = "x' or 'x'='x";
     $obj->email = '*****@*****.**';
     $obj->password = md5('123456');
     $obj->date = date('Y-m-d H:i:s');
     try {
         $return = $obj->add();
     } catch (Exception $e) {
         die($e->getMessage());
     }
 }
 /**
  * Create virtual customer to associate address for country selection
  *
  * @return bool
  */
 private function createCustomer()
 {
     $customer = new Customer();
     $customer->email = 'shipping_estimation@prestashop_virtual.com';
     $customer->lastname = 'Shipping';
     $customer->firstname = 'Estimation';
     $customer->deleted = 1;
     // Keep it Hidden
     $customer->passwd = Tools::encrypt(Tools::passwdGen());
     if ($customer->add()) {
         Configuration::updateValue(CarrierCompare::VIRTUAL_CUSTOMER, $customer->id);
         return true;
     }
     return false;
 }
 public function action_add_customer()
 {
     if (count($_POST)) {
         $post = new Validation($_POST);
         $post->filter('trim');
         if ($post->validate()) {
             $customer_id = Customer::add($post->as_array());
             $this->add_message('Customer ' . $post->get('name') . ' added with ID #' . $customer_id);
         } else {
             $this->add_error('Fix errors and try again');
             $this->add_form_errors($post->errors());
             $this->set_formdata($post->as_array());
         }
     }
 }
function customer_add()
{
    $customer = new Customer();
    $customer->name = isset($_POST['name']) ? $_POST['name'] : "";
    $customer->address = isset($_POST['address']) ? $_POST['address'] : "";
    $customer->phone = isset($_POST['phone']) ? $_POST['phone'] : "";
    $customer->cell = isset($_POST['cell']) ? $_POST['cell'] : "";
    $customer->active = isset($_POST['active']) ? $_POST['active'] : 0;
    $customer->email = isset($_POST['email']) ? $_POST['email'] : "";
    $customer->nit = isset($_POST['nit']) ? $_POST['nit'] : "";
    if ($customer->add()) {
        $params = array("customer" => $customer->id);
        header("location: " . Forms::getLink(FORM_CUSTOMER_DETAIL, $params));
        exit;
    }
    return false;
}
Exemple #7
0
 public function register()
 {
     if (post('register')) {
         $pengguna = ['username' => post('username'), 'email' => post('email'), 'level' => 0, 'aktif' => 1];
         $pelanggan = ['nama_lengkap' => post('nama'), 'alamat' => post('alamat'), 'kota' => post('kota'), 'telp' => post('telp')];
         if (post('password') == post('passconf')) {
             $pengguna['password'] = md5(post('password'));
         }
         if ($userId = User::add($pengguna)) {
             $pelanggan['id_pengguna'] = $userId;
             if (Customer::add($pelanggan)) {
                 set_alert('success', 'Registrasi berhasil, silahkan login ke akun yang baru saja anda buat');
                 redirect('login');
             } else {
                 set_alert('error', 'Maaf registrasi gagal');
                 redirect('register');
             }
         }
     }
     return $this->render('form-register', ['heading' => 'Silahkan register']);
 }
Exemple #8
0
function submitAccount()
{
    global $cookie, $errors, $smarty;
    $email = Tools::getValue('email');
    if (empty($email) or !Validate::isEmail($email)) {
        $errors[] = Tools::displayError('e-mail not valid');
    } elseif (!Validate::isPasswd(Tools::getValue('passwd'))) {
        $errors[] = Tools::displayError('invalid password');
    } elseif (Customer::customerExists($email)) {
        $errors[] = Tools::displayError('someone has already registered with this e-mail address');
    } elseif (!@checkdate(Tools::getValue('months'), Tools::getValue('days'), Tools::getValue('years')) and !(Tools::getValue('months') == '' and Tools::getValue('days') == '' and Tools::getValue('years') == '')) {
        $errors[] = Tools::displayError('invalid birthday');
    } else {
        $customer = new Customer();
        if (Tools::isSubmit('newsletter')) {
            $customer->ip_registration_newsletter = pSQL(Tools::getRemoteAddr());
            $customer->newsletter_date_add = pSQL(date('Y-m-d h:i:s'));
        }
        $customer->birthday = empty($_POST['years']) ? '' : (int) $_POST['years'] . '-' . (int) $_POST['months'] . '-' . (int) $_POST['days'];
        /* Customer and address, same fields, caching data */
        $errors = $customer->validateControler();
        $address = new Address();
        $address->id_customer = 1;
        $errors = array_unique(array_merge($errors, $address->validateControler()));
        if (!sizeof($errors)) {
            $customer->active = 1;
            if (!$customer->add()) {
                $errors[] = Tools::displayError('an error occurred while creating your account');
            } else {
                $address->id_customer = (int) $customer->id;
                if (!$address->add()) {
                    $errors[] = Tools::displayError('an error occurred while creating your address');
                } else {
                    if (Mail::Send((int) $cookie->id_lang, 'account', Mail::l('Welcome!', (int) $cookie->id_lang), array('{firstname}' => $customer->firstname, '{lastname}' => $customer->lastname, '{email}' => $customer->email, '{passwd}' => Tools::getValue('passwd')), $customer->email, $customer->firstname . ' ' . $customer->lastname)) {
                        $smarty->assign('confirmation', 1);
                    }
                    $cookie->id_customer = (int) $customer->id;
                    $cookie->customer_lastname = $customer->lastname;
                    $cookie->customer_firstname = $customer->firstname;
                    $cookie->passwd = $customer->passwd;
                    $cookie->logged = 1;
                    $cookie->email = $customer->email;
                    Module::hookExec('createAccount', array('_POST' => $_POST, 'newCustomer' => $customer));
                    // Next !
                    $payerID = strval(Tools::getValue('payerID'));
                    displayProcess($payerID);
                }
            }
        }
    }
}
 /**
  * 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');
     }
 }
 public function handleBuyerRegisterUserPassword($metadata, $request, $encoder)
 {
     // prepare the fields inside the POST (so we can use Prestashop's validateController)
     unset($_POST['email']);
     if (isset($request['Buyer']['Username'])) {
         $_POST['email'] = $request['Buyer']['Username'];
     }
     unset($_POST['passwd']);
     if (isset($request['Buyer']['Password'])) {
         $_POST['passwd'] = $request['Buyer']['Password'];
     }
     unset($_POST['firstname']);
     if (isset($request['Buyer']['FirstName'])) {
         $_POST['firstname'] = $request['Buyer']['FirstName'];
     }
     unset($_POST['lastname']);
     if (isset($request['Buyer']['LastName'])) {
         $_POST['lastname'] = $request['Buyer']['LastName'];
     }
     // verify fields are valid
     $customer = new Customer();
     if (_PS_VERSION_ < '1.5') {
         $errors = $customer->validateControler();
     } else {
         $errors = $customer->validateController();
     }
     if (is_array($errors) && count($errors) > 0) {
         CartAPI_Helpers::dieOnError($encoder, 'RegisterNotAuthorized', CartAPI_Handlers_Helpers::removeHtmlTags($errors[0]));
     }
     // make sure the customer doesn't already exist
     if (Customer::customerExists($_POST['email'])) {
         CartAPI_Helpers::dieOnError($encoder, 'RegisterNotAuthorized', CartAPI_Handlers_Helpers::removeHtmlTags(Tools::displayError('An account is already registered with this e-mail, please fill in the password or request a new one.')));
     }
     // add the new user
     $customer->active = 1;
     if (property_exists('Customer', 'is_guest')) {
         $customer->is_guest = 0;
     }
     if (!$customer->add()) {
         CartAPI_Helpers::dieOnError($encoder, 'RegisterNotAuthorized', CartAPI_Handlers_Helpers::removeHtmlTags(Tools::displayError('An error occurred while creating your account.')));
     }
     // see if we need to login too
     if (!isset($request['Login']) || $request['Login'] == 'true') {
         $cookie = $this->syncCookie($customer);
         // run the after login events, actually don't since prestashop AuthController doesn't do it
         // $this->afterBuyerLogin($customer);
     }
     // run the after register events
     $this->afterBuyerRegister($customer, $request['Buyer']);
 }
 public function orders($do = '', $id = '')
 {
     $this->data['heading'] = 'Administrasi: Pembelian';
     switch ($do) {
         case 'form':
             if (post('submit')) {
                 $userKey = User::primary();
                 $customerKey = Customer::primary();
                 $productKey = Product::primary();
                 $order = [$userKey => 1, 'status' => post('status') ?: 0];
                 if ($tanggal = post('tanggal')) {
                     $order['tanggal'] = formatTanggal($tanggal, 'Y-m-d');
                 } else {
                     $order['tanggal'] = date('Y-m-d');
                 }
                 try {
                     $upload = new Upload('pembayaran');
                     $order['pembayaran'] = $upload->doUpload();
                 } catch (Exception $e) {
                     setAlert('error', $e->getMessage());
                 }
                 if ($id_pelanggan = post($customerKey)) {
                     $order[$customerKey] = $id_pelanggan;
                 } else {
                     $pengguna = ['username' => post('username'), 'email' => post('email'), 'level' => 0, 'aktif' => 1];
                     $pelanggan = ['nama_lengkap' => post('nama_lengkap'), 'alamat' => post('alamat'), 'kota' => post('kota'), 'telp' => post('telp')];
                     if ($password = post('password') and $password == post('passconf')) {
                         $pengguna['password'] = $password;
                     }
                     if ($id_pengguna = User::add($pengguna)) {
                         $pelanggan[$userKey] = $id_pengguna;
                     }
                     if ($id_pengguna and $id_pelanggan = Customer::add($pelanggan)) {
                         $order[$customerKey] = $id_pelanggan;
                     }
                 }
                 if ($produks = post($productKey)) {
                     $produk_qty = post('produk_qty');
                     $produk_arr = [];
                     foreach ($produks as $i => $produk_id) {
                         $produk_arr[$produk_id] = $produk_qty[$i];
                     }
                     $order['produk'] = serialize($produk_arr);
                 }
                 if ($ongkir = post('ongkir') and $kurir = post('kurir')) {
                     $order['ongkir'] = $ongkir;
                     $order['kurir'] = $kurir;
                 }
                 if ($belanja = post('belanja') and $total = post('total')) {
                     $order['belanja'] = $belanja;
                     $order['total'] = $total;
                 }
                 if ($order['status'] === 0) {
                     $order['potongan'] = post('potongan') ?: 0;
                     $order['bayar'] = post('bayar') ?: 0;
                     $order['kembali'] = post('kembali') ?: 0;
                     if ($order['kembali'] < 0) {
                         $order['kembali'] = 0;
                     }
                     if ($order['bayar'] > 0) {
                         $order['status'] = 1;
                     }
                 }
                 if ($resi = post('resi')) {
                     $order['resi'] = $resi;
                 }
                 if (Order::save($order, $id)) {
                     if ($id) {
                         setAlert('success', 'Berhasil memperbarui data order <b>' . $order['nama'] . '</b>');
                     } else {
                         setAlert('success', 'Berhasil menambahkan order <b>' . $order['nama'] . '</b>');
                     }
                     return redirect('admin-shop/orders');
                 }
                 setAlert('error', 'Terjadi kesalahan dalam penyimpanan order');
                 return redirect($this->uri->path());
             }
             $order_data = $id ? Order::show($id)->fetchOne() : [];
             if (!User::is('admin') and ($order_data and $order_data->{$customerKey} != User::current($customerKey))) {
                 return redirect('admin-shop/orders');
             }
             $this->data['data'] = $order_data;
             return $this->render('order-form', $this->data);
             break;
         case 'delete':
             if (Order::del([Order::primary() => $id])) {
                 setAlert('success', 'Order berhasil terhapus');
             } else {
                 setAlert('error', 'Terjadi kesalahan dalam penghapusan order');
             }
             return redirect('admin-shop/orders');
             break;
         default:
             $filter = !User::is('admin') ? [Customer::primary() => User::current('id_pelanggan')] : [];
             $this->data['data'] = Order::show($filter, get('sort'));
             return $this->render('order-table', $this->data);
             break;
     }
 }
Exemple #12
0
    public function getOrAddCustomer($ebay_profile)
    {
        $id_customer = (int) Db::getInstance()->getValue('SELECT `id_customer`
			FROM `' . _DB_PREFIX_ . 'customer`
			WHERE `active` = 1
			AND `email` = \'' . pSQL($this->email) . '\'
			AND `id_shop` = ' . (int) $ebay_profile->id_shop . '
			AND `deleted` = 0' . (Tools::substr(_PS_VERSION_, 0, 3) == '1.3' ? '' : ' AND `is_guest` = 0'));
        $format = new TotFormat();
        // Add customer if he doesn't exist
        //if ($id_customer < 1) RAPH
        if (!$id_customer) {
            $customer = new Customer();
            $customer->id_gender = 0;
            $customer->id_default_group = 1;
            $customer->secure_key = md5(uniqid(rand(), true));
            $customer->email = $format->formatEmail($this->email);
            $customer->passwd = md5(_COOKIE_KEY_ . rand());
            $customer->last_passwd_gen = date('Y-m-d H:i:s');
            $customer->newsletter = 0;
            $customer->lastname = $format->formatName(EbayOrder::_formatFamilyName($this->familyname));
            $customer->firstname = $format->formatName($this->firstname);
            $customer->active = 1;
            $customer->id_shop = (int) $ebay_profile->id_shop;
            $res = $customer->add();
            $this->_writeLog($ebay_profile->id, 'add_customer', $res);
            $id_customer = $customer->id;
        }
        $this->id_customers[$ebay_profile->id_shop] = $id_customer;
        return $id_customer;
    }
 public function processSubmitLogin($provider)
 {
     $social_customer = $this->socialNetworkList[$provider]->processSubmitLogin();
     if (!$social_customer || !$social_customer->id_user) {
         FSLTools::returnError(Tools::displayError('Invalid social account'));
     }
     $customer = null;
     if ($social_customer->id_customer) {
         // If social customer already exist, just login
         $customer = new Customer($social_customer->id_customer);
     } else {
         if (Tools::getValue('createAccount') == 'on' || Tools::getValue('createAccount') == 'true' || Tools::getValue('createAccount') == '1') {
             if (Customer::customerExists($social_customer->email)) {
                 // Social customer not exist, but customer prestashop already exist. Update it.
                 $customer = new Customer();
                 $authentication = $customer->getByEmail($social_customer->email);
                 if (isset($authentication->active) && !$authentication->active) {
                     FSLTools::returnError(Tools::displayError('Your account isn\'t available at this time, please contact us'));
                 } else {
                     if (!$authentication || !$customer->id) {
                         FSLTools::returnError(Tools::displayError('Authentication failed.'));
                     } else {
                         if ($this->context->customer->isLogged() && $customer->id != $this->context->customer->id) {
                             FSLTools::returnError(Tools::displayError('Your current Prestashop account not corresponding to your Social account.'));
                         } else {
                             if (!$customer->birthday && $social_customer->birthday) {
                                 // Update customer if needed
                                 $customer->birthday = $social_customer->birthday;
                                 $customer->update();
                             }
                         }
                     }
                 }
             } else {
                 // Create both social and prestashop customers.
                 $customer = new Customer();
                 $customer->id_shop = $this->context->shop->id;
                 $customer->firstname = $social_customer->firstname;
                 $customer->lastname = $social_customer->lastname;
                 $customer->email = $social_customer->email;
                 $customer->id_gender = $social_customer->id_gender;
                 $customer->newsletter = (bool) Configuration::get('FSL_CUSTOMER_NWSL');
                 $customer->optin = (bool) Configuration::get('FSL_CUSTOMER_OPTIN');
                 $passwd = Tools::passwdGen();
                 $customer->passwd = Tools::encrypt($passwd);
                 if ($social_customer->birthday) {
                     $customer->birthday = $social_customer->birthday;
                 }
                 if (!$customer->add()) {
                     FSLTools::returnError(Tools::displayError('Error during account creation.'));
                 }
                 if ($customer->newsletter) {
                     FSLTools::processCustomerNewsletter($customer);
                 }
                 Hook::exec('actionCustomerAccountAdd', array('_POST' => $_POST, 'newCustomer' => $customer));
                 if (!FSLTools::sendConfirmationMail($social_customer, $passwd)) {
                     FSLTools::returnError(Tools::displayError('The email cannot be sent.'));
                 }
             }
             if ($customer != null && $customer->id) {
                 $social_customer->id_customer = $customer->id;
                 $social_customer->id_shop = $customer->id_shop;
                 $social_customer->add();
                 // Add social customer
             }
         } else {
             FSLTools::returnAjax();
         }
     }
     if (!$this->context->customer->isLogged() && $customer != null) {
         $this->processLogin($customer);
     }
     if (($back = Tools::getValue('back')) && $back == Tools::secureReferrer($back)) {
         $redirect_url = html_entity_decode($back);
     }
     // redirection: if cart is not empty : redirection to the cart
     if (isset(Context::getContext()->cart) && count(Context::getContext()->cart->getProducts(true)) > 0) {
         $redirect_url = Context::getContext()->link->getPageLink('order' . ($multi = (int) Tools::getValue('multi-shipping') ? '&multi-shipping=' . $multi : ''));
     } else {
         $redirect_url = Context::getContext()->link->getPageLink('my-account');
     }
     FSLTools::returnAjax($redirect_url, $social_customer);
 }
Exemple #14
0
 public function hookbackOfficeTop($params)
 {
     // Check if the module is configured
     if (!Configuration::get('EBAY_PAYPAL_EMAIL')) {
         return false;
     }
     // If no update yet
     if (!Configuration::get('EBAY_ORDER_LAST_UPDATE')) {
         Configuration::updateValue('EBAY_ORDER_LAST_UPDATE', date('Y-m-d') . 'T' . date('H:i:s') . '.000Z');
     }
     // init Var
     $dateNew = date('Y-m-d') . 'T' . date('H:i:s') . '.000Z';
     if (Configuration::get('EBAY_ORDER_LAST_UPDATE') < date('Y-m-d', strtotime('-45 minutes')) . 'T' . date('H:i:s', strtotime('-45 minutes')) . '.000Z') {
         $ebay = new eBayRequest();
         $orderList = $ebay->getOrders(Configuration::get('EBAY_ORDER_LAST_UPDATE'), $dateNew);
         if ($orderList) {
             foreach ($orderList as $order) {
                 if ($order['status'] == 'Complete') {
                     $result = Db::getInstance()->getRow('SELECT `id_customer` FROM `' . _DB_PREFIX_ . 'customer` WHERE `active` = 1 AND `email` = \'' . pSQL($order['email']) . '\' AND `deleted` = 0' . (substr(_PS_VERSION_, 0, 3) == '1.3' ? '' : ' AND `is_guest` = 0'));
                     $id_customer = isset($result['id_customer']) ? $result['id_customer'] : 0;
                     // Add customer if he doesn't exist
                     if ($id_customer < 1) {
                         $customer = new Customer();
                         $customer->id_gender = 9;
                         $customer->id_default_group = 1;
                         $customer->secure_key = md5(uniqid(rand(), true));
                         $customer->email = $order['email'];
                         $customer->passwd = md5(pSQL(_COOKIE_KEY_ . rand()));
                         $customer->last_passwd_gen = pSQL(date('Y-m-d H:i:s'));
                         $customer->newsletter = 0;
                         $customer->lastname = pSQL($order['familyname']);
                         $customer->firstname = pSQL($order['firstname']);
                         $customer->active = 1;
                         $customer->add();
                         $id_customer = $customer->id;
                     }
                     $address = new Address();
                     $address->id_customer = (int) $id_customer;
                     $address->id_country = (int) Country::getByIso($order['country_iso_code']);
                     $address->alias = 'eBay ' . date('Y-m-d H:i:s');
                     $address->lastname = pSQL($order['familyname']);
                     $address->firstname = pSQL($order['firstname']);
                     $address->address1 = pSQL($order['address1']);
                     $address->address2 = pSQL($order['address2']);
                     $address->postcode = pSQL($order['postalcode']);
                     $address->city = pSQL($order['city']);
                     $address->phone = pSQL($order['phone']);
                     $address->active = 1;
                     $address->add();
                     $id_address = $address->id;
                     $flag = 1;
                     foreach ($order['product_list'] as $product) {
                         if ((int) $product['id_product'] < 1 || !Db::getInstance()->getValue('SELECT `id_product` FROM `' . _DB_PREFIX_ . 'product` WHERE `id_product` = ' . (int) $product['id_product'])) {
                             $flag = 0;
                         }
                         if (isset($product['id_product_attribute']) && !Db::getInstance()->getValue('SELECT `id_product_attribute` FROM `' . _DB_PREFIX_ . 'product_attribute` WHERE `id_product` = ' . (int) $product['id_product'] . ' AND `id_product_attribute` = ' . (int) $product['id_product_attribute'])) {
                             $flag = 0;
                         }
                     }
                     if ($flag == 1) {
                         $cartAdd = new Cart();
                         $cartAdd->id_customer = $id_customer;
                         $cartAdd->id_address_invoice = $id_address;
                         $cartAdd->id_address_delivery = $id_address;
                         $cartAdd->id_carrier = 1;
                         $cartAdd->id_lang = $this->id_lang;
                         $cartAdd->id_currency = Currency::getIdByIsoCode('EUR');
                         $cartAdd->add();
                         foreach ($order['product_list'] as $product) {
                             $cartAdd->updateQty((int) $product['quantity'], (int) $product['id_product'], isset($product['id_product_attribute']) ? $product['id_product_attribute'] : NULL);
                         }
                         $cartAdd->update();
                         // Fix on sending e-mail
                         Db::getInstance()->autoExecute(_DB_PREFIX_ . 'customer', array('email' => 'NOSEND-EBAY'), 'UPDATE', '`id_customer` = ' . (int) $id_customer);
                         $customerClear = new Customer();
                         if (method_exists($customerClear, 'clearCache')) {
                             $customerClear->clearCache(true);
                         }
                         // Validate order
                         $paiement = new eBayPayment();
                         $paiement->validateOrder(intval($cartAdd->id), _PS_OS_PAYMENT_, floatval($cartAdd->getOrderTotal(true, 3)), 'Paypal eBay', NULL, array(), intval($cartAdd->id_currency));
                         $id_order = $paiement->currentOrder;
                         // Fix on sending e-mail
                         Db::getInstance()->autoExecute(_DB_PREFIX_ . 'customer', array('email' => pSQL($order['email'])), 'UPDATE', '`id_customer` = ' . (int) $id_customer);
                         // Update price (because of possibility of price impact)
                         $updateOrder = array('total_paid' => floatval($order['amount']), 'total_paid_real' => floatval($order['amount']), 'total_products' => floatval($order['amount']), 'total_products_wt' => floatval($order['amount']), 'total_shipping' => floatval($order['shippingServiceCost']));
                         Db::getInstance()->autoExecute(_DB_PREFIX_ . 'orders', $updateOrder, 'UPDATE', '`id_order` = ' . (int) $id_order);
                         foreach ($order['product_list'] as $product) {
                             Db::getInstance()->autoExecute(_DB_PREFIX_ . 'order_detail', array('product_price' => floatval($product['price']), 'tax_rate' => 0, 'reduction_percent' => 0), 'UPDATE', '`id_order` = ' . (int) $id_order . ' AND `product_id` = ' . (int) $product['id_product'] . ' AND `product_attribute_id` = ' . (int) $product['id_product_attribute']);
                         }
                     }
                 }
             }
         }
         Configuration::updateValue('EBAY_ORDER_LAST_UPDATE', $dateNew);
     }
 }
 public function createCustomerGuestAccount($encoder, $buyerDictionary, $addressDictionary = array())
 {
     global $cookie;
     // taken from AuthController
     // no need to create if already logged in and has a customer id
     if ($cookie->logged && $cookie->id_customer) {
         return;
     }
     // make sure we can create a guest account
     if (!Configuration::get('PS_GUEST_CHECKOUT_ENABLED')) {
         CartAPI_Helpers::dieOnError($encoder, 'RegisterNotAuthorized', CartAPI_Handlers_Helpers::removeHtmlTags(Tools::displayError('You cannot create a guest account.')));
     }
     // prepare the fields inside the POST (so we can use Prestashop's validateController)
     unset($_POST['email']);
     if (isset($buyerDictionary['Email'])) {
         $_POST['email'] = $buyerDictionary['Email'];
     }
     unset($_POST['passwd']);
     $_POST['passwd'] = md5(time() . _COOKIE_KEY_);
     unset($_POST['firstname']);
     if (isset($addressDictionary['FirstName'])) {
         $_POST['firstname'] = $addressDictionary['FirstName'];
     }
     // take from address as backup
     if (isset($buyerDictionary['FirstName'])) {
         $_POST['firstname'] = $buyerDictionary['FirstName'];
     }
     // take from buyer if given
     unset($_POST['lastname']);
     if (isset($addressDictionary['LastName'])) {
         $_POST['lastname'] = $addressDictionary['LastName'];
     }
     // take from address as backup
     if (isset($buyerDictionary['LastName'])) {
         $_POST['lastname'] = $buyerDictionary['LastName'];
     }
     // take from buyer if given
     // verify fields are valid
     $customer = new Customer();
     if (_PS_VERSION_ < '1.5') {
         $errors = $customer->validateControler();
     } else {
         $errors = $customer->validateController();
     }
     if (is_array($errors) && count($errors) > 0) {
         CartAPI_Helpers::dieOnError($encoder, 'RegisterNotAuthorized', CartAPI_Handlers_Helpers::removeHtmlTags($errors[0]));
     }
     // add the new user
     $customer->active = 1;
     $customer->is_guest = 1;
     if (!$customer->add()) {
         CartAPI_Helpers::dieOnError($encoder, 'RegisterNotAuthorized', CartAPI_Handlers_Helpers::removeHtmlTags(Tools::displayError('An error occurred while creating your account.')));
     }
     // sync the cookie
     $loginHandler = CartAPI_Handlers_Helpers::newHandlerInstance($encoder, 'Login');
     $loginHandler->syncCookie($customer);
 }
Exemple #16
0
 public function hookheader($params)
 {
     //Change context Shop to be default
     if ($this->isVersionOneDotFive() && Shop::isFeatureActive()) {
         $oldContextShop = $this->getContextShop();
         $this->setContextShop();
     }
     //End of change
     // Check if the module is configured
     if (!Configuration::get('EBAY_PAYPAL_EMAIL')) {
         return false;
     }
     // Fix hook update product attribute
     $this->hookupdateProductAttributeEbay();
     // init date to check from
     if (Configuration::get('EBAY_INSTALL_DATE') < date('Y-m-d', strtotime('-30 days')) . 'T' . date('H:i:s', strtotime('-30 days'))) {
         //If it is more than 30 days that we installed the module
         $dateToCheckFrom = Configuration::get('EBAY_ORDER_LAST_UPDATE');
         $dateToCheckFromArray = explode('T', $dateToCheckFrom);
         $dateToCheckFrom = date("Y-m-d", strtotime($dateToCheckFromArray[0] . " -30 day"));
         $dateToCheckFrom .= 'T' . $dateToCheckFromArray[1];
     } else {
         //If it is less than 30 days that we installed the module
         $dateToCheckFrom = Configuration::get('EBAY_INSTALL_DATE');
         $dateToCheckFromArray = explode('T', $dateToCheckFrom);
         $dateToCheckFrom = date("Y-m-d", strtotime($dateToCheckFromArray[0] . " -1 day"));
         $dateToCheckFrom .= 'T' . $dateToCheckFromArray[1];
     }
     if (Configuration::get('EBAY_ORDER_LAST_UPDATE') < date('Y-m-d', strtotime('-30 minutes')) . 'T' . date('H:i:s', strtotime('-30 minutes')) . '.000Z') {
         $dateNew = date('Y-m-d') . 'T' . date('H:i:s') . '.000Z';
         $this->setConfiguration('EBAY_ORDER_LAST_UPDATE', $dateNew);
         // eBay Request
         $ebay = new eBayRequest();
         $page = 1;
         $orderList = array();
         $orderCount = 0;
         $orderCountTmp = 100;
         while ($orderCountTmp == 100 && $page < 10) {
             $orderListTmp = $ebay->getOrders($dateToCheckFrom, $dateNew, $page);
             $orderCountTmp = count($orderListTmp);
             $orderList = array_merge((array) $orderList, (array) $orderListTmp);
             $orderCount += $orderCountTmp;
             $page++;
         }
         // Lock
         if ($orderList) {
             foreach ($orderList as $korder => $order) {
                 if ($order['status'] == 'Complete' && $order['amount'] > 0.1 && isset($order['product_list']) && count($order['product_list'])) {
                     if (!Db::getInstance()->getValue('SELECT `id_ebay_order` FROM `' . _DB_PREFIX_ . 'ebay_order` WHERE `id_order_ref` = \'' . pSQL($order['id_order_ref']) . '\'')) {
                         // Check for empty name
                         $order['firstname'] = trim($order['firstname']);
                         $order['familyname'] = trim($order['familyname']);
                         if (empty($order['familyname'])) {
                             $order['familyname'] = $order['firstname'];
                         }
                         if (empty($order['firstname'])) {
                             $order['firstname'] = $order['familyname'];
                         }
                         if (empty($order['phone']) || !Validate::isPhoneNumber($order['phone'])) {
                             $order['phone'] = '0100000000';
                         }
                         if (Validate::isEmail($order['email']) && !empty($order['firstname']) && !empty($order['familyname'])) {
                             // Getting the customer
                             $id_customer = (int) Db::getInstance()->getValue('SELECT `id_customer` FROM `' . _DB_PREFIX_ . 'customer` WHERE `active` = 1 AND `email` = \'' . pSQL($order['email']) . '\' AND `deleted` = 0' . (substr(_PS_VERSION_, 0, 3) == '1.3' ? '' : ' AND `is_guest` = 0'));
                             // Add customer if he doesn't exist
                             if ($id_customer < 1) {
                                 $customer = new Customer();
                                 $customer->id_gender = 0;
                                 $customer->id_default_group = 1;
                                 $customer->secure_key = md5(uniqid(rand(), true));
                                 $customer->email = $order['email'];
                                 $customer->passwd = md5(pSQL(_COOKIE_KEY_ . rand()));
                                 $customer->last_passwd_gen = pSQL(date('Y-m-d H:i:s'));
                                 $customer->newsletter = 0;
                                 $customer->lastname = pSQL($order['familyname']);
                                 $customer->firstname = pSQL($order['firstname']);
                                 $customer->active = 1;
                                 $customer->add();
                                 $id_customer = $customer->id;
                             }
                             // Search if address exists
                             $id_address = (int) Db::getInstance()->getValue('SELECT `id_address` FROM `' . _DB_PREFIX_ . 'address` WHERE `id_customer` = ' . (int) $id_customer . ' AND `alias` = \'eBay\'');
                             if ($id_address > 0) {
                                 $address = new Address((int) $id_address);
                             } else {
                                 $address = new Address();
                                 $address->id_customer = (int) $id_customer;
                             }
                             $address->id_country = (int) Country::getByIso($order['country_iso_code']);
                             $address->alias = 'eBay';
                             $address->lastname = pSQL($order['familyname']);
                             $address->firstname = pSQL($order['firstname']);
                             $address->address1 = pSQL($order['address1']);
                             $address->address2 = pSQL($order['address2']);
                             $address->postcode = pSQL($order['postalcode']);
                             $address->city = pSQL($order['city']);
                             $address->phone = pSQL($order['phone']);
                             $address->active = 1;
                             if ($id_address > 0 && Validate::isLoadedObject($address)) {
                                 $address->update();
                             } else {
                                 $address->add();
                             }
                             $id_address = $address->id;
                             $flag = 1;
                             foreach ($order['product_list'] as $product) {
                                 if ((int) $product['id_product'] < 1 || !Db::getInstance()->getValue('SELECT `id_product` FROM `' . _DB_PREFIX_ . 'product` WHERE `id_product` = ' . (int) $product['id_product'])) {
                                     $flag = 0;
                                 }
                                 if (isset($product['id_product_attribute']) && $product['id_product_attribute'] > 0 && !Db::getInstance()->getValue('SELECT `id_product_attribute` FROM `' . _DB_PREFIX_ . 'product_attribute` WHERE `id_product` = ' . (int) $product['id_product'] . ' AND `id_product_attribute` = ' . (int) $product['id_product_attribute'])) {
                                     $flag = 0;
                                 }
                             }
                             if ($flag == 1) {
                                 //Create a Cart for the order
                                 $cartNbProducts = 0;
                                 $cartAdd = new Cart();
                                 Context::getContext()->customer = new Customer($id_customer);
                                 $cartAdd->id_customer = $id_customer;
                                 $cartAdd->id_address_invoice = $id_address;
                                 $cartAdd->id_address_delivery = $id_address;
                                 $cartAdd->id_carrier = 0;
                                 $cartAdd->id_lang = $this->id_lang;
                                 $cartAdd->id_currency = Currency::getIdByIsoCode('EUR');
                                 $cartAdd->recyclable = 0;
                                 $cartAdd->gift = 0;
                                 $cartAdd->add();
                                 $id_lang = (int) Configuration::get('PS_LANG_DEFAULT');
                                 foreach ($order['product_list'] as $product) {
                                     $prod = new Product($product['id_product'], false, $id_lang);
                                     // Qty of product or attribute
                                     if (isset($product['id_product_attribute']) && !empty($product['id_product_attribute'])) {
                                         $minimalQty = (int) Attribute::getAttributeMinimalQty($product['id_product_attribute']);
                                     } else {
                                         $minimalQty = $prod->minimal_quantity;
                                     }
                                     if ($product['quantity'] >= $minimalQty) {
                                         if ($this->isVersionOneDotFive()) {
                                             $update = $cartAdd->updateQty((int) $product['quantity'], (int) $product['id_product'], isset($product['id_product_attribute']) && $product['id_product_attribute'] > 0 ? $product['id_product_attribute'] : NULL, false, 'up', 0, new Shop(Configuration::get('PS_SHOP_DEFAULT')));
                                             if ($update === TRUE) {
                                                 $cartNbProducts++;
                                             }
                                         } elseif ($cartAdd->updateQty((int) $product['quantity'], (int) $product['id_product'], isset($product['id_product_attribute']) && $product['id_product_attribute'] > 0 ? $product['id_product_attribute'] : NULL)) {
                                             $cartNbProducts++;
                                         }
                                     } else {
                                         $templateVars = array('{name_product}' => $prod->name, '{min_qty}' => $minimalQty, '{cart_qty}' => $product['quantity']);
                                         Mail::Send((int) Configuration::get('PS_LANG_DEFAULT'), 'alertEbay', Mail::l('Product quantity', $id_lang), $templateVars, strval(Configuration::get('PS_SHOP_EMAIL')), NULL, strval(Configuration::get('PS_SHOP_EMAIL')), strval(Configuration::get('PS_SHOP_NAME')), NULL, NULL, dirname(__FILE__) . '/mails/');
                                     }
                                 }
                                 $cartAdd->update();
                                 // Check number of products in the cart and check if order has already been taken
                                 if ($cartNbProducts > 0 && !Db::getInstance()->getValue('SELECT `id_ebay_order` FROM `' . _DB_PREFIX_ . 'ebay_order` WHERE `id_order_ref` = \'' . pSQL($order['id_order_ref']) . '\'')) {
                                     // Fix on sending e-mail
                                     Db::getInstance()->autoExecute(_DB_PREFIX_ . 'customer', array('email' => 'NOSEND-EBAY'), 'UPDATE', '`id_customer` = ' . (int) $id_customer);
                                     $customerClear = new Customer();
                                     if (method_exists($customerClear, 'clearCache')) {
                                         $customerClear->clearCache(true);
                                     }
                                     $paiement = new eBayPayment();
                                     // Validate order
                                     if ($this->isVersionOneDotFive()) {
                                         $customer = new Customer($id_customer);
                                         $paiement->validateOrder(intval($cartAdd->id), Configuration::get('PS_OS_PAYMENT'), floatval($cartAdd->getOrderTotal(true, 3)), 'eBay ' . $order['payment_method'] . ' ' . $order['id_order_seller'], NULL, array(), intval($cartAdd->id_currency), false, $customer->secure_key, new Shop(Configuration::get('PS_SHOP_DEFAULT')));
                                     } else {
                                         $customer = new Customer($id_customer);
                                         $paiement->validateOrder(intval($cartAdd->id), Configuration::get('PS_OS_PAYMENT'), floatval($cartAdd->getOrderTotal(true, 3)), 'eBay ' . $order['payment_method'] . ' ' . $order['id_order_seller'], NULL, array(), intval($cartAdd->id_currency), false, $customer->secure_key);
                                     }
                                     $id_order = $paiement->currentOrder;
                                     // Fix on date
                                     Db::getInstance()->autoExecute(_DB_PREFIX_ . 'orders', array('date_add' => pSQL($order['date_add'])), 'UPDATE', '`id_order` = ' . (int) $id_order);
                                     // Fix on sending e-mail
                                     Db::getInstance()->autoExecute(_DB_PREFIX_ . 'customer', array('email' => pSQL($order['email'])), 'UPDATE', '`id_customer` = ' . (int) $id_customer);
                                     // Update price (because of possibility of price impact)
                                     foreach ($order['product_list'] as $product) {
                                         $tax_rate = Db::getInstance()->getValue('SELECT `tax_rate` FROM `' . _DB_PREFIX_ . 'order_detail` WHERE `id_order` = ' . (int) $id_order . ' AND `product_id` = ' . (int) $product['id_product'] . ' AND `product_attribute_id` = ' . (int) $product['id_product_attribute']);
                                         Db::getInstance()->autoExecute(_DB_PREFIX_ . 'order_detail', array('product_price' => floatval($product['price'] / (1 + $tax_rate / 100)), 'reduction_percent' => 0), 'UPDATE', '`id_order` = ' . (int) $id_order . ' AND `product_id` = ' . (int) $product['id_product'] . ' AND `product_attribute_id` = ' . (int) $product['id_product_attribute']);
                                     }
                                     $updateOrder = array('total_paid' => floatval($order['amount']), 'total_paid_real' => floatval($order['amount']), 'total_products' => floatval(Db::getInstance()->getValue('SELECT SUM(`product_price`) FROM `' . _DB_PREFIX_ . 'order_detail` WHERE `id_order` = ' . (int) $id_order)), 'total_products_wt' => floatval($order['amount'] - $order['shippingServiceCost']), 'total_shipping' => floatval($order['shippingServiceCost']));
                                     Db::getInstance()->autoExecute(_DB_PREFIX_ . 'orders', $updateOrder, 'UPDATE', '`id_order` = ' . (int) $id_order);
                                     // Register the ebay order ref
                                     Db::getInstance()->autoExecute(_DB_PREFIX_ . 'ebay_order', array('id_order_ref' => pSQL($order['id_order_ref']), 'id_order' => (int) $id_order), 'INSERT');
                                     if (!$this->isVersionOneDotFive()) {
                                         //Fix on eBay not updating
                                         $params = array();
                                         foreach ($order['product_list'] as $product) {
                                             $params['product'] = new Product((int) $product['id_product']);
                                             $this->hookaddproduct($params);
                                         }
                                     }
                                 } else {
                                     $cartAdd->delete();
                                     $orderList[$korder]['errors'][] = $this->l('Could not add product to cart (maybe your stock quantity is 0)');
                                 }
                             } else {
                                 $orderList[$korder]['errors'][] = $this->l('Could not found products in database');
                             }
                         } else {
                             $orderList[$korder]['errors'][] = $this->l('Invalid e-mail');
                         }
                     } else {
                         $orderList[$korder]['errors'][] = $this->l('Order already imported');
                     }
                 } else {
                     $orderList[$korder]['errors'][] = $this->l('Status not complete or amount less than 0.1 or no product matching');
                 }
             }
             file_put_contents(dirname(__FILE__) . '/log/orders.php', "<?php\n\n" . '$dateLastImport = ' . "'" . date('d/m/Y H:i:s') . "';\n\n" . '$orderList = ' . var_export($orderList, true) . ";\n\n");
         }
     }
     // Set old Context Shop
     if ($this->isVersionOneDotFive() && Shop::isFeatureActive()) {
         $this->setContextShop($oldContextShop);
     }
 }
Exemple #17
0
 private function _setSimulatedCustomer()
 {
     $simulatedCustomer = new Customer();
     $simulatedCustomer->lastname = 'OPC';
     $simulatedCustomer->firstname = 'Module';
     $simulatedCustomer->passwd = 'opcpasswd';
     $simulatedCustomer->email = '*****@*****.**';
     $simulatedCustomer->enabled = 0;
     $simulatedCustomer->deleted = 1;
     $simulatedCustomer->add();
     return $simulatedCustomer->id;
 }
Exemple #18
0
 public function init()
 {
     self::$amz_payments = new AmzPayments();
     $this->isLogged = (bool) $this->context->customer->id && Customer::customerIdExistsStatic((int) $this->context->cookie->id_customer);
     parent::init();
     /* Disable some cache related bugs on the cart/order */
     header('Cache-Control: no-cache, must-revalidate');
     header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
     $this->display_column_left = false;
     $this->display_column_right = false;
     // Service initialisieren
     $this->service = self::$amz_payments->getService();
     if (Tools::isSubmit('ajax')) {
         if (Tools::isSubmit('method')) {
             switch (Tools::getValue('method')) {
                 case 'redirectAuthentication':
                 case 'setusertoshop':
                     if (Tools::getValue('access_token')) {
                         $this->context->cookie->amz_access_token = AmzPayments::prepareCookieValueForPrestaShopUse(Tools::getValue('access_token'));
                         $this->context->cookie->amz_access_token_set_time = time();
                     } else {
                         if (Tools::getValue('method') == 'redirectAuthentication') {
                             Tools::redirect('index');
                         } else {
                             error_log('Error, method not submitted and no token');
                             die('error');
                         }
                     }
                     if (Tools::getValue('action') == 'fromCheckout') {
                         $accessTokenValue = AmzPayments::prepareCookieValueForAmazonPaymentsUse(Tools::getValue('access_token'));
                     } else {
                         $accessTokenValue = Tools::getValue('access_token');
                     }
                     $d = self::$amz_payments->requestTokenInfo($accessTokenValue);
                     if ($d->aud != self::$amz_payments->client_id) {
                         if (Tools::getValue('method') == 'redirectAuthentication') {
                             Tools::redirect('index');
                         } else {
                             error_log('auth error LPA');
                             die('error');
                         }
                     }
                     $d = self::$amz_payments->requestProfile($accessTokenValue);
                     $customer_userid = $d->user_id;
                     $customer_name = $d->name;
                     $customer_email = $d->email;
                     // $postcode = $d->postal_code;
                     if ($customers_local_id = AmazonPaymentsCustomerHelper::findByAmazonCustomerId($customer_userid)) {
                         // Customer already exists - login
                         Hook::exec('actionBeforeAuthentication');
                         $customer = new Customer();
                         $authentication = AmazonPaymentsCustomerHelper::getByCustomerID($customers_local_id, true, $customer);
                         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');
                             // Login information have changed, so we check if the cart rules still apply
                             CartRule::autoRemoveFromCart($this->context);
                             CartRule::autoAddToCart($this->context);
                             if (Tools::getValue('action') == 'fromCheckout' && isset($this->context->cookie->amz_connect_order)) {
                                 AmzPayments::switchOrderToCustomer($this->context->customer->id, $this->context->cookie->amz_connect_order, true);
                             }
                             if (Tools::getValue('action') == 'checkout') {
                                 $goto = $this->context->link->getModuleLink('amzpayments', 'amzpayments');
                             } elseif (Tools::getValue('action') == 'fromCheckout') {
                                 $goto = 'index.php?controller=history';
                             } elseif ($this->context->cart->nbProducts()) {
                                 $goto = 'index.php?controller=order';
                             } else {
                                 if (Configuration::get('PS_SSL_ENABLED')) {
                                     $goto = _PS_BASE_URL_SSL_ . __PS_BASE_URI__;
                                 } else {
                                     $goto = _PS_BASE_URL_ . __PS_BASE_URI__;
                                 }
                             }
                             if (Tools::getValue('method') == 'redirectAuthentication') {
                                 Tools::redirect($goto);
                             } else {
                                 echo $goto;
                             }
                         }
                     } else {
                         if (AmazonPaymentsCustomerHelper::findByEmailAddress($customer_email)) {
                             $this->context->cookie->amzConnectEmail = $customer_email;
                             $this->context->cookie->amzConnectCustomerId = $customer_userid;
                             $goto = $this->context->link->getModuleLink('amzpayments', 'connect_accounts');
                             if (Tools::getValue('action') && Tools::getValue('action') == 'checkout') {
                                 if (strpos($goto, '?') > 0) {
                                     $goto .= '&checkout=1';
                                 } else {
                                     $goto .= '?checkout=1';
                                 }
                             }
                             if (Tools::getValue('method') == 'redirectAuthentication') {
                                 Tools::redirect($goto);
                             } else {
                                 echo $goto;
                             }
                         } else {
                             // Customer does not exist - Create account
                             Hook::exec('actionBeforeSubmitAccount');
                             $this->create_account = true;
                             $_POST['passwd'] = md5(time() . _COOKIE_KEY_);
                             $firstname = '';
                             $lastname = '';
                             $customer_name = preg_replace("/[0-9]/", "", $customer_name);
                             if (strpos(trim($customer_name), ' ') !== false) {
                                 list($firstname, $lastname) = explode(' ', trim($customer_name));
                             } elseif (strpos(trim($customer_name), '-') !== false) {
                                 list($firstname, $lastname) = explode('-', trim($customer_name));
                             } else {
                                 $firstname = trim($customer_name);
                                 $lastname = 'Placeholder';
                             }
                             $customer = new Customer();
                             $customer->email = $customer_email;
                             $lastname_address = $lastname;
                             $firstname_address = $firstname;
                             $_POST['lastname'] = Tools::getValue('customer_lastname', $lastname_address);
                             $_POST['firstname'] = Tools::getValue('customer_firstname', $firstname_address);
                             // $addresses_types = array('address');
                             $this->errors = array_unique(array_merge($this->errors, $customer->validateController()));
                             // Check the requires fields which are settings in the BO
                             $this->errors = $this->errors + $customer->validateFieldsRequiredDatabase();
                             if (!count($this->errors)) {
                                 $customer->firstname = Tools::ucwords($customer->firstname);
                                 $customer->is_guest = 0;
                                 $customer->active = 1;
                                 if (!count($this->errors)) {
                                     if ($customer->add()) {
                                         if (!$customer->is_guest) {
                                             if (!$this->sendConfirmationMail($customer)) {
                                                 $this->errors[] = Tools::displayError('The email cannot be sent.');
                                             }
                                         }
                                         AmazonPaymentsCustomerHelper::saveCustomersAmazonReference($customer, $customer_userid);
                                         $this->updateContext($customer);
                                         $this->context->cart->update();
                                         Hook::exec('actionCustomerAccountAdd', array('_POST' => $_POST, 'newCustomer' => $customer));
                                         if (Tools::getValue('action') == 'fromCheckout' && isset($this->context->cookie->amz_connect_order)) {
                                             AmzPayments::switchOrderToCustomer($customer->id, $this->context->cookie->amz_connect_order, true);
                                         }
                                         if (Tools::getValue('action') == 'checkout') {
                                             $goto = $this->context->link->getModuleLink('amzpayments', 'amzpayments');
                                         } elseif (Tools::getValue('action') == 'fromCheckout') {
                                             $goto = 'index.php?controller=history';
                                         } elseif ($this->context->cart->nbProducts()) {
                                             $goto = 'index.php?controller=order';
                                         } else {
                                             if (Configuration::get('PS_SSL_ENABLED')) {
                                                 $goto = _PS_BASE_URL_SSL_ . __PS_BASE_URI__;
                                             } else {
                                                 $goto = _PS_BASE_URL_ . __PS_BASE_URI__;
                                             }
                                         }
                                         if (Tools::getValue('method') == 'redirectAuthentication') {
                                             Tools::redirect($goto);
                                         } else {
                                             echo $goto;
                                         }
                                     } else {
                                         $this->errors[] = Tools::displayError('An error occurred while creating your account.');
                                     }
                                 }
                             } else {
                                 error_log('Error validating customers informations');
                                 die('error');
                             }
                         }
                     }
                     die;
             }
         }
     }
 }
 public function preProcess()
 {
     parent::preProcess();
     if (self::$cookie->isLogged() and !Tools::isSubmit('ajax')) {
         Tools::redirect('history.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 ($_POST['passwd'] != $_POST['retype_passwd']) {
             $this->errors[] = Tools::displayError('password and confirmation do not match');
         }
         $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;
         */
         //create customer and login
         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');
         }
         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'));
             }
             $customer->birthday = empty($_POST['years']) ? '' : (int) $_POST['years'] . '-' . (int) $_POST['months'] . '-' . (int) $_POST['days'];
             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 {
                     //award registration points
                     VBRewards::addRegistrationPoints($customer->id);
                     self::$cookie->new_reg = true;
                     self::$cookie->write();
                     //Add coupons to account
                     Tools::addCoupons($customer->id);
                     //$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) {
                         //TODO: remove these extra emails
                         /*Mail::Send((int)(self::$cookie->id_lang), 'alert_account', Mail::l('New Customer Registered'),
                         						array('{firstname}' => $customer->firstname, '{lastname}' => $customer->lastname, '{email}' => $customer->email, 
                         						'{passwd}' => Tools::getValue('passwd')), '*****@*****.**', 'Vineet Saxena');
                         		
                         		Mail::Send((int)(self::$cookie->id_lang), 'alert_account', Mail::l('New Customer Registered'),
                         							array('{firstname}' => $customer->firstname, '{lastname}' => $customer->lastname, '{email}' => $customer->email,
                         							'{passwd}' => Tools::getValue('passwd')), '*****@*****.**', 'Ramakant Sharma');
                         		
                         		*/
                         if ((int) self::$cookie->id_country === 110) {
                             $subject = Mail::l("Welcome to IndusDiva, INR 2500 has been credited to your account");
                             $amount = "INR 2500";
                         } else {
                             $subject = Mail::l("Welcome to IndusDiva, USD 100 has been credited to your account");
                             $amount = "USD 100";
                         }
                         if (!Mail::Send((int) self::$cookie->id_lang, 'account', $subject, array('{firstname}' => $customer->firstname, '{lastname}' => $customer->lastname, '{email}' => $customer->email, '{passwd}' => Tools::getValue('passwd'), '{amount}' => $amount), $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, 'token' => Tools::getToken(false));
                         die(Tools::jsonEncode($return));
                     }
                     if ($back = Tools::getValue('back')) {
                         Tools::redirect($back);
                     }
                     Tools::redirect('index.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 (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');
         }
         $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);
 }
Exemple #20
0
 public function hookbackOfficeTop($params)
 {
     // Check if the module is configured
     if (!Configuration::get('EBAY_PAYPAL_EMAIL')) {
         return false;
     }
     // If no update yet
     if (!Configuration::get('EBAY_ORDER_LAST_UPDATE')) {
         Configuration::updateValue('EBAY_ORDER_LAST_UPDATE', date('Y-m-d') . 'T' . date('H:i:s') . '.000Z');
     }
     // init Var
     $dateNew = date('Y-m-d') . 'T' . date('H:i:s') . '.000Z';
     if (Configuration::get('EBAY_ORDER_LAST_UPDATE') < date('Y-m-d', strtotime('-30 minutes')) . 'T' . date('H:i:s', strtotime('-30 minutes')) . '.000Z') {
         // Lock
         Configuration::updateValue('EBAY_ORDER_LAST_UPDATE', $dateNew);
         // eBay Request
         $ebay = new eBayRequest();
         $page = 1;
         $orderList = array();
         $orderCount = 0;
         $orderCountTmp = 100;
         while ($orderCountTmp == 100 && $page < 10) {
             $orderListTmp = $ebay->getOrders(date('Y-m-d', strtotime('-30 days')) . 'T' . date('H:i:s', strtotime('-30 days')) . '.000Z', $dateNew, $page);
             $orderCountTmp = count($orderListTmp);
             $orderList = array_merge((array) $orderList, (array) $orderListTmp);
             $orderCount += $orderCountTmp;
             $page++;
         }
         if ($orderList) {
             foreach ($orderList as $korder => $order) {
                 if ($order['status'] == 'Complete' && $order['amount'] > 0.1 && isset($order['product_list']) && count($order['product_list'])) {
                     if (!Db::getInstance()->getValue('SELECT `id_ebay_order` FROM `' . _DB_PREFIX_ . 'ebay_order` WHERE `id_order_ref` = \'' . pSQL($order['id_order_ref']) . '\'')) {
                         $id_customer = (int) Db::getInstance()->getValue('SELECT `id_customer` FROM `' . _DB_PREFIX_ . 'customer` WHERE `active` = 1 AND `email` = \'' . pSQL($order['email']) . '\' AND `deleted` = 0' . (substr(_PS_VERSION_, 0, 3) == '1.3' ? '' : ' AND `is_guest` = 0'));
                         // Check for empty name
                         $order['firstname'] = trim($order['firstname']);
                         $order['familyname'] = trim($order['familyname']);
                         if (empty($order['familyname'])) {
                             $order['familyname'] = $order['firstname'];
                         }
                         if (empty($order['firstname'])) {
                             $order['firstname'] = $order['familyname'];
                         }
                         if (empty($order['phone']) || !Validate::isPhoneNumber($order['phone'])) {
                             $order['phone'] = '0100000000';
                         }
                         if (Validate::isEmail($order['email']) && !empty($order['firstname']) && !empty($order['familyname'])) {
                             // Add customer if he doesn't exist
                             if ($id_customer < 1) {
                                 $customer = new Customer();
                                 $customer->id_gender = 9;
                                 $customer->id_default_group = 1;
                                 $customer->secure_key = md5(uniqid(rand(), true));
                                 $customer->email = $order['email'];
                                 $customer->passwd = md5(pSQL(_COOKIE_KEY_ . rand()));
                                 $customer->last_passwd_gen = pSQL(date('Y-m-d H:i:s'));
                                 $customer->newsletter = 0;
                                 $customer->lastname = pSQL($order['familyname']);
                                 $customer->firstname = pSQL($order['firstname']);
                                 $customer->active = 1;
                                 $customer->add();
                                 $id_customer = $customer->id;
                             }
                             // Search if address exists
                             $id_address = (int) Db::getInstance()->getValue('SELECT `id_address` FROM `' . _DB_PREFIX_ . 'address` WHERE `id_customer` = ' . (int) $id_customer . ' AND `alias` = \'eBay\'');
                             if ($id_address > 0) {
                                 $address = new Address((int) $id_address);
                             } else {
                                 $address = new Address();
                                 $address->id_customer = (int) $id_customer;
                             }
                             $address->id_country = (int) Country::getByIso($order['country_iso_code']);
                             $address->alias = 'eBay';
                             $address->lastname = pSQL($order['familyname']);
                             $address->firstname = pSQL($order['firstname']);
                             $address->address1 = pSQL($order['address1']);
                             $address->address2 = pSQL($order['address2']);
                             $address->postcode = pSQL($order['postalcode']);
                             $address->city = pSQL($order['city']);
                             $address->phone = pSQL($order['phone']);
                             $address->active = 1;
                             if ($id_address > 0 && Validate::isLoadedObject($address)) {
                                 $address->update();
                             } else {
                                 $address->add();
                             }
                             $id_address = $address->id;
                             $flag = 1;
                             foreach ($order['product_list'] as $product) {
                                 if ((int) $product['id_product'] < 1 || !Db::getInstance()->getValue('SELECT `id_product` FROM `' . _DB_PREFIX_ . 'product` WHERE `id_product` = ' . (int) $product['id_product'])) {
                                     $flag = 0;
                                 }
                                 if (isset($product['id_product_attribute']) && $product['id_product_attribute'] > 0 && !Db::getInstance()->getValue('SELECT `id_product_attribute` FROM `' . _DB_PREFIX_ . 'product_attribute` WHERE `id_product` = ' . (int) $product['id_product'] . ' AND `id_product_attribute` = ' . (int) $product['id_product_attribute'])) {
                                     $flag = 0;
                                 }
                             }
                             if ($flag == 1) {
                                 $cartNbProducts = 0;
                                 $cartAdd = new Cart();
                                 $cartAdd->id_customer = $id_customer;
                                 $cartAdd->id_address_invoice = $id_address;
                                 $cartAdd->id_address_delivery = $id_address;
                                 $cartAdd->id_carrier = 1;
                                 $cartAdd->id_lang = $this->id_lang;
                                 $cartAdd->id_currency = Currency::getIdByIsoCode('EUR');
                                 $cartAdd->recyclable = 0;
                                 $cartAdd->gift = 0;
                                 $cartAdd->add();
                                 foreach ($order['product_list'] as $product) {
                                     if ($cartAdd->updateQty((int) $product['quantity'], (int) $product['id_product'], isset($product['id_product_attribute']) && $product['id_product_attribute'] > 0 ? $product['id_product_attribute'] : NULL)) {
                                         $cartNbProducts++;
                                     }
                                 }
                                 $cartAdd->update();
                                 // Check number of products in the cart
                                 if ($cartNbProducts > 0) {
                                     // Fix on sending e-mail
                                     Db::getInstance()->autoExecute(_DB_PREFIX_ . 'customer', array('email' => 'NOSEND-EBAY'), 'UPDATE', '`id_customer` = ' . (int) $id_customer);
                                     $customerClear = new Customer();
                                     if (method_exists($customerClear, 'clearCache')) {
                                         $customerClear->clearCache(true);
                                     }
                                     // Validate order
                                     $paiement = new eBayPayment();
                                     $paiement->validateOrder(intval($cartAdd->id), Configuration::get('PS_OS_PAYMENT'), floatval($cartAdd->getOrderTotal(true, 3)), 'eBay ' . $order['payment_method'] . ' ' . $order['id_order_seller'], NULL, array(), intval($cartAdd->id_currency));
                                     $id_order = $paiement->currentOrder;
                                     // Fix on date
                                     Db::getInstance()->autoExecute(_DB_PREFIX_ . 'orders', array('date_add' => pSQL($order['date_add'])), 'UPDATE', '`id_order` = ' . (int) $id_order);
                                     // Fix on sending e-mail
                                     Db::getInstance()->autoExecute(_DB_PREFIX_ . 'customer', array('email' => pSQL($order['email'])), 'UPDATE', '`id_customer` = ' . (int) $id_customer);
                                     // Update price (because of possibility of price impact)
                                     $updateOrder = array('total_paid' => floatval($order['amount']), 'total_paid_real' => floatval($order['amount']), 'total_products' => floatval($order['amount']), 'total_products_wt' => floatval($order['amount']), 'total_shipping' => floatval($order['shippingServiceCost']));
                                     Db::getInstance()->autoExecute(_DB_PREFIX_ . 'orders', $updateOrder, 'UPDATE', '`id_order` = ' . (int) $id_order);
                                     foreach ($order['product_list'] as $product) {
                                         Db::getInstance()->autoExecute(_DB_PREFIX_ . 'order_detail', array('product_price' => floatval($product['price']), 'tax_rate' => 0, 'reduction_percent' => 0), 'UPDATE', '`id_order` = ' . (int) $id_order . ' AND `product_id` = ' . (int) $product['id_product'] . ' AND `product_attribute_id` = ' . (int) $product['id_product_attribute']);
                                     }
                                     // Register the ebay order ref
                                     Db::getInstance()->autoExecute(_DB_PREFIX_ . 'ebay_order', array('id_order_ref' => pSQL($order['id_order_ref']), 'id_order' => (int) $id_order), 'INSERT');
                                 } else {
                                     $cartAdd->delete();
                                     $orderList[$korder]['errors'][] = $this->l('Could not add product to cart (maybe your stock quantity is 0)');
                                 }
                             } else {
                                 $orderList[$korder]['errors'][] = $this->l('Could not found products in database');
                             }
                         } else {
                             $orderList[$korder]['errors'][] = $this->l('Invalid e-mail');
                         }
                     } else {
                         $orderList[$korder]['errors'][] = $this->l('Order already imported');
                     }
                 } else {
                     $orderList[$korder]['errors'][] = $this->l('Status not complete or amount less than 0.1 or no product matching');
                 }
             }
             file_put_contents(dirname(__FILE__) . '/log/orders.php', "<?php\n\n" . '$dateLastImport = ' . "'" . date('d/m/Y H:i:s') . "';\n\n" . '$orderList = ' . var_export($orderList, true) . ";\n\n");
         }
     }
 }
    /**
     * Add customer
     * @param $order_infos
     * @return mixed
     */
    private function addCustomerInBDD($neteven_order)
    {
        // If customer exist
        $client = Db::getInstance()->getRow('
				SELECT c.`id_customer`
				FROM `' . _DB_PREFIX_ . 'customer` c
				INNER JOIN `' . _DB_PREFIX_ . 'orders_gateway_customer` ogc ON (ogc.`id_customer` = c.`id_customer`)
				WHERE ogc.`id_customer_neteven` = ' . (int) $neteven_order->CustomerId . '
				OR ogc.`mail_customer_neteven` = "_' . pSQL($neteven_order->BillingAddress->Email) . '"
				OR ogc.`mail_customer_neteven` = "_client' . (int) $neteven_order->OrderID . '@' . $neteven_order->MarketPlaceName . '.com"');
        if (!$client) {
            if (empty($neteven_order->CustomerId) && empty($neteven_order->BillingAddress->Email)) {
                return $this->getValue('id_customer_neteven');
            }
            Toolbox::addLogLine(self::getL('Creation of customer for NetEven order Id') . ' ' . $neteven_order->OrderID);
            $last_name = Toolbox::removeAccents($neteven_order->BillingAddress->LastName);
            $new_customer = new Customer();
            $new_customer->firstname = !empty($neteven_order->BillingAddress->FirstName) ? substr(Toolbox::stringFilter($neteven_order->BillingAddress->FirstName), 0, 32) : ' ';
            $new_customer->lastname = !empty($last_name) ? substr(Toolbox::stringFilter($last_name), 0, 32) : ' ';
            $new_customer->passwd = Tools::encrypt($this->getValue('default_passwd'));
            $new_customer->email = Validate::isEmail($neteven_order->BillingAddress->Email) && !empty($neteven_order->BillingAddress->Email) ? '_' . $neteven_order->BillingAddress->Email : '_client' . $neteven_order->OrderID . '@' . $neteven_order->MarketPlaceName . '.com';
            $new_customer->optin = 0;
            if (isset($this->repere_customer) && $this->repere_customer) {
                $new_customer->is_neteven = 1;
            }
            if (!$new_customer->add()) {
                Toolbox::addLogLine(self::getL('Failed for creation of customer of NetEven order Id') . ' ' . $neteven_order->OrderID);
            }
            // Insert customer in orders_gateway_customer table
            if (!empty($neteven_order->CustomerId)) {
                Db::getInstance()->Execute('INSERT INTO `' . _DB_PREFIX_ . 'orders_gateway_customer` (`id_customer`, `id_customer_neteven`) VALUES (' . (int) $new_customer->id . ', ' . (int) $neteven_order->CustomerId . ')');
            } else {
                Db::getInstance()->Execute('INSERT INTO `' . _DB_PREFIX_ . 'orders_gateway_customer` (`id_customer`, `mail_customer_neteven`) VALUES (' . (int) $new_customer->id . ', "' . (Validate::isEmail($neteven_order->BillingAddress->Email) ? pSQL('_' . $neteven_order->BillingAddress->Email) : pSQL('_client' . (int) $neteven_order->OrderID . '@' . $neteven_order->MarketPlaceName . '.com')) . '")');
            }
            return (int) $new_customer->id;
        }
        Toolbox::addLogLine(self::getL('Get existing customer for NetEven Order Id') . ' ' . $neteven_order->OrderID);
        return (int) $client['id_customer'];
    }
    private function _getCustomer($email, $lastname, $firstname)
    {
        $id_customer = (int) Db::getInstance()->getValue('SELECT `id_customer`
			FROM `' . _DB_PREFIX_ . 'customer` WHERE `email` = \'' . pSQL($email) . '\'');
        if ($id_customer) {
            return $id_customer;
        }
        $customer = new Customer();
        $customer->lastname = !empty($lastname) ? pSQL($lastname) : '-';
        $customer->firstname = !empty($firstname) ? pSQL($firstname) : '-';
        $customer->passwd = md5(pSQL(_COOKIE_KEY_ . rand()));
        $customer->id_default_group = 1;
        $customer->email = pSQL($email);
        $customer->add();
        return $customer->id;
    }
 public function installConfig()
 {
     $rand_letters = range('a', 'z');
     shuffle($rand_letters);
     // Creation of employee NetEven
     $new_employe = new Employee();
     $new_employe->lastname = 'Employee';
     $new_employe->firstname = 'NetEven';
     $new_employe->id_lang = (int) $this->context->language->id;
     $new_employe->email = 'empl' . rand(0, 100) . $rand_letters[0] . rand(0, 100) . '@neteven.com';
     $new_employe->passwd = $rand_letters[0] . '$&-$&-$&-$&' . rand(0, 1000);
     $new_employe->id_profile = 3;
     $new_employe->active = 0;
     $new_employe->add();
     Gateway::updateConfig('ID_EMPLOYEE_NETEVEN', (int) $new_employe->id);
     // Creation of customer Neteven
     $new_customer = new Customer();
     $new_customer->lastname = 'Client';
     $new_customer->firstname = 'NetEven';
     $new_customer->passwd = $rand_letters[0] . '$&-$&-$&-$&' . rand(0, 1000);
     $new_customer->email = 'cust' . rand(0, 100) . $rand_letters[0] . rand(0, 100) . '@neteven.com';
     $new_customer->newsletter = 0;
     $new_customer->optin = 0;
     $new_customer->add();
     Gateway::updateConfig('ID_CUSTOMER_NETEVEN', (int) $new_customer->id);
     // Creation of order status Neteven
     $order_state = new OrderState();
     $order_state->name = array();
     foreach (Language::getLanguages() as $language) {
         $order_state->name[(int) $language['id_lang']] = $this->l('Statut NetEven');
     }
     $order_state->send_email = false;
     $order_state->color = '#7d204d';
     $order_state->hidden = false;
     $order_state->delivery = false;
     $order_state->logable = false;
     $order_state->invoice = false;
     if ($order_state->add()) {
         $source = dirname(__FILE__) . '/img/os.gif';
         $destination = dirname(__FILE__) . '/../../img/os/' . (int) $order_state->id . '.gif';
         copy($source, $destination);
     }
     // Set the configuration
     Gateway::updateConfig('ID_ORDER_STATE_NETEVEN', $order_state->id);
     Gateway::updateConfig('SHIPPING_DELAY', 3);
     Gateway::updateConfig('COMMENT', $this->l('Livraison rapide et soignée'));
     Gateway::updateConfig('DEFAULT_BRAND', Configuration::get('PS_SHOP_NAME'));
     Gateway::updateConfig('COUNTRY_DEFAULT', 8);
     Gateway::updateConfig('PASSWORD_DEFAULT', 'password');
     Gateway::updateConfig('NETEVEN_URL', 'http://ws.neteven.com/NWS');
     Gateway::updateConfig('NETEVEN_NS', 'urn:NWS:examples');
     Gateway::updateConfig('SYNCHRONISATION_ORDER', 0);
     Gateway::updateConfig('SYNCHRONISATION_PRODUCT', 0);
     Gateway::updateConfig('MAIL_ACTIVE', 1);
     Gateway::updateConfig('SEND_SHIPPING_PRICE', 0);
     Gateway::updateConfig('SHIPPING_BY_PRODUCT', 0);
     Gateway::updateConfig('SHIPPING_BY_PRODUCT_FIELDNAME', 'additional_shipping_cost');
     Gateway::updateConfig('IMAGE_TYPE_NAME', '');
     $this->installCarrier();
     return true;
 }
 $customer = null;
 // Create Customer if not exist with address etc
 if ($ppec->getContext()->cookie->logged) {
     if (!($id_customer = Paypal::getPayPalCustomerIdByEmail($ppec->result['EMAIL']))) {
         PayPal::addPayPalCustomer($ppec->getContext()->customer->id, $ppec->result['EMAIL']);
     }
     $customer = $ppec->getContext()->customer;
 } elseif ($id_customer = Customer::customerExists($ppec->result['EMAIL'], true)) {
     $customer = new Customer($id_customer);
 } else {
     $customer = new Customer();
     $customer->email = $ppec->result['EMAIL'];
     $customer->lastname = $ppec->result['LASTNAME'];
     $customer->firstname = $ppec->result['FIRSTNAME'];
     $customer->passwd = Tools::encrypt(Tools::passwdGen());
     $customer->add();
     PayPal::addPayPalCustomer($customer->id, $ppec->result['EMAIL']);
 }
 if (!$customer->id) {
     $ppec->logs[] = $ppec->l('Cannot create customer');
 }
 if (!isset($ppec->result['PAYMENTREQUEST_0_SHIPTOSTREET']) || !isset($ppec->result['PAYMENTREQUEST_0_SHIPTOCITY']) || !isset($ppec->result['SHIPTOZIP']) || !isset($ppec->result['COUNTRYCODE'])) {
     $ppec->redirectToCheckout($customer, $ppec->type != 'payment_cart');
 }
 foreach ($customer->getAddresses($ppec->getContext()->language->id) as $address) {
     if ($address['alias'] == 'Paypal_Address') {
         $address = new Address($address['id_address']);
         break;
     }
 }
 // Create address
 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 getOrAddCustomer()
    {
        $id_customer = (int) Db::getInstance()->getValue('SELECT `id_customer`
			FROM `' . _DB_PREFIX_ . 'customer`
			WHERE `active` = 1
			AND `email` = \'' . pSQL($this->email) . '\'
			AND `deleted` = 0' . (substr(_PS_VERSION_, 0, 3) == '1.3' ? '' : ' AND `is_guest` = 0'));
        // Add customer if he doesn't exist
        //if ($id_customer < 1) RAPH
        if (!$id_customer) {
            $customer = new Customer();
            $customer->id_gender = 0;
            $customer->id_default_group = 1;
            $customer->secure_key = md5(uniqid(rand(), true));
            $customer->email = $this->email;
            $customer->passwd = md5(pSQL(_COOKIE_KEY_ . rand()));
            $customer->last_passwd_gen = pSQL(date('Y-m-d H:i:s'));
            $customer->newsletter = 0;
            $customer->lastname = EbayOrder::_formatFamilyName($this->familyname);
            $customer->firstname = pSQL($this->firstname);
            $customer->active = 1;
            $customer->add();
            $id_customer = $customer->id;
        }
        $this->id_customer = $id_customer;
        return $id_customer;
    }
    public function update_cart_by_junglee_xml($order_id, $data)
    {
        $xml = simplexml_load_string($data);
        $prefix = _DB_PREFIX_;
        $tablename = $prefix . 'orders';
        $total_amount = 0;
        $total_principal = 0;
        $shipping_amount = 0;
        $total_promo = 0;
        foreach ($xml->ProcessedOrder->ProcessedOrderItems->ProcessedOrderItem as $item) {
            $product_id = (string) $item->SKU;
            $product = new Product((int) $product_id);
            $SKU = $product->reference;
            $Title = (string) $item->Title;
            $Amount = (double) $item->Price->Amount;
            $other_promo = 0;
            foreach ($item->ItemCharges->Component as $amount_type) {
                $item_charge_type = (string) $amount_type->Type;
                if ($item_charge_type == 'Principal') {
                    $principal = (string) $amount_type->Charge->Amount;
                }
                if ($item_charge_type == 'Shipping') {
                    $Shipping = (string) $amount_type->Charge->Amount;
                }
                if ($item_charge_type == 'PrincipalPromo') {
                    $principal_promo = (string) $amount_type->Charge->Amount;
                }
                if ($item_charge_type == 'ShippingPromo') {
                    $shipping_promo = (string) $amount_type->Charge->Amount;
                }
                if ($item_charge_type == 'OtherPromo') {
                    $other_promo = (string) $amount_type->Charge->Amount;
                }
            }
            $CurrencyCode = (string) $item->Price->CurrencyCode;
            $Quantity = (int) $item->Quantity;
            $total_principal += $principal;
            $total_amount += $principal - $principal_promo + ($Shipping - $shipping_promo);
            $shipping_amount += $Shipping;
            $total_promo += $principal_promo + $shipping_promo + $other_promo;
        }
        $ShippingServiceLevel = (string) $xml->ProcessedOrder->ShippingServiceLevel;
        $sql = 'UPDATE `' . $prefix . 'pwa_orders` set `shipping_service` = "' . $ShippingServiceLevel . '" , `order_type` = "junglee" where `prestashop_order_id` = "' . $order_id . '" ';
        Db::getInstance()->Execute($sql);
        $email = (string) $xml->ProcessedOrder->BuyerInfo->BuyerEmailAddress;
        $sql = 'SELECT * from `' . $prefix . 'customer` where email = "' . $email . '" ';
        $results = Db::getInstance()->ExecuteS($sql);
        if (empty($results)) {
            $name = (string) $xml->ProcessedOrder->BuyerInfo->BuyerName;
            $name_arr = explode(' ', $name);
            if (count($name_arr) > 1) {
                $firstname = '';
                for ($i = 0; $i <= count($name_arr) - 2; $i++) {
                    $firstname = $firstname . ' ' . $name_arr[$i];
                }
                $lastname = $name_arr[count($name_arr) - 1];
            } else {
                $firstname = $name;
                $lastname = '.';
            }
            $password = Tools::passwdGen();
            $customer = new Customer();
            $customer->firstname = trim($firstname);
            $customer->lastname = $lastname;
            $customer->email = (string) $xml->ProcessedOrder->BuyerInfo->BuyerEmailAddress;
            $customer->passwd = md5($password);
            $customer->active = 1;
            if (Configuration::get('PS_GUEST_CHECKOUT_ENABLED')) {
                $customer->is_guest = 1;
            } else {
                $customer->is_guest = 0;
            }
            $customer->add();
            $customer_id = $customer->id;
            if (Configuration::get('PS_CUSTOMER_CREATION_EMAIL') && !Configuration::get('PS_GUEST_CHECKOUT_ENABLED')) {
                Mail::Send($this->context->language->id, 'account', Mail::l('Welcome!'), array('{firstname}' => $customer->firstname, '{lastname}' => $customer->lastname, '{email}' => $customer->email, '{passwd}' => $password), $customer->email, $customer->firstname . ' ' . $customer->lastname);
            }
        } else {
            $customer_id = $results[0]['id_customer'];
        }
        $id_country = Country::getByIso((string) $xml->ProcessedOrder->ShippingAddress->CountryCode);
        if ($id_country == 0 || $id_country == '') {
            $id_country = 110;
        }
        $name = (string) $xml->ProcessedOrder->ShippingAddress->Name;
        $name_arr = explode(' ', $name);
        if (count($name_arr) > 1) {
            $firstname = '';
            for ($i = 0; $i <= count($name_arr) - 2; $i++) {
                $firstname = $firstname . ' ' . $name_arr[$i];
            }
            $lastname = $name_arr[count($name_arr) - 1];
        } else {
            $firstname = $name;
            $lastname = '.';
        }
        $address = new Address();
        $address->id_country = $id_country;
        $address->id_state = 0;
        $address->id_customer = $customer_id;
        $address->alias = 'My Address';
        $address->firstname = trim($firstname);
        $address->lastname = $lastname;
        $address->address1 = (string) $xml->ProcessedOrder->ShippingAddress->AddressFieldOne;
        $address->address2 = (string) $xml->ProcessedOrder->ShippingAddress->AddressFieldTwo;
        $address->postcode = (string) $xml->ProcessedOrder->ShippingAddress->PostalCode;
        $address->city = (string) $xml->ProcessedOrder->ShippingAddress->City . ' ' . (string) $xml->ProcessedOrder->ShippingAddress->State;
        $address->active = 1;
        $address->add();
        $address_id = $address->id;
        //$id_order_state = Configuration::get('PS_OS_PREPARATION');
        $id_order_state = 99;
        $reference = Order::generateReference();
        $order = new Order();
        $order->id = $order_id;
        $order->id_customer = (int) $customer_id;
        $order->id_address_invoice = (int) $address_id;
        $carrier = null;
        $sql = 'SELECT id_carrier from  `' . $prefix . 'carrier` where `active` = 1 and `deleted` = 0 limit 0,1';
        $result = Db::getInstance()->ExecuteS($sql);
        $id_carrier = $result[0]['id_carrier'];
        $sql = 'SELECT id_currency from  `' . $prefix . 'currency` where `active` = 1 and `deleted` = 0 and `iso_code` = "INR" limit 0,1';
        $result = Db::getInstance()->ExecuteS($sql);
        $currency_id = $result[0]['id_currency'];
        $sql = 'UPDATE `' . $tablename . '` set 
			  `id_customer` = ' . (int) $customer_id . ',
			  `id_carrier` = ' . $id_carrier . ',
			  `id_address_invoice` = ' . (int) $address_id . ',
			  `id_address_delivery` = ' . (int) $address_id . ',
			  `id_currency` = ' . $currency_id . ',
			  `reference` = "' . $reference . '",
			  `secure_key` = "' . md5(uniqid()) . '",
			  
			  `total_paid` = ' . $total_amount . ',
			  `total_paid_tax_incl` = ' . $total_amount . ',
			  `total_paid_tax_excl` = ' . $total_amount . ',
			  `total_paid_real` = 0,
			 
			  `total_shipping` = ' . $shipping_amount . ',
			  `total_shipping_tax_incl` = ' . $shipping_amount . ',
			  `total_shipping_tax_excl` = ' . $shipping_amount . ',
			  
			  `total_discounts` = ' . (double) $total_promo . ',
			  `total_discounts_tax_incl` = ' . (double) $total_promo . ',
			  `total_discounts_tax_excl` = ' . (double) $total_promo . ',
			  
			  `total_products` = ' . $total_principal . ',
			  `total_products_wt` = ' . $total_principal . ',
			  
			  `invoice_date` = "0000-00-00 00:00:00",
			  `delivery_date` = "0000-00-00 00:00:00"
			  where `id_order` = ' . $order_id . ' ';
        //`round_mode` = '.Configuration::get('PS_PRICE_ROUND_MODE').',
        /*`total_wrapping_tax_incl` = '.$WrappingAmount.',
          `total_wrapping_tax_excl` = '.$WrappingAmount.',
          `total_wrapping` = '.$WrappingAmount.',*/
        Db::getInstance()->Execute($sql);
        $acknowledge_arr = array();
        $i = 0;
        foreach ($xml->ProcessedOrder->ProcessedOrderItems->ProcessedOrderItem as $item) {
            $product_id = (string) $item->SKU;
            $product = new Product((int) $product_id);
            $SKU = $product->reference;
            $AmazonOrderItemCode = (string) $item->AmazonOrderItemCode;
            $Title = (string) $item->Title;
            $Amount = (double) $item->Price->Amount;
            $acknowledge_arr['items'][$i]['AmazonOrderItemCode'] = $AmazonOrderItemCode;
            $acknowledge_arr['items'][$i]['product_id'] = $product_id;
            $CurrencyCode = (string) $item->Price->CurrencyCode;
            $Quantity = (int) $item->Quantity;
            $other_promo = 0;
            foreach ($item->ItemCharges->Component as $amount_type) {
                $item_charge_type = (string) $amount_type->Type;
                if ($item_charge_type == 'Principal') {
                    $principal = (string) $amount_type->Charge->Amount;
                }
                if ($item_charge_type == 'Shipping') {
                    $Shipping = (string) $amount_type->Charge->Amount;
                }
                if ($item_charge_type == 'PrincipalPromo') {
                    $principal_promo = (string) $amount_type->Charge->Amount;
                }
                if ($item_charge_type == 'ShippingPromo') {
                    $shipping_promo = (string) $amount_type->Charge->Amount;
                }
                if ($item_charge_type == 'OtherPromo') {
                    $other_promo = (string) $amount_type->Charge->Amount;
                }
            }
            $sql = 'INSERT into `' . $prefix . 'order_detail` set
							`id_order` = ' . $order_id . ',
							`product_id` = ' . $product_id . ',
							`product_name` = "' . $Title . '",
							`product_quantity` = ' . $Quantity . ',
							`product_quantity_in_stock` = ' . $Quantity . ',
							`product_price` = ' . $Amount . ',
							`product_reference` = "' . $SKU . '",
							`total_price_tax_incl` = ' . $Amount * $Quantity . ',
							`total_price_tax_excl` = ' . $Amount * $Quantity . ',
							`unit_price_tax_incl` = ' . $Amount . ',
							`unit_price_tax_excl` = ' . $Amount . ',
							`original_product_price` = ' . $Amount . '
							';
            Db::getInstance()->Execute($sql);
            $sql = 'UPDATE `' . $prefix . 'stock_available` set
						`quantity` = `quantity` - ' . $Quantity . '
						where `id_product` = ' . $product_id . ' and
						`id_product_attribute` = 0
						';
            Db::getInstance()->Execute($sql);
            $date = date('Y-m-d');
            $sql = 'UPDATE `' . $prefix . 'product_sale` set
						`quantity` = `quantity` + ' . $Quantity . ',
						`sale_nbr` = `sale_nbr` + ' . $Quantity . ',
						`date_upd` = ' . $date . '
						where `id_product` = ' . $product_id . '
						';
            Db::getInstance()->Execute($sql);
            $i++;
        }
        // Adding an entry in order_carrier table
        if (!is_null($carrier)) {
            $order_carrier = new OrderCarrier();
            $order_carrier->id_order = (int) $order->id;
            $order_carrier->id_carrier = (int) $id_carrier;
            $order_carrier->weight = '0';
            $order_carrier->shipping_cost_tax_excl = (double) $shipping_amount;
            $order_carrier->shipping_cost_tax_incl = (double) $shipping_amount;
            $order_carrier->add();
        } else {
            $order_carrier = new OrderCarrier();
            $order_carrier->id_order = (int) $order->id;
            $order_carrier->id_carrier = (int) $id_carrier;
            $order_carrier->weight = '0';
            $order_carrier->shipping_cost_tax_excl = (double) $shipping_amount;
            $order_carrier->shipping_cost_tax_incl = (double) $shipping_amount;
            $order_carrier->add();
        }
        // Set the order status
        $history = new OrderHistory();
        $history->id_order = (int) $order->id;
        $history->changeIdOrderState((int) $id_order_state, $order->id, true);
        $history->addWithemail(true, array());
        $acknowledge_arr['MerchantOrderID'] = (int) $order->id;
    }
 public function install()
 {
     if (!parent::install() || !$this->registerHook('displayPayment') || !$this->registerHook('paymentReturn') || !$this->registerHook('displayFooter') || !$this->registerHook('displayHeader') || !$this->registerHook('ModuleRoutes') || !$this->registerHook('displayOrderConfirmation') || !$this->registerHook('displayAdminOrder') || !$this->registerHook('actionOrderStatusUpdate')) {
         return false;
     }
     $status = array('DELIVERY' => array('name' => 'YA Ждёт отправки', 'color' => '#8A2BE2', 'id' => 900, 'paid' => true, 'shipped' => false, 'logable' => true, 'delivery' => true), 'CANCELLED' => array('name' => 'YA Отменен', 'color' => '#b70038', 'id' => 901, 'paid' => false, 'shipped' => false, 'logable' => true, 'delivery' => false), 'PICKUP' => array('name' => 'YA В пункте самовывоза', 'color' => '#cd98ff', 'id' => 902, 'paid' => true, 'shipped' => true, 'logable' => true, 'delivery' => true), 'PROCESSING' => array('name' => 'YA В процессе подготовки', 'color' => '#FF8C00', 'id' => 903, 'paid' => true, 'shipped' => false, 'logable' => false, 'delivery' => true), 'DELIVERED' => array('name' => 'YA Доставлен', 'color' => '#108510', 'id' => 904, 'paid' => true, 'shipped' => true, 'logable' => true, 'delivery' => true), 'UNPAID' => array('name' => 'YA Не оплачен', 'color' => '#ff1c30', 'id' => 905, 'paid' => false, 'shipped' => false, 'logable' => false, 'delivery' => false), 'RESERVATION_EXPIRED' => array('name' => 'YA Резерв отменён', 'color' => '#ff2110', 'id' => 906, 'paid' => false, 'shipped' => false, 'logable' => false, 'delivery' => false), 'RESERVATION' => array('name' => 'YA Резерв', 'color' => '#0f00d3', 'id' => 907, 'paid' => false, 'shipped' => false, 'logable' => false, 'delivery' => false));
     foreach ($status as $s) {
         $os = new OrderState((int) $s['id']);
         $os->id = $s['id'];
         $os->force_id = true;
         $os->name = $this->multiLangField($s['name']);
         $os->color = $s['color'];
         $os->module_name = $this->name;
         $os->paid = $s['paid'];
         $os->logable = $s['logable'];
         $os->shipped = $s['shipped'];
         $os->delivery = $s['delivery'];
         $os->add();
     }
     $sql = array();
     $sql[] = 'CREATE TABLE IF NOT EXISTS `' . _DB_PREFIX_ . 'pokupki_orders`
         (
             `id_order` int(10) NOT NULL,
             `id_market_order` varchar(100) NOT NULL,
             `currency` varchar(100) NOT NULL,
             `ptype` varchar(100) NOT NULL,
             `home` varchar(100) NOT NULL,
             `pmethod` varchar(100) NOT NULL,
             `outlet` varchar(100) NOT NULL,
             PRIMARY KEY  (`id_order`,`id_market_order`)
         ) ENGINE=' . _MYSQL_ENGINE_ . ' DEFAULT CHARSET=utf8 COLLATE=utf8_general_ci';
     $sql[] = 'CREATE TABLE IF NOT EXISTS `' . _DB_PREFIX_ . 'mws_return`
         (
             `id_return` int(10) NOT NULL AUTO_INCREMENT,
             `invoice_id` varchar(128) NOT NULL,
             `cause` varchar(256) NOT NULL,
             `amount` DECIMAL(10,2) NOT NULL,
             `request` varchar(1024) NOT NULL,
             `response` varchar(1024) NOT NULL,
             `status` varchar(1024) NOT NULL,
             `error` varchar(1024) NOT NULL,
             `date` datetime NOT NULL,
             PRIMARY KEY  (`id_return`,`invoice_id`)
         ) ENGINE=' . _MYSQL_ENGINE_ . ' DEFAULT CHARSET=utf8 COLLATE=utf8_general_ci';
     foreach ($sql as $qr) {
         Db::getInstance()->execute($qr);
     }
     $customer = new Customer();
     $customer->firstname = 'YA POKUPKI Not Delete';
     $customer->lastname = 'YA POKUPKI Not Delete';
     $customer->email = '*****@*****.**';
     $customer->passwd = Tools::encrypt('OPC123456dmo');
     $customer->newsletter = 1;
     $customer->optin = 1;
     $customer->active = 0;
     $customer->add();
     Configuration::updateValue('YA_POKUPKI_CUSTOMER', $customer->id);
     Configuration::updateValue('YA_ORG_INSIDE', 1);
     return true;
 }
 $_POST['firstname'] = $_POST['customer_firstname'];
 $errors = $customer->validateControler();
 $_POST['lastname'] = $addrLastname;
 $_POST['firstname'] = $addrFirstname;
 $address = new Address();
 $address->id_customer = 1;
 $errors = array_unique(array_merge($errors, $address->validateControler()));
 if (!sizeof($errors)) {
     if (!($country = new Country($address->id_country)) or !Validate::isLoadedObject($country)) {
         die(Tools::displayError());
     }
     if (intval($country->contains_states) and !intval($address->id_state)) {
         $errors[] = Tools::displayError('this country require a state selection');
     } else {
         $customer->active = 1;
         if (!$customer->add()) {
             $errors[] = Tools::displayError('an error occurred while creating your account');
         } else {
             $address->id_customer = intval($customer->id);
             if (!$address->add()) {
                 $errors[] = Tools::displayError('an error occurred while creating your address');
             } else {
                 if (!Mail::Send(intval($cookie->id_lang), 'account', 'Welcome!', array('{firstname}' => $customer->firstname, '{lastname}' => $customer->lastname, '{email}' => $customer->email, '{passwd}' => Tools::getValue('passwd')), $customer->email, $customer->firstname . ' ' . $customer->lastname)) {
                     $errors[] = Tools::displayError('cannot send email');
                 }
                 $smarty->assign('confirmation', 1);
                 $cookie->id_customer = intval($customer->id);
                 $cookie->customer_lastname = $customer->lastname;
                 $cookie->customer_firstname = $customer->firstname;
                 $cookie->passwd = $customer->passwd;
                 $cookie->logged = 1;
 /**
  * Create a prestashop Customer
  * @param type $billingAddress
  * @param type $email
  * @return type
  */
 function createPrestashopCustomer($billingAddress, $email)
 {
     $customer_object = new Customer();
     $customer_object->firstname = $billingAddress->getfirstName();
     $customer_object->lastname = $billingAddress->getLastName();
     $customer_object->email = $email;
     $customer_object->passwd = md5(uniqid(rand(), true));
     $customer_object->add();
     return $customer_object->id;
 }