Completed
Push — master ( 1d6059...ca99f8 )
by Justin
17:57 queued 10:34
created

ajax.php ➔ add_to_cart_shortcode()   A

Complexity

Conditions 4
Paths 3

Size

Total Lines 13
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 4
eloc 9
c 1
b 0
f 0
nc 3
nop 1
dl 0
loc 13
rs 9.2
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 = apply_filters( 'wpsc_add_to_cart_json_response', $json_response + $output );
187
188
		die( json_encode( $json_response ) );
189
	}
190
}
191
192
function wpsc_get_cart() {
193
	_wpsc_ajax_get_cart();
194
}
195
196
/* 19-02-09
197
 * add cart button function used for php template tags and shortcodes
198
 */
199
200
function wpsc_add_to_cart_button( $product_id, $return = false ) {
201
	global $wpdb,$wpsc_variations;
202
	$output = '';
203
	if ( $product_id > 0 ) {
204
		// grab the variation form fields here
205
		$wpsc_variations = new wpsc_variations( $product_id );
206
		if ( $return )
207
			ob_start();
208
		?>
209
			<div class='wpsc-add-to-cart-button'>
210
				<form class='wpsc-add-to-cart-button-form' id='product_<?php echo esc_attr( $product_id ) ?>' action='' method='post'>
211
					<?php do_action( 'wpsc_add_to_cart_button_form_begin', $product_id ); ?>
212
					<div class='wpsc_variation_forms'>
213
						<?php while ( wpsc_have_variation_groups() ) : wpsc_the_variation_group(); ?>
214
							<p>
215
								<label for='<?php echo wpsc_vargrp_form_id(); ?>'><?php echo esc_html( wpsc_the_vargrp_name() ) ?>:</label>
216
								<select class='wpsc_select_variation' name='variation[<?php echo wpsc_vargrp_id(); ?>]' id='<?php echo wpsc_vargrp_form_id(); ?>'>
217
									<?php while ( wpsc_have_variations() ): wpsc_the_variation(); ?>
218
										<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>
219
									<?php endwhile; ?>
220
								</select>
221
							</p>
222
						<?php endwhile; ?>
223
					</div>
224
					<input type='hidden' name='wpsc_ajax_action' value='add_to_cart' />
225
					<input type='hidden' name='product_id' value='<?php echo $product_id; ?>' />
226
					<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' ); ?>'  />
227
					<?php do_action( 'wpsc_add_to_cart_button_form_end', $product_id ); ?>
228
				</form>
229
			</div>
230
		<?php
231
232
		if ( $return ) {
233
			return ob_get_clean();
234
		}
235
	}
236
}
237
238
/**
239
 * Add to cart shortcode function used for shortcodes calls the function in
240
 * product_display_functions.php
241
 *
242
 * @since  19-02-2009
243
 *
244
 * Note: Really old legacy shortcode support for add to cart buttons.
245
 * This isn't a proper WordPress shortcode!
246
 */
247
function add_to_cart_shortcode( $content = '' ) {
248
	if ( ! in_the_loop() )
249
		return $content;
250
251
	if ( preg_match_all( "/\[add_to_cart=([\d]+)\]/", $content, $matches ) ) {
252
		foreach ( $matches[1] as $key => $product_id ) {
253
			$original_string = $matches[0][$key];
254
			$output = wpsc_add_to_cart_button( $product_id, true );
255
			$content = str_replace( $original_string, $output, $content );
256
		}
257
	}
258
	return $content;
259
}
260
261
/**
262
 * empty cart function, used through ajax and in normal page loading.
263
 * No parameters, returns nothing
264
 */
265
function wpsc_empty_cart() {
266
	global $wpsc_cart;
267
	$wpsc_cart->empty_cart( false );
268
269
	if ( defined( 'DOING_AJAX' ) && DOING_AJAX ) {
270
		$output = apply_filters( 'wpsc_empty_cart_response', _wpsc_ajax_get_cart( false ) );
271
		die( json_encode( $output ) );
272
	}
273
}
274
275
/**
276
 * update quantity function, used through ajax and in normal page loading.
277
 * No parameters, returns nothing
278
 */
279
function wpsc_update_item_quantity() {
280
	global $wpsc_cart;
281
282
	if ( is_numeric( $_POST['key'] ) ) {
283
		$key = (int)$_POST['key'];
284
285
		$quantity = isset( $_POST['wpsc_quantity_update'] ) ? $_POST['wpsc_quantity_update'] : '';
286
287
		if ( isset( $_POST['quantity'] ) )
288
			$quantity = $_POST['quantity'];
289
290
		if ( $quantity > 0 ) {
291
			// if the quantity is greater than 0, update the item;
292
			$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...
293
			$wpsc_cart->edit_item( $key, $parameters );
294
		} else {
295
			// if the quantity is 0, remove the item.
296
			$wpsc_cart->remove_item( $key );
297
		}
298
299
		$coupon = wpsc_get_customer_meta( 'coupon' );
300
		if ( $coupon ) {
301
			wpsc_coupon_price( $coupon );
302
		}
303
	}
304
	$die = ! ( ( isset( $_REQUEST['wpsc_ajax_action'] ) && 'true' == $_REQUEST['wpsc_ajax_action'] ) || ( ! defined( 'DOING_AJAX' ) || ! DOING_AJAX ) );
305
	_wpsc_ajax_get_cart( $die );
306
}
307
308
309
function wpsc_update_product_rating() {
310
	global $wpdb;
311
	$nowtime = time();
312
	$product_id = absint( $_POST['product_id'] );
313
	$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...
314
	$rating = absint( $_POST['product_rating'] );
315
316
	$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...
317
318
	if ( is_numeric( $cookie_data[0] ) && ($cookie_data[0] > 0) ) {
319
		$vote_id = absint( $cookie_data[0] );
320
		$wpdb->update( WPSC_TABLE_PRODUCT_RATING, array(
321
		'rated' => $rating
322
		), array( 'id' => $vote_id ) );
323
	} else {
324
		$wpdb->insert( WPSC_TABLE_PRODUCT_RATING, array(
325
		'ipnum' => $ip_number,
326
		'productid' => $product_id,
327
		'rated' => $rating,
328
		'time' => $nowtime
329
		) );
330
		$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 );
331
		$vote_id = $data[0]['id'];
332
		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...
333
	}
334
	if ( $_POST['ajax'] == 'true' ) {
335
336
		exit();
337
	}
338
}
339
340
/**
341
 * update_shipping_price function, used through ajax and in normal page loading.
342
 * No parameters, returns nothing
343
 */
344
function wpsc_update_shipping_price() {
345
	global $wpsc_cart;
346
347
	$quote_shipping_method = $_POST['method'];
348
	$quote_shipping_option = str_replace( array( '®', '™' ), array( '&reg;', '&trade;' ), $_POST['option'] );
349
350
    if ( ! empty( $quote_shipping_option ) && ! empty( $quote_shipping_method ) ) {
351
        $wpsc_cart->update_shipping( $quote_shipping_method, $quote_shipping_option );
352
    }
353
354
    if ( defined( 'DOING_AJAX' ) && DOING_AJAX ) {
355
356
    	$response = apply_filters( 'wpsc_update_shipping_price_response', array(
357
				'shipping'   => wpsc_cart_shipping(),
358
				'coupon'     => wpsc_coupon_amount(),
359
				'cart_total' => wpsc_cart_total(),
360
				'tax'        => wpsc_cart_tax()
361
    		),
362
    		$quote_shipping_method,
363
    		$quote_shipping_option
364
    	);
365
 		echo json_encode( $response );
366
    	exit();
367
    }
368
369
}
370
371
/**
372
 * update_shipping_price function, used through ajax and in normal page loading.
373
 * No parameters, returns nothing
374
 */
375
function wpsc_get_rating_count() {
376
	global $wpdb, $wpsc_cart;
377
	$prodid = $_POST['product_id'];
378
	$count = $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(*) AS `count` FROM `" . WPSC_TABLE_PRODUCT_RATING . "` WHERE `productid` = %d", $prodid ) );
379
	echo $count . "," . absint( $prodid );
380
	exit();
381
}
382
383
/**
384
 * update_product_page_price function, used through ajax with variations
385
 * No parameters, returns nothing
386
 */
387
function wpsc_update_product_price() {
388
	if ( empty( $_POST['product_id'] ) || ! is_numeric( $_POST['product_id'] ) ) {
389
		return;
390
	}
391
392
	$from = '';
393
	$change_price = true;
394
	$product_id = (int) $_POST['product_id'];
395
	$variations = array();
396
	$response   = array(
397
		'product_id'      => $product_id,
398
		'variation_found' => false,
399
	);
400
401
	if ( ! empty( $_POST['variation'] ) ) {
402
		foreach ( $_POST['variation'] as $variation ) {
403
			if ( is_numeric( $variation ) ) {
404
				$variations[] = (int)$variation;
405
			}
406
		}
407
408
		do_action( 'wpsc_update_variation_product', $product_id, $variations );
409
410
		$stock = wpsc_check_variation_stock_availability( $product_id, $variations );
411
412
		if ( $stock !== false ) {
413
			$response['variation_found'] = true;
414
			if ( $stock === 0 ) {
415
				$response += array(
416
					'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...
417
					'variation_msg'   => __( 'Variation not in stock', 'wp-e-commerce' ),
418
					'stock_available' => false,
419
				);
420
			} else {
421
				$response += array(
422
					'variation_msg'   => __( 'Product in stock', 'wp-e-commerce' ),
423
					'stock_available' => true,
424
				);
425
			}
426
427
			if ( $change_price ) {
428
				$old_price           = wpsc_calculate_price( $product_id, $variations, false );
429
				$you_save_amount     = wpsc_you_save( array( 'product_id' => $product_id, 'type' => 'amount', 'variations' => $variations ) );
430
				$you_save_percentage = wpsc_you_save( array( 'product_id' => $product_id, 'variations' => $variations ) );
431
432
				$price = wpsc_calculate_price( $product_id, $variations, true );
433
434
				$response += array(
435
					'old_price'         => wpsc_currency_display( $old_price, array( 'display_as_html' => false ) ),
436
					'numeric_old_price' => (float) $old_price,
437
					'you_save'          => wpsc_currency_display( $you_save_amount, array( 'display_as_html' => false ) ) . "! (" . $you_save_percentage . "%)",
438
					'price'             => $from . wpsc_currency_display( $price, array( 'display_as_html' => false ) ),
439
					'numeric_price'     => (float) $price,
440
				);
441
			}
442
		}
443
	}
444
445
	$response = apply_filters( 'wpsc_update_product_price', $response, $product_id );
446
447
	echo json_encode( $response );
448
	exit();
449
}
450
451
/**
452
 * update location function, used through ajax and in normal page loading.
453
 * No parameters, returns nothing
454
 */
455
function wpsc_update_location() {
456
	global $wpsc_cart;
457
458
	/*
459
	 * Checkout page shipping calculator MAY provide a zip code using the identifier from prior
460
	 * releases.  Let's check for that.
461
	 */
462
	if ( isset( $_POST['zipcode'] ) ) {
463
		wpsc_update_customer_meta( 'shippingpostcode', sanitize_text_field( $_POST['zipcode'] ) );
464
	}
465
466
	/*
467
	 * Checkout page shipping calculator MAY provide a country code using the identifier from prior
468
	 * releases.  Let's check for that.
469
	 */
470
	if ( isset( $_POST['country'] ) ) {
471
		$wpsc_country = new WPSC_Country( $_POST['country'] );
472
		wpsc_update_customer_meta( 'shippingcountry', $wpsc_country->get_isocode() );
473
	}
474
475
	/*
476
	 * WPeC's totally awesome checkout page shipping calculator has a submit button that will send
477
	 * some of the shipping data to us in an AJAX request.  The format of the data as of version
478
	 * 3.8.14.1 uses the 'collected_data' array format just like in checkout. We should process
479
	 * this array in case it has some updates to the user meta (checkout information) that haven't been
480
	 * recorded at the time the calculate button was clicked.  If the country or zip code is set using the
481
	 * legacy 'country' or 'zip' code $_POST values they will be overwritten if they are also included
482
	 * in the collected_data $_POST value.
483
	 */
484
	if ( isset( $_POST['collected_data'] ) && is_array( $_POST['collected_data'] ) ) {
485
		_wpsc_checkout_customer_meta_update( $_POST['collected_data'] );
486
	}
487
488
	$wpsc_cart->update_location();
489
	$wpsc_cart->get_shipping_method();
490
	$wpsc_cart->get_shipping_option();
491
492
	if ( $wpsc_cart->selected_shipping_method != '' ) {
493
		$wpsc_cart->update_shipping( $wpsc_cart->selected_shipping_method, $wpsc_cart->selected_shipping_option );
494
	}
495
496
	if ( defined( 'DOING_AJAX' ) && DOING_AJAX && isset( $_REQUEST['action'] ) && 'update_location' == $_REQUEST['action'] )
497
		exit;
498
}
499
500
function wpsc_cart_html_page() {
501
	require_once(WPSC_FILE_PATH . '/wpsc-includes/shopping_cart_container.php' );
502
	exit();
503
}
504
505
/**
506
 * Populate Also Bought List
507
 * Runs on checking out and populates the also bought list.
508
 */
509
function wpsc_populate_also_bought_list() {
510
	global $wpdb, $wpsc_cart, $wpsc_coupons;
511
512
	$new_also_bought_data = array();
513
	foreach ( $wpsc_cart->cart_items as $outer_cart_item ) {
514
		$new_also_bought_data[$outer_cart_item->product_id] = array();
515
		foreach ( $wpsc_cart->cart_items as $inner_cart_item ) {
516
			if ( $outer_cart_item->product_id != $inner_cart_item->product_id ) {
517
				$new_also_bought_data[$outer_cart_item->product_id][$inner_cart_item->product_id] = $inner_cart_item->quantity;
518
			} else {
519
				continue;
520
			}
521
		}
522
	}
523
524
	$insert_statement_parts = array();
525
	foreach ( $new_also_bought_data as $new_also_bought_id => $new_also_bought_row ) {
526
		$new_other_ids = array_keys( $new_also_bought_row );
527
		$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 );
528
		$altered_new_also_bought_row = $new_also_bought_row;
529
530
		foreach ( (array)$also_bought_data as $also_bought_row ) {
531
			$quantity = $new_also_bought_row[$also_bought_row['associated_product']] + $also_bought_row['quantity'];
532
533
			unset( $altered_new_also_bought_row[$also_bought_row['associated_product']] );
534
			$wpdb->update(
535
				WPSC_TABLE_ALSO_BOUGHT,
536
				array(
537
				    'quantity' => $quantity
538
				),
539
				array(
540
				    'id' => $also_bought_row['id']
541
				),
542
				'%d',
543
				'%d'
544
			);
545
	    }
546
547
		if ( count( $altered_new_also_bought_row ) > 0 ) {
548
			foreach ( $altered_new_also_bought_row as $associated_product => $quantity ) {
549
				$insert_statement_parts[] = "(" . absint( esc_sql( $new_also_bought_id ) ) . "," . absint( esc_sql( $associated_product ) ) . "," . absint( esc_sql( $quantity ) ) . ")";
550
			}
551
		}
552
	}
553
554
	if ( count( $insert_statement_parts ) > 0 ) {
555
		$insert_statement = "INSERT INTO `" . WPSC_TABLE_ALSO_BOUGHT . "` (`selected_product`, `associated_product`, `quantity`) VALUES " . implode( ",\n ", $insert_statement_parts );
556
		$wpdb->query( $insert_statement );
557
	}
558
}
559
560
/**
561
 * submit checkout function, used through ajax and in normal page loading.
562
 * No parameters, returns nothing
563
 */
564
function wpsc_submit_checkout( $collected_data = true ) {
565
	global $wpdb, $wpsc_cart, $user_ID, $nzshpcrt_gateways, $wpsc_shipping_modules, $wpsc_gateways;
566
567
	if ( $collected_data && isset( $_POST['collected_data'] ) && is_array( $_POST['collected_data'] ) ) {
568
		_wpsc_checkout_customer_meta_update( $_POST['collected_data'] );
569
	}
570
571
	// initialize our checkout status variable, we start be assuming
572
	// checkout is falid, until we find a reason otherwise
573
	$is_valid           = true;
574
	$num_items          = 0;
575
	$use_shipping       = 0;
576
	$disregard_shipping = 0;
577
578
	do_action( 'wpsc_before_submit_checkout', $collected_data );
579
580
	$error_messages = wpsc_get_customer_meta( 'checkout_misc_error_messages' );
581
582
	if ( ! is_array( $error_messages ) ) {
583
		$error_messages = array();
584
	}
585
586
	$wpsc_checkout = new wpsc_checkout();
587
588
	$selected_gateways = get_option( 'custom_gateway_options' );
589
	$submitted_gateway = isset( $_POST['custom_gateway'] ) ? $_POST['custom_gateway'] : '';
590
591
	if ( $collected_data ) {
592
		$form_validity = $wpsc_checkout->validate_forms();
593
		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...
594
595
		if ( wpsc_has_tnc() && ( ! isset( $_POST['agree'] ) || $_POST['agree'] != 'yes' ) ) {
596
			$error_messages[] = __( 'Please agree to the terms and conditions, otherwise we cannot process your order.', 'wp-e-commerce' );
597
			$is_valid = false;
598
		}
599
	} else {
600
		$is_valid = true;
601
		$error_messages = array();
602
	}
603
604
	if ( wpsc_uses_shipping() ) {
605
		$wpsc_country = new WPSC_Country( wpsc_get_customer_meta( 'shippingcountry' ) );
606
		$country_id   = $wpsc_country->get_id();
607
		$country_name = $wpsc_country->get_name();
608
609
		foreach ( $wpsc_cart->cart_items as $cartitem ) {
610
611
			if ( ! empty( $cartitem->meta[0]['no_shipping'] ) ) {
612
				continue;
613
			}
614
615
			$category_ids = $cartitem->category_id_list;
616
617
			foreach ( (array) $category_ids as $catid ) {
618
				if ( is_array( $catid ) ) {
619
					$countries = wpsc_get_meta( $catid[0], 'target_market', 'wpsc_category' );
620
				} else {
621
					$countries = wpsc_get_meta( $catid, 'target_market', 'wpsc_category' );
622
				}
623
624
				if ( ! empty( $countries ) && ! in_array( $country_id, (array) $countries ) ) {
625
					$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 );
626
					wpsc_update_customer_meta( 'category_shipping_conflict', $errormessage );
627
					$is_valid = false;
628
				}
629
			}
630
631
			//count number of items, and number of items using shipping
632
			$num_items++;
633
634
			if ( $cartitem->uses_shipping != 1 ) {
635
				$disregard_shipping++;
636
			} else {
637
				$use_shipping++;
638
			}
639
		}
640
	}
641
642
	// check to see if the current gateway is in the list of available gateways
643
	if ( array_search( $submitted_gateway, $selected_gateways ) !== false || wpsc_is_free_cart() ) {
644
		wpsc_update_customer_meta( 'selected_gateway', $submitted_gateway );
645
	} else {
646
		$is_valid = false;
647
	}
648
649
	if ( $collected_data ) {
650
651
		// Test for required shipping information
652
		if ( wpsc_core_shipping_enabled() && ( $num_items != $disregard_shipping ) ) {
653
			// for shipping to work we need a method, option and a quote, unless we have free shipping.
654
655
			$shipping_discount_value  = get_option( 'shipping_discount_value' );
656
			$is_free_shipping_enabled = get_option( 'shipping_discount' );
657
			$subtotal                 = $wpsc_cart->calculate_subtotal();
658
659
			$has_free_shipping = $is_free_shipping_enabled && $shipping_discount_value > 0 && $shipping_discount_value <= $subtotal;
660
661
			if ( ! $has_free_shipping ) {
662
				if ( ! $wpsc_cart->shipping_method_selected() || ! $wpsc_cart->shipping_quote_selected() ) {
663
					$error_messages[] = __( 'Please select one of the available shipping options, then we can process your order.', 'wp-e-commerce' );
664
					$is_valid = false;
665
				}
666
			}
667
668
			// if we don't have a valid zip code ( the function also checks if we need it ) we have an error
669
			if ( ! wpsc_have_valid_shipping_zipcode() ) {
670
					wpsc_update_customer_meta( 'category_shipping_conflict', __( 'Please enter a Zipcode and click calculate to proceed', 'wp-e-commerce' ) );
671
					$is_valid = false;
672
			}
673
		}
674
	}
675
676
	wpsc_update_customer_meta( 'checkout_misc_error_messages', $error_messages );
677
678
	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...
679
		wpsc_delete_customer_meta( 'category_shipping_conflict' );
680
		// check that the submitted gateway is in the list of selected ones
681
		$sessionid = (mt_rand( 100, 999 ) . time());
682
		wpsc_update_customer_meta( 'checkout_session_id', $sessionid );
683
		$subtotal = $wpsc_cart->calculate_subtotal();
684
		if ( $wpsc_cart->has_total_shipping_discount() == false )
685
			$base_shipping = $wpsc_cart->calculate_base_shipping();
686
		else
687
			$base_shipping = 0;
688
689
		$delivery_country = $wpsc_cart->delivery_country;
690
		$delivery_region = $wpsc_cart->delivery_region;
691
692
		if ( wpsc_uses_shipping() ) {
693
			$shipping_method = $wpsc_cart->selected_shipping_method;
694
			$shipping_option = $wpsc_cart->selected_shipping_option;
695
		} else {
696
			$shipping_method = '';
697
			$shipping_option = '';
698
		}
699
		if ( isset( $_POST['how_find_us'] ) )
700
			$find_us = $_POST['how_find_us'];
701
		else
702
			$find_us = '';
703
704
		//keep track of tax if taxes are exclusive
705
		$wpec_taxes_controller = new wpec_taxes_controller();
706
		if ( ! $wpec_taxes_controller->wpec_taxes_isincluded() ) {
707
			$tax = $wpsc_cart->calculate_total_tax();
708
			$tax_percentage = $wpsc_cart->tax_percentage;
709
		} else {
710
			$tax = 0.00;
711
			$tax_percentage = 0.00;
712
		}
713
714
		$total = $wpsc_cart->calculate_total_price();
715
716
		$args = array(
717
			'totalprice'       => $total,
718
			'statusno'         => '0',
719
			'sessionid'        => $sessionid,
720
			'user_ID'          => (int) $user_ID,
721
			'date'             => time(),
722
			'gateway'          => $submitted_gateway,
723
			'billing_country'  => $wpsc_cart->selected_country,
724
			'shipping_country' => $delivery_country,
725
			'billing_region'   => $wpsc_cart->selected_region,
726
			'shipping_region'  => $delivery_region,
727
			'base_shipping'    => $base_shipping,
728
			'shipping_method'  => $shipping_method,
729
			'shipping_option'  => $shipping_option,
730
			'plugin_version'   => WPSC_VERSION,
731
			'discount_value'   => $wpsc_cart->coupons_amount,
732
			'discount_data'    => $wpsc_cart->coupons_name,
733
			'find_us'          => $find_us,
734
			'wpec_taxes_total' => $tax,
735
			'wpec_taxes_rate'  => $tax_percentage,
736
		);
737
738
		$purchase_log = new WPSC_Purchase_Log( $args );
739
		$purchase_log->save();
740
		$purchase_log_id = $purchase_log->get( 'id' );
741
742
		//Check to ensure log row was inserted successfully
743
		if(is_null($purchase_log_id)) {
744
			$error_messages[] = __( 'A database error occurred while processing your request.', 'wp-e-commerce' );
745
			wpsc_update_customer_meta( 'checkout_misc_error_messages', $error_messages );
746
			return;
747
		}
748
749
		if ( $collected_data ) {
750
			$wpsc_checkout->save_forms_to_db( $purchase_log_id );
751
		}
752
753
		$wpsc_cart->save_to_db( $purchase_log_id );
754
		$wpsc_cart->submit_stock_claims( $purchase_log_id );
755
756
		if ( ! isset( $our_user_id ) && isset( $user_ID ) ) {
757
			$our_user_id = $user_ID;
758
		}
759
760
		$wpsc_cart->log_id = $purchase_log_id;
761
		do_action( 'wpsc_submit_checkout', array( 'purchase_log_id' => $purchase_log_id, 'our_user_id' => $our_user_id ) );
762
		do_action( 'wpsc_submit_checkout_gateway', $submitted_gateway, $purchase_log );
763
	}
764
}
765
766
/**
767
 * wpsc_change_tax function, used through ajax and in normal page loading.
768
 * No parameters, returns nothing
769
 */
770
function wpsc_change_tax() {
771
	global $wpdb, $wpsc_cart;
772
0 ignored issues
show
Coding Style introduced by
Functions must not contain multiple empty lines in a row; found 2 empty lines
Loading history...
773
774
	$form_id = absint( $_POST['form_id'] );
775
776
	$wpsc_selected_country = $wpsc_cart->selected_country;
777
	$wpsc_selected_region  = $wpsc_cart->selected_region;
778
779
	$wpsc_delivery_country = $wpsc_cart->delivery_country;
780
	$wpsc_delivery_region  = $wpsc_cart->delivery_region;
781
782
	$previous_country = wpsc_get_customer_meta( 'billingcountry' );
783
784
	global $wpdb, $user_ID, $wpsc_customer_checkout_details;
785
786
	if ( isset( $_POST['billing_country'] ) ) {
787
		$wpsc_selected_country = sanitize_text_field( $_POST['billing_country'] );
788
		wpsc_update_customer_meta( 'billingcountry', $wpsc_selected_country );
789
	}
790
791
	if ( isset( $_POST['billing_region'] ) ) {
792
		$wpsc_selected_region = absint( $_POST['billing_region'] );
793
		wpsc_update_customer_meta( 'billingregion', $wpsc_selected_region );
794
	}
795
796
	$check_country_code = WPSC_Countries::get_country_id_by_region_id( wpsc_get_customer_meta( 'billing_region' ) );
797
798
	if ( wpsc_get_customer_meta( 'billingcountry' ) != $check_country_code ) {
799
		$wpsc_selected_region = null;
800
	}
801
802
	if ( isset( $_POST['shipping_country'] ) ) {
803
		$wpsc_delivery_country = sanitize_text_field( $_POST['shipping_country'] );
804
		wpsc_update_customer_meta( 'shippingcountry', $wpsc_delivery_country );
805
	}
806
	if ( isset( $_POST['shipping_region'] ) ) {
807
		$wpsc_delivery_region = absint( $_POST['shipping_region'] );
808
		wpsc_update_customer_meta( 'shippingregion', $wpsc_delivery_region );
809
	}
810
811
	$check_country_code = WPSC_Countries::get_country_id_by_region_id( $wpsc_delivery_region );
812
	if ( $wpsc_delivery_country != $check_country_code ) {
813
		$wpsc_delivery_region = null;
814
	}
815
816
	$wpsc_cart->update_location();
817
	$wpsc_cart->get_shipping_method();
818
	$wpsc_cart->get_shipping_option();
819
820
	if ( $wpsc_cart->selected_shipping_method != '' ) {
821
		$wpsc_cart->update_shipping( $wpsc_cart->selected_shipping_method, $wpsc_cart->selected_shipping_option );
822
	}
823
824
	$tax         = $wpsc_cart->calculate_total_tax();
825
	$total       = wpsc_cart_total();
826
	$total_input = wpsc_cart_total( false );
827
828
	if ( $wpsc_cart->coupons_amount >= $total_input && ! empty( $wpsc_cart->coupons_amount ) ) {
829
		$total = 0;
830
	}
831
832
	if ( $wpsc_cart->total_price < 0 ) {
833
		$wpsc_cart->coupons_amount += $wpsc_cart->total_price;
834
		$wpsc_cart->total_price     = null;
835
		$wpsc_cart->calculate_total_price();
836
	}
837
838
	$delivery_country = wpsc_get_customer_meta( 'shipping_country' );
839
	$output           = _wpsc_ajax_get_cart( false );
840
	$output           = $output['widget_output'];
841
842
	$json_response = array();
843
844
	global $wpsc_checkout;
845
	if ( empty( $wpsc_checkout ) ) {
846
		$wpsc_checkout = new wpsc_checkout();
847
	}
848
849
	$json_response['delivery_country'] = esc_js( $delivery_country );
850
	$json_response['billing_country']  = esc_js( $wpsc_selected_country );
851
	$json_response['widget_output']    = $output;
852
	$json_response['shipping_keys']    = array();
853
	$json_response['cart_shipping']    = wpsc_cart_shipping();
854
	$json_response['form_id']          = $form_id;
855
	$json_response['tax']              = $tax;
856
	$json_response['display_tax']      = wpsc_cart_tax();
857
	$json_response['total']            = $total;
858
	$json_response['total_input']      = $total_input;
859
860
	$json_response['lock_tax']     = get_option( 'lock_tax' );
861
	$json_response['country_name'] = wpsc_get_country( $delivery_country );
862
863
	if ( 'US' == $delivery_country || 'CA' == $delivery_country ) {
864
		$output = wpsc_shipping_region_list( $delivery_country, wpsc_get_customer_meta( 'shipping_region' ) );
865
		$output = str_replace( array( "\n", "\r" ), '', $output );
866
		$json_response['shipping_region_list'] = $output;
867
	}
868
869
	foreach ( $wpsc_cart->cart_items as $key => $cart_item ) {
870
		$json_response['shipping_keys'][ $key ] = wpsc_currency_display( $cart_item->shipping );
871
	}
872
873
	$form_selected_country = null;
874
	$form_selected_region  = null;
875
	$onchange_function     = null;
876
877
	if ( ! empty( $_POST['billing_country'] ) && $_POST['billing_country'] != 'undefined' && ! isset( $_POST['shipping_country'] ) ) {
878
		$form_selected_country = $wpsc_selected_country;
879
		$form_selected_region  = $wpsc_selected_region;
880
		$onchange_function     = 'set_billing_country';
881
	} else if ( ! empty( $_POST['shipping_country'] ) && $_POST['shipping_country'] != 'undefined' && ! isset( $_POST['billing_country'] ) ) {
882
		$form_selected_country = $wpsc_delivery_country;
883
		$form_selected_region  = $wpsc_delivery_region;
884
		$onchange_function     = 'set_shipping_country';
885
	}
886
887
	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...
888
889
		$checkoutfields = 'set_shipping_country' == $onchange_function;
890
		$region_list = wpsc_country_region_list( $form_id, false, $form_selected_country, $form_selected_region, $form_id, $checkoutfields );
891
892
		if ( $region_list != null ) {
893
			$json_response['region_list'] = str_replace( array( "\n", "\r" ), '', $region_list );
894
		}
895
	}
896
897
	echo json_encode( $json_response );
898
	exit();
899
}
900
901
function _wpsc_change_profile_country() {
902
	global $wpdb;
903
904
	$country_field_id = absint( $_REQUEST['form_id'] );
905
	$country          = $_REQUEST['country'];
906
907
	$sql = $wpdb->prepare( 'SELECT unique_name FROM `'.WPSC_TABLE_CHECKOUT_FORMS.'` WHERE `id`= %d', $country_field_id );
908
	$country_field_unique_name = $wpdb->get_var( $sql );
909
910
	$has_regions = wpsc_has_regions( $country );
911
	$response = array( 'has_regions' => $has_regions );
912
913
	$region_unique_name = 'shippingstate';
914
	if ( $country_field_unique_name == 'billingcountry' )
915
		$region_unique_name = 'billingstate';
916
917
	$sql = $wpdb->prepare( 'SELECT id FROM ' . WPSC_TABLE_CHECKOUT_FORMS . ' WHERE unique_name=%s AND active="1"', $region_unique_name );
918
	$response['region_field_id'] = $wpdb->get_var( $sql );
919
920
	if ( $has_regions )
921
		$response['html'] = "<select name='collected_data[" . $country_field_id . "][1]'>" . nzshpcrt_region_list( $country, '' ) . "</select>";
922
923
	echo json_encode( $response );
924
	exit;
925
}
926
927
function wpsc_shipping_same_as_billing(){
928
	wpsc_update_customer_meta( 'shippingSameBilling', sanitize_text_field( $_POST['wpsc_shipping_same_as_billing'] ) );
929
}
930
931
function wpsc_update_shipping_quotes_on_shipping_same_as_billing() {
932
	global $wpsc_cart;
933
934
	wpsc_update_location();
935
936
	if ( get_option( 'do_not_use_shipping' ) )
937
		die( '-1' );
938
939
	if ( ! wpsc_have_shipping_quote() ) {
940
		die( '0' );
941
	}
942
	else {
943
		?>
944
   <tr class="wpsc_shipping_info">
945
            <td colspan="5">
946
               <?php _e( 'Please choose a country below to calculate your shipping costs', 'wp-e-commerce' ); ?>
947
            </td>
948
         </tr>
949
950
         <?php if ( ! wpsc_have_shipping_quote() ) : // No valid shipping quotes ?>
951
            <?php if ( ! wpsc_have_valid_shipping_zipcode() ) : ?>
952
                  <tr class='wpsc_update_location'>
953
                     <td colspan='5' class='shipping_error' >
954
                        <?php _e('Please provide a ZIP code and click Calculate in order to continue.', 'wp-e-commerce'); ?>
955
                     </td>
956
                  </tr>
957
            <?php else: ?>
958
               <tr class='wpsc_update_location_error'>
959
                  <td colspan='5' class='shipping_error' >
960
                     <?php _e('Sorry, online ordering is unavailable for this destination and/or weight. Please double check your destination details.', 'wp-e-commerce'); ?>
961
                  </td>
962
               </tr>
963
            <?php endif; ?>
964
         <?php endif; ?>
965
         <tr class='wpsc_change_country'>
966
            <td colspan='5'>
967
               <form name='change_country' id='change_country' action='' method='post'>
968
                  <?php echo wpsc_shipping_country_list();?>
969
                  <input type='hidden' name='wpsc_update_location' value='true' />
970
                  <input type='submit' name='wpsc_submit_zipcode' value='Calculate' />
971
               </form>
972
            </td>
973
         </tr>
974
975
         <?php if (wpsc_have_morethanone_shipping_quote()) :?>
976
            <?php while (wpsc_have_shipping_methods()) : wpsc_the_shipping_method(); ?>
977
                  <?php    if (!wpsc_have_shipping_quotes()) { continue; } // Don't display shipping method if it doesn't have at least one quote ?>
978
                  <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>
979
                  <?php while (wpsc_have_shipping_quotes()) : wpsc_the_shipping_quote();  ?>
980
                     <tr class='<?php echo wpsc_shipping_quote_html_id(); ?>'>
981
                        <td class='wpsc_shipping_quote_name wpsc_shipping_quote_name_<?php echo wpsc_shipping_quote_html_id(); ?>' colspan='3'>
982
                           <label for='<?php echo wpsc_shipping_quote_html_id(); ?>'><?php echo wpsc_shipping_quote_name(); ?></label>
983
                        </td>
984
                        <td class='wpsc_shipping_quote_price wpsc_shipping_quote_price_<?php echo wpsc_shipping_quote_html_id(); ?>' style='text-align:center;'>
985
                           <label for='<?php echo wpsc_shipping_quote_html_id(); ?>'><?php echo wpsc_shipping_quote_value(); ?></label>
986
                        </td>
987
                        <td class='wpsc_shipping_quote_radio wpsc_shipping_quote_radio_<?php echo wpsc_shipping_quote_html_id(); ?>' style='text-align:center;'>
988
                           <?php if(wpsc_have_morethanone_shipping_methods_and_quotes()): ?>
989
                              <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' />
990
                           <?php else: ?>
991
                              <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' />
992
                                 <?php wpsc_update_shipping_single_method(); ?>
993
                           <?php endif; ?>
994
                        </td>
995
                     </tr>
996
                  <?php endwhile; ?>
997
            <?php endwhile; ?>
998
         <?php endif; ?>
999
1000
         <?php wpsc_update_shipping_multiple_methods(); ?>
1001
1002
		<?php
1003
1004
	}
1005
	exit;
1006
1007
}
1008
1009
function _wpsc_get_alternate_html( $cart_messages ) {
1010
	// These shenanigans are necessary for two reasons.
1011
	// 1) Some hook into POST, some GET, some REQUEST. They check for the conditional params below.
1012
	// 2) Most functions properly die() - that means that our output buffer stops there and won't continue on for our purposes.
1013
	// If there is a better way to get that output without dying, I'm all ears.  A nice slow HTTP request for now.
1014
1015
	$cookies = array();
1016
	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...
1017
		if ( 'PHPSESSID' == $name )
1018
			continue;
1019
1020
		$cookies[] = new WP_Http_Cookie( array( 'name' => $name, 'value' => $value ) );
1021
	}
1022
1023
	wpsc_serialize_shopping_cart();
1024
1025
	$javascript = wp_remote_retrieve_body(
1026
		wp_safe_remote_post(
1027
			esc_url_raw( add_query_arg( array( 'wpsc_action' => 'wpsc_get_alternate_html', 'ajax' => 'true', 'wpsc_ajax_action' => 'add_to_cart' ), home_url() ),
1028
			array(
1029
				'body' =>
1030
					array(
1031
						'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
1032
					),
1033
1034
				'cookies'    => $cookies,
1035
				'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...
1036
			)
1037
		) )
1038
	);
1039
	return $javascript;
1040
}
1041
1042
/**
1043
 * Returns the jQuery that is likely included in calls to this action.  For back compat only, will be deprecated soon.
1044
 * Couldn't think up a better way to return this output, which most often will end in die(), without die()ing early ourselves.
1045
 *
1046
 * @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...
1047
 */
1048
function _wpsc_ajax_return_alternate_html() {
1049
	$cart_messages = empty( $_POST['cart_messages'] ) ? array() : (array) $_POST['cart_messages'];
1050
	do_action( 'wpsc_alternate_cart_html', $cart_messages );
1051
	die;
1052
}
1053
1054
if ( isset( $_REQUEST['wpsc_action'] ) && 'wpsc_get_alternate_html' == $_REQUEST['wpsc_action'] )
1055
	add_action( 'init', '_wpsc_ajax_return_alternate_html' );
1056
1057
/**
1058
 * Returns the Cart Widget
1059
 *
1060
 * @param  boolean $die          Whether or not to return the output (for new JSON requests) or to die() on the old $output / action.
1061
 * @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...
1062
 *
1063
 * @since 3.8.11
1064
 * @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...
1065
 */
1066
function _wpsc_ajax_get_cart( $die = true, $cart_messages = array() ) {
1067
	$return = array();
1068
1069
	if ( defined( 'DOING_AJAX' ) && DOING_AJAX ) {
1070
		ob_start();
1071
		include_once( wpsc_get_template_file_path( 'wpsc-cart_widget.php' ) );
1072
1073
		$output = ob_get_contents();
1074
		ob_end_clean();
1075
		$output = str_replace( array( '\n', '\r' ), '', $output );
1076
1077
		$return['widget_output']   = $output;
1078
		$return['core_images_url'] = WPSC_CORE_IMAGES_URL;
1079
1080
		if ( 1 == get_option( 'show_sliding_cart' ) || empty( $cart_messages ) ) {
1081
			if ( wpsc_cart_item_count()  ) {
1082
				$_SESSION['slider_state']     = 1;
0 ignored issues
show
introduced by
Usage of $_SESSION variable is prohibited.
Loading history...
1083
				$return['sliding_cart_state'] = 'show';
1084
			} else {
1085
				$_SESSION['slider_state']     = 0;
0 ignored issues
show
introduced by
Usage of $_SESSION variable is prohibited.
Loading history...
1086
				$return['sliding_cart_state'] = 'hide';
1087
			}
1088
		}
1089
1090
		$action_output = '';
1091
		if ( has_action( 'wpsc_alternate_cart_html' ) && empty( $_REQUEST['_wpsc_compat_ajax'] ) ) {
1092
			//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.
1093
			ob_start();
1094
1095
			echo _wpsc_get_alternate_html( $cart_messages );
1096
			$action_output = ob_get_contents();
1097
			$output = '';
1098
			ob_end_clean();
1099
		}
1100
1101
		if ( ! empty( $action_output ) ) {
1102
			_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' );
1103
			$return['wpsc_alternate_cart_html'] = $action_output;
1104
		}
1105
	}
1106
1107
	if ( $die ) {
1108
		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...
1109
		die();
1110
	} else {
1111
		return $return;
1112
	}
1113
}
1114
1115
1116
/**
1117
 * Update the customer mata values that are passed to the application from the checkout form POST
1118
 *
1119
 * With the submit checkout we should get an array of all the checkout values.  These values should already
1120
 * be stored as customer meta, bet there are cases where the submit processing may arrive before or in parallel
1121
 * with the request to update meta.  There is also value in cehcking to be sure the meta stored is what is coming
1122
 * with the POST as it preserves non-js compatibility and being able to use the submit action as an API
1123
 *
1124
 * @since  3.8.14.1
1125
 *
1126
 * @access private
1127
 *
1128
 * @param  array $checkout_post_data
1129
 *
1130
 * @return none
1131
 */
1132
function _wpsc_checkout_customer_meta_update( $checkout_post_data ) {
1133
	global $wpdb;
1134
1135
	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...
1136
		return;
1137
	}
1138
1139
	$id = wpsc_get_current_customer_id();
1140
1141
	$form_sql  = 'SELECT * FROM `' . WPSC_TABLE_CHECKOUT_FORMS . '` WHERE `active` = "1" ORDER BY `checkout_set`, `checkout_order`;';
1142
	$form_data = $wpdb->get_results( $form_sql, ARRAY_A );
1143
1144
	foreach ( $form_data as $index => $form_field ) {
1145
		if (  isset( $checkout_post_data[$form_field['id']] ) ) {
1146
1147
			$meta_key   = $form_field['unique_name'];
1148
			$meta_value = $checkout_post_data[$form_field['id']];
1149
1150
			switch ( $form_field['type'] ) {
1151
				case 'delivery_country':
1152
					if ( is_array( $meta_value ) ) {
1153
1154
						if ( isset( $meta_value[0] ) ) {
1155
							wpsc_update_visitor_meta( $id, 'shippingcountry', $meta_value[0] );
1156
						}
1157
1158
						if ( isset( $meta_value[1] ) ) {
1159
							wpsc_update_visitor_meta( $id, 'shippingregion', $meta_value[1] );
1160
						}
1161
					} else {
1162
						// array had only country, update the country
1163
						wpsc_update_visitor_meta( $id, 'shippingcountry', $meta_value );
1164
					}
1165
1166
					break;
1167
1168
				case 'country':
1169
					if ( is_array( $meta_value ) && count( $meta_value ) == 2 ) {
1170
						wpsc_update_visitor_meta( $id, 'billingcountry', $meta_value[0] );
1171
						wpsc_update_visitor_meta( $id, 'billingregion', $meta_value[1] );
1172
					} else {
1173
						if ( is_array( $meta_value ) ) {
1174
							$meta_value = $meta_value[0];
1175
						}
1176
1177
						wpsc_update_visitor_meta( $id, 'billingcountry', $meta_value );
1178
					}
1179
1180
					break;
1181
1182
				default:
1183
					wpsc_update_visitor_meta( $id, $meta_key, $meta_value );
1184
					break;
1185
			}
1186
		}
1187
	}
1188
}
1189
1190
function wpsc_save_user_profile() {
1191
	if ( isset( $_POST['collected_data'] ) && is_array( $_POST['collected_data'] ) ) {
1192
		_wpsc_checkout_customer_meta_update( $_POST['collected_data'] );
1193
	}
1194
}
1195