Passed
Push — master ( 35bd8d...8ba8d0 )
by Brian
10:42 queued 04:43
created

WPInv_Ajax::payment_form_validate_discount()   F

Complexity

Conditions 28
Paths 174

Size

Total Lines 149
Code Lines 75

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 28
eloc 75
nc 174
nop 1
dl 0
loc 149
rs 3.55
c 0
b 0
f 0

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 functions related to Invoicing plugin.
4
 *
5
 * @since 1.0.0
6
 * @package Invoicing
7
 */
8
 
9
// MUST have WordPress.
10
if ( !defined( 'WPINC' ) ) {
11
    exit( 'Do NOT access this file directly: ' . basename( __FILE__ ) );
12
}
13
14
class WPInv_Ajax {
15
    public static function init() {
16
        add_action( 'init', array( __CLASS__, 'define_ajax' ), 0 );
17
        add_action( 'template_redirect', array( __CLASS__, 'do_wpinv_ajax' ), 0 );
18
        self::add_ajax_events();
19
    }
20
21
    public static function define_ajax() {
22
        if ( !empty( $_GET['wpinv-ajax'] ) ) {
23
            if ( ! defined( 'DOING_AJAX' ) ) {
24
                define( 'DOING_AJAX', true );
25
            }
26
            if ( ! defined( 'WC_DOING_AJAX' ) ) {
27
                define( 'WC_DOING_AJAX', true );
28
            }
29
            // Turn off display_errors during AJAX events to prevent malformed JSON
30
            if ( ! WP_DEBUG || ( WP_DEBUG && ! WP_DEBUG_DISPLAY ) ) {
31
                /** @scrutinizer ignore-unhandled */ @ini_set( 'display_errors', 0 );
32
            }
33
            $GLOBALS['wpdb']->hide_errors();
34
        }
35
    }
36
    
37
    public static function do_wpinv_ajax() {
38
        global $wp_query;
39
40
        if ( !empty( $_GET['wpinv-ajax'] ) ) {
41
            $wp_query->set( 'wpinv-ajax', sanitize_text_field( $_GET['wpinv-ajax'] ) );
42
        }
43
44
        if ( $action = $wp_query->get( 'wpinv-ajax' ) ) {
45
            self::wpinv_ajax_headers();
46
            do_action( 'wpinv_ajax_' . sanitize_text_field( $action ) );
47
            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...
48
        }
49
    }
50
    
51
    private static function wpinv_ajax_headers() {
52
        send_origin_headers();
53
        /** @scrutinizer ignore-unhandled */ @header( 'Content-Type: text/html; charset=' . get_option( 'blog_charset' ) );
54
        /** @scrutinizer ignore-unhandled */ @header( 'X-Robots-Tag: noindex' );
55
        send_nosniff_header();
56
        nocache_headers();
57
        status_header( 200 );
58
    }
59
    
60
    public static function add_ajax_events() {
61
        $ajax_events = array(
62
            'add_note' => false,
63
            'delete_note' => false,
64
            'get_states_field' => true,
65
            'checkout' => false,
66
            'payment_form_get_taxes' => true,
67
            'payment_form'     => true,
68
            'payment_form_discount' => true,
69
            'get_payment_form' => true,
70
            'get_payment_form_states_field' => true,
71
            'add_invoice_item' => false,
72
            'remove_invoice_item' => false,
73
            'create_invoice_item' => false,
74
            'get_billing_details' => false,
75
            'admin_recalculate_totals' => false,
76
            'admin_apply_discount' => false,
77
            'admin_remove_discount' => false,
78
            'check_email' => false,
79
            'run_tool' => false,
80
            'apply_discount' => true,
81
            'remove_discount' => true,
82
            'buy_items' => true,
83
        );
84
85
        foreach ( $ajax_events as $ajax_event => $nopriv ) {
86
            add_action( 'wp_ajax_wpinv_' . $ajax_event, array( __CLASS__, $ajax_event ) );
87
            add_action( 'wp_ajax_getpaid_' . $ajax_event, array( __CLASS__, $ajax_event ) );
88
            
89
            if ( !defined( 'WPI_AJAX_' . strtoupper( $nopriv ) ) ) {
90
                define( 'WPI_AJAX_' . strtoupper( $nopriv ), 1 );
91
            }
92
93
            if ( $nopriv ) {
94
                add_action( 'wp_ajax_nopriv_wpinv_' . $ajax_event, array( __CLASS__, $ajax_event ) );
95
                add_action( 'wp_ajax_nopriv_getpaid_' . $ajax_event, array( __CLASS__, $ajax_event ) );
96
97
                add_action( 'wpinv_ajax_' . $ajax_event, array( __CLASS__, $ajax_event ) );
98
            }
99
        }
100
    }
101
    
102
    public static function add_note() {
103
        check_ajax_referer( 'add-invoice-note', '_nonce' );
104
105
        if ( ! wpinv_current_user_can_manage_invoicing() ) {
106
            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...
107
        }
108
109
        $post_id   = absint( $_POST['post_id'] );
110
        $note      = wp_kses_post( trim( stripslashes( $_POST['note'] ) ) );
111
        $note_type = sanitize_text_field( $_POST['note_type'] );
112
113
        $is_customer_note = $note_type == 'customer' ? 1 : 0;
114
115
        if ( $post_id > 0 ) {
116
            $note_id = wpinv_insert_payment_note( $post_id, $note, $is_customer_note );
117
118
            if ( $note_id > 0 && !is_wp_error( $note_id ) ) {
119
                wpinv_get_invoice_note_line_item( $note_id );
120
            }
121
        }
122
123
        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...
124
    }
125
126
    public static function delete_note() {
127
        check_ajax_referer( 'delete-invoice-note', '_nonce' );
128
129
        if ( !wpinv_current_user_can_manage_invoicing() ) {
130
            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...
131
        }
132
133
        $note_id = (int)$_POST['note_id'];
134
135
        if ( $note_id > 0 ) {
136
            wp_delete_comment( $note_id, true );
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 get_states_field() {
143
        echo wpinv_get_states_field();
144
        
145
        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...
146
    }
147
    
148
    public static function checkout() {
149
        if ( ! defined( 'WPINV_CHECKOUT' ) ) {
150
            define( 'WPINV_CHECKOUT', true );
151
        }
152
153
        wpinv_process_checkout();
154
        die(0);
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...
155
    }
156
    
157
    public static function add_invoice_item() {
158
        global $wpi_userID, $wpinv_ip_address_country;
159
        check_ajax_referer( 'invoice-item', '_nonce' );
160
        if ( !wpinv_current_user_can_manage_invoicing() ) {
161
            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...
162
        }
163
        
164
        $item_id    = sanitize_text_field( $_POST['item_id'] );
165
        $invoice_id = absint( $_POST['invoice_id'] );
166
        
167
        if ( !is_numeric( $invoice_id ) || !is_numeric( $item_id ) ) {
168
            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...
169
        }
170
        
171
        $invoice    = wpinv_get_invoice( $invoice_id );
172
        if ( empty( $invoice ) ) {
173
            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...
174
        }
175
        
176
        if ( $invoice->is_paid() || $invoice->is_refunded() ) {
177
            die(); // Don't allow modify items for paid invoice.
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...
178
        }
179
        
180
        if ( !empty( $_POST['user_id'] ) ) {
181
            $wpi_userID = absint( $_POST['user_id'] ); 
182
        }
183
184
        $item = new WPInv_Item( $item_id );
185
        if ( !( !empty( $item ) && $item->post_type == 'wpi_item' ) ) {
186
            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...
187
        }
188
        
189
        // Validate item before adding to invoice because recurring item must be paid individually.
190
        if ( !empty( $invoice->cart_details ) ) {
191
            $valid = true;
192
            
193
            if ( $recurring_item = $invoice->get_recurring() ) {
194
                if ( $recurring_item != $item_id ) {
195
                    $valid = false;
196
                }
197
            } else if ( wpinv_is_recurring_item( $item_id ) ) {
198
                $valid = false;
199
            }
200
            
201
            if ( !$valid ) {
202
                $response               = array();
203
                $response['success']    = false;
204
                $response['msg']        = __( 'You can not add item because recurring item must be paid individually!', 'invoicing' );
205
                wp_send_json( $response );
206
            }
207
        }
208
        
209
        $checkout_session = wpinv_get_checkout_session();
210
        
211
        $data                   = array();
212
        $data['invoice_id']     = $invoice_id;
213
        $data['cart_discounts'] = $invoice->get_discounts( true );
214
        
215
        wpinv_set_checkout_session( $data );
216
        
217
        $quantity = wpinv_item_quantities_enabled() && !empty($_POST['qty']) && (int)$_POST['qty'] > 0 ? (int)$_POST['qty'] : 1;
218
219
        $args = array(
220
            'id'            => $item_id,
221
            'quantity'      => $quantity,
222
            'item_price'    => $item->get_price(),
223
            'custom_price'  => '',
224
            'tax'           => 0.00,
225
            'discount'      => 0,
226
            'meta'          => array(),
227
            'fees'          => array()
228
        );
229
230
        $invoice->add_item( $item_id, $args );
231
        $invoice->save();
232
        
233
        if ( empty( $_POST['country'] ) ) {
234
            $_POST['country'] = !empty($invoice->country) ? $invoice->country : wpinv_get_default_country();
235
        }
236
        if ( empty( $_POST['state'] ) ) {
237
            $_POST['state'] = $invoice->state;
238
        }
239
         
240
        $invoice->country   = sanitize_text_field( $_POST['country'] );
241
        $invoice->state     = sanitize_text_field( $_POST['state'] );
242
        
243
        $invoice->set( 'country', sanitize_text_field( $_POST['country'] ) );
244
        $invoice->set( 'state', sanitize_text_field( $_POST['state'] ) );
245
        
246
        $wpinv_ip_address_country = $invoice->country;
247
248
        $invoice->recalculate_totals(true);
249
        
250
        $response                       = array();
251
        $response['success']            = true;
252
        $response['data']['items']      = wpinv_admin_get_line_items( $invoice );
253
        $response['data']['subtotal']   = $invoice->get_subtotal();
254
        $response['data']['subtotalf']  = $invoice->get_subtotal(true);
255
        $response['data']['tax']        = $invoice->get_tax();
256
        $response['data']['taxf']       = $invoice->get_tax(true);
257
        $response['data']['discount']   = $invoice->get_discount();
258
        $response['data']['discountf']  = $invoice->get_discount(true);
259
        $response['data']['total']      = $invoice->get_total();
260
        $response['data']['totalf']     = $invoice->get_total(true);
261
        
262
        wpinv_set_checkout_session($checkout_session);
263
        
264
        wp_send_json( $response );
265
    }
266
267
268
    public static function remove_invoice_item() {
269
        global $wpi_userID, $wpinv_ip_address_country;
270
        
271
        check_ajax_referer( 'invoice-item', '_nonce' );
272
        if ( !wpinv_current_user_can_manage_invoicing() ) {
273
            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...
274
        }
275
        
276
        $item_id    = sanitize_text_field( $_POST['item_id'] );
277
        $invoice_id = absint( $_POST['invoice_id'] );
278
        $cart_index = isset( $_POST['index'] ) && $_POST['index'] >= 0 ? $_POST['index'] : false;
279
        
280
        if ( !is_numeric( $invoice_id ) || !is_numeric( $item_id ) ) {
281
            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...
282
        }
283
284
        $invoice    = wpinv_get_invoice( $invoice_id );
285
        if ( empty( $invoice ) ) {
286
            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...
287
        }
288
        
289
        if ( $invoice->is_paid() || $invoice->is_refunded() ) {
290
            die(); // Don't allow modify items for paid invoice.
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...
291
        }
292
        
293
        if ( !empty( $_POST['user_id'] ) ) {
294
            $wpi_userID = absint( $_POST['user_id'] ); 
295
        }
296
297
        $item       = new WPInv_Item( $item_id );
298
        if ( !( !empty( $item ) && $item->post_type == 'wpi_item' ) ) {
299
            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...
300
        }
301
        
302
        $checkout_session = wpinv_get_checkout_session();
303
        
304
        $data                   = array();
305
        $data['invoice_id']     = $invoice_id;
306
        $data['cart_discounts'] = $invoice->get_discounts( true );
307
        
308
        wpinv_set_checkout_session( $data );
309
310
        $args = array(
311
            'id'         => $item_id,
312
            'quantity'   => 1,
313
            'cart_index' => $cart_index
314
        );
315
316
        $invoice->remove_item( $item_id, $args );
317
        $invoice->save();
318
        
319
        if ( empty( $_POST['country'] ) ) {
320
            $_POST['country'] = !empty($invoice->country) ? $invoice->country : wpinv_get_default_country();
321
        }
322
        if ( empty( $_POST['state'] ) ) {
323
            $_POST['state'] = $invoice->state;
324
        }
325
         
326
        $invoice->country   = sanitize_text_field( $_POST['country'] );
327
        $invoice->state     = sanitize_text_field( $_POST['state'] );
328
        
329
        $invoice->set( 'country', sanitize_text_field( $_POST['country'] ) );
330
        $invoice->set( 'state', sanitize_text_field( $_POST['state'] ) );
331
        
332
        $wpinv_ip_address_country = $invoice->country;
333
        
334
        $invoice->recalculate_totals(true);
335
        
336
        $response                       = array();
337
        $response['success']            = true;
338
        $response['data']['items']      = wpinv_admin_get_line_items( $invoice );
339
        $response['data']['subtotal']   = $invoice->get_subtotal();
340
        $response['data']['subtotalf']  = $invoice->get_subtotal(true);
341
        $response['data']['tax']        = $invoice->get_tax();
342
        $response['data']['taxf']       = $invoice->get_tax(true);
343
        $response['data']['discount']   = $invoice->get_discount();
344
        $response['data']['discountf']  = $invoice->get_discount(true);
345
        $response['data']['total']      = $invoice->get_total();
346
        $response['data']['totalf']     = $invoice->get_total(true);
347
        
348
        wpinv_set_checkout_session($checkout_session);
349
        
350
        wp_send_json( $response );
351
    }
352
    
353
    public static function create_invoice_item() {
354
        check_ajax_referer( 'invoice-item', '_nonce' );
355
        if ( !wpinv_current_user_can_manage_invoicing() ) {
356
            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...
357
        }
358
        
359
        $invoice_id = absint( $_POST['invoice_id'] );
360
361
        // Find the item
362
        if ( !is_numeric( $invoice_id ) ) {
363
            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...
364
        }        
365
        
366
        $invoice     = wpinv_get_invoice( $invoice_id );
367
        if ( empty( $invoice ) ) {
368
            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...
369
        }
370
        
371
        // Validate item before adding to invoice because recurring item must be paid individually.
372
        if ( !empty( $invoice->cart_details ) && $invoice->get_recurring() ) {
373
            $response               = array();
374
            $response['success']    = false;
375
            $response['msg']        = __( 'You can not add item because recurring item must be paid individually!', 'invoicing' );
376
            wp_send_json( $response );
377
        }        
378
        
379
        $save_item = wp_unslash( $_POST['_wpinv_quick'] );
380
        
381
        $meta               = array();
382
        $meta['type']       = !empty($save_item['type']) ? sanitize_text_field($save_item['type']) : 'custom';
383
        $meta['price']      = !empty($save_item['price']) ? wpinv_sanitize_amount( $save_item['price'] ) : 0;
384
        $meta['vat_rule']   = !empty($save_item['vat_rule']) ? sanitize_text_field($save_item['vat_rule']) : 'digital';
385
        $meta['vat_class']  = !empty($save_item['vat_class']) ? sanitize_text_field($save_item['vat_class']) : '_standard';
386
        
387
        $data                   = array();
388
        $data['post_title']     = sanitize_text_field($save_item['name']);
389
        $data['post_status']    = 'publish';
390
        $data['post_excerpt']   = ! empty( $save_item['excerpt'] ) ? wp_kses_post( $save_item['excerpt'] ) : '';
391
        $data['meta']           = $meta;
392
        
393
        $item = new WPInv_Item();
394
        $item->create( $data );
395
        
396
        if ( !empty( $item ) ) {
397
            $_POST['item_id']   = $item->ID;
398
            $_POST['qty']       = !empty($save_item['qty']) && $save_item['qty'] > 0 ? (int)$save_item['qty'] : 1;
399
            
400
            self::add_invoice_item();
401
        }
402
        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...
403
    }
404
    
405
    public static function get_billing_details() {
406
        check_ajax_referer( 'get-billing-details', '_nonce' );
407
        
408
        if ( !wpinv_current_user_can_manage_invoicing() ) {
409
            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...
410
        }
411
412
        $user_id            = (int)$_POST['user_id'];
413
        $billing_details    = wpinv_get_user_address($user_id);
414
        $billing_details    = apply_filters( 'wpinv_fill_billing_details', $billing_details, $user_id );
415
        
416
        if (isset($billing_details['user_id'])) {
417
            unset($billing_details['user_id']);
418
        }
419
        
420
        if (isset($billing_details['email'])) {
421
            unset($billing_details['email']);
422
        }
423
424
        $response                               = array();
425
        $response['success']                    = true;
426
        $response['data']['billing_details']    = $billing_details;
427
        
428
        wp_send_json( $response );
429
    }
430
    
431
    public static function admin_recalculate_totals() {
432
        global $wpi_userID, $wpinv_ip_address_country;
433
        
434
        check_ajax_referer( 'wpinv-nonce', '_nonce' );
435
        if ( !wpinv_current_user_can_manage_invoicing() ) {
436
            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...
437
        }
438
        
439
        $invoice_id = absint( $_POST['invoice_id'] );        
440
        $invoice    = wpinv_get_invoice( $invoice_id );
441
        if ( empty( $invoice ) ) {
442
            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...
443
        }
444
445
        $checkout_session = wpinv_get_checkout_session();
446
447
        $data                   = array();
448
        $data['invoice_id']     = $invoice_id;
449
        $data['cart_discounts'] = $invoice->get_discounts( true );
450
451
        wpinv_set_checkout_session( $data );
452
        
453
        if ( !empty( $_POST['user_id'] ) ) {
454
            $wpi_userID = absint( $_POST['user_id'] ); 
455
        }
456
        
457
        if ( empty( $_POST['country'] ) ) {
458
            $_POST['country'] = !empty($invoice->country) ? $invoice->country : wpinv_get_default_country();
459
        }
460
461
        $disable_taxes = 0;
462
        if ( ! empty( $_POST['disable_taxes'] ) ) {
463
            $disable_taxes = 1;
464
        }
465
        $invoice->set( 'disable_taxes', $disable_taxes );
466
467
        $invoice->country = sanitize_text_field( $_POST['country'] );
468
        $invoice->set( 'country', sanitize_text_field( $_POST['country'] ) );
469
        if ( isset( $_POST['state'] ) ) {
470
            $invoice->state = sanitize_text_field( $_POST['state'] );
471
            $invoice->set( 'state', sanitize_text_field( $_POST['state'] ) );
472
        }
473
        
474
        $wpinv_ip_address_country = $invoice->country;
475
        
476
        $invoice = $invoice->recalculate_totals(true);
477
        
478
        $response                       = array();
479
        $response['success']            = true;
480
        $response['data']['items']      = wpinv_admin_get_line_items( $invoice );
481
        $response['data']['subtotal']   = $invoice->get_subtotal();
482
        $response['data']['subtotalf']  = $invoice->get_subtotal(true);
483
        $response['data']['tax']        = $invoice->get_tax();
484
        $response['data']['taxf']       = $invoice->get_tax(true);
485
        $response['data']['discount']   = $invoice->get_discount();
486
        $response['data']['discountf']  = $invoice->get_discount(true);
487
        $response['data']['total']      = $invoice->get_total();
488
        $response['data']['totalf']     = $invoice->get_total(true);
489
        
490
        wpinv_set_checkout_session($checkout_session);
491
492
        wp_send_json( $response );
493
    }
494
    
495
    public static function admin_apply_discount() {
496
        global $wpi_userID;
497
        
498
        check_ajax_referer( 'wpinv-nonce', '_nonce' );
499
        if ( !wpinv_current_user_can_manage_invoicing() ) {
500
            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...
501
        }
502
        
503
        $invoice_id = absint( $_POST['invoice_id'] );
504
        $discount_code = sanitize_text_field( $_POST['code'] );
505
        if ( empty( $invoice_id ) || empty( $discount_code ) ) {
506
            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...
507
        }
508
        
509
        $invoice = wpinv_get_invoice( $invoice_id );
510
        if ( empty( $invoice ) || ( !empty( $invoice ) && ( $invoice->is_paid() || $invoice->is_refunded() ) ) ) {
511
            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...
512
        }
513
        
514
        $checkout_session = wpinv_get_checkout_session();
515
        
516
        $data                   = array();
517
        $data['invoice_id']     = $invoice_id;
518
        $data['cart_discounts'] = $invoice->get_discounts( true );
519
        
520
        wpinv_set_checkout_session( $data );
521
        
522
        $response               = array();
523
        $response['success']    = false;
524
        $response['msg']        = __( 'This discount is invalid.', 'invoicing' );
525
        $response['data']['code'] = $discount_code;
526
        
527
        if ( wpinv_is_discount_valid( $discount_code, $invoice->get_user_id() ) ) {
528
            $discounts = wpinv_set_cart_discount( $discount_code );
0 ignored issues
show
Unused Code introduced by
The assignment to $discounts is dead and can be removed.
Loading history...
529
            
530
            $response['success'] = true;
531
            $response['msg'] = __( 'Discount has been applied successfully.', 'invoicing' );
532
        }  else {
533
            $errors = wpinv_get_errors();
534
            if ( !empty( $errors['wpinv-discount-error'] ) ) {
535
                $response['msg'] = $errors['wpinv-discount-error'];
536
            }
537
            wpinv_unset_error( 'wpinv-discount-error' );
538
        }
539
        
540
        wpinv_set_checkout_session($checkout_session);
541
        
542
        wp_send_json( $response );
543
    }
544
    
545
    public static function admin_remove_discount() {
546
        global $wpi_userID;
547
        
548
        check_ajax_referer( 'wpinv-nonce', '_nonce' );
549
        if ( !wpinv_current_user_can_manage_invoicing() ) {
550
            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...
551
        }
552
        
553
        $invoice_id = absint( $_POST['invoice_id'] );
554
        $discount_code = sanitize_text_field( $_POST['code'] );
555
        if ( empty( $invoice_id ) || empty( $discount_code ) ) {
556
            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...
557
        }
558
        
559
        $invoice = wpinv_get_invoice( $invoice_id );
560
        if ( empty( $invoice ) || ( !empty( $invoice ) && ( $invoice->is_paid() || $invoice->is_refunded() ) ) ) {
561
            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...
562
        }
563
        
564
        $checkout_session = wpinv_get_checkout_session();
565
        
566
        $data                   = array();
567
        $data['invoice_id']     = $invoice_id;
568
        $data['cart_discounts'] = $invoice->get_discounts( true );
569
        
570
        wpinv_set_checkout_session( $data );
571
        
572
        $response               = array();
573
        $response['success']    = false;
574
        $response['msg']        = NULL;
575
        
576
        $discounts  = wpinv_unset_cart_discount( $discount_code );
0 ignored issues
show
Unused Code introduced by
The assignment to $discounts is dead and can be removed.
Loading history...
577
        $response['success'] = true;
578
        $response['msg'] = __( 'Discount has been removed successfully.', 'invoicing' );
579
        
580
        wpinv_set_checkout_session($checkout_session);
581
        
582
        wp_send_json( $response );
583
    }
584
    
585
    public static function check_email() {
586
        check_ajax_referer( 'wpinv-nonce', '_nonce' );
587
        if ( !wpinv_current_user_can_manage_invoicing() ) {
588
            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...
589
        }
590
        
591
        $email = sanitize_text_field( $_POST['email'] );
592
        
593
        $response = array();
594
        if ( is_email( $email ) && email_exists( $email ) && $user_data = get_user_by( 'email', $email ) ) {
595
            $user_id            = $user_data->ID;
596
            $user_login         = $user_data->user_login;
597
            $display_name       = $user_data->display_name ? $user_data->display_name : $user_login;
0 ignored issues
show
Unused Code introduced by
The assignment to $display_name is dead and can be removed.
Loading history...
598
            $billing_details    = wpinv_get_user_address($user_id);
599
            $billing_details    = apply_filters( 'wpinv_fill_billing_details', $billing_details, $user_id );
600
            
601
            if (isset($billing_details['user_id'])) {
602
                unset($billing_details['user_id']);
603
            }
604
            
605
            if (isset($billing_details['email'])) {
606
                unset($billing_details['email']);
607
            }
608
            
609
            $response['success']                    = true;
610
            $response['data']['id']                 = $user_data->ID;
611
            $response['data']['name']               = $user_data->user_email;
612
            $response['data']['billing_details']    = $billing_details;
613
        }
614
        
615
        wp_send_json( $response );
616
    }
617
    
618
    public static function run_tool() {
619
        check_ajax_referer( 'wpinv-nonce', '_nonce' );
620
        if ( !wpinv_current_user_can_manage_invoicing() ) {
621
            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...
622
        }
623
        
624
        $tool = sanitize_text_field( $_POST['tool'] );
625
        
626
        do_action( 'wpinv_run_tool' );
627
        
628
        if ( !empty( $tool ) ) {
629
            do_action( 'wpinv_tool_' . $tool );
630
        }
631
    }
632
    
633
    public static function apply_discount() {
634
        global $wpi_userID;
635
        
636
        check_ajax_referer( 'wpinv-nonce', '_nonce' );
637
        
638
        $response = array();
639
        
640
        if ( isset( $_POST['code'] ) ) {
641
            $discount_code = sanitize_text_field( $_POST['code'] );
642
643
            $response['success']        = false;
644
            $response['msg']            = '';
645
            $response['data']['code']   = $discount_code;
646
            
647
            $invoice = wpinv_get_invoice_cart();
648
            if ( empty( $invoice->ID ) ) {
649
                $response['msg'] = __( 'Invalid checkout request.', 'invoicing' );
650
                wp_send_json( $response );
651
            }
652
653
            $wpi_userID = $invoice->get_user_id();
654
655
            if ( wpinv_is_discount_valid( $discount_code, $wpi_userID ) ) {
656
                $discount       = wpinv_get_discount_by_code( $discount_code );
657
                $discounts      = wpinv_set_cart_discount( $discount_code );
658
                $amount         = wpinv_format_discount_rate( wpinv_get_discount_type( $discount->ID ), wpinv_get_discount_amount( $discount->ID ) );
0 ignored issues
show
Unused Code introduced by
The assignment to $amount is dead and can be removed.
Loading history...
659
                $total          = wpinv_get_cart_total( null, $discounts );
0 ignored issues
show
Unused Code introduced by
The assignment to $total is dead and can be removed.
Loading history...
660
                $cart_totals    = wpinv_recalculate_tax( true );
661
            
662
                if ( !empty( $cart_totals ) ) {
663
                    $response['success']        = true;
664
                    $response['data']           = $cart_totals;
665
                    $response['data']['code']   = $discount_code;
666
                } else {
667
                    $response['success']        = false;
668
                }
669
            } else {
670
                $errors = wpinv_get_errors();
671
                $response['msg']  = $errors['wpinv-discount-error'];
672
                wpinv_unset_error( 'wpinv-discount-error' );
673
            }
674
675
            // Allow for custom discount code handling
676
            $response = apply_filters( 'wpinv_ajax_discount_response', $response );
677
        }
678
        
679
        wp_send_json( $response );
680
    }
681
    
682
    public static function remove_discount() {
683
        check_ajax_referer( 'wpinv-nonce', '_nonce' );
684
        
685
        $response = array();
686
        
687
        if ( isset( $_POST['code'] ) ) {
688
            $discount_code  = sanitize_text_field( $_POST['code'] );
689
            $discounts      = wpinv_unset_cart_discount( $discount_code );
690
            $total          = wpinv_get_cart_total( null, $discounts );
0 ignored issues
show
Unused Code introduced by
The assignment to $total is dead and can be removed.
Loading history...
691
            $cart_totals    = wpinv_recalculate_tax( true );
692
            
693
            if ( !empty( $cart_totals ) ) {
694
                $response['success']        = true;
695
                $response['data']           = $cart_totals;
696
                $response['data']['code']   = $discount_code;
697
            } else {
698
                $response['success']        = false;
699
            }
700
            
701
            // Allow for custom discount code handling
702
            $response = apply_filters( 'wpinv_ajax_discount_response', $response );
703
        }
704
        
705
        wp_send_json( $response );
706
    }
707
708
    /**
709
     * Retrieves the markup for a payment form.
710
     */
711
    public static function get_payment_form() {
712
713
        // Check nonce.
714
        if ( ! isset( $_GET['nonce'] ) || ! wp_verify_nonce( $_GET['nonce'], 'getpaid_ajax_form' ) ) {
715
            _e( 'Error: Reload the page and try again.', 'invoicing' );
716
            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...
717
        }
718
719
        // Is the request set up correctly?
720
		if ( empty( $_GET['form'] ) && empty( $_GET['item'] ) ) {
721
			echo aui()->alert(
0 ignored issues
show
Bug introduced by
The function aui was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

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

721
			echo /** @scrutinizer ignore-call */ aui()->alert(
Loading history...
722
				array(
723
					'type'    => 'warning',
724
					'content' => __( 'No payment form or item provided', 'invoicing' ),
725
				)
726
            );
727
            exit;
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

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

Loading history...
728
        }
729
730
        // Payment form or button?
731
		if ( ! empty( $_GET['form'] ) ) {
732
            echo getpaid_display_payment_form( $_GET['form'] );
733
		} else if( $_GET['invoice'] ) {
734
		    echo getpaid_display_invoice_payment_form( $_GET['invoice'] );
735
        } else {
736
			$items = getpaid_convert_items_to_array( $_GET['item'] );
737
		    echo getpaid_display_item_payment_form( $items );
738
        }
739
        
740
        exit;
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

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

Loading history...
741
742
    }
743
744
    /**
745
     * Payment forms.
746
     *
747
     * @since 1.0.18
748
     */
749
    public static function payment_form() {
750
        global $invoicing, $wpi_checkout_id, $cart_total;
751
752
        // Check nonce.
753
        if ( ! isset( $_POST['wpinv_payment_form'] ) || ! wp_verify_nonce( $_POST['wpinv_payment_form'], 'wpinv_payment_form' ) ) {
754
            wp_send_json_error( __( 'Security checks failed.', 'invoicing' ) );
755
        }
756
757
        // Prepare submitted data...
758
        $data = wp_unslash( $_POST );
759
760
        // ... form fields...
761
        if ( empty( $data['form_id'] ) || 'publish' != get_post_status( $data['form_id'] ) ) {
762
            wp_send_json_error( __( 'This payment form is no longer active.', 'invoicing' ) );
763
        }
764
765
        if ( empty( $data['billing_email'] ) || ! is_email( $data['billing_email'] ) ) {
766
            wp_send_json_error( __( 'Provide a valid billing email.', 'invoicing' ) );
767
        }
768
769
        $prepared = array(
770
            'billing_email'                    => sanitize_email( $data['billing_email'] ),
771
            __( 'Billing Email', 'invoicing' ) => sanitize_email( $data['billing_email'] ),
772
            __( 'Form Id', 'invoicing' )       => absint( $data['form_id'] ),
773
        );
774
775
        // Do we have a discount?
776
        $discount = 0;
777
        if ( ! empty( $data['discount'] ) ) {
778
779
            // Validate discount.
780
            $discount = self::payment_form_validate_discount( $data );
781
782
            if ( is_string( $discount ) ){
783
                wp_send_json_error( $discount );
784
            }
785
786
            if ( is_array( $discount ) ){
787
                $discount = $discount[ 'discount' ];
788
            }
789
790
            if ( ! $discount ) {
791
                $discount = 0;
792
            }
793
794
        }
795
796
        $fields = $invoicing->form_elements->get_form_elements( $data['form_id'] );
797
798
        // ... and form items.
799
        if ( ! empty( $data['invoice_id'] ) ) {
800
            $invoice = wpinv_get_invoice( $data['invoice_id'] );
801
802
            if ( empty( $invoice ) ) {
803
                wp_send_json_error( __( 'Invalid invoice.', 'invoicing' ) );
804
            }
805
806
            if ( $invoice->is_paid() ) {
807
                wp_send_json_error( __( 'This invoice has already been paid.', 'invoicing' ) );
808
            }
809
810
            $items   = $invoicing->form_elements->convert_checkout_items( $invoice->cart_details, $invoice );
811
812
        } else {
813
814
            if ( isset( $data['form_items'] ) ) {
815
                $items = getpaid_convert_items_to_array( $data['form_items'] );
816
                $items = $invoicing->form_elements->convert_normal_items( $items );
817
            } else {
818
                $items = $invoicing->form_elements->get_form_items( $data['form_id'] );
819
            }
820
821
            $invoice = 0;
822
        }
823
824
        $prepared_items = array();
825
        $address_fields = array();
826
827
        if ( ! empty( $data['wpinv-items'] ) ) {
828
829
            $selected_items = wpinv_clean( $data['wpinv-items'] );
830
831
            foreach ( $items as $item ) {
832
833
                if ( ! empty( $item['required'] ) && ! isset( $selected_items[ $item['id'] ] ) ) {
834
                    wp_send_json_error( __( 'A required item is missing.', 'invoicing' ) );
835
                }
836
837
                if ( ! isset( $selected_items[ $item['id'] ] ) ) {
838
                    continue;
839
                }
840
841
                $quantity = empty( $item['quantity'] ) ? 1 : absint( $item['quantity'] );
842
843
                if ( ! empty( $item['allow_quantities'] ) && ! empty( $data["wpinv-item-{$item['id']}-quantity"] ) ) {
844
845
                    $_quantity = intval( $data["wpinv-item-{$item['id']}-quantity"] );
846
847
                    if ( ! empty( $_quantity ) ) {
848
                        $quantity = $_quantity;
849
                    }
850
                }
851
852
                // Custom pricing.
853
                if ( ! empty( $item['custom_price'] ) ) {
854
855
                    $minimum_price = wpinv_sanitize_amount( $item['minimum_price'] );
856
                    $set_price     = wpinv_sanitize_amount( $selected_items[ $item['id'] ] );
857
858
                    if ( $set_price < $minimum_price ) {
859
                        wp_send_json_error( __( 'The provided amount is less than the minimum allowed value.', 'invoicing' ) );
860
                    }
861
862
                    $prepared_items[] = array(
863
                        'id'           =>$item['id'],
864
                        'item_price'   => wpinv_sanitize_amount( $item['price'] ),
865
                        'custom_price' => $set_price,
866
                        'name'         => $item['title'],
867
                        'quantity'     => $quantity,
868
                    );
869
870
                } else {
871
872
                    $prepared_items[] = array(
873
                        'id'           => $item['id'],
874
                        'item_price'   => wpinv_sanitize_amount( $item['price'] ),
875
                        'custom_price' => wpinv_sanitize_amount( $item['price'] ),
876
                        'name'         => $item['title'],
877
                        'quantity'     => $quantity,
878
                    );
879
880
                }
881
882
            }
883
884
        } else {
885
886
            wp_send_json_error( __( 'You have not selected any items.', 'invoicing' ) );
887
888
        }
889
890
        // Are all required fields provided?
891
        foreach ( $fields as $field ) {
892
893
            if ( ! empty( $field['premade'] ) ) {
894
                continue;
895
            }
896
897
            if ( ! empty( $field['required'] ) && empty( $data[ $field['id'] ] ) ) {
898
                wp_send_json_error( __( 'Some required fields have not been filled.', 'invoicing' ) );
899
            }
900
901
            if ( $field['type'] == 'address' ) {
902
903
                foreach ( $field['fields'] as $address_field ) {
904
905
                    if ( empty( $address_field['visible'] ) ) {
906
                        continue;
907
                    }
908
909
                    if ( ! empty( $address_field['required'] ) && empty( $data[ $address_field['name'] ] ) ) {
910
                        wp_send_json_error( __( 'Some required fields have not been filled.', 'invoicing' ) );
911
                    }
912
913
                    if ( isset( $data[ $address_field['name'] ] ) ) {
914
                        $label = str_replace( 'wpinv_', '', $address_field['name'] );
915
                        $address_fields[ $label ] = wpinv_clean( $data[ $address_field['name'] ] );
916
                    }
917
918
                }
919
920
            } else if ( isset( $data[ $field['id'] ] ) ) {
921
                $label = $field['id'];
922
923
                if ( isset( $field['label'] ) ) {
924
                    $label = $field['label'];
925
                }
926
927
                $prepared[ wpinv_clean( $label ) ] = wpinv_clean( $data[ $field['id'] ] );
928
            }
929
930
        }
931
932
        $user = get_user_by( 'email', $prepared['billing_email'] );
933
934
        if ( empty( $user ) ) {
935
            $user = wpinv_create_user( $prepared['billing_email'] );
936
        }
937
938
        if ( is_wp_error( $user ) ) {
939
            wp_send_json_error( $user->get_error_message() );
940
        }
941
942
        if ( is_numeric( $user ) ) {
943
            $user = get_user_by( 'id', $user );
944
        }
945
946
        if ( $discount ) {
947
            $address_fields['discount'] = array( $data['discount'] );
948
        }
949
950
        // Create the invoice.
951
        if ( empty( $invoice ) ) {
952
953
            $invoice = wpinv_insert_invoice(
954
                array(
955
                    'status'        => 'wpi-pending',
956
                    'created_via'   => 'payment_form',
957
                    'user_id'       => $user->ID,
0 ignored issues
show
Bug introduced by
The property ID does not seem to exist on WP_Error.
Loading history...
958
                    'cart_details'  => $prepared_items,
959
                    'user_info'     => $address_fields,
960
                ),
961
                true
962
            );
963
964
        } else {
965
966
            $invoice = wpinv_update_invoice(
967
                array(
968
                    'ID'            => $invoice->ID,
969
                    'status'        => 'wpi-pending',
970
                    'cart_details'  => $prepared_items,
971
                    'user_info'     => $address_fields,
972
                ),
973
                true
974
            );
975
976
        }
977
        
978
979
        if ( is_wp_error( $invoice ) ) {
980
            wp_send_json_error( $invoice->get_error_message() );
0 ignored issues
show
Bug introduced by
The method get_error_message() does not exist on WPInv_Invoice. ( Ignorable by Annotation )

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

980
            wp_send_json_error( $invoice->/** @scrutinizer ignore-call */ get_error_message() );

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...
981
        }
982
983
        if ( empty( $invoice ) ) {
984
            wp_send_json_error( __( 'Could not create your invoice.', 'invoicing' ) );
985
        }
986
987
        unset( $prepared['billing_email'] );
988
        update_post_meta( $invoice->ID, 'payment_form_data', $prepared );
989
990
        $wpi_checkout_id = $invoice->ID;
991
        $cart_total = wpinv_price(
992
            wpinv_format_amount(
993
                wpinv_get_cart_total( $invoice->get_cart_details(), NULL, $invoice ) ),
0 ignored issues
show
Bug introduced by
The method get_cart_details() 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

993
                wpinv_get_cart_total( $invoice->/** @scrutinizer ignore-call */ get_cart_details(), NULL, $invoice ) ),

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...
994
                $invoice->get_currency()
0 ignored issues
show
Bug introduced by
The method get_currency() 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

994
                $invoice->/** @scrutinizer ignore-call */ 
995
                          get_currency()

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...
995
        );
996
997
        $data                   = array();
998
        $data['invoice_id']     = $invoice->ID;
999
        $data['cart_discounts'] = $invoice->get_discounts( true );
0 ignored issues
show
Bug introduced by
The method get_discounts() 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

999
        /** @scrutinizer ignore-call */ 
1000
        $data['cart_discounts'] = $invoice->get_discounts( true );

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...
1000
1001
        wpinv_set_checkout_session( $data );
1002
        add_filter( 'wp_redirect', array( $invoicing->form_elements, 'send_redirect_response' ) );
1003
        add_action( 'wpinv_pre_send_back_to_checkout', array( $invoicing->form_elements, 'checkout_error' ) );
1004
        
1005
        if ( ! defined( 'WPINV_CHECKOUT' ) ) {
1006
            define( 'WPINV_CHECKOUT', true );
1007
        }
1008
1009
        wpinv_process_checkout();
1010
1011
        $invoicing->form_elements->checkout_error();
1012
1013
        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...
1014
    }
1015
1016
    /**
1017
     * Payment forms.
1018
     *
1019
     * @since 1.0.18
1020
     */
1021
    public static function get_payment_form_states_field() {
1022
        global $invoicing;
1023
1024
        if ( empty( $_GET['country'] ) || empty( $_GET['form'] ) ) {
1025
            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...
1026
        }
1027
1028
        $elements = $invoicing->form_elements->get_form_elements( $_GET['form'] );
1029
1030
        if ( empty( $elements ) ) {
1031
            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...
1032
        }
1033
1034
        $address_fields = array();
1035
        foreach ( $elements as $element ) {
1036
            if ( 'address' === $element['type'] ) {
1037
                $address_fields = $element;
1038
                break;
1039
            }
1040
        }
1041
1042
        if ( empty( $address_fields ) ) {
1043
            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...
1044
        }
1045
1046
        foreach( $address_fields['fields'] as $address_field ) {
1047
1048
            if ( 'wpinv_state' == $address_field['name'] ) {
1049
1050
                $label = $address_field['label'];
1051
1052
                if ( ! empty( $address_field['required'] ) ) {
1053
                    $label .= "<span class='text-danger'> *</span>";
1054
                }
1055
1056
                $states = wpinv_get_country_states( $_GET['country'] );
1057
1058
                if ( ! empty( $states ) ) {
1059
1060
                    $html = aui()->select(
0 ignored issues
show
Bug introduced by
The function aui was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

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

1060
                    $html = /** @scrutinizer ignore-call */ aui()->select(
Loading history...
1061
                            array(
1062
                                'options'          => $states,
1063
                                'name'             => esc_attr( $address_field['name'] ),
1064
                                'id'               => esc_attr( $address_field['name'] ),
1065
                                'placeholder'      => esc_attr( $address_field['placeholder'] ),
1066
                                'required'         => (bool) $address_field['required'],
1067
                                'no_wrap'          => true,
1068
                                'label'            => wp_kses_post( $label ),
1069
                                'select2'          => false,
1070
                            )
1071
                        );
1072
1073
                } else {
1074
1075
                    $html = aui()->input(
1076
                            array(
1077
                                'name'       => esc_attr( $address_field['name'] ),
1078
                                'id'         => esc_attr( $address_field['name'] ),
1079
                                'required'   => (bool) $address_field['required'],
1080
                                'label'      => wp_kses_post( $label ),
1081
                                'no_wrap'    => true,
1082
                                'type'       => 'text',
1083
                            )
1084
                        );
1085
1086
                }
1087
1088
                wp_send_json_success( str_replace( 'sr-only', '', $html ) );
1089
                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...
1090
1091
            }
1092
1093
        }
1094
    
1095
        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...
1096
    }
1097
1098
    /**
1099
     * Apply taxes.
1100
     *
1101
     * @since 1.0.18
1102
     */
1103
    public static function payment_form_get_taxes() {
1104
        global $invoicing;
1105
1106
        // Check nonce.
1107
        check_ajax_referer( 'wpinv_payment_form', 'wpinv_payment_form' );
1108
1109
        // Prepare submitted data...
1110
        $data = wp_unslash( $_POST );
1111
1112
        // ... form fields...
1113
        if ( empty( $data['form_id'] ) || 'publish' != get_post_status( $data['form_id'] ) ) {
1114
            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...
1115
        }
1116
1117
        // Do we have a discount?
1118
        if ( ! empty( $data['discount'] ) ) {
1119
1120
            // Validate discount.
1121
            $discount = self::payment_form_validate_discount( $data );
1122
1123
            if ( is_array( $discount ) ){
1124
                $discount = array_map( 'wpinv_format_amount', $discount );
1125
                $discount = array_map( 'wpinv_price', $discount );
1126
                wp_send_json_success( $discount );
1127
            }
1128
1129
        }        
1130
1131
        // For existing invoices.
1132
        if ( ! empty( $data['invoice_id'] ) ) {
1133
            $invoice = wpinv_get_invoice( $data['invoice_id'] );
1134
1135
            if ( empty( $invoice ) ) {
1136
                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...
1137
            }
1138
1139
            $items   = $invoicing->form_elements->convert_checkout_items( $invoice->cart_details, $invoice );
1140
            $country = $invoice->country;
1141
            $state   = $invoice->state;
1142
1143
        } else {
1144
1145
            if ( isset( $data['form_items'] ) ) {
1146
                $items = getpaid_convert_items_to_array( $data['form_items'] );
1147
                $items = $invoicing->form_elements->convert_normal_items( $items );
1148
            } else {
1149
                $items = $invoicing->form_elements->get_form_items( $data['form_id'] );
1150
            }
1151
1152
            $country   = wpinv_default_billing_country();
1153
            $state     = false;
1154
        }
1155
1156
        // What we will calculate.
1157
        $total     = 0;
1158
        $tax       = 0;
1159
        $sub_total = 0;
1160
1161
        if ( ! empty( $data['wpinv_country'] ) ) {
1162
            $country = $data['wpinv_country'];
1163
        }
1164
1165
        if ( ! empty( $data['wpinv_state'] ) ) {
1166
            $state = $data['wpinv_state'];
1167
        }
1168
1169
        if ( ! empty( $data['wpinv-items'] ) ) {
1170
1171
            $selected_items = wpinv_clean( $data['wpinv-items'] );
1172
1173
            foreach ( $items as $item ) {
1174
1175
                if ( ! isset( $selected_items[ $item['id'] ] ) ) {
1176
                    continue;
1177
                }
1178
1179
                $quantity = empty( $item['quantity'] ) ? 1 : absint( $item['quantity'] );
1180
1181
                if ( ! empty( $item['allow_quantities'] ) && ! empty( $data["wpinv-item-{$item['id']}-quantity"] ) ) {
1182
1183
                    $quantity = intval( $data["wpinv-item-{$item['id']}-quantity"] );
1184
1185
                    if ( 1 > $quantity ) {
1186
                        $quantity = 1;
1187
                    }
1188
1189
                }
1190
1191
                // Custom pricing.
1192
                $price = wpinv_sanitize_amount( $item['price'] );
1193
                if ( ! empty( $item['custom_price'] ) ) {
1194
1195
                    $minimum_price = wpinv_sanitize_amount( $item['minimum_price'] );
1196
                    $set_price     = wpinv_sanitize_amount( $selected_items[ $item['id'] ] );
1197
1198
                    if ( $set_price < $minimum_price ) {
1199
                        $set_price = $minimum_price;
1200
                    }
1201
1202
                    $price = wpinv_sanitize_amount( $set_price );
1203
1204
                }
1205
1206
                $price  = $quantity * floatval( $price );
1207
1208
                if ( wpinv_use_taxes() ) {
1209
1210
                    $rate = wpinv_get_tax_rate( $country, $state, (int) $item['id'] );
1211
1212
                    if ( wpinv_prices_include_tax() ) {
1213
                        $pre_tax  = ( $price - $price * $rate * 0.01 );
1214
                        $item_tax = $price - $pre_tax;
1215
                    } else {
1216
                        $pre_tax  = $price;
1217
                        $item_tax = $price * $rate * 0.01;
1218
                    }
1219
1220
                    $tax       = $tax + $item_tax;
1221
                    $sub_total = $sub_total + $pre_tax;
1222
                    $total     = $sub_total + $tax;
1223
1224
                } else {
1225
                    $total  = $total + $price;
1226
                }
1227
1228
            }
1229
1230
        }
1231
1232
        wp_send_json_success( array(
1233
            'total'     => wpinv_price( wpinv_format_amount( $total ) ),
1234
            'tax'       => wpinv_price( wpinv_format_amount( $tax ) ),
1235
            'sub_total' => wpinv_price( wpinv_format_amount( $sub_total ) ),
1236
            'discount'  => false,
1237
        ));
1238
        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...
1239
    }
1240
1241
    /**
1242
     * Apply discounts.
1243
     *
1244
     * @since 1.0.19
1245
     */
1246
    public static function payment_form_discount() {
1247
1248
        // Check nonce.
1249
        check_ajax_referer( 'wpinv_payment_form', 'wpinv_payment_form' );
1250
1251
        // Prepare submitted data...
1252
        $data = wp_unslash( $_POST );
1253
1254
        // ... form fields...
1255
        if ( empty( $data['form_id'] ) || 'publish' != get_post_status( $data['form_id'] ) ) {
1256
            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...
1257
        }
1258
1259
        // Do we have a discount?
1260
        if ( empty( $data['discount'] ) ) {
1261
            _e( 'Please enter your discount code', 'invoicing' );
1262
            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...
1263
        }
1264
1265
        // Validate discount.
1266
        $data = self::payment_form_validate_discount( $data );
1267
1268
        if ( false === $data ) {
1269
            _e( 'There was an error applying your discount code', 'invoicing' );
1270
            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...
1271
        }
1272
1273
        if ( is_string( $data ) ) {
1274
            echo $data;
1275
            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...
1276
        }
1277
1278
        $data = array_map( 'wpinv_format_amount', $data );
1279
        $data = array_map( 'wpinv_price', $data );
1280
        wp_send_json_success( $data );
1281
        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...
1282
1283
    }
1284
1285
    /**
1286
     * Validates discounts.
1287
     *
1288
     * @since 1.0.19
1289
     */
1290
    public static function payment_form_validate_discount( $data ) {
1291
        global $invoicing;
1292
1293
        // Do we have a discount?
1294
        if ( empty( $data['discount'] ) ) {
1295
            return false;
1296
        }
1297
1298
        // If yes, ensure that it exists.
1299
        $discount = wpinv_get_discount_obj( $data['discount'] );
1300
1301
        // Ensure it is active.
1302
        if ( ! $discount->exists() || ! $discount->is_active() || ! $discount->has_started() || $discount->is_expired() ) {
1303
            return __( 'This discount code is not valid', 'invoicing' );
1304
        }
1305
1306
        // If it can only be used once per user...
1307
        if ( $discount->is_single_use ) {
1308
1309
            if ( empty( $data['billing_email'] ) ) {
1310
                return __( 'Please enter your billing email before applying this discount', 'invoicing' );
1311
            }
1312
1313
            if ( ! $discount->is_valid_for_user( $data['billing_email'] ) ) {
1314
                return __( 'You have already used this discount', 'invoicing' );
1315
            }
1316
1317
        }
1318
1319
        // Prepare items.
1320
        if ( ! empty( $data['invoice_id'] ) ) {
1321
            $invoice = wpinv_get_invoice( $data['invoice_id'] );
1322
1323
            if ( empty( $invoice ) ) {
1324
                return false;
1325
            }
1326
1327
            $country = $invoice->country;
1328
            $state   = $invoice->state;
1329
            $items   = $invoicing->form_elements->convert_checkout_items( $invoice->cart_details, $invoice );
1330
1331
        } else {
1332
1333
            if ( isset( $data['form_items'] ) ) {
1334
                $items = getpaid_convert_items_to_array( $data['form_items'] );
1335
                $items = $invoicing->form_elements->convert_normal_items( $items );
1336
            } else {
1337
                $items = $invoicing->form_elements->get_form_items( $data['form_id'] );
1338
            }
1339
1340
            $country   = wpinv_default_billing_country();
1341
            $state     = false;
1342
1343
        }
1344
1345
        // What we will calculate.
1346
        $total     = 0;
1347
        $tax       = 0;
1348
        $sub_total = 0;
1349
1350
        if ( ! empty( $data['wpinv_country'] ) ) {
1351
            $country = $data['wpinv_country'];
1352
        }
1353
1354
        if ( ! empty( $data['wpinv_state'] ) ) {
1355
            $state = $data['wpinv_state'];
1356
        }
1357
1358
        if ( ! empty( $data['wpinv-items'] ) ) {
1359
1360
            $selected_items = wpinv_clean( $data['wpinv-items'] );
1361
1362
            // Check if it is valid for the selected items.
1363
            if ( ! $discount->is_valid_for_items( array_keys( $selected_items ) ) ) {
0 ignored issues
show
Bug introduced by
It seems like $selected_items can also be of type string; however, parameter $input of array_keys() does only seem to accept array, 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

1363
            if ( ! $discount->is_valid_for_items( array_keys( /** @scrutinizer ignore-type */ $selected_items ) ) ) {
Loading history...
1364
                return __( 'This discount is not valid for the items in your cart', 'invoicing' );
1365
            }
1366
1367
            foreach ( $items as $item ) {
1368
1369
                if ( ! isset( $selected_items[ $item['id'] ] ) ) {
1370
                    continue;
1371
                }
1372
1373
                $quantity = empty( $item['quantity'] ) ? 1 : absint( $item['quantity'] );
1374
1375
                if ( ! empty( $item['allow_quantities'] ) && ! empty( $data["wpinv-item-{$item['id']}-quantity"] ) ) {
1376
1377
                    $quantity = intval( $data["wpinv-item-{$item['id']}-quantity"] );
1378
1379
                    if ( 1 > $quantity ) {
1380
                        $quantity = 1;
1381
                    }
1382
1383
                }
1384
1385
                // Custom pricing.
1386
                $price = wpinv_sanitize_amount( $item['price'] );
1387
                if ( ! empty( $item['custom_price'] ) ) {
1388
1389
                    $minimum_price = wpinv_sanitize_amount( $item['minimum_price'] );
1390
                    $set_price     = wpinv_sanitize_amount( $selected_items[ $item['id'] ] );
1391
1392
                    if ( $set_price < $minimum_price ) {
1393
                        $set_price = $minimum_price;
1394
                    }
1395
1396
                    $price = wpinv_sanitize_amount( $set_price );
1397
1398
                }
1399
1400
                $price  = $quantity * floatval( $price );
1401
1402
                if ( wpinv_use_taxes() ) {
1403
1404
                    $rate = wpinv_get_tax_rate( $country, $state, (int) $item['id'] );
1405
1406
                    if ( wpinv_prices_include_tax() ) {
1407
                        $pre_tax  = ( $price - $price * $rate * 0.01 );
1408
                        $item_tax = $price - $pre_tax;
1409
                    } else {
1410
                        $pre_tax  = $price;
1411
                        $item_tax = $price * $rate * 0.01;
1412
                    }
1413
1414
                    $tax       = $tax + $item_tax;
1415
                    $sub_total = $sub_total + $pre_tax;
1416
                    $total     = $sub_total + $tax;
1417
1418
                } else {
1419
                    $total  = $total + $price;
1420
                }
1421
1422
            }
1423
1424
        }
1425
1426
        if ( ! $discount->is_minimum_amount_met( $total ) ) {
1427
            $min = wpinv_price( wpinv_format_amount( $discount->min_total ) );
1428
            return sprintf( __( 'The minimum total for using this discount is %s', 'invoicing' ), $min );
1429
        }
1430
1431
        if ( ! $discount->is_maximum_amount_met( $total ) ) {
1432
            $max = wpinv_price( wpinv_format_amount( $discount->max_total ) );
1433
            return sprintf( __( 'The maximum total for using this discount is %s', 'invoicing' ), $max );
1434
        }
1435
1436
        $discount = $discount->get_discounted_amount( $total );
1437
        $total    = $total - $discount;
1438
        return compact( 'total', 'tax', 'sub_total', 'discount' );
1439
1440
    }
1441
1442
    /**
1443
     * Lets users buy items via ajax.
1444
     *
1445
     * @since 1.0.0
1446
     */
1447
    public static function buy_items() {
1448
        $user_id = get_current_user_id();
1449
1450
        if ( empty( $user_id ) ) { // If not logged in then lets redirect to the login page
1451
            wp_send_json( array(
1452
                '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

1452
                'success' => wp_login_url( /** @scrutinizer ignore-type */ wp_get_referer() )
Loading history...
1453
            ) );
1454
        } else {
1455
            // Only check nonce if logged in as it could be cached when logged out.
1456
            if ( ! isset( $_POST['wpinv_buy_nonce'] ) || ! wp_verify_nonce( $_POST['wpinv_buy_nonce'], 'wpinv_buy_items' ) ) {
1457
                wp_send_json( array(
1458
                    'error' => __( 'Security checks failed.', 'invoicing' )
1459
                ) );
1460
                wp_die();
1461
            }
1462
1463
            // allow to set a custom price through post_id
1464
            $items = $_POST['items'];
1465
            $related_post_id = isset( $_POST['post_id'] ) ? (int)$_POST['post_id'] : 0;
1466
            $custom_item_price = $related_post_id ? abs( get_post_meta( $related_post_id, '_wpi_custom_price', true ) ) : 0;
1467
1468
            $cart_items = array();
1469
            if ( $items ) {
1470
                $items = explode( ',', $items );
1471
1472
                foreach( $items as $item ) {
1473
                    $item_id = $item;
1474
                    $quantity = 1;
1475
1476
                    if ( strpos( $item, '|' ) !== false ) {
1477
                        $item_parts = explode( '|', $item );
1478
                        $item_id = $item_parts[0];
1479
                        $quantity = $item_parts[1];
1480
                    }
1481
1482
                    if ( $item_id && $quantity ) {
1483
                        $cart_items_arr = array(
1484
                            'id'            => (int)$item_id,
1485
                            'quantity'      => (int)$quantity
1486
                        );
1487
1488
                        // If there is a related post id then add it to meta
1489
                        if ( $related_post_id ) {
1490
                            $cart_items_arr['meta'] = array(
1491
                                'post_id'   => $related_post_id
1492
                            );
1493
                        }
1494
1495
                        // If there is a custom price then set it.
1496
                        if ( $custom_item_price ) {
1497
                            $cart_items_arr['custom_price'] = $custom_item_price;
1498
                        }
1499
1500
                        $cart_items[] = $cart_items_arr;
1501
                    }
1502
                }
1503
            }
1504
1505
            /**
1506
             * Filter the wpinv_buy shortcode cart items on the fly.
1507
             *
1508
             * @param array $cart_items The cart items array.
1509
             * @param int $related_post_id The related post id if any.
1510
             * @since 1.0.0
1511
             */
1512
            $cart_items = apply_filters( 'wpinv_buy_cart_items', $cart_items, $related_post_id );
1513
1514
            // Make sure its not in the cart already, if it is then redirect to checkout.
1515
            $cart_invoice = wpinv_get_invoice_cart();
1516
1517
            if ( isset( $cart_invoice->items ) && !empty( $cart_invoice->items ) && !empty( $cart_items ) && serialize( $cart_invoice->items ) == serialize( $cart_items ) ) {
1518
                wp_send_json( array(
1519
                    'success' =>  $cart_invoice->get_checkout_payment_url()
1520
                ) );
1521
                wp_die();
1522
            }
1523
1524
            // Check if user has invoice with same items waiting to be paid.
1525
            $user_invoices = wpinv_get_users_invoices( $user_id , 10 , false , 'wpi-pending' );
1526
            if ( !empty( $user_invoices ) ) {
1527
                foreach( $user_invoices as $user_invoice ) {
1528
                    $user_cart_details = array();
1529
                    $invoice  = wpinv_get_invoice( $user_invoice->ID );
1530
                    $cart_details = $invoice->get_cart_details();
1531
1532
                    if ( !empty( $cart_details ) ) {
1533
                        foreach ( $cart_details as $invoice_item ) {
1534
                            $ii_arr = array();
1535
                            $ii_arr['id'] = (int)$invoice_item['id'];
1536
                            $ii_arr['quantity'] = (int)$invoice_item['quantity'];
1537
1538
                            if (isset( $invoice_item['meta'] ) && !empty( $invoice_item['meta'] ) ) {
1539
                                $ii_arr['meta'] = $invoice_item['meta'];
1540
                            }
1541
1542
                            if ( isset( $invoice_item['custom_price'] ) && !empty( $invoice_item['custom_price'] ) ) {
1543
                                $ii_arr['custom_price'] = $invoice_item['custom_price'];
1544
                            }
1545
1546
                            $user_cart_details[] = $ii_arr;
1547
                        }
1548
                    }
1549
1550
                    if ( !empty( $user_cart_details ) && serialize( $cart_items ) == serialize( $user_cart_details ) ) {
1551
                        wp_send_json( array(
1552
                            'success' =>  $invoice->get_checkout_payment_url()
1553
                        ) );
1554
                        wp_die();
1555
                    }
1556
                }
1557
            }
1558
1559
            // Create invoice and send user to checkout
1560
            if ( !empty( $cart_items ) ) {
1561
                $invoice_data = array(
1562
                    'status'        =>  'wpi-pending',
1563
                    'created_via'   =>  'wpi',
1564
                    'user_id'       =>  $user_id,
1565
                    'cart_details'  =>  $cart_items,
1566
                );
1567
1568
                $invoice = wpinv_insert_invoice( $invoice_data, true );
1569
1570
                if ( !empty( $invoice ) && isset( $invoice->ID ) ) {
1571
                    wp_send_json( array(
1572
                        '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

1572
                        '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...
1573
                    ) );
1574
                } else {
1575
                    wp_send_json( array(
1576
                        'error' => __( 'Invoice failed to create', 'invoicing' )
1577
                    ) );
1578
                }
1579
            } else {
1580
                wp_send_json( array(
1581
                    'error' => __( 'Items not valid.', 'invoicing' )
1582
                ) );
1583
            }
1584
        }
1585
1586
        wp_die();
1587
    }
1588
}
1589
1590
WPInv_Ajax::init();