You are here

function uc_coupon_find in Ubercart Discount Coupons 5

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

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

1 call to uc_coupon_find()
uc_coupon_validate in ./uc_coupon.module
Validate a coupon and calculate the coupon amount against the current cart contents.

File

./uc_coupon.module, line 805
Provides discount coupons for Ubercart.

Code

function uc_coupon_find($code) {

  // Look for matching single coupon first.
  $coupon = db_fetch_object(db_query("SELECT * FROM {uc_coupons} WHERE code = '%s' AND status = 1 AND bulk = 0 AND valid_from < %d AND valid_until > %d", $code, time(), time()));
  if ($coupon !== FALSE) {
    if ($coupon->data) {
      $coupon->data = unserialize($coupon->data);
    }
    return $coupon;
  }

  // Look through bulk coupons.
  $result = db_query("SELECT * FROM {uc_coupons} WHERE status = 1 AND bulk = 1 AND valid_from < %d AND valid_until > %d", time(), time());
  while ($coupon = db_fetch_object($result)) {

    // 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)) {
      return $coupon;
    }
  }
  return FALSE;
}