/**
 * WP eCommerce Admin AJAX functions
 *
 * These are the WPSC Admin AJAX functions
 *
 * @package wp-e-commerce
 * @since 3.7
 *
 * @uses update_option()                              Updates option in the database given key and value
 * @uses wp_delete_term()                             Removes term from the database
 * @uses fetch_rss()                                  DEPRECATED
 * @uses wpsc_member_dedeactivate_subscriptions()     @todo docs
 * @uses wpsc_member_deactivate_subscriptions()       @todo docs
 * @uses wpsc_update_purchase_log_status()            Updates the status of the logs for a purchase
 * @uses transaction_results()                        Main function for creating purchase reports
 * @uses wpsc_find_purchlog_status_name()             Finds name of given status
 */
function wpsc_admin_ajax()
{
    if (!wpsc_is_store_admin()) {
        return;
    }
    global $wpdb;
    if (isset($_POST['action']) && $_POST['action'] == 'product-page-order') {
        $current_order = get_option('wpsc_product_page_order');
        $new_order = $_POST['order'];
        if (isset($new_order["advanced"])) {
            $current_order["advanced"] = array_unique(explode(',', $new_order["advanced"]));
        }
        if (isset($new_order["side"])) {
            $current_order["side"] = array_unique(explode(',', $new_order["side"]));
        }
        update_option('wpsc_product_page_order', $current_order);
        exit(print_r($order, 1));
    }
    if (isset($_POST['save_image_upload_state']) && $_POST['save_image_upload_state'] == 'true' && is_numeric($_POST['image_upload_state'])) {
        $upload_state = (int) (bool) $_POST['image_upload_state'];
        update_option('wpsc_use_flash_uploader', $upload_state);
        exit("done");
    }
    if (isset($_POST['remove_variation_value']) && $_POST['remove_variation_value'] == "true" && is_numeric($_POST['variation_value_id'])) {
        $value_id = absint($_GET['variation_value_id']);
        echo wp_delete_term($value_id, 'wpsc-variation');
        exit;
    }
    if (isset($_REQUEST['log_state']) && $_REQUEST['log_state'] == "true" && is_numeric($_POST['id']) && is_numeric($_POST['value'])) {
        $newvalue = $_POST['value'];
        if ($_REQUEST['suspend'] == 'true') {
            if ($_REQUEST['value'] == 1 && function_exists('wpsc_member_dedeactivate_subscriptions')) {
                wpsc_member_dedeactivate_subscriptions($_POST['id']);
            } elseif (function_exists('wpsc_member_deactivate_subscriptions')) {
                wpsc_member_deactivate_subscriptions($_POST['id']);
            }
            exit;
        } else {
            $log_data = $wpdb->get_row($wpdb->prepare("SELECT * FROM `" . WPSC_TABLE_PURCHASE_LOGS . "` WHERE `id` = '%d' LIMIT 1", $_POST['id']), ARRAY_A);
            if ($newvalue == 2 && function_exists('wpsc_member_activate_subscriptions')) {
                wpsc_member_activate_subscriptions($_POST['id']);
            }
            wpsc_update_purchase_log_status($_POST['id'], $newvalue);
            if ($newvalue > $log_data['processed'] && $log_data['processed'] < 2) {
                transaction_results($log_data['sessionid'], false);
            }
            $status_name = wpsc_find_purchlog_status_name($purchase['processed']);
            echo "document.getElementById(\"form_group_" . absint($_POST['id']) . "_text\").innerHTML = '" . $status_name . "';\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(wpsc_currency_display(admin_display_total_price($start_timestamp, $end_timestamp))) . "';\n";
            echo "document.getElementById(\"log_total_absolute\").innerHTML = '" . addslashes(wpsc_currency_display(admin_display_total_price())) . "';\n";
            exit;
        }
    }
}
function wpsc_purchlog_edit_status($purchlog_id = '', $purchlog_status = '')
{
    global $wpdb;
    if (empty($purchlog_id) && empty($purchlog_status)) {
        $purchlog_id = absint($_POST['id']);
        $purchlog_status = absint($_POST['new_status']);
    }
    $purchase_log = new WPSC_Purchase_Log($purchlog_id);
    //in the future when everyone is using the 2.0 merchant api, we should use the merchant class to update the staus,
    // then you can get rid of this hook and have each person overwrite the method that updates the status.
    do_action('wpsc_edit_order_status', array('purchlog_id' => $purchlog_id, 'purchlog_data' => $purchase_log->get_data(), 'new_status' => $purchlog_status));
    $result = wpsc_update_purchase_log_status($purchlog_id, $purchlog_status);
    wpsc_clear_stock_claims();
    return $result;
}
/**
 * prcessing functions, this is where the main logic of paypal express lives
 * @access public
 *
 * @since 3.8
 */
function paypal_processingfunctions()
{
    global $wpdb, $wpsc_cart;
    $sessionid = (string) wpsc_get_customer_meta('paypal_express_sessionid');
    if (isset($_REQUEST['act']) && 'error' == $_REQUEST['act']) {
        $resArray = wpsc_get_customer_meta('paypal_express_reshash');
        $paypal_express_message = '
		<center>
		<table width="700" align="left">
		<tr>
			<td colspan="2" class="header">' . __('The PayPal API has returned an error!', 'wpsc') . '</td>
		</tr>
		';
        //it will print if any URL errors
        if (wpsc_get_customer_meta('paypal_express_curl_error_msg')) {
            $errorMessage = wpsc_get_customer_meta('paypal_express_curl_error_msg');
            $response = wpsc_get_customer_meta('paypal_express_response');
            $paypal_express_message .= '
			<tr>
				<td>response:</td>
				<td>' . $response . '</td>
			</tr>

			<tr>
				<td>Error Message:</td>
				<td>' . $errorMessage . '</td>
			</tr>';
        } else {
            /* If there is no URL Errors, Construct the HTML page with
               Response Error parameters.   */
            $paypal_express_message .= "\n\t\t\t\t<tr>\n\t\t\t\t\t<td>Ack:</td>\n\t\t\t\t\t<td>" . $resArray['ACK'] . "</td>\n\t\t\t\t</tr>\n\t\t\t\t<tr>\n\t\t\t\t\t<td>Correlation ID:</td>\n\t\t\t\t\t<td>" . $resArray['CORRELATIONID'] . "</td>\n\t\t\t\t</tr>\n\t\t\t\t<tr>\n\t\t\t\t\t<td>Version:</td>\n\t\t\t\t\t<td>" . $resArray['VERSION'] . "</td>\n\t\t\t\t</tr>";
            $count = 0;
            while (isset($resArray["L_SHORTMESSAGE" . $count])) {
                $errorCode = $resArray["L_ERRORCODE" . $count];
                $shortMessage = $resArray["L_SHORTMESSAGE" . $count];
                $longMessage = $resArray["L_LONGMESSAGE" . $count];
                $count = $count + 1;
                $paypal_express_message .= "\n\t\t\t\t\t<tr>\n\t\t\t\t\t\t<td>" . __('Error Number:', 'wpsc') . "</td>\n\t\t\t\t\t\t<td> {$errorCode} </td>\n\t\t\t\t\t</tr>\n\t\t\t\t\t<tr>\n\t\t\t\t\t\t<td>" . __('Short Message:', 'wpsc') . "</td>\n\t\t\t\t\t\t<td> {$shortMessage} </td>\n\t\t\t\t\t</tr>\n\t\t\t\t\t<tr>\n\t\t\t\t\t\t<td>" . __('Long Message:', 'wpsc') . "</td>\n\t\t\t\t\t\t<td> {$longMessage} </td>\n\t\t\t\t\t</tr>";
            }
            //end while
        }
        // end else
        $paypal_express_message .= "\n\t\t\t</center>\n\t\t\t\t</table>";
        wpsc_update_customer_meta('paypal_express_message', $paypal_express_message);
    } else {
        if (isset($_REQUEST['act']) && $_REQUEST['act'] == 'do') {
            /* Gather the information to make the final call to
               finalize the PayPal payment.  The variable nvpstr
               holds the name value pairs   */
            $token = urlencode($_REQUEST['token']);
            $paymentAmount = urlencode(wpsc_get_customer_meta('paypal_express_converted_amount'));
            $paymentType = urlencode(wpsc_get_customer_meta('paypal_express_payment_type'));
            $currCodeType = urlencode(wpsc_get_paypal_currency_code());
            $payerID = urlencode($_REQUEST['PayerID']);
            $serverName = urlencode($_SERVER['SERVER_NAME']);
            $BN = 'Instinct_e-commerce_wp-shopping-cart_NZ';
            $nvpstr = '&TOKEN=' . $token . '&PAYERID=' . $payerID . '&PAYMENTREQUEST_0_PAYMENTACTION=Sale&PAYMENTREQUEST_0_CURRENCYCODE=' . $currCodeType . '&IPADDRESS=' . $serverName . "&BUTTONSOURCE=" . $BN . "&PAYMENTREQUEST_0_INVNUM=" . urlencode($sessionid);
            // IPN data
            if (get_option('paypal_ipn') == 1) {
                $notify_url = add_query_arg('wpsc_action', 'gateway_notification', get_option('siteurl') . "/index.php");
                $notify_url = add_query_arg('gateway', 'wpsc_merchant_paypal_express', $notify_url);
                $notify_url = apply_filters('wpsc_paypal_express_notify_url', $notify_url);
                $nvpstr .= '&PAYMENTREQUEST_0_NOTIFYURL=' . urlencode($notify_url);
            }
            // Horrible code that I had to write to hot fix the issue with missing item detail in email receipts. arrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrgh!!!!! @#@$%@#%@##$#$
            $purchase_log = $wpdb->get_row($wpdb->prepare("SELECT * FROM `" . WPSC_TABLE_PURCHASE_LOGS . "` WHERE `sessionid` = %s", $sessionid), ARRAY_A);
            $cart_data = $original_cart_data = $wpdb->get_results("SELECT * FROM `" . WPSC_TABLE_CART_CONTENTS . "` WHERE `purchaseid` = {$purchase_log['id']}", ARRAY_A);
            $i = 0;
            $item_total = 0;
            $shipping_total = 0;
            foreach ($cart_data as $cart_item) {
                $converted_price = wpsc_paypal_express_convert($cart_item['price']);
                $nvpstr .= "&L_PAYMENTREQUEST_0_NAME{$i}=" . urlencode(apply_filters('the_title', $cart_item['name']));
                $nvpstr .= "&L_PAYMENTREQUEST_0_AMT{$i}=" . $converted_price;
                $nvpstr .= "&L_PAYMENTREQUEST_0_NUMBER{$i}=" . $i;
                $nvpstr .= "&L_PAYMENTREQUEST_0_QTY{$i}=" . $cart_item['quantity'];
                $item_total += $converted_price * $cart_item['quantity'];
                $shipping_total += wpsc_paypal_express_convert($cart_item['pnp']);
                $i++;
            }
            //if we have a discount then include a negative amount with that discount
            if ($purchase_log['discount_value'] && 0.0 != $purchase_log['discount_value']) {
                $discount_value = wpsc_paypal_express_convert($purchase_log['discount_value']);
                // if item total < discount amount, leave at least 0.01 unit in item total, then subtract
                // 0.01 from shipping as well
                if ($discount_value >= $item_total) {
                    $discount_value = $item_total - 0.01;
                    $shipping_total -= 0.01;
                }
                $nvpstr .= "&L_PAYMENTREQUEST_0_NAME{$i}=" . urlencode("Discount / Coupon");
                $nvpstr .= "&L_PAYMENTREQUEST_0_AMT{$i}=-" . urlencode($discount_value);
                $nvpstr .= "&L_PAYMENTREQUEST_0_NUMBER{$i}={$i}";
                $nvpstr .= "&L_PAYMENTREQUEST_0_QTY{$i}=1";
                $item_total -= $discount_value;
            }
            $item_total = wpsc_paypal_express_format($item_total);
            $shipping_total = wpsc_paypal_express_convert($purchase_log['base_shipping']) + $shipping_total;
            $nvpstr .= '&PAYMENTREQUEST_0_ITEMAMT=' . $item_total;
            $nvpstr .= '&PAYMENTREQUEST_0_SHIPPINGAMT=' . $shipping_total;
            $total = $item_total + $shipping_total;
            if (!wpsc_tax_isincluded()) {
                $tax = wpsc_paypal_express_convert($purchase_log['wpec_taxes_total']);
                $nvpstr .= '&PAYMENTREQUEST_0_TAXAMT=' . $tax;
                $total += $tax;
            }
            // adjust total amount in case we had to round up after converting currency
            if ($total != $paymentAmount) {
                $paymentAmount = $total;
            }
            $nvpstr .= "&PAYMENTREQUEST_0_AMT={$paymentAmount}";
            $resArray = paypal_hash_call("DoExpressCheckoutPayment", $nvpstr);
            /* Display the API response back to the browser.
               If the response from PayPal was a success, display the response parameters'
               If the response was an error, display the errors received using APIError.php. */
            $ack = strtoupper($resArray["ACK"]);
            wpsc_update_customer_meta('paypal_express_reshash', $resArray);
            if ($ack != "SUCCESS") {
                $location = get_option('transact_url') . "&act=error";
            } else {
                $transaction_id = $resArray['PAYMENTINFO_0_TRANSACTIONID'];
                switch ($resArray['PAYMENTINFO_0_PAYMENTSTATUS']) {
                    case 'Processed':
                        // I think this is mostly equivalent to Completed
                    // I think this is mostly equivalent to Completed
                    case 'Completed':
                        wpsc_update_purchase_log_status($sessionid, 3, 'sessionid');
                        transaction_results($sessionid, false);
                        break;
                    case 'Pending':
                        // need to wait for "Completed" before processing
                        wpsc_update_purchase_log_details($sessionid, array('processed' => 2, 'date' => time(), 'transactid' => $transaction_id), 'sessionid');
                        break;
                }
                $location = add_query_arg('sessionid', $sessionid, get_option('transact_url'));
                wpsc_delete_customer_meta('paypal_express_message');
                wp_redirect($location);
                exit;
            }
            wpsc_delete_customer_meta('nzshpcrt_serialized_cart');
            wpsc_delete_customer_meta('nzshpcart');
            $wpsc_cart->empty_cart();
        } else {
            if (isset($_REQUEST['paymentType']) || isset($_REQUEST['token'])) {
                $token = $_REQUEST['token'];
                if (!isset($token)) {
                    $paymentAmount = wpsc_get_customer_meta('paypal_express_converted_amount');
                    $currencyCodeType = wpsc_get_paypal_currency_code();
                    $paymentType = 'Sale';
                    if (get_option('permalink_structure') != '') {
                        $separator = "?";
                    } else {
                        $separator = "&";
                    }
                    $returnURL = urlencode(get_option('transact_url') . $separator . 'currencyCodeType=' . $currencyCodeType . '&paymentType=' . $paymentType . '&paymentAmount=' . $paymentAmount);
                    $cancelURL = urlencode(get_option('transact_url') . $separator . 'paymentType=$paymentType');
                    /* Construct the parameter string that describes the PayPal payment
                    			the varialbes were set in the web form, and the resulting string
                    			is stored in $nvpstr */
                    $nvpstr = "&PAYMENTREQUEST_0_AMT=" . $paymentAmount . "&PAYMENTREQUEST_0_PAYMENTACTION=" . $paymentType . "&ReturnUrl=" . $returnURL . "&CANCELURL=" . $cancelURL . "&PAYMENTREQUEST_0_CURRENCYCODE=" . $currencyCodeType;
                    /* Make the call to PayPal to set the Express Checkout token
                    			If the API call succeded, then redirect the buyer to PayPal
                    			to begin to authorize payment.  If an error occured, show the
                    			resulting errors
                    			*/
                    $resArray = paypal_hash_call("SetExpressCheckout", $nvpstr);
                    wpsc_update_customer_meta('paypal_express_reshash', $resArray);
                    $ack = strtoupper($resArray["ACK"]);
                    if ($ack == "SUCCESS") {
                        // Redirect to paypal.com here
                        $token = urldecode($resArray["TOKEN"]);
                        $payPalURL = $PAYPAL_URL . $token;
                        wp_redirect($payPalURL);
                    } else {
                        // Redirecting to APIError.php to display errors.
                        $location = get_option('transact_url') . "&act=error";
                        wp_redirect($location);
                    }
                    exit;
                } else {
                    /* At this point, the buyer has completed in authorizing payment
                    			at PayPal.  The script will now call PayPal with the details
                    			of the authorization, incuding any shipping information of the
                    			buyer.  Remember, the authorization is not a completed transaction
                    			at this state - the buyer still needs an additional step to finalize
                    			the transaction
                    			*/
                    $token = urlencode($_REQUEST['token']);
                    /* Build a second API request to PayPal, using the token as the
                    			ID to get the details on the payment authorization
                    			*/
                    $nvpstr = "&TOKEN=" . $token;
                    /* Make the API call and store the results in an array.  If the
                    			call was a success, show the authorization details, and provide
                    			an action to complete the payment.  If failed, show the error
                    			*/
                    $resArray = paypal_hash_call("GetExpressCheckoutDetails", $nvpstr);
                    wpsc_update_customer_meta('paypal_express_reshash', $resArray);
                    $ack = strtoupper($resArray["ACK"]);
                    if ($ack == "SUCCESS") {
                        /********************************************************
                        				GetExpressCheckoutDetails.php
                        
                        				This functionality is called after the buyer returns from
                        				PayPal and has authorized the payment.
                        
                        				Displays the payer details returned by the
                        				GetExpressCheckoutDetails response and calls
                        				DoExpressCheckoutPayment.php to complete the payment
                        				authorization.
                        
                        				Called by ReviewOrder.php.
                        
                        				Calls DoExpressCheckoutPayment.php and APIError.php.
                        
                        				********************************************************/
                        /* Collect the necessary information to complete the
                        			authorization for the PayPal payment
                        			*/
                        /* Display the API response back to the browser .
                        			If the response from PayPal was a success, display the response parameters
                        			*/
                        if (isset($_REQUEST['token']) && !isset($_REQUEST['PayerID'])) {
                            wpsc_update_customer_meta('paypal_express_message', _x('<h4>TRANSACTION CANCELED</h4>', 'paypal express cancel header', 'wpsc'));
                        } else {
                            wpsc_update_customer_meta('paypal_express_token', $_REQUEST['token']);
                            wpsc_update_customer_meta('paypal_express_payer_id', $_REQUEST['PayerID']);
                            $resArray = wpsc_get_customer_meta('paypal_express_reshash');
                            if (get_option('permalink_structure') != '') {
                                $separator = "?";
                            } else {
                                $separator = "&";
                            }
                            if (!isset($resArray['SHIPTOSTREET2'])) {
                                $resArray['SHIPTOSTREET2'] = '';
                            }
                            $output = "\n\t\t\t\t\t   <table width='400' class='paypal_express_form'>\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t<td align='left' class='firstcol'><b>" . __('Order Total:', 'wpsc') . "</b></td>\n\t\t\t\t\t\t\t<td align='left'>" . wpsc_currency_display(wpsc_get_customer_meta('paypal_express_original_amount')) . "</td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t<td align='left' colspan='2'><b>" . __('Shipping Address:', 'wpsc') . " </b></td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t<td align='left' class='firstcol'>\n\t\t\t\t\t\t\t\t" . __('Street 1:', 'wpsc') . "</td>\n\t\t\t\t\t\t\t<td align='left'>" . $resArray['SHIPTOSTREET'] . "</td>\n\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t<td align='left' class='firstcol'>\n\t\t\t\t\t\t\t\t" . __('Street 2:', 'wpsc') . "</td>\n\t\t\t\t\t\t\t<td align='left'>" . $resArray['SHIPTOSTREET2'] . "\n\t\t\t\t\t\t\t</td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t<td align='left' class='firstcol'>\n\t\t\t\t\t\t\t\t" . __('City:', 'wpsc') . "</td>\n\n\t\t\t\t\t\t\t<td align='left'>" . $resArray['SHIPTOCITY'] . "</td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t<td align='left' class='firstcol'>\n\t\t\t\t\t\t\t\t" . __('State:', 'wpsc') . "</td>\n\t\t\t\t\t\t\t<td align='left'>" . $resArray['SHIPTOSTATE'] . "</td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t<td align='left' class='firstcol'>\n\t\t\t\t\t\t\t\t" . __('Postal code:', 'wpsc') . "</td>\n\n\t\t\t\t\t\t\t<td align='left'>" . $resArray['SHIPTOZIP'] . "</td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t<td align='left' class='firstcol'>\n\t\t\t\t\t\t\t\t" . __('Country:', 'wpsc') . "</td>\n\t\t\t\t\t\t\t<td align='left'>" . $resArray['SHIPTOCOUNTRYNAME'] . "</td>\n\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t<td colspan='2'>";
                            $output .= "<form action=" . get_option('transact_url') . " method='post'>\n";
                            $output .= "\t<input type='hidden' name='totalAmount' value='" . wpsc_cart_total(false) . "' />\n";
                            $output .= "\t<input type='hidden' name='shippingStreet' value='" . $resArray['SHIPTOSTREET'] . "' />\n";
                            $output .= "\t<input type='hidden' name='shippingStreet2' value='" . $resArray['SHIPTOSTREET2'] . "' />\n";
                            $output .= "\t<input type='hidden' name='shippingCity' value='" . $resArray['SHIPTOCITY'] . "' />\n";
                            $output .= "\t<input type='hidden' name='shippingState' value='" . $resArray['SHIPTOSTATE'] . "' />\n";
                            $output .= "\t<input type='hidden' name='postalCode' value='" . $resArray['SHIPTOZIP'] . "' />\n";
                            $output .= "\t<input type='hidden' name='country' value='" . $resArray['SHIPTOCOUNTRYNAME'] . "' />\n";
                            $output .= "\t<input type='hidden' name='token' value='" . wpsc_get_customer_meta('paypal_express_token') . "' />\n";
                            $output .= "\t<input type='hidden' name='PayerID' value='" . wpsc_get_customer_meta('paypal_express_payer_id') . "' />\n";
                            $output .= "\t<input type='hidden' name='act' value='do' />\n";
                            $output .= "\t<p>  <input name='usePayPal' type='submit' value='" . __('Confirm Payment', 'wpsc') . "' /></p>\n";
                            $output .= "</form>";
                            $output .= " </td>\n\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t</table>\n\t\t\t\t\t</center>\n\t\t\t\t\t";
                            wpsc_update_customer_meta('paypal_express_message', $output);
                        }
                    }
                }
            }
        }
    }
}
function wpsc_transaction_theme()
{
    global $wpdb, $user_ID, $nzshpcrt_gateways, $sessionid, $cart_log_id, $errorcode;
    $errorcode = '';
    $transactid = '';
    $dont_show_transaction_results = false;
    if (isset($_GET['sessionid'])) {
        $sessionid = $_GET['sessionid'];
    }
    if (!isset($_GET['sessionid']) && isset($_GET['ms'])) {
        $sessionid = $_GET['ms'];
    }
    $selected_gateway = wpsc_get_customer_meta('selected_gateway');
    if ($selected_gateway && in_array($selected_gateway, array('paypal_certified', 'wpsc_merchant_paypal_express'))) {
        $sessionid = wpsc_get_customer_meta('paypal_express_sessionid');
    }
    if (isset($_REQUEST['eway']) && '1' == $_REQUEST['eway']) {
        $sessionid = $_GET['result'];
    } elseif (isset($_REQUEST['eway']) && '0' == $_REQUEST['eway']) {
        echo wpsc_get_customer_meta('eway_message');
    } elseif (isset($_REQUEST['payflow']) && '1' == $_REQUEST['payflow']) {
        echo wpsc_get_customer_meta('payflow_message');
        wpsc_delete_customer_meta('payflow_message');
    }
    $dont_show_transaction_results = false;
    if ($selected_gateway) {
        // Replaces the ugly if else for gateways
        switch ($selected_gateway) {
            case 'paypal_certified':
            case 'wpsc_merchant_paypal_express':
                echo wpsc_get_customer_meta('paypal_express_message');
                $reshash = wpsc_get_customer_meta('paypal_express_reshash');
                if (isset($reshash['PAYMENTINFO_0_TRANSACTIONTYPE']) && in_array($reshash['PAYMENTINFO_0_TRANSACTIONTYPE'], array('expresscheckout', 'cart'))) {
                    $dont_show_transaction_results = false;
                } else {
                    $dont_show_transaction_results = true;
                }
                break;
            case 'dps':
                $sessionid = decrypt_dps_response();
                break;
                //paystation was not updating the purchase logs for successful payment - this is ugly as need to have the databse update done in one place by all gatways on a sucsessful transaction hook not some within the gateway and some within here and some not at all??? This is getting a major overhaul but for here and now it just needs to work for the gold cart people!
            //paystation was not updating the purchase logs for successful payment - this is ugly as need to have the databse update done in one place by all gatways on a sucsessful transaction hook not some within the gateway and some within here and some not at all??? This is getting a major overhaul but for here and now it just needs to work for the gold cart people!
            case 'paystation':
                $ec = $_GET['ec'];
                $result = $_GET['em'];
                if ($result == 'Transaction successful' && $ec == 0) {
                    $processed_id = '3';
                }
                if ($result == 'Insufficient Funds' && $ec == 5) {
                    $processed_id = '6';
                }
                if ($processed_id) {
                    wpsc_update_purchase_log_status($sessionid, $processed_id, 'sessionid');
                }
                break;
            case 'wpsc_merchant_paymentexpress':
                // Payment Express sends back there own session id, which is temporarily stored in the Auth field
                // so just swapping that over here
                $query = "SELECT `sessionid` FROM  `" . WPSC_TABLE_PURCHASE_LOGS . "` WHERE  `authcode` ='" . $sessionid . "'";
                $result = $wpdb->get_var($query);
                if ($result != null) {
                    // just in case they are using an older version old gold cart (pre 2.9.5)
                    $sessionid = $result;
                    $dont_show_transaction_results = true;
                }
                break;
            case 'eway_hosted':
                $sessionid = decrypt_eway_uk_response();
                break;
                //default filter for other payment gateways to use
            //default filter for other payment gateways to use
            default:
                $sessionid = apply_filters('wpsc_previous_selected_gateway_' . $selected_gateway, $sessionid);
                break;
        }
    }
    if (!$dont_show_transaction_results) {
        if (!empty($sessionid)) {
            $cart_log_id = $wpdb->get_var($wpdb->prepare("SELECT `id` FROM `" . WPSC_TABLE_PURCHASE_LOGS . "` WHERE `sessionid`= %s LIMIT 1", $sessionid));
            echo transaction_results($sessionid, true);
        } else {
            printf(__('Sorry your transaction was not accepted.<br /><a href="%1$s">Click here to go back to checkout page</a>.', 'wp-e-commerce'), wpsc_get_checkout_url());
        }
    }
}
function wpsc_download_file()
{
    global $wpdb;
    if (isset($_GET['downloadid'])) {
        // strip out anything that isnt 'a' to 'z' or '0' to '9'
        ini_set('max_execution_time', 10800);
        $downloadid = preg_replace("/[^a-z0-9]+/i", '', strtolower($_GET['downloadid']));
        $download_data = $wpdb->get_row($wpdb->prepare("SELECT * FROM `" . WPSC_TABLE_DOWNLOAD_STATUS . "` WHERE `uniqueid` = '%s' AND `downloads` > '0' AND `active`='1' LIMIT 1", $downloadid), ARRAY_A);
        if (is_null($download_data) && is_numeric($downloadid)) {
            $download_data = $wpdb->get_row($wpdb->prepare("SELECT * FROM `" . WPSC_TABLE_DOWNLOAD_STATUS . "` WHERE `id` = %d AND `downloads` > '0' AND `active`='1' AND `uniqueid` IS NULL LIMIT 1", $downloadid), ARRAY_A);
        }
        if (get_option('wpsc_ip_lock_downloads') == 1 && $_SERVER['REMOTE_ADDR'] != null) {
            $ip_number = $_SERVER['REMOTE_ADDR'];
            if ($download_data['ip_number'] == '') {
                // if the IP number is not set, set it
                $wpdb->update(WPSC_TABLE_DOWNLOAD_STATUS, array('ip_number' => $ip_number), array('id' => $download_data['id']));
            } else {
                if ($ip_number != $download_data['ip_number']) {
                    // if the IP number is set but does not match, fail here.
                    exit(_e('This download is no longer valid, Please contact the site administrator for more information.', 'wpsc'));
                }
            }
        }
        $file_id = $download_data['fileid'];
        $file_data = wpsc_get_downloadable_file($file_id);
        if ($file_data == null) {
            exit(_e('This download is no longer valid, Please contact the site administrator for more information.', 'wpsc'));
        }
        if ($download_data != null) {
            if ((int) $download_data['downloads'] >= 1) {
                $download_count = (int) $download_data['downloads'] - 1;
            } else {
                $download_count = 0;
            }
            $wpdb->update(WPSC_TABLE_DOWNLOAD_STATUS, array('downloads' => $download_count), array('id' => $download_data['id']));
            $cart_contents = $wpdb->get_results($wpdb->prepare("SELECT `" . WPSC_TABLE_CART_CONTENTS . "`.*, {$wpdb->posts}.`guid` FROM `" . WPSC_TABLE_CART_CONTENTS . "` LEFT JOIN {$wpdb->posts} ON `" . WPSC_TABLE_CART_CONTENTS . "`.`prodid`= {$wpdb->posts}.`post_parent` WHERE {$wpdb->posts}.`post_type` = 'wpsc-product-file' AND `purchaseid` = %d", $download_data['purchid']), ARRAY_A);
            $dl = 0;
            foreach ($cart_contents as $cart_content) {
                if ($cart_content['guid'] == 1) {
                    $dl++;
                }
            }
            if (count($cart_contents) == $dl) {
                wpsc_update_purchase_log_status($download_data['purchid'], 4);
            }
            do_action('wpsc_alter_download_action', $file_id);
            $file_path = WPSC_FILE_DIR . basename($file_data->post_title);
            $file_name = basename($file_data->post_title);
            if (is_file($file_path)) {
                if (!ini_get('safe_mode')) {
                    set_time_limit(0);
                }
                header('Content-Type: ' . $file_data->post_mime_type);
                header('Content-Length: ' . filesize($file_path));
                header('Content-Transfer-Encoding: binary');
                header('Content-Disposition: attachment; filename="' . $file_name . '"');
                if (isset($_SERVER["HTTPS"]) && $_SERVER["HTTPS"] != '') {
                    /*
                     There is a bug in how IE handles downloads from servers using HTTPS, this is part of the fix, you may also need:
                     session_cache_limiter('public');
                     session_cache_expire(30);
                     At the start of your index.php file or before the session is started
                    */
                    header("Pragma: public");
                    header("Expires: 0");
                    header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
                    header("Cache-Control: public");
                } else {
                    header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
                }
                header("Pragma: public");
                header("Expires: 0");
                // destroy the session to allow the file to be downloaded on some buggy browsers and webservers
                session_destroy();
                wpsc_readfile_chunked($file_path);
                exit;
            } else {
                wp_die(__('Sorry something has gone wrong with your download!', 'wpsc'));
            }
        } else {
            exit(_e('This download is no longer valid, Please contact the site administrator for more information.', 'wpsc'));
        }
    }
}
 /**
  * set_purchase_processed_by_sessionid, this helps change the purchase log status
  * $status = integer status order
  */
 function set_purchase_processed_by_sessionid($status = 1)
 {
     wpsc_update_purchase_log_status($this->session_id, $status, 'sessionid');
 }
/**
 * Updates the 'processed' parameter after a new order is submitted with a free cart.
 *
 * @param  string            $gateway  Name of gateway.  In the case of a free cart, this will be empty.
 * @param  WPSC_Purchase_Log $log      WPSC_Purchase_Log object.
 * @uses   apply_filters               'wpsc_free_checkout_order_status' allows developers to change the status a free cart is saved with.
 * @since  3.9.0
 *
 */
function wpsc_free_checkout_update_processed_status($gateway, $log)
{
    wpsc_update_purchase_log_status($log->get('id'), apply_filters('wpsc_free_checkout_order_status', WPSC_Purchase_Log::ACCEPTED_PAYMENT));
    wp_safe_redirect(add_query_arg('sessionid', $log->get('sessionid'), get_option('transact_url')));
    exit;
}
function wpsc_download_file()
{
    global $wpdb;
    if (isset($_GET['downloadid'])) {
        // strip out anything that isnt 'a' to 'z' or '0' to '9'
        ini_set('max_execution_time', 10800);
        $downloadid = preg_replace("/[^a-z0-9]+/i", '', strtolower($_GET['downloadid']));
        $download_data = $wpdb->get_row($wpdb->prepare("SELECT * FROM `" . WPSC_TABLE_DOWNLOAD_STATUS . "` WHERE `uniqueid` = '%s' AND `downloads` > '0' AND `active`='1' LIMIT 1", $downloadid), ARRAY_A);
        if (is_null($download_data) && is_numeric($downloadid)) {
            $download_data = $wpdb->get_row($wpdb->prepare("SELECT * FROM `" . WPSC_TABLE_DOWNLOAD_STATUS . "` WHERE `id` = %d AND `downloads` > '0' AND `active`='1' AND `uniqueid` IS NULL LIMIT 1", $downloadid), ARRAY_A);
        }
        if (get_option('wpsc_ip_lock_downloads') == 1 && $_SERVER['REMOTE_ADDR'] != null) {
            $ip_number = $_SERVER['REMOTE_ADDR'];
            if ($download_data['ip_number'] == '') {
                // if the IP number is not set, set it
                $wpdb->update(WPSC_TABLE_DOWNLOAD_STATUS, array('ip_number' => $ip_number), array('id' => $download_data['id']));
            } else {
                if ($ip_number != $download_data['ip_number']) {
                    // if the IP number is set but does not match, fail here.
                    exit(_e('This download is no longer valid, Please contact the site administrator for more information.', 'wpsc'));
                }
            }
        }
        $file_id = $download_data['fileid'];
        $file_data = wpsc_get_downloadable_file($file_id);
        if ($file_data == null) {
            exit(_e('This download is no longer valid, Please contact the site administrator for more information.', 'wpsc'));
        }
        if ($download_data != null) {
            if ((int) $download_data['downloads'] >= 1) {
                $download_count = (int) $download_data['downloads'] - 1;
            } else {
                $download_count = 0;
            }
            $wpdb->update(WPSC_TABLE_DOWNLOAD_STATUS, array('downloads' => $download_count), array('id' => $download_data['id']));
            $cart_contents = $wpdb->get_results($wpdb->prepare("SELECT `" . WPSC_TABLE_CART_CONTENTS . "`.*, {$wpdb->posts}.`guid` FROM `" . WPSC_TABLE_CART_CONTENTS . "` LEFT JOIN {$wpdb->posts} ON `" . WPSC_TABLE_CART_CONTENTS . "`.`prodid`= {$wpdb->posts}.`post_parent` WHERE {$wpdb->posts}.`post_type` = 'wpsc-product-file' AND `purchaseid` = %d", $download_data['purchid']), ARRAY_A);
            $dl = 0;
            foreach ($cart_contents as $cart_content) {
                if ($cart_content['guid'] == 1) {
                    $dl++;
                }
            }
            if (count($cart_contents) == $dl) {
                wpsc_update_purchase_log_status($download_data['purchid'], 4);
            }
            _wpsc_force_download_file($file_id);
        } else {
            exit(_e('This download is no longer valid, Please contact the site administrator for more information.', 'wpsc'));
        }
    }
}
function gourlwpecommerce_gourlcallback($user_id, $order_id, $payment_details, $box_status)
{
    global $wpdb, $wpsc_merchant;
    if (!in_array($box_status, array("cryptobox_newrecord", "cryptobox_updated"))) {
        return false;
    }
    if (strpos($order_id, "order") === 0) {
        $order_id = intval(substr($order_id, 5));
    } else {
        return false;
    }
    if (!$user_id || $payment_details["status"] != "payment_received") {
        return false;
    }
    $sql = 'SELECT * FROM `' . WPSC_TABLE_PURCHASE_LOGS . '` WHERE id = ' . $order_id . ' LIMIT 1';
    $arr = $wpdb->get_row($sql, ARRAY_A);
    if (!$arr) {
        return false;
    }
    // Initialize
    $statuses = array(2 => 'Order Received', 3 => 'Accepted Payment', 4 => 'Job Dispatched', 5 => 'Closed Order');
    $ostatus = get_option(GOURLWPSC . 'ostatus');
    if (!in_array($ostatus, array_keys($statuses))) {
        $ostatus = 3;
    }
    // Accepted Payment
    $ostatus2 = get_option(GOURLWPSC . 'ostatus2');
    if (!in_array($ostatus2, array_keys($statuses))) {
        $ostatus2 = 3;
    }
    // Accepted Payment
    $coinName = ucfirst($payment_details["coinname"]);
    $amount = $payment_details["amount"] . " " . $payment_details["coinlabel"] . "&#160; ( \$" . $payment_details["amountusd"] . " )";
    $payID = $payment_details["paymentID"];
    $trID = $payment_details["tx"];
    $status = $payment_details["is_confirmed"] ? $ostatus2 : $ostatus;
    $confirmed = $payment_details["is_confirmed"] ? __('Yes', GOURLWPSC) : __('No', GOURLWPSC);
    // New Payment Received
    if ($box_status == "cryptobox_newrecord") {
        wpsc_gourl_gateway::add_order_note($order_id, sprintf(__('<b>%s</b> payment received<br>%s<br>Payment <a href="%s">id %s</a>. Awaiting network confirmation...' . ($arr["processed"] != $status ? '<br>Order status changed to: %s' : ''), GOURLWPSC), $coinName, $amount, GOURL_ADMIN . GOURL . "payments&s=payment_" . $payID, $payID, $statuses[$status]));
    }
    // Existing Payment confirmed (6+ confirmations)
    if ($payment_details["is_confirmed"]) {
        wpsc_gourl_gateway::add_order_note($order_id, sprintf(__('%s Payment id <a href="%s">%s</a> Confirmed' . ($arr["processed"] != $status ? '<br>Order status changed to: %s' : ''), GOURLWPSC), $coinName, GOURL_ADMIN . GOURL . "payments&s=payment_" . $payID, $payID, $statuses[$status]));
    }
    // Update Order Status
    wpsc_update_purchase_log_status($order_id, $status);
    wpsc_update_purchase_log_details($order_id, array('transactid' => $trID));
    // WP eCommerce not use new updated order status, therefore need to refresh page manually
    if (in_array($status, array(3, 4, 5)) && !in_array($arr["processed"], array(3, 4, 5)) && !stripos($_SERVER["REQUEST_URI"], "cryptobox.callback.php")) {
        header('Location: ' . $_SERVER["REQUEST_URI"]);
        echo "<script>window.location.href = '" . $_SERVER["REQUEST_URI"] . "';</script>";
        die;
    }
    return true;
}