PageRenderTime 57ms CodeModel.GetById 19ms RepoModel.GetById 0ms app.codeStats 1ms

/classes/Cart.php

https://github.com/netplayer/PrestaShop
PHP | 3736 lines | 2759 code | 497 blank | 480 comment | 543 complexity | 79c02b324d41b14f46787f59fae1d1b1 MD5 | raw file
Possible License(s): CC-BY-SA-3.0, LGPL-2.1, LGPL-3.0

Large files files are truncated, but you can click here to view the full file

  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, IFNULL(sp.`reduction_type`, 0) AS reduction_type');
  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. $sql->leftJoin('specific_price', 'sp', 'sp.`id_product` = cp.`id_product`'); // AND 'sp.`id_shop` = cp.`id_shop`
  389. // @todo test if everything is ok, then refactorise call of this method
  390. $sql->join(Product::sqlStock('cp', 'cp'));
  391. // Build WHERE clauses
  392. $sql->where('cp.`id_cart` = '.(int)$this->id);
  393. if ($id_product)
  394. $sql->where('cp.`id_product` = '.(int)$id_product);
  395. $sql->where('p.`id_product` IS NOT NULL');
  396. // Build GROUP BY
  397. $sql->groupBy('unique_id');
  398. // Build ORDER BY
  399. $sql->orderBy('cp.`date_add`, p.`id_product`, cp.`id_product_attribute` ASC');
  400. if (Customization::isFeatureActive())
  401. {
  402. $sql->select('cu.`id_customization`, cu.`quantity` AS customization_quantity');
  403. $sql->leftJoin('customization', 'cu',
  404. 'p.`id_product` = cu.`id_product` AND cp.`id_product_attribute` = cu.`id_product_attribute` AND cu.`id_cart` = '.(int)$this->id);
  405. }
  406. else
  407. $sql->select('NULL AS customization_quantity, NULL AS id_customization');
  408. if (Combination::isFeatureActive())
  409. {
  410. $sql->select('
  411. product_attribute_shop.`price` AS price_attribute, product_attribute_shop.`ecotax` AS ecotax_attr,
  412. IF (IFNULL(pa.`reference`, \'\') = \'\', p.`reference`, pa.`reference`) AS reference,
  413. (p.`weight`+ pa.`weight`) weight_attribute,
  414. IF (IFNULL(pa.`ean13`, \'\') = \'\', p.`ean13`, pa.`ean13`) AS ean13,
  415. IF (IFNULL(pa.`upc`, \'\') = \'\', p.`upc`, pa.`upc`) AS upc,
  416. pai.`id_image` as pai_id_image, il.`legend` as pai_legend,
  417. IFNULL(product_attribute_shop.`minimal_quantity`, product_shop.`minimal_quantity`) as minimal_quantity
  418. ');
  419. $sql->leftJoin('product_attribute', 'pa', 'pa.`id_product_attribute` = cp.`id_product_attribute`');
  420. $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`)');
  421. $sql->leftJoin('product_attribute_image', 'pai', 'pai.`id_product_attribute` = pa.`id_product_attribute`');
  422. $sql->leftJoin('image_lang', 'il', 'il.`id_image` = pai.`id_image` AND il.`id_lang` = '.(int)$this->id_lang);
  423. }
  424. else
  425. $sql->select(
  426. 'p.`reference` AS reference, p.`ean13`,
  427. p.`upc` AS upc, product_shop.`minimal_quantity` AS minimal_quantity'
  428. );
  429. $result = Db::getInstance()->executeS($sql);
  430. // Reset the cache before the following return, or else an empty cart will add dozens of queries
  431. $products_ids = array();
  432. $pa_ids = array();
  433. if ($result)
  434. foreach ($result as $row)
  435. {
  436. $products_ids[] = $row['id_product'];
  437. $pa_ids[] = $row['id_product_attribute'];
  438. }
  439. // Thus you can avoid one query per product, because there will be only one query for all the products of the cart
  440. Product::cacheProductsFeatures($products_ids);
  441. Cart::cacheSomeAttributesLists($pa_ids, $this->id_lang);
  442. $this->_products = array();
  443. if (empty($result))
  444. return array();
  445. $cart_shop_context = Context::getContext()->cloneContext();
  446. foreach ($result as &$row)
  447. {
  448. if (isset($row['ecotax_attr']) && $row['ecotax_attr'] > 0)
  449. $row['ecotax'] = (float)$row['ecotax_attr'];
  450. $row['stock_quantity'] = (int)$row['quantity'];
  451. // for compatibility with 1.2 themes
  452. $row['quantity'] = (int)$row['cart_quantity'];
  453. if (isset($row['id_product_attribute']) && (int)$row['id_product_attribute'] && isset($row['weight_attribute']))
  454. $row['weight'] = (float)$row['weight_attribute'];
  455. if (Configuration::get('PS_TAX_ADDRESS_TYPE') == 'id_address_invoice')
  456. $address_id = (int)$this->id_address_invoice;
  457. else
  458. $address_id = (int)$row['id_address_delivery'];
  459. if (!Address::addressExists($address_id))
  460. $address_id = null;
  461. if ($cart_shop_context->shop->id != $row['id_shop'])
  462. $cart_shop_context->shop = new Shop((int)$row['id_shop']);
  463. if ($this->_taxCalculationMethod == PS_TAX_EXC)
  464. {
  465. $row['price'] = Product::getPriceStatic(
  466. (int)$row['id_product'],
  467. false,
  468. isset($row['id_product_attribute']) ? (int)$row['id_product_attribute'] : null,
  469. 2,
  470. null,
  471. false,
  472. true,
  473. (int)$row['cart_quantity'],
  474. false,
  475. ((int)$this->id_customer ? (int)$this->id_customer : null),
  476. (int)$this->id,
  477. ((int)$address_id ? (int)$address_id : null),
  478. $specific_price_output,
  479. true,
  480. true,
  481. $cart_shop_context
  482. ); // Here taxes are computed only once the quantity has been applied to the product price
  483. $row['price_wt'] = Product::getPriceStatic(
  484. (int)$row['id_product'],
  485. true,
  486. isset($row['id_product_attribute']) ? (int)$row['id_product_attribute'] : null,
  487. 2,
  488. null,
  489. false,
  490. true,
  491. (int)$row['cart_quantity'],
  492. false,
  493. ((int)$this->id_customer ? (int)$this->id_customer : null),
  494. (int)$this->id,
  495. ((int)$address_id ? (int)$address_id : null),
  496. $null,
  497. true,
  498. true,
  499. $cart_shop_context
  500. );
  501. $tax_rate = Tax::getProductTaxRate((int)$row['id_product'], (int)$address_id);
  502. $row['total_wt'] = Tools::ps_round($row['price'] * (float)$row['cart_quantity'] * (1 + (float)$tax_rate / 100), 2);
  503. $row['total'] = $row['price'] * (int)$row['cart_quantity'];
  504. }
  505. else
  506. {
  507. $row['price'] = Product::getPriceStatic(
  508. (int)$row['id_product'],
  509. false,
  510. (int)$row['id_product_attribute'],
  511. 2,
  512. null,
  513. false,
  514. true,
  515. $row['cart_quantity'],
  516. false,
  517. ((int)$this->id_customer ? (int)$this->id_customer : null),
  518. (int)$this->id,
  519. ((int)$address_id ? (int)$address_id : null),
  520. $specific_price_output,
  521. true,
  522. true,
  523. $cart_shop_context
  524. );
  525. $row['price_wt'] = Product::getPriceStatic(
  526. (int)$row['id_product'],
  527. true,
  528. (int)$row['id_product_attribute'],
  529. 2,
  530. null,
  531. false,
  532. true,
  533. $row['cart_quantity'],
  534. false,
  535. ((int)$this->id_customer ? (int)$this->id_customer : null),
  536. (int)$this->id,
  537. ((int)$address_id ? (int)$address_id : null),
  538. $null,
  539. true,
  540. true,
  541. $cart_shop_context
  542. );
  543. // In case when you use QuantityDiscount, getPriceStatic() can be return more of 2 decimals
  544. $row['price_wt'] = Tools::ps_round($row['price_wt'], 2);
  545. $row['total_wt'] = $row['price_wt'] * (int)$row['cart_quantity'];
  546. $row['total'] = Tools::ps_round($row['price'] * (int)$row['cart_quantity'], 2);
  547. $row['description_short'] = Tools::nl2br($row['description_short']);
  548. }
  549. if (!isset($row['pai_id_image']) || $row['pai_id_image'] == 0)
  550. {
  551. $cache_id = 'Cart::getProducts_'.'-pai_id_image-'.(int)$row['id_product'].'-'.(int)$this->id_lang.'-'.(int)$row['id_shop'];
  552. if (!Cache::isStored($cache_id))
  553. {
  554. $row2 = Db::getInstance()->getRow('
  555. SELECT image_shop.`id_image` id_image, il.`legend`
  556. FROM `'._DB_PREFIX_.'image` i
  557. 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'].')
  558. LEFT JOIN `'._DB_PREFIX_.'image_lang` il ON (image_shop.`id_image` = il.`id_image` AND il.`id_lang` = '.(int)$this->id_lang.')
  559. WHERE i.`id_product` = '.(int)$row['id_product'].' AND image_shop.`cover` = 1'
  560. );
  561. Cache::store($cache_id, $row2);
  562. }
  563. $row2 = Cache::retrieve($cache_id);
  564. if (!$row2)
  565. $row2 = array('id_image' => false, 'legend' => false);
  566. else
  567. $row = array_merge($row, $row2);
  568. }
  569. else
  570. {
  571. $row['id_image'] = $row['pai_id_image'];
  572. $row['legend'] = $row['pai_legend'];
  573. }
  574. $row['reduction_applies'] = ($specific_price_output && (float)$specific_price_output['reduction']);
  575. $row['quantity_discount_applies'] = ($specific_price_output && $row['cart_quantity'] >= (int)$specific_price_output['from_quantity']);
  576. $row['id_image'] = Product::defineProductImage($row, $this->id_lang);
  577. $row['allow_oosp'] = Product::isAvailableWhenOutOfStock($row['out_of_stock']);
  578. $row['features'] = Product::getFeaturesStatic((int)$row['id_product']);
  579. if (array_key_exists($row['id_product_attribute'].'-'.$this->id_lang, self::$_attributesLists))
  580. $row = array_merge($row, self::$_attributesLists[$row['id_product_attribute'].'-'.$this->id_lang]);
  581. $row = Product::getTaxesInformations($row, $cart_shop_context);
  582. $this->_products[] = $row;
  583. }
  584. return $this->_products;
  585. }
  586. public static function cacheSomeAttributesLists($ipa_list, $id_lang)
  587. {
  588. if (!Combination::isFeatureActive())
  589. return;
  590. $pa_implode = array();
  591. foreach ($ipa_list as $id_product_attribute)
  592. if ((int)$id_product_attribute && !array_key_exists($id_product_attribute.'-'.$id_lang, self::$_attributesLists))
  593. {
  594. $pa_implode[] = (int)$id_product_attribute;
  595. self::$_attributesLists[(int)$id_product_attribute.'-'.$id_lang] = array('attributes' => '', 'attributes_small' => '');
  596. }
  597. if (!count($pa_implode))
  598. return;
  599. $result = Db::getInstance()->executeS('
  600. SELECT pac.`id_product_attribute`, agl.`public_name` AS public_group_name, al.`name` AS attribute_name
  601. FROM `'._DB_PREFIX_.'product_attribute_combination` pac
  602. LEFT JOIN `'._DB_PREFIX_.'attribute` a ON a.`id_attribute` = pac.`id_attribute`
  603. LEFT JOIN `'._DB_PREFIX_.'attribute_group` ag ON ag.`id_attribute_group` = a.`id_attribute_group`
  604. LEFT JOIN `'._DB_PREFIX_.'attribute_lang` al ON (
  605. a.`id_attribute` = al.`id_attribute`
  606. AND al.`id_lang` = '.(int)$id_lang.'
  607. )
  608. LEFT JOIN `'._DB_PREFIX_.'attribute_group_lang` agl ON (
  609. ag.`id_attribute_group` = agl.`id_attribute_group`
  610. AND agl.`id_lang` = '.(int)$id_lang.'
  611. )
  612. WHERE pac.`id_product_attribute` IN ('.implode(',', $pa_implode).')
  613. ORDER BY agl.`public_name` ASC'
  614. );
  615. foreach ($result as $row)
  616. {
  617. self::$_attributesLists[$row['id_product_attribute'].'-'.$id_lang]['attributes'] .= $row['public_group_name'].' : '.$row['attribute_name'].', ';
  618. self::$_attributesLists[$row['id_product_attribute'].'-'.$id_lang]['attributes_small'] .= $row['attribute_name'].', ';
  619. }
  620. foreach ($pa_implode as $id_product_attribute)
  621. {
  622. self::$_attributesLists[$id_product_attribute.'-'.$id_lang]['attributes'] = rtrim(
  623. self::$_attributesLists[$id_product_attribute.'-'.$id_lang]['attributes'],
  624. ', '
  625. );
  626. self::$_attributesLists[$id_product_attribute.'-'.$id_lang]['attributes_small'] = rtrim(
  627. self::$_attributesLists[$id_product_attribute.'-'.$id_lang]['attributes_small'],
  628. ', '
  629. );
  630. }
  631. }
  632. /**
  633. * Return cart products quantity
  634. *
  635. * @result integer Products quantity
  636. */
  637. public function nbProducts()
  638. {
  639. if (!$this->id)
  640. return 0;
  641. return Cart::getNbProducts($this->id);
  642. }
  643. public static function getNbProducts($id)
  644. {
  645. // Must be strictly compared to NULL, or else an empty cart will bypass the cache and add dozens of queries
  646. if (isset(self::$_nbProducts[$id]) && self::$_nbProducts[$id] !== null)
  647. return self::$_nbProducts[$id];
  648. self::$_nbProducts[$id] = (int)Db::getInstance()->getValue('
  649. SELECT SUM(`quantity`)
  650. FROM `'._DB_PREFIX_.'cart_product`
  651. WHERE `id_cart` = '.(int)$id
  652. );
  653. return self::$_nbProducts[$id];
  654. }
  655. /**
  656. * @deprecated 1.5.0, use Cart->addCartRule()
  657. */
  658. public function addDiscount($id_cart_rule)
  659. {
  660. Tools::displayAsDeprecated();
  661. return $this->addCartRule($id_cart_rule);
  662. }
  663. public function addCartRule($id_cart_rule)
  664. {
  665. // You can't add a cart rule that does not exist
  666. $cartRule = new CartRule($id_cart_rule, Context::getContext()->language->id);
  667. if (!Validate::isLoadedObject($cartRule))
  668. return false;
  669. 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))
  670. return false;
  671. // Add the cart rule to the cart
  672. if (!Db::getInstance()->insert('cart_cart_rule', array(
  673. 'id_cart_rule' => (int)$id_cart_rule,
  674. 'id_cart' => (int)$this->id
  675. )))
  676. return false;
  677. Cache::clean('Cart::getCartRules_'.$this->id.'-'.CartRule::FILTER_ACTION_ALL);
  678. Cache::clean('Cart::getCartRules_'.$this->id.'-'.CartRule::FILTER_ACTION_SHIPPING);
  679. Cache::clean('Cart::getCartRules_'.$this->id.'-'.CartRule::FILTER_ACTION_REDUCTION);
  680. Cache::clean('Cart::getCartRules_'.$this->id.'-'.CartRule::FILTER_ACTION_GIFT);
  681. if ((int)$cartRule->gift_product)
  682. $this->updateQty(1, $cartRule->gift_product, $cartRule->gift_product_attribute, false, 'up', 0, null, false);
  683. return true;
  684. }
  685. public function containsProduct($id_product, $id_product_attribute = 0, $id_customization = 0, $id_address_delivery = 0)
  686. {
  687. $sql = 'SELECT cp.`quantity` FROM `'._DB_PREFIX_.'cart_product` cp';
  688. if ($id_customization)
  689. $sql .= '
  690. LEFT JOIN `'._DB_PREFIX_.'customization` c ON (
  691. c.`id_product` = cp.`id_product`
  692. AND c.`id_product_attribute` = cp.`id_product_attribute`
  693. )';
  694. $sql .= '
  695. WHERE cp.`id_product` = '.(int)$id_product.'
  696. AND cp.`id_product_attribute` = '.(int)$id_product_attribute.'
  697. AND cp.`id_cart` = '.(int)$this->id;
  698. if (Configuration::get('PS_ALLOW_MULTISHIPPING') && $this->isMultiAddressDelivery())
  699. $sql .= ' AND cp.`id_address_delivery` = '.(int)$id_address_delivery;
  700. if ($id_customization)
  701. $sql .= ' AND c.`id_customization` = '.(int)$id_customization;
  702. return Db::getInstance()->getRow($sql);
  703. }
  704. /**
  705. * Update product quantity
  706. *
  707. * @param integer $quantity Quantity to add (or substract)
  708. * @param integer $id_product Product ID
  709. * @param integer $id_product_attribute Attribute ID if needed
  710. * @param string $operator Indicate if quantity must be increased or decreased
  711. */
  712. public function updateQty($quantity, $id_product, $id_product_attribute = null, $id_customization = false,
  713. $operator = 'up', $id_address_delivery = 0, Shop $shop = null, $auto_add_cart_rule = true)
  714. {
  715. if (!$shop)
  716. $shop = Context::getContext()->shop;
  717. if (Context::getContext()->customer->id)
  718. {
  719. if ($id_address_delivery == 0 && (int)$this->id_address_delivery) // The $id_address_delivery is null, use the cart delivery address
  720. $id_address_delivery = $this->id_address_delivery;
  721. elseif ($id_address_delivery == 0) // The $id_address_delivery is null, get the default customer address
  722. $id_address_delivery = (int)Address::getFirstCustomerAddressId((int)Context::getContext()->customer->id);
  723. elseif (!Customer::customerHasAddress(Context::getContext()->customer->id, $id_address_delivery)) // The $id_address_delivery must be linked with customer
  724. $id_address_delivery = 0;
  725. }
  726. $quantity = (int)$quantity;
  727. $id_product = (int)$id_product;
  728. $id_product_attribute = (int)$id_product_attribute;
  729. $product = new Product($id_product, false, Configuration::get('PS_LANG_DEFAULT'), $shop->id);
  730. if ($id_product_attribute)
  731. {
  732. $combination = new Combination((int)$id_product_attribute);
  733. if ($combination->id_product != $id_product)
  734. return false;
  735. }
  736. /* If we have a product combination, the minimal quantity is set with the one of this combination */
  737. if (!empty($id_product_attribute))
  738. $minimal_quantity = (int)Attribute::getAttributeMinimalQty($id_product_attribute);
  739. else
  740. $minimal_quantity = (int)$product->minimal_quantity;
  741. if (!Validate::isLoadedObject($product))
  742. die(Tools::displayError());
  743. if (isset(self::$_nbProducts[$this->id]))
  744. unset(self::$_nbProducts[$this->id]);
  745. if (isset(self::$_totalWeight[$this->id]))
  746. unset(self::$_totalWeight[$this->id]);
  747. if ((int)$quantity <= 0)
  748. return $this->deleteProduct($id_product, $id_product_attribute, (int)$id_customization);
  749. elseif (!$product->available_for_order || Configuration::get('PS_CATALOG_MODE'))
  750. return false;
  751. else
  752. {
  753. /* Check if the product is already in the cart */
  754. $result = $this->containsProduct($id_product, $id_product_attribute, (int)$id_customization, (int)$id_address_delivery);
  755. /* Update quantity if product already exist */
  756. if ($result)
  757. {
  758. if ($operator == 'up')
  759. {
  760. $sql = 'SELECT stock.out_of_stock, IFNULL(stock.quantity, 0) as quantity
  761. FROM '._DB_PREFIX_.'product p
  762. '.Product::sqlStock('p', $id_product_attribute, true, $shop).'
  763. WHERE p.id_product = '.$id_product;
  764. $result2 = Db::getInstance()->getRow($sql);
  765. $product_qty = (int)$result2['quantity'];
  766. // Quantity for product pack
  767. if (Pack::isPack($id_product))
  768. $product_qty = Pack::getQuantity($id_product, $id_product_attribute);
  769. $new_qty = (int)$result['quantity'] + (int)$quantity;
  770. $qty = '+ '.(int)$quantity;
  771. if (!Product::isAvailableWhenOutOfStock((int)$result2['out_of_stock']))
  772. if ($new_qty > $product_qty)
  773. return false;
  774. }
  775. else if ($operator == 'down')
  776. {
  777. $qty = '- '.(int)$quantity;
  778. $new_qty = (int)$result['quantity'] - (int)$quantity;
  779. if ($new_qty < $minimal_quantity && $minimal_quantity > 1)
  780. return -1;
  781. }
  782. else
  783. return false;
  784. /* Delete product from cart */
  785. if ($new_qty <= 0)
  786. return $this->deleteProduct((int)$id_product, (int)$id_product_attribute, (int)$id_customization);
  787. else if ($new_qty < $minimal_quantity)
  788. return -1;
  789. else
  790. Db::getInstance()->execute('
  791. UPDATE `'._DB_PREFIX_.'cart_product`
  792. SET `quantity` = `quantity` '.$qty.', `date_add` = NOW()
  793. WHERE `id_product` = '.(int)$id_product.
  794. (!empty($id_product_attribute) ? ' AND `id_product_attribute` = '.(int)$id_product_attribute : '').'
  795. AND `id_cart` = '.(int)$this->id.(Configuration::get('PS_ALLOW_MULTISHIPPING') && $this->isMultiAddressDelivery() ? ' AND `id_address_delivery` = '.(int)$id_address_delivery : '').'
  796. LIMIT 1'
  797. );
  798. }
  799. /* Add product to the cart */
  800. elseif ($operator == 'up')
  801. {
  802. $sql = 'SELECT stock.out_of_stock, IFNULL(stock.quantity, 0) as quantity
  803. FROM '._DB_PREFIX_.'product p
  804. '.Product::sqlStock('p', $id_product_attribute, true, $shop).'
  805. WHERE p.id_product = '.$id_product;
  806. $result2 = Db::getInstance()->getRow($sql);
  807. // Quantity for product pack
  808. if (Pack::isPack($id_product))
  809. $result2['quantity'] = Pack::getQuantity($id_product, $id_product_attribute);
  810. if (!Product::isAvailableWhenOutOfStock((int)$result2['out_of_stock']))
  811. if ((int)$quantity > $result2['quantity'])
  812. return false;
  813. if ((int)$quantity < $minimal_quantity)
  814. return -1;
  815. $result_add = Db::getInstance()->insert('cart_product', array(
  816. 'id_product' => (int)$id_product,
  817. 'id_product_attribute' => (int)$id_product_attribute,
  818. 'id_cart' => (int)$this->id,
  819. 'id_address_delivery' => (int)$id_address_delivery,
  820. 'id_shop' => $shop->id,
  821. 'quantity' => (int)$quantity,
  822. 'date_add' => date('Y-m-d H:i:s')
  823. ));
  824. if (!$result_add)
  825. return false;
  826. }
  827. }
  828. // refresh cache of self::_products
  829. $this->_products = $this->getProducts(true);
  830. $this->update(true);
  831. $context = Context::getContext()->cloneContext();
  832. $context->cart = $this;
  833. Cache::clean('getContextualValue_*');
  834. if ($auto_add_cart_rule)
  835. CartRule::autoAddToCart($context);
  836. if ($product->customizable)
  837. return $this->_updateCustomizationQuantity((int)$quantity, (int)$id_customization, (int)$id_product, (int)$id_product_attribute, (int)$id_address_delivery, $operator);
  838. else
  839. return true;
  840. }
  841. /*
  842. ** Customization management
  843. */
  844. protected function _updateCustomizationQuantity($quantity, $id_customization, $id_product, $id_product_attribute, $id_address_delivery, $operator = 'up')
  845. {
  846. // Link customization to product combination when it is first added to cart
  847. if (empty($id_customization))
  848. {
  849. $customization = $this->getProductCustomization($id_product, null, true);
  850. foreach ($customization as $field)
  851. {
  852. if ($field['quantity'] == 0)
  853. {
  854. Db::getInstance()->execute('
  855. UPDATE `'._DB_PREFIX_.'customization`
  856. SET `quantity` = '.(int)$quantity.',
  857. `id_product_attribute` = '.(int)$id_product_attribute.',
  858. `id_address_delivery` = '.(int)$id_address_delivery.',
  859. `in_cart` = 1
  860. WHERE `id_customization` = '.(int)$field['id_customization']);
  861. }
  862. }
  863. }
  864. /* Deletion */
  865. if (!empty($id_customization) && (int)$quantity < 1)
  866. return $this->_deleteCustomization((int)$id_customization, (int)$id_product, (int)$id_product_attribute);
  867. /* Quantity update */
  868. if (!empty($id_customization))
  869. {
  870. $result = Db::getInstance()->getRow('SELECT `quantity` FROM `'._DB_PREFIX_.'customization` WHERE `id_customization` = '.(int)$id_customization);
  871. if ($result && Db::getInstance()->NumRows())
  872. {
  873. if ($operator == 'down' && (int)$result['quantity'] - (int)$quantity < 1)
  874. return Db::getInstance()->execute('DELETE FROM `'._DB_PREFIX_.'customization` WHERE `id_customization` = '.(int)$id_customization);
  875. return Db::getInstance()->execute('
  876. UPDATE `'._DB_PREFIX_.'customization`
  877. SET
  878. `quantity` = `quantity` '.($operator == 'up' ? '+ ' : '- ').(int)$quantity.',
  879. `id_address_delivery` = '.(int)$id_address_delivery.'
  880. WHERE `id_customization` = '.(int)$id_customization);
  881. }
  882. else
  883. Db::getInstance()->execute('
  884. UPDATE `'._DB_PREFIX_.'customization`
  885. SET `id_address_delivery` = '.(int)$id_address_delivery.'
  886. WHERE `id_customization` = '.(int)$id_customization);
  887. }
  888. // refresh cache of self::_products
  889. $this->_products = $this->getProducts(true);
  890. $this->update(true);
  891. return true;
  892. }
  893. /**
  894. * Add customization item to database
  895. *
  896. * @param int $id_product
  897. * @param int $id_product_attribute
  898. * @param int $index
  899. * @param int $type
  900. * @param string $field
  901. * @param int $quantity
  902. * @return boolean success
  903. */
  904. public function _addCustomization($id_product, $id_product_attribute, $index, $type, $field, $quantity)
  905. {
  906. $exising_customization = Db::getInstance()->executeS('
  907. SELECT cu.`id_customization`, cd.`index`, cd.`value`, cd.`type` FROM `'._DB_PREFIX_.'customization` cu
  908. LEFT JOIN `'._DB_PREFIX_.'customized_data` cd
  909. ON cu.`id_customization` = cd.`id_customization`
  910. WHERE cu.id_cart = '.(int)$this->id.'
  911. AND cu.id_product = '.(int)$id_product.'
  912. AND in_cart = 0'
  913. );
  914. if ($exising_customization)
  915. {
  916. // If the customization field is alreay filled, delete it
  917. foreach ($exising_customization as $customization)
  918. {
  919. if ($customization['type'] == $type && $customization['index'] == $index)
  920. {
  921. Db::getInstance()->execute('
  922. DELETE FROM `'._DB_PREFIX_.'customized_data`
  923. WHERE id_customization = '.(int)$customization['id_customization'].'
  924. AND type = '.(int)$customization['type'].'
  925. AND `index` = '.(int)$customization['index']);
  926. if ($type == Product::CUSTOMIZE_FILE)
  927. {
  928. @unlink(_PS_UPLOAD_DIR_.$customization['value']);
  929. @unlink(_PS_UPLOAD_DIR_.$customization['value'].'_small');
  930. }
  931. break;
  932. }
  933. }
  934. $id_customization = $exising_customization[0]['id_customization'];
  935. }
  936. else
  937. {
  938. Db::getInstance()->execute(
  939. 'INSERT INTO `'._DB_PREFIX_.'customization` (`id_cart`, `id_product`, `id_product_attribute`, `quantity`)
  940. VALUES ('.(int)$this->id.', '.(int)$id_product.', '.(int)$id_product_attribute.', '.(int)$quantity.')'
  941. );
  942. $id_customization = Db::getInstance()->Insert_ID();
  943. }
  944. $query = 'INSERT INTO `'._DB_PREFIX_.'customized_data` (`id_customization`, `type`, `index`, `value`)
  945. VALUES ('.(int)$id_customization.', '.(int)$type.', '.(int)$index.', \''.pSQL($field).'\')';
  946. if (!Db::getInstance()->execute($query))
  947. return false;
  948. return true;
  949. }
  950. /**
  951. * Check if order has already been placed
  952. *
  953. * @return boolean result
  954. */
  955. public function orderExists()
  956. {
  957. $cache_id = 'Cart::orderExists_'.(int)$this->id;
  958. if (!Cache::isStored($cache_id))
  959. {
  960. $result = (bool)Db::getInstance()->getValue('SELECT count(*) FROM `'._DB_PREFIX_.'orders` WHERE `id_cart` = '.(int)$this->id);
  961. Cache::store($cache_id, $result);
  962. }
  963. return Cache::retrieve($cache_id);
  964. }
  965. /**
  966. * @deprecated 1.5.0, use Cart->removeCartRule()
  967. */
  968. public function deleteDiscount($id_cart_rule)
  969. {
  970. Tools::displayAsDeprecated();
  971. return $this->removeCartRule($id_cart_rule);
  972. }
  973. public function removeCartRule($id_cart_rule)
  974. {
  975. Cache::clean('Cart::getCartRules_'.$this->id.'-'.CartRule::FILTER_ACTION_ALL);
  976. Cache::clean('Cart::getCartRules_'.$this->id.'-'.CartRule::FILTER_ACTION_SHIPPING);
  977. Cache::clean('Cart::getCartRules_'.$this->id.'-'.CartRule::FILTER_ACTION_REDUCTION);
  978. Cache::clean('Cart::getCartRules_'.$this->id.'-'.CartRule::FILTER_ACTION_GIFT);
  979. $result = Db::getInstance()->execute('
  980. DELETE FROM `'._DB_PREFIX_.'cart_cart_rule`
  981. WHERE `id_cart_rule` = '.(int)$id_cart_rule.'
  982. AND `id_cart` = '.(int)$this->id.'
  983. LIMIT 1');
  984. $cart_rule = new CartRule($id_cart_rule, Configuration::get('PS_LANG_DEFAULT'));
  985. if ((int)$cart_rule->gift_product)
  986. $this->updateQty(1, $cart_rule->gift_product, $cart_rule->gift_product_attribute, null, 'down', 0, null, false);
  987. return $result;
  988. }
  989. /**
  990. * Delete a product from the cart
  991. *
  992. * @param integer $id_product Product ID
  993. * @param integer $id_product_attribute Attribute ID if needed
  994. * @param integer $id_customization Customization id
  995. * @return boolean result
  996. */
  997. public function deleteProduct($id_product, $id_product_attribute = null, $id_customization = null, $id_address_delivery = 0)
  998. {
  999. if (isset(self::$_nbProducts[$this->id]))
  1000. unset(self::$_nbProducts[$this->id]);
  1001. if (isset(self::$_totalWeight[$this->id]))
  1002. unset(self::$_totalWeight[$this->id]);
  1003. if ((int)$id_customization)
  1004. {
  1005. $product_total_quantity = (int)Db::getInstance()->getValue(
  1006. 'SELECT `quantity`
  1007. FROM `'._DB_PREFIX_.'cart_product`
  1008. WHERE `id_product` = '.(int)$id_product.'
  1009. AND `id_cart` = '.(int)$this->id.'
  1010. AND `id_product_attribute` = '.(int)$id_product_attribute);
  1011. $customization_quantity = (int)Db::getInstance()->getValue('
  1012. SELECT `quantity`
  1013. FROM `'._DB_PREFIX_.'customization`
  1014. WHERE `id_cart` = '.(int)$this->id.'
  1015. AND `id_product` = '.(int)$id_product.'
  1016. AND `id_product_attribute` = '.(int)$id_product_attribute.'
  1017. '.((int)$id_address_delivery ? 'AND `id_address_delivery` = '.(int)$id_address_delivery : ''));
  1018. if (!$this->_deleteCustomization((int)$id_customization, (int)$id_product, (int)$id_product_attribute, (int)$id_address_delivery))
  1019. return false;
  1020. // refresh cache of self::_products
  1021. $this->_products = $this->getProducts(true);
  1022. return ($customization_quantity == $product_total_quantity && $this->deleteProduct((int)$id_product, (int)$id_product_attribute, null, (int)$id_address_delivery));
  1023. }
  1024. /* Get customization quantity */
  1025. $result = Db::getInstance()->getRow('
  1026. SELECT SUM(`quantity`) AS \'quantity\'
  1027. FROM `'._DB_PREFIX_.'customization`
  1028. WHERE `id_cart` = '.(int)$this->id.'
  1029. AND `id_product` = '.(int)$id_product.'
  1030. AND `id_product_attribute` = '.(int)$id_product_attribute);
  1031. if ($result === false)
  1032. return false;
  1033. /* If the product still possesses customization it does not have to be deleted */
  1034. if (Db::getInstance()->NumRows() && (int)$result['quantity'])
  1035. return Db::getInstance()->execute('
  1036. UPDATE `'._DB_PREFIX_.'cart_product`
  1037. SET `quantity` = '.(int)$result['quantity'].'
  1038. WHERE `id_cart` = '.(int)$this->id.'
  1039. AND `id_product` = '.(int)$id_product.
  1040. ($id_product_attribute != null ? ' AND `id_product_attribute` = '.(int)$id_product_attribute : '')
  1041. );
  1042. /* Product deletion */
  1043. $result = Db::getInstance()->execute('
  1044. DELETE FROM `'._DB_PREFIX_.'cart_product`
  1045. WHERE `id_product` = '.(int)$id_product.'
  1046. '.(!is_null($id_product_attribute) ? ' AND `id_product_attribute` = '.(int)$id_product_attribute : '').'
  1047. AND `id_cart` = '.(int)$this->id.'
  1048. '.((int)$id_address_delivery ? 'AND `id_address_delivery` = '.(int)$id_address_delivery : ''));
  1049. if ($result)
  1050. {
  1051. $return = $this->update(true);
  1052. // refresh cache of self::_products
  1053. $this->_products = $this->getProducts(true);
  1054. CartRule::autoRemoveFromCart();
  1055. CartRule::autoAddToCart();
  1056. return $return;
  1057. }
  1058. return false;
  1059. }
  1060. /**
  1061. * Delete a customization from the cart. If customization is a Picture,
  1062. * then the image is also deleted
  1063. *
  1064. * @param integer $id_customization
  1065. * @return boolean result
  1066. */
  1067. protected function _deleteCustomization($id_customization, $id_product, $id_product_attribute, $id_address_delivery = 0)
  1068. {
  1069. $result = true;
  1070. $customization = Db::getInstance()->getRow('SELECT *
  1071. FROM `'._DB_PREFIX_.'customization`
  1072. WHERE `id_customization` = '.(int)$id_customization);
  1073. if ($customization)
  1074. {
  1075. $cust_data = Db::getInstance()->getRow('SELECT *
  1076. FROM `'._DB_PREFIX_.'customized_data`
  1077. WHERE `id_customization` = '.(int)$id_customization);
  1078. // Delete customization picture if necessary
  1079. if (isset($cust_data['type']) && $cust_data['type'] == 0)
  1080. $result &= (@unlink(_PS_UPLOAD_DIR_.$cust_data['value']) && @unlink(_PS_UPLOAD_DIR_.$cust_data['value'].'_small'));
  1081. $result &= Db::getInstance()->execute(
  1082. 'DELETE FROM `'._DB_PREFIX_.'customized_data`
  1083. WHERE `id_customization` = '.(int)$id_customization
  1084. );
  1085. if ($result)
  1086. $result &= Db::getInstance()->execute(
  1087. 'UPDATE `'._DB_PREFIX_.'cart_product`
  1088. SET `quantity` = `quantity` - '.(int)$customization['quantity'].'
  1089. WHERE `id_cart` = '.(int)$this->id.'
  1090. AND `id_product` = '.(int)$id_product.
  1091. ((int)$id_product_attribute ? ' AND `id_product_attribute` = '.(int)$id_product_attribute : '').'
  1092. AND `id_address_delivery` = '.(int)$id_address_delivery
  1093. );
  1094. if (!$result)
  1095. return false;
  1096. return Db::getInstance()->execute(
  1097. 'DELETE FROM `'._DB_PREFIX_.'customization`
  1098. WHERE `id_customization` = '.(int)$id_customization
  1099. );
  1100. }
  1101. return true;
  1102. }
  1103. public static function getTotalCart($id_cart, $use_tax_display = false, $type = Cart::BOTH)
  1104. {
  1105. $cart = new Cart($id_cart);
  1106. if (!Validate::isLoadedObject($cart))
  1107. die(Tools::displayError());
  1108. $with_taxes = $use_tax_display ? $cart->_taxCalculationMethod != PS_TAX_EXC : true;
  1109. return Tools::displayPrice($cart->getOrderTotal($with_taxes, $type), Currency::getCurrencyInstance((int)$cart->id_currency), false);
  1110. }
  1111. public static function getOrderTotalUsingTaxCalculationMethod($id_cart)
  1112. {
  1113. return Cart::getTotalCart($id_cart, true);
  1114. }
  1115. /**
  1116. * This function returns the total cart amount
  1117. *
  1118. * Possible values for $type:
  1119. * Cart::ONLY_PRODUCTS
  1120. * Cart::ONLY_DISCOUNTS
  1121. * Cart::BOTH
  1122. * Cart::BOTH_WITHOUT_SHIPPING
  1123. * Cart::ONLY_SHIPPING
  1124. * Cart::ONLY_WRAPPING
  1125. * Cart::ONLY_PRODUCTS_WITHOUT_SHIPPING
  1126. * Cart::ONLY_PHYSICAL_PRODUCTS_WITHOUT_SHIPPING
  1127. *
  1128. * @param boolean $withTaxes With or without taxes
  1129. * @param integer $type Total type
  1130. * @param boolean $use_cache Allow using cache of the method CartRule::getContextualValue
  1131. * @return float Order total
  1132. */
  1133. public function getOrderTotal($with_taxes = true, $type = Cart::BOTH, $products = null, $id_carrier = null, $use_cache = true)
  1134. {
  1135. if (!$this->id)
  1136. return 0;
  1137. $type = (int)$type;
  1138. $array_type = array(
  1139. Cart::ONLY_PRODUCTS,
  1140. Cart::ONLY_DISCOUNTS,
  1141. Cart::BOTH,
  1142. Cart::BOTH_WITHOUT_SHIPPING,
  1143. Cart::ONLY_SHIPPING,
  1144. Cart::ONLY_WRAPPING,
  1145. Cart::ONLY_PRODUCTS_WITHOUT_SHIPPING,
  1146. Cart::ONLY_PHYSICAL_PRODUCTS_WITHOUT_SHIPPING,
  1147. );
  1148. // Define virtual context to prevent case where the cart is not the in the global context
  1149. $virtual_context = Context::getContext()->cloneContext();
  1150. $virtual_context->cart = $this;
  1151. if (!in_array($type, $array_type))
  1152. die(Tools::displayError());
  1153. $with_shipping = in_array($type, array(Cart::BOTH, Cart::ONLY_SHIPPING));
  1154. // if cart rules are not used
  1155. if ($type == Cart::ONLY_DISCOUNTS && !CartRule::isFeatureActive())
  1156. return 0;
  1157. // no shipping cost if is a cart with only virtuals products
  1158. $virtual = $this->isVirtualCart();
  1159. if ($virtual && $type == Cart::ONLY_SHIPPING)
  1160. return 0;
  1161. if ($virtual && $type == Cart::BOTH)
  1162. $type = Cart::BOTH_WITHOUT_SHIPPING;
  1163. if ($with_shipping || $type == Cart::ONLY_DISCOUNTS)
  1164. {
  1165. if (is_null($products) && is_null($id_carrier))
  1166. $shipping_fees = $this->getTotalShippingCost(null, (boolean)$with_taxes);
  1167. else
  1168. $shipping_fees = $this->getPackageShippingCost($id_carrier, (bool)$with_taxes, null, $products);
  1169. }
  1170. else
  1171. $shipping_fees = 0;
  1172. if ($type == Cart::ONLY_SHIPPING)
  1173. return $shipping_fees;
  1174. if ($type == Cart::ONLY_PRODUCTS_WITHOUT_SHIPPING)
  1175. $type = Cart::ONLY_PRODUCTS;
  1176. $param_product = true;
  1177. if (is_null($products))
  1178. {
  1179. $param_product = false;
  1180. $products = $this->getProducts();
  1181. }
  1182. if ($type == Cart::ONLY_PHYSICAL_PRODUCTS_WITHOUT_SHIPPING)
  1183. {
  1184. foreach ($products as $key => $product)
  1185. if ($product['is_virtual'])
  1186. unset($products[$key]);
  1187. $type = Cart::ONLY_PRODUCTS;
  1188. }
  1189. $order_total = 0;
  1190. if (Tax::excludeTaxeOption())
  1191. $with_taxes = false;
  1192. foreach ($products as $product) // products refer to the cart details
  1193. {
  1194. if ($virtual_context->shop->id != $product['id_shop'])
  1195. $virtual_context->shop = new Shop((int)$product['id_shop']);
  1196. if (Configuration::get('PS_TAX_ADDRESS_TYPE') == 'id_address_invoice')
  1197. $address_id = (int)$this->id_address_invoice;
  1198. else
  1199. $address_id = (int)$product['id_address_delivery']; // Get delivery address of the product from the cart
  1200. if (!Address::addressExists($address_id))
  1201. $address_id = null;
  1202. if ($this->_taxCalculationMethod == PS_TAX_EXC)
  1203. {
  1204. // Here taxes are computed only once the quantity has been applied to the product price
  1205. $price = Product::getPriceStatic(
  1206. (int)$product['id_product'],
  1207. false,
  1208. (int)$product['id_product_attribute'],
  1209. 2,
  1210. null,
  1211. false,
  1212. true,
  1213. $product['cart_quantity'],
  1214. false,
  1215. (int)$this->id_customer ? (int)$this->id_customer : null,
  1216. (int)$this->id,
  1217. $address_id,
  1218. $null,
  1219. true,
  1220. true,
  1221. $virtual_context
  1222. );
  1223. $total_ecotax = $product['ecotax'] * (int)$product['cart_quantity'];
  1224. $total_price = $price * (int)$product['cart_quantity'];
  1225. if ($with_taxes)
  1226. {
  1227. $product_tax_rate = (float)Tax::getProductTaxRate((int)$product['id_product'], (int)$address_id, $virtual_context);
  1228. $product_eco_tax_rate = Tax::getProductEcotaxRate((int)$address_id);
  1229. $total_price = ($total_price - $total_ecotax) * (1 + $product_tax_rate / 100);
  1230. $total_e

Large files files are truncated, but you can click here to view the full file