summaryrefslogtreecommitdiffstats
path: root/system/libraries/Cart.php
diff options
context:
space:
mode:
authorFlorian Pritz <bluewind@xinu.at>2017-09-09 16:05:22 +0200
committerFlorian Pritz <bluewind@xinu.at>2017-09-09 16:05:22 +0200
commit27639d64d06b62f237bbde253c46cd28fdce8884 (patch)
tree7a2f00cfd44cfcdfe6cb1abc1cfc0675632948c4 /system/libraries/Cart.php
parent9c5bfbee5b42ea50a5611c537b8dbf01d7a64f79 (diff)
parent6c7a4266410070d30f8f6bcdf9c9e67f3d6478e3 (diff)
Merge tag '3.1.5' into dev-ci3
Signed-off-by: Florian Pritz <bluewind@xinu.at>
Diffstat (limited to 'system/libraries/Cart.php')
-rw-r--r--system/libraries/Cart.php376
1 files changed, 196 insertions, 180 deletions
diff --git a/system/libraries/Cart.php b/system/libraries/Cart.php
index 86a01f796..734c43420 100644
--- a/system/libraries/Cart.php
+++ b/system/libraries/Cart.php
@@ -1,19 +1,41 @@
-<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
+<?php
/**
* CodeIgniter
*
- * An open source application development framework for PHP 5.1.6 or newer
+ * An open source application development framework for PHP
*
- * @package CodeIgniter
- * @author ExpressionEngine Dev Team
- * @copyright Copyright (c) 2006 - 2014, EllisLab, Inc.
- * @license http://codeigniter.com/user_guide/license.html
- * @link http://codeigniter.com
- * @since Version 1.0
+ * This content is released under the MIT License (MIT)
+ *
+ * Copyright (c) 2014 - 2017, British Columbia Institute of Technology
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ *
+ * @package CodeIgniter
+ * @author EllisLab Dev Team
+ * @copyright Copyright (c) 2008 - 2014, EllisLab, Inc. (https://ellislab.com/)
+ * @copyright Copyright (c) 2014 - 2017, British Columbia Institute of Technology (http://bcit.ca/)
+ * @license http://opensource.org/licenses/MIT MIT License
+ * @link https://codeigniter.com
+ * @since Version 1.0.0
* @filesource
*/
-
-// ------------------------------------------------------------------------
+defined('BASEPATH') OR exit('No direct script access allowed');
/**
* Shopping Cart Class
@@ -21,24 +43,58 @@
* @package CodeIgniter
* @subpackage Libraries
* @category Shopping Cart
- * @author ExpressionEngine Dev Team
- * @link http://codeigniter.com/user_guide/libraries/cart.html
+ * @author EllisLab Dev Team
+ * @link https://codeigniter.com/user_guide/libraries/cart.html
+ * @deprecated 3.0.0 This class is too specific for CI.
*/
class CI_Cart {
- // These are the regular expression rules that we use to validate the product ID and product name
- var $product_id_rules = '\.a-z0-9_-'; // alpha-numeric, dashes, underscores, or periods
- var $product_name_rules = '\.\:\-_ a-z0-9'; // alpha-numeric, dashes, underscores, colons or periods
+ /**
+ * These are the regular expression rules that we use to validate the product ID and product name
+ * alpha-numeric, dashes, underscores, or periods
+ *
+ * @var string
+ */
+ public $product_id_rules = '\.a-z0-9_-';
- // Private variables. Do not change!
- var $CI;
- var $_cart_contents = array();
+ /**
+ * These are the regular expression rules that we use to validate the product ID and product name
+ * alpha-numeric, dashes, underscores, colons or periods
+ *
+ * @var string
+ */
+ public $product_name_rules = '\w \-\.\:';
+ /**
+ * only allow safe product names
+ *
+ * @var bool
+ */
+ public $product_name_safe = TRUE;
+
+ // --------------------------------------------------------------------------
+
+ /**
+ * Reference to CodeIgniter instance
+ *
+ * @var object
+ */
+ protected $CI;
+
+ /**
+ * Contents of the cart
+ *
+ * @var array
+ */
+ protected $_cart_contents = array();
/**
* Shopping Class Constructor
*
* The constructor loads the Session class, used to store the shopping cart contents.
+ *
+ * @param array
+ * @return void
*/
public function __construct($params = array())
{
@@ -46,31 +102,20 @@ class CI_Cart {
$this->CI =& get_instance();
// Are any config settings being passed manually? If so, set them
- $config = array();
- if (count($params) > 0)
- {
- foreach ($params as $key => $val)
- {
- $config[$key] = $val;
- }
- }
+ $config = is_array($params) ? $params : array();
// Load the Sessions class
- $this->CI->load->library('session', $config);
+ $this->CI->load->driver('session', $config);
- // Grab the shopping cart array from the session table, if it exists
- if ($this->CI->session->userdata('cart_contents') !== FALSE)
- {
- $this->_cart_contents = $this->CI->session->userdata('cart_contents');
- }
- else
+ // Grab the shopping cart array from the session table
+ $this->_cart_contents = $this->CI->session->userdata('cart_contents');
+ if ($this->_cart_contents === NULL)
{
// No cart exists so we'll set some base values
- $this->_cart_contents['cart_total'] = 0;
- $this->_cart_contents['total_items'] = 0;
+ $this->_cart_contents = array('cart_total' => 0, 'total_items' => 0);
}
- log_message('debug', "Cart Class Initialized");
+ log_message('info', 'Cart Class Initialized');
}
// --------------------------------------------------------------------
@@ -78,14 +123,13 @@ class CI_Cart {
/**
* Insert items into the cart and save it to the session table
*
- * @access public
* @param array
* @return bool
*/
- function insert($items = array())
+ public function insert($items = array())
{
// Was any cart data passed? No? Bah...
- if ( ! is_array($items) OR count($items) == 0)
+ if ( ! is_array($items) OR count($items) === 0)
{
log_message('error', 'The insert method must be passed an array containing data.');
return FALSE;
@@ -108,7 +152,7 @@ class CI_Cart {
{
foreach ($items as $val)
{
- if (is_array($val) AND isset($val['id']))
+ if (is_array($val) && isset($val['id']))
{
if ($this->_insert($val))
{
@@ -119,7 +163,7 @@ class CI_Cart {
}
// Save the cart data if the insert was successful
- if ($save_cart == TRUE)
+ if ($save_cart === TRUE)
{
$this->_save_cart();
return isset($rowid) ? $rowid : TRUE;
@@ -133,14 +177,13 @@ class CI_Cart {
/**
* Insert
*
- * @access private
* @param array
* @return bool
*/
- function _insert($items = array())
+ protected function _insert($items = array())
{
// Was any cart data passed? No? Bah...
- if ( ! is_array($items) OR count($items) == 0)
+ if ( ! is_array($items) OR count($items) === 0)
{
log_message('error', 'The insert method must be passed an array containing data.');
return FALSE;
@@ -149,7 +192,7 @@ class CI_Cart {
// --------------------------------------------------------------------
// Does the $items array contain an id, quantity, price, and name? These are required
- if ( ! isset($items['id']) OR ! isset($items['qty']) OR ! isset($items['price']) OR ! isset($items['name']))
+ if ( ! isset($items['id'], $items['qty'], $items['price'], $items['name']))
{
log_message('error', 'The cart array must contain a product ID, quantity, price, and name.');
return FALSE;
@@ -157,13 +200,11 @@ class CI_Cart {
// --------------------------------------------------------------------
- // Prep the quantity. It can only be a number. Duh...
- $items['qty'] = trim(preg_replace('/([^0-9])/i', '', $items['qty']));
- // Trim any leading zeros
- $items['qty'] = trim(preg_replace('/(^[0]+)/i', '', $items['qty']));
+ // Prep the quantity. It can only be a number. Duh... also trim any leading zeros
+ $items['qty'] = (float) $items['qty'];
// If the quantity is zero or blank there's nothing for us to do
- if ( ! is_numeric($items['qty']) OR $items['qty'] == 0)
+ if ($items['qty'] == 0)
{
return FALSE;
}
@@ -173,7 +214,7 @@ class CI_Cart {
// Validate the product ID. It can only be alpha-numeric, dashes, underscores or periods
// Not totally sure we should impose this rule, but it seems prudent to standardize IDs.
// Note: These can be user-specified by setting the $this->product_id_rules variable.
- if ( ! preg_match("/^[".$this->product_id_rules."]+$/i", $items['id']))
+ if ( ! preg_match('/^['.$this->product_id_rules.']+$/i', $items['id']))
{
log_message('error', 'Invalid product ID. The product ID can only contain alpha-numeric characters, dashes, and underscores');
return FALSE;
@@ -183,7 +224,7 @@ class CI_Cart {
// Validate the product name. It can only be alpha-numeric, dashes, underscores, colons or periods.
// Note: These can be user-specified by setting the $this->product_name_rules variable.
- if ( ! preg_match("/^[".$this->product_name_rules."]+$/i", $items['name']))
+ if ($this->product_name_safe && ! preg_match('/^['.$this->product_name_rules.']+$/i'.(UTF8_ENABLED ? 'u' : ''), $items['name']))
{
log_message('error', 'An invalid name was submitted as the product name: '.$items['name'].' The name can only contain alpha-numeric characters, dashes, underscores, colons, and spaces');
return FALSE;
@@ -191,19 +232,8 @@ class CI_Cart {
// --------------------------------------------------------------------
- // Prep the price. Remove anything that isn't a number or decimal point.
- $items['price'] = trim(preg_replace('/([^0-9\.])/i', '', $items['price']));
- // Trim any leading zeros
- $items['price'] = trim(preg_replace('/(^[0]+)/i', '', $items['price']));
-
- // Is the price a valid number?
- if ( ! is_numeric($items['price']))
- {
- log_message('error', 'An invalid price was submitted for product ID: '.$items['id']);
- return FALSE;
- }
-
- // --------------------------------------------------------------------
+ // Prep the price. Remove leading zeros and anything that isn't a number or decimal point.
+ $items['price'] = (float) $items['price'];
// We now need to create a unique identifier for the item being inserted into the cart.
// Every time something is added to the cart it is stored in the master cart array.
@@ -215,9 +245,9 @@ class CI_Cart {
// Internally, we need to treat identical submissions, but with different options, as a unique product.
// Our solution is to convert the options array to a string and MD5 it along with the product ID.
// This becomes the unique "row ID"
- if (isset($items['options']) AND count($items['options']) > 0)
+ if (isset($items['options']) && count($items['options']) > 0)
{
- $rowid = md5($items['id'].implode('', $items['options']));
+ $rowid = md5($items['id'].serialize($items['options']));
}
else
{
@@ -230,20 +260,14 @@ class CI_Cart {
// --------------------------------------------------------------------
// Now that we have our unique "row ID", we'll add our cart items to the master array
+ // grab quantity if it's already there and add it on
+ $old_quantity = isset($this->_cart_contents[$rowid]['qty']) ? (int) $this->_cart_contents[$rowid]['qty'] : 0;
- // let's unset this first, just to make sure our index contains only the data from this submission
- unset($this->_cart_contents[$rowid]);
-
- // Create a new index with our new row ID
- $this->_cart_contents[$rowid]['rowid'] = $rowid;
-
- // And add the new items to the cart array
- foreach ($items as $key => $val)
- {
- $this->_cart_contents[$rowid][$key] = $val;
- }
+ // Re-create the entry, just to make sure our index contains only the data from this submission
+ $items['rowid'] = $rowid;
+ $items['qty'] += $old_quantity;
+ $this->_cart_contents[$rowid] = $items;
- // Woot!
return $rowid;
}
@@ -257,27 +281,25 @@ class CI_Cart {
* changes to the quantity before checkout. That array must contain the
* product ID and quantity for each item.
*
- * @access public
* @param array
- * @param string
* @return bool
*/
- function update($items = array())
+ public function update($items = array())
{
// Was any cart data passed?
- if ( ! is_array($items) OR count($items) == 0)
+ if ( ! is_array($items) OR count($items) === 0)
{
return FALSE;
}
// You can either update a single product using a one-dimensional array,
// or multiple products using a multi-dimensional one. The way we
- // determine the array type is by looking for a required array key named "id".
+ // determine the array type is by looking for a required array key named "rowid".
// If it's not found we assume it's a multi-dimensional array
$save_cart = FALSE;
- if (isset($items['rowid']) AND isset($items['qty']))
+ if (isset($items['rowid']))
{
- if ($this->_update($items) == TRUE)
+ if ($this->_update($items) === TRUE)
{
$save_cart = TRUE;
}
@@ -286,9 +308,9 @@ class CI_Cart {
{
foreach ($items as $val)
{
- if (is_array($val) AND isset($val['rowid']) AND isset($val['qty']))
+ if (is_array($val) && isset($val['rowid']))
{
- if ($this->_update($val) == TRUE)
+ if ($this->_update($val) === TRUE)
{
$save_cart = TRUE;
}
@@ -297,7 +319,7 @@ class CI_Cart {
}
// Save the cart data if the insert was successful
- if ($save_cart == TRUE)
+ if ($save_cart === TRUE)
{
$this->_save_cart();
return TRUE;
@@ -311,48 +333,47 @@ class CI_Cart {
/**
* Update the cart
*
- * This function permits the quantity of a given item to be changed.
+ * This function permits changing item properties.
* Typically it is called from the "view cart" page if a user makes
* changes to the quantity before checkout. That array must contain the
- * product ID and quantity for each item.
+ * rowid and quantity for each item.
*
- * @access private
* @param array
* @return bool
*/
- function _update($items = array())
+ protected function _update($items = array())
{
// Without these array indexes there is nothing we can do
- if ( ! isset($items['qty']) OR ! isset($items['rowid']) OR ! isset($this->_cart_contents[$items['rowid']]))
+ if ( ! isset($items['rowid'], $this->_cart_contents[$items['rowid']]))
{
return FALSE;
}
// Prep the quantity
- $items['qty'] = preg_replace('/([^0-9])/i', '', $items['qty']);
-
- // Is the quantity a number?
- if ( ! is_numeric($items['qty']))
+ if (isset($items['qty']))
{
- return FALSE;
+ $items['qty'] = (float) $items['qty'];
+ // Is the quantity zero? If so we will remove the item from the cart.
+ // If the quantity is greater than zero we are updating
+ if ($items['qty'] == 0)
+ {
+ unset($this->_cart_contents[$items['rowid']]);
+ return TRUE;
+ }
}
- // Is the new quantity different than what is already saved in the cart?
- // If it's the same there's nothing to do
- if ($this->_cart_contents[$items['rowid']]['qty'] == $items['qty'])
+ // find updatable keys
+ $keys = array_intersect(array_keys($this->_cart_contents[$items['rowid']]), array_keys($items));
+ // if a price was passed, make sure it contains valid data
+ if (isset($items['price']))
{
- return FALSE;
+ $items['price'] = (float) $items['price'];
}
- // Is the quantity zero? If so we will remove the item from the cart.
- // If the quantity is greater than zero we are updating
- if ($items['qty'] == 0)
+ // product id & name shouldn't be changed
+ foreach (array_diff($keys, array('id', 'name')) as $key)
{
- unset($this->_cart_contents[$items['rowid']]);
- }
- else
- {
- $this->_cart_contents[$items['rowid']]['qty'] = $items['qty'];
+ $this->_cart_contents[$items['rowid']][$key] = $items[$key];
}
return TRUE;
@@ -363,38 +384,26 @@ class CI_Cart {
/**
* Save the cart array to the session DB
*
- * @access private
* @return bool
*/
- function _save_cart()
+ protected function _save_cart()
{
- // Unset these so our total can be calculated correctly below
- unset($this->_cart_contents['total_items']);
- unset($this->_cart_contents['cart_total']);
-
- // Lets add up the individual prices and set the cart sub-total
- $total = 0;
- $items = 0;
+ // Let's add up the individual prices and set the cart sub-total
+ $this->_cart_contents['total_items'] = $this->_cart_contents['cart_total'] = 0;
foreach ($this->_cart_contents as $key => $val)
{
// We make sure the array contains the proper indexes
- if ( ! is_array($val) OR ! isset($val['price']) OR ! isset($val['qty']))
+ if ( ! is_array($val) OR ! isset($val['price'], $val['qty']))
{
continue;
}
- $total += ($val['price'] * $val['qty']);
- $items += $val['qty'];
-
- // Set the subtotal
+ $this->_cart_contents['cart_total'] += ($val['price'] * $val['qty']);
+ $this->_cart_contents['total_items'] += $val['qty'];
$this->_cart_contents[$key]['subtotal'] = ($this->_cart_contents[$key]['price'] * $this->_cart_contents[$key]['qty']);
}
- // Set the cart total and total items.
- $this->_cart_contents['total_items'] = $items;
- $this->_cart_contents['cart_total'] = $total;
-
- // Is our cart empty? If so we delete it from the session
+ // Is our cart empty? If so we delete it from the session
if (count($this->_cart_contents) <= 2)
{
$this->CI->session->unset_userdata('cart_contents');
@@ -416,10 +425,9 @@ class CI_Cart {
/**
* Cart Total
*
- * @access public
- * @return integer
+ * @return int
*/
- function total()
+ public function total()
{
return $this->_cart_contents['cart_total'];
}
@@ -427,14 +435,31 @@ class CI_Cart {
// --------------------------------------------------------------------
/**
+ * Remove Item
+ *
+ * Removes an item from the cart
+ *
+ * @param int
+ * @return bool
+ */
+ public function remove($rowid)
+ {
+ // unset & save
+ unset($this->_cart_contents[$rowid]);
+ $this->_save_cart();
+ return TRUE;
+ }
+
+ // --------------------------------------------------------------------
+
+ /**
* Total Items
*
* Returns the total item count
*
- * @access public
- * @return integer
+ * @return int
*/
- function total_items()
+ public function total_items()
{
return $this->_cart_contents['total_items'];
}
@@ -446,12 +471,13 @@ class CI_Cart {
*
* Returns the entire cart array
*
- * @access public
+ * @param bool
* @return array
*/
- function contents()
+ public function contents($newest_first = FALSE)
{
- $cart = $this->_cart_contents;
+ // do we want the newest first?
+ $cart = ($newest_first) ? array_reverse($this->_cart_contents) : $this->_cart_contents;
// Remove these so they don't create a problem when showing the cart table
unset($cart['total_items']);
@@ -463,22 +489,34 @@ class CI_Cart {
// --------------------------------------------------------------------
/**
+ * Get cart item
+ *
+ * Returns the details of a specific item in the cart
+ *
+ * @param string $row_id
+ * @return array
+ */
+ public function get_item($row_id)
+ {
+ return (in_array($row_id, array('total_items', 'cart_total'), TRUE) OR ! isset($this->_cart_contents[$row_id]))
+ ? FALSE
+ : $this->_cart_contents[$row_id];
+ }
+
+ // --------------------------------------------------------------------
+
+ /**
* Has options
*
* Returns TRUE if the rowid passed to this function correlates to an item
* that has options associated with it.
*
- * @access public
- * @return array
+ * @param string $row_id = ''
+ * @return bool
*/
- function has_options($rowid = '')
+ public function has_options($row_id = '')
{
- if ( ! isset($this->_cart_contents[$rowid]['options']) OR count($this->_cart_contents[$rowid]['options']) === 0)
- {
- return FALSE;
- }
-
- return TRUE;
+ return (isset($this->_cart_contents[$row_id]['options']) && count($this->_cart_contents[$row_id]['options']) !== 0);
}
// --------------------------------------------------------------------
@@ -488,17 +526,12 @@ class CI_Cart {
*
* Returns the an array of options, for a particular product row ID
*
- * @access public
+ * @param string $row_id = ''
* @return array
*/
- function product_options($rowid = '')
+ public function product_options($row_id = '')
{
- if ( ! isset($this->_cart_contents[$rowid]['options']))
- {
- return array();
- }
-
- return $this->_cart_contents[$rowid]['options'];
+ return isset($this->_cart_contents[$row_id]['options']) ? $this->_cart_contents[$row_id]['options'] : array();
}
// --------------------------------------------------------------------
@@ -508,20 +541,12 @@ class CI_Cart {
*
* Returns the supplied number with commas and a decimal point.
*
- * @access public
- * @return integer
+ * @param float
+ * @return string
*/
- function format_number($n = '')
+ public function format_number($n = '')
{
- if ($n == '')
- {
- return '';
- }
-
- // Remove anything that isn't a number or decimal point.
- $n = trim(preg_replace('/([^0-9\.])/i', '', $n));
-
- return number_format($n, 2, '.', ',');
+ return ($n === '') ? '' : number_format( (float) $n, 2, '.', ',');
}
// --------------------------------------------------------------------
@@ -531,21 +556,12 @@ class CI_Cart {
*
* Empties the cart and kills the session
*
- * @access public
- * @return null
+ * @return void
*/
- function destroy()
+ public function destroy()
{
- unset($this->_cart_contents);
-
- $this->_cart_contents['cart_total'] = 0;
- $this->_cart_contents['total_items'] = 0;
-
+ $this->_cart_contents = array('cart_total' => 0, 'total_items' => 0);
$this->CI->session->unset_userdata('cart_contents');
}
-
}
-
-/* End of file Cart.php */
-/* Location: ./system/libraries/Cart.php */ \ No newline at end of file