Completed
Push — master ( 964b0c...cd5cb6 )
by frank
01:40
created
classes/autoptimizeCriticalCSSCore.php 1 patch
Spacing   +151 added lines, -151 removed lines patch added patch discarded remove patch
@@ -4,7 +4,7 @@  discard block
 block discarded – undo
4 4
  * gets called by AO core, checks the rules and if a matching rule is found returns the associated CCSS.
5 5
  */
6 6
 
7
-if ( ! defined( 'ABSPATH' ) ) {
7
+if (!defined('ABSPATH')) {
8 8
     exit;
9 9
 }
10 10
 
@@ -13,7 +13,7 @@  discard block
 block discarded – undo
13 13
     {
14 14
         // fetch all options at once and populate them individually explicitely as globals.
15 15
         $all_options = autoptimizeCriticalCSSBase::fetch_options();
16
-        foreach ( $all_options as $_option => $_value ) {
16
+        foreach ($all_options as $_option => $_value) {
17 17
             global ${$_option};
18 18
             ${$_option} = $_value;
19 19
         }
@@ -28,28 +28,28 @@  discard block
 block discarded – undo
28 28
         global $ao_ccss_unloadccss;
29 29
 
30 30
         // add all filters to do CCSS if key present.
31
-        if ( $ao_css_defer && isset( $ao_ccss_key ) && ! empty( $ao_ccss_key ) ) {
31
+        if ($ao_css_defer && isset($ao_ccss_key) && !empty($ao_ccss_key)) {
32 32
             // Set AO behavior: disable minification to avoid double minifying and caching.
33
-            add_filter( 'autoptimize_filter_css_critcss_minify', '__return_false' );
34
-            add_filter( 'autoptimize_filter_css_defer_inline', array( $this, 'ao_ccss_frontend' ), 10, 1 );
33
+            add_filter('autoptimize_filter_css_critcss_minify', '__return_false');
34
+            add_filter('autoptimize_filter_css_defer_inline', array($this, 'ao_ccss_frontend'), 10, 1);
35 35
 
36 36
             // Add the action to enqueue jobs for CriticalCSS cron.
37
-            add_action( 'autoptimize_action_css_hash', array( 'autoptimizeCriticalCSSEnqueue', 'ao_ccss_enqueue' ), 10, 1 );
37
+            add_action('autoptimize_action_css_hash', array('autoptimizeCriticalCSSEnqueue', 'ao_ccss_enqueue'), 10, 1);
38 38
 
39 39
             // conditionally add the filter to defer jquery and others.
40
-            if ( $ao_ccss_deferjquery ) {
41
-                add_filter( 'autoptimize_html_after_minify', array( $this, 'ao_ccss_defer_jquery' ), 11, 1 );
40
+            if ($ao_ccss_deferjquery) {
41
+                add_filter('autoptimize_html_after_minify', array($this, 'ao_ccss_defer_jquery'), 11, 1);
42 42
             }
43 43
 
44 44
             // conditionally add filter to unload the CCSS.
45
-            if ( $ao_ccss_unloadccss ) {
46
-                add_filter( 'autoptimize_html_after_minify', array( $this, 'ao_ccss_unloadccss' ), 12, 1 );
45
+            if ($ao_ccss_unloadccss) {
46
+                add_filter('autoptimize_html_after_minify', array($this, 'ao_ccss_unloadccss'), 12, 1);
47 47
             }
48 48
 
49 49
             // Order paths by length, as longest ones have greater priority in the rules.
50
-            if ( ! empty( $ao_ccss_rules['paths'] ) ) {
51
-                $keys = array_map( 'strlen', array_keys( $ao_ccss_rules['paths'] ) );
52
-                array_multisort( $keys, SORT_DESC, $ao_ccss_rules['paths'] );
50
+            if (!empty($ao_ccss_rules['paths'])) {
51
+                $keys = array_map('strlen', array_keys($ao_ccss_rules['paths']));
52
+                array_multisort($keys, SORT_DESC, $ao_ccss_rules['paths']);
53 53
             }
54 54
 
55 55
             // Add an array with default WordPress's conditional tags
@@ -58,14 +58,14 @@  discard block
 block discarded – undo
58 58
             $ao_ccss_types = $this->get_ao_ccss_core_types();
59 59
 
60 60
             // Extend conditional tags on plugin initalization.
61
-            add_action( apply_filters( 'autoptimize_filter_ccss_extend_types_hook', 'init' ), array( $this, 'ao_ccss_extend_types' ) );
61
+            add_action(apply_filters('autoptimize_filter_ccss_extend_types_hook', 'init'), array($this, 'ao_ccss_extend_types'));
62 62
 
63 63
             // When autoptimize cache is cleared, also clear transient cache for page templates.
64
-            add_action( 'autoptimize_action_cachepurged', array( 'autoptimizeCriticalCSSCore', 'ao_ccss_clear_page_tpl_cache' ), 10, 0 );
64
+            add_action('autoptimize_action_cachepurged', array('autoptimizeCriticalCSSCore', 'ao_ccss_clear_page_tpl_cache'), 10, 0);
65 65
         }
66 66
     }
67 67
 
68
-    public function ao_ccss_frontend( $inlined ) {
68
+    public function ao_ccss_frontend($inlined) {
69 69
         // Apply CriticalCSS to frontend pages
70 70
         // Attach types and settings arrays.
71 71
         global $ao_ccss_types;
@@ -77,20 +77,20 @@  discard block
 block discarded – undo
77 77
         $no_ccss = '';
78 78
 
79 79
         // Only if keystatus is OK and option to add CCSS for logged on users is on or user is not logged in.
80
-        if ( ( $ao_ccss_keyst && 2 == $ao_ccss_keyst ) && ( $ao_ccss_loggedin || ! is_user_logged_in() ) ) {
80
+        if (($ao_ccss_keyst && 2 == $ao_ccss_keyst) && ($ao_ccss_loggedin || !is_user_logged_in())) {
81 81
             // Check for a valid CriticalCSS based on path to return its contents.
82
-            $req_path = strtok( $_SERVER['REQUEST_URI'], '?' );
83
-            if ( ! empty( $ao_ccss_rules['paths'] ) ) {
84
-                foreach ( $ao_ccss_rules['paths'] as $path => $rule ) {
82
+            $req_path = strtok($_SERVER['REQUEST_URI'], '?');
83
+            if (!empty($ao_ccss_rules['paths'])) {
84
+                foreach ($ao_ccss_rules['paths'] as $path => $rule) {
85 85
                     // explicit match OR partial match if MANUAL rule.
86
-                    if ( $req_path == $path || urldecode( $req_path ) == $path || ( false == $rule['hash'] && false != $rule['file'] && strpos( $req_path, str_replace( site_url(), '', $path ) ) !== false ) ) {
87
-                        if ( file_exists( AO_CCSS_DIR . $rule['file'] ) ) {
88
-                            $_ccss_contents = file_get_contents( AO_CCSS_DIR . $rule['file'] );
89
-                            if ( 'none' != $_ccss_contents ) {
90
-                                if ( $ao_ccss_debug ) {
91
-                                    $_ccss_contents = '/* PATH: ' . $path . ' hash: ' . $rule['hash'] . ' file: ' . $rule['file'] . ' */ ' . $_ccss_contents;
86
+                    if ($req_path == $path || urldecode($req_path) == $path || (false == $rule['hash'] && false != $rule['file'] && strpos($req_path, str_replace(site_url(), '', $path)) !== false)) {
87
+                        if (file_exists(AO_CCSS_DIR.$rule['file'])) {
88
+                            $_ccss_contents = file_get_contents(AO_CCSS_DIR.$rule['file']);
89
+                            if ('none' != $_ccss_contents) {
90
+                                if ($ao_ccss_debug) {
91
+                                    $_ccss_contents = '/* PATH: '.$path.' hash: '.$rule['hash'].' file: '.$rule['file'].' */ '.$_ccss_contents;
92 92
                                 }
93
-                                return apply_filters( 'autoptimize_filter_ccss_core_ccss', $_ccss_contents . $ao_ccss_additional );
93
+                                return apply_filters('autoptimize_filter_ccss_core_ccss', $_ccss_contents.$ao_ccss_additional);
94 94
                             } else {
95 95
                                 $no_ccss = 'none';
96 96
                             }
@@ -100,55 +100,55 @@  discard block
 block discarded – undo
100 100
             }
101 101
 
102 102
             // Check for a valid CriticalCSS based on conditional tags to return its contents.
103
-            if ( ! empty( $ao_ccss_rules['types'] ) && 'none' !== $no_ccss ) {
103
+            if (!empty($ao_ccss_rules['types']) && 'none' !== $no_ccss) {
104 104
                 // order types-rules by the order of the original $ao_ccss_types array so as not to depend on the order in which rules were added.
105
-                $ao_ccss_rules['types'] = array_replace( array_intersect_key( array_flip( $ao_ccss_types ), $ao_ccss_rules['types'] ), $ao_ccss_rules['types'] );
105
+                $ao_ccss_rules['types'] = array_replace(array_intersect_key(array_flip($ao_ccss_types), $ao_ccss_rules['types']), $ao_ccss_rules['types']);
106 106
                 $is_front_page          = is_front_page();
107 107
 
108
-                foreach ( $ao_ccss_rules['types'] as $type => $rule ) {
109
-                    if ( in_array( $type, $ao_ccss_types ) && file_exists( AO_CCSS_DIR . $rule['file'] ) ) {
110
-                        $_ccss_contents = file_get_contents( AO_CCSS_DIR . $rule['file'] );
111
-                        if ( $is_front_page && 'is_front_page' == $type ) {
112
-                            if ( 'none' != $_ccss_contents ) {
113
-                                if ( $ao_ccss_debug ) {
114
-                                    $_ccss_contents = '/* TYPES: ' . $type . ' hash: ' . $rule['hash'] . ' file: ' . $rule['file'] . ' */ ' . $_ccss_contents;
108
+                foreach ($ao_ccss_rules['types'] as $type => $rule) {
109
+                    if (in_array($type, $ao_ccss_types) && file_exists(AO_CCSS_DIR.$rule['file'])) {
110
+                        $_ccss_contents = file_get_contents(AO_CCSS_DIR.$rule['file']);
111
+                        if ($is_front_page && 'is_front_page' == $type) {
112
+                            if ('none' != $_ccss_contents) {
113
+                                if ($ao_ccss_debug) {
114
+                                    $_ccss_contents = '/* TYPES: '.$type.' hash: '.$rule['hash'].' file: '.$rule['file'].' */ '.$_ccss_contents;
115 115
                                 }
116
-                                return apply_filters( 'autoptimize_filter_ccss_core_ccss', $_ccss_contents . $ao_ccss_additional );
116
+                                return apply_filters('autoptimize_filter_ccss_core_ccss', $_ccss_contents.$ao_ccss_additional);
117 117
                             } else {
118 118
                                 $no_ccss = 'none';
119 119
                             }
120
-                        } elseif ( strpos( $type, 'custom_post_' ) === 0 && ! $is_front_page ) {
121
-                            if ( get_post_type( get_the_ID() ) === substr( $type, 12 ) ) {
122
-                                if ( 'none' != $_ccss_contents ) {
123
-                                    if ( $ao_ccss_debug ) {
124
-                                        $_ccss_contents = '/* TYPES: ' . $type . ' hash: ' . $rule['hash'] . ' file: ' . $rule['file'] . ' */ ' . $_ccss_contents;
120
+                        } elseif (strpos($type, 'custom_post_') === 0 && !$is_front_page) {
121
+                            if (get_post_type(get_the_ID()) === substr($type, 12)) {
122
+                                if ('none' != $_ccss_contents) {
123
+                                    if ($ao_ccss_debug) {
124
+                                        $_ccss_contents = '/* TYPES: '.$type.' hash: '.$rule['hash'].' file: '.$rule['file'].' */ '.$_ccss_contents;
125 125
                                     }
126
-                                    return apply_filters( 'autoptimize_filter_ccss_core_ccss', $_ccss_contents . $ao_ccss_additional );
126
+                                    return apply_filters('autoptimize_filter_ccss_core_ccss', $_ccss_contents.$ao_ccss_additional);
127 127
                                 } else {
128 128
                                     $no_ccss = 'none';
129 129
                                 }
130 130
                             }
131
-                        } elseif ( 0 === strpos( $type, 'template_' ) && ! $is_front_page ) {
132
-                            if ( is_page_template( substr( $type, 9 ) ) ) {
133
-                                if ( 'none' != $_ccss_contents ) {
134
-                                    if ( $ao_ccss_debug ) {
135
-                                        $_ccss_contents = '/* TYPES: ' . $type . ' hash: ' . $rule['hash'] . ' file: ' . $rule['file'] . ' */ ' . $_ccss_contents;
131
+                        } elseif (0 === strpos($type, 'template_') && !$is_front_page) {
132
+                            if (is_page_template(substr($type, 9))) {
133
+                                if ('none' != $_ccss_contents) {
134
+                                    if ($ao_ccss_debug) {
135
+                                        $_ccss_contents = '/* TYPES: '.$type.' hash: '.$rule['hash'].' file: '.$rule['file'].' */ '.$_ccss_contents;
136 136
                                     }
137
-                                    return apply_filters( 'autoptimize_filter_ccss_core_ccss', $_ccss_contents . $ao_ccss_additional );
137
+                                    return apply_filters('autoptimize_filter_ccss_core_ccss', $_ccss_contents.$ao_ccss_additional);
138 138
                                 } else {
139 139
                                     $no_ccss = 'none';
140 140
                                 }
141 141
                             }
142
-                        } elseif ( ! $is_front_page ) {
142
+                        } elseif (!$is_front_page) {
143 143
                             // all "normal" conditional tags, core + woo + buddypress + edd + bbpress
144 144
                             // but we have to remove the prefix for the non-core ones for them to function.
145
-                            $type = str_replace( array( 'woo_', 'bp_', 'bbp_', 'edd_' ), '', $type );
146
-                            if ( function_exists( $type ) && call_user_func( $type ) ) {
147
-                                if ( 'none' != $_ccss_contents ) {
148
-                                    if ( $ao_ccss_debug ) {
149
-                                        $_ccss_contents = '/* TYPES: ' . $type . ' hash: ' . $rule['hash'] . ' file: ' . $rule['file'] . ' */ ' . $_ccss_contents;
145
+                            $type = str_replace(array('woo_', 'bp_', 'bbp_', 'edd_'), '', $type);
146
+                            if (function_exists($type) && call_user_func($type)) {
147
+                                if ('none' != $_ccss_contents) {
148
+                                    if ($ao_ccss_debug) {
149
+                                        $_ccss_contents = '/* TYPES: '.$type.' hash: '.$rule['hash'].' file: '.$rule['file'].' */ '.$_ccss_contents;
150 150
                                     }
151
-                                    return apply_filters( 'autoptimize_filter_ccss_core_ccss', $_ccss_contents . $ao_ccss_additional );
151
+                                    return apply_filters('autoptimize_filter_ccss_core_ccss', $_ccss_contents.$ao_ccss_additional);
152 152
                                 } else {
153 153
                                     $no_ccss = 'none';
154 154
                                 }
@@ -161,45 +161,45 @@  discard block
 block discarded – undo
161 161
 
162 162
         // Finally, inline the default CriticalCSS if any or else the entire CSS for the page
163 163
         // This also applies to logged in users if the option to add CCSS for logged in users has been disabled.
164
-        if ( ! empty( $inlined ) && 'none' !== $no_ccss ) {
165
-            return apply_filters( 'autoptimize_filter_ccss_core_ccss', $inlined . $ao_ccss_additional );
164
+        if (!empty($inlined) && 'none' !== $no_ccss) {
165
+            return apply_filters('autoptimize_filter_ccss_core_ccss', $inlined.$ao_ccss_additional);
166 166
         } else {
167
-            add_filter( 'autoptimize_filter_css_inline', '__return_true' );
167
+            add_filter('autoptimize_filter_css_inline', '__return_true');
168 168
             return;
169 169
         }
170 170
     }
171 171
 
172
-    public function ao_ccss_defer_jquery( $in ) {
172
+    public function ao_ccss_defer_jquery($in) {
173 173
         global $ao_ccss_loggedin;
174 174
         // defer all linked and inline JS.
175
-        if ( ( ! is_user_logged_in() || $ao_ccss_loggedin ) && preg_match_all( '#<script.*>(.*)</script>#Usmi', $in, $matches, PREG_SET_ORDER ) ) {
176
-            foreach ( $matches as $match ) {
177
-                if ( str_replace( apply_filters( 'autoptimize_filter_ccss_core_defer_exclude', array( 'data-noptimize="1"', 'data-cfasync="false"', 'data-pagespeed-no-defer' ) ), '', $match[0] ) !== $match[0] ) {
175
+        if ((!is_user_logged_in() || $ao_ccss_loggedin) && preg_match_all('#<script.*>(.*)</script>#Usmi', $in, $matches, PREG_SET_ORDER)) {
176
+            foreach ($matches as $match) {
177
+                if (str_replace(apply_filters('autoptimize_filter_ccss_core_defer_exclude', array('data-noptimize="1"', 'data-cfasync="false"', 'data-pagespeed-no-defer')), '', $match[0]) !== $match[0]) {
178 178
                     // do not touch JS with noptimize/ cfasync/ pagespeed-no-defer flags.
179 179
                     continue;
180
-                } elseif ( '' !== $match[1] && ( ! preg_match( '/<script.* type\s?=.*>/', $match[0] ) || preg_match( '/type\s*=\s*[\'"]?(?:text|application)\/(?:javascript|ecmascript)[\'"]?/i', $match[0] ) ) ) {
180
+                } elseif ('' !== $match[1] && (!preg_match('/<script.* type\s?=.*>/', $match[0]) || preg_match('/type\s*=\s*[\'"]?(?:text|application)\/(?:javascript|ecmascript)[\'"]?/i', $match[0]))) {
181 181
                     // base64-encode and defer all inline JS.
182
-                    $base64_js = '<script defer src="data:text/javascript;base64,' . base64_encode( $match[1] ) . '"></script>';
183
-                    $in        = str_replace( $match[0], $base64_js, $in );
184
-                } elseif ( str_replace( array( ' defer', ' async' ), '', $match[0] ) === $match[0] ) {
182
+                    $base64_js = '<script defer src="data:text/javascript;base64,'.base64_encode($match[1]).'"></script>';
183
+                    $in        = str_replace($match[0], $base64_js, $in);
184
+                } elseif (str_replace(array(' defer', ' async'), '', $match[0]) === $match[0]) {
185 185
                     // and defer linked JS unless already deferred or asynced.
186
-                    $new_match = str_replace( '<script ', '<script defer ', $match[0] );
187
-                    $in        = str_replace( $match[0], $new_match, $in );
186
+                    $new_match = str_replace('<script ', '<script defer ', $match[0]);
187
+                    $in        = str_replace($match[0], $new_match, $in);
188 188
                 }
189 189
             }
190 190
         }
191 191
         return $in;
192 192
     }
193 193
 
194
-    public function ao_ccss_unloadccss( $html_in ) {
194
+    public function ao_ccss_unloadccss($html_in) {
195 195
         // set media attrib of inline CCSS to none at onLoad to avoid it impacting full CSS (rarely needed).
196
-        $_unloadccss_js = apply_filters( 'autoptimize_filter_ccss_core_unloadccss_js', '<script>window.addEventListener("load", function(event) {document.getElementById("aoatfcss").media="none";})</script>' );
196
+        $_unloadccss_js = apply_filters('autoptimize_filter_ccss_core_unloadccss_js', '<script>window.addEventListener("load", function(event) {document.getElementById("aoatfcss").media="none";})</script>');
197 197
 
198
-        if ( false !== strpos( $html_in, $_unloadccss_js . '</body>' ) ) {
198
+        if (false !== strpos($html_in, $_unloadccss_js.'</body>')) {
199 199
             return $html_in;
200 200
         }
201 201
 
202
-        return str_replace( '</body>', $_unloadccss_js . '</body>', $html_in );
202
+        return str_replace('</body>', $_unloadccss_js.'</body>', $html_in);
203 203
     }
204 204
 
205 205
     public function ao_ccss_extend_types() {
@@ -208,9 +208,9 @@  discard block
 block discarded – undo
208 208
         global $ao_ccss_types;
209 209
 
210 210
         // in some cases $ao_ccss_types is empty and/or not an array, this should work around that problem.
211
-        if ( empty( $ao_ccss_types ) || ! is_array( $ao_ccss_types ) ) {
211
+        if (empty($ao_ccss_types) || !is_array($ao_ccss_types)) {
212 212
             $ao_ccss_types = get_ao_ccss_core_types();
213
-            autoptimizeCriticalCSSCore::ao_ccss_log( 'Empty types array in extend, refetching array with core conditionals.', 3 );
213
+            autoptimizeCriticalCSSCore::ao_ccss_log('Empty types array in extend, refetching array with core conditionals.', 3);
214 214
         }
215 215
 
216 216
         // Custom Post Types.
@@ -222,23 +222,23 @@  discard block
 block discarded – undo
222 222
             'names',
223 223
             'and'
224 224
         );
225
-        foreach ( $cpts as $cpt ) {
226
-            array_unshift( $ao_ccss_types, 'custom_post_' . $cpt );
225
+        foreach ($cpts as $cpt) {
226
+            array_unshift($ao_ccss_types, 'custom_post_'.$cpt);
227 227
         }
228 228
 
229 229
         // Templates.
230 230
         // Transient cache to avoid frequent disk reads.
231
-        $templates = get_transient( 'autoptimize_ccss_page_templates' );
232
-        if ( ! $templates ) {
231
+        $templates = get_transient('autoptimize_ccss_page_templates');
232
+        if (!$templates) {
233 233
             $templates = wp_get_theme()->get_page_templates();
234
-            set_transient( 'autoptimize_ccss_page_templates', $templates, HOUR_IN_SECONDS );
234
+            set_transient('autoptimize_ccss_page_templates', $templates, HOUR_IN_SECONDS);
235 235
         }
236
-        foreach ( $templates as $tplfile => $tplname ) {
237
-            array_unshift( $ao_ccss_types, 'template_' . $tplfile );
236
+        foreach ($templates as $tplfile => $tplname) {
237
+            array_unshift($ao_ccss_types, 'template_'.$tplfile);
238 238
         }
239 239
 
240 240
         // bbPress tags.
241
-        if ( function_exists( 'is_bbpress' ) ) {
241
+        if (function_exists('is_bbpress')) {
242 242
             $ao_ccss_types = array_merge(
243 243
                 array(
244 244
                     'bbp_is_bbpress',
@@ -270,7 +270,7 @@  discard block
 block discarded – undo
270 270
         }
271 271
 
272 272
         // BuddyPress tags.
273
-        if ( function_exists( 'is_buddypress' ) ) {
273
+        if (function_exists('is_buddypress')) {
274 274
             $ao_ccss_types = array_merge(
275 275
                 array(
276 276
                     'bp_is_activation_page',
@@ -312,7 +312,7 @@  discard block
 block discarded – undo
312 312
         }
313 313
 
314 314
         // Easy Digital Downloads (EDD) tags.
315
-        if ( function_exists( 'edd_is_checkout' ) ) {
315
+        if (function_exists('edd_is_checkout')) {
316 316
             $ao_ccss_types = array_merge(
317 317
                 array(
318 318
                     'edd_is_checkout',
@@ -324,7 +324,7 @@  discard block
 block discarded – undo
324 324
         }
325 325
 
326 326
         // WooCommerce tags.
327
-        if ( class_exists( 'WooCommerce' ) ) {
327
+        if (class_exists('WooCommerce')) {
328 328
             $ao_ccss_types = array_merge(
329 329
                 array(
330 330
                     'woo_is_account_page',
@@ -343,7 +343,7 @@  discard block
 block discarded – undo
343 343
 
344 344
     public function get_ao_ccss_core_types() {
345 345
         global $ao_ccss_types;
346
-        if ( empty( $ao_ccss_types ) || ! is_array( $ao_ccss_types ) ) {
346
+        if (empty($ao_ccss_types) || !is_array($ao_ccss_types)) {
347 347
             return array(
348 348
                 'is_404',
349 349
                 'is_archive',
@@ -364,7 +364,7 @@  discard block
 block discarded – undo
364 364
         }
365 365
     }
366 366
 
367
-    public static function ao_ccss_key_status( $render ) {
367
+    public static function ao_ccss_key_status($render) {
368 368
         // Provide key status
369 369
         // Get key and key status.
370 370
         global $ao_ccss_key;
@@ -377,55 +377,55 @@  discard block
 block discarded – undo
377 377
         $key_return = array();
378 378
         $status     = false;
379 379
 
380
-        if ( $key && 2 == $key_status ) {
380
+        if ($key && 2 == $key_status) {
381 381
             // Key exists and its status is valid.
382 382
             // Set valid key status.
383 383
             $status     = 'valid';
384
-            $status_msg = __( 'Valid' );
384
+            $status_msg = __('Valid');
385 385
             $color      = '#46b450'; // Green.
386 386
             $message    = null;
387
-        } elseif ( $key && 1 == $key_status ) {
387
+        } elseif ($key && 1 == $key_status) {
388 388
             // Key exists but its validation has failed.
389 389
             // Set invalid key status.
390 390
             $status     = 'invalid';
391
-            $status_msg = __( 'Invalid' );
391
+            $status_msg = __('Invalid');
392 392
             $color      = '#dc3232'; // Red.
393
-            $message    = __( 'Your API key is invalid. Please enter a valid <a href="https://criticalcss.com/?aff=1" target="_blank">criticalcss.com</a> key.', 'autoptimize' );
394
-        } elseif ( $key && ! $key_status ) {
393
+            $message    = __('Your API key is invalid. Please enter a valid <a href="https://criticalcss.com/?aff=1" target="_blank">criticalcss.com</a> key.', 'autoptimize');
394
+        } elseif ($key && !$key_status) {
395 395
             // Key exists but it has no valid status yet
396 396
             // Perform key validation.
397
-            $key_check = $self->ao_ccss_key_validation( $key );
397
+            $key_check = $self->ao_ccss_key_validation($key);
398 398
 
399 399
             // Key is valid, set valid status.
400
-            if ( $key_check ) {
400
+            if ($key_check) {
401 401
                 $status     = 'valid';
402
-                $status_msg = __( 'Valid' );
402
+                $status_msg = __('Valid');
403 403
                 $color      = '#46b450'; // Green.
404 404
                 $message    = null;
405 405
             } else {
406 406
                 // Key is invalid, set invalid status.
407 407
                 $status     = 'invalid';
408
-                $status_msg = __( 'Invalid' );
408
+                $status_msg = __('Invalid');
409 409
                 $color      = '#dc3232'; // Red.
410
-                if ( get_option( 'autoptimize_ccss_keyst' ) == 1 ) {
411
-                    $message = __( 'Your API key is invalid. Please enter a valid <a href="https://criticalcss.com/?aff=1" target="_blank">criticalcss.com</a> key.', 'autoptimize' );
410
+                if (get_option('autoptimize_ccss_keyst') == 1) {
411
+                    $message = __('Your API key is invalid. Please enter a valid <a href="https://criticalcss.com/?aff=1" target="_blank">criticalcss.com</a> key.', 'autoptimize');
412 412
                 } else {
413
-                    $message = __( 'Something went wrong when checking your API key, make sure you server can communicate with https://criticalcss.com and/ or try again later.', 'autoptimize' );
413
+                    $message = __('Something went wrong when checking your API key, make sure you server can communicate with https://criticalcss.com and/ or try again later.', 'autoptimize');
414 414
                 }
415 415
             }
416 416
         } else {
417 417
             // No key nor status
418 418
             // Set no key status.
419 419
             $status     = 'nokey';
420
-            $status_msg = __( 'None' );
420
+            $status_msg = __('None');
421 421
             $color      = '#ffb900'; // Yellow.
422
-            $message    = __( 'Please enter a valid <a href="https://criticalcss.com/?aff=1" target="_blank">criticalcss.com</a> API key to start.', 'autoptimize' );
422
+            $message    = __('Please enter a valid <a href="https://criticalcss.com/?aff=1" target="_blank">criticalcss.com</a> API key to start.', 'autoptimize');
423 423
         }
424 424
 
425 425
         // Fill returned values.
426 426
         $key_return['status'] = $status;
427 427
         // Provide rendering information if required.
428
-        if ( $render ) {
428
+        if ($render) {
429 429
             $key_return['stmsg'] = $status_msg;
430 430
             $key_return['color'] = $color;
431 431
             $key_return['msg']   = $message;
@@ -435,7 +435,7 @@  discard block
 block discarded – undo
435 435
         return $key_return;
436 436
     }
437 437
 
438
-    public function ao_ccss_key_validation( $key ) {
438
+    public function ao_ccss_key_validation($key) {
439 439
         global $ao_ccss_noptimize;
440 440
 
441 441
         // POST a dummy job to criticalcss.com to check for key validation
@@ -443,26 +443,26 @@  discard block
 block discarded – undo
443 443
         $src_url = get_home_url();
444 444
 
445 445
         // Avoid AO optimizations if required by config or avoid lazyload if lazyload is active in AO.
446
-        if ( ! empty( $ao_ccss_noptimize ) ) {
446
+        if (!empty($ao_ccss_noptimize)) {
447 447
             $src_url .= '?ao_noptirocket=1';
448
-        } elseif ( class_exists( 'autoptimizeImages', false ) && autoptimizeImages::should_lazyload_wrapper() ) {
448
+        } elseif (class_exists('autoptimizeImages', false) && autoptimizeImages::should_lazyload_wrapper()) {
449 449
             $src_url .= '?ao_nolazy=1';
450 450
         }
451 451
 
452
-        $src_url = apply_filters( 'autoptimize_filter_ccss_cron_srcurl', $src_url );
452
+        $src_url = apply_filters('autoptimize_filter_ccss_cron_srcurl', $src_url);
453 453
 
454 454
         // Prepare the request.
455
-        $url  = esc_url_raw( AO_CCSS_API . 'generate' );
455
+        $url  = esc_url_raw(AO_CCSS_API.'generate');
456 456
         $args = array(
457 457
             'headers' => array(
458
-                'User-Agent'    => 'Autoptimize v' . AO_CCSS_VER,
458
+                'User-Agent'    => 'Autoptimize v'.AO_CCSS_VER,
459 459
                 'Content-type'  => 'application/json; charset=utf-8',
460
-                'Authorization' => 'JWT ' . $key,
460
+                'Authorization' => 'JWT '.$key,
461 461
                 'Connection'    => 'close',
462 462
             ),
463 463
             // Body must be JSON.
464 464
             'body'    => json_encode(
465
-                apply_filters( 'autoptimize_ccss_cron_api_generate_body',
465
+                apply_filters('autoptimize_ccss_cron_api_generate_body',
466 466
                     array(
467 467
                         'url'    => $src_url,
468 468
                         'aff'    => 1,
@@ -473,23 +473,23 @@  discard block
 block discarded – undo
473 473
         );
474 474
 
475 475
         // Dispatch the request and store its response code.
476
-        $req  = wp_safe_remote_post( $url, $args );
477
-        $code = wp_remote_retrieve_response_code( $req );
478
-        $body = json_decode( wp_remote_retrieve_body( $req ), true );
476
+        $req  = wp_safe_remote_post($url, $args);
477
+        $code = wp_remote_retrieve_response_code($req);
478
+        $body = json_decode(wp_remote_retrieve_body($req), true);
479 479
 
480
-        if ( 200 == $code ) {
480
+        if (200 == $code) {
481 481
             // Response is OK.
482 482
             // Set key status as valid and log key check.
483
-            update_option( 'autoptimize_ccss_keyst', 2 );
484
-            autoptimizeCriticalCSSCore::ao_ccss_log( 'criticalcss.com: API key is valid, updating key status', 3 );
483
+            update_option('autoptimize_ccss_keyst', 2);
484
+            autoptimizeCriticalCSSCore::ao_ccss_log('criticalcss.com: API key is valid, updating key status', 3);
485 485
 
486 486
             // extract job-id from $body and put it in the queue as a P job
487 487
             // but only if no jobs and no rules!
488 488
             global $ao_ccss_queue;
489 489
             global $ao_ccss_rules;
490 490
 
491
-            if ( 0 == count( $ao_ccss_queue ) && 0 == count( $ao_ccss_rules['types'] ) && 0 == count( $ao_ccss_rules['paths'] ) ) {
492
-                if ( 'JOB_QUEUED' == $body['job']['status'] || 'JOB_ONGOING' == $body['job']['status'] ) {
491
+            if (0 == count($ao_ccss_queue) && 0 == count($ao_ccss_rules['types']) && 0 == count($ao_ccss_rules['paths'])) {
492
+                if ('JOB_QUEUED' == $body['job']['status'] || 'JOB_ONGOING' == $body['job']['status']) {
493 493
                     $jprops['ljid']     = 'firstrun';
494 494
                     $jprops['rtarget']  = 'types|is_front_page';
495 495
                     $jprops['ptype']    = 'is_front_page';
@@ -500,30 +500,30 @@  discard block
 block discarded – undo
500 500
                     $jprops['jqstat']   = $body['job']['status'];
501 501
                     $jprops['jrstat']   = null;
502 502
                     $jprops['jvstat']   = null;
503
-                    $jprops['jctime']   = microtime( true );
503
+                    $jprops['jctime']   = microtime(true);
504 504
                     $jprops['jftime']   = null;
505 505
                     $ao_ccss_queue['/'] = $jprops;
506
-                    $ao_ccss_queue_raw  = json_encode( $ao_ccss_queue );
507
-                    update_option( 'autoptimize_ccss_queue', $ao_ccss_queue_raw, false );
508
-                    autoptimizeCriticalCSSCore::ao_ccss_log( 'Created P job for is_front_page based on API key check response.', 3 );
506
+                    $ao_ccss_queue_raw  = json_encode($ao_ccss_queue);
507
+                    update_option('autoptimize_ccss_queue', $ao_ccss_queue_raw, false);
508
+                    autoptimizeCriticalCSSCore::ao_ccss_log('Created P job for is_front_page based on API key check response.', 3);
509 509
                 }
510 510
             }
511 511
             return true;
512
-        } elseif ( 401 == $code ) {
512
+        } elseif (401 == $code) {
513 513
             // Response is unauthorized
514 514
             // Set key status as invalid and log key check.
515
-            update_option( 'autoptimize_ccss_keyst', 1 );
516
-            autoptimizeCriticalCSSCore::ao_ccss_log( 'criticalcss.com: API key is invalid, updating key status', 3 );
515
+            update_option('autoptimize_ccss_keyst', 1);
516
+            autoptimizeCriticalCSSCore::ao_ccss_log('criticalcss.com: API key is invalid, updating key status', 3);
517 517
             return false;
518 518
         } else {
519 519
             // Response unkown
520 520
             // Log key check attempt.
521
-            autoptimizeCriticalCSSCore::ao_ccss_log( 'criticalcss.com: could not check API key status, this is a service error, body follows if any...', 2 );
522
-            if ( ! empty( $body ) ) {
523
-                autoptimizeCriticalCSSCore::ao_ccss_log( print_r( $body, true ), 2 );
521
+            autoptimizeCriticalCSSCore::ao_ccss_log('criticalcss.com: could not check API key status, this is a service error, body follows if any...', 2);
522
+            if (!empty($body)) {
523
+                autoptimizeCriticalCSSCore::ao_ccss_log(print_r($body, true), 2);
524 524
             }
525
-            if ( is_wp_error( $req ) ) {
526
-                autoptimizeCriticalCSSCore::ao_ccss_log( $req->get_error_message(), 2 );
525
+            if (is_wp_error($req)) {
526
+                autoptimizeCriticalCSSCore::ao_ccss_log($req->get_error_message(), 2);
527 527
             }
528 528
             return false;
529 529
         }
@@ -538,14 +538,14 @@  discard block
 block discarded – undo
538 538
         $viewport = array();
539 539
 
540 540
         // Viewport Width.
541
-        if ( ! empty( $ao_ccss_viewport['w'] ) ) {
541
+        if (!empty($ao_ccss_viewport['w'])) {
542 542
             $viewport['w'] = $ao_ccss_viewport['w'];
543 543
         } else {
544 544
             $viewport['w'] = '';
545 545
         }
546 546
 
547 547
         // Viewport Height.
548
-        if ( ! empty( $ao_ccss_viewport['h'] ) ) {
548
+        if (!empty($ao_ccss_viewport['h'])) {
549 549
             $viewport['h'] = $ao_ccss_viewport['h'];
550 550
         } else {
551 551
             $viewport['h'] = '';
@@ -554,23 +554,23 @@  discard block
 block discarded – undo
554 554
         return $viewport;
555 555
     }
556 556
 
557
-    public static function ao_ccss_check_contents( $ccss ) {
557
+    public static function ao_ccss_check_contents($ccss) {
558 558
         // Perform basic exploit avoidance and CSS validation.
559
-        if ( ! empty( $ccss ) ) {
559
+        if (!empty($ccss)) {
560 560
             // Try to avoid code injection.
561
-            $blocklist = array( '#!/', 'function(', '<script', '<?php' );
562
-            foreach ( $blocklist as $blocklisted ) {
563
-                if ( strpos( $ccss, $blocklisted ) !== false ) {
564
-                    autoptimizeCriticalCSSCore::ao_ccss_log( 'Critical CSS received contained blocklisted content.', 2 );
561
+            $blocklist = array('#!/', 'function(', '<script', '<?php');
562
+            foreach ($blocklist as $blocklisted) {
563
+                if (strpos($ccss, $blocklisted) !== false) {
564
+                    autoptimizeCriticalCSSCore::ao_ccss_log('Critical CSS received contained blocklisted content.', 2);
565 565
                     return false;
566 566
                 }
567 567
             }
568 568
 
569 569
             // Check for most basics CSS structures.
570
-            $needlist = array( '{', '}', ':' );
571
-            foreach ( $needlist as $needed ) {
572
-                if ( false === strpos( $ccss, $needed ) && 'none' !== $ccss ) {
573
-                    autoptimizeCriticalCSSCore::ao_ccss_log( 'Critical CSS received did not seem to contain real CSS.', 2 );
570
+            $needlist = array('{', '}', ':');
571
+            foreach ($needlist as $needed) {
572
+                if (false === strpos($ccss, $needed) && 'none' !== $ccss) {
573
+                    autoptimizeCriticalCSSCore::ao_ccss_log('Critical CSS received did not seem to contain real CSS.', 2);
574 574
                     return false;
575 575
                 }
576 576
             }
@@ -580,7 +580,7 @@  discard block
 block discarded – undo
580 580
         return true;
581 581
     }
582 582
 
583
-    public static function ao_ccss_log( $msg, $lvl ) {
583
+    public static function ao_ccss_log($msg, $lvl) {
584 584
         // Commom logging facility
585 585
         // Attach debug option.
586 586
         global $ao_ccss_debug;
@@ -591,7 +591,7 @@  discard block
 block discarded – undo
591 591
         // 3: DD (for debug)
592 592
         // Default: UU (for unkown).
593 593
         $level = false;
594
-        switch ( $lvl ) {
594
+        switch ($lvl) {
595 595
             case 1:
596 596
                 $level = 'II';
597 597
                 break;
@@ -600,7 +600,7 @@  discard block
 block discarded – undo
600 600
                 break;
601 601
             case 3:
602 602
                 // Output debug messages only if debug mode is enabled.
603
-                if ( $ao_ccss_debug ) {
603
+                if ($ao_ccss_debug) {
604 604
                     $level = 'DD';
605 605
                 }
606 606
                 break;
@@ -609,19 +609,19 @@  discard block
 block discarded – undo
609 609
         }
610 610
 
611 611
         // Prepare and write a log message if there's a valid level.
612
-        if ( $level ) {
612
+        if ($level) {
613 613
 
614 614
             // Prepare message.
615
-            $message = date( 'c' ) . ' - [' . $level . '] ' . htmlentities( $msg ) . '<br>';
615
+            $message = date('c').' - ['.$level.'] '.htmlentities($msg).'<br>';
616 616
 
617 617
             // Write message to log file.
618
-            error_log( $message, 3, AO_CCSS_LOG );
618
+            error_log($message, 3, AO_CCSS_LOG);
619 619
         }
620 620
     }
621 621
 
622 622
     public static function ao_ccss_clear_page_tpl_cache() {
623 623
         // Clears transient cache for page templates.
624
-        delete_transient( 'autoptimize_ccss_page_templates' );
624
+        delete_transient('autoptimize_ccss_page_templates');
625 625
     }
626 626
 
627 627
 }
Please login to merge, or discard this patch.
classes/autoptimizeCriticalCSSSettingsAjax.php 1 patch
Spacing   +106 added lines, -106 removed lines patch added patch discarded remove patch
@@ -3,7 +3,7 @@  discard block
 block discarded – undo
3 3
  * Critical CSS settings AJAX logic.
4 4
  */
5 5
 
6
-if ( ! defined( 'ABSPATH' ) ) {
6
+if (!defined('ABSPATH')) {
7 7
     exit;
8 8
 }
9 9
 
@@ -12,7 +12,7 @@  discard block
 block discarded – undo
12 12
     {
13 13
         // fetch all options at once and populate them individually explicitely as globals.
14 14
         $all_options = autoptimizeCriticalCSSBase::fetch_options();
15
-        foreach ( $all_options as $_option => $_value ) {
15
+        foreach ($all_options as $_option => $_value) {
16 16
             global ${$_option};
17 17
             ${$_option} = $_value;
18 18
         }
@@ -21,47 +21,47 @@  discard block
 block discarded – undo
21 21
 
22 22
     public function run() {
23 23
         // add filters.
24
-        add_action( 'wp_ajax_fetch_critcss', array( $this, 'critcss_fetch_callback' ) );
25
-        add_action( 'wp_ajax_save_critcss', array( $this, 'critcss_save_callback' ) );
26
-        add_action( 'wp_ajax_rm_critcss', array( $this, 'critcss_rm_callback' ) );
27
-        add_action( 'wp_ajax_rm_critcss_all', array( $this, 'critcss_rm_all_callback' ) );
28
-        add_action( 'wp_ajax_ao_ccss_export', array( $this, 'ao_ccss_export_callback' ) );
29
-        add_action( 'wp_ajax_ao_ccss_import', array( $this, 'ao_ccss_import_callback' ) );
24
+        add_action('wp_ajax_fetch_critcss', array($this, 'critcss_fetch_callback'));
25
+        add_action('wp_ajax_save_critcss', array($this, 'critcss_save_callback'));
26
+        add_action('wp_ajax_rm_critcss', array($this, 'critcss_rm_callback'));
27
+        add_action('wp_ajax_rm_critcss_all', array($this, 'critcss_rm_all_callback'));
28
+        add_action('wp_ajax_ao_ccss_export', array($this, 'ao_ccss_export_callback'));
29
+        add_action('wp_ajax_ao_ccss_import', array($this, 'ao_ccss_import_callback'));
30 30
     }
31 31
 
32 32
     public function critcss_fetch_callback() {
33 33
         // Ajax handler to obtain a critical CSS file from the filesystem.
34 34
         // Check referer.
35
-        check_ajax_referer( 'fetch_critcss_nonce', 'critcss_fetch_nonce' );
35
+        check_ajax_referer('fetch_critcss_nonce', 'critcss_fetch_nonce');
36 36
 
37 37
         // Initialize error flag.
38 38
         $error = true;
39 39
 
40 40
         // Allow no content for MANUAL rules (as they may not exist just yet).
41
-        if ( current_user_can( 'manage_options' ) && empty( $_POST['critcssfile'] ) ) {
41
+        if (current_user_can('manage_options') && empty($_POST['critcssfile'])) {
42 42
             $content = '';
43 43
             $error   = false;
44
-        } elseif ( current_user_can( 'manage_options' ) && $this->critcss_check_filename( $_POST['critcssfile'] ) ) {
44
+        } elseif (current_user_can('manage_options') && $this->critcss_check_filename($_POST['critcssfile'])) {
45 45
             // Or check user permissios and filename.
46 46
             // Set file path and obtain its content.
47
-            $critcssfile = AO_CCSS_DIR . strip_tags( $_POST['critcssfile'] );
48
-            if ( file_exists( $critcssfile ) ) {
49
-                $content = file_get_contents( $critcssfile );
47
+            $critcssfile = AO_CCSS_DIR.strip_tags($_POST['critcssfile']);
48
+            if (file_exists($critcssfile)) {
49
+                $content = file_get_contents($critcssfile);
50 50
                 $error   = false;
51 51
             }
52 52
         }
53 53
 
54 54
         // Prepare response.
55
-        if ( $error ) {
55
+        if ($error) {
56 56
             $response['code']   = '500';
57
-            $response['string'] = 'Error reading file ' . $critcssfile . '.';
57
+            $response['string'] = 'Error reading file '.$critcssfile.'.';
58 58
         } else {
59 59
             $response['code']   = '200';
60 60
             $response['string'] = $content;
61 61
         }
62 62
 
63 63
         // Dispatch respose.
64
-        echo json_encode( $response );
64
+        echo json_encode($response);
65 65
 
66 66
         // Close ajax request.
67 67
         wp_die();
@@ -74,22 +74,22 @@  discard block
 block discarded – undo
74 74
 
75 75
         // Ajax handler to write a critical CSS to the filesystem
76 76
         // Check referer.
77
-        check_ajax_referer( 'save_critcss_nonce', 'critcss_save_nonce' );
77
+        check_ajax_referer('save_critcss_nonce', 'critcss_save_nonce');
78 78
 
79 79
         // Allow empty contents for MANUAL rules (as they are fetched later).
80
-        if ( current_user_can( 'manage_options' ) && empty( $_POST['critcssfile'] ) ) {
80
+        if (current_user_can('manage_options') && empty($_POST['critcssfile'])) {
81 81
             $critcssfile = false;
82 82
             $status      = true;
83
-        } elseif ( current_user_can( 'manage_options' ) && $this->critcss_check_filename( $_POST['critcssfile'] ) ) {
83
+        } elseif (current_user_can('manage_options') && $this->critcss_check_filename($_POST['critcssfile'])) {
84 84
             // Or check user permissios and filename
85 85
             // Set critical CSS content.
86
-            $critcsscontents = stripslashes( $_POST['critcsscontents'] );
86
+            $critcsscontents = stripslashes($_POST['critcsscontents']);
87 87
 
88 88
             // If there is content and it's valid, write the file.
89
-            if ( $critcsscontents && autoptimizeCriticalCSSCore::ao_ccss_check_contents( $critcsscontents ) ) {
89
+            if ($critcsscontents && autoptimizeCriticalCSSCore::ao_ccss_check_contents($critcsscontents)) {
90 90
                 // Set file path and status.
91
-                $critcssfile = AO_CCSS_DIR . strip_tags( $_POST['critcssfile'] );
92
-                $status      = file_put_contents( $critcssfile, $critcsscontents, LOCK_EX );
91
+                $critcssfile = AO_CCSS_DIR.strip_tags($_POST['critcssfile']);
92
+                $status      = file_put_contents($critcssfile, $critcsscontents, LOCK_EX);
93 93
                 // Or set as error.
94 94
             } else {
95 95
                 $error = true;
@@ -100,20 +100,20 @@  discard block
 block discarded – undo
100 100
         }
101 101
 
102 102
         // Prepare response.
103
-        if ( ! $status || $error ) {
103
+        if (!$status || $error) {
104 104
             $response['code']   = '500';
105
-            $response['string'] = 'Error saving file ' . $critcssfile . '.';
105
+            $response['string'] = 'Error saving file '.$critcssfile.'.';
106 106
         } else {
107 107
             $response['code'] = '200';
108
-            if ( $critcssfile ) {
109
-                $response['string'] = 'File ' . $critcssfile . ' saved.';
108
+            if ($critcssfile) {
109
+                $response['string'] = 'File '.$critcssfile.' saved.';
110 110
             } else {
111 111
                 $response['string'] = 'Empty content do not need to be saved.';
112 112
             }
113 113
         }
114 114
 
115 115
         // Dispatch respose.
116
-        echo json_encode( $response );
116
+        echo json_encode($response);
117 117
 
118 118
         // Close ajax request.
119 119
         wp_die();
@@ -123,40 +123,40 @@  discard block
 block discarded – undo
123 123
     public function critcss_rm_callback() {
124 124
         // Ajax handler to delete a critical CSS from the filesystem
125 125
         // Check referer.
126
-        check_ajax_referer( 'rm_critcss_nonce', 'critcss_rm_nonce' );
126
+        check_ajax_referer('rm_critcss_nonce', 'critcss_rm_nonce');
127 127
 
128 128
         // Initialize error and status flags.
129 129
         $error  = true;
130 130
         $status = false;
131 131
 
132 132
         // Allow no file for MANUAL rules (as they may not exist just yet).
133
-        if ( current_user_can( 'manage_options' ) && empty( $_POST['critcssfile'] ) ) {
133
+        if (current_user_can('manage_options') && empty($_POST['critcssfile'])) {
134 134
             $error = false;
135
-        } elseif ( current_user_can( 'manage_options' ) && $this->critcss_check_filename( $_POST['critcssfile'] ) ) {
135
+        } elseif (current_user_can('manage_options') && $this->critcss_check_filename($_POST['critcssfile'])) {
136 136
             // Or check user permissios and filename
137 137
             // Set file path and delete it.
138
-            $critcssfile = AO_CCSS_DIR . strip_tags( $_POST['critcssfile'] );
139
-            if ( file_exists( $critcssfile ) ) {
140
-                $status = unlink( $critcssfile );
138
+            $critcssfile = AO_CCSS_DIR.strip_tags($_POST['critcssfile']);
139
+            if (file_exists($critcssfile)) {
140
+                $status = unlink($critcssfile);
141 141
                 $error  = false;
142 142
             }
143 143
         }
144 144
 
145 145
         // Prepare response.
146
-        if ( $error ) {
146
+        if ($error) {
147 147
             $response['code']   = '500';
148
-            $response['string'] = 'Error removing file ' . $critcssfile . '.';
148
+            $response['string'] = 'Error removing file '.$critcssfile.'.';
149 149
         } else {
150 150
             $response['code'] = '200';
151
-            if ( $status ) {
152
-                $response['string'] = 'File ' . $critcssfile . ' removed.';
151
+            if ($status) {
152
+                $response['string'] = 'File '.$critcssfile.' removed.';
153 153
             } else {
154 154
                 $response['string'] = 'No file to be removed.';
155 155
             }
156 156
         }
157 157
 
158 158
         // Dispatch respose.
159
-        echo json_encode( $response );
159
+        echo json_encode($response);
160 160
 
161 161
         // Close ajax request.
162 162
         wp_die();
@@ -165,28 +165,28 @@  discard block
 block discarded – undo
165 165
     public function critcss_rm_all_callback() {
166 166
         // Ajax handler to delete a critical CSS from the filesystem
167 167
         // Check referer.
168
-        check_ajax_referer( 'rm_critcss_all_nonce', 'critcss_rm_all_nonce' );
168
+        check_ajax_referer('rm_critcss_all_nonce', 'critcss_rm_all_nonce');
169 169
 
170 170
         // Initialize error and status flags.
171 171
         $error  = true;
172 172
         $status = false;
173 173
 
174 174
         // Remove all ccss files on filesystem.
175
-        if ( current_user_can( 'manage_options' ) ) {
176
-            if ( file_exists( AO_CCSS_DIR ) && is_dir( AO_CCSS_DIR ) ) {
177
-                array_map( 'unlink', glob( AO_CCSS_DIR . 'ccss_*.css', GLOB_BRACE ) );
175
+        if (current_user_can('manage_options')) {
176
+            if (file_exists(AO_CCSS_DIR) && is_dir(AO_CCSS_DIR)) {
177
+                array_map('unlink', glob(AO_CCSS_DIR.'ccss_*.css', GLOB_BRACE));
178 178
                 $error  = false;
179 179
                 $status = true;
180 180
             }
181 181
         }
182 182
 
183 183
         // Prepare response.
184
-        if ( $error ) {
184
+        if ($error) {
185 185
             $response['code']   = '500';
186 186
             $response['string'] = 'Error removing all critical CSS files.';
187 187
         } else {
188 188
             $response['code'] = '200';
189
-            if ( $status ) {
189
+            if ($status) {
190 190
                 $response['string'] = 'Critical CSS Files removed.';
191 191
             } else {
192 192
                 $response['string'] = 'No file removed.';
@@ -194,7 +194,7 @@  discard block
 block discarded – undo
194 194
         }
195 195
 
196 196
         // Dispatch respose.
197
-        echo json_encode( $response );
197
+        echo json_encode($response);
198 198
 
199 199
         // Close ajax request.
200 200
         wp_die();
@@ -203,70 +203,70 @@  discard block
 block discarded – undo
203 203
     public function ao_ccss_export_callback() {
204 204
         // Ajax handler export settings
205 205
         // Check referer.
206
-        check_ajax_referer( 'ao_ccss_export_nonce', 'ao_ccss_export_nonce' );
206
+        check_ajax_referer('ao_ccss_export_nonce', 'ao_ccss_export_nonce');
207 207
 
208
-        if ( ! class_exists( 'ZipArchive' ) ) {
208
+        if (!class_exists('ZipArchive')) {
209 209
             $response['code'] = '500';
210 210
             $response['msg']  = 'PHP ZipArchive not present, cannot create zipfile';
211
-            echo json_encode( $response );
211
+            echo json_encode($response);
212 212
             wp_die();
213 213
         }
214 214
 
215 215
         // Init array, get options and prepare the raw object.
216 216
         $settings               = array();
217
-        $settings['rules']      = get_option( 'autoptimize_ccss_rules' );
218
-        $settings['additional'] = get_option( 'autoptimize_ccss_additional' );
219
-        $settings['viewport']   = get_option( 'autoptimize_ccss_viewport' );
220
-        $settings['finclude']   = get_option( 'autoptimize_ccss_finclude' );
221
-        $settings['rlimit']     = get_option( 'autoptimize_ccss_rlimit' );
222
-        $settings['noptimize']  = get_option( 'autoptimize_ccss_noptimize' );
223
-        $settings['debug']      = get_option( 'autoptimize_ccss_debug' );
224
-        $settings['key']        = get_option( 'autoptimize_ccss_key' );
217
+        $settings['rules']      = get_option('autoptimize_ccss_rules');
218
+        $settings['additional'] = get_option('autoptimize_ccss_additional');
219
+        $settings['viewport']   = get_option('autoptimize_ccss_viewport');
220
+        $settings['finclude']   = get_option('autoptimize_ccss_finclude');
221
+        $settings['rlimit']     = get_option('autoptimize_ccss_rlimit');
222
+        $settings['noptimize']  = get_option('autoptimize_ccss_noptimize');
223
+        $settings['debug']      = get_option('autoptimize_ccss_debug');
224
+        $settings['key']        = get_option('autoptimize_ccss_key');
225 225
 
226 226
         // Initialize error flag.
227 227
         $error = true;
228 228
 
229 229
         // Check user permissions.
230
-        if ( current_user_can( 'manage_options' ) ) {
230
+        if (current_user_can('manage_options')) {
231 231
             // Prepare settings file path and content.
232
-            $exportfile = AO_CCSS_DIR . 'settings.json';
233
-            $contents   = json_encode( $settings );
234
-            $status     = file_put_contents( $exportfile, $contents, LOCK_EX );
232
+            $exportfile = AO_CCSS_DIR.'settings.json';
233
+            $contents   = json_encode($settings);
234
+            $status     = file_put_contents($exportfile, $contents, LOCK_EX);
235 235
             $error      = false;
236 236
         }
237 237
 
238 238
         // Prepare archive.
239
-        $zipfile = AO_CCSS_DIR . date( 'Ymd-H\hi' ) . '_ao_ccss_settings.zip';
240
-        $file    = pathinfo( $zipfile, PATHINFO_BASENAME );
239
+        $zipfile = AO_CCSS_DIR.date('Ymd-H\hi').'_ao_ccss_settings.zip';
240
+        $file    = pathinfo($zipfile, PATHINFO_BASENAME);
241 241
         $zip     = new ZipArchive();
242
-        $ret     = $zip->open( $zipfile, ZipArchive::CREATE );
243
-        if ( true !== $ret ) {
242
+        $ret     = $zip->open($zipfile, ZipArchive::CREATE);
243
+        if (true !== $ret) {
244 244
             $error = true;
245 245
         } else {
246
-            $zip->addFile( AO_CCSS_DIR . 'settings.json', 'settings.json' );
247
-            if ( file_exists( AO_CCSS_DIR . 'queue.json' ) ) {
248
-                $zip->addFile( AO_CCSS_DIR . 'queue.json', 'queue.json' );
246
+            $zip->addFile(AO_CCSS_DIR.'settings.json', 'settings.json');
247
+            if (file_exists(AO_CCSS_DIR.'queue.json')) {
248
+                $zip->addFile(AO_CCSS_DIR.'queue.json', 'queue.json');
249 249
             }
250 250
             $options = array(
251 251
                 'add_path'        => './',
252 252
                 'remove_all_path' => true,
253 253
             );
254
-            $zip->addGlob( AO_CCSS_DIR . '*.css', 0, $options );
254
+            $zip->addGlob(AO_CCSS_DIR.'*.css', 0, $options);
255 255
             $zip->close();
256 256
         }
257 257
 
258 258
         // Prepare response.
259
-        if ( ! $status || $error ) {
259
+        if (!$status || $error) {
260 260
             $response['code'] = '500';
261
-            $response['msg']  = 'Error saving file ' . $file . ', code: ' . $ret;
261
+            $response['msg']  = 'Error saving file '.$file.', code: '.$ret;
262 262
         } else {
263 263
             $response['code'] = '200';
264
-            $response['msg']  = 'File ' . $file . ' saved.';
264
+            $response['msg']  = 'File '.$file.' saved.';
265 265
             $response['file'] = $file;
266 266
         }
267 267
 
268 268
         // Dispatch respose.
269
-        echo json_encode( $response );
269
+        echo json_encode($response);
270 270
 
271 271
         // Close ajax request.
272 272
         wp_die();
@@ -275,54 +275,54 @@  discard block
 block discarded – undo
275 275
     public function ao_ccss_import_callback() {
276 276
         // Ajax handler import settings
277 277
         // Check referer.
278
-        check_ajax_referer( 'ao_ccss_import_nonce', 'ao_ccss_import_nonce' );
278
+        check_ajax_referer('ao_ccss_import_nonce', 'ao_ccss_import_nonce');
279 279
 
280 280
         // Initialize error flag.
281 281
         $error = false;
282 282
 
283 283
         // Process an uploaded file with no errors.
284
-        if ( current_user_can( 'manage_options' ) && ! $_FILES['file']['error'] && strpos( $_FILES['file']['name'], '.zip' ) === strlen( $_FILES['file']['name'] ) - 4 ) {
284
+        if (current_user_can('manage_options') && !$_FILES['file']['error'] && strpos($_FILES['file']['name'], '.zip') === strlen($_FILES['file']['name']) - 4) {
285 285
             // Save file to the cache directory.
286
-            $zipfile = AO_CCSS_DIR . $_FILES['file']['name'];
287
-            move_uploaded_file( $_FILES['file']['tmp_name'], $zipfile );
286
+            $zipfile = AO_CCSS_DIR.$_FILES['file']['name'];
287
+            move_uploaded_file($_FILES['file']['tmp_name'], $zipfile);
288 288
 
289 289
             // Extract archive.
290 290
             $zip = new ZipArchive;
291
-            if ( $zip->open( $zipfile ) === true ) {
292
-                $zip->extractTo( AO_CCSS_DIR );
291
+            if ($zip->open($zipfile) === true) {
292
+                $zip->extractTo(AO_CCSS_DIR);
293 293
                 $zip->close();
294 294
             } else {
295 295
                 $error = 'could not extract';
296 296
             }
297 297
 
298
-            if ( ! $error ) {
298
+            if (!$error) {
299 299
                 // only known files allowed, all others are deleted.
300
-                $_dir_contents_ccss = glob( AO_CCSS_DIR . 'ccss_*.css' );
301
-                $_dir_known_ok      = array( AO_CCSS_DIR . 'queue.lock', AO_CCSS_DIR . 'queuelog.html', AO_CCSS_DIR . 'index.html', AO_CCSS_DIR . 'settings.json' );
302
-                $_dir_contents_ok   = array_merge( $_dir_contents_ccss, $_dir_known_ok );
303
-                $_dir_contents_all  = glob( AO_CCSS_DIR . '*' );
304
-                $_dir_to_be_deleted = array_diff( $_dir_contents_all, $_dir_contents_ok );
305
-                foreach ( $_dir_to_be_deleted as $_file_to_be_deleted ) {
306
-                    unlink( $_file_to_be_deleted );
300
+                $_dir_contents_ccss = glob(AO_CCSS_DIR.'ccss_*.css');
301
+                $_dir_known_ok      = array(AO_CCSS_DIR.'queue.lock', AO_CCSS_DIR.'queuelog.html', AO_CCSS_DIR.'index.html', AO_CCSS_DIR.'settings.json');
302
+                $_dir_contents_ok   = array_merge($_dir_contents_ccss, $_dir_known_ok);
303
+                $_dir_contents_all  = glob(AO_CCSS_DIR.'*');
304
+                $_dir_to_be_deleted = array_diff($_dir_contents_all, $_dir_contents_ok);
305
+                foreach ($_dir_to_be_deleted as $_file_to_be_deleted) {
306
+                    unlink($_file_to_be_deleted);
307 307
                 }
308 308
 
309 309
                 // Archive extraction ok, continue settings importing
310 310
                 // Settings file.
311
-                $importfile = AO_CCSS_DIR . 'settings.json';
311
+                $importfile = AO_CCSS_DIR.'settings.json';
312 312
 
313
-                if ( file_exists( $importfile ) ) {
313
+                if (file_exists($importfile)) {
314 314
                     // Get settings and turn them into an object.
315
-                    $settings = json_decode( file_get_contents( $importfile ), true );
315
+                    $settings = json_decode(file_get_contents($importfile), true);
316 316
 
317 317
                     // Update options.
318
-                    update_option( 'autoptimize_ccss_rules', $settings['rules'] );
319
-                    update_option( 'autoptimize_ccss_additional', $settings['additional'] );
320
-                    update_option( 'autoptimize_ccss_viewport', $settings['viewport'] );
321
-                    update_option( 'autoptimize_ccss_finclude', $settings['finclude'] );
322
-                    update_option( 'autoptimize_ccss_rlimit', $settings['rlimit'] );
323
-                    update_option( 'autoptimize_ccss_noptimize', $settings['noptimize'] );
324
-                    update_option( 'autoptimize_ccss_debug', $settings['debug'] );
325
-                    update_option( 'autoptimize_ccss_key', $settings['key'] );
318
+                    update_option('autoptimize_ccss_rules', $settings['rules']);
319
+                    update_option('autoptimize_ccss_additional', $settings['additional']);
320
+                    update_option('autoptimize_ccss_viewport', $settings['viewport']);
321
+                    update_option('autoptimize_ccss_finclude', $settings['finclude']);
322
+                    update_option('autoptimize_ccss_rlimit', $settings['rlimit']);
323
+                    update_option('autoptimize_ccss_noptimize', $settings['noptimize']);
324
+                    update_option('autoptimize_ccss_debug', $settings['debug']);
325
+                    update_option('autoptimize_ccss_key', $settings['key']);
326 326
                 } else {
327 327
                     // Settings file doesn't exist, update error flag.
328 328
                     $error = 'settings file does not exist';
@@ -333,28 +333,28 @@  discard block
 block discarded – undo
333 333
         }
334 334
 
335 335
         // Prepare response.
336
-        if ( $error ) {
336
+        if ($error) {
337 337
             $response['code'] = '500';
338
-            $response['msg']  = 'Error importing settings: ' . $error;
338
+            $response['msg']  = 'Error importing settings: '.$error;
339 339
         } else {
340 340
             $response['code'] = '200';
341 341
             $response['msg']  = 'Settings imported successfully';
342 342
         }
343 343
 
344 344
         // Dispatch respose.
345
-        echo json_encode( $response );
345
+        echo json_encode($response);
346 346
 
347 347
         // Close ajax request.
348 348
         wp_die();
349 349
     }
350 350
 
351
-    public function critcss_check_filename( $filename ) {
351
+    public function critcss_check_filename($filename) {
352 352
         // Try to avoid directory traversal when reading/writing/deleting critical CSS files.
353
-        if ( strpos( $filename, 'ccss_' ) !== 0 ) {
353
+        if (strpos($filename, 'ccss_') !== 0) {
354 354
             return false;
355
-        } elseif ( substr( $filename, -4, 4 ) !== '.css' ) {
355
+        } elseif (substr($filename, -4, 4) !== '.css') {
356 356
             return false;
357
-        } elseif ( sanitize_file_name( $filename ) !== $filename ) {
357
+        } elseif (sanitize_file_name($filename) !== $filename) {
358 358
             // Use WordPress core's sanitize_file_name to see if anything fishy is going on.
359 359
             return false;
360 360
         } else {
Please login to merge, or discard this patch.
config/autoptimize_404_handler.php 1 patch
Spacing   +10 added lines, -10 removed lines patch added patch discarded remove patch
@@ -20,24 +20,24 @@
 block discarded – undo
20 20
  * to files that don't exist in AO's cache.
21 21
  */
22 22
 
23
-$original_request = strtok( $_SERVER['REQUEST_URI'], '?' );
23
+$original_request = strtok($_SERVER['REQUEST_URI'], '?');
24 24
 
25
-if ( strpos( $original_request, 'uucss/uucss-' ) !== false ) {
26
-    $original_request = preg_replace( '/uucss\/uucss-[a-z0-9]{32}-/', 'css/', $original_request  );
25
+if (strpos($original_request, 'uucss/uucss-') !== false) {
26
+    $original_request = preg_replace('/uucss\/uucss-[a-z0-9]{32}-/', 'css/', $original_request);
27 27
 }
28 28
 
29
-$fallback_target  = preg_replace( '/(.*)_(?:[a-z0-9]{32})\.(js|css)$/', '${1}_fallback.${2}', $original_request );
29
+$fallback_target  = preg_replace('/(.*)_(?:[a-z0-9]{32})\.(js|css)$/', '${1}_fallback.${2}', $original_request);
30 30
 $ao_cache_dir     = '<!--ao-cache-dir-->';
31
-$js_or_css        = pathinfo( $original_request, PATHINFO_EXTENSION );
32
-$fallback_path    = $ao_cache_dir . $js_or_css . '/autoptimize_fallback.' . $js_or_css;
31
+$js_or_css        = pathinfo($original_request, PATHINFO_EXTENSION);
32
+$fallback_path    = $ao_cache_dir.$js_or_css.'/autoptimize_fallback.'.$js_or_css;
33 33
 
34
-if ( $original_request !== $fallback_target && file_exists( $fallback_path ) ) {
34
+if ($original_request !== $fallback_target && file_exists($fallback_path)) {
35 35
     // error_log( 'Autoptimize file ' . $original_request . ' not found, using fallback instead.' );
36
-    header( 'HTTP/1.1 301 Moved Permanently' );
37
-    header( 'Location: ' . $fallback_target );
36
+    header('HTTP/1.1 301 Moved Permanently');
37
+    header('Location: '.$fallback_target);
38 38
 } else {
39 39
     // error_log( 'Autoptimize file ' . $original_request . ' not found, sending 410 gone response.' );
40
-    header( 'HTTP/1.1 410 Gone' );
40
+    header('HTTP/1.1 410 Gone');
41 41
 }
42 42
 
43 43
 exit();
Please login to merge, or discard this patch.