Exemple #1
0
         $value_data = $wpdb->get_results("SELECT * FROM `" . $wpdb->prefix . "variation_values` WHERE `id`='" . $value_id . "' LIMIT 1", ARRAY_A);
         $variation_list = " (" . $value_data[0]['name'] . ")";
     } else {
         $variation_list = '';
     }
 }
 if ($purch_data[0]['shipping_country'] != '') {
     $billing_country = $purch_data[0]['billing_country'];
     $shipping_country = $purch_data[0]['shipping_country'];
 } else {
     $country_sql = "SELECT * FROM `" . $wpdb->prefix . "submited_form_data` WHERE `log_id` = '" . $purchase['id'] . "' AND `form_id` = '" . get_option('country_form_field') . "' LIMIT 1";
     $country_data = $wpdb->get_results($country_sql, ARRAY_A);
     $billing_country = $country_data[0]['value'];
     $shipping_country = $country_data[0]['value'];
 }
 $shipping = nzshpcrt_determine_item_shipping($cart_row['prodid'], $cart_row['quantity'], $shipping_country);
 $total_shipping += $shipping;
 echo "<tr {$alternate}>";
 echo " <td>";
 echo $product_data[0]['name'];
 echo $variation_list;
 echo " </td>";
 echo " <td>";
 echo $cart_row['quantity'];
 echo " </td>";
 echo " <td>";
 $price = $cart_row['price'] * $cart_row['quantity'];
 echo nzshpcrt_currency_display($price, 1);
 echo " </td>";
 echo " <td>";
 $gst = $price - $price / (1 + $cart_row['gst'] / 100);
/**
 * Purchase log ajax code starts here
*/
function wpsc_purchlog_resend_email()
{
    global $wpdb;
    $siteurl = get_option('siteurl');
    $log_id = $_GET['email_buyer_id'];
    if (is_numeric($log_id)) {
        $selectsql = "SELECT * FROM `" . WPSC_TABLE_PURCHASE_LOGS . "` WHERE `id`= " . $log_id . " LIMIT 1";
        $purchase_log = $wpdb->get_row($selectsql, ARRAY_A);
        if ($purchase_log['gateway'] == "testmode" && $purchase_log['processed'] < 2) {
            $message = get_option("wpsc_email_receipt");
            $message_html = "<h2  style='font-size:16px;font-weight:bold;color:#000;border:0px;padding-top: 0px;' >" . __('Your Order', 'wpsc') . "</h2>";
        } else {
            $message = get_option("wpsc_email_receipt");
            $message_html = $message;
        }
        $order_url = $siteurl . "/wp-admin/admin.php?page=" . WPSC_DIR_NAME . "/display-log.php&amp;purchcaseid=" . $purchase_log['id'];
        $cartsql = "SELECT * FROM `" . WPSC_TABLE_CART_CONTENTS . "` WHERE `purchaseid`=" . $purchase_log['id'] . "";
        $cart = $wpdb->get_results($cartsql, ARRAY_A);
        if ($purchase_log['shipping_country'] != '') {
            $billing_country = $purchase_log['billing_country'];
            $shipping_country = $purchase_log['shipping_country'];
        } else {
            $country = $wpdb->get_results("SELECT * FROM `" . WPSC_TABLE_SUBMITED_FORM_DATA . "` WHERE `log_id`=" . $purchase_log['id'] . " AND `form_id` = '" . get_option('country_form_field') . "' LIMIT 1", ARRAY_A);
            $billing_country = $country[0]['value'];
            $shipping_country = $country[0]['value'];
        }
        $email_form_field = $wpdb->get_results("SELECT `id`,`type` FROM `" . WPSC_TABLE_CHECKOUT_FORMS . "` WHERE `type` IN ('email') AND `active` = '1' ORDER BY `order` ASC LIMIT 1", ARRAY_A);
        $email_address = $wpdb->get_results("SELECT * FROM `" . WPSC_TABLE_SUBMITED_FORM_DATA . "` WHERE `log_id`=" . $purchase_log['id'] . " AND `form_id` = '" . $email_form_field[0]['id'] . "' LIMIT 1", ARRAY_A);
        $email = $email_address[0]['value'];
        $previous_download_ids = array(0);
        if ($cart != null) {
            foreach ($cart as $row) {
                $link = "";
                $productsql = "SELECT * FROM `" . WPSC_TABLE_PRODUCT_LIST . "` WHERE `id`=" . $row['prodid'] . "";
                $product_data = $wpdb->get_results($productsql, ARRAY_A);
                if ($product_data[0]['file'] > 0) {
                    if ($purchase_log['email_sent'] != 1) {
                        $wpdb->query("UPDATE `" . WPSC_TABLE_DOWNLOAD_STATUS . "` SET `active`='1' WHERE `fileid`='" . $product_data[0]['file'] . "' AND `purchid` = '" . $purchase_log['id'] . "' LIMIT 1");
                    }
                    if ($purchase_log['processed'] >= 2) {
                        $download_data = $wpdb->get_results("SELECT *\r\n\t\t\t\t\t\tFROM `" . WPSC_TABLE_DOWNLOAD_STATUS . "` INNER JOIN `" . WPSC_TABLE_PRODUCT_FILES . "`\r\n\t\t\t\t\t\tON `" . WPSC_TABLE_DOWNLOAD_STATUS . "`.`fileid` = `" . WPSC_TABLE_PRODUCT_FILES . "`.`id`\r\n\t\t\t\t\t\tWHERE `" . WPSC_TABLE_DOWNLOAD_STATUS . "`.`active`='1'\r\n\t\t\t\t\t\tAND `" . WPSC_TABLE_DOWNLOAD_STATUS . "`.`purchid`='" . $purchase_log['id'] . "'\r\n\t\t\t\t\t\tAND (\r\n\t\t\t\t\t\t\t`" . WPSC_TABLE_DOWNLOAD_STATUS . "`.`cartid` = '" . $row['id'] . "'\r\n\t\t\t\t\t\t\tOR (\r\n\t\t\t\t\t\t\t\t`" . WPSC_TABLE_DOWNLOAD_STATUS . "`.`cartid` IS NULL\r\n\t\t\t\t\t\t\t\tAND `" . WPSC_TABLE_DOWNLOAD_STATUS . "`.`fileid` = '{$product_data['file']}'\r\n\t\t\t\t\t\t\t)\r\n\t\t\t\t\t\t)\r\n\t\t\t\t\t\t AND `" . WPSC_TABLE_DOWNLOAD_STATUS . "`.`id` NOT IN ('" . implode("','", $previous_download_ids) . "')", ARRAY_A);
                        $link = array();
                        //exit('IM HERE'.$errorcode.'<pre>'.print_r($download_data).'</pre>');
                        if (sizeof($download_data) != 0) {
                            foreach ($download_data as $single_download) {
                                if ($single_download['uniqueid'] == null) {
                                    // if the uniqueid is not equal to null, its "valid", regardless of what it is
                                    $link[] = array("url" => $siteurl . "?downloadid=" . $single_download['id'], "name" => $single_download["filename"]);
                                } else {
                                    $link[] = array("url" => $siteurl . "?downloadid=" . $single_download['uniqueid'], "name" => $single_download["filename"]);
                                }
                            }
                        }
                        $previous_download_ids[] = $download_data['id'];
                        $order_status = 4;
                    }
                }
                do_action('wpsc_confirm_checkout', $purchase_log['id']);
                $shipping = nzshpcrt_determine_item_shipping($row['prodid'], $row['quantity'], $shipping_country);
                if (isset($_SESSION['quote_shipping'])) {
                    $shipping = $_SESSION['quote_shipping'];
                }
                $total_shipping += $shipping;
                if ($product_data[0]['special'] == 1) {
                    $price_modifier = $product_data[0]['special_price'];
                } else {
                    $price_modifier = 0;
                }
                $total += $row['price'] * $row['quantity'];
                $message_price = nzshpcrt_currency_display($row['price'] * $row['quantity'], $product_data[0]['notax'], true);
                $shipping_price = nzshpcrt_currency_display($shipping, 1, true);
                $variation_sql = "SELECT * FROM `" . WPSC_TABLE_CART_ITEM_VARIATIONS . "` WHERE `cart_id`='" . $row['id'] . "'";
                $variation_data = $wpdb->get_results($variation_sql, ARRAY_A);
                $variation_count = count($variation_data);
                if ($variation_count > 1) {
                    $variation_list = " (";
                    if ($purchase['gateway'] != 'testmode') {
                        if ($gateway['internalname'] == $purch_data[0]['gateway']) {
                            $gateway_name = $gateway['name'];
                        }
                    } else {
                        $gateway_name = "Manual Payment";
                    }
                    $i = 0;
                    foreach ($variation_data as $variation) {
                        if ($i > 0) {
                            $variation_list .= ", ";
                        }
                        $value_id = $variation['value_id'];
                        $value_data = $wpdb->get_results("SELECT * FROM `" . WPSC_TABLE_VARIATION_VALUES . "` WHERE `id`='" . $value_id . "' LIMIT 1", ARRAY_A);
                        $variation_list .= $value_data[0]['name'];
                        $i++;
                    }
                    $variation_list .= ")";
                } else {
                    if ($variation_count == 1) {
                        $value_id = $variation_data[0]['value_id'];
                        $value_data = $wpdb->get_results("SELECT * FROM `" . WPSC_TABLE_VARIATION_VALUES . "` WHERE `id`='" . $value_id . "' LIMIT 1", ARRAY_A);
                        $variation_list = " (" . $value_data[0]['name'] . ")";
                    } else {
                        $variation_list = '';
                    }
                }
                if ($link != '') {
                    $product_list .= " - " . $product_data['name'] . stripslashes($variation_list) . "  " . $message_price . " " . __('Click to download', 'wpsc') . ":";
                    $product_list_html .= " - " . $product_data['name'] . stripslashes($variation_list) . "  " . $message_price . "&nbsp;&nbsp;" . __('Click to download', 'wpsc') . ":\n\r";
                    foreach ($link as $single_link) {
                        $product_list .= "\n\r " . $single_link["name"] . ": " . $single_link["url"] . "\n\r";
                        $product_list_html .= "<a href='" . $single_link["url"] . "'>" . $single_link["name"] . "</a>\n";
                    }
                } else {
                    $plural = '';
                    if ($row['quantity'] > 1) {
                        $plural = "s";
                    }
                    $product_list .= " - " . $row['quantity'] . " " . $product_data[0]['name'] . $variation_list . "  " . $message_price . "\n";
                    if ($shipping > 0) {
                        $product_list .= " - " . __('Shipping', 'wpsc') . ":" . $shipping_price . "\n\r";
                    }
                    $product_list_html .= " - " . $row['quantity'] . " " . $product_data[0]['name'] . $variation_list . "  " . $message_price . "\n";
                    if ($shipping > 0) {
                        $product_list_html .= " - " . __('Shipping', 'wpsc') . ":" . $shipping_price . "\n\r";
                    }
                }
                $report .= " - " . $product_data[0]['name'] . $variation_list . "  " . $message_price . "\n";
            }
            if ($purchase_log['discount_data'] != '') {
                $coupon_data = $wpdb->get_row("SELECT * FROM `" . WPSC_TABLE_COUPON_CODES . "` WHERE coupon_code='" . $wpdb->escape($purchase_log['discount_data']) . "' LIMIT 1", ARRAY_A);
                if ($coupon_data['use-once'] == 1) {
                    $wpdb->query("UPDATE `" . WPSC_TABLE_COUPON_CODES . "` SET `active`='0', `is-used`='1' WHERE `id`='" . $coupon_data['id'] . "' LIMIT 1");
                }
            }
            //$wpdb->query("UPDATE `".WPSC_TABLE_DOWNLOAD_STATUS."` SET `active`='1' WHERE `fileid`='".$product_data[0]['file']."' AND `purchid` = '".$purchase_log['id']."' LIMIT 1");
            $total_shipping += $purchase_log['base_shipping'];
            $total = $total + $total_shipping - $purchase_log['discount_value'];
            // $message.= "\n\r";
            $product_list .= "Your Purchase No.: " . $purchase_log['id'] . "\n\r";
            if ($purchase_log['discount_value'] > 0) {
                $discount_email .= __('Discount', 'wpsc') . ": " . nzshpcrt_currency_display($purchase_log['discount_value'], 1, true) . "\n\r";
            }
            $total_shipping_email .= __('Total Shipping', 'wpsc') . ": " . nzshpcrt_currency_display($total_shipping, 1, true) . "\n\r";
            $total_price_email .= __('Total', 'wpsc') . ": " . nzshpcrt_currency_display($total, 1, true) . "\n\r";
            $product_list_html .= "Your Purchase No.: " . $purchase_log['id'] . "\n\n\r";
            if ($purchase_log['discount_value'] > 0) {
                $discount_html .= __('Discount', 'wpsc') . ": " . nzshpcrt_currency_display($purchase_log['discount_value'], 1, true) . "\n\r";
            }
            $total_shipping_html .= __('Total Shipping', 'wpsc') . ": " . nzshpcrt_currency_display($total_shipping, 1, true) . "\n\r";
            $total_price_html .= __('Total', 'wpsc') . ": " . nzshpcrt_currency_display($total, 1, true) . "\n\r";
            if (isset($_GET['ti'])) {
                $message .= "\n\r" . __('Your Transaction ID', 'wpsc') . ": " . $_GET['ti'];
                $message_html .= "\n\r" . __('Your Transaction ID', 'wpsc') . ": " . $_GET['ti'];
                $report .= "\n\r" . __('Transaction ID', 'wpsc') . ": " . $_GET['ti'];
            } else {
                $report_id = "Purchase No.: " . $purchase_log['id'] . "\n\r";
            }
            $message = str_replace('%product_list%', $product_list, $message);
            $message = str_replace('%total_shipping%', $total_shipping_email, $message);
            $message = str_replace('%total_price%', $total_price_email, $message);
            //$message = str_replace('%order_status%',get_option('blogname'),$message);
            $message = str_replace('%shop_name%', get_option('blogname'), $message);
            $report = str_replace('%product_list%', $report_product_list, $report);
            $report = str_replace('%total_shipping%', $total_shipping_email, $report);
            $report = str_replace('%total_price%', $total_price_email, $report);
            $report = str_replace('%shop_name%', get_option('blogname'), $report);
            $message_html = str_replace('%product_list%', $product_list_html, $message_html);
            $message_html = str_replace('%total_shipping%', $total_shipping_html, $message_html);
            $message_html = str_replace('%total_price%', $total_price_email, $message_html);
            $message_html = str_replace('%shop_name%', get_option('blogname'), $message_html);
            //	exit($message_html);
            if ($email != '') {
                add_filter('wp_mail_from', 'wpsc_replace_reply_address', 0);
                add_filter('wp_mail_from_name', 'wpsc_replace_reply_name', 0);
                if ($purchase_log['processed'] < 2) {
                    $payment_instructions = strip_tags(get_option('payment_instructions'));
                    $message = __('Thank you, your purchase is pending, you will be sent an email once the order clears.', 'wpsc') . "\n\r" . $payment_instructions . "\n\r" . $message;
                    $resent = (bool) wp_mail($email, __('Order Pending: Payment Required', 'wpsc'), $message);
                    $sent = 1;
                } else {
                    $resent = (bool) wp_mail($email, __('Purchase Receipt', 'wpsc'), $message);
                    $sent = 1;
                }
                //echo "$message<br />";
                //exit($email);
                remove_filter('wp_mail_from_name', 'wpsc_replace_reply_name');
                remove_filter('wp_mail_from', 'wpsc_replace_reply_address');
            }
        }
    }
    $sendback = wp_get_referer();
    if (isset($sent)) {
        $sendback = add_query_arg('sent', $sent, $sendback);
    }
    wp_redirect($sendback);
    exit;
}
Exemple #3
0
function gateway_chronopay($seperator, $sessionid)
{
    global $wpdb;
    $purchase_log_sql = "SELECT * FROM `" . $wpdb->prefix . "purchase_logs` WHERE `sessionid`= " . $sessionid . " LIMIT 1";
    $purchase_log = $wpdb->get_results($purchase_log_sql, ARRAY_A);
    $cart_sql = "SELECT * FROM `" . $wpdb->prefix . "cart_contents` WHERE `purchaseid`='" . $purchase_log[0]['id'] . "'";
    $cart = $wpdb->get_results($cart_sql, ARRAY_A);
    // Chronopay post variables
    $chronopay_url = get_option('chronopay_url');
    $data['product_id'] = get_option('chronopay_product_id');
    $data['product_name'] = get_option('chronopay_product_name');
    $data['product_price_currency'] = get_option('chronopay_curcode');
    $data['language'] = get_option('chronopay_language');
    $data['cb_url'] = get_option('siteurl') . "/?chronopay_callback=true";
    $data['cb_type'] = 'P';
    $data['decline_url'] = get_option('siteurl') . "/?chronopay_callback=true";
    $data['cs1'] = $sessionid;
    $data['cs2'] = 'chronopay';
    $salt = get_option('chronopay_salt');
    $data['cs3'] = md5($salt . md5($sessionid . $salt));
    // placed in here for security so that the return call can be validated as 'real'
    // User details
    if ($_POST['collected_data'][get_option('chronopay_form_first_name')] != '') {
        $data['f_name'] = $_POST['collected_data'][get_option('chronopay_form_first_name')];
    }
    if ($_POST['collected_data'][get_option('chronopay_form_last_name')] != "") {
        $data['s_name'] = $_POST['collected_data'][get_option('chronopay_form_last_name')];
    }
    if ($_POST['collected_data'][get_option('chronopay_form_address')] != '') {
        $data['street'] = str_replace("\n", ', ', $_POST['collected_data'][get_option('chronopay_form_address')]);
    }
    if ($_POST['collected_data'][get_option('chronopay_form_city')] != '') {
        $data['city'] = $_POST['collected_data'][get_option('chronopay_form_city')];
    }
    if (preg_match("/^[a-zA-Z]{2}\$/", $_SESSION['selected_country'])) {
        $data['country'] = $_SESSION['selected_country'];
    }
    // Change suggested by waxfeet@gmail.com, if email to be sent is not there, dont send an email address
    $email_data = $wpdb->get_results("SELECT `id`,`type` FROM `" . $wpdb->prefix . "collect_data_forms` WHERE `type` IN ('email') AND `active` = '1'", ARRAY_A);
    foreach ((array) $email_data as $email) {
        $data['email'] = $_POST['collected_data'][$email['id']];
    }
    if ($_POST['collected_data'][get_option('email_form_field')] != null && $data['email'] == null) {
        $data['email'] = $_POST['collected_data'][get_option('email_form_field')];
    }
    // Get Currency details abd price
    $currency_code = $wpdb->get_results("SELECT `code` FROM `" . $wpdb->prefix . "currency_list` WHERE `id`='" . get_option(currency_type) . "' LIMIT 1", ARRAY_A);
    $local_currency_code = $currency_code[0]['code'];
    $chronopay_currency_code = get_option('chronopay_curcode');
    // Chronopay only processes in the set currency.  This is USD or EUR dependent on what the Chornopay account is set up with.
    // This must match the Chronopay settings set up in wordpress.  Convert to the chronopay currency and calculate total.
    $curr = new CURRENCYCONVERTER();
    $decimal_places = 2;
    $total_price = 0;
    $i = 1;
    $all_donations = true;
    $all_no_shipping = true;
    foreach ($cart as $item) {
        $product_data = $wpdb->get_results("SELECT * FROM `" . $wpdb->prefix . "product_list` WHERE `id`='" . $item['prodid'] . "' LIMIT 1", ARRAY_A);
        $product_data = $product_data[0];
        $variation_count = count($product_variations);
        $variation_sql = "SELECT * FROM `" . $wpdb->prefix . "cart_item_variations` WHERE `cart_id`='" . $item['id'] . "'";
        $variation_data = $wpdb->get_results($variation_sql, ARRAY_A);
        $variation_count = count($variation_data);
        if ($variation_count >= 1) {
            $variation_list = " (";
            $j = 0;
            foreach ($variation_data as $variation) {
                if ($j > 0) {
                    $variation_list .= ", ";
                }
                $value_id = $variation['venue_id'];
                $value_data = $wpdb->get_results("SELECT * FROM `" . $wpdb->prefix . "variation_values` WHERE `id`='" . $value_id . "' LIMIT 1", ARRAY_A);
                $variation_list .= $value_data[0]['name'];
                $j++;
            }
            $variation_list .= ")";
        } else {
            $variation_list = '';
        }
        $local_currency_productprice = $item['price'];
        $local_currency_shipping = nzshpcrt_determine_item_shipping($item['prodid'], 1, $_SESSION['delivery_country']);
        if ($chronopay_currency_code != $local_currency_code) {
            $chronopay_currency_productprice = $curr->convert($local_currency_productprice, $chronopay_currency_code, $local_currency_code);
            $chronopay_currency_shipping = $curr->convert($local_currency_shipping, $chronopay_currency_code, $local_currency_code);
        } else {
            $chronopay_currency_productprice = $local_currency_productprice;
            $chronopay_currency_shipping = $local_currency_shipping;
        }
        $data['item_name_' . $i] = $product_data['name'] . $variation_list;
        $data['amount_' . $i] = number_format(sprintf("%01.2f", $chronopay_currency_productprice), $decimal_places, '.', '');
        $data['quantity_' . $i] = $item['quantity'];
        $data['item_number_' . $i] = $product_data['id'];
        if ($item['donation'] != 1) {
            $all_donations = false;
            $data['shipping_' . $i] = number_format($chronopay_currency_shipping, $decimal_places, '.', '');
            $data['shipping2_' . $i] = number_format($chronopay_currency_shipping, $decimal_places, '.', '');
        } else {
            $data['shipping_' . $i] = number_format(0, $decimal_places, '.', '');
            $data['shipping2_' . $i] = number_format(0, $decimal_places, '.', '');
        }
        if ($product_data['no_shipping'] != 1) {
            $all_no_shipping = false;
        }
        $total_price = $total_price + $data['amount_' . $i] * $data['quantity_' . $i];
        if ($all_no_shipping != false) {
            $total_price = $total_price + $data['shipping_' . $i] + $data['shipping2_' . $i];
        }
        $i++;
    }
    $base_shipping = nzshpcrt_determine_base_shipping(0, $_SESSION['delivery_country']);
    if ($base_shipping > 0 && $all_donations == false && $all_no_shipping == false) {
        if ($chronopay_currency_code != $local_currency_code) {
            $base_shipping = $curr->convert($base_shipping, $chronopay_currency_code, $local_currency_code);
        }
        $data['handling_cart'] = number_format($base_shipping, $decimal_places, '.', '');
        $total_price += number_format($base_shipping, $decimal_places, '.', '');
    }
    $data['product_price'] = $total_price;
    // Create Form to post to Chronopay
    $output = "\n\t\t<form id=\"chronopay_form\" name=\"chronopay_form\" method=\"post\" action=\"{$chronopay_url}\">\n";
    foreach ($data as $n => $v) {
        $output .= "\t\t\t<input type=\"hidden\" name=\"{$n}\" value=\"{$v}\" />\n";
    }
    $output .= "\t\t\t<input type=\"submit\" value=\"Continue to ChronoPay\" />\n\t\t</form>\n\t";
    // echo form..
    if (get_option('chronopay_debug') == 1) {
        echo "DEBUG MODE ON!!<br/>";
        echo "The following form is created and would be posted to Chronopay for processing.  Press submit to continue:<br/>";
        echo "<pre>" . htmlspecialchars($output) . "</pre>";
    }
    echo $output;
    if (get_option('chronopay_debug') == 0) {
        echo "<script language=\"javascript\" type=\"text/javascript\">document.getElementById('chronopay_form').submit();</script>";
    }
    exit;
}
Exemple #4
0
/**
 * Purchase log ajax code starts here
*/
function wpsc_purchlog_resend_email()
{
    global $wpdb;
    $siteurl = get_option('siteurl');
    $log_id = $_GET['email_buyer_id'];
    if (is_numeric($log_id)) {
        $selectsql = "SELECT * FROM `" . WPSC_TABLE_PURCHASE_LOGS . "` WHERE `id`= " . $log_id . " LIMIT 1";
        $purchase_log = $wpdb->get_row($selectsql, ARRAY_A);
        if ($purchase_log['gateway'] == "testmode" && $purchase_log['processed'] < 2) {
            $message = get_option("wpsc_email_receipt");
            $message_html = "<h2  style='font-size:16px;font-weight:bold;color:#000;border:0px;padding-top: 0px;' >" . TXT_WPSC_YOUR_ORDER . "</h2>";
        } else {
            $message = get_option("wpsc_email_receipt");
            $message_html = $message;
        }
        $order_url = $siteurl . "/wp-admin/admin.php?page=" . WPSC_DIR_NAME . "/display-log.php&amp;purchcaseid=" . $purchase_log['id'];
        $cartsql = "SELECT * FROM `" . WPSC_TABLE_CART_CONTENTS . "` WHERE `purchaseid`=" . $purchase_log['id'] . "";
        $cart = $wpdb->get_results($cartsql, ARRAY_A);
        if ($purchase_log['shipping_country'] != '') {
            $billing_country = $purchase_log['billing_country'];
            $shipping_country = $purchase_log['shipping_country'];
        } else {
            $country = $wpdb->get_results("SELECT * FROM `" . WPSC_TABLE_SUBMITED_FORM_DATA . "` WHERE `log_id`=" . $purchase_log['id'] . " AND `form_id` = '" . get_option('country_form_field') . "' LIMIT 1", ARRAY_A);
            $billing_country = $country[0]['value'];
            $shipping_country = $country[0]['value'];
        }
        $email_form_field = $wpdb->get_results("SELECT `id`,`type` FROM `" . WPSC_TABLE_CHECKOUT_FORMS . "` WHERE `type` IN ('email') AND `active` = '1' ORDER BY `order` ASC LIMIT 1", ARRAY_A);
        $email_address = $wpdb->get_results("SELECT * FROM `" . WPSC_TABLE_SUBMITED_FORM_DATA . "` WHERE `log_id`=" . $purchase_log['id'] . " AND `form_id` = '" . $email_form_field[0]['id'] . "' LIMIT 1", ARRAY_A);
        $email = $email_address[0]['value'];
        $previous_download_ids = array(0);
        if ($cart != null) {
            foreach ($cart as $row) {
                $link = "";
                $productsql = "SELECT * FROM `" . WPSC_TABLE_PRODUCT_LIST . "` WHERE `id`=" . $row['prodid'] . "";
                $product_data = $wpdb->get_results($productsql, ARRAY_A);
                if ($product_data[0]['file'] > 0) {
                    if ($purchase_log['email_sent'] != 1) {
                        $wpdb->query("UPDATE `" . WPSC_TABLE_DOWNLOAD_STATUS . "` SET `active`='1' WHERE `fileid`='" . $product_data[0]['file'] . "' AND `purchid` = '" . $purchase_log['id'] . "' LIMIT 1");
                    }
                    if ($purchase_log['processed'] >= 2) {
                        $download_data = $wpdb->get_row("SELECT * FROM `" . WPSC_TABLE_DOWNLOAD_STATUS . "` WHERE `fileid`='" . $product_data[0]['file'] . "' AND `purchid`='" . $purchase_log['id'] . "' AND (`cartid` = '" . $row['id'] . "' OR `cartid` IS NULL) AND `id` NOT IN (" . make_csv($previous_download_ids) . ") LIMIT 1", ARRAY_A);
                        if ($download_data != null) {
                            if ($download_data['uniqueid'] == null) {
                                // if the uniqueid is not equal to null, its "valid", regardless of what it is
                                $link = $siteurl . "?downloadid=" . $download_data['id'];
                            } else {
                                $link = $siteurl . "?downloadid=" . $download_data['uniqueid'];
                            }
                        }
                        $previous_download_ids[] = $download_data['id'];
                        $order_status = 4;
                    }
                }
                do_action('wpsc_confirm_checkout', $purchase_log['id']);
                $shipping = nzshpcrt_determine_item_shipping($row['prodid'], $row['quantity'], $shipping_country);
                if (isset($_SESSION['quote_shipping'])) {
                    $shipping = $_SESSION['quote_shipping'];
                }
                $total_shipping += $shipping;
                if ($product_data[0]['special'] == 1) {
                    $price_modifier = $product_data[0]['special_price'];
                } else {
                    $price_modifier = 0;
                }
                $total += $row['price'] * $row['quantity'];
                $message_price = nzshpcrt_currency_display($row['price'] * $row['quantity'], $product_data[0]['notax'], true);
                $shipping_price = nzshpcrt_currency_display($shipping, 1, true);
                $variation_sql = "SELECT * FROM `" . WPSC_TABLE_CART_ITEM_VARIATIONS . "` WHERE `cart_id`='" . $row['id'] . "'";
                $variation_data = $wpdb->get_results($variation_sql, ARRAY_A);
                $variation_count = count($variation_data);
                if ($variation_count > 1) {
                    $variation_list = " (";
                    if ($purchase['gateway'] != 'testmode') {
                        if ($gateway['internalname'] == $purch_data[0]['gateway']) {
                            $gateway_name = $gateway['name'];
                        }
                    } else {
                        $gateway_name = "Manual Payment";
                    }
                    $i = 0;
                    foreach ($variation_data as $variation) {
                        if ($i > 0) {
                            $variation_list .= ", ";
                        }
                        $value_id = $variation['value_id'];
                        $value_data = $wpdb->get_results("SELECT * FROM `" . WPSC_TABLE_VARIATION_VALUES . "` WHERE `id`='" . $value_id . "' LIMIT 1", ARRAY_A);
                        $variation_list .= $value_data[0]['name'];
                        $i++;
                    }
                    $variation_list .= ")";
                } else {
                    if ($variation_count == 1) {
                        $value_id = $variation_data[0]['value_id'];
                        $value_data = $wpdb->get_results("SELECT * FROM `" . WPSC_TABLE_VARIATION_VALUES . "` WHERE `id`='" . $value_id . "' LIMIT 1", ARRAY_A);
                        $variation_list = " (" . $value_data[0]['name'] . ")";
                    } else {
                        $variation_list = '';
                    }
                }
                if ($link != '') {
                    $product_list .= " - " . $product_data['name'] . stripslashes($variation_list) . "  " . $message_price . " " . TXT_WPSC_CLICKTODOWNLOAD . ":\n {$link}\n";
                    $product_list_html .= " - " . $product_data['name'] . stripslashes($variation_list) . "  " . $message_price . "&nbsp;&nbsp;<a href='{$link}'>" . TXT_WPSC_CLICKTODOWNLOAD . "</a>\n";
                } else {
                    $plural = '';
                    if ($row['quantity'] > 1) {
                        $plural = "s";
                    }
                    $product_list .= " - " . $row['quantity'] . " " . $product_data[0]['name'] . $variation_list . "  " . $message_price . "\n";
                    if ($shipping > 0) {
                        $product_list .= " - " . TXT_WPSC_SHIPPING . ":" . $shipping_price . "\n\r";
                    }
                    $product_list_html .= " - " . $row['quantity'] . " " . $product_data[0]['name'] . $variation_list . "  " . $message_price . "\n";
                    if ($shipping > 0) {
                        $product_list_html .= " - " . TXT_WPSC_SHIPPING . ":" . $shipping_price . "\n\r";
                    }
                }
                $report .= " - " . $product_data[0]['name'] . $variation_list . "  " . $message_price . "\n";
            }
            if ($purchase_log['discount_data'] != '') {
                $coupon_data = $wpdb->get_row("SELECT * FROM `" . WPSC_TABLE_COUPON_CODES . "` WHERE coupon_code='" . $wpdb->escape($purchase_log['discount_data']) . "' LIMIT 1", ARRAY_A);
                if ($coupon_data['use-once'] == 1) {
                    $wpdb->query("UPDATE `" . WPSC_TABLE_COUPON_CODES . "` SET `active`='0', `is-used`='1' WHERE `id`='" . $coupon_data['id'] . "' LIMIT 1");
                }
            }
            //$wpdb->query("UPDATE `".WPSC_TABLE_DOWNLOAD_STATUS."` SET `active`='1' WHERE `fileid`='".$product_data[0]['file']."' AND `purchid` = '".$purchase_log['id']."' LIMIT 1");
            $total_shipping += $purchase_log['base_shipping'];
            $total = $total + $total_shipping - $purchase_log['discount_value'];
            // $message.= "\n\r";
            $product_list .= "Your Purchase No.: " . $purchase_log['id'] . "\n\r";
            if ($purchase_log['discount_value'] > 0) {
                $discount_email .= TXT_WPSC_DISCOUNT . ": " . nzshpcrt_currency_display($purchase_log['discount_value'], 1, true) . "\n\r";
            }
            $total_shipping_email .= TXT_WPSC_TOTALSHIPPING . ": " . nzshpcrt_currency_display($total_shipping, 1, true) . "\n\r";
            $total_price_email .= TXT_WPSC_TOTAL . ": " . nzshpcrt_currency_display($total, 1, true) . "\n\r";
            $product_list_html .= "Your Purchase No.: " . $purchase_log['id'] . "\n\n\r";
            if ($purchase_log['discount_value'] > 0) {
                $discount_html .= TXT_WPSC_DISCOUNT . ": " . nzshpcrt_currency_display($purchase_log['discount_value'], 1, true) . "\n\r";
            }
            $total_shipping_html .= TXT_WPSC_TOTALSHIPPING . ": " . nzshpcrt_currency_display($total_shipping, 1, true) . "\n\r";
            $total_price_html .= TXT_WPSC_TOTAL . ": " . nzshpcrt_currency_display($total, 1, true) . "\n\r";
            if (isset($_GET['ti'])) {
                $message .= "\n\r" . TXT_WPSC_YOURTRANSACTIONID . ": " . $_GET['ti'];
                $message_html .= "\n\r" . TXT_WPSC_YOURTRANSACTIONID . ": " . $_GET['ti'];
                $report .= "\n\r" . TXT_WPSC_TRANSACTIONID . ": " . $_GET['ti'];
            } else {
                $report_id = "Purchase No.: " . $purchase_log['id'] . "\n\r";
            }
            $message = str_replace('%product_list%', $product_list, $message);
            $message = str_replace('%total_shipping%', $total_shipping_email, $message);
            $message = str_replace('%total_price%', $total_price_email, $message);
            //$message = str_replace('%order_status%',get_option('blogname'),$message);
            $message = str_replace('%shop_name%', get_option('blogname'), $message);
            $report = str_replace('%product_list%', $report_product_list, $report);
            $report = str_replace('%total_shipping%', $total_shipping_email, $report);
            $report = str_replace('%total_price%', $total_price_email, $report);
            $report = str_replace('%shop_name%', get_option('blogname'), $report);
            $message_html = str_replace('%product_list%', $product_list_html, $message_html);
            $message_html = str_replace('%total_shipping%', $total_shipping_html, $message_html);
            $message_html = str_replace('%total_price%', $total_price_email, $message_html);
            $message_html = str_replace('%shop_name%', get_option('blogname'), $message_html);
            //	exit($message_html);
            if ($email != '') {
                add_filter('wp_mail_from', 'wpsc_replace_reply_address', 0);
                add_filter('wp_mail_from_name', 'wpsc_replace_reply_name', 0);
                if ($purchase_log['processed'] < 2) {
                    $payment_instructions = strip_tags(get_option('payment_instructions'));
                    $message = TXT_WPSC_ORDER_PENDING . "\n\r" . $payment_instructions . "\n\r" . $message;
                    $resent = (bool) wp_mail($email, TXT_WPSC_ORDER_PENDING_PAYMENT_REQUIRED, $message);
                    $sent = 1;
                } else {
                    $resent = (bool) wp_mail($email, TXT_WPSC_PURCHASERECEIPT, $message);
                    $sent = 1;
                }
                //echo "$message<br />";
                //exit($email);
                remove_filter('wp_mail_from_name', 'wpsc_replace_reply_name');
                remove_filter('wp_mail_from', 'wpsc_replace_reply_address');
            }
        }
    }
    $sendback = wp_get_referer();
    if (isset($sent)) {
        $sendback = add_query_arg('sent', $sent, $sendback);
    }
    wp_redirect($sendback);
    exit;
}
function nzshpcrt_find_total_price($purchase_id, $country_code)
{
    global $wpdb;
    if (is_numeric($purchase_id)) {
        $purch_sql = "SELECT * FROM `" . WPSC_TABLE_PURCHASE_LOGS . "` WHERE `id`='" . $purchase_id . "'";
        $purch_data = $wpdb->get_row($purch_sql, ARRAY_A);
        $cartsql = "SELECT * FROM `" . WPSC_TABLE_CART_CONTENTS . "` WHERE `purchaseid`=" . $purchase_id . "";
        $cart_log = $wpdb->get_results($cartsql, ARRAY_A);
        if ($cart_log != null) {
            $all_donations = true;
            $all_no_shipping = true;
            foreach ($cart_log as $cart_row) {
                $productsql = "SELECT * FROM `" . WPSC_TABLE_PRODUCT_LIST . "` WHERE `id`=" . $cart_row['prodid'] . "";
                $product_data = $wpdb->get_results($productsql, ARRAY_A);
                $variation_sql = "SELECT * FROM `" . WPSC_TABLE_CART_ITEM_VARIATIONS . "` WHERE `cart_id`='" . $cart_row['id'] . "'";
                $variation_data = $wpdb->get_results($variation_sql, ARRAY_A);
                $variation_count = count($variation_data);
                $price = $cart_row['price'] * $cart_row['quantity'];
                if ($purch_data['shipping_country'] != '') {
                    $country_code = $purch_data['shipping_country'];
                }
                if ($cart_row['donation'] == 1) {
                    $shipping = 0;
                } else {
                    $all_donations = false;
                }
                if ($cart_row['no_shipping'] == 1) {
                    $shipping = 0;
                } else {
                    $all_no_shipping = false;
                }
                if ($cart_row['donation'] != 1 && $cart_row['no_shipping'] != 1) {
                    $shipping = nzshpcrt_determine_item_shipping($cart_row['prodid'], $cart_row['quantity'], $country_code);
                }
                $endtotal += $shipping + $price;
            }
            if ($all_donations == false && $all_no_shipping == false) {
                if ($purch_data['base_shipping'] > 0) {
                    $base_shipping = $purch_data['base_shipping'];
                } else {
                    $base_shipping = nzshpcrt_determine_base_shipping(0, $country_code);
                }
                $endtotal += $base_shipping;
            }
            if ($purch_data['discount_value'] > 0) {
                $endtotal -= $purch_data['discount_value'];
                if ($endtotal < 0) {
                    $endtotal = 0;
                }
            }
        }
        return $endtotal;
    }
}
function nzshpcrt_submit_checkout()
{
    /*
     * This is the function used for handling the submitted checkout page
     */
    global $wpdb, $nzshpcrt_gateways, $user_ID;
    session_start();
    if (get_option('permalink_structure') != '') {
        $seperator = "?";
    } else {
        $seperator = "&";
    }
    if ($_POST['submitwpcheckout'] == 'true') {
        $check_checkout_page = $wpdb->get_var("SELECT `id` FROM `" . $wpdb->posts . "` WHERE `post_content` LIKE '%[checkout]%' LIMIT 1");
        if (is_numeric($check_checkout_page)) {
            $returnurl = "Location: " . get_option('shopping_cart_url') . $seperator . "total=" . $_GET['total'];
        } else {
            $returnurl = "Location: " . get_option('shopping_cart_url');
        }
        $_SESSION['collected_data'] = $_POST['collected_data'];
        $find_us = $_POST['how_find_us'];
        if (!($_POST['engrave1'] == '' && $_POST['engrave2'] == '')) {
            $engrave = $wpdb->escape($_POST['engrave1'] . "," . $_POST['engrave2']);
        }
        $any_bad_inputs = false;
        foreach ($_POST['collected_data'] as $value_id => $value) {
            $form_sql = "SELECT * FROM `" . $wpdb->prefix . "collect_data_forms` WHERE `id` = '{$value_id}' LIMIT 1";
            $form_data = $wpdb->get_results($form_sql, ARRAY_A);
            $form_data = $form_data[0];
            /*
            if($_POST['collected_data'][get_option('paypal_form_address')] != '')
            {
            $map_data['address'] = addslashes($_POST['collected_data'][get_option('paypal_form_address')]);
            }
            if($_POST['collected_data'][get_option('paypal_form_city')] != '')
            {
            $map_data['city'] = addslashes($_POST['collected_data'][get_option('paypal_form_city')]); 
            }
            if(preg_match("/^[a-zA-Z]{2}$/",$_SESSION['selected_country']))
            {
            $map_data['country'] = $_SESSION['selected_country'];
            }
            $map_data['zipcode']='';
            $map_data['radius'] = '50000';
            $map_data['state'] = '';
            $map_data['submit'] = 'Find Store';
            		
            $i=0;
            if (function_exists('getdistance')) {
            	$maps = getdistance($map_data);
            	while($rows = mysql_fetch_array($maps)) {
            		if ($i==0) {
            			$closest_store = $rows[5];
            		}
            		$i++;
            	}
            }
            //$wpdb->query("UPDATE `".$wpdb->prefix."purchase_logs` SET `closest_store` = '".$closest_store."' WHERE `id` = '".$log_id."' LIMIT 1 ;");
            */
            $bad_input = false;
            if ($form_data['mandatory'] == 1 || $form_data['type'] == "coupon") {
                switch ($form_data['type']) {
                    case "email":
                        if (!preg_match("/^[a-zA-Z0-9._-]+@[a-zA-Z0-9-.]+\\.[a-zA-Z]{2,5}\$/", $value)) {
                            $any_bad_inputs = true;
                            $bad_input = true;
                        }
                        break;
                    case "delivery_country":
                        break;
                    case "country":
                        break;
                    default:
                        if ($value == null) {
                            $any_bad_inputs = true;
                            $bad_input = true;
                        }
                        break;
                }
                /*
                if($form_data['type'] == "coupon") {
                	if($value != '') { // only act if data has been entered
                		$coupon_sql = "SELECT * FROM `".$wpdb->prefix."wpsc_coupon_codes` WHERE `coupon_code` = '".$value."' AND `active` = '1' LIMIT 1";
                		$coupon_data = $wpdb->get_results($coupon_sql,ARRAY_A);
                		if($coupon_data == null) {
                			$any_bad_inputs = true;
                			$bad_input = true;
                			}
                		}
                	}
                */
                if ($bad_input === true) {
                    switch ($form_data['name']) {
                        case TXT_WPSC_FIRSTNAME:
                            $bad_input_message .= TXT_WPSC_PLEASEENTERAVALIDNAME . "";
                            break;
                        case TXT_WPSC_LASTNAME:
                            $bad_input_message .= TXT_WPSC_PLEASEENTERAVALIDSURNAME . "";
                            break;
                        case TXT_WPSC_EMAIL:
                            $bad_input_message .= TXT_WPSC_PLEASEENTERAVALIDEMAILADDRESS . "";
                            break;
                        case TXT_WPSC_ADDRESS1:
                        case TXT_WPSC_ADDRESS2:
                            $bad_input_message .= TXT_WPSC_PLEASEENTERAVALIDADDRESS . "";
                            break;
                        case TXT_WPSC_CITY:
                            $bad_input_message .= TXT_WPSC_PLEASEENTERAVALIDCITY . "";
                            break;
                        case TXT_WPSC_PHONE:
                            $bad_input_message .= TXT_WPSC_PLEASEENTERAVALIDPHONENUMBER . "";
                            break;
                        case TXT_WPSC_COUNTRY:
                            $bad_input_message .= TXT_WPSC_PLEASESELECTCOUNTRY . "";
                            break;
                            //             case TXT_WPSC_COUPON:
                            //             $bad_input_message .= TXT_WPSC_COUPON_DOESNT_EXIST . "";
                            //             break;
                        //             case TXT_WPSC_COUPON:
                        //             $bad_input_message .= TXT_WPSC_COUPON_DOESNT_EXIST . "";
                        //             break;
                        default:
                            $bad_input_message .= TXT_WPSC_PLEASEENTERAVALID . " " . strtolower($form_data['name']) . ".";
                            break;
                    }
                    $bad_input_message .= "\n\r";
                }
            }
        }
        // this here section handles uploading files specified by the user for products
        $accepted_file_types['mime'][] = 'image/jpeg';
        $accepted_file_types['mime'][] = 'image/gif';
        $accepted_file_types['mime'][] = 'image/png';
        $accepted_file_types['ext'][] = 'jpeg';
        $accepted_file_types['ext'][] = 'jpg';
        $accepted_file_types['ext'][] = 'gif';
        $accepted_file_types['ext'][] = 'png';
        foreach ($_SESSION['nzshpcrt_cart'] as $key => $item) {
            $can_have_uploaded_image = get_product_meta($item->product_id, 'can_have_uploaded_image', true);
            if ($can_have_uploaded_image[0] == 'on') {
                $file_data['name'] = basename($_FILES['uploaded_image']['name'][$key]);
                $file_data['type'] = $_FILES['uploaded_image']['type'][$key];
                $file_data['tmp_name'] = $_FILES['uploaded_image']['tmp_name'][$key];
                $file_data['error'] = $_FILES['uploaded_image']['error'][$key];
                $file_data['size'] = $_FILES['uploaded_image']['size'][$key];
                $mime_type_data = wpsc_get_mimetype($file_data['tmp_name'], true);
                $name_parts = explode('.', basename($file_data['name']));
                $extension = array_pop($name_parts);
                echo $extension . "<br />";
                if ($mime_type_data['is_reliable'] == true) {
                    $mime_type = $mime_type_data['mime_type'];
                } else {
                    // if we can't use what PHP provides us with, we have to trust the user as there aren't really any other choices.
                    $mime_type = $file_data['type'];
                }
                if (array_search($mime_type, $accepted_file_types['mime']) !== false && array_search($extension, $accepted_file_types['ext']) !== false) {
                    if (is_file(WPSC_USER_UPLOADS_DIR . $file_data['name'])) {
                        $name_parts = explode('.', basename($file_data['name']));
                        $extension = array_pop($name_parts);
                        $name_base = implode('.', $name_parts);
                        $file_data['name'] = null;
                        $num = 2;
                        //  loop till we find a free file name, first time I get to do a do loop in yonks
                        do {
                            $test_name = "{$name_base}-{$num}.{$extension}";
                            if (!file_exists(WPSC_USER_UPLOADS_DIR . $test_name)) {
                                $file_data['name'] = $test_name;
                            }
                            $num++;
                        } while ($file_data['name'] == null);
                    }
                    //exit($file_data['name']);
                    if (move_uploaded_file($file_data['tmp_name'], WPSC_USER_UPLOADS_DIR . $file_data['name'])) {
                        $_SESSION['nzshpcrt_cart'][$key]->file_data = array('file_name' => $file_data['name'], 'mime_type' => $mime_type);
                    }
                }
            }
        }
        //echo("<pre>".print_r($_FILES,true)."</pre>");
        //exit("<pre>".print_r($_SESSION['nzshpcrt_cart'],true)."</pre>");
        foreach ((array) $_SESSION['nzshpcrt_cart'] as $item) {
            //exit("------><pre>".print_r((array)$_SESSION['nzshpcrt_cart'],1)."</pre>");
            $in_stock = check_in_stock($item->product_id, $item->product_variations, $item->quantity);
            if (get_option('checkbox_variation') == '1') {
                $in_stock = true;
            }
            if ($in_stock == false) {
                $bad_input_message .= TXT_WPSC_ITEM_GONE_OUT_OF_STOCK . "";
                $bad_input_message .= "\n\r";
                $any_bad_inputs = true;
                break;
            }
        }
        if (get_option('custom_gateway_options') == null) {
            $bad_input_message .= TXT_WPSC_PROCESSING_PROBLEM . "";
            $bad_input_message .= "\n\r";
            $any_bad_inputs = true;
        }
        list($bad_input_message, $any_bad_inputs) = apply_filters('wpsc_additional_checkout_checks', array($bad_input_message, $any_bad_inputs));
        //exit("<pre>".print_r($bad_input_message, true)."</pre>");
        if ($any_bad_inputs === true) {
            $_SESSION['nzshpcrt_checkouterr'] = nl2br($bad_input_message);
            header($returnurl);
            exit;
        }
        $cart = $_SESSION['nzshpcrt_cart'];
        $_SESSION['checkoutdata'] = $_POST;
        if ($_POST['agree'] != 'yes') {
            $_SESSION['nzshpcrt_checkouterr'] = TXT_WPSC_PLEASEAGREETERMSANDCONDITIONS;
            header($returnurl);
            exit;
        }
        if ($cart == null) {
            $_SESSION['nzshpcrt_checkouterr'] = TXT_WPSC_NOTHINGINYOURSHOPPINGCART;
            header($returnurl);
            exit;
        }
        $sessionid = mt_rand(100, 999) . time();
        if (!(is_numeric($user_ID) && $user_ID > 0)) {
            $user_ID = 'null';
        }
        if (isset($_SESSION['usps_shipping']) && is_numeric($_SESSION['usps_shipping'])) {
            $base_shipping = $_SESSION['usps_shipping'];
        } else {
            $base_shipping = nzshpcrt_determine_base_shipping(0, $_SESSION['delivery_country']);
        }
        //clear the coupon
        //$_SESSION['coupon_num'] = '';
        //insert the record into the purchase log table
        //exit("----->". $_SESSION['delivery_country']);
        $price = nzshpcrt_overall_total_price($_SESSION['selected_country'], false);
        $sql = "INSERT INTO `" . $wpdb->prefix . "purchase_logs` ( `totalprice` , `sessionid` , `date`, `billing_country`, `shipping_country`,`base_shipping`,`shipping_region`, `user_ID`, `discount_value`, `discount_data`, `find_us`, `engravetext`, `google_status`) VALUES ( '" . $wpdb->escape($price) . "', '" . $sessionid . "', '" . time() . "', '" . $_SESSION['selected_country'] . "', '" . $_SESSION['delivery_country'] . "', '" . $base_shipping . "','" . $_SESSION['selected_region'] . "' , '" . (int) $user_ID . "' , '" . (double) $_SESSION['wpsc_discount'] . "', '" . $wpdb->escape($_SESSION['coupon_num']) . "', '', '{$engrave}', ' ')";
        //exit($sql);
        $wpdb->query($sql);
        $email_user_detail = '';
        $log_id = $wpdb->get_var("SELECT `id` FROM `" . $wpdb->prefix . "purchase_logs` WHERE `sessionid` IN('" . $sessionid . "') LIMIT 1");
        foreach ($_POST['collected_data'] as $value_id => $value) {
            $wpdb->query("INSERT INTO `" . $wpdb->prefix . "submited_form_data` ( `log_id` , `form_id` , `value` ) VALUES ( '" . $log_id . "', '" . $value_id . "', '" . $value . "');");
        }
        if (function_exists("nzshpcrt_user_log")) {
            if ($wpdb->get_var("SHOW TABLES LIKE '" . $wpdb->prefix . "usermeta'")) {
                $saved_data_sql = "SELECT * FROM `" . $wpdb->prefix . "usermeta` WHERE `user_id` = '" . $user_ID . "' AND `meta_key` = 'wpshpcrt_usr_profile';";
                $saved_data = $wpdb->get_row($saved_data_sql, ARRAY_A);
                $new_meta_data = serialize($_POST['collected_data']);
                if ($saved_data != null) {
                    $wpdb->query("UPDATE `" . $wpdb->prefix . "usermeta` SET `meta_value` =  '{$new_meta_data}' WHERE `user_id` IN ('{$user_ID}') AND `meta_key` IN ('wpshpcrt_usr_profile');");
                } else {
                    if (is_numeric($user_ID)) {
                        $wpdb->query("INSERT INTO `" . $wpdb->prefix . "usermeta` ( `user_id` , `meta_key` , `meta_value` ) VALUES ( " . $user_ID . ", 'wpshpcrt_usr_profile', '{$new_meta_data}');");
                    }
                }
            }
        }
        $downloads = get_option('max_downloads');
        $also_bought = array();
        $all_donations = true;
        $all_no_shipping = true;
        foreach ($cart as $cart_item) {
            $row = $cart_item->product_id;
            $quantity = $cart_item->quantity;
            $variations = $cart_item->product_variations;
            $extras = $cart_item->extras;
            // serialize file data
            if (is_array($cart_item->file_data)) {
                $file_data = $wpdb->escape(serialize($cart_item->file_data));
            } else {
                $file_data = '';
            }
            /* creates an array of purchased items for logging further on */
            if (isset($also_bought[$cart_item->product_id])) {
                $also_bought[$cart_item->product_id]++;
            } else {
                $also_bought[$cart_item->product_id] = 1;
            }
            $product_data = $wpdb->get_row("SELECT * FROM `" . $wpdb->prefix . "product_list` WHERE `id` = '{$row}' LIMIT 1", ARRAY_A);
            if ($product_data['file'] > 0) {
                $unique_id = sha1(uniqid(mt_rand(), true));
                $wpdb->query("INSERT INTO `" . $wpdb->prefix . "download_status` ( `fileid` , `purchid` , `uniqueid`, `downloads` , `active` , `datetime` ) VALUES ( '" . $product_data['file'] . "', '" . $log_id . "', '" . $unique_id . "', '{$downloads}', '0', NOW( ));");
            }
            if ($product_data['donation'] == 1) {
                $price = $cart_item->donation_price;
                $gst = 0;
                $donation = 1;
            } else {
                $price = calculate_product_price($row, $variations);
                if ($product_data['notax'] != 1) {
                    $price = nzshpcrt_calculate_tax($price, $_SESSION['selected_country'], $_SESSION['selected_region']);
                    if (get_option('base_country') == $_SESSION['selected_country']) {
                        $country_data = $wpdb->get_row("SELECT * FROM `" . $wpdb->prefix . "currency_list` WHERE `isocode` IN('" . get_option('base_country') . "') LIMIT 1", ARRAY_A);
                        if ($country_data['has_regions'] == 1) {
                            if (get_option('base_region') == $_SESSION['selected_region']) {
                                $region_data = $wpdb->get_row("SELECT `" . $wpdb->prefix . "region_tax`.* FROM `" . $wpdb->prefix . "region_tax` WHERE `" . $wpdb->prefix . "region_tax`.`country_id` IN('" . $country_data['id'] . "') AND `" . $wpdb->prefix . "region_tax`.`id` IN('" . get_option('base_region') . "') ", ARRAY_A);
                            }
                            $gst = $region_data['tax'];
                        } else {
                            $gst = $country_data['tax'];
                        }
                    }
                } else {
                    $gst = 0;
                }
                $donation = 0;
                $all_donations = false;
            }
            if ($product_data['no_shipping'] != 1) {
                $all_no_shipping = false;
            }
            $country = $wpdb->get_results("SELECT * FROM `" . $wpdb->prefix . "submited_form_data` WHERE `log_id`='" . $log_id . "' AND `form_id` = '" . get_option('country_form_field') . "' LIMIT 1", ARRAY_A);
            $country = $country[0]['value'];
            $country_data = $wpdb->get_row("SELECT * FROM `" . $wpdb->prefix . "currency_list` WHERE `isocode` IN('" . get_option('base_country') . "') LIMIT 1", ARRAY_A);
            $shipping = nzshpcrt_determine_item_shipping($row, 1, $_SESSION['delivery_country']);
            $cartsql = "INSERT INTO `" . $wpdb->prefix . "cart_contents` ( `prodid` , `purchaseid`, `price`, `pnp`, `gst`, `quantity`, `donation`, `no_shipping`, `files` ) VALUES ('" . $row . "', '" . $log_id . "','" . $price . "','" . $shipping . "', '" . $gst . "','" . $quantity . "', '" . $donation . "', '" . $product_data['no_shipping'] . "', '{$file_data}')";
            //exit($cartsql);
            $wpdb->query($cartsql);
            $cart_id = $wpdb->get_results("SELECT LAST_INSERT_ID() AS `id` FROM `" . $wpdb->prefix . "product_variations` LIMIT 1", ARRAY_A);
            $cart_id = $cart_id[0]['id'];
            $extra_var = '';
            if ($variations != null) {
                $extra_var .= '[';
                $i = 0;
                foreach ($variations as $variation => $value) {
                    $wpdb->query("INSERT INTO `" . $wpdb->prefix . "cart_item_variations` ( `cart_id` , `variation_id` , `value_id` ) VALUES ( '" . $cart_id . "', '" . $variation . "', '" . $value . "' );");
                    $i++;
                    if ($i == 1) {
                        $extra_var .= $value;
                    } else {
                        $extra_var .= "," . $value;
                    }
                }
            }
            $j = 0;
            $extra_var .= '],[';
            if ($extras != null) {
                foreach ($extras as $extra) {
                    $wpdb->query("INSERT INTO `" . $wpdb->prefix . "cart_item_extras` ( `cart_id` , `extra_id`) VALUES ( '" . $cart_id . "', '" . $extra . "');");
                    $name = $wpdb->get_var("SELECT name FROM " . $wpdb->prefix . "extras_values WHERE id={$extra}");
                    $j++;
                    if ($j == 1) {
                        $extra_var .= $name;
                    } else {
                        $extra_var .= "," . $name;
                    }
                }
                $extra_var .= ']';
            }
            /*
            	if (function_exists('sendemailstostores')) {
            		if ($_POST['pickupordelivery']==1){
            			$delivery = "Pick Up";
            		} else {
            			$delivery = "Delivery";
            		}
            		$chosen_store = $_POST['chosen_store'];
            		$email_sql = "SELECT * FROM locations WHERE storename='".$chosen_store."'";
            		$email_data = $wpdb->get_results($email_sql,ARRAY_A);
            		
            		$email_message = "Order: ".$product_data['name']." with additional variations : ".$extra_var."<br>";
            		$email_message .= "<br>";
            		$email_message .= "Delivery/Pick Up:".$delivery;
            		$email_message .= "<br>";
            		$email_message .= "Customer detail: <br>";
            		$email_message .= "Name:". $_POST['collected_data'][get_option('paypal_form_first_name')]." ".$_POST['collected_data'][get_option('paypal_form_last_name')]."<br>";
            		$email_message .= "Address: ".$map_data['address']."<br>";
            		$email_message .= "City:".$map_data['city'];
            		sendemailstostores($email_data[0]['url'],'New Order',$email_message);
            	}*/
            /*
             * This code decrements the stock quantitycart_item_variations`
             */
            if (is_array($variations)) {
                $variation_values = array_values($variations);
            }
            //$debug .= "<pre>".print_r($variations,true)."</pre>";
            if ($product_data['quantity_limited'] == 1) {
                switch (count($variation_values)) {
                    case 2:
                        $variation_stock_data = $wpdb->get_row("SELECT * FROM `" . $wpdb->prefix . "variation_priceandstock` WHERE `product_id` = '" . $product_data['id'] . "' AND (`variation_id_1` = '" . $variation_values[0] . "' AND `variation_id_2` = '" . $variation_data[1] . "') OR (`variation_id_1` = '" . $variation_values[1] . "' AND `variation_id_2` = '" . $variation_values[0] . "') LIMIT 1", ARRAY_A);
                        //$debug .= "<pre>".print_r($variation_stock_data,true)."</pre>";
                        $wpdb->query("UPDATE `" . $wpdb->prefix . "variation_priceandstock` SET `stock` = '" . ($variation_stock_data['stock'] - $quantity) . "'  WHERE `id` = '" . $variation_stock_data['id'] . "' LIMIT 1", ARRAY_A);
                        break;
                    case 1:
                        $variation_stock_data = $wpdb->get_row("SELECT * FROM `" . $wpdb->prefix . "variation_priceandstock` WHERE `product_id` = '" . $product_data['id'] . "' AND (`variation_id_1` = '" . $variation_values[0] . "' AND `variation_id_2` = '0') LIMIT 1", ARRAY_A);
                        //$debug .= "<pre>".print_r($variation_stock_data,true)."</pre>";
                        $wpdb->query("UPDATE `" . $wpdb->prefix . "variation_priceandstock` SET `stock` = '" . ($variation_stock_data['stock'] - $quantity) . "'  WHERE `id` = '" . $variation_stock_data['id'] . "' LIMIT 1", ARRAY_A);
                        break;
                    default:
                        /* normal form of decrementing stock */
                        $wpdb->query("UPDATE `" . $wpdb->prefix . "product_list` SET `quantity`='" . ($product_data['quantity'] - $quantity) . "' WHERE `id`='" . $product_data['id'] . "' LIMIT 1");
                        break;
                }
            }
        }
        $unneeded_value = null;
        //this is only used to store the quantity for the item we are working on, so that we can get the array key
        $assoc_quantity = null;
        foreach ($also_bought as $selected_product => $unneeded_value) {
            foreach ($also_bought as $associated_product => $assoc_quantity) {
                if ($selected_product == $associated_product) {
                    continue;
                    //don't want to associate products with themselves
                }
                $check_assoc = $wpdb->get_var("SELECT `id` FROM `" . $wpdb->prefix . "also_bought_product` WHERE `selected_product` IN('{$selected_product}') AND `associated_product` IN('{$associated_product}') LIMIT 1");
                if (isset($check_assoc) && $check_assoc > 0) {
                    $wpdb->query("UPDATE `" . $wpdb->prefix . "also_bought_product` SET `quantity` = (`quantity` + {$assoc_quantity}) WHERE `id` = '{$check_assoc}' LIMIT 1;");
                } else {
                    $wpdb->query("INSERT INTO `" . $wpdb->prefix . "also_bought_product` ( `selected_product` , `associated_product` , `quantity` ) VALUES ( '{$selected_product}', '" . $associated_product . "', '" . $assoc_quantity . "' );");
                }
            }
        }
        do_action('wpsc_submit_checkout', $log_id);
        //mail( get_option('purch_log_email'),('debug from '.date("d/m/Y H:i:s")), $debug);
        $curgateway = get_option('payment_gateway');
        //	if (get_option('custom_gateway')) {
        $selected_gateways = get_option('custom_gateway_options');
        if (count($selected_gateways) > 1) {
            if (in_array($_POST['custom_gateway'], (array) $selected_gateways)) {
                $curgateway = $_POST['custom_gateway'];
            } else {
                $curgateway = get_option('payment_gateway');
            }
        } else {
            if (count($selected_gateways) == 1) {
                $curgateway = array_pop($selected_gateways);
            }
        }
        //} else {
        //	$curgateway = get_option('payment_gateway');
        //}
        if (get_option('permalink_structure') != '') {
            $seperator = "?";
        } else {
            $seperator = "&";
        }
        if ($_POST['payment_method'] == 2 && get_option('payment_method') == 2 || get_option('payment_method') == 3) {
            foreach ($nzshpcrt_gateways as $gateway) {
                if ($gateway['internalname'] == 'testmode') {
                    $gateway_used = $gateway['internalname'];
                    $wpdb->query("UPDATE `" . $wpdb->prefix . "purchase_logs` SET `gateway` = '" . $gateway_used . "' WHERE `id` = '" . $log_id . "' LIMIT 1 ;");
                    $gateway['function']($seperator, $sessionid);
                }
            }
        } else {
            foreach ($nzshpcrt_gateways as $gateway) {
                if ($gateway['internalname'] == $curgateway) {
                    $gateway_used = $gateway['internalname'];
                    $wpdb->query("UPDATE `" . $wpdb->prefix . "purchase_logs` SET `gateway` = '" . $gateway_used . "' WHERE `id` = '" . $log_id . "' LIMIT 1 ;");
                    $gateway['function']($seperator, $sessionid);
                }
            }
        }
        $_SESSION['coupon_num'] = '';
        //exit("<pre>".print_r($nzshpcrt_gateways,true)."</pre>");
    }
}
function nzshpcrt_submit_ajax()
{
    global $wpdb, $user_level, $wp_rewrite;
    get_currentuserinfo();
    if (get_option('permalink_structure') != '') {
        $seperator = "?";
    } else {
        $seperator = "&amp;";
    }
    $cartt = $_SESSION['nzshpcrt_cart'];
    $cartt1 = $cartt[0]->product_id;
    // if is an AJAX request, cruddy code, could be done better but getting approval would be impossible
    if ($_POST['ajax'] == "true" || $_GET['ajax'] == "true") {
        if ($_POST['metabox'] == 'true') {
            $output .= "<div class='meta_box'>";
            if (get_option('multi_add') == '1') {
                $output .= TXT_WPSC_QUANTITY . ": <input type='text' name='quantity[]' size='3'><br>";
            }
            if (get_option('time_requested') == '1') {
                $output .= TXT_WPSC_DATE_REQUESTED . ": <input type='text' class='time_requested' name='time_requested[]' size='10'><br>";
            }
            if (get_option('commenting') == '1') {
                $output .= TXT_WPSC_COMMENT . ":<br><textarea type='text' name='comment[]'></textarea><br>";
            }
            $output .= TXT_WPSC_LABEL . ":<br><textarea type='text' name='label[]'></textarea><br>";
            $output .= "</div>";
            exit($output);
        }
        if ($_POST['submittogoogle']) {
            $newvalue = $_POST['value'];
            $amount = $_POST['amount'];
            $reason = $_POST['reason'];
            $comment = $_POST['comment'];
            $message = $_POST['message'];
            $amount = number_format($amount, 2, '.', '');
            $log_data = $wpdb->get_row("SELECT * FROM `" . WPSC_TABLE_PURCHASE_LOGS . "` WHERE `id` = '" . $_POST['id'] . "' LIMIT 1", ARRAY_A);
            if ($newvalue == 2 && function_exists('wpsc_member_activate_subscriptions')) {
                wpsc_member_activate_subscriptions($_POST['id']);
            }
            $google_status = unserialize($log_data['google_status']);
            switch ($newvalue) {
                case "Charge":
                    if ($google_status[0] != 'CANCELLED_BY_GOOGLE') {
                        if ($amount == '') {
                            $google_status['0'] = 'Partially Charged';
                        } else {
                            $google_status['0'] = 'CHARGED';
                            $google_status['partial_charge_amount'] = $amount;
                        }
                    }
                    break;
                case "Cancel":
                    if ($google_status[0] != 'CANCELLED_BY_GOOGLE') {
                        $google_status[0] = 'CANCELLED';
                    }
                    if ($google_status[1] != 'DELIVERED') {
                        $google_status[1] = 'WILL_NOT_DELIVER';
                    }
                    break;
                case "Refund":
                    if ($amount == '') {
                        $google_status['0'] = 'Partially Refund';
                    } else {
                        $google_status['0'] = 'REFUND';
                        $google_status['partial_refund_amount'] = $amount;
                    }
                    break;
                case "Ship":
                    if ($google_status[1] != 'WILL_NOT_DELIVER') {
                        $google_status[1] = 'DELIVERED';
                    }
                    break;
                case "Archive":
                    $google_status[1] = 'ARCHIVED';
                    break;
            }
            $google_status_sql = "UPDATE `" . WPSC_TABLE_PURCHASE_LOGS . "` SET google_status='" . serialize($google_status) . "' WHERE `id` = '" . $_POST['id'] . "' LIMIT 1";
            $wpdb->query($google_status_sql);
            $merchant_id = get_option('google_id');
            $merchant_key = get_option('google_key');
            $server_type = get_option('google_server_type');
            $currency = get_option('google_cur');
            $Grequest = new GoogleRequest($merchant_id, $merchant_key, $server_type, $currency);
            $google_order_number = $wpdb->get_var("SELECT google_order_number FROM `" . WPSC_TABLE_PURCHASE_LOGS . "` WHERE `id` = '" . $_POST['id'] . "' LIMIT 1");
            switch ($newvalue) {
                case 'Charge':
                    $Grequest->SendChargeOrder($google_order_number, $amount);
                    break;
                case 'Ship':
                    $Grequest->SendDeliverOrder($google_order_number);
                    break;
                case 'Archive':
                    $Grequest->SendArchiveOrder($google_order_number);
                    break;
                case 'Refund':
                    $Grequest->SendRefundOrder($google_order_number, $amount, $reason);
                    break;
                case 'Cancel':
                    $Grequest->SendCancelOrder($google_order_number, $reason, $comment);
                    break;
                case 'Send Message':
                    $Grequest->SendBuyerMessage($google_order_number, $message);
                    break;
            }
            $newvalue++;
            $update_sql = "UPDATE `" . WPSC_TABLE_PURCHASE_LOGS . "` SET `processed` = '" . $newvalue . "' WHERE `id` = '" . $_POST['id'] . "' LIMIT 1";
            //$wpdb->query($update_sql);
            exit;
        }
        /*
        	if(($_GET['user'] == "true") && is_numeric($_POST['prodid'])) {
        		if(function_exists('wpsc_members_init')) {
        			$memberstatus = get_product_meta($_POST['prodid'],'is_membership',true);
        		}
        
        		if(($memberstatus=='1') && ($_SESSION['nzshopcrt_cart']!=NULL)){
        		} else{
        			$sql = "SELECT * FROM `".WPSC_TABLE_PRODUCT_LIST."` WHERE `id`='".$_POST['prodid']."' LIMIT 1";
        			$item_data = $wpdb->get_results($sql,ARRAY_A);
        			if ($_POST['quantity']!='') {
        				$add_quantity = $_POST['quantity'];
        			}
        			$item_quantity = 0;
        			if($_SESSION['nzshpcrt_cart'] != null) {
        				foreach($_SESSION['nzshpcrt_cart'] as $cart_key => $cart_item) {
        					if (($memberstatus[0]!='1')&&($_SESSION['nzshpcrt_cart']!=NULL)){
        						if($cart_item->product_id == $_POST['prodid']) {
        							if(($_SESSION['nzshpcrt_cart'][$cart_key]->product_variations === $_POST['variation'])&&($_SESSION['nzshpcrt_cart'][$cart_key]->extras === $_POST['extras'])) {
        								$item_quantity += $_SESSION['nzshpcrt_cart'][$cart_key]->quantity;
        								$item_variations = $_SESSION['nzshpcrt_cart'][$cart_key]->product_variations;
        							}
        						}
        					}
        				}
        			}
        		  
        		  $item_stock = null;
        		  $variation_count = count($_POST['variation']);
        		  if($variation_count >= 1) {
        				foreach($_POST['variation'] as $value_id) {
        					if(is_numeric($value_id)) {
        						$value_ids[] = (int)$value_id;
        					}
        				}
        				
                if(count($value_ids) > 0) {
                  $variation_ids = $wpdb->get_col("SELECT `variation_id` FROM `".WPSC_TABLE_VARIATION_VALUES."` WHERE `id` IN ('".implode("','",$value_ids)."')");
                  asort($variation_ids);
                  $all_variation_ids = implode(",", $variation_ids);
                
                
                  $priceandstock_id = $wpdb->get_var("SELECT `priceandstock_id` FROM `".WPSC_TABLE_VARIATION_COMBINATIONS."` WHERE `product_id` = '".(int)$_POST['prodid']."' AND `value_id` IN ( '".implode("', '",$value_ids )."' )  AND `all_variation_ids` IN('$all_variation_ids')  GROUP BY `priceandstock_id` HAVING COUNT( `priceandstock_id` ) = '".count($value_ids)."' LIMIT 1");
                  
                  $variation_stock_data = $wpdb->get_row("SELECT * FROM `".WPSC_TABLE_VARIATION_PROPERTIES."` WHERE `id` = '{$priceandstock_id}' LIMIT 1", ARRAY_A);
                  
                  $item_stock = $variation_stock_data['stock'];
                }				
        			}
        
        			
        		if($item_stock === null) {
        			$item_stock = $item_data[0]['quantity'];
        		}
        		
        			if((($item_data[0]['quantity_limited'] == 1) && ($item_stock > 0) && ($item_stock > $item_quantity)) || ($item_data[0]['quantity_limited'] == 0)) {
        				$cartcount = count($_SESSION['nzshpcrt_cart']);
        				if(is_array($_POST['variation'])) {  $variations = $_POST['variation'];  }  else  { $variations = null; }
        				//if(is_array($_POST['extras'])) {  $extras = $_POST['extras'];  }  else  { $extras = null; }
        				$updated_quantity = false;
        				if($_SESSION['nzshpcrt_cart'] != null) {
        					foreach($_SESSION['nzshpcrt_cart'] as $cart_key => $cart_item) {
        						if ((!($memberstatus[0]=='1')&&(count($_SESSION['nzshpcrt_cart'])>0))) {
        							if((int)$cart_item->product_id === (int)$_POST['prodid']) {  // force both to integer before testing for identicality
        								if(($_SESSION['nzshpcrt_cart'][$cart_key]->extras === $extras)&&($_SESSION['nzshpcrt_cart'][$cart_key]->product_variations === $variations) && ((int)$_SESSION['nzshpcrt_cart'][$cart_key]->donation_price == (int)$_POST['donation_price'])) {
        									if ($_POST['quantity'] != ''){
        									  if(is_array($_POST['quantity'])) {
        											foreach ((array)$_POST['quantity'] as $qty) {
        												$_SESSION['nzshpcrt_cart'][$cart_key]->quantity += (int)$qty;
        											}
        										} else {
        											$_SESSION['nzshpcrt_cart'][$cart_key]->quantity += (int)$_POST['quantity'];
        										}
        									} else {
        										$_SESSION['nzshpcrt_cart'][$cart_key]->quantity++;
        									}
        									$_SESSION['nzshpcrt_cart'][$cart_key]->comment = $_POST['comment'];
        									foreach((array)$_POST['label'] as $key => $label) {
        										if ($label != '') {
        											if (array_key_exists($label, $_SESSION['nzshpcrt_cart'][$cart_key]->meta)) {
        												$_SESSION['nzshpcrt_cart'][$cart_key]->meta[$label]+=(int)$_POST['quantity'][$key];
        												$_SESSION['nzshpcrt_cart'][$cart_key]->time_requested[$label] = $_POST['time_requested'][$key];
        											} else {
        												$_SESSION['nzshpcrt_cart'][$cart_key]->meta[$label] = $_POST['quantity'][$key];
        												$_SESSION['nzshpcrt_cart'][$cart_key]->time_requested[$label] = $_POST['time_requested'][$key];
        											}
        										}
        									}
        									$updated_quantity = true;
        								}
        							}
        						}
        					}
        				}
        				if($item_data[0]['donation'] == 1) {
        					$donation = $_POST['donation_price'];
        				} else {
        					$donation = false;
        				}
        				if(!(($memberstatus=='1')&&(count($_SESSION['nzshpcrt_cart'])>0))){
        					$status = get_product_meta($cartt1, 'is_membership', true);
        					if (function_exists('wpsc_members_init') && ( $status=='1')){
        						exit();
        					}	
        					$parameters = array();
        					if($updated_quantity === false) {
        						$parameters['variation_values'] = $variations;
        						$parameters['provided_price'] = $donation;
        						$parameters['meta']=null;
        						if($_POST['quantity'] != '') {
        							$total_qty = 0;
        							foreach ($_POST['quantity'] as $key=>$qty) {
        								$total_qty+=$qty;
        								$label[$_POST['label'][$key]] = $qty;
        								$time_requested[$_POST['label'][$key]] = $_POST['time_requested'][$key];
        							}
        							$parameters['quantity'] = $total_qty;
        							//$new_cart_item = new wpsc_cart_item($_POST['prodid'],$variations,$total_qty, $donation,$_POST['comment'],$time_requested,$label);
        						} else {
        							$parameters['quantity'] = 1;
        						}
        						//mail('*****@*****.**', 'stuff', print_r($parameters,true));
        						$new_cart_item = new wpsc_cart_item($_POST['prodid'],$parameters);
        						$_SESSION['nzshpcrt_cart'][] = $new_cart_item;
        					}
        				}
        			} else {
        				$quantity_limit = true;
        			}
        		
        			$cart = $_SESSION['nzshpcrt_cart'];
        		
        			if (($memberstatus[0]=='1')&&(count($cart)>1)) {
        			} else {
        				$status = get_product_meta($cartt1, 'is_membership', true);
        				if (function_exists('wpsc_members_init') && ( $status=='1')){
        					exit('st');
        				}
        
        				//require_once(WPSC_FILE_PATH."/shopping_cart_functions.php"); 
        			  echo  "if(document.getElementById('shoppingcartcontents') != null)
        					  {
        					  document.getElementById('shoppingcartcontents').innerHTML = \"".str_replace(Array("\n","\r") , "",addslashes(nzshpcrt_shopping_basket_internals($cart,$quantity_limit))). "\";
        					  }
        					";
        
        			  
        			  if($_SESSION['slider_state'] == 0) {
        				//echo  'jQuery("#sliding_cart").css({ display: "none"});'."\n\r";
        				} else {
        				//echo  'jQuery("#sliding_cart").css({ display: "block"});'."\n\r";
        				}
        			}
        		}
              exit();
        		} else if(($_POST['user'] == "true") && ($_POST['emptycart'] == "true")) {
        			$_SESSION['nzshpcrt_cart'] = '';			
        			$_SESSION['nzshpcrt_cart'] = Array();      
        			echo  "if(document.getElementById('shoppingcartcontents') != null) {   
        			document.getElementById('shoppingcartcontents').innerHTML = \"".str_replace(Array("\n","\r") , "", addslashes(nzshpcrt_shopping_basket_internals($cart))). "\";
        			}\n\r";
        			
        			if($_POST['current_page'] == get_option('shopping_cart_url')) {
        			  echo "window.location = '".get_option('shopping_cart_url')."';\n\r"; // if we are on the checkout page, redirect back to it to clear the non-ajax cart too
        			}
        			exit();
        		}*/
        if ($_POST['store_list'] == "true") {
            $map_data['address'] = $_POST['addr'];
            $map_data['city'] = $_POST['city'];
            $map_data['country'] = 'US';
            $map_data['zipcode'] = '';
            $map_data['radius'] = '50000';
            $map_data['state'] = '';
            $map_data['submit'] = 'Find Store';
            $stores = getdistance($map_data);
            $i = 0;
            while ($rows = mysql_fetch_array($stores)) {
                //echo "<pre>".print_r($rows,1)."</pre>";
                if ($i == 0) {
                    $closest_store = $rows[5];
                }
                $i++;
                $store_list[$i] = $rows[5];
            }
            foreach ($store_list as $store) {
                $output .= "<option value='{$store}'>{$store}</option>";
            }
            echo $output;
            exit;
        }
        if (is_numeric($_POST['currencyid'])) {
            $currency_data = $wpdb->get_results("SELECT `symbol`,`symbol_html`,`code` FROM `" . WPSC_TABLE_CURRENCY_LIST . "` WHERE `id`='" . $_POST['currencyid'] . "' LIMIT 1", ARRAY_A);
            $price_out = null;
            if ($currency_data[0]['symbol'] != '') {
                $currency_sign = $currency_data[0]['symbol_html'];
            } else {
                $currency_sign = $currency_data[0]['code'];
            }
            echo $currency_sign;
            exit;
        }
        if ($_POST['buynow'] == "true") {
            if (is_numeric($_REQUEST['product_id']) && is_numeric($_REQUEST['price'])) {
                $id = $wpdb->escape((int) $_REQUEST['product_id']);
                $price = $wpdb->escape((double) $_REQUEST['price']);
                $downloads = get_option('max_downloads');
                $product_info = $wpdb->get_row("SELECT * FROM " . WPSC_TABLE_PRODUCT_LIST . " WHERE id = " . $id . " LIMIT 1", ARRAY_A);
                if (count($product_info) > 0) {
                    $sessionid = mt_rand(100, 999) . time();
                    $sql = "INSERT INTO `" . WPSC_TABLE_PURCHASE_LOGS . "` ( `totalprice` , `sessionid` , `date`, `billing_country`, `shipping_country`,`shipping_region`, `user_ID`, `discount_value` ) VALUES ( '" . $price . "', '" . $sessionid . "', '" . time() . "', 'BuyNow', 'BuyNow', 'BuyNow' , NULL , 0)";
                    $wpdb->query($sql);
                    $log_id = $wpdb->get_var("SELECT `id` FROM `" . WPSC_TABLE_PURCHASE_LOGS . "` WHERE `sessionid` IN('" . $sessionid . "') LIMIT 1");
                    $cartsql = "INSERT INTO `" . WPSC_TABLE_CART_CONTENTS . "` ( `prodid` , `purchaseid`, `price`, `pnp`, `gst`, `quantity`, `donation`, `no_shipping` ) VALUES ('" . $id . "', '" . $log_id . "','" . $price . "','0', '0','1', '" . $donation . "', '1')";
                    $wpdb->query($cartsql);
                    $wpdb->query("INSERT INTO `" . WPSC_TABLE_DOWNLOAD_STATUS . "` ( `fileid` , `purchid` , `downloads` , `active` , `datetime` ) VALUES ( '" . $product_info['file'] . "', '" . $log_id . "', '{$downloads}', '0', NOW( ));");
                }
            }
            exit;
        }
        /* rate item */
        if ($_POST['rate_item'] == "true" && is_numeric($_POST['product_id']) && is_numeric($_POST['rating'])) {
            $nowtime = time();
            $prodid = $_POST['product_id'];
            $ip_number = $_SERVER['REMOTE_ADDR'];
            $rating = $_POST['rating'];
            $cookie_data = explode(",", $_COOKIE['voting_cookie'][$prodid]);
            if (is_numeric($cookie_data[0]) && $cookie_data[0] > 0) {
                $vote_id = $cookie_data[0];
                $wpdb->query("UPDATE `" . WPSC_TABLE_PRODUCT_RATING . "` SET `rated` = '" . $rating . "' WHERE `id` ='" . $vote_id . "' LIMIT 1 ;");
            } else {
                $insert_sql = "INSERT INTO `" . WPSC_TABLE_PRODUCT_RATING . "` ( `ipnum`  , `productid` , `rated`, `time`) VALUES ( '" . $ip_number . "', '" . $prodid . "', '" . $rating . "', '" . $nowtime . "');";
                $wpdb->query($insert_sql);
                $data = $wpdb->get_results("SELECT `id`,`rated` FROM `" . WPSC_TABLE_PRODUCT_RATING . "` WHERE `ipnum`='" . $ip_number . "' AND `productid` = '" . $prodid . "'  AND `rated` = '" . $rating . "' AND `time` = '" . $nowtime . "' ORDER BY `id` DESC LIMIT 1", ARRAY_A);
                $vote_id = $data[0]['id'];
                setcookie("voting_cookie[{$prodid}]", $vote_id . "," . $rating, time() + 60 * 60 * 24 * 360);
            }
            $output[1] = $prodid;
            $output[2] = $rating;
            echo $output[1] . "," . $output[2];
            exit;
        }
        //written by allen
        if ($_REQUEST['save_tracking_id'] == "true") {
            $id = $_POST['id'];
            $value = $_POST['value'];
            $update_sql = "UPDATE " . WPSC_TABLE_PURCHASE_LOGS . " SET track_id = '" . $value . "' WHERE id={$id}";
            $wpdb->query($update_sql);
            exit;
        }
        if ($_POST['get_updated_price'] == "true" && is_numeric($_POST['product_id'])) {
            $notax = $wpdb->get_var("SELECT `notax` FROM `" . WPSC_TABLE_PRODUCT_LIST . "` WHERE `id` IN('" . $_POST['product_id'] . "') LIMIT 1");
            foreach ((array) $_POST['variation'] as $variation) {
                if (is_numeric($variation)) {
                    $variations[] = (int) $variation;
                }
            }
            $pm = $_POST['pm'];
            echo "product_id=" . (int) $_POST['product_id'] . ";\n";
            echo "price=\"" . nzshpcrt_currency_display(calculate_product_price((int) $_POST['product_id'], $variations, 'stay', $extras), $notax, true) . "\";\n";
            echo "numeric_price=\"" . number_format(calculate_product_price((int) $_POST['product_id'], $variations, 'stay', $extras), 2) . "\";\n";
            //exit(print_r($extras,1));
            exit(" ");
        }
        // 	if(($_POST['redisplay_variation_values'] == "true")) {
        // 		$variation_processor = new nzshpcrt_variations();
        // 		$variations_selected = array_values(array_unique(array_merge((array)$_POST['new_variation_id'], (array)$_POST['variation_id'])));
        // 		foreach($variations_selected as $variation_id) {
        // 		  // cast everything to integer to make sure nothing nasty gets in.
        // 		  $variation_list[] = (int)$variation_id;
        // 		}
        // 		echo $variation_processor->variations_add_grid_view((array)$variation_list);
        // 		//echo "/*\n\r".print_r(array_values(array_unique($_POST['variation_id'])),true)."\n\r*/";
        // 		exit();
        // 	}
        //
        /*
         * function for handling the checkout billing address
         */
        if (preg_match("/[a-zA-Z]{2,4}/", $_POST['billing_country'])) {
            if ($_SESSION['selected_country'] == $_POST['billing_country']) {
                $do_not_refresh_regions = true;
            } else {
                $do_not_refresh_regions = false;
                $_SESSION['selected_country'] = $_POST['billing_country'];
            }
            if (is_numeric($_POST['form_id'])) {
                $form_id = $_POST['form_id'];
                $html_form_id = "region_country_form_{$form_id}";
            } else {
                $html_form_id = 'region_country_form';
            }
            if (is_numeric($_POST['billing_region'])) {
                $_SESSION['selected_region'] = $_POST['billing_region'];
            }
            $cart =& $_SESSION['nzshpcrt_cart'];
            if ($memberstatus[0] == '1' && count($cart) > 0) {
                echo "\n\r";
            } else {
                if ($status[0] == '1') {
                    exit;
                }
                echo "if(document.getElementById('shoppingcartcontents') != null)\n\t\t\t\t\t  {\n\t\t\t\t\t  document.getElementById('shoppingcartcontents').innerHTML = \"" . str_replace(array("\n", "\r"), "", addslashes(nzshpcrt_shopping_basket_internals($cart, $quantity_limit))) . "\";\n\t\t\t\t\t  }\n\r";
                if ($do_not_refresh_regions == false) {
                    $region_list = $wpdb->get_results("SELECT `" . WPSC_TABLE_REGION_TAX . "`.* FROM `" . WPSC_TABLE_REGION_TAX . "`, `" . WPSC_TABLE_CURRENCY_LIST . "`  WHERE `" . WPSC_TABLE_CURRENCY_LIST . "`.`isocode` IN('" . $_POST['billing_country'] . "') AND `" . WPSC_TABLE_CURRENCY_LIST . "`.`id` = `" . WPSC_TABLE_REGION_TAX . "`.`country_id`", ARRAY_A);
                    if ($region_list != null) {
                        $output .= "<select name='collected_data[" . $form_id . "][1]' class='current_region' onchange='set_billing_country(\\\"{$html_form_id}\\\", \\\"{$form_id}\\\");'>";
                        //$output .= "<option value=''>None</option>";
                        foreach ($region_list as $region) {
                            if ($_SESSION['selected_region'] == $region['id']) {
                                $selected = "selected='true'";
                            } else {
                                $selected = "";
                            }
                            $output .= "<option value='" . $region['id'] . "' {$selected}>" . $region['name'] . "</option>";
                        }
                        $output .= "</select>";
                        echo "if(document.getElementById('region_select_{$form_id}') != null)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\tdocument.getElementById('region_select_{$form_id}').innerHTML = \"" . $output . "\";\n\t\t\t\t\t\t\t}\n\r";
                    } else {
                        echo "if(document.getElementById('region_select_{$form_id}') != null)\n\t\t\t\t\t\t{\n\t\t\t\t\t\tdocument.getElementById('region_select_{$form_id}').innerHTML = \"\";\n\t\t\t\t\t\t}\n\r";
                    }
                }
            }
            if ($_POST['changetax'] == "true") {
                if (isset($_POST['billing_region'])) {
                    $billing_region = $_POST['billing_region'];
                } else {
                    $billing_region = $_SESSION['selected_region'];
                }
                $billing_country = $_POST['billing_country'];
                $price = 0;
                $tax = 0;
                foreach ((array) $cart as $cart_item) {
                    $product_id = $cart_item->product_id;
                    $quantity = $cart_item->quantity;
                    //echo("<pre>".print_r($cart_item->product_variations,true)."</pre>");
                    $product = $wpdb->get_row("SELECT * FROM `" . WPSC_TABLE_PRODUCT_LIST . "` WHERE `id` = '{$product_id}' LIMIT 1", ARRAY_A);
                    if ($product['donation'] == 1) {
                        $price += $quantity * $cart_item->donation_price;
                    } else {
                        $product_price = $quantity * calculate_product_price($product_id, $cart_item->product_variations);
                        if ($product['notax'] != 1) {
                            $tax += nzshpcrt_calculate_tax($product_price, $billing_country, $billing_region) - $product_price;
                        }
                        $price += $product_price;
                        $all_donations = false;
                    }
                    if ($_SESSION['delivery_country'] != null) {
                        $total_shipping += nzshpcrt_determine_item_shipping($product['id'], $quantity, $_SESSION['delivery_country']);
                    }
                }
                $total_shipping += nzshpcrt_determine_base_shipping(0, $_SESSION['delivery_country']);
                $total = number_format($tax + $price + $total_shipping, 2);
                if ($tax > 0) {
                    echo "jQuery(\"tr.total_tax td\").show();\n\r";
                } else {
                    echo "jQuery(\"tr.total_tax td\").hide();\n\r";
                }
                $tax = number_format($tax, 2);
                echo "jQuery('#checkout_tax').html(\"<span class='pricedisplay'>\${$tax}</span>\");\n\r";
                echo "jQuery('#checkout_total').html(\"<span class='pricedisplay'>\${$total}</span><input id='shopping_cart_total_price' type='hidden' value='\${$total}'>\");\n\r";
            }
            exit;
        }
        if ($_POST['get_country_tax'] == "true" && preg_match("/[a-zA-Z]{2,4}/", $_POST['country_id'])) {
            $country_id = $_POST['country_id'];
            $region_list = $wpdb->get_results("SELECT `" . WPSC_TABLE_REGION_TAX . "`.* FROM `" . WPSC_TABLE_REGION_TAX . "`, `" . WPSC_TABLE_CURRENCY_LIST . "`  WHERE `" . WPSC_TABLE_CURRENCY_LIST . "`.`isocode` IN('" . $country_id . "') AND `" . WPSC_TABLE_CURRENCY_LIST . "`.`id` = `" . WPSC_TABLE_REGION_TAX . "`.`country_id`", ARRAY_A);
            if ($region_list != null) {
                echo "<select name='base_region'>\n\r";
                foreach ($region_list as $region) {
                    if (get_option('base_region') == $region['id']) {
                        $selected = "selected='true'";
                    } else {
                        $selected = "";
                    }
                    echo "<option value='" . $region['id'] . "' {$selected}>" . $region['name'] . "</option>\n\r";
                }
                echo "</select>\n\r";
            } else {
                echo "&nbsp;";
            }
            exit;
        }
        /* fill product form */
        if ($_POST['set_slider'] == "true" && is_numeric($_POST['state'])) {
            $_SESSION['slider_state'] = $_POST['state'];
            exit;
        }
        /* fill category form */
        if ($_GET['action'] == "register") {
            $siteurl = get_option('siteurl');
            require_once ABSPATH . WPINC . '/registration-functions.php';
            if ($_POST['action'] == 'register' && get_settings('users_can_register')) {
                //exit("fail for testing purposes");
                $user_login = sanitize_user($_POST['user_login']);
                $user_email = $_POST['user_email'];
                $errors = array();
                if ($user_login == '') {
                    exit($errors['user_login'] = __('<strong>ERROR</strong>: Please enter a username.'));
                }
                /* checking e-mail address */
                if ($user_email == '') {
                    exit(__('<strong>ERROR</strong>: Please type your e-mail address.'));
                } else {
                    if (!is_email($user_email)) {
                        exit(__('<strong>ERROR</strong>: The email address isn&#8217;t correct.'));
                        $user_email = '';
                    }
                }
                if (!validate_username($user_login)) {
                    $errors['user_login'] = __('<strong>ERROR</strong>: This username is invalid.  Please enter a valid username.');
                    $user_login = '';
                }
                if (username_exists($user_login)) {
                    exit(__('<strong>ERROR</strong>: This username is already registered, please choose another one.'));
                }
                /* checking the email isn't already used by another user */
                $email_exists = $wpdb->get_row("SELECT user_email FROM {$wpdb->users} WHERE user_email = '{$user_email}'");
                if ($email_exists) {
                    die(__('<strong>ERROR</strong>: This email address is already registered, please supply another.'));
                }
                if (0 == count($errors)) {
                    $password = substr(md5(uniqid(microtime())), 0, 7);
                    //xit('there?');
                    $user_id = wp_create_user($user_login, $password, $user_email);
                    if (!$user_id) {
                        exit(sprintf(__('<strong>ERROR</strong>: Couldn&#8217;t register you... please contact the <a href="mailto:%s">webmaster</a> !'), get_settings('admin_email')));
                    } else {
                        wp_new_user_notification($user_id, $password);
                        ?>
<div id="login"> 
  <h2><?php 
                        _e('Registration Complete');
                        ?>
</h2>
  <p><?php 
                        printf(__('Username: %s'), "<strong>" . wp_specialchars($user_login) . "</strong>");
                        ?>
<br />
  <?php 
                        printf(__('Password: %s'), '<strong>' . __('emailed to you') . '</strong>');
                        ?>
 <br />
  <?php 
                        printf(__('E-mail: %s'), "<strong>" . wp_specialchars($user_email) . "</strong>");
                        ?>
</p>
</div>
<?php 
                    }
                }
            } else {
                // onsubmit='submit_register_form(this);return false;'
                echo "<div id='login'>\n    <h2>Register for this blog</h2>\n    <form id='registerform' action='index.php?ajax=true&amp;action=register'  onsubmit='submit_register_form(this);return false;' method='post'>\n      <p><input type='hidden' value='register' name='action'/>\n      <label for='user_login'>Username:</label><br/> <input type='text' value='' maxlength='20' size='20' id='user_login' name='user_login'/><br/></p>\n      <p><label for='user_email'>E-mail:</label><br/> <input type='text' value='' maxlength='100' size='25' id='user_email' name='user_email'/></p>\n      <p>A password will be emailed to you.</p>\n      <p class='submit'><input type='submit' name='submit_form' id='submit' value='" . TXT_WPSC_REGISTER . " »'/><img id='register_loading_img' src='" . WPSC_URL . "/images/loading.gif' alt='' title=''></p>\n\n      \n    </form>\n    </div>";
            }
            exit;
        }
    }
    /*
    * AJAX stuff stops here, I would put an exit here, but it may screw up other plugins
    //exit();
    */
}
function transaction_results($sessionid, $echo_to_screen = true, $transaction_id = null)
{
    global $wpdb, $_SESSION, $Debug, $_GET;
    //why are autoglobal arrays here?
    $curgateway = get_option('payment_gateway');
    $errorcode = '';
    $order_status = 2;
    $siteurl = get_option('siteurl');
    /*
     * {Notes} Double check that $Echo_To_Screen is a boolean value
     */
    $echo_to_screen = !is_bool($echo_to_screen) ? true : $echo_to_screen;
    if (is_numeric($sessionid)) {
        $report = TXT_WPSC_EMAILMSG2;
        $selectsql = "SELECT * FROM `" . $wpdb->prefix . "purchase_logs` WHERE `sessionid`= " . $sessionid . " LIMIT 1";
        $purchase_log = $wpdb->get_row($selectsql, ARRAY_A);
        if ($purchase_log['gateway'] == "testmode" && $purchase_log['processed'] < 2) {
            $message = "" . TXT_WPSC_YOUR_ORDER . ":\n";
            $message_html = "<h2  style='padding-top: 0px;' >" . TXT_WPSC_YOUR_ORDER . "</h2>";
        } else {
            $message = TXT_WPSC_EMAILMSG1;
            $message_html = $message;
        }
        $order_url = $siteurl . "/wp-admin/admin.php?page=" . WPSC_DIR_NAME . "/display-log.php&amp;purchcaseid=" . $purchase_log['id'];
        if ($_GET['ipn_request'] != 'true' and get_option('paypal_ipn') == 1) {
            if ($purchase_log == null) {
                echo TXT_WPSC_ORDER_FAILED;
                if (get_option('purch_log_email') != null && $purchase_log['email_sent'] != 1) {
                    mail(get_option('purch_log_email'), TXT_WPSC_NEW_ORDER_PENDING_SUBJECT, TXT_WPSC_NEW_ORDER_PENDING_BODY . $order_url, "From: " . get_option('return_email') . "");
                }
                return false;
            } else {
                if ($purchase_log['email_sent'] != 1 && $purchase_log['processed'] < 2) {
                    //added by Thomas on 20/6/2007
                    echo TXT_WPSC_ORDER_PENDING . "<p style='margin: 1em 0px 0px 0px;' >" . nl2br(get_option('payment_instructions')) . "</p>";
                    if ($purchase_log['gateway'] != 'testmode') {
                        if (get_option('purch_log_email') != null && $purchase_log['email_sent'] != 1) {
                            mail(get_option('purch_log_email'), TXT_WPSC_NEW_ORDER_PENDING_SUBJECT, TXT_WPSC_NEW_ORDER_PENDING_BODY . $order_url, "From: " . get_option('return_email') . "");
                        }
                        return false;
                    }
                }
            }
        } else {
            if ($purchase_log['processed'] < 2) {
                //added by Thomas on 20/6/2007
                echo TXT_WPSC_ORDER_PENDING . "<p style='margin: 1em 0px 0px 0px;' >" . nl2br(get_option('payment_instructions')) . "</p>";
                if ($purchase_log['gateway'] != 'testmode') {
                    if (get_option('purch_log_email') != null && $purchase_log['email_sent'] != 1) {
                        mail(get_option('purch_log_email'), TXT_WPSC_NEW_ORDER_PENDING_SUBJECT, TXT_WPSC_NEW_ORDER_PENDING_BODY . $order_url, "From: " . get_option('return_email') . "");
                    }
                    return false;
                }
            }
        }
        $cartsql = "SELECT * FROM `" . $wpdb->prefix . "cart_contents` WHERE `purchaseid`=" . $purchase_log['id'] . "";
        $cart = $wpdb->get_results($cartsql, ARRAY_A);
        if ($purchase_log['shipping_country'] != '') {
            $billing_country = $purchase_log['billing_country'];
            $shipping_country = $purchase_log['shipping_country'];
        } else {
            $country = $wpdb->get_results("SELECT * FROM `" . $wpdb->prefix . "submited_form_data` WHERE `log_id`=" . $purchase_log['id'] . " AND `form_id` = '" . get_option('country_form_field') . "' LIMIT 1", ARRAY_A);
            $billing_country = $country[0]['value'];
            $shipping_country = $country[0]['value'];
        }
        $email_form_field = $wpdb->get_results("SELECT `id`,`type` FROM `" . $wpdb->prefix . "collect_data_forms` WHERE `type` IN ('email') AND `active` = '1' ORDER BY `order` ASC LIMIT 1", ARRAY_A);
        $email_address = $wpdb->get_results("SELECT * FROM `" . $wpdb->prefix . "submited_form_data` WHERE `log_id`=" . $purchase_log['id'] . " AND `form_id` = '" . $email_form_field[0]['id'] . "' LIMIT 1", ARRAY_A);
        $email = $email_address[0]['value'];
        $previous_download_ids = array(0);
        if ($cart != null && $errorcode == 0) {
            foreach ($cart as $row) {
                $link = "";
                $productsql = "SELECT * FROM `" . $wpdb->prefix . "product_list` WHERE `id`=" . $row['prodid'] . "";
                $product_data = $wpdb->get_results($productsql, ARRAY_A);
                if ($product_data[0]['file'] > 0) {
                    if ($purchase_log['email_sent'] != 1) {
                        $wpdb->query("UPDATE `" . $wpdb->prefix . "download_status` SET `active`='1' WHERE `fileid`='" . $product_data[0]['file'] . "' AND `purchid` = '" . $purchase_log['id'] . "' LIMIT 1");
                    }
                    /*
                    			$digitalsql = "SELECT * FROM `".$wpdb->prefix."cart_contents` WHERE purchaseid=".$purchase_log['id']."";
                    			$digital = $wpdb->get_results($digitalsql,ARRAY_A);
                    			$digitalsql = "SELECT * FROM `".$wpdb->prefix."cart_item_variations` WHERE `cart_id`=".$digital[0]['id']."";
                    			$digital = $wpdb->get_results($digitalsql,ARRAY_A);
                    			$digitalsql = "SELECT * FROM `".$wpdb->prefix."variation_priceandstock` WHERE `variation_id_1`=".$digital[0]['value_id']." AND product_id=".$product_data[0]['id']."";
                    			$digital = $wpdb->get_results($digitalsql,ARRAY_A);*/
                    $downloadable = '1';
                    // 		if ($digital[0]['file'] == '1'){
                    // 			$downloadable='1';
                    // 		}
                    if ($downloadable) {
                        $download_data = $wpdb->get_results("SELECT * FROM `" . $wpdb->prefix . "download_status` WHERE `fileid`='" . $product_data[0]['file'] . "' AND `purchid`='" . $purchase_log['id'] . "' AND `id` NOT IN (" . make_csv($previous_download_ids) . ") LIMIT 1", ARRAY_A);
                        $download_data = $download_data[0];
                        if ($download_data['uniqueid'] == null) {
                            // if the uniqueid is not equal to null, its "valid", regardless of what it is
                            $link = $siteurl . "?downloadid=" . $download_data['id'];
                        } else {
                            $link = $siteurl . "?downloadid=" . $download_data['uniqueid'];
                        }
                        $previous_download_ids[] = $download_data['id'];
                        $order_status = 4;
                    }
                }
                do_action('wpsc_confirm_checkout', $purchase_log['id']);
                $shipping = nzshpcrt_determine_item_shipping($row['prodid'], $row['quantity'], $shipping_country);
                $total_shipping += $shipping;
                if ($product_data[0]['special'] == 1) {
                    $price_modifier = $product_data[0]['special_price'];
                } else {
                    $price_modifier = 0;
                }
                $total += $row['price'] * $row['quantity'];
                $message_price = nzshpcrt_currency_display($row['price'] * $row['quantity'], $product_data[0]['notax'], true);
                $shipping_price = nzshpcrt_currency_display($shipping, 1, true);
                $variation_sql = "SELECT * FROM `" . $wpdb->prefix . "cart_item_variations` WHERE `cart_id`='" . $row['id'] . "'";
                $variation_data = $wpdb->get_results($variation_sql, ARRAY_A);
                $variation_count = count($variation_data);
                if ($variation_count > 1) {
                    $variation_list = " (";
                    if ($purchase['gateway'] != 'testmode') {
                        if ($gateway['internalname'] == $purch_data[0]['gateway']) {
                            $gateway_name = $gateway['name'];
                        }
                    } else {
                        $gateway_name = "Manual Payment";
                    }
                    $i = 0;
                    foreach ($variation_data as $variation) {
                        if ($i > 0) {
                            $variation_list .= ", ";
                        }
                        $value_id = $variation['value_id'];
                        $value_data = $wpdb->get_results("SELECT * FROM `" . $wpdb->prefix . "variation_values` WHERE `id`='" . $value_id . "' LIMIT 1", ARRAY_A);
                        $variation_list .= $value_data[0]['name'];
                        $i++;
                    }
                    $variation_list .= ")";
                } else {
                    if ($variation_count == 1) {
                        $value_id = $variation_data[0]['value_id'];
                        $value_data = $wpdb->get_results("SELECT * FROM `" . $wpdb->prefix . "variation_values` WHERE `id`='" . $value_id . "' LIMIT 1", ARRAY_A);
                        $variation_list = " (" . $value_data[0]['name'] . ")";
                    } else {
                        $variation_list = '';
                    }
                }
                if ($link != '') {
                    $message .= " - " . $product_data[0]['name'] . $variation_list . "  " . $message_price . "  " . TXT_WPSC_CLICKTODOWNLOAD . ": {$link}\n";
                    $message_html .= " - " . $product_data[0]['name'] . $variation_list . "  " . $message_price . "&nbsp;&nbsp;<a href='{$link}'>" . TXT_WPSC_DOWNLOAD . "</a>\n";
                } else {
                    $plural = '';
                    if ($row['quantity'] > 1) {
                        $plural = "s";
                    }
                    $message .= " - " . $row['quantity'] . " " . $product_data[0]['name'] . $variation_list . "  " . $message_price . "\n - " . TXT_WPSC_SHIPPING . ":" . $shipping_price . "\n\r";
                    $message_html .= " - " . $row['quantity'] . " " . $product_data[0]['name'] . $variation_list . "  " . $message_price . "\n - " . TXT_WPSC_SHIPPING . ":" . $shipping_price . "\n\r";
                }
                $report .= " - " . $product_data[0]['name'] . $variation_list . "  " . $message_price . "\n";
            }
            if ($purchase_log['discount_data'] != '') {
                $coupon_data = $wpdb->get_row("SELECT * FROM `" . $wpdb->prefix . "wpsc_coupon_codes` WHERE coupon_code='" . $wpdb->escape($purchase_log['discount_data']) . "' LIMIT 1", ARRAY_A);
                if ($coupon_data['use-once'] == 1) {
                    $wpdb->query("UPDATE `" . $wpdb->prefix . "wpsc_coupon_codes` SET `active`='0', `is-used`='1' WHERE `id`='" . $coupon_data['id'] . "' LIMIT 1");
                }
            }
            //$wpdb->query("UPDATE `".$wpdb->prefix."download_status` SET `active`='1' WHERE `fileid`='".$product_data[0]['file']."' AND `purchid` = '".$purchase_log['id']."' LIMIT 1");
            $total_shipping = nzshpcrt_determine_base_shipping($total_shipping, $shipping_country);
            $total = $total + $total_shipping - $purchase_log['discount_value'];
            // $message.= "\n\r";
            $message .= "Your Purchase No.: " . $purchase_log['id'] . "\n\r";
            if ($purchase_log['discount_value'] > 0) {
                $message .= TXT_WPSC_DISCOUNT . ": " . nzshpcrt_currency_display($purchase_log['discount_value'], 1, true) . "\n\r";
            }
            $message .= TXT_WPSC_TOTALSHIPPING . ": " . nzshpcrt_currency_display($total_shipping, 1, true) . "\n\r";
            $message .= TXT_WPSC_TOTAL . ": " . nzshpcrt_currency_display($total, 1, true) . "\n\r";
            $message_html .= "Your Purchase No.: " . $purchase_log['id'] . "\n\n\r";
            if ($purchase_log['discount_value'] > 0) {
                $message_html .= TXT_WPSC_DISCOUNT . ": " . nzshpcrt_currency_display($purchase_log['discount_value'], 1, true) . "\n\r";
            }
            $message_html .= TXT_WPSC_TOTALSHIPPING . ": " . nzshpcrt_currency_display($total_shipping, 1, true) . "\n\r";
            $message_html .= TXT_WPSC_TOTAL . ": " . nzshpcrt_currency_display($total, 1, true) . "\n\r";
            if (isset($_GET['ti'])) {
                $message .= "\n\r" . TXT_WPSC_YOURTRANSACTIONID . ": " . $_GET['ti'];
                $message_html .= "\n\r" . TXT_WPSC_YOURTRANSACTIONID . ": " . $_GET['ti'];
                $report .= "\n\r" . TXT_WPSC_TRANSACTIONID . ": " . $_GET['ti'];
            } else {
                $report_id = "Purchase No.: " . $purchase_log['id'] . "\n\r";
            }
            if ($email != '' && $purchase_log['email_sent'] != 1) {
                if ($purchase_log['processed'] < 2) {
                    $payment_instructions = strip_tags(get_option('payment_instructions'));
                    $message = TXT_WPSC_ORDER_PENDING . "\n\r" . $payment_instructions . "\n\r" . $message;
                    mail($email, TXT_WPSC_ORDER_PENDING_PAYMENT_REQUIRED, $message, "From: " . get_option('return_email') . "");
                } else {
                    mail($email, TXT_WPSC_PURCHASERECEIPT, $message, "From: " . get_option('return_email') . "");
                }
            }
            $report_user = TXT_WPSC_CUSTOMERDETAILS . "\n\r";
            $form_sql = "SELECT * FROM `" . $wpdb->prefix . "submited_form_data` WHERE `log_id` = '" . $purchase_log['id'] . "'";
            $form_data = $wpdb->get_results($form_sql, ARRAY_A);
            if ($form_data != null) {
                foreach ($form_data as $form_field) {
                    $form_sql = "SELECT * FROM `" . $wpdb->prefix . "collect_data_forms` WHERE `id` = '" . $form_field['form_id'] . "' LIMIT 1";
                    $form_data = $wpdb->get_results($form_sql, ARRAY_A);
                    $form_data = $form_data[0];
                    if ($form_data['type'] == 'country') {
                        $report_user .= $form_data['name'] . ": " . get_country($form_field['value']) . "\n";
                    } else {
                        $report_user .= $form_data['name'] . ": " . $form_field['value'] . "\n";
                    }
                }
            }
            $report_user .= "\n\r";
            $report = $report_user . $report_id . $report;
            if (get_option('purch_log_email') != null && $purchase_log['email_sent'] != 1) {
                mail(get_option('purch_log_email'), TXT_WPSC_PURCHASEREPORT, $report, "From: " . get_option('return_email') . "");
            }
            if ($purchase_log['gateway'] == 'testmode' && $purchase_log['processed'] < 2) {
                echo "<br />" . nl2br(str_replace("\$", '\\$', $message_html));
                return;
            }
            $_SESSION['nzshpcrt_cart'] = '';
            $_SESSION['nzshpcrt_cart'] = array();
            if (true === $echo_to_screen) {
                echo '<div class="wrap">';
                if ($sessionid != null) {
                    echo TXT_WPSC_THETRANSACTIONWASSUCCESSFUL . "<br />";
                    echo "<br />" . nl2br(str_replace("\$", '\\$', $message_html));
                }
                echo '</div>';
            }
        } else {
            if (true === $echo_to_screen) {
                echo '<div class="wrap">';
                echo TXT_WPSC_BUYPRODUCTS;
                echo '</div>';
            }
        }
        if ($purchase_log['email_sent'] != 1 and $sessionid != '') {
            if (preg_match("/^[\\w\\s._,-]+\$/", $transaction_id)) {
                $transact_id_sql = "`transactid` = '" . $transaction_id . "',";
            }
            $update_sql = "UPDATE `" . $wpdb->prefix . "purchase_logs` SET {$transact_id_sql} `date` = '" . time() . "',`email_sent` = '1', `processed` = '{$order_status}' WHERE `sessionid` = " . $sessionid . " LIMIT 1";
            $wpdb->query($update_sql);
        }
    }
}
Exemple #9
0
function nzshpcrt_submit_ajax()
{
    global $wpdb, $user_level, $wp_rewrite;
    get_currentuserinfo();
    if (get_option('permalink_structure') != '') {
        $seperator = "?";
    } else {
        $seperator = "&amp;";
    }
    $cartt = $_SESSION['nzshpcrt_cart'];
    $cartt1 = $cartt[0]->product_id;
    // if is an AJAX request, cruddy code, could be done better but getting approval would be impossible
    if ($_POST['ajax'] == "true" || $_GET['ajax'] == "true") {
        if ($_POST['changetax'] == "true") {
            if (isset($_POST['billing_region'])) {
                $billing_region = $_POST['billing_region'];
            } else {
                $billing_region = $_SESSION['selected_region'];
            }
            $billing_country = $_POST['billing_country'];
            foreach ($cartt as $cart_item) {
                $product_id = $cart_item->product_id;
                $quantity = $cart_item->quantity;
                //echo("<pre>".print_r($cart_item->product_variations,true)."</pre>");
                $product = $wpdb->get_row("SELECT * FROM `" . $wpdb->prefix . "product_list` WHERE `id` = '{$product_id}' LIMIT 1", ARRAY_A);
                if ($product['donation'] == 1) {
                    $price = $quantity * $cart_item->donation_price;
                } else {
                    $price = $quantity * calculate_product_price($product_id, $cart_item->product_variations);
                    if ($product['notax'] != 1) {
                        $tax += nzshpcrt_calculate_tax($price, $billing_country, $billing_region) - $price;
                    }
                    $all_donations = false;
                }
                if ($_SESSION['delivery_country'] != null) {
                    $total_shipping += nzshpcrt_determine_item_shipping($product['id'], $quantity, $_SESSION['delivery_country']);
                }
            }
            echo $tax . ":" . $price . ":" . $total_shipping;
            exit;
        }
        if ($_POST['submittogoogle']) {
            $newvalue = $_POST['value'];
            $amount = $_POST['amount'];
            $reason = $_POST['reason'];
            $comment = $_POST['comment'];
            $message = $_POST['message'];
            $amount = number_format($amount, 2, '.', '');
            $log_data = $wpdb->get_row("SELECT * FROM `" . $wpdb->prefix . "purchase_logs` WHERE `id` = '" . $_POST['id'] . "' LIMIT 1", ARRAY_A);
            if ($newvalue == 2 && function_exists('wpsc_member_activate_subscriptions')) {
                wpsc_member_activate_subscriptions($_POST['id']);
            }
            $google_status = unserialize($log_data['google_status']);
            switch ($newvalue) {
                case "Charge":
                    if ($google_status[0] != 'CANCELLED_BY_GOOGLE') {
                        if ($amount == '') {
                            $google_status['0'] = 'Partially Charged';
                        } else {
                            $google_status['0'] = 'CHARGED';
                            $google_status['partial_charge_amount'] = $amount;
                        }
                    }
                    break;
                case "Cancel":
                    if ($google_status[0] != 'CANCELLED_BY_GOOGLE') {
                        $google_status[0] = 'CANCELLED';
                    }
                    if ($google_status[1] != 'DELIVERED') {
                        $google_status[1] = 'WILL_NOT_DELIVER';
                    }
                    break;
                case "Refund":
                    if ($amount == '') {
                        $google_status['0'] = 'Partially Refund';
                    } else {
                        $google_status['0'] = 'REFUND';
                        $google_status['partial_refund_amount'] = $amount;
                    }
                    break;
                case "Ship":
                    if ($google_status[1] != 'WILL_NOT_DELIVER') {
                        $google_status[1] = 'DELIVERED';
                    }
                    break;
                case "Archive":
                    $google_status[1] = 'ARCHIVED';
                    break;
            }
            $google_status_sql = "UPDATE `" . $wpdb->prefix . "purchase_logs` SET google_status='" . serialize($google_status) . "' WHERE `id` = '" . $_POST['id'] . "' LIMIT 1";
            $wpdb->query($google_status_sql);
            $merchant_id = get_option('google_id');
            $merchant_key = get_option('google_key');
            $server_type = get_option('google_server_type');
            $currency = get_option('google_cur');
            $Grequest = new GoogleRequest($merchant_id, $merchant_key, $server_type, $currency);
            $google_order_number = $wpdb->get_var("SELECT google_order_number FROM `" . $wpdb->prefix . "purchase_logs` WHERE `id` = '" . $_POST['id'] . "' LIMIT 1");
            switch ($newvalue) {
                case 'Charge':
                    $Grequest->SendChargeOrder($google_order_number, $amount);
                    break;
                case 'Ship':
                    $Grequest->SendDeliverOrder($google_order_number);
                    break;
                case 'Archive':
                    $Grequest->SendArchiveOrder($google_order_number);
                    break;
                case 'Refund':
                    $Grequest->SendRefundOrder($google_order_number, $amount, $reason);
                    break;
                case 'Cancel':
                    $Grequest->SendCancelOrder($google_order_number, $reason, $comment);
                    break;
                case 'Send Message':
                    $Grequest->SendBuyerMessage($google_order_number, $message);
                    break;
            }
            $newvalue++;
            $update_sql = "UPDATE `" . $wpdb->prefix . "purchase_logs` SET `processed` = '" . $newvalue . "' WHERE `id` = '" . $_POST['id'] . "' LIMIT 1";
            //$wpdb->query($update_sql);
            exit;
        }
        ////changes for usps
        if ($_POST['uspsswitch']) {
            foreach ($_SESSION['uspsQuote'] as $quotes) {
                $total = $_POST['total'];
                if ($quotes[$_POST['key']] != '') {
                    echo nzshpcrt_currency_display($total + $quotes[$_POST['key']], 1);
                    echo "<input type='hidden' value='" . $total . "' id='shopping_cart_total_price'>";
                    $_SESSION['usps_shipping'] = $quotes[$_POST['key']];
                }
            }
            exit;
        }
        //changes for usps ends
        if ($_GET['user'] == "true" && is_numeric($_POST['prodid'])) {
            $memberstatus = get_product_meta($_POST['prodid'], 'is_membership', true);
            if ($memberstatus[0] == '1' && $_SESSION['nzshopcrt_cart'] != NULL) {
            } else {
                $sql = "SELECT * FROM `" . $wpdb->prefix . "product_list` WHERE `id`='" . $_POST['prodid'] . "' LIMIT 1";
                $item_data = $wpdb->get_results($sql, ARRAY_A);
                $item_quantity = 0;
                if ($_SESSION['nzshpcrt_cart'] != null) {
                    foreach ($_SESSION['nzshpcrt_cart'] as $cart_key => $cart_item) {
                        if ($memberstatus[0] != '1' && $_SESSION['nzshpcrt_cart'] != NULL) {
                            if ($cart_item->product_id == $_POST['prodid']) {
                                if ($_SESSION['nzshpcrt_cart'][$cart_key]->product_variations === $_POST['variation'] && $_SESSION['nzshpcrt_cart'][$cart_key]->extras === $_POST['extras']) {
                                    $item_quantity += $_SESSION['nzshpcrt_cart'][$cart_key]->quantity;
                                    $item_variations = $_SESSION['nzshpcrt_cart'][$cart_key]->product_variations;
                                }
                            }
                        }
                    }
                }
                $item_stock = null;
                $variation_count = count($_POST['variation']);
                if ($variation_count >= 1 && $variation_count <= 2) {
                    foreach ($_POST['variation'] as $variation_id) {
                        if (is_numeric($variation_id)) {
                            $variation_ids[] = (int) $variation_id;
                        }
                    }
                    if (count($variation_ids) == 2) {
                        $variation_stock_data = $wpdb->get_row("SELECT * FROM `" . $wpdb->prefix . "variation_priceandstock` WHERE `product_id` = '" . $_POST['prodid'] . "' AND (`variation_id_1` = '" . $variation_ids[0] . "' AND `variation_id_2` = '" . $variation_ids[1] . "') OR (`variation_id_1` = '" . $variation_ids[1] . "' AND `variation_id_2` = '" . $variation_ids[0] . "') LIMIT 1", ARRAY_A);
                        $item_stock = $variation_stock_data['stock'];
                    } else {
                        if (count($variation_ids) == 1) {
                            $variation_stock_data = $wpdb->get_row("SELECT * FROM `" . $wpdb->prefix . "variation_priceandstock` WHERE `product_id` = '" . $_POST['prodid'] . "' AND (`variation_id_1` = '" . $variation_ids[0] . "' AND `variation_id_2` = '0') LIMIT 1", ARRAY_A);
                            $item_stock = $variation_stock_data['stock'];
                        }
                    }
                }
                if ($item_stock === null) {
                    $item_stock = $item_data[0]['quantity'];
                }
                if ($item_data[0]['quantity_limited'] == 1 && $item_stock > 0 && $item_stock > $item_quantity || $item_data[0]['quantity_limited'] == 0) {
                    $cartcount = count($_SESSION['nzshpcrt_cart']);
                    if (is_array($_POST['variation'])) {
                        $variations = $_POST['variation'];
                    } else {
                        $variations = null;
                    }
                    if (is_array($_POST['extras'])) {
                        $extras = $_POST['extras'];
                    } else {
                        $extras = null;
                    }
                    $updated_quantity = false;
                    if ($_SESSION['nzshpcrt_cart'] != null) {
                        foreach ($_SESSION['nzshpcrt_cart'] as $cart_key => $cart_item) {
                            if (!($memberstatus[0] == '1') && count($_SESSION['nzshpcrt_cart']) > 0) {
                                if ((int) $cart_item->product_id === (int) $_POST['prodid']) {
                                    // force both to integer before testing for identicality
                                    if ($_SESSION['nzshpcrt_cart'][$cart_key]->extras === $extras && $_SESSION['nzshpcrt_cart'][$cart_key]->product_variations === $variations && (int) $_SESSION['nzshpcrt_cart'][$cart_key]->donation_price == (int) $_POST['donation_price']) {
                                        if (is_numeric($_POST['quantity'])) {
                                            $_SESSION['nzshpcrt_cart'][$cart_key]->quantity += (int) $_POST['quantity'];
                                        } else {
                                            $_SESSION['nzshpcrt_cart'][$cart_key]->quantity++;
                                        }
                                        $updated_quantity = true;
                                    }
                                }
                            }
                        }
                    }
                    if ($item_data[0]['donation'] == 1) {
                        $donation = $_POST['donation_price'];
                    } else {
                        $donation = false;
                    }
                    if (!($memberstatus[0] == '1' && count($_SESSION['nzshpcrt_cart']) > 0)) {
                        $status = get_product_meta($cartt1, 'is_membership', true);
                        if ($status[0] == '1') {
                            exit;
                        }
                        if ($updated_quantity === false) {
                            if (is_numeric($_POST['quantity'])) {
                                if ($_POST['quantity'] > 0) {
                                    $new_cart_item = new cart_item($_POST['prodid'], $variations, $_POST['quantity'], $donation, $extras);
                                }
                            } else {
                                //echo "correct";
                                $new_cart_item = new cart_item($_POST['prodid'], $variations, 1, $donation, $extras);
                            }
                            $_SESSION['nzshpcrt_cart'][] = $new_cart_item;
                        }
                    }
                } else {
                    $quantity_limit = true;
                }
                $cart = $_SESSION['nzshpcrt_cart'];
                if ($memberstatus[0] == '1' && count($cart) > 1) {
                } else {
                    $status = get_product_meta($cartt1, 'is_membership', true);
                    if ($status[0] == '1') {
                        exit('st');
                    }
                    echo "if(document.getElementById('shoppingcartcontents') != null)\n\t\t\t\t\t  {\n\t\t\t\t\t  document.getElementById('shoppingcartcontents').innerHTML = \"" . str_replace(array("\n", "\r"), "", addslashes(nzshpcrt_shopping_basket_internals($cart, $quantity_limit))) . "\";\n\t\t\t\t\t  }\n\t\t\t\t\t";
                    if ($_POST['prodid'] != null && get_option('fancy_notifications') == 1) {
                        echo "if(document.getElementById('fancy_notification_content') != null)\n\t\t\t\t\t  {\n\t\t\t\t\t  document.getElementById('fancy_notification_content').innerHTML = \"" . str_replace(array("\n", "\r"), "", addslashes(fancy_notification_content($_POST['prodid'], $quantity_limit))) . "\";\n\t\t\t\t\t  jQuery('#loading_animation').css('display', 'none');\n\t\t\t\t\t  jQuery('#fancy_notification_content').css('display', 'block');  \n\t\t\t\t\t  }\n\t\t\t\t\t";
                    }
                    if ($_SESSION['slider_state'] == 0) {
                        echo 'jQuery("#sliding_cart").css({ display: "none"});' . "\n\r";
                    } else {
                        echo 'jQuery("#sliding_cart").css({ display: "block"});' . "\n\r";
                    }
                }
            }
            exit;
        } else {
            if ($_POST['user'] == "true" && $_POST['emptycart'] == "true") {
                //exit("/* \n\r ".get_option('shopping_cart_url')." \n\r ".print_r($_POST,true)." \n\r */");
                $_SESSION['nzshpcrt_cart'] = '';
                $_SESSION['nzshpcrt_cart'] = array();
                echo "if(document.getElementById('shoppingcartcontents') != null) {   \n\t\t\tdocument.getElementById('shoppingcartcontents').innerHTML = \"" . str_replace(array("\n", "\r"), "", addslashes(nzshpcrt_shopping_basket_internals($cart))) . "\";\n\t\t\t}\n\r";
                if ($_POST['current_page'] == get_option('shopping_cart_url')) {
                    echo "window.location = '" . get_option('shopping_cart_url') . "';\n\r";
                    // if we are on the checkout page, redirect back to it to clear the non-ajax cart too
                }
                exit;
            }
        }
        if ($_POST['store_list'] == "true") {
            $map_data['address'] = $_POST['addr'];
            $map_data['city'] = $_POST['city'];
            $map_data['country'] = 'US';
            $map_data['zipcode'] = '';
            $map_data['radius'] = '50000';
            $map_data['state'] = '';
            $map_data['submit'] = 'Find Store';
            $stores = getdistance($map_data);
            $i = 0;
            while ($rows = mysql_fetch_array($stores)) {
                //echo "<pre>".print_r($rows,1)."</pre>";
                if ($i == 0) {
                    $closest_store = $rows[5];
                }
                $i++;
                $store_list[$i] = $rows[5];
            }
            foreach ($store_list as $store) {
                $output .= "<option value='{$store}'>{$store}</option>";
            }
            echo $output;
            exit;
        }
        if ($_POST['admin'] == "true") {
            if (is_numeric($_POST['prodid'])) {
                /* fill product form */
                echo nzshpcrt_getproductform($_POST['prodid']);
                exit;
            } else {
                if (is_numeric($_POST['catid'])) {
                    /* fill category form */
                    echo nzshpcrt_getcategoryform($_POST['catid']);
                    exit;
                } else {
                    if (is_numeric($_POST['brandid'])) {
                        /* fill brand form */
                        echo nzshpcrt_getbrandsform($_POST['brandid']);
                        exit;
                    } else {
                        if (is_numeric($_POST['variation_id'])) {
                            echo nzshpcrt_getvariationform($_POST['variation_id']);
                            exit;
                        }
                    }
                }
            }
            if ($_POST['hide_ecom_dashboard'] == 'true') {
                require_once ABSPATH . WPINC . '/rss.php';
                $rss = fetch_rss('http://www.instinct.co.nz/feed/');
                $rss->items = array_slice($rss->items, 0, 5);
                $rss_hash = sha1(serialize($rss->items));
                update_option('wpsc_ecom_news_hash', $rss_hash);
                exit(1);
            }
            if ($_POST['remove_meta'] == 'true' && is_numeric($_POST['meta_id'])) {
                $meta_id = (int) $_POST['meta_id'];
                $selected_meta = $wpdb->get_row("SELECT * FROM `{$wpdb->prefix}wpsc_productmeta` WHERE `id` IN('{$meta_id}') ", ARRAY_A);
                if ($selected_meta != null) {
                    if ($wpdb->query("DELETE FROM `{$wpdb->prefix}wpsc_productmeta` WHERE `id` IN('{$meta_id}')  LIMIT 1")) {
                        echo $meta_id;
                        exit;
                    }
                }
                echo 0;
                exit;
            }
            exit;
        }
        if (is_numeric($_POST['currencyid'])) {
            $currency_data = $wpdb->get_results("SELECT `symbol`,`symbol_html`,`code` FROM `" . $wpdb->prefix . "currency_list` WHERE `id`='" . $_POST['currencyid'] . "' LIMIT 1", ARRAY_A);
            $price_out = null;
            if ($currency_data[0]['symbol'] != '') {
                $currency_sign = $currency_data[0]['symbol_html'];
            } else {
                $currency_sign = $currency_data[0]['code'];
            }
            echo $currency_sign;
            exit;
        }
        //echo "--==->";
        if ($_POST['buynow'] == "true") {
            $id = $_REQUEST['product_id'];
            $price = $_REQUEST['price'];
            $downloads = get_option('max_downloads');
            $product_sql = "SELECT * FROM " . $wpdb->prefix . "product_list WHERE id = " . $id . " LIMIT 1";
            $product_info = $wpdb->get_results($product_sql, ARRAY_A);
            $product_info = $product_info[0];
            $sessionid = mt_rand(100, 999) . time();
            $sql = "INSERT INTO `" . $wpdb->prefix . "purchase_logs` ( `totalprice` , `sessionid` , `date`, `billing_country`, `shipping_country`,`shipping_region`, `user_ID`, `discount_value` ) VALUES ( '" . $price . "', '" . $sessionid . "', '" . time() . "', 'BuyNow', 'BuyNow', 'BuyNow' , NULL , 0)";
            $wpdb->query($sql);
            $log_id = $wpdb->get_var("SELECT `id` FROM `" . $wpdb->prefix . "purchase_logs` WHERE `sessionid` IN('" . $sessionid . "') LIMIT 1");
            $cartsql = "INSERT INTO `" . $wpdb->prefix . "cart_contents` ( `prodid` , `purchaseid`, `price`, `pnp`, `gst`, `quantity`, `donation`, `no_shipping` ) VALUES ('" . $id . "', '" . $log_id . "','" . $price . "','0', '0','1', '" . $donation . "', '1')";
            $wpdb->query($cartsql);
            $wpdb->query("INSERT INTO `" . $wpdb->prefix . "download_status` ( `fileid` , `purchid` , `downloads` , `active` , `datetime` ) VALUES ( '" . $product_info['file'] . "', '" . $log_id . "', '{$downloads}', '0', NOW( ));");
            exit;
        }
        if ($_POST['changeorder'] == "true" && is_numeric($_POST['category_id'])) {
            $category_id = (int) $_POST['category_id'];
            $hash = $_POST['sort1'];
            $order = 1;
            foreach ($hash as $id) {
                $wpdb->query("UPDATE `" . $wpdb->prefix . "product_order` SET `order`={$order} WHERE `product_id`=" . (int) $id . " AND `category_id`=" . (int) $category_id . " LIMIT 1");
                $order++;
            }
            exit(" ");
        }
        /* rate item */
        if ($_POST['rate_item'] == "true" && is_numeric($_POST['product_id']) && is_numeric($_POST['rating'])) {
            $nowtime = time();
            $prodid = $_POST['product_id'];
            $ip_number = $_SERVER['REMOTE_ADDR'];
            $rating = $_POST['rating'];
            $cookie_data = explode(",", $_COOKIE['voting_cookie'][$prodid]);
            if (is_numeric($cookie_data[0]) && $cookie_data[0] > 0) {
                $vote_id = $cookie_data[0];
                $wpdb->query("UPDATE `" . $wpdb->prefix . "product_rating` SET `rated` = '" . $rating . "' WHERE `id` ='" . $vote_id . "' LIMIT 1 ;");
            } else {
                $insert_sql = "INSERT INTO `" . $wpdb->prefix . "product_rating` ( `ipnum`  , `productid` , `rated`, `time`) VALUES ( '" . $ip_number . "', '" . $prodid . "', '" . $rating . "', '" . $nowtime . "');";
                $wpdb->query($insert_sql);
                $data = $wpdb->get_results("SELECT `id`,`rated` FROM `" . $wpdb->prefix . "product_rating` WHERE `ipnum`='" . $ip_number . "' AND `productid` = '" . $prodid . "'  AND `rated` = '" . $rating . "' AND `time` = '" . $nowtime . "' ORDER BY `id` DESC LIMIT 1", ARRAY_A);
                $vote_id = $data[0]['id'];
                setcookie("voting_cookie[{$prodid}]", $vote_id . "," . $rating, time() + 60 * 60 * 24 * 360);
            }
            $output[1] = $prodid;
            $output[2] = $rating;
            echo $output[1] . "," . $output[2];
            exit;
        }
        //written by allen
        if ($_REQUEST['save_tracking_id'] == "true") {
            $id = $_POST['id'];
            $value = $_POST['value'];
            $update_sql = "UPDATE " . $wpdb->prefix . "purchase_logs SET track_id = '" . $value . "' WHERE id={$id}";
            $wpdb->query($update_sql);
            exit;
        }
        if ($_POST['get_rating_count'] == "true" && is_numeric($_POST['product_id'])) {
            $prodid = $_POST['product_id'];
            $data = $wpdb->get_results("SELECT COUNT(*) AS `count` FROM `" . $wpdb->prefix . "product_rating` WHERE `productid` = '" . $prodid . "'", ARRAY_A);
            echo $data[0]['count'] . "," . $prodid;
            exit;
        }
        /// Pointless AJAX call is pointless
        // 	if(isset($_POST['changeperpage'])) {
        // 		$item_per_page = $_POST['changeperpage'];
        // 		echo $item_per_page;
        // 		exit();
        // 	}
        if ($_POST['remove_variation_value'] == "true" && is_numeric($_POST['variation_value_id'])) {
            $wpdb->query("DELETE FROM `" . $wpdb->prefix . "variation_values_associations` WHERE `value_id` = '" . $_POST['variation_value_id'] . "'");
            $wpdb->query("DELETE FROM `" . $wpdb->prefix . "variation_values` WHERE `id` = '" . $_POST['variation_value_id'] . "' LIMIT 1");
            exit;
        }
        if ($_POST['get_updated_price'] == "true" && is_numeric($_POST['product_id'])) {
            $notax = $wpdb->get_var("SELECT `notax` FROM `" . $wpdb->prefix . "product_list` WHERE `id` IN('" . $_POST['product_id'] . "') LIMIT 1");
            foreach ((array) $_POST['variation'] as $variation) {
                if (is_numeric($variation)) {
                    $variations[] = $variation;
                }
            }
            foreach ((array) $_POST['extra'] as $extra) {
                if (is_numeric($extra)) {
                    $extras[] = $extra;
                }
            }
            $pm = $_POST['pm'];
            echo "product_id=" . $_POST['product_id'] . ";\n";
            echo "price=\"" . nzshpcrt_currency_display(calculate_product_price($_POST['product_id'], $variations, 'stay', $extras), $notax) . "\";\n";
            //exit(print_r($extras,1));
            exit;
        }
        if ($_REQUEST['log_state'] == "true" && is_numeric($_POST['id']) && is_numeric($_POST['value'])) {
            $newvalue = $_POST['value'];
            if ($_REQUEST['suspend'] == 'true') {
                if ($_REQUEST['value'] == 1) {
                    wpsc_member_dedeactivate_subscriptions($_POST['id']);
                } else {
                    wpsc_member_deactivate_subscriptions($_POST['id']);
                }
                exit;
            } else {
                $log_data = $wpdb->get_row("SELECT * FROM `" . $wpdb->prefix . "purchase_logs` WHERE `id` = '" . $_POST['id'] . "' LIMIT 1", ARRAY_A);
                if ($newvalue == 2 && function_exists('wpsc_member_activate_subscriptions')) {
                    wpsc_member_activate_subscriptions($_POST['id']);
                }
                $update_sql = "UPDATE `" . $wpdb->prefix . "purchase_logs` SET `processed` = '" . $newvalue . "' WHERE `id` = '" . $_POST['id'] . "' LIMIT 1";
                $wpdb->query($update_sql);
                //echo("/*");
                if ($newvalue > $log_data['processed'] && $log_data['processed'] < 2) {
                    transaction_results($log_data['sessionid'], false);
                }
                //echo("*/");
                $stage_sql = "SELECT * FROM `" . $wpdb->prefix . "purchase_statuses` WHERE `id`='" . $newvalue . "' AND `active`='1' LIMIT 1";
                $stage_data = $wpdb->get_row($stage_sql, ARRAY_A);
                echo "document.getElementById(\"form_group_" . $_POST['id'] . "_text\").innerHTML = '" . $stage_data['name'] . "';\n";
                echo "document.getElementById(\"form_group_" . $_POST['id'] . "_text\").style.color = '#" . $stage_data['colour'] . "';\n";
                $year = date("Y");
                $month = date("m");
                $start_timestamp = mktime(0, 0, 0, $month, 1, $year);
                $end_timestamp = mktime(0, 0, 0, $month + 1, 0, $year);
                echo "document.getElementById(\"log_total_month\").innerHTML = '" . addslashes(nzshpcrt_currency_display(admin_display_total_price($start_timestamp, $end_timestamp), 1)) . "';\n";
                echo "document.getElementById(\"log_total_absolute\").innerHTML = '" . addslashes(nzshpcrt_currency_display(admin_display_total_price(), 1)) . "';\n";
                exit;
            }
        }
        if ($_POST['list_variation_values'] == "true" && is_numeric($_POST['new_variation_id'])) {
            $variation_processor = new nzshpcrt_variations();
            echo "variation_value_id = \"" . $_POST['new_variation_id'] . "\";\n";
            echo "variation_value_html = \"" . $variation_processor->display_variation_values($_POST['prefix'], $_POST['new_variation_id']) . "\";\n";
            $variations_selected = array_values(array_unique(array_merge((array) $_POST['new_variation_id'], (array) $_POST['variation_id'])));
            echo "variation_subvalue_html = \"" . str_replace("\n\r", '\\n\\r', $variation_processor->variations_add_grid_view((array) $variations_selected)) . "\";\n";
            //echo "/*\n\r".print_r(array_values(array_unique(array_merge((array)$_POST['new_variation_id'], $_POST['variation_id']))),true)."\n\r*/";
            exit;
        }
        if ($_POST['redisplay_variation_values'] == "true") {
            $variation_processor = new nzshpcrt_variations();
            $variations_selected = array_values(array_unique(array_merge((array) $_POST['new_variation_id'], (array) $_POST['variation_id'])));
            foreach ($variations_selected as $variation_id) {
                // cast everything to integer to make sure nothing nasty gets in.
                $variation_list[] = (int) $variation_id;
            }
            echo $variation_processor->variations_add_grid_view((array) $variation_list);
            //echo "/*\n\r".print_r(array_values(array_unique($_POST['variation_id'])),true)."\n\r*/";
            exit;
        }
        if ($_POST['edit_variation_value_list'] == 'true' && is_numeric($_POST['variation_id']) && is_numeric($_POST['product_id'])) {
            $variation_id = (int) $_POST['variation_id'];
            $product_id = (int) $_POST['product_id'];
            $variations_processor = new nzshpcrt_variations();
            $variation_values = $variations_processor->falsepost_variation_values($variation_id);
            if (is_array($variation_values)) {
                //echo(print_r($variation_values,true));
                $check_variation_added = $wpdb->get_var("SELECT `id` FROM `" . $wpdb->prefix . "variation_associations` WHERE `type` IN ('product') AND `associated_id` IN ('{$product_id}') AND `variation_id` IN ('{$variation_id}') LIMIT 1");
                if ($check_variation_added == null) {
                    $variations_processor->add_to_existing_product($product_id, $variation_values);
                }
                echo $variations_processor->display_attached_variations($product_id);
                echo $variations_processor->variations_grid_view($product_id);
            } else {
                echo "false";
            }
            exit;
        }
        if ($_POST['remove_form_field'] == "true" && is_numeric($_POST['form_id'])) {
            //exit(print_r($user,true));
            if (current_user_can('level_7')) {
                $wpdb->query("UPDATE `" . $wpdb->prefix . "collect_data_forms` SET `active` = '0' WHERE `id` ='" . $_POST['form_id'] . "' LIMIT 1 ;");
                exit(' ');
            }
        }
        /*
         * function for handling the checkout billing address
         */
        if (preg_match("/[a-zA-Z]{2,4}/", $_POST['billing_country'])) {
            if ($_SESSION['selected_country'] == $_POST['billing_country']) {
                $do_not_refresh_regions = true;
            } else {
                $do_not_refresh_regions = false;
                $_SESSION['selected_country'] = $_POST['billing_country'];
            }
            if (is_numeric($_POST['form_id'])) {
                $form_id = $_POST['form_id'];
                $html_form_id = "region_country_form_{$form_id}";
            } else {
                $html_form_id = 'region_country_form';
            }
            if (is_numeric($_POST['billing_region'])) {
                $_SESSION['selected_region'] = $_POST['billing_region'];
            }
            $cart =& $_SESSION['nzshpcrt_cart'];
            if ($memberstatus[0] == '1' && count($cart) > 0) {
                echo "\n\t\t\t";
            } else {
                if ($status[0] == '1') {
                    exit;
                }
                echo "if(document.getElementById('shoppingcartcontents') != null)\n\t\t\t\t\t  {\n\t\t\t\t\t  document.getElementById('shoppingcartcontents').innerHTML = \"" . str_replace(array("\n", "\r"), "", addslashes(nzshpcrt_shopping_basket_internals($cart, $quantity_limit))) . "\";\n\t\t\t\t\t  }\n\t\t\t\t\t";
                if ($do_not_refresh_regions == false) {
                    $region_list = $wpdb->get_results("SELECT `" . $wpdb->prefix . "region_tax`.* FROM `" . $wpdb->prefix . "region_tax`, `" . $wpdb->prefix . "currency_list`  WHERE `" . $wpdb->prefix . "currency_list`.`isocode` IN('" . $_POST['billing_country'] . "') AND `" . $wpdb->prefix . "currency_list`.`id` = `" . $wpdb->prefix . "region_tax`.`country_id`", ARRAY_A);
                    if ($region_list != null) {
                        $output .= "<select name='collected_data[" . $form_id . "][1]' class='current_region' onchange='set_billing_country(\\\"{$html_form_id}\\\", \\\"{$form_id}\\\");'>";
                        //$output .= "<option value=''>None</option>";
                        foreach ($region_list as $region) {
                            if ($_SESSION['selected_region'] == $region['id']) {
                                $selected = "selected='true'";
                            } else {
                                $selected = "";
                            }
                            $output .= "<option value='" . $region['id'] . "' {$selected}>" . $region['name'] . "</option>";
                        }
                        $output .= "</select>";
                        echo "if(document.getElementById('region_select_{$form_id}') != null)\n\t\t  {\n\t\t  document.getElementById('region_select_{$form_id}').innerHTML = \"" . $output . "\";\n\t\t  }\n\t\t";
                    } else {
                        echo "if(document.getElementById('region_select_{$form_id}') != null)\n\t\t  {\n\t\t  document.getElementById('region_select_{$form_id}').innerHTML = \"\";\n\t\t  }\n\t\t";
                    }
                }
            }
            exit;
        }
        if ($_POST['get_country_tax'] == "true" && preg_match("/[a-zA-Z]{2,4}/", $_POST['country_id'])) {
            $country_id = $_POST['country_id'];
            $region_list = $wpdb->get_results("SELECT `" . $wpdb->prefix . "region_tax`.* FROM `" . $wpdb->prefix . "region_tax`, `" . $wpdb->prefix . "currency_list`  WHERE `" . $wpdb->prefix . "currency_list`.`isocode` IN('" . $country_id . "') AND `" . $wpdb->prefix . "currency_list`.`id` = `" . $wpdb->prefix . "region_tax`.`country_id`", ARRAY_A);
            if ($region_list != null) {
                echo "<select name='base_region'>\n\r";
                foreach ($region_list as $region) {
                    if (get_option('base_region') == $region['id']) {
                        $selected = "selected='true'";
                    } else {
                        $selected = "";
                    }
                    echo "<option value='" . $region['id'] . "' {$selected}>" . $region['name'] . "</option>\n\r";
                }
                echo "</select>\n\r";
            } else {
                echo "&nbsp;";
            }
            exit;
        }
        /* fill product form */
        if ($_POST['set_slider'] == "true" && is_numeric($_POST['state'])) {
            $_SESSION['slider_state'] = $_POST['state'];
            exit;
        }
        /* fill category form */
        if ($_GET['action'] == "register") {
            $siteurl = get_option('siteurl');
            require_once ABSPATH . WPINC . '/registration-functions.php';
            if ($_POST['action'] == 'register' && get_settings('users_can_register')) {
                //exit("fail for testing purposes");
                $user_login = sanitize_user($_POST['user_login']);
                $user_email = $_POST['user_email'];
                $errors = array();
                if ($user_login == '') {
                    exit($errors['user_login'] = __('<strong>ERROR</strong>: Please enter a username.'));
                }
                /* checking e-mail address */
                if ($user_email == '') {
                    exit(__('<strong>ERROR</strong>: Please type your e-mail address.'));
                } else {
                    if (!is_email($user_email)) {
                        exit(__('<strong>ERROR</strong>: The email address isn&#8217;t correct.'));
                        $user_email = '';
                    }
                }
                if (!validate_username($user_login)) {
                    $errors['user_login'] = __('<strong>ERROR</strong>: This username is invalid.  Please enter a valid username.');
                    $user_login = '';
                }
                if (username_exists($user_login)) {
                    exit(__('<strong>ERROR</strong>: This username is already registered, please choose another one.'));
                }
                /* checking the email isn't already used by another user */
                $email_exists = $wpdb->get_row("SELECT user_email FROM {$wpdb->users} WHERE user_email = '{$user_email}'");
                if ($email_exists) {
                    die(__('<strong>ERROR</strong>: This email address is already registered, please supply another.'));
                }
                if (0 == count($errors)) {
                    $password = substr(md5(uniqid(microtime())), 0, 7);
                    //xit('there?');
                    $user_id = wp_create_user($user_login, $password, $user_email);
                    if (!$user_id) {
                        exit(sprintf(__('<strong>ERROR</strong>: Couldn&#8217;t register you... please contact the <a href="mailto:%s">webmaster</a> !'), get_settings('admin_email')));
                    } else {
                        wp_new_user_notification($user_id, $password);
                        ?>
<div id="login"> 
  <h2><?php 
                        _e('Registration Complete');
                        ?>
</h2>
  <p><?php 
                        printf(__('Username: %s'), "<strong>" . wp_specialchars($user_login) . "</strong>");
                        ?>
<br />
  <?php 
                        printf(__('Password: %s'), '<strong>' . __('emailed to you') . '</strong>');
                        ?>
 <br />
  <?php 
                        printf(__('E-mail: %s'), "<strong>" . wp_specialchars($user_email) . "</strong>");
                        ?>
</p>
</div>
<?php 
                    }
                }
            } else {
                // onsubmit='submit_register_form(this);return false;'
                echo "<div id='login'>\n    <h2>Register for this blog</h2>\n    <form id='registerform' action='index.php?ajax=true&amp;action=register'  onsubmit='submit_register_form(this);return false;' method='post'>\n      <p><input type='hidden' value='register' name='action'/>\n      <label for='user_login'>Username:</label><br/> <input type='text' value='' maxlength='20' size='20' id='user_login' name='user_login'/><br/></p>\n      <p><label for='user_email'>E-mail:</label><br/> <input type='text' value='' maxlength='100' size='25' id='user_email' name='user_email'/></p>\n      <p>A password will be emailed to you.</p>\n      <p class='submit'><input type='submit' name='submit_form' id='submit' value='Register »'/><img id='register_loading_img' src='" . WPSC_URL . "/images/loading.gif' alt='' title=''></p>\n      \n    </form>\n    </div>";
            }
            exit;
        }
    }
    /*
    * AJAX stuff stops here, I would put an exit here, but it may screw up other plugins
    //exit();
    */
}
function nzshpcrt_find_total_price($purchase_id, $country_code)
{
    global $wpdb;
    $endtotal = '';
    if (is_numeric($purchase_id)) {
        $purch_sql = "SELECT * FROM `" . $wpdb->prefix . "purchase_logs` WHERE `id`='" . $purchase_id . "'";
        $purch_data = $wpdb->get_results($purch_sql, ARRAY_A);
        $cartsql = "SELECT * FROM `" . $wpdb->prefix . "cart_contents` WHERE `purchaseid`=" . $purchase_id . "";
        $cart_log = $wpdb->get_results($cartsql, ARRAY_A);
        if ($cart_log != null) {
            foreach ($cart_log as $cart_row) {
                $productsql = "SELECT * FROM `" . $wpdb->prefix . "product_list` WHERE `id`=" . $cart_row['prodid'] . "";
                $product_data = $wpdb->get_results($productsql, ARRAY_A);
                $variation_sql = "SELECT * FROM `" . $wpdb->prefix . "cart_item_variations` WHERE `cart_id`='" . $cart_row['id'] . "'";
                $variation_data = $wpdb->get_results($variation_sql, ARRAY_A);
                $variation_count = count($variation_data);
                $price = $cart_row['price'] * $cart_row['quantity'];
                if (isset($purch_data['shipping_country']) && $purch_data['shipping_country'] != '') {
                    $country_code = $purch_data['shipping_country'];
                }
                $shipping = nzshpcrt_determine_item_shipping($cart_row['prodid'], $cart_row['quantity'], $country_code);
                $endtotal = $shipping + $price;
            }
            $endtotal += nzshpcrt_determine_base_shipping(0, $country_code);
        }
        return $endtotal;
    }
}
Exemple #11
0
     if ($product_list['donation'] == 1) {
         $price = $quantity * $cart_item->donation_price;
     } else {
         $price = $quantity * calculate_product_price($product_id, $cart_item->product_variations, 'stay', $extras);
         if ($product_list['notax'] != 1) {
             $tax += nzshpcrt_calculate_tax($price, $_SESSION['selected_country'], $_SESSION['selected_region']) - $price;
         }
         $all_donations = false;
     }
     if ($product_list['no_shipping'] != 1) {
         $all_no_shipping = false;
     }
     echo nzshpcrt_currency_display($price, $product_list['notax']);
     $total += $price;
     echo "  </td>\n\r";
     $shipping = nzshpcrt_determine_item_shipping($product_id, $number, $_SESSION['delivery_country']);
     $total_shipping += $shipping;
     echo "  <td>\n\r";
     echo "<a href='" . get_option('shopping_cart_url') . $seperator . "remove=" . $key . "'>Remove</a>";
     echo "  </td>\n\r";
     echo "</tr>\n\r";
 }
 $siteurl = get_option('siteurl');
 if ($all_donations == false && $all_no_shipping == false) {
     $total_shipping = nzshpcrt_determine_base_shipping($total_shipping, $_SESSION['delivery_country']);
     $total += $total_shipping;
 }
 //Written by allen
 $status = get_product_meta($cart[0]->product_id, 'is_membership', true);
 $coupon_info = $wpdb->get_results('SELECT * FROM ' . $wpdb->prefix . 'wpsc_coupon_codes WHERE active="1"', ARRAY_A);
 if ($status[0] == '1' || count($coupon_info) < 1) {
function nzshpcrt_shopping_basket_internals($cart, $quantity_limit = false, $no_title = false)
{
    global $wpdb;
    if (get_option('permalink_structure') != '') {
        $seperator = "?";
    } else {
        $seperator = "&amp;";
    }
    if (get_option('show_sliding_cart') == 1) {
        if (is_numeric($_SESSION['slider_state'])) {
            if ($_SESSION['slider_state'] == 0) {
                $collapser_image = 'plus.png';
            } else {
                $collapser_image = 'minus.png';
            }
            $fancy_collapser = "<a href='#' onclick='return shopping_cart_collapser()' id='fancy_collapser_link'><img src='" . WPSC_URL . "/images/{$collapser_image}' title='' alt='' id='fancy_collapser' /></a>";
        } else {
            if ($_SESSION['nzshpcrt_cart'] == null) {
                $collapser_image = 'plus.png';
            } else {
                $collapser_image = 'minus.png';
            }
            $fancy_collapser = "<a href='#' onclick='return shopping_cart_collapser()' id='fancy_collapser_link'><img src='" . WPSC_URL . "/images/{$collapser_image}' title='' alt='' id='fancy_collapser' /></a>";
        }
    } else {
        $fancy_collapser = "";
    }
    $current_url = "http://" . $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'];
    if (get_option('cart_location') == 4) {
        $no_title = true;
    }
    switch (get_option('cart_location')) {
        case 1:
            if ($no_title !== true) {
                $output .= "<h2>" . TXT_WPSC_SHOPPINGCART . " {$fancy_collapser}</h2>";
                $output .= "<span id='alt_loadingindicator'><img id='alt_loadingimage' src='" . WPSC_URL . "/images/indicator.gif' alt='Loading' title='Loading' /> " . TXT_WPSC_UDPATING . "...</span></strong><br />";
            }
            $spacing = "";
            break;
        case 3:
            if ($no_title !== true) {
                $output .= "<strong class='cart_title'>" . TXT_WPSC_SHOPPINGCART . " {$fancy_collapser}</strong>";
            }
            //$output .= "<a href='#' onclick='return shopping_cart_collapser()' class='cart_title' id='fancy_collapser_link'>".TXT_WPSC_SHOPPINGCART." </a>";
            break;
        case 4:
            if ($no_title !== true) {
                if (is_array($GLOBALS['registered_sidebars'])) {
                    $sidebar_args = end($GLOBALS['registered_sidebars']);
                } else {
                    $sidebar_args['before_title'] = "<h2>";
                    $sidebar_args['after_title'] = "</h2>";
                }
                $output .= $sidebar_args['before_title'] . TXT_WPSC_SHOPPINGCART . " {$fancy_collapser}" . $sidebar_args['after_title'];
            }
            break;
        default:
            if ($no_title !== true) {
                //$output .= "<strong class='cart_title'>".TXT_WPSC_SHOPPINGCART." $fancy_collapser</strong>";
            }
            break;
    }
    $cart_count = 0;
    foreach ((array) $cart as $item) {
        $cart_count += $item->quantity;
    }
    $output .= "<div id='sliding_cart'>";
    if ($cart != null) {
        if ($quantity_limit == true || $_SESSION['out_of_stock'] == true) {
            $output .= "<span class='items'><span class='numberitems'>" . TXT_WPSC_NUMBEROFITEMS . ": </span><span class='cartcount'>" . $cart_count . "</span></span>";
            $output .= "<span class='nomore'>" . TXT_WPSC_NOMOREAVAILABLE . "</span>";
            $_SESSION['out_of_stock'] = false;
        } else {
            $output .= "<span class='items'><span class='numberitems'>" . TXT_WPSC_NUMBEROFITEMS . ": </span><span class='cartcount'>" . $cart_count . "</span></span>";
        }
        $output .= "<table class='shoppingcart'>\n\r";
        $output .= "<tr><th id='thproduct'>" . TXT_WPSC_PRODUCT . "</th><th id='thqty'>" . TXT_WPSC_QUANTITY_SHORT . "</th><th id='thprice'>" . TXT_WPSC_PRICE . "</th></tr>\n\r";
        $all_donations = true;
        $all_no_shipping = true;
        $tax = 0;
        //written by allen
        $merchant_id = get_option('google_id');
        // Your Merchant ID
        $merchant_key = get_option('google_key');
        // Your Merchant Key
        $server_type = get_option('google_server_type');
        $currency = get_option('google_cur');
        if (get_option('payment_gateway') == 'google') {
            $google_cart = new GoogleCart($merchant_id, $merchant_key, $server_type, $currency);
        }
        foreach ($cart as $cart_item) {
            $product_id = $cart_item->product_id;
            $quantity = $cart_item->quantity;
            //echo("<pre>".print_r($cart_item->product_variations,true)."</pre>");
            $product = $wpdb->get_row("SELECT * FROM `" . $wpdb->prefix . "product_list` WHERE `id` = '{$product_id}' LIMIT 1", ARRAY_A);
            if ($product['donation'] == 1) {
                if (get_option('payment_gateway') == 'google') {
                    $google_unit_price = $cart_item->donation_price;
                }
                $price = $quantity * $cart_item->donation_price;
            } else {
                if (get_option('payment_gateway') == 'google') {
                    $google_unit_price = calculate_product_price($product_id, $cart_item->product_variations, 'stay', $cart_item->extras);
                }
                $price = $quantity * calculate_product_price($product_id, $cart_item->product_variations, 'stay', $cart_item->extras);
                if ($product['notax'] != 1) {
                    $tax += nzshpcrt_calculate_tax($price, $_SESSION['selected_country'], $_SESSION['selected_region']) - $price;
                }
                $all_donations = false;
            }
            if ($product['no_shipping'] != 1) {
                $all_no_shipping = false;
            }
            if ($_SESSION['delivery_country'] != null) {
                $total_shipping += nzshpcrt_determine_item_shipping($product['id'], $quantity, $_SESSION['delivery_country']);
            }
            $total += $price;
            //exit(utf8_encode('&trade;'));
            $product['name'] = str_replace("™", "&trade;", $product['name']);
            $product['description'] = str_replace("™", "&trade;", $product['description']);
            if (get_option('payment_gateway') == 'google') {
                $google_item = new GoogleItem(utf8_decode($product['name']), utf8_decode($product['description']), $quantity, $google_unit_price);
                $google_item->SetMerchantItemId($product['id']);
                $google_cart->SetMerchantCalculations(get_option('siteurl'), "false", "false", "false");
                //echo serialize($cart_item->product_variations);
                $google_item->SetMerchantPrivateItemData("some variations");
                $google_cart->AddItem($google_item);
            }
            $output .= "<tr>";
            if (get_option("hide_name_link") == '1') {
                $output .= "<td class='tdproduct'>" . $product['name'] . "</td>";
            } else {
                $output .= "<td><a href='" . wpsc_product_url($product['id']) . "' >" . stripslashes($product['name']) . "</a></td>";
            }
            $output .= "<td class='tdqty'>" . $quantity . "</td>";
            $output .= "<td class='tdprice'>" . nzshpcrt_currency_display($price, 1) . "</td>";
            $output .= "</tr>\n\r";
        }
        //google checkout stuff.
        // 	if (get_option('payment_gateway') == 'google') {
        // 		$google_shipping = new GoogleFlatRateShipping("Flat Rate Shipping", $total_shipping);
        // 		$Gfilter = new GoogleShippingFilters();
        // 		$google_checkout_shipping=get_option("google_shipping_country");
        // 		$google_shipping_country_ids = implode(",",(array)$google_checkout_shipping);
        // 		if($google_shipping_country_ids != null) {
        // 			$google_shipping_country = $wpdb->get_var("SELECT isocode FROM ".$wpdb->prefix."currency_list WHERE id IN (".$google_shipping_country_ids.")");
        // 		}
        // 		$Gfilter->AddAllowedPostalArea($google_shipping_country);
        // 		$google_shipping->AddShippingRestrictions($Gfilter);
        // 		$google_cart->AddShipping($google_shipping);
        //
        // 		if ($_SESSION['selected_country']=='US'){
        // 			$tax_rule = new GoogleDefaultTaxRule(0.05);
        // 			$state_name = $wpdb->get_var("SELECT name FROM ".$wpdb->prefix."region_tax WHERE id='".$_SESSION['selected_region']."'");
        // 			$tax_rule->SetStateAreas(array($state_name));
        // 			$tax_rule->AddPostalArea($google_shipping_country);
        // 			$google_cart->AddDefaultTaxRules($tax_rule);
        // 		}
        // 	}
        //end of google checkout.
        $output .= "</table>";
        if ($_SESSION['delivery_country'] != null) {
            $total_shipping = nzshpcrt_determine_base_shipping($total_shipping, $_SESSION['delivery_country']);
            $output .= "<span class='subtotal'><span class='subtotalhead'>" . TXT_WPSC_SUBTOTAL . ":</span>" . nzshpcrt_currency_display($total, 1) . "</span>";
            if (get_option('do_not_use_shipping') != 1 && $all_donations == false && $all_no_shipping == false) {
                $output .= "<span class='postage'><span class='postagehead'>" . TXT_WPSC_POSTAGE . ":</span>" . nzshpcrt_currency_display($total_shipping, 1) . "</span> ";
            }
            if ($tax > 0) {
                $output .= "<span class='tax'><span class='taxhead'>" . TXT_WPSC_TAX . ":</span> &nbsp;&nbsp;" . nzshpcrt_currency_display($tax, 1) . "</span>";
            }
            if ($_SESSION['coupon_num']) {
                $overall_total = nzshpcrt_overall_total_price_numeric($_SESSION['selected_country'], true);
                $discount = $overall_total - nzshpcrt_apply_coupon($overall_total, $_SESSION['coupon_num']);
                $total_after_discount = $overall_total - $discount;
                $_SESSION['wpsc_discount'] = $discount;
            } else {
                $_SESSION['wpsc_discount'] = 0;
            }
            if ($discount > 0) {
                $output .= "<span class='discount'><span class='discounthead'>" . TXT_WPSC_DISCOUNT . ":</span>" . nzshpcrt_currency_display($discount, 1) . "</span>";
            }
            $output .= "<span class='total'><span class='totalhead'>" . TXT_WPSC_TOTAL . ":</span>" . nzshpcrt_overall_total_price($_SESSION['delivery_country'], true) . "</span>";
        } else {
            if ($discount > 0) {
                $output .= "<span class='discount'><span class='discounthead'>" . TXT_WPSC_DISCOUNT . ":</span>" . nzshpcrt_currency_display($discount, 1) . "</span>";
            }
            $output .= "<span class='total'><span class='totalhead'>" . TXT_WPSC_TOTAL . ":</span>" . nzshpcrt_overall_total_price($_SESSION['delivery_country'], true) . "</span>";
        }
        if (get_option('permalink_structure') != '') {
            $seperator = "?";
        } else {
            $seperator = "&amp;";
        }
        if ($discount > 0) {
            if (get_option('payment_gateway') == 'google') {
                $google_item = new GoogleItem(utf8_decode("Coupon Code: '" . $_SESSION['coupon_num'] . "'"), utf8_decode("A coupon redeem"), 1, -$discount);
                $google_item->SetMerchantPrivateItemData("Coupon Deduction");
                $google_cart->AddItem($google_item);
            }
        }
        if (get_option('payment_gateway') == 'google') {
            if (!$total_shipping) {
                $total_shipping = 0;
            }
            $pnp = $wpdb->get_var("SELECT SUM(pnp) FROM " . $wpdb->prefix . "product_list WHERE id IN (" . $google_product_id . ")");
            $local_shipping_price = nzshpcrt_determine_base_shipping($total_shipping, get_option('base_country'));
            $google_local_shipping = new GoogleFlatRateShipping("Local Shipping", $local_shipping_price + $pnp);
            $international_shipping_price = nzshpcrt_determine_base_shipping($total_shipping, get_option('base_country') . "-");
            $google_international_shipping = new GoogleFlatRateShipping("International Shipping", $international_shipping_price + $pnp);
            $Gfilter2 = new GoogleShippingFilters();
            $Gfilter = new GoogleShippingFilters();
            $google_checkout_shipping = get_option("google_shipping_country");
            if (!empty($google_checkout_shipping)) {
                $google_shipping_country_ids = implode(",", (array) $google_checkout_shipping);
                $google_shipping_country = $wpdb->get_results("SELECT isocode FROM " . $wpdb->prefix . "currency_list WHERE id IN (" . $google_shipping_country_ids . ")", ARRAY_A);
            }
            //exit(print_r($google_shipping_country,1));
            foreach ((array) $google_shipping_country as $country) {
                $Gfilter->AddAllowedPostalArea($country['isocode']);
                $Gfilter2->AddAllowedPostalArea($country['isocode']);
                $Gfilter2->AddExcludedPostalArea(get_option('base_country'));
                if ($country['isocode'] != get_option('base_country')) {
                    $Gfilter->AddExcludedPostalArea($country['isocode']);
                }
            }
            $google_local_shipping->AddShippingRestrictions($Gfilter);
            $google_international_shipping->AddShippingRestrictions($Gfilter2);
            $google_cart->AddShipping($google_local_shipping);
            $google_cart->AddShipping($google_international_shipping);
            $local_tax = $wpdb->get_var("SELECT tax from " . $wpdb->prefix . "currency_list WHERE isocode='" . get_option('base_country') . "'");
            //exit($local_tax);
            $tax_rule = new GoogleDefaultTaxRule($local_tax / 100);
            if ($_SESSION['selected_country'] == 'US' && get_option('base_country') == 'US') {
                $state_name = $wpdb->get_var("SELECT name FROM " . $wpdb->prefix . "region_tax WHERE id='" . $_SESSION['selected_region'] . "'");
                //foreach ($state_name as $state)
                $tax_rule->SetStateAreas(array($state_name));
            } else {
                $tax_rule->AddPostalArea(get_option('base_country'));
            }
            $google_cart->AddDefaultTaxRules($tax_rule);
            $alter_tax_rule = new GoogleDefaultTaxRule(0.0);
            foreach ((array) $google_shipping_country as $country) {
                if (get_option('base_country') != $country['isocode']) {
                    $alter_tax_rule->AddPostalArea($country['isocode']);
                }
            }
            if ($alter_tax_rule != '') {
                $google_cart->AddDefaultTaxRules($alter_tax_rule);
            }
        }
        $output .= "<span class='emptycart'><a href='" . get_option('product_list_url') . $seperator . "category=" . $_GET['category'] . "&amp;cart=empty' onclick='emptycart();return false;'>" . TXT_WPSC_EMPTYYOURCART . "</a><span>";
        $output .= "<span class='gocheckout'><a href='" . get_option('shopping_cart_url') . "'>" . TXT_WPSC_GOTOCHECKOUT . "</a></span>";
        if (get_option('payment_gateway') == 'google') {
            if (get_option('google_button_size') == '0') {
                $google_button_size = 'BIG';
            } elseif (get_option('google_button_size') == '1') {
                $google_button_size = 'MEDIUM';
            } elseif (get_option('google_button_size') == '2') {
                $google_button_size = 'SMALL';
            }
            $google_cart->SetMerchantCalculations(get_option('siteurl'), "false", "false");
            $google_cart->SetRequestBuyerPhone("true");
            $google_session = md5(time());
            $_SESSION['google_session'] = $google_session;
            if (!preg_match("/\\?/", get_option('product_list_url'))) {
                $seperator = "?";
            } else {
                $seperator = "&";
            }
            $continueshoppingurl = get_option('product_list_url') . $seperator . "action=bfg&session=" . $google_session;
            $google_cart->SetContinueShoppingUrl($continueshoppingurl);
            $google_cart->SetEditCartUrl(get_option('shopping_cart_url'));
            $_SESSION['google_shopping_cart'] = serialize($google_cart);
            // 		$output .= $google_cart->getXML();
            $output .= "<br>" . $google_cart->CheckoutButtonCode($google_button_size);
        }
        //$output .= "<a href='".get_option('product_list_url')."'>".TXT_WPSC_CONTINUESHOPPING."</a>";
    } else {
        $output .= $spacing;
        $output .= "<p class='empty'>" . TXT_WPSC_YOURSHOPPINGCARTISEMPTY . ".</p>";
        $output .= "<p class='visitshop'><a href='" . get_option('product_list_url') . "'>" . TXT_WPSC_VISITTHESHOP . "</a></p>";
    }
    $output .= "</div>";
    return $output;
}