예제 #1
0
 private function order($id)
 {
     $this->view = 'customer-account-order';
     $form_data_obj = new WPSC_Checkout_Form_Data($id);
     $this->form = WPSC_Checkout_Form::get();
     $this->log = new WPSC_Purchase_Log($id);
     $this->title = sprintf(__('View Order #%d', 'wpsc'), $id);
     foreach ($form_data_obj->get_raw_data() as $data) {
         $this->form_data[(int) $data->id] = $this->process_checkout_form_value($data);
     }
     require_once WPSC_TE_V2_CLASSES_PATH . '/cart-item-table-order.php';
     $this->cart_item_table = new WPSC_Cart_Item_Table_Order($id);
 }
 /**
  * Pull and Record PayPal Details
  *
  * @return void
  */
 public function pull_paypal_details()
 {
     $this->set_purchase_log_for_callbacks();
     // Pull the User Details from PayPal
     $this->paypal_data = $paypal = $this->gateway->get_details_for($_GET['token']);
     $payer = $paypal->get('payer');
     $address = $paypal->get('shipping_address');
     // PurchaseLog Update
     if (isset($address['country_code'])) {
         $this->purchase_log->set('billing_country', $address['country_code']);
         $this->purchase_log->set('shipping_country', $address['country_code']);
     }
     if (isset($address['state'])) {
         $this->purchase_log->set('billing_region', $address['state']);
         $this->purchase_log->set('shipping_region', $address['state']);
     }
     // Save Checkout Form Fields
     $form = WPSC_Checkout_Form::get();
     $fields = $form->get_fields();
     $_POST['wpsc_checkout_details'] = array();
     foreach ($fields as $field) {
         $this->set_post_var($field, $payer, $address);
     }
     // Save details to the Forms Table
     WPSC_Checkout_Form_Data::save_form($this->purchase_log, $fields);
 }
예제 #3
0
 public function save_shipping_and_billing_info()
 {
     global $wpsc_cart;
     $purchase_log = $this->get_purchase_log();
     $sessionid = mt_rand(100, 999) . time();
     wpsc_update_customer_meta('checkout_session_id', $sessionid);
     $purchase_log->set(array('user_ID' => get_current_user_id(), 'date' => time(), 'plugin_version' => WPSC_VERSION, 'statusno' => '0', 'sessionid' => $sessionid));
     $form = WPSC_Checkout_Form::get();
     $fields = $form->get_fields();
     foreach ($fields as $field) {
         if (!array_key_exists($field->id, $_POST['wpsc_checkout_details'])) {
             continue;
         }
         $value = $_POST['wpsc_checkout_details'][$field->id];
         switch ($field->unique_name) {
             case 'billingstate':
                 wpsc_update_customer_meta('billing_region', $value);
                 $purchase_log->set('billing_region', $value);
                 break;
             case 'shippingstate':
                 wpsc_update_customer_meta('shipping_region', $value);
                 $purchase_log->set('shipping_region', $value);
                 break;
             case 'billingcountry':
                 wpsc_update_customer_meta('billing_country', $value);
                 $purchase_log->set('billing_country', $value);
                 break;
             case 'shippingcountry':
                 wpsc_update_customer_meta('shipping_country', $value);
                 $purchase_log->set('shipping_region', $value);
                 break;
             case 'shippingpostcode':
                 wpsc_update_customer_meta('shipping_zip', $value);
                 break;
         }
     }
     _wpsc_update_location();
     //keep track of tax if taxes are exclusive
     $wpec_taxes_controller = new wpec_taxes_controller();
     if (!$wpec_taxes_controller->wpec_taxes_isincluded()) {
         $tax = $wpsc_cart->calculate_total_tax();
         $tax_percentage = $wpsc_cart->tax_percentage;
     } else {
         $tax = 0.0;
         $tax_percentage = 0.0;
     }
     $purchase_log->set(array('wpec_taxes_total' => $tax, 'wpec_taxes_rate' => $tax_percentage));
     $purchase_log->save();
     //Check to ensure purchase log row was inserted successfully
     if (is_null($purchase_log->get('id'))) {
         $this->message_collection->add(__('A database error occured while processing your request.', 'wp-e-commerce'), 'error');
         return;
     }
     $wpsc_cart->log_id = $purchase_log->get('id');
     wpsc_update_customer_meta('current_purchase_log_id', $purchase_log->get('id'));
     WPSC_Checkout_Form_Data::save_form($purchase_log, $fields);
     $this->init_shipping_calculator();
     if (wpsc_uses_shipping() && !$this->shipping_calculator->has_quotes) {
         $this->message_collection->add(__('Sorry, but we cannot ship products to your submitted address. Please either provide another shipping address or contact the store administrator about product availability to your location.', 'wp-e-commerce'), 'error');
         return;
     }
     $this->wizard->completed_step('shipping-and-billing');
     $url = add_query_arg($_GET, wpsc_get_checkout_url($this->wizard->pending_step));
     wp_redirect($url);
     exit;
 }
 public function get_raw_message()
 {
     global $wpdb;
     $form_data = new WPSC_Checkout_Form_Data($this->purchase_log->get('id'));
     $raw_data = $form_data->get_raw_data();
     $args = $this->get_common_args();
     $data = array('billing' => array('title' => __('Billing Details', 'wp-e-commerce'), 'fields' => array()), 'shipping' => array('title' => __('Shipping Details', 'wp-e-commerce'), 'fields' => array()), 'misc' => array('title' => __('Other Details', 'wp-e-commerce'), 'fields' => array()));
     foreach ($raw_data as $field) {
         if (strpos($field->unique_name, 'billing') !== false) {
             $type = 'billing';
         } elseif (strpos($field->unique_name, 'shipping') !== false) {
             $type = 'shipping';
         } else {
             $type = 'misc';
         }
         $data[$type]['fields'][] = $field;
     }
     // Transaction details
     $message = '<strong>' . __('Transaction Details', 'wp-e-commerce') . "</strong>\r\n";
     $message .= __('Sale Log ID', 'wp-e-commerce') . ': %purchase_id%' . "\r\n";
     if (!empty($args['transaction_id'])) {
         $message .= __('Transaction ID', 'wp-e-commerce') . ': %transaction_id%' . "\r\n";
     }
     // Discount
     if (!empty($args['coupon_code'])) {
         $message .= __('Coupon Code', 'wp-e-commerce') . ': %coupon_code%' . "\r\n";
         $message .= __('Discount Value', 'wp-e-commerce') . ': %discount%' . "\r\n";
     }
     // Subtotal, tax, shipping, total
     $message .= __('Subtotal', 'wp-e-commerce') . ': %subtotal%' . "\r\n";
     $message .= __('Tax', 'wp-e-commerce') . ': %tax%' . "\r\n";
     $message .= __('Shipping', 'wp-e-commerce') . ': %shipping%' . "\r\n";
     $message .= __('Total', 'wp-e-commerce') . ': %total%' . "\r\n";
     $message .= __('Payment Method', 'wp-e-commerce') . ': %payment_method%' . "\r\n";
     if (!get_option('do_not_use_shipping')) {
         $message .= __('Shipping Method', 'wp-e-commerce') . ': %shipping_method%' . "\r\n";
         $message .= __('Shipping Option', 'wp-e-commerce') . ': %shipping_option%' . "\r\n";
     }
     $message .= "\r\n";
     // Items
     $message .= '<strong>' . __('Items', 'wp-e-commerce') . "</strong>\r\n";
     $message .= "%product_list%\r\n";
     // Checkout fields
     $message .= "\r\n";
     foreach ($data as $section) {
         if (empty($section['fields'])) {
             continue;
         }
         $message .= "<strong>{$section['title']}</strong>\r\n";
         foreach ($section['fields'] as $field) {
             if (strpos($field->unique_name, 'state') && is_numeric($field->value)) {
                 $field->value = wpsc_get_region($field->value);
             }
             $message .= $field->name . ' : ' . $field->value . "\r\n";
         }
         $message .= "\r\n";
     }
     // preserve pre-3.8.9 hooks
     $message = apply_filters('wpsc_transaction_result_report', $message);
     return apply_filters('wpsc_purchase_log_admin_notification_raw_message', $message, $this);
 }
예제 #5
0
 /**
  * VAT registered sellers - Obtaining the Billing Address
  *
  * http://docs.developer.amazonservices.com/en_UK/apa_guide/APAGuide_GetAuthorizationStatus.html
  *
  * @param array $result
  */
 public function maybe_update_billing_details($result)
 {
     if (!empty($result['AuthorizationBillingAddress'])) {
         if (is_a($this->gateway->checkout_data, 'WPSC_Checkout_Form_Data')) {
             $checkout_data = $this->gateway->checkout_data;
         } else {
             $checkout_data = new WPSC_Checkout_Form_Data($this->log->get('id'));
         }
         $address = $result['AuthorizationBillingAddress'];
         $address_lines = array();
         if (!empty($address['AddressLine1'])) {
             $address_lines[] = $address['AddressLine1'];
         }
         if (!empty($address['AddressLine2'])) {
             $address_lines[] = $address['AddressLine2'];
         }
         if (!empty($address['AddressLine3'])) {
             $address_lines[] = $address['AddressLine3'];
         }
         $street_address = implode("\n", $address_lines);
         $checkout_data->set('billingaddress', $street_address);
         if (isset($address['Name'])) {
             $bits = explode(' ', $address['Name']);
             $first_name = array_shift($bits);
             $last_name = implode(' ', $bits);
             $checkout_data->set('billingfirstname', $first_name);
             $checkout_data->set('billinglastname', $last_name);
         }
         if (isset($address['City'])) {
             $checkout_data->set('billingcity', $address['City']);
         }
         if (isset($address['PostalCode'])) {
             $checkout_data->set('billingpostcode', $address['PostalCode']);
         }
         if (isset($address['StateOrRegion'])) {
             $checkout_data->set('billingstate', $address['StateOrRegion']);
         }
         if (isset($address['CountryCode'])) {
             $checkout_data->set('billingcountry', $address['CountryCode']);
         }
         $checkout_data->save();
     }
 }
예제 #6
0
 public function add_pushes($session_id)
 {
     $purchase = new WPSC_Purchase_Log($session_id, 'sessionid');
     $purchase_id = $purchase->get('id');
     $data = new WPSC_Checkout_Form_Data($purchase_id);
     $output = '';
     $city = $data->get('billingcity');
     $state = $data->get('billingstate');
     $country = $data->get('billingcountry');
     $state = !empty($state) ? wpsc_get_state_by_id($state, 'name') : '';
     $cart_items = $purchase->get_cart_contents();
     $total_shipping = wpsc_get_total_shipping($purchase_id);
     $total_tax = $total_price = 0;
     foreach ($cart_items as $item) {
         /* For backwards compatibility, convert objects to arrays */
         $item = (array) $item;
         $total_tax += $item['tax_charged'];
         $total_price += absint($item['quantity']) * $item['price'];
     }
     if ($this->is_theme_tracking || $this->advanced_code) {
         $output .= "<script type='text/javascript'>\n\r";
     }
     add_filter('wpsc_toggle_display_currency_code', array($this, 'remove_currency_and_html'));
     if ($this->use_universal_analytics()) {
         // Yoast GA Plugin switched to it's own object name __gaTracker - assign it to our ga object if it exists
         $output .= "var ga = typeof ga === 'undefined' && typeof __gaTracker !== 'undefined' ? __gaTracker : ga;";
         $output .= "ga('require', 'ecommerce');\n\r";
         $output .= "ga('ecommerce:addTransaction', {\n\t\t\t\t'id': '" . $purchase_id . "',                                               // Transaction ID. Required.\n\t\t\t\t'affiliation': '" . wp_specialchars_decode($this->get_site_name()) . "',  // Affiliation or store name.\n\t\t\t\t'revenue': '" . number_format($total_price, 2, '.', '') . "',             // Grand Total.\n\t\t\t\t'shipping': '" . wpsc_currency_display($total_shipping) . "',             // Shipping.\n\t\t\t\t'tax': '" . wpsc_currency_display($total_tax) . "'                        // Tax.\n\t\t\t});\n\r";
     } else {
         $output .= "\n\t\t\t\t_gaq.push(['_addTrans',\n\t\t\t\t'" . $purchase_id . "',                                     // order ID - required\n\t\t\t\t'" . wp_specialchars_decode($this->get_site_name()) . "', // affiliation or store name\n\t\t\t\t'" . number_format($total_price, 2, '.', '') . "',   // total - required\n\t\t\t\t'" . wpsc_currency_display($total_tax) . "',              // tax\n\t\t\t\t'" . wpsc_currency_display($total_shipping) . "',         // shipping\n\t\t\t\t'" . wp_specialchars_decode($city) . "',                  // city\n\t\t\t\t'" . wp_specialchars_decode($state) . "',                 // state or province\n\t\t\t\t'" . wp_specialchars_decode($country) . "'                // country\n\t\t\t]);\n\r";
     }
     remove_filter('wpsc_toggle_display_currency_code', array($this, 'remove_currency_and_html'));
     foreach ($cart_items as $item) {
         /* For backwards compatibility, convert objects to arrays */
         $item = (array) $item;
         $category = wp_get_object_terms($item['prodid'], 'wpsc_product_category', array('orderby' => 'count', 'order' => 'DESC', 'fields' => 'all_with_object_id'));
         $item['sku'] = get_post_meta($item['prodid'], '_wpsc_sku', true);
         if (empty($item['sku'])) {
             $item['sku'] = $item['prodid'];
         }
         if ($category) {
             $item['category'] = $category[0]->name;
         } else {
             $item['category'] = '';
         }
         $item = apply_filters('wpsc_google_analytics_pushed_product', array_map('wp_specialchars_decode', $item), $item, $this);
         if ($this->use_universal_analytics()) {
             $output .= "ga('ecommerce:addItem', {" . "'id': '" . $purchase_id . "'," . "'name': '" . $item['name'] . "'," . "'sku': '" . $item['sku'] . "'," . "'category': '" . $item['category'] . "'," . "'price': '" . $item['price'] . "'," . "'quantity': '" . $item['quantity'] . "'" . "});\n\r";
         } else {
             $output .= "_gaq.push(['_addItem'," . "'" . $purchase_id . "'," . "'" . $item['sku'] . "'," . "'" . $item['name'] . "'," . "'" . $item['category'] . "'," . "'" . $item['price'] . "'," . "'" . $item['quantity'] . "']);\n\r";
             // Item Quantity
         }
     }
     if ($this->use_universal_analytics()) {
         $output .= "ga('ecommerce:send');\n\r";
     } else {
         $output .= "_gaq.push(['_trackTrans']);\n\r";
     }
     if ($this->is_theme_tracking || $this->advanced_code) {
         $output .= "</script>\n\r";
     }
     return $output;
 }
예제 #7
0
function _wpsc_convert_checkout_form_fields($customer_settings = false)
{
    $form = WPSC_Checkout_Form::get();
    $fields = $form->get_fields();
    $args = array();
    $purchase_log_exists = false;
    if (!$customer_settings) {
        $purchase_log_id = wpsc_get_customer_meta('current_purchase_log_id');
        $purchase_log_exists = (bool) $purchase_log_id;
        if ($purchase_log_exists) {
            $form_data_obj = new WPSC_Checkout_Form_Data($purchase_log_id);
            $form_raw_data = $form_data_obj->get_raw_data();
            $form_data = array();
            foreach ($form_raw_data as $data) {
                $form_data[$data->id] = $data;
            }
        }
    }
    $i = 0;
    $state_country_pairs = array('billing_state' => array(), 'shipping_state' => array());
    $customer_details = wpsc_get_customer_meta('checkout_details');
    if (!is_array($customer_details)) {
        $customer_details = array();
    }
    foreach ($fields as $field) {
        $id = empty($field->unique_name) ? $field->id : $field->unique_name;
        $default_value = array_key_exists($field->id, $customer_details) ? $customer_details[$field->id] : '';
        if ($purchase_log_exists && $field->type != 'heading' && isset($form_data[$field->id])) {
            $default_value = $form_data[$field->id]->value;
        }
        $field_arr = array('type' => $field->type, 'id' => "wpsc-checkout-field-{$id}", 'title' => esc_html($field->name), 'name' => 'wpsc_checkout_details[' . $field->id . ']', 'value' => wpsc_submitted_value($field->id, $default_value, $_POST['wpsc_checkout_details']));
        $validation_rules = array('trim');
        if ($field->mandatory) {
            $validation_rules[] = 'required';
        }
        $optional_state_field = false;
        if (in_array($field->unique_name, array('billingstate', 'shippingstate'))) {
            $field_arr['type'] = 'select_region';
            /* output states for all countries just in case Javascript doesn't work */
            $field_arr['country'] = 'all';
            if ($field->unique_name == 'billingstate') {
                $state_country_pairs['billing_state']['key'] = $i;
            } else {
                $state_country_pairs['shipping_state']['key'] = $i;
            }
            // optional text field in case the country they select do not have states
            // and JS is disabled either by preferences or on error
            $optional_state_field = true;
            // convert state values in text into proper ID
            $validation_rules[] = '_wpsc_convert_state';
        } elseif (in_array($field->unique_name, array('billingcountry', 'shippingcountry')) || $field->type == 'delivery_country') {
            $field_arr['type'] = 'select_country';
            $validation_rules[] = 'country';
            if ($field->unique_name == 'billingcountry') {
                $state_country_pairs['billing_state']['country_field_id'] = $field->id;
            } else {
                $state_country_pairs['shipping_state']['country_field_id'] = $field->id;
            }
        } elseif ($field->type == 'text') {
            $field_arr['type'] = 'textfield';
        } elseif ($field->type == 'select') {
            $field_arr['options'] = array_flip(unserialize($field->options));
        } elseif ($field->type == 'radio') {
            $field_arr['type'] = 'radios';
            $field_arr['options'] = array_flip(unserialize($field->options));
        } elseif ($field->type == 'checkbox') {
            $field_arr['type'] = 'checkboxes';
            $field_arr['options'] = array_flip(unserialize($field->options));
        } elseif (in_array($field->type, array('address', 'city', 'email'))) {
            $field_arr['type'] = 'textfield';
            if ($field->type == 'email') {
                $validation_rules[] = 'email';
            }
        } elseif ($field->type == 'heading' && $field->unique_name == 'delivertoafriend') {
            $field_arr['shipping_heading'] = true;
        }
        $field_arr['rules'] = implode('|', $validation_rules);
        $args[$i] = $field_arr;
        $i++;
        if ($optional_state_field) {
            $args[$i] = $args[$i - 1];
            $args[$i]['type'] = 'textfield';
            $args[$i]['id'] = 'wpsc-checkout-field-' . $id . '-text';
            $i++;
        }
    }
    if (wpsc_has_tnc() && !$customer_settings) {
        $args[] = array('type' => 'checkbox', 'id' => 'wpsc-terms-and-conditions', 'title' => sprintf(__("I agree to the <a class='thickbox' target='_blank' href='%s' class='termsandconds'>Terms and Conditions</a>", "wpsc"), esc_url(site_url("?termsandconds=true&amp;width=360&amp;height=400"))), 'value' => 1, 'name' => 'wpsc_terms_conditions', 'rules' => 'required', 'checked' => wpsc_submitted_value('wpsc_terms_conditions', 0) == 1);
    }
    foreach ($state_country_pairs as $field) {
        $args[$field['key']]['rules'] .= '|state_of[' . $field['country_field_id'] . ']';
        $args[$field['key']]['rules'] = ltrim($args[$field['key']]['rules'], '|');
    }
    return $args;
}
예제 #8
0
        public function save_order($purchase_log)
        {
            $apiKey = get_option('retargeting_domain_api');
            $token = get_option('retargeting_token');
            if ($purchase_log instanceof WPSC_Purchase_Log) {
                $order = array('line_items' => array());
                $checkout_form = new WPSC_Checkout_Form_Data($purchase_log->get('id'));
                $products = $purchase_log->get_cart_contents();
                if (is_array($products)) {
                    foreach ($products as $product) {
                        $parent = $this->get_parent_post($product->prodid);
                        if ($parent) {
                            $product_id = $parent->ID;
                            $product_name = $parent->post_title;
                        } else {
                            $product_id = $product->prodid;
                            $product_name = $product->name;
                        }
                        $line_item = array('id' => (int) $product_id, 'quantity' => (int) $product->quantity, 'price' => $this->format_price($product->price), 'variation_code' => '');
                        $order['line_items'][] = $line_item;
                    }
                }
                if ($apiKey && $apiKey != "" && $token && $token != "") {
                    require_once "/lib/Retargeting_REST_API_Client.php";
                    $orderInfo = array("order_no" => $purchase_log->get('id'), "lastname" => $checkout_form->get('billinglastname'), "firstname" => $checkout_form->get('billingfirstname'), "email" => $checkout_form->get('billingemail'), "phone" => $checkout_form->get('billingphone'), "state" => $checkout_form->get('shippingstate'), "city" => $checkout_form->get('shippingcity'), "address" => $checkout_form->get('billingaddress'), "discount_code" => $purchase_log->get('discount_data'), "discount" => $purchase_log->get('discount_value'), "shipping" => $purchase_log->get('total_shipping'), "total" => $purchase_log->get('totalprice'));
                    $orderClient = new Retargeting_REST_API_Client($apiKey, $token);
                    $orderClient->setResponseFormat('json');
                    $orderClient->setDecoding(false);
                    $response = $orderClient->order->save($orderInfo, $order['line_items']);
                }
                echo '<script type="text/javascript">
						var _ra = _ra || {};
							_ra.saveOrderInfo = {
								"order_no": ' . $purchase_log->get('id') . ',
								"lastname": "' . $checkout_form->get('billinglastname') . '",
								"firstname": "' . $checkout_form->get('billingfirstname') . '",
								"email": "' . $checkout_form->get('billingemail') . '",
								"phone": "' . $checkout_form->get('billingphone') . '",
								"state": "' . $checkout_form->get('shippingstate') . '",
								"city": "' . $checkout_form->get('shippingcity') . '",
								"address": "' . $checkout_form->get('billingaddress') . '",
								"discount_code": "' . $purchase_log->get('discount_data') . '",
								"discount": "' . $purchase_log->get('discount_value') . '",
								"shipping": "' . $purchase_log->get('total_shipping') . '",
								"total": "' . $purchase_log->get('totalprice') . '"
							};
							_ra.saveOrderProducts = ' . json_encode($order['line_items'], JSON_PRETTY_PRINT) . '
							
							if( _ra.ready !== undefined ){
								_ra.saveOrder(_ra.saveOrderInfo, _ra.saveOrderProducts);
							}
						</script>';
            }
        }
예제 #9
0
function _wpsc_convert_checkout_form_fields($customer_settings = false)
{
    $form = WPSC_Checkout_Form::get();
    $fields = $form->get_fields();
    if (empty($fields)) {
        return array();
    }
    $args = array();
    $purchase_log_exists = false;
    $fieldsets = array('billing' => array('type' => 'fieldset', 'title' => apply_filters('wpsc_checkout_billing_header_label', __('<h2>Billing &amp; Shipping Details</h2>', 'wp-e-commerce')), 'id' => 'wpsc-checkout-form-billing', 'fields' => array()), 'shipping' => array('type' => 'fieldset', 'title' => apply_filters('wpsc_checkout_shipping_header_label', __('<h2>Shipping Details</h2>', 'wp-e-commerce')), 'id' => 'wpsc-checkout-form-shipping', 'fields' => array()));
    if (!$customer_settings) {
        $purchase_log_id = wpsc_get_customer_meta('current_purchase_log_id');
        $purchase_log_exists = (bool) $purchase_log_id;
        if ($purchase_log_exists) {
            $form_data_obj = new WPSC_Checkout_Form_Data($purchase_log_id);
            $form_raw_data = $form_data_obj->get_raw_data();
            $form_data = array();
            foreach ($form_raw_data as $data) {
                $form_data[$data->id] = $data;
            }
        }
    }
    $i = 0;
    $state_country_pairs = array('billing_state' => array(), 'shipping_state' => array());
    $customer_details = wpsc_get_customer_meta('checkout_details');
    if (!is_array($customer_details)) {
        $customer_details = array();
    }
    foreach ($fields as $field) {
        $id = empty($field->unique_name) ? $field->id : $field->unique_name;
        $is_shipping = false !== strpos($field->unique_name, 'shipping');
        $is_billing = false !== strpos($field->unique_name, 'billing');
        $default_value = array_key_exists($field->id, $customer_details) ? $customer_details[$field->id] : '';
        /* Doing our college-best to check for one of the two original headings */
        if ('heading' == $field->type && ('delivertoafriend' == $field->unique_name || '1' === $field->id)) {
            continue;
        }
        if ($purchase_log_exists && isset($form_data[$field->id])) {
            $default_value = $form_data[$field->id]->value;
        }
        if (isset($_POST['wpsc_checkout_details'])) {
            $_POST['wpsc_checkout_details'] = wp_unslash($_POST['wpsc_checkout_details']);
        }
        $field_arr = array('type' => $field->type, 'id' => "wpsc-checkout-field-{$id}", 'title' => esc_html($field->name), 'name' => 'wpsc_checkout_details[' . $field->id . ']', 'value' => wpsc_submitted_value($field->id, wp_unslash($default_value), $_POST['wpsc_checkout_details']));
        $validation_rules = array('trim');
        if ($field->mandatory) {
            $validation_rules[] = 'required';
        }
        $optional_state_field = false;
        if (in_array($field->unique_name, array('billingstate', 'shippingstate'))) {
            $field_arr['type'] = 'select_region';
            /* output states for all countries just in case Javascript doesn't work */
            $field_arr['country'] = 'all';
            if ($field->unique_name == 'billingstate') {
                $state_country_pairs['billing_state']['key'] = $i;
            } else {
                $state_country_pairs['shipping_state']['key'] = $i;
            }
            // optional text field in case the country they select do not have states
            // and JS is disabled either by preferences or on error
            $optional_state_field = true;
            // convert state values in text into proper ID
            $validation_rules[] = '_wpsc_convert_state';
        } elseif (in_array($field->unique_name, array('billingcountry', 'shippingcountry')) || $field->type == 'delivery_country') {
            $field_arr['type'] = 'select_country';
            $validation_rules[] = 'country';
            if ($field->unique_name == 'billingcountry') {
                $state_country_pairs['billing_state']['country_field_id'] = $field->id;
            } else {
                $state_country_pairs['shipping_state']['country_field_id'] = $field->id;
            }
        } elseif ($field->type == 'text') {
            $field_arr['type'] = 'textfield';
        } elseif ($field->type == 'select') {
            $field_arr['options'] = array_flip(unserialize($field->options));
        } elseif ($field->type == 'radio') {
            $field_arr['type'] = 'radios';
            $field_arr['options'] = array_flip(unserialize($field->options));
        } elseif ($field->type == 'checkbox') {
            $field_arr['type'] = 'checkboxes';
            $field_arr['options'] = array_flip(unserialize($field->options));
        } elseif (in_array($field->type, array('address', 'city', 'email'))) {
            $field_arr['type'] = 'textfield';
            if ($field->type == 'email') {
                $validation_rules[] = 'email';
            }
        } elseif ($field->type == 'heading' && $field->unique_name == 'delivertoafriend') {
            $field_arr['shipping_heading'] = true;
        }
        $field_arr['rules'] = implode('|', $validation_rules);
        if ($is_shipping) {
            $fieldsets['shipping']['fields'][$i] = $field_arr;
        } else {
            if ($is_billing) {
                $fieldsets['billing']['fields'][$i] = $field_arr;
            } else {
                $args[$i] = $field_arr;
            }
        }
        $i++;
        if ($optional_state_field && $is_billing) {
            $fieldsets['billing']['fields'][$i] = $fieldsets['billing']['fields'][$i - 1];
            $fieldsets['billing']['fields'][$i]['type'] = 'textfield';
            $fieldsets['billing']['fields'][$i]['id'] = 'wpsc-checkout-field-' . $id . '-text';
            $i++;
        } else {
            if ($optional_state_field && $is_shipping) {
                $fieldsets['shipping']['fields'][$i] = $fieldsets['shipping']['fields'][$i - 1];
                $fieldsets['shipping']['fields'][$i]['type'] = 'textfield';
                $fieldsets['shipping']['fields'][$i]['id'] = 'wpsc-checkout-field-' . $id . '-text';
            }
        }
    }
    if (wpsc_has_tnc() && !$customer_settings) {
        $args[] = array('type' => 'checkbox', 'id' => 'wpsc-terms-and-conditions', 'title' => sprintf(__("I agree to the <a class='thickbox' target='_blank' href='%s' class='termsandconds'>Terms and Conditions</a>", 'wp-e-commerce'), esc_url(add_query_arg(array('termsandconds' => 'true', 'width' => 360, 'height' => 400)))), 'value' => 1, 'name' => 'wpsc_terms_conditions', 'rules' => 'required', 'checked' => wpsc_submitted_value('wpsc_terms_conditions', 0) == 1);
    }
    foreach ($state_country_pairs as $state => $field) {
        $is_shipping = 'shipping_state' == $state;
        if (isset($field['key']) && $is_shipping) {
            $fieldsets['shipping']['fields'][$field['key']]['rules'] .= '|state_of[' . $field['country_field_id'] . ']';
            $fieldsets['shipping']['fields'][$field['key']]['rules'] = ltrim($fieldsets['shipping']['fields'][$field['key']]['rules'], '|');
        } else {
            if (isset($field['key'])) {
                $fieldsets['billing']['fields'][$field['key']]['rules'] .= '|state_of[' . $field['country_field_id'] . ']';
                $fieldsets['billing']['fields'][$field['key']]['rules'] = ltrim($fieldsets['billing']['fields'][$field['key']]['rules'], '|');
            }
        }
    }
    /* Add 'shipping same as billing' box to end of billing, rather than shipping header. */
    if (!empty($fieldsets['billing']['fields']) && !empty($fieldsets['shipping']['fields'])) {
        $checked = wpsc_get_customer_meta('wpsc_copy_billing_details');
        $fieldsets['billing']['fields'][$i++] = array('type' => 'checkbox', 'id' => 'wpsc-terms-and-conditions', 'title' => apply_filters('wpsc_shipping_same_as_billing', __('Shipping address is same as billing', 'wp-e-commerce')), 'value' => 1, 'name' => 'wpsc_copy_billing_details', 'checked' => empty($checked) || '1' == $checked);
    }
    if (empty($fieldsets['billing']['fields'])) {
        unset($fieldsets['billing']);
    }
    if (empty($fieldsets['shipping']['fields'])) {
        unset($fieldsets['shipping']);
    }
    return $fieldsets + $args;
}
 function do_export_file()
 {
     global $wpdb;
     $trnsid = 1;
     $gateway_accounts = get_option('pbci_gateway_accounts', array());
     $export_accounts = get_option('pbci_export_accounts', array('sales_revenue' => 'Product Revenue', 'shipping' => 'Shipping', 'sales_tax_account' => 'Sales Tax Payable', 'sales_tax_payee' => 'Sales Tax'));
     $cust = array('NAME' => '', 'FIRSTNAME' => '', 'LASTNAME' => '', 'EMAIL' => '', 'PHONE1' => '', 'BADDR1' => '', 'BADDR2' => '', 'BADDR3' => '', 'BADDR4' => '', 'SADDR1' => '', 'SADDR2' => '', 'SADDR3' => '', 'SADDR4' => '');
     $trans = array('TRNSID' => '', 'TRNSTYPE' => '', 'DATE' => '', 'ACCNT' => '', 'AMOUNT' => '', 'NAME' => '', 'MEMO' => '', 'PAYMETH' => '');
     $spl = array('SPLID' => '', 'TRNSTYPE' => '', 'DATE' => '', 'ACCNT' => '', 'AMOUNT' => '', 'NAME' => '', 'MEMO' => '', 'INVITEM' => '', 'PRICE' => '', 'EXTRA' => '');
     $content = "";
     $cust_content = "";
     $headers = "";
     $headers .= "!CUST\tNAME\t\n";
     $headers .= "!ACCNT\tNAME\tACCNTTYPE\tEXTRA\tACCNUM\n";
     $content .= "ACCNT\t" . $export_accounts['sales_revenue'] . "\tINC\t\n";
     $content .= "ACCNT\t" . $export_accounts['shipping'] . "\tINC\t\n";
     $content .= "ACCNT\t" . $export_accounts['sales_tax_account'] . "\tOCLIAB\tSALESTAX\t2201\n";
     foreach ($gateway_accounts as $gateway => $account_name) {
         if (!empty($account_name)) {
             $content .= "ACCNT\t" . $account_name . "\tBANK\t\n";
         }
     }
     // !TRNS line
     $headers .= '!TRNS';
     foreach ($trans as $key => $value) {
         $headers .= "\t" . $key;
     }
     $headers .= "\n";
     // !SPL line
     $headers .= '!SPL';
     foreach ($spl as $key => $value) {
         $headers .= "\t" . $key;
     }
     $headers .= "\n";
     // !CUST line
     $headers .= '!CUST';
     foreach ($cust as $key => $value) {
         $headers .= "\t" . $key;
     }
     $headers .= "\n";
     // !ENDTRNS line
     //$content .= '!ENDTRNS' . "\n";
     $export_dates = array_keys($_POST['period']);
     foreach ($export_dates as $export_date) {
         $a = explode('-', $export_date);
         $year = $a[0];
         $month = $a[1];
         $sql = "SELECT ID FROM " . WPSC_TABLE_PURCHASE_LOGS . ' WHERE MONTH( FROM_UNIXTIME( date ) ) = ' . $month . ' AND YEAR( FROM_UNIXTIME( DATE ) ) = ' . $year . ' ORDER by date DESC';
         $result = $wpdb->get_col($sql, 0);
         $purchase_log_ids = array_map('intval', $result);
         $max_rows = 1;
         foreach ($purchase_log_ids as $purchase_log_id) {
             $purchase_log = new WPSC_Purchase_Log($purchase_log_id);
             $gateway_id = $purchase_log->get('gateway');
             $data = $purchase_log->get_data();
             if (empty($gateway_accounts[$gateway_id])) {
                 continue;
             }
             // reset the transaction array back to empty
             foreach ($trans as $key => $value) {
                 $trans[$key] = '';
             }
             // reset the customer array back to empty
             foreach ($cust as $key => $value) {
                 $cust[$key] = '';
             }
             if ($purchase_log->get('processed') != WPSC_Purchase_Log::ACCEPTED_PAYMENT && $purchase_log->get('processed') != WPSC_Purchase_Log::CLOSED_ORDER) {
                 continue;
             }
             $checkout_form_data = new WPSC_Checkout_Form_Data($purchase_log_id);
             $checkout = $checkout_form_data->get_data();
             if (!isset($checkout['billingstate'])) {
                 $checkout['billingstate'] = '';
             }
             if (!isset($checkout['shippingstate'])) {
                 $checkout['shippingstate'] = '';
             }
             $timestamp = $purchase_log->get('date');
             $thedate = date('m/d/Y', $timestamp);
             foreach ($trans as $key => $value) {
                 switch ($key) {
                     case 'TRNSID':
                         $trans[$key] = $trnsid++;
                         break;
                     case 'TIMESTAMP':
                         $trans[$key] = $purchase_log->get('date');
                         break;
                     case 'TRNSTYPE':
                         $trans[$key] = 'CASH SALE';
                         break;
                     case 'DATE':
                         $trans[$key] = $thedate;
                         break;
                     case 'ACCNT':
                         $trans[$key] = $gateway_accounts[$gateway_id];
                         break;
                     case 'NAME':
                         $trans[$key] = $checkout['billingfirstname'] . ' ' . $checkout['billinglastname'];
                         break;
                     case 'AMOUNT':
                         $trans[$key] = $purchase_log->get('totalprice');
                         break;
                     case 'CLEAR':
                         $trans[$key] = 'N';
                         break;
                     case 'SHIPDATE':
                         $trans[$key] = $thedate;
                         break;
                     case 'PAYMETH':
                         $trans[$key] = $purchase_log->get('gateway_name');
                         break;
                     case 'DOCNUM':
                         $trans[$key] = $purchase_log_id;
                         break;
                     case 'MEMO':
                         $trans[$key] = 'sparkle-gear.com purchase #' . $purchase_log_id;
                         break;
                     case 'ADDR1':
                         $trans[$key] = $checkout['billingfirstname'] . ' ' . $checkout['billinglastname'];
                         break;
                     case 'ADDR2':
                         $trans[$key] = $checkout['billingaddress'];
                         break;
                     case 'ADDR3':
                         $trans[$key] = $checkout['billingcity'] . ', ' . $checkout['billingstate'] . ' ' . $checkout['billingpostcode'];
                         break;
                     case 'ADDR4':
                         $trans[$key] = $checkout['billingcountry'];
                         break;
                     case 'SHIPVIA':
                         $trans[$key] = $purchase_log->get('shipping_method_name');
                         break;
                     case 'INVTITLE':
                         $trans[$key] = 'Sparkle Gear Web Store';
                         break;
                     case 'SADDR1':
                         $trans[$key] = $checkout['shippingfirstname'] . ' ' . $checkout['shippinglastname'];
                         break;
                     case 'SADDR2':
                         $trans[$key] = $checkout['shippingaddress'];
                         break;
                     case 'SADDR3':
                         $trans[$key] = $checkout['shippingcity'] . ', ' . $checkout['shippingstate'] . ' ' . $checkout['shippingpostcode'];
                         break;
                     case 'SADDR4':
                         $trans[$key] = $checkout['billingcountry'];
                         break;
                 }
             }
             foreach ($cust as $key => $value) {
                 switch ($key) {
                     case 'NAME':
                         $cust[$key] = $checkout['billingfirstname'] . ' ' . $checkout['billinglastname'];
                         break;
                     case 'FIRSTNAME':
                         $cust[$key] = $checkout['billingfirstname'];
                         break;
                     case 'LASTNAME':
                         $cust[$key] = $checkout['billinglastname'];
                         break;
                     case 'EMAIL':
                         $cust[$key] = $checkout['billingemail'];
                         break;
                     case 'PHONE1':
                         $cust[$key] = $checkout['billingphone'];
                         break;
                     case 'BADDR1':
                         $cust[$key] = $checkout['billingfirstname'] . ' ' . $checkout['billinglastname'];
                         break;
                     case 'BADDR2':
                         $cust[$key] = $checkout['billingaddress'];
                         break;
                     case 'BADDR3':
                         $cust[$key] = $checkout['billingcity'] . ', ' . $checkout['billingstate'] . ' ' . $checkout['billingpostcode'];
                         break;
                     case 'BADDR4':
                         $cust[$key] = $checkout['billingcountry'];
                         break;
                     case 'SADDR1':
                         $cust[$key] = $checkout['shippingfirstname'] . ' ' . $checkout['shippinglastname'];
                         break;
                     case 'SADDR2':
                         $cust[$key] = $checkout['shippingaddress'];
                         break;
                     case 'SADDR3':
                         $cust[$key] = $checkout['shippingcity'] . ', ' . $checkout['shippingstate'] . ' ' . $checkout['shippingpostcode'];
                         break;
                     case 'SADDR4':
                         $cust[$key] = $checkout['billingcountry'];
                         break;
                 }
             }
             foreach ($trans as $key => $value) {
                 $trans[$key] = trim(preg_replace('/\\s+/', ' ', $value));
             }
             foreach ($cust as $key => $value) {
                 $cust[$key] = trim(preg_replace('/\\s+/', ' ', $value));
             }
             $splid = 1;
             // TRNS line
             $content .= 'TRNS';
             foreach ($trans as $key => $value) {
                 $content .= "\t" . $value;
             }
             $content .= "\n";
             $cart_contents = $purchase_log->get_cart_contents();
             foreach ($cart_contents as $cart_item) {
                 $product_id = $cart_item->prodid;
                 if ($parent_product = get_post_field('post_parent', $product_id)) {
                     $product_id = $parent_product;
                 }
                 $terms = wp_get_post_terms($product_id, 'wpsc_product_category');
                 if (!empty($terms)) {
                     foreach ($terms as $term) {
                         $invitem = $term->name;
                         if ($term->parent != 0) {
                             break;
                         }
                     }
                 } else {
                     $invitem = '';
                 }
                 /*
                 $item_name = '';
                 
                 $article = new Bling_Article( $cart_item->prodid );
                 if ( $article->check() ) {
                 	$item_name = $article->name();
                 }
                 */
                 $spl_product = array('SPLID' => $trnsid++, 'TRNSTYPE' => 'PAYMENT', 'DATE' => $trans['DATE'], 'ACCNT' => $export_accounts['sales_revenue'], 'AMOUNT' => -($cart_item->price * $cart_item->quantity), 'QNTY' => -$cart_item->quantity, 'PRICE' => $cart_item->price, 'NAME' => '', 'DOCNUM' => $purchase_log_id, 'MEMO' => $cart_item->name);
                 // SPL line
                 $content .= 'SPL';
                 foreach ($spl as $key => $value) {
                     $content .= "\t";
                     if (!empty($spl_product[$key])) {
                         $content .= $spl_product[$key];
                     }
                 }
                 $content .= "\n";
             }
             $spl_shipping = array('SPLID' => $trnsid++, 'TRNSTYPE' => 'PAYMENT', 'DATE' => $trans['DATE'], 'ACCNT' => $export_accounts['shipping'], 'AMOUNT' => -$purchase_log->get('total_shipping'), 'PRICE' => $purchase_log->get('total_shipping'), 'NAME' => '', 'DOCNUM' => $purchase_log_id, 'MEMO' => 'customer paid shipping', 'EXTRA' => '', 'QNTY' => '');
             $splid = 2;
             $spl_discount = array('SPLID' => $trnsid++, 'TRNSTYPE' => 'PAYMENT', 'DATE' => $trans['DATE'], 'ACCNT' => $export_accounts['sales_revenue'], 'AMOUNT' => $purchase_log->get('discount_value'), 'PRICE' => -$purchase_log->get('discount_value'), 'NAME' => '', 'DOCNUM' => $purchase_log_id, 'MEMO' => 'discount', 'EXTRA' => '', 'QNTY' => '');
             $spl_tax = array('SPLID' => $trnsid++, 'TRNSTYPE' => 'PAYMENT', 'DATE' => $trans['DATE'], 'ACCNT' => $export_accounts['sales_tax_account'], 'AMOUNT' => -$purchase_log->get('wpec_taxes_total'), 'PRICE' => "6.25%", 'NAME' => $export_accounts['sales_tax_payee'], 'DOCNUM' => $purchase_log_id, 'MEMO' => 'sales tax', 'EXTRA' => 'AUTOSTAX', 'QNTY' => '', 'INVITEM' => 'MA Sales/Use Tax');
             $spl_end = array('SPLID' => $trnsid++, 'EXTRA' => 'ENDGRP');
             // SPL line
             $content .= 'SPL';
             foreach ($spl as $key => $value) {
                 $content .= "\t";
                 if (!empty($spl_shipping[$key])) {
                     $content .= $spl_shipping[$key];
                 }
             }
             $content .= "\n";
             // SPL line
             $content .= 'SPL';
             foreach ($spl as $key => $value) {
                 $content .= "\t";
                 if (!empty($spl_tax[$key])) {
                     $content .= $spl_tax[$key];
                 }
             }
             $content .= "\n";
             // SPL line
             $content .= 'SPL';
             foreach ($spl as $key => $value) {
                 $content .= "\t";
                 if (!empty($spl_discount[$key])) {
                     $content .= $spl_discount[$key];
                 }
             }
             $content .= "\n";
             $content .= 'SPL';
             foreach ($spl as $key => $value) {
                 $content .= "\t";
                 if (!empty($spl_end[$key])) {
                     $content .= $spl_end[$key];
                 }
             }
             $content .= "\n";
             $splid = 3;
             $content .= 'ENDTRNS';
             $content .= "\n";
             //if ( --$max_rows == 0 )
             //	break;
             $cust_content .= 'CUST';
             foreach ($cust as $key => $value) {
                 $cust_content .= "\t" . $value;
             }
             $cust_content .= "\n";
         }
     }
     $file_name = 'download.iif';
     header('Content-Type: text/csv');
     header('Content-Disposition: inline; filename="' . $file_name . '"');
     echo $headers;
     echo $cust_content;
     echo $content;
     exit;
 }