Location: PHPKode > projects > Maian Gallery > maian_gallery/classes/class_cart.inc.php
<?php

/*++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

  Script: Maian Gallery v2.0
  Written by: David Ian Bennett
  E-Mail: hide@address.com
  Website: http://www.maianscriptworld.co.uk

  ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
  
  This File: class_cart.inc.php
  Description: Shopping Cart Class

  ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/

class mga_Cart extends genericOptions {

var $prefix,$shipRate,$shipSingle; 

// Assign cart vars..
function assignCartVars()
{
  $_SESSION['cart_count']  = '0';
  $_SESSION['pic_id']      = array();
  $_SESSION['pic_size']    = array();
  $_SESSION['pic_cost']    = array();
  $_SESSION['pic_item']    = array();
  $_SESSION['pic_qty']     = array();
  $_SESSION['pic_code']    = array();
  $_SESSION['pic_price']   = array();
}

// Adds pictures to cart..
function addToCart($pic,$size,$cost,$item,$qty)
{
  $q_pic = mysql_query("SELECT * FROM ".$this->prefix."images 
                        WHERE id = '{$pic}' 
                        LIMIT 1
                        ") or die(mysql_error());
  $PICTURE = mysql_fetch_object($q_pic);
  
  // Assign session vars if cart is empty..
  if (!isset($_SESSION['cart_count']) || (isset($_SESSION['cart_count']) && $_SESSION['cart_count']==0))
  {
    // Clear vars if present..
    if (isset($_SESSION['cart_count'])) {
      $this->clearCart();
    }
    
    // Assign vars..
    $this->assignCartVars();
  }
  
  // Is picture already in array..
  // If so, re-calculate and update picture total..
  // Prevents adding another entry for the same image..
  if (is_array($_SESSION['pic_id']) && in_array($pic,$_SESSION['pic_id'])) {
    $this->rebuildCartData($pic,$size,$cost,$item,$qty);
  } else {
    // Add data to session vars..
    $_SESSION['cart_count']  = $_SESSION['cart_count']+1;
    $_SESSION['pic_id'][]    = $pic;
    $_SESSION['pic_size'][]  = $size;
    $_SESSION['pic_cost'][]  = number_format($qty*$cost,2);
    $_SESSION['pic_item'][]  = $item;
    $_SESSION['pic_qty'][]   = $qty;
    $_SESSION['pic_code'][]  = strtolower($this->random_data(50));
    $_SESSION['pic_price'][] = $cost;
  }
}

// Rebuilds cart data if duplicate image is found..
function rebuildCartData($pic,$size,$cost,$item,$qty)
{
  // Now rebuild..
  for ($i=0; $i<count($_SESSION['pic_code']); $i++) {
    $match = ($pic===$_SESSION['pic_id'][$i] ? true : false);
    $_SESSION['pic_id'][$i]    = $_SESSION['pic_id'][$i];
    $_SESSION['pic_size'][$i]  = $_SESSION['pic_size'][$i];
    $_SESSION['pic_cost'][$i]  = ($match ? number_format($qty+$_SESSION['pic_qty'][$i]*$cost,2) : $_SESSION['pic_cost'][$i]);
    $_SESSION['pic_item'][$i]  = $_SESSION['pic_item'][$i];
    $_SESSION['pic_qty'][$i]   = ($match ? $qty+$_SESSION['pic_qty'][$i] : $_SESSION['pic_qty'][$i]);
    $_SESSION['pic_code'][$i]  = $_SESSION['pic_code'][$i];
    $_SESSION['pic_price'][$i] = $cost;
    unset($match);
  }
}

// Delete cart item..
function deleteCartItem($item)
{
  // Loop through cart...
  for ($i=0; $i<count($_SESSION['pic_code']); $i++) {
    if ($item===$_SESSION['pic_code'][$i]) {
      $this->clearSessionSlot($i);
    }
  }
  
  // If cart is now empty, clear vars..
  if ($_SESSION['cart_count']==0) {
    $this->clearCart();
  }
}

// Clears all cart items..
function clearCart()
{
  unset($_SESSION['pic_id']);
  unset($_SESSION['pic_size']);
  unset($_SESSION['pic_cost']);
  unset($_SESSION['pic_item']);
  unset($_SESSION['pic_qty']);
  unset($_SESSION['pic_code']);    
  unset($_SESSION['pic_price']);
  unset($_SESSION['cart_count']);
  unset($_SESSION);
  session_unset();
  session_destroy();
}

// Gets cost of cart...
function cartTotal($grand=false)
{
  $cost = '0.00';
  
  if (isset($_SESSION['cart_count']) && $_SESSION['cart_count']>0) {
    for ($i=0; $i<count($_SESSION['pic_cost']); $i++) {
      if ($_SESSION['pic_cost'][$i]>0) {
        $cost = $cost+$_SESSION['pic_cost'][$i];
      }  
    }
    if ($grand && $this->setShippingCharge()>0) {
      $cost = $cost+$this->setShippingCharge();
    }
  }
  
  return $this->formatPrice($cost);
}

// Calculates shipping charge if applicable..
function setShippingCharge()
{
  $cost = '0.00';
  
  // Is shipping to be applied?
  if ($this->shipRate!='0' || $this->shipSingle!='0') {
    // Assign vars..
    $default = ($this->shipSingle!='0' ? 'single' : 'rate');
    $rate    = ($this->shipSingle!='0' ? $this->shipSingle : $this->shipRate);
      
    // Calculate shipping charge..
    switch ($default) {
      case 'single': 
      $cost = $rate*array_sum($_SESSION['pic_qty']);
      break;
      case 'rate': 
      $cost = $this->shipRate;
      break;
    }  
  }
  
  return $this->formatPrice($cost);
}

// Gets count of items in cart..
function cartCount()
{
  return (isset($_SESSION['pic_qty']) ? array_sum($_SESSION['pic_qty']) : '0');
}

// Format price..
// This prevents problems with prices including a comma..ie: 1,000.00
function formatPrice($price) 
{
  $price = preg_replace("/[^0-9\.]/", "", str_replace(',','.',$price));
  if (substr($price,-3,1)=='.') {
    $cents = '.'.substr($price,-2);
    $price = substr($price,0,strlen($price)-3);
  } elseif (substr($price,-2,1)=='.') {
    $cents = '.'.substr($price,-1);
    $price = substr($price,0,strlen($price)-2);
  } else {
    $cents = '.00';
  }
  $price = preg_replace("/[^0-9]/", "", $price);
  return number_format($price.$cents,2,'.','');
}

// Gets array data based on array slot..
function getCartSessionData($slot)
{
  return array($_SESSION['pic_id'][$slot],
               $_SESSION['pic_size'][$slot],
               $_SESSION['pic_cost'][$slot],
               $_SESSION['pic_item'][$slot],
               $_SESSION['pic_qty'][$slot],
               $_SESSION['pic_code'][$slot],
               $_SESSION['pic_price'][$slot]
               );
}

// Clears single slot..
function clearSessionSlot($slot)
{
  $_SESSION['pic_id'][$slot]    = '0';
  $_SESSION['pic_size'][$slot]  = '0';
  $_SESSION['pic_cost'][$slot]  = '0';
  $_SESSION['pic_item'][$slot]  = '0';
  $_SESSION['pic_qty'][$slot]   = '0';
  $_SESSION['pic_code'][$slot]  = '0';
  $_SESSION['pic_price'][$slot] = '0';
      
  $_SESSION['cart_count']       = $_SESSION['cart_count']-1;
}

// Update array slot..
function updateSessionSlot($id,$data,$qty)
{
  $_SESSION['pic_id'][$id]    = $data[0];
  $_SESSION['pic_size'][$id]  = $data[1];
  $_SESSION['pic_cost'][$id]  = number_format($qty*$data[6],2);
  $_SESSION['pic_item'][$id]  = $data[3];
  $_SESSION['pic_qty'][$id]   = $qty;
  $_SESSION['pic_code'][$id]  = $data[5];
  $_SESSION['pic_price'][$id] = $data[6];
}

// Log cart data in database...
function logCartData($invoice,$cart)
{
  if (isset($_SESSION['cart_count']) && $_SESSION['cart_count']>0) {
    // Create ipn entry. This will be updated when a response comes back from Paypal..
    mysql_query("INSERT INTO ".$this->prefix."ipndata (
                 pay_date,
                 cartID,
                 invoice,
                 pictureShipping,
                 activeCart
                 ) VALUES (
                 '".date("Y-m-d")."',
                 '{$cart}',
                 '{$invoice}',
                 '".$this->setShippingCharge()."',
                 '0'
                 )") or die(mysql_error());
               
    // Now create a purchase entry for each picture purchased...
    for ($i=0; $i<count($_SESSION['pic_cost']); $i++) {
      if ($_SESSION['pic_id'][$i]>0) {
        $_SESSION['pic_item'][$i] = $this->safe_import($_SESSION['pic_item'][$i]);
        $PosCarattere = strrpos ($_SESSION['pic_id'][$i] , "-");
        if ($PosCarattere === false) {
            $PosCarattere = strlen($_SESSION['pic_id'][$i]);
        }
        $PicIdTmp = substr($_SESSION['pic_id'][$i],0,$PosCarattere);
        mysql_query("INSERT INTO ".$this->prefix."purchases (
                     pictureID,
                     pictureSize,
                     pictureCost,
                     pictureItem,
                     pictureQty,
                     cartID
                     ) VALUES (
                     '{$PicIdTmp}',
                     '{$_SESSION['pic_size'][$i]}',
                     '{$_SESSION['pic_cost'][$i]}',
                     '{$_SESSION['pic_item'][$i]}',
                     '{$_SESSION['pic_qty'][$i]}',
                     '{$cart}'
                     )") or die(mysql_error());
      }            
    }
  }
}

// Updates ipn table on successful processing..
function updateCartPurchaseTable($DATA,$cart)
{
  // Use callback function to prepare data for importing..
  $DATA = array_map(array($this,'safe_import'),$DATA);
  
  // Build address..
  if (isset($DATA['address_street']) && isset($DATA['address_city']) && isset($DATA['address_state'])
            && isset($DATA['address_zip']) && isset($DATA['address_country'])) { 
    $address = $DATA['address_street'].$this->define_newline().$DATA['address_city'].$this->define_newline().
               $DATA['address_state'].$this->define_newline().$DATA['address_zip'].$this->define_newline().
               $DATA['address_country'];
  } else {
    $address = '';
  }
  
  mysql_query("UPDATE ".$this->prefix."ipndata SET
               first_name      = '{$DATA['first_name']}',
               last_name       = '{$DATA['last_name']}',
               pay_date        = '".date("Y-m-d")."',
               address         = '{$address}',
               email           = '{$DATA['payer_email']}',
               memo            = '{$DATA['memo']}',
               payment_status  = '{$DATA['payment_status']}',
               pending_reason  = '{$DATA['pending_reason']}',
               gross           = '{$DATA['mc_gross']}',
               fee             = '{$DATA['mc_fee']}',
               txn_id          = '{$DATA['txn_id']}',
               activeCart      = '1'
               WHERE cartID    = '{$cart}'
               LIMIT 1
               ") or die(mysql_error());
}

// Get next order id..
function getNextOrderID()
{
  $query = mysql_query("SELECT * FROM ".$this->prefix."ipndata 
                        ORDER BY id DESC 
                        LIMIT 1
                        ") or die(mysql_error());
  $row = mysql_fetch_object($query);
  
  return (mysql_num_rows($query)>0 ? ($row->id+1) : '1');
}

// Get picture data..
function getPictureData($id)
{
  $q_pic = mysql_query("SELECT * FROM ".$this->prefix."images 
                        WHERE id = '{$id}' 
                        LIMIT 1
                        ") or die(mysql_error());
  
  return mysql_fetch_object($q_pic);
}

// Load purchases into string for e-mails...
function loadPurchasesIntoString($cart,$size,$qty,$cost)
{
  $string = '';
  
  $q_cart = mysql_query("SELECT * FROM ".$this->prefix."purchases 
                         WHERE cartID = '{$cart}' 
                         ORDER BY id
                         ") or die(mysql_error());
  
  while ($PICS = mysql_fetch_object($q_cart)) {
    // Get picture info..
    $IMG = $this->getPictureData($PICS->pictureID);
    // Create string..
    $string .= $this->strip_slashes($IMG->name).$this->define_newline();
    $string .= $size.': '.$PICS->pictureSize.$this->define_newline();
    $string .= $qty.': '.$PICS->pictureQty.$this->define_newline();
    $string .= $cost.': '.$PICS->pictureCost.$this->define_newline().$this->define_newline();
  }
  
  return trim($string);
}

}

?>
Return current item: Maian Gallery