'Gift Certificate Settings',
'page callback' => 'drupal_get_form',
'page arguments' => array('uc_gift_certificate_settings'),
'file' => 'uc_gift_certificate.admin.inc',
'description' => 'Administer Gift Certificates',
'access arguments' => array('administer store'),
);
$items['redeem'] = array(
'title' => 'Gift Certificate Code',
'page callback' => 'drupal_get_form',
'page arguments' => array('uc_gift_certificate_cert_code_form'),
'description' => 'Enter Your Gift Certificate Code',
'access arguments' => array('access content'),
'type' => MENU_SUGGESTED_ITEM,
);
$items['my_gift_certificates'] = array(
'title' => 'Send Gift Certificates',
'description' => 'Issue Gift Certificates',
'page callback' => 'uc_gift_certificate_issue',
'access arguments' => array('access content'),
'type' => MENU_CALLBACK,
);
$items['admin/store/gift_certificates'] = array(
'title' => 'Gift Certificates',
'description' => 'Manage Gift Certificates',
'page callback' => 'uc_gift_certificate_manage',
'file' => 'uc_gift_certificate.admin.inc',
'page arguments' => array('manage'),
'access arguments' => array('administer gift certificates'),
'type' => MENU_NORMAL_ITEM,
);
$items['admin/store/gift_certificates/list'] = array(
'title' => 'Gift Certificates',
'description' => 'Manage Gift Certificates',
'page callback' => 'uc_gift_certificate_manage',
'page arguments' => array('manage'),
'file' => 'uc_gift_certificate.admin.inc',
'access arguments' => array('administer gift certificates'),
'type' => MENU_DEFAULT_LOCAL_TASK,
);
$items['admin/store/gift_certificates/add'] = array(
'title' => 'Add',
'description' => 'Add A Gift Certificate',
'page callback' => 'drupal_get_form',
'page arguments' => array('uc_gift_certificate_add_form', 'add'),
'file' => 'uc_gift_certificate.admin.inc',
'access arguments' => array('administer gift certificates'),
'type' => MENU_LOCAL_TASK,
'weight' => 10,
);
$items['gift_certificates/%/issue'] = array(
'title' => 'Issue Gift Certificate',
'description' => 'Issue the gift certificate to a user',
'page callback' => 'drupal_get_form',
'page arguments' => array('uc_gift_certificate_issue_form', 1),
'file' => 'uc_gift_certificate.user.inc',
'access arguments' => array('access content'),
'type' => MENU_CALLBACK,
);
$items['admin/store/gift_certificates/%/edit'] = array(
'title' => 'Edit Certificate',
'description' => 'Edit a currently existing Gift Certificate',
'page callback' => 'drupal_get_form',
'page arguments' => array('uc_gift_certificate_add_form', 3),
'file' => 'uc_gift_certificate.admin.inc',
'access arguments' => array('administer gift certificates'),
'type' => MENU_CALLBACK,
);
$items['admin/store/gift_certificates/%/delete'] = array(
'title' => 'Delete Gift Certificate',
'description' => 'Delete Gift Certificate',
'page callback' => 'drupal_get_form',
'page arguments' => array('uc_gift_certificate_delete_confirm', 3),
'file' => 'uc_gift_certificate.admin.inc',
'access arguments' => array('administer gift certificates'),
'type' => MENU_CALLBACK,
);
$items['cart/checkout/get_certificate_discount/%'] = array(
'title' => 'Certificate details',
'description' => 'Certificate details.',
'page callback' => 'uc_gift_certificate_apply_discount',
'page arguments' => array(3),
'access arguments' => array('access content'),
'type' => MENU_CALLBACK,
);
$items['cart/checkout/certificate/%'] = array(
'title' => 'Certificate details',
'description' => 'Certificate details.',
'page callback' => 'uc_gift_certificate_apply',
'page arguments' => array(3),
'access arguments' => array('access content'),
'type' => MENU_CALLBACK,
);
return $items;
}
/**
* Implementation of hook_token_values(). (token.module)
*/
function uc_gift_certificate_token_values($type, $object = NULL) {
$values = array();
switch ($type) {
case 'gift_certificate':
$gc = $object;
$values['gift-cert-id'] = $gc->certificate_id;
$values['gift-cert-name'] = $gc->name;
$values['gift-cert-value'] = uc_currency_format($gc->value);
$values['gift-cert-user-id'] = $gc->user_id;
$values['gift-cert-purchaser-id'] = $gc->purchaser_id;
$values['gift-cert-order-id'] = $gc->order_id;
$values['gift-cert-product-id'] = $gc->order_product_id;
$values['gift-cert-code'] = $gc->cert_code;
if (!empty($gc->message)) {
$values['gift-cert-message'] = $gc->message;
}
break;
}
return $values;
}
/**
* Implementation of hook_token_list(). (token.module)
*/
function uc_gift_certificate_token_list($type = 'all') {
$tokens = array();
if ($type == 'gift_certificate' || $type == 'all') {
$tokens['gift_certificate']['gift-cert-id'] = t('The certificate ID.');
$tokens['gift_certificate']['gift-cert-name'] = t('The certificate name.');
$tokens['gift_certificate']['gift-cert-message'] = t('The message to the recipient.');
$tokens['gift_certificate']['gift-cert-value'] = t('The certificate value.');
$tokens['gift_certificate']['gift-cert-user-id'] = t('The ID of the certificate recipient.');
$tokens['gift_certificate']['gift-cert-purchaser-id'] = t('The ID of ther certificate purchaser.');
$tokens['gift_certificate']['gift-cert-order-id'] = t('The order assoicated with the certificate.');
$tokens['gift_certificate']['gift-cert-product-id'] = t('The product assoicated with the certificate.');
$tokens['gift_certificate']['gift-cert-code'] = t('The certificate code.');
}
return $tokens;
}
/**
* Implementation of hook_theme().
*/
function uc_gift_certificate_theme() {
return array(
'uc_gift_certificate' => array(
'template' => 'uc_gift_certificate',
'arguments' => array('gift_certificate' => NULL, 'account' => NULL),
),
);
}
/**
* Preprocess a formatted gift certificate email with a git cert's data.
* CHANGED BY JOAO
*/
function template_preprocess_uc_gift_certificate(&$variables) {
//ver qual o template a utilizar
//Get the attribute Ocasion
//First we get the order to see the gift in the order and the respective attributes
$order = uc_order_load($variables['gift_certificate']->order_id);
foreach ($order->products as $product) {
if ($product->data) {
$data = $product->data;
// Check if the product is a gift certificate
$Recipient_pt = locale("Recipient's Email Address","pt-pt");
if ($data && $data['attributes'] && (isset($data['attributes']["Recipient's Email Address"][0]) || isset($data['attributes'][$Recipient_pt][0]))) {
//Ler Ocasion
//Estou a traduzir so a string "Ocasião" (não os valores de cada ocasião)
$Ocasion_pt = locale("Ocasion","pt-pt");
if ($data['attributes']["Ocasion"] != null) {
//Ingles
$ocasiao_att = $data['attributes']["Ocasion"];
}else {
//Portugues
$ocasiao_att = $data['attributes'][$Ocasion_pt];
}
//Ler Estilo (Bijou Classic, Modern, Hippie)
$Style_pt = locale("Style","pt-pt");
if ($data['attributes']["Subject"] != null) {
//Ingles
$estilo_att = $data['attributes']["Style"];
}else {
//Portugues
$estilo_att = $data['attributes'][$Style_pt];
}
//Ler "From" - ("De")
$From_pt = locale("From","pt-pt");
if ($data['attributes']["From"] != null) {
//Ingles
$from_att = $data['attributes']["From"];
}else {
//Portugues
$from_att = $data['attributes'][$From_pt];
}
//Ler Subject/Assunto
$Subj_pt = locale("Subject","pt-pt");
if ($data['attributes']["Subject"] != null) {
//Ingles
$subject_att = $data['attributes']["Subject"];
}else {
//Portugues
$subject_att = $data['attributes'][$Subj_pt];
}
$email_subject = $subject_att[0];
$style = $estilo_att[0];
$ocasiao = strtolower($ocasiao_att[0]);
$from_user = $from_att[0];
switch ($style) {
case 'Bijou Classic':
$template_file = 'uc_gift-bijou_'.$ocasiao;
break;
case 'Modern Elegant':
$template_file = 'uc_gift-modern_'.$ocasiao;
break;
case 'Hippie Chic':
$template_file = 'uc_gift-hippie_'.$ocasiao;
break;
default:
$template_file = 'uc_gift-gift_certificate';
break;
}
}
}
}
$variables['template_file'] = $template_file;
//From name
$variables['from_name'] = $from_user;
$variables['order'] = uc_order_load($variables['gift_certificate']->order_id);
if (!empty($variables['order']) && !empty($variables['gift_certificate']->order_product_id)) {
$variables['order_product'] = db_fetch_object(db_query('SELECT * FROM {uc_order_products} WHERE order_product_id = %d', $variables['gift_certificate']->order_product_id));
}
$replacements = array(
'global' => NULL,
'gift_certificate' => $variables['gift_certificate'],
'user' => $variables['account'],
);
$full = new stdClass();
$full->tokens = $full->values = array();
foreach ($replacements as $type => $object) {
$temp = token_get_values($type, $object);
$full->tokens = array_merge($full->tokens, $temp->tokens);
$full->values = array_merge($full->values, $temp->values);
}
foreach ($full->tokens as $key => $token) {
$value = $full->values[$key];
$variables[str_replace('-', '_', $token)] = $value;
}
if (!empty($GLOBALS['uc_gc_new_user_pass'])) {
$variables['is_new_user'] = TRUE;
$variables['new_password'] = $GLOBALS['uc_gc_new_user_pass'];
}
}
/**
* Implementation of hook_mail()
*/
function uc_gift_certificate_mail($key, &$message, $params) {
switch ($key) {
case 'gift-certificate':
$replacements = array(
'global' => NULL,
'gift_certificate' => $params['gift_certificate'],
'user' => $params['account'],
);
$message['headers']['Content-Type'] = 'text/html; charset=UTF-8; format=flowed';
$subject_var = $params['is_new_user'] ? 'uc_gc_email_new_user_subject' : 'uc_gc_email_subject';
$message['subject'] = variable_get($subject_var, uc_gift_certificate_get_setting_defaults($subject_var));
$message['subject'] = token_replace_multiple($message['subject'], $replacements);
$message['from'] = uc_store_email_from();
$message['body'][] = theme('uc_gift_certificate', $params['gift_certificate'], $params['account']);
// die($message['body'][0]);
break;
}
}
/**
* Email the user a notification about their gift certificate
*/
function uc_gift_certificate_mail_cert($mail, $certificate_id, $msg_to_recipient = NULL) {
if (!valid_email_address($mail)) {
drupal_set_message(t('The e-mail address %mail is not valid.', array('%mail' => $mail)), 'error');
return FALSE;
}
$account = user_load(array('mail' => $mail));
if (!$account) {
drupal_set_message(t('The e-mail address %mail does not have a user account.', array('%mail' => $mail)), 'error');
return FALSE;
}
$gc = uc_gift_certificate_load($certificate_id);
$gc->message = $msg_to_recipient;
$params = array(
'gift_certificate' => $gc,
'account' => $account,
);
drupal_mail('uc_gift_certificate', 'gift-certificate', $mail, user_preferred_language($account), $params, uc_store_email_from());
}
/**
* Issues a certificate to a user. If the user doesn't exist we create them.
*/
function uc_gift_certificate_issue_cert($mail, $certificate_id) {
$account = user_load(array('mail' => $mail));
if (!$account) {
$fields = array(
'name' => uc_store_email_to_username($mail),
'mail' => $mail,
'init' => $mail,
'pass' => user_password(variable_get('uc_pwd_length', 6)),
'roles' => array(),
'status' => 1,
);
$account = user_save('', $fields);
// Used by the gift cert email. We need OOP :(
$GLOBALS['uc_gc_new_user_pass'] = $fields['pass'];
}
return db_query('UPDATE {uc_gift_certificates} SET user_id = %d WHERE certificate_id = %d', $account->uid, $certificate_id);
}
/**
* Callback function for the discount line item.
*/
function uc_gift_certificate_line_item_discount($op, $order) {
switch ($op) {
case 'load':
$discounts = uc_gift_certificate_calculate_discounts($order);
$lines = array();
foreach ($discounts as $discount) {
$lines[] = array(
'id' => 'discount',
'title' => $discount['title'],
'amount' => $discount['amount'],
'weight' => variable_get('uc_li_discount_weight', 5),
);
}
return $lines;
}
}
/**
* Calculates the discount line items from the configured conditional actions.
*
* @param $order
* The order object.
* @return
* The array of line items, each containing an id, a title, and an amount.
*/
function uc_gift_certificate_calculate_discounts($order) {
global $user;
if (isset($order->uid)) {
$account = user_load($order->uid);
}
else {
$account = $user;
}
if (is_array($order->line_items)) {
foreach ($order->line_items as $i => $line) {
if (drupal_substr($line['type'], 0, 9) == 'discount_') {
unset($order->line_items[$i]);
}
}
}
$arguments = array(
'order' => array(
'#entity' => 'uc_order',
'#title' => t('Order'),
'#data' => $order,
),
'account' => array(
'#entity' => 'user',
'#title' => t('User'),
'#data' => $account,
),
);
$id = 0;
$order->discounts = array();
// Pull the "calculate_discounts" trigger in such a way to get the results.
$predicates = ca_load_trigger_predicates('calculate_order_discounts');
foreach ($predicates as $predicate) {
if (ca_evaluate_conditions($predicate, $arguments)) {
$discounts = ca_perform_actions($predicate, $arguments);
foreach ((array) $discounts as $i => $discount) {
if ($predicate['#actions'][$i]['#name'] == 'uc_discount_action_get_order_discount' && $discount) {
// Allow successive discounts to inspect this discount by putting
// it in the order object.
$order->discounts[$id] = array(
'id' => $id,
'title' => check_plain($predicate['#actions'][$i]['#title']),
'amount' => $discount,
'weight' => $predicate['#actions'][$i]['#settings']['line_item_weight'],
);
$id++;
}
}
}
}
return $order->discounts;
}
/**
* Implementation of hook_order()
*/
function uc_gift_certificate_order($op, &$arg1, $arg2) {
switch ($op) {
case 'update':
$gc_status_array = variable_get('uc_gift_certificate_order_status_issue', uc_gift_certificate_get_setting_defaults('uc_gift_certificate_order_status_issue'));
if ($gc_status_array[$arg2]) {
uc_gift_certificate_create_new_certs($arg1->order_id);
}
$gc_status_array = variable_get('uc_gift_certificate_order_status_deduct', uc_gift_certificate_get_setting_defaults('uc_gift_certificate_order_status_deduct'));
if ($gc_status_array[$arg2]) {
uc_gift_certificate_update_cert_vals($arg1->order_id);
}
// TODO: If the order is canceled we need to refund their points because we are too lazy to do it by hand...
if ($arg2 == 'canceled') {
// Was this order purchased (or discounted) with certificates?
$certificate_amount = abs(db_result(db_query("SELECT SUM(amount) FROM {uc_order_line_items} WHERE `type` = 'gift_certificate' AND order_id = %d", $arg1->order_id)));
// If so, refund them to the user.
if ($certificate_amount) {
db_query("UPDATE {uc_gift_certificates} SET value = value + %f WHERE order_id = %d AND user_id = %d LIMIT 1", $certificate_amount, $arg1->order_id, $arg1->uid);
uc_order_comment_save($arg1->order_id, 0, t('Refunded gift certificates worth !value.', array('!value' => uc_currency_format($certificate_amount))));
}
$email_attrib = uc_attribute_load(variable_get('uc_gift_certificate_email_aid', ''));
// If this order contains (was used to PURCHASE) certificates, then we need to void them.
foreach ($arg1->products as $product) {
if (!empty($product->data['attributes'])) {
foreach ($product->data['attributes'] as $label => $vals) {
$attrib = _uc_gc_find_attrib_by_label($label, $product->nid);
if ($attrib->aid == $email_attrib->aid) {
db_query("DELETE FROM {uc_gift_certificates} WHERE order_id = %d AND order_product_id = %d", $product->order_id, $product->order_product_id);
uc_order_comment_save($arg1->order_id, 0, t('Voided gift certificates worth !value.', array('!value' => uc_currency_format($product->qty * $product->price))));
break;
}
}
}
}
}
break;
case 'delete':
db_query("DELETE FROM {uc_gift_certificates} WHERE order_id = %d", $arg1->order_id);
break;
case 'save':
$certificates = uc_gift_certificate_total($arg1->uid);
// Automatically apply gift certificates upon checkout
if ($certificates && arg(0) != 'admin') {
// Get current cart total including all line_items.
$order_total = $arg1->order_total;
$line_items = db_result(db_query("SELECT SUM(amount) FROM {uc_order_line_items} WHERE order_id = %d AND type <> 'gift_certificate'", $arg1->order_id));
$order_total += $line_items;
if ($certificates >= $order_total) {
$line_item_amount = -abs($order_total);
} else {
$line_item_amount = -$certificates;
}
$result = db_query("SELECT line_item_id FROM {uc_order_line_items} WHERE order_id = %d AND type = 'gift_certificate'", $arg1->order_id);
if ($lid = db_result($result)) {
uc_order_update_line_item($lid, t('Gift Certificates'), $line_item_amount);
} else {
uc_order_line_item_add($arg1->order_id, 'gift_certificate', t('Gift Certificates'), $line_item_amount);
}
}
break;
}
}
/**
* Implementation of hook_line_item()
*/
function uc_gift_certificate_line_item() {
$items[] = array(
'id' => 'gift_certificate',
'title' => t('Gift Certificates'),
'weight' => 10,
'stored' => TRUE,
'default' => FALSE,
'calculated' => TRUE,
'add_list' => TRUE,
);
return $items;
}
/**
* Create a new certificate; insert it into the database; notify a user (if it is an Electronic certificate)
*/
function uc_gift_certificate_create_new_certs($order_id) {
$order = uc_order_load($order_id);
$email_attrib = uc_attribute_load(variable_get('uc_gift_certificate_email_aid', ''));
$msg_attrib = uc_attribute_load(variable_get('uc_gift_certificate_message_aid', ''));
foreach ($order->products as $product) {
if ($product->data) {
$data = $product->data;
$is_gift_cert = FALSE;
// Check if the product is a gift certificate
if ($data && $data['attributes']) {
// Attribute is stored using label
foreach ($data['attributes'] as $label => $vals) {
$attrib = _uc_gc_find_attrib_by_label($label, $product->nid);
if ($attrib->aid == $email_attrib->aid) {
$is_gift_cert = TRUE;
$recipient_email = $vals[0];
}
elseif ($attrib->aid == $msg_attrib->aid) {
$msg_to_recipient = $vals[0];
}
}
}
if ($is_gift_cert) {
$data['attributes']['Certificate Code'][0] = '';
$title = t('@gc_title for order #@order_id', array('@gc_title' => $product->title, '@order_id' => $order_id));
// Generate a random code and insert the certificate. First delete other certificates for this order_id
$new_gc = new stdClass();
$new_gc->name = $title;
$new_gc->value = $product->qty * $product->price;
$new_gc->purchaser_id = $order->uid;
$new_gc->order_id = $order->order_id;
$new_gc->order_product_id = $product->order_product_id;
if (drupal_write_record('uc_gift_certificates', $new_gc)) {
$certificate_id = db_last_insert_id('uc_gift_certificates', 'certificate_id');
$cert_code = $certificate_id ."-". uc_gift_certificate_mKey();
db_query("UPDATE {uc_gift_certificates} SET cert_code = '%s' WHERE certificate_id = %d", $cert_code, $certificate_id);
uc_gift_certificate_issue_cert($recipient_email, $certificate_id);
uc_gift_certificate_mail_cert($recipient_email, $certificate_id, $msg_to_recipient);
// Add the newly created cert_code to the product's attributes (serialized in uc_order_products)
$data['attributes']['Certificate Code'][0] = $cert_code;
$data = serialize($data);
db_query("UPDATE {uc_order_products} SET data = '%s' WHERE order_id = %d AND order_product_id = %d", $data, $order_id, $product->order_product_id);
// Log these to Watchdog?...
uc_order_comment_save($order->order_id, 0, t('Added gift certificate !code worth !value.', array('!code' => $cert_code, '!value' => uc_currency_format($product->qty * $product->price))), 'admin');
}
}
}
}
}
/**
* Update gift certificate amounts
*/
function uc_gift_certificate_update_cert_vals($order_id) {
$num_rows = db_result(db_query("SELECT COUNT(*) FROM {uc_order_line_items} WHERE order_id = %d AND type ='gift_certificate'", $order_id));
if ($num_rows > 1) {
drupal_set_message("ERROR: there are $num_rows gift certificate line items");
}
else if ($num_rows == 0) {
// No certificates, so do nothing.
}
else {
$res = db_fetch_object(db_query("SELECT * FROM {uc_order_line_items} WHERE order_id = %d AND type ='gift_certificate'", $order_id));
$line_item_val = - $res->amount;
$query = db_query("SELECT * FROM {uc_orders} WHERE order_id = %d", $order_id);
$res = db_fetch_object($query);
$user_id = $res->uid;
$order_total = $res->order_total;
$deducted = 0;
$query_gift_certs = db_query("SELECT * FROM {uc_gift_certificates} WHERE user_id = %d AND value > 0", $user_id);
while (($cert = db_fetch_object($query_gift_certs)) && $deducted < $line_item_val) {
$cert_val = $cert->value;
$left_to_deduct = $line_item_val - $deducted;
if ($left_to_deduct <= $cert_val) {
$deduct_from_cert = $left_to_deduct;
}
else {
$deduct_from_cert = $cert_val;
}
$deducted += $deduct_from_cert;
$new_cert_val = $cert_val - $deduct_from_cert;
if (db_query("UPDATE {uc_gift_certificates} SET value = %f, order_id = %d WHERE certificate_id = %d", $new_cert_val, $order_id, $cert->certificate_id)) {
$user = user_load(array('uid' => $user_id));
// drupal_set_message('updated cert '.$cert->certificate_id .' to '.$new_cert_val);
}
else {
drupal_set_message("Error updating gift certificates");
}
}
}
return false;
}
/**
* Implementation of hook_payment_method().
*/
function uc_gift_certificate_payment_method() {
global $user;
$total = uc_gift_certificate_total($user->uid);
// Not enough certs available to user, so do not show the pane
if (!$total && arg(1) == 'checkout') {
return;
}
$methods[] = array(
'id' => 'zero_total',
'name' => t('Gift Certificates'),
'title' => t('Use my Gift Certificate to pay for the entire order. (You must choose another payment method if your gift certificates do not cover the ENTIRE cost.)'),
'desc' => t('Allow customers with $0 order totals to checkout without paying.'),
'callback' => 'uc_payment_method_zero_total',
'checkout' => TRUE,
'no_gateway' => TRUE,
'weight' => 10,
);
return $methods;
}
/**
* Handle the "Zero Total" payment method.
*/
function uc_payment_method_zero_total($op, &$arg1, $silent = FALSE) {
global $user;
switch ($op) {
case 'cart-process':
if ($arg1->payment_method == 'zero_total') {
// If they entered a certificate code in the checkout pane, make sure it belongs to them.
if ($arg1->data['certificate_code']) {
uc_gift_certificate_validate($arg1->data['certificate_code']);
}
// Get the total based on the current order_total (which will not include tax, shipping, etc.)
// TODO: Configure whether or not to include shipping, taxes, etc
$total = $arg1->order_total;
$line_items = db_result(db_query("SELECT SUM(amount) FROM {uc_order_line_items} WHERE order_id = %d AND type <> 'gift_certificate'", $arg1->order_id));
$total += $line_items;
// Get all of the certificates for the current order's user
$certificates = uc_gift_certificate_total($arg1->uid);
// If their total certificates cover it, deduct enough certificates to cover the total.
if ($certificates >= $total) {
$certificates = $total;
uc_add_js('$(document).ready(function() {
if (window.set_line_item) {
set_line_item("gift_certificate", "'. t('Gift Certificates') .'", '. -$certificates .', 6);
}
});', 'inline');
// Find any current line items in the database and add or update as necessary
$result = db_query("SELECT line_item_id FROM {uc_order_line_items} WHERE order_id = %d AND type = 'gift_certificate'", $arg1->order_id);
if ($lid = db_result($result)) {
uc_order_update_line_item($lid, t('Gift Certificates'), -$certificates);
}
else {
uc_order_line_item_add($arg1->order_id, 'gift_certificate', t('Gift Certificates'), -$certificates);
}
}
}
break;
case 'order-submit':
if ($arg1->order_total > .01 && $arg1->payment_method == 'zero_total') {
$result[] = array(
'pass' => FALSE,
'message' => t("Your final order total is not fully covered by your gift certificate amount. Please go back and select a different method of payment.",
array('!total' => uc_currency_format($arg1->order_total))));
$_SESSION['expanded_panes'][] = 'payment';
return $result;
}
// Kick them out of Reviewing the order if their order total isn't covered completely by Certificates
case 'cart-review':
if ($arg1->order_total > .01 && $arg1->payment_method == 'zero_total') {
drupal_set_message(t("Your final order total is not fully covered by your gift certificate amount. Please select a different method of payment.",
array('!total' => uc_currency_format($arg1->order_total))), 'error');
drupal_goto('cart/checkout');
}
break;
}
}
/**
* Generate a random alphanum code
*/
function uc_gift_certificate_mKey($len = 12, $type = 'ALNUM') {
// Register the lower case alphabet array
$alpha = array('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'j', 'k', 'l', 'm',
'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z');
// Register the upper case alphabet array
$ALPHA = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J', 'K', 'L', 'M',
'N', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z');
// Register the numeric array
$num = array('1', '2', '3', '4', '5', '6', '7', '8', '9');
// Initialize the keyVals array for use in the for loop
$keyVals = array();
// Initialize the key array to register each char
$key = array();
// Loop through the choices and register
// The choice to keyVals array
switch ($type) {
case 'lower' :
$keyVals = $alpha;
break;
case 'upper' :
$keyVals = $ALPHA;
break;
case 'numeric' :
$keyVals = $num;
break;
case 'ALPHA' :
$keyVals = array_merge($alpha, $ALPHA);
break;
case 'ALNUM' :
$keyVals = array_merge($alpha, $ALPHA, $num);
break;
}
// Loop as many times as specified
// Register each value to the key array
for($i = 0; $i <= $len-1; $i++) {
$r = rand(0,count($keyVals)-1);
$key[$i] = $keyVals[$r];
}
// Glue the key array into a string and return it
return join("", $key);
}
/**
* Implementation of hook_form_alter()
*/
function uc_gift_certificate_form_alter(&$form, &$form_state, $form_id) {
if (strpos($form_id,'uc_product_add_to_cart_form') !== FALSE) {
if (empty($form["attributes"])) {
return;
}
foreach (element_children($form['attributes']) as $attrib_id) {
if ($attrib_id == variable_get('uc_gift_certificate_email_aid', '')) {
$form['attributes'][$attrib_id]['#required'] = TRUE;
$form['#validate'][] = 'uc_gift_certificate_validate_addtocart_form';
}
if ($attrib_id == variable_get('uc_gift_certificate_message_aid', '')) {
$form['attributes'][$attrib_id]['#type'] = 'textarea';
}
}
}
}
/**
* Implementation of hook_form_validate()
*/
function uc_gift_certificate_validate_addtocart_form($form, &$form_state) {
$aid = variable_get('uc_gift_certificate_email_aid', '');
$mail = $form_state['values']['attributes'][$aid];
if (!empty($mail) && !valid_email_address($mail)) {
form_set_error("attributes[$aid]", t('@label is not a valid email address.', array('@label' => $form['attributes'][$aid]['#title'])));
}
}
/**
* Implementation of hook_add_to_cart()
*
* Validate that when a gift cert is added the email address is valid
*/
function uc_gift_certificate_add_to_cart($nid, $qty, $data) {
$node = node_load($nid);
if (!empty($node->attributes)) {
foreach ($node->attributes as $key => $attrib) {
if ($attrib->aid == variable_get('uc_gift_certificate_email_aid', '') && !valid_email_address($data['attributes'][$key])) {
$result[] = array(
'success' => FALSE,
'message' => t('@label is not a valid email address.', array('@label' => $attrib->label)),
);
return $result;
}
}
}
}
/**
* Implementation of hook_form()
*/
function uc_gift_certificate_cert_code_form() {
$form['certificate_code'] = array(
'#type' => 'textfield',
'#required' => true,
'#title' => t('Enter your gift certificate code'),
'#description' => t('If you have an old Gift Certificate from the previous shopping cart system, you can enter it here. The value remaining on your certificate will be transferred to your account, and immediately available for use towards your next purchase(s).
The gift certificate code will not need to be re-entered at checkout - simply checkout as normal and select the "Use My Gift Certificate" payment option.'),
);
$form['cancel'] = array(
'#type' => 'item',
'#value' => l(t('Cancel'), ''),
'#weight' => 20,
);
$form['op'] = array('#type' => 'submit',
'#value' => t('Submit'),
'#weight' => 21,
);
return $form;
}
/**
* Hook_submit()
*/
function uc_gift_certificate_cert_code_form_submit($form, &$form_state) {
global $user;
if ($form_state['values']['certificate_code'] != '') {
$num_rows = db_result(db_query("SELECT COUNT(*) FROM {uc_gift_certificates} WHERE cert_code = '%s'", $form_state['values']['certificate_code']));
if ($num_rows > 0) {
$cert = db_fetch_object(db_query("SELECT * FROM {uc_gift_certificates} WHERE cert_code = '%s'", $form_state['values']['certificate_code']));
if (db_query("UPDATE {uc_gift_certificates} SET user_id = %d WHERE certificate_id = %d", $user->uid, $cert->certificate_id)) {
$message = "";
}
else {
$message = "ERROR";
}
drupal_set_message(t("Added certificate %cert_code worth !value", array('%cert_code' => $form_state['values']['certificate_code'], '!value' => $cert->value)));
}
else {
drupal_set_message(t("There is no certificate with the code %cert_code", array('%cert_code' => $form_state['values']['certificate_code'])), 'error');
}
}
}
/**
* Implementation of hook_block()
*/
function uc_gift_certificate_block($op = 'list', $delta = 0, $edit = array()) {
switch ($op) {
case 'list':
$blocks[0]['info'] = t('Gift Certificate');
return $blocks;
case 'configure':
$form['uc_gift_certificate_block'] = array(
'#type' => 'textfield',
'#title' => t('Content for the gift certificate block (the variable !value is the gift certificate amount)'),
'#default_value' => variable_get('uc_gift_certificate_block', t('You have !value worth of gift certificates. They can be redeemed when you check out.')),
);
return $form;
case 'save':
variable_set('uc_gift_certificate_block', $edit['uc_gift_certificate_block']);
break;
case 'view':
global $user;
$total = uc_gift_certificate_total($user->uid);
if ($total) {
$block['subject'] = t('Gift Certificate');
$block['content'] = t(variable_get('uc_gift_certificate_block', t('You have !value worth of gift certificates. They can be redeemed when you check out.')), array('!value' => uc_currency_format($total)));
}
return $block;
}
}
/**
* Apply the Certificate at checkout - covers the entire order.
*/
function uc_gift_certificate_apply($code = NULL) {
$coupon = uc_gift_certificate_validate($code);
if (!$coupon->valid) {
$coupon->message = t('Sorry, the certificate '.$code.' is invalid or cannot be applied to this order.');
}
drupal_set_header("Content-Type: text/javascript; charset=utf-8");
print drupal_to_js($coupon);
exit();
}
/**
* Apply the Certificate at checkout as a DISCOUNT
*/
function uc_gift_certificate_apply_discount($user = NULL) {
$coupon = uc_gift_certificate_validate_user($user);
if (!$coupon->valid) {
$coupon->message = t('Sorry, no certificates can be applied to this order.');
}
drupal_set_header("Content-Type: text/javascript; charset=utf-8");
print drupal_to_js($coupon);
exit();
}
/**
* Validate a specific Gift Certificate code.
*/
function uc_gift_certificate_validate($code) {
global $user;
// Get the code passed in from the coupon code form
$today = time();
$coupon_result = new stdClass();
// Grab the Certificate based on its code. Make sure that it belongs to the current user, or is unclaimed.
$coupon_data = db_fetch_object(db_query("SELECT * FROM {uc_gift_certificates} WHERE cert_code = '%s' AND user_uid IN (0, %d", $code, $user->uid));
if ($coupon_data) {
$coupon_result->valid = TRUE;
foreach (uc_cart_get_contents() as $item) {
$cart_total += $item->price * $item->qty;
}
// If the user_id == 0, then this is a blank certificate at the moment. (Printed card instead of email certificate)
if ($coupon_data->user_id == 0) {
// This might not work for stores that are running Anonymous checkout. In that case, should we specify an email address?
update_certificate_user($user->uid, $code);
}
$coupon_result->valid = TRUE;
$coupon_result->cert_code = $coupon_data->cert_code;
$coupon_result->certificate_id = $coupon_data->certificate_id;
$coupon_result->title = t('Gift Certificate: @code', array('@code' => $coupon_data->cert_code));
$coupon_result->amount = $coupon_data->value;
// Find out if our certificate amount is equal to or more than the current total.
if ($coupon_result->amount >= $cart_total) {
$coupon_result->amount = $cart_total;
}
}
else {
// The coupon was not found, inactive, or is expired in the list of coupons
$coupon_result->valid = FALSE;
}
return $coupon_result;
}
function uc_gift_certificate_validate_cart($userid, $order_id) {
//drupal_set_message('Got user '.$userid.' and order '.$order_id);
// the following query grabs the sum of available Certificates for this specific user.
$coupon_data = db_fetch_object(db_query("SELECT *, SUM(value) AS value FROM {uc_gift_certificates} WHERE user_id = %d", $userid));
if ($coupon_data) {
$coupon_result->valid = TRUE;
$cart_total = db_query("SELECT SUM(amount) FROM {uc_order_line_items} WHERE order_id = %d AND type <> 'gift_certificate'", $order_id);
$coupon_result->valid = TRUE;
$coupon_result->total = $coupon_data->amount;
$coupon_result->amount = $coupon_data->amount;
// Find out if our certificate amount is equal to or more than the current total.
if ($coupon_result->amount >= $cart_total) {
$coupon_result->amount = $cart_total;
}
$coupon_result->title = t('Gift Certificates - Discount: @code', array('@code' => $coupon_result->amount));
}
else {
// The coupon was not found, inactive, or is expired in the list of coupons
$coupon_result->valid = FALSE;
}
return $coupon_result;
}
/**
* Load a gift certificate
*/
function uc_gift_certificate_load($id) {
$object = db_fetch_object(db_query("SELECT * FROM {uc_gift_certificates} WHERE certificate_id = %d", $id));
if ($object == '') {
drupal_set_message(t("The gift certificate !val does not exist."), array('!val' => $id));
//drupal_goto('');
}
return $object;
}
/**
* Find the total amount of gift certificates from a userid
*/
function uc_gift_certificate_total($uid) {
// Never return gift certificates for anonymous users, because even if it's
// in the database something went wrong
if (!$uid) {
return 0;
}
$cert_array = db_query("SELECT * FROM {uc_gift_certificates} WHERE user_id = %d", $uid);
$total = 0;
while ($cert = db_fetch_object($cert_array)) {
$total += $cert->value;
}
return $total;
}
/**
* Settings for gift certificate text field options
*/
function uc_gift_certificate_get_setting_defaults($setting) {
switch ($setting) {
case 'uc_gc_email_new_user_subject':
return 'You have received a gift certificate';
case 'uc_gc_email_subject':
return 'You have been sent a gift certificate';
case 'uc_gc_pane_msg':
return '
You have !tot worth of gift certificates. This amount will be automatically applied to your order total. PLEASE NOTE: If the value of your gift certificates, !tot, covers your order total, please select the USE MY GIFT CERTIFICATE payment option below. This avoids the need to enter credit card information
'; case 'uc_gift_certificate_order_status_issue': case 'uc_gift_certificate_order_status_deduct': return array ( 'payment_received' => 'payment_received', 'pending' => 0, 'processing' => 0, 'paypal_pending' => 0, 'completed' => 0, 'canceled' => 0, 'in_checkout' => 0, ); } } /** * Finds an attribute based on the label and nid */ function _uc_gc_find_attrib_by_label($label, $nid) { $result = db_query('SELECT ua.* FROM {uc_product_attributes} upa LEFT JOIN {uc_attributes} ua USING(aid) WHERE nid = %d AND (upa.label = "%s" OR ua.label = "%s" OR ua.name = "%s")', $nid, $label, $label, $label); return db_fetch_object($result); }