Completed
Push — master ( 2ef6f7...6fcb0f )
by frank
01:45
created

autoptimizeCriticalCSSBase::load_requires()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 16

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 4
nc 4
nop 0
dl 0
loc 16
rs 9.7333
c 0
b 0
f 0
1
<?php
2
/**
3
 * Critical CSS base file (initializes all ccss files).
4
 */
5
6
if ( ! defined( 'ABSPATH' ) ) {
7
    exit;
8
}
9
10
class autoptimizeCriticalCSSBase {
11
    /**
12
     * Main plugin filepath.
13
     * Used for activation/deactivation/uninstall hooks.
14
     *
15
     * @var string
16
     */
17
    protected $filepath = null;
18
19
    public function __construct()
20
    {
21
        // define constant, but only once.
22
        if ( ! defined( 'AO_CCSS_DIR' ) ) {
23
            // Define plugin version.
24
            define( 'AO_CCSS_VER', 'AO_' . AUTOPTIMIZE_PLUGIN_VERSION );
25
26
            // Define a constant with the directory to store critical CSS in.
27
            if ( is_multisite() ) {
28
                $blog_id = get_current_blog_id();
29
                define( 'AO_CCSS_DIR', WP_CONTENT_DIR . '/uploads/ao_ccss/' . $blog_id . '/' );
30
            } else {
31
                define( 'AO_CCSS_DIR', WP_CONTENT_DIR . '/uploads/ao_ccss/' );
32
            }
33
34
            // Define support files locations.
35
            define( 'AO_CCSS_LOCK', AO_CCSS_DIR . 'queue.lock' );
36
            define( 'AO_CCSS_LOG', AO_CCSS_DIR . 'queuelog.html' );
37
            define( 'AO_CCSS_DEBUG', AO_CCSS_DIR . 'queue.json' );
38
39
            // Define constants for criticalcss.com base path and API endpoints.
40
            // fixme: AO_CCSS_URL should be read from the autoptimize availability json stored as option.
41
            define( 'AO_CCSS_URL', 'https://criticalcss.com' );
42
            define( 'AO_CCSS_API', AO_CCSS_URL . '/api/premium/' );
43
        }
44
45
        $this->filepath = __FILE__;
46
47
        $this->setup();
48
        $this->load_requires();
49
    }
50
51
    public function setup()
52
    {
53
        // get all options.
54
        $all_options = $this->fetch_options();
55
        foreach ( $all_options as $option => $value ) {
56
            ${$option} = $value;
57
        }
58
59
        // make sure the 10 minutes cron schedule is added.
60
        add_filter( 'cron_schedules', array( $this, 'ao_ccss_interval' ) );
61
62
        // check if we need to upgrade.
63
        $this->check_upgrade();
64
65
        // make sure ao_ccss_queue is scheduled OK if an API key is set.
66 View Code Duplication
        if ( isset( $ao_ccss_key ) && ! empty( $ao_ccss_key ) && ! wp_next_scheduled( 'ao_ccss_queue' ) ) {
0 ignored issues
show
Bug introduced by
The variable $ao_ccss_key seems to never exist, and therefore isset should always return false. Did you maybe rename this variable?

This check looks for calls to isset(...) or empty() on variables that are yet undefined. These calls will always produce the same result and can be removed.

This is most likely caused by the renaming of a variable or the removal of a function/method parameter.

Loading history...
Duplication introduced by
This code seems to be duplicated across 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...
67
            wp_schedule_event( time(), apply_filters( 'ao_ccss_queue_schedule', 'ao_ccss' ), 'ao_ccss_queue' );
68
        }
69
    }
70
71
    public function load_requires() {
72
        // Required libs, core is always needed.
73
        $criticalcss_core = new autoptimizeCriticalCSSCore();
0 ignored issues
show
Unused Code introduced by
$criticalcss_core 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...
74
75
        if ( defined( 'DOING_CRON' ) || is_admin() ) {
76
            // TODO: also include if overridden somehow to force queue processing to be executed?
77
            $criticalcss_cron = new autoptimizeCriticalCSSCron();
0 ignored issues
show
Unused Code introduced by
$criticalcss_cron 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...
78
        }
79
80
        if ( is_admin() ) {
81
            $criticalcss_settings = new autoptimizeCriticalCSSSettings();
0 ignored issues
show
Unused Code introduced by
$criticalcss_settings 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...
82
        } else {
83
            // enqueuing only done when not wp-admin.
84
            $criticalcss_enqueue = new autoptimizeCriticalCSSEnqueue();
0 ignored issues
show
Unused Code introduced by
$criticalcss_enqueue 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...
85
        }
86
    }
87
88
    public static function fetch_options() {
89
        // Get options.
90
        $autoptimize_ccss_options['ao_css_defer']          = get_option( 'autoptimize_css_defer' );
0 ignored issues
show
Coding Style Comprehensibility introduced by
$autoptimize_ccss_options was never initialized. Although not strictly required by PHP, it is generally a good practice to add $autoptimize_ccss_options = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
91
        $autoptimize_ccss_options['ao_css_defer_inline']   = get_option( 'autoptimize_css_defer_inline' );
92
        $autoptimize_ccss_options['ao_ccss_rules_raw']     = get_option( 'autoptimize_ccss_rules', false );
93
        $autoptimize_ccss_options['ao_ccss_additional']    = get_option( 'autoptimize_ccss_additional' );
94
        $autoptimize_ccss_options['ao_ccss_queue_raw']     = get_option( 'autoptimize_ccss_queue', false );
95
        $autoptimize_ccss_options['ao_ccss_viewport']      = get_option( 'autoptimize_ccss_viewport', false );
96
        $autoptimize_ccss_options['ao_ccss_finclude']      = get_option( 'autoptimize_ccss_finclude', false );
97
        $autoptimize_ccss_options['ao_ccss_rlimit']        = get_option( 'autoptimize_ccss_rlimit', '5' );
98
        $autoptimize_ccss_options['ao_ccss_noptimize']     = get_option( 'autoptimize_ccss_noptimize', false );
99
        $autoptimize_ccss_options['ao_ccss_debug']         = get_option( 'autoptimize_ccss_debug', false );
100
        $autoptimize_ccss_options['ao_ccss_key']           = get_option( 'autoptimize_ccss_key' );
101
        $autoptimize_ccss_options['ao_ccss_keyst']         = get_option( 'autoptimize_ccss_keyst' );
102
        $autoptimize_ccss_options['ao_ccss_loggedin']      = get_option( 'autoptimize_ccss_loggedin', '1' );
103
        $autoptimize_ccss_options['ao_ccss_forcepath']     = get_option( 'autoptimize_ccss_forcepath', '1' );
104
        $autoptimize_ccss_options['ao_ccss_servicestatus'] = get_option( 'autoptimize_service_availablity' );
105
        $autoptimize_ccss_options['ao_ccss_deferjquery']   = get_option( 'autoptimize_ccss_deferjquery', false );
106
        $autoptimize_ccss_options['ao_ccss_domain']        = get_option( 'autoptimize_ccss_domain' );
107
108
        if ( strpos( $autoptimize_ccss_options['ao_ccss_domain'], 'http' ) === false && strpos( $autoptimize_ccss_options['ao_ccss_domain'], 'uggc' ) === 0 ) {
109
            $autoptimize_ccss_options['ao_ccss_domain'] = str_rot13( $autoptimize_ccss_options['ao_ccss_domain'] );
110
        } elseif ( strpos( $autoptimize_ccss_options['ao_ccss_domain'], 'http' ) !== false ) {
111
            // not rot13'ed yet, do so now (goal; avoid migration plugins change the bound domain).
112
            update_option( 'autoptimize_ccss_domain', str_rot13( $autoptimize_ccss_options['ao_ccss_domain'] ) );
113
        }
114
115
        // Setup the rules array.
116
        if ( empty( $autoptimize_ccss_options['ao_ccss_rules_raw'] ) ) {
117
            $autoptimize_ccss_options['ao_ccss_rules']['paths'] = array();
118
            $autoptimize_ccss_options['ao_ccss_rules']['types'] = array();
119
        } else {
120
            $autoptimize_ccss_options['ao_ccss_rules'] = json_decode( $autoptimize_ccss_options['ao_ccss_rules_raw'], true );
121
        }
122
123
        // Setup the queue array.
124
        if ( empty( $autoptimize_ccss_options['ao_ccss_queue_raw'] ) ) {
125
            $autoptimize_ccss_options['ao_ccss_queue'] = array();
126
        } else {
127
            $autoptimize_ccss_options['ao_ccss_queue'] = json_decode( $autoptimize_ccss_options['ao_ccss_queue_raw'], true );
128
        }
129
130
        // Override API key if constant is defined.
131
        if ( defined( 'AUTOPTIMIZE_CRITICALCSS_API_KEY' ) ) {
132
            $autoptimize_ccss_options['ao_ccss_key'] = AUTOPTIMIZE_CRITICALCSS_API_KEY;
133
        }
134
135
        return $autoptimize_ccss_options;
136
    }
137
138
    public function on_upgrade() {
139
        global $ao_ccss_key;
140
141
        // Create the cache directory if it doesn't exist already.
142
        if ( ! file_exists( AO_CCSS_DIR ) ) {
143
            mkdir( AO_CCSS_DIR, 0755, true );
144
        }
145
146
        // Create a scheduled event for the queue.
147 View Code Duplication
        if ( isset( $ao_ccss_key ) && ! empty( $ao_ccss_key ) && ! wp_next_scheduled( 'ao_ccss_queue' ) ) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
148
            wp_schedule_event( time(), apply_filters( 'ao_ccss_queue_schedule', 'ao_ccss' ), 'ao_ccss_queue' );
149
        }
150
151
        // Create a scheduled event for log maintenance.
152
        if ( isset( $ao_ccss_key ) && ! empty( $ao_ccss_key ) && ! wp_next_scheduled( 'ao_ccss_maintenance' ) ) {
153
            wp_schedule_event( time(), 'twicedaily', 'ao_ccss_maintenance' );
154
        }
155
    }
156
157
    public function check_upgrade() {
158
        $db_version = get_option( 'autoptimize_ccss_version', '' );
159
        if ( AO_CCSS_VER !== $db_version ) {
160
            // check schedules & re-schedule if needed.
161
            $this->on_upgrade();
162
            // and update db_version.
163
            update_option( 'autoptimize_ccss_version', AO_CCSS_VER );
164
        }
165
    }
166
167
    public function ao_ccss_interval( $schedules ) {
168
        // Let interval be configurable.
169
        if ( ! defined( 'AO_CCSS_DEBUG_INTERVAL' ) ) {
170
            $intsec = 600;
171
        } else {
172
            $intsec = AO_CCSS_DEBUG_INTERVAL;
173
            if ( $intsec >= 120 ) {
174
                $inttxt = $intsec / 60 . ' minutes';
175
            } else {
176
                $inttxt = $intsec . ' second(s)';
177
            }
178
            autoptimizeCriticalCSSCore::ao_ccss_log( 'Using custom WP-Cron interval of ' . $inttxt, 3 );
179
        }
180
181
        // Attach interval to schedule.
182
        $schedules['ao_ccss'] = array(
183
            'interval' => $intsec,
184
            'display'  => __( 'Autoptimize CriticalCSS' ),
185
        );
186
        return $schedules;
187
    }
188
}
189