Guest User

cart controller1.php

a guest
Mar 7th, 2016
100
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 23.82 KB | None | 0 0
  1. <?php
  2. /**
  3. * Magento
  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@magentocommerce.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 Magento to newer
  18. * versions in the future. If you wish to customize Magento for your
  19. * needs please refer to http://www.magentocommerce.com for more information.
  20. *
  21. * @category Mage
  22. * @package Mage_Checkout
  23. * @copyright Copyright (c) 2014 Magento Inc. (http://www.magentocommerce.com)
  24. * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
  25. */
  26.  
  27. /**
  28. * Shopping cart controller
  29. */
  30. class Mage_Checkout_CartController extends Mage_Core_Controller_Front_Action
  31. {
  32. /**
  33. * Action list where need check enabled cookie
  34. *
  35. * @var array
  36. */
  37. protected $_cookieCheckActions = array('add');
  38.  
  39. /**
  40. * Retrieve shopping cart model object
  41. *
  42. * @return Mage_Checkout_Model_Cart
  43. */
  44. protected function _getCart()
  45. {
  46. return Mage::getSingleton('checkout/cart');
  47. }
  48.  
  49. /**
  50. * Get checkout session model instance
  51. *
  52. * @return Mage_Checkout_Model_Session
  53. */
  54. protected function _getSession()
  55. {
  56. return Mage::getSingleton('checkout/session');
  57. }
  58.  
  59. /**
  60. * Get current active quote instance
  61. *
  62. * @return Mage_Sales_Model_Quote
  63. */
  64. protected function _getQuote()
  65. {
  66. return $this->_getCart()->getQuote();
  67. }
  68.  
  69. /**
  70. * Set back redirect url to response
  71. *
  72. * @return Mage_Checkout_CartController
  73. * @throws Mage_Exception
  74. */
  75. protected function _goBack()
  76. {
  77. $returnUrl = $this->getRequest()->getParam('return_url');
  78. if ($returnUrl) {
  79.  
  80. if (!$this->_isUrlInternal($returnUrl)) {
  81. throw new Mage_Exception('External urls redirect to "' . $returnUrl . '" denied!');
  82. }
  83.  
  84. $this->_getSession()->getMessages(true);
  85. $this->getResponse()->setRedirect($returnUrl);
  86. } elseif (!Mage::getStoreConfig('checkout/cart/redirect_to_cart')
  87. && !$this->getRequest()->getParam('in_cart')
  88. && $backUrl = $this->_getRefererUrl()
  89. ) {
  90. $this->getResponse()->setRedirect($backUrl);
  91. } else {
  92. if (($this->getRequest()->getActionName() == 'add') && !$this->getRequest()->getParam('in_cart')) {
  93. $this->_getSession()->setContinueShoppingUrl($this->_getRefererUrl());
  94. }
  95. $this->_redirect('checkout/cart');
  96. }
  97. return $this;
  98. }
  99.  
  100. /**
  101. * Initialize product instance from request data
  102. *
  103. * @return Mage_Catalog_Model_Product || false
  104. */
  105. protected function _initProduct()
  106. {
  107. $productId = (int) $this->getRequest()->getParam('product');
  108. if ($productId) {
  109. $product = Mage::getModel('catalog/product')
  110. ->setStoreId(Mage::app()->getStore()->getId())
  111. ->load($productId);
  112. if ($product->getId()) {
  113. return $product;
  114. }
  115. }
  116. return false;
  117. }
  118.  
  119. /**
  120. * Predispatch: remove isMultiShipping option from quote
  121. *
  122. * @return Mage_Checkout_CartController
  123. */
  124. public function preDispatch()
  125. {
  126. parent::preDispatch();
  127.  
  128. $cart = $this->_getCart();
  129. if ($cart->getQuote()->getIsMultiShipping()) {
  130. $cart->getQuote()->setIsMultiShipping(false);
  131. }
  132.  
  133. return $this;
  134. }
  135.  
  136. /**
  137. * Shopping cart display action
  138. */
  139. public function indexAction()
  140. {
  141. $cart = $this->_getCart();
  142. if ($cart->getQuote()->getItemsCount()) {
  143. $cart->init();
  144. $cart->save();
  145.  
  146. if (!$this->_getQuote()->validateMinimumAmount()) {
  147. $minimumAmount = Mage::app()->getLocale()->currency(Mage::app()->getStore()->getCurrentCurrencyCode())
  148. ->toCurrency(Mage::getStoreConfig('sales/minimum_order/amount'));
  149.  
  150. $warning = Mage::getStoreConfig('sales/minimum_order/description')
  151. ? Mage::getStoreConfig('sales/minimum_order/description')
  152. : Mage::helper('checkout')->__('Minimum order amount is %s', $minimumAmount);
  153.  
  154. $cart->getCheckoutSession()->addNotice($warning);
  155. }
  156. }
  157.  
  158. // Compose array of messages to add
  159. $messages = array();
  160. foreach ($cart->getQuote()->getMessages() as $message) {
  161. if ($message) {
  162. // Escape HTML entities in quote message to prevent XSS
  163. $message->setCode(Mage::helper('core')->escapeHtml($message->getCode()));
  164. $messages[] = $message;
  165. }
  166. }
  167. $cart->getCheckoutSession()->addUniqueMessages($messages);
  168.  
  169. /**
  170. * if customer enteres shopping cart we should mark quote
  171. * as modified bc he can has checkout page in another window.
  172. */
  173. $this->_getSession()->setCartWasUpdated(true);
  174.  
  175. Varien_Profiler::start(__METHOD__ . 'cart_display');
  176. $this
  177. ->loadLayout()
  178. ->_initLayoutMessages('checkout/session')
  179. ->_initLayoutMessages('catalog/session')
  180. ->getLayout()->getBlock('head')->setTitle($this->__('Shopping Cart'));
  181. $this->renderLayout();
  182. Varien_Profiler::stop(__METHOD__ . 'cart_display');
  183. }
  184.  
  185. /**
  186. * Add product to shopping cart action
  187. *
  188. * @return Mage_Core_Controller_Varien_Action
  189. * @throws Exception
  190. */
  191. public function addAction()
  192. {
  193. if (!$this->_validateFormKey()) {
  194. $this->_goBack();
  195. return;
  196. }
  197. $cart = $this->_getCart();
  198. $params = $this->getRequest()->getParams();
  199. try {
  200. if (isset($params['qty'])) {
  201. $filter = new Zend_Filter_LocalizedToNormalized(
  202. array('locale' => Mage::app()->getLocale()->getLocaleCode())
  203. );
  204. $params['qty'] = $filter->filter($params['qty']);
  205. }
  206.  
  207. $product = $this->_initProduct();
  208. $related = $this->getRequest()->getParam('related_product');
  209.  
  210. /**
  211. * Check product availability
  212. */
  213. if (!$product) {
  214. $this->_goBack();
  215. return;
  216. }
  217.  
  218. $cart->addProduct($product, $params);
  219. if (!empty($related)) {
  220. $cart->addProductsByIds(explode(',', $related));
  221. }
  222.  
  223. $cart->save();
  224.  
  225. $this->_getSession()->setCartWasUpdated(true);
  226.  
  227. /**
  228. * @todo remove wishlist observer processAddToCart
  229. */
  230. Mage::dispatchEvent('checkout_cart_add_product_complete',
  231. array('product' => $product, 'request' => $this->getRequest(), 'response' => $this->getResponse())
  232. );
  233.  
  234. if (!$this->_getSession()->getNoCartRedirect(true)) {
  235. if (!$cart->getQuote()->getHasError()) {
  236. $message = $this->__('%s was added to your shopping cart.', Mage::helper('core')->escapeHtml($product->getName()));
  237. $this->_getSession()->addSuccess($message);
  238. }
  239. $this->_goBack();
  240. }
  241. } catch (Mage_Core_Exception $e) {
  242. if ($this->_getSession()->getUseNotice(true)) {
  243. $this->_getSession()->addNotice(Mage::helper('core')->escapeHtml($e->getMessage()));
  244. } else {
  245. $messages = array_unique(explode("\n", $e->getMessage()));
  246. foreach ($messages as $message) {
  247. $this->_getSession()->addError(Mage::helper('core')->escapeHtml($message));
  248. }
  249. }
  250.  
  251. $url = $this->_getSession()->getRedirectUrl(true);
  252. if ($url) {
  253. $this->getResponse()->setRedirect($url);
  254. } else {
  255. $this->_redirectReferer(Mage::helper('checkout/cart')->getCartUrl());
  256. }
  257. } catch (Exception $e) {
  258. $this->_getSession()->addException($e, $this->__('Cannot add the item to shopping cart.'));
  259. Mage::logException($e);
  260. $this->_goBack();
  261. }
  262. }
  263.  
  264. /**
  265. * Add products in group to shopping cart action
  266. */
  267. public function addgroupAction()
  268. {
  269. $orderItemIds = $this->getRequest()->getParam('order_items', array());
  270.  
  271. if (!is_array($orderItemIds) || !$this->_validateFormKey()) {
  272. $this->_goBack();
  273. return;
  274. }
  275.  
  276. $itemsCollection = Mage::getModel('sales/order_item')
  277. ->getCollection()
  278. ->addIdFilter($orderItemIds)
  279. ->load();
  280. /* @var $itemsCollection Mage_Sales_Model_Mysql4_Order_Item_Collection */
  281. $cart = $this->_getCart();
  282. foreach ($itemsCollection as $item) {
  283. try {
  284. $cart->addOrderItem($item, 1);
  285. } catch (Mage_Core_Exception $e) {
  286. if ($this->_getSession()->getUseNotice(true)) {
  287. $this->_getSession()->addNotice($e->getMessage());
  288. } else {
  289. $this->_getSession()->addError($e->getMessage());
  290. }
  291. } catch (Exception $e) {
  292. $this->_getSession()->addException($e, $this->__('Cannot add the item to shopping cart.'));
  293. Mage::logException($e);
  294. $this->_goBack();
  295. }
  296. }
  297. $cart->save();
  298. $this->_getSession()->setCartWasUpdated(true);
  299. $this->_goBack();
  300. }
  301.  
  302. /**
  303. * Action to reconfigure cart item
  304. */
  305. public function configureAction()
  306. {
  307. // Extract item and product to configure
  308. $id = (int) $this->getRequest()->getParam('id');
  309. $quoteItem = null;
  310. $cart = $this->_getCart();
  311. if ($id) {
  312. $quoteItem = $cart->getQuote()->getItemById($id);
  313. }
  314.  
  315. if (!$quoteItem) {
  316. $this->_getSession()->addError($this->__('Quote item is not found.'));
  317. $this->_redirect('checkout/cart');
  318. return;
  319. }
  320.  
  321. try {
  322. $params = new Varien_Object();
  323. $params->setCategoryId(false);
  324. $params->setConfigureMode(true);
  325. $params->setBuyRequest($quoteItem->getBuyRequest());
  326.  
  327. Mage::helper('catalog/product_view')->prepareAndRender($quoteItem->getProduct()->getId(), $this, $params);
  328. } catch (Exception $e) {
  329. $this->_getSession()->addError($this->__('Cannot configure product.'));
  330. Mage::logException($e);
  331. $this->_goBack();
  332. return;
  333. }
  334. }
  335.  
  336. /**
  337. * Update product configuration for a cart item
  338. */
  339. public function updateItemOptionsAction()
  340. {
  341. $cart = $this->_getCart();
  342. $id = (int) $this->getRequest()->getParam('id');
  343. $params = $this->getRequest()->getParams();
  344.  
  345. if (!isset($params['options'])) {
  346. $params['options'] = array();
  347. }
  348. try {
  349. if (isset($params['qty'])) {
  350. $filter = new Zend_Filter_LocalizedToNormalized(
  351. array('locale' => Mage::app()->getLocale()->getLocaleCode())
  352. );
  353. $params['qty'] = $filter->filter($params['qty']);
  354. }
  355.  
  356. $quoteItem = $cart->getQuote()->getItemById($id);
  357. if (!$quoteItem) {
  358. Mage::throwException($this->__('Quote item is not found.'));
  359. }
  360.  
  361. $item = $cart->updateItem($id, new Varien_Object($params));
  362. if (is_string($item)) {
  363. Mage::throwException($item);
  364. }
  365. if ($item->getHasError()) {
  366. Mage::throwException($item->getMessage());
  367. }
  368.  
  369. $related = $this->getRequest()->getParam('related_product');
  370. if (!empty($related)) {
  371. $cart->addProductsByIds(explode(',', $related));
  372. }
  373.  
  374. $cart->save();
  375.  
  376. $this->_getSession()->setCartWasUpdated(true);
  377.  
  378. Mage::dispatchEvent('checkout_cart_update_item_complete',
  379. array('item' => $item, 'request' => $this->getRequest(), 'response' => $this->getResponse())
  380. );
  381. if (!$this->_getSession()->getNoCartRedirect(true)) {
  382. if (!$cart->getQuote()->getHasError()) {
  383. $message = $this->__('%s was updated in your shopping cart.', Mage::helper('core')->escapeHtml($item->getProduct()->getName()));
  384. $this->_getSession()->addSuccess($message);
  385. }
  386. $this->_goBack();
  387. }
  388. } catch (Mage_Core_Exception $e) {
  389. if ($this->_getSession()->getUseNotice(true)) {
  390. $this->_getSession()->addNotice($e->getMessage());
  391. } else {
  392. $messages = array_unique(explode("\n", $e->getMessage()));
  393. foreach ($messages as $message) {
  394. $this->_getSession()->addError($message);
  395. }
  396. }
  397.  
  398. $url = $this->_getSession()->getRedirectUrl(true);
  399. if ($url) {
  400. $this->getResponse()->setRedirect($url);
  401. } else {
  402. $this->_redirectReferer(Mage::helper('checkout/cart')->getCartUrl());
  403. }
  404. } catch (Exception $e) {
  405. $this->_getSession()->addException($e, $this->__('Cannot update the item.'));
  406. Mage::logException($e);
  407. $this->_goBack();
  408. }
  409. $this->_redirect('*/*');
  410. }
  411.  
  412. /**
  413. * Update shopping cart data action
  414. */
  415. public function updatePostAction()
  416. {
  417. if (!$this->_validateFormKey()) {
  418. $this->_redirect('*/*/');
  419. return;
  420. }
  421.  
  422. $updateAction = (string)$this->getRequest()->getParam('update_cart_action');
  423.  
  424. switch ($updateAction) {
  425. case 'empty_cart':
  426. $this->_emptyShoppingCart();
  427. break;
  428. case 'update_qty':
  429. $this->_updateShoppingCart();
  430. break;
  431. default:
  432. $this->_updateShoppingCart();
  433. }
  434.  
  435. $this->_goBack();
  436. }
  437.  
  438. /**
  439. * Update customer's shopping cart
  440. */
  441. protected function _updateShoppingCart()
  442. {
  443. try {
  444. $cartData = $this->getRequest()->getParam('cart');
  445. if (is_array($cartData)) {
  446. $filter = new Zend_Filter_LocalizedToNormalized(
  447. array('locale' => Mage::app()->getLocale()->getLocaleCode())
  448. );
  449. foreach ($cartData as $index => $data) {
  450. if (isset($data['qty'])) {
  451. $cartData[$index]['qty'] = $filter->filter(trim($data['qty']));
  452. }
  453. }
  454. $cart = $this->_getCart();
  455. if (! $cart->getCustomerSession()->getCustomer()->getId() && $cart->getQuote()->getCustomerId()) {
  456. $cart->getQuote()->setCustomerId(null);
  457. }
  458.  
  459. $cartData = $cart->suggestItemsQty($cartData);
  460. $cart->updateItems($cartData)
  461. ->save();
  462. }
  463. $this->_getSession()->setCartWasUpdated(true);
  464. } catch (Mage_Core_Exception $e) {
  465. $this->_getSession()->addError(Mage::helper('core')->escapeHtml($e->getMessage()));
  466. } catch (Exception $e) {
  467. $this->_getSession()->addException($e, $this->__('Cannot update shopping cart.'));
  468. Mage::logException($e);
  469. }
  470. }
  471.  
  472. /**
  473. * Empty customer's shopping cart
  474. */
  475. protected function _emptyShoppingCart()
  476. {
  477. try {
  478. $this->_getCart()->truncate()->save();
  479. $this->_getSession()->setCartWasUpdated(true);
  480. } catch (Mage_Core_Exception $exception) {
  481. $this->_getSession()->addError($exception->getMessage());
  482. } catch (Exception $exception) {
  483. $this->_getSession()->addException($exception, $this->__('Cannot update shopping cart.'));
  484. }
  485. }
  486.  
  487. /**
  488. * Delete shoping cart item action
  489. */
  490. public function deleteAction()
  491. {
  492. $id = (int) $this->getRequest()->getParam('id');
  493. if ($id) {
  494. try {
  495. $this->_getCart()->removeItem($id)
  496. ->save();
  497. } catch (Exception $e) {
  498. $this->_getSession()->addError($this->__('Cannot remove the item.'));
  499. Mage::logException($e);
  500. }
  501. }
  502. $this->_redirectReferer(Mage::getUrl('*/*'));
  503. }
  504.  
  505. /**
  506. * Initialize shipping information
  507. */
  508.  
  509. // prashnat
  510.  
  511. public function estimatePostAction()
  512. {
  513. $country = (string) $this->getRequest()->getParam('country_id');
  514. $postcode = (string) $this->getRequest()->getParam('estimate_postcode');
  515. $city = (string) $this->getRequest()->getParam('estimate_city');
  516. $regionId = (string) $this->getRequest()->getParam('region_id');
  517. $region = (string) $this->getRequest()->getParam('region');
  518.  
  519. $zipArray = array('12345','67890');
  520.  
  521. if(in_array($postcode,$zipArray){
  522. Mage::getSingleton('core/session')->setMyShipMessage('Ship is available.');
  523. }else{
  524. Mage::getSingleton('core/session')->setMyShipMessage('Ship is not available.');
  525. }
  526.  
  527. $this->_getQuote()->getShippingAddress()
  528. ->setCountryId($country)
  529. ->setCity($city)
  530. ->setPostcode($postcode)
  531. ->setRegionId($regionId)
  532. ->setRegion($region)
  533. ->setCollectShippingRates(true);
  534. $this->_getQuote()->save();
  535. $this->_goBack();
  536. }
  537.  
  538. // prashant end
  539.  
  540. /**
  541. * Estimate update action
  542. *
  543. * @return null
  544. */
  545. public function estimateUpdatePostAction()
  546. {
  547. $code = (string) $this->getRequest()->getParam('estimate_method');
  548. if (!empty($code)) {
  549. $this->_getQuote()->getShippingAddress()->setShippingMethod($code)/*->collectTotals()*/->save();
  550. }
  551. $this->_goBack();
  552. }
  553.  
  554. /**
  555. * Initialize coupon
  556. */
  557. public function couponPostAction()
  558. {
  559. /**
  560. * No reason continue with empty shopping cart
  561. */
  562. if (!$this->_getCart()->getQuote()->getItemsCount()) {
  563. $this->_goBack();
  564. return;
  565. }
  566.  
  567. $couponCode = (string) $this->getRequest()->getParam('coupon_code');
  568. if ($this->getRequest()->getParam('remove') == 1) {
  569. $couponCode = '';
  570. }
  571. $oldCouponCode = $this->_getQuote()->getCouponCode();
  572.  
  573. if (!strlen($couponCode) && !strlen($oldCouponCode)) {
  574. $this->_goBack();
  575. return;
  576. }
  577.  
  578. try {
  579. $codeLength = strlen($couponCode);
  580. $isCodeLengthValid = $codeLength && $codeLength <= Mage_Checkout_Helper_Cart::COUPON_CODE_MAX_LENGTH;
  581.  
  582. $this->_getQuote()->getShippingAddress()->setCollectShippingRates(true);
  583. $this->_getQuote()->setCouponCode($isCodeLengthValid ? $couponCode : '')
  584. ->collectTotals()
  585. ->save();
  586.  
  587. if ($codeLength) {
  588. if ($isCodeLengthValid && $couponCode == $this->_getQuote()->getCouponCode()) {
  589. $this->_getSession()->addSuccess(
  590. $this->__('Coupon code "%s" was applied.', Mage::helper('core')->escapeHtml($couponCode))
  591. );
  592. } else {
  593. $this->_getSession()->addError(
  594. $this->__('Coupon code "%s" is not valid.', Mage::helper('core')->escapeHtml($couponCode))
  595. );
  596. }
  597. } else {
  598. $this->_getSession()->addSuccess($this->__('Coupon code was canceled.'));
  599. }
  600.  
  601. } catch (Mage_Core_Exception $e) {
  602. $this->_getSession()->addError($e->getMessage());
  603. } catch (Exception $e) {
  604. $this->_getSession()->addError($this->__('Cannot apply the coupon code.'));
  605. Mage::logException($e);
  606. }
  607.  
  608. $this->_goBack();
  609. }
  610.  
  611. /**
  612. * Minicart delete action
  613. */
  614. public function ajaxDeleteAction()
  615. {
  616. if (!$this->_validateFormKey()) {
  617. Mage::throwException('Invalid form key');
  618. }
  619. $id = (int) $this->getRequest()->getParam('id');
  620. $result = array();
  621. if ($id) {
  622. try {
  623. $this->_getCart()->removeItem($id)->save();
  624.  
  625. $result['qty'] = $this->_getCart()->getSummaryQty();
  626.  
  627. $this->loadLayout();
  628. $result['content'] = $this->getLayout()->getBlock('minicart_content')->toHtml();
  629.  
  630. $result['success'] = 1;
  631. $result['message'] = $this->__('Item was removed successfully.');
  632. } catch (Exception $e) {
  633. $result['success'] = 0;
  634. $result['error'] = $this->__('Can not remove the item.');
  635. }
  636. }
  637.  
  638. $this->getResponse()->setHeader('Content-type', 'application/json');
  639. $this->getResponse()->setBody(Mage::helper('core')->jsonEncode($result));
  640. }
  641.  
  642. /**
  643. * Minicart ajax update qty action
  644. */
  645. public function ajaxUpdateAction()
  646. {
  647. if (!$this->_validateFormKey()) {
  648. Mage::throwException('Invalid form key');
  649. }
  650. $id = (int)$this->getRequest()->getParam('id');
  651. $qty = $this->getRequest()->getParam('qty');
  652. $result = array();
  653. if ($id) {
  654. try {
  655. $cart = $this->_getCart();
  656. if (isset($qty)) {
  657. $filter = new Zend_Filter_LocalizedToNormalized(
  658. array('locale' => Mage::app()->getLocale()->getLocaleCode())
  659. );
  660. $qty = $filter->filter($qty);
  661. }
  662.  
  663. $quoteItem = $cart->getQuote()->getItemById($id);
  664. if (!$quoteItem) {
  665. Mage::throwException($this->__('Quote item is not found.'));
  666. }
  667. if ($qty == 0) {
  668. $cart->removeItem($id);
  669. } else {
  670. $quoteItem->setQty($qty)->save();
  671. }
  672. $this->_getCart()->save();
  673.  
  674. $this->loadLayout();
  675. $result['content'] = $this->getLayout()->getBlock('minicart_content')->toHtml();
  676.  
  677. $result['qty'] = $this->_getCart()->getSummaryQty();
  678.  
  679. if (!$quoteItem->getHasError()) {
  680. $result['message'] = $this->__('Item was updated successfully.');
  681. } else {
  682. $result['notice'] = $quoteItem->getMessage();
  683. }
  684. $result['success'] = 1;
  685. } catch (Exception $e) {
  686. $result['success'] = 0;
  687. $result['error'] = $this->__('Can not save item.');
  688. }
  689. }
  690.  
  691. $this->getResponse()->setHeader('Content-type', 'application/json');
  692. $this->getResponse()->setBody(Mage::helper('core')->jsonEncode($result));
  693. }
  694. }
Add Comment
Please, Sign In to add comment