Test Failed
Push — master ( 25adfe...70178c )
by Devin
01:46
created

ajax-functions.php ➔ give_ajax_get_states_field()   C

Complexity

Conditions 7
Paths 40

Size

Total Lines 71
Code Lines 45

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 56

Importance

Changes 0
Metric Value
cc 7
eloc 45
nc 40
nop 0
dl 0
loc 71
ccs 0
cts 31
cp 0
crap 56
rs 6.7968
c 0
b 0
f 0

How to fix   Long Method   

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
/**
3
 * AJAX Functions
4
 *
5
 * Process the front-end AJAX actions.
6
 *
7
 * @package     Give
8
 * @subpackage  Functions/AJAX
9
 * @copyright   Copyright (c) 2016, WordImpress
10
 * @license     https://opensource.org/licenses/gpl-license GNU Public License
11
 * @since       1.0
12
 */
13
14
// Exit if accessed directly.
15
if ( ! defined( 'ABSPATH' ) ) {
16
	exit;
17
}
18
19
/**
20
 * Check if AJAX works as expected
21
 *
22
 * @since  1.0
23
 *
24
 * @return bool True if AJAX works, false otherwise
25
 */
26
function give_test_ajax_works() {
27
28
	// Check if the Airplane Mode plugin is installed.
29
	if ( class_exists( 'Airplane_Mode_Core' ) ) {
30
31
		$airplane = Airplane_Mode_Core::getInstance();
32
33
		if ( method_exists( $airplane, 'enabled' ) ) {
34
35
			if ( $airplane->enabled() ) {
36
				return true;
37
			}
38
		} else {
39
40
			if ( 'on' === $airplane->check_status()  ) {
41
				return true;
42
			}
43
		}
44
	}
45
46
	add_filter( 'block_local_requests', '__return_false' );
47
48
	if ( Give_Cache::get( '_give_ajax_works', true ) ) {
49
		return true;
50
	}
51
52
	$params = array(
53
		'sslverify' => false,
54
		'timeout'   => 30,
55
		'body'      => array(
56
			'action' => 'give_test_ajax',
57
		),
58
	);
59
60
	$ajax = wp_remote_post( give_get_ajax_url(), $params );
61
62
	$works = true;
63
64
	if ( is_wp_error( $ajax ) ) {
65
66
		$works = false;
67
68
	} else {
69
70
		if ( empty( $ajax['response'] ) ) {
71
			$works = false;
72
		}
73
74
		if ( empty( $ajax['response']['code'] ) || 200 !== (int) $ajax['response']['code'] ) {
75
			$works = false;
76
		}
77
78
		if ( empty( $ajax['response']['message'] ) || 'OK' !== $ajax['response']['message'] ) {
79
			$works = false;
80
		}
81
82
		if ( ! isset( $ajax['body'] ) || 0 !== (int) $ajax['body'] ) {
83
			$works = false;
84
		}
85
	}
86
87
	if ( $works ) {
88
		Give_Cache::set( '_give_ajax_works', '1', DAY_IN_SECONDS, true );
89
	}
90
91
	return $works;
92
}
93
94
95
/**
96
 * Get AJAX URL
97
 *
98
 * @since  1.0
99
 *
100
 * @return string
101
 */
102 2
function give_get_ajax_url() {
103
	$scheme = defined( 'FORCE_SSL_ADMIN' ) && FORCE_SSL_ADMIN ? 'https' : 'admin';
104 2
105 2
	$current_url = give_get_current_page_url();
106
	$ajax_url    = admin_url( 'admin-ajax.php', $scheme );
107 2
108
	if ( preg_match( '/^https/', $current_url ) && ! preg_match( '/^https/', $ajax_url ) ) {
109
		$ajax_url = preg_replace( '/^http/', 'https', $ajax_url );
110
	}
111 2
112
	return apply_filters( 'give_ajax_url', $ajax_url );
113
}
114
115
/**
116
 * Loads Checkout Login Fields via AJAX
117
 *
118
 * @since  1.0
119
 *
120
 * @return void
121
 */
122
function give_load_checkout_login_fields() {
123
	/**
124
	 * Fire when render login fields via ajax.
125
	 *
126
	 * @since 1.7
127
	 */
128
	do_action( 'give_donation_form_login_fields' );
129
130
	give_die();
131
}
132
133
add_action( 'wp_ajax_nopriv_give_checkout_login', 'give_load_checkout_login_fields' );
134
135
/**
136
 * Load Checkout Fields
137
 *
138
 * @since  1.3.6
139
 *
140
 * @return void
141
 */
142
function give_load_checkout_fields() {
143
	$form_id = isset( $_POST['form_id'] ) ? $_POST['form_id'] : '';
0 ignored issues
show
introduced by
Detected access of super global var $_POST, probably need manual inspection.
Loading history...
introduced by
Detected usage of a non-sanitized input variable: $_POST
Loading history...
144
145
	ob_start();
146
147
	/**
148
	 * Fire to render registration/login form.
149
	 *
150
	 * @since 1.7
151
	 */
152
	do_action( 'give_donation_form_register_login_fields', $form_id );
153
154
	$fields = ob_get_clean();
155
156
	wp_send_json( array(
157
		'fields' => wp_json_encode( $fields ),
158
		'submit' => wp_json_encode( give_get_donation_form_submit_button( $form_id ) ),
159
	) );
160
}
161
162
add_action( 'wp_ajax_nopriv_give_cancel_login', 'give_load_checkout_fields' );
163
add_action( 'wp_ajax_nopriv_give_checkout_register', 'give_load_checkout_fields' );
164
165
/**
166
 * Get Form Title via AJAX (used only in WordPress Admin)
167
 *
168
 * @since  1.0
169
 *
170
 * @return void
171
 */
172
function give_ajax_get_form_title() {
173
	if ( isset( $_POST['form_id'] ) ) {
174
		$title = get_the_title( $_POST['form_id'] );
0 ignored issues
show
introduced by
Detected access of super global var $_POST, probably need manual inspection.
Loading history...
175
		if ( $title ) {
176
			echo $title;
0 ignored issues
show
introduced by
Expected next thing to be a escaping function, not '$title'
Loading history...
177
		} else {
178
			echo 'fail';
179
		}
180
	}
181
	give_die();
182
}
183
184
add_action( 'wp_ajax_give_get_form_title', 'give_ajax_get_form_title' );
185
add_action( 'wp_ajax_nopriv_give_get_form_title', 'give_ajax_get_form_title' );
186
187
/**
188
 * Retrieve a states drop down
189
 *
190
 * @since  1.0
191
 *
192
 * @return void
193
 */
194
function give_ajax_get_states_field() {
195
	$states_found = false;
196
	$show_field = true;
197
	$states_require = true;
198
	// Get the Country code from the $_POST.
199
	$country = sanitize_text_field( $_POST['country'] );
0 ignored issues
show
introduced by
Detected access of super global var $_POST, probably need manual inspection.
Loading history...
introduced by
Detected usage of a non-validated input variable: $_POST
Loading history...
200
201
	// Get the field name from the $_POST.
202
	$field_name = sanitize_text_field( $_POST['field_name'] );
0 ignored issues
show
introduced by
Detected access of super global var $_POST, probably need manual inspection.
Loading history...
introduced by
Detected usage of a non-validated input variable: $_POST
Loading history...
203
204
	$label = __( 'State', 'give' );
205
	$states_label = give_get_states_label();
206
207
	$default_state = '';
208
	if ( $country === give_get_country() ) {
209
		$default_state = give_get_state();
210
	}
211
212
	// Check if $country code exists in the array key for states label.
213
	if ( array_key_exists( $country, $states_label ) ) {
214
		$label = $states_label[ $country ];
215
	}
216
217
	if ( empty( $country ) ) {
218
		$country = give_get_country();
219
	}
220
221
	$states = give_get_states( $country );
222
	if ( ! empty( $states ) ) {
223
		$args = array(
224
			'name'             => $field_name,
225
			'id'               => $field_name,
226
			'class'            => $field_name . '  give-select',
227
			'options'          => $states,
228
			'show_option_all'  => false,
229
			'show_option_none' => false,
230
			'placeholder'      => $label,
231
			'selected'         => $default_state,
232
		);
233
		$data = Give()->html->select( $args );
234
		$states_found = true;
235
	} else {
236
		$data = 'nostates';
237
238
		// Get the country list that does not have any states init.
239
		$no_states_country = give_no_states_country_list();
240
241
		// Check if $country code exists in the array key.
242
		if ( array_key_exists( $country, $no_states_country ) ) {
243
			$show_field = false;
244
		}
245
246
		// Get the country list that does not require states.
247
		$states_not_required_country_list = give_states_not_required_country_list();
248
249
		// Check if $country code exists in the array key.
250
		if ( array_key_exists( $country, $states_not_required_country_list ) ) {
251
			$states_require = false;
252
		}
253
	}
254
	$response = array(
255
		'success'        => true,
256
		'states_found'   => $states_found,
257
		'show_field'     => $show_field,
258
		'states_label'   => $label,
259
		'states_require' => $states_require,
260
		'data'           => $data,
261
		'default_state'  => $default_state,
262
	);
263
	wp_send_json( $response );
264
}
265
add_action( 'wp_ajax_give_get_states', 'give_ajax_get_states_field' );
266
add_action( 'wp_ajax_nopriv_give_get_states', 'give_ajax_get_states_field' );
267
268
/**
269
 * Retrieve donation forms via AJAX for chosen dropdown search field.
270
 *
271
 * @since  1.0
272
 *
273
 * @return void
274
 */
275
function give_ajax_form_search() {
276
	global $wpdb;
277
278
	$search   = esc_sql( sanitize_text_field( $_GET['s'] ) );
0 ignored issues
show
introduced by
Detected access of super global var $_GET, probably need manual inspection.
Loading history...
introduced by
Detected usage of a non-validated input variable: $_GET
Loading history...
279
	$excludes = ( isset( $_GET['current_id'] ) ? (array) $_GET['current_id'] : array() );
0 ignored issues
show
Unused Code introduced by
$excludes is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
introduced by
Detected access of super global var $_GET, probably need manual inspection.
Loading history...
introduced by
Detected usage of a non-sanitized input variable: $_GET
Loading history...
280
281
	$results = array();
282
	if ( current_user_can( 'edit_give_forms' ) ) {
283
		$items = $wpdb->get_results( "SELECT ID,post_title FROM $wpdb->posts WHERE `post_type` = 'give_forms' AND `post_title` LIKE '%$search%' LIMIT 50" );
0 ignored issues
show
introduced by
Usage of a direct database call is discouraged.
Loading history...
introduced by
Usage of a direct database call without caching is prohibited. Use wp_cache_get / wp_cache_set.
Loading history...
284
	} else {
285
		$items = $wpdb->get_results( "SELECT ID,post_title FROM $wpdb->posts WHERE `post_type` = 'give_forms' AND `post_status` = 'publish' AND `post_title` LIKE '%$search%' LIMIT 50" );
0 ignored issues
show
introduced by
Usage of a direct database call is discouraged.
Loading history...
introduced by
Usage of a direct database call without caching is prohibited. Use wp_cache_get / wp_cache_set.
Loading history...
286
	}
287
288
	if ( $items ) {
289
290
		foreach ( $items as $item ) {
291
292
			$results[] = array(
293
				'id'   => $item->ID,
294
				'name' => $item->post_title,
295
			);
296
		}
297
	} else {
298
299
		$items[] = array(
300
			'id'   => 0,
301
			'name' => __( 'No forms found.', 'give' ),
302
		);
303
304
	}
305
306
	echo json_encode( $results );
307
308
	give_die();
309
}
310
311
add_action( 'wp_ajax_give_form_search', 'give_ajax_form_search' );
312
add_action( 'wp_ajax_nopriv_give_form_search', 'give_ajax_form_search' );
313
314
/**
315
 * Search the donors database via Ajax
316
 *
317
 * @since  1.0
318
 *
319
 * @return void
320
 */
321
function give_ajax_donor_search() {
322
	global $wpdb;
323
324
	$search  = esc_sql( sanitize_text_field( $_GET['s'] ) );
0 ignored issues
show
introduced by
Detected access of super global var $_GET, probably need manual inspection.
Loading history...
introduced by
Detected usage of a non-validated input variable: $_GET
Loading history...
325
	$results = array();
326
	if ( ! current_user_can( 'view_give_reports' ) ) {
327
		$donors = array();
328
	} else {
329
		$donors = $wpdb->get_results( "SELECT id,name,email FROM {$wpdb->prefix}give_customers WHERE `name` LIKE '%$search%' OR `email` LIKE '%$search%' LIMIT 50" );
0 ignored issues
show
introduced by
Usage of a direct database call is discouraged.
Loading history...
introduced by
Usage of a direct database call without caching is prohibited. Use wp_cache_get / wp_cache_set.
Loading history...
330
	}
331
332
	if ( $donors ) {
333
334
		foreach ( $donors as $donor ) {
335
336
			$results[] = array(
337
				'id'   => $donor->id,
338
				'name' => $donor->name . ' (' . $donor->email . ')',
339
			);
340
		}
341
	} else {
342
343
		$donors[] = array(
344
			'id'   => 0,
345
			'name' => __( 'No donors found.', 'give' ),
346
		);
347
348
	}
349
350
	echo json_encode( $results );
351
352
	give_die();
353
}
354
355
add_action( 'wp_ajax_give_donor_search', 'give_ajax_donor_search' );
356
357
358
/**
359
 * Searches for users via ajax and returns a list of results
360
 *
361
 * @since  1.0
362
 *
363
 * @return void
364
 */
365
function give_ajax_search_users() {
366
367
	if ( current_user_can( 'manage_give_settings' ) ) {
368
369
		$search   = esc_sql( sanitize_text_field( $_GET['s'] ) );
0 ignored issues
show
introduced by
Detected access of super global var $_GET, probably need manual inspection.
Loading history...
introduced by
Detected usage of a non-validated input variable: $_GET
Loading history...
370
371
		$get_users_args = array(
372
			'number' => 9999,
373
			'search' => $search . '*',
374
		);
375
376
		$get_users_args = apply_filters( 'give_search_users_args', $get_users_args );
377
378
		$found_users = apply_filters( 'give_ajax_found_users', get_users( $get_users_args ), $search );
379
		$results     = array();
380
381
		if ( $found_users ) {
382
383
			foreach ( $found_users as $user ) {
384
385
				$results[] = array(
386
					'id'   => $user->ID,
387
					'name' => esc_html( $user->user_login . ' (' . $user->user_email . ')' ),
388
				);
389
			}
390
		} else {
391
392
			$results[] = array(
393
				'id'   => 0,
394
				'name' => __( 'No users found.', 'give' ),
395
			);
396
397
		}
398
399
		echo json_encode( $results );
400
401
	}// End if().
402
403
	give_die();
404
405
}
406
407
add_action( 'wp_ajax_give_user_search', 'give_ajax_search_users' );
408
409
410
/**
411
 * Check for Price Variations (Multi-level donation forms)
412
 *
413
 * @since  1.5
414
 *
415
 * @return void
416
 */
417
function give_check_for_form_price_variations() {
418
419
	if ( ! current_user_can( 'edit_give_forms', get_current_user_id() ) ) {
420
		die( '-1' );
421
	}
422
423
	$form_id = intval( $_POST['form_id'] );
0 ignored issues
show
introduced by
Detected access of super global var $_POST, probably need manual inspection.
Loading history...
introduced by
Detected usage of a non-validated input variable: $_POST
Loading history...
424
	$form    = get_post( $form_id );
425
426
	if ( 'give_forms' != $form->post_type ) {
427
		die( '-2' );
428
	}
429
430
	if ( give_has_variable_prices( $form_id ) ) {
431
		$variable_prices = give_get_variable_prices( $form_id );
432
433
		if ( $variable_prices ) {
434
			$ajax_response = '<select class="give_price_options_select give-select give-select" name="give_price_option">';
435
436
			if ( isset( $_POST['all_prices'] ) ) {
0 ignored issues
show
introduced by
Detected access of super global var $_POST, probably need manual inspection.
Loading history...
437
				$ajax_response .= '<option value="all">' . esc_html__( 'All Levels', 'give' ) . '</option>';
438
			}
439
440
			foreach ( $variable_prices as $key => $price ) {
441
442
				$level_text = ! empty( $price['_give_text'] ) ? esc_html( $price['_give_text'] ) : give_currency_filter( give_format_amount( $price['_give_amount'], array( 'sanitize' => false ) ) );
443
444
				$ajax_response .= '<option value="' . esc_attr( $price['_give_id']['level_id'] ) . '">' . $level_text . '</option>';
445
			}
446
			$ajax_response .= '</select>';
447
			echo $ajax_response;
0 ignored issues
show
introduced by
Expected next thing to be a escaping function, not '$ajax_response'
Loading history...
448
		}
449
	}
450
451
	give_die();
452
}
453
454
add_action( 'wp_ajax_give_check_for_form_price_variations', 'give_check_for_form_price_variations' );
455
456
457
/**
458
 * Check for Variation Prices HTML  (Multi-level donation forms)
459
 *
460
 * @since  1.6
461
 *
462
 * @return void
463
 */
464
function give_check_for_form_price_variations_html() {
465
	if ( ! current_user_can( 'edit_give_payments', get_current_user_id() ) ) {
466
		wp_die();
467
	}
468
469
	$form_id    = ! empty( $_POST['form_id'] ) ? intval( $_POST['form_id'] ) : 0;
0 ignored issues
show
introduced by
Detected access of super global var $_POST, probably need manual inspection.
Loading history...
470
	$payment_id = ! empty( $_POST['payment_id'] ) ? intval( $_POST['payment_id'] ) : 0;
0 ignored issues
show
introduced by
Detected access of super global var $_POST, probably need manual inspection.
Loading history...
471
	$form       = get_post( $form_id );
472
473
	if ( 'give_forms' != $form->post_type ) {
474
		wp_die();
475
	}
476
477
	if ( ! give_has_variable_prices( $form_id ) || ! $form_id ) {
478
		esc_html_e( 'n/a', 'give' );
479
	} else {
480
		$prices_atts = '';
481 View Code Duplication
		if ( $variable_prices = give_get_variable_prices( $form_id ) ) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
482
			foreach ( $variable_prices as $variable_price ) {
483
				$prices_atts[ $variable_price['_give_id']['level_id'] ] = give_format_amount( $variable_price['_give_amount'], array( 'sanitize' => false ) );
484
			}
485
		}
486
487
		// Variable price dropdown options.
488
		$variable_price_dropdown_option = array(
489
			'id'               => $form_id,
490
			'name'             => 'give-variable-price',
491
			'chosen'           => true,
492
			'show_option_all'  => '',
493
			'show_option_none' => '',
494
			'select_atts'      => 'data-prices=' . esc_attr( json_encode( $prices_atts ) ),
495
		);
496
497
		if ( $payment_id ) {
498
			// Payment object.
499
			$payment = new Give_Payment( $payment_id );
500
501
			// Payment meta.
502
			$payment_meta                               = $payment->get_meta();
503
			$variable_price_dropdown_option['selected'] = $payment_meta['price_id'];
504
		}
505
506
		// Render variable prices select tag html.
507
		give_get_form_variable_price_dropdown( $variable_price_dropdown_option, true );
508
	}
509
510
	give_die();
511
}
512
513
add_action( 'wp_ajax_give_check_for_form_price_variations_html', 'give_check_for_form_price_variations_html' );
514