Passed
Pull Request — master (#100)
by Kiran
05:19
created

wpinv-gd-functions.php ➔ wpinv_wpi_to_gdp_update_status()   C

Complexity

Conditions 12
Paths 16

Size

Total Lines 45
Code Lines 29

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 12
eloc 29
nc 16
nop 3
dl 0
loc 45
rs 5.1612
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
// MUST have WordPress.
3
if ( !defined( 'WPINC' ) ) {
4
    exit( 'Do NOT access this file directly: ' . basename( __FILE__ ) );
5
}
6
7
function wpinv_gd_active() {
8
    return (bool)defined( 'GEODIRECTORY_VERSION' );
9
}
10
11
function wpinv_pm_active() {
12
    return (bool)wpinv_gd_active() && (bool)defined( 'GEODIRPAYMENT_VERSION' );
13
}
14
15
function wpinv_is_gd_post_type( $post_type ) {
16
    global $gd_posttypes;
17
    
18
    $gd_posttypes = !empty( $gd_posttypes ) && is_array( $gd_posttypes ) ? $gd_posttypes : geodir_get_posttypes();
19
    
20
    if ( !empty( $post_type ) && !empty( $gd_posttypes ) && in_array( $post_type, $gd_posttypes ) ) {
21
        return true;
22
    }
23
    
24
    return false;
25
}
26
27
function wpinv_geodir_integration() {    
28
    if (!defined('GEODIRECTORY_VERSION')) {
29
        return;
30
    }
31
    
32
    if (!(defined( 'DOING_AJAX' ) && DOING_AJAX)) {
33
        // Add  fields for force upgrade
34
        if ( defined('INVOICE_TABLE') && !get_option('wpinv_gdp_column') ) {
35
            geodir_add_column_if_not_exist( INVOICE_TABLE, 'invoice_id', 'INT( 11 ) NOT NULL DEFAULT 0' );
36
            
37
            update_option('wpinv_gdp_column', '1');
38
        }
39
        // Merge price packages
40
        wpinv_merge_gd_packages_to_items();
41
    }
42
}
43
add_action( 'admin_init', 'wpinv_geodir_integration' );
44
45
function wpinv_get_gdp_package_type( $item_types ) {
46
    if ( wpinv_pm_active() ) {
47
        $item_types['package'] = __( 'Package', 'invoicing' );
48
    }
49
        
50
    return $item_types;
51
}
52
add_filter( 'wpinv_get_item_types', 'wpinv_get_gdp_package_type', 10, 1 );
53
54
function wpinv_update_package_item($package_id) {
55
    return wpinv_merge_gd_package_to_item($package_id, true);
56
}
57
add_action('geodir_after_save_package', 'wpinv_update_package_item', 10, 1);
58
59
function wpinv_merge_gd_packages_to_items( $force = false ) {    
60
    if ( $merged = get_option( 'wpinv_merge_gd_packages' ) && !$force ) {
0 ignored issues
show
Comprehensibility introduced by
Consider adding parentheses for clarity. Current Interpretation: $merged = (get_option('w..._packages') && !$force), Probably Intended Meaning: ($merged = get_option('w..._packages')) && !$force
Loading history...
61
        return true;
62
    }
63
64
    if(!function_exists('geodir_package_list_info')){
65
        return false;
66
    }
67
    
68
    $packages = geodir_package_list_info();
69
    
70
    foreach ( $packages as $key => $package ) {
71
        wpinv_merge_gd_package_to_item( $package->pid, $force, $package );
72
    }
73
    
74
    if ( !$merged ) {
75
        update_option( 'wpinv_merge_gd_packages', 1 );
76
    }
77
    
78
    return true;
79
}
80
81
function wpinv_get_gd_package_item($package_id, $create = false) {
82
    $item = wpinv_get_item_by('custom_id', $package_id, 'package');
83
    
84
    if (!$create) {
85
        return $item;
86
    }
87
    
88
    return wpinv_merge_gd_package_to_item($package_id, true);
89
}
90
91
function wpinv_merge_gd_package_to_item($package_id, $force = false, $package = NULL) {
92
    if (empty($package_id)) {
93
        return false;
94
    }
95
    
96
    $item = wpinv_get_item_by('custom_id', $package_id, 'package');
97
98
    if (!$force && !empty($item)) {
99
        return $item;
100
    }
101
102
    $package = empty($package) ? geodir_get_package_info_by_id($package_id, '') : $package;
103
104
    if ( empty($package) || !wpinv_is_gd_post_type( $package->post_type ) ) {
105
        return false;
106
    }
107
        
108
    $meta                           = array();
109
    $meta['type']                   = 'package';
110
    $meta['custom_id']              = $package_id;
111
    $meta['custom_singular_name']   = get_post_type_singular_label($package->post_type);
112
    $meta['custom_name']            = get_post_type_plural_label($package->post_type);
113
    $meta['price']                  = wpinv_round_amount( $package->amount );
114
    $meta['vat_rule']               = 'digital';
115
    $meta['vat_class']              = '_standard';
116
    
117
    if ( !empty( $package->sub_active ) ) {
118
        $sub_num_trial_days = absint( $package->sub_num_trial_days );
119
        
120
        $meta['is_recurring']       = 1;
121
        $meta['recurring_period']   = $package->sub_units;
122
        $meta['recurring_interval'] = absint( $package->sub_units_num );
123
        $meta['recurring_limit']    = absint( $package->sub_units_num_times );
124
        $meta['free_trial']         = $sub_num_trial_days > 0 ? 1 : 0;
125
        $meta['trial_period']       = $package->sub_num_trial_units;
126
        $meta['trial_interval']     = $sub_num_trial_days;
127 View Code Duplication
    } else {
128
        $meta['is_recurring']       = 0;
129
        $meta['recurring_period']   = '';
130
        $meta['recurring_interval'] = '';
131
        $meta['recurring_limit']    = '';
132
        $meta['free_trial']         = 0;
133
        $meta['trial_period']       = '';
134
        $meta['trial_interval']     = '';
135
    }
136
    
137
    $data  = array( 
138
        'post_title'    => $package->title,
139
        'post_excerpt'  => $package->title_desc,
140
        'post_status'   => $package->status == 1 ? 'publish' : 'pending',
141
        'meta'          => $meta
142
    );
143
144
    if (!empty($item)) {
145
        $item->update($data);
146
    } else {
147
        $item = new WPInv_Item();
148
        $item->create($data);
149
    }
150
    
151
    return $item;
152
}
153
154
function wpinv_gdp_to_wpi_gateway( $payment_method ) {
155
    switch( $payment_method ) {
156
        case 'prebanktransfer':
157
            $gateway = 'bank_transfer';
158
        break;
159
        default:
160
            $gateway = empty( $payment_method ) ? 'manual' : $payment_method;
161
        break;
162
    }
163
    
164
    return apply_filters( 'wpinv_gdp_to_wpi_gateway', $gateway, $payment_method );
165
}
166
167
function wpinv_gdp_to_wpi_gateway_title( $payment_method ) {
168
    $gateway = wpinv_gdp_to_wpi_gateway( $payment_method );
169
    
170
    $gateway_title = wpinv_get_gateway_checkout_label( $gateway );
171
    
172
    if ( $gateway == $gateway_title ) {
173
        $gateway_title = geodir_payment_method_title( $gateway );
174
    }
175
    
176
    return apply_filters( 'wpinv_gdp_to_wpi_gateway_title', $gateway_title, $payment_method );
177
}
178
179
function wpinv_print_checkout_errors() {
180
    global $wpi_session;
181
    wpinv_print_errors();
182
}
183
add_action( 'geodir_checkout_page_content', 'wpinv_print_checkout_errors', -10 );
184
185
function wpinv_cpt_save( $invoice_id, $update = false, $pre_status = NULL ) {
186
    global $wpi_nosave, $wpi_zero_tax, $wpi_gdp_inv_merge;
187
    
188
    $invoice_info = geodir_get_invoice( $invoice_id );
189
    
190
    $wpi_invoice_id  = !empty( $invoice_info->invoice_id ) ? $invoice_info->invoice_id : 0;
191
    
192
    if (!empty($invoice_info)) {
193
        $wpi_invoice = $wpi_invoice_id > 0 ? wpinv_get_invoice( $wpi_invoice_id ) : NULL;
194
        
195
        if ( !empty( $wpi_invoice ) ) { // update invoice
196
            $save = false;
197
            if ($invoice_info->coupon_code !== $wpi_invoice->discount_code || (float)$invoice_info->discount < (float)$wpi_invoice->discount || (float)$invoice_info->discount > (float)$wpi_invoice->discount) {
198
                $save = true;
199
                $wpi_invoice->set('discount_code', $invoice_info->coupon_code);
200
                $wpi_invoice->set('discount', $invoice_info->discount);
201
            }
202
            
203
            if ($invoice_info->paymentmethod !== $wpi_invoice->gateway) {
204
                $save = true;
205
                $gateway = !empty( $invoice_info->paymentmethod ) ? $invoice_info->paymentmethod : '';
206
                $gateway = wpinv_gdp_to_wpi_gateway( $gateway );
207
                $gateway_title = wpinv_gdp_to_wpi_gateway_title( $gateway );
208
                $wpi_invoice->set('gateway', $gateway );
209
                $wpi_invoice->set('gateway_title', $gateway_title );
210
            }
211
            
212
            if ( ( $status = wpinv_gdp_to_wpi_status( $invoice_info->status ) ) !== $wpi_invoice->status ) {
213
                $save = true;
214
                $wpi_invoice->set( 'status', $status );
215
            }
216
            
217
            if ($save) {
218
                $wpi_nosave = true;
219
                $wpi_invoice->recalculate_total();
220
                $wpi_invoice->save();
221
            }
222
            
223
            return $wpi_invoice;
224
        } else { // create invoice
225
            $user_info = get_userdata( $invoice_info->user_id );
0 ignored issues
show
Unused Code introduced by
$user_info is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
226
            
227
            if ( !empty( $pre_status ) ) {
228
                $invoice_info->status = $pre_status;
229
            }
230
            $status = wpinv_gdp_to_wpi_status( $invoice_info->status );
231
            
232
            $wpi_zero_tax = false;
233
            
234
            if ( $wpi_gdp_inv_merge && in_array( $status, array( 'publish', 'wpi-processing', 'wpi-renewal' ) ) ) {
235
                $wpi_zero_tax = true;
236
            }
237
            
238
            $invoice_data                   = array();
239
            $invoice_data['invoice_id']     = $wpi_invoice_id;
240
            $invoice_data['status']         = $status;
241
            $invoice_data['user_id']        = $invoice_info->user_id;
242
            $invoice_data['created_via']    = 'API';
243
            
244
            if ( !empty( $invoice_info->date ) ) {
245
                $invoice_data['created_date']   = $invoice_info->date;
246
            }
247
            
248
            $paymentmethod = !empty( $invoice_info->paymentmethod ) ? $invoice_info->paymentmethod : '';
249
            $paymentmethod = wpinv_gdp_to_wpi_gateway( $paymentmethod );
250
            $payment_method_title = wpinv_gdp_to_wpi_gateway_title( $paymentmethod );
251
            
252
            $invoice_data['payment_details'] = array( 
253
                'gateway'           => $paymentmethod, 
254
                'gateway_title'     => $payment_method_title,
255
                'currency'          => geodir_get_currency_type(),
256
            );
257
            
258
            $user_address = wpinv_get_user_address( $invoice_info->user_id, false );
259
            
260
            $invoice_data['user_info'] = array( 
261
                'user_id'       => $invoice_info->user_id, 
262
                'first_name'    => $user_address['first_name'],
263
                'last_name'     => $user_address['last_name'],
264
                'email'         => $user_address['email'],
265
                'company'       => $user_address['company'],
266
                'vat_number'    => $user_address['vat_number'],
267
                'phone'         => $user_address['phone'],
268
                'address'       => $user_address['address'],
269
                'city'          => $user_address['city'],
270
                'country'       => $user_address['country'],
271
                'state'         => $user_address['state'],
272
                'zip'           => $user_address['zip'],
273
                'discount'      => $invoice_info->coupon_code,
274
            );
275
            
276
            $invoice_data['discount']       = $invoice_info->discount;
277
            $invoice_data['discount_code']  = $invoice_info->coupon_code;
278
            
279
            $post_item = wpinv_get_gd_package_item($invoice_info->package_id);
280
281
            if ( $invoice_info->invoice_type == 'add_franchise' ) {
282
                $custom_price = $invoice_info->amount;
283
            } else {
284
                $custom_price = '';
285
            }
286
287
            if ( !empty( $post_item ) ) {
288
                $cart_details  = array();
289
                $cart_details[] = array(
290
                    'id'            => $post_item->ID,
291
                    'name'          => $post_item->get_name(),
292
                    'item_price'    => $post_item->get_price(),
293
                    'custom_price'  => $custom_price,
294
                    'discount'      => $invoice_info->discount,
295
                    'tax'           => 0.00,
296
                    'meta'          => array( 
297
                        'post_id'       => $invoice_info->post_id,
298
                        'invoice_title' => $invoice_info->post_title
299
                    ),
300
                );
301
                
302
                $invoice_data['cart_details']  = $cart_details;
303
            }
304
305
            $data = array( 'invoice' => $invoice_data );
306
307
            $wpinv_api = new WPInv_API();
308
            $data = $wpinv_api->insert_invoice( $data );
309
            
310
            if ( is_wp_error( $data ) ) {
311
                wpinv_error_log( 'WPInv_Invoice: ' . $data->get_error_message() );
0 ignored issues
show
Bug introduced by
The method get_error_message() does not seem to exist on object<WPInv_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...
312
            } else {
313
                if ( !empty( $data ) ) {
314
                    update_post_meta( $data->ID, '_wpinv_gdp_id', $invoice_id );
315
                    
316
                    $update_data = array();
317
                    $update_data['tax_amount'] = $data->get_tax();
318
                    $update_data['paied_amount'] = $data->get_total();
319
                    $update_data['invoice_id'] = $data->ID;
320
                    
321
                    global $wpdb;
322
                    $wpdb->update( INVOICE_TABLE, $update_data, array( 'id' => $invoice_id ) );
323
                    
324
                    return $data;
325
                } else {
326
                    if ( $update ) {
327
                        wpinv_error_log( 'WPInv_Invoice: ' . __( 'Fail to update invoice.', 'invoicing' ) );
328
                    } else {
329
                        wpinv_error_log( 'WPInv_Invoice: ' . __( 'Fail to create invoice.', 'invoicing' ) );
330
                    }
331
                }
332
            }
333
        }
334
    }
335
    
336
    return false;
337
}
338
add_action('geodir_payment_invoice_created', 'wpinv_cpt_save', 11, 3);
339
340
function wpinv_cpt_update( $invoice_id ) {
341
    return wpinv_cpt_save( $invoice_id, true );
342
}
343
add_action('geodir_payment_invoice_updated', 'wpinv_cpt_update', 11, 1);
344
345
function wpinv_payment_status_changed( $invoice_id, $new_status, $old_status = 'wpi-pending', $subscription = false ) {
0 ignored issues
show
Unused Code introduced by
The parameter $old_status is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
Unused Code introduced by
The parameter $subscription is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
346
    $invoice_info = geodir_get_invoice( $invoice_id );
347
    if ( empty( $invoice_info ) ) {
348
        return false;
349
    }
350
351
    $invoice = !empty( $invoice_info->invoice_id ) ? wpinv_get_invoice( $invoice_info->invoice_id ) : NULL;
352
    if ( !empty( $invoice ) ) {
353
        $new_status = wpinv_gdp_to_wpi_status($new_status);
354
        $invoice    = wpinv_update_payment_status( $invoice->ID, $new_status );
355
    } else {
356
        $invoice = wpinv_cpt_save( $invoice_id );
357
    }
358
    
359
    return $invoice;
360
}
361
add_action( 'geodir_payment_invoice_status_changed', 'wpinv_payment_status_changed', 11, 4 );
362
363
function wpinv_transaction_details_note( $invoice_id, $html ) {
364
    $invoice_info = geodir_get_invoice( $invoice_id );
365
    if ( empty( $invoice_info ) ) {
366
        return false;
367
    }
368
369
    $wpi_invoice_id = !empty( $invoice_info->invoice_id ) ? $invoice_info->invoice_id : NULL;
370
    
371
    if ( !$wpi_invoice_id ) {
372
        $invoice = wpinv_cpt_save( $invoice_id, false, $old_status );
0 ignored issues
show
Bug introduced by
The variable $old_status does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
373
        
374
        if ( !empty( $invoice ) ) {
375
            $wpi_invoice_id = $invoice->ID;
376
        }
377
    }
378
379
    $invoice = wpinv_get_invoice( $wpi_invoice_id );
380
    
381
    if ( empty( $invoice ) ) {
382
        return false;
383
    }
384
    
385
    return $invoice->add_note( $html, true );
386
}
387
add_action( 'geodir_payment_invoice_transaction_details_changed', 'wpinv_transaction_details_note', 11, 2 );
388
389 View Code Duplication
function wpinv_gdp_to_wpi_status( $status ) {
0 ignored issues
show
Duplication introduced by
This function seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
390
    $inv_status = $status ? $status : 'wpi-pending';
391
    
392
    switch ( $status ) {
393
        case 'pending':
394
            $inv_status = 'wpi-pending';
395
        break;
396
        case 'confirmed':
397
            $inv_status = 'publish';
398
        break;
399
        case 'cancelled':
400
            $inv_status = 'wpi-cancelled';
401
        break;
402
        case 'failed':
403
            $inv_status = 'wpi-failed';
404
        break;
405
        case 'onhold':
406
            $inv_status = 'wpi-onhold';
407
        break;
408
        case 'refunded':
409
            $inv_status = 'wpi-refunded';
410
        break;
411
    }
412
    return $inv_status;
413
}
414
415 View Code Duplication
function wpinv_wpi_to_gdp_status( $status ) {
0 ignored issues
show
Duplication introduced by
This function seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
416
    $inv_status = $status ? $status : 'pending';
417
    
418
    switch ( $status ) {
419
        case 'wpi-pending':
420
            $inv_status = 'pending';
421
        break;
422
        case 'publish':
423
        case 'wpi-processing':
424
        case 'wpi-renewal':
425
            $inv_status = 'confirmed';
426
        break;
427
        case 'wpi-cancelled':
428
            $inv_status = 'cancelled';
429
        break;
430
        case 'wpi-failed':
431
            $inv_status = 'failed';
432
        break;
433
        case 'wpi-onhold':
434
            $inv_status = 'onhold';
435
        break;
436
        case 'wpi-refunded':
437
            $inv_status = 'refunded';
438
        break;
439
    }
440
    
441
    return $inv_status;
442
}
443
444
function wpinv_wpi_to_gdp_id( $invoice_id ) {
445
    global $wpdb;
446
    
447
    return $wpdb->get_var( $wpdb->prepare( "SELECT `id` FROM `" . INVOICE_TABLE . "` WHERE `invoice_id` = %d AND `invoice_id` > 0 ORDER BY id DESC LIMIT 1", array( (int)$invoice_id ) ) );
448
}
449
450
function wpinv_gdp_to_wpi_id( $invoice_id ) {
451
    $invoice = geodir_get_invoice( $invoice_id );    
452
    return ( empty( $invoice->invoice_id ) ? $invoice->invoice_id : false);
453
}
454
455
function wpinv_to_gdp_recalculate_total( $invoice, $wpi_nosave ) {
456
    global $wpdb;
457
    
458
    if ( !empty( $wpi_nosave ) ) {
459
        return;
460
    }
461
    
462
    $gdp_invoice_id = wpinv_wpi_to_gdp_id( $invoice->ID );
463
    
464
    if ( $gdp_invoice_id > 0 ) {
465
        $update_data = array();
466
        $update_data['tax_amount']      = $invoice->tax;
467
        $update_data['paied_amount']    = $invoice->total;
468
        $update_data['discount']        = $invoice->discount;
469
        $update_data['coupon_code']     = $invoice->discount_code;
470
        
471
        $wpdb->update( INVOICE_TABLE, $update_data, array( 'id' => $gdp_invoice_id ) );
472
    }
473
    
474
    return;
475
}
476
//add_action( 'wpinv_invoice_recalculate_total', 'wpinv_to_gdp_recalculate_total', 10, 2 );
0 ignored issues
show
Unused Code Comprehensibility introduced by
63% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
477
478
function wpinv_gdp_to_wpi_invoice( $invoice_id ) {
479
    $invoice = geodir_get_invoice( $invoice_id );
480
    if ( empty( $invoice->invoice_id ) ) {
481
        return false;
482
    }
483
    
484
    return wpinv_get_invoice( $invoice->invoice_id );
485
}
486
487
function wpinv_payment_set_coupon_code( $status, $invoice_id, $coupon_code ) {
488
    $invoice = wpinv_gdp_to_wpi_invoice( $invoice_id );
489
    if ( empty( $invoice ) ) {
490
        return $status;
491
    }
492
493
    if ( $status === 1 || $status === 0 ) {
494
        if ( $status === 1 ) {
495
            $discount = geodir_get_discount_amount( $coupon_code, $invoice->get_subtotal() );
496
        } else {
497
            $discount = '';
498
            $coupon_code = '';
499
        }
500
        
501
        $invoice->set( 'discount', $discount );
502
        $invoice->set( 'discount_code', $coupon_code );
503
        $invoice->save();
504
        $invoice->recalculate_total();
505
    }
506
    
507
    return $status;
508
}
509
add_filter( 'geodir_payment_set_coupon_code', 'wpinv_payment_set_coupon_code', 10, 3 );
510
511
function wpinv_merge_gd_invoices() {
512
    if (!defined('GEODIRPAYMENT_VERSION')) {
513
        return;
514
    }
515
    ?>
516
    <tr>
517
        <td><?php _e( 'Merge Price Packages', 'invoicing' ); ?></td>
518
        <td><p><?php _e( 'Merge GeoDirectory Payment Manager price packages to the Invoicing items.', 'invoicing' ); ?></p></td>
519
        <td><input type="button" data-tool="merge_packages" class="button-primary wpinv-tool" value="<?php esc_attr_e( 'Run', 'invoicing' ); ?>"></td>
520
    </tr>
521
    <tr>
522
        <td><?php _e( 'Merge Invoices', 'invoicing' ); ?></td>
523
        <td><p><?php _e( 'Merge GeoDirectory Payment Manager invoices to the Invoicing.', 'invoicing' ); ?></p></td>
524
        <td><input type="button" data-tool="merge_invoices" class="button-primary wpinv-tool" value="<?php esc_attr_e( 'Run', 'invoicing' ); ?>"></td>
525
    </tr>
526
	<tr>
527
        <td><?php _e( 'Fix Taxes for Merged Invoices', 'invoicing' ); ?></td>
528
        <td><p><?php _e( 'Fix taxes for NON-PAID invoices which are merged before, from GeoDirectory Payment Manager invoices to Invoicing. This will recalculate taxes for non-paid merged invoices.', 'invoicing' ); ?></p></td>
529
        <td><input type="button" data-tool="merge_fix_taxes" class="button-primary wpinv-tool" value="<?php esc_attr_e( 'Run', 'invoicing' ); ?>"></td>
530
    </tr>
531
    <tr>
532
        <td><?php _e( 'Merge Coupons', 'invoicing' ); ?></td>
533
        <td><p><?php _e( 'Merge GeoDirectory Payment Manager coupons to the Invoicing.', 'invoicing' ); ?></p></td>
534
        <td><input type="button" data-tool="merge_coupons" class="button-primary wpinv-tool" value="<?php esc_attr_e( 'Run', 'invoicing' ); ?>"></td>
535
    </tr>
536
    <?php
537
}
538
add_action( 'wpinv_tools_row', 'wpinv_merge_gd_invoices', 10 );
539
540
function wpinv_tool_merge_packages() {
541
    $packages = geodir_package_list_info();
542
    
543
    $count = 0;
544
    
545
    if ( !empty( $packages ) ) {
546
        $success = true;
547
        
548
        foreach ( $packages as $key => $package ) {
549
            $item = wpinv_get_item_by('custom_id', $package->pid, 'package');
550
            if ( !empty( $item ) ) {
551
                continue;
552
            }
553
            
554
            $merged = wpinv_merge_gd_package_to_item( $package->pid, false, $package );
555
            
556
            if ( !empty( $merged ) ) {
557
                wpinv_error_log( 'Package merge S : ' . $package->pid );
558
                $count++;
559
            } else {
560
                wpinv_error_log( 'Package merge F : ' . $package->pid );
561
            }
562
        }
563
        
564 View Code Duplication
        if ( $count > 0 ) {
565
            $message = sprintf( _n( 'Total <b>%d</b> price package is merged successfully.', 'Total <b>%d</b> price packages are merged successfully.', $count, 'invoicing' ), $count );
566
        } else {
567
            $message = __( 'No price packages merged.', 'invoicing' );
568
        }
569
    } else {
570
        $success = false;
571
        $message = __( 'No price packages found to merge!', 'invoicing' );
572
    }
573
    
574
    $response = array();
575
    $response['success'] = $success;
576
    $response['data']['message'] = $message;
577
    wp_send_json( $response );
578
}
579
add_action( 'wpinv_tool_merge_packages', 'wpinv_tool_merge_packages' );
580
581
function wpinv_tool_merge_invoices() {
582
    global $wpdb, $wpi_gdp_inv_merge, $wpi_tax_rates;
583
    
584
    $sql = "SELECT `gdi`.`id`, `gdi`.`date`, `gdi`.`date_updated` FROM `" . INVOICE_TABLE . "` AS gdi LEFT JOIN `" . $wpdb->posts . "` AS p ON `p`.`ID` = `gdi`.`invoice_id` AND `p`.`post_type` = 'wpi_invoice' WHERE `p`.`ID` IS NULL ORDER BY `gdi`.`id` ASC";
585
586
    $items = $wpdb->get_results( $sql );
587
    
588
    $count = 0;
589
    
590
    if ( !empty( $items ) ) {
591
        $success = true;
592
        $wpi_gdp_inv_merge = true;
593
        
594
        foreach ( $items as $item ) {
595
            $wpi_tax_rates = NULL;
596
            
597
            $wpdb->query( "UPDATE `" . INVOICE_TABLE . "` SET `invoice_id` = 0 WHERE id = '" . $item->id . "'" );
598
            
599
            $merged = wpinv_cpt_save( $item->id );
600
            
601
            if ( !empty( $merged ) && !empty( $merged->ID ) ) {
602
                $count++;
603
                
604
                $post_date = !empty( $item->date ) && $item->date != '0000-00-00 00:00:00' ? $item->date : current_time( 'mysql' );
605
                $post_date_gmt = get_gmt_from_date( $post_date );
606
                $post_modified = !empty( $item->date_updated ) && $item->date_updated != '0000-00-00 00:00:00' ? $item->date_updated : $post_date;
607
                $post_modified_gmt = get_gmt_from_date( $post_modified );
608
                
609
                $wpdb->update( $wpdb->posts, array( 'post_date' => $post_date, 'post_date_gmt' => $post_date_gmt, 'post_modified' => $post_modified, 'post_modified_gmt' => $post_modified_gmt ), array( 'ID' => $merged->ID ) );
610
                
611
                if ( $merged->is_paid() ) {
612
                    update_post_meta( $merged->ID, '_wpinv_completed_date', $post_modified );
613
                }
614
                
615
                clean_post_cache( $merged->ID );
616
                
617
                wpinv_error_log( 'Invoice merge S : ' . $item->id . ' => ' . $merged->ID );
618
            } else {
619
                wpinv_error_log( 'Invoice merge F : ' . $item->id );
620
            }
621
        }
622
        
623
        $wpi_gdp_inv_merge = false;
624
        
625 View Code Duplication
        if ( $count > 0 ) {
626
            $message = sprintf( _n( 'Total <b>%d</b> invoice is merged successfully.', 'Total <b>%d</b> invoices are merged successfully.', $count, 'invoicing' ), $count );
627
        } else {
628
            $message = __( 'No invoices merged.', 'invoicing' );
629
        }
630
    } else {
631
        $success = false;
632
        $message = __( 'No invoices found to merge!', 'invoicing' );
633
    }
634
    
635
    $response = array();
636
    $response['success'] = $success;
637
    $response['data']['message'] = $message;
638
    wp_send_json( $response );
639
}
640
add_action( 'wpinv_tool_merge_invoices', 'wpinv_tool_merge_invoices' );
641
642
function wpinv_tool_merge_coupons() {
643
    global $wpdb;
644
    
645
    $sql = "SELECT * FROM `" . COUPON_TABLE . "` WHERE `coupon_code` IS NOT NULL AND `coupon_code` != '' ORDER BY `cid` ASC";
646
    $items = $wpdb->get_results( $sql );
647
    $count = 0;
648
    
649
    if ( !empty( $items ) ) {
650
        $success = true;
651
        
652
        foreach ( $items as $item ) {
653
            if ( wpinv_get_discount_by_code( $item->coupon_code ) ) {
654
                continue;
655
            }
656
            
657
            $args = array(
658
                'post_type'   => 'wpi_discount',
659
                'post_title'  => $item->coupon_code,
660
                'post_status' => !empty( $item->status ) ? 'publish' : 'pending'
661
            );
662
663
            $merged = wp_insert_post( $args );
664
            
665
            $item_id = $item->cid;
666
            
667
            if ( $merged ) {
668
                $meta = array(
669
                    'code'              => $item->coupon_code,
670
                    'type'              => $item->discount_type != 'per' ? 'flat' : 'percent',
671
                    'amount'            => (float)$item->discount_amount,
672
                    'max_uses'          => (int)$item->usage_limit,
673
                    'uses'              => (int)$item->usage_count,
674
                );
675
                wpinv_store_discount( $merged, $meta, get_post( $merged ) );
676
                
677
                $count++;
678
                
679
                wpinv_error_log( 'Coupon merge S : ' . $item_id . ' => ' . $merged );
680
            } else {
681
                wpinv_error_log( 'Coupon merge F : ' . $item_id );
682
            }
683
        }
684
        
685 View Code Duplication
        if ( $count > 0 ) {
686
            $message = sprintf( _n( 'Total <b>%d</b> coupon is merged successfully.', 'Total <b>%d</b> coupons are merged successfully.', $count, 'invoicing' ), $count );
687
        } else {
688
            $message = __( 'No coupons merged.', 'invoicing' );
689
        }
690
    } else {
691
        $success = false;
692
        $message = __( 'No coupons found to merge!', 'invoicing' );
693
    }
694
    
695
    $response = array();
696
    $response['success'] = $success;
697
    $response['data']['message'] = $message;
698
    wp_send_json( $response );
699
}
700
add_action( 'wpinv_tool_merge_coupons', 'wpinv_tool_merge_coupons' );
701
702
function wpinv_gdp_to_wpi_currency( $value, $option = '' ) {
0 ignored issues
show
Unused Code introduced by
The parameter $value is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
Unused Code introduced by
The parameter $option is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
703
    return wpinv_get_currency();
704
}
705
add_filter( 'pre_option_geodir_currency', 'wpinv_gdp_to_wpi_currency', 10, 2 );
706
707
function wpinv_gdp_to_wpi_currency_sign( $value, $option = '' ) {
0 ignored issues
show
Unused Code introduced by
The parameter $value is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
Unused Code introduced by
The parameter $option is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
708
    return wpinv_currency_symbol();
709
}
710
add_filter( 'pre_option_geodir_currencysym', 'wpinv_gdp_to_wpi_currency_sign', 10, 2 );
711
712
function wpinv_gdp_to_wpi_display_price( $price, $amount, $display = true , $decimal_sep, $thousand_sep ) {
0 ignored issues
show
Unused Code introduced by
The parameter $price is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
Unused Code introduced by
The parameter $decimal_sep is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
Unused Code introduced by
The parameter $thousand_sep is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
713
    if ( !$display ) {
714
        $price = wpinv_round_amount( $amount );
715
    } else {
716
        $price = wpinv_price( wpinv_format_amount( $amount ) );
717
    }
718
    
719
    return $price;
720
}
721
add_filter( 'geodir_payment_price' , 'wpinv_gdp_to_wpi_display_price', 10000, 5 );
722
723
function wpinv_gdp_to_inv_checkout_redirect( $redirect_url ) {
724
    $invoice_id         = geodir_payment_cart_id();
725
    $invoice_info       = geodir_get_invoice( $invoice_id );
726
    $wpi_invoice        = !empty( $invoice_info->invoice_id ) ? wpinv_get_invoice( $invoice_info->invoice_id ) : NULL;
727
    
728
    if ( !( !empty( $wpi_invoice ) && !empty( $wpi_invoice->ID ) ) ) {
729
        $wpi_invoice_id = wpinv_cpt_save( $invoice_id );
730
        $wpi_invoice    = wpinv_get_invoice( $wpi_invoice_id );
0 ignored issues
show
Bug introduced by
It seems like $wpi_invoice_id defined by wpinv_cpt_save($invoice_id) on line 729 can also be of type false or object<WPInv_Invoice>; however, wpinv_get_invoice() does only seem to accept integer, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
731
    }
732
    
733
    if ( !empty( $wpi_invoice ) && !empty( $wpi_invoice->ID ) ) {
734
        
735
        // Clear cart
736
        geodir_payment_clear_cart();
737
    
738
        $redirect_url = $wpi_invoice->get_checkout_payment_url();
739
    }
740
    
741
    return $redirect_url;
742
}
743
add_filter( 'geodir_payment_checkout_redirect_url', 'wpinv_gdp_to_inv_checkout_redirect', 100, 1 );
744
745
function wpinv_gdp_dashboard_invoice_history_link( $dashboard_links ) {    
746
    if ( get_current_user_id() ) {        
747
        $dashboard_links .= '<li><i class="fa fa-shopping-cart"></i><a class="gd-invoice-link" href="' . esc_url( wpinv_get_history_page_uri() ) . '">' . __( 'My Invoice History', 'invoicing' ) . '</a></li>';
748
    }
749
750
    return $dashboard_links;
751
}
752
add_action( 'geodir_dashboard_links', 'wpinv_gdp_dashboard_invoice_history_link' );
753
remove_action( 'geodir_dashboard_links', 'geodir_payment_invoices_list_page_link' );
754
755
function wpinv_wpi_to_gdp_update_status( $invoice_id, $new_status, $old_status ) {
0 ignored issues
show
Unused Code introduced by
The parameter $old_status is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
756
    global $wpdb;
757
758
    if (!defined('GEODIRPAYMENT_VERSION')) {
759
        return false;
760
    }
761
762
    $invoice    = wpinv_get_invoice( $invoice_id );
763
    if ( empty( $invoice ) ) {
764
        return false;
765
    }
766
    
767
    remove_action( 'geodir_payment_invoice_status_changed', 'wpinv_payment_status_changed', 11, 4 );
768
769
    $invoice_id = wpinv_wpi_to_gdp_id( $invoice_id );
770
    $new_status = wpinv_wpi_to_gdp_status( $new_status );
771
772
    if ( empty( $invoice_id ) && !empty( $invoice->parent_invoice ) && $item = $invoice->get_recurring( true ) ) {
773
        if ( $item->is_package() && $parent_invoice_id = wpinv_wpi_to_gdp_id( $invoice->parent_invoice ) ) {
774
            $geodir_invoice = geodir_get_invoice( $parent_invoice_id );
775
            if ( !empty( $geodir_invoice ) ) {
776
                unset( $geodir_invoice->id );
777
                $data = (array)$geodir_invoice;
778
                $data['invoice_id'] = $invoice->ID;
779
                $data['tax_amount'] = $invoice->get_tax();
780
                $data['paied_amount'] = $invoice->get_total();
781
                $data['discount'] = $invoice->get_discount();
782
                $data['coupon_code'] = $invoice->get_discount_code();
783
                $data['date'] = $invoice->get_invoice_date( false );
784
                if ( !empty( $data['alive_days'] ) ) {
785
                    $data['expire_date'] = date_i18n( 'Y-m-d', strtotime( $data['date'] . "+" . $data['alive_days'] . " days" ) );
786
                }
787
788
                if ( $wpdb->insert( INVOICE_TABLE, $data ) ) {
789
                    $invoice_id = (int)$wpdb->insert_id;
790
                    update_post_meta( $invoice->ID, '_wpinv_gdp_id', $invoice_id );
791
                }
792
            }
793
        }
794
    }
795
    
796
    if ( !empty( $invoice_id ) ) {
797
        geodir_update_invoice_status( $invoice_id, $new_status, $invoice->is_recurring() );
798
    }
799
}
800
add_action( 'wpinv_update_status', 'wpinv_wpi_to_gdp_update_status', 999, 3 );
801
802
function wpinv_gdp_to_wpi_delete_package( $gd_package_id ) {
803
    $item = wpinv_get_item_by( 'custom_id', $gd_package_id, 'package' );
804
    
805
    if ( !empty( $item ) ) {
806
        wpinv_remove_item( $item, true );
0 ignored issues
show
Documentation introduced by
$item is of type object<WPInv_Item>, but the function expects a integer.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
807
    }
808
}
809
add_action( 'geodir_payment_post_delete_package', 'wpinv_gdp_to_wpi_delete_package', 10, 1 ) ;
810
811
function wpinv_can_delete_package_item( $return, $post_id ) {
812
    if ( $return && function_exists( 'geodir_get_package_info_by_id' ) && get_post_meta( $post_id, '_wpinv_type', true ) == 'package' && $package_id = get_post_meta( $post_id, '_wpinv_custom_id', true ) ) {
813
        $gd_package = geodir_get_package_info_by_id( $package_id, '' );
814
        
815
        if ( !empty( $gd_package ) ) {
816
            $return = false;
817
        }
818
    }
819
820
    return $return;
821
}
822
add_filter( 'wpinv_can_delete_item', 'wpinv_can_delete_package_item', 10, 2 );
823
824
function wpinv_package_item_classes( $classes, $class, $post_id ) {
0 ignored issues
show
Unused Code introduced by
The parameter $class is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
825
    global $typenow;
826
827
    if ( $typenow == 'wpi_item' && in_array( 'wpi-gd-package', $classes ) ) {
828
        if ( wpinv_item_in_use( $post_id ) ) {
829
            $classes[] = 'wpi-inuse-pkg';
830
        } else if ( !( function_exists( 'geodir_get_package_info_by_id' ) && get_post_meta( $post_id, '_wpinv_type', true ) == 'package' && geodir_get_package_info_by_id( (int)get_post_meta( $post_id, '_wpinv_custom_id', true ), '' ) ) ) {
831
            $classes[] = 'wpi-delete-pkg';
832
        }
833
    }
834
835
    return $classes;
836
}
837
add_filter( 'post_class', 'wpinv_package_item_classes', 10, 3 );
838
839
function wpinv_gdp_package_type_info( $post ) {
0 ignored issues
show
Unused Code introduced by
The parameter $post is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
840
    if ( wpinv_pm_active() ) {
841
        ?><p class="wpi-m0"><?php _e( 'Package: GeoDirectory price packages items.', 'invoicing' );?></p>
842
        <?php
843
    }
844
}
845
add_action( 'wpinv_item_info_metabox_after', 'wpinv_gdp_package_type_info', 10, 1 ) ;
846
847
function wpinv_gdp_to_gdi_set_zero_tax( $is_taxable, $item_id, $country , $state ) {
0 ignored issues
show
Unused Code introduced by
The parameter $item_id is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
Unused Code introduced by
The parameter $country is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
Unused Code introduced by
The parameter $state is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
848
    global $wpi_zero_tax;
849
850
    if ( $wpi_zero_tax ) {
851
        $is_taxable = false;
852
    }
853
854
    return $is_taxable;
855
}
856
add_action( 'wpinv_item_is_taxable', 'wpinv_gdp_to_gdi_set_zero_tax', 10, 4 ) ;
857
858
function wpinv_tool_merge_fix_taxes() {
859
    global $wpdb;
860
    
861
	$sql = "SELECT DISTINCT p.ID FROM `" . $wpdb->posts . "` AS p LEFT JOIN " . $wpdb->postmeta . " AS pm ON pm.post_id = p.ID WHERE p.post_type = 'wpi_item' AND pm.meta_key = '_wpinv_type' AND pm.meta_value = 'package'";
862
	$items = $wpdb->get_results( $sql );
863
	
864
	if ( !empty( $items ) ) {
865
		foreach ( $items as $item ) {
866
			if ( get_post_meta( $item->ID, '_wpinv_vat_class', true ) == '_exempt' ) {
867
				update_post_meta( $item->ID, '_wpinv_vat_class', '_standard' );
868
			}
869
		}
870
	}
871
		
872
    $sql = "SELECT `p`.`ID`, gdi.id AS gdp_id FROM `" . INVOICE_TABLE . "` AS gdi LEFT JOIN `" . $wpdb->posts . "` AS p ON `p`.`ID` = `gdi`.`invoice_id` AND `p`.`post_type` = 'wpi_invoice' WHERE `p`.`ID` IS NOT NULL AND p.post_status NOT IN( 'publish', 'wpi-processing', 'wpi-renewal' ) ORDER BY `gdi`.`id` ASC";
873
    $items = $wpdb->get_results( $sql );
874
	
875
	if ( !empty( $items ) ) {
876
		$success = false;
877
        $message = __( 'Taxes fixed for non-paid merged GD invoices.', 'invoicing' );
878
		
879
		global $wpi_userID, $wpinv_ip_address_country, $wpi_tax_rates;
880
		
881
		foreach ( $items as $item ) {
882
			$wpi_tax_rates = NULL;               
883
			$data = wpinv_get_invoice($item->ID);
884
885
			if ( empty( $data ) ) {
886
				continue;
887
			}
888
			
889
			$checkout_session = wpinv_get_checkout_session();
890
			
891
			$data_session                   = array();
892
			$data_session['invoice_id']     = $data->ID;
893
			$data_session['cart_discounts'] = $data->get_discounts( true );
894
			
895
			wpinv_set_checkout_session( $data_session );
896
			
897
			$wpi_userID         = (int)$data->get_user_id();
898
			$_POST['country']   = !empty($data->country) ? $data->country : wpinv_get_default_country();
899
				
900
			$data->country      = sanitize_text_field( $_POST['country'] );
901
			$data->set( 'country', sanitize_text_field( $_POST['country'] ) );
902
			
903
			$wpinv_ip_address_country = $data->country;
904
			
905
			$data->recalculate_totals(true);
906
			
907
			wpinv_set_checkout_session( $checkout_session );
908
			
909
			$update_data = array();
910
			$update_data['tax_amount'] = $data->get_tax();
911
			$update_data['paied_amount'] = $data->get_total();
912
			$update_data['invoice_id'] = $data->ID;
913
			
914
			$wpdb->update( INVOICE_TABLE, $update_data, array( 'id' => $item->gdp_id ) );
915
		}
916
	} else {
917
        $success = false;
918
        $message = __( 'No invoices found to fix taxes!', 'invoicing' );
919
    }
920
	
921
	$response = array();
922
    $response['success'] = $success;
923
    $response['data']['message'] = $message;
924
    wp_send_json( $response );
925
}
926
add_action( 'wpinv_tool_merge_fix_taxes', 'wpinv_tool_merge_fix_taxes' );
927
remove_action( 'geodir_before_detail_fields' , 'geodir_build_coupon', 2 );
928
929
function wpinv_wpi_to_gdp_handle_subscription_cancel( $invoice_id, $invoice ) {
0 ignored issues
show
Unused Code introduced by
The parameter $invoice_id is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
930
    if ( wpinv_pm_active() && !empty( $invoice ) && $invoice->is_recurring() ) {
931
        if ( $invoice->is_renewal() ) {
932
            $invoice = $invoice->get_parent_payment();
933
        }
934
        
935
        if ( !empty( $invoice ) ) {
936
            wpinv_wpi_to_gdp_update_status( $invoice->ID, 'wpi-cancelled', $invoice->get_status() );
937
        }
938
    }
939
}
940
add_action( 'wpinv_subscription_cancelled', 'wpinv_wpi_to_gdp_handle_subscription_cancel', 10, 2 );