public function get_gateway_data()
 {
     if (!($this->gateway_data = wp_cache_get($this->log_id, 'wpsc_checkout_form_gateway_data'))) {
         $map = array('firstname' => 'first_name', 'lastname' => 'last_name', 'address' => 'street', 'city' => 'city', 'state' => 'state', 'country' => 'country', 'postcode' => 'zip', 'phone' => 'phone');
         foreach (array('shipping', 'billing') as $type) {
             $data_key = "{$type}_address";
             $this->gateway_data[$data_key] = array();
             foreach ($map as $key => $new_key) {
                 $key = $type . $key;
                 if (isset($this->data[$key])) {
                     $value = $this->data[$key];
                     if ($new_key == 'state' && is_numeric($value)) {
                         $value = wpsc_get_state_by_id($value, 'code');
                     }
                     $this->gateway_data[$data_key][$new_key] = $value;
                 }
             }
             $name = isset($this->gateway_data[$data_key]['first_name']) ? $this->gateway_data[$data_key]['first_name'] . ' ' : '';
             $name .= isset($this->gateway_data[$data_key]['last_name']) ? $this->gateway_data[$data_key]['last_name'] : '';
             $this->gateway_data[$data_key]['name'] = trim($name);
         }
         wp_cache_set($this->log_id, $this->gateway_data, 'wpsc_checkout_form_gateway_data');
     }
     return apply_filters('wpsc_checkout_form_gateway_data', $this->gateway_data, $this->log_id);
 }
Esempio n. 2
0
 /**
  * collate_data method, collate purchase data, like addresses, like country
  * @access public
  */
 function collate_data()
 {
     global $wpdb;
     // get purchase data, regardless of being fed the ID or the sessionid
     if ($this->purchase_id > 0) {
         $purchase_id =& $this->purchase_id;
         $purchase_logs = $wpdb->get_row("SELECT * FROM `" . WPSC_TABLE_PURCHASE_LOGS . "` WHERE `id` = {$purchase_id} LIMIT 1", ARRAY_A);
     } else {
         if ($this->session_id != null) {
             $purchase_logs = $wpdb->get_row("SELECT * FROM `" . WPSC_TABLE_PURCHASE_LOGS . "` WHERE `sessionid` = {$this->session_id} LIMIT 1", ARRAY_A);
             $this->purchase_id = $purchase_logs['id'];
             $purchase_id =& $this->purchase_id;
         }
     }
     $email_address = $wpdb->get_var("SELECT `value` FROM `" . WPSC_TABLE_CHECKOUT_FORMS . "` AS `form_field` INNER JOIN `" . WPSC_TABLE_SUBMITED_FORM_DATA . "` AS `collected_data` ON `form_field`.`id` = `collected_data`.`form_id` WHERE `form_field`.`type` IN ( 'email' ) AND `collected_data`.`log_id` IN ( '{$purchase_id}' )");
     $currency_code = $wpdb->get_var("SELECT `code` FROM `" . WPSC_TABLE_CURRENCY_LIST . "` WHERE `id`='" . get_option('currency_type') . "' LIMIT 1");
     $collected_form_data = $wpdb->get_results("SELECT `data_names`.`id`, `data_names`.`unique_name`, `collected_data`.`value` FROM `" . WPSC_TABLE_SUBMITED_FORM_DATA . "` AS `collected_data` JOIN `" . WPSC_TABLE_CHECKOUT_FORMS . "` AS `data_names` ON `collected_data`.`form_id` = `data_names`.`id` WHERE `log_id` = '" . $purchase_id . "'", ARRAY_A);
     $address_keys = array('billing' => array('first_name' => 'billingfirstname', 'last_name' => 'billinglastname', 'address' => 'billingaddress', 'city' => 'billingcity', 'state' => 'billingstate', 'country' => 'billingcountry', 'post_code' => 'billingpostcode'), 'shipping' => array('first_name' => 'shippingfirstname', 'last_name' => 'shippinglastname', 'address' => 'shippingaddress', 'city' => 'shippingcity', 'state' => 'shippingstate', 'country' => 'shippingcountry', 'post_code' => 'shippingpostcode'));
     $address_data = array('billing' => array(), 'shipping' => array());
     foreach ((array) $collected_form_data as $collected_form_row) {
         $address_data_set = 'billing';
         $address_key = array_search($collected_form_row['unique_name'], $address_keys['billing']);
         if ($address_key == null) {
             $address_data_set = 'shipping';
             //					exit('<pre>'.print_r($collected_form_row,true).'</pre>');
             $address_key = array_search($collected_form_row['unique_name'], $address_keys['shipping']);
         }
         if ($address_key == null) {
             continue;
         }
         if ($collected_form_row['unique_name'] == 'billingcountry' || $collected_form_row['unique_name'] == 'shippingcountry') {
             $country = maybe_unserialize($collected_form_row['value']);
             $address_data[$address_data_set][$address_key] = $country[0];
         } elseif ($collected_form_row['unique_name'] == 'shippingstate') {
             $address_data[$address_data_set][$address_key] = wpsc_get_state_by_id($collected_form_row['value'], 'code');
         } else {
             $address_data[$address_data_set][$address_key] = $collected_form_row['value'];
         }
     }
     //		exit('<pre>'.print_r($address_data,true).'</pre>');
     if (count($address_data['shipping']) < 1) {
         $address_data['shipping'] = $address_data['billing'];
     }
     $this->cart_data = array('software_name' => 'WP e-Commerce/' . WPSC_PRESENTABLE_VERSION . '', 'store_location' => get_option('base_country'), 'store_currency' => $currency_code, 'is_subscription' => false, 'has_discounts' => false, 'notification_url' => add_query_arg('wpsc_action', 'gateway_notification', get_option('siteurl') . "/index.php"), 'transaction_results_url' => get_option('transact_url'), 'shopping_cart_url' => get_option('shopping_cart_url'), 'products_page_url' => get_option('product_list_url'), 'base_shipping' => $purchase_logs['base_shipping'], 'total_price' => $purchase_logs['totalprice'], 'session_id' => $purchase_logs['sessionid'], 'transaction_id' => $purchase_logs['transaction_id'], 'email_address' => $email_address, 'billing_address' => $address_data['billing'], 'shipping_address' => $address_data['shipping']);
 }
Esempio n. 3
0
 /**
  * Builds XML API request for Shipping Rates API
  * 	 *
  * @uses apply_filters - filters XML on return
  * @todo Get ZIP as transient when #437 is complete
  * @since 3.8.9
  * @return string $xml
  */
 public static function get_shipping_xml()
 {
     global $wpsc_cart;
     $zip = wpsc_get_customer_meta('shipping_zip');
     $state = wpsc_get_state_by_id($wpsc_cart->delivery_region, 'code');
     $country = $wpsc_cart->delivery_country;
     $products = $wpsc_cart->cart_items;
     $products_xml = '';
     $num = 0;
     if (count($products)) {
         foreach ($products as $product) {
             if (!$product->uses_shipping) {
                 continue;
             }
             $products_xml .= '<Item num="' . $num . '">';
             $products_xml .= '<Code>' . wpsc_esc_xml($product->sku) . '</Code>';
             $products_xml .= '<Quantity>' . wpsc_esc_xml($product->quantity) . '</Quantity>';
             $products_xml .= '</Item>';
             $num++;
         }
     }
     if (empty($products_xml)) {
         return '';
     }
     $xml = '<?xml version="1.0" encoding="utf-8"?>';
     $xml .= '<RateRequest>';
     $xml .= '<Username>' . wpsc_esc_xml(self::$email) . '</Username>';
     $xml .= '<Password>' . wpsc_esc_xml(self::$passwd) . '</Password>';
     $xml .= '<Order>';
     $xml .= '<AddressInfo type="ship">';
     $xml .= '<State>' . wpsc_esc_xml($state) . '</State>';
     $xml .= '<Country>' . wpsc_esc_xml($country) . '</Country>';
     $xml .= '<Zip>' . wpsc_esc_xml($zip) . '</Zip>';
     $xml .= '</AddressInfo>';
     $xml .= $products_xml;
     $xml .= '</Order>';
     $xml .= '</RateRequest>';
     return apply_filters('get_shipping_xml', $xml);
 }
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);
        }
    }
}
 public function add_pushes($session_id)
 {
     global $wpdb;
     $purchase = $wpdb->get_row($wpdb->prepare("SELECT * FROM `" . WPSC_TABLE_PURCHASE_LOGS . "` WHERE `sessionid`= %s LIMIT 1", $session_id));
     $purchase_id = $purchase->id;
     $output = '';
     $city = $wpdb->get_var($wpdb->prepare("\n\t\t\t\t\t\tSELECT tf.value FROM " . WPSC_TABLE_SUBMITTED_FORM_DATA . " tf\n\t\t\t\t\t\tLEFT JOIN " . WPSC_TABLE_CHECKOUT_FORMS . " cf\n\t\t\t\t\t\tON cf.id = tf.form_id\n\t\t\t\t\t\tWHERE cf.unique_name = 'billingcity'\n\t\t\t\t\t\tAND log_id = %d", $purchase_id));
     $state = $wpdb->get_var($wpdb->prepare("\n\t\t\t\t\t\tSELECT tf.value\n\t\t\t\t\t\tFROM " . WPSC_TABLE_SUBMITTED_FORM_DATA . " tf\n\t\t\t\t\t\tLEFT JOIN " . WPSC_TABLE_CHECKOUT_FORMS . " cf\n\t\t\t\t\t\tON cf.id = tf.form_id\n\t\t\t\t\t\tWHERE cf.unique_name = 'billingstate'\n\t\t\t\t\t\tAND log_id = %d", $purchase_id));
     $country = $wpdb->get_var($wpdb->prepare("\n\t\t\t\t\t\tSELECT tf.value\n\t\t\t\t\t\tFROM " . WPSC_TABLE_SUBMITTED_FORM_DATA . " tf\n\t\t\t\t\t\tLEFT JOIN " . WPSC_TABLE_CHECKOUT_FORMS . " cf\n\t\t\t\t\t\tON cf.id = tf.form_id\n\t\t\t\t\t\tWHERE cf.unique_name = 'billingcountry'\n\t\t\t\t\t\tAND log_id = %d", $purchase_id));
     $city = !empty($city) ? $city : '';
     $state = !empty($state) ? wpsc_get_state_by_id($state, 'name') : '';
     $country = !empty($country) ? $country : '';
     $cart_items = $wpdb->get_results($wpdb->prepare("SELECT * FROM " . WPSC_TABLE_CART_CONTENTS . " WHERE purchaseid = %d", $purchase_id), ARRAY_A);
     $total_shipping = wpsc_get_total_shipping($purchase_id);
     $total_tax = $total_price = 0;
     foreach ($cart_items as $item) {
         $total_tax += $item['tax_charged'];
         $total_price += $item['price'];
     }
     if ($this->is_theme_tracking || $this->advanced_code) {
         $output .= "<script type='text/javascript'>\n\r";
     }
     add_filter('wpsc_toggle_display_currency_code', array($this, 'remove_currency_and_html'));
     $output .= "\n\t\t\t_gaq.push(['_addTrans',\n\t\t\t'" . $purchase_id . "',                                     // order ID - required\n\t\t\t'" . wp_specialchars_decode($this->get_site_name()) . "', // affiliation or store name\n\t\t\t'" . number_format($total_price, 2, '.', '') . "',   // total - required\n\t\t\t'" . wpsc_currency_display($total_tax) . "',              // tax\n\t\t\t'" . wpsc_currency_display($total_shipping) . "',         // shipping\n\t\t\t'" . wp_specialchars_decode($city) . "',                  // city\n\t\t\t'" . wp_specialchars_decode($state) . "',                 // state or province\n\t\t\t'" . wp_specialchars_decode($country) . "'                // country\n  \t\t]);\n\r";
     remove_filter('wpsc_toggle_display_currency_code', array($this, 'remove_currency_and_html'));
     foreach ($cart_items as $item) {
         $category = wp_get_object_terms($item['prodid'], 'wpsc_product_category', array('orderby' => 'count', 'order' => 'DESC', 'fields' => 'all_with_object_id'));
         $item['sku'] = get_post_meta($item['prodid'], '_wpsc_sku', true);
         if ($category) {
             $item['category'] = $category[0]->name;
         } else {
             $item['category'] = '';
         }
         $item = array_map('wp_specialchars_decode', $item);
         $output .= "_gaq.push(['_addItem'," . "'" . $purchase_id . "'," . "'" . $item['sku'] . "'," . "'" . $item['name'] . "'," . "'" . $item['category'] . "'," . "'" . $item['price'] . "'," . "'" . $item['quantity'] . "']);\n\r";
         // Item Quantity
     }
     $output .= "_gaq.push(['_trackTrans']);\n\r";
     if ($this->is_theme_tracking || $this->advanced_code) {
         $output .= "</script>\n\r";
     }
     return $output;
 }
function wpsc_user_purchases()
{
    global $wpdb, $user_ID, $wpsc_purchlog_statuses, $gateway_checkout_form_fields, $purchase_log, $col_count, $nzshpcrt_gateways;
    $i = 0;
    $subtotal = 0;
    do_action('wpsc_pre_purchase_logs');
    foreach ((array) $purchase_log as $purchase) {
        $status_state = "expand";
        $status_style = "display:none;";
        $alternate = "";
        $i++;
        if ($i % 2 != 0) {
            $alternate = "alt";
        }
        echo "<tr class='{$alternate}'>\n\r";
        echo " <td class='status processed'>";
        echo "<a href=\"#\" onclick=\"return show_details_box('status_box_" . $purchase['id'] . "','log_expander_icon_" . $purchase['id'] . "');\">";
        if (!empty($_GET['id']) && $_GET['id'] == $purchase['id']) {
            $status_state = "collapse";
            $status_style = "style='display: block;'";
        }
        echo "<img class=\"log_expander_icon\" id=\"log_expander_icon_" . $purchase['id'] . "\" src=\"" . WPSC_CORE_IMAGES_URL . "/icon_window_{$status_state}.gif\" alt=\"\" title=\"\" />";
        echo "<span id='form_group_" . $purchase['id'] . "_text'>" . __('Details', 'wpsc') . "</span>";
        echo "</a>";
        echo " </td>\n\r";
        echo " <td class='date'>";
        echo date("jS M Y", $purchase['date']);
        echo " </td>\n\r";
        echo " <td class='price'>";
        $country = get_option('country_form_field');
        if ($purchase['shipping_country'] != '') {
            $billing_country = $purchase['billing_country'];
            $shipping_country = $purchase['shipping_country'];
        } elseif (!empty($country)) {
            $country_sql = $wpdb->prepare("SELECT * FROM `" . WPSC_TABLE_SUBMITTED_FORM_DATA . "` WHERE `log_id` = %d AND `form_id` = %d LIMIT 1", $purchase['id'], get_option('country_form_field'));
            $country_data = $wpdb->get_results($country_sql, ARRAY_A);
            $billing_country = $country_data[0]['value'];
            $shipping_country = $country_data[0]['value'];
        }
        echo wpsc_currency_display($purchase['totalprice'], array('display_as_html' => false));
        $subtotal += $purchase['totalprice'];
        echo " </td>\n\r";
        if (get_option('payment_method') == 2) {
            echo " <td class='payment_method'>";
            $gateway_name = '';
            foreach ((array) $nzshpcrt_gateways as $gateway) {
                if ($purchase['gateway'] != 'testmode') {
                    if ($gateway['internalname'] == $purchase['gateway']) {
                        $gateway_name = $gateway['name'];
                    }
                } else {
                    $gateway_name = __("Manual Payment", 'wpsc');
                }
            }
            echo $gateway_name;
            echo " </td>\n\r";
        }
        echo "</tr>\n\r";
        echo "<tr>\n\r";
        echo " <td colspan='{$col_count}' class='details'>\n\r";
        echo "  <div id='status_box_" . $purchase['id'] . "' class='order_status' style=\"{$status_style}\">\n\r";
        echo "  <div>\n\r";
        //order status code lies here
        //check what $purchase['processed'] reflects in the $wpsc_purchlog_statuses array
        $status_name = wpsc_find_purchlog_status_name($purchase['processed']);
        echo "  <strong class='form_group'>" . __('Order Status', 'wpsc') . ":</strong>\n\r";
        echo $status_name . "<br /><br />";
        do_action('wpsc_user_log_after_order_status', $purchase);
        //written by allen
        $usps_id = get_option('usps_user_id');
        if ($usps_id != null) {
            $XML1 = "<TrackFieldRequest USERID=\"{$usps_id}\"><TrackID ID=\"" . $purchase['track_id'] . "\"></TrackID></TrackFieldRequest>";
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, "http://secure.shippingapis.com/ShippingAPITest.dll?");
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_HEADER, 0);
            $postdata = "API=TrackV2&XML=" . $XML1;
            curl_setopt($ch, CURLOPT_POSTFIELDS, $postdata);
            $parser = new xml2array();
            $parsed = $parser->parse($result);
            $parsed = $parsed[0]['children'][0]['children'];
            if ($purchase['track_id'] != null) {
                echo "<br /><br />";
                echo " <strong class='form_group'>" . __('Shipping Address', 'wpsc') . "</strong>\n\r";
                echo "<table>";
                foreach ((array) $parsed as $parse) {
                    if ($parse['name'] == "TRACKSUMMARY") {
                        foreach ((array) $parse['children'] as $attrs) {
                            if ($attrs['name'] != "EVENT") {
                                $attrs['name'] = str_replace("EVENT", "", $attrs['name']);
                            }
                            $bar = ucfirst(strtolower($attrs['name']));
                            echo "<tr><td>" . $bar . "</td><td>" . $attrs['tagData'] . "</td></tr>";
                        }
                    }
                }
                echo "</table>";
            }
            echo "<br /><br />";
        }
        //end of written by allen
        //cart contents display starts here;
        echo "  <strong class='form_group'>" . __('Order Details', 'wpsc') . ":</strong>\n\r";
        $cartsql = $wpdb->prepare("SELECT * FROM `" . WPSC_TABLE_CART_CONTENTS . "` WHERE `purchaseid`= %d", $purchase['id']);
        $cart_log = $wpdb->get_results($cartsql, ARRAY_A);
        $j = 0;
        // /*
        if ($cart_log != null) {
            echo "<table class='logdisplay'>";
            echo "<tr class='toprow2'>";
            echo " <th class='details_name'>";
            _e('Name', 'wpsc');
            echo " </th>";
            echo " <th class='details_quantity'>";
            _e('Quantity', 'wpsc');
            echo " </th>";
            echo " <th class='details_price'>";
            _e('Price', 'wpsc');
            echo " </th>";
            echo " <th class='details_tax'>";
            _e('GST', 'wpsc');
            echo " </th>";
            echo " <th class='details_shipping'>";
            _e('Shipping', 'wpsc');
            echo " </th>";
            echo " <th class='details_total'>";
            _e('Total', 'wpsc');
            echo " </th>";
            echo "</tr>";
            $gsttotal = false;
            $endtotal = $total_shipping = 0;
            foreach ((array) $cart_log as $cart_row) {
                $alternate = "";
                $j++;
                if ($j % 2 != 0) {
                    $alternate = "alt";
                }
                $variation_list = '';
                $billing_country = !empty($country_data[0]['value']) ? $country_data[0]['value'] : '';
                $shipping_country = !empty($country_data[0]['value']) ? $country_data[0]['value'] : '';
                $shipping = $cart_row['pnp'];
                $total_shipping += $shipping;
                echo "<tr class='{$alternate}'>";
                echo " <td class='details_name'>";
                echo apply_filters('the_title', $cart_row['name']);
                echo $variation_list;
                echo " </td>";
                echo " <td class='details_quantity'>";
                echo $cart_row['quantity'];
                echo " </td>";
                echo " <td class='details_price'>";
                $price = $cart_row['price'] * $cart_row['quantity'];
                echo wpsc_currency_display($price);
                echo " </td>";
                echo " <td class='details_tax'>";
                $gst = $cart_row['tax_charged'];
                if ($gst > 0) {
                    $gsttotal += $gst;
                }
                echo wpsc_currency_display($gst, array('display_as_html' => false));
                echo " </td>";
                echo " <td class='details_shipping'>";
                echo wpsc_currency_display($shipping, array('display_as_html' => false));
                echo " </td>";
                echo " <td class='details_total'>";
                $endtotal += $price;
                echo wpsc_currency_display($shipping + $price, array('display_as_html' => false));
                echo " </td>";
                echo '</tr>';
            }
            echo "<tr>";
            echo " <td>";
            echo " </td>";
            echo " <td>";
            echo " </td>";
            echo " <td>";
            echo " <td>";
            echo " </td>";
            echo " </td>";
            echo " <td class='details_totals_labels'>";
            echo "<strong>" . __('Total Shipping', 'wpsc') . ":</strong><br />";
            echo "<strong>" . __('Total Tax', 'wpsc') . ":</strong><br />";
            echo "<strong>" . __('Final Total', 'wpsc') . ":</strong>";
            echo " </td>";
            echo " <td class='details_totals_labels'>";
            $total_shipping += $purchase['base_shipping'];
            $endtotal += $total_shipping;
            $endtotal += $purchase['wpec_taxes_total'];
            echo wpsc_currency_display($total_shipping, array('display_as_html' => false)) . "<br />";
            if ($gsttotal) {
                //if false then must be exclusive.. doesnt seem too reliable needs more testing
                echo wpsc_currency_display($gsttotal, array('display_as_html' => false)) . "<br />";
            } else {
                echo wpsc_currency_display($purchase['wpec_taxes_total'], array('display_as_html' => false)) . "<br />";
            }
            echo wpsc_currency_display($endtotal, array('display_as_html' => false));
            echo " </td>";
            echo '</tr>';
            echo "</table>";
            echo "<br />";
            echo "<strong>" . __('Customer Details', 'wpsc') . ":</strong>";
            echo "<table class='customer_details'>";
            $usersql = $wpdb->prepare("SELECT `" . WPSC_TABLE_SUBMITTED_FORM_DATA . "`.value, `" . WPSC_TABLE_CHECKOUT_FORMS . "`.* FROM `" . WPSC_TABLE_CHECKOUT_FORMS . "` LEFT JOIN `" . WPSC_TABLE_SUBMITTED_FORM_DATA . "` ON `" . WPSC_TABLE_CHECKOUT_FORMS . "`.id = `" . WPSC_TABLE_SUBMITTED_FORM_DATA . "`.`form_id` WHERE `" . WPSC_TABLE_SUBMITTED_FORM_DATA . "`.log_id = %d OR `" . WPSC_TABLE_CHECKOUT_FORMS . "`.type = 'heading' ORDER BY `" . WPSC_TABLE_CHECKOUT_FORMS . "`.`checkout_set`, `" . WPSC_TABLE_CHECKOUT_FORMS . "`.`checkout_order`", $purchase['id']);
            $formfields = $wpdb->get_results($usersql, ARRAY_A);
            if (!empty($formfields)) {
                foreach ((array) $formfields as $form_field) {
                    // If its a heading display the Name otherwise continue on
                    if ('heading' == $form_field['type']) {
                        echo "  <tr><td colspan='2'>" . esc_html($form_field['name']) . ":</td></tr>";
                        continue;
                    }
                    switch ($form_field['unique_name']) {
                        case 'shippingcountry':
                        case 'billingcountry':
                            $country = maybe_unserialize($form_field['value']);
                            if (is_array($country)) {
                                $country = $country[0];
                            } else {
                                $country = $form_field['value'];
                            }
                            echo "  <tr><td>" . esc_html($form_field['name']) . ":</td><td>" . esc_html($country) . "</td></tr>";
                            break;
                        case 'billingstate':
                        case 'shippingstate':
                            if (is_numeric($form_field['value'])) {
                                $state = wpsc_get_state_by_id($form_field['value'], 'name');
                            } else {
                                $state = $form_field['value'];
                            }
                            echo "  <tr><td>" . esc_html($form_field['name']) . ":</td><td>" . esc_html($state) . "</td></tr>";
                            break;
                        default:
                            echo "  <tr><td>" . esc_html($form_field['name']) . ":</td><td>" . esc_html($form_field['value']) . "</td></tr>";
                    }
                }
            }
            $payment_gateway_names = '';
            $payment_gateway_names = get_option('payment_gateway_names');
            foreach ((array) $payment_gateway_names as $gatewayname) {
                //if the gateway has a custom name
                if (!empty($gatewayname)) {
                    $display_name = $payment_gateway_names[$purchase_log[0]['gateway']];
                } else {
                    //if not fall back on default name
                    foreach ((array) $nzshpcrt_gateways as $gateway) {
                        if ($gateway['internalname'] == $purchase['gateway']) {
                            $display_name = $gateway['name'];
                        }
                    }
                }
            }
            echo "  <tr><td>" . __('Payment Method', 'wpsc') . ":</td><td>" . $display_name . "</td></tr>";
            echo "  <tr><td>" . __('Purchase #', 'wpsc') . ":</td><td>" . $purchase['id'] . "</td></tr>";
            if ($purchase['transactid'] != '') {
                echo "  <tr><td>" . __('Transaction Id', 'wpsc') . ":</td><td>" . $purchase['transactid'] . "</td></tr>";
            }
            echo "</table>";
        }
        echo "  </div>\n\r";
        echo "  </div>\n\r";
        echo " </td>\n\r";
        echo "</tr>\n\r";
    }
}
Esempio n. 7
0
 function gateway_sagepay($seperator, $sessionid)
 {
     global $wpdb;
     // Get Purchase Log
     $purchase_log_sql = "SELECT * FROM `" . WPSC_TABLE_PURCHASE_LOGS . "` WHERE `sessionid`= " . $sessionid . " LIMIT 1";
     $purchase_log = $wpdb->get_results($purchase_log_sql, ARRAY_A);
     // Get Cart Contents
     $cart_sql = "SELECT * FROM `" . WPSC_TABLE_CART_CONTENTS . "` WHERE `purchaseid`='" . $purchase_log[0]['id'] . "'";
     $cart = $wpdb->get_results($cart_sql, ARRAY_A);
     // exit('<pre>' . print_r($cart, true) . '</pre>');
     foreach ((array) $cart as $item) {
         $product_data = $wpdb->get_results("SELECT * FROM `" . WPSC_TABLE_PRODUCT_LIST . "` WHERE `id`='" . $item['prodid'] . "' LIMIT 1", ARRAY_A);
         $product_data = $product_data[0];
     }
     //Set Post Data
     $data['VendorTxCode'] = $sessionid;
     $data['Amount'] = number_format($purchase_log[0]['totalprice'], 2, '.', '');
     $data['Currency'] = get_option('protx_cur');
     $data['Description'] = get_bloginfo('name') . " wpEcommerce";
     $transact_url = get_option('transact_url');
     $site_url = get_option('shopping_cart_url');
     $data['SuccessURL'] = $transact_url . $seperator . "protx=success";
     $data['FailureURL'] = $site_url;
     // $data['FailureURL'] = urlencode($transact_url);
     if ($_POST['collected_data'][get_option('protx_form_last_name')] != '') {
         $data['BillingSurname'] = urlencode($_POST['collected_data'][get_option('protx_form_last_name')]);
     }
     if ($_POST['collected_data'][get_option('protx_form_post_code')] != '') {
         $data['BillingPostCode'] = $_POST['collected_data'][get_option('protx_form_post_code')];
     }
     if ($_POST['collected_data'][get_option('protx_form_address')] != '') {
         $data['BillingAddress1'] = $_POST['collected_data'][get_option('protx_form_address')];
     }
     if ($_POST['collected_data'][get_option('protx_form_city')] != '') {
         $data['BillingCity'] = $_POST['collected_data'][get_option('protx_form_city')];
     }
     if ($_POST['collected_data'][get_option('protx_form_first_name')] != '') {
         $data['BillingFirstnames'] = urlencode($_POST['collected_data'][get_option('protx_form_first_name')]);
     }
     if ($_POST['collected_data'][get_option('protx_form_country')] != '') {
         $result = $wpdb->get_results("SELECT * FROM `" . WPSC_TABLE_CURRENCY_LIST . "` WHERE isocode='" . $_POST['collected_data'][get_option('protx_form_country')][0] . "'", ARRAY_A);
         if ($result[0]['isocode'] == 'UK') {
             $data['BillingCountry'] = 'GB';
         } else {
             $data['BillingCountry'] = $result[0]['isocode'];
         }
     }
     //billingstate
     if (is_numeric($_POST['collected_data'][get_option('protx_form_country')][1])) {
         $data['BillingState'] = wpsc_get_state_by_id($_POST['collected_data'][get_option('protx_form_country')][1], 'code');
     }
     if ($_POST['collected_data'][get_option('protx_form_last_name')] != '') {
         $data['DeliverySurname'] = urlencode($_POST['collected_data'][get_option('protx_form_last_name')]);
     }
     if ($_POST['collected_data'][get_option('protx_form_post_code')] != '') {
         $data['DeliveryPostCode'] = $_POST['collected_data'][get_option('protx_form_post_code')];
     }
     if ($_POST['collected_data'][get_option('protx_form_address')] != '') {
         $data['DeliveryAddress1'] = $_POST['collected_data'][get_option('protx_form_address')];
     }
     if ($_POST['collected_data'][get_option('protx_form_city')] != '') {
         $data['DeliveryCity'] = $_POST['collected_data'][get_option('protx_form_city')];
     }
     if ($_POST['collected_data'][get_option('protx_form_first_name')] != '') {
         $data['DeliveryFirstnames'] = urlencode($_POST['collected_data'][get_option('protx_form_first_name')]);
     }
     if (preg_match("/^[a-zA-Z]{2}\$/", $_SESSION['wpsc_delivery_country'])) {
         $result = $wpdb->get_results("SELECT * FROM `" . WPSC_TABLE_CURRENCY_LIST . "` WHERE isocode='" . $_SESSION['wpsc_delivery_country'] . "'", ARRAY_A);
         if ($result[0]['isocode'] == 'UK') {
             $data['DeliveryCountry'] = 'GB';
         } else {
             $data['DeliveryCountry'] = $result[0]['isocode'];
         }
     }
     if ($data['DeliveryCountry'] == '') {
         $data['DeliveryCountry'] = 'GB';
     }
     //billingstate
     if (is_numeric($_SESSION['wpsc_delivery_region'])) {
         $data['DeliveryState'] = wpsc_get_state_by_id($_SESSION['wpsc_delivery_region'], 'code');
     }
     // Start Create Basket Data
     $basket_productprice_total = 0;
     $basket_rows = count($cart) + 1;
     if (!empty($purchase_log[0]['discount_value'])) {
         $basket_rows += 1;
     }
     $data['Basket'] = $basket_rows . ':';
     foreach ((array) $cart as $item) {
         $product_data = $wpdb->get_results("SELECT * FROM `" . WPSC_TABLE_PRODUCT_LIST . "` WHERE `id`='" . $item['prodid'] . "' LIMIT 1", ARRAY_A);
         $product_data = $product_data[0];
         $basket_productprice_total += $item['price'] * $item['quantity'];
         $data['Basket'] .= preg_replace('/[^a-z0-9]/i', '_', $product_data['name']) . ":" . $item['quantity'] . ":" . $item['price'] . ":---:" . $item['price'] * $item['quantity'] . ":" . $item['price'] * $item['quantity'] . ":";
     }
     $basket_delivery = $data['Amount'] - $basket_productprice_total;
     if (!empty($purchase_log[0]['discount_value'])) {
         $basket_delivery += $purchase_log[0]['discount_value'];
     }
     $data['Basket'] .= "Delivery:---:---:---:---:" . $basket_delivery;
     if (!empty($purchase_log[0]['discount_value'])) {
         $data['Basket'] .= ":Discount (" . $purchase_log[0]['discount_data'] . "):---:---:---:---:-" . $purchase_log[0]['discount_value'];
     }
     // End Create Basket Data
     $postdata = "";
     $i = 0;
     // exit("<pre>" . print_r($data, true) . "</pre>");
     foreach ($data as $key => $da) {
         if ($i == 0) {
             $postdata .= "{$key}={$da}";
         } else {
             $postdata .= "&{$key}={$da}";
         }
         $i++;
     }
     $servertype = get_option('protx_server_type');
     if ($servertype == 'test') {
         $url = 'https://test.sagepay.com/gateway/service/vspform-register.vsp';
     } elseif ($servertype == 'sim') {
         $url = 'https://test.sagepay.com/Simulator/VSPFormGateway.asp';
     } elseif ($servertype == 'live') {
         $url = 'https://live.sagepay.com/gateway/service/vspform-register.vsp';
     }
     $crypt = base64_encode(SimpleXor($postdata, get_option('protx_enc_key')));
     $postdata1['VPSProtocol'] = get_option("protx_protocol");
     $postdata1['TxType'] = "PAYMENT";
     $postdata1['Vendor'] = get_option("protx_name");
     // $postdata1['VendorTxCode'] = $sessionid;
     $postdata1['Crypt'] = $crypt;
     $j = 0;
     $postdata2 = "";
     foreach ($postdata1 as $key => $dat) {
         if ($j == 0) {
             $postdata2 .= "{$key}={$dat}";
         } else {
             $postdata2 .= "&{$key}={$dat}";
         }
         $j++;
     }
     $output = '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"><html lang="en"><head><title></title></head><body>';
     $output .= "<form id=\"sagepay_form\" name=\"sagepay_form\" method=\"post\" action=\"{$url}\">\n";
     $output .= "<input type='hidden' value ='2.23' name='VPSProtocol' />";
     $output .= "<input type='hidden' value ='PAYMENT' name='TxType' />";
     $output .= "<input type='hidden' value ='" . get_option("protx_name") . "' name='Vendor' />";
     $output .= "<input type='hidden' value ='" . $crypt . "' name='Crypt' />";
     $output .= "</form>";
     $output .= "<script language=\"javascript\" type=\"text/javascript\">document.getElementById('sagepay_form').submit();</script>";
     $output .= '</body></html>';
     echo $output;
     exit;
 }
function wpsc_packing_slip($purchase_id)
{
    global $wpdb, $purchlogitem, $wpsc_cart, $purchlog;
    if (isset($_REQUEST['purchaselog_id'])) {
        $purchlogitem = new wpsc_purchaselogs_items((int) $_REQUEST['purchaselog_id']);
    }
    $purch_sql = "SELECT * FROM `" . WPSC_TABLE_PURCHASE_LOGS . "` WHERE `id`='" . $purchase_id . "'";
    $purch_data = $wpdb->get_row($purch_sql, ARRAY_A);
    //echo "<p style='padding-left: 5px;'><strong>".__('Date', 'wpsc')."</strong>:".date("jS M Y", $purch_data['date'])."</p>";
    $cartsql = "SELECT * FROM `" . WPSC_TABLE_CART_CONTENTS . "` WHERE `purchaseid`=" . $purchase_id . "";
    $cart_log = $wpdb->get_results($cartsql, ARRAY_A);
    $j = 0;
    if ($cart_log != null) {
        echo "<div class='packing_slip'>\n\r";
        echo apply_filters('wpsc_packing_slip_header', '<h2>' . __('Packing Slip', 'wpsc') . "</h2>\n\r");
        echo "<strong>" . __('Order', 'wpsc') . " #</strong> " . $purchase_id . "<br /><br />\n\r";
        echo "<table>\n\r";
        /*
        		
        			$form_sql = "SELECT * FROM `".WPSC_TABLE_SUBMITED_FORM_DATA."` WHERE  `log_id` = '".(int)$purchase_id."'";
        			$input_data = $wpdb->get_results($form_sql,ARRAY_A);
        */
        echo "<tr class='heading'><td colspan='2'><strong>Billing Info</strong></td></tr>";
        foreach ((array) $purchlogitem->userinfo as $userinfo) {
            if ($userinfo['unique_name'] != 'billingcountry') {
                echo "<tr><td>" . $userinfo['name'] . ": </td><td>" . $userinfo['value'] . "</td></tr>";
            } else {
                $userinfo['value'] = maybe_unserialize($userinfo['value']);
                if (is_array($userinfo['value'])) {
                    if (!empty($userinfo['value'][1]) && !is_numeric($userinfo['value'][1])) {
                        echo "<tr><td>State: </td><td>" . $userinfo['value'][1] . "</td></tr>";
                    } elseif (is_numeric($userinfo['value'][1])) {
                        echo "<tr><td>State: </td><td>" . wpsc_get_state_by_id($userinfo['value'][1], 'name') . "</td></tr>";
                    }
                    if (!empty($userinfo['value'][0])) {
                        echo "<tr><td>Country: </td><td>" . $userinfo['value'][0] . "</td></tr>";
                    }
                } else {
                    echo "<tr><td>" . $userinfo['name'] . ": </td><td>" . $userinfo['value'] . "</td></tr>";
                }
            }
        }
        echo "<tr class='heading'><td colspan='2'><strong>Shipping Info</strong></td></tr>";
        foreach ((array) $purchlogitem->shippinginfo as $userinfo) {
            if ($userinfo['unique_name'] != 'shippingcountry' && $userinfo['unique_name'] != 'shippingstate') {
                echo "<tr><td>" . $userinfo['name'] . ": </td><td>" . $userinfo['value'] . "</td></tr>";
            } 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])) {
                        echo "<tr><td>State: </td><td>" . $userinfo['value'][1] . "</td></tr>";
                    } elseif (is_numeric($userinfo['value'][1])) {
                        echo "<tr><td>State: </td><td>" . wpsc_get_state_by_id($userinfo['value'][1], 'name') . "</td></tr>";
                    }
                    if (!empty($userinfo['value'][0])) {
                        echo "<tr><td>Country: </td><td>" . $userinfo['value'][0] . "</td></tr>";
                    }
                } else {
                    echo "<tr><td>" . $userinfo['name'] . ": </td><td>" . $userinfo['value'] . "</td></tr>";
                }
            } elseif ($userinfo['unique_name'] == 'shippingstate') {
                if (!empty($userinfo['value']) && !is_numeric($userinfo['value'])) {
                    echo "<tr><td>" . $userinfo['name'] . ": </td><td>" . $userinfo['value'] . "</td</tr>>";
                } elseif (is_numeric($userinfo['value'])) {
                    echo "<tr><td>State: </td><td>" . wpsc_get_state_by_id($userinfo['value'], 'name') . "</td></tr>";
                }
            }
        }
        //		echo('<pre>'.print_r($purchlogitem,true).'</pre>');
        /*
        	foreach($input_data as $input_row) {
        			  $rekeyed_input[$input_row['form_id']] = $input_row;
        			}
        			
        			
        			if($input_data != null) {
                $form_data = $wpdb->get_results("SELECT * FROM `".WPSC_TABLE_CHECKOUT_FORMS."` WHERE `active` = '1'",ARRAY_A);
            // exit('<pre>'.print_r($purch_data, true).'</pre>');
                foreach($form_data as $form_field) {
                  switch($form_field['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( $purch_data['billing_country'])."')");
        
                    if(is_numeric($purch_data['billing_region']) && ($delivery_region_count > 0)) {
                      echo "  <tr><td>".__('State', 'wpsc').":</td><td>".wpsc_get_region($purch_data['billing_region'])."</td></tr>\n\r";
                    }
                    echo "  <tr><td>".wp_kses($form_field['name'], array() ).":</td><td>".wpsc_get_country($purch_data['billing_country'])."</td></tr>\n\r";
                    break;
                        
                    case 'delivery_country':
                    echo "  <tr><td>".$form_field['name'].":</td><td>".wpsc_get_country($purch_data['shipping_country'])."</td></tr>\n\r";
                    break;
                        
                    case 'heading':
                    echo "  <tr><td colspan='2'><strong>".wp_kses($form_field['name'], array()).":</strong></td></tr>\n\r";
                    break;
                    
                    default:
                    if($form_field['unique_name'] == 'shippingstate'){
                    	echo "  <tr><td>".wp_kses($form_field['name'], array() ).":</td><td>".wpsc_get_region($purch_data['shipping_region'])."</td></tr>\n\r";
                    }else{
                    	echo "  <tr><td>".wp_kses($form_field['name'], array() ).":</td><td>".htmlentities(stripslashes($rekeyed_input[$form_field['id']]['value']), ENT_QUOTES,'UTF-8')."</td></tr>\n\r";
                    }
                    break;
                  }
                }
        			} else {
                echo "  <tr><td>".__('Name', 'wpsc').":</td><td>".$purch_data['firstname']." ".$purch_data['lastname']."</td></tr>\n\r";
                echo "  <tr><td>".__('Address', 'wpsc').":</td><td>".$purch_data['address']."</td></tr>\n\r";
                echo "  <tr><td>".__('Phone', 'wpsc').":</td><td>".$purch_data['phone']."</td></tr>\n\r";
                echo "  <tr><td>".__('Email', 'wpsc').":</td><td>".$purch_data['email']."</td></tr>\n\r";
        			}
        */
        if (get_option('payment_method') == 2) {
            $gateway_name = '';
            foreach ($GLOBALS['nzshpcrt_gateways'] as $gateway) {
                if ($purch_data['gateway'] != 'testmode') {
                    if ($gateway['internalname'] == $purch_data['gateway']) {
                        $gateway_name = $gateway['name'];
                    }
                } else {
                    $gateway_name = "Manual Payment";
                }
            }
        }
        // 			echo "  <tr><td colspan='2'></td></tr>\n\r";
        // 			echo "  <tr><td>".__('Payment Method', 'wpsc').":</td><td>".$gateway_name."</td></tr>\n\r";
        // 			//echo "  <tr><td>".__('Purchase No.', 'wpsc').":</td><td>".$purch_data['id']."</td></tr>\n\r";
        // 			echo "  <tr><td>".__('How The Customer Found Us', 'wpsc').":</td><td>".$purch_data['find_us']."</td></tr>\n\r";
        // 			$engrave_line = explode(",",$purch_data['engravetext']);
        // 			echo "  <tr><td>".__('Engrave text', 'wpsc')."</td><td></td></tr>\n\r";
        // 			echo "  <tr><td>".__('Line 1', 'wpsc').":</td><td>".$engrave_line[0]."</td></tr>\n\r";
        // 			echo "  <tr><td>".__('Line 2', 'wpsc').":</td><td>".$engrave_line[1]."</td></tr>\n\r";
        // 			if($purch_data['transactid'] != '') {
        // 				echo "  <tr><td>".__('Transaction Id', 'wpsc').":</td><td>".$purch_data['transactid']."</td></tr>\n\r";
        // 			}
        echo "</table>\n\r";
        echo "<table class='packing_slip'>";
        echo "<tr>";
        echo " <th>" . __('Quantity', 'wpsc') . " </th>";
        echo " <th>" . __('Name', 'wpsc') . "</th>";
        echo " <th>" . __('Price', 'wpsc') . " </th>";
        echo " <th>" . __('Shipping', 'wpsc') . " </th>";
        echo "<th>" . wpsc_display_tax_label(false) . "</th>";
        echo '</tr>';
        $endtotal = 0;
        $all_donations = true;
        $all_no_shipping = true;
        $file_link_list = array();
        //			exit('<pre>'.print_r($cart_log,true).'</pre>');
        foreach ($cart_log as $cart_row) {
            $purchlogitem->the_purch_item();
            //			exit('<pre>'.print_r, true).'</pre>');
            $alternate = "";
            $j++;
            if ($j % 2 != 0) {
                $alternate = "class='alt'";
            }
            $productsql = "SELECT * FROM `" . WPSC_TABLE_PRODUCT_LIST . "` WHERE `id`=" . $cart_row['prodid'] . "";
            $product_data = $wpdb->get_results($productsql, ARRAY_A);
            $variation_sql = "SELECT * FROM `" . WPSC_TABLE_CART_ITEM_VARIATIONS . "` WHERE `cart_id`='" . $cart_row['id'] . "'";
            $variation_data = $wpdb->get_results($variation_sql, ARRAY_A);
            $variation_count = count($variation_data);
            if ($variation_count > 1) {
                $variation_list = " (";
                $i = 0;
                foreach ($variation_data as $variation) {
                    if ($i > 0) {
                        $variation_list .= ", ";
                    }
                    $value_id = $variation['value_id'];
                    $value_data = $wpdb->get_results("SELECT * FROM `" . WPSC_TABLE_VARIATION_VALUES . "` WHERE `id`='" . $value_id . "' LIMIT 1", ARRAY_A);
                    $variation_list .= $value_data[0]['name'];
                    $i++;
                }
                $variation_list .= ")";
            } else {
                if ($variation_count == 1) {
                    $value_id = $variation_data[0]['value_id'];
                    $value_data = $wpdb->get_results("SELECT * FROM `" . WPSC_TABLE_VARIATION_VALUES . "` WHERE `id`='" . $value_id . "' LIMIT 1", ARRAY_A);
                    $variation_list = " (" . $value_data[0]['name'] . ")";
                } else {
                    $variation_list = '';
                }
            }
            if ($cart_row['donation'] != 1) {
                $all_donations = false;
            }
            if ($cart_row['no_shipping'] != 1) {
                $shipping = $cart_row['pnp'] * $cart_row['quantity'];
                $total_shipping += $shipping;
                $all_no_shipping = false;
            } else {
                $shipping = 0;
            }
            $price = $cart_row['price'] * $cart_row['quantity'];
            $gst = $price - $price / (1 + $cart_row['gst'] / 100);
            if ($gst > 0) {
                $tax_per_item = $gst / $cart_row['quantity'];
            }
            echo "<tr {$alternate}>";
            echo " <td>";
            echo $cart_row['quantity'];
            echo " </td>";
            echo " <td>";
            echo $product_data[0]['name'];
            echo stripslashes($variation_list);
            echo " </td>";
            echo " <td>";
            echo nzshpcrt_currency_display($price, 1);
            echo " </td>";
            echo " <td>";
            echo nzshpcrt_currency_display($shipping, 1);
            echo " </td>";
            echo '<td>';
            if (wpsc_tax_isincluded()) {
                echo wpsc_purchaselog_details_tax();
            } else {
                echo nzshpcrt_currency_display($cart_row['tax_charged'], 1);
            }
            echo '<td>';
            echo '</tr>';
        }
        echo "</table>";
        echo '<table class="packing-slip-totals">';
        echo '<tr><th>Base Shipping</th><td>' . nzshpcrt_currency_display($purch_data['base_shipping'], 1) . '</td></tr>';
        echo '<tr><th>Total Shipping</th><td>' . nzshpcrt_currency_display($purch_data['base_shipping'] + $total_shipping, 1) . '</td></tr>';
        echo '<tr><th>Total Price</th><td>' . nzshpcrt_currency_display($purch_data['totalprice'], 1) . '</td></tr>';
        echo '</table>';
        echo "</div>\n\r";
    } else {
        echo "<br />" . __('This users cart was empty', 'wpsc');
    }
}
/**
 * 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();
        }
    }
}
Esempio n. 10
0
function gateway_bluepay($seperator, $sessionid)
{
    //$transact_url = get_option('transact_url');
    //exit("<pre>".print_r($_POST,true)."</pre>");
    //   if($_SESSION['cart_paid'] == true)
    //     {
    //     header("Location: ".get_option('transact_url').$seperator."sessionid=".$sessionid);
    //     }
    $x_Login = urlencode(get_option('bluepay_login'));
    // Replace LOGIN with your login
    $x_Password = urlencode(get_option("bluepay_password"));
    // Replace PASS with your password
    $x_Delim_Data = urlencode("TRUE");
    $x_Delim_Char = urlencode(",");
    $x_Encap_Char = urlencode("");
    $x_Type = urlencode("AUTH_CAPTURE");
    $x_ADC_Relay_Response = urlencode("FALSE");
    if (get_option('bluepay_testmode') == 1) {
        $x_Test_Request = urlencode("TRUE");
        // Remove this line of code when you are ready to go live
    }
    #
    # Customer Information
    #
    $x_Method = urlencode("CC");
    $x_Amount = urlencode(nzshpcrt_overall_total_price($_SESSION['delivery_country']));
    //exit($x_Amount);
    $x_First_Name = urlencode($_POST['collected_data'][get_option('bluepay_form_first_name')]);
    $x_Last_Name = urlencode($_POST['collected_data'][get_option('bluepay_form_last_name')]);
    $x_Card_Num = urlencode($_POST['card_number']);
    $ExpDate = urlencode($_POST['expiry']['month'] . $_POST['expiry']['year']);
    $x_Exp_Date = $ExpDate;
    $x_Address = urlencode($_POST['collected_data'][get_option('bluepay_form_address')]);
    $x_City = urlencode($_POST['collected_data'][get_option('bluepay_form_city')]);
    $State = urlencode($_POST['collected_data'][get_option('bluepay_form_state')]);
    $x_State = wpsc_get_state_by_id($State, 'name');
    $x_Zip = urlencode($_POST['collected_data'][get_option('bluepay_form_post_code')]);
    $x_Email = urlencode($_POST['collected_data'][get_option('bluepay_form_email')]);
    $x_Email_Customer = urlencode("TRUE");
    $x_Merchant_Email = urlencode(get_option('purch_log_email'));
    //  Replace MERCHANT_EMAIL with the merchant email address
    $x_Card_Code = urlencode($_POST['card_code']);
    #
    # Build fields string to post
    #
    $fields = "x_Version=3.1&x_Login={$x_Login}&x_Delim_Data={$x_Delim_Data}&x_Delim_Char={$x_Delim_Char}&x_Encap_Char={$x_Encap_Char}";
    $fields .= "&x_Type={$x_Type}&x_Test_Request={$x_Test_Request}&x_Method={$x_Method}&x_Amount={$x_Amount}&x_First_Name={$x_First_Name}";
    $fields .= "&x_Last_Name={$x_Last_Name}&x_Card_Num={$x_Card_Num}&x_Exp_Date={$x_Exp_Date}&x_Card_Code={$x_Card_Code}&x_Address={$x_Address}&x_City={$x_City}&x_State={$x_State}&x_Zip={$x_Zip}&x_Email={$x_Email}&x_Email_Customer={$x_Email_Customer}&x_Merchant_Email={$x_Merchant_Email}&x_ADC_Relay_Response={$x_ADC_Relay_Response}";
    if ($x_Password != '') {
        $fields .= "&x_Password={$x_Password}";
    }
    //exit($fields);
    #
    # Start CURL session
    #
    $agent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)";
    $ref = get_option('transact_url');
    // Replace this URL with the URL of this script
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, "https://secure.bluepay.com/interfaces/a.net");
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
    curl_setopt($ch, CURLOPT_NOPROGRESS, 1);
    curl_setopt($ch, CURLOPT_VERBOSE, 1);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 0);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
    curl_setopt($ch, CURLOPT_TIMEOUT, 120);
    curl_setopt($ch, CURLOPT_USERAGENT, $agent);
    curl_setopt($ch, CURLOPT_REFERER, $ref);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    $buffer = curl_exec($ch);
    curl_close($ch);
    // This section of the code is the change from Version 1.
    // This allows this script to process all information provided by Authorize.net...
    // and not just whether if the transaction was successful or not
    // Provided in the true spirit of giving by Chuck Carpenter (Chuck@MLSphotos.com)
    // Be sure to email him and tell him how much you appreciate his efforts for PHP coders everywhere
    $return = preg_split("/[,]+/", "{$buffer}");
    // Splits out the buffer return into an array so . . .
    $details = $return[0];
    // This can grab the Transaction ID at position 1 in the array
    // echo "Location: ".$transact_url.$seperator."sessionid=".$sessionid;
    // exit("<pre>".print_r($return,true)."</pre>");
    // Change the number to grab additional information.  Consult the AIM guidelines to see what information is provided in each position.
    // For instance, to get the Transaction ID from the returned information (in position 7)..
    // Simply add the following:
    // $x_trans_id = $return[6];
    // You may then use the switch statement (or other process) to process the information provided
    // Example below is to see if the transaction was charged successfully
    if (get_option('permalink_structure') != '') {
        $seperator = "?";
    } else {
        $seperator = "&";
    }
    //exit("<pre>".print_r($return,true)."</pre>");
    switch ($details) {
        case 1:
            // Credit Card Successfully Charged
            //$_SESSION['cart_paid'] = true;
            header("Location: " . get_option('transact_url') . $seperator . "sessionid=" . $sessionid);
            exit;
            break;
        default:
            // Credit Card Not Successfully Charged
            $_SESSION['wpsc_checkout_misc_error_messages'][] = "Credit Card Processing Error: " . $return[3];
            header("Location: " . get_option('checkout_url') . $seperator . "total=" . nzshpcrt_overall_total_price($_POST['collected_data'][get_option('country_form_field')]));
            exit;
            break;
    }
}
/**
 * Update any values dependant on billing region
 *
 * @since 3.8.14
 *
 * @access private
 * @param mixed $meta_value Optional. Metadata value.
 * @param string $meta_key Metadata name.
 * @param int $visitor_id visitor ID
 * @return none
 */
function _wpsc_updated_visitor_meta_billingregion($meta_value, $meta_key, $visitor_id)
{
    if (!empty($meta_value)) {
        $billingstate = wpsc_get_state_by_id($meta_value, 'name');
    } else {
        $billingstate = '';
    }
    wpsc_update_visitor_meta($visitor_id, 'billingstate', $billingstate);
}
function gateway_bitpay($seperator, $sessionid)
{
    global $wpdb;
    global $wpsc_cart;
    try {
        // Protect your data!
        $mcrypt_ext = new \Bitpay\Crypto\McryptExtension();
        $fingerprint = substr(sha1(sha1(__DIR__)), 0, 24);
        //Use token that is in_use and with facade = pos for generating invoices
        $is_a_token_paired = $wpdb->get_var("SELECT COUNT(*) FROM " . $wpdb->prefix . "bitpay_keys WHERE `in_use` = 'true' AND `facade` = 'pos' LIMIT 1");
        if ($is_a_token_paired < 1) {
            debuglog('[Error] In Bitpay plugin, bitpay.merchant.php::gateway_bitpay(): No tokens are paired so no transactions can be done!');
            var_dump("Error Processing Transaction. Please try again later. If the problem persists, please contact us at " . get_option('admin_email'));
        }
        $row = $wpdb->get_results("SELECT * FROM " . $wpdb->prefix . "bitpay_keys WHERE `in_use` = 'true' AND `facade` = 'pos' LIMIT 1");
        $token = unserialize(base64_decode($mcrypt_ext->decrypt($row[0]->token, $fingerprint, '00000000')));
        $public_key = unserialize(base64_decode($mcrypt_ext->decrypt($row[0]->public_key, $fingerprint, '00000000')));
        $private_key = unserialize(base64_decode($mcrypt_ext->decrypt($row[0]->private_key, $fingerprint, '00000000')));
        $network = $row[0]->network === 'Livenet' ? new \Bitpay\Network\Livenet() : new \Bitpay\Network\Testnet();
        $row_id = $row[0]->id;
        $adapter = new \Bitpay\Client\Adapter\CurlAdapter();
        // This grabs the purchase log id from
        // the database that refers to the $sessionid
        $purchase_log = $wpdb->get_row("SELECT * FROM `" . WPSC_TABLE_PURCHASE_LOGS . "` WHERE `sessionid`= " . $sessionid . " LIMIT 1", ARRAY_A);
        // This grabs the users info using the
        // $purchase_log from the previous SQL query
        $usersql = "SELECT  `" . WPSC_TABLE_SUBMITED_FORM_DATA . "`.value," . "`" . WPSC_TABLE_CHECKOUT_FORMS . "`.`name`," . "`" . WPSC_TABLE_CHECKOUT_FORMS . "`.`unique_name` FROM " . "`" . WPSC_TABLE_CHECKOUT_FORMS . "` LEFT JOIN " . "`" . WPSC_TABLE_SUBMITED_FORM_DATA . "` ON " . "`" . WPSC_TABLE_CHECKOUT_FORMS . "`.id = " . "`" . WPSC_TABLE_SUBMITED_FORM_DATA . "`.`form_id` WHERE " . "`" . WPSC_TABLE_SUBMITED_FORM_DATA . "`.`log_id`='" . $purchase_log['id'] . "'";
        $userinfo = $wpdb->get_results($usersql, ARRAY_A);
        // convert from awkward format
        $ui = array();
        foreach ((array) $userinfo as $value) {
            if (strlen($value['value'])) {
                $ui[$value['unique_name']] = $value['value'];
            }
        }
        $userinfo = $ui;
        /**
         * Create Buyer object that will be used later.
         */
        $buyer = new \Bitpay\Buyer();
        // name
        if (true === isset($userinfo['billingfirstname'])) {
            $buyer->setFirstName($userinfo['billingfirstname']);
        }
        if (true === isset($userinfo['billinglastname'])) {
            $buyer->setLastName($userinfo['billinglastname']);
        }
        // address -- remove newlines
        if (true === isset($userinfo['billingaddress'])) {
            $newline = strpos($userinfo['billingaddress'], "\n");
            $address2 = '';
            if ($newline !== FALSE) {
                $address_line1 = substr($userinfo['billingaddress'], 0, $newline);
                $address_line2 = substr($userinfo['billingaddress'], $newline + 1);
                $address_line2 = preg_replace('/\\r\\n/', ' ', $address_line2, -1, $count);
            } else {
                $address_line1 = $userinfo['billingaddress'];
            }
            $buyer->setAddress(array($address_line1, $address_line2));
        }
        // state
        if (true === isset($userinfo['billingstate'])) {
            // check if State is a number code used when Selecting country as US
            if (true === ctype_digit($userinfo['billingstate'])) {
                $buyer->setState(wpsc_get_state_by_id($userinfo['billingstate'], 'code'));
            } else {
                $buyer->setState($userinfo['billingstate']);
            }
        }
        // country
        if (true === isset($userinfo['billingcountry'])) {
            $buyer->setCountry($userinfo['billingcountry']);
        }
        // city
        if (true === isset($userinfo['billingcity'])) {
            $buyer->setCity($userinfo['billingcity']);
        }
        // postal code
        if (true === isset($userinfo['billingpostcode'])) {
            $buyer->setZip($userinfo['billingpostcode']);
        }
        // email
        if (true === isset($userinfo['billingemail'])) {
            $buyer->setEmail($userinfo['billingemail']);
        }
        // phone
        if (true === isset($userinfo['billingphone'])) {
            $buyer->setPhone($userinfo['billingphone']);
        }
        // more user info
        foreach (array('billingphone' => 'buyerPhone', 'billingemail' => 'buyerEmail', 'billingcity' => 'buyerCity', 'billingcountry' => 'buyerCountry', 'billingpostcode' => 'buyerZip') as $f => $t) {
            if ($userinfo[$f]) {
                $options[$t] = $userinfo[$f];
            }
        }
        /**
         * Create an Item object that will be used later
         */
        $item = new \Bitpay\Item();
        // itemDesc, Sku, and Quantity
        if (count($wpsc_cart->cart_items) == 1) {
            $item_incart = $wpsc_cart->cart_items[0];
            $item_id = $item_incart->product_id;
            $item_sku = wpsc_product_sku($item_id);
            $item_description = $item_incart->quantity > 1 ? $item_incart->quantity . ' x ' . $item_incart->product_name : $item_incart->product_name;
        } else {
            foreach ($wpsc_cart->cart_items as $item_incart) {
                $quantity += $item_incart->quantity;
                $item_id = $item_incart->product_id;
                $item_sku_individual = wpsc_product_sku($item_id);
                $item_sku .= $item_incart->quantity . ' x ' . $item_sku_individual . ' ';
            }
            $item_description = $quantity . ' items';
        }
        // price
        $price = number_format($wpsc_cart->total_price, 2, '.', '');
        $item->setDescription($item_description)->setCode($item_sku)->setPrice($price);
        // Create new BitPay invoice
        $invoice = new \Bitpay\Invoice();
        // Add the item to the invoice
        $invoice->setItem($item);
        // Add the buyers info to invoice
        $invoice->setBuyer($buyer);
        // Configure the rest of the invoice
        $purchase_log = $wpdb->get_row("SELECT * FROM `" . WPSC_TABLE_PURCHASE_LOGS . "` WHERE `sessionid`= " . $sessionid . " LIMIT 1", ARRAY_A);
        $invoice->setOrderId($purchase_log['id'])->setNotificationUrl(get_option('siteurl') . '/?bitpay_callback=true');
        /**
         * BitPay offers services for many different currencies. You will need to
         * configure the currency in which you are selling products with.
         */
        $currency = new \Bitpay\Currency();
        $currencyId = get_option('currency_type');
        $currency_code = $wpdb->get_var($wpdb->prepare("SELECT `code` FROM `" . WPSC_TABLE_CURRENCY_LIST . "` WHERE `id` = %d LIMIT 1", $currencyId));
        $currency->setCode($currency_code);
        // Set the invoice currency
        $invoice->setCurrency($currency);
        // Transaction Speed
        $invoice->setTransactionSpeed(get_option('bitpay_transaction_speed'));
        // Redirect URL
        $separator = get_option('permalink_structure') != '' ? '?' : '&';
        if (true === is_null(get_option('bitpay_redirect'))) {
            update_option('bitpay_redirect', get_site_url());
        }
        $redirect_url = get_option('bitpay_redirect');
        $invoice->setRedirectUrl($redirect_url);
        // PosData
        $invoice->setPosData($sessionid);
        // Full Notifications
        $invoice->setFullNotifications(true);
        /**
         * Create the client that will be used
         * to send requests to BitPay's API
         */
        $client = new \Bitpay\Client\Client();
        $client->setAdapter($adapter);
        $client->setNetwork($network);
        $client->setPrivateKey($private_key);
        $client->setPublicKey($public_key);
        /**
         * You will need to set the token that was
         * returned when you paired your keys.
         */
        $client->setToken($token);
        $transaction = true;
        // Send invoice
        try {
            $client->createInvoice($invoice);
        } catch (\Exception $e) {
            debuglog('[Error] In Bitpay plugin, bitpay.merchant.php::gateway_bitpay(): Call to createInvoice() failed with the message: ' . $e->getMessage());
            var_dump("Error Processing Transaction. Please try again later. If the problem persists, please contact us at " . get_option('admin_email'));
            $transaction = false;
        }
        if (true === $transaction) {
            $sql = "UPDATE `" . WPSC_TABLE_PURCHASE_LOGS . "` SET `notes`= 'The payment has not been received yet.' WHERE `sessionid`=" . $sessionid;
            $wpdb->query($sql);
            $wpsc_cart->empty_cart();
            unset($_SESSION['WpscGatewayErrorMessage']);
            header('Location: ' . $invoice->getUrl());
        }
        exit;
    } catch (\Exception $e) {
        debuglog('[Error] In Bitpay plugin, form_bitpay() function on line ' . $e->getLine() . ', with the error "' . $e->getMessage() . '" .');
        throw $e;
    }
}
Esempio n. 13
0
 public function add_pushes($session_id)
 {
     $purchase = new WPSC_Purchase_Log($session_id, 'sessionid');
     $purchase_id = $purchase->get('id');
     $data = new WPSC_Checkout_Form_Data($purchase_id);
     $output = '';
     $city = $data->get('billingcity');
     $state = $data->get('billingstate');
     $country = $data->get('billingcountry');
     $state = !empty($state) ? wpsc_get_state_by_id($state, 'name') : '';
     $cart_items = $purchase->get_cart_contents();
     $total_shipping = wpsc_get_total_shipping($purchase_id);
     $total_tax = $total_price = 0;
     foreach ($cart_items as $item) {
         /* For backwards compatibility, convert objects to arrays */
         $item = (array) $item;
         $total_tax += $item['tax_charged'];
         $total_price += absint($item['quantity']) * $item['price'];
     }
     if ($this->is_theme_tracking || $this->advanced_code) {
         $output .= "<script type='text/javascript'>\n\r";
     }
     add_filter('wpsc_toggle_display_currency_code', array($this, 'remove_currency_and_html'));
     if ($this->use_universal_analytics()) {
         // Yoast GA Plugin switched to it's own object name __gaTracker - assign it to our ga object if it exists
         $output .= "var ga = typeof ga === 'undefined' && typeof __gaTracker !== 'undefined' ? __gaTracker : ga;";
         $output .= "ga('require', 'ecommerce');\n\r";
         $output .= "ga('ecommerce:addTransaction', {\n\t\t\t\t'id': '" . $purchase_id . "',                                               // Transaction ID. Required.\n\t\t\t\t'affiliation': '" . wp_specialchars_decode($this->get_site_name()) . "',  // Affiliation or store name.\n\t\t\t\t'revenue': '" . number_format($total_price, 2, '.', '') . "',             // Grand Total.\n\t\t\t\t'shipping': '" . wpsc_currency_display($total_shipping) . "',             // Shipping.\n\t\t\t\t'tax': '" . wpsc_currency_display($total_tax) . "'                        // Tax.\n\t\t\t});\n\r";
     } else {
         $output .= "\n\t\t\t\t_gaq.push(['_addTrans',\n\t\t\t\t'" . $purchase_id . "',                                     // order ID - required\n\t\t\t\t'" . wp_specialchars_decode($this->get_site_name()) . "', // affiliation or store name\n\t\t\t\t'" . number_format($total_price, 2, '.', '') . "',   // total - required\n\t\t\t\t'" . wpsc_currency_display($total_tax) . "',              // tax\n\t\t\t\t'" . wpsc_currency_display($total_shipping) . "',         // shipping\n\t\t\t\t'" . wp_specialchars_decode($city) . "',                  // city\n\t\t\t\t'" . wp_specialchars_decode($state) . "',                 // state or province\n\t\t\t\t'" . wp_specialchars_decode($country) . "'                // country\n\t\t\t]);\n\r";
     }
     remove_filter('wpsc_toggle_display_currency_code', array($this, 'remove_currency_and_html'));
     foreach ($cart_items as $item) {
         /* For backwards compatibility, convert objects to arrays */
         $item = (array) $item;
         $category = wp_get_object_terms($item['prodid'], 'wpsc_product_category', array('orderby' => 'count', 'order' => 'DESC', 'fields' => 'all_with_object_id'));
         $item['sku'] = get_post_meta($item['prodid'], '_wpsc_sku', true);
         if (empty($item['sku'])) {
             $item['sku'] = $item['prodid'];
         }
         if ($category) {
             $item['category'] = $category[0]->name;
         } else {
             $item['category'] = '';
         }
         $item = apply_filters('wpsc_google_analytics_pushed_product', array_map('wp_specialchars_decode', $item), $item, $this);
         if ($this->use_universal_analytics()) {
             $output .= "ga('ecommerce:addItem', {" . "'id': '" . $purchase_id . "'," . "'name': '" . $item['name'] . "'," . "'sku': '" . $item['sku'] . "'," . "'category': '" . $item['category'] . "'," . "'price': '" . $item['price'] . "'," . "'quantity': '" . $item['quantity'] . "'" . "});\n\r";
         } else {
             $output .= "_gaq.push(['_addItem'," . "'" . $purchase_id . "'," . "'" . $item['sku'] . "'," . "'" . $item['name'] . "'," . "'" . $item['category'] . "'," . "'" . $item['price'] . "'," . "'" . $item['quantity'] . "']);\n\r";
             // Item Quantity
         }
     }
     if ($this->use_universal_analytics()) {
         $output .= "ga('ecommerce:send');\n\r";
     } else {
         $output .= "_gaq.push(['_trackTrans']);\n\r";
     }
     if ($this->is_theme_tracking || $this->advanced_code) {
         $output .= "</script>\n\r";
     }
     return $output;
 }
Esempio n. 14
0
function Usecase($separator, $sessionid, $fromcheckout)
{
    global $wpdb, $wpsc_cart;
    $purchase_log_sql = $wpdb->prepare("SELECT * FROM `" . WPSC_TABLE_PURCHASE_LOGS . "` WHERE `sessionid` = %s  LIMIT 1", $sessionid);
    $purchase_log = $wpdb->get_results($purchase_log_sql, ARRAY_A);
    $cart_sql = $wpdb->prepare("SELECT * FROM `" . WPSC_TABLE_CART_CONTENTS . "` WHERE `purchaseid` = %d", $purchase_log[0]['id']);
    $wp_cart = $wpdb->get_results($cart_sql, ARRAY_A);
    $merchant_id = get_option('google_id');
    $merchant_key = get_option('google_key');
    $server_type = get_option('google_server_type');
    $currency = get_option('google_cur');
    $transact_url = get_option('transact_url');
    $returnURL = $transact_url . $separator . "sessionid=" . $sessionid . "&gateway=google";
    $cart = new GoogleCart($merchant_id, $merchant_key, $server_type, $currency);
    $cart->SetContinueShoppingUrl($returnURL);
    $cart->SetEditCartUrl(get_option('shopping_cart_url'));
    //google prohibited items not implemented
    $currency_converter = new CURRENCYCONVERTER();
    $currency_code = $wpdb->get_results("SELECT `code` FROM `" . WPSC_TABLE_CURRENCY_LIST . "` WHERE `id`='" . get_option('currency_type') . "' LIMIT 1", ARRAY_A);
    $local_currency_code = $currency_code[0]['code'];
    $google_curr = get_option('google_cur');
    $currentcy_rate = 1;
    if ($google_curr != $local_currency_code) {
        $currentcy_rate = $currency_converter->convert(1, $local_currency_code, $google_curr);
    }
    while (wpsc_have_cart_items()) {
        wpsc_the_cart_item();
        $google_currency_productprice = $currentcy_rate * (wpsc_cart_item_price(false) / wpsc_cart_item_quantity());
        $cart_item = new GoogleItem(wpsc_cart_item_name(), '', wpsc_cart_item_quantity(), $google_currency_productprice);
        $cart->AddItem($cart_item);
    }
    //If there are coupons applied add coupon as a product with negative price
    if ($wpsc_cart->coupons_amount > 0) {
        $google_currency_productprice = $currentcy_rate * $wpsc_cart->coupons_amount;
        $coupon = new GoogleItem('Discount', 'Discount Price', 1, '-' . $google_currency_productprice);
        $cart->AddItem($coupon);
    }
    $shipping_country = $purchase_log[0]['shipping_country'];
    $shipping_region = $purchase_log[0]['shipping_region'];
    if ($shipping_country == "UK") {
        $shipping_country = "GB";
    }
    // Add shipping options
    if (wpsc_uses_shipping()) {
        $shipping_name = ucfirst($wpsc_cart->selected_shipping_method) . " - " . $wpsc_cart->selected_shipping_option;
        if ($shipping_name == "") {
            $shipping_name = "Calculated";
        }
        $shipping = new GoogleFlatRateShipping($shipping_name, $wpsc_cart->calculate_total_shipping() * $currentcy_rate);
        if (!empty($shipping_country)) {
            $shipping_filter = new GoogleShippingFilters();
            if (!empty($shipping_region) && is_numeric($shipping_region)) {
                $shipping_filter->AddAllowedPostalArea($shipping_country, wpsc_get_state_by_id($shipping_region, "code"));
                $shipping_filter->AddAllowedStateArea(wpsc_get_state_by_id($shipping_region, "code"));
            } else {
                $shipping_filter->AddAllowedPostalArea($shipping_country);
            }
            $shipping->AddShippingRestrictions($shipping_filter);
        }
        $cart->AddShipping($shipping);
    }
    // Add tax rules
    if (!empty($shipping_country)) {
        $tax_rule = new GoogleDefaultTaxRule(wpsc_cart_tax(false) / $wpsc_cart->calculate_subtotal());
        $tax_rule->AddPostalArea($shipping_country);
        $cart->AddDefaultTaxRules($tax_rule);
    }
    // Display Google Checkout button
    if (get_option('google_button_size') == '0') {
        $google_button_size = 'BIG';
    } elseif (get_option('google_button_size') == '1') {
        $google_button_size = 'MEDIUM';
    } elseif (get_option('google_button_size') == '2') {
        $google_button_size = 'SMALL';
    }
    echo $cart->CheckoutButtonCode($google_button_size);
}
Esempio n. 15
0
function wpsc_purchase_log_csv()
{
    global $wpdb, $wpsc_gateways;
    get_currentuserinfo();
    $count = 0;
    if ('key' == $_REQUEST['rss_key'] && current_user_can('manage_options')) {
        if (isset($_REQUEST['start_timestamp']) && isset($_REQUEST['end_timestamp'])) {
            $start_timestamp = $_REQUEST['start_timestamp'];
            $end_timestamp = $_REQUEST['end_timestamp'];
            $start_end_sql = "SELECT * FROM `" . WPSC_TABLE_PURCHASE_LOGS . "` WHERE `date` BETWEEN '%d' AND '%d' ORDER BY `date` DESC";
            $start_end_sql = apply_filters('wpsc_purchase_log_start_end_csv', $start_end_sql);
            $data = $wpdb->get_results($wpdb->prepare($start_end_sql, $start_timestamp, $end_timestamp), ARRAY_A);
            /* translators: %1$s is "start" date, %2$s is "to" date */
            $csv_name = _x('Purchase Log %1$s to %2$s.csv', 'exported purchase log csv file name', 'wpsc');
            $csv_name = sprintf($csv_name, date("M-d-Y", $start_timestamp), date("M-d-Y", $end_timestamp));
        } elseif (isset($_REQUEST['m'])) {
            $year = (int) substr($_REQUEST['m'], 0, 4);
            $month = (int) substr($_REQUEST['m'], -2);
            $month_year_sql = "\n\t\t\t\tSELECT *\n\t\t\t\tFROM " . WPSC_TABLE_PURCHASE_LOGS . "\n\t\t\t\tWHERE YEAR(FROM_UNIXTIME(date)) = %d AND MONTH(FROM_UNIXTIME(date)) = %d\n\t\t\t\tORDER BY `id` DESC\n\t\t\t";
            $month_year_sql = apply_filters('wpsc_purchase_log_month_year_csv', $month_year_sql);
            $data = $wpdb->get_results($wpdb->prepare($month_year_sql, $year, $month), ARRAY_A);
            /* translators: %1$s is month, %2$s is year */
            $csv_name = _x('Purchase Log %1$s/%2$s.csv', 'exported purchase log csv file name', 'wpsc');
            $csv_name = sprintf($csv_name, $month, $year);
        } else {
            $sql = apply_filters('wpsc_purchase_log_month_year_csv', "SELECT * FROM " . WPSC_TABLE_PURCHASE_LOGS . " ORDER BY `id` DESC");
            $data = $wpdb->get_results($sql, ARRAY_A);
            $csv_name = _x("All Purchase Logs.csv", 'exported purchase log csv file name', 'wpsc');
        }
        $form_sql = "SELECT * FROM `" . WPSC_TABLE_CHECKOUT_FORMS . "` WHERE `active` = '1' AND `type` != 'heading' ORDER BY `checkout_order` DESC;";
        $form_data = $wpdb->get_results($form_sql, ARRAY_A);
        $headers_array = array(_x('Purchase ID', 'purchase log csv headers', 'wpsc'), _x('Purchase Total', 'purchase log csv headers', 'wpsc'));
        $headers2_array = array(_x('Payment Gateway', 'purchase log csv headers', 'wpsc'), _x('Payment Status', 'purchase log csv headers', 'wpsc'), _x('Purchase Date', 'purchase log csv headers', 'wpsc'));
        $form_headers_array = array();
        $output = '';
        foreach ((array) $form_data as $form_field) {
            if (empty($form_field['unique_name'])) {
                $form_headers_array[] = $form_field['name'];
            } else {
                $prefix = false === strstr($form_field['unique_name'], 'billing') ? _x('Shipping ', 'purchase log csv header field prefix', 'wpsc') : _x('Billing ', 'purchase log csv header field prefix', 'wpsc');
                $form_headers_array[] = $prefix . $form_field['name'];
            }
        }
        foreach ((array) $data as $purchase) {
            $form_headers = '';
            $output .= "\"" . $purchase['id'] . "\",";
            //Purchase ID
            $output .= "\"" . $purchase['totalprice'] . "\",";
            //Purchase Total
            foreach ((array) $form_data as $form_field) {
                $collected_data_sql = "SELECT * FROM `" . WPSC_TABLE_SUBMITTED_FORM_DATA . "` WHERE `log_id` = '" . $purchase['id'] . "' AND `form_id` = '" . $form_field['id'] . "' LIMIT 1";
                $collected_data = $wpdb->get_results($collected_data_sql, ARRAY_A);
                $collected_data = $collected_data[0];
                if (('billingstate' == $form_field['unique_name'] || 'shippingstate' == $form_field['unique_name']) && is_numeric($collected_data['value'])) {
                    $output .= "\"" . wpsc_get_state_by_id($collected_data['value'], 'code') . "\",";
                } else {
                    $output .= "\"" . str_replace(array("\r", "\r\n", "\n"), ' ', $collected_data['value']) . "\",";
                }
                // get form fields
            }
            if (isset($wpsc_gateways[$purchase['gateway']]) && isset($wpsc_gateways[$purchase['gateway']]['display_name'])) {
                $output .= "\"" . $wpsc_gateways[$purchase['gateway']]['display_name'] . "\",";
            } else {
                $output .= "\"\",";
            }
            $status_name = wpsc_find_purchlog_status_name($purchase['processed']);
            $output .= "\"" . $status_name . "\",";
            //get purchase status
            $output .= "\"" . date("jS M Y", $purchase['date']) . "\",";
            //date
            $cartsql = "SELECT `prodid`, `quantity`, `name` FROM `" . WPSC_TABLE_CART_CONTENTS . "` WHERE `purchaseid`=" . $purchase['id'] . "";
            $cart = $wpdb->get_results($cartsql, ARRAY_A);
            if ($count < count($cart)) {
                $count = count($cart);
            }
            $items = count($cart);
            $i = 1;
            // Go through all products in cart and display quantity and sku
            foreach ((array) $cart as $item) {
                $skuvalue = get_product_meta($item['prodid'], 'sku', true);
                if (empty($skuvalue)) {
                    $skuvalue = __('N/A', 'wpsc');
                }
                $output .= "\"" . $item['quantity'] . "\",";
                $output .= "\"" . str_replace('"', '\\"', $item['name']) . "\",";
                if ($items <= 1) {
                    $output .= "\"" . $skuvalue . "\"";
                } elseif ($items > 1 && $i != $items) {
                    $output .= "\"" . $skuvalue . "\",";
                } else {
                    $output .= "\"" . $skuvalue . "\"";
                }
                $i++;
            }
            $output .= "\n";
            // terminates the row/line in the CSV file
        }
        // Get the most number of products and create a header for them
        $headers3 = array();
        for ($i = 0; $i < $count; $i++) {
            $headers3[] = _x('Quantity', 'purchase log csv headers', 'wpsc');
            $headers3[] = _x('Product Name', 'purchase log csv headers', 'wpsc');
            $headers3[] = _x('SKU', 'purchase log csv headers', 'wpsc');
        }
        $headers = '"' . implode('","', $headers_array) . '",';
        $form_headers = '"' . implode('","', $form_headers_array) . '",';
        $headers2 = '"' . implode('","', $headers2_array) . '",';
        $headers3 = '"' . implode('","', $headers3) . '"';
        $headers = apply_filters('wpsc_purchase_log_csv_headers', $headers . $form_headers . $headers2 . $headers3, $data, $form_data);
        $output = apply_filters('wpsc_purchase_log_csv_output', $output, $data, $form_data);
        do_action('wpsc_purchase_log_csv');
        header('Content-Type: text/csv');
        header('Content-Disposition: inline; filename="' . $csv_name . '"');
        echo $headers . "\n" . $output;
        exit;
    }
}
Esempio n. 16
0
 private function process_checkout_form_value($data)
 {
     if ('billingstate' !== $data->unique_name && 'shippingstate' !== $data->unique_name) {
         return $data;
     }
     if (!is_numeric($data->value)) {
         return $data;
     }
     $data->value = wpsc_get_state_by_id($data->value, 'name');
     return $data;
 }
function gateway_paypal_multiple($seperator, $sessionid)
{
    global $wpdb, $wpsc_cart;
    $purchase_log = $wpdb->get_row("SELECT * FROM `" . WPSC_TABLE_PURCHASE_LOGS . "` WHERE `sessionid`= " . $sessionid . " LIMIT 1", ARRAY_A);
    if ($purchase_log['totalprice'] == 0) {
        header("Location: " . get_option('transact_url') . $seperator . "sessionid=" . $sessionid);
        exit;
    }
    $cart_sql = "SELECT * FROM `" . WPSC_TABLE_CART_CONTENTS . "` WHERE `purchaseid`='" . $purchase_log['id'] . "'";
    $cart = $wpdb->get_results($cart_sql, ARRAY_A);
    //written by allen
    //exit("<pre>".print_r($cart,true)."</pre>");
    $member_subtype = get_product_meta($cart[0]['prodid'], 'is_permenant', true);
    $status = get_product_meta($cart[0]['prodid'], 'is_membership', true);
    $is_member = $status;
    $is_perm = $member_subtype;
    //end of written by allen
    $transact_url = get_option('transact_url');
    // paypal connection variables
    $data['business'] = get_option('paypal_multiple_business');
    $data['return'] = urlencode($transact_url . $seperator . "sessionid=" . $sessionid . "&gateway=paypal");
    $data['cancel_return'] = urlencode($transact_url);
    $data['notify_url'] = urlencode(get_option('siteurl') . "/?ipn_request=true");
    $data['rm'] = '2';
    //data['bn'] = 'Instinct-WP-e-commerce_ShoppingCart_EC';
    // look up the currency codes and local price
    $currency_code = $wpdb->get_results("SELECT `code` FROM `" . WPSC_TABLE_CURRENCY_LIST . "` WHERE `id`='" . get_option('currency_type') . "' LIMIT 1", ARRAY_A);
    $local_currency_code = $currency_code[0]['code'];
    $paypal_currency_code = get_option('paypal_curcode');
    if ($paypal_currency_code == '') {
        $paypal_currency_code = 'US';
    }
    //exit(get_option('currency_type'). " ".$paypal_currency_code);
    // Stupid paypal only accepts payments in one of 5 currencies. Convert from the currency of the users shopping cart to the curency which the user has specified in their paypal preferences.
    $curr = new CURRENCYCONVERTER();
    $data['currency_code'] = $paypal_currency_code;
    //   $data['lc'] = 'US';
    $data['lc'] = $paypal_currency_code;
    $data['bn'] = 'wp-e-commerce';
    if (get_option('address_override') == 1) {
        $data['address_override'] = '1';
    }
    if ((int) (bool) get_option('paypal_ship') == '1') {
        $data['no_shipping'] = '0';
        $data['address_override'] = '1';
    }
    $data['no_note'] = '1';
    switch ($paypal_currency_code) {
        case "JPY":
            $decimal_places = 0;
            break;
        case "HUF":
            $decimal_places = 0;
        default:
            $decimal_places = 2;
            break;
    }
    $i = 1;
    $all_donations = true;
    $all_no_shipping = true;
    $total = $wpsc_cart->calculate_total_price();
    $discount = $wpsc_cart->coupons_amount;
    //exit($discount);
    if ($discount > 0) {
        if ($paypal_currency_code != $local_currency_code) {
            $paypal_currency_productprice = $curr->convert($wpsc_cart->calculate_total_price(), $paypal_currency_code, $local_currency_code);
            $paypal_currency_shipping = $curr->convert($local_currency_shipping, $paypal_currency_code, $local_currency_code);
            $base_shipping = $curr->convert($wpsc_cart->calculate_total_shipping(), $paypal_currency_code, $local_currency_code);
            $tax_price = $curr->convert($item['tax_charged'], $paypal_currency_code, $local_currency_code);
        } else {
            $paypal_currency_productprice = $wpsc_cart->calculate_total_price();
            $paypal_currency_shipping = $local_currency_shipping;
            $base_shipping = $wpsc_cart->calculate_total_shipping();
            $tax_price = $item['tax_charged'];
        }
        $data['item_name_' . $i] = "Your Shopping Cart";
        $data['amount_' . $i] = number_format(sprintf("%01.2f", $paypal_currency_productprice), $decimal_places, '.', '');
        $data['quantity_' . $i] = 1;
        // $data['item_number_'.$i] = 0;
        $data['shipping_' . $i] = 0;
        $data['shipping2_' . $i] = 0;
        $data['handling_' . $i] = 0;
        $i++;
    } else {
        foreach ((array) $cart as $item) {
            $product_data = $wpdb->get_results("SELECT * FROM `" . WPSC_TABLE_PRODUCT_LIST . "` WHERE `id`='" . $item['prodid'] . "' LIMIT 1", ARRAY_A);
            $product_data = $product_data[0];
            if ((double) $item['price'] == 0) {
                continue;
            }
            $variation_count = count($product_variations);
            $local_currency_productprice = $item['price'];
            $local_currency_shipping = $item['pnp'] / $item['quantity'];
            if ($paypal_currency_code != $local_currency_code) {
                $paypal_currency_productprice = $curr->convert($local_currency_productprice, $paypal_currency_code, $local_currency_code);
                $paypal_currency_shipping = $curr->convert($local_currency_shipping, $paypal_currency_code, $local_currency_code);
                //	exit($paypal_currency_productprice . " " . $paypal_currency_shipping.' '.$local_currency_productprice . " " . $local_currency_code);
                $base_shipping = $curr->convert($wpsc_cart->calculate_base_shipping(), $paypal_currency_code, $local_currency_code);
                //exit($paypal_currency_productprice.' Local>'.$local_currency_productprice.' Base shp'.$base_shipping);
                $tax_price = $curr->convert($item['tax_charged'], $paypal_currency_code, $local_currency_code);
            } else {
                $paypal_currency_productprice = $local_currency_productprice;
                $paypal_currency_shipping = $local_currency_shipping;
                $base_shipping = $wpsc_cart->calculate_base_shipping();
                $tax_price = $item['tax_charged'];
            }
            //exit("<pre>".print_r(, true).'</pre>');
            $data['item_name_' . $i] = urlencode(stripslashes($item['name']));
            $data['amount_' . $i] = number_format(sprintf("%01.2f", $paypal_currency_productprice), $decimal_places, '.', '');
            $data['tax_' . $i] = number_format(sprintf("%01.2f", $tax_price), $decimal_places, '.', '');
            $data['quantity_' . $i] = $item['quantity'];
            $data['item_number_' . $i] = $product_data['id'];
            if ($item['donation'] != 1) {
                $all_donations = false;
                $data['shipping_' . $i] = number_format($paypal_currency_shipping, $decimal_places, '.', '');
                $data['shipping2_' . $i] = number_format($paypal_currency_shipping, $decimal_places, '.', '');
            } else {
                $data['shipping_' . $i] = number_format(0, $decimal_places, '.', '');
                $data['shipping2_' . $i] = number_format(0, $decimal_places, '.', '');
            }
            if ($product_data['no_shipping'] != 1) {
                $all_no_shipping = false;
            }
            $data['handling_' . $i] = '';
            $i++;
        }
    }
    $data['tax'] = '';
    //exit($base_shipping);
    if ($base_shipping > 0 && $all_donations == false && $all_no_shipping == false) {
        $data['handling_cart'] = number_format($base_shipping, $decimal_places, '.', '');
    }
    $data['custom'] = '';
    $data['invoice'] = $sessionid;
    // User details
    if ($_POST['collected_data'][get_option('paypal_form_first_name')] != '') {
        $data['first_name'] = urlencode($_POST['collected_data'][get_option('paypal_form_first_name')]);
    }
    if ($_POST['collected_data'][get_option('paypal_form_last_name')] != '') {
        $data['last_name'] = urlencode($_POST['collected_data'][get_option('paypal_form_last_name')]);
    }
    if ($_POST['collected_data'][get_option('paypal_form_address')] != '') {
        $address_rows = explode("\n\r", $_POST['collected_data'][get_option('paypal_form_address')]);
        $data['address1'] = urlencode(str_replace(array("\n", "\r"), '', $address_rows[0]));
        unset($address_rows[0]);
        if ($address_rows != null) {
            $data['address2'] = implode(", ", $address_rows);
        } else {
            $data['address2'] = '';
        }
    }
    if ($_POST['collected_data'][get_option('paypal_form_city')] != '') {
        $data['city'] = urlencode($_POST['collected_data'][get_option('paypal_form_city')]);
    }
    if ($_POST['collected_data'][get_option('paypal_form_state')] != '') {
        if (!is_array($_POST['collected_data'][get_option('paypal_form_state')])) {
            $data['state'] = urlencode($_POST['collected_data'][get_option('paypal_form_state')]);
        }
    }
    if ($_POST['collected_data'][get_option('paypal_form_country')] != '') {
        if (is_array($_POST['collected_data'][get_option('paypal_form_country')])) {
            $country = $_POST['collected_data'][get_option('paypal_form_country')][0];
            $id = $_POST['collected_data'][get_option('paypal_form_country')][1];
            $state = wpsc_get_state_by_id($id, 'code');
        } else {
            $country = $_POST['collected_data'][get_option('paypal_form_country')];
        }
        $data['country'] = urlencode($country);
        if ($state != '') {
            $data['state'] = $state;
        }
    }
    if (is_numeric($_POST['collected_data'][get_option('paypal_form_post_code')])) {
        $data['zip'] = urlencode($_POST['collected_data'][get_option('paypal_form_post_code')]);
    }
    // Change suggested by waxfeet@gmail.com, if email to be sent is not there, dont send an email address
    $email_data = $wpdb->get_results("SELECT `id`,`type` FROM `" . WPSC_TABLE_CHECKOUT_FORMS . "` WHERE `type` IN ('email') AND `active` = '1'", ARRAY_A);
    foreach ((array) $email_data as $email) {
        $data['email'] = $_POST['collected_data'][$email['id']];
    }
    if ($_POST['collected_data'][get_option('email_form_field')] != null && $data['email'] == null) {
        $data['email'] = $_POST['collected_data'][get_option('email_form_field')];
    }
    $data['upload'] = '1';
    $data['cmd'] = "_ext-enter";
    $data['redirect_cmd'] = "_cart";
    $data = apply_filters('wpsc_paypal_standard_post_data', $data);
    $datacount = count($data);
    $num = 0;
    //  exit('<pre>'.print_r($data,true).'</pre>');
    foreach ($data as $key => $value) {
        $amp = '&';
        $num++;
        if ($num == $datacount) {
            $amp = '';
        }
        //$output .= $key.'='.urlencode($value).$amp;
        $output .= $key . '=' . $value . $amp;
    }
    if (get_option('paypal_ipn') == 0) {
        //ensures that digital downloads still work for people without IPN, less secure, though
        //$wpdb->query("UPDATE `".WPSC_TABLE_PURCHASE_LOGS."` SET `processed` = '2' WHERE `sessionid` = ".$sessionid." LIMIT 1");
    }
    //written by allen
    if ($is_member == '1') {
        $membership_length = get_product_meta($cart[0]['prodid'], 'membership_length', true);
        if ($is_perm == '1') {
            $permsub = '&src=1';
        } else {
            $permsub = '';
        }
        $output = 'cmd=_xclick-subscriptions&currency_code=' . urlencode($data['currency_code']) . '&lc=' . urlencode($data['lc']) . '&business=' . urlencode($data['business']) . '&no_note=1&item_name=' . urlencode($data['item_name_1']) . '&return=' . urlencode($data['return']) . '&cancel_return=' . urlencode($data['cancel_return']) . $permsub . '&a3=' . urlencode($data['amount_1']) . '&p3=' . urlencode($membership_length['length']) . '&t3=' . urlencode(strtoupper($membership_length['unit']));
    }
    if (defined('WPSC_ADD_DEBUG_PAGE') and WPSC_ADD_DEBUG_PAGE == true) {
        echo "<a href='" . get_option('paypal_multiple_url') . "?" . $output . "'>Test the URL here</a>";
        echo "<pre>" . print_r($data, true) . "</pre>";
        // 	echo "<pre>".print_r($_POST,true)."</pre>";
        exit;
    }
    header("Location: " . get_option('paypal_multiple_url') . "?" . $output);
    exit;
}
Esempio n. 18
0
 /**
  * collate_data method, collate purchase data, like addresses, like country
  * @access public
  */
 function collate_data()
 {
     global $wpdb;
     // Get purchase data, regardless of being fed the ID or the sessionid
     if ($this->purchase_id > 0) {
         $purchase_id =& $this->purchase_id;
         $purchase_logs = $wpdb->get_row($wpdb->prepare("SELECT * FROM `" . WPSC_TABLE_PURCHASE_LOGS . "` WHERE `id` = %d LIMIT 1", $purchase_id), ARRAY_A);
     } else {
         if ($this->session_id != null) {
             $purchase_logs = $wpdb->get_row($wpdb->prepare("SELECT * FROM `" . WPSC_TABLE_PURCHASE_LOGS . "` WHERE `sessionid` = %s LIMIT 1", $this->session_id), ARRAY_A);
             $this->purchase_id = $purchase_logs['id'];
             $purchase_id =& $this->purchase_id;
         }
     }
     $email_address = $wpdb->get_var("SELECT `value` FROM `" . WPSC_TABLE_CHECKOUT_FORMS . "` AS `form_field` INNER JOIN `" . WPSC_TABLE_SUBMITTED_FORM_DATA . "` AS `collected_data` ON `form_field`.`id` = `collected_data`.`form_id` WHERE `form_field`.`type` IN ( 'email' ) AND `collected_data`.`log_id` IN ( '{$purchase_id}' )");
     $currency_code = WPSC_Countries::get_currency_code(get_option('currency_type'));
     $collected_form_data = $wpdb->get_results("SELECT `data_names`.`id`, `data_names`.`unique_name`, `collected_data`.`value` FROM `" . WPSC_TABLE_SUBMITTED_FORM_DATA . "` AS `collected_data` JOIN `" . WPSC_TABLE_CHECKOUT_FORMS . "` AS `data_names` ON `collected_data`.`form_id` = `data_names`.`id` WHERE `log_id` = '" . $purchase_id . "'", ARRAY_A);
     $address_data = array('billing' => array(), 'shipping' => array());
     foreach ($collected_form_data as $collected_form_row) {
         $address_data_set = 'billing';
         $address_key = array_search($collected_form_row['unique_name'], $this->address_keys['billing']);
         if ($address_key == null) {
             $address_data_set = 'shipping';
             $address_key = array_search($collected_form_row['unique_name'], $this->address_keys['shipping']);
         }
         if ($address_key == null) {
             continue;
         }
         switch ($collected_form_row['unique_name']) {
             case 'billingcountry':
             case 'shippingcountry':
                 $country = maybe_unserialize($collected_form_row['value']);
                 if (is_array($country)) {
                     $address_data[$address_data_set]['state'] = wpsc_get_state_by_id($country[1], 'code');
                     $country = $country[0];
                 }
                 $address_data[$address_data_set][$address_key] = $country;
                 break;
             case 'billingstate':
             case 'shippingstate':
                 if (empty($address_data[$address_data_set]['state'])) {
                     $address_data[$address_data_set]['state'] = is_numeric($collected_form_row['value']) ? wpsc_get_state_by_id($collected_form_row['value'], 'code') : $collected_form_row['value'];
                 }
                 break;
             default:
                 $address_data[$address_data_set][$address_key] = $collected_form_row['value'];
                 break;
         }
     }
     if (count($address_data['shipping']) < 1) {
         $address_data['shipping'] = $address_data['billing'];
     }
     if (!empty($purchase_logs['discount_value']) && $purchase_logs['discount_value'] > 0) {
         $has_discount = true;
     } else {
         $has_discount = false;
     }
     $this->cart_data = array('software_name' => 'WP eCommerce/' . WPSC_PRESENTABLE_VERSION . '', 'store_location' => get_option('base_country'), 'store_currency' => $currency_code, 'is_subscription' => false, 'has_discounts' => $has_discount, 'cart_discount_value' => $purchase_logs['discount_value'], 'cart_discount_coupon' => $purchase_logs['discount_data'], 'cart_tax' => $purchase_logs['wpec_taxes_total'], 'notification_url' => add_query_arg('wpsc_action', 'gateway_notification', home_url('/')), 'transaction_results_url' => get_option('transact_url'), 'shopping_cart_url' => get_option('shopping_cart_url'), 'products_page_url' => get_option('product_list_url'), 'base_shipping' => $purchase_logs['base_shipping'], 'total_price' => $purchase_logs['totalprice'], 'session_id' => $purchase_logs['sessionid'], 'transaction_id' => $purchase_logs['transactid'], 'email_address' => $email_address, 'billing_address' => $address_data['billing'], 'shipping_address' => $address_data['shipping']);
 }
 /**
  * construct value array method, converts the data gathered by the base class code to something acceptable to the gateway
  * @access public
  */
 function construct_value_array()
 {
     //$collected_gateway_data
     $paypal_vars = array();
     // Store settings to be sent to paypal
     $data = array();
     $data['USER'] = get_option('paypal_pro_username');
     $data['PWD'] = get_option('paypal_pro_password');
     $data['SIGNATURE'] = get_option('paypal_pro_signature');
     $data['VERSION'] = "52.0";
     $data['METHOD'] = "DoDirectPayment";
     $data['PAYMENTACTION'] = "Sale";
     $data['RETURNFMFDETAILS'] = "1";
     // optional - return fraud management filter data
     $data['CURRENCYCODE'] = $this->get_paypal_currency_code();
     // Basic Cart Data
     $data['INVNUM'] = $this->cart_data['session_id'];
     $data['NOTIFYURL'] = add_query_arg('gateway', 'wpsc_merchant_paypal_pro', $this->cart_data['notification_url']);
     $data['IPADDRESS'] = $_SERVER["REMOTE_ADDR"];
     if ($this->cart_data['billing_address']['country'] == 'UK') {
         $this->cart_data['billing_address']['country'] = 'GB';
     }
     // Billing Data
     $data['FIRSTNAME'] = $this->cart_data['billing_address']['first_name'];
     $data['LASTNAME'] = $this->cart_data['billing_address']['last_name'];
     $data['EMAIL'] = $this->cart_data['email_address'];
     $data['STREET'] = $this->cart_data['billing_address']['address'];
     $data['CITY'] = $this->cart_data['billing_address']['city'];
     $data['STATE'] = $this->cart_data['billing_address']['state'];
     $data['COUNTRYCODE'] = $this->cart_data['billing_address']['country'];
     $data['ZIP'] = $this->cart_data['billing_address']['post_code'];
     // Shipping Data
     $data['SHIPTONAME'] = $this->cart_data['shipping_address']['first_name'] . " " . $this->cart_data['shipping_address']['last_name'];
     $data['SHIPTOSTREET'] = $this->cart_data['shipping_address']['address'];
     $data['SHIPTOCITY'] = $this->cart_data['shipping_address']['city'];
     // Check the state for internal numeric ID and trap it
     if (is_numeric($this->cart_data['shipping_address']['state'])) {
         $this->cart_data['shipping_address']['state'] = wpsc_get_state_by_id($this->cart_data['shipping_address']['state'], 'code');
     }
     if ($this->cart_data['shipping_address']['country'] == 'UK') {
         $this->cart_data['shipping_address']['country'] = 'GB';
     }
     $data['SHIPTOSTATE'] = $this->cart_data['shipping_address']['state'];
     $data['SHIPTOCOUNTRY'] = $this->cart_data['shipping_address']['country'];
     $data['SHIPTOZIP'] = $this->cart_data['shipping_address']['post_code'];
     // Credit Card Data
     $data['CREDITCARDTYPE'] = $_POST['cctype'];
     $data['ACCT'] = str_replace(array(' ', '-'), '', $_POST['card_number']);
     $data['EXPDATE'] = $_POST['expiry']['month'] . $_POST['expiry']['year'];
     $data['CVV2'] = $_POST['card_code'];
     // Ordered Items
     // Cart Item Data
     $i = $item_total = 0;
     $tax_total = wpsc_tax_isincluded() ? 0 : $this->cart_data['cart_tax'];
     $shipping_total = $this->convert($this->cart_data['base_shipping']);
     foreach ($this->cart_items as $cart_row) {
         $data['L_NAME' . $i] = apply_filters('the_title', $cart_row['name']);
         $data['L_AMT' . $i] = $this->convert($cart_row['price']);
         $data['L_NUMBER' . $i] = $i;
         $data['L_QTY' . $i] = $cart_row['quantity'];
         $shipping_total += $this->convert($cart_row['shipping']);
         $item_total += $this->convert($cart_row['price']) * $cart_row['quantity'];
         $i++;
     }
     if ($this->cart_data['has_discounts']) {
         $discount_value = $this->convert($this->cart_data['cart_discount_value']);
         $coupon = new wpsc_coupons($this->cart_data['cart_discount_data']);
         // free shipping
         if ($coupon->is_percentage == 2) {
             $shipping_total = 0;
             $discount_value = 0;
         } elseif ($discount_value >= $item_total) {
             $discount_value = $item_total - 0.01;
             $shipping_total -= 0.01;
         }
         $data["L_NAME{$i}"] = _x('Coupon / Discount', 'PayPal Pro Item Name for Discounts', 'wpsc');
         $data["L_AMT{$i}"] = -$discount_value;
         $data["L_NUMBER{$i}"] = $i;
         $data["L_QTY{$i}"] = 1;
         $item_total -= $discount_value;
     }
     // Cart totals
     $data['ITEMAMT'] = $this->format_price($item_total);
     $data['SHIPPINGAMT'] = $this->format_price($shipping_total);
     $data['TAXAMT'] = $this->convert($tax_total);
     $data['AMT'] = $data['ITEMAMT'] + $data['SHIPPINGAMT'] + $data['TAXAMT'];
     $this->collected_gateway_data = apply_filters('wpsc_paypal_pro_gateway_data_array', $data, $this->cart_items);
 }
function gateway_bitpay($seperator, $sessionid)
{
    require 'wp-content/plugins/wp-e-commerce/wpsc-merchants/bitpay/bp_lib.php';
    //$wpdb is the database handle,
    //$wpsc_cart is the shopping cart object
    global $wpdb, $wpsc_cart;
    //This grabs the purchase log id from the database
    //that refers to the $sessionid
    $purchase_log = $wpdb->get_row("SELECT * FROM `" . WPSC_TABLE_PURCHASE_LOGS . "` WHERE `sessionid`= " . $sessionid . " LIMIT 1", ARRAY_A);
    //This grabs the users info using the $purchase_log
    // from the previous SQL query
    $usersql = "SELECT `" . WPSC_TABLE_SUBMITED_FORM_DATA . "`.value,\r\n\t\t`" . WPSC_TABLE_CHECKOUT_FORMS . "`.`name`,\r\n\t\t`" . WPSC_TABLE_CHECKOUT_FORMS . "`.`unique_name` FROM\r\n\t\t`" . WPSC_TABLE_CHECKOUT_FORMS . "` LEFT JOIN\r\n\t\t`" . WPSC_TABLE_SUBMITED_FORM_DATA . "` ON\r\n\t\t`" . WPSC_TABLE_CHECKOUT_FORMS . "`.id =\r\n\t\t`" . WPSC_TABLE_SUBMITED_FORM_DATA . "`.`form_id` WHERE\r\n\t\t`" . WPSC_TABLE_SUBMITED_FORM_DATA . "`.`log_id`=" . $purchase_log['id'];
    $userinfo = $wpdb->get_results($usersql, ARRAY_A);
    // convert from awkward format
    foreach ((array) $userinfo as $value) {
        if (strlen($value['value'])) {
            $ui[$value['unique_name']] = $value['value'];
        }
    }
    $userinfo = $ui;
    // name
    if (isset($userinfo['billingfirstname'])) {
        $options['buyerName'] = $userinfo['billingfirstname'];
        if (isset($userinfo['billinglastname'])) {
            $options['buyerName'] .= ' ' . $userinfo['billinglastname'];
        }
    }
    //address -- remove newlines
    if (isset($userinfo['billingaddress'])) {
        $newline = strpos($userinfo['billingaddress'], "\n");
        if ($newline !== FALSE) {
            $options['buyerAddress1'] = substr($userinfo['billingaddress'], 0, $newline);
            $options['buyerAddress2'] = substr($userinfo['billingaddress'], $newline + 1);
            $options['buyerAddress2'] = preg_replace('/\\r\\n/', ' ', $options['buyerAddress2'], -1, $count);
        } else {
            $options['buyerAddress1'] = $userinfo['billingaddress'];
        }
    }
    // state
    if (isset($userinfo['billingstate'])) {
        $options['buyerState'] = wpsc_get_state_by_id($userinfo['billingstate'], 'code');
    }
    // more user info
    foreach (array('billingphone' => 'buyerPhone', 'billingemail' => 'buyerEmail', 'billingcity' => 'buyerCity', 'billingcountry' => 'buyerCountry', 'billingpostcode' => 'buyerZip') as $f => $t) {
        if ($userinfo[$f]) {
            $options[$t] = $userinfo[$f];
        }
    }
    // itemDesc
    if (count($wpsc_cart->cart_items) == 1) {
        $item = $wpsc_cart->cart_items[0];
        $options['itemDesc'] = $item->product_name;
        if ($item->quantity > 1) {
            $options['itemDesc'] = $item->quantity . 'x ' . $options['itemDesc'];
        }
    } else {
        foreach ($wpsc_cart->cart_items as $item) {
            $quantity += $item->quantity;
        }
        $options['itemDesc'] = $quantity . ' items';
    }
    if (get_option('permalink_structure') != '') {
        $separator = "?";
    } else {
        $separator = "&";
    }
    //currency
    $currencyId = get_option('currency_type');
    $options['currency'] = $wpdb->get_var($wpdb->prepare("SELECT `code` FROM `" . WPSC_TABLE_CURRENCY_LIST . "` WHERE `id` = %d LIMIT 1", $currencyId));
    $options['notificationURL'] = get_option('siteurl') . '/?bitpay_callback=true';
    // Test or Live mode URL switch
    $options['testMode'] = get_option('test_mode');
    //pass sessionid along so that it can be used to populate the transaction results page
    $options['redirectURL'] = get_option('bitpay_redirect') . $separator . 'sessionid=' . $sessionid;
    $options['transactionSpeed'] = get_option('bitpay_transaction_speed');
    $options['apiKey'] = get_option('bitpay_apikey');
    $options['posData'] = $sessionid;
    $options['fullNotifications'] = true;
    // truncate if longer than 100 chars
    foreach (array("buyerName", "buyerAddress1", "buyerAddress2", "buyerCity", "buyerState", "buyerZip", "buyerCountry", "buyerEmail", "buyerPhone") as $k) {
        $options[$k] = substr($options[$k], 0, 100);
    }
    $price = number_format($wpsc_cart->total_price, 2);
    $invoice = bpCreateInvoice($sessionid, $price, $sessionid, $options);
    if (isset($invoice['error'])) {
        debuglog($invoice);
        // close order
        $sql = "UPDATE `" . WPSC_TABLE_PURCHASE_LOGS . "` SET `processed`= '5' WHERE `sessionid`=" . $sessionid;
        $wpdb->query($sql);
        //redirect back to checkout page with errors
        $_SESSION['WpscGatewayErrorMessage'] = __('Sorry your transaction did not go through successfully, please try again.');
        header('Location: ' . get_option('checkout_url'));
    } else {
        $wpsc_cart->empty_cart();
        unset($_SESSION['WpscGatewayErrorMessage']);
        header('Location: ' . $invoice['url']);
        exit;
    }
}