You are here

function uc_coupon_find in Ubercart Discount Coupons 7.2

Same name and namespace in other branches
  1. 5 uc_coupon.module \uc_coupon_find()
  2. 6 uc_coupon.module \uc_coupon_find()
  3. 7.3 uc_coupon.module \uc_coupon_find()

Load a coupon (single or bulk) from the supplied code.

Parameters

$code: The coupon code to search for.

$reset: If TRUE the cache of codes for this request will be purged. Any function which modifies a coupon should purge the cache.

6 calls to uc_coupon_find()
hook_uc_coupon_validate in ./uc_coupon.api.php
Add extra validation to a coupon.
uc_coupon_calculate_discounts in ./uc_coupon.module
Find items that a coupon will apply to and calculate the discounts.
uc_coupon_form_submit in ./uc_coupon.module
Submit handler for the uc_coupon form.
uc_coupon_uc_coupon_validate in ./uc_coupon.module
Implements hook_uc_coupon_validate().
uc_coupon_uc_update_cart_item in ./uc_coupon.module
Implements hook_uc_update_cart_item(). Remove a coupon from the order when the "Remove" button is clicked.

... See full list

File

./uc_coupon.module, line 364

Code

function uc_coupon_find($code, $reset = FALSE) {

  // This is expensive and can be called many times during coupon processing, so we
  // use a simple static cache.
  static $cached = array();
  if ($reset) {
    $cached = array();
  }
  if (!$code) {
    return FALSE;
  }
  elseif (array_key_exists($code, $cached)) {
    return $cached[$code];
  }

  // Look for matching single coupon first.
  $coupon = db_query("SELECT cid FROM {uc_coupons}\n    WHERE code = :code AND status = 1 AND bulk = 0 AND valid_from < :now AND (valid_until = 0 OR valid_until > :now)", array(
    ':code' => $code,
    ':now' => REQUEST_TIME,
  ))
    ->fetchObject();
  if ($coupon) {
    $cached[$code] = uc_coupon_load($coupon->cid);
    return $cached[$code];
  }

  // Look through bulk coupons.
  $result = db_query("SELECT cid, code, data, bulk_seed FROM {uc_coupons}\n    WHERE status = 1 AND bulk = 1 AND valid_from < :now AND (valid_until = 0 OR valid_until > :now)", array(
    ':now' => REQUEST_TIME,
  ));
  foreach ($result as $coupon) {

    // Check coupon prefix.
    $prefix_length = strlen($coupon->code);
    if (substr($code, 0, $prefix_length) != $coupon->code) {
      continue;
    }
    if ($coupon->data) {
      $coupon->data = unserialize($coupon->data);
    }

    // Check coupon sequence ID.
    $id = substr($code, $prefix_length, strlen(dechex($coupon->data['bulk_number'])));
    if (!preg_match("/^[0-9A-F]+\$/", $id)) {
      continue;
    }
    $id = hexdec($id);
    if ($id < 0 || $id > $coupon->data['bulk_number']) {
      continue;
    }

    // Check complete coupon code.
    if ($code == uc_coupon_get_bulk_code($coupon, $id)) {
      $cached[$code] = uc_coupon_load($coupon->cid);
      return $cached[$code];
    }
  }
  $cached[$code] = FALSE;
  return $cached[$code];
}