Passed
Push — master ( 77758e...0d18b8 )
by Brian
06:17
created

WPInv_Ajax::get_aui_states_field()   B

Complexity

Conditions 6
Paths 17

Size

Total Lines 53
Code Lines 35

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 6
eloc 35
nc 17
nop 0
dl 0
loc 53
rs 8.7377
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
 * Contains the ajax handlers.
4
 *
5
 * @since 1.0.0
6
 * @package Invoicing
7
 */
8
 
9
defined( 'ABSPATH' ) || exit;
10
11
/**
12
 * WPInv_Ajax class.
13
 */
14
class WPInv_Ajax {
15
16
    /**
17
	 * Hook in ajax handlers.
18
	 */
19
	public static function init() {
20
		add_action( 'init', array( __CLASS__, 'define_ajax' ), 0 );
21
		add_action( 'template_redirect', array( __CLASS__, 'do_wpinv_ajax' ), 0 );
22
		self::add_ajax_events();
23
    }
24
25
    /**
26
	 * Set GetPaid AJAX constant and headers.
27
	 */
28
	public static function define_ajax() {
29
30
		if ( ! empty( $_GET['wpinv-ajax'] ) ) {
31
			getpaid_maybe_define_constant( 'DOING_AJAX', true );
32
			getpaid_maybe_define_constant( 'WPInv_DOING_AJAX', true );
33
			if ( ! WP_DEBUG || ( WP_DEBUG && ! WP_DEBUG_DISPLAY ) ) {
34
				/** @scrutinizer ignore-unhandled */ @ini_set( 'display_errors', 0 );
35
			}
36
			$GLOBALS['wpdb']->hide_errors();
37
		}
38
39
    }
40
    
41
    /**
42
	 * Send headers for GetPaid Ajax Requests.
43
	 *
44
	 * @since 1.0.18
45
	 */
46
	private static function wpinv_ajax_headers() {
47
		if ( ! headers_sent() ) {
48
			send_origin_headers();
49
			send_nosniff_header();
50
			nocache_headers();
51
			header( 'Content-Type: text/html; charset=' . get_option( 'blog_charset' ) );
52
			header( 'X-Robots-Tag: noindex' );
53
			status_header( 200 );
54
		}
55
    }
56
    
57
    /**
58
	 * Check for GetPaid Ajax request and fire action.
59
	 */
60
	public static function do_wpinv_ajax() {
61
		global $wp_query;
62
63
		if ( ! empty( $_GET['wpinv-ajax'] ) ) {
64
			$wp_query->set( 'wpinv-ajax', sanitize_text_field( wp_unslash( $_GET['wpinv-ajax'] ) ) );
0 ignored issues
show
Bug introduced by
It seems like wp_unslash($_GET['wpinv-ajax']) can also be of type string[]; however, parameter $str of sanitize_text_field() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

64
			$wp_query->set( 'wpinv-ajax', sanitize_text_field( /** @scrutinizer ignore-type */ wp_unslash( $_GET['wpinv-ajax'] ) ) );
Loading history...
65
		}
66
67
		$action = $wp_query->get( 'wpinv-ajax' );
68
69
		if ( $action ) {
70
			self::wpinv_ajax_headers();
71
			$action = sanitize_text_field( $action );
72
			do_action( 'wpinv_ajax_' . $action );
73
			wp_die();
74
		}
75
76
    }
77
78
    /**
79
	 * Hook in ajax methods.
80
	 */
81
    public static function add_ajax_events() {
82
83
        // array( 'event' => is_frontend )
84
        $ajax_events = array(
85
            'add_note'                    => false,
86
            'delete_note'                 => false,
87
            'get_states_field'            => true,
88
            'get_aui_states_field'        => true,
89
            'payment_form'                => true,
90
            'get_payment_form'            => true,
91
            'get_payment_form_states_field' => true,
92
            'get_invoicing_items'         => false,
93
            'get_invoice_items'           => false,
94
            'add_invoice_items'           => false,
95
            'edit_invoice_item'           => false,
96
            'remove_invoice_item'         => false,
97
            'get_billing_details'         => false,
98
            'recalculate_invoice_totals'  => false,
99
            'check_new_user_email'        => false,
100
            'run_tool'                    => false,
101
            'payment_form_refresh_prices' => true,
102
        );
103
104
        foreach ( $ajax_events as $ajax_event => $nopriv ) {
105
            add_action( 'wp_ajax_wpinv_' . $ajax_event, array( __CLASS__, $ajax_event ) );
106
            add_action( 'wp_ajax_getpaid_' . $ajax_event, array( __CLASS__, $ajax_event ) );
107
108
            if ( $nopriv ) {
109
                add_action( 'wp_ajax_nopriv_wpinv_' . $ajax_event, array( __CLASS__, $ajax_event ) );
110
                add_action( 'wp_ajax_nopriv_getpaid_' . $ajax_event, array( __CLASS__, $ajax_event ) );
111
                add_action( 'wpinv_ajax_' . $ajax_event, array( __CLASS__, $ajax_event ) );
112
            }
113
        }
114
    }
115
    
116
    public static function add_note() {
117
        check_ajax_referer( 'add-invoice-note', '_nonce' );
118
119
        if ( ! wpinv_current_user_can_manage_invoicing() ) {
120
            die(-1);
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
121
        }
122
123
        $post_id   = absint( $_POST['post_id'] );
124
        $note      = wp_kses_post( trim( stripslashes( $_POST['note'] ) ) );
125
        $note_type = sanitize_text_field( $_POST['note_type'] );
126
127
        $is_customer_note = $note_type == 'customer' ? 1 : 0;
128
129
        if ( $post_id > 0 ) {
130
            $note_id = wpinv_insert_payment_note( $post_id, $note, $is_customer_note );
0 ignored issues
show
Deprecated Code introduced by
The function wpinv_insert_payment_note() has been deprecated. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-deprecated  annotation

130
            $note_id = /** @scrutinizer ignore-deprecated */ wpinv_insert_payment_note( $post_id, $note, $is_customer_note );
Loading history...
131
132
            if ( $note_id > 0 && !is_wp_error( $note_id ) ) {
133
                wpinv_get_invoice_note_line_item( $note_id );
134
            }
135
        }
136
137
        die();
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
138
    }
139
140
    public static function delete_note() {
141
        check_ajax_referer( 'delete-invoice-note', '_nonce' );
142
143
        if ( !wpinv_current_user_can_manage_invoicing() ) {
144
            die(-1);
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
145
        }
146
147
        $note_id = (int)$_POST['note_id'];
148
149
        if ( $note_id > 0 ) {
150
            wp_delete_comment( $note_id, true );
151
        }
152
153
        die();
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
154
    }
155
    
156
    public static function get_states_field() {
157
        echo wpinv_get_states_field();
158
        
159
        die();
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
160
    }
161
162
    /**
163
     * Retrieves a given user's billing address.
164
     */
165
    public static function get_billing_details() {
166
167
        // Verify nonce.
168
        check_ajax_referer( 'wpinv-nonce' );
169
170
        // Can the user manage the plugin?
171
        if ( ! wpinv_current_user_can_manage_invoicing() ) {
172
            die(-1);
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
173
        }
174
175
        // Do we have a user id?
176
        $user_id = $_GET['user_id'];
177
178
        if ( empty( $user_id ) || ! is_numeric( $user_id ) ) {
179
            die(-1);
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
180
        }
181
182
        // Fetch the billing details.
183
        $billing_details    = wpinv_get_user_address( $user_id );
184
        $billing_details    = apply_filters( 'wpinv_ajax_billing_details', $billing_details, $user_id );
185
186
        // unset the user id and email.
187
        $to_ignore = array( 'user_id', 'email' );
188
189
        foreach ( $to_ignore as $key ) {
190
            if ( isset( $billing_details[ $key ] ) ) {
191
                unset( $billing_details[ $key ] );
192
            }
193
        }
194
195
        wp_send_json_success( $billing_details );
196
197
    }
198
199
    /**
200
     * Checks if a new users email is valid.
201
     */
202
    public static function check_new_user_email() {
203
204
        // Verify nonce.
205
        check_ajax_referer( 'wpinv-nonce' );
206
207
        // Can the user manage the plugin?
208
        if ( ! wpinv_current_user_can_manage_invoicing() ) {
209
            die(-1);
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
210
        }
211
212
        // We need an email address.
213
        if ( empty( $_GET['email'] ) ) {
214
            _e( "Provide the new user's email address", 'invoicing' );
215
            exit;
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
216
        }
217
218
        // Ensure the email is valid.
219
        $email = sanitize_text_field( $_GET['email'] );
220
        if ( ! is_email( $email ) ) {
221
            _e( 'Invalid email address', 'invoicing' );
222
            exit;
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
223
        }
224
225
        // And it does not exist.
226
        if ( email_exists( $email ) ) {
227
            _e( 'A user with this email address already exists', 'invoicing' );
228
            exit;
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
229
        }
230
231
        wp_send_json_success( true );
232
    }
233
    
234
    public static function run_tool() {
235
        check_ajax_referer( 'wpinv-nonce', '_nonce' );
236
        if ( !wpinv_current_user_can_manage_invoicing() ) {
237
            die(-1);
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
238
        }
239
        
240
        $tool = sanitize_text_field( $_POST['tool'] );
241
        
242
        do_action( 'wpinv_run_tool' );
243
        
244
        if ( !empty( $tool ) ) {
245
            do_action( 'wpinv_tool_' . $tool );
246
        }
247
    }
248
249
    /**
250
     * Retrieves the markup for a payment form.
251
     */
252
    public static function get_payment_form() {
253
254
        // Check nonce.
255
        check_ajax_referer( 'getpaid_form_nonce' );
256
257
        // Is the request set up correctly?
258
		if ( empty( $_GET['form'] ) && empty( $_GET['item'] ) ) {
259
			echo aui()->alert(
260
				array(
261
					'type'    => 'warning',
262
					'content' => __( 'No payment form or item provided', 'invoicing' ),
263
				)
264
            );
265
            exit;
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
266
        }
267
268
        // Payment form or button?
269
		if ( ! empty( $_GET['form'] ) ) {
270
            getpaid_display_payment_form( urldecode( $_GET['form'] ) );
271
		} else if( ! empty( $_GET['invoice'] ) ) {
272
		    getpaid_display_invoice_payment_form( urldecode( $_GET['invoice'] ) );
273
        } else {
274
			$items = getpaid_convert_items_to_array( urldecode( $_GET['item'] ) );
275
		    getpaid_display_item_payment_form( $items );
276
        }
277
278
        exit;
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
279
280
    }
281
282
    /**
283
     * Payment forms.
284
     *
285
     * @since 1.0.18
286
     */
287
    public static function payment_form() {
288
289
        // Check nonce.
290
        check_ajax_referer( 'getpaid_form_nonce' );
291
292
        // ... form fields...
293
        if ( empty( $_POST['getpaid_payment_form_submission'] ) ) {
294
            _e( 'Error: Reload the page and try again.', 'invoicing' );
295
            exit;
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
296
        }
297
298
        // Process the payment form.
299
        $checkout_class = apply_filters( 'getpaid_checkout_class', 'GetPaid_Checkout' );
300
        $checkout       = new $checkout_class( new GetPaid_Payment_Form_Submission() );
301
        $checkout->process_checkout();
302
303
        exit;
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
304
    }
305
306
    /**
307
     * Payment forms.
308
     *
309
     * @since 1.0.18
310
     */
311
    public static function get_payment_form_states_field() {
312
313
        if ( empty( $_GET['country'] ) || empty( $_GET['form'] ) ) {
314
            exit;
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
315
        }
316
317
        $elements = getpaid_get_payment_form_elements( $_GET['form'] );
318
319
        if ( empty( $elements ) ) {
320
            exit;
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
321
        }
322
323
        $address_fields = array();
324
        foreach ( $elements as $element ) {
325
            if ( 'address' === $element['type'] ) {
326
                $address_fields = $element;
327
                break;
328
            }
329
        }
330
331
        if ( empty( $address_fields ) ) {
332
            exit;
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
333
        }
334
335
        foreach ( $address_fields['fields'] as $address_field ) {
336
337
            if ( 'wpinv_state' == $address_field['name'] ) {
338
339
                $wrap_class  = getpaid_get_form_element_grid_class( $address_field );
340
                $wrap_class  = esc_attr( "$wrap_class getpaid-address-field-wrapper" );
341
                $placeholder = empty( $address_field['placeholder'] ) ? '' : esc_attr( $address_field['placeholder'] );
342
                $description = empty( $address_field['description'] ) ? '' : wp_kses_post( $address_field['description'] );
343
                $value       = is_user_logged_in() ? get_user_meta( get_current_user_id(), '_wpinv_state', true ) : '';
344
                $label       = empty( $address_field['label'] ) ? '' : wp_kses_post( $address_field['label'] );
345
346
                if ( ! empty( $address_field['required'] ) ) {
347
                    $label .= "<span class='text-danger'> *</span>";
348
                }
349
350
                $html = getpaid_get_states_select_markup (
351
                    sanitize_text_field( $_GET['country'] ),
352
                    $value,
353
                    $placeholder,
354
                    $label,
355
                    $description,
356
                    ! empty( $address_field['required'] ),
357
                    $wrap_class,
358
                    wpinv_clean( $_GET['name'] )
359
                );
360
361
                wp_send_json_success( $html );
362
                exit;
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
363
364
            }
365
366
        }
367
    
368
        exit;
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
369
    }
370
371
    /**
372
     * Recalculates invoice totals.
373
     */
374
    public static function recalculate_invoice_totals() {
375
376
        // Verify nonce.
377
        check_ajax_referer( 'wpinv-nonce' );
378
379
        if ( ! wpinv_current_user_can_manage_invoicing() ) {
380
            exit;
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
381
        }
382
383
        // We need an invoice.
384
        if ( empty( $_POST['post_id'] ) ) {
385
            exit;
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
386
        }
387
388
        // Fetch the invoice.
389
        $invoice = new WPInv_Invoice( trim( $_POST['post_id'] ) );
390
391
        // Ensure it exists.
392
        if ( ! $invoice->get_id() ) {
393
            exit;
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
394
        }
395
396
        // Maybe set the country, state, currency.
397
        foreach ( array( 'country', 'state', 'currency' ) as $key ) {
398
            if ( isset( $_POST[ $key ] ) ) {
399
                $method = "set_$key";
400
                $invoice->$method( sanitize_text_field( $_POST[ $key ] ) );
401
            }
402
        }
403
404
        // Maybe disable taxes.
405
        $invoice->set_disable_taxes( ! empty( $_POST['taxes'] ) );
406
407
        // Recalculate totals.
408
        $invoice->recalculate_total();
409
410
        $total = wpinv_price( $invoice->get_total(), $invoice->get_currency() );
411
412
        if ( $invoice->is_recurring() && $invoice->is_parent() && $invoice->get_total() != $invoice->get_recurring_total() ) {
413
            $recurring_total = wpinv_price( $invoice->get_recurring_total(), $invoice->get_currency() );
414
            $total          .= '<small class="form-text text-muted">' . sprintf( __( 'Recurring Price: %s', 'invoicing' ), $recurring_total ) . '</small>';
415
        }
416
417
        $totals = array(
418
            'subtotal' => wpinv_price( $invoice->get_subtotal(), $invoice->get_currency() ),
419
            'discount' => wpinv_price( $invoice->get_total_discount(), $invoice->get_currency() ),
420
            'tax'      => wpinv_price( $invoice->get_total_tax(), $invoice->get_currency() ),
421
            'total'    => $total,
422
        );
423
424
        $totals = apply_filters( 'getpaid_invoice_totals', $totals, $invoice );
425
426
        wp_send_json_success( compact( 'totals' ) );
427
    }
428
429
    /**
430
     * Get items belonging to a given invoice.
431
     */
432
    public static function get_invoice_items() {
433
434
        // Verify nonce.
435
        check_ajax_referer( 'wpinv-nonce' );
436
437
        if ( ! wpinv_current_user_can_manage_invoicing() ) {
438
            exit;
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
439
        }
440
441
        // We need an invoice and items.
442
        if ( empty( $_POST['post_id'] ) ) {
443
            exit;
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
444
        }
445
446
        // Fetch the invoice.
447
        $invoice = new WPInv_Invoice( trim( $_POST['post_id'] ) );
448
449
        // Ensure it exists.
450
        if ( ! $invoice->get_id() ) {
451
            exit;
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
452
        }
453
454
        // Return an array of invoice items.
455
        $items = array();
456
457
        foreach ( $invoice->get_items() as $item_id => $item ) {
458
            $items[ $item_id ] = $item->prepare_data_for_invoice_edit_ajax(  $invoice->get_currency(), $invoice->is_renewal()  );
459
        }
460
461
        wp_send_json_success( compact( 'items' ) );
462
    }
463
464
    /**
465
     * Edits an invoice item.
466
     */
467
    public static function edit_invoice_item() {
468
469
        // Verify nonce.
470
        check_ajax_referer( 'wpinv-nonce' );
471
472
        if ( ! wpinv_current_user_can_manage_invoicing() ) {
473
            exit;
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
474
        }
475
476
        // We need an invoice and item details.
477
        if ( empty( $_POST['post_id'] ) || empty( $_POST['data'] ) ) {
478
            exit;
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
479
        }
480
481
        // Fetch the invoice.
482
        $invoice = new WPInv_Invoice( trim( $_POST['post_id'] ) );
483
484
        // Ensure it exists and its not been paid for.
485
        if ( ! $invoice->get_id() || $invoice->is_paid() || $invoice->is_refunded() ) {
486
            exit;
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
487
        }
488
489
        // Format the data.
490
        $data = wp_list_pluck( $_POST['data'], 'value', 'field' );
491
492
        // Ensure that we have an item id.
493
        if ( empty( $data['id'] ) ) {
494
            exit;
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
495
        }
496
497
        // Abort if the invoice does not have the specified item.
498
        $item = $invoice->get_item( (int) $data['id'] );
499
500
        if ( empty( $item ) ) {
501
            exit;
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
502
        }
503
504
        // Update the item.
505
        $item->set_price( $data['price'] );
506
        $item->set_name( $data['name'] );
507
        $item->set_description( $data['description'] );
508
        $item->set_quantity( $data['quantity'] );
509
510
        // Add it to the invoice.
511
        $error = $invoice->add_item( $item );
512
        $alert = false;
513
        if ( is_wp_error( $error ) ) {
514
            $alert = $error->get_error_message();
515
        }
516
517
        // Update totals.
518
        $invoice->recalculate_total();
519
520
        // Save the invoice.
521
        $invoice->save();
522
523
        // Return an array of invoice items.
524
        $items = array();
525
526
        foreach ( $invoice->get_items() as $item_id => $item ) {
527
            $items[ $item_id ] = $item->prepare_data_for_invoice_edit_ajax(  $invoice->get_currency()  );
528
        }
529
530
        wp_send_json_success( compact( 'items', 'alert' ) );
531
    }
532
533
    /**
534
     * Deletes an invoice item.
535
     */
536
    public static function remove_invoice_item() {
537
538
        // Verify nonce.
539
        check_ajax_referer( 'wpinv-nonce' );
540
541
        if ( ! wpinv_current_user_can_manage_invoicing() ) {
542
            exit;
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
543
        }
544
545
        // We need an invoice and an item.
546
        if ( empty( $_POST['post_id'] ) || empty( $_POST['item_id'] ) ) {
547
            exit;
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
548
        }
549
550
        // Fetch the invoice.
551
        $invoice = new WPInv_Invoice( trim( $_POST['post_id'] ) );
552
553
        // Ensure it exists and its not been paid for.
554
        if ( ! $invoice->get_id() || $invoice->is_paid() || $invoice->is_refunded() ) {
555
            exit;
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
556
        }
557
558
        // Abort if the invoice does not have the specified item.
559
        $item = $invoice->get_item( (int) $_POST['item_id'] );
560
561
        if ( empty( $item ) ) {
562
            exit;
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
563
        }
564
565
        $invoice->remove_item( (int) $_POST['item_id'] );
566
567
        // Update totals.
568
        $invoice->recalculate_total();
569
570
        // Save the invoice.
571
        $invoice->save();
572
573
        // Return an array of invoice items.
574
        $items = array();
575
576
        foreach ( $invoice->get_items() as $item_id => $item ) {
577
            $items[ $item_id ] = $item->prepare_data_for_invoice_edit_ajax(  $invoice->get_currency()  );
578
        }
579
580
        wp_send_json_success( compact( 'items' ) );
581
    }
582
583
    /**
584
     * Adds a items to an invoice.
585
     */
586
    public static function add_invoice_items() {
587
588
        // Verify nonce.
589
        check_ajax_referer( 'wpinv-nonce' );
590
591
        if ( ! wpinv_current_user_can_manage_invoicing() ) {
592
            exit;
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
593
        }
594
595
        // We need an invoice and items.
596
        if ( empty( $_POST['post_id'] ) || empty( $_POST['items'] ) ) {
597
            exit;
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
598
        }
599
600
        // Fetch the invoice.
601
        $invoice = new WPInv_Invoice( trim( $_POST['post_id'] ) );
602
        $alert   = false;
603
604
        // Ensure it exists and its not been paid for.
605
        if ( ! $invoice->get_id() || $invoice->is_paid() || $invoice->is_refunded() ) {
606
            exit;
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
607
        }
608
609
        // Add the items.
610
        foreach ( $_POST['items'] as $data ) {
611
612
            $item = new GetPaid_Form_Item( $data[ 'id' ] );
613
614
            if ( is_numeric( $data[ 'qty' ] ) && (float) $data[ 'qty' ] > 0 ) {
615
                $item->set_quantity( $data[ 'qty' ] );
616
            }
617
618
            if ( $item->get_id() > 0 ) {
619
                $error = $invoice->add_item( $item );
620
621
                if ( is_wp_error( $error ) ) {
622
                    $alert = $error->get_error_message();
623
                }
624
625
            }
626
627
        }
628
629
        // Save the invoice.
630
        $invoice->recalculate_total();
631
        $invoice->save();
632
633
        // Return an array of invoice items.
634
        $items = array();
635
636
        foreach ( $invoice->get_items() as $item_id => $item ) {
637
            $items[ $item_id ] = $item->prepare_data_for_invoice_edit_ajax( $invoice->get_currency() );
638
        }
639
640
        wp_send_json_success( compact( 'items', 'alert' ) );
641
    }
642
643
    /**
644
     * Retrieves items that should be added to an invoice.
645
     */
646
    public static function get_invoicing_items() {
647
648
        // Verify nonce.
649
        check_ajax_referer( 'wpinv-nonce' );
650
651
        if ( ! wpinv_current_user_can_manage_invoicing() ) {
652
            exit;
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
653
        }
654
655
        // We need a search term.
656
        if ( empty( $_GET['search'] ) ) {
657
            wp_send_json_success( array() );
658
        }
659
660
        // Retrieve items.
661
        $item_args = array(
662
            'post_type'      => 'wpi_item',
663
            'orderby'        => 'title',
664
            'order'          => 'ASC',
665
            'posts_per_page' => -1,
666
            'post_status'    => array( 'publish' ),
667
            's'              => trim( $_GET['search'] ),
668
            'meta_query'     => array(
669
                array(
670
                    'key'       => '_wpinv_type',
671
                    'compare'   => '!=',
672
                    'value'     => 'package'
673
                )
674
            )
675
        );
676
677
        $items = get_posts( apply_filters( 'getpaid_ajax_invoice_items_query_args', $item_args ) );
678
        $data  = array();
679
680
681
        $is_payment_form = ( ! empty( $_GET['post_id'] ) && 'wpi_payment_form' == get_post_type( $_GET['post_id'] ) );
682
683
        foreach ( $items as $item ) {
684
            $item      = new GetPaid_Form_Item( $item );
685
            $data[] = array(
686
                'id'        => (int) $item->get_id(),
687
                'text'      => strip_tags( $item->get_name() ),
688
                'form_data' => $is_payment_form ? $item->prepare_data_for_use( false ) : '',
689
            );
690
        }
691
692
        wp_send_json_success( $data );
693
694
    }
695
696
    /**
697
     * Retrieves the states field for AUI forms.
698
     */
699
    public static function get_aui_states_field() {
700
701
        // Verify nonce.
702
        check_ajax_referer( 'wpinv-nonce' );
703
704
        // We need a country.
705
        if ( empty( $_GET['country'] ) ) {
706
            exit;
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
707
        }
708
709
        $states = wpinv_get_country_states( sanitize_text_field( $_GET['country'] ) );
710
        $state  = isset( $_GET['state'] ) ? sanitize_text_field( $_GET['state'] ) : wpinv_get_default_state();
711
        $name   = isset( $_GET['name'] ) ? sanitize_text_field( $_GET['name'] ) : 'wpinv_state';
712
        $class  = isset( $_GET['class'] ) ? sanitize_text_field( $_GET['class'] ) : 'form-control-sm';
713
714
        if ( empty( $states ) ) {
715
716
            $html = aui()->input(
717
                array(
718
                    'type'        => 'text',
719
                    'id'          => 'wpinv_state',
720
                    'name'        => $name,
721
                    'label'       => __( 'State', 'invoicing' ),
722
                    'label_type'  => 'vertical',
723
                    'placeholder' => __( 'State', 'invoicing' ),
724
                    'class'       => $class,
725
                    'value'       => $state,
726
                )
727
            );
728
729
        } else {
730
731
            $html = aui()->select(
732
                array(
733
                    'id'          => 'wpinv_state',
734
                    'name'        => $name,
735
                    'label'       => __( 'State', 'invoicing' ),
736
                    'label_type'  => 'vertical',
737
                    'placeholder' => __( 'Select a state', 'invoicing' ),
738
                    'class'       => $class,
739
                    'value'       => $state,
740
                    'options'     => $states,
741
                    'data-allow-clear' => 'false',
742
                    'select2'          => true,
743
                )
744
            );
745
746
        }
747
748
        wp_send_json_success(
749
            array(
750
                'html'   => $html,
751
                'select' => ! empty ( $states )
752
            )
753
        );
754
755
    }
756
757
    /**
758
     * Refresh prices.
759
     *
760
     * @since 1.0.19
761
     */
762
    public static function payment_form_refresh_prices() {
763
764
        // Check nonce.
765
        check_ajax_referer( 'getpaid_form_nonce' );
766
767
        // ... form fields...
768
        if ( empty( $_POST['getpaid_payment_form_submission'] ) ) {
769
            _e( 'Error: Reload the page and try again.', 'invoicing' );
770
            exit;
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
771
        }
772
773
        // Load the submission.
774
        $submission = new GetPaid_Payment_Form_Submission();
775
776
        // Do we have an error?
777
        if ( ! empty( $submission->last_error ) ) {
778
            echo $submission->last_error;
779
            exit;
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
780
        }
781
782
        // Prepare the response.
783
        $response = new GetPaid_Payment_Form_Submission_Refresh_Prices( $submission );
784
        
785
        // Filter the response.
786
        $response = apply_filters( 'getpaid_payment_form_ajax_refresh_prices', $response->response, $submission );
787
788
        wp_send_json_success( $response );
789
    }
790
791
}
792
793
WPInv_Ajax::init();