Completed
Push — master ( ab284c...4fdc7c )
by Justin
07:07
created

ajax.php ➔ wpsc_submit_checkout()   F

Complexity

Conditions 38
Paths > 20000

Size

Total Lines 201
Code Lines 129

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 38
eloc 129
c 1
b 0
f 0
nc 155520
nop 1
dl 0
loc 201
rs 2

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
add_action( 'wp_ajax_wpsc_shipping_same_as_billing', 'wpsc_shipping_same_as_billing' );
3
add_action( 'wp_ajax_shipping_same_as_billing_update', 'wpsc_update_shipping_quotes_on_shipping_same_as_billing' );
4
add_action( 'wp_ajax_nopriv_shipping_same_as_billing_update', 'wpsc_update_shipping_quotes_on_shipping_same_as_billing' );
5
6
if ( isset( $_GET['termsandconds'] ) && 'true' == $_GET['termsandconds'] )
7
	add_action( 'init', 'wpsc_show_terms_and_conditions' );
8
9
if ( isset( $_REQUEST['submitwpcheckout_profile'] ) ) {
10
	add_action( 'init', 'wpsc_save_user_profile', 10, 0 );
11
}
12
13
if ( isset( $_REQUEST['wpsc_action'] ) && ($_REQUEST['wpsc_action'] == 'submit_checkout') ) {
14
	add_action( 'init', 'wpsc_submit_checkout', 10, 0 );
15
}
16
17
if ( isset( $_REQUEST['wpsc_action'] ) && ($_REQUEST['wpsc_action'] == 'cart_html_page') )
18
	add_action( 'init', 'wpsc_cart_html_page', 110 );
19
20
if ( get_option( 'wpsc_also_bought' ) == 1 )
21
	add_action( 'wpsc_submit_checkout', 'wpsc_populate_also_bought_list' );
22
23
if ( isset( $_REQUEST['get_rating_count'] ) && ($_REQUEST['get_rating_count'] == 'true') && is_numeric( $_POST['product_id'] ) )
24
	add_action( 'init', 'wpsc_get_rating_count' );
25
26
if ( isset( $_REQUEST['wpsc_ajax_action'] ) && ($_REQUEST['wpsc_ajax_action'] == 'special_widget' || $_REQUEST['wpsc_ajax_action'] == 'donations_widget') )
27
	add_action( 'init', 'wpsc_special_widget' );
28
29
if ( isset( $_REQUEST['wpsc_ajax_action'] ) && (($_REQUEST['wpsc_ajax_action'] == 'empty_cart') || (isset($_GET['sessionid'])  && ($_GET['sessionid'] > 0))) )
30
	add_action( 'init', 'wpsc_empty_cart' );
31
32
if ( isset( $_POST['coupon_num'] ) )
33
	add_action( 'init', 'wpsc_coupon_price' );
34
35
if ( isset( $_REQUEST['wpsc_ajax_action'] ) && 'add_to_cart' == $_REQUEST['wpsc_ajax_action'] )
36
    add_action( 'init', 'wpsc_add_to_cart' );
37
38
if ( isset( $_REQUEST['wpsc_update_quantity'] ) && ($_REQUEST['wpsc_update_quantity'] == 'true') )
39
	add_action( 'init', 'wpsc_update_item_quantity' );
40
41
if ( isset( $_REQUEST['wpsc_ajax_action'] ) && ($_REQUEST['wpsc_ajax_action'] == 'rate_product') )
42
	add_action( 'init', 'wpsc_update_product_rating' );
43
44
if ( isset( $_REQUEST['wpsc_ajax_action'] ) && 'update_location' == $_REQUEST['wpsc_ajax_action'] ) {
45
	add_action( 'init', 'wpsc_update_location' );
46
}
47
48
if ( isset( $_REQUEST['wpsc_ajax_action'] ) && 'update_shipping_price' == $_REQUEST['wpsc_ajax_action'] ) {
49
    add_action( 'init', 'wpsc_update_shipping_price' );
50
}
51
52
if ( isset( $_REQUEST['update_product_price'] ) && 'true' == $_REQUEST['update_product_price'] && ! empty( $_POST['product_id'] ) && is_numeric( $_POST['product_id'] ) ) {
53
    add_action( 'init', 'wpsc_update_product_price' );
54
}
55
56
add_action( 'wp_ajax_add_to_cart'       , 'wpsc_add_to_cart' );
57
add_action( 'wp_ajax_nopriv_add_to_cart', 'wpsc_add_to_cart' );
58
add_action( 'wp_ajax_get_cart'       , 'wpsc_get_cart' );
59
add_action( 'wp_ajax_nopriv_get_cart', 'wpsc_get_cart' );
60
add_action( 'wp_ajax_update_shipping_price'       , 'wpsc_update_shipping_price' );
61
add_action( 'wp_ajax_nopriv_update_shipping_price', 'wpsc_update_shipping_price' );
62
add_action( 'wp_ajax_update_product_price'       , 'wpsc_update_product_price' );
63
add_action( 'wp_ajax_nopriv_update_product_price', 'wpsc_update_product_price' );
64
add_action( 'wp_ajax_update_location'       , 'wpsc_update_location' );
65
add_action( 'wp_ajax_nopriv_update_location', 'wpsc_update_location' );
66
add_action( 'wp_ajax_change_tax'       , 'wpsc_change_tax' );
67
add_action( 'wp_ajax_nopriv_change_tax', 'wpsc_change_tax' );
68
add_action( 'wp_ajax_change_profile_country'       , '_wpsc_change_profile_country' );
69
add_action( 'wp_ajax_nopriv_change_profile_country', '_wpsc_change_profile_country' );
70
71
72
/**
73
 * WP eCommerce AJAX and Init functions
74
 *
75
 * These are the WPSC AJAX and Init functions
76
 *
77
 * @package wp-e-commerce
78
 * @since 3.7
79
 */
80
function wpsc_special_widget() {
81
	wpsc_add_to_cart();
82
}
83
84
/**
85
 * add_to_cart function, used through ajax and in normal page loading.
86
 * No parameters, returns nothing
87
 *
88
 * @uses wpsc_get_product_id_from_variations()              Given array of variation selections returns the variation product id as int
89
 */
90
function wpsc_add_to_cart() {
91
	global $wpsc_cart;
92
93
	$default_parameters = $cart_messages = $provided_parameters = array();
94
95
	/// default values
96
	$default_parameters['variation_values'] = null;
97
	$default_parameters['quantity'] = 1;
98
	$default_parameters['provided_price'] = null;
99
	$default_parameters['comment'] = null;
100
	$default_parameters['time_requested'] = null;
101
	$default_parameters['custom_message'] = '';
102
	$default_parameters['file_data'] = null;
103
	$default_parameters['is_customisable'] = false;
104
	$default_parameters['meta'] = null;
105
106
	$post_type_object = get_post_type_object( 'wpsc-product' );
107
	$permitted_post_statuses = current_user_can( $post_type_object->cap->edit_posts ) ? apply_filters( 'wpsc_product_display_status', array( 'publish' ) ) : array( 'publish' );
108
109
	/// sanitise submitted values
110
	$product_id = apply_filters( 'wpsc_add_to_cart_product_id'    , (int) $_REQUEST['product_id'] );
111
	$product    = apply_filters( 'wpsc_add_to_cart_product_object', get_post( $product_id, OBJECT, 'display' ) );
112
113
	if ( ! in_array( $product->post_status, $permitted_post_statuses ) || 'wpsc-product' != $product->post_type ) {
114
		return false;
115
	}
116
117
	// compatibility with older themes
118
	if ( isset( $_REQUEST['wpsc_quantity_update'] ) && is_array( $_REQUEST['wpsc_quantity_update'] ) ) {
119
		$_REQUEST['wpsc_quantity_update'] = $_REQUEST['wpsc_quantity_update'][$product_id];
120
	}
121
122
	if ( isset( $_REQUEST['variation'] ) ) {
123
		$return_variation_params                 = wpsc_get_product_data_from_variations( $_REQUEST['variation'], $product_id );
124
		$product_id                              = $return_variation_params['product_id'];
125
		$provided_parameters['variation_values'] = $return_variation_params['variation_values'];
126
	}
127
128
	if ( (isset( $_REQUEST['quantity'] ) && $_REQUEST['quantity'] > 0) && (!isset( $_REQUEST['wpsc_quantity_update'] )) ) {
129
		$provided_parameters['quantity'] = (int) $_REQUEST['quantity'];
130
	} else if ( isset( $_REQUEST['wpsc_quantity_update'] ) ) {
131
		$wpsc_cart->remove_item( $_REQUEST['key'] );
132
		$provided_parameters['quantity'] = (int) $_REQUEST['wpsc_quantity_update'];
133
	}
134
135
	if ( isset( $_REQUEST['is_customisable'] ) &&
136
		'true' == $_REQUEST['is_customisable'] ) {
137
		$provided_parameters['is_customisable'] = true;
138
139
		if ( isset( $_REQUEST['custom_text'] ) ) {
140
			$provided_parameters['custom_message'] = stripslashes( $_REQUEST['custom_text'] );
141
		}
142
		if ( isset( $_FILES['custom_file'] ) ) {
143
			$provided_parameters['file_data'] = $_FILES['custom_file'];
144
		}
145
	}
146
147
	if ( isset( $_REQUEST['donation_price'] ) && ( (float) $_REQUEST['donation_price'] > 0 ) ) {
148
		$provided_parameters['provided_price'] = (float) $_REQUEST['donation_price'];
149
	}
150
151
	$parameters = array_merge( $default_parameters, (array) $provided_parameters );
152
153
	$cart_item = $wpsc_cart->set_item( $product_id, $parameters );
154
155
	if ( is_object( $cart_item ) ) {
156
157
		do_action( 'wpsc_add_to_cart', $product, $cart_item );
158
		$cart_messages[] = str_replace( "[product_name]", $cart_item->get_title(), __( 'You just added "[product_name]" to your cart.', 'wp-e-commerce' ) );
159
160
	} else {
161
		if ( $parameters['quantity'] <= 0 ) {
162
163
			$cart_messages[] = __( 'Sorry, but you cannot add zero items to your cart', 'wp-e-commerce' );
164
165
		} else if ( wpsc_product_has_variations( $product_id ) && is_null( $parameters['variation_values'] ) ) {
166
167
			$cart_messages[] = apply_filters( 'wpsc_add_to_cart_variation_missing_message', sprintf( __( 'This product has several options to choose from.<br /><br /><a href="%s" style="display:inline; float:none; margin: 0; padding: 0;">Visit the product page</a> to select options.', 'wp-e-commerce' ), esc_url( get_permalink( $product_id ) ) ), $product_id );
168
169
		} else if ( $wpsc_cart->get_remaining_quantity( $product_id, $parameters['variation_values'], $parameters['quantity'] ) > 0 ) {
170
171
			$quantity        = $wpsc_cart->get_remaining_quantity( $product_id, $parameters['variation_values'], $parameters['quantity'] );
172
			$cart_messages[] = sprintf( _n( 'Sorry, but there is only %s of this item in stock.', 'Sorry, but there are only %s of this item in stock.', $quantity, 'wp-e-commerce' ), $quantity );
173
174
		} else {
175
176
			$cart_messages[] = apply_filters( 'wpsc_add_to_cart_out_of_stock_message', __( 'Sorry, but this item is out of stock.', 'wp-e-commerce' ), $product_id );
177
178
		}
179
	}
180
181
	if ( defined( 'DOING_AJAX' ) && DOING_AJAX ) {
182
		$json_response = array( 'cart_messages' => $cart_messages, 'product_id' => $product_id, 'cart_total' => wpsc_cart_total() );
183
184
		$output = _wpsc_ajax_get_cart( false, $cart_messages );
185
186
		$json_response = $json_response + $output;
187
188
		if ( is_numeric( $product_id ) && 1 == get_option( 'fancy_notifications' ) ) {
189
			$json_response['fancy_notification'] = str_replace( array( "\n", "\r" ), array( '\n', '\r' ), fancy_notification_content( $cart_messages ) );
190
		}
191
192
		$json_response = apply_filters( 'wpsc_add_to_cart_json_response', $json_response );
193
194
		die( json_encode( $json_response ) );
195
	}
196
}
197
198
function wpsc_get_cart() {
199
	_wpsc_ajax_get_cart();
200
}
201
202
/* 19-02-09
203
 * add cart button function used for php template tags and shortcodes
204
 */
205
206
function wpsc_add_to_cart_button( $product_id, $return = false ) {
207
	global $wpdb,$wpsc_variations;
208
	$output = '';
209
	if ( $product_id > 0 ) {
210
		// grab the variation form fields here
211
		$wpsc_variations = new wpsc_variations( $product_id );
212
		if ( $return )
213
			ob_start();
214
		?>
215
			<div class='wpsc-add-to-cart-button'>
216
				<form class='wpsc-add-to-cart-button-form' id='product_<?php echo esc_attr( $product_id ) ?>' action='' method='post'>
217
					<?php do_action( 'wpsc_add_to_cart_button_form_begin', $product_id ); ?>
218
					<div class='wpsc_variation_forms'>
219
						<?php while ( wpsc_have_variation_groups() ) : wpsc_the_variation_group(); ?>
220
							<p>
221
								<label for='<?php echo wpsc_vargrp_form_id(); ?>'><?php echo esc_html( wpsc_the_vargrp_name() ) ?>:</label>
222
								<select class='wpsc_select_variation' name='variation[<?php echo wpsc_vargrp_id(); ?>]' id='<?php echo wpsc_vargrp_form_id(); ?>'>
223
									<?php while ( wpsc_have_variations() ): wpsc_the_variation(); ?>
224
										<option value='<?php echo wpsc_the_variation_id(); ?>' <?php echo wpsc_the_variation_out_of_stock(); ?>><?php echo esc_html( wpsc_the_variation_name() ); ?></option>
225
									<?php endwhile; ?>
226
								</select>
227
							</p>
228
						<?php endwhile; ?>
229
					</div>
230
					<input type='hidden' name='wpsc_ajax_action' value='add_to_cart' />
231
					<input type='hidden' name='product_id' value='<?php echo $product_id; ?>' />
232
					<input type='submit' id='product_<?php echo $product_id; ?>_submit_button' class='wpsc_buy_button' name='Buy' value='<?php echo __( 'Add To Cart', 'wp-e-commerce' ); ?>'  />
233
					<?php do_action( 'wpsc_add_to_cart_button_form_end', $product_id ); ?>
234
				</form>
235
			</div>
236
		<?php
237
238
		if ( $return ) {
239
			return ob_get_clean();
240
		}
241
	}
242
}
243
244
/* 19-02-09
245
 * add to cart shortcode function used for shortcodes calls the function in
246
 * product_display_functions.php
247
 */
248
249
function add_to_cart_shortcode( $content = '' ) {
250
	static $fancy_notification_output = false;
251
	if ( ! in_the_loop() )
252
		return $content;
253
254
	if ( preg_match_all( "/\[add_to_cart=([\d]+)\]/", $content, $matches ) ) {
255
		foreach ( $matches[1] as $key => $product_id ) {
256
			$original_string = $matches[0][$key];
257
			$output = wpsc_add_to_cart_button( $product_id, true );
258
			$content = str_replace( $original_string, $output, $content );
259
		}
260
261
		if ( ! $fancy_notification_output ) {
262
			$content .= wpsc_fancy_notifications( true );
263
			$fancy_notification_output = true;
264
		}
265
	}
266
	return $content;
267
}
268
269
/**
270
 * empty cart function, used through ajax and in normal page loading.
271
 * No parameters, returns nothing
272
 */
273
function wpsc_empty_cart() {
274
	global $wpsc_cart;
275
	$wpsc_cart->empty_cart( false );
276
277
	if ( defined( 'DOING_AJAX' ) && DOING_AJAX ) {
278
		$output = apply_filters( 'wpsc_empty_cart_response', _wpsc_ajax_get_cart( false ) );
279
		die( json_encode( $output ) );
280
	}
281
}
282
283
/**
284
 * update quantity function, used through ajax and in normal page loading.
285
 * No parameters, returns nothing
286
 */
287
function wpsc_update_item_quantity() {
288
	global $wpsc_cart;
289
290
	if ( is_numeric( $_POST['key'] ) ) {
291
		$key = (int)$_POST['key'];
292
293
		$quantity = isset( $_POST['wpsc_quantity_update'] ) ? $_POST['wpsc_quantity_update'] : '';
294
295
		if ( isset( $_POST['quantity'] ) )
296
			$quantity = $_POST['quantity'];
297
298
		if ( $quantity > 0 ) {
299
			// if the quantity is greater than 0, update the item;
300
			$parameters['quantity'] = (int) $quantity;
0 ignored issues
show
Coding Style Comprehensibility introduced by
$parameters was never initialized. Although not strictly required by PHP, it is generally a good practice to add $parameters = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
301
			$wpsc_cart->edit_item( $key, $parameters );
302
		} else {
303
			// if the quantity is 0, remove the item.
304
			$wpsc_cart->remove_item( $key );
305
		}
306
307
		$coupon = wpsc_get_customer_meta( 'coupon' );
308
		if ( $coupon ) {
309
			wpsc_coupon_price( $coupon );
310
		}
311
	}
312
	$die = ! ( ( isset( $_REQUEST['wpsc_ajax_action'] ) && 'true' == $_REQUEST['wpsc_ajax_action'] ) || ( ! defined( 'DOING_AJAX' ) || ! DOING_AJAX ) );
313
	_wpsc_ajax_get_cart( $die );
314
}
315
316
317
function wpsc_update_product_rating() {
318
	global $wpdb;
319
	$nowtime = time();
320
	$product_id = absint( $_POST['product_id'] );
321
	$ip_number = $_SERVER['REMOTE_ADDR'];
0 ignored issues
show
introduced by
Due to using Batcache, server side based client related logic will not work, use JS instead.
Loading history...
322
	$rating = absint( $_POST['product_rating'] );
323
324
	$cookie_data = explode( ",", $_COOKIE['voting_cookie'][$product_id] );
0 ignored issues
show
introduced by
Due to using Batcache, server side based client related logic will not work, use JS instead.
Loading history...
325
326
	if ( is_numeric( $cookie_data[0] ) && ($cookie_data[0] > 0) ) {
327
		$vote_id = absint( $cookie_data[0] );
328
		$wpdb->update( WPSC_TABLE_PRODUCT_RATING, array(
329
		'rated' => $rating
330
		), array( 'id' => $vote_id ) );
331
	} else {
332
		$wpdb->insert( WPSC_TABLE_PRODUCT_RATING, array(
333
		'ipnum' => $ip_number,
334
		'productid' => $product_id,
335
		'rated' => $rating,
336
		'time' => $nowtime
337
		) );
338
		$data = $wpdb->get_results( "SELECT `id`,`rated` FROM `" . WPSC_TABLE_PRODUCT_RATING . "` WHERE `ipnum`='" . $ip_number . "' AND `productid` = '" . $product_id . "'  AND `rated` = '" . $rating . "' AND `time` = '" . $nowtime . "' ORDER BY `id` DESC LIMIT 1", ARRAY_A );
339
		$vote_id = $data[0]['id'];
340
		setcookie( "voting_cookie[$product_id]", ($vote_id . "," . $rating ), time() + (60 * 60 * 24 * 360) );
0 ignored issues
show
introduced by
Due to using Batcache, server side based client related logic will not work, use JS instead.
Loading history...
341
	}
342
	if ( $_POST['ajax'] == 'true' ) {
343
344
		exit();
345
	}
346
}
347
348
/**
349
 * update_shipping_price function, used through ajax and in normal page loading.
350
 * No parameters, returns nothing
351
 */
352
function wpsc_update_shipping_price() {
353
	global $wpsc_cart;
354
355
	$quote_shipping_method = $_POST['method'];
356
	$quote_shipping_option = str_replace( array( '®', '™' ), array( '&reg;', '&trade;' ), $_POST['option'] );
357
358
    if ( ! empty( $quote_shipping_option ) && ! empty( $quote_shipping_method ) ) {
359
        $wpsc_cart->update_shipping( $quote_shipping_method, $quote_shipping_option );
360
    }
361
362
    if ( defined( 'DOING_AJAX' ) && DOING_AJAX ) {
363
364
    	$response = apply_filters( 'wpsc_update_shipping_price_response', array(
365
				'shipping'   => wpsc_cart_shipping(),
366
				'coupon'     => wpsc_coupon_amount(),
367
				'cart_total' => wpsc_cart_total(),
368
				'tax'        => wpsc_cart_tax()
369
    		),
370
    		$quote_shipping_method,
371
    		$quote_shipping_option
372
    	);
373
 		echo json_encode( $response );
374
    	exit();
375
    }
376
377
}
378
379
/**
380
 * update_shipping_price function, used through ajax and in normal page loading.
381
 * No parameters, returns nothing
382
 */
383
function wpsc_get_rating_count() {
384
	global $wpdb, $wpsc_cart;
385
	$prodid = $_POST['product_id'];
386
	$count = $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(*) AS `count` FROM `" . WPSC_TABLE_PRODUCT_RATING . "` WHERE `productid` = %d", $prodid ) );
387
	echo $count . "," . absint( $prodid );
388
	exit();
389
}
390
391
/**
392
 * update_product_page_price function, used through ajax with variations
393
 * No parameters, returns nothing
394
 */
395
function wpsc_update_product_price() {
396
	if ( empty( $_POST['product_id'] ) || ! is_numeric( $_POST['product_id'] ) ) {
397
		return;
398
	}
399
400
	$from = '';
401
	$change_price = true;
402
	$product_id = (int) $_POST['product_id'];
403
	$variations = array();
404
	$response   = array(
405
		'product_id'      => $product_id,
406
		'variation_found' => false,
407
	);
408
409
	if ( ! empty( $_POST['variation'] ) ) {
410
		foreach ( $_POST['variation'] as $variation ) {
411
			if ( is_numeric( $variation ) ) {
412
				$variations[] = (int)$variation;
413
			}
414
		}
415
416
		do_action( 'wpsc_update_variation_product', $product_id, $variations );
417
418
		$stock = wpsc_check_variation_stock_availability( $product_id, $variations );
419
420
		if ( $stock !== false ) {
421
			$response['variation_found'] = true;
422
			if ( $stock === 0 ) {
423
				$response += array(
424
					'product_msg'     =>  __( 'Sorry, but this variation is out of stock.', 'wp-e-commerce' ),
0 ignored issues
show
introduced by
Expected 1 space after "=>"; 2 found
Loading history...
425
					'variation_msg'   => __( 'Variation not in stock', 'wp-e-commerce' ),
426
					'stock_available' => false,
427
				);
428
			} else {
429
				$response += array(
430
					'variation_msg'   => __( 'Product in stock', 'wp-e-commerce' ),
431
					'stock_available' => true,
432
				);
433
			}
434
435
			if ( $change_price ) {
436
				$old_price           = wpsc_calculate_price( $product_id, $variations, false );
437
				$you_save_amount     = wpsc_you_save( array( 'product_id' => $product_id, 'type' => 'amount', 'variations' => $variations ) );
438
				$you_save_percentage = wpsc_you_save( array( 'product_id' => $product_id, 'variations' => $variations ) );
439
440
				$price = wpsc_calculate_price( $product_id, $variations, true );
441
442
				$response += array(
443
					'old_price'         => wpsc_currency_display( $old_price, array( 'display_as_html' => false ) ),
444
					'numeric_old_price' => (float) $old_price,
445
					'you_save'          => wpsc_currency_display( $you_save_amount, array( 'display_as_html' => false ) ) . "! (" . $you_save_percentage . "%)",
446
					'price'             => $from . wpsc_currency_display( $price, array( 'display_as_html' => false ) ),
447
					'numeric_price'     => (float) $price,
448
				);
449
			}
450
		}
451
	}
452
453
	$response = apply_filters( 'wpsc_update_product_price', $response, $product_id );
454
455
	echo json_encode( $response );
456
	exit();
457
}
458
459
/**
460
 * update location function, used through ajax and in normal page loading.
461
 * No parameters, returns nothing
462
 */
463
function wpsc_update_location() {
464
	global $wpsc_cart;
465
466
	/*
467
	 * Checkout page shipping calculator MAY provide a zip code using the identifier from prior
468
	 * releases.  Let's check for that.
469
	 */
470
	if ( isset( $_POST['zipcode'] ) ) {
471
		wpsc_update_customer_meta( 'shippingpostcode', sanitize_text_field( $_POST['zipcode'] ) );
472
	}
473
474
	/*
475
	 * Checkout page shipping calculator MAY provide a country code using the identifier from prior
476
	 * releases.  Let's check for that.
477
	 */
478
	if ( isset( $_POST['country'] ) ) {
479
		$wpsc_country = new WPSC_Country( $_POST['country'] );
480
		wpsc_update_customer_meta( 'shippingcountry', $wpsc_country->get_isocode() );
481
	}
482
483
	/*
484
	 * WPeC's totally awesome checkout page shipping calculator has a submit button that will send
485
	 * some of the shipping data to us in an AJAX request.  The format of the data as of version
486
	 * 3.8.14.1 uses the 'collected_data' array format just like in checkout. We should process
487
	 * this array in case it has some updates to the user meta (checkout information) that haven't been
488
	 * recorded at the time the calculate button was clicked.  If the country or zip code is set using the
489
	 * legacy 'country' or 'zip' code $_POST values they will be overwritten if they are also included
490
	 * in the collected_data $_POST value.
491
	 */
492
	if ( isset( $_POST['collected_data'] ) && is_array( $_POST['collected_data'] ) ) {
493
		_wpsc_checkout_customer_meta_update( $_POST['collected_data'] );
494
	}
495
496
	$wpsc_cart->update_location();
497
	$wpsc_cart->get_shipping_method();
498
	$wpsc_cart->get_shipping_option();
499
500
	if ( $wpsc_cart->selected_shipping_method != '' ) {
501
		$wpsc_cart->update_shipping( $wpsc_cart->selected_shipping_method, $wpsc_cart->selected_shipping_option );
502
	}
503
504
	if ( defined( 'DOING_AJAX' ) && DOING_AJAX && isset( $_REQUEST['action'] ) && 'update_location' == $_REQUEST['action'] )
505
		exit;
506
}
507
508
function wpsc_cart_html_page() {
509
	require_once(WPSC_FILE_PATH . '/wpsc-includes/shopping_cart_container.php' );
510
	exit();
511
}
512
513
/**
514
 * Populate Also Bought List
515
 * Runs on checking out and populates the also bought list.
516
 */
517
function wpsc_populate_also_bought_list() {
518
	global $wpdb, $wpsc_cart, $wpsc_coupons;
519
520
	$new_also_bought_data = array();
521
	foreach ( $wpsc_cart->cart_items as $outer_cart_item ) {
522
		$new_also_bought_data[$outer_cart_item->product_id] = array();
523
		foreach ( $wpsc_cart->cart_items as $inner_cart_item ) {
524
			if ( $outer_cart_item->product_id != $inner_cart_item->product_id ) {
525
				$new_also_bought_data[$outer_cart_item->product_id][$inner_cart_item->product_id] = $inner_cart_item->quantity;
526
			} else {
527
				continue;
528
			}
529
		}
530
	}
531
532
	$insert_statement_parts = array();
533
	foreach ( $new_also_bought_data as $new_also_bought_id => $new_also_bought_row ) {
534
		$new_other_ids = array_keys( $new_also_bought_row );
535
		$also_bought_data = $wpdb->get_results( $wpdb->prepare( "SELECT `id`, `associated_product`, `quantity` FROM `" . WPSC_TABLE_ALSO_BOUGHT . "` WHERE `selected_product` IN(%d) AND `associated_product` IN('" . implode( "','", $new_other_ids ) . "')", $new_also_bought_id ), ARRAY_A );
536
		$altered_new_also_bought_row = $new_also_bought_row;
537
538
		foreach ( (array)$also_bought_data as $also_bought_row ) {
539
			$quantity = $new_also_bought_row[$also_bought_row['associated_product']] + $also_bought_row['quantity'];
540
541
			unset( $altered_new_also_bought_row[$also_bought_row['associated_product']] );
542
			$wpdb->update(
543
				WPSC_TABLE_ALSO_BOUGHT,
544
				array(
545
				    'quantity' => $quantity
546
				),
547
				array(
548
				    'id' => $also_bought_row['id']
549
				),
550
				'%d',
551
				'%d'
552
			);
553
	    }
554
555
		if ( count( $altered_new_also_bought_row ) > 0 ) {
556
			foreach ( $altered_new_also_bought_row as $associated_product => $quantity ) {
557
				$insert_statement_parts[] = "(" . absint( esc_sql( $new_also_bought_id ) ) . "," . absint( esc_sql( $associated_product ) ) . "," . absint( esc_sql( $quantity ) ) . ")";
558
			}
559
		}
560
	}
561
562
	if ( count( $insert_statement_parts ) > 0 ) {
563
		$insert_statement = "INSERT INTO `" . WPSC_TABLE_ALSO_BOUGHT . "` (`selected_product`, `associated_product`, `quantity`) VALUES " . implode( ",\n ", $insert_statement_parts );
564
		$wpdb->query( $insert_statement );
565
	}
566
}
567
568
/**
569
 * submit checkout function, used through ajax and in normal page loading.
570
 * No parameters, returns nothing
571
 */
572
function wpsc_submit_checkout( $collected_data = true ) {
573
	global $wpdb, $wpsc_cart, $user_ID, $nzshpcrt_gateways, $wpsc_shipping_modules, $wpsc_gateways;
574
575
	if ( $collected_data && isset( $_POST['collected_data'] ) && is_array( $_POST['collected_data'] ) ) {
576
		_wpsc_checkout_customer_meta_update( $_POST['collected_data'] );
577
	}
578
579
	// initialize our checkout status variable, we start be assuming
580
	// checkout is falid, until we find a reason otherwise
581
	$is_valid           = true;
582
	$num_items          = 0;
583
	$use_shipping       = 0;
584
	$disregard_shipping = 0;
585
586
	do_action( 'wpsc_before_submit_checkout', $collected_data );
587
588
	$error_messages = wpsc_get_customer_meta( 'checkout_misc_error_messages' );
589
590
	if ( ! is_array( $error_messages ) ) {
591
		$error_messages = array();
592
	}
593
594
	$wpsc_checkout = new wpsc_checkout();
595
596
	$selected_gateways = get_option( 'custom_gateway_options' );
597
	$submitted_gateway = isset( $_POST['custom_gateway'] ) ? $_POST['custom_gateway'] : '';
598
599
	if ( $collected_data ) {
600
		$form_validity = $wpsc_checkout->validate_forms();
601
		extract( $form_validity ); // extracts $is_valid and $error_messages
0 ignored issues
show
introduced by
extract() usage is highly discouraged, due to the complexity and unintended issues it might cause.
Loading history...
602
603
		if ( wpsc_has_tnc() && ( ! isset( $_POST['agree'] ) || $_POST['agree'] != 'yes' ) ) {
604
			$error_messages[] = __( 'Please agree to the terms and conditions, otherwise we cannot process your order.', 'wp-e-commerce' );
605
			$is_valid = false;
606
		}
607
	} else {
608
		$is_valid = true;
609
		$error_messages = array();
610
	}
611
612
	if ( wpsc_uses_shipping() ) {
613
		$wpsc_country = new WPSC_Country( wpsc_get_customer_meta( 'shippingcountry' ) );
614
		$country_id   = $wpsc_country->get_id();
615
		$country_name = $wpsc_country->get_name();
616
617
		foreach ( $wpsc_cart->cart_items as $cartitem ) {
618
619
			if ( ! empty( $cartitem->meta[0]['no_shipping'] ) ) {
620
				continue;
621
			}
622
623
			$category_ids = $cartitem->category_id_list;
624
625
			foreach ( (array) $category_ids as $catid ) {
626
				if ( is_array( $catid ) ) {
627
					$countries = wpsc_get_meta( $catid[0], 'target_market', 'wpsc_category' );
628
				} else {
629
					$countries = wpsc_get_meta( $catid, 'target_market', 'wpsc_category' );
630
				}
631
632
				if ( ! empty( $countries ) && ! in_array( $country_id, (array) $countries ) ) {
633
					$errormessage = sprintf( __( '%s cannot be shipped to %s. To continue with your transaction, please remove this product from the list below.', 'wp-e-commerce' ), $cartitem->get_title(), $country_name );
634
					wpsc_update_customer_meta( 'category_shipping_conflict', $errormessage );
635
					$is_valid = false;
636
				}
637
			}
638
639
			//count number of items, and number of items using shipping
640
			$num_items++;
641
642
			if ( $cartitem->uses_shipping != 1 ) {
643
				$disregard_shipping++;
644
			} else {
645
				$use_shipping++;
646
			}
647
		}
648
	}
649
650
	// check to see if the current gateway is in the list of available gateways
651
	if ( array_search( $submitted_gateway, $selected_gateways ) !== false || wpsc_is_free_cart() ) {
652
		wpsc_update_customer_meta( 'selected_gateway', $submitted_gateway );
653
	} else {
654
		$is_valid = false;
655
	}
656
657
	if ( $collected_data ) {
658
659
		// Test for required shipping information
660
		if ( wpsc_core_shipping_enabled() && ( $num_items != $disregard_shipping ) ) {
661
			// for shipping to work we need a method, option and a quote, unless we have free shipping.
662
663
			$shipping_discount_value  = get_option( 'shipping_discount_value' );
664
			$is_free_shipping_enabled = get_option( 'shipping_discount' );
665
			$subtotal                 = $wpsc_cart->calculate_subtotal();
666
667
			$has_free_shipping = $is_free_shipping_enabled && $shipping_discount_value > 0 && $shipping_discount_value <= $subtotal;
668
669
			if ( ! $has_free_shipping ) {
670
				if ( ! $wpsc_cart->shipping_method_selected() || ! $wpsc_cart->shipping_quote_selected() ) {
671
					$error_messages[] = __( 'Please select one of the available shipping options, then we can process your order.', 'wp-e-commerce' );
672
					$is_valid = false;
673
				}
674
			}
675
676
			// if we don't have a valid zip code ( the function also checks if we need it ) we have an error
677
			if ( ! wpsc_have_valid_shipping_zipcode() ) {
678
					wpsc_update_customer_meta( 'category_shipping_conflict', __( 'Please enter a Zipcode and click calculate to proceed', 'wp-e-commerce' ) );
679
					$is_valid = false;
680
			}
681
		}
682
	}
683
684
	wpsc_update_customer_meta( 'checkout_misc_error_messages', $error_messages );
685
686
	if ( $is_valid == true ) {
0 ignored issues
show
Coding Style Best Practice introduced by
It seems like you are loosely comparing two booleans. Considering using the strict comparison === instead.

When comparing two booleans, it is generally considered safer to use the strict comparison operator.

Loading history...
687
		wpsc_delete_customer_meta( 'category_shipping_conflict' );
688
		// check that the submitted gateway is in the list of selected ones
689
		$sessionid = (mt_rand( 100, 999 ) . time());
690
		wpsc_update_customer_meta( 'checkout_session_id', $sessionid );
691
		$subtotal = $wpsc_cart->calculate_subtotal();
692
		if ( $wpsc_cart->has_total_shipping_discount() == false )
693
			$base_shipping = $wpsc_cart->calculate_base_shipping();
694
		else
695
			$base_shipping = 0;
696
697
		$delivery_country = $wpsc_cart->delivery_country;
698
		$delivery_region = $wpsc_cart->delivery_region;
699
700
		if ( wpsc_uses_shipping() ) {
701
			$shipping_method = $wpsc_cart->selected_shipping_method;
702
			$shipping_option = $wpsc_cart->selected_shipping_option;
703
		} else {
704
			$shipping_method = '';
705
			$shipping_option = '';
706
		}
707
		if ( isset( $_POST['how_find_us'] ) )
708
			$find_us = $_POST['how_find_us'];
709
		else
710
			$find_us = '';
711
712
		//keep track of tax if taxes are exclusive
713
		$wpec_taxes_controller = new wpec_taxes_controller();
714
		if ( ! $wpec_taxes_controller->wpec_taxes_isincluded() ) {
715
			$tax = $wpsc_cart->calculate_total_tax();
716
			$tax_percentage = $wpsc_cart->tax_percentage;
717
		} else {
718
			$tax = 0.00;
719
			$tax_percentage = 0.00;
720
		}
721
722
		$total = $wpsc_cart->calculate_total_price();
723
724
		$args = array(
725
			'totalprice'       => $total,
726
			'statusno'         => '0',
727
			'sessionid'        => $sessionid,
728
			'user_ID'          => (int) $user_ID,
729
			'date'             => time(),
730
			'gateway'          => $submitted_gateway,
731
			'billing_country'  => $wpsc_cart->selected_country,
732
			'shipping_country' => $delivery_country,
733
			'billing_region'   => $wpsc_cart->selected_region,
734
			'shipping_region'  => $delivery_region,
735
			'base_shipping'    => $base_shipping,
736
			'shipping_method'  => $shipping_method,
737
			'shipping_option'  => $shipping_option,
738
			'plugin_version'   => WPSC_VERSION,
739
			'discount_value'   => $wpsc_cart->coupons_amount,
740
			'discount_data'    => $wpsc_cart->coupons_name,
741
			'find_us'          => $find_us,
742
			'wpec_taxes_total' => $tax,
743
			'wpec_taxes_rate'  => $tax_percentage,
744
		);
745
746
		$purchase_log = new WPSC_Purchase_Log( $args );
747
		$purchase_log->save();
748
		$purchase_log_id = $purchase_log->get( 'id' );
749
750
		//Check to ensure log row was inserted successfully
751
		if(is_null($purchase_log_id)) {
752
			$error_messages[] = __( 'A database error occurred while processing your request.', 'wp-e-commerce' );
753
			wpsc_update_customer_meta( 'checkout_misc_error_messages', $error_messages );
754
			return;
755
		}
756
757
		if ( $collected_data ) {
758
			$wpsc_checkout->save_forms_to_db( $purchase_log_id );
759
		}
760
761
		$wpsc_cart->save_to_db( $purchase_log_id );
762
		$wpsc_cart->submit_stock_claims( $purchase_log_id );
763
764
		if ( ! isset( $our_user_id ) && isset( $user_ID ) ) {
765
			$our_user_id = $user_ID;
766
		}
767
768
		$wpsc_cart->log_id = $purchase_log_id;
769
		do_action( 'wpsc_submit_checkout', array( 'purchase_log_id' => $purchase_log_id, 'our_user_id' => $our_user_id ) );
770
		do_action( 'wpsc_submit_checkout_gateway', $submitted_gateway, $purchase_log );
771
	}
772
}
773
774
/**
775
 * wpsc_change_tax function, used through ajax and in normal page loading.
776
 * No parameters, returns nothing
777
 */
778
function wpsc_change_tax() {
779
	global $wpdb, $wpsc_cart;
780
0 ignored issues
show
Coding Style introduced by
Functions must not contain multiple empty lines in a row; found 2 empty lines
Loading history...
781
782
	$form_id = absint( $_POST['form_id'] );
783
784
	$wpsc_selected_country = $wpsc_cart->selected_country;
785
	$wpsc_selected_region  = $wpsc_cart->selected_region;
786
787
	$wpsc_delivery_country = $wpsc_cart->delivery_country;
788
	$wpsc_delivery_region  = $wpsc_cart->delivery_region;
789
790
	$previous_country = wpsc_get_customer_meta( 'billingcountry' );
791
792
	global $wpdb, $user_ID, $wpsc_customer_checkout_details;
793
794
	if ( isset( $_POST['billing_country'] ) ) {
795
		$wpsc_selected_country = sanitize_text_field( $_POST['billing_country'] );
796
		wpsc_update_customer_meta( 'billingcountry', $wpsc_selected_country );
797
	}
798
799
	if ( isset( $_POST['billing_region'] ) ) {
800
		$wpsc_selected_region = absint( $_POST['billing_region'] );
801
		wpsc_update_customer_meta( 'billingregion', $wpsc_selected_region );
802
	}
803
804
	$check_country_code = WPSC_Countries::get_country_id_by_region_id( wpsc_get_customer_meta( 'billing_region' ) );
805
806
	if ( wpsc_get_customer_meta( 'billingcountry' ) != $check_country_code ) {
807
		$wpsc_selected_region = null;
808
	}
809
810
	if ( isset( $_POST['shipping_country'] ) ) {
811
		$wpsc_delivery_country = sanitize_text_field( $_POST['shipping_country'] );
812
		wpsc_update_customer_meta( 'shippingcountry', $wpsc_delivery_country );
813
	}
814
	if ( isset( $_POST['shipping_region'] ) ) {
815
		$wpsc_delivery_region = absint( $_POST['shipping_region'] );
816
		wpsc_update_customer_meta( 'shippingregion', $wpsc_delivery_region );
817
	}
818
819
	$check_country_code = WPSC_Countries::get_country_id_by_region_id( $wpsc_delivery_region );
820
	if ( $wpsc_delivery_country != $check_country_code ) {
821
		$wpsc_delivery_region = null;
822
	}
823
824
	$wpsc_cart->update_location();
825
	$wpsc_cart->get_shipping_method();
826
	$wpsc_cart->get_shipping_option();
827
828
	if ( $wpsc_cart->selected_shipping_method != '' ) {
829
		$wpsc_cart->update_shipping( $wpsc_cart->selected_shipping_method, $wpsc_cart->selected_shipping_option );
830
	}
831
832
	$tax         = $wpsc_cart->calculate_total_tax();
833
	$total       = wpsc_cart_total();
834
	$total_input = wpsc_cart_total( false );
835
836
	if ( $wpsc_cart->coupons_amount >= $total_input && ! empty( $wpsc_cart->coupons_amount ) ) {
837
		$total = 0;
838
	}
839
840
	if ( $wpsc_cart->total_price < 0 ) {
841
		$wpsc_cart->coupons_amount += $wpsc_cart->total_price;
842
		$wpsc_cart->total_price     = null;
843
		$wpsc_cart->calculate_total_price();
844
	}
845
846
	$delivery_country = wpsc_get_customer_meta( 'shipping_country' );
847
	$output           = _wpsc_ajax_get_cart( false );
848
	$output           = $output['widget_output'];
849
850
	$json_response = array();
851
852
	global $wpsc_checkout;
853
	if ( empty( $wpsc_checkout ) ) {
854
		$wpsc_checkout = new wpsc_checkout();
855
	}
856
857
	$json_response['delivery_country'] = esc_js( $delivery_country );
858
	$json_response['billing_country']  = esc_js( $wpsc_selected_country );
859
	$json_response['widget_output']    = $output;
860
	$json_response['shipping_keys']    = array();
861
	$json_response['cart_shipping']    = wpsc_cart_shipping();
862
	$json_response['form_id']          = $form_id;
863
	$json_response['tax']              = $tax;
864
	$json_response['display_tax']      = wpsc_cart_tax();
865
	$json_response['total']            = $total;
866
	$json_response['total_input']      = $total_input;
867
868
	$json_response['lock_tax']     = get_option( 'lock_tax' );
869
	$json_response['country_name'] = wpsc_get_country( $delivery_country );
870
871
	if ( 'US' == $delivery_country || 'CA' == $delivery_country ) {
872
		$output = wpsc_shipping_region_list( $delivery_country, wpsc_get_customer_meta( 'shipping_region' ) );
873
		$output = str_replace( array( "\n", "\r" ), '', $output );
874
		$json_response['shipping_region_list'] = $output;
875
	}
876
877
	foreach ( $wpsc_cart->cart_items as $key => $cart_item ) {
878
		$json_response['shipping_keys'][ $key ] = wpsc_currency_display( $cart_item->shipping );
879
	}
880
881
	$form_selected_country = null;
882
	$form_selected_region  = null;
883
	$onchange_function     = null;
884
885
	if ( ! empty( $_POST['billing_country'] ) && $_POST['billing_country'] != 'undefined' && ! isset( $_POST['shipping_country'] ) ) {
886
		$form_selected_country = $wpsc_selected_country;
887
		$form_selected_region  = $wpsc_selected_region;
888
		$onchange_function     = 'set_billing_country';
889
	} else if ( ! empty( $_POST['shipping_country'] ) && $_POST['shipping_country'] != 'undefined' && ! isset( $_POST['billing_country'] ) ) {
890
		$form_selected_country = $wpsc_delivery_country;
891
		$form_selected_region  = $wpsc_delivery_region;
892
		$onchange_function     = 'set_shipping_country';
893
	}
894
895
	if ( $form_selected_country != null && $onchange_function != null ) {
0 ignored issues
show
Bug introduced by
It seems like you are loosely comparing $onchange_function of type string|null against null; this is ambiguous if the string can be empty. Consider using a strict comparison !== instead.
Loading history...
896
897
		$checkoutfields = 'set_shipping_country' == $onchange_function;
898
		$region_list = wpsc_country_region_list( $form_id, false, $form_selected_country, $form_selected_region, $form_id, $checkoutfields );
899
900
		if ( $region_list != null ) {
901
			$json_response['region_list'] = str_replace( array( "\n", "\r" ), '', $region_list );
902
		}
903
	}
904
905
	echo json_encode( $json_response );
906
	exit();
907
}
908
909
function _wpsc_change_profile_country() {
910
	global $wpdb;
911
912
	$country_field_id = absint( $_REQUEST['form_id'] );
913
	$country          = $_REQUEST['country'];
914
915
	$sql = $wpdb->prepare( 'SELECT unique_name FROM `'.WPSC_TABLE_CHECKOUT_FORMS.'` WHERE `id`= %d', $country_field_id );
916
	$country_field_unique_name = $wpdb->get_var( $sql );
917
918
	$has_regions = wpsc_has_regions( $country );
919
	$response = array( 'has_regions' => $has_regions );
920
921
	$region_unique_name = 'shippingstate';
922
	if ( $country_field_unique_name == 'billingcountry' )
923
		$region_unique_name = 'billingstate';
924
925
	$sql = $wpdb->prepare( 'SELECT id FROM ' . WPSC_TABLE_CHECKOUT_FORMS . ' WHERE unique_name=%s AND active="1"', $region_unique_name );
926
	$response['region_field_id'] = $wpdb->get_var( $sql );
927
928
	if ( $has_regions )
929
		$response['html'] = "<select name='collected_data[" . $country_field_id . "][1]'>" . nzshpcrt_region_list( $country, '' ) . "</select>";
930
931
	echo json_encode( $response );
932
	exit;
933
}
934
935
function wpsc_shipping_same_as_billing(){
936
	wpsc_update_customer_meta( 'shippingSameBilling', sanitize_text_field( $_POST['wpsc_shipping_same_as_billing'] ) );
937
}
938
939
function wpsc_update_shipping_quotes_on_shipping_same_as_billing() {
940
	global $wpsc_cart;
941
942
	wpsc_update_location();
943
944
	if ( get_option( 'do_not_use_shipping' ) )
945
		die( '-1' );
946
947
	if ( ! wpsc_have_shipping_quote() ) {
948
		die( '0' );
949
	}
950
	else {
951
		?>
952
   <tr class="wpsc_shipping_info">
953
            <td colspan="5">
954
               <?php _e( 'Please choose a country below to calculate your shipping costs', 'wp-e-commerce' ); ?>
955
            </td>
956
         </tr>
957
958
         <?php if ( ! wpsc_have_shipping_quote() ) : // No valid shipping quotes ?>
959
            <?php if ( ! wpsc_have_valid_shipping_zipcode() ) : ?>
960
                  <tr class='wpsc_update_location'>
961
                     <td colspan='5' class='shipping_error' >
962
                        <?php _e('Please provide a ZIP code and click Calculate in order to continue.', 'wp-e-commerce'); ?>
963
                     </td>
964
                  </tr>
965
            <?php else: ?>
966
               <tr class='wpsc_update_location_error'>
967
                  <td colspan='5' class='shipping_error' >
968
                     <?php _e('Sorry, online ordering is unavailable for this destination and/or weight. Please double check your destination details.', 'wp-e-commerce'); ?>
969
                  </td>
970
               </tr>
971
            <?php endif; ?>
972
         <?php endif; ?>
973
         <tr class='wpsc_change_country'>
974
            <td colspan='5'>
975
               <form name='change_country' id='change_country' action='' method='post'>
976
                  <?php echo wpsc_shipping_country_list();?>
977
                  <input type='hidden' name='wpsc_update_location' value='true' />
978
                  <input type='submit' name='wpsc_submit_zipcode' value='Calculate' />
979
               </form>
980
            </td>
981
         </tr>
982
983
         <?php if (wpsc_have_morethanone_shipping_quote()) :?>
984
            <?php while (wpsc_have_shipping_methods()) : wpsc_the_shipping_method(); ?>
985
                  <?php    if (!wpsc_have_shipping_quotes()) { continue; } // Don't display shipping method if it doesn't have at least one quote ?>
986
                  <tr class='wpsc_shipping_header'><td class='shipping_header' colspan='5'><?php echo wpsc_shipping_method_name().__(' - Choose a Shipping Rate', 'wp-e-commerce'); ?> </td></tr>
987
                  <?php while (wpsc_have_shipping_quotes()) : wpsc_the_shipping_quote();  ?>
988
                     <tr class='<?php echo wpsc_shipping_quote_html_id(); ?>'>
989
                        <td class='wpsc_shipping_quote_name wpsc_shipping_quote_name_<?php echo wpsc_shipping_quote_html_id(); ?>' colspan='3'>
990
                           <label for='<?php echo wpsc_shipping_quote_html_id(); ?>'><?php echo wpsc_shipping_quote_name(); ?></label>
991
                        </td>
992
                        <td class='wpsc_shipping_quote_price wpsc_shipping_quote_price_<?php echo wpsc_shipping_quote_html_id(); ?>' style='text-align:center;'>
993
                           <label for='<?php echo wpsc_shipping_quote_html_id(); ?>'><?php echo wpsc_shipping_quote_value(); ?></label>
994
                        </td>
995
                        <td class='wpsc_shipping_quote_radio wpsc_shipping_quote_radio_<?php echo wpsc_shipping_quote_html_id(); ?>' style='text-align:center;'>
996
                           <?php if(wpsc_have_morethanone_shipping_methods_and_quotes()): ?>
997
                              <input type='radio' id='<?php echo wpsc_shipping_quote_html_id(); ?>' <?php echo wpsc_shipping_quote_selected_state(); ?>  onclick='switchmethod("<?php echo wpsc_shipping_quote_name(); ?>", "<?php echo wpsc_shipping_method_internal_name(); ?>")' value='<?php echo wpsc_shipping_quote_value(true); ?>' name='shipping_method' />
998
                           <?php else: ?>
999
                              <input <?php echo wpsc_shipping_quote_selected_state(); ?> disabled='disabled' type='radio' id='<?php echo wpsc_shipping_quote_html_id(); ?>'  value='<?php echo wpsc_shipping_quote_value(true); ?>' name='shipping_method' />
1000
                                 <?php wpsc_update_shipping_single_method(); ?>
1001
                           <?php endif; ?>
1002
                        </td>
1003
                     </tr>
1004
                  <?php endwhile; ?>
1005
            <?php endwhile; ?>
1006
         <?php endif; ?>
1007
1008
         <?php wpsc_update_shipping_multiple_methods(); ?>
1009
1010
		<?php
1011
1012
	}
1013
	exit;
1014
1015
}
1016
1017
function _wpsc_get_alternate_html( $cart_messages ) {
1018
	// These shenanigans are necessary for two reasons.
1019
	// 1) Some hook into POST, some GET, some REQUEST. They check for the conditional params below.
1020
	// 2) Most functions properly die() - that means that our output buffer stops there and won't continue on for our purposes.
1021
	// If there is a better way to get that output without dying, I'm all ears.  A nice slow HTTP request for now.
1022
1023
	$cookies = array();
1024
	foreach ( $_COOKIE as $name => $value ) {
0 ignored issues
show
introduced by
Due to using Batcache, server side based client related logic will not work, use JS instead.
Loading history...
1025
		if ( 'PHPSESSID' == $name )
1026
			continue;
1027
1028
		$cookies[] = new WP_Http_Cookie( array( 'name' => $name, 'value' => $value ) );
1029
	}
1030
1031
	wpsc_serialize_shopping_cart();
1032
1033
	$javascript = wp_remote_retrieve_body(
1034
		wp_safe_remote_post(
1035
			esc_url_raw( add_query_arg( array( 'wpsc_action' => 'wpsc_get_alternate_html', 'ajax' => 'true', 'wpsc_ajax_action' => 'add_to_cart' ), home_url() ),
1036
			array(
1037
				'body' =>
1038
					array(
1039
						'cart_messages' => $cart_messages, 'ajax' => 'true', 'wpsc_ajax_action' => 'add_to_cart', 'product_id' => empty( $_REQUEST['product_id'] ) ? '' : $_REQUEST['product_id'], '_wpsc_compat_ajax' => true
1040
					),
1041
1042
				'cookies'    => $cookies,
1043
				'user-agent' => $_SERVER['HTTP_USER_AGENT']
0 ignored issues
show
introduced by
Due to using Batcache, server side based client related logic will not work, use JS instead.
Loading history...
1044
			)
1045
		) )
1046
	);
1047
	return $javascript;
1048
}
1049
1050
/**
1051
 * Returns the jQuery that is likely included in calls to this action.  For back compat only, will be deprecated soon.
1052
 * Couldn't think up a better way to return this output, which most often will end in die(), without die()ing early ourselves.
1053
 *
1054
 * @param  array  $cart_messages [description]
0 ignored issues
show
Bug introduced by
There is no parameter named $cart_messages. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
1055
 */
1056
function _wpsc_ajax_return_alternate_html() {
1057
	$cart_messages = empty( $_POST['cart_messages'] ) ? array() : (array) $_POST['cart_messages'];
1058
	do_action( 'wpsc_alternate_cart_html', $cart_messages );
1059
	die;
1060
}
1061
1062
if ( isset( $_REQUEST['wpsc_action'] ) && 'wpsc_get_alternate_html' == $_REQUEST['wpsc_action'] )
1063
	add_action( 'init', '_wpsc_ajax_return_alternate_html' );
1064
1065
/**
1066
 * Returns the Cart Widget
1067
 *
1068
 * @param  boolean $die          Whether or not to return the output (for new JSON requests) or to die() on the old $output / action.
1069
 * @param  array   $cart_message An array of cart messages to be optionally passed.  Primarily passed via wpsc_add_to_cart().
0 ignored issues
show
Documentation introduced by
There is no parameter named $cart_message. Did you maybe mean $cart_messages?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function. It has, however, found a similar but not annotated parameter which might be a good fit.

Consider the following example. The parameter $ireland is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $ireland
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was changed, but the annotation was not.

Loading history...
1070
 *
1071
 * @since 3.8.11
1072
 * @return mixed                 Returns an array of output data, alternatively
0 ignored issues
show
Documentation introduced by
Consider making the return type a bit more specific; maybe use null|array.

This check looks for the generic type array as a return type and suggests a more specific type. This type is inferred from the actual code.

Loading history...
1073
 */
1074
function _wpsc_ajax_get_cart( $die = true, $cart_messages = array() ) {
1075
	$return = array();
1076
1077
	if ( defined( 'DOING_AJAX' ) && DOING_AJAX ) {
1078
		ob_start();
1079
		include_once( wpsc_get_template_file_path( 'wpsc-cart_widget.php' ) );
1080
1081
		$output = ob_get_contents();
1082
		ob_end_clean();
1083
		$output = str_replace( array( '\n', '\r' ), '', $output );
1084
1085
		$return['widget_output']   = $output;
1086
		$return['core_images_url'] = WPSC_CORE_IMAGES_URL;
1087
1088
		if ( 1 == get_option( 'show_sliding_cart' ) || empty( $cart_messages ) ) {
1089
			if ( wpsc_cart_item_count()  ) {
1090
				$_SESSION['slider_state']     = 1;
0 ignored issues
show
introduced by
Usage of $_SESSION variable is prohibited.
Loading history...
1091
				$return['sliding_cart_state'] = 'show';
1092
			} else {
1093
				$_SESSION['slider_state']     = 0;
0 ignored issues
show
introduced by
Usage of $_SESSION variable is prohibited.
Loading history...
1094
				$return['sliding_cart_state'] = 'hide';
1095
			}
1096
		}
1097
1098
		$action_output = '';
1099
		if ( has_action( 'wpsc_alternate_cart_html' ) && empty( $_REQUEST['_wpsc_compat_ajax'] ) ) {
1100
			//Deprecated action. Do not use.  We now have a custom JS event called 'wpsc_fancy_notification'. There is access to the complete $json_response object.
1101
			ob_start();
1102
1103
			echo _wpsc_get_alternate_html( $cart_messages );
1104
			$action_output = ob_get_contents();
1105
			$output = '';
1106
			ob_end_clean();
1107
		}
1108
1109
		if ( ! empty( $action_output ) ) {
1110
			_wpsc_doing_it_wrong( 'wpsc_alternate_cart_html', __( 'As of WPeC 3.8.11, it is improper to hook into "wpsc_alternate_cart_html" to output javascript.  We now have a custom javascript event called "wpsc_fancy_notification" you can hook into.', 'wp-e-commerce' ), '3.8.11' );
1111
			$return['wpsc_alternate_cart_html'] = $action_output;
1112
		}
1113
	}
1114
1115
	if ( $die ) {
1116
		echo $output . $action_output;
0 ignored issues
show
Bug introduced by
The variable $output does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
Bug introduced by
The variable $action_output does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
1117
		die();
1118
	} else {
1119
		return $return;
1120
	}
1121
}
1122
1123
1124
/**
1125
 * Update the customer mata values that are passed to the application from the checkout form POST
1126
 *
1127
 * With the submit checkout we should get an array of all the checkout values.  These values should already
1128
 * be stored as customer meta, bet there are cases where the submit processing may arrive before or in parallel
1129
 * with the request to update meta.  There is also value in cehcking to be sure the meta stored is what is coming
1130
 * with the POST as it preserves non-js compatibility and being able to use the submit action as an API
1131
 *
1132
 * @since  3.8.14.1
1133
 *
1134
 * @access private
1135
 *
1136
 * @param  array $checkout_post_data
1137
 *
1138
 * @return none
1139
 */
1140
function _wpsc_checkout_customer_meta_update( $checkout_post_data ) {
1141
	global $wpdb;
1142
1143
	if ( empty ( $checkout_post_data ) || ! is_array( $checkout_post_data ) ) {
0 ignored issues
show
Coding Style introduced by
Space before opening parenthesis of function call prohibited
Loading history...
1144
		return;
1145
	}
1146
1147
	$id = wpsc_get_current_customer_id();
1148
1149
	$form_sql  = 'SELECT * FROM `' . WPSC_TABLE_CHECKOUT_FORMS . '` WHERE `active` = "1" ORDER BY `checkout_set`, `checkout_order`;';
1150
	$form_data = $wpdb->get_results( $form_sql, ARRAY_A );
1151
1152
	foreach ( $form_data as $index => $form_field ) {
1153
		if (  isset( $checkout_post_data[$form_field['id']] ) ) {
1154
1155
			$meta_key   = $form_field['unique_name'];
1156
			$meta_value = $checkout_post_data[$form_field['id']];
1157
1158
			switch ( $form_field['type'] ) {
1159
				case 'delivery_country':
1160
					if ( is_array( $meta_value ) ) {
1161
1162
						if ( isset( $meta_value[0] ) ) {
1163
							wpsc_update_visitor_meta( $id, 'shippingcountry', $meta_value[0] );
1164
						}
1165
1166
						if ( isset( $meta_value[1] ) ) {
1167
							wpsc_update_visitor_meta( $id, 'shippingregion', $meta_value[1] );
1168
						}
1169
					} else {
1170
						// array had only country, update the country
1171
						wpsc_update_visitor_meta( $id, 'shippingcountry', $meta_value );
1172
					}
1173
1174
					break;
1175
1176
				case 'country':
1177
					if ( is_array( $meta_value ) && count( $meta_value ) == 2 ) {
1178
						wpsc_update_visitor_meta( $id, 'billingcountry', $meta_value[0] );
1179
						wpsc_update_visitor_meta( $id, 'billingregion', $meta_value[1] );
1180
					} else {
1181
						if ( is_array( $meta_value ) ) {
1182
							$meta_value = $meta_value[0];
1183
						}
1184
1185
						wpsc_update_visitor_meta( $id, 'billingcountry', $meta_value );
1186
					}
1187
1188
					break;
1189
1190
				default:
1191
					wpsc_update_visitor_meta( $id, $meta_key, $meta_value );
1192
					break;
1193
			}
1194
		}
1195
	}
1196
}
1197
1198
function wpsc_save_user_profile() {
1199
	if ( isset( $_POST['collected_data'] ) && is_array( $_POST['collected_data'] ) ) {
1200
		_wpsc_checkout_customer_meta_update( $_POST['collected_data'] );
1201
	}
1202
}
1203