Passed
Pull Request — master (#387)
by Brian
08:47
created

WPInv_Ajax::buy_items()   F

Complexity

Conditions 30
Paths 193

Size

Total Lines 140
Code Lines 75

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 30
eloc 75
c 0
b 0
f 0
nc 193
nop 0
dl 0
loc 140
rs 3.3916

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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

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

64
			$wp_query->set( 'wpinv-ajax', sanitize_text_field( /** @scrutinizer ignore-type */ wp_unslash( $_GET['wpinv-ajax'] ) ) );
Loading history...
65
		}
66
67
		$action = $wp_query->get( 'wpinv-ajax' );
68
69
		if ( $action ) {
70
			self::wpinv_ajax_headers();
71
			$action = sanitize_text_field( $action );
72
			do_action( 'wpinv_ajax_' . $action );
73
			wp_die();
74
		}
75
76
    }
77
78
    /**
79
	 * Hook in ajax methods.
80
	 */
81
    public static function add_ajax_events() {
82
83
        // array( 'event' => is_frontend )
84
        $ajax_events = array(
85
            'add_note'                    => false,
86
            'delete_note'                 => false,
87
            'get_states_field'            => true,
88
            'get_aui_states_field'        => true,
89
            'payment_form'                => true,
90
            'get_payment_form'            => true,
91
            'get_payment_form_states_field' => true,
92
            'get_invoicing_items'         => false,
93
            'get_invoice_items'           => false,
94
            'add_invoice_items'           => false,
95
            'edit_invoice_item'           => false,
96
            'remove_invoice_item'         => false,
97
            'get_billing_details'         => false,
98
            'recalculate_invoice_totals'  => false,
99
            'check_new_user_email'        => false,
100
            'run_tool'                    => false,
101
            '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
            echo getpaid_display_payment_form( $_GET['form'] );
0 ignored issues
show
Bug introduced by
Are you sure the usage of getpaid_display_payment_form($_GET['form']) is correct as it seems to always return null.

This check looks for function or method calls that always return null and whose return value is used.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
if ($a->getObject()) {

The method getObject() can return nothing but null, so it makes no sense to use the return value.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
276
		} else if( $_GET['invoice'] ) {
277
		    echo getpaid_display_invoice_payment_form( $_GET['invoice'] );
278
        } else {
279
			$items = getpaid_convert_items_to_array( $_GET['item'] );
280
		    echo 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
        global $invoicing;
294
295
        // Check nonce.
296
        check_ajax_referer( 'getpaid_form_nonce' );
297
298
        // ... form fields...
299
        if ( empty( $_POST['getpaid_payment_form_submission'] ) ) {
300
            _e( 'Error: Reload the page and try again.', 'invoicing' );
301
            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...
302
        }
303
304
        // Load the submission.
305
        $submission = new GetPaid_Payment_Form_Submission();
306
307
        // Do we have an error?
308
        if ( ! empty( $submission->last_error ) ) {
309
            echo $submission->last_error;
310
            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...
311
        }
312
313
        // We need a billing email.
314
        if ( ! $submission->has_billing_email() || ! is_email( $submission->get_billing_email() ) ) {
315
            wp_send_json_error( __( 'Provide a valid billing email.', 'invoicing' ) );
316
        }
317
318
        // Clear any checkout errors.
319
        wpinv_clear_errors();
320
321
        // Validate the gateway.
322
        wpinv_checkout_validate_gateway( $submission );
323
324
        // Allow themes and plugins to hook to errors
325
        do_action( 'getpaid_checkout_error_checks', $submission );
326
327
        // Do we have any errors?
328
        if ( wpinv_get_errors() ) {
329
            wp_send_json_error( getpaid_get_errors_html() );
330
        }
331
332
        // Prepare items.
333
        $items = $submission->get_items();
334
335
        // Ensure that we have items.
336
        if ( empty( $items ) ) {
337
            wp_send_json_error( __( 'You have not selected any items.', 'invoicing' ) );
338
        }
339
340
        // Prepare the invoice.
341
        if ( ! $submission->has_invoice() ) {
342
            $invoice = new WPInv_Invoice();
343
        } else {
344
            $invoice = $submission->get_invoice();
345
        }
346
347
        // Make sure that it is neither paid or refunded.
348
        if ( $invoice->is_paid() || $invoice->is_refunded() ) {
349
            wp_send_json_error( __( 'This invoice has already been paid for.', 'invoicing' ) );
350
        }
351
352
        // Set the billing email.
353
        $invoice->set_email( sanitize_email( $submission->get_billing_email() ) );
354
355
        // Payment form.
356
        $invoice->set_payment_form( absint( $submission->get_payment_form()->get_id() ) );
357
358
        // Discount code.
359
        if ( $submission->has_discount_code() ) {
360
            $invoice->set_discount_code( $submission->get_discount_code() );
361
        }
362
363
        // Items, Fees, taxes and discounts.
364
        $invoice->set_items( $items );
365
        $invoice->set_fees( $submission->get_fees() );
366
        $invoice->set_taxes( $submission->get_taxes() );
367
        $invoice->set_discounts( $submission->get_discounts() );
368
369
        // Prepared submission details.
370
        $prepared = array();
371
372
        // Raw submission details.
373
        $data = $submission->get_data();
374
375
        // Loop throught the submitted details.
376
        foreach ( $submission->get_payment_form()->get_elements() as $field ) {
377
378
            if ( ! empty( $field['premade'] ) ) {
379
                continue;
380
            }
381
382
            // If it is required and not set, abort.
383
            if ( ! $submission->is_required_field_set( $field ) ) {
384
                wp_send_json_error( __( 'Some required fields are not set.', 'invoicing' ) );
385
            }
386
387
            // Handle address fields.
388
            if ( $field['type'] == 'address' ) {
389
390
                foreach ( $field['fields'] as $address_field ) {
391
392
                    // skip if it is not visible.
393
                    if ( empty( $address_field['visible'] ) ) {
394
                        continue;
395
                    }
396
397
                    // If it is required and not set, abort
398
                    if ( ! empty( $address_field['required'] ) && empty( $data[ $address_field['name'] ] ) ) {
399
                        wp_send_json_error( __( 'Some required fields are not set.', 'invoicing' ) );
400
                    }
401
402
                    if ( isset( $data[ $address_field['name'] ] ) ) {
403
                        $name   = str_replace( 'wpinv_', '', $address_field['name'] );
404
                        $method = "set_$name";
405
                        $invoice->$method( wpinv_clean( $data[ $address_field['name'] ] ) );
406
                    }
407
408
                }
409
410
            } else if ( isset( $data[ $field['id'] ] ) ) {
411
                $label = $field['id'];
412
413
                if ( isset( $field['label'] ) ) {
414
                    $label = $field['label'];
415
                }
416
417
                $prepared[ wpinv_clean( $label ) ] = wpinv_clean( $data[ $field['id'] ] );
418
            }
419
420
        }
421
422
        // (Maybe) create the user.
423
        $user = get_current_user_id();
424
425
        if ( empty( $user ) ) {
426
            $user = get_user_by( 'email', $submission->get_billing_email() );
427
        }
428
429
        if ( empty( $user ) ) {
430
            $user = wpinv_create_user( $submission->get_billing_email() );
431
        }
432
433
        if ( is_wp_error( $user ) ) {
434
            wp_send_json_error( $user->get_error_message() );
435
        }
436
437
        if ( is_numeric( $user ) ) {
438
            $user = get_user_by( 'id', $user );
439
        }
440
441
        $invoice->set_user_id( $user->ID );
442
443
        // Set gateway.
444
        $invoice->set_gateway( $data['wpi-gateway'] );
445
446
        $invoice->recalculate_total();
447
448
        // Save the invoice.
449
        $invoice->save();
450
451
        // Was it saved successfully:
452
        if ($invoice->get_id() == 0 ) {
453
            wp_send_json_error( __( 'An error occured while saving your invoice.', 'invoicing' ) );
454
        }
455
456
        // Save payment form data.
457
        if ( ! empty( $prepared ) ) {
458
            update_post_meta( $invoice->get_id(), 'payment_form_data', $prepared );
459
        }
460
461
        // Process the checkout.
462
        add_filter( 'wp_redirect', array( $invoicing->form_elements, 'send_redirect_response' ) );
463
        add_action( 'wpinv_pre_send_back_to_checkout', array( $invoicing->form_elements, 'checkout_error' ) );
464
465
        wpinv_process_checkout( $invoice, $submission );
466
467
        // If we are here, there was an error.
468
        $invoicing->form_elements->checkout_error();
469
470
        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...
471
    }
472
473
    /**
474
     * Payment forms.
475
     *
476
     * @since 1.0.18
477
     */
478
    public static function get_payment_form_states_field() {
479
        global $invoicing;
480
481
        if ( empty( $_GET['country'] ) || empty( $_GET['form'] ) ) {
482
            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...
483
        }
484
485
        $elements = $invoicing->form_elements->get_form_elements( $_GET['form'] );
486
487
        if ( empty( $elements ) ) {
488
            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...
489
        }
490
491
        $address_fields = array();
492
        foreach ( $elements as $element ) {
493
            if ( 'address' === $element['type'] ) {
494
                $address_fields = $element;
495
                break;
496
            }
497
        }
498
499
        if ( empty( $address_fields ) ) {
500
            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...
501
        }
502
503
        foreach( $address_fields['fields'] as $address_field ) {
504
505
            if ( 'wpinv_state' == $address_field['name'] ) {
506
507
                $label = $address_field['label'];
508
509
                if ( ! empty( $address_field['required'] ) ) {
510
                    $label .= "<span class='text-danger'> *</span>";
511
                }
512
513
                $states = wpinv_get_country_states( $_GET['country'] );
514
515
                if ( ! empty( $states ) ) {
516
517
                    $html = aui()->select(
518
                            array(
519
                                'options'          => $states,
520
                                'name'             => esc_attr( $address_field['name'] ),
521
                                'id'               => esc_attr( $address_field['name'] ),
522
                                'placeholder'      => esc_attr( $address_field['placeholder'] ),
523
                                'required'         => (bool) $address_field['required'],
524
                                'no_wrap'          => true,
525
                                'label'            => wp_kses_post( $label ),
526
                                'select2'          => false,
527
                            )
528
                        );
529
530
                } else {
531
532
                    $html = aui()->input(
533
                            array(
534
                                'name'       => esc_attr( $address_field['name'] ),
535
                                'id'         => esc_attr( $address_field['name'] ),
536
                                'required'   => (bool) $address_field['required'],
537
                                'label'      => wp_kses_post( $label ),
538
                                'no_wrap'    => true,
539
                                'type'       => 'text',
540
                            )
541
                        );
542
543
                }
544
545
                wp_send_json_success( str_replace( 'sr-only', '', $html ) );
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
550
        }
551
    
552
        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...
553
    }
554
555
    /**
556
     * Recalculates invoice totals.
557
     */
558
    public static function recalculate_invoice_totals() {
559
560
        // Verify nonce.
561
        check_ajax_referer( 'wpinv-nonce' );
562
563
        if ( ! wpinv_current_user_can_manage_invoicing() ) {
564
            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...
565
        }
566
567
        // We need an invoice.
568
        if ( empty( $_POST['post_id'] ) ) {
569
            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...
570
        }
571
572
        // Fetch the invoice.
573
        $invoice = new WPInv_Invoice( trim( $_POST['post_id'] ) );
574
575
        // Ensure it exists.
576
        if ( ! $invoice->get_id() ) {
577
            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...
578
        }
579
580
        // Maybe set the country, state, currency.
581
        foreach ( array( 'country', 'state', 'currency' ) as $key ) {
582
            if ( isset( $_POST[ $key ] ) ) {
583
                $method = "set_$key";
584
                $invoice->$method( $_POST[ $key ] );
585
            }
586
        }
587
588
        // Maybe disable taxes.
589
        $invoice->set_disable_taxes( ! empty( $_POST['taxes'] ) );
590
591
        // Recalculate totals.
592
        $invoice->recalculate_total();
593
594
        $total = wpinv_price( wpinv_format_amount( $invoice->get_total() ), $invoice->get_currency() );
595
596
        if ( $invoice->is_recurring() && $invoice->is_parent() && $invoice->get_total() != $invoice->get_recurring_total() ) {
597
            $recurring_total = wpinv_price( wpinv_format_amount( $invoice->get_recurring_total() ), $invoice->get_currency() );
598
            $total          .= '<small class="form-text text-muted">' . sprintf( __( 'Recurring Price: %s', 'invoicing' ), $recurring_total ) . '</small>';
599
        }
600
601
        $totals = array(
602
            'subtotal' => wpinv_price( wpinv_format_amount( $invoice->get_subtotal() ), $invoice->get_currency() ),
603
            'discount' => wpinv_price( wpinv_format_amount( $invoice->get_total_discount() ), $invoice->get_currency() ),
604
            'tax'      => wpinv_price( wpinv_format_amount( $invoice->get_total_tax() ), $invoice->get_currency() ),
605
            'total'    => $total,
606
        );
607
608
        $totals = apply_filters( 'getpaid_invoice_totals', $totals, $invoice );
609
610
        wp_send_json_success( compact( 'totals' ) );
611
    }
612
613
    /**
614
     * Get items belonging to a given invoice.
615
     */
616
    public static function get_invoice_items() {
617
618
        // Verify nonce.
619
        check_ajax_referer( 'wpinv-nonce' );
620
621
        if ( ! wpinv_current_user_can_manage_invoicing() ) {
622
            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...
623
        }
624
625
        // We need an invoice and items.
626
        if ( empty( $_POST['post_id'] ) ) {
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
        // Fetch the invoice.
631
        $invoice = new WPInv_Invoice( trim( $_POST['post_id'] ) );
632
633
        // Ensure it exists.
634
        if ( ! $invoice->get_id() ) {
635
            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...
636
        }
637
638
        // Return an array of invoice items.
639
        $items = array();
640
641
        foreach ( $invoice->get_items() as $item_id => $item ) {
642
            $items[ $item_id ] = $item->prepare_data_for_invoice_edit_ajax(  $invoice->get_currency()  );
643
        }
644
645
        wp_send_json_success( compact( 'items' ) );
646
    }
647
648
    /**
649
     * Edits an invoice item.
650
     */
651
    public static function edit_invoice_item() {
652
653
        // Verify nonce.
654
        check_ajax_referer( 'wpinv-nonce' );
655
656
        if ( ! wpinv_current_user_can_manage_invoicing() ) {
657
            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...
658
        }
659
660
        // We need an invoice and item details.
661
        if ( empty( $_POST['post_id'] ) || empty( $_POST['data'] ) ) {
662
            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...
663
        }
664
665
        // Fetch the invoice.
666
        $invoice = new WPInv_Invoice( trim( $_POST['post_id'] ) );
667
668
        // Ensure it exists and its not been paid for.
669
        if ( ! $invoice->get_id() || $invoice->is_paid() || $invoice->is_refunded() ) {
670
            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...
671
        }
672
673
        // Format the data.
674
        $data = wp_list_pluck( $_POST['data'], 'value', 'field' );
675
676
        // Ensure that we have an item id.
677
        if ( empty( $data['id'] ) ) {
678
            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...
679
        }
680
681
        // Abort if the invoice does not have the specified item.
682
        $item = $invoice->get_item( (int) $data['id'] );
683
684
        if ( empty( $item ) ) {
685
            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...
686
        }
687
688
        // Update the item.
689
        $item->set_price( $data['price'] );
690
        $item->set_name( $data['name'] );
691
        $item->set_description( $data['description'] );
692
        $item->set_quantity( $data['quantity'] );
693
694
        // Add it to the invoice.
695
        $error = $invoice->add_item( $item );
696
        $alert = false;
697
        if ( is_wp_error( $error ) ) {
698
            $alert = $error->get_error_message();
699
        }
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_id => $item ) {
711
            $items[ $item_id ] = $item->prepare_data_for_invoice_edit_ajax(  $invoice->get_currency()  );
712
        }
713
714
        wp_send_json_success( compact( 'items', 'alert' ) );
715
    }
716
717
    /**
718
     * Deletes an invoice item.
719
     */
720
    public static function remove_invoice_item() {
721
722
        // Verify nonce.
723
        check_ajax_referer( 'wpinv-nonce' );
724
725
        if ( ! wpinv_current_user_can_manage_invoicing() ) {
726
            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...
727
        }
728
729
        // We need an invoice and an item.
730
        if ( empty( $_POST['post_id'] ) || empty( $_POST['item_id'] ) ) {
731
            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...
732
        }
733
734
        // Fetch the invoice.
735
        $invoice = new WPInv_Invoice( trim( $_POST['post_id'] ) );
736
737
        // Ensure it exists and its not been paid for.
738
        if ( ! $invoice->get_id() || $invoice->is_paid() || $invoice->is_refunded() ) {
739
            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...
740
        }
741
742
        // Abort if the invoice does not have the specified item.
743
        $item = $invoice->get_item( (int) $_POST['item_id'] );
744
745
        if ( empty( $item ) ) {
746
            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...
747
        }
748
749
        $invoice->remove_item( (int) $_POST['item_id'] );
750
751
        // Update totals.
752
        $invoice->recalculate_total();
753
754
        // Save the invoice.
755
        $invoice->save();
756
757
        // Return an array of invoice items.
758
        $items = array();
759
760
        foreach ( $invoice->get_items() as $item_id => $item ) {
761
            $items[ $item_id ] = $item->prepare_data_for_invoice_edit_ajax(  $invoice->get_currency()  );
762
        }
763
764
        wp_send_json_success( compact( 'items' ) );
765
    }
766
767
    /**
768
     * Adds a items to an invoice.
769
     */
770
    public static function add_invoice_items() {
771
772
        // Verify nonce.
773
        check_ajax_referer( 'wpinv-nonce' );
774
775
        if ( ! wpinv_current_user_can_manage_invoicing() ) {
776
            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...
777
        }
778
779
        // We need an invoice and items.
780
        if ( empty( $_POST['post_id'] ) || empty( $_POST['items'] ) ) {
781
            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...
782
        }
783
784
        // Fetch the invoice.
785
        $invoice = new WPInv_Invoice( trim( $_POST['post_id'] ) );
786
        $alert   = false;
787
788
        // Ensure it exists and its not been paid for.
789
        if ( ! $invoice->get_id() || $invoice->is_paid() || $invoice->is_refunded() ) {
790
            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...
791
        }
792
793
        // Add the items.
794
        foreach ( $_POST['items'] as $data ) {
795
796
            $item = new GetPaid_Form_Item( $data[ 'id' ] );
797
798
            if ( is_numeric( $data[ 'qty' ] ) && (int) $data[ 'qty' ] > 0 ) {
799
                $item->set_quantity( $data[ 'qty' ] );
800
            }
801
802
            if ( $item->get_id() > 0 ) {
803
                $error = $invoice->add_item( $item );
804
805
                if ( is_wp_error( $error ) ) {
806
                    $alert = $error->get_error_message();
807
                }
808
809
            }
810
811
        }
812
813
        // Save the invoice.
814
        $invoice->recalculate_total();
815
        $invoice->save();
816
817
        // Return an array of invoice items.
818
        $items = array();
819
820
        foreach ( $invoice->get_items() as $item_id => $item ) {
821
            $items[ $item_id ] = $item->prepare_data_for_invoice_edit_ajax( $invoice->get_currency() );
822
        }
823
824
        wp_send_json_success( compact( 'items', 'alert' ) );
825
    }
826
827
    /**
828
     * Retrieves items that should be added to an invoice.
829
     */
830
    public static function get_invoicing_items() {
831
832
        // Verify nonce.
833
        check_ajax_referer( 'wpinv-nonce' );
834
835
        if ( ! wpinv_current_user_can_manage_invoicing() ) {
836
            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...
837
        }
838
839
        // We need a search term.
840
        if ( empty( $_GET['search'] ) ) {
841
            wp_send_json_success( array() );
842
        }
843
844
        // Retrieve items.
845
        $item_args = array(
846
            'post_type'      => 'wpi_item',
847
            'orderby'        => 'title',
848
            'order'          => 'ASC',
849
            'posts_per_page' => -1,
850
            'post_status'    => array( 'publish' ),
851
            's'              => trim( $_GET['search'] ),
852
            'meta_query'     => array(
853
                array(
854
                    'key'       => '_wpinv_type',
855
                    'compare'   => '!=',
856
                    'value'     => 'package'
857
                )
858
            )
859
        );
860
861
        $items = get_posts( apply_filters( 'getpaid_ajax_invoice_items_query_args', $item_args ) );
862
        $data  = array();
863
864
        foreach ( $items as $item ) {
865
            $item      = new GetPaid_Form_Item( $item );
866
            $data[] = array(
867
                'id'   => $item->get_id(),
868
                'text' => $item->get_name()
869
            );
870
        }
871
872
        wp_send_json_success( $data );
873
874
    }
875
876
    /**
877
     * Retrieves the states field for AUI forms.
878
     */
879
    public static function get_aui_states_field() {
880
881
        // Verify nonce.
882
        check_ajax_referer( 'wpinv-nonce' );
883
884
        // We need a country.
885
        if ( empty( $_GET['country'] ) ) {
886
            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...
887
        }
888
889
        $states = wpinv_get_country_states( trim( $_GET['country'] ) );
890
        $state  = isset( $_GET['state'] ) ? trim( $_GET['state'] ) : wpinv_get_default_state();
891
892
        if ( empty( $states ) ) {
893
894
            $html = aui()->input(
895
                array(
896
                    'type'        => 'text',
897
                    'id'          => 'wpinv_state',
898
                    'name'        => 'wpinv_state',
899
                    'label'       => __( 'State', 'invoicing' ),
900
                    'label_type'  => 'vertical',
901
                    'placeholder' => 'Liège',
902
                    'class'       => 'form-control-sm',
903
                    'value'       => $state,
904
                )
905
            );
906
907
        } else {
908
909
            $html = aui()->select(
910
                array(
911
                    'id'          => 'wpinv_state',
912
                    'name'        => 'wpinv_state',
913
                    'label'       => __( 'State', 'invoicing' ),
914
                    'label_type'  => 'vertical',
915
                    'placeholder' => __( 'Select a state', 'invoicing' ),
916
                    'class'       => 'form-control-sm',
917
                    'value'       => $state,
918
                    'options'     => $states,
919
                    'data-allow-clear' => 'false',
920
                    'select2'          => true,
921
                )
922
            );
923
924
        }
925
926
        wp_send_json_success(
927
            array(
928
                'html'   => $html,
929
                'select' => ! empty ( $states )
930
            )
931
        );
932
933
    }
934
935
    /**
936
     * IP geolocation.
937
     *
938
     * @since 1.0.19
939
     */
940
    public static function ip_geolocation() {
941
942
        // Check nonce.
943
        check_ajax_referer( 'getpaid-ip-location' );
944
945
        // IP address.
946
        if ( empty( $_GET['ip'] ) || ! rest_is_ip_address( $_GET['ip'] ) ) {
947
            _e( 'Invalid IP Address.', 'invoicing' );
948
            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...
949
        }
950
951
        // Retrieve location info.
952
        $location = getpaid_geolocate_ip_address( $_GET['ip'] );
953
954
        if ( empty( $location ) ) {
955
            _e( 'Unable to find geolocation for the IP Address.', 'invoicing' );
956
            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...
957
        }
958
959
        // Sorry.
960
        extract( $location );
961
962
        // Prepare the address.
963
        $content = '';
964
965
        if ( ! empty( $location['city'] ) ) {
966
            $content .=  $location['city']  . ', ';
967
        }
968
        
969
        if ( ! empty( $location['region'] ) ) {
970
            $content .=  $location['region']  . ', ';
971
        }
972
        
973
        $content .=  $location['country'] . ' (' . $location['iso'] . ')';
974
975
        $location['address'] = $content;
976
977
        $content  = '<p>'. sprintf( __( '<b>Address:</b> %s', 'invoicing' ), $content ) . '</p>';
978
        $content .= '<p>'. $location['credit'] . '</p>';
979
980
        $location['content'] = $content;
981
982
        wpinv_get_template( 'geolocation.php', $location );
983
984
        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...
985
    }
986
987
    /**
988
     * Refresh prices.
989
     *
990
     * @since 1.0.19
991
     */
992
    public static function payment_form_refresh_prices() {
993
994
        // Check nonce.
995
        check_ajax_referer( 'getpaid_form_nonce' );
996
997
        // ... form fields...
998
        if ( empty( $_POST['getpaid_payment_form_submission'] ) ) {
999
            _e( 'Error: Reload the page and try again.', 'invoicing' );
1000
            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...
1001
        }
1002
1003
        // Load the submission.
1004
        $submission = new GetPaid_Payment_Form_Submission();
1005
1006
        // Do we have an error?
1007
        if ( ! empty( $submission->last_error ) ) {
1008
            echo $submission->last_error;
1009
            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...
1010
        }
1011
1012
        // Prepare the result.
1013
        $result = array(
1014
1015
            'submission_id' => $submission->id,
1016
            'has_recurring' => $submission->has_recurring,
1017
            'is_free'       => $submission->get_payment_details(),
1018
1019
            'totals'        => array(
1020
                'subtotal'  => wpinv_price( wpinv_format_amount( $submission->subtotal_amount ), $submission->get_currency() ),
1021
                'discount'  => wpinv_price( wpinv_format_amount( $submission->get_total_discount() ), $submission->get_currency() ),
1022
                'fees'      => wpinv_price( wpinv_format_amount( $submission->get_total_fees() ), $submission->get_currency() ),
1023
                'tax'       => wpinv_price( wpinv_format_amount( $submission->get_total_tax() ), $submission->get_currency() ),
1024
                'total'     => wpinv_price( wpinv_format_amount( $submission->get_total() ), $submission->get_currency() ),
1025
            ),
1026
1027
            'texts'         => array(
1028
                '.getpaid-checkout-total-payable' => wpinv_price( wpinv_format_amount( $submission->get_total() ), $submission->get_currency() ),
1029
            )
1030
1031
        );
1032
1033
        // Add items.
1034
        $items = $submission->get_items();
1035
        if ( ! empty( $items ) ) {
1036
            $result['items'] = array();
1037
1038
            foreach( $items as $item_id => $item ) {
1039
                $result['items']["$item_id"] = wpinv_price( wpinv_format_amount( $item->get_price() * $item->get_quantity() ) );
1040
            }
1041
        }
1042
1043
        // Add invoice.
1044
        if ( $submission->has_invoice() ) {
1045
            $result['invoice'] = $submission->get_invoice()->ID;
1046
        }
1047
1048
        // Add discount code.
1049
        if ( $submission->has_discount_code() ) {
1050
            $result['discount_code'] = $submission->get_discount_code();
1051
        }
1052
1053
        // Filter the result.
1054
        $result = apply_filters( 'getpaid_payment_form_ajax_refresh_prices', $result, $submission );
1055
1056
        wp_send_json_success( $result );
1057
    }
1058
1059
    /**
1060
     * Lets users buy items via ajax.
1061
     *
1062
     * @since 1.0.0
1063
     */
1064
    public static function buy_items() {
1065
        $user_id = get_current_user_id();
1066
1067
        if ( empty( $user_id ) ) { // If not logged in then lets redirect to the login page
1068
            wp_send_json( array(
1069
                '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

1069
                'success' => wp_login_url( /** @scrutinizer ignore-type */ wp_get_referer() )
Loading history...
1070
            ) );
1071
        } else {
1072
            // Only check nonce if logged in as it could be cached when logged out.
1073
            if ( ! isset( $_POST['wpinv_buy_nonce'] ) || ! wp_verify_nonce( $_POST['wpinv_buy_nonce'], 'wpinv_buy_items' ) ) {
1074
                wp_send_json( array(
1075
                    'error' => __( 'Security checks failed.', 'invoicing' )
1076
                ) );
1077
                wp_die();
1078
            }
1079
1080
            // allow to set a custom price through post_id
1081
            $items = $_POST['items'];
1082
            $related_post_id = isset( $_POST['post_id'] ) ? (int)$_POST['post_id'] : 0;
1083
            $custom_item_price = $related_post_id ? abs( get_post_meta( $related_post_id, '_wpi_custom_price', true ) ) : 0;
1084
1085
            $cart_items = array();
1086
            if ( $items ) {
1087
                $items = explode( ',', $items );
1088
1089
                foreach( $items as $item ) {
1090
                    $item_id = $item;
1091
                    $quantity = 1;
1092
1093
                    if ( strpos( $item, '|' ) !== false ) {
1094
                        $item_parts = explode( '|', $item );
1095
                        $item_id = $item_parts[0];
1096
                        $quantity = $item_parts[1];
1097
                    }
1098
1099
                    if ( $item_id && $quantity ) {
1100
                        $cart_items_arr = array(
1101
                            'id'            => (int)$item_id,
1102
                            'quantity'      => (int)$quantity
1103
                        );
1104
1105
                        // If there is a related post id then add it to meta
1106
                        if ( $related_post_id ) {
1107
                            $cart_items_arr['meta'] = array(
1108
                                'post_id'   => $related_post_id
1109
                            );
1110
                        }
1111
1112
                        // If there is a custom price then set it.
1113
                        if ( $custom_item_price ) {
1114
                            $cart_items_arr['custom_price'] = $custom_item_price;
1115
                        }
1116
1117
                        $cart_items[] = $cart_items_arr;
1118
                    }
1119
                }
1120
            }
1121
1122
            /**
1123
             * Filter the wpinv_buy shortcode cart items on the fly.
1124
             *
1125
             * @param array $cart_items The cart items array.
1126
             * @param int $related_post_id The related post id if any.
1127
             * @since 1.0.0
1128
             */
1129
            $cart_items = apply_filters( 'wpinv_buy_cart_items', $cart_items, $related_post_id );
1130
1131
            // Make sure its not in the cart already, if it is then redirect to checkout.
1132
            $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

1132
            $cart_invoice = /** @scrutinizer ignore-deprecated */ wpinv_get_invoice_cart();
Loading history...
1133
1134
            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...
1135
                wp_send_json( array(
1136
                    'success' =>  $cart_invoice->get_checkout_payment_url()
1137
                ) );
1138
                wp_die();
1139
            }
1140
1141
            // Check if user has invoice with same items waiting to be paid.
1142
            $user_invoices = wpinv_get_users_invoices( $user_id , 10 , false , 'wpi-pending' );
1143
            if ( !empty( $user_invoices ) ) {
1144
                foreach( $user_invoices as $user_invoice ) {
1145
                    $user_cart_details = array();
1146
                    $invoice  = wpinv_get_invoice( $user_invoice->ID );
1147
                    $cart_details = $invoice->get_cart_details();
1148
1149
                    if ( !empty( $cart_details ) ) {
1150
                        foreach ( $cart_details as $invoice_item ) {
1151
                            $ii_arr = array();
1152
                            $ii_arr['id'] = (int)$invoice_item['id'];
1153
                            $ii_arr['quantity'] = (int)$invoice_item['quantity'];
1154
1155
                            if (isset( $invoice_item['meta'] ) && !empty( $invoice_item['meta'] ) ) {
1156
                                $ii_arr['meta'] = $invoice_item['meta'];
1157
                            }
1158
1159
                            if ( isset( $invoice_item['custom_price'] ) && !empty( $invoice_item['custom_price'] ) ) {
1160
                                $ii_arr['custom_price'] = $invoice_item['custom_price'];
1161
                            }
1162
1163
                            $user_cart_details[] = $ii_arr;
1164
                        }
1165
                    }
1166
1167
                    if ( !empty( $user_cart_details ) && serialize( $cart_items ) == serialize( $user_cart_details ) ) {
1168
                        wp_send_json( array(
1169
                            'success' =>  $invoice->get_checkout_payment_url()
1170
                        ) );
1171
                        wp_die();
1172
                    }
1173
                }
1174
            }
1175
1176
            // Create invoice and send user to checkout
1177
            if ( !empty( $cart_items ) ) {
1178
                $invoice_data = array(
1179
                    'status'        =>  'wpi-pending',
1180
                    'created_via'   =>  'wpi',
1181
                    'user_id'       =>  $user_id,
1182
                    'cart_details'  =>  $cart_items,
1183
                );
1184
1185
                $invoice = wpinv_insert_invoice( $invoice_data, true );
1186
1187
                if ( !empty( $invoice ) && isset( $invoice->ID ) ) {
1188
                    wp_send_json( array(
1189
                        '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

1189
                        '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...
1190
                    ) );
1191
                } else {
1192
                    wp_send_json( array(
1193
                        'error' => __( 'Invoice failed to create', 'invoicing' )
1194
                    ) );
1195
                }
1196
            } else {
1197
                wp_send_json( array(
1198
                    'error' => __( 'Items not valid.', 'invoicing' )
1199
                ) );
1200
            }
1201
        }
1202
1203
        wp_die();
1204
    }
1205
}
1206
1207
WPInv_Ajax::init();