Passed
Push — master ( 684a37...347a19 )
by Brian
08:43 queued 03:30
created

WPInv_Ajax   F

Complexity

Total Complexity 182

Size/Duplication

Total Lines 1137
Duplicated Lines 0 %

Importance

Changes 5
Bugs 1 Features 1
Metric Value
wmc 182
eloc 535
c 5
b 1
f 1
dl 0
loc 1137
rs 2

27 Methods

Rating   Name   Duplication   Size   Complexity  
A wpinv_ajax_headers() 0 8 2
A init() 0 4 1
A define_ajax() 0 9 5
A do_wpinv_ajax() 0 14 3
A check_new_user_email() 0 30 5
A get_states_field() 0 4 1
A run_tool() 0 12 3
A add_note() 0 22 6
C file_upload() 0 60 11
C add_invoice_items() 0 53 13
A delete_note() 0 14 3
A add_ajax_events() 0 36 3
A payment_form() 0 14 2
C recalculate_invoice_totals() 0 63 13
B edit_invoice_item() 0 64 11
A get_invoice_items() 0 30 5
C get_payment_form() 0 76 14
C get_payment_form_states_field() 0 57 14
B get_billing_details() 0 31 7
C recalculate_full_prices() 0 65 12
B create_invoice_item() 0 69 10
B admin_add_invoice_item() 0 40 8
B remove_invoice_item() 0 45 9
B get_invoicing_items() 0 54 7
B get_aui_states_field() 0 50 6
A payment_form_refresh_prices() 0 28 3
A get_customers() 0 36 5

How to fix   Complexity   

Complex Class

Complex classes like WPInv_Ajax often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use WPInv_Ajax, and based on these observations, apply Extract Interface, too.

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 array; 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_customers'                 => false,
94
            'get_invoice_items'             => false,
95
            'add_invoice_items'             => false,
96
            'admin_add_invoice_item'        => false,
97
            'recalculate_full_prices'       => false,
98
            'edit_invoice_item'             => false,
99
            'create_invoice_item'           => false,
100
            'remove_invoice_item'           => false,
101
            'get_billing_details'           => false,
102
            'recalculate_invoice_totals'    => false,
103
            'check_new_user_email'          => false,
104
            'run_tool'                      => false,
105
            'payment_form_refresh_prices'   => true,
106
            'file_upload'                   => true,
107
        );
108
109
        foreach ( $ajax_events as $ajax_event => $nopriv ) {
110
            add_action( 'wp_ajax_wpinv_' . $ajax_event, array( __CLASS__, $ajax_event ) );
111
            add_action( 'wp_ajax_getpaid_' . $ajax_event, array( __CLASS__, $ajax_event ) );
112
113
            if ( $nopriv ) {
114
                add_action( 'wp_ajax_nopriv_wpinv_' . $ajax_event, array( __CLASS__, $ajax_event ) );
115
                add_action( 'wp_ajax_nopriv_getpaid_' . $ajax_event, array( __CLASS__, $ajax_event ) );
116
                add_action( 'wpinv_ajax_' . $ajax_event, array( __CLASS__, $ajax_event ) );
117
            }
118
        }
119
    }
120
121
    public static function add_note() {
122
        check_ajax_referer( 'add-invoice-note', '_nonce' );
123
124
        $post_id   = absint( $_POST['post_id'] );
125
        $note      = wp_kses_post( trim( stripslashes( $_POST['note'] ) ) );
126
        $note_type = sanitize_text_field( $_POST['note_type'] );
127
128
        if ( ! wpinv_current_user_can( 'invoice_add_note', array( 'post_id' => $post_id, 'note_type' => $note_type ) ) ) {
129
            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...
130
        }
131
132
        $is_customer_note = $note_type == 'customer' ? 1 : 0;
133
134
        if ( $post_id > 0 ) {
135
            $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

135
            $note_id = /** @scrutinizer ignore-deprecated */ wpinv_insert_payment_note( $post_id, $note, $is_customer_note );
Loading history...
136
137
            if ( $note_id > 0 && ! is_wp_error( $note_id ) ) {
138
                wpinv_get_invoice_note_line_item( $note_id );
139
            }
140
        }
141
142
        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...
143
    }
144
145
    public static function delete_note() {
146
        check_ajax_referer( 'delete-invoice-note', '_nonce' );
147
148
        $note_id = (int)$_POST['note_id'];
149
150
        if ( ! wpinv_current_user_can( 'invoice_delete_note', array( 'note_id' => $note_id ) ) ) {
151
            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...
152
        }
153
154
        if ( $note_id > 0 ) {
155
            wp_delete_comment( $note_id, true );
156
        }
157
158
        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...
159
    }
160
161
    public static function get_states_field() {
162
        wpinv_get_states_field();
163
164
        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...
165
    }
166
167
    /**
168
     * Retrieves a given user's billing address.
169
     */
170
    public static function get_billing_details() {
171
        // Verify nonce.
172
        check_ajax_referer( 'wpinv-nonce' );
173
174
        // Do we have a user id?
175
        $user_id = (int) $_GET['user_id'];
176
        $invoice_id = ! empty( $_REQUEST['post_id'] ) ? (int) $_REQUEST['post_id'] : 0;
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
        // Can the user manage the plugin?
183
        if ( ! wpinv_current_user_can( 'invoice_get_billing_details', array( 'user_id' => $user_id, 'invoice_id' => $invoice_id ) ) ) {
184
            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...
185
        }
186
187
        // Fetch the billing details.
188
        $billing_details    = wpinv_get_user_address( $user_id );
189
        $billing_details    = apply_filters( 'wpinv_ajax_billing_details', $billing_details, $user_id );
190
191
        // unset the user id and email.
192
        $to_ignore = array( 'user_id', 'email' );
193
194
        foreach ( $to_ignore as $key ) {
195
            if ( isset( $billing_details[ $key ] ) ) {
196
                unset( $billing_details[ $key ] );
197
            }
198
        }
199
200
        wp_send_json_success( $billing_details );
201
202
    }
203
204
    /**
205
     * Checks if a new users email is valid.
206
     */
207
    public static function check_new_user_email() {
208
209
        // Verify nonce.
210
        check_ajax_referer( 'wpinv-nonce' );
211
212
        // Can the user manage the plugin?
213
        if ( ! wpinv_current_user_can_manage_invoicing() ) {
214
            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...
215
        }
216
217
        // We need an email address.
218
        if ( empty( $_GET['email'] ) ) {
219
            esc_html_e( "Provide the new user's email address", 'invoicing' );
220
            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...
221
        }
222
223
        // Ensure the email is valid.
224
        $email = sanitize_email( $_GET['email'] );
225
        if ( ! is_email( $email ) ) {
226
            esc_html_e( 'Invalid email address', 'invoicing' );
227
            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...
228
        }
229
230
        // And it does not exist.
231
        $id = email_exists( $email );
232
        if ( $id ) {
233
            wp_send_json_success( compact( 'id' ) );
234
        }
235
236
        wp_send_json_success( true );
237
    }
238
239
    public static function run_tool() {
240
        check_ajax_referer( 'wpinv-nonce', '_nonce' );
241
        if ( ! wpinv_current_user_can_manage_invoicing() ) {
242
            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...
243
        }
244
245
        $tool = sanitize_text_field( $_POST['tool'] );
246
247
        do_action( 'wpinv_run_tool' );
248
249
        if ( ! empty( $tool ) ) {
250
            do_action( 'wpinv_tool_' . $tool );
251
        }
252
    }
253
254
    /**
255
     * Retrieves the markup for a payment form.
256
     */
257
    public static function get_payment_form() {
258
        global $getpaid_force_checkbox;
259
260
        // Is the request set up correctly?
261
		if ( empty( $_GET['form'] ) && empty( $_GET['item'] ) && empty( $_GET['invoice'] ) ) {
262
			aui()->alert(
263
				array(
264
					'type'    => 'warning',
265
					'content' => __( 'No payment form or item provided', 'invoicing' ),
266
                ),
267
                true
268
            );
269
            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...
270
        }
271
272
        // Payment form or button?
273
		if ( ! empty( $_GET['form'] ) ) {
274
            $form = sanitize_text_field( urldecode( $_GET['form'] ) );
275
276
            if ( false !== strpos( $form, '|' ) ) {
277
                $form_pos = strpos( $form, '|' );
278
                $_items   = getpaid_convert_items_to_array( substr( $form, $form_pos + 1 ) );
279
                $form     = substr( $form, 0, $form_pos );
280
281
                // Retrieve appropriate payment form.
282
                $payment_form = new GetPaid_Payment_Form( $form );
283
                $payment_form = $payment_form->exists() ? $payment_form : new GetPaid_Payment_Form( wpinv_get_default_payment_form() );
284
285
                $items    = array();
286
                $item_ids = array();
287
288
                foreach ( $_items as $item_id => $qty ) {
289
                    if ( ! in_array( $item_id, $item_ids ) ) {
290
                        $item = new GetPaid_Form_Item( $item_id );
291
                        $item->set_quantity( $qty );
292
293
                        if ( 0 == $qty ) {
294
                            $item->set_allow_quantities( true );
295
                            $item->set_is_required( false );
296
                            $getpaid_force_checkbox = true;
297
                        }
298
299
                        $item_ids[] = $item->get_id();
300
                        $items[]    = $item;
301
                    }
302
                }
303
304
                if ( ! $payment_form->is_default() ) {
305
306
                    foreach ( $payment_form->get_items() as $item ) {
307
                        if ( ! in_array( $item->get_id(), $item_ids ) ) {
308
                            $item_ids[] = $item->get_id();
309
                            $items[]    = $item;
310
                        }
311
                    }
312
                }
313
314
                $payment_form->set_items( $items );
315
                $extra_items     = esc_attr( getpaid_convert_items_to_string( $_items ) );
316
                $extra_items_key = md5( NONCE_KEY . AUTH_KEY . $extra_items );
317
                $extra_items     = "<input type='hidden' name='getpaid-form-items' value='$extra_items' />";
318
                $extra_items    .= "<input type='hidden' name='getpaid-form-items-key' value='$extra_items_key' />";
319
                $payment_form->display( $extra_items );
320
                $getpaid_force_checkbox = false;
321
322
            } else {
323
                getpaid_display_payment_form( $form );
0 ignored issues
show
Bug introduced by
$form of type string is incompatible with the type GetPaid_Payment_Form expected by parameter $form of getpaid_display_payment_form(). ( Ignorable by Annotation )

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

323
                getpaid_display_payment_form( /** @scrutinizer ignore-type */ $form );
Loading history...
324
            }
325
} elseif ( ! empty( $_GET['invoice'] ) ) {
326
		    getpaid_display_invoice_payment_form( (int) urldecode( $_GET['invoice'] ) );
327
        } else {
328
			$items = getpaid_convert_items_to_array( sanitize_text_field( urldecode( $_GET['item'] ) ) );
329
		    getpaid_display_item_payment_form( $items );
330
        }
331
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
336
    /**
337
     * Payment forms.
338
     *
339
     * @since 1.0.18
340
     */
341
    public static function payment_form() {
342
343
        // ... form fields...
344
        if ( empty( $_POST['getpaid_payment_form_submission'] ) ) {
345
            esc_html_e( 'Error: Reload the page and try again.', 'invoicing' );
346
            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...
347
        }
348
349
        // Process the payment form.
350
        $checkout_class = apply_filters( 'getpaid_checkout_class', 'GetPaid_Checkout' );
351
        $checkout       = new $checkout_class( new GetPaid_Payment_Form_Submission() );
352
        $checkout->process_checkout();
353
354
        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...
355
    }
356
357
    /**
358
     * Payment forms.
359
     *
360
     * @since 1.0.18
361
     */
362
    public static function get_payment_form_states_field() {
363
364
        if ( empty( $_GET['country'] ) || empty( $_GET['form'] ) ) {
365
            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...
366
        }
367
368
        $elements = getpaid_get_payment_form_elements( (int) $_GET['form'] );
369
370
        if ( empty( $elements ) ) {
371
            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...
372
        }
373
374
        $address_fields = array();
375
        foreach ( $elements as $element ) {
376
            if ( 'address' === $element['type'] ) {
377
                $address_fields = $element;
378
                break;
379
            }
380
        }
381
382
        if ( empty( $address_fields ) ) {
383
            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...
384
        }
385
386
        foreach ( $address_fields['fields'] as $address_field ) {
387
388
            if ( 'wpinv_state' == $address_field['name'] ) {
389
390
                $wrap_class  = getpaid_get_form_element_grid_class( $address_field );
391
                $wrap_class  = esc_attr( "$wrap_class getpaid-address-field-wrapper" );
392
                $placeholder = empty( $address_field['placeholder'] ) ? '' : esc_attr( $address_field['placeholder'] );
393
                $description = empty( $address_field['description'] ) ? '' : wp_kses_post( $address_field['description'] );
394
                $value       = is_user_logged_in() ? get_user_meta( get_current_user_id(), '_wpinv_state', true ) : '';
395
                $label       = empty( $address_field['label'] ) ? '' : wp_kses_post( $address_field['label'] );
396
397
                if ( ! empty( $address_field['required'] ) ) {
398
                    $label .= "<span class='text-danger'> *</span>";
399
                }
400
401
                $html = getpaid_get_states_select_markup(
402
                    sanitize_text_field( $_GET['country'] ),
403
                    $value,
404
                    $placeholder,
405
                    $label,
406
                    $description,
407
                    ! empty( $address_field['required'] ),
408
                    $wrap_class,
409
                    sanitize_text_field( $_GET['name'] )
410
                );
411
412
                wp_send_json_success( $html );
413
                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...
414
415
            }
416
}
417
418
        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...
419
    }
420
421
    /**
422
     * Recalculates invoice totals.
423
     */
424
    public static function recalculate_invoice_totals() {
425
426
        // Verify nonce.
427
        check_ajax_referer( 'wpinv-nonce' );
428
429
        if ( ! wpinv_current_user_can_manage_invoicing() ) {
430
            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...
431
        }
432
433
        // We need an invoice.
434
        if ( empty( $_POST['post_id'] ) ) {
435
            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...
436
        }
437
438
        // Fetch the invoice.
439
        $invoice = new WPInv_Invoice( intval( $_POST['post_id'] ) );
440
441
        // Ensure it exists.
442
        if ( ! $invoice->get_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
        // Maybe set the country, state, currency.
447
        foreach ( array( 'country', 'state', 'currency', 'vat_number', 'discount_code' ) as $key ) {
448
            if ( isset( $_POST[ $key ] ) ) {
449
                $method = "set_$key";
450
                $invoice->$method( sanitize_text_field( $_POST[ $key ] ) );
451
            }
452
        }
453
454
        // Maybe disable taxes.
455
        $invoice->set_disable_taxes( ! empty( $_POST['taxes'] ) );
456
457
        // Discount code.
458
        if ( ! $invoice->is_paid() && ! $invoice->is_refunded() ) {
459
            $discount = new WPInv_Discount( $invoice->get_discount_code() );
460
            if ( $discount->exists() ) {
461
                $invoice->add_discount( getpaid_calculate_invoice_discount( $invoice, $discount ) );
462
            } else {
463
                $invoice->remove_discount( 'discount_code' );
464
            }
465
        }
466
467
        // Recalculate totals.
468
        $invoice->recalculate_total();
469
470
        $total        = wpinv_price( $invoice->get_total(), $invoice->get_currency() );
471
        $suscriptions = getpaid_get_invoice_subscriptions( $invoice );
472
        if ( is_a( $suscriptions, 'WPInv_Subscription' ) && $invoice->is_recurring() && $invoice->is_parent() && $invoice->get_total() != $invoice->get_recurring_total() ) {
473
            $recurring_total = wpinv_price( $invoice->get_recurring_total(), $invoice->get_currency() );
474
            $total          .= '<small class="form-text text-muted">' . sprintf( __( 'Recurring Price: %s', 'invoicing' ), $recurring_total ) . '</small>';
475
        }
476
477
        $totals = array(
478
            'subtotal' => wpinv_price( $invoice->get_subtotal(), $invoice->get_currency() ),
479
            'discount' => wpinv_price( $invoice->get_total_discount(), $invoice->get_currency() ),
480
            'tax'      => wpinv_price( $invoice->get_total_tax(), $invoice->get_currency() ),
481
            'total'    => $total,
482
        );
483
484
        $totals = apply_filters( 'getpaid_invoice_totals', $totals, $invoice );
485
486
        wp_send_json_success( compact( 'totals' ) );
487
    }
488
489
    /**
490
     * Get items belonging to a given invoice.
491
     */
492
    public static function get_invoice_items() {
493
494
        // Verify nonce.
495
        check_ajax_referer( 'wpinv-nonce' );
496
497
        if ( ! wpinv_current_user_can_manage_invoicing() ) {
498
            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...
499
        }
500
501
        // We need an invoice and items.
502
        if ( empty( $_POST['post_id'] ) ) {
503
            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...
504
        }
505
506
        // Fetch the invoice.
507
        $invoice = new WPInv_Invoice( intval( $_POST['post_id'] ) );
508
509
        // Ensure it exists.
510
        if ( ! $invoice->get_id() ) {
511
            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...
512
        }
513
514
        // Return an array of invoice items.
515
        $items = array();
516
517
        foreach ( $invoice->get_items() as $item ) {
518
            $items[] = $item->prepare_data_for_invoice_edit_ajax( $invoice->get_currency(), $invoice->is_renewal() );
519
        }
520
521
        wp_send_json_success( compact( 'items' ) );
522
    }
523
524
    /**
525
     * Edits an invoice item.
526
     */
527
    public static function edit_invoice_item() {
528
529
        // Verify nonce.
530
        check_ajax_referer( 'wpinv-nonce' );
531
532
        if ( ! wpinv_current_user_can_manage_invoicing() ) {
533
            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...
534
        }
535
536
        // We need an invoice and item details.
537
        if ( empty( $_POST['post_id'] ) || empty( $_POST['data'] ) ) {
538
            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...
539
        }
540
541
        // Fetch the invoice.
542
        $invoice = new WPInv_Invoice( intval( $_POST['post_id'] ) );
543
544
        // Ensure it exists and its not been paid for.
545
        if ( ! $invoice->get_id() || $invoice->is_paid() || $invoice->is_refunded() ) {
546
            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...
547
        }
548
549
        // Format the data.
550
        $data = wp_kses_post_deep( wp_unslash( wp_list_pluck( $_POST['data'], 'value', 'field' ) ) );
551
552
        // Ensure that we have an item id.
553
        if ( empty( $data['id'] ) ) {
554
            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...
555
        }
556
557
        // Abort if the invoice does not have the specified item.
558
        $item = $invoice->get_item( (int) $data['id'] );
559
560
        if ( empty( $item ) ) {
561
            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...
562
        }
563
564
        // Update the item.
565
        $item->set_price( getpaid_standardize_amount( $data['price'] ) );
566
        $item->set_name( sanitize_text_field( $data['name'] ) );
567
        $item->set_description( wp_kses_post( $data['description'] ) );
568
        $item->set_quantity( floatval( $data['quantity'] ) );
569
570
        // Add it to the invoice.
571
        $error = $invoice->add_item( $item );
572
        $alert = false;
573
        if ( is_wp_error( $error ) ) {
574
            $alert = $error->get_error_message();
575
        }
576
577
        // Update totals.
578
        $invoice->recalculate_total();
579
580
        // Save the invoice.
581
        $invoice->save();
582
583
        // Return an array of invoice items.
584
        $items = array();
585
586
        foreach ( $invoice->get_items() as $item ) {
587
            $items[] = $item->prepare_data_for_invoice_edit_ajax( $invoice->get_currency() );
588
        }
589
590
        wp_send_json_success( compact( 'items', 'alert' ) );
591
    }
592
593
    /**
594
     * Creates an invoice item.
595
     */
596
    public static function create_invoice_item() {
597
598
        // Verify nonce.
599
        check_ajax_referer( 'wpinv-nonce' );
600
601
        // We need an invoice and item details.
602
        if ( empty( $_POST['invoice_id'] ) || empty( $_POST['_wpinv_quick'] ) ) {
603
            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...
604
        }
605
606
        // Fetch the invoice.
607
        $invoice = new WPInv_Invoice( intval( $_POST['invoice_id'] ) );
608
609
        // Ensure it exists and its not been paid for.
610
        if ( ! $invoice->get_id() || $invoice->is_paid() || $invoice->is_refunded() ) {
611
            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...
612
        }
613
614
        if ( ! wpinv_current_user_can( 'invoice_create_item', array( 'invoice' => $invoice ) ) ) {
615
            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...
616
        }
617
618
        // Format the data.
619
        $data = wp_kses_post_deep( wp_unslash( $_POST['_wpinv_quick'] ) );
620
621
        $item = new WPInv_Item();
622
        $item->set_price( getpaid_standardize_amount( $data['price'] ) );
623
        $item->set_name( sanitize_text_field( $data['name'] ) );
624
        $item->set_description( wp_kses_post( $data['description'] ) );
625
        $item->set_type( sanitize_text_field( $data['type'] ) );
626
        $item->set_vat_rule( sanitize_text_field( $data['vat_rule'] ) );
627
        $item->set_vat_class( sanitize_text_field( $data['vat_class'] ) );
628
        $item->set_status( 'publish' );
629
        $item->save();
630
631
        if ( ! $item->exists() ) {
632
            $alert = __( 'Could not create invoice item. Please try again.', 'invoicing' );
633
            wp_send_json_success( compact( 'alert' ) );
634
        }
635
636
        if ( ! empty( $data['one-time'] ) ) {
637
            update_post_meta( $item->get_id(), '_wpinv_one_time', 'yes' );
638
        }
639
640
        $item = new GetPaid_Form_Item( $item->get_id() );
641
        $item->set_quantity( floatval( $data['qty'] ) );
642
643
        // Add it to the invoice.
644
        $error = $invoice->add_item( $item );
645
        $alert = false;
0 ignored issues
show
Unused Code introduced by
The assignment to $alert is dead and can be removed.
Loading history...
646
647
        if ( is_wp_error( $error ) ) {
648
            $alert = $error->get_error_message();
649
            wp_send_json_success( compact( 'alert' ) );
650
         }
651
652
        // Update totals.
653
        $invoice->recalculate_total();
654
655
        // Save the invoice.
656
        $invoice->save();
657
658
        // Save the invoice.
659
        $invoice->recalculate_total();
660
        $invoice->save();
661
        ob_start();
662
        GetPaid_Meta_Box_Invoice_Items::output_row( GetPaid_Meta_Box_Invoice_Items::get_columns( $invoice ), $item, $invoice );
663
        $row = ob_get_clean();
664
        wp_send_json_success( compact( 'row' ) );
665
    }
666
667
    /**
668
     * Deletes an invoice item.
669
     */
670
    public static function remove_invoice_item() {
671
672
        // Verify nonce.
673
        check_ajax_referer( 'wpinv-nonce' );
674
675
        if ( ! wpinv_current_user_can_manage_invoicing() ) {
676
            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...
677
        }
678
679
        // We need an invoice and an item.
680
        if ( empty( $_POST['post_id'] ) || empty( $_POST['item_id'] ) ) {
681
            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...
682
        }
683
684
        // Fetch the invoice.
685
        $invoice = new WPInv_Invoice( intval( $_POST['post_id'] ) );
686
687
        // Ensure it exists and its not been paid for.
688
        if ( ! $invoice->get_id() || $invoice->is_paid() || $invoice->is_refunded() ) {
689
            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...
690
        }
691
692
        // Abort if the invoice does not have the specified item.
693
        $item = $invoice->get_item( (int) $_POST['item_id'] );
694
695
        if ( empty( $item ) ) {
696
            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...
697
        }
698
699
        $invoice->remove_item( (int) $_POST['item_id'] );
700
701
        // Update totals.
702
        $invoice->recalculate_total();
703
704
        // Save the invoice.
705
        $invoice->save();
706
707
        // Return an array of invoice items.
708
        $items = array();
709
710
        foreach ( $invoice->get_items() as $item ) {
711
            $items[] = $item->prepare_data_for_invoice_edit_ajax( $invoice->get_currency() );
712
        }
713
714
        wp_send_json_success( compact( 'items' ) );
715
    }
716
717
    /**
718
     * Adds an item to an invoice.
719
     */
720
    public static function recalculate_full_prices() {
721
722
        // Verify nonce.
723
        check_ajax_referer( 'wpinv-nonce' );
724
725
        // We need an invoice and item.
726
        if ( empty( $_POST['post_id'] ) ) {
727
            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...
728
        }
729
730
        // Fetch the invoice.
731
        $invoice = new WPInv_Invoice( intval( $_POST['post_id'] ) );
732
        $alert   = false;
0 ignored issues
show
Unused Code introduced by
The assignment to $alert is dead and can be removed.
Loading history...
733
734
        // Ensure it exists and its not been paid for.
735
        if ( ! $invoice->get_id() || $invoice->is_paid() || $invoice->is_refunded() ) {
736
            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...
737
        }
738
739
        if ( ! wpinv_current_user_can( 'invoice_recalculate_full_prices', array( 'invoice' => $invoice ) ) ) {
740
            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...
741
        }
742
743
        $invoice->set_items( array() );
744
745
        if ( ! empty( $_POST['getpaid_items'] ) ) {
746
747
            foreach ( wp_kses_post_deep( $_POST['getpaid_items'] ) as $item_id => $args ) {
748
                $item = new GetPaid_Form_Item( $item_id );
749
750
                if ( $item->exists() ) {
751
                    $item->set_price( getpaid_standardize_amount( $args['price'] ) );
752
                    $item->set_quantity( floatval( $args['quantity'] ) );
753
                    $item->set_name( sanitize_text_field( $args['name'] ) );
754
                    $item->set_description( wp_kses_post( $args['description'] ) );
755
                    $invoice->add_item( $item );
756
                }
757
            }
758
}
759
760
        $invoice->set_disable_taxes( ! empty( $_POST['disable_taxes'] ) );
761
762
        // Maybe set the country, state, currency.
763
        foreach ( array( 'wpinv_country', 'wpinv_state', 'wpinv_currency', 'wpinv_vat_number', 'wpinv_discount_code' ) as $key ) {
764
            if ( isset( $_POST[ $key ] ) ) {
765
                $_key   = str_replace( 'wpinv_', '', $key );
766
                $method = "set_$_key";
767
                $invoice->$method( sanitize_text_field( $_POST[ $key ] ) );
768
            }
769
        }
770
771
        $discount = new WPInv_Discount( $invoice->get_discount_code() );
772
        if ( $discount->exists() ) {
773
            $invoice->add_discount( getpaid_calculate_invoice_discount( $invoice, $discount ) );
774
        } else {
775
            $invoice->remove_discount( 'discount_code' );
776
        }
777
778
        // Save the invoice.
779
        $invoice->recalculate_total();
780
        $invoice->save();
781
        ob_start();
782
        GetPaid_Meta_Box_Invoice_Items::output( get_post( $invoice->get_id() ), $invoice );
783
        $table = ob_get_clean();
784
        wp_send_json_success( compact( 'table' ) );
785
    }
786
787
    /**
788
     * Adds an item to an invoice.
789
     */
790
    public static function admin_add_invoice_item() {
791
792
        // Verify nonce.
793
        check_ajax_referer( 'wpinv-nonce' );
794
795
        // We need an invoice and item.
796
        if ( empty( $_POST['post_id'] ) || empty( $_POST['item_id'] ) ) {
797
            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...
798
        }
799
800
        // Fetch the invoice.
801
        $invoice = new WPInv_Invoice( intval( $_POST['post_id'] ) );
802
        $alert   = false;
0 ignored issues
show
Unused Code introduced by
The assignment to $alert is dead and can be removed.
Loading history...
803
804
        // Ensure it exists and its not been paid for.
805
        if ( ! $invoice->get_id() || $invoice->is_paid() || $invoice->is_refunded() ) {
806
            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...
807
        }
808
809
        // Add the item.
810
        $item  = new GetPaid_Form_Item( (int) $_POST['item_id'] );
811
812
        if ( ! wpinv_current_user_can( 'invoice_add_item', array( 'invoice' => $invoice, 'invoice_item' => $item ) ) ) {
813
            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...
814
        }
815
816
        $error = $invoice->add_item( $item );
817
818
        if ( is_wp_error( $error ) ) {
819
            $alert = $error->get_error_message();
820
            wp_send_json_success( compact( 'alert' ) );
821
        }
822
823
        // Save the invoice.
824
        $invoice->recalculate_total();
825
        $invoice->save();
826
        ob_start();
827
        GetPaid_Meta_Box_Invoice_Items::output_row( GetPaid_Meta_Box_Invoice_Items::get_columns( $invoice ), $item, $invoice );
828
        $row = ob_get_clean();
829
        wp_send_json_success( compact( 'row' ) );
830
    }
831
832
    /**
833
     * Adds a items to an invoice.
834
     */
835
    public static function add_invoice_items() {
836
837
        // Verify nonce.
838
        check_ajax_referer( 'wpinv-nonce' );
839
840
        if ( ! wpinv_current_user_can_manage_invoicing() ) {
841
            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...
842
        }
843
844
        // We need an invoice and items.
845
        if ( empty( $_POST['post_id'] ) || empty( $_POST['items'] ) ) {
846
            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...
847
        }
848
849
        // Fetch the invoice.
850
        $invoice = new WPInv_Invoice( intval( $_POST['post_id'] ) );
851
        $alert   = false;
852
853
        // Ensure it exists and its not been paid for.
854
        if ( ! $invoice->get_id() || $invoice->is_paid() || $invoice->is_refunded() ) {
855
            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...
856
        }
857
858
        // Add the items.
859
        foreach ( wp_kses_post_deep( wp_unslash( $_POST['items'] ) ) as $data ) {
860
861
            $item = new GetPaid_Form_Item( (int) $data['id'] );
862
863
            if ( is_numeric( $data['qty'] ) && (float) $data['qty'] > 0 ) {
864
                $item->set_quantity( floatval( $data['qty'] ) );
865
            }
866
867
            if ( $item->get_id() > 0 ) {
868
                $error = $invoice->add_item( $item );
869
870
                if ( is_wp_error( $error ) ) {
871
                    $alert = $error->get_error_message();
872
                }
873
}
874
}
875
876
        // Save the invoice.
877
        $invoice->recalculate_total();
878
        $invoice->save();
879
880
        // Return an array of invoice items.
881
        $items = array();
882
883
        foreach ( $invoice->get_items() as $item ) {
884
            $items[] = $item->prepare_data_for_invoice_edit_ajax( $invoice->get_currency() );
885
        }
886
887
        wp_send_json_success( compact( 'items', 'alert' ) );
888
    }
889
890
    /**
891
     * Retrieves items that should be added to an invoice.
892
     */
893
    public static function get_invoicing_items() {
894
895
        // Verify nonce.
896
        check_ajax_referer( 'wpinv-nonce' );
897
898
        if ( ! wpinv_current_user_can_manage_invoicing() ) {
899
            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...
900
        }
901
902
        // We need a search term.
903
        if ( empty( $_GET['search'] ) ) {
904
            wp_send_json_success( array() );
905
        }
906
907
        // Retrieve items.
908
        $item_args = array(
909
            'post_type'      => 'wpi_item',
910
            'orderby'        => 'title',
911
            'order'          => 'ASC',
912
            'posts_per_page' => -1,
913
            'post_status'    => array( 'publish' ),
914
            's'              => sanitize_text_field( urldecode( $_GET['search'] ) ),
915
            'meta_query'     => array(
916
                array(
917
                    'key'     => '_wpinv_type',
918
                    'compare' => '!=',
919
                    'value'   => 'package',
920
                ),
921
                array(
922
                    'key'     => '_wpinv_one_time',
923
                    'compare' => 'NOT EXISTS',
924
                ),
925
            ),
926
        );
927
928
        if ( ! empty( $_GET['ignore'] ) ) {
929
            $item_args['exclude'] = wp_parse_id_list( sanitize_text_field( $_GET['ignore'] ) );
930
        }
931
932
        $items = get_posts( apply_filters( 'getpaid_ajax_invoice_items_query_args', $item_args ) );
933
        $data  = array();
934
935
        $is_payment_form = ( ! empty( $_GET['post_id'] ) && 'wpi_payment_form' == get_post_type( (int) $_GET['post_id'] ) );
936
937
        foreach ( $items as $item ) {
938
            $item      = new GetPaid_Form_Item( $item );
939
            $data[] = array(
940
                'id'        => (int) $item->get_id(),
941
                'text'      => strip_tags( $item->get_name() ),
942
                'form_data' => $is_payment_form ? $item->prepare_data_for_use( false ) : '',
943
            );
944
        }
945
946
        wp_send_json_success( $data );
947
948
    }
949
950
    /**
951
     * Retrieves items that should be added to an invoice.
952
     */
953
    public static function get_customers() {
954
        // Verify nonce.
955
        check_ajax_referer( 'wpinv-nonce' );
956
957
        $invoice_id = ! empty( $_REQUEST['post_id'] ) ? (int) $_REQUEST['post_id'] : 0;
958
959
        // Can the user manage the plugin?
960
        if ( ! wpinv_current_user_can( 'invoice_get_customers', array( 'invoice_id' => $invoice_id ) ) ) {
961
            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...
962
        }
963
964
        // We need a search term.
965
        if ( empty( $_GET['search'] ) ) {
966
            wp_send_json_success( array() );
967
        }
968
969
        // Retrieve customers.
970
971
        $customer_args = array(
972
            'fields'         => array( 'ID', 'user_email', 'display_name' ),
973
            'orderby'        => 'display_name',
974
            'search'         => '*' . sanitize_text_field( $_GET['search'] ) . '*',
975
            'search_columns' => array( 'user_login', 'user_email', 'display_name' ),
976
        );
977
978
        $customers = get_users( apply_filters( 'getpaid_ajax_invoice_customers_query_args', $customer_args ) );
979
        $data      = array();
980
981
        foreach ( $customers as $customer ) {
982
            $data[] = array(
983
                'id'   => (int) $customer->ID,
984
                'text' => strip_tags( sprintf( _x( '%1$s (%2$s)', 'user dropdown', 'invoicing' ), $customer->display_name, $customer->user_email ) ),
985
            );
986
        }
987
988
        wp_send_json_success( $data );
989
990
    }
991
992
    /**
993
     * Retrieves the states field for AUI forms.
994
     */
995
    public static function get_aui_states_field() {
996
997
        // We need a country.
998
        if ( empty( $_GET['country'] ) ) {
999
            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...
1000
        }
1001
1002
        $states = wpinv_get_country_states( sanitize_text_field( $_GET['country'] ) );
1003
        $state  = isset( $_GET['state'] ) ? sanitize_text_field( $_GET['state'] ) : wpinv_get_default_state();
1004
        $name   = isset( $_GET['name'] ) ? sanitize_text_field( $_GET['name'] ) : 'wpinv_state';
1005
        $class  = isset( $_GET['class'] ) ? sanitize_text_field( $_GET['class'] ) : 'form-control-sm';
1006
1007
        if ( empty( $states ) ) {
1008
1009
            $html = aui()->input(
1010
                array(
1011
                    'type'        => 'text',
1012
                    'id'          => 'wpinv_state',
1013
                    'name'        => $name,
1014
                    'label'       => __( 'State', 'invoicing' ),
1015
                    'label_type'  => 'vertical',
1016
                    'placeholder' => __( 'State', 'invoicing' ),
1017
                    'class'       => $class,
1018
                    'value'       => $state,
1019
                )
1020
            );
1021
1022
        } else {
1023
1024
            $html = aui()->select(
1025
                array(
1026
                    'id'               => 'wpinv_state',
1027
                    'name'             => $name,
1028
                    'label'            => __( 'State', 'invoicing' ),
1029
                    'label_type'       => 'vertical',
1030
                    'placeholder'      => __( 'Select a state', 'invoicing' ),
1031
                    'class'            => $class,
1032
                    'value'            => $state,
1033
                    'options'          => $states,
1034
                    'data-allow-clear' => 'false',
1035
                    'select2'          => true,
1036
                )
1037
            );
1038
1039
        }
1040
1041
        wp_send_json_success(
1042
            array(
1043
                'html'   => $html,
1044
                'select' => ! empty( $states ),
1045
            )
1046
        );
1047
1048
    }
1049
1050
    /**
1051
     * Refresh prices.
1052
     *
1053
     * @since 1.0.19
1054
     */
1055
    public static function payment_form_refresh_prices() {
1056
1057
        // ... form fields...
1058
        if ( empty( $_POST['getpaid_payment_form_submission'] ) ) {
1059
            esc_html_e( 'Error: Reload the page and try again.', 'invoicing' );
1060
            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...
1061
        }
1062
1063
        // Load the submission.
1064
        $submission = new GetPaid_Payment_Form_Submission();
1065
1066
        // Do we have an error?
1067
        if ( ! empty( $submission->last_error ) ) {
1068
            wp_send_json_error(
1069
                array(
1070
                    'code'  => $submission->last_error_code,
1071
                    'error' => $submission->last_error,
1072
                )
1073
            );
1074
        }
1075
1076
        // Prepare the response.
1077
        $response = new GetPaid_Payment_Form_Submission_Refresh_Prices( $submission );
1078
1079
        // Filter the response.
1080
        $response = apply_filters( 'getpaid_payment_form_ajax_refresh_prices', $response->response, $submission );
1081
1082
        wp_send_json_success( $response );
1083
    }
1084
1085
    /**
1086
	 * Handles file uploads.
1087
	 *
1088
	 * @since       1.0.0
1089
	 * @return      void
1090
	 */
1091
	public static function file_upload() {
1092
1093
        // Check nonce.
1094
        check_ajax_referer( 'getpaid_form_nonce' );
1095
1096
        if ( empty( $_POST['form_id'] ) || empty( $_POST['field_name'] ) || empty( $_FILES['file'] ) ) {
1097
            wp_die( esc_html_e( 'Bad Request', 'invoicing' ), 400 );
1098
        }
1099
1100
        // Fetch form.
1101
        $form = new GetPaid_Payment_Form( intval( $_POST['form_id'] ) );
1102
1103
        if ( ! $form->is_active() ) {
1104
            wp_send_json_error( __( 'Payment form not active', 'invoicing' ) );
1105
        }
1106
1107
        // Fetch appropriate field.
1108
        $upload_field = current( wp_list_filter( $form->get_elements(), array( 'id' => sanitize_text_field( $_POST['field_name'] ) ) ) );
1109
        if ( empty( $upload_field ) ) {
1110
            wp_send_json_error( __( 'Invalid upload field.', 'invoicing' ) );
1111
        }
1112
1113
        // Prepare allowed file types.
1114
        $file_types = isset( $upload_field['file_types'] ) ? $upload_field['file_types'] : array( 'jpg|jpeg|jpe', 'gif', 'png' );
1115
        $all_types  = getpaid_get_allowed_mime_types();
1116
        $mime_types = array();
1117
1118
        foreach ( $file_types as $file_type ) {
1119
            if ( isset( $all_types[ $file_type ] ) ) {
1120
                $mime_types[] = $all_types[ $file_type ];
1121
            }
1122
        }
1123
1124
        if ( ! in_array( $_FILES['file']['type'], $mime_types ) ) {
1125
            wp_send_json_error( __( 'Unsupported file type.', 'invoicing' ) );
1126
        }
1127
1128
        // Upload file.
1129
        $file_name = explode( '.', strtolower( $_FILES['file']['name'] ) );
1130
        $file_name = uniqid( 'getpaid-' ) . '.' . array_pop( $file_name );
1131
1132
        $uploaded = wp_upload_bits(
1133
            $file_name,
1134
            null,
1135
            file_get_contents( $_FILES['file']['tmp_name'] )
1136
        );
1137
1138
        if ( ! empty( $uploaded['error'] ) ) {
1139
            wp_send_json_error( $uploaded['error'] );
1140
        }
1141
1142
        // Retrieve response.
1143
        $response = sprintf(
1144
            '<input type="hidden" name="%s[%s]" value="%s" />',
1145
            esc_attr( sanitize_text_field( $_POST['field_name'] ) ),
1146
            esc_url( $uploaded['url'] ),
1147
            esc_attr( sanitize_text_field( strtolower( $_FILES['file']['name'] ) ) )
1148
        );
1149
1150
        wp_send_json_success( $response );
1151
1152
	}
1153
1154
}
1155
1156
WPInv_Ajax::init();
1157