Passed
Pull Request — master (#416)
by Brian
10:03
created

WPInv_Ajax::payment_form()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 16
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 7
c 1
b 0
f 0
dl 0
loc 16
rs 10
cc 2
nc 2
nop 0
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
            'buy_items'                   => true,
102
            'payment_form_refresh_prices' => true,
103
            'ip_geolocation'              => true,
104
        );
105
106
        foreach ( $ajax_events as $ajax_event => $nopriv ) {
107
            add_action( 'wp_ajax_wpinv_' . $ajax_event, array( __CLASS__, $ajax_event ) );
108
            add_action( 'wp_ajax_getpaid_' . $ajax_event, array( __CLASS__, $ajax_event ) );
109
110
            if ( $nopriv ) {
111
                add_action( 'wp_ajax_nopriv_wpinv_' . $ajax_event, array( __CLASS__, $ajax_event ) );
112
                add_action( 'wp_ajax_nopriv_getpaid_' . $ajax_event, array( __CLASS__, $ajax_event ) );
113
                add_action( 'wpinv_ajax_' . $ajax_event, array( __CLASS__, $ajax_event ) );
114
            }
115
        }
116
    }
117
    
118
    public static function add_note() {
119
        check_ajax_referer( 'add-invoice-note', '_nonce' );
120
121
        if ( ! wpinv_current_user_can_manage_invoicing() ) {
122
            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...
123
        }
124
125
        $post_id   = absint( $_POST['post_id'] );
126
        $note      = wp_kses_post( trim( stripslashes( $_POST['note'] ) ) );
127
        $note_type = sanitize_text_field( $_POST['note_type'] );
128
129
        $is_customer_note = $note_type == 'customer' ? 1 : 0;
130
131
        if ( $post_id > 0 ) {
132
            $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

132
            $note_id = /** @scrutinizer ignore-deprecated */ wpinv_insert_payment_note( $post_id, $note, $is_customer_note );
Loading history...
133
134
            if ( $note_id > 0 && !is_wp_error( $note_id ) ) {
135
                wpinv_get_invoice_note_line_item( $note_id );
136
            }
137
        }
138
139
        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...
140
    }
141
142
    public static function delete_note() {
143
        check_ajax_referer( 'delete-invoice-note', '_nonce' );
144
145
        if ( !wpinv_current_user_can_manage_invoicing() ) {
146
            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...
147
        }
148
149
        $note_id = (int)$_POST['note_id'];
150
151
        if ( $note_id > 0 ) {
152
            wp_delete_comment( $note_id, true );
153
        }
154
155
        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...
156
    }
157
    
158
    public static function get_states_field() {
159
        echo wpinv_get_states_field();
160
        
161
        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...
162
    }
163
164
    /**
165
     * Retrieves a given user's billing address.
166
     */
167
    public static function get_billing_details() {
168
169
        // Verify nonce.
170
        check_ajax_referer( 'wpinv-nonce' );
171
172
        // Can the user manage the plugin?
173
        if ( ! wpinv_current_user_can_manage_invoicing() ) {
174
            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...
175
        }
176
177
        // Do we have a user id?
178
        $user_id = $_GET['user_id'];
179
180
        if ( empty( $user_id ) || ! is_numeric( $user_id ) ) {
181
            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...
182
        }
183
184
        // Fetch the billing details.
185
        $billing_details    = wpinv_get_user_address( $user_id );
186
        $billing_details    = apply_filters( 'wpinv_ajax_billing_details', $billing_details, $user_id );
187
188
        // unset the user id and email.
189
        $to_ignore = array( 'user_id', 'email' );
190
191
        foreach ( $to_ignore as $key ) {
192
            if ( isset( $billing_details[ $key ] ) ) {
193
                unset( $billing_details[ $key ] );
194
            }
195
        }
196
197
        wp_send_json_success( $billing_details );
198
199
    }
200
201
    /**
202
     * Checks if a new users email is valid.
203
     */
204
    public static function check_new_user_email() {
205
206
        // Verify nonce.
207
        check_ajax_referer( 'wpinv-nonce' );
208
209
        // Can the user manage the plugin?
210
        if ( ! wpinv_current_user_can_manage_invoicing() ) {
211
            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...
212
        }
213
214
        // We need an email address.
215
        if ( empty( $_GET['email'] ) ) {
216
            _e( "Provide the new user's email address", 'invoicing' );
217
            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...
218
        }
219
220
        // Ensure the email is valid.
221
        $email = sanitize_text_field( $_GET['email'] );
222
        if ( ! is_email( $email ) ) {
223
            _e( 'Invalid email address', 'invoicing' );
224
            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...
225
        }
226
227
        // And it does not exist.
228
        if ( email_exists( $email ) ) {
229
            _e( 'A user with this email address already exists', 'invoicing' );
230
            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...
231
        }
232
233
        wp_send_json_success( true );
234
    }
235
    
236
    public static function run_tool() {
237
        check_ajax_referer( 'wpinv-nonce', '_nonce' );
238
        if ( !wpinv_current_user_can_manage_invoicing() ) {
239
            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...
240
        }
241
        
242
        $tool = sanitize_text_field( $_POST['tool'] );
243
        
244
        do_action( 'wpinv_run_tool' );
245
        
246
        if ( !empty( $tool ) ) {
247
            do_action( 'wpinv_tool_' . $tool );
248
        }
249
    }
250
251
    /**
252
     * Retrieves the markup for a payment form.
253
     */
254
    public static function get_payment_form() {
255
256
        // Check nonce.
257
        if ( ! isset( $_GET['nonce'] ) || ! wp_verify_nonce( $_GET['nonce'], 'getpaid_ajax_form' ) ) {
258
            _e( 'Error: Reload the page and try again.', 'invoicing' );
259
            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...
260
        }
261
262
        // Is the request set up correctly?
263
		if ( empty( $_GET['form'] ) && empty( $_GET['item'] ) ) {
264
			echo aui()->alert(
265
				array(
266
					'type'    => 'warning',
267
					'content' => __( 'No payment form or item provided', 'invoicing' ),
268
				)
269
            );
270
            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...
271
        }
272
273
        // Payment form or button?
274
		if ( ! empty( $_GET['form'] ) ) {
275
            getpaid_display_payment_form( $_GET['form'] );
276
		} else if( ! empty( $_GET['invoice'] ) ) {
277
		    echo getpaid_display_invoice_payment_form( $_GET['invoice'] );
278
        } else {
279
			$items = getpaid_convert_items_to_array( $_GET['item'] );
280
		    getpaid_display_item_payment_form( $items );
281
        }
282
283
        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...
284
285
    }
286
287
    /**
288
     * Payment forms.
289
     *
290
     * @since 1.0.18
291
     */
292
    public static function payment_form() {
293
294
        // Check nonce.
295
        check_ajax_referer( 'getpaid_form_nonce' );
296
297
        // ... form fields...
298
        if ( empty( $_POST['getpaid_payment_form_submission'] ) ) {
299
            _e( 'Error: Reload the page and try again.', 'invoicing' );
300
            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...
301
        }
302
303
        // Process the payment form.
304
        $checkout = new GetPaid_Checkout( new GetPaid_Payment_Form_Submission() );
305
        $checkout->process_checkout();
306
307
        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...
308
    }
309
310
    /**
311
     * Payment forms.
312
     *
313
     * @since 1.0.18
314
     */
315
    public static function get_payment_form_states_field() {
316
        global $invoicing;
317
318
        if ( empty( $_GET['country'] ) || empty( $_GET['form'] ) ) {
319
            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...
320
        }
321
322
        $elements = $invoicing->form_elements->get_form_elements( $_GET['form'] );
323
324
        if ( empty( $elements ) ) {
325
            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...
326
        }
327
328
        $address_fields = array();
329
        foreach ( $elements as $element ) {
330
            if ( 'address' === $element['type'] ) {
331
                $address_fields = $element;
332
                break;
333
            }
334
        }
335
336
        if ( empty( $address_fields ) ) {
337
            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...
338
        }
339
340
        foreach( $address_fields['fields'] as $address_field ) {
341
342
            if ( 'wpinv_state' == $address_field['name'] ) {
343
344
                $label = $address_field['label'];
345
346
                if ( ! empty( $address_field['required'] ) ) {
347
                    $label .= "<span class='text-danger'> *</span>";
348
                }
349
350
                $states = wpinv_get_country_states( $_GET['country'] );
351
352
                if ( ! empty( $states ) ) {
353
354
                    $html = aui()->select(
355
                            array(
356
                                'options'          => $states,
357
                                'name'             => esc_attr( $address_field['name'] ),
358
                                'id'               => esc_attr( $address_field['name'] ),
359
                                'placeholder'      => esc_attr( $address_field['placeholder'] ),
360
                                'required'         => (bool) $address_field['required'],
361
                                'no_wrap'          => true,
362
                                'label'            => wp_kses_post( $label ),
363
                                'select2'          => false,
364
                            )
365
                        );
366
367
                } else {
368
369
                    $html = aui()->input(
370
                            array(
371
                                'name'       => esc_attr( $address_field['name'] ),
372
                                'id'         => esc_attr( $address_field['name'] ),
373
                                'required'   => (bool) $address_field['required'],
374
                                'label'      => wp_kses_post( $label ),
375
                                'no_wrap'    => true,
376
                                'type'       => 'text',
377
                            )
378
                        );
379
380
                }
381
382
                wp_send_json_success( str_replace( 'sr-only', '', $html ) );
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
387
        }
388
    
389
        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...
390
    }
391
392
    /**
393
     * Recalculates invoice totals.
394
     */
395
    public static function recalculate_invoice_totals() {
396
397
        // Verify nonce.
398
        check_ajax_referer( 'wpinv-nonce' );
399
400
        if ( ! wpinv_current_user_can_manage_invoicing() ) {
401
            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...
402
        }
403
404
        // We need an invoice.
405
        if ( empty( $_POST['post_id'] ) ) {
406
            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...
407
        }
408
409
        // Fetch the invoice.
410
        $invoice = new WPInv_Invoice( trim( $_POST['post_id'] ) );
411
412
        // Ensure it exists.
413
        if ( ! $invoice->get_id() ) {
414
            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...
415
        }
416
417
        // Maybe set the country, state, currency.
418
        foreach ( array( 'country', 'state', 'currency' ) as $key ) {
419
            if ( isset( $_POST[ $key ] ) ) {
420
                $method = "set_$key";
421
                $invoice->$method( $_POST[ $key ] );
422
            }
423
        }
424
425
        // Maybe disable taxes.
426
        $invoice->set_disable_taxes( ! empty( $_POST['taxes'] ) );
427
428
        // Recalculate totals.
429
        $invoice->recalculate_total();
430
431
        $total = wpinv_price( wpinv_format_amount( $invoice->get_total() ), $invoice->get_currency() );
432
433
        if ( $invoice->is_recurring() && $invoice->is_parent() && $invoice->get_total() != $invoice->get_recurring_total() ) {
434
            $recurring_total = wpinv_price( wpinv_format_amount( $invoice->get_recurring_total() ), $invoice->get_currency() );
435
            $total          .= '<small class="form-text text-muted">' . sprintf( __( 'Recurring Price: %s', 'invoicing' ), $recurring_total ) . '</small>';
436
        }
437
438
        $totals = array(
439
            'subtotal' => wpinv_price( wpinv_format_amount( $invoice->get_subtotal() ), $invoice->get_currency() ),
440
            'discount' => wpinv_price( wpinv_format_amount( $invoice->get_total_discount() ), $invoice->get_currency() ),
441
            'tax'      => wpinv_price( wpinv_format_amount( $invoice->get_total_tax() ), $invoice->get_currency() ),
442
            'total'    => $total,
443
        );
444
445
        $totals = apply_filters( 'getpaid_invoice_totals', $totals, $invoice );
446
447
        wp_send_json_success( compact( 'totals' ) );
448
    }
449
450
    /**
451
     * Get items belonging to a given invoice.
452
     */
453
    public static function get_invoice_items() {
454
455
        // Verify nonce.
456
        check_ajax_referer( 'wpinv-nonce' );
457
458
        if ( ! wpinv_current_user_can_manage_invoicing() ) {
459
            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...
460
        }
461
462
        // We need an invoice and items.
463
        if ( empty( $_POST['post_id'] ) ) {
464
            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...
465
        }
466
467
        // Fetch the invoice.
468
        $invoice = new WPInv_Invoice( trim( $_POST['post_id'] ) );
469
470
        // Ensure it exists.
471
        if ( ! $invoice->get_id() ) {
472
            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...
473
        }
474
475
        // Return an array of invoice items.
476
        $items = array();
477
478
        foreach ( $invoice->get_items() as $item_id => $item ) {
479
            $items[ $item_id ] = $item->prepare_data_for_invoice_edit_ajax(  $invoice->get_currency()  );
480
        }
481
482
        wp_send_json_success( compact( 'items' ) );
483
    }
484
485
    /**
486
     * Edits an invoice item.
487
     */
488
    public static function edit_invoice_item() {
489
490
        // Verify nonce.
491
        check_ajax_referer( 'wpinv-nonce' );
492
493
        if ( ! wpinv_current_user_can_manage_invoicing() ) {
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
        // We need an invoice and item details.
498
        if ( empty( $_POST['post_id'] ) || empty( $_POST['data'] ) ) {
499
            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...
500
        }
501
502
        // Fetch the invoice.
503
        $invoice = new WPInv_Invoice( trim( $_POST['post_id'] ) );
504
505
        // Ensure it exists and its not been paid for.
506
        if ( ! $invoice->get_id() || $invoice->is_paid() || $invoice->is_refunded() ) {
507
            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...
508
        }
509
510
        // Format the data.
511
        $data = wp_list_pluck( $_POST['data'], 'value', 'field' );
512
513
        // Ensure that we have an item id.
514
        if ( empty( $data['id'] ) ) {
515
            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...
516
        }
517
518
        // Abort if the invoice does not have the specified item.
519
        $item = $invoice->get_item( (int) $data['id'] );
520
521
        if ( empty( $item ) ) {
522
            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...
523
        }
524
525
        // Update the item.
526
        $item->set_price( $data['price'] );
527
        $item->set_name( $data['name'] );
528
        $item->set_description( $data['description'] );
529
        $item->set_quantity( $data['quantity'] );
530
531
        // Add it to the invoice.
532
        $error = $invoice->add_item( $item );
533
        $alert = false;
534
        if ( is_wp_error( $error ) ) {
535
            $alert = $error->get_error_message();
536
        }
537
538
        // Update totals.
539
        $invoice->recalculate_total();
540
541
        // Save the invoice.
542
        $invoice->save();
543
544
        // Return an array of invoice items.
545
        $items = array();
546
547
        foreach ( $invoice->get_items() as $item_id => $item ) {
548
            $items[ $item_id ] = $item->prepare_data_for_invoice_edit_ajax(  $invoice->get_currency()  );
549
        }
550
551
        wp_send_json_success( compact( 'items', 'alert' ) );
552
    }
553
554
    /**
555
     * Deletes an invoice item.
556
     */
557
    public static function remove_invoice_item() {
558
559
        // Verify nonce.
560
        check_ajax_referer( 'wpinv-nonce' );
561
562
        if ( ! wpinv_current_user_can_manage_invoicing() ) {
563
            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...
564
        }
565
566
        // We need an invoice and an item.
567
        if ( empty( $_POST['post_id'] ) || empty( $_POST['item_id'] ) ) {
568
            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...
569
        }
570
571
        // Fetch the invoice.
572
        $invoice = new WPInv_Invoice( trim( $_POST['post_id'] ) );
573
574
        // Ensure it exists and its not been paid for.
575
        if ( ! $invoice->get_id() || $invoice->is_paid() || $invoice->is_refunded() ) {
576
            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...
577
        }
578
579
        // Abort if the invoice does not have the specified item.
580
        $item = $invoice->get_item( (int) $_POST['item_id'] );
581
582
        if ( empty( $item ) ) {
583
            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...
584
        }
585
586
        $invoice->remove_item( (int) $_POST['item_id'] );
587
588
        // Update totals.
589
        $invoice->recalculate_total();
590
591
        // Save the invoice.
592
        $invoice->save();
593
594
        // Return an array of invoice items.
595
        $items = array();
596
597
        foreach ( $invoice->get_items() as $item_id => $item ) {
598
            $items[ $item_id ] = $item->prepare_data_for_invoice_edit_ajax(  $invoice->get_currency()  );
599
        }
600
601
        wp_send_json_success( compact( 'items' ) );
602
    }
603
604
    /**
605
     * Adds a items to an invoice.
606
     */
607
    public static function add_invoice_items() {
608
609
        // Verify nonce.
610
        check_ajax_referer( 'wpinv-nonce' );
611
612
        if ( ! wpinv_current_user_can_manage_invoicing() ) {
613
            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...
614
        }
615
616
        // We need an invoice and items.
617
        if ( empty( $_POST['post_id'] ) || empty( $_POST['items'] ) ) {
618
            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...
619
        }
620
621
        // Fetch the invoice.
622
        $invoice = new WPInv_Invoice( trim( $_POST['post_id'] ) );
623
        $alert   = false;
624
625
        // Ensure it exists and its not been paid for.
626
        if ( ! $invoice->get_id() || $invoice->is_paid() || $invoice->is_refunded() ) {
627
            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...
628
        }
629
630
        // Add the items.
631
        foreach ( $_POST['items'] as $data ) {
632
633
            $item = new GetPaid_Form_Item( $data[ 'id' ] );
634
635
            if ( is_numeric( $data[ 'qty' ] ) && (int) $data[ 'qty' ] > 0 ) {
636
                $item->set_quantity( $data[ 'qty' ] );
637
            }
638
639
            if ( $item->get_id() > 0 ) {
640
                $error = $invoice->add_item( $item );
641
642
                if ( is_wp_error( $error ) ) {
643
                    $alert = $error->get_error_message();
644
                }
645
646
            }
647
648
        }
649
650
        // Save the invoice.
651
        $invoice->recalculate_total();
652
        $invoice->save();
653
654
        // Return an array of invoice items.
655
        $items = array();
656
657
        foreach ( $invoice->get_items() as $item_id => $item ) {
658
            $items[ $item_id ] = $item->prepare_data_for_invoice_edit_ajax( $invoice->get_currency() );
659
        }
660
661
        wp_send_json_success( compact( 'items', 'alert' ) );
662
    }
663
664
    /**
665
     * Retrieves items that should be added to an invoice.
666
     */
667
    public static function get_invoicing_items() {
668
669
        // Verify nonce.
670
        check_ajax_referer( 'wpinv-nonce' );
671
672
        if ( ! wpinv_current_user_can_manage_invoicing() ) {
673
            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...
674
        }
675
676
        // We need a search term.
677
        if ( empty( $_GET['search'] ) ) {
678
            wp_send_json_success( array() );
679
        }
680
681
        // Retrieve items.
682
        $item_args = array(
683
            'post_type'      => 'wpi_item',
684
            'orderby'        => 'title',
685
            'order'          => 'ASC',
686
            'posts_per_page' => -1,
687
            'post_status'    => array( 'publish' ),
688
            's'              => trim( $_GET['search'] ),
689
            'meta_query'     => array(
690
                array(
691
                    'key'       => '_wpinv_type',
692
                    'compare'   => '!=',
693
                    'value'     => 'package'
694
                )
695
            )
696
        );
697
698
        $items = get_posts( apply_filters( 'getpaid_ajax_invoice_items_query_args', $item_args ) );
699
        $data  = array();
700
701
        foreach ( $items as $item ) {
702
            $item      = new GetPaid_Form_Item( $item );
703
            $data[] = array(
704
                'id'   => $item->get_id(),
705
                'text' => $item->get_name()
706
            );
707
        }
708
709
        wp_send_json_success( $data );
710
711
    }
712
713
    /**
714
     * Retrieves the states field for AUI forms.
715
     */
716
    public static function get_aui_states_field() {
717
718
        // Verify nonce.
719
        check_ajax_referer( 'wpinv-nonce' );
720
721
        // We need a country.
722
        if ( empty( $_GET['country'] ) ) {
723
            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...
724
        }
725
726
        $states = wpinv_get_country_states( trim( $_GET['country'] ) );
727
        $state  = isset( $_GET['state'] ) ? trim( $_GET['state'] ) : wpinv_get_default_state();
728
729
        if ( empty( $states ) ) {
730
731
            $html = aui()->input(
732
                array(
733
                    'type'        => 'text',
734
                    'id'          => 'wpinv_state',
735
                    'name'        => 'wpinv_state',
736
                    'label'       => __( 'State', 'invoicing' ),
737
                    'label_type'  => 'vertical',
738
                    'placeholder' => 'Liège',
739
                    'class'       => 'form-control-sm',
740
                    'value'       => $state,
741
                )
742
            );
743
744
        } else {
745
746
            $html = aui()->select(
747
                array(
748
                    'id'          => 'wpinv_state',
749
                    'name'        => 'wpinv_state',
750
                    'label'       => __( 'State', 'invoicing' ),
751
                    'label_type'  => 'vertical',
752
                    'placeholder' => __( 'Select a state', 'invoicing' ),
753
                    'class'       => 'form-control-sm',
754
                    'value'       => $state,
755
                    'options'     => $states,
756
                    'data-allow-clear' => 'false',
757
                    'select2'          => true,
758
                )
759
            );
760
761
        }
762
763
        wp_send_json_success(
764
            array(
765
                'html'   => $html,
766
                'select' => ! empty ( $states )
767
            )
768
        );
769
770
    }
771
772
    /**
773
     * IP geolocation.
774
     *
775
     * @since 1.0.19
776
     */
777
    public static function ip_geolocation() {
778
779
        // Check nonce.
780
        check_ajax_referer( 'getpaid-ip-location' );
781
782
        // IP address.
783
        if ( empty( $_GET['ip'] ) || ! rest_is_ip_address( $_GET['ip'] ) ) {
784
            _e( 'Invalid IP Address.', 'invoicing' );
785
            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...
786
        }
787
788
        // Retrieve location info.
789
        $location = getpaid_geolocate_ip_address( $_GET['ip'] );
790
791
        if ( empty( $location ) ) {
792
            _e( 'Unable to find geolocation for the IP Address.', 'invoicing' );
793
            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...
794
        }
795
796
        // Sorry.
797
        extract( $location );
798
799
        // Prepare the address.
800
        $content = '';
801
802
        if ( ! empty( $location['city'] ) ) {
803
            $content .=  $location['city']  . ', ';
804
        }
805
        
806
        if ( ! empty( $location['region'] ) ) {
807
            $content .=  $location['region']  . ', ';
808
        }
809
        
810
        $content .=  $location['country'] . ' (' . $location['iso'] . ')';
811
812
        $location['address'] = $content;
813
814
        $content  = '<p>'. sprintf( __( '<b>Address:</b> %s', 'invoicing' ), $content ) . '</p>';
815
        $content .= '<p>'. $location['credit'] . '</p>';
816
817
        $location['content'] = $content;
818
819
        wpinv_get_template( 'geolocation.php', $location );
820
821
        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...
822
    }
823
824
    /**
825
     * Refresh prices.
826
     *
827
     * @since 1.0.19
828
     */
829
    public static function payment_form_refresh_prices() {
830
831
        // Check nonce.
832
        check_ajax_referer( 'getpaid_form_nonce' );
833
834
        // ... form fields...
835
        if ( empty( $_POST['getpaid_payment_form_submission'] ) ) {
836
            _e( 'Error: Reload the page and try again.', 'invoicing' );
837
            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...
838
        }
839
840
        // Load the submission.
841
        $submission = new GetPaid_Payment_Form_Submission();
842
843
        // Do we have an error?
844
        if ( ! empty( $submission->last_error ) ) {
845
            echo $submission->last_error;
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
        // Prepare the result.
850
        $result = array(
851
852
            'submission_id' => $submission->id,
853
            'has_recurring' => $submission->has_recurring,
854
            'is_free'       => $submission->get_payment_details(),
855
856
            'totals'        => array(
857
                'subtotal'  => wpinv_price( wpinv_format_amount( $submission->subtotal_amount ), $submission->get_currency() ),
858
                'discount'  => wpinv_price( wpinv_format_amount( $submission->get_total_discount() ), $submission->get_currency() ),
859
                'fees'      => wpinv_price( wpinv_format_amount( $submission->get_total_fees() ), $submission->get_currency() ),
860
                'tax'       => wpinv_price( wpinv_format_amount( $submission->get_total_tax() ), $submission->get_currency() ),
861
                'total'     => wpinv_price( wpinv_format_amount( $submission->get_total() ), $submission->get_currency() ),
862
            ),
863
864
            'texts'         => array(
865
                '.getpaid-checkout-total-payable' => wpinv_price( wpinv_format_amount( $submission->get_total() ), $submission->get_currency() ),
866
            )
867
868
        );
869
870
        // Add items.
871
        $items = $submission->get_items();
872
        if ( ! empty( $items ) ) {
873
            $result['items'] = array();
874
875
            foreach( $items as $item_id => $item ) {
876
                $result['items']["$item_id"] = wpinv_price( wpinv_format_amount( $item->get_price() * $item->get_quantity() ) );
877
            }
878
        }
879
880
        // Add invoice.
881
        if ( $submission->has_invoice() ) {
882
            $result['invoice'] = $submission->get_invoice()->ID;
883
        }
884
885
        // Add discount code.
886
        if ( $submission->has_discount_code() ) {
887
            $result['discount_code'] = $submission->get_discount_code();
888
        }
889
890
        // Filter the result.
891
        $result = apply_filters( 'getpaid_payment_form_ajax_refresh_prices', $result, $submission );
892
893
        wp_send_json_success( $result );
894
    }
895
896
    /**
897
     * Lets users buy items via ajax.
898
     *
899
     * @since 1.0.0
900
     */
901
    public static function buy_items() {
902
        $user_id = get_current_user_id();
903
904
        if ( empty( $user_id ) ) { // If not logged in then lets redirect to the login page
905
            wp_send_json( array(
906
                'success' => wp_login_url( wp_get_referer() )
0 ignored issues
show
Bug introduced by
It seems like wp_get_referer() can also be of type false; however, parameter $redirect of wp_login_url() 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

906
                'success' => wp_login_url( /** @scrutinizer ignore-type */ wp_get_referer() )
Loading history...
907
            ) );
908
        } else {
909
            // Only check nonce if logged in as it could be cached when logged out.
910
            if ( ! isset( $_POST['wpinv_buy_nonce'] ) || ! wp_verify_nonce( $_POST['wpinv_buy_nonce'], 'wpinv_buy_items' ) ) {
911
                wp_send_json( array(
912
                    'error' => __( 'Security checks failed.', 'invoicing' )
913
                ) );
914
                wp_die();
915
            }
916
917
            // allow to set a custom price through post_id
918
            $items = $_POST['items'];
919
            $related_post_id = isset( $_POST['post_id'] ) ? (int)$_POST['post_id'] : 0;
920
            $custom_item_price = $related_post_id ? abs( get_post_meta( $related_post_id, '_wpi_custom_price', true ) ) : 0;
921
922
            $cart_items = array();
923
            if ( $items ) {
924
                $items = explode( ',', $items );
925
926
                foreach( $items as $item ) {
927
                    $item_id = $item;
928
                    $quantity = 1;
929
930
                    if ( strpos( $item, '|' ) !== false ) {
931
                        $item_parts = explode( '|', $item );
932
                        $item_id = $item_parts[0];
933
                        $quantity = $item_parts[1];
934
                    }
935
936
                    if ( $item_id && $quantity ) {
937
                        $cart_items_arr = array(
938
                            'id'            => (int)$item_id,
939
                            'quantity'      => (int)$quantity
940
                        );
941
942
                        // If there is a related post id then add it to meta
943
                        if ( $related_post_id ) {
944
                            $cart_items_arr['meta'] = array(
945
                                'post_id'   => $related_post_id
946
                            );
947
                        }
948
949
                        // If there is a custom price then set it.
950
                        if ( $custom_item_price ) {
951
                            $cart_items_arr['custom_price'] = $custom_item_price;
952
                        }
953
954
                        $cart_items[] = $cart_items_arr;
955
                    }
956
                }
957
            }
958
959
            /**
960
             * Filter the wpinv_buy shortcode cart items on the fly.
961
             *
962
             * @param array $cart_items The cart items array.
963
             * @param int $related_post_id The related post id if any.
964
             * @since 1.0.0
965
             */
966
            $cart_items = apply_filters( 'wpinv_buy_cart_items', $cart_items, $related_post_id );
967
968
            // Make sure its not in the cart already, if it is then redirect to checkout.
969
            $cart_invoice = wpinv_get_invoice_cart();
0 ignored issues
show
Deprecated Code introduced by
The function wpinv_get_invoice_cart() 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

969
            $cart_invoice = /** @scrutinizer ignore-deprecated */ wpinv_get_invoice_cart();
Loading history...
970
971
            if ( isset( $cart_invoice->items ) && !empty( $cart_invoice->items ) && !empty( $cart_items ) && serialize( $cart_invoice->items ) == serialize( $cart_items ) ) {
0 ignored issues
show
Bug Best Practice introduced by
The property items does not exist on WPInv_Invoice. Since you implemented __get, consider adding a @property annotation.
Loading history...
972
                wp_send_json( array(
973
                    'success' =>  $cart_invoice->get_checkout_payment_url()
974
                ) );
975
                wp_die();
976
            }
977
978
            // Check if user has invoice with same items waiting to be paid.
979
            $user_invoices = wpinv_get_users_invoices( $user_id , 10 , false , 'wpi-pending' );
980
            if ( !empty( $user_invoices ) ) {
981
                foreach( $user_invoices as $user_invoice ) {
982
                    $user_cart_details = array();
983
                    $invoice  = wpinv_get_invoice( $user_invoice->ID );
984
                    $cart_details = $invoice->get_cart_details();
985
986
                    if ( !empty( $cart_details ) ) {
987
                        foreach ( $cart_details as $invoice_item ) {
988
                            $ii_arr = array();
989
                            $ii_arr['id'] = (int)$invoice_item['id'];
990
                            $ii_arr['quantity'] = (int)$invoice_item['quantity'];
991
992
                            if (isset( $invoice_item['meta'] ) && !empty( $invoice_item['meta'] ) ) {
993
                                $ii_arr['meta'] = $invoice_item['meta'];
994
                            }
995
996
                            if ( isset( $invoice_item['custom_price'] ) && !empty( $invoice_item['custom_price'] ) ) {
997
                                $ii_arr['custom_price'] = $invoice_item['custom_price'];
998
                            }
999
1000
                            $user_cart_details[] = $ii_arr;
1001
                        }
1002
                    }
1003
1004
                    if ( !empty( $user_cart_details ) && serialize( $cart_items ) == serialize( $user_cart_details ) ) {
1005
                        wp_send_json( array(
1006
                            'success' =>  $invoice->get_checkout_payment_url()
1007
                        ) );
1008
                        wp_die();
1009
                    }
1010
                }
1011
            }
1012
1013
            // Create invoice and send user to checkout
1014
            if ( !empty( $cart_items ) ) {
1015
                $invoice_data = array(
1016
                    'status'        =>  'wpi-pending',
1017
                    'created_via'   =>  'wpi',
1018
                    'user_id'       =>  $user_id,
1019
                    'cart_details'  =>  $cart_items,
1020
                );
1021
1022
                $invoice = wpinv_insert_invoice( $invoice_data, true );
1023
1024
                if ( !empty( $invoice ) && isset( $invoice->ID ) ) {
1025
                    wp_send_json( array(
1026
                        'success' =>  $invoice->get_checkout_payment_url()
0 ignored issues
show
Bug introduced by
The method get_checkout_payment_url() does not exist on WP_Error. ( Ignorable by Annotation )

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

1026
                        'success' =>  $invoice->/** @scrutinizer ignore-call */ get_checkout_payment_url()

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
1027
                    ) );
1028
                } else {
1029
                    wp_send_json( array(
1030
                        'error' => __( 'Invoice failed to create', 'invoicing' )
1031
                    ) );
1032
                }
1033
            } else {
1034
                wp_send_json( array(
1035
                    'error' => __( 'Items not valid.', 'invoicing' )
1036
                ) );
1037
            }
1038
        }
1039
1040
        wp_die();
1041
    }
1042
}
1043
1044
WPInv_Ajax::init();