Passed
Push — master ( 258987...4a6585 )
by Brian
09:29 queued 04:10
created

wpinv_v119_upgrades()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 2
nc 1
nop 0
dl 0
loc 3
rs 10
c 0
b 0
f 0
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
    // Update tables.
17
    if ( ! get_option( 'getpaid_created_invoice_tables' ) ) {
18
        wpinv_v119_upgrades();
19
        update_option( 'getpaid_created_invoice_tables', true );
20
    }
21
22
    if ( $wpi_version == WPINV_VERSION ) {
23
        return;
24
    }
25
26
    if ( version_compare( $wpi_version, '0.0.5', '<' ) ) {
0 ignored issues
show
Bug introduced by
It seems like $wpi_version can also be of type false; however, parameter $version1 of version_compare() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

26
    if ( version_compare( /** @scrutinizer ignore-type */ $wpi_version, '0.0.5', '<' ) ) {
Loading history...
27
        wpinv_v005_upgrades();
28
    }
29
30
    if ( version_compare( $wpi_version, '1.0.3', '<' ) ) {
31
        wpinv_v110_upgrades();
32
    }
33
34
    update_option( 'wpinv_version', WPINV_VERSION );
35
}
36
add_action( 'admin_init', 'wpinv_automatic_upgrade' );
37
38
function wpinv_v005_upgrades() {
39
    global $wpdb;
40
41
    // Invoices status
42
    $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' )" );
43
    if ( !empty( $results ) ) {
44
        $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' )" );
45
46
        // Clean post cache
47
        foreach ( $results as $row ) {
48
            clean_post_cache( $row->ID );
49
        }
50
    }
51
52
    // Item meta key changes
53
    $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' )";
54
    $results = $wpdb->get_results( $query );
55
56
    if ( !empty( $results ) ) {
57
        $wpdb->query( "UPDATE " . $wpdb->postmeta . " SET meta_key = '_wpinv_custom_id' WHERE meta_key IN( '_wpinv_item_id', '_wpinv_package_id', '_wpinv_post_id' )" );
58
        $wpdb->query( "UPDATE " . $wpdb->postmeta . " SET meta_key = '_wpinv_custom_name' WHERE meta_key = '_wpinv_cpt_name'" );
59
        $wpdb->query( "UPDATE " . $wpdb->postmeta . " SET meta_key = '_wpinv_custom_singular_name' WHERE meta_key = '_wpinv_cpt_singular_name'" );
60
        
61
        foreach ( $results as $row ) {
62
            clean_post_cache( $row->post_id );
63
        }
64
    }
65
66
    wpinv_add_admin_caps();
67
}
68
69
function wpinv_v110_upgrades() {
70
    // Upgrade email settings
71
    wpinv_update_new_email_settings();
72
73
    // Add Subscription tables
74
    $db = new WPInv_Subscriptions_DB;
75
    /** @scrutinizer ignore-unhandled */ @$db->create_table();
0 ignored issues
show
Bug introduced by
Are you sure the usage of $db->create_table() targeting WPInv_Subscriptions_DB::create_table() seems to always return null.

This check looks for function or method calls that always return null and whose return value is used.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
if ($a->getObject()) {

The method getObject() can return nothing but null, so it makes no sense to use the return value.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
76
77
}
78
79
function wpinv_update_new_email_settings() {
80
    global $wpinv_options;
81
82
    $current_options = get_option( 'wpinv_settings', array() );
83
    $options = array(
84
        'email_new_invoice_body' => __( '<p>Hi Admin,</p><p>You have received payment invoice from {name}.</p>', 'invoicing' ),
85
        'email_cancelled_invoice_body' => __( '<p>Hi Admin,</p><p>The invoice #{invoice_number} from {site_title} has been cancelled.</p>', 'invoicing' ),
86
        'email_failed_invoice_body' => __( '<p>Hi Admin,</p><p>Payment for invoice #{invoice_number} from {site_title} has been failed.</p>', 'invoicing' ),
87
        'email_onhold_invoice_body' => __( '<p>Hi {name},</p><p>Your invoice is on-hold until we confirm your payment has been received.</p>', 'invoicing' ),
88
        'email_processing_invoice_body' => __( '<p>Hi {name},</p><p>Your invoice has been received at {site_title} and is now being processed.</p>', 'invoicing' ),
89
        'email_refunded_invoice_body' => __( '<p>Hi {name},</p><p>Your invoice on {site_title} has been refunded.</p>', 'invoicing' ),
90
        'email_user_invoice_body' => __( '<p>Hi {name},</p><p>An invoice has been created for you on {site_title}. To view / pay for this invoice please use the following link: <a class="btn btn-success" href="{invoice_link}">View / Pay</a></p>', 'invoicing' ),
91
        'email_user_note_body' => __( '<p>Hi {name},</p><p>Following note has been added to your {invoice_label}:</p><blockquote class="wpinv-note">{customer_note}</blockquote>', 'invoicing' ),
92
        'email_overdue_body' => __( '<p>Hi {full_name},</p><p>This is just a friendly reminder that your invoice <a href="{invoice_link}">#{invoice_number}</a> {is_was} due on {invoice_due_date}.</p><p>The total of this invoice is {invoice_total}</p><p>To view / pay now for this invoice please use the following link: <a class="btn btn-success" href="{invoice_link}">View / Pay</a></p>', 'invoicing' ),
93
    );
94
95
    foreach ($options as $option => $value){
96
        if (!isset($current_options[$option])) {
97
            $current_options[$option] = $value;
98
        }
99
    }
100
101
    $wpinv_options = $current_options;
102
103
    update_option( 'wpinv_settings', $current_options );
104
}
105
106
/**
107
 * Version 119 upgrades.
108
 */
109
function wpinv_v119_upgrades() {
110
    wpinv_create_invoices_table();
111
    wpinv_convert_old_invoices();
112
}
113
114
/**
115
 * Creates the invoices table.
116
 */
117
function wpinv_create_invoices_table() {
118
    global $wpdb;
119
120
    require_once( ABSPATH . 'wp-admin/includes/upgrade.php' );
121
122
    // Create invoices table.
123
    $table = $wpdb->prefix . 'getpaid_invoices';
124
    $sql   = "CREATE TABLE $table (
125
126
            post_id BIGINT(20) NOT NULL,
127
            `number` VARCHAR(100),
128
            `key` VARCHAR(100),
129
            `type` VARCHAR(100) NOT NULL DEFAULT 'invoice',
130
            mode VARCHAR(100) NOT NULL DEFAULT 'live',
131
132
            user_ip VARCHAR(100),
133
            first_name VARCHAR(100),
134
            last_name VARCHAR(100),
135
            `address` VARCHAR(100),
136
            city VARCHAR(100),
137
            `state` VARCHAR(100),
138
            country VARCHAR(100),
139
            zip VARCHAR(100),
140
            adddress_confirmed INT(10),
141
142
            gateway VARCHAR(100),
143
            transaction_id VARCHAR(100),
144
            currency VARCHAR(10),
145
            subtotal FLOAT NOT NULL DEFAULT 0,
146
            tax FLOAT NOT NULL DEFAULT 0,
147
            fees_total FLOAT NOT NULL DEFAULT 0,
148
            total FLOAT NOT NULL DEFAULT 0,
149
            discount FLOAT NOT NULL DEFAULT 0,
150
            discount_code VARCHAR(100),
151
            disable_taxes INT(2) NOT NULL DEFAULT 0,
152
            due_date DATETIME,
153
            completed_date DATETIME,
154
            company VARCHAR(100),
155
            vat_number VARCHAR(100),
156
            vat_rate VARCHAR(100),
157
158
            custom_meta TEXT,
159
            PRIMARY KEY  (post_id),
160
            KEY number (number),
161
            KEY `key` ( `key` )
162
            ) CHARACTER SET utf8 COLLATE utf8_general_ci;";
163
164
    dbDelta( $sql );
165
166
    // Create invoice items table.
167
    $table = $wpdb->prefix . 'getpaid_invoice_items';
168
    $sql   = "CREATE TABLE $table (
169
            ID BIGINT(20) NOT NULL AUTO_INCREMENT,
170
            post_id BIGINT(20) NOT NULL,
171
172
            item_id BIGINT(20) NOT NULL,
173
            item_name TEXT NOT NULL,
174
            item_description TEXT NOT NULL,
175
176
            vat_rate FLOAT NOT NULL DEFAULT 0,
177
            vat_class VARCHAR(100),
178
            tax FLOAT NOT NULL DEFAULT 0,
179
            item_price FLOAT NOT NULL DEFAULT 0,
180
            custom_price FLOAT NOT NULL DEFAULT 0,
181
            quantity INT(20) NOT NULL DEFAULT 1,
182
            discount FLOAT NOT NULL DEFAULT 0,
183
            subtotal FLOAT NOT NULL DEFAULT 0,
184
            price FLOAT NOT NULL DEFAULT 0,
185
            meta TEXT,
186
            fees TEXT,
187
            PRIMARY KEY  (ID),
188
            KEY item_id (item_id),
189
            KEY post_id ( post_id )
190
            ) CHARACTER SET utf8 COLLATE utf8_general_ci;";
191
192
    dbDelta( $sql );
193
}
194
195
/**
196
 * Copies data from meta tables to our custom tables.
197
 */
198
function wpinv_convert_old_invoices() {
199
    global $wpdb;
200
201
    $invoices = array_unique(
202
        get_posts(
203
            array(
204
                'post_type'      => array( 'wpi_invoice', 'wpi_quote' ),
205
                'posts_per_page' => -1,
206
                'fields'         => 'ids',
207
                'post_status'    => array_keys( wpinv_get_invoice_statuses( true ) ),
208
            )
209
        )
210
    );
211
    $invoices_table = $wpdb->prefix . 'getpaid_invoices';
212
    $invoice_items_table = $wpdb->prefix . 'getpaid_invoice_items';
213
214
    if ( ! class_exists( 'WPInv_Legacy_Invoice' ) ) {
215
        require_once( WPINV_PLUGIN_DIR . 'includes/class-wpinv-legacy-invoice.php' );
216
    }
217
218
    $invoice_rows = array();
219
    foreach ( $invoices as $invoice ) {
220
221
        $invoice = new WPInv_Legacy_Invoice( $invoice );
222
        $fields = array (
223
            'post_id'        => $invoice->ID,
224
            'number'         => $invoice->get_number(),
225
            'key'            => $invoice->get_key(),
226
            'type'           => str_replace( 'wpi_', '', $invoice->post_type ),
227
            'mode'           => $invoice->mode,
228
            'user_ip'        => $invoice->get_ip(),
229
            'first_name'     => $invoice->get_first_name(),
230
            'last_name'      => $invoice->get_last_name(),
231
            'address'        => $invoice->get_address(),
232
            'city'           => $invoice->city,
233
            'state'          => $invoice->state,
234
            'country'        => $invoice->country,
235
            'zip'            => $invoice->zip,
236
            'adddress_confirmed' => (int) $invoice->adddress_confirmed,
237
            'gateway'        => $invoice->get_gateway(),
238
            'transaction_id' => $invoice->get_transaction_id(),
239
            'currency'       => $invoice->get_currency(),
240
            'subtotal'       => $invoice->get_subtotal(),
241
            'tax'            => $invoice->get_tax(),
242
            'fees_total'     => $invoice->get_fees_total(),
243
            'total'          => $invoice->get_total(),
244
            'discount'       => $invoice->get_discount(),
245
            'discount_code'  => $invoice->get_discount_code(),
246
            'disable_taxes'  => $invoice->disable_taxes,
247
            'due_date'       => $invoice->get_due_date(),
248
            'completed_date' => $invoice->get_completed_date(),
249
            'company'        => $invoice->company,
250
            'vat_number'     => $invoice->vat_number,
251
            'vat_rate'       => $invoice->vat_rate,
252
            'custom_meta'    => $invoice->payment_meta
253
        );
254
255
        foreach ( $fields as $key => $val ) {
256
            if ( is_null( $val ) ) {
257
                $val = '';
258
            }
259
            $val = maybe_serialize( $val );
260
            $fields[ $key ] = $wpdb->prepare( '%s', $val );
261
        }
262
263
        $fields = implode( ', ', $fields );
264
        $invoice_rows[] = "($fields)";
265
266
        $item_rows    = array();
267
        $item_columns = array();
268
        foreach ( $invoice->get_cart_details() as $details ) {
269
            $fields = array(
270
                'post_id'          => $invoice->ID,
271
                'item_id'          => $details['id'],
272
                'item_name'        => $details['name'],
273
                'item_description' => empty( $details['meta']['description'] ) ? '' : $details['meta']['description'],
274
                'vat_rate'         => $details['vat_rate'],
275
                'vat_class'        => empty( $details['vat_class'] ) ? '_standard' : $details['vat_class'],
276
                'tax'              => $details['tax'],
277
                'item_price'       => $details['item_price'],
278
                'custom_price'     => $details['custom_price'],
279
                'quantity'         => $details['quantity'],
280
                'discount'         => $details['discount'],
281
                'subtotal'         => $details['subtotal'],
282
                'price'            => $details['price'],
283
                'meta'             => $details['meta'],
284
                'fees'             => $details['fees'],
285
            );
286
287
            $item_columns = array_keys ( $fields );
288
289
            foreach ( $fields as $key => $val ) {
290
                if ( is_null( $val ) ) {
291
                    $val = '';
292
                }
293
                $val = maybe_serialize( $val );
294
                $fields[ $key ] = $wpdb->prepare( '%s', $val );
295
            }
296
297
            $fields = implode( ', ', $fields );
298
            $item_rows[] = "($fields)";
299
        }
300
301
        $item_rows    = implode( ', ', $item_rows );
302
        $item_columns = implode( ', ', $item_columns );
303
        $wpdb->query( "INSERT INTO $invoice_items_table ($item_columns) VALUES $item_rows" );
304
    }
305
306
    $invoice_rows = implode( ', ', $invoice_rows );
307
    $wpdb->query( "INSERT INTO $invoices_table VALUES $invoice_rows" );
308
309
}
310