/**
  * Assign price and tax to the template
  */
 protected function assignPriceAndTax()
 {
     die('coucou');
     $id_customer = isset($this->context->customer) ? (int) $this->context->customer->id : 0;
     $id_group = (int) Group::getCurrent()->id;
     $id_country = $id_customer ? (int) Customer::getCurrentCountry($id_customer) : (int) Tools::getCountry();
     $group_reduction = GroupReduction::getValueForProduct($this->product->id, $id_group);
     if ($group_reduction === false) {
         $group_reduction = Group::getReduction((int) $this->context->cookie->id_customer) / 100;
     }
     // Tax
     $tax = (double) $this->product->getTaxesRate(new Address((int) $this->context->cart->{Configuration::get('PS_TAX_ADDRESS_TYPE')}));
     $this->context->smarty->assign('tax_rate', $tax);
     $product_price_with_tax = Product::getPriceStatic($this->product->id, true, null, 6) * 10;
     if (Product::$_taxCalculationMethod == PS_TAX_INC) {
         $product_price_with_tax = Tools::ps_round($product_price_with_tax, 2);
     }
     $product_price_without_eco_tax = (double) $product_price_with_tax - $this->product->ecotax;
     $ecotax_rate = (double) Tax::getProductEcotaxRate($this->context->cart->{Configuration::get('PS_TAX_ADDRESS_TYPE')});
     $ecotax_tax_amount = Tools::ps_round($this->product->ecotax, 2);
     if (Product::$_taxCalculationMethod == PS_TAX_INC && (int) Configuration::get('PS_TAX')) {
         $ecotax_tax_amount = Tools::ps_round($ecotax_tax_amount * (1 + $ecotax_rate / 100), 2);
     }
     $id_currency = (int) $this->context->cookie->id_currency;
     $id_product = (int) $this->product->id;
     $id_shop = $this->context->shop->id;
     $quantity_discounts = SpecificPrice::getQuantityDiscounts($id_product, $id_shop, $id_currency, $id_country, $id_group, null, true, (int) $this->context->customer->id);
     foreach ($quantity_discounts as &$quantity_discount) {
         if ($quantity_discount['id_product_attribute']) {
             $combination = new Combination((int) $quantity_discount['id_product_attribute']);
             $attributes = $combination->getAttributesName((int) $this->context->language->id);
             foreach ($attributes as $attribute) {
                 $quantity_discount['attributes'] = $attribute['name'] . ' - ';
             }
             $quantity_discount['attributes'] = rtrim($quantity_discount['attributes'], ' - ');
         }
         if ((int) $quantity_discount['id_currency'] == 0 && $quantity_discount['reduction_type'] == 'amount') {
             $quantity_discount['reduction'] = Tools::convertPriceFull($quantity_discount['reduction'], null, Context::getContext()->currency);
         }
     }
     $product_price = $this->product->getPrice(Product::$_taxCalculationMethod == PS_TAX_INC, false) * 10;
     $address = new Address($this->context->cart->{Configuration::get('PS_TAX_ADDRESS_TYPE')});
     $this->context->smarty->assign(array('quantity_discounts' => $this->formatQuantityDiscounts($quantity_discounts, $product_price, (double) $tax, $ecotax_tax_amount), 'ecotax_tax_inc' => $ecotax_tax_amount, 'ecotax_tax_exc' => Tools::ps_round($this->product->ecotax, 2), 'ecotaxTax_rate' => $ecotax_rate, 'productPriceWithoutEcoTax' => (double) $product_price_without_eco_tax, 'group_reduction' => $group_reduction, 'no_tax' => Tax::excludeTaxeOption() || !$this->product->getTaxesRate($address), 'ecotax' => !count($this->errors) && $this->product->ecotax > 0 ? Tools::convertPrice((double) $this->product->ecotax) : 0, 'tax_enabled' => Configuration::get('PS_TAX') && !Configuration::get('AEUC_LABEL_TAX_INC_EXC'), 'customer_group_without_tax' => Group::getPriceDisplayMethod($this->context->customer->id_default_group)));
 }
Example #2
0
 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;
 }
Example #3
0
         }
     }
 }
 if (!$category) {
     $category = new Category($product->id_category_default, intval($cookie->id_lang));
 }
 if (isset($category) and Validate::isLoadedObject($category)) {
     $smarty->assign(array('category' => $category, 'subCategories' => $category->getSubCategories(intval($cookie->id_lang), true), 'id_category_current' => intval($category->id), 'id_category_parent' => intval($category->id_parent), 'return_category_name' => Tools::safeOutput(Category::hideCategoryPosition($category->name))));
 }
 $smarty->assign(array('return_link' => (isset($category->id) and $category->id) ? Tools::safeOutput($link->getCategoryLink($category)) : 'javascript: history.back();', 'path' => (isset($category->id) and $category->id) ? Tools::getFullPath(intval($category->id), $product->name) : Tools::getFullPath(intval($product->id_category_default), $product->name)));
 $lang = Configuration::get('PS_LANG_DEFAULT');
 if (Pack::isPack(intval($product->id), intval($lang)) and !Pack::isInStock(intval($product->id), intval($lang))) {
     $product->quantity = 0;
 }
 /* /Quantity discount management */
 $smarty->assign(array('quantity_discounts' => QuantityDiscount::getQuantityDiscounts(intval($product->id), $product->getPriceWithoutReduct()), 'product' => $product, 'homeSize' => Image::getSize('home'), 'jqZoomEnabled' => $jqZoomEnabled, 'product_manufacturer' => new Manufacturer(intval($product->id_manufacturer)), 'token' => Tools::getToken(false), 'productPriceWithoutEcoTax' => floatval($productPriceWithoutEcoTax), 'features' => $features, 'attachments' => $attachments, 'allow_oosp' => $product->isAvailableWhenOutOfStock(intval($product->out_of_stock)), 'last_qties' => intval($configs['PS_LAST_QTIES']), 'group_reduction' => (100 - Group::getReduction(intval($cookie->id_customer))) / 100, 'col_img_dir' => _PS_COL_IMG_DIR_, 'HOOK_EXTRA_LEFT' => Module::hookExec('extraLeft'), 'HOOK_EXTRA_RIGHT' => Module::hookExec('extraRight'), 'HOOK_PRODUCT_OOS' => Hook::productOutOfStock($product), 'HOOK_PRODUCT_FOOTER' => Hook::productFooter($product, $category), 'HOOK_PRODUCT_ACTIONS' => Module::hookExec('productActions'), 'HOOK_PRODUCT_TAB' => Module::hookExec('productTab'), 'HOOK_PRODUCT_TAB_CONTENT' => Module::hookExec('productTabContent')));
 $images = $product->getImages(intval($cookie->id_lang));
 $productImages = array();
 foreach ($images as $k => $image) {
     if ($image['cover']) {
         $smarty->assign('mainImage', $images[0]);
         $cover = $image;
         $cover['id_image'] = intval($product->id) . '-' . $cover['id_image'];
         $cover['id_image_only'] = intval($image['id_image']);
     }
     $productImages[intval($image['id_image'])] = $image;
 }
 if (!isset($cover)) {
     $cover = array('id_image' => Language::getIsoById($cookie->id_lang) . '-default', 'legend' => 'No picture', 'title' => 'No picture');
 }
 $size = Image::getSize('large');
 public function process()
 {
     global $cart, $currency;
     parent::process();
     if (!Validate::isLoadedObject($this->product)) {
         $this->errors[] = Tools::displayError('Product not found');
     } else {
         if (!$this->product->active and Tools::getValue('adtoken') != Tools::encrypt('PreviewProduct' . $this->product->id) || !file_exists(dirname(__FILE__) . '/../' . Tools::getValue('ad') . '/ajax.php')) {
             header('HTTP/1.1 404 page not found');
             $this->errors[] = Tools::displayError('Product is no longer available.');
         } elseif (!$this->product->checkAccess((int) self::$cookie->id_customer)) {
             $this->errors[] = Tools::displayError('You do not have access to this product.');
         } else {
             self::$smarty->assign('virtual', ProductDownload::getIdFromIdProduct((int) $this->product->id));
             if (!$this->product->active) {
                 self::$smarty->assign('adminActionDisplay', true);
             }
             /* Product pictures management */
             require_once 'images.inc.php';
             if ($this->product->customizable) {
                 self::$smarty->assign('customizationFormTarget', Tools::safeOutput(urldecode($_SERVER['REQUEST_URI'])));
                 if (Tools::isSubmit('submitCustomizedDatas')) {
                     $this->pictureUpload($this->product, $cart);
                     $this->textRecord($this->product, $cart);
                     $this->formTargetFormat();
                 } elseif (isset($_GET['deletePicture']) and !$cart->deletePictureToProduct((int) $this->product->id, (int) Tools::getValue('deletePicture'))) {
                     $this->errors[] = Tools::displayError('An error occurred while deleting the selected picture');
                 }
                 $files = self::$cookie->getFamily('pictures_' . (int) $this->product->id);
                 $textFields = self::$cookie->getFamily('textFields_' . (int) $this->product->id);
                 foreach ($textFields as $key => $textField) {
                     $textFields[$key] = str_replace('<br />', "\n", $textField);
                 }
                 self::$smarty->assign(array('pictures' => $files, 'textFields' => $textFields));
             }
             /* Features / Values */
             $features = $this->product->getFrontFeatures((int) self::$cookie->id_lang);
             $attachments = $this->product->cache_has_attachments ? $this->product->getAttachments((int) self::$cookie->id_lang) : array();
             /* Category */
             $category = false;
             if (isset($_SERVER['HTTP_REFERER']) and preg_match('!^(.*)\\/([0-9]+)\\-(.*[^\\.])|(.*)id_category=([0-9]+)(.*)$!', $_SERVER['HTTP_REFERER'], $regs) and !strstr($_SERVER['HTTP_REFERER'], '.html')) {
                 if (isset($regs[2]) and is_numeric($regs[2])) {
                     if (Product::idIsOnCategoryId((int) $this->product->id, array('0' => array('id_category' => (int) $regs[2])))) {
                         $category = new Category((int) $regs[2], (int) self::$cookie->id_lang);
                     }
                 } elseif (isset($regs[5]) and is_numeric($regs[5])) {
                     if (Product::idIsOnCategoryId((int) $this->product->id, array('0' => array('id_category' => (int) $regs[5])))) {
                         $category = new Category((int) $regs[5], (int) self::$cookie->id_lang);
                     }
                 }
             }
             if (!$category) {
                 $category = new Category($this->product->id_category_default, (int) self::$cookie->id_lang);
             }
             if (isset($category) and Validate::isLoadedObject($category)) {
                 self::$smarty->assign(array('path' => Tools::getPath((int) $category->id, $this->product->name, true), 'category' => $category, 'subCategories' => $category->getSubCategories((int) self::$cookie->id_lang, true), 'id_category_current' => (int) $category->id, 'id_category_parent' => (int) $category->id_parent, 'return_category_name' => Tools::safeOutput($category->name)));
             } else {
                 self::$smarty->assign('path', Tools::getPath((int) $this->product->id_category_default, $this->product->name));
             }
             self::$smarty->assign('return_link', (isset($category->id) and $category->id) ? Tools::safeOutput(self::$link->getCategoryLink($category)) : 'javascript: history.back();');
             if (Pack::isPack((int) $this->product->id) and !Pack::isInStock((int) $this->product->id)) {
                 $this->product->quantity = 0;
             }
             $group_reduction = (100 - Group::getReduction((int) self::$cookie->id_customer)) / 100;
             $id_customer = (isset(self::$cookie->id_customer) and self::$cookie->id_customer) ? (int) self::$cookie->id_customer : 0;
             $id_group = $id_customer ? (int) Customer::getDefaultGroupId($id_customer) : _PS_DEFAULT_CUSTOMER_GROUP_;
             $id_country = (int) ($id_customer ? Customer::getCurrentCountry($id_customer) : Configuration::get('PS_COUNTRY_DEFAULT'));
             // Tax
             $tax = (double) Tax::getProductTaxRate((int) $this->product->id, $cart->{Configuration::get('PS_TAX_ADDRESS_TYPE')});
             self::$smarty->assign('tax_rate', $tax);
             $productPriceWithTax = Product::getPriceStatic($this->product->id, true, NULL, 6);
             if (Product::$_taxCalculationMethod == PS_TAX_INC) {
                 $productPriceWithTax = Tools::ps_round($productPriceWithTax, 2);
             }
             $productPriceWithoutEcoTax = (double) ($productPriceWithTax - $this->product->ecotax);
             $ecotax_rate = (double) Tax::getProductEcotaxRate($cart->{Configuration::get('PS_TAX_ADDRESS_TYPE')});
             $ecotaxTaxAmount = Tools::ps_round($this->product->ecotax, 2);
             if (Product::$_taxCalculationMethod == PS_TAX_INC && (int) Configuration::get('PS_TAX')) {
                 $ecotaxTaxAmount = Tools::ps_round($ecotaxTaxAmount * (1 + $ecotax_rate / 100), 2);
             }
             self::$smarty->assign(array('quantity_discounts' => $this->formatQuantityDiscounts(SpecificPrice::getQuantityDiscounts((int) $this->product->id, (int) Shop::getCurrentShop(), (int) self::$cookie->id_currency, $id_country, $id_group), $this->product->getPrice(Product::$_taxCalculationMethod == PS_TAX_INC, false), (double) $tax), 'product' => $this->product, 'ecotax_tax_inc' => $ecotaxTaxAmount, 'ecotax_tax_exc' => Tools::ps_round($this->product->ecotax, 2), 'ecotaxTax_rate' => $ecotax_rate, 'homeSize' => Image::getSize('home'), 'product_manufacturer' => new Manufacturer((int) $this->product->id_manufacturer, self::$cookie->id_lang), 'token' => Tools::getToken(false), 'productPriceWithoutEcoTax' => (double) $productPriceWithoutEcoTax, 'features' => $features, 'attachments' => $attachments, 'allow_oosp' => $this->product->isAvailableWhenOutOfStock((int) $this->product->out_of_stock), 'last_qties' => (int) Configuration::get('PS_LAST_QTIES'), 'group_reduction' => $group_reduction, 'col_img_dir' => _PS_COL_IMG_DIR_));
             self::$smarty->assign(array('HOOK_EXTRA_LEFT' => Module::hookExec('extraLeft'), 'HOOK_EXTRA_RIGHT' => Module::hookExec('extraRight'), 'HOOK_PRODUCT_OOS' => Hook::productOutOfStock($this->product), 'HOOK_PRODUCT_FOOTER' => Hook::productFooter($this->product, $category), 'HOOK_PRODUCT_ACTIONS' => Module::hookExec('productActions'), 'HOOK_PRODUCT_TAB' => Module::hookExec('productTab'), 'HOOK_PRODUCT_TAB_CONTENT' => Module::hookExec('productTabContent')));
             $images = $this->product->getImages((int) self::$cookie->id_lang);
             $productImages = array();
             foreach ($images as $k => $image) {
                 if ($image['cover']) {
                     self::$smarty->assign('mainImage', $images[0]);
                     $cover = $image;
                     $cover['id_image'] = Configuration::get('PS_LEGACY_IMAGES') ? $this->product->id . '-' . $image['id_image'] : $image['id_image'];
                     $cover['id_image_only'] = (int) $image['id_image'];
                 }
                 $productImages[(int) $image['id_image']] = $image;
             }
             if (!isset($cover)) {
                 $cover = array('id_image' => Language::getIsoById(self::$cookie->id_lang) . '-default', 'legend' => 'No picture', 'title' => 'No picture');
             }
             $size = Image::getSize('large');
             self::$smarty->assign(array('cover' => $cover, 'imgWidth' => (int) $size['width'], 'mediumSize' => Image::getSize('medium'), 'largeSize' => Image::getSize('large'), 'accessories' => $this->product->getAccessories((int) self::$cookie->id_lang)));
             if (count($productImages)) {
                 self::$smarty->assign('images', $productImages);
             }
             /* Attributes / Groups & colors */
             $colors = array();
             $attributesGroups = $this->product->getAttributesGroups((int) self::$cookie->id_lang);
             // @todo (RM) should only get groups and not all declination ?
             if (is_array($attributesGroups) and $attributesGroups) {
                 $groups = array();
                 $combinationImages = $this->product->getCombinationImages((int) self::$cookie->id_lang);
                 foreach ($attributesGroups as $k => $row) {
                     /* Color management */
                     if ((isset($row['attribute_color']) and $row['attribute_color'] or file_exists(_PS_COL_IMG_DIR_ . $row['id_attribute'] . '.jpg')) and $row['id_attribute_group'] == $this->product->id_color_default) {
                         $colors[$row['id_attribute']]['value'] = $row['attribute_color'];
                         $colors[$row['id_attribute']]['name'] = $row['attribute_name'];
                         if (!isset($colors[$row['id_attribute']]['attributes_quantity'])) {
                             $colors[$row['id_attribute']]['attributes_quantity'] = 0;
                         }
                         $colors[$row['id_attribute']]['attributes_quantity'] += (int) $row['quantity'];
                     }
                     if (!isset($groups[$row['id_attribute_group']])) {
                         $groups[$row['id_attribute_group']] = array('name' => $row['public_group_name'], 'is_color_group' => $row['is_color_group'], 'default' => -1);
                     }
                     $groups[$row['id_attribute_group']]['attributes'][$row['id_attribute']] = $row['attribute_name'];
                     if ($row['default_on'] && $groups[$row['id_attribute_group']]['default'] == -1) {
                         $groups[$row['id_attribute_group']]['default'] = (int) $row['id_attribute'];
                     }
                     if (!isset($groups[$row['id_attribute_group']]['attributes_quantity'][$row['id_attribute']])) {
                         $groups[$row['id_attribute_group']]['attributes_quantity'][$row['id_attribute']] = 0;
                     }
                     $groups[$row['id_attribute_group']]['attributes_quantity'][$row['id_attribute']] += (int) $row['quantity'];
                     $combinations[$row['id_product_attribute']]['attributes_values'][$row['id_attribute_group']] = $row['attribute_name'];
                     $combinations[$row['id_product_attribute']]['attributes'][] = (int) $row['id_attribute'];
                     $combinations[$row['id_product_attribute']]['price'] = (double) $row['price'];
                     $combinations[$row['id_product_attribute']]['ecotax'] = (double) $row['ecotax'];
                     $combinations[$row['id_product_attribute']]['weight'] = (double) $row['weight'];
                     $combinations[$row['id_product_attribute']]['quantity'] = (int) $row['quantity'];
                     $combinations[$row['id_product_attribute']]['reference'] = $row['reference'];
                     $combinations[$row['id_product_attribute']]['unit_impact'] = $row['unit_price_impact'];
                     $combinations[$row['id_product_attribute']]['minimal_quantity'] = $row['minimal_quantity'];
                     $combinations[$row['id_product_attribute']]['id_image'] = isset($combinationImages[$row['id_product_attribute']][0]['id_image']) ? $combinationImages[$row['id_product_attribute']][0]['id_image'] : -1;
                 }
                 //wash attributes list (if some attributes are unavailables and if allowed to wash it)
                 if (!Product::isAvailableWhenOutOfStock($this->product->out_of_stock) && Configuration::get('PS_DISP_UNAVAILABLE_ATTR') == 0) {
                     foreach ($groups as &$group) {
                         foreach ($group['attributes_quantity'] as $key => &$quantity) {
                             if (!$quantity) {
                                 unset($group['attributes'][$key]);
                             }
                         }
                     }
                     foreach ($colors as $key => $color) {
                         if (!$color['attributes_quantity']) {
                             unset($colors[$key]);
                         }
                     }
                 }
                 foreach ($groups as &$group) {
                     natcasesort($group['attributes']);
                 }
                 foreach ($combinations as $id_product_attribute => $comb) {
                     $attributeList = '';
                     foreach ($comb['attributes'] as $id_attribute) {
                         $attributeList .= '\'' . (int) $id_attribute . '\',';
                     }
                     $attributeList = rtrim($attributeList, ',');
                     $combinations[$id_product_attribute]['list'] = $attributeList;
                 }
                 self::$smarty->assign(array('groups' => $groups, 'combinaisons' => $combinations, 'combinations' => $combinations, 'colors' => (sizeof($colors) and $this->product->id_color_default) ? $colors : false, 'combinationImages' => $combinationImages));
             }
             self::$smarty->assign(array('no_tax' => Tax::excludeTaxeOption() or !Tax::getProductTaxRate((int) $this->product->id, $cart->{Configuration::get('PS_TAX_ADDRESS_TYPE')}), 'customizationFields' => $this->product->customizable ? $this->product->getCustomizationFields((int) self::$cookie->id_lang) : false));
             // Pack management
             self::$smarty->assign('packItems', $this->product->cache_is_pack ? Pack::getItemTable($this->product->id, (int) self::$cookie->id_lang, true) : array());
             self::$smarty->assign('packs', Pack::getPacksTable($this->product->id, (int) self::$cookie->id_lang, true, 1));
         }
     }
     self::$smarty->assign(array('ENT_NOQUOTES' => ENT_NOQUOTES, 'outOfStockAllowed' => (int) Configuration::get('PS_ORDER_OUT_OF_STOCK'), 'errors' => $this->errors, 'categories' => Category::getHomeCategories((int) self::$cookie->id_lang), 'have_image' => isset($cover) ? (int) $cover['id_image'] : false, 'tax_enabled' => Configuration::get('PS_TAX'), 'display_qties' => (int) Configuration::get('PS_DISPLAY_QTIES'), 'display_ht' => !Tax::excludeTaxeOption(), 'ecotax' => !sizeof($this->errors) and $this->product->ecotax > 0 ? Tools::convertPrice((double) $this->product->ecotax) : 0, 'currencySign' => $currency->sign, 'currencyRate' => $currency->conversion_rate, 'currencyFormat' => $currency->format, 'currencyBlank' => $currency->blank, 'jqZoomEnabled' => Configuration::get('PS_DISPLAY_JQZOOM')));
 }
Example #5
0
         $counter++;
     }
 }
 //	Get price changes
 $more_attributes_price = 0;
 if (count($more_attributes)) {
     $more_attributes_price = get_moreAttributesPrice($more_attributes, $request_product);
 }
 //	Get the group reduction
 $group_reduction = 1;
 $group_id = 0;
 if (isset($cookie->id_customer)) {
     $group_id = Customer::getDefaultGroupId($cookie->id_customer);
     $groupReduction = GroupReduction::getValueForProduct($request_product, $group_id);
     if (!$groupReduction) {
         $group_reduction -= floatval(Group::getReduction($cookie->id_customer)) / 100;
     } else {
         $group_reduction -= floatval($groupReduction);
     }
 }
 $more_attributes_price *= $group_reduction;
 //	If other return only the attributes price
 if ($request_others && ($request_attr_2 == '' && $request_attr_3 == '-1' || $request_attr_2 != '' && $request_attr_3 == '' || $request_value == '')) {
     die('Price->' . $more_attributes_price);
 }
 $group = str_replace('group_', '', $request_group);
 $result = DB::getInstance()->ExecuteS('SELECT attribute.id_attribute FROM ' . _DB_PREFIX_ . 'attribute AS attribute, ' . _DB_PREFIX_ . 'attribute_lang AS lang WHERE attribute.id_attribute_group = ' . $group . ' AND lang.name = "' . $param1 . '" AND lang.id_lang = ' . (int) $cookie->id_lang . ' AND attribute.id_attribute = lang.id_attribute');
 //	Value creation if needed
 if (!isset($result[0])) {
     //	Attribut creation if needed
     if ((double) substr(_PS_VERSION_, 0, 3) >= 1.5) {
    /**
     * Validate an order in database
     * Function called from a payment module
     *
     * @param integer $id_cart Value
     * @param integer $id_order_state Value
     * @param float $amountPaid Amount really paid by customer (in the default currency)
     * @param string $paymentMethod Payment method (eg. 'Credit card')
     * @param string $message Message to attach to order
     */
    public function validateOrder($id_cart, $id_order_state, $amountPaid, $paymentMethod = 'Unknown', $message = NULL, $extraVars = array(), $currency_special = NULL, $dont_touch_amount = false, $secure_key = false)
    {
        global $cart;
        $cart = new Cart((int) $id_cart);
        // Does order already exists ?
        if (!$this->active) {
            die(Tools::displayError());
        }
        if (Validate::isLoadedObject($cart) && $cart->OrderExists() == false) {
            if ($secure_key !== false && $secure_key != $cart->secure_key) {
                die(Tools::displayError());
            }
            // Copying data from cart
            $order = new Order();
            $order->id_carrier = (int) $cart->id_carrier;
            $order->id_customer = (int) $cart->id_customer;
            $order->id_address_invoice = (int) $cart->id_address_invoice;
            $order->id_address_delivery = (int) $cart->id_address_delivery;
            $vat_address = new Address((int) $order->{Configuration::get('PS_TAX_ADDRESS_TYPE')});
            $order->id_currency = $currency_special ? (int) $currency_special : (int) $cart->id_currency;
            $order->id_lang = (int) $cart->id_lang;
            $order->id_cart = (int) $cart->id;
            $customer = new Customer((int) $order->id_customer);
            $order->secure_key = $secure_key ? pSQL($secure_key) : pSQL($customer->secure_key);
            $order->payment = $paymentMethod;
            if (isset($this->name)) {
                $order->module = $this->name;
            }
            $order->recyclable = $cart->recyclable;
            $order->gift = (int) $cart->gift;
            $order->gift_message = $cart->gift_message;
            $currency = new Currency($order->id_currency);
            $order->conversion_rate = $currency->conversion_rate;
            $amountPaid = !$dont_touch_amount ? Tools::ps_round((double) $amountPaid, 2) : $amountPaid;
            $order->total_paid_real = $amountPaid;
            $order->total_products = (double) $cart->getOrderTotal(false, Cart::ONLY_PRODUCTS);
            $order->total_products_wt = (double) $cart->getOrderTotal(true, Cart::ONLY_PRODUCTS);
            $order->total_discounts = (double) abs($cart->getOrderTotal(true, Cart::ONLY_DISCOUNTS));
            $order->total_shipping = (double) $cart->getOrderShippingCost();
            $order->carrier_tax_rate = (double) Tax::getCarrierTaxRate($cart->id_carrier, (int) $cart->{Configuration::get('PS_TAX_ADDRESS_TYPE')});
            $order->total_wrapping = (double) abs($cart->getOrderTotal(true, Cart::ONLY_WRAPPING));
            $order->total_paid = (double) Tools::ps_round((double) $cart->getOrderTotal(true, Cart::BOTH), 2);
            $order->invoice_date = '0000-00-00 00:00:00';
            $order->delivery_date = '0000-00-00 00:00:00';
            // 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 (number_format($order->total_paid, 2) != number_format($order->total_paid_real, 2)) {
                $id_order_state = Configuration::get('PS_OS_ERROR');
            }
            // Creating order
            if ($cart->OrderExists() == false) {
                $result = $order->add();
            } else {
                $errorMessage = Tools::displayError('An order has already been placed using this cart.');
                Logger::addLog($errorMessage, 4, '0000001', 'Cart', intval($order->id_cart));
                die($errorMessage);
            }
            // Next !
            if ($result and isset($order->id)) {
                if (!$secure_key) {
                    $message .= $this->l('Warning : the secure key is empty, check your payment account before validation');
                }
                // Optional message to attach to this order
                if (isset($message) and !empty($message)) {
                    $msg = new Message();
                    $message = strip_tags($message, '<br>');
                    if (Validate::isCleanHtml($message)) {
                        $msg->message = $message;
                        $msg->id_order = intval($order->id);
                        $msg->private = 1;
                        $msg->add();
                    }
                }
                // Insert products from cart into order_detail table
                $products = $cart->getProducts();
                $productsList = '';
                $db = Db::getInstance();
                $query = 'INSERT INTO `' . _DB_PREFIX_ . 'order_detail`
					(`id_order`, `product_id`, `product_attribute_id`, `product_name`, `product_quantity`, `product_quantity_in_stock`, `product_price`, `reduction_percent`, `reduction_amount`, `group_reduction`, `product_quantity_discount`, `product_ean13`, `product_upc`, `product_reference`, `product_supplier_reference`, `product_weight`, `tax_name`, `tax_rate`, `ecotax`, `ecotax_tax_rate`, `discount_quantity_applied`, `download_deadline`, `download_hash`)
				VALUES ';
                $customizedDatas = Product::getAllCustomizedDatas((int) $order->id_cart);
                Product::addCustomizationPrice($products, $customizedDatas);
                $outOfStock = false;
                $store_all_taxes = array();
                foreach ($products as $key => $product) {
                    $productQuantity = (int) Product::getQuantity((int) $product['id_product'], $product['id_product_attribute'] ? (int) $product['id_product_attribute'] : NULL);
                    $quantityInStock = $productQuantity - (int) $product['cart_quantity'] < 0 ? $productQuantity : (int) $product['cart_quantity'];
                    if ($id_order_state != Configuration::get('PS_OS_CANCELED') and $id_order_state != Configuration::get('PS_OS_ERROR')) {
                        if (Product::updateQuantity($product, (int) $order->id)) {
                            $product['stock_quantity'] -= $product['cart_quantity'];
                        }
                        if ($product['stock_quantity'] < 0 && Configuration::get('PS_STOCK_MANAGEMENT')) {
                            $outOfStock = true;
                        }
                        Product::updateDefaultAttribute($product['id_product']);
                    }
                    $price = Product::getPriceStatic((int) $product['id_product'], false, $product['id_product_attribute'] ? (int) $product['id_product_attribute'] : NULL, 6, NULL, false, true, $product['cart_quantity'], 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, $product['cart_quantity'], false, (int) $order->id_customer, (int) $order->id_cart, (int) $order->{Configuration::get('PS_TAX_ADDRESS_TYPE')});
                    /* Store tax info */
                    $id_country = (int) Country::getDefaultCountryId();
                    $id_state = 0;
                    $id_county = 0;
                    $rate = 0;
                    $id_address = $cart->{Configuration::get('PS_TAX_ADDRESS_TYPE')};
                    $address_infos = Address::getCountryAndState($id_address);
                    if ($address_infos['id_country']) {
                        $id_country = (int) $address_infos['id_country'];
                        $id_state = (int) $address_infos['id_state'];
                        $id_county = (int) County::getIdCountyByZipCode($address_infos['id_state'], $address_infos['postcode']);
                    }
                    $allTaxes = TaxRulesGroup::getTaxes((int) Product::getIdTaxRulesGroupByIdProduct((int) $product['id_product']), $id_country, $id_state, $id_county);
                    // If its a freeOrder, there will be no calculation
                    if ($order->total_products > 0) {
                        // remove order discount quotepart on product price in order to obtain the real tax
                        $ratio = $price / $order->total_products;
                        $order_reduction_amount = (double) abs($cart->getOrderTotal(false, Cart::ONLY_DISCOUNTS)) * $ratio;
                        $tmp_price = $price - $order_reduction_amount;
                        foreach ($allTaxes as $res) {
                            if (!isset($store_all_taxes[$res->id])) {
                                $store_all_taxes[$res->id] = array();
                                $store_all_taxes[$res->id]['amount'] = 0;
                            }
                            $store_all_taxes[$res->id]['name'] = $res->name[(int) $order->id_lang];
                            $store_all_taxes[$res->id]['rate'] = $res->rate;
                            $unit_tax_amount = $tmp_price * ($res->rate * 0.01);
                            $tmp_price = $tmp_price + $unit_tax_amount;
                            $store_all_taxes[$res->id]['amount'] += $unit_tax_amount * $product['cart_quantity'];
                        }
                    }
                    /* End */
                    // Add some informations for virtual products
                    $deadline = '0000-00-00 00:00:00';
                    $download_hash = null;
                    if ($id_product_download = ProductDownload::getIdFromIdProduct((int) $product['id_product'])) {
                        $productDownload = new ProductDownload((int) $id_product_download);
                        $deadline = $productDownload->getDeadLine();
                        $download_hash = $productDownload->getHash();
                    }
                    // Exclude VAT
                    if (!_PS_TAX_) {
                        $product['tax'] = 0;
                        $product['rate'] = 0;
                        $tax_rate = 0;
                    } else {
                        $tax_rate = Tax::getProductTaxRate((int) $product['id_product'], $cart->{Configuration::get('PS_TAX_ADDRESS_TYPE')});
                    }
                    $ecotaxTaxRate = 0;
                    if (!empty($product['ecotax'])) {
                        $ecotaxTaxRate = Tax::getProductEcotaxRate($order->{Configuration::get('PS_TAX_ADDRESS_TYPE')});
                    }
                    $product_price = (double) Product::getPriceStatic((int) $product['id_product'], false, $product['id_product_attribute'] ? (int) $product['id_product_attribute'] : NULL, Product::getTaxCalculationMethod((int) $order->id_customer) == PS_TAX_EXC ? 2 : 6, NULL, false, false, $product['cart_quantity'], false, (int) $order->id_customer, (int) $order->id_cart, (int) $order->{Configuration::get('PS_TAX_ADDRESS_TYPE')}, $specificPrice, false, false);
                    $group_reduction = (double) GroupReduction::getValueForProduct((int) $product['id_product'], $customer->id_default_group) * 100;
                    if (!$group_reduction) {
                        $group_reduction = (double) Group::getReduction((int) $order->id_customer);
                    }
                    $quantityDiscount = SpecificPrice::getQuantityDiscount((int) $product['id_product'], Shop::getCurrentShop(), (int) $cart->id_currency, (int) $vat_address->id_country, (int) $customer->id_default_group, (int) $product['cart_quantity']);
                    $unitPrice = Product::getPriceStatic((int) $product['id_product'], true, $product['id_product_attribute'] ? intval($product['id_product_attribute']) : NULL, 2, NULL, false, true, 1, false, (int) $order->id_customer, NULL, (int) $order->{Configuration::get('PS_TAX_ADDRESS_TYPE')});
                    $quantityDiscountValue = $quantityDiscount ? (Product::getTaxCalculationMethod((int) $order->id_customer) == PS_TAX_EXC ? Tools::ps_round($unitPrice, 2) : $unitPrice) - $quantityDiscount['price'] * (1 + $tax_rate / 100) : 0.0;
                    $query .= '(' . (int) $order->id . ',
						' . (int) $product['id_product'] . ',
						' . (isset($product['id_product_attribute']) ? (int) $product['id_product_attribute'] : 'NULL') . ',
						\'' . pSQL($product['name'] . ((isset($product['attributes']) and $product['attributes'] != NULL) ? ' - ' . $product['attributes'] : '')) . '\',
						' . (int) $product['cart_quantity'] . ',
						' . $quantityInStock . ',
						' . $product_price . ',
						' . (double) (($specificPrice and $specificPrice['reduction_type'] == 'percentage') ? $specificPrice['reduction'] * 100 : 0.0) . ',
						' . (double) (($specificPrice and $specificPrice['reduction_type'] == 'amount') ? !$specificPrice['id_currency'] ? Tools::convertPrice($specificPrice['reduction'], $order->id_currency) : $specificPrice['reduction'] : 0.0) . ',
						' . $group_reduction . ',
						' . $quantityDiscountValue . ',
						' . (empty($product['ean13']) ? 'NULL' : '\'' . pSQL($product['ean13']) . '\'') . ',
						' . (empty($product['upc']) ? 'NULL' : '\'' . pSQL($product['upc']) . '\'') . ',
						' . (empty($product['reference']) ? 'NULL' : '\'' . pSQL($product['reference']) . '\'') . ',
						' . (empty($product['supplier_reference']) ? 'NULL' : '\'' . pSQL($product['supplier_reference']) . '\'') . ',
						' . (double) ($product['id_product_attribute'] ? $product['weight_attribute'] : $product['weight']) . ',
						\'' . (empty($tax_rate) ? '' : pSQL($product['tax'])) . '\',
						' . (double) $tax_rate . ',
						' . (double) Tools::convertPrice(floatval($product['ecotax']), intval($order->id_currency)) . ',
						' . (double) $ecotaxTaxRate . ',
						' . (($specificPrice and $specificPrice['from_quantity'] > 1) ? 1 : 0) . ',
						\'' . pSQL($deadline) . '\',
						\'' . pSQL($download_hash) . '\'),';
                    $customizationQuantity = 0;
                    if (isset($customizedDatas[$product['id_product']][$product['id_product_attribute']])) {
                        $customizationText = '';
                        foreach ($customizedDatas[$product['id_product']][$product['id_product_attribute']] as $customization) {
                            if (isset($customization['datas'][_CUSTOMIZE_TEXTFIELD_])) {
                                foreach ($customization['datas'][_CUSTOMIZE_TEXTFIELD_] as $text) {
                                    $customizationText .= $text['name'] . ':' . ' ' . $text['value'] . '<br />';
                                }
                            }
                            if (isset($customization['datas'][_CUSTOMIZE_FILE_])) {
                                $customizationText .= count($customization['datas'][_CUSTOMIZE_FILE_]) . ' ' . Tools::displayError('image(s)') . '<br />';
                            }
                            $customizationText .= '---<br />';
                        }
                        $customizationText = rtrim($customizationText, '---<br />');
                        $customizationQuantity = (int) $product['customizationQuantityTotal'];
                        $productsList .= '<tr style="background-color: ' . ($key % 2 ? '#DDE2E6' : '#EBECEE') . ';">
							<td style="padding: 0.6em 0.4em;">' . (isset($product['reference']) && !empty($product['reference']) ? $product['reference'] : '&nbsp;') . '</td>
							<td style="padding: 0.6em 0.4em;"><strong>' . $product['name'] . (isset($product['attributes']) ? ' - ' . $product['attributes'] : '') . ' - ' . $this->l('Customized') . (!empty($customizationText) ? ' - ' . $customizationText : '') . '</strong></td>
							<td style="padding: 0.6em 0.4em; text-align: right;">' . Tools::displayPrice(Product::getTaxCalculationMethod() == PS_TAX_EXC ? Tools::ps_round($price, 2) : $price_wt, $currency, false) . '</td>
							<td style="padding: 0.6em 0.4em; text-align: center;">' . $customizationQuantity . '</td>
							<td style="padding: 0.6em 0.4em; text-align: right;">' . Tools::displayPrice($customizationQuantity * (Product::getTaxCalculationMethod() == PS_TAX_EXC ? Tools::ps_round($price, 2) : $price_wt), $currency, false) . '</td>
						</tr>';
                    }
                    if (!$customizationQuantity or (int) $product['cart_quantity'] > $customizationQuantity) {
                        $productsList .= '<tr style="background-color: ' . ($key % 2 ? '#DDE2E6' : '#EBECEE') . ';">
							<td style="padding: 0.6em 0.4em;">' . (isset($product['reference']) && !empty($product['reference']) ? $product['reference'] : '&nbsp;') . '</td>
							<td style="padding: 0.6em 0.4em;"><strong>' . $product['name'] . (isset($product['attributes']) ? ' - ' . $product['attributes'] : '') . '</strong></td>
							<td style="padding: 0.6em 0.4em; text-align: right;">' . Tools::displayPrice(Product::getTaxCalculationMethod() == PS_TAX_EXC ? Tools::ps_round($price, 2) : $price_wt, $currency, false) . '</td>
							<td style="padding: 0.6em 0.4em; text-align: center;">' . ((int) $product['cart_quantity'] - $customizationQuantity) . '</td>
							<td style="padding: 0.6em 0.4em; text-align: right;">' . Tools::displayPrice(((int) $product['cart_quantity'] - $customizationQuantity) * (Product::getTaxCalculationMethod() == PS_TAX_EXC ? Tools::ps_round($price, 2) : $price_wt), $currency, false) . '</td>
						</tr>';
                    }
                }
                // end foreach ($products)
                $query = rtrim($query, ',');
                $result = $db->Execute($query);
                /* Add carrier tax */
                $shippingCostTaxExcl = $cart->getOrderShippingCost((int) $order->id_carrier, false);
                $allTaxes = TaxRulesGroup::getTaxes((int) Carrier::getIdTaxRulesGroupByIdCarrier((int) $order->id_carrier), $id_country, $id_state, $id_county);
                $nTax = 0;
                foreach ($allTaxes as $tax) {
                    if (!isset($tax->id)) {
                        continue;
                    }
                    if (!isset($store_all_taxes[$tax->id])) {
                        $store_all_taxes[$tax->id] = array();
                    }
                    if (!isset($store_all_taxes[$tax->id]['amount'])) {
                        $store_all_taxes[$tax->id]['amount'] = 0;
                    }
                    $store_all_taxes[$tax->id]['name'] = $tax->name[(int) $order->id_lang];
                    $store_all_taxes[$tax->id]['rate'] = $tax->rate;
                    if (!$nTax++) {
                        $store_all_taxes[$tax->id]['amount'] += $shippingCostTaxExcl * (1 + $tax->rate * 0.01) - $shippingCostTaxExcl;
                    } else {
                        $store_all_taxes[$tax->id]['amount'] += $order->total_shipping - $order->total_shipping / (1 + $tax->rate * 0.01);
                    }
                }
                /* Store taxes */
                foreach ($store_all_taxes as $tax) {
                    Db::getInstance()->Execute('
					INSERT INTO `' . _DB_PREFIX_ . 'order_tax` (`id_order`, `tax_name`, `tax_rate`, `amount`)
					VALUES (' . (int) $order->id . ', \'' . pSQL($tax['name']) . '\', ' . (double) $tax['rate'] . ', ' . (double) $tax['amount'] . ')');
                }
                // Insert discounts from cart into order_discount table
                $discounts = $cart->getDiscounts();
                $discountsList = '';
                $total_discount_value = 0;
                $shrunk = false;
                foreach ($discounts as $discount) {
                    $objDiscount = new Discount((int) $discount['id_discount']);
                    $value = $objDiscount->getValue(count($discounts), $cart->getOrderTotal(true, Cart::ONLY_PRODUCTS), $order->total_shipping, $cart->id);
                    if ($objDiscount->id_discount_type == 2 and in_array($objDiscount->behavior_not_exhausted, array(1, 2))) {
                        $shrunk = true;
                    }
                    if ($shrunk and $total_discount_value + $value > $order->total_products_wt + $order->total_shipping + $order->total_wrapping) {
                        $amount_to_add = $order->total_products_wt + $order->total_shipping + $order->total_wrapping - $total_discount_value;
                        if ($objDiscount->id_discount_type == 2 and $objDiscount->behavior_not_exhausted == 2) {
                            $voucher = new Discount();
                            foreach ($objDiscount as $key => $discountValue) {
                                $voucher->{$key} = $discountValue;
                            }
                            $voucher->name = 'VSRK' . (int) $order->id_customer . 'O' . (int) $order->id;
                            $voucher->value = (double) $value - $amount_to_add;
                            $voucher->add();
                            $params['{voucher_amount}'] = Tools::displayPrice($voucher->value, $currency, false);
                            $params['{voucher_num}'] = $voucher->name;
                            $params['{firstname}'] = $customer->firstname;
                            $params['{lastname}'] = $customer->lastname;
                            $params['{id_order}'] = $order->id;
                            $params['{order_name}'] = sprintf("#%06d", (int) $order->id);
                            @Mail::Send((int) $order->id_lang, 'voucher', Mail::l('New voucher regarding your order #', (int) $order->id_lang) . sprintf("%06d", (int) $order->id), $params, $customer->email, $customer->firstname . ' ' . $customer->lastname);
                        }
                    } else {
                        $amount_to_add = $value;
                    }
                    $order->addDiscount($objDiscount->id, $objDiscount->name, $amount_to_add);
                    $total_discount_value += $amount_to_add;
                    if ($id_order_state != Configuration::get('PS_OS_ERROR') and $id_order_state != Configuration::get('PS_OS_CANCELED')) {
                        $objDiscount->quantity = $objDiscount->quantity - 1;
                    }
                    $objDiscount->update();
                    $discountsList .= '<tr style="background-color:#EBECEE;">
							<td colspan="4" style="padding: 0.6em 0.4em; text-align: right;">' . $this->l('Voucher code:') . ' ' . $objDiscount->name . '</td>
							<td style="padding: 0.6em 0.4em; text-align: right;">' . ($value != 0.0 ? '-' : '') . Tools::displayPrice($value, $currency, false) . '</td>
					</tr>';
                }
                // Specify order id for message
                $oldMessage = Message::getMessageByCartId((int) $cart->id);
                if ($oldMessage) {
                    $message = new Message((int) $oldMessage['id_message']);
                    $message->id_order = (int) $order->id;
                    $message->update();
                }
                // Hook new order
                $orderStatus = new OrderState((int) $id_order_state, (int) $order->id_lang);
                if (Validate::isLoadedObject($orderStatus)) {
                    Hook::newOrder($cart, $order, $customer, $currency, $orderStatus);
                    foreach ($cart->getProducts() as $product) {
                        if ($orderStatus->logable) {
                            ProductSale::addProductSale((int) $product['id_product'], (int) $product['cart_quantity']);
                        }
                    }
                }
                if (isset($outOfStock) && $outOfStock && Configuration::get('PS_STOCK_MANAGEMENT')) {
                    $history = new OrderHistory();
                    $history->id_order = (int) $order->id;
                    $history->changeIdOrderState(Configuration::get('PS_OS_OUTOFSTOCK'), (int) $order->id);
                    $history->addWithemail();
                }
                // Set order state in order history ONLY even if the "out of stock" status has not been yet reached
                // So you migth have two order states
                $new_history = new OrderHistory();
                $new_history->id_order = (int) $order->id;
                $new_history->changeIdOrderState((int) $id_order_state, (int) $order->id);
                $new_history->addWithemail(true, $extraVars);
                // Order is reloaded because the status just changed
                $order = new Order($order->id);
                // Send an e-mail to customer
                if ($id_order_state != Configuration::get('PS_OS_ERROR') and $id_order_state != Configuration::get('PS_OS_CANCELED') and $customer->id) {
                    $invoice = new Address((int) $order->id_address_invoice);
                    $delivery = new Address((int) $order->id_address_delivery);
                    $carrier = new Carrier((int) $order->id_carrier, $order->id_lang);
                    $delivery_state = $delivery->id_state ? new State((int) $delivery->id_state) : false;
                    $invoice_state = $invoice->id_state ? new State((int) $invoice->id_state) : false;
                    $data = array('{firstname}' => $customer->firstname, '{lastname}' => $customer->lastname, '{email}' => $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="color:#DB3484; font-weight:bold;">%s</span>', 'lastname' => '<span style="color:#DB3484; font-weight:bold;">%s</span>')), '{invoice_block_html}' => $this->_getFormatedAddress($invoice, "<br />", array('firstname' => '<span style="color:#DB3484; font-weight:bold;">%s</span>', 'lastname' => '<span style="color:#DB3484; 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}' => sprintf("#%06d", (int) $order->id), '{date}' => Tools::displayDate(date('Y-m-d H:i:s'), (int) $order->id_lang, 1), '{carrier}' => $carrier->name, '{payment}' => Tools::substr($order->payment, 0, 32), '{products}' => $productsList, '{discounts}' => $discountsList, '{total_paid}' => Tools::displayPrice($order->total_paid, $currency, false), '{total_products}' => Tools::displayPrice($order->total_paid - $order->total_shipping - $order->total_wrapping + $order->total_discounts, $currency, false), '{total_discounts}' => Tools::displayPrice($order->total_discounts, $currency, false), '{total_shipping}' => Tools::displayPrice($order->total_shipping, $currency, false), '{total_wrapping}' => Tools::displayPrice($order->total_wrapping, $currency, false));
                    if (is_array($extraVars)) {
                        $data = array_merge($data, $extraVars);
                    }
                    // Join PDF invoice
                    if ((int) Configuration::get('PS_INVOICE') and Validate::isLoadedObject($orderStatus) and $orderStatus->invoice and $order->invoice_number) {
                        $fileAttachment['content'] = PDF::invoice($order, 'S');
                        $fileAttachment['name'] = Configuration::get('PS_INVOICE_PREFIX', (int) $order->id_lang) . sprintf('%06d', $order->invoice_number) . '.pdf';
                        $fileAttachment['mime'] = 'application/pdf';
                    } else {
                        $fileAttachment = null;
                    }
                    if (Validate::isEmail($customer->email)) {
                        Mail::Send((int) $order->id_lang, 'order_conf', Mail::l('Order confirmation', (int) $order->id_lang), $data, $customer->email, $customer->firstname . ' ' . $customer->lastname, NULL, NULL, $fileAttachment);
                    }
                }
                $this->currentOrder = (int) $order->id;
                return true;
            } else {
                $errorMessage = Tools::displayError('Order creation failed');
                Logger::addLog($errorMessage, 4, '0000002', 'Cart', intval($order->id_cart));
                die($errorMessage);
            }
        } else {
            $errorMessage = Tools::displayError('Cart cannot be loaded or an order has already been placed using this cart');
            Logger::addLog($errorMessage, 4, '0000001', 'Cart', intval($cart->id));
            die($errorMessage);
        }
    }
Example #7
0
    /**
     * Get product price
     *
     * @param integer $id_product Product id
     * @param boolean $tax With taxes or not (optional)
     * @param integer $id_product_attribute Product attribute id (optional)
     * @param integer $decimals Number of decimals (optional)
     * @param integer $divisor Useful when paying many time without fees (optional)
     * @return float Product price
     */
    public static function getPriceStatic($id_product, $usetax = true, $id_product_attribute = NULL, $decimals = 6, $divisor = NULL, $only_reduc = false, $usereduc = true, $quantity = 1, $forceAssociatedTax = false, $id_customer = NULL, $id_cart = NULL, $id_address_delivery = NULL)
    {
        global $cookie, $cart;
        // Get id_customer if exists
        if (!$id_customer) {
            $id_customer = (Validate::isCookie($cookie) and isset($cookie->id_customer) and $cookie->id_customer) ? intval($cookie->id_customer) : null;
        }
        if (!is_object($cart)) {
            /*
             * When a user (e.g., guest, customer, Google...) is on PrestaShop, he has already its cart as the global (see /init.php)
             * When a non-user calls directly this method (e.g., payment module...) is on PrestaShop, he does not have already it BUT knows the cart ID
             */
            if (!$id_cart and !Validate::isCookie($cookie)) {
                die(Tools::displayError());
            }
            $cart = $id_cart ? new Cart(intval($id_cart)) : new Cart(intval($cookie->id_cart));
        }
        if (Validate::isLoadedObject($cart)) {
            $currency = new Currency(intval($cart->id_currency));
        } elseif (isset($cookie->id_currency) and intval($cookie->id_currency)) {
            $currency = new Currency(intval($cookie->id_currency));
        } else {
            $currency = new Currency(intval(Configuration::get('PS_CURRENCY_DEFAULT')));
        }
        if (!$id_address_delivery) {
            $id_address_delivery = $cart->id_address_delivery;
        }
        if (!Validate::isBool($usetax) or !Validate::isUnsignedId($id_product)) {
            die(Tools::displayError());
        }
        if (Tax::excludeTaxeOption()) {
            $usetax = false;
        }
        // Caching system
        $cacheId = $id_product . '-' . ($usetax ? '1' : '0') . '-' . $id_product_attribute . '-' . $decimals . '-' . $divisor . '-' . ($only_reduc ? '1' : '0') . '-' . ($usereduc ? '1' : '0') . '-' . $quantity . '-' . ($id_customer ? $id_customer : '0');
        if (isset(self::$_prices[$cacheId])) {
            return self::$_prices[$cacheId];
        }
        // Getting price
        $result = Db::getInstance()->getRow('
		SELECT p.`price`, p.`reduction_price`, p.`reduction_percent`, p.`reduction_from`, p.`reduction_to`, p.`id_tax`, t.`rate`, 
		' . ($id_product_attribute ? 'pa.`price`' : 'IFNULL((SELECT pa.price FROM `' . _DB_PREFIX_ . 'product_attribute` pa WHERE id_product = ' . intval($id_product) . ' AND default_on = 1), 0)') . ' AS attribute_price
		FROM `' . _DB_PREFIX_ . 'product` p
		' . ($id_product_attribute ? 'LEFT JOIN `' . _DB_PREFIX_ . 'product_attribute` pa ON pa.`id_product_attribute` = ' . intval($id_product_attribute) : '') . '
		LEFT JOIN `' . _DB_PREFIX_ . 'tax` AS t ON t.`id_tax` = p.`id_tax`
		WHERE p.`id_product` = ' . intval($id_product));
        $price = Tools::convertPrice(floatval($result['price']), $currency);
        // Exclude tax
        $tax = floatval(Tax::getApplicableTax(intval($result['id_tax']), floatval($result['rate']), $id_address_delivery ? intval($id_address_delivery) : NULL));
        if ($forceAssociatedTax) {
            $tax = floatval($result['rate']);
        }
        if (!$tax) {
            $usetax = false;
        }
        if ($usetax) {
            $price = $price * (1 + $tax / 100);
        }
        /* Keep this line */
        // $price = Tools::ps_round($price, ($only_reduc OR $usereduc) ? 2 : $decimals);
        // Attribute price
        $attribute_price = Tools::convertPrice(array_key_exists('attribute_price', $result) ? floatval($result['attribute_price']) : 0, $currency);
        $attribute_price = $usetax ? Tools::ps_round($attribute_price, 2) : $attribute_price / (1 + ($tax ? $tax : $result['rate']) / 100);
        $price += $attribute_price;
        $reduc = Tools::convertPrice($result['reduction_price'], $currency);
        if ($only_reduc or $usereduc) {
            $reduc = self::getReductionValue($reduc, $result['reduction_percent'], $result['reduction_from'], $result['reduction_to'], Tools::ps_round($price, 2), $usetax, floatval($result['rate']));
        }
        // Only reduction
        if ($only_reduc) {
            return $reduc;
        }
        // Reduction
        if ($usereduc) {
            if ($reduc) {
                $price = Tools::ps_round($price, 2);
            }
            $price -= $reduc;
        }
        if (intval($id_cart)) {
            $totalQuantity = intval(Db::getInstance()->getValue('
				SELECT SUM(`quantity`)
				FROM `' . _DB_PREFIX_ . 'cart_product`
				WHERE `id_product` = ' . intval($id_product) . ' AND `id_cart` = ' . intval($id_cart))) + intval($quantity);
        }
        if ($quantity > 1 and $qtyD = QuantityDiscount::getDiscountFromQuantity($id_product, $quantity)) {
            $discount_qty_price = QuantityDiscount::getValue($price, $qtyD->id_discount_type, $qtyD->value, $usetax, floatval($result['rate']), $currency);
            $price -= $discount_qty_price;
        }
        // Group reduction
        $price *= (100 - Group::getReduction((isset($id_customer) and $id_customer) ? $id_customer : 0)) / 100;
        $price = ($divisor and $divisor != NULL) ? $price / $divisor : $price;
        if ($quantity <= 1 or !$qtyD) {
            $price = Tools::ps_round($price, $decimals);
        }
        self::$_prices[$cacheId] = $price;
        return self::$_prices[$cacheId];
    }
Example #8
0
 public function getTemplateVarProduct()
 {
     $productSettings = $this->getProductPresentationSettings();
     $product = $this->objectPresenter->present($this->product);
     $product['id_product'] = (int) $this->product->id;
     $product['out_of_stock'] = (int) $this->product->out_of_stock;
     $product['new'] = (int) $this->product->new;
     $product['id_product_attribute'] = (int) Tools::getValue('id_product_attribute');
     $product['minimal_quantity'] = $this->getProductMinimalQuantity($product);
     $product['quantity_wanted'] = $this->getRequiredQuantity($product);
     $product_full = Product::getProductProperties($this->context->language->id, $product, $this->context);
     $product_full = $this->addProductCustomizationData($product_full);
     $product_full['show_quantities'] = (bool) (Configuration::get('PS_DISPLAY_QTIES') && Configuration::get('PS_STOCK_MANAGEMENT') && $this->product->quantity > 0 && $this->product->available_for_order && !Configuration::isCatalogMode());
     $product_full['quantity_label'] = $this->product->quantity > 1 ? $this->trans('Items', array(), 'Shop.Theme.Catalog') : $this->trans('Item', array(), 'Shop.Theme.Catalog');
     $product_full['quantity_discounts'] = $this->quantity_discounts;
     if ($product_full['unit_price_ratio'] > 0) {
         $unitPrice = $productSettings->include_taxes ? $product_full['price'] : $product_full['price_tax_exc'];
         $product_full['unit_price'] = $unitPrice / $product_full['unit_price_ratio'];
     }
     $group_reduction = GroupReduction::getValueForProduct($this->product->id, (int) Group::getCurrent()->id);
     if ($group_reduction === false) {
         $group_reduction = Group::getReduction((int) $this->context->cookie->id_customer) / 100;
     }
     $product_full['customer_group_discount'] = $group_reduction;
     $presenter = $this->getProductPresenter();
     return $presenter->present($productSettings, $product_full, $this->context->language);
 }
Example #9
0
     $scales[Configuration::get('AIMD_FIRST_DIMENSION_ID')] = Configuration::get('AIMD_FIRST_DIMENSION_SCALE');
 }
 if (Configuration::get('AIMD_SECOND_DIMENSION_ACTIVE') == 1) {
     $dimensions[] = Configuration::get('AIMD_SECOND_DIMENSION_ID');
     $scales[Configuration::get('AIMD_SECOND_DIMENSION_ID')] = Configuration::get('AIMD_SECOND_DIMENSION_SCALE');
 }
 if (Configuration::get('AIMD_THIRD_DIMENSION_ACTIVE') == 1) {
     $dimensions[] = Configuration::get('AIMD_THIRD_DIMENSION_ID');
     $scales[Configuration::get('AIMD_THIRD_DIMENSION_ID')] = Configuration::get('AIMD_THIRD_DIMENSION_SCALE');
 }
 //	Get the group reduction
 $groupReduction = 1;
 if (isset($cookie->id_customer)) {
     $productGroupReduction = GroupReduction::getValueForProduct($idProduct, $groupId);
     if (!$productGroupReduction) {
         $groupReduction -= floatval(Group::getReduction((int) $cookie->id_customer)) / 100;
     } else {
         $groupReduction -= floatval($productGroupReduction);
     }
 }
 //	Get the product price with attributes but the multidimensionnals attributes (including taxes)
 $more_tmp = array();
 $more_attributes_price = 0;
 $more_attributes = DB::getInstance()->ExecuteS('SELECT pac.id_attribute FROM ' . _DB_PREFIX_ . 'attribute_lang AS lang LEFT JOIN ' . _DB_PREFIX_ . 'product_attribute_combination AS pac ON lang.id_attribute = pac.id_attribute' . ' LEFT JOIN ' . _DB_PREFIX_ . 'attribute AS attribute ON lang.id_attribute = attribute.id_attribute LEFT JOIN ' . _DB_PREFIX_ . 'product_attribute AS pa ON pac.id_product_attribute = pa.id_product_attribute' . ' WHERE pa.id_product = ' . $idProduct . ' AND pa.id_product_attribute = ' . $idProductAttribute . ' AND lang.id_lang = ' . (int) $cookie->id_lang . ' AND attribute.id_attribute_group NOT IN (' . implode(', ', $dimensions) . ')');
 if (count($more_attributes)) {
     foreach ($more_attributes as $more_attribute) {
         $more_tmp[] = $more_attribute['id_attribute'];
     }
     $more_attributes_price = get_moreAttributesPrice($more_tmp, $idProduct);
 }
 $product_price = $base_price + $more_attributes_price * $groupReduction * $taxes;
 public function initContent()
 {
     if (!$this->ajax) {
         parent::initContent();
     }
     //  parent::initContent();
     $this->setTemplate(_PS_THEME_DIR_ . 'category.tpl');
     if (!$this->customer_access) {
         return;
     }
     if (isset($this->context->cookie->id_compare)) {
         $this->context->smarty->assign('compareProducts', CompareProduct::getCompareProducts((int) $this->context->cookie->id_compare));
     }
     $this->productSort();
     // Product sort must be called before assignProductList()
     $this->assignScenes();
     $this->assignSubcategories();
     $this->assignProductList();
     $products = isset($this->cat_products) && $this->cat_products ? $this->cat_products : null;
     $combinations = array();
     if ($products !== NULL) {
         foreach ($products as &$pro) {
             $product_obj = new Product($pro['id_product'], $this->context->language->id);
             $pro['groups'] = $product_obj->getProductCombinationsGroups($pro['id_product']);
             $combinations[$pro['id_product']] = $product_obj->getProductAttributeCombinations($pro['id_product']);
             $id_group = (int) Group::getCurrent()->id;
             $group_reduction = GroupReduction::getValueForProduct($pro['id_product'], $id_group);
             if ($group_reduction === false) {
                 $group_reduction = Group::getReduction((int) $this->context->cookie->id_customer) / 100;
             }
             $pro['group_reduction'] = $group_reduction;
             $address = new Address($this->context->cart->{Configuration::get('PS_TAX_ADDRESS_TYPE')});
             $pro['no_tax'] = Tax::excludeTaxeOption() || !$product_obj->getTaxesRate($address);
             $pro['customer_group_without_tax'] = Group::getPriceDisplayMethod($this->context->customer->id_default_group);
             $tax = (double) $product_obj->getTaxesRate(new Address((int) $this->context->cart->{Configuration::get('PS_TAX_ADDRESS_TYPE')}));
             $pro['tax_rate'] = $tax;
             $pro['unit_price_ratio'] = $product_obj->unit_price_ratio;
             $ecotax_rate = (double) Tax::getProductEcotaxRate($this->context->cart->{Configuration::get('PS_TAX_ADDRESS_TYPE')});
             $pro['ecotaxTax_rate'] = $ecotax_rate;
         }
     }
     $this->context->smarty->assign(array('category' => $this->category, 'description_short' => Tools::truncateString($this->category->description, 350), 'products' => $products, 'id_category' => (int) $this->category->id, 'id_category_parent' => (int) $this->category->id_parent, 'return_category_name' => Tools::safeOutput($this->category->name), 'path' => Tools::getPath($this->category->id), 'add_prod_display' => Configuration::get('PS_ATTRIBUTE_CATEGORY_DISPLAY'), 'categorySize' => Image::getSize(ImageType::getFormatedName('category')), 'mediumSize' => Image::getSize(ImageType::getFormatedName('medium')), 'thumbSceneSize' => Image::getSize(ImageType::getFormatedName('m_scene')), 'homeSize' => Image::getSize(ImageType::getFormatedName('home')), 'allow_oosp' => (int) Configuration::get('PS_ORDER_OUT_OF_STOCK'), 'comparator_max_item' => (int) Configuration::get('PS_COMPARATOR_MAX_ITEM'), 'suppliers' => Supplier::getSuppliers(), 'body_classes' => array($this->php_self . '-' . $this->category->id, $this->php_self . '-' . $this->category->link_rewrite), 'combinations' => $combinations));
 }
Example #11
0
    /**
     * Get product price
     *
     * @param integer $id_product Product id
     * @param boolean $tax With taxes or not (optional)
     * @param integer $id_product_attribute Product attribute id (optional)
     * @param integer $decimals Number of decimals (optional)
     * @param integer $divisor Useful when paying many time without fees (optional)
     * @return float Product price
     */
    public static function getPriceStatic($id_product, $usetax = true, $id_product_attribute = NULL, $decimals = 6, $divisor = NULL, $only_reduc = false, $usereduc = true, $quantity = 1, $forceAssociatedTax = false, $id_customer = NULL, $id_cart = NULL, $id_address_delivery = NULL)
    {
        global $cookie;
        // Get id_customer if exists
        if (!$id_customer) {
            $id_customer = (isset($cookie) and get_class($cookie) == 'Cookie' and isset($cookie->id_customer) and $cookie->id_customer) ? intval($cookie->id_customer) : null;
        }
        if (!$id_cart) {
            $id_cart = (isset($cookie) and get_class($cookie) == 'Cookie' and isset($cookie->id_cart) and $cookie->id_cart) ? intval($cookie->id_cart) : null;
        }
        if (!$id_address_delivery) {
            $id_address_delivery = (isset($cookie) and get_class($cookie) == 'Cookie' and isset($cookie->id_address_delivery) and $cookie->id_address_delivery) ? intval($cookie->id_address_delivery) : null;
        }
        if (!Validate::isBool($usetax) or !Validate::isUnsignedId($id_product)) {
            die(Tools::displayError());
        }
        // Caching system
        $cacheId = $id_product . '-' . ($usetax ? '1' : '0') . '-' . $id_product_attribute . '-' . $decimals . '-' . $divisor . '-' . ($only_reduc ? '1' : '0') . '-' . ($usereduc ? '1' : '0') . '-' . $quantity;
        if (isset(self::$_prices[$cacheId])) {
            return self::$_prices[$cacheId];
        }
        // Getting price
        $result = Db::getInstance()->getRow('
		SELECT p.`price`, p.`reduction_price`, p.`reduction_percent`, p.`reduction_from`, p.`reduction_to`, p.`id_tax`, t.`rate`, 
		' . ($id_product_attribute ? 'pa.`price`' : 'IFNULL((SELECT pa.price FROM `' . _DB_PREFIX_ . 'product_attribute` pa WHERE id_product = ' . intval($id_product) . ' AND default_on = 1), 0)') . ' AS attribute_price
		FROM `' . _DB_PREFIX_ . 'product` p
		' . ($id_product_attribute ? 'LEFT JOIN `' . _DB_PREFIX_ . 'product_attribute` pa ON pa.`id_product_attribute` = ' . intval($id_product_attribute) : '') . '
		LEFT JOIN `' . _DB_PREFIX_ . 'tax` AS t ON t.`id_tax` = p.`id_tax`
		WHERE p.`id_product` = ' . intval($id_product));
        $price = Tools::convertPrice(floatval($result['price']));
        // Exclude tax
        $tax = floatval(Tax::getApplicableTax(intval($result['id_tax']), floatval($result['rate']), $id_address_delivery ? intval($id_address_delivery) : NULL));
        if ($forceAssociatedTax) {
            $tax = floatval($result['rate']);
        }
        if (Tax::excludeTaxeOption() or !$tax) {
            $usetax = false;
        }
        if ($usetax) {
            $price = $price * (1 + $tax / 100);
        }
        // Attribute price
        $attribute_price = Tools::convertPrice(array_key_exists('attribute_price', $result) ? floatval($result['attribute_price']) : 0);
        $attribute_price = $usetax ? Tools::ps_round($attribute_price, 2) : $attribute_price / (1 + ($tax ? $tax : $result['rate']) / 100);
        $price += $attribute_price;
        if ($only_reduc or $usereduc) {
            $reduc = self::getReductionValue($result['reduction_price'], $result['reduction_percent'], $result['reduction_from'], $result['reduction_to'], $price, $usetax, floatval($result['rate']));
        }
        // Only reduction
        if ($only_reduc) {
            return $reduc;
        }
        // Reduction
        if ($usereduc) {
            $price -= $reduc;
        }
        // Quantity discount
        if (intval($id_cart)) {
            $totalQuantity = intval(Db::getInstance()->getValue('
				SELECT SUM(`quantity`)
				FROM `' . _DB_PREFIX_ . 'cart_product`
				WHERE `id_product` = ' . intval($id_product) . ' AND `id_cart` = ' . intval($cookie->id_cart))) + intval($quantity);
        }
        if ($quantity > 1 and $qtyD = QuantityDiscount::getDiscountFromQuantity($id_product, $quantity)) {
            $discount_qty_price = QuantityDiscount::getValue($price, $qtyD->id_discount_type, $qtyD->value);
            $price -= $discount_qty_price;
        }
        // Group reduction
        if ($id_customer) {
            $price *= (100 - Group::getReduction($id_customer)) / 100;
        }
        $price = ($divisor and $divisor != NULL) ? $price / $divisor : $price;
        if ($quantity <= 1 or !$qtyD) {
            $price = Tools::ps_round($price, $decimals);
        }
        self::$_prices[$cacheId] = $price;
        return self::$_prices[$cacheId];
    }
    /**
     * Get product price
     *
     * @param integer $id_product Product id
     * @param boolean $tax With taxes or not (optional)
     * @param integer $id_product_attribute Product attribute id (optional)
     * @param integer $decimals Number of decimals (optional)
     * @param integer $divisor Util when paying many time without fees (optional)
     * @return float Product price
     */
    public static function getPriceStatic($id_product, $usetax = true, $id_product_attribute = NULL, $decimals = 6, $divisor = NULL, $only_reduc = false, $usereduc = true, $quantity = 1, $forceAssociatedTax = false)
    {
        global $cookie;
        // Get id_customer if exists
        $id_customer = (isset($cookie) and get_class($cookie) == 'Cookie' and isset($cookie->id_customer) and $cookie->id_customer) ? intval($cookie->id_customer) : null;
        if (!Validate::isBool($usetax) or !Validate::isUnsignedId($id_product)) {
            die(Tools::displayError());
        }
        // Caching system
        $cacheId = $id_product . '-' . ($usetax ? '1' : '0') . '-' . $id_product_attribute . '-' . $decimals . '-' . $divisor . '-' . ($only_reduc ? '1' : '0') . '-' . ($usereduc ? '1' : '0') . '-' . $quantity;
        if (isset(self::$_prices[$cacheId])) {
            return self::$_prices[$cacheId];
        }
        // Getting price
        $result = Db::getInstance()->getRow('
		SELECT p.`price`, p.`reduction_price`, p.`reduction_percent`, p.`reduction_from`, p.`reduction_to`, p.`id_tax`, t.`rate`, 
		' . ($id_product_attribute ? 'pa.`price`' : 'IFNULL((SELECT pa.price FROM `' . _DB_PREFIX_ . 'product_attribute` pa WHERE id_product = ' . intval($id_product) . ' AND default_on = 1), 0)') . ' AS attribute_price
		FROM `' . _DB_PREFIX_ . 'product` p
		' . ($id_product_attribute ? 'LEFT JOIN `' . _DB_PREFIX_ . 'product_attribute` pa ON pa.`id_product_attribute` = ' . intval($id_product_attribute) : '') . '
		LEFT JOIN `' . _DB_PREFIX_ . 'tax` AS t ON t.`id_tax` = p.`id_tax`
		WHERE p.`id_product` = ' . intval($id_product));
        $price = $result['price'];
        // Exclude tax
        $tax = floatval(Tax::getApplicableTax(intval($result['id_tax']), floatval($result['rate'])));
        if ($forceAssociatedTax) {
            $tax = floatval($result['rate']);
        }
        if (Tax::excludeTaxeOption() or !$tax) {
            $usetax = false;
        }
        if ($usetax) {
            $price *= 1 + $tax / 100;
        }
        // Attribute price
        $attribute_price = $usetax ? $result['attribute_price'] : $result['attribute_price'] / (1 + ($tax ? $tax : $result['rate']) / 100);
        if (isset($result['attribute_price'])) {
            $price += $attribute_price;
        }
        $reduc = self::getReductionValue($result['reduction_price'], $result['reduction_percent'], $result['reduction_from'], $result['reduction_to'], $price, $usetax, floatval($result['rate']));
        // Only reduction
        if ($only_reduc) {
            return $reduc;
        }
        // Reduction
        if ($usereduc) {
            $price -= $reduc;
        }
        // Quantity discount
        if ($quantity > 1 and $qtyD = QuantityDiscount::getDiscountFromQuantity($id_product, $quantity)) {
            $price -= QuantityDiscount::getValue($price, $qtyD->id_discount_type, $qtyD->value);
        }
        // Group reduction
        if ($id_customer) {
            $price *= (100 - Group::getReduction($id_customer)) / 100;
        }
        self::$_prices[$cacheId] = ($divisor and $divisor != 'NULL') ? number_format($price / $divisor, $decimals, '.', '') : number_format($price, $decimals, '.', '');
        return self::$_prices[$cacheId];
    }
    /**
     * Validate an order in database
     * Function called from a payment module
     *
     * @param integer $id_cart Value
     * @param integer $id_order_state Value
     * @param float $amountPaid Amount really paid by customer (in the default currency)
     * @param string $paymentMethod Payment method (eg. 'Credit card')
     * @param string $message Message to attach to order
     */
    public function validateOrder($id_cart, $id_order_state, $amountPaid, $paymentMethod = 'Unknown', $message = NULL, $extraVars = array(), $currency_special = NULL, $dont_touch_amount = false, $secure_key = false)
    {
        global $cart, $link, $cookie;
        $id_payment_state = _PS_PS_NOT_PAID_;
        $cart = new Cart((int) $id_cart);
        // Does order already exists ?
        if (Validate::isLoadedObject($cart) and $cart->OrderExists() == false) {
            if ($secure_key !== false and $secure_key != $cart->secure_key) {
                die(Tools::displayError());
            }
            // Copying data from cart
            $order = new Order();
            $order->id_carrier = (int) $cart->id_carrier;
            $order->id_customer = (int) $cart->id_customer;
            $order->id_address_invoice = (int) $cart->id_address_invoice;
            $order->id_address_delivery = (int) $cart->id_address_delivery;
            $vat_address = new Address((int) $order->id_address_delivery);
            $order->id_currency = $currency_special ? (int) $currency_special : (int) $cart->id_currency;
            $order->id_lang = (int) $cart->id_lang;
            $order->id_cart = (int) $cart->id;
            $customer = new Customer((int) $order->id_customer);
            $order->secure_key = $secure_key ? pSQL($secure_key) : pSQL($customer->secure_key);
            $order->payment = $paymentMethod;
            if (isset($this->name)) {
                $order->module = $this->name;
            }
            $order->recyclable = $cart->recyclable;
            $order->gift = (int) $cart->gift;
            $order->gift_message = $cart->gift_message;
            $currency = new Currency($order->id_currency);
            $order->conversion_rate = $currency->conversion_rate;
            $amountPaid = !$dont_touch_amount ? Tools::ps_round((double) $amountPaid, 2) : $amountPaid;
            $order->total_paid_real = $amountPaid;
            $order->total_products = (double) $cart->getOrderTotal(false, Cart::ONLY_PRODUCTS);
            $order->total_products_wt = (double) $cart->getOrderTotal(true, Cart::ONLY_PRODUCTS);
            $order->total_customization = $cart->getCartCustomizationCost();
            $order->total_donation = round($cookie->donation_amount);
            unset($cookie->donation_amount);
            if (strpos($order->payment, 'COD') === false) {
                $order->total_discounts = (double) abs($cart->getOrderTotal(true, Cart::ONLY_DISCOUNTS, true));
                $order->total_paid = (double) Tools::ps_round((double) $cart->getOrderTotal(true, Cart::BOTH, true));
            } else {
                $order->total_discounts = (double) abs($cart->getOrderTotal(true, Cart::ONLY_DISCOUNTS, false));
                $order->total_paid = (double) Tools::ps_round((double) $cart->getOrderTotal(true, Cart::BOTH, false));
                $order->total_cod = COD_CHARGE;
            }
            $order->total_shipping = (double) $cart->getOrderShippingCost();
            $order->carrier_tax_rate = (double) Tax::getCarrierTaxRate($cart->id_carrier, (int) $cart->{Configuration::get('PS_TAX_ADDRESS_TYPE')});
            $order->total_wrapping = (double) abs($cart->getOrderTotal(true, Cart::ONLY_WRAPPING));
            $order->invoice_date = '0000-00-00 00:00:00';
            $order->delivery_date = '0000-00-00 00:00:00';
            $shippingdate = $cart->getExpectedShippingDate();
            $order->expected_shipping_date = pSQL($shippingdate->format('Y-m-d H:i:s'));
            $order->actual_expected_shipping_date = pSQL($shippingdate->format('Y-m-d H:i:s'));
            // 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 (number_format(round($order->total_paid)) != number_format(round($order->total_paid_real))) {
                $id_order_state = _PS_OS_ERROR_;
                $id_payment_state = _PS_PS_NOT_PAID_;
            } else {
                if (strpos($order->payment, 'COD') === false) {
                    $id_payment_state = _PS_PS_PAID_;
                }
            }
            //update payment status
            // Creating order
            if ($cart->OrderExists() == false) {
                $cart_value = $cart->getOrderTotal();
                if ($cart_value >= 1000) {
                    //if(!$cart->containsProduct(FREE_GIFT_ID, NULL, NULL))
                    //$cart->updateQty(1, FREE_GIFT_ID, NULL, false, 'up', TRUE);
                }
                $result = $order->add();
            } else {
                $errorMessage = Tools::displayError('An order has already been placed using this cart.');
                Logger::addLog($errorMessage, 4, '0000001', 'Cart', intval($order->id_cart));
                die($errorMessage);
            }
            // Next !
            if ($result and isset($order->id)) {
                if (!$secure_key) {
                    $message .= $this->l('Warning : the secure key is empty, check your payment account before validation');
                }
                // Optional message to attach to this order
                if (isset($message) and !empty($message)) {
                    $msg = new Message();
                    $message = strip_tags($message, '<br>');
                    if (Validate::isCleanHtml($message)) {
                        $msg->message = $message;
                        $msg->id_order = intval($order->id);
                        $msg->private = 1;
                        $msg->add();
                    }
                }
                // Insert products from cart into order_detail table
                $products = $cart->getProducts();
                $productsList = '';
                $db = Db::getInstance();
                $query = 'INSERT INTO `' . _DB_PREFIX_ . 'order_detail`
					(`id_order`, `product_id`, `product_attribute_id`, `product_name`, `product_quantity`, `product_quantity_in_stock`, `product_price`, `reduction_percent`, `reduction_amount`, `group_reduction`, `product_quantity_discount`, `product_ean13`, `product_upc`, `product_reference`, `product_supplier_reference`, `product_weight`, `tax_name`, `tax_rate`, `ecotax`, `ecotax_tax_rate`, `discount_quantity_applied`, `download_deadline`, `download_hash`, `customization`)
				VALUES ';
                $customizedDatas = Product::getAllCustomizedDatas((int) $order->id_cart);
                Product::addCustomizationPrice($products, $customizedDatas);
                $outOfStock = false;
                foreach ($products as $key => $product) {
                    $productQuantity = (int) Product::getQuantity((int) $product['id_product'], $product['id_product_attribute'] ? (int) $product['id_product_attribute'] : NULL);
                    $quantityInStock = $productQuantity - (int) $product['cart_quantity'] < 0 ? $productQuantity : (int) $product['cart_quantity'];
                    if ($id_order_state != _PS_OS_CANCELED_ and $id_order_state != _PS_OS_ERROR_) {
                        if (Product::updateQuantity($product, (int) $order->id)) {
                            $product['stock_quantity'] -= $product['cart_quantity'];
                        }
                        if ($product['stock_quantity'] < 0 && Configuration::get('PS_STOCK_MANAGEMENT')) {
                            $outOfStock = true;
                        }
                        if ($product['stock_quantity'] < 1) {
                            SolrSearch::updateProduct((int) $product['id_product']);
                        }
                        Product::updateDefaultAttribute($product['id_product']);
                    }
                    $price = Product::getPriceStatic((int) $product['id_product'], false, $product['id_product_attribute'] ? (int) $product['id_product_attribute'] : NULL, 6, NULL, false, true, $product['cart_quantity'], 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, $product['cart_quantity'], false, (int) $order->id_customer, (int) $order->id_cart, (int) $order->{Configuration::get('PS_TAX_ADDRESS_TYPE')});
                    // Add some informations for virtual products
                    $deadline = '0000-00-00 00:00:00';
                    $download_hash = NULL;
                    if ($id_product_download = ProductDownload::getIdFromIdProduct((int) $product['id_product'])) {
                        $productDownload = new ProductDownload((int) $id_product_download);
                        $deadline = $productDownload->getDeadLine();
                        $download_hash = $productDownload->getHash();
                    }
                    // Exclude VAT
                    if (Tax::excludeTaxeOption()) {
                        $product['tax'] = 0;
                        $product['rate'] = 0;
                        $tax_rate = 0;
                    } else {
                        $tax_rate = Tax::getProductTaxRate((int) $product['id_product'], $cart->{Configuration::get('PS_TAX_ADDRESS_TYPE')});
                    }
                    $ecotaxTaxRate = 0;
                    if (!empty($product['ecotax'])) {
                        $ecotaxTaxRate = Tax::getProductEcotaxRate($order->{Configuration::get('PS_TAX_ADDRESS_TYPE')});
                    }
                    $quantityDiscount = SpecificPrice::getQuantityDiscount((int) $product['id_product'], Shop::getCurrentShop(), (int) $cart->id_currency, (int) $vat_address->id_country, (int) $customer->id_default_group, (int) $product['cart_quantity']);
                    $unitPrice = Product::getPriceStatic((int) $product['id_product'], true, $product['id_product_attribute'] ? intval($product['id_product_attribute']) : NULL, 2, NULL, false, true, 1, false, (int) $order->id_customer, NULL, (int) $order->{Configuration::get('PS_TAX_ADDRESS_TYPE')});
                    $quantityDiscountValue = $quantityDiscount ? (Product::getTaxCalculationMethod((int) $order->id_customer) == PS_TAX_EXC ? Tools::ps_round($unitPrice, 2) : $unitPrice) - $quantityDiscount['price'] * (1 + $tax_rate / 100) : 0.0;
                    $specificPrice = 0;
                    $query .= '(' . (int) $order->id . ',
						' . (int) $product['id_product'] . ',
						' . (isset($product['id_product_attribute']) ? (int) $product['id_product_attribute'] : 'NULL') . ',
						\'' . pSQL($product['name'] . ((isset($product['attributes']) and $product['attributes'] != NULL) ? ' - ' . $product['attributes'] : '')) . '\',
						' . (int) $product['cart_quantity'] . ',
						' . $quantityInStock . ',
						' . (double) Product::getPriceStatic((int) $product['id_product'], false, $product['id_product_attribute'] ? (int) $product['id_product_attribute'] : NULL, Product::getTaxCalculationMethod((int) $order->id_customer) == PS_TAX_EXC ? 2 : 6, NULL, false, false, $product['cart_quantity'], false, (int) $order->id_customer, (int) $order->id_cart, (int) $order->{Configuration::get('PS_TAX_ADDRESS_TYPE')}, $specificPrice, FALSE) . ',
						' . (double) (($specificPrice and $specificPrice['reduction_type'] == 'percentage') ? $specificPrice['reduction'] * 100 : 0.0) . ',
						' . (double) (($specificPrice and $specificPrice['reduction_type'] == 'amount') ? !$specificPrice['id_currency'] ? Tools::convertPrice($specificPrice['reduction'], $order->id_currency) : $specificPrice['reduction'] : 0.0) . ',
						' . (double) Group::getReduction((int) $order->id_customer) . ',
						' . $quantityDiscountValue . ',
						' . (empty($product['ean13']) ? 'NULL' : '\'' . pSQL($product['ean13']) . '\'') . ',
						' . (empty($product['upc']) ? 'NULL' : '\'' . pSQL($product['upc']) . '\'') . ',
						' . (empty($product['reference']) ? 'NULL' : '\'' . pSQL($product['reference']) . '\'') . ',
						' . (empty($product['supplier_reference']) ? 'NULL' : '\'' . pSQL($product['supplier_reference']) . '\'') . ',
						' . (double) ($product['id_product_attribute'] ? $product['weight_attribute'] : $product['weight']) . ',
						\'' . (empty($tax_rate) ? '' : pSQL($product['tax'])) . '\',
						' . (double) $tax_rate . ',
						' . (double) Tools::convertPrice(floatval($product['ecotax']), intval($order->id_currency)) . ',
						' . (double) $ecotaxTaxRate . ',
						' . (($specificPrice and $specificPrice['from_quantity'] > 1) ? 1 : 0) . ',
						\'' . pSQL($deadline) . '\',
						\'' . pSQL($download_hash) . '\', ' . $cart->getProductCustomizationCost($product['id_product']) . '),';
                    $customizationQuantity = 0;
                    if (isset($customizedDatas[$product['id_product']][$product['id_product_attribute']])) {
                        $customizationText = '';
                        foreach ($customizedDatas[$product['id_product']][$product['id_product_attribute']] as $customization) {
                            if (isset($customization['datas'][_CUSTOMIZE_TEXTFIELD_])) {
                                foreach ($customization['datas'][_CUSTOMIZE_TEXTFIELD_] as $text) {
                                    if ($text['index'] == 8) {
                                        $customizationText .= 'Saree with unstitched blouse and fall/pico work.' . '<br />';
                                    } else {
                                        if ($text['index'] == 1) {
                                            $customizationText .= 'Pre-stitched saree with unstitched blouse and fall/pico work.' . '<br />';
                                        } else {
                                            if ($text['index'] == 2) {
                                                $customizationText .= 'Stitched to measure blouse.' . '<br />';
                                            } else {
                                                if ($text['index'] == 3) {
                                                    $customizationText .= 'Stitched to measure in-skirt.' . '<br />';
                                                } else {
                                                    if ($text['index'] == 4) {
                                                        $customizationText .= 'Stitched to measure kurta.' . '<br />';
                                                    } else {
                                                        if ($text['index'] == 5) {
                                                            $customizationText .= 'Stitched to measure salwar.' . '<br />';
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                            if (isset($customization['datas'][_CUSTOMIZE_FILE_])) {
                                $customizationText .= sizeof($customization['datas'][_CUSTOMIZE_FILE_]) . ' ' . Tools::displayError('image(s)') . '<br />';
                            }
                            $customizationText .= '---<br />';
                        }
                        $customizationText = rtrim($customizationText, '---<br />');
                        $customizationQuantity = (int) $product['customizationQuantityTotal'];
                        $productsList .= '<tr style="background-color: ' . ($key % 2 ? '#DDE2E6' : '#EBECEE') . ';">
							<td style="padding: 0.6em 0.4em;">' . $product['reference'] . '</td>
							<td style="padding: 0.6em 0.4em;"><strong>' . $product['name'] . (isset($product['attributes_small']) ? ' ' . $product['attributes_small'] : '') . ' - ' . $this->l('Customized') . (!empty($customizationText) ? ' - ' . $customizationText : '') . '</strong></td>
							<td style="padding: 0.6em 0.4em; text-align: right;">' . Tools::displayPrice(round(Product::getTaxCalculationMethod() == PS_TAX_EXC ? $price : $price_wt), $currency, false) . '</td>
							<td style="padding: 0.6em 0.4em; text-align: center;">' . $customizationQuantity . '</td>
							<td style="padding: 0.6em 0.4em; text-align: right;">' . Tools::displayPrice($customizationQuantity * round(Product::getTaxCalculationMethod() == PS_TAX_EXC ? $price : $price_wt), $currency, false) . '</td>
						</tr>';
                    }
                    if (!$customizationQuantity or (int) $product['cart_quantity'] > $customizationQuantity) {
                        $productsList .= '<tr style="background-color: ' . ($key % 2 ? '#DDE2E6' : '#EBECEE') . ';">
							<td style="padding: 0.6em 0.4em;">' . $product['reference'] . '</td>
							<td style="padding: 0.6em 0.4em;"><strong>' . $product['name'] . (isset($product['attributes_small']) ? ' ' . $product['attributes_small'] : '') . '</strong></td>
							<td style="padding: 0.6em 0.4em; text-align: right;">' . Tools::displayPrice(round(Product::getTaxCalculationMethod() == PS_TAX_EXC ? $price : $price_wt), $currency, false) . '</td>
							<td style="padding: 0.6em 0.4em; text-align: center;">' . ((int) $product['cart_quantity'] - $customizationQuantity) . '</td>
							<td style="padding: 0.6em 0.4em; text-align: right;">' . Tools::displayPrice(((int) $product['cart_quantity'] - $customizationQuantity) * round(Product::getTaxCalculationMethod() == PS_TAX_EXC ? $price : $price_wt), $currency, false) . '</td>
						</tr>';
                    }
                    //if giftcard, create voucher and send the mails now.
                    $categories = Product::getProductCategories($product['id_product']);
                    if (in_array(CAT_GIFTCARD, $categories)) {
                        $friendsName = '';
                        $friendsEmail = '';
                        $giftMessage = '';
                        foreach ($customizedDatas[$product['id_product']][$product['id_product_attribute']] as $customization) {
                            if (isset($customization['datas'][_CUSTOMIZE_TEXTFIELD_])) {
                                foreach ($customization['datas'][_CUSTOMIZE_TEXTFIELD_] as $text) {
                                    if ($text['index'] == 21) {
                                        $friendsName = $text['value'];
                                    } else {
                                        if ($text['index'] == 22) {
                                            $friendsEmail = $text['value'];
                                        } else {
                                            if ($text['index'] == 23) {
                                                $giftMessage = $text['value'];
                                            } else {
                                                if ($text['index'] == 25) {
                                                    $couponCode = $text['value'];
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                        //$couponCode = "GC" . Tools::rand_string(8);
                        // create discount
                        $languages = Language::getLanguages($order);
                        $voucher = new Discount();
                        $voucher->id_discount_type = 2;
                        foreach ($languages as $language) {
                            $voucher->description[$language['id_lang']] = $product['name'];
                        }
                        $voucher->value = (double) $unitPrice;
                        $voucher->name = $couponCode;
                        $voucher->id_currency = 2;
                        //USD
                        $voucher->quantity = 1;
                        $voucher->quantity_per_user = 1;
                        $voucher->cumulable = 1;
                        $voucher->cumulable_reduction = 1;
                        $voucher->minimal = 0;
                        $voucher->active = 1;
                        $voucher->cart_display = 0;
                        $now = time();
                        $voucher->date_from = date('Y-m-d H:i:s', $now);
                        $voucher->date_to = date('Y-m-d H:i:s', $now + 3600 * 24 * 365);
                        /* 365 days */
                        $voucher->add();
                        $productObj = new Product($product['id_product'], true, 1);
                        $idImage = $productObj->getCoverWs();
                        if ($idImage) {
                            $idImage = $productObj->id . '-' . $idImage;
                        } else {
                            $idImage = Language::getIsoById(1) . '-default';
                        }
                        $params = array();
                        $params['{voucher_code}'] = $voucher->name;
                        $params['{freinds_name}'] = $friendsName;
                        $params['{gift_message}'] = $giftMessage;
                        $params['{product_name}'] = $product['name'];
                        $params['{voucher_value}'] = $voucher->value;
                        $params['{image_url}'] = _PS_BASE_URL_ . _PS_IMG_ . 'banners/' . $productObj->location;
                        $params['{sender_name}'] = $customer->firstname . ' ' . $customer->lastname;
                        $subject = $friendsName . ', You Have Received A $' . $voucher->value . ' IndusDiva Gift Card';
                        @Mail::Send(1, 'gift_card', $subject, $params, $friendsEmail, $friendsName, '*****@*****.**', 'Indusdiva.com', NULL, NULL, _PS_MAIL_DIR_, true);
                        @Mail::Send(1, 'gift_card', $subject, $params, $customer->email, $customer->firstname . ' ' . $customer->lastname, '*****@*****.**', 'Indusdiva.com', NULL, NULL, _PS_MAIL_DIR_, true);
                    }
                }
                // end foreach ($products)
                $query = rtrim($query, ',');
                $result = $db->Execute($query);
                // Insert discounts from cart into order_discount table
                $discounts = $cart->getDiscounts();
                $discountsList = '';
                $total_discount_value = 0;
                $shrunk = false;
                foreach ($discounts as $discount) {
                    $objDiscount = new Discount((int) $discount['id_discount'], $order->id_lang);
                    $value = $objDiscount->getValue(sizeof($discounts), $cart->getOrderTotal(true, Cart::ONLY_PRODUCTS), $order->total_shipping, $cart->id);
                    if ($objDiscount->id_discount_type == 2 || $objDiscount->id_discount_type == 4 and in_array($objDiscount->behavior_not_exhausted, array(1, 2))) {
                        $shrunk = true;
                    }
                    if ($shrunk and $total_discount_value + $value > $order->total_products + $order->total_shipping + $order->total_wrapping) {
                        $amount_to_add = $order->total_products + $order->total_shipping + $order->total_wrapping - $total_discount_value;
                        if ($objDiscount->id_discount_type == 2 || $objDiscount->id_discount_type == 4 and $objDiscount->behavior_not_exhausted == 2) {
                            $voucher = new Discount();
                            foreach ($objDiscount as $key => $discountValue) {
                                $voucher->{$key} = $discountValue;
                            }
                            $voucher->name = 'VSRK' . (int) $order->id_customer . 'O' . (int) $order->id;
                            $voucher->value = (double) $value - $amount_to_add;
                            $voucher->add();
                            $params['{voucher_amount}'] = Tools::displayPrice($voucher->value, $currency, false);
                            $params['{voucher_num}'] = $voucher->name;
                            @Mail::Send((int) $order->id_lang, 'voucher', Mail::l('New voucher regarding your order #') . $order->id, $params, $customer->email, $customer->firstname . ' ' . $customer->lastname);
                        }
                    } else {
                        $amount_to_add = $value;
                    }
                    $order->addDiscount($objDiscount->id, $objDiscount->name, $amount_to_add);
                    $total_discount_value += $amount_to_add;
                    if ($id_order_state != _PS_OS_ERROR_ and $id_order_state != _PS_OS_CANCELED_) {
                        $objDiscount->quantity = $objDiscount->quantity - 1;
                    }
                    $objDiscount->update();
                    $discountsList .= '<tr style="background-color:#EBECEE;">
							<td colspan="4" style="padding: 0.6em 0.4em; text-align: right;">' . $this->l('Voucher code:') . ' ' . $objDiscount->name . '</td>
							<td style="padding: 0.6em 0.4em; text-align: right;">' . ($value != 0.0 ? '-' : '') . Tools::displayPrice($value, $currency, false) . '</td>
					</tr>';
                }
                // Specify order id for message
                $oldMessage = Message::getMessageByCartId((int) $cart->id);
                if ($oldMessage) {
                    $message = new Message((int) $oldMessage['id_message']);
                    $message->id_order = (int) $order->id;
                    $message->update();
                }
                // Hook new order
                $orderStatus = new OrderState((int) $id_order_state, (int) $order->id_lang);
                if (Validate::isLoadedObject($orderStatus)) {
                    Hook::newOrder($cart, $order, $customer, $currency, $orderStatus);
                    foreach ($cart->getProducts() as $product) {
                        if ($orderStatus->logable) {
                            ProductSale::addProductSale((int) $product['id_product'], (int) $product['cart_quantity']);
                        }
                    }
                }
                if (isset($outOfStock) and $outOfStock) {
                    $history = new OrderHistory();
                    $history->id_order = (int) $order->id;
                    $history->changeIdOrderState(_PS_OS_OUTOFSTOCK_, (int) $order->id);
                    $history->addWithemail();
                }
                // Set order state in order history ONLY even if the "out of stock" status has not been yet reached
                // So you migth have two order states
                $new_history = new OrderHistory();
                $new_history->id_order = (int) $order->id;
                $new_history->changeIdOrderState((int) $id_order_state, (int) $order->id);
                $new_history->addWithemail(true, $extraVars);
                //Payment status
                $paymentHistory = new OrderPaymentHistory();
                $paymentHistory->id_order = (int) $order->id;
                $paymentHistory->changeIdOrderPaymentState($id_payment_state, (int) $order->id);
                $paymentHistory->addState();
                // Order is reloaded because the status just changed
                $order = new Order($order->id);
                //Update tracking code for quantium
                if ($order->id_carrier == QUANTIUM) {
                    if (strpos($order->payment, 'COD') === false) {
                        $order->shipping_number = 'VBN' . $order->id;
                    } else {
                        $order->shipping_number = 'VBC' . $order->id;
                    }
                    $order->update();
                } else {
                    if ($order->id_carrier == SABEXPRESS) {
                        $db = Db::getInstance();
                        $db->Execute('LOCK TABLES vb_awb_pool WRITE');
                        $res = $db->getRow("select min(id) as 'id', awb from vb_awb_pool where id_carrier = " . SABEXPRESS . " and assigned = 0");
                        $awb = $res['awb'];
                        $id = $res['id'];
                        $db->Execute("update vb_awb_pool set assigned = 1 where id = " . $id);
                        $db->Execute('UNLOCK TABLES');
                        $order->shipping_number = $awb;
                        $order->update();
                    } else {
                        if ($order->id_carrier == AFL) {
                            $db = Db::getInstance();
                            $db->Execute('LOCK TABLES vb_awb_pool WRITE');
                            $res = $db->getRow("select min(id) as 'id' , awb from vb_awb_pool where id_carrier = " . AFL . " and assigned = 0");
                            $awb = $res['awb'];
                            $id = $res['id'];
                            $db->Execute("update vb_awb_pool set assigned = 1 where id = " . $id);
                            $db->Execute('UNLOCK TABLES');
                            $order->shipping_number = $awb;
                            $order->update();
                        }
                    }
                }
                // Send an e-mail to customer
                if ($id_order_state != _PS_OS_ERROR_ and $id_order_state != _PS_OS_CANCELED_ and $customer->id and $id_order_state != _PS_OS_OP_PAYEMENT_FAILED) {
                    //deduct reward points
                    $points_redeemed = $cart->getPoints();
                    if ($points_redeemed) {
                        VBRewards::removeRewardPoints($order->id_customer, EVENT_POINTS_REDEEMED, 0, $cart->getPoints(), 'Coins redeemed - Order no ' . $order->id, $order->id, $order->date_add);
                    }
                    /*
                    if(strpos($order->payment, 'COD') === false && $order->total_paid_real > 0)
                    {
                        VBRewards::addRewardPoints($order->id_customer, ONLINE_ORDER, 0, 100, 'Online payment bonus - Order no ' . $order->id, $order->id, $order->date_add);
                    }
                    */
                    $invoice = new Address((int) $order->id_address_invoice);
                    $delivery = new Address((int) $order->id_address_delivery);
                    $carrier = new Carrier((int) $order->id_carrier, $order->id_lang);
                    $delivery_state = $delivery->id_state ? new State((int) $delivery->id_state) : false;
                    $invoice_state = $invoice->id_state ? new State((int) $invoice->id_state) : false;
                    $shippingdate = new DateTime($order->expected_shipping_date);
                    $data = array('{firstname}' => $customer->firstname, '{shipping_date}' => $shippingdate->format("F j, Y"), '{lastname}' => $customer->lastname, '{email}' => $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="color:#DB3484; font-weight:bold;">%s</span>', 'lastname' => '<span style="color:#DB3484; font-weight:bold;">%s</span>')), '{invoice_block_html}' => $this->_getFormatedAddress($invoice, "<br />", array('firstname' => '<span style="color:#DB3484; font-weight:bold;">%s</span>', 'lastname' => '<span style="color:#DB3484; 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}' => sprintf("#%06d", (int) $order->id), '{date}' => date("F j, Y, g:i a"), '{carrier}' => $carrier->name, '{payment}' => Tools::substr($order->payment, 0, 32), '{products}' => $productsList, '{discounts}' => $discountsList, '{total_paid}' => Tools::displayPrice($order->total_paid, $currency, false), '{total_products}' => Tools::displayPrice($order->total_paid - $order->total_shipping - $order->total_cod - $order->total_wrapping + $order->total_discounts, $currency, false), '{total_discounts}' => Tools::displayPrice($order->total_discounts, $currency, false), '{total_shipping}' => Tools::displayPrice($order->total_shipping, $currency, false), '{total_cod}' => Tools::displayPrice($order->total_cod, $currency, false), '{total_wrapping}' => Tools::displayPrice($order->total_wrapping, $currency, false));
                    if (is_array($extraVars)) {
                        $data = array_merge($data, $extraVars);
                    }
                    // Join PDF invoice
                    if ((int) Configuration::get('PS_INVOICE') and Validate::isLoadedObject($orderStatus) and $orderStatus->invoice and $order->invoice_number) {
                        $fileAttachment['content'] = PDF::invoice($order, 'S');
                        $fileAttachment['name'] = $fileAttachment['name'] = 'IndusDiva Order #' . sprintf('%06d', (int) $order->id) . '.pdf';
                        $fileAttachment['mime'] = 'application/pdf';
                    } else {
                        $fileAttachment = NULL;
                    }
                    if (Validate::isEmail($customer->email)) {
                        if ($id_order_state == _PS_OS_BANKWIRE_) {
                            Mail::Send((int) $order->id_lang, 'order_conf_bankwire', Mail::l('Your order #' . $order->id . ' with IndusDiva.com is confirmed'), $data, $customer->email, $customer->firstname . ' ' . $customer->lastname, NULL, NULL, $fileAttachment);
                        } else {
                            $data['payment'] = 'Online Payment';
                            Mail::Send((int) $order->id_lang, 'order_conf', Mail::l('Your order #' . $order->id . ' with IndusDiva.com is confirmed'), $data, $customer->email, $customer->firstname . ' ' . $customer->lastname, NULL, NULL, $fileAttachment);
                        }
                    }
                    //Send SMS
                    //$smsText = 'Dear customer, your order #'.$order->id.' at IndusDiva.com is confirmed and will be delivered to you within 3-5 business days. www.indusdiva.com';
                    //Tools::sendSMS($delivery->phone_mobile, $smsText);
                }
                $this->currentOrder = (int) $order->id;
                return true;
            } else {
                $errorMessage = Tools::displayError('Order creation failed');
                Logger::addLog($errorMessage, 4, '0000002', 'Cart', intval($order->id_cart));
                die($errorMessage);
            }
        } else {
            $errorMessage = Tools::displayError('Cart can\'t be loaded or an order has already been placed using this cart');
            Logger::addLog($errorMessage, 4, '0000001', 'Cart', intval($cart->id));
            die($errorMessage);
        }
    }
Example #14
0
 public function getProducts($selected_filters, &$products, &$nb_products, &$p, &$n, &$pages_nb, &$start, &$stop, &$range, &$combinations)
 {
     global $cookie;
     $products = $this->getProductByFilters($selected_filters);
     $products = Product::getProductsProperties((int) $cookie->id_lang, $products);
     $nb_products = $this->nbr_products;
     $range = 2;
     /* how many pages around page selected */
     $n = (int) Tools::getValue('n', Configuration::get('PS_PRODUCTS_PER_PAGE'));
     if ($n <= 0) {
         $n = 1;
     }
     $p = $this->page;
     if ($p < 0) {
         $p = 0;
     }
     if ($p > $nb_products / $n) {
         $p = ceil($nb_products / $n);
     }
     $pages_nb = ceil($nb_products / (int) $n);
     $start = (int) ($p - $range);
     if ($start < 1) {
         $start = 1;
     }
     $stop = (int) ($p + $range);
     if ($stop > $pages_nb) {
         $stop = (int) $pages_nb;
     }
     foreach ($products as &$product) {
         if ($product['id_product_attribute'] && isset($product['product_attribute_minimal_quantity'])) {
             $product['minimal_quantity'] = $product['product_attribute_minimal_quantity'];
         }
         $product_obj = new Product((int) $product['id_product'], $this->context->language->id);
         $product['groups'] = $product_obj->getProductCombinationsGroups((int) $product['id_product']);
         $product['obj'] = $product_obj;
         $combinations[$product['id_product']] = $product_obj->getProductAttributeCombinations($product['id_product']);
         $id_group = (int) Group::getCurrent()->id;
         $group_reduction = GroupReduction::getValueForProduct($product['id_product'], $id_group);
         if ($group_reduction === false) {
             $group_reduction = Group::getReduction((int) $this->context->cookie->id_customer) / 100;
         }
         $product['group_reduction'] = $group_reduction;
         $address = new Address($this->context->cart->{Configuration::get('PS_TAX_ADDRESS_TYPE')});
         $product['no_tax'] = Tax::excludeTaxeOption() || !$product_obj->getTaxesRate($address);
         $product['customer_group_without_tax'] = Group::getPriceDisplayMethod($this->context->customer->id_default_group);
         $tax = (double) $product_obj->getTaxesRate(new Address((int) $this->context->cart->{Configuration::get('PS_TAX_ADDRESS_TYPE')}));
         $product['tax_rate'] = $tax;
         $product['unit_price_ratio'] = $product_obj->unit_price_ratio;
         $ecotax_rate = (double) Tax::getProductEcotaxRate($this->context->cart->{Configuration::get('PS_TAX_ADDRESS_TYPE')});
         $product['ecotaxTax_rate'] = $ecotax_rate;
     }
 }
Example #15
0
    function hookProductFooter($params)
    {
        global $smarty, $cookie;
        $priceFormat = Configuration::get('PRODUCT_ATTRIB_NC_PRICE_FORMAT');
        $fullPrice = Configuration::get('PRODUCT_ATTRIB_NC_FULL_PRICE');
        $product = new Product(intval($_GET['id_product']), true, intval($cookie->id_lang));
        if ($priceFormat > 1) {
            // Tax
            $tax_datas = Db::getInstance()->getRow('
			SELECT p.`id_tax`, t.`rate`
			FROM `' . _DB_PREFIX_ . 'product` p
			LEFT JOIN `' . _DB_PREFIX_ . 'tax` AS t ON t.`id_tax` = p.`id_tax`
			WHERE p.`id_product` = ' . intval($product->id));
            $tax = floatval(Tax::getApplicableTax(intval($tax_datas['id_tax']), floatval($tax_datas['rate'])));
        }
        /* Attributes / Groups & colors */
        $colors = array();
        $attributesGroups = Db::getInstance()->ExecuteS('
			SELECT ag.`id_attribute_group`, agl.`name` AS group_name, agl.`public_name` AS public_group_name, a.`id_attribute`, al.`name` AS attribute_name,
			a.`color` AS attribute_color, pa.`id_product_attribute`, pa.`quantity`, pa.`price`, pa.`ecotax`, pa.`weight`, pa.`default_on`, pa.`reference`
			FROM `' . _DB_PREFIX_ . 'product_attribute` pa
			LEFT JOIN `' . _DB_PREFIX_ . 'product_attribute_combination` pac ON pac.`id_product_attribute` = pa.`id_product_attribute`
			LEFT JOIN `' . _DB_PREFIX_ . 'attribute` a ON a.`id_attribute` = pac.`id_attribute`
			LEFT JOIN `' . _DB_PREFIX_ . 'attribute_group` ag ON ag.`id_attribute_group` = a.`id_attribute_group`
			LEFT JOIN `' . _DB_PREFIX_ . 'attribute_lang` al ON a.`id_attribute` = al.`id_attribute`
			LEFT JOIN `' . _DB_PREFIX_ . 'attribute_group_lang` agl ON ag.`id_attribute_group` = agl.`id_attribute_group`
			WHERE pa.`id_product` = ' . intval($product->id) . '
			AND al.`id_lang` = ' . intval($cookie->id_lang) . '
			AND agl.`id_lang` = ' . intval($cookie->id_lang) . '
			ORDER BY agl.`public_name`');
        if (Db::getInstance()->numRows()) {
            foreach ($attributesGroups as $k => $row) {
                /* Color management */
                if (isset($row['attribute_color']) and $row['attribute_color'] and $row['id_attribute_group'] == $product->id_color_default) {
                    $colors[$row['id_attribute']]['value'] = $row['attribute_color'];
                    $colors[$row['id_attribute']]['name'] = $row['attribute_name'];
                }
                $groups[$row['id_attribute_group']]['attributes'][$row['id_attribute']] = $row['attribute_name'];
                if (strpos($row['public_group_name'], '|') !== FALSE) {
                    $label = explode('|', $row['public_group_name'], 2);
                    $groups[$row['id_attribute_group']]['label'] = $label[0];
                    $groups[$row['id_attribute_group']]['name'] = $label[1];
                } else {
                    $groups[$row['id_attribute_group']]['name'] = $row['public_group_name'];
                }
                if ($row['default_on']) {
                    $groups[$row['id_attribute_group']]['default'] = intval($row['id_attribute']);
                }
                if (!isset($groups[$row['id_attribute_group']]['attributes_quantity'][$row['id_attribute']])) {
                    $groups[$row['id_attribute_group']]['attributes_quantity'][$row['id_attribute']] = 0;
                }
                $groups[$row['id_attribute_group']]['attributes_quantity'][$row['id_attribute']] += intval($row['quantity']);
            }
            $smarty->assign(array('col_img_dir' => _PS_COL_IMG_DIR_, 'reductionPrice' => $product->reduction_price, 'reductionPercent' => $product->reduction_percent, 'reductionFrom' => $product->reduction_from, 'reductionTo' => $product->reduction_to, 'groupReduction' => (100 - Group::getReduction(intval($cookie->id_customer))) / 100, 'groups' => $groups, 'attributeImpacts' => Db::getInstance()->ExecuteS('SELECT * FROM `' . _DB_PREFIX_ . 'attribute_impact` WHERE `id_product` = ' . intval($_GET['id_product'])), 'fullPrice' => $fullPrice, 'price' => $fullPrice ? number_format($product->price * (1 + $tax * 0.01), 2, '.', '') : 0, 'priceFormat' => $priceFormat, 'hideZeros' => Configuration::get('PRODUCT_ATTRIB_NC_HIDE_ZEROS'), 'weight' => $product->weight, 'weightUnit' => Configuration::get('PS_WEIGHT_UNIT'), 'displayWeight' => Configuration::get('PRODUCT_ATTRIB_NC_DISPLAY_WEIGHT'), 'displayImage' => Configuration::get('PRODUCT_ATTRIB_NC_DISPLAY_IMAGE'), 'displayDescription' => Configuration::get('PRODUCT_ATTRIB_NC_DISPLAY_DESC')));
            if ($priceFormat > 1) {
                $smarty->assign(array('tax' => 1 - $tax / 100));
            }
        }
        return $this->display(__FILE__, 'productattributesnc.tpl');
    }
 public function process()
 {
     global $cart, $currency;
     parent::process();
     if (!($id_product = (int) Tools::getValue('id_product')) or !Validate::isUnsignedId($id_product)) {
         $this->errors[] = Tools::displayError('Product not found');
     } else {
         if (!Validate::isLoadedObject($this->product) or !$this->product->active and Tools::getValue('adtoken') != Tools::encrypt('PreviewProduct' . $this->product->id) || !file_exists(dirname(__FILE__) . '/../' . Tools::getValue('ad') . '/ajax.php')) {
             header('HTTP/1.1 404 page not found');
             $this->errors[] = Tools::displayError('Product is no longer available.');
         } elseif (!$this->product->checkAccess((int) self::$cookie->id_customer)) {
             $this->errors[] = Tools::displayError('You do not have access to this product.');
         } else {
             self::$smarty->assign('virtual', ProductDownload::getIdFromIdProduct((int) $this->product->id));
             if (!$this->product->active) {
                 self::$smarty->assign('adminActionDisplay', true);
             }
             /* rewrited url set */
             $rewrited_url = self::$link->getProductLink($this->product->id, $this->product->link_rewrite);
             /* Product pictures management */
             require_once 'images.inc.php';
             self::$smarty->assign('customizationFormTarget', Tools::safeOutput(urldecode($_SERVER['REQUEST_URI'])));
             if (Tools::isSubmit('submitCustomizedDatas')) {
                 $this->pictureUpload($this->product, $cart);
                 $this->textRecord($this->product, $cart);
                 $this->formTargetFormat();
             } elseif (isset($_GET['deletePicture']) and !$cart->deletePictureToProduct((int) $this->product->id, (int) Tools::getValue('deletePicture'))) {
                 $this->errors[] = Tools::displayError('An error occurred while deleting the selected picture');
             }
             $files = self::$cookie->getFamily('pictures_' . (int) $this->product->id);
             $textFields = self::$cookie->getFamily('textFields_' . (int) $this->product->id);
             foreach ($textFields as $key => $textField) {
                 $textFields[$key] = str_replace('<br />', "\n", $textField);
             }
             self::$smarty->assign(array('pictures' => $files, 'textFields' => $textFields));
             if ((int) Tools::getValue('pp') == 1) {
                 echo 'here1';
             }
             $productPriceWithTax = Product::getPriceStatic($id_product, true, NULL, 6);
             if (Product::$_taxCalculationMethod == PS_TAX_INC) {
                 $productPriceWithTax = Tools::ps_round($productPriceWithTax, 2);
             }
             if ((int) Tools::getValue('pp') == 1) {
                 $time2 = time();
                 echo 'time2: ' . $time2;
             }
             $productPriceWithoutEcoTax = (double) ($productPriceWithTax - $this->product->ecotax);
             $configs = Configuration::getMultiple(array('PS_ORDER_OUT_OF_STOCK', 'PS_LAST_QTIES'));
             /* Features / Values */
             $features = $this->product->getFrontFeatures((int) self::$cookie->id_lang);
             $attachments = $this->product->getAttachments((int) self::$cookie->id_lang);
             /* Category */
             $category = false;
             if (isset($_SERVER['HTTP_REFERER']) and preg_match('!^(.*)\\/([0-9]+)\\-(.*[^\\.])|(.*)id_category=([0-9]+)(.*)$!', $_SERVER['HTTP_REFERER'], $regs) and !strstr($_SERVER['HTTP_REFERER'], '.html')) {
                 if (isset($regs[2]) and is_numeric($regs[2])) {
                     if (Product::idIsOnCategoryId((int) $this->product->id, array('0' => array('id_category' => (int) $regs[2])))) {
                         $category = new Category((int) $regs[2], (int) self::$cookie->id_lang);
                     }
                 } elseif (isset($regs[5]) and is_numeric($regs[5])) {
                     if (Product::idIsOnCategoryId((int) $this->product->id, array('0' => array('id_category' => (int) $regs[5])))) {
                         $category = new Category((int) $regs[5], (int) self::$cookie->id_lang);
                     }
                 }
             }
             if (!$category) {
                 $category = new Category($this->product->id_category_default, (int) self::$cookie->id_lang);
             }
             if (isset($category) and Validate::isLoadedObject($category)) {
                 self::$smarty->assign(array('path' => Tools::getPath((int) $category->id, $this->product->name, true), 'category' => $category, 'subCategories' => $category->getSubCategories((int) self::$cookie->id_lang, true), 'id_category_current' => (int) $category->id, 'id_category_parent' => (int) $category->id_parent, 'return_category_name' => Tools::safeOutput($category->name)));
             } else {
                 self::$smarty->assign('path', Tools::getPath((int) $this->product->id_category_default, $this->product->name));
             }
             self::$smarty->assign('return_link', (isset($category->id) and $category->id) ? Tools::safeOutput(self::$link->getCategoryLink($category)) : 'javascript: history.back();');
             $lang = Configuration::get('PS_LANG_DEFAULT');
             if (Pack::isPack((int) $this->product->id, (int) $lang) and !Pack::isInStock((int) $this->product->id, (int) $lang)) {
                 $this->product->quantity = 0;
             }
             $group_reduction = (100 - Group::getReduction((int) self::$cookie->id_customer)) / 100;
             $id_customer = (isset(self::$cookie->id_customer) and self::$cookie->id_customer) ? (int) self::$cookie->id_customer : 0;
             $id_group = $id_customer ? (int) Customer::getDefaultGroupId($id_customer) : _PS_DEFAULT_CUSTOMER_GROUP_;
             $id_country = (int) ($id_customer ? Customer::getCurrentCountry($id_customer) : Configuration::get('PS_COUNTRY_DEFAULT'));
             if ((int) Tools::getValue('pp') == 1) {
                 $time3 = time();
                 echo 'time3: ' . $time3;
             }
             // Tax
             $tax = (double) Tax::getProductTaxRate((int) $this->product->id, $cart->{Configuration::get('PS_TAX_ADDRESS_TYPE')});
             self::$smarty->assign('tax_rate', $tax);
             $ecotax_rate = (double) Tax::getProductEcotaxRate($cart->{Configuration::get('PS_TAX_ADDRESS_TYPE')});
             $ecotaxTaxAmount = Tools::ps_round($this->product->ecotax, 2);
             if (Product::$_taxCalculationMethod == PS_TAX_INC && (int) Configuration::get('PS_TAX')) {
                 $ecotaxTaxAmount = Tools::ps_round($ecotaxTaxAmount * (1 + $ecotax_rate / 100), 2);
             }
             $manufacturer = new Manufacturer((int) $this->product->id_manufacturer, 1);
             $sizechart = new Sizechart((int) $this->product->id_sizechart, 1);
             //see if the product is already in the wishlist
             if ($id_customer) {
                 $sql = "select id from ps_wishlist where id_customer = " . $id_customer . " and id_product = " . $this->product->id;
                 $res = Db::getInstance()->ExecuteS($sql);
                 if ($res) {
                     self::$smarty->assign("in_wishlist", true);
                 } else {
                     self::$smarty->assign("in_wishlist", false);
                 }
             } else {
                 self::$smarty->assign("in_wishlist", false);
             }
             self::$smarty->assign(array('quantity_discounts' => $this->formatQuantityDiscounts(SpecificPrice::getQuantityDiscounts((int) $this->product->id, (int) Shop::getCurrentShop(), (int) self::$cookie->id_currency, $id_country, $id_group), $this->product->getPrice(Product::$_taxCalculationMethod == PS_TAX_INC, false), (double) $tax), 'product' => $this->product, 'ecotax_tax_inc' => $ecotaxTaxAmount, 'ecotax_tax_exc' => Tools::ps_round($this->product->ecotax, 2), 'ecotaxTax_rate' => $ecotax_rate, 'homeSize' => Image::getSize('home'), 'product_manufacturer' => $manufacturer, 'token' => Tools::getToken(false), 'productPriceWithoutEcoTax' => (double) $productPriceWithoutEcoTax, 'features' => $features, 'attachments' => $attachments, 'allow_oosp' => $this->product->isAvailableWhenOutOfStock((int) $this->product->out_of_stock), 'last_qties' => (int) $configs['PS_LAST_QTIES'], 'group_reduction' => $group_reduction, 'col_img_dir' => _PS_COL_IMG_DIR_, 'sizechart' => $sizechart->sizechart, 'sizechart_data' => $sizechart->sizechart_data));
             self::$smarty->assign(array('HOOK_EXTRA_LEFT' => Module::hookExec('extraLeft'), 'HOOK_EXTRA_RIGHT' => Module::hookExec('extraRight'), 'HOOK_PRODUCT_OOS' => Hook::productOutOfStock($this->product), 'HOOK_PRODUCT_FOOTER' => Hook::productFooter($this->product, $category), 'HOOK_PRODUCT_ACTIONS' => Module::hookExec('productActions'), 'HOOK_PRODUCT_TAB' => Module::hookExec('productTab'), 'HOOK_PRODUCT_TAB_CONTENT' => Module::hookExec('productTabContent')));
             if ((int) Tools::getValue('pp') == 1) {
                 $time4 = time();
                 echo 'time4: ' . $time4;
             }
             $images = $this->product->getImages((int) self::$cookie->id_lang);
             $productImages = array();
             foreach ($images as $k => $image) {
                 if ($image['cover']) {
                     self::$smarty->assign('mainImage', $images[0]);
                     $cover = $image;
                     $cover['id_image'] = Configuration::get('PS_LEGACY_IMAGES') ? $this->product->id . '-' . $image['id_image'] : $image['id_image'];
                     $cover['id_image_only'] = (int) $image['id_image'];
                 }
                 $productImages[(int) $image['id_image']] = $image;
             }
             if (!isset($cover)) {
                 $cover = array('id_image' => Language::getIsoById(self::$cookie->id_lang) . '-default', 'legend' => 'No picture', 'title' => 'No picture');
             }
             $size = Image::getSize('large');
             self::$smarty->assign(array('cover' => $cover, 'imgWidth' => (int) $size['width'], 'mediumSize' => Image::getSize('medium'), 'largeSize' => Image::getSize('large'), 'accessories' => $this->product->getAccessories((int) self::$cookie->id_lang)));
             if (sizeof($productImages)) {
                 self::$smarty->assign('images', $productImages);
             }
             if ((int) Tools::getValue('pp') == 1) {
                 $time5 = time();
                 echo 'time5: ' . $time5;
             }
             /* Attributes / Groups & colors */
             $colors = array();
             //see if the product has shades
             if ($this->product->id_group && $this->product->id_group > 0) {
                 global $link;
                 $related_productIds = $this->product->getRelatedProducts();
                 $related_products = array();
                 foreach ($related_productIds as &$productId) {
                     $relProduct = new Product((int) $productId['id_product'], true, self::$cookie->id_lang);
                     $idImage = $relProduct->getCoverWs();
                     if ($idImage) {
                         $idImage = $relProduct->id . '-' . $idImage;
                     } else {
                         $idImage = Language::getIsoById(1) . '-default';
                     }
                     $relProduct->image_link = $link->getImageLink($relProduct->link_rewrite, $idImage, 'small');
                     $relProduct->link = $relProduct->getLink();
                     $related_products[] = $relProduct;
                 }
                 self::$smarty->assign('relatedProducts', $related_products);
             }
             if ((int) Tools::getValue('pp') == 1) {
                 $time6 = time();
                 echo 'time6: ' . $time6;
             }
             $attributesGroups = $this->product->getAttributesGroups((int) self::$cookie->id_lang);
             // @todo (RM) should only get groups and not all declination ?
             if (is_array($attributesGroups) and $attributesGroups) {
                 $groups = array();
                 $combinationImages = $this->product->getCombinationImages((int) self::$cookie->id_lang);
                 foreach ($attributesGroups as $k => $row) {
                     /* Color management */
                     if ((isset($row['attribute_color']) and $row['attribute_color'] or file_exists(_PS_COL_IMG_DIR_ . $row['id_attribute'] . '.jpg')) and $row['id_attribute_group'] == $this->product->id_color_default) {
                         $colors[$row['id_attribute']]['value'] = $row['attribute_color'];
                         $colors[$row['id_attribute']]['name'] = $row['attribute_name'];
                         if (!isset($colors[$row['id_attribute']]['attributes_quantity'])) {
                             $colors[$row['id_attribute']]['attributes_quantity'] = 0;
                         }
                         $colors[$row['id_attribute']]['attributes_quantity'] += (int) $row['quantity'];
                     }
                     if (!isset($groups[$row['id_attribute_group']])) {
                         $groups[$row['id_attribute_group']] = array('name' => $row['public_group_name'], 'is_color_group' => $row['is_color_group'], 'default' => -1);
                     }
                     $groups[$row['id_attribute_group']]['attributes'][$row['id_attribute']] = $row['attribute_name'];
                     if ($row['default_on'] && $groups[$row['id_attribute_group']]['default'] == -1) {
                         $groups[$row['id_attribute_group']]['default'] = (int) $row['id_attribute'];
                     }
                     if (!isset($groups[$row['id_attribute_group']]['attributes_quantity'][$row['id_attribute']])) {
                         $groups[$row['id_attribute_group']]['attributes_quantity'][$row['id_attribute']] = 0;
                     }
                     $groups[$row['id_attribute_group']]['attributes_quantity'][$row['id_attribute']] += (int) $row['quantity'];
                     $combinations[$row['id_product_attribute']]['attributes_values'][$row['id_attribute_group']] = $row['attribute_name'];
                     $combinations[$row['id_product_attribute']]['attributes'][] = (int) $row['id_attribute'];
                     $combinations[$row['id_product_attribute']]['price'] = (double) $row['price'];
                     $combinations[$row['id_product_attribute']]['ecotax'] = (double) $row['ecotax'];
                     $combinations[$row['id_product_attribute']]['weight'] = (double) $row['weight'];
                     $combinations[$row['id_product_attribute']]['quantity'] = (int) $row['quantity'];
                     $combinations[$row['id_product_attribute']]['reference'] = $row['reference'];
                     $combinations[$row['id_product_attribute']]['unit_impact'] = $row['unit_price_impact'];
                     $combinations[$row['id_product_attribute']]['minimal_quantity'] = $row['minimal_quantity'];
                     $combinations[$row['id_product_attribute']]['id_image'] = isset($combinationImages[$row['id_product_attribute']][0]['id_image']) ? $combinationImages[$row['id_product_attribute']][0]['id_image'] : -1;
                 }
                 if ((int) Tools::getValue('pp') == 1) {
                     $time7 = time();
                     echo 'time7: ' . $time7;
                 }
                 //wash attributes list (if some attributes are unavailables and if allowed to wash it)
                 if (!Product::isAvailableWhenOutOfStock($this->product->out_of_stock) && Configuration::get('PS_DISP_UNAVAILABLE_ATTR') == 0) {
                     foreach ($groups as &$group) {
                         foreach ($group['attributes_quantity'] as $key => &$quantity) {
                             if (!$quantity) {
                                 unset($group['attributes'][$key]);
                             }
                         }
                     }
                     foreach ($colors as $key => $color) {
                         if (!$color['attributes_quantity']) {
                             unset($colors[$key]);
                         }
                     }
                 }
                 if ((int) Tools::getValue('pp') == 1) {
                     $time71 = time();
                     echo 'time71: ' . $time71;
                 }
                 foreach ($groups as &$group) {
                     natcasesort($group['attributes']);
                 }
                 foreach ($combinations as $id_product_attribute => $comb) {
                     $attributeList = '';
                     foreach ($comb['attributes'] as $id_attribute) {
                         $attributeList .= '\'' . (int) $id_attribute . '\',';
                     }
                     $attributeList = rtrim($attributeList, ',');
                     $combinations[$id_product_attribute]['list'] = $attributeList;
                 }
                 self::$smarty->assign(array('groups' => $groups, 'combinaisons' => $combinations, 'combinations' => $combinations, 'colors' => (sizeof($colors) and $this->product->id_color_default) ? $colors : false, 'combinationImages' => $combinationImages));
             }
             if ((int) Tools::getValue('pp') == 1) {
                 $time72 = time();
                 echo 'time72: ' . $time72;
             }
             //$newProducts = Product::getNewProducts((int)(self::$cookie->id_lang), 0, 10, false, 'date_add', 'desc');
             /*$categoryProducts = $this->getRandomCatProducts();
               self::$smarty->assign('cat_products', $categoryProducts);*/
             //$brandProducts = $this->getRandomBrandProducts();
             //self::$smarty->assign('brand_products', $brandProducts);
             if ((int) Tools::getValue('pp') == 1) {
                 $time73 = time();
                 echo ' time73: ' . $time73;
             }
             self::$smarty->assign(array('no_tax' => Tax::excludeTaxeOption() or !Tax::getProductTaxRate((int) $this->product->id, $cart->{Configuration::get('PS_TAX_ADDRESS_TYPE')}), 'customizationFields' => $this->product->getCustomizationFields((int) self::$cookie->id_lang)));
             if ((int) Tools::getValue('pp') == 1) {
                 $time74 = time();
                 echo 'time74: ' . $time74;
             }
             // Pack management
             self::$smarty->assign('packItems', $this->product->cache_is_pack ? Pack::getItemTable($this->product->id, (int) self::$cookie->id_lang, true) : array());
             self::$smarty->assign('packs', Pack::getPacksTable($this->product->id, (int) self::$cookie->id_lang, true, 1));
             if ((int) Tools::getValue('pp') == 1) {
                 print_r('pack done');
             }
         }
     }
     if ((int) Tools::getValue('pp') == 1) {
         $time8 = time();
         echo 'time8: ' . $time8;
     }
     if ($this->is_saree || $this->is_lehenga) {
         if ($this->is_lehenga) {
             self::$smarty->assign('is_lehenga', $this->is_lehenga);
         }
         self::$smarty->assign('as_shown', (bool) $this->product->as_shown);
         /*if($blouse_measurements = $this->getCustomerMeasurements(self::$cookie->id_customer, 1))
               self::$smarty->assign('measurement_info', $blouse_measurements);
           if($skirt_measurements = $this->getCustomerMeasurements(self::$cookie->id_customer, 2))
               self::$smarty->assign('skirt_measurement_info', $skirt_measurements);*/
         if ((int) Tools::getValue('pp') == 1) {
             $time81 = time();
             echo 'time81: ' . $time81;
         }
         if ($this->is_saree) {
             //count of all styles mapped to this product
             $res = Db::getInstance()->getRow("select count(s.id_style) as style_count from ps_styles s inner join ps_product_style ps on ps.id_style = s.id_style and ps.id_product = {$id_product} and s.style_type = 1");
             $style_count = (int) $res['style_count'];
             if ($style_count === 0) {
                 // show the default style for sarees
                 $style = array('id_style' => 1, 'style_image_small' => '1-small.png', 'style_name' => 'Round');
             } else {
                 $res = Db::getInstance()->getRow("select s.id_style, s.style_name, s.style_image_small  from ps_styles s inner join ps_product_style ps on ps.id_style = s.id_style and ps.id_product = {$id_product} and s.style_type = 1 and ps.is_default = 1");
                 if (!empty($res)) {
                     //show the default style for this product
                     $style = array('id_style' => $res['id_style'], 'style_image_small' => $res['style_image_small'], 'style_name' => $res['style_name']);
                 }
             }
             if ((int) Tools::getValue('pp') == 1) {
                 $time82 = time();
                 echo 'time82: ' . $time82;
             }
             self::$smarty->assign('blouse_style_count', $style_count);
             self::$smarty->assign('blouse_style', $style);
         }
     } else {
         if ($this->is_skd || $this->is_skd_rts) {
             self::$smarty->assign('is_anarkali', $this->is_anarkali);
             if ($this->is_anarkali) {
                 if ($kurta_measurements = $this->getCustomerMeasurements(self::$cookie->id_customer, 5)) {
                     self::$smarty->assign('kurta_measurement_info', $kurta_measurements);
                 }
             } else {
                 if ($kurta_measurements = $this->getCustomerMeasurements(self::$cookie->id_customer, 3)) {
                     self::$smarty->assign('kurta_measurement_info', $kurta_measurements);
                 }
             }
             if ($salwar_measurements = $this->getCustomerMeasurements(self::$cookie->id_customer, 4)) {
                 self::$smarty->assign('salwar_measurement_info', $salwar_measurements);
             }
             //get default styles for this product (RTS)
             if ($this->is_skd_rts) {
                 $res = Db::getInstance()->ExecuteS("select count(s.id_style) as style_count, s.style_type, ps.id_product from ps_styles s inner join ps_product_style ps on ps.id_style = s.id_style and ps.id_product = {$id_product} group by ps.id_product,s.style_type");
                 foreach ($res as $s) {
                     $style_count = (int) $s['style_count'];
                     if ((int) $s['style_type'] === 4) {
                         self::$smarty->assign('kurta_style_count', $style_count);
                     } else {
                         if ((int) $s['style_type'] === 5) {
                             self::$smarty->assign('salwar_style_count', $style_count);
                         }
                     }
                 }
                 $res = Db::getInstance()->ExecuteS("select s.id_style, s.style_type, s.style_image_small, s.style_name from ps_styles s inner join ps_product_style ps on ps.id_style = s.id_style and ps.id_product = {$id_product} and ps.is_default = 1");
                 foreach ($res as $s) {
                     $style = array('id_style' => $s['id_style'], 'style_image_small' => $s['style_image_small'], 'style_name' => $s['style_name']);
                     if ((int) $s['style_type'] === 4) {
                         self::$smarty->assign('kurta_style', $style);
                     } else {
                         if ((int) $s['style_type'] === 5) {
                             self::$smarty->assign('salwar_style', $style);
                         }
                     }
                 }
             }
         }
     }
     self::$smarty->assign('is_bottoms', $this->is_bottoms);
     self::$smarty->assign('is_abaya', $this->is_abaya);
     self::$smarty->assign('is_wristwear', $this->is_wristwear);
     self::$smarty->assign('is_pakistani_rts', $this->is_pakistani_rts);
     if ((int) Tools::getValue('pp') == 1) {
         $time85 = time();
         echo 'time85: ' . $time85;
     }
     self::$smarty->assign(array('ENT_NOQUOTES' => ENT_NOQUOTES, 'outOfStockAllowed' => (int) Configuration::get('PS_ORDER_OUT_OF_STOCK'), 'errors' => $this->errors, 'categories' => Category::getHomeCategories((int) self::$cookie->id_lang), 'have_image' => Product::getCover((int) Tools::getValue('id_product')), 'tax_enabled' => Configuration::get('PS_TAX'), 'display_qties' => (int) Configuration::get('PS_DISPLAY_QTIES'), 'display_ht' => !Tax::excludeTaxeOption(), 'ecotax' => !sizeof($this->errors) and $this->product->ecotax > 0 ? Tools::convertPrice((double) $this->product->ecotax) : 0, 'currencySign' => $currency->sign, 'currencyRate' => $currency->conversion_rate, 'currencyFormat' => $currency->format, 'currencyBlank' => $currency->blank, 'jqZoomEnabled' => Configuration::get('PS_DISPLAY_JQZOOM')));
     if ((int) Tools::getValue('pp') == 1) {
         $time9 = time();
         echo 'time9: ' . $time9;
     }
     //add this to product stats
     //Tools::captureActivity(PSTAT_VIEWS,$id_product);
     if ((int) Tools::getValue('pp') == 1) {
         $time1 = time();
         echo 'process end: ' . $time1;
     }
 }
Example #17
0
 /**
  * Get product price
  *
  * @param integer $id_product Product id
  * @param boolean $tax With taxes or not (optional)
  * @param integer $id_product_attribute Product attribute id (optional)
  * @param integer $decimals Number of decimals (optional)
  * @param integer $divisor Util when paying many time without fees (optional)
  * @return float Product price
  */
 public static function getPriceStaticLC($id_product, $usetax = true, $id_product_attribute = NULL, $decimals = 6, $divisor = NULL, $only_reduc = false, $usereduc = true, $quantity = 1, $forceAssociatedTax = false)
 {
     global $cookie, $currency;
     // Get id_customer if exists
     $id_customer = (isset($cookie) and get_class($cookie) == 'Cookie' and isset($cookie->id_customer) and $cookie->id_customer) ? intval($cookie->id_customer) : null;
     if (!Validate::isBool($usetax) or !Validate::isUnsignedId($id_product)) {
         die(Tools::displayError());
     }
     // Caching system
     $currency_id = '';
     if ($currency) {
         $currency_id = $currency->id;
     }
     $cacheId = $currency_id . '-' . $id_product . '-' . ($usetax ? '1' : '0') . '-' . $id_product_attribute . '-' . $decimals . '-' . $divisor . '-' . ($only_reduc ? '1' : '0') . '-' . ($usereduc ? '1' : '0') . '-' . $quantity;
     if (isset(self::$_prices[$cacheId])) {
         return self::$_prices[$cacheId];
     }
     // Getting price
     $prices = self::getBasePriceStaticLC($id_product, $id_product_attribute);
     $price = $prices['price'];
     // Exclude tax
     $tax = floatval(Tax::getApplicableTax(intval($prices['id_tax']), floatval($prices['rate'])));
     if ($forceAssociatedTax) {
         $tax = floatval($prices['rate']);
     }
     if (Tax::excludeTaxeOption() or !$tax) {
         $usetax = false;
     }
     if ($usetax) {
         $price *= 1 + $tax / 100;
     }
     // Attribute price
     $attribute_price = $usetax ? $prices['attribute_price'] : $prices['attribute_price'] / (1 + ($tax ? $tax : $prices['rate']) / 100);
     if (isset($prices['attribute_price'])) {
         $price += $attribute_price;
     }
     $reduc = self::getReductionValue($prices['reduction_price'], $prices['reduction_percent'], $prices['reduction_from'], $prices['reduction_to'], $price, $usetax, floatval($prices['rate']));
     // Only reduction
     if ($only_reduc) {
         return $reduc;
     }
     // Reduction
     if ($usereduc) {
         $price -= $reduc;
     }
     // Quantity discount
     if ($quantity > 1 and $qtyD = QuantityDiscount::getDiscountFromQuantity($id_product, $quantity)) {
         $price -= QuantityDiscount::getValue($price, $qtyD->id_discount_type, $qtyD->value);
     }
     // * $currency->conversion_rate;
     // Group reduction
     if ($id_customer) {
         $price *= (100 - Group::getReduction($id_customer)) / 100;
     }
     self::$_prices[$cacheId] = ($divisor and $divisor != 'NULL') ? number_format($price / $divisor, $decimals, '.', '') : number_format($price, $decimals, '.', '');
     return self::$_prices[$cacheId];
 }