function transaction_results($sessionid, $echo_to_screen = true, $transaction_id = null)
{
    global $wpdb, $wpsc_cart, $wpsc_shipping_modules;
    echo $sessionid;
    //$curgateway = get_option('payment_gateway');
    $curgateway = $wpdb->get_var("SELECT gateway FROM " . WPSC_TABLE_PURCHASE_LOGS . " WHERE sessionid='{$sessionid}'");
    $errorcode = 0;
    $order_status = 2;
    /*
     * {Notes} Double check that $Echo_To_Screen is a boolean value
     */
    $echo_to_screen = !is_bool($echo_to_screen) ? true : $echo_to_screen;
    //exit('triggered but with errors?'.$echo_to_screen);
    if (is_numeric($sessionid)) {
        if ($echo_to_screen) {
            echo apply_filters('wpsc_pre_transaction_results', '');
        }
        $purchase_log = $wpdb->get_row("SELECT * FROM `" . WPSC_TABLE_PURCHASE_LOGS . "` WHERE `sessionid`= " . $sessionid . " LIMIT 1", ARRAY_A);
        $thepurchlogitem = new wpsc_purchaselogs_items((int) $purchase_log['id']);
        if ($purchase_log['gateway'] == "testmode" && $purchase_log['processed'] < 2) {
            $message = stripslashes(get_option('wpsc_email_receipt'));
            $message_html = $message;
        } else {
            $message = stripslashes(get_option('wpsc_email_receipt'));
            $message_html = $message;
        }
        $order_url = site_url("/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 __('We&#39;re Sorry, your order has not been accepted, the most likely reason is that you have insufficient funds.', 'wpsc');
                if (get_option('purch_log_email') != null && $purchase_log['email_sent'] != 1) {
                    wp_mail(get_option('purch_log_email'), __('New pending order', 'wpsc'), __('There is a new order awaiting processing:', 'wpsc') . $order_url, "From: " . get_option('return_email') . "");
                }
                return false;
            } else {
                if ($purchase_log['processed'] < 2) {
                    //added by Thomas on 20/6/2007
                    echo __('Thank you, your purchase is pending, you will be sent an email once the order clears.', 'wpsc') . "<p style='margin: 1em 0px 0px 0px;' >" . nl2br(stripslashes(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'), __('New pending order', 'wpsc'), __('There is a new order awaiting processing:', 'wpsc').$order_url, "From: ".get_option('return_email')."");
                    			}
                    			return false;
                    		}*/
                }
            }
        }
        if (isset($_GET['ssl_result_message']) && $_GET['ssl_result_message'] == 'APPROVAL') {
            $order_status = 2;
            $purchase_log['processed'] = 2;
        }
        $cart = $wpdb->get_results("SELECT * FROM `" . WPSC_TABLE_CART_CONTENTS . "` WHERE `purchaseid`='{$purchase_log['id']}'", ARRAY_A);
        if ($purchase_log['shipping_country'] != '') {
            $billing_country = $purchase_log['billing_country'];
            $shipping_country = $purchase_log['shipping_country'];
        } else {
            $country = $wpdb->get_var("SELECT `value` FROM `" . WPSC_TABLE_SUBMITED_FORM_DATA . "` WHERE `log_id`=" . $purchase_log['id'] . " AND `form_id` = '" . get_option('country_form_field') . "' LIMIT 1");
            $billing_country = $country;
            $shipping_country = $country;
        }
        $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 = $wpdb->get_var("SELECT `value` FROM `" . WPSC_TABLE_SUBMITED_FORM_DATA . "` WHERE `log_id`=" . $purchase_log['id'] . " AND `form_id` = '" . $email_form_field[0]['id'] . "' LIMIT 1");
        $stock_adjusted = false;
        $previous_download_ids = array(0);
        $product_list = '';
        if ($cart != null && $errorcode == 0) {
            foreach ($cart as $row) {
                $link = "";
                $product_data = $wpdb->get_row("SELECT * FROM `" . WPSC_TABLE_PRODUCT_LIST . "` WHERE `id`='{$row['prodid']}' LIMIT 1", ARRAY_A);
                if ($purchase_log['email_sent'] != 1) {
                    $wpdb->query("UPDATE `" . WPSC_TABLE_DOWNLOAD_STATUS . "` SET `active`='1' WHERE (`fileid` = '{$product_data['file']}' OR `cartid` = '{$row['id']}' ) AND `purchid` = '{$purchase_log['id']}'");
                }
                do_action('wpsc_transaction_result_cart_item', array("purchase_id" => $purchase_log['id'], "cart_item" => $row, "purchase_log" => $purchase_log));
                if ($purchase_log['processed'] >= 2) {
                    $download_data = $wpdb->get_results("SELECT * FROM `" . WPSC_TABLE_DOWNLOAD_STATUS . "`\r\n\t\t\t\t\t INNER JOIN `" . WPSC_TABLE_PRODUCT_FILES . "`\r\n\t\t\t\t\t  ON `" . WPSC_TABLE_DOWNLOAD_STATUS . "`.`fileid` = `" . WPSC_TABLE_PRODUCT_FILES . "`.`id`\r\n\t\t\t\t\t  WHERE `" . WPSC_TABLE_DOWNLOAD_STATUS . "`.`active`='1'\r\n\t\t\t\t\t  AND `" . WPSC_TABLE_DOWNLOAD_STATUS . "`.`purchid`='" . $purchase_log['id'] . "'\r\n\t\t\t\t\t  AND (\r\n\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\tAND `" . 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" => site_url("?downloadid=" . $single_download['id']), "name" => $single_download["filename"]);
                            } else {
                                $link[] = array("url" => site_url("?downloadid=" . $single_download['uniqueid']), "name" => $single_download["filename"]);
                            }
                        }
                        //$order_status= 4;
                    } else {
                        $order_status = $purchase_log['processed'];
                    }
                    $previous_download_ids[] = $download_data['id'];
                    do_action('wpsc_confirm_checkout', $purchase_log['id']);
                }
                //	do_action('wpsc_confirm_checkout', $purchase_log['id']);
                $shipping = $row['pnp'];
                $total_shipping += $shipping;
                if ($product_data['special'] == 1) {
                    $price_modifier = $product_data['special_price'];
                } else {
                    $price_modifier = 0;
                }
                $total += $row['price'] * $row['quantity'];
                $message_price = nzshpcrt_currency_display($row['price'] * $row['quantity'], $product_data['notax'], true);
                $shipping_price = nzshpcrt_currency_display($shipping, 1, true);
                $variation_values = $wpdb->get_col("SELECT `value_id`  FROM `" . WPSC_TABLE_CART_ITEM_VARIATIONS . "` WHERE `cart_id`='{$row['id']}'");
                //echo "<pre>".print_r($product_data,true)."</pre>";
                $variation_count = count($variation_values);
                if ($purchase['gateway'] != 'testmode') {
                    if ($gateway['internalname'] == $purch_data[0]['gateway']) {
                        $gateway_name = $gateway['name'];
                    }
                } else {
                    $gateway_name = "Manual Payment";
                }
                //echo "<pre>".print_r($variation_values,true)."</pre>";
                $variation_list = '';
                if ($variation_count > 0) {
                    $value_names = $wpdb->get_col("SELECT `name` FROM `" . WPSC_TABLE_VARIATION_VALUES . "` WHERE `id` IN ('" . implode("','", $variation_values) . "')");
                    $variation_list = " (" . stripslashes(implode(", ", $value_names)) . ")";
                }
                if ($link != '' && !empty($link)) {
                    $additional_content = apply_filters('wpsc_transaction_result_content', array("purchase_id" => $purchase_log['id'], "cart_item" => $row, "purchase_log" => $purchase_log));
                    if (!is_string($additional_content)) {
                        $additional_content = '';
                    }
                    //$product_list .= " - ". $product_data['name'] . stripslashes($variation_list) ."  ".$message_price ." ".__('Click to download', 'wpsc').":\n\r $link\n\r".$additional_content;
                    //$product_list_html .= " - ". $product_data['name'] . stripslashes($variation_list) ."  ".$message_price ."&nbsp;&nbsp;<a href='$link'>".__('Click to download', 'wpsc')."</a>\n". $additional_content;
                    $product_list .= " - " . $product_data['name'] . stripslashes($variation_list) . "  " . $message_price;
                    $product_list_html .= " - " . $product_data['name'] . stripslashes($variation_list) . "  " . $message_price;
                    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";
                        $report_product_list .= "\n\r " . $single_link["name"] . ": " . $single_link["url"] . "\n\r";
                        //	$report_product_list .="<a href='".$single_link["url"]."'>".$single_link["name"]."</a>\n";
                    }
                    $product_list .= $additional_content;
                    $product_list_html .= $additional_content;
                } else {
                    $plural = '';
                    if ($row['quantity'] > 1) {
                        $plural = "s";
                    }
                    $product_list .= $row['quantity'] . " - " . $product_data['name'] . stripslashes($variation_list) . "  " . $message_price . "\n\r";
                    if ($shipping > 0) {
                        $product_list .= " - " . __('Shipping', 'wpsc') . ":" . $shipping_price . "\n\r";
                    }
                    $product_list_html .= $row['quantity'] . " -  " . $product_data['name'] . stripslashes($variation_list) . "  " . $message_price . "\n\r";
                    if ($shipping > 0) {
                        $product_list_html .= " &nbsp; " . __('Shipping', 'wpsc') . ":" . $shipping_price . "\n\r";
                    }
                    $report_product_list .= $row['quantity'] . " - " . $product_data['name'] . stripslashes($variation_list) . "  " . $message_price . "\n\r";
                }
                $report = get_option('wpsc_email_admin');
            }
            // Decrement the stock here
            if ($purchase_log['processed'] >= 2) {
                wpsc_decrement_claimed_stock($purchase_log['id']);
            }
            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['file']."' AND `purchid` = '".$purchase_log['id']."' LIMIT 1");
            //if (!isset($_SESSION['quote_shipping']))
            //$total_shipping = nzshpcrt_determine_base_shipping($total_shipping, $shipping_country);
            $total_shipping += $purchase_log['base_shipping'];
            $total = $purchase_log['totalprice'];
            // echo $total;
            // $message.= "\n\r";
            $product_list .= "Your Purchase No.: " . $purchase_log['id'] . "\n\r";
            if ($purchase_log['discount_value'] > 0) {
                $discount_email .= __('Discount', 'wpsc') . "\n\r: ";
                $discount_email .= $purchase_log['discount_data'] . ' : ' . 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) {
                $report .= $discount_email . "\n\r";
                $total_shipping_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 # " . $purchase_log['id'] . "\n\r";
            }
            //echo "<pre>".print_r($purchase_log,true)."</pre>";
            $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('%shop_name%', get_option('blogname'), $message);
            $message = str_replace('%find_us%', $purchase_log['find_us'], $message);
            //$message = str_replace('%order_status%',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);
            $report = str_replace('%find_us%', $purchase_log['find_us'], $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);
            $message_html = str_replace('%find_us%', $purchase_log['find_us'], $message_html);
            //$message_html = str_replace('%order_status%',get_option('blogname'),$message_html);
            if ($email != '' && $purchase_log['email_sent'] != 1) {
                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;
                    wp_mail($email, __('Order Pending: Payment Required', 'wpsc'), $message);
                } else {
                    wp_mail($email, __('Purchase Receipt', 'wpsc'), $message);
                }
            }
            remove_filter('wp_mail_from_name', 'wpsc_replace_reply_name');
            remove_filter('wp_mail_from', 'wpsc_replace_reply_address');
            $report_user = __('Customer Details', 'wpsc') . "\n\r";
            $report_user .= "Billing Info \n\r";
            foreach ((array) $thepurchlogitem->userinfo as $userinfo) {
                if ($userinfo['unique_name'] != 'billingcountry') {
                    $report_user .= "" . $userinfo['name'] . ": " . $userinfo['value'] . "\n";
                } else {
                    $userinfo['value'] = maybe_unserialize($userinfo['value']);
                    if (is_array($userinfo['value'])) {
                        if (!empty($userinfo['value'][1]) && !is_numeric($userinfo['value'][1])) {
                            $report_user .= "State: " . $userinfo['value'][1] . "\n";
                        } elseif (is_numeric($userinfo['value'][1])) {
                            $report_user .= "State: " . wpsc_get_state_by_id($userinfo['value'][1], 'name') . "\n";
                        }
                        if (!empty($userinfo['value'][0])) {
                            $report_user .= "Country: " . $userinfo['value'][0] . "\n";
                        }
                    } else {
                        $report_user .= "" . $userinfo['name'] . ": " . $userinfo['value'] . "\n";
                    }
                }
            }
            $report_user .= "\n\rShipping Info \n\r";
            foreach ((array) $thepurchlogitem->shippinginfo as $userinfo) {
                if ($userinfo['unique_name'] != 'shippingcountry' && $userinfo['unique_name'] != 'shippingstate') {
                    $report_user .= "" . $userinfo['name'] . ": " . $userinfo['value'] . "\n";
                } elseif ($userinfo['unique_name'] == 'shippingcountry') {
                    $userinfo['value'] = maybe_unserialize($userinfo['value']);
                    if (is_array($userinfo['value'])) {
                        if (!empty($userinfo['value'][1]) && !is_numeric($userinfo['value'][1])) {
                            $report_user .= "State: " . $userinfo['value'][1] . "\n";
                        } elseif (is_numeric($userinfo['value'][1])) {
                            $report_user .= "State: " . wpsc_get_state_by_id($userinfo['value'][1], 'name') . "\n";
                        }
                        if (!empty($userinfo['value'][0])) {
                            $report_user .= "Country: " . $userinfo['value'][0] . "\n";
                        }
                    } else {
                        $report_user .= "" . $userinfo['name'] . ": " . $userinfo['value'] . "\n";
                    }
                } elseif ($userinfo['unique_name'] == 'shippingstate') {
                    if (!empty($userinfo['value']) && !is_numeric($userinfo['value'])) {
                        $report_user .= "" . $userinfo['name'] . ": " . $userinfo['value'] . "\n";
                    } elseif (is_numeric($userinfo['value'])) {
                        $report_user .= "State: " . wpsc_get_state_by_id($userinfo['value'], 'name') . "\n";
                    }
                }
            }
            $report_user .= "\n\r";
            /*
            				$form_sql = "SELECT * FROM `".WPSC_TABLE_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_data = $wpdb->get_row("SELECT * FROM `".WPSC_TABLE_CHECKOUT_FORMS."` WHERE `id` = '".$form_field['form_id']."' LIMIT 1", ARRAY_A);
            
            						switch($form_data['type']) {
            							case "country":
            							$report_user .= $form_data['name'].": ".wpsc_get_country($form_field['value'])."\n";
            							$report_user .= __('State', 'wpsc').": ".wpsc_get_region($purchase_log['billing_region'])."\n";
            							break;
            							
            							case "delivery_country":
            							$report_user .= $form_data['name'].": ".wpsc_get_country($form_field['value'])."\n";
            							$report_user .= __('Delivery State', 'wpsc').": ".wpsc_get_region($purchase_log['shipping_region'])."\n";
            							break;
            							
            							default:
            							$report_user .= wp_kses($form_data['name'], array()).": ".$form_field['value']."\n";
            							break;
            						}
            					}
            				}
            	
            				$report_user .= "\n\r";
            */
            $report = $report_user . $report_id . $report;
            if ($stock_adjusted == true) {
                $wpdb->query("UPDATE `" . WPSC_TABLE_PURCHASE_LOGS . "` SET `stock_adjusted` = '1' WHERE `sessionid` = " . $sessionid . " LIMIT 1");
            }
            if (get_option('purch_log_email') != null && $purchase_log['email_sent'] != 1) {
                wp_mail(get_option('purch_log_email'), __('Purchase Report', 'wpsc'), $report);
            }
            if ($purchase_log['processed'] < 2) {
                echo "<br />" . nl2br(str_replace("\$", '\\$', $message_html));
                return;
            }
            /// Empty the cart
            $wpsc_cart->submit_stock_claims($purchase_log['id']);
            $wpsc_cart->empty_cart();
            if (true === $echo_to_screen) {
                echo '<div class="wrap">';
                if ($sessionid != null) {
                    echo __('The Transaction was successful', 'wpsc') . "<br />";
                    echo "<br />" . nl2br(str_replace("\$", '\\$', $message_html));
                }
                echo '</div>';
            }
        } else {
            if (true === $echo_to_screen) {
                echo '<div class="wrap">';
                echo __('Oops, there is nothing in your cart.', 'wpsc') . "<a href='" . get_option("product_list_url") . "'>" . __('Please visit our shop', 'wpsc') . "</a>";
                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 `" . WPSC_TABLE_PURCHASE_LOGS . "` SET {$transact_id_sql} `email_sent` = '1', `processed` = '{$order_status}' WHERE `sessionid` = " . $sessionid . " LIMIT 1";
            $wpdb->query($update_sql);
        }
    }
}
/**
 * Routine that runs when updating a purchase log's status, used to update status of inventory.
 *
 * @since  4.0
 *
 * @param  int               $id             Purchase Log ID.
 * @param  int               $status         Current status.
 * @param  int               $old_status     Previous status.
 * @param  WPSC_Purchase_Log $purchase_log   Purchase Log Object.
 *
 * @return void
 */
function _wpsc_update_purchase_log_stock_status($id, $status, $old_status, $purchase_log)
{
    if (!$purchase_log->is_transaction_completed()) {
        return;
    }
    $already_processed = in_array($old_status, array(WPSC_Purchase_Log::ACCEPTED_PAYMENT, WPSC_Purchase_Log::JOB_DISPATCHED, WPSC_Purchase_Log::CLOSED_ORDER));
    if ($already_processed) {
        return;
    }
    wpsc_decrement_claimed_stock($id);
}
function transaction_results($sessionid, $echo_to_screen = true, $transaction_id = null)
{
    global $wpdb, $wpsc_cart;
    //$curgateway = get_option('payment_gateway');
    $curgateway = $wpdb->get_var("SELECT gateway FROM " . WPSC_TABLE_PURCHASE_LOGS . " WHERE sessionid='{$sessionid}'");
    $errorcode = 0;
    $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;
    //exit('triggered but with errors?'.$echo_to_screen);
    if (is_numeric($sessionid)) {
        if ($echo_to_screen) {
            echo apply_filters('wpsc_pre_transaction_results', '');
        }
        $purchase_log = $wpdb->get_row("SELECT * FROM `" . WPSC_TABLE_PURCHASE_LOGS . "` WHERE `sessionid`= " . $sessionid . " LIMIT 1", ARRAY_A);
        if ($purchase_log['gateway'] == "testmode" && $purchase_log['processed'] < 2) {
            $message = get_option('wpsc_email_receipt');
            $message_html = $message;
        } 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'];
        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) {
                    wp_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;
                    		}*/
                }
            }
        }
        $cart = $wpdb->get_results("SELECT * FROM `" . WPSC_TABLE_CART_CONTENTS . "` WHERE `purchaseid`='{$purchase_log['id']}'", ARRAY_A);
        if ($purchase_log['shipping_country'] != '') {
            $billing_country = $purchase_log['billing_country'];
            $shipping_country = $purchase_log['shipping_country'];
        } else {
            $country = $wpdb->get_var("SELECT `value` FROM `" . WPSC_TABLE_SUBMITED_FORM_DATA . "` WHERE `log_id`=" . $purchase_log['id'] . " AND `form_id` = '" . get_option('country_form_field') . "' LIMIT 1");
            $billing_country = $country;
            $shipping_country = $country;
        }
        $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 = $wpdb->get_var("SELECT `value` FROM `" . WPSC_TABLE_SUBMITED_FORM_DATA . "` WHERE `log_id`=" . $purchase_log['id'] . " AND `form_id` = '" . $email_form_field[0]['id'] . "' LIMIT 1");
        $stock_adjusted = false;
        $previous_download_ids = array(0);
        $product_list = '';
        if ($cart != null && $errorcode == 0) {
            foreach ($cart as $row) {
                $link = "";
                $product_data = $wpdb->get_row("SELECT * FROM `" . WPSC_TABLE_PRODUCT_LIST . "` WHERE `id`='{$row['prodid']}' LIMIT 1", ARRAY_A);
                if ($purchase_log['email_sent'] != 1) {
                    $wpdb->query("UPDATE `" . WPSC_TABLE_DOWNLOAD_STATUS . "` SET `active`='1' WHERE (`fileid` = '{$product_data['file']}' OR `cartid` = '{$row['id']}' ) AND `purchid` = '{$purchase_log['id']}'");
                }
                do_action('wpsc_transaction_result_cart_item', array("purchase_id" => $purchase_log['id'], "cart_item" => $row, "purchase_log" => $purchase_log));
                if ($purchase_log['processed'] >= 2) {
                    //echo "SELECT * FROM `".WPSC_TABLE_DOWNLOAD_STATUS."` WHERE `active`='1' AND `purchid`='".$purchase_log['id']."' AND (`cartid` = '".$row['id']."' OR (`cartid` IS NULL AND `fileid` = '{$product_data['file']}') ) AND `id` NOT IN ('".implode("','",$previous_download_ids)."') LIMIT 1";
                    $download_data = $wpdb->get_row("SELECT * FROM `" . WPSC_TABLE_DOWNLOAD_STATUS . "` WHERE `active`='1' AND `purchid`='" . $purchase_log['id'] . "' AND (`cartid` = '" . $row['id'] . "' OR (`cartid` IS NULL AND `fileid` = '{$product_data['file']}') ) AND `id` NOT IN ('" . implode("','", $previous_download_ids) . "') LIMIT 1", ARRAY_A);
                    //exit('IM HERE'.$errorcode.'<pre>'.print_r($download_data).'</pre>');
                    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'];
                        }
                        //$order_status= 4;
                    } else {
                        $order_status = $purchase_log['processed'];
                    }
                    $previous_download_ids[] = $download_data['id'];
                }
                do_action('wpsc_confirm_checkout', $purchase_log['id']);
                $shipping = $row['pnp'] * $row['quantity'];
                $total_shipping += $shipping;
                if ($product_data['special'] == 1) {
                    $price_modifier = $product_data['special_price'];
                } else {
                    $price_modifier = 0;
                }
                $total += $row['price'] * $row['quantity'];
                $message_price = nzshpcrt_currency_display($row['price'] * $row['quantity'], $product_data['notax'], true);
                $shipping_price = nzshpcrt_currency_display($shipping, 1, true);
                $variation_values = $wpdb->get_col("SELECT `value_id`  FROM `" . WPSC_TABLE_CART_ITEM_VARIATIONS . "` WHERE `cart_id`='{$row['id']}'");
                //echo "<pre>".print_r($product_data,true)."</pre>";
                $variation_count = count($variation_values);
                if ($purchase['gateway'] != 'testmode') {
                    if ($gateway['internalname'] == $purch_data[0]['gateway']) {
                        $gateway_name = $gateway['name'];
                    }
                } else {
                    $gateway_name = "Manual Payment";
                }
                //echo "<pre>".print_r($variation_values,true)."</pre>";
                $variation_list = '';
                if ($variation_count > 0) {
                    $value_names = $wpdb->get_col("SELECT `name` FROM `" . WPSC_TABLE_VARIATION_VALUES . "` WHERE `id` IN ('" . implode("','", $variation_values) . "')");
                    $variation_list = " (" . stripslashes(implode(", ", $value_names)) . ")";
                }
                if ($link != '') {
                    $additional_content = apply_filters('wpsc_transaction_result_content', array("purchase_id" => $purchase_log['id'], "cart_item" => $row, "purchase_log" => $purchase_log));
                    if (!is_string($additional_content)) {
                        $additional_content = '';
                    }
                    $product_list .= " - " . $product_data['name'] . stripslashes($variation_list) . "  " . $message_price . " " . TXT_WPSC_CLICKTODOWNLOAD . ":\n\r {$link}\n\r" . $additional_content;
                    $product_list_html .= " - " . $product_data['name'] . stripslashes($variation_list) . "  " . $message_price . "&nbsp;&nbsp;<a href='{$link}'>" . TXT_WPSC_CLICKTODOWNLOAD . "</a>\n" . $additional_content;
                } else {
                    $plural = '';
                    if ($row['quantity'] > 1) {
                        $plural = "s";
                    }
                    $product_list .= " - " . $row['quantity'] . " " . $product_data['name'] . stripslashes($variation_list) . "  " . $message_price . "\n\r";
                    if ($shipping > 0) {
                        $product_list .= " - " . TXT_WPSC_SHIPPING . ":" . $shipping_price . "\n\r";
                    }
                    $product_list_html .= " - " . $row['quantity'] . " " . $product_data['name'] . stripslashes($variation_list) . "  " . $message_price . "\n\r";
                    if ($shipping > 0) {
                        $product_list_html .= " &nbsp; " . TXT_WPSC_SHIPPING . ":" . $shipping_price . "\n\r";
                    }
                }
                $report = get_option('wpsc_email_admin');
                $report_product_list .= " - " . $product_data['name'] . stripslashes($variation_list) . "  " . $message_price . "\n\r";
            }
            // KTTODO - call out to ezprints here
            if ($purchase_log['processed'] >= 2 && $purchase_log['ezprints_order_sent_count'] < 1) {
                $ezprints_body = sendEzPrintsOrder($purchase_log['id']);
                $wpdb->query("UPDATE `" . WPSC_TABLE_PURCHASE_LOGS . "` SET `ezprints_order_sent_count` = 1 WHERE `id` = " . $purchase_log['id'] . " LIMIT 1");
            }
            // Decrement the stock here
            if ($purchase_log['processed'] >= 2) {
                wpsc_decrement_claimed_stock($purchase_log['id']);
            }
            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['file']."' AND `purchid` = '".$purchase_log['id']."' LIMIT 1");
            //if (!isset($_SESSION['quote_shipping']))
            //$total_shipping = nzshpcrt_determine_base_shipping($total_shipping, $shipping_country);
            $total_shipping += $purchase_log['base_shipping'];
            $total = $purchase_log['totalprice'];
            // echo $total;
            // $message.= "\n\r";
            $product_list .= "Your Purchase No.: " . $purchase_log['id'] . "\n\r";
            if ($purchase_log['discount_value'] > 0) {
                $discount_email .= TXT_WPSC_DISCOUNT . "\n\r: ";
                $discount_email .= $purchase_log['discount_data'] . ' : ' . 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) {
                $report .= $discount_email . "\n\r";
                $total_shipping_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";
            }
            //echo "<pre>".print_r($purchase_log,true)."</pre>";
            $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);
            //$message_html = str_replace('%order_status%',get_option('blogname'),$message_html);
            if ($email != '' && $purchase_log['email_sent'] != 1) {
                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;
                    wp_mail($email, TXT_WPSC_ORDER_PENDING_PAYMENT_REQUIRED, $message);
                } else {
                    wp_mail($email, TXT_WPSC_PURCHASERECEIPT, $message);
                }
            }
            remove_filter('wp_mail_from_name', 'wpsc_replace_reply_name');
            remove_filter('wp_mail_from', 'wpsc_replace_reply_address');
            $report_user = TXT_WPSC_CUSTOMERDETAILS . "\n\r";
            $form_sql = "SELECT * FROM `" . WPSC_TABLE_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_data = $wpdb->get_row("SELECT * FROM `" . WPSC_TABLE_CHECKOUT_FORMS . "` WHERE `id` = '" . $form_field['form_id'] . "' LIMIT 1", ARRAY_A);
                    switch ($form_data['type']) {
                        case "country":
                            $delivery_region_count = $wpdb->get_var("SELECT COUNT(`regions`.`id`) FROM `" . WPSC_TABLE_REGION_TAX . "` AS `regions` INNER JOIN `" . WPSC_TABLE_CURRENCY_LIST . "` AS `country` ON `country`.`id` = `regions`.`country_id` WHERE `country`.`isocode` IN('" . $wpdb->escape($purchase_log['billing_country']) . "')");
                            if (is_numeric($purchase_log['shipping_region']) && $delivery_region_count > 0) {
                                $report_user .= TXT_WPSC_STATE . ": " . wpsc_get_region($purchase_log['billing_region']) . "\n";
                            }
                            $report_user .= $form_data['name'] . ": " . wpsc_get_country($form_field['value']) . "\n";
                            break;
                        case "delivery_country":
                            $delivery_region_count = $wpdb->get_var("SELECT COUNT(`regions`.`id`) FROM `" . WPSC_TABLE_REGION_TAX . "` AS `regions` INNER JOIN `" . WPSC_TABLE_CURRENCY_LIST . "` AS `country` ON `country`.`id` = `regions`.`country_id` WHERE `country`.`isocode` IN('" . $wpdb->escape($purchase_log['shipping_country']) . "')");
                            if (is_numeric($purchase_log['shipping_region']) && $delivery_region_count > 0) {
                                $report_user .= TXT_WPSC_DELIVERY_STATE . ": " . wpsc_get_region($purchase_log['shipping_region']) . "\n";
                            }
                            $report_user .= $form_data['name'] . ": " . wpsc_get_country($form_field['value']) . "\n";
                            break;
                        default:
                            $report_user .= $form_data['name'] . ": " . $form_field['value'] . "\n";
                            break;
                    }
                }
            }
            $report_user .= "\n\r";
            $report = $report_user . $report_id . $report;
            if ($stock_adjusted == true) {
                $wpdb->query("UPDATE `" . WPSC_TABLE_PURCHASE_LOGS . "` SET `stock_adjusted` = '1' WHERE `sessionid` = " . $sessionid . " LIMIT 1");
            }
            if (get_option('purch_log_email') != null && $purchase_log['email_sent'] != 1) {
                wp_mail(get_option('purch_log_email'), TXT_WPSC_PURCHASEREPORT, $report);
            }
            if ($purchase_log['processed'] < 2) {
                echo "<br />" . nl2br(str_replace("\$", '\\$', $message_html));
                return;
            }
            /// Empty the cart
            $wpsc_cart->submit_stock_claims($purchase_log['id']);
            $wpsc_cart->empty_cart();
            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 `" . WPSC_TABLE_PURCHASE_LOGS . "` SET {$transact_id_sql} `email_sent` = '1', `processed` = '{$order_status}' WHERE `sessionid` = " . $sessionid . " LIMIT 1";
            $wpdb->query($update_sql);
        }
    }
}
function _wpsc_action_update_purchase_log_status($id, $status, $old_status, $purchase_log)
{
    if ($purchase_log->is_order_received() || $purchase_log->is_accepted_payment()) {
        wpsc_send_customer_email($purchase_log);
        wpsc_send_admin_email($purchase_log);
    }
    if (!$purchase_log->is_transaction_completed()) {
        return;
    }
    $already_processed = in_array($old_status, array(WPSC_Purchase_Log::ACCEPTED_PAYMENT, WPSC_Purchase_Log::JOB_DISPATCHED, WPSC_Purchase_Log::CLOSED_ORDER));
    if ($already_processed) {
        return;
    }
    _wpsc_process_transaction_coupon($purchase_log);
    wpsc_decrement_claimed_stock($id);
}
function _wpsc_action_update_purchase_log_status($id, $status, $old_status, $purchase_log)
{
    wpsc_send_customer_email($purchase_log);
    wpsc_send_admin_email($purchase_log);
    if (!$purchase_log->is_transaction_completed()) {
        return;
    }
    _wpsc_process_transaction_coupon($purchase_log);
    wpsc_decrement_claimed_stock($id);
}
Example #6
0
function wpsc_purchlog_edit_status($purchlog_id = '', $purchlog_status = '')
{
    global $wpdb;
    if (empty($purchlog_id) && empty($purchlog_status)) {
        $purchlog_id = absint($_POST['purchlog_id']);
        $purchlog_status = absint($_POST['purchlog_status']);
    }
    $log_data = $wpdb->get_row("SELECT * FROM `" . WPSC_TABLE_PURCHASE_LOGS . "` WHERE `id` = '{$purchlog_id}' LIMIT 1", ARRAY_A);
    $is_transaction = wpsc_check_purchase_processed($log_data['processed']);
    if ($is_transaction && function_exists('wpsc_member_activate_subscriptions')) {
        wpsc_member_activate_subscriptions($_POST['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' => $log_data, 'new_status' => $purchlog_status));
    $wpdb->update(WPSC_TABLE_PURCHASE_LOGS, array('processed' => $purchlog_status), array('id' => $purchlog_id), '%d', '%d');
    wpsc_clear_stock_claims();
    wpsc_decrement_claimed_stock($purchlog_id);
    if ($purchlog_status == 3) {
        transaction_results($log_data['sessionid'], false, null);
    }
}
/**
 * transaction_results function main function for creating the purchase reports, transaction results page, and email receipts
 * @access public
 *
 * @since 3.7
 * @param $sessionid (string) unique session id
 * @param echo_to_screen (boolean) whether to output the results or return them (potentially redundant)
 * @param $transaction_id (int) the transaction id
 */
function transaction_results($sessionid, $display_to_screen = true, $transaction_id = null)
{
    // Do we seriously need this many globals?
    global $wpdb, $wpsc_cart, $echo_to_screen, $purchase_log, $order_url;
    global $message_html, $cart, $errorcode, $wpsc_purchlog_statuses, $wpsc_gateways;
    $wpec_taxes_controller = new wpec_taxes_controller();
    $is_transaction = false;
    $errorcode = 0;
    $purchase_log = $wpdb->get_row($wpdb->prepare("SELECT * FROM `" . WPSC_TABLE_PURCHASE_LOGS . "` WHERE `sessionid`= %s LIMIT 1", $sessionid), ARRAY_A);
    $order_status = $purchase_log['processed'];
    $curgateway = $purchase_log['gateway'];
    if (!is_bool($display_to_screen)) {
        $display_to_screen = true;
    }
    $echo_to_screen = $display_to_screen;
    //new variable to check whether function is being called from wpsc_purchlog_resend_email()
    $resend_email = isset($_REQUEST['email_buyer_id']) ? true : false;
    if (is_numeric($sessionid)) {
        if ($echo_to_screen) {
            echo apply_filters('wpsc_pre_transaction_results', '');
        }
        // New code to check whether transaction is processed, true if accepted false if pending or incomplete
        $is_transaction = wpsc_check_purchase_processed($purchase_log['processed']);
        $message_html = $message = stripslashes(get_option('wpsc_email_receipt'));
        if ($is_transaction) {
            $message = __('The Transaction was successful', 'wpsc') . "\r\n" . $message;
            $message_html = __('The Transaction was successful', 'wpsc') . "<br />" . $message_html;
        }
        $country = get_option('country_form_field');
        $billing_country = '';
        $shipping_country = '';
        if (!empty($purchase_log['shipping_country'])) {
            $billing_country = $purchase_log['billing_country'];
            $shipping_country = $purchase_log['shipping_country'];
        } elseif (!empty($country)) {
            $country = $wpdb->get_var($wpdb->prepare("SELECT `value` FROM `" . WPSC_TABLE_SUBMITED_FORM_DATA . "` WHERE `log_id` = %d AND `form_id` = %d LIMIT 1", $purchase_log['id'], get_option('country_form_field')));
            $billing_country = $country;
            $shipping_country = $country;
        }
        $email = wpsc_get_buyers_email($purchase_log['id']);
        $previous_download_ids = array();
        $product_list = $product_list_html = $report_product_list = '';
        $cart = $wpdb->get_results($wpdb->prepare("SELECT * FROM `" . WPSC_TABLE_CART_CONTENTS . "` WHERE `purchaseid` = %d", $purchase_log['id']), ARRAY_A);
        if ($cart != null && $errorcode == 0) {
            $total_shipping = '';
            foreach ($cart as $row) {
                $link = array();
                $wpdb->update(WPSC_TABLE_DOWNLOAD_STATUS, array('active' => '1'), array('cartid' => $row['id'], 'purchid' => $purchase_log['id']));
                do_action('wpsc_transaction_result_cart_item', array("purchase_id" => $purchase_log['id'], "cart_item" => $row, "purchase_log" => $purchase_log));
                if ($is_transaction) {
                    $download_data = $wpdb->get_results($wpdb->prepare("SELECT *\n\t\t\t\t\tFROM `" . WPSC_TABLE_DOWNLOAD_STATUS . "`\n\t\t\t\t\tWHERE `active`='1'\n\t\t\t\t\tAND `purchid` = %d\n\t\t\t\t\tAND `cartid` = %d", $purchase_log['id'], $row['id']), ARRAY_A);
                    if (count($download_data) > 0) {
                        foreach ($download_data as $single_download) {
                            $file_data = get_post($single_download['product_id']);
                            // if the uniqueid is not equal to null, its "valid", regardless of what it is
                            $argsdl = array('post_type' => 'wpsc-product-file', 'post_parent' => $single_download['product_id'], 'numberposts' => -1, 'post_status' => 'all');
                            $download_file_posts = (array) get_posts($argsdl);
                            foreach ((array) $download_file_posts as $single_file_post) {
                                if ($single_file_post->ID == $single_download['fileid']) {
                                    $current_Dl_product_file_post = $single_file_post;
                                    break;
                                }
                            }
                            $file_name = $current_Dl_product_file_post->post_title;
                            if ($single_download['uniqueid'] == null) {
                                $link[] = array("url" => site_url("?downloadid=" . $single_download['id']), "name" => $file_name);
                            } else {
                                $link[] = array("url" => site_url("?downloadid=" . $single_download['uniqueid']), "name" => $file_name);
                            }
                        }
                    } else {
                        $order_status = $purchase_log['processed'];
                    }
                    if (isset($download_data['id'])) {
                        $previous_download_ids[] = $download_data['id'];
                    }
                }
                do_action('wpsc_confirm_checkout', $purchase_log['id']);
                $total = 0;
                $shipping = $row['pnp'];
                $total_shipping += $shipping;
                $total += $row['price'] * $row['quantity'];
                $message_price = wpsc_currency_display($total, array('display_as_html' => false));
                $message_price_html = wpsc_currency_display($total);
                $shipping_price = wpsc_currency_display($shipping, array('display_as_html' => false));
                if (isset($purchase['gateway']) && 'wpsc_merchant_testmode' != $purchase['gateway']) {
                    if ($gateway['internalname'] == $purch_data[0]['gateway']) {
                        $gateway_name = $gateway['name'];
                    }
                } else {
                    $gateway_name = "Manual Payment";
                }
                $variation_list = '';
                if (!empty($link)) {
                    $additional_content = apply_filters('wpsc_transaction_result_content', array("purchase_id" => $purchase_log['id'], "cart_item" => $row, "purchase_log" => $purchase_log));
                    if (!is_string($additional_content)) {
                        $additional_content = '';
                    }
                    $product_list .= " - " . $row['name'] . "  " . $message_price . " " . __('Click to download', 'wpsc') . ":";
                    $product_list_html .= " - " . $row['name'] . "  " . $message_price_html . "&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";
                    }
                    $product_list .= $additional_content;
                    $product_list_html .= $additional_content;
                } else {
                    $product_list .= " - " . $row['quantity'] . " " . $row['name'] . "  " . $message_price . "\n\r";
                    if ($shipping > 0) {
                        $product_list .= sprintf(__(' - Shipping: %s
', 'wpsc'), $shipping_price);
                    }
                    $product_list_html .= "\n\r - " . $row['quantity'] . " " . $row['name'] . "  " . $message_price_html . "\n\r";
                    if ($shipping > 0) {
                        $product_list_html .= sprintf(__(' &nbsp; Shipping: %s
', 'wpsc'), $shipping_price);
                    }
                }
                //add tax if included
                if ($wpec_taxes_controller->wpec_taxes_isenabled() && $wpec_taxes_controller->wpec_taxes_isincluded()) {
                    $taxes_text = ' - - ' . __('Tax Included', 'wpsc') . ': ' . wpsc_currency_display($row['tax_charged'], array('display_as_html' => false)) . "\n\r";
                    $taxes_text_html = ' - - ' . __('Tax Included', 'wpsc') . ': ' . wpsc_currency_display($row['tax_charged']);
                    $product_list .= $taxes_text;
                    $product_list_html .= $taxes_text_html;
                }
                // if
                $report = get_option('wpsc_email_admin');
                $report_product_list .= " - " . $row['quantity'] . " " . $row['name'] . "  " . $message_price . "\n\r";
            }
            // closes foreach cart as row
            // Decrement the stock here
            if ($is_transaction) {
                wpsc_decrement_claimed_stock($purchase_log['id']);
            }
            if (!empty($purchase_log['discount_data'])) {
                $coupon_data = $wpdb->get_row($wpdb->prepare("SELECT * FROM `" . WPSC_TABLE_COUPON_CODES . "` WHERE coupon_code = %s LIMIT 1", $purchase_log['discount_data']), ARRAY_A);
                if ($coupon_data['use-once'] == 1) {
                    $wpdb->update(WPSC_TABLE_COUPON_CODES, array('active' => '0', 'is-used' => '1'), array('id' => $coupon_data['id']));
                }
            }
            $total_shipping = wpsc_get_total_shipping($purchase_log['id']);
            $total = $purchase_log['totalprice'];
            $total_price_email = '';
            $total_price_html = '';
            $total_tax_html = '';
            $total_tax = '';
            $total_shipping_html = '';
            $total_shipping_email = '';
            if (wpsc_uses_shipping() || !empty($purchase_log['base_shipping'])) {
                $total_shipping_email .= sprintf(__('Total Shipping: %s
	', 'wpsc'), wpsc_currency_display($total_shipping, array('display_as_html' => false)));
            }
            $total_price_email .= sprintf(__('Total: %s
', 'wpsc'), wpsc_currency_display($total, array('display_as_html' => false)));
            if ($purchase_log['discount_value'] > 0) {
                $discount_email = __('Discount', 'wpsc') . "\n\r: ";
                $discount_email .= $purchase_log['discount_data'] . ' : ' . wpsc_currency_display($purchase_log['discount_value'], array('display_as_html' => false)) . "\n\r";
                $report .= $discount_email . "\n\r";
                $total_shipping_email .= $discount_email;
                $total_shipping_html .= __('Discount', 'wpsc') . ": " . wpsc_currency_display($purchase_log['discount_value']) . "\n\r";
            }
            //only show total tax if tax is not included
            if ($wpec_taxes_controller->wpec_taxes_isenabled() && !$wpec_taxes_controller->wpec_taxes_isincluded()) {
                $total_tax_html .= __('Total Tax', 'wpsc') . ': ' . wpsc_currency_display($purchase_log['wpec_taxes_total']) . "\n\r";
                $total_tax .= __('Total Tax', 'wpsc') . ': ' . wpsc_currency_display($purchase_log['wpec_taxes_total'], array('display_as_html' => false)) . "\n\r";
            }
            if (wpsc_uses_shipping() || !empty($purchase_log['base_shipping'])) {
                $total_shipping_html .= '<hr>' . sprintf(__('Total Shipping: %s
	', 'wpsc'), wpsc_currency_display($total_shipping));
            }
            $total_price_html .= sprintf(__('Total: %s
', 'wpsc'), wpsc_currency_display($total));
            $report_id = sprintf(__("Purchase # %s\n", 'wpsc'), $purchase_log['id']);
            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'];
            }
            $message = apply_filters('wpsc_transaction_result_message', $message);
            $message = str_replace('%purchase_id%', $report_id, $message);
            $message = str_replace('%product_list%', $product_list, $message);
            $message = str_replace('%total_tax%', $total_tax, $message);
            $message = str_replace('%total_shipping%', $total_shipping_email, $message);
            $message = str_replace('%total_price%', $total_price_email, $message);
            $message = str_replace('%shop_name%', get_option('blogname'), $message);
            $message = str_replace('%find_us%', $purchase_log['find_us'], $message);
            $report = apply_filters('wpsc_transaction_result_report', $report);
            $report = str_replace('%purchase_id%', $report_id, $report);
            $report = str_replace('%product_list%', $report_product_list, $report);
            $report = str_replace('%total_tax%', $total_tax, $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);
            $report = str_replace('%find_us%', $purchase_log['find_us'], $report);
            $message_html = apply_filters('wpsc_transaction_result_message_html', $message_html);
            $message_html = str_replace('%purchase_id%', $report_id, $message_html);
            $message_html = str_replace('%product_list%', $product_list_html, $message_html);
            $message_html = str_replace('%total_tax%', $total_tax_html, $message_html);
            $message_html = str_replace('%total_shipping%', $total_shipping_html, $message_html);
            $message_html = str_replace('%total_price%', $total_price_html, $message_html);
            $message_html = str_replace('%shop_name%', get_option('blogname'), $message_html);
            $message_html = str_replace('%find_us%', $purchase_log['find_us'], $message_html);
            if (!empty($email)) {
                add_filter('wp_mail_from', 'wpsc_replace_reply_address', 0);
                add_filter('wp_mail_from_name', 'wpsc_replace_reply_name', 0);
                $message = apply_filters('wpsc_email_message', $message, $report_id, $product_list, $total_tax, $total_shipping_email, $total_price_email);
                if (!$is_transaction) {
                    $payment_instructions = strip_tags(stripslashes(get_option('payment_instructions')));
                    if (!empty($payment_instructions)) {
                        $payment_instructions .= "\n\r";
                    }
                    $message = __('Thank you, your purchase is pending, you will be sent an email once the order clears.', 'wpsc') . "\n\r" . $payment_instructions . $message;
                    $message_html = __('Thank you, your purchase is pending, you will be sent an email once the order clears.', 'wpsc') . "\n\r" . $payment_instructions . $message_html;
                    // prevent email duplicates
                    if (!get_transient("{$sessionid}_pending_email_sent") || $resend_email) {
                        wp_mail($email, __('Order Pending: Payment Required', 'wpsc'), $message);
                        set_transient("{$sessionid}_pending_email_sent", true, 60 * 60 * 12);
                    }
                } elseif (!get_transient("{$sessionid}_receipt_email_sent") || $resend_email) {
                    wp_mail($email, __('Purchase Receipt', 'wpsc'), $message);
                    set_transient("{$sessionid}_receipt_email_sent", true, 60 * 60 * 12);
                }
            }
            remove_filter('wp_mail_from_name', 'wpsc_replace_reply_name');
            remove_filter('wp_mail_from', 'wpsc_replace_reply_address');
            $report_user = __('Customer Details', 'wpsc') . "\n\r";
            $form_sql = $wpdb->prepare("SELECT * FROM `" . WPSC_TABLE_SUBMITED_FORM_DATA . "` WHERE `log_id` = %d", $purchase_log['id']);
            $form_data = $wpdb->get_results($form_sql, ARRAY_A);
            if ($form_data != null) {
                foreach ($form_data as $form_field) {
                    $form_data = $wpdb->get_row($wpdb->prepare("SELECT * FROM `" . WPSC_TABLE_CHECKOUT_FORMS . "` WHERE `id` = %d LIMIT 1", $form_field['form_id']), ARRAY_A);
                    switch ($form_data['type']) {
                        case "country":
                            $country_code = $form_field['value'];
                            $report_user .= $form_data['name'] . ": " . wpsc_get_country($country_code) . "\n";
                            //check if country has a state then display if it does.
                            $country_data = wpsc_country_has_state($country_code);
                            if ($country_data['has_regions'] == 1) {
                                $report_user .= __('Billing State', 'wpsc') . ": " . wpsc_get_region($purchase_log['billing_region']) . "\n";
                            }
                            break;
                        case "delivery_country":
                            $report_user .= $form_data['name'] . ": " . wpsc_get_country($form_field['value']) . "\n";
                            break;
                        default:
                            if ($form_data['name'] == 'State' && is_numeric($form_field['value'])) {
                                $report_user .= __('Delivery State', 'wpsc') . ": " . wpsc_get_state_by_id($form_field['value'], 'name') . "\n";
                            } else {
                                $report_user .= wp_kses($form_data['name'], array()) . ": " . $form_field['value'] . "\n";
                            }
                            break;
                    }
                }
            }
            $report_user .= "\n\r";
            $report = $report_id . $report_user . $report;
            //echo '======REPORT======<br />'.$report.'<br />';
            //echo '======EMAIL======<br />'.$message.'<br />';
            if (get_option('purch_log_email') != null && $purchase_log['email_sent'] != 1) {
                wp_mail(get_option('purch_log_email'), __('Purchase Report', 'wpsc'), $report);
                $wpdb->update(WPSC_TABLE_PURCHASE_LOGS, array('email_sent' => '1'), array('sessionid' => $sessionid));
            }
            /// Adjust stock and empty the cart
            $wpsc_cart->submit_stock_claims($purchase_log['id']);
            $wpsc_cart->empty_cart();
        }
    }
}
Example #8
0
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']);
    }
    $log_data = $wpdb->get_row("SELECT * FROM `" . WPSC_TABLE_PURCHASE_LOGS . "` WHERE `id` = '{$purchlog_id}' LIMIT 1", ARRAY_A);
    $is_transaction = wpsc_check_purchase_processed($log_data['processed']);
    if ($is_transaction && function_exists('wpsc_member_activate_subscriptions')) {
        wpsc_member_activate_subscriptions($_POST['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' => $log_data, 'new_status' => $purchlog_status));
    $wpdb->update(WPSC_TABLE_PURCHASE_LOGS, array('processed' => $purchlog_status), array('id' => $purchlog_id), '%d', '%d');
    wpsc_clear_stock_claims();
    wpsc_decrement_claimed_stock($purchlog_id);
    if ($purchlog_status == 3) {
        transaction_results($log_data['sessionid'], false, null);
    }
    if (defined('DOING_AJAX') && DOING_AJAX) {
        set_current_screen('dashboard_page_wpsc-sales-logs');
        require_once WPSC_FILE_PATH . '/wpsc-admin/includes/purchase-log-list-table-class.php';
        $purchaselog_table = new WPSC_Purchase_Log_List_Table();
        $purchaselog_table->views();
        exit;
    }
}