public function hookProductFooter($params) { $id_product = (int) $params['product']->id; $product = $params['product']; if (isset($params['product']->id_manufacturer) && $params['product']->id_manufacturer) { $cache_id = 'productsmanufacturer|' . $id_product . '|' . (int) $params['product']->id_manufacturer; if (!$this->isCached('productsmanufacturer.tpl', $this->getCacheId($cache_id))) { // Get infos $manufacturer_products = Manufacturer::getProducts($params['product']->id_manufacturer, $this->context->language->id, 1, Configuration::get('pmslid_limit')); /* 100 products max. */ // Remove current product from the list if (is_array($manufacturer_products) && count($manufacturer_products)) { foreach ($manufacturer_products as $key => $manufacturer_product) { if ($manufacturer_product['id_product'] == $id_product) { unset($manufacturer_products[$key]); break; } } $taxes = Product::getTaxCalculationMethod(); if (!Configuration::get('pmslid_DISPLAY_PRICE')) { foreach ($manufacturer_products as $key => $manufacturer_product) { if ($manufacturer_product['id_product'] != $id_product) { $manufacturer_products[$key]['show_price'] = 0; } } } } // Display tpl $this->smarty->assign(array('manufacturer_products' => $manufacturer_products, 'ProdDisplayPrice' => Configuration::get('pmslid_DISPLAY_PRICE'))); } return $this->display(__FILE__, 'productsmanufacturer.tpl', $this->getCacheId($cache_id)); } }
public function setProduct($product, $combination) { // create the product $context = Context::getContext(); $this->give_it_product = new GiveItSdkProduct(); $this->give_it_product->setCurrency($context->currency->iso_code); $usetax = Product::getTaxCalculationMethod((int) $context->customer->id) != PS_TAX_EXC; if ($combination['id_product_attribute'] == 0) { $combination['attributes'] = ''; $image = Product::getCover($product->id); } else { $comb = new Combination($combination['id_product_attribute']); if ($image = $comb->getWsImages()) { $image = $image[0]; $image['id_image'] = $image['id']; } } $image['id_product'] = $product->id; $image['id_image'] = Product::defineProductImage($image, Context::getContext()->language->id); $img_profile = version_compare(_PS_VERSION_, '1.5', '<') ? 'home' : ImageType::getFormatedName('medium'); $image = $image ? $context->link->getImageLink($product->link_rewrite, $image['id_image'], $img_profile) : ''; // first, set the product details. $this->give_it_product->setProductDetails(array('code' => $product->id . '_' . $combination['id_product_attribute'], 'price' => (int) (Product::getPriceStatic((int) $product->id, $usetax, $combination['id_product_attribute']) * 100), 'name' => $product->name . ($combination['attributes'] ? ' : ' . $combination['attributes'] : ''), 'image' => $image)); $delivery = $this->setDelivery(); // add the delivery option to the product $this->give_it_product->addBuyerOption($delivery); //We should validate this product $this->product_valid = $this->give_it_product->validate(); }
public static function getCartNbPoints($cart, $newProduct = NULL) { $total = 0; if (Validate::isLoadedObject($cart)) { $cartProducts = $cart->getProducts(); $taxesEnabled = Product::getTaxCalculationMethod(); if (isset($newProduct) and !empty($newProduct)) { $cartProductsNew['id_product'] = (int) $newProduct->id; if ($taxesEnabled == PS_TAX_EXC) { $cartProductsNew['price'] = number_format($newProduct->getPrice(false, (int) $newProduct->getIdProductAttributeMostExpensive()), 2, '.', ''); } else { $cartProductsNew['price_wt'] = number_format($newProduct->getPrice(true, (int) $newProduct->getIdProductAttributeMostExpensive()), 2, '.', ''); } $cartProductsNew['cart_quantity'] = 1; $cartProducts[] = $cartProductsNew; } foreach ($cartProducts as $product) { if (!(int) Configuration::get('PS_LOYALTY_NONE_AWARD') and Product::isDiscounted((int) $product['id_product'])) { global $smarty; if (isset($smarty) and is_object($newProduct) and $product['id_product'] == $newProduct->id) { $smarty->assign('no_pts_discounted', 1); } continue; } $total += self::getNbPointsByPrice($taxesEnabled == PS_TAX_EXC ? $product['price'] : $product['price_wt']) * (int) $product['cart_quantity']; } foreach ($cart->getDiscounts(false) as $discount) { $total -= self::getNbPointsByPrice($discount['value_real']); } } return $total; }
public function includeTaxes() { if (!Configuration::get('PS_TAX')) { return false; } return !Product::getTaxCalculationMethod(Context::getContext()->cookie->id_customer); }
protected function _assignSummaryInformations() { $summary = $this->context->cart->getSummaryDetails(); $customizedDatas = Product::getAllCustomizedDatas($this->context->cart->id); // override customization tax rate with real tax (tax rules) if ($customizedDatas) { foreach ($summary['products'] as &$productUpdate) { $productId = (int) isset($productUpdate['id_product']) ? $productUpdate['id_product'] : $productUpdate['product_id']; $productAttributeId = (int) isset($productUpdate['id_product_attribute']) ? $productUpdate['id_product_attribute'] : $productUpdate['product_attribute_id']; if (isset($customizedDatas[$productId][$productAttributeId])) { $productUpdate['tax_rate'] = Tax::getProductTaxRate($productId, $this->context->cart->{Configuration::get('PS_TAX_ADDRESS_TYPE')}); } } Product::addCustomizationPrice($summary['products'], $customizedDatas); } $cart_product_context = Context::getContext()->cloneContext(); foreach ($summary['products'] as $key => &$product) { $product['quantity'] = $product['cart_quantity']; // for compatibility with 1.2 themes if ($cart_product_context->shop->id != $product['id_shop']) { $cart_product_context->shop = new Shop((int) $product['id_shop']); } $product['price_without_specific_price'] = Product::getPriceStatic($product['id_product'], !Product::getTaxCalculationMethod(), $product['id_product_attribute'], _PS_PRICE_COMPUTE_PRECISION_, null, false, false, 1, false, null, null, null, $null, true, true, $cart_product_context); /** * ABU edit: variable is_discount set à 1 à tord, calcul foireux de presta * @bugfix: https://github.com/PrestaShop/PrestaShop/commit/379e28b341730ea95c0b2d6567817305ea841b23 * @perso: soustraction de l'ecotax au price_without_specific_price @else */ if (Product::getTaxCalculationMethod()) { // $product['is_discounted'] = $product['price_without_specific_price'] != Tools::ps_round($product['price'], _PS_PRICE_COMPUTE_PRECISION_); $product['is_discounted'] = Tools::ps_round($product['price_without_specific_price'], _PS_PRICE_COMPUTE_PRECISION_) != Tools::ps_round($product['price'], _PS_PRICE_COMPUTE_PRECISION_); } else { // $product['is_discounted'] = $product['price_without_specific_price'] != Tools::ps_round($product['price_wt'], _PS_PRICE_COMPUTE_PRECISION_); $product['is_discounted'] = Tools::ps_round($product['price_without_specific_price'] - $product['ecotax'], _PS_PRICE_COMPUTE_PRECISION_) != Tools::ps_round($product['price_wt'], _PS_PRICE_COMPUTE_PRECISION_); } } // Get available cart rules and unset the cart rules already in the cart $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); $cart_cart_rules = $this->context->cart->getCartRules(); foreach ($available_cart_rules as $key => $available_cart_rule) { if (!$available_cart_rule['highlight'] || strpos($available_cart_rule['code'], CartRule::BO_ORDER_CODE_PREFIX) === 0) { unset($available_cart_rules[$key]); continue; } foreach ($cart_cart_rules as $cart_cart_rule) { if ($available_cart_rule['id_cart_rule'] == $cart_cart_rule['id_cart_rule']) { unset($available_cart_rules[$key]); continue 2; } } } $show_option_allow_separate_package = !$this->context->cart->isAllProductsInStock(true) && Configuration::get('PS_SHIP_WHEN_AVAILABLE'); $this->context->smarty->assign($summary); $this->context->smarty->assign(array('token_cart' => Tools::getToken(false), 'isLogged' => $this->isLogged, 'isVirtualCart' => $this->context->cart->isVirtualCart(), 'productNumber' => $this->context->cart->nbProducts(), 'voucherAllowed' => CartRule::isFeatureActive(), 'shippingCost' => $this->context->cart->getOrderTotal(true, Cart::ONLY_SHIPPING), 'shippingCostTaxExc' => $this->context->cart->getOrderTotal(false, Cart::ONLY_SHIPPING), 'customizedDatas' => $customizedDatas, 'CUSTOMIZE_FILE' => Product::CUSTOMIZE_FILE, 'CUSTOMIZE_TEXTFIELD' => Product::CUSTOMIZE_TEXTFIELD, 'lastProductAdded' => $this->context->cart->getLastProduct(), 'displayVouchers' => $available_cart_rules, 'show_option_allow_separate_package' => $show_option_allow_separate_package, 'smallSize' => Image::getSize(ImageType::getFormatedName('small')))); $this->context->smarty->assign(array('HOOK_SHOPPING_CART' => Hook::exec('displayShoppingCartFooter', $summary), 'HOOK_SHOPPING_CART_EXTRA' => Hook::exec('displayShoppingCart', $summary))); }
private function bootstrap() { $translator = $this->getTranslator(); $session = $this->getCheckoutSession(); $this->checkoutProcess = new CheckoutProcess($this->context, $session); $this->checkoutProcess->addStep(new CheckoutPersonalInformationStep($this->context, $translator, $this->makeLoginForm(), $this->makeCustomerForm()))->addStep(new CheckoutAddressesStep($this->context, $translator, $this->makeAddressForm())); if (!$this->context->cart->isVirtualCart()) { $checkoutDeliveryStep = new CheckoutDeliveryStep($this->context, $translator); $checkoutDeliveryStep->setRecyclablePackAllowed((bool) Configuration::get('PS_RECYCLABLE_PACK'))->setGiftAllowed((bool) Configuration::get('PS_GIFT_WRAPPING'))->setIncludeTaxes(!Product::getTaxCalculationMethod((int) $this->context->cart->id_customer) && (int) Configuration::get('PS_TAX'))->setDisplayTaxesLabel(Configuration::get('PS_TAX') && !Configuration::get('AEUC_LABEL_TAX_INC_EXC'))->setGiftCost($this->context->cart->getGiftWrappingPrice($checkoutDeliveryStep->getIncludeTaxes())); $this->checkoutProcess->addStep($checkoutDeliveryStep); } $this->checkoutProcess->addStep(new CheckoutPaymentStep($this->context, $translator, new PaymentOptionsFinder(), new ConditionsToApproveFinder($this->context, $translator))); }
public function getDeliveryOptions() { $delivery_option_list = $this->context->cart->getDeliveryOptionList(); $include_taxes = !Product::getTaxCalculationMethod((int) $this->context->cart->id_customer) && (int) Configuration::get('PS_TAX'); $display_taxes_label = Configuration::get('PS_TAX') && !Configuration::get('AEUC_LABEL_TAX_INC_EXC'); $carriers_available = array(); if (isset($delivery_option_list[$this->context->cart->id_address_delivery])) { foreach ($delivery_option_list[$this->context->cart->id_address_delivery] as $id_carriers_list => $carriers_list) { foreach ($carriers_list as $carriers) { if (is_array($carriers)) { foreach ($carriers as $carrier) { $carrier = array_merge($carrier, $this->objectPresenter->present($carrier['instance'])); $delay = $carrier['delay'][$this->context->language->id]; unset($carrier['instance'], $carrier['delay']); $carrier['delay'] = $delay; if ($this->isFreeShipping($this->context->cart, $carriers_list)) { $carrier['price'] = $this->translator->trans('Free', array(), 'Shop.Theme.Checkout'); } else { if ($include_taxes) { $carrier['price'] = $this->priceFormatter->convertAndFormat($carriers_list['total_price_with_tax']); if ($display_taxes_label) { $carrier['price'] = sprintf($this->translator->trans('%s tax incl.', array(), 'Shop.Theme.Checkout'), $carrier['price']); } } else { $carrier['price'] = $this->priceFormatter->convertAndFormat($carriers_list['total_price_without_tax']); if ($display_taxes_label) { $carrier['price'] = sprintf($this->translator->trans('%s tax excl.', array(), 'Shop.Theme.Checkout'), $carrier['price']); } } } if (count($carriers) > 1) { $carrier['label'] = $carrier['price']; } else { $carrier['label'] = $carrier['name'] . ' - ' . $carrier['delay'] . ' - ' . $carrier['price']; } // If carrier related to a module, check for additionnal data to display $carrier['extraContent'] = ''; if ($carrier['is_module']) { if ($moduleId = Module::getModuleIdByName($carrier['external_module_name'])) { $carrier['extraContent'] = Hook::exec('displayCarrierExtraContent', array('carrier' => $carrier), $moduleId); } } $carriers_available[$id_carriers_list] = $carrier; } } } } } return $carriers_available; }
protected function getBestSellers($params) { if (Configuration::get('PS_CATALOG_MODE')) { return false; } if (!($result = ProductSale::getBestSalesLight((int) $params['cookie']->id_lang, 0, 3))) { return Configuration::get('PS_BLOCK_BESTSELLERS_DISPLAY') ? array() : false; } $currency = new Currency($params['cookie']->id_currency); $usetax = Product::getTaxCalculationMethod((int) $this->context->customer->id) != PS_TAX_EXC; foreach ($result as &$row) { $row['price'] = Tools::displayPrice(Product::getPriceStatic((int) $row['id_product'], $usetax), $currency); } return $result; }
public static function getCartNbPoints($cart, $newProduct = NULL) { $total = 0; if (Validate::isLoadedObject($cart)) { $currentContext = Context::getContext(); $context = clone $currentContext; $context->cart = $cart; // if customer is logged we do not recreate it if (!$context->customer->isLogged(true)) { $context->customer = new Customer($context->cart->id_customer); } $context->language = new Language($context->cart->id_lang); $context->shop = new Shop($context->cart->id_shop); $context->currency = new Currency($context->cart->id_currency, null, $context->shop->id); $cartProducts = $cart->getProducts(); $taxesEnabled = Product::getTaxCalculationMethod(); if (isset($newProduct) and !empty($newProduct)) { $cartProductsNew['id_product'] = (int) $newProduct->id; if ($taxesEnabled == PS_TAX_EXC) { $cartProductsNew['price'] = number_format($newProduct->getPrice(false, (int) $newProduct->getIdProductAttributeMostExpensive()), 2, '.', ''); } else { $cartProductsNew['price_wt'] = number_format($newProduct->getPrice(true, (int) $newProduct->getIdProductAttributeMostExpensive()), 2, '.', ''); } $cartProductsNew['cart_quantity'] = 1; $cartProducts[] = $cartProductsNew; } foreach ($cartProducts as $product) { if (!(int) Configuration::get('PS_LOYALTY_NONE_AWARD') and Product::isDiscounted((int) $product['id_product'])) { if (isset(Context::getContext()->smarty) and is_object($newProduct) and $product['id_product'] == $newProduct->id) { Context::getContext()->smarty->assign('no_pts_discounted', 1); } continue; } $total += ($taxesEnabled == PS_TAX_EXC ? $product['price'] : $product['price_wt']) * (int) $product['cart_quantity']; } foreach ($cart->getCartRules(false) as $cart_rule) { if ($taxesEnabled == PS_TAX_EXC) { $total -= $cart_rule['value_tax_exc']; } else { $total -= $cart_rule['value_real']; } } } return self::getNbPointsByPrice($total); }
protected function setDetailProductPrice(Order $order, Cart $cart, $product) { $this->setContext((int) $product['id_shop']); $specific_price = $null = null; Product::getPriceStatic((int) $product['id_product'], true, (int) $product['id_product_attribute'], 6, null, false, true, array($product['cart_quantity'], $product['cart_quantity_fractional']), false, (int) $order->id_customer, (int) $order->id_cart, (int) $order->{Configuration::get('PS_TAX_ADDRESS_TYPE')}, $specific_price, true, true, $this->context); $this->specificPrice = $specific_price; $this->original_product_price = Product::getPriceStatic($product['id_product'], false, (int) $product['id_product_attribute'], 6, null, false, false, 1, false, null, null, null, $null, true, true, $this->context); $this->product_price = $this->original_product_price; $this->unit_price_tax_incl = (double) $product['price_wt']; $this->unit_price_tax_excl = (double) $product['price']; $this->total_price_tax_incl = (double) $product['total_wt']; $this->total_price_tax_excl = (double) $product['total']; $this->purchase_supplier_price = (double) $product['wholesale_price']; if ($product['id_supplier'] > 0 && ($supplier_price = ProductSupplier::getProductPrice((int) $product['id_supplier'], $product['id_product'], $product['id_product_attribute'], true)) > 0) { $this->purchase_supplier_price = (double) $supplier_price; } $this->setSpecificPrice($order, $product); $this->group_reduction = (double) Group::getReduction((int) $order->id_customer); $shop_id = $this->context->shop->id; $quantity_discount = SpecificPrice::getQuantityDiscount((int) $product['id_product'], $shop_id, (int) $cart->id_currency, (int) $this->vat_address->id_country, (int) $this->customer->id_default_group, (int) PP::resolveQty($product['cart_quantity'], $product['cart_quantity_fractional']), false, null, null, $null, true, true, $this->context); $unit_price = Product::getPriceStatic((int) $product['id_product'], true, $product['id_product_attribute'] ? (int) $product['id_product_attribute'] : null, 2, null, false, true, 1, false, (int) $order->id_customer, null, (int) $order->{Configuration::get('PS_TAX_ADDRESS_TYPE')}, $null, true, true, $this->context); $this->product_quantity_discount = 0.0; if ($quantity_discount) { $this->product_quantity_discount = $unit_price; if (Product::getTaxCalculationMethod((int) $order->id_customer) == PS_TAX_EXC) { $this->product_quantity_discount = Tools::ps_round($unit_price, 2); } if (isset($this->tax_calculator)) { $this->product_quantity_discount -= $this->tax_calculator->addTaxes($quantity_discount['price']); } } $this->discount_quantity_applied = $this->specificPrice && $this->specificPrice['from_quantity'] > PP::getSpecificPriceFromQty((int) $product['id_product']) ? 1 : 0; $this->id_cart_product = (int) $product['id_cart_product']; $this->product_quantity_fractional = (double) $product['cart_quantity_fractional']; $ppropertiessmartprice_hook3 = null; }
/** * Returns module content for left column */ public function hookProductFooter($params) { $cache_id = 'crossselling_mod|productfooter|' . (int) $params['product']->id; if (!$this->isCached('crossselling_mod.tpl', $this->getCacheId($cache_id))) { $orders = Db::getInstance(_PS_USE_SQL_SLAVE_)->executeS('SELECT o.id_order FROM ' . _DB_PREFIX_ . 'orders o LEFT JOIN ' . _DB_PREFIX_ . 'order_detail od ON (od.id_order = o.id_order) WHERE o.valid = 1 AND od.product_id = ' . (int) $params['product']->id); if (count($orders)) { $list = ''; foreach ($orders as $order) { $list .= (int) $order['id_order'] . ','; } $list = rtrim($list, ','); if (Group::isFeatureActive()) { $sql_groups_join = ' LEFT JOIN `' . _DB_PREFIX_ . 'category_product` cp ON (cp.`id_category` = product_shop.id_category_default AND cp.id_product = product_shop.id_product) LEFT JOIN `' . _DB_PREFIX_ . 'category_group` cg ON (cp.`id_category` = cg.`id_category`)'; $groups = FrontController::getCurrentCustomerGroups(); $sql_groups_where = 'AND cg.`id_group` ' . (count($groups) ? 'IN (' . implode(',', $groups) . ')' : '=' . (int) Group::getCurrent()->id); } $order_products = Db::getInstance(_PS_USE_SQL_SLAVE_)->executeS('SELECT DISTINCT od.product_id, pl.name, pl.link_rewrite, p.reference, i.id_image, product_shop.show_price, product_shop.id_category_default, p.available_for_order, p.customizable, cl.link_rewrite category, p.ean13, stock.out_of_stock, IFNULL(stock.quantity, 0) as quantity FROM ' . _DB_PREFIX_ . 'order_detail od LEFT JOIN ' . _DB_PREFIX_ . 'product p ON (p.id_product = od.product_id) ' . Shop::addSqlAssociation('product', 'p') . (Combination::isFeatureActive() ? 'LEFT JOIN `' . _DB_PREFIX_ . 'product_attribute` pa ON (p.`id_product` = pa.`id_product`) ' . Shop::addSqlAssociation('product_attribute', 'pa', false, 'product_attribute_shop.`default_on` = 1') . ' ' . Product::sqlStock('p', 'product_attribute_shop', false, $this->context->shop) : Product::sqlStock('p', 'product', false, $this->context->shop)) . ' LEFT JOIN ' . _DB_PREFIX_ . 'product_lang pl ON (pl.id_product = od.product_id' . Shop::addSqlRestrictionOnLang('pl') . ') LEFT JOIN ' . _DB_PREFIX_ . 'category_lang cl ON (cl.id_category = product_shop.id_category_default' . Shop::addSqlRestrictionOnLang('cl') . ') LEFT JOIN ' . _DB_PREFIX_ . 'image i ON (i.id_product = od.product_id) ' . (Group::isFeatureActive() ? $sql_groups_join : '') . ' WHERE od.id_order IN (' . $list . ') AND pl.id_lang = ' . (int) $this->context->language->id . ' AND cl.id_lang = ' . (int) $this->context->language->id . ' AND od.product_id != ' . (int) $params['product']->id . ' AND i.cover = 1 AND product_shop.active = 1 ' . (Group::isFeatureActive() ? $sql_groups_where : '') . ' ORDER BY RAND() LIMIT ' . (int) Configuration::get('CROSSSELLING_NBR_M')); $tax_calc = Product::getTaxCalculationMethod(); foreach ($order_products as &$order_product) { $order_product['id_product'] = (int) $order_product['product_id']; $order_product['image'] = $this->context->link->getImageLink($order_product['link_rewrite'], (int) $order_product['product_id'] . '-' . (int) $order_product['id_image'], ImageType::getFormatedName('home')); $order_product['link'] = $this->context->link->getProductLink((int) $order_product['product_id'], $order_product['link_rewrite'], $order_product['category'], $order_product['ean13']); if ($tax_calc == 0 || $tax_calc == 2) { $order_product['price'] = Product::getPriceStatic((int) $order_product['product_id'], true, null); } elseif ($tax_calc == 1) { $order_product['price'] = Product::getPriceStatic((int) $order_product['product_id'], false, null); } $order_product['allow_oosp'] = Product::isAvailableWhenOutOfStock((int) $order_product['out_of_stock']); } $order_products = Product::getProductsProperties((int) $this->context->language->id, $order_products); $this->smarty->assign(array('order' => false, 'orderProducts' => $order_products, 'homeSize' => Image::getSize(ImageType::getFormatedName('home')), 'middlePosition_crossselling' => round(count($order_products) / 2, 0), 'crossDisplayPrice' => Configuration::get('CROSSSELLING_DISPLAY_PRICE_M'))); } } return $this->display(__FILE__, 'crossselling_mod.tpl', $this->getCacheId($cache_id)); }
/** * Calculates the price (including tax if applicable) and returns it. * * We need to check if taxes are to be included in the prices, given that they are configured. * This is determined by the "Price display method" setting of the active user group. * Possible values are 1, tax excluded, and 0, tax included. * * @param Product $product the product model. * @param Context $context the context to calculate the price on (currency conversion). * @param bool $discounted_price if discounts should be applied. * @return string the calculated price. */ protected function calcPrice(Product $product, Context $context, $discounted_price = true) { $incl_tax = (bool) (!Product::getTaxCalculationMethod((int) $context->cookie->id_customer)); $specific_price_output = null; $value = Product::getPriceStatic((int) $product->id, $incl_tax, null, 6, null, false, $discounted_price, 1, false, null, null, null, $specific_price_output, true, true, $context, true); return Nosto::helper('price')->format($value); }
/** * Returns module content for left column */ public function hookProductFooter($params) { global $smarty, $cookie, $link; $orders = Db::getInstance(_PS_USE_SQL_SLAVE_)->ExecuteS(' SELECT o.id_order FROM ' . _DB_PREFIX_ . 'orders o LEFT JOIN ' . _DB_PREFIX_ . 'order_detail od ON (od.id_order = o.id_order) WHERE o.valid = 1 AND od.product_id = ' . (int) $params['product']->id); if (sizeof($orders)) { $list = ''; foreach ($orders as $order) { $list .= (int) $order['id_order'] . ','; } $list = rtrim($list, ','); $orderProducts = Db::getInstance(_PS_USE_SQL_SLAVE_)->ExecuteS(' SELECT DISTINCT od.product_id, pl.name, pl.link_rewrite, p.reference, i.id_image, p.show_price, cl.link_rewrite category, p.ean13 FROM ' . _DB_PREFIX_ . 'order_detail od LEFT JOIN ' . _DB_PREFIX_ . 'product p ON (p.id_product = od.product_id) LEFT JOIN ' . _DB_PREFIX_ . 'product_lang pl ON (pl.id_product = od.product_id) LEFT JOIN ' . _DB_PREFIX_ . 'category_lang cl ON (cl.id_category = p.id_category_default) LEFT JOIN ' . _DB_PREFIX_ . 'image i ON (i.id_product = od.product_id) WHERE od.id_order IN (' . $list . ') AND pl.id_lang = ' . (int) $cookie->id_lang . ' AND cl.id_lang = ' . (int) $cookie->id_lang . ' AND od.product_id != ' . (int) $params['product']->id . ' AND i.cover = 1 AND p.active = 1 ORDER BY RAND() LIMIT 10'); $taxCalc = Product::getTaxCalculationMethod(); foreach ($orderProducts as &$orderProduct) { $orderProduct['image'] = $link->getImageLink($orderProduct['link_rewrite'], (int) $orderProduct['product_id'] . '-' . (int) $orderProduct['id_image'], 'medium'); $orderProduct['link'] = $link->getProductLink((int) $orderProduct['product_id'], $orderProduct['link_rewrite'], $orderProduct['category'], $orderProduct['ean13']); if (Configuration::get('CROSSSELLING_DISPLAY_PRICE') and ($taxCalc == 0 or $taxCalc == 2)) { $orderProduct['displayed_price'] = Product::getPriceStatic((int) $orderProduct['product_id'], true, NULL); } elseif (Configuration::get('CROSSSELLING_DISPLAY_PRICE') and $taxCalc == 1) { $orderProduct['displayed_price'] = Product::getPriceStatic((int) $orderProduct['product_id'], false, NULL); } } $smarty->assign(array('orderProducts' => $orderProducts, 'middlePosition_crossselling' => round(sizeof($orderProducts) / 2, 0), 'crossDisplayPrice' => Configuration::get('CROSSSELLING_DISPLAY_PRICE'))); } return $this->display(__FILE__, 'crossselling.tpl'); }
public function hookExtraRight($params) { include_once dirname(__FILE__) . '/LoyaltyModule.php'; $product = new Product((int) Tools::getValue('id_product')); if (Validate::isLoadedObject($product)) { if (Validate::isLoadedObject($params['cart'])) { $pointsBefore = (int) LoyaltyModule::getCartNbPoints($params['cart']); $pointsAfter = (int) LoyaltyModule::getCartNbPoints($params['cart'], $product); $points = (int) ($pointsAfter - $pointsBefore); } else { if (!(int) Configuration::get('PS_LOYALTY_NONE_AWARD') && Product::isDiscounted((int) $product->id)) { $points = 0; $this->smarty->assign('no_pts_discounted', 1); } else { $points = (int) LoyaltyModule::getNbPointsByPrice($product->getPrice(Product::getTaxCalculationMethod() == PS_TAX_EXC ? false : true, (int) $product->getDefaultIdProductAttribute())); } $pointsAfter = $points; $pointsBefore = 0; } $this->smarty->assign(array('points' => (int) $points, 'total_points' => (int) $pointsAfter, 'point_rate' => Configuration::get('PS_LOYALTY_POINT_RATE'), 'point_value' => Configuration::get('PS_LOYALTY_POINT_VALUE'), 'points_in_cart' => (int) $pointsBefore, 'voucher' => LoyaltyModule::getVoucherValue((int) $pointsAfter), 'none_award' => Configuration::get('PS_LOYALTY_NONE_AWARD'))); return $this->display(__FILE__, 'product.tpl'); } return false; }
public function hookDisplayProductButtons($params) { $taxes = Product::getTaxCalculationMethod(); $id_product = (int) Tools::getValue('id_product'); if ($taxes == 0 || $taxes == 2) { $askforprice_product_price = Product::getPriceStatic($id_product, true, null, 2); } elseif ($taxes == 1) { $askforprice_product_price = Product::getPriceStatic($id_product, false, null, 2); } $this->context->smarty->assign(array('ASKFORPRICE_MINIMAL_PRICE' => Configuration::get('ASKFORPRICE_MINIMAL_PRICE', null), 'askforprice_product_price' => $askforprice_product_price, 'askforprice_form_url' => $this->context->link->getModuleLink('askforprice', 'form', array('id_product' => $id_product)))); return $this->display($this->_path, 'views/templates/front/askforprice.tpl'); }
public function displayAjax() { if ($this->errors) { $this->ajaxDie(Tools::jsonEncode(array('hasError' => true, 'errors' => $this->errors))); } if ($this->ajax_refresh) { $this->ajaxDie(Tools::jsonEncode(array('refresh' => true))); } $this->context->cookie->write(); if (Tools::getIsset('summary')) { $result = array(); if (Configuration::get('PS_ORDER_PROCESS_TYPE') == 1) { $groups = Validate::isLoadedObject($this->context->customer) ? $this->context->customer->getGroups() : array(1); if ($this->context->cart->id_address_delivery) { $delivery_address = new Address($this->context->cart->id_address_delivery); } $id_country = isset($delivery_address) && $delivery_address->id ? (int) $delivery_address->id_country : (int) Tools::getCountry(); Cart::addExtraCarriers($result); } $result['summary'] = $this->context->cart->getSummaryDetails(null, true); $result['customizedDatas'] = Product::getAllCustomizedDatas($this->context->cart->id, null, true); $result['HOOK_SHOPPING_CART'] = Hook::exec('displayShoppingCartFooter', $result['summary']); $result['HOOK_SHOPPING_CART_EXTRA'] = Hook::exec('displayShoppingCart', $result['summary']); foreach ($result['summary']['products'] as $key => &$product) { $product['quantity_without_customization'] = $product['quantity']; if ($result['customizedDatas'] && isset($result['customizedDatas'][(int) $product['id_product']][(int) $product['id_product_attribute']])) { foreach ($result['customizedDatas'][(int) $product['id_product']][(int) $product['id_product_attribute']] as $addresses) { foreach ($addresses as $customization) { if ($product['id_cart_product'] == $customization['id_cart_product']) { $product['quantity_without_customization'] -= (int) $customization['quantity']; } } } } $product['price_without_quantity_discount'] = Product::getPriceStatic($product['id_product'], !Product::getTaxCalculationMethod(), $product['id_product_attribute'], 6, null, false, false); $ppropertiessmartprice_hook1 = null; if ($product['reduction_type'] == 'amount') { $reduction = (double) $product['price_wt'] - (double) $product['price_without_quantity_discount']; $product['reduction_formatted'] = Tools::displayPrice($reduction); } } if ($result['customizedDatas']) { Product::addCustomizationPrice($result['summary']['products'], $result['customizedDatas']); } $json = null; Hook::exec('actionCartListOverride', array('summary' => $result, 'json' => &$json)); $this->ajaxDie(Tools::jsonEncode(array_merge($result, (array) Tools::jsonDecode($json, true)))); } elseif (file_exists(_PS_MODULE_DIR_ . '/blockcart/blockcart-ajax.php')) { $context = Context::getContext(); $cart = $context->cart; if ($cart && isset($cart->last_icp)) { $context->smarty->assign('last_icp', $cart->last_icp); } require_once _PS_MODULE_DIR_ . '/blockcart/blockcart-ajax.php'; } }
protected function _assignSummaryInformations() { $summary = $this->context->cart->getSummaryDetails(); $customizedDatas = Product::getAllCustomizedDatas($this->context->cart->id); // override customization tax rate with real tax (tax rules) if ($customizedDatas) { foreach ($summary['products'] as &$productUpdate) { $productId = (int) (isset($productUpdate['id_product']) ? $productUpdate['id_product'] : $productUpdate['product_id']); $productAttributeId = (int) (isset($productUpdate['id_product_attribute']) ? $productUpdate['id_product_attribute'] : $productUpdate['product_attribute_id']); if (isset($customizedDatas[$productId][$productAttributeId])) { $productUpdate['tax_rate'] = Tax::getProductTaxRate($productId, $this->context->cart->{Configuration::get('PS_TAX_ADDRESS_TYPE')}); } } Product::addCustomizationPrice($summary['products'], $customizedDatas); } $cart_product_context = Context::getContext()->cloneContext(); foreach ($summary['products'] as $key => &$product) { $product['quantity'] = $product['cart_quantity']; // for compatibility with 1.2 themes if ($cart_product_context->shop->id != $product['id_shop']) { $cart_product_context->shop = new Shop((int) $product['id_shop']); } $product['price_without_specific_price'] = Product::getPriceStatic($product['id_product'], !Product::getTaxCalculationMethod(), $product['id_product_attribute'], 2, null, false, false, 1, false, null, null, null, $null, true, true, $cart_product_context); if (Product::getTaxCalculationMethod()) { $product['is_discounted'] = $product['price_without_specific_price'] != $product['price']; } else { $product['is_discounted'] = $product['price_without_specific_price'] != $product['price_wt']; } } // Get available cart rules and unset the cart rules already in the cart $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); $cart_cart_rules = $this->context->cart->getCartRules(); foreach ($available_cart_rules as $key => $available_cart_rule) { if (!$available_cart_rule['highlight'] || strpos($available_cart_rule['code'], 'BO_ORDER_') === 0) { unset($available_cart_rules[$key]); continue; } foreach ($cart_cart_rules as $cart_cart_rule) { if ($available_cart_rule['id_cart_rule'] == $cart_cart_rule['id_cart_rule']) { unset($available_cart_rules[$key]); continue 2; } } } $show_option_allow_separate_package = !$this->context->cart->isAllProductsInStock(true) && Configuration::get('PS_SHIP_WHEN_AVAILABLE'); $this->context->smarty->assign($summary); $this->context->smarty->assign(array('token_cart' => Tools::getToken(false), 'isLogged' => $this->isLogged, 'isVirtualCart' => $this->context->cart->isVirtualCart(), 'productNumber' => $this->context->cart->nbProducts(), 'voucherAllowed' => CartRule::isFeatureActive(), 'shippingCost' => $this->context->cart->getOrderTotal(true, Cart::ONLY_SHIPPING), 'shippingCostTaxExc' => $this->context->cart->getOrderTotal(false, Cart::ONLY_SHIPPING), 'customizedDatas' => $customizedDatas, 'CUSTOMIZE_FILE' => Product::CUSTOMIZE_FILE, 'CUSTOMIZE_TEXTFIELD' => Product::CUSTOMIZE_TEXTFIELD, 'lastProductAdded' => $this->context->cart->getLastProduct(), 'displayVouchers' => $available_cart_rules, 'currencySign' => $this->context->currency->sign, 'currencyRate' => $this->context->currency->conversion_rate, 'currencyFormat' => $this->context->currency->format, 'currencyBlank' => $this->context->currency->blank, 'show_option_allow_separate_package' => $show_option_allow_separate_package, 'smallSize' => Image::getSize(ImageType::getFormatedName('small')))); $this->context->smarty->assign(array('HOOK_SHOPPING_CART' => Hook::exec('displayShoppingCartFooter', $summary), 'HOOK_SHOPPING_CART_EXTRA' => Hook::exec('displayShoppingCart', $summary))); }
public static function getRetailPrice($product) { $price_display = Product::getTaxCalculationMethod(); return $product->getPrice(!$price_display || $price_display == 2, false, _PS_PRICE_DISPLAY_PRECISION_); }
public function hookProductFooter($params) { $id_product = (int) $params['product']->id; $product = $params['product']; $cache_id = 'productscategory|' . $id_product . '|' . (isset($params['category']->id_category) ? (int) $params['category']->id_category : $product->id_category_default); if (!$this->isCached('productscategory.tpl', $this->getCacheId($cache_id))) { $category = false; if (isset($params['category']->id_category)) { $category = $params['category']; } else { if (isset($product->id_category_default) && $product->id_category_default > 1) { $category = new Category((int) $product->id_category_default); } } if (!Validate::isLoadedObject($category) || !$category->active) { return false; } // Get infos $category_products = $category->getProducts($this->context->language->id, 1, 100); /* 100 products max. */ $nb_category_products = (int) count($category_products); $middle_position = 0; // Remove current product from the list if (is_array($category_products) && count($category_products)) { foreach ($category_products as $key => $category_product) { if ($category_product['id_product'] == $id_product) { unset($category_products[$key]); break; } } $taxes = Product::getTaxCalculationMethod(); if (Configuration::get('PRODUCTSCATEGORY_DISPLAY_PRICE')) { foreach ($category_products as $key => $category_product) { if ($category_product['id_product'] != $id_product) { if ($taxes == 0 || $taxes == 2) { $category_products[$key]['displayed_price'] = Product::getPriceStatic((int) $category_product['id_product'], true, null, 2); } elseif ($taxes == 1) { $category_products[$key]['displayed_price'] = Product::getPriceStatic((int) $category_product['id_product'], false, null, 2); } } } } // Get positions $middle_position = (int) round($nb_category_products / 2, 0); $product_position = $this->getCurrentProduct($category_products, (int) $id_product); // Flip middle product with current product if ($product_position) { $tmp = $category_products[$middle_position - 1]; $category_products[$middle_position - 1] = $category_products[$product_position]; $category_products[$product_position] = $tmp; } // If products tab higher than 30, slice it if ($nb_category_products > 30) { $category_products = array_slice($category_products, $middle_position - 15, 30, true); $middle_position = 15; } } // Display tpl $this->smarty->assign(array('categoryProducts' => $category_products, 'middlePosition' => (int) $middle_position, 'ProdDisplayPrice' => Configuration::get('PRODUCTSCATEGORY_DISPLAY_PRICE'))); } return $this->display(__FILE__, 'productscategory.tpl', $this->getCacheId($cache_id)); }
public function init() { global $cookie, $smarty, $cart, $iso, $defaultCountry, $protocol_link, $protocol_content, $link, $css_files, $js_files; if (self::$initialized) { return; } self::$initialized = true; $css_files = array(); $js_files = array(); if ($this->ssl and (empty($_SERVER['HTTPS']) or strtolower($_SERVER['HTTPS']) == 'off') and Configuration::get('PS_SSL_ENABLED')) { header('HTTP/1.1 301 Moved Permanently'); header('Location: ' . Tools::getShopDomainSsl(true) . $_SERVER['REQUEST_URI']); exit; } ob_start(); /* Loading default country */ $defaultCountry = new Country((int) Configuration::get('PS_COUNTRY_DEFAULT'), Configuration::get('PS_LANG_DEFAULT')); $cookie = new Cookie('ps'); $link = new Link(); if ($this->auth and !$cookie->isLogged($this->guestAllowed)) { Tools::redirect('authentication.php' . ($this->authRedirection ? '?back=' . $this->authRedirection : '')); } /* Theme is missing or maintenance */ if (!is_dir(_PS_THEME_DIR_)) { die(Tools::displayError('Current theme unavailable. Please check your theme directory name and permissions.')); } elseif (basename($_SERVER['PHP_SELF']) != 'disabled.php' and !(int) Configuration::get('PS_SHOP_ENABLE')) { $this->maintenance = true; } elseif (Configuration::get('PS_GEOLOCATION_ENABLED')) { if (!isset($cookie->iso_code_country)) { if ($cookie->logged) { $id_country = Customer::getCurrentCountry((int) $cookie->id_customer); $cookie->iso_code_country = Country::getIsoById($id_country); } else { $this->geolocationManagement(); } } if (!isset($cookie->iso_code_country)) { $current_country_id = Customer::getCurrentCountry((int) $cookie->id_customer); } else { $current_country_id = Country::getByIso($cookie->iso_code_country); } $current_country = new Country($current_country_id, 1); $cookie->id_country = $current_country->id; $smarty->assign('current_country', $current_country->name); $smarty->assign('current_country_id', $current_country->id); if ($cookie->id_country == 110 && !isset($cookie->id_currency)) { $cookie->id_currency = 4; } } //set imagesize if not set if (!isset($cookie->image_size)) { $cookie->image_size = IMAGE_SIZE_LARGE; $cookie->write(); } if (!isset($cookie->greetings) && !$cookie->logged) { $cookie->greetings = 1; $cookie->write(); $smarty->assign('show_greetings', 1); } //echo $cookie->image_size; if ($image_size = Tools::getValue("is")) { if ($image_size == "s" && $cookie->image_size == IMAGE_SIZE_LARGE) { $cookie->image_size = IMAGE_SIZE_SMALL; $cookie->write(); } else { if ($image_size == "l" && $cookie->image_size == IMAGE_SIZE_SMALL) { $cookie->image_size = IMAGE_SIZE_LARGE; $cookie->write(); } } } // Switch language if needed and init cookie language if ($iso = Tools::getValue('isolang') and Validate::isLanguageIsoCode($iso) and $id_lang = (int) Language::getIdByIso($iso)) { $_GET['id_lang'] = $id_lang; } Tools::switchLanguage(); Tools::setCookieLanguage(); /* attribute id_lang is often needed, so we create a constant for performance reasons */ if (!defined('_USER_ID_LANG_')) { define('_USER_ID_LANG_', (int) $cookie->id_lang); } if (isset($_GET['logout']) or $cookie->logged and Customer::isBanned((int) $cookie->id_customer)) { $cookie->logout(); Tools::redirect(isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : NULL); } elseif (isset($_GET['mylogout'])) { $this->logoutFacebook(); $cookie->mylogout(); Tools::redirect(isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : NULL); } if ($source = Tools::getValue('utm_source')) { $cookie->last_source = $source; $cookie->write(); } if ($ref_source = Tools::getValue('vbref')) { $cookie->last_ref_source = $ref_source; $cookie->write(); } /*else { if(!isset($cookie->last_ref_source)) { $cookie->last_ref_source = 0; $cookie->write(); } }*/ global $currency; $currency = Tools::setCurrency(); $_MODULES = array(); /* Cart already exists */ if ((int) $cookie->id_cart) { $cart = new Cart((int) $cookie->id_cart); if ($cart->OrderExists()) { unset($cookie->id_cart, $cart, $cookie->checkedTOS); } elseif (intval(Configuration::get('PS_GEOLOCATION_ENABLED')) and !in_array(strtoupper($cookie->iso_code_country), explode(';', Configuration::get('PS_ALLOWED_COUNTRIES'))) and $cart->nbProducts() and intval(Configuration::get('PS_GEOLOCATION_NA_BEHAVIOR')) != -1 and !self::isInWhitelistForGeolocation()) { unset($cookie->id_cart, $cart); } elseif ($cookie->id_customer != $cart->id_customer or $cookie->id_lang != $cart->id_lang or $cookie->id_currency != $cart->id_currency) { if ($cookie->id_customer) { $cart->id_customer = (int) $cookie->id_customer; } $cart->id_lang = (int) $cookie->id_lang; $cart->id_currency = (int) $cookie->id_currency; $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) && $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) or !$cart->id) { $this->checkIDS(); $cart = new Cart(); $cart->id_lang = (int) $cookie->id_lang; $cart->id_currency = (int) $cookie->id_currency; $cart->id_guest = (int) $cookie->id_guest; if ($cookie->id_customer) { $cart->id_customer = (int) $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; } } if (!$cart->nbProducts()) { $cart->id_carrier = NULL; } $locale = strtolower(Configuration::get('PS_LOCALE_LANGUAGE')) . '_' . strtoupper(Configuration::get('PS_LOCALE_COUNTRY') . '.UTF-8'); setlocale(LC_COLLATE, $locale); setlocale(LC_CTYPE, $locale); setlocale(LC_TIME, $locale); setlocale(LC_NUMERIC, 'en_US.UTF-8'); if (Validate::isLoadedObject($currency)) { $smarty->ps_currency = $currency; } if (Validate::isLoadedObject($ps_language = new Language((int) $cookie->id_lang))) { $smarty->ps_language = $ps_language; } /* get page name to display it in body id */ $pathinfo = pathinfo(__FILE__); $page_name = basename($_SERVER['PHP_SELF'], '.' . $pathinfo['extension']); $page_name = preg_match('/^[0-9]/', $page_name) ? 'page_' . $page_name : $page_name; $smarty->assign(Tools::getMetaTags($cookie->id_lang, $page_name)); $smarty->assign('request_uri', Tools::safeOutput(urldecode($_SERVER['REQUEST_URI']))); /* Breadcrumb */ $navigationPipe = Configuration::get('PS_NAVIGATION_PIPE') ? Configuration::get('PS_NAVIGATION_PIPE') : '>'; $smarty->assign('navigationPipe', $navigationPipe); $protocol_link = (Configuration::get('PS_SSL_ENABLED') or !empty($_SERVER['HTTPS']) and strtolower($_SERVER['HTTPS']) != 'off') ? 'https://' : 'http://'; $protocol_content = (isset($useSSL) and $useSSL and Configuration::get('PS_SSL_ENABLED') or !empty($_SERVER['HTTPS']) and strtolower($_SERVER['HTTPS']) != 'off') ? 'https://' : 'http://'; if (!defined('_PS_BASE_URL_')) { define('_PS_BASE_URL_', Tools::getShopDomain(true)); } if (!defined('_PS_BASE_URL_SSL_')) { define('_PS_BASE_URL_SSL_', Tools::getShopDomainSsl(true)); } $link->preloadPageLinks(); $this->canonicalRedirection(); Product::initPricesComputation(); $display_tax_label = $defaultCountry->display_tax_label; if ($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']); if (Validate::isLoadedObject($country)) { $display_tax_label = $country->display_tax_label; } } global $isBetaUser, $conversion_rate_inr; $conversion_rate_inr = 55; if (!$cookie->isLogged()) { $this->initFacebook(); } else { $customer_groups = Customer::getGroupsStatic((int) $cookie->id_customer); if (in_array(2, $customer_groups)) { $smarty->assign('internal_vb_user', 1); } if (in_array(3, $customer_groups)) { $isBetaUser = true; } else { $isBetaUser = false; } /*$reward_points = VBRewards::getCustomerPoints($cookie->id_customer); $can_redeem = VBRewards::checkPointsValidity($cookie->id_customer, 0); if($can_redeem) $smarty->assign('can_redeem_points', 1); $smarty->assign('balance_points', $reward_points);*/ } $smarty->assign('img_version', IMG_VERSION); $this->setRecaptchaHTML(); if ($page_name === "index") { $sql = "select title,image_path,url from ps_banner where is_active = 1 order by display_order asc"; $home_banners = Db::getInstance()->ExecuteS($sql); $smarty->assign("home_banners", $home_banners); } $smarty->assign(array('lazy' => 1, 'link' => $link, 'cart' => $cart, 'currency' => $currency, 'cookie' => $cookie, 'page_name' => $page_name, 'base_dir' => _PS_BASE_URL_ . __PS_BASE_URI__, 'base_dir_ssl' => $protocol_link . Tools::getShopDomainSsl() . __PS_BASE_URI__, 'content_dir' => $protocol_content . Tools::getShopDomain() . __PS_BASE_URI__, 'tpl_dir' => _PS_THEME_DIR_, 'modules_dir' => _MODULE_DIR_, 'mail_dir' => _MAIL_DIR_, 'lang_iso' => $ps_language->iso_code, 'come_from' => Tools::getHttpHost(true, true) . Tools::htmlentitiesUTF8(str_replace('\'', '', urldecode($_SERVER['REQUEST_URI']))), 'cart_qties' => (int) $cart->nbProducts(), 'currencies' => Currency::getCurrencies(), 'languages' => Language::getLanguages(), 'priceDisplay' => Product::getTaxCalculationMethod(), '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'), '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'), 'conversion_rate' => $conversion_rate_inr)); // Deprecated $smarty->assign(array('id_currency_cookie' => (int) $currency->id, 'logged' => $cookie->isLogged(), 'customerName' => $cookie->logged ? $cookie->customer_firstname . ' ' . $cookie->customer_lastname : false)); // TODO for better performances (cache usage), remove these assign and use a smarty function to get the right media server in relation to the full ressource name $assignArray = 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_); foreach ($assignArray as $assignKey => $assignValue) { if (substr($assignValue, 0, 1) == '/' or $protocol_content == 'https://') { $smarty->assign($assignKey, $protocol_content . Tools::getMediaServer($assignValue) . $assignValue); } else { $smarty->assign($assignKey, $assignValue); } } // setting properties from global var self::$cookie = $cookie; self::$cart = $cart; self::$smarty = $smarty; self::$link = $link; if ($this->maintenance) { $this->displayMaintenancePage(); } if ($this->restrictedCountry) { $this->displayRestrictedCountryPage(); } //live edit if (Tools::isSubmit('live_edit') and $ad = Tools::getValue('ad') and Tools::getValue('liveToken') == sha1(Tools::getValue('ad') . _COOKIE_KEY_)) { if (!is_dir(_PS_ROOT_DIR_ . DIRECTORY_SEPARATOR . $ad)) { die(Tools::displayError()); } } $this->iso = $iso; $this->setMedia(); //For sokrati pixel self::$smarty->assign("new_customer_regd", false); if ((int) self::$cookie->new_reg === 1) { self::$smarty->assign("new_customer_regd", true); unset(self::$cookie->new_reg); } if (self::$cookie->id_customer) { self::$smarty->assign("balance_points", VBRewards::getCustomerPoints(self::$cookie->id_customer)); } }
/** * Return useful informations for cart * * @return array Cart details */ public function getSummaryDetails($id_lang = null, $refresh = false) { $context = Context::getContext(); if (!$id_lang) { $id_lang = $context->language->id; } $delivery = new Address((int) $this->id_address_delivery); $invoice = new Address((int) $this->id_address_invoice); // New layout system with personalization fields $formatted_addresses = array('delivery' => AddressFormat::getFormattedLayoutData($delivery), 'invoice' => AddressFormat::getFormattedLayoutData($invoice)); $base_total_tax_inc = $this->getOrderTotal(true); $base_total_tax_exc = $this->getOrderTotal(false); $total_tax = $base_total_tax_inc - $base_total_tax_exc; if ($total_tax < 0) { $total_tax = 0; } $currency = new Currency($this->id_currency); $products = $this->getProducts($refresh); foreach ($products as $key => &$product) { $product['price_without_quantity_discount'] = Product::getPriceStatic($product['id_product'], !Product::getTaxCalculationMethod(), $product['id_product_attribute'], 6, null, false, false); if ($product['reduction_type'] == 'amount') { $reduction = (!Product::getTaxCalculationMethod() ? (double) $product['price_wt'] : (double) $product['price']) - (double) $product['price_without_quantity_discount']; $product['reduction_formatted'] = Tools::displayPrice($reduction); } } $gift_products = array(); $cart_rules = $this->getCartRules(); $total_shipping = $this->getTotalShippingCost(); $total_shipping_tax_exc = $this->getTotalShippingCost(null, false); $total_products_wt = $this->getOrderTotal(true, Cart::ONLY_PRODUCTS); $total_products = $this->getOrderTotal(false, Cart::ONLY_PRODUCTS); $total_discounts = $this->getOrderTotal(true, Cart::ONLY_DISCOUNTS); $total_discounts_tax_exc = $this->getOrderTotal(false, Cart::ONLY_DISCOUNTS); // The cart content is altered for display foreach ($cart_rules as &$cart_rule) { // If the cart rule is automatic (wihtout any code) and include free shipping, it should not be displayed as a cart rule but only set the shipping cost to 0 if ($cart_rule['free_shipping'] && (empty($cart_rule['code']) || preg_match('/^' . CartRule::BO_ORDER_CODE_PREFIX . '[0-9]+/', $cart_rule['code']))) { $cart_rule['value_real'] -= $total_shipping; $cart_rule['value_tax_exc'] -= $total_shipping_tax_exc; $cart_rule['value_real'] = Tools::ps_round($cart_rule['value_real'], (int) $context->currency->decimals * _PS_PRICE_COMPUTE_PRECISION_); $cart_rule['value_tax_exc'] = Tools::ps_round($cart_rule['value_tax_exc'], (int) $context->currency->decimals * _PS_PRICE_COMPUTE_PRECISION_); if ($total_discounts > $cart_rule['value_real']) { $total_discounts -= $total_shipping; } if ($total_discounts_tax_exc > $cart_rule['value_tax_exc']) { $total_discounts_tax_exc -= $total_shipping_tax_exc; } // Update total shipping $total_shipping = 0; $total_shipping_tax_exc = 0; } if ($cart_rule['gift_product']) { foreach ($products as $key => &$product) { if (empty($product['gift']) && $product['id_product'] == $cart_rule['gift_product'] && $product['id_product_attribute'] == $cart_rule['gift_product_attribute']) { // Update total products $total_products_wt = Tools::ps_round($total_products_wt - $product['price_wt'], (int) $context->currency->decimals * _PS_PRICE_COMPUTE_PRECISION_); $total_products = Tools::ps_round($total_products - $product['price'], (int) $context->currency->decimals * _PS_PRICE_COMPUTE_PRECISION_); // Update total discounts $total_discounts = Tools::ps_round($total_discounts - $product['price_wt'], (int) $context->currency->decimals * _PS_PRICE_COMPUTE_PRECISION_); $total_discounts_tax_exc = Tools::ps_round($total_discounts_tax_exc - $product['price'], (int) $context->currency->decimals * _PS_PRICE_COMPUTE_PRECISION_); // Update cart rule value $cart_rule['value_real'] = Tools::ps_round($cart_rule['value_real'] - $product['price_wt'], (int) $context->currency->decimals * _PS_PRICE_COMPUTE_PRECISION_); $cart_rule['value_tax_exc'] = Tools::ps_round($cart_rule['value_tax_exc'] - $product['price'], (int) $context->currency->decimals * _PS_PRICE_COMPUTE_PRECISION_); // Update product quantity $product['total_wt'] = Tools::ps_round($product['total_wt'] - $product['price_wt'], (int) $currency->decimals * _PS_PRICE_COMPUTE_PRECISION_); $product['total'] = Tools::ps_round($product['total'] - $product['price'], (int) $currency->decimals * _PS_PRICE_COMPUTE_PRECISION_); $product['cart_quantity']--; if (!$product['cart_quantity']) { unset($products[$key]); } // Add a new product line $gift_product = $product; $gift_product['cart_quantity'] = 1; $gift_product['price'] = 0; $gift_product['price_wt'] = 0; $gift_product['total_wt'] = 0; $gift_product['total'] = 0; $gift_product['gift'] = true; $gift_products[] = $gift_product; break; // One gift product per cart rule } } } } foreach ($cart_rules as $key => &$cart_rule) { if ((double) $cart_rule['value_real'] == 0 && (int) $cart_rule['free_shipping'] == 0) { unset($cart_rules[$key]); } } $summary = array('delivery' => $delivery, 'delivery_state' => State::getNameById($delivery->id_state), 'invoice' => $invoice, 'invoice_state' => State::getNameById($invoice->id_state), 'formattedAddresses' => $formatted_addresses, 'products' => array_values($products), 'gift_products' => $gift_products, 'discounts' => array_values($cart_rules), 'is_virtual_cart' => (int) $this->isVirtualCart(), 'total_discounts' => $total_discounts, 'total_discounts_tax_exc' => $total_discounts_tax_exc, 'total_wrapping' => $this->getOrderTotal(true, Cart::ONLY_WRAPPING), 'total_wrapping_tax_exc' => $this->getOrderTotal(false, Cart::ONLY_WRAPPING), 'total_shipping' => $total_shipping, 'total_shipping_tax_exc' => $total_shipping_tax_exc, 'total_products_wt' => $total_products_wt, 'total_products' => $total_products, 'total_price' => $base_total_tax_inc, 'total_tax' => $total_tax, 'total_price_without_tax' => $base_total_tax_exc, 'is_multi_address_delivery' => $this->isMultiAddressDelivery() || (int) Tools::getValue('multi-shipping') == 1, 'free_ship' => !$total_shipping && !count($this->getDeliveryAddressesWithoutCarriers(true, $errors)), 'carrier' => new Carrier($this->id_carrier, $id_lang)); $hook = Hook::exec('actionCartSummary', $summary, null, true); if (is_array($hook)) { $summary = array_merge($summary, array_shift($hook)); } return $summary; }
/** * Initialize order opc controller * @see FrontController::init() */ public function init() { parent::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 '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(); 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('An error occurred while updating the 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('HOOK_TOP_PAYMENT' => Hook::exec('displayPaymentTop'), 'HOOK_PAYMENT' => $this->_getPaymentMethods()))); } break; case 'getCarrierList': die(Tools::jsonEncode($this->_getCarrierList())); 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'); } $_POST['lastname'] = $_POST['customer_lastname']; $_POST['firstname'] = $_POST['customer_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()) { // check if customer have addresses 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()); $this->_processAddressFormat(); $this->_assignAddress(); if (!($formatedAddressFieldsValuesList = $this->context->smarty->getTemplateVars('formatedAddressFieldsValuesList'))) { $formatedAddressFieldsValuesList = array(); } // Wrapping fees $wrapping_fees = $this->context->cart->getGiftWrappingPrice(false); $wrapping_fees_tax_inc = $wrapping_fees = $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($blockUserInfo) ? $blockUserInfo->hookDisplayTop(array()) : '', 'formatedAddressFieldsValuesList' => $formatedAddressFieldsValuesList, '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()); 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 die('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 = $wrapping_fees = $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()); die(Tools::jsonEncode($result)); } } if (count($this->errors)) { die(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(); 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; 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('No product in your cart.'); die('{"hasError" : true, "errors" : ["' . implode('\',\'', $this->errors) . '"]}'); } }
/** * wrap products to provide a standard products information for google analytics script */ public function wrapProducts($products, $extras = array(), $full = false) { $result_products = array(); if (!is_array($products)) { return; } $currency = new Currency($this->context->currency->id); $usetax = Product::getTaxCalculationMethod((int) $this->context->customer->id) != PS_TAX_EXC; if (count($products) > 20) { $full = false; } else { $full = true; } foreach ($products as $index => $product) { if ($product instanceof Product) { $product = (array) $product; } if (!isset($product['price'])) { $product['price'] = (double) Tools::displayPrice(Product::getPriceStatic((int) $product['id_product'], $usetax), $currency); } $result_products[] = $this->wrapProduct($product, $extras, $index, $full); } return $result_products; }
public function preProcess() { parent::preProcess(); if ($this->nbProducts) { self::$smarty->assign('virtual_cart', false); } $this->isLogged = (bool) ((int) self::$cookie->id_customer and Customer::customerIdExistsStatic((int) self::$cookie->id_customer)); if (self::$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 (sizeof($this->errors)) { die('{"hasError" : true, "errors" : ["' . implode('\',\'', $this->errors) . '"]}'); } die(true); } break; case 'updateCarrierAndGetPayments': if (Tools::isSubmit('id_carrier') and Tools::isSubmit('recyclable') and Tools::isSubmit('gift') and Tools::isSubmit('gift_message')) { if ($this->_processCarrier()) { $return = array('summary' => self::$cart->getSummaryDetails(), 'HOOK_TOP_PAYMENT' => Module::hookExec('paymentTop'), 'HOOK_PAYMENT' => $this->_getPaymentMethods()); die(Tools::jsonEncode($return)); } else { $this->errors[] = Tools::displayError('Error occurred updating cart.'); } if (sizeof($this->errors)) { die('{"hasError" : true, "errors" : ["' . implode('\',\'', $this->errors) . '"]}'); } exit; } break; case 'updateTOSStatusAndGetPayments': if (Tools::isSubmit('checked')) { self::$cookie->checkedTOS = (int) Tools::getValue('checked'); die(Tools::jsonEncode(array('HOOK_TOP_PAYMENT' => Module::hookExec('paymentTop'), 'HOOK_PAYMENT' => $this->_getPaymentMethods()))); } break; case 'getCarrierList': die(Tools::jsonEncode($this->_getCarrierList())); break; case 'editCustomer': if (!$this->isLogged) { exit; } $customer = new Customer((int) self::$cookie->id_customer); if (Tools::getValue('years')) { $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 = $customer->validateControler(); $customer->newsletter = (int) Tools::isSubmit('newsletter'); $customer->optin = (int) Tools::isSubmit('optin'); $return = array('hasError' => !empty($this->errors), 'errors' => $this->errors, 'id_customer' => (int) self::$cookie->id_customer, 'token' => Tools::getToken(false)); if (!sizeof($this->errors)) { $return['isSaved'] = (bool) $customer->update(); } else { $return['isSaved'] = false; } die(Tools::jsonEncode($return)); break; case 'getAddressBlockAndCarriersAndPayments': if (self::$cookie->isLogged()) { // check if customer have addresses if (!Customer::getAddressesTotalById((int) self::$cookie->id_customer)) { 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(); } self::$smarty->assign('isVirtualCart', self::$cart->isVirtualCart()); $this->_processAddressFormat(); $this->_assignAddress(); // Wrapping fees $wrapping_fees = (double) Configuration::get('PS_GIFT_WRAPPING_PRICE'); $wrapping_fees_tax = new Tax((int) Configuration::get('PS_GIFT_WRAPPING_TAX')); $wrapping_fees_tax_inc = $wrapping_fees * (1 + (double) $wrapping_fees_tax->rate / 100); $return = array('summary' => self::$cart->getSummaryDetails(), 'order_opc_adress' => self::$smarty->fetch(_PS_THEME_DIR_ . 'order-address.tpl'), 'block_user_info' => isset($blockUserInfo) ? $blockUserInfo->hookTop(array()) : '', 'carrier_list' => $this->_getCarrierList(), 'HOOK_TOP_PAYMENT' => Module::hookExec('paymentTop'), '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) self::$cookie->id_currency)))); die(Tools::jsonEncode($return)); } die(Tools::displayError()); break; case 'makeFreeOrder': /* Bypass payment step if total is 0 */ if ($id_order = $this->_checkFreeOrder() and $id_order) { $email = self::$cookie->email; if (self::$cookie->is_guest) { self::$cookie->logout(); } // If guest we clear the cookie for security reason die('freeorder:' . $id_order . ':' . $email); } exit; break; case 'updateAddressesSelected': if (self::$cookie->isLogged(true)) { $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 ($address_delivery->id_customer != self::$cookie->id_customer || $address_invoice->id_customer != self::$cookie->id_customer) { $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) or !Validate::isLoadedObject($address_invoice) or $address_invoice->deleted or $address_delivery->deleted) { $this->errors[] = Tools::displayError('This address is invalid.'); } else { self::$cart->id_address_delivery = (int) Tools::getValue('id_address_delivery'); self::$cart->id_address_invoice = Tools::isSubmit('same') ? self::$cart->id_address_delivery : (int) Tools::getValue('id_address_invoice'); if (!self::$cart->update()) { $this->errors[] = Tools::displayError('An error occurred while updating your cart.'); } if (!sizeof($this->errors)) { if (self::$cookie->id_customer) { $customer = new Customer((int) self::$cookie->id_customer); $groups = $customer->getGroups(); } else { $groups = array(1); } $result = $this->_getCarrierList(); // Wrapping fees $wrapping_fees = (double) Configuration::get('PS_GIFT_WRAPPING_PRICE'); $wrapping_fees_tax = new Tax((int) Configuration::get('PS_GIFT_WRAPPING_TAX')); $wrapping_fees_tax_inc = $wrapping_fees * (1 + (double) $wrapping_fees_tax->rate / 100); $result = array_merge($result, array('summary' => self::$cart->getSummaryDetails(), 'HOOK_TOP_PAYMENT' => Module::hookExec('paymentTop'), 'HOOK_PAYMENT' => $this->_getPaymentMethods(), 'gift_price' => Tools::displayPrice(Tools::convertPrice(Product::getTaxCalculationMethod() == 1 ? $wrapping_fees : $wrapping_fees_tax_inc, new Currency((int) self::$cookie->id_currency))))); die(Tools::jsonEncode($result)); } } if (sizeof($this->errors)) { die('{"hasError" : true, "errors" : ["' . implode('\',\'', $this->errors) . '"]}'); } } die(Tools::displayError()); break; default: exit; } } exit; } } elseif (Tools::isSubmit('ajax')) { exit; } }
public function validateOrder($id_cart, $id_order_state, $amount_paid, $payment_method = 'Unknown', $message = null, $extra_vars = array(), $currency_special = null, $dont_touch_amount = false, $secure_key = false, Shop $shop = null) { if (self::DEBUG_MODE) { PrestaShopLogger::addLog('PaymentModule::validateOrder - Function called', 1, null, 'Cart', (int) $id_cart, true); } if (!isset($this->context)) { $this->context = Context::getContext(); } $this->context->cart = new Cart($id_cart); $this->context->customer = new Customer($this->context->cart->id_customer); // The tax cart is loaded before the customer so re-cache the tax calculation method $this->context->cart->setTaxCalculationMethod(); $this->context->language = new Language($this->context->cart->id_lang); $this->context->shop = $shop ? $shop : new Shop($this->context->cart->id_shop); ShopUrl::resetMainDomainCache(); $id_currency = $currency_special ? (int) $currency_special : (int) $this->context->cart->id_currency; $this->context->currency = new Currency($id_currency, null, $this->context->shop->id); if (Configuration::get('PS_TAX_ADDRESS_TYPE') == 'id_address_delivery') { $context_country = $this->context->country; } $order_status = new OrderState((int) $id_order_state, (int) $this->context->language->id); if (!Validate::isLoadedObject($order_status)) { PrestaShopLogger::addLog('PaymentModule::validateOrder - Order Status cannot be loaded', 3, null, 'Cart', (int) $id_cart, true); throw new PrestaShopException('Can\'t load Order status'); } if (!$this->active) { PrestaShopLogger::addLog('PaymentModule::validateOrder - Module is not active', 3, null, 'Cart', (int) $id_cart, true); die(Tools::displayError()); } // Does order already exists ? if (Validate::isLoadedObject($this->context->cart) && $this->context->cart->OrderExists() == false) { if ($secure_key !== false && $secure_key != $this->context->cart->secure_key) { PrestaShopLogger::addLog('PaymentModule::validateOrder - Secure key does not match', 3, null, 'Cart', (int) $id_cart, true); die(Tools::displayError()); } // For each package, generate an order $delivery_option_list = $this->context->cart->getDeliveryOptionList(); $package_list = $this->context->cart->getPackageList(); $cart_delivery_option = $this->context->cart->getDeliveryOption(); // If some delivery options are not defined, or not valid, use the first valid option foreach ($delivery_option_list as $id_address => $package) { if (!isset($cart_delivery_option[$id_address]) || !array_key_exists($cart_delivery_option[$id_address], $package)) { foreach ($package as $key => $val) { $cart_delivery_option[$id_address] = $key; break; } } } $order_list = array(); $order_detail_list = array(); do { $reference = Order::generateReference(); } while (Order::getByReference($reference)->count()); $this->currentOrderReference = $reference; $order_creation_failed = false; $cart_total_paid = (double) Tools::ps_round((double) $this->context->cart->getOrderTotal(true, Cart::BOTH), 2); foreach ($cart_delivery_option as $id_address => $key_carriers) { foreach ($delivery_option_list[$id_address][$key_carriers]['carrier_list'] as $id_carrier => $data) { foreach ($data['package_list'] as $id_package) { // Rewrite the id_warehouse $package_list[$id_address][$id_package]['id_warehouse'] = (int) $this->context->cart->getPackageIdWarehouse($package_list[$id_address][$id_package], (int) $id_carrier); $package_list[$id_address][$id_package]['id_carrier'] = $id_carrier; } } } // Make sure CartRule caches are empty CartRule::cleanCache(); $cart_rules = $this->context->cart->getCartRules(); foreach ($cart_rules as $cart_rule) { if (($rule = new CartRule((int) $cart_rule['obj']->id)) && Validate::isLoadedObject($rule)) { if ($error = $rule->checkValidity($this->context, true, true)) { $this->context->cart->removeCartRule((int) $rule->id); if (isset($this->context->cookie) && isset($this->context->cookie->id_customer) && $this->context->cookie->id_customer && !empty($rule->code)) { if (Configuration::get('PS_ORDER_PROCESS_TYPE') == 1) { Tools::redirect('index.php?controller=order-opc&submitAddDiscount=1&discount_name=' . urlencode($rule->code)); } Tools::redirect('index.php?controller=order&submitAddDiscount=1&discount_name=' . urlencode($rule->code)); } else { $rule_name = isset($rule->name[(int) $this->context->cart->id_lang]) ? $rule->name[(int) $this->context->cart->id_lang] : $rule->code; $error = Tools::displayError(sprintf('CartRule ID %1s (%2s) used in this cart is not valid and has been withdrawn from cart', (int) $rule->id, $rule_name)); PrestaShopLogger::addLog($error, 3, '0000002', 'Cart', (int) $this->context->cart->id); } } } } foreach ($package_list as $id_address => $packageByAddress) { foreach ($packageByAddress as $id_package => $package) { $order = new Order(); $order->product_list = $package['product_list']; if (Configuration::get('PS_TAX_ADDRESS_TYPE') == 'id_address_delivery') { $address = new Address($id_address); $this->context->country = new Country($address->id_country, $this->context->cart->id_lang); if (!$this->context->country->active) { throw new PrestaShopException('The delivery address country is not active.'); } } $carrier = null; if (!$this->context->cart->isVirtualCart() && isset($package['id_carrier'])) { $carrier = new Carrier($package['id_carrier'], $this->context->cart->id_lang); $order->id_carrier = (int) $carrier->id; $id_carrier = (int) $carrier->id; } else { $order->id_carrier = 0; $id_carrier = 0; } $order->id_customer = (int) $this->context->cart->id_customer; $order->id_address_invoice = (int) $this->context->cart->id_address_invoice; $order->id_address_delivery = (int) $id_address; $order->id_currency = $this->context->currency->id; $order->id_lang = (int) $this->context->cart->id_lang; $order->id_cart = (int) $this->context->cart->id; $order->reference = $reference; $order->id_shop = (int) $this->context->shop->id; $order->id_shop_group = (int) $this->context->shop->id_shop_group; $order->secure_key = $secure_key ? pSQL($secure_key) : pSQL($this->context->customer->secure_key); $order->payment = $payment_method; if (isset($this->name)) { $order->module = $this->name; } $order->recyclable = $this->context->cart->recyclable; $order->gift = (int) $this->context->cart->gift; $order->gift_message = $this->context->cart->gift_message; $order->mobile_theme = $this->context->cart->mobile_theme; $order->conversion_rate = $this->context->currency->conversion_rate; $amount_paid = !$dont_touch_amount ? Tools::ps_round((double) $amount_paid, 2) : $amount_paid; $order->total_paid_real = 0; $order->total_products = (double) $this->context->cart->getOrderTotal(false, Cart::ONLY_PRODUCTS, $order->product_list, $id_carrier); $order->total_products_wt = (double) $this->context->cart->getOrderTotal(true, Cart::ONLY_PRODUCTS, $order->product_list, $id_carrier); $order->total_discounts_tax_excl = (double) abs($this->context->cart->getOrderTotal(false, Cart::ONLY_DISCOUNTS, $order->product_list, $id_carrier)); $order->total_discounts_tax_incl = (double) abs($this->context->cart->getOrderTotal(true, Cart::ONLY_DISCOUNTS, $order->product_list, $id_carrier)); $order->total_discounts = $order->total_discounts_tax_incl; $order->total_shipping_tax_excl = (double) $this->context->cart->getPackageShippingCost((int) $id_carrier, false, null, $order->product_list); $order->total_shipping_tax_incl = (double) $this->context->cart->getPackageShippingCost((int) $id_carrier, true, null, $order->product_list); $order->total_shipping = $order->total_shipping_tax_incl; if (!is_null($carrier) && Validate::isLoadedObject($carrier)) { $order->carrier_tax_rate = $carrier->getTaxesRate(new Address($this->context->cart->{Configuration::get('PS_TAX_ADDRESS_TYPE')})); } $order->total_wrapping_tax_excl = (double) abs($this->context->cart->getOrderTotal(false, Cart::ONLY_WRAPPING, $order->product_list, $id_carrier)); $order->total_wrapping_tax_incl = (double) abs($this->context->cart->getOrderTotal(true, Cart::ONLY_WRAPPING, $order->product_list, $id_carrier)); $order->total_wrapping = $order->total_wrapping_tax_incl; $order->total_paid_tax_excl = (double) Tools::ps_round((double) $this->context->cart->getOrderTotal(false, Cart::BOTH, $order->product_list, $id_carrier), _PS_PRICE_COMPUTE_PRECISION_); $order->total_paid_tax_incl = (double) Tools::ps_round((double) $this->context->cart->getOrderTotal(true, Cart::BOTH, $order->product_list, $id_carrier), _PS_PRICE_COMPUTE_PRECISION_); $order->total_paid = $order->total_paid_tax_incl; $order->round_mode = Configuration::get('PS_PRICE_ROUND_MODE'); $order->invoice_date = '0000-00-00 00:00:00'; $order->delivery_date = '0000-00-00 00:00:00'; if (self::DEBUG_MODE) { PrestaShopLogger::addLog('PaymentModule::validateOrder - Order is about to be added', 1, null, 'Cart', (int) $id_cart, true); } // Creating order $result = $order->add(); if (!$result) { PrestaShopLogger::addLog('PaymentModule::validateOrder - Order cannot be created', 3, null, 'Cart', (int) $id_cart, true); throw new PrestaShopException('Can\'t save Order'); } // Amount paid by customer is not the right one -> Status = payment error // We don't use the following condition to avoid the float precision issues : http://www.php.net/manual/en/language.types.float.php // if ($order->total_paid != $order->total_paid_real) // We use number_format in order to compare two string if ($order_status->logable && number_format($cart_total_paid, _PS_PRICE_COMPUTE_PRECISION_) != number_format($amount_paid, _PS_PRICE_COMPUTE_PRECISION_)) { $id_order_state = Configuration::get('PS_OS_ERROR'); } $order_list[] = $order; if (self::DEBUG_MODE) { PrestaShopLogger::addLog('PaymentModule::validateOrder - OrderDetail is about to be added', 1, null, 'Cart', (int) $id_cart, true); } // Insert new Order detail list using cart for the current order $order_detail = new OrderDetail(null, null, $this->context); $order_detail->createList($order, $this->context->cart, $id_order_state, $order->product_list, 0, true, $package_list[$id_address][$id_package]['id_warehouse']); $order_detail_list[] = $order_detail; if (self::DEBUG_MODE) { PrestaShopLogger::addLog('PaymentModule::validateOrder - OrderCarrier is about to be added', 1, null, 'Cart', (int) $id_cart, true); } // Adding an entry in order_carrier table if (!is_null($carrier)) { $order_carrier = new OrderCarrier(); $order_carrier->id_order = (int) $order->id; $order_carrier->id_carrier = (int) $id_carrier; $order_carrier->weight = (double) $order->getTotalWeight(); $order_carrier->shipping_cost_tax_excl = (double) $order->total_shipping_tax_excl; $order_carrier->shipping_cost_tax_incl = (double) $order->total_shipping_tax_incl; $order_carrier->add(); } } } // The country can only change if the address used for the calculation is the delivery address, and if multi-shipping is activated if (Configuration::get('PS_TAX_ADDRESS_TYPE') == 'id_address_delivery') { $this->context->country = $context_country; } if (!$this->context->country->active) { PrestaShopLogger::addLog('PaymentModule::validateOrder - Country is not active', 3, null, 'Cart', (int) $id_cart, true); throw new PrestaShopException('The order address country is not active.'); } if (self::DEBUG_MODE) { PrestaShopLogger::addLog('PaymentModule::validateOrder - Payment is about to be added', 1, null, 'Cart', (int) $id_cart, true); } // Register Payment only if the order status validate the order if ($order_status->logable) { // $order is the last order loop in the foreach // The method addOrderPayment of the class Order make a create a paymentOrder // linked to the order reference and not to the order id if (isset($extra_vars['transaction_id'])) { $transaction_id = $extra_vars['transaction_id']; } else { $transaction_id = null; } if (!$order->addOrderPayment($amount_paid, null, $transaction_id)) { PrestaShopLogger::addLog('PaymentModule::validateOrder - Cannot save Order Payment', 3, null, 'Cart', (int) $id_cart, true); throw new PrestaShopException('Can\'t save Order Payment'); } } // Next ! $only_one_gift = false; $cart_rule_used = array(); $products = $this->context->cart->getProducts(); // Make sure CarRule caches are empty CartRule::cleanCache(); foreach ($order_detail_list as $key => $order_detail) { $order = $order_list[$key]; if (!$order_creation_failed && isset($order->id)) { if (!$secure_key) { $message .= '<br />' . Tools::displayError('Warning: the secure key is empty, check your payment account before validation'); } // Optional message to attach to this order if (isset($message) & !empty($message)) { $msg = new Message(); $message = strip_tags($message, '<br>'); if (Validate::isCleanHtml($message)) { if (self::DEBUG_MODE) { PrestaShopLogger::addLog('PaymentModule::validateOrder - Message is about to be added', 1, null, 'Cart', (int) $id_cart, true); } $msg->message = $message; $msg->id_order = (int) $order->id; $msg->private = 1; $msg->add(); } } // Insert new Order detail list using cart for the current order //$orderDetail = new OrderDetail(null, null, $this->context); //$orderDetail->createList($order, $this->context->cart, $id_order_state); // Construct order detail table for the email $products_list = ''; $virtual_product = true; $ppropertiessmartprice_hook1 = null; $product_var_tpl_list = array(); foreach ($order->product_list as $product) { PP::smartyPPAssign(array('cart' => $product, 'currency' => $this->context->currency)); $price = Product::getPriceStatic((int) $product['id_product'], false, $product['id_product_attribute'] ? (int) $product['id_product_attribute'] : null, 6, null, false, true, array($product['cart_quantity'], $product['cart_quantity_fractional']), false, (int) $order->id_customer, (int) $order->id_cart, (int) $order->{Configuration::get('PS_TAX_ADDRESS_TYPE')}); $price_wt = Product::getPriceStatic((int) $product['id_product'], true, $product['id_product_attribute'] ? (int) $product['id_product_attribute'] : null, 2, null, false, true, array($product['cart_quantity'], $product['cart_quantity_fractional']), false, (int) $order->id_customer, (int) $order->id_cart, (int) $order->{Configuration::get('PS_TAX_ADDRESS_TYPE')}); $ppropertiessmartprice_hook2 = ''; $product_var_tpl = array('reference' => $product['reference'], 'name' => $product['name'] . (isset($product['attributes']) ? ' - ' . $product['attributes'] : '') . PP::smartyDisplayProductName(array('name' => '')) . $ppropertiessmartprice_hook2, 'unit_price' => PP::smartyDisplayPrice(array('price' => Product::getTaxCalculationMethod() == PS_TAX_EXC ? Tools::ps_round($price, 2) : $price_wt)), 'price' => PP::smartyDisplayPrice(array('price' => Product::getTaxCalculationMethod() == PS_TAX_EXC ? $product['total'] : $product['total_wt'], 'quantity' => (int) $product['cart_quantity'], 'm' => 'total')), 'quantity' => PP::smartyDisplayQty(array('quantity' => (int) $product['cart_quantity'])), 'customization' => array()); $customized_datas = Product::getAllCustomizedDatas((int) $order->id_cart); $productHasCustomizedDatas = Product::hasCustomizedDatas($product, $customized_datas); if ($productHasCustomizedDatas && isset($customized_datas[$product['id_product']][$product['id_product_attribute']])) { $product_var_tpl['customization'] = array(); foreach ($customized_datas[$product['id_product']][$product['id_product_attribute']][$order->id_address_delivery] as $customization) { if ($product['id_cart_product'] == $customization['id_cart_product']) { $customization_text = ''; if (isset($customization['datas'][Product::CUSTOMIZE_TEXTFIELD])) { foreach ($customization['datas'][Product::CUSTOMIZE_TEXTFIELD] as $text) { $customization_text .= $text['name'] . ': ' . $text['value'] . '<br />'; } } if (isset($customization['datas'][Product::CUSTOMIZE_FILE])) { $customization_text .= sprintf(Tools::displayError('%d image(s)'), count($customization['datas'][Product::CUSTOMIZE_FILE])) . '<br />'; } $customization_quantity = (int) $product['customization_quantity']; $product_var_tpl['customization'][] = array('customization_text' => $customization_text, 'customization_quantity' => PP::smartyDisplayQty(array('quantity' => $customization_quantity)), 'quantity' => PP::smartyDisplayPrice(array('price' => Product::getTaxCalculationMethod() == PS_TAX_EXC ? $product['total_customization'] : $product['total_customization_wt'], 'm' => 'total'))); } } } $product_var_tpl_list[] = $product_var_tpl; // Check if is not a virutal product for the displaying of shipping if (!$product['is_virtual']) { $virtual_product &= false; } } // end foreach ($products) PP::smartyPPAssign(); $product_list_txt = ''; $product_list_html = ''; if (count($product_var_tpl_list) > 0) { $product_list_txt = $this->getEmailTemplateContent('order_conf_product_list.txt', Mail::TYPE_TEXT, $product_var_tpl_list); $product_list_html = $this->getEmailTemplateContent('order_conf_product_list.tpl', Mail::TYPE_HTML, $product_var_tpl_list); } $cart_rules_list = array(); $total_reduction_value_ti = 0; $total_reduction_value_tex = 0; foreach ($cart_rules as $cart_rule) { $package = array('id_carrier' => $order->id_carrier, 'id_address' => $order->id_address_delivery, 'products' => $order->product_list); $values = array('tax_incl' => $cart_rule['obj']->getContextualValue(true, $this->context, CartRule::FILTER_ACTION_ALL_NOCAP, $package), 'tax_excl' => $cart_rule['obj']->getContextualValue(false, $this->context, CartRule::FILTER_ACTION_ALL_NOCAP, $package)); // If the reduction is not applicable to this order, then continue with the next one if (!$values['tax_excl']) { continue; } // IF // This is not multi-shipping // The value of the voucher is greater than the total of the order // Partial use is allowed // This is an "amount" reduction, not a reduction in % or a gift // THEN // The voucher is cloned with a new value corresponding to the remainder if (count($order_list) == 1 && $values['tax_incl'] > $order->total_products_wt - $total_reduction_value_ti && $cart_rule['obj']->partial_use == 1 && $cart_rule['obj']->reduction_amount > 0) { // Create a new voucher from the original $voucher = new CartRule($cart_rule['obj']->id); // We need to instantiate the CartRule without lang parameter to allow saving it unset($voucher->id); // Set a new voucher code $voucher->code = empty($voucher->code) ? Tools::substr(md5($order->id . '-' . $order->id_customer . '-' . $cart_rule['obj']->id), 0, 16) : $voucher->code . '-2'; if (preg_match('/\\-([0-9]{1,2})\\-([0-9]{1,2})$/', $voucher->code, $matches) && $matches[1] == $matches[2]) { $voucher->code = preg_replace('/' . $matches[0] . '$/', '-' . (int) ($matches[1] + 1), $voucher->code); } // Set the new voucher value if ($voucher->reduction_tax) { $voucher->reduction_amount = $total_reduction_value_ti + $values['tax_incl'] - $order->total_products_wt; // Add total shipping amout only if reduction amount > total shipping if ($voucher->free_shipping == 1 && $voucher->reduction_amount >= $order->total_shipping_tax_incl) { $voucher->reduction_amount -= $order->total_shipping_tax_incl; } } else { $voucher->reduction_amount = $total_reduction_value_tex + $values['tax_excl'] - $order->total_products; // Add total shipping amout only if reduction amount > total shipping if ($voucher->free_shipping == 1 && $voucher->reduction_amount >= $order->total_shipping_tax_excl) { $voucher->reduction_amount -= $order->total_shipping_tax_excl; } } if ($voucher->reduction_amount <= 0) { continue; } $voucher->id_customer = $order->id_customer; $voucher->quantity = 1; $voucher->quantity_per_user = 1; $voucher->free_shipping = 0; if ($voucher->add()) { // If the voucher has conditions, they are now copied to the new voucher CartRule::copyConditions($cart_rule['obj']->id, $voucher->id); $params = array('{voucher_amount}' => Tools::displayPrice($voucher->reduction_amount, $this->context->currency, false), '{voucher_num}' => $voucher->code, '{firstname}' => $this->context->customer->firstname, '{lastname}' => $this->context->customer->lastname, '{id_order}' => $order->reference, '{order_name}' => $order->getUniqReference()); Mail::Send((int) $order->id_lang, 'voucher', sprintf(Mail::l('New voucher for your order %s', (int) $order->id_lang), $order->reference), $params, $this->context->customer->email, $this->context->customer->firstname . ' ' . $this->context->customer->lastname, null, null, null, null, _PS_MAIL_DIR_, false, (int) $order->id_shop); } $values['tax_incl'] = $order->total_products_wt - $total_reduction_value_ti; $values['tax_excl'] = $order->total_products - $total_reduction_value_tex; } $total_reduction_value_ti += $values['tax_incl']; $total_reduction_value_tex += $values['tax_excl']; $order->addCartRule($cart_rule['obj']->id, $cart_rule['obj']->name, $values, 0, $cart_rule['obj']->free_shipping); if ($id_order_state != Configuration::get('PS_OS_ERROR') && $id_order_state != Configuration::get('PS_OS_CANCELED') && !in_array($cart_rule['obj']->id, $cart_rule_used)) { $cart_rule_used[] = $cart_rule['obj']->id; // Create a new instance of Cart Rule without id_lang, in order to update its quantity $cart_rule_to_update = new CartRule($cart_rule['obj']->id); $cart_rule_to_update->quantity = max(0, $cart_rule_to_update->quantity - 1); $cart_rule_to_update->update(); } $cart_rules_list[] = array('voucher_name' => $cart_rule['obj']->name, 'voucher_reduction' => ($values['tax_incl'] != 0.0 ? '-' : '') . Tools::displayPrice($values['tax_incl'], $this->context->currency, false)); } $cart_rules_list_txt = ''; $cart_rules_list_html = ''; if (count($cart_rules_list) > 0) { $cart_rules_list_txt = $this->getEmailTemplateContent('order_conf_cart_rules.txt', Mail::TYPE_TEXT, $cart_rules_list); $cart_rules_list_html = $this->getEmailTemplateContent('order_conf_cart_rules.tpl', Mail::TYPE_HTML, $cart_rules_list); } // Specify order id for message $old_message = Message::getMessageByCartId((int) $this->context->cart->id); if ($old_message) { $update_message = new Message((int) $old_message['id_message']); $update_message->id_order = (int) $order->id; $update_message->update(); // Add this message in the customer thread $customer_thread = new CustomerThread(); $customer_thread->id_contact = 0; $customer_thread->id_customer = (int) $order->id_customer; $customer_thread->id_shop = (int) $this->context->shop->id; $customer_thread->id_order = (int) $order->id; $customer_thread->id_lang = (int) $this->context->language->id; $customer_thread->email = $this->context->customer->email; $customer_thread->status = 'open'; $customer_thread->token = Tools::passwdGen(12); $customer_thread->add(); $customer_message = new CustomerMessage(); $customer_message->id_customer_thread = $customer_thread->id; $customer_message->id_employee = 0; $customer_message->message = $update_message->message; $customer_message->private = 0; if (!$customer_message->add()) { $this->errors[] = Tools::displayError('An error occurred while saving message'); } } if (self::DEBUG_MODE) { PrestaShopLogger::addLog('PaymentModule::validateOrder - Hook validateOrder is about to be called', 1, null, 'Cart', (int) $id_cart, true); } // Hook validate order Hook::exec('actionValidateOrder', array('cart' => $this->context->cart, 'order' => $order, 'customer' => $this->context->customer, 'currency' => $this->context->currency, 'orderStatus' => $order_status)); foreach ($this->context->cart->getProducts() as $product) { if ($order_status->logable) { ProductSale::addProductSale((int) $product['id_product'], (int) $product['cart_quantity']); } } if (self::DEBUG_MODE) { PrestaShopLogger::addLog('PaymentModule::validateOrder - Order Status is about to be added', 1, null, 'Cart', (int) $id_cart, true); } // Set the order status $new_history = new OrderHistory(); $new_history->id_order = (int) $order->id; $new_history->changeIdOrderState((int) $id_order_state, $order, true); $new_history->addWithemail(true, $extra_vars); // Switch to back order if needed if (Configuration::get('PS_STOCK_MANAGEMENT') && $order_detail->getStockState()) { $history = new OrderHistory(); $history->id_order = (int) $order->id; $history->changeIdOrderState(Configuration::get($order->valid ? 'PS_OS_OUTOFSTOCK_PAID' : 'PS_OS_OUTOFSTOCK_UNPAID'), $order, true); $history->addWithemail(); } unset($order_detail); // Order is reloaded because the status just changed $order = new Order($order->id); // Send an e-mail to customer (one order = one email) if ($id_order_state != Configuration::get('PS_OS_ERROR') && $id_order_state != Configuration::get('PS_OS_CANCELED') && $this->context->customer->id) { $invoice = new Address($order->id_address_invoice); $delivery = new Address($order->id_address_delivery); $delivery_state = $delivery->id_state ? new State($delivery->id_state) : false; $invoice_state = $invoice->id_state ? new State($invoice->id_state) : false; $data = array('{firstname}' => $this->context->customer->firstname, '{lastname}' => $this->context->customer->lastname, '{email}' => $this->context->customer->email, '{delivery_block_txt}' => $this->_getFormatedAddress($delivery, "\n"), '{invoice_block_txt}' => $this->_getFormatedAddress($invoice, "\n"), '{delivery_block_html}' => $this->_getFormatedAddress($delivery, '<br />', array('firstname' => '<span style="font-weight:bold;">%s</span>', 'lastname' => '<span style="font-weight:bold;">%s</span>')), '{invoice_block_html}' => $this->_getFormatedAddress($invoice, '<br />', array('firstname' => '<span style="font-weight:bold;">%s</span>', 'lastname' => '<span style="font-weight:bold;">%s</span>')), '{delivery_company}' => $delivery->company, '{delivery_firstname}' => $delivery->firstname, '{delivery_lastname}' => $delivery->lastname, '{delivery_address1}' => $delivery->address1, '{delivery_address2}' => $delivery->address2, '{delivery_city}' => $delivery->city, '{delivery_postal_code}' => $delivery->postcode, '{delivery_country}' => $delivery->country, '{delivery_state}' => $delivery->id_state ? $delivery_state->name : '', '{delivery_phone}' => $delivery->phone ? $delivery->phone : $delivery->phone_mobile, '{delivery_other}' => $delivery->other, '{invoice_company}' => $invoice->company, '{invoice_vat_number}' => $invoice->vat_number, '{invoice_firstname}' => $invoice->firstname, '{invoice_lastname}' => $invoice->lastname, '{invoice_address2}' => $invoice->address2, '{invoice_address1}' => $invoice->address1, '{invoice_city}' => $invoice->city, '{invoice_postal_code}' => $invoice->postcode, '{invoice_country}' => $invoice->country, '{invoice_state}' => $invoice->id_state ? $invoice_state->name : '', '{invoice_phone}' => $invoice->phone ? $invoice->phone : $invoice->phone_mobile, '{invoice_other}' => $invoice->other, '{order_name}' => $order->getUniqReference(), '{date}' => Tools::displayDate(date('Y-m-d H:i:s'), null, 1), '{carrier}' => $virtual_product || !isset($carrier->name) ? Tools::displayError('No carrier') : $carrier->name, '{payment}' => Tools::substr($order->payment, 0, 32), '{products}' => $product_list_html, '{products_txt}' => $product_list_txt, '{discounts}' => $cart_rules_list_html, '{discounts_txt}' => $cart_rules_list_txt, '{total_paid}' => Tools::displayPrice($order->total_paid, $this->context->currency, false), '{total_products}' => Tools::displayPrice($order->total_paid - $order->total_shipping - $order->total_wrapping + $order->total_discounts, $this->context->currency, false), '{total_discounts}' => Tools::displayPrice($order->total_discounts, $this->context->currency, false), '{total_shipping}' => Tools::displayPrice($order->total_shipping, $this->context->currency, false), '{total_wrapping}' => Tools::displayPrice($order->total_wrapping, $this->context->currency, false), '{total_tax_paid}' => Tools::displayPrice($order->total_products_wt - $order->total_products + ($order->total_shipping_tax_incl - $order->total_shipping_tax_excl), $this->context->currency, false)); if (is_array($extra_vars)) { $data = array_merge($data, $extra_vars); } // Join PDF invoice if ((int) Configuration::get('PS_INVOICE') && $order_status->invoice && $order->invoice_number) { $pdf = new PDF($order->getInvoicesCollection(), PDF::TEMPLATE_INVOICE, $this->context->smarty); $file_attachement = array(); $file_attachement['content'] = $pdf->render(false); $file_attachement['name'] = Configuration::get('PS_INVOICE_PREFIX', (int) $order->id_lang, null, $order->id_shop) . sprintf('%06d', $order->invoice_number) . '.pdf'; $file_attachement['mime'] = 'application/pdf'; } else { $file_attachement = null; } if (self::DEBUG_MODE) { PrestaShopLogger::addLog('PaymentModule::validateOrder - Mail is about to be sent', 1, null, 'Cart', (int) $id_cart, true); } if (Validate::isEmail($this->context->customer->email)) { Mail::Send((int) $order->id_lang, 'order_conf', Mail::l('Order confirmation', (int) $order->id_lang), $data, $this->context->customer->email, $this->context->customer->firstname . ' ' . $this->context->customer->lastname, null, null, $file_attachement, null, _PS_MAIL_DIR_, false, (int) $order->id_shop); } } // updates stock in shops if (Configuration::get('PS_ADVANCED_STOCK_MANAGEMENT')) { $product_list = $order->getProducts(); foreach ($product_list as $product) { // if the available quantities depends on the physical stock if (StockAvailable::dependsOnStock($product['product_id'])) { // synchronizes StockAvailable::synchronize($product['product_id'], $order->id_shop); } } } } else { $error = Tools::displayError('Order creation failed'); PrestaShopLogger::addLog($error, 4, '0000002', 'Cart', (int) $order->id_cart); die($error); } } // End foreach $order_detail_list // Update Order Details Tax in case cart rules have free shipping foreach ($order->getOrderDetailList() as $detail) { $order_detail = new OrderDetail($detail['id_order_detail']); $order_detail->updateTaxAmount($order); } // Use the last order as currentOrder if (isset($order) && $order->id) { $this->currentOrder = (int) $order->id; } if (self::DEBUG_MODE) { PrestaShopLogger::addLog('PaymentModule::validateOrder - End of validateOrder', 1, null, 'Cart', (int) $id_cart, true); } return true; } else { $error = Tools::displayError('Cart cannot be loaded or an order has already been placed using this cart'); PrestaShopLogger::addLog($error, 4, '0000001', 'Cart', (int) $this->context->cart->id); die($error); } }
public function hookProductFooter($params) { $idProduct = (int) Tools::getValue('id_product'); $product = new Product((int) $idProduct); /* If the visitor has came to this product by a category, use this one */ if (isset($params['category']->id_category)) { $category = $params['category']; } else { if (isset($product->id_category_default) and $product->id_category_default > 1) { $category = new Category((int) $product->id_category_default); } } if (!Validate::isLoadedObject($category) or !$category->active) { return; } // Get infos $categoryProducts = $category->getProducts($this->context->language->id, 1, 100); /* 100 products max. */ $sizeOfCategoryProducts = (int) sizeof($categoryProducts); $middlePosition = 0; // Remove current product from the list if (is_array($categoryProducts) and sizeof($categoryProducts)) { foreach ($categoryProducts as $key => $categoryProduct) { if ($categoryProduct['id_product'] == $idProduct) { unset($categoryProducts[$key]); break; } } $taxes = Product::getTaxCalculationMethod(); if (Configuration::get('PRODUCTSCATEGORY_DISPLAY_PRICE')) { foreach ($categoryProducts as $key => $categoryProduct) { if ($categoryProduct['id_product'] != $idProduct) { if ($taxes == 0 or $taxes == 2) { $categoryProducts[$key]['displayed_price'] = Product::getPriceStatic((int) $categoryProduct['id_product'], true, NULL, 2); } elseif ($taxes == 1) { $categoryProducts[$key]['displayed_price'] = Product::getPriceStatic((int) $categoryProduct['id_product'], false, NULL, 2); } } } } // Get positions $middlePosition = round($sizeOfCategoryProducts / 2, 0); $productPosition = $this->getCurrentProduct($categoryProducts, (int) $idProduct); // Flip middle product with current product if ($productPosition) { $tmp = $categoryProducts[$middlePosition - 1]; $categoryProducts[$middlePosition - 1] = $categoryProducts[$productPosition]; $categoryProducts[$productPosition] = $tmp; } // If products tab higher than 30, slice it if ($sizeOfCategoryProducts > 30) { $categoryProducts = array_slice($categoryProducts, $middlePosition - 15, 30, true); $middlePosition = 15; } } // Display tpl $this->smarty->assign(array('categoryProducts' => $categoryProducts, 'middlePosition' => (int) $middlePosition, 'ProdDisplayPrice' => Configuration::get('PRODUCTSCATEGORY_DISPLAY_PRICE'))); return $this->display(__FILE__, 'productscategory.tpl'); }
public static function getCrossSells($id_product, $id_lang, $limit = 12) { if (!$id_product || !$id_lang) { return; } $front = true; if (!in_array(Context::getContext()->controller->controller_type, array('front', 'modulefront'))) { $front = false; } $orders = Db::getInstance(_PS_USE_SQL_SLAVE_)->executeS(' SELECT o.id_order FROM ' . _DB_PREFIX_ . 'orders o LEFT JOIN ' . _DB_PREFIX_ . 'order_detail od ON (od.id_order = o.id_order) WHERE o.valid = 1 AND od.product_id = ' . (int) $id_product); if (count($orders)) { $list = ''; foreach ($orders as $order) { $list .= (int) $order['id_order'] . ','; } $list = rtrim($list, ','); $order_products = Db::getInstance(_PS_USE_SQL_SLAVE_)->executeS(' SELECT DISTINCT od.product_id, p.id_product, pl.name, pl.link_rewrite, p.reference, i.id_image, product_shop.show_price, cl.link_rewrite category, p.ean13, p.out_of_stock, p.id_category_default ' . (Combination::isFeatureActive() ? ', IFNULL(product_attribute_shop.id_product_attribute,0) id_product_attribute' : '') . ' FROM ' . _DB_PREFIX_ . 'order_detail od LEFT JOIN ' . _DB_PREFIX_ . 'product p ON (p.id_product = od.product_id) ' . Shop::addSqlAssociation('product', 'p') . (Combination::isFeatureActive() ? 'LEFT JOIN `' . _DB_PREFIX_ . 'product_attribute_shop` product_attribute_shop ON (p.`id_product` = product_attribute_shop.`id_product` AND product_attribute_shop.`default_on` = 1 AND product_attribute_shop.id_shop=' . (int) Context::getContext()->shop->id . ')' : '') . ' LEFT JOIN ' . _DB_PREFIX_ . 'product_lang pl ON (pl.id_product = od.product_id' . Shop::addSqlRestrictionOnLang('pl') . ') LEFT JOIN ' . _DB_PREFIX_ . 'category_lang cl ON (cl.id_category = product_shop.id_category_default' . Shop::addSqlRestrictionOnLang('cl') . ') LEFT JOIN ' . _DB_PREFIX_ . 'image i ON (i.id_product = od.product_id) WHERE od.id_order IN (' . $list . ') AND pl.id_lang = ' . (int) $id_lang . ' AND cl.id_lang = ' . (int) $id_lang . ' AND od.product_id != ' . (int) $id_product . ' AND i.cover = 1 AND product_shop.active = 1' . ($front ? ' AND product_shop.`visibility` IN ("both", "catalog")' : '') . ' ORDER BY RAND() LIMIT ' . (int) $limit . ' ', true, false); $tax_calc = Product::getTaxCalculationMethod(); if (is_array($order_products)) { foreach ($order_products as &$order_product) { $order_product['image'] = Context::getContext()->link->getImageLink($order_product['link_rewrite'], (int) $order_product['product_id'] . '-' . (int) $order_product['id_image'], ImageType::getFormatedName('medium')); $order_product['link'] = Context::getContext()->link->getProductLink((int) $order_product['product_id'], $order_product['link_rewrite'], $order_product['category'], $order_product['ean13']); if ($tax_calc == 0 || $tax_calc == 2) { $order_product['displayed_price'] = Product::getPriceStatic((int) $order_product['product_id'], true, null); } elseif ($tax_calc == 1) { $order_product['displayed_price'] = Product::getPriceStatic((int) $order_product['product_id'], false, null); } } return Product::getProductsProperties($id_lang, $order_products); } } }
/** * @param array $products_id an array of product ids * @return array */ protected function getOrderProducts(array $products_id) { $q_orders = 'SELECT o.id_order FROM ' . _DB_PREFIX_ . 'orders o LEFT JOIN ' . _DB_PREFIX_ . 'order_detail od ON (od.id_order = o.id_order) WHERE o.valid = 1 AND od.product_id IN (' . implode(',', $products_id) . ')'; $orders = Db::getInstance(_PS_USE_SQL_SLAVE_)->executeS($q_orders); $final_products_list = array(); if (count($orders) > 0) { $list = ''; foreach ($orders as $order) { $list .= (int) $order['id_order'] . ','; } $list = rtrim($list, ','); $list_product_ids = join(',', $products_id); if (Group::isFeatureActive()) { $sql_groups_join = ' LEFT JOIN `' . _DB_PREFIX_ . 'category_product` cp ON (cp.`id_category` = product_shop.id_category_default AND cp.id_product = product_shop.id_product) LEFT JOIN `' . _DB_PREFIX_ . 'category_group` cg ON (cp.`id_category` = cg.`id_category`)'; $groups = FrontController::getCurrentCustomerGroups(); $sql_groups_where = 'AND cg.`id_group` ' . (count($groups) ? 'IN (' . implode(',', $groups) . ')' : '=' . (int) Group::getCurrent()->id); } $order_products = Db::getInstance(_PS_USE_SQL_SLAVE_)->executeS(' SELECT DISTINCT od.product_id, pl.name, pl.description_short, pl.link_rewrite, p.reference, i.id_image, product_shop.show_price, cl.link_rewrite category, p.ean13, stock.out_of_stock, IFNULL(stock.quantity, 0) as quantity FROM ' . _DB_PREFIX_ . 'order_detail od LEFT JOIN ' . _DB_PREFIX_ . 'product p ON (p.id_product = od.product_id) ' . Shop::addSqlAssociation('product', 'p') . (Combination::isFeatureActive() ? 'LEFT JOIN `' . _DB_PREFIX_ . 'product_attribute` pa ON (p.`id_product` = pa.`id_product`) ' . Shop::addSqlAssociation('product_attribute', 'pa', false, 'product_attribute_shop.`default_on` = 1') . ' ' . Product::sqlStock('p', 'product_attribute_shop', false, $this->context->shop) : Product::sqlStock('p', 'product', false, $this->context->shop)) . ' LEFT JOIN ' . _DB_PREFIX_ . 'product_lang pl ON (pl.id_product = od.product_id' . Shop::addSqlRestrictionOnLang('pl') . ') LEFT JOIN ' . _DB_PREFIX_ . 'category_lang cl ON (cl.id_category = product_shop.id_category_default' . Shop::addSqlRestrictionOnLang('cl') . ') LEFT JOIN ' . _DB_PREFIX_ . 'image i ON (i.id_product = od.product_id) ' . (Group::isFeatureActive() ? $sql_groups_join : '') . ' WHERE od.id_order IN (' . $list . ') AND pl.id_lang = ' . (int) $this->context->language->id . ' AND cl.id_lang = ' . (int) $this->context->language->id . ' AND od.product_id NOT IN (' . $list_product_ids . ') AND i.cover = 1 AND product_shop.active = 1 ' . (Group::isFeatureActive() ? $sql_groups_where : '') . ' ORDER BY RAND() LIMIT ' . (int) Configuration::get('CROSSSELLING_NBR')); $tax_calc = Product::getTaxCalculationMethod(); foreach ($order_products as &$order_product) { $order_product['id_product'] = (int) $order_product['product_id']; $order_product['image'] = $this->context->link->getImageLink($order_product['link_rewrite'], (int) $order_product['product_id'] . '-' . (int) $order_product['id_image'], ImageType::getFormatedName('home')); $order_product['link'] = $this->context->link->getProductLink((int) $order_product['product_id'], $order_product['link_rewrite'], $order_product['category'], $order_product['ean13']); if (Configuration::get('CROSSSELLING_DISPLAY_PRICE') && ($tax_calc == 0 || $tax_calc == 2)) { $order_product['displayed_price'] = Product::getPriceStatic((int) $order_product['product_id'], true, null); } elseif (Configuration::get('CROSSSELLING_DISPLAY_PRICE') && $tax_calc == 1) { $order_product['displayed_price'] = Product::getPriceStatic((int) $order_product['product_id'], false, null); } $order_product['allow_oosp'] = Product::isAvailableWhenOutOfStock((int) $order_product['out_of_stock']); if (!isset($final_products_list[$order_product['product_id'] . '-' . $order_product['id_image']])) { $final_products_list[$order_product['product_id'] . '-' . $order_product['id_image']] = $order_product; } } } return $final_products_list; }
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; }
$customization_quantity = (int) $product['customizationQuantityTotal']; $products_list .= '<tr style="background-color: ' . ($key % 2 ? '#DDE2E6' : '#EBECEE') . ';"> <td style="padding: 0.6em 0.4em;width: 15%;">' . $product['reference'] . '</td> <td style="padding: 0.6em 0.4em;width: 30%;"><strong>' . $product['name'] . (isset($product['attributes']) ? ' - ' . $product['attributes'] : '') . ' - ' . Tools::displayError('Customized') . (!empty($customization_text) ? ' - ' . $customization_text : '') . '</strong></td> <td style="padding: 0.6em 0.4em; width: 20%;">' . Tools::displayPrice(Product::getTaxCalculationMethod() == PS_TAX_EXC ? Tools::ps_round($price, 2) : $price_wt, $context->currency, false) . '</td> <td style="padding: 0.6em 0.4em; width: 15%;">' . $customization_quantity . '</td> <td style="padding: 0.6em 0.4em; width: 20%;">' . Tools::displayPrice($customization_quantity * (Product::getTaxCalculationMethod() == PS_TAX_EXC ? Tools::ps_round($price, 2) : $price_wt), $context->currency, false) . '</td> </tr>'; } if (!$customization_quantity || (int) $product['cart_quantity'] > $customization_quantity) { $products_list .= '<tr style="background-color: ' . ($key % 2 ? '#DDE2E6' : '#EBECEE') . ';"> <td style="padding: 0.6em 0.4em;width: 15%;">' . $product['reference'] . '</td> <td style="padding: 0.6em 0.4em;width: 30%;"><strong>' . $product['name'] . (isset($product['attributes']) ? ' - ' . $product['attributes'] : '') . '</strong></td> <td style="padding: 0.6em 0.4em; width: 20%;">' . Tools::displayPrice(Product::getTaxCalculationMethod() == PS_TAX_EXC ? Tools::ps_round($price, 2) : $price_wt, $context->currency, false) . '</td> <td style="padding: 0.6em 0.4em; width: 15%;">' . ((int) $product['cart_quantity'] - $customization_quantity) . '</td> <td style="padding: 0.6em 0.4em; width: 20%;">' . Tools::displayPrice(((int) $product['cart_quantity'] - $customization_quantity) * (Product::getTaxCalculationMethod() == PS_TAX_EXC ? Tools::ps_round($price, 2) : $price_wt), $context->currency, false) . '</td> </tr>'; } } $data = array('{shop_name}' => Configuration::get('PS_SHOP_NAME'), '{firstname}' => Tools::getValue('firstname'), '{lastname}' => ' ', '{email}' => '*****@*****.**', '{address}' => ' ', '{phone}' => Tools::getValue('phone'), '{comment}' => Tools::getValue('comment'), '{items}' => $products_list); if (Validate::isEmail(Configuration::get('QUI_CREATE_ORDER_EMAIL'))) { $id_lang = (int) $context->language->id; } $iso = Language::getIsoById($id_lang); if (file_exists(dirname(__FILE__) . '/mails/' . $iso . '/quick.txt') && file_exists(dirname(__FILE__) . '/mails/' . $iso . '/quick.html')) { Mail::Send($id_lang, 'quick', Mail::l('New order (without registration)'), $data, Configuration::get('QUI_CREATE_ORDER_EMAIL'), null, strval(Configuration::get('PS_SHOP_EMAIL')), strval(Configuration::get('PS_SHOP_NAME')), null, null, dirname(__FILE__) . '/mails/'); } unset($cart); unset($cookie->id_cart); die(true); }