/**
     * @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');
    }
 /**
  * Start forms process.
  *
  * @see FrontController::postProcess()
  */
 public function postProcess()
 {
     $order_reference = current(explode('#', Tools::getValue('order_reference')));
     $email = Tools::getValue('email');
     if (!$email && !$order_reference) {
         return;
     } elseif (!$email || !$order_reference) {
         $this->errors[] = $this->getTranslator()->trans('Please provide the required information', array(), 'Shop.Notifications.Error');
         return;
     }
     $isCustomer = Customer::customerExists($email, false, true);
     if ($isCustomer) {
         $this->info[] = $this->trans('Please log in to your customer account to view the order', array(), 'Shop.Notifications.Info');
         $this->redirectWithNotifications($this->context->link->getPageLink('history'));
     } else {
         $this->order = Order::getByReferenceAndEmail($order_reference, $email);
         if (!Validate::isLoadedObject($this->order)) {
             $this->errors[] = $this->getTranslator()->trans('We couldn\'t find your order with the information provided, please try again', array(), 'Shop.Notifications.Error');
         }
     }
     if (Tools::isSubmit('submitTransformGuestToCustomer') && Tools::getValue('password')) {
         $customer = new Customer((int) $this->order->id_customer);
         $password = Tools::getValue('password');
         if (strlen($password) < Validate::PASSWORD_LENGTH) {
             $this->errors[] = $this->trans('Your password must be at least %min% characters long.', array('%min%' => Validate::PASSWORD_LENGTH), 'Shop.Forms.Help');
         } elseif ($customer->transformToCustomer($this->context->language->id, $password)) {
             $this->success[] = $this->trans('Your guest account has been successfully transformed into a customer account. You can now log in as a registered shopper.', array(), 'Shop.Notifications.Success');
         } else {
             $this->success[] = $this->trans('An unexpected error occurred while creating your account.', array(), 'Shop.Notifications.Error');
         }
     }
 }
 public function preProcess()
 {
     parent::preProcess();
     $customer = new Customer((int) self::$cookie->id_customer);
     if (isset($_POST['years']) && isset($_POST['months']) && isset($_POST['days'])) {
         $customer->birthday = (int) $_POST['years'] . '-' . (int) $_POST['months'] . '-' . (int) $_POST['days'];
     }
     if (Tools::isSubmit('submitIdentity')) {
         if (Module::getInstanceByName('blocknewsletter')->active) {
             if (!isset($_POST['optin'])) {
                 $customer->optin = 0;
             }
             if (!isset($_POST['newsletter'])) {
                 $customer->newsletter = 0;
             }
         }
         if (!isset($_POST['id_gender'])) {
             $_POST['id_gender'] = 9;
         }
         if (!@checkdate(Tools::getValue('months'), Tools::getValue('days'), Tools::getValue('years')) && !(Tools::getValue('months') == '' && Tools::getValue('days') == '' && Tools::getValue('years') == '')) {
             $this->errors[] = Tools::displayError('Invalid date of birth');
         } else {
             $customer->birthday = empty($_POST['years']) ? '' : (int) $_POST['years'] . '-' . (int) $_POST['months'] . '-' . (int) $_POST['days'];
             $id_customer_exists = (int) Customer::customerExists(Tools::getValue('email'), true, false);
             if ($id_customer_exists && $id_customer_exists != (int) self::$cookie->id_customer) {
                 $this->errors[] = Tools::displayError('An account is already registered with this e-mail.');
             }
             $_POST['old_passwd'] = trim($_POST['old_passwd']);
             if (empty($_POST['old_passwd']) || Tools::encrypt($_POST['old_passwd']) != self::$cookie->passwd) {
                 $this->errors[] = Tools::displayError('Your password is incorrect.');
             } elseif ($_POST['passwd'] != $_POST['confirmation']) {
                 $this->errors[] = Tools::displayError('Password and confirmation do not match');
             } else {
                 $prev_id_default_group = $customer->id_default_group;
                 $this->errors = array_unique(array_merge($this->errors, $customer->validateController(true, true)));
             }
             if (!count($this->errors)) {
                 $customer->id_default_group = (int) $prev_id_default_group;
                 $customer->firstname = Tools::ucfirst(Tools::strtolower($customer->firstname));
                 if (Tools::getValue('passwd')) {
                     self::$cookie->passwd = $customer->passwd;
                 }
                 if ($customer->update()) {
                     self::$cookie->customer_lastname = $customer->lastname;
                     self::$cookie->customer_firstname = $customer->firstname;
                     self::$smarty->assign('confirmation', 1);
                 } else {
                     $this->errors[] = Tools::displayError('Cannot update information');
                 }
             }
         }
     } else {
         $_POST = array_map('stripslashes', $customer->getFields());
     }
     $birthday = $customer->birthday ? explode('-', $customer->birthday) : array('-', '-', '-');
     /* Generate years, months and days */
     self::$smarty->assign(array('years' => Tools::dateYears(), 'sl_year' => $birthday[0], 'months' => Tools::dateMonths(), 'sl_month' => $birthday[1], 'days' => Tools::dateDays(), 'sl_day' => $birthday[2], 'errors' => $this->errors));
     self::$smarty->assign('newsletter', (int) Module::getInstanceByName('blocknewsletter')->active);
 }
 /**
  * Start forms process
  * @see FrontController::postProcess()
  */
 public function postProcess()
 {
     if (Tools::isSubmit('submitGuestTracking') || Tools::isSubmit('submitTransformGuestToCustomer')) {
         // These lines are here for retrocompatibility with old theme
         $id_order = Tools::getValue('id_order');
         $order_collection = array();
         if ($id_order) {
             if (is_numeric($id_order)) {
                 $order = new Order((int) $id_order);
                 if (Validate::isLoadedObject($order)) {
                     $order_collection = Order::getByReference($order->reference);
                 }
             } else {
                 $order_collection = Order::getByReference($id_order);
             }
         }
         // Get order reference, ignore package reference (after the #, on the order reference)
         $order_reference = current(explode('#', Tools::getValue('order_reference')));
         // Ignore $result_number
         if (!empty($order_reference)) {
             $order_collection = Order::getByReference($order_reference);
         }
         $email = Tools::getValue('email');
         if (empty($order_reference) && empty($id_order)) {
             $this->errors[] = Tools::displayError('Please provide your order\'s reference number.');
         } elseif (empty($email)) {
             $this->errors[] = Tools::displayError('Please provide a valid email address.');
         } elseif (!Validate::isEmail($email)) {
             $this->errors[] = Tools::displayError('Please provide a valid email address.');
         } elseif (!Customer::customerExists($email, false, false)) {
             $this->errors[] = Tools::displayError('There is no account associated with this email address.');
         } elseif (Customer::customerExists($email, false, true)) {
             $this->errors[] = Tools::displayError('This page is for guest accounts only. Since your guest account has already been transformed into a customer account, you can no longer view your order here. Please log in to your customer account to view this order');
             $this->context->smarty->assign('show_login_link', true);
         } elseif (!count($order_collection)) {
             $this->errors[] = Tools::displayError('Invalid order reference');
         } elseif (!$order_collection->getFirst()->isAssociatedAtGuest($email)) {
             $this->errors[] = Tools::displayError('Invalid order reference');
         } else {
             $this->assignOrderTracking($order_collection);
             if (Tools::isSubmit('submitTransformGuestToCustomer')) {
                 $customer = new Customer((int) $order->id_customer);
                 if (!Validate::isLoadedObject($customer)) {
                     $this->errors[] = Tools::displayError('Invalid customer');
                 } elseif (!Tools::getValue('password')) {
                     $this->errors[] = Tools::displayError('Invalid password.');
                 } elseif (!$customer->transformToCustomer($this->context->language->id, Tools::getValue('password'))) {
                     // @todo clarify error message
                     $this->errors[] = Tools::displayError('An error occurred while transforming a guest into a registered customer.');
                 } else {
                     $this->context->smarty->assign('transformSuccess', true);
                 }
             }
         }
     }
 }
 public function preProcess()
 {
     global $cookie;
     $customer = new Customer((int) self::$cookie->id_customer);
     if (Tools::getValue('ref_emails')) {
         $emails = Tools::getValue('ref_emails');
         $emails = str_replace("\n", "", $emails);
         $emails = trim($emails);
         $emailList = explode(",", $emails);
         $invited = false;
         $db = Db::getInstance(_PS_USE_SQL_SLAVE_);
         $countInvited = 0;
         $countInvalid = 0;
         $invite_id = time();
         $date_invite = date('Y-m-d H:i:s');
         $pattern = '/<?([a-z0-9!#$%&\'*+\\/=?^`{}|~_-]+[.a-z0-9!#$%&\'*+\\/=?^`{}|~_-]*@[a-z0-9]+[._a-z0-9-]*\\.[a-z0-9]+)>?$/i';
         foreach ($emailList as $email) {
             $email = trim($email);
             $emailId = '';
             $name = '';
             //see if it contains the name
             if (strpos($email, '<') === false) {
                 $emailId = $email;
             } else {
                 preg_match($pattern, $email, $matches);
                 $emailId = $matches[1];
                 $name = strstr($email, '<', true);
             }
             $name = trim($name);
             $emailId = trim($emailId);
             //echo $name . ' : ' . $emailId . '<br />';
             if (!Validate::isEmail($emailId) || Customer::customerExists($emailId)) {
                 ++$countInvalid;
                 continue;
             }
             //Add referral record for this customer
             //$result = $db->getRow("SELECT `id_customer` FROM vb_customer_referrals WHERE email = '".$email."'");
             //if(!isset($result['id_customer']))
             $db->ExecuteS("INSERT INTO vb_customer_referrals (id_customer, email, date_add, id_invite, name) VALUES (" . $customer->id . ", '" . $emailId . "', '" . $date_invite . "', " . $invite_id . ", '" . $name . "')");
             ++$countInvited;
         }
         if ($countInvited) {
             Tools::sendSQSInviteMessage($invite_id, $customer->id);
         }
         self::$smarty->assign('countInvited', $countInvited);
         self::$smarty->assign('countInvalid', $countInvalid);
     }
     $res = Db::getInstance()->ExecuteS("select \n\t\t\t\t\t\t\t\t\t\t\tc.id_customer, \n\t\t\t\t\t\t\t\t\t\t\tconcat(c.firstname, ' ', c.lastname) as 'name', \n\t\t\t\t\t\t\t\t\t\t\tc.email, \n\t\t\t\t\t\t\t\t\t\t\tc.total_delivered,\n\t\t\t\t\t\t\t\t\t\t\tr.date_add\n\t\t\t\t\t\t\t\t\t\t\tfrom ps_customer c \n\t\t\t\t\t\t\t\t\t\t\tleft join vb_customer_referrals r on (c.email = r.email) \n\t\t\t\t\t\t\t\t\t\t\twhere id_referrer = " . self::$cookie->id_customer . "\n\t\t\t\t\t\t\t\t\t\t\tgroup by c.email");
     self::$smarty->assign(array('referrals' => $res, 'customer_id' => $customer->id));
     $res = Db::getInstance()->getRow("select count(*) as 'invited'\n\t\t\t\t\t\t\t\t\t\t\tfrom vb_customer_referrals\n\t\t\t\t\t\t\t\t\t\t\twhere id_customer = " . self::$cookie->id_customer . "\n\t\t\t\t\t\t\t\t\t\t\tgroup by email");
     if ($res && $res['invited'] > 0) {
         self::$smarty->assign('referrals_invited', 1);
     }
 }
Exemple #6
0
 public function validate()
 {
     $emailField = $this->getField('email');
     $id_customer = Customer::customerExists($emailField->getValue(), true, true);
     if ($id_customer && $id_customer != $this->getCustomer()->id) {
         $emailField->addError(sprintf($this->translator->trans('The email "%s" is already used, please choose another one or sign in', array(), 'Shop.Notifications.Error'), $emailField->getValue()));
     }
     // birthday is from input type text..., so we need to convert to a valid date
     $birthdayField = $this->getField('birthday');
     if (!empty($birthdayField)) {
         $birthdayValue = $birthdayField->getValue();
         if (!empty($birthdayValue)) {
             $dateBuilt = DateTime::createFromFormat(Context::getContext()->language->date_format_lite, $birthdayValue);
             if (!empty($dateBuilt)) {
                 $birthdayField->setValue($dateBuilt->format('Y-m-d'));
             }
         }
     }
     return parent::validate();
 }
     $error = 'conditions not valided';
 } else {
     $friendsLastName = Tools::getValue('friendsLastName');
     $friendsFirstName = Tools::getValue('friendsFirstName');
     $mails_exists = array();
     foreach ($friendsEmail as $key => $friendEmail) {
         $friendEmail = strval($friendEmail);
         $friendLastName = strval($friendsLastName[$key]);
         $friendFirstName = strval($friendsFirstName[$key]);
         if (empty($friendEmail) and empty($friendLastName) and empty($friendFirstName)) {
             continue;
         } elseif (empty($friendEmail) or !Validate::isEmail($friendEmail)) {
             $error = 'email invalid';
         } elseif (empty($friendFirstName) or empty($friendLastName) or !Validate::isName($friendLastName) or !Validate::isName($friendFirstName)) {
             $error = 'name invalid';
         } elseif (ReferralProgramModule::isEmailExists($friendEmail) or Customer::customerExists($friendEmail)) {
             $mails_exists[] = $friendEmail;
         } else {
             $referralprogram = new ReferralProgramModule();
             $referralprogram->id_sponsor = (int) $cookie->id_customer;
             $referralprogram->firstname = $friendFirstName;
             $referralprogram->lastname = $friendLastName;
             $referralprogram->email = $friendEmail;
             if (!$referralprogram->validateFields(false)) {
                 $error = 'name invalid';
             } else {
                 if ($referralprogram->save()) {
                     if (Configuration::get('PS_CIPHER_ALGORITHM')) {
                         $cipherTool = new Rijndael(_RIJNDAEL_KEY_, _RIJNDAEL_IV_);
                     } else {
                         $cipherTool = new Blowfish(_COOKIE_KEY_, _COOKIE_IV_);
 public function process()
 {
     global $link;
     parent::process();
     if (Tools::isSubmit('submitGuestTracking') or Tools::isSubmit('submitTransformGuestToCustomer')) {
         $id_order = (int) Tools::getValue('id_order');
         $email = Tools::getValue('email');
         $order = new Order((int) $id_order);
         if (empty($id_order)) {
             $this->errors[] = Tools::displayError('Please provide your Order ID');
         } elseif (empty($email)) {
             $this->errors[] = Tools::displayError('Please provide your e-mail address');
         } elseif (!Validate::isEmail($email)) {
             $this->errors[] = Tools::displayError('Please provide a valid e-mail address');
         } elseif (!Customer::customerExists($email, false, false)) {
             $this->errors[] = Tools::displayError('There is no account associated with this e-mail address');
         } elseif (Customer::customerExists($email, false, true)) {
             $this->errors[] = Tools::displayError('Your guest account has already been transformed into a customer account. Please log-in to your customer account to view this order, this section is reserved for guest accounts');
             self::$smarty->assign('show_login_link', true);
         } elseif (!Validate::isLoadedObject($order)) {
             $this->errors[] = Tools::displayError('Invalid Order ID');
         } elseif (!$order->isAssociatedAtGuest($email)) {
             $this->errors[] = Tools::displayError('This order has been placed by a customer account. Please log-in to your customer account to view this order, this section is reserved for guest accounts');
         } else {
             $customer = new Customer((int) $order->id_customer);
             $id_order_state = (int) $order->getCurrentState();
             $carrier = new Carrier((int) $order->id_carrier, (int) $order->id_lang);
             $addressInvoice = new Address((int) $order->id_address_invoice);
             $addressDelivery = new Address((int) $order->id_address_delivery);
             $inv_adr_fields = AddressFormat::getOrderedAddressFields((int) $addressInvoice->id_country);
             $dlv_adr_fields = AddressFormat::getOrderedAddressFields((int) $addressDelivery->id_country);
             $invoiceAddressFormatedValues = AddressFormat::getFormattedAddressFieldsValues($addressInvoice, $inv_adr_fields);
             $deliveryAddressFormatedValues = AddressFormat::getFormattedAddressFieldsValues($addressDelivery, $dlv_adr_fields);
             if ($order->total_discounts > 0) {
                 self::$smarty->assign('total_old', (double) ($order->total_paid - $order->total_discounts));
             }
             $products = $order->getProducts();
             $customizedDatas = Product::getAllCustomizedDatas((int) $order->id_cart);
             Product::addCustomizationPrice($products, $customizedDatas);
             $this->processAddressFormat($addressDelivery, $addressInvoice);
             self::$smarty->assign(array('shop_name' => Configuration::get('PS_SHOP_NAME'), 'order' => $order, 'return_allowed' => false, 'currency' => new Currency($order->id_currency), 'order_state' => (int) $id_order_state, 'invoiceAllowed' => (int) Configuration::get('PS_INVOICE'), 'invoice' => OrderState::invoiceAvailable((int) $id_order_state) and $order->invoice_number, 'order_history' => $order->getHistory((int) self::$cookie->id_lang, false, true), 'products' => $products, 'discounts' => $order->getDiscounts(), 'carrier' => $carrier, 'address_invoice' => $addressInvoice, 'invoiceState' => (Validate::isLoadedObject($addressInvoice) and $addressInvoice->id_state) ? new State((int) $addressInvoice->id_state) : false, 'address_delivery' => $addressDelivery, 'deliveryState' => (Validate::isLoadedObject($addressDelivery) and $addressDelivery->id_state) ? new State((int) $addressDelivery->id_state) : false, 'is_guest' => true, 'group_use_tax' => Group::getPriceDisplayMethod($customer->id_default_group) == PS_TAX_INC, 'CUSTOMIZE_FILE' => _CUSTOMIZE_FILE_, 'CUSTOMIZE_TEXTFIELD' => _CUSTOMIZE_TEXTFIELD_, 'use_tax' => Configuration::get('PS_TAX'), 'customizedDatas' => $customizedDatas, 'invoiceAddressFormatedValues' => $invoiceAddressFormatedValues, 'deliveryAddressFormatedValues' => $deliveryAddressFormatedValues));
             if ($carrier->url and $order->shipping_number) {
                 self::$smarty->assign('followup', str_replace('@', $order->shipping_number, $carrier->url));
             }
             self::$smarty->assign('HOOK_ORDERDETAILDISPLAYED', Module::hookExec('orderDetailDisplayed', array('order' => $order)));
             Module::hookExec('OrderDetail', array('carrier' => $carrier, 'order' => $order));
             if (Tools::isSubmit('submitTransformGuestToCustomer')) {
                 $customer = new Customer((int) $order->id_customer);
                 if (!Validate::isLoadedObject($customer)) {
                     $this->errors[] = Tools::displayError('Invalid customer');
                 }
                 if (!$customer->transformToCustomer(self::$cookie->id_lang, Tools::getValue('password'))) {
                     $this->errors[] = Tools::displayError('An error occurred while transforming guest to customer.');
                 }
                 if (!Tools::getValue('password')) {
                     $this->errors[] = Tools::displayError('Invalid password');
                 } else {
                     self::$smarty->assign('transformSuccess', true);
                 }
             }
         }
     }
     /* Handle brute force attacks */
     if (sizeof($this->errors)) {
         sleep(1);
     }
     self::$smarty->assign(array('action' => $link->getPageLink('guest-tracking.php'), 'errors' => $this->errors));
 }
Exemple #9
0
 /**
  * Start forms process
  * @see FrontController::postProcess()
  */
 public function postProcess()
 {
     $origin_newsletter = (bool) $this->customer->newsletter;
     if (Tools::isSubmit('submitIdentity')) {
         $email = trim(Tools::getValue('email'));
         if (Tools::getValue('months') != '' && Tools::getValue('days') != '' && Tools::getValue('years') != '') {
             $this->customer->birthday = (int) Tools::getValue('years') . '-' . (int) Tools::getValue('months') . '-' . (int) Tools::getValue('days');
         } elseif (Tools::getValue('months') == '' && Tools::getValue('days') == '' && Tools::getValue('years') == '') {
             $this->customer->birthday = null;
         } else {
             $this->errors[] = Tools::displayError('Invalid date of birth.');
         }
         if (Tools::getIsset('old_passwd')) {
             $old_passwd = trim(Tools::getValue('old_passwd'));
         }
         if (!Validate::isEmail($email)) {
             $this->errors[] = Tools::displayError('This email address is not valid');
         } elseif ($this->customer->email != $email && Customer::customerExists($email, true)) {
             $this->errors[] = Tools::displayError('An account using this email address has already been registered.');
         } elseif (!Tools::getIsset('old_passwd') || Tools::encrypt($old_passwd) != $this->context->cookie->passwd) {
             $this->errors[] = Tools::displayError('The password you entered is incorrect.');
         } elseif (Tools::getValue('passwd') != Tools::getValue('confirmation')) {
             $this->errors[] = Tools::displayError('The password and confirmation do not match.');
         } else {
             $prev_id_default_group = $this->customer->id_default_group;
             // Merge all errors of this file and of the Object Model
             $this->errors = array_merge($this->errors, $this->customer->validateController());
         }
         if (!count($this->errors)) {
             $this->customer->id_default_group = (int) $prev_id_default_group;
             $this->customer->firstname = Tools::ucwords($this->customer->firstname);
             if (Configuration::get('PS_B2B_ENABLE')) {
                 $this->customer->website = Tools::getValue('website');
                 // force update of website, even if box is empty, this allows user to remove the website
                 $this->customer->company = Tools::getValue('company');
             }
             if (!Tools::getIsset('newsletter')) {
                 $this->customer->newsletter = 0;
             } elseif (!$origin_newsletter && Tools::getIsset('newsletter')) {
                 if ($module_newsletter = Module::getInstanceByName('blocknewsletter')) {
                     /** @var Blocknewsletter $module_newsletter */
                     if ($module_newsletter->active) {
                         $module_newsletter->confirmSubscription($this->customer->email);
                     }
                 }
             }
             if (!Tools::getIsset('optin')) {
                 $this->customer->optin = 0;
             }
             if (Tools::getValue('passwd')) {
                 $this->context->cookie->passwd = $this->customer->passwd;
             }
             if ($this->customer->update()) {
                 $this->context->cookie->customer_lastname = $this->customer->lastname;
                 $this->context->cookie->customer_firstname = $this->customer->firstname;
                 $this->context->smarty->assign('confirmation', 1);
             } else {
                 $this->errors[] = Tools::displayError('The information cannot be updated.');
             }
         }
     } else {
         $_POST = array_map('stripslashes', $this->customer->getFields());
     }
     return $this->customer;
 }
Exemple #10
0
 private function create(Customer $customer, $clearTextPassword)
 {
     if (!$clearTextPassword) {
         if (!$this->guest_allowed) {
             $this->errors['password'][] = $this->translator->trans('Password is required', [], 'Shop.Notifications.Error');
             return false;
         }
         /**
          * Warning: this is only safe provided
          * that guests cannot log in even with the generated
          * password. That's the case at least at the time of writing.
          */
         $clearTextPassword = $this->crypto->encrypt(microtime(), _COOKIE_KEY_);
         $customer->is_guest = true;
     }
     $customer->passwd = $this->crypto->encrypt($clearTextPassword, _COOKIE_KEY_);
     if (Customer::customerExists($customer->email, false, true)) {
         $this->errors['email'][] = $this->translator->trans('An account was already registered with this email address', [], 'Shop.Notifications.Error');
         return false;
     }
     $ok = $customer->save();
     if ($ok) {
         $this->context->updateCustomer($customer);
         $this->context->cart->update();
         $this->sendConfirmationMail($customer);
         Hook::exec('actionCustomerAccountUpdate', array('customer' => $customer));
     }
     return $ok;
 }
 public function initFacebook()
 {
     global $smarty, $cookie, $cart;
     //echo str_replace('//','/',dirname(__FILE__).'/') .'facebook.php'; exi
     require_once str_replace('//', '/', dirname(__FILE__) . '/') . 'facebook.php';
     // Create our Application instance
     $this->facebook = new Facebook(array('appId' => FB_API_KEY, 'secret' => FB_SECRET, 'cookie' => true));
     //check if the user has logged in
     $fb_user = $this->facebook->getUser();
     // echo "<script>console.log("+$fb_user+")</script>";
     $userInfo = null;
     if ($fb_user) {
         try {
             // Proceed knowing you have a logged in user who's authenticated.
             $customer = new Customer();
             $customer = $customer->getByFacebookID($fb_user);
             if ($customer) {
                 $this->loginCustomer($customer);
                 if (Tools::getValue('fblogin') == 1) {
                     Tools::redirect('index.php');
                 } else {
                     return;
                 }
             }
             $userInfo = $this->facebook->api("/{$fb_user}");
         } catch (FacebookApiException $e) {
             $this->facebook->logout();
             $fb_user = null;
         }
     }
     $logoutUrl = $this->facebook->getLogoutUrl(array('next' => _PS_BASE_URL_ . __PS_BASE_URI__ . '?mylogout=1'));
     $smarty->assign('fblogout_url', $logoutUrl);
     // Login or logout url will be needed depending on current user state.
     if ($fb_user && $userInfo && $userInfo['email']) {
         //print_r($userInfo);print_r('<br/>');
         //dump fb data for this user first
         $this->dumpFacebookData($fb_user, $userInfo);
         //echo print_r($userInfo);exit;
         $userEmail = $userInfo['email'];
         if (Customer::customerExists($userEmail)) {
             //customer is registered and not logged in
             $customer = new Customer();
             // print_r($customer);
             // print_r('<br/>');
             $customer = $customer->getByEmail($userEmail);
             // print_r('<br/>will get customer here by email: '.$userEmail);
             // print_r($customer);
             // print_r('<br/>');
             //check if she is connected
             if (!$customer->fbid || $customer->fbid == '') {
                 $this->updateCustomerInfo($customer, $userInfo, $fb_user, false);
                 //print_r($customer);
                 $customer->update();
             }
             $this->loginCustomer($customer);
         } else {
             //new customer. create and add this customer and log her in
             $customer = new Customer();
             $this->updateCustomerInfo($customer, $userInfo, $fb_user, true);
             if (!$customer->add()) {
                 $this->errors[] = Tools::displayError('An error occurred while logging you in.');
             } else {
                 //award registration points
                 VBRewards::addRegistrationPoints($customer->id);
                 Tools::addCoupons($customer->id);
                 $cookie->new_reg = 1;
                 $cookie->write();
                 $this->loginCustomer($customer);
                 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) $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');
                 }
             }
         }
     } else {
         $redirectURL = _PS_BASE_URL_ . __PS_BASE_URI__;
         if (Tools::getValue('back')) {
             $redirectURL = $redirectURL . Tools::getValue('back');
         }
         $loginUrl = $this->facebook->getLoginUrl(array('scope' => 'email,user_location,user_birthday', 'redirect_uri' => $redirectURL));
         $smarty->assign('fblogin_url', $loginUrl);
         // echo "<script>alert('in')</script>";
     }
     if (Tools::getValue('fblogin') == 1) {
         // echo "<script>alert('in 1')</script>";
         Tools::redirect('index.php');
     }
 }
Exemple #12
0
        $ppec->displayPayPalAPIError($ppec->l('Error during the preparation of the Express Checkout payment'), $ppec->logs);
    }
} elseif (!empty($ppec->token) && $ppec->token == $token && ($ppec->payer_id = $payer_id)) {
    /* Get payment infos from paypal */
    $ppec->getExpressCheckout();
    if ($ppec->hasSucceedRequest() && !empty($ppec->token)) {
        $address = $customer = null;
        $email = $ppec->result['EMAIL'];
        /* Create Customer if not exist with address etc */
        if ($ppec->context->cookie->logged) {
            $id_customer = Paypal::getPayPalCustomerIdByEmail($email);
            if (!$id_customer) {
                PayPal::addPayPalCustomer($ppec->context->customer->id, $email);
            }
            $customer = $ppec->context->customer;
        } elseif ($id_customer = Customer::customerExists($email, true)) {
            $customer = new Customer($id_customer);
        } else {
            $customer = setCustomerInformation($ppec, $email);
            $customer->add();
            PayPal::addPayPalCustomer($customer->id, $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');
        }
        $addresses = $customer->getAddresses($ppec->context->language->id);
        foreach ($addresses as $address) {
            if ($address['alias'] == 'Paypal_Address') {
    public function viewcustomer()
    {
        global $currentIndex, $cookie, $link;
        $irow = 0;
        $configurations = Configuration::getMultiple(array('PS_LANG_DEFAULT', 'PS_CURRENCY_DEFAULT'));
        $defaultLanguage = (int) $configurations['PS_LANG_DEFAULT'];
        $defaultCurrency = (int) $configurations['PS_CURRENCY_DEFAULT'];
        if (!($customer = $this->loadObject())) {
            return;
        }
        $customerStats = $customer->getStats();
        $addresses = $customer->getAddresses($defaultLanguage);
        $products = $customer->getBoughtProducts();
        $discounts = Discount::getCustomerDiscounts($defaultLanguage, (int) $customer->id, false, false);
        $orders = Order::getCustomerOrders((int) $customer->id, true);
        $carts = Cart::getCustomerCarts((int) $customer->id);
        $groups = $customer->getGroups();
        $messages = CustomerThread::getCustomerMessages((int) $customer->id);
        $referrers = Referrer::getReferrers((int) $customer->id);
        if ($totalCustomer = Db::getInstance()->getValue('SELECT SUM(total_paid_real) FROM ' . _DB_PREFIX_ . 'orders WHERE id_customer = ' . $customer->id . ' AND valid = 1')) {
            Db::getInstance()->getValue('SELECT SQL_CALC_FOUND_ROWS COUNT(*) FROM ' . _DB_PREFIX_ . 'orders WHERE valid = 1 GROUP BY id_customer HAVING SUM(total_paid_real) > ' . $totalCustomer);
            $countBetterCustomers = (int) Db::getInstance()->getValue('SELECT FOUND_ROWS()') + 1;
        } else {
            $countBetterCustomers = '-';
        }
        echo '
		<fieldset style="width:400px;float: left"><div style="float: right"><a href="' . $currentIndex . '&addcustomer&id_customer=' . $customer->id . '&token=' . $this->token . '"><img src="../img/admin/edit.gif" /></a></div>
			<span style="font-weight: bold; font-size: 14px;">' . $customer->firstname . ' ' . $customer->lastname . '</span>
			<img src="../img/admin/' . ($customer->id_gender == 2 ? 'female' : ($customer->id_gender == 1 ? 'male' : 'unknown')) . '.gif" style="margin-bottom: 5px" /><br />
			<a href="mailto:' . $customer->email . '" style="text-decoration: underline; color: blue">' . $customer->email . '</a><br /><br />
			' . $this->l('ID:') . ' ' . sprintf('%06d', $customer->id) . '<br />
			' . $this->l('Registration date:') . ' ' . Tools::displayDate($customer->date_add, (int) $cookie->id_lang, true) . '<br />
			' . $this->l('Last visit:') . ' ' . ($customerStats['last_visit'] ? Tools::displayDate($customerStats['last_visit'], (int) $cookie->id_lang, true) : $this->l('never')) . '<br />
			' . ($countBetterCustomers != '-' ? $this->l('Rank: #') . ' ' . (int) $countBetterCustomers . '<br />' : '') . '
		</fieldset>
		<fieldset style="width:300px;float:left;margin-left:50px">
			<div style="float: right">
				<a href="' . $currentIndex . '&addcustomer&id_customer=' . $customer->id . '&token=' . $this->token . '"><img src="../img/admin/edit.gif" /></a>
			</div>
			' . $this->l('Newsletter:') . ' ' . ($customer->newsletter ? '<img src="../img/admin/enabled.gif" />' : '<img src="../img/admin/disabled.gif" />') . '<br />
			' . $this->l('Opt-in:') . ' ' . ($customer->optin ? '<img src="../img/admin/enabled.gif" />' : '<img src="../img/admin/disabled.gif" />') . '<br />
			' . $this->l('Age:') . ' ' . $customerStats['age'] . ' ' . (!empty($customer->birthday['age']) ? '(' . Tools::displayDate($customer->birthday, (int) $cookie->id_lang) . ')' : $this->l('unknown')) . '<br /><br />
			' . $this->l('Last update:') . ' ' . Tools::displayDate($customer->date_upd, (int) $cookie->id_lang, true) . '<br />
			' . $this->l('Status:') . ' ' . ($customer->active ? '<img src="../img/admin/enabled.gif" />' : '<img src="../img/admin/disabled.gif" />');
        if ($customer->isGuest()) {
            echo '
			<div>
			' . $this->l('This customer is registered as') . ' <b>' . $this->l('guest') . '</b>';
            if (!Customer::customerExists($customer->email)) {
                echo '
					<form method="POST" action="index.php?tab=AdminCustomers&id_customer=' . (int) $customer->id . '&token=' . Tools::getAdminTokenLite('AdminCustomers') . '">
						<input type="hidden" name="id_lang" value="' . (int) (sizeof($orders) ? $orders[0]['id_lang'] : Configuration::get('PS_LANG_DEFAULT')) . '" />
						<p class="center"><input class="button" type="submit" name="submitGuestToCustomer" value="' . $this->l('Transform to customer') . '" /></p>
						' . $this->l('This feature generates a random password and sends an e-mail to the customer') . '</form>';
            } else {
                echo '</div><div><b style="color:red;">' . $this->l('A registered customer account exists with the same email address') . '</b>';
            }
            echo '
			</div>
			';
        }
        echo '
		</fieldset>
		<div class="clear">&nbsp;</div>';
        echo '<fieldset style="height:190px"><legend><img src="../img/admin/cms.gif" /> ' . $this->l('Add a private note') . '</legend>
			<p>' . $this->l('This note will be displayed to all the employees but not to the customer.') . '</p>
			<form action="ajax.php" method="post" onsubmit="saveCustomerNote();return false;" id="customer_note">
				<textarea name="note" id="noteContent" style="width:600px;height:100px" onkeydown="$(\'#submitCustomerNote\').removeAttr(\'disabled\');">' . Tools::htmlentitiesUTF8($customer->note) . '</textarea><br />
				<input type="submit" id="submitCustomerNote" class="button" value="' . $this->l('   Save   ') . '" style="float:left;margin-top:5px" disabled="disabled" />
				<span id="note_feedback" style="float:left;margin:10px 0 0 10px"></span>
			</form>
		</fieldset>
		<div class="clear">&nbsp;</div>
		<script type="text/javascript">
			function saveCustomerNote()
			{
				$("#note_feedback").html("<img src=\\"../img/loader.gif\\" />").show();
				var noteContent = $("#noteContent").val();
				$.post("ajax.php", {submitCustomerNote:1,id_customer:' . (int) $customer->id . ',note:noteContent}, function (r) {
					$("#note_feedback").html("").hide();
					if (r == "ok")
					{
						$("#note_feedback").html("<b style=\\"color:green\\">' . addslashes($this->l('Your note has been saved')) . '</b>").fadeIn(400);
						$("#submitCustomerNote").attr("disabled", "disabled");
					}
					else if (r == "error:validation")
						$("#note_feedback").html("<b style=\\"color:red\\">' . addslashes($this->l('Error: your note is not valid')) . '</b>").fadeIn(400);
					else if (r == "error:update")
						$("#note_feedback").html("<b style=\\"color:red\\">' . addslashes($this->l('Error: cannot save your note')) . '</b>").fadeIn(400);
					$("#note_feedback").fadeOut(3000);
				});
			}
		</script>';
        echo '<h2>' . $this->l('Messages') . ' (' . sizeof($messages) . ')</h2>';
        if (sizeof($messages)) {
            echo '
			<table cellspacing="0" cellpadding="0" class="table">
				<tr>
					<th class="center">' . $this->l('Status') . '</th>
					<th class="center">' . $this->l('Message') . '</th>
					<th class="center">' . $this->l('Sent on') . '</th>
				</tr>';
            foreach ($messages as $message) {
                echo '<tr>
					<td>' . $message['status'] . '</td>
					<td><a href="index.php?tab=AdminCustomerThreads&id_customer_thread=' . (int) $message['id_customer_thread'] . '&viewcustomer_thread&token=' . Tools::getAdminTokenLite('AdminCustomerThreads') . '">' . substr(strip_tags(html_entity_decode($message['message'], ENT_NOQUOTES, 'UTF-8')), 0, 75) . '...</a></td>
					<td>' . Tools::displayDate($message['date_add'], (int) $cookie->id_lang, true) . '</td>
				</tr>';
            }
            echo '</table>
			<div class="clear">&nbsp;</div>';
        } else {
            echo $customer->firstname . ' ' . $customer->lastname . ' ' . $this->l('has never contacted you.');
        }
        // display hook specified to this page : AdminCustomers
        if (($hook = Module::hookExec('adminCustomers', array('id_customer' => $customer->id))) !== false) {
            echo '<div>' . $hook . '</div>';
        }
        echo '<div class="clear">&nbsp;</div>';
        echo '<h2>' . $this->l('Groups') . ' (' . sizeof($groups) . ')</h2>';
        if ($groups and sizeof($groups)) {
            echo '
			<table cellspacing="0" cellpadding="0" class="table">
				<tr>
					<th class="center">' . $this->l('ID') . '</th>
					<th class="center">' . $this->l('Name') . '</th>
					<th class="center">' . $this->l('Actions') . '</th>
				</tr>';
            $tokenGroups = Tools::getAdminToken('AdminGroups' . (int) Tab::getIdFromClassName('AdminGroups') . (int) $cookie->id_employee);
            foreach ($groups as $group) {
                $objGroup = new Group($group);
                echo '
				<tr ' . ($irow++ % 2 ? 'class="alt_row"' : '') . ' style="cursor: pointer" onclick="document.location = \'?tab=AdminGroups&id_group=' . $objGroup->id . '&viewgroup&token=' . $tokenGroups . '\'">
					<td class="center">' . $objGroup->id . '</td>
					<td>' . $objGroup->name[$defaultLanguage] . '</td>
					<td align="center"><a href="?tab=AdminGroups&id_group=' . $objGroup->id . '&viewgroup&token=' . $tokenGroups . '"><img src="../img/admin/details.gif" /></a></td>
				</tr>';
            }
            echo '
			</table>';
        }
        echo '<div class="clear">&nbsp;</div>';
        echo '<h2>' . $this->l('Orders') . ' (' . sizeof($orders) . ')</h2>';
        if ($orders and sizeof($orders)) {
            $totalOK = 0;
            $ordersOK = array();
            $ordersKO = array();
            $tokenOrders = Tools::getAdminToken('AdminOrders' . (int) Tab::getIdFromClassName('AdminOrders') . (int) $cookie->id_employee);
            foreach ($orders as $order) {
                if ($order['valid']) {
                    $ordersOK[] = $order;
                    $totalOK += $order['total_paid_real'];
                } else {
                    $ordersKO[] = $order;
                }
            }
            $orderHead = '
			<table cellspacing="0" cellpadding="0" class="table float">
				<tr>
					<th class="center">' . $this->l('ID') . '</th>
					<th class="center">' . $this->l('Date') . '</th>
					<th class="center">' . $this->l('Products') . '</th>
					<th class="center">' . $this->l('Total paid') . '</th>
					<th class="center">' . $this->l('Payment') . '</th>
					<th class="center">' . $this->l('State') . '</th>
					<th class="center">' . $this->l('Actions') . '</th>
				</tr>';
            $orderFoot = '</table>';
            if ($countOK = sizeof($ordersOK)) {
                echo '<div style="float:left;margin-right:20px"><h3 style="color:green;font-weight:700">' . $this->l('Valid orders:') . ' ' . $countOK . ' ' . $this->l('for') . ' ' . Tools::displayPrice($totalOK, new Currency($defaultCurrency)) . '</h3>' . $orderHead;
                foreach ($ordersOK as $order) {
                    echo '<tr ' . ($irow++ % 2 ? 'class="alt_row"' : '') . ' style="cursor: pointer" onclick="document.location = \'?tab=AdminOrders&id_order=' . $order['id_order'] . '&vieworder&token=' . $tokenOrders . '\'">
						<td class="center">' . $order['id_order'] . '</td>
							<td>' . Tools::displayDate($order['date_add'], (int) $cookie->id_lang) . '</td>
							<td align="right">' . $order['nb_products'] . '</td>
							<td align="right">' . Tools::displayPrice($order['total_paid_real'], new Currency((int) $order['id_currency'])) . '</td>
							<td>' . $order['payment'] . '</td>
							<td>' . $order['order_state'] . '</td>
							<td align="center"><a href="?tab=AdminOrders&id_order=' . $order['id_order'] . '&vieworder&token=' . $tokenOrders . '"><img src="../img/admin/details.gif" /></a></td>
						</tr>';
                }
                echo $orderFoot . '</div>';
            }
            if ($countKO = sizeof($ordersKO)) {
                echo '<div style="float:left;margin-right:20px"><h3 style="color:red;font-weight:700">' . $this->l('Invalid orders:') . ' ' . $countKO . '</h3>' . $orderHead;
                foreach ($ordersKO as $order) {
                    echo '
						<tr ' . ($irow++ % 2 ? 'class="alt_row"' : '') . ' style="cursor: pointer" onclick="document.location = \'?tab=AdminOrders&id_order=' . $order['id_order'] . '&vieworder&token=' . $tokenOrders . '\'">
							<td class="center">' . $order['id_order'] . '</td>
							<td>' . Tools::displayDate($order['date_add'], (int) $cookie->id_lang) . '</td>
							<td align="right">' . $order['nb_products'] . '</td>
							<td align="right">' . Tools::displayPrice($order['total_paid_real'], new Currency((int) $order['id_currency'])) . '</td>
							<td>' . $order['payment'] . '</td>
							<td>' . $order['order_state'] . '</td>
							<td align="center"><a href="?tab=AdminOrders&id_order=' . $order['id_order'] . '&vieworder&token=' . $tokenOrders . '"><img src="../img/admin/details.gif" /></a></td>
						</tr>';
                }
                echo $orderFoot . '</div><div class="clear">&nbsp;</div>';
            }
        } else {
            echo $customer->firstname . ' ' . $customer->lastname . ' ' . $this->l('has not placed any orders yet');
        }
        if ($products and sizeof($products)) {
            echo '<div class="clear">&nbsp;</div>
			<h2>' . $this->l('Products') . ' (' . sizeof($products) . ')</h2>
			<table cellspacing="0" cellpadding="0" class="table">
				<tr>
					<th class="center">' . $this->l('Date') . '</th>
					<th class="center">' . $this->l('Name') . '</th>
					<th class="center">' . $this->l('Quantity') . '</th>
					<th class="center">' . $this->l('Actions') . '</th>
				</tr>';
            $tokenOrders = Tools::getAdminToken('AdminOrders' . (int) Tab::getIdFromClassName('AdminOrders') . (int) $cookie->id_employee);
            foreach ($products as $product) {
                echo '
				<tr ' . ($irow++ % 2 ? 'class="alt_row"' : '') . ' style="cursor: pointer" onclick="document.location = \'?tab=AdminOrders&id_order=' . $product['id_order'] . '&vieworder&token=' . $tokenOrders . '\'">
					<td>' . Tools::displayDate($product['date_add'], (int) $cookie->id_lang, true) . '</td>
					<td>' . $product['product_name'] . '</td>
					<td align="right">' . $product['product_quantity'] . '</td>
					<td align="center"><a href="?tab=AdminOrders&id_order=' . $product['id_order'] . '&vieworder&token=' . $tokenOrders . '"><img src="../img/admin/details.gif" /></a></td>
				</tr>';
            }
            echo '
			</table>';
        }
        echo '<div class="clear">&nbsp;</div>
		<h2>' . $this->l('Addresses') . ' (' . sizeof($addresses) . ')</h2>';
        if (sizeof($addresses)) {
            echo '
			<table cellspacing="0" cellpadding="0" class="table">
				<tr>
					<th>' . $this->l('Company') . '</th>
					<th>' . $this->l('Name') . '</th>
					<th>' . $this->l('Address') . '</th>
					<th>' . $this->l('Country') . '</th>
					<th>' . $this->l('Phone number(s)') . '</th>
					<th>' . $this->l('Actions') . '</th>
				</tr>';
            $tokenAddresses = Tools::getAdminToken('AdminAddresses' . (int) Tab::getIdFromClassName('AdminAddresses') . (int) $cookie->id_employee);
            foreach ($addresses as $address) {
                echo '
				<tr ' . ($irow++ % 2 ? 'class="alt_row"' : '') . '>
					<td>' . ($address['company'] ? $address['company'] : '--') . '</td>
					<td>' . $address['firstname'] . ' ' . $address['lastname'] . '</td>
					<td>' . $address['address1'] . ($address['address2'] ? ' ' . $address['address2'] : '') . ' ' . $address['postcode'] . ' ' . $address['city'] . '</td>
					<td>' . $address['country'] . '</td>
					<td>' . ($address['phone'] ? $address['phone'] . ($address['phone_mobile'] ? '<br />' . $address['phone_mobile'] : '') : ($address['phone_mobile'] ? '<br />' . $address['phone_mobile'] : '--')) . '</td>
					<td align="center">
						<a href="?tab=AdminAddresses&id_address=' . $address['id_address'] . '&addaddress&token=' . $tokenAddresses . '"><img src="../img/admin/edit.gif" /></a>
						<a href="?tab=AdminAddresses&id_address=' . $address['id_address'] . '&deleteaddress&token=' . $tokenAddresses . '"><img src="../img/admin/delete.gif" /></a>
					</td>
				</tr>';
            }
            echo '
			</table>';
        } else {
            echo $customer->firstname . ' ' . $customer->lastname . ' ' . $this->l('has not registered any addresses yet') . '.';
        }
        echo '<div class="clear">&nbsp;</div>
		<h2>' . $this->l('Discounts') . ' (' . sizeof($discounts) . ')</h2>';
        if (sizeof($discounts)) {
            echo '
			<table cellspacing="0" cellpadding="0" class="table">
				<tr>
					<th>' . $this->l('ID') . '</th>
					<th>' . $this->l('Code') . '</th>
					<th>' . $this->l('Type') . '</th>
					<th>' . $this->l('Value') . '</th>
					<th>' . $this->l('Qty available') . '</th>
					<th>' . $this->l('Status') . '</th>
					<th>' . $this->l('Actions') . '</th>
				</tr>';
            $tokenDiscounts = Tools::getAdminToken('AdminDiscounts' . (int) Tab::getIdFromClassName('AdminDiscounts') . (int) $cookie->id_employee);
            foreach ($discounts as $discount) {
                echo '
				<tr ' . ($irow++ % 2 ? 'class="alt_row"' : '') . '>
					<td align="center">' . $discount['id_discount'] . '</td>
					<td>' . $discount['name'] . '</td>
					<td>' . $discount['type'] . '</td>
					<td align="right">' . $discount['value'] . '</td>
					<td align="center">' . $discount['quantity_for_user'] . '</td>
					<td align="center"><img src="../img/admin/' . ($discount['active'] ? 'enabled.gif' : 'disabled.gif') . '" alt="' . $this->l('Status') . '" title="' . $this->l('Status') . '" /></td>
					<td align="center">
						<a href="?tab=AdminDiscounts&id_discount=' . $discount['id_discount'] . '&adddiscount&token=' . $tokenDiscounts . '"><img src="../img/admin/edit.gif" /></a>
						<a href="?tab=AdminDiscounts&id_discount=' . $discount['id_discount'] . '&deletediscount&token=' . $tokenDiscounts . '"><img src="../img/admin/delete.gif" /></a>
					</td>
				</tr>';
            }
            echo '
			</table>';
        } else {
            echo $customer->firstname . ' ' . $customer->lastname . ' ' . $this->l('has no discount vouchers') . '.';
        }
        echo '<div class="clear">&nbsp;</div>';
        echo '<div style="float:left">
		<h2>' . $this->l('Carts') . ' (' . sizeof($carts) . ')</h2>';
        if ($carts and sizeof($carts)) {
            echo '
			<table cellspacing="0" cellpadding="0" class="table">
				<tr>
					<th class="center">' . $this->l('ID') . '</th>
					<th class="center">' . $this->l('Date') . '</th>
					<th class="center">' . $this->l('Total') . '</th>
					<th class="center">' . $this->l('Carrier') . '</th>
					<th class="center">' . $this->l('Actions') . '</th>
				</tr>';
            $tokenCarts = Tools::getAdminToken('AdminCarts' . (int) Tab::getIdFromClassName('AdminCarts') . (int) $cookie->id_employee);
            foreach ($carts as $cart) {
                $cartI = new Cart((int) $cart['id_cart']);
                $summary = $cartI->getSummaryDetails();
                $currency = new Currency((int) $cart['id_currency']);
                $carrier = new Carrier((int) $cart['id_carrier']);
                echo '
				<tr ' . ($irow++ % 2 ? 'class="alt_row"' : '') . ' style="cursor: pointer" onclick="document.location = \'?tab=AdminCarts&id_cart=' . $cart['id_cart'] . '&viewcart&token=' . $tokenCarts . '\'">
					<td class="center">' . sprintf('%06d', $cart['id_cart']) . '</td>
					<td>' . Tools::displayDate($cart['date_add'], (int) $cookie->id_lang, true) . '</td>
					<td align="right">' . Tools::displayPrice($summary['total_price'], $currency) . '</td>
					<td>' . $carrier->name . '</td>
					<td align="center"><a href="index.php?tab=AdminCarts&id_cart=' . $cart['id_cart'] . '&viewcart&token=' . $tokenCarts . '"><img src="../img/admin/details.gif" /></a></td>
				</tr>';
            }
            echo '
			</table>';
        } else {
            echo $this->l('No cart available') . '.';
        }
        echo '</div>';
        $interested = Db::getInstance()->ExecuteS('SELECT DISTINCT id_product FROM ' . _DB_PREFIX_ . 'cart_product cp INNER JOIN ' . _DB_PREFIX_ . 'cart c on c.id_cart = cp.id_cart WHERE c.id_customer = ' . (int) $customer->id . ' AND cp.id_product NOT IN (
		SELECT product_id FROM ' . _DB_PREFIX_ . 'orders o inner join ' . _DB_PREFIX_ . 'order_detail od ON o.id_order = od.id_order WHERE o.valid = 1 AND o.id_customer = ' . (int) $customer->id . ')');
        if (count($interested)) {
            echo '<div style="float:left;margin-left:20px">
			<h2>' . $this->l('Products') . ' (' . count($interested) . ')</h2>
			<table cellspacing="0" cellpadding="0" class="table">';
            foreach ($interested as $p) {
                $product = new Product((int) $p['id_product'], false, $cookie->id_lang);
                echo '
				<tr ' . ($irow++ % 2 ? 'class="alt_row"' : '') . ' style="cursor: pointer" onclick="document.location = \'' . $link->getProductLink((int) $product->id, $product->link_rewrite, Category::getLinkRewrite($product->id_category_default, (int) $cookie->id_lang)) . '\'">
					<td>' . (int) $product->id . '</td>
					<td>' . Tools::htmlentitiesUTF8($product->name) . '</td>
					<td align="center"><a href="' . $link->getProductLink((int) $product->id, $product->link_rewrite, Category::getLinkRewrite($product->id_category_default, (int) $cookie->id_lang)) . '"><img src="../img/admin/details.gif" /></a></td>
				</tr>';
            }
            echo '</table></div>';
        }
        echo '<div class="clear">&nbsp;</div>';
        /* Last connections */
        $connections = $customer->getLastConnections();
        if (sizeof($connections)) {
            echo '<h2>' . $this->l('Last connections') . '</h2>
			<table cellspacing="0" cellpadding="0" class="table">
				<tr>
					<th style="width: 200px">' . $this->l('Date') . '</th>
					<th style="width: 100px">' . $this->l('Pages viewed') . '</th>
					<th style="width: 100px">' . $this->l('Total time') . '</th>
					<th style="width: 100px">' . $this->l('Origin') . '</th>
					<th style="width: 100px">' . $this->l('IP Address') . '</th>
				</tr>';
            foreach ($connections as $connection) {
                echo '<tr>
						<td>' . Tools::displayDate($connection['date_add'], (int) $cookie->id_lang, true) . '</td>
						<td>' . (int) $connection['pages'] . '</td>
						<td>' . $connection['time'] . '</td>
						<td>' . ($connection['http_referer'] ? preg_replace('/^www./', '', parse_url($connection['http_referer'], PHP_URL_HOST)) : $this->l('Direct link')) . '</td>
						<td>' . $connection['ipaddress'] . '</td>
					</tr>';
            }
            echo '</table><div class="clear">&nbsp;</div>';
        }
        if (sizeof($referrers)) {
            echo '<h2>' . $this->l('Referrers') . '</h2>
			<table cellspacing="0" cellpadding="0" class="table">
				<tr>
					<th style="width: 200px">' . $this->l('Date') . '</th>
					<th style="width: 200px">' . $this->l('Name') . '</th>
				</tr>';
            foreach ($referrers as $referrer) {
                echo '<tr>
						<td>' . Tools::displayDate($referrer['date_add'], (int) $cookie->id_lang, true) . '</td>
						<td>' . $referrer['name'] . '</td>
					</tr>';
            }
            echo '</table><div class="clear">&nbsp;</div>';
        }
        echo '<a href="' . $currentIndex . '&token=' . $this->token . '"><img src="../img/admin/arrow2.gif" /> ' . $this->l('Back to customer list') . '</a><br />';
    }
 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']);
 }
Exemple #15
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);
                }
            }
        }
    }
}
 /**
  * Transform a guest account into a registered customer account
  */
 public function processGuestToCustomer()
 {
     $customer = new Customer((int) Tools::getValue('id_customer'));
     if (!Validate::isLoadedObject($customer)) {
         $this->errors[] = Tools::displayError('This customer does not exist.');
     }
     if (Customer::customerExists($customer->email)) {
         $this->errors[] = Tools::displayError('This customer already exists as a non-guest.');
     } elseif ($customer->transformToCustomer(Tools::getValue('id_lang', $this->context->language->id))) {
         Tools::redirectAdmin(self::$currentIndex . '&' . $this->identifier . '=' . $customer->id . '&conf=3&token=' . $this->token);
     } else {
         $this->errors[] = Tools::displayError('An error occurred while updating customer information.');
     }
 }
 /**
  * Initialize order opc controller
  * @see FrontController::init()
  */
 public function init()
 {
     parent::init();
     $this->sendNP();
     if ($this->nbProducts) {
         $this->context->smarty->assign('virtual_cart', $this->context->cart->isVirtualCart());
     }
     $this->context->smarty->assign('is_multi_address_delivery', $this->context->cart->isMultiAddressDelivery() || (int) Tools::getValue('multi-shipping') == 1);
     $this->context->smarty->assign('open_multishipping_fancybox', (int) Tools::getValue('multi-shipping') == 1);
     if ($this->context->cart->nbProducts()) {
         if (Tools::isSubmit('ajax')) {
             if (Tools::isSubmit('method')) {
                 switch (Tools::getValue('method')) {
                     case 'updateMessage':
                         if (Tools::isSubmit('message')) {
                             $txt_message = urldecode(Tools::getValue('message'));
                             $this->_updateMessage($txt_message);
                             if (count($this->errors)) {
                                 $this->ajaxDie('{"hasError" : true, "errors" : ["' . implode('\',\'', $this->errors) . '"]}');
                             }
                             $this->ajaxDie(true);
                         }
                         break;
                     case 'updateCarrierAndGetPayments':
                         if ((Tools::isSubmit('delivery_option') || Tools::isSubmit('id_carrier')) && Tools::isSubmit('recyclable') && Tools::isSubmit('gift') && Tools::isSubmit('gift_message') && Tools::isSubmit('department')) {
                             $this->_assignWrappingAndTOS();
                             if ($this->_processCarrier()) {
                                 $carriers = $this->context->cart->simulateCarriersOutput();
                                 $return = array_merge(array('HOOK_TOP_PAYMENT' => Hook::exec('displayPaymentTop'), 'HOOK_PAYMENT' => $this->_getPaymentMethods(), 'carrier_data' => $this->_getCarrierList(), 'HOOK_BEFORECARRIER' => Hook::exec('displayBeforeCarrier', array('carriers' => $carriers))), $this->getFormatedSummaryDetail());
                                 Cart::addExtraCarriers($return);
                                 $this->ajaxDie(Tools::jsonEncode($return));
                             } else {
                                 $this->errors[] = Tools::displayError('An error occurred while updating the cart.');
                             }
                             if (count($this->errors)) {
                                 $this->ajaxDie('{"hasError" : true, "errors" : ["' . implode('\',\'', $this->errors) . '"]}');
                             }
                             exit;
                         }
                         break;
                     case 'updateTOSStatusAndGetPayments':
                         if (Tools::isSubmit('checked')) {
                             $this->context->cookie->checkedTOS = (int) Tools::getValue('checked');
                             $this->ajaxDie(Tools::jsonEncode(array('HOOK_TOP_PAYMENT' => Hook::exec('displayPaymentTop'), 'HOOK_PAYMENT' => $this->_getPaymentMethods())));
                         }
                         break;
                     case 'getCarrierList':
                         $this->ajaxDie(Tools::jsonEncode($this->_getCarrierList()));
                         break;
                     case 'editCustomer':
                         if (!$this->isLogged || !$this->context->customer->is_guest) {
                             exit;
                         }
                         if (Validate::isEmail($email = Tools::getValue('email')) && !empty($email)) {
                             if (Customer::customerExists($email)) {
                                 $this->errors[] = Tools::displayError('An account using this email address has already been registered.', false);
                             }
                         }
                         if (Tools::getValue('years')) {
                             $this->context->customer->birthday = (int) Tools::getValue('years') . '-' . (int) Tools::getValue('months') . '-' . (int) Tools::getValue('days');
                         }
                         $_POST['lastname'] = $_POST['customer_lastname'];
                         $_POST['firstname'] = $_POST['customer_firstname'];
                         $this->errors = array_merge($this->errors, $this->context->customer->validateController());
                         $this->context->customer->newsletter = (int) Tools::isSubmit('newsletter');
                         $this->context->customer->optin = (int) Tools::isSubmit('optin');
                         $this->context->customer->is_guest = Tools::isSubmit('is_new_customer') ? !Tools::getValue('is_new_customer', 1) : 0;
                         $return = array('hasError' => !empty($this->errors), 'errors' => $this->errors, 'id_customer' => (int) $this->context->customer->id, 'token' => Tools::getToken(false));
                         if (!count($this->errors)) {
                             $return['isSaved'] = (bool) $this->context->customer->update();
                         } else {
                             $return['isSaved'] = false;
                         }
                         $this->ajaxDie(Tools::jsonEncode($return));
                         break;
                     case 'getAddressBlockAndCarriersAndPayments':
                         if ($this->context->customer->isLogged() || $this->context->customer->isGuest()) {
                             // check if customer have addresses
                             if (!Customer::getAddressesTotalById($this->context->customer->id)) {
                                 $this->ajaxDie(Tools::jsonEncode(array('no_address' => 1)));
                             }
                             if (file_exists(_PS_MODULE_DIR_ . 'blockuserinfo/blockuserinfo.php')) {
                                 include_once _PS_MODULE_DIR_ . 'blockuserinfo/blockuserinfo.php';
                                 $block_user_info = new BlockUserInfo();
                             }
                             $this->context->smarty->assign('isVirtualCart', $this->context->cart->isVirtualCart());
                             $this->_processAddressFormat();
                             $this->_assignAddress();
                             if (!($formated_address_fields_values_list = $this->context->smarty->getTemplateVars('formatedAddressFieldsValuesList'))) {
                                 $formated_address_fields_values_list = array();
                             }
                             // Wrapping fees
                             $wrapping_fees = $this->context->cart->getGiftWrappingPrice(false);
                             $wrapping_fees_tax_inc = $this->context->cart->getGiftWrappingPrice();
                             $is_adv_api = Tools::getValue('isAdvApi');
                             if ($is_adv_api) {
                                 $tpl = 'order-address-advanced.tpl';
                                 $this->context->smarty->assign(array('products' => $this->context->cart->getProducts()));
                             } else {
                                 $tpl = 'order-address.tpl';
                             }
                             $return = array_merge(array('order_opc_adress' => $this->context->smarty->fetch(_PS_THEME_DIR_ . $tpl), 'block_user_info' => isset($block_user_info) ? $block_user_info->hookDisplayTop(array()) : '', 'formatedAddressFieldsValuesList' => $formated_address_fields_values_list, 'carrier_data' => $is_adv_api ? '' : $this->_getCarrierList(), 'HOOK_TOP_PAYMENT' => $is_adv_api ? '' : Hook::exec('displayPaymentTop'), 'HOOK_PAYMENT' => $is_adv_api ? '' : $this->_getPaymentMethods(), 'no_address' => 0, 'gift_price' => Tools::displayPrice(Tools::convertPrice(Product::getTaxCalculationMethod() == 1 ? $wrapping_fees : $wrapping_fees_tax_inc, new Currency((int) $this->context->cookie->id_currency)))), $this->getFormatedSummaryDetail());
                             $this->ajaxDie(Tools::jsonEncode($return));
                         }
                         die(Tools::displayError());
                         break;
                     case 'makeFreeOrder':
                         /* Bypass payment step if total is 0 */
                         if (($id_order = $this->_checkFreeOrder()) && $id_order) {
                             $order = new Order((int) $id_order);
                             $email = $this->context->customer->email;
                             if ($this->context->customer->is_guest) {
                                 $this->context->customer->logout();
                             }
                             // If guest we clear the cookie for security reason
                             $this->ajaxDie('freeorder:' . $order->reference . ':' . $email);
                         }
                         exit;
                         break;
                     case 'updateAddressesSelected':
                         if ($this->context->customer->isLogged(true)) {
                             $address_delivery = new Address((int) Tools::getValue('id_address_delivery'));
                             $this->context->smarty->assign('isVirtualCart', $this->context->cart->isVirtualCart());
                             $address_invoice = (int) Tools::getValue('id_address_delivery') == (int) Tools::getValue('id_address_invoice') ? $address_delivery : new Address((int) Tools::getValue('id_address_invoice'));
                             if ($address_delivery->id_customer != $this->context->customer->id || $address_invoice->id_customer != $this->context->customer->id) {
                                 $this->errors[] = Tools::displayError('This address is not yours.');
                             } elseif (!Address::isCountryActiveById((int) Tools::getValue('id_address_delivery'))) {
                                 $this->errors[] = Tools::displayError('This address is not in a valid area.');
                             } elseif (!Validate::isLoadedObject($address_delivery) || !Validate::isLoadedObject($address_invoice) || $address_invoice->deleted || $address_delivery->deleted) {
                                 $this->errors[] = Tools::displayError('This address is invalid.');
                             } else {
                                 $this->context->cart->id_address_delivery = (int) Tools::getValue('id_address_delivery');
                                 $this->context->cart->id_address_invoice = Tools::isSubmit('same') ? $this->context->cart->id_address_delivery : (int) Tools::getValue('id_address_invoice');
                                 if (!$this->context->cart->update()) {
                                     $this->errors[] = Tools::displayError('An error occurred while updating your cart.');
                                 }
                                 $infos = Address::getCountryAndState((int) $this->context->cart->id_address_delivery);
                                 if (isset($infos['id_country']) && $infos['id_country']) {
                                     $country = new Country((int) $infos['id_country']);
                                     $this->context->country = $country;
                                 }
                                 // Address has changed, so we check if the cart rules still apply
                                 $cart_rules = $this->context->cart->getCartRules();
                                 CartRule::autoRemoveFromCart($this->context);
                                 CartRule::autoAddToCart($this->context);
                                 if ((int) Tools::getValue('allow_refresh')) {
                                     // If the cart rules has changed, we need to refresh the whole cart
                                     $cart_rules2 = $this->context->cart->getCartRules();
                                     if (count($cart_rules2) != count($cart_rules)) {
                                         $this->ajax_refresh = true;
                                     } else {
                                         $rule_list = array();
                                         foreach ($cart_rules2 as $rule) {
                                             $rule_list[] = $rule['id_cart_rule'];
                                         }
                                         foreach ($cart_rules as $rule) {
                                             if (!in_array($rule['id_cart_rule'], $rule_list)) {
                                                 $this->ajax_refresh = true;
                                                 break;
                                             }
                                         }
                                     }
                                 }
                                 if (!$this->context->cart->isMultiAddressDelivery()) {
                                     $this->context->cart->setNoMultishipping();
                                 }
                                 // As the cart is no multishipping, set each delivery address lines with the main delivery address
                                 if (!count($this->errors)) {
                                     $result = $this->_getCarrierList();
                                     // Wrapping fees
                                     $wrapping_fees = $this->context->cart->getGiftWrappingPrice(false);
                                     $wrapping_fees_tax_inc = $this->context->cart->getGiftWrappingPrice();
                                     $result = array_merge($result, array('HOOK_TOP_PAYMENT' => Hook::exec('displayPaymentTop'), 'HOOK_PAYMENT' => $this->_getPaymentMethods(), 'gift_price' => Tools::displayPrice(Tools::convertPrice(Product::getTaxCalculationMethod() == 1 ? $wrapping_fees : $wrapping_fees_tax_inc, new Currency((int) $this->context->cookie->id_currency))), 'carrier_data' => $this->_getCarrierList(), 'refresh' => (bool) $this->ajax_refresh), $this->getFormatedSummaryDetail());
                                     $this->ajaxDie(Tools::jsonEncode($result));
                                 }
                             }
                             if (count($this->errors)) {
                                 $this->ajaxDie(Tools::jsonEncode(array('hasError' => true, 'errors' => $this->errors)));
                             }
                         }
                         die(Tools::displayError());
                         break;
                     case 'multishipping':
                         $this->_assignSummaryInformations();
                         $this->context->smarty->assign('product_list', $this->context->cart->getProducts());
                         if ($this->context->customer->id) {
                             $this->context->smarty->assign('address_list', $this->context->customer->getAddresses($this->context->language->id));
                         } else {
                             $this->context->smarty->assign('address_list', array());
                         }
                         $this->setTemplate(_PS_THEME_DIR_ . 'order-address-multishipping-products.tpl');
                         $this->display();
                         $this->ajaxDie();
                         break;
                     case 'cartReload':
                         $this->_assignSummaryInformations();
                         if ($this->context->customer->id) {
                             $this->context->smarty->assign('address_list', $this->context->customer->getAddresses($this->context->language->id));
                         } else {
                             $this->context->smarty->assign('address_list', array());
                         }
                         $this->context->smarty->assign('opc', true);
                         $this->setTemplate(_PS_THEME_DIR_ . 'shopping-cart.tpl');
                         $this->display();
                         $this->ajaxDie();
                         break;
                     case 'noMultiAddressDelivery':
                         $this->context->cart->setNoMultishipping();
                         $this->ajaxDie();
                         break;
                     default:
                         throw new PrestaShopException('Unknown method "' . Tools::getValue('method') . '"');
                 }
             } else {
                 throw new PrestaShopException('Method is not defined');
             }
         }
     } elseif (Tools::isSubmit('ajax')) {
         $this->errors[] = Tools::displayError('There is no product in your cart.');
         $this->ajaxDie('{"hasError" : true, "errors" : ["' . implode('\',\'', $this->errors) . '"]}');
     }
 }
Exemple #18
0
// Exit if already logged in.
if ($cookie->isLogged()) {
    exit('Already logged in.');
}
$customer_email = $email;
// email adress that will pass by the questionaire
$customer_fname = $firstname;
// first name from api
$customer_lname = $lastname;
// last name from api
$customer = new Customer();
$customer->email = $urlemail;
$customer->firstname = $customer_fname;
$customer->lastname = $customer_lname;
$customer->passwd = generatePassword();
$result = Customer::customerExists($customer_email);
if ($result > 0) {
    $cookieCustomer = new Customer();
    $cookieCustomer->getByEmail($customer->email);
    $cookie->id_customer = intval($cookieCustomer->id);
    $cookie->customer_lastname = $cookieCustomer->lastname;
    $cookie->customer_firstname = $cookieCustomer->firstname;
    $cookie->logged = 1;
    $cookie->passwd = $cookieCustomer->passwd;
    $cookie->email = $cookieCustomer->email;
    if (Configuration::get('PS_CART_FOLLOWING') and (empty($context->cookie->id_cart) or Cart::getNbProducts($context->cookie->id_cart) == 0)) {
        $context->cookie->id_cart = intval(Cart::lastNoneOrderedCart(intval($customer->id)));
    }
} else {
    try {
        $webService = new PrestaShopWebservice(PS_SHOP_PATH, PS_WS_AUTH_KEY, false);
 public function init()
 {
     if (!$this->isOpcModuleActive()) {
         return parent::init();
     }
     if (Tools::getIsset('id_carrier') && strpos(Tools::getValue('id_carrier'), ",") > 0) {
         $_POST['id_carrier'] = Cart::intifier(Tools::getValue('id_carrier'));
     }
     $this->opc_templates_path = _PS_MODULE_DIR_ . 'onepagecheckout/views/templates/front';
     $this->origInit();
     $this->_assignOpcSettings();
     if ($this->opc_config != null && $this->opc_config['goods_return_cms'] > 0) {
         $cms = new CMS((int) $this->opc_config['goods_return_cms'], (int) $this->context->language->id);
         $link_goods_return = $this->context->link->getCMSLink($cms, $cms->link_rewrite, true);
         if (!strpos($link_goods_return, '?')) {
             $link_goods_return .= '?content_only=1';
         } else {
             $link_goods_return .= '&content_only=1';
         }
         $this->context->smarty->assign("link_goods_return", $link_goods_return);
     }
     $this->_setInfoBlockContent();
     $this->_setExtraDivPaymentBlock();
     if ($this->nbProducts) {
         $this->context->smarty->assign('virtual_cart', false);
     }
     $this->context->smarty->assign('is_multi_address_delivery', $this->context->cart->isMultiAddressDelivery() || (int) Tools::getValue('multi-shipping') == 1);
     $this->context->smarty->assign('open_multishipping_fancybox', (int) Tools::getValue('multi-shipping') == 1);
     $this->context->smarty->assign('order_process_type', Configuration::get('PS_ORDER_PROCESS_TYPE'));
     $this->context->smarty->assign('one_phone_at_least', (int) Configuration::get('PS_ONE_PHONE_AT_LEAST'));
     $this->inv_first_on = isset($this->opc_config) && isset($this->opc_config["invoice_first"]) && $this->opc_config["invoice_first"] == "1";
     $this->default_ps_carriers = isset($this->opc_config) && isset($this->opc_config["default_ps_carriers"]) && $this->opc_config["default_ps_carriers"] == "1";
     if (version_compare(_PS_VERSION_, "1.5.2.0") <= 0) {
         $this->isLogged = (bool) ($this->context->customer->id && Customer::customerIdExistsStatic((int) $this->context->cookie->id_customer));
     }
     if ($this->context->cart->nbProducts()) {
         if (Tools::isSubmit('ajax')) {
             if (Tools::isSubmit('method')) {
                 switch (Tools::getValue('method')) {
                     case 'updateMessage':
                         if (Tools::isSubmit('message')) {
                             $txtMessage = urldecode(Tools::getValue('message'));
                             $this->_updateMessage($txtMessage);
                             if (count($this->errors)) {
                                 die('{"hasError" : true, "errors" : ["' . implode('\',\'', $this->errors) . '"]}');
                             }
                             die(true);
                         }
                         break;
                     case 'updateCarrierAndGetPayments':
                         if ((Tools::isSubmit('delivery_option') || Tools::isSubmit('id_carrier')) && Tools::isSubmit('recyclable') && Tools::isSubmit('gift') && Tools::isSubmit('gift_message')) {
                             $this->_assignWrappingAndTOS();
                             CartRule::autoRemoveFromCart($this->context);
                             CartRule::autoAddToCart($this->context);
                             if ($this->_processCarrier()) {
                                 $carriers = $this->context->cart->simulateCarriersOutput();
                                 $return = array_merge(array('HOOK_TOP_PAYMENT' => Hook::exec('displayPaymentTop'), 'HOOK_PAYMENT' => $this->_getPaymentMethods(), 'carrier_data' => $this->_getCarrierList(), 'HOOK_BEFORECARRIER' => Hook::exec('displayBeforeCarrier', array('carriers' => $carriers))), $this->getFormatedSummaryDetail());
                                 Cart::addExtraCarriers($return);
                                 die(Tools::jsonEncode($return));
                             } else {
                                 $this->errors[] = Tools::displayError('Error occurred while updating cart.');
                             }
                             if (count($this->errors)) {
                                 die('{"hasError" : true, "errors" : ["' . implode('\',\'', $this->errors) . '"]}');
                             }
                             exit;
                         }
                         break;
                     case 'updateTOSStatusAndGetPayments':
                         if (Tools::isSubmit('checked')) {
                             $this->context->cookie->checkedTOS = (int) Tools::getValue('checked');
                             die(Tools::jsonEncode(array()));
                         }
                         break;
                     case 'updatePaymentsOnly':
                         die(Tools::jsonEncode(array('HOOK_TOP_PAYMENT' => Hook::exec('displayPaymentTop'), 'HOOK_PAYMENT' => self::_getPaymentMethods())));
                         break;
                     case 'getCarrierList':
                         $this->context->smarty->assign('isVirtualCart', $this->context->cart->isVirtualCart());
                         $result = $this->_getCarrierList();
                         $result = array_merge($result, array('HOOK_TOP_PAYMENT' => Hook::exec('displayPaymentTop'), 'HOOK_PAYMENT' => $this->_getPaymentMethods()), $this->getFormatedSummaryDetail());
                         die(Tools::jsonEncode($result));
                         break;
                     case 'editCustomer':
                         if (!$this->isLogged) {
                             exit;
                         }
                         if (Tools::getValue('years')) {
                             $this->context->customer->birthday = (int) Tools::getValue('years') . '-' . (int) Tools::getValue('months') . '-' . (int) Tools::getValue('days');
                         }
                         if (trim(Tools::getValue('customer_lastname')) == "") {
                             $_POST['customer_lastname'] = $this->inv_first_on ? Tools::getValue('lastname_invoice') : Tools::getValue('lastname');
                         }
                         if (trim(Tools::getValue('customer_firstname')) == "") {
                             $_POST['customer_firstname'] = $this->inv_first_on ? Tools::getValue('firstname_invoice') : Tools::getValue('firstname');
                         }
                         $this->errors = $this->context->customer->validateController();
                         $this->context->customer->newsletter = (int) Tools::isSubmit('newsletter');
                         $this->context->customer->optin = (int) Tools::isSubmit('optin');
                         $return = array('hasError' => !empty($this->errors), 'errors' => $this->errors, 'id_customer' => (int) $this->context->customer->id, 'token' => Tools::getToken(false));
                         if (!count($this->errors)) {
                             $return['isSaved'] = (bool) $this->context->customer->update();
                         } else {
                             $return['isSaved'] = false;
                         }
                         die(Tools::jsonEncode($return));
                         break;
                     case 'getAddressBlockAndCarriersAndPayments':
                         if ($this->context->customer->isLogged()) {
                             if (!Customer::getAddressesTotalById($this->context->customer->id)) {
                                 die(Tools::jsonEncode(array('no_address' => 1)));
                             }
                             if (file_exists(_PS_MODULE_DIR_ . 'blockuserinfo/blockuserinfo.php')) {
                                 include_once _PS_MODULE_DIR_ . 'blockuserinfo/blockuserinfo.php';
                                 $blockUserInfo = new BlockUserInfo();
                             }
                             $this->context->smarty->assign('isVirtualCart', $this->context->cart->isVirtualCart());
                             $customer = $this->context->customer;
                             $customer_info = array("id" => $customer->id, "email" => $customer->email, "id_gender" => $customer->id_gender, "birthday" => $customer->birthday, "newsletter" => $customer->newsletter, "optin" => $customer->optin, "is_guest" => $customer->is_guest);
                             $this->_processAddressFormat();
                             $this->_assignAddress();
                             $address_delivery = $this->context->smarty->tpl_vars['delivery']->value;
                             $address_invoice = $this->context->smarty->tpl_vars['invoice']->value;
                             if (Configuration::get('VATNUMBER_MANAGEMENT') && file_exists(_PS_MODULE_DIR_ . '/vatnumber/vatnumber.php') && !class_exists("VatNumber", false)) {
                                 include_once _PS_MODULE_DIR_ . '/vatnumber/vatnumber.php';
                             }
                             if (isset($address_delivery) && Configuration::get('VATNUMBER_MANAGEMENT') and file_exists(dirname(__FILE__) . '/../../modules/vatnumber/vatnumber.php') && VatNumber::isApplicable($address_delivery->id_country) && Configuration::get('VATNUMBER_COUNTRY') != $address_delivery->id_country) {
                                 $allow_eu_vat_delivery = 1;
                             } else {
                                 $allow_eu_vat_delivery = 0;
                             }
                             if (isset($address_invoice) && Configuration::get('VATNUMBER_MANAGEMENT') and file_exists(dirname(__FILE__) . '/../../modules/vatnumber/vatnumber.php') && VatNumber::isApplicable($address_invoice->id_country) && Configuration::get('VATNUMBER_COUNTRY') != $address_invoice->id_country) {
                                 $allow_eu_vat_invoice = 1;
                             } else {
                                 $allow_eu_vat_invoice = 0;
                             }
                             $wrapping_fees_tax = new Tax((int) Configuration::get('PS_GIFT_WRAPPING_TAX'));
                             if (version_compare(_PS_VERSION_, "1.5.2.0") <= 0) {
                                 $wrapping_fees = (double) Configuration::get('PS_GIFT_WRAPPING_PRICE');
                                 $wrapping_fees_tax_inc = $wrapping_fees * (1 + (double) $wrapping_fees_tax->rate / 100);
                             } else {
                                 $wrapping_fees = $this->context->cart->getGiftWrappingPrice(false);
                                 $wrapping_fees_tax_inc = $wrapping_fees = $this->context->cart->getGiftWrappingPrice();
                             }
                             $return = array_merge(array('customer_info' => $customer_info, 'allow_eu_vat_delivery' => $allow_eu_vat_delivery, 'allow_eu_vat_invoice' => $allow_eu_vat_invoice, 'customer_addresses' => $this->context->smarty->tpl_vars['addresses']->value, 'block_user_info' => isset($blockUserInfo) ? method_exists($blockUserInfo, 'hookTop') ? $blockUserInfo->hookTop(array()) : $blockUserInfo->hookDisplayTop(array()) : '', 'carrier_data' => $this->_getCarrierList(), 'HOOK_TOP_PAYMENT' => Hook::exec('displayPaymentTop'), 'HOOK_PAYMENT' => $this->_getPaymentMethods(), 'no_address' => 0, 'gift_price' => Tools::displayPrice(Tools::convertPrice(Product::getTaxCalculationMethod() == 1 ? $wrapping_fees : $wrapping_fees_tax_inc, new Currency((int) $this->context->cookie->id_currency)))), $this->getFormatedSummaryDetail());
                             die(Tools::jsonEncode($return));
                         }
                         die(Tools::displayError("Customer is not logged in, while he should be. Check please AuthController and cookies."));
                         break;
                     case 'makeFreeOrder':
                         if (($id_order = $this->_checkFreeOrder()) && $id_order) {
                             $order = new Order((int) $id_order);
                             $email = $this->context->customer->email;
                             if ($this->context->customer->is_guest) {
                                 $this->context->customer->logout();
                             }
                             // If guest we clear the cookie for security reason
                             die('freeorder:' . $order->reference . ':' . $email);
                         }
                         exit;
                         break;
                     case 'updateAddressesSelected':
                         $id_address_delivery = (int) Tools::getValue('id_address_delivery');
                         $id_address_invoice = (int) Tools::getValue('id_address_invoice');
                         $address_delivery = new Address((int) Tools::getValue('id_address_delivery'));
                         $address_invoice = (int) Tools::getValue('id_address_delivery') == (int) Tools::getValue('id_address_invoice') ? $address_delivery : new Address((int) Tools::getValue('id_address_invoice'));
                         if (Configuration::get('VATNUMBER_MANAGEMENT') && file_exists(_PS_MODULE_DIR_ . '/vatnumber/vatnumber.php') && !class_exists("VatNumber", false)) {
                             include_once _PS_MODULE_DIR_ . '/vatnumber/vatnumber.php';
                         }
                         if (isset($address_delivery) && Configuration::get('VATNUMBER_MANAGEMENT') && file_exists(_PS_MODULE_DIR_ . '/vatnumber/vatnumber.php') && VatNumber::isApplicable($address_delivery->id_country) && Configuration::get('VATNUMBER_COUNTRY') != $address_delivery->id_country) {
                             $allow_eu_vat_delivery = 1;
                         } else {
                             $allow_eu_vat_delivery = 0;
                         }
                         if (isset($address_invoice) && Configuration::get('VATNUMBER_MANAGEMENT') and file_exists(_PS_MODULE_DIR_ . '/vatnumber/vatnumber.php') && VatNumber::isApplicable($address_invoice->id_country) && Configuration::get('VATNUMBER_COUNTRY') != $address_invoice->id_country) {
                             $allow_eu_vat_invoice = 1;
                         } else {
                             $allow_eu_vat_invoice = 0;
                         }
                         $address_delivery = new Address((int) Tools::getValue('id_address_delivery'));
                         $this->context->smarty->assign('isVirtualCart', $this->context->cart->isVirtualCart());
                         $address_invoice = (int) Tools::getValue('id_address_delivery') == (int) Tools::getValue('id_address_invoice') ? $address_delivery : new Address((int) Tools::getValue('id_address_invoice'));
                         if ($address_delivery->id_customer && $address_delivery->id_customer != $this->context->customer->id || $address_invoice->id_customer && $address_invoice->id_customer != $this->context->customer->id) {
                             $this->errors = "not_your_address";
                         }
                         if (!Address::isCountryActiveById((int) Tools::getValue('id_address_delivery'))) {
                             $this->errors[] = Tools::displayError('This address is not in a valid area.');
                         } elseif (!Validate::isLoadedObject($address_delivery) || !Validate::isLoadedObject($address_invoice) || $address_invoice->deleted || $address_delivery->deleted) {
                             $this->errors[] = Tools::displayError('This address is invalid.');
                         } else {
                             $this->context->cart->id_address_delivery = (int) Tools::getValue('id_address_delivery');
                             $this->context->cart->id_address_invoice = Tools::isSubmit('same') ? $this->context->cart->id_address_delivery : (int) Tools::getValue('id_address_invoice');
                             if (!$this->context->cart->update()) {
                                 $this->errors[] = Tools::displayError('An error occurred while updating your cart.');
                             }
                             CartRule::autoRemoveFromCart($this->context);
                             CartRule::autoAddToCart($this->context);
                             $this->context->cart->setNoMultishipping();
                             // As the cart is no multishipping, set each delivery address lines with the main delivery address
                             if (!count($this->errors)) {
                                 $result = $this->_getCarrierList();
                                 $wrapping_fees_tax = new Tax((int) Configuration::get('PS_GIFT_WRAPPING_TAX'));
                                 if (version_compare(_PS_VERSION_, "1.5.2.0") <= 0) {
                                     $wrapping_fees = (double) Configuration::get('PS_GIFT_WRAPPING_PRICE');
                                     $wrapping_fees_tax_inc = $wrapping_fees * (1 + (double) $wrapping_fees_tax->rate / 100);
                                 } else {
                                     $wrapping_fees = $this->context->cart->getGiftWrappingPrice(false);
                                     $wrapping_fees_tax_inc = $wrapping_fees = $this->context->cart->getGiftWrappingPrice();
                                 }
                                 $result = array_merge($result, array('allow_eu_vat_delivery' => $allow_eu_vat_delivery, 'allow_eu_vat_invoice' => $allow_eu_vat_invoice, 'HOOK_TOP_PAYMENT' => Hook::exec('displayPaymentTop'), 'HOOK_PAYMENT' => $this->_getPaymentMethods(), 'gift_price' => Tools::displayPrice(Tools::convertPrice(Product::getTaxCalculationMethod() == 1 ? $wrapping_fees : $wrapping_fees_tax_inc, new Currency((int) $this->context->cookie->id_currency))), 'carrier_data' => $this->_getCarrierList()), $this->getFormatedSummaryDetail());
                                 die(Tools::jsonEncode($result));
                             }
                         }
                         if (count($this->errors)) {
                             die(Tools::jsonEncode(array('hasError' => true, 'errors' => $this->errors)));
                         }
                         break;
                     case 'multishipping':
                         $this->_assignSummaryInformations();
                         $this->context->smarty->assign('product_list', $this->context->cart->getProducts());
                         if ($this->context->customer->id) {
                             $this->context->smarty->assign('address_list', $this->context->customer->getAddresses($this->context->language->id));
                         } else {
                             $this->context->smarty->assign('address_list', array());
                         }
                         $this->setTemplate(_PS_THEME_DIR_ . 'order-address-multishipping-products.tpl');
                         $this->display();
                         die;
                         break;
                     case 'cartReload':
                         $this->_assignSummaryInformations();
                         if ($this->context->customer->id) {
                             $this->context->smarty->assign('address_list', $this->context->customer->getAddresses($this->context->language->id));
                         } else {
                             $this->context->smarty->assign('address_list', array());
                         }
                         $this->context->smarty->assign('opc', true);
                         $this->setTemplate(_PS_THEME_DIR_ . 'shopping-cart.tpl');
                         $this->display();
                         die;
                         break;
                     case 'noMultiAddressDelivery':
                         $this->context->cart->setNoMultishipping();
                         die;
                         break;
                     case 'emailCheck':
                         if (Tools::isSubmit('cust_email')) {
                             $customer_email = Tools::getValue('cust_email');
                             $is_registered = Validate::isEmail($customer_email) ? Customer::customerExists($customer_email) : 0;
                             $return = array('is_registered' => $is_registered);
                             die(Tools::jsonEncode($return));
                         }
                         break;
                     case 'zipCheck':
                         if (Tools::isSubmit('id_country')) {
                             $id_country = Tools::getValue('id_country');
                             if ($id_country > 0) {
                                 $errors = array();
                                 $country = new Country($id_country);
                                 $zip_code_format = $country->zip_code_format;
                                 if ($country->need_zip_code) {
                                     if ($postcode = Tools::getValue('postcode') and $zip_code_format) {
                                         $zip_regexp = '/^' . $zip_code_format . '$/ui';
                                         $zip_regexp = str_replace(' ', '( |)', $zip_regexp);
                                         $zip_regexp = str_replace('-', '(-|)', $zip_regexp);
                                         $zip_regexp = str_replace('N', '[0-9]', $zip_regexp);
                                         $zip_regexp = str_replace('L', '[a-zA-Z]', $zip_regexp);
                                         $zip_regexp = str_replace('C', $country->iso_code, $zip_regexp);
                                         if (!preg_match($zip_regexp, $postcode)) {
                                             $errors[] = '<strong>' . Tools::displayError('Zip/ Postal code') . '</strong> ' . Tools::displayError('is invalid.') . '<br />' . Tools::displayError('Must be typed as follows:') . ' ' . str_replace('C', $country->iso_code, str_replace('N', '0', str_replace('L', 'A', $zip_code_format)));
                                         }
                                     } elseif ($zip_code_format) {
                                         $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)) {
                                         $errors[] = '<strong>' . Tools::displayError('Zip/ Postal code') . '</strong> ' . Tools::displayError('is invalid.') . '<br />' . Tools::displayError('Must be typed as follows:') . ' ' . str_replace('C', $country->iso_code, str_replace('N', '0', str_replace('L', 'A', $zip_code_format)));
                                     }
                                 }
                             }
                             //if($id_country>0)
                             $return = array('is_ok' => empty($errors), 'errors' => $errors);
                             die(Tools::jsonEncode($return));
                         }
                         break;
                     default:
                         throw new PrestaShopException('Unknown method "' . Tools::getValue('method') . '"');
                 }
             } else {
                 throw new PrestaShopException('Method is not defined');
             }
         }
     } elseif (Tools::isSubmit('ajax')) {
         throw new PrestaShopException('Method is not defined');
     }
 }
Exemple #20
0
 /**
  * @see FrontController::initContent()
  */
 public function initContent()
 {
     parent::initContent();
     // get discount value (ready to display)
     $discount_type = (int) Configuration::get('REFERRAL_DISCOUNT_TYPE');
     if ($discount_type == 1) {
         $discount = Discount::display((double) Configuration::get('REFERRAL_PERCENTAGE'), $discount_type, new Currency($this->context->currency->id));
     } else {
         $discount = Discount::display((double) Configuration::get('REFERRAL_DISCOUNT_VALUE_' . (int) $this->context->currency->id), $discount_type, new Currency($this->context->currency->id));
     }
     $activeTab = 'sponsor';
     $error = false;
     // Mailing invitation to friend sponsor
     $invitation_sent = false;
     $nbInvitation = 0;
     if (Tools::isSubmit('submitSponsorFriends') and Tools::getValue('friendsEmail') and sizeof($friendsEmail = Tools::getValue('friendsEmail')) >= 1) {
         $activeTab = 'sponsor';
         if (!Tools::getValue('conditionsValided')) {
             $error = 'conditions not valided';
         } else {
             $friendsLastName = Tools::getValue('friendsLastName');
             $friendsFirstName = Tools::getValue('friendsFirstName');
             $mails_exists = array();
             foreach ($friendsEmail as $key => $friendEmail) {
                 $friendEmail = strval($friendEmail);
                 $friendLastName = strval($friendsLastName[$key]);
                 $friendFirstName = strval($friendsFirstName[$key]);
                 if (empty($friendEmail) and empty($friendLastName) and empty($friendFirstName)) {
                     continue;
                 } elseif (empty($friendEmail) or !Validate::isEmail($friendEmail)) {
                     $error = 'email invalid';
                 } elseif (empty($friendFirstName) or empty($friendLastName) or !Validate::isName($friendLastName) or !Validate::isName($friendFirstName)) {
                     $error = 'name invalid';
                 } elseif (ReferralProgramModule::isEmailExists($friendEmail) or Customer::customerExists($friendEmail)) {
                     $mails_exists[] = $friendEmail;
                 } else {
                     $referralprogram = new ReferralProgramModule();
                     $referralprogram->id_sponsor = (int) $this->context->customer->id;
                     $referralprogram->firstname = $friendFirstName;
                     $referralprogram->lastname = $friendLastName;
                     $referralprogram->email = $friendEmail;
                     if (!$referralprogram->validateFields(false)) {
                         $error = 'name invalid';
                     } else {
                         if ($referralprogram->save()) {
                             if (Configuration::get('PS_CIPHER_ALGORITHM')) {
                                 $cipherTool = new Rijndael(_RIJNDAEL_KEY_, _RIJNDAEL_IV_);
                             } else {
                                 $cipherTool = new Blowfish(_COOKIE_KEY_, _COOKIE_IV_);
                             }
                             $vars = array('{email}' => strval($this->context->customer->email), '{lastname}' => strval($this->context->customer->lastname), '{firstname}' => strval($this->context->customer->firstname), '{email_friend}' => $friendEmail, '{lastname_friend}' => $friendLastName, '{firstname_friend}' => $friendFirstName, '{link}' => Context::getContext()->link->getPageLink('authentication', true, Context::getContext()->language->id, 'create_account=1&sponsor=' . urlencode($cipherTool->encrypt($referralprogram->id . '|' . $referralprogram->email . '|')), false), '{discount}' => $discount);
                             Mail::Send((int) $this->context->language->id, 'referralprogram-invitation', Mail::l('Referral Program', (int) $this->context->language->id), $vars, $friendEmail, $friendFirstName . ' ' . $friendLastName, strval(Configuration::get('PS_SHOP_EMAIL')), strval(Configuration::get('PS_SHOP_NAME')), NULL, NULL, dirname(__FILE__) . '/../../mails/');
                             $invitation_sent = true;
                             $nbInvitation++;
                             $activeTab = 'pending';
                         } else {
                             $error = 'cannot add friends';
                         }
                     }
                 }
                 if ($error) {
                     break;
                 }
             }
             if ($nbInvitation > 0) {
                 unset($_POST);
             }
             //Not to stop the sending of e-mails in case of doubloon
             if (sizeof($mails_exists)) {
                 $error = 'email exists';
             }
         }
     }
     // Mailing revive
     $revive_sent = false;
     $nbRevive = 0;
     if (Tools::isSubmit('revive')) {
         $activeTab = 'pending';
         if (Tools::getValue('friendChecked') and sizeof($friendsChecked = Tools::getValue('friendChecked')) >= 1) {
             foreach ($friendsChecked as $key => $friendChecked) {
                 if (ReferralProgramModule::isSponsorFriend((int) $this->context->customer->id, (int) $friendChecked)) {
                     if (Configuration::get('PS_CIPHER_ALGORITHM')) {
                         $cipherTool = new Rijndael(_RIJNDAEL_KEY_, _RIJNDAEL_IV_);
                     } else {
                         $cipherTool = new Blowfish(_COOKIE_KEY_, _COOKIE_IV_);
                     }
                     $referralprogram = new ReferralProgramModule((int) $key);
                     $vars = array('{email}' => $this->context->customer->email, '{lastname}' => $this->context->customer->lastname, '{firstname}' => $this->context->customer->firstname, '{email_friend}' => $referralprogram->email, '{lastname_friend}' => $referralprogram->lastname, '{firstname_friend}' => $referralprogram->firstname, '{link}' => Context::getContext()->link->getPageLink('authentication', true, Context::getContext()->language->id, 'create_account=1&sponsor=' . urlencode($cipherTool->encrypt($referralprogram->id . '|' . $referralprogram->email . '|')), false), '{discount}' => $discount);
                     $referralprogram->save();
                     Mail::Send((int) $this->context->language->id, 'referralprogram-invitation', Mail::l('Referral Program', (int) $this->context->language->id), $vars, $referralprogram->email, $referralprogram->firstname . ' ' . $referralprogram->lastname, strval(Configuration::get('PS_SHOP_EMAIL')), strval(Configuration::get('PS_SHOP_NAME')), NULL, NULL, dirname(__FILE__) . '/../../mails/');
                     $revive_sent = true;
                     $nbRevive++;
                 }
             }
         } else {
             $error = 'no revive checked';
         }
     }
     $customer = new Customer((int) $this->context->customer->id);
     $stats = $customer->getStats();
     $orderQuantity = (int) Configuration::get('REFERRAL_ORDER_QUANTITY');
     $canSendInvitations = false;
     if ((int) $stats['nb_orders'] >= $orderQuantity) {
         $canSendInvitations = true;
     }
     // Smarty display
     $this->context->smarty->assign(array('activeTab' => $activeTab, 'discount' => $discount, 'orderQuantity' => $orderQuantity, 'canSendInvitations' => $canSendInvitations, 'nbFriends' => (int) Configuration::get('REFERRAL_NB_FRIENDS'), 'error' => $error, 'invitation_sent' => $invitation_sent, 'nbInvitation' => $nbInvitation, 'pendingFriends' => ReferralProgramModule::getSponsorFriend((int) $this->context->customer->id, 'pending'), 'revive_sent' => $revive_sent, 'nbRevive' => $nbRevive, 'subscribeFriends' => ReferralProgramModule::getSponsorFriend((int) $this->context->customer->id, 'subscribed'), 'mails_exists' => isset($mails_exists) ? $mails_exists : array()));
     $this->setTemplate('program.tpl');
 }
Exemple #21
0
 protected function processSubmitAccount()
 {
     if (!$this->isOpcModuleActive()) {
         return parent::processSubmitAccount();
     }
     // Entire override is here just because of rigid address set-up. Original PS do not expect
     // address being set to cart prior to processSubmitAccount call and thus always creates new Address
     $inv_first_on = Configuration::get('OPC_INVOICE_FIRST') == "1";
     Hook::exec('actionBeforeSubmitAccount');
     $this->create_account = true;
     if (Tools::isSubmit('submitAccount')) {
         $this->context->smarty->assign('email_create', 1);
     }
     // New Guest customer
     if (!Tools::getValue('is_new_customer', 1) && !Configuration::get('PS_GUEST_CHECKOUT_ENABLED')) {
         $this->errors[] = Tools::displayError('You cannot create a guest account.');
     }
     // Customer (not-guest) checkout, password field is hidden and password is automatically generated
     if ((!Tools::getIsset('passwd') || trim($_POST['passwd']) == "") && trim(Tools::getValue('email')) != "" && Configuration::get('OPC_CREATE_CUSTOMER_PASSWORD') && !CustomerCore::customerExists(Tools::getValue('email'))) {
         $_POST['is_new_customer'] = 1;
         $_POST['passwd'] = Tools::passwdGen(5);
     } elseif (!Tools::getValue('is_new_customer', 1)) {
         $_POST['passwd'] = md5(time() . _COOKIE_KEY_);
     }
     if (Tools::getIsset('guest_email') && $_POST['guest_email']) {
         $_POST['email'] = $_POST['guest_email'];
     }
     // Checked the user address in case he changed his email address
     if (Validate::isEmail($email = Tools::getValue('email')) && !empty($email)) {
         if (Customer::customerExists($email)) {
             $this->errors[] = Tools::displayError('An account is already registered with this e-mail.', false);
         }
     }
     // Preparing customer
     $customer = new Customer();
     $_POST['lastname'] = Tools::getValue('customer_lastname');
     $_POST['firstname'] = Tools::getValue('customer_firstname');
     //        if (Configuration::get('PS_ONE_PHONE_AT_LEAST') && !Tools::getValue('phone') && !Tools::getValue('phone_mobile') &&
     //            (Configuration::get('PS_REGISTRATION_PROCESS_TYPE') || Configuration::get('PS_GUEST_CHECKOUT_ENABLED')))
     //            $this->errors[] = Tools::displayError('You must register at least one phone number');
     $error_phone = false;
     if (Configuration::get('PS_ONE_PHONE_AT_LEAST')) {
         $inv_suffix = $inv_first_on ? "_invoice" : "";
         if (Tools::isSubmit('submitGuestAccount') || !Tools::getValue('is_new_customer')) {
             if (!Tools::getValue('phone' . $inv_suffix) && !Tools::getValue('phone_mobile' . $inv_suffix)) {
                 $error_phone = true;
             }
         } elseif ((Configuration::get('PS_REGISTRATION_PROCESS_TYPE') || Configuration::get('PS_ORDER_PROCESS_TYPE')) && (Configuration::get('PS_ORDER_PROCESS_TYPE') && !Tools::getValue('email_create')) && (!Tools::getValue('phone' . $inv_suffix) && !Tools::getValue('phone_mobile' . $inv_suffix))) {
             $error_phone = true;
         } elseif (Configuration::get('PS_REGISTRATION_PROCESS_TYPE') && Configuration::get('PS_ORDER_PROCESS_TYPE') && Tools::getValue('email_create') && (!Tools::getValue('phone' . $inv_suffix) && !Tools::getValue('phone_mobile' . $inv_suffix))) {
             $error_phone = true;
         }
     }
     if ($error_phone) {
         $this->errors[] = Tools::displayError('You must register at least one phone number.');
     }
     $this->errors = array_unique(array_merge($this->errors, $customer->validateController()));
     // Check the requires fields which are settings in the BO
     $this->errors = array_merge($this->errors, $customer->validateFieldsRequiredDatabase());
     if (!Configuration::get('PS_REGISTRATION_PROCESS_TYPE') && !$this->ajax && !Tools::isSubmit('submitGuestAccount')) {
         if (!count($this->errors)) {
             if (Tools::isSubmit('newsletter')) {
                 $this->processCustomerNewsletter($customer);
             }
             $customer->birthday = empty($_POST['years']) ? '' : (int) $_POST['years'] . '-' . (int) $_POST['months'] . '-' . (int) $_POST['days'];
             if (!Validate::isBirthDate($customer->birthday)) {
                 $this->errors[] = Tools::displayError('Invalid birthday.');
             }
             $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 (!count($this->errors)) {
                 if (!$customer->add()) {
                     $this->errors[] = Tools::displayError('An error occurred while creating your account.');
                 } else {
                     if (!$customer->is_guest) {
                         if (!$this->sendConfirmationMail($customer)) {
                             $this->errors[] = Tools::displayError('Cannot send e-mail');
                         }
                     }
                     $this->updateContext($customer);
                     $this->context->cart->update();
                     Hook::exec('actionCustomerAccountAdd', array('_POST' => $_POST, 'newCustomer' => $customer));
                     if ($this->ajax) {
                         $return = array('hasError' => !empty($this->errors), 'errors' => $this->errors, 'isSaved' => true, 'id_customer' => (int) $this->context->cookie->id_customer, 'id_address_delivery' => $this->context->cart->id_address_delivery, 'id_address_invoice' => $this->context->cart->id_address_invoice, 'token' => Tools::getToken(false));
                         die(Tools::jsonEncode($return));
                     }
                     // redirection: if cart is not empty : redirection to the cart
                     if (count($this->context->cart->getProducts(true)) > 0) {
                         Tools::redirect('index.php?controller=order&multi-shipping=' . (int) Tools::getValue('multi-shipping'));
                     } else {
                         Tools::redirect('index.php?controller=my-account');
                     }
                 }
             }
         }
     } else {
         $lastnameAddress = $inv_first_on ? $_POST['lastname_invoice'] : $_POST['lastname'];
         $firstnameAddress = $inv_first_on ? $_POST['firstname_invoice'] : $_POST['firstname'];
         // Preparing address
         $id_address = isset($this->context->cart->id_address_delivery) ? (int) $this->context->cart->id_address_delivery : 0;
         if ($id_address > 0) {
             $address = new Address($id_address);
         } else {
             $address = new Address();
         }
         $_POST['lastname'] = $lastnameAddress;
         $_POST['firstname'] = $firstnameAddress;
         $address->id_customer = 1;
         $this->errors = array_unique(array_merge($this->errors, $address->validateController()));
         // US customer: normalize the address
         if (version_compare(_PS_VERSION_, "1.6.0") < 0 && $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);
         }
         $inv_suffix = $inv_first_on ? "_invoice" : "";
         $country = new Country((int) Tools::getValue('id_country' . $inv_suffix));
         if ($country->need_zip_code) {
             if (($postcode = Tools::getValue('postcode' . $inv_suffix)) && $country->zip_code_format) {
                 if (!$country->checkZipCode($postcode)) {
                     $this->errors[] = sprintf(Tools::displayError('Zip/Postal code is invalid. Must be typed as follows: %s'), str_replace('C', $country->iso_code, str_replace('N', '0', str_replace('L', 'A', $country->zip_code_format))));
                 }
             } elseif ($country->zip_code_format && !$this->context->cart->isVirtualCart()) {
                 $this->errors[] = Tools::displayError('Zip/Postal code is required.');
             } elseif ($postcode && !preg_match('/^[0-9a-zA-Z -]{4,9}$/ui', $postcode)) {
                 $this->errors[] = Tools::displayError('Zip/Postal code is invalid.');
             }
         }
         /*if ($country->need_identification_number && (!Tools::getValue('dni') || !Validate::isDniLite(Tools::getValue('dni'))))
                     $this->errors[] = Tools::displayError('Identification number is incorrect or has already been used.');
                 elseif (!$country->need_identification_number)
           $address->dni = null;*/
     }
     if (!@checkdate(Tools::getValue('months'), Tools::getValue('days'), Tools::getValue('years')) && !(Tools::getValue('months') == '' && Tools::getValue('days') == '' && Tools::getValue('years') == '')) {
         $this->errors[] = Tools::displayError('Invalid date of birth');
     }
     if (!count($this->errors)) {
         if (Customer::customerExists(Tools::getValue('email'))) {
             $this->errors[] = Tools::displayError('An account is already registered with this e-mail, please enter your password or request a new one.', false);
         }
         if (Tools::isSubmit('newsletter')) {
             $this->processCustomerNewsletter($customer);
         }
         $customer->birthday = empty($_POST['years']) ? '' : (int) $_POST['years'] . '-' . (int) $_POST['months'] . '-' . (int) $_POST['days'];
         if (!Validate::isBirthDate($customer->birthday)) {
             $this->errors[] = Tools::displayError('Invalid birthday.');
         }
         if (!count($this->errors)) {
             // if registration type is in one step, we save the address
             if (Configuration::get('PS_REGISTRATION_PROCESS_TYPE')) {
                 if (!($country = new Country($address->id_country, Configuration::get('PS_LANG_DEFAULT'))) || !Validate::isLoadedObject($country)) {
                     die(Tools::displayError());
                 }
             }
             $contains_state = isset($country) && is_object($country) ? (int) $country->contains_states : 0;
             $id_state = isset($address) && is_object($address) ? (int) $address->id_state : 0;
             if ($contains_state && !$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;
                     $this->errors = array_unique(array_merge($this->errors, $address->validateController()));
                     if (!count($this->errors) && (Configuration::get('PS_REGISTRATION_PROCESS_TYPE') || $this->ajax || Tools::isSubmit('submitGuestAccount'))) {
                         if ($address->id > 0 && !$address->update() || !($address->id > 0) && !$address->add()) {
                             $this->errors[] = Tools::displayError('An error occurred while creating your address.');
                         } else {
                             if (!$customer->is_guest) {
                                 $this->context->customer = $customer;
                                 $customer->cleanGroups();
                                 // we add the guest customer in the default customer group
                                 $customer->addGroups(array((int) Configuration::get('PS_CUSTOMER_GROUP')));
                                 if (!$this->sendConfirmationMail($customer)) {
                                     $this->errors[] = Tools::displayError('Cannot send e-mail');
                                 }
                             } else {
                                 $customer->cleanGroups();
                                 // we add the guest customer in the guest customer group
                                 $customer->addGroups(array((int) Configuration::get('PS_GUEST_GROUP')));
                             }
                             $this->updateContext($customer);
                             $this->context->cart->id_address_delivery = Address::getFirstCustomerAddressId((int) $customer->id);
                             if ($this->context->cart->id_address_invoice == 0) {
                                 $this->context->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
                             $this->context->cart->update();
                             // Avoid articles without delivery address on the cart
                             $this->context->cart->autosetProductAddress();
                             Hook::exec('actionCustomerAccountAdd', array('_POST' => $_POST, 'newCustomer' => $customer));
                             if ($this->ajax) {
                                 $return = array('hasError' => !empty($this->errors), 'errors' => $this->errors, 'isSaved' => true, 'id_customer' => (int) $this->context->cookie->id_customer, 'id_address_delivery' => $this->context->cart->id_address_delivery, 'id_address_invoice' => $this->context->cart->id_address_invoice, 'token' => Tools::getToken(false));
                                 die(Tools::jsonEncode($return));
                             }
                             // if registration type is in two steps, we redirect to register address
                             if (!Configuration::get('PS_REGISTRATION_PROCESS_TYPE') && !$this->ajax && !Tools::isSubmit('submitGuestAccount')) {
                                 Tools::redirect('index.php?controller=address');
                             }
                             if ($back = Tools::getValue('back')) {
                                 Tools::redirect($back);
                             }
                             Tools::redirect('index.php?controller=my-account');
                             // redirection: if cart is not empty : redirection to the cart
                             if (count($this->context->cart->getProducts(true)) > 0) {
                                 Tools::redirect('index.php?controller=order&multi-shipping=' . (int) Tools::getValue('multi-shipping'));
                             } else {
                                 Tools::redirect('index.php?controller=my-account');
                             }
                         }
                     }
                 }
             }
         }
     }
     if (count($this->errors)) {
         //for retro compatibility to display guest account creation form on authentication page
         if (Tools::getValue('submitGuestAccount')) {
             $_GET['display_guest_checkout'] = 1;
         }
         if (!Tools::getValue('is_new_customer')) {
             unset($_POST['passwd']);
         }
         if ($this->ajax) {
             $return = array('hasError' => !empty($this->errors), 'errors' => $this->errors, 'isSaved' => false, 'id_customer' => 0);
             die(Tools::jsonEncode($return));
         }
         $this->context->smarty->assign('account_error', $this->errors);
     }
 }
    /**
     * Return if an email is already register
     *
     * @return boolean OR int idReferralProgram
     */
    public static function isEmailExists($email, $getId = false, $checkCustomer = true)
    {
        if (empty($email) or !Validate::isEmail($email)) {
            die(Tools::displayError('Email invalid.'));
        }
        if ($checkCustomer === true and Customer::customerExists($email)) {
            return false;
        }
        $result = Db::getInstance()->getRow('
		SELECT s.`id_referralprogram`
		FROM `' . _DB_PREFIX_ . 'referralprogram` s
		WHERE s.`email` = \'' . pSQL($email) . '\'');
        if ($getId) {
            return (int) $result['id_referralprogram'];
        }
        return isset($result['id_referralprogram']);
    }
 /**
  * Process submit on a creation
  */
 protected function processSubmitCreate()
 {
     if (!Validate::isEmail($email = trim(Tools::getValue('email_create'))) || empty($email)) {
         $this->errors[] = Tools::displayError('Invalid email address.');
     } elseif (Customer::customerExists($email)) {
         $this->errors[] = Tools::displayError('An account using this email address has already been registered. Please enter a valid password or request a new one. ', false);
         $_POST['email'] = trim(Tools::getValue('email_create'));
         unset($_POST['email_create']);
     } else {
         $this->create_account = true;
         $this->context->smarty->assign('email_create', Tools::safeOutput($email));
         $_POST['email'] = $email;
     }
 }
        $errors[] = Tools::displayError('someone has already registered with this e-mail address');
    } else {
        $create_account = 1;
        $smarty->assign('email_create', Tools::safeOutput($email));
        $_POST['email'] = $email;
    }
}
if (Tools::isSubmit('submitAccount')) {
    $create_account = 1;
    $smarty->assign('email_create', 1);
    $validateDni = Validate::isDni(Tools::getValue('dni'));
    if (!Validate::isEmail($email = Tools::getValue('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 (Tools::getValue('dni') != NULL and $validateDni != 1) {
        $error = array(0 => Tools::displayError('DNI isn\'t valid'), -1 => Tools::displayError('this DNI has been already used'), -2 => Tools::displayError('NIF isn\'t valid'), -3 => Tools::displayError('CIF isn\'t valid'), -4 => Tools::displayError('NIE isn\'t valid'));
        $errors[] = $error[$validateDni];
    } 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($_SERVER['REMOTE_ADDR']);
            $customer->newsletter_date_add = pSQL(date('Y-m-d H:i:s'));
        }
        $customer->birthday = empty($_POST['years']) ? '' : intval($_POST['years']) . '-' . intval($_POST['months']) . '-' . intval($_POST['days']);
        /* Customer and address, same fields, caching data */
        $addrLastname = isset($_POST['lastname']) ? $_POST['lastname'] : $_POST['customer_lastname'];
    function content_555da72d894037_71189998($_smarty_tpl)
    {
        if (!is_callable('smarty_modifier_replace')) {
            include '/home/matej/webapps/webshop/tools/smarty/plugins/modifier.replace.php';
        }
        if (!is_callable('smarty_modifier_regex_replace')) {
            include '/home/matej/webapps/webshop/tools/smarty/plugins/modifier.regex_replace.php';
        }
        ?>

<div class="leadin"></div>


	<script type="text/javascript">
	var admin_order_tab_link = "<?php 
        echo addslashes($_smarty_tpl->tpl_vars['link']->value->getAdminLink('AdminOrders'));
        ?>
";
	var id_order = <?php 
        echo $_smarty_tpl->tpl_vars['order']->value->id;
        ?>
;
	var id_lang = <?php 
        echo $_smarty_tpl->tpl_vars['current_id_lang']->value;
        ?>
;
	var id_currency = <?php 
        echo $_smarty_tpl->tpl_vars['order']->value->id_currency;
        ?>
;
	var id_customer = <?php 
        echo intval($_smarty_tpl->tpl_vars['order']->value->id_customer);
        ?>
;
	<?php 
        $_smarty_tpl->tpl_vars['PS_TAX_ADDRESS_TYPE'] = new Smarty_variable(Configuration::get('PS_TAX_ADDRESS_TYPE'), null, 0);
        ?>
	var id_address = <?php 
        echo $_smarty_tpl->tpl_vars['order']->value->{$_smarty_tpl->tpl_vars['PS_TAX_ADDRESS_TYPE']->value};
        ?>
;
	var currency_sign = "<?php 
        echo $_smarty_tpl->tpl_vars['currency']->value->sign;
        ?>
";
	var currency_format = "<?php 
        echo $_smarty_tpl->tpl_vars['currency']->value->format;
        ?>
";
	var currency_blank = "<?php 
        echo $_smarty_tpl->tpl_vars['currency']->value->blank;
        ?>
";
	var priceDisplayPrecision = <?php 
        echo intval(@constant('_PS_PRICE_DISPLAY_PRECISION_'));
        ?>
;
	var use_taxes = <?php 
        if ($_smarty_tpl->tpl_vars['order']->value->getTaxCalculationMethod() == @constant('PS_TAX_INC')) {
            ?>
true<?php 
        } else {
            ?>
false<?php 
        }
        ?>
;
	var stock_management = <?php 
        echo intval($_smarty_tpl->tpl_vars['stock_management']->value);
        ?>
;
	var txt_add_product_stock_issue = "<?php 
        echo smartyTranslate(array('s' => 'Are you sure you want to add this quantity?', 'js' => 1), $_smarty_tpl);
        ?>
";
	var txt_add_product_new_invoice = "<?php 
        echo smartyTranslate(array('s' => 'Are you sure you want to create a new invoice?', 'js' => 1), $_smarty_tpl);
        ?>
";
	var txt_add_product_no_product = "<?php 
        echo smartyTranslate(array('s' => 'Error: No product has been selected', 'js' => 1), $_smarty_tpl);
        ?>
";
	var txt_add_product_no_product_quantity = "<?php 
        echo smartyTranslate(array('s' => 'Error: Quantity of products must be set', 'js' => 1), $_smarty_tpl);
        ?>
";
	var txt_add_product_no_product_price = "<?php 
        echo smartyTranslate(array('s' => 'Error: Product price must be set', 'js' => 1), $_smarty_tpl);
        ?>
";
	var txt_confirm = "<?php 
        echo smartyTranslate(array('s' => 'Are you sure?', 'js' => 1), $_smarty_tpl);
        ?>
";
	var statesShipped = new Array();
	var has_voucher = <?php 
        if (count($_smarty_tpl->tpl_vars['discounts']->value)) {
            ?>
1<?php 
        } else {
            ?>
0<?php 
        }
        ?>
;
	<?php 
        $_smarty_tpl->tpl_vars['state'] = new Smarty_Variable();
        $_smarty_tpl->tpl_vars['state']->_loop = false;
        $_from = $_smarty_tpl->tpl_vars['states']->value;
        if (!is_array($_from) && !is_object($_from)) {
            settype($_from, 'array');
        }
        foreach ($_from as $_smarty_tpl->tpl_vars['state']->key => $_smarty_tpl->tpl_vars['state']->value) {
            $_smarty_tpl->tpl_vars['state']->_loop = true;
            ?>
		<?php 
            if (isset($_smarty_tpl->tpl_vars['currentState']->value->shipped) && !$_smarty_tpl->tpl_vars['currentState']->value->shipped && $_smarty_tpl->tpl_vars['state']->value['shipped']) {
                ?>
			statesShipped.push(<?php 
                echo $_smarty_tpl->tpl_vars['state']->value['id_order_state'];
                ?>
);
		<?php 
            }
            ?>
	<?php 
        }
        ?>
	var order_discount_price = <?php 
        if ($_smarty_tpl->tpl_vars['order']->value->getTaxCalculationMethod() == @constant('PS_TAX_EXC')) {
            ?>
									<?php 
            echo $_smarty_tpl->tpl_vars['order']->value->total_discounts_tax_excl;
            ?>

								<?php 
        } else {
            ?>
									<?php 
            echo $_smarty_tpl->tpl_vars['order']->value->total_discounts_tax_incl;
            ?>

								<?php 
        }
        ?>
;

	var errorRefund = "<?php 
        echo smartyTranslate(array('s' => 'Error. You cannot refund a negative amount.'), $_smarty_tpl);
        ?>
";
	</script>

	<?php 
        ob_start();
        echo $_smarty_tpl->smarty->registered_plugins[Smarty::PLUGIN_FUNCTION]['hook'][0][0]->smartyHook(array('h' => "displayInvoice", 'id_order' => $_smarty_tpl->tpl_vars['order']->value->id), $_smarty_tpl);
        $_tmp1 = ob_get_clean();
        $_smarty_tpl->tpl_vars["hook_invoice"] = new Smarty_variable($_tmp1, null, 0);
        ?>
	<?php 
        if ($_smarty_tpl->tpl_vars['hook_invoice']->value) {
            ?>
	<div><?php 
            echo $_smarty_tpl->tpl_vars['hook_invoice']->value;
            ?>
</div>
	<?php 
        }
        ?>

	<div class="panel kpi-container">
		<div class="row">
			<div class="col-xs-6 col-sm-3 box-stats color3" >
				<div class="kpi-content">
					<i class="icon-calendar-empty"></i>
					<span class="title"><?php 
        echo smartyTranslate(array('s' => 'Date'), $_smarty_tpl);
        ?>
</span>
					<span class="value"><?php 
        echo $_smarty_tpl->smarty->registered_plugins[Smarty::PLUGIN_FUNCTION]['dateFormat'][0][0]->dateFormat(array('date' => $_smarty_tpl->tpl_vars['order']->value->date_add, 'full' => false), $_smarty_tpl);
        ?>
</span>
				</div>
			</div>
			<div class="col-xs-6 col-sm-3 box-stats color4" >
				<div class="kpi-content">
					<i class="icon-money"></i>
					<span class="title"><?php 
        echo smartyTranslate(array('s' => 'Total'), $_smarty_tpl);
        ?>
</span>
					<span class="value"><?php 
        echo $_smarty_tpl->smarty->registered_plugins[Smarty::PLUGIN_FUNCTION]['displayPrice'][0][0]->displayPriceSmarty(array('price' => $_smarty_tpl->tpl_vars['order']->value->total_paid_tax_incl, 'currency' => $_smarty_tpl->tpl_vars['currency']->value->id), $_smarty_tpl);
        ?>
</span>
				</div>
			</div>
			<div class="col-xs-6 col-sm-3 box-stats color2" >
				<div class="kpi-content">
					<i class="icon-comments"></i>
					<span class="title"><?php 
        echo smartyTranslate(array('s' => 'Messages'), $_smarty_tpl);
        ?>
</span>
					<span class="value"><a href="<?php 
        echo htmlspecialchars($_smarty_tpl->tpl_vars['link']->value->getAdminLink('AdminCustomerThreads'), ENT_QUOTES, 'UTF-8', true);
        ?>
&amp;id_order=<?php 
        echo intval($_smarty_tpl->tpl_vars['order']->value->id);
        ?>
"><?php 
        echo sizeof($_smarty_tpl->tpl_vars['customer_thread_message']->value);
        ?>
</a></span>
				</div>
			</div>
			<div class="col-xs-6 col-sm-3 box-stats color1" >
				<a href="#start_products">
					<div class="kpi-content">
						<i class="icon-book"></i>
						<span class="title"><?php 
        echo smartyTranslate(array('s' => 'Products'), $_smarty_tpl);
        ?>
</span>
						<span class="value"><?php 
        echo sizeof($_smarty_tpl->tpl_vars['products']->value);
        ?>
</span>
					</div>
				</a>
			</div>
		</div>
	</div>
	<div class="row">
		<div class="col-lg-7">
			<div class="panel">
				<div class="panel-heading">
					<i class="icon-credit-card"></i>
					<?php 
        echo smartyTranslate(array('s' => 'Order'), $_smarty_tpl);
        ?>

					<span class="badge"><?php 
        echo $_smarty_tpl->tpl_vars['order']->value->reference;
        ?>
</span>
					<span class="badge"><?php 
        echo smartyTranslate(array('s' => "#"), $_smarty_tpl);
        echo $_smarty_tpl->tpl_vars['order']->value->id;
        ?>
</span>
					<div class="panel-heading-action">
						<div class="btn-group">
							<a class="btn btn-default<?php 
        if (!$_smarty_tpl->tpl_vars['previousOrder']->value) {
            ?>
 disabled<?php 
        }
        ?>
" href="<?php 
        echo htmlspecialchars($_smarty_tpl->tpl_vars['link']->value->getAdminLink('AdminOrders'), ENT_QUOTES, 'UTF-8', true);
        ?>
&amp;vieworder&amp;id_order=<?php 
        echo intval($_smarty_tpl->tpl_vars['previousOrder']->value);
        ?>
">
								<i class="icon-backward"></i>
							</a>
							<a class="btn btn-default<?php 
        if (!$_smarty_tpl->tpl_vars['nextOrder']->value) {
            ?>
 disabled<?php 
        }
        ?>
" href="<?php 
        echo htmlspecialchars($_smarty_tpl->tpl_vars['link']->value->getAdminLink('AdminOrders'), ENT_QUOTES, 'UTF-8', true);
        ?>
&amp;vieworder&amp;id_order=<?php 
        echo intval($_smarty_tpl->tpl_vars['nextOrder']->value);
        ?>
">
								<i class="icon-forward"></i>
							</a>
						</div>
					</div>
				</div>
				<!-- Orders Actions -->
				<div class="well hidden-print">
					<a class="btn btn-default" href="javascript:window.print()">
						<i class="icon-print"></i>
						<?php 
        echo smartyTranslate(array('s' => 'Print order'), $_smarty_tpl);
        ?>

					</a>
					&nbsp;
					<?php 
        if (Configuration::get('PS_INVOICE') && count($_smarty_tpl->tpl_vars['invoices_collection']->value) && $_smarty_tpl->tpl_vars['order']->value->invoice_number) {
            ?>
						<a data-selenium-id="view_invoice" class="btn btn-default _blank" href="<?php 
            echo htmlspecialchars($_smarty_tpl->tpl_vars['link']->value->getAdminLink('AdminPdf'), ENT_QUOTES, 'UTF-8', true);
            ?>
&amp;submitAction=generateInvoicePDF&amp;id_order=<?php 
            echo intval($_smarty_tpl->tpl_vars['order']->value->id);
            ?>
">
							<i class="icon-file"></i>
							<?php 
            echo smartyTranslate(array('s' => 'View invoice'), $_smarty_tpl);
            ?>

						</a>
					<?php 
        } else {
            ?>
						<span class="span label label-inactive">
							<i class="icon-remove"></i>
							<?php 
            echo smartyTranslate(array('s' => 'No invoice'), $_smarty_tpl);
            ?>

						</span>
					<?php 
        }
        ?>
					&nbsp;
					<?php 
        if ($_smarty_tpl->tpl_vars['order']->value->delivery_number) {
            ?>
						<a class="btn btn-default _blank"  href="<?php 
            echo htmlspecialchars($_smarty_tpl->tpl_vars['link']->value->getAdminLink('AdminPdf'), ENT_QUOTES, 'UTF-8', true);
            ?>
&amp;submitAction=generateDeliverySlipPDF&amp;id_order=<?php 
            echo intval($_smarty_tpl->tpl_vars['order']->value->id);
            ?>
">
							<i class="icon-truck"></i>
							<?php 
            echo smartyTranslate(array('s' => 'View delivery slip'), $_smarty_tpl);
            ?>

						</a>
					<?php 
        } else {
            ?>
						<span class="span label label-inactive">
							<i class="icon-remove"></i>
							<?php 
            echo smartyTranslate(array('s' => 'No delivery slip'), $_smarty_tpl);
            ?>

						</span>
					<?php 
        }
        ?>
					&nbsp;
					<?php 
        if (Configuration::get('PS_ORDER_RETURN')) {
            ?>
						<a id="desc-order-standard_refund" class="btn btn-default" href="#refundForm">
							<i class="icon-exchange"></i>
							<?php 
            if ($_smarty_tpl->tpl_vars['order']->value->hasBeenShipped()) {
                ?>
								<?php 
                echo smartyTranslate(array('s' => 'Return products'), $_smarty_tpl);
                ?>

							<?php 
            } elseif ($_smarty_tpl->tpl_vars['order']->value->hasBeenPaid()) {
                ?>
								<?php 
                echo smartyTranslate(array('s' => 'Standard refund'), $_smarty_tpl);
                ?>

							<?php 
            } else {
                ?>
								<?php 
                echo smartyTranslate(array('s' => 'Cancel products'), $_smarty_tpl);
                ?>

							<?php 
            }
            ?>
						</a>
						&nbsp;
					<?php 
        }
        ?>
					<?php 
        if ($_smarty_tpl->tpl_vars['order']->value->hasInvoice()) {
            ?>
						<a id="desc-order-partial_refund" class="btn btn-default" href="#refundForm">
							<i class="icon-exchange"></i>
							<?php 
            echo smartyTranslate(array('s' => 'Partial refund'), $_smarty_tpl);
            ?>

						</a>
					<?php 
        }
        ?>
				</div>
				<!-- Tab nav -->
				<ul class="nav nav-tabs" id="tabOrder">
					<?php 
        echo $_smarty_tpl->tpl_vars['HOOK_TAB_ORDER']->value;
        ?>

					<li class="active">
						<a href="#status">
							<i class="icon-time"></i>
							<?php 
        echo smartyTranslate(array('s' => 'Status'), $_smarty_tpl);
        ?>
 <span class="badge"><?php 
        echo count($_smarty_tpl->tpl_vars['history']->value);
        ?>
</span>
						</a>
					</li>
					<li>
						<a href="#documents">
							<i class="icon-file-text"></i>
							<?php 
        echo smartyTranslate(array('s' => 'Documents'), $_smarty_tpl);
        ?>
 <span class="badge"><?php 
        echo count($_smarty_tpl->tpl_vars['order']->value->getDocuments());
        ?>
</span>
						</a>
					</li>
				</ul>
				<!-- Tab content -->
				<div class="tab-content panel">
					<?php 
        echo $_smarty_tpl->tpl_vars['HOOK_CONTENT_ORDER']->value;
        ?>

					<!-- Tab status -->
					<div class="tab-pane active" id="status">
						<h4 class="visible-print"><?php 
        echo smartyTranslate(array('s' => 'Status'), $_smarty_tpl);
        ?>
 <span class="badge">(<?php 
        echo count($_smarty_tpl->tpl_vars['history']->value);
        ?>
)</span></h4>
						<!-- History of status -->
						<div class="table-responsive">
							<table class="table history-status row-margin-bottom">
								<tbody>
									<?php 
        $_smarty_tpl->tpl_vars['row'] = new Smarty_Variable();
        $_smarty_tpl->tpl_vars['row']->_loop = false;
        $_smarty_tpl->tpl_vars['key'] = new Smarty_Variable();
        $_from = $_smarty_tpl->tpl_vars['history']->value;
        if (!is_array($_from) && !is_object($_from)) {
            settype($_from, 'array');
        }
        foreach ($_from as $_smarty_tpl->tpl_vars['row']->key => $_smarty_tpl->tpl_vars['row']->value) {
            $_smarty_tpl->tpl_vars['row']->_loop = true;
            $_smarty_tpl->tpl_vars['key']->value = $_smarty_tpl->tpl_vars['row']->key;
            ?>
										<?php 
            if ($_smarty_tpl->tpl_vars['key']->value == 0) {
                ?>
											<tr>
												<td style="background-color:<?php 
                echo $_smarty_tpl->tpl_vars['row']->value['color'];
                ?>
"><img src="../img/os/<?php 
                echo intval($_smarty_tpl->tpl_vars['row']->value['id_order_state']);
                ?>
.gif" width="16" height="16" alt="<?php 
                echo stripslashes($_smarty_tpl->tpl_vars['row']->value['ostate_name']);
                ?>
" /></td>
												<td style="background-color:<?php 
                echo $_smarty_tpl->tpl_vars['row']->value['color'];
                ?>
;color:<?php 
                echo $_smarty_tpl->tpl_vars['row']->value['text-color'];
                ?>
"><?php 
                echo stripslashes($_smarty_tpl->tpl_vars['row']->value['ostate_name']);
                ?>
</td>
												<td style="background-color:<?php 
                echo $_smarty_tpl->tpl_vars['row']->value['color'];
                ?>
;color:<?php 
                echo $_smarty_tpl->tpl_vars['row']->value['text-color'];
                ?>
"><?php 
                if ($_smarty_tpl->tpl_vars['row']->value['employee_lastname']) {
                    echo stripslashes($_smarty_tpl->tpl_vars['row']->value['employee_firstname']);
                    ?>
 <?php 
                    echo stripslashes($_smarty_tpl->tpl_vars['row']->value['employee_lastname']);
                }
                ?>
</td>
												<td style="background-color:<?php 
                echo $_smarty_tpl->tpl_vars['row']->value['color'];
                ?>
;color:<?php 
                echo $_smarty_tpl->tpl_vars['row']->value['text-color'];
                ?>
"><?php 
                echo $_smarty_tpl->smarty->registered_plugins[Smarty::PLUGIN_FUNCTION]['dateFormat'][0][0]->dateFormat(array('date' => $_smarty_tpl->tpl_vars['row']->value['date_add'], 'full' => true), $_smarty_tpl);
                ?>
</td>
											</tr>
										<?php 
            } else {
                ?>
											<tr>
												<td><img src="../img/os/<?php 
                echo intval($_smarty_tpl->tpl_vars['row']->value['id_order_state']);
                ?>
.gif" width="16" height="16" /></td>
												<td><?php 
                echo stripslashes($_smarty_tpl->tpl_vars['row']->value['ostate_name']);
                ?>
</td>
												<td><?php 
                if ($_smarty_tpl->tpl_vars['row']->value['employee_lastname']) {
                    echo stripslashes($_smarty_tpl->tpl_vars['row']->value['employee_firstname']);
                    ?>
 <?php 
                    echo stripslashes($_smarty_tpl->tpl_vars['row']->value['employee_lastname']);
                } else {
                    ?>
&nbsp;<?php 
                }
                ?>
</td>
												<td><?php 
                echo $_smarty_tpl->smarty->registered_plugins[Smarty::PLUGIN_FUNCTION]['dateFormat'][0][0]->dateFormat(array('date' => $_smarty_tpl->tpl_vars['row']->value['date_add'], 'full' => true), $_smarty_tpl);
                ?>
</td>
											</tr>
										<?php 
            }
            ?>
									<?php 
        }
        ?>
								</tbody>
							</table>
						</div>
						<!-- Change status form -->
						<form action="<?php 
        echo htmlspecialchars($_smarty_tpl->tpl_vars['currentIndex']->value, ENT_QUOTES, 'UTF-8', true);
        ?>
&amp;vieworder&amp;token=<?php 
        echo $_GET['token'];
        ?>
" method="post" class="form-horizontal well hidden-print">
							<div class="row">
								<div class="col-lg-9">
									<select id="id_order_state" class="chosen form-control" name="id_order_state">
									<?php 
        $_smarty_tpl->tpl_vars['state'] = new Smarty_Variable();
        $_smarty_tpl->tpl_vars['state']->_loop = false;
        $_from = $_smarty_tpl->tpl_vars['states']->value;
        if (!is_array($_from) && !is_object($_from)) {
            settype($_from, 'array');
        }
        foreach ($_from as $_smarty_tpl->tpl_vars['state']->key => $_smarty_tpl->tpl_vars['state']->value) {
            $_smarty_tpl->tpl_vars['state']->_loop = true;
            ?>
										<option value="<?php 
            echo intval($_smarty_tpl->tpl_vars['state']->value['id_order_state']);
            ?>
"<?php 
            if (isset($_smarty_tpl->tpl_vars['currentState']->value) && $_smarty_tpl->tpl_vars['state']->value['id_order_state'] == $_smarty_tpl->tpl_vars['currentState']->value->id) {
                ?>
 selected="selected" disabled="disabled"<?php 
            }
            ?>
><?php 
            echo htmlspecialchars($_smarty_tpl->tpl_vars['state']->value['name'], ENT_QUOTES, 'UTF-8', true);
            ?>
</option>
									<?php 
        }
        ?>
									</select>
									<input type="hidden" name="id_order" value="<?php 
        echo $_smarty_tpl->tpl_vars['order']->value->id;
        ?>
" />
								</div>
								<div class="col-lg-3">
									<button type="submit" name="submitState" class="btn btn-primary">
										<?php 
        echo smartyTranslate(array('s' => 'Update status'), $_smarty_tpl);
        ?>

									</button>
								</div>
							</div>
						</form>
					</div>
					<!-- Tab documents -->
					<div class="tab-pane" id="documents">
						<h4 class="visible-print"><?php 
        echo smartyTranslate(array('s' => 'Documents'), $_smarty_tpl);
        ?>
 <span class="badge">(<?php 
        echo count($_smarty_tpl->tpl_vars['order']->value->getDocuments());
        ?>
)</span></h4>
						
						<?php 
        /*  Call merged included template "controllers/orders/_documents.tpl" */
        $_tpl_stack[] = $_smarty_tpl;
        $_smarty_tpl = $_smarty_tpl->setupInlineSubTemplate('controllers/orders/_documents.tpl', $_smarty_tpl->cache_id, $_smarty_tpl->compile_id, 0, null, array(), 0, '2029977810555da72cbcc318-60413189');
        content_555da72ce258d6_83092321($_smarty_tpl);
        $_smarty_tpl = array_pop($_tpl_stack);
        /*  End of included template "controllers/orders/_documents.tpl" */
        ?>
					</div>
				</div>
				<script>
					$('#tabOrder a').click(function (e) {
						e.preventDefault()
						$(this).tab('show')
					})
				</script>
				<hr />
				<!-- Tab nav -->
				<ul class="nav nav-tabs" id="myTab">
					<?php 
        echo $_smarty_tpl->tpl_vars['HOOK_TAB_SHIP']->value;
        ?>

					<li class="active">
						<a href="#shipping">
							<i class="icon-truck "></i>
							<?php 
        echo smartyTranslate(array('s' => 'Shipping'), $_smarty_tpl);
        ?>
 <span class="badge"><?php 
        echo count($_smarty_tpl->tpl_vars['order']->value->getShipping());
        ?>
</span>
						</a>
					</li>
					<li>
						<a href="#returns">
							<i class="icon-undo"></i>
							<?php 
        echo smartyTranslate(array('s' => 'Merchandise Returns'), $_smarty_tpl);
        ?>
 <span class="badge"><?php 
        echo count($_smarty_tpl->tpl_vars['order']->value->getReturn());
        ?>
</span>
						</a>
					</li>
				</ul>
				<!-- Tab content -->
				<div class="tab-content panel">
				<?php 
        echo $_smarty_tpl->tpl_vars['HOOK_CONTENT_SHIP']->value;
        ?>

					<!-- Tab shipping -->
					<div class="tab-pane active" id="shipping">
						<h4 class="visible-print"><?php 
        echo smartyTranslate(array('s' => 'Shipping'), $_smarty_tpl);
        ?>
 <span class="badge">(<?php 
        echo count($_smarty_tpl->tpl_vars['order']->value->getShipping());
        ?>
)</span></h4>
						<!-- Shipping block -->
						<?php 
        if (!$_smarty_tpl->tpl_vars['order']->value->isVirtual()) {
            ?>
						<div class="form-horizontal">
							<?php 
            if ($_smarty_tpl->tpl_vars['order']->value->gift_message) {
                ?>
							<div class="form-group">
								<label class="control-label col-lg-3"><?php 
                echo smartyTranslate(array('s' => 'Message'), $_smarty_tpl);
                ?>
</label>
								<div class="col-lg-9">
									<p class="form-control-static"><?php 
                echo nl2br($_smarty_tpl->tpl_vars['order']->value->gift_message);
                ?>
</p>
								</div>
							</div>
							<?php 
            }
            ?>
							<?php 
            /*  Call merged included template "controllers/orders/_shipping.tpl" */
            $_tpl_stack[] = $_smarty_tpl;
            $_smarty_tpl = $_smarty_tpl->setupInlineSubTemplate('controllers/orders/_shipping.tpl', $_smarty_tpl->cache_id, $_smarty_tpl->compile_id, 0, null, array(), 0, '2029977810555da72cbcc318-60413189');
            content_555da72cf33e54_32419215($_smarty_tpl);
            $_smarty_tpl = array_pop($_tpl_stack);
            /*  End of included template "controllers/orders/_shipping.tpl" */
            ?>
							<?php 
            if ($_smarty_tpl->tpl_vars['carrierModuleCall']->value) {
                ?>
								<?php 
                echo $_smarty_tpl->tpl_vars['carrierModuleCall']->value;
                ?>

							<?php 
            }
            ?>
							<hr />
							<?php 
            if ($_smarty_tpl->tpl_vars['order']->value->recyclable) {
                ?>
								<span class="label label-success"><i class="icon-check"></i> <?php 
                echo smartyTranslate(array('s' => 'Recycled packaging'), $_smarty_tpl);
                ?>
</span>
							<?php 
            } else {
                ?>
								<span class="label label-inactive"><i class="icon-remove"></i> <?php 
                echo smartyTranslate(array('s' => 'Recycled packaging'), $_smarty_tpl);
                ?>
</span>
							<?php 
            }
            ?>

							<?php 
            if ($_smarty_tpl->tpl_vars['order']->value->gift) {
                ?>
								<span class="label label-success"><i class="icon-check"></i> <?php 
                echo smartyTranslate(array('s' => 'Gift wrapping'), $_smarty_tpl);
                ?>
</span>
							<?php 
            } else {
                ?>
								<span class="label label-inactive"><i class="icon-remove"></i> <?php 
                echo smartyTranslate(array('s' => 'Gift wrapping'), $_smarty_tpl);
                ?>
</span>
							<?php 
            }
            ?>
						</div>
						<?php 
        }
        ?>
					</div>
					<!-- Tab returns -->
					<div class="tab-pane" id="returns">
						<h4 class="visible-print"><?php 
        echo smartyTranslate(array('s' => 'Merchandise Returns'), $_smarty_tpl);
        ?>
 <span class="badge">(<?php 
        echo count($_smarty_tpl->tpl_vars['order']->value->getReturn());
        ?>
)</span></h4>
						<?php 
        if (!$_smarty_tpl->tpl_vars['order']->value->isVirtual()) {
            ?>
						<!-- Return block -->
							<?php 
            if (count($_smarty_tpl->tpl_vars['order']->value->getReturn()) > 0) {
                ?>
							<div class="table-responsive">
								<table class="table">
									<thead>
										<tr>
											<th><span class="title_box ">Date</span></th>
											<th><span class="title_box ">Type</span></th>
											<th><span class="title_box ">Carrier</span></th>
											<th><span class="title_box ">Tracking number</span></th>
										</tr>
									</thead>
									<tbody>
										<?php 
                $_smarty_tpl->tpl_vars['line'] = new Smarty_Variable();
                $_smarty_tpl->tpl_vars['line']->_loop = false;
                $_from = $_smarty_tpl->tpl_vars['order']->value->getReturn();
                if (!is_array($_from) && !is_object($_from)) {
                    settype($_from, 'array');
                }
                foreach ($_from as $_smarty_tpl->tpl_vars['line']->key => $_smarty_tpl->tpl_vars['line']->value) {
                    $_smarty_tpl->tpl_vars['line']->_loop = true;
                    ?>
										<tr>
											<td><?php 
                    echo $_smarty_tpl->tpl_vars['line']->value['date_add'];
                    ?>
</td>
											<td><?php 
                    echo $_smarty_tpl->tpl_vars['line']->value['type'];
                    ?>
</td>
											<td><?php 
                    echo $_smarty_tpl->tpl_vars['line']->value['state_name'];
                    ?>
</td>
											<td class="actions">
												<span class="shipping_number_show"><?php 
                    if (isset($_smarty_tpl->tpl_vars['line']->value['url']) && isset($_smarty_tpl->tpl_vars['line']->value['tracking_number'])) {
                        ?>
<a href="<?php 
                        echo htmlspecialchars(smarty_modifier_replace($_smarty_tpl->tpl_vars['line']->value['url'], '@', $_smarty_tpl->tpl_vars['line']->value['tracking_number']), ENT_QUOTES, 'UTF-8', true);
                        ?>
"><?php 
                        echo $_smarty_tpl->tpl_vars['line']->value['tracking_number'];
                        ?>
</a><?php 
                    } elseif (isset($_smarty_tpl->tpl_vars['line']->value['tracking_number'])) {
                        echo $_smarty_tpl->tpl_vars['line']->value['tracking_number'];
                    }
                    ?>
</span>
												<?php 
                    if ($_smarty_tpl->tpl_vars['line']->value['can_edit']) {
                        ?>
												<form method="post" action="<?php 
                        echo htmlspecialchars($_smarty_tpl->tpl_vars['link']->value->getAdminLink('AdminOrders'), ENT_QUOTES, 'UTF-8', true);
                        ?>
&amp;vieworder&amp;id_order=<?php 
                        echo intval($_smarty_tpl->tpl_vars['order']->value->id);
                        ?>
&amp;id_order_invoice=<?php 
                        if ($_smarty_tpl->tpl_vars['line']->value['id_order_invoice']) {
                            echo intval($_smarty_tpl->tpl_vars['line']->value['id_order_invoice']);
                        } else {
                            ?>
0<?php 
                        }
                        ?>
&amp;id_carrier=<?php 
                        if ($_smarty_tpl->tpl_vars['line']->value['id_carrier']) {
                            echo htmlspecialchars($_smarty_tpl->tpl_vars['line']->value['id_carrier'], ENT_QUOTES, 'UTF-8', true);
                        } else {
                            ?>
0<?php 
                        }
                        ?>
">
													<span class="shipping_number_edit" style="display:none;">
														<button type="button" name="tracking_number">
															<?php 
                        echo htmlentities($_smarty_tpl->tpl_vars['line']->value['tracking_number']);
                        ?>

														</button>
														<button type="submit" class="btn btn-default" name="submitShippingNumber">
															<?php 
                        echo smartyTranslate(array('s' => 'Update'), $_smarty_tpl);
                        ?>

														</button>
													</span>
													<button href="#" class="edit_shipping_number_link">
														<i class="icon-pencil"></i>
														<?php 
                        echo smartyTranslate(array('s' => 'Edit'), $_smarty_tpl);
                        ?>

													</button>
													<button href="#" class="cancel_shipping_number_link" style="display: none;">
														<i class="icon-remove"></i>
														<?php 
                        echo smartyTranslate(array('s' => 'Cancel'), $_smarty_tpl);
                        ?>

													</button>
												</form>
												<?php 
                    }
                    ?>
											</td>
										</tr>
										<?php 
                }
                ?>
									</tbody>
								</table>
							</div>
							<?php 
            } else {
                ?>
							<div class="list-empty hidden-print">
								<div class="list-empty-msg">
									<i class="icon-warning-sign list-empty-icon"></i>
									<?php 
                echo smartyTranslate(array('s' => 'No merchandise returned yet'), $_smarty_tpl);
                ?>

								</div>
							</div>
							<?php 
            }
            ?>
							<?php 
            if ($_smarty_tpl->tpl_vars['carrierModuleCall']->value) {
                ?>
								<?php 
                echo $_smarty_tpl->tpl_vars['carrierModuleCall']->value;
                ?>

							<?php 
            }
            ?>
						<?php 
        }
        ?>
					</div>
				</div>
				<script>
					$('#myTab a').click(function (e) {
						e.preventDefault()
						$(this).tab('show')
					})
				</script>
			</div>
			<!-- Payments block -->
			<div id="formAddPaymentPanel" class="panel">
				<div class="panel-heading">
					<i class="icon-money"></i>
					<?php 
        echo smartyTranslate(array('s' => "Payment"), $_smarty_tpl);
        ?>
 <span class="badge"><?php 
        echo count($_smarty_tpl->tpl_vars['order']->value->getOrderPayments());
        ?>
</span>
				</div>
				<?php 
        if (count($_smarty_tpl->tpl_vars['order']->value->getOrderPayments()) > 0) {
            ?>
					<p class="alert alert-danger"<?php 
            if (round($_smarty_tpl->tpl_vars['orders_total_paid_tax_incl']->value, 2) == round($_smarty_tpl->tpl_vars['total_paid']->value, 2) || isset($_smarty_tpl->tpl_vars['currentState']->value) && $_smarty_tpl->tpl_vars['currentState']->value->id == 6) {
                ?>
 style="display: none;"<?php 
            }
            ?>
>
						<?php 
            echo smartyTranslate(array('s' => 'Warning'), $_smarty_tpl);
            ?>

						<strong><?php 
            echo $_smarty_tpl->smarty->registered_plugins[Smarty::PLUGIN_FUNCTION]['displayPrice'][0][0]->displayPriceSmarty(array('price' => $_smarty_tpl->tpl_vars['total_paid']->value, 'currency' => $_smarty_tpl->tpl_vars['currency']->value->id), $_smarty_tpl);
            ?>
</strong>
						<?php 
            echo smartyTranslate(array('s' => 'paid instead of'), $_smarty_tpl);
            ?>

						<strong class="total_paid"><?php 
            echo $_smarty_tpl->smarty->registered_plugins[Smarty::PLUGIN_FUNCTION]['displayPrice'][0][0]->displayPriceSmarty(array('price' => $_smarty_tpl->tpl_vars['orders_total_paid_tax_incl']->value, 'currency' => $_smarty_tpl->tpl_vars['currency']->value->id), $_smarty_tpl);
            ?>
</strong>
						<?php 
            $_smarty_tpl->tpl_vars['brother_order'] = new Smarty_Variable();
            $_smarty_tpl->tpl_vars['brother_order']->_loop = false;
            $_from = $_smarty_tpl->tpl_vars['order']->value->getBrother();
            if (!is_array($_from) && !is_object($_from)) {
                settype($_from, 'array');
            }
            $_smarty_tpl->tpl_vars['brother_order']->index = -1;
            foreach ($_from as $_smarty_tpl->tpl_vars['brother_order']->key => $_smarty_tpl->tpl_vars['brother_order']->value) {
                $_smarty_tpl->tpl_vars['brother_order']->_loop = true;
                $_smarty_tpl->tpl_vars['brother_order']->index++;
                $_smarty_tpl->tpl_vars['brother_order']->first = $_smarty_tpl->tpl_vars['brother_order']->index === 0;
                ?>
							<?php 
                if ($_smarty_tpl->tpl_vars['brother_order']->first) {
                    ?>
								<?php 
                    if (count($_smarty_tpl->tpl_vars['order']->value->getBrother()) == 1) {
                        ?>
									<br /><?php 
                        echo smartyTranslate(array('s' => 'This warning also concerns order '), $_smarty_tpl);
                        ?>

								<?php 
                    } else {
                        ?>
									<br /><?php 
                        echo smartyTranslate(array('s' => 'This warning also concerns the next orders:'), $_smarty_tpl);
                        ?>

								<?php 
                    }
                    ?>
							<?php 
                }
                ?>
							<a href="<?php 
                echo $_smarty_tpl->tpl_vars['current_index']->value;
                ?>
&amp;vieworder&amp;id_order=<?php 
                echo $_smarty_tpl->tpl_vars['brother_order']->value->id;
                ?>
&amp;token=<?php 
                echo htmlspecialchars($_GET['token'], ENT_QUOTES, 'UTF-8', true);
                ?>
">
								#<?php 
                echo sprintf('%06d', $_smarty_tpl->tpl_vars['brother_order']->value->id);
                ?>

							</a>
						<?php 
            }
            ?>
					</p>
				<?php 
        }
        ?>
				<form id="formAddPayment"  method="post" action="<?php 
        echo $_smarty_tpl->tpl_vars['current_index']->value;
        ?>
&amp;vieworder&amp;id_order=<?php 
        echo $_smarty_tpl->tpl_vars['order']->value->id;
        ?>
&amp;token=<?php 
        echo htmlspecialchars($_GET['token'], ENT_QUOTES, 'UTF-8', true);
        ?>
">
					<div class="table-responsive">
						<table class="table">
							<thead>
								<tr>
									<th><span class="title_box "><?php 
        echo smartyTranslate(array('s' => 'Date'), $_smarty_tpl);
        ?>
</span></th>
									<th><span class="title_box "><?php 
        echo smartyTranslate(array('s' => 'Payment method'), $_smarty_tpl);
        ?>
</span></th>
									<th><span class="title_box "><?php 
        echo smartyTranslate(array('s' => 'Transaction ID'), $_smarty_tpl);
        ?>
</span></th>
									<th><span class="title_box "><?php 
        echo smartyTranslate(array('s' => 'Amount'), $_smarty_tpl);
        ?>
</span></th>
									<th><span class="title_box "><?php 
        echo smartyTranslate(array('s' => 'Invoice'), $_smarty_tpl);
        ?>
</span></th>
									<th></th>
								</tr>
							</thead>
							<tbody>
								<?php 
        $_smarty_tpl->tpl_vars['payment'] = new Smarty_Variable();
        $_smarty_tpl->tpl_vars['payment']->_loop = false;
        $_from = $_smarty_tpl->tpl_vars['order']->value->getOrderPaymentCollection();
        if (!is_array($_from) && !is_object($_from)) {
            settype($_from, 'array');
        }
        foreach ($_from as $_smarty_tpl->tpl_vars['payment']->key => $_smarty_tpl->tpl_vars['payment']->value) {
            $_smarty_tpl->tpl_vars['payment']->_loop = true;
            ?>
								<tr>
									<td><?php 
            echo $_smarty_tpl->smarty->registered_plugins[Smarty::PLUGIN_FUNCTION]['dateFormat'][0][0]->dateFormat(array('date' => $_smarty_tpl->tpl_vars['payment']->value->date_add, 'full' => true), $_smarty_tpl);
            ?>
</td>
									<td><?php 
            echo htmlspecialchars($_smarty_tpl->tpl_vars['payment']->value->payment_method, ENT_QUOTES, 'UTF-8', true);
            ?>
</td>
									<td><?php 
            echo htmlspecialchars($_smarty_tpl->tpl_vars['payment']->value->transaction_id, ENT_QUOTES, 'UTF-8', true);
            ?>
</td>
									<td><?php 
            echo $_smarty_tpl->smarty->registered_plugins[Smarty::PLUGIN_FUNCTION]['displayPrice'][0][0]->displayPriceSmarty(array('price' => $_smarty_tpl->tpl_vars['payment']->value->amount, 'currency' => $_smarty_tpl->tpl_vars['payment']->value->id_currency), $_smarty_tpl);
            ?>
</td>
									<td>
									<?php 
            if (!isset($_smarty_tpl->tpl_vars['invoice'])) {
                $_smarty_tpl->tpl_vars['invoice'] = new Smarty_Variable(null);
            }
            if ($_smarty_tpl->tpl_vars['invoice']->value = $_smarty_tpl->tpl_vars['payment']->value->getOrderInvoice($_smarty_tpl->tpl_vars['order']->value->id)) {
                ?>
										<?php 
                echo $_smarty_tpl->tpl_vars['invoice']->value->getInvoiceNumberFormatted($_smarty_tpl->tpl_vars['current_id_lang']->value, $_smarty_tpl->tpl_vars['order']->value->id_shop);
                ?>

									<?php 
            } else {
                ?>
									<?php 
            }
            ?>
									</td>
									<td class="actions">
										<button class="btn btn-default open_payment_information">
											<i class="icon-search"></i>
											<?php 
            echo smartyTranslate(array('s' => 'Details'), $_smarty_tpl);
            ?>

										</button>
									</td>
								</tr>
								<tr class="payment_information" style="display: none;">
									<td colspan="5">
										<p>
											<b><?php 
            echo smartyTranslate(array('s' => 'Card Number'), $_smarty_tpl);
            ?>
</b>&nbsp;
											<?php 
            if ($_smarty_tpl->tpl_vars['payment']->value->card_number) {
                ?>
												<?php 
                echo $_smarty_tpl->tpl_vars['payment']->value->card_number;
                ?>

											<?php 
            } else {
                ?>
												<i><?php 
                echo smartyTranslate(array('s' => 'Not defined'), $_smarty_tpl);
                ?>
</i>
											<?php 
            }
            ?>
										</p>
										<p>
											<b><?php 
            echo smartyTranslate(array('s' => 'Card Brand'), $_smarty_tpl);
            ?>
</b>&nbsp;
											<?php 
            if ($_smarty_tpl->tpl_vars['payment']->value->card_brand) {
                ?>
												<?php 
                echo $_smarty_tpl->tpl_vars['payment']->value->card_brand;
                ?>

											<?php 
            } else {
                ?>
												<i><?php 
                echo smartyTranslate(array('s' => 'Not defined'), $_smarty_tpl);
                ?>
</i>
											<?php 
            }
            ?>
										</p>
										<p>
											<b><?php 
            echo smartyTranslate(array('s' => 'Card Expiration'), $_smarty_tpl);
            ?>
</b>&nbsp;
											<?php 
            if ($_smarty_tpl->tpl_vars['payment']->value->card_expiration) {
                ?>
												<?php 
                echo $_smarty_tpl->tpl_vars['payment']->value->card_expiration;
                ?>

											<?php 
            } else {
                ?>
												<i><?php 
                echo smartyTranslate(array('s' => 'Not defined'), $_smarty_tpl);
                ?>
</i>
											<?php 
            }
            ?>
										</p>
										<p>
											<b><?php 
            echo smartyTranslate(array('s' => 'Card Holder'), $_smarty_tpl);
            ?>
</b>&nbsp;
											<?php 
            if ($_smarty_tpl->tpl_vars['payment']->value->card_holder) {
                ?>
												<?php 
                echo $_smarty_tpl->tpl_vars['payment']->value->card_holder;
                ?>

											<?php 
            } else {
                ?>
												<i><?php 
                echo smartyTranslate(array('s' => 'Not defined'), $_smarty_tpl);
                ?>
</i>
											<?php 
            }
            ?>
										</p>
									</td>
								</tr>
								<?php 
        }
        if (!$_smarty_tpl->tpl_vars['payment']->_loop) {
            ?>
								<tr>
									<td class="list-empty hidden-print" colspan="6">
										<div class="list-empty-msg">
											<i class="icon-warning-sign list-empty-icon"></i>
											<?php 
            echo smartyTranslate(array('s' => 'No payment methods are available'), $_smarty_tpl);
            ?>

										</div>
									</td>
								</tr>
								<?php 
        }
        ?>
								<tr class="current-edit hidden-print">
									<td>
										<div class="input-group fixed-width-xl">
											<input type="text" name="payment_date" class="datepicker" value="<?php 
        echo date('Y-m-d');
        ?>
" />
											<div class="input-group-addon">
												<i class="icon-calendar-o"></i>
											</div>
										</div>
									</td>
									<td>
										<input name="payment_method" list="payment_method" class="payment_method">
										<datalist id="payment_method">
										<?php 
        $_smarty_tpl->tpl_vars['payment_method'] = new Smarty_Variable();
        $_smarty_tpl->tpl_vars['payment_method']->_loop = false;
        $_from = $_smarty_tpl->tpl_vars['payment_methods']->value;
        if (!is_array($_from) && !is_object($_from)) {
            settype($_from, 'array');
        }
        foreach ($_from as $_smarty_tpl->tpl_vars['payment_method']->key => $_smarty_tpl->tpl_vars['payment_method']->value) {
            $_smarty_tpl->tpl_vars['payment_method']->_loop = true;
            ?>
											<option value="<?php 
            echo $_smarty_tpl->tpl_vars['payment_method']->value;
            ?>
">
										<?php 
        }
        ?>
										</datalist>
									</td>
									<td>
										<input type="text" name="payment_transaction_id" value="" class="form-control fixed-width-sm"/>
									</td>
									<td>
										<input type="text" name="payment_amount" value="" class="form-control fixed-width-sm pull-left" />
										<select name="payment_currency" class="payment_currency form-control fixed-width-xs pull-left">
											<?php 
        $_smarty_tpl->tpl_vars['current_currency'] = new Smarty_Variable();
        $_smarty_tpl->tpl_vars['current_currency']->_loop = false;
        $_from = $_smarty_tpl->tpl_vars['currencies']->value;
        if (!is_array($_from) && !is_object($_from)) {
            settype($_from, 'array');
        }
        foreach ($_from as $_smarty_tpl->tpl_vars['current_currency']->key => $_smarty_tpl->tpl_vars['current_currency']->value) {
            $_smarty_tpl->tpl_vars['current_currency']->_loop = true;
            ?>
												<option value="<?php 
            echo $_smarty_tpl->tpl_vars['current_currency']->value['id_currency'];
            ?>
"<?php 
            if ($_smarty_tpl->tpl_vars['current_currency']->value['id_currency'] == $_smarty_tpl->tpl_vars['currency']->value->id) {
                ?>
 selected="selected"<?php 
            }
            ?>
><?php 
            echo $_smarty_tpl->tpl_vars['current_currency']->value['sign'];
            ?>
</option>
											<?php 
        }
        ?>
										</select>
									</td>
									<td>
										<?php 
        if (count($_smarty_tpl->tpl_vars['invoices_collection']->value) > 0) {
            ?>
											<select name="payment_invoice" id="payment_invoice">
											<?php 
            $_smarty_tpl->tpl_vars['invoice'] = new Smarty_Variable();
            $_smarty_tpl->tpl_vars['invoice']->_loop = false;
            $_from = $_smarty_tpl->tpl_vars['invoices_collection']->value;
            if (!is_array($_from) && !is_object($_from)) {
                settype($_from, 'array');
            }
            foreach ($_from as $_smarty_tpl->tpl_vars['invoice']->key => $_smarty_tpl->tpl_vars['invoice']->value) {
                $_smarty_tpl->tpl_vars['invoice']->_loop = true;
                ?>
												<option value="<?php 
                echo $_smarty_tpl->tpl_vars['invoice']->value->id;
                ?>
" selected="selected"><?php 
                echo $_smarty_tpl->tpl_vars['invoice']->value->getInvoiceNumberFormatted($_smarty_tpl->tpl_vars['current_id_lang']->value, $_smarty_tpl->tpl_vars['order']->value->id_shop);
                ?>
</option>
											<?php 
            }
            ?>
											</select>
										<?php 
        }
        ?>
									</td>
									<td class="actions">
										<button class="btn btn-primary btn-block" type="submit" name="submitAddPayment">
											<?php 
        echo smartyTranslate(array('s' => 'Add'), $_smarty_tpl);
        ?>

										</button>
									</td>
								</tr>
							</tbody>
						</table>
					</div>
				</form>
				<?php 
        if (!$_smarty_tpl->tpl_vars['order']->value->valid && sizeof($_smarty_tpl->tpl_vars['currencies']->value) > 1) {
            ?>
					<form class="form-horizontal well" method="post" action="<?php 
            echo htmlspecialchars($_smarty_tpl->tpl_vars['currentIndex']->value, ENT_QUOTES, 'UTF-8', true);
            ?>
&amp;vieworder&amp;id_order=<?php 
            echo $_smarty_tpl->tpl_vars['order']->value->id;
            ?>
&amp;token=<?php 
            echo htmlspecialchars($_GET['token'], ENT_QUOTES, 'UTF-8', true);
            ?>
">
						<div class="row">
							<label class="control-label col-lg-3"><?php 
            echo smartyTranslate(array('s' => 'Change currency'), $_smarty_tpl);
            ?>
</label>
							<div class="col-lg-6">
								<select name="new_currency">
								<?php 
            $_smarty_tpl->tpl_vars['currency_change'] = new Smarty_Variable();
            $_smarty_tpl->tpl_vars['currency_change']->_loop = false;
            $_from = $_smarty_tpl->tpl_vars['currencies']->value;
            if (!is_array($_from) && !is_object($_from)) {
                settype($_from, 'array');
            }
            foreach ($_from as $_smarty_tpl->tpl_vars['currency_change']->key => $_smarty_tpl->tpl_vars['currency_change']->value) {
                $_smarty_tpl->tpl_vars['currency_change']->_loop = true;
                ?>
									<?php 
                if ($_smarty_tpl->tpl_vars['currency_change']->value['id_currency'] != $_smarty_tpl->tpl_vars['order']->value->id_currency) {
                    ?>
									<option value="<?php 
                    echo $_smarty_tpl->tpl_vars['currency_change']->value['id_currency'];
                    ?>
"><?php 
                    echo $_smarty_tpl->tpl_vars['currency_change']->value['name'];
                    ?>
 - <?php 
                    echo $_smarty_tpl->tpl_vars['currency_change']->value['sign'];
                    ?>
</option>
									<?php 
                }
                ?>
								<?php 
            }
            ?>
								</select>
								<p class="help-block"><?php 
            echo smartyTranslate(array('s' => 'Do not forget to update your exchange rate before making this change.'), $_smarty_tpl);
            ?>
</p>
							</div>
							<div class="col-lg-3">
								<button type="submit" class="btn btn-default" name="submitChangeCurrency"><i class="icon-refresh"></i> <?php 
            echo smartyTranslate(array('s' => 'Change'), $_smarty_tpl);
            ?>
</button>
							</div>
						</div>
					</form>
				<?php 
        }
        ?>
			</div>
			<?php 
        echo $_smarty_tpl->smarty->registered_plugins[Smarty::PLUGIN_FUNCTION]['hook'][0][0]->smartyHook(array('h' => "displayAdminOrderLeft", 'id_order' => $_smarty_tpl->tpl_vars['order']->value->id), $_smarty_tpl);
        ?>

		</div>
		<div class="col-lg-5">
			<!-- Customer informations -->
			<div class="panel">
				<?php 
        if ($_smarty_tpl->tpl_vars['customer']->value->id) {
            ?>
					<div class="panel-heading">
						<i class="icon-user"></i>
						<?php 
            echo smartyTranslate(array('s' => 'Customer'), $_smarty_tpl);
            ?>

						<span class="badge">
							<a href="?tab=AdminCustomers&amp;id_customer=<?php 
            echo $_smarty_tpl->tpl_vars['customer']->value->id;
            ?>
&amp;viewcustomer&amp;token=<?php 
            echo $_smarty_tpl->smarty->registered_plugins[Smarty::PLUGIN_FUNCTION]['getAdminToken'][0][0]->getAdminTokenLiteSmarty(array('tab' => 'AdminCustomers'), $_smarty_tpl);
            ?>
">
								<?php 
            if (Configuration::get('PS_B2B_ENABLE')) {
                echo $_smarty_tpl->tpl_vars['customer']->value->company;
                ?>
 - <?php 
            }
            ?>
								<?php 
            echo htmlspecialchars($_smarty_tpl->tpl_vars['gender']->value->name, ENT_QUOTES, 'UTF-8', true);
            ?>

								<?php 
            echo $_smarty_tpl->tpl_vars['customer']->value->firstname;
            ?>

								<?php 
            echo $_smarty_tpl->tpl_vars['customer']->value->lastname;
            ?>

							</a>
						</span>
						<span class="badge">
							<?php 
            echo smartyTranslate(array('s' => '#'), $_smarty_tpl);
            echo $_smarty_tpl->tpl_vars['customer']->value->id;
            ?>

						</span>
					</div>
					<div class="row">
						<div class="col-xs-6">
							<?php 
            if ($_smarty_tpl->tpl_vars['customer']->value->isGuest()) {
                ?>
								<?php 
                echo smartyTranslate(array('s' => 'This order has been placed by a guest.'), $_smarty_tpl);
                ?>

								<?php 
                if (!Customer::customerExists($_smarty_tpl->tpl_vars['customer']->value->email)) {
                    ?>
									<form method="post" action="index.php?tab=AdminCustomers&amp;id_customer=<?php 
                    echo $_smarty_tpl->tpl_vars['customer']->value->id;
                    ?>
&amp;token=<?php 
                    echo $_smarty_tpl->smarty->registered_plugins[Smarty::PLUGIN_FUNCTION]['getAdminToken'][0][0]->getAdminTokenLiteSmarty(array('tab' => 'AdminCustomers'), $_smarty_tpl);
                    ?>
">
										<input type="hidden" name="id_lang" value="<?php 
                    echo $_smarty_tpl->tpl_vars['order']->value->id_lang;
                    ?>
" />
										<input class="btn btn-default" type="submit" name="submitGuestToCustomer" value="<?php 
                    echo smartyTranslate(array('s' => 'Transform a guest into a customer'), $_smarty_tpl);
                    ?>
" />
										<p class="help-block"><?php 
                    echo smartyTranslate(array('s' => 'This feature will generate a random password and send an email to the customer.'), $_smarty_tpl);
                    ?>
</p>
									</form>
								<?php 
                } else {
                    ?>
									<div class="alert alert-warning">
										<?php 
                    echo smartyTranslate(array('s' => 'A registered customer account has already claimed this email address'), $_smarty_tpl);
                    ?>

									</div>
								<?php 
                }
                ?>
							<?php 
            } else {
                ?>
								<dl class="well list-detail">
									<dt><?php 
                echo smartyTranslate(array('s' => 'Email'), $_smarty_tpl);
                ?>
</dt>
										<dd><a href="mailto:<?php 
                echo $_smarty_tpl->tpl_vars['customer']->value->email;
                ?>
"><i class="icon-envelope-o"></i> <?php 
                echo $_smarty_tpl->tpl_vars['customer']->value->email;
                ?>
</a></dd>
									<dt><?php 
                echo smartyTranslate(array('s' => 'Account registered'), $_smarty_tpl);
                ?>
</dt>
										<dd class="text-muted"><i class="icon-calendar-o"></i> <?php 
                echo $_smarty_tpl->smarty->registered_plugins[Smarty::PLUGIN_FUNCTION]['dateFormat'][0][0]->dateFormat(array('date' => $_smarty_tpl->tpl_vars['customer']->value->date_add, 'full' => true), $_smarty_tpl);
                ?>
</dd>
									<dt><?php 
                echo smartyTranslate(array('s' => 'Valid orders placed'), $_smarty_tpl);
                ?>
</dt>
										<dd><span class="badge"><?php 
                echo intval($_smarty_tpl->tpl_vars['customerStats']->value['nb_orders']);
                ?>
</span></dd>
									<dt><?php 
                echo smartyTranslate(array('s' => 'Total spent since registration'), $_smarty_tpl);
                ?>
</dt>
										<dd><span class="badge badge-success"><?php 
                echo $_smarty_tpl->smarty->registered_plugins[Smarty::PLUGIN_FUNCTION]['displayPrice'][0][0]->displayPriceSmarty(array('price' => Tools::ps_round(Tools::convertPrice($_smarty_tpl->tpl_vars['customerStats']->value['total_orders'], $_smarty_tpl->tpl_vars['currency']->value), 2), 'currency' => $_smarty_tpl->tpl_vars['currency']->value->id), $_smarty_tpl);
                ?>
</span></dd>
									<?php 
                if (Configuration::get('PS_B2B_ENABLE')) {
                    ?>
										<dt><?php 
                    echo smartyTranslate(array('s' => 'Siret'), $_smarty_tpl);
                    ?>
</dt>
											<dd><?php 
                    echo $_smarty_tpl->tpl_vars['customer']->value->siret;
                    ?>
</dd>
										<dt><?php 
                    echo smartyTranslate(array('s' => 'APE'), $_smarty_tpl);
                    ?>
</dt>
											<dd><?php 
                    echo $_smarty_tpl->tpl_vars['customer']->value->ape;
                    ?>
</dd>
									<?php 
                }
                ?>
								</dl>
							<?php 
            }
            ?>
						</div>

						<div class="col-xs-6">
							<div class="form-group hidden-print">
								<a href="?tab=AdminCustomers&amp;id_customer=<?php 
            echo $_smarty_tpl->tpl_vars['customer']->value->id;
            ?>
&amp;viewcustomer&amp;token=<?php 
            echo $_smarty_tpl->smarty->registered_plugins[Smarty::PLUGIN_FUNCTION]['getAdminToken'][0][0]->getAdminTokenLiteSmarty(array('tab' => 'AdminCustomers'), $_smarty_tpl);
            ?>
" class="btn btn-default btn-block"><?php 
            echo smartyTranslate(array('s' => 'View full details...'), $_smarty_tpl);
            ?>
</a>
							</div>
							<div class="panel panel-sm">
								<div class="panel-heading">
									<i class="icon-eye-slash"></i>
									<?php 
            echo smartyTranslate(array('s' => 'Private note'), $_smarty_tpl);
            ?>

								</div>
								<form id="customer_note" class="form-horizontal" action="ajax.php" method="post" onsubmit="saveCustomerNote(<?php 
            echo $_smarty_tpl->tpl_vars['customer']->value->id;
            ?>
);return false;" >
									<div class="form-group">
										<div class="col-lg-12">
											<textarea name="note" id="noteContent" class="textarea-autosize" onkeyup="$(this).val().length > 0 ? $('#submitCustomerNote').removeAttr('disabled') : $('#submitCustomerNote').attr('disabled', 'disabled')"><?php 
            echo $_smarty_tpl->tpl_vars['customer']->value->note;
            ?>
</textarea>
										</div>
									</div>
									<div class="row">
										<div class="col-lg-12">
											<button type="submit" id="submitCustomerNote" class="btn btn-default pull-right" disabled="disabled">
												<i class="icon-save"></i>
												<?php 
            echo smartyTranslate(array('s' => 'Save'), $_smarty_tpl);
            ?>

											</button>
										</div>
									</div>
									<span id="note_feedback"></span>
								</form>
							</div>
						</div>
					</div>
				<?php 
        }
        ?>
				<!-- Tab nav -->
				<div class="row">
					<ul class="nav nav-tabs" id="tabAddresses">
						<li class="active">
							<a href="#addressShipping">
								<i class="icon-truck"></i>
								<?php 
        echo smartyTranslate(array('s' => 'Shipping address'), $_smarty_tpl);
        ?>

							</a>
						</li>
						<li>
							<a href="#addressInvoice">
								<i class="icon-file-text"></i>
								<?php 
        echo smartyTranslate(array('s' => 'Invoice address'), $_smarty_tpl);
        ?>

							</a>
						</li>
					</ul>
					<!-- Tab content -->
					<div class="tab-content panel">
						<!-- Tab status -->
						<div class="tab-pane  in active" id="addressShipping">
							<!-- Addresses -->
							<h4 class="visible-print"><?php 
        echo smartyTranslate(array('s' => 'Shipping address'), $_smarty_tpl);
        ?>
</h4>
							<?php 
        if (!$_smarty_tpl->tpl_vars['order']->value->isVirtual()) {
            ?>
							<!-- Shipping address -->
								<?php 
            if ($_smarty_tpl->tpl_vars['can_edit']->value) {
                ?>
									<form class="form-horizontal hidden-print" method="post" action="<?php 
                echo htmlspecialchars($_smarty_tpl->tpl_vars['link']->value->getAdminLink('AdminOrders'), ENT_QUOTES, 'UTF-8', true);
                ?>
&amp;vieworder&amp;id_order=<?php 
                echo intval($_smarty_tpl->tpl_vars['order']->value->id);
                ?>
">
										<div class="form-group">
											<div class="col-lg-9">
												<select name="id_address">
													<?php 
                $_smarty_tpl->tpl_vars['address'] = new Smarty_Variable();
                $_smarty_tpl->tpl_vars['address']->_loop = false;
                $_from = $_smarty_tpl->tpl_vars['customer_addresses']->value;
                if (!is_array($_from) && !is_object($_from)) {
                    settype($_from, 'array');
                }
                foreach ($_from as $_smarty_tpl->tpl_vars['address']->key => $_smarty_tpl->tpl_vars['address']->value) {
                    $_smarty_tpl->tpl_vars['address']->_loop = true;
                    ?>
													<option value="<?php 
                    echo $_smarty_tpl->tpl_vars['address']->value['id_address'];
                    ?>
"
														<?php 
                    if ($_smarty_tpl->tpl_vars['address']->value['id_address'] == $_smarty_tpl->tpl_vars['order']->value->id_address_delivery) {
                        ?>
															selected="selected"
														<?php 
                    }
                    ?>
>
														<?php 
                    echo $_smarty_tpl->tpl_vars['address']->value['alias'];
                    ?>
 -
														<?php 
                    echo $_smarty_tpl->tpl_vars['address']->value['address1'];
                    ?>

														<?php 
                    echo $_smarty_tpl->tpl_vars['address']->value['postcode'];
                    ?>

														<?php 
                    echo $_smarty_tpl->tpl_vars['address']->value['city'];
                    ?>

														<?php 
                    if (!empty($_smarty_tpl->tpl_vars['address']->value['state'])) {
                        ?>
															<?php 
                        echo $_smarty_tpl->tpl_vars['address']->value['state'];
                        ?>

														<?php 
                    }
                    ?>
,
														<?php 
                    echo $_smarty_tpl->tpl_vars['address']->value['country'];
                    ?>

													</option>
													<?php 
                }
                ?>
												</select>
											</div>
											<div class="col-lg-3">
												<button class="btn btn-default" type="submit" name="submitAddressShipping"><i class="icon-refresh"></i> <?php 
                echo smartyTranslate(array('s' => 'Change'), $_smarty_tpl);
                ?>
</button>
											</div>
										</div>
									</form>
								<?php 
            }
            ?>
								<div class="well">
									<div class="row">
										<div class="col-sm-6">
											<a class="btn btn-default pull-right" href="?tab=AdminAddresses&amp;id_address=<?php 
            echo $_smarty_tpl->tpl_vars['addresses']->value['delivery']->id;
            ?>
&amp;addaddress&amp;realedit=1&amp;id_order=<?php 
            echo $_smarty_tpl->tpl_vars['order']->value->id;
            ?>
&amp;address_type=1&amp;token=<?php 
            echo $_smarty_tpl->smarty->registered_plugins[Smarty::PLUGIN_FUNCTION]['getAdminToken'][0][0]->getAdminTokenLiteSmarty(array('tab' => 'AdminAddresses'), $_smarty_tpl);
            ?>
&amp;back=<?php 
            echo urlencode($_SERVER['REQUEST_URI']);
            ?>
">
												<i class="icon-pencil"></i>
												<?php 
            echo smartyTranslate(array('s' => 'Edit'), $_smarty_tpl);
            ?>

											</a>
											<?php 
            echo $_smarty_tpl->smarty->registered_plugins[Smarty::PLUGIN_FUNCTION]['displayAddressDetail'][0][0]->generateAddressSmarty(array('address' => $_smarty_tpl->tpl_vars['addresses']->value['delivery'], 'newLine' => '<br />'), $_smarty_tpl);
            ?>

											<?php 
            if ($_smarty_tpl->tpl_vars['addresses']->value['delivery']->other) {
                ?>
												<hr /><?php 
                echo $_smarty_tpl->tpl_vars['addresses']->value['delivery']->other;
                ?>
<br />
											<?php 
            }
            ?>
										</div>
										<div class="col-sm-6 hidden-print">
											<div id="map-delivery-canvas" style="height: 190px"></div>
										</div>
									</div>
								</div>
							<?php 
        }
        ?>
						</div>
						<div class="tab-pane " id="addressInvoice">
							<!-- Invoice address -->
							<h4 class="visible-print"><?php 
        echo smartyTranslate(array('s' => 'Invoice address'), $_smarty_tpl);
        ?>
</h4>
							<?php 
        if ($_smarty_tpl->tpl_vars['can_edit']->value) {
            ?>
								<form class="form-horizontal hidden-print" method="post" action="<?php 
            echo htmlspecialchars($_smarty_tpl->tpl_vars['link']->value->getAdminLink('AdminOrders'), ENT_QUOTES, 'UTF-8', true);
            ?>
&amp;vieworder&amp;id_order=<?php 
            echo intval($_smarty_tpl->tpl_vars['order']->value->id);
            ?>
">
									<div class="form-group">
										<div class="col-lg-9">
											<select name="id_address">
												<?php 
            $_smarty_tpl->tpl_vars['address'] = new Smarty_Variable();
            $_smarty_tpl->tpl_vars['address']->_loop = false;
            $_from = $_smarty_tpl->tpl_vars['customer_addresses']->value;
            if (!is_array($_from) && !is_object($_from)) {
                settype($_from, 'array');
            }
            foreach ($_from as $_smarty_tpl->tpl_vars['address']->key => $_smarty_tpl->tpl_vars['address']->value) {
                $_smarty_tpl->tpl_vars['address']->_loop = true;
                ?>
												<option value="<?php 
                echo $_smarty_tpl->tpl_vars['address']->value['id_address'];
                ?>
"
													<?php 
                if ($_smarty_tpl->tpl_vars['address']->value['id_address'] == $_smarty_tpl->tpl_vars['order']->value->id_address_invoice) {
                    ?>
													selected="selected"
													<?php 
                }
                ?>
>
													<?php 
                echo $_smarty_tpl->tpl_vars['address']->value['alias'];
                ?>
 -
													<?php 
                echo $_smarty_tpl->tpl_vars['address']->value['address1'];
                ?>

													<?php 
                echo $_smarty_tpl->tpl_vars['address']->value['postcode'];
                ?>

													<?php 
                echo $_smarty_tpl->tpl_vars['address']->value['city'];
                ?>

													<?php 
                if (!empty($_smarty_tpl->tpl_vars['address']->value['state'])) {
                    ?>
														<?php 
                    echo $_smarty_tpl->tpl_vars['address']->value['state'];
                    ?>

													<?php 
                }
                ?>
,
													<?php 
                echo $_smarty_tpl->tpl_vars['address']->value['country'];
                ?>

												</option>
												<?php 
            }
            ?>
											</select>
										</div>
										<div class="col-lg-3">
											<button class="btn btn-default" type="submit" name="submitAddressInvoice"><i class="icon-refresh"></i> <?php 
            echo smartyTranslate(array('s' => 'Change'), $_smarty_tpl);
            ?>
</button>
										</div>
									</div>
								</form>
							<?php 
        }
        ?>
							<div class="well">
								<div class="row">
									<div class="col-sm-6">
										<a class="btn btn-default pull-right" href="?tab=AdminAddresses&amp;id_address=<?php 
        echo $_smarty_tpl->tpl_vars['addresses']->value['invoice']->id;
        ?>
&amp;addaddress&amp;realedit=1&amp;id_order=<?php 
        echo $_smarty_tpl->tpl_vars['order']->value->id;
        ?>
&amp;address_type=2&amp;back=<?php 
        echo urlencode($_SERVER['REQUEST_URI']);
        ?>
&amp;token=<?php 
        echo $_smarty_tpl->smarty->registered_plugins[Smarty::PLUGIN_FUNCTION]['getAdminToken'][0][0]->getAdminTokenLiteSmarty(array('tab' => 'AdminAddresses'), $_smarty_tpl);
        ?>
">
											<i class="icon-pencil"></i>
											<?php 
        echo smartyTranslate(array('s' => 'Edit'), $_smarty_tpl);
        ?>

										</a>
										<?php 
        echo $_smarty_tpl->smarty->registered_plugins[Smarty::PLUGIN_FUNCTION]['displayAddressDetail'][0][0]->generateAddressSmarty(array('address' => $_smarty_tpl->tpl_vars['addresses']->value['invoice'], 'newLine' => '<br />'), $_smarty_tpl);
        ?>

										<?php 
        if ($_smarty_tpl->tpl_vars['addresses']->value['invoice']->other) {
            ?>
											<hr /><?php 
            echo $_smarty_tpl->tpl_vars['addresses']->value['invoice']->other;
            ?>
<br />
										<?php 
        }
        ?>
									</div>
									<div class="col-sm-6 hidden-print">
										<div id="map-invoice-canvas" style="height: 190px"></div>
									</div>
								</div>
							</div>
						</div>
					</div>
				</div>
				<script>
					$('#tabAddresses a').click(function (e) {
						e.preventDefault()
						$(this).tab('show')
					})
				</script>
			</div>
			<div class="panel">
				<div class="panel-heading">
					<i class="icon-envelope"></i> <?php 
        echo smartyTranslate(array('s' => 'Messages'), $_smarty_tpl);
        ?>
 <span class="badge"><?php 
        echo sizeof($_smarty_tpl->tpl_vars['customer_thread_message']->value);
        ?>
</span>
				</div>
				<?php 
        if (sizeof($_smarty_tpl->tpl_vars['messages']->value)) {
            ?>
					<div class="panel panel-highlighted">
						<div class="message-item">
							<?php 
            $_smarty_tpl->tpl_vars['message'] = new Smarty_Variable();
            $_smarty_tpl->tpl_vars['message']->_loop = false;
            $_from = $_smarty_tpl->tpl_vars['messages']->value;
            if (!is_array($_from) && !is_object($_from)) {
                settype($_from, 'array');
            }
            foreach ($_from as $_smarty_tpl->tpl_vars['message']->key => $_smarty_tpl->tpl_vars['message']->value) {
                $_smarty_tpl->tpl_vars['message']->_loop = true;
                ?>
								<div class="message-avatar">
									<div class="avatar-md">
										<i class="icon-user icon-2x"></i>
									</div>
								</div>
								<div class="message-body">

									<span class="message-date">&nbsp;<i class="icon-calendar"></i>
										<?php 
                echo $_smarty_tpl->smarty->registered_plugins[Smarty::PLUGIN_FUNCTION]['dateFormat'][0][0]->dateFormat(array('date' => $_smarty_tpl->tpl_vars['message']->value['date_add']), $_smarty_tpl);
                ?>
 -
									</span>
									<h4 class="message-item-heading">
										<?php 
                if (htmlspecialchars($_smarty_tpl->tpl_vars['message']->value['elastname'], ENT_QUOTES, 'UTF-8', true)) {
                    echo htmlspecialchars($_smarty_tpl->tpl_vars['message']->value['efirstname'], ENT_QUOTES, 'UTF-8', true);
                    ?>

											<?php 
                    echo htmlspecialchars($_smarty_tpl->tpl_vars['message']->value['elastname'], ENT_QUOTES, 'UTF-8', true);
                } else {
                    echo htmlspecialchars($_smarty_tpl->tpl_vars['message']->value['cfirstname'], ENT_QUOTES, 'UTF-8', true);
                    ?>
 <?php 
                    echo htmlspecialchars($_smarty_tpl->tpl_vars['message']->value['clastname'], ENT_QUOTES, 'UTF-8', true);
                    ?>

										<?php 
                }
                ?>
										<?php 
                if ($_smarty_tpl->tpl_vars['message']->value['private'] == 1) {
                    ?>
											<span class="badge badge-info"><?php 
                    echo smartyTranslate(array('s' => 'Private'), $_smarty_tpl);
                    ?>
</span>
										<?php 
                }
                ?>
									</h4>
									<p class="message-item-text">
										<?php 
                echo nl2br(htmlspecialchars($_smarty_tpl->tpl_vars['message']->value['message'], ENT_QUOTES, 'UTF-8', true));
                ?>

									</p>
								</div>
								
							<?php 
            }
            ?>
						</div>
					</div>
				<?php 
        }
        ?>
				<div id="messages" class="well hidden-print">
					<form action="<?php 
        echo htmlspecialchars($_SERVER['REQUEST_URI'], ENT_QUOTES, 'UTF-8', true);
        ?>
&amp;token=<?php 
        echo htmlspecialchars($_GET['token'], ENT_QUOTES, 'UTF-8', true);
        ?>
" method="post" onsubmit="if (getE('visibility').checked == true) return confirm('<?php 
        echo smartyTranslate(array('s' => 'Do you want to send this message to the customer?'), $_smarty_tpl);
        ?>
');">
						<div id="message" class="form-horizontal">
							<div class="form-group">
								<label class="control-label col-lg-3"><?php 
        echo smartyTranslate(array('s' => 'Choose a standard message'), $_smarty_tpl);
        ?>
</label>
								<div class="col-lg-9">
									<select class="chosen form-control" name="order_message" id="order_message" onchange="orderOverwriteMessage(this, '<?php 
        echo smartyTranslate(array('s' => 'Do you want to overwrite your existing message?'), $_smarty_tpl);
        ?>
')">
										<option value="0" selected="selected">-</option>
										<?php 
        $_smarty_tpl->tpl_vars['orderMessage'] = new Smarty_Variable();
        $_smarty_tpl->tpl_vars['orderMessage']->_loop = false;
        $_from = $_smarty_tpl->tpl_vars['orderMessages']->value;
        if (!is_array($_from) && !is_object($_from)) {
            settype($_from, 'array');
        }
        foreach ($_from as $_smarty_tpl->tpl_vars['orderMessage']->key => $_smarty_tpl->tpl_vars['orderMessage']->value) {
            $_smarty_tpl->tpl_vars['orderMessage']->_loop = true;
            ?>
										<option value="<?php 
            echo htmlspecialchars($_smarty_tpl->tpl_vars['orderMessage']->value['message'], ENT_QUOTES, 'UTF-8', true);
            ?>
"><?php 
            echo $_smarty_tpl->tpl_vars['orderMessage']->value['name'];
            ?>
</option>
										<?php 
        }
        ?>
									</select>
									<p class="help-block">
										<a href="<?php 
        echo htmlspecialchars($_smarty_tpl->tpl_vars['link']->value->getAdminLink('AdminOrderMessage'), ENT_QUOTES, 'UTF-8', true);
        ?>
">
											<?php 
        echo smartyTranslate(array('s' => 'Configure predefined messages'), $_smarty_tpl);
        ?>

											<i class="icon-external-link"></i>
										</a>
									</p>
								</div>
							</div>

							<div class="form-group">
								<label class="control-label col-lg-3"><?php 
        echo smartyTranslate(array('s' => 'Display to customer?'), $_smarty_tpl);
        ?>
</label>
								<div class="col-lg-9">
									<span class="switch prestashop-switch fixed-width-lg">
										<input type="radio" name="visibility" id="visibility_on" value="0" />
										<label for="visibility_on">
											<?php 
        echo smartyTranslate(array('s' => 'Yes'), $_smarty_tpl);
        ?>

										</label>
										<input type="radio" name="visibility" id="visibility_off" value="1" checked="checked" />
										<label for="visibility_off">
											<?php 
        echo smartyTranslate(array('s' => 'No'), $_smarty_tpl);
        ?>

										</label>
										<a class="slide-button btn"></a>
									</span>
								</div>
							</div>

							<div class="form-group">
								<label class="control-label col-lg-3"><?php 
        echo smartyTranslate(array('s' => 'Message'), $_smarty_tpl);
        ?>
</label>
								<div class="col-lg-9">
									<textarea id="txt_msg" class="textarea-autosize" name="message"><?php 
        echo htmlspecialchars(Tools::getValue('message'), ENT_QUOTES, 'UTF-8', true);
        ?>
</textarea>
									<p id="nbchars"></p>
								</div>
							</div>


							<input type="hidden" name="id_order" value="<?php 
        echo $_smarty_tpl->tpl_vars['order']->value->id;
        ?>
" />
							<input type="hidden" name="id_customer" value="<?php 
        echo $_smarty_tpl->tpl_vars['order']->value->id_customer;
        ?>
" />
							<button type="submit" id="submitMessage" class="btn btn-primary pull-right" name="submitMessage">
								<?php 
        echo smartyTranslate(array('s' => 'Send message'), $_smarty_tpl);
        ?>

							</button>
							<a class="btn btn-default" href="<?php 
        echo htmlspecialchars($_smarty_tpl->tpl_vars['link']->value->getAdminLink('AdminCustomerThreads'), ENT_QUOTES, 'UTF-8', true);
        ?>
&amp;id_order=<?php 
        echo intval($_smarty_tpl->tpl_vars['order']->value->id);
        ?>
">
								<?php 
        echo smartyTranslate(array('s' => 'Show all messages'), $_smarty_tpl);
        ?>

								<i class="icon-external-link"></i>
							</a>
						</div>
					</form>
				</div>
			</div>
			<?php 
        echo $_smarty_tpl->smarty->registered_plugins[Smarty::PLUGIN_FUNCTION]['hook'][0][0]->smartyHook(array('h' => "displayAdminOrderRight", 'id_order' => $_smarty_tpl->tpl_vars['order']->value->id), $_smarty_tpl);
        ?>

		</div>
	</div>
	<?php 
        echo $_smarty_tpl->smarty->registered_plugins[Smarty::PLUGIN_FUNCTION]['hook'][0][0]->smartyHook(array('h' => "displayAdminOrder", 'id_order' => $_smarty_tpl->tpl_vars['order']->value->id), $_smarty_tpl);
        ?>

	<div class="row" id="start_products">
		<div class="col-lg-12">
			<form class="container-command-top-spacing" action="<?php 
        echo $_smarty_tpl->tpl_vars['current_index']->value;
        ?>
&amp;vieworder&amp;token=<?php 
        echo htmlspecialchars($_GET['token'], ENT_QUOTES, 'UTF-8', true);
        ?>
&amp;id_order=<?php 
        echo intval($_smarty_tpl->tpl_vars['order']->value->id);
        ?>
" method="post" onsubmit="return orderDeleteProduct('<?php 
        echo smartyTranslate(array('s' => 'This product cannot be returned.'), $_smarty_tpl);
        ?>
', '<?php 
        echo smartyTranslate(array('s' => 'Quantity to cancel is greater than quantity available.'), $_smarty_tpl);
        ?>
');">
				<input type="hidden" name="id_order" value="<?php 
        echo $_smarty_tpl->tpl_vars['order']->value->id;
        ?>
" />
				<div style="display: none">
					<input type="hidden" value="<?php 
        echo implode($_smarty_tpl->tpl_vars['order']->value->getWarehouseList());
        ?>
" id="warehouse_list" />
				</div>

				<div class="panel">
					<div class="panel-heading">
						<i class="icon-shopping-cart"></i>
						<?php 
        echo smartyTranslate(array('s' => 'Products'), $_smarty_tpl);
        ?>
 <span class="badge"><?php 
        echo count($_smarty_tpl->tpl_vars['products']->value);
        ?>
</span>
					</div>
					<div id="refundForm">
					<!--
						<a href="#" class="standard_refund"><img src="../img/admin/add.gif" alt="<?php 
        echo smartyTranslate(array('s' => 'Process a standard refund'), $_smarty_tpl);
        ?>
" /> <?php 
        echo smartyTranslate(array('s' => 'Process a standard refund'), $_smarty_tpl);
        ?>
</a>
						<a href="#" class="partial_refund"><img src="../img/admin/add.gif" alt="<?php 
        echo smartyTranslate(array('s' => 'Process a partial refund'), $_smarty_tpl);
        ?>
" /> <?php 
        echo smartyTranslate(array('s' => 'Process a partial refund'), $_smarty_tpl);
        ?>
</a>
					-->
					</div>

					<?php 
        $_smarty_tpl->_capture_stack[0][] = array("TaxMethod", null, null);
        ob_start();
        ?>
						<?php 
        if ($_smarty_tpl->tpl_vars['order']->value->getTaxCalculationMethod() == @constant('PS_TAX_EXC')) {
            ?>
							<?php 
            echo smartyTranslate(array('s' => 'tax excluded.'), $_smarty_tpl);
            ?>

						<?php 
        } else {
            ?>
							<?php 
            echo smartyTranslate(array('s' => 'tax included.'), $_smarty_tpl);
            ?>

						<?php 
        }
        ?>
					<?php 
        list($_capture_buffer, $_capture_assign, $_capture_append) = array_pop($_smarty_tpl->_capture_stack[0]);
        if (!empty($_capture_buffer)) {
            if (isset($_capture_assign)) {
                $_smarty_tpl->assign($_capture_assign, ob_get_contents());
            }
            if (isset($_capture_append)) {
                $_smarty_tpl->append($_capture_append, ob_get_contents());
            }
            Smarty::$_smarty_vars['capture'][$_capture_buffer] = ob_get_clean();
        } else {
            $_smarty_tpl->capture_error();
        }
        ?>
					<?php 
        if ($_smarty_tpl->tpl_vars['order']->value->getTaxCalculationMethod() == @constant('PS_TAX_EXC')) {
            ?>
						<input type="hidden" name="TaxMethod" value="0">
					<?php 
        } else {
            ?>
						<input type="hidden" name="TaxMethod" value="1">
					<?php 
        }
        ?>
					<div class="table-responsive">
						<table class="table" id="orderProducts">
							<thead>
								<tr>
									<th></th>
									<th><span class="title_box "><?php 
        echo smartyTranslate(array('s' => 'Product'), $_smarty_tpl);
        ?>
</span></th>
									<th>
										<span class="title_box "><?php 
        echo smartyTranslate(array('s' => 'Unit Price'), $_smarty_tpl);
        ?>
</span>
										<small class="text-muted"><?php 
        echo Smarty::$_smarty_vars['capture']['TaxMethod'];
        ?>
</small>
									</th>
									<th class="text-center"><span class="title_box "><?php 
        echo smartyTranslate(array('s' => 'Qty'), $_smarty_tpl);
        ?>
</span></th>
									<?php 
        if ($_smarty_tpl->tpl_vars['display_warehouse']->value) {
            ?>
<th><span class="title_box "><?php 
            echo smartyTranslate(array('s' => 'Warehouse'), $_smarty_tpl);
            ?>
</span></th><?php 
        }
        ?>
									<?php 
        if ($_smarty_tpl->tpl_vars['order']->value->hasBeenPaid()) {
            ?>
<th class="text-center"><span class="title_box "><?php 
            echo smartyTranslate(array('s' => 'Refunded'), $_smarty_tpl);
            ?>
</span></th><?php 
        }
        ?>
									<?php 
        if ($_smarty_tpl->tpl_vars['order']->value->hasBeenDelivered() || $_smarty_tpl->tpl_vars['order']->value->hasProductReturned()) {
            ?>
										<th class="text-center"><span class="title_box "><?php 
            echo smartyTranslate(array('s' => 'Returned'), $_smarty_tpl);
            ?>
</span></th>
									<?php 
        }
        ?>
									<?php 
        if ($_smarty_tpl->tpl_vars['stock_management']->value) {
            ?>
<th class="text-center"><span class="title_box "><?php 
            echo smartyTranslate(array('s' => 'Available quantity'), $_smarty_tpl);
            ?>
</span></th><?php 
        }
        ?>
									<th>
										<span class="title_box "><?php 
        echo smartyTranslate(array('s' => 'Total'), $_smarty_tpl);
        ?>
</span>
										<small class="text-muted"><?php 
        echo Smarty::$_smarty_vars['capture']['TaxMethod'];
        ?>
</small>
									</th>
									<th style="display: none;" class="add_product_fields"></th>
									<th style="display: none;" class="edit_product_fields"></th>
									<th style="display: none;" class="standard_refund_fields">
										<i class="icon-minus-sign"></i>
										<?php 
        if ($_smarty_tpl->tpl_vars['order']->value->hasBeenDelivered() || $_smarty_tpl->tpl_vars['order']->value->hasBeenShipped()) {
            ?>
											<?php 
            echo smartyTranslate(array('s' => 'Return'), $_smarty_tpl);
            ?>

										<?php 
        } elseif ($_smarty_tpl->tpl_vars['order']->value->hasBeenPaid()) {
            ?>
											<?php 
            echo smartyTranslate(array('s' => 'Refund'), $_smarty_tpl);
            ?>

										<?php 
        } else {
            ?>
											<?php 
            echo smartyTranslate(array('s' => 'Cancel'), $_smarty_tpl);
            ?>

										<?php 
        }
        ?>
									</th>
									<th style="display:none" class="partial_refund_fields">
										<span class="title_box "><?php 
        echo smartyTranslate(array('s' => 'Partial refund'), $_smarty_tpl);
        ?>
</span>
									</th>
									<?php 
        if (!$_smarty_tpl->tpl_vars['order']->value->hasBeenDelivered()) {
            ?>
									<th></th>
									<?php 
        }
        ?>
								</tr>
							</thead>
							<tbody>
							<?php 
        $_smarty_tpl->tpl_vars['product'] = new Smarty_Variable();
        $_smarty_tpl->tpl_vars['product']->_loop = false;
        $_smarty_tpl->tpl_vars['k'] = new Smarty_Variable();
        $_from = $_smarty_tpl->tpl_vars['products']->value;
        if (!is_array($_from) && !is_object($_from)) {
            settype($_from, 'array');
        }
        foreach ($_from as $_smarty_tpl->tpl_vars['product']->key => $_smarty_tpl->tpl_vars['product']->value) {
            $_smarty_tpl->tpl_vars['product']->_loop = true;
            $_smarty_tpl->tpl_vars['k']->value = $_smarty_tpl->tpl_vars['product']->key;
            ?>
								
								<?php 
            /*  Call merged included template "controllers/orders/_customized_data.tpl" */
            $_tpl_stack[] = $_smarty_tpl;
            $_smarty_tpl = $_smarty_tpl->setupInlineSubTemplate('controllers/orders/_customized_data.tpl', $_smarty_tpl->cache_id, $_smarty_tpl->compile_id, 0, null, array(), 0, '2029977810555da72cbcc318-60413189');
            content_555da72d38de47_10184571($_smarty_tpl);
            $_smarty_tpl = array_pop($_tpl_stack);
            /*  End of included template "controllers/orders/_customized_data.tpl" */
            ?>
								
								<?php 
            /*  Call merged included template "controllers/orders/_product_line.tpl" */
            $_tpl_stack[] = $_smarty_tpl;
            $_smarty_tpl = $_smarty_tpl->setupInlineSubTemplate('controllers/orders/_product_line.tpl', $_smarty_tpl->cache_id, $_smarty_tpl->compile_id, 0, null, array(), 0, '2029977810555da72cbcc318-60413189');
            content_555da72d5599b6_01089697($_smarty_tpl);
            $_smarty_tpl = array_pop($_tpl_stack);
            /*  End of included template "controllers/orders/_product_line.tpl" */
            ?>
							<?php 
        }
        ?>
							<?php 
        if ($_smarty_tpl->tpl_vars['can_edit']->value) {
            ?>
								<?php 
            /*  Call merged included template "controllers/orders/_new_product.tpl" */
            $_tpl_stack[] = $_smarty_tpl;
            $_smarty_tpl = $_smarty_tpl->setupInlineSubTemplate('controllers/orders/_new_product.tpl', $_smarty_tpl->cache_id, $_smarty_tpl->compile_id, 0, null, array(), 0, '2029977810555da72cbcc318-60413189');
            content_555da72d6a9ac3_63298073($_smarty_tpl);
            $_smarty_tpl = array_pop($_tpl_stack);
            /*  End of included template "controllers/orders/_new_product.tpl" */
            ?>
							<?php 
        }
        ?>
							</tbody>
						</table>
					</div>

					<?php 
        if ($_smarty_tpl->tpl_vars['can_edit']->value) {
            ?>
					<div class="row-margin-bottom row-margin-top order_action">
					<?php 
            if (!$_smarty_tpl->tpl_vars['order']->value->hasBeenDelivered()) {
                ?>
						<button type="button" id="add_product" class="btn btn-default">
							<i class="icon-plus-sign"></i>
							<?php 
                echo smartyTranslate(array('s' => 'Add a product'), $_smarty_tpl);
                ?>

						</button>
					<?php 
            }
            ?>
						<button id="add_voucher" class="btn btn-default" type="button" >
							<i class="icon-ticket"></i>
							<?php 
            echo smartyTranslate(array('s' => 'Add a new discount'), $_smarty_tpl);
            ?>

						</button>
					</div>
					<?php 
        }
        ?>
					<div class="clear">&nbsp;</div>
					<div class="row">
						<div class="col-xs-6">
							<div class="alert alert-warning">
								<?php 
        echo smartyTranslate(array('s' => 'For this customer group, prices are displayed as: [1]%s[/1]', 'sprintf' => array(Smarty::$_smarty_vars['capture']['TaxMethod']), 'tags' => array('<strong>')), $_smarty_tpl);
        ?>

								<?php 
        if (!Configuration::get('PS_ORDER_RETURN')) {
            ?>
									<br/><strong><?php 
            echo smartyTranslate(array('s' => 'Merchandise returns are disabled'), $_smarty_tpl);
            ?>
</strong>
								<?php 
        }
        ?>
							</div>
						</div>
						<div class="col-xs-6">
							<div class="panel panel-vouchers" style="<?php 
        if (!sizeof($_smarty_tpl->tpl_vars['discounts']->value)) {
            ?>
display:none;<?php 
        }
        ?>
">
								<?php 
        if (sizeof($_smarty_tpl->tpl_vars['discounts']->value) || $_smarty_tpl->tpl_vars['can_edit']->value) {
            ?>
								<div class="table-responsive">
									<table class="table">
										<thead>
											<tr>
												<th>
													<span class="title_box ">
														<?php 
            echo smartyTranslate(array('s' => 'Discount name'), $_smarty_tpl);
            ?>

													</span>
												</th>
												<th>
													<span class="title_box ">
														<?php 
            echo smartyTranslate(array('s' => 'Value'), $_smarty_tpl);
            ?>

													</span>
												</th>
												<?php 
            if ($_smarty_tpl->tpl_vars['can_edit']->value) {
                ?>
												<th></th>
												<?php 
            }
            ?>
											</tr>
										</thead>
										<tbody>
											<?php 
            $_smarty_tpl->tpl_vars['discount'] = new Smarty_Variable();
            $_smarty_tpl->tpl_vars['discount']->_loop = false;
            $_from = $_smarty_tpl->tpl_vars['discounts']->value;
            if (!is_array($_from) && !is_object($_from)) {
                settype($_from, 'array');
            }
            foreach ($_from as $_smarty_tpl->tpl_vars['discount']->key => $_smarty_tpl->tpl_vars['discount']->value) {
                $_smarty_tpl->tpl_vars['discount']->_loop = true;
                ?>
											<tr>
												<td><?php 
                echo $_smarty_tpl->tpl_vars['discount']->value['name'];
                ?>
</td>
												<td>
												<?php 
                if ($_smarty_tpl->tpl_vars['discount']->value['value'] != 0.0) {
                    ?>
													-
												<?php 
                }
                ?>
												<?php 
                echo $_smarty_tpl->smarty->registered_plugins[Smarty::PLUGIN_FUNCTION]['displayPrice'][0][0]->displayPriceSmarty(array('price' => $_smarty_tpl->tpl_vars['discount']->value['value'], 'currency' => $_smarty_tpl->tpl_vars['currency']->value->id), $_smarty_tpl);
                ?>

												</td>
												<?php 
                if ($_smarty_tpl->tpl_vars['can_edit']->value) {
                    ?>
												<td>
													<a href="<?php 
                    echo $_smarty_tpl->tpl_vars['current_index']->value;
                    ?>
&amp;submitDeleteVoucher&amp;id_order_cart_rule=<?php 
                    echo $_smarty_tpl->tpl_vars['discount']->value['id_order_cart_rule'];
                    ?>
&amp;id_order=<?php 
                    echo $_smarty_tpl->tpl_vars['order']->value->id;
                    ?>
&amp;token=<?php 
                    echo htmlspecialchars($_GET['token'], ENT_QUOTES, 'UTF-8', true);
                    ?>
">
														<i class="icon-minus-sign"></i>
														<?php 
                    echo smartyTranslate(array('s' => 'Delete voucher'), $_smarty_tpl);
                    ?>

													</a>
												</td>
												<?php 
                }
                ?>
											</tr>
											<?php 
            }
            ?>
										</tbody>
									</table>
								</div>
								<div class="current-edit" id="voucher_form" style="display:none;">
									<?php 
            /*  Call merged included template "controllers/orders/_discount_form.tpl" */
            $_tpl_stack[] = $_smarty_tpl;
            $_smarty_tpl = $_smarty_tpl->setupInlineSubTemplate('controllers/orders/_discount_form.tpl', $_smarty_tpl->cache_id, $_smarty_tpl->compile_id, 0, null, array(), 0, '2029977810555da72cbcc318-60413189');
            content_555da72d728801_34299088($_smarty_tpl);
            $_smarty_tpl = array_pop($_tpl_stack);
            /*  End of included template "controllers/orders/_discount_form.tpl" */
            ?>
								</div>
								<?php 
        }
        ?>
							</div>
							<div class="panel panel-total">
								<div class="table-responsive">
									<table class="table">
										
										<?php 
        if ($_smarty_tpl->tpl_vars['order']->value->getTaxCalculationMethod() == @constant('PS_TAX_EXC')) {
            ?>
											<?php 
            $_smarty_tpl->tpl_vars['order_product_price'] = new Smarty_variable($_smarty_tpl->tpl_vars['order']->value->total_products, null, 0);
            ?>
											<?php 
            $_smarty_tpl->tpl_vars['order_discount_price'] = new Smarty_variable($_smarty_tpl->tpl_vars['order']->value->total_discounts_tax_excl, null, 0);
            ?>
											<?php 
            $_smarty_tpl->tpl_vars['order_wrapping_price'] = new Smarty_variable($_smarty_tpl->tpl_vars['order']->value->total_wrapping_tax_excl, null, 0);
            ?>
											<?php 
            $_smarty_tpl->tpl_vars['order_shipping_price'] = new Smarty_variable($_smarty_tpl->tpl_vars['order']->value->total_shipping_tax_excl, null, 0);
            ?>
										<?php 
        } else {
            ?>
											<?php 
            $_smarty_tpl->tpl_vars['order_product_price'] = new Smarty_variable($_smarty_tpl->tpl_vars['order']->value->total_products_wt, null, 0);
            ?>
											<?php 
            $_smarty_tpl->tpl_vars['order_discount_price'] = new Smarty_variable($_smarty_tpl->tpl_vars['order']->value->total_discounts_tax_incl, null, 0);
            ?>
											<?php 
            $_smarty_tpl->tpl_vars['order_wrapping_price'] = new Smarty_variable($_smarty_tpl->tpl_vars['order']->value->total_wrapping_tax_incl, null, 0);
            ?>
											<?php 
            $_smarty_tpl->tpl_vars['order_shipping_price'] = new Smarty_variable($_smarty_tpl->tpl_vars['order']->value->total_shipping_tax_incl, null, 0);
            ?>
										<?php 
        }
        ?>
										<tr id="total_products">
											<td class="text-right"><?php 
        echo smartyTranslate(array('s' => 'Products:'), $_smarty_tpl);
        ?>
</td>
											<td class="amount text-right nowrap">
												<?php 
        echo $_smarty_tpl->smarty->registered_plugins[Smarty::PLUGIN_FUNCTION]['displayPrice'][0][0]->displayPriceSmarty(array('price' => $_smarty_tpl->tpl_vars['order_product_price']->value, 'currency' => $_smarty_tpl->tpl_vars['currency']->value->id), $_smarty_tpl);
        ?>

											</td>
											<td class="partial_refund_fields current-edit" style="display:none;"></td>
										</tr>
										<tr id="total_discounts" <?php 
        if ($_smarty_tpl->tpl_vars['order']->value->total_discounts_tax_incl == 0) {
            ?>
style="display: none;"<?php 
        }
        ?>
>
											<td class="text-right"><?php 
        echo smartyTranslate(array('s' => 'Discounts'), $_smarty_tpl);
        ?>
</td>
											<td class="amount text-right nowrap">
												-<?php 
        echo $_smarty_tpl->smarty->registered_plugins[Smarty::PLUGIN_FUNCTION]['displayPrice'][0][0]->displayPriceSmarty(array('price' => $_smarty_tpl->tpl_vars['order_discount_price']->value, 'currency' => $_smarty_tpl->tpl_vars['currency']->value->id), $_smarty_tpl);
        ?>

											</td>
											<td class="partial_refund_fields current-edit" style="display:none;"></td>
										</tr>
										<tr id="total_wrapping" <?php 
        if ($_smarty_tpl->tpl_vars['order']->value->total_wrapping_tax_incl == 0) {
            ?>
style="display: none;"<?php 
        }
        ?>
>
											<td class="text-right"><?php 
        echo smartyTranslate(array('s' => 'Wrapping'), $_smarty_tpl);
        ?>
</td>
											<td class="amount text-right nowrap">
												<?php 
        echo $_smarty_tpl->smarty->registered_plugins[Smarty::PLUGIN_FUNCTION]['displayPrice'][0][0]->displayPriceSmarty(array('price' => $_smarty_tpl->tpl_vars['order_wrapping_price']->value, 'currency' => $_smarty_tpl->tpl_vars['currency']->value->id), $_smarty_tpl);
        ?>

											</td>
											<td class="partial_refund_fields current-edit" style="display:none;"></td>
										</tr>
										<tr id="total_shipping">
											<td class="text-right"><?php 
        echo smartyTranslate(array('s' => 'Shipping'), $_smarty_tpl);
        ?>
</td>
											<td class="amount text-right nowrap" >
												<?php 
        echo $_smarty_tpl->smarty->registered_plugins[Smarty::PLUGIN_FUNCTION]['displayPrice'][0][0]->displayPriceSmarty(array('price' => $_smarty_tpl->tpl_vars['order_shipping_price']->value, 'currency' => $_smarty_tpl->tpl_vars['currency']->value->id), $_smarty_tpl);
        ?>

											</td>
											<td class="partial_refund_fields current-edit" style="display:none;">
												<div class="input-group">
													<div class="input-group-addon">
														<?php 
        echo $_smarty_tpl->tpl_vars['currency']->value->prefix;
        ?>

														<?php 
        echo $_smarty_tpl->tpl_vars['currency']->value->suffix;
        ?>

													</div>
													<input type="text" name="partialRefundShippingCost" value="0" />
												</div>
												<p class="help-block"><i class="icon-warning-sign"></i> <?php 
        echo smartyTranslate(array('s' => '(%s)', 'sprintf' => Smarty::$_smarty_vars['capture']['TaxMethod']), $_smarty_tpl);
        ?>
</p>
											</td>
										</tr>
										<?php 
        if ($_smarty_tpl->tpl_vars['order']->value->getTaxCalculationMethod() == @constant('PS_TAX_EXC')) {
            ?>
			 							<tr id="total_taxes">
			 								<td class="text-right"><?php 
            echo smartyTranslate(array('s' => 'Taxes'), $_smarty_tpl);
            ?>
</td>
			 								<td class="amount text-right nowrap" ><?php 
            echo $_smarty_tpl->smarty->registered_plugins[Smarty::PLUGIN_FUNCTION]['displayPrice'][0][0]->displayPriceSmarty(array('price' => $_smarty_tpl->tpl_vars['order']->value->total_paid_tax_incl - $_smarty_tpl->tpl_vars['order']->value->total_paid_tax_excl, 'currency' => $_smarty_tpl->tpl_vars['currency']->value->id), $_smarty_tpl);
            ?>
</td>
			 								<td class="partial_refund_fields current-edit" style="display:none;"></td>
			 							</tr>
			 							<?php 
        }
        ?>
										<?php 
        $_smarty_tpl->tpl_vars['order_total_price'] = new Smarty_variable($_smarty_tpl->tpl_vars['order']->value->total_paid_tax_incl, null, 0);
        ?>
										<tr id="total_order">
											<td class="text-right"><strong><?php 
        echo smartyTranslate(array('s' => 'Total'), $_smarty_tpl);
        ?>
</strong></td>
											<td class="amount text-right nowrap">
												<strong><?php 
        echo $_smarty_tpl->smarty->registered_plugins[Smarty::PLUGIN_FUNCTION]['displayPrice'][0][0]->displayPriceSmarty(array('price' => $_smarty_tpl->tpl_vars['order_total_price']->value, 'currency' => $_smarty_tpl->tpl_vars['currency']->value->id), $_smarty_tpl);
        ?>
</strong>
											</td>
											<td class="partial_refund_fields current-edit" style="display:none;"></td>
										</tr>
									</table>
								</div>
							</div>
						</div>
					</div>
					<div style="display: none;" class="standard_refund_fields form-horizontal panel">
						<div class="form-group">
							<?php 
        if ($_smarty_tpl->tpl_vars['order']->value->hasBeenDelivered() && Configuration::get('PS_ORDER_RETURN')) {
            ?>
							<p class="checkbox">
								<label for="reinjectQuantities">
									<input type="checkbox" id="reinjectQuantities" name="reinjectQuantities" />
									<?php 
            echo smartyTranslate(array('s' => 'Re-stock products'), $_smarty_tpl);
            ?>

								</label>
							</p>
							<?php 
        }
        ?>
							<?php 
        if (!$_smarty_tpl->tpl_vars['order']->value->hasBeenDelivered() && $_smarty_tpl->tpl_vars['order']->value->hasBeenPaid() || $_smarty_tpl->tpl_vars['order']->value->hasBeenDelivered() && Configuration::get('PS_ORDER_RETURN')) {
            ?>
							<p class="checkbox">
								<label for="generateCreditSlip">
									<input type="checkbox" id="generateCreditSlip" name="generateCreditSlip" onclick="toggleShippingCost()" />
									<?php 
            echo smartyTranslate(array('s' => 'Generate a credit slip'), $_smarty_tpl);
            ?>

								</label>
							</p>
							<p class="checkbox">
								<label for="generateDiscount">
									<input type="checkbox" id="generateDiscount" name="generateDiscount" onclick="toggleShippingCost()" />
									<?php 
            echo smartyTranslate(array('s' => 'Generate a voucher'), $_smarty_tpl);
            ?>

								</label>
							</p>
							<p class="checkbox" id="spanShippingBack" style="display:none;">
								<label for="shippingBack">
									<input type="checkbox" id="shippingBack" name="shippingBack" />
									<?php 
            echo smartyTranslate(array('s' => 'Repay shipping costs'), $_smarty_tpl);
            ?>

								</label>
							</p>
							<?php 
            if ($_smarty_tpl->tpl_vars['order']->value->total_discounts_tax_excl > 0 || $_smarty_tpl->tpl_vars['order']->value->total_discounts_tax_incl > 0) {
                ?>
							<br/><p><?php 
                echo smartyTranslate(array('s' => 'This order has been partially paid by voucher. Choose the amount you want to refund:'), $_smarty_tpl);
                ?>
</p>
							<p class="radio">
								<label id="lab_refund_total_1" for="refund_total_1">
									<input type="radio" value="0" name="refund_total_voucher_off" id="refund_total_1" checked="checked" />
									<?php 
                echo smartyTranslate(array('s' => 'Include amount of initial voucher: '), $_smarty_tpl);
                ?>

								</label>
							</p>
							<p class="radio">
								<label id="lab_refund_total_2" for="refund_total_2">
									<input type="radio" value="1" name="refund_total_voucher_off" id="refund_total_2"/>
									<?php 
                echo smartyTranslate(array('s' => 'Exclude amount of initial voucher: '), $_smarty_tpl);
                ?>

								</label>
							</p>
							<div class="nowrap radio-inline">
								<label id="lab_refund_total_3" class="pull-left" for="refund_total_3">
									<?php 
                echo smartyTranslate(array('s' => 'Amount of your choice: '), $_smarty_tpl);
                ?>

									<input type="radio" value="2" name="refund_total_voucher_off" id="refund_total_3"/>
								</label>
								<div class="input-group col-lg-1 pull-left">
									<div class="input-group-addon">
										<?php 
                echo $_smarty_tpl->tpl_vars['currency']->value->prefix;
                ?>

										<?php 
                echo $_smarty_tpl->tpl_vars['currency']->value->suffix;
                ?>

									</div>
									<input type="text" class="input fixed-width-md" name="refund_total_voucher_choose" value="0"/>
								</div>
							</div>
							<?php 
            }
            ?>
						<?php 
        }
        ?>
						</div>
						<?php 
        if (!$_smarty_tpl->tpl_vars['order']->value->hasBeenDelivered() || $_smarty_tpl->tpl_vars['order']->value->hasBeenDelivered() && Configuration::get('PS_ORDER_RETURN')) {
            ?>
						<div class="row">
							<input type="submit" name="cancelProduct" value="<?php 
            if ($_smarty_tpl->tpl_vars['order']->value->hasBeenDelivered()) {
                echo smartyTranslate(array('s' => 'Return products'), $_smarty_tpl);
            } elseif ($_smarty_tpl->tpl_vars['order']->value->hasBeenPaid()) {
                echo smartyTranslate(array('s' => 'Refund products'), $_smarty_tpl);
            } else {
                echo smartyTranslate(array('s' => 'Cancel products'), $_smarty_tpl);
            }
            ?>
" class="btn btn-default" />
						</div>
						<?php 
        }
        ?>
					</div>
					<div style="display:none;" class="partial_refund_fields">
						<p class="checkbox">
							<label for="reinjectQuantitiesRefund">
								<input type="checkbox" id="reinjectQuantitiesRefund" name="reinjectQuantities" />
								<?php 
        echo smartyTranslate(array('s' => 'Re-stock products'), $_smarty_tpl);
        ?>

							</label>
						</p>
						<p class="checkbox">
							<label for="generateDiscountRefund">
								<input type="checkbox" id="generateDiscountRefund" name="generateDiscountRefund" onclick="toggleShippingCost()" />
								<?php 
        echo smartyTranslate(array('s' => 'Generate a voucher'), $_smarty_tpl);
        ?>

							</label>
						</p>
						<?php 
        if ($_smarty_tpl->tpl_vars['order']->value->total_discounts_tax_excl > 0 || $_smarty_tpl->tpl_vars['order']->value->total_discounts_tax_incl > 0) {
            ?>
						<p><?php 
            echo smartyTranslate(array('s' => 'This order has been partially paid by voucher. Choose the amount you want to refund:'), $_smarty_tpl);
            ?>
</p>
						<p class="radio">
							<label id="lab_refund_1" for="refund_1">
								<input type="radio" value="0" name="refund_voucher_off" id="refund_1" checked="checked" />
								<?php 
            echo smartyTranslate(array('s' => 'Product(s) price: '), $_smarty_tpl);
            ?>

							</label>
						</p>
						<p class="radio">
							<label id="lab_refund_2" for="refund_2">
								<input type="radio" value="1" name="refund_voucher_off" id="refund_2"/>
								<?php 
            echo smartyTranslate(array('s' => 'Product(s) price, excluding amount of initial voucher: '), $_smarty_tpl);
            ?>

							</label>
						</p>
						<div class="nowrap radio-inline">
								<label id="lab_refund_3" class="pull-left" for="refund_3">
									<?php 
            echo smartyTranslate(array('s' => 'Amount of your choice: '), $_smarty_tpl);
            ?>

									<input type="radio" value="2" name="refund_voucher_off" id="refund_3"/>
								</label>
								<div class="input-group col-lg-1 pull-left">
									<div class="input-group-addon">
										<?php 
            echo $_smarty_tpl->tpl_vars['currency']->value->prefix;
            ?>

										<?php 
            echo $_smarty_tpl->tpl_vars['currency']->value->suffix;
            ?>

									</div>
									<input type="text" class="input fixed-width-md" name="refund_voucher_choose" value="0"/>
								</div>
							</div>
						<?php 
        }
        ?>
						<br/>
						<button type="submit" name="partialRefund" class="btn btn-default">
							<i class="icon-check"></i> <?php 
        echo smartyTranslate(array('s' => 'Partial refund'), $_smarty_tpl);
        ?>

						</button>
					</div>
				</div>
			</form>
		</div>
	</div>

	<div class="row">
		<div class="col-lg-12">
			<!-- Sources block -->
			<?php 
        if (sizeof($_smarty_tpl->tpl_vars['sources']->value)) {
            ?>
			<div class="panel">
				<div class="panel-heading">
					<i class="icon-globe"></i>
					<?php 
            echo smartyTranslate(array('s' => 'Sources'), $_smarty_tpl);
            ?>
 <span class="badge"><?php 
            echo count($_smarty_tpl->tpl_vars['sources']->value);
            ?>
</span>
				</div>
				<ul <?php 
            if (sizeof($_smarty_tpl->tpl_vars['sources']->value) > 3) {
                ?>
style="height: 200px; overflow-y: scroll;"<?php 
            }
            ?>
>
				<?php 
            $_smarty_tpl->tpl_vars['source'] = new Smarty_Variable();
            $_smarty_tpl->tpl_vars['source']->_loop = false;
            $_from = $_smarty_tpl->tpl_vars['sources']->value;
            if (!is_array($_from) && !is_object($_from)) {
                settype($_from, 'array');
            }
            foreach ($_from as $_smarty_tpl->tpl_vars['source']->key => $_smarty_tpl->tpl_vars['source']->value) {
                $_smarty_tpl->tpl_vars['source']->_loop = true;
                ?>
					<li>
						<?php 
                echo $_smarty_tpl->smarty->registered_plugins[Smarty::PLUGIN_FUNCTION]['dateFormat'][0][0]->dateFormat(array('date' => $_smarty_tpl->tpl_vars['source']->value['date_add'], 'full' => true), $_smarty_tpl);
                ?>
<br />
						<b><?php 
                echo smartyTranslate(array('s' => 'From'), $_smarty_tpl);
                ?>
</b><?php 
                if ($_smarty_tpl->tpl_vars['source']->value['http_referer'] != '') {
                    ?>
<a href="<?php 
                    echo $_smarty_tpl->tpl_vars['source']->value['http_referer'];
                    ?>
"><?php 
                    echo smarty_modifier_regex_replace(parse_url($_smarty_tpl->tpl_vars['source']->value['http_referer'], @constant('PHP_URL_HOST')), '/^www./', '');
                    ?>
</a><?php 
                } else {
                    ?>
-<?php 
                }
                ?>
<br />
						<b><?php 
                echo smartyTranslate(array('s' => 'To'), $_smarty_tpl);
                ?>
</b> <a href="http://<?php 
                echo $_smarty_tpl->tpl_vars['source']->value['request_uri'];
                ?>
"><?php 
                echo $_smarty_tpl->smarty->registered_plugins[Smarty::PLUGIN_MODIFIER]['truncate'][0][0]->smarty_modifier_truncate($_smarty_tpl->tpl_vars['source']->value['request_uri'], 100, '...');
                ?>
</a><br />
						<?php 
                if ($_smarty_tpl->tpl_vars['source']->value['keywords']) {
                    ?>
<b><?php 
                    echo smartyTranslate(array('s' => 'Keywords'), $_smarty_tpl);
                    ?>
</b> <?php 
                    echo $_smarty_tpl->tpl_vars['source']->value['keywords'];
                    ?>
<br /><?php 
                }
                ?>
<br />
					</li>
				<?php 
            }
            ?>
				</ul>
			</div>
			<?php 
        }
        ?>

			<!-- linked orders block -->
			<?php 
        if (count($_smarty_tpl->tpl_vars['order']->value->getBrother()) > 0) {
            ?>
			<div class="panel">
				<div class="panel-heading">
					<i class="icon-cart"></i>
					<?php 
            echo smartyTranslate(array('s' => 'Linked orders'), $_smarty_tpl);
            ?>

				</div>
				<div class="table-responsive">
					<table class="table">
						<thead>
							<tr>
								<th>
									<?php 
            echo smartyTranslate(array('s' => 'Order no. '), $_smarty_tpl);
            ?>

								</th>
								<th>
									<?php 
            echo smartyTranslate(array('s' => 'Status'), $_smarty_tpl);
            ?>

								</th>
								<th>
									<?php 
            echo smartyTranslate(array('s' => 'Amount'), $_smarty_tpl);
            ?>

								</th>
								<th></th>
							</tr>
						</thead>
						<tbody>
							<?php 
            $_smarty_tpl->tpl_vars['brother_order'] = new Smarty_Variable();
            $_smarty_tpl->tpl_vars['brother_order']->_loop = false;
            $_from = $_smarty_tpl->tpl_vars['order']->value->getBrother();
            if (!is_array($_from) && !is_object($_from)) {
                settype($_from, 'array');
            }
            $_smarty_tpl->tpl_vars['brother_order']->index = -1;
            foreach ($_from as $_smarty_tpl->tpl_vars['brother_order']->key => $_smarty_tpl->tpl_vars['brother_order']->value) {
                $_smarty_tpl->tpl_vars['brother_order']->_loop = true;
                $_smarty_tpl->tpl_vars['brother_order']->index++;
                $_smarty_tpl->tpl_vars['brother_order']->first = $_smarty_tpl->tpl_vars['brother_order']->index === 0;
                ?>
							<tr>
								<td>
									<a href="<?php 
                echo $_smarty_tpl->tpl_vars['current_index']->value;
                ?>
&amp;vieworder&amp;id_order=<?php 
                echo $_smarty_tpl->tpl_vars['brother_order']->value->id;
                ?>
&amp;token=<?php 
                echo htmlspecialchars($_GET['token'], ENT_QUOTES, 'UTF-8', true);
                ?>
">#<?php 
                echo $_smarty_tpl->tpl_vars['brother_order']->value->id;
                ?>
</a>
								</td>
								<td>
									<?php 
                echo $_smarty_tpl->tpl_vars['brother_order']->value->getCurrentOrderState()->name[$_smarty_tpl->tpl_vars['current_id_lang']->value];
                ?>

								</td>
								<td>
									<?php 
                echo $_smarty_tpl->smarty->registered_plugins[Smarty::PLUGIN_FUNCTION]['displayPrice'][0][0]->displayPriceSmarty(array('price' => $_smarty_tpl->tpl_vars['brother_order']->value->total_paid_tax_incl, 'currency' => $_smarty_tpl->tpl_vars['currency']->value->id), $_smarty_tpl);
                ?>

								</td>
								<td>
									<a href="<?php 
                echo $_smarty_tpl->tpl_vars['current_index']->value;
                ?>
&amp;vieworder&amp;id_order=<?php 
                echo $_smarty_tpl->tpl_vars['brother_order']->value->id;
                ?>
&amp;token=<?php 
                echo htmlspecialchars($_GET['token'], ENT_QUOTES, 'UTF-8', true);
                ?>
">
										<i class="icon-eye-open"></i>
										<?php 
                echo smartyTranslate(array('s' => 'See the order'), $_smarty_tpl);
                ?>

									</a>
								</td>
							</tr>
							<?php 
            }
            ?>
						</tbody>
					</table>
				</div>
			</div>
			<?php 
        }
        ?>
		</div>
	</div>

	<script type="text/javascript">
		var geocoder = new google.maps.Geocoder();
		var delivery_map, invoice_map;

		$(document).ready(function()
		{
			$(".textarea-autosize").autosize();

			geocoder.geocode({
				address: '<?php 
        echo addcslashes($_smarty_tpl->tpl_vars['addresses']->value['delivery']->address1, '\'');
        ?>
,<?php 
        echo addcslashes($_smarty_tpl->tpl_vars['addresses']->value['delivery']->postcode, '\'');
        ?>
,<?php 
        echo addcslashes($_smarty_tpl->tpl_vars['addresses']->value['delivery']->city, '\'');
        if (isset($_smarty_tpl->tpl_vars['addresses']->value['deliveryState']->name) && $_smarty_tpl->tpl_vars['addresses']->value['delivery']->id_state) {
            ?>
,<?php 
            echo addcslashes($_smarty_tpl->tpl_vars['addresses']->value['deliveryState']->name, '\'');
        }
        ?>
,<?php 
        echo addcslashes($_smarty_tpl->tpl_vars['addresses']->value['delivery']->country, '\'');
        ?>
'
				}, function(results, status) {
				if (status === google.maps.GeocoderStatus.OK)
				{
					delivery_map = new google.maps.Map(document.getElementById('map-delivery-canvas'), {
						zoom: 10,
						mapTypeId: google.maps.MapTypeId.ROADMAP,
						center: results[0].geometry.location
					});
					var delivery_marker = new google.maps.Marker({
						map: delivery_map,
						position: results[0].geometry.location,
						url: 'http://maps.google.com?q=<?php 
        echo urlencode($_smarty_tpl->tpl_vars['addresses']->value['delivery']->address1);
        ?>
,<?php 
        echo urlencode($_smarty_tpl->tpl_vars['addresses']->value['delivery']->postcode);
        ?>
,<?php 
        echo urlencode($_smarty_tpl->tpl_vars['addresses']->value['delivery']->city);
        if (isset($_smarty_tpl->tpl_vars['addresses']->value['deliveryState']->name) && $_smarty_tpl->tpl_vars['addresses']->value['delivery']->id_state) {
            ?>
,<?php 
            echo urlencode($_smarty_tpl->tpl_vars['addresses']->value['deliveryState']->name);
        }
        ?>
,<?php 
        echo urlencode($_smarty_tpl->tpl_vars['addresses']->value['delivery']->country);
        ?>
'
					});
					google.maps.event.addListener(delivery_marker, 'click', function() {
						window.open(delivery_marker.url);
					});
				}
			});

			geocoder.geocode({
				address: '<?php 
        echo addcslashes($_smarty_tpl->tpl_vars['addresses']->value['invoice']->address1, '\'');
        ?>
,<?php 
        echo addcslashes($_smarty_tpl->tpl_vars['addresses']->value['invoice']->postcode, '\'');
        ?>
,<?php 
        echo addcslashes($_smarty_tpl->tpl_vars['addresses']->value['invoice']->city, '\'');
        if (isset($_smarty_tpl->tpl_vars['addresses']->value['deliveryState']->name) && $_smarty_tpl->tpl_vars['addresses']->value['invoice']->id_state) {
            ?>
,<?php 
            echo addcslashes($_smarty_tpl->tpl_vars['addresses']->value['deliveryState']->name, '\'');
        }
        ?>
,<?php 
        echo addcslashes($_smarty_tpl->tpl_vars['addresses']->value['invoice']->country, '\'');
        ?>
'
				}, function(results, status) {
				if (status === google.maps.GeocoderStatus.OK)
				{
					invoice_map = new google.maps.Map(document.getElementById('map-invoice-canvas'), {
						zoom: 10,
						mapTypeId: google.maps.MapTypeId.ROADMAP,
						center: results[0].geometry.location
					});
					invoice_marker = new google.maps.Marker({
						map: invoice_map,
						position: results[0].geometry.location,
						url: 'http://maps.google.com?q=<?php 
        echo urlencode($_smarty_tpl->tpl_vars['addresses']->value['invoice']->address1);
        ?>
,<?php 
        echo urlencode($_smarty_tpl->tpl_vars['addresses']->value['invoice']->postcode);
        ?>
,<?php 
        echo urlencode($_smarty_tpl->tpl_vars['addresses']->value['invoice']->city);
        if (isset($_smarty_tpl->tpl_vars['addresses']->value['deliveryState']->name) && $_smarty_tpl->tpl_vars['addresses']->value['invoice']->id_state) {
            ?>
,<?php 
            echo urlencode($_smarty_tpl->tpl_vars['addresses']->value['deliveryState']->name);
        }
        ?>
,<?php 
        echo urlencode($_smarty_tpl->tpl_vars['addresses']->value['invoice']->country);
        ?>
'
					});
					google.maps.event.addListener(invoice_marker, 'click', function() {
						window.open(invoice_marker.url);
					});
				}
			});

			var date = new Date();
			var hours = date.getHours();
			if (hours < 10)
				hours = "0" + hours;
			var mins = date.getMinutes();
			if (mins < 10)
				mins = "0" + mins;
			var secs = date.getSeconds();
			if (secs < 10)
				secs = "0" + secs;

			$('.datepicker').datetimepicker({
				prevText: '',
				nextText: '',
				dateFormat: 'yy-mm-dd ' + hours + ':' + mins + ':' + secs
			});
		});

		// Fix wrong maps center when map is hidden
		$('#tabAddresses').click(function(){
			x = delivery_map.getZoom();
			c = delivery_map.getCenter();
			google.maps.event.trigger(delivery_map, 'resize');
			delivery_map.setZoom(x);
			delivery_map.setCenter(c);

			x = invoice_map.getZoom();
			c = invoice_map.getCenter();
			google.maps.event.trigger(invoice_map, 'resize');
			invoice_map.setZoom(x);
			invoice_map.setCenter(c);
		});
	</script>



<?php 
        echo $_smarty_tpl->smarty->registered_plugins[Smarty::PLUGIN_FUNCTION]['hook'][0][0]->smartyHook(array('h' => 'displayAdminView'), $_smarty_tpl);
        ?>

<?php 
        if (isset($_smarty_tpl->tpl_vars['name_controller']->value)) {
            ?>
	<?php 
            $_smarty_tpl->_capture_stack[0][] = array('hookName', 'hookName', null);
            ob_start();
            ?>
display<?php 
            echo ucfirst($_smarty_tpl->tpl_vars['name_controller']->value);
            ?>
View<?php 
            list($_capture_buffer, $_capture_assign, $_capture_append) = array_pop($_smarty_tpl->_capture_stack[0]);
            if (!empty($_capture_buffer)) {
                if (isset($_capture_assign)) {
                    $_smarty_tpl->assign($_capture_assign, ob_get_contents());
                }
                if (isset($_capture_append)) {
                    $_smarty_tpl->append($_capture_append, ob_get_contents());
                }
                Smarty::$_smarty_vars['capture'][$_capture_buffer] = ob_get_clean();
            } else {
                $_smarty_tpl->capture_error();
            }
            ?>
	<?php 
            echo $_smarty_tpl->smarty->registered_plugins[Smarty::PLUGIN_FUNCTION]['hook'][0][0]->smartyHook(array('h' => $_smarty_tpl->tpl_vars['hookName']->value), $_smarty_tpl);
            ?>

<?php 
        } elseif (isset($_GET['controller'])) {
            ?>
	<?php 
            $_smarty_tpl->_capture_stack[0][] = array('hookName', 'hookName', null);
            ob_start();
            ?>
display<?php 
            echo htmlentities(ucfirst($_GET['controller']));
            ?>
View<?php 
            list($_capture_buffer, $_capture_assign, $_capture_append) = array_pop($_smarty_tpl->_capture_stack[0]);
            if (!empty($_capture_buffer)) {
                if (isset($_capture_assign)) {
                    $_smarty_tpl->assign($_capture_assign, ob_get_contents());
                }
                if (isset($_capture_append)) {
                    $_smarty_tpl->append($_capture_append, ob_get_contents());
                }
                Smarty::$_smarty_vars['capture'][$_capture_buffer] = ob_get_clean();
            } else {
                $_smarty_tpl->capture_error();
            }
            ?>
	<?php 
            echo $_smarty_tpl->smarty->registered_plugins[Smarty::PLUGIN_FUNCTION]['hook'][0][0]->smartyHook(array('h' => $_smarty_tpl->tpl_vars['hookName']->value), $_smarty_tpl);
            ?>

<?php 
        }
    }
     } else {
         $ppec->displayPayPalAPIError($ppec->l('Error during the prepration of the express checkout payment'), $ppec->logs);
     }
 } elseif (!empty($ppec->token) && $ppec->token == Tools::getValue('token') && ($ppec->payer_id = Tools::getValue('PayerID'))) {
     // Get payment infos from paypal
     $ppec->getExpressCheckout();
     if ($ppec->hasSucceedRequest() && !empty($ppec->token)) {
         $address = null;
         $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');
 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 addOrder(ShopgateOrder $order)
 {
     $this->log("PS start add_order", ShopgateLogger::LOGTYPE_DEBUG);
     $shopgateOrder = PSShopgateOrder::instanceByOrderNumber($order->getOrderNumber());
     if ($shopgateOrder->id) {
         throw new ShopgateLibraryException(ShopgateLibraryException::PLUGIN_DUPLICATE_ORDER, 'external_order_id: ' . $shopgateOrder->id_order, true);
     }
     $comments = array();
     // generate products array
     $products = $this->insertOrderItems($order);
     //Get or create customer
     $id_customer = Customer::customerExists($order->getMail(), true, false);
     $customer = new Customer($id_customer ? $id_customer : (int) $order->getExternalCustomerId());
     if (!$customer->id) {
         $customer = $this->createCustomer($customer, $order);
     }
     // prepare addresses: company has to be shorten. add mobile phone / telephone
     $this->prepareAddresses($order);
     //Get invoice and delivery addresses
     $invoiceAddress = $this->getPSAddress($customer, $order->getInvoiceAddress());
     $deliveryAddress = $order->getInvoiceAddress() == $order->getDeliveryAddress() ? $invoiceAddress : $this->getPSAddress($customer, $order->getDeliveryAddress());
     //Creating currency
     $this->log("PS setting currency", ShopgateLogger::LOGTYPE_DEBUG);
     $id_currency = $order->getCurrency() ? Currency::getIdByIsoCode($order->getCurrency()) : $this->id_currency;
     $currency = new Currency($id_currency ? $id_currency : $this->id_currency);
     //Creating new cart
     $this->log("PS set cart variables", ShopgateLogger::LOGTYPE_DEBUG);
     $cart = new Cart();
     $cart->id_lang = $this->id_lang;
     $cart->id_currency = $currency->id;
     $cart->id_address_delivery = $deliveryAddress->id;
     $cart->id_address_invoice = $invoiceAddress->id;
     $cart->id_customer = $customer->id;
     if (version_compare(_PS_VERSION_, '1.4.1.0', '>=')) {
         // id_guest is a connection to a ps_guest entry which includes screen width etc.
         // is_guest field only exists in Prestashop 1.4.1.0 and higher
         $cart->id_guest = $customer->is_guest;
     }
     $cart->recyclable = 0;
     $cart->gift = 0;
     $cart->id_carrier = (int) Configuration::get('SHOPGATE_CARRIER_ID');
     $cart->secure_key = $customer->secure_key;
     $this->log("PS try to create cart", ShopgateLogger::LOGTYPE_DEBUG);
     if (!$cart->add()) {
         throw new ShopgateLibraryException(ShopgateLibraryException::PLUGIN_DATABASE_ERROR, 'Unable to create cart', true);
     }
     //Adding items to cart
     $this->log("PS adding items to cart", ShopgateLogger::LOGTYPE_DEBUG);
     foreach ($products as $p) {
         $this->log("PS cart updateQty product id: " . $p['id_product'], ShopgateLogger::LOGTYPE_DEBUG);
         $this->log("PS cart updateQty product quantity: " . $p['quantity'], ShopgateLogger::LOGTYPE_DEBUG);
         $this->log("PS cart updateQty product quantity_difference: " . $p['quantity_difference'], ShopgateLogger::LOGTYPE_DEBUG);
         $this->log("PS cart updateQty product id_product_attribute: " . $p['id_product_attribute'], ShopgateLogger::LOGTYPE_DEBUG);
         $this->log("PS cart updateQty product delivery address: " . $deliveryAddress->id, ShopgateLogger::LOGTYPE_DEBUG);
         //TODO deal with customizations
         $id_customization = false;
         if ($p['quantity'] - $p['quantity_difference'] > 0) {
             // only if the result of $p['quantity'] - $p['quantity_difference'] is higher then 0
             $cart->updateQty($p['quantity'] - $p['quantity_difference'], $p['id_product'], $p['id_product_attribute'], $id_customization, 'up', $deliveryAddress->id);
         }
         if ($p['quantity_difference'] > 0) {
             $this->log("PS try to add cart message ", ShopgateLogger::LOGTYPE_DEBUG);
             $message = new Message();
             $message->id_cart = $cart->id;
             $message->private = 1;
             $message->message = 'Warning, wanted quantity for product "' . $p['name'] . '" was ' . $p['quantity'] . ' unit(s), however, the amount in stock is ' . $p['quantity_in_stock'] . ' unit(s). Only ' . $p['quantity_in_stock'] . ' unit(s) were added to the order';
             $message->save();
         }
     }
     $id_order_state = 0;
     $shopgate = new Shopgate();
     $payment_name = $shopgate->getTranslation('Mobile Payment');
     $this->log("PS map payment method", ShopgateLogger::LOGTYPE_DEBUG);
     if (!$order->getIsShippingBlocked()) {
         $id_order_state = $this->getOrderStateId('PS_OS_PREPARATION');
         switch ($order->getPaymentMethod()) {
             case 'SHOPGATE':
                 $payment_name = $shopgate->getTranslation('Shopgate');
                 break;
             case 'PREPAY':
                 $payment_name = $shopgate->getTranslation('Bankwire');
                 $id_order_state = $this->getOrderStateId('PS_OS_BANKWIRE');
                 break;
             case 'COD':
                 $payment_name = $shopgate->getTranslation('Cash on Delivery');
                 break;
             case 'PAYPAL':
                 $payment_name = $shopgate->getTranslation('PayPal');
                 break;
             default:
                 break;
         }
     } else {
         $id_order_state = $this->getOrderStateId('PS_OS_SHOPGATE');
         switch ($order->getPaymentMethod()) {
             case 'SHOPGATE':
                 $payment_name = $shopgate->getTranslation('Shopgate');
                 break;
             case 'PREPAY':
                 $payment_name = $shopgate->getTranslation('Bankwire');
                 break;
             case 'COD':
                 $payment_name = $shopgate->getTranslation('Cash on Delivery');
                 break;
             case 'PAYPAL':
                 $id_order_state = $this->getOrderStateId('PS_OS_PAYPAL');
                 $payment_name = $shopgate->getTranslation('PayPal');
                 break;
             default:
                 $id_order_state = $this->getOrderStateId('PS_OS_SHOPGATE');
                 break;
         }
     }
     $shippingCosts = $order->getAmountShipping() + $order->getAmountShopPayment();
     //Creates shopgate order record and save shipping cost for future use
     $this->log("PS set PSShopgateOrder object variables", ShopgateLogger::LOGTYPE_DEBUG);
     $shopgateOrder = new PSShopgateOrder();
     $shopgateOrder->order_number = $order->getOrderNumber();
     $shopgateOrder->shipping_cost = $shippingCosts;
     $shopgateOrder->shipping_service = Configuration::get('SHOPGATE_SHIPPING_SERVICE');
     $shopgateOrder->id_cart = $cart->id;
     $shopgateOrder->shop_number = $this->config->getShopNumber();
     $shopgateOrder->comments = $this->jsonEncode($comments);
     if (version_compare(_PS_VERSION_, '1.4.0.2', '<')) {
         $this->log("PS lower 1.4.0.2: ", ShopgateLogger::LOGTYPE_DEBUG);
         // Fix: sets in database ps_delivery all zones of passed shippingCosts
         $this->setShippingCosts(0);
     }
     $this->log("PS try creating PSShopgateOrder object", ShopgateLogger::LOGTYPE_DEBUG);
     if (!$shopgateOrder->add()) {
         throw new ShopgateLibraryException(ShopgateLibraryException::PLUGIN_DATABASE_ERROR, 'Unable to create shopgate order', true);
     }
     //PS 1.5 compatibility
     if (version_compare(_PS_VERSION_, '1.5.0.0', '>=')) {
         $this->log("PS 1.5.x.x: set cart context", ShopgateLogger::LOGTYPE_DEBUG);
         $this->context = Context::getContext();
         $this->context->cart = $cart;
         $this->log("PS 1.5.x.x: \$cart->setDeliveryOption(array(\$cart->id_address_delivery => \$cart->id_carrier.','))\n\n==============", ShopgateLogger::LOGTYPE_DEBUG);
         $cart->setDeliveryOption(array($cart->id_address_delivery => $cart->id_carrier . ','));
         $this->log("PS 1.5.x.x: \$cart->update()", ShopgateLogger::LOGTYPE_DEBUG);
         $cart->update();
         $cart->id_carrier = (int) Configuration::get('SHOPGATE_CARRIER_ID');
     }
     $amountPaid = $order->getAmountComplete();
     if (version_compare(_PS_VERSION_, '1.4.0.2', '<')) {
         // substract the shipping costs.
         $amountPaid -= $shippingCosts;
     }
     $this->log("\$shopgate->validateOrder(\$cart->id, \$id_order_state, \$amountPaid, \$payment_name, NULL, array(), NULL, false, \$cart->secure_key", ShopgateLogger::LOGTYPE_DEBUG);
     $this->log("\$cart->id = " . var_export($cart->id, true) . "\n\$id_order_state = " . var_export($id_order_state, true) . "\n\$amountPaid = " . var_export($amountPaid, true) . "\n\$payment_name = " . var_export($payment_name, true) . "\n\$cart->secure_key" . var_export($cart->secure_key, true) . "\n==============", ShopgateLogger::LOGTYPE_DEBUG);
     try {
         $shopgate->validateOrder($cart->id, $id_order_state, $amountPaid, $payment_name, NULL, array(), NULL, false, $cart->secure_key);
     } catch (Swift_Message_MimeException $ex) {
         $this->log("\$shopgate->validateOrder(\$cart->id, \$id_order_state, \$amountPaid, \$payment_name, NULL, array(), NULL, false, \$cart->secure_key) FAILED with Swift_Message_MimeException", ShopgateLogger::LOGTYPE_ERROR);
         // catch Exception if there is a problem with sending mails
     }
     if (version_compare(_PS_VERSION_, '1.4.0.2', '<') && (int) $shopgate->currentOrder > 0) {
         $this->log("PS < 1.4.0.2: update shipping and payment cost", ShopgateLogger::LOGTYPE_DEBUG);
         // in versions below 1.4.0.2 the shipping and payment costs must be updated after the order
         $updateShopgateOrder = new Order($shopgate->currentOrder);
         $updateShopgateOrder->total_paid = $order->getAmountComplete();
         $updateShopgateOrder->total_paid_real = $order->getAmountComplete();
         $updateShopgateOrder->total_products_wt = $order->getAmountItems();
         $updateShopgateOrder->total_shipping = $order->getAmountShipping() + $order->getAmountShopPayment();
         $updateShopgateOrder->update();
     }
     if ((int) $shopgate->currentOrder > 0) {
         $this->log("\$shopgateOrder->update()", ShopgateLogger::LOGTYPE_DEBUG);
         $shopgateOrder->id_order = $shopgate->currentOrder;
         $shopgateOrder->update();
         return array('external_order_id' => $shopgate->currentOrder, 'external_order_number' => $shopgate->currentOrder);
     } else {
         $this->log("\$shopgateOrder->delete()", ShopgateLogger::LOGTYPE_DEBUG);
         $shopgateOrder->delete();
         throw new ShopgateLibraryException(ShopgateLibraryException::PLUGIN_DATABASE_ERROR, 'Unable to create order', true);
     }
 }
Exemple #29
0
 public function addressImport()
 {
     $this->receiveTab();
     $defaultLanguageId = (int) Configuration::get('PS_LANG_DEFAULT');
     $handle = $this->openCsvFile();
     self::setLocale();
     for ($current_line = 0; $line = fgetcsv($handle, MAX_LINE_SIZE, Tools::getValue('separator')); $current_line++) {
         if (Tools::getValue('convert')) {
             $line = $this->utf8_encode_array($line);
         }
         $info = self::getMaskedRow($line);
         self::setDefaultValues($info);
         $address = new Address();
         self::array_walk($info, array('AdminImport', 'fillInfo'), $address);
         if (isset($address->country) and is_numeric($address->country)) {
             if (Country::getNameById(Configuration::get('PS_LANG_DEFAULT'), (int) $address->country)) {
                 $address->id_country = (int) $address->country;
             }
         } elseif (isset($address->country) and is_string($address->country) and !empty($address->country)) {
             if ($id_country = Country::getIdByName(NULL, $address->country)) {
                 $address->id_country = (int) $id_country;
             } else {
                 $country = new Country();
                 $country->active = 1;
                 $country->name = self::createMultiLangField($address->country);
                 $country->id_zone = 0;
                 // Default zone for country to create
                 $country->iso_code = strtoupper(substr($address->country, 0, 2));
                 // Default iso for country to create
                 $country->contains_states = 0;
                 // Default value for country to create
                 $langFieldError = $country->validateFieldsLang(UNFRIENDLY_ERROR, true);
                 if (($fieldError = $country->validateFields(UNFRIENDLY_ERROR, true)) === true and ($langFieldError = $country->validateFieldsLang(UNFRIENDLY_ERROR, true)) === true and $country->add()) {
                     $address->id_country = (int) $country->id;
                 } else {
                     $this->_errors[] = $country->name[$defaultLanguageId] . ' ' . Tools::displayError('Cannot be saved');
                     $this->_errors[] = ($fieldError !== true ? $fieldError : '') . ($langFieldError !== true ? $langFieldError : '') . mysql_error();
                 }
             }
         }
         if (isset($address->state) and is_numeric($address->state)) {
             if (State::getNameById((int) $address->state)) {
                 $address->id_state = (int) $address->state;
             }
         } elseif (isset($address->state) and is_string($address->state) and !empty($address->state)) {
             if ($id_state = State::getIdByName($address->state)) {
                 $address->id_state = (int) $id_state;
             } else {
                 $state = new State();
                 $state->active = 1;
                 $state->name = $address->state;
                 $state->id_country = isset($country->id) ? (int) $country->id : 0;
                 $state->id_zone = 0;
                 // Default zone for state to create
                 $state->iso_code = strtoupper(substr($address->state, 0, 2));
                 // Default iso for state to create
                 $state->tax_behavior = 0;
                 if (($fieldError = $state->validateFields(UNFRIENDLY_ERROR, true)) === true and ($langFieldError = $state->validateFieldsLang(UNFRIENDLY_ERROR, true)) === true and $state->add()) {
                     $address->id_state = (int) $state->id;
                 } else {
                     $this->_errors[] = $state->name . ' ' . Tools::displayError('Cannot be saved');
                     $this->_errors[] = ($fieldError !== true ? $fieldError : '') . ($langFieldError !== true ? $langFieldError : '') . mysql_error();
                 }
             }
         }
         if (isset($address->customer_email) and !empty($address->customer_email)) {
             if (Validate::isEmail($address->customer_email)) {
                 $customer = Customer::customerExists($address->customer_email, true);
                 if ($customer) {
                     $address->id_customer = (int) $customer;
                 } else {
                     $this->_errors[] = mysql_error() . ' ' . $address->customer_email . ' ' . Tools::displayError('does not exist in database') . ' ' . (isset($info['id']) ? ' (ID ' . $info['id'] . ')' : '') . ' ' . Tools::displayError('Cannot be saved');
                 }
             } else {
                 $this->_errors[] = '"' . $address->customer_email . '" :' . Tools::displayError('Is not a valid Email');
             }
         }
         if (isset($address->manufacturer) and is_numeric($address->manufacturer) and Manufacturer::manufacturerExists((int) $address->manufacturer)) {
             $address->id_manufacturer = (int) $address->manufacturer;
         } elseif (isset($address->manufacturer) and is_string($address->manufacturer) and !empty($address->manufacturer)) {
             $manufacturer = new Manufacturer();
             $manufacturer->name = $address->manufacturer;
             if (($fieldError = $manufacturer->validateFields(UNFRIENDLY_ERROR, true)) === true and ($langFieldError = $manufacturer->validateFieldsLang(UNFRIENDLY_ERROR, true)) === true and $manufacturer->add()) {
                 $address->id_manufacturer = (int) $manufacturer->id;
             } else {
                 $this->_errors[] = mysql_error() . ' ' . $manufacturer->name . (isset($manufacturer->id) ? ' (' . $manufacturer->id . ')' : '') . ' ' . Tools::displayError('Cannot be saved');
                 $this->_errors[] = ($fieldError !== true ? $fieldError : '') . ($langFieldError !== true ? $langFieldError : '') . mysql_error();
             }
         }
         if (isset($address->supplier) and is_numeric($address->supplier) and Supplier::supplierExists((int) $address->supplier)) {
             $address->id_supplier = (int) $address->supplier;
         } elseif (isset($address->supplier) and is_string($address->supplier) and !empty($address->supplier)) {
             $supplier = new Supplier();
             $supplier->name = $address->supplier;
             if (($fieldError = $supplier->validateFields(UNFRIENDLY_ERROR, true)) === true and ($langFieldError = $supplier->validateFieldsLang(UNFRIENDLY_ERROR, true)) === true and $supplier->add()) {
                 $address->id_supplier = (int) $supplier->id;
             } else {
                 $this->_errors[] = mysql_error() . ' ' . $supplier->name . (isset($supplier->id) ? ' (' . $supplier->id . ')' : '') . ' ' . Tools::displayError('Cannot be saved');
                 $this->_errors[] = ($fieldError !== true ? $fieldError : '') . ($langFieldError !== true ? $langFieldError : '') . mysql_error();
             }
         }
         $res = false;
         if (($fieldError = $address->validateFields(UNFRIENDLY_ERROR, true)) === true and ($langFieldError = $address->validateFieldsLang(UNFRIENDLY_ERROR, true)) === true) {
             if ($address->id and $address->addressExists($address->id)) {
                 $res = $address->update();
             }
             if (!$res) {
                 $res = $address->add();
             }
         }
         if (!$res) {
             $this->_errors[] = $info['alias'] . (isset($info['id']) ? ' (ID ' . $info['id'] . ')' : '') . ' ' . Tools::displayError('Cannot be saved');
             $this->_errors[] = ($fieldError !== true ? $fieldError : '') . ($langFieldError !== true ? $langFieldError : '') . mysql_error();
         }
     }
     $this->closeCsvFile($handle);
 }
 /**
  * Start forms process
  * @see FrontController::postProcess()
  */
 public function postProcess()
 {
     $origin_newsletter = (bool) $this->customer->newsletter;
     if (isset($_POST['years']) && isset($_POST['months']) && isset($_POST['days'])) {
         $this->customer->birthday = (int) $_POST['years'] . '-' . (int) $_POST['months'] . '-' . (int) $_POST['days'];
     }
     if (Tools::isSubmit('submitIdentity')) {
         if (!@checkdate(Tools::getValue('months'), Tools::getValue('days'), Tools::getValue('years')) && !(Tools::getValue('months') == '' && Tools::getValue('days') == '' && Tools::getValue('years') == '')) {
             $this->errors[] = Tools::displayError('Invalid date of birth.');
         } else {
             $email = trim(Tools::getValue('email'));
             $this->customer->birthday = empty($_POST['years']) ? '' : (int) $_POST['years'] . '-' . (int) $_POST['months'] . '-' . (int) $_POST['days'];
             if (isset($_POST['old_passwd'])) {
                 $_POST['old_passwd'] = trim($_POST['old_passwd']);
             }
             if (!Validate::isEmail($email)) {
                 $this->errors[] = Tools::displayError('This email address is not valid');
             } elseif ($this->customer->email != $email && Customer::customerExists($email, true)) {
                 $this->errors[] = Tools::displayError('An account using this email address has already been registered.');
             } elseif (!isset($_POST['old_passwd']) || empty($_POST['old_passwd']) || Tools::encrypt($_POST['old_passwd']) != $this->context->cookie->passwd) {
                 $this->errors[] = Tools::displayError('The password you entered is incorrect.');
             } elseif ($_POST['passwd'] != $_POST['confirmation']) {
                 $this->errors[] = Tools::displayError('The password and confirmation do not match.');
             } else {
                 $prev_id_default_group = $this->customer->id_default_group;
                 // Merge all errors of this file and of the Object Model
                 $this->errors = array_merge($this->errors, $this->customer->validateController());
             }
             if (!count($this->errors)) {
                 $this->customer->id_default_group = (int) $prev_id_default_group;
                 $this->customer->firstname = Tools::ucfirst(Tools::strtolower($this->customer->firstname));
                 if (!isset($_POST['newsletter'])) {
                     $this->customer->newsletter = 0;
                 } elseif (!$origin_newsletter && isset($_POST['newsletter'])) {
                     if ($module_newsletter = Module::getInstanceByName('blocknewsletter')) {
                         if ($module_newsletter->active) {
                             $module_newsletter->confirmSubscription($this->customer->email);
                         }
                     }
                 }
                 if (!isset($_POST['optin'])) {
                     $this->customer->optin = 0;
                 }
                 if (Tools::getValue('passwd')) {
                     $this->context->cookie->passwd = $this->customer->passwd;
                 }
                 if ($this->customer->update()) {
                     $this->context->cookie->customer_lastname = $this->customer->lastname;
                     $this->context->cookie->customer_firstname = $this->customer->firstname;
                     $this->context->smarty->assign('confirmation', 1);
                 } else {
                     $this->errors[] = Tools::displayError('The information cannot be updated.');
                 }
             }
         }
     } else {
         $_POST = array_map('stripslashes', $this->customer->getFields());
     }
     return $this->customer;
 }