forked from OpenMage/magento-mirror
/
CartController.php
553 lines (498 loc) · 18.9 KB
/
CartController.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
<?php
/**
* Magento
*
* NOTICE OF LICENSE
*
* This source file is subject to the Open Software License (OSL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://opensource.org/licenses/osl-3.0.php
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@magentocommerce.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade Magento to newer
* versions in the future. If you wish to customize Magento for your
* needs please refer to http://www.magentocommerce.com for more information.
*
* @category Mage
* @package Mage_Checkout
* @copyright Copyright (c) 2012 Magento Inc. (http://www.magentocommerce.com)
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
*/
/**
* Shopping cart controller
*/
class Mage_Checkout_CartController extends Mage_Core_Controller_Front_Action
{
/**
* Action list where need check enabled cookie
*
* @var array
*/
protected $_cookieCheckActions = array('add');
/**
* Retrieve shopping cart model object
*
* @return Mage_Checkout_Model_Cart
*/
protected function _getCart()
{
return Mage::getSingleton('checkout/cart');
}
/**
* Get checkout session model instance
*
* @return Mage_Checkout_Model_Session
*/
protected function _getSession()
{
return Mage::getSingleton('checkout/session');
}
/**
* Get current active quote instance
*
* @return Mage_Sales_Model_Quote
*/
protected function _getQuote()
{
return $this->_getCart()->getQuote();
}
/**
* Set back redirect url to response
*
* @return Mage_Checkout_CartController
*/
protected function _goBack()
{
$returnUrl = $this->getRequest()->getParam('return_url');
if ($returnUrl) {
if (!$this->_isUrlInternal($returnUrl)) {
throw new Mage_Exception('External urls redirect to "' . $returnUrl . '" denied!');
}
$this->_getSession()->getMessages(true);
$this->getResponse()->setRedirect($returnUrl);
} elseif (!Mage::getStoreConfig('checkout/cart/redirect_to_cart')
&& !$this->getRequest()->getParam('in_cart')
&& $backUrl = $this->_getRefererUrl()
) {
$this->getResponse()->setRedirect($backUrl);
} else {
if (($this->getRequest()->getActionName() == 'add') && !$this->getRequest()->getParam('in_cart')) {
$this->_getSession()->setContinueShoppingUrl($this->_getRefererUrl());
}
$this->_redirect('checkout/cart');
}
return $this;
}
/**
* Initialize product instance from request data
*
* @return Mage_Catalog_Model_Product || false
*/
protected function _initProduct()
{
$productId = (int) $this->getRequest()->getParam('product');
if ($productId) {
$product = Mage::getModel('catalog/product')
->setStoreId(Mage::app()->getStore()->getId())
->load($productId);
if ($product->getId()) {
return $product;
}
}
return false;
}
/**
* Shopping cart display action
*/
public function indexAction()
{
$cart = $this->_getCart();
if ($cart->getQuote()->getItemsCount()) {
$cart->init();
$cart->save();
if (!$this->_getQuote()->validateMinimumAmount()) {
$minimumAmount = Mage::app()->getLocale()->currency(Mage::app()->getStore()->getCurrentCurrencyCode())
->toCurrency(Mage::getStoreConfig('sales/minimum_order/amount'));
$warning = Mage::getStoreConfig('sales/minimum_order/description')
? Mage::getStoreConfig('sales/minimum_order/description')
: Mage::helper('checkout')->__('Minimum order amount is %s', $minimumAmount);
$cart->getCheckoutSession()->addNotice($warning);
}
}
// Compose array of messages to add
$messages = array();
foreach ($cart->getQuote()->getMessages() as $message) {
if ($message) {
// Escape HTML entities in quote message to prevent XSS
$message->setCode(Mage::helper('core')->escapeHtml($message->getCode()));
$messages[] = $message;
}
}
$cart->getCheckoutSession()->addUniqueMessages($messages);
/**
* if customer enteres shopping cart we should mark quote
* as modified bc he can has checkout page in another window.
*/
$this->_getSession()->setCartWasUpdated(true);
Varien_Profiler::start(__METHOD__ . 'cart_display');
$this
->loadLayout()
->_initLayoutMessages('checkout/session')
->_initLayoutMessages('catalog/session')
->getLayout()->getBlock('head')->setTitle($this->__('Shopping Cart'));
$this->renderLayout();
Varien_Profiler::stop(__METHOD__ . 'cart_display');
}
/**
* Add product to shopping cart action
*/
public function addAction()
{
$cart = $this->_getCart();
$params = $this->getRequest()->getParams();
try {
if (isset($params['qty'])) {
$filter = new Zend_Filter_LocalizedToNormalized(
array('locale' => Mage::app()->getLocale()->getLocaleCode())
);
$params['qty'] = $filter->filter($params['qty']);
}
$product = $this->_initProduct();
$related = $this->getRequest()->getParam('related_product');
/**
* Check product availability
*/
if (!$product) {
$this->_goBack();
return;
}
$cart->addProduct($product, $params);
if (!empty($related)) {
$cart->addProductsByIds(explode(',', $related));
}
$cart->save();
$this->_getSession()->setCartWasUpdated(true);
/**
* @todo remove wishlist observer processAddToCart
*/
Mage::dispatchEvent('checkout_cart_add_product_complete',
array('product' => $product, 'request' => $this->getRequest(), 'response' => $this->getResponse())
);
if (!$this->_getSession()->getNoCartRedirect(true)) {
if (!$cart->getQuote()->getHasError()){
$message = $this->__('%s was added to your shopping cart.', Mage::helper('core')->escapeHtml($product->getName()));
$this->_getSession()->addSuccess($message);
}
$this->_goBack();
}
} catch (Mage_Core_Exception $e) {
if ($this->_getSession()->getUseNotice(true)) {
$this->_getSession()->addNotice(Mage::helper('core')->escapeHtml($e->getMessage()));
} else {
$messages = array_unique(explode("\n", $e->getMessage()));
foreach ($messages as $message) {
$this->_getSession()->addError(Mage::helper('core')->escapeHtml($message));
}
}
$url = $this->_getSession()->getRedirectUrl(true);
if ($url) {
$this->getResponse()->setRedirect($url);
} else {
$this->_redirectReferer(Mage::helper('checkout/cart')->getCartUrl());
}
} catch (Exception $e) {
$this->_getSession()->addException($e, $this->__('Cannot add the item to shopping cart.'));
Mage::logException($e);
$this->_goBack();
}
}
public function addgroupAction()
{
$orderItemIds = $this->getRequest()->getParam('order_items', array());
if (is_array($orderItemIds)) {
$itemsCollection = Mage::getModel('sales/order_item')
->getCollection()
->addIdFilter($orderItemIds)
->load();
/* @var $itemsCollection Mage_Sales_Model_Mysql4_Order_Item_Collection */
$cart = $this->_getCart();
foreach ($itemsCollection as $item) {
try {
$cart->addOrderItem($item, 1);
} catch (Mage_Core_Exception $e) {
if ($this->_getSession()->getUseNotice(true)) {
$this->_getSession()->addNotice($e->getMessage());
} else {
$this->_getSession()->addError($e->getMessage());
}
} catch (Exception $e) {
$this->_getSession()->addException($e, $this->__('Cannot add the item to shopping cart.'));
Mage::logException($e);
$this->_goBack();
}
}
$cart->save();
$this->_getSession()->setCartWasUpdated(true);
}
$this->_goBack();
}
/**
* Action to reconfigure cart item
*/
public function configureAction()
{
// Extract item and product to configure
$id = (int) $this->getRequest()->getParam('id');
$quoteItem = null;
$cart = $this->_getCart();
if ($id) {
$quoteItem = $cart->getQuote()->getItemById($id);
}
if (!$quoteItem) {
$this->_getSession()->addError($this->__('Quote item is not found.'));
$this->_redirect('checkout/cart');
return;
}
try {
$params = new Varien_Object();
$params->setCategoryId(false);
$params->setConfigureMode(true);
$params->setBuyRequest($quoteItem->getBuyRequest());
Mage::helper('catalog/product_view')->prepareAndRender($quoteItem->getProduct()->getId(), $this, $params);
} catch (Exception $e) {
$this->_getSession()->addError($this->__('Cannot configure product.'));
Mage::logException($e);
$this->_goBack();
return;
}
}
/**
* Update product configuration for a cart item
*/
public function updateItemOptionsAction()
{
$cart = $this->_getCart();
$id = (int) $this->getRequest()->getParam('id');
$params = $this->getRequest()->getParams();
if (!isset($params['options'])) {
$params['options'] = array();
}
try {
if (isset($params['qty'])) {
$filter = new Zend_Filter_LocalizedToNormalized(
array('locale' => Mage::app()->getLocale()->getLocaleCode())
);
$params['qty'] = $filter->filter($params['qty']);
}
$quoteItem = $cart->getQuote()->getItemById($id);
if (!$quoteItem) {
Mage::throwException($this->__('Quote item is not found.'));
}
$item = $cart->updateItem($id, new Varien_Object($params));
if (is_string($item)) {
Mage::throwException($item);
}
if ($item->getHasError()) {
Mage::throwException($item->getMessage());
}
$related = $this->getRequest()->getParam('related_product');
if (!empty($related)) {
$cart->addProductsByIds(explode(',', $related));
}
$cart->save();
$this->_getSession()->setCartWasUpdated(true);
Mage::dispatchEvent('checkout_cart_update_item_complete',
array('item' => $item, 'request' => $this->getRequest(), 'response' => $this->getResponse())
);
if (!$this->_getSession()->getNoCartRedirect(true)) {
if (!$cart->getQuote()->getHasError()){
$message = $this->__('%s was updated in your shopping cart.', Mage::helper('core')->htmlEscape($item->getProduct()->getName()));
$this->_getSession()->addSuccess($message);
}
$this->_goBack();
}
} catch (Mage_Core_Exception $e) {
if ($this->_getSession()->getUseNotice(true)) {
$this->_getSession()->addNotice($e->getMessage());
} else {
$messages = array_unique(explode("\n", $e->getMessage()));
foreach ($messages as $message) {
$this->_getSession()->addError($message);
}
}
$url = $this->_getSession()->getRedirectUrl(true);
if ($url) {
$this->getResponse()->setRedirect($url);
} else {
$this->_redirectReferer(Mage::helper('checkout/cart')->getCartUrl());
}
} catch (Exception $e) {
$this->_getSession()->addException($e, $this->__('Cannot update the item.'));
Mage::logException($e);
$this->_goBack();
}
$this->_redirect('*/*');
}
/**
* Update shopping cart data action
*/
public function updatePostAction()
{
$updateAction = (string)$this->getRequest()->getParam('update_cart_action');
switch ($updateAction) {
case 'empty_cart':
$this->_emptyShoppingCart();
break;
case 'update_qty':
$this->_updateShoppingCart();
break;
default:
$this->_updateShoppingCart();
}
$this->_goBack();
}
/**
* Update customer's shopping cart
*/
protected function _updateShoppingCart()
{
try {
$cartData = $this->getRequest()->getParam('cart');
if (is_array($cartData)) {
$filter = new Zend_Filter_LocalizedToNormalized(
array('locale' => Mage::app()->getLocale()->getLocaleCode())
);
foreach ($cartData as $index => $data) {
if (isset($data['qty'])) {
$cartData[$index]['qty'] = $filter->filter(trim($data['qty']));
}
}
$cart = $this->_getCart();
if (! $cart->getCustomerSession()->getCustomer()->getId() && $cart->getQuote()->getCustomerId()) {
$cart->getQuote()->setCustomerId(null);
}
$cartData = $cart->suggestItemsQty($cartData);
$cart->updateItems($cartData)
->save();
}
$this->_getSession()->setCartWasUpdated(true);
} catch (Mage_Core_Exception $e) {
$this->_getSession()->addError(Mage::helper('core')->escapeHtml($e->getMessage()));
} catch (Exception $e) {
$this->_getSession()->addException($e, $this->__('Cannot update shopping cart.'));
Mage::logException($e);
}
}
/**
* Empty customer's shopping cart
*/
protected function _emptyShoppingCart()
{
try {
$this->_getCart()->truncate()->save();
$this->_getSession()->setCartWasUpdated(true);
} catch (Mage_Core_Exception $exception) {
$this->_getSession()->addError($exception->getMessage());
} catch (Exception $exception) {
$this->_getSession()->addException($exception, $this->__('Cannot update shopping cart.'));
}
}
/**
* Delete shoping cart item action
*/
public function deleteAction()
{
$id = (int) $this->getRequest()->getParam('id');
if ($id) {
try {
$this->_getCart()->removeItem($id)
->save();
} catch (Exception $e) {
$this->_getSession()->addError($this->__('Cannot remove the item.'));
Mage::logException($e);
}
}
$this->_redirectReferer(Mage::getUrl('*/*'));
}
/**
* Initialize shipping information
*/
public function estimatePostAction()
{
$country = (string) $this->getRequest()->getParam('country_id');
$postcode = (string) $this->getRequest()->getParam('estimate_postcode');
$city = (string) $this->getRequest()->getParam('estimate_city');
$regionId = (string) $this->getRequest()->getParam('region_id');
$region = (string) $this->getRequest()->getParam('region');
$this->_getQuote()->getShippingAddress()
->setCountryId($country)
->setCity($city)
->setPostcode($postcode)
->setRegionId($regionId)
->setRegion($region)
->setCollectShippingRates(true);
$this->_getQuote()->save();
$this->_goBack();
}
public function estimateUpdatePostAction()
{
$code = (string) $this->getRequest()->getParam('estimate_method');
if (!empty($code)) {
$this->_getQuote()->getShippingAddress()->setShippingMethod($code)/*->collectTotals()*/->save();
}
$this->_goBack();
}
/**
* Initialize coupon
*/
public function couponPostAction()
{
/**
* No reason continue with empty shopping cart
*/
if (!$this->_getCart()->getQuote()->getItemsCount()) {
$this->_goBack();
return;
}
$couponCode = (string) $this->getRequest()->getParam('coupon_code');
if ($this->getRequest()->getParam('remove') == 1) {
$couponCode = '';
}
$oldCouponCode = $this->_getQuote()->getCouponCode();
if (!strlen($couponCode) && !strlen($oldCouponCode)) {
$this->_goBack();
return;
}
try {
$this->_getQuote()->getShippingAddress()->setCollectShippingRates(true);
$this->_getQuote()->setCouponCode(strlen($couponCode) ? $couponCode : '')
->collectTotals()
->save();
if (strlen($couponCode)) {
if ($couponCode == $this->_getQuote()->getCouponCode()) {
$this->_getSession()->addSuccess(
$this->__('Coupon code "%s" was applied.', Mage::helper('core')->htmlEscape($couponCode))
);
}
else {
$this->_getSession()->addError(
$this->__('Coupon code "%s" is not valid.', Mage::helper('core')->htmlEscape($couponCode))
);
}
} else {
$this->_getSession()->addSuccess($this->__('Coupon code was canceled.'));
}
} catch (Mage_Core_Exception $e) {
$this->_getSession()->addError($e->getMessage());
} catch (Exception $e) {
$this->_getSession()->addError($this->__('Cannot apply the coupon code.'));
Mage::logException($e);
}
$this->_goBack();
}
}