Completed
Pull Request — master (#99)
by
unknown
03:03
created

autoptimizeStyles::hide_fontface_and_maybe_cdn()   B

Complexity

Conditions 4
Paths 2

Size

Total Lines 25
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 4
eloc 11
nc 2
nop 1
dl 0
loc 25
rs 8.5806
c 0
b 0
f 0
1
<?php
2
if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly
3
4
class autoptimizeStyles extends autoptimizeBase {
5
6
    const ASSETS_REGEX = '/url\s*\(\s*(?!["\']?data:)(?![\'|\"]?[\#|\%|])([^)]+)\s*\)([^;},]*)/i';
7
8
    /**
9
     * Font-face regex-fu from HamZa at: https://stackoverflow.com/a/21395083
10
     * ~
11
     * @font-face\s* # Match @font-face and some spaces
12
     * (             # Start group 1
13
     * \{            # Match {
14
     * (?:           # A non-capturing group
15
     * [^{}]+        # Match anything except {} one or more times
16
     * |             # Or
17
     * (?1)          # Recurse/rerun the expression of group 1
18
     * )*            # Repeat 0 or more times
19
     * \}            # Match }
20
     * )             # End group 1
21
     * ~xs';
22
     */
23
    const FONT_FACE_REGEX = '~@font-face\s*(\{(?:[^{}]+|(?1))*\})~xsi'; // added `i` flag for case-insensitivity
24
25
    private $css = array();
26
    private $csscode = array();
27
    private $url = array();
28
    private $restofcontent = '';
29
    private $datauris = false;
30
    private $hashmap = array();
31
    private $alreadyminified = false;
32
    private $inline = false;
33
    private $defer = false;
34
    private $defer_inline = false;
35
    private $whitelist = '';
36
    private $cssinlinesize = '';
37
    private $cssremovables = array();
38
    private $include_inline = false;
39
    private $inject_min_late = '';
40
41
    //Reads the page and collects style tags
42
    public function read($options) {
43
        $noptimizeCSS = apply_filters( 'autoptimize_filter_css_noptimize', false, $this->content );
44
        if ($noptimizeCSS) return false;
45
46
        $whitelistCSS = apply_filters( 'autoptimize_filter_css_whitelist', '', $this->content );
47
        if (!empty($whitelistCSS)) {
48
            $this->whitelist = array_filter(array_map('trim',explode(",",$whitelistCSS)));
0 ignored issues
show
Documentation Bug introduced by
It seems like array_filter(array_map('...e(',', $whitelistCSS))) of type array is incompatible with the declared type string of property $whitelist.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
49
        }
50
        
51
        if ($options['nogooglefont'] == true) {
52
            $removableCSS = "fonts.googleapis.com";
53
        } else {
54
            $removableCSS = "";
55
        }
56
        $removableCSS = apply_filters( 'autoptimize_filter_css_removables', $removableCSS);
57 View Code Duplication
        if (!empty($removableCSS)) {
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...
58
            $this->cssremovables = array_filter(array_map('trim',explode(",",$removableCSS)));
59
        }
60
61
        $this->cssinlinesize = apply_filters('autoptimize_filter_css_inlinesize',256);
62
63
        // filter to "late inject minified CSS", default to true for now (it is faster)
64
        $this->inject_min_late = apply_filters('autoptimize_filter_css_inject_min_late',true);
65
66
        // Remove everything that's not the header
67 View Code Duplication
        if ( apply_filters('autoptimize_filter_css_justhead',$options['justhead']) == true ) {
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...
68
            $content = explode('</head>',$this->content,2);
69
            $this->content = $content[0].'</head>';
70
            $this->restofcontent = $content[1];
71
        }
72
73
        // include inline?
74
        if( apply_filters('autoptimize_css_include_inline',$options['include_inline']) == true ) {
75
            $this->include_inline = true;
76
        }
77
        
78
        // what CSS shouldn't be autoptimized
79
        $excludeCSS = $options['css_exclude'];
80
        $excludeCSS = apply_filters( 'autoptimize_filter_css_exclude', $excludeCSS, $this->content );
81
        if ($excludeCSS!=="") {
82
            $this->dontmove = array_filter(array_map('trim',explode(",",$excludeCSS)));
0 ignored issues
show
Bug introduced by
The property dontmove does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
83
        } else {
84
            $this->dontmove = "";
85
        }
86
87
        // should we defer css?
88
        // value: true/ false
89
        $this->defer = $options['defer'];
90
        $this->defer = apply_filters( 'autoptimize_filter_css_defer', $this->defer, $this->content );
91
92
        // should we inline while deferring?
93
        // value: inlined CSS
94
        $this->defer_inline = $options['defer_inline'];
95
        $this->defer_inline = apply_filters( 'autoptimize_filter_css_defer_inline', $this->defer_inline, $this->content );
96
97
        // should we inline?
98
        // value: true/ false
99
        $this->inline = $options['inline'];
100
        $this->inline = apply_filters( 'autoptimize_filter_css_inline', $this->inline, $this->content );
101
        
102
        // get cdn url
103
        $this->cdn_url = $options['cdn_url'];
0 ignored issues
show
Bug introduced by
The property cdn_url does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
104
        
105
        // Store data: URIs setting for later use
106
        $this->datauris = $options['datauris'];
107
        
108
        // noptimize me
109
        $this->content = $this->hide_noptimize($this->content);
110
        
111
        // exclude (no)script, as those may contain CSS which should be left as is
112 View Code Duplication
        if ( strpos( $this->content, '<script' ) !== false ) { 
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...
113
            $this->content = preg_replace_callback(
114
                '#<(?:no)?script.*?<\/(?:no)?script>#is',
115
                create_function(
0 ignored issues
show
Security Best Practice introduced by
The use of create_function is highly discouraged, better use a closure.

create_function can pose a great security vulnerability as it is similar to eval, and could be used for arbitrary code execution. We highly recommend to use a closure instead.

// Instead of
$function = create_function('$a, $b', 'return $a + $b');

// Better use
$function = function($a, $b) { return $a + $b; }
Loading history...
116
                    '$matches',
117
                    'return "%%SCRIPT".AUTOPTIMIZE_HASH."%%".base64_encode($matches[0])."%%SCRIPT%%";'
118
                ),
119
                $this->content
120
            );
121
        }
122
123
        // Save IE hacks
124
        $this->content = $this->hide_iehacks($this->content);
125
126
        // hide comments
127
        $this->content = $this->hide_comments($this->content);
128
        
129
        // Get <style> and <link>
130
        if(preg_match_all('#(<style[^>]*>.*</style>)|(<link[^>]*stylesheet[^>]*>)#Usmi',$this->content,$matches)) {
131
            foreach($matches[0] as $tag) {
132
                if ($this->isremovable($tag,$this->cssremovables)) {
133
                    $this->content = str_replace($tag,'',$this->content);
134
                } else if ($this->ismovable($tag)) {
135
                    // Get the media
136
                    if(strpos($tag,'media=')!==false) {
137
                        preg_match('#media=(?:"|\')([^>]*)(?:"|\')#Ui',$tag,$medias);
138
                        $medias = explode(',',$medias[1]);
139
                        $media = array();
140
                        foreach($medias as $elem) {
141
                            if (empty($elem)) { $elem="all"; }
142
                            $media[] = $elem;
143
                        }
144
                    } else {
145
                        // No media specified - applies to all
146
                        $media = array('all');
147
                    }
148
                    $media = apply_filters( 'autoptimize_filter_css_tagmedia',$media,$tag );
149
                
150
                    if(preg_match('#<link.*href=("|\')(.*)("|\')#Usmi',$tag,$source)) {
151
                        // <link>
152
                        $explUrl = explode('?',$source[2],2);
153
                        $url = $explUrl[0];
154
                        $path = $this->getpath($url);
155
                        
156
                        if($path!==false && preg_match('#\.css$#',$path)) {
157
                            // Good link
158
                            $this->css[] = array($media,$path);
159
                        }else{
160
                            // Link is dynamic (.php etc)
161
                            $tag = '';
162
                        }
163
                    } else {
164
                        // inline css in style tags can be wrapped in comment tags, so restore comments
165
                        $tag = $this->restore_comments($tag);
166
                        preg_match('#<style.*>(.*)</style>#Usmi',$tag,$code);
167
168
                        // and re-hide them to be able to to the removal based on tag
169
                        $tag = $this->hide_comments($tag);
170
171
                        if ( $this->include_inline ) {
172
                            $code = preg_replace('#^.*<!\[CDATA\[(?:\s*\*/)?(.*)(?://|/\*)\s*?\]\]>.*$#sm','$1',$code[1]);
173
                            $this->css[] = array($media,'INLINE;'.$code);
174
                        } else {
175
                            $tag = '';
176
                        }
177
                    }
178
                    
179
                    // Remove the original style tag
180
                    $this->content = str_replace($tag,'',$this->content);
181
                } else {
182
					// excluded CSS, minify if getpath 
183
					if (preg_match('#<link.*href=("|\')(.*)("|\')#Usmi',$tag,$source)) {
184
						$explUrl = explode('?',$source[2],2);
185
                        $url = $explUrl[0];
186
                        $path = $this->getpath($url);
187
 					
188
						if ($path && apply_filters('autoptimize_filter_css_minify_excluded',false)) {
189
							$_CachedMinifiedUrl = $this->minify_single($path);
190
191
							if (!empty($_CachedMinifiedUrl)) {
192
								// replace orig URL with URL to cache
193
								$newTag = str_replace($url, $_CachedMinifiedUrl, $tag);
194
							} else {
195
								$newTag = $tag;
196
							}
197
							
198
							// remove querystring from URL
199 View Code Duplication
							if ( !empty($explUrl[1]) ) {
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...
200
								$newTag = str_replace("?".$explUrl[1],"",$newTag);
201
							}
202
203
							// and replace
204
							$this->content = str_replace($tag,$newTag,$this->content);
205
						}
206
					}					
207
				}
208
            }
209
            return true;
210
        }
211
        // Really, no styles?
212
        return false;
213
    }
214
    
215
    // Joins and optimizes CSS
216
    public function minify() {
217
        foreach($this->css as $group) {
218
            list($media,$css) = $group;
219
            if(preg_match('#^INLINE;#',$css)) {
220
                // <style>
221
                $css = preg_replace('#^INLINE;#','',$css);
222
                $css = $this->fixurls(ABSPATH.'/index.php',$css);
223
                $tmpstyle = apply_filters( 'autoptimize_css_individual_style', $css, "" );
224
                if ( has_filter('autoptimize_css_individual_style') && !empty($tmpstyle) ) {
225
                    $css=$tmpstyle;
226
                    $this->alreadyminified=true;
227
                }
228
            } else {
229
                //<link>
230
                if($css !== false && file_exists($css) && is_readable($css)) {
231
                    $cssPath = $css;
232
                    $cssContents = file_get_contents($cssPath);
233
                    $cssHash = md5($cssContents);
234
                    $css = $this->fixurls($cssPath,$cssContents);
235
                    $css = preg_replace('/\x{EF}\x{BB}\x{BF}/','',$css);
236
                    $tmpstyle = apply_filters( 'autoptimize_css_individual_style', $css, $cssPath );
237 View Code Duplication
                    if (has_filter('autoptimize_css_individual_style') && !empty($tmpstyle)) {
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...
238
                        $css=$tmpstyle;
239
                        $this->alreadyminified=true;
240
                    } else if ($this->can_inject_late($cssPath,$css)) {
241
                        $css="/*!%%INJECTLATER%%".base64_encode($cssPath)."|".$cssHash."%%INJECTLATER%%*/";
242
                    }
243
                } else {
244
                    // Couldn't read CSS. Maybe getpath isn't working?
245
                    $css = '';
246
                }
247
            }
248
            
249
            foreach($media as $elem) {
250
                if(!isset($this->csscode[$elem]))
251
                    $this->csscode[$elem] = '';
252
                $this->csscode[$elem] .= "\n/*FILESTART*/".$css;
253
            }
254
        }
255
        
256
        // Check for duplicate code
257
        $md5list = array();
258
        $tmpcss = $this->csscode;
259
        foreach($tmpcss as $media => $code) {
260
            $md5sum = md5($code);
261
            $medianame = $media;
262
            foreach($md5list as $med => $sum) {
263
                // If same code
264
                if($sum === $md5sum) {
265
                    //Add the merged code
266
                    $medianame = $med.', '.$media;
267
                    $this->csscode[$medianame] = $code;
268
                    $md5list[$medianame] = $md5list[$med];
269
                    unset($this->csscode[$med], $this->csscode[$media]);
270
                    unset($md5list[$med]);
271
                }
272
            }
273
            $md5list[$medianame] = $md5sum;
274
        }
275
        unset($tmpcss);
276
        
277
        // Manage @imports, while is for recursive import management
278
        foreach ($this->csscode as &$thiscss) {
279
            // Flag to trigger import reconstitution and var to hold external imports
280
            $fiximports = false;
281
            $external_imports = "";
282
283
            // remove comments to avoid importing commented-out imports
284
            $thiscss_nocomments = preg_replace('#/\*.*\*/#Us','',$thiscss);
285
286
            while(preg_match_all('#@import.*(?:;|$)#Um',$thiscss_nocomments,$matches)) {
287
                foreach($matches[0] as $import)    {
288
                    if ($this->isremovable($import,$this->cssremovables)) {
289
                        $thiscss = str_replace($import,'',$thiscss);
290
                        $import_ok = true;
291
                    } else {
292
                        $url = trim(preg_replace('#^.*((?:https?:|ftp:)?//.*\.css).*$#','$1',trim($import))," \t\n\r\0\x0B\"'");
293
                        $path = $this->getpath($url);
294
                        $import_ok = false;
295
                        if (file_exists($path) && is_readable($path)) {
296
                            $code = addcslashes($this->fixurls($path,file_get_contents($path)),"\\");
297
                            $code = preg_replace('/\x{EF}\x{BB}\x{BF}/','',$code);
298
                            $tmpstyle = apply_filters( 'autoptimize_css_individual_style', $code, "" );
299
                            if ( has_filter('autoptimize_css_individual_style') && !empty($tmpstyle)) {
300
                                $code=$tmpstyle;
301
                                $this->alreadyminified=true;
302
                            } else if ($this->can_inject_late($path,$code)) {
303
                                $code="/*!%%INJECTLATER".AUTOPTIMIZE_HASH."%%".base64_encode($path)."|".md5($code)."%%INJECTLATER%%*/";
304
                            }
305
                            
306
                            if(!empty($code)) {
307
                                $tmp_thiscss = preg_replace('#(/\*FILESTART\*/.*)'.preg_quote($import,'#').'#Us','/*FILESTART2*/'.$code.'$1',$thiscss);
308
                                if (!empty($tmp_thiscss)) {
309
                                    $thiscss = $tmp_thiscss;
310
                                    $import_ok = true;
311
                                    unset($tmp_thiscss);
312
                                }
313
                                unset($code);
314
                            }
315
                        }
316
                    }
317
318
                    if (!$import_ok) {
319
                        // external imports and general fall-back
320
                        $external_imports .= $import;
321
                        $thiscss = str_replace($import,'',$thiscss);
322
                        $fiximports = true;
323
                    }
324
                }
325
                $thiscss = preg_replace('#/\*FILESTART\*/#','',$thiscss);
326
                $thiscss = preg_replace('#/\*FILESTART2\*/#','/*FILESTART*/',$thiscss);
327
                
328
                // and update $thiscss_nocomments before going into next iteration in while loop
329
                $thiscss_nocomments=preg_replace('#/\*.*\*/#Us','',$thiscss);
330
            }
331
            unset($thiscss_nocomments);
332
            
333
            // add external imports to top of aggregated CSS
334
            if($fiximports) {
335
                $thiscss=$external_imports.$thiscss;
336
            }
337
        }
338
        unset($thiscss);
339
        
340
        // $this->csscode has all the uncompressed code now. 
341
        foreach($this->csscode as &$code) {
342
            // Check for already-minified code
343
            $hash = md5($code);
344
            $ccheck = new autoptimizeCache($hash,'css');
345
            if($ccheck->check()) {
346
                $code = $ccheck->retrieve();
347
                $this->hashmap[md5($code)] = $hash;
348
                continue;
349
            }
350
            unset($ccheck);            
351
352
            // Handle @font-face rules by hiding and processing them separately
353
            $code = $this->hide_fontface_and_maybe_cdn($code);
354
355
            // Do the imaging!
356
            $imgreplace = array();
357
            preg_match_all( self::ASSETS_REGEX, $code, $matches );
358
359
            if ( ($this->datauris == true) && (function_exists('base64_encode')) && (is_array($matches)) ) {
0 ignored issues
show
Coding Style Best Practice introduced by
It seems like you are loosely comparing two booleans. Considering using the strict comparison === instead.

When comparing two booleans, it is generally considered safer to use the strict comparison operator.

Loading history...
360
                foreach($matches[1] as $count => $quotedurl) {
361
                    $iurl = trim($quotedurl," \t\n\r\0\x0B\"'");
362
363
                    // if querystring, remove it from url
364
                    if (strpos($iurl,'?') !== false) { $iurl = strtok($iurl,'?'); }
365
                    
366
                    $ipath = $this->getpath($iurl);
367
368
                    $datauri_max_size = 4096;
369
                    $datauri_max_size = (int) apply_filters( 'autoptimize_filter_css_datauri_maxsize', $datauri_max_size );
370
                    $datauri_exclude = apply_filters( 'autoptimize_filter_css_datauri_exclude', "");
371
                    if (!empty($datauri_exclude)) {
372
                        $no_datauris=array_filter(array_map('trim',explode(",",$datauri_exclude)));
373
                        foreach ($no_datauris as $no_datauri) {
374
                            if (strpos($iurl,$no_datauri)!==false) {
375
                                $ipath=false;
376
                                break;
377
                            }
378
                        }
379
                    }
380
381
                    if($ipath != false && preg_match('#\.(jpe?g|png|gif|bmp)$#i',$ipath) && file_exists($ipath) && is_readable($ipath) && filesize($ipath) <= $datauri_max_size) {
0 ignored issues
show
Bug introduced by
It seems like you are loosely comparing $ipath of type false|string against false; this is ambiguous if the string can be empty. Consider using a strict comparison !== instead.
Loading history...
382
                        $ihash=md5($ipath);
383
                        $icheck = new autoptimizeCache($ihash,'img');
384
                        if($icheck->check()) {
385
                            // we have the base64 image in cache
386
                            $headAndData=$icheck->retrieve();
387
                            $_base64data=explode(";base64,",$headAndData);
388
                            $base64data=$_base64data[1];
0 ignored issues
show
Unused Code introduced by
$base64data 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...
389
                        } else {
390
                            // It's an image and we don't have it in cache, get the type
391
                            $explA=explode('.',$ipath);
392
                            $type=end($explA);
393
394
                            switch($type) {
395
                                case 'jpeg':
396
                                    $dataurihead = 'data:image/jpeg;base64,';
397
                                    break;
398
                                case 'jpg':
399
                                    $dataurihead = 'data:image/jpeg;base64,';
400
                                    break;
401
                                case 'gif':
402
                                    $dataurihead = 'data:image/gif;base64,';
403
                                    break;
404
                                case 'png':
405
                                    $dataurihead = 'data:image/png;base64,';
406
                                    break;
407
                                case 'bmp':
408
                                    $dataurihead = 'data:image/bmp;base64,';
409
                                    break;
410
                                default:
411
                                    $dataurihead = 'data:application/octet-stream;base64,';
412
                            }
413
                        
414
                            // Encode the data
415
                            $base64data = base64_encode(file_get_contents($ipath));
416
                            $headAndData=$dataurihead.$base64data;
417
418
                            // Save in cache
419
                            $icheck->cache($headAndData,"text/plain");
420
                        }
421
                        unset($icheck);
422
423
                        // Add it to the list for replacement
424
                        $imgreplace[$matches[0][$count]] = str_replace($quotedurl,$headAndData,$matches[0][$count]);
425
                    } else {
426
                        // just cdn the URL if applicable
427
                        if (!empty($this->cdn_url)) {
428
                            $imgreplace[$matches[0][$count]] = str_replace($quotedurl,$this->url_replace_cdn($quotedurl),$matches[0][$count]);
429
						}
430
                    }
431
                }
432
            } else if ((is_array($matches)) && (!empty($this->cdn_url))) {
433
                // change urls to cdn-url
434
                foreach($matches[1] as $count => $quotedurl) {
435
                    $imgreplace[$matches[0][$count]] = str_replace($quotedurl,$this->url_replace_cdn($quotedurl),$matches[0][$count]);
436
                }
437
            }
438
            
439
            if(!empty($imgreplace)) {
440
                $code = str_replace(array_keys($imgreplace),array_values($imgreplace),$code);
441
            }
442
            
443
            // Replace back font-face markers with actual font-face declarations
444
            $code = $this->restore_fontface($code);
445
446
            // Minify
447
            if (($this->alreadyminified!==true) && (apply_filters( "autoptimize_css_do_minify", true))) {
448 View Code Duplication
                if (class_exists('Minify_CSS_Compressor')) {
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...
449
                    $tmp_code = trim(Minify_CSS_Compressor::process($code));
450
                } else if(class_exists('CSSmin')) {
451
                    $cssmin = new CSSmin();
452
                    if (method_exists($cssmin,"run")) {
453
                        $tmp_code = trim($cssmin->run($code));
454
                    } elseif (@is_callable(array($cssmin,"minify"))) {
455
                        $tmp_code = trim(CssMin::minify($code));
0 ignored issues
show
Bug introduced by
The method minify() cannot be called from this context as it is declared private in class CSSmin.

This check looks for access to methods that are not accessible from the current context.

If you need to make a method accessible to another context you can raise its visibility level in the defining class.

Loading history...
Bug introduced by
The call to minify() misses a required argument $linebreak_pos.

This check looks for function calls that miss required arguments.

Loading history...
456
                    }
457
                }
458
                if (!empty($tmp_code)) {
459
                    $code = $tmp_code;
460
                    unset($tmp_code);
461
                }
462
            }
463
            
464
            $code = $this->inject_minified($code);
465
            
466
            $tmp_code = apply_filters( 'autoptimize_css_after_minify', $code );
467
            if (!empty($tmp_code)) {
468
                $code = $tmp_code;
469
                unset($tmp_code);
470
            }
471
            
472
            $this->hashmap[md5($code)] = $hash;
473
        }
474
        unset($code);
475
        return true;
476
    }
477
    
478
    //Caches the CSS in uncompressed, deflated and gzipped form.
479
    public function cache() {
480
        // CSS cache
481
        foreach($this->csscode as $media => $code) {
482
            $md5 = $this->hashmap[md5($code)];
483
                
484
            $cache = new autoptimizeCache($md5,'css');
485
            if(!$cache->check()) {
486
                // Cache our code
487
                $cache->cache($code,'text/css');
488
            }
489
            $this->url[$media] = AUTOPTIMIZE_CACHE_URL.$cache->getname();
490
        }
491
    }
492
    
493
    //Returns the content
494
    public function getcontent() {
495
        // restore IE hacks
496
        $this->content = $this->restore_iehacks($this->content);
497
498
        // restore comments
499
        $this->content = $this->restore_comments($this->content);
500
        
501
        // restore (no)script
502 View Code Duplication
        if ( strpos( $this->content, '%%SCRIPT%%' ) !== false ) { 
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...
503
            $this->content = preg_replace_callback(
504
                '#%%SCRIPT'.AUTOPTIMIZE_HASH.'%%(.*?)%%SCRIPT%%#is',
505
                create_function(
0 ignored issues
show
Security Best Practice introduced by
The use of create_function is highly discouraged, better use a closure.

create_function can pose a great security vulnerability as it is similar to eval, and could be used for arbitrary code execution. We highly recommend to use a closure instead.

// Instead of
$function = create_function('$a, $b', 'return $a + $b');

// Better use
$function = function($a, $b) { return $a + $b; }
Loading history...
506
                    '$matches',
507
                    'return base64_decode($matches[1]);'
508
                ),
509
                $this->content
510
            );
511
        }
512
513
        // restore noptimize
514
        $this->content = $this->restore_noptimize($this->content);
515
        
516
        //Restore the full content
517
        if(!empty($this->restofcontent)) {
518
            $this->content .= $this->restofcontent;
519
            $this->restofcontent = '';
520
        }
521
        
522
        // Inject the new stylesheets
523
        $replaceTag = array("<title","before");
524
        $replaceTag = apply_filters( 'autoptimize_filter_css_replacetag', $replaceTag, $this->content );
525
526
        if ($this->inline == true) {
0 ignored issues
show
Coding Style Best Practice introduced by
It seems like you are loosely comparing two booleans. Considering using the strict comparison === instead.

When comparing two booleans, it is generally considered safer to use the strict comparison operator.

Loading history...
527
            foreach($this->csscode as $media => $code) {
528
                $this->inject_in_html('<style type="text/css" media="'.$media.'">'.$code.'</style>',$replaceTag);
529
            }
530
        } else {
531
            if ($this->defer == true) {
0 ignored issues
show
Coding Style Best Practice introduced by
It seems like you are loosely comparing two booleans. Considering using the strict comparison === instead.

When comparing two booleans, it is generally considered safer to use the strict comparison operator.

Loading history...
532
                $preloadCssBlock = "";
533
                $noScriptCssBlock = "<noscript id=\"aonoscrcss\">";
534
                $defer_inline_code=$this->defer_inline;
535
                if(!empty($defer_inline_code)){
536
                    if ( apply_filters( 'autoptimize_filter_css_critcss_minify', true ) ) {
537
                        $iCssHash = md5($defer_inline_code);
538
                        $iCssCache = new autoptimizeCache($iCssHash,'css');
539
                        if($iCssCache->check()) { 
540
                            // we have the optimized inline CSS in cache
541
                            $defer_inline_code=$iCssCache->retrieve();
542
                        } else {
543
                            if (class_exists('Minify_CSS_Compressor')) {
544
                                $tmp_code = trim(Minify_CSS_Compressor::process($defer_inline_code));
0 ignored issues
show
Documentation introduced by
$defer_inline_code is of type boolean, but the function expects a string.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
545
                            } else if(class_exists('CSSmin')) {
546
                                $cssmin = new CSSmin();
547
                                $tmp_code = trim($cssmin->run($defer_inline_code));
0 ignored issues
show
Documentation introduced by
$defer_inline_code is of type boolean, but the function expects a string.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
548
                            }
549
                            if (!empty($tmp_code)) {
550
                                $defer_inline_code = $tmp_code;
551
                                $iCssCache->cache($defer_inline_code,"text/css");
552
                                unset($tmp_code);
553
                            }
554
                        }
555
                    }
556
                    $code_out='<style type="text/css" id="aoatfcss" media="all">'.$defer_inline_code.'</style>';
557
                    $this->inject_in_html($code_out,$replaceTag);
558
                }
559
            }
560
561
            foreach($this->url as $media => $url) {
562
                $url = $this->url_replace_cdn($url);
563
                
564
                //Add the stylesheet either deferred (import at bottom) or normal links in head
565
                if($this->defer == true) {
0 ignored issues
show
Coding Style Best Practice introduced by
It seems like you are loosely comparing two booleans. Considering using the strict comparison === instead.

When comparing two booleans, it is generally considered safer to use the strict comparison operator.

Loading history...
566
                    $preloadCssBlock .= '<link rel="preload" as="style" media="'.$media.'" href="'.$url.'" onload="this.rel=\'stylesheet\'" />';
0 ignored issues
show
Bug introduced by
The variable $preloadCssBlock does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
567
                    $noScriptCssBlock .= '<link type="text/css" media="'.$media.'" href="'.$url.'" rel="stylesheet" />';
0 ignored issues
show
Bug introduced by
The variable $noScriptCssBlock does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
568
                } else {
569
                    if (strlen($this->csscode[$media]) > $this->cssinlinesize) {
570
                        $this->inject_in_html('<link type="text/css" media="'.$media.'" href="'.$url.'" rel="stylesheet" />',$replaceTag);
571
                    } else if (strlen($this->csscode[$media])>0) {
572
                        $this->inject_in_html('<style type="text/css" media="'.$media.'">'.$this->csscode[$media].'</style>',$replaceTag);
573
                    }
574
                }
575
            }
576
            
577
            if($this->defer == true) {
0 ignored issues
show
Coding Style Best Practice introduced by
It seems like you are loosely comparing two booleans. Considering using the strict comparison === instead.

When comparing two booleans, it is generally considered safer to use the strict comparison operator.

Loading history...
578
                $preloadPolyfill = '<script data-cfasync=\'false\'>/*! loadCSS. [c]2017 Filament Group, Inc. MIT License */
579
!function(a){"use strict";var b=function(b,c,d){function e(a){return h.body?a():void setTimeout(function(){e(a)})}function f(){i.addEventListener&&i.removeEventListener("load",f),i.media=d||"all"}var g,h=a.document,i=h.createElement("link");if(c)g=c;else{var j=(h.body||h.getElementsByTagName("head")[0]).childNodes;g=j[j.length-1]}var k=h.styleSheets;i.rel="stylesheet",i.href=b,i.media="only x",e(function(){g.parentNode.insertBefore(i,c?g:g.nextSibling)});var l=function(a){for(var b=i.href,c=k.length;c--;)if(k[c].href===b)return a();setTimeout(function(){l(a)})};return i.addEventListener&&i.addEventListener("load",f),i.onloadcssdefined=l,l(f),i};"undefined"!=typeof exports?exports.loadCSS=b:a.loadCSS=b}("undefined"!=typeof global?global:this);
580
/*! loadCSS rel=preload polyfill. [c]2017 Filament Group, Inc. MIT License */
581
!function(a){if(a.loadCSS){var b=loadCSS.relpreload={};if(b.support=function(){try{return a.document.createElement("link").relList.supports("preload")}catch(b){return!1}},b.poly=function(){for(var b=a.document.getElementsByTagName("link"),c=0;c<b.length;c++){var d=b[c];"preload"===d.rel&&"style"===d.getAttribute("as")&&(a.loadCSS(d.href,d,d.getAttribute("media")),d.rel=null)}},!b.support()){b.poly();var c=a.setInterval(b.poly,300);a.addEventListener&&a.addEventListener("load",function(){b.poly(),a.clearInterval(c)}),a.attachEvent&&a.attachEvent("onload",function(){a.clearInterval(c)})}}}(this);</script>';
582
                $noScriptCssBlock .= "</noscript>";
583
                $this->inject_in_html($preloadCssBlock.$noScriptCssBlock,$replaceTag);
584
                $this->inject_in_html($preloadPolyfill,array('</body>','before'));
585
            }
586
        }
587
588
        //Return the modified stylesheet
589
        return $this->content;
590
    }
591
    
592
    static function fixurls($file, $code) {
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
593
        // Switch all imports to the url() syntax
594
        $code = preg_replace( '#@import ("|\')(.+?)\.css.*("|\')#', '@import url("${2}.css")', $code );
595
596
        if ( preg_match_all( self::ASSETS_REGEX, $code, $matches ) ) {
597
            $file = str_replace( WP_ROOT_DIR, '/', $file );
598
            $dir = dirname( $file ); // Like /themes/expound/css
599
600
            // $dir should not contain backslashes, since it's used to replace
601
            // urls, but it can contain them when running on Windows because
602
            // fixurls() is sometimes called with `ABSPATH . 'index.php'`
603
            $dir = str_replace( '\\', '/', $dir );
604
            unset( $file ); // not used below at all
605
606
            $replace = array();
607
            foreach ( $matches[1] as $k => $url ) {
608
                // Remove quotes
609
                $url    = trim( $url," \t\n\r\0\x0B\"'" );
610
                $noQurl = trim( $url, "\"'" );
611
                if ( $url !== $noQurl ) {
612
                    $removedQuotes = true;
613
                } else {
614
                    $removedQuotes = false;
615
                }
616
617
                if ( '' === $noQurl ) {
618
                    continue;
619
                }
620
621
                $url = $noQurl;
622
                if ( '/' === $url{0} || preg_match( '#^(https?://|ftp://|data:)#i', $url ) ) {
623
                    // URL is protocol-relative, host-relative or something we don't touch
624
                    continue;
625
                } else {
626
                    // Relative URL
627
                    $newurl = preg_replace( '/https?:/', '', str_replace( ' ', '%20', AUTOPTIMIZE_WP_ROOT_URL . str_replace( '//', '/', $dir . '/' . $url ) ) );
628
629
                    // Hash the url + whatever was behind potentially for replacement
630
                    // We must do this, or different css classes referencing the same bg image (but
631
                    // different parts of it, say, in sprites and such) loose their stuff...
632
                    $hash = md5( $url . $matches[2][$k] );
633
                    $code = str_replace( $matches[0][$k], $hash, $code );
634
635
                    if ( $removedQuotes ) {
636
                        $replace[$hash] = "url('" . $newurl . "')" . $matches[2][$k];
637
                    } else {
638
                        $replace[$hash] = 'url(' . $newurl . ')' . $matches[2][$k];
639
                    }
640
                }
641
            }
642
643
            $code = $this->replace_longest_matches_first($code, $replace);
0 ignored issues
show
Bug introduced by
The variable $this does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
644
        }
645
646
        return $code;
647
    }
648
    
649
    private function ismovable($tag) {
650
		if ( apply_filters('autoptimize_filter_css_dontaggregate', false) ) {
651
			return false;
652
        } else if (!empty($this->whitelist)) {
653
            foreach ($this->whitelist as $match) {
0 ignored issues
show
Bug introduced by
The expression $this->whitelist of type string is not traversable.
Loading history...
654
                if(strpos($tag,$match)!==false) {
655
                    return true;
656
                }
657
            }
658
            // no match with whitelist
659
            return false;
660
        } else {
661
            if (is_array($this->dontmove)) {
662
                foreach($this->dontmove as $match) {
663
                    if(strpos($tag,$match)!==false) {
664
                        //Matched something
665
                        return false;
666
                    }
667
                }
668
            }
669
            
670
            //If we're here it's safe to move
671
            return true;
672
        }
673
    }
674
    
675
    private function can_inject_late($cssPath,$css) {
676
		$consider_minified_array = apply_filters('autoptimize_filter_css_consider_minified', false, $cssPath);
677
        if ( $this->inject_min_late !== true ) {
678
            // late-inject turned off
679
            return false;
680
        } else if ( (strpos($cssPath,"min.css") === false) && ( str_replace($consider_minified_array, '', $cssPath) === $cssPath ) ) {
681
			// file not minified based on filename & filter
682
			return false;
683
        } else if ( strpos($css,"@import") !== false ) {
684
            // can't late-inject files with imports as those need to be aggregated 
685
            return false;
686
        } else if ( (strpos($css,"@font-face")!==false ) && ( apply_filters("autoptimize_filter_css_fonts_cdn",false)===true) && (!empty($this->cdn_url)) ) {
687
            // don't late-inject CSS with font-src's if fonts are set to be CDN'ed
688
            return false;
689
        } else if ( (($this->datauris == true) || (!empty($this->cdn_url))) && preg_match("#background[^;}]*url\(#Ui",$css) ) {
0 ignored issues
show
Coding Style Best Practice introduced by
It seems like you are loosely comparing two booleans. Considering using the strict comparison === instead.

When comparing two booleans, it is generally considered safer to use the strict comparison operator.

Loading history...
690
            // don't late-inject CSS with images if CDN is set OR is image inlining is on
691
            return false;
692
        } else {
693
            // phew, all is safe, we can late-inject
694
            return true;
695
        }
696
    }
697
698
    /**
699
     * Given an array of key/value pairs to replace in $string,
700
     * does so in a way that the longest strings are replaced first.
701
     *
702
     * @param string $string
703
     * @param array $replacements
704
     *
705
     * @return string
706
     */
707
    protected function replace_longest_matches_first($string, $replacements = array())
708
    {
709
        if ( ! empty( $replacements ) ) {
710
            // Sort the replacements array by key length in desc order (so that the longest strings are replaced first)
711
            $keys = array_map( 'strlen', array_keys( $replacements ) );
712
            array_multisort( $keys, SORT_DESC, $replacements );
713
            // $this->debug_log($replacements);
0 ignored issues
show
Unused Code Comprehensibility introduced by
75% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
714
            $string = str_replace( array_keys( $replacements ), array_values( $replacements ), $string );
715
        }
716
717
        return $string;
718
    }
719
720
    /**
721
     * Rewrites/Replaces any ASSETS_REGEX-matching urls in a string.
722
     * Removes quotes/cruft around each one and passes it through to
723
     * `autoptimizeBase::url_replace_cdn()` if needed.
724
     * Replacements are performed in a `longest-match-replaced-first` way.
725
     *
726
     * @param string $code
727
     * @return string
728
     */
729
    public function replace_urls($code = '')
730
    {
731
        preg_match_all( self::ASSETS_REGEX, $code, $url_src_matches );
732
        if ( is_array( $url_src_matches ) && ! empty( $url_src_matches ) ) {
733
            foreach ( $url_src_matches[1] as $count => $original_url ) {
734
                // Removes quotes and other cruft
735
                $url = trim( $original_url, " \t\n\r\0\x0B\"'" );
736
                // Do CDN replacement if needed
737
                if ( ! empty( $this->cdn_url ) ) {
738
                    $replacement_url = $this->url_replace_cdn($url);
739
                    // Prepare replacements array
740
                    $replacements[ $url_src_matches[1][ $count ] ] = str_replace(
0 ignored issues
show
Coding Style Comprehensibility introduced by
$replacements was never initialized. Although not strictly required by PHP, it is generally a good practice to add $replacements = 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...
741
                        $original_url, $replacement_url, $url_src_matches[1][$count]
742
                    );
743
                }
744
            }
745
        }
746
747
        $code = $this->replace_longest_matches_first($code, $replacements);
0 ignored issues
show
Bug introduced by
The variable $replacements does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
748
749
        return $code;
750
    }
751
752
    /**
753
     * "Hides" @font-face declarations by replacing them with `%%FONTFACE%%$base64encoded%%FONTFACE%%` markers.
754
     * Also does CDN replacement of any font-urls within those declarations if the `autoptimize_filter_css_fonts_cdn`
755
     * filter is used.
756
     *
757
     * @param string $code
758
     * @return string
759
     */
760
    public function hide_fontface_and_maybe_cdn($code)
761
    {
762
        // Proceed only if @font-face declarations exist within $code
763
        preg_match_all( self::FONT_FACE_REGEX, $code, $fontfaces );
764
        if ( isset( $fontfaces[0] ) ) {
765
            // Check if we need to cdn fonts or not
766
            $do_font_cdn = apply_filters( 'autoptimize_filter_css_fonts_cdn', false );
767
768
            foreach ( $fontfaces[0] as $full_match ) {
769
                // Keep original match so we can search/replace it
770
                $match_search = $full_match;
771
772
                // Do font cdn if needed
773
                if ( $do_font_cdn ) {
774
                    $full_match = $this->replace_urls($full_match);
775
                }
776
777
                // Replace declaration with its base64 encoded string
778
                $replacement = self::build_marker('FONTFACE', $full_match);
779
                $code = str_replace( $match_search, $replacement, $code );
780
            }
781
        }
782
783
        return $code;
784
    }
785
786
    /**
787
     * Restores original @font-face declarations that have been "hidden"
788
     * using `hide_fontface_and_maybe_cdn()`.
789
     *
790
     * @param string $code
791
     * @return string
792
     */
793
    public function restore_fontface($code)
794
    {
795
        return $this->restore_marked_content('FONTFACE', $code);
796
    }
797
}
798