private function init()
 {
     global $woocommerce;
     // Load the settings.
     $this->init_form_fields();
     $this->init_settings();
     $this->crates = array();
     $this->enabled = $this->get_var('enabled');
     $this->title = $this->get_var('title');
     $this->debug = $this->get_var('debug');
     $this->availability = $this->get_var('availability');
     $this->countries = $this->get_var('countries', array());
     $this->origin_postalcode = $this->get_var('origin_postalcode');
     $this->uri = key($this->uris);
     $this->user_id = $this->get_var('user_id');
     $this->packing_method = $this->get_var('packing_method');
     $this->fee = $this->get_var('fee');
     $this->shipping_methods = $this->get_var('shipping_methods', array());
     $this->custom_methods = $this->get_var('custom_methods', array());
     $this->boxes = $this->get_var('boxes', array());
     if (empty($this->custom_methods) && !empty($this->services)) {
         foreach ($this->services as $method_key => $method_name) {
             $this->custom_methods[$method_key] = array('name' => woocommerce_clean($method_name), 'price_ajustment' => '', 'enabled' => isset($this->settings['shipping_methods']) && array_search($method_key, $this->settings['shipping_methods']) !== false || !isset($this->settings['shipping_methods']) || empty($this->settings['shipping_methods']) ? '1' : '0');
         }
     }
     // Used for weight based packing only
     $this->max_weight = '150';
     add_action('woocommerce_update_options_shipping_' . $this->id, array($this, 'process_admin_options'));
     add_action('woocommerce_update_options_shipping_' . $this->id, array($this, 'clear_transients'));
     parent::__construct();
 }
 /**
  * Process the payment
  */
 function process_payment($order_id)
 {
     global $woocommerce;
     if (class_exists('WC_Subscriptions_Order') && WC_Subscriptions_Order::order_contains_subscription($order_id)) {
         $order = new WC_Order($order_id);
         $stripe_token = isset($_POST['stripe_token']) ? woocommerce_clean($_POST['stripe_token']) : '';
         // Use Stripe CURL API for payment
         try {
             $post_data = array();
             $customer_id = 0;
             // Check if paying via customer ID
             if (isset($_POST['stripe_customer_id']) && $_POST['stripe_customer_id'] !== 'new' && is_user_logged_in()) {
                 $customer_ids = get_user_meta(get_current_user_id(), '_stripe_customer_id', false);
                 if (isset($customer_ids[$_POST['stripe_customer_id']]['customer_id'])) {
                     $customer_id = $customer_ids[$_POST['stripe_customer_id']]['customer_id'];
                 } else {
                     throw new Exception(__('Invalid card.', 'wc_stripe'));
                 }
             } elseif (empty($stripe_token)) {
                 throw new Exception(__('Please make sure your card details have been entered correctly and that your browser supports JavaScript.', 'wc_stripe'));
             }
             if (method_exists('WC_Subscriptions_Order', 'get_total_initial_payment')) {
                 $initial_payment = WC_Subscriptions_Order::get_total_initial_payment($order);
             } else {
                 $initial_payment = WC_Subscriptions_Order::get_sign_up_fee($order) + WC_Subscriptions_Order::get_price_per_period($order);
             }
             $customer_response = $this->add_customer_to_order($order, $customer_id, $stripe_token);
             if ($initial_payment > 0) {
                 $payment_response = $this->process_subscription_payment($order, $initial_payment);
             }
             if (is_wp_error($customer_response)) {
                 throw new Exception($customer_response->get_error_message());
             } else {
                 if (isset($payment_response) && is_wp_error($payment_response)) {
                     throw new Exception($payment_response->get_error_message());
                 } else {
                     // Payment complete
                     $order->payment_complete();
                     // Remove cart
                     $woocommerce->cart->empty_cart();
                     // Activate subscriptions
                     WC_Subscriptions_Manager::activate_subscriptions_for_order($order);
                     // Store token
                     if ($stripe_token) {
                         update_post_meta($order->id, '_stripe_token', $stripe_token);
                     }
                     // Return thank you page redirect
                     return array('result' => 'success', 'redirect' => $this->get_return_url($order));
                 }
             }
         } catch (Exception $e) {
             $woocommerce->add_error(__('Error:', 'wc_stripe') . ' "' . $e->getMessage() . '"');
             return;
         }
     } else {
         return parent::process_payment($order_id);
     }
 }
function custom_woocommerce_get_catalog_ordering_args($args)
{
    $orderby_value = isset($_GET['orderby']) ? woocommerce_clean($_GET['orderby']) : apply_filters('woocommerce_default_catalog_orderby', get_option('woocommerce_default_catalog_orderby'));
    if ('stock' == $orderby_value) {
        $args['orderby'] = '_stock';
        $args['order'] = 'ASC';
        $args['meta_key'] = '';
    }
    return $args;
}
 /**
  * Output the cart shortcode.
  *
  * @access public
  * @param array $atts
  * @return void
  */
 public static function output($atts)
 {
     global $woocommerce;
     if (!defined('WOOCOMMERCE_CART')) {
         define('WOOCOMMERCE_CART', true);
     }
     // Add Discount
     if (!empty($_POST['apply_coupon'])) {
         if (!empty($_POST['coupon_code'])) {
             $woocommerce->cart->add_discount(sanitize_text_field($_POST['coupon_code']));
         } else {
             $woocommerce->add_error(WC_Coupon::get_generic_coupon_error(WC_Coupon::E_WC_COUPON_PLEASE_ENTER));
         }
         // Remove Coupon Codes
     } elseif (isset($_GET['remove_discounts'])) {
         $woocommerce->cart->remove_coupons($_GET['remove_discounts']);
         // Update Shipping
     } elseif (!empty($_POST['calc_shipping']) && $woocommerce->verify_nonce('cart')) {
         $validation = $woocommerce->validation();
         $woocommerce->shipping->reset_shipping();
         $woocommerce->customer->calculated_shipping(true);
         $country = woocommerce_clean($_POST['calc_shipping_country']);
         $state = woocommerce_clean($_POST['calc_shipping_state']);
         $postcode = apply_filters('woocommerce_shipping_calculator_enable_postcode', true) ? woocommerce_clean($_POST['calc_shipping_postcode']) : '';
         $city = apply_filters('woocommerce_shipping_calculator_enable_city', false) ? woocommerce_clean($_POST['calc_shipping_city']) : '';
         if ($postcode && !$validation->is_postcode($postcode, $country)) {
             $woocommerce->add_error(__('Please enter a valid postcode/ZIP.', 'woocommerce'));
             $postcode = '';
         } elseif ($postcode) {
             $postcode = $validation->format_postcode($postcode, $country);
         }
         if ($country) {
             // Update customer location
             $woocommerce->customer->set_location($country, $state, $postcode, $city);
             $woocommerce->customer->set_shipping_location($country, $state, $postcode, $city);
             $woocommerce->add_message(__('Shipping costs updated.', 'woocommerce'));
         } else {
             $woocommerce->customer->set_to_base();
             $woocommerce->customer->set_shipping_to_base();
             $woocommerce->add_message(__('Shipping costs updated.', 'woocommerce'));
         }
         do_action('woocommerce_calculated_shipping');
     }
     // Check cart items are valid
     do_action('woocommerce_check_cart_items');
     // Calc totals
     $woocommerce->cart->calculate_totals();
     if (sizeof($woocommerce->cart->get_cart()) == 0) {
         //woocommerce_get_template( 'cart/cart-empty.php' );
         woocommerce_get_template('checkout/form-checkout.php');
     } else {
         //woocommerce_get_template( 'cart/cart.php' );
         woocommerce_get_template('checkout/form-checkout.php');
     }
 }
    /**
     * Output the product sorting options.
     *
     * @access public
     * @subpackage	Loop
     * @return void
     */
    function woocommerce_catalog_ordering()
    {
        global $woocommerce;
        $orderby = isset($_GET['orderby']) ? woocommerce_clean($_GET['orderby']) : apply_filters('woocommerce_default_catalog_orderby', get_option('woocommerce_default_catalog_orderby'));
        /**
         * Show options for ordering
         *
         * @author 		WooThemes
         * @package 	WooCommerce/Templates
         * @version     2.0.0
         */
        if (!defined('ABSPATH')) {
            exit;
        }
        // Exit if accessed directly
        global $woocommerce, $wp_query;
        if (1 == $wp_query->found_posts || !woocommerce_products_will_display()) {
            return;
        }
        ?>
        <form class="woocommerce-ordering" method="get">
            <div class="woocommerce-ordering-div">
            	<select name="orderby" class="orderby">
            		<?php 
        $catalog_orderby = apply_filters('woocommerce_catalog_orderby', array('menu_order' => __('Default sorting', 'woocommerce'), 'popularity' => __('Sort by popularity', 'woocommerce'), 'rating' => __('Sort by average rating', 'woocommerce'), 'date' => __('Sort by newness', 'woocommerce'), 'price' => __('Sort by price: low to high', 'woocommerce'), 'price-desc' => __('Sort by price: high to low', 'woocommerce')));
        if (get_option('woocommerce_enable_review_rating') == 'no') {
            unset($catalog_orderby['rating']);
        }
        foreach ($catalog_orderby as $id => $name) {
            echo '<option value="' . esc_attr($id) . '" ' . selected($orderby, $id, false) . '>' . esc_attr($name) . '</option>';
        }
        ?>
            	</select>
        	</div>
        	<?php 
        // Keep query string vars intact
        foreach ($_GET as $key => $val) {
            if ('orderby' == $key) {
                continue;
            }
            if (is_array($val)) {
                foreach ($val as $innerVal) {
                    echo '<input type="hidden" name="' . esc_attr($key) . '[]" value="' . esc_attr($innerVal) . '" />';
                }
            } else {
                echo '<input type="hidden" name="' . esc_attr($key) . '" value="' . esc_attr($val) . '" />';
            }
        }
        ?>
        </form>

<?php 
    }
 /**
  * Searches for all matching country/state/postcode tax rates.
  *
  * @access public
  * @param string $args (default: '')
  * @return array
  */
 public function find_rates($args = array(), $deprecated_state = null, $deprecated_postcode = null, $deprecated_class = null)
 {
     global $wpdb;
     // Make sure the arguments match the WC 2.0 structure
     if (is_string($args)) {
         _deprecated_argument(__CLASS__ . '->' . __FUNCTION__, '2.0', 'Use $args["country"] instead. Deprecated argument will be removed in WC 2.1.');
         $args = array('country' => $args);
     }
     if (func_num_args() > 1) {
         if (null !== $deprecated_state) {
             _deprecated_argument(__CLASS__ . '->' . __FUNCTION__, '2.0', 'Use $args["state"] instead. Deprecated argument will be removed in WC 2.1.');
             $args['state'] = $deprecated_state;
         }
         if (null !== $deprecated_postcode) {
             _deprecated_argument(__CLASS__ . '->' . __FUNCTION__, '2.0', 'Use $args["postcode"] instead. Deprecated argument will be removed in WC 2.1.');
             $args['postcode'] = $deprecated_postcode;
         }
         if (null !== $deprecated_class) {
             _deprecated_argument(__CLASS__ . '->' . __FUNCTION__, '2.0', 'Use $args["tax_class"] instead. Deprecated argument will be removed in WC 2.1.');
             $args['tax_class'] = $deprecated_class;
         }
     }
     $defaults = array('country' => '', 'state' => '', 'city' => '', 'postcode' => '', 'tax_class' => '');
     $args = wp_parse_args($args, $defaults);
     extract($args, EXTR_SKIP);
     if (!$country) {
         return array();
     }
     // Handle postcodes
     $valid_postcodes = array('*', strtoupper(woocommerce_clean($postcode)));
     // Work out possible valid wildcard postcodes
     $postcode_length = strlen($postcode);
     $wildcard_postcode = strtoupper(woocommerce_clean($postcode));
     for ($i = 0; $i < $postcode_length; $i++) {
         $wildcard_postcode = substr($wildcard_postcode, 0, -1);
         $valid_postcodes[] = $wildcard_postcode . '*';
     }
     // Run the query
     $found_rates = $wpdb->get_results($wpdb->prepare("\n\t\t\tSELECT tax_rates.* FROM\n\t\t\t\t{$wpdb->prefix}woocommerce_tax_rates as tax_rates\n\t\t\tLEFT OUTER JOIN\n\t\t\t\t{$wpdb->prefix}woocommerce_tax_rate_locations as locations ON tax_rates.tax_rate_id = locations.tax_rate_id\n\t\t\tWHERE\n\t\t\t\ttax_rate_country IN ( %s, '' )\n\t\t\t\tAND tax_rate_state IN ( %s, '' )\n\t\t\t\tAND tax_rate_class = %s\n\t\t\t\tAND (\n\t\t\t\t\t(\n\t\t\t\t\t\tlocations.location_type = 'postcode' AND locations.location_code IN ('" . implode("','", $valid_postcodes) . "')\n\t\t\t\t\t)\n\t\t\t\t\tOR\n\t\t\t\t\t(\n\t\t\t\t\t\tlocations.location_type = 'city' AND locations.location_code = %s\n\t\t\t\t\t)\n\t\t\t\t\tOR locations.location_type IS null\n\t\t\t\t)\n\t\t\tGROUP BY\n\t\t\t\ttax_rate_priority\n\t\t\tORDER BY\n\t\t\t\ttax_rate_priority, tax_rate_order\n\t\t\t", strtoupper($country), strtoupper($state), sanitize_title($tax_class), strtoupper($city)));
     // Put results into array
     $matched_tax_rates = array();
     foreach ($found_rates as $found_rate) {
         $matched_tax_rates[$found_rate->tax_rate_id] = array('rate' => $found_rate->tax_rate, 'label' => $found_rate->tax_rate_name, 'shipping' => $found_rate->tax_rate_shipping ? 'yes' : 'no', 'compound' => $found_rate->tax_rate_compound ? 'yes' : 'no');
     }
     /*
     echo '<pre>' . __( 'Matched tax rates:', 'woocommerce' );
     var_dump( $matched_tax_rates );
     echo '</pre>';
     */
     return apply_filters('woocommerce_matched_tax_rates', $matched_tax_rates, $country, $state, $postcode, $city, $tax_class);
 }
 public function createCard($giftInformation)
 {
     global $wpdb;
     if (isset($giftInformation['rpgc_description'])) {
         $giftCard['description'] = woocommerce_clean($giftInformation['rpgc_description']);
     }
     if (isset($giftInformation['rpgc_to'])) {
         $giftCard['to'] = woocommerce_clean($giftInformation['rpgc_to']);
     }
     if (isset($giftInformation['rpgc_email_to'])) {
         $giftCard['toEmail'] = woocommerce_clean($giftInformation['rpgc_email_to']);
     }
     if (isset($giftInformation['rpgc_from'])) {
         $giftCard['from'] = woocommerce_clean($giftInformation['rpgc_from']);
     }
     if (isset($giftInformation['rpgc_email_from'])) {
         $giftCard['fromEmail'] = woocommerce_clean($giftInformation['rpgc_email_from']);
     }
     if (isset($giftInformation['rpgc_amount'])) {
         $giftCard['amount'] = woocommerce_clean($giftInformation['rpgc_amount']);
         if (!isset($giftInformation['rpgc_balance'])) {
             $giftCard['balance'] = woocommerce_clean($giftInformation['rpgc_amount']);
             $giftCard['sendTheEmail'] = 1;
         }
     }
     if (isset($giftInformation['rpgc_balance'])) {
         $giftCard['balance'] = woocommerce_clean($giftInformation['rpgc_balance']);
     }
     if (isset($giftInformation['rpgc_note'])) {
         $giftCard['note'] = woocommerce_clean($giftInformation['rpgc_note']);
     }
     if (isset($giftInformation['rpgc_expiry_date'])) {
         $giftCard['expiry_date'] = woocommerce_clean($giftInformation['rpgc_expiry_date']);
     } else {
         $giftCard['expiry_date'] = '';
     }
     if ($_POST['post_title'] == '' || isset($giftInformation['rpgc_regen_number'])) {
         if ($giftInformation['rpgc_regen_number'] == 'yes' || $_POST['post_title'] == '') {
             $newNumber = apply_filters('rpgc_regen_number', $this->generateNumber());
             $wpdb->update($wpdb->posts, array('post_title' => $newNumber), array('ID' => $_POST['ID']));
             $wpdb->update($wpdb->posts, array('post_name' => $newNumber), array('ID' => $_POST['ID']));
         }
     }
     if ($giftCard['sendTheEmail'] == 1 && $giftCard['balance'] != 0 || isset($giftInformation['rpgc_resend_email'])) {
         $email = new WPR_Giftcard_Email();
         $post = get_post($_POST['ID']);
         $email->sendEmail($post);
     }
     update_post_meta($_POST['ID'], '_wpr_giftcard', $giftCard);
 }
 /**
  * Process the payment
  */
 function process_payment($order_id)
 {
     global $woocommerce;
     if (class_exists('WC_Sponsorship_Order') && WC_Sponsorship_Order::order_contains_sponsorship($order_id)) {
         $order = new WC_Order($order_id);
         $stripe_token = isset($_POST['stripe_token']) ? woocommerce_clean($_POST['stripe_token']) : '';
         // Use Stripe CURL API for payment
         try {
             $post_data = array();
             $customer_id = 0;
             // Check if paying via customer ID
             if (isset($_POST['stripe_customer_id']) && $_POST['stripe_customer_id'] !== 'new' && is_user_logged_in()) {
                 $customer_ids = get_user_meta(get_current_user_id(), '_stripe_customer_id', false);
                 if (isset($customer_ids[$_POST['stripe_customer_id']]['customer_id'])) {
                     $customer_id = $customer_ids[$_POST['stripe_customer_id']]['customer_id'];
                 } else {
                     throw new Exception(__('Invalid card.', 'wc_stripe'));
                 }
             } elseif (empty($stripe_token)) {
                 throw new Exception(__('Please make sure your card details have been entered correctly and that your browser supports JavaScript.', 'wc_stripe'));
             }
             $customer_response = $this->add_customer_to_order($order, $customer_id, $stripe_token);
             $customer_response = $this->add_customer_to_order($order, $stripe_token);
             if (is_wp_error($customer_response)) {
                 throw new Exception($customer_response->get_error_message());
             } else {
                 // Mark as on-hold (we're awaiting the cheque)
                 $order->update_status('on-hold', 'Awaiting the sponsorship project\'s goal to be met.');
                 // Empty awaiting payment session
                 if (defined($_SESSION) && array_key_exists('order_awaiting_payment', $_SESSION)) {
                     unset($_SESSION['order_awaiting_payment']);
                 }
                 // Remove cart
                 $woocommerce->cart->empty_cart();
                 // Store token
                 if ($stripe_token) {
                     update_post_meta($order->id, '_stripe_token', $stripe_token);
                 }
                 // Return thank you page redirect
                 return array('result' => 'success', 'redirect' => $this->get_return_url($order));
             }
         } catch (Exception $e) {
             $woocommerce->add_error(__('Error:', 'wc_stripe') . ' "' . $e->getMessage() . '"');
             return;
         }
     } else {
         return parent::process_payment($order_id);
     }
 }
 function save_admin_settings()
 {
     if (!is_admin()) {
         return;
     }
     $permalinks = array();
     foreach ($this->taxonomies as $taxonomy) {
         if (isset($_POST['pe_wc_product_' . $taxonomy . '_slug'])) {
             $permalinks[$taxonomy . '_tax_base'] = untrailingslashit(woocommerce_clean($_POST['pe_wc_product_' . $taxonomy . '_slug']));
         }
     }
     if (!empty($permalinks)) {
         update_option('pe_wc_permalinks', $permalinks);
         flush_rewrite_rules();
     }
 }
function rf_process_giftcard_meta($post_id, $post)
{
    global $wpdb, $woocommerce_errors;
    $code = '';
    $coupon_type = '';
    $coupon_amount = '';
    $description = '';
    $product_id = '';
    $usage_limit = '';
    $expiry_date = '';
    $wpdb->update($wpdb->posts, array('post_title' => $post->post_title), array('ID' => $post_id));
    if (isset($_POST['rf_coupon_type'])) {
        $coupon_type = woocommerce_clean($_POST['rf_coupon_type']);
        update_post_meta($post_id, 'rf_coupon_type', $coupon_type);
    }
    if (isset($_POST['rf_coupon_amount'])) {
        $coupon_amount = woocommerce_clean($_POST['rf_coupon_amount']);
        update_post_meta($post_id, 'rf_coupon_amount', $coupon_amount);
    }
    if (isset($_POST['rf_description'])) {
        $description = woocommerce_clean($_POST['rf_description']);
        update_post_meta($post_id, 'rf_description', $description);
    }
    if (isset($_POST['rf_product_id'])) {
        $product_id = woocommerce_clean($_POST['rf_product_id']);
        update_post_meta($post_id, 'rf_product_id', $product_id);
    }
    if (isset($_POST['rf_usage'])) {
        $usage = woocommerce_clean($_POST['rf_usage']);
        update_post_meta($post_id, 'rf_usage', $usage);
    }
    if (isset($_POST['rf_limit'])) {
        $limit = woocommerce_clean($_POST['rf_limit']);
        update_post_meta($post_id, 'rf_limit', $limit);
    }
    if (isset($_POST['rf_expiry_date'])) {
        $expiry_date = woocommerce_clean($_POST['rf_expiry_date']);
        update_post_meta($post_id, 'rf_expiry_date', $expiry_date);
    }
    if (isset($_POST['rf_type'])) {
        $type = woocommerce_clean($_POST['rf_type']);
        update_post_meta($post_id, 'rf_type', $type);
    }
    /* Deprecated - same hook name as in the meta */
    do_action('woocommerce_rf_options');
    do_action('woocommerce_rf_options_save');
}
 /**
  * Output the shortcode.
  *
  * @access public
  * @param array $atts
  * @return void
  */
 public static function output($atts)
 {
     global $woocommerce;
     $woocommerce->show_messages();
     $order = false;
     // Get the order
     $order_id = apply_filters('woocommerce_thankyou_order_id', empty($_GET['order']) ? 0 : absint($_GET['order']));
     $order_key = apply_filters('woocommerce_thankyou_order_key', empty($_GET['key']) ? '' : woocommerce_clean($_GET['key']));
     if ($order_id > 0) {
         $order = new WC_Order($order_id);
         if ($order->order_key != $order_key) {
             unset($order);
         }
     }
     // Empty awaiting payment session
     unset($woocommerce->session->order_awaiting_payment);
     woocommerce_get_template('checkout/thankyou.php', array('order' => $order));
 }
 /**
  * Process this field after being posted
  * @return array on success, WP_ERROR on failure
  */
 public function get_cart_item_data()
 {
     $cart_item_data = array();
     foreach ($this->addon['options'] as $option) {
         $field_name = $this->get_field_name() . '-' . sanitize_title($option['label']);
         if (!empty($_FILES[$field_name]) && !empty($_FILES[$field_name]['name'])) {
             $upload = $this->handle_upload($_FILES[$field_name]);
             if (empty($upload['error']) && !empty($upload['file'])) {
                 $value = woocommerce_clean($upload['url']);
                 $cart_item_data[] = array('name' => $this->get_option_label($option), 'value' => $value, 'display' => basename($value), 'price' => $this->get_option_price($option));
             } else {
                 return new WP_Error('addon-error', $upload['error']);
             }
         } elseif (isset($this->value[sanitize_title($option['label'])])) {
             $cart_item_data[] = array('name' => $this->get_option_label($option), 'value' => $this->value[sanitize_title($option['label'])], 'display' => basename($this->value[sanitize_title($option['label'])]), 'price' => $this->get_option_price($option));
         }
     }
     return $cart_item_data;
 }
 /**
  * Perform order actions for amazon
  */
 public function order_actions()
 {
     check_ajax_referer('amazon_order_action', 'security');
     $order_id = absint($_POST['order_id']);
     $id = isset($_POST['amazon_id']) ? woocommerce_clean($_POST['amazon_id']) : '';
     $action = sanitize_title($_POST['amazon_action']);
     switch ($action) {
         case 'refresh':
             $this->clear_stored_states($order_id);
             break;
         case 'authorize':
             // Delete old
             delete_post_meta($order_id, 'amazon_authorization_id');
             delete_post_meta($order_id, 'amazon_capture_id');
             $this->authorize_payment($order_id, $id, false);
             $this->clear_stored_states($order_id);
             break;
         case 'authorize_capture':
             // Delete old
             delete_post_meta($order_id, 'amazon_authorization_id');
             delete_post_meta($order_id, 'amazon_capture_id');
             $this->authorize_payment($order_id, $id, true);
             $this->clear_stored_states($order_id);
             break;
         case 'close_authorization':
             $this->close_authorization($order_id, $id);
             $this->clear_stored_states($order_id);
             break;
         case 'capture':
             $this->capture_payment($order_id, $id);
             $this->clear_stored_states($order_id);
             break;
         case 'refund':
             $amazon_refund_amount = floatval(woocommerce_clean($_POST['amazon_refund_amount']));
             $amazon_refund_note = woocommerce_clean($_POST['amazon_refund_note']);
             $this->refund_payment($order_id, $id, $amazon_refund_amount, $amazon_refund_note);
             $this->clear_stored_states($order_id);
             break;
     }
     die;
 }
 /**
  * Output the shortcode.
  *
  * @access public
  * @param array $atts
  * @return void
  */
 public static function output($atts)
 {
     global $woocommerce;
     $woocommerce->show_messages();
     $order = false;
     // Get the order
     //echo $order_id  = apply_filters( 'woocommerce_thankyou_order_id', empty( $_GET['order'] ) ? 0 : absint( $_GET['order'] ) );
     $order_id = base64_decode(base64_decode(str_replace('564|||', '', $_GET['order'])));
     $order_key = apply_filters('woocommerce_thankyou_order_key', empty($_GET['key']) ? '' : woocommerce_clean($_GET['key']));
     if ($order_id > 0) {
         $order = new WC_Order($order_id);
         //echo $order->order_key;
         /*echo '<pre>';
         print_r($order);echo '</pre>';*/
         /*if ( $order->order_key != $order_key )
         		unset( $order );*/
     }
     // Empty awaiting payment session
     unset($woocommerce->session->order_awaiting_payment);
     woocommerce_get_template('checkout/thankyou.php', array('order' => $order));
 }
Exemple #15
0
function siw_wc_catalog_ordering($args)
{
    $orderby_value = isset($_GET['orderby']) ? woocommerce_clean($_GET['orderby']) : apply_filters('woocommerce_default_catalog_orderby', get_option('woocommerce_default_catalog_orderby'));
    switch ($orderby_value) {
        case 'random':
            $sort_args['orderby'] = 'rand';
            $sort_args['order'] = '';
            $sort_args['meta_key'] = '';
            break;
        case 'startdate':
            $sort_args['orderby'] = 'meta_value';
            $sort_args['order'] = 'asc';
            $sort_args['meta_key'] = 'startdatum';
            break;
        case 'country':
            $sort_args['orderby'] = 'meta_value';
            $sort_args['order'] = 'asc';
            $sort_args['meta_key'] = 'land';
            break;
    }
    return $sort_args;
}
Exemple #16
0
function custom_woocommerce_get_catalog_ordering_args($args)
{
    $orderby_value = isset($_GET['orderby']) ? woocommerce_clean($_GET['orderby']) : apply_filters('woocommerce_default_catalog_orderby', get_option('woocommerce_default_catalog_orderby'));
    $args['order'] = isset($_GET['order']) && $_GET['order'] == 'DESC' ? 'DESC' : 'ASC';
    if (isset($_GET['posts_per_page']) && $_GET['posts_per_page'] != "") {
        $args['posts_per_page'] = $_GET['posts_per_page'];
        global $wp_query;
        $wp_query->set('posts_per_page', $_GET['posts_per_page']);
    }
    if ('name' == $orderby_value) {
        $args['orderby'] = 'title';
        $args['meta_key'] = '';
    } elseif ('price' == $orderby_value) {
        $args['orderby'] = 'price';
        $args['meta_key'] = '';
    } elseif ('position' == $orderby_value) {
        $args['orderby'] = 'position';
        $args['meta_key'] = '';
    }
    //echo "<pre>";
    //print_r($args);
    //echo "</pre>";
    return $args;
}
/**
 * woocommerce_tax_rates_setting_save function.
 *
 * @access public
 * @return void
 */
function woocommerce_tax_rates_setting_save()
{
    global $wpdb, $current_section;
    // Get class
    $tax_classes = array_filter(array_map('trim', explode("\n", get_option('woocommerce_tax_classes'))));
    $current_class = '';
    foreach ($tax_classes as $class) {
        if (sanitize_title($class) == $current_section) {
            $current_class = $class;
        }
    }
    // Get POST data
    $tax_rate_country = isset($_POST['tax_rate_country']) ? $_POST['tax_rate_country'] : array();
    $tax_rate_state = isset($_POST['tax_rate_state']) ? $_POST['tax_rate_state'] : array();
    $tax_rate_postcode = isset($_POST['tax_rate_postcode']) ? $_POST['tax_rate_postcode'] : array();
    $tax_rate_city = isset($_POST['tax_rate_city']) ? $_POST['tax_rate_city'] : array();
    $tax_rate = isset($_POST['tax_rate']) ? $_POST['tax_rate'] : array();
    $tax_rate_name = isset($_POST['tax_rate_name']) ? $_POST['tax_rate_name'] : array();
    $tax_rate_priority = isset($_POST['tax_rate_priority']) ? $_POST['tax_rate_priority'] : array();
    $tax_rate_compound = isset($_POST['tax_rate_compound']) ? $_POST['tax_rate_compound'] : array();
    $tax_rate_shipping = isset($_POST['tax_rate_shipping']) ? $_POST['tax_rate_shipping'] : array();
    $i = 0;
    // Loop posted fields
    foreach ($tax_rate_country as $key => $value) {
        // new keys are inserted...
        if ($key == 'new') {
            foreach ($value as $new_key => $new_value) {
                // Sanitize + format
                $country = strtoupper(woocommerce_clean($tax_rate_country[$key][$new_key]));
                $state = strtoupper(woocommerce_clean($tax_rate_state[$key][$new_key]));
                $postcode = woocommerce_clean($tax_rate_postcode[$key][$new_key]);
                $city = woocommerce_clean($tax_rate_city[$key][$new_key]);
                $rate = number_format(woocommerce_clean($tax_rate[$key][$new_key]), 4, '.', '');
                $name = woocommerce_clean($tax_rate_name[$key][$new_key]);
                $priority = absint(woocommerce_clean($tax_rate_priority[$key][$new_key]));
                $compound = isset($tax_rate_compound[$key][$new_key]) ? 1 : 0;
                $shipping = isset($tax_rate_shipping[$key][$new_key]) ? 1 : 0;
                if (!$name) {
                    $name = __('Tax', 'woocommerce');
                }
                if ($country == '*') {
                    $country = '';
                }
                if ($state == '*') {
                    $state = '';
                }
                $wpdb->insert($wpdb->prefix . "woocommerce_tax_rates", array('tax_rate_country' => $country, 'tax_rate_state' => $state, 'tax_rate' => $rate, 'tax_rate_name' => $name, 'tax_rate_priority' => $priority, 'tax_rate_compound' => $compound, 'tax_rate_shipping' => $shipping, 'tax_rate_order' => $i, 'tax_rate_class' => sanitize_title($current_class)));
                $tax_rate_id = $wpdb->insert_id;
                if (!empty($postcode)) {
                    $postcodes = explode(';', $postcode);
                    $postcodes = array_map('strtoupper', array_map('woocommerce_clean', $postcodes));
                    $postcode_query = array();
                    foreach ($postcodes as $postcode) {
                        if (strstr($postcode, '-')) {
                            $postcode_parts = explode('-', $postcode);
                            if (is_numeric($postcode_parts[0]) && is_numeric($postcode_parts[1]) && $postcode_parts[1] > $postcode_parts[0]) {
                                for ($i = $postcode_parts[0]; $i <= $postcode_parts[1]; $i++) {
                                    if ($i) {
                                        $postcode_query[] = "( '" . esc_sql($i) . "', {$tax_rate_id}, 'postcode' )";
                                    }
                                }
                            }
                        } else {
                            if ($postcode) {
                                $postcode_query[] = "( '" . esc_sql($postcode) . "', {$tax_rate_id}, 'postcode' )";
                            }
                        }
                    }
                    $wpdb->query("INSERT INTO {$wpdb->prefix}woocommerce_tax_rate_locations ( location_code, tax_rate_id, location_type ) VALUES " . implode(',', $postcode_query));
                }
                if (!empty($city)) {
                    $cities = explode(';', $city);
                    $cities = array_map('strtoupper', array_map('woocommerce_clean', $cities));
                    foreach ($cities as $city) {
                        $wpdb->insert($wpdb->prefix . "woocommerce_tax_rate_locations", array('location_code' => $city, 'tax_rate_id' => $tax_rate_id, 'location_type' => 'city'));
                    }
                }
                $i++;
            }
            // ...whereas the others are updated
        } else {
            $tax_rate_id = absint($key);
            if ($_POST['remove_tax_rate'][$key] == 1) {
                $wpdb->query($wpdb->prepare("DELETE FROM {$wpdb->prefix}woocommerce_tax_rate_locations WHERE tax_rate_id = %d;", $tax_rate_id));
                $wpdb->query($wpdb->prepare("DELETE FROM {$wpdb->prefix}woocommerce_tax_rates WHERE tax_rate_id = %d;", $tax_rate_id));
                continue;
            }
            // Sanitize + format
            $country = strtoupper(woocommerce_clean($tax_rate_country[$key]));
            $state = strtoupper(woocommerce_clean($tax_rate_state[$key]));
            $rate = number_format(woocommerce_clean($tax_rate[$key]), 4, '.', '');
            $name = woocommerce_clean($tax_rate_name[$key]);
            $priority = absint(woocommerce_clean($tax_rate_priority[$key]));
            $compound = isset($tax_rate_compound[$key]) ? 1 : 0;
            $shipping = isset($tax_rate_shipping[$key]) ? 1 : 0;
            if (!$name) {
                $name = __('Tax', 'woocommerce');
            }
            if ($country == '*') {
                $country = '';
            }
            if ($state == '*') {
                $state = '';
            }
            $wpdb->update($wpdb->prefix . "woocommerce_tax_rates", array('tax_rate_country' => $country, 'tax_rate_state' => $state, 'tax_rate' => $rate, 'tax_rate_name' => $name, 'tax_rate_priority' => $priority, 'tax_rate_compound' => $compound, 'tax_rate_shipping' => $shipping, 'tax_rate_order' => $i, 'tax_rate_class' => sanitize_title($current_class)), array('tax_rate_id' => $tax_rate_id));
            if (isset($tax_rate_postcode[$key])) {
                // Delete old
                $wpdb->query($wpdb->prepare("DELETE FROM {$wpdb->prefix}woocommerce_tax_rate_locations WHERE tax_rate_id = %d AND location_type = 'postcode';", $tax_rate_id));
                // Add changed
                $postcode = woocommerce_clean($tax_rate_postcode[$key]);
                $postcodes = explode(';', $postcode);
                $postcodes = array_map('strtoupper', array_map('woocommerce_clean', $postcodes));
                $postcode_query = array();
                foreach ($postcodes as $postcode) {
                    if (strstr($postcode, '-')) {
                        $postcode_parts = explode('-', $postcode);
                        if (is_numeric($postcode_parts[0]) && is_numeric($postcode_parts[1]) && $postcode_parts[1] > $postcode_parts[0]) {
                            for ($i = $postcode_parts[0]; $i <= $postcode_parts[1]; $i++) {
                                if ($i) {
                                    $postcode_query[] = "( '" . esc_sql($i) . "', {$tax_rate_id}, 'postcode' )";
                                }
                            }
                        }
                    } else {
                        if ($postcode) {
                            $postcode_query[] = "( '" . esc_sql($postcode) . "', {$tax_rate_id}, 'postcode' )";
                        }
                    }
                }
                $wpdb->query("INSERT INTO {$wpdb->prefix}woocommerce_tax_rate_locations ( location_code, tax_rate_id, location_type ) VALUES " . implode(',', $postcode_query));
            }
            if (isset($tax_rate_city[$key])) {
                // Delete old
                $wpdb->query($wpdb->prepare("DELETE FROM {$wpdb->prefix}woocommerce_tax_rate_locations WHERE tax_rate_id = %d AND location_type = 'city';", $tax_rate_id));
                // Add changed
                $city = woocommerce_clean($tax_rate_city[$key]);
                $cities = explode(';', $city);
                $cities = array_map('strtoupper', array_map('woocommerce_clean', $cities));
                foreach ($cities as $city) {
                    if ($city) {
                        $wpdb->insert($wpdb->prefix . "woocommerce_tax_rate_locations", array('location_code' => $city, 'tax_rate_id' => $tax_rate_id, 'location_type' => 'city'));
                    }
                }
            }
            $i++;
        }
    }
}
function woocommerce_save_attributes()
{
    global $woocommerce;
    check_ajax_referer('save-attributes', 'security');
    // Get post data
    parse_str($_POST['data'], $data);
    $post_id = absint($_POST['post_id']);
    // Save Attributes
    $attributes = array();
    if (isset($data['attribute_names'])) {
        $attribute_names = array_map('stripslashes', $data['attribute_names']);
        $attribute_values = $data['attribute_values'];
        if (isset($data['attribute_visibility'])) {
            $attribute_visibility = $data['attribute_visibility'];
        }
        if (isset($data['attribute_variation'])) {
            $attribute_variation = $data['attribute_variation'];
        }
        $attribute_is_taxonomy = $data['attribute_is_taxonomy'];
        $attribute_position = $data['attribute_position'];
        $attribute_names_count = sizeof($attribute_names);
        for ($i = 0; $i < $attribute_names_count; $i++) {
            if (!$attribute_names[$i]) {
                continue;
            }
            $is_visible = isset($attribute_visibility[$i]) ? 1 : 0;
            $is_variation = isset($attribute_variation[$i]) ? 1 : 0;
            $is_taxonomy = $attribute_is_taxonomy[$i] ? 1 : 0;
            if ($is_taxonomy) {
                if (isset($attribute_values[$i])) {
                    // Select based attributes - Format values (posted values are slugs)
                    if (is_array($attribute_values[$i])) {
                        $values = array_map('sanitize_title', $attribute_values[$i]);
                        // Text based attributes - Posted values are term names - don't change to slugs
                    } else {
                        $values = array_map('stripslashes', array_map('strip_tags', explode('|', $attribute_values[$i])));
                    }
                    // Remove empty items in the array
                    $values = array_filter($values, 'strlen');
                } else {
                    $values = array();
                }
                // Update post terms
                if (taxonomy_exists($attribute_names[$i])) {
                    wp_set_object_terms($post_id, $values, $attribute_names[$i]);
                }
                if ($values) {
                    // Add attribute to array, but don't set values
                    $attributes[sanitize_title($attribute_names[$i])] = array('name' => woocommerce_clean($attribute_names[$i]), 'value' => '', 'position' => $attribute_position[$i], 'is_visible' => $is_visible, 'is_variation' => $is_variation, 'is_taxonomy' => $is_taxonomy);
                }
            } elseif (isset($attribute_values[$i])) {
                // Text based, separate by pipe
                $values = implode(' | ', array_map('woocommerce_clean', array_map('stripslashes', explode('|', $attribute_values[$i]))));
                // Custom attribute - Add attribute to array and set the values
                $attributes[sanitize_title($attribute_names[$i])] = array('name' => woocommerce_clean($attribute_names[$i]), 'value' => $values, 'position' => $attribute_position[$i], 'is_visible' => $is_visible, 'is_variation' => $is_variation, 'is_taxonomy' => $is_taxonomy);
            }
        }
    }
    if (!function_exists('attributes_cmp')) {
        function attributes_cmp($a, $b)
        {
            if ($a['position'] == $b['position']) {
                return 0;
            }
            return $a['position'] < $b['position'] ? -1 : 1;
        }
    }
    uasort($attributes, 'attributes_cmp');
    update_post_meta($post_id, '_product_attributes', $attributes);
    die;
}
        /**
         * import function.
         *
         * @access public
         * @param mixed $file
         * @return void
         */
        function import($file)
        {
            global $woocommerce, $wpdb;
            $this->imported = $this->skipped = 0;
            if (!is_file($file)) {
                echo '<p><strong>' . __('Sorry, there has been an error.', 'woocommerce') . '</strong><br />';
                echo __('The file does not exist, please try again.', 'woocommerce') . '</p>';
                $this->footer();
                die;
            }
            $new_rates = array();
            if (($handle = fopen($file, "r")) !== FALSE) {
                $header = fgetcsv($handle, 0, $this->delimiter);
                if (sizeof($header) == 10) {
                    $loop = 0;
                    while (($row = fgetcsv($handle, 0, $this->delimiter)) !== FALSE) {
                        list($country, $state, $postcode, $city, $rate, $name, $priority, $compound, $shipping, $class) = $row;
                        $country = trim(strtoupper($country));
                        $state = trim(strtoupper($state));
                        if ($country == '*') {
                            $country = '';
                        }
                        if ($state == '*') {
                            $state = '';
                        }
                        $wpdb->insert($wpdb->prefix . "woocommerce_tax_rates", array('tax_rate_country' => $country, 'tax_rate_state' => $state, 'tax_rate' => number_format($rate, 4, '.', ''), 'tax_rate_name' => trim($name), 'tax_rate_priority' => absint($priority), 'tax_rate_compound' => $compound ? 1 : 0, 'tax_rate_shipping' => $shipping ? 1 : 0, 'tax_rate_order' => $loop, 'tax_rate_class' => sanitize_title($class)));
                        $tax_rate_id = $wpdb->insert_id;
                        $postcode = woocommerce_clean($postcode);
                        $postcodes = explode(';', $postcode);
                        $postcodes = array_map('strtoupper', array_map('woocommerce_clean', $postcodes));
                        foreach ($postcodes as $postcode) {
                            if (!empty($postcode) && $postcode != '*') {
                                $wpdb->insert($wpdb->prefix . "woocommerce_tax_rate_locations", array('location_code' => $postcode, 'tax_rate_id' => $tax_rate_id, 'location_type' => 'postcode'));
                            }
                        }
                        $city = woocommerce_clean($city);
                        $cities = explode(';', $city);
                        $cities = array_map('strtoupper', array_map('woocommerce_clean', $cities));
                        foreach ($cities as $city) {
                            if (!empty($city) && $city != '*') {
                                $wpdb->insert($wpdb->prefix . "woocommerce_tax_rate_locations", array('location_code' => $city, 'tax_rate_id' => $tax_rate_id, 'location_type' => 'city'));
                            }
                        }
                        $loop++;
                        $this->imported++;
                    }
                } else {
                    echo '<p><strong>' . __('Sorry, there has been an error.', 'woocommerce') . '</strong><br />';
                    echo __('The CSV is invalid.', 'woocommerce') . '</p>';
                    $this->footer();
                    die;
                }
                fclose($handle);
            }
            // Show Result
            echo '<div class="updated settings-error below-h2"><p>
				' . sprintf(__('Import complete - imported <strong>%s</strong> tax rates and skipped <strong>%s</strong>.', 'woocommerce'), $this->imported, $this->skipped) . '
			</p></div>';
            $this->import_end();
        }
Exemple #20
0
/**
 * Custom quick edit - save
 *
 * @access public
 * @param mixed $post_id
 * @param mixed $post
 * @return void
 */
function woocommerce_admin_product_quick_edit_save($post_id, $post)
{
    if (!$_POST || is_int(wp_is_post_revision($post_id)) || is_int(wp_is_post_autosave($post_id))) {
        return $post_id;
    }
    if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
        return $post_id;
    }
    if (!isset($_POST['woocommerce_quick_edit_nonce']) || !wp_verify_nonce($_POST['woocommerce_quick_edit_nonce'], 'woocommerce_quick_edit_nonce')) {
        return $post_id;
    }
    if (!current_user_can('edit_post', $post_id)) {
        return $post_id;
    }
    if ($post->post_type != 'product') {
        return $post_id;
    }
    global $woocommerce, $wpdb;
    $product = get_product($post);
    $old_regular_price = $product->regular_price;
    $old_sale_price = $product->sale_price;
    // Save fields
    if (isset($_POST['_sku'])) {
        update_post_meta($post_id, '_sku', woocommerce_clean($_POST['_sku']));
    }
    if (isset($_POST['_weight'])) {
        update_post_meta($post_id, '_weight', woocommerce_clean($_POST['_weight']));
    }
    if (isset($_POST['_length'])) {
        update_post_meta($post_id, '_length', woocommerce_clean($_POST['_length']));
    }
    if (isset($_POST['_width'])) {
        update_post_meta($post_id, '_width', woocommerce_clean($_POST['_width']));
    }
    if (isset($_POST['_height'])) {
        update_post_meta($post_id, '_height', woocommerce_clean($_POST['_height']));
    }
    if (isset($_POST['_stock_status'])) {
        update_post_meta($post_id, '_stock_status', woocommerce_clean($_POST['_stock_status']));
    }
    if (isset($_POST['_visibility'])) {
        update_post_meta($post_id, '_visibility', woocommerce_clean($_POST['_visibility']));
    }
    if (isset($_POST['_featured'])) {
        update_post_meta($post_id, '_featured', 'yes');
    } else {
        update_post_meta($post_id, '_featured', 'no');
    }
    if ($product->is_type('simple') || $product->is_type('external')) {
        if (isset($_POST['_regular_price'])) {
            update_post_meta($post_id, '_regular_price', woocommerce_clean($_POST['_regular_price']));
        }
        if (isset($_POST['_sale_price'])) {
            update_post_meta($post_id, '_sale_price', woocommerce_clean($_POST['_sale_price']));
        }
        // Handle price - remove dates and set to lowest
        $price_changed = false;
        if (isset($_POST['_regular_price']) && woocommerce_clean($_POST['_regular_price']) != $old_regular_price) {
            $price_changed = true;
        }
        if (isset($_POST['_sale_price']) && woocommerce_clean($_POST['_sale_price']) != $old_sale_price) {
            $price_changed = true;
        }
        if ($price_changed) {
            update_post_meta($post_id, '_sale_price_dates_from', '');
            update_post_meta($post_id, '_sale_price_dates_to', '');
            if (isset($_POST['_sale_price']) && $_POST['_sale_price'] != '') {
                update_post_meta($post_id, '_price', woocommerce_clean($_POST['_sale_price']));
            } else {
                update_post_meta($post_id, '_price', woocommerce_clean($_POST['_regular_price']));
            }
        }
    }
    // Handle stock
    if (!$product->is_type('grouped')) {
        if (isset($_POST['_manage_stock'])) {
            update_post_meta($post_id, '_manage_stock', 'yes');
            update_post_meta($post_id, '_stock', (int) $_POST['_stock']);
        } else {
            update_post_meta($post_id, '_manage_stock', 'no');
            update_post_meta($post_id, '_stock', '0');
        }
    }
    // Clear transient
    $woocommerce->clear_product_transients($post_id);
}
function woocommerce_add_order_note()
{
    global $woocommerce;
    check_ajax_referer('add-order-note', 'security');
    $post_id = (int) $_POST['post_id'];
    $note = strip_tags(woocommerce_clean($_POST['note']));
    $note_type = $_POST['note_type'];
    $is_customer_note = $note_type == 'customer' ? 1 : 0;
    if ($post_id > 0) {
        $order = new WC_Order($post_id);
        $comment_id = $order->add_order_note($note, $is_customer_note);
        echo '<li rel="' . $comment_id . '" class="note ';
        if ($is_customer_note) {
            echo 'customer-note';
        }
        echo '"><div class="note_content">';
        echo wpautop(wptexturize($note));
        echo '</div><p class="meta">' . sprintf(__('added %s ago', 'woocommerce'), human_time_diff(current_time('timestamp'))) . ' - <a href="#" class="delete_note">' . __('Delete note', 'woocommerce') . '</a></p>';
        echo '</li>';
    }
    // Quit out
    die;
}
    function woocommerce_form_field($key, $args, $value = '')
    {
        global $woocommerce;
        $defaults = array('type' => 'text', 'label' => '', 'placeholder' => '', 'required' => false, 'class' => array(), 'label_class' => array(), 'return' => false, 'options' => array());
        $args = wp_parse_args($args, $defaults);
        if (isset($args['clear']) && $args['clear']) {
            $after = '<div class="clear"></div>';
        } else {
            $after = '';
        }
        $required = $args['required'] ? ' <abbr class="required" title="' . esc_attr__('required', 'woocommerce') . '">*</abbr>' : '';
        switch ($args['type']) {
            case "country":
                $field = '<p class="form-row ' . implode(' ', $args['class']) . '" id="' . $key . '_field">
					<label for="' . $key . '" class="' . implode(' ', $args['label_class']) . '">' . $args['label'] . $required . '</label>
					<select name="' . $key . '" id="' . $key . '" class="country_to_state ' . implode(' ', $args['class']) . '">
						<option value="">' . __('Select a country&hellip;', 'woocommerce') . '</option>';
                foreach ($woocommerce->countries->get_allowed_countries() as $ckey => $cvalue) {
                    $field .= '<option value="' . $ckey . '" ' . selected($value, $ckey, false) . '>' . __($cvalue, 'woocommerce') . '</option>';
                }
                $field .= '</select>';
                $field .= '<noscript><input type="submit" name="woocommerce_checkout_update_totals" value="' . __('Update country', 'woocommerce') . '" /></noscript>';
                $field .= '</p>' . $after;
                break;
            case "state":
                /* Get Country */
                $country_key = $key == 'billing_state' ? 'billing_country' : 'shipping_country';
                if (isset($_POST[$country_key])) {
                    $current_cc = woocommerce_clean($_POST[$country_key]);
                } elseif (is_user_logged_in()) {
                    $current_cc = get_user_meta(get_current_user_id(), $country_key, true);
                } elseif ($country_key == 'billing_country') {
                    $current_cc = apply_filters('default_checkout_country', $woocommerce->customer->get_country() ? $woocommerce->customer->get_country() : $woocommerce->countries->get_base_country());
                } else {
                    $current_cc = apply_filters('default_checkout_country', $woocommerce->customer->get_shipping_country() ? $woocommerce->customer->get_shipping_country() : $woocommerce->countries->get_base_country());
                }
                $states = $woocommerce->countries->get_states($current_cc);
                if (is_array($states) && empty($states)) {
                    $field = '<p class="form-row ' . implode(' ', $args['class']) . '" id="' . $key . '_field" style="display: none">';
                    $field .= '<label for="' . $key . '" class="' . implode(' ', $args['label_class']) . '">' . $args['label'] . $required . '</label>';
                    $field .= '<input type="hidden" class="hidden" name="' . $key . '" id="' . $key . '" value="" />';
                    $field .= '</p>' . $after;
                } elseif (is_array($states)) {
                    $field = '<p class="form-row ' . implode(' ', $args['class']) . '" id="' . $key . '_field">';
                    $field .= '<label for="' . $key . '" class="' . implode(' ', $args['label_class']) . '">' . $args['label'] . $required . '</label>';
                    $field .= '<select name="' . $key . '" id="' . $key . '" class="state_select">
					<option value="">' . __('Select a state&hellip;', 'woocommerce') . '</option>';
                    foreach ($states as $ckey => $cvalue) {
                        $field .= '<option value="' . $ckey . '" ' . selected($value, $ckey, false) . '>' . __($cvalue, 'woocommerce') . '</option>';
                    }
                    $field .= '</select>';
                    $field .= '</p>' . $after;
                } else {
                    $field = '<p class="form-row ' . implode(' ', $args['class']) . '" id="' . $key . '_field">';
                    $field .= '<label for="' . $key . '" class="' . implode(' ', $args['label_class']) . '">' . $args['label'] . $required . '</label>';
                    $field .= '<input type="text" class="input-text" value="' . $value . '"  placeholder="' . $args['placeholder'] . '" name="' . $key . '" id="' . $key . '" />';
                    $field .= '</p>' . $after;
                }
                break;
            case "textarea":
                $field = '<p class="form-row ' . implode(' ', $args['class']) . '" id="' . $key . '_field">
					<label for="' . $key . '" class="' . implode(' ', $args['label_class']) . '">' . $args['label'] . $required . '</label>
					<textarea name="' . $key . '" class="input-text" id="' . $key . '" placeholder="' . $args['placeholder'] . '" cols="5" rows="2">' . esc_textarea($value) . '</textarea>
				</p>' . $after;
                break;
            case "checkbox":
                $field = '<p class="form-row ' . implode(' ', $args['class']) . '" id="' . $key . '_field">
					<input type="' . $args['type'] . '" class="input-checkbox" name="' . $key . '" id="' . $key . '" value="1" ' . checked($value, 1, false) . ' />
					<label for="' . $key . '" class="checkbox ' . implode(' ', $args['label_class']) . '">' . $args['label'] . $required . '</label>
				</p>' . $after;
                break;
            case "password":
                $field = '<p class="form-row ' . implode(' ', $args['class']) . '" id="' . $key . '_field">
					<label for="' . $key . '" class="' . implode(' ', $args['label_class']) . '">' . $args['label'] . $required . '</label>
					<input type="password" class="input-text" name="' . $key . '" id="' . $key . '" placeholder="' . $args['placeholder'] . '" value="' . $value . '" />
				</p>' . $after;
                break;
            case "text":
                $field = '<p class="form-row ' . implode(' ', $args['class']) . '" id="' . $key . '_field">
					<label for="' . $key . '" class="' . implode(' ', $args['label_class']) . '">' . $args['label'] . $required . '</label>
					<input type="text" class="input-text" name="' . $key . '" id="' . $key . '" placeholder="' . $args['placeholder'] . '" value="' . $value . '" />
				</p>' . $after;
                break;
            case "select":
                $options = '';
                if (!empty($args['options'])) {
                    foreach ($args['options'] as $option_key => $option_text) {
                        $options .= '<option value="' . $option_key . '" ' . selected($value, $option_key, false) . '>' . $option_text . '</option>';
                    }
                }
                $field = '<p class="form-row ' . implode(' ', $args['class']) . '" id="' . $key . '_field">
					<label for="' . $key . '" class="' . implode(' ', $args['label_class']) . '">' . $args['label'] . $required . '</label>
					<select name="' . $key . '" id="' . $key . '" class="select">
						' . $options . '
					</select>
				</p>' . $after;
                break;
            default:
                $field = apply_filters('woocommerce_form_field_' . $args['type'], '', $key, $args, $value);
                break;
        }
        if ($args['return']) {
            return $field;
        } else {
            echo $field;
        }
    }
 /**
  * Update the recurring payment method for a subscription after a customer has paid for a failed renewal order
  * (which usually failed because of an issue with the existing payment, like an expired card or token).
  *
  * Also trigger a hook for payment gateways to update any meta on the original order for a subscription.
  *
  * @param WC_Order $renewal_order The order which recorded the successful payment (to make up for the failed automatic payment).
  * @param WC_Order $original_order The original order in which the subscription was purchased.
  * @since 1.4
  */
 public static function change_failing_payment_method($renewal_order, $original_order)
 {
     $subscription_key = WC_Subscriptions_Manager::get_subscription_key($original_order->id);
     $new_payment_method = woocommerce_clean($_POST['payment_method']);
     self::update_recurring_payment_method($subscription_key, $original_order, $new_payment_method);
     do_action('woocommerce_subscriptions_changed_failing_payment_method', $original_order, $renewal_order, $subscription_key);
     do_action('woocommerce_subscriptions_changed_failing_payment_method_' . $new_payment_method, $original_order, $renewal_order, $subscription_key);
 }
 /**
  * Process the checkout after the confirm order button is pressed
  *
  * @access public
  * @return void
  */
 public function process_checkout()
 {
     global $wpdb, $woocommerce, $current_user;
     $woocommerce->verify_nonce('process_checkout');
     if (!defined('WOOCOMMERCE_CHECKOUT')) {
         define('WOOCOMMERCE_CHECKOUT', true);
     }
     // Prevent timeout
     @set_time_limit(0);
     do_action('woocommerce_before_checkout_process');
     if (sizeof($woocommerce->cart->get_cart()) == 0) {
         $woocommerce->add_error(sprintf(__('Sorry, your session has expired. <a href="%s">Return to homepage &rarr;</a>', 'woocommerce'), home_url()));
     }
     do_action('woocommerce_checkout_process');
     // Checkout fields (not defined in checkout_fields)
     $this->posted['shiptobilling'] = isset($_POST['shiptobilling']) ? 1 : 0;
     $this->posted['terms'] = isset($_POST['terms']) ? 1 : 0;
     $this->posted['createaccount'] = isset($_POST['createaccount']) ? 1 : 0;
     $this->posted['payment_method'] = isset($_POST['payment_method']) ? woocommerce_clean($_POST['payment_method']) : '';
     $this->posted['shipping_method'] = isset($_POST['shipping_method']) ? woocommerce_clean($_POST['shipping_method']) : '';
     // Ship to billing only option
     if ($woocommerce->cart->ship_to_billing_address_only()) {
         $this->posted['shiptobilling'] = 1;
     }
     // Update customer shipping and payment method to posted method
     $woocommerce->session->chosen_shipping_method = $this->posted['shipping_method'];
     $woocommerce->session->chosen_payment_method = $this->posted['payment_method'];
     // Note if we skip shipping
     $skipped_shipping = false;
     // Get validation class
     $validation = $woocommerce->validation();
     // Get posted checkout_fields and do validation
     foreach ($this->checkout_fields as $fieldset_key => $fieldset) {
         // Skip shipping if its not needed
         if ($fieldset_key == 'shipping' && ($woocommerce->cart->ship_to_billing_address_only() || $this->posted['shiptobilling'] || !$woocommerce->cart->needs_shipping() && get_option('woocommerce_require_shipping_address') == 'no')) {
             $skipped_shipping = true;
             continue;
         }
         foreach ($fieldset as $key => $field) {
             if (!isset($field['type'])) {
                 $field['type'] = 'text';
             }
             // Get Value
             switch ($field['type']) {
                 case "checkbox":
                     $this->posted[$key] = isset($_POST[$key]) ? 1 : 0;
                     break;
                 case "multiselect":
                     $this->posted[$key] = isset($_POST[$key]) ? implode(', ', array_map('woocommerce_clean', $_POST[$key])) : '';
                     break;
                 default:
                     $this->posted[$key] = isset($_POST[$key]) ? woocommerce_clean($_POST[$key]) : '';
                     break;
             }
             // Hooks to allow modification of value
             $this->posted[$key] = apply_filters('woocommerce_process_checkout_' . sanitize_title($field['type']) . '_field', $this->posted[$key]);
             $this->posted[$key] = apply_filters('woocommerce_process_checkout_field_' . $key, $this->posted[$key]);
             // Validation: Required fields
             if (isset($field['required']) && $field['required'] && empty($this->posted[$key])) {
                 $woocommerce->add_error('<strong>' . $field['label'] . '</strong> ' . __('is a required field.', 'woocommerce'));
             }
             if (!empty($this->posted[$key])) {
                 // Special handling for validation and formatting
                 switch ($key) {
                     case "billing_postcode":
                     case "shipping_postcode":
                         $validate_against = $key == 'billing_postcode' ? 'billing_country' : 'shipping_country';
                         $this->posted[$key] = strtoupper(str_replace(' ', '', $this->posted[$key]));
                         if (!$validation->is_postcode($this->posted[$key], $_POST[$validate_against])) {
                             $woocommerce->add_error('<strong>' . $field['label'] . '</strong> ' . sprintf(__('(%s) is not a valid postcode/ZIP.', 'woocommerce'), $this->posted[$key]));
                         } else {
                             $this->posted[$key] = $validation->format_postcode($this->posted[$key], $_POST[$validate_against]);
                         }
                         break;
                     case "billing_state":
                     case "shipping_state":
                         // Get valid states
                         $validate_against = $key == 'billing_state' ? 'billing_country' : 'shipping_country';
                         $valid_states = $woocommerce->countries->get_states($_POST[$validate_against]);
                         if ($valid_states) {
                             $valid_state_values = array_flip(array_map('strtolower', $valid_states));
                         }
                         // Convert value to key if set
                         if (isset($valid_state_values[strtolower($this->posted[$key])])) {
                             $this->posted[$key] = $valid_state_values[strtolower($this->posted[$key])];
                         }
                         // Only validate if the country has specific state options
                         if ($valid_states && sizeof($valid_states) > 0) {
                             if (!in_array($this->posted[$key], array_keys($valid_states))) {
                                 $woocommerce->add_error('<strong>' . $field['label'] . '</strong> ' . __('is not valid. Please enter one of the following:', 'woocommerce') . ' ' . implode(', ', $valid_states));
                             }
                         }
                         break;
                     case "billing_phone":
                         $this->posted[$key] = $validation->format_phone($this->posted[$key]);
                         if (!$validation->is_phone($this->posted[$key])) {
                             $woocommerce->add_error('<strong>' . $field['label'] . '</strong> ' . __('is not a valid number.', 'woocommerce'));
                         }
                         break;
                     case "billing_email":
                         $this->posted[$key] = strtolower($this->posted[$key]);
                         if (!$validation->is_email($this->posted[$key])) {
                             $woocommerce->add_error('<strong>' . $field['label'] . '</strong> ' . __('is not a valid email address.', 'woocommerce'));
                         }
                         break;
                 }
             }
         }
     }
     // Update customer location to posted location so we can correctly check available shipping methods
     if (isset($this->posted['billing_country'])) {
         $woocommerce->customer->set_country($this->posted['billing_country']);
     }
     if (isset($this->posted['billing_state'])) {
         $woocommerce->customer->set_state($this->posted['billing_state']);
     }
     if (isset($this->posted['billing_postcode'])) {
         $woocommerce->customer->set_postcode($this->posted['billing_postcode']);
     }
     // Shipping Information
     if (!$skipped_shipping) {
         // Update customer location to posted location so we can correctly check available shipping methods
         if (isset($this->posted['shipping_country'])) {
             $woocommerce->customer->set_shipping_country($this->posted['shipping_country']);
         }
         if (isset($this->posted['shipping_state'])) {
             $woocommerce->customer->set_shipping_state($this->posted['shipping_state']);
         }
         if (isset($this->posted['shipping_postcode'])) {
             $woocommerce->customer->set_shipping_postcode($this->posted['shipping_postcode']);
         }
     } else {
         // Update customer location to posted location so we can correctly check available shipping methods
         if (isset($this->posted['billing_country'])) {
             $woocommerce->customer->set_shipping_country($this->posted['billing_country']);
         }
         if (isset($this->posted['billing_state'])) {
             $woocommerce->customer->set_shipping_state($this->posted['billing_state']);
         }
         if (isset($this->posted['billing_postcode'])) {
             $woocommerce->customer->set_shipping_postcode($this->posted['billing_postcode']);
         }
     }
     // Update cart totals now we have customer address
     $woocommerce->cart->calculate_totals();
     // Handle accounts
     if (is_user_logged_in()) {
         $this->creating_account = false;
     } elseif (!empty($this->posted['createaccount'])) {
         $this->creating_account = true;
     } elseif ($this->must_create_account) {
         $this->creating_account = true;
     } else {
         $this->creating_account = false;
     }
     if ($this->creating_account) {
         if (get_option('woocommerce_registration_email_for_username') == 'no') {
             if (empty($this->posted['account_username'])) {
                 $woocommerce->add_error(__('Please enter an account username.', 'woocommerce'));
             }
             // Check the username
             if (!validate_username($this->posted['account_username'])) {
                 $woocommerce->add_error(__('Invalid email/username.', 'woocommerce'));
             } elseif (username_exists($this->posted['account_username'])) {
                 $woocommerce->add_error(__('An account is already registered with that username. Please choose another.', 'woocommerce'));
             }
         } else {
             $this->posted['account_username'] = $this->posted['billing_email'];
         }
         // Validate passwords
         if (empty($this->posted['account_password'])) {
             $woocommerce->add_error(__('Please enter an account password.', 'woocommerce'));
         }
         if ($this->posted['account_password-2'] !== $this->posted['account_password']) {
             $woocommerce->add_error(__('Passwords do not match.', 'woocommerce'));
         }
         // Check the e-mail address
         if (email_exists($this->posted['billing_email'])) {
             $woocommerce->add_error(__('An account is already registered with your email address. Please login.', 'woocommerce'));
         }
     }
     // Terms
     if (!isset($_POST['woocommerce_checkout_update_totals']) && empty($this->posted['terms']) && woocommerce_get_page_id('terms') > 0) {
         $woocommerce->add_error(__('You must accept our Terms &amp; Conditions.', 'woocommerce'));
     }
     if ($woocommerce->cart->needs_shipping()) {
         // Shipping Method
         $available_methods = $woocommerce->shipping->get_available_shipping_methods();
         if (!isset($available_methods[$this->posted['shipping_method']])) {
             $this->shipping_method = '';
             $woocommerce->add_error(__('Invalid shipping method.', 'woocommerce'));
         } else {
             $this->shipping_method = $available_methods[$this->posted['shipping_method']];
         }
     }
     if ($woocommerce->cart->needs_payment()) {
         // Payment Method
         $available_gateways = $woocommerce->payment_gateways->get_available_payment_gateways();
         if (!isset($available_gateways[$this->posted['payment_method']])) {
             $this->payment_method = '';
             $woocommerce->add_error(__('Invalid payment method.', 'woocommerce'));
         } else {
             $this->payment_method = $available_gateways[$this->posted['payment_method']];
             $this->payment_method->validate_fields();
         }
     }
     // Action after validation
     do_action('woocommerce_after_checkout_validation', $this->posted);
     if (!isset($_POST['woocommerce_checkout_update_totals']) && $woocommerce->error_count() == 0) {
         $this->customer_id = get_current_user_id();
         try {
             // Create customer account and log them in
             if ($this->creating_account && !$this->customer_id) {
                 $reg_errors = new WP_Error();
                 do_action('woocommerce_register_post', $this->posted['account_username'], $this->posted['billing_email'], $reg_errors);
                 $errors = apply_filters('woocommerce_registration_errors', $reg_errors, $this->posted['account_username'], $this->posted['billing_email']);
                 // if there are no errors, let's create the user account
                 if (!$reg_errors->get_error_code()) {
                     $user_pass = esc_attr($this->posted['account_password']);
                     $new_customer_data = array('user_login' => $this->posted['account_username'], 'user_pass' => $user_pass, 'user_email' => $this->posted['billing_email'], 'role' => 'customer');
                     $this->customer_id = wp_insert_user(apply_filters('woocommerce_new_customer_data', $new_customer_data));
                     if (is_wp_error($this->customer_id)) {
                         throw new MyException('<strong>' . __('ERROR', 'woocommerce') . '</strong>: ' . __('Couldn&#8217;t register you&hellip; please contact us if you continue to have problems.', 'woocommerce'));
                     }
                     // Set the global user object
                     $current_user = get_user_by('id', $this->customer_id);
                     // Action
                     do_action('woocommerce_created_customer', $this->customer_id);
                     // send the user a confirmation and their login details
                     $mailer = $woocommerce->mailer();
                     $mailer->customer_new_account($this->customer_id, $user_pass);
                     // set the WP login cookie
                     $secure_cookie = is_ssl() ? true : false;
                     wp_set_auth_cookie($this->customer_id, true, $secure_cookie);
                 } else {
                     throw new MyException($reg_errors->get_error_message());
                 }
             }
             // Abort if errors are present
             if ($woocommerce->error_count() > 0) {
                 throw new MyException();
             }
             // Create the order
             $order_id = $this->create_order();
             // Order is saved
             do_action('woocommerce_checkout_order_processed', $order_id, $this->posted);
             // Process payment
             if ($woocommerce->cart->needs_payment()) {
                 // Store Order ID in session so it can be re-used after payment failure
                 $woocommerce->session->order_awaiting_payment = $order_id;
                 // Process Payment
                 $result = $available_gateways[$this->posted['payment_method']]->process_payment($order_id);
                 // Redirect to success/confirmation/payment page
                 if ($result['result'] == 'success') {
                     $result = apply_filters('woocommerce_payment_successful_result', $result);
                     if (is_ajax()) {
                         echo '<!--WC_START-->' . json_encode($result) . '<!--WC_END-->';
                         exit;
                     } else {
                         wp_redirect($result['redirect']);
                         exit;
                     }
                 }
             } else {
                 if (empty($order)) {
                     $order = new WC_Order($order_id);
                 }
                 // No payment was required for order
                 $order->payment_complete();
                 // Empty the Cart
                 $woocommerce->cart->empty_cart();
                 // Get redirect
                 $return_url = get_permalink(woocommerce_get_page_id('thanks'));
                 $return_url = add_query_arg('key', $order->order_key, add_query_arg('order', $order->id, $return_url));
                 // Redirect to success/confirmation/payment page
                 if (is_ajax()) {
                     echo '<!--WC_START-->' . json_encode(array('result' => 'success', 'redirect' => apply_filters('woocommerce_checkout_no_payment_needed_redirect', $return_url, $order))) . '<!--WC_END-->';
                     exit;
                 } else {
                     wp_safe_redirect(apply_filters('woocommerce_checkout_no_payment_needed_redirect', $return_url, $order));
                     exit;
                 }
             }
         } catch (Exception $e) {
             if (!empty($e)) {
                 $woocommerce->add_error($e);
             }
         }
     }
     // endif
     // If we reached this point then there were errors
     if (is_ajax()) {
         ob_start();
         $woocommerce->show_messages();
         $messages = ob_get_clean();
         echo '<!--WC_START-->' . json_encode(array('result' => 'failure', 'messages' => $messages, 'refresh' => isset($woocommerce->session->refresh_totals) ? 'true' : 'false')) . '<!--WC_END-->';
         unset($woocommerce->session->refresh_totals);
         exit;
     }
 }
 /**
  * Process the payment
  */
 function process_payment($order_id)
 {
     global $woocommerce;
     $order = new WC_Order($order_id);
     $card_type = isset($_POST['eway_card_type']) ? woocommerce_clean($_POST['eway_card_type']) : '';
     $card_number = isset($_POST['eway_card_number']) ? woocommerce_clean($_POST['eway_card_number']) : '';
     $cardholder_name = isset($_POST['eway_card_holdername']) ? woocommerce_clean($_POST['eway_card_holdername']) : '';
     $card_csc = isset($_POST['eway_card_csc']) ? woocommerce_clean($_POST['eway_card_csc']) : '';
     $card_exp_month = isset($_POST['eway_card_expiration_month']) ? woocommerce_clean($_POST['eway_card_expiration_month']) : '';
     $card_exp_year = isset($_POST['eway_card_expiration_year']) ? woocommerce_clean($_POST['eway_card_expiration_year']) : '';
     // Format card expiration data
     $card_exp_month = (int) $card_exp_month;
     if ($card_exp_month < 10) {
         $card_exp_month = '0' . $card_exp_month;
     }
     $card_exp_year = (int) $card_exp_year;
     $card_exp_year += 2000;
     $card_exp = $card_exp_month . $card_exp_year;
     // Format card number
     $card_number = str_replace(array(' ', '-'), '', $card_number);
     // Send request to eway
     try {
         $url = $this->antifraud == "yes" ? $this->antifraudurl : $this->testmode == 'yes' ? $this->testurl : $this->liveurl;
         $post_data = array('ewayCustomerID' => $this->customer_id, 'ewayTotalAmount' => $order->order_total * 100, 'ewayCardNumber' => $card_number, 'ewayCardExpiryMonth' => $card_exp_month, 'ewayCardExpiryYear' => $card_exp_year, 'ewayCVN' => $card_csc, 'ewayTrxnNumber' => '', 'ewayCustomerInvoiceDescription' => '', 'ewayCustomerInvoiceRef' => '', 'ewayOption1' => '', 'ewayOption2' => '', 'ewayOption3' => '', 'ewayCustomerFirstName' => $order->billing_first_name, 'ewayCustomerLastName' => $order->billing_last_name, 'ewayCustomerEmail' => $order->billing_email, 'ewayCardHoldersName' => $cardholder_name, 'ewayCustomerAddress' => $order->billing_address_1 . ' ' . $order->billing_address_2 . ' ' . $order->billing_city . ' ' . $order->billing_state . ' ' . $order->billing_country, 'ewayCustomerPostcode' => $order->billing_postcode);
         if ($this->antifraud == "yes") {
             $post_data['ewayCustomerIPAddress'] = $this->get_user_ip();
             $post_data['ewayCustomerBillingCountry'] = $this->get_country_code();
         }
         $xmlRequest = "<ewaygateway>";
         foreach ($post_data as $key => $value) {
             $xmlRequest .= "<{$key}>{$value}</{$key}>";
         }
         $xmlRequest .= "</ewaygateway>";
         $response = wp_remote_post($url, array('method' => 'POST', 'body' => $xmlRequest, 'timeout' => 70, 'sslverify' => true));
         if (is_wp_error($response)) {
             throw new Exception(__('There was a problem connecting to the payment gateway.', 'woothemes'));
         }
         if (empty($response['body'])) {
             throw new Exception(__('Empty eWAY response.', 'woothemes'));
         }
         $parsed_response = $response['body'];
         $parsed_response = $this->parseResponse($parsed_response);
         switch (strtolower($parsed_response['EWAYTRXNSTATUS'])) {
             case 'true':
                 // Add order note
                 $order->add_order_note(sprintf(__('eWAY payment completed', 'woothemes')));
                 // Payment complete
                 $order->payment_complete();
                 // Remove cart
                 $woocommerce->cart->empty_cart();
                 // Empty awaiting payment session
                 unset($_SESSION['order_awaiting_payment']);
                 // Return thank you page redirect
                 return array('result' => 'success', 'redirect' => add_query_arg('key', $order->order_key, add_query_arg('order', $order_id, get_permalink(get_option('woocommerce_thanks_page_id')))));
                 break;
             case 'false':
                 // Payment failed :(
                 $order->add_order_note(sprintf(__('eWAY payment failed (Correlation ID: %s). Payment was rejected due to an error: ', 'woothemes'), $parsed_response['EWAYAUTHCODE']) . '"' . $parsed_response['EWAYTRXNERROR'] . '"');
                 $woocommerce->add_error(__('Payment error:', 'woothemes') . $parsed_response['EWAYTRXNERROR']);
                 return;
                 break;
             default:
                 // Payment failed :(
                 $order->add_order_note(sprintf(__('eWAY payment failed (Correlation ID: %s). Payment was rejected due to an error: ', 'woothemes'), $parsed_response['CORRELATIONID']) . '"' . $error_message . '"');
                 $woocommerce->add_error(__('Payment error:', 'woothemes') . $parsed_response['EWAYTRXNERROR']);
                 return;
                 break;
         }
     } catch (Exception $e) {
         $woocommerce->add_error(__('Connection error:', 'woothemes') . ': "' . $e->getMessage() . '"');
         return;
     }
 }
Exemple #26
0
/**
 * Update all settings which are passed.
 *
 * @access public
 * @param array $options
 * @return void
 */
function woocommerce_update_options($options)
{
    if (empty($_POST)) {
        return false;
    }
    // Options to update will be stored here
    $update_options = array();
    // Loop options and get values to save
    foreach ($options as $value) {
        if (!isset($value['id'])) {
            continue;
        }
        $type = isset($value['type']) ? sanitize_title($value['type']) : '';
        // Get the option name
        $option_value = null;
        switch ($type) {
            // Standard types
            case "checkbox":
                if (isset($_POST[$value['id']])) {
                    $option_value = 'yes';
                } else {
                    $option_value = 'no';
                }
                break;
            case "textarea":
                if (isset($_POST[$value['id']])) {
                    $option_value = wp_kses_post($_POST[$value['id']]);
                } else {
                    $option_value = '';
                }
                break;
            case "text":
            case 'email':
            case 'number':
            case "select":
            case "color":
            case 'password':
            case "single_select_page":
            case "single_select_country":
            case 'radio':
                if ($value['id'] == 'woocommerce_price_thousand_sep' || $value['id'] == 'woocommerce_price_decimal_sep') {
                    // price separators get a special treatment as they should allow a spaces (don't trim)
                    if (isset($_POST[$value['id']])) {
                        $option_value = esc_attr($_POST[$value['id']]);
                    } else {
                        $option_value = '';
                    }
                } elseif ($value['id'] == 'woocommerce_price_num_decimals') {
                    // price separators get a special treatment as they should allow a spaces (don't trim)
                    if (isset($_POST[$value['id']])) {
                        $option_value = absint(esc_attr($_POST[$value['id']]));
                    } else {
                        $option_value = 2;
                    }
                } elseif ($value['id'] == 'woocommerce_hold_stock_minutes') {
                    if (isset($_POST[$value['id']])) {
                        $option_value = esc_attr($_POST[$value['id']]);
                    } else {
                        $option_value = '';
                    }
                    wp_clear_scheduled_hook('woocommerce_cancel_unpaid_orders');
                    if ($option_value != '') {
                        wp_schedule_single_event(time() + absint($option_value) * 60, 'woocommerce_cancel_unpaid_orders');
                    }
                } else {
                    if (isset($_POST[$value['id']])) {
                        $option_value = woocommerce_clean($_POST[$value['id']]);
                    } else {
                        $option_value = '';
                    }
                }
                break;
                // Special types
            // Special types
            case "multiselect":
            case "multi_select_countries":
                // Get countries array
                if (isset($_POST[$value['id']])) {
                    $selected_countries = array_map('woocommerce_clean', (array) $_POST[$value['id']]);
                } else {
                    $selected_countries = array();
                }
                $option_value = $selected_countries;
                break;
            case "image_width":
                if (isset($_POST[$value['id']]['width'])) {
                    $update_options[$value['id']]['width'] = woocommerce_clean($_POST[$value['id']]['width']);
                    $update_options[$value['id']]['height'] = woocommerce_clean($_POST[$value['id']]['height']);
                    if (isset($_POST[$value['id']]['crop'])) {
                        $update_options[$value['id']]['crop'] = 1;
                    } else {
                        $update_options[$value['id']]['crop'] = 0;
                    }
                } else {
                    $update_options[$value['id']]['width'] = $value['default']['width'];
                    $update_options[$value['id']]['height'] = $value['default']['height'];
                    $update_options[$value['id']]['crop'] = $value['default']['crop'];
                }
                break;
                // Custom handling
            // Custom handling
            default:
                do_action('woocommerce_update_option_' . $type, $value);
                break;
        }
        if (!is_null($option_value)) {
            // Check if option is an array
            if (strstr($value['id'], '[')) {
                parse_str($value['id'], $option_array);
                // Option name is first key
                $option_name = current(array_keys($option_array));
                // Get old option value
                if (!isset($update_options[$option_name])) {
                    $update_options[$option_name] = get_option($option_name, array());
                }
                if (!is_array($update_options[$option_name])) {
                    $update_options[$option_name] = array();
                }
                // Set keys and value
                $key = key($option_array[$option_name]);
                $update_options[$option_name][$key] = $option_value;
                // Single value
            } else {
                $update_options[$value['id']] = $option_value;
            }
        }
        // Custom handling
        do_action('woocommerce_update_option', $value);
    }
    // Now save the options
    foreach ($update_options as $name => $value) {
        update_option($name, $value);
    }
    return true;
}
// Do the same kind of update for order_taxes - move to lines
// Reverse with UPDATE `wpwc_postmeta` SET meta_key = '_order_taxes' WHERE meta_key = '_order_taxes_old'
$order_tax_rows = $wpdb->get_results("\r\n\tSELECT * FROM {$wpdb->postmeta}\r\n\tWHERE meta_key = '_order_taxes'\r\n");
foreach ($order_tax_rows as $order_tax_row) {
    $order_taxes = (array) maybe_unserialize($order_tax_row->meta_value);
    if ($order_taxes) {
        foreach ($order_taxes as $order_tax) {
            if (!isset($order_tax['label']) || !isset($order_tax['cart_tax']) || !isset($order_tax['shipping_tax'])) {
                continue;
            }
            $item_id = woocommerce_add_order_item($order_tax_row->post_id, array('order_item_name' => $order_tax['label'], 'order_item_type' => 'tax'));
            // Add line item meta
            if ($item_id) {
                woocommerce_add_order_item_meta($item_id, 'compound', absint(isset($order_tax['compound']) ? $order_tax['compound'] : 0));
                woocommerce_add_order_item_meta($item_id, 'tax_amount', woocommerce_clean($order_tax['cart_tax']));
                woocommerce_add_order_item_meta($item_id, 'shipping_tax_amount', woocommerce_clean($order_tax['shipping_tax']));
            }
            // Delete from DB (rename)
            $wpdb->query($wpdb->prepare("\r\n\t\t\t\tUPDATE {$wpdb->postmeta}\r\n\t\t\t\tSET meta_key = '_order_taxes_old'\r\n\t\t\t\tWHERE meta_key = '_order_taxes'\r\n\t\t\t\tAND post_id = %d\r\n\t\t\t", $order_tax_row->post_id));
            unset($tax_amount);
        }
    }
}
// Grab the pre 2.0 Image options and use to populate the new image options settings,
// cleaning up afterwards like nice people do
foreach (array('catalog', 'single', 'thumbnail') as $value) {
    $old_settings = array_filter(array('width' => get_option('woocommerce_' . $value . '_image_width'), 'height' => get_option('woocommerce_' . $value . '_image_height'), 'crop' => get_option('woocommerce_' . $value . '_image_crop')));
    if (!empty($old_settings) && update_option('shop_' . $value . '_image_size', $old_settings)) {
        delete_option('woocommerce_' . $value . '_image_width');
        delete_option('woocommerce_' . $value . '_image_height');
        delete_option('woocommerce_' . $value . '_image_crop');
/**
 * Save and and update a billing or shipping address if the
 * form was submitted through the user account page.
 *
 * @access public
 */
function woocommerce_save_address()
{
    global $woocommerce;
    if ('POST' !== strtoupper($_SERVER['REQUEST_METHOD'])) {
        return;
    }
    if (empty($_POST['action']) || 'edit_address' !== $_POST['action']) {
        return;
    }
    $woocommerce->verify_nonce('edit_address');
    $validation = $woocommerce->validation();
    $user_id = get_current_user_id();
    if ($user_id <= 0) {
        return;
    }
    $load_address = isset($_GET['address']) ? esc_attr($_GET['address']) : '';
    $load_address = $load_address == 'billing' || $load_address == 'shipping' ? $load_address : '';
    $address = $woocommerce->countries->get_address_fields(esc_attr($_POST[$load_address . '_country']), $load_address . '_');
    foreach ($address as $key => $field) {
        if (!isset($field['type'])) {
            $field['type'] = 'text';
        }
        // Get Value
        switch ($field['type']) {
            case "checkbox":
                $_POST[$key] = isset($_POST[$key]) ? 1 : 0;
                break;
            default:
                $_POST[$key] = isset($_POST[$key]) ? woocommerce_clean($_POST[$key]) : '';
                break;
        }
        // Hook to allow modification of value
        $_POST[$key] = apply_filters('woocommerce_process_myaccount_field_' . $key, $_POST[$key]);
        // Validation: Required fields
        if (isset($field['required']) && $field['required'] && empty($_POST[$key])) {
            $woocommerce->add_error($field['label'] . ' ' . __('is a required field.', 'woocommerce'));
        }
        // Postcode
        if ($key == 'billing_postcode' || $key == 'shipping_postcode') {
            if (!$validation->is_postcode($_POST[$key], $_POST[$load_address . '_country'])) {
                $woocommerce->add_error(__('Please enter a valid postcode/ZIP.', 'woocommerce'));
            } else {
                $_POST[$key] = $validation->format_postcode($_POST[$key], $_POST[$load_address . '_country']);
            }
        }
    }
    if ($woocommerce->error_count() == 0) {
        foreach ($address as $key => $field) {
            update_user_meta($user_id, $key, $_POST[$key]);
        }
        $woocommerce->add_message(__('Address changed successfully.', 'woocommerce'));
        do_action('woocommerce_customer_save_address', $user_id);
        wp_safe_redirect(get_permalink(woocommerce_get_page_id('myaccount')));
        exit;
    }
}
 /**
  * Save global addons
  *
  * @return bool success or failure
  */
 public function save_global_addons()
 {
     $edit_id = !empty($_POST['edit_id']) ? absint($_POST['edit_id']) : '';
     $reference = woocommerce_clean($_POST['addon-reference']);
     $priority = absint($_POST['addon-priority']);
     $objects = !empty($_POST['addon-objects']) ? array_map('absint', $_POST['addon-objects']) : array();
     $product_addons = $this->get_posted_product_addons();
     if (!$reference) {
         $global_addons_count = wp_count_posts('global_product_addon');
         $reference = __('Global Add-on Group') . ' #' . ($global_addons_count->publish + 1);
     }
     if (!$priority && $priority !== 0) {
         $priority = 10;
     }
     if ($edit_id) {
         $edit_post = array();
         $edit_post['ID'] = $edit_id;
         $edit_post['post_title'] = $reference;
         wp_update_post($edit_post);
         wp_set_post_terms($edit_id, $objects, 'product_cat', false);
         do_action('woocommerce_product_addons_global_edit_addons', $edit_post, $objects);
     } else {
         $edit_id = wp_insert_post(apply_filters('woocommerce_product_addons_global_insert_post_args', array('post_title' => $reference, 'post_status' => 'publish', 'post_type' => 'global_product_addon', 'tax_input' => array('product_cat' => $objects)), $reference, $objects));
     }
     if (in_array(0, $objects)) {
         update_post_meta($edit_id, '_all_products', 1);
     } else {
         update_post_meta($edit_id, '_all_products', 0);
     }
     update_post_meta($edit_id, '_priority', $priority);
     update_post_meta($edit_id, '_product_addons', $product_addons);
     return $edit_id;
 }
 /**
  * Valid options.
  *
  * @param  array $input options to valid.
  *
  * @return array        validated options.
  */
 public function validate_options($input)
 {
     $output = array();
     // Loop through each of the incoming options.
     foreach ($input as $key => $value) {
         // Check to see if the current option has a value. If so, process it.
         if (isset($input[$key])) {
             $output[$key] = woocommerce_clean($input[$key]);
         }
     }
     return $output;
 }