Ejemplo n.º 1
0
 /**
  * Do whatever you have to before redirecting the customer on the website of your payment processor.
  */
 public function postProcess()
 {
     /**
      * Oops, an error occured.
      */
     if (Tools::getValue('action') == 'error') {
         return $this->displayError('An error occurred while trying to redirect the customer');
     } else {
         //First solution to know if refreshed page: http://stackoverflow.com/a/6127748
         $refreshButtonPressed = isset($_SERVER['HTTP_CACHE_CONTROL']) && $_SERVER['HTTP_CACHE_CONTROL'] === 'max-age=0';
         $result = $this->module->callToRest('GET', '/orders?mid=' . Context::getContext()->cart->id, null, false);
         $result['response'] = json_decode($result['response'], true);
         if ($result['code'] == '200' && isset($result['response']['results'][0]['id']) && !$refreshButtonPressed) {
             //The cart exists on Aplazame, we try to send with another ID
             $oldCart = new Cart(Context::getContext()->cart->id);
             $data = $oldCart->duplicate();
             if ($data['success']) {
                 $cart = $data['cart'];
                 Context::getContext()->cart = $cart;
                 CartRule::autoAddToCart(Context::getContext());
                 Context::getContext()->cookie->id_cart = $cart->id;
             } else {
                 $this->module->logError('Error: Cannot duplicate cart ' . Context::getContext()->cart->id);
             }
         }
         $this->context->smarty->assign(array('cart_id' => Context::getContext()->cart->id, 'secure_key' => Context::getContext()->customer->secure_key, 'aplazame_order_json' => json_encode($this->module->getCheckoutSerializer(0, Context::getContext()->cart->id), 128), 'aplazame_version' => ConfigurationCore::get('APLAZAME_API_VERSION', null), 'aplazame_url' => Configuration::get('APLAZAME_API_URL', null), 'aplazame_mode' => Configuration::get('APLAZAME_LIVE_MODE', null) ? 'false' : 'true'));
         return $this->setTemplate('redirect.tpl');
     }
 }
Ejemplo n.º 2
0
 /**
  * Logs a given customer in.
  */
 public static function login_customer($id_customer)
 {
     // Make sure that that the customers exists.
     $sql = "SELECT * FROM `" . _DB_PREFIX_ . "customer` WHERE `id_customer` = '" . pSQL($id_customer) . "'";
     $result = Db::getInstance()->GetRow($sql);
     // The user account has been found!
     if (!empty($result['id_customer'])) {
         // See => CustomerCore::getByEmail
         $customer = new Customer();
         $customer->id = $result['id_customer'];
         foreach ($result as $key => $value) {
             if (key_exists($key, $customer)) {
                 $customer->{$key} = $value;
             }
         }
         // See => AuthControllerCore::processSubmitLogin
         Hook::exec('actionBeforeAuthentication');
         $context = Context::getContext();
         $context->cookie->id_compare = isset($context->cookie->id_compare) ? $context->cookie->id_compare : CompareProduct::getIdCompareByIdCustomer($customer->id);
         $context->cookie->id_customer = (int) $customer->id;
         $context->cookie->customer_lastname = $customer->lastname;
         $context->cookie->customer_firstname = $customer->firstname;
         $context->cookie->logged = 1;
         $customer->logged = 1;
         $context->cookie->is_guest = $customer->isGuest();
         $context->cookie->passwd = $customer->passwd;
         $context->cookie->email = $customer->email;
         // Add customer to the context
         $context->customer = $customer;
         if (Configuration::get('PS_CART_FOLLOWING') && (empty($context->cookie->id_cart) || Cart::getNbProducts($context->cookie->id_cart) == 0) && ($id_cart = (int) Cart::lastNoneOrderedCart($context->customer->id))) {
             $context->cart = new Cart($id_cart);
         } else {
             $context->cart->id_carrier = 0;
             $context->cart->setDeliveryOption(null);
             $context->cart->id_address_delivery = Address::getFirstCustomerAddressId((int) $customer->id);
             $context->cart->id_address_invoice = Address::getFirstCustomerAddressId((int) $customer->id);
         }
         $context->cart->id_customer = (int) $customer->id;
         $context->cart->secure_key = $customer->secure_key;
         $context->cart->save();
         $context->cookie->id_cart = (int) $context->cart->id;
         $context->cookie->update();
         $context->cart->autosetProductAddress();
         Hook::exec('actionAuthentication');
         // Login information have changed, so we check if the cart rules still apply
         CartRule::autoRemoveFromCart($context);
         CartRule::autoAddToCart($context);
         // Customer is now logged in.
         return true;
     }
     // Invalid customer specified.
     return false;
 }
Ejemplo n.º 3
0
 private function duplicateCart(Cart $oldCart)
 {
     $data = $oldCart->duplicate();
     if (!$data || !$data['success']) {
         $this->module->log(Aplazame::LOG_WARNING, 'Cannot duplicate cart', $oldCart->id);
         return $oldCart;
     }
     $cart = $data['cart'];
     $this->context->cookie->id_cart = $cart->id;
     $this->context->cart = $cart;
     CartRule::autoAddToCart($this->context);
     $this->context->cookie->write();
     return $cart;
 }
Ejemplo n.º 4
0
 public function submit()
 {
     if ($this->validate()) {
         Hook::exec('actionAuthenticationBefore');
         $customer = new Customer();
         $authentication = $customer->getByEmail($this->getValue('email'), $this->getValue('password'));
         if (isset($authentication->active) && !$authentication->active) {
             $this->errors[''][] = $this->translator->trans('Your account isn\'t available at this time, please contact us', [], 'Shop.Notifications.Error');
         } elseif (!$authentication || !$customer->id || $customer->is_guest) {
             $this->errors[''][] = $this->translator->trans('Authentication failed.', [], 'Shop.Notifications.Error');
         } else {
             $this->context->updateCustomer($customer);
             Hook::exec('actionAuthentication', ['customer' => $this->context->customer]);
             // Login information have changed, so we check if the cart rules still apply
             CartRule::autoRemoveFromCart($this->context);
             CartRule::autoAddToCart($this->context);
         }
     }
     return !$this->hasErrors();
 }
Ejemplo n.º 5
0
 public function postProcess()
 {
     parent::postProcess();
     if (Tools::isSubmit('submitReorder') && ($id_order = (int) Tools::getValue('id_order'))) {
         $oldCart = new Cart(Order::getCartIdStatic($id_order, $this->context->customer->id));
         $duplication = $oldCart->duplicate();
         if (!$duplication || !Validate::isLoadedObject($duplication['cart'])) {
             $this->errors[] = $this->trans('Sorry. We cannot renew your order.', array(), 'Shop.Notifications.Error');
         } elseif (!$duplication['success']) {
             $this->errors[] = $this->trans('Some items are no longer available, and we are unable to renew your order.', array(), 'Shop.Notifications.Error');
         } else {
             $this->context->cookie->id_cart = $duplication['cart']->id;
             $context = $this->context;
             $context->cart = $duplication['cart'];
             CartRule::autoAddToCart($context);
             $this->context->cookie->write();
             Tools::redirect('index.php?controller=order');
         }
     }
     $this->bootstrap();
 }
Ejemplo n.º 6
0
    /**
     * Update product quantity
     *
     * @param integer $quantity Quantity to add (or substract)
     * @param integer $id_product Product ID
     * @param integer $id_product_attribute Attribute ID if needed
     * @param string $operator Indicate if quantity must be increased or decreased
     */
    public function updateQty($quantity, $id_product, $id_product_attribute = null, $id_customization = false, $operator = 'up', $id_address_delivery = 0, Shop $shop = null, $auto_add_cart_rule = true)
    {
        if (!$shop) {
            $shop = Context::getContext()->shop;
        }
        if (Context::getContext()->customer->id) {
            if ($id_address_delivery == 0 && (int) $this->id_address_delivery) {
                // The $id_address_delivery is null, use the cart delivery address
                $id_address_delivery = $this->id_address_delivery;
            } elseif ($id_address_delivery == 0) {
                // The $id_address_delivery is null, get the default customer address
                $id_address_delivery = (int) Address::getFirstCustomerAddressId((int) Context::getContext()->customer->id);
            } elseif (!Customer::customerHasAddress(Context::getContext()->customer->id, $id_address_delivery)) {
                // The $id_address_delivery must be linked with customer
                $id_address_delivery = 0;
            }
        }
        $quantity = (int) $quantity;
        $id_product = (int) $id_product;
        $id_product_attribute = (int) $id_product_attribute;
        $product = new Product($id_product, false, Configuration::get('PS_LANG_DEFAULT'), $shop->id);
        if ($id_product_attribute) {
            $combination = new Combination((int) $id_product_attribute);
            if ($combination->id_product != $id_product) {
                return false;
            }
        }
        /* If we have a product combination, the minimal quantity is set with the one of this combination */
        if (!empty($id_product_attribute)) {
            $minimal_quantity = (int) Attribute::getAttributeMinimalQty($id_product_attribute);
        } else {
            $minimal_quantity = (int) $product->minimal_quantity;
        }
        if (!Validate::isLoadedObject($product)) {
            die(Tools::displayError());
        }
        if (isset(self::$_nbProducts[$this->id])) {
            unset(self::$_nbProducts[$this->id]);
        }
        if (isset(self::$_totalWeight[$this->id])) {
            unset(self::$_totalWeight[$this->id]);
        }
        if ((int) $quantity <= 0) {
            return $this->deleteProduct($id_product, $id_product_attribute, (int) $id_customization);
        } elseif (!$product->available_for_order || Configuration::get('PS_CATALOG_MODE')) {
            return false;
        } else {
            /* Check if the product is already in the cart */
            $result = $this->containsProduct($id_product, $id_product_attribute, (int) $id_customization, (int) $id_address_delivery);
            /* Update quantity if product already exist */
            if ($result) {
                if ($operator == 'up') {
                    $sql = 'SELECT stock.out_of_stock, IFNULL(stock.quantity, 0) as quantity
							FROM ' . _DB_PREFIX_ . 'product p
							' . Product::sqlStock('p', $id_product_attribute, true, $shop) . '
							WHERE p.id_product = ' . $id_product;
                    $result2 = Db::getInstance()->getRow($sql);
                    $product_qty = (int) $result2['quantity'];
                    // Quantity for product pack
                    if (Pack::isPack($id_product)) {
                        $product_qty = Pack::getQuantity($id_product, $id_product_attribute);
                    }
                    $new_qty = (int) $result['quantity'] + (int) $quantity;
                    $qty = '+ ' . (int) $quantity;
                    if (!Product::isAvailableWhenOutOfStock((int) $result2['out_of_stock'])) {
                        if ($new_qty > $product_qty) {
                            return false;
                        }
                    }
                } else {
                    if ($operator == 'down') {
                        $qty = '- ' . (int) $quantity;
                        $new_qty = (int) $result['quantity'] - (int) $quantity;
                        if ($new_qty < $minimal_quantity && $minimal_quantity > 1) {
                            return -1;
                        }
                    } else {
                        return false;
                    }
                }
                /* Delete product from cart */
                if ($new_qty <= 0) {
                    return $this->deleteProduct((int) $id_product, (int) $id_product_attribute, (int) $id_customization);
                } else {
                    if ($new_qty < $minimal_quantity) {
                        return -1;
                    } else {
                        Db::getInstance()->execute('
						UPDATE `' . _DB_PREFIX_ . 'cart_product`
						SET `quantity` = `quantity` ' . $qty . ', `date_add` = NOW()
						WHERE `id_product` = ' . (int) $id_product . (!empty($id_product_attribute) ? ' AND `id_product_attribute` = ' . (int) $id_product_attribute : '') . '
						AND `id_cart` = ' . (int) $this->id . (Configuration::get('PS_ALLOW_MULTISHIPPING') && $this->isMultiAddressDelivery() ? ' AND `id_address_delivery` = ' . (int) $id_address_delivery : '') . '
						LIMIT 1');
                    }
                }
            } elseif ($operator == 'up') {
                $sql = 'SELECT stock.out_of_stock, IFNULL(stock.quantity, 0) as quantity
						FROM ' . _DB_PREFIX_ . 'product p
						' . Product::sqlStock('p', $id_product_attribute, true, $shop) . '
						WHERE p.id_product = ' . $id_product;
                $result2 = Db::getInstance()->getRow($sql);
                // Quantity for product pack
                if (Pack::isPack($id_product)) {
                    $result2['quantity'] = Pack::getQuantity($id_product, $id_product_attribute);
                }
                if (!Product::isAvailableWhenOutOfStock((int) $result2['out_of_stock'])) {
                    if ((int) $quantity > $result2['quantity']) {
                        return false;
                    }
                }
                if ((int) $quantity < $minimal_quantity) {
                    return -1;
                }
                $result_add = Db::getInstance()->insert('cart_product', array('id_product' => (int) $id_product, 'id_product_attribute' => (int) $id_product_attribute, 'id_cart' => (int) $this->id, 'id_address_delivery' => (int) $id_address_delivery, 'id_shop' => $shop->id, 'quantity' => (int) $quantity, 'date_add' => date('Y-m-d H:i:s')));
                if (!$result_add) {
                    return false;
                }
            }
        }
        // refresh cache of self::_products
        $this->_products = $this->getProducts(true);
        $this->update(true);
        $context = Context::getContext()->cloneContext();
        $context->cart = $this;
        if ($auto_add_cart_rule) {
            CartRule::autoAddToCart($context);
        }
        if ($product->customizable) {
            return $this->_updateCustomizationQuantity((int) $quantity, (int) $id_customization, (int) $id_product, (int) $id_product_attribute, (int) $id_address_delivery, $operator);
        } else {
            return true;
        }
    }
Ejemplo n.º 7
0
 /**
  * Process login
  */
 protected function processSubmitLogin()
 {
     Hook::exec('actionBeforeAuthentication');
     $passwd = trim(Tools::getValue('passwd'));
     $_POST['passwd'] = null;
     $email = trim(Tools::getValue('email'));
     if (empty($email)) {
         $this->errors[] = Tools::displayError('An email address required.');
     } elseif (!Validate::isEmail($email)) {
         $this->errors[] = Tools::displayError('Invalid email address.');
     } elseif (empty($passwd)) {
         $this->errors[] = Tools::displayError('Password is required.');
     } elseif (!Validate::isPasswd($passwd)) {
         $this->errors[] = Tools::displayError('Invalid password.');
     } else {
         $customer = new Customer();
         $authentication = $customer->getByEmail(trim($email), trim($passwd));
         if (isset($authentication->active) && !$authentication->active) {
             $this->errors[] = Tools::displayError('Your account isn\'t available at this time, please contact us');
         } elseif (!$authentication || !$customer->id) {
             $this->errors[] = Tools::displayError('Authentication failed.');
         } else {
             $this->context->cookie->id_compare = isset($this->context->cookie->id_compare) ? $this->context->cookie->id_compare : CompareProduct::getIdCompareByIdCustomer($customer->id);
             $this->context->cookie->id_customer = (int) $customer->id;
             $this->context->cookie->customer_lastname = $customer->lastname;
             $this->context->cookie->customer_firstname = $customer->firstname;
             $this->context->cookie->logged = 1;
             $customer->logged = 1;
             $this->context->cookie->is_guest = $customer->isGuest();
             $this->context->cookie->passwd = $customer->passwd;
             $this->context->cookie->email = $customer->email;
             // Add customer to the context
             $this->context->customer = $customer;
             if (Configuration::get('PS_CART_FOLLOWING') && (empty($this->context->cookie->id_cart) || Cart::getNbProducts($this->context->cookie->id_cart) == 0) && ($id_cart = (int) Cart::lastNoneOrderedCart($this->context->customer->id))) {
                 $this->context->cart = new Cart($id_cart);
             } else {
                 $id_carrier = (int) $this->context->cart->id_carrier;
                 $this->context->cart->id_carrier = 0;
                 $this->context->cart->setDeliveryOption(null);
                 $this->context->cart->id_address_delivery = (int) Address::getFirstCustomerAddressId((int) $customer->id);
                 $this->context->cart->id_address_invoice = (int) Address::getFirstCustomerAddressId((int) $customer->id);
             }
             $this->context->cart->id_customer = (int) $customer->id;
             $this->context->cart->secure_key = $customer->secure_key;
             if ($this->ajax && isset($id_carrier) && $id_carrier && Configuration::get('PS_ORDER_PROCESS_TYPE')) {
                 $delivery_option = array($this->context->cart->id_address_delivery => $id_carrier . ',');
                 $this->context->cart->setDeliveryOption($delivery_option);
             }
             $this->context->cart->save();
             $this->context->cookie->id_cart = (int) $this->context->cart->id;
             $this->context->cookie->write();
             $this->context->cart->autosetProductAddress();
             Hook::exec('actionAuthentication', array('customer' => $this->context->customer));
             // Login information have changed, so we check if the cart rules still apply
             CartRule::autoRemoveFromCart($this->context);
             CartRule::autoAddToCart($this->context);
             if (!$this->ajax) {
                 $back = Tools::getValue('back', 'my-account');
                 if ($back == Tools::secureReferrer($back)) {
                     Tools::redirect(html_entity_decode($back));
                 }
                 Tools::redirect('index.php?controller=' . ($this->authRedirection !== false ? urlencode($this->authRedirection) : $back));
             }
         }
     }
     if ($this->ajax) {
         $return = array('hasError' => !empty($this->errors), 'errors' => $this->errors, 'token' => Tools::getToken(false));
         $this->ajaxDie(Tools::jsonEncode($return));
     } else {
         $this->context->smarty->assign('authentification_error', $this->errors);
     }
 }
Ejemplo n.º 8
0
 /**
  * This process delete a product from the cart
  */
 protected function processDeleteProductInCart()
 {
     if ($this->context->cart->deleteProduct($this->id_product, $this->id_product_attribute, $this->customization_id, $this->id_address_delivery)) {
         if (!Cart::getNbProducts((int) $this->context->cart->id)) {
             $this->context->cart->setDeliveryOption(null);
             $this->context->cart->gift = 0;
             $this->context->cart->gift_message = '';
             $this->context->cart->update();
         }
     }
     $removed = CartRule::autoAddToCart();
     if (count($removed) && (int) Tools::getValue('allow_refresh')) {
         $this->ajax_refresh = true;
     }
 }
Ejemplo n.º 9
0
 /**
  * Assign template vars related to page content
  * @see FrontController::initContent()
  */
 public function initContent()
 {
     parent::initContent();
     /* id_carrier is not defined in database before choosing a carrier, set it to a default one to match a potential cart _rule */
     if (empty($this->context->cart->id_carrier)) {
         $checked = $this->context->cart->simulateCarrierSelectedOutput();
         $checked = (int) Cart::desintifier($checked);
         $this->context->cart->id_carrier = $checked;
         $this->context->cart->update();
         CartRule::autoRemoveFromCart($this->context);
         CartRule::autoAddToCart($this->context);
     }
     // SHOPPING CART
     $this->_assignSummaryInformations();
     // WRAPPING AND TOS
     $this->_assignWrappingAndTOS();
     if (Configuration::get('PS_RESTRICT_DELIVERED_COUNTRIES')) {
         $countries = Carrier::getDeliveredCountries($this->context->language->id, true, true);
     } else {
         $countries = Country::getCountries($this->context->language->id, true);
     }
     // If a rule offer free-shipping, force hidding shipping prices
     $free_shipping = false;
     foreach ($this->context->cart->getCartRules() as $rule) {
         if ($rule['free_shipping'] && !$rule['carrier_restriction']) {
             $free_shipping = true;
             break;
         }
     }
     $this->context->smarty->assign(array('free_shipping' => $free_shipping, 'isGuest' => isset($this->context->cookie->is_guest) ? $this->context->cookie->is_guest : 0, 'countries' => $countries, 'sl_country' => (int) Tools::getCountry(), 'PS_GUEST_CHECKOUT_ENABLED' => Configuration::get('PS_GUEST_CHECKOUT_ENABLED'), 'errorCarrier' => Tools::displayError('You must choose a carrier.', false), 'errorTOS' => Tools::displayError('You must accept the Terms of Service.', false), 'isPaymentStep' => isset($_GET['isPaymentStep']) && $_GET['isPaymentStep'], 'genders' => Gender::getGenders(), 'one_phone_at_least' => (int) Configuration::get('PS_ONE_PHONE_AT_LEAST'), 'HOOK_CREATE_ACCOUNT_FORM' => Hook::exec('displayCustomerAccountForm'), 'HOOK_CREATE_ACCOUNT_TOP' => Hook::exec('displayCustomerAccountFormTop')));
     $years = Tools::dateYears();
     $months = Tools::dateMonths();
     $days = Tools::dateDays();
     $this->context->smarty->assign(array('years' => $years, 'months' => $months, 'days' => $days));
     /* Load guest informations */
     if ($this->isLogged && $this->context->cookie->is_guest) {
         $this->context->smarty->assign('guestInformations', $this->_getGuestInformations());
     }
     // ADDRESS
     if ($this->isLogged) {
         $this->_assignAddress();
     }
     // CARRIER
     $this->_assignCarrier();
     // PAYMENT
     $this->_assignPayment();
     Tools::safePostVars();
     $newsletter = Configuration::get('PS_CUSTOMER_NWSL') || Module::isInstalled('blocknewsletter') && Module::getInstanceByName('blocknewsletter')->active;
     $this->context->smarty->assign('newsletter', $newsletter);
     $this->context->smarty->assign('optin', (bool) Configuration::get('PS_CUSTOMER_OPTIN'));
     $this->context->smarty->assign('field_required', $this->context->customer->validateFieldsRequiredDatabase());
     $this->_processAddressFormat();
     $link = new Link();
     if (Tools::getValue('deleteFromOrderLine')) {
         $id_product = Tools::getValue('id_product');
         $date_from = Tools::getValue('date_from');
         $date_to = Tools::getValue('date_to');
         $obj_cart_bk_data = new HotelCartBookingData();
         $cart_data_dlt = $obj_cart_bk_data->deleteRoomDataFromOrderLine($this->context->cart->id, $this->context->cart->id_guest, $id_product, $date_from, $date_to);
         if ($cart_data_dlt) {
             Tools::redirect($link->getPageLink('order', null, $this->context->language->id));
         }
     }
     if ((bool) Configuration::get('PS_ADVANCED_PAYMENT_API')) {
         $this->addJS(_THEME_JS_DIR_ . 'advanced-payment-api.js');
         $this->setTemplate(_PS_THEME_DIR_ . 'order-opc-advanced.tpl');
     } else {
         if (Module::isInstalled('hotelreservationsystem')) {
             require_once _PS_MODULE_DIR_ . 'hotelreservationsystem/define.php';
             $obj_cart_bk_data = new HotelCartBookingData();
             $obj_htl_bk_dtl = new HotelBookingDetail();
             $obj_rm_type = new HotelRoomType();
             $htl_rm_types = $this->context->cart->getProducts();
             if (!empty($htl_rm_types)) {
                 foreach ($htl_rm_types as $type_key => $type_value) {
                     $product = new Product($type_value['id_product'], false, $this->context->language->id);
                     $cover_image_arr = $product->getCover($type_value['id_product']);
                     if (!empty($cover_image_arr)) {
                         $cover_img = $this->context->link->getImageLink($product->link_rewrite, $product->id . '-' . $cover_image_arr['id_image'], 'small_default');
                     } else {
                         $cover_img = $this->context->link->getImageLink($product->link_rewrite, $this->context->language->iso_code . "-default", 'small_default');
                     }
                     $unit_price = Product::getPriceStatic($type_value['id_product'], true, null, 6, null, false, true, 1);
                     if (isset($this->context->customer->id)) {
                         $cart_bk_data = $obj_cart_bk_data->getOnlyCartBookingData($this->context->cart->id, $this->context->cart->id_guest, $type_value['id_product']);
                     } else {
                         $cart_bk_data = $obj_cart_bk_data->getOnlyCartBookingData($this->context->cart->id, $this->context->cart->id_guest, $type_value['id_product']);
                     }
                     $rm_dtl = $obj_rm_type->getRoomTypeInfoByIdProduct($type_value['id_product']);
                     $cart_htl_data[$type_key]['id_product'] = $type_value['id_product'];
                     $cart_htl_data[$type_key]['cover_img'] = $cover_img;
                     $cart_htl_data[$type_key]['name'] = $product->name;
                     $cart_htl_data[$type_key]['unit_price'] = $unit_price;
                     $cart_htl_data[$type_key]['adult'] = $rm_dtl['adult'];
                     $cart_htl_data[$type_key]['children'] = $rm_dtl['children'];
                     foreach ($cart_bk_data as $data_k => $data_v) {
                         $date_join = strtotime($data_v['date_from']) . strtotime($data_v['date_to']);
                         if (isset($cart_htl_data[$type_key]['date_diff'][$date_join])) {
                             $cart_htl_data[$type_key]['date_diff'][$date_join]['num_rm'] += 1;
                             $num_days = $cart_htl_data[$type_key]['date_diff'][$date_join]['num_days'];
                             $vart_quant = (int) $cart_htl_data[$type_key]['date_diff'][$date_join]['num_rm'] * $num_days;
                             $amount = Product::getPriceStatic($type_value['id_product'], true, null, 6, null, false, true, 1);
                             $amount *= $vart_quant;
                             $cart_htl_data[$type_key]['date_diff'][$date_join]['amount'] = $amount;
                         } else {
                             $num_days = $obj_htl_bk_dtl->getNumberOfDays($data_v['date_from'], $data_v['date_to']);
                             $cart_htl_data[$type_key]['date_diff'][$date_join]['num_rm'] = 1;
                             $cart_htl_data[$type_key]['date_diff'][$date_join]['data_form'] = $data_v['date_from'];
                             $cart_htl_data[$type_key]['date_diff'][$date_join]['data_to'] = $data_v['date_to'];
                             $cart_htl_data[$type_key]['date_diff'][$date_join]['num_days'] = $num_days;
                             $amount = Product::getPriceStatic($type_value['id_product'], true, null, 6, null, false, true, 1);
                             $amount *= $num_days;
                             $cart_htl_data[$type_key]['date_diff'][$date_join]['amount'] = $amount;
                             $cart_htl_data[$type_key]['date_diff'][$date_join]['link'] = $link->getPageLink('order', null, $this->context->language->id, "id_product=" . $type_value['id_product'] . "&deleteFromOrderLine=1&date_from=" . $data_v['date_from'] . "&date_to=" . $data_v['date_to']);
                         }
                     }
                 }
                 $this->context->smarty->assign('cart_htl_data', $cart_htl_data);
             }
         }
         $this->setTemplate(_PS_THEME_DIR_ . 'order-opc.tpl');
     }
 }
Ejemplo n.º 10
0
     }
     $address->firstname = Tools::getValue('firstname');
     $address->lastname = ' ';
     $address->phone_mobile = Tools::getValue('phone');
     $address->other = 'Эл.адрес:' . ' default@default.ru' . "\r\n" . 'Время: ' . Tools::getValue('time');
     $address->address1 = ' ';
     $address->city = ' ';
     $address->alias = 'quickorder_' . substr(md5(time() . _COOKIE_KEY_), 0, 7);
     $address->id_customer = $customer->id;
     $address->save();
     $cart->id_address_invoice = (int) $address->id;
     $cart->id_address_delivery = (int) $address->id;
     $id_address = (int) $address->id;
     $cart->update();
     CartRule::autoRemoveFromCart($context);
     CartRule::autoAddToCart($context);
     if (!$context->cart->isMultiAddressDelivery()) {
         $context->cart->setNoMultishipping();
     }
 } else {
     $message = new Message();
     $message->id_cart = $cart->id;
     $message->message = 'Имя:' . ' ' . Tools::getValue('firstname') . "\r\n" . 'Эл.адрес:' . ' default@default.ru' . "\r\n" . 'Телефон:' . ' ' . Tools::getValue('phone') . "\r\n" . 'Время:	 ' . Tools::getValue('time');
     $message->private = true;
     $message->add();
 }
 if (Configuration::get('QUI_CARRIER')) {
     $cart->id_carrier = Configuration::get('QUI_CARRIER');
 }
 if (Configuration::get('QUI_PAYMENT')) {
     $payment = Module::getInstanceById(Configuration::get('QUI_PAYMENT'));
Ejemplo n.º 11
0
    /**
     * Update product quantity
     *
     * @param integer $quantity Quantity to add (or substract)
     * @param $product_id
     * @param null $product_attribute_id
     * @param bool $customization_id
     * @param string $operator Indicate if quantity must be increased or decreased
     * @param int $address_delivery_id
     * @param JeproshopShopModelShop $shop
     * @param bool $auto_add_cart_rule
     * @return bool|int
     * @internal param int $id_product Product ID
     * @internal param int $id_product_attribute Attribute ID if needed
     */
    public function updateQuantity($quantity, $product_id, $product_attribute_id = null, $customization_id = false, $operator = 'up', $address_delivery_id = 0, JeproshopShopModelShop $shop = null, $auto_add_cart_rule = true)
    {
        if (!$shop) {
            $shop = JeproshopContext::getContext()->shop;
        }
        $db = JFactory::getDBO();
        if (JeproshopContext::getContext()->customer->customer_id) {
            if ($address_delivery_id == 0 && (int) $this->address_delivery_id) {
                // The $id_address_delivery is null, use the cart delivery address
                $address_delivery_id = $this->address_delivery_id;
            } elseif ($address_delivery_id == 0) {
                // The $id_address_delivery is null, get the default customer address
                $address_delivery_id = (int) JeproshopAddressModelAddress::getCustomerFirstAddressId((int) JeproshopContext::getContext()->customer->customer_id);
            } elseif (!JeproshopCustomerModelCustomer::customerHasAddress(JeproshopContext::getContext()->customer->customer_id, $address_delivery_id)) {
                // The $id_address_delivery must be linked with customer
                $address_delivery_id = 0;
            }
        }
        $quantity = (int) $quantity;
        $product_id = (int) $product_id;
        $product_attribute_id = (int) $product_attribute_id;
        $product = new JeproshopProductModelProduct($product_id, false, JeproshopSettingModelSetting::getValue('default_lang'), $shop->shop_id);
        if ($product_attribute_id) {
            $combination = new JeproshopCombinationModelCombination((int) $product_attribute_id);
            if ($combination->product_id != $product_id) {
                return false;
            }
        }
        /* If we have a product combination, the minimal quantity is set with the one of this combination */
        if (!empty($product_attribute_id)) {
            $minimal_quantity = (int) JeproshopAttributeModelAttribute::getAttributeMinimalQty($product_attribute_id);
        } else {
            $minimal_quantity = (int) $product->minimal_quantity;
        }
        if (!JeproshopValidator::isLoadedObject($product, 'product_id')) {
            die(Tools::displayError());
        }
        if (isset(self::$_nbProducts[$this->cart_id])) {
            unset(self::$_nbProducts[$this->cart_id]);
        }
        if (isset(self::$_totalWeight[$this->cart_id])) {
            unset(self::$_totalWeight[$this->cart_id]);
        }
        if ((int) $quantity <= 0) {
            return $this->deleteProduct($product_id, $product_attribute_id, (int) $customization_id);
        } elseif (!$product->available_for_order || JeproshopSettingModelSeting::getValue('catalog_mode')) {
            return false;
        } else {
            /* Check if the product is already in the cart */
            $result = $this->containsProduct($product_id, $product_attribute_id, (int) $customization_id, (int) $address_delivery_id);
            /* Update quantity if product already exist */
            if ($result) {
                if ($operator == 'up') {
                    $query = "SELECT stock.out_of_stock, IFNULL(stock.quantity, 0) as quantity FROM " . $db->quoteName('#__jeproshop_product') . " AS product" . JeproshopProductModelProduct::sqlStock('p', $product_attribute_id, true, $shop);
                    $query .= " WHERE product.product_id = " . $product_id;
                    $db->setQuery($query);
                    $result2 = $db->loadObject();
                    $product_qty = (int) $result2->quantity;
                    // Quantity for product pack
                    if (JeproshopProductPack::isPack($product_id)) {
                        $product_qty = JeproshopProductPack::getQuantity($product_id, $product_attribute_id);
                    }
                    $new_qty = (int) $result->quantity + (int) $quantity;
                    $qty = '+ ' . (int) $quantity;
                    if (!JeproshopProductModelProduct::isAvailableWhenOutOfStock((int) $result2->out_of_stock)) {
                        if ($new_qty > $product_qty) {
                            return false;
                        }
                    }
                } else {
                    if ($operator == 'down') {
                        $qty = '- ' . (int) $quantity;
                        $new_qty = (int) $result->quantity - (int) $quantity;
                        if ($new_qty < $minimal_quantity && $minimal_quantity > 1) {
                            return -1;
                        }
                    } else {
                        return false;
                    }
                }
                /* Delete product from cart */
                if ($new_qty <= 0) {
                    return $this->deleteProduct((int) $product_id, (int) $product_attribute_id, (int) $customization_id);
                } else {
                    if ($new_qty < $minimal_quantity) {
                        return -1;
                    } else {
                        $query = "UPDATE " . $db->quoteName('#__jeproshop_cart_product') . " SET " . $db->quoteName('quantity') . " = " . $db->quoteName('quantity') . $qty . ", ";
                        $query .= $db->quoteName('date_add') . " = NOW() WHERE " . $db->quoteName('product_id') . " = " . (int) $product_id;
                        $query .= (!empty($product_attribute_id) ? " AND " . $db->quoteName('product_attribute_id') . " = " . (int) $product_attribute_id : "") . " AND " . $db->quoteName('cart_id') . " = " . (int) $this->cart_id;
                        $query .= (JeproshopSettingModelSeting::getValue('allow_multi_shipping') && $this->isMultiAddressDelivery() ? " AND " . $db->quoteName('address_delivery_id') . " = " . (int) $address_delivery_id : "") . " LIMIT 1";
                        $db->setQuery($query);
                        $db->query();
                    }
                }
            } elseif ($operator == 'up') {
                $sql = 'SELECT stock.out_of_stock, IFNULL(stock.quantity, 0) as quantity
						FROM ' . _DB_PREFIX_ . 'product p
						' . Product::sqlStock('p', $product_attribute_id, true, $shop) . '
						WHERE p.id_product = ' . $product_id;
                $result2 = Db::getInstance()->getRow($sql);
                // Quantity for product pack
                if (Pack::isPack($product_id)) {
                    $result2['quantity'] = Pack::getQuantity($product_id, $product_attribute_id);
                }
                if (!Product::isAvailableWhenOutOfStock((int) $result2['out_of_stock'])) {
                    if ((int) $quantity > $result2['quantity']) {
                        return false;
                    }
                }
                if ((int) $quantity < $minimal_quantity) {
                    return -1;
                }
                $result_add = Db::getInstance()->insert('cart_product', array('id_product' => (int) $product_id, 'id_product_attribute' => (int) $product_attribute_id, 'id_cart' => (int) $this->cart_id, 'id_address_delivery' => (int) $address_delivery_id, 'id_shop' => $shop->shop_id, 'quantity' => (int) $quantity, 'date_add' => date('Y-m-d H:i:s')));
                if (!$result_add) {
                    return false;
                }
            }
        }
        // refresh cache of self::_products
        $this->_products = $this->getProducts(true);
        $this->update(true);
        $context = Context::getContext()->cloneContext();
        $context->cart = $this;
        Cache::clean('getContextualValue_*');
        if ($auto_add_cart_rule) {
            CartRule::autoAddToCart($context);
        }
        if ($product->customizable) {
            return $this->updateCustomizationQuantity((int) $quantity, (int) $customization_id, (int) $product_id, (int) $product_attribute_id, (int) $address_delivery_id, $operator);
        } else {
            return true;
        }
    }
Ejemplo n.º 12
0
 public function init()
 {
     self::$amz_payments = new AmzPayments();
     $this->isLogged = (bool) $this->context->customer->id && Customer::customerIdExistsStatic((int) $this->context->cookie->id_customer);
     parent::init();
     /* Disable some cache related bugs on the cart/order */
     header('Cache-Control: no-cache, must-revalidate');
     header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
     $this->display_column_left = false;
     $this->display_column_right = false;
     // Service initialisieren
     $this->service = self::$amz_payments->getService();
     if (Tools::isSubmit('ajax')) {
         if (Tools::isSubmit('method')) {
             switch (Tools::getValue('method')) {
                 case 'redirectAuthentication':
                 case 'setusertoshop':
                     if (Tools::getValue('access_token')) {
                         $this->context->cookie->amz_access_token = AmzPayments::prepareCookieValueForPrestaShopUse(Tools::getValue('access_token'));
                         $this->context->cookie->amz_access_token_set_time = time();
                     } else {
                         if (Tools::getValue('method') == 'redirectAuthentication') {
                             Tools::redirect('index');
                         } else {
                             error_log('Error, method not submitted and no token');
                             die('error');
                         }
                     }
                     if (Tools::getValue('action') == 'fromCheckout') {
                         $accessTokenValue = AmzPayments::prepareCookieValueForAmazonPaymentsUse(Tools::getValue('access_token'));
                     } else {
                         $accessTokenValue = Tools::getValue('access_token');
                     }
                     $d = self::$amz_payments->requestTokenInfo($accessTokenValue);
                     if ($d->aud != self::$amz_payments->client_id) {
                         if (Tools::getValue('method') == 'redirectAuthentication') {
                             Tools::redirect('index');
                         } else {
                             error_log('auth error LPA');
                             die('error');
                         }
                     }
                     $d = self::$amz_payments->requestProfile($accessTokenValue);
                     $customer_userid = $d->user_id;
                     $customer_name = $d->name;
                     $customer_email = $d->email;
                     // $postcode = $d->postal_code;
                     if ($customers_local_id = AmazonPaymentsCustomerHelper::findByAmazonCustomerId($customer_userid)) {
                         // Customer already exists - login
                         Hook::exec('actionBeforeAuthentication');
                         $customer = new Customer();
                         $authentication = AmazonPaymentsCustomerHelper::getByCustomerID($customers_local_id, true, $customer);
                         if (isset($authentication->active) && !$authentication->active) {
                             $this->errors[] = Tools::displayError('Your account isn\'t available at this time, please contact us');
                         } elseif (!$authentication || !$customer->id) {
                             $this->errors[] = Tools::displayError('Authentication failed.');
                         } else {
                             $this->context->cookie->id_compare = isset($this->context->cookie->id_compare) ? $this->context->cookie->id_compare : CompareProduct::getIdCompareByIdCustomer($customer->id);
                             $this->context->cookie->id_customer = (int) $customer->id;
                             $this->context->cookie->customer_lastname = $customer->lastname;
                             $this->context->cookie->customer_firstname = $customer->firstname;
                             $this->context->cookie->logged = 1;
                             $customer->logged = 1;
                             $this->context->cookie->is_guest = $customer->isGuest();
                             $this->context->cookie->passwd = $customer->passwd;
                             $this->context->cookie->email = $customer->email;
                             // Add customer to the context
                             $this->context->customer = $customer;
                             if (Configuration::get('PS_CART_FOLLOWING') && (empty($this->context->cookie->id_cart) || Cart::getNbProducts($this->context->cookie->id_cart) == 0) && ($id_cart = (int) Cart::lastNoneOrderedCart($this->context->customer->id))) {
                                 $this->context->cart = new Cart($id_cart);
                             } else {
                                 $id_carrier = (int) $this->context->cart->id_carrier;
                                 $this->context->cart->id_carrier = 0;
                                 $this->context->cart->setDeliveryOption(null);
                                 $this->context->cart->id_address_delivery = (int) Address::getFirstCustomerAddressId((int) $customer->id);
                                 $this->context->cart->id_address_invoice = (int) Address::getFirstCustomerAddressId((int) $customer->id);
                             }
                             $this->context->cart->id_customer = (int) $customer->id;
                             $this->context->cart->secure_key = $customer->secure_key;
                             if ($this->ajax && isset($id_carrier) && $id_carrier && Configuration::get('PS_ORDER_PROCESS_TYPE')) {
                                 $delivery_option = array($this->context->cart->id_address_delivery => $id_carrier . ',');
                                 $this->context->cart->setDeliveryOption($delivery_option);
                             }
                             $this->context->cart->save();
                             $this->context->cookie->id_cart = (int) $this->context->cart->id;
                             $this->context->cookie->write();
                             $this->context->cart->autosetProductAddress();
                             Hook::exec('actionAuthentication');
                             // Login information have changed, so we check if the cart rules still apply
                             CartRule::autoRemoveFromCart($this->context);
                             CartRule::autoAddToCart($this->context);
                             if (Tools::getValue('action') == 'fromCheckout' && isset($this->context->cookie->amz_connect_order)) {
                                 AmzPayments::switchOrderToCustomer($this->context->customer->id, $this->context->cookie->amz_connect_order, true);
                             }
                             if (Tools::getValue('action') == 'checkout') {
                                 $goto = $this->context->link->getModuleLink('amzpayments', 'amzpayments');
                             } elseif (Tools::getValue('action') == 'fromCheckout') {
                                 $goto = 'index.php?controller=history';
                             } elseif ($this->context->cart->nbProducts()) {
                                 $goto = 'index.php?controller=order';
                             } else {
                                 if (Configuration::get('PS_SSL_ENABLED')) {
                                     $goto = _PS_BASE_URL_SSL_ . __PS_BASE_URI__;
                                 } else {
                                     $goto = _PS_BASE_URL_ . __PS_BASE_URI__;
                                 }
                             }
                             if (Tools::getValue('method') == 'redirectAuthentication') {
                                 Tools::redirect($goto);
                             } else {
                                 echo $goto;
                             }
                         }
                     } else {
                         if (AmazonPaymentsCustomerHelper::findByEmailAddress($customer_email)) {
                             $this->context->cookie->amzConnectEmail = $customer_email;
                             $this->context->cookie->amzConnectCustomerId = $customer_userid;
                             $goto = $this->context->link->getModuleLink('amzpayments', 'connect_accounts');
                             if (Tools::getValue('action') && Tools::getValue('action') == 'checkout') {
                                 if (strpos($goto, '?') > 0) {
                                     $goto .= '&checkout=1';
                                 } else {
                                     $goto .= '?checkout=1';
                                 }
                             }
                             if (Tools::getValue('method') == 'redirectAuthentication') {
                                 Tools::redirect($goto);
                             } else {
                                 echo $goto;
                             }
                         } else {
                             // Customer does not exist - Create account
                             Hook::exec('actionBeforeSubmitAccount');
                             $this->create_account = true;
                             $_POST['passwd'] = md5(time() . _COOKIE_KEY_);
                             $firstname = '';
                             $lastname = '';
                             $customer_name = preg_replace("/[0-9]/", "", $customer_name);
                             if (strpos(trim($customer_name), ' ') !== false) {
                                 list($firstname, $lastname) = explode(' ', trim($customer_name));
                             } elseif (strpos(trim($customer_name), '-') !== false) {
                                 list($firstname, $lastname) = explode('-', trim($customer_name));
                             } else {
                                 $firstname = trim($customer_name);
                                 $lastname = 'Placeholder';
                             }
                             $customer = new Customer();
                             $customer->email = $customer_email;
                             $lastname_address = $lastname;
                             $firstname_address = $firstname;
                             $_POST['lastname'] = Tools::getValue('customer_lastname', $lastname_address);
                             $_POST['firstname'] = Tools::getValue('customer_firstname', $firstname_address);
                             // $addresses_types = array('address');
                             $this->errors = array_unique(array_merge($this->errors, $customer->validateController()));
                             // Check the requires fields which are settings in the BO
                             $this->errors = $this->errors + $customer->validateFieldsRequiredDatabase();
                             if (!count($this->errors)) {
                                 $customer->firstname = Tools::ucwords($customer->firstname);
                                 $customer->is_guest = 0;
                                 $customer->active = 1;
                                 if (!count($this->errors)) {
                                     if ($customer->add()) {
                                         if (!$customer->is_guest) {
                                             if (!$this->sendConfirmationMail($customer)) {
                                                 $this->errors[] = Tools::displayError('The email cannot be sent.');
                                             }
                                         }
                                         AmazonPaymentsCustomerHelper::saveCustomersAmazonReference($customer, $customer_userid);
                                         $this->updateContext($customer);
                                         $this->context->cart->update();
                                         Hook::exec('actionCustomerAccountAdd', array('_POST' => $_POST, 'newCustomer' => $customer));
                                         if (Tools::getValue('action') == 'fromCheckout' && isset($this->context->cookie->amz_connect_order)) {
                                             AmzPayments::switchOrderToCustomer($customer->id, $this->context->cookie->amz_connect_order, true);
                                         }
                                         if (Tools::getValue('action') == 'checkout') {
                                             $goto = $this->context->link->getModuleLink('amzpayments', 'amzpayments');
                                         } elseif (Tools::getValue('action') == 'fromCheckout') {
                                             $goto = 'index.php?controller=history';
                                         } elseif ($this->context->cart->nbProducts()) {
                                             $goto = 'index.php?controller=order';
                                         } else {
                                             if (Configuration::get('PS_SSL_ENABLED')) {
                                                 $goto = _PS_BASE_URL_SSL_ . __PS_BASE_URI__;
                                             } else {
                                                 $goto = _PS_BASE_URL_ . __PS_BASE_URI__;
                                             }
                                         }
                                         if (Tools::getValue('method') == 'redirectAuthentication') {
                                             Tools::redirect($goto);
                                         } else {
                                             echo $goto;
                                         }
                                     } else {
                                         $this->errors[] = Tools::displayError('An error occurred while creating your account.');
                                     }
                                 }
                             } else {
                                 error_log('Error validating customers informations');
                                 die('error');
                             }
                         }
                     }
                     die;
             }
         }
     }
 }
Ejemplo n.º 13
0
 /**
  * This process add or update a product in the cart
  */
 protected function processChangeProductInCart()
 {
     $mode = Tools::getIsset('update') && $this->id_product ? 'update' : 'add';
     if ($this->qty == 0) {
         $this->errors[] = Tools::displayError('Null quantity.', !Tools::getValue('ajax'));
     } elseif (!$this->id_product) {
         $this->errors[] = Tools::displayError('Product not found', !Tools::getValue('ajax'));
     }
     $product = new Product($this->id_product, true, $this->context->language->id);
     if (!$product->id || !$product->active || !$product->checkAccess($this->context->cart->id_customer)) {
         $this->errors[] = Tools::displayError('This product is no longer available.', !Tools::getValue('ajax'));
         return;
     }
     $qty_to_check = $this->qty;
     $cart_products = $this->context->cart->getProducts();
     if (is_array($cart_products)) {
         foreach ($cart_products as $cart_product) {
             if ((!isset($this->id_product_attribute) || $cart_product['id_product_attribute'] == $this->id_product_attribute) && (isset($this->id_product) && $cart_product['id_product'] == $this->id_product)) {
                 $qty_to_check = $cart_product['cart_quantity'];
                 if (Tools::getValue('op', 'up') == 'down') {
                     $qty_to_check -= $this->qty;
                 } else {
                     $qty_to_check += $this->qty;
                 }
                 break;
             }
         }
     }
     // Check product quantity availability
     if ($this->id_product_attribute) {
         if (!Product::isAvailableWhenOutOfStock($product->out_of_stock) && !Attribute::checkAttributeQty($this->id_product_attribute, $qty_to_check)) {
             $this->errors[] = Tools::displayError('There isn\'t enough product in stock.', !Tools::getValue('ajax'));
         }
     } elseif ($product->hasAttributes()) {
         $minimumQuantity = $product->out_of_stock == 2 ? !Configuration::get('PS_ORDER_OUT_OF_STOCK') : !$product->out_of_stock;
         $this->id_product_attribute = Product::getDefaultAttribute($product->id, $minimumQuantity);
         // @todo do something better than a redirect admin !!
         if (!$this->id_product_attribute) {
             Tools::redirectAdmin($this->context->link->getProductLink($product));
         } elseif (!Product::isAvailableWhenOutOfStock($product->out_of_stock) && !Attribute::checkAttributeQty($this->id_product_attribute, $qty_to_check)) {
             $this->errors[] = Tools::displayError('There isn\'t enough product in stock.', !Tools::getValue('ajax'));
         }
     } elseif (!$product->checkQty($qty_to_check)) {
         $this->errors[] = Tools::displayError('There isn\'t enough product in stock.', !Tools::getValue('ajax'));
     }
     // If no errors, process product addition
     if (!$this->errors && $mode == 'add') {
         // Add cart if no cart found
         if (!$this->context->cart->id) {
             if (Context::getContext()->cookie->id_guest) {
                 $guest = new Guest(Context::getContext()->cookie->id_guest);
                 $this->context->cart->mobile_theme = $guest->mobile_theme;
             }
             $this->context->cart->add();
             if ($this->context->cart->id) {
                 $this->context->cookie->id_cart = (int) $this->context->cart->id;
             }
         }
         // Check customizable fields
         if (!$product->hasAllRequiredCustomizableFields() && !$this->customization_id) {
             $this->errors[] = Tools::displayError('Please fill in all of the required fields, and then save your customizations.', !Tools::getValue('ajax'));
         }
         if (!$this->errors) {
             $cart_rules = $this->context->cart->getCartRules();
             $available_cart_rules = CartRule::getCustomerCartRules($this->context->language->id, isset($this->context->customer->id) ? $this->context->customer->id : 0, true, true, true, $this->context->cart, false, true);
             $update_quantity = $this->context->cart->updateQty($this->qty, $this->id_product, $this->id_product_attribute, $this->customization_id, Tools::getValue('op', 'up'), $this->id_address_delivery);
             if ($update_quantity < 0) {
                 // If product has attribute, minimal quantity is set with minimal quantity of attribute
                 $minimal_quantity = $this->id_product_attribute ? Attribute::getAttributeMinimalQty($this->id_product_attribute) : $product->minimal_quantity;
                 $this->errors[] = sprintf(Tools::displayError('You must add %d minimum quantity', !Tools::getValue('ajax')), $minimal_quantity);
             } elseif (!$update_quantity) {
                 $this->errors[] = Tools::displayError('You already have the maximum quantity available for this product.', !Tools::getValue('ajax'));
             } elseif ((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;
                 } elseif (count($cart_rules2)) {
                     $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;
                         }
                     }
                 } else {
                     $available_cart_rules2 = CartRule::getCustomerCartRules($this->context->language->id, isset($this->context->customer->id) ? $this->context->customer->id : 0, true, true, true, $this->context->cart, false, true);
                     if (count($available_cart_rules2) != count($available_cart_rules)) {
                         $this->ajax_refresh = true;
                     } elseif (count($available_cart_rules2)) {
                         $rule_list = array();
                         foreach ($available_cart_rules2 as $rule) {
                             $rule_list[] = $rule['id_cart_rule'];
                         }
                         foreach ($cart_rules2 as $rule) {
                             if (!in_array($rule['id_cart_rule'], $rule_list)) {
                                 $this->ajax_refresh = true;
                                 break;
                             }
                         }
                     }
                 }
             }
         }
     }
     $removed = CartRule::autoRemoveFromCart();
     CartRule::autoAddToCart();
     if (count($removed) && (int) Tools::getValue('allow_refresh')) {
         $this->ajax_refresh = true;
     }
 }
Ejemplo n.º 14
0
 function refillCart($orderId)
 {
     if (!$orderId) {
         return false;
     }
     $oldCart = new Cart(Order::getCartIdStatic($orderId, $this->context->customer->id));
     $duplication = $oldCart->duplicate();
     if (!$duplication || !Validate::isLoadedObject($duplication['cart'])) {
         //$this->errors[] = Tools::displayError('Sorry. We cannot renew your order.');
         return false;
     } elseif (!$duplication['success']) {
         //$this->errors[] = Tools::displayError('Some items are no longer available, and we are unable to renew your order.');
         return false;
     } else {
         $this->context->cookie->id_cart = $duplication['cart']->id;
         $context = $this->context;
         $context->cart = $duplication['cart'];
         CartRule::autoAddToCart($context);
         $this->context->cookie->write();
         if (Configuration::get('PS_ORDER_PROCESS_TYPE') == 1) {
             //Tools::redirect('index.php?controller=order-opc');
         }
         //Tools::redirect('index.php?controller=order');
         return true;
     }
 }
    /**
     * @see FrontController::initContent()
     */
    public function initContent()
    {
        parent::initContent();
        $fb_connect_appid = Configuration::get('FB_CONNECT_APPID');
        $fb_connect_appkey = Configuration::get('FB_CONNECT_APPKEY');
        $this->login_url = $this->context->link->getModuleLink('fbconnect_psb', 'login', array(), 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')));
        }
        // current user state Logged In with FB
        if ($user) {
            //get the user email from DB with FB ID
            $sql = 'SELECT c.`email`
				FROM `' . _DB_PREFIX_ . 'customer` c
					LEFT JOIN `' . _DB_PREFIX_ . 'customer_profile_connect` pc ON pc.id_customer = c.id_customer
				WHERE pc.`facebook_id` = ' . (int) $fb_user_profile['id'] . Shop::addSqlRestriction(Shop::SHARE_CUSTOMER, 'c');
            $email = Db::getInstance(_PS_USE_SQL_SLAVE_)->getValue($sql);
            if (empty($email)) {
                Tools::redirect($this->context->link->getModuleLink('fbconnect_psb', 'registration', array(), TRUE, $this->context->language->id));
            } else {
                $customer = new Customer();
                $authentication = $customer->getByEmail(trim($email));
                if (!$authentication || !$customer->id) {
                    $this->errors[] = Tools::displayError('Error: Authentication failed.');
                } else {
                    $this->context->cookie->id_compare = isset($this->context->cookie->id_compare) ? $this->context->cookie->id_compare : CompareProduct::getIdCompareByIdCustomer($customer->id);
                    $this->context->cookie->id_customer = (int) $customer->id;
                    $this->context->cookie->customer_lastname = $customer->lastname;
                    $this->context->cookie->customer_firstname = $customer->firstname;
                    $this->context->cookie->logged = 1;
                    $customer->logged = 1;
                    $this->context->cookie->is_guest = $customer->isGuest();
                    $this->context->cookie->passwd = $customer->passwd;
                    $this->context->cookie->email = $customer->email;
                    // Add customer to the context
                    $this->context->customer = $customer;
                    if (Configuration::get('PS_CART_FOLLOWING') && (empty($this->context->cookie->id_cart) || Cart::getNbProducts($this->context->cookie->id_cart) == 0) && ($id_cart = (int) Cart::lastNoneOrderedCart($this->context->customer->id))) {
                        $this->context->cart = new Cart($id_cart);
                    } else {
                        $this->context->cart->id_carrier = 0;
                        $this->context->cart->setDeliveryOption(null);
                        $this->context->cart->id_address_delivery = Address::getFirstCustomerAddressId((int) $customer->id);
                        $this->context->cart->id_address_invoice = Address::getFirstCustomerAddressId((int) $customer->id);
                    }
                    $this->context->cart->id_customer = (int) $customer->id;
                    $this->context->cart->secure_key = $customer->secure_key;
                    $this->context->cart->save();
                    $this->context->cookie->id_cart = (int) $this->context->cart->id;
                    $this->context->cookie->update();
                    $this->context->cart->autosetProductAddress();
                    Hook::exec('actionAuthentication');
                    // Login information have changed, so we check if the cart rules still apply
                    CartRule::autoRemoveFromCart($this->context);
                    CartRule::autoAddToCart($this->context);
                    if ($back = Tools::getValue('back')) {
                        Tools::redirect(html_entity_decode($back));
                    } else {
                        Tools::redirect('index.php?controller=' . ($this->authRedirection !== false ? url_encode($this->authRedirection) : 'my-account'));
                    }
                }
            }
            $this->context->smarty->assign(array('redirect_uri' => urlencode($this->login_url), 'fb_connect_appid' => $fb_connect_appid, 'fb_connect_error' => $this->errors));
            $this->setTemplate('login_fb.tpl');
        } else {
            if (isset($_GET['error']) && isset($_GET['error_code'])) {
                $msg = 'There was error while trying to get information from Facebook.';
                $msg .= '<br>' . $_GET['error'] . ' - ' . $_GET['error_code'] . ' - ' . $_GET['error_description'] . ' - ' . $_GET['error_reason'];
                $this->errors[] = Tools::displayError($msg);
                $this->setTemplate('login_fb.tpl');
            } else {
                Tools::redirect($facebook->getLoginUrl(array('scope' => 'email')));
            }
        }
    }
Ejemplo n.º 16
0
 /**
  * Initializes front controller: sets smarty variables,
  * class properties, redirects depending on context, etc.
  *
  * @global bool     $useSSL           SSL connection flag
  * @global Cookie   $cookie           Visitor's cookie
  * @global Smarty   $smarty
  * @global Cart     $cart             Visitor's cart
  * @global string   $iso              Language ISO
  * @global Country  $defaultCountry   Visitor's country object
  * @global string   $protocol_link
  * @global string   $protocol_content
  * @global Link     $link
  * @global array    $css_files
  * @global array    $js_files
  * @global Currency $currency         Visitor's selected currency
  *
  * @throws PrestaShopException
  */
 public function init()
 {
     /*
      * Globals are DEPRECATED as of version 1.5.0.1
      * Use the Context object to access objects instead.
      * Example: $this->context->cart
      */
     global $useSSL, $cookie, $smarty, $cart, $iso, $defaultCountry, $protocol_link, $protocol_content, $link, $css_files, $js_files, $currency;
     if (self::$initialized) {
         return;
     }
     self::$initialized = true;
     parent::init();
     // enable Symfony error handler if debug mode enabled
     $this->initDebugguer();
     // If current URL use SSL, set it true (used a lot for module redirect)
     if (Tools::usingSecureMode()) {
         $useSSL = true;
     }
     // For compatibility with globals, DEPRECATED as of version 1.5.0.1
     $css_files = $this->css_files;
     $js_files = $this->js_files;
     $this->sslRedirection();
     if ($this->ajax) {
         $this->display_header = false;
         $this->display_footer = false;
     }
     // If account created with the 2 steps register process, remove 'account_created' from cookie
     if (isset($this->context->cookie->account_created)) {
         unset($this->context->cookie->account_created);
     }
     ob_start();
     // Init cookie language
     // @TODO This method must be moved into switchLanguage
     Tools::setCookieLanguage($this->context->cookie);
     $protocol_link = Configuration::get('PS_SSL_ENABLED') || Tools::usingSecureMode() ? 'https://' : 'http://';
     $useSSL = isset($this->ssl) && $this->ssl && Configuration::get('PS_SSL_ENABLED') || Tools::usingSecureMode() ? true : false;
     $protocol_content = $useSSL ? 'https://' : 'http://';
     $link = new Link($protocol_link, $protocol_content);
     $this->context->link = $link;
     if ($id_cart = (int) $this->recoverCart()) {
         $this->context->cookie->id_cart = (int) $id_cart;
     }
     if ($this->auth && !$this->context->customer->isLogged()) {
         Tools::redirect('index.php?controller=authentication' . ($this->authRedirection ? '&back=' . $this->authRedirection : ''));
     }
     /* Theme is missing */
     if (!is_dir(_PS_THEME_DIR_)) {
         throw new PrestaShopException(sprintf(Tools::displayError('Current theme unavailable "%s". Please check your theme directory name and permissions.'), basename(rtrim(_PS_THEME_DIR_, '/\\'))));
     }
     if (Configuration::get('PS_GEOLOCATION_ENABLED')) {
         if (($new_default = $this->geolocationManagement($this->context->country)) && Validate::isLoadedObject($new_default)) {
             $this->context->country = $new_default;
         }
     } elseif (Configuration::get('PS_DETECT_COUNTRY')) {
         $has_currency = isset($this->context->cookie->id_currency) && (int) $this->context->cookie->id_currency;
         $has_country = isset($this->context->cookie->iso_code_country) && $this->context->cookie->iso_code_country;
         $has_address_type = false;
         if ((int) $this->context->cookie->id_cart && ($cart = new Cart($this->context->cookie->id_cart)) && Validate::isLoadedObject($cart)) {
             $has_address_type = isset($cart->{Configuration::get('PS_TAX_ADDRESS_TYPE')}) && $cart->{Configuration::get('PS_TAX_ADDRESS_TYPE')};
         }
         if ((!$has_currency || $has_country) && !$has_address_type) {
             $id_country = $has_country && !Validate::isLanguageIsoCode($this->context->cookie->iso_code_country) ? (int) Country::getByIso(strtoupper($this->context->cookie->iso_code_country)) : (int) Tools::getCountry();
             $country = new Country($id_country, (int) $this->context->cookie->id_lang);
             if (!$has_currency && validate::isLoadedObject($country) && $this->context->country->id !== $country->id) {
                 $this->context->country = $country;
                 $this->context->cookie->id_currency = (int) Currency::getCurrencyInstance($country->id_currency ? (int) $country->id_currency : (int) Configuration::get('PS_CURRENCY_DEFAULT'))->id;
                 $this->context->cookie->iso_code_country = strtoupper($country->iso_code);
             }
         }
     }
     $currency = Tools::setCurrency($this->context->cookie);
     if (isset($_GET['logout']) || $this->context->customer->logged && Customer::isBanned($this->context->customer->id)) {
         $this->context->customer->logout();
         Tools::redirect(isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : null);
     } elseif (isset($_GET['mylogout'])) {
         $this->context->customer->mylogout();
         Tools::redirect(isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : null);
     }
     /* Cart already exists */
     if ((int) $this->context->cookie->id_cart) {
         if (!isset($cart)) {
             $cart = new Cart($this->context->cookie->id_cart);
         }
         if (Validate::isLoadedObject($cart) && $cart->OrderExists()) {
             PrestaShopLogger::addLog('Frontcontroller::init - Cart cannot be loaded or an order has already been placed using this cart', 1, null, 'Cart', (int) $this->context->cookie->id_cart, true);
             unset($this->context->cookie->id_cart, $cart, $this->context->cookie->checkedTOS);
             $this->context->cookie->check_cgv = false;
         } elseif (intval(Configuration::get('PS_GEOLOCATION_ENABLED')) && !in_array(strtoupper($this->context->cookie->iso_code_country), explode(';', Configuration::get('PS_ALLOWED_COUNTRIES'))) && $cart->nbProducts() && intval(Configuration::get('PS_GEOLOCATION_NA_BEHAVIOR')) != -1 && !FrontController::isInWhitelistForGeolocation() && !in_array($_SERVER['SERVER_NAME'], array('localhost', '127.0.0.1'))) {
             /* Delete product of cart, if user can't make an order from his country */
             PrestaShopLogger::addLog('Frontcontroller::init - GEOLOCATION is deleting a cart', 1, null, 'Cart', (int) $this->context->cookie->id_cart, true);
             unset($this->context->cookie->id_cart, $cart);
         } elseif ($this->context->cookie->id_customer != $cart->id_customer || $this->context->cookie->id_lang != $cart->id_lang || $currency->id != $cart->id_currency) {
             // update cart values
             if ($this->context->cookie->id_customer) {
                 $cart->id_customer = (int) $this->context->cookie->id_customer;
             }
             $cart->id_lang = (int) $this->context->cookie->id_lang;
             $cart->id_currency = (int) $currency->id;
             $cart->update();
         }
         /* Select an address if not set */
         if (isset($cart) && (!isset($cart->id_address_delivery) || $cart->id_address_delivery == 0 || !isset($cart->id_address_invoice) || $cart->id_address_invoice == 0) && $this->context->cookie->id_customer) {
             $to_update = false;
             if (!isset($cart->id_address_delivery) || $cart->id_address_delivery == 0) {
                 $to_update = true;
                 $cart->id_address_delivery = (int) Address::getFirstCustomerAddressId($cart->id_customer);
             }
             if (!isset($cart->id_address_invoice) || $cart->id_address_invoice == 0) {
                 $to_update = true;
                 $cart->id_address_invoice = (int) Address::getFirstCustomerAddressId($cart->id_customer);
             }
             if ($to_update) {
                 $cart->update();
             }
         }
     }
     if (!isset($cart) || !$cart->id) {
         $cart = new Cart();
         $cart->id_lang = (int) $this->context->cookie->id_lang;
         $cart->id_currency = (int) $this->context->cookie->id_currency;
         $cart->id_guest = (int) $this->context->cookie->id_guest;
         $cart->id_shop_group = (int) $this->context->shop->id_shop_group;
         $cart->id_shop = $this->context->shop->id;
         if ($this->context->cookie->id_customer) {
             $cart->id_customer = (int) $this->context->cookie->id_customer;
             $cart->id_address_delivery = (int) Address::getFirstCustomerAddressId($cart->id_customer);
             $cart->id_address_invoice = (int) $cart->id_address_delivery;
         } else {
             $cart->id_address_delivery = 0;
             $cart->id_address_invoice = 0;
         }
         // Needed if the merchant want to give a free product to every visitors
         $this->context->cart = $cart;
         CartRule::autoAddToCart($this->context);
     } else {
         $this->context->cart = $cart;
     }
     $this->context->cart->checkAndUpdateAddresses();
     $this->context->smarty->assign('request_uri', Tools::safeOutput(urldecode($_SERVER['REQUEST_URI'])));
     // Automatically redirect to the canonical URL if needed
     if (!empty($this->php_self) && !Tools::getValue('ajax')) {
         $this->canonicalRedirection($this->context->link->getPageLink($this->php_self, $this->ssl, $this->context->language->id));
     }
     Product::initPricesComputation();
     $display_tax_label = $this->context->country->display_tax_label;
     if (isset($cart->{Configuration::get('PS_TAX_ADDRESS_TYPE')}) && $cart->{Configuration::get('PS_TAX_ADDRESS_TYPE')}) {
         $infos = Address::getCountryAndState((int) $cart->{Configuration::get('PS_TAX_ADDRESS_TYPE')});
         $country = new Country((int) $infos['id_country']);
         $this->context->country = $country;
         if (Validate::isLoadedObject($country)) {
             $display_tax_label = $country->display_tax_label;
         }
     }
     $languages = Language::getLanguages(true, $this->context->shop->id);
     $meta_language = array();
     foreach ($languages as $lang) {
         $meta_language[] = $lang['iso_code'];
     }
     /*
      * These shortcuts are DEPRECATED as of version 1.5.0.1
      * Use the Context to access objects instead.
      * Example: $this->context->cart
      */
     self::$cookie = $this->context->cookie;
     self::$cart = $cart;
     self::$smarty = $this->context->smarty;
     self::$link = $link;
     $defaultCountry = $this->context->country;
     $this->displayMaintenancePage();
     if (Country::GEOLOC_FORBIDDEN == $this->restrictedCountry) {
         $this->displayRestrictedCountryPage();
     }
     $this->iso = $iso;
     $this->context->cart = $cart;
     $this->context->currency = $currency;
 }
Ejemplo n.º 17
0
 protected function processForm()
 {
     if (Tools::getValue('action') == 'tryConnect') {
         if (Tools::getValue('email') == $this->context->cookie->amzConnectEmail) {
             $customer = new Customer();
             $authentication = $customer->getByEmail(trim(Tools::getValue('email')), trim(Tools::getValue('passwd')));
             if (isset($authentication->active) && !$authentication->active) {
                 $this->errors[] = Tools::displayError('Your account isn\'t available at this time, please contact us');
             } elseif (!$authentication || !$customer->id) {
                 $this->errors[] = Tools::displayError('Authentication failed.');
             } else {
                 $authentication->save();
                 AmazonPaymentsCustomerHelper::saveCustomersAmazonReference($authentication, $this->context->cookie->amzConnectCustomerId);
                 $this->context->cookie->id_compare = isset($this->context->cookie->id_compare) ? $this->context->cookie->id_compare : CompareProduct::getIdCompareByIdCustomer($customer->id);
                 $this->context->cookie->id_customer = (int) $customer->id;
                 $this->context->cookie->customer_lastname = $customer->lastname;
                 $this->context->cookie->customer_firstname = $customer->firstname;
                 $this->context->cookie->logged = 1;
                 $customer->logged = 1;
                 $this->context->cookie->is_guest = $customer->isGuest();
                 $this->context->cookie->passwd = $customer->passwd;
                 $this->context->cookie->email = $customer->email;
                 // Add customer to the context
                 $this->context->customer = $customer;
                 if (Configuration::get('PS_CART_FOLLOWING') && (empty($this->context->cookie->id_cart) || Cart::getNbProducts($this->context->cookie->id_cart) == 0) && ($id_cart = (int) Cart::lastNoneOrderedCart($this->context->customer->id))) {
                     $this->context->cart = new Cart($id_cart);
                 } else {
                     $id_carrier = (int) $this->context->cart->id_carrier;
                     $this->context->cart->id_carrier = 0;
                     $this->context->cart->setDeliveryOption(null);
                     $this->context->cart->id_address_delivery = (int) Address::getFirstCustomerAddressId((int) $customer->id);
                     $this->context->cart->id_address_invoice = (int) Address::getFirstCustomerAddressId((int) $customer->id);
                 }
                 $this->context->cart->id_customer = (int) $customer->id;
                 $this->context->cart->secure_key = $customer->secure_key;
                 if ($this->ajax && isset($id_carrier) && $id_carrier && Configuration::get('PS_ORDER_PROCESS_TYPE')) {
                     $delivery_option = array($this->context->cart->id_address_delivery => $id_carrier . ',');
                     $this->context->cart->setDeliveryOption($delivery_option);
                 }
                 $this->context->cart->save();
                 $this->context->cookie->id_cart = (int) $this->context->cart->id;
                 $this->context->cookie->write();
                 $this->context->cart->autosetProductAddress();
                 Hook::exec('actionAuthentication');
                 // Login information have changed, so we check if the cart rules still apply
                 CartRule::autoRemoveFromCart($this->context);
                 CartRule::autoAddToCart($this->context);
                 if (Tools::getValue('toCheckout') == '1') {
                     $goto = $this->context->link->getModuleLink('amzpayments', 'amzpayments');
                 } elseif (Tools::getValue('fromCheckout') == '1') {
                     $goto = 'index.php?controller=history';
                 } elseif ($this->context->cart->nbProducts()) {
                     $goto = 'index.php?controller=order';
                 } else {
                     if (Configuration::get('PS_SSL_ENABLED')) {
                         $goto = _PS_BASE_URL_SSL_ . __PS_BASE_URI__;
                     } else {
                         $goto = _PS_BASE_URL_ . __PS_BASE_URI__;
                     }
                 }
                 Tools::redirect($goto);
             }
         }
     }
 }
Ejemplo n.º 18
0
 private function processLogin($customer)
 {
     if (!Validate::isLoadedObject($customer)) {
         FSLTools::returnError(Tools::displayError('Bad customer object.'));
     }
     Hook::exec('actionBeforeAuthentication');
     $context = $this->context;
     $context->cookie->id_compare = isset($context->cookie->id_compare) ? $context->cookie->id_compare : CompareProduct::getIdCompareByIdCustomer($customer->id);
     $context->cookie->id_customer = (int) $customer->id;
     $context->cookie->customer_lastname = $customer->lastname;
     $context->cookie->customer_firstname = $customer->firstname;
     $context->cookie->logged = 1;
     $customer->logged = 1;
     $context->cookie->is_guest = $customer->isGuest();
     $context->cookie->passwd = $customer->passwd;
     $context->cookie->email = $customer->email;
     // Add customer to the context
     $context->customer = $customer;
     if (isset($context->cart)) {
         if (Configuration::get('PS_CART_FOLLOWING') && (empty($context->cookie->id_cart) || Cart::getNbProducts($context->cookie->id_cart) == 0) && ($id_cart = (int) Cart::lastNoneOrderedCart($context->customer->id))) {
             $context->cart = new Cart($id_cart);
         } else {
             $id_carrier = (int) $context->cart->id_carrier;
             $context->cart->id_carrier = 0;
             $context->cart->setDeliveryOption(null);
             $context->cart->id_address_delivery = (int) Address::getFirstCustomerAddressId((int) $customer->id);
             $context->cart->id_address_invoice = (int) Address::getFirstCustomerAddressId((int) $customer->id);
         }
         $context->cart->id_customer = (int) $customer->id;
         $context->cart->secure_key = $customer->secure_key;
         if (isset($id_carrier) && $id_carrier && Configuration::get('PS_ORDER_PROCESS_TYPE')) {
             $delivery_option = array($context->cart->id_address_delivery => $id_carrier . ',');
             $context->cart->setDeliveryOption($delivery_option);
         }
         $context->cart->save();
         $context->cookie->id_cart = (int) $context->cart->id;
         $context->cart->autosetProductAddress();
     }
     $context->cookie->write();
     Hook::exec('actionAuthentication');
     // Login information have changed, so we check if the cart rules still apply
     CartRule::autoRemoveFromCart($context);
     CartRule::autoAddToCart($context);
 }
Ejemplo n.º 19
0
 /**
  * Assign template vars related to page content
  * @see FrontController::initContent()
  */
 public function initContent()
 {
     parent::initContent();
     /* id_carrier is not defined in database before choosing a carrier, set it to a default one to match a potential cart _rule */
     if (empty($this->context->cart->id_carrier)) {
         $checked = $this->context->cart->simulateCarrierSelectedOutput();
         $checked = (int) Cart::desintifier($checked);
         $this->context->cart->id_carrier = $checked;
         $this->context->cart->update();
         CartRule::autoRemoveFromCart($this->context);
         CartRule::autoAddToCart($this->context);
     }
     // SHOPPING CART
     $this->_assignSummaryInformations();
     // WRAPPING AND TOS
     $this->_assignWrappingAndTOS();
     $selectedCountry = (int) Configuration::get('PS_COUNTRY_DEFAULT');
     if (Configuration::get('PS_RESTRICT_DELIVERED_COUNTRIES')) {
         $countries = Carrier::getDeliveredCountries($this->context->language->id, true, true);
     } else {
         $countries = Country::getCountries($this->context->language->id, true);
     }
     // If a rule offer free-shipping, force hidding shipping prices
     $free_shipping = false;
     foreach ($this->context->cart->getCartRules() as $rule) {
         if ($rule['free_shipping'] && !$rule['carrier_restriction']) {
             $free_shipping = true;
             break;
         }
     }
     $this->context->smarty->assign(array('free_shipping' => $free_shipping, 'isGuest' => isset($this->context->cookie->is_guest) ? $this->context->cookie->is_guest : 0, 'countries' => $countries, 'sl_country' => isset($selectedCountry) ? $selectedCountry : 0, 'PS_GUEST_CHECKOUT_ENABLED' => Configuration::get('PS_GUEST_CHECKOUT_ENABLED'), 'errorCarrier' => Tools::displayError('You must choose a carrier.', false), 'errorTOS' => Tools::displayError('You must accept the Terms of Service.', false), 'isPaymentStep' => (bool) (isset($_GET['isPaymentStep']) && $_GET['isPaymentStep']), 'genders' => Gender::getGenders(), 'one_phone_at_least' => (int) Configuration::get('PS_ONE_PHONE_AT_LEAST'), 'HOOK_CREATE_ACCOUNT_FORM' => Hook::exec('displayCustomerAccountForm'), 'HOOK_CREATE_ACCOUNT_TOP' => Hook::exec('displayCustomerAccountFormTop')));
     $years = Tools::dateYears();
     $months = Tools::dateMonths();
     $days = Tools::dateDays();
     $this->context->smarty->assign(array('years' => $years, 'months' => $months, 'days' => $days));
     /* Load guest informations */
     if ($this->isLogged && $this->context->cookie->is_guest) {
         $this->context->smarty->assign('guestInformations', $this->_getGuestInformations());
     }
     // ADDRESS
     if ($this->isLogged) {
         $this->_assignAddress();
     }
     // CARRIER
     $this->_assignCarrier();
     // PAYMENT
     $this->_assignPayment();
     Tools::safePostVars();
     $blocknewsletter = Module::getInstanceByName('blocknewsletter');
     $this->context->smarty->assign('newsletter', (bool) ($blocknewsletter && $blocknewsletter->active));
     $this->_processAddressFormat();
     $this->setTemplate(_PS_THEME_DIR_ . 'order-opc.tpl');
 }
Ejemplo n.º 20
0
 protected function processChangeProductInCart()
 {
     $mode = Tools::getIsset('update') && $this->id_product ? 'update' : 'add';
     if (!$this->id_product) {
         $this->errors[] = Tools::displayError('Product not found', !Tools::getValue('ajax'));
     }
     $product = new Product($this->id_product, true, $this->context->language->id);
     if (!$product->id || !$product->active || !$product->checkAccess($this->context->cart->id_customer)) {
         $this->errors[] = Tools::displayError('This product is no longer available.', !Tools::getValue('ajax'));
         return;
     }
     $qty_factor = 1;
     $ext_qty_factor = 1;
     $ext_prop_quantities = null;
     $id_cart_product = 0;
     $qty_behavior = 0;
     $icp = (int) Tools::getValue('icp');
     $properties = $product->productProperties();
     if ($icp && $this->context->cart->id) {
         $cart_products = $this->context->cart->getProducts();
         if (count($cart_products)) {
             foreach ($cart_products as $cart_product) {
                 if ($icp == (int) $cart_product['id_cart_product']) {
                     $id_cart_product = $icp;
                     if ($mode == 'add') {
                         if (Tools::getValue('qty') != 'default') {
                             $qty_factor = (int) Tools::getValue('qty');
                         }
                         $_POST['qty'] = (double) $cart_product['cart_quantity_fractional'] > 0 ? (double) $cart_product['cart_quantity_fractional'] : ($product->qtyStep() > 0 ? $product->qtyStep() : 1);
                     } elseif ($mode == 'update') {
                         $qty_behavior = PP::qtyBehavior($product, $cart_product['cart_quantity']);
                     }
                     break;
                 }
             }
         }
     } else {
         if ($properties['pp_ext'] == 1 && in_array($properties['pp_ext_policy'], array(0, 2))) {
             $ext_prop_quantities = array();
             $ext_prop_qty_ratio = array();
             if ($properties['pp_ext_policy'] == 2) {
                 $prop = $product->productProp();
                 if ($this->id_product_attribute) {
                     $id_product_attribute = $this->id_product_attribute;
                 } else {
                     if ($product->hasAttributes()) {
                         $id_product_attribute = Product::getDefaultAttribute($product->id);
                     } else {
                         $id_product_attribute = 0;
                     }
                 }
             }
             $positions = count($properties['pp_ext_prop']);
             for ($position = 1; $position <= $positions; $position++) {
                 $pp_ext_prop = $properties['pp_ext_prop'][$position];
                 if ($properties['pp_ext_policy'] == 2) {
                     $q = PP::productProp($prop, $id_product_attribute, $position, 'quantity');
                     if ($q === false) {
                         $q = (double) $pp_ext_prop['default_quantity'];
                     }
                     if ($q <= 0) {
                         $q = 1;
                     }
                 } else {
                     $q = PP::resolveInputQty(Tools::getValue('pp_ext_prop_quantity_' . $position, 'default'), $properties['pp_qty_policy'], $pp_ext_prop['qty_step'], $pp_ext_prop['default_quantity'] > 0 ? $pp_ext_prop['default_quantity'] : 1);
                 }
                 $ext_prop_quantities[$position] = $q;
                 $ext_prop_qty_ratio[$position] = $properties['pp_ext_prop'][$position]['qty_ratio'];
                 if ($q <= 0) {
                     $this->errors[] = Tools::displayError('Quantity not specified.', !Tools::getValue('ajax'));
                 }
                 $min_qty = (double) $pp_ext_prop['minimum_quantity'];
                 if ($min_qty > 0 && $q < $min_qty) {
                     $this->errors[] = Tools::displayError(sprintf('Please specify at least %s for %s', (string) PP::formatQty($min_qty), (string) $pp_ext_prop['property']), !Tools::getValue('ajax'));
                 }
                 $max_qty = (double) $pp_ext_prop['maximum_quantity'];
                 if ($max_qty > 0 && $q > $max_qty) {
                     $this->errors[] = Tools::displayError(sprintf('Please specify no more than %s for %s', (string) PP::formatQty($max_qty), (string) $pp_ext_prop['property']), !Tools::getValue('ajax'));
                 }
             }
             if (!$this->errors) {
                 $ext_qty_factor = $properties['pp_ext_method'] == 1 ? 1 : 0;
                 $positions = count($ext_prop_quantities);
                 for ($position = 1; $position <= $positions; $position++) {
                     $value = $ext_prop_quantities[$position];
                     $qty_ratio = $ext_prop_qty_ratio[$position];
                     if ($properties['pp_ext_method'] == 1) {
                         $ext_qty_factor *= $qty_ratio > 0 ? $value / $qty_ratio : $value;
                     } elseif ($properties['pp_ext_method'] == 2) {
                         $ext_qty_factor += $qty_ratio > 0 ? $value / $qty_ratio : $value;
                     }
                 }
             }
         }
     }
     if (!$this->errors) {
         if ($this->id_product_attribute) {
             $default_quantity = $product->attributeDefaultQty($this->id_product_attribute);
             $this->qty = $qty_factor * $this->resolveInputQty($properties, $default_quantity);
             if ($this->qty == 0) {
                 $this->errors[] = Tools::displayError('Quantity not specified.', !Tools::getValue('ajax'));
             } else {
                 if (!Product::isAvailableWhenOutOfStock($product->out_of_stock) && !Attribute::checkAttributeQty($this->id_product_attribute, $ext_qty_factor * $this->qty)) {
                     $this->errors[] = Tools::displayError('There isn\'t enough product in stock.', !Tools::getValue('ajax'));
                 }
             }
         } else {
             if ($product->hasAttributes()) {
                 $min_quantity = $product->out_of_stock == 2 ? !Configuration::get('PS_ORDER_OUT_OF_STOCK') : !$product->out_of_stock;
                 $this->id_product_attribute = Product::getDefaultAttribute($product->id, $min_quantity);
                 if (!$this->id_product_attribute) {
                     Tools::redirectAdmin($this->context->link->getProductLink($product));
                 } else {
                     $default_quantity = $product->attributeDefaultQty($this->id_product_attribute);
                     $this->qty = $qty_factor * $this->resolveInputQty($properties, $default_quantity);
                     if ($this->qty == 0) {
                         $this->errors[] = Tools::displayError('Quantity not specified.', !Tools::getValue('ajax'));
                     } else {
                         if (!Product::isAvailableWhenOutOfStock($product->out_of_stock) && !Attribute::checkAttributeQty($this->id_product_attribute, $ext_qty_factor * $this->qty)) {
                             $this->errors[] = Tools::displayError('There isn\'t enough product in stock.', !Tools::getValue('ajax'));
                         }
                     }
                 }
             } else {
                 $default_quantity = $product->defaultQty();
                 $this->qty = $qty_factor * $this->resolveInputQty($properties, $default_quantity);
                 if ($this->qty == 0) {
                     $this->errors[] = Tools::displayError('Quantity not specified.', !Tools::getValue('ajax'));
                 } else {
                     if (!$product->checkQty($ext_qty_factor * $this->qty)) {
                         $this->errors[] = Tools::displayError('There isn\'t enough product in stock.', !Tools::getValue('ajax'));
                     }
                 }
             }
         }
     }
     if (!$this->errors && ($mode == 'add' || $mode == 'update' && $qty_behavior)) {
         if ($mode == 'add' && !$this->context->cart->id) {
             if (Context::getContext()->cookie->id_guest) {
                 $guest = new Guest(Context::getContext()->cookie->id_guest);
                 $this->context->cart->mobile_theme = $guest->mobile_theme;
             }
             $this->context->cart->add();
             if ($this->context->cart->id) {
                 $this->context->cookie->id_cart = (int) $this->context->cart->id;
             }
         }
         if (!$product->hasAllRequiredCustomizableFields() && !$this->customization_id) {
             $this->errors[] = Tools::displayError('Please fill in all of the required fields, and then save your customizations.', !Tools::getValue('ajax'));
         }
         if (!$this->errors) {
             $cart_rules = $this->context->cart->getCartRules();
             $update_quantity = $this->context->cart->updateQty($id_cart_product ? $mode == 'add' ? $qty_factor : $this->qty : ($ext_prop_quantities !== null ? $ext_qty_factor : $this->qty), $this->id_product, $this->id_product_attribute, $this->customization_id, $mode == 'update' ? 'update' : Tools::getValue('op', 'up'), $this->id_address_delivery, null, true, $id_cart_product, $ext_prop_quantities, $this->qty);
             if ($update_quantity < 0) {
                 $minimal_quantity = $this->id_product_attribute ? $product->attributeMinQty($this->id_product_attribute) : $product->minQty();
                 $this->errors[] = Tools::displayError(sprintf('You must add %s minimum quantity', $minimal_quantity), !Tools::getValue('ajax'));
             } elseif (!$update_quantity) {
                 $this->errors[] = Tools::displayError('You already have the maximum quantity available for this product.', !Tools::getValue('ajax'));
             } elseif ((int) Tools::getValue('allow_refresh')) {
                 $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;
                         }
                     }
                 }
             }
         }
     }
     $removed = CartRule::autoRemoveFromCart();
     CartRule::autoAddToCart();
     if (count($removed) && (int) Tools::getValue('allow_refresh')) {
         $this->ajax_refresh = true;
     }
 }
Ejemplo n.º 21
0
 public function addData($data, $add, $type)
 {
     $delivery = array();
     $cart = new Cart();
     if ($data->{$type}->currency == 'RUR') {
         $currency_id = Currency::getIdByIsoCode('RUB');
     } else {
         $currency_id = Currency::getIdByIsoCode($data->cart->currency);
     }
     $def_currency = Configuration::get('PS_CURRENCY_DEFAULT');
     $this->context->cookie->id_currency = $def_currency != $currency_id ? $currency_id : $def_currency;
     $this->context->cookie->write();
     $this->context->currency = new Currency($this->context->cookie->id_currency);
     $cart->id_lang = (int) $this->context->cookie->id_lang;
     $cart->id_currency = (int) $this->context->cookie->id_currency;
     $cart->id_guest = (int) $this->context->cookie->id_guest;
     $cart->add();
     $this->context->cookie->id_cart = (int) $cart->id;
     $this->context->cookie->write();
     $buyer = isset($data->{$type}->buyer) ? $data->{$type}->buyer : '';
     $b = array();
     if ($add) {
         $delivery = isset($data->{$type}->delivery->address) ? $data->{$type}->delivery->address : new stdClass();
         $street = isset($delivery->street) ? ' Улица: ' . $delivery->street : 'Самовывоз';
         $subway = isset($delivery->subway) ? ' Метро: ' . $delivery->subway : '';
         $block = isset($delivery->block) ? ' Корпус/Строение: ' . $delivery->block : '';
         $floor = isset($delivery->floor) ? ' Этаж: ' . $delivery->floor : '';
         $house = isset($delivery->house) ? ' Дом: ' . $delivery->house : '';
         $address1 = $street . $subway . $block . $floor . $house;
         $customer = new Customer(Configuration::get('YA_POKUPKI_CUSTOMER'));
         $address = new Address();
         $address->firstname = $customer->firstname;
         $address->lastname = $customer->lastname;
         $address->phone_mobile = isset($buyer->phone) ? $buyer->phone : 999999;
         $address->postcode = isset($delivery->postcode) ? $delivery->postcode : 00;
         $address->address1 = $address1;
         $address->city = isset($delivery->city) ? $delivery->city : 'Город';
         $address->alias = 'pokupki_' . Tools::substr(md5(time() . _COOKIE_KEY_), 0, 7);
         $address->id_customer = $customer->id;
         $address->id_country = Configuration::get('PS_COUNTRY_DEFAULT');
         $address->save();
         $cart->id_address_invoice = (int) $address->id;
         $cart->id_address_delivery = (int) $address->id;
         $cart->update();
         $cart->id_customer = (int) $customer->id;
         $this->context->cookie->id_customer = (int) $customer->id;
         $this->context->cookie->write();
         $b = array('address' => $address, 'customer' => $customer);
     }
     CartRule::autoRemoveFromCart($this->context);
     CartRule::autoAddToCart($this->context);
     $a = array('cart' => $cart);
     $dd = array_merge($a, $b);
     return $dd;
 }
 /**
  * Manage address
  */
 public function processAddress()
 {
     $same = Tools::isSubmit('same');
     if (!Tools::getValue('id_address_invoice', false) && !$same) {
         $same = true;
     }
     if (!Customer::customerHasAddress($this->context->customer->id, (int) Tools::getValue('id_address_delivery')) || !$same && Tools::getValue('id_address_delivery') != Tools::getValue('id_address_invoice') && !Customer::customerHasAddress($this->context->customer->id, (int) Tools::getValue('id_address_invoice'))) {
         $this->errors[] = Tools::displayError('Invalid address', !Tools::getValue('ajax'));
     } else {
         $this->context->cart->id_address_delivery = (int) Tools::getValue('id_address_delivery');
         $this->context->cart->id_address_invoice = $same ? $this->context->cart->id_address_delivery : (int) Tools::getValue('id_address_invoice');
         CartRule::autoRemoveFromCart($this->context);
         CartRule::autoAddToCart($this->context);
         if (!$this->context->cart->update()) {
             $this->errors[] = Tools::displayError('An error occurred while updating your cart.', !Tools::getValue('ajax'));
         }
         if (!$this->context->cart->isMultiAddressDelivery()) {
             $this->context->cart->setNoMultishipping();
         }
         // If there is only one delivery address, set each delivery address lines with the main delivery address
         if (Tools::isSubmit('message')) {
             $this->_updateMessage(Tools::getValue('message'));
         }
         // Add checking for all addresses
         $address_without_carriers = $this->context->cart->getDeliveryAddressesWithoutCarriers();
         if (count($address_without_carriers) && !$this->context->cart->isVirtualCart()) {
             if (count($address_without_carriers) > 1) {
                 $this->errors[] = sprintf(Tools::displayError('There are no carriers that deliver to some addresses you selected.', !Tools::getValue('ajax')));
             } elseif ($this->context->cart->isMultiAddressDelivery()) {
                 $this->errors[] = sprintf(Tools::displayError('There are no carriers that deliver to one of the address you selected.', !Tools::getValue('ajax')));
             } else {
                 $this->errors[] = sprintf(Tools::displayError('There are no carriers that deliver to the address you selected.', !Tools::getValue('ajax')));
             }
         }
     }
     if ($this->errors) {
         if (Tools::getValue('ajax')) {
             die('{"hasError" : true, "errors" : ["' . implode('\',\'', $this->errors) . '"]}');
         }
         $this->step = 1;
     }
     if ($this->ajax) {
         die(true);
     }
 }
Ejemplo n.º 23
0
 /**
  * Manage address
  */
 public function processAddress()
 {
     $same = Tools::isSubmit('same');
     if (!Tools::getValue('id_address_invoice', false) && !$same) {
         $same = true;
     }
     if (!Customer::customerHasAddress($this->context->customer->id, (int) Tools::getValue('id_address_delivery')) || !$same && Tools::getValue('id_address_delivery') != Tools::getValue('id_address_invoice') && !Customer::customerHasAddress($this->context->customer->id, (int) Tools::getValue('id_address_invoice'))) {
         $this->errors[] = Tools::displayError('Invalid address', !Tools::getValue('ajax'));
     } else {
         $this->context->cart->id_address_delivery = (int) Tools::getValue('id_address_delivery');
         $this->context->cart->id_address_invoice = $same ? $this->context->cart->id_address_delivery : (int) Tools::getValue('id_address_invoice');
         CartRule::autoRemoveFromCart($this->context);
         CartRule::autoAddToCart($this->context);
         if (!$this->context->cart->update()) {
             $this->errors[] = Tools::displayError('An error occurred while updating your cart.', !Tools::getValue('ajax'));
         }
         if (!$this->context->cart->isMultiAddressDelivery()) {
             $this->context->cart->setNoMultishipping();
         }
         // If there is only one delivery address, set each delivery address lines with the main delivery address
         if (Tools::isSubmit('message')) {
             $this->_updateMessage(Tools::getValue('message'));
         }
         // Add checking for all addresses
         $errors = array();
         $address_without_carriers = $this->context->cart->getDeliveryAddressesWithoutCarriers(false, $errors);
         if (count($address_without_carriers) && !$this->context->cart->isVirtualCart()) {
             $flag_error_message = false;
             foreach ($errors as $error) {
                 if ($error == Carrier::SHIPPING_WEIGHT_EXCEPTION && !$flag_error_message) {
                     $this->errors[] = sprintf(Tools::displayError('The product selection cannot be delivered by the available carrier(s): it is too heavy. Please amend your cart to lower its weight.', !Tools::getValue('ajax')));
                     $flag_error_message = true;
                 } elseif ($error == Carrier::SHIPPING_PRICE_EXCEPTION && !$flag_error_message) {
                     $this->errors[] = sprintf(Tools::displayError('The product selection cannot be delivered by the available carrier(s). Please amend your cart.', !Tools::getValue('ajax')));
                     $flag_error_message = true;
                 } elseif ($error == Carrier::SHIPPING_SIZE_EXCEPTION && !$flag_error_message) {
                     $this->errors[] = sprintf(Tools::displayError('The product selection cannot be delivered by the available carrier(s): its size does not fit. Please amend your cart to reduce its size.', !Tools::getValue('ajax')));
                     $flag_error_message = true;
                 }
             }
             if (count($address_without_carriers) > 1 && !$flag_error_message) {
                 $this->errors[] = sprintf(Tools::displayError('There are no carriers that deliver to some addresses you selected.', !Tools::getValue('ajax')));
             } elseif ($this->context->cart->isMultiAddressDelivery() && !$flag_error_message) {
                 $this->errors[] = sprintf(Tools::displayError('There are no carriers that deliver to one of the address you selected.', !Tools::getValue('ajax')));
             } elseif (!$flag_error_message) {
                 $this->errors[] = sprintf(Tools::displayError('There are no carriers that deliver to the address you selected.', !Tools::getValue('ajax')));
             }
         }
     }
     if ($this->errors) {
         if (Tools::getValue('ajax')) {
             $this->ajaxDie('{"hasError" : true, "errors" : ["' . implode('\',\'', $this->errors) . '"]}');
         }
         $this->step = 1;
     }
     if ($this->ajax) {
         $this->ajaxDie(true);
     }
 }
 public function hookExtraCarrier($params)
 {
     $carrier_so = new Carrier((int) Configuration::get('SOCOLISSIMO_CARRIER_ID'));
     if (!isset($carrier_so) || !$carrier_so->active) {
         return '';
     }
     $country = new Country((int) $params['address']->id_country);
     $carriers = Carrier::getCarriers($this->context->language->id, true, false, false, null, defined('ALL_CARRIERS') ? ALL_CARRIERS : Carrier::ALL_CARRIERS);
     // Backward compatibility 1.5
     $id_carrier = $carrier_so->id;
     // bug fix for cart rule with restriction
     if (!version_compare(_PS_VERSION_, '1.5', '<')) {
         CartRule::autoAddToCart($this->context);
     }
     // For now works only with single shipping !
     if (method_exists($params['cart'], 'carrierIsSelected')) {
         if ($params['cart']->carrierIsSelected((int) $carrier_so->id, $params['address']->id)) {
             $id_carrier = (int) $carrier_so->id;
         }
     }
     $customer = new Customer($params['address']->id_customer);
     $gender = array('1' => 'MR', '2' => 'MME', '3' => 'MLE');
     if (in_array((int) $customer->id_gender, array(1, 2))) {
         $cecivility = $gender[(int) $customer->id_gender];
     } else {
         $cecivility = 'MR';
     }
     $tax_rate = Tax::getCarrierTaxRate($id_carrier, isset($params['cart']->id_address_delivery) ? $params['cart']->id_address_delivery : null);
     $tax_rate_seller = Tax::getCarrierTaxRate(Configuration::get('SOCOLISSIMO_CARRIER_ID_SELLER'), isset($params['cart']->id_address_delivery) ? $params['cart']->id_address_delivery : null);
     if ($tax_rate) {
         $std_cost_with_taxes = number_format((double) $this->initial_cost * (1 + $tax_rate / 100), 2, ',', ' ');
     } else {
         $std_cost_with_taxes = number_format((double) $this->initial_cost, 2, ',', ' ');
     }
     $seller_cost_with_taxes = 0;
     if ($this->seller_cost) {
         if ($tax_rate_seller) {
             $seller_cost_with_taxes = number_format((double) $this->seller_cost * (1 + $tax_rate_seller / 100), 2, ',', ' ');
         } else {
             $seller_cost_with_taxes = number_format((double) $this->seller_cost, 2, ',', ' ');
         }
     }
     $free_shipping = false;
     if (version_compare(_PS_VERSION_, '1.5', '<')) {
         $rules = $params['cart']->getDiscounts();
         if (!empty($rules)) {
             foreach ($rules as $rule) {
                 if ($rule['id_discount_type'] == 3) {
                     $free_shipping = true;
                     break;
                 }
             }
         }
     } else {
         $rules = $params['cart']->getCartRules();
         if (!empty($rules)) {
             foreach ($rules as $rule) {
                 if ($rule['free_shipping'] && !$rule['carrier_restriction']) {
                     $free_shipping = true;
                     break;
                 }
             }
             if (!$free_shipping) {
                 $key_search = $id_carrier . ',';
                 $deliveries_list = $params['cart']->getDeliveryOptionList();
                 foreach ($deliveries_list as $deliveries) {
                     foreach ($deliveries as $key => $elt) {
                         if ($key == $key_search) {
                             $free_shipping = $elt['is_free'];
                         }
                     }
                 }
             }
         } else {
             // for cart rule with restriction
             $key_search = $id_carrier . ',';
             $deliveries_list = $params['cart']->getDeliveryOptionList();
             foreach ($deliveries_list as $deliveries) {
                 foreach ($deliveries as $key => $elt) {
                     if ($key == $key_search) {
                         $free_shipping = $elt['is_free'];
                     }
                 }
             }
         }
     }
     if ($free_shipping) {
         $std_cost_with_taxes = 0;
         $seller_cost_with_taxes = 0;
     }
     // Keep this fields order (see doc.)
     $inputs = array('pudoFOId' => Configuration::get('SOCOLISSIMO_ID'), 'ceName' => $this->replaceAccentedChars(Tools::substr($params['address']->lastname, 0, 34)), 'dyPreparationTime' => (int) Configuration::Get('SOCOLISSIMO_PREPARATION_TIME'), 'dyForwardingCharges' => $std_cost_with_taxes, 'dyForwardingChargesCMT' => $seller_cost_with_taxes, 'trClientNumber' => (int) $params['address']->id_customer, 'orderId' => $this->formatOrderId((int) $params['address']->id), 'numVersion' => $this->getNumVersion(), 'ceCivility' => $cecivility, 'ceFirstName' => $this->replaceAccentedChars(Tools::substr($params['address']->firstname, 0, 29)), 'ceCompanyName' => $this->replaceAccentedChars(Tools::substr($params['address']->company, 0, 38)), 'ceAdress3' => $this->replaceAccentedChars(Tools::substr($params['address']->address1, 0, 38)), 'ceAdress4' => $this->replaceAccentedChars(Tools::substr($params['address']->address2, 0, 38)), 'ceZipCode' => $this->replaceAccentedChars($params['address']->postcode), 'ceTown' => $this->replaceAccentedChars(Tools::substr($params['address']->city, 0, 32)), 'ceEmail' => $this->replaceAccentedChars($params['cookie']->email), 'cePhoneNumber' => $this->replaceAccentedChars(str_replace(array(' ', '.', '-', ',', ';', '/', '\\', '(', ')'), '', $params['address']->phone_mobile)), 'dyWeight' => (double) $params['cart']->getTotalWeight() * 1000, 'trParamPlus' => $carrier_so->id, 'trReturnUrlKo' => htmlentities($this->url, ENT_NOQUOTES, 'UTF-8'), 'trReturnUrlOk' => htmlentities($this->url, ENT_NOQUOTES, 'UTF-8'), 'CHARSET' => 'UTF-8', 'cePays' => $country->iso_code, 'trInter' => Configuration::get('SOCOLISSIMO_EXP_BEL'), 'ceLang' => 'FR');
     if (!$inputs['dyForwardingChargesCMT'] && !Configuration::get('SOCOLISSIMO_COST_SELLER')) {
         unset($inputs['dyForwardingChargesCMT']);
     }
     // set params for Api 3.0 if needed
     $inputs = $this->setInputParams($inputs);
     // generate key for API
     $inputs['signature'] = $this->generateKey($inputs);
     // calculate lowest cost
     $from_cost = $std_cost_with_taxes;
     if ($seller_cost_with_taxes || Configuration::get('SOCOLISSIMO_CARRIER_ID_SELLER') && Configuration::get('SOCOLISSIMO_COST_SELLER')) {
         if ((double) str_replace(',', '.', $seller_cost_with_taxes) < (double) str_replace(',', '.', $std_cost_with_taxes)) {
             $from_cost = $seller_cost_with_taxes;
         }
     }
     $rewrite_active = true;
     if (!Configuration::get('PS_REWRITING_SETTINGS')) {
         $rewrite_active = false;
     }
     // module link for prestashop 1.5 to get proper url
     $link = new Link();
     $module_link = '';
     if (!version_compare(_PS_VERSION_, '1.5', '<')) {
         $module_link = $link->getModuleLink('socolissimo', 'redirect', array(), true);
     }
     $module_link_mobile = '';
     if (!version_compare(_PS_VERSION_, '1.5', '<')) {
         $module_link_mobile = $link->getModuleLink('socolissimo', 'redirectmobile', array(), true);
     }
     // automatic settings api protocol for ssl
     $protocol = 'http://';
     if (Configuration::get('PS_SSL_ENABLED')) {
         $protocol = 'https://';
     }
     $this->context->smarty->assign(array('select_label' => $this->l('Select delivery mode'), 'edit_label' => $this->l('Edit delivery mode'), 'token' => sha1('socolissimo' . _COOKIE_KEY_ . Context::getContext()->cookie->id_cart), 'urlSo' => $protocol . Configuration::get('SOCOLISSIMO_URL') . '?trReturnUrlKo=' . htmlentities($this->url, ENT_NOQUOTES, 'UTF-8'), 'urlSoMobile' => $protocol . Configuration::get('SOCOLISSIMO_URL_MOBILE') . '?trReturnUrlKo=' . htmlentities($this->url, ENT_NOQUOTES, 'UTF-8'), 'id_carrier' => $id_carrier, 'id_carrier_seller' => Configuration::get('SOCOLISSIMO_CARRIER_ID_SELLER'), 'SOBWD_C' => version_compare(_PS_VERSION_, '1.5', '<') ? false : true, 'inputs' => $inputs, 'initialCost_label' => $this->l('From'), 'initialCost' => $from_cost . $this->l(' €'), 'taxMention' => $this->l(' TTC'), 'finishProcess' => $this->l('To choose SoColissimo, click on a delivery method'), 'rewrite_active' => $rewrite_active, 'link_socolissimo' => $module_link, 'link_socolissimo_mobile' => $module_link_mobile));
     $ids = array();
     foreach ($carriers as $carrier) {
         $ids[] = $carrier['id_carrier'];
     }
     if ($params['cart']->id_carrier == Configuration::Get('SOCOLISSIMO_CARRIER_ID') && $this->getDeliveryInfos($this->context->cart->id, $this->context->customer->id)) {
         $this->context->smarty->assign('already_select_delivery', true);
     } else {
         $this->context->smarty->assign('already_select_delivery', false);
     }
     if (($country->iso_code == 'FR' || $country->iso_code == 'BE' && Configuration::get('SOCOLISSIMO_EXP_BEL')) && Configuration::Get('SOCOLISSIMO_ID') != null && Configuration::get('SOCOLISSIMO_KEY') != null && $this->checkAvailibility() && $this->checkSoCarrierAvailable((int) Configuration::get('SOCOLISSIMO_CARRIER_ID')) && in_array((int) Configuration::get('SOCOLISSIMO_CARRIER_ID'), $ids)) {
         // if mobile or iPad
         if (version_compare(_PS_VERSION_, '1.5', '<')) {
             // 1.4
             if ($this->context->getMobileDevice()) {
                 return $this->fetchTemplate('socolissimo_redirect_mobile.tpl');
             }
         } else {
             // 1.5
             if (Context::getContext()->getMobileDevice() || _THEME_NAME_ == 'prestashop_mobile' || $this->isIpad()) {
                 if (Configuration::get('PS_ORDER_PROCESS_TYPE')) {
                     $tab_id_soco = explode('|', Configuration::get('SOCOLISSIMO_CARRIER_ID_HIST'));
                     $tab_id_soco[] = $id_carrier;
                     $this->context->smarty->assign('ids', $tab_id_soco);
                     return $this->fetchTemplate('socolissimo_error_mobile_opc.tpl');
                 } else {
                     return $this->fetchTemplate('socolissimo_redirect_mobile.tpl');
                 }
             }
         }
         // route display mode
         if (Configuration::get('PS_ORDER_PROCESS_TYPE') || Configuration::get('SOCOLISSIMO_USE_FANCYBOX')) {
             return $this->fetchTemplate('socolissimo_fancybox.tpl');
         }
         if (Configuration::get('SOCOLISSIMO_USE_IFRAME')) {
             return $this->fetchTemplate('socolissimo_iframe.tpl');
         }
         return $this->fetchTemplate('socolissimo_redirect.tpl');
     } else {
         $tab_id_soco = explode('|', Configuration::get('SOCOLISSIMO_CARRIER_ID_HIST'));
         $tab_id_soco[] = $id_carrier;
         $this->context->smarty->assign('ids', $tab_id_soco);
         return $this->fetchTemplate('socolissimo_error.tpl');
     }
 }
 protected function _assignAddress()
 {
     //if guest checkout disabled and flag is_guest  in cookies is actived
     if (Configuration::get('PS_GUEST_CHECKOUT_ENABLED') == 0 && (int) $this->context->customer->is_guest != Configuration::get('PS_GUEST_CHECKOUT_ENABLED')) {
         $this->context->customer->logout();
         Tools::redirect('');
     } else {
         if (!Customer::getAddressesTotalById($this->context->customer->id)) {
             Tools::redirect('index.php?controller=address&back=' . urlencode('order.php?step=1&multi-shipping=' . (int) Tools::getValue('multi-shipping')));
         }
     }
     $customer = $this->context->customer;
     if (Validate::isLoadedObject($customer)) {
         /* Getting customer addresses */
         $customerAddresses = $customer->getAddresses($this->context->language->id);
         // Getting a list of formated address fields with associated values
         $formatedAddressFieldsValuesList = array();
         foreach ($customerAddresses as $i => $address) {
             if (!Address::isCountryActiveById((int) $address['id_address'])) {
                 unset($customerAddresses[$i]);
             }
             $tmpAddress = new Address($address['id_address']);
             $formatedAddressFieldsValuesList[$address['id_address']]['ordered_fields'] = AddressFormat::getOrderedAddressFields($address['id_country']);
             $formatedAddressFieldsValuesList[$address['id_address']]['formated_fields_values'] = AddressFormat::getFormattedAddressFieldsValues($tmpAddress, $formatedAddressFieldsValuesList[$address['id_address']]['ordered_fields']);
             unset($tmpAddress);
         }
         if (key($customerAddresses) != 0) {
             $customerAddresses = array_values($customerAddresses);
         }
         if (!count($customerAddresses)) {
             $bad_delivery = false;
             if (($bad_delivery = (bool) (!Address::isCountryActiveById((int) $this->context->cart->id_address_delivery))) || !Address::isCountryActiveById((int) $this->context->cart->id_address_invoice)) {
                 $back_url = $this->context->link->getPageLink('order', true, (int) $this->context->language->id, array('step' => Tools::getValue('step'), 'multi-shipping' => (int) Tools::getValue('multi-shipping')));
                 $params = array('multi-shipping' => (int) Tools::getValue('multi-shipping'), 'id_address' => $bad_delivery ? (int) $this->context->cart->id_address_delivery : (int) $this->context->cart->id_address_invoice, 'back' => $back_url);
                 Tools::redirect($this->context->link->getPageLink('address', true, (int) $this->context->language->id, $params));
             }
         }
         $this->context->smarty->assign(array('addresses' => $customerAddresses, 'formatedAddressFieldsValuesList' => $formatedAddressFieldsValuesList));
         /* Setting default addresses for cart */
         if ((!isset($this->context->cart->id_address_delivery) || empty($this->context->cart->id_address_delivery)) && count($customerAddresses)) {
             $this->context->cart->id_address_delivery = (int) $customerAddresses[0]['id_address'];
             $update = 1;
         }
         if ((!isset($this->context->cart->id_address_invoice) || empty($this->context->cart->id_address_invoice)) && count($customerAddresses)) {
             $this->context->cart->id_address_invoice = (int) $customerAddresses[0]['id_address'];
             $update = 1;
         }
         /* Update cart addresses only if needed */
         if (isset($update) && $update) {
             $this->context->cart->update();
             // Address has changed, so we check if the cart rules still apply
             CartRule::autoRemoveFromCart($this->context);
             CartRule::autoAddToCart($this->context);
         }
         /* If delivery address is valid in cart, assign it to Smarty */
         if (isset($this->context->cart->id_address_delivery)) {
             $deliveryAddress = new Address((int) $this->context->cart->id_address_delivery);
             if (Validate::isLoadedObject($deliveryAddress) && $deliveryAddress->id_customer == $customer->id) {
                 $this->context->smarty->assign('delivery', $deliveryAddress);
             }
         }
         /* If invoice address is valid in cart, assign it to Smarty */
         if (isset($this->context->cart->id_address_invoice)) {
             $invoiceAddress = new Address((int) $this->context->cart->id_address_invoice);
             if (Validate::isLoadedObject($invoiceAddress) && $invoiceAddress->id_customer == $customer->id) {
                 $this->context->smarty->assign('invoice', $invoiceAddress);
             }
         }
     }
     if ($oldMessage = Message::getMessageByCartId((int) $this->context->cart->id)) {
         $this->context->smarty->assign('oldMessage', $oldMessage['message']);
     }
 }
Ejemplo n.º 26
0
 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');
     }
 }
Ejemplo n.º 27
0
    /**
     * Delete a product from the cart
     *
     * @param integer $id_product Product ID
     * @param integer $id_product_attribute Attribute ID if needed
     * @param integer $id_customization Customization id
     * @return boolean result
     */
    public function deleteProduct($id_product, $id_product_attribute = null, $id_customization = null, $id_address_delivery = 0)
    {
        if (isset(self::$_nbProducts[$this->id])) {
            unset(self::$_nbProducts[$this->id]);
        }
        if (isset(self::$_totalWeight[$this->id])) {
            unset(self::$_totalWeight[$this->id]);
        }
        if ((int) $id_customization) {
            $product_total_quantity = (int) Db::getInstance()->getValue('SELECT `quantity`
				FROM `' . _DB_PREFIX_ . 'cart_product`
				WHERE `id_product` = ' . (int) $id_product . '
				AND `id_cart` = ' . (int) $this->id . '
				AND `id_product_attribute` = ' . (int) $id_product_attribute);
            $customization_quantity = (int) Db::getInstance()->getValue('
			SELECT `quantity`
			FROM `' . _DB_PREFIX_ . 'customization`
			WHERE `id_cart` = ' . (int) $this->id . '
			AND `id_product` = ' . (int) $id_product . '
			AND `id_product_attribute` = ' . (int) $id_product_attribute . '
			' . ((int) $id_address_delivery ? 'AND `id_address_delivery` = ' . (int) $id_address_delivery : ''));
            if (!$this->_deleteCustomization((int) $id_customization, (int) $id_product, (int) $id_product_attribute, (int) $id_address_delivery)) {
                return false;
            }
            // refresh cache of self::_products
            $this->_products = $this->getProducts(true);
            return $customization_quantity == $product_total_quantity && $this->deleteProduct((int) $id_product, (int) $id_product_attribute, null, (int) $id_address_delivery);
        }
        /* Get customization quantity */
        $result = Db::getInstance()->getRow('
			SELECT SUM(`quantity`) AS \'quantity\'
			FROM `' . _DB_PREFIX_ . 'customization`
			WHERE `id_cart` = ' . (int) $this->id . '
			AND `id_product` = ' . (int) $id_product . '
			AND `id_product_attribute` = ' . (int) $id_product_attribute);
        if ($result === false) {
            return false;
        }
        /* If the product still possesses customization it does not have to be deleted */
        if (Db::getInstance()->NumRows() && (int) $result['quantity']) {
            return Db::getInstance()->execute('
				UPDATE `' . _DB_PREFIX_ . 'cart_product`
				SET `quantity` = ' . (int) $result['quantity'] . '
				WHERE `id_cart` = ' . (int) $this->id . '
				AND `id_product` = ' . (int) $id_product . ($id_product_attribute != null ? ' AND `id_product_attribute` = ' . (int) $id_product_attribute : ''));
        }
        /* Product deletion */
        $result = Db::getInstance()->execute('
		DELETE FROM `' . _DB_PREFIX_ . 'cart_product`
		WHERE `id_product` = ' . (int) $id_product . '
		' . (!is_null($id_product_attribute) ? ' AND `id_product_attribute` = ' . (int) $id_product_attribute : '') . '
		AND `id_cart` = ' . (int) $this->id . '
		' . ((int) $id_address_delivery ? 'AND `id_address_delivery` = ' . (int) $id_address_delivery : ''));
        if ($result) {
            $return = $this->update(true);
            // refresh cache of self::_products
            $this->_products = $this->getProducts(true);
            CartRule::autoRemoveFromCart();
            CartRule::autoAddToCart();
            return $return;
        }
        return false;
    }
 public function init()
 {
     ParentOrderController::init();
     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 'getCartSummary':
                         if ($this->_legal && ($tpl = $this->_legal->getThemeOverride('order-summary'))) {
                             $summary = $this->context->cart->getSummaryDetails();
                             $this->context->smarty->assign($summary);
                             $this->context->smarty->assign('HOOK_SHOPPING_CART', Hook::exec('displayShoppingCartFooter', $summary));
                             die(Tools::jsonEncode(array('summary' => $this->context->smarty->fetch($tpl))));
                         }
                         break;
                     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')) {
                             $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');
                         $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()) {
                             // 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();
                             $return = array_merge(array('order_opc_adress' => $this->context->smarty->fetch(_PS_THEME_DIR_ . 'order-address.tpl'), 'block_user_info' => isset($block_user_info) ? $block_user_info->hookDisplayTop(array()) : '', 'formatedAddressFieldsValuesList' => $formated_address_fields_values_list, '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());
                             $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) . '"]}');
     }
 }
Ejemplo n.º 29
0
 public function init()
 {
     /*
      * Globals are DEPRECATED as of version 1.5.
      * Use the Context to access objects instead.
      * Example: $this->context->cart
      */
     global $useSSL, $cookie, $smarty, $cart, $iso, $defaultCountry, $protocol_link, $protocol_content, $link, $css_files, $js_files, $currency;
     if (self::$initialized) {
         return;
     }
     self::$initialized = true;
     parent::init();
     // If current URL use SSL, set it true (used a lot for module redirect)
     if (Tools::usingSecureMode()) {
         $useSSL = true;
     }
     // For compatibility with globals, DEPRECATED as of version 1.5
     $css_files = $this->css_files;
     $js_files = $this->js_files;
     // If we call a SSL controller without SSL or a non SSL controller with SSL, we redirect with the right protocol
     if (Configuration::get('PS_SSL_ENABLED') && $_SERVER['REQUEST_METHOD'] != 'POST' && $this->ssl != Tools::usingSecureMode()) {
         header('HTTP/1.1 301 Moved Permanently');
         header('Cache-Control: no-cache');
         if ($this->ssl) {
             header('Location: ' . Tools::getShopDomainSsl(true) . $_SERVER['REQUEST_URI']);
         } else {
             header('Location: ' . Tools::getShopDomain(true) . $_SERVER['REQUEST_URI']);
         }
         exit;
     }
     if ($this->ajax) {
         $this->display_header = false;
         $this->display_footer = false;
     }
     // if account created with the 2 steps register process, remove 'accoun_created' from cookie
     if (isset($this->context->cookie->account_created)) {
         $this->context->smarty->assign('account_created', 1);
         unset($this->context->cookie->account_created);
     }
     ob_start();
     // Init cookie language
     // @TODO This method must be moved into switchLanguage
     Tools::setCookieLanguage($this->context->cookie);
     $protocol_link = Configuration::get('PS_SSL_ENABLED') || Tools::usingSecureMode() ? 'https://' : 'http://';
     $useSSL = isset($this->ssl) && $this->ssl && Configuration::get('PS_SSL_ENABLED') || Tools::usingSecureMode() ? true : false;
     $protocol_content = $useSSL ? 'https://' : 'http://';
     $link = new Link($protocol_link, $protocol_content);
     $this->context->link = $link;
     if ($id_cart = (int) $this->recoverCart()) {
         $this->context->cookie->id_cart = (int) $id_cart;
     }
     if ($this->auth && !$this->context->customer->isLogged($this->guestAllowed)) {
         Tools::redirect('index.php?controller=authentication' . ($this->authRedirection ? '&back=' . $this->authRedirection : ''));
     }
     /* Theme is missing */
     if (!is_dir(_PS_THEME_DIR_)) {
         throw new PrestaShopException(sprintf(Tools::displayError('Current theme unavailable "%s". Please check your theme directory name and permissions.'), basename(rtrim(_PS_THEME_DIR_, '/\\'))));
     }
     if (Configuration::get('PS_GEOLOCATION_ENABLED')) {
         if (($newDefault = $this->geolocationManagement($this->context->country)) && Validate::isLoadedObject($newDefault)) {
             $this->context->country = $newDefault;
         }
     }
     $currency = Tools::setCurrency($this->context->cookie);
     if (isset($_GET['logout']) || $this->context->customer->logged && Customer::isBanned($this->context->customer->id)) {
         $this->context->customer->logout();
         Tools::redirect(isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : null);
     } elseif (isset($_GET['mylogout'])) {
         $this->context->customer->mylogout();
         Tools::redirect(isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : null);
     }
     /* Cart already exists */
     if ((int) $this->context->cookie->id_cart) {
         $cart = new Cart($this->context->cookie->id_cart);
         if ($cart->OrderExists()) {
             unset($this->context->cookie->id_cart, $cart, $this->context->cookie->checkedTOS);
             $this->context->cookie->check_cgv = false;
         } elseif (intval(Configuration::get('PS_GEOLOCATION_ENABLED')) && !in_array(strtoupper($this->context->cookie->iso_code_country), explode(';', Configuration::get('PS_ALLOWED_COUNTRIES'))) && $cart->nbProducts() && intval(Configuration::get('PS_GEOLOCATION_NA_BEHAVIOR')) != -1 && !FrontController::isInWhitelistForGeolocation() && !in_array($_SERVER['SERVER_NAME'], array('localhost', '127.0.0.1'))) {
             unset($this->context->cookie->id_cart, $cart);
         } elseif ($this->context->cookie->id_customer != $cart->id_customer || $this->context->cookie->id_lang != $cart->id_lang || $currency->id != $cart->id_currency) {
             if ($this->context->cookie->id_customer) {
                 $cart->id_customer = (int) $this->context->cookie->id_customer;
             }
             $cart->id_lang = (int) $this->context->cookie->id_lang;
             $cart->id_currency = (int) $currency->id;
             $cart->update();
         }
         /* Select an address if not set */
         if (isset($cart) && (!isset($cart->id_address_delivery) || $cart->id_address_delivery == 0 || !isset($cart->id_address_invoice) || $cart->id_address_invoice == 0) && $this->context->cookie->id_customer) {
             $to_update = false;
             if (!isset($cart->id_address_delivery) || $cart->id_address_delivery == 0) {
                 $to_update = true;
                 $cart->id_address_delivery = (int) Address::getFirstCustomerAddressId($cart->id_customer);
             }
             if (!isset($cart->id_address_invoice) || $cart->id_address_invoice == 0) {
                 $to_update = true;
                 $cart->id_address_invoice = (int) Address::getFirstCustomerAddressId($cart->id_customer);
             }
             if ($to_update) {
                 $cart->update();
             }
         }
     }
     if (!isset($cart) || !$cart->id) {
         $cart = new Cart();
         $cart->id_lang = (int) $this->context->cookie->id_lang;
         $cart->id_currency = (int) $this->context->cookie->id_currency;
         $cart->id_guest = (int) $this->context->cookie->id_guest;
         $cart->id_shop_group = (int) $this->context->shop->id_shop_group;
         $cart->id_shop = $this->context->shop->id;
         if ($this->context->cookie->id_customer) {
             $cart->id_customer = (int) $this->context->cookie->id_customer;
             $cart->id_address_delivery = (int) Address::getFirstCustomerAddressId($cart->id_customer);
             $cart->id_address_invoice = $cart->id_address_delivery;
         } else {
             $cart->id_address_delivery = 0;
             $cart->id_address_invoice = 0;
         }
         // Needed if the merchant want to give a free product to every visitors
         $this->context->cart = $cart;
         CartRule::autoAddToCart($this->context);
     } else {
         $this->context->cart = $cart;
     }
     /* get page name to display it in body id */
     // Are we in a payment module
     $module_name = '';
     if (Validate::isModuleName(Tools::getValue('module'))) {
         $module_name = Tools::getValue('module');
     }
     if (!empty($this->page_name)) {
         $page_name = $this->page_name;
     } elseif (!empty($this->php_self)) {
         $page_name = $this->php_self;
     } elseif (Tools::getValue('fc') == 'module' && $module_name != '' && Module::getInstanceByName($module_name) instanceof PaymentModule) {
         $page_name = 'module-payment-submit';
     } elseif (preg_match('#^' . preg_quote($this->context->shop->physical_uri, '#') . 'modules/([a-zA-Z0-9_-]+?)/(.*)$#', $_SERVER['REQUEST_URI'], $m)) {
         $page_name = 'module-' . $m[1] . '-' . str_replace(array('.php', '/'), array('', '-'), $m[2]);
     } else {
         $page_name = Dispatcher::getInstance()->getController();
         $page_name = preg_match('/^[0-9]/', $page_name) ? 'page_' . $page_name : $page_name;
     }
     $this->context->smarty->assign(Meta::getMetaTags($this->context->language->id, $page_name));
     $this->context->smarty->assign('request_uri', Tools::safeOutput(urldecode($_SERVER['REQUEST_URI'])));
     /* Breadcrumb */
     $navigationPipe = Configuration::get('PS_NAVIGATION_PIPE') ? Configuration::get('PS_NAVIGATION_PIPE') : '>';
     $this->context->smarty->assign('navigationPipe', $navigationPipe);
     // Automatically redirect to the canonical URL if needed
     if (!empty($this->php_self) && !Tools::getValue('ajax')) {
         $this->canonicalRedirection($this->context->link->getPageLink($this->php_self, $this->ssl, $this->context->language->id));
     }
     Product::initPricesComputation();
     $display_tax_label = $this->context->country->display_tax_label;
     if (isset($cart->{Configuration::get('PS_TAX_ADDRESS_TYPE')}) && $cart->{Configuration::get('PS_TAX_ADDRESS_TYPE')}) {
         $infos = Address::getCountryAndState((int) $cart->{Configuration::get('PS_TAX_ADDRESS_TYPE')});
         $country = new Country((int) $infos['id_country']);
         $this->context->country = $country;
         if (Validate::isLoadedObject($country)) {
             $display_tax_label = $country->display_tax_label;
         }
     }
     $languages = Language::getLanguages(true, $this->context->shop->id);
     $meta_language = array();
     foreach ($languages as $lang) {
         $meta_language[] = $lang['iso_code'];
     }
     $compared_products = array();
     if (Configuration::get('PS_COMPARATOR_MAX_ITEM') && isset($this->context->cookie->id_compare)) {
         $compared_products = CompareProduct::getCompareProducts($this->context->cookie->id_compare);
     }
     $this->context->smarty->assign(array('mobile_device' => $this->context->getMobileDevice(), 'link' => $link, 'cart' => $cart, 'currency' => $currency, 'cookie' => $this->context->cookie, 'page_name' => $page_name, 'hide_left_column' => !$this->display_column_left, 'hide_right_column' => !$this->display_column_right, 'base_dir' => _PS_BASE_URL_ . __PS_BASE_URI__, 'base_dir_ssl' => $protocol_link . Tools::getShopDomainSsl() . __PS_BASE_URI__, 'content_dir' => $protocol_content . Tools::getHttpHost() . __PS_BASE_URI__, 'base_uri' => $protocol_content . Tools::getHttpHost() . __PS_BASE_URI__ . (!Configuration::get('PS_REWRITING_SETTINGS') ? 'index.php' : ''), 'tpl_dir' => _PS_THEME_DIR_, 'modules_dir' => _MODULE_DIR_, 'mail_dir' => _MAIL_DIR_, 'lang_iso' => $this->context->language->iso_code, 'come_from' => Tools::getHttpHost(true, true) . Tools::htmlentitiesUTF8(str_replace(array('\'', '\\'), '', urldecode($_SERVER['REQUEST_URI']))), 'cart_qties' => (int) $cart->nbProducts(), 'currencies' => Currency::getCurrencies(), 'languages' => $languages, 'meta_language' => implode(',', $meta_language), 'priceDisplay' => Product::getTaxCalculationMethod((int) $this->context->cookie->id_customer), 'is_logged' => (bool) $this->context->customer->isLogged(), 'is_guest' => (bool) $this->context->customer->isGuest(), 'add_prod_display' => (int) Configuration::get('PS_ATTRIBUTE_CATEGORY_DISPLAY'), 'shop_name' => Configuration::get('PS_SHOP_NAME'), 'roundMode' => (int) Configuration::get('PS_PRICE_ROUND_MODE'), 'use_taxes' => (int) Configuration::get('PS_TAX'), 'show_taxes' => (int) (Configuration::get('PS_TAX_DISPLAY') == 1 && (int) Configuration::get('PS_TAX')), 'display_tax_label' => (bool) $display_tax_label, 'vat_management' => (int) Configuration::get('VATNUMBER_MANAGEMENT'), 'opc' => (bool) Configuration::get('PS_ORDER_PROCESS_TYPE'), 'PS_CATALOG_MODE' => (bool) Configuration::get('PS_CATALOG_MODE') || !(bool) Group::getCurrent()->show_prices, 'b2b_enable' => (bool) Configuration::get('PS_B2B_ENABLE'), 'request' => $link->getPaginationLink(false, false, false, true), 'PS_STOCK_MANAGEMENT' => Configuration::get('PS_STOCK_MANAGEMENT'), 'quick_view' => (bool) Configuration::get('PS_QUICK_VIEW'), 'shop_phone' => Configuration::get('PS_SHOP_PHONE'), 'compared_products' => is_array($compared_products) ? $compared_products : array(), 'comparator_max_item' => (int) Configuration::get('PS_COMPARATOR_MAX_ITEM')));
     // Add the tpl files directory for mobile
     if ($this->useMobileTheme()) {
         $this->context->smarty->assign(array('tpl_mobile_uri' => _PS_THEME_MOBILE_DIR_));
     }
     // Deprecated
     $this->context->smarty->assign(array('id_currency_cookie' => (int) $currency->id, 'logged' => $this->context->customer->isLogged(), 'customerName' => $this->context->customer->logged ? $this->context->cookie->customer_firstname . ' ' . $this->context->cookie->customer_lastname : false));
     $assign_array = array('img_ps_dir' => _PS_IMG_, 'img_cat_dir' => _THEME_CAT_DIR_, 'img_lang_dir' => _THEME_LANG_DIR_, 'img_prod_dir' => _THEME_PROD_DIR_, 'img_manu_dir' => _THEME_MANU_DIR_, 'img_sup_dir' => _THEME_SUP_DIR_, 'img_ship_dir' => _THEME_SHIP_DIR_, 'img_store_dir' => _THEME_STORE_DIR_, 'img_col_dir' => _THEME_COL_DIR_, 'img_dir' => _THEME_IMG_DIR_, 'css_dir' => _THEME_CSS_DIR_, 'js_dir' => _THEME_JS_DIR_, 'pic_dir' => _THEME_PROD_PIC_DIR_);
     // Add the images directory for mobile
     if ($this->useMobileTheme()) {
         $assign_array['img_mobile_dir'] = _THEME_MOBILE_IMG_DIR_;
     }
     // Add the CSS directory for mobile
     if ($this->useMobileTheme()) {
         $assign_array['css_mobile_dir'] = _THEME_MOBILE_CSS_DIR_;
     }
     foreach ($assign_array as $assign_key => $assign_value) {
         if (substr($assign_value, 0, 1) == '/' || $protocol_content == 'https://') {
             $this->context->smarty->assign($assign_key, $protocol_content . Tools::getMediaServer($assign_value) . $assign_value);
         } else {
             $this->context->smarty->assign($assign_key, $assign_value);
         }
     }
     /*
      * These shortcuts are DEPRECATED as of version 1.5.
      * Use the Context to access objects instead.
      * Example: $this->context->cart
      */
     self::$cookie = $this->context->cookie;
     self::$cart = $cart;
     self::$smarty = $this->context->smarty;
     self::$link = $link;
     $defaultCountry = $this->context->country;
     $this->displayMaintenancePage();
     if ($this->restrictedCountry) {
         $this->displayRestrictedCountryPage();
     }
     if (Tools::isSubmit('live_edit') && !$this->checkLiveEditAccess()) {
         Tools::redirect('index.php?controller=404');
     }
     $this->iso = $iso;
     $this->context->cart = $cart;
     $this->context->currency = $currency;
 }
Ejemplo n.º 30
0
 /**
  * Process login
  */
 protected function processSubmitLogin()
 {
     Hook::exec('actionBeforeAuthentication');
     $passwd = trim(Tools::getValue('passwd'));
     $email = trim(Tools::getValue('email'));
     if (empty($email)) {
         $this->errors[] = Tools::displayError('E-mail address required');
     } elseif (!Validate::isEmail($email)) {
         $this->errors[] = Tools::displayError('Invalid e-mail address');
     } elseif (empty($passwd)) {
         $this->errors[] = Tools::displayError('Password is required');
     } elseif (!Validate::isPasswd($passwd)) {
         $this->errors[] = Tools::displayError('Invalid password');
     } else {
         $customer = new Customer();
         $authentication = $customer->getByEmail(trim($email), trim($passwd));
         if (!$authentication || !$customer->id) {
             $this->errors[] = Tools::displayError('Authentication failed');
         } else {
             $this->context->cookie->id_compare = isset($this->context->cookie->id_compare) ? $this->context->cookie->id_compare : CompareProduct::getIdCompareByIdCustomer($customer->id);
             $this->context->cookie->id_customer = (int) $customer->id;
             $this->context->cookie->customer_lastname = $customer->lastname;
             $this->context->cookie->customer_firstname = $customer->firstname;
             $this->context->cookie->logged = 1;
             $customer->logged = 1;
             $this->context->cookie->is_guest = $customer->isGuest();
             $this->context->cookie->passwd = $customer->passwd;
             $this->context->cookie->email = $customer->email;
             // Add customer to the context
             $this->context->customer = $customer;
             if (Configuration::get('PS_CART_FOLLOWING') && (empty($this->context->cookie->id_cart) || Cart::getNbProducts($this->context->cookie->id_cart) == 0)) {
                 $this->context->cookie->id_cart = (int) Cart::lastNoneOrderedCart($this->context->customer->id);
             }
             // Update cart address
             $this->context->cart->id = $this->context->cookie->id_cart;
             $this->context->cart->setDeliveryOption(null);
             $this->context->cart->id_address_delivery = Address::getFirstCustomerAddressId((int) $customer->id);
             $this->context->cart->id_address_invoice = Address::getFirstCustomerAddressId((int) $customer->id);
             $this->context->cart->secure_key = $customer->secure_key;
             $this->context->cart->update();
             $this->context->cart->autosetProductAddress();
             Hook::exec('actionAuthentication');
             // Login information have changed, so we check if the cart rules still apply
             CartRule::autoRemoveFromCart($this->context);
             CartRule::autoAddToCart($this->context);
             if (!$this->ajax) {
                 if ($back = Tools::getValue('back')) {
                     Tools::redirect(html_entity_decode($back));
                 }
                 Tools::redirect('index.php?controller=my-account');
             }
         }
     }
     if ($this->ajax) {
         $return = array('hasError' => !empty($this->errors), 'errors' => $this->errors, 'token' => Tools::getToken(false));
         die(Tools::jsonEncode($return));
     } else {
         $this->context->smarty->assign('authentification_error', $this->errors);
     }
 }