Passed
Pull Request — master (#47)
by Kiran
04:02
created

wpinv-gd-functions.php ➔ wpinv_wpi_to_gdp_status()   D

Complexity

Conditions 9
Paths 16

Size

Total Lines 25
Code Lines 21

Duplication

Lines 25
Ratio 100 %

Importance

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