Passed
Pull Request — master (#50)
by Kiran
03:42
created

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

Complexity

Conditions 7
Paths 12

Size

Total Lines 22
Code Lines 19

Duplication

Lines 22
Ratio 100 %

Importance

Changes 0
Metric Value
cc 7
eloc 19
nc 12
nop 1
dl 22
loc 22
rs 6.9811
c 0
b 0
f 0
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 = '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 : 'pending';
391
    
392
    switch ( $status ) {
393
        case 'confirmed':
394
            $inv_status = 'publish';
395
        break;
396
        case 'cancelled':
397
            $inv_status = 'wpi-cancelled';
398
        break;
399
        case 'failed':
400
            $inv_status = 'wpi-failed';
401
        break;
402
        case 'onhold':
403
            $inv_status = 'wpi-onhold';
404
        break;
405
        case 'refunded':
406
            $inv_status = 'wpi-refunded';
407
        break;
408
    }
409
    return $inv_status;
410
}
411
412 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...
413
    $inv_status = $status ? $status : 'pending';
414
    
415
    switch ( $status ) {
416
        case 'publish':
417
        case 'wpi-processing':
418
        case 'wpi-renewal':
419
            $inv_status = 'confirmed';
420
        break;
421
        case 'wpi-cancelled':
422
            $inv_status = 'cancelled';
423
        break;
424
        case 'wpi-failed':
425
            $inv_status = 'failed';
426
        break;
427
        case 'wpi-onhold':
428
            $inv_status = 'onhold';
429
        break;
430
        case 'wpi-refunded':
431
            $inv_status = 'refunded';
432
        break;
433
    }
434
    
435
    return $inv_status;
436
}
437
438
function wpinv_wpi_to_gdp_id( $invoice_id ) {
439
    global $wpdb;
440
    
441
    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 ) ) );
442
}
443
444
function wpinv_gdp_to_wpi_id( $invoice_id ) {
445
    $invoice = geodir_get_invoice( $invoice_id );    
446
    return ( empty( $invoice->invoice_id ) ? $invoice->invoice_id : false);
447
}
448
449
function wpinv_to_gdp_recalculate_total( $invoice, $wpi_nosave ) {
450
    global $wpdb;
451
    
452
    if ( !empty( $wpi_nosave ) ) {
453
        return;
454
    }
455
    
456
    $gdp_invoice_id = wpinv_wpi_to_gdp_id( $invoice->ID );
457
    
458
    if ( $gdp_invoice_id > 0 ) {
459
        $update_data = array();
460
        $update_data['tax_amount']      = $invoice->tax;
461
        $update_data['paied_amount']    = $invoice->total;
462
        $update_data['discount']        = $invoice->discount;
463
        $update_data['coupon_code']     = $invoice->discount_code;
464
        
465
        $wpdb->update( INVOICE_TABLE, $update_data, array( 'id' => $gdp_invoice_id ) );
466
    }
467
    
468
    return;
469
}
470
//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...
471
472
function wpinv_gdp_to_wpi_invoice( $invoice_id ) {
473
    $invoice = geodir_get_invoice( $invoice_id );
474
    if ( empty( $invoice->invoice_id ) ) {
475
        return false;
476
    }
477
    
478
    return wpinv_get_invoice( $invoice->invoice_id );
479
}
480
481
function wpinv_payment_set_coupon_code( $status, $invoice_id, $coupon_code ) {
482
    $invoice = wpinv_gdp_to_wpi_invoice( $invoice_id );
483
    if ( empty( $invoice ) ) {
484
        return $status;
485
    }
486
487
    if ( $status === 1 || $status === 0 ) {
488
        if ( $status === 1 ) {
489
            $discount = geodir_get_discount_amount( $coupon_code, $invoice->get_subtotal() );
490
        } else {
491
            $discount = '';
492
            $coupon_code = '';
493
        }
494
        
495
        $invoice->set( 'discount', $discount );
496
        $invoice->set( 'discount_code', $coupon_code );
497
        $invoice->save();
498
        $invoice->recalculate_total();
499
    }
500
    
501
    return $status;
502
}
503
add_filter( 'geodir_payment_set_coupon_code', 'wpinv_payment_set_coupon_code', 10, 3 );
504
505
function wpinv_merge_gd_invoices() {
506
    if (!defined('GEODIRPAYMENT_VERSION')) {
507
        return;
508
    }
509
    ?>
510
    <tr>
511
        <td><?php _e( 'Merge Price Packages', 'invoicing' ); ?></td>
512
        <td><p><?php _e( 'Merge GeoDirectory Payment Manager price packages to the Invoicing items.', 'invoicing' ); ?></p></td>
513
        <td><input type="button" data-tool="merge_packages" class="button-primary wpinv-tool" value="<?php esc_attr_e( 'Run', 'invoicing' ); ?>"></td>
514
    </tr>
515
    <tr>
516
        <td><?php _e( 'Merge Invoices', 'invoicing' ); ?></td>
517
        <td><p><?php _e( 'Merge GeoDirectory Payment Manager invoices to the Invoicing.', 'invoicing' ); ?></p></td>
518
        <td><input type="button" data-tool="merge_invoices" class="button-primary wpinv-tool" value="<?php esc_attr_e( 'Run', 'invoicing' ); ?>"></td>
519
    </tr>
520
	<tr>
521
        <td><?php _e( 'Fix Taxes for Merged Invoices', 'invoicing' ); ?></td>
522
        <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>
523
        <td><input type="button" data-tool="merge_fix_taxes" class="button-primary wpinv-tool" value="<?php esc_attr_e( 'Run', 'invoicing' ); ?>"></td>
524
    </tr>
525
    <tr>
526
        <td><?php _e( 'Merge Coupons', 'invoicing' ); ?></td>
527
        <td><p><?php _e( 'Merge GeoDirectory Payment Manager coupons to the Invoicing.', 'invoicing' ); ?></p></td>
528
        <td><input type="button" data-tool="merge_coupons" class="button-primary wpinv-tool" value="<?php esc_attr_e( 'Run', 'invoicing' ); ?>"></td>
529
    </tr>
530
    <?php
531
}
532
add_action( 'wpinv_tools_row', 'wpinv_merge_gd_invoices', 10 );
533
534
function wpinv_tool_merge_packages() {
535
    $packages = geodir_package_list_info();
536
    
537
    $count = 0;
538
    
539
    if ( !empty( $packages ) ) {
540
        $success = true;
541
        
542
        foreach ( $packages as $key => $package ) {
543
            $item = wpinv_get_item_by('custom_id', $package->pid, 'package');
544
            if ( !empty( $item ) ) {
545
                continue;
546
            }
547
            
548
            $merged = wpinv_merge_gd_package_to_item( $package->pid, false, $package );
549
            
550
            if ( !empty( $merged ) ) {
551
                wpinv_error_log( 'Package merge S : ' . $package->pid );
552
                $count++;
553
            } else {
554
                wpinv_error_log( 'Package merge F : ' . $package->pid );
555
            }
556
        }
557
        
558 View Code Duplication
        if ( $count > 0 ) {
559
            $message = sprintf( _n( 'Total <b>%d</b> price package is merged successfully.', 'Total <b>%d</b> price packages are merged successfully.', $count, 'invoicing' ), $count );
560
        } else {
561
            $message = __( 'No price packages merged.', 'invoicing' );
562
        }
563
    } else {
564
        $success = false;
565
        $message = __( 'No price packages found to merge!', 'invoicing' );
566
    }
567
    
568
    $response = array();
569
    $response['success'] = $success;
570
    $response['data']['message'] = $message;
571
    wp_send_json( $response );
572
}
573
add_action( 'wpinv_tool_merge_packages', 'wpinv_tool_merge_packages' );
574
575
function wpinv_tool_merge_invoices() {
576
    global $wpdb, $wpi_gdp_inv_merge, $wpi_tax_rates;
577
    
578
    $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";
579
580
    $items = $wpdb->get_results( $sql );
581
    
582
    $count = 0;
583
    
584
    if ( !empty( $items ) ) {
585
        $success = true;
586
        $wpi_gdp_inv_merge = true;
587
        
588
        foreach ( $items as $item ) {
589
            $wpi_tax_rates = NULL;
590
            
591
            $wpdb->query( "UPDATE `" . INVOICE_TABLE . "` SET `invoice_id` = 0 WHERE id = '" . $item->id . "'" );
592
            
593
            $merged = wpinv_cpt_save( $item->id );
594
            
595
            if ( !empty( $merged ) && !empty( $merged->ID ) ) {
596
                $count++;
597
                
598
                $post_date = !empty( $item->date ) && $item->date != '0000-00-00 00:00:00' ? $item->date : current_time( 'mysql' );
599
                $post_date_gmt = get_gmt_from_date( $post_date );
600
                $post_modified = !empty( $item->date_updated ) && $item->date_updated != '0000-00-00 00:00:00' ? $item->date_updated : $post_date;
601
                $post_modified_gmt = get_gmt_from_date( $post_modified );
602
                
603
                $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 ) );
604
                
605
                if ( $merged->is_paid() ) {
606
                    update_post_meta( $merged->ID, '_wpinv_completed_date', $post_modified );
607
                }
608
                
609
                clean_post_cache( $merged->ID );
610
                
611
                wpinv_error_log( 'Invoice merge S : ' . $item->id . ' => ' . $merged->ID );
612
            } else {
613
                wpinv_error_log( 'Invoice merge F : ' . $item->id );
614
            }
615
        }
616
        
617
        $wpi_gdp_inv_merge = false;
618
        
619 View Code Duplication
        if ( $count > 0 ) {
620
            $message = sprintf( _n( 'Total <b>%d</b> invoice is merged successfully.', 'Total <b>%d</b> invoices are merged successfully.', $count, 'invoicing' ), $count );
621
        } else {
622
            $message = __( 'No invoices merged.', 'invoicing' );
623
        }
624
    } else {
625
        $success = false;
626
        $message = __( 'No invoices found to merge!', 'invoicing' );
627
    }
628
    
629
    $response = array();
630
    $response['success'] = $success;
631
    $response['data']['message'] = $message;
632
    wp_send_json( $response );
633
}
634
add_action( 'wpinv_tool_merge_invoices', 'wpinv_tool_merge_invoices' );
635
636
function wpinv_tool_merge_coupons() {
637
    global $wpdb;
638
    
639
    $sql = "SELECT * FROM `" . COUPON_TABLE . "` WHERE `coupon_code` IS NOT NULL AND `coupon_code` != '' ORDER BY `cid` ASC";
640
    $items = $wpdb->get_results( $sql );
641
    $count = 0;
642
    
643
    if ( !empty( $items ) ) {
644
        $success = true;
645
        
646
        foreach ( $items as $item ) {
647
            if ( wpinv_get_discount_by_code( $item->coupon_code ) ) {
648
                continue;
649
            }
650
            
651
            $args = array(
652
                'post_type'   => 'wpi_discount',
653
                'post_title'  => $item->coupon_code,
654
                'post_status' => !empty( $item->status ) ? 'publish' : 'pending'
655
            );
656
657
            $merged = wp_insert_post( $args );
658
            
659
            $item_id = $item->cid;
660
            
661
            if ( $merged ) {
662
                $meta = array(
663
                    'code'              => $item->coupon_code,
664
                    'type'              => $item->discount_type != 'per' ? 'flat' : 'percent',
665
                    'amount'            => (float)$item->discount_amount,
666
                    'max_uses'          => (int)$item->usage_limit,
667
                    'uses'              => (int)$item->usage_count,
668
                );
669
                wpinv_store_discount( $merged, $meta, get_post( $merged ) );
670
                
671
                $count++;
672
                
673
                wpinv_error_log( 'Coupon merge S : ' . $item_id . ' => ' . $merged );
674
            } else {
675
                wpinv_error_log( 'Coupon merge F : ' . $item_id );
676
            }
677
        }
678
        
679 View Code Duplication
        if ( $count > 0 ) {
680
            $message = sprintf( _n( 'Total <b>%d</b> coupon is merged successfully.', 'Total <b>%d</b> coupons are merged successfully.', $count, 'invoicing' ), $count );
681
        } else {
682
            $message = __( 'No coupons merged.', 'invoicing' );
683
        }
684
    } else {
685
        $success = false;
686
        $message = __( 'No coupons found to merge!', 'invoicing' );
687
    }
688
    
689
    $response = array();
690
    $response['success'] = $success;
691
    $response['data']['message'] = $message;
692
    wp_send_json( $response );
693
}
694
add_action( 'wpinv_tool_merge_coupons', 'wpinv_tool_merge_coupons' );
695
696
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...
697
    return wpinv_get_currency();
698
}
699
add_filter( 'pre_option_geodir_currency', 'wpinv_gdp_to_wpi_currency', 10, 2 );
700
701
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...
702
    return wpinv_currency_symbol();
703
}
704
add_filter( 'pre_option_geodir_currencysym', 'wpinv_gdp_to_wpi_currency_sign', 10, 2 );
705
706
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...
707
    if ( !$display ) {
708
        $price = wpinv_round_amount( $amount );
709
    } else {
710
        $price = wpinv_price( wpinv_format_amount( $amount ) );
711
    }
712
    
713
    return $price;
714
}
715
add_filter( 'geodir_payment_price' , 'wpinv_gdp_to_wpi_display_price', 10000, 5 );
716
717
function wpinv_gdp_to_inv_checkout_redirect( $redirect_url ) {
718
    $invoice_id         = geodir_payment_cart_id();
719
    $invoice_info       = geodir_get_invoice( $invoice_id );
720
    $wpi_invoice        = !empty( $invoice_info->invoice_id ) ? wpinv_get_invoice( $invoice_info->invoice_id ) : NULL;
721
    
722
    if ( !( !empty( $wpi_invoice ) && !empty( $wpi_invoice->ID ) ) ) {
723
        $wpi_invoice_id = wpinv_cpt_save( $invoice_id );
724
        $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 723 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...
725
    }
726
    
727
    if ( !empty( $wpi_invoice ) && !empty( $wpi_invoice->ID ) ) {
728
        
729
        // Clear cart
730
        geodir_payment_clear_cart();
731
    
732
        $redirect_url = $wpi_invoice->get_checkout_payment_url();
733
    }
734
    
735
    return $redirect_url;
736
}
737
add_filter( 'geodir_payment_checkout_redirect_url', 'wpinv_gdp_to_inv_checkout_redirect', 100, 1 );
738
739
function wpinv_gdp_dashboard_invoice_history_link( $dashboard_links ) {    
740
    if ( get_current_user_id() ) {        
741
        $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>';
742
    }
743
744
    return $dashboard_links;
745
}
746
add_action( 'geodir_dashboard_links', 'wpinv_gdp_dashboard_invoice_history_link' );
747
remove_action( 'geodir_dashboard_links', 'geodir_payment_invoices_list_page_link' );
748
749
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...
750
    if (!defined('GEODIRPAYMENT_VERSION')) {
751
        return false;
752
    }
753
    
754
    $invoice    = wpinv_get_invoice( $invoice_id );
755
    if ( empty( $invoice ) ) {
756
        return false;
757
    }
758
    
759
    remove_action( 'geodir_payment_invoice_status_changed', 'wpinv_payment_status_changed', 11, 4 );
760
    
761
    $invoice_id = wpinv_wpi_to_gdp_id( $invoice_id );
762
    $new_status = wpinv_wpi_to_gdp_status( $new_status );
763
    
764
    geodir_update_invoice_status( $invoice_id, $new_status, $invoice->is_recurring() );
765
}
766
add_action( 'wpinv_update_status', 'wpinv_wpi_to_gdp_update_status', 999, 3 );
767
768
function wpinv_gdp_to_wpi_delete_package( $gd_package_id ) {
769
    $item = wpinv_get_item_by( 'custom_id', $gd_package_id, 'package' );
770
    
771
    if ( !empty( $item ) ) {
772
        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...
773
    }
774
}
775
add_action( 'geodir_payment_post_delete_package', 'wpinv_gdp_to_wpi_delete_package', 10, 1 ) ;
776
777
function wpinv_can_delete_package_item( $return, $post_id ) {
778
    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 ) ) {
779
        $gd_package = geodir_get_package_info_by_id( $package_id, '' );
780
        
781
        if ( !empty( $gd_package ) ) {
782
            $return = false;
783
        }
784
    }
785
786
    return $return;
787
}
788
add_filter( 'wpinv_can_delete_item', 'wpinv_can_delete_package_item', 10, 2 );
789
790
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...
791
    global $typenow;
792
793
    if ( $typenow == 'wpi_item' && in_array( 'wpi-gd-package', $classes ) ) {
794
        if ( wpinv_item_in_use( $post_id ) ) {
795
            $classes[] = 'wpi-inuse-pkg';
796
        } 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 ), '' ) ) ) {
797
            $classes[] = 'wpi-delete-pkg';
798
        }
799
    }
800
801
    return $classes;
802
}
803
add_filter( 'post_class', 'wpinv_package_item_classes', 10, 3 );
804
805
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...
806
    if ( wpinv_pm_active() ) {
807
        ?><p class="wpi-m0"><?php _e( 'Package: GeoDirectory price packages items.', 'invoicing' );?></p>
808
        <?php
809
    }
810
}
811
add_action( 'wpinv_item_info_metabox_after', 'wpinv_gdp_package_type_info', 10, 1 ) ;
812
813
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...
814
    global $wpi_zero_tax;
815
816
    if ( $wpi_zero_tax ) {
817
        $is_taxable = false;
818
    }
819
820
    return $is_taxable;
821
}
822
add_action( 'wpinv_item_is_taxable', 'wpinv_gdp_to_gdi_set_zero_tax', 10, 4 ) ;
823
824
function wpinv_tool_merge_fix_taxes() {
825
    global $wpdb;
826
    
827
	$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'";
828
	$items = $wpdb->get_results( $sql );
829
	
830
	if ( !empty( $items ) ) {
831
		foreach ( $items as $item ) {
832
			if ( get_post_meta( $item->ID, '_wpinv_vat_class', true ) == '_exempt' ) {
833
				update_post_meta( $item->ID, '_wpinv_vat_class', '_standard' );
834
			}
835
		}
836
	}
837
		
838
    $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";
839
    $items = $wpdb->get_results( $sql );
840
	
841
	if ( !empty( $items ) ) {
842
		$success = false;
843
        $message = __( 'Taxes fixed for non-paid merged GD invoices.', 'invoicing' );
844
		
845
		global $wpi_userID, $wpinv_ip_address_country, $wpi_tax_rates;
846
		
847
		foreach ( $items as $item ) {
848
			$wpi_tax_rates = NULL;               
849
			$data = wpinv_get_invoice($item->ID);
850
851
			if ( empty( $data ) ) {
852
				continue;
853
			}
854
			
855
			$checkout_session = wpinv_get_checkout_session();
856
			
857
			$data_session                   = array();
858
			$data_session['invoice_id']     = $data->ID;
859
			$data_session['cart_discounts'] = $data->get_discounts( true );
860
			
861
			wpinv_set_checkout_session( $data_session );
862
			
863
			$wpi_userID         = (int)$data->get_user_id();
864
			$_POST['country']   = !empty($data->country) ? $data->country : wpinv_get_default_country();
865
				
866
			$data->country      = sanitize_text_field( $_POST['country'] );
867
			$data->set( 'country', sanitize_text_field( $_POST['country'] ) );
868
			
869
			$wpinv_ip_address_country = $data->country;
870
			
871
			$data->recalculate_totals(true);
872
			
873
			wpinv_set_checkout_session( $checkout_session );
874
			
875
			$update_data = array();
876
			$update_data['tax_amount'] = $data->get_tax();
877
			$update_data['paied_amount'] = $data->get_total();
878
			$update_data['invoice_id'] = $data->ID;
879
			
880
			$wpdb->update( INVOICE_TABLE, $update_data, array( 'id' => $item->gdp_id ) );
881
		}
882
	} else {
883
        $success = false;
884
        $message = __( 'No invoices found to fix taxes!', 'invoicing' );
885
    }
886
	
887
	$response = array();
888
    $response['success'] = $success;
889
    $response['data']['message'] = $message;
890
    wp_send_json( $response );
891
}
892
add_action( 'wpinv_tool_merge_fix_taxes', 'wpinv_tool_merge_fix_taxes' );
893
remove_action( 'geodir_before_detail_fields' , 'geodir_build_coupon', 2 );
894
895
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...
896
    if ( wpinv_pm_active() && !empty( $invoice ) && $invoice->is_recurring() ) {
897
        if ( $invoice->is_renewal() ) {
898
            $invoice = $invoice->get_parent_payment();
899
        }
900
        
901
        if ( !empty( $invoice ) ) {
902
            wpinv_wpi_to_gdp_update_status( $invoice->ID, 'wpi-cancelled', $invoice->get_status() );
903
        }
904
    }
905
}
906
add_action( 'wpinv_subscription_cancelled', 'wpinv_wpi_to_gdp_handle_subscription_cancel', 10, 2 );