Passed
Pull Request — master (#279)
by Brian
05:56
created

WPInv_Ajax::create_invoice_item()   F

Complexity

Conditions 14
Paths 323

Size

Total Lines 50
Code Lines 32

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 14
eloc 32
nc 323
nop 0
dl 0
loc 50
rs 3.8958
c 0
b 0
f 0

How to fix   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
            'add_invoice_item' => false,
67
            'remove_invoice_item' => false,
68
            'create_invoice_item' => false,
69
            'get_billing_details' => false,
70
            'admin_recalculate_totals' => false,
71
            'admin_apply_discount' => false,
72
            'admin_remove_discount' => false,
73
            'check_email' => false,
74
            'run_tool' => false,
75
            'apply_discount' => true,
76
            'remove_discount' => true,
77
            'buy_items' => true,
78
        );
79
80
        foreach ( $ajax_events as $ajax_event => $nopriv ) {
81
            add_action( 'wp_ajax_wpinv_' . $ajax_event, array( __CLASS__, $ajax_event ) );
82
            
83
            if ( !defined( 'WPI_AJAX_' . strtoupper( $nopriv ) ) ) {
84
                define( 'WPI_AJAX_' . strtoupper( $nopriv ), 1 );
85
            }
86
87
            if ( $nopriv ) {
88
                add_action( 'wp_ajax_nopriv_wpinv_' . $ajax_event, array( __CLASS__, $ajax_event ) );
89
90
                add_action( 'wpinv_ajax_' . $ajax_event, array( __CLASS__, $ajax_event ) );
91
            }
92
        }
93
    }
94
    
95
    public static function add_note() {
96
        check_ajax_referer( 'add-invoice-note', '_nonce' );
97
98
        if ( ! wpinv_current_user_can_manage_invoicing() ) {
99
            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...
100
        }
101
102
        $post_id   = absint( $_POST['post_id'] );
103
        $note      = wp_kses_post( trim( stripslashes( $_POST['note'] ) ) );
104
        $note_type = sanitize_text_field( $_POST['note_type'] );
105
106
        $is_customer_note = $note_type == 'customer' ? 1 : 0;
107
108
        if ( $post_id > 0 ) {
109
            $note_id = wpinv_insert_payment_note( $post_id, $note, $is_customer_note );
110
111
            if ( $note_id > 0 && !is_wp_error( $note_id ) ) {
112
                wpinv_get_invoice_note_line_item( $note_id );
113
            }
114
        }
115
116
        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...
117
    }
118
119
    public static function delete_note() {
120
        check_ajax_referer( 'delete-invoice-note', '_nonce' );
121
122
        if ( !wpinv_current_user_can_manage_invoicing() ) {
123
            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...
124
        }
125
126
        $note_id = (int)$_POST['note_id'];
127
128
        if ( $note_id > 0 ) {
129
            wp_delete_comment( $note_id, true );
130
        }
131
132
        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...
133
    }
134
    
135
    public static function get_states_field() {
136
        echo wpinv_get_states_field();
137
        
138
        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...
139
    }
140
    
141
    public static function checkout() {
142
        if ( ! defined( 'WPINV_CHECKOUT' ) ) {
143
            define( 'WPINV_CHECKOUT', true );
144
        }
145
146
        wpinv_process_checkout();
147
        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...
148
    }
149
    
150
    public static function add_invoice_item() {
151
        global $wpi_userID, $wpinv_ip_address_country;
152
        check_ajax_referer( 'invoice-item', '_nonce' );
153
        if ( !wpinv_current_user_can_manage_invoicing() ) {
154
            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...
155
        }
156
        
157
        $item_id    = sanitize_text_field( $_POST['item_id'] );
158
        $invoice_id = absint( $_POST['invoice_id'] );
159
        
160
        if ( !is_numeric( $invoice_id ) || !is_numeric( $item_id ) ) {
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
        $invoice    = wpinv_get_invoice( $invoice_id );
165
        if ( empty( $invoice ) ) {
166
            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...
167
        }
168
        
169
        if ( $invoice->is_paid() || $invoice->is_refunded() ) {
170
            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...
171
        }
172
        
173
        if ( !empty( $_POST['user_id'] ) ) {
174
            $wpi_userID = absint( $_POST['user_id'] ); 
175
        }
176
177
        $item = new WPInv_Item( $item_id );
178
        if ( !( !empty( $item ) && $item->post_type == 'wpi_item' ) ) {
179
            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...
180
        }
181
        
182
        // Validate item before adding to invoice because recurring item must be paid individually.
183
        if ( !empty( $invoice->cart_details ) ) {
184
            $valid = true;
185
            
186
            if ( $recurring_item = $invoice->get_recurring() ) {
187
                if ( $recurring_item != $item_id ) {
188
                    $valid = false;
189
                }
190
            } else if ( wpinv_is_recurring_item( $item_id ) ) {
191
                $valid = false;
192
            }
193
            
194
            if ( !$valid ) {
195
                $response               = array();
196
                $response['success']    = false;
197
                $response['msg']        = __( 'You can not add item because recurring item must be paid individually!', 'invoicing' );
198
                wp_send_json( $response );
199
            }
200
        }
201
        
202
        $checkout_session = wpinv_get_checkout_session();
203
        
204
        $data                   = array();
205
        $data['invoice_id']     = $invoice_id;
206
        $data['cart_discounts'] = $invoice->get_discounts( true );
207
        
208
        wpinv_set_checkout_session( $data );
209
        
210
        $quantity = wpinv_item_quantities_enabled() && !empty($_POST['qty']) && (int)$_POST['qty'] > 0 ? (int)$_POST['qty'] : 1;
211
212
        $args = array(
213
            'id'            => $item_id,
214
            'quantity'      => $quantity,
215
            'item_price'    => $item->get_price(),
216
            'custom_price'  => '',
217
            'tax'           => 0.00,
218
            'discount'      => 0,
219
            'meta'          => array(),
220
            'fees'          => array()
221
        );
222
223
        $invoice->add_item( $item_id, $args );
224
        $invoice->save();
225
        
226
        if ( empty( $_POST['country'] ) ) {
227
            $_POST['country'] = !empty($invoice->country) ? $invoice->country : wpinv_get_default_country();
228
        }
229
        if ( empty( $_POST['state'] ) ) {
230
            $_POST['state'] = $invoice->state;
231
        }
232
         
233
        $invoice->country   = sanitize_text_field( $_POST['country'] );
234
        $invoice->state     = sanitize_text_field( $_POST['state'] );
235
        
236
        $invoice->set( 'country', sanitize_text_field( $_POST['country'] ) );
237
        $invoice->set( 'state', sanitize_text_field( $_POST['state'] ) );
238
        
239
        $wpinv_ip_address_country = $invoice->country;
240
241
        $invoice->recalculate_totals(true);
242
        
243
        $response                       = array();
244
        $response['success']            = true;
245
        $response['data']['items']      = wpinv_admin_get_line_items( $invoice );
246
        $response['data']['subtotal']   = $invoice->get_subtotal();
247
        $response['data']['subtotalf']  = $invoice->get_subtotal(true);
248
        $response['data']['tax']        = $invoice->get_tax();
249
        $response['data']['taxf']       = $invoice->get_tax(true);
250
        $response['data']['discount']   = $invoice->get_discount();
251
        $response['data']['discountf']  = $invoice->get_discount(true);
252
        $response['data']['total']      = $invoice->get_total();
253
        $response['data']['totalf']     = $invoice->get_total(true);
254
        
255
        wpinv_set_checkout_session($checkout_session);
256
        
257
        wp_send_json( $response );
258
    }
259
    
260
    public static function remove_invoice_item() {
261
        global $wpi_userID, $wpinv_ip_address_country;
262
        
263
        check_ajax_referer( 'invoice-item', '_nonce' );
264
        if ( !wpinv_current_user_can_manage_invoicing() ) {
265
            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...
266
        }
267
        
268
        $item_id    = sanitize_text_field( $_POST['item_id'] );
269
        $invoice_id = absint( $_POST['invoice_id'] );
270
        $cart_index = isset( $_POST['index'] ) && $_POST['index'] >= 0 ? $_POST['index'] : false;
271
        
272
        if ( !is_numeric( $invoice_id ) || !is_numeric( $item_id ) ) {
273
            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...
274
        }
275
276
        $invoice    = wpinv_get_invoice( $invoice_id );
277
        if ( empty( $invoice ) ) {
278
            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...
279
        }
280
        
281
        if ( $invoice->is_paid() || $invoice->is_refunded() ) {
282
            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...
283
        }
284
        
285
        if ( !empty( $_POST['user_id'] ) ) {
286
            $wpi_userID = absint( $_POST['user_id'] ); 
287
        }
288
289
        $item       = new WPInv_Item( $item_id );
290
        if ( !( !empty( $item ) && $item->post_type == 'wpi_item' ) ) {
291
            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...
292
        }
293
        
294
        $checkout_session = wpinv_get_checkout_session();
295
        
296
        $data                   = array();
297
        $data['invoice_id']     = $invoice_id;
298
        $data['cart_discounts'] = $invoice->get_discounts( true );
299
        
300
        wpinv_set_checkout_session( $data );
301
302
        $args = array(
303
            'id'         => $item_id,
304
            'quantity'   => 1,
305
            'cart_index' => $cart_index
306
        );
307
308
        $invoice->remove_item( $item_id, $args );
309
        $invoice->save();
310
        
311
        if ( empty( $_POST['country'] ) ) {
312
            $_POST['country'] = !empty($invoice->country) ? $invoice->country : wpinv_get_default_country();
313
        }
314
        if ( empty( $_POST['state'] ) ) {
315
            $_POST['state'] = $invoice->state;
316
        }
317
         
318
        $invoice->country   = sanitize_text_field( $_POST['country'] );
319
        $invoice->state     = sanitize_text_field( $_POST['state'] );
320
        
321
        $invoice->set( 'country', sanitize_text_field( $_POST['country'] ) );
322
        $invoice->set( 'state', sanitize_text_field( $_POST['state'] ) );
323
        
324
        $wpinv_ip_address_country = $invoice->country;
325
        
326
        $invoice->recalculate_totals(true);
327
        
328
        $response                       = array();
329
        $response['success']            = true;
330
        $response['data']['items']      = wpinv_admin_get_line_items( $invoice );
331
        $response['data']['subtotal']   = $invoice->get_subtotal();
332
        $response['data']['subtotalf']  = $invoice->get_subtotal(true);
333
        $response['data']['tax']        = $invoice->get_tax();
334
        $response['data']['taxf']       = $invoice->get_tax(true);
335
        $response['data']['discount']   = $invoice->get_discount();
336
        $response['data']['discountf']  = $invoice->get_discount(true);
337
        $response['data']['total']      = $invoice->get_total();
338
        $response['data']['totalf']     = $invoice->get_total(true);
339
        
340
        wpinv_set_checkout_session($checkout_session);
341
        
342
        wp_send_json( $response );
343
    }
344
    
345
    public static function create_invoice_item() {
346
        check_ajax_referer( 'invoice-item', '_nonce' );
347
        if ( !wpinv_current_user_can_manage_invoicing() ) {
348
            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...
349
        }
350
        
351
        $invoice_id = absint( $_POST['invoice_id'] );
352
353
        // Find the item
354
        if ( !is_numeric( $invoice_id ) ) {
355
            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...
356
        }        
357
        
358
        $invoice     = wpinv_get_invoice( $invoice_id );
359
        if ( empty( $invoice ) ) {
360
            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...
361
        }
362
        
363
        // Validate item before adding to invoice because recurring item must be paid individually.
364
        if ( !empty( $invoice->cart_details ) && $invoice->get_recurring() ) {
365
            $response               = array();
366
            $response['success']    = false;
367
            $response['msg']        = __( 'You can not add item because recurring item must be paid individually!', 'invoicing' );
368
            wp_send_json( $response );
369
        }        
370
        
371
        $save_item = wp_unslash( $_POST['_wpinv_quick'] );
372
        
373
        $meta               = array();
374
        $meta['type']       = !empty($save_item['type']) ? sanitize_text_field($save_item['type']) : 'custom';
375
        $meta['price']      = !empty($save_item['price']) ? wpinv_sanitize_amount( $save_item['price'] ) : 0;
376
        $meta['vat_rule']   = !empty($save_item['vat_rule']) ? sanitize_text_field($save_item['vat_rule']) : 'digital';
377
        $meta['vat_class']  = !empty($save_item['vat_class']) ? sanitize_text_field($save_item['vat_class']) : '_standard';
378
        
379
        $data                   = array();
380
        $data['post_title']     = sanitize_text_field($save_item['name']);
381
        $data['post_status']    = 'publish';
382
        $data['post_excerpt']   = ! empty( $save_item['excerpt'] ) ? wp_kses_post( $save_item['excerpt'] ) : '';
383
        $data['meta']           = $meta;
384
        
385
        $item = new WPInv_Item();
386
        $item->create( $data );
387
        
388
        if ( !empty( $item ) ) {
389
            $_POST['item_id']   = $item->ID;
390
            $_POST['qty']       = !empty($save_item['qty']) && $save_item['qty'] > 0 ? (int)$save_item['qty'] : 1;
391
            
392
            self::add_invoice_item();
393
        }
394
        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...
395
    }
396
    
397
    public static function get_billing_details() {
398
        check_ajax_referer( 'get-billing-details', '_nonce' );
399
        
400
        if ( !wpinv_current_user_can_manage_invoicing() ) {
401
            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...
402
        }
403
404
        $user_id            = (int)$_POST['user_id'];
405
        $billing_details    = wpinv_get_user_address($user_id);
406
        $billing_details    = apply_filters( 'wpinv_fill_billing_details', $billing_details, $user_id );
407
        
408
        if (isset($billing_details['user_id'])) {
409
            unset($billing_details['user_id']);
410
        }
411
        
412
        if (isset($billing_details['email'])) {
413
            unset($billing_details['email']);
414
        }
415
416
        $response                               = array();
417
        $response['success']                    = true;
418
        $response['data']['billing_details']    = $billing_details;
419
        
420
        wp_send_json( $response );
421
    }
422
    
423
    public static function admin_recalculate_totals() {
424
        global $wpi_userID, $wpinv_ip_address_country;
425
        
426
        check_ajax_referer( 'wpinv-nonce', '_nonce' );
427
        if ( !wpinv_current_user_can_manage_invoicing() ) {
428
            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...
429
        }
430
        
431
        $invoice_id = absint( $_POST['invoice_id'] );        
432
        $invoice    = wpinv_get_invoice( $invoice_id );
433
        if ( empty( $invoice ) ) {
434
            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...
435
        }
436
        
437
        $checkout_session = wpinv_get_checkout_session();
438
        
439
        $data                   = array();
440
        $data['invoice_id']     = $invoice_id;
441
        $data['cart_discounts'] = $invoice->get_discounts( true );
442
        
443
        wpinv_set_checkout_session( $data );
444
        
445
        if ( !empty( $_POST['user_id'] ) ) {
446
            $wpi_userID = absint( $_POST['user_id'] ); 
447
        }
448
        
449
        if ( empty( $_POST['country'] ) ) {
450
            $_POST['country'] = !empty($invoice->country) ? $invoice->country : wpinv_get_default_country();
451
        }
452
            
453
        $invoice->country = sanitize_text_field( $_POST['country'] );
454
        $invoice->set( 'country', sanitize_text_field( $_POST['country'] ) );
455
        if ( isset( $_POST['state'] ) ) {
456
            $invoice->state = sanitize_text_field( $_POST['state'] );
457
            $invoice->set( 'state', sanitize_text_field( $_POST['state'] ) );
458
        }
459
        
460
        $wpinv_ip_address_country = $invoice->country;
461
        
462
        $invoice = $invoice->recalculate_totals(true);
463
        
464
        $response                       = array();
465
        $response['success']            = true;
466
        $response['data']['items']      = wpinv_admin_get_line_items( $invoice );
467
        $response['data']['subtotal']   = $invoice->get_subtotal();
468
        $response['data']['subtotalf']  = $invoice->get_subtotal(true);
469
        $response['data']['tax']        = $invoice->get_tax();
470
        $response['data']['taxf']       = $invoice->get_tax(true);
471
        $response['data']['discount']   = $invoice->get_discount();
472
        $response['data']['discountf']  = $invoice->get_discount(true);
473
        $response['data']['total']      = $invoice->get_total();
474
        $response['data']['totalf']     = $invoice->get_total(true);
475
        
476
        wpinv_set_checkout_session($checkout_session);
477
        
478
        wp_send_json( $response );
479
    }
480
    
481
    public static function admin_apply_discount() {
482
        global $wpi_userID;
483
        
484
        check_ajax_referer( 'wpinv-nonce', '_nonce' );
485
        if ( !wpinv_current_user_can_manage_invoicing() ) {
486
            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...
487
        }
488
        
489
        $invoice_id = absint( $_POST['invoice_id'] );
490
        $discount_code = sanitize_text_field( $_POST['code'] );
491
        if ( empty( $invoice_id ) || empty( $discount_code ) ) {
492
            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...
493
        }
494
        
495
        $invoice = wpinv_get_invoice( $invoice_id );
496
        if ( empty( $invoice ) || ( !empty( $invoice ) && ( $invoice->is_paid() || $invoice->is_refunded() ) ) ) {
497
            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...
498
        }
499
        
500
        $checkout_session = wpinv_get_checkout_session();
501
        
502
        $data                   = array();
503
        $data['invoice_id']     = $invoice_id;
504
        $data['cart_discounts'] = $invoice->get_discounts( true );
505
        
506
        wpinv_set_checkout_session( $data );
507
        
508
        $response               = array();
509
        $response['success']    = false;
510
        $response['msg']        = __( 'This discount is invalid.', 'invoicing' );
511
        $response['data']['code'] = $discount_code;
512
        
513
        if ( wpinv_is_discount_valid( $discount_code, $invoice->get_user_id() ) ) {
514
            $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...
515
            
516
            $response['success'] = true;
517
            $response['msg'] = __( 'Discount has been applied successfully.', 'invoicing' );
518
        }  else {
519
            $errors = wpinv_get_errors();
520
            if ( !empty( $errors['wpinv-discount-error'] ) ) {
521
                $response['msg'] = $errors['wpinv-discount-error'];
522
            }
523
            wpinv_unset_error( 'wpinv-discount-error' );
524
        }
525
        
526
        wpinv_set_checkout_session($checkout_session);
527
        
528
        wp_send_json( $response );
529
    }
530
    
531
    public static function admin_remove_discount() {
532
        global $wpi_userID;
533
        
534
        check_ajax_referer( 'wpinv-nonce', '_nonce' );
535
        if ( !wpinv_current_user_can_manage_invoicing() ) {
536
            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...
537
        }
538
        
539
        $invoice_id = absint( $_POST['invoice_id'] );
540
        $discount_code = sanitize_text_field( $_POST['code'] );
541
        if ( empty( $invoice_id ) || empty( $discount_code ) ) {
542
            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...
543
        }
544
        
545
        $invoice = wpinv_get_invoice( $invoice_id );
546
        if ( empty( $invoice ) || ( !empty( $invoice ) && ( $invoice->is_paid() || $invoice->is_refunded() ) ) ) {
547
            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...
548
        }
549
        
550
        $checkout_session = wpinv_get_checkout_session();
551
        
552
        $data                   = array();
553
        $data['invoice_id']     = $invoice_id;
554
        $data['cart_discounts'] = $invoice->get_discounts( true );
555
        
556
        wpinv_set_checkout_session( $data );
557
        
558
        $response               = array();
559
        $response['success']    = false;
560
        $response['msg']        = NULL;
561
        
562
        $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...
563
        $response['success'] = true;
564
        $response['msg'] = __( 'Discount has been removed successfully.', 'invoicing' );
565
        
566
        wpinv_set_checkout_session($checkout_session);
567
        
568
        wp_send_json( $response );
569
    }
570
    
571
    public static function check_email() {
572
        check_ajax_referer( 'wpinv-nonce', '_nonce' );
573
        if ( !wpinv_current_user_can_manage_invoicing() ) {
574
            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...
575
        }
576
        
577
        $email = sanitize_text_field( $_POST['email'] );
578
        
579
        $response = array();
580
        if ( is_email( $email ) && email_exists( $email ) && $user_data = get_user_by( 'email', $email ) ) {
581
            $user_id            = $user_data->ID;
582
            $user_login         = $user_data->user_login;
583
            $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...
584
            $billing_details    = wpinv_get_user_address($user_id);
585
            $billing_details    = apply_filters( 'wpinv_fill_billing_details', $billing_details, $user_id );
586
            
587
            if (isset($billing_details['user_id'])) {
588
                unset($billing_details['user_id']);
589
            }
590
            
591
            if (isset($billing_details['email'])) {
592
                unset($billing_details['email']);
593
            }
594
            
595
            $response['success']                    = true;
596
            $response['data']['id']                 = $user_data->ID;
597
            $response['data']['name']               = $user_data->user_email;
598
            $response['data']['billing_details']    = $billing_details;
599
        }
600
        
601
        wp_send_json( $response );
602
    }
603
    
604
    public static function run_tool() {
605
        check_ajax_referer( 'wpinv-nonce', '_nonce' );
606
        if ( !wpinv_current_user_can_manage_invoicing() ) {
607
            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...
608
        }
609
        
610
        $tool = sanitize_text_field( $_POST['tool'] );
611
        
612
        do_action( 'wpinv_run_tool' );
613
        
614
        if ( !empty( $tool ) ) {
615
            do_action( 'wpinv_tool_' . $tool );
616
        }
617
    }
618
    
619
    public static function apply_discount() {
620
        global $wpi_userID;
621
        
622
        check_ajax_referer( 'wpinv-nonce', '_nonce' );
623
        
624
        $response = array();
625
        
626
        if ( isset( $_POST['code'] ) ) {
627
            $discount_code = sanitize_text_field( $_POST['code'] );
628
629
            $response['success']        = false;
630
            $response['msg']            = '';
631
            $response['data']['code']   = $discount_code;
632
            
633
            $invoice = wpinv_get_invoice_cart();
634
            if ( empty( $invoice->ID ) ) {
635
                $response['msg'] = __( 'Invalid checkout request.', 'invoicing' );
636
                wp_send_json( $response );
637
            }
638
639
            $wpi_userID = $invoice->get_user_id();
640
641
            if ( wpinv_is_discount_valid( $discount_code, $wpi_userID ) ) {
642
                $discount       = wpinv_get_discount_by_code( $discount_code );
643
                $discounts      = wpinv_set_cart_discount( $discount_code );
644
                $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...
645
                $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...
646
                $cart_totals    = wpinv_recalculate_tax( true );
647
            
648
                if ( !empty( $cart_totals ) ) {
649
                    $response['success']        = true;
650
                    $response['data']           = $cart_totals;
651
                    $response['data']['code']   = $discount_code;
652
                } else {
653
                    $response['success']        = false;
654
                }
655
            } else {
656
                $errors = wpinv_get_errors();
657
                $response['msg']  = $errors['wpinv-discount-error'];
658
                wpinv_unset_error( 'wpinv-discount-error' );
659
            }
660
661
            // Allow for custom discount code handling
662
            $response = apply_filters( 'wpinv_ajax_discount_response', $response );
663
        }
664
        
665
        wp_send_json( $response );
666
    }
667
    
668
    public static function remove_discount() {
669
        check_ajax_referer( 'wpinv-nonce', '_nonce' );
670
        
671
        $response = array();
672
        
673
        if ( isset( $_POST['code'] ) ) {
674
            $discount_code  = sanitize_text_field( $_POST['code'] );
675
            $discounts      = wpinv_unset_cart_discount( $discount_code );
676
            $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...
677
            $cart_totals    = wpinv_recalculate_tax( true );
678
            
679
            if ( !empty( $cart_totals ) ) {
680
                $response['success']        = true;
681
                $response['data']           = $cart_totals;
682
                $response['data']['code']   = $discount_code;
683
            } else {
684
                $response['success']        = false;
685
            }
686
            
687
            // Allow for custom discount code handling
688
            $response = apply_filters( 'wpinv_ajax_discount_response', $response );
689
        }
690
        
691
        wp_send_json( $response );
692
    }
693
694
695
    /**
696
     * Lets users buy items via ajax.
697
     *
698
     * @since 1.0.0
699
     */
700
    public static function buy_items() {
701
        $user_id = get_current_user_id();
702
703
        if ( empty( $user_id ) ) { // If not logged in then lets redirect to the login page
704
            wp_send_json( array(
705
                '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

705
                'success' => wp_login_url( /** @scrutinizer ignore-type */ wp_get_referer() )
Loading history...
706
            ) );
707
        } else {
708
            // Only check nonce if logged in as it could be cached when logged out.
709
            if ( ! isset( $_POST['wpinv_buy_nonce'] ) || ! wp_verify_nonce( $_POST['wpinv_buy_nonce'], 'wpinv_buy_items' ) ) {
710
                wp_send_json( array(
711
                    'error' => __( 'Security checks failed.', 'invoicing' )
712
                ) );
713
                wp_die();
714
            }
715
716
            // allow to set a custom price through post_id
717
            $items = $_POST['items'];
718
            $related_post_id = isset( $_POST['post_id'] ) ? (int)$_POST['post_id'] : 0;
719
            $custom_item_price = $related_post_id ? abs( get_post_meta( $related_post_id, '_wpi_custom_price', true ) ) : 0;
720
721
            $cart_items = array();
722
            if ( $items ) {
723
                $items = explode( ',', $items );
724
725
                foreach( $items as $item ) {
726
                    $item_id = $item;
727
                    $quantity = 1;
728
729
                    if ( strpos( $item, '|' ) !== false ) {
730
                        $item_parts = explode( '|', $item );
731
                        $item_id = $item_parts[0];
732
                        $quantity = $item_parts[1];
733
                    }
734
735
                    if ( $item_id && $quantity ) {
736
                        $cart_items_arr = array(
737
                            'id'            => (int)$item_id,
738
                            'quantity'      => (int)$quantity
739
                        );
740
741
                        // If there is a related post id then add it to meta
742
                        if ( $related_post_id ) {
743
                            $cart_items_arr['meta'] = array(
744
                                'post_id'   => $related_post_id
745
                            );
746
                        }
747
748
                        // If there is a custom price then set it.
749
                        if ( $custom_item_price ) {
750
                            $cart_items_arr['custom_price'] = $custom_item_price;
751
                        }
752
753
                        $cart_items[] = $cart_items_arr;
754
                    }
755
                }
756
            }
757
758
            /**
759
             * Filter the wpinv_buy shortcode cart items on the fly.
760
             *
761
             * @param array $cart_items The cart items array.
762
             * @param int $related_post_id The related post id if any.
763
             * @since 1.0.0
764
             */
765
            $cart_items = apply_filters( 'wpinv_buy_cart_items', $cart_items, $related_post_id );
766
767
            // Make sure its not in the cart already, if it is then redirect to checkout.
768
            $cart_invoice = wpinv_get_invoice_cart();
769
770
            if ( isset( $cart_invoice->items ) && !empty( $cart_invoice->items ) && !empty( $cart_items ) && serialize( $cart_invoice->items ) == serialize( $cart_items ) ) {
771
                wp_send_json( array(
772
                    'success' =>  $cart_invoice->get_checkout_payment_url()
773
                ) );
774
                wp_die();
775
            }
776
777
            // Check if user has invoice with same items waiting to be paid.
778
            $user_invoices = wpinv_get_users_invoices( $user_id , 10 , false , 'wpi-pending' );
779
            if ( !empty( $user_invoices ) ) {
780
                foreach( $user_invoices as $user_invoice ) {
781
                    $user_cart_details = array();
782
                    $invoice  = wpinv_get_invoice( $user_invoice->ID );
783
                    $cart_details = $invoice->get_cart_details();
784
785
                    if ( !empty( $cart_details ) ) {
786
                        foreach ( $cart_details as $invoice_item ) {
787
                            $ii_arr = array();
788
                            $ii_arr['id'] = (int)$invoice_item['id'];
789
                            $ii_arr['quantity'] = (int)$invoice_item['quantity'];
790
791
                            if (isset( $invoice_item['meta'] ) && !empty( $invoice_item['meta'] ) ) {
792
                                $ii_arr['meta'] = $invoice_item['meta'];
793
                            }
794
795
                            if ( isset( $invoice_item['custom_price'] ) && !empty( $invoice_item['custom_price'] ) ) {
796
                                $ii_arr['custom_price'] = $invoice_item['custom_price'];
797
                            }
798
799
                            $user_cart_details[] = $ii_arr;
800
                        }
801
                    }
802
803
                    if ( !empty( $user_cart_details ) && serialize( $cart_items ) == serialize( $user_cart_details ) ) {
804
                        wp_send_json( array(
805
                            'success' =>  $invoice->get_checkout_payment_url()
806
                        ) );
807
                        wp_die();
808
                    }
809
                }
810
            }
811
812
            // Create invoice and send user to checkout
813
            if ( !empty( $cart_items ) ) {
814
                $invoice_data = array(
815
                    'status'        =>  'wpi-pending',
816
                    'created_via'   =>  'wpi',
817
                    'user_id'       =>  $user_id,
818
                    'cart_details'  =>  $cart_items,
819
                );
820
821
                $invoice = wpinv_insert_invoice( $invoice_data, true );
822
823
                if ( !empty( $invoice ) && isset( $invoice->ID ) ) {
824
                    wp_send_json( array(
825
                        '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

825
                        '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...
826
                    ) );
827
                } else {
828
                    wp_send_json( array(
829
                        'error' => __( 'Invoice failed to create', 'invoicing' )
830
                    ) );
831
                }
832
            } else {
833
                wp_send_json( array(
834
                    'error' => __( 'Items not valid.', 'invoicing' )
835
                ) );
836
            }
837
        }
838
839
        wp_die();
840
    }
841
}
842
843
WPInv_Ajax::init();