function eStore_paypal_pdt_listener()
{
    if (isset($_GET['tx']) && isset($_GET['amt']) && get_option('eStore_display_tx_result')) {
        reset_eStore_cart();
        //Reset the cart if it's not empty yet
        include_once 'lib/gateway/paypal_utility.php';
        if (WP_ESTORE_VALIDATE_PAYPAL_PDT_USING_CURL === '1') {
            eStore_paypal_validate_pdt_with_curl();
        } else {
            eStore_paypal_validate_pdt_no_curl();
        }
    }
}
if ($wp_eStore_config->getValue('eStore_enable_store_pickup') == '1') {
    define('WP_ESTORE_DO_NOT_APPLY_SHIPPING_FOR_STORE_PICKUP', WP_ESTORE_STORE_PICKUP_LABEL);
} else {
    define('WP_ESTORE_DO_NOT_APPLY_SHIPPING_FOR_STORE_PICKUP', '0');
}
/* If you want to set one gateway as the default selected gateway then uncomment the following line 
* and use one of "authorize", "manual" or "2co" values to make that gateway as the default selected one in the cart */
//$_COOKIE['eStore_gateway'] = "authorize";
if (function_exists('is_multisite') && is_multisite()) {
    $blog_id = $wpdb->blogid;
    if (isset($_COOKIE['eStore_cart_blog_id'])) {
        if ($_COOKIE['eStore_cart_blog_id'] != $blog_id) {
            $cookie_domain = COOKIE_DOMAIN;
            //eStore_get_top_level_domain();
            setcookie("eStore_cart_blog_id", $blog_id, time() + 7200, "/", $cookie_domain);
            reset_eStore_cart();
        }
    } else {
        $cookie_domain = COOKIE_DOMAIN;
        //eStore_get_top_level_domain();
        setcookie("eStore_cart_blog_id", $blog_id, time() + 7200, "/", $cookie_domain);
    }
}
function wp_eStore_check_cookie_flag_and_store_values()
{
    if (WP_ESTORE_SAVE_SESSION_TO_COOKIE) {
        wp_eStore_save_session_values_to_cookie();
    }
}
function wp_eStore_save_session_values_to_cookie()
{
function eStore_manual_gateway_form_processing_code()
{
    if (isset($_POST['submit_shipping'])) {
        if (eStore_get_total_cart_item_qty() < 1) {
            //Cart does not have any item
            echo '<div class="eStore_error_message">Error! Your shopping cart is empty. Please add items to your cart before checking out.</div>';
            return;
        }
        $input_verified = false;
        global $wpdb;
        $wp_eStore_config = WP_eStore_Config::getInstance();
        $err_msg = eStore_check_address_details();
        if (!empty($err_msg)) {
            $msg = '<div id="error">';
            $msg .= ESTORE_REQUIRED_FIELDS_MISSING;
            $msg .= $err_msg;
            $msg .= '</div>';
            echo $msg;
        } else {
            //Fire the begin processing hook
            $clientip = $_SERVER['REMOTE_ADDR'];
            $clientemail = $_POST['email'];
            do_action('eStore_begin_manual_co_processing', $clientemail, $clientip);
            $last_records_id = $wp_eStore_config->getValue('eStore_custom_receipt_counter');
            //get_option('eStore_custom_receipt_counter');
            if (empty($last_records_id)) {
                $last_records_id = 0;
            }
            $receipt_counter = $last_records_id + 1;
            $wp_eStore_config->setValue('eStore_custom_receipt_counter', $receipt_counter);
            $wp_eStore_config->saveConfig();
            $address = $_POST['address'] . ", " . $_POST['city'] . ", " . $_POST['state'] . " " . $_POST['postcode'] . " " . $_POST['country'];
            $payment_data = extract_manaul_co_general_payment_data($_POST['firstname'], $_POST['lastname'], $_POST['email'], $address, $_POST['phone']);
            $cart_items = extract_manual_item_data();
            $cust_direction = get_option('eStore_manual_co_cust_direction');
            $curr_symbol = get_option('cart_currency_symbol');
            if (!empty($cust_direction)) {
                $cust_direction_mod = eStore_apply_post_payment_dynamic_tags($cust_direction, $payment_data, $cart_items);
                $body .= "\n-------------------------------\n";
                $body .= $cust_direction_mod;
                $body .= "\n-------------------------------\n";
            }
            $count = 1;
            $constructed_download_link .= "<br />";
            $product_key_data = "";
            $show_tax_inc_price = $wp_eStore_config->getValue('eStore_show_tax_inclusive_price');
            foreach ($_SESSION['eStore_cart'] as $item) {
                $products_table_name = $wpdb->prefix . "wp_eStore_tbl";
                $key = $item['item_number'];
                $retrieved_product = $wpdb->get_row("SELECT * FROM {$products_table_name} WHERE id = '{$key}'", OBJECT);
                $rounded_price = round($item['price'], 2);
                $body .= "\n" . WP_ESTORE_DETAILS_OF_ORDERED_PRODUCT . ": " . $count;
                $body .= "\n-------------------------";
                $body .= "\n" . ESTORE_PRODUCT_ID . ": " . $item['item_number'];
                $body .= "\n" . ESTORE_PRODUCT_NAME . ": " . $item['name'];
                if ($show_tax_inc_price == '1') {
                    $rounded_price = eStore_get_tax_include_price_by_prod_id($item['item_number'], $rounded_price);
                }
                $formatted_price = print_digi_cart_payment_currency($rounded_price, $curr_symbol);
                $body .= "\n" . ESTORE_PRICE . ": " . $formatted_price;
                $body .= "\n" . ESTORE_QUANTITY . ": " . $item['quantity'] . "\n";
                if (get_option('eStore_manual_co_give_download_links') != '') {
                    $download_link = generate_download_link_for_product($item['item_number'], $item['name'], $payment_data);
                    $constructed_download_link .= $download_link . "<br />";
                    $body .= $download_link . "\n";
                    $product_key = eStore_post_sale_retrieve_serial_key_and_update($retrieved_product, $item['name'], $item['quantity']);
                    $product_key_data .= $product_key;
                    $body .= $product_key;
                    $product_specific_instructions = eStore_get_product_specific_instructions($retrieved_product);
                    $product_specific_instructions = eStore_apply_post_payment_dynamic_tags($product_specific_instructions, $payment_data, $cart_items);
                    $body .= $product_specific_instructions;
                }
                $count++;
                //Check and signup WishList or WP eMember user if needed
                //if(get_option('eStore_manual_co_auto_update_db')=='1')
                if ($wp_eStore_config->getValue('eStore_manual_co_auto_create_membership') == '1') {
                    $member_ref = $retrieved_product->ref_text;
                    eStore_payment_debug('Checking if membership inegration is being used. Reference Text Value: ' . $member_ref, true);
                    if (!empty($member_ref)) {
                        if (get_option('eStore_enable_wishlist_int')) {
                            eStore_payment_debug('WishList integration is being used... doing member account creation/upgrade task... see the "subscription_handle_debug.log" file for details', true);
                            wl_handle_subsc_signup($payment_data, $member_ref, $payment_data['txn_id']);
                        } else {
                            if (function_exists('wp_eMember_install')) {
                                $eMember_id = $payment_data['eMember_userid'];
                                eStore_payment_debug('eMember integration is being used... doing member account creation/upgrade task... see the "subscription_handle_debug.log" file for details', true);
                                eMember_handle_subsc_signup($payment_data, $member_ref, $payment_data['txn_id'], $eMember_id);
                            }
                        }
                    }
                }
                //=== End of membership handling code ===
            }
            $body .= "\n-------------------------------\n";
            if ($show_tax_inc_price != '1') {
                $body .= ESTORE_SUB_TOTAL . ": " . print_digi_cart_payment_currency($_SESSION['eStore_cart_sub_total'], $curr_symbol);
            }
            if (!empty($_SESSION['eStore_cart_postage_cost'])) {
                $body .= "\n" . ESTORE_SHIPPING . ": " . print_digi_cart_payment_currency($_SESSION['eStore_cart_postage_cost'], $curr_symbol);
            }
            if (!empty($_SESSION['eStore_cart_total_tax'])) {
                $body .= "\n" . WP_ESTORE_TAX . ": " . print_digi_cart_payment_currency($_SESSION['eStore_cart_total_tax'], $curr_symbol);
            }
            $total = $_SESSION['eStore_cart_sub_total'] + $_SESSION['eStore_cart_postage_cost'] + $_SESSION['eStore_cart_total_tax'];
            $body .= "\n" . ESTORE_TOTAL . ": " . print_digi_cart_payment_currency($total, $curr_symbol);
            $conversion_rate = get_option('eStore_secondary_currency_conversion_rate');
            if (!empty($conversion_rate)) {
                $secondary_curr_symbol = get_option('eStore_secondary_currency_symbol');
                $body .= "\n" . ESTORE_TOTAL . ' (' . get_option('eStore_secondary_currency_code') . '): ' . print_digi_cart_payment_currency($total * $conversion_rate, $secondary_curr_symbol);
            }
            if (isset($_SESSION['eStore_store_pickup_checked']) && $_SESSION['eStore_store_pickup_checked'] == '1') {
                $body .= "\nStore Pickup: Yes";
            }
            $total_items = $count - 1;
            $body .= "\n" . WP_ESTORE_TOTAL_ITEMS_ORDERED . ": " . $total_items;
            $body .= "\n" . ESTORE_TRANSACTION_ID . ": " . $payment_data['txn_id'];
            $body .= "\n\n" . WP_ESTORE_CUSTOMER_DETAILS;
            $body .= "\n-------------------------";
            $body .= "\n" . WP_ESTORE_NAME . ": " . $_POST['firstname'] . " " . $_POST['lastname'];
            $body .= "\n" . ESTORE_EMAIL . ": " . $_POST['email'];
            $body .= "\n" . ESTORE_PHONE . ": " . $_POST['phone'];
            $body .= "\n" . ESTORE_ADDRESS . ": " . $_POST['address'];
            $body .= "\n" . ESTORE_CITY . ": " . $_POST['city'];
            $body .= "\n" . ESTORE_STATE . ": " . $_POST['state'];
            $body .= "\n" . ESTORE_POSTCODE . ": " . $_POST['postcode'];
            $body .= "\n" . ESTORE_COUNTRY . ": " . $_POST['country'];
            $body .= "\n" . WP_ESTORE_ADDITIONAL_COMMENT . ": " . $_POST['additional_comment'];
            $notify_email = get_option('eStore_manual_notify_email');
            $buyer_email = $_POST['email'];
            if (empty($notify_email)) {
                $notify_email = get_bloginfo('admin_email');
            }
            // Get referrer
            if (!empty($_SESSION['ap_id'])) {
                $referrer = $_SESSION['ap_id'];
            } else {
                if (isset($_COOKIE['ap_id'])) {
                    $referrer = $_COOKIE['ap_id'];
                }
            }
            //Call the filter for email notification body
            eStore_payment_debug('Applying filter - eStore_notification_email_body_filter', true);
            $body = apply_filters('eStore_notification_email_body_filter', $body, $payment_data, $cart_items);
            $seller_email_body = $body . "\n\n" . WP_ESTORE_REFERRER . ": " . $referrer;
            $from_email_address = get_option('eStore_download_email_address');
            $headers = 'From: ' . $from_email_address . "\r\n";
            // Notify Seller
            $n_subject = $wp_eStore_config->getValue('seller_email_subject_manual_co');
            if (empty($n_subject)) {
                $n_subject = get_option('eStore_seller_email_subj');
            }
            wp_mail($notify_email, $n_subject, $seller_email_body, $headers);
            // Notify Buyer
            $buyer_email_subj = $wp_eStore_config->getValue('buyer_email_subject_manual_co');
            if (empty($buyer_email_subj)) {
                $buyer_email_subj = get_option('eStore_buyer_email_subj');
            }
            wp_mail($buyer_email, $buyer_email_subj, $body, $headers);
            if (!empty($product_key_data)) {
                //Lets add any serial key info to the data
                $payment_data['product_key_data'] = $product_key_data;
            }
            //Fire the manual checkout hook
            do_action('eStore_manual_checkout_form_data', $payment_data, $cart_items);
            //Add to the customer database if the option is enabled
            if (get_option('eStore_manual_co_auto_update_db') == '1') {
                record_sales_data($payment_data, $cart_items);
            }
            //Perform autoresponder signup
            if (get_option('eStore_manual_co_do_autoresponder_signup') == '1') {
                eStore_item_specific_autoresponder_signup($cart_items, $_POST['firstname'], $_POST['lastname'], $_POST['email']);
                eStore_global_autoresponder_signup($_POST['firstname'], $_POST['lastname'], $_POST['email']);
            }
            //Award Affiliate Commission
            eStore_award_commission_manual_co($payment_data, $cart_items);
            // Revenue sharing
            eStore_award_author_commission_manual_co($payment_data, $cart_items);
            //Create affiliate account if needed
            eStore_handle_auto_affiliate_account_creation($payment_data);
            //Post IPN data to external site if needed
            eStore_POST_IPN_data_to_url($payment_data, '', $cart_items);
            //Save transaction result for thank you page display
            if (get_option('eStore_manual_co_give_download_links') != '') {
                $constructed_download_link = wp_eStore_replace_url_in_string_with_link($constructed_download_link);
                eStore_save_trans_result_for_thank_you_page_display($payment_data, $constructed_download_link, $cart_items);
            }
            $return_url = get_option('eStore_manual_return_url');
            if (empty($return_url)) {
                $return_url = get_bloginfo('wpurl');
            }
            //Google analytics tracking
            if (get_option('eStore_enable_analytics_tracking') && get_option('eStore_manual_co_give_download_links') != '') {
                eStore_track_ga_ecommerce($payment_data, $cart_items);
                $return_url = eStore_append_http_get_data_to_url($return_url, "eStore_manual_co_track_ga", "1");
            }
            //Reset cart and redirect to Thank you page
            reset_eStore_cart();
            eStore_redirect_to_url($return_url);
        }
    }
}
function submit_to_paypal()
{
    $eStore_default_currency = get_option('cart_payment_currency');
    $eStore_return_url = get_option('cart_return_from_paypal_url');
    $eStore_sandbox_enabled = get_option('eStore_cart_enable_sandbox');
    if (!empty($eStore_default_currency)) {
        $paypal_currency = $eStore_default_currency;
    } else {
        $paypal_currency = 'USD';
    }
    $email = get_option('cart_paypal_email');
    $myPaypal = new Paypal();
    $myPaypal->gatewayUrl = 'https://www.paypal.com/cgi-bin/webscr';
    //PAYPAL_LIVE_URL
    $myPaypal->addField('charset', "utf-8");
    $myPaypal->addField('business', $email);
    $paypal_currency = apply_filters('eStore_change_curr_code_before_payment_filter', $paypal_currency);
    $myPaypal->addField('currency_code', $paypal_currency);
    $cancel_url = get_option('cart_cancel_from_paypal_url');
    if (!empty($cancel_url)) {
        $myPaypal->addField('cancel_return', $cancel_url);
    }
    if (get_option('eStore_auto_product_delivery') != '') {
        if (WP_ESTORE_ENABLE_NEW_CHECKOUT_REDIRECTION === '1') {
            $notify = WP_ESTORE_SITE_HOME_URL . '/?estore_pp_ipn=process';
        } else {
            $notify = WP_ESTORE_URL . '/paypal.php';
        }
        $myPaypal->addField('notify_url', $notify);
    }
    // =======================
    global $wpdb;
    $products_table_name = WP_ESTORE_PRODUCTS_TABLE_NAME;
    $weight = 0;
    $count = 1;
    $all_items_digital = true;
    foreach ($_SESSION['eStore_cart'] as $item) {
        $rounded_price = round($item['price'], 2);
        $rounded_price = apply_filters('eStore_change_price_before_payment_filter', $rounded_price);
        $myPaypal->addField("item_name_{$count}", htmlspecialchars($item['name']));
        $myPaypal->addField("amount_{$count}", $rounded_price);
        $myPaypal->addField("quantity_{$count}", $item['quantity']);
        $myPaypal->addField("item_number_{$count}", $item['item_number']);
        //Check to see if this is a tax free item and set the tax accordingly so that the profile based PayPal tax can work nicely
        if ($item['tax'] == "0") {
            $myPaypal->addField("tax_{$count}", $item['tax']);
        }
        $id = $item['item_number'];
        $ret_product = $wpdb->get_row("SELECT * FROM {$products_table_name} WHERE id = '{$id}'", OBJECT);
        if (!empty($ret_product->weight)) {
            $weight += $ret_product->weight * $item['quantity'];
        }
        if (empty($item['digital_flag'])) {
            $all_items_digital = false;
        }
        $count++;
    }
    $total_items_in_cart = count($_SESSION['eStore_cart']);
    if ($total_items_in_cart == 1 && !empty($ret_product->return_url)) {
        $myPaypal->addField('return', $ret_product->return_url);
    } else {
        if (!empty($eStore_return_url)) {
            $myPaypal->addField('return', $eStore_return_url);
        }
    }
    if (!get_option('eStore_paypal_profile_shipping')) {
        //Not Using paypal's profile based shipping so include shipping otherwise ignore shipping here as it will be calculated on paypal's site
        $shipping = round($_SESSION['eStore_cart_postage_cost'], 2);
        if (!empty($shipping)) {
            $shipping = apply_filters('eStore_change_shipping_before_payment_filter', $shipping);
            //change tax amount before submitting if converting currency to another type
            $myPaypal->addField('no_shipping', '2');
            $myPaypal->addField('handling_cart', $shipping);
            //$myPaypal->addField('shipping_1', $shipping);
        } else {
            //If you do not want to collect address for checkout that has no shipping cost then uncomment the following line of code.
            //$myPaypal->addField('no_shipping', '1');
        }
    } else {
        //Include the weight for profile based shipping calc
        $myPaypal->addField('weight_cart', round($weight, 2));
        $myPaypal->addField('weight_unit', 'lbs');
        if ($all_items_digital) {
            //All the items in the cart are digital items so set the shipping flag to 0 so no shipping is charged
            $total_items = count($_SESSION['eStore_cart']);
            for ($i = 1; $i <= $total_items; $i++) {
                $myPaypal->addField('shipping_' . $i, '0');
            }
        } else {
            if (isset($_SESSION['eStore_cart_postage_cost']) && $_SESSION['eStore_cart_postage_cost'] == 0) {
                //Free shipping discount applied. send 0 shipping to override profile based shipping
                if (empty($weight)) {
                    //Add $0 shipping override
                    $myPaypal->addField('shipping_1', '0');
                }
            }
        }
    }
    if (!empty($_SESSION['eStore_cart_total_tax'])) {
        $cart_total_tax = round($_SESSION['eStore_cart_total_tax'], 2);
        $cart_total_tax = apply_filters('eStore_change_tax_before_payment_filter', $cart_total_tax);
        //change tax amount before submitting if converting currency to another type
        $myPaypal->addField('tax_cart', $cart_total_tax);
    }
    if (get_option('eStore_display_tx_result')) {
        $myPaypal->addField('rm', '1');
    }
    if (defined('WP_ESTORE_FORCE_LANGUAGE_OF_PAYPAL_PAGE') && WP_ESTORE_FORCE_LANGUAGE_OF_PAYPAL_PAGE !== '0') {
        //Set the country/region preference by force.
        $myPaypal->addField('lc', WP_ESTORE_FORCE_LANGUAGE_OF_PAYPAL_PAGE);
    }
    $myPaypal->addField('cmd', '_cart');
    $myPaypal->addField('upload', '1');
    $custom_field_val = eStore_get_custom_field_value();
    $myPaypal->addField('custom', $custom_field_val);
    $myPaypal->addField('mrb', '3FWGC6LFTMTUG');
    $page_style_name = get_option('eStore_paypal_co_page_style');
    if (!empty($page_style_name)) {
        $myPaypal->addField('page_style', $page_style_name);
    }
    $returnButtonText = get_option('eStore_paypal_return_button_text');
    if (!empty($returnButtonText)) {
        $myPaypal->addField('cbt', $returnButtonText);
    }
    // Enable sandbox mode if needed
    if ($eStore_sandbox_enabled) {
        $myPaypal->enableTestMode();
    }
    // Lets clear the cart if automatic redirection is not being used otherwise we will empty the cart after the redirection
    $PDT_auth_token = get_option('eStore_paypal_pdt_token');
    if (empty($PDT_auth_token)) {
        reset_eStore_cart();
    }
    // submit the payment!
    $myPaypal->submitPayment2(WP_ESTORE_CLICK_HERE);
}
function handle_payment_data($raw_data, $gateway)
{
    eStore_payment_debug("Handling payment data from: " . $gateway, true);
    if ($gateway == "2co") {
        $mc_currency = $raw_data['list_currency'];
        if (empty($mc_currency)) {
            $mc_currency = $raw_data['currency_code'];
        }
        $uniqueOrderId = $raw_data['item_id_1'];
        if (empty($uniqueOrderId)) {
            //This is a tank you page post (not a background IPN post)
            $uniqueOrderId = $raw_data['cart_order_id'];
        }
        $cart_items = eStore_retrieve_order_details_from_db($uniqueOrderId, $gateway, $mc_currency);
        if (empty($raw_data['message_type'])) {
            //Normal Thank You page post
            $payment_data = extract_2co_general_payment_data_secondary($raw_data, $gateway, $cart_items);
        } else {
            //proper INS post
            $payment_data = extract_2co_general_payment_data($raw_data, $gateway, $cart_items);
        }
        if ($payment_data['txn_type'] == "ORDER_CREATED") {
            eStore_payment_debug("Order Received... verifying payment data.", true);
            eStore_do_post_payment_tasks($payment_data, $cart_items);
        }
        //Log the payment and cart data to the debug file
        foreach ($payment_data as $key => $value) {
            $text .= "{$key}={$value}, ";
        }
        foreach ($cart_items as $key => $value) {
            $text .= "{$key}={$value}, ";
        }
        eStore_payment_debug($text, true, true);
    } else {
        if ($gateway == "authorize") {
            $cart_items = eStore_retrieve_order_details_from_db($raw_data['x_cust_id'], $gateway);
            $payment_data = extract_authorize_general_payment_data($raw_data, $gateway, $cart_items);
            //print_r($cart_items);
            if (!empty($cart_items)) {
                eStore_payment_debug("Order Received... verifying payment data.", true);
                eStore_do_post_payment_tasks($payment_data, $cart_items);
            } else {
                eStore_payment_debug("Cart items empty! Could not retrieve items from the database.", false);
            }
            //Log the payment data to the debug file
            foreach ($payment_data as $key => $value) {
                $text .= "{$key}={$value}, ";
            }
            foreach ($cart_items as $key => $value) {
                $text .= "{$key}={$value}, ";
            }
            eStore_payment_debug($text, true, true);
            //The pending payment data can be deleted at this stage
        }
    }
    //file_put_contents('2co_process.txt', $text);
    reset_eStore_cart();
    $post_payment_return_url = get_option('cart_return_from_paypal_url');
    $post_payment_return_url = eStore_append_http_get_data_to_url($post_payment_return_url, "reset_eStore_cart", "1");
    eStore_redirect_to_url($post_payment_return_url);
}