PageRenderTime 67ms CodeModel.GetById 13ms RepoModel.GetById 0ms app.codeStats 0ms

/classes/Cart.php

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