Passed
Pull Request — master (#81)
by Kiran
06:28
created

wpinv-upgrade-functions.php ➔ wpinv_v005_upgrades()   B

Complexity

Conditions 5
Paths 4

Size

Total Lines 30
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 5
eloc 16
nc 4
nop 0
dl 0
loc 30
rs 8.439
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
    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
    update_option( 'wpinv_version', WPINV_VERSION );
25
}
26
add_action( 'admin_init', 'wpinv_automatic_upgrade' );
27
28
function wpinv_v005_upgrades() {
29
    global $wpdb;
30
    
31
    // Invoices status
32
    $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' )" );
33
    if ( !empty( $results ) ) {
34
        $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' )" );
35
        
36
        // Clean post cache
37
        foreach ( $results as $row ) {
38
            clean_post_cache( $row->ID );
39
        }
40
    }
41
    
42
    // Item meta key changes
43
    $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' )";
44
    $results = $wpdb->get_results( $query );
45
    
46
    if ( !empty( $results ) ) {
47
        $wpdb->query( "UPDATE " . $wpdb->postmeta . " SET meta_key = '_wpinv_custom_id' WHERE meta_key IN( '_wpinv_item_id', '_wpinv_package_id', '_wpinv_post_id' )" );
48
        $wpdb->query( "UPDATE " . $wpdb->postmeta . " SET meta_key = '_wpinv_custom_name' WHERE meta_key = '_wpinv_cpt_name'" );
49
        $wpdb->query( "UPDATE " . $wpdb->postmeta . " SET meta_key = '_wpinv_custom_singular_name' WHERE meta_key = '_wpinv_cpt_singular_name'" );
50
        
51
        foreach ( $results as $row ) {
52
            clean_post_cache( $row->post_id );
53
        }
54
    }
55
56
    wpinv_add_admin_caps();
57
}