Passed
Pull Request — master (#126)
by Kiran
04:13
created

wpinv-upgrade-functions.php ➔ wpinv_convert_old_subscriptions()   F

Complexity

Conditions 23
Paths 545

Size

Total Lines 111
Code Lines 71

Duplication

Lines 9
Ratio 8.11 %

Importance

Changes 0
Metric Value
cc 23
eloc 71
nc 545
nop 0
dl 9
loc 111
rs 2.609
c 0
b 0
f 0

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
/**
3
 * Upgrade related functions.
4
 *
5
 * @since 1.0.0
6
 */
7
8
/**
9
 * Perform automatic upgrades when necessary.
10
 *
11
 * @since 1.0.0
12
*/
13
function wpinv_automatic_upgrade() {
14
    $wpi_version = get_option( 'wpinv_version' );
15
16
    if ( $wpi_version == WPINV_VERSION ) {
17
        return;
18
    }
19
    
20
    if ( version_compare( $wpi_version, '0.0.5', '<' ) ) {
21
        wpinv_v005_upgrades();
22
    }
23
    
24
    if ( version_compare( $wpi_version, '1.0.3', '<' ) ) {
25
        wpinv_v103_upgrades();
26
    }
27
    
28
    update_option( 'wpinv_version', WPINV_VERSION );
29
}
30
add_action( 'admin_init', 'wpinv_automatic_upgrade' );
31
32
function wpinv_v005_upgrades() {
33
    global $wpdb;
34
    
35
    // Invoices status
36
    $results = $wpdb->get_results( "SELECT ID FROM " . $wpdb->posts . " WHERE post_type = 'wpi_invoice' AND post_status IN( 'pending', 'processing', 'onhold', 'refunded', 'cancelled', 'failed', 'renewal' )" );
37
    if ( !empty( $results ) ) {
38
        $wpdb->query( "UPDATE " . $wpdb->posts . " SET post_status = CONCAT( 'wpi-', post_status ) WHERE post_type = 'wpi_invoice' AND post_status IN( 'pending', 'processing', 'onhold', 'refunded', 'cancelled', 'failed', 'renewal' )" );
39
        
40
        // Clean post cache
41
        foreach ( $results as $row ) {
42
            clean_post_cache( $row->ID );
43
        }
44
    }
45
    
46
    // Item meta key changes
47
    $query = "SELECT DISTINCT post_id FROM " . $wpdb->postmeta . " WHERE meta_key IN( '_wpinv_item_id', '_wpinv_package_id', '_wpinv_post_id', '_wpinv_cpt_name', '_wpinv_cpt_singular_name' )";
48
    $results = $wpdb->get_results( $query );
49
    
50
    if ( !empty( $results ) ) {
51
        $wpdb->query( "UPDATE " . $wpdb->postmeta . " SET meta_key = '_wpinv_custom_id' WHERE meta_key IN( '_wpinv_item_id', '_wpinv_package_id', '_wpinv_post_id' )" );
52
        $wpdb->query( "UPDATE " . $wpdb->postmeta . " SET meta_key = '_wpinv_custom_name' WHERE meta_key = '_wpinv_cpt_name'" );
53
        $wpdb->query( "UPDATE " . $wpdb->postmeta . " SET meta_key = '_wpinv_custom_singular_name' WHERE meta_key = '_wpinv_cpt_singular_name'" );
54
        
55
        foreach ( $results as $row ) {
56
            clean_post_cache( $row->post_id );
57
        }
58
    }
59
60
    wpinv_add_admin_caps();
61
}
62
63
function wpinv_v103_upgrades() {
64
    // Upgrade email settings
65
    wpinv_update_new_email_settings();
66
    
67
    // Add Subscription tables
68
    $db = new WPInv_Subscriptions_DB;
69
    @$db->create_table();
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
70
71
    wpinv_convert_old_subscriptions();
72
}
73
74
function wpinv_convert_old_subscriptions() {
75
    global $wpdb;
76
77
    $query = "SELECT ". $wpdb->posts .".ID FROM ". $wpdb->posts ." INNER JOIN ". $wpdb->postmeta ." ON ( ". $wpdb->posts .".ID = ". $wpdb->postmeta .".post_id ) WHERE 1=1  AND ". $wpdb->postmeta .".meta_key = '_wpinv_subscr_status' AND (". $wpdb->postmeta .".meta_value = 'pending' OR ". $wpdb->postmeta .".meta_value = 'active' OR ". $wpdb->postmeta .".meta_value = 'cancelled' OR ". $wpdb->postmeta .".meta_value = 'completed' OR ". $wpdb->postmeta .".meta_value = 'expired' OR ". $wpdb->postmeta .".meta_value = 'trialling' OR ". $wpdb->postmeta .".meta_value = 'failing') AND ". $wpdb->posts .".post_type = 'wpi_invoice' GROUP BY ". $wpdb->posts .".ID ORDER BY ". $wpdb->posts .".ID ASC";
78
79
    $results = $wpdb->get_results( $query );
80
81
    if ( empty( $results ) ) {
82
        return;
83
    }
84
85
    foreach ( $results as $row ) {
86
        $invoice = new WPInv_Invoice( $row->ID );
87
88
        if ( empty( $invoice->ID ) ) {
89
            continue;
90
        }
91
92
        if ( $invoice->has_status( 'wpi-renewal' ) ) {
93
            continue;
94
        }
95
        
96
        $item = $invoice->get_recurring( true );
97
98
        if ( empty( $item ) ) {
99
            continue;
100
        }
101
102
        $is_free_trial          = $invoice->is_free_trial();
0 ignored issues
show
Unused Code introduced by
$is_free_trial 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...
103
        $profile_id             = get_post_meta( $invoice->ID, '_wpinv_subscr_profile_id', true );
104
        $subscription_status    = get_post_meta( $invoice->ID, '_wpinv_subscr_status', true );
105
        $transaction_id         = $invoice->get_transaction_id();
106
107
        // Last invoice
108
        $query          = "SELECT ID, post_date FROM ". $wpdb->posts ." WHERE post_type = 'wpi_invoice' AND post_parent = '" . $invoice->ID . "' ORDER BY ID DESC LIMIT 1";
109
        $last_payment   = $wpdb->get_row( $query );
110
111
        if ( !empty( $last_payment ) ) {
112
            $invoice_date       = $last_payment->post_date;
113
            
114
            $meta_profile_id     = get_post_meta( $last_payment->ID, '_wpinv_subscr_profile_id', true );
115
            $meta_transaction_id = get_post_meta( $last_payment->ID, '_wpinv_transaction_id', true );
116
117
            if ( !empty( $meta_profile_id ) ) {
118
                $profile_id  = $meta_profile_id;
119
            }
120
121
            if ( !empty( $meta_transaction_id ) ) {
122
                $transaction_id  = $meta_transaction_id;
123
            }
124
        } else {
125
            $invoice_date       = $invoice->get_invoice_date( false );
126
        }
127
        
128
        $profile_id             = empty( $profile_id ) ? $invoice->ID : $profile_id;
129
        $status                 = empty( $subscription_status ) ? 'pending' : $subscription_status;
130
        
131
        $period                 = $item->get_recurring_period( true );
132
        $interval               = $item->get_recurring_interval();
133
        $bill_times             = (int)$item->get_recurring_limit();
134
        $add_period             = $interval . ' ' . $period;
135
        $trial_period           = '';
136
137 View Code Duplication
        if ( $invoice->is_free_trial() ) {
138
            $trial_period       = $item->get_trial_period( true );
139
            $free_interval      = $item->get_trial_interval();
140
            $trial_period       = $free_interval . ' ' . $trial_period;
141
142
            if ( empty( $last_payment ) ) {
143
                $add_period     = $trial_period;
144
            }
145
        }
146
147
        $expiration             = date_i18n( 'Y-m-d H:i:s', strtotime( '+' . $add_period  . ' 23:59:59', strtotime( $invoice_date ) ) );
148
        if ( strtotime( $expiration ) <  strtotime( date_i18n( 'Y-m-d' ) ) ) {
149
            if ( $status == 'active' || $status == 'trialling' || $status == 'pending' ) {
150
                $status = 'expired';
151
            }
152
        }
153
154
        $args = array(
155
            'product_id'        => $item->ID,
156
            'customer_id'       => $invoice->user_id,
157
            'parent_payment_id' => $invoice->ID,
158
            'status'            => $status,
159
            'frequency'         => $interval,
160
            'period'            => $period,
161
            'initial_amount'    => $invoice->get_total(),
162
            'recurring_amount'  => $invoice->get_recurring_details( 'total' ),
163
            'bill_times'        => $bill_times,
164
            'created'           => $invoice_date,
165
            'expiration'        => $expiration,
166
            'trial_period'      => $trial_period,
167
            'profile_id'        => $profile_id,
168
            'transaction_id'    => $transaction_id,
169
        );
170
171
        $subs_db      = new WPInv_Subscriptions_DB;
172
        $subs         = $subs_db->get_subscriptions( array( 'parent_payment_id' => $invoice->ID, 'number' => 1 ) );
173
        $subscription = reset( $subs );
174
175
        if ( empty( $subscription ) || $subscription->id <= 0 ) {
176
            $subscription = new WPInv_Subscription();
177
            $new_sub = $subscription->create( $args );
178
179
            if ( !empty( $bill_times ) && $new_sub->get_times_billed() >= $bill_times && ( 'active' == $new_sub->status || 'trialling' == $new_sub->status ) ) {
180
                $new_sub->complete(); // Mark completed if all times billed
181
            }
182
        }
183
    }
184
}
185
186
function wpinv_update_new_email_settings() {
187
    global $wpinv_options;
188
189
    $current_options = get_option( 'wpinv_settings', array() );
190
    $options = array();
191
192
    // Populate some default values
193 View Code Duplication
    foreach( wpinv_get_registered_settings() as $tab => $sections ) {
194
        foreach( $sections as $section => $settings) {
195
            // Check for backwards compatibility
196
            $tab_sections = wpinv_get_settings_tab_sections( $tab );
0 ignored issues
show
Documentation introduced by
$tab is of type integer|string, but the function expects a boolean.

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...
197
            if( ! is_array( $tab_sections ) || ! array_key_exists( $section, $tab_sections ) ) {
198
                $section = 'main';
199
                $settings = $sections;
200
            }
201
202
            foreach ( $settings as $option ) {
203
                if ( !empty( $option['id'] ) && !isset( $wpinv_options[ $option['id'] ] ) ) {
204
                    if ( 'checkbox' == $option['type'] && !empty( $option['std'] ) ) {
205
                        $options[ $option['id'] ] = '1';
206
                    } else if ( !empty( $option['std'] ) ) {
207
                        $options[ $option['id'] ] = $option['std'];
208
                    }
209
                }
210
            }
211
        }
212
    }
213
214
    $merged_options_current = array_merge( $wpinv_options, $options );
215
    $merged_options = array_merge( $merged_options_current, $current_options );
216
    $wpinv_options = $merged_options;
217
218
    update_option( 'wpinv_settings', $merged_options );
219
}