PageRenderTime 41ms CodeModel.GetById 20ms RepoModel.GetById 0ms app.codeStats 1ms

/classes/Cart.php

https://github.com/cokarmando/PrestaShop
PHP | 3674 lines | 2701 code | 492 blank | 481 comment | 518 complexity | ccb827a3975b3fcc40b4b742e18d3f0d MD5 | raw file
  1. <?php
  2. /*
  3. * 2007-2013 PrestaShop
  4. *
  5. * NOTICE OF LICENSE
  6. *
  7. * This source file is subject to the Open Software License (OSL 3.0)
  8. * that is bundled with this package in the file LICENSE.txt.
  9. * It is also available through the world-wide-web at this URL:
  10. * http://opensource.org/licenses/osl-3.0.php
  11. * If you did not receive a copy of the license and are unable to
  12. * obtain it through the world-wide-web, please send an email
  13. * to license@prestashop.com so we can send you a copy immediately.
  14. *
  15. * DISCLAIMER
  16. *
  17. * Do not edit or add to this file if you wish to upgrade PrestaShop to newer
  18. * versions in the future. If you wish to customize PrestaShop for your
  19. * needs please refer to http://www.prestashop.com for more information.
  20. *
  21. * @author PrestaShop SA <contact@prestashop.com>
  22. * @copyright 2007-2013 PrestaShop SA
  23. * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
  24. * International Registered Trademark & Property of PrestaShop SA
  25. */
  26. class CartCore extends ObjectModel
  27. {
  28. public $id;
  29. public $id_shop_group;
  30. public $id_shop;
  31. /** @var integer Customer delivery address ID */
  32. public $id_address_delivery;
  33. /** @var integer Customer invoicing address ID */
  34. public $id_address_invoice;
  35. /** @var integer Customer currency ID */
  36. public $id_currency;
  37. /** @var integer Customer ID */
  38. public $id_customer;
  39. /** @var integer Guest ID */
  40. public $id_guest;
  41. /** @var integer Language ID */
  42. public $id_lang;
  43. /** @var boolean True if the customer wants a recycled package */
  44. public $recyclable = 0;
  45. /** @var boolean True if the customer wants a gift wrapping */
  46. public $gift = 0;
  47. /** @var string Gift message if specified */
  48. public $gift_message;
  49. /** @var boolean Mobile Theme */
  50. public $mobile_theme;
  51. /** @var string Object creation date */
  52. public $date_add;
  53. /** @var string secure_key */
  54. public $secure_key;
  55. /** @var integer Carrier ID */
  56. public $id_carrier = 0;
  57. /** @var string Object last modification date */
  58. public $date_upd;
  59. public $checkedTos = false;
  60. public $pictures;
  61. public $textFields;
  62. public $delivery_option;
  63. /** @var boolean Allow to seperate order in multiple package in order to recieve as soon as possible the available products */
  64. public $allow_seperated_package = false;
  65. protected static $_nbProducts = array();
  66. protected static $_isVirtualCart = array();
  67. protected $_products = null;
  68. protected static $_totalWeight = array();
  69. protected $_taxCalculationMethod = PS_TAX_EXC;
  70. protected static $_carriers = null;
  71. protected static $_taxes_rate = null;
  72. protected static $_attributesLists = array();
  73. /**
  74. * @see ObjectModel::$definition
  75. */
  76. public static $definition = array(
  77. 'table' => 'cart',
  78. 'primary' => 'id_cart',
  79. 'fields' => array(
  80. 'id_shop_group' => array('type' => self::TYPE_INT, 'validate' => 'isUnsignedId'),
  81. 'id_shop' => array('type' => self::TYPE_INT, 'validate' => 'isUnsignedId'),
  82. 'id_address_delivery' => array('type' => self::TYPE_INT, 'validate' => 'isUnsignedId'),
  83. 'id_address_invoice' => array('type' => self::TYPE_INT, 'validate' => 'isUnsignedId'),
  84. 'id_carrier' => array('type' => self::TYPE_INT, 'validate' => 'isUnsignedId'),
  85. 'id_currency' => array('type' => self::TYPE_INT, 'validate' => 'isUnsignedId', 'required' => true),
  86. 'id_customer' => array('type' => self::TYPE_INT, 'validate' => 'isUnsignedId'),
  87. 'id_guest' => array('type' => self::TYPE_INT, 'validate' => 'isUnsignedId'),
  88. 'id_lang' => array('type' => self::TYPE_INT, 'validate' => 'isUnsignedId', 'required' => true),
  89. 'recyclable' => array('type' => self::TYPE_BOOL, 'validate' => 'isBool'),
  90. 'gift' => array('type' => self::TYPE_BOOL, 'validate' => 'isBool'),
  91. 'gift_message' => array('type' => self::TYPE_STRING, 'validate' => 'isMessage'),
  92. 'mobile_theme' => array('type' => self::TYPE_BOOL, 'validate' => 'isBool'),
  93. 'delivery_option' => array('type' => self::TYPE_STRING),
  94. 'secure_key' => array('type' => self::TYPE_STRING, 'size' => 32),
  95. 'allow_seperated_package' =>array('type' => self::TYPE_BOOL, 'validate' => 'isBool'),
  96. 'date_add' => array('type' => self::TYPE_DATE, 'validate' => 'isDateFormat'),
  97. 'date_upd' => array('type' => self::TYPE_DATE, 'validate' => 'isDateFormat'),
  98. ),
  99. );
  100. protected $webserviceParameters = array(
  101. 'fields' => array(
  102. 'id_address_delivery' => array('xlink_resource' => 'addresses'),
  103. 'id_address_invoice' => array('xlink_resource' => 'addresses'),
  104. 'id_currency' => array('xlink_resource' => 'currencies'),
  105. 'id_customer' => array('xlink_resource' => 'customers'),
  106. 'id_guest' => array('xlink_resource' => 'guests'),
  107. 'id_lang' => array('xlink_resource' => 'languages'),
  108. ),
  109. 'associations' => array(
  110. 'cart_rows' => array('resource' => 'cart_row', 'virtual_entity' => true, 'fields' => array(
  111. 'id_product' => array('required' => true, 'xlink_resource' => 'products'),
  112. 'id_product_attribute' => array('required' => true, 'xlink_resource' => 'combinations'),
  113. 'quantity' => array('required' => true),
  114. )
  115. ),
  116. ),
  117. );
  118. const ONLY_PRODUCTS = 1;
  119. const ONLY_DISCOUNTS = 2;
  120. const BOTH = 3;
  121. const BOTH_WITHOUT_SHIPPING = 4;
  122. const ONLY_SHIPPING = 5;
  123. const ONLY_WRAPPING = 6;
  124. const ONLY_PRODUCTS_WITHOUT_SHIPPING = 7;
  125. const ONLY_PHYSICAL_PRODUCTS_WITHOUT_SHIPPING = 8;
  126. public function __construct($id = null, $id_lang = null)
  127. {
  128. parent::__construct($id, $id_lang);
  129. if ($this->id_customer)
  130. {
  131. if (isset(Context::getContext()->customer) && Context::getContext()->customer->id == $this->id_customer)
  132. $customer = Context::getContext()->customer;
  133. else
  134. $customer = new Customer((int)$this->id_customer);
  135. if ((!$this->secure_key || $this->secure_key == '-1') && $customer->secure_key)
  136. {
  137. $this->secure_key = $customer->secure_key;
  138. $this->save();
  139. }
  140. }
  141. $this->_taxCalculationMethod = Group::getPriceDisplayMethod(Group::getCurrent()->id);
  142. }
  143. public function add($autodate = true, $null_values = false)
  144. {
  145. if (!$this->id_lang)
  146. $this->id_lang = Configuration::get('PS_LANG_DEFAULT');
  147. if (!$this->id_shop)
  148. $this->id_shop = Context::getContext()->shop->id;
  149. $return = parent::add($autodate);
  150. Hook::exec('actionCartSave');
  151. return $return;
  152. }
  153. public function update($null_values = false)
  154. {
  155. if (isset(self::$_nbProducts[$this->id]))
  156. unset(self::$_nbProducts[$this->id]);
  157. if (isset(self::$_totalWeight[$this->id]))
  158. unset(self::$_totalWeight[$this->id]);
  159. $this->_products = null;
  160. $return = parent::update();
  161. Hook::exec('actionCartSave');
  162. return $return;
  163. }
  164. /**
  165. * Update the address id of the cart
  166. *
  167. * @param int $id_address Current address id to change
  168. * @param int $id_address_new New address id
  169. */
  170. public function updateAddressId($id_address, $id_address_new)
  171. {
  172. $to_update = false;
  173. if (!isset($this->id_address_invoice) || $this->id_address_invoice == $id_address)
  174. {
  175. $to_update = true;
  176. $this->context->cart->id_address_invoice = $id_address_new;
  177. }
  178. if (!isset($this->id_address_delivery) || $this->id_address_delivery == $id_address)
  179. {
  180. $to_update = true;
  181. $this->id_address_delivery = $id_address_new;
  182. }
  183. if ($to_update)
  184. $this->update();
  185. $sql = 'UPDATE `'._DB_PREFIX_.'cart_product`
  186. SET `id_address_delivery` = '.(int)$id_address_new.'
  187. WHERE `id_cart` = '.(int)$this->id.'
  188. AND `id_address_delivery` = '.(int)$id_address;
  189. Db::getInstance()->execute($sql);
  190. $sql = 'UPDATE `'._DB_PREFIX_.'customization`
  191. SET `id_address_delivery` = '.(int)$id_address_new.'
  192. WHERE `id_cart` = '.(int)$this->id.'
  193. AND `id_address_delivery` = '.(int)$id_address;
  194. Db::getInstance()->execute($sql);
  195. }
  196. public function delete()
  197. {
  198. if ($this->OrderExists()) //NOT delete a cart which is associated with an order
  199. return false;
  200. $uploaded_files = Db::getInstance()->executeS('
  201. SELECT cd.`value`
  202. FROM `'._DB_PREFIX_.'customized_data` cd
  203. INNER JOIN `'._DB_PREFIX_.'customization` c ON (cd.`id_customization`= c.`id_customization`)
  204. WHERE cd.`type`= 0 AND c.`id_cart`='.(int)$this->id
  205. );
  206. foreach ($uploaded_files as $must_unlink)
  207. {
  208. unlink(_PS_UPLOAD_DIR_.$must_unlink['value'].'_small');
  209. unlink(_PS_UPLOAD_DIR_.$must_unlink['value']);
  210. }
  211. Db::getInstance()->execute('
  212. DELETE FROM `'._DB_PREFIX_.'customized_data`
  213. WHERE `id_customization` IN (
  214. SELECT `id_customization`
  215. FROM `'._DB_PREFIX_.'customization`
  216. WHERE `id_cart`='.(int)$this->id.'
  217. )'
  218. );
  219. Db::getInstance()->execute('
  220. DELETE FROM `'._DB_PREFIX_.'customization`
  221. WHERE `id_cart` = '.(int)$this->id
  222. );
  223. if (!Db::getInstance()->execute('DELETE FROM `'._DB_PREFIX_.'cart_cart_rule` WHERE `id_cart` = '.(int)$this->id)
  224. || !Db::getInstance()->execute('DELETE FROM `'._DB_PREFIX_.'cart_product` WHERE `id_cart` = '.(int)$this->id))
  225. return false;
  226. return parent::delete();
  227. }
  228. public static function getTaxesAverageUsed($id_cart)
  229. {
  230. $cart = new Cart((int)$id_cart);
  231. if (!Validate::isLoadedObject($cart))
  232. die(Tools::displayError());
  233. if (!Configuration::get('PS_TAX'))
  234. return 0;
  235. $products = $cart->getProducts();
  236. $total_products_moy = 0;
  237. $ratio_tax = 0;
  238. if (!count($products))
  239. return 0;
  240. foreach ($products as $product) // products refer to the cart details
  241. {
  242. if (Configuration::get('PS_TAX_ADDRESS_TYPE') == 'id_address_invoice')
  243. $address_id = (int)$cart->id_address_invoice;
  244. else
  245. $address_id = (int)$product['id_address_delivery']; // Get delivery address of the product from the cart
  246. if (!Address::addressExists($address_id))
  247. $address_id = null;
  248. $total_products_moy += $product['total_wt'];
  249. $ratio_tax += $product['total_wt'] * Tax::getProductTaxRate(
  250. (int)$product['id_product'],
  251. (int)$address_id
  252. );
  253. }
  254. if ($total_products_moy > 0)
  255. return $ratio_tax / $total_products_moy;
  256. return 0;
  257. }
  258. /**
  259. * @deprecated 1.5.0, use Cart->getCartRules()
  260. */
  261. public function getDiscounts($lite = false, $refresh = false)
  262. {
  263. Tools::displayAsDeprecated();
  264. return $this->getCartRules();
  265. }
  266. public function getCartRules($filter = CartRule::FILTER_ACTION_ALL)
  267. {
  268. // If the cart has not been saved, then there can't be any cart rule applied
  269. if (!CartRule::isFeatureActive() || !$this->id)
  270. return array();
  271. $cache_key = 'Cart::getCartRules'.$this->id.'-'.$filter;
  272. if (!Cache::isStored($cache_key))
  273. {
  274. $result = Db::getInstance()->executeS('
  275. SELECT *
  276. FROM `'._DB_PREFIX_.'cart_cart_rule` cd
  277. LEFT JOIN `'._DB_PREFIX_.'cart_rule` cr ON cd.`id_cart_rule` = cr.`id_cart_rule`
  278. LEFT JOIN `'._DB_PREFIX_.'cart_rule_lang` crl ON (
  279. cd.`id_cart_rule` = crl.`id_cart_rule`
  280. AND crl.id_lang = '.(int)$this->id_lang.'
  281. )
  282. WHERE `id_cart` = '.(int)$this->id.'
  283. '.($filter == CartRule::FILTER_ACTION_SHIPPING ? 'AND free_shipping = 1' : '').'
  284. '.($filter == CartRule::FILTER_ACTION_GIFT ? 'AND gift_product != 0' : '').'
  285. '.($filter == CartRule::FILTER_ACTION_REDUCTION ? 'AND (reduction_percent != 0 OR reduction_amount != 0)' : '')
  286. );
  287. Cache::store($cache_key, $result);
  288. }
  289. $result = Cache::retrieve($cache_key);
  290. // Define virtual context to prevent case where the cart is not the in the global context
  291. $virtual_context = Context::getContext()->cloneContext();
  292. $virtual_context->cart = $this;
  293. foreach ($result as &$row)
  294. {
  295. $row['obj'] = new CartRule($row['id_cart_rule'], (int)$this->id_lang);
  296. $row['value_real'] = $row['obj']->getContextualValue(true, $virtual_context, $filter);
  297. $row['value_tax_exc'] = $row['obj']->getContextualValue(false, $virtual_context, $filter);
  298. // Retro compatibility < 1.5.0.2
  299. $row['id_discount'] = $row['id_cart_rule'];
  300. $row['description'] = $row['name'];
  301. }
  302. return $result;
  303. }
  304. public function getDiscountsCustomer($id_cart_rule)
  305. {
  306. if (!CartRule::isFeatureActive())
  307. return 0;
  308. return Db::getInstance()->getValue('
  309. SELECT COUNT(*)
  310. FROM `'._DB_PREFIX_.'cart_cart_rule`
  311. WHERE `id_cart_rule` = '.(int)$id_cart_rule.' AND `id_cart` = '.(int)$this->id
  312. );
  313. }
  314. public function getLastProduct()
  315. {
  316. $sql = '
  317. SELECT `id_product`, `id_product_attribute`, id_shop
  318. FROM `'._DB_PREFIX_.'cart_product`
  319. WHERE `id_cart` = '.(int)$this->id.'
  320. ORDER BY `date_add` DESC';
  321. $result = Db::getInstance()->getRow($sql);
  322. if ($result && isset($result['id_product']) && $result['id_product'])
  323. foreach ($this->getProducts() as $product)
  324. if ($result['id_product'] == $product['id_product']
  325. && (
  326. !$result['id_product_attribute']
  327. || $result['id_product_attribute'] == $product['id_product_attribute']
  328. ))
  329. return $product;
  330. return false;
  331. }
  332. /**
  333. * Return cart products
  334. *
  335. * @result array Products
  336. */
  337. public function getProducts($refresh = false, $id_product = false, $id_country = null)
  338. {
  339. if (!$this->id)
  340. return array();
  341. // Product cache must be strictly compared to NULL, or else an empty cart will add dozens of queries
  342. if ($this->_products !== null && !$refresh)
  343. {
  344. // Return product row with specified ID if it exists
  345. if (is_int($id_product))
  346. {
  347. foreach ($this->_products as $product)
  348. if ($product['id_product'] == $id_product)
  349. return array($product);
  350. return array();
  351. }
  352. return $this->_products;
  353. }
  354. // Build query
  355. $sql = new DbQuery();
  356. // Build SELECT
  357. $sql->select('cp.`id_product_attribute`, cp.`id_product`, cp.`quantity` AS cart_quantity, cp.id_shop, pl.`name`, p.`is_virtual`,
  358. pl.`description_short`, pl.`available_now`, pl.`available_later`, p.`id_product`, product_shop.`id_category_default`, p.`id_supplier`,
  359. p.`id_manufacturer`, product_shop.`on_sale`, product_shop.`ecotax`, product_shop.`additional_shipping_cost`, product_shop.`available_for_order`, product_shop.`price`, p.`weight`,
  360. stock.`quantity` quantity_available, p.`width`, p.`height`, p.`depth`, stock.`out_of_stock`, product_shop.`active`, p.`date_add`,
  361. p.`date_upd`, IFNULL(stock.quantity, 0) as quantity, pl.`link_rewrite`, cl.`link_rewrite` AS category,
  362. CONCAT(cp.`id_product`, IFNULL(cp.`id_product_attribute`, 0), IFNULL(cp.`id_address_delivery`, 0)) AS unique_id, cp.id_address_delivery,
  363. product_shop.`wholesale_price`, product_shop.advanced_stock_management, ps.product_supplier_reference supplier_reference');
  364. // Build FROM
  365. $sql->from('cart_product', 'cp');
  366. // Build JOIN
  367. $sql->leftJoin('product', 'p', 'p.`id_product` = cp.`id_product`');
  368. $sql->innerJoin('product_shop', 'product_shop', '(product_shop.id_shop=cp.id_shop AND product_shop.id_product = p.id_product)');
  369. $sql->leftJoin('product_lang', 'pl', '
  370. p.`id_product` = pl.`id_product`
  371. AND pl.`id_lang` = '.(int)$this->id_lang.Shop::addSqlRestrictionOnLang('pl', 'cp.id_shop')
  372. );
  373. $sql->leftJoin('category_lang', 'cl', '
  374. product_shop.`id_category_default` = cl.`id_category`
  375. AND cl.`id_lang` = '.(int)$this->id_lang.Shop::addSqlRestrictionOnLang('cl', 'cp.id_shop')
  376. );
  377. $sql->leftJoin('product_supplier', 'ps', 'ps.id_product=cp.id_product AND ps.id_product_attribute=cp.id_product_attribute AND ps.id_supplier=p.id_supplier');
  378. // @todo test if everything is ok, then refactorise call of this method
  379. $sql->join(Product::sqlStock('cp', 'cp'));
  380. // Build WHERE clauses
  381. $sql->where('cp.`id_cart` = '.(int)$this->id);
  382. if ($id_product)
  383. $sql->where('cp.`id_product` = '.(int)$id_product);
  384. $sql->where('p.`id_product` IS NOT NULL');
  385. // Build GROUP BY
  386. $sql->groupBy('unique_id');
  387. // Build ORDER BY
  388. $sql->orderBy('p.id_product, cp.id_product_attribute, cp.date_add ASC');
  389. if (Customization::isFeatureActive())
  390. {
  391. $sql->select('cu.`id_customization`, cu.`quantity` AS customization_quantity');
  392. $sql->leftJoin('customization', 'cu',
  393. 'p.`id_product` = cu.`id_product` AND cp.`id_product_attribute` = cu.id_product_attribute AND cu.id_cart='.(int)$this->id);
  394. }
  395. else
  396. $sql->select('NULL AS customization_quantity, NULL AS id_customization');
  397. if (Combination::isFeatureActive())
  398. {
  399. $sql->select('
  400. product_attribute_shop.`price` AS price_attribute, product_attribute_shop.`ecotax` AS ecotax_attr,
  401. IF (IFNULL(pa.`reference`, \'\') = \'\', p.`reference`, pa.`reference`) AS reference,
  402. (p.`weight`+ pa.`weight`) weight_attribute,
  403. IF (IFNULL(pa.`ean13`, \'\') = \'\', p.`ean13`, pa.`ean13`) AS ean13,
  404. IF (IFNULL(pa.`upc`, \'\') = \'\', p.`upc`, pa.`upc`) AS upc,
  405. pai.`id_image` as pai_id_image, il.`legend` as pai_legend,
  406. IFNULL(product_attribute_shop.`minimal_quantity`, product_shop.`minimal_quantity`) as minimal_quantity
  407. ');
  408. $sql->leftJoin('product_attribute', 'pa', 'pa.`id_product_attribute` = cp.`id_product_attribute`');
  409. $sql->leftJoin('product_attribute_shop', 'product_attribute_shop', '(product_attribute_shop.id_shop=cp.id_shop AND product_attribute_shop.id_product_attribute = pa.id_product_attribute)');
  410. $sql->leftJoin('product_attribute_image', 'pai', 'pai.`id_product_attribute` = pa.`id_product_attribute`');
  411. $sql->leftJoin('image_lang', 'il', 'il.id_image = pai.id_image AND il.id_lang = '.(int)$this->id_lang);
  412. }
  413. else
  414. $sql->select(
  415. 'p.`reference` AS reference, p.`ean13`,
  416. p.`upc` AS upc, product_shop.`minimal_quantity` AS minimal_quantity'
  417. );
  418. $result = Db::getInstance()->executeS($sql);
  419. // Reset the cache before the following return, or else an empty cart will add dozens of queries
  420. $products_ids = array();
  421. $pa_ids = array();
  422. if ($result)
  423. foreach ($result as $row)
  424. {
  425. $products_ids[] = $row['id_product'];
  426. $pa_ids[] = $row['id_product_attribute'];
  427. }
  428. // Thus you can avoid one query per product, because there will be only one query for all the products of the cart
  429. Product::cacheProductsFeatures($products_ids);
  430. Cart::cacheSomeAttributesLists($pa_ids, $this->id_lang);
  431. $this->_products = array();
  432. if (empty($result))
  433. return array();
  434. $cart_shop_context = Context::getContext()->cloneContext();
  435. foreach ($result as &$row)
  436. {
  437. if (isset($row['ecotax_attr']) && $row['ecotax_attr'] > 0)
  438. $row['ecotax'] = (float)$row['ecotax_attr'];
  439. $row['stock_quantity'] = (int)$row['quantity'];
  440. // for compatibility with 1.2 themes
  441. $row['quantity'] = (int)$row['cart_quantity'];
  442. if (isset($row['id_product_attribute']) && (int)$row['id_product_attribute'] && isset($row['weight_attribute']))
  443. $row['weight'] = (float)$row['weight_attribute'];
  444. if (Configuration::get('PS_TAX_ADDRESS_TYPE') == 'id_address_invoice')
  445. $address_id = (int)$this->id_address_invoice;
  446. else
  447. $address_id = (int)$row['id_address_delivery'];
  448. if (!Address::addressExists($address_id))
  449. $address_id = null;
  450. if ($cart_shop_context->shop->id != $row['id_shop'])
  451. $cart_shop_context->shop = new Shop((int)$row['id_shop']);
  452. if ($this->_taxCalculationMethod == PS_TAX_EXC)
  453. {
  454. $row['price'] = Product::getPriceStatic(
  455. (int)$row['id_product'],
  456. false,
  457. isset($row['id_product_attribute']) ? (int)$row['id_product_attribute'] : null,
  458. 2,
  459. null,
  460. false,
  461. true,
  462. (int)$row['cart_quantity'],
  463. false,
  464. ((int)$this->id_customer ? (int)$this->id_customer : null),
  465. (int)$this->id,
  466. ((int)$address_id ? (int)$address_id : null),
  467. $specific_price_output,
  468. true,
  469. true,
  470. $cart_shop_context
  471. ); // Here taxes are computed only once the quantity has been applied to the product price
  472. $row['price_wt'] = Product::getPriceStatic(
  473. (int)$row['id_product'],
  474. true,
  475. isset($row['id_product_attribute']) ? (int)$row['id_product_attribute'] : null,
  476. 2,
  477. null,
  478. false,
  479. true,
  480. (int)$row['cart_quantity'],
  481. false,
  482. ((int)$this->id_customer ? (int)$this->id_customer : null),
  483. (int)$this->id,
  484. ((int)$address_id ? (int)$address_id : null),
  485. $null,
  486. true,
  487. true,
  488. $cart_shop_context
  489. );
  490. $tax_rate = Tax::getProductTaxRate((int)$row['id_product'], (int)$address_id);
  491. $row['total_wt'] = Tools::ps_round($row['price'] * (float)$row['cart_quantity'] * (1 + (float)$tax_rate / 100), 2);
  492. $row['total'] = $row['price'] * (int)$row['cart_quantity'];
  493. }
  494. else
  495. {
  496. $row['price'] = Product::getPriceStatic(
  497. (int)$row['id_product'],
  498. false,
  499. (int)$row['id_product_attribute'],
  500. 2,
  501. null,
  502. false,
  503. true,
  504. $row['cart_quantity'],
  505. false,
  506. ((int)$this->id_customer ? (int)$this->id_customer : null),
  507. (int)$this->id,
  508. ((int)$address_id ? (int)$address_id : null),
  509. $specific_price_output,
  510. true,
  511. true,
  512. $cart_shop_context
  513. );
  514. $row['price_wt'] = Product::getPriceStatic(
  515. (int)$row['id_product'],
  516. true,
  517. (int)$row['id_product_attribute'],
  518. 2,
  519. null,
  520. false,
  521. true,
  522. $row['cart_quantity'],
  523. false,
  524. ((int)$this->id_customer ? (int)$this->id_customer : null),
  525. (int)$this->id,
  526. ((int)$address_id ? (int)$address_id : null),
  527. $null,
  528. true,
  529. true,
  530. $cart_shop_context
  531. );
  532. // In case when you use QuantityDiscount, getPriceStatic() can be return more of 2 decimals
  533. $row['price_wt'] = Tools::ps_round($row['price_wt'], 2);
  534. $row['total_wt'] = $row['price_wt'] * (int)$row['cart_quantity'];
  535. $row['total'] = Tools::ps_round($row['price'] * (int)$row['cart_quantity'], 2);
  536. }
  537. if (!isset($row['pai_id_image']) || $row['pai_id_image'] == 0)
  538. {
  539. $row2 = Db::getInstance()->getRow('
  540. SELECT image_shop.`id_image` id_image, il.`legend`
  541. FROM `'._DB_PREFIX_.'image` i'.
  542. Shop::addSqlAssociation('image', 'i', false, 'image_shop.cover=1').'
  543. LEFT JOIN `'._DB_PREFIX_.'image_lang` il ON (image_shop.`id_image` = il.`id_image` AND il.`id_lang` = '.(int)$this->id_lang.')
  544. WHERE i.`id_product` = '.(int)$row['id_product'].' AND image_shop.`cover` = 1'
  545. );
  546. if (!$row2)
  547. $row2 = array('id_image' => false, 'legend' => false);
  548. else
  549. $row = array_merge($row, $row2);
  550. }
  551. else
  552. {
  553. $row['id_image'] = $row['pai_id_image'];
  554. $row['legend'] = $row['pai_legend'];
  555. }
  556. $row['reduction_applies'] = ($specific_price_output && (float)$specific_price_output['reduction']);
  557. $row['quantity_discount_applies'] = ($specific_price_output && $row['cart_quantity'] >= (int)$specific_price_output['from_quantity']);
  558. $row['id_image'] = Product::defineProductImage($row, $this->id_lang);
  559. $row['allow_oosp'] = Product::isAvailableWhenOutOfStock($row['out_of_stock']);
  560. $row['features'] = Product::getFeaturesStatic((int)$row['id_product']);
  561. if (array_key_exists($row['id_product_attribute'].'-'.$this->id_lang, self::$_attributesLists))
  562. $row = array_merge($row, self::$_attributesLists[$row['id_product_attribute'].'-'.$this->id_lang]);
  563. $row = Product::getTaxesInformations($row, $cart_shop_context);
  564. $this->_products[] = $row;
  565. }
  566. return $this->_products;
  567. }
  568. public static function cacheSomeAttributesLists($ipa_list, $id_lang)
  569. {
  570. if (!Combination::isFeatureActive())
  571. return;
  572. $pa_implode = array();
  573. foreach ($ipa_list as $id_product_attribute)
  574. if ((int)$id_product_attribute && !array_key_exists($id_product_attribute.'-'.$id_lang, self::$_attributesLists))
  575. {
  576. $pa_implode[] = (int)$id_product_attribute;
  577. self::$_attributesLists[(int)$id_product_attribute.'-'.$id_lang] = array('attributes' => '', 'attributes_small' => '');
  578. }
  579. if (!count($pa_implode))
  580. return;
  581. $result = Db::getInstance()->executeS('
  582. SELECT pac.`id_product_attribute`, agl.`public_name` AS public_group_name, al.`name` AS attribute_name
  583. FROM `'._DB_PREFIX_.'product_attribute_combination` pac
  584. LEFT JOIN `'._DB_PREFIX_.'attribute` a ON a.`id_attribute` = pac.`id_attribute`
  585. LEFT JOIN `'._DB_PREFIX_.'attribute_group` ag ON ag.`id_attribute_group` = a.`id_attribute_group`
  586. LEFT JOIN `'._DB_PREFIX_.'attribute_lang` al ON (
  587. a.`id_attribute` = al.`id_attribute`
  588. AND al.`id_lang` = '.(int)$id_lang.'
  589. )
  590. LEFT JOIN `'._DB_PREFIX_.'attribute_group_lang` agl ON (
  591. ag.`id_attribute_group` = agl.`id_attribute_group`
  592. AND agl.`id_lang` = '.(int)$id_lang.'
  593. )
  594. WHERE pac.`id_product_attribute` IN ('.implode($pa_implode, ',').')
  595. ORDER BY agl.`public_name` ASC'
  596. );
  597. foreach ($result as $row)
  598. {
  599. self::$_attributesLists[$row['id_product_attribute'].'-'.$id_lang]['attributes'] .= $row['public_group_name'].' : '.$row['attribute_name'].', ';
  600. self::$_attributesLists[$row['id_product_attribute'].'-'.$id_lang]['attributes_small'] .= $row['attribute_name'].', ';
  601. }
  602. foreach ($pa_implode as $id_product_attribute)
  603. {
  604. self::$_attributesLists[$id_product_attribute.'-'.$id_lang]['attributes'] = rtrim(
  605. self::$_attributesLists[$id_product_attribute.'-'.$id_lang]['attributes'],
  606. ', '
  607. );
  608. self::$_attributesLists[$id_product_attribute.'-'.$id_lang]['attributes_small'] = rtrim(
  609. self::$_attributesLists[$id_product_attribute.'-'.$id_lang]['attributes_small'],
  610. ', '
  611. );
  612. }
  613. }
  614. /**
  615. * Return cart products quantity
  616. *
  617. * @result integer Products quantity
  618. */
  619. public function nbProducts()
  620. {
  621. if (!$this->id)
  622. return 0;
  623. return Cart::getNbProducts($this->id);
  624. }
  625. public static function getNbProducts($id)
  626. {
  627. // Must be strictly compared to NULL, or else an empty cart will bypass the cache and add dozens of queries
  628. if (isset(self::$_nbProducts[$id]) && self::$_nbProducts[$id] !== null)
  629. return self::$_nbProducts[$id];
  630. self::$_nbProducts[$id] = (int)Db::getInstance()->getValue('
  631. SELECT SUM(`quantity`)
  632. FROM `'._DB_PREFIX_.'cart_product`
  633. WHERE `id_cart` = '.(int)$id
  634. );
  635. return self::$_nbProducts[$id];
  636. }
  637. /**
  638. * @deprecated 1.5.0, use Cart->addCartRule()
  639. */
  640. public function addDiscount($id_cart_rule)
  641. {
  642. Tools::displayAsDeprecated();
  643. return $this->addCartRule($id_cart_rule);
  644. }
  645. public function addCartRule($id_cart_rule)
  646. {
  647. // You can't add a cart rule that does not exist
  648. $cartRule = new CartRule($id_cart_rule, Context::getContext()->language->id);
  649. if (!Validate::isLoadedObject($cartRule))
  650. return false;
  651. // Add the cart rule to the cart
  652. if (!Db::getInstance()->insert('cart_cart_rule', array(
  653. 'id_cart_rule' => (int)$id_cart_rule,
  654. 'id_cart' => (int)$this->id
  655. )))
  656. return false;
  657. Cache::clean('Cart::getCartRules'.$this->id.'-'.CartRule::FILTER_ACTION_ALL);
  658. Cache::clean('Cart::getCartRules'.$this->id.'-'.CartRule::FILTER_ACTION_SHIPPING);
  659. Cache::clean('Cart::getCartRules'.$this->id.'-'.CartRule::FILTER_ACTION_REDUCTION);
  660. Cache::clean('Cart::getCartRules'.$this->id.'-'.CartRule::FILTER_ACTION_GIFT);
  661. if ((int)$cartRule->gift_product)
  662. $this->updateQty(1, $cartRule->gift_product, $cartRule->gift_product_attribute, false, 'up', 0, null, false);
  663. return true;
  664. }
  665. public function containsProduct($id_product, $id_product_attribute = 0, $id_customization = false, $id_address_delivery = 0)
  666. {
  667. $sql = 'SELECT cp.`quantity` FROM `'._DB_PREFIX_.'cart_product` cp';
  668. if ($id_customization)
  669. $sql .= '
  670. LEFT JOIN `'._DB_PREFIX_.'customization` c ON (
  671. c.`id_product` = cp.`id_product`
  672. AND c.`id_product_attribute` = cp.`id_product_attribute`
  673. )';
  674. $sql .= '
  675. WHERE cp.`id_product` = '.(int)$id_product.'
  676. AND cp.`id_product_attribute` = '.(int)$id_product_attribute.'
  677. AND cp.`id_cart` = '.(int)$this->id;
  678. if (Configuration::get('PS_ALLOW_MULTISHIPPING') && $this->isMultiAddressDelivery())
  679. $sql .= ' AND cp.`id_address_delivery` = '.(int)$id_address_delivery;
  680. if ($id_customization)
  681. $sql .= ' AND c.`id_customization` = '.(int)$id_customization;
  682. return Db::getInstance()->getRow($sql);
  683. }
  684. /**
  685. * Update product quantity
  686. *
  687. * @param integer $quantity Quantity to add (or substract)
  688. * @param integer $id_product Product ID
  689. * @param integer $id_product_attribute Attribute ID if needed
  690. * @param string $operator Indicate if quantity must be increased or decreased
  691. */
  692. public function updateQty($quantity, $id_product, $id_product_attribute = null, $id_customization = false,
  693. $operator = 'up', $id_address_delivery = 0, Shop $shop = null, $auto_add_cart_rule = true)
  694. {
  695. if (!$shop)
  696. $shop = Context::getContext()->shop;
  697. if (Context::getContext()->customer->id)
  698. {
  699. if ($id_address_delivery == 0 && (int)$this->id_address_delivery) // The $id_address_delivery is null, use the cart delivery address
  700. $id_address_delivery = $this->id_address_delivery;
  701. elseif ($id_address_delivery == 0) // The $id_address_delivery is null, get the default customer address
  702. $id_address_delivery = (int)Address::getFirstCustomerAddressId((int)Context::getContext()->customer->id);
  703. elseif (!Customer::customerHasAddress(Context::getContext()->customer->id, $id_address_delivery)) // The $id_address_delivery must be linked with customer
  704. $id_address_delivery = 0;
  705. }
  706. $quantity = (int)$quantity;
  707. $id_product = (int)$id_product;
  708. $id_product_attribute = (int)$id_product_attribute;
  709. $product = new Product($id_product, false, Configuration::get('PS_LANG_DEFAULT'), $shop->id);
  710. if ($id_product_attribute)
  711. {
  712. $combination = new Combination((int)$id_product_attribute);
  713. if ($combination->id_product != $id_product)
  714. return false;
  715. }
  716. /* If we have a product combination, the minimal quantity is set with the one of this combination */
  717. if (!empty($id_product_attribute))
  718. $minimal_quantity = (int)Attribute::getAttributeMinimalQty($id_product_attribute);
  719. else
  720. $minimal_quantity = (int)$product->minimal_quantity;
  721. if (!Validate::isLoadedObject($product))
  722. die(Tools::displayError());
  723. if (isset(self::$_nbProducts[$this->id]))
  724. unset(self::$_nbProducts[$this->id]);
  725. if (isset(self::$_totalWeight[$this->id]))
  726. unset(self::$_totalWeight[$this->id]);
  727. if ((int)$quantity <= 0)
  728. return $this->deleteProduct($id_product, $id_product_attribute, (int)$id_customization);
  729. elseif (!$product->available_for_order || Configuration::get('PS_CATALOG_MODE'))
  730. return false;
  731. else
  732. {
  733. /* Check if the product is already in the cart */
  734. $result = $this->containsProduct($id_product, $id_product_attribute, (int)$id_customization, (int)$id_address_delivery);
  735. /* Update quantity if product already exist */
  736. if ($result)
  737. {
  738. if ($operator == 'up')
  739. {
  740. $sql = 'SELECT stock.out_of_stock, IFNULL(stock.quantity, 0) as quantity
  741. FROM '._DB_PREFIX_.'product p
  742. '.Product::sqlStock('p', $id_product_attribute, true, $shop).'
  743. WHERE p.id_product = '.$id_product;
  744. $result2 = Db::getInstance()->getRow($sql);
  745. $product_qty = (int)$result2['quantity'];
  746. // Quantity for product pack
  747. if (Pack::isPack($id_product))
  748. $product_qty = Pack::getQuantity($id_product, $id_product_attribute);
  749. $new_qty = (int)$result['quantity'] + (int)$quantity;
  750. $qty = '+ '.(int)$quantity;
  751. if (!Product::isAvailableWhenOutOfStock((int)$result2['out_of_stock']))
  752. if ($new_qty > $product_qty)
  753. return false;
  754. }
  755. else if ($operator == 'down')
  756. {
  757. $qty = '- '.(int)$quantity;
  758. $new_qty = (int)$result['quantity'] - (int)$quantity;
  759. if ($new_qty < $minimal_quantity && $minimal_quantity > 1)
  760. return -1;
  761. }
  762. else
  763. return false;
  764. /* Delete product from cart */
  765. if ($new_qty <= 0)
  766. return $this->deleteProduct((int)$id_product, (int)$id_product_attribute, (int)$id_customization);
  767. else if ($new_qty < $minimal_quantity)
  768. return -1;
  769. else
  770. Db::getInstance()->execute('
  771. UPDATE `'._DB_PREFIX_.'cart_product`
  772. SET `quantity` = `quantity` '.$qty.', `date_add` = NOW()
  773. WHERE `id_product` = '.(int)$id_product.
  774. (!empty($id_product_attribute) ? ' AND `id_product_attribute` = '.(int)$id_product_attribute : '').'
  775. AND `id_cart` = '.(int)$this->id.(Configuration::get('PS_ALLOW_MULTISHIPPING') && $this->isMultiAddressDelivery() ? ' AND `id_address_delivery` = '.(int)$id_address_delivery : '').'
  776. LIMIT 1'
  777. );
  778. }
  779. /* Add product to the cart */
  780. elseif ($operator == 'up')
  781. {
  782. $sql = 'SELECT stock.out_of_stock, IFNULL(stock.quantity, 0) as quantity
  783. FROM '._DB_PREFIX_.'product p
  784. '.Product::sqlStock('p', $id_product_attribute, true, $shop).'
  785. WHERE p.id_product = '.$id_product;
  786. $result2 = Db::getInstance()->getRow($sql);
  787. // Quantity for product pack
  788. if (Pack::isPack($id_product))
  789. $result2['quantity'] = Pack::getQuantity($id_product, $id_product_attribute);
  790. if (!Product::isAvailableWhenOutOfStock((int)$result2['out_of_stock']))
  791. if ((int)$quantity > $result2['quantity'])
  792. return false;
  793. if ((int)$quantity < $minimal_quantity)
  794. return -1;
  795. $result_add = Db::getInstance()->insert('cart_product', array(
  796. 'id_product' => (int)$id_product,
  797. 'id_product_attribute' => (int)$id_product_attribute,
  798. 'id_cart' => (int)$this->id,
  799. 'id_address_delivery' => (int)$id_address_delivery,
  800. 'id_shop' => $shop->id,
  801. 'quantity' => (int)$quantity,
  802. 'date_add' => date('Y-m-d H:i:s')
  803. ));
  804. if (!$result_add)
  805. return false;
  806. }
  807. }
  808. // refresh cache of self::_products
  809. $this->_products = $this->getProducts(true);
  810. $this->update(true);
  811. $context = Context::getContext()->cloneContext();
  812. $context->cart = $this;
  813. Cache::clean('getContextualValue_*');
  814. if ($auto_add_cart_rule)
  815. CartRule::autoAddToCart($context);
  816. if ($product->customizable)
  817. return $this->_updateCustomizationQuantity((int)$quantity, (int)$id_customization, (int)$id_product, (int)$id_product_attribute, (int)$id_address_delivery, $operator);
  818. else
  819. return true;
  820. }
  821. /*
  822. ** Customization management
  823. */
  824. protected function _updateCustomizationQuantity($quantity, $id_customization, $id_product, $id_product_attribute, $id_address_delivery, $operator = 'up')
  825. {
  826. // Link customization to product combination when it is first added to cart
  827. if (empty($id_customization))
  828. {
  829. $customization = $this->getProductCustomization($id_product, null, true);
  830. foreach ($customization as $field)
  831. {
  832. if ($field['quantity'] == 0)
  833. {
  834. Db::getInstance()->execute('
  835. UPDATE `'._DB_PREFIX_.'customization`
  836. SET `quantity` = '.(int)$quantity.',
  837. `id_product_attribute` = '.(int)$id_product_attribute.',
  838. `id_address_delivery` = '.(int)$id_address_delivery.',
  839. `in_cart` = 1
  840. WHERE `id_customization` = '.(int)$field['id_customization']);
  841. }
  842. }
  843. }
  844. /* Deletion */
  845. if (!empty($id_customization) && (int)$quantity < 1)
  846. return $this->_deleteCustomization((int)$id_customization, (int)$id_product, (int)$id_product_attribute);
  847. /* Quantity update */
  848. if (!empty($id_customization))
  849. {
  850. $result = Db::getInstance()->getRow('SELECT `quantity` FROM `'._DB_PREFIX_.'customization` WHERE `id_customization` = '.(int)$id_customization);
  851. if ($result && Db::getInstance()->NumRows())
  852. {
  853. if ($operator == 'down' && (int)$result['quantity'] - (int)$quantity < 1)
  854. return Db::getInstance()->execute('DELETE FROM `'._DB_PREFIX_.'customization` WHERE `id_customization` = '.(int)$id_customization);
  855. return Db::getInstance()->execute('
  856. UPDATE `'._DB_PREFIX_.'customization`
  857. SET
  858. `quantity` = `quantity` '.($operator == 'up' ? '+ ' : '- ').(int)$quantity.',
  859. `id_address_delivery` = '.(int)$id_address_delivery.'
  860. WHERE `id_customization` = '.(int)$id_customization);
  861. }
  862. else
  863. Db::getInstance()->execute('
  864. UPDATE `'._DB_PREFIX_.'customization`
  865. SET `id_address_delivery` = '.(int)$id_address_delivery.'
  866. WHERE `id_customization` = '.(int)$id_customization);
  867. }
  868. // refresh cache of self::_products
  869. $this->_products = $this->getProducts(true);
  870. $this->update(true);
  871. return true;
  872. }
  873. /**
  874. * Add customization item to database
  875. *
  876. * @param int $id_product
  877. * @param int $id_product_attribute
  878. * @param int $index
  879. * @param int $type
  880. * @param string $field
  881. * @param int $quantity
  882. * @return boolean success
  883. */
  884. public function _addCustomization($id_product, $id_product_attribute, $index, $type, $field, $quantity)
  885. {
  886. $exising_customization = Db::getInstance()->executeS('
  887. SELECT cu.`id_customization`, cd.`index`, cd.`value`, cd.`type` FROM `'._DB_PREFIX_.'customization` cu
  888. LEFT JOIN `'._DB_PREFIX_.'customized_data` cd
  889. ON cu.`id_customization` = cd.`id_customization`
  890. WHERE cu.id_cart = '.(int)$this->id.'
  891. AND cu.id_product = '.(int)$id_product.'
  892. AND in_cart = 0'
  893. );
  894. if ($exising_customization)
  895. {
  896. // If the customization field is alreay filled, delete it
  897. foreach ($exising_customization as $customization)
  898. {
  899. if ($customization['type'] == $type && $customization['index'] == $index)
  900. {
  901. Db::getInstance()->execute('
  902. DELETE FROM `'._DB_PREFIX_.'customized_data`
  903. WHERE id_customization = '.(int)$customization['id_customization'].'
  904. AND type = '.(int)$customization['type'].'
  905. AND `index` = '.(int)$customization['index']);
  906. if ($type == Product::CUSTOMIZE_FILE)
  907. {
  908. @unlink(_PS_UPLOAD_DIR_.$customization['value']);
  909. @unlink(_PS_UPLOAD_DIR_.$customization['value'].'_small');
  910. }
  911. break;
  912. }
  913. }
  914. $id_customization = $exising_customization[0]['id_customization'];
  915. }
  916. else
  917. {
  918. Db::getInstance()->execute(
  919. 'INSERT INTO `'._DB_PREFIX_.'customization` (`id_cart`, `id_product`, `id_product_attribute`, `quantity`)
  920. VALUES ('.(int)$this->id.', '.(int)$id_product.', '.(int)$id_product_attribute.', '.(int)$quantity.')'
  921. );
  922. $id_customization = Db::getInstance()->Insert_ID();
  923. }
  924. $query = 'INSERT INTO `'._DB_PREFIX_.'customized_data` (`id_customization`, `type`, `index`, `value`)
  925. VALUES ('.(int)$id_customization.', '.(int)$type.', '.(int)$index.', \''.pSql($field).'\')';
  926. if (!Db::getInstance()->execute($query))
  927. return false;
  928. return true;
  929. }
  930. /**
  931. * Check if order has already been placed
  932. *
  933. * @return boolean result
  934. */
  935. public function orderExists()
  936. {
  937. return (bool)Db::getInstance()->getValue('SELECT count(*) FROM `'._DB_PREFIX_.'orders` WHERE `id_cart` = '.(int)$this->id);
  938. }
  939. /**
  940. * @deprecated 1.5.0, use Cart->removeCartRule()
  941. */
  942. public function deleteDiscount($id_cart_rule)
  943. {
  944. Tools::displayAsDeprecated();
  945. return $this->removeCartRule($id_cart_rule);
  946. }
  947. public function removeCartRule($id_cart_rule)
  948. {
  949. Cache::clean('Cart::getCartRules'.$this->id.'-'.CartRule::FILTER_ACTION_ALL);
  950. Cache::clean('Cart::getCartRules'.$this->id.'-'.CartRule::FILTER_ACTION_SHIPPING);
  951. Cache::clean('Cart::getCartRules'.$this->id.'-'.CartRule::FILTER_ACTION_REDUCTION);
  952. Cache::clean('Cart::getCartRules'.$this->id.'-'.CartRule::FILTER_ACTION_GIFT);
  953. $result = Db::getInstance()->execute('
  954. DELETE FROM `'._DB_PREFIX_.'cart_cart_rule`
  955. WHERE `id_cart_rule` = '.(int)$id_cart_rule.'
  956. AND `id_cart` = '.(int)$this->id.'
  957. LIMIT 1');
  958. $cart_rule = new CartRule($id_cart_rule, Configuration::get('PS_LANG_DEFAULT'));
  959. if ((int)$cart_rule->gift_product)
  960. $this->updateQty(1, $cart_rule->gift_product, $cart_rule->gift_product_attribute, null, 'down', 0, null, false);
  961. return $result;
  962. }
  963. /**
  964. * Delete a product from the cart
  965. *
  966. * @param integer $id_product Product ID
  967. * @param integer $id_product_attribute Attribute ID if needed
  968. * @param integer $id_customization Customization id
  969. * @return boolean result
  970. */
  971. public function deleteProduct($id_product, $id_product_attribute = null, $id_customization = null, $id_address_delivery = 0)
  972. {
  973. if (isset(self::$_nbProducts[$this->id]))
  974. unset(self::$_nbProducts[$this->id]);
  975. if (isset(self::$_totalWeight[$this->id]))
  976. unset(self::$_totalWeight[$this->id]);
  977. if ((int)$id_customization)
  978. {
  979. $product_total_quantity = (int)Db::getInstance()->getValue(
  980. 'SELECT `quantity`
  981. FROM `'._DB_PREFIX_.'cart_product`
  982. WHERE `id_product` = '.(int)$id_product.'
  983. AND `id_cart` = '.(int)$this->id.'
  984. AND `id_product_attribute` = '.(int)$id_product_attribute);
  985. $customization_quantity = (int)Db::getInstance()->getValue('
  986. SELECT `quantity`
  987. FROM `'._DB_PREFIX_.'customization`
  988. WHERE `id_cart` = '.(int)$this->id.'
  989. AND `id_product` = '.(int)$id_product.'
  990. AND `id_product_attribute` = '.(int)$id_product_attribute.'
  991. '.((int)$id_address_delivery ? 'AND `id_address_delivery` = '.(int)$id_address_delivery : ''));
  992. if (!$this->_deleteCustomization((int)$id_customization, (int)$id_product, (int)$id_product_attribute, (int)$id_address_delivery))
  993. return false;
  994. // refresh cache of self::_products
  995. $this->_products = $this->getProducts(true);
  996. return ($customization_quantity == $product_total_quantity && $this->deleteProduct((int)$id_product, (int)$id_product_attribute, null, (int)$id_address_delivery));
  997. }
  998. /* Get customization quantity */
  999. $result = Db::getInstance()->getRow('
  1000. SELECT SUM(`quantity`) AS \'quantity\'
  1001. FROM `'._DB_PREFIX_.'customization`
  1002. WHERE `id_cart` = '.(int)$this->id.'
  1003. AND `id_product` = '.(int)$id_product.'
  1004. AND `id_product_attribute` = '.(int)$id_product_attribute);
  1005. if ($result === false)
  1006. return false;
  1007. /* If the product still possesses customization it does not have to be deleted */
  1008. if (Db::getInstance()->NumRows() && (int)$result['quantity'])
  1009. return Db::getInstance()->execute('
  1010. UPDATE `'._DB_PREFIX_.'cart_product`
  1011. SET `quantity` = '.(int)$result['quantity'].'
  1012. WHERE `id_cart` = '.(int)$this->id.'
  1013. AND `id_product` = '.(int)$id_product.
  1014. ($id_product_attribute != null ? ' AND `id_product_attribute` = '.(int)$id_product_attribute : '')
  1015. );
  1016. /* Product deletion */
  1017. $result = Db::getInstance()->execute('
  1018. DELETE FROM `'._DB_PREFIX_.'cart_product`
  1019. WHERE `id_product` = '.(int)$id_product.'
  1020. '.(!is_null($id_product_attribute) ? ' AND `id_product_attribute` = '.(int)$id_product_attribute : '').'
  1021. AND `id_cart` = '.(int)$this->id.'
  1022. '.((int)$id_address_delivery ? 'AND `id_address_delivery` = '.(int)$id_address_delivery : ''));
  1023. if ($result)
  1024. {
  1025. $return = $this->update(true);
  1026. // refresh cache of self::_products
  1027. $this->_products = $this->getProducts(true);
  1028. CartRule::autoRemoveFromCart();
  1029. CartRule::autoAddToCart();
  1030. return $return;
  1031. }
  1032. return false;
  1033. }
  1034. /**
  1035. * Delete a customization from the cart. If customization is a Picture,
  1036. * then the image is also deleted
  1037. *
  1038. * @param integer $id_customization
  1039. * @return boolean result
  1040. */
  1041. protected function _deleteCustomization($id_customization, $id_product, $id_product_attribute, $id_address_delivery = 0)
  1042. {
  1043. $result = true;
  1044. $customization = Db::getInstance()->getRow('SELECT *
  1045. FROM `'._DB_PREFIX_.'customization`
  1046. WHERE `id_customization` = '.(int)$id_customization);
  1047. if ($customization)
  1048. {
  1049. $cust_data = Db::getInstance()->getRow('SELECT *
  1050. FROM `'._DB_PREFIX_.'customized_data`
  1051. WHERE `id_customization` = '.(int)$id_customization);
  1052. // Delete customization picture if necessary
  1053. if (isset($cust_data['type']) && $cust_data['type'] == 0)
  1054. $result &= (@unlink(_PS_UPLOAD_DIR_.$cust_data['value']) && @unlink(_PS_UPLOAD_DIR_.$cust_data['value'].'_small'));
  1055. $result &= Db::getInstance()->execute(
  1056. 'DELETE FROM `'._DB_PREFIX_.'customized_data`
  1057. WHERE `id_customization` = '.(int)$id_customization
  1058. );
  1059. if ($result)
  1060. $result &= Db::getInstance()->execute(
  1061. 'UPDATE `'._DB_PREFIX_.'cart_product`
  1062. SET `quantity` = `quantity` - '.(int)$customization['quantity'].'
  1063. WHERE `id_cart` = '.(int)$this->id.'
  1064. AND `id_product` = '.(int)$id_product.
  1065. ((int)$id_product_attribute ? ' AND `id_product_attribute` = '.(int)$id_product_attribute : '').'
  1066. AND `id_address_delivery` = '.(int)$id_address_delivery
  1067. );
  1068. if (!$result)
  1069. return false;
  1070. return Db::getInstance()->execute(
  1071. 'DELETE FROM `'._DB_PREFIX_.'customization`
  1072. WHERE `id_customization` = '.(int)$id_customization
  1073. );
  1074. }
  1075. return true;
  1076. }
  1077. public static function getTotalCart($id_cart, $use_tax_display = false, $type = CART::BOTH)
  1078. {
  1079. $cart = new Cart($id_cart);
  1080. if (!Validate::isLoadedObject($cart))
  1081. die(Tools::displayError());
  1082. $with_taxes = $use_tax_display ? $cart->_taxCalculationMethod != PS_TAX_EXC : true;
  1083. return Tools::displayPrice($cart->getOrderTotal($with_taxes, $type), Currency::getCurrencyInstance((int)$cart->id_currency), false);
  1084. }
  1085. public static function getOrderTotalUsingTaxCalculationMethod($id_cart)
  1086. {
  1087. return Cart::getTotalCart($id_cart, true);
  1088. }
  1089. /**
  1090. * This function returns the total cart amount
  1091. *
  1092. * Possible values for $type:
  1093. * Cart::ONLY_PRODUCTS
  1094. * Cart::ONLY_DISCOUNTS
  1095. * Cart::BOTH
  1096. * Cart::BOTH_WITHOUT_SHIPPING
  1097. * Cart::ONLY_SHIPPING
  1098. * Cart::ONLY_WRAPPING
  1099. * Cart::ONLY_PRODUCTS_WITHOUT_SHIPPING
  1100. * Cart::ONLY_PHYSICAL_PRODUCTS_WITHOUT_SHIPPING
  1101. *
  1102. * @param boolean $withTaxes With or without taxes
  1103. * @param integer $type Total type
  1104. * @param boolean $use_cache Allow using cache of the method CartRule::getContextualValue
  1105. * @return float Order total
  1106. */
  1107. public function getOrderTotal($with_taxes = true, $type = Cart::BOTH, $products = null, $id_carrier = null, $use_cache = true)
  1108. {
  1109. if (!$this->id)
  1110. return 0;
  1111. $type = (int)$type;
  1112. $array_type = array(
  1113. Cart::ONLY_PRODUCTS,
  1114. Cart::ONLY_DISCOUNTS,
  1115. Cart::BOTH,
  1116. Cart::BOTH_WITHOUT_SHIPPING,
  1117. Cart::ONLY_SHIPPING,
  1118. Cart::ONLY_WRAPPING,
  1119. Cart::ONLY_PRODUCTS_WITHOUT_SHIPPING,
  1120. Cart::ONLY_PHYSICAL_PRODUCTS_WITHOUT_SHIPPING,
  1121. );
  1122. // Define virtual context to prevent case where the cart is not the in the global context
  1123. $virtual_context = Context::getContext()->cloneContext();
  1124. $virtual_context->cart = $this;
  1125. if (!in_array($type, $array_type))
  1126. die(Tools::displayError());
  1127. $with_shipping = in_array($type, array(Cart::BOTH, Cart::ONLY_SHIPPING));
  1128. // if cart rules are not used
  1129. if ($type == Cart::ONLY_DISCOUNTS && !CartRule::isFeatureActive())
  1130. return 0;
  1131. // no shipping cost if is a cart with only virtuals products
  1132. $virtual = $this->isVirtualCart();
  1133. if ($virtual && $type == Cart::ONLY_SHIPPING)
  1134. return 0;
  1135. if ($virtual && $type == Cart::BOTH)
  1136. $type = Cart::BOTH_WITHOUT_SHIPPING;
  1137. if ($with_shipping)
  1138. {
  1139. if (is_null($products) && is_null($id_carrier))
  1140. $shipping_fees = $this->getTotalShippingCost(null, (boolean)$with_taxes);
  1141. else
  1142. $shipping_fees = $this->getPackageShippingCost($id_carrier, (int)$with_taxes, null, $products);
  1143. }
  1144. else
  1145. $shipping_fees = 0;
  1146. if ($type == Cart::ONLY_SHIPPING)
  1147. return $shipping_fees;
  1148. if ($type == Cart::ONLY_PRODUCTS_WITHOUT_SHIPPING)
  1149. $type = Cart::ONLY_PRODUCTS;
  1150. $param_product = true;
  1151. if (is_null($products))
  1152. {
  1153. $param_product = false;
  1154. $products = $this->getProducts();
  1155. }
  1156. if ($type == Cart::ONLY_PHYSICAL_PRODUCTS_WITHOUT_SHIPPING)
  1157. {
  1158. foreach ($products as $key => $product)
  1159. if ($product['is_virtual'])
  1160. unset($products[$key]);
  1161. $type = Cart::ONLY_PRODUCTS;
  1162. }
  1163. $order_total = 0;
  1164. if (Tax::excludeTaxeOption())
  1165. $with_taxes = false;
  1166. foreach ($products as $product) // products refer to the cart details
  1167. {
  1168. if ($virtual_context->shop->id != $product['id_shop'])
  1169. $virtual_context->shop = new Shop((int)$product['id_shop']);
  1170. if (Configuration::get('PS_TAX_ADDRESS_TYPE') == 'id_address_invoice')
  1171. $address_id = (int)$this->id_address_invoice;
  1172. else
  1173. $address_id = (int)$product['id_address_delivery']; // Get delivery address of the product from the cart
  1174. if (!Address::addressExists($address_id))
  1175. $address_id = null;
  1176. if ($this->_taxCalculationMethod == PS_TAX_EXC)
  1177. {
  1178. // Here taxes are computed only once the quantity has been applied to the product price
  1179. $price = Product::getPriceStatic(
  1180. (int)$product['id_product'],
  1181. false,
  1182. (int)$product['id_product_attribute'],
  1183. 2,
  1184. null,
  1185. false,
  1186. true,
  1187. $product['cart_quantity'],
  1188. false,
  1189. (int)$this->id_customer ? (int)$this->id_customer : null,
  1190. (int)$this->id,
  1191. $address_id,
  1192. $null,
  1193. true,
  1194. true,
  1195. $virtual_context
  1196. );
  1197. $total_ecotax = $product['ecotax'] * (int)$product['cart_quantity'];
  1198. $total_price = $price * (int)$product['cart_quantity'];
  1199. if ($with_taxes)
  1200. {
  1201. $product_tax_rate = (float)Tax::getProductTaxRate((int)$product['id_product'], (int)$address_id, $virtual_context);
  1202. $product_eco_tax_rate = Tax::getProductEcotaxRate((int)$address_id);
  1203. $total_price = ($total_price - $total_ecotax) * (1 + $product_tax_rate / 100);
  1204. $total_ecotax = $total_ecotax * (1 + $product_eco_tax_rate / 100);
  1205. $total_price = Tools::ps_round($total_price + $total_ecotax, 2);
  1206. }
  1207. }
  1208. else
  1209. {
  1210. if ($with_taxes)
  1211. $price = Product::getPriceStatic(
  1212. (int)$product['id_product'],
  1213. true,
  1214. (int)$product['id_product_attribute'],
  1215. 2,
  1216. null,
  1217. false,
  1218. true,
  1219. $product['cart_quantity'],
  1220. false,
  1221. ((int)$this->id_customer ? (int)$this->id_customer : null),
  1222. (int)$this->id,
  1223. ((int)$address_id ? (int)$address_id : null),
  1224. $null,
  1225. true,
  1226. true,
  1227. $virtual_context
  1228. );
  1229. else
  1230. $price = Product::getPriceStatic(
  1231. (int)$product['id_product'],
  1232. false,
  1233. (int)$product['id_product_attribute'],
  1234. 2,
  1235. null,
  1236. false,
  1237. true,
  1238. $product['cart_quantity'],
  1239. false,
  1240. ((int)$this->id_customer ? (int)$this->id_customer : null),
  1241. (int)$this->id,
  1242. ((int)$address_id ? (int)$address_id : null),
  1243. $null,
  1244. true,
  1245. true,
  1246. $virtual_context
  1247. );
  1248. $total_price = Tools::ps_round($price * (int)$product['cart_quantity'], 2);
  1249. }
  1250. $order_total += $total_price;
  1251. }
  1252. $order_total_products = $order_total;
  1253. if ($type == Cart::ONLY_DISCOUNTS)
  1254. $order_total = 0;
  1255. // Wrapping Fees
  1256. $wrapping_fees = 0;
  1257. if ($this->gift)
  1258. $wrapping_fees = Tools::convertPrice(Tools::ps_round($this->getGiftWrappingPrice($with_taxes), 2), Currency::getCurrencyInstance((int)$this->id_currency));
  1259. if ($type == Cart::ONLY_WRAPPING)
  1260. return $wrapping_fees;
  1261. $order_total_discount = 0;
  1262. if (!in_array($type, array(Cart::ONLY_SHIPPING, Cart::ONLY_PRODUCTS)) && CartRule::isFeatureActive())
  1263. {
  1264. // First, retrieve the cart rules associated to this "getOrderTotal"
  1265. if ($with_shipping || $type == Cart::ONLY_DISCOUNTS)
  1266. $cart_rules = $this->getCartRules(CartRule::FILTER_ACTION_ALL);
  1267. else
  1268. {
  1269. $cart_rules = $this->getCartRules(CartRule::FILTER_ACTION_REDUCTION);
  1270. // Cart Rules array are merged manually in order to avoid doubles
  1271. foreach ($this->getCartRules(CartRule::FILTER_ACTION_GIFT) as $tmp_cart_rule)
  1272. {
  1273. $flag = false;
  1274. foreach ($cart_rules as $cart_rule)
  1275. if ($tmp_cart_rule['id_cart_rule'] == $cart_rule['id_cart_rule'])
  1276. $flag = true;
  1277. if (!$flag)
  1278. $cart_rules[] = $tmp_cart_rule;
  1279. }
  1280. }
  1281. $id_address_delivery = 0;
  1282. if (isset($products[0]))
  1283. $id_address_delivery = (is_null($products) ? $this->id_address_delivery : $products[0]['id_address_delivery']);
  1284. $package = array('id_carrier' => $id_carrier, 'id_address' => $id_address_delivery, 'products' => $products);
  1285. // Then, calculate the contextual value for each one
  1286. foreach ($cart_rules as $cart_rule)
  1287. {
  1288. // If the cart rule offers free shipping, add the shipping cost
  1289. if (($with_shipping || $type == Cart::ONLY_DISCOUNTS) && $cart_rule['obj']->free_shipping)
  1290. $order_total_discount += Tools::ps_round($cart_rule['obj']->getContextualValue($with_taxes, $virtual_context, CartRule::FILTER_ACTION_SHIPPING, ($param_product ? $package : null), $use_cache), 2);
  1291. // If the cart rule is a free gift, then add the free gift value only if the gift is in this package
  1292. if ((int)$cart_rule['obj']->gift_product)
  1293. {
  1294. $in_order = false;
  1295. if (is_null($products))
  1296. $in_order = true;
  1297. else
  1298. foreach ($products as $product)
  1299. if ($cart_rule['obj']->gift_product == $product['id_product'] && $cart_rule['obj']->gift_product_attribute == $product['id_product_attribute'])
  1300. $in_order = true;
  1301. if ($in_order)
  1302. $order_total_discount += $cart_rule['obj']->getContextualValue($with_taxes, $virtual_context, CartRule::FILTER_ACTION_GIFT, $package, $use_cache);
  1303. }
  1304. // If the cart rule offers a reduction, the amount is prorated (with the products in the package)
  1305. if ($cart_rule['obj']->reduction_percent > 0 || $cart_rule['obj']->reduction_amount > 0)
  1306. $order_total_discount += Tools::ps_round($cart_rule['obj']->getContextualValue($with_taxes, $virtual_context, CartRule::FILTER_ACTION_REDUCTION, $package, $use_cache), 2);
  1307. }
  1308. $order_total_discount = min(Tools::ps_round($order_total_discount, 2), $wrapping_fees + $order_total_products + $shipping_fees);
  1309. $order_total -= $order_total_discount;
  1310. }
  1311. if ($type == Cart::BOTH)
  1312. $order_total += $shipping_fees + $wrapping_fees;
  1313. if ($order_total < 0 && $type != Cart::ONLY_DISCOUNTS)
  1314. return 0;
  1315. if ($type == Cart::ONLY_DISCOUNTS)
  1316. return $order_total_discount;
  1317. return Tools::ps_round((float)$order_total, 2);
  1318. }
  1319. /**
  1320. * Get the gift wrapping price
  1321. * @param boolean $with_taxes With or without taxes
  1322. * @return gift wrapping price
  1323. */
  1324. public function getGiftWrappingPrice($with_taxes = true, $id_address = null)
  1325. {
  1326. static $address = null;
  1327. if ($id_address === null)
  1328. $id_address = (int)$this->{Configuration::get('PS_TAX_ADDRESS_TYPE')};
  1329. if ($address === null)
  1330. $address = Address::initialize($id_address);
  1331. $wrapping_fees = (float)Configuration::get('PS_GIFT_WRAPPING_PRICE');
  1332. if ($with_taxes && $wrapping_fees > 0)
  1333. {
  1334. $tax_manager = TaxManagerFactory::getManager($address, (int)Configuration::get('PS_GIFT_WRAPPING_TAX_RULES_GROUP'));
  1335. $tax_calculator = $tax_manager->getTaxCalculator();
  1336. $wrapping_fees = $tax_calculator->addTaxes($wrapping_fees);
  1337. }
  1338. return $wrapping_fees;
  1339. }
  1340. /**
  1341. * Get the number of packages
  1342. *
  1343. * @return int number of packages
  1344. */
  1345. public function getNbOfPackages()
  1346. {
  1347. static $nb_packages = 0;
  1348. if (!$nb_packages)
  1349. foreach ($this->getPackageList() as $by_address)
  1350. $nb_packages += count($by_address);
  1351. return $nb_packages;
  1352. }
  1353. /**
  1354. * Get products grouped by package and by addresses to be sent individualy (one package = one shipping cost).
  1355. *
  1356. * @return array array(
  1357. * 0 => array( // First address
  1358. * 0 => array( // First package
  1359. * 'product_list' => array(...),
  1360. * 'carrier_list' => array(...),
  1361. * 'id_warehouse' => array(...),
  1362. * ),
  1363. * ),
  1364. * );
  1365. * @todo Add avaibility check
  1366. */
  1367. public function getPackageList($flush = false)
  1368. {
  1369. static $cache = array();
  1370. if (isset($cache[(int)$this->id]) && $cache[(int)$this->id] !== false && !$flush)
  1371. return $cache[(int)$this->id];
  1372. $product_list = $this->getProducts();
  1373. // Step 1 : Get product informations (warehouse_list and carrier_list), count warehouse
  1374. // Determine the best warehouse to determine the packages
  1375. // For that we count the number of time we can use a warehouse for a specific delivery address
  1376. $warehouse_count_by_address = array();
  1377. $warehouse_carrier_list = array();
  1378. $stock_management_active = Configuration::get('PS_ADVANCED_STOCK_MANAGEMENT');
  1379. foreach ($product_list as &$product)
  1380. {
  1381. if ((int)$product['id_address_delivery'] == 0)
  1382. $product['id_address_delivery'] = (int)$this->id_address_delivery;
  1383. if (!isset($warehouse_count_by_address[$product['id_address_delivery']]))
  1384. $warehouse_count_by_address[$product['id_address_delivery']] = array();
  1385. $product['warehouse_list'] = array();
  1386. if ($stock_management_active &&
  1387. ((int)$product['advanced_stock_management'] == 1 || Pack::usesAdvancedStockManagement((int)$product['id_product'])))
  1388. {
  1389. $warehouse_list = Warehouse::getProductWarehouseList($product['id_product'], $product['id_product_attribute'], $this->id_shop);
  1390. if (count($warehouse_list) == 0)
  1391. $warehouse_list = Warehouse::getProductWarehouseList($product['id_product'], $product['id_product_attribute']);
  1392. // Does the product is in stock ?
  1393. // If yes, get only warehouse where the product is in stock
  1394. $warehouse_in_stock = array();
  1395. $manager = StockManagerFactory::getManager();
  1396. foreach ($warehouse_list as $key => $warehouse)
  1397. {
  1398. $product_real_quantities = $manager->getProductRealQuantities(
  1399. $product['id_product'],
  1400. $product['id_product_attribute'],
  1401. array($warehouse['id_warehouse']),
  1402. true
  1403. );
  1404. if ($product_real_quantities > 0 || Pack::isPack((int)$product['id_product']))
  1405. $warehouse_in_stock[] = $warehouse;
  1406. }
  1407. if (!empty($warehouse_in_stock))
  1408. {
  1409. $warehouse_list = $warehouse_in_stock;
  1410. $product['in_stock'] = true;
  1411. }
  1412. else
  1413. $product['in_stock'] = false;
  1414. }
  1415. else
  1416. {
  1417. //simulate default warehouse
  1418. $warehouse_list = array(0);
  1419. $product['in_stock'] = StockAvailable::getQuantityAvailableByProduct($product['id_product'], $product['id_product_attribute']) > 0;
  1420. }
  1421. foreach ($warehouse_list as $warehouse)
  1422. {
  1423. if (!isset($warehouse_carrier_list[$warehouse['id_warehouse']]))
  1424. {
  1425. $warehouse_object = new Warehouse($warehouse['id_warehouse']);
  1426. $warehouse_carrier_list[$warehouse['id_warehouse']] = $warehouse_object->getCarriers();
  1427. }
  1428. $product['warehouse_list'][] = $warehouse['id_warehouse'];
  1429. if (!isset($warehouse_count_by_address[$product['id_address_delivery']][$warehouse['id_warehouse']]))
  1430. $warehouse_count_by_address[$product['id_address_delivery']][$warehouse['id_warehouse']] = 0;
  1431. $warehouse_count_by_address[$product['id_address_delivery']][$warehouse['id_warehouse']]++;
  1432. }
  1433. }
  1434. arsort($warehouse_count_by_address);
  1435. // Step 2 : Group product by warehouse
  1436. $grouped_by_warehouse = array();
  1437. foreach ($product_list as &$product)
  1438. {
  1439. if (!isset($grouped_by_warehouse[$product['id_address_delivery']]))
  1440. $grouped_by_warehouse[$product['id_address_delivery']] = array(
  1441. 'in_stock' => array(),
  1442. 'out_of_stock' => array(),
  1443. );
  1444. $product['carrier_list'] = array();
  1445. $id_warehouse = 0;
  1446. foreach ($warehouse_count_by_address[$product['id_address_delivery']] as $id_war => $val)
  1447. {
  1448. $product['carrier_list'] = array_merge($product['carrier_list'], Carrier::getAvailableCarrierList(new Product($product['id_product']), $id_war, $product['id_address_delivery'], null, $this));
  1449. if (in_array((int)$id_war, $product['warehouse_list']) && $id_warehouse == 0)
  1450. $id_warehouse = (int)$id_war;
  1451. }
  1452. if (!isset($grouped_by_warehouse[$product['id_address_delivery']]['in_stock'][$id_warehouse]))
  1453. {
  1454. $grouped_by_warehouse[$product['id_address_delivery']]['in_stock'][$id_warehouse] = array();
  1455. $grouped_by_warehouse[$product['id_address_delivery']]['out_of_stock'][$id_warehouse] = array();
  1456. }
  1457. if (!$this->allow_seperated_package)
  1458. $key = 'in_stock';
  1459. else
  1460. $key = $product['in_stock'] ? 'in_stock' : 'out_of_stock';
  1461. if (empty($product['carrier_list']))
  1462. $product['carrier_list'] = array(0);
  1463. $grouped_by_warehouse[$product['id_address_delivery']][$key][$id_warehouse][] = $product;
  1464. }
  1465. // Step 3 : grouped product from grouped_by_warehouse by available carriers
  1466. $grouped_by_carriers = array();
  1467. foreach ($grouped_by_warehouse as $id_address_delivery => $products_in_stock_list)
  1468. {
  1469. if (!isset($grouped_by_carriers[$id_address_delivery]))
  1470. $grouped_by_carriers[$id_address_delivery] = array(
  1471. 'in_stock' => array(),
  1472. 'out_of_stock' => array(),
  1473. );
  1474. foreach ($products_in_stock_list as $key => $warehouse_list)
  1475. {
  1476. if (!isset($grouped_by_carriers[$id_address_delivery][$key]))
  1477. $grouped_by_carriers[$id_address_delivery][$key] = array();
  1478. foreach ($warehouse_list as $id_warehouse => $product_list)
  1479. {
  1480. if (!isset($grouped_by_carriers[$id_address_delivery][$key][$id_warehouse]))
  1481. $grouped_by_carriers[$id_address_delivery][$key][$id_warehouse] = array();
  1482. foreach ($product_list as $product)
  1483. {
  1484. $package_carriers_key = implode(',', $product['carrier_list']);
  1485. if (!isset($grouped_by_carriers[$id_address_delivery][$key][$id_warehouse][$package_carriers_key]))
  1486. $grouped_by_carriers[$id_address_delivery][$key][$id_warehouse][$package_carriers_key] = array(
  1487. 'product_list' => array(),
  1488. 'carrier_list' => $product['carrier_list'],
  1489. 'warehouse_list' => $product['warehouse_list']
  1490. );
  1491. $grouped_by_carriers[$id_address_delivery][$key][$id_warehouse][$package_carriers_key]['product_list'][] = $product;
  1492. }
  1493. }
  1494. }
  1495. }
  1496. $package_list = array();
  1497. // Step 4 : merge product from grouped_by_carriers into $package to minimize the number of package
  1498. foreach ($grouped_by_carriers as $id_address_delivery => $products_in_stock_list)
  1499. {
  1500. if (!isset($package_list[$id_address_delivery]))
  1501. $package_list[$id_address_delivery] = array(
  1502. 'in_stock' => array(),
  1503. 'out_of_stock' => array(),
  1504. );
  1505. foreach ($products_in_stock_list as $key => $warehouse_list)
  1506. {
  1507. if (!isset($package_list[$id_address_delivery][$key]))
  1508. $package_list[$id_address_delivery][$key] = array();
  1509. // Count occurance of each carriers to minimize the number of packages
  1510. $carrier_count = array();
  1511. foreach ($warehouse_list as $id_warehouse => $products_grouped_by_carriers)
  1512. {
  1513. foreach ($products_grouped_by_carriers as $data)
  1514. {
  1515. foreach ($data['carrier_list'] as $id_carrier)
  1516. {
  1517. if (!isset($carrier_count[$id_carrier]))
  1518. $carrier_count[$id_carrier] = 0;
  1519. $carrier_count[$id_carrier]++;
  1520. }
  1521. }
  1522. }
  1523. arsort($carrier_count);
  1524. foreach ($warehouse_list as $id_warehouse => $products_grouped_by_carriers)
  1525. {
  1526. if (!isset($package_list[$id_address_delivery][$key][$id_warehouse]))
  1527. $package_list[$id_address_delivery][$key][$id_warehouse] = array();
  1528. foreach ($products_grouped_by_carriers as $data)
  1529. {
  1530. foreach ($carrier_count as $id_carrier => $rate)
  1531. {
  1532. if (in_array($id_carrier, $data['carrier_list']))
  1533. {
  1534. if (!isset($package_list[$id_address_delivery][$key][$id_warehouse][$id_carrier]))
  1535. $package_list[$id_address_delivery][$key][$id_warehouse][$id_carrier] = array(
  1536. 'carrier_list' => $data['carrier_list'],
  1537. 'warehouse_list' => $data['warehouse_list'],
  1538. 'product_list' => array(),
  1539. );
  1540. $package_list[$id_address_delivery][$key][$id_warehouse][$id_carrier]['carrier_list'] =
  1541. array_intersect($package_list[$id_address_delivery][$key][$id_warehouse][$id_carrier]['carrier_list'], $data['carrier_list']);
  1542. $package_list[$id_address_delivery][$key][$id_warehouse][$id_carrier]['product_list'] =
  1543. array_merge($package_list[$id_address_delivery][$key][$id_warehouse][$id_carrier]['product_list'], $data['product_list']);
  1544. break;
  1545. }
  1546. }
  1547. }
  1548. }
  1549. }
  1550. }
  1551. // Step 5 : Reduce depth of $package_list
  1552. $final_package_list = array();
  1553. foreach ($package_list as $id_address_delivery => $products_in_stock_list)
  1554. {
  1555. if (!isset($final_package_list[$id_address_delivery]))
  1556. $final_package_list[$id_address_delivery] = array();
  1557. foreach ($products_in_stock_list as $key => $warehouse_list)
  1558. foreach ($warehouse_list as $id_warehouse => $products_grouped_by_carriers)
  1559. foreach ($products_grouped_by_carriers as $data)
  1560. {
  1561. $final_package_list[$id_address_delivery][] = array(
  1562. 'product_list' => $data['product_list'],
  1563. 'carrier_list' => $data['carrier_list'],
  1564. 'warehouse_list' => $data['warehouse_list'],
  1565. 'id_warehouse' => $id_warehouse,
  1566. );
  1567. }
  1568. }
  1569. $cache[(int)$this->id] = $final_package_list;
  1570. return $final_package_list;
  1571. }
  1572. public function getPackageIdWarehouse($package, $id_carrier = null)
  1573. {
  1574. if ($id_carrier === null)
  1575. if (isset($package['id_carrier']))
  1576. $id_carrier = (int)$package['id_carrier'];
  1577. if ($id_carrier == null)
  1578. return $package['id_warehouse'];
  1579. foreach ($package['warehouse_list'] as $id_warehouse)
  1580. {
  1581. $warehouse = new Warehouse((int)$id_warehouse);
  1582. $available_warehouse_carriers = $warehouse->getCarriers();
  1583. if (in_array($id_carrier, $available_warehouse_carriers))
  1584. return (int)$id_warehouse;
  1585. }
  1586. return 0;
  1587. }
  1588. /**
  1589. * Get all deliveries options available for the current cart
  1590. * @param Country $default_country
  1591. * @param boolean $flush Force flushing cache
  1592. *
  1593. * @return array array(
  1594. * 0 => array( // First address
  1595. * '12,' => array( // First delivery option available for this address
  1596. * carrier_list => array(
  1597. * 12 => array( // First carrier for this option
  1598. * 'instance' => Carrier Object,
  1599. * 'logo' => <url to the carriers logo>,
  1600. * 'price_with_tax' => 12.4,
  1601. * 'price_without_tax' => 12.4,
  1602. * 'package_list' => array(
  1603. * 1,
  1604. * 3,
  1605. * ),
  1606. * ),
  1607. * ),
  1608. * is_best_grade => true, // Does this option have the biggest grade (quick shipping) for this shipping address
  1609. * is_best_price => true, // Does this option have the lower price for this shipping address
  1610. * unique_carrier => true, // Does this option use a unique carrier
  1611. * total_price_with_tax => 12.5,
  1612. * total_price_without_tax => 12.5,
  1613. * position => 5, // Average of the carrier position
  1614. * ),
  1615. * ),
  1616. * );
  1617. * If there are no carriers available for an address, return an empty array
  1618. */
  1619. public function getDeliveryOptionList(Country $default_country = null, $flush = false)
  1620. {
  1621. static $cache = null;
  1622. if ($cache !== null && !$flush)
  1623. return $cache;
  1624. $delivery_option_list = array();
  1625. $carriers_price = array();
  1626. $carrier_collection = array();
  1627. $package_list = $this->getPackageList();
  1628. // Foreach addresses
  1629. foreach ($package_list as $id_address => $packages)
  1630. {
  1631. // Initialize vars
  1632. $delivery_option_list[$id_address] = array();
  1633. $carriers_price[$id_address] = array();
  1634. $common_carriers = null;
  1635. $best_price_carriers = array();
  1636. $best_grade_carriers = array();
  1637. $carriers_instance = array();
  1638. // Get country
  1639. if ($id_address)
  1640. {
  1641. $address = new Address($id_address);
  1642. $country = new Country($address->id_country);
  1643. }
  1644. else
  1645. $country = $default_country;
  1646. // Foreach packages, get the carriers with best price, best position and best grade
  1647. foreach ($packages as $id_package => $package)
  1648. {
  1649. // No carriers available
  1650. if (count($package['carrier_list']) == 1 && current($package['carrier_list']) == 0)
  1651. {
  1652. $cache = array();
  1653. return $cache;
  1654. }
  1655. $carriers_price[$id_address][$id_package] = array();
  1656. // Get all common carriers for each packages to the same address
  1657. if (is_null($common_carriers))
  1658. $common_carriers = $package['carrier_list'];
  1659. else
  1660. $common_carriers = array_intersect($common_carriers, $package['carrier_list']);
  1661. $best_price = null;
  1662. $best_price_carrier = null;
  1663. $best_grade = null;
  1664. $best_grade_carrier = null;
  1665. // Foreach carriers of the package, calculate his price, check if it the best price, position and grade
  1666. foreach ($package['carrier_list'] as $id_carrier)
  1667. {
  1668. if (!isset($carriers_instance[$id_carrier]))
  1669. $carriers_instance[$id_carrier] = new Carrier($id_carrier);
  1670. $price_with_tax = $this->getPackageShippingCost($id_carrier, true, $country, $package['product_list']);
  1671. $price_without_tax = $this->getPackageShippingCost($id_carrier, false, $country, $package['product_list']);
  1672. if (is_null($best_price) || $price_with_tax < $best_price)
  1673. {
  1674. $best_price = $price_with_tax;
  1675. $best_price_carrier = $id_carrier;
  1676. }
  1677. $carriers_price[$id_address][$id_package][$id_carrier] = array(
  1678. 'without_tax' => $price_without_tax,
  1679. 'with_tax' => $price_with_tax);
  1680. $grade = $carriers_instance[$id_carrier]->grade;
  1681. if (is_null($best_grade) || $grade > $best_grade)
  1682. {
  1683. $best_grade = $grade;
  1684. $best_grade_carrier = $id_carrier;
  1685. }
  1686. }
  1687. $best_price_carriers[$id_package] = $best_price_carrier;
  1688. $best_grade_carriers[$id_package] = $best_grade_carrier;
  1689. }
  1690. // Reset $best_price_carrier, it's now an array
  1691. $best_price_carrier = array();
  1692. $key = '';
  1693. // Get the delivery option with the lower price
  1694. foreach ($best_price_carriers as $id_package => $id_carrier)
  1695. {
  1696. $key .= $id_carrier.',';
  1697. if (!isset($best_price_carrier[$id_carrier]))
  1698. $best_price_carrier[$id_carrier] = array(
  1699. 'price_with_tax' => 0,
  1700. 'price_without_tax' => 0,
  1701. 'package_list' => array(),
  1702. 'product_list' => array(),
  1703. );
  1704. $best_price_carrier[$id_carrier]['price_with_tax'] += $carriers_price[$id_address][$id_package][$id_carrier]['with_tax'];
  1705. $best_price_carrier[$id_carrier]['price_without_tax'] += $carriers_price[$id_address][$id_package][$id_carrier]['without_tax'];
  1706. $best_price_carrier[$id_carrier]['package_list'][] = $id_package;
  1707. $best_price_carrier[$id_carrier]['product_list'] = array_merge($best_price_carrier[$id_carrier]['product_list'], $packages[$id_package]['product_list']);
  1708. $best_price_carrier[$id_carrier]['instance'] = $carriers_instance[$id_carrier];
  1709. }
  1710. // Add the delivery option with best price as best price
  1711. $delivery_option_list[$id_address][$key] = array(
  1712. 'carrier_list' => $best_price_carrier,
  1713. 'is_best_price' => true,
  1714. 'is_best_grade' => false,
  1715. 'unique_carrier' => (count($best_price_carrier) <= 1)
  1716. );
  1717. // Reset $best_grade_carrier, it's now an array
  1718. $best_grade_carrier = array();
  1719. $key = '';
  1720. // Get the delivery option with the best grade
  1721. foreach ($best_grade_carriers as $id_package => $id_carrier)
  1722. {
  1723. $key .= $id_carrier.',';
  1724. if (!isset($best_grade_carrier[$id_carrier]))
  1725. $best_grade_carrier[$id_carrier] = array(
  1726. 'price_with_tax' => 0,
  1727. 'price_without_tax' => 0,
  1728. 'package_list' => array(),
  1729. 'product_list' => array(),
  1730. );
  1731. $best_grade_carrier[$id_carrier]['price_with_tax'] += $carriers_price[$id_address][$id_package][$id_carrier]['with_tax'];
  1732. $best_grade_carrier[$id_carrier]['price_without_tax'] += $carriers_price[$id_address][$id_package][$id_carrier]['without_tax'];
  1733. $best_grade_carrier[$id_carrier]['package_list'][] = $id_package;
  1734. $best_grade_carrier[$id_carrier]['product_list'] = array_merge($best_grade_carrier[$id_carrier]['product_list'], $packages[$id_package]['product_list']);
  1735. $best_grade_carrier[$id_carrier]['instance'] = $carriers_instance[$id_carrier];
  1736. }
  1737. // Add the delivery option with best grade as best grade
  1738. if (!isset($delivery_option_list[$id_address][$key]))
  1739. $delivery_option_list[$id_address][$key] = array(
  1740. 'carrier_list' => $best_grade_carrier,
  1741. 'is_best_price' => false,
  1742. 'unique_carrier' => (count($best_grade_carrier) <= 1)
  1743. );
  1744. $delivery_option_list[$id_address][$key]['is_best_grade'] = true;
  1745. // Get all delivery options with a unique carrier
  1746. foreach ($common_carriers as $id_carrier)
  1747. {
  1748. $price = 0;
  1749. $key = '';
  1750. $package_list = array();
  1751. $product_list = array();
  1752. $total_price_with_tax = 0;
  1753. $total_price_without_tax = 0;
  1754. $price_with_tax = 0;
  1755. $price_without_tax = 0;
  1756. foreach ($packages as $id_package => $package)
  1757. {
  1758. $key .= $id_carrier.',';
  1759. $price_with_tax += $carriers_price[$id_address][$id_package][$id_carrier]['with_tax'];
  1760. $price_without_tax += $carriers_price[$id_address][$id_package][$id_carrier]['without_tax'];
  1761. $package_list[] = $id_package;
  1762. $product_list = array_merge($product_list, $package['product_list']);
  1763. }
  1764. if (!isset($delivery_option_list[$id_address][$key]))
  1765. $delivery_option_list[$id_address][$key] = array(
  1766. 'is_best_price' => false,
  1767. 'is_best_grade' => false,
  1768. 'unique_carrier' => true,
  1769. 'carrier_list' => array(
  1770. $id_carrier => array(
  1771. 'price_with_tax' => $price_with_tax,
  1772. 'price_without_tax' => $price_without_tax,
  1773. 'instance' => $carriers_instance[$id_carrier],
  1774. 'package_list' => $package_list,
  1775. 'product_list' => $product_list,
  1776. )
  1777. )
  1778. );
  1779. else
  1780. $delivery_option_list[$id_address][$key]['unique_carrier'] = (count($delivery_option_list[$id_address][$key]['carrier_list']) <= 1);
  1781. }
  1782. }
  1783. // For each delivery options :
  1784. // - Set the carrier list
  1785. // - Calculate the price
  1786. // - Calculate the average position
  1787. foreach ($delivery_option_list as $id_address => $delivery_option)
  1788. foreach ($delivery_option as $key => $value)
  1789. {
  1790. $total_price_with_tax = 0;
  1791. $total_price_without_tax = 0;
  1792. $position = 0;
  1793. foreach ($value['carrier_list'] as $id_carrier => $data)
  1794. {
  1795. $total_price_with_tax += $data['price_with_tax'];
  1796. $total_price_without_tax += $data['price_without_tax'];
  1797. if (!isset($carrier_collection[$id_carrier]))
  1798. $carrier_collection[$id_carrier] = new Carrier($id_carrier);
  1799. $delivery_option_list[$id_address][$key]['carrier_list'][$id_carrier]['instance'] = $carrier_collection[$id_carrier];
  1800. if (file_exists(_PS_SHIP_IMG_DIR_.$id_carrier.'.jpg'))
  1801. $delivery_option_list[$id_address][$key]['carrier_list'][$id_carrier]['logo'] = _THEME_SHIP_DIR_.$id_carrier.'.jpg';
  1802. else
  1803. $delivery_option_list[$id_address][$key]['carrier_list'][$id_carrier]['logo'] = false;
  1804. $position += $carrier_collection[$id_carrier]->position;
  1805. }
  1806. $delivery_option_list[$id_address][$key]['total_price_with_tax'] = $total_price_with_tax;
  1807. $delivery_option_list[$id_address][$key]['total_price_without_tax'] = $total_price_without_tax;
  1808. $delivery_option_list[$id_address][$key]['position'] = $position / count($value['carrier_list']);
  1809. }
  1810. // Sort delivery option list
  1811. foreach ($delivery_option_list as &$array)
  1812. uasort ($array, array('Cart', 'sortDeliveryOptionList'));
  1813. $cache = $delivery_option_list;
  1814. return $delivery_option_list;
  1815. }
  1816. /**
  1817. *
  1818. * Sort list of option delivery by parameters define in the BO
  1819. * @param $option1
  1820. * @param $option2
  1821. * @return int -1 if $option 1 must be placed before and 1 if the $option1 must be placed after the $option2
  1822. */
  1823. public static function sortDeliveryOptionList($option1, $option2)
  1824. {
  1825. static $order_by_price = null;
  1826. static $order_way = null;
  1827. if (is_null($order_by_price))
  1828. $order_by_price = !Configuration::get('PS_CARRIER_DEFAULT_SORT');
  1829. if (is_null($order_way))
  1830. $order_way = Configuration::get('PS_CARRIER_DEFAULT_ORDER');
  1831. if ($order_by_price)
  1832. if ($order_way)
  1833. return ($option1['total_price_with_tax'] < $option2['total_price_with_tax']) * 2 - 1; // return -1 or 1
  1834. else
  1835. return ($option1['total_price_with_tax'] >= $option2['total_price_with_tax']) * 2 - 1; // return -1 or 1
  1836. else
  1837. if ($order_way)
  1838. return ($option1['position'] < $option2['position']) * 2 - 1; // return -1 or 1
  1839. else
  1840. return ($option1['position'] >= $option2['position']) * 2 - 1; // return -1 or 1
  1841. }
  1842. public function carrierIsSelected($id_carrier, $id_address)
  1843. {
  1844. $delivery_option = $this->getDeliveryOption();
  1845. $delivery_option_list = $this->getDeliveryOptionList();
  1846. if (!isset($delivery_option[$id_address]))
  1847. return false;
  1848. if (!isset($delivery_option_list[$id_address][$delivery_option[$id_address]]))
  1849. return false;
  1850. if (!in_array($id_carrier, array_keys($delivery_option_list[$id_address][$delivery_option[$id_address]]['carrier_list'])))
  1851. return false;
  1852. return true;
  1853. }
  1854. /**
  1855. * Get all deliveries options available for the current cart formated like Carriers::getCarriersForOrder
  1856. * This method was wrote for retrocompatibility with 1.4 theme
  1857. * New theme need to use Cart::getDeliveryOptionList() to generate carriers option in the checkout process
  1858. *
  1859. * @since 1.5.0
  1860. *
  1861. * @param Country $default_country
  1862. * @param boolean $flush Force flushing cache
  1863. *
  1864. */
  1865. public function simulateCarriersOutput(Country $default_country = null, $flush = false)
  1866. {
  1867. static $cache = false;
  1868. if ($cache !== false && !$flush)
  1869. return $cache;
  1870. $delivery_option_list = $this->getDeliveryOptionList($default_country, $flush);
  1871. // This method cannot work if there is multiple address delivery
  1872. if (count($delivery_option_list) > 1 || empty($delivery_option_list))
  1873. return array();
  1874. $carriers = array();
  1875. foreach (reset($delivery_option_list) as $key => $option)
  1876. {
  1877. $price = $option['total_price_with_tax'];
  1878. $price_tax_exc = $option['total_price_without_tax'];
  1879. if ($option['unique_carrier'])
  1880. {
  1881. $carrier = reset($option['carrier_list']);
  1882. $name = $carrier['instance']->name;
  1883. $img = $carrier['logo'];
  1884. $delay = $carrier['instance']->delay;
  1885. $delay = isset($delay[Context::getContext()->language->id]) ? $delay[Context::getContext()->language->id] : $delay[(int)Configuration::get('PS_LANG_DEFAULT')];
  1886. }
  1887. else
  1888. {
  1889. $nameList = array();
  1890. foreach ($option['carrier_list'] as $carrier)
  1891. $nameList[] = $carrier['instance']->name;
  1892. $name = join(' -', $nameList);
  1893. $img = ''; // No images if multiple carriers
  1894. $delay = '';
  1895. }
  1896. $carriers[] = array(
  1897. 'name' => $name,
  1898. 'img' => $img,
  1899. 'delay' => $delay,
  1900. 'price' => $price,
  1901. 'price_tax_exc' => $price_tax_exc,
  1902. 'id_carrier' => Cart::intifier($key), // Need to translate to an integer for retrocompatibility reason, in 1.4 template we used intval
  1903. 'is_module' => false,
  1904. );
  1905. }
  1906. return $carriers;
  1907. }
  1908. public function simulateCarrierSelectedOutput()
  1909. {
  1910. $delivery_option = $this->getDeliveryOption();
  1911. if (count($delivery_option) > 1 || empty($delivery_option))
  1912. return 0;
  1913. return Cart::intifier(reset($delivery_option));
  1914. }
  1915. /**
  1916. * Translate a string option_delivery identifier ('24,3,') in a int (3240002000)
  1917. *
  1918. * The option_delivery identifier is a list of integers separated by a ','.
  1919. * This method replace the delimiter by a sequence of '0'.
  1920. * The size of this sequence is fixed by the first digit of the return
  1921. *
  1922. * @return int
  1923. */
  1924. public static function intifier($string, $delimiter = ',')
  1925. {
  1926. $elm = explode($delimiter, $string);
  1927. $max = max($elm);
  1928. return strlen($max).implode(str_repeat('0', strlen($max) + 1), $elm);
  1929. }
  1930. /**
  1931. * Translate a int option_delivery identifier (3240002000) in a string ('24,3,')
  1932. */
  1933. public static function desintifier($int, $delimiter = ',')
  1934. {
  1935. $delimiter_len = $int[0];
  1936. $int = strrev(substr($int, 1));
  1937. $elm = explode(str_repeat('0', $delimiter_len + 1), $int);
  1938. return strrev(implode($delimiter, $elm));
  1939. }
  1940. /**
  1941. * Does the cart use multiple address
  1942. * @return boolean
  1943. */
  1944. public function isMultiAddressDelivery()
  1945. {
  1946. static $cache = null;
  1947. if (is_null($cache))
  1948. {
  1949. $sql = new DbQuery();
  1950. $sql->select('count(distinct id_address_delivery)');
  1951. $sql->from('cart_product', 'cp');
  1952. $sql->where('id_cart = '.(int)$this->id);
  1953. $cache = Db::getInstance()->getValue($sql) > 1;
  1954. }
  1955. return $cache;
  1956. }
  1957. /**
  1958. * Get all delivery addresses object for the current cart
  1959. */
  1960. public function getAddressCollection()
  1961. {
  1962. $collection = array();
  1963. $result = Db::getInstance()->executeS(
  1964. 'SELECT DISTINCT `id_address_delivery`
  1965. FROM `'._DB_PREFIX_.'cart_product`
  1966. WHERE id_cart = '.(int)$this->id
  1967. );
  1968. $result[] = array('id_address_delivery' => (int)$this->id_address_delivery);
  1969. foreach ($result as $row)
  1970. if ((int)$row['id_address_delivery'] != 0)
  1971. $collection[(int)$row['id_address_delivery']] = new Address((int)$row['id_address_delivery']);
  1972. return $collection;
  1973. }
  1974. /**
  1975. * Set the delivery option and id_carrier, if there is only one carrier
  1976. */
  1977. public function setDeliveryOption($delivery_option = null)
  1978. {
  1979. if (empty($delivery_option) || count($delivery_option) == 0)
  1980. {
  1981. $this->delivery_option = '';
  1982. $this->id_carrier = 0;
  1983. return;
  1984. }
  1985. Cache::clean('getContextualValue_*');
  1986. $delivery_option_list = $this->getDeliveryOptionList(null, true);
  1987. foreach ($delivery_option_list as $id_address => $options)
  1988. if (!isset($delivery_option[$id_address]))
  1989. foreach ($options as $key => $option)
  1990. if ($option['is_best_price'])
  1991. {
  1992. $delivery_option[$id_address] = $key;
  1993. break;
  1994. }
  1995. if (count($delivery_option) == 1)
  1996. $this->id_carrier = $this->getIdCarrierFromDeliveryOption($delivery_option);
  1997. $this->delivery_option = serialize($delivery_option);
  1998. }
  1999. protected function getIdCarrierFromDeliveryOption($delivery_option)
  2000. {
  2001. $delivery_option_list = $this->getDeliveryOptionList();
  2002. foreach ($delivery_option as $key => $value)
  2003. if (isset($delivery_option_list[$key]) && isset($delivery_option_list[$key][$value]))
  2004. if (count($delivery_option_list[$key][$value]['carrier_list']) == 1)
  2005. return current(array_keys($delivery_option_list[$key][$value]['carrier_list']));
  2006. return 0;
  2007. }
  2008. /**
  2009. * Get the delivery option seleted, or if no delivery option was selected, the cheapest option for each address
  2010. * @return array delivery option
  2011. */
  2012. public function getDeliveryOption($default_country = null, $dontAutoSelectOptions = false, $use_cache = true)
  2013. {
  2014. static $cache = array();
  2015. $cache_id = (int)(is_object($default_country) ? $default_country->id : 0).'-'.(int)$dontAutoSelectOptions;
  2016. if (isset($cache[$cache_id]) && $use_cache)
  2017. return $cache[$cache_id];
  2018. $delivery_option_list = $this->getDeliveryOptionList($default_country);
  2019. // The delivery option was selected
  2020. if (isset($this->delivery_option) && $this->delivery_option != '')
  2021. {
  2022. $delivery_option = Tools::unSerialize($this->delivery_option);
  2023. $validated = true;
  2024. foreach ($delivery_option as $id_address => $key)
  2025. if (!isset($delivery_option_list[$id_address][$key]))
  2026. {
  2027. $validated = false;
  2028. break;
  2029. }
  2030. if ($validated)
  2031. {
  2032. $cache[$cache_id] = $delivery_option;
  2033. return $delivery_option;
  2034. }
  2035. }
  2036. if ($dontAutoSelectOptions)
  2037. return false;
  2038. // No delivery option selected or delivery option selected is not valid, get the better for all options
  2039. $delivery_option = array();
  2040. foreach ($delivery_option_list as $id_address => $options)
  2041. {
  2042. foreach ($options as $key => $option)
  2043. if (Configuration::get('PS_CARRIER_DEFAULT') == -1 && $option['is_best_price'])
  2044. {
  2045. $delivery_option[$id_address] = $key;
  2046. break;
  2047. }
  2048. elseif (Configuration::get('PS_CARRIER_DEFAULT') == -2 && $option['is_best_grade'])
  2049. {
  2050. $delivery_option[$id_address] = $key;
  2051. break;
  2052. }
  2053. elseif ($option['unique_carrier'] && in_array(Configuration::get('PS_CARRIER_DEFAULT'), array_keys($option['carrier_list'])))
  2054. {
  2055. $delivery_option[$id_address] = $key;
  2056. break;
  2057. }
  2058. reset($options);
  2059. if (!isset($delivery_option[$id_address]))
  2060. $delivery_option[$id_address] = key($options);
  2061. }
  2062. $cache[$cache_id] = $delivery_option;
  2063. return $delivery_option;
  2064. }
  2065. /**
  2066. * Return shipping total for the cart
  2067. *
  2068. * @param array $delivery_option Array of the delivery option for each address
  2069. * @param booleal $use_tax
  2070. * @param Country $default_country
  2071. * @return float Shipping total
  2072. */
  2073. public function getTotalShippingCost($delivery_option = null, $use_tax = true, Country $default_country = null)
  2074. {
  2075. if(isset(Context::getContext()->cookie->id_country))
  2076. $default_country = new Country(Context::getContext()->cookie->id_country);
  2077. if (is_null($delivery_option))
  2078. $delivery_option = $this->getDeliveryOption($default_country, false, false);
  2079. $total_shipping = 0;
  2080. $delivery_option_list = $this->getDeliveryOptionList($default_country);
  2081. foreach ($delivery_option as $id_address => $key)
  2082. {
  2083. if (!isset($delivery_option_list[$id_address]) || !isset($delivery_option_list[$id_address][$key]))
  2084. continue;
  2085. if ($use_tax)
  2086. $total_shipping += $delivery_option_list[$id_address][$key]['total_price_with_tax'];
  2087. else
  2088. $total_shipping += $delivery_option_list[$id_address][$key]['total_price_without_tax'];
  2089. }
  2090. return $total_shipping;
  2091. }
  2092. /**
  2093. * Return shipping total of a specific carriers for the cart
  2094. *
  2095. * @param int $id_carrier
  2096. * @param array $delivery_option Array of the delivery option for each address
  2097. * @param booleal $useTax
  2098. * @param Country $default_country
  2099. * @return float Shipping total
  2100. */
  2101. public function getCarrierCost($id_carrier, $useTax = true, Country $default_country = null, $delivery_option = null)
  2102. {
  2103. if (is_null($delivery_option))
  2104. $delivery_option = $this->getDeliveryOption($default_country);
  2105. $total_shipping = 0;
  2106. $delivery_option_list = $this->getDeliveryOptionList();
  2107. foreach ($delivery_option as $id_address => $key)
  2108. {
  2109. if (!isset($delivery_option_list[$id_address]) || !isset($delivery_option_list[$id_address][$key]))
  2110. continue;
  2111. if (isset($delivery_option_list[$id_address][$key]['carrier_list'][$id_carrier]))
  2112. {
  2113. if ($useTax)
  2114. $total_shipping += $delivery_option_list[$id_address][$key]['carrier_list'][$id_carrier]['price_with_tax'];
  2115. else
  2116. $total_shipping += $delivery_option_list[$id_address][$key]['carrier_list'][$id_carrier]['price_without_tax'];
  2117. }
  2118. }
  2119. return $total_shipping;
  2120. }
  2121. /**
  2122. * @deprecated 1.5.0, use Cart->getPackageShippingCost()
  2123. */
  2124. public function getOrderShippingCost($id_carrier = null, $use_tax = true, Country $default_country = null, $product_list = null)
  2125. {
  2126. Tools::displayAsDeprecated();
  2127. return $this->getPackageShippingCost($id_carrier, $use_tax, $default_country, $product_list);
  2128. }
  2129. /**
  2130. * Return package shipping cost
  2131. *
  2132. * @param integer $id_carrier Carrier ID (default : current carrier)
  2133. * @param booleal $use_tax
  2134. * @param Country $default_country
  2135. * @param Array $product_list
  2136. * @param array $product_list List of product concerned by the shipping. If null, all the product of the cart are used to calculate the shipping cost
  2137. *
  2138. * @return float Shipping total
  2139. */
  2140. public function getPackageShippingCost($id_carrier = null, $use_tax = true, Country $default_country = null, $product_list = null, $id_zone = null)
  2141. {
  2142. if ($this->isVirtualCart())
  2143. return 0;
  2144. if (!$default_country)
  2145. $default_country = Context::getContext()->country;
  2146. $complete_product_list = $this->getProducts();
  2147. if (is_null($product_list))
  2148. $products = $complete_product_list;
  2149. else
  2150. $products = $product_list;
  2151. if (Configuration::get('PS_TAX_ADDRESS_TYPE') == 'id_address_invoice')
  2152. $address_id = (int)$this->id_address_invoice;
  2153. elseif (count($product_list))
  2154. {
  2155. $prod = current($product_list);
  2156. $address_id = (int)$prod['id_address_delivery'];
  2157. }
  2158. else
  2159. $address_id = null;
  2160. if (!Address::addressExists($address_id))
  2161. $address_id = null;
  2162. $cache_id = 'getPackageShippingCost_'.(int)$this->id.'_'.(int)$address_id.'_'.(int)$id_carrier.'_'.(int)$use_tax.'_'.(int)$default_country->id;
  2163. if ($products)
  2164. foreach ($products as $product)
  2165. $cache_id .= '_'.(int)$product['id_product'].'_'.(int)$product['id_product_attribute'];
  2166. if (Cache::isStored($cache_id))
  2167. return Cache::retrieve($cache_id);
  2168. // Order total in default currency without fees
  2169. $order_total = $this->getOrderTotal(true, Cart::ONLY_PHYSICAL_PRODUCTS_WITHOUT_SHIPPING, $product_list);
  2170. // Start with shipping cost at 0
  2171. $shipping_cost = 0;
  2172. // If no product added, return 0
  2173. if (!count($products))
  2174. {
  2175. Cache::store($cache_id, $shipping_cost);
  2176. return $shipping_cost;
  2177. }
  2178. if(!isset($id_zone))
  2179. {
  2180. // Get id zone
  2181. if (!$this->isMultiAddressDelivery()
  2182. && isset($this->id_address_delivery) // Be carefull, id_address_delivery is not usefull one 1.5
  2183. && $this->id_address_delivery
  2184. && Customer::customerHasAddress($this->id_customer, $this->id_address_delivery
  2185. ))
  2186. $id_zone = Address::getZoneById((int)$this->id_address_delivery);
  2187. else
  2188. {
  2189. if (!Validate::isLoadedObject($default_country))
  2190. $default_country = new Country(Configuration::get('PS_COUNTRY_DEFAULT'), Configuration::get('PS_LANG_DEFAULT'));
  2191. $id_zone = (int)$default_country->id_zone;
  2192. }
  2193. }
  2194. if ($id_carrier && !$this->isCarrierInRange((int)$id_carrier, (int)$id_zone))
  2195. $id_carrier = '';
  2196. if (empty($id_carrier) && $this->isCarrierInRange((int)Configuration::get('PS_CARRIER_DEFAULT'), (int)$id_zone))
  2197. $id_carrier = (int)Configuration::get('PS_CARRIER_DEFAULT');
  2198. if (empty($id_carrier))
  2199. {
  2200. if ((int)$this->id_customer)
  2201. {
  2202. $customer = new Customer((int)$this->id_customer);
  2203. $result = Carrier::getCarriers((int)Configuration::get('PS_LANG_DEFAULT'), true, false, (int)$id_zone, $customer->getGroups());
  2204. unset($customer);
  2205. }
  2206. else
  2207. $result = Carrier::getCarriers((int)Configuration::get('PS_LANG_DEFAULT'), true, false, (int)$id_zone);
  2208. foreach ($result as $k => $row)
  2209. {
  2210. if ($row['id_carrier'] == Configuration::get('PS_CARRIER_DEFAULT'))
  2211. continue;
  2212. if (!isset(self::$_carriers[$row['id_carrier']]))
  2213. self::$_carriers[$row['id_carrier']] = new Carrier((int)$row['id_carrier']);
  2214. $carrier = self::$_carriers[$row['id_carrier']];
  2215. // Get only carriers that are compliant with shipping method
  2216. if (($carrier->getShippingMethod() == Carrier::SHIPPING_METHOD_WEIGHT && $carrier->getMaxDeliveryPriceByWeight((int)$id_zone) === false)
  2217. || ($carrier->getShippingMethod() == Carrier::SHIPPING_METHOD_PRICE && $carrier->getMaxDeliveryPriceByPrice((int)$id_zone) === false))
  2218. {
  2219. unset($result[$k]);
  2220. continue;
  2221. }
  2222. // If out-of-range behavior carrier is set on "Desactivate carrier"
  2223. if ($row['range_behavior'])
  2224. {
  2225. $check_delivery_price_by_weight = Carrier::checkDeliveryPriceByWeight($row['id_carrier'], $this->getTotalWeight(), (int)$id_zone);
  2226. $total_order = $this->getOrderTotal(true, Cart::BOTH_WITHOUT_SHIPPING, $product_list);
  2227. $check_delivery_price_by_price = Carrier::checkDeliveryPriceByPrice($row['id_carrier'], $total_order, (int)$id_zone, (int)$this->id_currency);
  2228. // Get only carriers that have a range compatible with cart
  2229. if (($carrier->getShippingMethod() == Carrier::SHIPPING_METHOD_WEIGHT && !$check_delivery_price_by_weight)
  2230. || ($carrier->getShippingMethod() == Carrier::SHIPPING_METHOD_PRICE && !$check_delivery_price_by_price))
  2231. {
  2232. unset($result[$k]);
  2233. continue;
  2234. }
  2235. }
  2236. if ($carrier->getShippingMethod() == Carrier::SHIPPING_METHOD_WEIGHT)
  2237. $shipping = $carrier->getDeliveryPriceByWeight($this->getTotalWeight($product_list), (int)$id_zone);
  2238. else
  2239. $shipping = $carrier->getDeliveryPriceByPrice($order_total, (int)$id_zone, (int)$this->id_currency);
  2240. if (!isset($min_shipping_price))
  2241. $min_shipping_price = $shipping;
  2242. if ($shipping <= $min_shipping_price)
  2243. {
  2244. $id_carrier = (int)$row['id_carrier'];
  2245. $min_shipping_price = $shipping;
  2246. }
  2247. }
  2248. }
  2249. if (empty($id_carrier))
  2250. $id_carrier = Configuration::get('PS_CARRIER_DEFAULT');
  2251. if (!isset(self::$_carriers[$id_carrier]))
  2252. self::$_carriers[$id_carrier] = new Carrier((int)$id_carrier, Configuration::get('PS_LANG_DEFAULT'));
  2253. $carrier = self::$_carriers[$id_carrier];
  2254. // No valid Carrier or $id_carrier <= 0 ?
  2255. if (!Validate::isLoadedObject($carrier))
  2256. {
  2257. Cache::store($cache_id, 0);
  2258. return 0;
  2259. }
  2260. if (!$carrier->active)
  2261. {
  2262. Cache::store($cache_id, $shipping_cost);
  2263. return $shipping_cost;
  2264. }
  2265. // Free fees if free carrier
  2266. if ($carrier->is_free == 1)
  2267. {
  2268. Cache::store($cache_id, 0);
  2269. return 0;
  2270. }
  2271. // Select carrier tax
  2272. if ($use_tax && !Tax::excludeTaxeOption())
  2273. {
  2274. $address = Address::initialize((int)$address_id);
  2275. $carrier_tax = $carrier->getTaxesRate($address);
  2276. }
  2277. $configuration = Configuration::getMultiple(array(
  2278. 'PS_SHIPPING_FREE_PRICE',
  2279. 'PS_SHIPPING_HANDLING',
  2280. 'PS_SHIPPING_METHOD',
  2281. 'PS_SHIPPING_FREE_WEIGHT'
  2282. ));
  2283. // Free fees
  2284. $free_fees_price = 0;
  2285. if (isset($configuration['PS_SHIPPING_FREE_PRICE']))
  2286. $free_fees_price = Tools::convertPrice((float)$configuration['PS_SHIPPING_FREE_PRICE'], Currency::getCurrencyInstance((int)$this->id_currency));
  2287. $orderTotalwithDiscounts = $this->getOrderTotal(true, Cart::BOTH_WITHOUT_SHIPPING, null, null, false);
  2288. if ($orderTotalwithDiscounts >= (float)($free_fees_price) && (float)($free_fees_price) > 0)
  2289. {
  2290. Cache::store($cache_id, $shipping_cost);
  2291. return $shipping_cost;
  2292. }
  2293. if (isset($configuration['PS_SHIPPING_FREE_WEIGHT'])
  2294. && $this->getTotalWeight() >= (float)$configuration['PS_SHIPPING_FREE_WEIGHT']
  2295. && (float)$configuration['PS_SHIPPING_FREE_WEIGHT'] > 0)
  2296. {
  2297. Cache::store($cache_id, $shipping_cost);
  2298. return $shipping_cost;
  2299. }
  2300. // Get shipping cost using correct method
  2301. if ($carrier->range_behavior)
  2302. {
  2303. if(!isset($id_zone))
  2304. {
  2305. // Get id zone
  2306. if (isset($this->id_address_delivery)
  2307. && $this->id_address_delivery
  2308. && Customer::customerHasAddress($this->id_customer, $this->id_address_delivery))
  2309. $id_zone = Address::getZoneById((int)$this->id_address_delivery);
  2310. else
  2311. $id_zone = (int)$default_country->id_zone;
  2312. }
  2313. $check_delivery_price_by_weight = Carrier::checkDeliveryPriceByWeight((int)$carrier->id, $this->getTotalWeight(), (int)$id_zone);
  2314. // Code Review V&V TO FINISH
  2315. $check_delivery_price_by_price = Carrier::checkDeliveryPriceByPrice(
  2316. $carrier->id,
  2317. $this->getOrderTotal(
  2318. true,
  2319. Cart::BOTH_WITHOUT_SHIPPING,
  2320. $product_list
  2321. ),
  2322. $id_zone,
  2323. (int)$this->id_currency
  2324. );
  2325. if ((
  2326. $carrier->getShippingMethod() == Carrier::SHIPPING_METHOD_WEIGHT
  2327. && !$check_delivery_price_by_weight
  2328. ) || (
  2329. $carrier->getShippingMethod() == Carrier::SHIPPING_METHOD_PRICE
  2330. && !$check_delivery_price_by_price
  2331. ))
  2332. $shipping_cost += 0;
  2333. else
  2334. {
  2335. if ($carrier->getShippingMethod() == Carrier::SHIPPING_METHOD_WEIGHT)
  2336. $shipping_cost += $carrier->getDeliveryPriceByWeight($this->getTotalWeight($product_list), $id_zone);
  2337. else // by price
  2338. $shipping_cost += $carrier->getDeliveryPriceByPrice($order_total, $id_zone, (int)$this->id_currency);
  2339. }
  2340. }
  2341. else
  2342. {
  2343. if ($carrier->getShippingMethod() == Carrier::SHIPPING_METHOD_WEIGHT)
  2344. $shipping_cost += $carrier->getDeliveryPriceByWeight($this->getTotalWeight($product_list), $id_zone);
  2345. else
  2346. $shipping_cost += $carrier->getDeliveryPriceByPrice($order_total, $id_zone, (int)$this->id_currency);
  2347. }
  2348. // Adding handling charges
  2349. if (isset($configuration['PS_SHIPPING_HANDLING']) && $carrier->shipping_handling)
  2350. $shipping_cost += (float)$configuration['PS_SHIPPING_HANDLING'];
  2351. // Additional Shipping Cost per product
  2352. foreach ($products as $product)
  2353. if (!$product['is_virtual'])
  2354. $shipping_cost += $product['additional_shipping_cost'] * $product['cart_quantity'];
  2355. $shipping_cost = Tools::convertPrice($shipping_cost, Currency::getCurrencyInstance((int)$this->id_currency));
  2356. //get external shipping cost from module
  2357. if ($carrier->shipping_external)
  2358. {
  2359. $module_name = $carrier->external_module_name;
  2360. $module = Module::getInstanceByName($module_name);
  2361. if (Validate::isLoadedObject($module))
  2362. {
  2363. if (array_key_exists('id_carrier', $module))
  2364. $module->id_carrier = $carrier->id;
  2365. if ($carrier->need_range)
  2366. if (method_exists($module, 'getPackageShippingCost'))
  2367. $shipping_cost = $module->getPackageShippingCost($this, $shipping_cost, $products);
  2368. else
  2369. $shipping_cost = $module->getOrderShippingCost($this, $shipping_cost);
  2370. else
  2371. $shipping_cost = $module->getOrderShippingCostExternal($this);
  2372. // Check if carrier is available
  2373. if ($shipping_cost === false)
  2374. {
  2375. Cache::store($cache_id, false);
  2376. return false;
  2377. }
  2378. }
  2379. else
  2380. {
  2381. Cache::store($cache_id, false);
  2382. return false;
  2383. }
  2384. }
  2385. // Apply tax
  2386. if ($use_tax && isset($carrier_tax))
  2387. $shipping_cost *= 1 + ($carrier_tax / 100);
  2388. $shipping_cost = (float)Tools::ps_round((float)$shipping_cost, 2);
  2389. Cache::store($cache_id, $shipping_cost);
  2390. return $shipping_cost;
  2391. }
  2392. /**
  2393. * Return cart weight
  2394. * @return float Cart weight
  2395. */
  2396. public function getTotalWeight($products = null)
  2397. {
  2398. if (!is_null($products))
  2399. {
  2400. $total_weight = 0;
  2401. foreach ($products as $product)
  2402. {
  2403. if (!isset($product['weight_attribute']) || is_null($product['weight_attribute']))
  2404. $total_weight += $product['weight'] * $product['cart_quantity'];
  2405. else
  2406. $total_weight += $product['weight_attribute'] * $product['cart_quantity'];
  2407. }
  2408. return $total_weight;
  2409. }
  2410. if (!isset(self::$_totalWeight[$this->id]))
  2411. {
  2412. if (Combination::isFeatureActive())
  2413. $weight_product_with_attribute = Db::getInstance()->getValue('
  2414. SELECT SUM((p.`weight` + pa.`weight`) * cp.`quantity`) as nb
  2415. FROM `'._DB_PREFIX_.'cart_product` cp
  2416. LEFT JOIN `'._DB_PREFIX_.'product` p ON (cp.`id_product` = p.`id_product`)
  2417. LEFT JOIN `'._DB_PREFIX_.'product_attribute` pa ON (cp.`id_product_attribute` = pa.`id_product_attribute`)
  2418. WHERE (cp.`id_product_attribute` IS NOT NULL AND cp.`id_product_attribute` != 0)
  2419. AND cp.`id_cart` = '.(int)$this->id);
  2420. else
  2421. $weight_product_with_attribute = 0;
  2422. $weight_product_without_attribute = Db::getInstance()->getValue('
  2423. SELECT SUM(p.`weight` * cp.`quantity`) as nb
  2424. FROM `'._DB_PREFIX_.'cart_product` cp
  2425. LEFT JOIN `'._DB_PREFIX_.'product` p ON (cp.`id_product` = p.`id_product`)
  2426. WHERE (cp.`id_product_attribute` IS NULL OR cp.`id_product_attribute` = 0)
  2427. AND cp.`id_cart` = '.(int)$this->id);
  2428. self::$_totalWeight[$this->id] = round((float)$weight_product_with_attribute + (float)$weight_product_without_attribute, 3);
  2429. }
  2430. return self::$_totalWeight[$this->id];
  2431. }
  2432. /**
  2433. * @deprecated 1.5.0
  2434. */
  2435. public function checkDiscountValidity($obj, $discounts, $order_total, $products, $check_cart_discount = false)
  2436. {
  2437. Tools::displayAsDeprecated();
  2438. $context = Context::getContext()->cloneContext();
  2439. $context->cart = $this;
  2440. return $obj->checkValidity($context);
  2441. }
  2442. /**
  2443. * Return useful informations for cart
  2444. *
  2445. * @return array Cart details
  2446. */
  2447. public function getSummaryDetails($id_lang = null, $refresh = false)
  2448. {
  2449. $context = Context::getContext();
  2450. if (!$id_lang)
  2451. $id_lang = $context->language->id;
  2452. $delivery = new Address((int)$this->id_address_delivery);
  2453. $invoice = new Address((int)$this->id_address_invoice);
  2454. // New layout system with personalization fields
  2455. $formatted_addresses['delivery'] = AddressFormat::getFormattedLayoutData($delivery);
  2456. $formatted_addresses['invoice'] = AddressFormat::getFormattedLayoutData($invoice);
  2457. $total_tax = $this->getOrderTotal() - $this->getOrderTotal(false);
  2458. if ($total_tax < 0)
  2459. $total_tax = 0;
  2460. $currency = new Currency($this->id_currency);
  2461. $products = $this->getProducts($refresh);
  2462. $gift_products = array();
  2463. $cart_rules = $this->getCartRules();
  2464. $total_shipping = $this->getTotalShippingCost();
  2465. $total_shipping_tax_exc = $this->getTotalShippingCost(null, false);
  2466. $total_products_wt = $this->getOrderTotal(true, Cart::ONLY_PRODUCTS);
  2467. $total_products = $this->getOrderTotal(false, Cart::ONLY_PRODUCTS);
  2468. $total_discounts = $this->getOrderTotal(true, Cart::ONLY_DISCOUNTS);
  2469. $total_discounts_tax_exc = $this->getOrderTotal(false, Cart::ONLY_DISCOUNTS);
  2470. // The cart content is altered for display
  2471. foreach ($cart_rules as &$cart_rule)
  2472. {
  2473. // If the cart rule is automatic (wihtout any code) and include free shipping, it should not be displayed as a cart rule but only set the shipping cost to 0
  2474. if ($cart_rule['free_shipping'] && (empty($cart_rule['code']) || preg_match('/^'.CartRule::BO_ORDER_CODE_PREFIX.'[0-9]+/', $cart_rule['code'])))
  2475. {
  2476. $cart_rule['value_real'] -= $total_shipping;
  2477. $cart_rule['value_tax_exc'] -= $total_shipping_tax_exc;
  2478. $cart_rule['value_real'] = Tools::ps_round($cart_rule['value_real'], (int)$context->currency->decimals * _PS_PRICE_DISPLAY_PRECISION_);
  2479. $cart_rule['value_tax_exc'] = Tools::ps_round($cart_rule['value_tax_exc'], (int)$context->currency->decimals * _PS_PRICE_DISPLAY_PRECISION_);
  2480. if ($total_discounts > $cart_rule['value_real'])
  2481. $total_discounts -= $total_shipping;
  2482. if ($total_discounts_tax_exc > $cart_rule['value_tax_exc'])
  2483. $total_discounts_tax_exc -= $total_shipping_tax_exc;
  2484. // Update total shipping
  2485. $total_shipping = 0;
  2486. $total_shipping_tax_exc = 0;
  2487. }
  2488. if ($cart_rule['gift_product'])
  2489. {
  2490. foreach ($products as $key => &$product)
  2491. if (empty($product['gift']) && $product['id_product'] == $cart_rule['gift_product'] && $product['id_product_attribute'] == $cart_rule['gift_product_attribute'])
  2492. {
  2493. // Update total products
  2494. $total_products_wt = Tools::ps_round($total_products_wt - $product['price_wt'], (int)$context->currency->decimals * _PS_PRICE_DISPLAY_PRECISION_);
  2495. $total_products = Tools::ps_round($total_products - $product['price'], (int)$context->currency->decimals * _PS_PRICE_DISPLAY_PRECISION_);
  2496. // Update total discounts
  2497. $total_discounts = Tools::ps_round($total_discounts - $product['price_wt'], (int)$context->currency->decimals * _PS_PRICE_DISPLAY_PRECISION_);
  2498. $total_discounts_tax_exc = Tools::ps_round($total_discounts_tax_exc - $product['price'], (int)$context->currency->decimals * _PS_PRICE_DISPLAY_PRECISION_);
  2499. // Update cart rule value
  2500. $cart_rule['value_real'] = Tools::ps_round($cart_rule['value_real'] - $product['price_wt'], (int)$context->currency->decimals * _PS_PRICE_DISPLAY_PRECISION_);
  2501. $cart_rule['value_tax_exc'] = Tools::ps_round($cart_rule['value_tax_exc'] - $product['price'], (int)$context->currency->decimals * _PS_PRICE_DISPLAY_PRECISION_);
  2502. // Update product quantity
  2503. $product['total_wt'] = Tools::ps_round($product['total_wt'] - $product['price_wt'], (int)$currency->decimals * _PS_PRICE_DISPLAY_PRECISION_);
  2504. $product['total'] = Tools::ps_round($product['total'] - $product['price'], (int)$currency->decimals * _PS_PRICE_DISPLAY_PRECISION_);
  2505. $product['cart_quantity']--;
  2506. if (!$product['cart_quantity'])
  2507. unset($products[$key]);
  2508. // Add a new product line
  2509. $gift_product = $product;
  2510. $gift_product['cart_quantity'] = 1;
  2511. $gift_product['price'] = 0;
  2512. $gift_product['price_wt'] = 0;
  2513. $gift_product['total_wt'] = 0;
  2514. $gift_product['total'] = 0;
  2515. $gift_product['gift'] = true;
  2516. $gift_products[] = $gift_product;
  2517. break; // One gift product per cart rule
  2518. }
  2519. }
  2520. }
  2521. foreach ($cart_rules as $key => &$cart_rule)
  2522. if ($cart_rule['value_real'] == 0)
  2523. unset($cart_rules[$key]);
  2524. return array(
  2525. 'delivery' => $delivery,
  2526. 'delivery_state' => State::getNameById($delivery->id_state),
  2527. 'invoice' => $invoice,
  2528. 'invoice_state' => State::getNameById($invoice->id_state),
  2529. 'formattedAddresses' => $formatted_addresses,
  2530. 'products' => array_values($products),
  2531. 'gift_products' => $gift_products,
  2532. 'discounts' => $cart_rules,
  2533. 'is_virtual_cart' => (int)$this->isVirtualCart(),
  2534. 'total_discounts' => $total_discounts,
  2535. 'total_discounts_tax_exc' => $total_discounts_tax_exc,
  2536. 'total_wrapping' => $this->getOrderTotal(true, Cart::ONLY_WRAPPING),
  2537. 'total_wrapping_tax_exc' => $this->getOrderTotal(false, Cart::ONLY_WRAPPING),
  2538. 'total_shipping' => $total_shipping,
  2539. 'total_shipping_tax_exc' => $total_shipping_tax_exc,
  2540. 'total_products_wt' => $total_products_wt,
  2541. 'total_products' => $total_products,
  2542. 'total_price' => $this->getOrderTotal(),
  2543. 'total_tax' => $total_tax,
  2544. 'total_price_without_tax' => $this->getOrderTotal(false),
  2545. 'is_multi_address_delivery' => $this->isMultiAddressDelivery() || ((int)Tools::getValue('multi-shipping') == 1),
  2546. 'free_ship' => $total_shipping ? 0 : 1,
  2547. 'carrier' => new Carrier($this->id_carrier, $id_lang),
  2548. );
  2549. }
  2550. public function checkQuantities()
  2551. {
  2552. if (Configuration::get('PS_CATALOG_MODE'))
  2553. return false;
  2554. foreach ($this->getProducts() as $product)
  2555. if (!$product['active']
  2556. || (
  2557. !$product['allow_oosp'] && $product['stock_quantity'] < $product['cart_quantity']
  2558. )
  2559. || !$product['available_for_order'])
  2560. return false;
  2561. return true;
  2562. }
  2563. public static function lastNoneOrderedCart($id_customer)
  2564. {
  2565. $sql = 'SELECT c.`id_cart`
  2566. FROM '._DB_PREFIX_.'cart c
  2567. WHERE c.`id_cart` NOT IN (SELECT o.`id_cart` FROM '._DB_PREFIX_.'orders o WHERE o.`id_customer` = '.(int)$id_customer.')
  2568. AND c.`id_customer` = '.(int)$id_customer.'
  2569. '.Shop::addSqlRestriction(Shop::SHARE_ORDER, 'c').'
  2570. ORDER BY c.`date_upd` DESC';
  2571. if (!$id_cart = Db::getInstance()->getValue($sql))
  2572. return false;
  2573. return (int)$id_cart;
  2574. }
  2575. /**
  2576. * Check if cart contains only virtual products
  2577. *
  2578. * @return boolean true if is a virtual cart or false
  2579. */
  2580. public function isVirtualCart($strict = false)
  2581. {
  2582. if (!ProductDownload::isFeatureActive())
  2583. return false;
  2584. if (!isset(self::$_isVirtualCart[$this->id]))
  2585. {
  2586. $products = $this->getProducts();
  2587. if (!count($products))
  2588. return false;
  2589. $is_virtual = 1;
  2590. foreach ($products as $product)
  2591. {
  2592. if (empty($product['is_virtual']))
  2593. $is_virtual = 0;
  2594. }
  2595. self::$_isVirtualCart[$this->id] = (int)$is_virtual;
  2596. }
  2597. return self::$_isVirtualCart[$this->id];
  2598. }
  2599. /**
  2600. * Build cart object from provided id_order
  2601. *
  2602. * @param int $id_order
  2603. * @return Cart|bool
  2604. */
  2605. public static function getCartByOrderId($id_order)
  2606. {
  2607. if ($id_cart = Cart::getCartIdByOrderId($id_order))
  2608. return new Cart((int)$id_cart);
  2609. return false;
  2610. }
  2611. public static function getCartIdByOrderId($id_order)
  2612. {
  2613. $result = Db::getInstance()->getRow('SELECT `id_cart` FROM '._DB_PREFIX_.'orders WHERE `id_order` = '.(int)$id_order);
  2614. if (!$result || empty($result) || !key_exists('id_cart', $result))
  2615. return false;
  2616. return $result['id_cart'];
  2617. }
  2618. /**
  2619. * Add customer's text
  2620. *
  2621. * @params int $id_product
  2622. * @params int $index
  2623. * @params int $type
  2624. * @params string $textValue
  2625. *
  2626. * @return bool Always true
  2627. */
  2628. public function addTextFieldToProduct($id_product, $index, $type, $text_value)
  2629. {
  2630. $text_value = str_replace(array("\n", "\r"), '', nl2br($text_value));
  2631. $text_value = str_replace('\\', '\\\\', $text_value);
  2632. $text_value = str_replace('\'', '\\\'', $text_value);
  2633. return $this->_addCustomization($id_product, 0, $index, $type, $text_value, 0);
  2634. }
  2635. /**
  2636. * Add customer's pictures
  2637. *
  2638. * @return bool Always true
  2639. */
  2640. public function addPictureToProduct($id_product, $index, $type, $file)
  2641. {
  2642. return $this->_addCustomization($id_product, 0, $index, $type, $file, 0);
  2643. }
  2644. public function deletePictureToProduct($id_product, $index)
  2645. {
  2646. Tools::displayAsDeprecated();
  2647. return $this->deleteCustomizationToProduct($id_product, 0);
  2648. }
  2649. /**
  2650. * Remove a customer's customization
  2651. *
  2652. * @param int $id_product
  2653. * @param int $index
  2654. * @return bool
  2655. */
  2656. public function deleteCustomizationToProduct($id_product, $index)
  2657. {
  2658. $result = true;
  2659. $cust_data = Db::getInstance()->getRow('
  2660. SELECT cu.`id_customization`, cd.`index`, cd.`value`, cd.`type` FROM `'._DB_PREFIX_.'customization` cu
  2661. LEFT JOIN `'._DB_PREFIX_.'customized_data` cd
  2662. ON cu.`id_customization` = cd.`id_customization`
  2663. WHERE cu.`id_cart` = '.(int)$this->id.'
  2664. AND cu.`id_product` = '.(int)$id_product.'
  2665. AND `index` = '.(int)$index.'
  2666. AND `in_cart` = 0'
  2667. );
  2668. // Delete customization picture if necessary
  2669. if ($cust_data['type'] == 0)
  2670. $result &= (@unlink(_PS_UPLOAD_DIR_.$cust_data['value']) && @unlink(_PS_UPLOAD_DIR_.$cust_data['value'].'_small'));
  2671. $result &= Db::getInstance()->execute('DELETE
  2672. FROM `'._DB_PREFIX_.'customized_data`
  2673. WHERE `id_customization` = '.(int)$cust_data['id_customization'].'
  2674. AND `index` = '.(int)$index
  2675. );
  2676. return $result;
  2677. }
  2678. /**
  2679. * Return custom pictures in this cart for a specified product
  2680. *
  2681. * @param int $id_product
  2682. * @param int $type only return customization of this type
  2683. * @param bool $not_in_cart only return customizations that are not in cart already
  2684. * @return array result rows
  2685. */
  2686. public function getProductCustomization($id_product, $type = null, $not_in_cart = false)
  2687. {
  2688. if (!Customization::isFeatureActive())
  2689. return array();
  2690. $result = Db::getInstance()->executeS('
  2691. SELECT cu.id_customization, cd.index, cd.value, cd.type, cu.in_cart, cu.quantity
  2692. FROM `'._DB_PREFIX_.'customization` cu
  2693. LEFT JOIN `'._DB_PREFIX_.'customized_data` cd ON (cu.`id_customization` = cd.`id_customization`)
  2694. WHERE cu.id_cart = '.(int)$this->id.'
  2695. AND cu.id_product = '.(int)$id_product.
  2696. ($type === Product::CUSTOMIZE_FILE ? ' AND type = '.(int)Product::CUSTOMIZE_FILE : '').
  2697. ($type === Product::CUSTOMIZE_TEXTFIELD ? ' AND type = '.(int)Product::CUSTOMIZE_TEXTFIELD : '').
  2698. ($not_in_cart ? ' AND in_cart = 0' : '')
  2699. );
  2700. return $result;
  2701. }
  2702. public static function getCustomerCarts($id_customer, $with_order = true)
  2703. {
  2704. return Db::getInstance(_PS_USE_SQL_SLAVE_)->executeS('
  2705. SELECT *
  2706. FROM '._DB_PREFIX_.'cart c
  2707. WHERE c.`id_customer` = '.(int)$id_customer.'
  2708. '.(!$with_order ? 'AND id_cart NOT IN (SELECT id_cart FROM '._DB_PREFIX_.'orders o)' : '').'
  2709. ORDER BY c.`date_add` DESC');
  2710. }
  2711. public static function replaceZeroByShopName($echo, $tr)
  2712. {
  2713. return ($echo == '0' ? Configuration::get('PS_SHOP_NAME') : $echo);
  2714. }
  2715. public function duplicate()
  2716. {
  2717. if (!Validate::isLoadedObject($this))
  2718. return false;
  2719. $cart = new Cart($this->id);
  2720. $cart->id = null;
  2721. $cart->id_shop = $this->id_shop;
  2722. $cart->id_shop_group = $this->id_shop_group;
  2723. $cart->add();
  2724. if (!Validate::isLoadedObject($cart))
  2725. return false;
  2726. $success = true;
  2727. $products = Db::getInstance(_PS_USE_SQL_SLAVE_)->executeS('SELECT * FROM `'._DB_PREFIX_.'cart_product` WHERE `id_cart` = '.(int)$this->id);
  2728. foreach ($products as $product)
  2729. $success &= $cart->updateQty(
  2730. $product['quantity'],
  2731. (int)$product['id_product'],
  2732. (int)$product['id_product_attribute'],
  2733. null,
  2734. 'up',
  2735. (int)$product['id_address_delivery'],
  2736. new Shop($cart->id_shop)
  2737. );
  2738. // Customized products
  2739. $customs = Db::getInstance(_PS_USE_SQL_SLAVE_)->executeS('
  2740. SELECT *
  2741. FROM '._DB_PREFIX_.'customization c
  2742. LEFT JOIN '._DB_PREFIX_.'customized_data cd ON cd.id_customization = c.id_customization
  2743. WHERE c.id_cart = '.(int)$this->id
  2744. );
  2745. // Get datas from customization table
  2746. $customs_by_id = array();
  2747. foreach ($customs as $custom)
  2748. {
  2749. if (!isset($customs_by_id[$custom['id_customization']]))
  2750. $customs_by_id[$custom['id_customization']] = array(
  2751. 'id_product_attribute' => $custom['id_product_attribute'],
  2752. 'id_product' => $custom['id_product'],
  2753. 'quantity' => $custom['quantity']
  2754. );
  2755. }
  2756. // Insert new customizations
  2757. $custom_ids = array();
  2758. foreach ($customs_by_id as $customization_id => $val)
  2759. {
  2760. Db::getInstance()->execute('
  2761. INSERT INTO `'._DB_PREFIX_.'customization` (id_cart, id_product_attribute, id_product, `id_address_delivery`, quantity, `quantity_refunded`, `quantity_returned`, `in_cart`)
  2762. VALUES('.(int)$cart->id.', '.(int)$val['id_product_attribute'].', '.(int)$val['id_product'].', '.(int)$this->id_address_delivery.', '.(int)$val['quantity'].', 0, 0, 1)'
  2763. );
  2764. $custom_ids[$customization_id] = Db::getInstance(_PS_USE_SQL_SLAVE_)->Insert_ID();
  2765. }
  2766. // Insert customized_data
  2767. if (count($customs))
  2768. {
  2769. $first = true;
  2770. $sql_custom_data = 'INSERT INTO '._DB_PREFIX_.'customized_data (`id_customization`, `type`, `index`, `value`) VALUES ';
  2771. foreach ($customs as $custom)
  2772. {
  2773. if (!$first)
  2774. $sql_custom_data .= ',';
  2775. else
  2776. $first = false;
  2777. $sql_custom_data .= '('.(int)$custom_ids[$custom['id_customization']].', '.(int)$custom['type'].', '.
  2778. (int)$custom['index'].', \''.pSQL($custom['value']).'\')';
  2779. }
  2780. Db::getInstance()->execute($sql_custom_data);
  2781. }
  2782. return array('cart' => $cart, 'success' => $success);
  2783. }
  2784. public function getWsCartRows()
  2785. {
  2786. $query = '
  2787. SELECT id_product, id_product_attribute, quantity
  2788. FROM `'._DB_PREFIX_.'cart_product`
  2789. WHERE id_cart = '.(int)$this->id.'
  2790. AND id_shop = '.(int)Context::getContext()->shop->id;
  2791. $result = Db::getInstance()->executeS($query);
  2792. return $result;
  2793. }
  2794. public function setWsCartRows($values)
  2795. {
  2796. if ($this->deleteAssociations())
  2797. {
  2798. $query = 'INSERT INTO `'._DB_PREFIX_.'cart_product`(`id_cart`, `id_product`, `id_product_attribute`, `quantity`, `date_add`, `id_shop`) VALUES ';
  2799. foreach ($values as $value)
  2800. $query .= '('.(int)$this->id.', '.(int)$value['id_product'].', '.
  2801. (isset($value['id_product_attribute']) ? (int)$value['id_product_attribute'] : 'NULL').', '.(int)$value['quantity'].', NOW(), '.(int)Context::getContext()->shop->id.'),';
  2802. Db::getInstance()->execute(rtrim($query, ','));
  2803. }
  2804. return true;
  2805. }
  2806. public function setProductAddressDelivery($id_product, $id_product_attribute, $old_id_address_delivery, $new_id_address_delivery)
  2807. {
  2808. // Check address is linked with the customer
  2809. if (!Customer::customerHasAddress(Context::getContext()->customer->id, $new_id_address_delivery))
  2810. return false;
  2811. if ($new_id_address_delivery == $old_id_address_delivery)
  2812. return false;
  2813. // Checking if the product with the old address delivery exists
  2814. $sql = new DbQuery();
  2815. $sql->select('count(*)');
  2816. $sql->from('cart_product', 'cp');
  2817. $sql->where('id_product = '.(int)$id_product);
  2818. $sql->where('id_product_attribute = '.(int)$id_product_attribute);
  2819. $sql->where('id_address_delivery = '.(int)$old_id_address_delivery);
  2820. $sql->where('id_cart = '.(int)$this->id);
  2821. $result = Db::getInstance()->getValue($sql);
  2822. if ($result == 0)
  2823. return false;
  2824. // Checking if there is no others similar products with this new address delivery
  2825. $sql = new DbQuery();
  2826. $sql->select('sum(quantity) as qty');
  2827. $sql->from('cart_product', 'cp');
  2828. $sql->where('id_product = '.(int)$id_product);
  2829. $sql->where('id_product_attribute = '.(int)$id_product_attribute);
  2830. $sql->where('id_address_delivery = '.(int)$new_id_address_delivery);
  2831. $sql->where('id_cart = '.(int)$this->id);
  2832. $result = Db::getInstance()->getValue($sql);
  2833. // Removing similar products with this new address delivery
  2834. $sql = 'DELETE FROM '._DB_PREFIX_.'cart_product
  2835. WHERE id_product = '.(int)$id_product.'
  2836. AND id_product_attribute = '.(int)$id_product_attribute.'
  2837. AND id_address_delivery = '.(int)$new_id_address_delivery.'
  2838. AND id_cart = '.(int)$this->id.'
  2839. LIMIT 1';
  2840. Db::getInstance()->execute($sql);
  2841. // Changing the address
  2842. $sql = 'UPDATE '._DB_PREFIX_.'cart_product
  2843. SET `id_address_delivery` = '.(int)$new_id_address_delivery.',
  2844. `quantity` = `quantity` + '.(int)$result['sum'].'
  2845. WHERE id_product = '.(int)$id_product.'
  2846. AND id_product_attribute = '.(int)$id_product_attribute.'
  2847. AND id_address_delivery = '.(int)$old_id_address_delivery.'
  2848. AND id_cart = '.(int)$this->id.'
  2849. LIMIT 1';
  2850. Db::getInstance()->execute($sql);
  2851. // Changing the address of the customizations
  2852. $sql = 'UPDATE '._DB_PREFIX_.'customization
  2853. SET `id_address_delivery` = '.(int)$new_id_address_delivery.'
  2854. WHERE id_product = '.(int)$id_product.'
  2855. AND id_product_attribute = '.(int)$id_product_attribute.'
  2856. AND id_address_delivery = '.(int)$old_id_address_delivery.'
  2857. AND id_cart = '.(int)$this->id;
  2858. Db::getInstance()->execute($sql);
  2859. return true;
  2860. }
  2861. public function duplicateProduct($id_product, $id_product_attribute, $id_address_delivery,
  2862. $new_id_address_delivery, $quantity = 1, $keep_quantity = false)
  2863. {
  2864. // Check address is linked with the customer
  2865. if (!Customer::customerHasAddress(Context::getContext()->customer->id, $new_id_address_delivery))
  2866. return false;
  2867. // Checking the product do not exist with the new address
  2868. $sql = new DbQuery();
  2869. $sql->select('count(*)');
  2870. $sql->from('cart_product', 'c');
  2871. $sql->where('id_product = '.(int)$id_product);
  2872. $sql->where('id_product_attribute = '.(int)$id_product_attribute);
  2873. $sql->where('id_address_delivery = '.(int)$new_id_address_delivery);
  2874. $sql->where('id_cart = '.(int)$this->id);
  2875. $result = Db::getInstance()->getValue($sql);
  2876. if ($result > 0)
  2877. return false;
  2878. // Duplicating cart_product line
  2879. $sql = 'INSERT INTO '._DB_PREFIX_.'cart_product
  2880. (`id_cart`, `id_product`, `id_shop`, `id_product_attribute`, `quantity`, `date_add`, `id_address_delivery`)
  2881. values(
  2882. '.(int)$this->id.',
  2883. '.(int)$id_product.',
  2884. '.(int)$this->id_shop.',
  2885. '.(int)$id_product_attribute.',
  2886. '.(int)$quantity.',
  2887. NOW(),
  2888. '.(int)$new_id_address_delivery.')';
  2889. Db::getInstance()->execute($sql);
  2890. if (!$keep_quantity)
  2891. {
  2892. $sql = new DbQuery();
  2893. $sql->select('quantity');
  2894. $sql->from('cart_product', 'c');
  2895. $sql->where('id_product = '.(int)$id_product);
  2896. $sql->where('id_product_attribute = '.(int)$id_product_attribute);
  2897. $sql->where('id_address_delivery = '.(int)$id_address_delivery);
  2898. $sql->where('id_cart = '.(int)$this->id);
  2899. $duplicatedQuantity = Db::getInstance()->getValue($sql);
  2900. if ($duplicatedQuantity > $quantity)
  2901. {
  2902. $sql = 'UPDATE '._DB_PREFIX_.'cart_product
  2903. SET `quantity` = `quantity` - '.(int)$quantity.'
  2904. WHERE id_cart = '.(int)$this->id.'
  2905. AND id_product = '.(int)$id_product.'
  2906. AND id_shop = '.(int)$this->id_shop.'
  2907. AND id_product_attribute = '.(int)$id_product_attribute.'
  2908. AND id_address_delivery = '.(int)$id_address_delivery;
  2909. Db::getInstance()->execute($sql);
  2910. }
  2911. }
  2912. // Checking if there is customizations
  2913. $sql = new DbQuery();
  2914. $sql->select('*');
  2915. $sql->from('customization', 'c');
  2916. $sql->where('id_product = '.(int)$id_product);
  2917. $sql->where('id_product_attribute = '.(int)$id_product_attribute);
  2918. $sql->where('id_address_delivery = '.(int)$id_address_delivery);
  2919. $sql->where('id_cart = '.(int)$this->id);
  2920. $results = Db::getInstance()->executeS($sql);
  2921. foreach ($results as $customization)
  2922. {
  2923. // Duplicate customization
  2924. $sql = 'INSERT INTO '._DB_PREFIX_.'customization
  2925. (`id_product_attribute`, `id_address_delivery`, `id_cart`, `id_product`, `quantity`, `in_cart`)
  2926. VALUES (
  2927. '.$customization['id_product_attribute'].',
  2928. '.$new_id_address_delivery.',
  2929. '.$customization['id_cart'].',
  2930. '.$customization['id_product'].',
  2931. '.$quantity.',
  2932. '.$customization['in_cart'].')';
  2933. Db::getInstance()->execute($sql);
  2934. $sql = 'INSERT INTO '._DB_PREFIX_.'customized_data(`id_customization`, `type`, `index`, `value`)
  2935. (
  2936. SELECT '.(int)Db::getInstance()->Insert_ID().' `id_customization`, `type`, `index`, `value`
  2937. FROM customized_data
  2938. WHERE id_customization = '.$customization['id_customization'].'
  2939. )';
  2940. Db::getInstance()->execute($sql);
  2941. }
  2942. $customization_count = count($results);
  2943. if ($customization_count > 0)
  2944. {
  2945. $sql = 'UPDATE '._DB_PREFIX_.'cart_product
  2946. SET `quantity` = `quantity` = '.(int)$customization_count * $quantity.'
  2947. WHERE id_cart = '.(int)$this->id.'
  2948. AND id_product = '.(int)$id_product.'
  2949. AND id_shop = '.(int)$this->id_shop.'
  2950. AND id_product_attribute = '.(int)$id_product_attribute.'
  2951. AND id_address_delivery = '.(int)$new_id_address_delivery;
  2952. Db::getInstance()->execute($sql);
  2953. }
  2954. return true;
  2955. }
  2956. /**
  2957. * Update products cart address delivery with the address delivery of the cart
  2958. */
  2959. public function setNoMultishipping()
  2960. {
  2961. // Upgrading quantities
  2962. $sql = 'SELECT sum(`quantity`) as quantity, id_product, id_product_attribute, count(*) as count
  2963. FROM `'._DB_PREFIX_.'cart_product`
  2964. WHERE `id_cart` = '.(int)$this->id.'
  2965. AND `id_shop` = '.(int)$this->id_shop.'
  2966. GROUP BY id_product, id_product_attribute
  2967. HAVING count > 1';
  2968. foreach (Db::getInstance()->executeS($sql) as $product)
  2969. {
  2970. $sql = 'UPDATE `'._DB_PREFIX_.'cart_product`
  2971. SET `quantity` = '.$product['quantity'].'
  2972. WHERE `id_cart` = '.(int)$this->id.'
  2973. AND `id_shop` = '.(int)$this->id_shop.'
  2974. AND id_product = '.$product['id_product'].'
  2975. AND id_product_attribute = '.$product['id_product_attribute'];
  2976. Db::getInstance()->execute($sql);
  2977. }
  2978. // Merging multiple lines
  2979. $sql = 'DELETE cp1
  2980. FROM `'._DB_PREFIX_.'cart_product` cp1
  2981. INNER JOIN `'._DB_PREFIX_.'cart_product` cp2
  2982. ON (
  2983. (cp1.id_cart = cp2.id_cart)
  2984. AND (cp1.id_product = cp2.id_product)
  2985. AND (cp1.id_product_attribute = cp2.id_product_attribute)
  2986. AND (cp1.id_address_delivery <> cp2.id_address_delivery)
  2987. AND (cp1.date_add > cp2.date_add)
  2988. )';
  2989. Db::getInstance()->execute($sql);
  2990. // Upgrading address delivery
  2991. $sql = 'UPDATE `'._DB_PREFIX_.'cart_product`
  2992. SET `id_address_delivery` =
  2993. (
  2994. SELECT `id_address_delivery`
  2995. FROM `'._DB_PREFIX_.'cart`
  2996. WHERE `id_cart` = '.(int)$this->id.'
  2997. AND `id_shop` = '.(int)$this->id_shop.'
  2998. )
  2999. WHERE `id_cart` = '.(int)$this->id.'
  3000. '.(Configuration::get('PS_ALLOW_MULTISHIPPING') ? ' AND `id_shop` = '.(int)$this->id_shop : '');
  3001. Db::getInstance()->execute($sql);
  3002. $sql = 'UPDATE `'._DB_PREFIX_.'customization`
  3003. SET `id_address_delivery` =
  3004. (
  3005. SELECT `id_address_delivery`
  3006. FROM `'._DB_PREFIX_.'cart`
  3007. WHERE `id_cart` = '.(int)$this->id.'
  3008. )
  3009. WHERE `id_cart` = '.(int)$this->id;
  3010. Db::getInstance()->execute($sql);
  3011. }
  3012. /**
  3013. * Set an address to all products on the cart without address delivery
  3014. */
  3015. public function autosetProductAddress()
  3016. {
  3017. $id_address_delivery = 0;
  3018. // Get the main address of the customer
  3019. if ((int)$this->id_address_delivery > 0)
  3020. $id_address_delivery = (int)$this->id_address_delivery;
  3021. else
  3022. $id_address_delivery = (int)Address::getFirstCustomerAddressId(Context::getContext()->customer->id);
  3023. if (!$id_address_delivery)
  3024. return;
  3025. // Update
  3026. $sql = 'UPDATE `'._DB_PREFIX_.'cart_product`
  3027. SET `id_address_delivery` = '.(int)$id_address_delivery.'
  3028. WHERE `id_cart` = '.(int)$this->id.'
  3029. AND (`id_address_delivery` = 0 OR `id_address_delivery` IS NULL)
  3030. AND `id_shop` = '.(int)$this->id_shop;
  3031. Db::getInstance()->execute($sql);
  3032. $sql = 'UPDATE `'._DB_PREFIX_.'customization`
  3033. SET `id_address_delivery` = '.(int)$id_address_delivery.'
  3034. WHERE `id_cart` = '.(int)$this->id.'
  3035. AND (`id_address_delivery` = 0 OR `id_address_delivery` IS NULL)';
  3036. Db::getInstance()->execute($sql);
  3037. }
  3038. public function deleteAssociations()
  3039. {
  3040. return (Db::getInstance()->execute('
  3041. DELETE FROM `'._DB_PREFIX_.'cart_product`
  3042. WHERE `id_cart` = '.(int)$this->id) !== false);
  3043. }
  3044. /**
  3045. * isGuestCartByCartId
  3046. *
  3047. * @param int $id_cart
  3048. * @return bool true if cart has been made by a guest customer
  3049. */
  3050. public static function isGuestCartByCartId($id_cart)
  3051. {
  3052. if (!(int)$id_cart)
  3053. return false;
  3054. return (bool)Db::getInstance()->getValue('
  3055. SELECT `is_guest`
  3056. FROM `'._DB_PREFIX_.'customer` cu
  3057. LEFT JOIN `'._DB_PREFIX_.'cart` ca ON (ca.`id_customer` = cu.`id_customer`)
  3058. WHERE ca.`id_cart` = '.(int)$id_cart);
  3059. }
  3060. /**
  3061. * isCarrierInRange
  3062. *
  3063. * Check if the specified carrier is in range
  3064. *
  3065. * @id_carrier int
  3066. * @id_zone int
  3067. */
  3068. public function isCarrierInRange($id_carrier, $id_zone)
  3069. {
  3070. $carrier = new Carrier((int)$id_carrier, Configuration::get('PS_LANG_DEFAULT'));
  3071. $shipping_method = $carrier->getShippingMethod();
  3072. if (!$carrier->range_behavior)
  3073. return true;
  3074. if ($shipping_method == Carrier::SHIPPING_METHOD_FREE)
  3075. return true;
  3076. $check_delivery_price_by_weight = Carrier::checkDeliveryPriceByWeight(
  3077. (int)$id_carrier,
  3078. $this->getTotalWeight(),
  3079. $id_zone
  3080. );
  3081. if ($shipping_method == Carrier::SHIPPING_METHOD_WEIGHT && $check_delivery_price_by_weight)
  3082. return true;
  3083. $check_delivery_price_by_price = Carrier::checkDeliveryPriceByPrice(
  3084. (int)$id_carrier,
  3085. $this->getOrderTotal(
  3086. true,
  3087. Cart::BOTH_WITHOUT_SHIPPING
  3088. ),
  3089. $id_zone,
  3090. (int)$this->id_currency
  3091. );
  3092. if ($shipping_method == Carrier::SHIPPING_METHOD_PRICE && $check_delivery_price_by_price)
  3093. return true;
  3094. return false;
  3095. }
  3096. /**
  3097. * @param bool $ignore_virtual Ignore virtual product
  3098. * @param bool $exclusive If true, the validation is exclusive : it must be present product in stock and out of stock
  3099. * @since 1.5.0
  3100. *
  3101. * @return bool false is some products from the cart are out of stock
  3102. */
  3103. public function isAllProductsInStock($ignore_virtual = false, $exclusive = false)
  3104. {
  3105. $product_out_of_stock = 0;
  3106. $product_in_stock = 0;
  3107. foreach ($this->getProducts() as $product)
  3108. {
  3109. if (!$exclusive)
  3110. {
  3111. if ((int)$product['quantity_available'] <= 0
  3112. && (!$ignore_virtual || !$product['is_virtual']))
  3113. return false;
  3114. }
  3115. else
  3116. {
  3117. if ((int)$product['quantity_available'] <= 0
  3118. && (!$ignore_virtual || !$product['is_virtual']))
  3119. $product_out_of_stock++;
  3120. if ((int)$product['quantity_available'] > 0
  3121. && (!$ignore_virtual || !$product['is_virtual']))
  3122. $product_in_stock++;
  3123. if ($product_in_stock > 0 && $product_out_of_stock > 0)
  3124. return false;
  3125. }
  3126. }
  3127. return true;
  3128. }
  3129. /**
  3130. *
  3131. * Execute hook displayCarrierList (extraCarrier) and merge theme to the $array
  3132. * @param array $array
  3133. */
  3134. public static function addExtraCarriers(&$array)
  3135. {
  3136. $first = true;
  3137. $hook_extracarrier_addr = array();
  3138. foreach (Context::getContext()->cart->getAddressCollection() as $address)
  3139. {
  3140. $hook = Hook::exec('displayCarrierList', array('address' => $address));
  3141. $hook_extracarrier_addr[$address->id] = $hook;
  3142. if ($first)
  3143. {
  3144. $array = array_merge(
  3145. $array,
  3146. array('HOOK_EXTRACARRIER' => $hook)
  3147. );
  3148. $first = false;
  3149. }
  3150. $array = array_merge(
  3151. $array,
  3152. array('HOOK_EXTRACARRIER_ADDR' => $hook_extracarrier_addr)
  3153. );
  3154. }
  3155. }
  3156. /**
  3157. * Get all the ids of the delivery addresses without carriers
  3158. *
  3159. * @param bool $return_collection Return a collection
  3160. *
  3161. * @return array Array of address id or of address object
  3162. */
  3163. public function getDeliveryAddressesWithoutCarriers($return_collection = false)
  3164. {
  3165. $addresses_without_carriers = array();
  3166. foreach ($this->getProducts() as $product)
  3167. {
  3168. if (!in_array($product['id_address_delivery'], $addresses_without_carriers)
  3169. && !count(Carrier::getAvailableCarrierList(new Product($product['id_product']), null, $product['id_address_delivery'])))
  3170. $addresses_without_carriers[] = $product['id_address_delivery'];
  3171. }
  3172. if (!$return_collection)
  3173. return $addresses_without_carriers;
  3174. else
  3175. {
  3176. $addresses_instance_without_carriers = array();
  3177. foreach ($addresses_without_carriers as $id_address)
  3178. $addresses_instance_without_carriers[] = new Address($id_address);
  3179. return $addresses_instance_without_carriers;
  3180. }
  3181. }
  3182. }